@mattebox/player-ads 0.0.0 → 1.1.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.
Files changed (127) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +36 -2
  3. package/dist/ad-info.d.ts +25 -0
  4. package/dist/ad-info.d.ts.map +1 -0
  5. package/dist/ad-info.js +80 -0
  6. package/dist/ad-info.js.map +1 -0
  7. package/dist/ad-link.d.ts +19 -0
  8. package/dist/ad-link.d.ts.map +1 -0
  9. package/dist/ad-link.js +51 -0
  10. package/dist/ad-link.js.map +1 -0
  11. package/dist/ad-progress.d.ts +18 -0
  12. package/dist/ad-progress.d.ts.map +1 -0
  13. package/dist/ad-progress.js +51 -0
  14. package/dist/ad-progress.js.map +1 -0
  15. package/dist/ad-skip-button.d.ts +21 -0
  16. package/dist/ad-skip-button.d.ts.map +1 -0
  17. package/dist/ad-skip-button.js +66 -0
  18. package/dist/ad-skip-button.js.map +1 -0
  19. package/dist/beacons.d.ts +29 -0
  20. package/dist/beacons.d.ts.map +1 -0
  21. package/dist/beacons.js +44 -0
  22. package/dist/beacons.js.map +1 -0
  23. package/dist/cdn/mattebox-player-ads.min.js +1 -0
  24. package/dist/component.d.ts +54 -0
  25. package/dist/component.d.ts.map +1 -0
  26. package/dist/component.js +95 -0
  27. package/dist/component.js.map +1 -0
  28. package/dist/controller.d.ts +200 -0
  29. package/dist/controller.d.ts.map +1 -0
  30. package/dist/controller.js +830 -0
  31. package/dist/controller.js.map +1 -0
  32. package/dist/es2015/_virtual/_@oxc-project_runtime@0.158.0/helpers/esm/asyncToGenerator.js +26 -0
  33. package/dist/es2015/_virtual/_@oxc-project_runtime@0.158.0/helpers/esm/defineProperty.js +11 -0
  34. package/dist/es2015/_virtual/_@oxc-project_runtime@0.158.0/helpers/esm/objectSpread2.js +24 -0
  35. package/dist/es2015/_virtual/_@oxc-project_runtime@0.158.0/helpers/esm/toPrimitive.js +13 -0
  36. package/dist/es2015/_virtual/_@oxc-project_runtime@0.158.0/helpers/esm/toPropertyKey.js +8 -0
  37. package/dist/es2015/_virtual/_@oxc-project_runtime@0.158.0/helpers/esm/typeof.js +10 -0
  38. package/dist/es2015/ad-info.js +79 -0
  39. package/dist/es2015/ad-link.js +53 -0
  40. package/dist/es2015/ad-progress.js +51 -0
  41. package/dist/es2015/ad-skip-button.js +68 -0
  42. package/dist/es2015/beacons.js +42 -0
  43. package/dist/es2015/component.js +94 -0
  44. package/dist/es2015/controller.js +854 -0
  45. package/dist/es2015/host.js +18 -0
  46. package/dist/es2015/index.js +72 -0
  47. package/dist/es2015/locales/ar.js +13 -0
  48. package/dist/es2015/locales/ca.js +13 -0
  49. package/dist/es2015/locales/de.js +13 -0
  50. package/dist/es2015/locales/es.js +13 -0
  51. package/dist/es2015/locales/fr.js +13 -0
  52. package/dist/es2015/locales/hi.js +13 -0
  53. package/dist/es2015/locales/it.js +13 -0
  54. package/dist/es2015/locales/ja.js +13 -0
  55. package/dist/es2015/locales/ko.js +13 -0
  56. package/dist/es2015/locales/pt.js +13 -0
  57. package/dist/es2015/locales/zh.js +13 -0
  58. package/dist/es2015/shared.js +26 -0
  59. package/dist/es2015/vast.js +255 -0
  60. package/dist/es2015/vmap.js +73 -0
  61. package/dist/host.d.ts +14 -0
  62. package/dist/host.d.ts.map +1 -0
  63. package/dist/host.js +20 -0
  64. package/dist/host.js.map +1 -0
  65. package/dist/index.d.ts +40 -0
  66. package/dist/index.d.ts.map +1 -0
  67. package/dist/index.js +74 -0
  68. package/dist/index.js.map +1 -0
  69. package/dist/locales/ar.d.ts +13 -0
  70. package/dist/locales/ar.d.ts.map +1 -0
  71. package/dist/locales/ar.js +15 -0
  72. package/dist/locales/ar.js.map +1 -0
  73. package/dist/locales/ca.d.ts +13 -0
  74. package/dist/locales/ca.d.ts.map +1 -0
  75. package/dist/locales/ca.js +15 -0
  76. package/dist/locales/ca.js.map +1 -0
  77. package/dist/locales/de.d.ts +13 -0
  78. package/dist/locales/de.d.ts.map +1 -0
  79. package/dist/locales/de.js +15 -0
  80. package/dist/locales/de.js.map +1 -0
  81. package/dist/locales/es.d.ts +13 -0
  82. package/dist/locales/es.d.ts.map +1 -0
  83. package/dist/locales/es.js +15 -0
  84. package/dist/locales/es.js.map +1 -0
  85. package/dist/locales/fr.d.ts +13 -0
  86. package/dist/locales/fr.d.ts.map +1 -0
  87. package/dist/locales/fr.js +15 -0
  88. package/dist/locales/fr.js.map +1 -0
  89. package/dist/locales/hi.d.ts +13 -0
  90. package/dist/locales/hi.d.ts.map +1 -0
  91. package/dist/locales/hi.js +15 -0
  92. package/dist/locales/hi.js.map +1 -0
  93. package/dist/locales/it.d.ts +13 -0
  94. package/dist/locales/it.d.ts.map +1 -0
  95. package/dist/locales/it.js +15 -0
  96. package/dist/locales/it.js.map +1 -0
  97. package/dist/locales/ja.d.ts +13 -0
  98. package/dist/locales/ja.d.ts.map +1 -0
  99. package/dist/locales/ja.js +15 -0
  100. package/dist/locales/ja.js.map +1 -0
  101. package/dist/locales/ko.d.ts +13 -0
  102. package/dist/locales/ko.d.ts.map +1 -0
  103. package/dist/locales/ko.js +15 -0
  104. package/dist/locales/ko.js.map +1 -0
  105. package/dist/locales/pt.d.ts +13 -0
  106. package/dist/locales/pt.d.ts.map +1 -0
  107. package/dist/locales/pt.js +15 -0
  108. package/dist/locales/pt.js.map +1 -0
  109. package/dist/locales/zh.d.ts +13 -0
  110. package/dist/locales/zh.d.ts.map +1 -0
  111. package/dist/locales/zh.js +15 -0
  112. package/dist/locales/zh.js.map +1 -0
  113. package/dist/messages.d.ts +30 -0
  114. package/dist/messages.d.ts.map +1 -0
  115. package/dist/shared.d.ts +7 -0
  116. package/dist/shared.d.ts.map +1 -0
  117. package/dist/shared.js +25 -0
  118. package/dist/shared.js.map +1 -0
  119. package/dist/vast.d.ts +94 -0
  120. package/dist/vast.d.ts.map +1 -0
  121. package/dist/vast.js +254 -0
  122. package/dist/vast.js.map +1 -0
  123. package/dist/vmap.d.ts +31 -0
  124. package/dist/vmap.d.ts.map +1 -0
  125. package/dist/vmap.js +71 -0
  126. package/dist/vmap.js.map +1 -0
  127. package/package.json +52 -6
