@clipmux/player 0.1.0 → 0.1.2

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 CHANGED
@@ -1,177 +1,187 @@
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
+ 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.
4
4
 
5
5
  ```bash
6
6
  npm install @clipmux/player
7
7
  ```
8
8
 
9
- ## Quick Start
9
+ ## Quick Start (Public Videos)
10
+
11
+ For public videos that don't require secure signed tokens, integration is a single line:
10
12
 
11
13
  ```tsx
12
14
  import { ClipMuxPlayer } from '@clipmux/player'
15
+ import '@clipmux/player/dist/index.css' // if applicable or if styles are extracted
13
16
 
14
17
  function App() {
15
18
  return <ClipMuxPlayer playbackId="your-video-id" />
16
19
  }
17
20
  ```
18
21
 
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" />
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);
62
+ }
27
63
  ```
28
64
 
29
- The player resolves the video URL automatically from the `playbackId`.
65
+ ### Step 2: Render the Player (Your Frontend)
30
66
 
31
- ### Signed / Private Videos
67
+ Fetch the session from your backend, and pass the properties directly into `<ClipMuxPlayer>`.
32
68
 
33
69
  ```tsx
34
- <ClipMuxPlayer
35
- playbackId="abc-123"
36
- token="eyJhbGciOiJIUzI1NiIs..."
37
- />
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
+ }
38
99
  ```
39
100
 
40
- The `token` is appended to the playback URL as a query parameter for secure delivery.
101
+ By providing the `token`, the player automatically appends it to all requested resources (video segments, subtitle tracks, and thumbnails), preventing unauthorized access.
41
102
 
42
- ### Custom Source (Escape Hatch)
103
+ ---
43
104
 
44
- If you use your own CDN or proxy, pass `src` directly. Keep `playbackId` so analytics still tracks correctly:
105
+ ## Advanced Features
45
106
 
46
- ```tsx
47
- <ClipMuxPlayer
48
- playbackId="abc-123"
49
- src="https://my-cdn.example.com/videos/abc-123/playlist.m3u8"
50
- />
51
- ```
52
-
53
- ### Full Example
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.
54
109
 
55
110
  ```tsx
56
111
  <ClipMuxPlayer
57
112
  playbackId="abc-123"
58
- envKey="pk_live_xxxxxxxx"
59
- token="eyJ..."
60
- title="Product Demo"
61
- poster="https://cdn.example.com/thumb.jpg"
62
- subtitles="https://cdn.example.com/subs-en.vtt"
113
+ subtitles="https://delivery.clipmux.com/.../subs.vtt"
63
114
  chapters={[
64
- { startTime: 0, endTime: 30, title: 'Intro' },
65
- { startTime: 30, endTime: 120, title: 'Features' },
66
- { startTime: 120, endTime: 180, title: 'Pricing' },
115
+ { startTime: 0, endTime: 60, title: 'Introduction' },
116
+ { startTime: 60, endTime: 300, title: 'Main Content' },
67
117
  ]}
68
- autoPlay
69
- muted
70
- theme={{ primaryColor: '#6366f1' }}
71
- onReady={() => console.log('Player loaded')}
72
- onEnded={() => console.log('Finished')}
73
- onError={(err) => console.error('Playback error:', err)}
74
118
  />
