@clipmux/player 0.1.2 → 0.6.1

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,171 @@
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
+ The docs: [Add the player](https://clipmux.com/docs/build/play/player) and the [reference](https://clipmux.com/docs/reference/sdks/player).
4
4
 
5
- ```bash
6
- npm install @clipmux/player
7
- ```
8
-
9
- ## Quick Start (Public Videos)
10
-
11
- For public videos that don't require secure signed tokens, integration is a single line:
5
+ Plays ClipMux videos with Video.js 10 and refreshes expired playback tokens
6
+ without losing the viewer's place.
12
7
 
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" />
19
- }
8
+ ```html
9
+ <script type="module">import '@clipmux/player/element'</script>
10
+ <clipmux-player playback-id="pid_…" session-url="/api/clipmux/playback"></clipmux-player>
20
11
  ```
21
12
 
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);
13
+ With `session-url` the page needs only the playback ID: the element POSTs
14
+ `{"playback_id": "pid_…", "native": false}` to your backend, which checks the
15
+ viewer and answers with the playback session, the same shape as ClipMux's
16
+ `POST /s/{secret}/playback`:
17
+
18
+ ```json
19
+ {
20
+ "playback_id": "pid_…",
21
+ "base_url": "https://media.example.net",
22
+ "token": "eyJ…",
23
+ "expires_at": "…",
24
+ "poster_url": "https://media.example.net/v/eyJ…(poster-only token)/pid_…/poster.jpg",
25
+ "title": "Lesson 42",
26
+ "duration_seconds": 612.4,
27
+ "tracks": [{ "id": "trk_…", "kind": "chapters", "status": "ready" }]
62
28
  }
63
29
  ```
64
30
 
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
- );
31
+ The `@clipmux/node` handler's `/playback` route answers exactly this, and its
32
+ `PlaybackSession` type is assignable to this package's. The
33
+ element plays from `base_url` with `token`, shows `poster_url` unless you set
34
+ `poster`, marks the first ready chapters track unless you set
35
+ `chapters-track`, and asks the same URL again whenever the token expires. A
36
+ `401` or `403` from it fires `clipmux-denied`; any other failure,
37
+ `clipmux-error` with its `status`. `native` is `true` when the browser will
38
+ play HLS itself (no MediaSource), where tokens can't be refreshed, so the
39
+ backend signs one that outlives the session. A `getToken` you set as well wins
40
+ for refreshes; `player.session` holds the answer in use.
41
+
42
+ Or bring your own token. The element asks `getToken` for the first token and
43
+ for every refresh, saying which playback ID and whether the browser plays HLS
44
+ natively:
45
+
46
+ ```ts
47
+ import '@clipmux/player/element'
48
+
49
+ const player = document.querySelector('clipmux-player')!
50
+ player.getToken = async ({ playbackId, native }) => {
51
+ const res = await fetch(`/api/playback-token?playback_id=${playbackId}&native=${native}`)
52
+ return res.ok ? res.text() : null // null denies
98
53
  }
99
54
  ```
100
55
 
101
- By providing the `token`, the player automatically appends it to all requested resources (video segments, subtitle tracks, and thumbnails), preventing unauthorized access.
56
+ ```html
57
+ <clipmux-player base-url="https://media.example.net" playback-id="pid_…"></clipmux-player>
58
+ ```
102
59
 
