@streamlayer/feature-advertisement 0.4.3 → 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.
@@ -0,0 +1,20 @@
1
+ import type { SsaiCreative } from './ssai-creative';
2
+ /**
3
+ * How long the overlay is willing to wait for artwork. A slow or dead image host
4
+ * must never hold the bar back — the ad is already playing, and a bar that shows
5
+ * late is worse than one that shows without its logo (the logo is hidden on error
6
+ * anyway). Warming the browser cache is the goal; blocking is not.
7
+ */
8
+ export declare const DEFAULT_PRELOAD_TIMEOUT_MS = 2000;
9
+ /**
10
+ * Fetch images into the browser cache and resolve once they are all settled, or
11
+ * once `timeoutMs` elapses — whichever comes first. Never rejects: a creative
12
+ * whose artwork fails is still a creative worth showing.
13
+ */
14
+ export declare const preloadImages: (urls: (string | undefined | null)[], timeoutMs?: number) => Promise<void>;
15
+ /**
16
+ * Warm every image the creative carries — the overlay's brand logo, and the
17
+ * companion banner for hosts that render one — so the bar fades in complete
18
+ * rather than popping its artwork in a beat later.
19
+ */
20
+ export declare const preloadCreativeAssets: (creative: SsaiCreative, timeoutMs?: number) => Promise<void>;
@@ -0,0 +1,55 @@
1
+ import { createLogger } from '@streamlayer/sdk-web-logger';
2
+ const log = createLogger('ssai:preload');
3
+ /**
4
+ * How long the overlay is willing to wait for artwork. A slow or dead image host
5
+ * must never hold the bar back — the ad is already playing, and a bar that shows
6
+ * late is worse than one that shows without its logo (the logo is hidden on error
7
+ * anyway). Warming the browser cache is the goal; blocking is not.
8
+ */
9
+ export const DEFAULT_PRELOAD_TIMEOUT_MS = 2000;
10
+ /**
11
+ * Fetch images into the browser cache and resolve once they are all settled, or
12
+ * once `timeoutMs` elapses — whichever comes first. Never rejects: a creative
13
+ * whose artwork fails is still a creative worth showing.
14
+ */
15
+ export const preloadImages = (urls, timeoutMs = DEFAULT_PRELOAD_TIMEOUT_MS) => {
16
+ const targets = urls.filter((url) => !!url);
17
+ // `Image` is absent in SSR/worker contexts; there is nothing to warm there.
18
+ if (targets.length === 0 || typeof Image === 'undefined') {
19
+ return Promise.resolve();
20
+ }
21
+ return new Promise((resolve) => {
22
+ let settled = false;
23
+ let remaining = targets.length;
24
+ const finish = () => {
25
+ if (settled) {
26
+ return;
27
+ }
28
+ settled = true;
29
+ clearTimeout(timer);
30
+ resolve();
31
+ };
32
+ const timer = setTimeout(() => {
33
+ log.debug({ remaining }, 'ssai preload timed out, showing anyway');
34
+ finish();
35
+ }, timeoutMs);
36
+ const one = () => {
37
+ remaining -= 1;
38
+ if (remaining <= 0) {
39
+ finish();
40
+ }
41
+ };
42
+ for (const url of targets) {
43
+ const image = new Image();
44
+ image.onload = one;
45
+ image.onerror = one;
46
+ image.src = url;
47
+ }
48
+ });
49
+ };
50
+ /**
51
+ * Warm every image the creative carries — the overlay's brand logo, and the
52
+ * companion banner for hosts that render one — so the bar fades in complete
53
+ * rather than popping its artwork in a beat later.
54
+ */
55
+ export const preloadCreativeAssets = (creative, timeoutMs) => preloadImages([creative.iconUrl, creative.companion?.staticResource], timeoutMs);
@@ -0,0 +1,117 @@
1
+ import type { SsaiCreative } from './ssai-creative';
2
+ export declare const DEFAULT_CREATIVE_API_BASE = "https://hls.next.streamlayer.io/api/creatives/";
3
+ /**
4
+ * A creative provider encapsulates everything that differs between ad sources:
5
+ * how a creativeId resolves to the normalized {@link SsaiCreative}, and how
6
+ * impressions (and, in the future, other tracking events) are fired. The overlay
7
+ * UI only ever sees the normalized shape, so it never learns about providers.
8
+ */
9
+ export interface SsaiCreativeProvider {
10
+ /** Stable id for logging/diagnostics, e.g. 'streamlayer' | 'vast'. */
11
+ readonly id: string;
12
+ /** Resolve a creativeId (from EXT-X-DATERANGE) to the normalized SsaiCreative. */
13
+ resolve(creativeId: string, signal: AbortSignal): Promise<SsaiCreative>;
14
+ /**
15
+ * Fire an impression for a resolved creative. Provider-specific (URL shape,
16
+ * beacon vs pixel vs SDK call). Optional — falls back to the shared default
17
+ * (first trackingEvent named 'impression' via sendBeacon/fetch) when omitted.
18
+ */
19
+ fireImpression?(creative: SsaiCreative): void;
20
+ /** Optional hook for other tracking events (click, quartiles) — future-facing, no-op default. */
21
+ fireTracking?(creative: SsaiCreative, event: string): void;
22
+ }
23
+ /**
24
+ * Shared low-level beacon helper. Prefers `navigator.sendBeacon` and falls back
25
+ * to a no-cors `fetch`. Used by the default impression path and available to
26
+ * providers that fire URL-based tracking pixels.
27
+ */
28
+ export declare const fireBeacon: (url: string) => void;
29
+ /**
30
+ * Fire every tracking event with the given name, and report how many went out.
31
+ *
32
+ * ALL matches, not the first: the creative contract states that a creative may
33
+ * repeat an `event` value to carry several URLs, and that consumers must not
34
+ * assume uniqueness. Today's payloads carry one URL per event, so this is not a
35
+ * change in what goes on the wire — it just stops being wrong the day a server
36
+ * sends two.
37
+ */
38
+ export declare const fireTrackingEvents: (creative: SsaiCreative, event: string) => number;
39
+ /**
40
+ * Shared default impression behavior: fire the `impression` tracking events.
41
+ * Used by the StreamLayer provider and as the fallback in
42
+ * {@link SsaiCreativeCache} when a provider doesn't override `fireImpression`.
43
+ * Exported so both call sites share one definition.
44
+ */
45
+ export declare const fireDefaultImpression: (creative: SsaiCreative) => void;
46
+ export type StreamLayerProviderConfig = {
47
+ /** Base URL of the StreamLayer JSON creative metadata API. */
48
+ creativeApiBase?: string;
49
+ };
50
+ /**
51
+ * StreamLayer's internal creative provider. Resolves creatives from the JSON
52
+ * creative API (`GET {creativeApiBase}{encodeURIComponent(creativeId)}`) and
53
+ * fires impressions from the `'impression'` tracking event via `sendBeacon`.
54
+ */
55
+ export declare const createStreamLayerProvider: (config?: StreamLayerProviderConfig) => SsaiCreativeProvider;
56
+ export type QuortexProviderConfig = {
57
+ /**
58
+ * Full URL of the tenant's ad metadata endpoint, e.g.
59
+ * `https://ads.example.com/get_ad` or, with the tenant baked in,
60
+ * `https://ads.example.com/get_ad?TenantName=acme`. Required — this is
61
+ * customer infrastructure, so there is no sensible SDK-level default.
62
+ */
63
+ adApiBase?: string;
64
+ /**
65
+ * Tenant the ad ids belong to, appended as the `TenantName` query parameter.
66
+ * Optional: omit it when `adApiBase` already carries the tenant.
67
+ */
68
+ tenantName?: string;
69
+ };
70
+ /**
71
+ * Quortex / Synamedia DAI ad metadata provider.
72
+ *
73
+ * `GET {adApiBase}?TenantName={tenantName}&adID={adId}&info=1` (the `TenantName`
74
+ * part omitted when `adApiBase` already carries it) — the ad id comes
75
+ * from the manifest's `X-AD-ID` DATERANGE attribute (see `ssai-detector.ts`, which
76
+ * reconstructs the ad window from the tracking-marker burst those tags form).
77
+ *
78
+ * The response is byte-compatible with the StreamLayer creative API, so the same
79
+ * `mapApiResponse` normalizes both.
80
+ *
81
+ * Known limitation: impressions fire the `impression` tracking event from the API
82
+ * response, not the per-session beacon the manifest carries in `X-AD-URL`. The two
83
+ * differ in `trackingid`/`USERID`, so Quortex-side attribution will see the
84
+ * generic id rather than the viewer's session until the manifest beacons are
85
+ * plumbed through to the provider.
86
+ */
87
+ export declare const createQuortexProvider: (config?: QuortexProviderConfig) => SsaiCreativeProvider;
88
+ export type VastProviderConfig = Record<string, never>;
89
+ /**
90
+ * Maps a VAST tag into the normalized SsaiCreative shape.
91
+ *
92
+ * Note: `fireImpression` is intentionally left to the shared default for now.
93
+ * Proper VAST impression/tracking wiring through `VASTTracker` is a documented
94
+ * follow-up; it requires retaining the parsed ad/tracker per creative.
95
+ */
96
+ export declare const createVastProvider: (_config?: VastProviderConfig) => SsaiCreativeProvider;
97
+ export type SsaiProviderName = 'streamlayer' | 'quortex' | 'vast';
98
+ /** Union of every built-in provider's config; each factory reads its own keys. */
99
+ export type SsaiProviderConfig = StreamLayerProviderConfig & QuortexProviderConfig;
100
+ /** Built-in provider factories keyed by name. */
101
+ export declare const BUILTIN_PROVIDERS: Record<SsaiProviderName, (config?: SsaiProviderConfig) => SsaiCreativeProvider>;
102
+ export type SsaiProviderOption =
103
+ /** A ready provider instance (built-in or fully custom). */
104
+ SsaiCreativeProvider
105
+ /** A built-in provider selected by name. */
106
+ | SsaiProviderName
107
+ /** A built-in provider selected by name with optional config. */
108
+ | {
109
+ name: SsaiProviderName;
110
+ config?: SsaiProviderConfig;
111
+ };
112
+ /**
113
+ * Resolve a {@link SsaiProviderOption} into a concrete {@link SsaiCreativeProvider}.
114
+ * Defaults to the StreamLayer provider (using `fallbackConfig`) when no option is
115
+ * supplied.
116
+ */
117
+ export declare const resolveProvider: (option?: SsaiProviderOption, fallbackConfig?: SsaiProviderConfig) => SsaiCreativeProvider;
@@ -0,0 +1,250 @@
1
+ import { createLogger } from '@streamlayer/sdk-web-logger';
2
+ import { VASTClient } from '@dailymotion/vast-client';
3
+ const log = createLogger('ssai:provider');
4
+ export const DEFAULT_CREATIVE_API_BASE = 'https://hls.next.streamlayer.io/api/creatives/';
5
+ /**
6
+ * Shared low-level beacon helper. Prefers `navigator.sendBeacon` and falls back
7
+ * to a no-cors `fetch`. Used by the default impression path and available to
8
+ * providers that fire URL-based tracking pixels.
9
+ */
10
+ export const fireBeacon = (url) => {
11
+ try {
12
+ if (typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {
13
+ navigator.sendBeacon(url);
14
+ }
15
+ else {
16
+ void fetch(url, { mode: 'no-cors' }).catch((error) => {
17
+ log.warn(error, 'ssai beacon failed');
18
+ });
19
+ }
20
+ }
21
+ catch (error) {
22
+ log.warn(error, 'ssai beacon failed');
23
+ }
24
+ };
25
+ const resolveAdvertiser = (advertiser, title) => {
26
+ if (advertiser) {
27
+ return advertiser;
28
+ }
29
+ if (title) {
30
+ return title;
31
+ }
32
+ return 'Ad';
33
+ };
34
+ const buildCreativeUrl = (base, creativeId) => {
35
+ const normalizedBase = base.endsWith('/') ? base : `${base}/`;
36
+ return `${normalizedBase}${encodeURIComponent(creativeId)}`;
37
+ };
38
+ const mapApiResponse = (raw) => {
39
+ const trackingEvents = Array.isArray(raw.trackingEvents)
40
+ ? raw.trackingEvents
41
+ .filter((entry) => Boolean(entry?.event && entry?.url))
42
+ .map((entry) => ({ event: entry.event, url: entry.url }))
43
+ : [];
44
+ const rawCompanion = Array.isArray(raw.companions)
45
+ ? raw.companions.find((entry) => !!entry?.staticResource)
46
+ : undefined;
47
+ const companion = rawCompanion?.staticResource
48
+ ? {
49
+ staticResource: rawCompanion.staticResource,
50
+ width: Number(rawCompanion.width) || 0,
51
+ height: Number(rawCompanion.height) || 0,
52
+ clickThrough: rawCompanion.clickThrough,
53
+ clickTracking: Array.isArray(rawCompanion.clickTracking)
54
+ ? rawCompanion.clickTracking.filter((url) => typeof url === 'string' && !!url)
55
+ : [],
56
+ }
57
+ : undefined;
58
+ return {
59
+ creativeId: raw.creativeId,
60
+ advertiser: resolveAdvertiser(raw.advertiser, raw.title),
61
+ title: raw.title || resolveAdvertiser(raw.advertiser, raw.title),
62
+ iconUrl: raw.iconUrl || undefined,
63
+ clickThroughUrl: raw.clickThroughUrl || undefined,
64
+ trackingEvents,
65
+ companion,
66
+ };
67
+ };
68
+ /**
69
+ * Fire every tracking event with the given name, and report how many went out.
70
+ *
71
+ * ALL matches, not the first: the creative contract states that a creative may
72
+ * repeat an `event` value to carry several URLs, and that consumers must not
73
+ * assume uniqueness. Today's payloads carry one URL per event, so this is not a
74
+ * change in what goes on the wire — it just stops being wrong the day a server
75
+ * sends two.
76
+ */
77
+ export const fireTrackingEvents = (creative, event) => {
78
+ const matches = creative.trackingEvents.filter((entry) => entry.event === event);
79
+ for (const match of matches) {
80
+ fireBeacon(match.url);
81
+ }
82
+ return matches.length;
83
+ };
84
+ /**
85
+ * Shared default impression behavior: fire the `impression` tracking events.
86
+ * Used by the StreamLayer provider and as the fallback in
87
+ * {@link SsaiCreativeCache} when a provider doesn't override `fireImpression`.
88
+ * Exported so both call sites share one definition.
89
+ */
90
+ export const fireDefaultImpression = (creative) => {
91
+ fireTrackingEvents(creative, 'impression');
92
+ };
93
+ /**
94
+ * StreamLayer's internal creative provider. Resolves creatives from the JSON
95
+ * creative API (`GET {creativeApiBase}{encodeURIComponent(creativeId)}`) and
96
+ * fires impressions from the `'impression'` tracking event via `sendBeacon`.
97
+ */
98
+ export const createStreamLayerProvider = (config = {}) => {
99
+ const creativeApiBase = config.creativeApiBase ?? DEFAULT_CREATIVE_API_BASE;
100
+ return {
101
+ id: 'streamlayer',
102
+ resolve: async (creativeId, signal) => {
103
+ const url = buildCreativeUrl(creativeApiBase, creativeId);
104
+ const response = await fetch(url, { signal });
105
+ if (!response.ok) {
106
+ throw new Error(`creative request failed: ${response.status}`);
107
+ }
108
+ const raw = (await response.json());
109
+ return mapApiResponse({ ...raw, creativeId: raw.creativeId || creativeId });
110
+ },
111
+ fireImpression: fireDefaultImpression,
112
+ };
113
+ };
114
+ const buildQuortexUrl = (base, tenantName, adId) => {
115
+ // Deliberately string concatenation rather than `URL`/`URLSearchParams`: this
116
+ // package ships to 2016-era TV engines (see the chrome-32 classic build).
117
+ const separator = base.indexOf('?') === -1 ? '?' : '&';
118
+ const tenant = tenantName ? `TenantName=${encodeURIComponent(tenantName)}&` : '';
119
+ return `${base}${separator}${tenant}adID=${encodeURIComponent(adId)}&info=1`;
120
+ };
121
+ /**
122
+ * Quortex / Synamedia DAI ad metadata provider.
123
+ *
124
+ * `GET {adApiBase}?TenantName={tenantName}&adID={adId}&info=1` (the `TenantName`
125
+ * part omitted when `adApiBase` already carries it) — the ad id comes
126
+ * from the manifest's `X-AD-ID` DATERANGE attribute (see `ssai-detector.ts`, which
127
+ * reconstructs the ad window from the tracking-marker burst those tags form).
128
+ *
129
+ * The response is byte-compatible with the StreamLayer creative API, so the same
130
+ * `mapApiResponse` normalizes both.
131
+ *
132
+ * Known limitation: impressions fire the `impression` tracking event from the API
133
+ * response, not the per-session beacon the manifest carries in `X-AD-URL`. The two
134
+ * differ in `trackingid`/`USERID`, so Quortex-side attribution will see the
135
+ * generic id rather than the viewer's session until the manifest beacons are
136
+ * plumbed through to the provider.
137
+ */
138
+ export const createQuortexProvider = (config = {}) => {
139
+ const { adApiBase, tenantName } = config;
140
+ if (!adApiBase) {
141
+ // Loud, but not thrown: this runs inside the host's render effect via
142
+ // `startSsaiMonitoring`, and taking the app down over a config typo is worse
143
+ // than an overlay that never appears and says why.
144
+ log.error({ adApiBase, tenantName }, 'quortex provider requires `adApiBase`');
145
+ }
146
+ return {
147
+ id: 'quortex',
148
+ resolve: async (adId, signal) => {
149
+ if (!adApiBase) {
150
+ throw new Error('quortex provider is missing `adApiBase`');
151
+ }
152
+ const response = await fetch(buildQuortexUrl(adApiBase, tenantName, adId), { signal });
153
+ if (!response.ok) {
154
+ throw new Error(`quortex creative request failed: ${response.status}`);
155
+ }
156
+ const raw = (await response.json());
157
+ return mapApiResponse({ ...raw, creativeId: raw.creativeId || adId });
158
+ },
159
+ fireImpression: fireDefaultImpression,
160
+ };
161
+ };
162
+ // --- VAST provider ---------------------------------------------------------
163
+ const mapVastResponse = async (creativeId, signal) => {
164
+ const vastClient = new VASTClient();
165
+ const parsedVAST = await vastClient.get(creativeId, { timeout: 8000 });
166
+ if (signal.aborted) {
167
+ throw new DOMException('aborted', 'AbortError');
168
+ }
169
+ const validAd = parsedVAST.ads.find((ad) => ad.creatives.length > 0);
170
+ if (!validAd) {
171
+ throw new Error('no_valid_ad');
172
+ }
173
+ const advertiserValue = Array.isArray(validAd.advertiser)
174
+ ? validAd.advertiser.find((entry) => !!entry?.value)?.value
175
+ : undefined;
176
+ const advertiser = resolveAdvertiser(advertiserValue, validAd.title || undefined);
177
+ let iconUrl;
178
+ let clickThroughUrl;
179
+ let companion;
180
+ for (const creative of validAd.creatives) {
181
+ if (creative.type === 'linear') {
182
+ const linear = creative;
183
+ iconUrl = iconUrl || linear.icons?.find((icon) => !!icon?.staticResource)?.staticResource || undefined;
184
+ clickThroughUrl = clickThroughUrl || linear.videoClickThroughURLTemplate?.url;
185
+ }
186
+ if (creative.type === 'companion') {
187
+ const variation = creative.variations?.[0];
188
+ const staticResource = variation?.staticResources?.[0]?.url;
189
+ if (staticResource && !companion) {
190
+ companion = {
191
+ staticResource,
192
+ width: Number(variation?.width) || 0,
193
+ height: Number(variation?.height) || 0,
194
+ clickThrough: variation?.companionClickThroughURLTemplate?.url,
195
+ clickTracking: (variation?.companionClickTrackingURLTemplates ?? [])
196
+ .map((entry) => entry?.url)
197
+ .filter((url) => !!url),
198
+ };
199
+ }
200
+ }
201
+ }
202
+ return {
203
+ creativeId,
204
+ advertiser,
205
+ title: validAd.title || advertiser,
206
+ iconUrl,
207
+ clickThroughUrl,
208
+ trackingEvents: [],
209
+ companion,
210
+ };
211
+ };
212
+ /**
213
+ * Maps a VAST tag into the normalized SsaiCreative shape.
214
+ *
215
+ * Note: `fireImpression` is intentionally left to the shared default for now.
216
+ * Proper VAST impression/tracking wiring through `VASTTracker` is a documented
217
+ * follow-up; it requires retaining the parsed ad/tracker per creative.
218
+ */
219
+ export const createVastProvider = (_config = {}) => {
220
+ return {
221
+ id: 'vast',
222
+ resolve: mapVastResponse,
223
+ };
224
+ };
225
+ /** Built-in provider factories keyed by name. */
226
+ export const BUILTIN_PROVIDERS = {
227
+ streamlayer: (config) => createStreamLayerProvider(config),
228
+ quortex: (config) => createQuortexProvider(config),
229
+ vast: () => createVastProvider(),
230
+ };
231
+ const isProviderInstance = (option) => {
232
+ return typeof option === 'object' && typeof option.resolve === 'function';
233
+ };
234
+ /**
235
+ * Resolve a {@link SsaiProviderOption} into a concrete {@link SsaiCreativeProvider}.
236
+ * Defaults to the StreamLayer provider (using `fallbackConfig`) when no option is
237
+ * supplied.
238
+ */
239
+ export const resolveProvider = (option, fallbackConfig) => {
240
+ if (!option) {
241
+ return createStreamLayerProvider(fallbackConfig);
242
+ }
243
+ if (typeof option === 'string') {
244
+ return BUILTIN_PROVIDERS[option](fallbackConfig);
245
+ }
246
+ if (isProviderInstance(option)) {
247
+ return option;
248
+ }
249
+ return BUILTIN_PROVIDERS[option.name](option.config ?? fallbackConfig);
250
+ };
@@ -0,0 +1,45 @@
1
+ /**
2
+ * One place that constructs a `VASTTracker`.
3
+ *
4
+ * Every StreamLayer surface that reports VAST beacons — the GAM video player, both pause-ad
5
+ * renderers and the Standard Ad sidebar — needs the same `(ad, creative, variation)` triple, and
6
+ * each was assembling it by hand behind its own `@ts-ignore`. The parsed shapes those triples
7
+ * come from (`AdData` / `AdCompanion` / `AdNonLinear`) are defined in this package, so the
8
+ * mapping belongs here too.
9
+ *
10
+ * Deliberately *only* construction: when a beacon may fire, and how a surface de-duplicates its
11
+ * impression, stays with that surface. Those policies differ on purpose (per-ad-id in module
12
+ * scope for the sidebar, per component instance for the pause ads, per tracker identity for the
13
+ * player) and they are billing-visible, so collapsing them here would silently change counts.
14
+ */
15
+ import { VASTTracker, VastAd, VastCompanionAd, VastCreativeCompanion, VastCreativeLinear, VastCreativeNonLinear, VastNonLinearAd } from '@dailymotion/vast-client';
16
+ import type { AdCompanion, AdData } from './external-ad';
17
+ /** The creative (and, for non-linear creatives, the variation) a tracker reports through. */
18
+ export type VastTrackerTarget = {
19
+ ad: VastAd;
20
+ /** `<Linear>`, `<NonLinearAds>` or `<CompanionAds>` — whichever owns the `<TrackingEvents>`. */
21
+ creative: VastCreativeLinear | VastCreativeNonLinear | VastCreativeCompanion;
22
+ /**
23
+ * The `<NonLinear>` / `<Companion>` variation. Omitted for a linear creative; required for the
24
+ * others, since the variation is what owns their `creativeView`, click-through and click
25
+ * trackers.
26
+ */
27
+ variation?: VastNonLinearAd | VastCompanionAd;
28
+ };
29
+ export declare const createVastTracker: ({ ad, creative, variation }: VastTrackerTarget) => VASTTracker;
30
+ /**
31
+ * A tracker for a single `<Companion>`. A `<CompanionAds>` creative has no creative-level
32
+ * `<TrackingEvents>` — each variation owns its own `creativeView` — so a companion is reported
33
+ * through its own tracker. `undefined` when the companion was parsed without them (nothing to
34
+ * report against).
35
+ */
36
+ export declare const createCompanionTracker: (ad: VastAd, companion: AdCompanion) => VASTTracker | undefined;
37
+ /**
38
+ * The creative a parsed ad reports its impression / playback beacons through, in the order the
39
+ * shells draw them: the `<Linear>` creative first, then the `<NonLinear>` still, then — for a tag
40
+ * whose only creative is `<CompanionAds>` — the companion that was actually drawn.
41
+ *
42
+ * `drawnCompanion` is a parameter rather than `adData.companion` because only the rendering shell
43
+ * knows which companion reached the screen, and reporting one that did not is a false view.
44
+ */
45
+ export declare const resolveVastTrackerTarget: (adData: AdData, drawnCompanion?: AdCompanion) => VastTrackerTarget | undefined;
@@ -0,0 +1,57 @@
1
+ /**
2
+ * One place that constructs a `VASTTracker`.
3
+ *
4
+ * Every StreamLayer surface that reports VAST beacons — the GAM video player, both pause-ad
5
+ * renderers and the Standard Ad sidebar — needs the same `(ad, creative, variation)` triple, and
6
+ * each was assembling it by hand behind its own `@ts-ignore`. The parsed shapes those triples
7
+ * come from (`AdData` / `AdCompanion` / `AdNonLinear`) are defined in this package, so the
8
+ * mapping belongs here too.
9
+ *
10
+ * Deliberately *only* construction: when a beacon may fire, and how a surface de-duplicates its
11
+ * impression, stays with that surface. Those policies differ on purpose (per-ad-id in module
12
+ * scope for the sidebar, per component instance for the pause ads, per tracker identity for the
13
+ * player) and they are billing-visible, so collapsing them here would silently change counts.
14
+ */
15
+ // eslint-disable-next-line @typescript-eslint/triple-slash-reference
16
+ /// <reference path="../module.d.ts" />
17
+ import { VASTTracker, } from '@dailymotion/vast-client';
18
+ export const createVastTracker = ({ ad, creative, variation }) =>
19
+ // The first argument is the `VASTClient` the tracker may update; every surface here drives
20
+ // playback itself and only wants the beacons, so it is always `null`.
21
+ //
22
+ // The type shim declares the 3rd argument as `VastCreativeLinear` and the 4th as another
23
+ // *creative*. At runtime `vast-client` accepts any creative in the 3rd and expects the
24
+ // `<Companion>` / `<NonLinear>` *variation* in the 4th. The casts encode that runtime contract
25
+ // once here rather than at every call site.
26
+ new VASTTracker(null, ad, creative, variation);
27
+ /**
28
+ * A tracker for a single `<Companion>`. A `<CompanionAds>` creative has no creative-level
29
+ * `<TrackingEvents>` — each variation owns its own `creativeView` — so a companion is reported
30
+ * through its own tracker. `undefined` when the companion was parsed without them (nothing to
31
+ * report against).
32
+ */
33
+ export const createCompanionTracker = (ad, companion) => companion.creative && companion.variation
34
+ ? createVastTracker({ ad, creative: companion.creative, variation: companion.variation })
35
+ : undefined;
36
+ /**
37
+ * The creative a parsed ad reports its impression / playback beacons through, in the order the
38
+ * shells draw them: the `<Linear>` creative first, then the `<NonLinear>` still, then — for a tag
39
+ * whose only creative is `<CompanionAds>` — the companion that was actually drawn.
40
+ *
41
+ * `drawnCompanion` is a parameter rather than `adData.companion` because only the rendering shell
42
+ * knows which companion reached the screen, and reporting one that did not is a false view.
43
+ */
44
+ export const resolveVastTrackerTarget = (adData, drawnCompanion) => {
45
+ // `AdData.creative` is not optional in the type but `getCreative` can return nothing: a
46
+ // programmatic tag does not have to carry a `<Linear>` creative.
47
+ if (adData.creative) {
48
+ return { ad: adData.ad, creative: adData.creative };
49
+ }
50
+ if (adData.nonLinear) {
51
+ return { ad: adData.ad, creative: adData.nonLinear.creative, variation: adData.nonLinear.variation };
52
+ }
53
+ if (drawnCompanion?.creative && drawnCompanion.variation) {
54
+ return { ad: adData.ad, creative: drawnCompanion.creative, variation: drawnCompanion.variation };
55
+ }
56
+ return undefined;
57
+ };
package/package.json CHANGED
@@ -1,15 +1,17 @@
1
1
  {
2
2
  "name": "@streamlayer/feature-advertisement",
3
- "version": "0.4.3",
3
+ "version": "1.1.0",
4
4
  "peerDependencies": {
5
- "@dailymotion/vast-client": "^6.4.2",
6
- "@streamlayer/sl-eslib": "^5.229.1",
5
+ "@dailymotion/vast-client": "^6.4.5",
6
+ "@streamlayer/sl-eslib": "^5.268.1",
7
+ "uuid": "^11.1.0",
7
8
  "nanostores": "^1.1.0",
8
- "@streamlayer/sdk-web-core": "^1.22.6",
9
- "@streamlayer/sdk-web-api": "^1.17.6",
10
- "@streamlayer/sdk-web-interfaces": "^1.10.6",
11
- "@streamlayer/sdk-web-logger": "^1.1.6",
12
- "@streamlayer/sdk-web-types": "^1.18.6"
9
+ "@streamlayer/sdk-web-core": "^1.23.1",
10
+ "@streamlayer/sdk-web-api": "^1.18.1",
11
+ "@streamlayer/sdk-web-interfaces": "^1.11.1",
12
+ "@streamlayer/sdk-web-types": "^2.0.1",
13
+ "@streamlayer/sdk-web-logger": "^1.2.1",
14
+ "@streamlayer/sdk-web-storage": "^1.2.1"
13
15
  },
14
16
  "devDependencies": {
15
17
  "@types/vast-client": "^3.0.4"