@clipmux/player 0.1.2 → 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,188 +1,167 @@
1
1
  # @clipmux/player
2
2
 
3
- A beautiful, drop-in React video player engineered for the ClipMux video platform. Built on top of [Vidstack](https://vidstack.io) with baked-in analytics, HLS support, token-based security, chapters, and subtitles.
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 (Public Videos)
10
-
11
- For public videos that don't require secure signed tokens, integration is a single line:
12
-
13
- ```tsx
14
- import { ClipMuxPlayer } from '@clipmux/player'
15
- import '@clipmux/player/dist/index.css' // if applicable or if styles are extracted
16
-
17
- function App() {
18
- return <ClipMuxPlayer playbackId="your-video-id" />
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`:
15
+
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" }]
19
26
  }
20
27
  ```
21
28
 
22
- That's it. It automatically resolves the HLS URL and begins securely sending playback analytics.
23
-
24
- ---
25
-
26
- ## Integrating with the ClipMux API (Private/Signed Videos)
27
-
28
- For secure, private videos (the default), your application needs to authenticate the user, request a short-lived playback token from the ClipMux backend, and securely pass that to the player.
29
-
30
- ### Step 1: Request a Playback Token (Your Backend)
31
-
32
- Your backend should keep your ClipMux API key (`sk_live_...`) secret. When a user requests to watch a video, your backend calls the ClipMux API to get a temporary session.
33
-
34
- ```typescript
35
- // Example: Node.js / Next.js API Route
36
- export async function GET(request, { params }) {
37
- const videoId = params.id;
38
- const viewerIp = request.headers.get('x-forwarded-for')?.split(',')[0]?.trim();
39
- const viewerUserAgent = request.headers.get('user-agent');
40
-
41
- // 1. Verify your user has access to this video first!
42
- // ...
43
-
44
- // 2. Request a signed token from ClipMux
45
- const clipmuxRes = await fetch(`https://api.clipmux.com/v1/video/${videoId}/playback-token`, {
46
- method: 'POST',
47
- headers: {
48
- 'Authorization': `Bearer ${process.env.CLIPMUX_API_KEY}`,
49
- 'Content-Type': 'application/json'
50
- },
51
- body: JSON.stringify({
52
- expires_in: "2h",
53
- viewer_ip: viewerIp, // Bind token to real viewer IP
54
- viewer_user_agent: viewerUserAgent // Bind token to viewer User-Agent
55
- })
56
- });
57
-
58
- const session = await clipmuxRes.json();
59
-
60
- // session returns: { playback_url, token, expires_at, subtitle_url, chapters }
61
- return Response.json(session);
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
62
51
  }
63
52
  ```
64
53
 
65
- ### Step 2: Render the Player (Your Frontend)
66
-
67
- Fetch the session from your backend, and pass the properties directly into `<ClipMuxPlayer>`.
68
-
69
- ```tsx
70
- import { useState, useEffect } from 'react';
71
- import { ClipMuxPlayer } from '@clipmux/player';
72
-
73
- function LessonViewer({ videoId }) {
74
- const [session, setSession] = useState(null);
75
-
76
- useEffect(() => {
77
- // Fetch the session from YOUR backend
78
- fetch(`/api/videos/${videoId}/play`)
79
- .then(res => res.json())
80
- .then(data => setSession(data));
81
- }, [videoId]);
82
-
83
- if (!session) return <div>Loading...</div>;
84
-
85
- return (
86
- <ClipMuxPlayer
87
- playbackId={videoId}
88
- token={session.token} // Secure playback token
89
- subtitles={session.subtitle_url} // Auto-loads AI generated subtitles
90
- chapters={session.chapters} // Auto-generates chapter markers
91
-
92
- // Optional customizations
93
- title="Advanced React Patterns"
94
- autoPlay={true}
95
- theme={{ primaryColor: '#6366f1' }}
96
- />
97
- );
98
- }
54
+ ```html
55
+ <clipmux-player base-url="https://media.example.net" playback-id="pid_…"></clipmux-player>
99
56
  ```
100
57
 
101
- By providing the `token`, the player automatically appends it to all requested resources (video segments, subtitle tracks, and thumbnails), preventing unauthorized access.
102
-
103
- ---
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
+ ```
104
95
 
105
- ## Advanced Features
96
+ ## Subtitles and chapters
106
97
 
107
- ### Chapters & Subtitles
108
- ClipMux can auto-generate AI subtitles and chapters. When fetching your playback token, the API will return `subtitle_url` and `chapters`. Passing these to the player automatically renders them using native WebVTT.
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.
109
103
 
110
- ```tsx
111
- <ClipMuxPlayer
112
- playbackId="abc-123"
113
- subtitles="https://delivery.clipmux.com/.../subs.vtt"
114
- chapters={[
115
- { startTime: 0, endTime: 60, title: 'Introduction' },
116
- { startTime: 60, endTime: 300, title: 'Main Content' },
117
- ]}
118
- />
104
+ ```html
105
+ <clipmux-player base-url="…" playback-id="pid_…" chapters-track="trk_…"></clipmux-player>
119
106
  ```
