@portalshq/capability-video-delivery 0.1.1 → 0.1.6
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 +70 -6
- package/dist/browser.d.ts +16 -0
- package/dist/browser.js +46 -0
- package/dist/captions.d.ts +39 -0
- package/dist/captions.js +84 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/live-session.d.ts +50 -10
- package/dist/live-session.js +173 -4
- package/package.json +26 -7
- package/dist/vod-session.d.ts +0 -8
- package/dist/vod-session.js +0 -5
package/README.md
CHANGED
|
@@ -1,8 +1,72 @@
|
|
|
1
1
|
# @portalshq/capability-video-delivery
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
3
|
+
`LiveDelivery` connects one configured HLS playback stream per instance. It
|
|
4
|
+
does not create an origin, schedule programs, or define whether content is
|
|
5
|
+
"live" or "VOD"; those are application business decisions. It verifies the
|
|
6
|
+
configured manifest on start, retries connection failures, and continues to
|
|
7
|
+
monitor its health while active.
|
|
8
|
+
|
|
9
|
+
`HlsPlaybackSession` is the common, token-free descriptor for an HLS-capable
|
|
10
|
+
application player. Queue Broadcast returns this descriptor after its trusted
|
|
11
|
+
backend has talked to the queue control plane; the player receives only the
|
|
12
|
+
public/unlisted manifest URL.
|
|
13
|
+
|
|
14
|
+
## Sidecar captions
|
|
15
|
+
|
|
16
|
+
Captions are a `video-delivery` feature: it validates supplied WebVTT URLs or
|
|
17
|
+
timed cues, returns them with the playback descriptor, and mounts native HTML
|
|
18
|
+
`<track>` elements in the viewer. They are never pixels burned into the stream.
|
|
19
|
+
For supplied cues, the package creates and later revokes a browser-local WebVTT
|
|
20
|
+
source. A cross-origin caption host must permit the player origin with the
|
|
21
|
+
appropriate CORS headers.
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
const playback = await client.getPlayback({
|
|
25
|
+
captionTracks: [{
|
|
26
|
+
id: "en",
|
|
27
|
+
label: "English",
|
|
28
|
+
language: "en",
|
|
29
|
+
cues: [
|
|
30
|
+
{ startTimeSeconds: 0, endTimeSeconds: 2.5, text: "Welcome." },
|
|
31
|
+
],
|
|
32
|
+
default: true,
|
|
33
|
+
}],
|
|
34
|
+
});
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
import { mountPlaybackCaptions } from "@portalshq/capability-video-delivery/browser";
|
|
39
|
+
|
|
40
|
+
const video = document.querySelector("video")!;
|
|
41
|
+
video.src = playback.playbackManifestUrl;
|
|
42
|
+
const mountedCaptions = mountPlaybackCaptions(video, playback);
|
|
43
|
+
|
|
44
|
+
// Remove these package-managed tracks when this playback session is replaced.
|
|
45
|
+
mountedCaptions.remove();
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Use `src` instead of `cues` when the consuming app already hosts a `.vtt` file.
|
|
49
|
+
`createWebVtt(cues)` is also available when it needs VTT content for a custom
|
|
50
|
+
storage flow.
|
|
51
|
+
|
|
52
|
+
## Scheduled and dual-format programming
|
|
53
|
+
|
|
54
|
+
Create separate delivery objects for independent stream windows. For example,
|
|
55
|
+
an application can start a `morning` instance for a 9am–12pm manifest and an
|
|
56
|
+
`afternoon` instance for a 1pm–5pm manifest. The application owns that clock,
|
|
57
|
+
its routing, and any VOD-versus-live presentation rules; each `LiveDelivery`
|
|
58
|
+
object only observes and returns its one configured HLS stream.
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
const morning = new LiveDelivery({
|
|
62
|
+
sessionId: "morning-stream",
|
|
63
|
+
playbackManifestUrl: "https://media.example/morning/index.m3u8",
|
|
64
|
+
});
|
|
65
|
+
const afternoon = new LiveDelivery({
|
|
66
|
+
sessionId: "afternoon-stream",
|
|
67
|
+
playbackManifestUrl: "https://media.example/afternoon/index.m3u8",
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
await morning.start();
|
|
71
|
+
// Application-owned scheduler later calls morning.stop() and afternoon.start().
|
|
72
|
+
```
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type CaptionTrack } from "./captions.js";
|
|
2
|
+
import type { HlsPlaybackSession } from "./live-session.js";
|
|
3
|
+
export interface MountedCaptionTracks {
|
|
4
|
+
/** The exact native elements added to the player. */
|
|
5
|
+
readonly elements: readonly HTMLTrackElement[];
|
|
6
|
+
/** Removes only the tracks added by this mount operation. */
|
|
7
|
+
remove(): void;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Adds sidecar captions to a browser media element. This deliberately uses
|
|
11
|
+
* native HTML track rendering, so captions stay selectable and never become
|
|
12
|
+
* part of the encoded HLS stream.
|
|
13
|
+
*/
|
|
14
|
+
export declare function mountCaptionTracks(player: HTMLMediaElement, tracks: readonly CaptionTrack[]): MountedCaptionTracks;
|
|
15
|
+
/** Mounts every caption track declared by a `LiveDelivery` playback session. */
|
|
16
|
+
export declare function mountPlaybackCaptions(player: HTMLMediaElement, playback: Pick<HlsPlaybackSession, "captionTracks">): MountedCaptionTracks;
|
package/dist/browser.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { createWebVtt, normalizeCaptionTracks } from "./captions.js";
|
|
2
|
+
/**
|
|
3
|
+
* Adds sidecar captions to a browser media element. This deliberately uses
|
|
4
|
+
* native HTML track rendering, so captions stay selectable and never become
|
|
5
|
+
* part of the encoded HLS stream.
|
|
6
|
+
*/
|
|
7
|
+
export function mountCaptionTracks(player, tracks) {
|
|
8
|
+
const normalizedTracks = normalizeCaptionTracks(tracks);
|
|
9
|
+
const document = player.ownerDocument;
|
|
10
|
+
if (!document)
|
|
11
|
+
throw new TypeError("player must belong to a document");
|
|
12
|
+
const objectUrls = [];
|
|
13
|
+
let removed = false;
|
|
14
|
+
const elements = normalizedTracks.map((caption) => {
|
|
15
|
+
const element = document.createElement("track");
|
|
16
|
+
element.setAttribute("data-video-delivery-caption", caption.id);
|
|
17
|
+
element.kind = caption.kind ?? "captions";
|
|
18
|
+
if (caption.src !== undefined) {
|
|
19
|
+
element.src = caption.src;
|
|
20
|
+
}
|
|
21
|
+
else {
|
|
22
|
+
const objectUrl = URL.createObjectURL(new Blob([createWebVtt(caption.cues)], { type: "text/vtt" }));
|
|
23
|
+
objectUrls.push(objectUrl);
|
|
24
|
+
element.src = objectUrl;
|
|
25
|
+
}
|
|
26
|
+
element.srclang = caption.language;
|
|
27
|
+
element.label = caption.label;
|
|
28
|
+
element.default = caption.default ?? false;
|
|
29
|
+
player.append(element);
|
|
30
|
+
return element;
|
|
31
|
+
});
|
|
32
|
+
return {
|
|
33
|
+
elements,
|
|
34
|
+
remove: () => {
|
|
35
|
+
if (removed)
|
|
36
|
+
return;
|
|
37
|
+
removed = true;
|
|
38
|
+
elements.forEach((element) => element.remove());
|
|
39
|
+
objectUrls.forEach((objectUrl) => URL.revokeObjectURL(objectUrl));
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
/** Mounts every caption track declared by a `LiveDelivery` playback session. */
|
|
44
|
+
export function mountPlaybackCaptions(player, playback) {
|
|
45
|
+
return mountCaptionTracks(player, playback.captionTracks ?? []);
|
|
46
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/** A timed text item that can be encoded as a WebVTT sidecar file. */
|
|
2
|
+
export interface CaptionCue {
|
|
3
|
+
id?: string;
|
|
4
|
+
startTimeSeconds: number;
|
|
5
|
+
endTimeSeconds: number;
|
|
6
|
+
text: string;
|
|
7
|
+
}
|
|
8
|
+
interface CaptionTrackDetails {
|
|
9
|
+
/** Stable, application-owned identifier for the track. */
|
|
10
|
+
id: string;
|
|
11
|
+
/** Human-readable picker label, for example "English". */
|
|
12
|
+
label: string;
|
|
13
|
+
/** BCP 47 language tag, passed to the viewer as `srclang`. */
|
|
14
|
+
language: string;
|
|
15
|
+
/** HTML track kind. Defaults to `captions`. */
|
|
16
|
+
kind?: "captions" | "subtitles";
|
|
17
|
+
/** Whether the viewer should select this track initially. At most one may be true. */
|
|
18
|
+
default?: boolean;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Sidecar captions rendered by this package into native `<track>` elements.
|
|
22
|
+
* Provide a hosted VTT URL or directly supply timed cues for the package to
|
|
23
|
+
* turn into a temporary browser-local VTT source.
|
|
24
|
+
*/
|
|
25
|
+
export type CaptionTrack = CaptionTrackDetails & ({
|
|
26
|
+
src: string;
|
|
27
|
+
cues?: never;
|
|
28
|
+
} | {
|
|
29
|
+
cues: readonly CaptionCue[];
|
|
30
|
+
src?: never;
|
|
31
|
+
});
|
|
32
|
+
/**
|
|
33
|
+
* Validates and copies caption metadata for safe transport in a playback
|
|
34
|
+
* descriptor. Caption media remains outside the video stream.
|
|
35
|
+
*/
|
|
36
|
+
export declare function normalizeCaptionTracks(tracks: readonly CaptionTrack[]): CaptionTrack[];
|
|
37
|
+
/** Creates a standards-compliant WebVTT document when an app owns cue generation. */
|
|
38
|
+
export declare function createWebVtt(cues: readonly CaptionCue[]): string;
|
|
39
|
+
export {};
|
package/dist/captions.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Validates and copies caption metadata for safe transport in a playback
|
|
3
|
+
* descriptor. Caption media remains outside the video stream.
|
|
4
|
+
*/
|
|
5
|
+
export function normalizeCaptionTracks(tracks) {
|
|
6
|
+
const ids = new Set();
|
|
7
|
+
let defaultCount = 0;
|
|
8
|
+
return tracks.map((track, index) => {
|
|
9
|
+
const id = requiredText(track.id, `captionTracks[${index}].id`);
|
|
10
|
+
if (ids.has(id))
|
|
11
|
+
throw new TypeError(`captionTracks contains duplicate id: ${id}`);
|
|
12
|
+
ids.add(id);
|
|
13
|
+
const label = requiredText(track.label, `captionTracks[${index}].label`);
|
|
14
|
+
const language = requiredText(track.language, `captionTracks[${index}].language`);
|
|
15
|
+
const hasSrc = track.src !== undefined;
|
|
16
|
+
const hasCues = track.cues !== undefined;
|
|
17
|
+
if (hasSrc === hasCues) {
|
|
18
|
+
throw new TypeError(`captionTracks[${index}] must contain exactly one of src or cues`);
|
|
19
|
+
}
|
|
20
|
+
const kind = track.kind ?? "captions";
|
|
21
|
+
if (kind !== "captions" && kind !== "subtitles") {
|
|
22
|
+
throw new TypeError(`captionTracks[${index}].kind must be captions or subtitles`);
|
|
23
|
+
}
|
|
24
|
+
if (track.default)
|
|
25
|
+
defaultCount += 1;
|
|
26
|
+
if (defaultCount > 1)
|
|
27
|
+
throw new TypeError("captionTracks can contain at most one default track");
|
|
28
|
+
const details = { id, label, language, kind, ...(track.default ? { default: true } : {}) };
|
|
29
|
+
return hasSrc
|
|
30
|
+
? { ...details, src: normalizeVttUrl(track.src, `captionTracks[${index}].src`) }
|
|
31
|
+
: { ...details, cues: normalizeCaptionCues(track.cues, `captionTracks[${index}].cues`) };
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
/** Creates a standards-compliant WebVTT document when an app owns cue generation. */
|
|
35
|
+
export function createWebVtt(cues) {
|
|
36
|
+
return `WEBVTT\n\n${normalizeCaptionCues(cues, "cues").map((cue) => {
|
|
37
|
+
const id = cue.id === undefined ? "" : `${cue.id}\n`;
|
|
38
|
+
return `${id}${formatTimestamp(cue.startTimeSeconds)} --> ${formatTimestamp(cue.endTimeSeconds)}\n${cue.text}`;
|
|
39
|
+
}).join("\n\n")}\n`;
|
|
40
|
+
}
|
|
41
|
+
function normalizeCaptionCues(cues, field) {
|
|
42
|
+
if (cues.length === 0)
|
|
43
|
+
throw new TypeError(`${field} must contain at least one cue`);
|
|
44
|
+
let previousEnd = 0;
|
|
45
|
+
return cues.map((cue, index) => {
|
|
46
|
+
if (!Number.isFinite(cue.startTimeSeconds) || cue.startTimeSeconds < 0) {
|
|
47
|
+
throw new TypeError(`${field}[${index}].startTimeSeconds must be a non-negative finite number`);
|
|
48
|
+
}
|
|
49
|
+
if (!Number.isFinite(cue.endTimeSeconds) || cue.endTimeSeconds <= cue.startTimeSeconds) {
|
|
50
|
+
throw new TypeError(`${field}[${index}].endTimeSeconds must be after startTimeSeconds`);
|
|
51
|
+
}
|
|
52
|
+
if (cue.startTimeSeconds < previousEnd) {
|
|
53
|
+
throw new TypeError("cues must be ordered without overlapping");
|
|
54
|
+
}
|
|
55
|
+
previousEnd = cue.endTimeSeconds;
|
|
56
|
+
const text = requiredText(cue.text, `${field}[${index}].text`);
|
|
57
|
+
const id = cue.id === undefined ? undefined : requiredText(cue.id, `${field}[${index}].id`);
|
|
58
|
+
return { startTimeSeconds: cue.startTimeSeconds, endTimeSeconds: cue.endTimeSeconds, text, ...(id === undefined ? {} : { id }) };
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
function normalizeVttUrl(value, field) {
|
|
62
|
+
const url = new URL(value);
|
|
63
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
64
|
+
throw new TypeError(`${field} must use http or https`);
|
|
65
|
+
}
|
|
66
|
+
if (url.username || url.password || url.hash) {
|
|
67
|
+
throw new TypeError(`${field} cannot include credentials or a fragment`);
|
|
68
|
+
}
|
|
69
|
+
return url.toString();
|
|
70
|
+
}
|
|
71
|
+
function requiredText(value, field) {
|
|
72
|
+
const normalized = value.trim();
|
|
73
|
+
if (!normalized)
|
|
74
|
+
throw new TypeError(`${field} is required`);
|
|
75
|
+
return normalized;
|
|
76
|
+
}
|
|
77
|
+
function formatTimestamp(totalSeconds) {
|
|
78
|
+
const milliseconds = Math.round(totalSeconds * 1_000);
|
|
79
|
+
const hours = Math.floor(milliseconds / 3_600_000);
|
|
80
|
+
const minutes = Math.floor((milliseconds % 3_600_000) / 60_000);
|
|
81
|
+
const seconds = Math.floor((milliseconds % 60_000) / 1_000);
|
|
82
|
+
const remainder = milliseconds % 1_000;
|
|
83
|
+
return `${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}.${String(remainder).padStart(3, "0")}`;
|
|
84
|
+
}
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
package/dist/live-session.d.ts
CHANGED
|
@@ -1,15 +1,55 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
* bitrate ladder, and origin packaging are implementation details that can
|
|
5
|
-
* change without breaking any channel that consumes this capability.
|
|
6
|
-
*/
|
|
7
|
-
export interface LiveSessionHandle {
|
|
1
|
+
import { type CaptionTrack } from "./captions.js";
|
|
2
|
+
/** A token-free HLS source that an application can hand to its player. */
|
|
3
|
+
export interface HlsPlaybackSession {
|
|
8
4
|
sessionId: string;
|
|
9
|
-
ingestUrl: string;
|
|
10
5
|
playbackManifestUrl: string;
|
|
6
|
+
/** Optional application-owned sidecar WebVTT tracks for the viewer. */
|
|
7
|
+
captionTracks?: readonly CaptionTrack[];
|
|
8
|
+
}
|
|
9
|
+
export interface LiveDeliveryOptions extends HlsPlaybackSession {
|
|
10
|
+
/** Number of immediate connection attempts before start fails. */
|
|
11
|
+
retryAttempts?: number;
|
|
12
|
+
/** Delay between connection attempts. */
|
|
13
|
+
retryDelayMs?: number;
|
|
14
|
+
/** Recheck the configured manifest while the delivery is active. */
|
|
15
|
+
healthCheckIntervalMs?: number;
|
|
16
|
+
/** Abort an individual manifest request after this duration. Defaults to 10 seconds. */
|
|
17
|
+
requestTimeoutMs?: number;
|
|
18
|
+
/** Injectable for non-browser server runtimes and tests. */
|
|
19
|
+
fetch?: typeof fetch;
|
|
11
20
|
}
|
|
21
|
+
export interface LiveDeliveryStatus extends HlsPlaybackSession {
|
|
22
|
+
isRunning: boolean;
|
|
23
|
+
isHealthy: boolean;
|
|
24
|
+
lastCheckedAt?: string;
|
|
25
|
+
lastError?: string;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Connects one configured HLS playback stream. It never provisions an origin,
|
|
29
|
+
* schedules programming, or distinguishes live from on-demand business flows.
|
|
30
|
+
*/
|
|
12
31
|
export declare class LiveDelivery {
|
|
13
|
-
|
|
14
|
-
|
|
32
|
+
private readonly session;
|
|
33
|
+
private readonly retryAttempts;
|
|
34
|
+
private readonly retryDelayMs;
|
|
35
|
+
private readonly healthCheckIntervalMs;
|
|
36
|
+
private readonly requestTimeoutMs;
|
|
37
|
+
private readonly requestFetch;
|
|
38
|
+
private healthCheckTimer;
|
|
39
|
+
private startPromise;
|
|
40
|
+
private activeRequest;
|
|
41
|
+
private lifecycleGeneration;
|
|
42
|
+
private isRunning;
|
|
43
|
+
private isHealthy;
|
|
44
|
+
private lastCheckedAt;
|
|
45
|
+
private lastError;
|
|
46
|
+
constructor(options: LiveDeliveryOptions);
|
|
47
|
+
start(): Promise<HlsPlaybackSession>;
|
|
48
|
+
stop(): Promise<void>;
|
|
49
|
+
getStatus(): LiveDeliveryStatus;
|
|
50
|
+
private connect;
|
|
51
|
+
private scheduleHealthCheck;
|
|
52
|
+
private refreshHealth;
|
|
53
|
+
private checkHealthWithRetry;
|
|
54
|
+
private assertCurrent;
|
|
15
55
|
}
|
package/dist/live-session.js
CHANGED
|
@@ -1,8 +1,177 @@
|
|
|
1
|
+
import { normalizeCaptionTracks } from "./captions.js";
|
|
2
|
+
/**
|
|
3
|
+
* Connects one configured HLS playback stream. It never provisions an origin,
|
|
4
|
+
* schedules programming, or distinguishes live from on-demand business flows.
|
|
5
|
+
*/
|
|
1
6
|
export class LiveDelivery {
|
|
2
|
-
|
|
3
|
-
|
|
7
|
+
session;
|
|
8
|
+
retryAttempts;
|
|
9
|
+
retryDelayMs;
|
|
10
|
+
healthCheckIntervalMs;
|
|
11
|
+
requestTimeoutMs;
|
|
12
|
+
requestFetch;
|
|
13
|
+
healthCheckTimer = null;
|
|
14
|
+
startPromise = null;
|
|
15
|
+
activeRequest = null;
|
|
16
|
+
lifecycleGeneration = 0;
|
|
17
|
+
isRunning = false;
|
|
18
|
+
isHealthy = false;
|
|
19
|
+
lastCheckedAt;
|
|
20
|
+
lastError;
|
|
21
|
+
constructor(options) {
|
|
22
|
+
this.session = {
|
|
23
|
+
sessionId: assertSessionId(options.sessionId),
|
|
24
|
+
playbackManifestUrl: normalizeManifestUrl(options.playbackManifestUrl),
|
|
25
|
+
...(options.captionTracks === undefined
|
|
26
|
+
? {}
|
|
27
|
+
: { captionTracks: normalizeCaptionTracks(options.captionTracks) }),
|
|
28
|
+
};
|
|
29
|
+
this.retryAttempts = options.retryAttempts ?? 3;
|
|
30
|
+
this.retryDelayMs = options.retryDelayMs ?? 1_000;
|
|
31
|
+
this.healthCheckIntervalMs = options.healthCheckIntervalMs ?? 30_000;
|
|
32
|
+
this.requestTimeoutMs = options.requestTimeoutMs ?? 10_000;
|
|
33
|
+
this.requestFetch = options.fetch ?? fetch;
|
|
34
|
+
assertPositiveInteger("retryAttempts", this.retryAttempts);
|
|
35
|
+
assertNonNegativeInteger("retryDelayMs", this.retryDelayMs);
|
|
36
|
+
assertPositiveInteger("healthCheckIntervalMs", this.healthCheckIntervalMs);
|
|
37
|
+
assertPositiveInteger("requestTimeoutMs", this.requestTimeoutMs);
|
|
4
38
|
}
|
|
5
|
-
async
|
|
6
|
-
|
|
39
|
+
async start() {
|
|
40
|
+
if (this.isRunning)
|
|
41
|
+
return this.session;
|
|
42
|
+
if (!this.startPromise) {
|
|
43
|
+
const generation = ++this.lifecycleGeneration;
|
|
44
|
+
this.startPromise = this.connect(generation);
|
|
45
|
+
}
|
|
46
|
+
const pendingStart = this.startPromise;
|
|
47
|
+
try {
|
|
48
|
+
return await pendingStart;
|
|
49
|
+
}
|
|
50
|
+
finally {
|
|
51
|
+
if (this.startPromise === pendingStart)
|
|
52
|
+
this.startPromise = null;
|
|
53
|
+
}
|
|
7
54
|
}
|
|
55
|
+
async stop() {
|
|
56
|
+
this.lifecycleGeneration += 1;
|
|
57
|
+
this.isRunning = false;
|
|
58
|
+
this.isHealthy = false;
|
|
59
|
+
this.activeRequest?.abort(new Error("LiveDelivery stopped"));
|
|
60
|
+
this.activeRequest = null;
|
|
61
|
+
this.startPromise = null;
|
|
62
|
+
if (this.healthCheckTimer)
|
|
63
|
+
clearTimeout(this.healthCheckTimer);
|
|
64
|
+
this.healthCheckTimer = null;
|
|
65
|
+
}
|
|
66
|
+
getStatus() {
|
|
67
|
+
return {
|
|
68
|
+
...this.session,
|
|
69
|
+
isRunning: this.isRunning,
|
|
70
|
+
isHealthy: this.isHealthy,
|
|
71
|
+
...(this.lastCheckedAt ? { lastCheckedAt: this.lastCheckedAt } : {}),
|
|
72
|
+
...(this.lastError ? { lastError: this.lastError } : {}),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
async connect(generation) {
|
|
76
|
+
await this.checkHealthWithRetry(generation);
|
|
77
|
+
this.assertCurrent(generation);
|
|
78
|
+
this.isRunning = true;
|
|
79
|
+
this.scheduleHealthCheck(generation);
|
|
80
|
+
return this.session;
|
|
81
|
+
}
|
|
82
|
+
scheduleHealthCheck(generation) {
|
|
83
|
+
if (!this.isRunning || generation !== this.lifecycleGeneration)
|
|
84
|
+
return;
|
|
85
|
+
if (this.healthCheckTimer)
|
|
86
|
+
clearTimeout(this.healthCheckTimer);
|
|
87
|
+
this.healthCheckTimer = setTimeout(() => {
|
|
88
|
+
this.healthCheckTimer = null;
|
|
89
|
+
void this.refreshHealth(generation);
|
|
90
|
+
}, this.healthCheckIntervalMs);
|
|
91
|
+
this.healthCheckTimer.unref?.();
|
|
92
|
+
}
|
|
93
|
+
async refreshHealth(generation) {
|
|
94
|
+
try {
|
|
95
|
+
await this.checkHealthWithRetry(generation);
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
// The status records the error; an intermittent check must not crash the host process.
|
|
99
|
+
}
|
|
100
|
+
finally {
|
|
101
|
+
this.scheduleHealthCheck(generation);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
async checkHealthWithRetry(generation) {
|
|
105
|
+
let error;
|
|
106
|
+
for (let attempt = 1; attempt <= this.retryAttempts; attempt++) {
|
|
107
|
+
this.assertCurrent(generation);
|
|
108
|
+
const controller = new AbortController();
|
|
109
|
+
const timeout = setTimeout(() => controller.abort(new Error(`manifest request timed out after ${this.requestTimeoutMs}ms`)), this.requestTimeoutMs);
|
|
110
|
+
timeout.unref?.();
|
|
111
|
+
this.activeRequest = controller;
|
|
112
|
+
try {
|
|
113
|
+
const response = await this.requestFetch(this.session.playbackManifestUrl, {
|
|
114
|
+
method: "GET",
|
|
115
|
+
headers: { Accept: "application/vnd.apple.mpegurl, application/x-mpegURL" },
|
|
116
|
+
signal: controller.signal,
|
|
117
|
+
});
|
|
118
|
+
this.assertCurrent(generation);
|
|
119
|
+
if (!response.ok)
|
|
120
|
+
throw new Error(`manifest returned HTTP ${response.status}`);
|
|
121
|
+
this.isHealthy = true;
|
|
122
|
+
this.lastError = undefined;
|
|
123
|
+
this.lastCheckedAt = new Date().toISOString();
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
catch (caught) {
|
|
127
|
+
this.assertCurrent(generation);
|
|
128
|
+
error = caught;
|
|
129
|
+
if (attempt < this.retryAttempts) {
|
|
130
|
+
await wait(this.retryDelayMs);
|
|
131
|
+
this.assertCurrent(generation);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
finally {
|
|
135
|
+
clearTimeout(timeout);
|
|
136
|
+
if (this.activeRequest === controller)
|
|
137
|
+
this.activeRequest = null;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
this.isHealthy = false;
|
|
141
|
+
this.lastCheckedAt = new Date().toISOString();
|
|
142
|
+
this.lastError = error instanceof Error ? error.message : String(error);
|
|
143
|
+
throw new Error(`Unable to connect to configured stream: ${this.lastError}`, { cause: error });
|
|
144
|
+
}
|
|
145
|
+
assertCurrent(generation) {
|
|
146
|
+
if (generation !== this.lifecycleGeneration) {
|
|
147
|
+
throw new Error("LiveDelivery operation was stopped");
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
function assertSessionId(sessionId) {
|
|
152
|
+
const normalized = sessionId.trim();
|
|
153
|
+
if (!normalized)
|
|
154
|
+
throw new TypeError("sessionId is required");
|
|
155
|
+
return normalized;
|
|
156
|
+
}
|
|
157
|
+
function normalizeManifestUrl(value) {
|
|
158
|
+
const url = new URL(value);
|
|
159
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
160
|
+
throw new TypeError("playbackManifestUrl must use http or https");
|
|
161
|
+
}
|
|
162
|
+
if (url.username || url.password || url.hash) {
|
|
163
|
+
throw new TypeError("playbackManifestUrl cannot include credentials or a fragment");
|
|
164
|
+
}
|
|
165
|
+
return url.toString();
|
|
166
|
+
}
|
|
167
|
+
function assertPositiveInteger(name, value) {
|
|
168
|
+
if (!Number.isInteger(value) || value < 1)
|
|
169
|
+
throw new TypeError(`${name} must be a positive integer`);
|
|
170
|
+
}
|
|
171
|
+
function assertNonNegativeInteger(name, value) {
|
|
172
|
+
if (!Number.isInteger(value) || value < 0)
|
|
173
|
+
throw new TypeError(`${name} must be a non-negative integer`);
|
|
174
|
+
}
|
|
175
|
+
function wait(delayMs) {
|
|
176
|
+
return new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
8
177
|
}
|
package/package.json
CHANGED
|
@@ -1,26 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@portalshq/capability-video-delivery",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.6",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
|
-
"url": "git+https://github.com/portalshq/portals-cloud"
|
|
6
|
+
"url": "git+https://github.com/portalshq/portals-cloud.git",
|
|
7
|
+
"directory": "packages/video-delivery"
|
|
7
8
|
},
|
|
8
|
-
"description": "
|
|
9
|
+
"description": "Configured HLS stream delivery for application-owned programming and scheduling.",
|
|
9
10
|
"type": "module",
|
|
10
11
|
"main": "dist/index.js",
|
|
11
12
|
"types": "dist/index.d.ts",
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"types": "./dist/index.d.ts",
|
|
16
|
+
"default": "./dist/index.js"
|
|
17
|
+
},
|
|
18
|
+
"./browser": {
|
|
19
|
+
"types": "./dist/browser.d.ts",
|
|
20
|
+
"default": "./dist/browser.js"
|
|
21
|
+
}
|
|
22
|
+
},
|
|
12
23
|
"files": [
|
|
13
24
|
"dist"
|
|
14
25
|
],
|
|
15
26
|
"scripts": {
|
|
16
|
-
"build": "tsc -p tsconfig.json",
|
|
17
|
-
"typecheck": "tsc -p tsconfig.json --noEmit"
|
|
27
|
+
"build": "rm -rf dist && tsc -p tsconfig.json",
|
|
28
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
29
|
+
"test": "vitest run",
|
|
30
|
+
"test:coverage": "vitest run --coverage"
|
|
18
31
|
},
|
|
19
32
|
"dependencies": {
|
|
20
|
-
"@portalshq/contracts": "
|
|
33
|
+
"@portalshq/contracts": "^0.0.4"
|
|
21
34
|
},
|
|
22
35
|
"devDependencies": {
|
|
36
|
+
"@types/node": "^20.0.0",
|
|
37
|
+
"@vitest/coverage-v8": "^3.2.7",
|
|
23
38
|
"typescript": "^5.5.0",
|
|
24
|
-
"
|
|
39
|
+
"vitest": "^3.2.7"
|
|
40
|
+
},
|
|
41
|
+
"publishConfig": {
|
|
42
|
+
"access": "public",
|
|
43
|
+
"registry": "https://registry.npmjs.org/"
|
|
25
44
|
}
|
|
26
45
|
}
|
package/dist/vod-session.d.ts
DELETED