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