@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/package.json CHANGED
@@ -1,51 +1,70 @@
1
1
  {
2
2
  "name": "@clipmux/player",
3
- "version": "0.1.2",
4
- "description": "ClipMux video player — drop-in React component with built-in analytics",
3
+ "version": "0.6.1",
4
+ "description": "A Video.js player for ClipMux that refreshes expired playback tokens without losing its place.",
5
+ "license": "MIT",
6
+ "keywords": [
7
+ "video",
8
+ "hls",
9
+ "player",
10
+ "videojs",
11
+ "clipmux",
12
+ "web-component",
13
+ "video-player",
14
+ "signed-playback",
15
+ "self-hosted"
16
+ ],
17
+ "homepage": "https://clipmux.com/docs/reference/sdks/player",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/visheshgubrani/clipmux.git",
21
+ "directory": "packages/player"
22
+ },
23
+ "bugs": {
24
+ "url": "https://github.com/visheshgubrani/clipmux/issues"
25
+ },
5
26
  "type": "module",
6
- "main": "./dist/index.cjs",
7
- "module": "./dist/index.js",
8
- "types": "./dist/index.d.ts",
9
27
  "exports": {
10
28
  ".": {
11
29
  "types": "./dist/index.d.ts",
12
- "import": "./dist/index.js",
13
- "require": "./dist/index.cjs"
30
+ "default": "./dist/index.js"
31
+ },
32
+ "./element": {
33
+ "types": "./dist/element.d.ts",
34
+ "default": "./dist/element.js"
35
+ },
36
+ "./react": {
37
+ "types": "./dist/react.d.ts",
38
+ "default": "./dist/react.js"
14
39
  }
15
40
  },
16
41
  "files": [
17
42
  "dist",
18
- "README.md"
43
+ "src",
44
+ "!src/**/*.test.ts"
19
45
  ],
20
46
  "scripts": {
21
- "build": "tsup",
22
- "dev": "tsup --watch",
23
- "typecheck": "tsc --noEmit"
47
+ "build": "tsc -p tsconfig.json",
48
+ "typecheck": "tsc -p tsconfig.json --noEmit",
49
+ "test": "node --test src/*.test.ts"
50
+ },
51
+ "dependencies": {
52
+ "@videojs/html": "10.2.0",
53
+ "@videojs/hlsjs-video": "10.2.0",
54
+ "hls.js": "1.6.19"
24
55
  },
25
56
  "peerDependencies": {
26
- "react": ">=18",
27
- "react-dom": ">=18"
57
+ "@types/react": ">=18"
58
+ },
59
+ "peerDependenciesMeta": {
60
+ "@types/react": {
61
+ "optional": true
62
+ }
28
63
  },
29
64
  "devDependencies": {
30
- "@types/react": "^19.0.0",
31
- "@types/react-dom": "^19.0.0",
32
- "react": "^19.0.0",
33
- "react-dom": "^19.0.0",
34
- "tsup": "^8.0.0",
35
- "typescript": "^5.0.0"
65
+ "@types/react": "19.3.0"
36
66
  },
37
- "keywords": [
38
- "video",
39
- "player",
40
- "hls",
41
- "clipmux",
42
- "vidstack",
43
- "react",
44
- "analytics",
45
- "streaming"
46
- ],
47
- "license": "MIT",
48
- "dependencies": {
49
- "@vidstack/react": "^1.12.13"
67
+ "publishConfig": {
68
+ "access": "public"
50
69
  }
51
70
  }
