@mebius-io/web 0.3.0 → 0.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 +25 -2
- package/dist/index.cjs +130 -9
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +32 -3
- package/dist/index.d.ts +32 -3
- package/dist/index.global.js +130 -9
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +130 -9
- package/dist/index.js.map +1 -1
- package/package.json +12 -11
- package/LICENSE +0 -21
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/events.ts","../src/internal/view-target.ts","../src/internal/webrtc-util.ts","../src/internal/publish-transport.ts","../src/internal/ll-view-transport.ts","../src/internal/scale-view-transport.ts","../src/internal/balanced-view-transport.ts","../src/internal/transport.ts","../src/broadcaster.ts","../src/player.ts","../src/internal/signaling.ts","../src/internal/token.ts","../src/client.ts","../src/mebius.ts"],"sourcesContent":["/**\n * @mebius-io/web — Mebius Client SDK for the web.\n *\n * Public surface only. Everything under `internal/` is private and is never\n * re-exported here.\n */\nexport { Mebius } from \"./mebius.js\";\nexport { MebiusClient } from \"./client.js\";\nexport { MebiusBroadcaster } from \"./broadcaster.js\";\nexport { MebiusPlayer } from \"./player.js\";\nexport { MebiusError, mebiusError } from \"./errors.js\";\n\nexport type {\n ClientEventMap,\n BroadcasterEventMap,\n PlayerEventMap,\n} from \"./events.js\";\n\nexport type {\n MebiusInitOptions,\n MebiusConnectOptions,\n MebiusDelivery,\n BroadcasterOptions,\n PlayerOptions,\n PlaybackMode,\n ViewTarget,\n MediaConstraint,\n BroadcastStats,\n PlaybackStats,\n MebiusErrorCode,\n} from \"./types.js\";\n","import type { MebiusErrorCode } from \"./types.js\";\n\n/**\n * The single error type the SDK surfaces. Always uses Mebius terminology —\n * never raw transport/protocol wording.\n *\n * Inspect {@link MebiusError.code} to decide how to recover (for example,\n * refresh the token on `\"TOKEN_EXPIRED\"`).\n */\nexport class MebiusError extends Error {\n readonly code: MebiusErrorCode;\n /** The underlying cause, if any. Useful for logging, opaque to the contract. */\n readonly cause?: unknown;\n\n constructor(code: MebiusErrorCode, message: string, cause?: unknown) {\n super(message);\n this.name = \"MebiusError\";\n this.code = code;\n this.cause = cause;\n Object.setPrototypeOf(this, MebiusError.prototype);\n }\n}\n\n/** Human-readable default messages, kept in Mebius terms. */\nconst DEFAULT_MESSAGES: Record<MebiusErrorCode, string> = {\n TOKEN_EXPIRED: \"Your Mebius token has expired. Mint a fresh token and reconnect.\",\n PERMISSION_DENIED: \"Camera/microphone permission was denied by the user or browser.\",\n CONNECTION_FAILED: \"Could not establish a connection to the Mebius gateway.\",\n NOT_CONNECTED: \"Not connected to Mebius. Call connect() before using this client.\",\n STREAM_NOT_FOUND: \"The requested stream could not be found on the Mebius gateway.\",\n UNKNOWN: \"An unexpected Mebius error occurred.\",\n};\n\n/** Create a {@link MebiusError}, falling back to a sensible default message. */\nexport function mebiusError(\n code: MebiusErrorCode,\n message?: string,\n cause?: unknown,\n): MebiusError {\n return new MebiusError(code, message ?? DEFAULT_MESSAGES[code], cause);\n}\n","import type { MebiusError } from \"./errors.js\";\nimport type { BroadcastStats, PlaybackStats } from \"./types.js\";\n\n// NOTE: these are `type` aliases (not interfaces) so they satisfy the\n// `Record<string, unknown>` constraint on TypedEmitter — TS only treats object\n// type aliases (not augmentable interfaces) as having an implicit index\n// signature.\n\n/** Event payloads emitted by {@link MebiusClient}. */\nexport type ClientEventMap = {\n connected: void;\n disconnected: { reason?: string };\n error: MebiusError;\n};\n\n/** Event payloads emitted by a broadcaster. */\nexport type BroadcasterEventMap = {\n started: { streamId: string };\n stopped: void;\n stats: BroadcastStats;\n};\n\n/** Event payloads emitted by a player. */\nexport type PlayerEventMap = {\n playing: { streamId: string };\n buffering: void;\n ended: void;\n stats: PlaybackStats;\n};\n\ntype Listener<T> = (payload: T) => void;\n\n/**\n * A tiny strongly-typed event emitter. `EventMap` maps each event name to its\n * payload type, so `on(\"started\", cb)` infers `cb`'s argument automatically.\n */\nexport class TypedEmitter<EventMap extends Record<string, unknown>> {\n private readonly listeners = new Map<keyof EventMap, Set<Listener<unknown>>>();\n\n /** Subscribe to an event. Returns an unsubscribe function. */\n on<K extends keyof EventMap>(event: K, cb: Listener<EventMap[K]>): () => void {\n let set = this.listeners.get(event);\n if (!set) {\n set = new Set();\n this.listeners.set(event, set);\n }\n set.add(cb as Listener<unknown>);\n return () => this.off(event, cb);\n }\n\n /** Unsubscribe a previously-registered listener. */\n off<K extends keyof EventMap>(event: K, cb: Listener<EventMap[K]>): void {\n this.listeners.get(event)?.delete(cb as Listener<unknown>);\n }\n\n /** Emit an event to all listeners. Internal use. */\n protected emit<K extends keyof EventMap>(event: K, payload: EventMap[K]): void {\n const set = this.listeners.get(event);\n if (!set) return;\n for (const cb of [...set]) (cb as Listener<EventMap[K]>)(payload);\n }\n\n /** Remove every listener. Internal use during teardown. */\n protected removeAllListeners(): void {\n this.listeners.clear();\n }\n}\n","/** INTERNAL — resolve a public {@link ViewTarget} to a real `<video>` element. */\nimport { mebiusError } from \"../errors.js\";\nimport type { ViewTarget } from \"../types.js\";\n\nexport function resolveVideoElement(target: ViewTarget): HTMLVideoElement {\n if (typeof target !== \"string\") {\n if (target instanceof HTMLVideoElement) return target;\n throw mebiusError(\"UNKNOWN\", \"View target must be a <video> element or a CSS selector.\");\n }\n const el = document.querySelector(target);\n if (!el) {\n throw mebiusError(\"UNKNOWN\", `No element matches the selector \"${target}\".`);\n }\n if (!(el instanceof HTMLVideoElement)) {\n throw mebiusError(\"UNKNOWN\", `Selector \"${target}\" did not resolve to a <video> element.`);\n }\n return el;\n}\n","/** INTERNAL — small WebRTC helpers shared by publish/view transports. */\n\n/**\n * Wait until ICE gathering completes (or a short timeout elapses) so the SDP\n * we send already contains candidates. Keeps the gateway exchange to a single\n * round-trip.\n */\nexport function waitForIceGathering(pc: RTCPeerConnection, timeoutMs = 2000): Promise<void> {\n if (pc.iceGatheringState === \"complete\") return Promise.resolve();\n return new Promise((resolve) => {\n const done = () => {\n pc.removeEventListener(\"icegatheringstatechange\", check);\n clearTimeout(timer);\n resolve();\n };\n const check = () => {\n if (pc.iceGatheringState === \"complete\") done();\n };\n const timer = setTimeout(done, timeoutMs);\n pc.addEventListener(\"icegatheringstatechange\", check);\n });\n}\n\n/** Default ICE configuration. The gateway may also relay; STUN aids direct paths. */\nexport const DEFAULT_RTC_CONFIG: RTCConfiguration = {\n iceServers: [{ urls: \"stun:stun.l.google.com:19302\" }],\n};\n","/**\n * INTERNAL — publish transport (WHIP over the gateway).\n *\n * Sends a locally-captured MediaStream to the Mebius gateway via a standard\n * WHIP offer/answer exchange. Hidden from the public API.\n */\nimport type { BroadcastStats } from \"../types.js\";\nimport { mebiusError } from \"../errors.js\";\nimport type { SignalingClient } from \"./signaling.js\";\nimport type { PublishTransport } from \"./transport.js\";\nimport { DEFAULT_RTC_CONFIG, waitForIceGathering } from \"./webrtc-util.js\";\n\nexport class WhipPublishTransport implements PublishTransport {\n private pc: RTCPeerConnection | null = null;\n private resourceUrl: string | null = null;\n\n constructor(private readonly signaling: SignalingClient) {}\n\n async start(streamId: string, stream: MediaStream): Promise<void> {\n const pc = new RTCPeerConnection(DEFAULT_RTC_CONFIG);\n this.pc = pc;\n\n for (const track of stream.getTracks()) {\n pc.addTrack(track, stream);\n }\n\n const offer = await pc.createOffer();\n await pc.setLocalDescription(offer);\n await waitForIceGathering(pc);\n\n const localSdp = pc.localDescription?.sdp;\n if (!localSdp) throw mebiusError(\"CONNECTION_FAILED\", \"Failed to create a local session.\");\n\n const { answer, resourceUrl } = await this.signaling.exchangeSession(\n \"publish\",\n streamId,\n localSdp,\n );\n this.resourceUrl = resourceUrl;\n await pc.setRemoteDescription({ type: \"answer\", sdp: answer });\n }\n\n async replaceVideoTrack(track: MediaStreamTrack | null): Promise<void> {\n const sender = this.pc?.getSenders().find((s) => s.track?.kind === \"video\");\n if (sender) await sender.replaceTrack(track);\n }\n\n async stop(): Promise<void> {\n await this.signaling.deleteResource(this.resourceUrl);\n this.resourceUrl = null;\n this.pc?.getSenders().forEach((s) => s.track?.stop());\n this.pc?.close();\n this.pc = null;\n }\n\n async getStats(): Promise<BroadcastStats | null> {\n if (!this.pc) return null;\n const report = await this.pc.getStats();\n let bitrateKbps = 0;\n let framesPerSecond = 0;\n let rttMs: number | undefined;\n report.forEach((stat) => {\n if (stat.type === \"outbound-rtp\" && !stat.isRemote) {\n if (typeof stat.framesPerSecond === \"number\") framesPerSecond = stat.framesPerSecond;\n }\n if (stat.type === \"candidate-pair\" && stat.state === \"succeeded\") {\n if (typeof stat.availableOutgoingBitrate === \"number\") {\n bitrateKbps = Math.round(stat.availableOutgoingBitrate / 1000);\n }\n if (typeof stat.currentRoundTripTime === \"number\") {\n rttMs = Math.round(stat.currentRoundTripTime * 1000);\n }\n }\n });\n return { bitrateKbps, framesPerSecond, rttMs };\n }\n}\n","/**\n * INTERNAL — low-latency view transport (WHEP over the gateway).\n *\n * Pulls a remote stream from the Mebius gateway via a standard WHEP exchange\n * and renders it into a video element. Hidden from the public API.\n */\nimport type { PlaybackStats } from \"../types.js\";\nimport { mebiusError } from \"../errors.js\";\nimport type { SignalingClient } from \"./signaling.js\";\nimport type { ViewTransport } from \"./transport.js\";\nimport { DEFAULT_RTC_CONFIG, waitForIceGathering } from \"./webrtc-util.js\";\n\nexport class WhepViewTransport implements ViewTransport {\n private pc: RTCPeerConnection | null = null;\n private resourceUrl: string | null = null;\n private endedCb: (() => void) | null = null;\n private bufferingCb: (() => void) | null = null;\n\n constructor(private readonly signaling: SignalingClient) {}\n\n onEnded(cb: () => void): void {\n this.endedCb = cb;\n }\n\n onBuffering(cb: () => void): void {\n this.bufferingCb = cb;\n }\n\n async start(streamId: string, video: HTMLVideoElement): Promise<void> {\n const pc = new RTCPeerConnection(DEFAULT_RTC_CONFIG);\n this.pc = pc;\n const remote = new MediaStream();\n\n pc.addTransceiver(\"video\", { direction: \"recvonly\" });\n pc.addTransceiver(\"audio\", { direction: \"recvonly\" });\n\n pc.ontrack = (ev) => {\n remote.addTrack(ev.track);\n video.srcObject = remote;\n void video.play().catch(() => {\n /* autoplay may require a user gesture; left to the app */\n });\n };\n pc.onconnectionstatechange = () => {\n if (pc.connectionState === \"disconnected\" || pc.connectionState === \"failed\") {\n this.bufferingCb?.();\n }\n if (pc.connectionState === \"closed\") this.endedCb?.();\n };\n\n const offer = await pc.createOffer();\n await pc.setLocalDescription(offer);\n await waitForIceGathering(pc);\n\n const localSdp = pc.localDescription?.sdp;\n if (!localSdp) throw mebiusError(\"CONNECTION_FAILED\", \"Failed to create a local session.\");\n\n const { answer, resourceUrl } = await this.signaling.exchangeSession(\n \"view\",\n streamId,\n localSdp,\n );\n this.resourceUrl = resourceUrl;\n await pc.setRemoteDescription({ type: \"answer\", sdp: answer });\n }\n\n async stop(): Promise<void> {\n await this.signaling.deleteResource(this.resourceUrl);\n this.resourceUrl = null;\n this.pc?.close();\n this.pc = null;\n }\n\n async getStats(): Promise<PlaybackStats | null> {\n if (!this.pc) return null;\n const report = await this.pc.getStats();\n let bitrateKbps = 0;\n let framesPerSecond = 0;\n let latencyMs: number | undefined;\n report.forEach((stat) => {\n if (stat.type === \"inbound-rtp\") {\n if (typeof stat.framesPerSecond === \"number\") framesPerSecond = stat.framesPerSecond;\n if (typeof stat.jitter === \"number\") latencyMs = Math.round(stat.jitter * 1000);\n }\n if (stat.type === \"candidate-pair\" && stat.state === \"succeeded\") {\n if (typeof stat.availableIncomingBitrate === \"number\") {\n bitrateKbps = Math.round(stat.availableIncomingBitrate / 1000);\n }\n }\n });\n return { bitrateKbps, framesPerSecond, latencyMs };\n }\n}\n","/**\n * INTERNAL — scale view transport (HLS via hls.js / native).\n *\n * For large-audience playback Mebius delivers an HLS playlist from the\n * gateway. hls.js is loaded lazily; Safari plays the playlist natively.\n * Hidden from the public API.\n */\nimport type { PlaybackStats } from \"../types.js\";\nimport { mebiusError } from \"../errors.js\";\nimport type { SignalingClient } from \"./signaling.js\";\nimport type { ViewTransport } from \"./transport.js\";\n\n// Loaded on demand so it never weighs down low-latency-only apps.\ntype HlsModule = typeof import(\"hls.js\");\ntype HlsInstance = import(\"hls.js\").default;\n\nexport class HlsViewTransport implements ViewTransport {\n private hls: HlsInstance | null = null;\n private video: HTMLVideoElement | null = null;\n private endedCb: (() => void) | null = null;\n private bufferingCb: (() => void) | null = null;\n\n /**\n * deliveryPath, when given, is a gateway-relative path from the gateway's own\n * delivery list — that is how a CDN-backed playlist gets used instead of the\n * origin one. Without it this falls back to the origin playlist, which is\n * still correct, just served from our own bandwidth.\n */\n constructor(\n private readonly signaling: SignalingClient,\n private readonly deliveryPath?: string,\n ) {}\n\n onEnded(cb: () => void): void {\n this.endedCb = cb;\n }\n\n onBuffering(cb: () => void): void {\n this.bufferingCb = cb;\n }\n\n async start(streamId: string, video: HTMLVideoElement): Promise<void> {\n this.video = video;\n const url = this.deliveryPath\n ? this.signaling.deliveryUrl(this.deliveryPath)\n : this.signaling.scalePlaylistUrl(streamId);\n\n video.addEventListener(\"ended\", () => this.endedCb?.());\n video.addEventListener(\"waiting\", () => this.bufferingCb?.());\n\n // Safari and iOS play HLS natively — no library needed.\n if (video.canPlayType(\"application/vnd.apple.mpegurl\")) {\n video.src = url;\n await video.play().catch(() => undefined);\n return;\n }\n\n let mod: HlsModule;\n try {\n mod = await import(\"hls.js\");\n } catch (cause) {\n throw mebiusError(\"CONNECTION_FAILED\", \"Scale playback support failed to load.\", cause);\n }\n const Hls = mod.default;\n if (!Hls.isSupported()) {\n throw mebiusError(\"CONNECTION_FAILED\", \"Scale playback is not supported in this browser.\");\n }\n\n const hls = new Hls({ lowLatencyMode: true });\n this.hls = hls;\n hls.on(Hls.Events.ERROR, (_evt, data) => {\n if (data.fatal) this.bufferingCb?.();\n });\n hls.loadSource(url);\n hls.attachMedia(video);\n await video.play().catch(() => undefined);\n }\n\n async stop(): Promise<void> {\n this.hls?.destroy();\n this.hls = null;\n if (this.video) {\n this.video.removeAttribute(\"src\");\n this.video.load();\n }\n this.video = null;\n }\n\n async getStats(): Promise<PlaybackStats | null> {\n if (!this.video) return null;\n const level = this.hls?.levels?.[this.hls.currentLevel];\n return {\n bitrateKbps: level ? Math.round(level.bitrate / 1000) : 0,\n framesPerSecond: 0,\n };\n }\n}\n","/**\n * INTERNAL — balanced view transport (HTTP-FLV via flv.js).\n *\n * For typical one-to-many web viewers Mebius pulls an HTTP-FLV stream and feeds\n * it through flv.js (Media Source Extensions). Latency is ~1-3s — lower than\n * HLS, higher than the WebRTC pull — and it scales over a CDN edge.\n *\n * History worth keeping: 0.2.0 deleted this file on the reading that the mode\n * was \"unserved\", because the gateway had no route for it. The route simply had\n * not been built yet — production web playback has always been HTTP-FLV. The\n * gateway now serves it, so this comes back, with one change: the URL is no\n * longer derived from a hardcoded path. It comes from the gateway's own\n * delivery list, so the gateway can move or re-point that path without an SDK\n * release.\n *\n * Browser-only: flv.js needs MSE, which iOS Safari lacks — createViewCandidates\n * is what keeps this off platforms that cannot play it. flv.js is a BUNDLED\n * dependency, never a peer dependency: an integrator must never have to type a\n * transport library's name to make Mebius work.\n *\n * Hidden from the public API; the public surface speaks only of the\n * `\"balanced\"` playback mode.\n */\nimport type { PlaybackStats } from \"../types.js\";\nimport { mebiusError } from \"../errors.js\";\nimport type { SignalingClient } from \"./signaling.js\";\nimport type { ViewTransport } from \"./transport.js\";\n\ntype FlvModule = typeof import(\"flv.js\");\ntype FlvPlayer = ReturnType<FlvModule[\"default\"][\"createPlayer\"]>;\n\nexport class FlvViewTransport implements ViewTransport {\n private player: FlvPlayer | null = null;\n private video: HTMLVideoElement | null = null;\n private endedCb: (() => void) | null = null;\n private bufferingCb: (() => void) | null = null;\n\n constructor(\n private readonly signaling: SignalingClient,\n private readonly deliveryPath: string,\n ) {}\n\n onEnded(cb: () => void): void {\n this.endedCb = cb;\n }\n\n onBuffering(cb: () => void): void {\n this.bufferingCb = cb;\n }\n\n async start(_streamId: string, video: HTMLVideoElement): Promise<void> {\n this.video = video;\n const url = this.signaling.deliveryUrl(this.deliveryPath);\n\n video.addEventListener(\"ended\", () => this.endedCb?.());\n video.addEventListener(\"waiting\", () => this.bufferingCb?.());\n\n let mod: FlvModule;\n try {\n // Literal specifier on purpose: a bundler must be able to see it and inline\n // the library into the single-file drop-in build. A computed specifier\n // leaves a bare module request in the output, which no browser can resolve.\n // Types come from internal/flv.js.d.ts.\n mod = await import(\"flv.js\");\n } catch (cause) {\n throw mebiusError(\"CONNECTION_FAILED\", \"Balanced playback support failed to load.\", cause);\n }\n\n const flvjs = mod.default;\n if (!flvjs.isSupported()) {\n throw mebiusError(\"CONNECTION_FAILED\", \"Balanced playback is not supported in this browser.\");\n }\n\n const player = flvjs.createPlayer({ type: \"flv\", url, isLive: true });\n this.player = player;\n player.on(flvjs.Events.ERROR ?? \"error\", () => this.bufferingCb?.());\n player.attachMediaElement(video);\n player.load();\n await Promise.resolve(player.play()).catch(() => undefined);\n }\n\n async stop(): Promise<void> {\n if (this.player) {\n this.player.unload();\n this.player.detachMediaElement();\n this.player.destroy();\n this.player = null;\n }\n if (this.video) {\n this.video.removeAttribute(\"src\");\n this.video.load();\n }\n this.video = null;\n }\n\n async getStats(): Promise<PlaybackStats | null> {\n if (!this.video) return null;\n return {\n bitrateKbps: 0,\n framesPerSecond: 0,\n latencyMs: undefined,\n };\n }\n}\n","/**\n * INTERNAL — transport interfaces + auto-selection.\n *\n * The public API never names a transport; it only asks for a playback *mode*.\n * This factory maps a mode to the right hidden delivery mechanism.\n */\nimport type { BroadcastStats, MebiusDelivery, PlaybackMode, PlaybackStats } from \"../types.js\";\nimport type { SignalingClient } from \"./signaling.js\";\nimport { WhipPublishTransport } from \"./publish-transport.js\";\nimport { WhepViewTransport } from \"./ll-view-transport.js\";\nimport { HlsViewTransport } from \"./scale-view-transport.js\";\nimport { FlvViewTransport } from \"./balanced-view-transport.js\";\n\n/** Hidden transport that sends a captured stream to the gateway. */\nexport interface PublishTransport {\n start(streamId: string, stream: MediaStream): Promise<void>;\n stop(): Promise<void>;\n getStats(): Promise<BroadcastStats | null>;\n /** Swap the outgoing video track in place (e.g. on camera switch). */\n replaceVideoTrack(track: MediaStreamTrack | null): Promise<void>;\n}\n\n/** Hidden transport that renders a remote stream into a video element. */\nexport interface ViewTransport {\n start(streamId: string, video: HTMLVideoElement): Promise<void>;\n stop(): Promise<void>;\n getStats(): Promise<PlaybackStats | null>;\n /** Fired by the transport when playback reaches its natural end. */\n onEnded(cb: () => void): void;\n /** Fired when the transport (re)enters a buffering state. */\n onBuffering(cb: () => void): void;\n}\n\nexport function createPublishTransport(signaling: SignalingClient): PublishTransport {\n return new WhipPublishTransport(signaling);\n}\n\n/**\n * Delivery kinds the gateway may offer. Neutral by design — the gateway names\n * an intent (\"fast\", \"wide\"), never a protocol, and this module is the only\n * place that decides which transport serves which intent. That is what lets the\n * gateway change protocol without an SDK release.\n */\nconst KIND_FAST = \"fast\";\nconst KIND_WIDE = \"wide\";\nconst KIND_LOCAL = \"local\";\n\n/** True when this browser can play a Media-Source-based stream (not iOS Safari). */\nfunction canPlayBuffered(): boolean {\n return typeof MediaSource !== \"undefined\";\n}\n\nfunction transportFor(\n kind: string,\n path: string,\n signaling: SignalingClient,\n): ViewTransport | null {\n if (kind === KIND_FAST) return canPlayBuffered() ? new FlvViewTransport(signaling, path) : null;\n if (kind === KIND_WIDE || kind === KIND_LOCAL) return new HlsViewTransport(signaling, path);\n // An unknown kind is a newer gateway talking to an older SDK. Skip it rather\n // than guess: the list is ordered, so the next entry is the intended fallback.\n return null;\n}\n\n/**\n * Ordered list of transports to try for a playback mode, most-preferred first.\n *\n * Returning a LIST rather than one transport is the whole point: a transport can\n * connect and still deliver no frames (a CDN edge with no ingest yet, MSE\n * failing mid-init, WebRTC reporting `connected` with zero frames). The player\n * walks this list on a watchdog, so a dead first choice degrades instead of\n * showing a black frame.\n *\n * `deliveries` comes from the gateway and is already in the gateway's preferred\n * order; ordering policy therefore lives server-side, not here.\n */\nexport function createViewCandidates(\n mode: PlaybackMode,\n signaling: SignalingClient,\n deliveries: readonly MebiusDelivery[] = [],\n): ViewTransport[] {\n const fromGateway = (kinds: readonly string[]): ViewTransport[] =>\n deliveries\n .filter((d) => kinds.includes(d.kind))\n .map((d) => transportFor(d.kind, d.path, signaling))\n .filter((t): t is ViewTransport => t !== null);\n\n // Every mode ends with the origin playlist, reachable with no delivery list at\n // all. Without this, a caller that never passes `deliveries` (every 0.x\n // integration today) would get an empty candidate list and fail to play.\n const originFallback = new HlsViewTransport(signaling);\n const allKinds = [KIND_FAST, KIND_WIDE, KIND_LOCAL];\n\n switch (mode) {\n case \"low-latency\":\n // The real-time pull is not in `deliveries` — it is signaled, not fetched.\n return [new WhepViewTransport(signaling), ...fromGateway(allKinds), originFallback];\n case \"balanced\":\n return [...fromGateway(allKinds), originFallback];\n case \"scale\":\n return [...fromGateway([KIND_WIDE, KIND_LOCAL]), originFallback];\n case \"auto\":\n // Take the gateway ordering verbatim: it knows which paths are actually\n // serving and what each one costs to serve.\n return [...fromGateway(allKinds), originFallback];\n }\n}\n\n/**\n * Single-transport selection, kept for callers written against 0.1/0.2.\n * @deprecated Use {@link createViewCandidates} — a single transport cannot fall\n * back, so a dead delivery becomes a black frame.\n */\nexport function createViewTransport(\n mode: PlaybackMode,\n signaling: SignalingClient,\n): ViewTransport {\n return createViewCandidates(mode, signaling)[0]!;\n}\n","import { mebiusError } from \"./errors.js\";\nimport { TypedEmitter, type BroadcasterEventMap } from \"./events.js\";\nimport { resolveVideoElement } from \"./internal/view-target.js\";\nimport type { SignalingClient } from \"./internal/signaling.js\";\nimport { createPublishTransport, type PublishTransport } from \"./internal/transport.js\";\nimport type { BroadcasterOptions, MediaConstraint, ViewTarget } from \"./types.js\";\n\nconst STATS_INTERVAL_MS = 2000;\n\n/**\n * Publishes the local camera/microphone to a Mebius stream.\n *\n * Create one with {@link MebiusClient.createBroadcaster}, then\n * {@link MebiusBroadcaster.start | start} it with a stream id.\n */\nexport class MebiusBroadcaster extends TypedEmitter<BroadcasterEventMap> {\n private readonly transport: PublishTransport;\n private stream: MediaStream | null = null;\n private facingMode: \"user\" | \"environment\" = \"user\";\n private statsTimer: ReturnType<typeof setInterval> | null = null;\n private started = false;\n\n /** @internal */\n constructor(\n signaling: SignalingClient,\n private readonly options: BroadcasterOptions,\n ) {\n super();\n this.transport = createPublishTransport(signaling);\n }\n\n /** Begin broadcasting under the given stream id. */\n async start(streamId: string): Promise<void> {\n if (this.started) return;\n this.stream = await this.capture();\n await this.transport.start(streamId, this.stream);\n this.started = true;\n this.startStats();\n this.emit(\"started\", { streamId });\n }\n\n /** Stop broadcasting and release the camera/microphone. */\n async stop(): Promise<void> {\n this.stopStats();\n await this.transport.stop();\n this.stream?.getTracks().forEach((t) => t.stop());\n this.stream = null;\n this.started = false;\n this.emit(\"stopped\", undefined);\n }\n\n /** Flip between front and back camera (where available). */\n async switchCamera(): Promise<void> {\n if (!this.stream) return;\n this.facingMode = this.facingMode === \"user\" ? \"environment\" : \"user\";\n const next = await navigator.mediaDevices.getUserMedia({\n video: { facingMode: this.facingMode },\n audio: false,\n });\n const newTrack = next.getVideoTracks()[0] ?? null;\n const oldTrack = this.stream.getVideoTracks()[0];\n if (oldTrack) {\n this.stream.removeTrack(oldTrack);\n oldTrack.stop();\n }\n if (newTrack) this.stream.addTrack(newTrack);\n await this.transport.replaceVideoTrack(newTrack);\n }\n\n /** Mute or unmute the outgoing microphone. */\n setMicEnabled(enabled: boolean): void {\n this.stream?.getAudioTracks().forEach((t) => (t.enabled = enabled));\n }\n\n /** Enable or disable the outgoing camera. */\n setCameraEnabled(enabled: boolean): void {\n this.stream?.getVideoTracks().forEach((t) => (t.enabled = enabled));\n }\n\n /**\n * Web convenience: render the local camera preview into a `<video>` element.\n * This is the web analog of the mobile preview view; it does not affect what\n * is broadcast.\n */\n attachPreview(target: ViewTarget): void {\n if (!this.stream) return;\n const video = resolveVideoElement(target);\n video.srcObject = this.stream;\n video.muted = true;\n void video.play().catch(() => undefined);\n }\n\n private async capture(): Promise<MediaStream> {\n const video = normalize(this.options.video, true);\n const audio = normalize(this.options.audio, true);\n try {\n return await navigator.mediaDevices.getUserMedia({ video, audio });\n } catch (cause) {\n throw mebiusError(\"PERMISSION_DENIED\", undefined, cause);\n }\n }\n\n private startStats(): void {\n this.statsTimer = setInterval(async () => {\n const stats = await this.transport.getStats();\n if (stats) this.emit(\"stats\", stats);\n }, STATS_INTERVAL_MS);\n }\n\n private stopStats(): void {\n if (this.statsTimer) clearInterval(this.statsTimer);\n this.statsTimer = null;\n }\n}\n\nfunction normalize(c: MediaConstraint | undefined, fallback: boolean): boolean | MediaTrackConstraints {\n if (c === undefined) return fallback;\n return c;\n}\n","import { TypedEmitter, type PlayerEventMap } from \"./events.js\";\nimport { mebiusError } from \"./errors.js\";\nimport { resolveVideoElement } from \"./internal/view-target.js\";\nimport type { SignalingClient } from \"./internal/signaling.js\";\nimport { createViewCandidates, type ViewTransport } from \"./internal/transport.js\";\nimport type { MebiusDelivery, PlayerOptions, ViewTarget } from \"./types.js\";\n\nconst STATS_INTERVAL_MS = 2000;\n\n/**\n * How long a route gets to produce its first frame before we move to the next.\n *\n * Not arbitrary: a route can report a healthy connection and still deliver\n * nothing — a CDN edge that has no ingest yet answers 200 with an empty stream,\n * and a real-time connection reports `connected` while zero frames arrive. The\n * only trustworthy signal is the picture actually advancing, so that is what is\n * measured. 8s is long enough to survive a slow first segment on mobile data and\n * short enough that a viewer has not yet left.\n */\nconst FIRST_FRAME_TIMEOUT_MS = 8000;\n\n/**\n * Plays a Mebius stream into a `<video>` element.\n *\n * Create one with {@link MebiusClient.createPlayer}, optionally choosing a\n * playback {@link PlaybackMode | mode}; Mebius selects the delivery route, and\n * moves to the next one by itself if the current one stops producing frames.\n */\nexport class MebiusPlayer extends TypedEmitter<PlayerEventMap> {\n private readonly candidates: ViewTransport[];\n private transport: ViewTransport | null = null;\n private video: HTMLVideoElement | null = null;\n private statsTimer: ReturnType<typeof setInterval> | null = null;\n private playing = false;\n\n /** @internal */\n constructor(\n signaling: SignalingClient,\n options: PlayerOptions = {},\n deliveries: readonly MebiusDelivery[] = [],\n ) {\n super();\n this.candidates = createViewCandidates(options.mode ?? \"auto\", signaling, deliveries);\n }\n\n /** Start playing `streamId` into the given video element or selector. */\n async play(streamId: string, viewTarget: ViewTarget): Promise<void> {\n if (this.playing) return;\n const video = resolveVideoElement(viewTarget);\n this.video = video;\n\n let lastError: unknown = null;\n for (const candidate of this.candidates) {\n try {\n this.attach(candidate);\n await candidate.start(streamId, video);\n // start() resolving only means the route was opened, not that it is\n // delivering. Confirm with the picture itself before accepting it.\n if (await hasFirstFrame(video)) {\n this.transport = candidate;\n this.playing = true;\n this.startStats();\n this.emit(\"playing\", { streamId });\n return;\n }\n lastError = mebiusError(\"CONNECTION_FAILED\", \"A Mebius route delivered no video.\");\n } catch (cause) {\n lastError = cause;\n }\n // Tear the dead route down before opening the next one: leaving it attached\n // keeps a peer connection or a media source bound to the same element, and\n // the next route then renders into a element that is not free.\n await candidate.stop().catch(() => undefined);\n }\n\n this.video = null;\n throw lastError ?? mebiusError(\"CONNECTION_FAILED\", \"No Mebius route could play this stream.\");\n }\n\n /** Stop playback and detach from the video element. */\n async stop(): Promise<void> {\n this.stopStats();\n await this.transport?.stop();\n this.transport = null;\n this.video = null;\n this.playing = false;\n }\n\n /** Set output volume in the range 0..1. */\n setVolume(volume: number): void {\n const v = Math.min(1, Math.max(0, volume));\n if (this.video) this.video.volume = v;\n }\n\n private attach(transport: ViewTransport): void {\n transport.onEnded(() => {\n // Only the route currently serving may end playback. A route we already\n // abandoned firing late must not close a stream that is playing fine.\n if (this.transport !== transport) return;\n this.playing = false;\n this.stopStats();\n this.emit(\"ended\", undefined);\n });\n transport.onBuffering(() => {\n if (this.transport !== transport) return;\n this.emit(\"buffering\", undefined);\n });\n }\n\n private startStats(): void {\n this.statsTimer = setInterval(async () => {\n const stats = await this.transport?.getStats();\n if (stats) this.emit(\"stats\", stats);\n }, STATS_INTERVAL_MS);\n }\n\n private stopStats(): void {\n if (this.statsTimer) clearInterval(this.statsTimer);\n this.statsTimer = null;\n }\n}\n\n/**\n * Resolves true once the element is actually rendering, false on timeout.\n *\n * `timeupdate` is the signal rather than `readyState` because readiness only\n * says data arrived; a live stream that stalls right after its first buffer can\n * report ready forever without the picture moving.\n */\nfunction hasFirstFrame(video: HTMLVideoElement): Promise<boolean> {\n if (video.currentTime > 0 && !video.paused) return Promise.resolve(true);\n return new Promise((resolve) => {\n const done = (ok: boolean) => {\n clearTimeout(timer);\n video.removeEventListener(\"timeupdate\", onTime);\n resolve(ok);\n };\n const onTime = () => {\n if (video.currentTime > 0) done(true);\n };\n const timer = setTimeout(() => done(false), FIRST_FRAME_TIMEOUT_MS);\n video.addEventListener(\"timeupdate\", onTime);\n });\n}\n","/**\n * INTERNAL — gateway signaling client.\n *\n * This module is the ONE place that knows the wire protocols Mebius uses\n * behind the scenes (WHIP for publishing, WHEP for low-latency viewing, HLS\n * for scale viewing). None of these terms ever escape `internal/` — the public\n * API speaks only in Mebius vocabulary.\n *\n * The gateway HTTP contract (mebius-stream-engine public edge):\n * - Publish: POST {gateway}/whip/{streamId}?token=<jwt> (application/sdp)\n * - View low-latency: POST {gateway}/whep/{streamId}?token=<jwt> (application/sdp)\n * - View scale: GET {gateway}/live/{streamId}/index.m3u8?token=<jwt>\n * - Teardown: DELETE {resourceUrl}\n *\n * The engine validates the token from the `?token=` QUERY parameter (its\n * MediaMTX auth hook + HLS playback gate both read the query, not a header).\n * We still send `Authorization: Bearer <token>` for gateways that prefer it,\n * but the query token is what the engine actually enforces. HLS segment URLs\n * inside the playlist inherit `?token=` automatically (the engine rewrites the\n * m3u8), so no extra header is needed for segment fetches.\n */\nimport { mebiusError } from \"../errors.js\";\n\n/**\n * A media session direction. Deliberately neutral vocabulary (\"publish\" /\n * \"view\") so that if a type bundler ever inlines this into the public `.d.ts`\n * (e.g. via a private field reference), no wire-protocol term leaks to clients.\n * The concrete path segment is derived inside {@link SignalingClient} only.\n */\nexport type SessionKind = \"publish\" | \"view\";\n\nexport interface SessionResult {\n /** The remote session answer returned by the gateway. */\n answer: string;\n /** Resource URL to DELETE on teardown, if the gateway returned one. */\n resourceUrl: string | null;\n}\n\nexport class SignalingClient {\n constructor(\n private readonly gateway: string,\n private readonly token: string,\n ) {}\n\n private base(): string {\n return this.gateway.replace(/\\/+$/, \"\");\n }\n\n private headers(contentType?: string): HeadersInit {\n const h: Record<string, string> = { Authorization: `Bearer ${this.token}` };\n if (contentType) h[\"Content-Type\"] = contentType;\n return h;\n }\n\n /** Append the access token as a query param (the form the engine enforces). */\n private withToken(url: string): string {\n const sep = url.includes(\"?\") ? \"&\" : \"?\";\n return `${url}${sep}token=${encodeURIComponent(this.token)}`;\n }\n\n // Build the playlist URL used by scale-mode playback (HLS path, hidden). The\n // engine serves the playlist under /live/{id}/index.m3u8 and requires the\n // token in the query; segment URIs in the playlist inherit it automatically.\n /**\n * Absolute, tokenized URL for a gateway-relative delivery path handed to us\n * by the gateway (`deliveries[].path`). The gateway decides which paths exist\n * and in what order; the SDK only resolves them against its own base and\n * attaches the access token. Anything that is not a plain gateway-relative\n * path is rejected rather than fetched: an absolute URL there would send the\n * token to a host we did not choose.\n */\n deliveryUrl(path: string): string {\n if (!path.startsWith(\"/\") || path.startsWith(\"//\") || path.includes(\"://\")) {\n throw mebiusError(\"CONNECTION_FAILED\", \"The gateway returned an unusable delivery path.\");\n }\n return this.withToken(`${this.base()}${path}`);\n }\n\n /** Playlist URL for scale-mode playback. */\n scalePlaylistUrl(streamId: string): string {\n return this.withToken(`${this.base()}/live/${encodeURIComponent(streamId)}/index.m3u8`);\n }\n\n // Maps a neutral session kind to the concrete signaling path segment. This\n // mapping (publish -> WHIP, view -> WHEP) lives ONLY in this method body, so\n // the protocol names never appear in any exported type signature.\n private pathFor(kind: SessionKind): string {\n return kind === \"publish\" ? \"whip\" : \"whep\";\n }\n\n // Performs the offer/answer exchange for a publish or a low-latency view\n // session. Protocol detail kept inside the method body so it never leaks into\n // the bundled public .d.ts.\n /**\n * Run the session offer/answer exchange. Throws a {@link MebiusError} with a\n * Mebius-flavored code on failure — never the raw protocol name.\n */\n async exchangeSession(\n kind: SessionKind,\n streamId: string,\n offer: string,\n ): Promise<SessionResult> {\n const url = this.withToken(`${this.base()}/${this.pathFor(kind)}/${encodeURIComponent(streamId)}`);\n let res: Response;\n try {\n res = await fetch(url, {\n method: \"POST\",\n headers: this.headers(\"application/sdp\"),\n body: offer,\n });\n } catch (cause) {\n throw mebiusError(\"CONNECTION_FAILED\", undefined, cause);\n }\n\n if (res.status === 401 || res.status === 403) {\n throw mebiusError(\"TOKEN_EXPIRED\");\n }\n if (res.status === 404) {\n throw mebiusError(\"STREAM_NOT_FOUND\");\n }\n if (!res.ok) {\n throw mebiusError(\"CONNECTION_FAILED\", `Mebius gateway returned ${res.status}.`);\n }\n\n const answer = await res.text();\n const location = res.headers.get(\"Location\");\n const resourceUrl = location ? new URL(location, url).toString() : null;\n return { answer, resourceUrl };\n }\n\n /** Tear down a previously-created session resource. Best-effort. */\n async deleteResource(resourceUrl: string | null): Promise<void> {\n if (!resourceUrl) return;\n try {\n await fetch(resourceUrl, { method: \"DELETE\", headers: this.headers() });\n } catch {\n // Teardown is best-effort; the gateway reaps idle sessions anyway.\n }\n }\n}\n","/**\n * INTERNAL — read (NOT verify) a Mebius token's expiry.\n *\n * The token is a short-lived JWT minted by the developer's backend. The client\n * never verifies it (only the gateway can) — it just peeks at `exp` so it can\n * proactively surface a TOKEN_EXPIRED error and let the app refresh.\n */\nexport interface TokenInfo {\n /** Expiry as a UNIX epoch in milliseconds, if present. */\n expiresAtMs: number | null;\n}\n\nfunction base64UrlDecode(input: string): string {\n const padded = input.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const pad = padded.length % 4 === 0 ? \"\" : \"=\".repeat(4 - (padded.length % 4));\n const b64 = padded + pad;\n if (typeof atob === \"function\") return atob(b64);\n // Node fallback (tests / SSR).\n return Buffer.from(b64, \"base64\").toString(\"binary\");\n}\n\nexport function readToken(token: string): TokenInfo {\n const parts = token.split(\".\");\n if (parts.length < 2) return { expiresAtMs: null };\n try {\n const payload = JSON.parse(base64UrlDecode(parts[1] ?? \"\")) as { exp?: number };\n return { expiresAtMs: typeof payload.exp === \"number\" ? payload.exp * 1000 : null };\n } catch {\n return { expiresAtMs: null };\n }\n}\n","import { MebiusBroadcaster } from \"./broadcaster.js\";\nimport { mebiusError } from \"./errors.js\";\nimport { TypedEmitter, type ClientEventMap } from \"./events.js\";\nimport { MebiusPlayer } from \"./player.js\";\nimport { SignalingClient } from \"./internal/signaling.js\";\nimport { readToken } from \"./internal/token.js\";\nimport type {\n BroadcasterOptions,\n MebiusDelivery,\n MebiusInitOptions,\n PlayerOptions,\n} from \"./types.js\";\n\n/**\n * A live connection to Mebius. Obtain one from {@link Mebius.connect}, then\n * create broadcasters and players from it.\n */\nexport class MebiusClient extends TypedEmitter<ClientEventMap> {\n private readonly signaling: SignalingClient;\n private expiryTimer: ReturnType<typeof setTimeout> | null = null;\n private connected = false;\n\n /** @internal */\n constructor(\n config: MebiusInitOptions,\n private readonly token: string,\n private readonly deliveries: readonly MebiusDelivery[] = [],\n ) {\n super();\n this.signaling = new SignalingClient(config.gateway, token);\n }\n\n /** @internal Called by {@link Mebius.connect}. */\n open(): void {\n const { expiresAtMs } = readToken(this.token);\n const now = Date.now();\n if (expiresAtMs !== null && expiresAtMs <= now) {\n // Surface asynchronously so listeners attached after connect() still fire.\n queueMicrotask(() => this.emit(\"error\", mebiusError(\"TOKEN_EXPIRED\")));\n return;\n }\n this.connected = true;\n if (expiresAtMs !== null) {\n this.expiryTimer = setTimeout(\n () => this.emit(\"error\", mebiusError(\"TOKEN_EXPIRED\")),\n Math.max(0, expiresAtMs - now),\n );\n }\n queueMicrotask(() => this.emit(\"connected\", undefined));\n }\n\n /** Create a broadcaster bound to this connection. */\n createBroadcaster(options: BroadcasterOptions = {}): MebiusBroadcaster {\n this.assertConnected();\n return new MebiusBroadcaster(this.signaling, options);\n }\n\n /** Create a player bound to this connection. */\n createPlayer(options: PlayerOptions = {}): MebiusPlayer {\n this.assertConnected();\n return new MebiusPlayer(this.signaling, options, this.deliveries);\n }\n\n /**\n * Create a monitor: a player tuned for watching a stream you are interacting\n * WITH rather than merely watching — the other side of a co-broadcast, where a\n * second or two of delay makes the interaction feel broken.\n *\n * It is a player with the delay budget spent differently, not a different API:\n * it starts on the real-time route and falls back on its own if that route\n * delivers no frames. Apps used to hand-roll this (open a real-time view, run a\n * timer, swap players when it stayed black); getting the fallback wrong showed a\n * black frame to a live audience, so it belongs here rather than in every app.\n */\n createMonitor(): MebiusPlayer {\n this.assertConnected();\n return new MebiusPlayer(this.signaling, { mode: \"low-latency\" }, this.deliveries);\n }\n\n /** Close the connection and release resources. */\n disconnect(reason?: string): void {\n if (this.expiryTimer) clearTimeout(this.expiryTimer);\n this.expiryTimer = null;\n this.connected = false;\n this.emit(\"disconnected\", { reason });\n this.removeAllListeners();\n }\n\n private assertConnected(): void {\n if (!this.connected) throw mebiusError(\"NOT_CONNECTED\");\n }\n}\n","import { MebiusClient } from \"./client.js\";\nimport { mebiusError } from \"./errors.js\";\nimport type { MebiusConnectOptions, MebiusInitOptions } from \"./types.js\";\n\nlet config: MebiusInitOptions | null = null;\n\n/**\n * Entry point to the Mebius Web SDK.\n *\n * ```ts\n * Mebius.init({ appId: \"app_123\", gateway: \"https://gateway.mebius.io\" });\n * const client = Mebius.connect({ token });\n * ```\n */\nexport const Mebius = {\n /** Configure the SDK once, before connecting. */\n init(options: MebiusInitOptions): void {\n if (!options.appId) throw mebiusError(\"UNKNOWN\", \"Mebius.init requires an appId.\");\n if (!options.gateway) throw mebiusError(\"UNKNOWN\", \"Mebius.init requires a gateway URL.\");\n config = { ...options };\n },\n\n /**\n * Connect using a short-lived token minted by your backend. Returns a\n * {@link MebiusClient}. Listen for `\"connected\"` / `\"error\"` on it.\n */\n connect(options: MebiusConnectOptions): MebiusClient {\n if (!config) {\n throw mebiusError(\"UNKNOWN\", \"Call Mebius.init() before Mebius.connect().\");\n }\n if (!options.token) throw mebiusError(\"UNKNOWN\", \"Mebius.connect requires a token.\");\n const client = new MebiusClient(config, options.token, options.deliveries ?? []);\n client.open();\n return client;\n },\n\n /** @internal Reset configuration (used in tests). */\n _reset(): void {\n config = null;\n },\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACSO,IAAM,cAAN,MAAM,qBAAoB,MAAM;AAAA,EAKrC,YAAY,MAAuB,SAAiB,OAAiB;AACnE,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,QAAQ;AACb,WAAO,eAAe,MAAM,aAAY,SAAS;AAAA,EACnD;AACF;AAGA,IAAM,mBAAoD;AAAA,EACxD,eAAe;AAAA,EACf,mBAAmB;AAAA,EACnB,mBAAmB;AAAA,EACnB,eAAe;AAAA,EACf,kBAAkB;AAAA,EAClB,SAAS;AACX;AAGO,SAAS,YACd,MACA,SACA,OACa;AACb,SAAO,IAAI,YAAY,MAAM,WAAW,iBAAiB,IAAI,GAAG,KAAK;AACvE;;;ACJO,IAAM,eAAN,MAA6D;AAAA,EAA7D;AACL,SAAiB,YAAY,oBAAI,IAA4C;AAAA;AAAA;AAAA,EAG7E,GAA6B,OAAU,IAAuC;AAC5E,QAAI,MAAM,KAAK,UAAU,IAAI,KAAK;AAClC,QAAI,CAAC,KAAK;AACR,YAAM,oBAAI,IAAI;AACd,WAAK,UAAU,IAAI,OAAO,GAAG;AAAA,IAC/B;AACA,QAAI,IAAI,EAAuB;AAC/B,WAAO,MAAM,KAAK,IAAI,OAAO,EAAE;AAAA,EACjC;AAAA;AAAA,EAGA,IAA8B,OAAU,IAAiC;AACvE,SAAK,UAAU,IAAI,KAAK,GAAG,OAAO,EAAuB;AAAA,EAC3D;AAAA;AAAA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nD,SAAK,cAAc;AACnB,SAAK,YAAY;AACjB,SAAK,KAAK,gBAAgB,EAAE,OAAO,CAAC;AACpC,SAAK,mBAAmB;AAAA,EAC1B;AAAA,EAEQ,kBAAwB;AAC9B,QAAI,CAAC,KAAK,UAAW,OAAM,YAAY,eAAe;AAAA,EACxD;AACF;;;ACvFA,IAAI,SAAmC;AAUhC,IAAM,SAAS;AAAA;AAAA,EAEpB,KAAK,SAAkC;AACrC,QAAI,CAAC,QAAQ,MAAO,OAAM,YAAY,WAAW,gCAAgC;AACjF,QAAI,CAAC,QAAQ,QAAS,OAAM,YAAY,WAAW,qCAAqC;AACxF,aAAS,EAAE,GAAG,QAAQ;AAAA,EACxB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,QAAQ,SAA6C;AACnD,QAAI,CAAC,QAAQ;AACX,YAAM,YAAY,WAAW,6CAA6C;AAAA,IAC5E;AACA,QAAI,CAAC,QAAQ,MAAO,OAAM,YAAY,WAAW,kCAAkC;AACnF,UAAM,SAAS,IAAI,aAAa,QAAQ,QAAQ,OAAO,QAAQ,cAAc,CAAC,CAAC;AAC/E,WAAO,KAAK;AACZ,WAAO;AAAA,EACT;AAAA;AAAA,EAGA,SAAe;AACb,aAAS;AAAA,EACX;AACF;","names":["STATS_INTERVAL_MS","config"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/events.ts","../src/internal/view-target.ts","../src/internal/webrtc-util.ts","../src/internal/publish-transport.ts","../src/internal/ll-view-transport.ts","../src/internal/scale-view-transport.ts","../src/internal/balanced-view-transport.ts","../src/internal/transport.ts","../src/internal/telemetry.ts","../src/broadcaster.ts","../src/player.ts","../src/internal/signaling.ts","../src/internal/token.ts","../src/client.ts","../src/mebius.ts"],"sourcesContent":["/**\n * @mebius-io/web — Mebius Client SDK for the web.\n *\n * Public surface only. Everything under `internal/` is private and is never\n * re-exported here.\n */\nexport { Mebius } from \"./mebius.js\";\nexport { MebiusClient } from \"./client.js\";\nexport { MebiusBroadcaster } from \"./broadcaster.js\";\nexport { MebiusPlayer } from \"./player.js\";\nexport { MebiusError, mebiusError } from \"./errors.js\";\n\nexport type {\n ClientEventMap,\n BroadcasterEventMap,\n PlayerEventMap,\n} from \"./events.js\";\n\nexport type {\n MebiusInitOptions,\n MebiusConnectOptions,\n MebiusDelivery,\n BroadcasterOptions,\n PlayerOptions,\n PlaybackMode,\n ViewTarget,\n MediaConstraint,\n BroadcastStats,\n PlaybackStats,\n MebiusErrorCode,\n} from \"./types.js\";\n","import type { MebiusErrorCode } from \"./types.js\";\n\n/**\n * The single error type the SDK surfaces. Always uses Mebius terminology —\n * never raw transport/protocol wording.\n *\n * Inspect {@link MebiusError.code} to decide how to recover (for example,\n * refresh the token on `\"TOKEN_EXPIRED\"`).\n */\nexport class MebiusError extends Error {\n readonly code: MebiusErrorCode;\n /** The underlying cause, if any. Useful for logging, opaque to the contract. */\n readonly cause?: unknown;\n\n constructor(code: MebiusErrorCode, message: string, cause?: unknown) {\n super(message);\n this.name = \"MebiusError\";\n this.code = code;\n this.cause = cause;\n Object.setPrototypeOf(this, MebiusError.prototype);\n }\n}\n\n/** Human-readable default messages, kept in Mebius terms. */\nconst DEFAULT_MESSAGES: Record<MebiusErrorCode, string> = {\n TOKEN_EXPIRED: \"Your Mebius token has expired. Mint a fresh token and reconnect.\",\n PERMISSION_DENIED: \"Camera/microphone permission was denied by the user or browser.\",\n CONNECTION_FAILED: \"Could not establish a connection to the Mebius gateway.\",\n NOT_CONNECTED: \"Not connected to Mebius. Call connect() before using this client.\",\n STREAM_NOT_FOUND: \"The requested stream could not be found on the Mebius gateway.\",\n UNKNOWN: \"An unexpected Mebius error occurred.\",\n};\n\n/** Create a {@link MebiusError}, falling back to a sensible default message. */\nexport function mebiusError(\n code: MebiusErrorCode,\n message?: string,\n cause?: unknown,\n): MebiusError {\n return new MebiusError(code, message ?? DEFAULT_MESSAGES[code], cause);\n}\n","import type { MebiusError } from \"./errors.js\";\nimport type { BroadcastStats, PlaybackStats } from \"./types.js\";\n\n// NOTE: these are `type` aliases (not interfaces) so they satisfy the\n// `Record<string, unknown>` constraint on TypedEmitter — TS only treats object\n// type aliases (not augmentable interfaces) as having an implicit index\n// signature.\n\n/** Event payloads emitted by {@link MebiusClient}. */\nexport type ClientEventMap = {\n connected: void;\n disconnected: { reason?: string };\n error: MebiusError;\n};\n\n/** Event payloads emitted by a broadcaster. */\nexport type BroadcasterEventMap = {\n started: { streamId: string };\n stopped: void;\n stats: BroadcastStats;\n};\n\n/** Event payloads emitted by a player. */\nexport type PlayerEventMap = {\n playing: { streamId: string };\n buffering: void;\n ended: void;\n stats: PlaybackStats;\n};\n\ntype Listener<T> = (payload: T) => void;\n\n/**\n * A tiny strongly-typed event emitter. `EventMap` maps each event name to its\n * payload type, so `on(\"started\", cb)` infers `cb`'s argument automatically.\n */\nexport class TypedEmitter<EventMap extends Record<string, unknown>> {\n private readonly listeners = new Map<keyof EventMap, Set<Listener<unknown>>>();\n\n /** Subscribe to an event. Returns an unsubscribe function. */\n on<K extends keyof EventMap>(event: K, cb: Listener<EventMap[K]>): () => void {\n let set = this.listeners.get(event);\n if (!set) {\n set = new Set();\n this.listeners.set(event, set);\n }\n set.add(cb as Listener<unknown>);\n return () => this.off(event, cb);\n }\n\n /** Unsubscribe a previously-registered listener. */\n off<K extends keyof EventMap>(event: K, cb: Listener<EventMap[K]>): void {\n this.listeners.get(event)?.delete(cb as Listener<unknown>);\n }\n\n /** Emit an event to all listeners. Internal use. */\n protected emit<K extends keyof EventMap>(event: K, payload: EventMap[K]): void {\n const set = this.listeners.get(event);\n if (!set) return;\n for (const cb of [...set]) (cb as Listener<EventMap[K]>)(payload);\n }\n\n /** Remove every listener. Internal use during teardown. */\n protected removeAllListeners(): void {\n this.listeners.clear();\n }\n}\n","/** INTERNAL — resolve a public {@link ViewTarget} to a real `<video>` element. */\nimport { mebiusError } from \"../errors.js\";\nimport type { ViewTarget } from \"../types.js\";\n\nexport function resolveVideoElement(target: ViewTarget): HTMLVideoElement {\n if (typeof target !== \"string\") {\n if (target instanceof HTMLVideoElement) return target;\n throw mebiusError(\"UNKNOWN\", \"View target must be a <video> element or a CSS selector.\");\n }\n const el = document.querySelector(target);\n if (!el) {\n throw mebiusError(\"UNKNOWN\", `No element matches the selector \"${target}\".`);\n }\n if (!(el instanceof HTMLVideoElement)) {\n throw mebiusError(\"UNKNOWN\", `Selector \"${target}\" did not resolve to a <video> element.`);\n }\n return el;\n}\n","/** INTERNAL — small WebRTC helpers shared by publish/view transports. */\n\n/**\n * Wait until ICE gathering completes (or a short timeout elapses) so the SDP\n * we send already contains candidates. Keeps the gateway exchange to a single\n * round-trip.\n */\nexport function waitForIceGathering(pc: RTCPeerConnection, timeoutMs = 2000): Promise<void> {\n if (pc.iceGatheringState === \"complete\") return Promise.resolve();\n return new Promise((resolve) => {\n const done = () => {\n pc.removeEventListener(\"icegatheringstatechange\", check);\n clearTimeout(timer);\n resolve();\n };\n const check = () => {\n if (pc.iceGatheringState === \"complete\") done();\n };\n const timer = setTimeout(done, timeoutMs);\n pc.addEventListener(\"icegatheringstatechange\", check);\n });\n}\n\n/** Default ICE configuration. The gateway may also relay; STUN aids direct paths. */\nexport const DEFAULT_RTC_CONFIG: RTCConfiguration = {\n iceServers: [{ urls: \"stun:stun.l.google.com:19302\" }],\n};\n","/**\n * INTERNAL — publish transport (WHIP over the gateway).\n *\n * Sends a locally-captured MediaStream to the Mebius gateway via a standard\n * WHIP offer/answer exchange. Hidden from the public API.\n */\nimport type { BroadcastStats } from \"../types.js\";\nimport { mebiusError } from \"../errors.js\";\nimport type { SignalingClient } from \"./signaling.js\";\nimport type { PublishTransport } from \"./transport.js\";\nimport { DEFAULT_RTC_CONFIG, waitForIceGathering } from \"./webrtc-util.js\";\n\nexport class WhipPublishTransport implements PublishTransport {\n private pc: RTCPeerConnection | null = null;\n private resourceUrl: string | null = null;\n\n constructor(private readonly signaling: SignalingClient) {}\n\n async start(streamId: string, stream: MediaStream): Promise<void> {\n const pc = new RTCPeerConnection(DEFAULT_RTC_CONFIG);\n this.pc = pc;\n\n for (const track of stream.getTracks()) {\n pc.addTrack(track, stream);\n }\n\n const offer = await pc.createOffer();\n await pc.setLocalDescription(offer);\n await waitForIceGathering(pc);\n\n const localSdp = pc.localDescription?.sdp;\n if (!localSdp) throw mebiusError(\"CONNECTION_FAILED\", \"Failed to create a local session.\");\n\n const { answer, resourceUrl } = await this.signaling.exchangeSession(\n \"publish\",\n streamId,\n localSdp,\n );\n this.resourceUrl = resourceUrl;\n await pc.setRemoteDescription({ type: \"answer\", sdp: answer });\n }\n\n async replaceVideoTrack(track: MediaStreamTrack | null): Promise<void> {\n const sender = this.pc?.getSenders().find((s) => s.track?.kind === \"video\");\n if (sender) await sender.replaceTrack(track);\n }\n\n async stop(): Promise<void> {\n await this.signaling.deleteResource(this.resourceUrl);\n this.resourceUrl = null;\n this.pc?.getSenders().forEach((s) => s.track?.stop());\n this.pc?.close();\n this.pc = null;\n }\n\n async getStats(): Promise<BroadcastStats | null> {\n if (!this.pc) return null;\n const report = await this.pc.getStats();\n let bitrateKbps = 0;\n let framesPerSecond = 0;\n let rttMs: number | undefined;\n report.forEach((stat) => {\n if (stat.type === \"outbound-rtp\" && !stat.isRemote) {\n if (typeof stat.framesPerSecond === \"number\") framesPerSecond = stat.framesPerSecond;\n }\n if (stat.type === \"candidate-pair\" && stat.state === \"succeeded\") {\n if (typeof stat.availableOutgoingBitrate === \"number\") {\n bitrateKbps = Math.round(stat.availableOutgoingBitrate / 1000);\n }\n if (typeof stat.currentRoundTripTime === \"number\") {\n rttMs = Math.round(stat.currentRoundTripTime * 1000);\n }\n }\n });\n return { bitrateKbps, framesPerSecond, rttMs };\n }\n}\n","/**\n * INTERNAL — low-latency view transport (WHEP over the gateway).\n *\n * Pulls a remote stream from the Mebius gateway via a standard WHEP exchange\n * and renders it into a video element. Hidden from the public API.\n */\nimport type { PlaybackStats } from \"../types.js\";\nimport { mebiusError } from \"../errors.js\";\nimport type { SignalingClient } from \"./signaling.js\";\nimport type { ViewTransport } from \"./transport.js\";\nimport { DEFAULT_RTC_CONFIG, waitForIceGathering } from \"./webrtc-util.js\";\n\nexport class WhepViewTransport implements ViewTransport {\n private pc: RTCPeerConnection | null = null;\n private resourceUrl: string | null = null;\n private endedCb: (() => void) | null = null;\n private bufferingCb: (() => void) | null = null;\n\n constructor(private readonly signaling: SignalingClient) {}\n\n onEnded(cb: () => void): void {\n this.endedCb = cb;\n }\n\n onBuffering(cb: () => void): void {\n this.bufferingCb = cb;\n }\n\n async start(streamId: string, video: HTMLVideoElement): Promise<void> {\n const pc = new RTCPeerConnection(DEFAULT_RTC_CONFIG);\n this.pc = pc;\n const remote = new MediaStream();\n\n pc.addTransceiver(\"video\", { direction: \"recvonly\" });\n pc.addTransceiver(\"audio\", { direction: \"recvonly\" });\n\n pc.ontrack = (ev) => {\n remote.addTrack(ev.track);\n video.srcObject = remote;\n void video.play().catch(() => {\n /* autoplay may require a user gesture; left to the app */\n });\n };\n pc.onconnectionstatechange = () => {\n if (pc.connectionState === \"disconnected\" || pc.connectionState === \"failed\") {\n this.bufferingCb?.();\n }\n if (pc.connectionState === \"closed\") this.endedCb?.();\n };\n\n const offer = await pc.createOffer();\n await pc.setLocalDescription(offer);\n await waitForIceGathering(pc);\n\n const localSdp = pc.localDescription?.sdp;\n if (!localSdp) throw mebiusError(\"CONNECTION_FAILED\", \"Failed to create a local session.\");\n\n const { answer, resourceUrl } = await this.signaling.exchangeSession(\n \"view\",\n streamId,\n localSdp,\n );\n this.resourceUrl = resourceUrl;\n await pc.setRemoteDescription({ type: \"answer\", sdp: answer });\n }\n\n async stop(): Promise<void> {\n await this.signaling.deleteResource(this.resourceUrl);\n this.resourceUrl = null;\n this.pc?.close();\n this.pc = null;\n }\n\n async getStats(): Promise<PlaybackStats | null> {\n if (!this.pc) return null;\n const report = await this.pc.getStats();\n let bitrateKbps = 0;\n let framesPerSecond = 0;\n let latencyMs: number | undefined;\n report.forEach((stat) => {\n if (stat.type === \"inbound-rtp\") {\n if (typeof stat.framesPerSecond === \"number\") framesPerSecond = stat.framesPerSecond;\n if (typeof stat.jitter === \"number\") latencyMs = Math.round(stat.jitter * 1000);\n }\n if (stat.type === \"candidate-pair\" && stat.state === \"succeeded\") {\n if (typeof stat.availableIncomingBitrate === \"number\") {\n bitrateKbps = Math.round(stat.availableIncomingBitrate / 1000);\n }\n }\n });\n return { bitrateKbps, framesPerSecond, latencyMs };\n }\n}\n","/**\n * INTERNAL — scale view transport (HLS via hls.js / native).\n *\n * For large-audience playback Mebius delivers an HLS playlist from the\n * gateway. hls.js is loaded lazily; Safari plays the playlist natively.\n * Hidden from the public API.\n */\nimport type { PlaybackStats } from \"../types.js\";\nimport { mebiusError } from \"../errors.js\";\nimport type { SignalingClient } from \"./signaling.js\";\nimport type { ViewTransport } from \"./transport.js\";\n\n// Loaded on demand so it never weighs down low-latency-only apps.\ntype HlsModule = typeof import(\"hls.js\");\ntype HlsInstance = import(\"hls.js\").default;\n\nexport class HlsViewTransport implements ViewTransport {\n private hls: HlsInstance | null = null;\n private video: HTMLVideoElement | null = null;\n private endedCb: (() => void) | null = null;\n private bufferingCb: (() => void) | null = null;\n\n /**\n * deliveryPath, when given, is a gateway-relative path from the gateway's own\n * delivery list — that is how a CDN-backed playlist gets used instead of the\n * origin one. Without it this falls back to the origin playlist, which is\n * still correct, just served from our own bandwidth.\n */\n constructor(\n private readonly signaling: SignalingClient,\n private readonly deliveryPath?: string,\n ) {}\n\n onEnded(cb: () => void): void {\n this.endedCb = cb;\n }\n\n onBuffering(cb: () => void): void {\n this.bufferingCb = cb;\n }\n\n async start(streamId: string, video: HTMLVideoElement): Promise<void> {\n this.video = video;\n const url = this.deliveryPath\n ? this.signaling.deliveryUrl(this.deliveryPath)\n : this.signaling.scalePlaylistUrl(streamId);\n\n video.addEventListener(\"ended\", () => this.endedCb?.());\n video.addEventListener(\"waiting\", () => this.bufferingCb?.());\n\n // Safari and iOS play HLS natively — no library needed.\n if (video.canPlayType(\"application/vnd.apple.mpegurl\")) {\n video.src = url;\n await video.play().catch(() => undefined);\n return;\n }\n\n let mod: HlsModule;\n try {\n mod = await import(\"hls.js\");\n } catch (cause) {\n throw mebiusError(\"CONNECTION_FAILED\", \"Scale playback support failed to load.\", cause);\n }\n const Hls = mod.default;\n if (!Hls.isSupported()) {\n throw mebiusError(\"CONNECTION_FAILED\", \"Scale playback is not supported in this browser.\");\n }\n\n const hls = new Hls({ lowLatencyMode: true });\n this.hls = hls;\n hls.on(Hls.Events.ERROR, (_evt, data) => {\n if (data.fatal) this.bufferingCb?.();\n });\n hls.loadSource(url);\n hls.attachMedia(video);\n await video.play().catch(() => undefined);\n }\n\n async stop(): Promise<void> {\n this.hls?.destroy();\n this.hls = null;\n if (this.video) {\n this.video.removeAttribute(\"src\");\n this.video.load();\n }\n this.video = null;\n }\n\n async getStats(): Promise<PlaybackStats | null> {\n if (!this.video) return null;\n const level = this.hls?.levels?.[this.hls.currentLevel];\n return {\n bitrateKbps: level ? Math.round(level.bitrate / 1000) : 0,\n framesPerSecond: 0,\n };\n }\n}\n","/**\n * INTERNAL — balanced view transport (HTTP-FLV via flv.js).\n *\n * For typical one-to-many web viewers Mebius pulls an HTTP-FLV stream and feeds\n * it through flv.js (Media Source Extensions). Latency is ~1-3s — lower than\n * HLS, higher than the WebRTC pull — and it scales over a CDN edge.\n *\n * History worth keeping: 0.2.0 deleted this file on the reading that the mode\n * was \"unserved\", because the gateway had no route for it. The route simply had\n * not been built yet — production web playback has always been HTTP-FLV. The\n * gateway now serves it, so this comes back, with one change: the URL is no\n * longer derived from a hardcoded path. It comes from the gateway's own\n * delivery list, so the gateway can move or re-point that path without an SDK\n * release.\n *\n * Browser-only: flv.js needs MSE, which iOS Safari lacks — createViewCandidates\n * is what keeps this off platforms that cannot play it. flv.js is a BUNDLED\n * dependency, never a peer dependency: an integrator must never have to type a\n * transport library's name to make Mebius work.\n *\n * Hidden from the public API; the public surface speaks only of the\n * `\"balanced\"` playback mode.\n */\nimport type { PlaybackStats } from \"../types.js\";\nimport { mebiusError } from \"../errors.js\";\nimport type { SignalingClient } from \"./signaling.js\";\nimport type { ViewTransport } from \"./transport.js\";\n\ntype FlvModule = typeof import(\"flv.js\");\ntype FlvPlayer = ReturnType<FlvModule[\"default\"][\"createPlayer\"]>;\n\nexport class FlvViewTransport implements ViewTransport {\n private player: FlvPlayer | null = null;\n private video: HTMLVideoElement | null = null;\n private endedCb: (() => void) | null = null;\n private bufferingCb: (() => void) | null = null;\n\n constructor(\n private readonly signaling: SignalingClient,\n private readonly deliveryPath: string,\n ) {}\n\n onEnded(cb: () => void): void {\n this.endedCb = cb;\n }\n\n onBuffering(cb: () => void): void {\n this.bufferingCb = cb;\n }\n\n async start(_streamId: string, video: HTMLVideoElement): Promise<void> {\n this.video = video;\n const url = this.signaling.deliveryUrl(this.deliveryPath);\n\n video.addEventListener(\"ended\", () => this.endedCb?.());\n video.addEventListener(\"waiting\", () => this.bufferingCb?.());\n\n let mod: FlvModule;\n try {\n // Literal specifier on purpose: a bundler must be able to see it and inline\n // the library into the single-file drop-in build. A computed specifier\n // leaves a bare module request in the output, which no browser can resolve.\n // Types come from internal/flv.js.d.ts.\n mod = await import(\"flv.js\");\n } catch (cause) {\n throw mebiusError(\"CONNECTION_FAILED\", \"Balanced playback support failed to load.\", cause);\n }\n\n const flvjs = mod.default;\n if (!flvjs.isSupported()) {\n throw mebiusError(\"CONNECTION_FAILED\", \"Balanced playback is not supported in this browser.\");\n }\n\n const player = flvjs.createPlayer({ type: \"flv\", url, isLive: true });\n this.player = player;\n player.on(flvjs.Events.ERROR ?? \"error\", () => this.bufferingCb?.());\n player.attachMediaElement(video);\n player.load();\n await Promise.resolve(player.play()).catch(() => undefined);\n }\n\n async stop(): Promise<void> {\n if (this.player) {\n this.player.unload();\n this.player.detachMediaElement();\n this.player.destroy();\n this.player = null;\n }\n if (this.video) {\n this.video.removeAttribute(\"src\");\n this.video.load();\n }\n this.video = null;\n }\n\n async getStats(): Promise<PlaybackStats | null> {\n if (!this.video) return null;\n return {\n bitrateKbps: 0,\n framesPerSecond: 0,\n latencyMs: undefined,\n };\n }\n}\n","/**\n * INTERNAL — transport interfaces + auto-selection.\n *\n * The public API never names a transport; it only asks for a playback *mode*.\n * This factory maps a mode to the right hidden delivery mechanism.\n */\nimport type { BroadcastStats, MebiusDelivery, PlaybackMode, PlaybackStats } from \"../types.js\";\nimport type { SignalingClient } from \"./signaling.js\";\nimport { WhipPublishTransport } from \"./publish-transport.js\";\nimport { WhepViewTransport } from \"./ll-view-transport.js\";\nimport { HlsViewTransport } from \"./scale-view-transport.js\";\nimport { FlvViewTransport } from \"./balanced-view-transport.js\";\n\n/** Hidden transport that sends a captured stream to the gateway. */\nexport interface PublishTransport {\n start(streamId: string, stream: MediaStream): Promise<void>;\n stop(): Promise<void>;\n getStats(): Promise<BroadcastStats | null>;\n /** Swap the outgoing video track in place (e.g. on camera switch). */\n replaceVideoTrack(track: MediaStreamTrack | null): Promise<void>;\n}\n\n/** Hidden transport that renders a remote stream into a video element. */\nexport interface ViewTransport {\n start(streamId: string, video: HTMLVideoElement): Promise<void>;\n stop(): Promise<void>;\n getStats(): Promise<PlaybackStats | null>;\n /** Fired by the transport when playback reaches its natural end. */\n onEnded(cb: () => void): void;\n /** Fired when the transport (re)enters a buffering state. */\n onBuffering(cb: () => void): void;\n}\n\nexport function createPublishTransport(signaling: SignalingClient): PublishTransport {\n return new WhipPublishTransport(signaling);\n}\n\n/**\n * Delivery kinds the gateway may offer. Neutral by design — the gateway names\n * an intent (\"fast\", \"wide\"), never a protocol, and this module is the only\n * place that decides which transport serves which intent. That is what lets the\n * gateway change protocol without an SDK release.\n */\nconst KIND_FAST = \"fast\";\nconst KIND_WIDE = \"wide\";\nconst KIND_LOCAL = \"local\";\n\n/** True when this browser can play a Media-Source-based stream (not iOS Safari). */\nfunction canPlayBuffered(): boolean {\n return typeof MediaSource !== \"undefined\";\n}\n\nfunction transportFor(\n kind: string,\n path: string,\n signaling: SignalingClient,\n): ViewTransport | null {\n if (kind === KIND_FAST) return canPlayBuffered() ? new FlvViewTransport(signaling, path) : null;\n if (kind === KIND_WIDE || kind === KIND_LOCAL) return new HlsViewTransport(signaling, path);\n // An unknown kind is a newer gateway talking to an older SDK. Skip it rather\n // than guess: the list is ordered, so the next entry is the intended fallback.\n return null;\n}\n\n/**\n * Ordered list of transports to try for a playback mode, most-preferred first.\n *\n * Returning a LIST rather than one transport is the whole point: a transport can\n * connect and still deliver no frames (a CDN edge with no ingest yet, MSE\n * failing mid-init, WebRTC reporting `connected` with zero frames). The player\n * walks this list on a watchdog, so a dead first choice degrades instead of\n * showing a black frame.\n *\n * `deliveries` comes from the gateway and is already in the gateway's preferred\n * order; ordering policy therefore lives server-side, not here.\n */\nexport function createViewCandidates(\n mode: PlaybackMode,\n signaling: SignalingClient,\n deliveries: readonly MebiusDelivery[] = [],\n): ViewTransport[] {\n const fromGateway = (kinds: readonly string[]): ViewTransport[] =>\n deliveries\n .filter((d) => kinds.includes(d.kind))\n .map((d) => transportFor(d.kind, d.path, signaling))\n .filter((t): t is ViewTransport => t !== null);\n\n // Every mode ends with the origin playlist, reachable with no delivery list at\n // all. Without this, a caller that never passes `deliveries` (every 0.x\n // integration today) would get an empty candidate list and fail to play.\n const originFallback = new HlsViewTransport(signaling);\n const allKinds = [KIND_FAST, KIND_WIDE, KIND_LOCAL];\n\n switch (mode) {\n case \"low-latency\":\n // The real-time pull is not in `deliveries` — it is signaled, not fetched.\n return [new WhepViewTransport(signaling), ...fromGateway(allKinds), originFallback];\n case \"balanced\":\n return [...fromGateway(allKinds), originFallback];\n case \"scale\":\n return [...fromGateway([KIND_WIDE, KIND_LOCAL]), originFallback];\n case \"auto\":\n // Take the gateway ordering verbatim: it knows which paths are actually\n // serving and what each one costs to serve.\n return [...fromGateway(allKinds), originFallback];\n }\n}\n\n/**\n * Single-transport selection, kept for callers written against 0.1/0.2.\n * @deprecated Use {@link createViewCandidates} — a single transport cannot fall\n * back, so a dead delivery becomes a black frame.\n */\nexport function createViewTransport(\n mode: PlaybackMode,\n signaling: SignalingClient,\n): ViewTransport {\n return createViewCandidates(mode, signaling)[0]!;\n}\n","/**\n * INTERNAL — quality-of-experience reporting.\n *\n * Mebius shows per-stream publish/playback quality (bitrate, fps, rtt, freezes)\n * in the integrator's dashboard, and derives viewer minutes from play-side\n * reports. Both come from here: nothing else in the product observes a viewer's\n * actual experience, because only the client can see it.\n *\n * The credential and the endpoint both come from the token your backend already\n * fetches — the SDK is never configured with them and never learns which tenant\n * it belongs to. The token is scoped by signed claims to one stream and one\n * project, so it can only ever write its own telemetry.\n */\n\n/** SDK identifier reported with each batch. Keep in step with package.json. */\nconst SDK_VERSION = \"web/0.4.0\";\n\n/** How often a batch is sent. Long enough to batch, short enough to survive a tab close. */\nconst FLUSH_INTERVAL_MS = 15_000;\n\n/**\n * Server cap on samples per request (beaconSchema: max 64). Flushing at this\n * point rather than growing without bound means a long broadcast on a throttled\n * network drops nothing to a 400.\n */\nconst MAX_BATCH = 64;\n\nexport interface QoeSample {\n /** Unix seconds. The server keys samples on this. */\n ts: number;\n bitrateKbps?: number;\n fps?: number;\n rttMs?: number;\n packetLossPct?: number;\n freezeMs?: number;\n firstFrameMs?: number;\n}\n\nexport interface TelemetryTarget {\n /** Absolute beacon URL, as returned with the token. */\n url: string;\n /** Beacon credential, as returned with the token. */\n token: string;\n}\n\n/** Best-effort environment description. Absent fields are simply not reported. */\nfunction describeDevice(): { os?: string; sdk: string } {\n const nav = typeof navigator === \"undefined\" ? undefined : navigator;\n // navigator.platform is deprecated but still the only universally available\n // hint; userAgentData exists on Chromium only. Neither is load-bearing — the\n // dashboard shows it as context, so a missing value costs nothing.\n const uaData = (nav as { userAgentData?: { platform?: string } } | undefined)?.userAgentData;\n return { os: uaData?.platform || nav?.platform || undefined, sdk: SDK_VERSION };\n}\n\nfunction describeNetwork(): { type?: string } | undefined {\n const conn = (\n typeof navigator === \"undefined\"\n ? undefined\n : (navigator as { connection?: { effectiveType?: string } }).connection\n );\n return conn?.effectiveType ? { type: conn.effectiveType } : undefined;\n}\n\n/**\n * Collects samples for one session and ships them in batches.\n *\n * Every failure path is silent by design: telemetry must never break playback or\n * a broadcast. A rejected batch is dropped rather than retried — the next batch\n * is 15s away and carries the same picture of stream health, so retrying would\n * only pile up requests against an endpoint that is already unhappy.\n */\nexport class QoeReporter {\n private readonly sessionId = randomId();\n private readonly buffer: QoeSample[] = [];\n private timer: ReturnType<typeof setInterval> | null = null;\n private unloadHandler: (() => void) | null = null;\n\n constructor(\n private readonly target: TelemetryTarget,\n private readonly role: \"pub\" | \"play\",\n private readonly streamId: string,\n private readonly userId?: string,\n ) {}\n\n start(): void {\n if (this.timer) return;\n this.timer = setInterval(() => void this.flush(), FLUSH_INTERVAL_MS);\n // A viewer closing the tab is the normal end of a session, not an edge case:\n // without this the last interval of every session — and the watch time it\n // represents — is simply lost.\n if (typeof window !== \"undefined\") {\n this.unloadHandler = () => void this.flush(true);\n window.addEventListener(\"pagehide\", this.unloadHandler);\n }\n }\n\n add(sample: QoeSample): void {\n this.buffer.push(sample);\n if (this.buffer.length >= MAX_BATCH) void this.flush();\n }\n\n async stop(): Promise<void> {\n if (this.timer) clearInterval(this.timer);\n this.timer = null;\n if (this.unloadHandler && typeof window !== \"undefined\") {\n window.removeEventListener(\"pagehide\", this.unloadHandler);\n }\n this.unloadHandler = null;\n await this.flush();\n }\n\n /** Send and clear the buffer. `beacon` uses sendBeacon, for page-unload flushes. */\n async flush(beacon = false): Promise<void> {\n if (!this.buffer.length) return;\n const samples = this.buffer.splice(0, MAX_BATCH);\n const body = JSON.stringify({\n sessionId: this.sessionId,\n streamId: this.streamId,\n role: this.role,\n userId: this.userId,\n samples,\n device: describeDevice(),\n network: describeNetwork(),\n });\n\n // sendBeacon cannot carry an Authorization header, so the credential travels\n // as a query parameter on the unload path only. Same token, same scope — the\n // server accepts either, and losing the final batch of every session was the\n // alternative.\n if (beacon && typeof navigator !== \"undefined\" && navigator.sendBeacon) {\n const url = `${this.target.url}${this.target.url.includes(\"?\") ? \"&\" : \"?\"}token=${encodeURIComponent(this.target.token)}`;\n try {\n navigator.sendBeacon(url, new Blob([body], { type: \"application/json\" }));\n } catch {\n /* nothing to do at unload */\n }\n return;\n }\n\n try {\n await fetch(this.target.url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", Authorization: `Bearer ${this.target.token}` },\n body,\n keepalive: true,\n });\n } catch {\n /* telemetry never breaks the stream */\n }\n }\n}\n\nfunction randomId(): string {\n const c = typeof crypto === \"undefined\" ? undefined : crypto;\n if (c?.randomUUID) return c.randomUUID();\n // Older Safari/WebView: a collision only merges two sessions' samples, so a\n // cheap fallback beats refusing to report at all.\n return `s-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n","import { mebiusError } from \"./errors.js\";\nimport { TypedEmitter, type BroadcasterEventMap } from \"./events.js\";\nimport { resolveVideoElement } from \"./internal/view-target.js\";\nimport type { SignalingClient } from \"./internal/signaling.js\";\nimport { createPublishTransport, type PublishTransport } from \"./internal/transport.js\";\nimport { QoeReporter, type TelemetryTarget } from \"./internal/telemetry.js\";\nimport type { BroadcasterOptions, MediaConstraint, ViewTarget } from \"./types.js\";\n\nconst STATS_INTERVAL_MS = 2000;\n\n/**\n * Publishes the local camera/microphone to a Mebius stream.\n *\n * Create one with {@link MebiusClient.createBroadcaster}, then\n * {@link MebiusBroadcaster.start | start} it with a stream id.\n */\nexport class MebiusBroadcaster extends TypedEmitter<BroadcasterEventMap> {\n private readonly transport: PublishTransport;\n private stream: MediaStream | null = null;\n private facingMode: \"user\" | \"environment\" = \"user\";\n private statsTimer: ReturnType<typeof setInterval> | null = null;\n private started = false;\n private reporter: QoeReporter | null = null;\n\n /** @internal */\n constructor(\n signaling: SignalingClient,\n private readonly options: BroadcasterOptions,\n private readonly telemetry: TelemetryTarget | null = null,\n private readonly userId?: string,\n ) {\n super();\n this.transport = createPublishTransport(signaling);\n }\n\n /** Begin broadcasting under the given stream id. */\n async start(streamId: string): Promise<void> {\n if (this.started) return;\n this.stream = await this.capture();\n await this.transport.start(streamId, this.stream);\n this.started = true;\n // Report against the id the caller published under, so a sample can be traced\n // back to the stream row the dashboard shows.\n if (this.telemetry) {\n this.reporter = new QoeReporter(this.telemetry, \"pub\", streamId, this.userId);\n this.reporter.start();\n }\n this.startStats();\n this.emit(\"started\", { streamId });\n }\n\n /** Stop broadcasting and release the camera/microphone. */\n async stop(): Promise<void> {\n this.stopStats();\n // Flush before tearing down the transport: the last interval of a broadcast is\n // the one most likely to explain why it ended.\n await this.reporter?.stop();\n this.reporter = null;\n await this.transport.stop();\n this.stream?.getTracks().forEach((t) => t.stop());\n this.stream = null;\n this.started = false;\n this.emit(\"stopped\", undefined);\n }\n\n /** Flip between front and back camera (where available). */\n async switchCamera(): Promise<void> {\n if (!this.stream) return;\n this.facingMode = this.facingMode === \"user\" ? \"environment\" : \"user\";\n const next = await navigator.mediaDevices.getUserMedia({\n video: { facingMode: this.facingMode },\n audio: false,\n });\n const newTrack = next.getVideoTracks()[0] ?? null;\n const oldTrack = this.stream.getVideoTracks()[0];\n if (oldTrack) {\n this.stream.removeTrack(oldTrack);\n oldTrack.stop();\n }\n if (newTrack) this.stream.addTrack(newTrack);\n await this.transport.replaceVideoTrack(newTrack);\n }\n\n /** Mute or unmute the outgoing microphone. */\n setMicEnabled(enabled: boolean): void {\n this.stream?.getAudioTracks().forEach((t) => (t.enabled = enabled));\n }\n\n /** Enable or disable the outgoing camera. */\n setCameraEnabled(enabled: boolean): void {\n this.stream?.getVideoTracks().forEach((t) => (t.enabled = enabled));\n }\n\n /**\n * Web convenience: render the local camera preview into a `<video>` element.\n * This is the web analog of the mobile preview view; it does not affect what\n * is broadcast.\n */\n attachPreview(target: ViewTarget): void {\n if (!this.stream) return;\n const video = resolveVideoElement(target);\n video.srcObject = this.stream;\n video.muted = true;\n void video.play().catch(() => undefined);\n }\n\n private async capture(): Promise<MediaStream> {\n const video = normalize(this.options.video, true);\n const audio = normalize(this.options.audio, true);\n try {\n return await navigator.mediaDevices.getUserMedia({ video, audio });\n } catch (cause) {\n throw mebiusError(\"PERMISSION_DENIED\", undefined, cause);\n }\n }\n\n private startStats(): void {\n this.statsTimer = setInterval(async () => {\n const stats = await this.transport.getStats();\n if (!stats) return;\n this.emit(\"stats\", stats);\n this.reporter?.add({\n ts: Math.floor(Date.now() / 1000),\n bitrateKbps: stats.bitrateKbps,\n fps: stats.framesPerSecond,\n rttMs: stats.rttMs,\n });\n }, STATS_INTERVAL_MS);\n }\n\n private stopStats(): void {\n if (this.statsTimer) clearInterval(this.statsTimer);\n this.statsTimer = null;\n }\n}\n\nfunction normalize(c: MediaConstraint | undefined, fallback: boolean): boolean | MediaTrackConstraints {\n if (c === undefined) return fallback;\n return c;\n}\n","import { TypedEmitter, type PlayerEventMap } from \"./events.js\";\nimport { mebiusError } from \"./errors.js\";\nimport { resolveVideoElement } from \"./internal/view-target.js\";\nimport type { SignalingClient } from \"./internal/signaling.js\";\nimport { createViewCandidates, type ViewTransport } from \"./internal/transport.js\";\nimport { QoeReporter, type TelemetryTarget } from \"./internal/telemetry.js\";\nimport type { MebiusDelivery, PlayerOptions, ViewTarget } from \"./types.js\";\n\nconst STATS_INTERVAL_MS = 2000;\n\n/**\n * How long a route gets to produce its first frame before we move to the next.\n *\n * Not arbitrary: a route can report a healthy connection and still deliver\n * nothing — a CDN edge that has no ingest yet answers 200 with an empty stream,\n * and a real-time connection reports `connected` while zero frames arrive. The\n * only trustworthy signal is the picture actually advancing, so that is what is\n * measured. 8s is long enough to survive a slow first segment on mobile data and\n * short enough that a viewer has not yet left.\n */\nconst FIRST_FRAME_TIMEOUT_MS = 8000;\n\n/**\n * Plays a Mebius stream into a `<video>` element.\n *\n * Create one with {@link MebiusClient.createPlayer}, optionally choosing a\n * playback {@link PlaybackMode | mode}; Mebius selects the delivery route, and\n * moves to the next one by itself if the current one stops producing frames.\n */\nexport class MebiusPlayer extends TypedEmitter<PlayerEventMap> {\n private readonly candidates: ViewTransport[];\n private transport: ViewTransport | null = null;\n private video: HTMLVideoElement | null = null;\n private statsTimer: ReturnType<typeof setInterval> | null = null;\n private playing = false;\n private reporter: QoeReporter | null = null;\n\n /** @internal */\n constructor(\n signaling: SignalingClient,\n options: PlayerOptions = {},\n deliveries: readonly MebiusDelivery[] = [],\n private readonly telemetry: TelemetryTarget | null = null,\n private readonly userId?: string,\n ) {\n super();\n this.candidates = createViewCandidates(options.mode ?? \"auto\", signaling, deliveries);\n }\n\n /** Start playing `streamId` into the given video element or selector. */\n async play(streamId: string, viewTarget: ViewTarget): Promise<void> {\n if (this.playing) return;\n const video = resolveVideoElement(viewTarget);\n this.video = video;\n\n // Measured across route attempts, not from the accepted route: a viewer who\n // waited through a dead edge waited, and reporting only the winning route's\n // time would hide exactly the delay worth knowing about.\n const startedAtMs = Date.now();\n let lastError: unknown = null;\n for (const candidate of this.candidates) {\n try {\n this.attach(candidate);\n await candidate.start(streamId, video);\n // start() resolving only means the route was opened, not that it is\n // delivering. Confirm with the picture itself before accepting it.\n if (await hasFirstFrame(video)) {\n this.transport = candidate;\n this.playing = true;\n if (this.telemetry) {\n this.reporter = new QoeReporter(this.telemetry, \"play\", streamId, this.userId);\n this.reporter.start();\n // One sample at join time carries the join delay. Viewer minutes are\n // derived from the span between a session's first and last sample, so\n // a viewer who leaves before the first stats tick still counts.\n this.reporter.add({ ts: Math.floor(Date.now() / 1000), firstFrameMs: Date.now() - startedAtMs });\n }\n this.startStats();\n this.emit(\"playing\", { streamId });\n return;\n }\n lastError = mebiusError(\"CONNECTION_FAILED\", \"A Mebius route delivered no video.\");\n } catch (cause) {\n lastError = cause;\n }\n // Tear the dead route down before opening the next one: leaving it attached\n // keeps a peer connection or a media source bound to the same element, and\n // the next route then renders into a element that is not free.\n await candidate.stop().catch(() => undefined);\n }\n\n this.video = null;\n throw lastError ?? mebiusError(\"CONNECTION_FAILED\", \"No Mebius route could play this stream.\");\n }\n\n /** Stop playback and detach from the video element. */\n async stop(): Promise<void> {\n this.stopStats();\n await this.reporter?.stop();\n this.reporter = null;\n await this.transport?.stop();\n this.transport = null;\n this.video = null;\n this.playing = false;\n }\n\n /** Set output volume in the range 0..1. */\n setVolume(volume: number): void {\n const v = Math.min(1, Math.max(0, volume));\n if (this.video) this.video.volume = v;\n }\n\n private attach(transport: ViewTransport): void {\n transport.onEnded(() => {\n // Only the route currently serving may end playback. A route we already\n // abandoned firing late must not close a stream that is playing fine.\n if (this.transport !== transport) return;\n this.playing = false;\n this.stopStats();\n // A stream ending is a session ending: flush now or the watch time since the\n // last batch is never counted.\n void this.reporter?.stop();\n this.reporter = null;\n this.emit(\"ended\", undefined);\n });\n transport.onBuffering(() => {\n if (this.transport !== transport) return;\n this.emit(\"buffering\", undefined);\n });\n }\n\n private startStats(): void {\n this.statsTimer = setInterval(async () => {\n const stats = await this.transport?.getStats();\n if (!stats) return;\n this.emit(\"stats\", stats);\n this.reporter?.add({\n ts: Math.floor(Date.now() / 1000),\n bitrateKbps: stats.bitrateKbps,\n fps: stats.framesPerSecond,\n });\n }, STATS_INTERVAL_MS);\n }\n\n private stopStats(): void {\n if (this.statsTimer) clearInterval(this.statsTimer);\n this.statsTimer = null;\n }\n}\n\n/**\n * Resolves true once the element is actually rendering, false on timeout.\n *\n * `timeupdate` is the signal rather than `readyState` because readiness only\n * says data arrived; a live stream that stalls right after its first buffer can\n * report ready forever without the picture moving.\n */\nfunction hasFirstFrame(video: HTMLVideoElement): Promise<boolean> {\n if (video.currentTime > 0 && !video.paused) return Promise.resolve(true);\n return new Promise((resolve) => {\n const done = (ok: boolean) => {\n clearTimeout(timer);\n video.removeEventListener(\"timeupdate\", onTime);\n resolve(ok);\n };\n const onTime = () => {\n if (video.currentTime > 0) done(true);\n };\n const timer = setTimeout(() => done(false), FIRST_FRAME_TIMEOUT_MS);\n video.addEventListener(\"timeupdate\", onTime);\n });\n}\n","/**\n * INTERNAL — gateway signaling client.\n *\n * This module is the ONE place that knows the wire protocols Mebius uses\n * behind the scenes (WHIP for publishing, WHEP for low-latency viewing, HLS\n * for scale viewing). None of these terms ever escape `internal/` — the public\n * API speaks only in Mebius vocabulary.\n *\n * The gateway HTTP contract (mebius-stream-engine public edge):\n * - Publish: POST {gateway}/whip/{streamId}?token=<jwt> (application/sdp)\n * - View low-latency: POST {gateway}/whep/{streamId}?token=<jwt> (application/sdp)\n * - View scale: GET {gateway}/live/{streamId}/index.m3u8?token=<jwt>\n * - Teardown: DELETE {resourceUrl}\n *\n * The engine validates the token from the `?token=` QUERY parameter (its\n * MediaMTX auth hook + HLS playback gate both read the query, not a header).\n * We still send `Authorization: Bearer <token>` for gateways that prefer it,\n * but the query token is what the engine actually enforces. HLS segment URLs\n * inside the playlist inherit `?token=` automatically (the engine rewrites the\n * m3u8), so no extra header is needed for segment fetches.\n */\nimport { mebiusError } from \"../errors.js\";\n\n/**\n * A media session direction. Deliberately neutral vocabulary (\"publish\" /\n * \"view\") so that if a type bundler ever inlines this into the public `.d.ts`\n * (e.g. via a private field reference), no wire-protocol term leaks to clients.\n * The concrete path segment is derived inside {@link SignalingClient} only.\n */\nexport type SessionKind = \"publish\" | \"view\";\n\nexport interface SessionResult {\n /** The remote session answer returned by the gateway. */\n answer: string;\n /** Resource URL to DELETE on teardown, if the gateway returned one. */\n resourceUrl: string | null;\n}\n\nexport class SignalingClient {\n constructor(\n private readonly gateway: string,\n private readonly token: string,\n ) {}\n\n private base(): string {\n return this.gateway.replace(/\\/+$/, \"\");\n }\n\n private headers(contentType?: string): HeadersInit {\n const h: Record<string, string> = { Authorization: `Bearer ${this.token}` };\n if (contentType) h[\"Content-Type\"] = contentType;\n return h;\n }\n\n /** Append the access token as a query param (the form the engine enforces). */\n private withToken(url: string): string {\n const sep = url.includes(\"?\") ? \"&\" : \"?\";\n return `${url}${sep}token=${encodeURIComponent(this.token)}`;\n }\n\n // Build the playlist URL used by scale-mode playback (HLS path, hidden). The\n // engine serves the playlist under /live/{id}/index.m3u8 and requires the\n // token in the query; segment URIs in the playlist inherit it automatically.\n /**\n * Absolute, tokenized URL for a gateway-relative delivery path handed to us\n * by the gateway (`deliveries[].path`). The gateway decides which paths exist\n * and in what order; the SDK only resolves them against its own base and\n * attaches the access token. Anything that is not a plain gateway-relative\n * path is rejected rather than fetched: an absolute URL there would send the\n * token to a host we did not choose.\n */\n deliveryUrl(path: string): string {\n if (!path.startsWith(\"/\") || path.startsWith(\"//\") || path.includes(\"://\")) {\n throw mebiusError(\"CONNECTION_FAILED\", \"The gateway returned an unusable delivery path.\");\n }\n return this.withToken(`${this.base()}${path}`);\n }\n\n /** Playlist URL for scale-mode playback. */\n scalePlaylistUrl(streamId: string): string {\n return this.withToken(`${this.base()}/live/${encodeURIComponent(streamId)}/index.m3u8`);\n }\n\n // Maps a neutral session kind to the concrete signaling path segment. This\n // mapping (publish -> WHIP, view -> WHEP) lives ONLY in this method body, so\n // the protocol names never appear in any exported type signature.\n private pathFor(kind: SessionKind): string {\n return kind === \"publish\" ? \"whip\" : \"whep\";\n }\n\n // Performs the offer/answer exchange for a publish or a low-latency view\n // session. Protocol detail kept inside the method body so it never leaks into\n // the bundled public .d.ts.\n /**\n * Run the session offer/answer exchange. Throws a {@link MebiusError} with a\n * Mebius-flavored code on failure — never the raw protocol name.\n */\n async exchangeSession(\n kind: SessionKind,\n streamId: string,\n offer: string,\n ): Promise<SessionResult> {\n const url = this.withToken(`${this.base()}/${this.pathFor(kind)}/${encodeURIComponent(streamId)}`);\n let res: Response;\n try {\n res = await fetch(url, {\n method: \"POST\",\n headers: this.headers(\"application/sdp\"),\n body: offer,\n });\n } catch (cause) {\n throw mebiusError(\"CONNECTION_FAILED\", undefined, cause);\n }\n\n if (res.status === 401 || res.status === 403) {\n throw mebiusError(\"TOKEN_EXPIRED\");\n }\n if (res.status === 404) {\n throw mebiusError(\"STREAM_NOT_FOUND\");\n }\n if (!res.ok) {\n throw mebiusError(\"CONNECTION_FAILED\", `Mebius gateway returned ${res.status}.`);\n }\n\n const answer = await res.text();\n const location = res.headers.get(\"Location\");\n const resourceUrl = location ? new URL(location, url).toString() : null;\n return { answer, resourceUrl };\n }\n\n /** Tear down a previously-created session resource. Best-effort. */\n async deleteResource(resourceUrl: string | null): Promise<void> {\n if (!resourceUrl) return;\n try {\n await fetch(resourceUrl, { method: \"DELETE\", headers: this.headers() });\n } catch {\n // Teardown is best-effort; the gateway reaps idle sessions anyway.\n }\n }\n}\n","/**\n * INTERNAL — read (NOT verify) a Mebius token's expiry.\n *\n * The token is a short-lived JWT minted by the developer's backend. The client\n * never verifies it (only the gateway can) — it just peeks at `exp` so it can\n * proactively surface a TOKEN_EXPIRED error and let the app refresh.\n */\nexport interface TokenInfo {\n /** Expiry as a UNIX epoch in milliseconds, if present. */\n expiresAtMs: number | null;\n}\n\nfunction base64UrlDecode(input: string): string {\n const padded = input.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const pad = padded.length % 4 === 0 ? \"\" : \"=\".repeat(4 - (padded.length % 4));\n const b64 = padded + pad;\n if (typeof atob === \"function\") return atob(b64);\n // Node fallback (tests / SSR).\n return Buffer.from(b64, \"base64\").toString(\"binary\");\n}\n\nexport function readToken(token: string): TokenInfo {\n const parts = token.split(\".\");\n if (parts.length < 2) return { expiresAtMs: null };\n try {\n const payload = JSON.parse(base64UrlDecode(parts[1] ?? \"\")) as { exp?: number };\n return { expiresAtMs: typeof payload.exp === \"number\" ? payload.exp * 1000 : null };\n } catch {\n return { expiresAtMs: null };\n }\n}\n","import { MebiusBroadcaster } from \"./broadcaster.js\";\nimport { mebiusError } from \"./errors.js\";\nimport { TypedEmitter, type ClientEventMap } from \"./events.js\";\nimport { MebiusPlayer } from \"./player.js\";\nimport { SignalingClient } from \"./internal/signaling.js\";\nimport type { TelemetryTarget } from \"./internal/telemetry.js\";\nimport { readToken } from \"./internal/token.js\";\nimport type {\n BroadcasterOptions,\n MebiusDelivery,\n MebiusInitOptions,\n PlayerOptions,\n} from \"./types.js\";\n\n/**\n * A live connection to Mebius. Obtain one from {@link Mebius.connect}, then\n * create broadcasters and players from it.\n */\nexport class MebiusClient extends TypedEmitter<ClientEventMap> {\n private readonly signaling: SignalingClient;\n private expiryTimer: ReturnType<typeof setTimeout> | null = null;\n private connected = false;\n\n /** @internal */\n constructor(\n config: MebiusInitOptions,\n private readonly token: string,\n private readonly deliveries: readonly MebiusDelivery[] = [],\n private readonly telemetry: TelemetryTarget | null = null,\n private readonly userId?: string,\n ) {\n super();\n this.signaling = new SignalingClient(config.gateway, token);\n }\n\n /** @internal Called by {@link Mebius.connect}. */\n open(): void {\n const { expiresAtMs } = readToken(this.token);\n const now = Date.now();\n if (expiresAtMs !== null && expiresAtMs <= now) {\n // Surface asynchronously so listeners attached after connect() still fire.\n queueMicrotask(() => this.emit(\"error\", mebiusError(\"TOKEN_EXPIRED\")));\n return;\n }\n this.connected = true;\n if (expiresAtMs !== null) {\n this.expiryTimer = setTimeout(\n () => this.emit(\"error\", mebiusError(\"TOKEN_EXPIRED\")),\n Math.max(0, expiresAtMs - now),\n );\n }\n queueMicrotask(() => this.emit(\"connected\", undefined));\n }\n\n /** Create a broadcaster bound to this connection. */\n createBroadcaster(options: BroadcasterOptions = {}): MebiusBroadcaster {\n this.assertConnected();\n return new MebiusBroadcaster(this.signaling, options, this.telemetry, this.userId);\n }\n\n /** Create a player bound to this connection. */\n createPlayer(options: PlayerOptions = {}): MebiusPlayer {\n this.assertConnected();\n return new MebiusPlayer(this.signaling, options, this.deliveries, this.telemetry, this.userId);\n }\n\n /**\n * Create a monitor: a player tuned for watching a stream you are interacting\n * WITH rather than merely watching — the other side of a co-broadcast, where a\n * second or two of delay makes the interaction feel broken.\n *\n * It is a player with the delay budget spent differently, not a different API:\n * it starts on the real-time route and falls back on its own if that route\n * delivers no frames. Apps used to hand-roll this (open a real-time view, run a\n * timer, swap players when it stayed black); getting the fallback wrong showed a\n * black frame to a live audience, so it belongs here rather than in every app.\n */\n createMonitor(): MebiusPlayer {\n this.assertConnected();\n return new MebiusPlayer(this.signaling, { mode: \"low-latency\" }, this.deliveries, this.telemetry, this.userId);\n }\n\n /** Close the connection and release resources. */\n disconnect(reason?: string): void {\n if (this.expiryTimer) clearTimeout(this.expiryTimer);\n this.expiryTimer = null;\n this.connected = false;\n this.emit(\"disconnected\", { reason });\n this.removeAllListeners();\n }\n\n private assertConnected(): void {\n if (!this.connected) throw mebiusError(\"NOT_CONNECTED\");\n }\n}\n","import { MebiusClient } from \"./client.js\";\nimport { mebiusError } from \"./errors.js\";\nimport type { MebiusConnectOptions, MebiusInitOptions } from \"./types.js\";\n\nlet config: MebiusInitOptions | null = null;\n\n/**\n * Entry point to the Mebius Web SDK.\n *\n * ```ts\n * Mebius.init({ appId: \"app_123\", gateway: \"https://gateway.mebius.io\" });\n * const client = Mebius.connect({ token });\n * ```\n */\nexport const Mebius = {\n /** Configure the SDK once, before connecting. */\n init(options: MebiusInitOptions): void {\n if (!options.appId) throw mebiusError(\"UNKNOWN\", \"Mebius.init requires an appId.\");\n if (!options.gateway) throw mebiusError(\"UNKNOWN\", \"Mebius.init requires a gateway URL.\");\n config = { ...options };\n },\n\n /**\n * Connect using a short-lived token minted by your backend. Returns a\n * {@link MebiusClient}. Listen for `\"connected\"` / `\"error\"` on it.\n */\n connect(options: MebiusConnectOptions): MebiusClient {\n if (!config) {\n throw mebiusError(\"UNKNOWN\", \"Call Mebius.init() before Mebius.connect().\");\n }\n if (!options.token) throw mebiusError(\"UNKNOWN\", \"Mebius.connect requires a token.\");\n const telemetry =\n options.beaconToken && options.beaconUrl\n ? { token: options.beaconToken, url: options.beaconUrl }\n : null;\n const client = new MebiusClient(config, options.token, options.deliveries ?? [], telemetry, options.userId);\n client.open();\n return client;\n },\n\n /** @internal Reset configuration (used in tests). */\n _reset(): void {\n config = null;\n },\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACSO,IAAM,cAAN,MAAM,qBAAoB,MAAM;A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,UAAU,IACrD;AACN,UAAM,SAAS,IAAI,aAAa,QAAQ,QAAQ,OAAO,QAAQ,cAAc,CAAC,GAAG,WAAW,QAAQ,MAAM;AAC1G,WAAO,KAAK;AACZ,WAAO;AAAA,EACT;AAAA;AAAA,EAGA,SAAe;AACb,aAAS;AAAA,EACX;AACF;","names":["STATS_INTERVAL_MS","config"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -43,6 +43,20 @@ interface MebiusConnectOptions {
|
|
|
43
43
|
* Mebius origin rather than the nearest edge.
|
|
44
44
|
*/
|
|
45
45
|
deliveries?: MebiusDelivery[];
|
|
46
|
+
/**
|
|
47
|
+
* Quality reporting credential from the same token response
|
|
48
|
+
* (`beaconToken`). Pass it through and Mebius shows this stream's publish and
|
|
49
|
+
* playback quality in your dashboard, and counts viewer minutes from it.
|
|
50
|
+
*
|
|
51
|
+
* Optional: without it the stream works exactly the same, you just see no
|
|
52
|
+
* quality data for it. Safe in the client — it can only report telemetry for
|
|
53
|
+
* this one stream.
|
|
54
|
+
*/
|
|
55
|
+
beaconToken?: string;
|
|
56
|
+
/** Where to report it, from the same token response (`beaconUrl`). */
|
|
57
|
+
beaconUrl?: string;
|
|
58
|
+
/** Your own id for the person on this connection, if you want it in reports. */
|
|
59
|
+
userId?: string;
|
|
46
60
|
}
|
|
47
61
|
/** A media capture constraint: enable/disable, or a detailed constraint set. */
|
|
48
62
|
type MediaConstraint = boolean | MediaTrackConstraints;
|
|
@@ -197,6 +211,13 @@ declare class SignalingClient {
|
|
|
197
211
|
deleteResource(resourceUrl: string | null): Promise<void>;
|
|
198
212
|
}
|
|
199
213
|
|
|
214
|
+
interface TelemetryTarget {
|
|
215
|
+
/** Absolute beacon URL, as returned with the token. */
|
|
216
|
+
url: string;
|
|
217
|
+
/** Beacon credential, as returned with the token. */
|
|
218
|
+
token: string;
|
|
219
|
+
}
|
|
220
|
+
|
|
200
221
|
/**
|
|
201
222
|
* Publishes the local camera/microphone to a Mebius stream.
|
|
202
223
|
*
|
|
@@ -205,13 +226,16 @@ declare class SignalingClient {
|
|
|
205
226
|
*/
|
|
206
227
|
declare class MebiusBroadcaster extends TypedEmitter<BroadcasterEventMap> {
|
|
207
228
|
private readonly options;
|
|
229
|
+
private readonly telemetry;
|
|
230
|
+
private readonly userId?;
|
|
208
231
|
private readonly transport;
|
|
209
232
|
private stream;
|
|
210
233
|
private facingMode;
|
|
211
234
|
private statsTimer;
|
|
212
235
|
private started;
|
|
236
|
+
private reporter;
|
|
213
237
|
/** @internal */
|
|
214
|
-
constructor(signaling: SignalingClient, options: BroadcasterOptions);
|
|
238
|
+
constructor(signaling: SignalingClient, options: BroadcasterOptions, telemetry?: TelemetryTarget | null, userId?: string | undefined);
|
|
215
239
|
/** Begin broadcasting under the given stream id. */
|
|
216
240
|
start(streamId: string): Promise<void>;
|
|
217
241
|
/** Stop broadcasting and release the camera/microphone. */
|
|
@@ -241,13 +265,16 @@ declare class MebiusBroadcaster extends TypedEmitter<BroadcasterEventMap> {
|
|
|
241
265
|
* moves to the next one by itself if the current one stops producing frames.
|
|
242
266
|
*/
|
|
243
267
|
declare class MebiusPlayer extends TypedEmitter<PlayerEventMap> {
|
|
268
|
+
private readonly telemetry;
|
|
269
|
+
private readonly userId?;
|
|
244
270
|
private readonly candidates;
|
|
245
271
|
private transport;
|
|
246
272
|
private video;
|
|
247
273
|
private statsTimer;
|
|
248
274
|
private playing;
|
|
275
|
+
private reporter;
|
|
249
276
|
/** @internal */
|
|
250
|
-
constructor(signaling: SignalingClient, options?: PlayerOptions, deliveries?: readonly MebiusDelivery[]);
|
|
277
|
+
constructor(signaling: SignalingClient, options?: PlayerOptions, deliveries?: readonly MebiusDelivery[], telemetry?: TelemetryTarget | null, userId?: string | undefined);
|
|
251
278
|
/** Start playing `streamId` into the given video element or selector. */
|
|
252
279
|
play(streamId: string, viewTarget: ViewTarget): Promise<void>;
|
|
253
280
|
/** Stop playback and detach from the video element. */
|
|
@@ -266,11 +293,13 @@ declare class MebiusPlayer extends TypedEmitter<PlayerEventMap> {
|
|
|
266
293
|
declare class MebiusClient extends TypedEmitter<ClientEventMap> {
|
|
267
294
|
private readonly token;
|
|
268
295
|
private readonly deliveries;
|
|
296
|
+
private readonly telemetry;
|
|
297
|
+
private readonly userId?;
|
|
269
298
|
private readonly signaling;
|
|
270
299
|
private expiryTimer;
|
|
271
300
|
private connected;
|
|
272
301
|
/** @internal */
|
|
273
|
-
constructor(config: MebiusInitOptions, token: string, deliveries?: readonly MebiusDelivery[]);
|
|
302
|
+
constructor(config: MebiusInitOptions, token: string, deliveries?: readonly MebiusDelivery[], telemetry?: TelemetryTarget | null, userId?: string | undefined);
|
|
274
303
|
/** @internal Called by {@link Mebius.connect}. */
|
|
275
304
|
open(): void;
|
|
276
305
|
/** Create a broadcaster bound to this connection. */
|
package/dist/index.d.ts
CHANGED
|
@@ -43,6 +43,20 @@ interface MebiusConnectOptions {
|
|
|
43
43
|
* Mebius origin rather than the nearest edge.
|
|
44
44
|
*/
|
|
45
45
|
deliveries?: MebiusDelivery[];
|
|
46
|
+
/**
|
|
47
|
+
* Quality reporting credential from the same token response
|
|
48
|
+
* (`beaconToken`). Pass it through and Mebius shows this stream's publish and
|
|
49
|
+
* playback quality in your dashboard, and counts viewer minutes from it.
|
|
50
|
+
*
|
|
51
|
+
* Optional: without it the stream works exactly the same, you just see no
|
|
52
|
+
* quality data for it. Safe in the client — it can only report telemetry for
|
|
53
|
+
* this one stream.
|
|
54
|
+
*/
|
|
55
|
+
beaconToken?: string;
|
|
56
|
+
/** Where to report it, from the same token response (`beaconUrl`). */
|
|
57
|
+
beaconUrl?: string;
|
|
58
|
+
/** Your own id for the person on this connection, if you want it in reports. */
|
|
59
|
+
userId?: string;
|
|
46
60
|
}
|
|
47
61
|
/** A media capture constraint: enable/disable, or a detailed constraint set. */
|
|
48
62
|
type MediaConstraint = boolean | MediaTrackConstraints;
|
|
@@ -197,6 +211,13 @@ declare class SignalingClient {
|
|
|
197
211
|
deleteResource(resourceUrl: string | null): Promise<void>;
|
|
198
212
|
}
|
|
199
213
|
|
|
214
|
+
interface TelemetryTarget {
|
|
215
|
+
/** Absolute beacon URL, as returned with the token. */
|
|
216
|
+
url: string;
|
|
217
|
+
/** Beacon credential, as returned with the token. */
|
|
218
|
+
token: string;
|
|
219
|
+
}
|
|
220
|
+
|
|
200
221
|
/**
|
|
201
222
|
* Publishes the local camera/microphone to a Mebius stream.
|
|
202
223
|
*
|
|
@@ -205,13 +226,16 @@ declare class SignalingClient {
|
|
|
205
226
|
*/
|
|
206
227
|
declare class MebiusBroadcaster extends TypedEmitter<BroadcasterEventMap> {
|
|
207
228
|
private readonly options;
|
|
229
|
+
private readonly telemetry;
|
|
230
|
+
private readonly userId?;
|
|
208
231
|
private readonly transport;
|
|
209
232
|
private stream;
|
|
210
233
|
private facingMode;
|
|
211
234
|
private statsTimer;
|
|
212
235
|
private started;
|
|
236
|
+
private reporter;
|
|
213
237
|
/** @internal */
|
|
214
|
-
constructor(signaling: SignalingClient, options: BroadcasterOptions);
|
|
238
|
+
constructor(signaling: SignalingClient, options: BroadcasterOptions, telemetry?: TelemetryTarget | null, userId?: string | undefined);
|
|
215
239
|
/** Begin broadcasting under the given stream id. */
|
|
216
240
|
start(streamId: string): Promise<void>;
|
|
217
241
|
/** Stop broadcasting and release the camera/microphone. */
|
|
@@ -241,13 +265,16 @@ declare class MebiusBroadcaster extends TypedEmitter<BroadcasterEventMap> {
|
|
|
241
265
|
* moves to the next one by itself if the current one stops producing frames.
|
|
242
266
|
*/
|
|
243
267
|
declare class MebiusPlayer extends TypedEmitter<PlayerEventMap> {
|
|
268
|
+
private readonly telemetry;
|
|
269
|
+
private readonly userId?;
|
|
244
270
|
private readonly candidates;
|
|
245
271
|
private transport;
|
|
246
272
|
private video;
|
|
247
273
|
private statsTimer;
|
|
248
274
|
private playing;
|
|
275
|
+
private reporter;
|
|
249
276
|
/** @internal */
|
|
250
|
-
constructor(signaling: SignalingClient, options?: PlayerOptions, deliveries?: readonly MebiusDelivery[]);
|
|
277
|
+
constructor(signaling: SignalingClient, options?: PlayerOptions, deliveries?: readonly MebiusDelivery[], telemetry?: TelemetryTarget | null, userId?: string | undefined);
|
|
251
278
|
/** Start playing `streamId` into the given video element or selector. */
|
|
252
279
|
play(streamId: string, viewTarget: ViewTarget): Promise<void>;
|
|
253
280
|
/** Stop playback and detach from the video element. */
|
|
@@ -266,11 +293,13 @@ declare class MebiusPlayer extends TypedEmitter<PlayerEventMap> {
|
|
|
266
293
|
declare class MebiusClient extends TypedEmitter<ClientEventMap> {
|
|
267
294
|
private readonly token;
|
|
268
295
|
private readonly deliveries;
|
|
296
|
+
private readonly telemetry;
|
|
297
|
+
private readonly userId?;
|
|
269
298
|
private readonly signaling;
|
|
270
299
|
private expiryTimer;
|
|
271
300
|
private connected;
|
|
272
301
|
/** @internal */
|
|
273
|
-
constructor(config: MebiusInitOptions, token: string, deliveries?: readonly MebiusDelivery[]);
|
|
302
|
+
constructor(config: MebiusInitOptions, token: string, deliveries?: readonly MebiusDelivery[], telemetry?: TelemetryTarget | null, userId?: string | undefined);
|
|
274
303
|
/** @internal Called by {@link Mebius.connect}. */
|
|
275
304
|
open(): void;
|
|
276
305
|
/** Create a broadcaster bound to this connection. */
|