@streamlayer/feature-advertisement 1.0.0 → 1.1.1-rc.1342

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 (68) hide show
  1. package/classic/package.json +5 -0
  2. package/lib/cjs/advertisement.d.ts +64 -0
  3. package/lib/cjs/advertisement.js +307 -0
  4. package/lib/cjs/index.d.ts +19 -0
  5. package/lib/cjs/index.js +39 -0
  6. package/lib/cjs/package.json +1 -0
  7. package/lib/cjs/units/external-ad.d.ts +58 -0
  8. package/lib/cjs/units/external-ad.js +390 -0
  9. package/lib/cjs/units/external-pause-ad.d.ts +50 -0
  10. package/lib/cjs/units/external-pause-ad.js +253 -0
  11. package/lib/cjs/units/gam.d.ts +16 -0
  12. package/lib/cjs/units/gam.js +104 -0
  13. package/lib/cjs/units/parse-vast-extensions.d.ts +17 -0
  14. package/lib/cjs/units/parse-vast-extensions.js +52 -0
  15. package/lib/cjs/units/pause-ad-card.d.ts +49 -0
  16. package/lib/cjs/units/pause-ad-card.js +136 -0
  17. package/lib/cjs/units/pause-ad.d.ts +16 -0
  18. package/lib/cjs/units/pause-ad.js +52 -0
  19. package/lib/cjs/units/ssai-ad-break.d.ts +21 -0
  20. package/lib/cjs/units/ssai-ad-break.js +11 -0
  21. package/lib/cjs/units/ssai-creative.d.ts +89 -0
  22. package/lib/cjs/units/ssai-creative.js +136 -0
  23. package/lib/cjs/units/ssai-detector.d.ts +180 -0
  24. package/lib/cjs/units/ssai-detector.js +1156 -0
  25. package/lib/cjs/units/ssai-preload.d.ts +20 -0
  26. package/lib/cjs/units/ssai-preload.js +62 -0
  27. package/lib/cjs/units/ssai-providers.d.ts +117 -0
  28. package/lib/cjs/units/ssai-providers.js +263 -0
  29. package/lib/cjs/units/vast-tracker.d.ts +45 -0
  30. package/lib/cjs/units/vast-tracker.js +64 -0
  31. package/lib/classic/_virtual/_rollupPluginBabelHelpers.js +71 -0
  32. package/lib/classic/advertisement.js +331 -0
  33. package/lib/classic/cjs/_virtual/_rollupPluginBabelHelpers.js +77 -0
  34. package/lib/classic/cjs/advertisement.js +333 -0
  35. package/lib/classic/cjs/index.js +47 -0
  36. package/lib/classic/cjs/package.json +1 -0
  37. package/lib/classic/cjs/units/external-ad.js +453 -0
  38. package/lib/classic/cjs/units/external-pause-ad.js +274 -0
  39. package/lib/classic/cjs/units/gam.js +110 -0
  40. package/lib/classic/cjs/units/parse-vast-extensions.js +56 -0
  41. package/lib/classic/cjs/units/pause-ad-card.js +134 -0
  42. package/lib/classic/cjs/units/pause-ad.js +72 -0
  43. package/lib/classic/cjs/units/ssai-ad-break.js +11 -0
  44. package/lib/classic/cjs/units/ssai-creative.js +142 -0
  45. package/lib/classic/cjs/units/ssai-detector.js +1170 -0
  46. package/lib/classic/cjs/units/ssai-preload.js +72 -0
  47. package/lib/classic/cjs/units/ssai-providers.js +299 -0
  48. package/lib/classic/cjs/units/vast-tracker.js +81 -0
  49. package/lib/classic/index.js +28 -0
  50. package/lib/classic/units/external-ad.js +447 -0
  51. package/lib/classic/units/external-pause-ad.js +271 -0
  52. package/lib/classic/units/gam.js +108 -0
  53. package/lib/classic/units/parse-vast-extensions.js +54 -0
  54. package/lib/classic/units/pause-ad-card.js +131 -0
  55. package/lib/classic/units/pause-ad.js +70 -0
  56. package/lib/classic/units/ssai-ad-break.js +9 -0
  57. package/lib/classic/units/ssai-creative.js +140 -0
  58. package/lib/classic/units/ssai-detector.js +1167 -0
  59. package/lib/classic/units/ssai-preload.js +68 -0
  60. package/lib/classic/units/ssai-providers.js +289 -0
  61. package/lib/classic/units/vast-tracker.js +77 -0
  62. package/lib/index.d.ts +2 -1
  63. package/lib/index.js +6 -0
  64. package/lib/units/pause-ad-card.d.ts +49 -0
  65. package/lib/units/pause-ad-card.js +130 -0
  66. package/lib/units/pause-ad.d.ts +1 -18
  67. package/lib/units/pause-ad.js +2 -49
  68. package/package.json +42 -9
