@clipmux/player 0.1.1 → 0.6.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Vishesh Gubrani and the ClipMux contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,179 +1,167 @@
1
1
  # @clipmux/player
2
2
 
3
- A drop-in React video player with built-in analytics, theming, and HLS support. Powered by [Vidstack](https://vidstack.io) — batteries included.
3
+ Plays ClipMux videos with Video.js 10 and refreshes expired playback tokens
4
+ without losing the viewer's place.
4
5
 
5
- ```bash
6
- npm install @clipmux/player
6
+ ```html
7
+ <script type="module">import '@clipmux/player/element'</script>
8
+ <clipmux-player playback-id="pid_…" session-url="/api/clipmux/playback"></clipmux-player>
7
9
  ```
8
10
 
9
- ## Quick Start
11
+ With `session-url` the page needs only the playback ID: the element POSTs
12
+ `{"playback_id": "pid_…", "native": false}` to your backend, which checks the
13
+ viewer and answers with the playback session, the same shape as ClipMux's
14
+ `POST /s/{secret}/playback`:
10
15
 
11
- ```tsx
12
- import { ClipMuxPlayer } from '@clipmux/player'
13
-
14
- function App() {
15
- return <ClipMuxPlayer playbackId="your-video-id" />
16
+ ```json
17
+ {
18
+ "playback_id": "pid_…",
19
+ "base_url": "https://media.example.net",
20
+ "token": "eyJ…",
21
+ "expires_at": "…",
22
+ "poster_url": "https://media.example.net/v/eyJ…(poster-only token)/pid_…/poster.jpg",
23
+ "title": "Lesson 42",
24
+ "duration_seconds": 612.4,
25
+ "tracks": [{ "id": "trk_…", "kind": "chapters", "status": "ready" }]
16
26
  }
17
27
  ```
18
28
 
19
- That's it. No CSS imports, no extra dependencies — it just works.
20
-
21
- ## Usage
22
-
23
- ### Basic Playback
24
-
25
- ```tsx
26
- <ClipMuxPlayer playbackId="abc-123" />
29
+ The `@clipmux/node` handler's `/playback` route answers exactly this, and its
30
+ `PlaybackSession` type is assignable to this package's. The
31
+ element plays from `base_url` with `token`, shows `poster_url` unless you set
32
+ `poster`, marks the first ready chapters track unless you set
33
+ `chapters-track`, and asks the same URL again whenever the token expires. A
34
+ `401` or `403` from it fires `clipmux-denied`; any other failure,
35
+ `clipmux-error` with its `status`. `native` is `true` when the browser will
36
+ play HLS itself (no MediaSource), where tokens can't be refreshed, so the
37
+ backend signs one that outlives the session. A `getToken` you set as well wins
38
+ for refreshes; `player.session` holds the answer in use.
39
+
40
+ Or bring your own token. The element asks `getToken` for the first token and
41
+ for every refresh, saying which playback ID and whether the browser plays HLS
42
+ natively:
43
+
44
+ ```ts
45
+ import '@clipmux/player/element'
46
+
47
+ const player = document.querySelector('clipmux-player')!
48
+ player.getToken = async ({ playbackId, native }) => {
49
+ const res = await fetch(`/api/playback-token?playback_id=${playbackId}&native=${native}`)
50
+ return res.ok ? res.text() : null // null denies
51
+ }
27
52
  ```
28
53
 
29
- The player resolves the video URL automatically from the `playbackId`.
30
-
31
- ### Signed / Private Videos
32
-
33
- ```tsx
34
- <ClipMuxPlayer
35
- playbackId="abc-123"
36
- token="eyJhbGciOiJIUzI1NiIs..."
37
- />
54
+ ```html
55
+ <clipmux-player base-url="https://media.example.net" playback-id="pid_…"></clipmux-player>
38
56
  ```
39
57
 
40
- The `token` is appended to the playback URL as a query parameter for secure delivery.
41
- When provided, the same token is also appended to `subtitles` and `poster` URLs (if set).
58
+ How refresh works: tokens ride in the URL path, so on a `401 token_expired` the
59
+ player calls `getToken({ playbackId, native })` once, puts the new token into that request and every
60
+ later one, and retries; hls.js never sees the error. `null` (or a `403` from
61
+ delivery) stops playback and fires `clipmux-denied`. A playback ID that was
62
+ revoked or never existed is a `404` from delivery: `clipmux-error` with
63
+ `status: 404`, which an app shows as "this video was removed".
64
+
65
+ **Native HLS can't refresh.** Where the browser plays HLS itself (iOS before
66
+ 17.1, AirPlay, Chromecast), the token must outlive the session: sign it for the
67
+ larger of 2 × the video's duration or 4 hours. The element tells your backend
68
+ (`native` in the `session-url` POST, or `getToken`'s argument), and
69
+ `@clipmux/node` signs for it: `playback.token(id, { native, durationSeconds })`.
70
+ iOS 17.1+ plays through hls.js (ManagedMediaSource) and refreshes.
71
+
72
+ For another player, `rewriteTokenUrl`, `TokenSession` and `createRefreshLoader`
73
+ (an hls.js `loader`) are exported without the UI.
74
+
75
+ ## Events and types
76
+
77
+ | Event | `detail` |
78
+ | ------------------ | --------------------------------------------------------------------------------------------------------- |
79
+ | `clipmux-token` | `{ token }`: a fresh token is in use |
80
+ | `clipmux-denied` | `{}`: the app said no (`null`, `401`/`403` from `session-url`) or delivery answered `403`; playback stops |
81
+ | `clipmux-error` | `{ status, track? }`: `0` for a network or media error |
82
+ | `clipmux-chapters` | `{ chapters }`, in seconds |
83
+
84
+ They bubble and are typed on `HTMLElementEventMap`, so
85
+ `player.addEventListener('clipmux-chapters', (e) => e.detail.chapters)` needs
86
+ no cast. For React (18 or 19), import the JSX types once; they type the attributes,
87
+ the `token`/`getToken`/`hls` properties and `onclipmux-*` handlers, and add no
88
+ React dependency:
89
+
90
+ ```ts
91
+ import type {} from '@clipmux/player/react'
92
+
93
+ <clipmux-player playback-id={pid} session-url="/api/clipmux/playback" onclipmux-denied={() => setDenied(true)} />
94
+ ```
42
95
 
43
- ### Custom Source (Escape Hatch)
96
+ ## Subtitles and chapters
44
97
 
45
- If you use your own CDN or proxy, pass `src` directly. Keep `playbackId` so analytics still tracks correctly:
98
+ Subtitles listed in the master playlist show in the player's captions menu;
99
+ hls.js loads their playlist and VTT through the same refresh loader as the
100
+ video, so a refreshed token keeps them loading. Chapters are never listed in
101
+ the master: name the asset's ready chapters track and the player fetches its
102
+ VTT with the playback token and marks the chapters on the time slider.
46
103
 
47
- ```tsx
48
- <ClipMuxPlayer
49
- playbackId="abc-123"
50
- src="https://my-cdn.example.com/videos/abc-123/playlist.m3u8"
51
- />
104
+ ```html
105
+ <clipmux-player base-url="…" playback-id="pid_…" chapters-track="trk_…"></clipmux-player>
52
106
  ```
53
107
 
54
- ### Full Example
55
-
56
- ```tsx
57
- <ClipMuxPlayer
58
- playbackId="abc-123"
59
- envKey="pk_live_xxxxxxxx"
60
- token="eyJ..."
61
- title="Product Demo"
62
- poster="https://cdn.example.com/thumb.jpg"
63
- subtitles="https://cdn.example.com/subs-en.vtt"
64
- chapters={[
65
- { startTime: 0, endTime: 30, title: 'Intro' },
66
- { startTime: 30, endTime: 120, title: 'Features' },
67
- { startTime: 120, endTime: 180, title: 'Pricing' },
68
- ]}
69
- autoPlay
70
- muted
71
- theme={{ primaryColor: '#6366f1' }}
72
- onReady={() => console.log('Player loaded')}
73
- onEnded={() => console.log('Finished')}
74
- onError={(err) => console.error('Playback error:', err)}
75
- />
76
- ```
108
+ `player.chapters` holds them in seconds (`PlayerChapter`) once
109
+ `clipmux-chapters` fires. (`@clipmux/node`'s `Chapter` is the API's, in
110
+ milliseconds.) For
111
+ another player, `trackUrl` gives a track's sidecar VTT URL, `fetchTrack` loads
112
+ it with a `TokenSession`, and `parseChapters` reads a chapters VTT.
77
113
 
78
- ## Props
79
-
80
- | Prop | Type | Default | Description |
81
- |------|------|---------|-------------|
82
- | `playbackId` | `string` | — | ClipMux video ID. Resolves to the HLS URL automatically. |
83
- | `src` | `string` | — | Direct HLS/DASH URL. Overrides `playbackId` for playback. |
84
- | `envKey` | `string` | — | Tenant/environment key for multi-tenant analytics. |
85
- | `token` | `string` | — | Signed playback token for private content (auto-appended to playback, subtitles, and poster URLs). |
86
- | `title` | `string` | — | Video title displayed in the player UI. |
87
- | `poster` | `string` | — | Poster/thumbnail image URL. |
88
- | `subtitles` | `string` | — | VTT subtitle file URL. |
89
- | `chapters` | `Chapter[]` | — | Chapter markers (converted to VTT internally). |
90
- | `autoPlay` | `boolean` | `false` | Auto-play on load. |
91
- | `muted` | `boolean` | `false` | Start muted. |
92
- | `theme` | `object` | — | `{ primaryColor?, accentColor? }` — customize player colors. |
93
- | `className` | `string` | — | Additional CSS class on the player container. |
94
- | `style` | `CSSProperties` | — | Inline styles on the player container. |
95
- | `analyticsEndpoint` | `string \| false` | Production URL | Override the analytics beacon URL. Set to `false` to disable. |
96
- | `onReady` | `() => void` | — | Fired when the player is ready to play. |
97
- | `onError` | `(err: Error) => void` | — | Fired on playback error. |
98
- | `onEnded` | `() => void` | — | Fired when the video finishes. |
99
-
100
- ## Analytics
101
-
102
- The player sends playback analytics automatically:
103
-
104
- - **Events tracked**: `play`, `pause`, `seeking`, `seeked`, `ended`, `error`
105
- - **Heartbeat**: Every 10 seconds with accumulated `watchedDelta`
106
- - **Reliability**: Uses `navigator.sendBeacon` on page unload to guarantee delivery
107
- - **Session tracking**: A unique `sessionId` (UUID) is generated per player mount
108
-
109
- ### Disable Analytics
110
-
111
- ```tsx
112
- <ClipMuxPlayer playbackId="abc-123" analyticsEndpoint={false} />
113
- ```
114
+ ## Your backend: signing playback tokens
114
115
 
115
- ### Custom Analytics Endpoint
116
+ The player never sees a key. Your backend signs a short-lived ES256 JWT with
117
+ the app's signing key (Dashboard → Apps, or `clipmux admin create-signing-key`)
118
+ for each viewer it allows, and `getToken` fetches it. With `@clipmux/node`:
116
119
 
117
- ```tsx
118
- <ClipMuxPlayer
119
- playbackId="abc-123"
120
- analyticsEndpoint="https://your-proxy.example.com/v1/beacon"
121
- />
120
+ ```ts
121
+ const token = await clipmux.playback.token(playbackId, { native, viewerId: user.id })
122
122
  ```
123
123
 
124
- The endpoint receives `POST` requests with a JSON array of events:
125
-
126
- ```json
127
- [
128
- {
129
- "event": "heartbeat",
130
- "ts": "2026-02-16T10:30:00.000Z",
131
- "videoId": "abc-123",
132
- "sessionId": "550e8400-e29b-41d4-a716-446655440000",
133
- "envKey": "pk_live_xxx",
134
- "currentTime": 45.2,
135
- "duration": 180,
136
- "watchedDelta": 10.1
137
- }
138
- ]
139
- ```
124
+ Or with [`jose`](https://github.com/panva/jose), in any JavaScript runtime:
140
125
 
141
- ## Theming
126
+ ```ts
127
+ import { SignJWT, importPKCS8 } from 'jose'
142
128
 
143
- Customize the player accent color using the `theme` prop:
129
+ const key = await importPKCS8(process.env.CLIPMUX_SIGNING_KEY!, 'ES256') // the PEM
130
+ const kid = process.env.CLIPMUX_SIGNING_KID! // kid_…
144
131
 
145
- ```tsx
146
- <ClipMuxPlayer
147
- playbackId="abc-123"
148
- theme={{
149
- primaryColor: '#6366f1', // Indigo
150
- accentColor: '#f59e0b', // Amber
151
- }}
152
- />
132
+ // GET /api/playback-token?playback_id=…, after your own access check
133
+ export async function playbackToken(playbackId: string): Promise<string> {
134
+ return new SignJWT({})
135
+ .setProtectedHeader({ alg: 'ES256', kid })
136
+ .setSubject(playbackId) // sub: the playback ID
137
+ .setAudience('v') // v: playback; t: the poster
138
+ .setIssuedAt()
139
+ .setExpirationTime('10m') // the player refreshes it
140
+ .sign(key)
141
+ }
153
142
  ```
154
143
 
155
- `primaryColor` maps to the Vidstack `--video-brand` CSS variable. You can also override styles via the `.clipmux-player` CSS class.
144
+ A public playback ID needs no token: set `playback-id` and leave `getToken`
145
+ unset. The full contract, including posters and the maximum lifetime, is the
146
+ Delivery section of [docs/api.md](https://github.com/visheshgubrani/clipmux/blob/main/docs/api.md#delivery).
156
147
 
157
- ## Chapters
148
+ ## TypeScript
158
149
 
159
- Pass chapter markers as an array — they're converted to WebVTT internally:
150
+ The element's types come with the package. Video.js 10.2's own declaration
151
+ files don't all type-check, so keep `"skipLibCheck": true` (the default in
152
+ most templates) in a project that imports the element.
160
153
 
161
- ```tsx
162
- <ClipMuxPlayer
163
- playbackId="abc-123"
164
- chapters={[
165
- { startTime: 0, endTime: 60, title: 'Introduction' },
166
- { startTime: 60, endTime: 300, title: 'Main Content' },
167
- { startTime: 300, endTime: 360, title: 'Conclusion' },
168
- ]}
169
- />
170
- ```
154
+ ## Content-Security-Policy
171
155
 
172
- ## Requirements
156
+ A page with the player must allow, besides its own origin:
157
+ - `connect-src` and `media-src`: the media origin (`base_url`), and `blob:`
158
+ in `media-src` for Media Source playback;
159
+ - `img-src`: the media origin, for the poster;
160
+ - `style-src 'unsafe-inline'`: Video.js injects its skin's styles.
173
161
 
174
- - **React** ≥ 18
175
- - No other peer dependencies — Vidstack is bundled inside the package.
162
+ `npx @clipmux/node doctor` prints the exact origins. hls.js runs on the main
163
+ thread, so no `worker-src` is needed.
176
164
 
177
- ## License
165
+ ## Licence
178
166
 
179
- MIT
167
+ MIT. The ClipMux server is AGPL-3.0; this package is MIT so apps embed it freely.
@@ -0,0 +1,90 @@
1
+ import '@videojs/html/video/player';
2
+ import '@videojs/html/video/skin';
3
+ import '@videojs/html/media/hlsjs-video';
4
+ import { type GetToken } from './refresh.ts';
5
+ import { type PlaybackSession } from './session.ts';
6
+ import { type PlayerChapter } from './tracks.ts';
7
+ interface MediaElement extends HTMLVideoElement {
8
+ source: unknown;
9
+ /** The <video> it plays in. */
10
+ target?: HTMLVideoElement | null;
11
+ engine: {
12
+ on(event: string, fn: (event: string, data: {
13
+ response?: {
14
+ code?: number;
15
+ };
16
+ }) => void): void;
17
+ } | null;
18
+ }
19
+ export interface ClipMuxTokenDetail {
20
+ token: string;
21
+ }
22
+ export interface ClipMuxErrorDetail {
23
+ /** The HTTP status that failed, or 0 for a network or media error. */
24
+ status: number;
25
+ /** Set when a track's VTT failed to load. */
26
+ track?: string;
27
+ }
28
+ export interface ClipMuxChaptersDetail {
29
+ chapters: PlayerChapter[];
30
+ }
31
+ export type ClipMuxTokenEvent = CustomEvent<ClipMuxTokenDetail>;
32
+ export type ClipMuxDeniedEvent = CustomEvent<Record<string, never>>;
33
+ export type ClipMuxErrorEvent = CustomEvent<ClipMuxErrorDetail>;
34
+ export type ClipMuxChaptersEvent = CustomEvent<ClipMuxChaptersDetail>;
35
+ /** The events of <clipmux-player>; they bubble. */
36
+ export interface ClipMuxPlayerEventMap {
37
+ 'clipmux-token': ClipMuxTokenEvent;
38
+ 'clipmux-denied': ClipMuxDeniedEvent;
39
+ 'clipmux-error': ClipMuxErrorEvent;
40
+ 'clipmux-chapters': ClipMuxChaptersEvent;
41
+ }
42
+ /**
43
+ * The attributes and properties of <clipmux-player> for JSX, without the
44
+ * framework's own; @clipmux/player/react adds them to React's
45
+ * IntrinsicElements.
46
+ */
47
+ export interface ClipMuxPlayerProps {
48
+ 'playback-id'?: string | undefined;
49
+ 'session-url'?: string | undefined;
50
+ 'base-url'?: string | undefined;
51
+ poster?: string | undefined;
52
+ 'chapters-track'?: string | undefined;
53
+ autoplay?: boolean | undefined;
54
+ muted?: boolean | undefined;
55
+ token?: string | undefined;
56
+ getToken?: GetToken | undefined;
57
+ hls?: Record<string, unknown> | undefined;
58
+ 'onclipmux-token'?: ((event: ClipMuxTokenEvent) => void) | undefined;
59
+ 'onclipmux-denied'?: ((event: ClipMuxDeniedEvent) => void) | undefined;
60
+ 'onclipmux-error'?: ((event: ClipMuxErrorEvent) => void) | undefined;
61
+ 'onclipmux-chapters'?: ((event: ClipMuxChaptersEvent) => void) | undefined;
62
+ }
63
+ export declare class ClipMuxPlayerElement extends HTMLElement {
64
+ #private;
65
+ static observedAttributes: string[];
66
+ /** The playback token; unset for a public playback ID. */
67
+ get token(): string;
68
+ set token(t: string);
69
+ /** Called on a 401 for a fresh token; return null to stop playback. */
70
+ get getToken(): GetToken | undefined;
71
+ set getToken(fn: GetToken | undefined);
72
+ /** Extra hls.js options; set before the first load. */
73
+ set hls(options: Record<string, unknown>);
74
+ /** The session-url answer in use, once there is one. */
75
+ get session(): PlaybackSession | null;
76
+ /** The chapters of chapters-track, in seconds, once loaded. */
77
+ get chapters(): PlayerChapter[];
78
+ /** The <hlsjs-video> element, for its properties and events. */
79
+ get media(): MediaElement | null;
80
+ connectedCallback(): void;
81
+ attributeChangedCallback(): void;
82
+ }
83
+ declare global {
84
+ interface HTMLElementTagNameMap {
85
+ 'clipmux-player': ClipMuxPlayerElement;
86
+ }
87
+ interface HTMLElementEventMap extends ClipMuxPlayerEventMap {
88
+ }
89
+ }
90
+ export {};