@vtex/ads-stories 0.4.1 → 0.7.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 (60) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/README.md +44 -88
  3. package/dist/cdn/vtex-ads-stories.js +1313 -74
  4. package/dist/cdn/vtex-ads-stories.js.map +1 -1
  5. package/dist/cjs/index.cjs +3744 -513
  6. package/dist/cjs/index.cjs.map +1 -1
  7. package/dist/cjs/index.d.cts +46 -15
  8. package/dist/cjs/react.cjs.map +1 -1
  9. package/dist/cjs/react.d.cts +51 -5
  10. package/dist/cjs/story-DAiAN9v-.d.cts +260 -0
  11. package/dist/esm/index.d.ts +46 -15
  12. package/dist/esm/index.js +3348 -217
  13. package/dist/esm/index.js.map +1 -1
  14. package/dist/esm/react.d.ts +51 -5
  15. package/dist/esm/story-DAiAN9v-.d.ts +260 -0
  16. package/package.json +18 -4
  17. package/src/cdn.ts +7 -3
  18. package/src/commerce-events.ts +93 -0
  19. package/src/components/card/card.ts +79 -14
  20. package/src/components/carousel/carousel-skeleton.ts +113 -0
  21. package/src/components/carousel/carousel.ts +715 -0
  22. package/src/components/carousel/index.ts +22 -0
  23. package/src/components/events/events-controller.ts +222 -0
  24. package/src/components/events/index.ts +6 -0
  25. package/src/components/icons/assets/caret-left-bold.svg +1 -0
  26. package/src/components/icons/assets/caret-right-bold.svg +1 -0
  27. package/src/components/icons/assets/caret-up-bold.svg +1 -0
  28. package/src/components/icons/assets/minus.svg +1 -0
  29. package/src/components/icons/assets/plus.svg +1 -0
  30. package/src/components/icons/assets/trash.svg +1 -0
  31. package/src/components/icons/assets/warning-circle-fill.svg +1 -0
  32. package/src/components/icons/index.ts +14 -0
  33. package/src/components/media/index.ts +8 -1
  34. package/src/components/media/media.styles.ts +113 -0
  35. package/src/components/media/media.ts +124 -23
  36. package/src/components/media/video-controller.ts +127 -6
  37. package/src/components/player/index.ts +6 -2
  38. package/src/components/player/player.ts +824 -50
  39. package/src/components/product/cta.ts +56 -0
  40. package/src/components/product/index.ts +22 -0
  41. package/src/components/product/price.ts +86 -0
  42. package/src/components/product/product.styles.ts +426 -0
  43. package/src/components/product/product.ts +336 -0
  44. package/src/index.ts +17 -1
  45. package/src/locales/en.ts +39 -0
  46. package/src/locales/es.ts +40 -0
  47. package/src/locales/index.ts +36 -0
  48. package/src/locales/pt.ts +39 -0
  49. package/src/locales/types.ts +44 -0
  50. package/src/react.ts +55 -7
  51. package/src/story/index.ts +5 -1
  52. package/src/story/story.ts +679 -49
  53. package/src/tag-name.ts +1 -0
  54. package/src/types.ts +8 -12
  55. package/src/utils/fetch-story.ts +113 -0
  56. package/src/utils/hydrate-products.ts +112 -0
  57. package/src/utils/media-ready.ts +58 -0
  58. package/src/utils/safe-url.ts +36 -0
  59. package/src/utils/send-event.ts +71 -0
  60. package/src/utils/with-timeout.ts +43 -0
@@ -0,0 +1 @@
1
+ export const TAG_NAME = "vtex-ads-story-carousel";
package/src/types.ts CHANGED
@@ -1,14 +1,10 @@
1
+ import type { StoryAdDetail } from "@vtex/ads-core";
2
+
3
+ /** One Story from the ad API response, as returned by `@vtex/ads-core`. */
4
+ export type StoryAd = StoryAdDetail;
5
+
1
6
  /**
2
- * One Story from the ad API response. Field names follow the API; only the
3
- * fields the component reads so far are listed.
7
+ * What the card and the player show: the cover and the video. Both optional,
8
+ * so a Story missing either still renders what it has.
4
9
  */