@@ -0,0 +1,253 @@
1
+ 'use strict';
2
+
3
+ var sdkWebInterfaces = require('@streamlayer/sdk-web-interfaces');
4
+ var sdkWebLogger = require('@streamlayer/sdk-web-logger');
5
+ require('@streamlayer/sdk-web-api');
6
+ var vastClient$1 = require('@dailymotion/vast-client');
7
+
8
+ // Pins the `@dailymotion/vast-client` → `@types/vast-client` shim: TypeDoc
9
+ // compiles this file through dependent packages' programs, whose tsconfig
10
+ // `include` does not cover this package's ambient declarations.
11
+ // eslint-disable-next-line @typescript-eslint/triple-slash-reference
12
+ /// <reference path="../module.d.ts" />
13
+ const FULLBLEED_VIDEO_TEMPLATES = [
14
+ 'fullbleed-video',
15
+ 'fullbleed-video-center',
16
+ 'fullbleed-video-left',
17
+ ];
18
+ /**
19
+ * `indexOf` rather than `Array.prototype.includes`: this package ships to Chrome 32
20
+ * TV webviews and must stay ES5-compatible without a polyfill.
21
+ */
22
+ const isFullbleedVideoTemplate = (template) => !!template && FULLBLEED_VIDEO_TEMPLATES.indexOf(template) !== -1;
23
+ const MP4_MIME = 'video/mp4';
24
+ // Programmatic spec (Index Exchange): bitrate window for a linear pause-ad MP4.
25
+ const MIN_BITRATE = 5000;
26
+ const MAX_BITRATE = 40000;
27
+ const TARGET_WIDTH = 1920;
28
+ const TARGET_HEIGHT = 1080;
29
+ const bitrateDistanceToWindow = (bitrate) => {
30
+ if (bitrate < MIN_BITRATE)
31
+ return MIN_BITRATE - bitrate;
32
+ if (bitrate > MAX_BITRATE)
33
+ return bitrate - MAX_BITRATE;
34
+ return 0;
35
+ };
36
+ const resolutionDistanceToTarget = (file) => Math.abs((file.width ?? 0) - TARGET_WIDTH) + Math.abs((file.height ?? 0) - TARGET_HEIGHT);
37
+ /**
38
+ * Pick the best linear MP4 from a VAST creative's media files: prefer the
39
+ * highest bitrate inside the 5000–40000 kbps window; if none qualify, pick the
40
+ * one closest to the window. Ties break toward 1920×1080. Returns `undefined`
41
+ * when no MP4 is present so image-only VAST keeps working.
42
+ */
43
+ const selectMp4MediaFile = (mediaFiles = []) => {
44
+ const mp4s = (mediaFiles ?? []).filter((file) => !!file?.fileURL && file.mimeType === MP4_MIME);
45
+ if (mp4s.length === 0) {
46
+ return undefined;
47
+ }
48
+ const inWindow = mp4s.filter((file) => {
49
+ const bitrate = file.bitrate ?? 0;
50
+ return bitrate >= MIN_BITRATE && bitrate <= MAX_BITRATE;
51
+ });
52
+ if (inWindow.length > 0) {
53
+ return [...inWindow].sort((a, b) => {
54
+ const byBitrate = (b.bitrate ?? 0) - (a.bitrate ?? 0);
55
+ return byBitrate !== 0 ? byBitrate : resolutionDistanceToTarget(a) - resolutionDistanceToTarget(b);
56
+ })[0];
57
+ }
58
+ return [...mp4s].sort((a, b) => {
59
+ const byWindow = bitrateDistanceToWindow(a.bitrate ?? 0) - bitrateDistanceToWindow(b.bitrate ?? 0);
60
+ return byWindow !== 0 ? byWindow : resolutionDistanceToTarget(a) - resolutionDistanceToTarget(b);
61
+ })[0];
62
+ };
63
+ const vastClient = new vastClient$1.VASTClient();
64
+ const log = sdkWebLogger.createLogger('ui:gam-static');
65
+ const preloadImage = (src) => {
66
+ return new Promise((resolve, reject) => {
67
+ const image = new Image();
68
+ image.onload = () => resolve(src);
69
+ image.onerror = () => reject();
70
+ image.src = src;
71
+ });
72
+ };
73
+ const externalPauseAd = (instance) => {
74
+ return (gamUrl, $enabled, options) =>
75
+ // `template` MUST be a key part: nanoquery joins parts with `''` (no separator)
76
+ // and its `cache` Map is global per transport, so two stores that produce the
77
+ // same joined key share data AND cross-trigger each other's `revalidate()`.
78
+ // The `tpl:` prefix keeps the url/template boundary unambiguous. Never let this
79
+ // part be `undefined` — an undefined part nulls the WHOLE key and permanently
80
+ // suspends fetching (that is exactly how `$enabled: false` works).
81
+ instance.transport.nanoquery.createFetcherStore([gamUrl, $enabled, `tpl:${options.template ?? 'default'}`], {
82
+ dedupeTime: options.prefetch ? options.refetchInterval : Infinity,
83
+ revalidateInterval: options.refetchInterval > 0 ? options.refetchInterval : 0,
84
+ // A creative-type mismatch is DETERMINISTIC: this tag returned no usable linear
85
+ // MP4 and retrying it can never change that, so cancel nanoquery's BACKOFF RETRY
86
+ // LOOP (any falsy return does) instead of re-hitting the ad server for the rest of
87
+ // the session — with the default `pauseAdDelay: 0` the store is enabled from mount.
88
+ // This only cancels the retry loop: `revalidateInterval` still re-runs the fetcher
89
+ // on its timer, and `Advertisement.getExternalPauseAd` forces a `revalidate()` on
90
+ // every `$enabled` false → true edge, so with `pauseAdDelay > 0` the tag is still
91
+ // re-requested on every pause.
92
+ // Transient failures (network, CORS, malformed XML, 5xx) still retry; the backoff
93
+ // below mirrors nanoquery's `defaultOnErrorRetry` so the two templates stay on the
94
+ // same curve. The jitter is not decorative — it spreads out retries that would
95
+ // otherwise fire in lockstep when the failure is correlated across stores/clients
96
+ // (ad-server 5xx, CORS), which the `pauseAdDelay: 0` prefetch-at-mount makes more
97
+ // likely.
98
+ // On `default` this is `undefined`, i.e. exactly as if the option were not passed —
99
+ // true as long as the shared nanoquery instance sets no global `onErrorRetry` (an
100
+ // explicit `undefined` DOES shadow a global one, and only then does nanoquery's
101
+ // destructuring default restore `defaultOnErrorRetry`).
102
+ onErrorRetry: isFullbleedVideoTemplate(options.template)
103
+ ? ({ error, retryCount }) => {
104
+ if (error instanceof Error && error.message === 'no_valid_ad') {
105
+ return false;
106
+ }
107
+ return ~~((Math.random() + 0.5) * (1 << Math.min(retryCount, 8))) * 2000;
108
+ }
109
+ : undefined,
110
+ fetcher: async (adUrl) => {
111
+ if (!adUrl || typeof adUrl !== 'string') {
112
+ throw new Error('ad url is empty');
113
+ }
114
+ sdkWebInterfaces.eventBus.emit('exposedPauseAd', {
115
+ action: 'load',
116
+ payload: {},
117
+ });
118
+ try {
119
+ // `resolveAll: true` follows every `VASTAdTagURI` wrapper chain and resolves all
120
+ // Ads (the default only resolves the first standalone Ad and stops at the wrapper).
121
+ const parsedVAST = await vastClient.get(adUrl, { resolveAll: true });
122
+ const template = options.template ?? 'default';
123
+ // `fullbleed-video` needs an ad that actually carries a usable linear MP4. With
124
+ // `resolveAll: true` the response can be a pod/wrapper chain, so prefer the first
125
+ // ad that satisfies the template and fall back to the first ad with any creative
126
+ // (which preserves the existing `no_valid_ad` error and event sequencing).
127
+ const validAd = isFullbleedVideoTemplate(template)
128
+ ? (parsedVAST.ads.find((ad) => ad.creatives.some((creative) => creative.type === 'linear' &&
129
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
130
+ // @ts-ignore vast-client linear creative carries mediaFiles
131
+ selectMp4MediaFile(creative.mediaFiles)?.fileURL)) ?? parsedVAST.ads.find((ads) => ads.creatives.length > 0))
132
+ : parsedVAST.ads.find((ads) => ads.creatives.length > 0);
133
+ if (validAd) {
134
+ const parentId = validAd.id || '';
135
+ log.debug(validAd, 'validAd');
136
+ // The HOST decides which creative wins (SC-322-2). `fullbleed-video` asks
137
+ // for the linear MP4 explicitly, so it is resolved FIRST and never falls
138
+ // back to a static image — the nonlinear/companion branches below `return`
139
+ // early, so without this a VAST carrying BOTH an image and a linear MP4
140
+ // (e.g. Google `single_ad_samples`) would never reach the linear creative.
141
+ // `default` keeps the pre-SC-322 nonlinear → companion order below and can
142
+ // never produce a video.
143
+ if (isFullbleedVideoTemplate(template)) {
144
+ const linear = validAd.creatives.find((creative) => creative.type === 'linear' &&
145
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
146
+ // @ts-ignore vast-client linear creative carries mediaFiles
147
+ selectMp4MediaFile(creative.mediaFiles)?.fileURL);
148
+ if (linear) {
149
+ log.debug(linear, 'linear');
150
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
151
+ // @ts-ignore vast-client linear creative carries mediaFiles
152
+ const mediaFile = selectMp4MediaFile(linear.mediaFiles);
153
+ if (mediaFile?.fileURL) {
154
+ const id = linear.adId || linear.id || parentId;
155
+ sdkWebInterfaces.eventBus.emit('exposedPauseAd', {
156
+ action: 'loaded',
157
+ payload: {
158
+ id,
159
+ parentId,
160
+ },
161
+ });
162
+ return {
163
+ id,
164
+ parentId,
165
+ url: adUrl,
166
+ backgroundVideoSrc: mediaFile.fileURL,
167
+ ad: validAd,
168
+ creative: linear,
169
+ };
170
+ }
171
+ }
172
+ // Host asked for full-bleed video and this VAST carries no usable linear
173
+ // MP4 → fail closed so `ExposedPauseAd`'s error effect auto-closes the ad,
174
+ // exactly like any other unusable VAST. See §5 of the brief.
175
+ throw new Error('no_valid_ad');
176
+ }
177
+ const nonlinear = validAd.creatives.find((creative) => creative.type === 'nonlinear');
178
+ if (nonlinear) {
179
+ const id = nonlinear.adId || nonlinear.id || parentId;
180
+ log.debug(nonlinear, 'nonlinear');
181
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
182
+ // @ts-ignore
183
+ const variation = nonlinear.variations?.[0];
184
+ const staticResource = variation?.staticResource;
185
+ const adUrlTemplate = variation?.nonlinearClickThroughURLTemplate;
186
+ if (staticResource) {
187
+ await preloadImage(staticResource);
188
+ sdkWebInterfaces.eventBus.emit('exposedPauseAd', {
189
+ action: 'loaded',
190
+ payload: {
191
+ id,
192
+ parentId,
193
+ },
194
+ });
195
+ return {
196
+ id,
197
+ parentId,
198
+ url: adUrl,
199
+ imageSrc: staticResource,
200
+ adUrl: adUrlTemplate,
201
+ ad: validAd,
202
+ creative: nonlinear,
203
+ variation,
204
+ };
205
+ }
206
+ }
207
+ const companion = validAd.creatives.find((creative) => creative.type === 'companion');
208
+ log.debug(companion, 'companion');
209
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
210
+ // @ts-ignore
211
+ const variation = companion?.variations?.[0];
212
+ const staticResource = variation?.staticResources?.[0]?.url;
213
+ const adUrlTemplate = variation?.companionClickThroughURLTemplate;
214
+ // `&& companion` is for TS narrowing only (companion.adId access below);
215
+ // it is runtime-redundant since staticResource derives from companion.
216
+ if (staticResource && companion) {
217
+ const id = companion.adId || companion.id || parentId;
218
+ await preloadImage(staticResource);
219
+ sdkWebInterfaces.eventBus.emit('exposedPauseAd', {
220
+ action: 'loaded',
221
+ payload: {
222
+ id,
223
+ parentId,
224
+ },
225
+ });
226
+ return {
227
+ id,
228
+ parentId,
229
+ url: adUrl,
230
+ imageSrc: staticResource,
231
+ adUrl: adUrlTemplate,
232
+ ad: validAd,
233
+ creative: companion,
234
+ variation,
235
+ };
236
+ }
237
+ }
238
+ throw new Error('no_valid_ad');
239
+ }
240
+ catch (err) {
241
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
242
+ // @ts-expect-error
243
+ if (err.message !== 'no_valid_ad' && err.message !== 'ad url is empty') {
244
+ console.error(err);
245
+ }
246
+ throw err;
247
+ }
248
+ },
249
+ });
250
+ };
251
+
252
+ exports.externalPauseAd = externalPauseAd;
253
+ exports.isFullbleedVideoTemplate = isFullbleedVideoTemplate;
@@ -0,0 +1,16 @@
1
+ export type PalNonceManager = {
2
+ getNonce: () => string;
3
+ sendAdClick: () => void;
4
+ sendPlaybackStart: () => void;
5
+ sendPlaybackEnd: () => void;
6
+ };
7
+ export type GamNonceResult = {
8
+ url: URL;
9
+ manager?: PalNonceManager;
10
+ };
11
+ export declare const gam: (url: string, adContainer?: HTMLDivElement) => (() => Promise<{
12
+ url: URL;
13
+ }>) | (() => Promise<{
14
+ url: URL;
15
+ manager: PalNonceManager;
16
+ } | undefined>);
@@ -0,0 +1,104 @@
1
+ 'use strict';
2
+
3
+ var sdkWebStorage = require('@streamlayer/sdk-web-storage');
4
+ var uuid = require('uuid');
5
+
6
+ /**
7
+ * Google PAL nonce manager + ad-tag resolution for programmatic (GAM) VAST requests.
8
+ *
9
+ * Lives here because the VAST fetcher (`units/external-ad.ts`) is its only consumer: this is the
10
+ * request side of an ad tag, not the promotion side. The *composition* of a tag URL from the proto
11
+ * (`processGamAdvertisement` / `selectGamOptions`) stays in `feature-gamification`, next to the
12
+ * `$store` bridge that is its only consumer — so the two feature packages share no code and
13
+ * neither depends on the other.
14
+ */
15
+ const urlIsNotGam = (url) => {
16
+ return url.origin !== 'https://pubads.g.doubleclick.net';
17
+ };
18
+ const gam = (url, adContainer) => {
19
+ const parsedUrl = (() => {
20
+ try {
21
+ const parsedUrl = new URL(url);
22
+ return parsedUrl;
23
+ }
24
+ catch (_err) {
25
+ return undefined;
26
+ }
27
+ })();
28
+ // Non-GAM VAST/VMAP URLs carry no GAM ad-request params and need no PAL nonce, so
29
+ // resolve them directly. PAL is only required for pubads.g.doubleclick.net requests —
30
+ // raw-VAST consumers (e.g. injected sidebar / l-bar) must not depend on the Google PAL
31
+ // SDK being loaded, so this must run before touching `goog`.
32
+ if (parsedUrl && urlIsNotGam(parsedUrl)) {
33
+ // eslint-disable-next-line require-await
34
+ return async () => {
35
+ return { url: parsedUrl };
36
+ };
37
+ }
38
+ // @ts-expect-error goog is injected by the externally-loaded Google PAL SDK
39
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
40
+ const pal = (typeof goog === 'undefined' ? undefined : goog.pal);
41
+ if (!pal || !parsedUrl) {
42
+ // eslint-disable-next-line require-await
43
+ return async () => {
44
+ return undefined;
45
+ };
46
+ }
47
+ const consentSettings = new pal.ConsentSettings();
48
+ consentSettings.allowStorage = false;
49
+ const nonceLoader = new pal.NonceLoader(consentSettings);
50
+ const generateUrl = async () => {
51
+ try {
52
+ const parsedUrl = new URL(url);
53
+ const request = new pal.NonceRequest();
54
+ let deviceId = sdkWebStorage.safeLocalStorage().getItem('sl-device-id') || uuid.v4();
55
+ let sessionId = sdkWebStorage.safeSessionStorage().getItem('sl-ad-session-id');
56
+ if (!sessionId) {
57
+ sessionId = uuid.v4();
58
+ sdkWebStorage.safeSessionStorage().setItem('sl-ad-session-id', sessionId);
59
+ }
60
+ if (!uuid.validate(deviceId)) {
61
+ deviceId = uuid.v5(`https://${deviceId}`, uuid.v5.URL);
62
+ }
63
+ if (!parsedUrl.searchParams.get('url')) {
64
+ parsedUrl.searchParams.set('url', 'https://streamlayer.io');
65
+ }
66
+ if (!parsedUrl.searchParams.get('description_url')) {
67
+ parsedUrl.searchParams.set('description_url', 'https://streamlayer.io');
68
+ }
69
+ request.adWillAutoPlay = parsedUrl.searchParams.get('vpa') === 'auto';
70
+ request.adWillPlayMuted = parsedUrl.searchParams.get('vpmute') === '1';
71
+ request.continuousPlayback = true;
72
+ request.descriptionUrl = parsedUrl.searchParams.get('description_url');
73
+ request.iconsSupported = true;
74
+ request.sessionId = deviceId;
75
+ // Player support for VPAID 2.0, OMID 1.0, and SIMID 1.1
76
+ request.supportedApiFrameworks = '2,7,9';
77
+ request.videoHeight = adContainer?.clientHeight ?? 0;
78
+ request.videoWidth = adContainer?.clientWidth ?? 0;
79
+ const nonceManager = await nonceLoader.loadNonceManager(request);
80
+ if (parsedUrl.searchParams.get('is_lat') === '[placeholder]') {
81
+ parsedUrl.searchParams.set('is_lat', '1');
82
+ }
83
+ if (parsedUrl.searchParams.get('rdid') === '[placeholder]') {
84
+ parsedUrl.searchParams.set('rdid', deviceId);
85
+ }
86
+ if (parsedUrl.searchParams.get('correlator') === '[placeholder]') {
87
+ parsedUrl.searchParams.set('correlator', sessionId);
88
+ }
89
+ parsedUrl.searchParams.set('wta', '1');
90
+ parsedUrl.searchParams.set('givn', nonceManager.getNonce());
91
+ return {
92
+ url: parsedUrl,
93
+ manager: nonceManager,
94
+ };
95
+ }
96
+ catch (adError) {
97
+ console.log('AdsManager could not be started', adError);
98
+ return undefined;
99
+ }
100
+ };
101
+ return generateUrl;
102
+ };
103
+
104
+ exports.gam = gam;
@@ -0,0 +1,17 @@
1
+ import { AdType } from '@streamlayer/sl-eslib/interactive/interactive.common_pb';
2
+ export interface VastCreative {
3
+ adName: string;
4
+ adType: AdType;
5
+ landscapeBackground?: string;
6
+ portraitBackground?: string;
7
+ sponsorLogo?: string;
8
+ ctaLabel?: string;
9
+ }
10
+ interface VastNode {
11
+ name: string;
12
+ value: string | null;
13
+ attributes: Record<string, string>;
14
+ children: VastNode[];
15
+ }
16
+ export declare function parseVastExtension(root: VastNode): VastCreative | undefined;
17
+ export {};
@@ -0,0 +1,52 @@
1
+ 'use strict';
2
+
3
+ var interactive_common_pb = require('@streamlayer/sl-eslib/interactive/interactive.common_pb');
4
+
5
+ const MAP_EXTENSION_NAME_AD_TYPE = {
6
+ DoubleBox: interactive_common_pb.AdType.SIDE_BY_SIDE,
7
+ };
8
+ function parseVastExtension(root) {
9
+ if (!root) {
10
+ return undefined;
11
+ }
12
+ const child = (node, name) => node.children.find((c) => c.name === name);
13
+ const childrenByName = (node, name) => node.children.filter((c) => c.name === name);
14
+ const urlOf = (node) => child(node, 'Url')?.value ?? '';
15
+ const num = (v) => (v == null ? NaN : Number(v));
16
+ const adName = child(root, 'AdName')?.value ?? '';
17
+ const backgroundsNode = child(root, 'Backgrounds');
18
+ const backgrounds = backgroundsNode
19
+ ? childrenByName(backgroundsNode, 'Background').map((bg) => ({
20
+ orientation: bg.attributes.orientation,
21
+ width: num(bg.attributes.width),
22
+ height: num(bg.attributes.height),
23
+ type: bg.attributes.type,
24
+ url: urlOf(bg),
25
+ }))
26
+ : [];
27
+ const logosNode = child(root, 'Logos');
28
+ const logos = logosNode
29
+ ? childrenByName(logosNode, 'Logo').map((logo) => ({
30
+ role: logo.attributes.role,
31
+ width: num(logo.attributes.width),
32
+ height: num(logo.attributes.height),
33
+ type: logo.attributes.type,
34
+ url: urlOf(logo),
35
+ }))
36
+ : [];
37
+ const ctaNode = child(root, 'CTA');
38
+ const cta = {
39
+ label: ctaNode ? (child(ctaNode, 'Label')?.value ?? '') : '',
40
+ type: ctaNode ? (child(ctaNode, 'Type')?.value ?? '') : '',
41
+ };
42
+ return {
43
+ adName,
44
+ adType: MAP_EXTENSION_NAME_AD_TYPE[root.name] || interactive_common_pb.AdType.SIDE_BY_SIDE,
45
+ landscapeBackground: backgrounds.find((b) => b.orientation === 'landscape')?.url,
46
+ portraitBackground: backgrounds.find((b) => b.orientation === 'portrait')?.url,
47
+ sponsorLogo: logos.find((l) => l.role === 'header')?.url,
48
+ ctaLabel: cta.label,
49
+ };
50
+ }
51
+
52
+ exports.parseVastExtension = parseVastExtension;
@@ -0,0 +1,49 @@
1
+ import { type Question } from '@streamlayer/sl-eslib/interactive/interactive.common_pb';
2
+ export type PauseAdLayout = 'left' | 'center' | 'image';
3
+ /**
4
+ * Which full-bleed renderer draws the card. Absent === `'standard'`.
5
+ *
6
+ * - `'standard'` — the Standard/Image pause ad (promotion card).
7
+ * - `'insight'` — the Insight Pause Ad (factoid card): sponsor logo, heading and a
8
+ * single-column body beside an optional media image (SC-353).
9
+ */
10
+ export type PauseAdKind = 'standard' | 'insight';
11
+ /** How the Insight media image is cropped — mirrors Studio's Media switcher. */
12
+ export type PauseAdMediaMode = 'image' | 'circle' | 'none';
13
+ /**
14
+ * Insight body cap (SC-353). Studio enforces it on the Additional Content field; the
15
+ * SDK clamps as well so a card authored before the limit landed cannot overflow the
16
+ * screen — the format is explicitly designed to fit without scrolling.
17
+ */
18
+ export declare const INSIGHT_BODY_MAX_LENGTH = 600;
19
+ export type PauseAdCard = {
20
+ id: string;
21
+ parentId: string;
22
+ /** Optional: a video-only card (programmatic VAST, SC-322) has no image. */
23
+ backgroundImageSrc?: string;
24
+ /** Linear MP4 from VAST → renders full-bleed `<video>` instead of the image (SC-322). */
25
+ backgroundVideoSrc?: string;
26
+ layout: PauseAdLayout;
27
+ isInteractive: boolean;
28
+ logoSrc?: string;
29
+ title?: string;
30
+ description?: string;
31
+ ctaLabel?: string;
32
+ ctaUrl?: string;
33
+ qrCodeUrl?: string;
34
+ qrCodeLabel?: string;
35
+ /** Absent === `'standard'`. */
36
+ kind?: PauseAdKind;
37
+ /** Insight only: the Media image (`FactoidOptions.image`). */
38
+ mediaSrc?: string;
39
+ /** Insight only: how `mediaSrc` is cropped. */
40
+ mediaMode?: PauseAdMediaMode;
41
+ };
42
+ /**
43
+ * The `pauseAdList` response, shaped for the renderers: keep the cards the SDK has chrome for,
44
+ * turn each into a `PauseAdCard`, drop the ones that cannot be drawn.
45
+ *
46
+ * Pure on purpose — `pause-ad.ts` owns the store and the transport, this owns the card shapes,
47
+ * and only this half needs unit tests.
48
+ */
49
+ export declare const parsePauseAdCards: (questions: Question[]) => PauseAdCard[];
@@ -0,0 +1,136 @@
1
+ 'use strict';
2
+
3
+ var interactive_common_pb = require('@streamlayer/sl-eslib/interactive/interactive.common_pb');
4
+
5
+ /**
6
+ * Insight body cap (SC-353). Studio enforces it on the Additional Content field; the
7
+ * SDK clamps as well so a card authored before the limit landed cannot overflow the
8
+ * screen — the format is explicitly designed to fit without scrolling.
9
+ */
10
+ const INSIGHT_BODY_MAX_LENGTH = 600;
11
+ /**
12
+ * Sponsor logo for a factoid card. Same General-tab opt-in as the promotion path below,
13
+ * but the logo lives on `question.promotion.sponsor` (a factoid card carries no
14
+ * `PromotionOptions`) and Studio writes the uploaded file to `logo`, not `centerLogo`.
15
+ *
16
+ * `logo` therefore WINS over `centerLogo`: the latter is an optional field carried over from the
17
+ * notification/header surfaces, so a card that kept a stale `centerLogo` from an earlier revision
18
+ * would otherwise render it instead of the Insight logo the author just uploaded.
19
+ */
20
+ const resolveInsightSponsorLogo = (question) => {
21
+ const sponsor = question.promotion?.sponsor;
22
+ if (sponsor?.logoPosition === interactive_common_pb.NotificationSponsorLogoMode.NOTIFICATION_SPONSOR_LOGO_NONE) {
23
+ return undefined;
24
+ }
25
+ return sponsor?.useGeneralLogo === interactive_common_pb.UseGeneralLogo.ENABLED
26
+ ? question.promotion?.generalTabMetadata?.advertiserTransparentLogo || undefined
27
+ : sponsor?.logo || sponsor?.centerLogo || undefined;
28
+ };
29
+ const MEDIA_MODE_BY_PROTO = {
30
+ [interactive_common_pb.FactoidMediaMode.IMAGE]: 'image',
31
+ [interactive_common_pb.FactoidMediaMode.CIRCLE]: 'circle',
32
+ };
33
+ /**
34
+ * Insight Pause Ad, Full Bleed (SC-353). A factoid card, so none of the promotion
35
+ * plumbing above applies: the heading is the question subject, the body is
36
+ * `FactoidOptions.body`, and the sponsor logo comes off `question.promotion.sponsor`.
37
+ *
38
+ * `FACTOID_MEDIA_MODE_VIDEO` is deliberately treated as "no media": the full-bleed
39
+ * format has no player chrome and no way to start playback, unlike the sidebar variant.
40
+ */
41
+ const parseInsightPauseAdCard = (question) => {
42
+ const factoidOptions = question.options?.options.case === 'factoid' ? question.options.options.value : undefined;
43
+ if (!factoidOptions) {
44
+ return null;
45
+ }
46
+ const mediaMode = MEDIA_MODE_BY_PROTO[factoidOptions.mode] ?? 'none';
47
+ const body = factoidOptions.body.slice(0, INSIGHT_BODY_MAX_LENGTH);
48
+ return {
49
+ id: question.id,
50
+ parentId: question.eventId || question.id,
51
+ // `landscapeUrl` ONLY. `portraitUrl` keeps stale artwork from earlier revisions of the
52
+ // card that Studio no longer shows in its Background Image slot, so falling back to it
53
+ // paints a background the author has already removed. Unlike the standard card, an
54
+ // Insight one renders fine with no background at all — its copy is the ad.
55
+ backgroundImageSrc: question.backgroundImage?.landscapeUrl || undefined,
56
+ kind: 'insight',
57
+ layout: 'left',
58
+ isInteractive: false,
59
+ logoSrc: resolveInsightSponsorLogo(question),
60
+ title: question.subject || undefined,
61
+ description: body || undefined,
62
+ mediaSrc: mediaMode === 'none' ? undefined : factoidOptions.image || undefined,
63
+ mediaMode,
64
+ };
65
+ };
66
+ const parsePauseAdCard = (question) => {
67
+ if (question.options?.options.case === 'factoid') {
68
+ return parseInsightPauseAdCard(question);
69
+ }
70
+ const backgroundImageSrc = question.backgroundImage?.landscapeUrl;
71
+ if (!backgroundImageSrc) {
72
+ return null;
73
+ }
74
+ const promotionOptions = question.options?.options.case === 'promotion' ? question.options.options.value : undefined;
75
+ const pauseAdOptions = promotionOptions?.pauseAdOptions;
76
+ const optionsSponsor = promotionOptions?.sponsor;
77
+ const layoutProto = pauseAdOptions?.layout ?? interactive_common_pb.PauseAdLayout.UNSET;
78
+ const layout = layoutProto === interactive_common_pb.PauseAdLayout.CENTER ? 'center' : layoutProto === interactive_common_pb.PauseAdLayout.IMAGE ? 'image' : 'left';
79
+ const isInteractive = promotionOptions?.buttonType === interactive_common_pb.PromotionButtonType.SEND_TO_USER;
80
+ const hasQr = pauseAdOptions?.qrCode === interactive_common_pb.QRCode.QR_CODE_ENABLED && !!pauseAdOptions?.qrCodeUrl;
81
+ let ctaLabel;
82
+ let ctaUrl;
83
+ if (isInteractive && promotionOptions?.buttonOptions.case === 'sendToUserOptions') {
84
+ const accountInfo = promotionOptions.buttonOptions.value.userAccountInfo;
85
+ const isPhone = accountInfo === interactive_common_pb.UserAccountInfo.PHONE;
86
+ ctaUrl = isPhone ? 'sendToPhone:' : 'sendToEmail:';
87
+ ctaLabel = isPhone ? 'Send info to account phone' : 'Send info to account email';
88
+ }
89
+ const logoSrc = optionsSponsor?.logoPosition === interactive_common_pb.NotificationSponsorLogoMode.NOTIFICATION_SPONSOR_LOGO_NONE
90
+ ? undefined
91
+ : optionsSponsor?.useGeneralLogo === interactive_common_pb.UseGeneralLogo.ENABLED
92
+ ? question.promotion?.generalTabMetadata?.advertiserTransparentLogo || undefined
93
+ : optionsSponsor?.centerLogo || undefined;
94
+ return {
95
+ id: question.id,
96
+ parentId: question.eventId || question.id,
97
+ backgroundImageSrc,
98
+ layout,
99
+ logoSrc,
100
+ title: promotionOptions?.banner?.title || undefined,
101
+ description: promotionOptions?.banner?.body || undefined,
102
+ isInteractive,
103
+ ctaLabel: ctaLabel || undefined,
104
+ ctaUrl: ctaUrl || undefined,
105
+ qrCodeUrl: hasQr ? (pauseAdOptions?.qrCodeUrl ?? undefined) : undefined,
106
+ qrCodeLabel: hasQr ? (pauseAdOptions?.qrCodeLabel ?? undefined) : undefined,
107
+ };
108
+ };
109
+ /**
110
+ * Which cards from `pauseAdList` the SDK can actually draw. Both renderers are full bleed; a
111
+ * Sidebar-format pause ad has no chrome yet and is skipped.
112
+ */
113
+ const isFullBleedPauseAd = (question) => {
114
+ if (question.options?.options.case === 'factoid') {
115
+ // Insight Pause Ad (SC-353). Studio does not write `CardFormat` on these cards yet
116
+ // (SLW-7062), so an UNSET format is taken as Full Bleed — the only Insight pause-ad chrome
117
+ // the SDK has. An explicit Sidebar stays out. Drop the UNSET arm once Studio sets the field.
118
+ return question.format === interactive_common_pb.CardFormat.FULL_BLEED || question.format === interactive_common_pb.CardFormat.UNSET;
119
+ }
120
+ const promotionOptions = question.options?.options.case === 'promotion' ? question.options.options.value : undefined;
121
+ return promotionOptions?.format === interactive_common_pb.PromotionFormat.FULL_BLEED || question.format === interactive_common_pb.CardFormat.FULL_BLEED;
122
+ };
123
+ /**
124
+ * The `pauseAdList` response, shaped for the renderers: keep the cards the SDK has chrome for,
125
+ * turn each into a `PauseAdCard`, drop the ones that cannot be drawn.
126
+ *
127
+ * Pure on purpose — `pause-ad.ts` owns the store and the transport, this owns the card shapes,
128
+ * and only this half needs unit tests.
129
+ */
130
+ const parsePauseAdCards = (questions) => questions
131
+ .filter(isFullBleedPauseAd)
132
+ .map(parsePauseAdCard)
133
+ .filter((card) => card !== null);
134
+
135
+ exports.INSIGHT_BODY_MAX_LENGTH = INSIGHT_BODY_MAX_LENGTH;
136
+ exports.parsePauseAdCards = parsePauseAdCards;
@@ -0,0 +1,16 @@
1
+ import { createSingleStore, StreamLayerContext } from '@streamlayer/sdk-web-interfaces';
2
+ import '@streamlayer/sdk-web-api';
3
+ import '@streamlayer/sdk-web-core/store';
4
+ import { type PauseAdCard } from './pause-ad-card';
5
+ export type PauseAdListOptions = {
6
+ refetchInterval: number;
7
+ $enabled: boolean;
8
+ };
9
+ export declare const pauseAdListStore: (instance: StreamLayerContext) => ($enabled: ReturnType<typeof createSingleStore<boolean>>, options: PauseAdListOptions) => {
10
+ $list: import("@nanostores/query", { with: { "resolution-mode": "import" } }).FetcherStore<PauseAdCard[], any>;
11
+ $index: import("nanostores", { with: { "resolution-mode": "import" } }).PreinitializedWritableAtom<number> & object;
12
+ next: () => void;
13
+ reset: () => void;
14
+ getCurrent: () => PauseAdCard | undefined;
15
+ };
16
+ export type PauseAdStore = ReturnType<ReturnType<typeof pauseAdListStore>>;