electron-cast 0.1.1 → 0.2.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.
@@ -49,7 +49,7 @@ export function installChromeCast(bridgeKey: string): boolean {
49
49
  const SenderPlatform = { CHROME: "chrome", IOS: "ios", ANDROID: "android" };
50
50
  const SessionStatus = { CONNECTED: "connected", DISCONNECTED: "disconnected", STOPPED: "stopped" };
51
51
  const VolumeControlType = { ATTENUATION: "attenuation", FIXED: "fixed", MASTER: "master" };
52
- const media = { DEFAULT_MEDIA_RECEIVER_APP_ID: "CC1AD845" };
52
+ const MEDIA_NAMESPACE = "urn:x-cast:com.google.cast.media";
53
53
 
54
54
  class Timeout {
55
55
  requestSession = 60000;
@@ -185,6 +185,722 @@ export function installChromeCast(bridgeKey: string): boolean {
185
185
  }
186
186
  }
187
187
 
188
+ const PlayerState = { IDLE: "IDLE", PLAYING: "PLAYING", PAUSED: "PAUSED", BUFFERING: "BUFFERING" };
189
+ const MediaCommand = { PAUSE: "pause", SEEK: "seek", STREAM_VOLUME: "stream_volume", STREAM_MUTE: "stream_mute" };
190
+ const MetadataType = { GENERIC: 0, MOVIE: 1, TV_SHOW: 2, MUSIC_TRACK: 3, PHOTO: 4 };
191
+ const RepeatMode = { OFF: "REPEAT_OFF", ALL: "REPEAT_ALL", SINGLE: "REPEAT_SINGLE", ALL_AND_SHUFFLE: "REPEAT_ALL_AND_SHUFFLE" };
192
+ const ResumeState = { PLAYBACK_START: "PLAYBACK_START", PLAYBACK_PAUSE: "PLAYBACK_PAUSE" };
193
+ const StreamType = { BUFFERED: "BUFFERED", LIVE: "LIVE", OTHER: "OTHER" };
194
+ const IdleReason = { CANCELLED: "CANCELLED", INTERRUPTED: "INTERRUPTED", FINISHED: "FINISHED", ERROR: "ERROR" };
195
+ const TrackType = { TEXT: "TEXT", AUDIO: "AUDIO", VIDEO: "VIDEO" };
196
+ const TextTrackType = { SUBTITLES: "SUBTITLES", CAPTIONS: "CAPTIONS", DESCRIPTIONS: "DESCRIPTIONS", CHAPTERS: "CHAPTERS", METADATA: "METADATA" };
197
+ const TextTrackEdgeType = { NONE: "NONE", OUTLINE: "OUTLINE", DROP_SHADOW: "DROP_SHADOW", RAISED: "RAISED", DEPRESSED: "DEPRESSED" };
198
+ const TextTrackWindowType = { NONE: "NONE", NORMAL: "NORMAL", ROUNDED_CORNERS: "ROUNDED_CORNERS" };
199
+ const TextTrackFontGenericFamily = { SANS_SERIF: "SANS_SERIF", MONOSPACED_SANS_SERIF: "MONOSPACED_SANS_SERIF", SERIF: "SERIF", MONOSPACED_SERIF: "MONOSPACED_SERIF", CASUAL: "CASUAL", CURSIVE: "CURSIVE", SMALL_CAPITALS: "SMALL_CAPITALS" };
200
+ const TextTrackFontStyle = { NORMAL: "NORMAL", BOLD: "BOLD", BOLD_ITALIC: "BOLD_ITALIC", ITALIC: "ITALIC" };
201
+
202
+ class MediaInfo {
203
+ contentId: any;
204
+ streamType: any;
205
+ contentType: any;
206
+ metadata: any;
207
+ duration: any;
208
+ tracks: any;
209
+ textTrackStyle: any;
210
+ customData: any;
211
+ constructor(contentId: any, contentType: any) {
212
+ this.contentId = contentId;
213
+ this.streamType = "BUFFERED";
214
+ this.contentType = contentType;
215
+ this.metadata = null;
216
+ this.duration = null;
217
+ this.tracks = null;
218
+ this.textTrackStyle = null;
219
+ this.customData = null;
220
+ }
221
+ }
222
+
223
+ class LoadRequest {
224
+ type: any;
225
+ requestId: any;
226
+ sessionId: any;
227
+ media: any;
228
+ activeTrackIds: any;
229
+ autoplay: any;
230
+ currentTime: any;
231
+ customData: any;
232
+ constructor(media: any) {
233
+ this.type = "LOAD";
234
+ this.requestId = 0;
235
+ this.sessionId = null;
236
+ this.media = media;
237
+ this.activeTrackIds = null;
238
+ this.autoplay = true;
239
+ this.currentTime = null;
240
+ this.customData = null;
241
+ }
242
+ }
243
+
244
+ class QueueItem {
245
+ itemId: any;
246
+ media: any;
247
+ autoplay: any;
248
+ startTime: any;
249
+ playbackDuration: any;
250
+ preloadTime: any;
251
+ activeTrackIds: any;
252
+ customData: any;
253
+ constructor(media: any) {
254
+ this.itemId = null;
255
+ this.media = media;
256
+ this.autoplay = true;
257
+ this.startTime = 0;
258
+ this.playbackDuration = null;
259
+ this.preloadTime = 0;
260
+ this.activeTrackIds = null;
261
+ this.customData = null;
262
+ }
263
+ }
264
+
265
+ class QueueLoadRequest {
266
+ type: any;
267
+ requestId: any;
268
+ sessionId: any;
269
+ items: any;
270
+ startIndex: any;
271
+ repeatMode: any;
272
+ customData: any;
273
+ constructor(items: any) {
274
+ this.type = "QUEUE_LOAD";
275
+ this.requestId = null;
276
+ this.sessionId = null;
277
+ this.items = items;
278
+ this.startIndex = 0;
279
+ this.repeatMode = "REPEAT_OFF";
280
+ this.customData = null;
281
+ }
282
+ }
283
+
284
+ class QueueInsertItemsRequest {
285
+ type: any;
286
+ requestId: any;
287
+ sessionId: any;
288
+ items: any;
289
+ insertBefore: any;
290
+ customData: any;
291
+ constructor(items: any) {
292
+ this.type = "QUEUE_INSERT";
293
+ this.requestId = null;
294
+ this.sessionId = null;
295
+ this.items = items;
296
+ this.insertBefore = null;
297
+ this.customData = null;
298
+ }
299
+ }
300
+
301
+ class QueueRemoveItemsRequest {
302
+ type: any;
303
+ requestId: any;
304
+ sessionId: any;
305
+ itemIds: any;
306
+ customData: any;
307
+ constructor(itemIds: any) {
308
+ this.type = "QUEUE_REMOVE";
309
+ this.requestId = null;
310
+ this.sessionId = null;
311
+ this.itemIds = itemIds;
312
+ this.customData = null;
313
+ }
314
+ }
315
+
316
+ class QueueReorderItemsRequest {
317
+ type: any;
318
+ requestId: any;
319
+ sessionId: any;
320
+ itemIds: any;
321
+ insertBefore: any;
322
+ customData: any;
323
+ constructor(itemIds: any) {
324
+ this.type = "QUEUE_REORDER";
325
+ this.requestId = null;
326
+ this.sessionId = null;
327
+ this.itemIds = itemIds;
328
+ this.insertBefore = null;
329
+ this.customData = null;
330
+ }
331
+ }
332
+
333
+ class QueueUpdateItemsRequest {
334
+ type: any;
335
+ requestId: any;
336
+ sessionId: any;
337
+ items: any;
338
+ customData: any;
339
+ constructor(items: any) {
340
+ this.type = "QUEUE_UPDATE";
341
+ this.requestId = null;
342
+ this.sessionId = null;
343
+ this.items = items;
344
+ this.customData = null;
345
+ }
346
+ }
347
+
348
+ class QueueSetPropertiesRequest {
349
+ type: any;
350
+ requestId: any;
351
+ sessionId: any;
352
+ repeatMode: any;
353
+ customData: any;
354
+ constructor() {
355
+ this.type = "QUEUE_UPDATE";
356
+ this.requestId = null;
357
+ this.sessionId = null;
358
+ this.repeatMode = null;
359
+ this.customData = null;
360
+ }
361
+ }
362
+
363
+ class QueueJumpRequest {
364
+ type: any;
365
+ requestId: any;
366
+ sessionId: any;
367
+ currentItemId: any;
368
+ jump: any;
369
+ customData: any;
370
+ constructor() {
371
+ this.type = "QUEUE_UPDATE";
372
+ this.requestId = null;
373
+ this.sessionId = null;
374
+ this.currentItemId = null;
375
+ this.jump = null;
376
+ this.customData = null;
377
+ }
378
+ }
379
+
380
+ class SeekRequest {
381
+ currentTime: any;
382
+ resumeState: any;
383
+ customData: any;
384
+ constructor() {
385
+ this.currentTime = null;
386
+ this.resumeState = null;
387
+ this.customData = null;
388
+ }
389
+ }
390
+
391
+ class VolumeRequest {
392
+ volume: any;
393
+ customData: any;
394
+ constructor(volume: any) {
395
+ this.volume = volume;
396
+ this.customData = null;
397
+ }
398
+ }
399
+
400
+ class PlayRequest {
401
+ customData: any;
402
+ constructor() {
403
+ this.customData = null;
404
+ }
405
+ }
406
+
407
+ class PauseRequest {
408
+ customData: any;
409
+ constructor() {
410
+ this.customData = null;
411
+ }
412
+ }
413
+
414
+ class StopRequest {
415
+ customData: any;
416
+ constructor() {
417
+ this.customData = null;
418
+ }
419
+ }
420
+
421
+ class GetStatusRequest {
422
+ customData: any;
423
+ constructor() {
424
+ this.customData = null;
425
+ }
426
+ }
427
+
428
+ class EditTracksInfoRequest {
429
+ requestId: any;
430
+ activeTrackIds: any;
431
+ textTrackStyle: any;
432
+ constructor(activeTrackIds: any, textTrackStyle: any) {
433
+ this.requestId = 0;
434
+ this.activeTrackIds = activeTrackIds ?? null;
435
+ this.textTrackStyle = textTrackStyle ?? null;
436
+ }
437
+ }
438
+
439
+ class Track {
440
+ trackId: any;
441
+ trackContentId: any;
442
+ trackContentType: any;
443
+ type: any;
444
+ name: any;
445
+ language: any;
446
+ subtype: any;
447
+ customData: any;
448
+ constructor(trackId: any, type: any) {
449
+ this.trackId = trackId;
450
+ this.trackContentId = null;
451
+ this.trackContentType = null;
452
+ this.type = type;
453
+ this.name = null;
454
+ this.language = null;
455
+ this.subtype = null;
456
+ this.customData = null;
457
+ }
458
+ }
459
+
460
+ class TextTrackStyle {
461
+ foregroundColor: any;
462
+ backgroundColor: any;
463
+ edgeType: any;
464
+ edgeColor: any;
465
+ windowType: any;
466
+ windowColor: any;
467
+ windowRoundedCornerRadius: any;
468
+ fontScale: any;
469
+ fontFamily: any;
470
+ fontGenericFamily: any;
471
+ fontStyle: any;
472
+ customData: any;
473
+ constructor() {
474
+ this.foregroundColor = null;
475
+ this.backgroundColor = null;
476
+ this.edgeType = null;
477
+ this.edgeColor = null;
478
+ this.windowType = null;
479
+ this.windowColor = null;
480
+ this.windowRoundedCornerRadius = null;
481
+ this.fontScale = null;
482
+ this.fontFamily = null;
483
+ this.fontGenericFamily = null;
484
+ this.fontStyle = null;
485
+ this.customData = null;
486
+ }
487
+ }
488
+
489
+ class GenericMediaMetadata {
490
+ type: any;
491
+ metadataType: any;
492
+ title: any;
493
+ subtitle: any;
494
+ images: any;
495
+ releaseYear: any;
496
+ releaseDate: any;
497
+ constructor() {
498
+ this.type = 0;
499
+ this.metadataType = 0;
500
+ this.title = null;
501
+ this.subtitle = null;
502
+ this.images = null;
503
+ this.releaseYear = null;
504
+ this.releaseDate = null;
505
+ }
506
+ }
507
+
508
+ class MovieMediaMetadata {
509
+ type: any;
510
+ metadataType: any;
511
+ title: any;
512
+ studio: any;
513
+ subtitle: any;
514
+ images: any;
515
+ releaseYear: any;
516
+ releaseDate: any;
517
+ constructor() {
518
+ this.type = 1;
519
+ this.metadataType = 1;
520
+ this.title = null;
521
+ this.studio = null;
522
+ this.subtitle = null;
523
+ this.images = null;
524
+ this.releaseYear = null;
525
+ this.releaseDate = null;
526
+ }
527
+ }
528
+
529
+ class TvShowMediaMetadata {
530
+ type: any;
531
+ metadataType: any;
532
+ seriesTitle: any;
533
+ title: any;
534
+ episodeTitle: any;
535
+ seasonNumber: any;
536
+ season: any;
537
+ episodeNumber: any;
538
+ episode: any;
539
+ images: any;
540
+ releaseYear: any;
541
+ originalAirdate: any;
542
+ constructor() {
543
+ this.type = 2;
544
+ this.metadataType = 2;
545
+ this.seriesTitle = null;
546
+ this.title = null;
547
+ this.episodeTitle = null;
548
+ this.seasonNumber = null;
549
+ this.season = null;
550
+ this.episodeNumber = null;
551
+ this.episode = null;
552
+ this.images = null;
553
+ this.releaseYear = null;
554
+ this.originalAirdate = null;
555
+ }
556
+ }
557
+
558
+ class MusicTrackMediaMetadata {
559
+ type: any;
560
+ metadataType: any;
561
+ albumName: any;
562
+ title: any;
563
+ albumArtist: any;
564
+ artist: any;
565
+ composer: any;
566
+ songName: any;
567
+ artistName: any;
568
+ trackNumber: any;
569
+ discNumber: any;
570
+ images: any;
571
+ releaseYear: any;
572
+ releaseDate: any;
573
+ constructor() {
574
+ this.type = 3;
575
+ this.metadataType = 3;
576
+ this.albumName = null;
577
+ this.title = null;
578
+ this.albumArtist = null;
579
+ this.artist = null;
580
+ this.composer = null;
581
+ this.songName = null;
582
+ this.artistName = null;
583
+ this.trackNumber = null;
584
+ this.discNumber = null;
585
+ this.images = null;
586
+ this.releaseYear = null;
587
+ this.releaseDate = null;
588
+ }
589
+ }
590
+
591
+ class PhotoMediaMetadata {
592
+ type: any;
593
+ metadataType: any;
594
+ title: any;
595
+ artist: any;
596
+ location: any;
597
+ images: any;
598
+ latitude: any;
599
+ longitude: any;
600
+ width: any;
601
+ height: any;
602
+ creationDateTime: any;
603
+ constructor() {
604
+ this.type = 4;
605
+ this.metadataType = 4;
606
+ this.title = null;
607
+ this.artist = null;
608
+ this.location = null;
609
+ this.images = null;
610
+ this.latitude = null;
611
+ this.longitude = null;
612
+ this.width = null;
613
+ this.height = null;
614
+ this.creationDateTime = null;
615
+ }
616
+ }
617
+
618
+ class Media {
619
+ sessionId: any;
620
+ mediaSessionId: any;
621
+ media: any;
622
+ playbackRate: any;
623
+ playerState: any;
624
+ currentTime: any;
625
+ supportedMediaCommands: any[];
626
+ volume: any;
627
+ idleReason: any;
628
+ activeTrackIds: any;
629
+ customData: any;
630
+ currentItemId: any;
631
+ loadingItemId: any;
632
+ preloadedItemId: any;
633
+ items: any;
634
+ repeatMode: any;
635
+ liveSeekableRange: any;
636
+ breakStatus: any;
637
+ videoInfo: any;
638
+ queueData: any;
639
+ _updateListeners: any[];
640
+ _lastUpdate: number;
641
+ _announced: boolean;
642
+ constructor(sessionId: any, mediaSessionId: any) {
643
+ this.sessionId = sessionId;
644
+ this.mediaSessionId = mediaSessionId;
645
+ this.media = null;
646
+ this.playbackRate = 1;
647
+ this.playerState = "IDLE";
648
+ this.currentTime = 0;
649
+ this.supportedMediaCommands = [];
650
+ this.volume = new Volume();
651
+ this.idleReason = null;
652
+ this.activeTrackIds = null;
653
+ this.customData = null;
654
+ this.currentItemId = null;
655
+ this.loadingItemId = null;
656
+ this.preloadedItemId = null;
657
+ this.items = null;
658
+ this.repeatMode = "REPEAT_OFF";
659
+ this.liveSeekableRange = null;
660
+ this.breakStatus = null;
661
+ this.videoInfo = null;
662
+ this.queueData = null;
663
+ this._updateListeners = [];
664
+ this._lastUpdate = 0;
665
+ this._announced = false;
666
+ }
667
+
668
+ addUpdateListener(fn: any): void {
669
+ if (typeof fn === "function" && !this._updateListeners.includes(fn)) this._updateListeners.push(fn);
670
+ }
671
+
672
+ removeUpdateListener(fn: any): void {
673
+ const i = this._updateListeners.indexOf(fn);
674
+ if (i >= 0) this._updateListeners.splice(i, 1);
675
+ }
676
+
677
+ supportsCommand(cmd: any): boolean {
678
+ return this.supportedMediaCommands.includes(cmd);
679
+ }
680
+
681
+ getEstimatedTime(): any {
682
+ if (this.playerState === "PLAYING") {
683
+ let t = this.currentTime + this.playbackRate * (Date.now() - this._lastUpdate) / 1000;
684
+ const duration = this.media && this.media.duration;
685
+ if (typeof duration === "number") t = Math.min(t, duration);
686
+ return t;
687
+ }
688
+ return this.currentTime;
689
+ }
690
+
691
+ getEstimatedBreakTime(): any {
692
+ const base = this.breakStatus && this.breakStatus.currentBreakTime;
693
+ if (typeof base !== "number") return undefined;
694
+ return base + this._estimateElapsed();
695
+ }
696
+
697
+ getEstimatedBreakClipTime(): any {
698
+ const base = this.breakStatus && this.breakStatus.currentBreakClipTime;
699
+ if (typeof base !== "number") return undefined;
700
+ return base + this._estimateElapsed();
701
+ }
702
+
703
+ getEstimatedLiveSeekableRange(): any {
704
+ const r = this.liveSeekableRange;
705
+ if (r == null) return undefined;
706
+ const elapsed = this._estimateElapsed();
707
+ const out: any = {
708
+ start: r.start,
709
+ end: r.end,
710
+ isMovingWindow: r.isMovingWindow,
711
+ isLiveDone: r.isLiveDone,
712
+ };
713
+ if (r.isLiveDone !== true) {
714
+ if (typeof out.end === "number") out.end += elapsed;
715
+ if (r.isMovingWindow === true && typeof out.start === "number") out.start += elapsed;
716
+ }
717
+ return out;
718
+ }
719
+
720
+ /** Seconds advanced since the last status update: playbackRate * elapsed while PLAYING, else 0. */
721
+ _estimateElapsed(): number {
722
+ if (this.playerState !== "PLAYING") return 0;
723
+ return this.playbackRate * (Date.now() - this._lastUpdate) / 1000;
724
+ }
725
+
726
+ /** Send a command on the media namespace; resolves with no arguments on the matching MEDIA_STATUS. */
727
+ sendCommand(type: string, extra: any, success: any, error: any): void {
728
+ const sess = sessions.get(this.sessionId);
729
+ if (!sess || sess.status !== "connected") {
730
+ fail(error, "session_error");
731
+ return;
732
+ }
733
+ const requestId = nextRequestId();
734
+ const message = stripNulls({ type, requestId, mediaSessionId: this.mediaSessionId, ...extra });
735
+ sendMediaRequest(sess, requestId, message, MEDIA_TIMEOUT_KEYS[type] ?? "getStatus", success, error);
736
+ }
737
+
738
+ getStatus(req: any, success: any, error: any): void {
739
+ this.sendCommand("GET_STATUS", { customData: req?.customData ?? null }, success, error);
740
+ }
741
+
742
+ play(req: any, success: any, error: any): void {
743
+ this.sendCommand("PLAY", { customData: req?.customData ?? null }, success, error);
744
+ }
745
+
746
+ pause(req: any, success: any, error: any): void {
747
+ this.sendCommand("PAUSE", { customData: req?.customData ?? null }, success, error);
748
+ }
749
+
750
+ seek(seekRequest: any, success: any, error: any): void {
751
+ this.sendCommand("SEEK", {
752
+ currentTime: seekRequest?.currentTime ?? null,
753
+ resumeState: seekRequest?.resumeState ?? null,
754
+ customData: seekRequest?.customData ?? null,
755
+ }, success, error);
756
+ }
757
+
758
+ stop(req: any, success: any, error: any): void {
759
+ this.sendCommand("STOP", { customData: req?.customData ?? null }, success, error);
760
+ }
761
+
762
+ setVolume(volumeRequest: any, success: any, error: any): void {
763
+ const vol = volumeRequest?.volume;
764
+ this.sendCommand("SET_VOLUME", {
765
+ volume: vol ? { level: vol.level ?? null, muted: vol.muted ?? null } : null,
766
+ customData: volumeRequest?.customData ?? null,
767
+ }, success, error);
768
+ }
769
+
770
+ editTracksInfo(req: any, success: any, error: any): void {
771
+ this.sendCommand("EDIT_TRACKS_INFO", {
772
+ activeTrackIds: req?.activeTrackIds ?? null,
773
+ textTrackStyle: req?.textTrackStyle ?? null,
774
+ }, success, error);
775
+ }
776
+
777
+ queueInsertItems(req: any, success: any, error: any): void {
778
+ this.sendCommand("QUEUE_INSERT", {
779
+ items: req?.items ?? null,
780
+ insertBefore: req?.insertBefore ?? null,
781
+ customData: req?.customData ?? null,
782
+ }, success, error);
783
+ }
784
+
785
+ queueAppendItem(item: any, success: any, error: any): void {
786
+ this.sendCommand("QUEUE_INSERT", { items: [item] }, success, error);
787
+ }
788
+
789
+ queueUpdateItems(req: any, success: any, error: any): void {
790
+ this.sendCommand("QUEUE_UPDATE", {
791
+ items: req?.items ?? null,
792
+ customData: req?.customData ?? null,
793
+ }, success, error);
794
+ }
795
+
796
+ queueJumpToItem(itemId: any, success: any, error: any): void {
797
+ this.sendCommand("QUEUE_UPDATE", { currentItemId: itemId }, success, error);
798
+ }
799
+
800
+ queueNext(success: any, error: any): void {
801
+ this.sendCommand("QUEUE_UPDATE", { jump: 1 }, success, error);
802
+ }
803
+
804
+ queuePrev(success: any, error: any): void {
805
+ this.sendCommand("QUEUE_UPDATE", { jump: -1 }, success, error);
806
+ }
807
+
808
+ queueSetRepeatMode(mode: any, success: any, error: any): void {
809
+ this.sendCommand("QUEUE_UPDATE", { repeatMode: mode }, success, error);
810
+ }
811
+
812
+ queueRemoveItems(req: any, success: any, error: any): void {
813
+ this.sendCommand("QUEUE_REMOVE", {
814
+ itemIds: req?.itemIds ?? null,
815
+ customData: req?.customData ?? null,
816
+ }, success, error);
817
+ }
818
+
819
+ queueRemoveItem(itemId: any, success: any, error: any): void {
820
+ this.sendCommand("QUEUE_REMOVE", { itemIds: [itemId] }, success, error);
821
+ }
822
+
823
+ queueReorderItems(req: any, success: any, error: any): void {
824
+ this.sendCommand("QUEUE_REORDER", {
825
+ itemIds: req?.itemIds ?? null,
826
+ insertBefore: req?.insertBefore ?? null,
827
+ customData: req?.customData ?? null,
828
+ }, success, error);
829
+ }
830
+
831
+ queueMoveItemToNewIndex(itemId: any, newIndex: any, success: any, error: any): void {
832
+ const items = Array.isArray(this.items) ? this.items : null;
833
+ if (!items || !items.some((i: any) => i && i.itemId === itemId) || !Number.isInteger(newIndex) || newIndex < 0) {
834
+ fail(error, "invalid_parameter");
835
+ return;
836
+ }
837
+ const remaining = items.map((i: any) => i.itemId).filter((id: any) => id !== itemId);
838
+ const extra = newIndex >= remaining.length
839
+ ? { itemIds: [itemId] }
840
+ : { itemIds: [itemId], insertBefore: remaining[newIndex] };
841
+ this.sendCommand("QUEUE_REORDER", extra, success, error);
842
+ }
843
+ }
844
+
845
+ const media = {
846
+ DEFAULT_MEDIA_RECEIVER_APP_ID: "CC1AD845",
847
+ PlayerState,
848
+ MediaCommand,
849
+ MetadataType,
850
+ RepeatMode,
851
+ ResumeState,
852
+ StreamType,
853
+ IdleReason,
854
+ TrackType,
855
+ TextTrackType,
856
+ TextTrackEdgeType,
857
+ TextTrackWindowType,
858
+ TextTrackFontGenericFamily,
859
+ TextTrackFontStyle,
860
+ timeout: { load: 15000, getStatus: 15000, play: 15000, pause: 15000, seek: 15000, stop: 15000, setVolume: 15000, editTracksInfo: 15000, queue: 15000 },
861
+ MediaInfo,
862
+ LoadRequest,
863
+ QueueItem,
864
+ QueueLoadRequest,
865
+ QueueInsertItemsRequest,
866
+ QueueRemoveItemsRequest,
867
+ QueueReorderItemsRequest,
868
+ QueueUpdateItemsRequest,
869
+ QueueSetPropertiesRequest,
870
+ QueueJumpRequest,
871
+ SeekRequest,
872
+ VolumeRequest,
873
+ PlayRequest,
874
+ PauseRequest,
875
+ StopRequest,
876
+ GetStatusRequest,
877
+ EditTracksInfoRequest,
878
+ Track,
879
+ TextTrackStyle,
880
+ GenericMediaMetadata,
881
+ MovieMediaMetadata,
882
+ TvShowMediaMetadata,
883
+ MusicTrackMediaMetadata,
884
+ PhotoMediaMetadata,
885
+ Media,
886
+ };
887
+
888
+ const MEDIA_TIMEOUT_KEYS: Record<string, string> = {
889
+ LOAD: "load",
890
+ GET_STATUS: "getStatus",
891
+ PLAY: "play",
892
+ PAUSE: "pause",
893
+ SEEK: "seek",
894
+ STOP: "stop",
895
+ SET_VOLUME: "setVolume",
896
+ EDIT_TRACKS_INFO: "editTracksInfo",
897
+ QUEUE_LOAD: "queue",
898
+ QUEUE_INSERT: "queue",
899
+ QUEUE_REMOVE: "queue",
900
+ QUEUE_REORDER: "queue",
901
+ QUEUE_UPDATE: "queue",
902
+ };
903
+
188
904
  function safe(fn: any, ...args: any[]): void {
189
905
  if (typeof fn !== "function") return;
190
906
  try {
@@ -198,6 +914,178 @@ export function installChromeCast(bridgeKey: string): boolean {
198
914
  setTimeout(() => safe(error, new CastError(code, description ?? null)), 0);
199
915
  }
200
916
 
917
+ const REQ_ID_MAX = 2 ** 30;
918
+ let requestIdCounter = Math.floor(Math.random() * (REQ_ID_MAX - 1)) + 1;
919
+
920
+ /** Positive integer requestIds, unique within the page, starting at a random value in [1, 2^30). */
921
+ function nextRequestId(): number {
922
+ const id = requestIdCounter;
923
+ requestIdCounter += 1;
924
+ if (requestIdCounter >= REQ_ID_MAX) requestIdCounter = 1;
925
+ return id;
926
+ }
927
+
928
+ /** A timer that does not keep a Node test process alive; plain in the browser. */
929
+ function later(ms: number, fn: () => void): any {
930
+ const t: any = setTimeout(fn, ms);
931
+ if (t && typeof t.unref === "function") t.unref();
932
+ return t;
933
+ }
934
+
935
+ /** Remove every key whose value is null or undefined, recursively through objects and arrays. */
936
+ function stripNulls(value: any): any {
937
+ if (Array.isArray(value)) return value.map(stripNulls).filter((v: any) => v !== null && v !== undefined);
938
+ if (value && typeof value === "object") {
939
+ const out: any = {};
940
+ for (const key of Object.keys(value)) {
941
+ const v = value[key];
942
+ if (v === null || v === undefined) continue;
943
+ out[key] = stripNulls(v);
944
+ }
945
+ return out;
946
+ }
947
+ return value;
948
+ }
949
+
950
+ function settlePendingMedia(sess: any, requestId: number, outcome: () => void): void {
951
+ const p = sess._pendingMedia.get(requestId);
952
+ if (!p) return;
953
+ sess._pendingMedia.delete(requestId);
954
+ if (p.timer) clearTimeout(p.timer);
955
+ outcome();
956
+ }
957
+
958
+ /** Send one media-namespace message and track it until its reply (or timeout) arrives. */
959
+ function sendMediaRequest(sess: any, requestId: number, message: any, timeoutKey: string, success: any, error: any): void {
960
+ const pending: any = { kind: message.type, success, error, timer: null };
961
+ const timeoutMs = (media.timeout as Record<string, number>)[timeoutKey];
962
+ if (typeof timeoutMs === "number" && timeoutMs > 0) {
963
+ pending.timer = later(timeoutMs, () => settlePendingMedia(sess, requestId, () => fail(error, "timeout")));
964
+ }
965
+ sess._pendingMedia.set(requestId, pending);
966
+ bridge.call("sendMessage", { sessionId: sess.sessionId, namespace: MEDIA_NAMESPACE, message: JSON.stringify(message) })
967
+ .then((res: any) => {
968
+ if (!res.ok) settlePendingMedia(sess, requestId, () => fail(error, res.code, res.description));
969
+ })
970
+ .catch((e: unknown) => settlePendingMedia(sess, requestId, () => fail(error, "session_error", String(e))));
971
+ }
972
+
973
+ /** Kill every Media of the session (update listeners get false) without touching pending requests. */
974
+ function killAllMedia(sess: any): void {
975
+ for (const m of [...sess.media]) {
976
+ for (const fn of [...m._updateListeners]) safe(fn, false);
977
+ }
978
+ sess.media = [];
979
+ }
980
+
981
+ /** The session is gone: kill its media and fail every pending media request with session_error. */
982
+ function killSessionMedia(sess: any): void {
983
+ killAllMedia(sess);
984
+ for (const p of [...sess._pendingMedia.values()]) {
985
+ if (p.timer) clearTimeout(p.timer);
986
+ fail(p.error, "session_error");
987
+ }
988
+ sess._pendingMedia.clear();
989
+ }
990
+
991
+ function applyMediaStatus(sess: any, msg: any): void {
992
+ const entries: any[] = Array.isArray(msg.status) ? msg.status : msg.status && typeof msg.status === "object" ? [msg.status] : [];
993
+ if (entries.length === 0) {
994
+ killAllMedia(sess);
995
+ return;
996
+ }
997
+ const pending = typeof msg.requestId === "number" ? sess._pendingMedia.get(msg.requestId) : undefined;
998
+ const suppressAnnounce = !!pending && (pending.kind === "LOAD" || pending.kind === "QUEUE_LOAD");
999
+ for (const e of entries) {
1000
+ if (!e || typeof e !== "object" || e.mediaSessionId == null) continue;
1001
+ let m = sess.media.find((x: any) => x.mediaSessionId === e.mediaSessionId);
1002
+ const isNew = !m;
1003
+ if (isNew) {
1004
+ m = new Media(sess.sessionId, e.mediaSessionId);
1005
+ sess.media.push(m);
1006
+ }
1007
+ if (e.media != null) m.media = e.media;
1008
+ if (e.playbackRate != null) m.playbackRate = e.playbackRate;
1009
+ if (e.playerState != null) m.playerState = e.playerState;
1010
+ if (e.currentTime != null) m.currentTime = e.currentTime;
1011
+ if (e.activeTrackIds != null) m.activeTrackIds = e.activeTrackIds;
1012
+ if (e.customData != null) m.customData = e.customData;
1013
+ if (e.currentItemId != null) m.currentItemId = e.currentItemId;
1014
+ if (e.loadingItemId != null) m.loadingItemId = e.loadingItemId;
1015
+ if (e.preloadedItemId != null) m.preloadedItemId = e.preloadedItemId;
1016
+ if (e.items != null) m.items = e.items;
1017
+ if (e.repeatMode != null) m.repeatMode = e.repeatMode;
1018
+ // A MEDIA_STATUS entry is the receiver's full status except that unchanged fields may be left out:
1019
+ // an ad break that ended, or a stream that is no longer live, drops the field, so these default to null.
1020
+ m.liveSeekableRange = e.liveSeekableRange ?? null;
1021
+ m.breakStatus = e.breakStatus ?? null;
1022
+ if (e.videoInfo != null) m.videoInfo = e.videoInfo;
1023
+ if (e.queueData != null) m.queueData = e.queueData;
1024
+ m.idleReason = e.idleReason ?? null;
1025
+ if (e.volume != null) m.volume = new Volume(e.volume.level ?? null, e.volume.muted ?? null);
1026
+ if (e.supportedMediaCommands != null) {
1027
+ const bits = [MediaCommand.PAUSE, MediaCommand.SEEK, MediaCommand.STREAM_VOLUME, MediaCommand.STREAM_MUTE];
1028
+ m.supportedMediaCommands = bits.filter((_: any, i: number) => (e.supportedMediaCommands & (1 << i)) !== 0);
1029
+ }
1030
+ m._lastUpdate = Date.now();
1031
+ const alive = !(m.playerState === PlayerState.IDLE && m.idleReason !== null);
1032
+ for (const fn of [...m._updateListeners]) safe(fn, alive);
1033
+ if (!alive) {
1034
+ const i = sess.media.indexOf(m);
1035
+ if (i >= 0) sess.media.splice(i, 1);
1036
+ } else if (isNew && !m._announced) {
1037
+ m._announced = true;
1038
+ if (!suppressAnnounce) for (const fn of [...sess._mediaListeners]) safe(fn, m);
1039
+ }
1040
+ }
1041
+ }
1042
+
1043
+ /** Resolve a pending media request from a reply on the media namespace. */
1044
+ function resolveMediaReply(sess: any, msg: any): void {
1045
+ if (!msg || typeof msg !== "object" || typeof msg.requestId !== "number") return;
1046
+ const p = sess._pendingMedia.get(msg.requestId);
1047
+ if (!p) return;
1048
+ switch (msg.type) {
1049
+ case "MEDIA_STATUS": {
1050
+ if (p.kind === "LOAD" || p.kind === "QUEUE_LOAD") {
1051
+ // Some receivers (a Nest Hub) answer a LOAD with an interim MEDIA_STATUS whose entry still
1052
+ // reports extendedStatus.playerState "LOADING"; keep waiting for the final status.
1053
+ const entries: any[] = Array.isArray(msg.status) ? msg.status : msg.status && typeof msg.status === "object" ? [msg.status] : [];
1054
+ const interim = entries.some((e: any) => e && e.extendedStatus && e.extendedStatus.playerState === "LOADING");
1055
+ if (interim) return;
1056
+ const first = Array.isArray(msg.status) ? msg.status[0] : msg.status;
1057
+ const m = first && sess.media.find((x: any) => x.mediaSessionId === first.mediaSessionId);
1058
+ settlePendingMedia(sess, msg.requestId, () => (m ? safe(p.success, m) : fail(p.error, "load_media_failed")));
1059
+ } else {
1060
+ settlePendingMedia(sess, msg.requestId, () => safe(p.success));
1061
+ }
1062
+ return;
1063
+ }
1064
+ case "LOAD_FAILED":
1065
+ settlePendingMedia(sess, msg.requestId, () => fail(p.error, "load_media_failed"));
1066
+ return;
1067
+ case "LOAD_CANCELLED":
1068
+ settlePendingMedia(sess, msg.requestId, () => fail(p.error, "cancel"));
1069
+ return;
1070
+ case "INVALID_REQUEST":
1071
+ case "INVALID_PLAYER_STATE":
1072
+ settlePendingMedia(sess, msg.requestId, () => fail(p.error, "session_error", msg.reason));
1073
+ return;
1074
+ }
1075
+ }
1076
+
1077
+ function handleMediaMessage(sess: any, raw: any): void {
1078
+ let msg: any;
1079
+ try {
1080
+ msg = typeof raw === "string" ? JSON.parse(raw) : raw;
1081
+ } catch {
1082
+ return;
1083
+ }
1084
+ if (!msg || typeof msg !== "object") return;
1085
+ if (msg.type === "MEDIA_STATUS") applyMediaStatus(sess, msg);
1086
+ resolveMediaReply(sess, msg);
1087
+ }
1088
+
201
1089
  function toImage(img: any): any {
202
1090
  const out = new Image(img.url);
203
1091
  if (img.height != null) out.height = img.height;
@@ -253,6 +1141,8 @@ export function installChromeCast(bridgeKey: string): boolean {
253
1141
  transportId: any;
254
1142
  updateListeners: any[];
255
1143
  messageListeners: Map<string, any[]>;
1144
+ _mediaListeners: any[];
1145
+ _pendingMedia: Map<number, any>;
256
1146
  constructor(sessionId: any, appId: any, displayName: any, appImages: any, receiver: any) {
257
1147
  this.sessionId = sessionId;
258
1148
  this.appId = appId;
@@ -267,6 +1157,8 @@ export function installChromeCast(bridgeKey: string): boolean {
267
1157
  this.transportId = sessionId;
268
1158
  this.updateListeners = [];
269
1159
  this.messageListeners = new Map<string, any[]>();
1160
+ this._mediaListeners = [];
1161
+ this._pendingMedia = new Map<number, any>();
270
1162
  }
271
1163
 
272
1164
  sendMessage(namespace: any, message: any, success?: any, error?: any): void {
@@ -306,9 +1198,14 @@ export function installChromeCast(bridgeKey: string): boolean {
306
1198
  if (i >= 0) this.updateListeners.splice(i, 1);
307
1199
  }
308
1200
 
309
- addMediaListener(_fn: any): void {}
1201
+ addMediaListener(fn: any): void {
1202
+ if (typeof fn === "function" && !this._mediaListeners.includes(fn)) this._mediaListeners.push(fn);
1203
+ }
310
1204
 
311
- removeMediaListener(_fn: any): void {}
1205
+ removeMediaListener(fn: any): void {
1206
+ const i = this._mediaListeners.indexOf(fn);
1207
+ if (i >= 0) this._mediaListeners.splice(i, 1);
1208
+ }
312
1209
 
313
1210
  stop(success: any, error: any): void {
314
1211
  bridge.call("stopSession", { sessionId: this.sessionId }).then((res: any) => {
@@ -316,8 +1213,7 @@ export function installChromeCast(bridgeKey: string): boolean {
316
1213
  fail(error, res.code, res.description);
317
1214
  return;
318
1215
  }
319
- this.status = "stopped";
320
- for (const fn of [...this.updateListeners]) safe(fn, false);
1216
+ endSession(this, "stopped");
321
1217
  safe(success);
322
1218
  }).catch((e: unknown) => fail(error, "session_error", String(e)));
323
1219
  }
@@ -328,8 +1224,7 @@ export function installChromeCast(bridgeKey: string): boolean {
328
1224
  fail(error, res.code, res.description);
329
1225
  return;
330
1226
  }
331
- this.status = "disconnected";
332
- for (const fn of [...this.updateListeners]) safe(fn, false);
1227
+ endSession(this, "disconnected");
333
1228
  safe(success);
334
1229
  }).catch((e: unknown) => fail(error, "session_error", String(e)));
335
1230
  }
@@ -358,24 +1253,93 @@ export function installChromeCast(bridgeKey: string): boolean {
358
1253
  }).catch((e: unknown) => fail(error, "session_error", String(e)));
359
1254
  }
360
1255
 
361
- loadMedia(_req: any, _success: any, error: any): void {
362
- fail(error, "session_error", "Media is not supported yet");
1256
+ loadMedia(req: any, success: any, error: any): void {
1257
+ if (!req || typeof req !== "object" || !req.media) {
1258
+ fail(error, "invalid_parameter");
1259
+ return;
1260
+ }
1261
+ if (this.status !== "connected") {
1262
+ fail(error, "session_error");
1263
+ return;
1264
+ }
1265
+ const requestId = nextRequestId();
1266
+ const message = stripNulls({
1267
+ type: "LOAD",
1268
+ requestId,
1269
+ sessionId: this.sessionId,
1270
+ media: req.media,
1271
+ autoplay: req.autoplay ?? true,
1272
+ currentTime: req.currentTime ?? null,
1273
+ activeTrackIds: req.activeTrackIds ?? null,
1274
+ customData: req.customData ?? null,
1275
+ });
1276
+ sendMediaRequest(this, requestId, message, "load", success, error);
363
1277
  }
364
1278
 
365
- queueLoad(_req: any, _success: any, error: any): void {
366
- fail(error, "session_error", "Media is not supported yet");
1279
+ queueLoad(req: any, success: any, error: any): void {
1280
+ if (!req || typeof req !== "object" || !Array.isArray(req.items)) {
1281
+ fail(error, "invalid_parameter");
1282
+ return;
1283
+ }
1284
+ if (this.status !== "connected") {
1285
+ fail(error, "session_error");
1286
+ return;
1287
+ }
1288
+ const requestId = nextRequestId();
1289
+ const message = stripNulls({
1290
+ type: "QUEUE_LOAD",
1291
+ requestId,
1292
+ sessionId: this.sessionId,
1293
+ items: req.items,
1294
+ startIndex: req.startIndex ?? 0,
1295
+ repeatMode: req.repeatMode ?? "REPEAT_OFF",
1296
+ customData: req.customData ?? null,
1297
+ });
1298
+ sendMediaRequest(this, requestId, message, "queue", success, error);
367
1299
  }
368
1300
  }
369
1301
 
370
1302
  const sessions = new Map<string, any>();
371
1303
 
1304
+ /** End a session: notify, then drop it from the session map so later events for it are ignored. */
1305
+ function endSession(sess: any, status: string): void {
1306
+ sess.status = status;
1307
+ killSessionMedia(sess);
1308
+ notifyUpdate(sess, false);
1309
+ sessions.delete(sess.sessionId);
1310
+ }
1311
+
1312
+ /**
1313
+ * Report a session to a sessionListener function at most once: remember, per listener function, the
1314
+ * session ids already announced to it, so a second initialize (or a requestSessionById) does not
1315
+ * re-announce a session that function already got.
1316
+ */
1317
+ const announcedTo = new WeakMap<any, Set<string>>();
1318
+ function announce(sess: any, listener: any): void {
1319
+ if (!sess || typeof listener !== "function") return;
1320
+ let set = announcedTo.get(listener);
1321
+ if (!set) {
1322
+ set = new Set<string>();
1323
+ announcedTo.set(listener, set);
1324
+ }
1325
+ if (set.has(sess.sessionId)) return;
1326
+ set.add(sess.sessionId);
1327
+ safe(listener, sess);
1328
+ }
1329
+
372
1330
  function upsertSession(snap: any): any {
373
1331
  let sess = sessions.get(snap.sessionId);
374
- if (!sess) {
1332
+ const created = !sess;
1333
+ if (created) {
375
1334
  sess = new Session(snap.sessionId, snap.appId, snap.displayName, [], toReceiver(snap.receiver));
376
1335
  sessions.set(snap.sessionId, sess);
377
1336
  }
378
1337
  applySnapshot(sess, snap);
1338
+ if (created && sess.namespaces.some((n: any) => n.name === MEDIA_NAMESPACE)) {
1339
+ // Discover media the receiver already has; its failure is ignored.
1340
+ const requestId = nextRequestId();
1341
+ sendMediaRequest(sess, requestId, { type: "GET_STATUS", requestId }, "getStatus", () => {}, () => {});
1342
+ }
379
1343
  return sess;
380
1344
  }
381
1345
 
@@ -408,8 +1372,14 @@ export function installChromeCast(bridgeKey: string): boolean {
408
1372
  case "sessionEnded": {
409
1373
  const sess = sessions.get(event.sessionId);
410
1374
  if (!sess) return;
411
- sess.status = event.status;
412
- notifyUpdate(sess, false);
1375
+ endSession(sess, event.status);
1376
+ return;
1377
+ }
1378
+ case "receiverAction": {
1379
+ // A live session only: unknown ids and sessions that already ended are ignored.
1380
+ const sess = sessions.get(event.sessionId);
1381
+ if (!sess) return;
1382
+ for (const fn of [...receiverActionListeners]) safe(fn, sess.receiver, ReceiverAction.STOP);
413
1383
  return;
414
1384
  }
415
1385
  case "message": {
@@ -417,6 +1387,7 @@ export function installChromeCast(bridgeKey: string): boolean {
417
1387
  if (!sess) return;
418
1388
  const fns = sess.messageListeners.get(event.namespace) ?? [];
419
1389
  for (const fn of [...fns]) safe(fn, event.namespace, event.message);
1390
+ if (event.namespace === MEDIA_NAMESPACE) handleMediaMessage(sess, event.message);
420
1391
  return;
421
1392
  }
422
1393
  }
@@ -446,7 +1417,7 @@ export function installChromeCast(bridgeKey: string): boolean {
446
1417
  lastAvailability = availability;
447
1418
  safe(success);
448
1419
  safe(apiCfg.receiverListener, availability);
449
- for (const snap of value.sessions ?? []) safe(apiCfg.sessionListener, upsertSession(snap));
1420
+ for (const snap of value.sessions ?? []) announce(upsertSession(snap), apiCfg.sessionListener);
450
1421
  }).catch((e: unknown) => fail(error, "session_error", String(e)));
451
1422
  }
452
1423
 
@@ -484,7 +1455,7 @@ export function installChromeCast(bridgeKey: string): boolean {
484
1455
  bridge.call("joinSession", { sessionId }).then((res: any) => {
485
1456
  if (!res.ok) return;
486
1457
  const sess = upsertSession(res.value);
487
- if (apiConfig) safe(apiConfig.sessionListener, sess);
1458
+ if (apiConfig) announce(sess, apiConfig.sessionListener);
488
1459
  }).catch((e: unknown) => console.error(e));
489
1460
  }
490
1461
 
@@ -557,18 +1528,82 @@ export function installChromeCast(bridgeKey: string): boolean {
557
1528
  unescape,
558
1529
  };
559
1530
 
1531
+ // Google's cast_sender.js loader (it takes the desktop-Chrome path because Electron exposes
1532
+ // navigator.presentation) injects its own chrome.cast implementations from gstatic/eureka/clank and
1533
+ // from the two Cast extensions. The first one that loads would overwrite this polyfill with an
1534
+ // implementation on the Presentation API, which finds no devices in Electron, so those scripts are
1535
+ // blocked before they can load. A blocked element ends up with no src, so it never fires load or
1536
+ // error and the loader's chain simply stops there.
1537
+ const blockedClankRe = /^(https?:)?\/\/www\.gstatic\.com\/eureka\/clank\/(\d+\/)?cast_sender\.js/i;
1538
+ const blockedExtensionRe = /^chrome-extension:\/\/(pkedcjkdefgpdelpbcmbmeomcjbeemfm|enhhojjnijigcajfphajepfemndkmdlo)\//i;
1539
+ const isBlockedSrc = (value: any): boolean => {
1540
+ let url: string;
1541
+ try {
1542
+ url = String(value);
1543
+ } catch {
1544
+ return false;
1545
+ }
1546
+ return blockedClankRe.test(url) || blockedExtensionRe.test(url);
1547
+ };
1548
+ if (typeof HTMLScriptElement === "function") {
1549
+ let proto: any = HTMLScriptElement.prototype;
1550
+ let srcDesc: any = proto ? Object.getOwnPropertyDescriptor(proto, "src") : undefined;
1551
+ while (!srcDesc && proto) {
1552
+ proto = Object.getPrototypeOf(proto);
1553
+ if (proto) srcDesc = Object.getOwnPropertyDescriptor(proto, "src");
1554
+ }
1555
+ if (srcDesc && typeof srcDesc.set === "function") {
1556
+ const originalSetSrc = srcDesc.set;
1557
+ Object.defineProperty(HTMLScriptElement.prototype, "src", {
1558
+ configurable: srcDesc.configurable === true,
1559
+ enumerable: srcDesc.enumerable === true,
1560
+ get: srcDesc.get,
1561
+ set(v: any) {
1562
+ if (isBlockedSrc(v)) return;
1563
+ originalSetSrc.call(this, v);
1564
+ },
1565
+ });
1566
+ }
1567
+ }
1568
+ if (typeof Element === "function" && typeof Element.prototype.setAttribute === "function") {
1569
+ const originalSetAttribute = Element.prototype.setAttribute;
1570
+ Element.prototype.setAttribute = function (this: any, name: any, value: any) {
1571
+ if (typeof HTMLScriptElement === "function"
1572
+ && this instanceof HTMLScriptElement
1573
+ && typeof name === "string"
1574
+ && name.toLowerCase() === "src"
1575
+ && isBlockedSrc(value)) {
1576
+ return undefined;
1577
+ }
1578
+ return originalSetAttribute.call(this, name, value);
1579
+ };
1580
+ }
1581
+
1582
+ // While the document is still loading, a page assigns its __onGCastApiAvailable callback and then the
1583
+ // parser loads cast_sender.js; calling the callback on a timer would run it before the page's scripts
1584
+ // (and cast.framework) exist. So until DOMContentLoaded only store the callback, then call whatever is
1585
+ // stored at that moment. With Google's loader that is its counter wrapper, which stands in for the
1586
+ // second report-in and fires the page's callback once the framework has loaded as well.
1587
+ const docIsLoading = (): boolean => typeof document !== "undefined" && document.readyState === "loading";
560
1588
  let onGCastApiAvailable: any = g.__onGCastApiAvailable;
561
- const notifyGCastApiAvailable = (): void => {
562
- setTimeout(() => safe(onGCastApiAvailable, true), 0);
1589
+ const notifiedCallbacks = new WeakSet();
1590
+ const notifyGCastApiAvailable = (fn: any): void => {
1591
+ if (typeof fn !== "function" || notifiedCallbacks.has(fn)) return;
1592
+ notifiedCallbacks.add(fn);
1593
+ setTimeout(() => safe(fn, true), 0);
563
1594
  };
564
- if (typeof onGCastApiAvailable === "function") notifyGCastApiAvailable();
1595
+ if (docIsLoading() && typeof document.addEventListener === "function") {
1596
+ document.addEventListener("DOMContentLoaded", () => notifyGCastApiAvailable(onGCastApiAvailable));
1597
+ } else {
1598
+ notifyGCastApiAvailable(onGCastApiAvailable);
1599
+ }
565
1600
  Object.defineProperty(g, "__onGCastApiAvailable", {
566
1601
  configurable: true,
567
1602
  enumerable: true,
568
1603
  get: () => onGCastApiAvailable,
569
1604
  set: (v: any) => {
570
1605
  onGCastApiAvailable = v;
571
- if (typeof v === "function") notifyGCastApiAvailable();
1606
+ if (typeof v === "function" && !docIsLoading()) notifyGCastApiAvailable(v);
572
1607
  },
573
1608
  });
574
1609