75
119
  ```
76
120
 
77
- ## Props
78
-
79
- | Prop | Type | Default | Description |
80
- |------|------|---------|-------------|
81
- | `playbackId` | `string` | — | ClipMux video ID. Resolves to the HLS URL automatically. |
82
- | `src` | `string` | — | Direct HLS/DASH URL. Overrides `playbackId` for playback. |
83
- | `envKey` | `string` | — | Tenant/environment key for multi-tenant analytics. |
84
- | `token` | `string` | — | Signed playback token for private content. |
85
- | `title` | `string` | — | Video title displayed in the player UI. |
86
- | `poster` | `string` | — | Poster/thumbnail image URL. |
87
- | `subtitles` | `string` | — | VTT subtitle file URL. |
88
- | `chapters` | `Chapter[]` | — | Chapter markers (converted to VTT internally). |
89
- | `autoPlay` | `boolean` | `false` | Auto-play on load. |
90
- | `muted` | `boolean` | `false` | Start muted. |
91
- | `theme` | `object` | — | `{ primaryColor?, accentColor? }` — customize player colors. |
92
- | `className` | `string` | — | Additional CSS class on the player container. |
93
- | `style` | `CSSProperties` | — | Inline styles on the player container. |
94
- | `analyticsEndpoint` | `string \| false` | Production URL | Override the analytics beacon URL. Set to `false` to disable. |
95
- | `onReady` | `() => void` | — | Fired when the player is ready to play. |
96
- | `onError` | `(err: Error) => void` | — | Fired on playback error. |
97
- | `onEnded` | `() => void` | — | Fired when the video finishes. |
98
-
99
- ## Analytics
100
-
101
- The player sends playback analytics automatically:
102
-
103
- - **Events tracked**: `play`, `pause`, `seeking`, `seeked`, `ended`, `error`
104
- - **Heartbeat**: Every 10 seconds with accumulated `watchedDelta`
105
- - **Reliability**: Uses `navigator.sendBeacon` on page unload to guarantee delivery
106
- - **Session tracking**: A unique `sessionId` (UUID) is generated per player mount
107
-
108
- ### Disable Analytics
121
+ ### Theming
122
+ Customize the player to match your brand. `primaryColor` updates the timeline scrubber and main buttons.
109
123
 
110
124
  ```tsx
111
- <ClipMuxPlayer playbackId="abc-123" analyticsEndpoint={false} />
125
+ <ClipMuxPlayer
126
+ // ...
127
+ theme={{
128
+ primaryColor: '#6366f1', // Indigo
129
+ accentColor: '#f59e0b', // Amber
130
+ }}
131
+ />
112
132
  ```
113
133
 
114
- ### Custom Analytics Endpoint
134
+ ### Analytics
135
+ The player securely tracks real-time analytics (heartbeat, play/pause, seek, watch time) out of the box.
115
136
 
137
+ If you are using environments or multiple tenants, you can differentiate metrics by passing an environment key:
116
138
  ```tsx
117
- <ClipMuxPlayer
118
- playbackId="abc-123"
119
- analyticsEndpoint="https://your-proxy.example.com/v1/beacon"
120
- />
139
+ <ClipMuxPlayer playbackId="abc-123" envKey="pk_live_xxxx" />
121
140
  ```
122
141
 
123
- The endpoint receives `POST` requests with a JSON array of events:
124
-
125
- ```json
126
- [
127
- {
128
- "event": "heartbeat",
129
- "ts": "2026-02-16T10:30:00.000Z",
130
- "videoId": "abc-123",
131
- "sessionId": "550e8400-e29b-41d4-a716-446655440000",
132
- "envKey": "pk_live_xxx",
133
- "currentTime": 45.2,
134
- "duration": 180,
135
- "watchedDelta": 10.1
136
- }
137
- ]
142
+ To entirely disable analytics:
143
+ ```tsx
144
+ <ClipMuxPlayer playbackId="abc-123" analyticsEndpoint={false} />
138
145
  ```
139
146
 
140
- ## Theming
141
-
142
- Customize the player accent color using the `theme` prop:
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.
143
149
 
144
150
  ```tsx
145
151
  <ClipMuxPlayer
146
152
  playbackId="abc-123"
147
- theme={{
148
- primaryColor: '#6366f1', // Indigo
149
- accentColor: '#f59e0b', // Amber
150
- }}
153
+ src="https://my-custom-cdn.com/videos/abc-123/playlist.m3u8"
151
154
  />
152
155
  ```
153
156
 
154
- `primaryColor` maps to the Vidstack `--video-brand` CSS variable. You can also override styles via the `.clipmux-player` CSS class.
157
+ ---
155
158
 
156
- ## Chapters
159
+ ## Props Reference
157
160
 
