@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/package.json CHANGED
@@ -1,51 +1,67 @@
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.0",
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
+ ],
14
+ "homepage": "https://github.com/visheshgubrani/clipmux/tree/main/packages/player#readme",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/visheshgubrani/clipmux.git",
18
+ "directory": "packages/player"
19
+ },
20
+ "bugs": {
21
+ "url": "https://github.com/visheshgubrani/clipmux/issues"
22
+ },
5
23
  "type": "module",
6
- "main": "./dist/index.cjs",
7
- "module": "./dist/index.js",
8
- "types": "./dist/index.d.ts",
9
24
  "exports": {
10
25
  ".": {
11
26
  "types": "./dist/index.d.ts",
12
- "import": "./dist/index.js",
13
- "require": "./dist/index.cjs"
27
+ "default": "./dist/index.js"
28
+ },
29
+ "./element": {
30
+ "types": "./dist/element.d.ts",
31
+ "default": "./dist/element.js"
32
+ },
33
+ "./react": {
34
+ "types": "./dist/react.d.ts",
35
+ "default": "./dist/react.js"
14
36
  }
15
37
  },
16
38
  "files": [
17
39
  "dist",
18
- "README.md"
40
+ "src",
41
+ "!src/**/*.test.ts"
19
42
  ],
20
43
  "scripts": {
21
- "build": "tsup",
22
- "dev": "tsup --watch",
23
- "typecheck": "tsc --noEmit"
44
+ "build": "tsc -p tsconfig.json",
45
+ "typecheck": "tsc -p tsconfig.json --noEmit",
46
+ "test": "node --test src/*.test.ts"
47
+ },
48
+ "dependencies": {
49
+ "@videojs/html": "10.2.0",
50
+ "@videojs/hlsjs-video": "10.2.0",
51
+ "hls.js": "1.6.19"
24
52
  },
25
53
  "peerDependencies": {
26
- "react": ">=18",
27
- "react-dom": ">=18"
54
+ "@types/react": ">=18"
55
+ },
56
+ "peerDependenciesMeta": {
57
+ "@types/react": {
58
+ "optional": true
59
+ }
28
60
  },
29
61
  "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"
62
+ "@types/react": "19.3.0"
36
63
  },
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"
64
+ "publishConfig": {
65
+ "access": "public"
50
66
  }
51
67
  }