120
107
 
121
- ### Theming
122
- Customize the player to match your brand. `primaryColor` updates the timeline scrubber and main buttons.
123
-
124
- ```tsx
125
- <ClipMuxPlayer
126
- // ...
127
- theme={{
128
- primaryColor: '#6366f1', // Indigo
129
- accentColor: '#f59e0b', // Amber
130
- }}
131
- />
132
- ```
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.
133
113
 
134
- ### Analytics
135
- The player securely tracks real-time analytics (heartbeat, play/pause, seek, watch time) out of the box.
114
+ ## Your backend: signing playback tokens
136
115
 
137
- If you are using environments or multiple tenants, you can differentiate metrics by passing an environment key:
138
- ```tsx
139
- <ClipMuxPlayer playbackId="abc-123" envKey="pk_live_xxxx" />
140
- ```
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`:
141
119
 
142
- To entirely disable analytics:
143
- ```tsx
144
- <ClipMuxPlayer playbackId="abc-123" analyticsEndpoint={false} />
120
+ ```ts
121
+ const token = await clipmux.playback.token(playbackId, { native, viewerId: user.id })
145
122
  ```
146
123
 
147
- ### Custom Sources (Escape Hatch)
148
- If you are proxying the video through your own CDN, provide a `src` explicitly. `playbackId` is still strongly recommended so analytics continue to log properly against the video entity.
124
+ Or with [`jose`](https://github.com/panva/jose), in any JavaScript runtime:
125
+
126
+ ```ts
127
+ import { SignJWT, importPKCS8 } from 'jose'
149
128
 
150
- ```tsx
151
- <ClipMuxPlayer
152
- playbackId="abc-123"
153
- src="https://my-custom-cdn.com/videos/abc-123/playlist.m3u8"
154
- />
129
+ const key = await importPKCS8(process.env.CLIPMUX_SIGNING_KEY!, 'ES256') // the PEM
130
+ const kid = process.env.CLIPMUX_SIGNING_KID! // kid_…
131
+
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
+ }
155
142
  ```
156
143
 
157
- ---
158
-
159
- ## Props Reference
160
-
161
- | Prop | Type | Default | Description |
162
- |------|------|---------|-------------|
163
- | `playbackId` | `string` | — | **Required.** The ClipMux video ID. Automatically resolves the secure delivery URL. |
164
- | `token` | `string` | — | Signed JWT for private content. Securely appended to video, subset, and poster requests. |
165
- | `src` | `string` | — | Direct HLS/DASH URL. Overrides the auto-resolved URL from `playbackId`. |
166
- | `envKey` | `string` | — | Tenant/environment key for multi-tenant analytics separation. |
167
- | `title` | `string` | — | Video title displayed in the player UI heading. |
168
- | `poster` | `string` | — | Custom poster/thumbnail image URL. |
169
- | `subtitles` | `string` | — | VTT subtitle file URL (AI generated or custom). |
170
- | `chapters` | `Chapter[]` | — | Array of chapter markers `{ startTime, endTime, title }`. |
171
- | `autoPlay` | `boolean` | `false` | Start playback automatically when loaded. |
172
- | `muted` | `boolean` | `false` | Start player muted. |
173
- | `theme` | `object` | — | `{ primaryColor?, accentColor? }` to customize UI colors. |
174
- | `className` | `string` | — | Additional CSS class for the player container. |
175
- | `style` | `object` | — | Inline CSS properties. |
176
- | `analyticsEndpoint` | `string \| false` | `default` | Custom analytics ingestion endpoint, or `false` to disable. |
177
- | `onReady` | `() => void` | — | Fired when the video is loaded and ready to play. |
178
- | `onError` | `(err) => void` | — | Fired on playback error. |
179
- | `onEnded` | `() => void` | — | Fired when the video naturally finishes. |
180
-
181
- ## Requirements
182
-
183
- - **React** ≥ 18
184
- - No other peer dependencies — Vidstack is fully bundled inside the package to avoid version conflicts.
185
-
186
- ## License
187
-
188
- MIT
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).
147
+
148
+ ## TypeScript
149
+
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.
153
+
154
+ ## Content-Security-Policy
155
+
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.
161
+
162
+ `npx @clipmux/node doctor` prints the exact origins. hls.js runs on the main
163
+ thread, so no `worker-src` is needed.
164
+
165
+ ## Licence
166
+
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 {};