@vouchfor/embeds 0.0.0-experiment.b565b72 → 0.0.0-experiment.b764e6a

Sign up to get free protection for your applications and to get access to all the features.
package/package.json CHANGED
@@ -1,12 +1,15 @@
1
1
  {
2
2
  "name": "@vouchfor/embeds",
3
- "version": "0.0.0-experiment.b565b72",
3
+ "version": "0.0.0-experiment.b764e6a",
4
4
  "license": "MIT",
5
5
  "author": "Aaron Williams",
6
- "main": "dist/embeds.js",
7
- "module": "dist/embeds.js",
6
+ "main": "dist/es/embeds.js",
7
+ "module": "dist/es/embeds.js",
8
8
  "type": "module",
9
- "types": "dist/src/index.d.ts",
9
+ "types": "dist/es/index.d.ts",
10
+ "exports": {
11
+ ".": "./dist/es/embeds.js"
12
+ },
10
13
  "files": ["dist", "src"],
11
14
  "publishConfig": {
12
15
  "tag": "experiment",
@@ -23,7 +26,7 @@
23
26
  "lint:staged": "lint-staged",
24
27
  "prepublishOnly": "yarn build",
25
28
  "size": "size-limit",
26
- "storybook": "yarn prebuild && storybook dev -p 6006",
29
+ "storybook": "yarn prebuild && storybook dev -p 6007",
27
30
  "prebuild": "yarn build:deps && yarn generate:manifest",
28
31
  "test": "true"
29
32
  },
@@ -32,10 +35,12 @@
32
35
  "**/*.{md,json,yml}": "prettier --write"
33
36
  },
34
37
  "dependencies": {
35
- "@vouchfor/media-player": "0.0.0-experiment.b565b72"
38
+ "@lit/task": "^1.0.0",
39
+ "@vouchfor/media-player": "0.0.0-experiment.b764e6a",
40
+ "uuid": "^9.0.1"
36
41
  },
37
42
  "peerDependencies": {
38
- "lit": "^2.7.5"
43
+ "lit": "^3.1.0"
39
44
  },