158
- Pass chapter markers as an array — they're converted to WebVTT internally:
159
-
160
- ```tsx
161
- <ClipMuxPlayer
162
- playbackId="abc-123"
163
- chapters={[
164
- { startTime: 0, endTime: 60, title: 'Introduction' },
165
- { startTime: 60, endTime: 300, title: 'Main Content' },
166
- { startTime: 300, endTime: 360, title: 'Conclusion' },
167
- ]}
168
- />
169
- ```
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. |
170
180
 
171
181
  ## Requirements
172
182
 
173
183
  - **React** ≥ 18
174
- - No other peer dependencies — Vidstack is bundled inside the package.
184
+ - No other peer dependencies — Vidstack is fully bundled inside the package to avoid version conflicts.
175
185
 
176
186
  ## License
177
187
 
package/dist/index.cjs CHANGED
@@ -7600,6 +7600,9 @@ function sortVideoQualities(qualities, desc) {
7600
7600
  function compareVideoQualityAsc(a, b) {
7601
7601
  return a.height === b.height ? (a.bitrate ?? 0) - (b.bitrate ?? 0) : a.height - b.height;
7602
7602
  }
7603
+ function isHLSProvider(provider2) {
7604
+ return provider2?.$$PROVIDER_TYPE === "HLS";
7605
+ }
7603
7606
  function isHTMLAudioElement(element) {
7604
7607
  return !IS_SERVER3 && element instanceof HTMLAudioElement;
7605
7608
  }
@@ -12009,8 +12012,8 @@ var init_vidstack_D5Pzx_k5 = __esm({
12009
12012
  canGoogleCast.set(supported);
12010
12013
  }
12011
12014
  #watchFullscreenSupport() {
12012
- const { canFullscreen } = this.$state, supported = this.#fullscreen.supported || !!this.#$provider()?.fullscreen?.supported;
12013
- canFullscreen.set(supported);
12015
+ const { canFullscreen: canFullscreen2 } = this.$state, supported = this.#fullscreen.supported || !!this.#$provider()?.fullscreen?.supported;
12016
+ canFullscreen2.set(supported);
12014
12017
  }
12015
12018
  #watchPiPSupport() {
12016
12019
  const { canPictureInPicture } = this.$state, supported = !!this.#$provider()?.pictureInPicture?.supported;
@@ -14788,8 +14791,8 @@ var init_vidstack_D5Pzx_k5 = __esm({
14788
14791
  return fullscreen();
14789
14792
  }
14790
14793
  #isSupported() {
14791
- const { canFullscreen } = this.#media.$state;
14792
- return canFullscreen();
14794
+ const { canFullscreen: canFullscreen2 } = this.#media.$state;
14795
+ return canFullscreen2();
14793
14796
  }
14794
14797
  };