5
- export interface StoryAd {
6
- ad_id: string;
7
- /** Cover image shown before the video plays. */
8
- poster_url?: string;
9
- /** The 9:16 MP4 the card and the player play. */
10
- media_url?: string;
11
- }
12
-
13
- /** What the card and the player show: the cover and the video. */
14
- export type StoryMedia = Pick<StoryAd, "poster_url" | "media_url">;
10
+ export type StoryMedia = Partial<Pick<StoryAd, "poster_url" | "media_url">>;
@@ -0,0 +1,113 @@
1
+ import { getRawAds, type Channel } from "@vtex/ads-core";
2
+ import { TAG_NAME } from "../tag-name";
3
+ import type { StoryAd } from "../types";
4
+ import { withTimeout } from "./with-timeout";
5
+
6
+ /**
7
+ * Default time limit for the Story request, in milliseconds. A card that
8
+ * shows up later than this would appear well after the page loaded.
9
+ */
10
+ export const DEFAULT_TIMEOUT_MS = 2000;
11
+
12
+ /**
13
+ * How many Stories the element asks for.
14
+ */
15
+ export const DEFAULT_QUANTITY = 8;
16
+
17
+ /** What the element sends to the ad API. */
18
+ export interface StoryRequest {
19
+ /** Required. */
20
+ publisherId?: string;
21
+ /** Required. */
22
+ sessionId?: string;
23
+ /** Required. */
24
+ placement?: string;
25
+ userId?: string;
26
+ accountName?: string;
27
+ channel?: Channel;
28
+ /**
29
+ * How many Stories to ask for: the carousel positions. Missing, below 1 or
30
+ * not a number: DEFAULT_QUANTITY. A fraction is rounded down.
31
+ */
32
+ quantity?: number;
33
+ }
34
+
35
+ export interface FetchStoryOptions {
36
+ /** Cancels the request. */
37
+ signal?: AbortSignal;
38
+ /**
39
+ * Time limit in milliseconds. Missing, zero, negative or not a number:
40
+ * DEFAULT_TIMEOUT_MS.
41
+ */
42
+ timeout?: number;
43
+ }
44
+
45
+ const toQuantity = (quantity?: number) =>
46
+ quantity !== undefined && Number.isFinite(quantity) && quantity >= 1
47
+ ? Math.floor(quantity)
48
+ : DEFAULT_QUANTITY;
49
+
50
+ /**
51
+ * Requests up to `quantity` Stories for the placement from the ad API, in
52
+ * the order the ad API returns them.
53
+ *
54
+ * Resolves to an empty list, without throwing, when a required value is
55
+ * missing, during server-side rendering, when the request fails, is cancelled
56
+ * or takes longer than the time limit, or when the placement has no Story.
57
+ */
58
+ export async function fetchStories(
59
+ {
60
+ publisherId,
61
+ sessionId,
62
+ placement,
63
+ userId,
64
+ accountName,
65
+ channel,
66
+ quantity,
67
+ }: StoryRequest,
68
+ { signal, timeout }: FetchStoryOptions = {},
69
+ ): Promise<StoryAd[]> {
70
+ // No request during server-side rendering, where nothing renders. Not
71
+ // Lit's isServer: it is also true in Node with a DOM, as in the tests.
72
+ const onServer = globalThis.window === undefined;
73
+ if (onServer || !publisherId || !sessionId || !placement) return [];
74
+
75
+ const limit = withTimeout(timeout, DEFAULT_TIMEOUT_MS, signal);
76
+ const count = toQuantity(quantity);
77
+
78
+ try {
79
+ const { stories } = await getRawAds(
80
+ {
81
+ identity: {
82
+ accountName: accountName ?? "",
83
+ publisherId,
84
+ sessionId,
85
+ userId,
86
+ channel,
87
+ },
88
+ search: {},
89
+ placements: {
90
+ [placement]: { quantity: count, types: ["story"] },
91
+ },
92
+ },
93
+ { signal: limit.signal },
94
+ );
95
+
96
+ // The ad API may send more than asked for: only the first ones fit.
97
+ return (stories[placement] ?? []).slice(0, count);
98
+ } catch (error) {
99
+ // A cancelled or timed out request needs no log. Anything else (network
100
+ // failure, HTTP or validation error) is logged, so a failing request can
101
+ // be told apart from a placement with no Story.
102
+ if (!limit.signal.aborted) {
103
+ console.error(`[${TAG_NAME}] Story request failed`, {
104
+ placement,
105
+ publisherId,
106
+ error,
107
+ });
108
+ }
109
+ return [];
110
+ } finally {
111
+ limit.clear();
112
+ }
113
+ }
@@ -0,0 +1,112 @@
1
+ import {
2
+ hydrateAds,
3
+ intelligentSearchAvailability,
4
+ intelligentSearchFetcher,
5
+ intelligentSearchMatcher,
6
+ intelligentSearchPrice,
7
+ type Identity,
8
+ type Offer,
9
+ type Product,
10
+ type ProductFetcher,
11
+ type ProductPrice,
12
+ } from "@vtex/ads-core";
13
+ import { TAG_NAME } from "../tag-name";
14
+ import type { StoryAd } from "../types";
15
+ import { withTimeout } from "./with-timeout";
16
+
17
+ const DEFAULT_HYDRATION_TIMEOUT_MS = 5000;
18
+
19
+ /**
20
+ * Where the element gets its products' details: a fetcher and a matcher, as
21
+ * in `@vtex/ads-core`, and a reader for the price of a fetched product.
22
+ */
23
+ export interface StoryHydration<TProduct extends object = object> {
24
+ fetcher: ProductFetcher<TProduct>;
25
+ matcher(product: TProduct, offer: Offer): boolean;
26
+ price(product: TProduct, offer: Offer): ProductPrice | undefined;
27
+ /** Whether the product can be bought. Without it, it isn't checked. */
28
+ available?(product: TProduct, offer: Offer): boolean | undefined;
29
+ }
30
+
31
+ export const intelligentSearchHydration: StoryHydration<Product> = {
32
+ fetcher: intelligentSearchFetcher,
33
+ matcher: intelligentSearchMatcher,
34
+ price: intelligentSearchPrice,
35
+ available: intelligentSearchAvailability,
36
+ };
37
+
38
+ export interface StoryProductDetails {
39
+ price?: ProductPrice;
40
+ /** Missing when the strategy doesn't say. */
41
+ available?: boolean;
42
+ }
43
+
44
+ // A price the card can show: an amount (0 included, as the strategy says),
45
+ // with the "from" price only when it is above it, as intelligentSearchPrice
46
+ // reads them. A store's own reader may return anything (a missing amount,
47
+ // NaN, a string): then the ad server's price shows instead.
48
+ function toShownPrice(
49
+ value: ProductPrice | undefined,
50
+ ): ProductPrice | undefined {
51
+ const isAmount = (amount: unknown): amount is number =>
52
+ typeof amount === "number" && Number.isFinite(amount) && amount >= 0;
53
+
54
+ if (!isAmount(value?.price)) return undefined;
55
+ const { price, listPrice } = value;
56
+ return isAmount(listPrice) && listPrice > price
57
+ ? { price, listPrice }
58
+ : { price };
59
+ }
60
+
61
+ export interface HydrateProductsOptions {
62
+ signal?: AbortSignal;
63
+ timeout?: number;
64
+ }
65
+
66
+ export async function hydrateStoryProducts(
67
+ placement: string,
68
+ stories: StoryAd[],
69
+ hydration: StoryHydration,
70
+ identity: Identity,
71
+ { signal, timeout }: HydrateProductsOptions = {},
72
+ ): Promise<Map<string, StoryProductDetails>> {
73
+ const products = new Map<string, StoryProductDetails>();
74
+ const limit = withTimeout(timeout, DEFAULT_HYDRATION_TIMEOUT_MS, signal);
75
+
76
+ try {
77
+ const hydrated = await hydrateAds(
78
+ { stories: { [placement]: stories } },
79
+ hydration.fetcher,
80
+ (product, offer) => hydration.matcher(product, offer),
81
+ identity,
82
+ { signal: limit.signal },
83
+ );
84
+
85
+ for (const { story, product, offer } of hydrated.stories[placement] ?? []) {
86
+ if (!product || !offer) continue;
87
+ try {
88
+ const price = toShownPrice(hydration.price(product, offer));
89
+ const available = hydration.available?.(product, offer);
90
+ products.set(story.ad_id, {
91
+ ...(price && { price }),
92
+ ...(available !== undefined && { available }),
93
+ });
94
+ } catch (error) {
95
+ console.error(
96
+ `[${TAG_NAME}] Product details failed for ad ${story.ad_id}`,
97
+ error,
98
+ );
99
+ }
100
+ }
101
+ } catch (error) {
102
+ // As for the Story request: a cancelled or timed out request needs no
103
+ // log, any other failure does.
104
+ if (!limit.signal.aborted) {
105
+ console.error(`[${TAG_NAME}] Product request failed`, error);
106
+ }
107
+ } finally {
108
+ limit.clear();
109
+ }
110
+
111
+ return products;
112
+ }
@@ -0,0 +1,58 @@
1
+ import { withTimeout } from "./with-timeout";
2
+
3
+ /** How long the first Story's media may take before it shows anyway, in ms. */
4
+ export const MEDIA_TIMEOUT = 3000;
5
+
6
+ /**
7
+ * Loads and decodes an image, so it paints at once when it shows. Resolves
8
+ * true once it is ready and false if it fails. Never rejects.
9
+ *
10
+ * Without `Image` or `decode` (SSR, old browsers, jsdom) there is nothing to
11
+ * wait for: it resolves true at once.
12
+ */
13
+ export function decodeImage(url: string): Promise<boolean> {
14
+ if (typeof Image === "undefined") return Promise.resolve(true);
15
+
16
+ const image = new Image();
17
+ image.src = url;
18
+ if (!image.decode) return Promise.resolve(true);
19
+ return image.decode().then(
20
+ () => true,
21
+ () => false,
22
+ );
23
+ }
24
+
25
+ /**
26
+ * Waits for the first of `checks` to be ready: resolves when one resolves
27
+ * true, when all resolved false (nothing left to wait for), after
28
+ * MEDIA_TIMEOUT, or when `signal` aborts. Never rejects.
29
+ */
30
+ export function firstReady(
31
+ checks: readonly Promise<boolean>[],
32
+ signal?: AbortSignal,
33
+ ): Promise<void> {
34
+ if (!checks.length) return Promise.resolve();
35
+
36
+ const limit = withTimeout(undefined, MEDIA_TIMEOUT, signal);
37
+
38
+ return new Promise<void>((resolve) => {
39
+ const done = () => {
40
+ limit.clear();
41
+ resolve();
42
+ };
43
+ if (limit.signal.aborted) return done();
44
+ limit.signal.addEventListener("abort", done, { once: true });
45
+
46
+ let failed = 0;
47
+ for (const check of checks) {
48
+ check.then(
49
+ (ready) => {
50
+ if (ready || ++failed === checks.length) done();
51
+ },
52
+ () => {
53
+ if (++failed === checks.length) done();
54
+ },
55
+ );
56
+ }
57
+ });
58
+ }
@@ -0,0 +1,36 @@
1
+ // Only absolute http(s) URLs reach the DOM or the network. Relative and
2
+ // protocol-relative ones ("/a.jpg", "//host/a.jpg") don't parse without a
3
+ // base, so they're out.
4
+ export function httpUrl(value: string | undefined) {
5
+ if (!value) return null;
6
+ try {
7
+ const { protocol } = new URL(value);
8
+ return protocol === "https:" || protocol === "http:" ? value : null;
9
+ } catch {
10
+ return null;
11
+ }
12
+ }
13
+
14
+ const STORE_BASE = "https://store.invalid";
15
+
16
+ // A path on the store the Story runs in ("/product/p"), resolved the way the
17
+ // browser would, or null when it lands on another host ("//evil.com",
18
+ // "/\\evil.com", "/\t/evil.com").
19
+ function storePath(value: string) {
20
+ try {
21
+ const url = new URL(value, STORE_BASE);
22
+ if (url.origin !== STORE_BASE || url.pathname.startsWith("//")) {
23
+ return null;
24
+ }
25
+ return `${url.pathname}${url.search}${url.hash}`;
26
+ } catch {
27
+ return null;
28
+ }
29
+ }
30
+
31
+ // A destination is an absolute http(s) URL or a path on the store the
32
+ // Story runs in.
33
+ export function destinationUrl(value: string | undefined) {
34
+ if (!value) return null;
35
+ return value.startsWith("/") ? storePath(value) : httpUrl(value);
36
+ }
@@ -0,0 +1,71 @@
1
+ import { httpUrl } from "./safe-url";
2
+ import { TAG_NAME } from "../tag-name";
3
+
4
+ // A CORS-safelisted type: the browser sends the event without a preflight
5
+ // request, and sendBeacon accepts it everywhere. The event host reads the
6
+ // body as JSON whatever its type.
7
+ const CONTENT_TYPE = "text/plain;charset=utf-8";
8
+
9
+ /** Who the event is for: the same session sent in the ad request. */
10
+ export interface EventIdentity {
11
+ sessionId: string;
12
+ userId?: string;
13
+ }
14
+
15
+ /**
16
+ * Sends an impression, view or click to the event URL from the ad response,
17
+ * as VTEX Ads asks of browsers: a POST with a JSON body holding `session_id`
18
+ * and, when known, `user_id`, through `navigator.sendBeacon`, so the event
19
+ * survives the page being left. Without the Beacon API, or when the browser
20
+ * refuses to queue the beacon, it falls back to a `fetch` with `keepalive`.
21
+ * The body goes as `text/plain` (see CONTENT_TYPE).
22
+ *
23
+ * The fallback isn't awaited: it returns true once the `fetch` starts, and a
24
+ * failed request is logged, not sent again. The server deduplicates by
25
+ * session anyway, and a retry could outlive the page.
26
+ *
27
+ * Returns false, sending nothing, when the URL isn't an absolute http(s)
28
+ * URL, during server-side rendering or when both ways fail at once.
29
+ */
30
+ export function sendEvent(
31
+ url: string | undefined,
32
+ { sessionId, userId }: EventIdentity,
33
+ ): boolean {
34
+ const target = httpUrl(url);
35
+ if (!target || globalThis.window === undefined) return false;
36
+
37
+ const body = JSON.stringify(
38
+ userId
39
+ ? { session_id: sessionId, user_id: userId }
40
+ : { session_id: sessionId },
41
+ );
42
+
43
+ try {
44
+ const queued = globalThis.navigator?.sendBeacon?.(
45
+ target,
46
+ new Blob([body], { type: CONTENT_TYPE }),
47
+ );
48
+ if (queued) return true;
49
+ } catch {
50
+ // A browser that throws instead of refusing (for example, for a URL it
51
+ // won't beacon to): the fetch below sends it instead.
52
+ }
53
+
54
+ if (typeof globalThis.fetch !== "function") return false;
55
+
56
+ globalThis
57
+ .fetch(target, {
58
+ method: "POST",
59
+ headers: { "Content-Type": CONTENT_TYPE },
60
+ body,
61
+ keepalive: true,
62
+ credentials: "omit",
63
+ })
64
+ .catch((error: unknown) => {
65
+ console.error(`[${TAG_NAME}] Event request failed`, {
66
+ url: target,
67
+ error,
68
+ });
69
+ });
70
+ return true;
71
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * A signal that aborts when the caller's signal aborts or after `timeout`
3
+ * milliseconds, whichever comes first. A `timeout` missing, zero, negative or
4
+ * not a number uses `fallback`. Built by hand instead of with
5
+ * `AbortSignal.any` and `AbortSignal.timeout`, which older browsers lack.
6
+ *
7
+ * Call `clear()` once the work is done, so the timer and the listener on the
8
+ * caller's signal don't outlive it.
9
+ */
10
+ export const withTimeout = (
11
+ timeout: number | undefined,
12
+ fallback: number,
13
+ signal?: AbortSignal,
14
+ ): { signal: AbortSignal; clear: () => void } => {
15
+ const ms =
16
+ timeout !== undefined && Number.isFinite(timeout) && timeout > 0
17
+ ? timeout
18
+ : fallback;
19
+ const controller = new AbortController();
20
+
21
+ const timer = setTimeout(
22
+ () =>
23
+ controller.abort(
24
+ new DOMException(`Timed out after ${ms} ms`, "TimeoutError"),
25
+ ),
26
+ ms,
27
+ );
28
+ const onAbort = () => controller.abort(signal?.reason);
29
+
30
+ if (signal?.aborted) {
31
+ onAbort();
32
+ } else {
33
+ signal?.addEventListener("abort", onAbort, { once: true });
34
+ }
35
+
36
+ return {
37
+ signal: controller.signal,
38
+ clear: () => {
39
+ clearTimeout(timer);
40
+ signal?.removeEventListener("abort", onAbort);
41
+ },
42
+ };
43
+ };