40
45
  "devDependencies": {
41
46
  "@esm-bundle/chai": "^4.3.4-fix.0",
@@ -57,7 +62,7 @@
57
62
  "eslint": "^8.50.0",
58
63
  "eslint-plugin-import": "^2.28.1",
59
64
  "lint-staged": "^14.0.1",
60
- "lit": "^2.8.0",
65
+ "lit": "^3.1.0",
61
66
  "prettier": "^3.0.3",
62
67
  "react": "^18.2.0",
63
68
  "react-dom": "^18.2.0",
@@ -0,0 +1,79 @@
1
+ import { html } from 'lit';
2
+ import { ifDefined } from 'lit/directives/if-defined.js';
3
+
4
+ import type { EmbedProps } from './';
5
+ import type { Meta, StoryObj } from '@storybook/web-components';
6
+
7
+ import './';
8
+
9
+ type EmbedArgs = EmbedProps & {
10
+ showVouch?: boolean;
11
+ };
12
+
13
+ const _Embed = ({
14
+ vouchId,
15
+ templateId,
16
+ questions,
17
+ preload,
18
+ autoplay,
19
+ env,
20
+ apiKey,
21
+ controls,
22
+ aspectRatio
23
+ }: EmbedArgs) => {
24
+ return html`
25
+ <div style="height: 100vh">
26
+ <vouch-embed
27
+ env=${ifDefined(env)}
28
+ apiKey=${ifDefined(apiKey)}
29
+ vouchId=${ifDefined(vouchId)}
30
+ templateId=${ifDefined(templateId)}
31
+ .questions=${questions}
32
+ .controls=${controls}
33
+ ?autoplay=${autoplay}
34
+ preload=${ifDefined(preload)}
35
+ aspectRatio=${ifDefined(aspectRatio)}
36
+ @error=${console.log}
37
+ ></vouch-embed>
38
+ </div>
39
+ `;
40
+ };
41
+
42
+ // More on how to set up stories at: https://storybook.js.org/docs/web-components/writing-stories/introduction
43
+ const meta = {
44
+ title: 'Embed',
45
+ tags: ['autodocs'],
46
+ render: (args) => _Embed(args),
47
+ component: 'vouch-embed'
48
+ } satisfies Meta<EmbedProps>;
49
+
50
+ type Story = StoryObj<EmbedArgs>;
51
+
52
+ const Embed: Story = {
53
+ args: {
54
+ env: 'local',
55
+ apiKey: 'TVik9uTMgE-PD25UTHIS6gyl0hMBWC7AT4dkpdlLBT4VIfDWZJrQiCk6Ak7m1',
56
+ vouchId: '6JQEIPeStt',
57
+ templateId: '357fc118-e179-4171-9446-ff2b8e9d1b29',
58
+ questions: [],
59
+ aspectRatio: 0,
60
+ preload: 'none',
61
+ autoplay: false
62
+ },
63
+ argTypes: {
64
+ env: {
65
+ control: 'radio',
66
+ options: ['local', 'dev', 'staging', 'prod']
67
+ },
68
+ preload: {
69
+ control: 'radio',
70
+ options: ['auto', 'none']
71
+ }
72
+ },
73
+ parameters: {
74
+ layout: 'fullscreen'
75
+ }
76
+ };
77
+
78
+ export default meta;
79
+ export { Embed };
@@ -0,0 +1,47 @@
1
+ import { createRef, ref } from 'lit/directives/ref.js';
2
+
3
+ import type { Embed } from '..';
4
+ import type { ReactiveController, ReactiveControllerHost } from 'lit';
5
+ import type { Ref } from 'lit/directives/ref.js';
6
+
7
+ import { forwardEvent } from '~/utils/events';
8
+
9
+ type EmbedHost = ReactiveControllerHost & Embed;
10
+
11
+ class EventForwardController implements ReactiveController {
12
+ host: EmbedHost;
13
+
14
+ private _events: string[] = [];
15
+ private _cleanup: (() => void)[] = [];
16
+ private _forwardElementRef: Ref<HTMLElement> = createRef();
17
+
18
+ constructor(host: EmbedHost, events: string[]) {
19
+ this.host = host;
20
+ this._events = events;
21
+ host.addController(this);
22
+ }
23
+
24
+ register() {
25
+ return ref(this._forwardElementRef);
26
+ }
27
+
28
+ hostConnected() {
29
+ // Guaranteed to have the element ref in the RAF callback because of how the lit lifecycle works
30
+ requestAnimationFrame(() => {
31
+ this._events.forEach((event) => {
32
+ if (this._forwardElementRef.value) {
33
+ this._cleanup.push(forwardEvent(event, this._forwardElementRef.value, this.host));
34
+ }
35
+ });
36
+ });
37
+ }
38
+
39
+ hostDisconnected() {
40
+ this._cleanup.forEach((fn) => {
41
+ fn();
42
+ });
43
+ this._cleanup = [];
44
+ }
45
+ }
46
+
47
+ export { EventForwardController };
@@ -0,0 +1,152 @@
1
+ import { Task } from '@lit/task';
2
+ import { v4 as uuidv4 } from 'uuid';
3
+
4
+ import type { Embed, EmbedProps } from '..';
5
+ import type { ReactiveControllerHost } from 'lit';
6
+ import type { Environment } from '~/utils/env';
7
+
8
+ import { getEnvUrls } from '~/utils/env';
9
+
10
+ type EmbedHost = ReactiveControllerHost & Embed;
11
+
12
+ type FetchTaskDeps = [
13
+ EmbedProps['env'],
14
+ EmbedProps['apiKey'],
15
+ EmbedProps['data'],
16
+ EmbedProps['vouchId'],
17
+ EmbedProps['templateId']
18
+ ];
19
+
20
+ type FilterTaskDeps = [EmbedProps['data'], EmbedProps['questions']];
21
+
22
+ class FetcherController {
23
+ host: EmbedHost;
24
+
25
+ private _fetching = false;
26
+ private _vouch: EmbedProps['data'];
27
+
28
+ set fetching(value) {
29
+ if (this._fetching !== value) {
30
+ this._fetching = value;
31
+ this.host.requestUpdate();
32
+ }
33
+ }
34
+ get fetching() {
35
+ return this._fetching;
36
+ }
37
+
38
+ private getVouch = async (env: Environment, apiKey: string, vouchId: string) => {
39
+ const { embedApiUrl } = getEnvUrls(env);
40
+
41
+ const cacheCheck = uuidv4();
42
+ const res = await fetch(`${embedApiUrl}/vouches/${vouchId}`, {
43
+ method: 'GET',
44
+ headers: [
45
+ ['X-Api-Key', apiKey],
46
+ ['X-Cache-Check', cacheCheck]
47
+ ]
48
+ });
49
+
50
+ const vouch = await res.json();
51
+ this.host.dispatchEvent(new CustomEvent('vouch:loaded', { detail: vouch?.id }));
52
+
53
+ // HACK: we're currently using API Gateway caching on the embed API without any invalidation logic,
54
+ // so to ensure that the cache stays up to date, whenever we detect a cache hit we trigger another
55
+ // API call with the `Cache-Control` header which will re-fill the cache
56
+ const resCacheCheck = res?.headers?.get('X-Cache-Check');
57
+ if (resCacheCheck !== cacheCheck) {
58
+ fetch(`${embedApiUrl}/vouches/${vouchId}`, {
59
+ method: 'GET',
60
+ headers: [
61
+ ['X-Api-Key', apiKey],
62
+ ['Cache-Control', 'max-age=0']
63
+ ]
64
+ });
65
+ }
66
+
67
+ return vouch;
68
+ };
69
+
70
+ private getTemplate = async (env: Environment, apiKey: string, templateId: string) => {
71
+ const { embedApiUrl } = getEnvUrls(env);
72
+
73
+ const cacheCheck = uuidv4();
74
+ const res = await fetch(`${embedApiUrl}/templates/${templateId}`, {
75
+ method: 'GET',
76
+ headers: [
77
+ ['X-Api-Key', apiKey],
78
+ ['X-Cache-Check', cacheCheck]
79
+ ]
80
+ });
81
+ const template = await res.json();
82
+
83
+ // HACK: we're currently using API Gateway caching on the embed API without any invalidation logic,
84
+ // so to ensure that the cache stays up to date, whenever we detect a cache hit we trigger another
85
+ // API call with the `Cache-Control` header which will re-fill the cache
86
+ const resCacheCheck = res?.headers?.get('X-Cache-Check');
87
+ if (resCacheCheck !== cacheCheck) {
88
+ fetch(`${embedApiUrl}/templates/${templateId}`, {
89
+ method: 'GET',
90
+ headers: [
91
+ ['X-Api-Key', apiKey],
92
+ ['Cache-Control', 'max-age=0']
93
+ ]
94
+ });
95
+ }
96
+
97
+ return template;
98
+ };
99
+
100
+ constructor(host: EmbedHost) {
101
+ this.host = host;
102
+ new Task<FetchTaskDeps, void>(
103
+ this.host,
104
+ async ([env, apiKey, data, vouchId, templateId]: FetchTaskDeps) => {
105
+ try {
106
+ host.vouch = undefined;
107
+ host.template = undefined;
108
+
109
+ if (data) {
110
+ let template;
111
+ if (templateId) {
112
+ this.fetching = true;
113
+ template = await this.getTemplate(env, apiKey, templateId);
114
+ }
115
+ this._vouch = data;
116
+ host.template = template ?? data?.settings?.template?.instance;
117
+ } else if (vouchId) {
118
+ this.fetching = true;
119
+
120
+ const [vouch, template] = await Promise.all([
121
+ this.getVouch(env, apiKey, vouchId),
122
+ templateId ? this.getTemplate(env, apiKey, templateId) : null
123
+ ]);
124
+ this._vouch = vouch;
125
+ host.template = template ?? vouch?.settings?.template?.instance;
126
+ }
127
+ } finally {
128
+ this.fetching = false;
129
+ }
130
+ },
131
+ () => [host.env, host.apiKey, host.data, host.vouchId, host.templateId]
132
+ );
133
+
134
+ // This second task is to be able to filter the vouch without fetching it again if only the questions changed
135
+ new Task<FilterTaskDeps, void>(
136
+ this.host,
137
+ ([vouch, questions]: FilterTaskDeps) => {
138
+ host.vouch = vouch
139
+ ? {
140
+ ...vouch,
141
+ questions: {
142
+ items: vouch?.questions.items.filter((_, index) => !questions?.length || questions?.includes(index + 1))
143
+ }
144
+ }
145
+ : undefined;
146
+ },
147
+ () => [this._vouch, host.questions]
148
+ );
149
+ }
150
+ }
151
+
152
+ export { FetcherController };
@@ -0,0 +1,292 @@
1
+ import { v4 as uuidv4 } from 'uuid';
2
+
3
+ import type { Embed } from '..';
4
+ import type { VideoEventDetail } from '@vouchfor/media-player';
5
+ import type { ReactiveController, ReactiveControllerHost } from 'lit';
6
+
7
+ import packageJson from '../../../../package.json';
8
+ import { getEnvUrls } from '~/utils/env';
9
+
10
+ const MINIMUM_SEND_THRESHOLD = 1;
11
+
12
+ type EmbedHost = ReactiveControllerHost & Embed;
13
+
14
+ type TrackingEvent = 'VOUCH_LOADED' | 'VOUCH_RESPONSE_VIEWED' | 'VIDEO_PLAYED' | 'VIDEO_STREAMED';
15
+ type TrackingPayload = {
16
+ vouchId?: string;
17
+ answerId?: string;
18
+ streamStart?: number;
19
+ streamEnd?: number;
20
+ };
21
+
22
+ type TimeMap = {
23
+ [key: string]: number;
24
+ };
25
+
26
+ type BooleanMap = {
27
+ [key: string]: boolean;
28
+ };
29
+
30
+ class TrackingController implements ReactiveController {
31
+ host: EmbedHost;
32
+
33
+ private _tabId: string | undefined = undefined;
34
+ private _clientId: string | undefined = undefined;
35
+ private _visitorId: string | undefined = undefined;
36
+
37
+ private _hasPlayed = false;
38
+ private _hasLoaded: BooleanMap = {};
39
+ private _answersViewed: BooleanMap = {};
40
+ private _streamStartTime: TimeMap = {};
41
+ private _streamLatestTime: TimeMap = {};
42
+ private _currentlyPlayingVideo: VideoEventDetail | null = null;
43
+
44
+ constructor(host: EmbedHost) {
45
+ this.host = host;
46
+ host.addController(this);
47
+ }
48
+
49
+ private _findVouchId(payload?: TrackingPayload) {
50
+ if (payload && 'vouchId' in payload) {
51
+ return payload.vouchId;
52
+ }
53
+ if (this.host.vouch) {
54
+ return this.host.vouch.id;
55
+ }
56
+ return null;
57
+ }
58
+
59
+ private _createVisitor = (visitorId: string) => {
60
+ const { publicApiUrl } = getEnvUrls(this.host.env);
61
+ window.localStorage?.setItem?.('vouch-uid-visitor', visitorId);
62
+ navigator.sendBeacon(`${publicApiUrl}/api/visitor`, JSON.stringify({ visitorId }));
63
+ return visitorId;
64
+ };
65
+
66
+ private _getUids() {
67
+ if (typeof window === 'undefined') {
68
+ return {
69
+ client: null,
70
+ tab: null,
71
+ request: uuidv4()
72
+ };
73
+ }
74
+
75
+ // Persisted for a user for the same device + browser, so we can e.g. search for all logs related to that browser
76
+ const visitorId =
77
+ this._visitorId || window.localStorage?.getItem?.('vouch-uid-visitor') || this._createVisitor(uuidv4());
78
+ // Persisted for a user for the same device + browser, so we can e.g. search for all logs related to that browser
79
+ const clientId = this._clientId || window.localStorage?.getItem?.('vouch-uid-client') || uuidv4();
80
+ // Persisted in session storage, so we can search for everything the user has done in a specific tab
81
+ const tabId = this._tabId || window.sessionStorage?.getItem?.('vouch-uid-tab') || uuidv4();
82
+ // Not persisted, allows us to search for any logs related to a single FE request
83
+ // E.g. BE should pass this request ID through all other services to be able to group logs
84
+ const requestId = uuidv4();
85
+
86
+ // Cache and persist uids
87
+ if (visitorId !== this._visitorId) {
88
+ this._visitorId = visitorId;
89
+ window.localStorage?.setItem?.('vouch-uid-visitor', visitorId);
90
+ }
91
+
92
+ if (clientId !== this._clientId) {
93
+ this._clientId = clientId;
94
+ window.localStorage?.setItem?.('vouch-uid-client', clientId);
95
+ }
96
+
97
+ if (tabId !== this._tabId) {
98
+ this._tabId = tabId;
99
+ window.sessionStorage?.setItem?.('vouch-uid-tab', tabId);
100
+ }
101
+
102
+ return {
103
+ client: clientId,
104
+ tab: tabId,
105
+ request: requestId,
106
+ visitor: visitorId
107
+ };
108
+ }
109
+
110
+ private _getReportingMetadata = () => {
111
+ const [country, region] = Intl.DateTimeFormat().resolvedOptions().timeZone?.split?.('/') ?? [];
112
+
113
+ const utmParams: any = {};
114
+ [...new URLSearchParams(location.search).entries()].forEach(([key, value]) => {
115
+ if (/utm/.test(key)) {
116
+ const param = key.toLowerCase().replace(/[-_][a-z0-9]/g, (group) => group.slice(-1).toUpperCase());
117
+ utmParams[param] = value;
118
+ }
119
+ });
120
+
121
+ return {
122
+ source: this.host.trackingSource,
123
+ time: new Date(),
124
+ region,
125
+ country,
126
+ screenHeight: window.screen.height,
127
+ screenWidth: window.screen.width,
128
+ referrer: document.referrer,
129
+ currentUrl: location.href,
130
+ ...utmParams
131
+ };
132
+ };
133
+
134
+ private _sendTrackingEvent = (event: TrackingEvent, payload?: TrackingPayload) => {
135
+ const vouchId = this._findVouchId(payload);
136
+
137
+ if (!vouchId || this.host.disableTracking) {
138
+ return;
139
+ }
140
+
141
+ const { publicApiUrl } = getEnvUrls(this.host.env);
142
+ const { client, tab, request, visitor } = this._getUids();
143
+
144
+ navigator.sendBeacon(
145
+ `${publicApiUrl}/api/v2/events`,
146
+ JSON.stringify({
147
+ event,
148
+ payload: {
149
+ ...payload,
150
+ vouchId
151
+ },
152
+ context: {
153
+ 'x-uid-client': client,
154
+ 'x-uid-tab': tab,
155
+ 'x-uid-request': request,
156
+ 'x-uid-visitor': visitor,
157
+ 'x-reporting-metadata': this._getReportingMetadata(),
158
+ 'x-embeds-version': packageJson.version
159
+ }
160
+ })
161
+ );
162
+ };
163
+
164
+ private _streamEnded = () => {
165
+ if (this._currentlyPlayingVideo) {
166
+ const { id, key } = this._currentlyPlayingVideo;
167
+ // Don't send a tracking event when seeking backwards
168
+ if (this._streamLatestTime[key] > this._streamStartTime[key] + MINIMUM_SEND_THRESHOLD) {
169
+ // Send a video streamed event any time the stream ends to capture the time between starting
170
+ // the video and the video stopping for any reason (pausing, deleting the embed node or closing the browser)
171
+ this._sendTrackingEvent('VIDEO_STREAMED', {
172
+ answerId: id,
173
+ streamStart: this._streamStartTime[key],
174
+ streamEnd: this._streamLatestTime[key]
175
+ });
176
+ }
177
+
178
+ // Make sure these events are only sent once by deleting the start and latest times
179
+ delete this._streamStartTime[key];
180
+ delete this._streamLatestTime[key];
181
+ }
182
+ };
183
+
184
+ private _handleVouchLoaded = ({ detail: vouchId }: CustomEvent<string>) => {
185
+ if (!vouchId) {
186
+ return;
187
+ }
188
+
189
+ // Only send loaded event once per session
190
+ if (!this._hasLoaded[vouchId]) {
191
+ this._sendTrackingEvent('VOUCH_LOADED', { vouchId });
192
+ this._hasLoaded[vouchId] = true;
193
+ }
194
+ };
195
+
196
+ private _handlePlay = () => {
197
+ // Only send the video played event once per session
198
+ if (!this._hasPlayed) {
199
+ this._sendTrackingEvent('VIDEO_PLAYED', {
200
+ streamStart: this.host.currentTime
201
+ });
202
+ this._hasPlayed = true;
203
+ }
204
+ };
205
+
206
+ private _handleVideoPlay = ({ detail: { id, key, node } }: CustomEvent<VideoEventDetail>) => {
207
+ // Only increment play count once per session
208
+ if (!this._answersViewed[key]) {
209
+ this._sendTrackingEvent('VOUCH_RESPONSE_VIEWED', {
210
+ answerId: id
211
+ });
212
+ this._answersViewed[key] = true;
213
+ }
214
+
215
+ if (!this._streamStartTime[key]) {
216
+ this._streamStartTime[key] = node.currentTime;
217
+ this._streamLatestTime[key] = node.currentTime;
218
+ }
219
+ };
220
+
221
+ private _handleVideoTimeUpdate = ({ detail: { id, key, node } }: CustomEvent<VideoEventDetail>) => {
222
+ if (
223
+ // We only want to count any time that the video is actually playing
224
+ !this.host.paused &&
225
+ // Only update the latest time if this event fires for the currently active video
226
+ id === this.host.scene?.video?.id
227
+ ) {
228
+ this._currentlyPlayingVideo = { id, key, node };
229
+ this._streamLatestTime[key] = node.currentTime;
230
+ }
231
+ };
232
+
233
+ private _handleVideoPause = ({ detail: { id, key } }: CustomEvent<VideoEventDetail>) => {
234
+ if (this._streamLatestTime[key] > this._streamStartTime[key] + MINIMUM_SEND_THRESHOLD) {
235
+ this._sendTrackingEvent('VIDEO_STREAMED', {
236
+ answerId: id,
237
+ streamStart: this._streamStartTime[key],
238
+ streamEnd: this._streamLatestTime[key]
239
+ });
240
+ }
241
+ delete this._streamStartTime[key];
242
+ delete this._streamLatestTime[key];
243
+ };
244
+
245
+ private _pageUnloading = () => {
246
+ this._streamEnded();
247
+ // This will try to send the same stream event again so we delete the start and latest
248
+ // time in stream ended so that there is no times to send and the pause event does nothing
249
+ this.host.pause();
250
+ };
251
+
252
+ private _handleVisibilityChange = () => {
253
+ if (document.visibilityState === 'hidden') {
254
+ this._pageUnloading();
255
+ }
256
+ };
257
+
258
+ private _handlePageHide = () => {
259
+ this._pageUnloading();
260
+ };
261
+
262
+ hostConnected() {
263
+ requestAnimationFrame(() => {
264
+ if ('onvisibilitychange' in document) {
265
+ document.addEventListener('visibilitychange', this._handleVisibilityChange);
266
+ } else {
267
+ window.addEventListener('pagehide', this._handlePageHide);
268
+ }
269
+ this.host.addEventListener('vouch:loaded', this._handleVouchLoaded);
270
+ this.host.mediaPlayer?.addEventListener('play', this._handlePlay);
271
+ this.host.mediaPlayer?.addEventListener('video:play', this._handleVideoPlay);
272
+ this.host.mediaPlayer?.addEventListener('video:pause', this._handleVideoPause);
273
+ this.host.mediaPlayer?.addEventListener('video:timeupdate', this._handleVideoTimeUpdate);
274
+ });
275
+ }
276
+
277
+ hostDisconnected() {
278
+ this._streamEnded();
279
+ if ('onvisibilitychange' in document) {
280
+ document.removeEventListener('visibilitychange', this._handleVisibilityChange);
281
+ } else {
282
+ window.removeEventListener('pagehide', this._handlePageHide);
283
+ }
284
+ this.host.removeEventListener('vouch:loaded', this._handleVouchLoaded);
285
+ this.host.mediaPlayer?.removeEventListener('play', this._handlePlay);
286
+ this.host.mediaPlayer?.removeEventListener('video:play', this._handleVideoPlay);
287
+ this.host.mediaPlayer?.removeEventListener('video:pause', this._handleVideoPause);
288
+ this.host.mediaPlayer?.removeEventListener('video:timeupdate', this._handleVideoTimeUpdate);
289
+ }
290
+ }
291
+
292
+ export { TrackingController };