@mebius-io/web 0.2.0 → 0.3.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 +54 -12
- package/dist/index.cjs +181 -24
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +59 -9
- package/dist/index.d.ts +59 -9
- package/dist/index.global.js +9709 -33
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +181 -24
- package/dist/index.js.map +1 -1
- package/package.json +2 -1
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/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 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 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 this.video = video;\n const url = 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 — 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, 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\";\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/** Auto-select the view transport for a playback mode. */\nexport function createViewTransport(\n mode: PlaybackMode,\n signaling: SignalingClient,\n): ViewTransport {\n switch (mode) {\n case \"low-latency\":\n return new WhepViewTransport(signaling);\n case \"scale\":\n return new HlsViewTransport(signaling);\n }\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 { resolveVideoElement } from \"./internal/view-target.js\";\nimport type { SignalingClient } from \"./internal/signaling.js\";\nimport { createViewTransport, type ViewTransport } from \"./internal/transport.js\";\nimport type { PlayerOptions, ViewTarget } from \"./types.js\";\n\nconst STATS_INTERVAL_MS = 2000;\n\n/**\n * Plays a Mebius stream into a `<video>` element.\n *\n * Create one with {@link MebiusClient.createPlayer}, choosing a playback\n * {@link PlaybackMode | mode}; Mebius selects the right delivery automatically.\n */\nexport class MebiusPlayer extends TypedEmitter<PlayerEventMap> {\n private readonly transport: ViewTransport;\n private video: HTMLVideoElement | null = null;\n private statsTimer: ReturnType<typeof setInterval> | null = null;\n private playing = false;\n\n /** @internal */\n constructor(signaling: SignalingClient, options: PlayerOptions) {\n super();\n this.transport = createViewTransport(options.mode, signaling);\n this.transport.onEnded(() => {\n this.playing = false;\n this.stopStats();\n this.emit(\"ended\", undefined);\n });\n this.transport.onBuffering(() => this.emit(\"buffering\", undefined));\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 this.video = resolveVideoElement(viewTarget);\n await this.transport.start(streamId, this.video);\n this.playing = true;\n this.startStats();\n this.emit(\"playing\", { streamId });\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.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 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 * 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 /** 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 { BroadcasterOptions, MebiusInitOptions, PlayerOptions } 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(config: MebiusInitOptions, private readonly token: string) {\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);\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);\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,OA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K,gBAAgB;AACrB,WAAO,IAAI,aAAa,KAAK,WAAW,OAAO;AAAA,EACjD;AAAA;AAAA,EAGA,WAAW,QAAuB;AAChC,QAAI,KAAK,YAAa,cAAa,KAAK,WAAW;AACnD,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;;;AC9DA,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,KAAK;AACrD,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/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;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,CAAC;AAC/E,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
|
@@ -15,6 +15,18 @@ interface MebiusInitOptions {
|
|
|
15
15
|
*/
|
|
16
16
|
gateway: string;
|
|
17
17
|
}
|
|
18
|
+
/**
|
|
19
|
+
* One playback route Mebius has prepared for a stream, as returned alongside the
|
|
20
|
+
* token by your backend. Pass the list through untouched — Mebius orders it and
|
|
21
|
+
* picks from it. `kind` is a Mebius intent label, not a format: treat both fields
|
|
22
|
+
* as opaque.
|
|
23
|
+
*/
|
|
24
|
+
interface MebiusDelivery {
|
|
25
|
+
/** Mebius intent label, e.g. `"fast"` or `"wide"`. Opaque to your app. */
|
|
26
|
+
kind: string;
|
|
27
|
+
/** A Mebius-relative path. Opaque to your app; Mebius resolves it. */
|
|
28
|
+
path: string;
|
|
29
|
+
}
|
|
18
30
|
/** Options for {@link Mebius.connect}. */
|
|
19
31
|
interface MebiusConnectOptions {
|
|
20
32
|
/**
|
|
@@ -22,6 +34,15 @@ interface MebiusConnectOptions {
|
|
|
22
34
|
* The app secret must never be embedded in client code.
|
|
23
35
|
*/
|
|
24
36
|
token: string;
|
|
37
|
+
/**
|
|
38
|
+
* The `deliveries` list your backend received together with the token. Pass it
|
|
39
|
+
* through as-is and Mebius will pick the best route for each viewer's device,
|
|
40
|
+
* falling back automatically if one stops delivering frames.
|
|
41
|
+
*
|
|
42
|
+
* Optional: without it playback still works, but every viewer is served from
|
|
43
|
+
* Mebius origin rather than the nearest edge.
|
|
44
|
+
*/
|
|
45
|
+
deliveries?: MebiusDelivery[];
|
|
25
46
|
}
|
|
26
47
|
/** A media capture constraint: enable/disable, or a detailed constraint set. */
|
|
27
48
|
type MediaConstraint = boolean | MediaTrackConstraints;
|
|
@@ -34,17 +55,21 @@ interface BroadcasterOptions {
|
|
|
34
55
|
}
|
|
35
56
|
/**
|
|
36
57
|
* Playback mode.
|
|
58
|
+
* - `"auto"` — recommended. Mebius picks per viewer and falls back on its own.
|
|
37
59
|
* - `"low-latency"` — minimal (sub-second) delay, best for interactive/real-time
|
|
38
60
|
* viewing. Web browsers only.
|
|
61
|
+
* - `"balanced"` — a low delay that still scales to a large audience. Web
|
|
62
|
+
* browsers with Media Source support (i.e. not iOS Safari).
|
|
39
63
|
* - `"scale"` — optimized for the largest audiences; higher delay. Plays on
|
|
40
64
|
* every platform, including iOS Safari.
|
|
41
65
|
*
|
|
42
66
|
* Mebius picks the right delivery method for each mode automatically.
|
|
43
67
|
*/
|
|
44
|
-
type PlaybackMode = "low-latency" | "scale";
|
|
68
|
+
type PlaybackMode = "auto" | "low-latency" | "balanced" | "scale";
|
|
45
69
|
/** Options for {@link MebiusClient.createPlayer}. */
|
|
46
70
|
interface PlayerOptions {
|
|
47
|
-
|
|
71
|
+
/** Defaults to `"auto"` — let Mebius choose per viewer. */
|
|
72
|
+
mode?: PlaybackMode;
|
|
48
73
|
}
|
|
49
74
|
/**
|
|
50
75
|
* Where a player renders video: a `<video>` element, or a CSS selector that
|
|
@@ -151,6 +176,15 @@ declare class SignalingClient {
|
|
|
151
176
|
private headers;
|
|
152
177
|
/** Append the access token as a query param (the form the engine enforces). */
|
|
153
178
|
private withToken;
|
|
179
|
+
/**
|
|
180
|
+
* Absolute, tokenized URL for a gateway-relative delivery path handed to us
|
|
181
|
+
* by the gateway (`deliveries[].path`). The gateway decides which paths exist
|
|
182
|
+
* and in what order; the SDK only resolves them against its own base and
|
|
183
|
+
* attaches the access token. Anything that is not a plain gateway-relative
|
|
184
|
+
* path is rejected rather than fetched: an absolute URL there would send the
|
|
185
|
+
* token to a host we did not choose.
|
|
186
|
+
*/
|
|
187
|
+
deliveryUrl(path: string): string;
|
|
154
188
|
/** Playlist URL for scale-mode playback. */
|
|
155
189
|
scalePlaylistUrl(streamId: string): string;
|
|
156
190
|
private pathFor;
|
|
@@ -202,22 +236,25 @@ declare class MebiusBroadcaster extends TypedEmitter<BroadcasterEventMap> {
|
|
|
202
236
|
/**
|
|
203
237
|
* Plays a Mebius stream into a `<video>` element.
|
|
204
238
|
*
|
|
205
|
-
* Create one with {@link MebiusClient.createPlayer}, choosing a
|
|
206
|
-
* {@link PlaybackMode | mode}; Mebius selects the
|
|
239
|
+
* Create one with {@link MebiusClient.createPlayer}, optionally choosing a
|
|
240
|
+
* playback {@link PlaybackMode | mode}; Mebius selects the delivery route, and
|
|
241
|
+
* moves to the next one by itself if the current one stops producing frames.
|
|
207
242
|
*/
|
|
208
243
|
declare class MebiusPlayer extends TypedEmitter<PlayerEventMap> {
|
|
209
|
-
private readonly
|
|
244
|
+
private readonly candidates;
|
|
245
|
+
private transport;
|
|
210
246
|
private video;
|
|
211
247
|
private statsTimer;
|
|
212
248
|
private playing;
|
|
213
249
|
/** @internal */
|
|
214
|
-
constructor(signaling: SignalingClient, options
|
|
250
|
+
constructor(signaling: SignalingClient, options?: PlayerOptions, deliveries?: readonly MebiusDelivery[]);
|
|
215
251
|
/** Start playing `streamId` into the given video element or selector. */
|
|
216
252
|
play(streamId: string, viewTarget: ViewTarget): Promise<void>;
|
|
217
253
|
/** Stop playback and detach from the video element. */
|
|
218
254
|
stop(): Promise<void>;
|
|
219
255
|
/** Set output volume in the range 0..1. */
|
|
220
256
|
setVolume(volume: number): void;
|
|
257
|
+
private attach;
|
|
221
258
|
private startStats;
|
|
222
259
|
private stopStats;
|
|
223
260
|
}
|
|
@@ -228,17 +265,30 @@ declare class MebiusPlayer extends TypedEmitter<PlayerEventMap> {
|
|
|
228
265
|
*/
|
|
229
266
|
declare class MebiusClient extends TypedEmitter<ClientEventMap> {
|
|
230
267
|
private readonly token;
|
|
268
|
+
private readonly deliveries;
|
|
231
269
|
private readonly signaling;
|
|
232
270
|
private expiryTimer;
|
|
233
271
|
private connected;
|
|
234
272
|
/** @internal */
|
|
235
|
-
constructor(config: MebiusInitOptions, token: string);
|
|
273
|
+
constructor(config: MebiusInitOptions, token: string, deliveries?: readonly MebiusDelivery[]);
|
|
236
274
|
/** @internal Called by {@link Mebius.connect}. */
|
|
237
275
|
open(): void;
|
|
238
276
|
/** Create a broadcaster bound to this connection. */
|
|
239
277
|
createBroadcaster(options?: BroadcasterOptions): MebiusBroadcaster;
|
|
240
278
|
/** Create a player bound to this connection. */
|
|
241
|
-
createPlayer(options
|
|
279
|
+
createPlayer(options?: PlayerOptions): MebiusPlayer;
|
|
280
|
+
/**
|
|
281
|
+
* Create a monitor: a player tuned for watching a stream you are interacting
|
|
282
|
+
* WITH rather than merely watching — the other side of a co-broadcast, where a
|
|
283
|
+
* second or two of delay makes the interaction feel broken.
|
|
284
|
+
*
|
|
285
|
+
* It is a player with the delay budget spent differently, not a different API:
|
|
286
|
+
* it starts on the real-time route and falls back on its own if that route
|
|
287
|
+
* delivers no frames. Apps used to hand-roll this (open a real-time view, run a
|
|
288
|
+
* timer, swap players when it stayed black); getting the fallback wrong showed a
|
|
289
|
+
* black frame to a live audience, so it belongs here rather than in every app.
|
|
290
|
+
*/
|
|
291
|
+
createMonitor(): MebiusPlayer;
|
|
242
292
|
/** Close the connection and release resources. */
|
|
243
293
|
disconnect(reason?: string): void;
|
|
244
294
|
private assertConnected;
|
|
@@ -264,4 +314,4 @@ declare const Mebius: {
|
|
|
264
314
|
_reset(): void;
|
|
265
315
|
};
|
|
266
316
|
|
|
267
|
-
export { type BroadcastStats, type BroadcasterEventMap, type BroadcasterOptions, type ClientEventMap, Mebius, MebiusBroadcaster, MebiusClient, type MebiusConnectOptions, MebiusError, type MebiusErrorCode, type MebiusInitOptions, MebiusPlayer, type MediaConstraint, type PlaybackMode, type PlaybackStats, type PlayerEventMap, type PlayerOptions, type ViewTarget, mebiusError };
|
|
317
|
+
export { type BroadcastStats, type BroadcasterEventMap, type BroadcasterOptions, type ClientEventMap, Mebius, MebiusBroadcaster, MebiusClient, type MebiusConnectOptions, type MebiusDelivery, MebiusError, type MebiusErrorCode, type MebiusInitOptions, MebiusPlayer, type MediaConstraint, type PlaybackMode, type PlaybackStats, type PlayerEventMap, type PlayerOptions, type ViewTarget, mebiusError };
|
package/dist/index.d.ts
CHANGED
|
@@ -15,6 +15,18 @@ interface MebiusInitOptions {
|
|
|
15
15
|
*/
|
|
16
16
|
gateway: string;
|
|
17
17
|
}
|
|
18
|
+
/**
|
|
19
|
+
* One playback route Mebius has prepared for a stream, as returned alongside the
|
|
20
|
+
* token by your backend. Pass the list through untouched — Mebius orders it and
|
|
21
|
+
* picks from it. `kind` is a Mebius intent label, not a format: treat both fields
|
|
22
|
+
* as opaque.
|
|
23
|
+
*/
|
|
24
|
+
interface MebiusDelivery {
|
|
25
|
+
/** Mebius intent label, e.g. `"fast"` or `"wide"`. Opaque to your app. */
|
|
26
|
+
kind: string;
|
|
27
|
+
/** A Mebius-relative path. Opaque to your app; Mebius resolves it. */
|
|
28
|
+
path: string;
|
|
29
|
+
}
|
|
18
30
|
/** Options for {@link Mebius.connect}. */
|
|
19
31
|
interface MebiusConnectOptions {
|
|
20
32
|
/**
|
|
@@ -22,6 +34,15 @@ interface MebiusConnectOptions {
|
|
|
22
34
|
* The app secret must never be embedded in client code.
|
|
23
35
|
*/
|
|
24
36
|
token: string;
|
|
37
|
+
/**
|
|
38
|
+
* The `deliveries` list your backend received together with the token. Pass it
|
|
39
|
+
* through as-is and Mebius will pick the best route for each viewer's device,
|
|
40
|
+
* falling back automatically if one stops delivering frames.
|
|
41
|
+
*
|
|
42
|
+
* Optional: without it playback still works, but every viewer is served from
|
|
43
|
+
* Mebius origin rather than the nearest edge.
|
|
44
|
+
*/
|
|
45
|
+
deliveries?: MebiusDelivery[];
|
|
25
46
|
}
|
|
26
47
|
/** A media capture constraint: enable/disable, or a detailed constraint set. */
|
|
27
48
|
type MediaConstraint = boolean | MediaTrackConstraints;
|
|
@@ -34,17 +55,21 @@ interface BroadcasterOptions {
|
|
|
34
55
|
}
|
|
35
56
|
/**
|
|
36
57
|
* Playback mode.
|
|
58
|
+
* - `"auto"` — recommended. Mebius picks per viewer and falls back on its own.
|
|
37
59
|
* - `"low-latency"` — minimal (sub-second) delay, best for interactive/real-time
|
|
38
60
|
* viewing. Web browsers only.
|
|
61
|
+
* - `"balanced"` — a low delay that still scales to a large audience. Web
|
|
62
|
+
* browsers with Media Source support (i.e. not iOS Safari).
|
|
39
63
|
* - `"scale"` — optimized for the largest audiences; higher delay. Plays on
|
|
40
64
|
* every platform, including iOS Safari.
|
|
41
65
|
*
|
|
42
66
|
* Mebius picks the right delivery method for each mode automatically.
|
|
43
67
|
*/
|
|
44
|
-
type PlaybackMode = "low-latency" | "scale";
|
|
68
|
+
type PlaybackMode = "auto" | "low-latency" | "balanced" | "scale";
|
|
45
69
|
/** Options for {@link MebiusClient.createPlayer}. */
|
|
46
70
|
interface PlayerOptions {
|
|
47
|
-
|
|
71
|
+
/** Defaults to `"auto"` — let Mebius choose per viewer. */
|
|
72
|
+
mode?: PlaybackMode;
|
|
48
73
|
}
|
|
49
74
|
/**
|
|
50
75
|
* Where a player renders video: a `<video>` element, or a CSS selector that
|
|
@@ -151,6 +176,15 @@ declare class SignalingClient {
|
|
|
151
176
|
private headers;
|
|
152
177
|
/** Append the access token as a query param (the form the engine enforces). */
|
|
153
178
|
private withToken;
|
|
179
|
+
/**
|
|
180
|
+
* Absolute, tokenized URL for a gateway-relative delivery path handed to us
|
|
181
|
+
* by the gateway (`deliveries[].path`). The gateway decides which paths exist
|
|
182
|
+
* and in what order; the SDK only resolves them against its own base and
|
|
183
|
+
* attaches the access token. Anything that is not a plain gateway-relative
|
|
184
|
+
* path is rejected rather than fetched: an absolute URL there would send the
|
|
185
|
+
* token to a host we did not choose.
|
|
186
|
+
*/
|
|
187
|
+
deliveryUrl(path: string): string;
|
|
154
188
|
/** Playlist URL for scale-mode playback. */
|
|
155
189
|
scalePlaylistUrl(streamId: string): string;
|
|
156
190
|
private pathFor;
|
|
@@ -202,22 +236,25 @@ declare class MebiusBroadcaster extends TypedEmitter<BroadcasterEventMap> {
|
|
|
202
236
|
/**
|
|
203
237
|
* Plays a Mebius stream into a `<video>` element.
|
|
204
238
|
*
|
|
205
|
-
* Create one with {@link MebiusClient.createPlayer}, choosing a
|
|
206
|
-
* {@link PlaybackMode | mode}; Mebius selects the
|
|
239
|
+
* Create one with {@link MebiusClient.createPlayer}, optionally choosing a
|
|
240
|
+
* playback {@link PlaybackMode | mode}; Mebius selects the delivery route, and
|
|
241
|
+
* moves to the next one by itself if the current one stops producing frames.
|
|
207
242
|
*/
|
|
208
243
|
declare class MebiusPlayer extends TypedEmitter<PlayerEventMap> {
|
|
209
|
-
private readonly
|
|
244
|
+
private readonly candidates;
|
|
245
|
+
private transport;
|
|
210
246
|
private video;
|
|
211
247
|
private statsTimer;
|
|
212
248
|
private playing;
|
|
213
249
|
/** @internal */
|
|
214
|
-
constructor(signaling: SignalingClient, options
|
|
250
|
+
constructor(signaling: SignalingClient, options?: PlayerOptions, deliveries?: readonly MebiusDelivery[]);
|
|
215
251
|
/** Start playing `streamId` into the given video element or selector. */
|
|
216
252
|
play(streamId: string, viewTarget: ViewTarget): Promise<void>;
|
|
217
253
|
/** Stop playback and detach from the video element. */
|
|
218
254
|
stop(): Promise<void>;
|
|
219
255
|
/** Set output volume in the range 0..1. */
|
|
220
256
|
setVolume(volume: number): void;
|
|
257
|
+
private attach;
|
|
221
258
|
private startStats;
|
|
222
259
|
private stopStats;
|
|
223
260
|
}
|
|
@@ -228,17 +265,30 @@ declare class MebiusPlayer extends TypedEmitter<PlayerEventMap> {
|
|
|
228
265
|
*/
|
|
229
266
|
declare class MebiusClient extends TypedEmitter<ClientEventMap> {
|
|
230
267
|
private readonly token;
|
|
268
|
+
private readonly deliveries;
|
|
231
269
|
private readonly signaling;
|
|
232
270
|
private expiryTimer;
|
|
233
271
|
private connected;
|
|
234
272
|
/** @internal */
|
|
235
|
-
constructor(config: MebiusInitOptions, token: string);
|
|
273
|
+
constructor(config: MebiusInitOptions, token: string, deliveries?: readonly MebiusDelivery[]);
|
|
236
274
|
/** @internal Called by {@link Mebius.connect}. */
|
|
237
275
|
open(): void;
|
|
238
276
|
/** Create a broadcaster bound to this connection. */
|
|
239
277
|
createBroadcaster(options?: BroadcasterOptions): MebiusBroadcaster;
|
|
240
278
|
/** Create a player bound to this connection. */
|
|
241
|
-
createPlayer(options
|
|
279
|
+
createPlayer(options?: PlayerOptions): MebiusPlayer;
|
|
280
|
+
/**
|
|
281
|
+
* Create a monitor: a player tuned for watching a stream you are interacting
|
|
282
|
+
* WITH rather than merely watching — the other side of a co-broadcast, where a
|
|
283
|
+
* second or two of delay makes the interaction feel broken.
|
|
284
|
+
*
|
|
285
|
+
* It is a player with the delay budget spent differently, not a different API:
|
|
286
|
+
* it starts on the real-time route and falls back on its own if that route
|
|
287
|
+
* delivers no frames. Apps used to hand-roll this (open a real-time view, run a
|
|
288
|
+
* timer, swap players when it stayed black); getting the fallback wrong showed a
|
|
289
|
+
* black frame to a live audience, so it belongs here rather than in every app.
|
|
290
|
+
*/
|
|
291
|
+
createMonitor(): MebiusPlayer;
|
|
242
292
|
/** Close the connection and release resources. */
|
|
243
293
|
disconnect(reason?: string): void;
|
|
244
294
|
private assertConnected;
|
|
@@ -264,4 +314,4 @@ declare const Mebius: {
|
|
|
264
314
|
_reset(): void;
|
|
265
315
|
};
|
|
266
316
|
|
|
267
|
-
export { type BroadcastStats, type BroadcasterEventMap, type BroadcasterOptions, type ClientEventMap, Mebius, MebiusBroadcaster, MebiusClient, type MebiusConnectOptions, MebiusError, type MebiusErrorCode, type MebiusInitOptions, MebiusPlayer, type MediaConstraint, type PlaybackMode, type PlaybackStats, type PlayerEventMap, type PlayerOptions, type ViewTarget, mebiusError };
|
|
317
|
+
export { type BroadcastStats, type BroadcasterEventMap, type BroadcasterOptions, type ClientEventMap, Mebius, MebiusBroadcaster, MebiusClient, type MebiusConnectOptions, type MebiusDelivery, MebiusError, type MebiusErrorCode, type MebiusInitOptions, MebiusPlayer, type MediaConstraint, type PlaybackMode, type PlaybackStats, type PlayerEventMap, type PlayerOptions, type ViewTarget, mebiusError };
|