14795
14798
  MuteButton = class extends Component {
@@ -18162,6 +18165,7 @@ var init_vidstack_D5Pzx_k5 = __esm({
18162
18165
 
18163
18166
  // node_modules/.pnpm/@vidstack+react@1.12.13_@types+react@19.2.14_react@19.2.4/node_modules/@vidstack/react/prod/vidstack.js
18164
18167
  init_vidstack_D5Pzx_k5();
18168
+ init_vidstack_D5Pzx_k5();
18165
18169
  init_vidstack_CZgUA94N();
18166
18170
 
18167
18171
  // node_modules/.pnpm/@vidstack+react@1.12.13_@types+react@19.2.14_react@19.2.4/node_modules/@vidstack/react/prod/chunks/vidstack-DqtDbuaC.js
@@ -20886,12 +20890,14 @@ styleInject('[data-media-player] {\n width: 100%;\n display: inline-flex;\n a
20886
20890
  styleInject(".clipmux-player[data-view-type=video] {\n aspect-ratio: 16 / 9;\n}\n.clipmux-player .vds-video-layout {\n --video-brand: hsl(0, 0%, 96%);\n}\n");
20887
20891
  var DEFAULT_ANALYTICS_URL = "https://api.clipmux.com/api/playback/journal";
20888
20892
  var CDN_BASE = "https://delivery.clipmux.com/videos";
20893
+ function withToken(url, token) {
20894
+ if (!token || /(?:\?|&)token=/.test(url) || url.startsWith("data:") || url.startsWith("blob:")) return url;
20895
+ const separator = url.includes("?") ? "&" : "?";
20896
+ return `${url}${separator}token=${encodeURIComponent(token)}`;
20897
+ }
20889
20898
  function resolveSourceUrl(props) {
20890
- let url = props.src || `${CDN_BASE}/${props.playbackId}/playlist.m3u8`;
20891
- if (props.token && !url.includes("token=")) {
20892
- url += `${url.includes("?") ? "&" : "?"}token=${props.token}`;
20893
- }
20894
- return url;
20899
+ const url = props.src || `${CDN_BASE}/${props.playbackId}/playlist.m3u8`;
20900
+ return withToken(url, props.token);
20895
20901
  }
20896
20902
  function chaptersToVttUrl(chapters) {
20897
20903
  let vtt = "WEBVTT\n\n";
@@ -21102,6 +21108,14 @@ function ClipMuxPlayer({
21102
21108
  if (!chapters || chapters.length === 0) return null;
21103
21109
  return chaptersToVttUrl(chapters);
21104
21110
  }, [chapters]);
21111
+ const posterSrc = React8__namespace.useMemo(() => {
21112
+ if (!poster) return void 0;
21113
+ return withToken(poster, token);
21114
+ }, [poster, token]);
21115
+ const subtitlesSrc = React8__namespace.useMemo(() => {
21116
+ if (!subtitles) return void 0;
21117
+ return withToken(subtitles, token);
21118
+ }, [subtitles, token]);
21105
21119
  const mergedStyle = React8__namespace.useMemo(() => {
21106
21120
  const vars = {};
21107
21121
  if (theme?.primaryColor) vars["--video-brand"] = theme.primaryColor;
@@ -21131,6 +21145,15 @@ function ClipMuxPlayer({
21131
21145
  analytics.onError(e2?.message || "unknown");
21132
21146
  onError?.(new Error(e2?.message || "Playback error"));
21133
21147
  },
21148
+ onProviderChange: (provider2) => {
21149
+ if (isHLSProvider(provider2)) {
21150
+ provider2.config = {
21151
+ ...provider2.config,
21152
+ maxBufferLength: 30,
21153
+ maxMaxBufferLength: 30
21154
+ };
21155
+ }
21156
+ },
21134
21157
  onTimeUpdate: (detail) => {
21135
21158
  if (playerStateRef.current) {
21136
21159
  playerStateRef.current.currentTime = detail.currentTime;
@@ -21151,14 +21174,14 @@ function ClipMuxPlayer({
21151
21174
  Poster2,
21152
21175
  {
21153
21176
  className: "vds-poster absolute inset-0 block h-full w-full object-cover opacity-0 transition-opacity data-[visible]:opacity-100",
21154
- src: poster,
21177
+ src: posterSrc,
21155
21178
  alt: title || "Video poster"
21156
21179
  }
21157
21180
  ),
21158
- subtitles && /* @__PURE__ */ jsxRuntime.jsx(
21181
+ subtitlesSrc && /* @__PURE__ */ jsxRuntime.jsx(
21159
21182
  Track3,
21160
21183
  {
21161
- src: subtitles,
21184
+ src: subtitlesSrc,
21162
21185
  kind: "subtitles",
21163
21186
  label: "English",
21164
21187
  lang: "en",
@@ -21179,7 +21202,7 @@ function ClipMuxPlayer({
21179
21202
  /* @__PURE__ */ jsxRuntime.jsx(
21180
21203
  DefaultVideoLayout,
21181
21204
  {
21182
- thumbnails: poster,
21205
+ thumbnails: posterSrc,
21183
21206
  icons: defaultLayoutIcons,
21184
21207
  menuGroup: "bottom",
21185
21208
  smallLayoutWhen: ({ width }) => width < 520