@@ -0,0 +1,830 @@
1
+ import { expand, send } from "./beacons.js";
2
+ import { fetchText, resolveVast } from "./vast.js";
3
+ import { offsetTime, parseVmap } from "./vmap.js";
4
+ // src/controller.ts
5
+ /** Seconds before a break at which its VAST is fetched: fresh, and in time for the preload. */
6
+ const LOOKAHEAD = 10;
7
+ const QUARTILE_EVENTS = [
8
+ "firstQuartile",
9
+ "midpoint",
10
+ "thirdQuartile"
11
+ ];
12
+ /** The keys that seek: the bar's arrows and media keys, the seek bar's Home, End and pages. */
13
+ const SEEK_KEYS = /* @__PURE__ */ new Set([
14
+ "ArrowLeft",
15
+ "ArrowRight",
16
+ "Home",
17
+ "End",
18
+ "PageUp",
19
+ "PageDown",
20
+ "MediaRewind",
21
+ "MediaFastForward",
22
+ "MediaTrackNext",
23
+ "MediaTrackPrevious",
24
+ "j",
25
+ "J",
26
+ "l",
27
+ "L",
28
+ ..."0123456789"
29
+ ]);
30
+ const STREAMING = /mpegurl|dash\+xml/i;
31
+ const controllers = /* @__PURE__ */ new WeakMap();
32
+ /** The ads of `player`, created on first use. */
33
+ function controllerFor(player, options) {
34
+ let found = controllers.get(player);
35
+ if (found === void 0) {
36
+ found = new Controller(player, options ?? {});
37
+ controllers.set(player, found);
38
+ } else if (options !== void 0) found.configure(options);
39
+ return found;
40
+ }
41
+ /** The time form of a scheduled offset. */
42
+ function offsetFrom(value) {
43
+ if (value === "start" || value === "end") return value;
44
+ if (typeof value === "number") return { time: value };
45
+ if (value.endsWith("%")) return { percent: Number(value.slice(0, -1)) };
46
+ return { time: value.split(":").map(Number).reduce((sum, part) => sum * 60 + part, 0) };
47
+ }
48
+ /** The file to play: a streaming one the engine reads, else the progressive one closest above the player's height. */
49
+ function pick(ad, engine, video, height) {
50
+ const usable = ad.mediaFiles.filter((file) => file.apiFramework === void 0);
51
+ if (engine) {
52
+ const stream = usable.find((file) => STREAMING.test(file.type));
53
+ if (stream !== void 0) return stream;
54
+ }
55
+ const progressive = usable.filter((file) => !STREAMING.test(file.type) && video.canPlayType(file.type) !== "").sort((a, b) => (a.height ?? 0) - (b.height ?? 0));
56
+ return progressive.find((file) => (file.height ?? 0) >= height) ?? progressive[progressive.length - 1];
57
+ }
58
+ var Controller = class {
59
+ constructor(player, options) {
60
+ this.onOpportunity = null;
61
+ this.player = player;
62
+ this.fetchDoc = fetchText;
63
+ this.progressive = "play";
64
+ this.send = send;
65
+ this.stitchedMode = "free";
66
+ this.own = /* @__PURE__ */ new Set();
67
+ this.configure(options);
68
+ this.plans = /* @__PURE__ */ new Map();
69
+ this.given = {
70
+ urls: [],
71
+ breaks: []
72
+ };
73
+ this.current = null;
74
+ this.watchers = /* @__PURE__ */ new Set();
75
+ this.offEngine = null;
76
+ this.lastTime = 0;
77
+ this.holding = false;
78
+ this.fetching = 0;
79
+ this.observer = null;
80
+ this.visibleSince = null;
81
+ this.seq = 0;
82
+ this.done = /* @__PURE__ */ new Set();
83
+ }
84
+ configure(options) {
85
+ this.fetchDoc = options.fetch ?? fetchText;
86
+ this.progressive = options.progressive ?? "play";
87
+ this.send = options.beacon ?? send;
88
+ this.stitchedMode = options.stitched ?? "free";
89
+ }
90
+ /** Follows the player until `detach`. */
91
+ attach() {
92
+ const player = this.player;
93
+ const video = player.media;
94
+ const onSource = () => {
95
+ this.reset();
96
+ this.bindEngine();
97
+ const schedule = player.getAttribute("ad-schedule");
98
+ if (schedule !== null && schedule !== "") this.load(schedule);
99
+ };
100
+ const onTime = () => this.tick();
101
+ const onMetadata = () => {
102
+ this.mark();
103
+ this.tick();
104
+ };
105
+ const onPlay = () => {
106
+ if (this.away()) return;
107
+ if (this.current === null && this.pending("start")) {
108
+ this.holding = true;
109
+ video.pause();
110
+ } else if (this.current === null) {
111
+ const pre = [...this.plans.values()].find((plan) => plan.offset === "start" && plan.status === "progressive");
112
+ if (pre !== void 0) {
113
+ video.pause();
114
+ this.startProgressive(pre);
115
+ }
116
+ }
117
+ this.tick();
118
+ };
119
+ const onEnded = () => {
120
+ if (this.away() && this.current === null) return;
121
+ if (this.current?.interrupt === true) {
122
+ this.nextProgressive();
123
+ return;
124
+ }
125
+ if (this.current !== null || this.engineBreaks()?.playing != null) return;
126
+ const post = [...this.plans.values()].find((plan) => plan.offset === "end" && plan.status === "progressive");
127
+ if (post !== void 0) this.startProgressive(post);
128
+ };
129
+ const onError = () => {
130
+ const current = this.current;
131
+ if (current?.interrupt !== true) return;
132
+ if (current.ad !== void 0) for (const url of current.ad.errors) this.send(expand(url, {
133
+ ...this.macros(current),
134
+ errorCode: 405
135
+ }));
136
+ this.emit("aderror", {
137
+ id: current.plan?.id,
138
+ code: 405
139
+ });
140
+ this.nextProgressive();
141
+ };
142
+ const onSeeking = () => {
143
+ const current = this.current;
144
+ if (current?.interrupt !== true) return;
145
+ if (Math.abs(video.currentTime - current.last) > .5) video.currentTime = current.last;
146
+ };
147
+ const onAdPause = () => {
148
+ if (this.current !== null) this.adPaused(video);
149
+ };
150
+ const onAdPlay = () => {
151
+ if (this.current !== null) this.adResumed(video);
152
+ };
153
+ const onAdVolume = () => {
154
+ if (this.current !== null && !this.current.stitched) this.adVolume(video);
155
+ };
156
+ const onKey = (event) => {
157
+ if (this.current === null || this.free(this.current)) return;
158
+ if (!SEEK_KEYS.has(event.key)) return;
159
+ if (event.composedPath().some((node) => node instanceof HTMLElement && node.localName.startsWith("mbx-volume"))) return;
160
+ event.preventDefault();
161
+ event.stopImmediatePropagation();
162
+ };
163
+ player.addEventListener("keydown", onKey, true);
164
+ const onMarkers = () => this.spans();
165
+ player.addEventListener("markerschange", onMarkers);
166
+ const scrub = new MutationObserver(() => {
167
+ if (!player.hasAttribute("scrubbing")) this.landed();
168
+ });
169
+ scrub.observe(player, {
170
+ attributes: true,
171
+ attributeFilter: ["scrubbing"]
172
+ });
173
+ player.addEventListener("sourcechange", onSource);
174
+ video.addEventListener("timeupdate", onTime);
175
+ video.addEventListener("play", onPlay);
176
+ video.addEventListener("loadedmetadata", onMetadata);
177
+ video.addEventListener("ended", onEnded);
178
+ video.addEventListener("error", onError);
179
+ video.addEventListener("seeking", onSeeking);
180
+ video.addEventListener("pause", onAdPause);
181
+ video.addEventListener("playing", onAdPlay);
182
+ video.addEventListener("volumechange", onAdVolume);
183
+ this.bindEngine();
184
+ return () => {
185
+ scrub.disconnect();
186
+ player.removeEventListener("markerschange", onMarkers);
187
+ player.removeEventListener("keydown", onKey, true);
188
+ player.removeEventListener("sourcechange", onSource);
189
+ video.removeEventListener("timeupdate", onTime);
190
+ video.removeEventListener("play", onPlay);
191
+ video.removeEventListener("loadedmetadata", onMetadata);
192
+ video.removeEventListener("ended", onEnded);
193
+ video.removeEventListener("error", onError);
194
+ video.removeEventListener("seeking", onSeeking);
195
+ video.removeEventListener("pause", onAdPause);
196
+ video.removeEventListener("playing", onAdPlay);
197
+ video.removeEventListener("volumechange", onAdVolume);
198
+ this.reset();
199
+ this.offEngine?.();
200
+ this.offEngine = null;
201
+ };
202
+ }
203
+ get state() {
204
+ const current = this.current;
205
+ if (current === null) return null;
206
+ const media = this.player.media;
207
+ const ads = current.plan?.ads ?? [];
208
+ const assets = current.entry?.assets ?? [];
209
+ const total = Math.max(1, ads.length || assets.length);
210
+ const time = current.stitched ? this.player.media.currentTime - (current.entry?.start ?? 0) : media.currentTime;
211
+ const duration = current.stitched ? current.entry?.covers ?? NaN : Number.isFinite(media.duration) ? media.duration : current.ad?.duration ?? assets[current.index]?.duration ?? NaN;
212
+ const later = (ads.length > 0 ? ads.map((ad) => ad.duration) : assets.map((asset) => asset.duration ?? NaN)).slice(current.index + 1).reduce((sum, value) => sum + value, 0);
213
+ const free = this.free(current);
214
+ const skipOffset = current.ad?.skipOffset ?? current.creative?.skipOffset ?? (current.ad === void 0 && !current.stitched ? current.entry?.skipAfter : void 0);
215
+ const clickThrough = current.ad?.clickThrough ?? current.creative?.clickThrough;
216
+ return {
217
+ breakId: current.plan?.id ?? current.entry?.id ?? "",
218
+ index: current.index + 1,
219
+ total,
220
+ currentTime: time,
221
+ duration,
222
+ remaining: duration - time + later,
223
+ skipIn: free ? 0 : skipOffset === void 0 ? null : Math.max(0, skipOffset - time),
224
+ ...clickThrough !== void 0 ? { clickThrough } : {},
225
+ ...current.ad !== void 0 ? { ad: current.ad } : {},
226
+ stitched: current.stitched,
227
+ role: current.entry?.role === "promo" ? "promo" : "ad",
228
+ free
229
+ };
230
+ }
231
+ /** A break the stream plays itself, with no rule of its own, under `stitched: 'free'`. */
232
+ free(current) {
233
+ const entry = current.entry;
234
+ return current.stitched && this.stitchedMode === "free" && entry !== null && !entry.noSkip && !entry.noJump && current.creative?.skipOffset === void 0;
235
+ }
236
+ watch(fn) {
237
+ this.watchers.add(fn);
238
+ return () => {
239
+ this.watchers.delete(fn);
240
+ };
241
+ }
242
+ /** The schedule the page gave, for the page of a device. Undefined without one. */
243
+ remoteData() {
244
+ const { urls, breaks } = this.given;
245
+ if (urls.length === 0 && breaks.length === 0) return void 0;
246
+ return {
247
+ ...urls.length === 0 ? {} : { urls: [...urls] },
248
+ ...breaks.length === 0 ? {} : { breaks: [...breaks] }
249
+ };
250
+ }
251
+ /**
252
+ * A device plays in the video's place, and it is not the video itself as
253
+ * under AirPlay. The device's own page plays the ads then, so nothing
254
+ * starts here: the same break would play twice.
255
+ */
256
+ away() {
257
+ const target = this.player.casting;
258
+ return target !== null && target.kind !== "airplay";
259
+ }
260
+ async load(source) {
261
+ const url = new URL(source, location.href).href;
262
+ this.given.urls.push(url);
263
+ let text;
264
+ this.fetching += 1;
265
+ try {
266
+ text = await this.fetchDoc(url, new AbortController().signal);
267
+ } catch {
268
+ this.fetching -= 1;
269
+ this.emit("aderror", {
270
+ code: 900,
271
+ url
272
+ });
273
+ this.release();
274
+ return;
275
+ }
276
+ this.fetching -= 1;
277
+ const breaks = parseVmap(text, url);
278
+ if (breaks === null) this.add({
279
+ id: "preroll",
280
+ offset: "start",
281
+ vast: { xml: text },
282
+ tracking: []
283
+ });
284
+ else for (const entry of breaks) this.add(entry);
285
+ this.release();
286
+ this.tick();
287
+ }
288
+ schedule(breaks) {
289
+ this.given.breaks.push(...breaks);
290
+ for (const entry of breaks) {
291
+ this.seq += 1;
292
+ this.add({
293
+ id: entry.id ?? `ad-break-${this.seq}`,
294
+ offset: offsetFrom(entry.offset),
295
+ vast: { url: new URL(entry.vast, location.href).href },
296
+ tracking: []
297
+ });
298
+ }
299
+ this.tick();
300
+ }
301
+ skip() {
302
+ const current = this.current;
303
+ const state = this.state;
304
+ if (current === null || state === null || state.skipIn === null || state.skipIn > 0) return;
305
+ if (current.interrupt) {
306
+ current.skipped = true;
307
+ this.track(current, "skip");
308
+ this.emit("adskip", this.detail());
309
+ this.nextProgressive();
310
+ return;
311
+ }
312
+ current.skipped = true;
313
+ this.track(current, "skip");
314
+ this.emit("adskip", this.detail());
315
+ if (current.stitched && current.entry !== null) {
316
+ this.player.media.currentTime = current.entry.start + current.entry.covers;
317
+ return;
318
+ }
319
+ this.engineBreaks()?.skip();
320
+ }
321
+ click() {
322
+ const current = this.current;
323
+ const target = current?.ad?.clickThrough ?? current?.creative?.clickThrough;
324
+ if (current === null || target === void 0) return;
325
+ for (const url of current.ad?.clickTracking ?? []) this.send(expand(url, this.macros(current)));
326
+ this.track(current, "clickTracking");
327
+ window.open(target, "_blank", "noopener");
328
+ this.player.media.pause();
329
+ this.emit("adclick", this.detail());
330
+ }
331
+ add(entry) {
332
+ this.plans.set(entry.id, {
333
+ ...entry,
334
+ status: "waiting",
335
+ ads: [],
336
+ files: []
337
+ });
338
+ this.mark();
339
+ }
340
+ /**
341
+ * The seek bar's ticks: the mid-roll breaks of the engine and of the
342
+ * schedule, spans where a break replaces a part, faded once played. A
343
+ * pre-roll and a post-roll sit at the ends and get none.
344
+ */
345
+ mark() {
346
+ const marks = [];
347
+ const engine = this.engineBreaks();
348
+ const ids = /* @__PURE__ */ new Set();
349
+ for (const entry of engine?.breaks ?? []) {
350
+ ids.add(entry.id);
351
+ if (entry.cue !== void 0) continue;
352
+ if (entry.role !== void 0 && entry.role !== "ad" && entry.role !== "promo") continue;
353
+ marks.push({
354
+ start: entry.start,
355
+ ...entry.covers > 0 ? { end: entry.start + entry.covers } : {},
356
+ ...this.done.has(entry.id) ? { played: true } : {}
357
+ });
358
+ }
359
+ const duration = this.programmeDuration();
360
+ for (const plan of this.plans.values()) {
361
+ if (ids.has(plan.id) || plan.offset === "start" || plan.offset === "end") continue;
362
+ const at = offsetTime(plan.offset, duration);
363
+ if (at === null) continue;
364
+ marks.push({
365
+ start: at,
366
+ ...plan.status === "done" ? { played: true } : {}
367
+ });
368
+ }
369
+ this.player.breaks.set("ads", marks);
370
+ this.spans();
371
+ }
372
+ /**
373
+ * The credits and chapters a SCTE-35 section names, as the player shows
374
+ * them: the credits as markers, which give Skip intro and Skip credits,
375
+ * beside the page's own, and the chapters in the chapter menu when nothing
376
+ * else gives chapters.
377
+ */
378
+ spans() {
379
+ const breaks = this.engineBreaks()?.breaks ?? [];
380
+ const credits = breaks.flatMap((entry) => (entry.role === "opening-credits" || entry.role === "closing-credits") && entry.covers > 0 ? [{
381
+ start: entry.start,
382
+ end: entry.start + entry.covers,
383
+ kind: entry.role
384
+ }] : []);
385
+ const markers = this.player.markers;
386
+ const theirs = markers.list.filter((marker) => !this.own.has(marker));
387
+ if (!(credits.length === this.own.size && [...this.own].every((marker, i) => {
388
+ const next = credits[i];
389
+ return next !== void 0 && next.start === marker.start && next.end === marker.end;
390
+ }) && [...this.own].every((marker) => markers.list.includes(marker)))) {
391
+ this.own = new Set(credits);
392
+ markers.set([...theirs, ...credits]);
393
+ }
394
+ const chapters = breaks.filter((entry) => entry.role === "chapter");
395
+ const api = this.player.engine?.chapters;
396
+ if (api !== void 0 && chapters.length > 0 && api.source !== "manifest" && api.source !== "app") api.set(chapters.map((entry, i) => ({
397
+ start: entry.start,
398
+ ...entry.covers > 0 ? { end: entry.start + entry.covers } : {},
399
+ title: `${i + 1}`
400
+ })));
401
+ }
402
+ pending(offset) {
403
+ if (this.fetching > 0) return true;
404
+ return [...this.plans.values()].some((plan) => plan.offset === offset && (plan.status === "waiting" || plan.status === "resolving"));
405
+ }
406
+ engineBreaks() {
407
+ return this.player.engine?.interstitials;
408
+ }
409
+ /** The programme's own time, through a break. */
410
+ programmeTime() {
411
+ return this.engineBreaks()?.primary.currentTime ?? this.player.media.currentTime;
412
+ }
413
+ programmeDuration() {
414
+ return this.engineBreaks()?.primary.duration ?? this.player.media.duration;
415
+ }
416
+ /** Fetches the VAST of each break as it comes near, and starts the progressive ones on time. */
417
+ tick() {
418
+ this.update();
419
+ if (this.current !== null) {
420
+ this.followAd(this.current);
421
+ return;
422
+ }
423
+ if (this.away()) return;
424
+ const time = this.programmeTime();
425
+ const duration = this.programmeDuration();
426
+ const seeked = Math.abs(time - this.lastTime) > 2;
427
+ for (const plan of this.plans.values()) {
428
+ const at = offsetTime(plan.offset, duration);
429
+ if (at === null) continue;
430
+ if (plan.status === "waiting" && (plan.offset === "start" || at - time <= LOOKAHEAD)) this.resolve(plan, at);
431
+ else if (plan.status === "progressive" && plan.offset !== "end" && !seeked && this.lastTime <= at && time >= at && plan.offset !== "start") {
432
+ this.startProgressive(plan);
433
+ break;
434
+ }
435
+ }
436
+ this.lastTime = time;
437
+ }
438
+ async resolve(plan, at) {
439
+ plan.status = "resolving";
440
+ const result = await resolveVast(plan.vast, this.fetchDoc);
441
+ if (this.plans.get(plan.id) !== plan) return;
442
+ const engine = this.engineBreaks() !== void 0;
443
+ const height = this.player.clientHeight;
444
+ const playable = [];
445
+ const files = [];
446
+ for (const ad of result.ads) {
447
+ const file = pick(ad, engine, this.player.media, height);
448
+ if (file === void 0 || !STREAMING.test(file.type) && this.progressive === "skip") {
449
+ for (const url of ad.errors) this.send(expand(url, { errorCode: 403 }));
450
+ continue;
451
+ }
452
+ playable.push(ad);
453
+ files.push(file);
454
+ }
455
+ if (result.ads.length === 0) for (const url of result.errors) this.send(expand(url, { errorCode: result.code ?? 303 }));
456
+ plan.ads = playable;
457
+ plan.files = files;
458
+ plan.start = at;
459
+ if (playable.length === 0) {
460
+ plan.status = "done";
461
+ this.vmapTrack(plan, "error");
462
+ this.emit("aderror", {
463
+ id: plan.id,
464
+ code: result.code ?? 403
465
+ });
466
+ this.release();
467
+ return;
468
+ }
469
+ const streams = files.every((file) => STREAMING.test(file.type));
470
+ if (engine && streams) {
471
+ plan.status = "stream";
472
+ const offsets = playable.flatMap((ad) => ad.skipOffset === void 0 ? [] : [ad.skipOffset]);
473
+ if (this.holding) {
474
+ this.holding = false;
475
+ this.player.media.play()?.catch(() => {});
476
+ }
477
+ this.engineBreaks()?.schedule({
478
+ id: plan.id,
479
+ start: at,
480
+ ...plan.offset === "start" ? { cue: "pre" } : plan.offset === "end" ? { cue: "post" } : {},
481
+ ...plan.covers !== void 0 ? { covers: plan.covers } : {},
482
+ assets: files.map((file, i) => ({
483
+ url: file.url,
484
+ duration: playable[i]?.duration ?? 0,
485
+ mimeType: /dash/i.test(file.type) ? "application/dash+xml" : "application/vnd.apple.mpegurl"
486
+ })),
487
+ noSkip: true,
488
+ noJump: true,
489
+ once: true,
490
+ ...offsets.length > 0 ? { skipAfter: Math.min(...offsets) } : {}
491
+ });
492
+ return;
493
+ }
494
+ plan.status = "progressive";
495
+ if (plan.offset === "start" && (this.holding || !this.player.media.paused)) {
496
+ this.holding = false;
497
+ this.player.media.pause();
498
+ this.startProgressive(plan);
499
+ }
500
+ }
501
+ /** Lets the programme play once no pre-roll holds it. */
502
+ release() {
503
+ if (!this.holding || this.pending("start")) return;
504
+ this.holding = false;
505
+ this.player.media.play()?.catch(() => {});
506
+ }
507
+ bindEngine() {
508
+ this.offEngine?.();
509
+ this.offEngine = null;
510
+ const engine = this.player.engine;
511
+ if (engine === null || this.engineBreaks() === void 0) return;
512
+ const on = (name, fn) => engine.on(`interstitials:${name}`, (payload) => fn(payload));
513
+ const offs = [
514
+ on("break-start", (p) => {
515
+ if (p.stitched === true && this.player.hasAttribute("scrubbing")) return;
516
+ this.engineBreakStart(p.break, p.stitched === true);
517
+ }),
518
+ on("asset-start", (p) => this.engineAssetStart(Number(p.asset))),
519
+ on("progress", (p) => this.quartile(Number(p.quartile))),
520
+ on("asset-end", () => this.adEnd()),
521
+ on("break-end", (p) => {
522
+ if (p.stitched === true && this.player.hasAttribute("scrubbing")) return;
523
+ this.breakEnd();
524
+ }),
525
+ on("warning", (p) => {
526
+ const current = this.current;
527
+ if (current?.ad !== void 0) for (const url of current.ad.errors) this.send(expand(url, {
528
+ ...this.macros(current),
529
+ errorCode: 405
530
+ }));
531
+ this.emit("aderror", {
532
+ id: p.id,
533
+ code: 405,
534
+ reason: p.reason
535
+ });
536
+ }),
537
+ on("opportunity", (p) => this.opportunity(p.break, Number(p.duration)))
538
+ ];
539
+ offs.push(engine.on("interstitials:changed", () => this.mark()));
540
+ this.offEngine = () => {
541
+ for (const off of offs) off();
542
+ };
543
+ this.mark();
544
+ }
545
+ /** After a drag: in an ad the stream plays, it starts; out of it, the ad that showed ends. */
546
+ landed() {
547
+ const time = this.player.media.currentTime;
548
+ const inside = (this.engineBreaks()?.breaks ?? []).find((entry) => entry.assets.length === 0 && entry.assetList === void 0 && time >= entry.start && time < entry.start + Math.max(entry.covers, .001));
549
+ const current = this.current;
550
+ if (current?.stitched === true && current.entry?.id !== inside?.id) this.breakEnd();
551
+ if (inside !== void 0 && this.current === null) this.engineBreakStart(inside, true);
552
+ }
553
+ engineBreakStart(entry, stitched) {
554
+ const plan = this.plans.get(entry.id) ?? null;
555
+ this.current = {
556
+ plan,
557
+ entry,
558
+ stitched,
559
+ index: -1,
560
+ ad: void 0,
561
+ creative: void 0,
562
+ file: void 0,
563
+ skipped: false,
564
+ quartiles: 0,
565
+ sent: /* @__PURE__ */ new Set(),
566
+ viewable: false,
567
+ paused: false,
568
+ interrupt: false,
569
+ last: 0,
570
+ at: this.programmeTime()
571
+ };
572
+ this.breakStart();
573
+ if (stitched) this.engineAssetStart(0);
574
+ }
575
+ engineAssetStart(index) {
576
+ const current = this.current;
577
+ if (current === null) return;
578
+ current.index = index;
579
+ current.ad = current.plan?.ads[index];
580
+ current.creative = current.stitched ? current.entry?.creatives?.[0] : current.entry?.assets[index]?.creatives?.[0];
581
+ current.file = current.plan?.files[index];
582
+ current.skipped = false;
583
+ current.quartiles = 0;
584
+ current.sent = /* @__PURE__ */ new Set();
585
+ current.viewable = false;
586
+ this.adStart(current);
587
+ }
588
+ opportunity(entry, duration) {
589
+ const url = this.onOpportunity?.({
590
+ id: entry.id,
591
+ start: entry.start,
592
+ duration
593
+ });
594
+ if (url === null || url === void 0) return;
595
+ this.add({
596
+ id: entry.id,
597
+ offset: { time: entry.start },
598
+ vast: { url: new URL(url, location.href).href },
599
+ tracking: [],
600
+ covers: duration
601
+ });
602
+ const plan = this.plans.get(entry.id);
603
+ if (plan !== void 0) this.resolve(plan, entry.start);
604
+ }
605
+ /** A break of progressive ads: each in the programme's place, then the programme again. */
606
+ startProgressive(plan) {
607
+ plan.status = "done";
608
+ this.current = {
609
+ plan,
610
+ entry: null,
611
+ stitched: false,
612
+ index: -1,
613
+ ad: void 0,
614
+ creative: void 0,
615
+ file: void 0,
616
+ skipped: false,
617
+ quartiles: 0,
618
+ sent: /* @__PURE__ */ new Set(),
619
+ viewable: false,
620
+ paused: false,
621
+ interrupt: true,
622
+ last: 0,
623
+ at: this.programmeTime()
624
+ };
625
+ this.breakStart();
626
+ this.nextProgressive();
627
+ }
628
+ nextProgressive() {
629
+ const current = this.current;
630
+ if (current === null || !current.interrupt || current.plan === null) return;
631
+ if (current.index >= 0) this.adEnd();
632
+ current.index += 1;
633
+ const ad = current.plan.ads[current.index];
634
+ const file = current.plan.files[current.index];
635
+ if (ad === void 0 || file === void 0) {
636
+ const plan = current.plan;
637
+ this.breakEnd();
638
+ this.player.resume(plan.offset === "end" ? {
639
+ at: plan.start ?? null,
640
+ playing: false
641
+ } : { playing: true });
642
+ return;
643
+ }
644
+ current.ad = ad;
645
+ current.file = file;
646
+ current.skipped = false;
647
+ current.quartiles = 0;
648
+ current.sent = /* @__PURE__ */ new Set();
649
+ current.viewable = false;
650
+ current.paused = false;
651
+ current.last = 0;
652
+ this.player.interrupt({
653
+ url: file.url,
654
+ type: file.type
655
+ }).catch(() => {
656
+ if (this.current !== current) return;
657
+ for (const url of ad.errors) this.send(expand(url, {
658
+ ...this.macros(current),
659
+ errorCode: 405
660
+ }));
661
+ this.emit("aderror", {
662
+ id: current.plan?.id,
663
+ code: 405
664
+ });
665
+ this.nextProgressive();
666
+ });
667
+ this.adStart(current);
668
+ }
669
+ breakStart() {
670
+ const current = this.current;
671
+ if (current === null) return;
672
+ this.player.setAttribute("ad", this.free(current) ? "stitched" : "");
673
+ if (current.plan !== null) this.vmapTrack(current.plan, "breakStart");
674
+ this.observe();
675
+ this.emit("adbreakstart", this.detail());
676
+ }
677
+ adStart(current) {
678
+ if (current.ad !== void 0) for (const url of current.ad.impressions) this.send(expand(url, this.macros(current)));
679
+ this.track(current, "impression");
680
+ this.track(current, "creativeView");
681
+ this.track(current, "start");
682
+ this.visibleSince = null;
683
+ this.emit("adstart", this.detail());
684
+ this.update();
685
+ }
686
+ quartile(n) {
687
+ const current = this.current;
688
+ if (current === null || n <= current.quartiles) return;
689
+ current.quartiles = n;
690
+ const event = QUARTILE_EVENTS[n - 1];
691
+ if (event !== void 0) this.track(current, event);
692
+ this.emit("adprogress", {
693
+ ...this.detail(),
694
+ quartile: n
695
+ });
696
+ }
697
+ /** The ad's own time: progressive quartiles, progress beacons, the stream's callbacks, viewability. */
698
+ followAd(current) {
699
+ const media = this.player.media;
700
+ const time = current.stitched ? this.player.media.currentTime - (current.entry?.start ?? 0) : media.currentTime;
701
+ if (current.interrupt && !media.seeking) current.last = time;
702
+ if (current.interrupt && Number.isFinite(media.duration) && media.duration > 0) {
703
+ const reached = Math.floor(time / media.duration * 4);
704
+ for (let n = current.quartiles + 1; n <= Math.min(3, reached); n += 1) this.quartile(n);
705
+ }
706
+ (current.ad?.tracking ?? []).forEach((entry, i) => {
707
+ if (entry.event !== "progress" || entry.offset === void 0 || current.sent.has(i) || time < entry.offset) return;
708
+ current.sent.add(i);
709
+ this.send(expand(entry.url, this.macros(current)));
710
+ });
711
+ (current.entry?.assets[current.index]?.tracking ?? []).forEach((entry, i) => {
712
+ const key = 1e3 + i;
713
+ if (current.sent.has(key) || time < entry.offset) return;
714
+ current.sent.add(key);
715
+ this.send(entry.url);
716
+ });
717
+ this.view(current);
718
+ }
719
+ adPaused(media) {
720
+ const current = this.current;
721
+ if (current === null || media.ended || current.paused) return;
722
+ current.paused = true;
723
+ this.track(current, "pause");
724
+ }
725
+ adResumed(media) {
726
+ const current = this.current;
727
+ if (current === null || !current.paused || media !== this.player.media) return;
728
+ current.paused = false;
729
+ this.track(current, "resume");
730
+ }
731
+ adVolume(media) {
732
+ const current = this.current;
733
+ if (current === null) return;
734
+ this.track(current, media.muted ? "mute" : "unmute");
735
+ }
736
+ adEnd() {
737
+ const current = this.current;
738
+ if (current === null || current.index < 0) return;
739
+ if (!current.skipped) this.track(current, "complete");
740
+ if (current.ad !== void 0 && !current.viewable) for (const url of current.ad.notViewable) this.send(expand(url, this.macros(current)));
741
+ this.emit("adend", this.detail());
742
+ }
743
+ breakEnd() {
744
+ const current = this.current;
745
+ if (current === null) return;
746
+ if (current.stitched) this.adEnd();
747
+ if (current.plan !== null) {
748
+ current.plan.status = "done";
749
+ this.vmapTrack(current.plan, "breakEnd");
750
+ }
751
+ const detail = this.detail();
752
+ const id = current.plan?.id ?? current.entry?.id;
753
+ if (id !== void 0) this.done.add(id);
754
+ this.current = null;
755
+ this.player.removeAttribute("ad");
756
+ this.mark();
757
+ this.observer?.disconnect();
758
+ this.observer = null;
759
+ this.emit("adbreakend", detail);
760
+ this.update();
761
+ }
762
+ /** MRC: half the player in view for two seconds in a row. */
763
+ observe() {
764
+ if (typeof IntersectionObserver === "undefined" || this.observer !== null) return;
765
+ this.observer = new IntersectionObserver((entries) => {
766
+ const seen = entries.some((entry) => entry.intersectionRatio >= .5);
767
+ this.visibleSince = seen ? this.visibleSince ?? performance.now() : null;
768
+ }, { threshold: [0, .5] });
769
+ this.observer.observe(this.player);
770
+ }
771
+ view(current) {
772
+ if (current.viewable || current.ad === void 0 || this.visibleSince === null) return;
773
+ if (performance.now() - this.visibleSince < 2e3) return;
774
+ current.viewable = true;
775
+ for (const url of current.ad.viewable) this.send(expand(url, this.macros(current)));
776
+ this.emit("adviewable", this.detail());
777
+ }
778
+ macros(current) {
779
+ const media = this.player.media;
780
+ const offset = current.plan?.offset;
781
+ return {
782
+ mediaPlayhead: current.at,
783
+ adPlayhead: media.currentTime,
784
+ ...current.file !== void 0 ? { assetUri: current.file.url } : {},
785
+ breakPosition: offset === "start" ? 1 : offset === "end" ? 3 : 2,
786
+ playerSize: [this.player.clientWidth, this.player.clientHeight]
787
+ };
788
+ }
789
+ track(current, event) {
790
+ for (const entry of current.ad?.tracking ?? []) if (entry.event === event) this.send(expand(entry.url, this.macros(current)));
791
+ }
792
+ vmapTrack(plan, event) {
793
+ for (const entry of plan.tracking) if (entry.event === event) this.send(entry.url);
794
+ }
795
+ detail() {
796
+ const current = this.current;
797
+ return {
798
+ breakId: current?.plan?.id ?? current?.entry?.id ?? null,
799
+ index: (current?.index ?? 0) + 1,
800
+ ad: current?.ad ?? null,
801
+ stitched: current?.stitched ?? false
802
+ };
803
+ }
804
+ emit(name, detail) {
805
+ this.player.dispatchEvent(new CustomEvent(name, { detail }));
806
+ }
807
+ update() {
808
+ for (const fn of [...this.watchers]) fn();
809
+ }
810
+ reset() {
811
+ if (this.current !== null) this.player.removeAttribute("ad");
812
+ this.current = null;
813
+ this.plans = /* @__PURE__ */ new Map();
814
+ this.given = {
815
+ urls: [],
816
+ breaks: []
817
+ };
818
+ this.done = /* @__PURE__ */ new Set();
819
+ this.own = /* @__PURE__ */ new Set();
820
+ this.player.breaks.set("ads", []);
821
+ this.holding = false;
822
+ this.lastTime = 0;
823
+ this.observer?.disconnect();
824
+ this.observer = null;
825
+ this.update();
826
+ }
827
+ };
828
+ export { Controller, controllerFor };
829
+
830
+ //# sourceMappingURL=controller.js.map