103
- ---
60
+ How refresh works: tokens ride in the URL path, so on a `401 token_expired` the
61
+ player calls `getToken({ playbackId, native })` once, puts the new token into that request and every
62
+ later one, and retries; hls.js never sees the error. `null` (or a `403` from
63
+ delivery) stops playback and fires `clipmux-denied`. A playback ID that was
64
+ revoked or never existed is a `404` from delivery: `clipmux-error` with
65
+ `status: 404`, which an app shows as "this video was removed".
66
+
67
+ **Native HLS can't refresh.** Where the browser plays HLS itself (iOS before
68
+ 17.1, AirPlay, Chromecast), the token must outlive the session: sign it for the
69
+ larger of 2 × the video's duration or 4 hours. The element tells your backend
70
+ (`native` in the `session-url` POST, or `getToken`'s argument), and
71
+ `@clipmux/node` signs for it: `playback.token(id, { native, durationSeconds })`.
72
+ iOS 17.1+ plays through hls.js (ManagedMediaSource) and refreshes.
73
+
74
+ For another player, `rewriteTokenUrl`, `TokenSession` and `createRefreshLoader`
75
+ (an hls.js `loader`) are exported without the UI.
76
+
77
+ ## Events and types
78
+
79
+ | Event | `detail` |
80
+ | ------------------ | --------------------------------------------------------------------------------------------------------- |
81
+ | `clipmux-token` | `{ token }`: a fresh token is in use |
82
+ | `clipmux-denied` | `{}`: the app said no (`null`, `401`/`403` from `session-url`) or delivery answered `403`; playback stops |
83
+ | `clipmux-error` | `{ status, track? }`: `0` for a network or media error |
84
+ | `clipmux-chapters` | `{ chapters }`, in seconds |
85
+
86
+ They bubble and are typed on `HTMLElementEventMap`, so
87
+ `player.addEventListener('clipmux-chapters', (e) => e.detail.chapters)` needs
88
+ no cast. For React (18 or 19), import the JSX types once; they type the attributes,
89
+ the `token`/`getToken`/`hls` properties and `onclipmux-*` handlers, and add no
90
+ React dependency:
91
+
92
+ ```ts
93
+ import type {} from '@clipmux/player/react'
94
+
95
+ <clipmux-player playback-id={pid} session-url="/api/clipmux/playback" onclipmux-denied={() => setDenied(true)} />
96
+ ```
104
97
 
105
- ## Advanced Features
98
+ ## Subtitles and chapters
106
99
 
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.
100
+ Subtitles listed in the master playlist show in the player's captions menu;
101
+ hls.js loads their playlist and VTT through the same refresh loader as the
102
+ video, so a refreshed token keeps them loading. Chapters are never listed in
103
+ the master: name the asset's ready chapters track and the player fetches its
104
+ VTT with the playback token and divides the seek bar into segments. Hover
105
+ or scrub to preview a chapter title and timestamp. A refreshed playback
106
+ session can update the chapters while the video keeps playing.
109
107
 
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
- />
108
+ ```html
109
+ <clipmux-player base-url="…" playback-id="pid_…" chapters-track="trk_…"></clipmux-player>
119
110
  ```
120
111
 
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
- ```
112
+ `player.chapters` holds them in seconds (`PlayerChapter`) once
113
+ `clipmux-chapters` fires. (`@clipmux/node`'s `Chapter` is the API's, in
114
+ milliseconds.) For
115
+ another player, `trackUrl` gives a track's sidecar VTT URL, `fetchTrack` loads
116
+ it with a `TokenSession`, and `parseChapters` reads a chapters VTT.
133
117
 
134
- ### Analytics
135
- The player securely tracks real-time analytics (heartbeat, play/pause, seek, watch time) out of the box.
118
+ ## Your backend: signing playback tokens
136
119
 
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
- ```
120
+ The player never sees a key. Your backend signs a short-lived ES256 JWT with
121
+ the app's signing key (Dashboard → Apps, or `clipmux admin create-signing-key`)
122
+ for each viewer it allows, and `getToken` fetches it. With `@clipmux/node`:
141
123
 
142
- To entirely disable analytics:
143
- ```tsx
144
- <ClipMuxPlayer playbackId="abc-123" analyticsEndpoint={false} />
124
+ ```ts
125
+ const token = await clipmux.playback.token(playbackId, { native, viewerId: user.id })
145
126
  ```
146
127
 
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.
128
+ Or with [`jose`](https://github.com/panva/jose), in any JavaScript runtime:
129
+
130
+ ```ts
131
+ import { SignJWT, importPKCS8 } from 'jose'
149
132
 
150
- ```tsx
151
- <ClipMuxPlayer
152
- playbackId="abc-123"
153
- src="https://my-custom-cdn.com/videos/abc-123/playlist.m3u8"
154
- />
133
+ const key = await importPKCS8(process.env.CLIPMUX_SIGNING_KEY!, 'ES256') // the PEM
134
+ const kid = process.env.CLIPMUX_SIGNING_KID! // kid_…
135
+
136
+ // GET /api/playback-token?playback_id=…, after your own access check
137
+ export async function playbackToken(playbackId: string): Promise<string> {
138
+ return new SignJWT({})
139
+ .setProtectedHeader({ alg: 'ES256', kid })
140
+ .setSubject(playbackId) // sub: the playback ID
141
+ .setAudience('v') // v: playback; t: the poster
142
+ .setIssuedAt()
143
+ .setExpirationTime('10m') // the player refreshes it
144
+ .sign(key)
145
+ }
155
146
  ```
156
147
 
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
148
+ A public playback ID needs no token: set `playback-id` and leave `getToken`
149
+ unset. The full contract, including posters and the maximum lifetime, is the
150
+ [delivery reference](https://clipmux.com/docs/reference/api/delivery).
151
+
152
+ ## TypeScript
153
+
154
+ The element's types come with the package. Video.js 10.2's own declaration
155
+ files don't all type-check, so keep `"skipLibCheck": true` (the default in
156
+ most templates) in a project that imports the element.
157
+
158
+ ## Content-Security-Policy
159
+
160
+ A page with the player must allow, besides its own origin:
161
+ - `connect-src` and `media-src`: the media origin (`base_url`), and `blob:`
162
+ in `media-src` for Media Source playback;
163
+ - `img-src`: the media origin, for the poster;
164
+ - `style-src 'unsafe-inline'`: Video.js injects its skin's styles.
165
+
166
+ `npx @clipmux/node doctor` prints the exact origins. hls.js runs on the main
167
+ thread, so no `worker-src` is needed.
168
+
169
+ ## Licence
170
+
171
+ 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 {};