package/src/element.ts ADDED
@@ -0,0 +1,354 @@
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
+ interface MediaElement extends HTMLVideoElement {
35
+ source: unknown
36
+ /** The <video> it plays in. */
37
+ target?: HTMLVideoElement | null
38
+ engine: {
39
+ on(event: string, fn: (event: string, data: { response?: { code?: number } }) => void): void
40
+ } | null
41
+ }
42
+
43
+ export interface ClipMuxTokenDetail {
44
+ token: string
45
+ }
46
+ export interface ClipMuxErrorDetail {
47
+ /** The HTTP status that failed, or 0 for a network or media error. */
48
+ status: number
49
+ /** Set when a track's VTT failed to load. */
50
+ track?: string
51
+ }
52
+ export interface ClipMuxChaptersDetail {
53
+ chapters: PlayerChapter[]
54
+ }
55
+ export type ClipMuxTokenEvent = CustomEvent<ClipMuxTokenDetail>
56
+ export type ClipMuxDeniedEvent = CustomEvent<Record<string, never>>
57
+ export type ClipMuxErrorEvent = CustomEvent<ClipMuxErrorDetail>
58
+ export type ClipMuxChaptersEvent = CustomEvent<ClipMuxChaptersDetail>
59
+
60
+ /** The events of <clipmux-player>; they bubble. */
61
+ export interface ClipMuxPlayerEventMap {
62
+ 'clipmux-token': ClipMuxTokenEvent
63
+ 'clipmux-denied': ClipMuxDeniedEvent
64
+ 'clipmux-error': ClipMuxErrorEvent
65
+ 'clipmux-chapters': ClipMuxChaptersEvent
66
+ }
67
+
68
+ /**
69
+ * The attributes and properties of <clipmux-player> for JSX, without the
70
+ * framework's own; @clipmux/player/react adds them to React's
71
+ * IntrinsicElements.
72
+ */
73
+ export interface ClipMuxPlayerProps {
74
+ 'playback-id'?: string | undefined
75
+ 'session-url'?: string | undefined
76
+ 'base-url'?: string | undefined
77
+ poster?: string | undefined
78
+ 'chapters-track'?: string | undefined
79
+ autoplay?: boolean | undefined
80
+ muted?: boolean | undefined
81
+ token?: string | undefined
82
+ getToken?: GetToken | undefined
83
+ hls?: Record<string, unknown> | undefined
84
+ 'onclipmux-token'?: ((event: ClipMuxTokenEvent) => void) | undefined
85
+ 'onclipmux-denied'?: ((event: ClipMuxDeniedEvent) => void) | undefined
86
+ 'onclipmux-error'?: ((event: ClipMuxErrorEvent) => void) | undefined
87
+ 'onclipmux-chapters'?: ((event: ClipMuxChaptersEvent) => void) | undefined
88
+ }
89
+
90
+ export class ClipMuxPlayerElement extends HTMLElement {
91
+ static observedAttributes = [
92
+ 'base-url',
93
+ 'playback-id',
94
+ 'session-url',
95
+ 'poster',
96
+ 'autoplay',
97
+ 'muted',
98
+ 'chapters-track',
99
+ ]
100
+ #token = ''
101
+ #getToken: GetToken | undefined
102
+ #hls: Record<string, unknown> = {}
103
+ #media: MediaElement | null = null
104
+ #session: TokenSession | null = null
105
+ #loaded = ''
106
+ #fetching = false
107
+ // session-url: the answer in use, the url|playback ID it answers, and
108
+ // the one being asked for.
109
+ #playback: PlaybackSession | null = null
110
+ #playbackFor = ''
111
+ #asking = ''
112
+ #chaptersLoaded = ''
113
+ #chapters: PlayerChapter[] = []
114
+ #chaptersTrack: TextTrack | null = null
115
+
116
+ /** The playback token; unset for a public playback ID. */
117
+ get token(): string {
118
+ return this.#session?.current ?? this.#token
119
+ }
120
+ set token(t: string) {
121
+ this.#token = t
122
+ this.#load()
123
+ }
124
+
125
+ /** Called on a 401 for a fresh token; return null to stop playback. */
126
+ get getToken(): GetToken | undefined {
127
+ return this.#getToken
128
+ }
129
+ set getToken(fn: GetToken | undefined) {
130
+ this.#getToken = fn
131
+ this.#load()
132
+ }
133
+
134
+ /** Extra hls.js options; set before the first load. */
135
+ set hls(options: Record<string, unknown>) {
136
+ this.#hls = options
137
+ }
138
+
139
+ /** The session-url answer in use, once there is one. */
140
+ get session(): PlaybackSession | null {
141
+ return this.#playback
142
+ }
143
+
144
+ /** The chapters of chapters-track, in seconds, once loaded. */
145
+ get chapters(): PlayerChapter[] {
146
+ return this.#chapters
147
+ }
148
+
149
+ /** The <hlsjs-video> element, for its properties and events. */
150
+ get media(): MediaElement | null {
151
+ return this.#media
152
+ }
153
+
154
+ connectedCallback(): void {
155
+ if (!this.#media) {
156
+ this.innerHTML =
157
+ '<video-player><video-skin style="display:block;width:100%;aspect-ratio:16/9">' +
158
+ '<hlsjs-video playsinline crossorigin="anonymous"></hlsjs-video></video-skin></video-player>'
159
+ this.#media = this.querySelector('hlsjs-video') as MediaElement | null
160
+ this.#media?.addEventListener('error', () => this.#emit('clipmux-error', { status: 0 }))
161
+ }
162
+ this.#load()
163
+ }
164
+
165
+ attributeChangedCallback(): void {
166
+ this.#load()
167
+ }
168
+
169
+ #emit<K extends keyof ClipMuxPlayerEventMap>(type: K, detail: ClipMuxPlayerEventMap[K]['detail']): void {
170
+ this.dispatchEvent(new CustomEvent(type, { detail, bubbles: true }))
171
+ }
172
+
173
+ // autoplay and muted reach the media element before any source does.
174
+ #flags(media: MediaElement): void {
175
+ for (const flag of ['autoplay', 'muted'] as const) {
176
+ if (this.hasAttribute(flag)) media.setAttribute(flag, '')
177
+ else media.removeAttribute(flag)
178
+ }
179
+ media.muted = this.hasAttribute('muted')
180
+ }
181
+
182
+ #load(): void {
183
+ const media = this.#media
184
+ if (media) this.#flags(media)
185
+ const sessionUrl = this.getAttribute('session-url')
186
+ if (sessionUrl) {
187
+ this.#loadSession(sessionUrl)
188
+ return
189
+ }
190
+ const baseUrl = this.getAttribute('base-url')
191
+ const playbackId = this.getAttribute('playback-id')
192
+ if (!media || !baseUrl || !playbackId) return
193
+ const poster = this.getAttribute('poster')
194
+ if (poster) media.poster = poster
195
+ // A signed ID needs its first token before anything loads.
196
+ if (!this.#token && this.#getToken) {
197
+ if (!this.#fetching) {
198
+ this.#fetching = true
199
+ this.#getToken({ playbackId, native: playsNatively() }).then(
200
+ (t) => {
201
+ this.#fetching = false
202
+ if (this.#token) return // a token was set meanwhile; it wins
203
+ if (t === null) return this.#emit('clipmux-denied', {})
204
+ this.#token = t
205
+ this.#load()
206
+ },
207
+ () => {
208
+ this.#fetching = false
209
+ this.#emit('clipmux-error', { status: 0 })
210
+ },
211
+ )
212
+ }
213
+ return
214
+ }
215
+ // Reload only when what plays changes; a refreshed token doesn't.
216
+ const loading = `${baseUrl}|${playbackId}|${this.#token}`
217
+ if (loading !== this.#loaded) this.#play(media, baseUrl, playbackId, loading)
218
+ this.#loadChapters(media, baseUrl, playbackId, this.getAttribute('chapters-track') ?? '')
219
+ }
220
+
221
+ // session-url: each playback ID gets its session first; then it plays
222
+ // like any other, from the session's base URL, playback ID and token.
223
+ #loadSession(sessionUrl: string): void {
224
+ const media = this.#media
225
+ const playbackId = this.getAttribute('playback-id')
226
+ if (!media || !playbackId) return
227
+ const key = `${sessionUrl}|${playbackId}`
228
+ if (key !== this.#playbackFor) {
229
+ if (key === this.#asking) return
230
+ this.#asking = key
231
+ fetchSession(sessionUrl, playbackId, playsNatively()).then(
232
+ (s) => {
233
+ if (key !== this.#asking) return // the playback changed meanwhile
234
+ this.#asking = ''
235
+ if (s === null) return this.#emit('clipmux-denied', {})
236
+ this.#playback = s
237
+ this.#playbackFor = key
238
+ this.#token = s.token
239
+ this.#load()
240
+ },
241
+ (err: unknown) => {
242
+ if (key !== this.#asking) return
243
+ this.#asking = ''
244
+ this.#emit('clipmux-error', { status: err instanceof SessionError ? err.status : 0 })
245
+ },
246
+ )
247
+ return
248
+ }
249
+ const s = this.#playback as PlaybackSession
250
+ const baseUrl = this.getAttribute('base-url') ?? s.base_url
251
+ const poster = this.getAttribute('poster') ?? s.poster_url
252
+ if (poster) media.poster = poster
253
+ const loading = `${baseUrl}|${s.playback_id}|${this.#token}`
254
+ if (loading !== this.#loaded) this.#play(media, baseUrl, s.playback_id, loading)
255
+ this.#loadChapters(
256
+ media,
257
+ baseUrl,
258
+ s.playback_id,
259
+ this.getAttribute('chapters-track') ?? chaptersTrackOf(s),
260
+ )
261
+ }
262
+
263
+ // A fresh token for the session: getToken's, else the session URL's.
264
+ async #nextToken(): Promise<string | null> {
265
+ const sessionUrl = this.getAttribute('session-url')
266
+ const playbackId = this.getAttribute('playback-id')
267
+ if (!playbackId) return null
268
+ if (this.#getToken) return this.#getToken({ playbackId, native: playsNatively() })
269
+ if (!sessionUrl) return null
270
+ const s = await fetchSession(sessionUrl, playbackId, playsNatively())
271
+ if (s === null) return null
272
+ if (`${sessionUrl}|${playbackId}` === this.#playbackFor && this.#playback) {
273
+ this.#playback = {
274
+ ...this.#playback,
275
+ token: s.token,
276
+ ...(s.expires_at ? { expires_at: s.expires_at } : {}),
277
+ }
278
+ }
279
+ return s.token
280
+ }
281
+
282
+ #play(media: MediaElement, baseUrl: string, playbackId: string, loading: string): void {
283
+ this.#loaded = loading
284
+ this.#session = this.#token
285
+ ? new TokenSession(this.#token, () => this.#nextToken(), {
286
+ onToken: (token) => this.#emit('clipmux-token', { token }),
287
+ onDenied: () => {
288
+ media.pause()
289
+ this.#emit('clipmux-denied', {})
290
+ },
291
+ })
292
+ : null
293
+ media.source = clipmuxSource(
294
+ { baseUrl, playbackId, token: this.#token, hls: this.#hls },
295
+ this.#session ?? undefined,
296
+ )
297
+ }
298
+
299
+ // The chapters become the cues of a hidden chapters text track of the
300
+ // <video> itself, which the skin's time slider reads. It is made with
301
+ // addTextTrack: a <track> without a src empties its cues when it fails to
302
+ // load, and a light-DOM one is copied into the <video> without them.
303
+ // hls.js clears every text track's cues as its manifest loads, so the
304
+ // cues are added once the media has metadata.
305
+ #loadChapters(media: MediaElement, baseUrl: string, playbackId: string, trackId: string): void {
306
+ const key = `${baseUrl}|${playbackId}|${trackId}`
307
+ if (key === this.#chaptersLoaded) return
308
+ this.#chaptersLoaded = key
309
+ this.#dropChapters()
310
+ if (!trackId) return
311
+ fetchTrack(
312
+ (t) => trackUrl(baseUrl, playbackId, trackId, t),
313
+ this.#session,
314
+ this.#token || undefined,
315
+ ).then(
316
+ (vtt) => {
317
+ if (key !== this.#chaptersLoaded) return
318
+ this.#chapters = parseChapters(vtt)
319
+ const add = () => {
320
+ if (key !== this.#chaptersLoaded) return
321
+ const video = media.target ?? media
322
+ const track = video.addTextTrack('chapters', 'Chapters')
323
+ track.mode = 'hidden'
324
+ for (const c of this.#chapters) track.addCue(new VTTCue(c.startTime, c.endTime, c.title))
325
+ this.#chaptersTrack = track
326
+ this.#emit('clipmux-chapters', { chapters: this.#chapters })
327
+ }
328
+ if (media.readyState >= HTMLMediaElement.HAVE_METADATA) add()
329
+ else media.addEventListener('loadedmetadata', add, { once: true })
330
+ },
331
+ () => this.#emit('clipmux-error', { status: 0, track: trackId }),
332
+ )
333
+ }
334
+
335
+ // A text track can't be removed: the old one is emptied and disabled.
336
+ #dropChapters(): void {
337
+ const old = this.#chaptersTrack
338
+ if (old) {
339
+ for (const cue of Array.from(old.cues ?? [])) old.removeCue(cue)
340
+ old.mode = 'disabled'
341
+ }
342
+ this.#chaptersTrack = null
343
+ this.#chapters = []
344
+ }
345
+ }
346
+
347
+ if (!customElements.get('clipmux-player')) customElements.define('clipmux-player', ClipMuxPlayerElement)
348
+
349
+ declare global {
350
+ interface HTMLElementTagNameMap {
351
+ 'clipmux-player': ClipMuxPlayerElement
352
+ }
353
+ interface HTMLElementEventMap extends ClipMuxPlayerEventMap {}
354
+ }
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
+ }