@codenkay/video-nsgplayer-core 5.2.0 → 5.4.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/dist/index.d.ts CHANGED
@@ -150,8 +150,10 @@ type StreamingConfig = {
150
150
  };
151
151
  /**
152
152
  * Same-origin BFF proxy for playlists, segments, and keys.
153
- * The playback API rejects the browser Origin and does not send CORS
154
- * headers, so cross-origin media URLs must be rewritten before fetch.
153
+ * The browser must not call the playback host directly: that host does not
154
+ * send CORS headers. The BFF must forward the validated viewer Origin on
155
+ * grant, refresh, and key requests. Cross-origin media URLs must be
156
+ * rewritten before fetch.
155
157
  * The builder is not called for URLs that are already on the page origin.
156
158
  */
157
159
  mediaProxyUrlBuilder?: (ctx: {
@@ -182,6 +184,26 @@ type StreamingConfig = {
182
184
  * a Cloudflare-blocked BFF (9–10× 502s).
183
185
  */
184
186
  keyProxyMaxFailures?: number;
187
+ /**
188
+ * When true, hls.js is configured with `appexHlsConfig(isLive)` (the
189
+ * Appextech reference profile) instead of the package buffer defaults.
190
+ * Off by default so existing integrations keep their current behavior.
191
+ */
192
+ useAppexHlsProfile?: boolean;
193
+ /**
194
+ * Native HLS (Safari) uses a BFF-managed session cookie instead of a token
195
+ * in the media URL. When true, a token renewal calls `onNativeAuthUpdate`
196
+ * and does not replace `video.src`, so playback does not reload.
197
+ */
198
+ nativeSessionMode?: boolean;
199
+ /**
200
+ * Called on native HLS when auth parameters change and
201
+ * `nativeSessionMode` is true. Update the BFF session/cookie here.
202
+ */
203
+ onNativeAuthUpdate?: (ctx: {
204
+ params: Record<string, string>;
205
+ url: string;
206
+ }) => void | Promise<void>;
185
207
  };
186
208
  type LoggingConfig = {
187
209
  enabled?: boolean;
@@ -231,6 +253,9 @@ type PlayerConfig = Required<{
231
253
  keyProxyUrlBuilder?: StreamingConfig["keyProxyUrlBuilder"];
232
254
  getKeyAccessToken?: StreamingConfig["getKeyAccessToken"];
233
255
  keyProxyMaxFailures?: StreamingConfig["keyProxyMaxFailures"];
256
+ useAppexHlsProfile?: StreamingConfig["useAppexHlsProfile"];
257
+ nativeSessionMode?: StreamingConfig["nativeSessionMode"];
258
+ onNativeAuthUpdate?: StreamingConfig["onNativeAuthUpdate"];
234
259
  };
235
260
  logging: Required<LoggingConfig>;
236
261
  debug: Required<DebugConfig>;
@@ -317,7 +342,7 @@ declare const PLAYBACK_RATES: readonly [0.5, 0.75, 1, 1.25, 1.5, 2];
317
342
  * and applies the new token on the next media request.
318
343
  */
319
344
  declare const DEFAULT_PLAYBACK_REFRESH_INTERVAL_MS = 45000;
320
- declare const PACKAGE_VERSION = "5.2.0";
345
+ declare const PACKAGE_VERSION = "5.4.0";
321
346
  declare const DEFAULT_PLAYER_BEHAVIOR: Required<PlayerBehaviorConfig>;
322
347
  declare const DEFAULT_CONTROLS: Required<ControlsConfig>;
323
348
  declare const DEFAULT_THEME: Required<ThemeConfig>;
@@ -352,6 +377,9 @@ type PlayerConfigPartial = Partial<{
352
377
  keyProxyUrlBuilder?: PlayerConfig["streaming"]["keyProxyUrlBuilder"];
353
378
  getKeyAccessToken?: PlayerConfig["streaming"]["getKeyAccessToken"];
354
379
  keyProxyMaxFailures?: PlayerConfig["streaming"]["keyProxyMaxFailures"];
380
+ useAppexHlsProfile?: PlayerConfig["streaming"]["useAppexHlsProfile"];
381
+ nativeSessionMode?: PlayerConfig["streaming"]["nativeSessionMode"];
382
+ onNativeAuthUpdate?: PlayerConfig["streaming"]["onNativeAuthUpdate"];
355
383
  };
356
384
  logging: Partial<PlayerConfig["logging"]>;
357
385
  debug: Partial<PlayerConfig["debug"]>;
@@ -482,6 +510,16 @@ type HlsEngineOptions = {
482
510
  maxBufferSize: number;
483
511
  fatalRecoveryLimit: number;
484
512
  };
513
+ /** Apply `appexHlsConfig(isLive)` on top of `hlsConfig` (opt-in). */
514
+ useAppexHlsProfile?: boolean;
515
+ /** Selects the live variant of the Appextech profile. */
516
+ isLive?: boolean;
517
+ /**
518
+ * Native HLS only: auth is carried by a BFF session cookie. A token renewal
519
+ * calls `onNativeAuthUpdate` and does not replace `video.src`.
520
+ */
521
+ nativeSessionMode?: boolean;
522
+ onNativeAuthUpdate?: StreamingConfig["onNativeAuthUpdate"];
485
523
  logger: Logger;
486
524
  callbacks: HlsEngineCallbacks;
487
525
  };
@@ -513,6 +551,18 @@ declare class HlsEngine {
513
551
  private applyStartPositionAndAutoplay;
514
552
  private bindMediaEvents;
515
553
  updateAuthParams(): void;
554
+ /**
555
+ * Native HLS: apply new auth parameters without replacing `video.src`.
556
+ *
557
+ * With `nativeSessionMode`, `onNativeAuthUpdate` receives the params and the
558
+ * current request URL so the BFF session/cookie can be renewed; the element
559
+ * keeps playing. Without it this method is a no-op unless a callback exists,
560
+ * because rewriting `video.src` would restart the stream (use
561
+ * `updateAuthParams()` for that reload path).
562
+ *
563
+ * Returns true when a callback handled the update.
564
+ */
565
+ updateNativeAuthParams(params: Record<string, string>): Promise<boolean>;
516
566
  private playbackRequestUrl;
517
567
  /**
518
568
  * Auth params are already on the shared store, so the next request uses
@@ -596,8 +646,16 @@ declare enum PlayerErrorCode {
596
646
  PLAYBACK_ERROR = "PLAYBACK_ERROR",
597
647
  UNSUPPORTED_BROWSER = "UNSUPPORTED_BROWSER",
598
648
  AUTOPLAY_BLOCKED = "AUTOPLAY_BLOCKED",
649
+ /** Student lease: the viewer already has an active session on another platform. */
650
+ PLATFORM_IN_USE = "PLATFORM_IN_USE",
651
+ /** Student lease: live media is still being prepared. Retry shortly. */
652
+ PLAYBACK_NOT_READY = "PLAYBACK_NOT_READY",
599
653
  UNKNOWN = "UNKNOWN"
600
654
  }
655
+ /** Student playback API error code: another platform holds the lease (HTTP 409). */
656
+ declare const PLATFORM_IN_USE: "PLATFORM_IN_USE";
657
+ /** Student playback API error code: live media is not ready yet. */
658
+ declare const PLAYBACK_NOT_READY: "PLAYBACK_NOT_READY";
601
659
  type PlayerError = {
602
660
  code: PlayerErrorCode;
603
661
  message: string;
@@ -610,6 +668,250 @@ type PlayerError = {
610
668
  declare function createPlayerError(code: PlayerErrorCode, message: string, options?: Partial<Omit<PlayerError, "code" | "message" | "timestamp">>): PlayerError;
611
669
  declare function redactSensitive(input: string): string;
612
670
 
671
+ /**
672
+ * Appextech reference hls.js profile (matches the Appextech student sample).
673
+ *
674
+ * This is an opt-in helper. The package defaults in `DEFAULT_PLAYER_CONFIG`
675
+ * are unchanged. Use it in one of two ways:
676
+ *
677
+ * - Pass `appexHlsConfig(isLive)` to your own `new Hls({...})`.
678
+ * - Set `streaming.useAppexHlsProfile: true`. The engine then applies this
679
+ * profile on top of its own settings (loader, worker, start position). The
680
+ * profile wins for the keys it defines.
681
+ */
682
+ type AppexHlsConfig = {
683
+ maxBufferLength: number;
684
+ maxMaxBufferLength: number;
685
+ maxBufferSize: number;
686
+ backBufferLength: number;
687
+ startLevel: number;
688
+ abrEwmaDefaultEstimate: number;
689
+ abrBandWidthFactor: number;
690
+ abrBandWidthUpFactor: number;
691
+ maxStarvationDelay: number;
692
+ lowLatencyMode: boolean;
693
+ liveSyncDurationCount: number;
694
+ liveMaxLatencyDurationCount: number;
695
+ maxLiveSyncPlaybackRate: number;
696
+ };
697
+ /** hls.js options for Appextech playback. Live uses a shorter forward buffer. */
698
+ declare function hlsConfig(isLive?: boolean): AppexHlsConfig;
699
+ /** Alias of `hlsConfig`, named to avoid clashing with other `hlsConfig` values. */
700
+ declare const appexHlsConfig: typeof hlsConfig;
701
+
702
+ /** Selector for caption tracks owned by the SDK or the Appextech sample. */
703
+ declare const SDK_SUBTITLE_TRACK_SELECTOR = "track[data-sample-subtitle],track[data-appextech-subtitle]";
704
+ /**
705
+ * Restore only SDK-owned captions after a media source is renewed.
706
+ * Tracks that the host app added without the data attributes are untouched.
707
+ * Pass an empty language to turn every SDK-owned track off.
708
+ */
709
+ declare function restoreSubtitleSelection(video: Pick<HTMLVideoElement, "querySelectorAll">, language?: string | null): void;
710
+
711
+ /** Heartbeat cadence for an active student lease. */
712
+ declare const STUDENT_HEARTBEAT_INTERVAL_MS = 15000;
713
+ /** Per-request timeout for lease calls. */
714
+ declare const STUDENT_REQUEST_TIMEOUT_MS = 10000;
715
+ /** `PLAYBACK_NOT_READY` retry policy: 20 attempts, 3s apart, 60s deadline. */
716
+ declare const STUDENT_NOT_READY_MAX_ATTEMPTS = 20;
717
+ declare const STUDENT_NOT_READY_RETRY_DELAY_MS = 3000;
718
+ declare const STUDENT_NOT_READY_DEADLINE_MS = 60000;
719
+ type StudentMediaType = "video" | "audio";
720
+ type StudentLeaseConfig = {
721
+ /** HTTPS origin of the student playback API (no path, query, or userinfo). */
722
+ baseUrl: string;
723
+ /** Student identifier. Required, max 200 characters. */
724
+ userId: string;
725
+ /** Student playback bearer token. Never pass a management API key here. */
726
+ authorizationToken: string;
727
+ /** Text shown as an intermittent on-screen watermark. */
728
+ watermarkText?: string | null;
729
+ /** Only `web` is supported by the browser client. Defaults to `web`. */
730
+ platform?: "web";
731
+ };
732
+ type StudentLease = {
733
+ token: string;
734
+ watermark_text?: string;
735
+ [key: string]: unknown;
736
+ };
737
+ /** `data` payload returned by `/student/playback`. */
738
+ type StudentPlaybackData = {
739
+ student_session: StudentLease;
740
+ [key: string]: unknown;
741
+ };
742
+ type StudentVideoLike = Pick<HTMLVideoElement, "addEventListener" | "removeEventListener" | "pause" | "paused" | "ended"> & {
743
+ parentElement?: HTMLElement | null;
744
+ };
745
+ type StudentLeaseClientOptions = {
746
+ /** Called when a heartbeat fails and the lease has been released. */
747
+ onError?: (error: StudentLeaseError) => void;
748
+ /** Container for the watermark overlay. Defaults to `video.parentElement`. */
749
+ watermarkContainer?: HTMLElement | null;
750
+ /** Injected for tests or a wrapped transport. Defaults to `globalThis.fetch`. */
751
+ fetch?: typeof fetch;
752
+ /** Injected delay used between `PLAYBACK_NOT_READY` retries. */
753
+ sleep?: (ms: number) => Promise<void>;
754
+ /** Injected clock for the retry deadline. Defaults to `Date.now`. */
755
+ now?: () => number;
756
+ /** Injected randomness for watermark placement. Defaults to `Math.random`. */
757
+ random?: () => number;
758
+ };
759
+ declare class StudentLeaseError extends Error {
760
+ readonly code?: string;
761
+ readonly activePlatform?: string;
762
+ readonly status?: number;
763
+ constructor(message: string, details?: {
764
+ code?: string;
765
+ activePlatform?: string;
766
+ status?: number;
767
+ });
768
+ }
769
+ /** Map an API error payload to a user-facing error. Exported for BFF reuse. */
770
+ declare function mapStudentLeaseError(status: number, payload: unknown): StudentLeaseError;
771
+ /**
772
+ * Online-institution student playback lease: acquire (`/student/playback`),
773
+ * keep alive (`/student/heartbeat` every 15s), and release
774
+ * (`/student/release` on stop, `ended`, or `pagehide`).
775
+ *
776
+ * Ported from the Appextech student sample. Never pass a management API key.
777
+ */
778
+ declare class StudentLeaseClient {
779
+ private readonly video;
780
+ private readonly config;
781
+ private readonly onError;
782
+ private readonly fetchImpl;
783
+ private readonly sleep;
784
+ private readonly now;
785
+ private readonly random;
786
+ private readonly container;
787
+ private watermarkEl;
788
+ private active;
789
+ private version;
790
+ private closed;
791
+ private inFlight;
792
+ private heartbeatTimer;
793
+ private watermarkTimer;
794
+ private hideTimer;
795
+ private readonly onEnded;
796
+ private readonly onPageHide;
797
+ constructor(video: StudentVideoLike, config: StudentLeaseConfig, options?: StudentLeaseClientOptions);
798
+ /** Replace the student bearer token (for example after the BFF renews it). */
799
+ updateAuthorizationToken(value: string): void;
800
+ /** True while a lease is held. */
801
+ get isActive(): boolean;
802
+ /**
803
+ * Acquire a lease. Retries `PLAYBACK_NOT_READY` up to 20 attempts, 3s apart,
804
+ * inside a 60s deadline. Rejects with `StudentLeaseError` otherwise
805
+ * (`PLATFORM_IN_USE` carries `activePlatform`).
806
+ */
807
+ start(videoId: string, mediaType?: StudentMediaType): Promise<StudentPlaybackData>;
808
+ /** Send one heartbeat. On failure the lease is released and `onError` runs. */
809
+ heartbeat(): Promise<void>;
810
+ /**
811
+ * Show the watermark at random positions every 30-90s for 5s while the video
812
+ * plays. An empty string clears it. Requires an active lease.
813
+ */
814
+ scheduleWatermark(text: string): void;
815
+ /** Pause the video, stop timers, and release the lease (keepalive). */
816
+ stop(): Promise<void>;
817
+ /** Release the lease, remove the overlay, and detach listeners. */
818
+ close(): Promise<void>;
819
+ private request;
820
+ private createWatermarkElement;
821
+ private showWatermark;
822
+ private hideWatermark;
823
+ }
824
+
825
+ /**
826
+ * Transport used for analytics calls. A BFF can wrap it to rewrite the URL to
827
+ * `/api/media?url=...`. Resolve with the parsed JSON body; reject on failure.
828
+ */
829
+ type AnalyticsSend = (url: string, body: Record<string, unknown>, opts?: {
830
+ keepalive?: boolean;
831
+ }) => Promise<unknown>;
832
+ /** Session returned by `analytics/start`. */
833
+ type AnalyticsSession = {
834
+ token: string;
835
+ event_url: string;
836
+ [key: string]: unknown;
837
+ };
838
+ type AnalyticsVideoLike = Pick<HTMLVideoElement, "addEventListener" | "removeEventListener" | "paused" | "ended" | "seeking" | "readyState" | "currentTime" | "playbackRate">;
839
+ type AnalyticsClientOptions = {
840
+ video: AnalyticsVideoLike;
841
+ /** Playback API origin. `event_url` is resolved against it. */
842
+ origin: string;
843
+ videoKey: string;
844
+ /** Playback token for `analytics/start`. May be a getter after a refresh. */
845
+ playbackToken: string | (() => string);
846
+ deviceId: string;
847
+ /** Defaults to `web`. */
848
+ platform?: string;
849
+ /** Defaults to a JSON `fetch` POST. */
850
+ send?: AnalyticsSend;
851
+ /** Event heartbeat cadence. Default 15000. */
852
+ heartbeatIntervalMs?: number;
853
+ /** Watch-time sampling cadence. Default 1000. */
854
+ sampleIntervalMs?: number;
855
+ /** `playing` is true only if time advanced within this window. Default 5000. */
856
+ progressWindowMs?: number;
857
+ /** Injected monotonic clock. Defaults to `performance.now`. */
858
+ now?: () => number;
859
+ /** Receives start and heartbeat failures. Failures never throw. */
860
+ onError?: (error: unknown) => void;
861
+ };
862
+ type AnalyticsEventBody = {
863
+ token: string;
864
+ seq: number;
865
+ watched_seconds: number;
866
+ playing: boolean;
867
+ ended: boolean;
868
+ };
869
+ /**
870
+ * Watch-time analytics: `analytics/start`, then event heartbeats carrying
871
+ * `watched_seconds`, `seq`, `playing`, and `ended`. The final heartbeat uses
872
+ * `keepalive` so it can complete during page unload.
873
+ *
874
+ * Failures are reported through `onError` and never interrupt playback.
875
+ */
876
+ declare class AnalyticsClient {
877
+ private readonly options;
878
+ private session;
879
+ private watched;
880
+ private sequence;
881
+ private finished;
882
+ private destroyed;
883
+ private lastTime;
884
+ private lastPosition;
885
+ private progressedAt;
886
+ private sampleTimer;
887
+ private heartbeatTimer;
888
+ private readonly send;
889
+ private readonly now;
890
+ private readonly onError;
891
+ private readonly onPause;
892
+ private readonly onEnded;
893
+ private readonly onPageHide;
894
+ constructor(options: AnalyticsClientOptions);
895
+ /** Total seconds credited as watched so far. */
896
+ get watchedSeconds(): number;
897
+ /** Session from `analytics/start`, or null before it resolves. */
898
+ get currentSession(): AnalyticsSession | null;
899
+ /**
900
+ * POST `{origin}/media/{videoKey}/analytics/start` and begin sampling.
901
+ * Resolves to the session, or null on failure (reported via `onError`).
902
+ */
903
+ start(): Promise<AnalyticsSession | null>;
904
+ /** Credit elapsed wall time when the video genuinely advanced. */
905
+ sample(): void;
906
+ /**
907
+ * Send an event heartbeat. `end: true` marks the session finished, sends with
908
+ * `keepalive`, and suppresses further heartbeats.
909
+ */
910
+ heartbeat(end?: boolean): Promise<void>;
911
+ /** Send the final heartbeat (if started) and detach everything. */
912
+ destroy(): Promise<void>;
913
+ }
914
+
613
915
  /**
614
916
  * Manages provider auth-token lifecycle (independent from signed playback URL).
615
917
  * Single-flight refresh; never stores clientSecret.
@@ -795,4 +1097,4 @@ declare function redactValue(key: string, value: unknown, seen?: WeakSet<object>
795
1097
  */
796
1098
  declare function redactObject(obj: Record<string, unknown>, seen?: WeakSet<object>, depth?: number): Record<string, unknown>;
797
1099
 
798
- export { type AccessibilityConfig, type AnalyticsConfig, type AuthConfig, AuthManager, AuthParamsStore, type AuthToken, type AuthTokenProviderContext, type BufferedRange, type ControlsConfig, type CreateVideoPlayerOptions, DEFAULT_CONTROLS, DEFAULT_LIVE_EDGE_TOLERANCE_SECONDS, DEFAULT_PLAYBACK_REFRESH_INTERVAL_MS, DEFAULT_PLAYER_BEHAVIOR, DEFAULT_PLAYER_CONFIG, DEFAULT_THEME, DEFAULT_WATERMARK, type DebugConfig, EventEmitter, type HlsLoaderConstructor, type HlsModuleLike, type HlsQualityLevel, type HlsSupportMode, KEY_PROXY_MAX_FAILURES, type LiveMediaSnapshot, type LoggingConfig, PACKAGE_VERSION, PLAYBACK_RATES, type PlayIconPreset, type PlaybackCredentialConfig, type PlaybackRate, type PlaybackSource, type PlaybackSourceContext, PlaybackSourceManager, type PlayerAudioTrack, type PlayerBehaviorConfig, type PlayerConfig, type PlayerDiagnostics, type PlayerError, PlayerErrorCode, type PlayerEventMap, type PlayerSkipSeconds, type PlayerState, type PlayerTextTrack, type PlayerZoomLevel, type QualitySelection, RefreshManager, SECRET_SCAN_MAX_DEPTH, type SeekToLiveResult, type StreamingConfig, type TextTrackSelection, type ThemeConfig, type VideoPlayer, type WatermarkConfig, assertNoSecretsInConfig, createAuthParamsLoader, createPlayerError, createVideoPlayer, getLiveEdgeTime, isAtLiveEdge, isEncryptionKeyUrl, isLivePlaylistUrl, isPlainObject, isSameOriginHttpUrl, mergePlayerConfig, redactObject, redactSensitive, redactValue, resolveBuiltinHlsLoader, rewriteHlsRequestUrl, seekToLiveEdge, themeToCssVars };
1100
+ export { type AccessibilityConfig, AnalyticsClient, type AnalyticsClientOptions, type AnalyticsConfig, type AnalyticsEventBody, type AnalyticsSend, type AnalyticsSession, type AppexHlsConfig, type AuthConfig, AuthManager, AuthParamsStore, type AuthToken, type AuthTokenProviderContext, type BufferedRange, type ControlsConfig, type CreateVideoPlayerOptions, DEFAULT_CONTROLS, DEFAULT_LIVE_EDGE_TOLERANCE_SECONDS, DEFAULT_PLAYBACK_REFRESH_INTERVAL_MS, DEFAULT_PLAYER_BEHAVIOR, DEFAULT_PLAYER_CONFIG, DEFAULT_THEME, DEFAULT_WATERMARK, type DebugConfig, EventEmitter, type HlsLoaderConstructor, type HlsModuleLike, type HlsQualityLevel, type HlsSupportMode, KEY_PROXY_MAX_FAILURES, type LiveMediaSnapshot, type LoggingConfig, PACKAGE_VERSION, PLATFORM_IN_USE, PLAYBACK_NOT_READY, PLAYBACK_RATES, type PlayIconPreset, type PlaybackCredentialConfig, type PlaybackRate, type PlaybackSource, type PlaybackSourceContext, PlaybackSourceManager, type PlayerAudioTrack, type PlayerBehaviorConfig, type PlayerConfig, type PlayerDiagnostics, type PlayerError, PlayerErrorCode, type PlayerEventMap, type PlayerSkipSeconds, type PlayerState, type PlayerTextTrack, type PlayerZoomLevel, type QualitySelection, RefreshManager, SDK_SUBTITLE_TRACK_SELECTOR, SECRET_SCAN_MAX_DEPTH, STUDENT_HEARTBEAT_INTERVAL_MS, STUDENT_NOT_READY_DEADLINE_MS, STUDENT_NOT_READY_MAX_ATTEMPTS, STUDENT_NOT_READY_RETRY_DELAY_MS, STUDENT_REQUEST_TIMEOUT_MS, type SeekToLiveResult, type StreamingConfig, type StudentLease, StudentLeaseClient, type StudentLeaseClientOptions, type StudentLeaseConfig, StudentLeaseError, type StudentMediaType, type StudentPlaybackData, type TextTrackSelection, type ThemeConfig, type VideoPlayer, type WatermarkConfig, appexHlsConfig, assertNoSecretsInConfig, createAuthParamsLoader, createPlayerError, createVideoPlayer, getLiveEdgeTime, hlsConfig, isAtLiveEdge, isEncryptionKeyUrl, isLivePlaylistUrl, isPlainObject, isSameOriginHttpUrl, mapStudentLeaseError, mergePlayerConfig, redactObject, redactSensitive, redactValue, resolveBuiltinHlsLoader, restoreSubtitleSelection, rewriteHlsRequestUrl, seekToLiveEdge, themeToCssVars };