@reactor-team/js-sdk 3.2.0 → 3.4.0
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.
- package/README.md +131 -0
- package/dist/index.cjs +752 -9
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +399 -5
- package/dist/index.d.ts +399 -5
- package/dist/index.js +743 -9
- package/dist/index.js.map +1 -1
- package/dist/wasm/README.md +38 -2
- package/dist/wasm/reactor_wasm.d.ts +229 -2
- package/dist/wasm/reactor_wasm.js +348 -8
- package/dist/wasm/reactor_wasm_bg.wasm.d.ts +10 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/reactor.ts","../src/internal/capabilities.ts","../src/internal/debug-log.ts","../src/errors.ts","../src/internal/emitter.ts","../src/file-ref.ts","../src/internal/file-ref.ts","../src/internal/recording.ts","../src/internal/stats.ts","../src/internal/wasm.ts","../package.json","../src/internal/jwt-resolver.ts","../src/recording.ts","../src/jwt.ts","../src/react/ReactorProvider.tsx","../src/react/store.ts","../src/react/hooks.ts","../src/react/ReactorView.tsx","../src/react/WebcamStream.tsx","../src/react/ClipPlayer.tsx","../src/clip-playback.ts","../src/react/ClipDownloadButton.tsx","../src/react/useClipDownload.ts"],"sourcesContent":["import { AwaitQueue } from 'awaitqueue';\nimport { toPublicCapabilities } from './internal/capabilities';\nimport { debugLog } from './internal/debug-log';\nimport { toReactorError, type ReactorError } from './errors';\nimport { Emitter } from './internal/emitter';\nimport { extractFileRefs, toPublicFileRef } from './internal/file-ref';\nimport { toPublicClip } from './internal/recording';\nimport type { ReactorClient } from './internal/reactor-wasm.types';\nimport {\n LOCAL_STATS_INTERVAL_MS,\n RUNTIME_REPORT_INTERVAL_MS,\n createConnectionStatsExtractor,\n createTrackStatsExtractor,\n pollPeerStats,\n toClientConnectionStat,\n type TrackStatsExtractor,\n} from './internal/stats';\nimport { loadReactorWasm } from './internal/wasm';\nimport packageJson from '../package.json';\nimport type { FileRef } from './file-ref';\nimport { downloadClipAsFile as downloadClipAsFileFn, type DownloadClipOptions } from './recording';\nimport type {\n Capabilities,\n Clip,\n ConnectionStats,\n ConnectionTimings,\n ConnectOptions,\n JwtSource,\n MessageScope,\n ModelSchema,\n NotFunction,\n ReactorEventMap,\n ReactorMessage,\n ReactorOptions,\n ReactorStatus,\n SessionResponse,\n TrackCapability,\n TrackMappingEntry,\n} from './types';\n\n/**\n * A live connection to a Reactor model.\n */\nexport class Reactor implements Disposable {\n private readonly clientOptions: Omit<ReactorOptions, 'jwt'>;\n private jwt: JwtSource | null | undefined;\n private client: ReactorClient | undefined;\n private clientPromise: Promise<ReactorClient> | undefined;\n private disposed = false;\n private _lastError: ReactorError | undefined;\n private schema: ModelSchema | undefined;\n /** Bumped on every `refreshSchema()` call — lets a call detect it's been\n * superseded by a newer one even when `client` itself hasn't changed\n * (e.g. two \"ready\" transitions on the same reused client). */\n private schemaRefreshId = 0;\n private capabilities: Capabilities | undefined;\n\n private stats: ConnectionStats | undefined;\n private connectionTimings: ConnectionTimings | undefined;\n /** The stop functions of the running stats pollers — see `pollPeerStats()`. */\n private stopStatsPollers: Array<() => void> = [];\n /** Whether this connection has already reported its time to connect —\n * a one-time fact, sent on the first client-stats report that carries it\n * and omitted on every one after. Set only once a batch actually went out\n * with it, so a batch sent before the timings exist doesn't use it up.\n * Reset per `startStatsPolling()` call, i.e. per connect()/reconnect(). */\n private hasSentConnectTime = false;\n /** Set on the \"connecting\" status transition, cleared once `connectionTimings`\n * is finalized on \"ready\" — see `handleStatusChanged()`. */\n private connectStartTime: number | undefined;\n private waitingStartTime: number | undefined;\n\n private readonly emitter = new Emitter<ReactorEventMap>();\n /** Serializes connect()/reconnect()/disconnect() (and the free() inside\n * disconnect()/[Symbol.dispose]) against each other. Calling into the\n * client concurrently with one of these (e.g. a user clicking Disconnect\n * mid-connect) races its internal state and can throw (\"attempted to\n * take ownership of Rust value while it was borrowed\") or corrupt it\n * outright. */\n private readonly queue = new AwaitQueue();\n\n /** In-flight calls to `withReaderAccess()` — a \"reply\" `.catch(() => {})`\n * copy of each, never the caller's own promise, so one rejecting can't\n * make `Promise.all()` in `withWriterAccess()` reject and skip waiting\n * for the rest. See `withReaderAccess()`/`withWriterAccess()`. */\n private readonly activeReads = new Set<Promise<unknown>>();\n /** True for the span of a `withWriterAccess()` call — after it has waited\n * out every read active when it started, before it releases the ones\n * that arrived while it ran. */\n private writerActive = false;\n /** Readers parked in `withReaderAccess()`'s wait loop, woken once\n * `withWriterAccess()` finishes; each re-checks `writerActive` rather\n * than assuming its turn, since another writer already queued behind the\n * first one may have claimed it first. */\n private writerIdleWaiters: Array<() => void> = [];\n\n /**\n * Runs a read — sendCommand()/requestSchema()/requestClip()/\n * requestRecording() — excluded from a lifecycle op (`withWriterAccess()`)\n * but not from other reads: unlike `queue`, concurrent reads run\n * concurrently. Queuing them the same way `queue` serializes writes would\n * head-of-line block an unrelated command, or even disconnect() itself,\n * behind one slow reply (the binding correlates replies independently, so\n * nothing requires this to be serial).\n *\n * Race-free the same way the wasm binding's own `readyState` check is: the\n * `writerActive` check and this call's registration in `activeReads` both\n * happen before the first `await` inside *fn*, so nothing can run between\n * them on a single-threaded JS event loop.\n */\n private async withReaderAccess<T>(fn: () => Promise<T>): Promise<T> {\n while (this.writerActive) {\n await new Promise<void>((resolve) => this.writerIdleWaiters.push(resolve));\n }\n const result = fn();\n const tracked = result.catch(() => undefined);\n\n this.activeReads.add(tracked);\n try {\n return await result;\n } finally {\n this.activeReads.delete(tracked);\n }\n }\n\n /**\n * Runs a lifecycle op's client-touching body exclusively: waits out every\n * read already in flight, then blocks new ones (`writerActive`) until it\n * finishes. Only ever called from inside a `queue`-serialized task, so at\n * most one writer runs this at a time — it doesn't serialize against\n * itself, only against `activeReads`.\n */\n private async withWriterAccess<T>(fn: () => Promise<T>): Promise<T> {\n // Mark the writer active *before* awaiting the current reads, not after:\n // withReaderAccess()'s gate check is what keeps a new read from entering\n // during that wait, and it only works once this flag is already true.\n // Setting it first can't race a second writer — writers only ever run\n // from inside a `queue`-serialized task, so at most one is ever here.\n this.writerActive = true;\n // Skip the await entirely when nothing is in flight — `await\n // Promise.all([])` still costs a microtask tick, which the common\n // (uncontended) case shouldn't pay: connect()/disconnect()/reconnect()\n // calling into the client promptly is a property callers (React's\n // effect-cleanup unmount included) rely on.\n if (this.activeReads.size > 0) {\n await Promise.all(this.activeReads);\n }\n try {\n return await fn();\n } finally {\n this.writerActive = false;\n const waiters = this.writerIdleWaiters;\n\n this.writerIdleWaiters = [];\n for (const wake of waiters) {wake();}\n }\n }\n\n constructor(options: ReactorOptions) {\n const { jwt, ...clientOptions } = options;\n\n // The wasm binding's own default (`reactor-core`'s crate version) tracks\n // the Rust workspace, not this package — without this, `client_info`\n // reports the wrong version to the coordinator. Still overridable via\n // `options.sdkVersion`.\n this.clientOptions = { sdkVersion: packageJson.version, ...clientOptions };\n this.jwt = jwt ?? null;\n }\n\n // ── Lifecycle ───────────────────────────────────────────────────────────\n\n /**\n * `jwt`, when given, replaces whatever `new Reactor({ jwt })` was given —\n * including on a client that's still around from a recoverable\n * `disconnect(true)`.\n *\n * Throws if already connected or connecting; call `disconnect()` first.\n */\n async connect(jwt?: JwtSource, options?: ConnectOptions): Promise<void> {\n this.assertNotDisposed();\n try {\n if (this.getStatus() !== 'disconnected') {\n throw new Error('Already connected or connecting.');\n }\n if (jwt !== undefined) {\n this.jwt = jwt;\n this.client?.setJwt(jwt);\n }\n await this.queue.push(\n () =>\n this.withWriterAccess(async () => {\n const client = await this.getOrCreateClient();\n\n await client.connect(options);\n }),\n 'connect',\n );\n } catch (cause) {\n throw this.captureError(cause);\n }\n }\n\n /**\n * Ends the connection. By default (`recoverable = false`) this also frees\n * the wasm resource graph — the pump/dispatcher/heartbeat tasks and the\n * peer connection — in one step. Pass `recoverable: true` to keep the\n * wasm client alive so a later `connect()`/`reconnect()` doesn't have to\n * reload wasm and reconstruct it from scratch.\n *\n * Note this only governs the *local* resource graph — the binding's own\n * `disconnect()` always ends the session server-side regardless of this\n * flag, so `recoverable` isn't a way to keep the session itself alive.\n *\n * Queued behind any in-flight `connect()`/`reconnect()` — see `queue`'s\n * docs for why calling into the client concurrently with one of those is\n * unsafe.\n */\n async disconnect(recoverable = false): Promise<void> {\n this.assertNotDisposed();\n try {\n await this.queue.push(\n () =>\n this.withWriterAccess(async () => {\n if (this.client) {\n await this.client.disconnect();\n }\n this.resetConnectionState();\n if (!recoverable) {\n this.freeClient();\n }\n }),\n 'disconnect',\n );\n } catch (cause) {\n throw this.captureError(cause);\n }\n }\n\n /**\n * Only `options.maxAttempts` has an effect here — the rest of\n * `ConnectOptions` (session adoption, connection id, auto-resume) only\n * makes sense when establishing a session in the first place, same as v2's\n * `reconnect()` always ignored them.\n */\n async reconnect(options?: ConnectOptions): Promise<void> {\n this.assertNotDisposed();\n try {\n await this.queue.push(\n () =>\n this.withWriterAccess(async () => {\n const client = await this.getOrCreateClient();\n\n await client.reconnect(options);\n }),\n 'reconnect',\n );\n } catch (cause) {\n throw this.captureError(cause);\n }\n }\n\n // ── Messaging ───────────────────────────────────────────────────────────\n\n /**\n * Sends a command to the model and resolves with its correlated reply.\n *\n * `undefined` means the handler acknowledged the command but sent no\n * reply body. The binding's own typed signature promises `undefined` for\n * that case, but its serializer (serde_wasm_bindgen's `json_compatible`\n * mode) actually hands back `null` — normalized here so callers can rely\n * on the documented type instead of the binding's serialization quirk.\n *\n * A `FileRef` (from `uploadFile`) may be passed in `data` wherever the\n * model's schema declares a file. As a top-level value it is extracted and\n * sent as a separate upload reference rather than embedded in the JSON\n * payload; inside an array or object (a parameter that takes several files,\n * say) it is serialized as an upload reference in place.\n *\n * Unlike every other method here, this never rejects — a failure (the\n * session isn't `\"ready\"`, the send itself fails, …) is reported through\n * `getLastError()`/the `error` event instead, resolving with `undefined`.\n * This is a JS-only compatibility shim, kept because callers routinely\n * fire-and-forget `sendCommand(...)` without `await`/`catch`, and a\n * rejection nobody handles is an unhandled-rejection warning at best. It\n * is deliberately not applied to `publishTrack`/`uploadFile`/etc., which\n * throw normally.\n *\n * `scope` is forwarded to `sendRuntimeScopedCommand()` — see there for\n * what `\"runtime\"` actually does.\n *\n * `data` accepts any object, except a function.\n */\n async sendCommand<T extends object = Record<string, unknown>>(\n command: string,\n data?: NotFunction<T>,\n scope?: MessageScope,\n ): Promise<ReactorMessage | undefined> {\n if (scope === 'runtime') {\n return this.sendRuntimeScopedCommand(command, data);\n }\n try {\n this.assertNotDisposed();\n const extracted = extractFileRefs(data as Record<string, unknown> | undefined);\n // Excluded from connect()/disconnect()/reconnect() — a concurrent\n // disconnect() can otherwise free the wasm client while this call into\n // it is still in flight (see `withReaderAccess()`'s docs) — but not\n // from other reads, unlike the track ops on `queue`: two sendCommand()\n // calls (or a slow one and a disconnect()) shouldn't head-of-line\n // block each other when the binding correlates replies independently.\n const reply = await this.withReaderAccess(async () => {\n const client = await this.getOrCreateClient();\n\n return client.sendCommand(command, extracted.data, extracted.uploads);\n });\n\n return reply ?? undefined;\n } catch (cause) {\n this.emitError(cause);\n return undefined;\n }\n }\n\n /**\n * Handles `sendCommand(command, data, \"runtime\")` — this SDK has no\n * generic runtime-scope channel. `reactor-core`'s `send_command` is a\n * single channel; `requestSchema`/clip requests/heartbeat are each their\n * own dedicated RPC instead of a scoped envelope, so there's nothing\n * generic to route a scope through at the wire level.\n *\n * `requestSchema` and `requestCapabilities` route to their direct\n * equivalents below, neither of which returns a `ReactorMessage` the way a\n * normal `sendCommand()` reply would, so both resolve `undefined`; the\n * actual data surfaces through `getSchema()`/`schemaReceived` and\n * `getCapabilities()`/`capabilitiesReceived` as it already does. Anything\n * else has no runtime-scope destination to route to — rather than silently\n * doing nothing, it falls through as a normal application-scope send, with\n * a console warning.\n */\n private async sendRuntimeScopedCommand(\n command: string,\n data?: object,\n ): Promise<ReactorMessage | undefined> {\n switch (command) {\n case 'requestSchema':\n try {\n // Same exclusion as `sendCommand()` above.\n await this.withReaderAccess(async () => {\n const client = await this.getOrCreateClient();\n\n await this.refreshSchema(client);\n });\n } catch (cause) {\n // refreshSchema() reports failures itself when it has a client to\n // key the race guard on; getOrCreateClient() failing before that\n // doesn't, so report it here. Either way, sendCommand's own\n // contract never rejects.\n this.emitError(cause);\n }\n return undefined;\n case 'requestCapabilities':\n // No dedicated \"request\" exists — reactor-core pushes capabilities\n // once negotiated, so getCapabilities()/capabilitiesReceived already\n // reflect the latest value with nothing left to trigger here.\n return undefined;\n default:\n console.warn(\n `[Reactor] sendCommand(${JSON.stringify(command)}, …, \"runtime\") has no runtime-scope destination in this SDK — sending as a normal application-scope command instead.`,\n );\n return this.sendCommand(command, data);\n }\n }\n\n /** Requests the model's command schema directly. Most callers don't need\n * this — it's already fetched once and cached as soon as the session\n * reaches `\"ready\"`; use `getSchema()` for that. Resolves `undefined`\n * when the model doesn't expose a schema — the binding replies with a\n * wire `null` in that case rather than omitting the field. */\n async requestSchema(): Promise<ModelSchema | undefined> {\n this.assertNotDisposed();\n try {\n // Excluded from connect()/disconnect()/reconnect() — see\n // `withReaderAccess()`'s docs.\n return await this.withReaderAccess(async () => {\n const client = await this.getOrCreateClient();\n\n return this.normalizeSchema(await client.requestSchema());\n });\n } catch (cause) {\n throw this.captureError(cause);\n }\n }\n\n /** The model's command schema (an OpenAPI document), cached from the\n * `requestSchema()` call fired automatically on `\"ready\"`. `undefined`\n * until that reply has landed. */\n getSchema(): ModelSchema | undefined {\n return this.schema;\n }\n\n /** The runtime's declared capabilities (negotiated tracks, and the\n * command set when the model exposes one) — pushed once available, no\n * explicit request needed. `undefined` until `capabilitiesReceived`\n * fires. */\n getCapabilities(): Capabilities | undefined {\n return this.capabilities;\n }\n\n /** The session resource, as the coordinator reports it — id, state,\n * model, cluster, server info, and (once negotiated) `capabilities`.\n * A live read straight off the wasm client, not cached — reflects\n * whatever's current. `undefined` before a client exists. */\n getSessionInfo(): SessionResponse | undefined {\n return this.client?.sessionInfo();\n }\n\n // ── Tracks ──────────────────────────────────────────────────────────────\n\n /**\n * Publishes a local `MediaStreamTrack` under `name` — the counterpart to a\n * `sendonly` track the model declares. Awaitable. Queued behind\n * connect()/disconnect()/reconnect() (unlike `sendCommand()`): a track\n * operation awaits its own control round-trip, and a concurrent\n * disconnect() freeing the wasm client mid-await would otherwise resume\n * into a freed client — the same class of use-after-free `queue` exists to\n * prevent for connect/disconnect/reconnect themselves.\n */\n async publishTrack(name: string, track: MediaStreamTrack): Promise<void> {\n this.assertNotDisposed();\n try {\n await this.queue.push(async () => {\n const client = await this.getOrCreateClient();\n\n await client.publishTrack(name, track);\n }, 'publishTrack');\n } catch (cause) {\n throw this.captureError(cause);\n }\n }\n\n /**\n * Unlike every other track method, this doesn't reject — a failure is\n * reported through the `error` event instead, since this is commonly the\n * last call in a `finally` block, and raising there would replace\n * whatever exception was already propagating.\n */\n async unpublishTrack(name: string): Promise<void> {\n this.assertNotDisposed();\n try {\n await this.queue.push(async () => {\n const client = await this.getOrCreateClient();\n\n await client.unpublishTrack(name);\n }, 'unpublishTrack');\n } catch (cause) {\n this.emitError(cause);\n }\n }\n\n /**\n * Stops a received track: the receiver goes inactive and the runtime stops\n * producing it. Awaitable, and queued behind connect()/disconnect()/\n * reconnect() for the same reason as `publishTrack()`.\n */\n async pauseTrack(name: string): Promise<void> {\n this.assertNotDisposed();\n try {\n await this.queue.push(async () => {\n const client = await this.getOrCreateClient();\n\n await client.pauseTrack(name);\n }, 'pauseTrack');\n } catch (cause) {\n throw this.captureError(cause);\n }\n }\n\n /**\n * Bounds what one sender may spend, in bits per second.\n *\n * This is the ceiling that actually caps a video encoder, and it is easy to\n * hit without knowing it exists: with nothing set, a Chromium-based browser\n * derives a sender's maximum from the frame size alone, and that maximum is\n * 2500 kbps for anything above 960x540. A 720p or 1080p publish caps at\n * 2.5 Mbps until this raises it, however good the connection is.\n *\n * ```ts\n * await reactor.publishTrack('camera', cameraTrack);\n * await reactor.setTrackBitrate('camera', { maxBps: 8_000_000 });\n * ```\n *\n * A ceiling is permission, not a target: the encoder still spends only what\n * the congestion controller allocated and what the picture needs. What\n * raising it buys is headroom for the moments that would otherwise clip.\n *\n * Needs a connected client, and a published track — there is no sender to\n * bound before `publishTrack()`.\n *\n * Omit a bound to leave it at the browser default. `minBps` is non-standard —\n * Chromium honours it, other engines ignore it.\n *\n * There is no connection-wide counterpart: browsers expose no equivalent of\n * the native SDKs' `setBitrate`, and a method that quietly did nothing would\n * be worse than its absence.\n */\n async setTrackBitrate(\n name: string,\n bounds: { minBps?: number; maxBps?: number } = {},\n ): Promise<void> {\n this.assertNotDisposed();\n try {\n await this.queue.push(async () => {\n const client = await this.getOrCreateClient();\n\n await client.setTrackBitrate(name, bounds.minBps, bounds.maxBps);\n }, 'setTrackBitrate');\n } catch (cause) {\n throw this.captureError(cause);\n }\n }\n\n /** Resumes a track previously stopped with `pauseTrack()`. */\n async resumeTrack(name: string): Promise<void> {\n this.assertNotDisposed();\n try {\n await this.queue.push(async () => {\n const client = await this.getOrCreateClient();\n\n await client.resumeTrack(name);\n }, 'resumeTrack');\n } catch (cause) {\n throw this.captureError(cause);\n }\n }\n\n // ── Recording ───────────────────────────────────────────────────────────\n\n /**\n * Requests a clip covering the last `durationSeconds` of the session.\n * `reactor-core` correlates the reply itself (and enforces `\"ready\"`), so\n * this is a thin delegation, same as `requestSchema()`. See\n * `downloadClipAsFile()` to turn the result into a file.\n */\n async requestClip(durationSeconds: number): Promise<Clip> {\n this.assertNotDisposed();\n try {\n // Excluded from connect()/disconnect()/reconnect() — see\n // `withReaderAccess()`'s docs.\n return await this.withReaderAccess(async () => {\n const client = await this.getOrCreateClient();\n\n return toPublicClip(await client.requestClip(durationSeconds));\n });\n } catch (cause) {\n throw this.captureError(cause);\n }\n }\n\n /** Requests a clip covering the entire session up to now. See `requestClip()`. */\n async requestRecording(): Promise<Clip> {\n this.assertNotDisposed();\n try {\n // Excluded from connect()/disconnect()/reconnect() — see\n // `withReaderAccess()`'s docs.\n return await this.withReaderAccess(async () => {\n const client = await this.getOrCreateClient();\n\n return toPublicClip(await client.requestRecording());\n });\n } catch (cause) {\n throw this.captureError(cause);\n }\n }\n\n /** Thin delegation to the standalone `downloadClipAsFile()` — see its own doc comment. */\n async downloadClipAsFile(\n clip: Clip,\n filename: string | null = 'reactor-clip.mp4',\n options?: DownloadClipOptions,\n ): Promise<Blob> {\n return downloadClipAsFileFn(clip, filename, options);\n }\n\n // ── Uploads ─────────────────────────────────────────────────────────────\n\n /**\n * Uploads a file to the session's object store, resolving with a\n * `FileRef` to pass in a `sendCommand()`'s `data`, at the top level or\n * inside an array or object (see `extractFileRefs`). The binding itself\n * takes `(file, name?)`\n * positionally and already applies the right defaulting — a bare\n * `Blob`'s name falls back to `\"upload\"`, and an empty/missing mime type\n * to `\"application/octet-stream\"` — so there's nothing to wrap here.\n *\n * Queued behind connect()/disconnect()/reconnect(), same as the track\n * ops: this awaits its own round-trip, and a concurrent disconnect()\n * freeing the wasm client mid-upload would otherwise resume into a freed\n * client — the same use-after-free class of race the queue exists to\n * prevent.\n */\n async uploadFile(file: File | Blob, options?: { name?: string }): Promise<FileRef> {\n this.assertNotDisposed();\n try {\n const wireFileRef = await this.queue.push(async () => {\n const client = await this.getOrCreateClient();\n\n return client.uploadFile(file, options?.name);\n }, 'uploadFile');\n\n return toPublicFileRef(wireFileRef);\n } catch (cause) {\n throw this.captureError(cause);\n }\n }\n\n /** All tracks the model declared, whether or not media has arrived for —\n * or been published to — them yet. Empty before a client exists. */\n tracks(): TrackCapability[] {\n return this.client?.tracks() ?? [];\n }\n\n /** Same as `tracks()`, plus each entry's negotiated `mid` — the id\n * `trackReceived`'s `mid` argument and the `getXByMid` escape hatches key\n * on. Only populated once SDP negotiation has assigned mids. */\n trackMapping(): TrackMappingEntry[] {\n return this.client?.trackMapping() ?? [];\n }\n\n pausedTracks(): string[] {\n return this.client?.pausedTracks() ?? [];\n }\n\n // ── Escape hatches ──────────────────────────────────────────────────────\n\n /** Drops to the raw `RTCPeerConnection` for anything this class doesn't\n * wrap directly. `undefined` before a client exists. */\n getPeerConnection(): RTCPeerConnection | undefined {\n return this.client?.getPeerConnection();\n }\n\n getTrackByMid(mid: string): MediaStreamTrack | undefined {\n return this.client?.getTrackByMid(mid);\n }\n\n getStreamByMid(mid: string): MediaStream | undefined {\n return this.client?.getStreamByMid(mid);\n }\n\n getTrackByName(name: string): MediaStreamTrack | undefined {\n return this.client?.getTrackByName(name);\n }\n\n getStreamByName(name: string): MediaStream | undefined {\n return this.client?.getStreamByName(name);\n }\n\n /**\n * Supports `using reactor = new Reactor(...)`: releases the wasm resource\n * graph and drops every registered event handler for good. Unlike a plain\n * `disconnect()`, this instance is unusable afterward — construct a new\n * `Reactor` instead of trying to `connect()` again.\n */\n [Symbol.dispose](): void {\n if (this.disposed) {\n return;\n }\n this.disposed = true;\n const client = this.client;\n\n this.client = undefined;\n this.clientPromise = undefined;\n this.schema = undefined;\n this.capabilities = undefined;\n this.resetConnectionState();\n this.emitter.clear();\n if (client) {\n // Queued behind any in-flight connect()/reconnect()/disconnect(), same\n // as freeClient() — this can't await that itself, since [Symbol.dispose]\n // is synchronous per the `using` contract. Also excluded from any read\n // still in flight, same as freeClient() — see `withWriterAccess()`.\n void this.queue\n .push(() => this.withWriterAccess(() => Promise.resolve(client.free())), 'dispose')\n .catch(() => {});\n }\n }\n\n // ── Introspection ───────────────────────────────────────────────────────\n\n /** The wasm binding's own terser `status()` name can be added alongside\n * this later if it turns out to be worth it. */\n getStatus(): ReactorStatus {\n return this.client?.status() ?? 'disconnected';\n }\n\n /** See `getStatus()`. */\n getSessionId(): string | undefined {\n return this.client?.sessionId();\n }\n\n /** The `jwt` this instance was constructed (or last `connect()`ed) with —\n * lets a component composed inside a `ReactorProvider` (e.g. `ClipPlayer`)\n * authenticate its own requests without the caller repeating the resolver. */\n getJwtResolver(): JwtSource | undefined {\n return this.jwt ?? undefined;\n }\n\n /** The most recent `ReactorError`, from either an `error` event or a\n * rejected call — whichever landed last. `undefined` until the first\n * failure. */\n getLastError(): ReactorError | undefined {\n return this._lastError;\n }\n\n /** The most recent WebRTC connection stats, polled every `LOCAL_STATS_INTERVAL_MS`\n * while \"ready\" — see `statsUpdate`. `undefined` before the first sample. */\n getStats(): ConnectionStats | undefined {\n return this.stats;\n }\n\n /** Timing breakdown from the most recent `connect()`/`reconnect()`\n * handshake — see `ConnectionTimings`. */\n getConnectionTimings(): ConnectionTimings | undefined {\n return this.connectionTimings;\n }\n\n // ── Events ──────────────────────────────────────────────────────────────\n\n on<Name extends keyof ReactorEventMap>(event: Name, handler: ReactorEventMap[Name]): void {\n this.emitter.on(event, handler);\n }\n\n off<Name extends keyof ReactorEventMap>(event: Name, handler: ReactorEventMap[Name]): void {\n this.emitter.off(event, handler);\n }\n\n once<Name extends keyof ReactorEventMap>(event: Name, handler: ReactorEventMap[Name]): void {\n this.emitter.once(event, handler);\n }\n\n // ── Internal ────────────────────────────────────────────────────────────\n\n private getOrCreateClient(): Promise<ReactorClient> {\n if (!this.clientPromise) {\n this.clientPromise = this.createClient().catch((cause) => {\n // A failed first connect shouldn't wedge every later attempt behind\n // a client that never came up.\n this.clientPromise = undefined;\n throw cause;\n });\n }\n return this.clientPromise;\n }\n\n private async createClient(): Promise<ReactorClient> {\n const { ReactorClient: WasmReactorClient } = await loadReactorWasm();\n\n // [Symbol.dispose] may have run while the wasm module was loading above;\n // bail out before constructing a client that would otherwise outlive it\n // and never get freed.\n if (this.disposed) {\n throw new Error('Reactor was disposed while connecting.');\n }\n const client = new WasmReactorClient(this.clientOptions, this.jwt);\n\n client.onStatusChanged((status) => {\n this.emitter.emit('statusChanged', status);\n this.handleStatusChanged(client, status);\n });\n client.onSessionIdChanged((sessionId) => this.emitter.emit('sessionIdChanged', sessionId));\n client.onError((error) => this.emitError(error));\n // DATA channel — the model's own application traffic.\n client.onMessage((message) => {\n debugLog('[Reactor] message:', message);\n this.emitter.emit('message', message);\n });\n // CONTROL channel — platform traffic (moderation, clip/recording lifecycle).\n client.onRuntimeMessage((message) => {\n debugLog('[Reactor] runtimeMessage:', message);\n this.emitter.emit('runtimeMessage', message);\n });\n client.onCapabilitiesReceived((capabilities) => {\n this.capabilities = toPublicCapabilities(capabilities);\n this.emitter.emit('capabilitiesReceived', this.capabilities);\n });\n client.onTrackReceived((name, mid) => {\n const track = client.getTrackByName(name);\n const stream = client.getStreamByName(name);\n\n // Structurally shouldn't happen — `reactor-core` only dispatches this\n // event once the track is already resolvable — but if it ever does\n // (e.g. a teardown racing the dispatch), skip rather than emitting a\n // lie about the (non-optional) type.\n if (!track || !stream) {\n return;\n }\n this.emitter.emit('trackReceived', name, track, stream, mid);\n });\n this.client = client;\n return client;\n }\n\n /** Fired once per `\"ready\"` transition — see `getSchema()`. `getSchema()`\n * isn't guaranteed populated by the time a `statusChanged` \"ready\" handler\n * runs (this fetch is async and dispatched separately), so callers that\n * need the schema as soon as it lands should listen for `schemaReceived`\n * instead of reading `getSchema()` synchronously off `statusChanged`.\n *\n * Guards against a stale reply: if `disconnect()`/a later `connect()`\n * replaces `client` before this resolves, or a newer `refreshSchema()`\n * call for the same client wins the race, the result is discarded rather\n * than clobbering `this.schema` (or emitting `schema`) with old data.\n *\n * A rejection here (e.g. the session drops mid-request) surfaces like any\n * other binding failure, through the same `error` event as `onError`. */\n private async refreshSchema(client: ReactorClient): Promise<void> {\n const refreshId = ++this.schemaRefreshId;\n\n try {\n const schema = this.normalizeSchema(await client.requestSchema());\n\n if (this.client !== client || refreshId !== this.schemaRefreshId) {\n return;\n }\n // No schema for this model (wire `null`): leave the cache/event alone\n // rather than surfacing an empty document.\n if (schema === undefined) {\n return;\n }\n this.schema = schema;\n this.emitter.emit('schemaReceived', this.schema);\n // Also surface as a generic runtime-scope message so consumers that\n // filter `runtimeMessage` by `type` (rather than the typed event) see\n // it too — the same reply, two shapes, emitted from the same `schema`\n // value in the same tick, so they can't disagree here. `schemaReceived`\n // /`getSchema()` is the authoritative surface; `runtimeMessage` is the\n // generic fan-out kept for parity with v2 (`core/Reactor.ts`), which\n // does the same dual emit from the same `requestSchema` reply.\n this.emitter.emit('runtimeMessage', { type: 'modelSchema', data: this.schema });\n } catch (cause) {\n if (this.client !== client || refreshId !== this.schemaRefreshId) {\n return;\n }\n this.emitError(cause);\n }\n }\n\n /** The binding replies with a wire `null` (not an omitted field) when the\n * model doesn't expose a schema — normalized to `undefined` so callers\n * get the same \"no schema\" sentinel `getSchema()` already uses instead\n * of a document they could otherwise dereference. */\n private normalizeSchema(schema: unknown): ModelSchema | undefined {\n return (schema ?? undefined) as ModelSchema | undefined;\n }\n\n /** Frees the wasm resource graph, if one exists, and clears the cached\n * schema. Reusable — unlike `[Symbol.dispose]`, this doesn't set the\n * permanent `disposed` flag, so a later `connect()`/`reconnect()` lazily\n * builds a fresh client.\n *\n * Only called from within `disconnect()`'s queued task, so `client.free()`\n * is safe to call directly here — the queue already guarantees no other\n * operation is running concurrently against it. */\n private freeClient(): void {\n this.client?.free();\n this.client = undefined;\n this.clientPromise = undefined;\n this.schema = undefined;\n this.capabilities = undefined;\n }\n\n /** Tracks `connectionTimings` off the binding's own \"connecting\" → \"waiting\"\n * → \"ready\" status sequence (see `ReactorStatus`), and starts/stops stats\n * polling around the \"ready\" window. */\n private handleStatusChanged(client: ReactorClient, status: ReactorStatus): void {\n switch (status) {\n case 'connecting':\n this.connectStartTime = performance.now();\n this.waitingStartTime = undefined;\n break;\n case 'waiting':\n this.waitingStartTime = performance.now();\n break;\n case 'ready': {\n const readyTime = performance.now();\n\n if (this.connectStartTime != null) {\n const waitingStartTime = this.waitingStartTime ?? readyTime;\n\n this.connectionTimings = {\n sessionCreationMs: waitingStartTime - this.connectStartTime,\n transportConnectingMs: readyTime - waitingStartTime,\n totalMs: readyTime - this.connectStartTime,\n };\n }\n this.startStatsPolling(client);\n void this.refreshSchema(client);\n break;\n }\n default:\n this.stopStatsPolling();\n }\n }\n\n /** Starts both stats pollers: the local one updates `getStats()` and emits\n * `statsUpdate`, the runtime one sends a client-stats batch. Each owns the\n * extractor it computes bitrates with, so a bitrate covers its own\n * poller's interval. */\n private startStatsPolling(client: ReactorClient): void {\n this.stopStatsPolling();\n const extractConnectionStats = createConnectionStatsExtractor();\n const extractTrackStats = createTrackStatsExtractor();\n\n this.hasSentConnectTime = false;\n this.stopStatsPollers = [\n pollPeerStats(client, LOCAL_STATS_INTERVAL_MS, (report) => {\n this.stats = { ...extractConnectionStats(report), connectionTimings: this.connectionTimings };\n this.emitter.emit('statsUpdate', this.stats);\n }),\n pollPeerStats(client, RUNTIME_REPORT_INTERVAL_MS, (report) => {\n this.reportClientStats(client, report, extractTrackStats);\n }),\n ];\n }\n\n /** Report one quality batch to the runtime: a reading per negotiated\n * track — audio and video, sent and received — see\n * `createTrackStatsExtractor`, and the connection-wide reading — see\n * `toClientConnectionStat`. The connection reading goes even while no\n * track has one yet (none negotiated onto a named track, or no codec\n * reported yet), so the runtime gets the bandwidth estimate, the\n * round-trip time and the time to connect without waiting on the tracks.\n * Skipped only when there is nothing at all to say; one is due again in\n * `RUNTIME_REPORT_INTERVAL_MS`. The time to connect goes on the first batch\n * actually sent for this connection — see `hasSentConnectTime`.\n * `sendClientStats` throws synchronously on a closing connection; caught\n * here for the same reason `getStats()`'s rejection is above. */\n private reportClientStats(\n client: ReactorClient,\n report: RTCStatsReport,\n extractTrackStats: TrackStatsExtractor,\n ): void {\n const trackStats = extractTrackStats(report, this.trackMapping(), this.pausedTracks());\n const timeToConnectMs = this.hasSentConnectTime ? undefined : this.connectionTimings?.totalMs;\n const connectionStat = toClientConnectionStat(report, timeToConnectMs);\n\n if (trackStats.length === 0 && Object.keys(connectionStat.metrics).length === 0) {\n return;\n }\n\n try {\n client.sendClientStats(trackStats, connectionStat);\n if (timeToConnectMs !== undefined) {\n this.hasSentConnectTime = true;\n }\n } catch {\n // Connection may be closing.\n }\n }\n\n private stopStatsPolling(): void {\n for (const stop of this.stopStatsPollers) {\n stop();\n }\n this.stopStatsPollers = [];\n this.stats = undefined;\n }\n\n /** Called on every `disconnect()` and on `[Symbol.dispose]`. Leaves\n * `client`/`schema` alone — that's `freeClient()`'s job, run separately\n * when `disconnect()` isn't recoverable. `capabilities` is cleared here\n * regardless, though: unlike the schema, it isn't re-fetched on demand,\n * so a recoverable disconnect that skips `freeClient()` would otherwise\n * leave `getCapabilities()` returning the previous session's stale\n * tracks/commands until a new `capabilitiesReceived` lands. */\n private resetConnectionState(): void {\n this.stopStatsPolling();\n this.connectionTimings = undefined;\n this.connectStartTime = undefined;\n this.waitingStartTime = undefined;\n this.capabilities = undefined;\n }\n\n /** Wraps `cause` and records it as the most recent failure, for a call\n * that's about to throw rather than emit — see `getLastError()`'s doc\n * comment. */\n private captureError(cause: unknown): ReactorError {\n const error = toReactorError(cause);\n\n this._lastError = error;\n return error;\n }\n\n /** Wraps `cause`, records it as the most recent failure, and fires the\n * `error` event — the one place recording and emitting happen together,\n * so `getLastError()` never drifts from what listeners were told. */\n private emitError(cause: unknown): void {\n this.emitter.emit('error', this.captureError(cause));\n }\n\n private assertNotDisposed(): void {\n if (this.disposed) {\n throw new Error(\"This Reactor was disposed and can't be used again — construct a new one.\");\n }\n }\n}\n","import type { Capabilities } from '../types';\nimport type { Capabilities as WireCapabilities } from './reactor-wasm.types';\n\n/** The wasm binding's snake_case wire shape → the public, camelCase one —\n * what `Reactor.getCapabilities()`/`capabilitiesReceived` hand back to a\n * caller. */\nexport function toPublicCapabilities(wire: WireCapabilities): Capabilities {\n const capabilities: Capabilities = {\n protocolVersion: wire.protocol_version,\n tracks: wire.tracks,\n };\n\n if (wire.commands !== undefined) {\n capabilities.commands = wire.commands;\n }\n if (wire.emission_fps !== undefined) {\n capabilities.emissionFps = wire.emission_fps;\n }\n return capabilities;\n}\n","declare const process: { env?: { NODE_ENV?: string } } | undefined;\ndeclare global {\n interface ImportMeta {\n readonly env?: { readonly DEV?: boolean };\n }\n}\n\n// No single check covers every bundler actually used with this SDK: webpack\n// and Next.js globally replace `process.env.NODE_ENV` (including inside\n// dependencies), even though no real `process` global exists in the browser\n// at runtime — but Vite does not, by default, do that same replacement for a\n// dependency's `process.env.NODE_ENV` (verified: it survives, unreplaced,\n// into a Vite production bundle, where `typeof process` is then genuinely\n// `'undefined'` at runtime — silently always off). Vite instead exposes its\n// own `import.meta.env.DEV`, real at runtime, for every module it processes,\n// dependencies included. Checking both covers both; neither reference\n// throws where the other bundler's mechanism is the one in play.\nconst isDev =\n (typeof process !== 'undefined' && process?.env?.NODE_ENV === 'development') ||\n import.meta.env?.DEV === true;\n\n/** Logs wire traffic (data/control channel messages) in development builds\n * only — useful while iterating against a model, silent in production. */\nexport function debugLog(...args: unknown[]): void {\n if (isDev) {\n console.debug(...args);\n }\n}\n","/**\n * Every Reactor failure carries `code`, `recoverable`, `status`, `operation`,\n * `retry_after_ms` and `timestamp_ms` — `reactor-core`'s canonical shape,\n * shared by every SDK on it. `timestamp`/`retryAfter` are kept alongside\n * under their previous names for compatibility — see their own doc comments\n * below — rather than dropped, since this package's public API may only\n * grow.\n *\n * There is **one class**, not two: the `error` event payload and a rejected\n * call's error are the same shape and the same instance type.\n *\n * `ReactorError` is the base of a typed hierarchy keyed by `code` —\n * `reactor-core`'s own per-failure-kind classification — so `instanceof\n * UnauthorizedError` and `code === 'UNAUTHORIZED'` are equivalent, one just\n * typed. Codes are open-ended (the platform can send its own), so an\n * unrecognized one falls back to the base class itself rather than\n * throwing.\n */\n/** Fields a `ReactorError` constructor accepts, all optional — an\n * unrecognized code still constructs cleanly on the base class, and a\n * purely local failure (no payload at all) still constructs cleanly too. */\nexport interface ReactorErrorOptions {\n code?: string | undefined;\n recoverable?: boolean | undefined;\n status?: number | undefined;\n operation?: string | undefined;\n retry_after_ms?: number | undefined;\n timestamp_ms?: number | undefined;\n /** The underlying error, kept as the standard `Error.cause`. */\n cause?: unknown;\n}\n\nexport class ReactorError extends Error {\n /** The code this class stands for. `ReactorError` itself is the fallback,\n * so it claims none and takes whatever the payload reported. */\n static readonly code: string = 'INTERNAL_ERROR';\n\n /** `reactor-core`'s own canonical code for this failure — the same value\n * used to pick this instance's class (see the typed subclasses below for\n * the vocabulary). Open-ended: an unrecognized code still constructs the\n * base class, with `code` set to whatever was reported. */\n readonly code: string;\n /** Whether the same call could succeed later. */\n readonly recoverable: boolean;\n /** The HTTP status, when the failure came from one. */\n readonly status: number | undefined;\n /** Which call failed, e.g. \"connect\", \"sendCommand\". */\n readonly operation: string | undefined;\n /** Backoff hint the platform sent. */\n readonly retry_after_ms: number | undefined;\n /** When `reactor-core` reported this failure. For a purely local one (no\n * payload at all — see {@link ReactorErrorOptions}), this is synthesized\n * as the construction time instead, since there's nothing to report —\n * not a value read off the wire. */\n readonly timestamp_ms: number;\n\n /** Same value as `retry_after_ms`, under its previous name. Kept for\n * compatibility — prefer `retry_after_ms`. */\n readonly retryAfter: number | undefined;\n /** Same value as `timestamp_ms`, under its previous name. Kept for\n * compatibility — prefer `timestamp_ms`. */\n readonly timestamp: number;\n\n constructor(message: string, options: ReactorErrorOptions = {}) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause });\n this.name = 'ReactorError';\n // An explicit code wins, so an unrecognized one survives on the base\n // class rather than being relabelled as the fallback it was routed to.\n this.code = options.code ?? new.target.code;\n this.recoverable = options.recoverable ?? false;\n this.status = options.status;\n this.operation = options.operation;\n this.retry_after_ms = options.retry_after_ms;\n this.retryAfter = options.retry_after_ms;\n this.timestamp_ms = options.timestamp_ms ?? Date.now();\n this.timestamp = this.timestamp_ms;\n }\n}\n\n/** The request never got a reply — DNS, TLS, a refused socket. */\nexport class NetworkError extends ReactorError {\n static override readonly code = 'NETWORK_ERROR';\n}\n\n/** 401 or 403: the token is missing, expired, or not scoped for this call. */\nexport class UnauthorizedError extends ReactorError {\n static override readonly code = 'UNAUTHORIZED';\n}\n\n/** 404: no such model, session or upload. */\nexport class NotFoundError extends ReactorError {\n static override readonly code = 'NOT_FOUND';\n}\n\n/** 409: the session is in a state that does not allow this — usually a\n * session left orphaned by a previous run that went away without\n * disconnecting. */\nexport class ConflictError extends ReactorError {\n static override readonly code = 'CONFLICT';\n}\n\n/** 429: too many requests. `retry_after_ms` carries the server's\n * `Retry-After` when it sent one; `undefined` means back off on your own\n * terms rather than retrying immediately. */\nexport class RateLimitedError extends ReactorError {\n static override readonly code = 'RATE_LIMITED';\n}\n\n/** A 4xx other than the ones above: the request itself was wrong. */\nexport class BadRequestError extends ReactorError {\n static override readonly code = 'BAD_REQUEST';\n}\n\n/** 5xx: the coordinator failed, and the same request may work later. */\nexport class ServerError extends ReactorError {\n static override readonly code = 'SERVER_ERROR';\n}\n\n/** This client and the platform disagree on the protocol — upgrade the SDK. */\nexport class VersionMismatchError extends ReactorError {\n static override readonly code = 'VERSION_MISMATCH';\n}\n\n/** A reply arrived and could not be understood. */\nexport class DecodeError extends ReactorError {\n static override readonly code = 'DECODE_FAILED';\n}\n\n/** The operation is not allowed from the state the client is in — most often\n * a call that needs a live session, made before `connect()` or after the\n * status left `\"ready\"`. */\nexport class InvalidStateError extends ReactorError {\n static override readonly code = 'INVALID_STATE';\n}\n\n/** The session reached a state it cannot leave. Start a new one. */\nexport class SessionTerminalError extends ReactorError {\n static override readonly code = 'SESSION_TERMINAL';\n}\n\n/** The payload exceeds what the data channel accepts — send large content\n * with `uploadFile()` and pass the `FileRef` instead of embedding it\n * inline in a command. */\nexport class MessageTooLargeError extends ReactorError {\n static override readonly code = 'MESSAGE_TOO_LARGE';\n}\n\n/** The media transport failed. */\nexport class TransportError extends ReactorError {\n static override readonly code = 'TRANSPORT_ERROR';\n}\n\n/** The connection went away, either dropped mid-request or lost after being\n * established. `reconnect()` is the way back. */\nexport class DisconnectedError extends ReactorError {\n static override readonly code = 'DISCONNECTED';\n}\n\n/** The operation was sent and nothing came back in time. */\nexport class RequestTimeoutError extends ReactorError {\n static override readonly code = 'REQUEST_TIMEOUT';\n}\n\n/** The operation was abandoned before it finished. */\nexport class AbortedError extends ReactorError {\n static override readonly code = 'ABORTED';\n}\n\n/**\n * A `requestClip()`/`requestRecording()` call failed because the model's\n * recorder is disabled or has crashed.\n *\n * Unlike every other code here, `RECORDER_DISABLED` isn't platform-sent —\n * `reactor-core` produces it by matching known reason strings on an\n * otherwise free-text `ClipFailed` message, as a stopgap until that message\n * carries a structured reason (tracked as REA-5403). Treat it as best-effort:\n * a clip failure for the same underlying reason may still arrive as the\n * base `ReactorError` (`code: \"INTERNAL_ERROR\"`) if the reason text ever\n * changes upstream.\n *\n * `recoverable` is `false`: the recorder being disabled or crashed isn't\n * something retrying the same `requestClip()`/`requestRecording()` call can\n * fix — it needs an operator to re-enable or restart the recorder on the\n * model side first.\n */\nexport class RecorderDisabledError extends ReactorError {\n static override readonly code = 'RECORDER_DISABLED';\n}\n\n/** Every code this package has a class for. Anything else — a platform code\n * for a rejected request — falls back to `ReactorError` with `code` set to\n * it. */\nconst ERROR_CLASSES = [\n NetworkError,\n UnauthorizedError,\n NotFoundError,\n ConflictError,\n RateLimitedError,\n BadRequestError,\n ServerError,\n VersionMismatchError,\n DecodeError,\n InvalidStateError,\n SessionTerminalError,\n MessageTooLargeError,\n TransportError,\n DisconnectedError,\n RequestTimeoutError,\n AbortedError,\n RecorderDisabledError,\n] as const;\n\ninterface ReactorErrorClass {\n readonly code: string;\n new (message: string, options?: ReactorErrorOptions): ReactorError;\n}\n\nconst BY_CODE = new Map<string, ReactorErrorClass>(\n ERROR_CLASSES.map((errorClass) => [errorClass.code, errorClass]),\n);\n\n/** The exception class for `code`, or the base class for anything unknown. */\nexport function errorForCode(code: string | undefined): ReactorErrorClass {\n return (code && BY_CODE.get(code)) || ReactorError;\n}\n\n/** A record shape the wasm binding hands over, either as an `onError` event\n * payload or `Object.assign`ed onto a rejected call's thrown `Error`. */\ninterface ReactorErrorLike {\n code?: string;\n message?: string;\n recoverable?: boolean;\n status?: number;\n operation?: string;\n retry_after_ms?: number;\n timestamp_ms?: number;\n}\n\n/**\n * Builds the typed exception for whatever the wasm binding handed over —\n * the plain object an `onError` event delivers, or the `Error` a rejected\n * call throws (message plus the same fields, `Object.assign`ed on).\n *\n * Already a `ReactorError`? Returned as-is, so wrapping is idempotent.\n * Anything else not shaped like the binding's payload (a bug elsewhere, a\n * plain string, or a purely local failure with no payload at all — a wasm\n * load/constructor throw, a call on a disposed client) still becomes a\n * `ReactorError` rather than propagating an untyped failure, falling back to\n * `INTERNAL_ERROR` when there's no code to report.\n */\nexport function toReactorError(cause: unknown): ReactorError {\n if (cause instanceof ReactorError) {\n return cause;\n }\n const payload = (cause ?? {}) as ReactorErrorLike;\n const message = typeof payload.message === 'string' ? payload.message : String(cause);\n const ErrorClass = errorForCode(payload.code);\n\n return new ErrorClass(message, {\n code: payload.code,\n recoverable: payload.recoverable,\n status: payload.status,\n operation: payload.operation,\n retry_after_ms: payload.retry_after_ms,\n timestamp_ms: payload.timestamp_ms,\n // A thrown JS error (a failed wasm load, say) keeps its stack and its own\n // `cause` reachable; reactor-core's plain payload objects have neither.\n cause: cause instanceof Error ? cause : undefined,\n });\n}\n","/** A minimal typed pub/sub — `on`/`off`/`once` over a fixed event map.\n *\n * `EventMap` is deliberately unconstrained: a `Record<string, ...>` bound\n * would force every event map to declare a string index signature, which\n * would let any string through as an event name and throw away the whole\n * point of typing this per call site. */\nexport class Emitter<EventMap extends { [Name in keyof EventMap]: (...args: never[]) => void }> {\n private readonly listeners = new Map<keyof EventMap, Set<EventMap[keyof EventMap]>>();\n\n on<Name extends keyof EventMap>(event: Name, handler: EventMap[Name]): void {\n let handlers = this.listeners.get(event);\n\n if (!handlers) {\n handlers = new Set();\n this.listeners.set(event, handlers);\n }\n handlers.add(handler);\n }\n\n off<Name extends keyof EventMap>(event: Name, handler: EventMap[Name]): void {\n this.listeners.get(event)?.delete(handler);\n }\n\n once<Name extends keyof EventMap>(event: Name, handler: EventMap[Name]): void {\n const wrapped = ((...args: Parameters<EventMap[Name]>) => {\n this.off(event, wrapped);\n (handler as (...args: Parameters<EventMap[Name]>) => void)(...args);\n }) as EventMap[Name];\n\n this.on(event, wrapped);\n }\n\n emit<Name extends keyof EventMap>(event: Name, ...args: Parameters<EventMap[Name]>): void {\n const handlers = this.listeners.get(event);\n\n if (!handlers) {\n return;\n }\n // Snapshot before calling: a handler is free to `off`/`once` itself or\n // register another one mid-dispatch without corrupting this pass.\n for (const handler of [...handlers]) {\n try {\n (handler as (...args: Parameters<EventMap[Name]>) => void)(...args);\n } catch (error) {\n // A handler throwing shouldn't stop delivery to the handlers after\n // it — one broken listener in the app shouldn't break the SDK's own\n // reporting to its other listeners.\n console.error(`[Emitter] handler for \"${String(event)}\" threw:`, error);\n }\n }\n }\n\n /** Drops every registered handler for every event. */\n clear(): void {\n this.listeners.clear();\n }\n}\n","/**\n * Reference to a file uploaded via `Reactor.uploadFile()`. Pass it back in\n * `sendCommand()`'s `data` wherever the model's schema declares a file: as a\n * top-level value it's extracted and sent as a separate upload reference,\n * and inside an array or object it's serialized as one — see\n * `extractFileRefs()`.\n */\nexport class FileRef {\n constructor(\n public readonly uploadId: string,\n public readonly name: string,\n public readonly mimeType: string,\n public readonly size: number,\n ) {}\n}\n\n/**\n * Structural check for anything shaped like a `FileRef`, for callers who'd\n * rather duck-type than rely on `instanceof` (e.g. across two copies of this\n * package bundled into the same page). `extractFileRefs()` uses this too,\n * for the same reason.\n */\nexport function isFileRef(value: unknown): value is FileRef {\n if (value instanceof FileRef) {\n return true;\n }\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n const candidate = value as Partial<FileRef>;\n\n return (\n typeof candidate.uploadId === 'string' &&\n typeof candidate.name === 'string' &&\n typeof candidate.mimeType === 'string' &&\n typeof candidate.size === 'number'\n );\n}\n","import { FileRef, isFileRef } from '../file-ref';\nimport type { FileRef as WireFileRef } from './reactor-wasm.types';\n\n/** camelCase → the wasm binding's own snake_case wire shape. */\nfunction toWireFileRef(fileRef: FileRef): WireFileRef {\n return {\n upload_id: fileRef.uploadId,\n name: fileRef.name,\n mime_type: fileRef.mimeType,\n size: fileRef.size,\n };\n}\n\n/** The wasm binding's snake_case wire shape → the public `FileRef` — what\n * `Reactor.uploadFile()` actually hands back to a caller. */\nexport function toPublicFileRef(fileRef: WireFileRef): FileRef {\n return new FileRef(fileRef.upload_id, fileRef.name, fileRef.mime_type, fileRef.size);\n}\n\n/**\n * Splits `data` into scalar command args and `FileRef` uploads: callers pass\n * a `FileRef` (from `uploadFile`) inline as a normal field and never build\n * the `uploads` map by hand. Each matched `FileRef` is translated to the\n * wasm binding's wire shape here, since that's what `sendCommand`'s\n * `uploads` argument actually expects.\n *\n * A top-level `FileRef` moves into `uploads`, keyed by its parameter name —\n * the one slot the wire has for a named upload. A `FileRef` nested inside an\n * array or an object has no such slot, so it stays in `data` and is rewritten\n * to the wire shape in place: the binding serializes `data` by reading each\n * object's own enumerable properties, so a `FileRef` left as-is would cross\n * the wire with its camelCase field names, which the model side does not\n * read. The walk follows the same rule the binding does — every array\n * element and every own enumerable property of every object, whatever its\n * prototype — so a `FileRef` is found wherever the binding would have\n * serialized it. A `Date` or a `Blob` has no enumerable properties and passes\n * through; a typed array is bytes and is skipped outright.\n *\n * Uses `isFileRef()`'s structural check rather than `instanceof FileRef`:\n * a duplicate copy of this package (e.g. two versions bundled into the same\n * page) produces a `FileRef` that fails `instanceof` against this module's\n * class but still type-checks and looks identical on the wire — routing it\n * through `data` instead of `uploads` would otherwise make the wire reject\n * an otherwise-valid command.\n */\nexport function extractFileRefs(data: Record<string, unknown> | undefined): {\n data: Record<string, unknown> | undefined;\n uploads: Record<string, WireFileRef> | undefined;\n} {\n if (!data) {\n return { data, uploads: undefined };\n }\n\n let uploads: Record<string, WireFileRef> | undefined;\n let scalars: Record<string, unknown> | undefined;\n\n for (const [key, value] of Object.entries(data)) {\n if (isFileRef(value)) {\n uploads ??= {};\n scalars ??= { ...data };\n uploads[key] = toWireFileRef(value);\n delete scalars[key];\n continue;\n }\n const rewritten = rewriteNestedFileRefs(value);\n\n if (rewritten !== value) {\n scalars ??= { ...data };\n scalars[key] = rewritten;\n }\n }\n\n return { data: scalars ?? data, uploads };\n}\n\n/**\n * Returns `value` with every `FileRef` inside it replaced by its wire shape,\n * or `value` itself when it contains none, so an untouched payload keeps its\n * identity.\n */\nfunction rewriteNestedFileRefs(value: unknown): unknown {\n if (isFileRef(value)) {\n return toWireFileRef(value);\n }\n if (Array.isArray(value)) {\n const elements: unknown[] = value;\n let copy: unknown[] | undefined;\n\n elements.forEach((element, index) => {\n const rewritten = rewriteNestedFileRefs(element);\n\n if (rewritten !== element) {\n copy ??= [...elements];\n copy[index] = rewritten;\n }\n });\n return copy ?? elements;\n }\n if (isSerializedAsObject(value)) {\n let copy: Record<string, unknown> | undefined;\n\n // A copy spreads the own enumerable properties, which is exactly the set\n // the binding would have serialized off the original, so a class instance\n // that held a `FileRef` reaches the wire the same as before, minus the\n // camelCase reference.\n for (const [key, element] of Object.entries(value)) {\n const rewritten = rewriteNestedFileRefs(element);\n\n if (rewritten !== element) {\n copy ??= { ...value };\n copy[key] = rewritten;\n }\n }\n return copy ?? value;\n }\n return value;\n}\n\n/** Whether the binding serializes `value` as an object of its own enumerable\n * properties — anything object-like except a typed array, which it serializes\n * as bytes and which could hold no `FileRef` anyway. */\nfunction isSerializedAsObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !ArrayBuffer.isView(value);\n}\n","import type { Clip, ClipKind } from '../types';\nimport type { Clip as WireClip } from './reactor-wasm.types';\n\n/** The wasm binding's snake_case wire shape → the public, camelCase one —\n * what `Reactor.requestClip()` / `requestRecording()` hand back to a caller.\n * One-directional: a `Clip` is only ever received, never sent, so there's no\n * `toWireClip` counterpart.\n *\n * `kind` is narrowed from the binding's own untyped `string` — `reactor-core`\n * only ever sends `\"snap\"` (from `requestClip()`) or `\"recording\"` (from\n * `requestRecording()`), same as `crates/reactor-wasm/src/types.rs`'s own\n * doc comment for the field. */\nexport function toPublicClip(clip: WireClip): Clip {\n return {\n sessionId: clip.session_id,\n kind: clip.kind as ClipKind,\n startMarker: clip.start_marker,\n endMarker: clip.end_marker,\n nowMarker: clip.now_marker,\n predictedReadyAtMs: clip.predicted_ready_at_ms,\n playlistUrl: clip.playlist_url,\n };\n}\n","import type { ConnectionStats } from '../types';\nimport type {\n ClientConnectionStat,\n ClientTrackStat,\n ReactorClient,\n TrackDirection,\n TrackKind,\n TrackMappingEntry,\n} from './reactor-wasm.types';\n\n// Two intervals, so the local `statsUpdate` cadence and the runtime report\n// cadence can each change without affecting the other.\n\n/** How often `Reactor` reads `getStats()` while ready to update the stats it\n * exposes inside the SDK: `getStats()` and the `statsUpdate` event. Nothing\n * read on this timer leaves the browser. */\nexport const LOCAL_STATS_INTERVAL_MS = 2_000;\n\n/** How often `Reactor` sends a client-stats batch to the runtime while ready.\n * Runs on its own timer and its own `getStats()` read, apart from\n * `LOCAL_STATS_INTERVAL_MS`, so each batch's bitrates cover the whole\n * interval since the previous batch. */\nexport const RUNTIME_REPORT_INTERVAL_MS = 5_000;\n\n/** Reads `getStats()` off *client*'s peer connection every *intervalMs* and\n * hands each report to *onReport*. A tick without a peer connection, or\n * whose read rejects (the connection may be closing), is skipped. An error\n * thrown by *onReport* itself is a bug, not a closing connection, so it is\n * logged rather than swallowed, and polling goes on.\n *\n * One read at a time: a tick that finds the previous read still pending is\n * skipped. Reads that overlapped could resolve out of order, and a\n * bitrate is a delta against the previous report, so an older report\n * landing after a newer one would set the baseline back in time.\n *\n * Returns the function that stops it. Clearing the interval can't cancel a\n * `getStats()` already in flight, so a read that resolves after the stop is\n * dropped instead of reaching *onReport*: a recoverable disconnect can\n * restart polling on the same client, and the old read must not land in the\n * new one. */\nexport function pollPeerStats(\n client: Pick<ReactorClient, 'getPeerConnection'>,\n intervalMs: number,\n onReport: (report: RTCStatsReport) => void,\n): () => void {\n let stopped = false;\n let reading = false;\n const handle = setInterval(() => {\n if (reading) {\n return;\n }\n const peerConnection = client.getPeerConnection();\n\n if (!peerConnection) {\n return;\n }\n reading = true;\n void peerConnection\n .getStats()\n .then(\n (report) => {\n if (stopped) {\n return;\n }\n try {\n onReport(report);\n } catch (error) {\n console.error('[Reactor] stats report handler threw:', error);\n }\n },\n () => {\n // Connection may be closing.\n },\n )\n .finally(() => {\n reading = false;\n });\n }, intervalMs);\n\n return () => {\n stopped = true;\n clearInterval(handle);\n };\n}\n\n/** A duration in milliseconds rounded to the microsecond, for the runtime\n * report. Durations reach it as binary floats — `getStats()` seconds times\n * 1000, or the difference of two `performance.now()` readings — and would\n * otherwise travel as values like `0.8109999999999999` or\n * `6294.200000047684`. */\nfunction roundMs(ms: number): number {\n return Math.round(ms * 1_000) / 1_000;\n}\n\n/** A WebRTC duration in seconds as milliseconds — see `roundMs()`. */\nfunction secondsToMs(seconds: number): number {\n return roundMs(seconds * 1_000);\n}\n\n/** The codecs the wire's `VideoCodec`/`AudioCodec` enums can carry, per\n * track kind. `sendClientStats` rejects the whole batch over one codec\n * outside this set, so a track negotiated onto anything else is left out\n * of the batch rather than taking every other track's reading down with it.\n *\n * Mirrors `client_track_codec` in `crates/reactor-core/src/stats.rs`. A\n * reactor-core test compares this list with the wire's codec enums, so it\n * fails when the wire gains a codec: add it there and here together. */\nconst WIRE_CODECS: Record<TrackKind, ReadonlySet<string>> = {\n video: new Set(['vp8', 'vp9', 'av1', 'h264', 'h265']),\n audio: new Set(['opus']),\n};\n\n/** The previous reading of one RTP stream's byte counter, for turning it\n * into a bitrate. */\ninterface ByteSample {\n bytes: number;\n timestamp: number;\n}\n\n/** Builds one batch of the wire's `ClientTrackStat`s from a stats report, a\n * reading per negotiated track — audio and video, sent and received. */\nexport type TrackStatsExtractor = (\n report: RTCStatsReport,\n tracks: readonly TrackMappingEntry[],\n pausedTracks: readonly string[],\n) => ClientTrackStat[];\n\n/**\n * The per-track part of the runtime report: one reading per track, every\n * `RUNTIME_REPORT_INTERVAL_MS`. Not used for `getStats()` / `statsUpdate`.\n *\n * A closure over each RTP stream's previous byte counter, needed to turn the\n * cumulative `bytesReceived`/`bytesSent` into a bitrate averaged over the\n * interval since the previous batch. A stream's first batch carries no\n * `bitrate_bps` — there is nothing to diff against yet.\n *\n * Each `inbound-rtp` (a `recvonly` track) and `outbound-rtp` (a `sendonly`\n * track) resolves to its track through its `mid`; a stream on a `mid` that\n * hasn't negotiated onto a named track, or whose codec isn't known yet, is\n * skipped. A sent stream's loss, jitter and round-trip time are what the\n * remote end reported back for it (its `remote-inbound-rtp`), the only\n * vantage point onto them. A received stream carries no round-trip time: a\n * receiver has no per-stream one, so the connection's own ICE round-trip time\n * goes on the connection stat instead (`connection_rtt_ms`). With several\n * streams on one `mid` (simulcast layers), the first one reported stands for\n * the track.\n *\n * Reports raw cumulative counters (`packets_lost`/`packets_received`, not a\n * pre-computed loss ratio) so the runtime's downstream aggregation across\n * sessions stays a sum of sums — a pre-averaged ratio can't be re-aggregated\n * correctly. A reading the browser hasn't produced is left out of `metrics`\n * rather than reported as `0`, so it can't pass for a real zero.\n */\nexport function createTrackStatsExtractor(): TrackStatsExtractor {\n const lastBytes = new Map<string, ByteSample>();\n\n return (report, tracks, pausedTracks) => {\n const reportWithLookup = report as RTCStatsReportWithLookup;\n const stats: ClientTrackStat[] = [];\n // Keyed by direction too: a sendrecv transceiver shares one mid between\n // its sent and received stream.\n const seenStreams = new Set<string>();\n const remoteInbound = new Map<string, RTCStatsReportEntry>();\n\n report.forEach((stat: RTCStatsReportEntry) => {\n if (stat.type === 'remote-inbound-rtp' && stat.localId !== undefined) {\n remoteInbound.set(stat.localId, stat);\n }\n });\n\n report.forEach((stat: RTCStatsReportEntry) => {\n const inbound = stat.type === 'inbound-rtp';\n\n if ((!inbound && stat.type !== 'outbound-rtp') || stat.mid === undefined) {\n return;\n }\n const direction: TrackDirection = inbound ? 'recvonly' : 'sendonly';\n const streamKey = `${direction}:${stat.mid}`;\n\n if (seenStreams.has(streamKey)) {\n return;\n }\n const track = tracks.find((entry) => entry.mid === stat.mid && entry.direction === direction);\n const codecStat = stat.codecId !== undefined ? reportWithLookup.get(stat.codecId) : undefined;\n // \"video/VP9\" -> \"vp9\".\n const codec = codecStat?.mimeType?.split('/')[1]?.toLowerCase();\n\n if (track === undefined || codec === undefined || !WIRE_CODECS[track.kind].has(codec)) {\n return;\n }\n seenStreams.add(streamKey);\n\n const metrics: Record<string, number> = {};\n const put = (key: string, value: number | undefined) => {\n if (value !== undefined) {\n metrics[key] = value;\n }\n };\n const bytes = inbound ? stat.bytesReceived : stat.bytesSent;\n\n if (bytes !== undefined) {\n const previous = lastBytes.get(stat.id);\n\n if (previous !== undefined && stat.timestamp > previous.timestamp && bytes >= previous.bytes) {\n put('bitrate_bps', Math.round(((bytes - previous.bytes) * 8 * 1000) / (stat.timestamp - previous.timestamp)));\n }\n lastBytes.set(stat.id, { bytes, timestamp: stat.timestamp });\n }\n const keyframeRequests =\n stat.firCount !== undefined || stat.pliCount !== undefined\n ? (stat.firCount ?? 0) + (stat.pliCount ?? 0)\n : undefined;\n\n if (inbound) {\n put('packets_received', stat.packetsReceived);\n put('packets_lost', stat.packetsLost);\n put('jitter_ms', stat.jitter !== undefined ? secondsToMs(stat.jitter) : undefined);\n put('nack_count', stat.nackCount);\n if (track.kind === 'video') {\n put('frames_per_second', stat.framesPerSecond);\n put('frames_decoded', stat.framesDecoded);\n put('frames_dropped', stat.framesDropped);\n put('frame_width', stat.frameWidth);\n put('frame_height', stat.frameHeight);\n put('keyframe_requests', keyframeRequests);\n } else {\n put('concealed_samples', stat.concealedSamples);\n put('total_samples_received', stat.totalSamplesReceived);\n }\n } else {\n const remote = remoteInbound.get(stat.id);\n\n put('packets_sent', stat.packetsSent);\n put('retransmitted_packets_sent', stat.retransmittedPacketsSent);\n put('nack_count', stat.nackCount);\n put('packets_lost', remote?.packetsLost);\n put('jitter_ms', remote?.jitter !== undefined ? secondsToMs(remote.jitter) : undefined);\n put('round_trip_time_ms', remote?.roundTripTime !== undefined ? secondsToMs(remote.roundTripTime) : undefined);\n if (track.kind === 'video') {\n put('frames_per_second', stat.framesPerSecond);\n put('frames_encoded', stat.framesEncoded);\n put('frame_width', stat.frameWidth);\n put('frame_height', stat.frameHeight);\n put('keyframe_requests', keyframeRequests);\n }\n }\n\n stats.push({\n timestamp: Date.now(),\n trackName: track.name,\n kind: track.kind,\n direction,\n codec,\n paused: pausedTracks.includes(track.name),\n metrics,\n });\n });\n\n return stats;\n };\n}\n\n/**\n * The connection-wide part of the runtime report, read straight off one stats\n * report — the facts that belong to the connection, not to any one track.\n * Every value is a point-in-time reading of the active candidate-pair (see\n * `activeCandidatePair()`), so nothing here depends on a previous report.\n *\n * - `available_outgoing_bitrate_bps`: the congestion controller's current\n * send-side estimate.\n * - `available_incoming_bitrate_bps`: the receive-side estimate, which a\n * browser only has when it estimates as the receiver.\n * - `connection_rtt_ms`: the ICE round-trip time, one value for the whole\n * connection.\n * - `time_to_connect_ms`: *timeToConnectMs*, a one-time fact the caller passes\n * only on the first report after connecting.\n *\n * Like a track's metrics, a reading the browser hasn't produced is left out\n * rather than reported as `0`, so it can't pass for a collapsed estimate.\n */\nexport function toClientConnectionStat(report: RTCStatsReport, timeToConnectMs?: number): ClientConnectionStat {\n const pair = activeCandidatePair(report);\n const metrics: Record<string, number> = {};\n\n if (pair?.availableOutgoingBitrate !== undefined) {\n metrics.available_outgoing_bitrate_bps = pair.availableOutgoingBitrate;\n }\n if (pair?.availableIncomingBitrate !== undefined) {\n metrics.available_incoming_bitrate_bps = pair.availableIncomingBitrate;\n }\n if (pair?.currentRoundTripTime !== undefined) {\n metrics.connection_rtt_ms = secondsToMs(pair.currentRoundTripTime);\n }\n if (timeToConnectMs !== undefined) {\n metrics.time_to_connect_ms = roundMs(timeToConnectMs);\n }\n return { timestamp: Date.now(), metrics };\n}\n\ntype ConnectionStatsExtractor = (report: RTCStatsReport) => ConnectionStats;\n\n/**\n * `lib.dom`'s own `RTCStats` only has `id`/`timestamp`/`type` — the fields\n * below are the real, spec-defined ones this extractor reads off whichever\n * concrete stat type each belongs to (`RTCIceCandidatePairStats`,\n * `RTCIceCandidateStats`, `RTCInboundRtpStreamStats`, `RTCOutboundRtpStreamStats`,\n * `RTCRemoteInboundRtpStreamStats`). `forEach()`'s callback\n * is typed `any` in `lib.dom`, so annotating it with this instead is what\n * gets every access below out from under `no-unsafe-member-access`.\n *\n * Also fills in `get()` — Map-like lookup by id (e.g. a candidate-pair's\n * `localCandidateId`) is how the spec's `RTCStatsReport` actually behaves,\n * but `lib.dom` doesn't declare it either.\n */\ninterface RTCStatsReportEntry extends RTCStats {\n state?: string;\n nominated?: boolean;\n selectedCandidatePairId?: string;\n selected?: boolean;\n currentRoundTripTime?: number;\n availableOutgoingBitrate?: number;\n availableIncomingBitrate?: number;\n localCandidateId?: string;\n bytesReceived?: number;\n bytesSent?: number;\n candidateType?: string;\n kind?: string;\n framesPerSecond?: number;\n jitter?: number;\n packetsReceived?: number;\n packetsLost?: number;\n mid?: string;\n framesDecoded?: number;\n framesDropped?: number;\n frameWidth?: number;\n frameHeight?: number;\n nackCount?: number;\n firCount?: number;\n pliCount?: number;\n codecId?: string;\n mimeType?: string;\n localId?: string;\n roundTripTime?: number;\n packetsSent?: number;\n retransmittedPacketsSent?: number;\n framesEncoded?: number;\n concealedSamples?: number;\n totalSamplesReceived?: number;\n}\n\ninterface RTCStatsReportWithLookup extends RTCStatsReport {\n get(id: string): RTCStatsReportEntry | undefined;\n}\n\n/**\n * The candidate-pair carrying the connection's media. Several pairs can be\n * `succeeded` and `nominated` at once (one per local interface), and only the\n * one the transport actually uses has a live round-trip time, a bandwidth\n * estimate and moving byte counters. In order of preference:\n *\n * 1. the pair the `transport` stat names (Chrome, Safari),\n * 2. the pair flagged `selected` (Firefox, which has no `transport` stat),\n * 3. the first `succeeded` and `nominated` pair, for a browser that marks\n * neither.\n *\n * Every choice must have `succeeded`: a pair that hasn't carries no media.\n */\nfunction activeCandidatePair(report: RTCStatsReport): RTCStatsReportEntry | undefined {\n let namedByTransport: string | undefined;\n let flaggedSelected: RTCStatsReportEntry | undefined;\n let firstNominated: RTCStatsReportEntry | undefined;\n\n report.forEach((stat: RTCStatsReportEntry) => {\n if (stat.type === 'transport' && stat.selectedCandidatePairId) {\n namedByTransport ??= stat.selectedCandidatePairId;\n }\n if (stat.type === 'candidate-pair' && stat.state === 'succeeded') {\n if (stat.selected) {\n flaggedSelected ??= stat;\n }\n if (stat.nominated) {\n firstNominated ??= stat;\n }\n }\n });\n\n const named =\n namedByTransport !== undefined ? (report as RTCStatsReportWithLookup).get(namedByTransport) : undefined;\n const namedSucceeded = named?.state === 'succeeded' ? named : undefined;\n\n return namedSucceeded ?? flaggedSelected ?? firstNominated;\n}\n\n/**\n * A summary of the whole connection: the `ConnectionStats` behind\n * `getStats()` and `statsUpdate`. Connection-wide values come from the active\n * candidate-pair (see `activeCandidatePair()`); frame rate, jitter and loss\n * from the first received video stream.\n *\n * A closure over the previous reading's candidate-pair byte counters, needed\n * to turn them into a bitrate — so each poller keeps its own instance.\n */\nexport function createConnectionStatsExtractor(): ConnectionStatsExtractor {\n let lastBytesReceived: number | undefined;\n let lastBytesSent: number | undefined;\n let lastCandPairTimestamp: number | undefined;\n // An ICE restart or failover nominates a different candidate-pair, whose\n // byte counters start from their own, unrelated baseline — diffing against\n // the previous pair's counters would produce a bogus (often negative)\n // bitrate for that one sample.\n let lastCandPairId: string | undefined;\n\n return (report: RTCStatsReport) => {\n let rtt: number | undefined;\n let availableOutgoingBitrate: number | undefined;\n let availableIncomingBitrate: number | undefined;\n let incomingBitrate: number | undefined;\n let outgoingBitrate: number | undefined;\n let videoInboundRtpId: string | undefined;\n let framesPerSecond: number | undefined;\n let jitter: number | undefined;\n let packetLossRatio: number | undefined;\n let candidateType: string | undefined;\n\n const pair = activeCandidatePair(report);\n\n if (pair !== undefined) {\n if (pair.currentRoundTripTime !== undefined) {\n rtt = pair.currentRoundTripTime * 1000;\n }\n availableOutgoingBitrate = pair.availableOutgoingBitrate;\n availableIncomingBitrate = pair.availableIncomingBitrate;\n\n const localCandidate =\n pair.localCandidateId !== undefined\n ? (report as RTCStatsReportWithLookup).get(pair.localCandidateId)\n : undefined;\n\n if (localCandidate?.candidateType) {\n candidateType = localCandidate.candidateType;\n }\n const samePair = lastCandPairId === pair.id;\n const timeDiff: number =\n samePair && lastCandPairTimestamp !== undefined ? pair.timestamp - lastCandPairTimestamp : 0;\n\n if (pair.bytesReceived !== undefined) {\n if (samePair && lastBytesReceived !== undefined && timeDiff > 0) {\n incomingBitrate = (((pair.bytesReceived - lastBytesReceived) * 8) / timeDiff) * 1000; /* Bits/Second */\n }\n lastBytesReceived = pair.bytesReceived;\n }\n if (pair.bytesSent !== undefined) {\n if (samePair && lastBytesSent !== undefined && timeDiff > 0) {\n outgoingBitrate = (((pair.bytesSent - lastBytesSent) * 8) / timeDiff) * 1000; /* Bits/Second */\n }\n lastBytesSent = pair.bytesSent;\n }\n lastCandPairTimestamp = pair.timestamp;\n lastCandPairId = pair.id;\n }\n\n report.forEach((stat: RTCStatsReportEntry) => {\n // If there is more than one video stream the stats will be from the first one encountered.\n if (videoInboundRtpId === undefined && stat.type === 'inbound-rtp' && stat.kind === 'video') {\n videoInboundRtpId = stat.id;\n if (stat.framesPerSecond !== undefined) {\n framesPerSecond = stat.framesPerSecond;\n }\n if (stat.jitter !== undefined) {\n jitter = stat.jitter;\n }\n if (\n stat.packetsReceived !== undefined &&\n stat.packetsLost !== undefined &&\n stat.packetsReceived + stat.packetsLost > 0\n ) {\n packetLossRatio = stat.packetsLost / (stat.packetsReceived + stat.packetsLost);\n }\n }\n });\n\n return {\n rtt,\n candidateType,\n availableIncomingBitrate,\n availableOutgoingBitrate,\n incomingBitrate,\n outgoingBitrate,\n framesPerSecond,\n packetLossRatio,\n jitter,\n timestamp: Date.now(),\n };\n };\n}\n","/**\n * Lazy, idempotent access to the `reactor-wasm` module.\n *\n * Nothing imports `reactor_wasm.js` at module scope: pulling in wasm on\n * import would make constructing a `Reactor` that never connects pay for a\n * network fetch and a WebAssembly compile it never needed. The module is\n * fetched and instantiated on first use and cached module-wide, so every\n * `Reactor` in a page shares one `init()` — a second `new Reactor(...)`, or a\n * reconnect, never re-runs it.\n */\nimport type { ReactorWasmModule } from './reactor-wasm.types';\n\nlet modulePromise: Promise<ReactorWasmModule> | null = null;\n\n/**\n * `wasm-pack --target web` emits a plain ES module that instantiates the\n * binding — this loader only needs to reach that module and call its default\n * export once. tsup bundles this whole package into one flat\n * `dist/index.{js,cjs}`, so at runtime this file lives at the *root* of\n * `dist/`, not under `dist/internal/` — the path is relative to that, to line\n * up with where `scripts/copy-wasm.mjs` copies `crates/reactor-wasm/pkg`\n * (`dist/wasm/`).\n *\n * That module carries the `.wasm` binary inlined (see copy-wasm.mjs), so a\n * consumer's bundler only has to follow this one relative `import()` — which\n * every bundler does, and turns into a separate chunk fetched on first use.\n * Nothing else has to stay reachable at a fixed location next to it.\n *\n * The specifier is inlined directly in the `import()` call below, not\n * hoisted to a `const`, and not marked `@vite-ignore` — bundlers only resolve\n * a literal argument statically. Routed through an intermediate binding,\n * webpack can't trace it back to a literal and throws \"Critical dependency:\n * the request of a dependency is an expression\" at runtime; marked ignored,\n * Vite leaves it as a bare relative path that breaks as soon as Vite moves\n * this file (its dependency optimizer, or a production build).\n */\n\nexport function loadReactorWasm(): Promise<ReactorWasmModule> {\n if (!modulePromise) {\n modulePromise = importWasmModule().catch((cause) => {\n // Don't cache a failed load — a transient fetch failure shouldn't\n // permanently poison every later `Reactor` in the page.\n modulePromise = null;\n throw new Error(`reactor-wasm failed to load: ${describeCause(cause)}`, { cause });\n });\n }\n return modulePromise;\n}\n\nasync function importWasmModule(): Promise<ReactorWasmModule> {\n // @ts-expect-error — no declaration file to resolve at typecheck time; the\n // module only exists after scripts/copy-wasm.mjs copies it into dist/wasm,\n // post-build. Cast to ReactorWasmModule below instead.\n const module = (await import('./wasm/reactor_wasm.js')) as ReactorWasmModule;\n\n await module.default();\n return module;\n}\n\n/** The underlying failure, named in the message itself rather than only in\n * `cause` — plenty of error reporting (and `String(error)`) never looks at\n * `cause`, and \"failed to load\" alone gives nothing to act on. */\nfunction describeCause(cause: unknown): string {\n if (cause instanceof Error) {\n return cause.message ? `${cause.name}: ${cause.message}` : cause.name;\n }\n return String(cause);\n}\n","{\n \"name\": \"@reactor-team/js-sdk\",\n \"version\": \"3.2.0\",\n \"description\": \"Connect your JavaScript/TypeScript app to a live Reactor model in the browser.\",\n \"license\": \"Apache-2.0\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/reactor-team/reactor-client-sdks.git\",\n \"directory\": \"sdks/js\"\n },\n \"type\": \"module\",\n \"sideEffects\": false,\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\",\n \"require\": \"./dist/index.cjs\"\n }\n },\n \"files\": [\n \"dist\"\n ],\n \"engines\": {\n \"node\": \">=18\"\n },\n \"scripts\": {\n \"build\": \"tsup && node scripts/copy-wasm.mjs\",\n \"prepack\": \"npm run build\",\n \"dev\": \"tsup --watch\",\n \"type-check\": \"tsc --noEmit\",\n \"lint\": \"eslint .\",\n \"test\": \"vitest run\",\n \"clean\": \"rm -rf dist\"\n },\n \"dependencies\": {\n \"awaitqueue\": \"^3.3.1\",\n \"hls.js\": \"^1.6.0\",\n \"mp4box\": \"^2.4.1\"\n },\n \"peerDependencies\": {\n \"react\": \"^18.0.0 || ^19.0.0\"\n },\n \"devDependencies\": {\n \"@eslint/js\": \"^9.39.5\",\n \"@stylistic/eslint-plugin\": \"^5.10.0\",\n \"@testing-library/react\": \"^16.0.0\",\n \"@types/react\": \"^19.0.0\",\n \"eslint\": \"^9.39.5\",\n \"eslint-plugin-react-hooks\": \"^5.0.0\",\n \"jsdom\": \"^25.0.0\",\n \"react\": \"^19.0.0\",\n \"react-dom\": \"^19.0.0\",\n \"tsup\": \"^8.3.0\",\n \"typescript\": \"^5.6.0\",\n \"typescript-eslint\": \"^8.67.0\",\n \"vitest\": \"^4.1.11\"\n }\n}\n","import type { JwtRequestContext, JwtSource } from '../types';\n\n/** Resolves a `JwtSource` (a plain string, or a resolver called at request\n * time with `context`) to a plain string — shared by the clip surfaces,\n * which fall back to a `ReactorProvider`'s own `JwtSource` when no explicit\n * resolver is passed. */\nexport async function resolveJwtSource(source: JwtSource, context?: JwtRequestContext): Promise<string> {\n return typeof source === 'function' ? source(context) : source;\n}\n","/**\n * Browser-side primitives for turning a `Clip` (from `requestClip()` /\n * `requestRecording()`) into playable or downloadable media.\n *\n * `Clip.playlistUrl` names an HLS media playlist — `#EXT-X-VERSION:7`\n * fragmented MP4, an `#EXT-X-MAP` init segment followed by `.m4s` media\n * fragments — that the caller fetches and assembles; Reactor itself doesn't\n * host clips. This module owns fetching and parsing that playlist\n * (`fetchPlaylist` / `parsePlaylist`), wrapping it for a `<video>` element or\n * `hls.js` (`createPlayableManifestUrl`), and assembling the referenced\n * chunks into a flat, downloadable MP4 (`downloadClipAsFile`).\n */\n\nimport type * as MP4BoxTypes from 'mp4box';\nimport { resolveJwtSource } from './internal/jwt-resolver';\nimport type { Clip, JwtRequestContext, JwtSource } from './types';\n\n/**\n * Error thrown when a clip's playlist or chunks can't be fetched, parsed, or\n * assembled into a file. Scoped to this module — a failure in\n * `requestClip()` / `requestRecording()` themselves surfaces as a\n * `ReactorError`, since those go through `reactor-core`'s own error channel.\n *\n * `code` is a stable, machine-readable identifier; `reason` is the raw\n * string behind it (an HTTP status, a parse complaint, …).\n */\nexport class RecordingError extends Error {\n constructor(\n public readonly code:\n | 'CLIP_GONE'\n | 'CLIP_NOT_READY'\n | 'PLAYLIST_FETCH_FAILED'\n | 'CHUNK_FETCH_FAILED'\n | 'INVALID_PLAYLIST'\n | 'DOWNLOAD_UNSUPPORTED',\n public readonly reason: string,\n ) {\n super(`${code}: ${reason}`);\n this.name = 'RecordingError';\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// HLS playlist fetching + parsing\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Segments referenced by an HLS manifest, in playback order. */\ninterface ParsedPlaylist {\n initUrl: string;\n segmentUrls: string[];\n}\n\n/**\n * Suggested grace period for callers that opt into a bounded wait by passing\n * it as `FetchPlaylistOptions.slackMs`. Not a default — `fetchPlaylist()`\n * polls indefinitely unless a bound is supplied.\n */\nexport const DEFAULT_PLAYLIST_POLL_SLACK_MS = 15_000;\n\nexport interface FetchPlaylistOptions {\n /**\n * Unix epoch (ms) when the runtime predicts the boundary chunk will be\n * servable — pass `clip.predictedReadyAtMs`. On its own this doesn't stop\n * polling; it only anchors the optional `slackMs` deadline.\n */\n predictedReadyAtMs?: number;\n /**\n * Opt-in grace period that turns polling into a bounded wait: a stuck\n * `202` produces `CLIP_NOT_READY` once `max(predictedReadyAtMs, pollStart)\n * + slackMs` passes. Omit (the default) to poll indefinitely until the\n * manifest is ready or the caller aborts via `signal`.\n */\n slackMs?: number;\n /** Hard cap on the per-poll wait. `Retry-After` is honored but clamped. Default 2000 ms. */\n maxRetryDelayMs?: number;\n /** Floor on the per-poll wait so a cheap network doesn't hot-loop. Default 200 ms. */\n minRetryDelayMs?: number;\n /**\n * Opt-in cap on the number of `202` responses tolerated before\n * `CLIP_NOT_READY`. Omit (the default) to poll indefinitely.\n */\n maxRetries?: number;\n /**\n * Aborts in-flight fetches and the inter-poll sleep — the primary way to\n * end an unbounded wait (a timeout, a user cancel, a component unmount).\n */\n signal?: AbortSignal;\n /**\n * Coordinator JWT for the manifest GET: a string, or a resolver called\n * before every poll with `{ sessionId }`, so a long 202 wait can cross a\n * token refresh. Omit in local mode (HttpRuntime).\n */\n jwt?: JwtSource;\n /** The clip's session, handed to a resolver `jwt`. `downloadClipAsFile()`\n * fills it from `clip.sessionId`. */\n sessionId?: string;\n}\n\n/**\n * Fetch `playlistUrl`, polling on `202 Accepted` — returned while the\n * boundary chunk is still uploading.\n *\n * - `200` → the manifest body.\n * - `410` / `404` → `CLIP_GONE`.\n * - other → `PLAYLIST_FETCH_FAILED` (no retry).\n * - `202` past an opt-in `slackMs` deadline or `maxRetries` cap → `CLIP_NOT_READY`.\n * - aborted `signal` → rejects with the fetch/sleep `AbortError`.\n */\nexport async function fetchPlaylist(\n playlistUrl: string,\n options: FetchPlaylistOptions = {},\n): Promise<string> {\n const minDelay = Math.max(0, options.minRetryDelayMs ?? 200);\n const maxDelay = Math.max(minDelay, options.maxRetryDelayMs ?? 2_000);\n\n const hasDeadline = typeof options.slackMs === 'number' && Number.isFinite(options.slackMs);\n // Anchored at max(predictedReadyAtMs, now) so a late start still gets the\n // full grace window rather than a deadline already in the past.\n const startedPollingAt = Date.now();\n const deadlineMs = hasDeadline\n ? Math.max(options.predictedReadyAtMs ?? startedPollingAt, startedPollingAt) +\n (options.slackMs as number)\n : undefined;\n const maxRetries = typeof options.maxRetries === 'number' ? options.maxRetries : undefined;\n\n let attempt = 0;\n\n while (true) {\n const init: RequestInit = {};\n\n if (options.signal) {\n init.signal = options.signal;\n }\n // Resolved per poll, not once: a 202 wait can outlive the token it\n // started with, and the resolver is where a fresh one comes from.\n const jwt = await resolveManifestJwt(options);\n\n if (jwt) {\n init.headers = { Authorization: `Bearer ${jwt}` };\n }\n\n let response: Response;\n\n try {\n response = await fetch(playlistUrl, init);\n } catch (error) {\n if (isAbortError(error)) {\n throw error;\n }\n throw new RecordingError(\n 'PLAYLIST_FETCH_FAILED',\n `Network error fetching playlist: ${(error as Error).message}`,\n );\n }\n\n // 202 is in the 2xx range, so it has to be checked before response.ok.\n if (response.status === 202) {\n if (deadlineMs !== undefined && Date.now() >= deadlineMs) {\n throw new RecordingError(\n 'CLIP_NOT_READY',\n `Boundary chunk still pending after ${options.slackMs}ms grace (predicted ready ${new Date(\n options.predictedReadyAtMs ?? startedPollingAt,\n ).toISOString()}). Runtime may have crashed mid-clip.`,\n );\n }\n if (maxRetries !== undefined && attempt >= maxRetries) {\n throw new RecordingError(\n 'CLIP_NOT_READY',\n `Manifest still pending after ${attempt + 1} attempts (last status 202)`,\n );\n }\n\n const headerDelay = parseRetryAfter(response.headers.get('Retry-After'), minDelay);\n const delay = Math.min(maxDelay, Math.max(minDelay, headerDelay));\n const clampedDelay =\n deadlineMs !== undefined ? Math.min(delay, Math.max(0, deadlineMs - Date.now())) : delay;\n\n await sleep(clampedDelay, options.signal);\n attempt++;\n continue;\n }\n\n if (response.status === 200) {\n return await response.text();\n }\n if (response.status === 410 || response.status === 404) {\n throw new RecordingError('CLIP_GONE', 'Clip is no longer available or session unknown');\n }\n throw new RecordingError('PLAYLIST_FETCH_FAILED', `Manifest endpoint returned HTTP ${response.status}`);\n }\n}\n\n/**\n * Parse an HLS `.m3u8` body into the init segment URL plus the ordered media\n * segment URLs, resolving relative URLs against `playlistUrl` itself.\n */\nexport function parsePlaylist(manifestBody: string, playlistUrl: string): ParsedPlaylist {\n let initUrl: string | undefined;\n const segments: string[] = [];\n\n for (const rawLine of manifestBody.split(/\\r?\\n/)) {\n const trimmed = rawLine.trim();\n\n if (!trimmed) {\n continue;\n }\n\n if (trimmed.startsWith('#EXT-X-MAP')) {\n const match = trimmed.match(/URI=\"([^\"]+)\"/);\n\n if (match?.[1]) {\n initUrl = resolveAgainst(match[1], playlistUrl);\n }\n continue;\n }\n if (trimmed.startsWith('#')) {\n continue;\n }\n segments.push(resolveAgainst(trimmed, playlistUrl));\n }\n\n if (!initUrl) {\n throw new RecordingError('INVALID_PLAYLIST', 'Playlist is missing an #EXT-X-MAP init segment URI');\n }\n if (segments.length === 0) {\n throw new RecordingError('INVALID_PLAYLIST', 'Playlist contains no media segments');\n }\n\n return { initUrl, segmentUrls: segments };\n}\n\n/**\n * Wrap an HLS manifest body in a `blob:` URL suitable for `<video src>` or\n * `hls.js`. Bypasses \"the player can't set an Authorization header\": the\n * manifest is served from memory, and its chunk URLs are already-signed S3\n * GETs. Path-only chunk URLs in the body are absolutized against\n * `playlistUrl` first — without that, the browser would resolve them against\n * the `blob:` URL's own origin instead of the runtime's.\n *\n * Caller owns the returned URL — revoke it via `URL.revokeObjectURL` when\n * playback tears down. Browser-only; throws `INVALID_PLAYLIST` outside a DOM\n * environment.\n */\nexport function createPlayableManifestUrl(manifestBody: string, playlistUrl: string): string {\n if (\n typeof Blob === 'undefined' ||\n typeof URL === 'undefined' ||\n typeof URL.createObjectURL !== 'function'\n ) {\n throw new RecordingError(\n 'INVALID_PLAYLIST',\n 'createPlayableManifestUrl requires a browser environment with URL.createObjectURL',\n );\n }\n const rewritten = absolutizeManifestUrls(manifestBody, playlistUrl);\n const blob = new Blob([rewritten], { type: 'application/vnd.apple.mpegurl' });\n\n return URL.createObjectURL(blob);\n}\n\nfunction absolutizeManifestUrls(manifestBody: string, playlistUrl: string): string {\n const eol = manifestBody.includes('\\r\\n') ? '\\r\\n' : '\\n';\n const out: string[] = [];\n\n for (const line of manifestBody.split(/\\r?\\n/)) {\n if (line.startsWith('#EXT-X-MAP')) {\n out.push(\n line.replace(/URI=\"([^\"]+)\"/, (_: string, uri: string) => `URI=\"${resolveAgainst(uri, playlistUrl)}\"`),\n );\n continue;\n }\n const trimmed = line.trim();\n\n if (!trimmed || trimmed.startsWith('#')) {\n out.push(line);\n continue;\n }\n out.push(resolveAgainst(trimmed, playlistUrl));\n }\n return out.join(eol);\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// downloadClipAsFile\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface DownloadClipOptions {\n /** Coordinator JWT for the manifest GET: a string, or a resolver called\n * per poll with `{ sessionId: clip.sessionId }`. The chunks the manifest\n * references are S3 presigned URLs, fetched unauthenticated. */\n jwt?: JwtSource;\n /** Cancels both the playlist poll and any in-flight chunk fetches. */\n signal?: AbortSignal;\n /** Called after each chunk completes — useful for progress UI. */\n onProgress?: (info: { fetched: number; total: number; bytes: number }) => void;\n}\n\n/**\n * Fetch the chunks `clip.playlistUrl` references, remux them into a flat\n * MP4, and (when `filename` is non-null) trigger a browser `<a download>`.\n * Pass `filename: null` to skip the download trigger and just get the Blob.\n *\n * See {@link assembleClipBlob} for the remux and memory-bound caveats.\n */\nexport async function downloadClipAsFile(\n clip: Clip,\n filename: string | null = 'reactor-clip.mp4',\n options: DownloadClipOptions = {},\n): Promise<Blob> {\n const playlistOptions: FetchPlaylistOptions = {\n predictedReadyAtMs: clip.predictedReadyAtMs,\n sessionId: clip.sessionId,\n };\n\n if (options.signal) {\n playlistOptions.signal = options.signal;\n }\n if (options.jwt) {\n playlistOptions.jwt = options.jwt;\n }\n\n const manifestBody = await fetchPlaylist(clip.playlistUrl, playlistOptions);\n const blob = await assembleClipBlob(manifestBody, clip.playlistUrl, options);\n\n if (filename === null) {\n return blob;\n }\n if (typeof document === 'undefined' || typeof URL.createObjectURL !== 'function') {\n throw new RecordingError(\n 'DOWNLOAD_UNSUPPORTED',\n 'downloadClipAsFile requires a DOM environment; pass filename=null to skip the download trigger',\n );\n }\n triggerBrowserDownload(blob, filename);\n return blob;\n}\n\nexport interface AssembleClipOptions {\n /** Cancels any in-flight chunk fetches. */\n signal?: AbortSignal;\n /** Called after each chunk completes — useful for progress UI. */\n onProgress?: (info: { fetched: number; total: number; bytes: number }) => void;\n}\n\n/**\n * Fetch the chunks an already-fetched `manifestBody` references and remux\n * them into a flat MP4 Blob. Split out of {@link downloadClipAsFile} so\n * `ClipPlayer`'s MP4 fallback path can reuse it against the manifest it\n * already has, instead of fetching the playlist a second time.\n *\n * The remux rewrites the container only — H.264 NAL units and AAC packets\n * pass through unchanged — so `start_time=0`, faststart, and\n * `major_brand=isom` come for free with no re-encode. See `maybeRemux()` for\n * the fallback on the rare parse failure.\n *\n * Memory-bound: every chunk is held in `parts` for the full duration of the\n * fetch loop, and `maybeRemux()`'s underlying `mp4box` parser needs the whole\n * input up front, so there's no streaming path to disk. Fine for a bounded\n * clip; a full-session `requestRecording()` download can hold the entire\n * recording in memory at once.\n */\nexport async function assembleClipBlob(\n manifestBody: string,\n playlistUrl: string,\n options: AssembleClipOptions = {},\n): Promise<Blob> {\n const { initUrl, segmentUrls } = parsePlaylist(manifestBody, playlistUrl);\n const orderedUrls = [initUrl, ...segmentUrls];\n const chunkInit: RequestInit = {};\n\n if (options.signal) {\n chunkInit.signal = options.signal;\n }\n\n const parts: Uint8Array[] = [];\n let bytes = 0;\n\n for (const [i, url] of orderedUrls.entries()) {\n let response: Response;\n\n try {\n response = await fetch(url, chunkInit);\n } catch (error) {\n if (isAbortError(error)) {\n throw error;\n }\n throw new RecordingError('CHUNK_FETCH_FAILED', `Network error fetching chunk ${i}: ${(error as Error).message}`);\n }\n if (!response.ok) {\n throw new RecordingError('CHUNK_FETCH_FAILED', `Chunk ${i} returned HTTP ${response.status}`);\n }\n const data = new Uint8Array(await response.arrayBuffer());\n\n parts.push(data);\n bytes += data.byteLength;\n options.onProgress?.({ fetched: i + 1, total: orderedUrls.length, bytes });\n }\n\n const finalBytes = await maybeRemux(parts);\n\n return new Blob([finalBytes as BlobPart], { type: 'video/mp4' });\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Fragmented MP4 → flat MP4 remux\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Concatenate `parts` and pipe the result through `remuxFragmentedToFlat()`.\n * Remux failures (`mp4box` blocked by an exotic bundler/CSP, corrupt input,\n * an unsupported codec) are funneled through one path: a `console.warn` and\n * the unmodified concatenation, so the download still succeeds end-to-end\n * with the (worse, but still playable) fragmented MP4 the runtime emitted.\n */\nasync function maybeRemux(parts: Uint8Array[]): Promise<Uint8Array> {\n const input = concatUint8Arrays(parts);\n\n try {\n const MP4Box = await loadMp4Box();\n\n return await remuxFragmentedToFlat(input, MP4Box);\n } catch (error) {\n console.warn('[Reactor] Clip remux failed, returning fragmented MP4 instead.', error);\n return input;\n }\n}\n\n/** Indirection so tests can stub the dynamic `mp4box` import without pulling\n * the real bytes through every test that calls `downloadClipAsFile`.\n * @internal */\nexport const __remuxInternals = {\n loadMp4Box: (): Promise<typeof MP4BoxTypes> => import('mp4box'),\n};\n\nfunction loadMp4Box(): Promise<typeof MP4BoxTypes> {\n return __remuxInternals.loadMp4Box();\n}\n\n/**\n * The actual fMP4 → flat MP4 conversion. No re-encode: every NAL unit and AAC\n * packet passes through unchanged. Only the container framing (boxes) and\n * decode timestamps are rewritten.\n *\n * The output file is initialized with `[\"isom\", \"mp42\", \"avc1\", \"iso2\"]` as\n * compatible brands so the major brand is `isom` (not `iso5`, what\n * byte-concatenated fragments default to) and the sample tables are written\n * ahead of `mdat` — i.e. the file is implicitly faststart. Decode times are\n * shifted by one shared presentation-time origin across every track — the\n * earliest first-sample time, converted through each track's own timescale\n * — so the output starts at (close to) `0.000000` while the original\n * inter-track offset (e.g. audio starting slightly before or after video)\n * is preserved rather than each track independently zeroing to its own\n * first sample.\n */\nasync function remuxFragmentedToFlat(\n input: Uint8Array,\n MP4Box: typeof MP4BoxTypes,\n): Promise<Uint8Array> {\n return new Promise<Uint8Array>((resolve, reject) => {\n const inFile = MP4Box.createFile();\n const outFile = MP4Box.createFile();\n\n outFile.init({ brands: ['isom', 'mp42', 'avc1', 'iso2'] });\n\n interface PendingTrack {\n trackOptions: MP4BoxTypes.IsoFileOptions;\n timescale: number;\n firstDts: number;\n samples: MP4BoxTypes.Sample[];\n }\n\n const pendingTracks = new Map<number, PendingTrack>();\n let settled = false;\n\n const fail = (err: Error) => {\n if (settled) {\n return;\n }\n settled = true;\n reject(err);\n };\n\n inFile.onError = (_module: string, message: string) => {\n fail(new Error(message));\n };\n\n inFile.onReady = (info) => {\n if (!info.tracks.length) {\n fail(new Error('no tracks in input'));\n return;\n }\n for (const track of info.tracks) {\n // setExtractionOptions delivers samples in batches via onSamples;\n // nbSamples controls batch size only, not the total.\n inFile.setExtractionOptions(track.id, null, { nbSamples: 1000 });\n }\n inFile.start();\n };\n\n // Samples are buffered per track (not written to outFile yet) because\n // the shared origin below needs every track's first sample DTS, and\n // tracks arrive interleaved as fragments are parsed.\n inFile.onSamples = (id, _user, samples) => {\n if (settled || samples.length === 0) {\n return;\n }\n\n let pending = pendingTracks.get(id);\n\n if (!pending) {\n // The sample carries the parsed input SampleEntry (avc1 / mp4a / …)\n // whose child boxes are the actual codec config (avcC, esds, …).\n // addTrack creates a fresh empty SampleEntry of the requested type,\n // so the input's child boxes are passed via description_boxes: they\n // become direct children of the new SampleEntry, where decoders\n // expect them. Passing the whole input SampleEntry as `description`\n // instead would nest it (stsd > avc1 > avc1 > avcC) and decoders\n // would fail to find avcC and render black.\n const firstSample = samples[0];\n\n if (!firstSample) {\n return;\n }\n\n const sampleEntry = firstSample.description as MP4BoxTypes.SampleEntry;\n const inputTrack = trackInfoById(inFile, id);\n const trackOptions: MP4BoxTypes.IsoFileOptions = {\n type: sampleEntry.type as MP4BoxTypes.SampleEntryFourCC,\n timescale: firstSample.timescale,\n // `boxes` is typed as `Box[]` but `description_boxes` wants the\n // narrower `BoxKind[]` union — at runtime they're the same\n // concrete instances, just typed loosely.\n description_boxes: sampleEntry.boxes as unknown as MP4BoxTypes.BoxKind[],\n };\n\n if (inputTrack?.track_width !== undefined) {\n trackOptions.width = inputTrack.track_width;\n }\n if (inputTrack?.track_height !== undefined) {\n trackOptions.height = inputTrack.track_height;\n }\n if (inputTrack?.language !== undefined) {\n trackOptions.language = inputTrack.language;\n }\n if (inputTrack?.video) {\n trackOptions.hdlr = 'vide';\n } else if (inputTrack?.audio) {\n trackOptions.hdlr = 'soun';\n }\n\n pending = { trackOptions, timescale: firstSample.timescale, firstDts: firstSample.dts, samples: [] };\n pendingTracks.set(id, pending);\n }\n\n pending.samples.push(...samples);\n };\n\n let buf: MP4BoxTypes.MP4BoxBuffer;\n\n try {\n buf = MP4Box.MP4BoxBuffer.fromArrayBuffer(\n input.buffer.slice(input.byteOffset, input.byteOffset + input.byteLength),\n 0,\n );\n } catch (error) {\n fail(error as Error);\n return;\n }\n\n try {\n inFile.appendBuffer(buf);\n inFile.flush();\n } catch (error) {\n fail(error as Error);\n return;\n }\n\n if (settled) {\n return;\n }\n if (pendingTracks.size === 0) {\n fail(new Error('no samples extracted from input'));\n return;\n }\n\n let originSeconds = Infinity;\n\n for (const pending of pendingTracks.values()) {\n originSeconds = Math.min(originSeconds, pending.firstDts / pending.timescale);\n }\n\n try {\n for (const pending of pendingTracks.values()) {\n const outId = outFile.addTrack(pending.trackOptions);\n const dtsShift = Math.round(originSeconds * pending.timescale);\n\n for (const sample of pending.samples) {\n if (!sample.data) {\n continue;\n }\n outFile.addSample(outId, sample.data, {\n duration: sample.duration,\n dts: sample.dts - dtsShift,\n cts: sample.cts - dtsShift,\n is_sync: sample.is_sync,\n });\n }\n }\n } catch (error) {\n fail(error as Error);\n return;\n }\n\n let output: Uint8Array;\n\n try {\n const stream = outFile.getBuffer();\n\n output = new Uint8Array(stream.buffer.slice(0, stream.byteLength));\n } catch (error) {\n fail(error as Error);\n return;\n }\n\n settled = true;\n resolve(output);\n });\n}\n\nfunction trackInfoById(file: MP4BoxTypes.ISOFile, id: number): MP4BoxTypes.Track | undefined {\n const info = file.getInfo();\n\n return info.tracks.find((t) => t.id === id);\n}\n\nfunction concatUint8Arrays(parts: Uint8Array[]): Uint8Array {\n const only = parts.length === 1 ? parts[0] : undefined;\n\n if (only) {\n return only;\n }\n\n let total = 0;\n\n for (const p of parts) {total += p.byteLength;}\n\n const out = new Uint8Array(total);\n let offset = 0;\n\n for (const p of parts) {\n out.set(p, offset);\n offset += p.byteLength;\n }\n return out;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Internal helpers\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction isAbortError(error: unknown): boolean {\n return error instanceof DOMException && error.name === 'AbortError';\n}\n\nfunction resolveAgainst(target: string, base: string): string {\n try {\n return new URL(target, base).toString();\n } catch {\n return target;\n }\n}\n\nfunction parseRetryAfter(header: string | null, fallbackMs: number): number {\n if (!header) {\n return fallbackMs;\n }\n\n const seconds = Number(header);\n\n if (Number.isFinite(seconds) && seconds >= 0) {\n return seconds * 1000;\n }\n const dateMs = Date.parse(header);\n\n if (!Number.isNaN(dateMs)) {\n return Math.max(0, dateMs - Date.now());\n }\n return fallbackMs;\n}\n\nasync function resolveManifestJwt(options: FetchPlaylistOptions): Promise<string | undefined> {\n if (options.jwt === undefined) {\n return undefined;\n }\n const context: JwtRequestContext = options.sessionId === undefined ? {} : { sessionId: options.sessionId };\n\n return abortable(resolveJwtSource(options.jwt, context), options.signal);\n}\n\n// Settles with `promise`, or rejects as soon as `signal` aborts. The resolver\n// itself keeps running; nothing here can stop it.\nfunction abortable<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {\n if (!signal) {\n return promise;\n }\n return new Promise((resolve, reject) => {\n const onAbort = () => reject(new DOMException('Aborted', 'AbortError'));\n\n if (signal.aborted) {\n onAbort();\n } else {\n signal.addEventListener('abort', onAbort, { once: true });\n }\n void promise.then(resolve, reject).finally(() => signal.removeEventListener('abort', onAbort));\n });\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(new DOMException('Aborted', 'AbortError'));\n return;\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(timer);\n reject(new DOMException('Aborted', 'AbortError'));\n };\n\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\nfunction triggerBrowserDownload(blob: Blob, filename: string): void {\n const objectUrl = URL.createObjectURL(blob);\n\n try {\n const a = document.createElement('a');\n\n a.href = objectUrl;\n a.download = filename;\n a.style.display = 'none';\n document.body.appendChild(a);\n a.click();\n a.remove();\n } finally {\n URL.revokeObjectURL(objectUrl);\n }\n}\n","import type { JwtRequestContext, JwtSource } from './types';\n\n/** Lazy resolver for a Coordinator/runtime bearer token, called immediately\n * before each authenticated request with the session that request is for —\n * see `JwtSource` and `JwtRequestContext`. A resolver that ignores the\n * context keeps working. */\nexport type JwtResolver = (context?: JwtRequestContext) => string | Promise<string>;\n\n/**\n * Wraps a `JwtSource` into a `JwtResolver`: a static string becomes a\n * resolver that always returns it, a resolver passes through unchanged.\n * Useful for feeding a source that may be either form (e.g. a\n * `ReactorProvider`'s `jwtToken`) into a `getJwt` prop that expects a\n * resolver.\n */\nexport function normalizeJwtSource(source: JwtSource): JwtResolver {\n if (typeof source === 'function') {\n return source;\n }\n return () => source;\n}\n","'use client';\n\nimport { createContext, useContext, useEffect, useRef, useState, useSyncExternalStore, type ReactNode } from 'react';\nimport { createReactorStore, type ReactorStore, type StoreApi } from './store';\nimport type { ConnectOptions, JwtSource, ReactorOptions, TrackCapability } from '../types';\n\n/** `connectOptions` for the provider — adds `autoConnect` to the core\n * `ConnectOptions`. Live, same as every other `ReactorProviderProps` field —\n * see `ReactorProvider`'s doc comment. */\nexport interface ReactorConnectOptions extends ConnectOptions {\n /** Connect automatically once a Reactor is built — initial mount, or any\n * later rebuild. Default `false`. */\n autoConnect?: boolean;\n}\n\nexport interface ReactorProviderProps {\n apiUrl?: string | undefined;\n modelName: string;\n local?: boolean | undefined;\n /** Media tracks to declare up front, so the transport can prepare the SDP\n * offer in parallel with session polling instead of waiting to discover\n * them from the model's schema. */\n modelTracks?: TrackCapability[] | undefined;\n /** Static token, or a resolver called before every authenticated request\n * — see `JwtSource`. Required for `autoConnect` against a non-local\n * runtime; can also be supplied later via an explicit `connect()` call\n * instead. */\n jwtToken?: JwtSource | undefined;\n connectOptions?: ReactorConnectOptions | undefined;\n children?: ReactNode;\n}\n\n/** Exported so a component can optionally read the nearest provider's store\n * without requiring one — e.g. `ClipPlayer`, which works both inside and\n * outside a `ReactorProvider`. Most consumers want `useReactor`/`useReactorStore`\n * instead, which throw outside a provider rather than returning `undefined`. */\nexport const ReactorContext = createContext<StoreApi<ReactorStore> | undefined>(undefined);\n\ntype BuildStoreProps = Pick<\n ReactorProviderProps,\n 'apiUrl' | 'modelName' | 'local' | 'modelTracks' | 'jwtToken' | 'connectOptions'\n>;\n\n/**\n * Builds a fresh store (and the `Reactor` underneath) from the provider's\n * props, firing `connect()` immediately when `autoConnect` is set. Used for\n * both the initial mount and every later rebuild, so both go through the\n * same auto-connect path rather than only the first one.\n */\nfunction buildStore({\n apiUrl,\n modelName,\n local,\n modelTracks,\n jwtToken,\n connectOptions,\n}: BuildStoreProps): StoreApi<ReactorStore> {\n // Built up field-by-field, not as one object literal, so an omitted prop\n // stays omitted rather than becoming an explicit `undefined` — required\n // under `exactOptionalPropertyTypes`.\n const options: ReactorOptions = { modelName };\n\n if (apiUrl !== undefined) {\n options.apiUrl = apiUrl;\n }\n if (local !== undefined) {\n options.local = local;\n }\n if (modelTracks !== undefined) {\n options.modelTracks = modelTracks;\n }\n if (jwtToken !== undefined) {\n options.jwt = jwtToken;\n }\n\n // `autoConnect` isn't acted on here — see the effect in `ReactorProvider`\n // that fires it. `ConnectOptions` (unlike `ReactorConnectOptions`) has no\n // `autoConnect` field, so it's stripped before this is stored as the\n // store's `defaultConnectOptions`.\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { autoConnect, ...pollingOptions } = connectOptions ?? {};\n\n return createReactorStore(options, pollingOptions);\n}\n\n/**\n * Owns a `Reactor` instance and exposes it to `useReactor` below.\n *\n * `apiUrl`/`modelName`/`local`/`modelTracks`/`jwtToken`/`connectOptions`\n * (including `autoConnect`) are live: changing any of them tears down the\n * current `Reactor` (`disconnect()` then `[Symbol.dispose]()`) and builds a\n * fresh one — the same way `useLiveKitRoom` rebuilds its `Room` when its\n * construction `options` change. `Reactor` has no equivalent of LiveKit's\n * `token`/`serverUrl` split (reconnecting the *same* instance with new\n * credentials) or its live `connect` boolean (toggling the same `Room`'s\n * connection without rebuilding it) — its constructor bundles everything, so\n * any change, `autoConnect` included, means a fresh instance rather than\n * reconnecting/disconnecting the existing one. Pass a stable `jwtToken`\n * (e.g. via `useCallback` for a resolver) and stable `modelTracks`/\n * `connectOptions` references if you don't want an unrelated parent render to\n * rebuild the connection — object/array props are compared by reference\n * (`modelTracks`/`connectOptions` via a `JSON.stringify` snapshot, same as\n * `useLiveKitRoom` does for its own `options`).\n *\n * Unmounting tears down the same way — see `Reactor.disconnect()`/\n * `[Symbol.dispose]()` for what that frees.\n */\nexport function ReactorProvider({\n apiUrl,\n modelName,\n local,\n modelTracks,\n jwtToken,\n connectOptions,\n children,\n}: ReactorProviderProps) {\n const [store, setStore] = useState(() =>\n buildStore({ apiUrl, modelName, local, modelTracks, jwtToken, connectOptions }),\n );\n // Skips the rebuild effect's mandatory first run — the initial store was\n // already built synchronously above, so re-running the same construction\n // on mount would just replace it with an equivalent one for nothing.\n const isFirstRun = useRef(true);\n\n useEffect(() => {\n if (isFirstRun.current) {\n isFirstRun.current = false;\n\n return;\n }\n setStore(buildStore({ apiUrl, modelName, local, modelTracks, jwtToken, connectOptions }));\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [apiUrl, modelName, local, JSON.stringify(modelTracks), jwtToken, JSON.stringify(connectOptions)]);\n\n // Fires autoConnect for whichever Reactor this provider currently owns —\n // on initial mount and on every rebuild, since both produce a new `store`.\n // Deliberately an effect, not part of `buildStore`'s synchronous\n // construction: `buildStore` runs inside `useState`'s lazy initializer,\n // and React 18 StrictMode double-invokes that during render to surface\n // impure side effects — calling connect() from there fires it against two\n // separate, independently-constructed Reactor instances, and the discarded\n // one leaks a live connection nothing ever tears down. Matches v2, which\n // also fires autoConnect from an effect rather than during construction.\n useEffect(() => {\n const { autoConnect = false, ...pollingOptions } = connectOptions ?? {};\n\n if (autoConnect && store.getState().status === 'disconnected') {\n // A rejection here (auth/network failure, ...) would otherwise escape\n // as an unhandled promise rejection — connect() throws rather than\n // reporting failures through the `error` event, and nothing here\n // awaits this fire-and-forget call.\n store.getState().connect(jwtToken, pollingOptions).catch((error: unknown) => {\n console.error('[Reactor.ReactorProvider] autoConnect failed:', error);\n });\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [store]);\n\n // Tears down whichever Reactor this provider currently owns — on rebuild\n // (store changes, so this cleanup fires for the one being replaced) and on\n // final unmount. disconnect() first (ends the session server-side; a bare\n // [Symbol.dispose]() skips that), then dispose to free local resources for\n // good and stop the store's event listeners from lingering on a Reactor\n // nothing references any more.\n useEffect(() => {\n return () => {\n const reactor = store.getState().internal.reactor;\n\n void reactor.disconnect().finally(() => reactor[Symbol.dispose]());\n };\n }, [store]);\n\n return <ReactorContext.Provider value={store}>{children}</ReactorContext.Provider>;\n}\n\n/** Reads the store directly, with whatever equality behavior `selector`\n * itself implies — most callers want `useReactor` instead, which adds\n * shallow comparison. Throws outside a `ReactorProvider`. */\nexport function useReactorStore<T>(selector: (state: ReactorStore) => T): T {\n const store = useContext(ReactorContext);\n\n if (store === undefined) {\n throw new Error('useReactor must be used within a ReactorProvider');\n }\n\n // The same function serves as both snapshots: `createReactorStore()` is\n // side-effect-free at construction (the wasm client only loads lazily, on\n // first `connect()`), so the state a server render sees is identical to\n // what the client sees before hydration — there's no divergence to\n // reconcile. Omitting `getServerSnapshot` entirely makes React bail out of\n // SSR for this subtree instead (\"Missing getServerSnapshot\").\n const getSnapshot = () => selector(store.getState());\n\n return useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);\n}\n","import { Reactor } from '../reactor';\nimport type { ReactorError } from '../errors';\nimport type { FileRef } from '../file-ref';\nimport type { DownloadClipOptions } from '../recording';\nimport type {\n Clip,\n ConnectOptions,\n JwtSource,\n MessageScope,\n NotFunction,\n ReactorMessage,\n ReactorOptions,\n ReactorStatus,\n} from '../types';\n\n/** State kept reactive for `useReactor` selectors. Stats/schema/capabilities\n * aren't mirrored here — reach them through the `internal.reactor` escape\n * hatch. */\nexport interface ReactorState {\n status: ReactorStatus;\n sessionId: string | undefined;\n lastError: ReactorError | undefined;\n /** Most recent app-scope `message` payload; `runtimeMessage` isn't mirrored\n * here — subscribe on `internal.reactor` for that. */\n lastMessage: ReactorMessage | undefined;\n /** Media tracks received from the model, keyed by track name. Reset to\n * `{}` on every \"disconnected\" status transition — a fresh connection\n * invalidates whatever arrived under the previous one. Append-only within\n * a session: a track pausing/unpublishing mid-session doesn't remove its\n * entry, so a stale `MediaStreamTrack` can linger until the next\n * disconnect. Matches v2's identical behavior (`core/store.ts`). */\n tracks: Record<string, MediaStreamTrack>;\n /** The `jwt` the store was created with — see `createReactorStore`'s\n * `options.jwt`. Set once at creation, not resynced afterward. */\n jwtToken: JwtSource | undefined;\n /** The `defaultConnectOptions` the store was created with — set once at\n * creation, not resynced afterward. Lets a component read the\n * provider-level defaults (e.g. `autoResumeTracks`) without threading\n * them through props of its own. */\n connectOptions: ConnectOptions | undefined;\n}\n\nexport interface ReactorActions {\n connect: (jwt?: JwtSource, options?: ConnectOptions) => Promise<void>;\n disconnect: (recoverable?: boolean) => Promise<void>;\n reconnect: (options?: ConnectOptions) => Promise<void>;\n sendCommand: <T extends object = Record<string, unknown>>(\n command: string,\n data?: NotFunction<T>,\n scope?: MessageScope,\n ) => Promise<ReactorMessage | undefined>;\n publish: (name: string, track: MediaStreamTrack) => Promise<void>;\n unpublish: (name: string) => Promise<void>;\n pauseTrack: (name: string) => Promise<void>;\n resumeTrack: (name: string) => Promise<void>;\n uploadFile: (file: File | Blob, options?: { name?: string }) => Promise<FileRef>;\n requestClip: (durationSeconds: number) => Promise<Clip>;\n requestRecording: () => Promise<Clip>;\n downloadClipAsFile: (clip: Clip, filename?: string | null, options?: DownloadClipOptions) => Promise<Blob>;\n}\n\nexport interface ReactorInternal {\n /** Escape hatch: the underlying `Reactor` instance, for anything the\n * selector state / action bindings above don't cover. */\n reactor: Reactor;\n}\n\nexport type ReactorStore = ReactorState & ReactorActions & { internal: ReactorInternal };\n\nexport const defaultReactorState: ReactorState = {\n status: 'disconnected',\n sessionId: undefined,\n lastError: undefined,\n lastMessage: undefined,\n tracks: {},\n jwtToken: undefined,\n connectOptions: undefined,\n};\n\nexport interface StoreApi<T> {\n getState: () => T;\n subscribe: (listener: () => void) => () => void;\n}\n\n/** Bare-bones observable-state container: a `set`/`get` pair for the\n * builder to mirror events into, `subscribe` for `useSyncExternalStore`. */\nfunction createStore<T extends object>(build: (set: (partial: Partial<T>) => void, get: () => T) => T): StoreApi<T> {\n const listeners = new Set<() => void>();\n let state: T;\n\n const set = (partial: Partial<T>): void => {\n state = { ...state, ...partial };\n listeners.forEach((listener) => listener());\n };\n const get = (): T => state;\n\n state = build(set, get);\n\n return {\n getState: get,\n subscribe: (listener) => {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n };\n}\n\n/**\n * Builds a `Reactor` and the store mirroring it. `defaultConnectOptions` is\n * applied to every `connect()`/`reconnect()` call; a call-site `options`\n * argument still wins field-by-field.\n */\nexport function createReactorStore(\n options: ReactorOptions,\n defaultConnectOptions?: ConnectOptions,\n): StoreApi<ReactorStore> {\n return createStore<ReactorStore>((set, get) => {\n const reactor = new Reactor(options);\n\n reactor.on('statusChanged', (status) => {\n set(status === 'disconnected' ? { status, tracks: {} } : { status });\n });\n reactor.on('sessionIdChanged', (sessionId) => set({ sessionId }));\n reactor.on('error', (lastError) => set({ lastError }));\n reactor.on('message', (lastMessage) => set({ lastMessage }));\n reactor.on('trackReceived', (name, track) => set({ tracks: { ...get().tracks, [name]: track } }));\n\n return {\n ...defaultReactorState,\n jwtToken: options.jwt,\n connectOptions: defaultConnectOptions,\n internal: { reactor },\n connect: (jwt, callOptions) =>\n get().internal.reactor.connect(jwt, { ...defaultConnectOptions, ...callOptions }),\n disconnect: (recoverable) => get().internal.reactor.disconnect(recoverable),\n reconnect: (callOptions) =>\n get().internal.reactor.reconnect({ ...defaultConnectOptions, ...callOptions }),\n sendCommand: (command, data, scope) => get().internal.reactor.sendCommand(command, data, scope),\n publish: (name, track) => get().internal.reactor.publishTrack(name, track),\n unpublish: (name) => get().internal.reactor.unpublishTrack(name),\n pauseTrack: (name) => get().internal.reactor.pauseTrack(name),\n resumeTrack: (name) => get().internal.reactor.resumeTrack(name),\n uploadFile: (file, options) => get().internal.reactor.uploadFile(file, options),\n requestClip: (durationSeconds) => get().internal.reactor.requestClip(durationSeconds),\n requestRecording: () => get().internal.reactor.requestRecording(),\n downloadClipAsFile: (clip, filename, options) =>\n get().internal.reactor.downloadClipAsFile(clip, filename, options),\n };\n });\n}\n","'use client';\n\nimport { useEffect, useRef, useState } from 'react';\nimport { useReactorStore } from './ReactorProvider';\nimport type { ReactorStore } from './store';\nimport type { ConnectionStats, ReactorMessage } from '../types';\n\nfunction shallowEqual(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) {\n return true;\n }\n if (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) {\n return false;\n }\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n return (\n keysA.length === keysB.length &&\n keysA.every((key) => Object.is((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key]))\n );\n}\n\n/** Wraps `selector` so repeated calls return the *previous* result whenever\n * the new one is shallowly equal to it — lets a selector return a fresh\n * object each call without forcing a re-render on every unrelated store\n * update (the object reference `useReactor` sees only changes when its\n * shallow contents do). */\nfunction useShallowSelector<T>(selector: (state: ReactorStore) => T): (state: ReactorStore) => T {\n const cache = useRef<{ value: T } | undefined>(undefined);\n\n return (state) => {\n const next = selector(state);\n\n if (cache.current && shallowEqual(cache.current.value, next)) {\n return cache.current.value;\n }\n\n cache.current = { value: next };\n return next;\n };\n}\n\n/** Reads from the nearest `ReactorProvider`'s store, with a shallow-equality\n * check on the selector's result — so a selector returning a fresh object\n * each call doesn't cause a re-render on every unrelated store update. */\nexport function useReactor<T>(selector: (state: ReactorStore) => T): T {\n return useReactorStore(useShallowSelector(selector));\n}\n\n/** Subscribes to app-scope `message` payloads sent by the model via\n * `get_ctx().send()`. `handler` is kept in a ref so identity churn on\n * every render doesn't retrigger the subscription effect. */\nexport function useReactorMessage(handler: (message: ReactorMessage) => void): void {\n const reactor = useReactor((state) => state.internal.reactor);\n const handlerRef = useRef(handler);\n\n handlerRef.current = handler;\n\n useEffect(() => {\n const listener = (message: ReactorMessage) => handlerRef.current(message);\n\n reactor.on('message', listener);\n return () => reactor.off('message', listener);\n }, [reactor]);\n}\n\n/** Subscribes to platform-scope `runtimeMessage` payloads (moderation,\n * clip/recording lifecycle, ...) — see `useReactorMessage` for app-scope\n * payloads instead. */\nexport function useReactorInternalMessage(handler: (message: ReactorMessage) => void): void {\n const reactor = useReactor((state) => state.internal.reactor);\n const handlerRef = useRef(handler);\n\n handlerRef.current = handler;\n\n useEffect(() => {\n const listener = (message: ReactorMessage) => handlerRef.current(message);\n\n reactor.on('runtimeMessage', listener);\n return () => reactor.off('runtimeMessage', listener);\n }, [reactor]);\n}\n\n/** The most recent `statsUpdate` sample; `undefined` until the first one\n * arrives, and reset back to `undefined` on unmount or reactor change. */\nexport function useStats(): ConnectionStats | undefined {\n const reactor = useReactor((state) => state.internal.reactor);\n const [stats, setStats] = useState<ConnectionStats | undefined>(undefined);\n\n useEffect(() => {\n setStats(undefined);\n reactor.on('statsUpdate', setStats);\n return () => {\n reactor.off('statsUpdate', setStats);\n setStats(undefined);\n };\n }, [reactor]);\n\n return stats;\n}\n","'use client';\n\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport type { CSSProperties, VideoHTMLAttributes } from 'react';\nimport { useReactor } from './hooks';\n\nexport interface ReactorViewProps {\n /** Name of the recvonly video track to render. Must match a track name\n * declared in the model's capabilities. Defaults to `\"main_video\"`. */\n track?: string;\n /** Name of a recvonly audio track to mix into the same `<video>` element\n * alongside `track`. */\n audioTrack?: string;\n width?: number;\n height?: number;\n className?: string;\n style?: CSSProperties;\n videoObjectFit?: NonNullable<VideoHTMLAttributes<HTMLVideoElement>['style']>['objectFit'];\n /** Defaults to `true` when no `audioTrack` is set (keeps the element within\n * browser autoplay policies), `false` otherwise. Pass an explicit value to\n * override either default. */\n muted?: boolean;\n}\n\n/** The current `MediaStreamTrack` for `name`, kept live across `trackReceived`\n * events. Reads through `internal.reactor` directly rather than the store —\n * there's no reactive `tracks` map on `ReactorState` to select from. */\nfunction useReceivedTrack(name: string | undefined): MediaStreamTrack | undefined {\n const reactor = useReactor((state) => state.internal.reactor);\n const [track, setTrack] = useState(() => (name ? reactor.getTrackByName(name) : undefined));\n\n useEffect(() => {\n setTrack(name ? reactor.getTrackByName(name) : undefined);\n\n if (!name) {\n return;\n }\n\n const listener = (receivedName: string, receivedTrack: MediaStreamTrack) => {\n if (receivedName === name) {\n setTrack(receivedTrack);\n }\n };\n\n reactor.on('trackReceived', listener);\n return () => reactor.off('trackReceived', listener);\n }, [reactor, name]);\n\n return track;\n}\n\nexport function ReactorView({\n track = 'main_video',\n audioTrack,\n width,\n height,\n className,\n style,\n videoObjectFit = 'contain',\n muted = audioTrack === undefined,\n}: ReactorViewProps) {\n const videoMediaTrack = useReceivedTrack(track);\n const audioMediaTrack = useReceivedTrack(audioTrack);\n const videoRef = useRef<HTMLVideoElement>(null);\n\n const mediaStream = useMemo(() => {\n const tracks: MediaStreamTrack[] = [];\n\n if (videoMediaTrack) {\n tracks.push(videoMediaTrack);\n }\n if (audioMediaTrack) {\n tracks.push(audioMediaTrack);\n }\n return tracks.length > 0 ? new MediaStream(tracks) : null;\n }, [videoMediaTrack, audioMediaTrack]);\n\n useEffect(() => {\n const el = videoRef.current;\n\n if (!el || !mediaStream) {\n return;\n }\n\n const attach = (reset: boolean) => {\n if (reset) {\n el.srcObject = null;\n }\n el.srcObject = mediaStream;\n void el.play().catch(() => {});\n };\n\n attach(false);\n\n // A recvonly track negotiated while the server has it paused arrives\n // muted (no RTP). When the server resumes sending, the track fires\n // `unmute`, but some browsers keep rendering black on the already-attached\n // `srcObject` until it's reattached — so re-attach on `unmute` to render\n // auto-resumed tracks without a manual pause/resume round-trip.\n const onUnmute = () => attach(true);\n const tracks = mediaStream.getTracks();\n\n for (const t of tracks) {\n t.addEventListener('unmute', onUnmute);\n }\n\n return () => {\n for (const t of tracks) {\n t.removeEventListener('unmute', onUnmute);\n }\n el.srcObject = null;\n };\n }, [mediaStream]);\n\n return (\n <div\n style={{\n position: 'relative',\n background: '#000',\n ...(width !== undefined && { width }),\n ...(height !== undefined && { height }),\n ...style,\n }}\n className={className}\n >\n <video\n ref={videoRef}\n style={{\n width: '100%',\n height: '100%',\n objectFit: videoObjectFit,\n display: videoMediaTrack ? 'block' : 'none',\n }}\n muted={muted}\n playsInline\n />\n </div>\n );\n}\n","'use client';\n\nimport { useEffect, useRef, useState } from 'react';\nimport type { CSSProperties, VideoHTMLAttributes } from 'react';\nimport { useReactor } from './hooks';\nimport type { ReactorError } from '../errors';\n\nexport interface WebcamStreamProps {\n /** Name of the sendonly video track to publish the webcam to. Must match a\n * track name declared in the model's capabilities. */\n track: string;\n /** Capture and publish the microphone alongside the webcam. `true` for\n * default constraints, or explicit `MediaTrackConstraints`. Requires\n * `audioTrack`. Defaults to `false`. */\n audio?: boolean | MediaTrackConstraints;\n /** Name of the sendonly audio track to publish the mic to. Ignored unless\n * `audio` is set. */\n audioTrack?: string;\n className?: string;\n style?: CSSProperties;\n /** Read once, at mount — changing this after mount doesn't re-request\n * `getUserMedia`. Matches v2. */\n videoConstraints?: MediaTrackConstraints;\n showWebcam?: boolean;\n videoObjectFit?: NonNullable<VideoHTMLAttributes<HTMLVideoElement>['style']>['objectFit'];\n /** Fires once `getUserMedia` is rejected with `NotAllowedError` or\n * `PermissionDeniedError`. */\n onPermissionDenied?: () => void;\n /** Fires after the local media has been published (video, and audio when\n * `audio` is enabled). Re-fires after a reconnect. */\n onPublished?: () => void;\n /** Fires on non-permission `getUserMedia` failures and on publish/unpublish\n * rejections. Permission denials route to `onPermissionDenied` instead. */\n onError?: (error: Error) => void;\n}\n\nconst DEFAULT_VIDEO_CONSTRAINTS: MediaTrackConstraints = {\n width: { ideal: 1280 },\n height: { ideal: 720 },\n};\n\nexport function WebcamStream({\n track,\n audio = false,\n audioTrack,\n className,\n style,\n videoConstraints = DEFAULT_VIDEO_CONSTRAINTS,\n showWebcam = true,\n videoObjectFit = 'contain',\n onPermissionDenied,\n onPublished,\n onError,\n}: WebcamStreamProps) {\n const [stream, setStream] = useState<MediaStream | null>(null);\n const [published, setPublished] = useState<{ video: string; audio?: string } | null>(null);\n const [permissionDenied, setPermissionDenied] = useState(false);\n\n const { status, publish, unpublish, reactor } = useReactor((state) => ({\n status: state.status,\n publish: state.publish,\n unpublish: state.unpublish,\n reactor: state.internal.reactor,\n }));\n\n const videoRef = useRef<HTMLVideoElement>(null);\n\n // Held in refs so inline callback identity doesn't churn the\n // publish/unpublish effect below on every parent render.\n const onPermissionDeniedRef = useRef(onPermissionDenied);\n const onPublishedRef = useRef(onPublished);\n const onErrorRef = useRef(onError);\n\n onPermissionDeniedRef.current = onPermissionDenied;\n onPublishedRef.current = onPublished;\n onErrorRef.current = onError;\n\n // Without an `audioTrack` the captured mic has nowhere to publish, so\n // capture stays video-only.\n const audioRequested = audio !== false;\n const audioEnabled = audioRequested && audioTrack !== undefined;\n\n // The mount/unmount effect below only runs once (empty deps), so its\n // cleanup would otherwise close over the props/state from the initial\n // render — mirror them here so teardown unpublishes whatever is actually\n // published and stops the right stream even if they changed since mount.\n //\n // Same empty-deps effect also means `videoConstraints`/`audio`/`audioTrack`\n // are only read once, at mount — changing them later doesn't re-request\n // getUserMedia. Matches v2's WebcamStream, which has the same limitation.\n const latestRef = useRef({ published, unpublish, stream });\n\n latestRef.current = { published, unpublish, stream };\n\n useEffect(() => {\n let cancelled = false;\n\n navigator.mediaDevices\n .getUserMedia({\n video: videoConstraints,\n audio: audioEnabled ? audio : false,\n })\n .then((mediaStream) => {\n if (cancelled) {\n for (const t of mediaStream.getTracks()) {\n t.stop();\n }\n return;\n }\n setStream(mediaStream);\n setPermissionDenied(false);\n })\n .catch((err: unknown) => {\n if (cancelled) {\n return;\n }\n\n if (err instanceof DOMException && (err.name === 'NotAllowedError' || err.name === 'PermissionDeniedError')) {\n setPermissionDenied(true);\n onPermissionDeniedRef.current?.();\n } else {\n onErrorRef.current?.(err instanceof Error ? err : new Error(String(err)));\n }\n });\n\n return () => {\n cancelled = true;\n\n const current = latestRef.current;\n // Unpublish failures don't block local-track teardown — leaving\n // tracks running keeps the camera/mic indicator on after unmount.\n const tasks: Array<Promise<void>> = [];\n\n if (current.published) {\n tasks.push(current.unpublish(current.published.video));\n\n if (current.published.audio) {\n tasks.push(current.unpublish(current.published.audio));\n }\n }\n\n if (tasks.length > 0) {\n void Promise.allSettled(tasks).then((results) => {\n for (const r of results) {\n if (r.status === 'rejected') {\n onErrorRef.current?.(r.reason instanceof Error ? r.reason : new Error(String(r.reason)));\n }\n }\n });\n }\n\n current.stream?.getTracks().forEach((t) => t.stop());\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n useEffect(() => {\n const el = videoRef.current;\n\n if (!el) {\n return;\n }\n el.srcObject = stream;\n }, [stream]);\n\n useEffect(() => {\n if (!stream) {\n return;\n }\n\n let cancelled = false;\n const desiredAudio = audioEnabled ? audioTrack : undefined;\n const activeStream = stream;\n\n async function sync() {\n if (status === 'ready') {\n if (published && published.video === track && published.audio === desiredAudio) {\n return;\n }\n\n // Names changed while already published: drop the stale\n // publication before publishing under the new ones.\n if (published) {\n const rollback: Array<Promise<void>> = [unpublish(published.video)];\n\n if (published.audio) {\n rollback.push(unpublish(published.audio));\n }\n await Promise.allSettled(rollback);\n\n if (cancelled) {\n return;\n }\n setPublished(null);\n }\n\n const videoMediaTrack = activeStream.getVideoTracks()[0];\n const audioMediaTrack = desiredAudio ? activeStream.getAudioTracks()[0] : undefined;\n const attempts: Array<{ name: string; task: Promise<void> }> = [];\n\n if (videoMediaTrack) {\n attempts.push({ name: track, task: publish(track, videoMediaTrack) });\n }\n if (audioMediaTrack && desiredAudio) {\n attempts.push({ name: desiredAudio, task: publish(desiredAudio, audioMediaTrack) });\n }\n if (attempts.length === 0) {\n return;\n }\n\n const results = await Promise.allSettled(attempts.map((a) => a.task));\n\n if (cancelled) {\n return;\n }\n\n const failureIndex = results.findIndex((r) => r.status === 'rejected');\n\n if (failureIndex !== -1) {\n // Roll back whatever did succeed so we never report an error\n // while leaving some names published behind our backs.\n const succeeded = attempts.filter((_, i) => results[i]?.status === 'fulfilled');\n\n await Promise.allSettled(succeeded.map((a) => unpublish(a.name)));\n\n if (cancelled) {\n return;\n }\n\n const failure = results[failureIndex] as PromiseRejectedResult;\n\n onErrorRef.current?.(failure.reason instanceof Error ? failure.reason : new Error(String(failure.reason)));\n return;\n }\n\n const newPublished: { video: string; audio?: string } = { video: track };\n\n if (audioMediaTrack && desiredAudio) {\n newPublished.audio = desiredAudio;\n }\n setPublished(newPublished);\n onPublishedRef.current?.();\n } else if (published) {\n const tasks: Array<Promise<void>> = [unpublish(published.video)];\n\n if (published.audio) {\n tasks.push(unpublish(published.audio));\n }\n\n const results = await Promise.allSettled(tasks);\n\n if (cancelled) {\n return;\n }\n\n for (const r of results) {\n if (r.status === 'rejected') {\n onErrorRef.current?.(r.reason instanceof Error ? r.reason : new Error(String(r.reason)));\n }\n }\n setPublished(null);\n }\n }\n\n void sync();\n\n return () => {\n cancelled = true;\n };\n }, [status, stream, published, publish, unpublish, track, audioEnabled, audioTrack]);\n\n // A rejected publish() is already handled inline in sync() above (awaited,\n // then routed to onError). This listener is for TRACK_PUBLISH_FAILED\n // reported out-of-band by the runtime *after* publish() already resolved —\n // e.g. the track was accepted but later failed to actually flow. Resetting\n // `published` here makes the sync effect re-run and republish.\n useEffect(() => {\n const handleError = (error: ReactorError) => {\n if (error.code === 'TRACK_PUBLISH_FAILED') {\n setPublished(null);\n }\n };\n\n reactor.on('error', handleError);\n return () => reactor.off('error', handleError);\n }, [reactor]);\n\n const showPlaceholder = !stream;\n\n return (\n <div\n style={{\n display: showWebcam ? 'block' : 'none',\n position: 'relative',\n background: '#000',\n ...style,\n }}\n className={className}\n >\n <video\n ref={videoRef}\n style={{\n width: '100%',\n height: '100%',\n objectFit: videoObjectFit,\n display: showPlaceholder ? 'none' : 'block',\n }}\n muted\n playsInline\n autoPlay\n />\n {showPlaceholder && (\n <div\n style={{\n position: 'absolute',\n top: 0,\n left: 0,\n width: '100%',\n height: '100%',\n color: '#fff',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n fontSize: '16px',\n fontFamily: 'monospace',\n textAlign: 'center',\n padding: '20px',\n boxSizing: 'border-box',\n flexDirection: 'column',\n gap: '12px',\n }}\n >\n {permissionDenied ? (\n <div style={{ fontSize: '12px', fontFamily: 'monospace' }}>\n Camera access denied.\n <br />\n Please allow access in your browser settings.\n </div>\n ) : (\n <div style={{ fontSize: '12px', fontFamily: 'monospace' }}>Starting camera...</div>\n )}\n </div>\n )}\n </div>\n );\n}\n","'use client';\n\nimport { useContext, useEffect, useRef, useState } from 'react';\nimport type { CSSProperties } from 'react';\nimport { type ClipPlayback, attachClipPlayback } from '../clip-playback';\nimport { resolveJwtSource } from '../internal/jwt-resolver';\nimport type { JwtResolver } from '../jwt';\nimport { RecordingError, assembleClipBlob, createPlayableManifestUrl, fetchPlaylist } from '../recording';\nimport { ReactorContext } from './ReactorProvider';\nimport type { Clip } from '../types';\n\n/**\n * Video preview for a captured {@link Clip}. Streams the clip with `hls.js`\n * wherever Media Source Extensions exist — every current browser, iOS\n * Safari 17.1 and later included. `hls.js` is dynamically imported, so\n * bundlers give it a chunk of its own that an app importing this component\n * fetches on first play, and one that never renders a player drops\n * entirely. Where Media Source Extensions don't exist — iOS before 17.1 —\n * the clip is assembled into a single MP4 and played from memory instead.\n * Failures surface in an inline error overlay; the chunks remain\n * downloadable via {@link useClipDownload}/`ClipDownloadButton` either way.\n *\n * Preview only — this component doesn't render a download UI. Compose it\n * with `ClipDownloadButton`, or build a custom download surface around\n * `useClipDownload`.\n *\n * Unlike `ReactorView`/`WebcamStream`, this doesn't require a\n * `ReactorProvider` in the tree — it operates on the `Clip` value alone, so\n * it stays usable after `reactor.disconnect()` and works with clips loaded\n * from fixtures or any other source. When a `ReactorProvider` is mounted\n * above, an omitted `getJwt` inherits the provider's resolver.\n */\nexport interface ClipPlayerProps {\n /** The captured clip to play. Re-fetches the manifest and re-attaches the\n * player when this changes by reference. */\n clip: Clip;\n /**\n * Lazy resolver for the Coordinator JWT used on the manifest GET, called\n * before every poll with `{ sessionId: clip.sessionId }` so token refreshes\n * are picked up automatically.\n *\n * Required outside a `ReactorProvider` in production; optional inside one\n * (inherits the provider's resolver). Omit in local-dev mode (HttpRuntime)\n * — the manifest endpoint there is auth-free.\n */\n getJwt?: JwtResolver;\n /**\n * Opt into a bounded wait: give up polling the manifest with\n * `CLIP_NOT_READY` once `max(clip.predictedReadyAtMs, pollStart) + slackMs`\n * passes. Unset by default — the player polls indefinitely until the clip\n * is ready, stopping only when it unmounts or `clip` changes. Forwarded\n * directly to `fetchPlaylist()`'s `slackMs` option.\n */\n slackMs?: number;\n /** Play automatically once the manifest is attached. Default `true`. */\n autoPlay?: boolean;\n /** Start muted. Default `true` — browser autoplay policies block\n * audio-bearing video from playing without a user gesture; the user can\n * unmute via the native controls. */\n muted?: boolean;\n className?: string;\n style?: CSSProperties;\n /** Fires when the player enters its inline error state. A `RecordingError`\n * for manifest-fetch failures, a plain `Error` for hls.js/element playback\n * failures. */\n onError?: (error: Error) => void;\n}\n\ntype Phase =\n | { kind: 'waiting' }\n | { kind: 'loading' }\n | { kind: 'ready' }\n | { kind: 'error'; message: string; error: Error };\n\nexport function ClipPlayer({\n clip,\n getJwt,\n slackMs,\n autoPlay = true,\n muted = true,\n className,\n style,\n onError,\n}: ClipPlayerProps) {\n const videoRef = useRef<HTMLVideoElement | null>(null);\n const [phase, setPhase] = useState<Phase>({ kind: 'waiting' });\n\n // `undefined` outside a `ReactorProvider`; used to inherit the provider's\n // JWT resolver when `getJwt` is omitted.\n const store = useContext(ReactorContext);\n\n // The playback effect intentionally depends only on `clip`. Callers\n // typically pass an inline `getJwt={() => token}` that changes identity on\n // every render — using it directly in the effect deps would tear down the\n // player and re-fetch the manifest on every parent re-render. Same\n // reasoning for `autoPlay`: it's only read at the moment of attach. Refs\n // keep the latest values reachable from inside the effect without forcing\n // it to re-run.\n const getJwtRef = useRef(getJwt);\n const autoPlayRef = useRef(autoPlay);\n const slackMsRef = useRef(slackMs);\n const onErrorRef = useRef(onError);\n // Same ref pattern: the resolver is looked up inside `setup` at request\n // time, so a provider swap is picked up on next attach without tearing the\n // player down.\n const storeRef = useRef(store);\n\n getJwtRef.current = getJwt;\n autoPlayRef.current = autoPlay;\n slackMsRef.current = slackMs;\n onErrorRef.current = onError;\n storeRef.current = store;\n\n // Re-fires per error transition: each new `clip` resets through\n // `waiting`/`loading` before potentially re-entering `error`.\n useEffect(() => {\n if (phase.kind === 'error') {\n onErrorRef.current?.(phase.error);\n }\n }, [phase]);\n\n // Playback pipeline: fetch manifest (with optional JWT) → wrap in blob URL\n // → hand to `attachClipPlayback`, which either streams it with hls.js or\n // assembles the chunks into an MP4. Re-runs only when `clip` changes by\n // reference. The cleanup closure tears every piece down deterministically.\n useEffect(() => {\n const video = videoRef.current;\n\n if (!video) {\n return;\n }\n\n const abort = new AbortController();\n let cancelled = false;\n let playback: ClipPlayback | null = null;\n let manifestBlobUrl: string | null = null;\n\n const fail = (error: Error) => {\n if (cancelled) {\n return;\n }\n const message = error instanceof RecordingError ? `${error.code}: ${error.reason}` : error.message;\n\n setPhase({ kind: 'error', message, error });\n };\n\n const setup = async () => {\n try {\n setPhase({ kind: 'waiting' });\n // Explicit `getJwt` wins; fall back to the provider's source. Read\n // through the refs on every poll, so a rerender with a new `getJwt`\n // reaches a wait already in progress.\n const source = () => getJwtRef.current ?? storeRef.current?.getState().internal.reactor.getJwtResolver();\n const playlistOptions: Parameters<typeof fetchPlaylist>[1] = {\n predictedReadyAtMs: clip.predictedReadyAtMs,\n sessionId: clip.sessionId,\n signal: abort.signal,\n };\n\n if (slackMsRef.current !== undefined) {\n playlistOptions.slackMs = slackMsRef.current;\n }\n if (source() !== undefined) {\n playlistOptions.jwt = (context) => resolveJwtSource(source() ?? '', context);\n }\n\n const body = await fetchPlaylist(clip.playlistUrl, playlistOptions);\n\n if (cancelled) {\n return;\n }\n setPhase({ kind: 'loading' });\n manifestBlobUrl = createPlayableManifestUrl(body, clip.playlistUrl);\n playback = attachClipPlayback(\n video,\n {\n manifestUrl: manifestBlobUrl,\n assembleMp4: () => assembleClipBlob(body, clip.playlistUrl, { signal: abort.signal }),\n },\n {\n autoPlay: autoPlayRef.current,\n onReady: () => {\n if (!cancelled) {\n setPhase({ kind: 'ready' });\n }\n },\n onError: fail,\n },\n );\n } catch (err) {\n if (cancelled) {\n return;\n }\n // `AbortError` from teardown is expected — don't paint it as a failure.\n if (err instanceof DOMException && err.name === 'AbortError') {\n return;\n }\n fail(err instanceof Error ? err : new Error(String(err)));\n }\n };\n\n void setup();\n\n return () => {\n cancelled = true;\n abort.abort();\n playback?.destroy();\n video.pause();\n video.removeAttribute('src');\n video.load();\n if (manifestBlobUrl) {\n URL.revokeObjectURL(manifestBlobUrl);\n }\n };\n }, [clip]);\n\n const overlayText = phase.kind === 'waiting' ? 'Waiting for clip…' : phase.kind === 'loading' ? 'Loading player…' : null;\n\n return (\n <div\n className={className}\n style={{\n position: 'relative',\n background: '#000',\n width: '100%',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n ...style,\n }}\n >\n <video\n ref={videoRef}\n controls\n playsInline\n muted={muted}\n style={{\n display: 'block',\n width: '100%',\n height: 'auto',\n maxHeight: '100%',\n }}\n />\n\n {overlayText && (\n <div\n style={{\n position: 'absolute',\n inset: 0,\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n color: 'rgba(255,255,255,0.6)',\n font: '11px ui-monospace, SFMono-Regular, Menlo, monospace',\n letterSpacing: '0.1em',\n textTransform: 'uppercase',\n pointerEvents: 'none',\n }}\n >\n {overlayText}\n </div>\n )}\n\n {phase.kind === 'error' && (\n <div\n style={{\n position: 'absolute',\n inset: 0,\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n padding: 24,\n background: 'rgba(0,0,0,0.8)',\n color: '#ef4444',\n font: '11px ui-monospace, SFMono-Regular, Menlo, monospace',\n textAlign: 'center',\n }}\n >\n {phase.message}\n </div>\n )}\n </div>\n );\n}\n","/**\n * Attaches a captured clip to a `<video>` element for preview.\n *\n * There are two ways to put a clip on an element, and which one is available\n * is decided by `Hls.isSupported()` — never by\n * `canPlayType(\"application/vnd.apple.mpegurl\")`, which answers `\"maybe\"` in\n * browsers that then fail the load with `MediaError` 4.\n *\n * `hls.js` streams the clip wherever Media Source Extensions exist, which is\n * every current browser, including the Managed variant iOS Safari exposes.\n * Where they don't — iOS before 17.1 — the clip is assembled into a single\n * flat MP4 and played from memory. That costs the whole clip up front\n * instead of streaming it, which for a few seconds of video is a fair trade\n * for working at all.\n *\n * Handing the manifest to the element instead is not a third option, and\n * each engine rules it out for its own reason. Native HLS makes the element\n * load the media segments itself, and Chromium refuses segments from an\n * origin other than the page's whatever CORS headers they carry, while a\n * clip's chunks are presigned URLs that always come from elsewhere. WebKit\n * takes those cross-origin segments happily but won't read a `blob:`\n * manifest at all — and the manifest is always a blob, because fetching it\n * takes an `Authorization` header. Both playback paths here therefore fetch\n * the media themselves: `hls.js` appends it through Media Source Extensions,\n * and the assembled MP4 has no sub-resources left to load.\n *\n * The element is the single source of truth for readiness and failure:\n * `loadedmetadata` marks playback ready (a parsed manifest says nothing\n * about the element holding decodable media), and the element's `error`\n * event carries the `MediaError` that would otherwise leave the viewer\n * looking at a black frame.\n *\n * Rendering, state, and manifest fetching live in the `ClipPlayer` React\n * component; this module owns nothing but the attach.\n */\n\n/** The two forms a clip can take, either of which can drive an element. */\nexport interface ClipSource {\n /** `blob:` URL of the HLS manifest, streamed by `hls.js`. */\n manifestUrl: string;\n /** Assemble the clip into one self-contained MP4. Called only when\n * `hls.js` can't run, and expected to honour the caller's abort signal. */\n assembleMp4: () => Promise<Blob>;\n}\n\n/** Wired up by {@link attachClipPlayback}. */\nexport interface ClipPlaybackOptions {\n /** Start playing as soon as the element has metadata. */\n autoPlay: boolean;\n /** Called once the element has loaded the clip's metadata. */\n onReady: () => void;\n /** Called at most once, with an error suitable for display. */\n onError: (error: Error) => void;\n /** Resolves `hls.js`. Defaults to a dynamic `import()`, which bundlers keep\n * in its own chunk so consumers who never render a player aren't billed\n * for it. A rejection is not fatal: playback falls back to the assembled\n * MP4. */\n loadHls?: () => Promise<HlsConstructor>;\n}\n\nexport interface ClipPlayback {\n /** Detaches every listener, tears down `hls.js`, frees the MP4. */\n destroy: () => void;\n}\n\n/**\n * Play `source` on `video`.\n *\n * Returns as soon as the element is wired up: choosing a path means loading\n * `hls.js`, and taking the fallback means downloading the clip, so both\n * happen in the background and the handle is destroyable throughout.\n * Playback becoming available is reported through\n * {@link ClipPlaybackOptions.onReady}.\n */\nexport function attachClipPlayback(\n video: HTMLVideoElement,\n source: ClipSource,\n {\n autoPlay,\n onReady,\n onError,\n loadHls = () => import('hls.js').then((mod) => (mod as { default: HlsConstructor }).default),\n }: ClipPlaybackOptions,\n): ClipPlayback {\n let destroyed = false;\n let failed = false;\n let ready = false;\n let hls: HlsInstance | null = null;\n let mp4Url: string | null = null;\n\n const fail = (error: Error) => {\n if (destroyed || failed) {\n return;\n }\n failed = true;\n onError(error);\n };\n\n const handleLoadedMetadata = () => {\n // Metadata can arrive more than once, and can arrive after a failure was\n // reported. Reporting it again would clear an error the viewer is\n // reading, or restart a clip they paused.\n if (destroyed || failed || ready) {\n return;\n }\n ready = true;\n onReady();\n if (autoPlay) {\n video.play().catch(() => {\n // Autoplay may be blocked by the browser; native controls still work.\n });\n }\n };\n\n const handleElementError = () => {\n fail(new Error(describeMediaError(video.error)));\n };\n\n video.addEventListener('loadedmetadata', handleLoadedMetadata);\n video.addEventListener('error', handleElementError);\n\n const handle: ClipPlayback = {\n destroy: () => {\n destroyed = true;\n video.removeEventListener('loadedmetadata', handleLoadedMetadata);\n video.removeEventListener('error', handleElementError);\n hls?.destroy();\n hls = null;\n if (mp4Url) {\n URL.revokeObjectURL(mp4Url);\n mp4Url = null;\n }\n },\n };\n\n const selectPath = async () => {\n // A browser with no MediaSource of any kind can't run `hls.js`, so don't\n // spend the download to find out — go straight to the MP4. Loading it\n // and asking is still the rule everywhere else: this test is the weakest\n // part of `Hls.isSupported()`, never a reimplementation of it.\n const HlsCtor = hasMediaSource() ? await loadHls().catch(() => null) : null;\n\n if (destroyed) {\n return;\n }\n\n if (HlsCtor?.isSupported()) {\n const instance = new HlsCtor();\n\n instance.loadSource(source.manifestUrl);\n instance.attachMedia(video);\n instance.on(HlsCtor.Events.ERROR, (_evt: unknown, data: HlsErrorData) => {\n if (destroyed) {\n return;\n }\n if (data.fatal) {\n fail(new Error(`Playback error: ${data.details ?? 'unknown'}`));\n return;\n }\n // Non-fatal errors are the usual explanation for a \"fetches but\n // nothing renders\" symptom (bufferAppendingError, fragParsingError,\n // levelLoadError), which the user-facing overlay would otherwise\n // hide.\n console.warn('[Reactor.ClipPlayer] hls.js non-fatal error', data);\n });\n hls = instance;\n return;\n }\n\n const blob = await source.assembleMp4();\n\n if (destroyed) {\n return;\n }\n mp4Url = URL.createObjectURL(blob);\n video.src = mp4Url;\n };\n\n selectPath().catch((err: unknown) => {\n fail(err instanceof Error ? err : new Error(String(err)));\n });\n\n return handle;\n}\n\n/**\n * Whether the browser exposes a MediaSource `hls.js` could drive — the\n * Managed variant included, which is the one iOS Safari 17.1 added. Older\n * iOS has none of the three and is the reason clips still need a path that\n * doesn't stream.\n */\nfunction hasMediaSource(): boolean {\n const scope = globalThis as Record<string, unknown>;\n\n return Boolean(scope.ManagedMediaSource ?? scope.MediaSource ?? scope.WebKitMediaSource);\n}\n\nconst MEDIA_ERROR_MESSAGES: Record<number, string> = {\n 1: 'Playback was aborted.',\n 2: 'A network error interrupted playback.',\n 3: 'This clip could not be decoded.',\n 4: 'This browser cannot play this clip. Use Download instead.',\n};\n\n/**\n * Turn the element's `MediaError` into displayable text, keeping the\n * browser's own diagnostic (`DEMUXER_ERROR_...` and friends) when it\n * provides one.\n */\nfunction describeMediaError(error: MediaError | null): string {\n const message = (error && MEDIA_ERROR_MESSAGES[error.code]) ?? 'This clip failed to play in this browser. Use Download instead.';\n\n return error?.message ? `${message} (${error.message})` : message;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Structural typings covering exactly the `hls.js` surface this module\n// drives. Naming the shape rather than importing the class keeps the loader\n// swappable, which is what lets the tests exercise every path without the\n// real library.\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface HlsInstance {\n loadSource: (url: string) => void;\n attachMedia: (el: HTMLMediaElement) => void;\n on: (event: string, cb: (evt: unknown, data: HlsErrorData) => void) => void;\n destroy: () => void;\n}\n\nexport interface HlsConstructor {\n new (): HlsInstance;\n isSupported: () => boolean;\n readonly Events: {\n readonly ERROR: string;\n };\n}\n\nexport interface HlsErrorData {\n fatal?: boolean;\n details?: string;\n}\n","'use client';\n\nimport { useEffect, useRef } from 'react';\nimport type { CSSProperties, ReactNode } from 'react';\nimport { useClipDownload } from './useClipDownload';\nimport type { ClipDownloadState, UseClipDownloadOptions } from './useClipDownload';\nimport type { JwtResolver } from '../jwt';\nimport type { Clip } from '../types';\n\n/**\n * Standalone download button for a captured {@link Clip}. Drops anywhere in\n * your UI — modal headers, list rows, hover menus, floating action buttons\n * — and is responsible for nothing more than triggering a download and\n * reflecting its state. Wraps `useClipDownload` internally; for completely\n * custom UIs (progress bars, menu items, post-download blob handling) call\n * that hook directly.\n *\n * Styling is intentionally minimal — override via `className`/`style`, or\n * replace the inner content with the `children` render-prop. No CSS file is\n * shipped; every default style is inline so it loses to anything the\n * consumer provides.\n */\nexport interface ClipDownloadButtonProps {\n /** The clip to download. */\n clip: Clip;\n /** Lazy JWT resolver. Optional inside a `ReactorProvider` (inherits the\n * provider's resolver) and in local-dev mode. See `ClipPlayerProps.getJwt`. */\n getJwt?: JwtResolver;\n /** Filename for the saved MP4. Default `\"reactor-clip.mp4\"`. */\n filename?: string;\n /**\n * Inner content of the button. Three forms:\n *\n * - Omitted — renders a default label that follows the state\n * (`\"Download\"` / `\"Downloading 3/8…\"` / etc.).\n * - `ReactNode` — static label, no state-driven text.\n * - `(state) => ReactNode` — state-aware render function, for custom\n * progress strings, spinners, etc.\n */\n children?: ReactNode | ((state: ClipDownloadState) => ReactNode);\n /** Forwarded to the underlying `<button>`. */\n className?: string;\n /** Forwarded to the underlying `<button>` — merges after the defaults so\n * each property overrides. */\n style?: CSSProperties;\n /** Forwarded to the underlying `<button>`. ORed with the internal\n * \"downloading\" state. */\n disabled?: boolean;\n /** Fires when the download completes with the assembled MP4 Blob. */\n onSuccess?: (blob: Blob) => void;\n /** Fires when the download fails. Message mirrors the in-button state —\n * `\"<CODE>: <reason>\"` for `RecordingError`s, the plain error message\n * otherwise. */\n onError?: (error: Error) => void;\n}\n\nexport function ClipDownloadButton({\n clip,\n getJwt,\n filename = 'reactor-clip.mp4',\n children,\n className,\n style,\n disabled,\n onSuccess,\n onError,\n}: ClipDownloadButtonProps) {\n const downloadOptions: UseClipDownloadOptions = { filename };\n\n if (getJwt !== undefined) {\n downloadOptions.getJwt = getJwt;\n }\n\n const { state, download } = useClipDownload(clip, downloadOptions);\n const downloading = state.kind === 'downloading';\n const isDisabled = downloading || !!disabled;\n\n // Held in refs so inline callback identity doesn't churn the error-emit\n // effect or the click handler on every parent render.\n const onSuccessRef = useRef(onSuccess);\n const onErrorRef = useRef(onError);\n\n onSuccessRef.current = onSuccess;\n onErrorRef.current = onError;\n\n // `useClipDownload.download()` resolves to `undefined` on failure (the\n // hook surfaces errors through state, not by rejecting). Each retry that\n // lands back in `\"error\"` re-fires `onError`.\n useEffect(() => {\n if (state.kind === 'error') {\n onErrorRef.current?.(new Error(state.message));\n }\n }, [state]);\n\n const content = typeof children === 'function' ? children(state) : children !== undefined ? children : defaultLabel(state);\n\n return (\n <button\n type=\"button\"\n onClick={() => {\n void download().then((blob) => {\n if (blob) {\n onSuccessRef.current?.(blob);\n }\n });\n }}\n disabled={isDisabled}\n title={state.kind === 'error' ? state.message : undefined}\n className={className}\n style={{\n padding: '5px 12px',\n borderRadius: 4,\n border: '1px solid rgba(255,255,255,0.15)',\n background: 'rgba(255,255,255,0.05)',\n color: '#fff',\n font: '11px ui-monospace, SFMono-Regular, Menlo, monospace',\n cursor: isDisabled ? 'default' : 'pointer',\n opacity: isDisabled ? 0.6 : 1,\n transition: 'background-color 120ms ease',\n ...style,\n }}\n >\n {content}\n </button>\n );\n}\n\nfunction defaultLabel(state: ClipDownloadState): ReactNode {\n if (state.kind === 'downloading') {\n if (state.total > 0) {\n return `Downloading ${state.fetched}/${state.total}…`;\n }\n return 'Downloading…';\n }\n return 'Download';\n}\n","'use client';\n\nimport { useCallback, useContext, useEffect, useRef, useState } from 'react';\nimport { resolveJwtSource } from '../internal/jwt-resolver';\nimport type { JwtResolver } from '../jwt';\nimport { RecordingError, downloadClipAsFile } from '../recording';\nimport { ReactorContext } from './ReactorProvider';\nimport type { Clip } from '../types';\n\n/**\n * State machine for an in-progress clip download.\n *\n * - `idle`: no download in flight (initial state, and what the hook returns\n * to after a successful save).\n * - `downloading`: chunks are being fetched. `fetched`/`total` count the\n * chunks (init segment + media segments) — useful for a progress bar.\n * `total` is 0 until the manifest is parsed and the chunk count is known.\n * - `error`: most recent attempt failed; `message` is suitable for\n * surfacing inline. `RecordingError`s are formatted as `\"<CODE>: <reason>\"`.\n */\nexport type ClipDownloadState =\n | { kind: 'idle' }\n | { kind: 'downloading'; fetched: number; total: number }\n | { kind: 'error'; message: string };\n\nexport interface UseClipDownloadOptions {\n /** Filename used when the browser save dialog opens. Pass `null` to skip\n * the `<a download>` trigger entirely — the returned Blob is still\n * resolved so the caller can `URL.createObjectURL` it or re-upload it.\n * Default `\"reactor-clip.mp4\"`. */\n filename?: string | null;\n /**\n * Lazy resolver for the Coordinator JWT used on the manifest GET. Called\n * before every poll of a {@link UseClipDownloadResult.download} with\n * `{ sessionId: clip.sessionId }`, so token refreshes are picked up\n * automatically.\n *\n * Optional inside a `ReactorProvider` (inherits the provider's resolver)\n * and in local-dev mode.\n */\n getJwt?: JwtResolver;\n}\n\nexport interface UseClipDownloadResult {\n /** Current state of the most recent download attempt. */\n state: ClipDownloadState;\n /**\n * Trigger a download. Resolves with the assembled fragmented-MP4 Blob, or\n * `undefined` if a download was already in flight (a no-op in that case)\n * or the attempt failed. Errors are surfaced via {@link state} rather than\n * a rejection — check `state.kind === \"error\"` to drive failure UI.\n */\n download: () => Promise<Blob | undefined>;\n /** Reset to `idle`. Does *not* cancel an in-flight download. */\n reset: () => void;\n}\n\n/**\n * Headless download primitive for a {@link Clip}. Wraps `downloadClipAsFile`\n * in a React state machine so the consumer can render any button they want,\n * anywhere they want, and still get progress + error feedback. Used\n * internally by `ClipDownloadButton` — reach for this hook directly when you\n * need custom placement or styling.\n *\n * `download`/`reset` are stable callback identities across renders, so\n * they're safe to pass through memoized children without forcing re-renders.\n */\nexport function useClipDownload(clip: Clip, options: UseClipDownloadOptions = {}): UseClipDownloadResult {\n const [state, setState] = useState<ClipDownloadState>({ kind: 'idle' });\n\n // `undefined` outside a `ReactorProvider`; used to inherit the provider's\n // JWT resolver when `options.getJwt` is omitted.\n const store = useContext(ReactorContext);\n\n // Latest-value refs so `download` can be a stable callback (empty deps)\n // without forcing the caller to memoize `clip`/`options`.\n const clipRef = useRef(clip);\n const filenameRef = useRef<string | null>(options.filename ?? 'reactor-clip.mp4');\n const getJwtRef = useRef(options.getJwt);\n const storeRef = useRef(store);\n\n clipRef.current = clip;\n filenameRef.current = options.filename === undefined ? 'reactor-clip.mp4' : options.filename;\n getJwtRef.current = options.getJwt;\n storeRef.current = store;\n\n // Re-entrancy guard. Lives in a ref (not state) so back-to-back\n // synchronous clicks before the first `setState` flushes are still\n // handled correctly.\n const inFlightRef = useRef(false);\n\n // `downloadClipAsFile` polls the manifest indefinitely by default, so an\n // in-flight download that never resolves would otherwise outlive the\n // component. Abort it on unmount; the abort surfaces as an `AbortError`,\n // swallowed below rather than painted as a failure.\n const abortRef = useRef<AbortController | null>(null);\n\n useEffect(() => () => abortRef.current?.abort(), []);\n\n const download = useCallback(async (): Promise<Blob | undefined> => {\n if (inFlightRef.current) {\n return undefined;\n }\n inFlightRef.current = true;\n const abort = new AbortController();\n\n abortRef.current = abort;\n setState({ kind: 'downloading', fetched: 0, total: 0 });\n try {\n // Explicit `options.getJwt` wins; fall back to the provider's source.\n // Read through the refs on every poll, so a rerender with a new\n // `getJwt` during a `202` wait reaches the next poll.\n const source = () => getJwtRef.current ?? storeRef.current?.getState().internal.reactor.getJwtResolver();\n const downloadOptions: Parameters<typeof downloadClipAsFile>[2] = {\n signal: abort.signal,\n onProgress: ({ fetched, total }) => setState({ kind: 'downloading', fetched, total }),\n };\n\n if (source() !== undefined) {\n downloadOptions.jwt = (context) => resolveJwtSource(source() ?? '', context);\n }\n\n const blob = await downloadClipAsFile(clipRef.current, filenameRef.current, downloadOptions);\n\n setState({ kind: 'idle' });\n return blob;\n } catch (err) {\n if (err instanceof DOMException && err.name === 'AbortError') {\n return undefined;\n }\n const message =\n err instanceof RecordingError ? `${err.code}: ${err.reason}` : err instanceof Error ? err.message : String(err);\n\n setState({ kind: 'error', message });\n return undefined;\n } finally {\n inFlightRef.current = false;\n }\n }, []);\n\n const reset = useCallback(() => setState({ kind: 'idle' }), []);\n\n return { state, download, reset };\n}\n"],"mappings":";;;AAAA,SAAS,kBAAkB;;;ACMpB,SAAS,qBAAqB,MAAsC;AACzE,QAAM,eAA6B;AAAA,IACjC,iBAAiB,KAAK;AAAA,IACtB,QAAQ,KAAK;AAAA,EACf;AAEA,MAAI,KAAK,aAAa,QAAW;AAC/B,iBAAa,WAAW,KAAK;AAAA,EAC/B;AACA,MAAI,KAAK,iBAAiB,QAAW;AACnC,iBAAa,cAAc,KAAK;AAAA,EAClC;AACA,SAAO;AACT;;;ACFA,IAAM,QACH,OAAO,YAAY,eAAe,SAAS,KAAK,aAAa,iBAC9D,YAAY,KAAK,QAAQ;AAIpB,SAAS,YAAY,MAAuB;AACjD,MAAI,OAAO;AACT,YAAQ,MAAM,GAAG,IAAI;AAAA,EACvB;AACF;;;ACKO,IAAM,eAAN,cAA2B,MAAM;AAAA;AAAA;AAAA,EAGtC,OAAgB,OAAe;AAAA;AAAA;AAAA;AAAA;AAAA,EAMtB;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA;AAAA;AAAA;AAAA,EAIA;AAAA;AAAA;AAAA,EAGA;AAA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AAA,MACH;AAAA,MACA,UAAU;AAAA,MACV,OAAO,MAAM,SAAS,UAAU,MAAM,UAAU;AAAA,MAChD;AAAA,MACA,OAAO;AAAA,QACL,SAAS;AAAA,QACT,cAAc;AAAA,QACd,QAAQ;AAAA,QACR,YAAY;AAAA,QACZ,OAAO;AAAA,QACP,MAAM;AAAA,QACN,QAAQ,aAAa,YAAY;AAAA,QACjC,SAAS,aAAa,MAAM;AAAA,QAC5B,YAAY;AAAA,QACZ,GAAG;AAAA,MACL;AAAA,MAEC;AAAA;AAAA,EACH;AAEJ;AAEA,SAAS,aAAa,OAAqC;AACzD,MAAI,MAAM,SAAS,eAAe;AAChC,QAAI,MAAM,QAAQ,GAAG;AACnB,aAAO,eAAe,MAAM,OAAO,IAAI,MAAM,KAAK;AAAA,IACpD;AACA,WAAO;AAAA,EACT;AACA,SAAO;AACT;","names":["options","useEffect","useRef","useState","useRef","useEffect","useState","useEffect","useRef","useState","jsx","useState","useEffect","useRef","useEffect","useRef","useState","jsx","useState","useRef","useEffect","useContext","useEffect","useRef","useState","jsx","jsxs","useRef","useState","useContext","useEffect","useEffect","useRef","useContext","useEffect","useRef","useState","useState","useContext","useRef","useEffect","jsx","useRef","useEffect"]}
|
|
1
|
+
{"version":3,"sources":["../src/reactor.ts","../src/internal/capabilities.ts","../src/internal/debug-log.ts","../src/errors.ts","../src/internal/emitter.ts","../src/internal/encoded-frames.ts","../src/file-ref.ts","../src/internal/file-ref.ts","../src/internal/push-frames.ts","../src/internal/recording.ts","../src/internal/step-media.ts","../src/internal/stats.ts","../src/internal/wasm.ts","../package.json","../src/internal/jwt-resolver.ts","../src/recording.ts","../src/step-frames.ts","../src/jwt.ts","../src/react/ReactorProvider.tsx","../src/react/store.ts","../src/react/hooks.ts","../src/react/ReactorView.tsx","../src/react/WebcamStream.tsx","../src/react/ClipPlayer.tsx","../src/clip-playback.ts","../src/react/ClipDownloadButton.tsx","../src/react/useClipDownload.ts"],"sourcesContent":["import { AwaitQueue } from 'awaitqueue';\nimport { toPublicCapabilities } from './internal/capabilities';\nimport { debugLog } from './internal/debug-log';\nimport { InvalidStateError, toReactorError, type ReactorError } from './errors';\nimport { Emitter } from './internal/emitter';\nimport { toEncodedBytes } from './internal/encoded-frames';\nimport { extractFileRefs, rewriteNestedFileRefs, toPublicFileRef } from './internal/file-ref';\nimport { holdFrame, isAudioFrame, toPixels } from './internal/push-frames';\nimport { toPublicClip } from './internal/recording';\nimport {\n checkStepFrame,\n holdStepMedia,\n readStepFrame,\n type ReadyStepFrame,\n} from './internal/step-media';\nimport type { ReactorClient } from './internal/reactor-wasm.types';\nimport {\n LOCAL_STATS_INTERVAL_MS,\n RUNTIME_REPORT_INTERVAL_MS,\n createConnectionStatsExtractor,\n createTrackStatsExtractor,\n pollPeerStats,\n toClientConnectionStat,\n type TrackStatsExtractor,\n} from './internal/stats';\nimport { loadReactorWasm } from './internal/wasm';\nimport packageJson from '../package.json';\nimport type { FileRef } from './file-ref';\nimport { downloadClipAsFile as downloadClipAsFileFn, type DownloadClipOptions } from './recording';\nimport type {\n Capabilities,\n Clip,\n ConnectionStats,\n ConnectionTimings,\n ConnectOptions,\n EncodedFrame,\n JwtSource,\n MessageScope,\n ModelSchema,\n NotFunction,\n PushFrame,\n PublishedTrack,\n PushFrameOptions,\n ReactorEventMap,\n ReactorMessage,\n ReactorOptions,\n ReactorStatus,\n SessionResponse,\n StepOptions,\n StepResult,\n TrackCapability,\n TrackMappingEntry,\n} from './types';\n\n/**\n * A live connection to a Reactor model.\n */\nexport class Reactor implements Disposable {\n private readonly clientOptions: Omit<ReactorOptions, 'jwt'>;\n private jwt: JwtSource | null | undefined;\n private client: ReactorClient | undefined;\n private clientPromise: Promise<ReactorClient> | undefined;\n private disposed = false;\n private _lastError: ReactorError | undefined;\n private schema: ModelSchema | undefined;\n /** Bumped on every `refreshSchema()` call — lets a call detect it's been\n * superseded by a newer one even when `client` itself hasn't changed\n * (e.g. two \"ready\" transitions on the same reused client). */\n private schemaRefreshId = 0;\n private capabilities: Capabilities | undefined;\n\n private stats: ConnectionStats | undefined;\n private connectionTimings: ConnectionTimings | undefined;\n /** The stop functions of the running stats pollers — see `pollPeerStats()`. */\n private stopStatsPollers: Array<() => void> = [];\n /** Whether this connection has already reported its time to connect —\n * a one-time fact, sent on the first client-stats report that carries it\n * and omitted on every one after. Set only once a batch actually went out\n * with it, so a batch sent before the timings exist doesn't use it up.\n * Reset per `startStatsPolling()` call, i.e. per connect()/reconnect(). */\n private hasSentConnectTime = false;\n /** Whether this connection has sent a client-stats batch yet. The first\n * one goes out even with no reading, for the environment the bridge adds\n * to it. Reset with `hasSentConnectTime`. */\n private hasSentClientStats = false;\n /** Set on the \"connecting\" status transition, cleared once `connectionTimings`\n * is finalized on \"ready\" — see `handleStatusChanged()`. */\n private connectStartTime: number | undefined;\n private waitingStartTime: number | undefined;\n\n /** The tail of every `pushFrame()`/`pushEncodedFrame()` so far, settled\n * either way — pushes reach the binding in call order however long each\n * one's pixels take to read, and `step()` waits for the ones called\n * before it. */\n private pendingPushes: Promise<void> = Promise.resolve();\n\n private readonly emitter = new Emitter<ReactorEventMap>();\n /** Serializes connect()/reconnect()/disconnect() (and the free() inside\n * disconnect()/[Symbol.dispose]) against each other. Calling into the\n * client concurrently with one of these (e.g. a user clicking Disconnect\n * mid-connect) races its internal state and can throw (\"attempted to\n * take ownership of Rust value while it was borrowed\") or corrupt it\n * outright. */\n private readonly queue = new AwaitQueue();\n\n /** In-flight calls to `withReaderAccess()` — a \"reply\" `.catch(() => {})`\n * copy of each, never the caller's own promise, so one rejecting can't\n * make `Promise.all()` in `withWriterAccess()` reject and skip waiting\n * for the rest. See `withReaderAccess()`/`withWriterAccess()`. */\n private readonly activeReads = new Set<Promise<unknown>>();\n /** True for the span of a `withWriterAccess()` call — after it has waited\n * out every read active when it started, before it releases the ones\n * that arrived while it ran. */\n private writerActive = false;\n /** Counts `disconnect()`s and disposal. A push captures it when called, and\n * one whose frame was still being read when it moved is dropped, rather\n * than recreating a client to carry the frame into the next session. */\n private connectionEpoch = 0;\n /** Input tracks published on this connection, each with the publication\n * that claimed it: a push needs one, and a `PublishedTrack` only feeds the\n * publication it came from. Cleared with the connection. */\n private readonly publishedInputs = new Map<string, number>();\n private publications = 0;\n /** Readers parked in `withReaderAccess()`'s wait loop, woken once\n * `withWriterAccess()` finishes; each re-checks `writerActive` rather\n * than assuming its turn, since another writer already queued behind the\n * first one may have claimed it first. */\n private writerIdleWaiters: Array<() => void> = [];\n\n /**\n * Runs a read — sendCommand()/requestSchema()/requestClip()/\n * requestRecording() — excluded from a lifecycle op (`withWriterAccess()`)\n * but not from other reads: unlike `queue`, concurrent reads run\n * concurrently. Queuing them the same way `queue` serializes writes would\n * head-of-line block an unrelated command, or even disconnect() itself,\n * behind one slow reply (the binding correlates replies independently, so\n * nothing requires this to be serial).\n *\n * Race-free the same way the wasm binding's own `readyState` check is: the\n * `writerActive` check and this call's registration in `activeReads` both\n * happen before the first `await` inside *fn*, so nothing can run between\n * them on a single-threaded JS event loop.\n */\n private async withReaderAccess<T>(fn: () => Promise<T>): Promise<T> {\n while (this.writerActive) {\n await new Promise<void>((resolve) => this.writerIdleWaiters.push(resolve));\n }\n const result = fn();\n const tracked = result.catch(() => undefined);\n\n this.activeReads.add(tracked);\n try {\n return await result;\n } finally {\n this.activeReads.delete(tracked);\n }\n }\n\n /**\n * Runs a lifecycle op's client-touching body exclusively: waits out every\n * read already in flight, then blocks new ones (`writerActive`) until it\n * finishes. Only ever called from inside a `queue`-serialized task, so at\n * most one writer runs this at a time — it doesn't serialize against\n * itself, only against `activeReads`.\n */\n private async withWriterAccess<T>(fn: () => Promise<T>): Promise<T> {\n // Mark the writer active *before* awaiting the current reads, not after:\n // withReaderAccess()'s gate check is what keeps a new read from entering\n // during that wait, and it only works once this flag is already true.\n // Setting it first can't race a second writer — writers only ever run\n // from inside a `queue`-serialized task, so at most one is ever here.\n this.writerActive = true;\n // Skip the await entirely when nothing is in flight — `await\n // Promise.all([])` still costs a microtask tick, which the common\n // (uncontended) case shouldn't pay: connect()/disconnect()/reconnect()\n // calling into the client promptly is a property callers (React's\n // effect-cleanup unmount included) rely on.\n if (this.activeReads.size > 0) {\n await Promise.all(this.activeReads);\n }\n try {\n return await fn();\n } finally {\n this.writerActive = false;\n const waiters = this.writerIdleWaiters;\n\n this.writerIdleWaiters = [];\n for (const wake of waiters) {wake();}\n }\n }\n\n constructor(options: ReactorOptions) {\n const { jwt, ...clientOptions } = options;\n\n // The wasm binding's own default (`reactor-core`'s crate version) tracks\n // the Rust workspace, not this package — without this, `client_info`\n // reports the wrong version to the coordinator. Still overridable via\n // `options.sdkVersion`.\n this.clientOptions = { sdkVersion: packageJson.version, ...clientOptions };\n this.jwt = jwt ?? null;\n }\n\n // ── Lifecycle ───────────────────────────────────────────────────────────\n\n /**\n * `jwt`, when given, replaces whatever `new Reactor({ jwt })` was given —\n * including on a client that's still around from a recoverable\n * `disconnect(true)`.\n *\n * Throws if already connected or connecting; call `disconnect()` first.\n */\n async connect(jwt?: JwtSource, options?: ConnectOptions): Promise<void> {\n this.assertNotDisposed();\n try {\n if (this.getStatus() !== 'disconnected') {\n throw new Error('Already connected or connecting.');\n }\n if (jwt !== undefined) {\n this.jwt = jwt;\n this.client?.setJwt(jwt);\n }\n await this.queue.push(\n () =>\n this.withWriterAccess(async () => {\n const client = await this.getOrCreateClient();\n\n await client.connect(options);\n }),\n 'connect',\n );\n } catch (cause) {\n throw this.captureError(cause);\n }\n }\n\n /**\n * Ends the connection. By default (`recoverable = false`) this also frees\n * the wasm resource graph — the pump/dispatcher/heartbeat tasks and the\n * peer connection — in one step. Pass `recoverable: true` to keep the\n * wasm client alive so a later `connect()`/`reconnect()` doesn't have to\n * reload wasm and reconstruct it from scratch.\n *\n * Note this only governs the *local* resource graph — the binding's own\n * `disconnect()` always ends the session server-side regardless of this\n * flag, so `recoverable` isn't a way to keep the session itself alive.\n *\n * Queued behind any in-flight `connect()`/`reconnect()` — see `queue`'s\n * docs for why calling into the client concurrently with one of those is\n * unsafe.\n */\n async disconnect(recoverable = false): Promise<void> {\n this.assertNotDisposed();\n try {\n await this.queue.push(\n () =>\n this.withWriterAccess(async () => {\n if (this.client) {\n await this.client.disconnect();\n }\n this.resetConnectionState();\n if (!recoverable) {\n this.freeClient();\n }\n }),\n 'disconnect',\n );\n } catch (cause) {\n throw this.captureError(cause);\n }\n }\n\n /**\n * Only `options.maxAttempts` has an effect here — the rest of\n * `ConnectOptions` (session adoption, connection id, auto-resume) only\n * makes sense when establishing a session in the first place, same as v2's\n * `reconnect()` always ignored them.\n */\n async reconnect(options?: ConnectOptions): Promise<void> {\n this.assertNotDisposed();\n try {\n await this.queue.push(\n () =>\n this.withWriterAccess(async () => {\n const client = await this.getOrCreateClient();\n\n await client.reconnect(options);\n }),\n 'reconnect',\n );\n } catch (cause) {\n throw this.captureError(cause);\n }\n }\n\n // ── Messaging ───────────────────────────────────────────────────────────\n\n /**\n * Sends a command to the model and resolves with its correlated reply.\n *\n * `undefined` means the handler acknowledged the command but sent no\n * reply body. The binding's own typed signature promises `undefined` for\n * that case, but its serializer (serde_wasm_bindgen's `json_compatible`\n * mode) actually hands back `null` — normalized here so callers can rely\n * on the documented type instead of the binding's serialization quirk.\n *\n * A `FileRef` (from `uploadFile`) may be passed in `data` wherever the\n * model's schema declares a file. As a top-level value it is extracted and\n * sent as a separate upload reference rather than embedded in the JSON\n * payload; inside an array or object (a parameter that takes several files,\n * say) it is serialized as an upload reference in place.\n *\n * Unlike every other method here, this never rejects — a failure (the\n * session isn't `\"ready\"`, the send itself fails, …) is reported through\n * `getLastError()`/the `error` event instead, resolving with `undefined`.\n * This is a JS-only compatibility shim, kept because callers routinely\n * fire-and-forget `sendCommand(...)` without `await`/`catch`, and a\n * rejection nobody handles is an unhandled-rejection warning at best. It\n * is deliberately not applied to `publishTrack`/`uploadFile`/etc., which\n * throw normally.\n *\n * `scope` is forwarded to `sendRuntimeScopedCommand()` — see there for\n * what `\"runtime\"` actually does.\n *\n * `data` accepts any object, except a function.\n */\n async sendCommand<T extends object = Record<string, unknown>>(\n command: string,\n data?: NotFunction<T>,\n scope?: MessageScope,\n ): Promise<ReactorMessage | undefined> {\n if (scope === 'runtime') {\n return this.sendRuntimeScopedCommand(command, data);\n }\n try {\n this.assertNotDisposed();\n const extracted = extractFileRefs(data as Record<string, unknown> | undefined);\n // Excluded from connect()/disconnect()/reconnect() — a concurrent\n // disconnect() can otherwise free the wasm client while this call into\n // it is still in flight (see `withReaderAccess()`'s docs) — but not\n // from other reads, unlike the track ops on `queue`: two sendCommand()\n // calls (or a slow one and a disconnect()) shouldn't head-of-line\n // block each other when the binding correlates replies independently.\n const reply = await this.withReaderAccess(async () => {\n const client = await this.getOrCreateClient();\n\n return client.sendCommand(command, extracted.data, extracted.uploads);\n });\n\n return reply ?? undefined;\n } catch (cause) {\n this.emitError(cause);\n return undefined;\n }\n }\n\n /**\n * Handles `sendCommand(command, data, \"runtime\")` — this SDK has no\n * generic runtime-scope channel. `reactor-core`'s `send_command` is a\n * single channel; `requestSchema`/clip requests/heartbeat are each their\n * own dedicated RPC instead of a scoped envelope, so there's nothing\n * generic to route a scope through at the wire level.\n *\n * `requestSchema` and `requestCapabilities` route to their direct\n * equivalents below, neither of which returns a `ReactorMessage` the way a\n * normal `sendCommand()` reply would, so both resolve `undefined`; the\n * actual data surfaces through `getSchema()`/`schemaReceived` and\n * `getCapabilities()`/`capabilitiesReceived` as it already does. Anything\n * else has no runtime-scope destination to route to — rather than silently\n * doing nothing, it falls through as a normal application-scope send, with\n * a console warning.\n */\n private async sendRuntimeScopedCommand(\n command: string,\n data?: object,\n ): Promise<ReactorMessage | undefined> {\n switch (command) {\n case 'requestSchema':\n try {\n // Same exclusion as `sendCommand()` above.\n await this.withReaderAccess(async () => {\n const client = await this.getOrCreateClient();\n\n await this.refreshSchema(client);\n });\n } catch (cause) {\n // refreshSchema() reports failures itself when it has a client to\n // key the race guard on; getOrCreateClient() failing before that\n // doesn't, so report it here. Either way, sendCommand's own\n // contract never rejects.\n this.emitError(cause);\n }\n return undefined;\n case 'requestCapabilities':\n // No dedicated \"request\" exists — reactor-core pushes capabilities\n // once negotiated, so getCapabilities()/capabilitiesReceived already\n // reflect the latest value with nothing left to trigger here.\n return undefined;\n default:\n console.warn(\n `[Reactor] sendCommand(${JSON.stringify(command)}, …, \"runtime\") has no runtime-scope destination in this SDK — sending as a normal application-scope command instead.`,\n );\n return this.sendCommand(command, data);\n }\n }\n\n /** Requests the model's command schema directly. Most callers don't need\n * this — it's already fetched once and cached as soon as the session\n * reaches `\"ready\"`; use `getSchema()` for that. Resolves `undefined`\n * when the model doesn't expose a schema — the binding replies with a\n * wire `null` in that case rather than omitting the field. */\n async requestSchema(): Promise<ModelSchema | undefined> {\n this.assertNotDisposed();\n try {\n // Excluded from connect()/disconnect()/reconnect() — see\n // `withReaderAccess()`'s docs.\n return await this.withReaderAccess(async () => {\n const client = await this.getOrCreateClient();\n\n return this.normalizeSchema(await client.requestSchema());\n });\n } catch (cause) {\n throw this.captureError(cause);\n }\n }\n\n /** The model's command schema (an OpenAPI document), cached from the\n * `requestSchema()` call fired automatically on `\"ready\"`. `undefined`\n * until that reply has landed. */\n getSchema(): ModelSchema | undefined {\n return this.schema;\n }\n\n /** The runtime's declared capabilities (negotiated tracks, and the\n * command set when the model exposes one) — pushed once available, no\n * explicit request needed. `undefined` until `capabilitiesReceived`\n * fires. */\n getCapabilities(): Capabilities | undefined {\n return this.capabilities;\n }\n\n /** The session resource, as the coordinator reports it — id, state,\n * model, cluster, server info, and (once negotiated) `capabilities`.\n * A live read straight off the wasm client, not cached — reflects\n * whatever's current. `undefined` before a client exists. */\n getSessionInfo(): SessionResponse | undefined {\n return this.client?.sessionInfo();\n }\n\n // ── Tracks ──────────────────────────────────────────────────────────────\n\n /**\n * Publishes a local `MediaStreamTrack` under `name` — the counterpart to a\n * `sendonly` track the model declares. Awaitable. Queued behind\n * connect()/disconnect()/reconnect() (unlike `sendCommand()`): a track\n * operation awaits its own control round-trip, and a concurrent\n * disconnect() freeing the wasm client mid-await would otherwise resume\n * into a freed client — the same class of use-after-free `queue` exists to\n * prevent for connect/disconnect/reconnect themselves.\n *\n * Resolves with a `PublishedTrack` handle whose `pushFrame()` feeds the\n * track in a stepped session.\n *\n * In a `generation: \"stepped\"` session, input frames never travel over\n * RTP: `track` is optional, and the frames are pushed with\n * `published.pushFrame(...)` for the next `step()`. A `MediaStreamTrack`\n * passed there is ignored, with a console warning — nothing is sent from\n * it. In a streamed session `track` is required, and omitting it rejects\n * with an `InvalidStateError`.\n *\n * ```ts\n * const camera = await reactor.publishTrack('camera');\n * await camera.pushFrame(imageData);\n * const result = await reactor.step();\n * ```\n */\n async publishTrack(name: string, track?: MediaStreamTrack): Promise<PublishedTrack> {\n this.assertNotDisposed();\n try {\n let media = track;\n\n if (this.isStepped() && media !== undefined) {\n console.warn(\n `[Reactor] publishTrack('${name}'): ignoring the MediaStreamTrack — a stepped session ` +\n 'sends no RTP and takes frames through track.pushFrame(...) on the track publishTrack() returns.',\n );\n media = undefined;\n }\n if (!this.isStepped() && media === undefined) {\n throw new InvalidStateError(\n `publishTrack('${name}') needs a MediaStreamTrack in a streamed session.`,\n { operation: 'publishTrack' },\n );\n }\n const publication = (this.publications += 1);\n\n await this.queue.push(async () => {\n const client = await this.getOrCreateClient();\n\n await client.publishTrack(name, media);\n this.publishedInputs.set(name, publication);\n }, 'publishTrack');\n\n return {\n name,\n pushFrame: (frame, options) => this.pushTo(name, publication, frame, options),\n pushEncodedFrame: (frame) => this.pushEncodedTo(name, publication, frame),\n };\n } catch (cause) {\n throw this.captureError(cause);\n }\n }\n\n /**\n * Unlike every other track method, this doesn't reject — a failure is\n * reported through the `error` event instead, since this is commonly the\n * last call in a `finally` block, and raising there would replace\n * whatever exception was already propagating.\n */\n async unpublishTrack(name: string): Promise<void> {\n this.assertNotDisposed();\n try {\n await this.queue.push(async () => {\n const client = await this.getOrCreateClient();\n\n await client.unpublishTrack(name);\n this.publishedInputs.delete(name);\n }, 'unpublishTrack');\n } catch (cause) {\n this.emitError(cause);\n }\n }\n\n /**\n * Stops a received track: the receiver goes inactive and the runtime stops\n * producing it. Awaitable, and queued behind connect()/disconnect()/\n * reconnect() for the same reason as `publishTrack()`.\n */\n async pauseTrack(name: string): Promise<void> {\n this.assertNotDisposed();\n try {\n await this.queue.push(async () => {\n const client = await this.getOrCreateClient();\n\n await client.pauseTrack(name);\n }, 'pauseTrack');\n } catch (cause) {\n throw this.captureError(cause);\n }\n }\n\n /**\n * Bounds what one sender may spend, in bits per second.\n *\n * This is the ceiling that actually caps a video encoder, and it is easy to\n * hit without knowing it exists: with nothing set, a Chromium-based browser\n * derives a sender's maximum from the frame size alone, and that maximum is\n * 2500 kbps for anything above 960x540. A 720p or 1080p publish caps at\n * 2.5 Mbps until this raises it, however good the connection is.\n *\n * ```ts\n * await reactor.publishTrack('camera', cameraTrack);\n * await reactor.setTrackBitrate('camera', { maxBps: 8_000_000 });\n * ```\n *\n * A ceiling is permission, not a target: the encoder still spends only what\n * the congestion controller allocated and what the picture needs. What\n * raising it buys is headroom for the moments that would otherwise clip.\n *\n * Needs a connected client, and a published track — there is no sender to\n * bound before `publishTrack()`.\n *\n * Omit a bound to leave it at the browser default. `minBps` is non-standard —\n * Chromium honours it, other engines ignore it.\n *\n * There is no connection-wide counterpart: browsers expose no equivalent of\n * the native SDKs' `setBitrate`, and a method that quietly did nothing would\n * be worse than its absence.\n */\n async setTrackBitrate(\n name: string,\n bounds: { minBps?: number; maxBps?: number } = {},\n ): Promise<void> {\n this.assertNotDisposed();\n try {\n await this.queue.push(async () => {\n const client = await this.getOrCreateClient();\n\n await client.setTrackBitrate(name, bounds.minBps, bounds.maxBps);\n }, 'setTrackBitrate');\n } catch (cause) {\n throw this.captureError(cause);\n }\n }\n\n /** Resumes a track previously stopped with `pauseTrack()`. */\n async resumeTrack(name: string): Promise<void> {\n this.assertNotDisposed();\n try {\n await this.queue.push(async () => {\n const client = await this.getOrCreateClient();\n\n await client.resumeTrack(name);\n }, 'resumeTrack');\n } catch (cause) {\n throw this.captureError(cause);\n }\n }\n\n // ── Stepped generation ──────────────────────────────────────────────────\n\n /**\n * Runs one step of a `generation: \"stepped\"` session and resolves with\n * what it produced, per output track.\n *\n * The request carries `state`, `commands` and every frame pushed since the\n * previous step. The runtime applies them in that order — each `state` key\n * as the model's `set_<key>` command, then `commands`, then the frames —\n * and then generates. They are separate calls, not a transaction: one that\n * fails does not undo the ones before it. All of it is optional:\n * `step()` with nothing set and nothing pushed runs on the model's current\n * state, which commands sent outside a step (`sendCommand()`) also change.\n * A file goes in the way it does for a command: upload it with\n * `uploadFile()`, then put the `FileRef` in a command's `data` or a state\n * value.\n *\n * A step that ran but that the model reported as failed still resolves,\n * with `result.error` set. `result.files` lists the files the model kept\n * with the step (name, content type, size); their bytes are served over\n * HTTP from the session's step results, not carried here.\n *\n * Rejects with a `StepRefusedError` when the runtime or the model turns\n * the step down (the runtime checks a whole request first, so nothing it\n * carried was applied), `StepNotReadyError` when the session cannot take a\n * step yet (neither ran the step), `StepCommandFailedError` when a state key\n * or command failed (the calls before it stay applied; the step did not\n * run); both name the part at fault in `entry`, and `StepCommandFailedError`\n * the handler's code in `command_code`,\n * `StepSessionEndedError` when the session ended before the result came\n * back, `StepResultTooLargeError` when the result does not fit in one\n * message, `MessageTooLargeError` when the request itself is too large\n * (nothing was sent), `InvalidStateError` outside a ready stepped\n * session, or whatever else failed the step (`DisconnectedError`,\n * `RequestTimeoutError`, ...). The frames pushed for a step belong to it:\n * when its request cannot be sent, they are dropped with it rather than\n * kept for the next step.\n *\n * `media` gives the step frames of its own, by input track name, pushed\n * after the ones already pushed to that track: what `pushFrame()` takes,\n * or an `EncodedFrame` — H.264 the runtime decodes before the step runs,\n * so the model reads RGB frames as for a raw push. They are pushed only\n * once `state` and `commands` are well formed and the session is ready, so\n * a step refused for those leaves the frames buffered as they were. They go\n * all or nothing: a bad track or frame anywhere in `media` rejects the step\n * before any of it is pushed or sent, leaving the buffer as it was. A\n * session that leaves 'ready' once the media is in has the step refused and\n * keeps the frames for the next one, as pushed frames are.\n * A track's encoded frames of one step go in decode order, starting at a\n * keyframe; a step whose frames do not decode rejects with a\n * `StepRefusedError`.\n *\n * ```ts\n * const camera = await reactor.publishTrack('camera');\n * await camera.pushFrame(imageData);\n * const result = await reactor.step({ state: { prompt: 'a cat' } });\n * if (result.error) console.warn('step failed:', result.error);\n * const frame = result.tracks.find((t) => t.track === 'main_video')?.frames[0];\n * if (frame) ctx.putImageData(stepFrameToImageData(frame), 0, 0);\n * ```\n */\n async step(options: StepOptions = {}): Promise<StepResult> {\n this.assertNotDisposed();\n try {\n // A step has no uploads map: a FileRef rides inline, in its wire shape.\n // The rest goes to the binding as given, for it to check.\n const state = rewriteNestedFileRefs(options.state ?? null);\n const commands = rewriteNestedFileRefs(options.commands ?? []);\n\n // Every push called before this step; it never rejects.\n const previous = this.pendingPushes;\n // Pushed only once the binding would take the state and commands, so a\n // step refused for those leaves the buffer as the caller left it.\n const before =\n options.media !== undefined ? this.pushStepMedia(options.media, state, commands) : previous;\n // This step's place in line, taken now, before a later push or step can\n // queue ahead of it: it goes once its media and every push called before\n // it are in. A push called after it waits only until the step has taken\n // the buffer, not for its result.\n let taken!: () => void;\n const bufferTaken = new Promise<void>((resolve) => {\n taken = resolve;\n });\n const stepping = before.then(() =>\n // Excluded from connect()/disconnect()/reconnect() like sendCommand():\n // a step can take minutes, and must neither be freed out from under\n // nor block unrelated reads.\n this.withReaderAccess(async () => {\n const client = await this.getOrCreateClient();\n\n try {\n return client.step(state, commands);\n } finally {\n // The binding has taken the buffer by the time step() returns (or\n // throws), so a push queued behind this goes to the next step.\n taken();\n }\n }),\n );\n\n // Refused before it reached the binding, the step lets the line move on,\n // but only once every push called before it is in: media refused before\n // it joined the line must not let a later step overtake those pushes.\n stepping.catch(() => previous.then(taken));\n this.pendingPushes = bufferTaken;\n return await stepping;\n } catch (cause) {\n throw this.captureError(cause);\n }\n }\n\n /**\n * Buffers one input frame for the next `step()` on the sendonly track\n * `trackName`. Nothing is sent until that step, which carries every frame\n * pushed since the one before it, per track in push order. The\n * `PublishedTrack` that `publishTrack()` resolves with does the same\n * through `track.pushFrame(frame)`.\n *\n * Video: a `VideoFrame` (cloned when called, so the caller may close it as\n * soon as this returns; it stays the caller's), an\n * `ImageData`, or `{ data, width, height, format? }` raw pixels (`\"rgba\"`\n * by default, or `\"rgb\"`/`\"bgra\"`). Sent to the model as RGB. A\n * `VideoFrame` is sent as it is displayed: its `rotation` and `flip` are\n * applied, so a 90° frame arrives with its width and height swapped.\n * Audio: `{ samples, sampleRate, channels? }`, interleaved `Int16Array`\n * PCM at the rate the model's track declares.\n *\n * Pushes keep their call order, and a `step()` waits for every push called\n * before it. A refused push rejects: await it, or `.catch()` it in a frame\n * loop, or every bad frame is an unhandled rejection. What waits for\n * the next step is at most one message's worth of frames: pushing faster\n * than steps run drops the oldest frames, across tracks. Rejects with\n * an `InvalidStateError` outside a stepped session, for a track not\n * published on this connection (`publishTrack(trackName)` first), for a\n * frame whose size does not match its dimensions, or for a name the model\n * does not declare as a sendonly track of that kind.\n */\n async pushFrame(trackName: string, frame: PushFrame, options: PushFrameOptions = {}): Promise<void> {\n return this.pushTo(trackName, undefined, frame, options);\n }\n\n /** `pushFrame()`, for the track's current publication or, from a\n * `PublishedTrack`, only for the `publication` it came from. */\n private async pushTo(\n trackName: string,\n publication: number | undefined,\n frame: PushFrame,\n options: PushFrameOptions = {},\n ): Promise<void> {\n this.assertNotDisposed();\n const epoch = this.connectionEpoch;\n let held: ReturnType<typeof holdFrame>;\n\n try {\n held = holdFrame(frame);\n } catch (cause) {\n throw this.captureError(cause);\n }\n const push = this.pendingPushes.then(async () => {\n let pixels;\n\n try {\n if (!this.isStepped()) {\n throw new InvalidStateError(\n `pushFrame('${trackName}') needs a session created with generation: \"stepped\"; ` +\n 'a streamed session sends media from a MediaStreamTrack given to publishTrack().',\n { operation: 'pushFrame' },\n );\n }\n pixels = isAudioFrame(held.frame) ? undefined : await toPixels(held.frame);\n } finally {\n held.release();\n }\n\n // Read access, like step(): a disconnect() must not free the client\n // between resolving it and the (synchronous) push into it.\n await this.withReaderAccess(async () => {\n this.checkPushTarget('pushFrame', trackName, publication, epoch);\n const client = await this.getOrCreateClient();\n\n if (pixels) {\n client.pushVideoFrame(\n trackName,\n pixels.data,\n pixels.width,\n pixels.height,\n pixels.format,\n options.metadata ?? null,\n options.captureTimeUs ?? null,\n );\n } else if (isAudioFrame(frame)) {\n client.pushAudioFrame(trackName, frame.samples, frame.sampleRate, frame.channels ?? 1);\n }\n });\n });\n\n this.pendingPushes = push.catch(() => undefined);\n try {\n await push;\n } catch (cause) {\n throw this.captureError(cause);\n }\n }\n\n /**\n * Buffers one encoded video frame for the next `step()` on the sendonly\n * video track `trackName`, its bytes as they are: one H.264 access unit\n * (Annex B), with the `width` and `height` it decodes to. The\n * `PublishedTrack` that `publishTrack()` resolves with does the same\n * through `track.pushEncodedFrame(frame)`.\n *\n * The runtime decodes a track's encoded frames of one step as one stream,\n * before the step runs, and the model reads the RGB frames as if they had\n * been pushed raw. So push them in decode order, starting at a keyframe; a\n * step whose frames do not decode rejects with a `StepRefusedError`, as\n * does a runtime that predates encoded frames. Encoded and raw pushes keep\n * their call order, and a `step()` waits for every push called before it.\n *\n * ```ts\n * const encoder = new VideoEncoder({\n * output: (chunk) => void camera.pushEncodedFrame({ codec: 'h264', data: chunk, width, height }),\n * error: console.error,\n * });\n * encoder.configure({ codec: 'avc1.42001f', width, height, avc: { format: 'annexb' } });\n * ```\n *\n * Rejects with an `InvalidStateError` outside a stepped session, for a\n * track not published on this connection, for an audio or recvonly track,\n * for empty data, a zero dimension or a codec other than `\"h264\"`.\n */\n async pushEncodedFrame(trackName: string, frame: EncodedFrame): Promise<void> {\n return this.pushEncodedTo(trackName, undefined, frame);\n }\n\n /** `pushEncodedFrame()`, for the track's current publication or, from a\n * `PublishedTrack`, only for the `publication` it came from. */\n private async pushEncodedTo(\n trackName: string,\n publication: number | undefined,\n frame: EncodedFrame,\n ): Promise<void> {\n const operation = 'pushEncodedFrame';\n\n this.assertNotDisposed();\n const epoch = this.connectionEpoch;\n let encoded: ReturnType<typeof toEncodedBytes>;\n\n try {\n // Read now: a chunk is copied, its extras taken, and a malformed frame\n // refused, at call time.\n encoded = toEncodedBytes(frame, operation, trackName);\n } catch (cause) {\n throw this.captureError(cause);\n }\n const push = this.pendingPushes.then(() =>\n this.withReaderAccess(async () => {\n if (!this.isStepped()) {\n throw new InvalidStateError(\n `${operation}('${trackName}') needs a session created with generation: \"stepped\"; ` +\n 'a streamed session sends media from a MediaStreamTrack given to publishTrack().',\n { operation },\n );\n }\n this.checkPushTarget(operation, trackName, publication, epoch);\n const client = await this.getOrCreateClient();\n const declared = client.tracks().find((track) => track.name === trackName);\n\n if (declared && (declared.kind !== 'video' || declared.direction !== 'sendonly')) {\n throw new InvalidStateError(\n `${operation}('${trackName}'): '${trackName}' is a ${declared.direction} ${declared.kind} track; ` +\n 'only a sendonly video track takes encoded frames.',\n { operation },\n );\n }\n client.pushEncodedVideoFrame(\n trackName,\n encoded.codec,\n encoded.data,\n encoded.width,\n encoded.height,\n encoded.metadata,\n encoded.captureTimeUs,\n );\n }),\n );\n\n this.pendingPushes = push.catch(() => undefined);\n try {\n await push;\n } catch (cause) {\n throw this.captureError(cause);\n }\n }\n\n /** Refuses a push whose connection ended since it was called, or whose\n * track is not (or no longer) published on it. */\n private checkPushTarget(\n operation: string,\n trackName: string,\n publication: number | undefined,\n epoch: number,\n ): void {\n if (epoch !== this.connectionEpoch) {\n throw new InvalidStateError(\n `${operation}('${trackName}'): the connection it was pushed to ended while its frame was read`,\n { operation },\n );\n }\n const current = this.publishedInputs.get(trackName);\n\n if (current === undefined || (publication !== undefined && publication !== current)) {\n throw new InvalidStateError(\n publication === undefined\n ? `${operation}('${trackName}') needs publishTrack('${trackName}') first.`\n : `${operation}('${trackName}'): this track was unpublished, or its connection ended.`,\n { operation },\n );\n }\n }\n\n /** Pushes `step()`'s `media`, track by track and in order, each frame as\n * `pushFrame()` or `pushEncodedFrame()` would. All or nothing: the binding\n * checks the step's `state` and `commands`, then every frame, before the\n * first is pushed, so a refused step, or a bad track or frame anywhere,\n * leaves the buffer as it was. */\n private async pushStepMedia(\n media: NonNullable<StepOptions['media']>,\n state: StepOptions['state'] | null,\n commands: NonNullable<StepOptions['commands']>,\n ): Promise<void> {\n const epoch = this.connectionEpoch;\n // Read now, as a single push would.\n const held = holdStepMedia(media);\n const push = this.pendingPushes.then(async () => {\n const ready: ReadyStepFrame[] = [];\n\n try {\n for (const frame of held) {\n ready.push(await readStepFrame(frame));\n }\n } finally {\n for (const frame of held) {\n frame.release();\n }\n }\n\n await this.withReaderAccess(async () => {\n const client = await this.getOrCreateClient();\n\n // The step's own checks: a streamed session, one not 'ready', or a\n // malformed state or command, refused before any frame goes in. A\n // session leaving 'ready' after this still can take the media: then\n // the frames ride the next step.\n client.checkStep(state, commands);\n for (const frame of ready) {\n this.checkPushTarget(frame.operation, frame.track, undefined, epoch);\n checkStepFrame(client, frame);\n }\n // Every frame passed: only now does the first go into the buffer.\n for (const frame of ready) {\n if (frame.kind === 'encoded') {\n client.pushEncodedVideoFrame(\n frame.track,\n frame.encoded.codec,\n frame.encoded.data,\n frame.encoded.width,\n frame.encoded.height,\n frame.encoded.metadata,\n frame.encoded.captureTimeUs,\n );\n } else if (frame.kind === 'video') {\n const { data, width, height, format } = frame.pixels;\n\n client.pushVideoFrame(frame.track, data, width, height, format, null, null);\n } else {\n const { samples, sampleRate, channels } = frame.audio;\n\n client.pushAudioFrame(frame.track, samples, sampleRate, channels ?? 1);\n }\n }\n });\n });\n\n this.pendingPushes = push.catch(() => undefined);\n await push;\n }\n\n /** Drops every frame buffered for the next step, pushes called before it\n * included: it waits its turn behind them, as a `step()` does. */\n async clearStepInputs(): Promise<void> {\n this.assertNotDisposed();\n const clear = this.pendingPushes.then(() =>\n this.withReaderAccess(() => {\n this.client?.clearStepInputs();\n return Promise.resolve();\n }),\n );\n\n this.pendingPushes = clear.catch(() => undefined);\n try {\n await clear;\n } catch (cause) {\n throw this.captureError(cause);\n }\n }\n\n // ── Recording ───────────────────────────────────────────────────────────\n\n /**\n * Requests a clip covering the last `durationSeconds` of the session.\n * `reactor-core` correlates the reply itself (and enforces `\"ready\"`), so\n * this is a thin delegation, same as `requestSchema()`. See\n * `downloadClipAsFile()` to turn the result into a file.\n */\n async requestClip(durationSeconds: number): Promise<Clip> {\n this.assertNotDisposed();\n try {\n // Excluded from connect()/disconnect()/reconnect() — see\n // `withReaderAccess()`'s docs.\n return await this.withReaderAccess(async () => {\n const client = await this.getOrCreateClient();\n\n return toPublicClip(await client.requestClip(durationSeconds));\n });\n } catch (cause) {\n throw this.captureError(cause);\n }\n }\n\n /** Requests a clip covering the entire session up to now. See `requestClip()`. */\n async requestRecording(): Promise<Clip> {\n this.assertNotDisposed();\n try {\n // Excluded from connect()/disconnect()/reconnect() — see\n // `withReaderAccess()`'s docs.\n return await this.withReaderAccess(async () => {\n const client = await this.getOrCreateClient();\n\n return toPublicClip(await client.requestRecording());\n });\n } catch (cause) {\n throw this.captureError(cause);\n }\n }\n\n /** Thin delegation to the standalone `downloadClipAsFile()` — see its own doc comment. */\n async downloadClipAsFile(\n clip: Clip,\n filename: string | null = 'reactor-clip.mp4',\n options?: DownloadClipOptions,\n ): Promise<Blob> {\n return downloadClipAsFileFn(clip, filename, options);\n }\n\n // ── Uploads ─────────────────────────────────────────────────────────────\n\n /**\n * Uploads a file to the session's object store, resolving with a\n * `FileRef` to pass in a `sendCommand()`'s `data`, at the top level or\n * inside an array or object (see `extractFileRefs`). The binding itself\n * takes `(file, name?)`\n * positionally and already applies the right defaulting — a bare\n * `Blob`'s name falls back to `\"upload\"`, and an empty/missing mime type\n * to `\"application/octet-stream\"` — so there's nothing to wrap here.\n *\n * Queued behind connect()/disconnect()/reconnect(), same as the track\n * ops: this awaits its own round-trip, and a concurrent disconnect()\n * freeing the wasm client mid-upload would otherwise resume into a freed\n * client — the same use-after-free class of race the queue exists to\n * prevent.\n */\n async uploadFile(file: File | Blob, options?: { name?: string }): Promise<FileRef> {\n this.assertNotDisposed();\n try {\n const wireFileRef = await this.queue.push(async () => {\n const client = await this.getOrCreateClient();\n\n return client.uploadFile(file, options?.name);\n }, 'uploadFile');\n\n return toPublicFileRef(wireFileRef);\n } catch (cause) {\n throw this.captureError(cause);\n }\n }\n\n /** All tracks the model declared, whether or not media has arrived for —\n * or been published to — them yet. Empty before a client exists. */\n tracks(): TrackCapability[] {\n return this.client?.tracks() ?? [];\n }\n\n /** Same as `tracks()`, plus each entry's negotiated `mid` — the id\n * `trackReceived`'s `mid` argument and the `getXByMid` escape hatches key\n * on. Only populated once SDP negotiation has assigned mids. */\n trackMapping(): TrackMappingEntry[] {\n return this.client?.trackMapping() ?? [];\n }\n\n pausedTracks(): string[] {\n return this.client?.pausedTracks() ?? [];\n }\n\n // ── Escape hatches ──────────────────────────────────────────────────────\n\n /** Drops to the raw `RTCPeerConnection` for anything this class doesn't\n * wrap directly. `undefined` before a client exists. */\n getPeerConnection(): RTCPeerConnection | undefined {\n return this.client?.getPeerConnection();\n }\n\n getTrackByMid(mid: string): MediaStreamTrack | undefined {\n return this.client?.getTrackByMid(mid);\n }\n\n getStreamByMid(mid: string): MediaStream | undefined {\n return this.client?.getStreamByMid(mid);\n }\n\n getTrackByName(name: string): MediaStreamTrack | undefined {\n return this.client?.getTrackByName(name);\n }\n\n getStreamByName(name: string): MediaStream | undefined {\n return this.client?.getStreamByName(name);\n }\n\n /**\n * Supports `using reactor = new Reactor(...)`: releases the wasm resource\n * graph and drops every registered event handler for good. Unlike a plain\n * `disconnect()`, this instance is unusable afterward — construct a new\n * `Reactor` instead of trying to `connect()` again.\n */\n [Symbol.dispose](): void {\n if (this.disposed) {\n return;\n }\n this.disposed = true;\n const client = this.client;\n\n this.client = undefined;\n this.clientPromise = undefined;\n this.schema = undefined;\n this.capabilities = undefined;\n this.resetConnectionState();\n this.emitter.clear();\n if (client) {\n // Queued behind any in-flight connect()/reconnect()/disconnect(), same\n // as freeClient() — this can't await that itself, since [Symbol.dispose]\n // is synchronous per the `using` contract. Also excluded from any read\n // still in flight, same as freeClient() — see `withWriterAccess()`.\n void this.queue\n .push(() => this.withWriterAccess(() => Promise.resolve(client.free())), 'dispose')\n .catch(() => {});\n }\n }\n\n // ── Introspection ───────────────────────────────────────────────────────\n\n /** The wasm binding's own terser `status()` name can be added alongside\n * this later if it turns out to be worth it. */\n getStatus(): ReactorStatus {\n return this.client?.status() ?? 'disconnected';\n }\n\n /** See `getStatus()`. */\n getSessionId(): string | undefined {\n return this.client?.sessionId();\n }\n\n /** The `jwt` this instance was constructed (or last `connect()`ed) with —\n * lets a component composed inside a `ReactorProvider` (e.g. `ClipPlayer`)\n * authenticate its own requests without the caller repeating the resolver. */\n getJwtResolver(): JwtSource | undefined {\n return this.jwt ?? undefined;\n }\n\n /** The most recent `ReactorError`, from either an `error` event or a\n * rejected call — whichever landed last. `undefined` until the first\n * failure. */\n getLastError(): ReactorError | undefined {\n return this._lastError;\n }\n\n /** The most recent WebRTC connection stats, polled every `LOCAL_STATS_INTERVAL_MS`\n * while \"ready\" — see `statsUpdate`. `undefined` before the first sample. */\n getStats(): ConnectionStats | undefined {\n return this.stats;\n }\n\n /** Timing breakdown from the most recent `connect()`/`reconnect()`\n * handshake — see `ConnectionTimings`. */\n getConnectionTimings(): ConnectionTimings | undefined {\n return this.connectionTimings;\n }\n\n // ── Events ──────────────────────────────────────────────────────────────\n\n on<Name extends keyof ReactorEventMap>(event: Name, handler: ReactorEventMap[Name]): void {\n this.emitter.on(event, handler);\n }\n\n off<Name extends keyof ReactorEventMap>(event: Name, handler: ReactorEventMap[Name]): void {\n this.emitter.off(event, handler);\n }\n\n once<Name extends keyof ReactorEventMap>(event: Name, handler: ReactorEventMap[Name]): void {\n this.emitter.once(event, handler);\n }\n\n // ── Internal ────────────────────────────────────────────────────────────\n\n private getOrCreateClient(): Promise<ReactorClient> {\n if (!this.clientPromise) {\n this.clientPromise = this.createClient().catch((cause) => {\n // A failed first connect shouldn't wedge every later attempt behind\n // a client that never came up.\n this.clientPromise = undefined;\n throw cause;\n });\n }\n return this.clientPromise;\n }\n\n private async createClient(): Promise<ReactorClient> {\n const { ReactorClient: WasmReactorClient } = await loadReactorWasm();\n\n // [Symbol.dispose] may have run while the wasm module was loading above;\n // bail out before constructing a client that would otherwise outlive it\n // and never get freed.\n if (this.disposed) {\n throw new Error('Reactor was disposed while connecting.');\n }\n const client = new WasmReactorClient(this.clientOptions, this.jwt);\n\n client.onStatusChanged((status) => {\n this.emitter.emit('statusChanged', status);\n this.handleStatusChanged(client, status);\n });\n client.onSessionIdChanged((sessionId) => this.emitter.emit('sessionIdChanged', sessionId));\n client.onError((error) => this.emitError(error));\n // DATA channel — the model's own application traffic.\n client.onMessage((message) => {\n debugLog('[Reactor] message:', message);\n this.emitter.emit('message', message);\n });\n // CONTROL channel — platform traffic (moderation, clip/recording lifecycle).\n client.onRuntimeMessage((message) => {\n debugLog('[Reactor] runtimeMessage:', message);\n this.emitter.emit('runtimeMessage', message);\n });\n client.onCapabilitiesReceived((capabilities) => {\n this.capabilities = toPublicCapabilities(capabilities);\n this.emitter.emit('capabilitiesReceived', this.capabilities);\n });\n client.onTrackReceived((name, mid) => {\n const track = client.getTrackByName(name);\n const stream = client.getStreamByName(name);\n\n // Structurally shouldn't happen — `reactor-core` only dispatches this\n // event once the track is already resolvable — but if it ever does\n // (e.g. a teardown racing the dispatch), skip rather than emitting a\n // lie about the (non-optional) type.\n if (!track || !stream) {\n return;\n }\n this.emitter.emit('trackReceived', name, track, stream, mid);\n });\n this.client = client;\n return client;\n }\n\n /** Fired once per `\"ready\"` transition — see `getSchema()`. `getSchema()`\n * isn't guaranteed populated by the time a `statusChanged` \"ready\" handler\n * runs (this fetch is async and dispatched separately), so callers that\n * need the schema as soon as it lands should listen for `schemaReceived`\n * instead of reading `getSchema()` synchronously off `statusChanged`.\n *\n * Guards against a stale reply: if `disconnect()`/a later `connect()`\n * replaces `client` before this resolves, or a newer `refreshSchema()`\n * call for the same client wins the race, the result is discarded rather\n * than clobbering `this.schema` (or emitting `schema`) with old data.\n *\n * A rejection here (e.g. the session drops mid-request) surfaces like any\n * other binding failure, through the same `error` event as `onError`. */\n private async refreshSchema(client: ReactorClient): Promise<void> {\n const refreshId = ++this.schemaRefreshId;\n\n try {\n const schema = this.normalizeSchema(await client.requestSchema());\n\n if (this.client !== client || refreshId !== this.schemaRefreshId) {\n return;\n }\n // No schema for this model (wire `null`): leave the cache/event alone\n // rather than surfacing an empty document.\n if (schema === undefined) {\n return;\n }\n this.schema = schema;\n this.emitter.emit('schemaReceived', this.schema);\n // Also surface as a generic runtime-scope message so consumers that\n // filter `runtimeMessage` by `type` (rather than the typed event) see\n // it too — the same reply, two shapes, emitted from the same `schema`\n // value in the same tick, so they can't disagree here. `schemaReceived`\n // /`getSchema()` is the authoritative surface; `runtimeMessage` is the\n // generic fan-out kept for parity with v2 (`core/Reactor.ts`), which\n // does the same dual emit from the same `requestSchema` reply.\n this.emitter.emit('runtimeMessage', { type: 'modelSchema', data: this.schema });\n } catch (cause) {\n if (this.client !== client || refreshId !== this.schemaRefreshId) {\n return;\n }\n this.emitError(cause);\n }\n }\n\n /** The binding replies with a wire `null` (not an omitted field) when the\n * model doesn't expose a schema — normalized to `undefined` so callers\n * get the same \"no schema\" sentinel `getSchema()` already uses instead\n * of a document they could otherwise dereference. */\n private normalizeSchema(schema: unknown): ModelSchema | undefined {\n return (schema ?? undefined) as ModelSchema | undefined;\n }\n\n /** Frees the wasm resource graph, if one exists, and clears the cached\n * schema. Reusable — unlike `[Symbol.dispose]`, this doesn't set the\n * permanent `disposed` flag, so a later `connect()`/`reconnect()` lazily\n * builds a fresh client.\n *\n * Only called from within `disconnect()`'s queued task, so `client.free()`\n * is safe to call directly here — the queue already guarantees no other\n * operation is running concurrently against it. */\n private freeClient(): void {\n this.client?.free();\n this.client = undefined;\n this.clientPromise = undefined;\n this.schema = undefined;\n this.capabilities = undefined;\n }\n\n /** Tracks `connectionTimings` off the binding's own \"connecting\" → \"waiting\"\n * → \"ready\" status sequence (see `ReactorStatus`), and starts/stops stats\n * polling around the \"ready\" window. */\n private handleStatusChanged(client: ReactorClient, status: ReactorStatus): void {\n switch (status) {\n case 'connecting':\n this.connectStartTime = performance.now();\n this.waitingStartTime = undefined;\n break;\n case 'waiting':\n this.waitingStartTime = performance.now();\n break;\n case 'ready': {\n const readyTime = performance.now();\n\n if (this.connectStartTime != null) {\n const waitingStartTime = this.waitingStartTime ?? readyTime;\n\n this.connectionTimings = {\n sessionCreationMs: waitingStartTime - this.connectStartTime,\n transportConnectingMs: readyTime - waitingStartTime,\n totalMs: readyTime - this.connectStartTime,\n };\n }\n this.startStatsPolling(client);\n void this.refreshSchema(client);\n break;\n }\n default:\n this.stopStatsPolling();\n }\n }\n\n /** Starts both stats pollers: the local one updates `getStats()` and emits\n * `statsUpdate`, the runtime one sends a client-stats batch. Each owns the\n * extractor it computes bitrates with, so a bitrate covers its own\n * poller's interval. */\n private startStatsPolling(client: ReactorClient): void {\n this.stopStatsPolling();\n const extractConnectionStats = createConnectionStatsExtractor();\n const extractTrackStats = createTrackStatsExtractor();\n\n this.hasSentConnectTime = false;\n this.hasSentClientStats = false;\n this.stopStatsPollers = [\n pollPeerStats(client, LOCAL_STATS_INTERVAL_MS, (report) => {\n this.stats = { ...extractConnectionStats(report), connectionTimings: this.connectionTimings };\n this.emitter.emit('statsUpdate', this.stats);\n }),\n pollPeerStats(client, RUNTIME_REPORT_INTERVAL_MS, (report) => {\n this.reportClientStats(client, report, extractTrackStats);\n }),\n ];\n }\n\n /** Report one quality batch to the runtime: a reading per negotiated\n * track — audio and video, sent and received — see\n * `createTrackStatsExtractor`, and the connection-wide reading — see\n * `toClientConnectionStat`. The connection reading goes even while no\n * track has one yet (none negotiated onto a named track, or no codec\n * reported yet), so the runtime gets the bandwidth estimate, the\n * round-trip time and the time to connect without waiting on the tracks.\n * Skipped only when there is nothing at all to say and a batch has already\n * gone out for this connection, so the first one still carries the\n * environment; one is due again in `RUNTIME_REPORT_INTERVAL_MS`. The time to connect goes on the first batch\n * actually sent for this connection — see `hasSentConnectTime`.\n * `sendClientStats` throws synchronously on a closing connection; caught\n * here for the same reason `getStats()`'s rejection is above. */\n private reportClientStats(\n client: ReactorClient,\n report: RTCStatsReport,\n extractTrackStats: TrackStatsExtractor,\n ): void {\n const trackStats = extractTrackStats(report, this.trackMapping(), this.pausedTracks());\n const timeToConnectMs = this.hasSentConnectTime ? undefined : this.connectionTimings?.totalMs;\n const connectionStat = toClientConnectionStat(report, timeToConnectMs);\n\n if (this.hasSentClientStats && trackStats.length === 0 && Object.keys(connectionStat.metrics).length === 0) {\n return;\n }\n\n try {\n client.sendClientStats(trackStats, connectionStat);\n extractTrackStats.commit();\n this.hasSentClientStats = true;\n if (timeToConnectMs !== undefined) {\n this.hasSentConnectTime = true;\n }\n } catch {\n // Connection may be closing.\n }\n }\n\n private stopStatsPolling(): void {\n for (const stop of this.stopStatsPollers) {\n stop();\n }\n this.stopStatsPollers = [];\n this.stats = undefined;\n }\n\n /** Called on every `disconnect()` and on `[Symbol.dispose]`. Leaves\n * `client`/`schema` alone — that's `freeClient()`'s job, run separately\n * when `disconnect()` isn't recoverable. `capabilities` is cleared here\n * regardless, though: unlike the schema, it isn't re-fetched on demand,\n * so a recoverable disconnect that skips `freeClient()` would otherwise\n * leave `getCapabilities()` returning the previous session's stale\n * tracks/commands until a new `capabilitiesReceived` lands. */\n private resetConnectionState(): void {\n this.connectionEpoch += 1;\n this.publishedInputs.clear();\n this.stopStatsPolling();\n this.connectionTimings = undefined;\n this.connectStartTime = undefined;\n this.waitingStartTime = undefined;\n this.capabilities = undefined;\n }\n\n /** Wraps `cause` and records it as the most recent failure, for a call\n * that's about to throw rather than emit — see `getLastError()`'s doc\n * comment. */\n private captureError(cause: unknown): ReactorError {\n const error = toReactorError(cause);\n\n this._lastError = error;\n return error;\n }\n\n /** Wraps `cause`, records it as the most recent failure, and fires the\n * `error` event — the one place recording and emitting happen together,\n * so `getLastError()` never drifts from what listeners were told. */\n private emitError(cause: unknown): void {\n this.emitter.emit('error', this.captureError(cause));\n }\n\n private isStepped(): boolean {\n return this.clientOptions.generation === 'stepped';\n }\n\n private assertNotDisposed(): void {\n if (this.disposed) {\n throw new Error(\"This Reactor was disposed and can't be used again — construct a new one.\");\n }\n }\n}\n","import type { Capabilities } from '../types';\nimport type { Capabilities as WireCapabilities } from './reactor-wasm.types';\n\n/** The wasm binding's snake_case wire shape → the public, camelCase one —\n * what `Reactor.getCapabilities()`/`capabilitiesReceived` hand back to a\n * caller. */\nexport function toPublicCapabilities(wire: WireCapabilities): Capabilities {\n const capabilities: Capabilities = {\n protocolVersion: wire.protocol_version,\n tracks: wire.tracks,\n };\n\n if (wire.commands !== undefined) {\n capabilities.commands = wire.commands;\n }\n if (wire.emission_fps !== undefined) {\n capabilities.emissionFps = wire.emission_fps;\n }\n return capabilities;\n}\n","declare const process: { env?: { NODE_ENV?: string } } | undefined;\ndeclare global {\n interface ImportMeta {\n readonly env?: { readonly DEV?: boolean };\n }\n}\n\n// No single check covers every bundler actually used with this SDK: webpack\n// and Next.js globally replace `process.env.NODE_ENV` (including inside\n// dependencies), even though no real `process` global exists in the browser\n// at runtime — but Vite does not, by default, do that same replacement for a\n// dependency's `process.env.NODE_ENV` (verified: it survives, unreplaced,\n// into a Vite production bundle, where `typeof process` is then genuinely\n// `'undefined'` at runtime — silently always off). Vite instead exposes its\n// own `import.meta.env.DEV`, real at runtime, for every module it processes,\n// dependencies included. Checking both covers both; neither reference\n// throws where the other bundler's mechanism is the one in play.\nconst isDev =\n (typeof process !== 'undefined' && process?.env?.NODE_ENV === 'development') ||\n import.meta.env?.DEV === true;\n\n/** Logs wire traffic (data/control channel messages) in development builds\n * only — useful while iterating against a model, silent in production. */\nexport function debugLog(...args: unknown[]): void {\n if (isDev) {\n console.debug(...args);\n }\n}\n","/**\n * Every Reactor failure carries `code`, `recoverable`, `status`, `operation`,\n * `retry_after_ms` and `timestamp_ms` — `reactor-core`'s canonical shape,\n * shared by every SDK on it. `timestamp`/`retryAfter` are kept alongside\n * under their previous names for compatibility — see their own doc comments\n * below — rather than dropped, since this package's public API may only\n * grow.\n *\n * There is **one class**, not two: the `error` event payload and a rejected\n * call's error are the same shape and the same instance type.\n *\n * `ReactorError` is the base of a typed hierarchy keyed by `code` —\n * `reactor-core`'s own per-failure-kind classification — so `instanceof\n * UnauthorizedError` and `code === 'UNAUTHORIZED'` are equivalent, one just\n * typed. Codes are open-ended (the platform can send its own), so an\n * unrecognized one falls back to the base class itself rather than\n * throwing.\n */\n/** Fields a `ReactorError` constructor accepts, all optional — an\n * unrecognized code still constructs cleanly on the base class, and a\n * purely local failure (no payload at all) still constructs cleanly too. */\nexport interface ReactorErrorOptions {\n code?: string | undefined;\n recoverable?: boolean | undefined;\n status?: number | undefined;\n operation?: string | undefined;\n retry_after_ms?: number | undefined;\n timestamp_ms?: number | undefined;\n entry?: string | undefined;\n command_code?: string | undefined;\n /** The underlying error, kept as the standard `Error.cause`. */\n cause?: unknown;\n}\n\nexport class ReactorError extends Error {\n /** The code this class stands for. `ReactorError` itself is the fallback,\n * so it claims none and takes whatever the payload reported. */\n static readonly code: string = 'INTERNAL_ERROR';\n\n /** `reactor-core`'s own canonical code for this failure — the same value\n * used to pick this instance's class (see the typed subclasses below for\n * the vocabulary). Open-ended: an unrecognized code still constructs the\n * base class, with `code` set to whatever was reported. */\n readonly code: string;\n /** Whether the same call could succeed later. */\n readonly recoverable: boolean;\n /** The HTTP status, when the failure came from one. */\n readonly status: number | undefined;\n /** Which call failed, e.g. \"connect\", \"sendCommand\". */\n readonly operation: string | undefined;\n /** Backoff hint the platform sent. */\n readonly retry_after_ms: number | undefined;\n /** For a refused step or a step whose call failed, the part of the step\n * request at fault: `\"state.<key>\"`, `\"commands[<i>]\"` or\n * `\"media_input[<i>]\"`. */\n readonly entry: string | undefined;\n /** For a step whose call failed, the stable code its handler raised (its\n * `CommandError` code, or `internal_error`), to branch on instead of the\n * message. */\n readonly command_code: string | undefined;\n /** When `reactor-core` reported this failure. For a purely local one (no\n * payload at all — see {@link ReactorErrorOptions}), this is synthesized\n * as the construction time instead, since there's nothing to report —\n * not a value read off the wire. */\n readonly timestamp_ms: number;\n\n /** Same value as `retry_after_ms`, under its previous name. Kept for\n * compatibility — prefer `retry_after_ms`. */\n readonly retryAfter: number | undefined;\n /** Same value as `timestamp_ms`, under its previous name. Kept for\n * compatibility — prefer `timestamp_ms`. */\n readonly timestamp: number;\n\n constructor(message: string, options: ReactorErrorOptions = {}) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause });\n this.name = 'ReactorError';\n // An explicit code wins, so an unrecognized one survives on the base\n // class rather than being relabelled as the fallback it was routed to.\n this.code = options.code ?? new.target.code;\n this.recoverable = options.recoverable ?? false;\n this.status = options.status;\n this.operation = options.operation;\n this.retry_after_ms = options.retry_after_ms;\n this.retryAfter = options.retry_after_ms;\n this.entry = options.entry;\n this.command_code = options.command_code;\n this.timestamp_ms = options.timestamp_ms ?? Date.now();\n this.timestamp = this.timestamp_ms;\n }\n}\n\n/** The request never got a reply — DNS, TLS, a refused socket. */\nexport class NetworkError extends ReactorError {\n static override readonly code = 'NETWORK_ERROR';\n}\n\n/** 401 or 403: the token is missing, expired, or not scoped for this call. */\nexport class UnauthorizedError extends ReactorError {\n static override readonly code = 'UNAUTHORIZED';\n}\n\n/** 404: no such model, session or upload. */\nexport class NotFoundError extends ReactorError {\n static override readonly code = 'NOT_FOUND';\n}\n\n/** 409: the session is in a state that does not allow this — usually a\n * session left orphaned by a previous run that went away without\n * disconnecting. */\nexport class ConflictError extends ReactorError {\n static override readonly code = 'CONFLICT';\n}\n\n/** 429: too many requests. `retry_after_ms` carries the server's\n * `Retry-After` when it sent one; `undefined` means back off on your own\n * terms rather than retrying immediately. */\nexport class RateLimitedError extends ReactorError {\n static override readonly code = 'RATE_LIMITED';\n}\n\n/** A 4xx other than the ones above: the request itself was wrong. */\nexport class BadRequestError extends ReactorError {\n static override readonly code = 'BAD_REQUEST';\n}\n\n/** 5xx: the coordinator failed, and the same request may work later. */\nexport class ServerError extends ReactorError {\n static override readonly code = 'SERVER_ERROR';\n}\n\n/** This client and the platform disagree on the protocol — upgrade the SDK. */\nexport class VersionMismatchError extends ReactorError {\n static override readonly code = 'VERSION_MISMATCH';\n}\n\n/** A reply arrived and could not be understood. */\nexport class DecodeError extends ReactorError {\n static override readonly code = 'DECODE_FAILED';\n}\n\n/** The operation is not allowed from the state the client is in — most often\n * a call that needs a live session, made before `connect()` or after the\n * status left `\"ready\"`. */\nexport class InvalidStateError extends ReactorError {\n static override readonly code = 'INVALID_STATE';\n}\n\n/** The session reached a state it cannot leave. Start a new one. */\nexport class SessionTerminalError extends ReactorError {\n static override readonly code = 'SESSION_TERMINAL';\n}\n\n/** The payload exceeds what the data channel accepts — send large content\n * with `uploadFile()` and pass the `FileRef` instead of embedding it\n * inline in a command. */\nexport class MessageTooLargeError extends ReactorError {\n static override readonly code = 'MESSAGE_TOO_LARGE';\n}\n\n/** The media transport failed. */\nexport class TransportError extends ReactorError {\n static override readonly code = 'TRANSPORT_ERROR';\n}\n\n/** The connection went away, either dropped mid-request or lost after being\n * established. `reconnect()` is the way back. */\nexport class DisconnectedError extends ReactorError {\n static override readonly code = 'DISCONNECTED';\n}\n\n/** The operation was sent and nothing came back in time. */\nexport class RequestTimeoutError extends ReactorError {\n static override readonly code = 'REQUEST_TIMEOUT';\n}\n\n/** The operation was abandoned before it finished. */\nexport class AbortedError extends ReactorError {\n static override readonly code = 'ABORTED';\n}\n\n/**\n * A `requestClip()`/`requestRecording()` call failed because the model's\n * recorder is disabled or has crashed.\n *\n * Unlike every other code here, `RECORDER_DISABLED` isn't platform-sent —\n * `reactor-core` produces it by matching known reason strings on an\n * otherwise free-text `ClipFailed` message, as a stopgap until that message\n * carries a structured reason (tracked as REA-5403). Treat it as best-effort:\n * a clip failure for the same underlying reason may still arrive as the\n * base `ReactorError` (`code: \"INTERNAL_ERROR\"`) if the reason text ever\n * changes upstream.\n *\n * `recoverable` is `false`: the recorder being disabled or crashed isn't\n * something retrying the same `requestClip()`/`requestRecording()` call can\n * fix — it needs an operator to re-enable or restart the recorder on the\n * model side first.\n */\nexport class RecorderDisabledError extends ReactorError {\n static override readonly code = 'RECORDER_DISABLED';\n}\n\n/** The runtime did not start the session in the requested `generation` —\n * most often a runtime without stepped generation, which ignores the\n * request rather than refusing it. Not recoverable: the same `connect()`\n * against the same runtime fails the same way. */\nexport class GenerationModeMismatchError extends ReactorError {\n static override readonly code = 'GENERATION_MODE_MISMATCH';\n}\n\n/** `connect()` asked for stepped generation over a data channel that did not\n * negotiate chunking: this client or the runtime does not support it. A\n * step's inputs and result each ride one data-channel message, and without\n * chunking a single camera frame outgrows it. Not recoverable. */\nexport class DataChannelChunkingRequiredError extends ReactorError {\n static override readonly code = 'DATA_CHANNEL_CHUNKING_REQUIRED';\n}\n\n/** The runtime refused a `step()` — the request or the model turned it down.\n * The runtime checks the whole request before it applies any of it, so a\n * refused step changed nothing. The code is the runtime's own, passed\n * through, hence lowercase. */\nexport class StepRefusedError extends ReactorError {\n static override readonly code = 'step_refused';\n}\n\n/** A `step()` did not run because the session cannot take a step yet — it\n * is not in a running state that can. Nothing the step carried was applied.\n * Lowercase, as the runtime names the outcome. */\nexport class StepNotReadyError extends ReactorError {\n static override readonly code = 'step_not_ready';\n}\n\n/** A `step()` ran, but its result did not fit in one data-channel message. */\nexport class StepResultTooLargeError extends ReactorError {\n static override readonly code = 'step_result_too_large';\n}\n\n/** A `step()` did not run because the handler of one of its state keys or\n * commands failed. The calls before it stay applied and the ones after it\n * were skipped. Lowercase, as the runtime names the outcome. */\nexport class StepCommandFailedError extends ReactorError {\n static override readonly code = 'step_command_failed';\n}\n\n/** The session ended before a `step()`'s result could be sent, so whether the\n * step ran is unknown. Lowercase, as the runtime names the outcome. */\nexport class StepSessionEndedError extends ReactorError {\n static override readonly code = 'step_session_ended';\n}\n\n/** A `step()` result carried a frame in an encoding this SDK cannot decode. */\nexport class UnsupportedFrameEncodingError extends ReactorError {\n static override readonly code = 'UNSUPPORTED_FRAME_ENCODING';\n}\n\n/** Every code this package has a class for. Anything else — a platform code\n * for a rejected request — falls back to `ReactorError` with `code` set to\n * it. */\nconst ERROR_CLASSES = [\n NetworkError,\n UnauthorizedError,\n NotFoundError,\n ConflictError,\n RateLimitedError,\n BadRequestError,\n ServerError,\n VersionMismatchError,\n DecodeError,\n InvalidStateError,\n SessionTerminalError,\n MessageTooLargeError,\n TransportError,\n DisconnectedError,\n RequestTimeoutError,\n AbortedError,\n RecorderDisabledError,\n GenerationModeMismatchError,\n DataChannelChunkingRequiredError,\n StepRefusedError,\n StepNotReadyError,\n StepResultTooLargeError,\n StepCommandFailedError,\n StepSessionEndedError,\n UnsupportedFrameEncodingError,\n] as const;\n\ninterface ReactorErrorClass {\n readonly code: string;\n new (message: string, options?: ReactorErrorOptions): ReactorError;\n}\n\nconst BY_CODE = new Map<string, ReactorErrorClass>(\n ERROR_CLASSES.map((errorClass) => [errorClass.code, errorClass]),\n);\n\n/** The exception class for `code`, or the base class for anything unknown. */\nexport function errorForCode(code: string | undefined): ReactorErrorClass {\n return (code && BY_CODE.get(code)) || ReactorError;\n}\n\n/** A record shape the wasm binding hands over, either as an `onError` event\n * payload or `Object.assign`ed onto a rejected call's thrown `Error`. */\ninterface ReactorErrorLike {\n code?: string;\n message?: string;\n recoverable?: boolean;\n status?: number;\n operation?: string;\n retry_after_ms?: number;\n timestamp_ms?: number;\n entry?: string;\n command_code?: string;\n}\n\n/**\n * Builds the typed exception for whatever the wasm binding handed over —\n * the plain object an `onError` event delivers, or the `Error` a rejected\n * call throws (message plus the same fields, `Object.assign`ed on).\n *\n * Already a `ReactorError`? Returned as-is, so wrapping is idempotent.\n * Anything else not shaped like the binding's payload (a bug elsewhere, a\n * plain string, or a purely local failure with no payload at all — a wasm\n * load/constructor throw, a call on a disposed client) still becomes a\n * `ReactorError` rather than propagating an untyped failure, falling back to\n * `INTERNAL_ERROR` when there's no code to report.\n */\nexport function toReactorError(cause: unknown): ReactorError {\n if (cause instanceof ReactorError) {\n return cause;\n }\n const payload = (cause ?? {}) as ReactorErrorLike;\n const message = typeof payload.message === 'string' ? payload.message : String(cause);\n const ErrorClass = errorForCode(payload.code);\n\n return new ErrorClass(message, {\n code: payload.code,\n recoverable: payload.recoverable,\n status: payload.status,\n operation: payload.operation,\n retry_after_ms: payload.retry_after_ms,\n timestamp_ms: payload.timestamp_ms,\n entry: payload.entry,\n command_code: payload.command_code,\n // A thrown JS error (a failed wasm load, say) keeps its stack and its own\n // `cause` reachable; reactor-core's plain payload objects have neither.\n cause: cause instanceof Error ? cause : undefined,\n });\n}\n","/** A minimal typed pub/sub — `on`/`off`/`once` over a fixed event map.\n *\n * `EventMap` is deliberately unconstrained: a `Record<string, ...>` bound\n * would force every event map to declare a string index signature, which\n * would let any string through as an event name and throw away the whole\n * point of typing this per call site. */\nexport class Emitter<EventMap extends { [Name in keyof EventMap]: (...args: never[]) => void }> {\n private readonly listeners = new Map<keyof EventMap, Set<EventMap[keyof EventMap]>>();\n\n on<Name extends keyof EventMap>(event: Name, handler: EventMap[Name]): void {\n let handlers = this.listeners.get(event);\n\n if (!handlers) {\n handlers = new Set();\n this.listeners.set(event, handlers);\n }\n handlers.add(handler);\n }\n\n off<Name extends keyof EventMap>(event: Name, handler: EventMap[Name]): void {\n this.listeners.get(event)?.delete(handler);\n }\n\n once<Name extends keyof EventMap>(event: Name, handler: EventMap[Name]): void {\n const wrapped = ((...args: Parameters<EventMap[Name]>) => {\n this.off(event, wrapped);\n (handler as (...args: Parameters<EventMap[Name]>) => void)(...args);\n }) as EventMap[Name];\n\n this.on(event, wrapped);\n }\n\n emit<Name extends keyof EventMap>(event: Name, ...args: Parameters<EventMap[Name]>): void {\n const handlers = this.listeners.get(event);\n\n if (!handlers) {\n return;\n }\n // Snapshot before calling: a handler is free to `off`/`once` itself or\n // register another one mid-dispatch without corrupting this pass.\n for (const handler of [...handlers]) {\n try {\n (handler as (...args: Parameters<EventMap[Name]>) => void)(...args);\n } catch (error) {\n // A handler throwing shouldn't stop delivery to the handlers after\n // it — one broken listener in the app shouldn't break the SDK's own\n // reporting to its other listeners.\n console.error(`[Emitter] handler for \"${String(event)}\" threw:`, error);\n }\n }\n }\n\n /** Drops every registered handler for every event. */\n clear(): void {\n this.listeners.clear();\n }\n}\n","/**\n * Turns an `EncodedFrame` into what the wasm binding's `pushEncodedVideoFrame`\n * takes, refusing what could never be a frame before it is queued. Whether\n * the bytes really decode is the runtime's to say, when the step runs.\n */\nimport { InvalidStateError } from '../errors';\nimport type { EncodedVideoCodec } from './reactor-wasm.types';\nimport type { EncodedFrame, PushFrame } from '../types';\n\n/** The codecs an encoded step frame can carry. */\nconst CODECS: ReadonlySet<string> = new Set<EncodedVideoCodec>(['h264']);\n\n/** An encoded frame's bytes and extras, ready for the binding, read once when\n * the call is made: a caller changing the frame afterwards changes nothing. */\nexport interface EncodedBytes {\n codec: EncodedVideoCodec;\n data: Uint8Array;\n width: number;\n height: number;\n metadata: Uint8Array | null;\n captureTimeUs: number | null;\n}\n\n/** Whether a `step()` media entry is an `EncodedFrame` rather than a frame\n * `pushFrame()` takes: only an encoded frame names a `codec`. */\nexport function isEncodedFrame(frame: PushFrame | EncodedFrame): frame is EncodedFrame {\n return typeof frame === 'object' && frame !== null && 'codec' in frame;\n}\n\nfunction isChunk(data: EncodedFrame['data']): data is EncodedVideoChunk {\n return (\n !(data instanceof Uint8Array) &&\n !(data instanceof ArrayBuffer) &&\n typeof data.copyTo === 'function'\n );\n}\n\n/** `frame`'s bytes as a `Uint8Array`: a view over an array or buffer, a copy\n * of an `EncodedVideoChunk`'s. Throws an `InvalidStateError` naming\n * `operation('trackName')` for a frame that could not be pushed. */\nexport function toEncodedBytes(frame: EncodedFrame, operation: string, trackName: string): EncodedBytes {\n const refuse = (why: string) =>\n new InvalidStateError(`${operation}('${trackName}'): ${why}`, { operation });\n\n if (typeof frame !== 'object' || frame === null) {\n throw refuse('expected an EncodedFrame, { codec, data, width, height }');\n }\n const { codec, data, width, height, metadata, captureTimeUs } = frame;\n\n if (!CODECS.has(codec)) {\n throw refuse(`unknown codec ${JSON.stringify(codec)}; expected \"h264\"`);\n }\n let bytes: Uint8Array;\n\n if (data instanceof Uint8Array) {\n bytes = data;\n } else if (data instanceof ArrayBuffer) {\n bytes = new Uint8Array(data);\n } else if (data && isChunk(data)) {\n bytes = new Uint8Array(data.byteLength);\n data.copyTo(bytes);\n } else {\n throw refuse('data must be a Uint8Array, an ArrayBuffer or an EncodedVideoChunk');\n }\n if (bytes.byteLength === 0) {\n throw refuse('an encoded frame needs data');\n }\n if (!isDimension(width) || !isDimension(height)) {\n throw refuse(`width and height are the decoded frame's, got ${String(width)}x${String(height)}`);\n }\n if (metadata != null && !(metadata instanceof Uint8Array)) {\n throw refuse('metadata must be a Uint8Array');\n }\n if (captureTimeUs != null && !Number.isFinite(captureTimeUs)) {\n throw refuse('captureTimeUs must be a finite number');\n }\n return { codec, data: bytes, width, height, metadata: metadata ?? null, captureTimeUs: captureTimeUs ?? null };\n}\n\nfunction isDimension(value: unknown): value is number {\n return typeof value === 'number' && Number.isInteger(value) && value > 0 && value <= 0xffff_ffff;\n}\n","/**\n * Reference to a file uploaded via `Reactor.uploadFile()`. Pass it back in\n * `sendCommand()`'s `data` wherever the model's schema declares a file: as a\n * top-level value it's extracted and sent as a separate upload reference,\n * and inside an array or object it's serialized as one — see\n * `extractFileRefs()`.\n */\nexport class FileRef {\n constructor(\n public readonly uploadId: string,\n public readonly name: string,\n public readonly mimeType: string,\n public readonly size: number,\n ) {}\n}\n\n/**\n * Structural check for anything shaped like a `FileRef`, for callers who'd\n * rather duck-type than rely on `instanceof` (e.g. across two copies of this\n * package bundled into the same page). `extractFileRefs()` uses this too,\n * for the same reason.\n */\nexport function isFileRef(value: unknown): value is FileRef {\n if (value instanceof FileRef) {\n return true;\n }\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n const candidate = value as Partial<FileRef>;\n\n return (\n typeof candidate.uploadId === 'string' &&\n typeof candidate.name === 'string' &&\n typeof candidate.mimeType === 'string' &&\n typeof candidate.size === 'number'\n );\n}\n","import { FileRef, isFileRef } from '../file-ref';\nimport type { FileRef as WireFileRef } from './reactor-wasm.types';\n\n/** camelCase → the wasm binding's own snake_case wire shape. */\nfunction toWireFileRef(fileRef: FileRef): WireFileRef {\n return {\n upload_id: fileRef.uploadId,\n name: fileRef.name,\n mime_type: fileRef.mimeType,\n size: fileRef.size,\n };\n}\n\n/** The wasm binding's snake_case wire shape → the public `FileRef` — what\n * `Reactor.uploadFile()` actually hands back to a caller. */\nexport function toPublicFileRef(fileRef: WireFileRef): FileRef {\n return new FileRef(fileRef.upload_id, fileRef.name, fileRef.mime_type, fileRef.size);\n}\n\n/**\n * Splits `data` into scalar command args and `FileRef` uploads: callers pass\n * a `FileRef` (from `uploadFile`) inline as a normal field and never build\n * the `uploads` map by hand. Each matched `FileRef` is translated to the\n * wasm binding's wire shape here, since that's what `sendCommand`'s\n * `uploads` argument actually expects.\n *\n * A top-level `FileRef` moves into `uploads`, keyed by its parameter name —\n * the one slot the wire has for a named upload. A `FileRef` nested inside an\n * array or an object has no such slot, so it stays in `data` and is rewritten\n * to the wire shape in place: the binding serializes `data` by reading each\n * object's own enumerable properties, so a `FileRef` left as-is would cross\n * the wire with its camelCase field names, which the model side does not\n * read. The walk follows the same rule the binding does — every array\n * element and every own enumerable property of every object, whatever its\n * prototype — so a `FileRef` is found wherever the binding would have\n * serialized it. A `Date` or a `Blob` has no enumerable properties and passes\n * through; a typed array is bytes and is skipped outright.\n *\n * Uses `isFileRef()`'s structural check rather than `instanceof FileRef`:\n * a duplicate copy of this package (e.g. two versions bundled into the same\n * page) produces a `FileRef` that fails `instanceof` against this module's\n * class but still type-checks and looks identical on the wire — routing it\n * through `data` instead of `uploads` would otherwise make the wire reject\n * an otherwise-valid command.\n */\nexport function extractFileRefs(data: Record<string, unknown> | undefined): {\n data: Record<string, unknown> | undefined;\n uploads: Record<string, WireFileRef> | undefined;\n} {\n if (!data) {\n return { data, uploads: undefined };\n }\n\n let uploads: Record<string, WireFileRef> | undefined;\n let scalars: Record<string, unknown> | undefined;\n\n for (const [key, value] of Object.entries(data)) {\n if (isFileRef(value)) {\n uploads ??= {};\n scalars ??= { ...data };\n uploads[key] = toWireFileRef(value);\n delete scalars[key];\n continue;\n }\n const rewritten = rewriteNestedFileRefs(value);\n\n if (rewritten !== value) {\n scalars ??= { ...data };\n scalars[key] = rewritten;\n }\n }\n\n return { data: scalars ?? data, uploads };\n}\n\n/**\n * Returns `value` with every `FileRef` inside it replaced by its wire shape,\n * or `value` itself when it contains none, so an untouched payload keeps its\n * identity. A step has no `uploads` slot, so `step()` sends its state and\n * command data through this whole.\n */\nexport function rewriteNestedFileRefs<T>(value: T): T;\nexport function rewriteNestedFileRefs(value: unknown): unknown {\n if (isFileRef(value)) {\n return toWireFileRef(value);\n }\n if (Array.isArray(value)) {\n const elements: unknown[] = value;\n let copy: unknown[] | undefined;\n\n elements.forEach((element, index) => {\n const rewritten = rewriteNestedFileRefs(element);\n\n if (rewritten !== element) {\n copy ??= [...elements];\n copy[index] = rewritten;\n }\n });\n return copy ?? elements;\n }\n if (isSerializedAsObject(value)) {\n let copy: Record<string, unknown> | undefined;\n\n // A copy spreads the own enumerable properties, which is exactly the set\n // the binding would have serialized off the original, so a class instance\n // that held a `FileRef` reaches the wire the same as before, minus the\n // camelCase reference.\n for (const [key, element] of Object.entries(value)) {\n const rewritten = rewriteNestedFileRefs(element);\n\n if (rewritten !== element) {\n copy ??= { ...value };\n copy[key] = rewritten;\n }\n }\n return copy ?? value;\n }\n return value;\n}\n\n/** Whether the binding serializes `value` as an object of its own enumerable\n * properties — anything object-like except a typed array, which it serializes\n * as bytes and which could hold no `FileRef` anyway. */\nfunction isSerializedAsObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !ArrayBuffer.isView(value);\n}\n","/**\n * Turns what `Reactor.pushFrame()` accepts into what the wasm binding's\n * `pushVideoFrame`/`pushAudioFrame` take: bytes, dimensions, and the layout\n * the bytes are in. The binding converts that layout to what `reactor-core`\n * buffers — this only gets the pixels out of whichever browser object holds\n * them, without converting them again on the JS side.\n */\nimport type { PixelFormat } from './reactor-wasm.types';\nimport type { PushAudioFrame, PushFrame, PushVideoFrame, RawVideoFrame } from '../types';\n\n/** Pixels in a layout the binding accepts. */\nexport interface Pixels {\n data: Uint8Array;\n width: number;\n height: number;\n format: PixelFormat;\n}\n\nexport function isAudioFrame(frame: PushFrame): frame is PushAudioFrame {\n return 'samples' in frame;\n}\n\nfunction isVideoFrame(frame: PushVideoFrame): frame is VideoFrame {\n return typeof (frame as VideoFrame).copyTo === 'function' && 'displayWidth' in frame;\n}\n\n/** A pushed frame the queue can read later. A `VideoFrame` is cloned at call\n * time, so the caller may close theirs as soon as `pushFrame()` returns;\n * `release` closes the clone once its pixels are out. */\nexport function holdFrame(frame: PushFrame): { frame: PushFrame; release: () => void } {\n if (!isAudioFrame(frame) && isVideoFrame(frame)) {\n const clone = frame.clone();\n\n return { frame: clone, release: () => clone.close() };\n }\n return { frame, release: () => {} };\n}\n\n/** The pixels of a pushed video frame. Async because a `VideoFrame`'s live\n * in GPU or decoder memory and copying them out is. A `VideoFrame` comes out\n * as it is displayed: its visible rect, rotated by its `rotation`, then\n * flipped by its `flip`, whichever path reads it. */\nexport async function toPixels(frame: PushVideoFrame): Promise<Pixels> {\n if (isVideoFrame(frame)) {\n return videoFramePixels(frame);\n }\n return rawPixels(frame);\n}\n\nfunction rawPixels(frame: RawVideoFrame | ImageData): Pixels {\n const { data, width, height } = frame;\n // A view, not a copy: `ImageData.data` is a Uint8ClampedArray, which the\n // binding's `Uint8Array` parameter would otherwise refuse at type level.\n const bytes =\n data instanceof Uint8Array ? data : new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n\n return { data: bytes, width, height, format: ('format' in frame && frame.format) || 'rgba' };\n}\n\n/** Native layouts `copyTo()` can hand over as they are. */\nconst NATIVE_FORMATS: Partial<Record<string, PixelFormat>> = {\n RGBA: 'rgba',\n RGBX: 'rgba',\n BGRA: 'bgra',\n BGRX: 'bgra',\n};\n\n/** A `VideoFrame`'s orientation. Both fields are recent WebCodecs additions,\n * so an engine without them reports neither. */\ninterface Orientation {\n rotation: number;\n flip: boolean;\n}\n\nfunction orientationOf(frame: VideoFrame): Orientation {\n const { rotation, flip } = frame as VideoFrame & Partial<Orientation>;\n\n return { rotation: (((rotation ?? 0) % 360) + 360) % 360, flip: flip ?? false };\n}\n\nasync function videoFramePixels(frame: VideoFrame): Promise<Pixels> {\n const rect = frame.visibleRect;\n const width = rect?.width ?? frame.codedWidth;\n const height = rect?.height ?? frame.codedHeight;\n const native = frame.format ? NATIVE_FORMATS[frame.format] : undefined;\n const orientation = orientationOf(frame);\n\n if (native) {\n const data = new Uint8Array(width * height * 4);\n\n await frame.copyTo(data, { layout: [{ offset: 0, stride: width * 4 }] });\n return orient({ data, width, height, format: native }, orientation);\n }\n // A YUV frame (a camera's, a decoder's): ask copyTo() to convert. Newer\n // engines can; the rest refuse the `format` option, and a canvas does it.\n try {\n const data = new Uint8Array(width * height * 4);\n const options = { format: 'RGBA', layout: [{ offset: 0, stride: width * 4 }] };\n\n await frame.copyTo(data, options as VideoFrameCopyToOptions);\n return orient({ data, width, height, format: 'rgba' }, orientation);\n } catch {\n return canvasPixels(frame, width, height, orientation);\n }\n}\n\n/** Turn pixels `copyTo()` read in stored orientation into the displayed one:\n * rotate clockwise by `rotation`, then flip horizontally if `flip`, as\n * WebCodecs renders a frame. A rotation that is not a multiple of 90 is not\n * a valid `VideoFrame` rotation and leaves the pixels as they are. */\nexport function orient(pixels: Pixels, { rotation, flip }: Orientation): Pixels {\n if (rotation % 90 !== 0 || (rotation === 0 && !flip)) {\n return pixels;\n }\n const { width: w, height: h } = pixels;\n const turned = rotation === 90 || rotation === 270;\n const outWidth = turned ? h : w;\n const outHeight = turned ? w : h;\n // One 32-bit word per pixel: the layout is 4 bytes a pixel, whatever order.\n // A view needs its offset 4-byte aligned; copy the bytes when it is not.\n const bytes = pixels.data.byteOffset % 4 === 0 ? pixels.data : pixels.data.slice();\n const source = new Uint32Array(bytes.buffer, bytes.byteOffset, w * h);\n const data = new Uint8Array(outWidth * outHeight * 4);\n const target = new Uint32Array(data.buffer);\n\n for (let y = 0; y < h; y++) {\n for (let x = 0; x < w; x++) {\n let tx: number;\n let ty: number;\n\n if (rotation === 90) {\n [tx, ty] = [h - 1 - y, x];\n } else if (rotation === 180) {\n [tx, ty] = [w - 1 - x, h - 1 - y];\n } else if (rotation === 270) {\n [tx, ty] = [y, w - 1 - x];\n } else {\n [tx, ty] = [x, y];\n }\n if (flip) {\n tx = outWidth - 1 - tx;\n }\n target[ty * outWidth + tx] = source[y * w + x] as number;\n }\n }\n return { data, width: outWidth, height: outHeight, format: pixels.format };\n}\n\n/** Read a frame through a 2D canvas, which renders it as displayed. The\n * canvas takes the visible size, turned for a rotation of 90 or 270, so the\n * pixels match what `orient()` makes of a `copyTo()` read. */\nfunction canvasPixels(\n frame: VideoFrame,\n visibleWidth: number,\n visibleHeight: number,\n { rotation }: Orientation,\n): Pixels {\n const turned = rotation === 90 || rotation === 270;\n const width = turned ? visibleHeight : visibleWidth;\n const height = turned ? visibleWidth : visibleHeight;\n\n if (typeof OffscreenCanvas === 'undefined') {\n throw new Error(\n `pushFrame: cannot read a ${frame.format ?? 'formatless'} VideoFrame here — ` +\n 'push its pixels as an ImageData or a Uint8Array instead.',\n );\n }\n const context = new OffscreenCanvas(width, height).getContext('2d');\n\n if (!context) {\n throw new Error('pushFrame: no 2D canvas context to read the VideoFrame through.');\n }\n context.drawImage(frame, 0, 0, width, height);\n return rawPixels(context.getImageData(0, 0, width, height));\n}\n","import type { Clip, ClipKind } from '../types';\nimport type { Clip as WireClip } from './reactor-wasm.types';\n\n/** The wasm binding's snake_case wire shape → the public, camelCase one —\n * what `Reactor.requestClip()` / `requestRecording()` hand back to a caller.\n * One-directional: a `Clip` is only ever received, never sent, so there's no\n * `toWireClip` counterpart.\n *\n * `kind` is narrowed from the binding's own untyped `string` — `reactor-core`\n * only ever sends `\"snap\"` (from `requestClip()`) or `\"recording\"` (from\n * `requestRecording()`), same as `crates/reactor-wasm/src/types.rs`'s own\n * doc comment for the field. */\nexport function toPublicClip(clip: WireClip): Clip {\n return {\n sessionId: clip.session_id,\n kind: clip.kind as ClipKind,\n startMarker: clip.start_marker,\n endMarker: clip.end_marker,\n nowMarker: clip.now_marker,\n predictedReadyAtMs: clip.predicted_ready_at_ms,\n playlistUrl: clip.playlist_url,\n };\n}\n","/**\n * The read half of `step()`'s `media`: each frame held when `step()` is\n * called, read into what the binding takes, and checked by the binding's own\n * checks before any of them is pushed. `Reactor` keeps only the queueing and\n * the final pushes.\n */\nimport { InvalidStateError } from '../errors';\nimport { isEncodedFrame, toEncodedBytes, type EncodedBytes } from './encoded-frames';\nimport { holdFrame, isAudioFrame, toPixels, type Pixels } from './push-frames';\nimport type { ReactorClient } from './reactor-wasm.types';\nimport type { EncodedFrame, PushAudioFrame, PushFrame, StepOptions } from '../types';\n\n/** One frame of `step()`'s `media`, held from call time until it is read. */\nexport type HeldStepFrame = { track: string; release: () => void } & (\n | { kind: 'encoded'; operation: 'pushEncodedFrame'; encoded: EncodedBytes }\n | { kind: 'raw'; operation: 'pushFrame'; frame: PushFrame }\n);\n\n/** One frame of `step()`'s `media`, read out, as the binding takes it. */\nexport type ReadyStepFrame = { track: string } & (\n | { kind: 'encoded'; operation: 'pushEncodedFrame'; encoded: EncodedBytes }\n | { kind: 'video'; operation: 'pushFrame'; pixels: Pixels }\n | { kind: 'audio'; operation: 'pushFrame'; audio: PushAudioFrame }\n);\n\n/** Every frame of `media`, held as at call time, track by track and in order:\n * a chunk copied, a VideoFrame cloned, and a malformed frame refused, now.\n * On a refusal, whatever was already held is released before it throws. */\nexport function holdStepMedia(media: NonNullable<StepOptions['media']>): HeldStepFrame[] {\n if (typeof media !== 'object' || media === null || Array.isArray(media)) {\n throw new InvalidStateError('step(): media must map track names to arrays of frames', {\n operation: 'step',\n });\n }\n const held: HeldStepFrame[] = [];\n\n try {\n for (const [trackName, frames] of Object.entries(media)) {\n if (!Array.isArray(frames)) {\n throw new InvalidStateError(`step(): media['${trackName}'] must be an array of frames`, {\n operation: 'step',\n });\n }\n for (const frame of frames as ReadonlyArray<PushFrame | EncodedFrame>) {\n held.push(holdStepFrame(trackName, frame));\n }\n }\n } catch (cause) {\n for (const frame of held) {\n frame.release();\n }\n throw cause;\n }\n return held;\n}\n\nfunction holdStepFrame(track: string, frame: PushFrame | EncodedFrame): HeldStepFrame {\n if (isEncodedFrame(frame)) {\n const operation = 'pushEncodedFrame';\n\n return { track, kind: 'encoded', operation, encoded: toEncodedBytes(frame, operation, track), release: () => {} };\n }\n if (typeof frame !== 'object' || frame === null) {\n throw new InvalidStateError(`pushFrame('${track}'): expected a frame`, { operation: 'pushFrame' });\n }\n const held = holdFrame(frame);\n\n return { track, kind: 'raw', operation: 'pushFrame', frame: held.frame, release: held.release };\n}\n\n/** `frame` read out into what the binding's push takes: a VideoFrame's\n * pixels copied out, as `pushFrame()` would. */\nexport async function readStepFrame(frame: HeldStepFrame): Promise<ReadyStepFrame> {\n const { track } = frame;\n\n if (frame.kind === 'encoded') {\n return { track, kind: 'encoded', operation: frame.operation, encoded: frame.encoded };\n }\n if (isAudioFrame(frame.frame)) {\n return { track, kind: 'audio', operation: frame.operation, audio: frame.frame };\n }\n return { track, kind: 'video', operation: frame.operation, pixels: await toPixels(frame.frame) };\n}\n\n/** Throws what the binding's push would refuse of `frame`, pushing nothing:\n * the push's own checks, so a step refuses a bad frame anywhere in its media\n * before the first goes into the buffer. A raw or encoded frame is checked\n * by its length, so its bytes are not copied into wasm memory twice. */\nexport function checkStepFrame(client: ReactorClient, frame: ReadyStepFrame): void {\n if (frame.kind === 'encoded') {\n const { codec, data, width, height, captureTimeUs } = frame.encoded;\n\n client.checkEncodedVideoFrame(frame.track, codec, data.byteLength, width, height, captureTimeUs);\n } else if (frame.kind === 'video') {\n const { data, width, height, format } = frame.pixels;\n\n client.checkVideoFrame(frame.track, data.byteLength, width, height, format);\n } else {\n client.checkAudioFrame(frame.track, frame.audio.samples, frame.audio.channels ?? 1);\n }\n}\n","import type { ConnectionStats } from '../types';\nimport type {\n ClientConnectionStat,\n ClientTrackStat,\n FrameStage,\n ReactorClient,\n TrackDirection,\n TrackKind,\n TrackMappingEntry,\n} from './reactor-wasm.types';\n\n// Two intervals, so the local `statsUpdate` cadence and the runtime report\n// cadence can each change without affecting the other.\n\n/** How often `Reactor` reads `getStats()` while ready to update the stats it\n * exposes inside the SDK: `getStats()` and the `statsUpdate` event. Nothing\n * read on this timer leaves the browser. */\nexport const LOCAL_STATS_INTERVAL_MS = 2_000;\n\n/** How often `Reactor` sends a client-stats batch to the runtime while ready.\n * Runs on its own timer and its own `getStats()` read, apart from\n * `LOCAL_STATS_INTERVAL_MS`, so each batch's bitrates cover the whole\n * interval since the previous batch. */\nexport const RUNTIME_REPORT_INTERVAL_MS = 5_000;\n\n/** Reads `getStats()` off *client*'s peer connection every *intervalMs* and\n * hands each report to *onReport*. A tick without a peer connection, or\n * whose read rejects (the connection may be closing), is skipped. An error\n * thrown by *onReport* itself is a bug, not a closing connection, so it is\n * logged rather than swallowed, and polling goes on.\n *\n * One read at a time: a tick that finds the previous read still pending is\n * skipped. Reads that overlapped could resolve out of order, and a\n * bitrate is a delta against the previous report, so an older report\n * landing after a newer one would set the baseline back in time.\n *\n * Returns the function that stops it. Clearing the interval can't cancel a\n * `getStats()` already in flight, so a read that resolves after the stop is\n * dropped instead of reaching *onReport*: a recoverable disconnect can\n * restart polling on the same client, and the old read must not land in the\n * new one. */\nexport function pollPeerStats(\n client: Pick<ReactorClient, 'getPeerConnection'>,\n intervalMs: number,\n onReport: (report: RTCStatsReport) => void,\n): () => void {\n let stopped = false;\n let reading = false;\n const handle = setInterval(() => {\n if (reading) {\n return;\n }\n const peerConnection = client.getPeerConnection();\n\n if (!peerConnection) {\n return;\n }\n reading = true;\n void peerConnection\n .getStats()\n .then(\n (report) => {\n if (stopped) {\n return;\n }\n try {\n onReport(report);\n } catch (error) {\n console.error('[Reactor] stats report handler threw:', error);\n }\n },\n () => {\n // Connection may be closing.\n },\n )\n .finally(() => {\n reading = false;\n });\n }, intervalMs);\n\n return () => {\n stopped = true;\n clearInterval(handle);\n };\n}\n\n/** A duration in milliseconds rounded to the microsecond, for the runtime\n * report. Durations reach it as binary floats — `getStats()` seconds times\n * 1000, or the difference of two `performance.now()` readings — and would\n * otherwise travel as values like `0.8109999999999999` or\n * `6294.200000047684`. */\nfunction roundMs(ms: number): number {\n return Math.round(ms * 1_000) / 1_000;\n}\n\n/** A WebRTC duration in seconds as milliseconds — see `roundMs()`. */\nfunction secondsToMs(seconds: number): number {\n return roundMs(seconds * 1_000);\n}\n\n/** The codecs the wire's `VideoCodec`/`AudioCodec` enums can carry, per\n * track kind. `sendClientStats` rejects the whole batch over one codec\n * outside this set, so a track negotiated onto anything else is left out\n * of the batch rather than taking every other track's reading down with it.\n *\n * Mirrors `client_track_codec` in `crates/reactor-core/src/stats.rs`. A\n * reactor-core test compares this list with the wire's codec enums, so it\n * fails when the wire gains a codec: add it there and here together. */\nconst WIRE_CODECS: Record<TrackKind, ReadonlySet<string>> = {\n video: new Set(['vp8', 'vp9', 'av1', 'h264', 'h265']),\n audio: new Set(['opus']),\n};\n\n/** The previous reading of one RTP stream's byte counter, for turning it\n * into a bitrate. */\ninterface ByteSample {\n bytes: number;\n timestamp: number;\n}\n\n/** Builds one batch of the wire's `ClientTrackStat`s from a stats report, a\n * reading per negotiated track — audio and video, sent and received. Call\n * `commit()` once the batch has gone out: until then the next batch still\n * measures from the last one that did, so an unsent batch's interval is not\n * lost. */\nexport type TrackStatsExtractor = ((\n report: RTCStatsReport,\n tracks: readonly TrackMappingEntry[],\n pausedTracks: readonly string[],\n) => ClientTrackStat[]) & { commit(): void };\n\n/** A stage's running total as of the last batch sent: time in seconds, and\n * the frames it covers. */\ninterface StageTotal {\n seconds: number;\n frames: number;\n}\n\n// The native SDKs send the same readings from reactor-core, and its tests read\n// this file: `crates/reactor-core/src/stats.rs` checks that the native reporter\n// sends exactly the metric names written here, for each direction and kind of\n// track and for the connection, and that `WIRE_CODECS` matches the wire. They\n// find the sections below by their code: the direction and kind branches of\n// the extractor, the remote-inbound lookup, and each named metric write. A\n// change to a metric, or to how this function is laid out, can fail Rust CI.\n\n/**\n * The per-track part of the runtime report: one reading per track, every\n * `RUNTIME_REPORT_INTERVAL_MS`. Not used for `getStats()` / `statsUpdate`.\n *\n * A closure over each RTP stream's previous byte counter, needed to turn the\n * cumulative `bytesReceived`/`bytesSent` into a bitrate averaged over the\n * interval since the previous batch. A stream's first batch carries no\n * `bitrate_bps` — there is nothing to diff against yet.\n *\n * Each `inbound-rtp` (a `recvonly` track) and `outbound-rtp` (a `sendonly`\n * track) resolves to its track through its `mid`; a stream on a `mid` that\n * hasn't negotiated onto a named track, or whose codec isn't known yet, is\n * skipped. A sent stream's loss, jitter and round-trip time are what the\n * remote end reported back for it (its `remote-inbound-rtp`), the only\n * vantage point onto them. A received stream carries no round-trip time: a\n * receiver has no per-stream one, so the connection's own ICE round-trip time\n * goes on the connection stat instead (`connection_rtt_ms`). With several\n * streams on one `mid` (simulcast layers), the first one reported stands for\n * the track.\n *\n * Reports raw cumulative counters (`packets_lost`/`packets_received`, not a\n * pre-computed loss ratio) so the runtime's downstream aggregation across\n * sessions stays a sum of sums — a pre-averaged ratio can't be re-aggregated\n * correctly. A reading the browser hasn't produced is left out of `metrics`\n * rather than reported as `0`, so it can't pass for a real zero.\n *\n * A video track also carries the time its frames spent in each stage the\n * browser times, since the previous batch: `jitter_buffer` and `decode` on a\n * received track, `encode` on a sent one, from the cumulative totals the\n * browser keeps. As with the bitrate, a stream's first batch has none.\n */\nexport function createTrackStatsExtractor(): TrackStatsExtractor {\n const lastBytes = new Map<string, ByteSample>();\n const lastStages = new Map<string, StageTotal>();\n // What the batch being built moves the baselines to, once committed.\n // `undefined` drops a baseline.\n let pendingBytes = new Map<string, ByteSample>();\n let pendingStages = new Map<string, StageTotal | undefined>();\n\n /** The time a stream's frames spent in *name* since the last batch sent,\n * from the browser's running total of *seconds* over *frames*. */\n const stage = (\n streamId: string,\n name: string,\n seconds: number | undefined,\n frames: number | undefined,\n ): FrameStage | undefined => {\n if (seconds === undefined || frames === undefined) {\n return undefined;\n }\n const key = `${streamId}:${name}`;\n\n // A total that is not a number is no baseline either.\n if (!Number.isFinite(seconds)) {\n pendingStages.set(key, undefined);\n\n return undefined;\n }\n pendingStages.set(key, { seconds, frames });\n const before = lastStages.get(key);\n\n // A stream's first batch, no frame through the stage, or a total that\n // went backwards (a reset engine): nothing to report.\n if (before === undefined || frames <= before.frames || seconds < before.seconds) {\n return undefined;\n }\n\n return { name, totalMs: (seconds - before.seconds) * 1_000, frames: frames - before.frames };\n };\n\n const extract = (report: RTCStatsReport, tracks: readonly TrackMappingEntry[], pausedTracks: readonly string[]) => {\n pendingBytes = new Map();\n pendingStages = new Map();\n const reportWithLookup = report as RTCStatsReportWithLookup;\n const stats: ClientTrackStat[] = [];\n // Keyed by direction too: a sendrecv transceiver shares one mid between\n // its sent and received stream.\n const seenStreams = new Set<string>();\n const remoteInbound = new Map<string, RTCStatsReportEntry>();\n\n report.forEach((stat: RTCStatsReportEntry) => {\n if (stat.type === 'remote-inbound-rtp' && stat.localId !== undefined) {\n remoteInbound.set(stat.localId, stat);\n }\n });\n\n report.forEach((stat: RTCStatsReportEntry) => {\n const inbound = stat.type === 'inbound-rtp';\n\n if ((!inbound && stat.type !== 'outbound-rtp') || stat.mid === undefined) {\n return;\n }\n const direction: TrackDirection = inbound ? 'recvonly' : 'sendonly';\n const streamKey = `${direction}:${stat.mid}`;\n\n if (seenStreams.has(streamKey)) {\n return;\n }\n const track = tracks.find((entry) => entry.mid === stat.mid && entry.direction === direction);\n const codecStat = stat.codecId !== undefined ? reportWithLookup.get(stat.codecId) : undefined;\n // \"video/VP9\" -> \"vp9\".\n const codec = codecStat?.mimeType?.split('/')[1]?.toLowerCase();\n\n if (track === undefined || codec === undefined || !WIRE_CODECS[track.kind].has(codec)) {\n return;\n }\n seenStreams.add(streamKey);\n\n const metrics: Record<string, number> = {};\n const put = (key: string, value: number | undefined) => {\n if (value !== undefined) {\n metrics[key] = value;\n }\n };\n const bytes = inbound ? stat.bytesReceived : stat.bytesSent;\n\n if (bytes !== undefined) {\n const previous = lastBytes.get(stat.id);\n\n if (previous !== undefined && stat.timestamp > previous.timestamp && bytes >= previous.bytes) {\n put('bitrate_bps', Math.round(((bytes - previous.bytes) * 8 * 1000) / (stat.timestamp - previous.timestamp)));\n }\n pendingBytes.set(stat.id, { bytes, timestamp: stat.timestamp });\n }\n const keyframeRequests =\n stat.firCount !== undefined || stat.pliCount !== undefined\n ? (stat.firCount ?? 0) + (stat.pliCount ?? 0)\n : undefined;\n\n if (inbound) {\n put('packets_received', stat.packetsReceived);\n put('packets_lost', stat.packetsLost);\n put('jitter_ms', stat.jitter !== undefined ? secondsToMs(stat.jitter) : undefined);\n put('nack_count', stat.nackCount);\n if (track.kind === 'video') {\n put('frames_per_second', stat.framesPerSecond);\n put('frames_decoded', stat.framesDecoded);\n put('frames_dropped', stat.framesDropped);\n put('frame_width', stat.frameWidth);\n put('frame_height', stat.frameHeight);\n put('keyframe_requests', keyframeRequests);\n } else {\n put('concealed_samples', stat.concealedSamples);\n put('total_samples_received', stat.totalSamplesReceived);\n }\n } else {\n const remote = remoteInbound.get(stat.id);\n\n put('packets_sent', stat.packetsSent);\n put('retransmitted_packets_sent', stat.retransmittedPacketsSent);\n put('nack_count', stat.nackCount);\n put('packets_lost', remote?.packetsLost);\n put('jitter_ms', remote?.jitter !== undefined ? secondsToMs(remote.jitter) : undefined);\n put('round_trip_time_ms', remote?.roundTripTime !== undefined ? secondsToMs(remote.roundTripTime) : undefined);\n if (track.kind === 'video') {\n put('frames_per_second', stat.framesPerSecond);\n put('frames_encoded', stat.framesEncoded);\n put('frame_width', stat.frameWidth);\n put('frame_height', stat.frameHeight);\n put('keyframe_requests', keyframeRequests);\n }\n }\n\n const frameStages: FrameStage[] = [];\n\n if (track.kind === 'video') {\n const stages = inbound\n ? [\n stage(stat.id, 'jitter_buffer', stat.jitterBufferDelay, stat.jitterBufferEmittedCount),\n stage(stat.id, 'decode', stat.totalDecodeTime, stat.framesDecoded),\n ]\n : [stage(stat.id, 'encode', stat.totalEncodeTime, stat.framesEncoded)];\n\n for (const s of stages) {\n if (s !== undefined) {\n frameStages.push(s);\n }\n }\n }\n\n // Which encoder or decoder the video runs, and whether it is the\n // power-efficient (hardware) one. A browser only says to a page that\n // holds capture permission, so both are often absent.\n const codecImplementation = inbound ? stat.decoderImplementation : stat.encoderImplementation;\n const hardwareCodec = inbound ? stat.powerEfficientDecoder : stat.powerEfficientEncoder;\n\n stats.push({\n timestamp: Date.now(),\n trackName: track.name,\n kind: track.kind,\n direction,\n codec,\n paused: pausedTracks.includes(track.name),\n metrics,\n ...(frameStages.length > 0 ? { frameStages } : {}),\n ...(track.kind === 'video' && codecImplementation !== undefined ? { codecImplementation } : {}),\n ...(track.kind === 'video' && hardwareCodec !== undefined ? { hardwareCodec } : {}),\n });\n });\n\n return stats;\n };\n\n return Object.assign(extract, {\n commit(): void {\n for (const [id, sample] of pendingBytes) {\n lastBytes.set(id, sample);\n }\n for (const [key, total] of pendingStages) {\n if (total === undefined) {\n lastStages.delete(key);\n } else {\n lastStages.set(key, total);\n }\n }\n pendingBytes = new Map();\n pendingStages = new Map();\n },\n });\n}\n\n/**\n * The connection-wide part of the runtime report, read straight off one stats\n * report — the facts that belong to the connection, not to any one track.\n * Every value is a point-in-time reading of the active candidate-pair (see\n * `activeCandidatePair()`), so nothing here depends on a previous report.\n *\n * - `available_outgoing_bitrate_bps`: the congestion controller's current\n * send-side estimate.\n * - `available_incoming_bitrate_bps`: the receive-side estimate, which a\n * browser only has when it estimates as the receiver.\n * - `connection_rtt_ms`: the ICE round-trip time, one value for the whole\n * connection.\n * - `time_to_connect_ms`: *timeToConnectMs*, a one-time fact the caller passes\n * only on the first report after connecting.\n *\n * Like a track's metrics, a reading the browser hasn't produced is left out\n * rather than reported as `0`, so it can't pass for a collapsed estimate.\n */\nexport function toClientConnectionStat(report: RTCStatsReport, timeToConnectMs?: number): ClientConnectionStat {\n const pair = activeCandidatePair(report);\n const metrics: Record<string, number> = {};\n\n if (pair?.availableOutgoingBitrate !== undefined) {\n metrics.available_outgoing_bitrate_bps = pair.availableOutgoingBitrate;\n }\n if (pair?.availableIncomingBitrate !== undefined) {\n metrics.available_incoming_bitrate_bps = pair.availableIncomingBitrate;\n }\n if (pair?.currentRoundTripTime !== undefined) {\n metrics.connection_rtt_ms = secondsToMs(pair.currentRoundTripTime);\n }\n if (timeToConnectMs !== undefined) {\n metrics.time_to_connect_ms = roundMs(timeToConnectMs);\n }\n return { timestamp: Date.now(), metrics };\n}\n\ntype ConnectionStatsExtractor = (report: RTCStatsReport) => ConnectionStats;\n\n/**\n * `lib.dom`'s own `RTCStats` only has `id`/`timestamp`/`type` — the fields\n * below are the real, spec-defined ones this extractor reads off whichever\n * concrete stat type each belongs to (`RTCIceCandidatePairStats`,\n * `RTCIceCandidateStats`, `RTCInboundRtpStreamStats`, `RTCOutboundRtpStreamStats`,\n * `RTCRemoteInboundRtpStreamStats`). `forEach()`'s callback\n * is typed `any` in `lib.dom`, so annotating it with this instead is what\n * gets every access below out from under `no-unsafe-member-access`.\n *\n * Also fills in `get()` — Map-like lookup by id (e.g. a candidate-pair's\n * `localCandidateId`) is how the spec's `RTCStatsReport` actually behaves,\n * but `lib.dom` doesn't declare it either.\n */\ninterface RTCStatsReportEntry extends RTCStats {\n state?: string;\n nominated?: boolean;\n selectedCandidatePairId?: string;\n selected?: boolean;\n currentRoundTripTime?: number;\n availableOutgoingBitrate?: number;\n availableIncomingBitrate?: number;\n localCandidateId?: string;\n bytesReceived?: number;\n bytesSent?: number;\n candidateType?: string;\n kind?: string;\n framesPerSecond?: number;\n jitter?: number;\n packetsReceived?: number;\n packetsLost?: number;\n mid?: string;\n framesDecoded?: number;\n framesDropped?: number;\n frameWidth?: number;\n frameHeight?: number;\n nackCount?: number;\n firCount?: number;\n pliCount?: number;\n codecId?: string;\n mimeType?: string;\n localId?: string;\n roundTripTime?: number;\n packetsSent?: number;\n retransmittedPacketsSent?: number;\n framesEncoded?: number;\n concealedSamples?: number;\n totalSamplesReceived?: number;\n jitterBufferDelay?: number;\n jitterBufferEmittedCount?: number;\n totalDecodeTime?: number;\n totalEncodeTime?: number;\n encoderImplementation?: string;\n decoderImplementation?: string;\n powerEfficientEncoder?: boolean;\n powerEfficientDecoder?: boolean;\n}\n\ninterface RTCStatsReportWithLookup extends RTCStatsReport {\n get(id: string): RTCStatsReportEntry | undefined;\n}\n\n/**\n * The candidate-pair carrying the connection's media. Several pairs can be\n * `succeeded` and `nominated` at once (one per local interface), and only the\n * one the transport actually uses has a live round-trip time, a bandwidth\n * estimate and moving byte counters. In order of preference:\n *\n * 1. the pair the `transport` stat names (Chrome, Safari),\n * 2. the pair flagged `selected` (Firefox, which has no `transport` stat),\n * 3. the first `succeeded` and `nominated` pair, for a browser that marks\n * neither.\n *\n * Every choice must have `succeeded`: a pair that hasn't carries no media.\n */\nfunction activeCandidatePair(report: RTCStatsReport): RTCStatsReportEntry | undefined {\n let namedByTransport: string | undefined;\n let flaggedSelected: RTCStatsReportEntry | undefined;\n let firstNominated: RTCStatsReportEntry | undefined;\n\n report.forEach((stat: RTCStatsReportEntry) => {\n if (stat.type === 'transport' && stat.selectedCandidatePairId) {\n namedByTransport ??= stat.selectedCandidatePairId;\n }\n if (stat.type === 'candidate-pair' && stat.state === 'succeeded') {\n if (stat.selected) {\n flaggedSelected ??= stat;\n }\n if (stat.nominated) {\n firstNominated ??= stat;\n }\n }\n });\n\n const named =\n namedByTransport !== undefined ? (report as RTCStatsReportWithLookup).get(namedByTransport) : undefined;\n const namedSucceeded = named?.state === 'succeeded' ? named : undefined;\n\n return namedSucceeded ?? flaggedSelected ?? firstNominated;\n}\n\n/**\n * A summary of the whole connection: the `ConnectionStats` behind\n * `getStats()` and `statsUpdate`. Connection-wide values come from the active\n * candidate-pair (see `activeCandidatePair()`); frame rate, jitter and loss\n * from the first received video stream.\n *\n * A closure over the previous reading's candidate-pair byte counters, needed\n * to turn them into a bitrate — so each poller keeps its own instance.\n */\nexport function createConnectionStatsExtractor(): ConnectionStatsExtractor {\n let lastBytesReceived: number | undefined;\n let lastBytesSent: number | undefined;\n let lastCandPairTimestamp: number | undefined;\n // An ICE restart or failover nominates a different candidate-pair, whose\n // byte counters start from their own, unrelated baseline — diffing against\n // the previous pair's counters would produce a bogus (often negative)\n // bitrate for that one sample.\n let lastCandPairId: string | undefined;\n\n return (report: RTCStatsReport) => {\n let rtt: number | undefined;\n let availableOutgoingBitrate: number | undefined;\n let availableIncomingBitrate: number | undefined;\n let incomingBitrate: number | undefined;\n let outgoingBitrate: number | undefined;\n let videoInboundRtpId: string | undefined;\n let framesPerSecond: number | undefined;\n let jitter: number | undefined;\n let packetLossRatio: number | undefined;\n let candidateType: string | undefined;\n\n const pair = activeCandidatePair(report);\n\n if (pair !== undefined) {\n if (pair.currentRoundTripTime !== undefined) {\n rtt = pair.currentRoundTripTime * 1000;\n }\n availableOutgoingBitrate = pair.availableOutgoingBitrate;\n availableIncomingBitrate = pair.availableIncomingBitrate;\n\n const localCandidate =\n pair.localCandidateId !== undefined\n ? (report as RTCStatsReportWithLookup).get(pair.localCandidateId)\n : undefined;\n\n if (localCandidate?.candidateType) {\n candidateType = localCandidate.candidateType;\n }\n const samePair = lastCandPairId === pair.id;\n const timeDiff: number =\n samePair && lastCandPairTimestamp !== undefined ? pair.timestamp - lastCandPairTimestamp : 0;\n\n if (pair.bytesReceived !== undefined) {\n if (samePair && lastBytesReceived !== undefined && timeDiff > 0) {\n incomingBitrate = (((pair.bytesReceived - lastBytesReceived) * 8) / timeDiff) * 1000; /* Bits/Second */\n }\n lastBytesReceived = pair.bytesReceived;\n }\n if (pair.bytesSent !== undefined) {\n if (samePair && lastBytesSent !== undefined && timeDiff > 0) {\n outgoingBitrate = (((pair.bytesSent - lastBytesSent) * 8) / timeDiff) * 1000; /* Bits/Second */\n }\n lastBytesSent = pair.bytesSent;\n }\n lastCandPairTimestamp = pair.timestamp;\n lastCandPairId = pair.id;\n }\n\n report.forEach((stat: RTCStatsReportEntry) => {\n // If there is more than one video stream the stats will be from the first one encountered.\n if (videoInboundRtpId === undefined && stat.type === 'inbound-rtp' && stat.kind === 'video') {\n videoInboundRtpId = stat.id;\n if (stat.framesPerSecond !== undefined) {\n framesPerSecond = stat.framesPerSecond;\n }\n if (stat.jitter !== undefined) {\n jitter = stat.jitter;\n }\n if (\n stat.packetsReceived !== undefined &&\n stat.packetsLost !== undefined &&\n stat.packetsReceived + stat.packetsLost > 0\n ) {\n packetLossRatio = stat.packetsLost / (stat.packetsReceived + stat.packetsLost);\n }\n }\n });\n\n return {\n rtt,\n candidateType,\n availableIncomingBitrate,\n availableOutgoingBitrate,\n incomingBitrate,\n outgoingBitrate,\n framesPerSecond,\n packetLossRatio,\n jitter,\n timestamp: Date.now(),\n };\n };\n}\n","/**\n * Lazy, idempotent access to the `reactor-wasm` module.\n *\n * Nothing imports `reactor_wasm.js` at module scope: pulling in wasm on\n * import would make constructing a `Reactor` that never connects pay for a\n * network fetch and a WebAssembly compile it never needed. The module is\n * fetched and instantiated on first use and cached module-wide, so every\n * `Reactor` in a page shares one `init()` — a second `new Reactor(...)`, or a\n * reconnect, never re-runs it.\n */\nimport type { ReactorWasmModule } from './reactor-wasm.types';\n\nlet modulePromise: Promise<ReactorWasmModule> | null = null;\n\n/**\n * `wasm-pack --target web` emits a plain ES module that instantiates the\n * binding — this loader only needs to reach that module and call its default\n * export once. tsup bundles this whole package into one flat\n * `dist/index.{js,cjs}`, so at runtime this file lives at the *root* of\n * `dist/`, not under `dist/internal/` — the path is relative to that, to line\n * up with where `scripts/copy-wasm.mjs` copies `crates/reactor-wasm/pkg`\n * (`dist/wasm/`).\n *\n * That module carries the `.wasm` binary inlined (see copy-wasm.mjs), so a\n * consumer's bundler only has to follow this one relative `import()` — which\n * every bundler does, and turns into a separate chunk fetched on first use.\n * Nothing else has to stay reachable at a fixed location next to it.\n *\n * The specifier is inlined directly in the `import()` call below, not\n * hoisted to a `const`, and not marked `@vite-ignore` — bundlers only resolve\n * a literal argument statically. Routed through an intermediate binding,\n * webpack can't trace it back to a literal and throws \"Critical dependency:\n * the request of a dependency is an expression\" at runtime; marked ignored,\n * Vite leaves it as a bare relative path that breaks as soon as Vite moves\n * this file (its dependency optimizer, or a production build).\n */\n\nexport function loadReactorWasm(): Promise<ReactorWasmModule> {\n if (!modulePromise) {\n modulePromise = importWasmModule().catch((cause) => {\n // Don't cache a failed load — a transient fetch failure shouldn't\n // permanently poison every later `Reactor` in the page.\n modulePromise = null;\n throw new Error(`reactor-wasm failed to load: ${describeCause(cause)}`, { cause });\n });\n }\n return modulePromise;\n}\n\nasync function importWasmModule(): Promise<ReactorWasmModule> {\n // @ts-expect-error — no declaration file to resolve at typecheck time; the\n // module only exists after scripts/copy-wasm.mjs copies it into dist/wasm,\n // post-build. Cast to ReactorWasmModule below instead.\n const module = (await import('./wasm/reactor_wasm.js')) as ReactorWasmModule;\n\n await module.default();\n return module;\n}\n\n/** The underlying failure, named in the message itself rather than only in\n * `cause` — plenty of error reporting (and `String(error)`) never looks at\n * `cause`, and \"failed to load\" alone gives nothing to act on. */\nfunction describeCause(cause: unknown): string {\n if (cause instanceof Error) {\n return cause.message ? `${cause.name}: ${cause.message}` : cause.name;\n }\n return String(cause);\n}\n","{\n \"name\": \"@reactor-team/js-sdk\",\n \"version\": \"3.4.0\",\n \"description\": \"Connect your JavaScript/TypeScript app to a live Reactor model in the browser.\",\n \"license\": \"Apache-2.0\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/reactor-team/reactor-client-sdks.git\",\n \"directory\": \"sdks/js\"\n },\n \"type\": \"module\",\n \"sideEffects\": false,\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\",\n \"require\": \"./dist/index.cjs\"\n }\n },\n \"files\": [\n \"dist\"\n ],\n \"engines\": {\n \"node\": \">=18\"\n },\n \"scripts\": {\n \"build\": \"tsup && node scripts/copy-wasm.mjs\",\n \"prepack\": \"npm run build\",\n \"dev\": \"tsup --watch\",\n \"type-check\": \"tsc --noEmit\",\n \"lint\": \"eslint .\",\n \"test\": \"vitest run\",\n \"clean\": \"rm -rf dist\"\n },\n \"dependencies\": {\n \"awaitqueue\": \"^3.3.1\",\n \"hls.js\": \"^1.6.0\",\n \"mp4box\": \"^2.4.1\"\n },\n \"peerDependencies\": {\n \"react\": \"^18.0.0 || ^19.0.0\"\n },\n \"devDependencies\": {\n \"@eslint/js\": \"^9.39.5\",\n \"@stylistic/eslint-plugin\": \"^5.10.0\",\n \"@testing-library/react\": \"^16.0.0\",\n \"@types/react\": \"^19.0.0\",\n \"eslint\": \"^9.39.5\",\n \"eslint-plugin-react-hooks\": \"^5.0.0\",\n \"jsdom\": \"^25.0.0\",\n \"react\": \"^19.0.0\",\n \"react-dom\": \"^19.0.0\",\n \"tsup\": \"^8.3.0\",\n \"typescript\": \"^5.6.0\",\n \"typescript-eslint\": \"^8.67.0\",\n \"vitest\": \"^4.1.11\"\n }\n}\n","import type { JwtRequestContext, JwtSource } from '../types';\n\n/** Resolves a `JwtSource` (a plain string, or a resolver called at request\n * time with `context`) to a plain string — shared by the clip surfaces,\n * which fall back to a `ReactorProvider`'s own `JwtSource` when no explicit\n * resolver is passed. */\nexport async function resolveJwtSource(source: JwtSource, context?: JwtRequestContext): Promise<string> {\n return typeof source === 'function' ? source(context) : source;\n}\n","/**\n * Browser-side primitives for turning a `Clip` (from `requestClip()` /\n * `requestRecording()`) into playable or downloadable media.\n *\n * `Clip.playlistUrl` names an HLS media playlist — `#EXT-X-VERSION:7`\n * fragmented MP4, an `#EXT-X-MAP` init segment followed by `.m4s` media\n * fragments — that the caller fetches and assembles; Reactor itself doesn't\n * host clips. This module owns fetching and parsing that playlist\n * (`fetchPlaylist` / `parsePlaylist`), wrapping it for a `<video>` element or\n * `hls.js` (`createPlayableManifestUrl`), and assembling the referenced\n * chunks into a flat, downloadable MP4 (`downloadClipAsFile`).\n */\n\nimport type * as MP4BoxTypes from 'mp4box';\nimport { resolveJwtSource } from './internal/jwt-resolver';\nimport type { Clip, JwtRequestContext, JwtSource } from './types';\n\n/**\n * Error thrown when a clip's playlist or chunks can't be fetched, parsed, or\n * assembled into a file. Scoped to this module — a failure in\n * `requestClip()` / `requestRecording()` themselves surfaces as a\n * `ReactorError`, since those go through `reactor-core`'s own error channel.\n *\n * `code` is a stable, machine-readable identifier; `reason` is the raw\n * string behind it (an HTTP status, a parse complaint, …).\n */\nexport class RecordingError extends Error {\n constructor(\n public readonly code:\n | 'CLIP_GONE'\n | 'CLIP_NOT_READY'\n | 'PLAYLIST_FETCH_FAILED'\n | 'CHUNK_FETCH_FAILED'\n | 'INVALID_PLAYLIST'\n | 'DOWNLOAD_UNSUPPORTED',\n public readonly reason: string,\n ) {\n super(`${code}: ${reason}`);\n this.name = 'RecordingError';\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// HLS playlist fetching + parsing\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Segments referenced by an HLS manifest, in playback order. */\ninterface ParsedPlaylist {\n initUrl: string;\n segmentUrls: string[];\n}\n\n/**\n * Suggested grace period for callers that opt into a bounded wait by passing\n * it as `FetchPlaylistOptions.slackMs`. Not a default — `fetchPlaylist()`\n * polls indefinitely unless a bound is supplied.\n */\nexport const DEFAULT_PLAYLIST_POLL_SLACK_MS = 15_000;\n\nexport interface FetchPlaylistOptions {\n /**\n * Unix epoch (ms) when the runtime predicts the boundary chunk will be\n * servable — pass `clip.predictedReadyAtMs`. On its own this doesn't stop\n * polling; it only anchors the optional `slackMs` deadline.\n */\n predictedReadyAtMs?: number;\n /**\n * Opt-in grace period that turns polling into a bounded wait: a stuck\n * `202` produces `CLIP_NOT_READY` once `max(predictedReadyAtMs, pollStart)\n * + slackMs` passes. Omit (the default) to poll indefinitely until the\n * manifest is ready or the caller aborts via `signal`.\n */\n slackMs?: number;\n /** Hard cap on the per-poll wait. `Retry-After` is honored but clamped. Default 2000 ms. */\n maxRetryDelayMs?: number;\n /** Floor on the per-poll wait so a cheap network doesn't hot-loop. Default 200 ms. */\n minRetryDelayMs?: number;\n /**\n * Opt-in cap on the number of `202` responses tolerated before\n * `CLIP_NOT_READY`. Omit (the default) to poll indefinitely.\n */\n maxRetries?: number;\n /**\n * Aborts in-flight fetches and the inter-poll sleep — the primary way to\n * end an unbounded wait (a timeout, a user cancel, a component unmount).\n */\n signal?: AbortSignal;\n /**\n * Coordinator JWT for the manifest GET: a string, or a resolver called\n * before every poll with `{ sessionId }`, so a long 202 wait can cross a\n * token refresh. Omit in local mode (HttpRuntime).\n */\n jwt?: JwtSource;\n /** The clip's session, handed to a resolver `jwt`. `downloadClipAsFile()`\n * fills it from `clip.sessionId`. */\n sessionId?: string;\n}\n\n/**\n * Fetch `playlistUrl`, polling on `202 Accepted` — returned while the\n * boundary chunk is still uploading.\n *\n * - `200` → the manifest body.\n * - `410` / `404` → `CLIP_GONE`.\n * - other → `PLAYLIST_FETCH_FAILED` (no retry).\n * - `202` past an opt-in `slackMs` deadline or `maxRetries` cap → `CLIP_NOT_READY`.\n * - aborted `signal` → rejects with the fetch/sleep `AbortError`.\n */\nexport async function fetchPlaylist(\n playlistUrl: string,\n options: FetchPlaylistOptions = {},\n): Promise<string> {\n const minDelay = Math.max(0, options.minRetryDelayMs ?? 200);\n const maxDelay = Math.max(minDelay, options.maxRetryDelayMs ?? 2_000);\n\n const hasDeadline = typeof options.slackMs === 'number' && Number.isFinite(options.slackMs);\n // Anchored at max(predictedReadyAtMs, now) so a late start still gets the\n // full grace window rather than a deadline already in the past.\n const startedPollingAt = Date.now();\n const deadlineMs = hasDeadline\n ? Math.max(options.predictedReadyAtMs ?? startedPollingAt, startedPollingAt) +\n (options.slackMs as number)\n : undefined;\n const maxRetries = typeof options.maxRetries === 'number' ? options.maxRetries : undefined;\n\n let attempt = 0;\n\n while (true) {\n const init: RequestInit = {};\n\n if (options.signal) {\n init.signal = options.signal;\n }\n // Resolved per poll, not once: a 202 wait can outlive the token it\n // started with, and the resolver is where a fresh one comes from.\n const jwt = await resolveManifestJwt(options);\n\n if (jwt) {\n init.headers = { Authorization: `Bearer ${jwt}` };\n }\n\n let response: Response;\n\n try {\n response = await fetch(playlistUrl, init);\n } catch (error) {\n if (isAbortError(error)) {\n throw error;\n }\n throw new RecordingError(\n 'PLAYLIST_FETCH_FAILED',\n `Network error fetching playlist: ${(error as Error).message}`,\n );\n }\n\n // 202 is in the 2xx range, so it has to be checked before response.ok.\n if (response.status === 202) {\n if (deadlineMs !== undefined && Date.now() >= deadlineMs) {\n throw new RecordingError(\n 'CLIP_NOT_READY',\n `Boundary chunk still pending after ${options.slackMs}ms grace (predicted ready ${new Date(\n options.predictedReadyAtMs ?? startedPollingAt,\n ).toISOString()}). Runtime may have crashed mid-clip.`,\n );\n }\n if (maxRetries !== undefined && attempt >= maxRetries) {\n throw new RecordingError(\n 'CLIP_NOT_READY',\n `Manifest still pending after ${attempt + 1} attempts (last status 202)`,\n );\n }\n\n const headerDelay = parseRetryAfter(response.headers.get('Retry-After'), minDelay);\n const delay = Math.min(maxDelay, Math.max(minDelay, headerDelay));\n const clampedDelay =\n deadlineMs !== undefined ? Math.min(delay, Math.max(0, deadlineMs - Date.now())) : delay;\n\n await sleep(clampedDelay, options.signal);\n attempt++;\n continue;\n }\n\n if (response.status === 200) {\n return await response.text();\n }\n if (response.status === 410 || response.status === 404) {\n throw new RecordingError('CLIP_GONE', 'Clip is no longer available or session unknown');\n }\n throw new RecordingError('PLAYLIST_FETCH_FAILED', `Manifest endpoint returned HTTP ${response.status}`);\n }\n}\n\n/**\n * Parse an HLS `.m3u8` body into the init segment URL plus the ordered media\n * segment URLs, resolving relative URLs against `playlistUrl` itself.\n */\nexport function parsePlaylist(manifestBody: string, playlistUrl: string): ParsedPlaylist {\n let initUrl: string | undefined;\n const segments: string[] = [];\n\n for (const rawLine of manifestBody.split(/\\r?\\n/)) {\n const trimmed = rawLine.trim();\n\n if (!trimmed) {\n continue;\n }\n\n if (trimmed.startsWith('#EXT-X-MAP')) {\n const match = trimmed.match(/URI=\"([^\"]+)\"/);\n\n if (match?.[1]) {\n initUrl = resolveAgainst(match[1], playlistUrl);\n }\n continue;\n }\n if (trimmed.startsWith('#')) {\n continue;\n }\n segments.push(resolveAgainst(trimmed, playlistUrl));\n }\n\n if (!initUrl) {\n throw new RecordingError('INVALID_PLAYLIST', 'Playlist is missing an #EXT-X-MAP init segment URI');\n }\n if (segments.length === 0) {\n throw new RecordingError('INVALID_PLAYLIST', 'Playlist contains no media segments');\n }\n\n return { initUrl, segmentUrls: segments };\n}\n\n/**\n * Wrap an HLS manifest body in a `blob:` URL suitable for `<video src>` or\n * `hls.js`. Bypasses \"the player can't set an Authorization header\": the\n * manifest is served from memory, and its chunk URLs are already-signed S3\n * GETs. Path-only chunk URLs in the body are absolutized against\n * `playlistUrl` first — without that, the browser would resolve them against\n * the `blob:` URL's own origin instead of the runtime's.\n *\n * Caller owns the returned URL — revoke it via `URL.revokeObjectURL` when\n * playback tears down. Browser-only; throws `INVALID_PLAYLIST` outside a DOM\n * environment.\n */\nexport function createPlayableManifestUrl(manifestBody: string, playlistUrl: string): string {\n if (\n typeof Blob === 'undefined' ||\n typeof URL === 'undefined' ||\n typeof URL.createObjectURL !== 'function'\n ) {\n throw new RecordingError(\n 'INVALID_PLAYLIST',\n 'createPlayableManifestUrl requires a browser environment with URL.createObjectURL',\n );\n }\n const rewritten = absolutizeManifestUrls(manifestBody, playlistUrl);\n const blob = new Blob([rewritten], { type: 'application/vnd.apple.mpegurl' });\n\n return URL.createObjectURL(blob);\n}\n\nfunction absolutizeManifestUrls(manifestBody: string, playlistUrl: string): string {\n const eol = manifestBody.includes('\\r\\n') ? '\\r\\n' : '\\n';\n const out: string[] = [];\n\n for (const line of manifestBody.split(/\\r?\\n/)) {\n if (line.startsWith('#EXT-X-MAP')) {\n out.push(\n line.replace(/URI=\"([^\"]+)\"/, (_: string, uri: string) => `URI=\"${resolveAgainst(uri, playlistUrl)}\"`),\n );\n continue;\n }\n const trimmed = line.trim();\n\n if (!trimmed || trimmed.startsWith('#')) {\n out.push(line);\n continue;\n }\n out.push(resolveAgainst(trimmed, playlistUrl));\n }\n return out.join(eol);\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// downloadClipAsFile\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface DownloadClipOptions {\n /** Coordinator JWT for the manifest GET: a string, or a resolver called\n * per poll with `{ sessionId: clip.sessionId }`. The chunks the manifest\n * references are S3 presigned URLs, fetched unauthenticated. */\n jwt?: JwtSource;\n /** Cancels both the playlist poll and any in-flight chunk fetches. */\n signal?: AbortSignal;\n /** Called after each chunk completes — useful for progress UI. */\n onProgress?: (info: { fetched: number; total: number; bytes: number }) => void;\n}\n\n/**\n * Fetch the chunks `clip.playlistUrl` references, remux them into a flat\n * MP4, and (when `filename` is non-null) trigger a browser `<a download>`.\n * Pass `filename: null` to skip the download trigger and just get the Blob.\n *\n * See {@link assembleClipBlob} for the remux and memory-bound caveats.\n */\nexport async function downloadClipAsFile(\n clip: Clip,\n filename: string | null = 'reactor-clip.mp4',\n options: DownloadClipOptions = {},\n): Promise<Blob> {\n const playlistOptions: FetchPlaylistOptions = {\n predictedReadyAtMs: clip.predictedReadyAtMs,\n sessionId: clip.sessionId,\n };\n\n if (options.signal) {\n playlistOptions.signal = options.signal;\n }\n if (options.jwt) {\n playlistOptions.jwt = options.jwt;\n }\n\n const manifestBody = await fetchPlaylist(clip.playlistUrl, playlistOptions);\n const blob = await assembleClipBlob(manifestBody, clip.playlistUrl, options);\n\n if (filename === null) {\n return blob;\n }\n if (typeof document === 'undefined' || typeof URL.createObjectURL !== 'function') {\n throw new RecordingError(\n 'DOWNLOAD_UNSUPPORTED',\n 'downloadClipAsFile requires a DOM environment; pass filename=null to skip the download trigger',\n );\n }\n triggerBrowserDownload(blob, filename);\n return blob;\n}\n\nexport interface AssembleClipOptions {\n /** Cancels any in-flight chunk fetches. */\n signal?: AbortSignal;\n /** Called after each chunk completes — useful for progress UI. */\n onProgress?: (info: { fetched: number; total: number; bytes: number }) => void;\n}\n\n/**\n * Fetch the chunks an already-fetched `manifestBody` references and remux\n * them into a flat MP4 Blob. Split out of {@link downloadClipAsFile} so\n * `ClipPlayer`'s MP4 fallback path can reuse it against the manifest it\n * already has, instead of fetching the playlist a second time.\n *\n * The remux rewrites the container only — H.264 NAL units and AAC packets\n * pass through unchanged — so `start_time=0`, faststart, and\n * `major_brand=isom` come for free with no re-encode. See `maybeRemux()` for\n * the fallback on the rare parse failure.\n *\n * Memory-bound: every chunk is held in `parts` for the full duration of the\n * fetch loop, and `maybeRemux()`'s underlying `mp4box` parser needs the whole\n * input up front, so there's no streaming path to disk. Fine for a bounded\n * clip; a full-session `requestRecording()` download can hold the entire\n * recording in memory at once.\n */\nexport async function assembleClipBlob(\n manifestBody: string,\n playlistUrl: string,\n options: AssembleClipOptions = {},\n): Promise<Blob> {\n const { initUrl, segmentUrls } = parsePlaylist(manifestBody, playlistUrl);\n const orderedUrls = [initUrl, ...segmentUrls];\n const chunkInit: RequestInit = {};\n\n if (options.signal) {\n chunkInit.signal = options.signal;\n }\n\n const parts: Uint8Array[] = [];\n let bytes = 0;\n\n for (const [i, url] of orderedUrls.entries()) {\n let response: Response;\n\n try {\n response = await fetch(url, chunkInit);\n } catch (error) {\n if (isAbortError(error)) {\n throw error;\n }\n throw new RecordingError('CHUNK_FETCH_FAILED', `Network error fetching chunk ${i}: ${(error as Error).message}`);\n }\n if (!response.ok) {\n throw new RecordingError('CHUNK_FETCH_FAILED', `Chunk ${i} returned HTTP ${response.status}`);\n }\n const data = new Uint8Array(await response.arrayBuffer());\n\n parts.push(data);\n bytes += data.byteLength;\n options.onProgress?.({ fetched: i + 1, total: orderedUrls.length, bytes });\n }\n\n const finalBytes = await maybeRemux(parts);\n\n return new Blob([finalBytes as BlobPart], { type: 'video/mp4' });\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Fragmented MP4 → flat MP4 remux\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Concatenate `parts` and pipe the result through `remuxFragmentedToFlat()`.\n * Remux failures (`mp4box` blocked by an exotic bundler/CSP, corrupt input,\n * an unsupported codec) are funneled through one path: a `console.warn` and\n * the unmodified concatenation, so the download still succeeds end-to-end\n * with the (worse, but still playable) fragmented MP4 the runtime emitted.\n */\nasync function maybeRemux(parts: Uint8Array[]): Promise<Uint8Array> {\n const input = concatUint8Arrays(parts);\n\n try {\n const MP4Box = await loadMp4Box();\n\n return await remuxFragmentedToFlat(input, MP4Box);\n } catch (error) {\n console.warn('[Reactor] Clip remux failed, returning fragmented MP4 instead.', error);\n return input;\n }\n}\n\n/** Indirection so tests can stub the dynamic `mp4box` import without pulling\n * the real bytes through every test that calls `downloadClipAsFile`.\n * @internal */\nexport const __remuxInternals = {\n loadMp4Box: (): Promise<typeof MP4BoxTypes> => import('mp4box'),\n};\n\nfunction loadMp4Box(): Promise<typeof MP4BoxTypes> {\n return __remuxInternals.loadMp4Box();\n}\n\n/**\n * The actual fMP4 → flat MP4 conversion. No re-encode: every NAL unit and AAC\n * packet passes through unchanged. Only the container framing (boxes) and\n * decode timestamps are rewritten.\n *\n * The output file is initialized with `[\"isom\", \"mp42\", \"avc1\", \"iso2\"]` as\n * compatible brands so the major brand is `isom` (not `iso5`, what\n * byte-concatenated fragments default to) and the sample tables are written\n * ahead of `mdat` — i.e. the file is implicitly faststart. Decode times are\n * shifted by one shared presentation-time origin across every track — the\n * earliest first-sample time, converted through each track's own timescale\n * — so the output starts at (close to) `0.000000` while the original\n * inter-track offset (e.g. audio starting slightly before or after video)\n * is preserved rather than each track independently zeroing to its own\n * first sample.\n */\nasync function remuxFragmentedToFlat(\n input: Uint8Array,\n MP4Box: typeof MP4BoxTypes,\n): Promise<Uint8Array> {\n return new Promise<Uint8Array>((resolve, reject) => {\n const inFile = MP4Box.createFile();\n const outFile = MP4Box.createFile();\n\n outFile.init({ brands: ['isom', 'mp42', 'avc1', 'iso2'] });\n\n interface PendingTrack {\n trackOptions: MP4BoxTypes.IsoFileOptions;\n timescale: number;\n firstDts: number;\n samples: MP4BoxTypes.Sample[];\n }\n\n const pendingTracks = new Map<number, PendingTrack>();\n let settled = false;\n\n const fail = (err: Error) => {\n if (settled) {\n return;\n }\n settled = true;\n reject(err);\n };\n\n inFile.onError = (_module: string, message: string) => {\n fail(new Error(message));\n };\n\n inFile.onReady = (info) => {\n if (!info.tracks.length) {\n fail(new Error('no tracks in input'));\n return;\n }\n for (const track of info.tracks) {\n // setExtractionOptions delivers samples in batches via onSamples;\n // nbSamples controls batch size only, not the total.\n inFile.setExtractionOptions(track.id, null, { nbSamples: 1000 });\n }\n inFile.start();\n };\n\n // Samples are buffered per track (not written to outFile yet) because\n // the shared origin below needs every track's first sample DTS, and\n // tracks arrive interleaved as fragments are parsed.\n inFile.onSamples = (id, _user, samples) => {\n if (settled || samples.length === 0) {\n return;\n }\n\n let pending = pendingTracks.get(id);\n\n if (!pending) {\n // The sample carries the parsed input SampleEntry (avc1 / mp4a / …)\n // whose child boxes are the actual codec config (avcC, esds, …).\n // addTrack creates a fresh empty SampleEntry of the requested type,\n // so the input's child boxes are passed via description_boxes: they\n // become direct children of the new SampleEntry, where decoders\n // expect them. Passing the whole input SampleEntry as `description`\n // instead would nest it (stsd > avc1 > avc1 > avcC) and decoders\n // would fail to find avcC and render black.\n const firstSample = samples[0];\n\n if (!firstSample) {\n return;\n }\n\n const sampleEntry = firstSample.description as MP4BoxTypes.SampleEntry;\n const inputTrack = trackInfoById(inFile, id);\n const trackOptions: MP4BoxTypes.IsoFileOptions = {\n type: sampleEntry.type as MP4BoxTypes.SampleEntryFourCC,\n timescale: firstSample.timescale,\n // `boxes` is typed as `Box[]` but `description_boxes` wants the\n // narrower `BoxKind[]` union — at runtime they're the same\n // concrete instances, just typed loosely.\n description_boxes: sampleEntry.boxes as unknown as MP4BoxTypes.BoxKind[],\n };\n\n if (inputTrack?.track_width !== undefined) {\n trackOptions.width = inputTrack.track_width;\n }\n if (inputTrack?.track_height !== undefined) {\n trackOptions.height = inputTrack.track_height;\n }\n if (inputTrack?.language !== undefined) {\n trackOptions.language = inputTrack.language;\n }\n if (inputTrack?.video) {\n trackOptions.hdlr = 'vide';\n } else if (inputTrack?.audio) {\n trackOptions.hdlr = 'soun';\n }\n\n pending = { trackOptions, timescale: firstSample.timescale, firstDts: firstSample.dts, samples: [] };\n pendingTracks.set(id, pending);\n }\n\n pending.samples.push(...samples);\n };\n\n let buf: MP4BoxTypes.MP4BoxBuffer;\n\n try {\n buf = MP4Box.MP4BoxBuffer.fromArrayBuffer(\n input.buffer.slice(input.byteOffset, input.byteOffset + input.byteLength),\n 0,\n );\n } catch (error) {\n fail(error as Error);\n return;\n }\n\n try {\n inFile.appendBuffer(buf);\n inFile.flush();\n } catch (error) {\n fail(error as Error);\n return;\n }\n\n if (settled) {\n return;\n }\n if (pendingTracks.size === 0) {\n fail(new Error('no samples extracted from input'));\n return;\n }\n\n let originSeconds = Infinity;\n\n for (const pending of pendingTracks.values()) {\n originSeconds = Math.min(originSeconds, pending.firstDts / pending.timescale);\n }\n\n try {\n for (const pending of pendingTracks.values()) {\n const outId = outFile.addTrack(pending.trackOptions);\n const dtsShift = Math.round(originSeconds * pending.timescale);\n\n for (const sample of pending.samples) {\n if (!sample.data) {\n continue;\n }\n outFile.addSample(outId, sample.data, {\n duration: sample.duration,\n dts: sample.dts - dtsShift,\n cts: sample.cts - dtsShift,\n is_sync: sample.is_sync,\n });\n }\n }\n } catch (error) {\n fail(error as Error);\n return;\n }\n\n let output: Uint8Array;\n\n try {\n const stream = outFile.getBuffer();\n\n output = new Uint8Array(stream.buffer.slice(0, stream.byteLength));\n } catch (error) {\n fail(error as Error);\n return;\n }\n\n settled = true;\n resolve(output);\n });\n}\n\nfunction trackInfoById(file: MP4BoxTypes.ISOFile, id: number): MP4BoxTypes.Track | undefined {\n const info = file.getInfo();\n\n return info.tracks.find((t) => t.id === id);\n}\n\nfunction concatUint8Arrays(parts: Uint8Array[]): Uint8Array {\n const only = parts.length === 1 ? parts[0] : undefined;\n\n if (only) {\n return only;\n }\n\n let total = 0;\n\n for (const p of parts) {total += p.byteLength;}\n\n const out = new Uint8Array(total);\n let offset = 0;\n\n for (const p of parts) {\n out.set(p, offset);\n offset += p.byteLength;\n }\n return out;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Internal helpers\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction isAbortError(error: unknown): boolean {\n return error instanceof DOMException && error.name === 'AbortError';\n}\n\nfunction resolveAgainst(target: string, base: string): string {\n try {\n return new URL(target, base).toString();\n } catch {\n return target;\n }\n}\n\nfunction parseRetryAfter(header: string | null, fallbackMs: number): number {\n if (!header) {\n return fallbackMs;\n }\n\n const seconds = Number(header);\n\n if (Number.isFinite(seconds) && seconds >= 0) {\n return seconds * 1000;\n }\n const dateMs = Date.parse(header);\n\n if (!Number.isNaN(dateMs)) {\n return Math.max(0, dateMs - Date.now());\n }\n return fallbackMs;\n}\n\nasync function resolveManifestJwt(options: FetchPlaylistOptions): Promise<string | undefined> {\n if (options.jwt === undefined) {\n return undefined;\n }\n const context: JwtRequestContext = options.sessionId === undefined ? {} : { sessionId: options.sessionId };\n\n return abortable(resolveJwtSource(options.jwt, context), options.signal);\n}\n\n// Settles with `promise`, or rejects as soon as `signal` aborts. The resolver\n// itself keeps running; nothing here can stop it.\nfunction abortable<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {\n if (!signal) {\n return promise;\n }\n return new Promise((resolve, reject) => {\n const onAbort = () => reject(new DOMException('Aborted', 'AbortError'));\n\n if (signal.aborted) {\n onAbort();\n } else {\n signal.addEventListener('abort', onAbort, { once: true });\n }\n void promise.then(resolve, reject).finally(() => signal.removeEventListener('abort', onAbort));\n });\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(new DOMException('Aborted', 'AbortError'));\n return;\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(timer);\n reject(new DOMException('Aborted', 'AbortError'));\n };\n\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\nfunction triggerBrowserDownload(blob: Blob, filename: string): void {\n const objectUrl = URL.createObjectURL(blob);\n\n try {\n const a = document.createElement('a');\n\n a.href = objectUrl;\n a.download = filename;\n a.style.display = 'none';\n document.body.appendChild(a);\n a.click();\n a.remove();\n } finally {\n URL.revokeObjectURL(objectUrl);\n }\n}\n","import type { StepFrame } from './types';\n\n/**\n * A step's video frame as an `ImageData`, ready for a canvas's\n * `putImageData()` (or `createImageBitmap()`).\n *\n * A step's video frames are `(height, width, 3)` `uint8` RGB; a canvas wants\n * RGBA, so this adds an opaque alpha. Throws on any other frame — an audio\n * frame, or a dtype or shape that is not RGB video.\n */\nexport function stepFrameToImageData(frame: StepFrame): ImageData {\n const [height, width, channels] = frame.shape;\n\n if (\n frame.dtype !== 'uint8' ||\n frame.shape.length !== 3 ||\n channels !== 3 ||\n height === undefined ||\n width === undefined ||\n frame.data.length !== width * height * 3\n ) {\n throw new Error(\n `stepFrameToImageData: expected a (height, width, 3) uint8 RGB frame, got ${frame.dtype} [${frame.shape.join(', ')}]`,\n );\n }\n const rgb = frame.data as Uint8Array;\n const rgba = new Uint8ClampedArray(width * height * 4);\n\n for (let src = 0, dst = 0; src < rgb.length; src += 3, dst += 4) {\n rgba[dst] = rgb[src]!;\n rgba[dst + 1] = rgb[src + 1]!;\n rgba[dst + 2] = rgb[src + 2]!;\n rgba[dst + 3] = 255;\n }\n return new ImageData(rgba, width, height);\n}\n","import type { JwtRequestContext, JwtSource } from './types';\n\n/** Lazy resolver for a Coordinator/runtime bearer token, called immediately\n * before each authenticated request with the session that request is for —\n * see `JwtSource` and `JwtRequestContext`. A resolver that ignores the\n * context keeps working. */\nexport type JwtResolver = (context?: JwtRequestContext) => string | Promise<string>;\n\n/**\n * Wraps a `JwtSource` into a `JwtResolver`: a static string becomes a\n * resolver that always returns it, a resolver passes through unchanged.\n * Useful for feeding a source that may be either form (e.g. a\n * `ReactorProvider`'s `jwtToken`) into a `getJwt` prop that expects a\n * resolver.\n */\nexport function normalizeJwtSource(source: JwtSource): JwtResolver {\n if (typeof source === 'function') {\n return source;\n }\n return () => source;\n}\n","'use client';\n\nimport { createContext, useContext, useEffect, useRef, useState, useSyncExternalStore, type ReactNode } from 'react';\nimport { createReactorStore, type ReactorStore, type StoreApi } from './store';\nimport type { ConnectOptions, JwtSource, ReactorOptions, TrackCapability } from '../types';\n\n/** `connectOptions` for the provider — adds `autoConnect` to the core\n * `ConnectOptions`. Live, same as every other `ReactorProviderProps` field —\n * see `ReactorProvider`'s doc comment. */\nexport interface ReactorConnectOptions extends ConnectOptions {\n /** Connect automatically once a Reactor is built — initial mount, or any\n * later rebuild. Default `false`. */\n autoConnect?: boolean;\n}\n\nexport interface ReactorProviderProps {\n apiUrl?: string | undefined;\n modelName: string;\n local?: boolean | undefined;\n /** Media tracks to declare up front, so the transport can prepare the SDP\n * offer in parallel with session polling instead of waiting to discover\n * them from the model's schema. */\n modelTracks?: TrackCapability[] | undefined;\n /** Static token, or a resolver called before every authenticated request\n * — see `JwtSource`. Required for `autoConnect` against a non-local\n * runtime; can also be supplied later via an explicit `connect()` call\n * instead. */\n jwtToken?: JwtSource | undefined;\n connectOptions?: ReactorConnectOptions | undefined;\n children?: ReactNode;\n}\n\n/** Exported so a component can optionally read the nearest provider's store\n * without requiring one — e.g. `ClipPlayer`, which works both inside and\n * outside a `ReactorProvider`. Most consumers want `useReactor`/`useReactorStore`\n * instead, which throw outside a provider rather than returning `undefined`. */\nexport const ReactorContext = createContext<StoreApi<ReactorStore> | undefined>(undefined);\n\ntype BuildStoreProps = Pick<\n ReactorProviderProps,\n 'apiUrl' | 'modelName' | 'local' | 'modelTracks' | 'jwtToken' | 'connectOptions'\n>;\n\n/**\n * Builds a fresh store (and the `Reactor` underneath) from the provider's\n * props, firing `connect()` immediately when `autoConnect` is set. Used for\n * both the initial mount and every later rebuild, so both go through the\n * same auto-connect path rather than only the first one.\n */\nfunction buildStore({\n apiUrl,\n modelName,\n local,\n modelTracks,\n jwtToken,\n connectOptions,\n}: BuildStoreProps): StoreApi<ReactorStore> {\n // Built up field-by-field, not as one object literal, so an omitted prop\n // stays omitted rather than becoming an explicit `undefined` — required\n // under `exactOptionalPropertyTypes`.\n const options: ReactorOptions = { modelName };\n\n if (apiUrl !== undefined) {\n options.apiUrl = apiUrl;\n }\n if (local !== undefined) {\n options.local = local;\n }\n if (modelTracks !== undefined) {\n options.modelTracks = modelTracks;\n }\n if (jwtToken !== undefined) {\n options.jwt = jwtToken;\n }\n\n // `autoConnect` isn't acted on here — see the effect in `ReactorProvider`\n // that fires it. `ConnectOptions` (unlike `ReactorConnectOptions`) has no\n // `autoConnect` field, so it's stripped before this is stored as the\n // store's `defaultConnectOptions`.\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { autoConnect, ...pollingOptions } = connectOptions ?? {};\n\n return createReactorStore(options, pollingOptions);\n}\n\n/**\n * Owns a `Reactor` instance and exposes it to `useReactor` below.\n *\n * `apiUrl`/`modelName`/`local`/`modelTracks`/`jwtToken`/`connectOptions`\n * (including `autoConnect`) are live: changing any of them tears down the\n * current `Reactor` (`disconnect()` then `[Symbol.dispose]()`) and builds a\n * fresh one — the same way `useLiveKitRoom` rebuilds its `Room` when its\n * construction `options` change. `Reactor` has no equivalent of LiveKit's\n * `token`/`serverUrl` split (reconnecting the *same* instance with new\n * credentials) or its live `connect` boolean (toggling the same `Room`'s\n * connection without rebuilding it) — its constructor bundles everything, so\n * any change, `autoConnect` included, means a fresh instance rather than\n * reconnecting/disconnecting the existing one. Pass a stable `jwtToken`\n * (e.g. via `useCallback` for a resolver) and stable `modelTracks`/\n * `connectOptions` references if you don't want an unrelated parent render to\n * rebuild the connection — object/array props are compared by reference\n * (`modelTracks`/`connectOptions` via a `JSON.stringify` snapshot, same as\n * `useLiveKitRoom` does for its own `options`).\n *\n * Unmounting tears down the same way — see `Reactor.disconnect()`/\n * `[Symbol.dispose]()` for what that frees.\n */\nexport function ReactorProvider({\n apiUrl,\n modelName,\n local,\n modelTracks,\n jwtToken,\n connectOptions,\n children,\n}: ReactorProviderProps) {\n const [store, setStore] = useState(() =>\n buildStore({ apiUrl, modelName, local, modelTracks, jwtToken, connectOptions }),\n );\n // Skips the rebuild effect's mandatory first run — the initial store was\n // already built synchronously above, so re-running the same construction\n // on mount would just replace it with an equivalent one for nothing.\n const isFirstRun = useRef(true);\n\n useEffect(() => {\n if (isFirstRun.current) {\n isFirstRun.current = false;\n\n return;\n }\n setStore(buildStore({ apiUrl, modelName, local, modelTracks, jwtToken, connectOptions }));\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [apiUrl, modelName, local, JSON.stringify(modelTracks), jwtToken, JSON.stringify(connectOptions)]);\n\n // Fires autoConnect for whichever Reactor this provider currently owns —\n // on initial mount and on every rebuild, since both produce a new `store`.\n // Deliberately an effect, not part of `buildStore`'s synchronous\n // construction: `buildStore` runs inside `useState`'s lazy initializer,\n // and React 18 StrictMode double-invokes that during render to surface\n // impure side effects — calling connect() from there fires it against two\n // separate, independently-constructed Reactor instances, and the discarded\n // one leaks a live connection nothing ever tears down. Matches v2, which\n // also fires autoConnect from an effect rather than during construction.\n useEffect(() => {\n const { autoConnect = false, ...pollingOptions } = connectOptions ?? {};\n\n if (autoConnect && store.getState().status === 'disconnected') {\n // A rejection here (auth/network failure, ...) would otherwise escape\n // as an unhandled promise rejection — connect() throws rather than\n // reporting failures through the `error` event, and nothing here\n // awaits this fire-and-forget call.\n store.getState().connect(jwtToken, pollingOptions).catch((error: unknown) => {\n console.error('[Reactor.ReactorProvider] autoConnect failed:', error);\n });\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [store]);\n\n // Tears down whichever Reactor this provider currently owns — on rebuild\n // (store changes, so this cleanup fires for the one being replaced) and on\n // final unmount. disconnect() first (ends the session server-side; a bare\n // [Symbol.dispose]() skips that), then dispose to free local resources for\n // good and stop the store's event listeners from lingering on a Reactor\n // nothing references any more.\n useEffect(() => {\n return () => {\n const reactor = store.getState().internal.reactor;\n\n void reactor.disconnect().finally(() => reactor[Symbol.dispose]());\n };\n }, [store]);\n\n return <ReactorContext.Provider value={store}>{children}</ReactorContext.Provider>;\n}\n\n/** Reads the store directly, with whatever equality behavior `selector`\n * itself implies — most callers want `useReactor` instead, which adds\n * shallow comparison. Throws outside a `ReactorProvider`. */\nexport function useReactorStore<T>(selector: (state: ReactorStore) => T): T {\n const store = useContext(ReactorContext);\n\n if (store === undefined) {\n throw new Error('useReactor must be used within a ReactorProvider');\n }\n\n // The same function serves as both snapshots: `createReactorStore()` is\n // side-effect-free at construction (the wasm client only loads lazily, on\n // first `connect()`), so the state a server render sees is identical to\n // what the client sees before hydration — there's no divergence to\n // reconcile. Omitting `getServerSnapshot` entirely makes React bail out of\n // SSR for this subtree instead (\"Missing getServerSnapshot\").\n const getSnapshot = () => selector(store.getState());\n\n return useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);\n}\n","import { Reactor } from '../reactor';\nimport type { ReactorError } from '../errors';\nimport type { FileRef } from '../file-ref';\nimport type { DownloadClipOptions } from '../recording';\nimport type {\n Clip,\n ConnectOptions,\n JwtSource,\n MessageScope,\n NotFunction,\n PublishedTrack,\n ReactorMessage,\n ReactorOptions,\n ReactorStatus,\n} from '../types';\n\n/** State kept reactive for `useReactor` selectors. Stats/schema/capabilities\n * aren't mirrored here — reach them through the `internal.reactor` escape\n * hatch. */\nexport interface ReactorState {\n status: ReactorStatus;\n sessionId: string | undefined;\n lastError: ReactorError | undefined;\n /** Most recent app-scope `message` payload; `runtimeMessage` isn't mirrored\n * here — subscribe on `internal.reactor` for that. */\n lastMessage: ReactorMessage | undefined;\n /** Media tracks received from the model, keyed by track name. Reset to\n * `{}` on every \"disconnected\" status transition — a fresh connection\n * invalidates whatever arrived under the previous one. Append-only within\n * a session: a track pausing/unpublishing mid-session doesn't remove its\n * entry, so a stale `MediaStreamTrack` can linger until the next\n * disconnect. Matches v2's identical behavior (`core/store.ts`). */\n tracks: Record<string, MediaStreamTrack>;\n /** The `jwt` the store was created with — see `createReactorStore`'s\n * `options.jwt`. Set once at creation, not resynced afterward. */\n jwtToken: JwtSource | undefined;\n /** The `defaultConnectOptions` the store was created with — set once at\n * creation, not resynced afterward. Lets a component read the\n * provider-level defaults (e.g. `autoResumeTracks`) without threading\n * them through props of its own. */\n connectOptions: ConnectOptions | undefined;\n}\n\nexport interface ReactorActions {\n connect: (jwt?: JwtSource, options?: ConnectOptions) => Promise<void>;\n disconnect: (recoverable?: boolean) => Promise<void>;\n reconnect: (options?: ConnectOptions) => Promise<void>;\n sendCommand: <T extends object = Record<string, unknown>>(\n command: string,\n data?: NotFunction<T>,\n scope?: MessageScope,\n ) => Promise<ReactorMessage | undefined>;\n /** `Reactor.publishTrack()`. `track` is required in a streamed session\n * and ignored (with a warning) in a stepped one, whose frames go through\n * the resolved handle's `pushFrame()`. */\n publish: (name: string, track?: MediaStreamTrack) => Promise<PublishedTrack>;\n unpublish: (name: string) => Promise<void>;\n pauseTrack: (name: string) => Promise<void>;\n resumeTrack: (name: string) => Promise<void>;\n uploadFile: (file: File | Blob, options?: { name?: string }) => Promise<FileRef>;\n requestClip: (durationSeconds: number) => Promise<Clip>;\n requestRecording: () => Promise<Clip>;\n downloadClipAsFile: (clip: Clip, filename?: string | null, options?: DownloadClipOptions) => Promise<Blob>;\n}\n\nexport interface ReactorInternal {\n /** Escape hatch: the underlying `Reactor` instance, for anything the\n * selector state / action bindings above don't cover. */\n reactor: Reactor;\n}\n\nexport type ReactorStore = ReactorState & ReactorActions & { internal: ReactorInternal };\n\nexport const defaultReactorState: ReactorState = {\n status: 'disconnected',\n sessionId: undefined,\n lastError: undefined,\n lastMessage: undefined,\n tracks: {},\n jwtToken: undefined,\n connectOptions: undefined,\n};\n\nexport interface StoreApi<T> {\n getState: () => T;\n subscribe: (listener: () => void) => () => void;\n}\n\n/** Bare-bones observable-state container: a `set`/`get` pair for the\n * builder to mirror events into, `subscribe` for `useSyncExternalStore`. */\nfunction createStore<T extends object>(build: (set: (partial: Partial<T>) => void, get: () => T) => T): StoreApi<T> {\n const listeners = new Set<() => void>();\n let state: T;\n\n const set = (partial: Partial<T>): void => {\n state = { ...state, ...partial };\n listeners.forEach((listener) => listener());\n };\n const get = (): T => state;\n\n state = build(set, get);\n\n return {\n getState: get,\n subscribe: (listener) => {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n };\n}\n\n/**\n * Builds a `Reactor` and the store mirroring it. `defaultConnectOptions` is\n * applied to every `connect()`/`reconnect()` call; a call-site `options`\n * argument still wins field-by-field.\n */\nexport function createReactorStore(\n options: ReactorOptions,\n defaultConnectOptions?: ConnectOptions,\n): StoreApi<ReactorStore> {\n return createStore<ReactorStore>((set, get) => {\n const reactor = new Reactor(options);\n\n reactor.on('statusChanged', (status) => {\n set(status === 'disconnected' ? { status, tracks: {} } : { status });\n });\n reactor.on('sessionIdChanged', (sessionId) => set({ sessionId }));\n reactor.on('error', (lastError) => set({ lastError }));\n reactor.on('message', (lastMessage) => set({ lastMessage }));\n reactor.on('trackReceived', (name, track) => set({ tracks: { ...get().tracks, [name]: track } }));\n\n return {\n ...defaultReactorState,\n jwtToken: options.jwt,\n connectOptions: defaultConnectOptions,\n internal: { reactor },\n connect: (jwt, callOptions) =>\n get().internal.reactor.connect(jwt, { ...defaultConnectOptions, ...callOptions }),\n disconnect: (recoverable) => get().internal.reactor.disconnect(recoverable),\n reconnect: (callOptions) =>\n get().internal.reactor.reconnect({ ...defaultConnectOptions, ...callOptions }),\n sendCommand: (command, data, scope) => get().internal.reactor.sendCommand(command, data, scope),\n publish: (name, track) => get().internal.reactor.publishTrack(name, track),\n unpublish: (name) => get().internal.reactor.unpublishTrack(name),\n pauseTrack: (name) => get().internal.reactor.pauseTrack(name),\n resumeTrack: (name) => get().internal.reactor.resumeTrack(name),\n uploadFile: (file, options) => get().internal.reactor.uploadFile(file, options),\n requestClip: (durationSeconds) => get().internal.reactor.requestClip(durationSeconds),\n requestRecording: () => get().internal.reactor.requestRecording(),\n downloadClipAsFile: (clip, filename, options) =>\n get().internal.reactor.downloadClipAsFile(clip, filename, options),\n };\n });\n}\n","'use client';\n\nimport { useEffect, useRef, useState } from 'react';\nimport { useReactorStore } from './ReactorProvider';\nimport type { ReactorStore } from './store';\nimport type { ConnectionStats, ReactorMessage } from '../types';\n\nfunction shallowEqual(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) {\n return true;\n }\n if (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) {\n return false;\n }\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n return (\n keysA.length === keysB.length &&\n keysA.every((key) => Object.is((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key]))\n );\n}\n\n/** Wraps `selector` so repeated calls return the *previous* result whenever\n * the new one is shallowly equal to it — lets a selector return a fresh\n * object each call without forcing a re-render on every unrelated store\n * update (the object reference `useReactor` sees only changes when its\n * shallow contents do). */\nfunction useShallowSelector<T>(selector: (state: ReactorStore) => T): (state: ReactorStore) => T {\n const cache = useRef<{ value: T } | undefined>(undefined);\n\n return (state) => {\n const next = selector(state);\n\n if (cache.current && shallowEqual(cache.current.value, next)) {\n return cache.current.value;\n }\n\n cache.current = { value: next };\n return next;\n };\n}\n\n/** Reads from the nearest `ReactorProvider`'s store, with a shallow-equality\n * check on the selector's result — so a selector returning a fresh object\n * each call doesn't cause a re-render on every unrelated store update. */\nexport function useReactor<T>(selector: (state: ReactorStore) => T): T {\n return useReactorStore(useShallowSelector(selector));\n}\n\n/** Subscribes to app-scope `message` payloads sent by the model via\n * `get_ctx().send()`. `handler` is kept in a ref so identity churn on\n * every render doesn't retrigger the subscription effect. */\nexport function useReactorMessage(handler: (message: ReactorMessage) => void): void {\n const reactor = useReactor((state) => state.internal.reactor);\n const handlerRef = useRef(handler);\n\n handlerRef.current = handler;\n\n useEffect(() => {\n const listener = (message: ReactorMessage) => handlerRef.current(message);\n\n reactor.on('message', listener);\n return () => reactor.off('message', listener);\n }, [reactor]);\n}\n\n/** Subscribes to platform-scope `runtimeMessage` payloads (moderation,\n * clip/recording lifecycle, ...) — see `useReactorMessage` for app-scope\n * payloads instead. */\nexport function useReactorInternalMessage(handler: (message: ReactorMessage) => void): void {\n const reactor = useReactor((state) => state.internal.reactor);\n const handlerRef = useRef(handler);\n\n handlerRef.current = handler;\n\n useEffect(() => {\n const listener = (message: ReactorMessage) => handlerRef.current(message);\n\n reactor.on('runtimeMessage', listener);\n return () => reactor.off('runtimeMessage', listener);\n }, [reactor]);\n}\n\n/** The most recent `statsUpdate` sample; `undefined` until the first one\n * arrives, and reset back to `undefined` on unmount or reactor change. */\nexport function useStats(): ConnectionStats | undefined {\n const reactor = useReactor((state) => state.internal.reactor);\n const [stats, setStats] = useState<ConnectionStats | undefined>(undefined);\n\n useEffect(() => {\n setStats(undefined);\n reactor.on('statsUpdate', setStats);\n return () => {\n reactor.off('statsUpdate', setStats);\n setStats(undefined);\n };\n }, [reactor]);\n\n return stats;\n}\n","'use client';\n\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport type { CSSProperties, VideoHTMLAttributes } from 'react';\nimport { useReactor } from './hooks';\n\nexport interface ReactorViewProps {\n /** Name of the recvonly video track to render. Must match a track name\n * declared in the model's capabilities. Defaults to `\"main_video\"`. */\n track?: string;\n /** Name of a recvonly audio track to mix into the same `<video>` element\n * alongside `track`. */\n audioTrack?: string;\n width?: number;\n height?: number;\n className?: string;\n style?: CSSProperties;\n videoObjectFit?: NonNullable<VideoHTMLAttributes<HTMLVideoElement>['style']>['objectFit'];\n /** Defaults to `true` when no `audioTrack` is set (keeps the element within\n * browser autoplay policies), `false` otherwise. Pass an explicit value to\n * override either default. */\n muted?: boolean;\n}\n\n/** The current `MediaStreamTrack` for `name`, kept live across `trackReceived`\n * events. Reads through `internal.reactor` directly rather than the store —\n * there's no reactive `tracks` map on `ReactorState` to select from. */\nfunction useReceivedTrack(name: string | undefined): MediaStreamTrack | undefined {\n const reactor = useReactor((state) => state.internal.reactor);\n const [track, setTrack] = useState(() => (name ? reactor.getTrackByName(name) : undefined));\n\n useEffect(() => {\n setTrack(name ? reactor.getTrackByName(name) : undefined);\n\n if (!name) {\n return;\n }\n\n const listener = (receivedName: string, receivedTrack: MediaStreamTrack) => {\n if (receivedName === name) {\n setTrack(receivedTrack);\n }\n };\n\n reactor.on('trackReceived', listener);\n return () => reactor.off('trackReceived', listener);\n }, [reactor, name]);\n\n return track;\n}\n\nexport function ReactorView({\n track = 'main_video',\n audioTrack,\n width,\n height,\n className,\n style,\n videoObjectFit = 'contain',\n muted = audioTrack === undefined,\n}: ReactorViewProps) {\n const videoMediaTrack = useReceivedTrack(track);\n const audioMediaTrack = useReceivedTrack(audioTrack);\n const videoRef = useRef<HTMLVideoElement>(null);\n\n const mediaStream = useMemo(() => {\n const tracks: MediaStreamTrack[] = [];\n\n if (videoMediaTrack) {\n tracks.push(videoMediaTrack);\n }\n if (audioMediaTrack) {\n tracks.push(audioMediaTrack);\n }\n return tracks.length > 0 ? new MediaStream(tracks) : null;\n }, [videoMediaTrack, audioMediaTrack]);\n\n useEffect(() => {\n const el = videoRef.current;\n\n if (!el || !mediaStream) {\n return;\n }\n\n const attach = (reset: boolean) => {\n if (reset) {\n el.srcObject = null;\n }\n el.srcObject = mediaStream;\n void el.play().catch(() => {});\n };\n\n attach(false);\n\n // A recvonly track negotiated while the server has it paused arrives\n // muted (no RTP). When the server resumes sending, the track fires\n // `unmute`, but some browsers keep rendering black on the already-attached\n // `srcObject` until it's reattached — so re-attach on `unmute` to render\n // auto-resumed tracks without a manual pause/resume round-trip.\n const onUnmute = () => attach(true);\n const tracks = mediaStream.getTracks();\n\n for (const t of tracks) {\n t.addEventListener('unmute', onUnmute);\n }\n\n return () => {\n for (const t of tracks) {\n t.removeEventListener('unmute', onUnmute);\n }\n el.srcObject = null;\n };\n }, [mediaStream]);\n\n return (\n <div\n style={{\n position: 'relative',\n background: '#000',\n ...(width !== undefined && { width }),\n ...(height !== undefined && { height }),\n ...style,\n }}\n className={className}\n >\n <video\n ref={videoRef}\n style={{\n width: '100%',\n height: '100%',\n objectFit: videoObjectFit,\n display: videoMediaTrack ? 'block' : 'none',\n }}\n muted={muted}\n playsInline\n />\n </div>\n );\n}\n","'use client';\n\nimport { useEffect, useRef, useState } from 'react';\nimport type { CSSProperties, VideoHTMLAttributes } from 'react';\nimport { useReactor } from './hooks';\nimport type { ReactorError } from '../errors';\n\nexport interface WebcamStreamProps {\n /** Name of the sendonly video track to publish the webcam to. Must match a\n * track name declared in the model's capabilities. */\n track: string;\n /** Capture and publish the microphone alongside the webcam. `true` for\n * default constraints, or explicit `MediaTrackConstraints`. Requires\n * `audioTrack`. Defaults to `false`. */\n audio?: boolean | MediaTrackConstraints;\n /** Name of the sendonly audio track to publish the mic to. Ignored unless\n * `audio` is set. */\n audioTrack?: string;\n className?: string;\n style?: CSSProperties;\n /** Read once, at mount — changing this after mount doesn't re-request\n * `getUserMedia`. Matches v2. */\n videoConstraints?: MediaTrackConstraints;\n showWebcam?: boolean;\n videoObjectFit?: NonNullable<VideoHTMLAttributes<HTMLVideoElement>['style']>['objectFit'];\n /** Fires once `getUserMedia` is rejected with `NotAllowedError` or\n * `PermissionDeniedError`. */\n onPermissionDenied?: () => void;\n /** Fires after the local media has been published (video, and audio when\n * `audio` is enabled). Re-fires after a reconnect. */\n onPublished?: () => void;\n /** Fires on non-permission `getUserMedia` failures and on publish/unpublish\n * rejections. Permission denials route to `onPermissionDenied` instead. */\n onError?: (error: Error) => void;\n}\n\nconst DEFAULT_VIDEO_CONSTRAINTS: MediaTrackConstraints = {\n width: { ideal: 1280 },\n height: { ideal: 720 },\n};\n\nexport function WebcamStream({\n track,\n audio = false,\n audioTrack,\n className,\n style,\n videoConstraints = DEFAULT_VIDEO_CONSTRAINTS,\n showWebcam = true,\n videoObjectFit = 'contain',\n onPermissionDenied,\n onPublished,\n onError,\n}: WebcamStreamProps) {\n const [stream, setStream] = useState<MediaStream | null>(null);\n const [published, setPublished] = useState<{ video: string; audio?: string } | null>(null);\n const [permissionDenied, setPermissionDenied] = useState(false);\n\n const { status, publish, unpublish, reactor } = useReactor((state) => ({\n status: state.status,\n publish: state.publish,\n unpublish: state.unpublish,\n reactor: state.internal.reactor,\n }));\n\n const videoRef = useRef<HTMLVideoElement>(null);\n\n // Held in refs so inline callback identity doesn't churn the\n // publish/unpublish effect below on every parent render.\n const onPermissionDeniedRef = useRef(onPermissionDenied);\n const onPublishedRef = useRef(onPublished);\n const onErrorRef = useRef(onError);\n\n onPermissionDeniedRef.current = onPermissionDenied;\n onPublishedRef.current = onPublished;\n onErrorRef.current = onError;\n\n // Without an `audioTrack` the captured mic has nowhere to publish, so\n // capture stays video-only.\n const audioRequested = audio !== false;\n const audioEnabled = audioRequested && audioTrack !== undefined;\n\n // The mount/unmount effect below only runs once (empty deps), so its\n // cleanup would otherwise close over the props/state from the initial\n // render — mirror them here so teardown unpublishes whatever is actually\n // published and stops the right stream even if they changed since mount.\n //\n // Same empty-deps effect also means `videoConstraints`/`audio`/`audioTrack`\n // are only read once, at mount — changing them later doesn't re-request\n // getUserMedia. Matches v2's WebcamStream, which has the same limitation.\n const latestRef = useRef({ published, unpublish, stream });\n\n latestRef.current = { published, unpublish, stream };\n\n useEffect(() => {\n let cancelled = false;\n\n navigator.mediaDevices\n .getUserMedia({\n video: videoConstraints,\n audio: audioEnabled ? audio : false,\n })\n .then((mediaStream) => {\n if (cancelled) {\n for (const t of mediaStream.getTracks()) {\n t.stop();\n }\n return;\n }\n setStream(mediaStream);\n setPermissionDenied(false);\n })\n .catch((err: unknown) => {\n if (cancelled) {\n return;\n }\n\n if (err instanceof DOMException && (err.name === 'NotAllowedError' || err.name === 'PermissionDeniedError')) {\n setPermissionDenied(true);\n onPermissionDeniedRef.current?.();\n } else {\n onErrorRef.current?.(err instanceof Error ? err : new Error(String(err)));\n }\n });\n\n return () => {\n cancelled = true;\n\n const current = latestRef.current;\n // Unpublish failures don't block local-track teardown — leaving\n // tracks running keeps the camera/mic indicator on after unmount.\n const tasks: Array<Promise<void>> = [];\n\n if (current.published) {\n tasks.push(current.unpublish(current.published.video));\n\n if (current.published.audio) {\n tasks.push(current.unpublish(current.published.audio));\n }\n }\n\n if (tasks.length > 0) {\n void Promise.allSettled(tasks).then((results) => {\n for (const r of results) {\n if (r.status === 'rejected') {\n onErrorRef.current?.(r.reason instanceof Error ? r.reason : new Error(String(r.reason)));\n }\n }\n });\n }\n\n current.stream?.getTracks().forEach((t) => t.stop());\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n useEffect(() => {\n const el = videoRef.current;\n\n if (!el) {\n return;\n }\n el.srcObject = stream;\n }, [stream]);\n\n useEffect(() => {\n if (!stream) {\n return;\n }\n\n let cancelled = false;\n const desiredAudio = audioEnabled ? audioTrack : undefined;\n const activeStream = stream;\n\n async function sync() {\n if (status === 'ready') {\n if (published && published.video === track && published.audio === desiredAudio) {\n return;\n }\n\n // Names changed while already published: drop the stale\n // publication before publishing under the new ones.\n if (published) {\n const rollback: Array<Promise<void>> = [unpublish(published.video)];\n\n if (published.audio) {\n rollback.push(unpublish(published.audio));\n }\n await Promise.allSettled(rollback);\n\n if (cancelled) {\n return;\n }\n setPublished(null);\n }\n\n const videoMediaTrack = activeStream.getVideoTracks()[0];\n const audioMediaTrack = desiredAudio ? activeStream.getAudioTracks()[0] : undefined;\n const attempts: Array<{ name: string; task: Promise<unknown> }> = [];\n\n if (videoMediaTrack) {\n attempts.push({ name: track, task: publish(track, videoMediaTrack) });\n }\n if (audioMediaTrack && desiredAudio) {\n attempts.push({ name: desiredAudio, task: publish(desiredAudio, audioMediaTrack) });\n }\n if (attempts.length === 0) {\n return;\n }\n\n const results = await Promise.allSettled(attempts.map((a) => a.task));\n\n if (cancelled) {\n return;\n }\n\n const failureIndex = results.findIndex((r) => r.status === 'rejected');\n\n if (failureIndex !== -1) {\n // Roll back whatever did succeed so we never report an error\n // while leaving some names published behind our backs.\n const succeeded = attempts.filter((_, i) => results[i]?.status === 'fulfilled');\n\n await Promise.allSettled(succeeded.map((a) => unpublish(a.name)));\n\n if (cancelled) {\n return;\n }\n\n const failure = results[failureIndex] as PromiseRejectedResult;\n\n onErrorRef.current?.(failure.reason instanceof Error ? failure.reason : new Error(String(failure.reason)));\n return;\n }\n\n const newPublished: { video: string; audio?: string } = { video: track };\n\n if (audioMediaTrack && desiredAudio) {\n newPublished.audio = desiredAudio;\n }\n setPublished(newPublished);\n onPublishedRef.current?.();\n } else if (published) {\n const tasks: Array<Promise<void>> = [unpublish(published.video)];\n\n if (published.audio) {\n tasks.push(unpublish(published.audio));\n }\n\n const results = await Promise.allSettled(tasks);\n\n if (cancelled) {\n return;\n }\n\n for (const r of results) {\n if (r.status === 'rejected') {\n onErrorRef.current?.(r.reason instanceof Error ? r.reason : new Error(String(r.reason)));\n }\n }\n setPublished(null);\n }\n }\n\n void sync();\n\n return () => {\n cancelled = true;\n };\n }, [status, stream, published, publish, unpublish, track, audioEnabled, audioTrack]);\n\n // A rejected publish() is already handled inline in sync() above (awaited,\n // then routed to onError). This listener is for TRACK_PUBLISH_FAILED\n // reported out-of-band by the runtime *after* publish() already resolved —\n // e.g. the track was accepted but later failed to actually flow. Resetting\n // `published` here makes the sync effect re-run and republish.\n useEffect(() => {\n const handleError = (error: ReactorError) => {\n if (error.code === 'TRACK_PUBLISH_FAILED') {\n setPublished(null);\n }\n };\n\n reactor.on('error', handleError);\n return () => reactor.off('error', handleError);\n }, [reactor]);\n\n const showPlaceholder = !stream;\n\n return (\n <div\n style={{\n display: showWebcam ? 'block' : 'none',\n position: 'relative',\n background: '#000',\n ...style,\n }}\n className={className}\n >\n <video\n ref={videoRef}\n style={{\n width: '100%',\n height: '100%',\n objectFit: videoObjectFit,\n display: showPlaceholder ? 'none' : 'block',\n }}\n muted\n playsInline\n autoPlay\n />\n {showPlaceholder && (\n <div\n style={{\n position: 'absolute',\n top: 0,\n left: 0,\n width: '100%',\n height: '100%',\n color: '#fff',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n fontSize: '16px',\n fontFamily: 'monospace',\n textAlign: 'center',\n padding: '20px',\n boxSizing: 'border-box',\n flexDirection: 'column',\n gap: '12px',\n }}\n >\n {permissionDenied ? (\n <div style={{ fontSize: '12px', fontFamily: 'monospace' }}>\n Camera access denied.\n <br />\n Please allow access in your browser settings.\n </div>\n ) : (\n <div style={{ fontSize: '12px', fontFamily: 'monospace' }}>Starting camera...</div>\n )}\n </div>\n )}\n </div>\n );\n}\n","'use client';\n\nimport { useContext, useEffect, useRef, useState } from 'react';\nimport type { CSSProperties } from 'react';\nimport { type ClipPlayback, attachClipPlayback } from '../clip-playback';\nimport { resolveJwtSource } from '../internal/jwt-resolver';\nimport type { JwtResolver } from '../jwt';\nimport { RecordingError, assembleClipBlob, createPlayableManifestUrl, fetchPlaylist } from '../recording';\nimport { ReactorContext } from './ReactorProvider';\nimport type { Clip } from '../types';\n\n/**\n * Video preview for a captured {@link Clip}. Streams the clip with `hls.js`\n * wherever Media Source Extensions exist — every current browser, iOS\n * Safari 17.1 and later included. `hls.js` is dynamically imported, so\n * bundlers give it a chunk of its own that an app importing this component\n * fetches on first play, and one that never renders a player drops\n * entirely. Where Media Source Extensions don't exist — iOS before 17.1 —\n * the clip is assembled into a single MP4 and played from memory instead.\n * Failures surface in an inline error overlay; the chunks remain\n * downloadable via {@link useClipDownload}/`ClipDownloadButton` either way.\n *\n * Preview only — this component doesn't render a download UI. Compose it\n * with `ClipDownloadButton`, or build a custom download surface around\n * `useClipDownload`.\n *\n * Unlike `ReactorView`/`WebcamStream`, this doesn't require a\n * `ReactorProvider` in the tree — it operates on the `Clip` value alone, so\n * it stays usable after `reactor.disconnect()` and works with clips loaded\n * from fixtures or any other source. When a `ReactorProvider` is mounted\n * above, an omitted `getJwt` inherits the provider's resolver.\n */\nexport interface ClipPlayerProps {\n /** The captured clip to play. Re-fetches the manifest and re-attaches the\n * player when this changes by reference. */\n clip: Clip;\n /**\n * Lazy resolver for the Coordinator JWT used on the manifest GET, called\n * before every poll with `{ sessionId: clip.sessionId }` so token refreshes\n * are picked up automatically.\n *\n * Required outside a `ReactorProvider` in production; optional inside one\n * (inherits the provider's resolver). Omit in local-dev mode (HttpRuntime)\n * — the manifest endpoint there is auth-free.\n */\n getJwt?: JwtResolver;\n /**\n * Opt into a bounded wait: give up polling the manifest with\n * `CLIP_NOT_READY` once `max(clip.predictedReadyAtMs, pollStart) + slackMs`\n * passes. Unset by default — the player polls indefinitely until the clip\n * is ready, stopping only when it unmounts or `clip` changes. Forwarded\n * directly to `fetchPlaylist()`'s `slackMs` option.\n */\n slackMs?: number;\n /** Play automatically once the manifest is attached. Default `true`. */\n autoPlay?: boolean;\n /** Start muted. Default `true` — browser autoplay policies block\n * audio-bearing video from playing without a user gesture; the user can\n * unmute via the native controls. */\n muted?: boolean;\n className?: string;\n style?: CSSProperties;\n /** Fires when the player enters its inline error state. A `RecordingError`\n * for manifest-fetch failures, a plain `Error` for hls.js/element playback\n * failures. */\n onError?: (error: Error) => void;\n}\n\ntype Phase =\n | { kind: 'waiting' }\n | { kind: 'loading' }\n | { kind: 'ready' }\n | { kind: 'error'; message: string; error: Error };\n\nexport function ClipPlayer({\n clip,\n getJwt,\n slackMs,\n autoPlay = true,\n muted = true,\n className,\n style,\n onError,\n}: ClipPlayerProps) {\n const videoRef = useRef<HTMLVideoElement | null>(null);\n const [phase, setPhase] = useState<Phase>({ kind: 'waiting' });\n\n // `undefined` outside a `ReactorProvider`; used to inherit the provider's\n // JWT resolver when `getJwt` is omitted.\n const store = useContext(ReactorContext);\n\n // The playback effect intentionally depends only on `clip`. Callers\n // typically pass an inline `getJwt={() => token}` that changes identity on\n // every render — using it directly in the effect deps would tear down the\n // player and re-fetch the manifest on every parent re-render. Same\n // reasoning for `autoPlay`: it's only read at the moment of attach. Refs\n // keep the latest values reachable from inside the effect without forcing\n // it to re-run.\n const getJwtRef = useRef(getJwt);\n const autoPlayRef = useRef(autoPlay);\n const slackMsRef = useRef(slackMs);\n const onErrorRef = useRef(onError);\n // Same ref pattern: the resolver is looked up inside `setup` at request\n // time, so a provider swap is picked up on next attach without tearing the\n // player down.\n const storeRef = useRef(store);\n\n getJwtRef.current = getJwt;\n autoPlayRef.current = autoPlay;\n slackMsRef.current = slackMs;\n onErrorRef.current = onError;\n storeRef.current = store;\n\n // Re-fires per error transition: each new `clip` resets through\n // `waiting`/`loading` before potentially re-entering `error`.\n useEffect(() => {\n if (phase.kind === 'error') {\n onErrorRef.current?.(phase.error);\n }\n }, [phase]);\n\n // Playback pipeline: fetch manifest (with optional JWT) → wrap in blob URL\n // → hand to `attachClipPlayback`, which either streams it with hls.js or\n // assembles the chunks into an MP4. Re-runs only when `clip` changes by\n // reference. The cleanup closure tears every piece down deterministically.\n useEffect(() => {\n const video = videoRef.current;\n\n if (!video) {\n return;\n }\n\n const abort = new AbortController();\n let cancelled = false;\n let playback: ClipPlayback | null = null;\n let manifestBlobUrl: string | null = null;\n\n const fail = (error: Error) => {\n if (cancelled) {\n return;\n }\n const message = error instanceof RecordingError ? `${error.code}: ${error.reason}` : error.message;\n\n setPhase({ kind: 'error', message, error });\n };\n\n const setup = async () => {\n try {\n setPhase({ kind: 'waiting' });\n // Explicit `getJwt` wins; fall back to the provider's source. Read\n // through the refs on every poll, so a rerender with a new `getJwt`\n // reaches a wait already in progress.\n const source = () => getJwtRef.current ?? storeRef.current?.getState().internal.reactor.getJwtResolver();\n const playlistOptions: Parameters<typeof fetchPlaylist>[1] = {\n predictedReadyAtMs: clip.predictedReadyAtMs,\n sessionId: clip.sessionId,\n signal: abort.signal,\n };\n\n if (slackMsRef.current !== undefined) {\n playlistOptions.slackMs = slackMsRef.current;\n }\n if (source() !== undefined) {\n playlistOptions.jwt = (context) => resolveJwtSource(source() ?? '', context);\n }\n\n const body = await fetchPlaylist(clip.playlistUrl, playlistOptions);\n\n if (cancelled) {\n return;\n }\n setPhase({ kind: 'loading' });\n manifestBlobUrl = createPlayableManifestUrl(body, clip.playlistUrl);\n playback = attachClipPlayback(\n video,\n {\n manifestUrl: manifestBlobUrl,\n assembleMp4: () => assembleClipBlob(body, clip.playlistUrl, { signal: abort.signal }),\n },\n {\n autoPlay: autoPlayRef.current,\n onReady: () => {\n if (!cancelled) {\n setPhase({ kind: 'ready' });\n }\n },\n onError: fail,\n },\n );\n } catch (err) {\n if (cancelled) {\n return;\n }\n // `AbortError` from teardown is expected — don't paint it as a failure.\n if (err instanceof DOMException && err.name === 'AbortError') {\n return;\n }\n fail(err instanceof Error ? err : new Error(String(err)));\n }\n };\n\n void setup();\n\n return () => {\n cancelled = true;\n abort.abort();\n playback?.destroy();\n video.pause();\n video.removeAttribute('src');\n video.load();\n if (manifestBlobUrl) {\n URL.revokeObjectURL(manifestBlobUrl);\n }\n };\n }, [clip]);\n\n const overlayText = phase.kind === 'waiting' ? 'Waiting for clip…' : phase.kind === 'loading' ? 'Loading player…' : null;\n\n return (\n <div\n className={className}\n style={{\n position: 'relative',\n background: '#000',\n width: '100%',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n ...style,\n }}\n >\n <video\n ref={videoRef}\n controls\n playsInline\n muted={muted}\n style={{\n display: 'block',\n width: '100%',\n height: 'auto',\n maxHeight: '100%',\n }}\n />\n\n {overlayText && (\n <div\n style={{\n position: 'absolute',\n inset: 0,\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n color: 'rgba(255,255,255,0.6)',\n font: '11px ui-monospace, SFMono-Regular, Menlo, monospace',\n letterSpacing: '0.1em',\n textTransform: 'uppercase',\n pointerEvents: 'none',\n }}\n >\n {overlayText}\n </div>\n )}\n\n {phase.kind === 'error' && (\n <div\n style={{\n position: 'absolute',\n inset: 0,\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n padding: 24,\n background: 'rgba(0,0,0,0.8)',\n color: '#ef4444',\n font: '11px ui-monospace, SFMono-Regular, Menlo, monospace',\n textAlign: 'center',\n }}\n >\n {phase.message}\n </div>\n )}\n </div>\n );\n}\n","/**\n * Attaches a captured clip to a `<video>` element for preview.\n *\n * There are two ways to put a clip on an element, and which one is available\n * is decided by `Hls.isSupported()` — never by\n * `canPlayType(\"application/vnd.apple.mpegurl\")`, which answers `\"maybe\"` in\n * browsers that then fail the load with `MediaError` 4.\n *\n * `hls.js` streams the clip wherever Media Source Extensions exist, which is\n * every current browser, including the Managed variant iOS Safari exposes.\n * Where they don't — iOS before 17.1 — the clip is assembled into a single\n * flat MP4 and played from memory. That costs the whole clip up front\n * instead of streaming it, which for a few seconds of video is a fair trade\n * for working at all.\n *\n * Handing the manifest to the element instead is not a third option, and\n * each engine rules it out for its own reason. Native HLS makes the element\n * load the media segments itself, and Chromium refuses segments from an\n * origin other than the page's whatever CORS headers they carry, while a\n * clip's chunks are presigned URLs that always come from elsewhere. WebKit\n * takes those cross-origin segments happily but won't read a `blob:`\n * manifest at all — and the manifest is always a blob, because fetching it\n * takes an `Authorization` header. Both playback paths here therefore fetch\n * the media themselves: `hls.js` appends it through Media Source Extensions,\n * and the assembled MP4 has no sub-resources left to load.\n *\n * The element is the single source of truth for readiness and failure:\n * `loadedmetadata` marks playback ready (a parsed manifest says nothing\n * about the element holding decodable media), and the element's `error`\n * event carries the `MediaError` that would otherwise leave the viewer\n * looking at a black frame.\n *\n * Rendering, state, and manifest fetching live in the `ClipPlayer` React\n * component; this module owns nothing but the attach.\n */\n\n/** The two forms a clip can take, either of which can drive an element. */\nexport interface ClipSource {\n /** `blob:` URL of the HLS manifest, streamed by `hls.js`. */\n manifestUrl: string;\n /** Assemble the clip into one self-contained MP4. Called only when\n * `hls.js` can't run, and expected to honour the caller's abort signal. */\n assembleMp4: () => Promise<Blob>;\n}\n\n/** Wired up by {@link attachClipPlayback}. */\nexport interface ClipPlaybackOptions {\n /** Start playing as soon as the element has metadata. */\n autoPlay: boolean;\n /** Called once the element has loaded the clip's metadata. */\n onReady: () => void;\n /** Called at most once, with an error suitable for display. */\n onError: (error: Error) => void;\n /** Resolves `hls.js`. Defaults to a dynamic `import()`, which bundlers keep\n * in its own chunk so consumers who never render a player aren't billed\n * for it. A rejection is not fatal: playback falls back to the assembled\n * MP4. */\n loadHls?: () => Promise<HlsConstructor>;\n}\n\nexport interface ClipPlayback {\n /** Detaches every listener, tears down `hls.js`, frees the MP4. */\n destroy: () => void;\n}\n\n/**\n * Play `source` on `video`.\n *\n * Returns as soon as the element is wired up: choosing a path means loading\n * `hls.js`, and taking the fallback means downloading the clip, so both\n * happen in the background and the handle is destroyable throughout.\n * Playback becoming available is reported through\n * {@link ClipPlaybackOptions.onReady}.\n */\nexport function attachClipPlayback(\n video: HTMLVideoElement,\n source: ClipSource,\n {\n autoPlay,\n onReady,\n onError,\n loadHls = () => import('hls.js').then((mod) => (mod as { default: HlsConstructor }).default),\n }: ClipPlaybackOptions,\n): ClipPlayback {\n let destroyed = false;\n let failed = false;\n let ready = false;\n let hls: HlsInstance | null = null;\n let mp4Url: string | null = null;\n\n const fail = (error: Error) => {\n if (destroyed || failed) {\n return;\n }\n failed = true;\n onError(error);\n };\n\n const handleLoadedMetadata = () => {\n // Metadata can arrive more than once, and can arrive after a failure was\n // reported. Reporting it again would clear an error the viewer is\n // reading, or restart a clip they paused.\n if (destroyed || failed || ready) {\n return;\n }\n ready = true;\n onReady();\n if (autoPlay) {\n video.play().catch(() => {\n // Autoplay may be blocked by the browser; native controls still work.\n });\n }\n };\n\n const handleElementError = () => {\n fail(new Error(describeMediaError(video.error)));\n };\n\n video.addEventListener('loadedmetadata', handleLoadedMetadata);\n video.addEventListener('error', handleElementError);\n\n const handle: ClipPlayback = {\n destroy: () => {\n destroyed = true;\n video.removeEventListener('loadedmetadata', handleLoadedMetadata);\n video.removeEventListener('error', handleElementError);\n hls?.destroy();\n hls = null;\n if (mp4Url) {\n URL.revokeObjectURL(mp4Url);\n mp4Url = null;\n }\n },\n };\n\n const selectPath = async () => {\n // A browser with no MediaSource of any kind can't run `hls.js`, so don't\n // spend the download to find out — go straight to the MP4. Loading it\n // and asking is still the rule everywhere else: this test is the weakest\n // part of `Hls.isSupported()`, never a reimplementation of it.\n const HlsCtor = hasMediaSource() ? await loadHls().catch(() => null) : null;\n\n if (destroyed) {\n return;\n }\n\n if (HlsCtor?.isSupported()) {\n const instance = new HlsCtor();\n\n instance.loadSource(source.manifestUrl);\n instance.attachMedia(video);\n instance.on(HlsCtor.Events.ERROR, (_evt: unknown, data: HlsErrorData) => {\n if (destroyed) {\n return;\n }\n if (data.fatal) {\n fail(new Error(`Playback error: ${data.details ?? 'unknown'}`));\n return;\n }\n // Non-fatal errors are the usual explanation for a \"fetches but\n // nothing renders\" symptom (bufferAppendingError, fragParsingError,\n // levelLoadError), which the user-facing overlay would otherwise\n // hide.\n console.warn('[Reactor.ClipPlayer] hls.js non-fatal error', data);\n });\n hls = instance;\n return;\n }\n\n const blob = await source.assembleMp4();\n\n if (destroyed) {\n return;\n }\n mp4Url = URL.createObjectURL(blob);\n video.src = mp4Url;\n };\n\n selectPath().catch((err: unknown) => {\n fail(err instanceof Error ? err : new Error(String(err)));\n });\n\n return handle;\n}\n\n/**\n * Whether the browser exposes a MediaSource `hls.js` could drive — the\n * Managed variant included, which is the one iOS Safari 17.1 added. Older\n * iOS has none of the three and is the reason clips still need a path that\n * doesn't stream.\n */\nfunction hasMediaSource(): boolean {\n const scope = globalThis as Record<string, unknown>;\n\n return Boolean(scope.ManagedMediaSource ?? scope.MediaSource ?? scope.WebKitMediaSource);\n}\n\nconst MEDIA_ERROR_MESSAGES: Record<number, string> = {\n 1: 'Playback was aborted.',\n 2: 'A network error interrupted playback.',\n 3: 'This clip could not be decoded.',\n 4: 'This browser cannot play this clip. Use Download instead.',\n};\n\n/**\n * Turn the element's `MediaError` into displayable text, keeping the\n * browser's own diagnostic (`DEMUXER_ERROR_...` and friends) when it\n * provides one.\n */\nfunction describeMediaError(error: MediaError | null): string {\n const message = (error && MEDIA_ERROR_MESSAGES[error.code]) ?? 'This clip failed to play in this browser. Use Download instead.';\n\n return error?.message ? `${message} (${error.message})` : message;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Structural typings covering exactly the `hls.js` surface this module\n// drives. Naming the shape rather than importing the class keeps the loader\n// swappable, which is what lets the tests exercise every path without the\n// real library.\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface HlsInstance {\n loadSource: (url: string) => void;\n attachMedia: (el: HTMLMediaElement) => void;\n on: (event: string, cb: (evt: unknown, data: HlsErrorData) => void) => void;\n destroy: () => void;\n}\n\nexport interface HlsConstructor {\n new (): HlsInstance;\n isSupported: () => boolean;\n readonly Events: {\n readonly ERROR: string;\n };\n}\n\nexport interface HlsErrorData {\n fatal?: boolean;\n details?: string;\n}\n","'use client';\n\nimport { useEffect, useRef } from 'react';\nimport type { CSSProperties, ReactNode } from 'react';\nimport { useClipDownload } from './useClipDownload';\nimport type { ClipDownloadState, UseClipDownloadOptions } from './useClipDownload';\nimport type { JwtResolver } from '../jwt';\nimport type { Clip } from '../types';\n\n/**\n * Standalone download button for a captured {@link Clip}. Drops anywhere in\n * your UI — modal headers, list rows, hover menus, floating action buttons\n * — and is responsible for nothing more than triggering a download and\n * reflecting its state. Wraps `useClipDownload` internally; for completely\n * custom UIs (progress bars, menu items, post-download blob handling) call\n * that hook directly.\n *\n * Styling is intentionally minimal — override via `className`/`style`, or\n * replace the inner content with the `children` render-prop. No CSS file is\n * shipped; every default style is inline so it loses to anything the\n * consumer provides.\n */\nexport interface ClipDownloadButtonProps {\n /** The clip to download. */\n clip: Clip;\n /** Lazy JWT resolver. Optional inside a `ReactorProvider` (inherits the\n * provider's resolver) and in local-dev mode. See `ClipPlayerProps.getJwt`. */\n getJwt?: JwtResolver;\n /** Filename for the saved MP4. Default `\"reactor-clip.mp4\"`. */\n filename?: string;\n /**\n * Inner content of the button. Three forms:\n *\n * - Omitted — renders a default label that follows the state\n * (`\"Download\"` / `\"Downloading 3/8…\"` / etc.).\n * - `ReactNode` — static label, no state-driven text.\n * - `(state) => ReactNode` — state-aware render function, for custom\n * progress strings, spinners, etc.\n */\n children?: ReactNode | ((state: ClipDownloadState) => ReactNode);\n /** Forwarded to the underlying `<button>`. */\n className?: string;\n /** Forwarded to the underlying `<button>` — merges after the defaults so\n * each property overrides. */\n style?: CSSProperties;\n /** Forwarded to the underlying `<button>`. ORed with the internal\n * \"downloading\" state. */\n disabled?: boolean;\n /** Fires when the download completes with the assembled MP4 Blob. */\n onSuccess?: (blob: Blob) => void;\n /** Fires when the download fails. Message mirrors the in-button state —\n * `\"<CODE>: <reason>\"` for `RecordingError`s, the plain error message\n * otherwise. */\n onError?: (error: Error) => void;\n}\n\nexport function ClipDownloadButton({\n clip,\n getJwt,\n filename = 'reactor-clip.mp4',\n children,\n className,\n style,\n disabled,\n onSuccess,\n onError,\n}: ClipDownloadButtonProps) {\n const downloadOptions: UseClipDownloadOptions = { filename };\n\n if (getJwt !== undefined) {\n downloadOptions.getJwt = getJwt;\n }\n\n const { state, download } = useClipDownload(clip, downloadOptions);\n const downloading = state.kind === 'downloading';\n const isDisabled = downloading || !!disabled;\n\n // Held in refs so inline callback identity doesn't churn the error-emit\n // effect or the click handler on every parent render.\n const onSuccessRef = useRef(onSuccess);\n const onErrorRef = useRef(onError);\n\n onSuccessRef.current = onSuccess;\n onErrorRef.current = onError;\n\n // `useClipDownload.download()` resolves to `undefined` on failure (the\n // hook surfaces errors through state, not by rejecting). Each retry that\n // lands back in `\"error\"` re-fires `onError`.\n useEffect(() => {\n if (state.kind === 'error') {\n onErrorRef.current?.(new Error(state.message));\n }\n }, [state]);\n\n const content = typeof children === 'function' ? children(state) : children !== undefined ? children : defaultLabel(state);\n\n return (\n <button\n type=\"button\"\n onClick={() => {\n void download().then((blob) => {\n if (blob) {\n onSuccessRef.current?.(blob);\n }\n });\n }}\n disabled={isDisabled}\n title={state.kind === 'error' ? state.message : undefined}\n className={className}\n style={{\n padding: '5px 12px',\n borderRadius: 4,\n border: '1px solid rgba(255,255,255,0.15)',\n background: 'rgba(255,255,255,0.05)',\n color: '#fff',\n font: '11px ui-monospace, SFMono-Regular, Menlo, monospace',\n cursor: isDisabled ? 'default' : 'pointer',\n opacity: isDisabled ? 0.6 : 1,\n transition: 'background-color 120ms ease',\n ...style,\n }}\n >\n {content}\n </button>\n );\n}\n\nfunction defaultLabel(state: ClipDownloadState): ReactNode {\n if (state.kind === 'downloading') {\n if (state.total > 0) {\n return `Downloading ${state.fetched}/${state.total}…`;\n }\n return 'Downloading…';\n }\n return 'Download';\n}\n","'use client';\n\nimport { useCallback, useContext, useEffect, useRef, useState } from 'react';\nimport { resolveJwtSource } from '../internal/jwt-resolver';\nimport type { JwtResolver } from '../jwt';\nimport { RecordingError, downloadClipAsFile } from '../recording';\nimport { ReactorContext } from './ReactorProvider';\nimport type { Clip } from '../types';\n\n/**\n * State machine for an in-progress clip download.\n *\n * - `idle`: no download in flight (initial state, and what the hook returns\n * to after a successful save).\n * - `downloading`: chunks are being fetched. `fetched`/`total` count the\n * chunks (init segment + media segments) — useful for a progress bar.\n * `total` is 0 until the manifest is parsed and the chunk count is known.\n * - `error`: most recent attempt failed; `message` is suitable for\n * surfacing inline. `RecordingError`s are formatted as `\"<CODE>: <reason>\"`.\n */\nexport type ClipDownloadState =\n | { kind: 'idle' }\n | { kind: 'downloading'; fetched: number; total: number }\n | { kind: 'error'; message: string };\n\nexport interface UseClipDownloadOptions {\n /** Filename used when the browser save dialog opens. Pass `null` to skip\n * the `<a download>` trigger entirely — the returned Blob is still\n * resolved so the caller can `URL.createObjectURL` it or re-upload it.\n * Default `\"reactor-clip.mp4\"`. */\n filename?: string | null;\n /**\n * Lazy resolver for the Coordinator JWT used on the manifest GET. Called\n * before every poll of a {@link UseClipDownloadResult.download} with\n * `{ sessionId: clip.sessionId }`, so token refreshes are picked up\n * automatically.\n *\n * Optional inside a `ReactorProvider` (inherits the provider's resolver)\n * and in local-dev mode.\n */\n getJwt?: JwtResolver;\n}\n\nexport interface UseClipDownloadResult {\n /** Current state of the most recent download attempt. */\n state: ClipDownloadState;\n /**\n * Trigger a download. Resolves with the assembled fragmented-MP4 Blob, or\n * `undefined` if a download was already in flight (a no-op in that case)\n * or the attempt failed. Errors are surfaced via {@link state} rather than\n * a rejection — check `state.kind === \"error\"` to drive failure UI.\n */\n download: () => Promise<Blob | undefined>;\n /** Reset to `idle`. Does *not* cancel an in-flight download. */\n reset: () => void;\n}\n\n/**\n * Headless download primitive for a {@link Clip}. Wraps `downloadClipAsFile`\n * in a React state machine so the consumer can render any button they want,\n * anywhere they want, and still get progress + error feedback. Used\n * internally by `ClipDownloadButton` — reach for this hook directly when you\n * need custom placement or styling.\n *\n * `download`/`reset` are stable callback identities across renders, so\n * they're safe to pass through memoized children without forcing re-renders.\n */\nexport function useClipDownload(clip: Clip, options: UseClipDownloadOptions = {}): UseClipDownloadResult {\n const [state, setState] = useState<ClipDownloadState>({ kind: 'idle' });\n\n // `undefined` outside a `ReactorProvider`; used to inherit the provider's\n // JWT resolver when `options.getJwt` is omitted.\n const store = useContext(ReactorContext);\n\n // Latest-value refs so `download` can be a stable callback (empty deps)\n // without forcing the caller to memoize `clip`/`options`.\n const clipRef = useRef(clip);\n const filenameRef = useRef<string | null>(options.filename ?? 'reactor-clip.mp4');\n const getJwtRef = useRef(options.getJwt);\n const storeRef = useRef(store);\n\n clipRef.current = clip;\n filenameRef.current = options.filename === undefined ? 'reactor-clip.mp4' : options.filename;\n getJwtRef.current = options.getJwt;\n storeRef.current = store;\n\n // Re-entrancy guard. Lives in a ref (not state) so back-to-back\n // synchronous clicks before the first `setState` flushes are still\n // handled correctly.\n const inFlightRef = useRef(false);\n\n // `downloadClipAsFile` polls the manifest indefinitely by default, so an\n // in-flight download that never resolves would otherwise outlive the\n // component. Abort it on unmount; the abort surfaces as an `AbortError`,\n // swallowed below rather than painted as a failure.\n const abortRef = useRef<AbortController | null>(null);\n\n useEffect(() => () => abortRef.current?.abort(), []);\n\n const download = useCallback(async (): Promise<Blob | undefined> => {\n if (inFlightRef.current) {\n return undefined;\n }\n inFlightRef.current = true;\n const abort = new AbortController();\n\n abortRef.current = abort;\n setState({ kind: 'downloading', fetched: 0, total: 0 });\n try {\n // Explicit `options.getJwt` wins; fall back to the provider's source.\n // Read through the refs on every poll, so a rerender with a new\n // `getJwt` during a `202` wait reaches the next poll.\n const source = () => getJwtRef.current ?? storeRef.current?.getState().internal.reactor.getJwtResolver();\n const downloadOptions: Parameters<typeof downloadClipAsFile>[2] = {\n signal: abort.signal,\n onProgress: ({ fetched, total }) => setState({ kind: 'downloading', fetched, total }),\n };\n\n if (source() !== undefined) {\n downloadOptions.jwt = (context) => resolveJwtSource(source() ?? '', context);\n }\n\n const blob = await downloadClipAsFile(clipRef.current, filenameRef.current, downloadOptions);\n\n setState({ kind: 'idle' });\n return blob;\n } catch (err) {\n if (err instanceof DOMException && err.name === 'AbortError') {\n return undefined;\n }\n const message =\n err instanceof RecordingError ? `${err.code}: ${err.reason}` : err instanceof Error ? err.message : String(err);\n\n setState({ kind: 'error', message });\n return undefined;\n } finally {\n inFlightRef.current = false;\n }\n }, []);\n\n const reset = useCallback(() => setState({ kind: 'idle' }), []);\n\n return { state, download, reset };\n}\n"],"mappings":";;;AAAA,SAAS,kBAAkB;;;ACMpB,SAAS,qBAAqB,MAAsC;AACzE,QAAM,eAA6B;AAAA,IACjC,iBAAiB,KAAK;AAAA,IACtB,QAAQ,KAAK;AAAA,EAC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Aa,eAAe,CAAC,CAAC;AAIpC,QAAM,eAAeC,QAAO,SAAS;AACrC,QAAM,aAAaA,QAAO,OAAO;AAEjC,eAAa,UAAU;AACvB,aAAW,UAAU;AAKrB,EAAAC,WAAU,MAAM;AACd,QAAI,MAAM,SAAS,SAAS;AAC1B,iBAAW,UAAU,IAAI,MAAM,MAAM,OAAO,CAAC;AAAA,IAC/C;AAAA,EACF,GAAG,CAAC,KAAK,CAAC;AAEV,QAAM,UAAU,OAAO,aAAa,aAAa,SAAS,KAAK,IAAI,aAAa,SAAY,WAAW,aAAa,KAAK;AAEzH,SACE,gBAAAF;AAAA,IAAC;AAAA;AAAA,MACC,MAAK;AAAA,MACL,SAAS,MAAM;AACb,aAAK,SAAS,EAAE,KAAK,CAAC,SAAS;AAC7B,cAAI,MAAM;AACR,yBAAa,UAAU,IAAI;AAAA,UAC7B;AAAA,QACF,CAAC;AAAA,MACH;AAAA,MACA,UAAU;AAAA,MACV,OAAO,MAAM,SAAS,UAAU,MAAM,UAAU;AAAA,MAChD;AAAA,MACA,OAAO;AAAA,QACL,SAAS;AAAA,QACT,cAAc;AAAA,QACd,QAAQ;AAAA,QACR,YAAY;AAAA,QACZ,OAAO;AAAA,QACP,MAAM;AAAA,QACN,QAAQ,aAAa,YAAY;AAAA,QACjC,SAAS,aAAa,MAAM;AAAA,QAC5B,YAAY;AAAA,QACZ,GAAG;AAAA,MACL;AAAA,MAEC;AAAA;AAAA,EACH;AAEJ;AAEA,SAAS,aAAa,OAAqC;AACzD,MAAI,MAAM,SAAS,eAAe;AAChC,QAAI,MAAM,QAAQ,GAAG;AACnB,aAAO,eAAe,MAAM,OAAO,IAAI,MAAM,KAAK;AAAA,IACpD;AACA,WAAO;AAAA,EACT;AACA,SAAO;AACT;","names":["options","useEffect","useRef","useState","useRef","useEffect","useState","useEffect","useRef","useState","jsx","useState","useEffect","useRef","useEffect","useRef","useState","jsx","useState","useRef","useEffect","useContext","useEffect","useRef","useState","jsx","jsxs","useRef","useState","useContext","useEffect","useEffect","useRef","useContext","useEffect","useRef","useState","useState","useContext","useRef","useEffect","jsx","useRef","useEffect"]}
|