stream-lens-sdk
v0.1.1
Published
Lightweight HTML video telemetry SDK — QoE metrics from a <video> element
Maintainers
Readme
stream-lens-sdk
Lightweight HTML video telemetry SDK — Quality-of-Experience (QoE)
metrics derived directly from a <video> element. Zero runtime
dependencies, ESM-only, fully typed.
Point it at any HTMLVideoElement (native, video.js, hls.js, Shaka,
etc.) and it will emit structured telemetry events you can log to the
console, forward to your own collector, or ship directly to a
stream-lens-api
instance.
The Stream Lens ecosystem
stream-lens-sdk is the browser layer of a three-repo stack. Each repo
is independent, but they are designed to compose end-to-end.
| Repo | Role |
| --- | --- |
| stream-lens-sdk | This package. Instruments a <video> element and emits QoE telemetry through a pluggable Reporter. |
| stream-lens-api | Ingestion service. Accepts sessions + batched events (POST /v1/sessions, /events, /close) and persists them for analysis. |
| stream-lens-client | Dashboard that visualises the data collected by the API — startup times, rebuffer ratios, error rates, EBVS. |
What it tracks
- Video startup time — ms between the first
playintent (orloadstart) and the firstplayingevent. - Time to first frame — ms between
loadstartandloadeddata. - Rebuffering — count + cumulative duration of
waiting → playingtransitions after startup, plus the derived rebuffer ratio. - Exit before video start (EBVS) — destroyed before playback ever
began while a
playhad already been requested. - Playback failures —
errorevents, with theMediaErrorcode and message. - Lifecycle — every native media event (
loadstart,canplay,pause,seeked,ended,timeupdate, etc.) for full-fidelity debugging.
Installation
npm install stream-lens-sdkRequires Node >=20.19 to build against, runs in any evergreen browser.
Quick start (console reporter)
import { createVideoMonitor } from 'stream-lens-sdk';
const video = document.querySelector<HTMLVideoElement>('video')!;
const monitor = createVideoMonitor(video, {
videoId: 'abc-123',
metadata: { title: 'Intro video', userId: 'u-42' },
});
// When the player unmounts / the user navigates away:
monitor.destroy();With no reporter option, every event is logged via console.log.
Shipping to stream-lens-api
Use createHttpReporter to batch-send events to a running
stream-lens-api
instance. It opens a session on construction, flushes event batches by
size or interval, and posts a final close when the monitor is
destroyed.
import { createVideoMonitor, createHttpReporter } from 'stream-lens-sdk';
const reporter = createHttpReporter({
apiUrl: 'https://your-stream-lens-api.example.com',
videoId: 'abc-123',
userId: 'u-42',
metadata: { title: 'Intro video' },
// Optional tuning — defaults shown:
flushIntervalMs: 2000,
maxBatchSize: 50,
onError: (err) => console.warn('[stream-lens]', err),
});
const video = document.querySelector<HTMLVideoElement>('video')!;
const monitor = createVideoMonitor(video, { videoId: 'abc-123', reporter });
// `monitor.destroy()` already flushes and closes the reporter — you
// only need to call `reporter.close()` yourself if you destroy the
// monitor without going through `destroy()`.
window.addEventListener('pagehide', () => monitor.destroy());Custom reporter
Reporter is the transport seam — implement it to forward events to any
collector (your own API, analytics SDK, IndexedDB queue, etc.).
import { createVideoMonitor, type Reporter } from 'stream-lens-sdk';
const reporter: Reporter = {
report(event) {
fetch('/telemetry', {
method: 'POST',
body: JSON.stringify(event),
keepalive: true,
});
},
};
createVideoMonitor(video, { videoId: 'abc-123', reporter });Public API
import {
createVideoMonitor,
createHttpReporter,
consoleReporter,
type VideoMonitor,
type VideoMonitorOptions,
type VideoMonitorState,
type PlaybackPhase,
type Reporter,
type HttpReporter,
type HttpReporterOptions,
type TelemetryEvent,
type StartupTelemetryEvent,
type RebufferTelemetryEvent,
type ErrorTelemetryEvent,
type EbvsTelemetryEvent,
type LifecycleTelemetryEvent,
type NativeMediaEventName,
} from 'stream-lens-sdk';createVideoMonitor(video, options)
| Option | Type | Default | Notes |
| --- | --- | --- | --- |
| videoId | string | — | Stamped on every emitted event. |
| metadata | Record<string, unknown> | {} | Arbitrary context forwarded to the reporter. |
| reporter | Reporter | consoleReporter | Any object with a report(event) method. |
| timeUpdateThrottleMs | number | 1000 | Minimum gap between timeupdate lifecycle emits. |
Returns a VideoMonitor with a readonly state snapshot and a
destroy() method. destroy() aborts all listeners, emits a final
ebvs event when applicable, and calls reporter.close?.().
createHttpReporter(options)
| Option | Type | Default | Notes |
| --- | --- | --- | --- |
| apiUrl | string | — | Required. Base URL of a stream-lens-api deployment. |
| videoId | string | — | Required. |
| sessionId | string | crypto.randomUUID() | Override to correlate across reloads. |
| userId, anonId, userAgent, pageUrl, metadata | — | — | Forwarded on session open. |
| flushIntervalMs | number | 2000 | Time-based batch flush. |
| maxBatchSize | number | 50 | Size-based batch flush. |
| fetch | typeof fetch | globalThis.fetch | Inject a custom fetch (SSR, retries). |
| onError | (err) => void | noop | All network failures route here. |
Behavioural notes
- Startup time is measured from the earlier of
playIntentAtMsandloadStartAtMs. - A
waiting → playingtransition is only counted as a rebuffer after startup has been reported — the initialwaitingthat precedes first play is part of normal load, not a rebuffer. destroy()emits anebvsevent iff the monitor saw aplayintent but never reached the firstplaying.timeupdatelifecycle events are throttled (timeUpdateThrottleMs, default1000ms) to keep the reporter from drowning.
Run the showcase app
A standalone Vite + video.js playground lives under
example/. It plays Big Buck Bunny over HLS, attaches a
monitor, and renders live telemetry in a side panel with buttons to
force stalls / errors / EBVS.
git clone https://github.com/gabriel-hahn/stream-lens-sdk.git
cd stream-lens-sdk/example
npm install
npm run dev
# → http://localhost:5173The example consumes the SDK from ../src/index.ts via a Vite alias,
so no prior build of the root package is required — SDK edits
hot-reload into the demo.
Development
npm install
npm test # Vitest (jsdom)
npm run test:watch
npm run test:coverage
npm run lint # Biome + ESLint
npm run typecheck # tsc --noEmit
npm run build # tsup → dist/Releases go through Changesets: npm run changeset → npm run version
→ npm run release. prepublishOnly runs lint, typecheck, tests, and
build.
License
MIT © Gabriel Hahn Schaeffer