package/src/element.ts ADDED
@@ -0,0 +1,429 @@
1
+ // <clipmux-player base-url="…" playback-id="…">: Video.js 10's default skin
2
+ // around an hls.js-backed media element, with token refresh.
3
+ //
4
+ // import '@clipmux/player/element'
5
+ // const player = document.querySelector('clipmux-player')
6
+ // player.getToken = async ({ playbackId, native }) =>
7
+ // (await fetch(`/my/token?id=${playbackId}&native=${native}`)).text()
8
+ //
9
+ // With getToken and no token, the element asks for the first token itself;
10
+ // set token instead to start with one. autoplay and muted pass through to
11
+ // the media element.
12
+ //
13
+ // Or let the app's backend answer for it: session-url="/api/clipmux/playback"
14
+ // POSTs {playback_id, native} there for the first load and every refresh,
15
+ // and takes base_url, the token, the poster and the tracks from the answer
16
+ // (session.ts). base-url isn't needed then; a getToken set as well wins for
17
+ // refreshes.
18
+ //
19
+ // Subtitles listed in the master show in the captions menu. Chapters are a
20
+ // track the app names: chapters-track="trk_…" loads its VTT with the
21
+ // playback's token and marks the chapters on the time slider.
22
+ //
23
+ // Events: clipmux-token (a new token is in use), clipmux-denied (getToken
24
+ // returned null or delivery answered 403; playback stops), clipmux-error
25
+ // ({ status }), clipmux-chapters ({ chapters }, in seconds).
26
+ import '@videojs/html/video/player'
27
+ import '@videojs/html/video/skin'
28
+ import '@videojs/html/media/hlsjs-video'
29
+ import { type GetToken, TokenSession } from './refresh.ts'
30
+ import { chaptersTrackOf, fetchSession, type PlaybackSession, SessionError } from './session.ts'
31
+ import { clipmuxSource, playsNatively } from './source.ts'
32
+ import { fetchTrack, type PlayerChapter, parseChapters, trackUrl } from './tracks.ts'
33
+
34
+ // A generated track ends at the asset duration. HLS can report a slightly
35
+ // longer duration as it loads, which would leave a sliver on the seek bar.
36
+ const CHAPTER_END_TOLERANCE = 0.25
37
+
38
+ interface MediaElement extends HTMLVideoElement {
39
+ source: unknown
40
+ /** The <video> it plays in. */
41
+ target?: HTMLVideoElement | null
42
+ engine: {
43
+ on(event: string, fn: (event: string, data: { response?: { code?: number } }) => void): void
44
+ } | null
45
+ }
46
+
47
+ interface ChaptersRequest {
48
+ trackId: string
49
+ token: string
50
+ status: 'loading' | 'ready' | 'failed'
51
+ announced: boolean
52
+ }
53
+
54
+ export interface ClipMuxTokenDetail {
55
+ token: string
56
+ }
57
+ export interface ClipMuxErrorDetail {
58
+ /** The HTTP status that failed, or 0 for a network or media error. */
59
+ status: number
60
+ /** Set when a track's VTT failed to load. */
61
+ track?: string
62
+ }
63
+ export interface ClipMuxChaptersDetail {
64
+ chapters: PlayerChapter[]
65
+ }
66
+ export type ClipMuxTokenEvent = CustomEvent<ClipMuxTokenDetail>
67
+ export type ClipMuxDeniedEvent = CustomEvent<Record<string, never>>
68
+ export type ClipMuxErrorEvent = CustomEvent<ClipMuxErrorDetail>
69
+ export type ClipMuxChaptersEvent = CustomEvent<ClipMuxChaptersDetail>
70
+
71
+ /** The events of <clipmux-player>; they bubble. */
72
+ export interface ClipMuxPlayerEventMap {
73
+ 'clipmux-token': ClipMuxTokenEvent
74
+ 'clipmux-denied': ClipMuxDeniedEvent
75
+ 'clipmux-error': ClipMuxErrorEvent
76
+ 'clipmux-chapters': ClipMuxChaptersEvent
77
+ }
78
+
79
+ /**
80
+ * The attributes and properties of <clipmux-player> for JSX, without the
81
+ * framework's own; @clipmux/player/react adds them to React's
82
+ * IntrinsicElements.
83
+ */
84
+ export interface ClipMuxPlayerProps {
85
+ 'playback-id'?: string | undefined
86
+ 'session-url'?: string | undefined
87
+ 'base-url'?: string | undefined
88
+ poster?: string | undefined
89
+ 'chapters-track'?: string | undefined
90
+ autoplay?: boolean | undefined
91
+ muted?: boolean | undefined
92
+ token?: string | undefined
93
+ getToken?: GetToken | undefined
94
+ hls?: Record<string, unknown> | undefined
95
+ 'onclipmux-token'?: ((event: ClipMuxTokenEvent) => void) | undefined
96
+ 'onclipmux-denied'?: ((event: ClipMuxDeniedEvent) => void) | undefined
97
+ 'onclipmux-error'?: ((event: ClipMuxErrorEvent) => void) | undefined
98
+ 'onclipmux-chapters'?: ((event: ClipMuxChaptersEvent) => void) | undefined
99
+ }
100
+
101
+ export class ClipMuxPlayerElement extends HTMLElement {
102
+ static observedAttributes = [
103
+ 'base-url',
104
+ 'playback-id',
105
+ 'session-url',
106
+ 'poster',
107
+ 'autoplay',
108
+ 'muted',
109
+ 'chapters-track',
110
+ ]
111
+ #token = ''
112
+ #getToken: GetToken | undefined
113
+ #hls: Record<string, unknown> = {}
114
+ #media: MediaElement | null = null
115
+ #session: TokenSession | null = null
116
+ #loaded = ''
117
+ #fetching = false
118
+ // session-url: the answer in use, the url|playback ID it answers, and
119
+ // the one being asked for.
120
+ #playback: PlaybackSession | null = null
121
+ #playbackFor = ''
122
+ #asking: { key: string } | null = null
123
+ #chaptersRequest: ChaptersRequest | null = null
124
+ #chapters: PlayerChapter[] = []
125
+ #chaptersTrack: { video: HTMLVideoElement; track: TextTrack } | null = null
126
+
127
+ /** The playback token; unset for a public playback ID. */
128
+ get token(): string {
129
+ return this.#session?.current ?? this.#token
130
+ }
131
+ set token(t: string) {
132
+ this.#token = t
133
+ this.#load()
134
+ }
135
+
136
+ /** Called on a 401 for a fresh token; return null to stop playback. */
137
+ get getToken(): GetToken | undefined {
138
+ return this.#getToken
139
+ }
140
+ set getToken(fn: GetToken | undefined) {
141
+ this.#getToken = fn
142
+ this.#load()
143
+ }
144
+
145
+ /** Extra hls.js options; set before the first load. */
146
+ set hls(options: Record<string, unknown>) {
147
+ this.#hls = options
148
+ }
149
+
150
+ /** The session-url answer in use, once there is one. */
151
+ get session(): PlaybackSession | null {
152
+ return this.#playback
153
+ }
154
+
155
+ /** The chapters of chapters-track, in seconds, once loaded. */
156
+ get chapters(): PlayerChapter[] {
157
+ return this.#chapters
158
+ }
159
+
160
+ /** The <hlsjs-video> element, for its properties and events. */
161
+ get media(): MediaElement | null {
162
+ return this.#media
163
+ }
164
+
165
+ connectedCallback(): void {
166
+ if (!this.#media) {
167
+ this.innerHTML =
168
+ '<video-player><video-skin style="display:block;width:100%;aspect-ratio:16/9">' +
169
+ '<hlsjs-video playsinline crossorigin="anonymous"></hlsjs-video></video-skin></video-player>'
170
+ this.#media = this.querySelector('hlsjs-video') as MediaElement | null
171
+ this.#media?.addEventListener('error', () => this.#emit('clipmux-error', { status: 0 }))
172
+ this.#media?.addEventListener('loadedmetadata', () => this.#showChapters())
173
+ this.#media?.addEventListener('durationchange', () => this.#showChapters())
174
+ }
175
+ this.#load()
176
+ }
177
+
178
+ attributeChangedCallback(): void {
179
+ this.#load()
180
+ }
181
+
182
+ #emit<K extends keyof ClipMuxPlayerEventMap>(type: K, detail: ClipMuxPlayerEventMap[K]['detail']): void {
183
+ this.dispatchEvent(new CustomEvent(type, { detail, bubbles: true }))
184
+ }
185
+
186
+ // autoplay and muted reach the media element before any source does.
187
+ #flags(media: MediaElement): void {
188
+ for (const flag of ['autoplay', 'muted'] as const) {
189
+ if (this.hasAttribute(flag)) media.setAttribute(flag, '')
190
+ else media.removeAttribute(flag)
191
+ }
192
+ media.muted = this.hasAttribute('muted')
193
+ }
194
+
195
+ #load(): void {
196
+ const media = this.#media
197
+ if (media) this.#flags(media)
198
+ const sessionUrl = this.getAttribute('session-url')
199
+ if (sessionUrl) {
200
+ this.#loadSession(sessionUrl)
201
+ return
202
+ }
203
+ this.#asking = null
204
+ const baseUrl = this.getAttribute('base-url')
205
+ const playbackId = this.getAttribute('playback-id')
206
+ if (!media) return
207
+ if (!baseUrl || !playbackId) {
208
+ this.#clearChapters()
209
+ return
210
+ }
211
+ const poster = this.getAttribute('poster')
212
+ if (poster) media.poster = poster
213
+ // A signed ID needs its first token before anything loads.
214
+ if (!this.#token && this.#getToken) {
215
+ this.#clearChapters()
216
+ if (!this.#fetching) {
217
+ this.#fetching = true
218
+ this.#getToken({ playbackId, native: playsNatively() }).then(
219
+ (t) => {
220
+ this.#fetching = false
221
+ if (this.#token) return // a token was set meanwhile; it wins
222
+ if (t === null) return this.#emit('clipmux-denied', {})
223
+ this.#token = t
224
+ this.#load()
225
+ },
226
+ () => {
227
+ this.#fetching = false
228
+ this.#emit('clipmux-error', { status: 0 })
229
+ },
230
+ )
231
+ }
232
+ return
233
+ }
234
+ // Reload only when what plays changes; a refreshed token doesn't.
235
+ const loading = `${baseUrl}|${playbackId}|${this.#token}`
236
+ if (loading !== this.#loaded) this.#play(media, baseUrl, playbackId, loading)
237
+ this.#loadChapters(baseUrl, playbackId, this.getAttribute('chapters-track') ?? '')
238
+ }
239
+
240
+ // session-url: each playback ID gets its session first; then it plays
241
+ // like any other, from the session's base URL, playback ID and token.
242
+ #loadSession(sessionUrl: string): void {
243
+ const media = this.#media
244
+ const playbackId = this.getAttribute('playback-id')
245
+ if (!media) return
246
+ if (!playbackId) {
247
+ this.#asking = null
248
+ this.#clearChapters()
249
+ return
250
+ }
251
+ const key = `${sessionUrl}|${playbackId}`
252
+ if (key !== this.#playbackFor) {
253
+ if (key === this.#asking?.key) return
254
+ this.#clearChapters()
255
+ const request = { key }
256
+ this.#asking = request
257
+ fetchSession(sessionUrl, playbackId, playsNatively()).then(
258
+ (s) => {
259
+ if (request !== this.#asking) return // the playback changed meanwhile
260
+ this.#asking = null
261
+ if (s === null) return this.#emit('clipmux-denied', {})
262
+ this.#playback = s
263
+ this.#playbackFor = key
264
+ this.#token = s.token
265
+ this.#load()
266
+ },
267
+ (err: unknown) => {
268
+ if (request !== this.#asking) return
269
+ this.#asking = null
270
+ this.#emit('clipmux-error', { status: err instanceof SessionError ? err.status : 0 })
271
+ },
272
+ )
273
+ return
274
+ }
275
+ this.#asking = null
276
+ const s = this.#playback as PlaybackSession
277
+ const baseUrl = this.getAttribute('base-url') ?? s.base_url
278
+ const poster = this.getAttribute('poster') ?? s.poster_url
279
+ if (poster) media.poster = poster
280
+ const loading = `${baseUrl}|${s.playback_id}|${this.#token}`
281
+ if (loading !== this.#loaded) this.#play(media, baseUrl, s.playback_id, loading)
282
+ this.#loadChapters(baseUrl, s.playback_id, this.getAttribute('chapters-track') ?? chaptersTrackOf(s))
283
+ }
284
+
285
+ // A fresh token for the session: getToken's, else the session URL's.
286
+ async #nextToken(): Promise<string | null> {
287
+ const sessionUrl = this.getAttribute('session-url')
288
+ const playbackId = this.getAttribute('playback-id')
289
+ if (!playbackId) return null
290
+ if (this.#getToken) return this.#getToken({ playbackId, native: playsNatively() })
291
+ if (!sessionUrl) return null
292
+ const playing = this.#session
293
+ const s = await fetchSession(sessionUrl, playbackId, playsNatively())
294
+ if (s === null) return null
295
+ if (
296
+ playing === this.#session &&
297
+ sessionUrl === this.getAttribute('session-url') &&
298
+ playbackId === this.getAttribute('playback-id') &&
299
+ this.#playback?.playback_id === s.playback_id
300
+ ) {
301
+ this.#playback = {
302
+ ...this.#playback,
303
+ token: s.token,
304
+ ...(s.expires_at ? { expires_at: s.expires_at } : {}),
305
+ ...(s.tracks ? { tracks: s.tracks } : {}),
306
+ }
307
+ }
308
+ return s.token
309
+ }
310
+
311
+ #play(media: MediaElement, baseUrl: string, playbackId: string, loading: string): void {
312
+ this.#clearChapters()
313
+ this.#loaded = loading
314
+ const sessionUrl = this.getAttribute('session-url')
315
+ const requestedId = this.getAttribute('playback-id')
316
+ const requestedBase = this.getAttribute('base-url')
317
+ const isCurrent = () =>
318
+ session === this.#session &&
319
+ sessionUrl === this.getAttribute('session-url') &&
320
+ requestedId === this.getAttribute('playback-id') &&
321
+ requestedBase === this.getAttribute('base-url')
322
+ const session: TokenSession | null = this.#token
323
+ ? new TokenSession(this.#token, () => (isCurrent() ? this.#nextToken() : Promise.resolve(null)), {
324
+ onToken: (token) => {
325
+ if (!isCurrent()) return
326
+ const trackId =
327
+ this.getAttribute('chapters-track') ?? (sessionUrl ? chaptersTrackOf(this.#playback) : '')
328
+ this.#loadChapters(baseUrl, playbackId, trackId)
329
+ this.#emit('clipmux-token', { token })
330
+ },
331
+ onDenied: () => {
332
+ if (!isCurrent()) return
333
+ media.pause()
334
+ this.#emit('clipmux-denied', {})
335
+ },
336
+ })
337
+ : null
338
+ this.#session = session
339
+ media.source = clipmuxSource(
340
+ { baseUrl, playbackId, token: this.#token, hls: this.#hls },
341
+ this.#session ?? undefined,
342
+ )
343
+ }
344
+
345
+ #loadChapters(baseUrl: string, playbackId: string, trackId: string): void {
346
+ if (!trackId) {
347
+ this.#clearChapters()
348
+ return
349
+ }
350
+ const previous = this.#chaptersRequest
351
+ const token = this.token
352
+ if (previous?.trackId === trackId && (previous.status !== 'failed' || previous.token === token)) {
353
+ return
354
+ }
355
+ const request: ChaptersRequest = { trackId, token, status: 'loading', announced: false }
356
+ this.#chaptersRequest = request
357
+ void fetchTrack((t) => trackUrl(baseUrl, playbackId, trackId, t), this.#session, token || undefined)
358
+ .then((vtt) => {
359
+ if (this.#chaptersRequest !== request) return
360
+ this.#chapters = parseChapters(vtt)
361
+ request.status = 'ready'
362
+ this.#showChapters()
363
+ })
364
+ .catch(() => {
365
+ if (this.#chaptersRequest !== request) return
366
+ request.status = 'failed'
367
+ this.#chapters = []
368
+ this.#writeChapterCues()
369
+ this.#emit('clipmux-error', { status: 0, track: trackId })
370
+ })
371
+ }
372
+
373
+ // hls.js clears text cues when loading a manifest. Wait for metadata so
374
+ // the skin gets the current chapters even when the VTT arrives first.
375
+ #showChapters(): void {
376
+ const request = this.#chaptersRequest
377
+ if (
378
+ request?.status !== 'ready' ||
379
+ !this.#media ||
380
+ this.#media.readyState < HTMLMediaElement.HAVE_METADATA
381
+ ) {
382
+ return
383
+ }
384
+ this.#writeChapterCues()
385
+ if (!request.announced) {
386
+ request.announced = true
387
+ this.#emit('clipmux-chapters', { chapters: this.#chapters })
388
+ }
389
+ }
390
+
391
+ #clearChapters(): void {
392
+ if (!this.#chaptersRequest) return
393
+ this.#chaptersRequest = null
394
+ this.#chapters = []
395
+ this.#writeChapterCues()
396
+ }
397
+
398
+ // Video.js reads the first chapters track. TextTrackList has no removal
399
+ // API for addTextTrack, so keep one track and notify the skin of cue edits.
400
+ #writeChapterCues(): void {
401
+ const video = this.#media?.target ?? this.#media
402
+ if (!video) return
403
+ let track = this.#chaptersTrack?.video === video ? this.#chaptersTrack.track : null
404
+ if (!track) {
405
+ if (this.#chapters.length === 0) return
406
+ track = video.addTextTrack('chapters', 'Chapters')
407
+ track.mode = 'hidden'
408
+ this.#chaptersTrack = { video, track }
409
+ }
410
+ for (const cue of Array.from(track.cues ?? [])) track.removeCue(cue)
411
+ const last = this.#chapters.at(-1)
412
+ for (const chapter of this.#chapters) {
413
+ const gap = video.duration - chapter.endTime
414
+ const end =
415
+ chapter === last && gap > 0 && gap <= CHAPTER_END_TOLERANCE ? video.duration : chapter.endTime
416
+ track.addCue(new VTTCue(chapter.startTime, end, chapter.title))
417
+ }
418
+ video.textTracks.dispatchEvent(new Event('change'))
419
+ }
420
+ }
421
+
422
+ if (!customElements.get('clipmux-player')) customElements.define('clipmux-player', ClipMuxPlayerElement)
423
+
424
+ declare global {
425
+ interface HTMLElementTagNameMap {
426
+ 'clipmux-player': ClipMuxPlayerElement
427
+ }
428
+ interface HTMLElementEventMap extends ClipMuxPlayerEventMap {}
429
+ }
package/src/index.ts ADDED
@@ -0,0 +1,28 @@
1
+ // @clipmux/player: play ClipMux videos with Video.js 10, refreshing expired
2
+ // playback tokens without losing the viewer's place. Import
3
+ // "@clipmux/player/element" to register <clipmux-player>; this module has
4
+ // the parts without the UI.
5
+ export {
6
+ createRefreshLoader,
7
+ type GetToken,
8
+ type LoaderClass,
9
+ rewriteTokenUrl,
10
+ type SessionOptions,
11
+ type TokenRequest,
12
+ TokenSession,
13
+ } from './refresh.ts'
14
+ export {
15
+ chaptersTrackOf,
16
+ fetchSession,
17
+ type PlaybackSession,
18
+ SessionError,
19
+ type SessionTrack,
20
+ } from './session.ts'
21
+ export {
22
+ type ClipMuxSource,
23
+ clipmuxSource,
24
+ playbackUrl,
25
+ playsNatively,
26
+ type SourceOptions,
27
+ } from './source.ts'
28
+ export { type Chapter, fetchTrack, type PlayerChapter, parseChapters, trackUrl } from './tracks.ts'
package/src/react.ts ADDED
@@ -0,0 +1,18 @@
1
+ // React 19 JSX types for <clipmux-player>. Types only: React is not a
2
+ // dependency. Import it once in an app that renders the element from JSX.
3
+ //
4
+ // import type {} from '@clipmux/player/react'
5
+ import type * as React from 'react'
6
+ import type { ClipMuxPlayerElement, ClipMuxPlayerProps } from './element.ts'
7
+
8
+ declare module 'react' {
9
+ namespace JSX {
10
+ interface IntrinsicElements {
11
+ 'clipmux-player': React.DetailedHTMLProps<
12
+ React.HTMLAttributes<ClipMuxPlayerElement>,
13
+ ClipMuxPlayerElement
14
+ > &
15
+ ClipMuxPlayerProps
16
+ }
17
+ }
18
+ }