@vouchfor/embeds 0.0.0-experiment.2d4da6c → 0.0.0-experiment.2da2c49

Sign up to get free protection for your applications and to get access to all the features.
Files changed (74) hide show
  1. package/dist/es/{browser-8b4ecf1d.js → browser-17f8a53b.js} +2 -2
  2. package/dist/es/{browser-8b4ecf1d.js.map → browser-17f8a53b.js.map} +1 -1
  3. package/dist/es/embeds.js +5 -2
  4. package/dist/es/embeds.js.map +1 -1
  5. package/dist/es/index-747e8b52.js +10478 -0
  6. package/dist/es/index-747e8b52.js.map +1 -0
  7. package/dist/es/src/components/DialogEmbed/DialogOverlay.d.ts +19 -0
  8. package/dist/es/src/components/DialogEmbed/DialogPortal.d.ts +35 -0
  9. package/dist/es/src/components/DialogEmbed/index.d.ts +35 -0
  10. package/dist/es/src/components/PlayerEmbed/controllers/event-forwarder.d.ts +15 -0
  11. package/dist/es/src/components/{Embed → PlayerEmbed}/controllers/fetcher.d.ts +4 -4
  12. package/dist/es/src/components/{Embed/controllers/tracking.d.ts → PlayerEmbed/controllers/tracking/index.d.ts} +14 -11
  13. package/dist/es/src/components/PlayerEmbed/controllers/tracking/utils.d.ts +17 -0
  14. package/dist/es/src/components/PlayerEmbed/tests/data.d.ts +3 -0
  15. package/dist/es/src/index.d.ts +2 -1
  16. package/dist/iife/dialog-embed/browser-2436b04a.js +433 -0
  17. package/dist/iife/dialog-embed/browser-2436b04a.js.map +1 -0
  18. package/dist/iife/dialog-embed/embed.iife.js +1721 -0
  19. package/dist/iife/dialog-embed/embed.iife.js.map +1 -0
  20. package/dist/iife/dialog-embed/embed.js +5 -0
  21. package/dist/iife/dialog-embed/embed.js.map +1 -0
  22. package/dist/iife/dialog-embed/index-c39a015a.js +32937 -0
  23. package/dist/iife/dialog-embed/index-c39a015a.js.map +1 -0
  24. package/dist/iife/dialog-embed/src/components/DialogEmbed/DialogOverlay.d.ts +19 -0
  25. package/dist/iife/dialog-embed/src/components/DialogEmbed/DialogPortal.d.ts +35 -0
  26. package/dist/iife/dialog-embed/src/components/DialogEmbed/index.d.ts +35 -0
  27. package/dist/iife/dialog-embed/src/components/PlayerEmbed/controllers/event-forwarder.d.ts +15 -0
  28. package/dist/iife/dialog-embed/src/components/PlayerEmbed/controllers/fetcher.d.ts +14 -0
  29. package/dist/iife/dialog-embed/src/components/PlayerEmbed/controllers/tracking/index.d.ts +36 -0
  30. package/dist/iife/dialog-embed/src/components/PlayerEmbed/controllers/tracking/utils.d.ts +17 -0
  31. package/dist/iife/dialog-embed/src/components/PlayerEmbed/tests/data.d.ts +3 -0
  32. package/dist/iife/dialog-embed/src/index.d.ts +2 -0
  33. package/dist/iife/dialog-embed/src/utils/env.d.ts +12 -0
  34. package/dist/iife/dialog-embed/src/utils/events.d.ts +2 -0
  35. package/dist/iife/embeds.iife.js +428 -265
  36. package/dist/iife/embeds.iife.js.map +1 -1
  37. package/dist/iife/player-embed/browser-88dbf1ce.js +433 -0
  38. package/dist/iife/player-embed/browser-88dbf1ce.js.map +1 -0
  39. package/dist/iife/player-embed/embed.iife.js +1585 -0
  40. package/dist/iife/player-embed/embed.iife.js.map +1 -0
  41. package/dist/iife/player-embed/embed.js +5 -0
  42. package/dist/iife/player-embed/embed.js.map +1 -0
  43. package/dist/iife/player-embed/index-601226fd.js +32494 -0
  44. package/dist/iife/player-embed/index-601226fd.js.map +1 -0
  45. package/dist/iife/player-embed/src/components/DialogEmbed/DialogOverlay.d.ts +19 -0
  46. package/dist/iife/player-embed/src/components/DialogEmbed/DialogPortal.d.ts +35 -0
  47. package/dist/iife/player-embed/src/components/DialogEmbed/index.d.ts +35 -0
  48. package/dist/iife/player-embed/src/components/PlayerEmbed/controllers/event-forwarder.d.ts +15 -0
  49. package/dist/iife/player-embed/src/components/PlayerEmbed/controllers/fetcher.d.ts +14 -0
  50. package/dist/iife/player-embed/src/components/PlayerEmbed/controllers/tracking/index.d.ts +36 -0
  51. package/dist/iife/player-embed/src/components/PlayerEmbed/controllers/tracking/utils.d.ts +17 -0
  52. package/dist/iife/player-embed/src/components/PlayerEmbed/tests/data.d.ts +3 -0
  53. package/dist/iife/player-embed/src/index.d.ts +2 -0
  54. package/dist/iife/player-embed/src/utils/env.d.ts +12 -0
  55. package/dist/iife/player-embed/src/utils/events.d.ts +2 -0
  56. package/package.json +13 -5
  57. package/src/components/DialogEmbed/Dialog.stories.ts +79 -0
  58. package/src/components/DialogEmbed/DialogOverlay.ts +130 -0
  59. package/src/components/DialogEmbed/DialogPortal.ts +114 -0
  60. package/src/components/DialogEmbed/index.ts +93 -0
  61. package/src/components/{Embed/Embed.stories.ts → PlayerEmbed/PlayerEmbed.stories.ts} +15 -15
  62. package/src/components/{Embed → PlayerEmbed}/controllers/event-forwarder.ts +6 -5
  63. package/src/components/{Embed → PlayerEmbed}/controllers/fetcher.ts +11 -11
  64. package/src/components/{Embed/controllers/tracking.ts → PlayerEmbed/controllers/tracking/index.ts} +47 -118
  65. package/src/components/PlayerEmbed/controllers/tracking/utils.ts +95 -0
  66. package/src/components/PlayerEmbed/index.ts +149 -0
  67. package/src/components/PlayerEmbed/tests/PlayerEmbed.spec.ts +80 -0
  68. package/src/components/PlayerEmbed/tests/data.ts +183 -0
  69. package/src/index.ts +2 -1
  70. package/src/mixins/media-player-proxy.ts +116 -0
  71. package/dist/es/index-4c628d0f.js +0 -9948
  72. package/dist/es/index-4c628d0f.js.map +0 -1
  73. package/dist/es/src/components/Embed/index.d.ts +0 -70
  74. package/src/components/Embed/index.ts +0 -217
@@ -0,0 +1,93 @@
1
+ import { css, html, LitElement } from 'lit';
2
+ import { customElement, property } from 'lit/decorators.js';
3
+ import { ifDefined } from 'lit/directives/if-defined.js';
4
+
5
+ import type { PlayerEmbedProps } from '../PlayerEmbed';
6
+
7
+ import '../PlayerEmbed';
8
+ import './DialogPortal';
9
+
10
+ type DialogEmbedProps = Omit<PlayerEmbedProps, 'data'> & {
11
+ disableAutoplay?: boolean;
12
+ };
13
+
14
+ @customElement('vouch-embed-dialog')
15
+ class DialogEmbed extends LitElement {
16
+ static styles = [
17
+ css`
18
+ :host {
19
+ --vu-button-padding: 10px 20px;
20
+ --vu-button-background: #287179;
21
+ --vu-button-background-hover: #4faab2;
22
+
23
+ display: flex;
24
+ width: fit-content;
25
+ height: fit-content;
26
+ }
27
+ `
28
+ ];
29
+
30
+ @property({ type: String }) vouchId: DialogEmbedProps['vouchId'];
31
+ @property({ type: String }) templateId: DialogEmbedProps['templateId'];
32
+ @property({ type: Array }) questions: DialogEmbedProps['questions'];
33
+
34
+ @property({ type: String }) env: DialogEmbedProps['env'] = 'prod';
35
+ @property({ type: String }) apiKey: DialogEmbedProps['apiKey'] = '';
36
+ @property({ type: Boolean }) disableTracking: DialogEmbedProps['disableTracking'] = false;
37
+ @property({ type: String }) trackingSource: DialogEmbedProps['trackingSource'] = 'embedded_player';
38
+
39
+ @property({ type: Array }) controls: DialogEmbedProps['controls'];
40
+ @property({ type: String }) preload: DialogEmbedProps['preload'] = 'none';
41
+ @property({ type: Boolean }) disableAutoplay: DialogEmbedProps['disableAutoplay'] = false;
42
+ @property({ type: Number }) aspectRatio: DialogEmbedProps['aspectRatio'] = 0;
43
+
44
+ private _handleRootClick = () => {
45
+ this.dispatchEvent(new CustomEvent('dialogembed:click', { bubbles: true, composed: true }));
46
+ };
47
+
48
+ connectedCallback(): void {
49
+ super.connectedCallback();
50
+ this.addEventListener('click', this._handleRootClick);
51
+ }
52
+
53
+ disconnectedCallback(): void {
54
+ super.disconnectedCallback();
55
+ this.removeEventListener('click', this._handleRootClick);
56
+ }
57
+
58
+ render() {
59
+ return html`
60
+ <slot>
61
+ <vmp-button size="large">Play</vmp-button>
62
+ </slot>
63
+ <vouch-embed-dialog-portal
64
+ ?autoplay=${false}
65
+ vouchId=${ifDefined(this.vouchId)}
66
+ templateId=${ifDefined(this.templateId)}
67
+ .questions=${this.questions}
68
+ .controls=${this.controls}
69
+ env=${ifDefined(this.env)}
70
+ apiKey=${ifDefined(this.apiKey)}
71
+ ?disableTracking=${this.disableTracking}
72
+ trackingSource=${ifDefined(this.trackingSource)}
73
+ preload=${ifDefined(this.preload)}
74
+ aspectRatio=${this.aspectRatio}
75
+ ></vouch-embed-dialog-portal>
76
+ `;
77
+ }
78
+ }
79
+
80
+ declare global {
81
+ interface HTMLElementTagNameMap {
82
+ 'vouch-embed-dialog': DialogEmbed;
83
+ }
84
+
85
+ namespace JSX {
86
+ interface IntrinsicElements {
87
+ 'vouch-embed-dialog': DialogEmbed;
88
+ }
89
+ }
90
+ }
91
+
92
+ export { DialogEmbed };
93
+ export type { DialogEmbedProps };
@@ -1,16 +1,16 @@
1
1
  import { html } from 'lit';
2
2
  import { ifDefined } from 'lit/directives/if-defined.js';
3
3
 
4
- import type { EmbedProps } from './';
4
+ import type { PlayerEmbedProps } from '.';
5
5
  import type { Meta, StoryObj } from '@storybook/web-components';
6
6
 
7
- import './';
7
+ import '.';
8
8
 
9
- type EmbedArgs = EmbedProps & {
9
+ type PlayerEmbedArgs = PlayerEmbedProps & {
10
10
  showVouch?: boolean;
11
11
  };
12
12
 
13
- const _Embed = ({
13
+ const _PlayerEmbed = ({
14
14
  vouchId,
15
15
  templateId,
16
16
  questions,
@@ -20,10 +20,10 @@ const _Embed = ({
20
20
  apiKey,
21
21
  controls,
22
22
  aspectRatio
23
- }: EmbedArgs) => {
23
+ }: PlayerEmbedArgs) => {
24
24
  return html`
25
25
  <div style="height: 100vh">
26
- <vouch-embed
26
+ <vouch-embed-player
27
27
  env=${ifDefined(env)}
28
28
  apiKey=${ifDefined(apiKey)}
29
29
  vouchId=${ifDefined(vouchId)}
@@ -34,24 +34,24 @@ const _Embed = ({
34
34
  preload=${ifDefined(preload)}
35
35
  aspectRatio=${ifDefined(aspectRatio)}
36
36
  @error=${console.log}
37
- ></vouch-embed>
37
+ ></vouch-embed-player>
38
38
  </div>
39
39
  `;
40
40
  };
41
41
 
42
42
  // More on how to set up stories at: https://storybook.js.org/docs/web-components/writing-stories/introduction
43
43
  const meta = {
44
- title: 'Embed',
44
+ title: 'Embeds',
45
45
  tags: ['autodocs'],
46
- render: (args) => _Embed(args),
47
- component: 'vouch-embed'
48
- } satisfies Meta<EmbedProps>;
46
+ render: (args) => _PlayerEmbed(args),
47
+ component: 'vouch-embed-player'
48
+ } satisfies Meta<PlayerEmbedProps>;
49
49
 
50
- type Story = StoryObj<EmbedArgs>;
50
+ type Story = StoryObj<PlayerEmbedArgs>;
51
51
 
52
- const Embed: Story = {
52
+ const Player: Story = {
53
53
  args: {
54
- env: 'local',
54
+ env: 'dev',
55
55
  apiKey: 'TVik9uTMgE-PD25UTHIS6gyl0hMBWC7AT4dkpdlLBT4VIfDWZJrQiCk6Ak7m1',
56
56
  vouchId: '6JQEIPeStt',
57
57
  templateId: '357fc118-e179-4171-9446-ff2b8e9d1b29',
@@ -76,4 +76,4 @@ const Embed: Story = {
76
76
  };
77
77
 
78
78
  export default meta;
79
- export { Embed };
79
+ export { Player };
@@ -1,27 +1,28 @@
1
1
  import { createRef, ref } from 'lit/directives/ref.js';
2
2
 
3
- import type { Embed } from '..';
3
+ import type { PlayerEmbed } from '..';
4
4
  import type { ReactiveController, ReactiveControllerHost } from 'lit';
5
+ import type { DirectiveResult } from 'lit/directive.js';
5
6
  import type { Ref } from 'lit/directives/ref.js';
6
7
 
7
8
  import { forwardEvent } from '~/utils/events';
8
9
 
9
- type EmbedHost = ReactiveControllerHost & Embed;
10
+ type PlayerEmbedHost = ReactiveControllerHost & PlayerEmbed;
10
11
 
11
12
  class EventForwardController implements ReactiveController {
12
- host: EmbedHost;
13
+ host: PlayerEmbedHost;
13
14
 
14
15
  private _events: string[] = [];
15
16
  private _cleanup: (() => void)[] = [];
16
17
  private _forwardElementRef: Ref<HTMLElement> = createRef();
17
18
 
18
- constructor(host: EmbedHost, events: string[]) {
19
+ constructor(host: PlayerEmbedHost, events: string[]) {
19
20
  this.host = host;
20
21
  this._events = events;
21
22
  host.addController(this);
22
23
  }
23
24
 
24
- register() {
25
+ register(): DirectiveResult {
25
26
  return ref(this._forwardElementRef);
26
27
  }
27
28
 
@@ -1,29 +1,29 @@
1
1
  import { Task } from '@lit/task';
2
2
  import { v4 as uuidv4 } from 'uuid';
3
3
 
4
- import type { Embed, EmbedProps } from '..';
4
+ import type { PlayerEmbed, PlayerEmbedProps } from '..';
5
5
  import type { ReactiveControllerHost } from 'lit';
6
6
  import type { Environment } from '~/utils/env';
7
7
 
8
8
  import { getEnvUrls } from '~/utils/env';
9
9
 
10
- type EmbedHost = ReactiveControllerHost & Embed;
10
+ type PlayerEmbedHost = ReactiveControllerHost & PlayerEmbed;
11
11
 
12
12
  type FetchTaskDeps = [
13
- EmbedProps['env'],
14
- EmbedProps['apiKey'],
15
- EmbedProps['data'],
16
- EmbedProps['vouchId'],
17
- EmbedProps['templateId']
13
+ PlayerEmbedProps['env'],
14
+ PlayerEmbedProps['apiKey'],
15
+ PlayerEmbedProps['data'],
16
+ PlayerEmbedProps['vouchId'],
17
+ PlayerEmbedProps['templateId']
18
18
  ];
19
19
 
20
- type FilterTaskDeps = [EmbedProps['data'], EmbedProps['questions']];
20
+ type FilterTaskDeps = [PlayerEmbedProps['data'], PlayerEmbedProps['questions']];
21
21
 
22
22
  class FetcherController {
23
- host: EmbedHost;
23
+ host: PlayerEmbedHost;
24
24
 
25
25
  private _fetching = false;
26
- private _vouch: EmbedProps['data'];
26
+ private _vouch: PlayerEmbedProps['data'];
27
27
 
28
28
  set fetching(value) {
29
29
  if (this._fetching !== value) {
@@ -97,7 +97,7 @@ class FetcherController {
97
97
  return template;
98
98
  };
99
99
 
100
- constructor(host: EmbedHost) {
100
+ constructor(host: PlayerEmbedHost) {
101
101
  this.host = host;
102
102
  new Task<FetchTaskDeps, void>(
103
103
  this.host,
@@ -1,16 +1,13 @@
1
- import { TEMPLATE_VERSION } from '@vouchfor/canvas-video';
2
- import { v4 as uuidv4 } from 'uuid';
3
-
4
- import type { Embed } from '..';
1
+ import type { PlayerEmbed } from '../..';
5
2
  import type { VideoEventDetail } from '@vouchfor/media-player';
6
3
  import type { ReactiveController, ReactiveControllerHost } from 'lit';
7
4
 
8
- import packageJson from '../../../../package.json';
5
+ import { findVouchId, getReportingMetadata, getUids } from './utils';
9
6
  import { getEnvUrls } from '~/utils/env';
10
7
 
11
8
  const MINIMUM_SEND_THRESHOLD = 1;
12
9
 
13
- type EmbedHost = ReactiveControllerHost & Embed;
10
+ type PlayerEmbedHost = ReactiveControllerHost & PlayerEmbed;
14
11
 
15
12
  type TrackingEvent = 'VOUCH_LOADED' | 'VOUCH_RESPONSE_VIEWED' | 'VIDEO_PLAYED' | 'VIDEO_STREAMED';
16
13
  type TrackingPayload = {
@@ -20,6 +17,13 @@ type TrackingPayload = {
20
17
  streamEnd?: number;
21
18
  };
22
19
 
20
+ type BatchEvent = {
21
+ event: TrackingEvent;
22
+ payload: TrackingPayload & {
23
+ time: string;
24
+ };
25
+ };
26
+
23
27
  type TimeMap = {
24
28
  [key: string]: number;
25
29
  };
@@ -29,12 +33,9 @@ type BooleanMap = {
29
33
  };
30
34
 
31
35
  class TrackingController implements ReactiveController {
32
- host: EmbedHost;
33
-
34
- private _tabId: string | undefined = undefined;
35
- private _clientId: string | undefined = undefined;
36
- private _visitorId: string | undefined = undefined;
36
+ host: PlayerEmbedHost;
37
37
 
38
+ private _batchedEvents: BatchEvent[] = [];
38
39
  private _hasPlayed = false;
39
40
  private _hasLoaded: BooleanMap = {};
40
41
  private _answersViewed: BooleanMap = {};
@@ -42,126 +43,53 @@ class TrackingController implements ReactiveController {
42
43
  private _streamLatestTime: TimeMap = {};
43
44
  private _currentlyPlayingVideo: VideoEventDetail | null = null;
44
45
 
45
- constructor(host: EmbedHost) {
46
+ constructor(host: PlayerEmbedHost) {
46
47
  this.host = host;
47
48
  host.addController(this);
48
49
  }
49
50
 
50
- private _findVouchId(payload?: TrackingPayload) {
51
- if (payload && 'vouchId' in payload) {
52
- return payload.vouchId;
53
- }
54
- if (this.host.vouch) {
55
- return this.host.vouch.id;
56
- }
57
- return null;
58
- }
59
-
60
- private _createVisitor = (visitorId: string) => {
61
- const { publicApiUrl } = getEnvUrls(this.host.env);
62
- window.localStorage?.setItem?.('vouch-uid-visitor', visitorId);
63
- navigator.sendBeacon(`${publicApiUrl}/api/visitor`, JSON.stringify({ visitorId }));
64
- return visitorId;
65
- };
66
-
67
- private _getUids() {
68
- if (typeof window === 'undefined') {
69
- return {
70
- client: null,
71
- tab: null,
72
- request: uuidv4()
73
- };
74
- }
75
-
76
- // Persisted for a user for the same device + browser, so we can e.g. search for all logs related to that browser
77
- const visitorId =
78
- this._visitorId || window.localStorage?.getItem?.('vouch-uid-visitor') || this._createVisitor(uuidv4());
79
- // Persisted for a user for the same device + browser, so we can e.g. search for all logs related to that browser
80
- const clientId = this._clientId || window.localStorage?.getItem?.('vouch-uid-client') || uuidv4();
81
- // Persisted in session storage, so we can search for everything the user has done in a specific tab
82
- const tabId = this._tabId || window.sessionStorage?.getItem?.('vouch-uid-tab') || uuidv4();
83
- // Not persisted, allows us to search for any logs related to a single FE request
84
- // E.g. BE should pass this request ID through all other services to be able to group logs
85
- const requestId = uuidv4();
86
-
87
- // Cache and persist uids
88
- if (visitorId !== this._visitorId) {
89
- this._visitorId = visitorId;
90
- window.localStorage?.setItem?.('vouch-uid-visitor', visitorId);
91
- }
92
-
93
- if (clientId !== this._clientId) {
94
- this._clientId = clientId;
95
- window.localStorage?.setItem?.('vouch-uid-client', clientId);
96
- }
51
+ private _createTrackingEvent = (event: TrackingEvent, payload?: TrackingPayload) => {
52
+ const vouchId = findVouchId(payload, this.host.vouch);
97
53
 
98
- if (tabId !== this._tabId) {
99
- this._tabId = tabId;
100
- window.sessionStorage?.setItem?.('vouch-uid-tab', tabId);
54
+ if (!vouchId || this.host.disableTracking) {
55
+ return;
101
56
  }
102
57
 
103
- return {
104
- client: clientId,
105
- tab: tabId,
106
- request: requestId,
107
- visitor: visitorId
108
- };
109
- }
110
-
111
- private _getReportingMetadata = () => {
112
- const [country, region] = Intl.DateTimeFormat().resolvedOptions().timeZone?.split?.('/') ?? [];
113
-
114
- const utmParams: any = {};
115
- [...new URLSearchParams(location.search).entries()].forEach(([key, value]) => {
116
- if (/utm/.test(key)) {
117
- const param = key.toLowerCase().replace(/[-_][a-z0-9]/g, (group) => group.slice(-1).toUpperCase());
118
- utmParams[param] = value;
58
+ this._batchedEvents.push({
59
+ event,
60
+ payload: {
61
+ ...payload,
62
+ vouchId,
63
+ time: new Date().toISOString()
119
64
  }
120
65
  });
121
-
122
- return {
123
- source: this.host.trackingSource,
124
- time: new Date(),
125
- region,
126
- country,
127
- screenHeight: window.screen.height,
128
- screenWidth: window.screen.width,
129
- referrer: document.referrer,
130
- currentUrl: location.href,
131
- embedType: 'media-player-embed',
132
- embedVersion: packageJson.version,
133
- templateVersion: TEMPLATE_VERSION,
134
- ...utmParams
135
- };
136
66
  };
137
67
 
138
- private _sendTrackingEvent = (event: TrackingEvent, payload?: TrackingPayload) => {
139
- const vouchId = this._findVouchId(payload);
140
-
141
- if (!vouchId || this.host.disableTracking) {
68
+ private _sendTrackingEvent = () => {
69
+ if (this._batchedEvents.length <= 0) {
142
70
  return;
143
71
  }
144
72
 
145
73
  const { publicApiUrl } = getEnvUrls(this.host.env);
146
- const { client, tab, request, visitor } = this._getUids();
74
+ const { client, tab, request, visitor } = getUids(this.host.env);
147
75
 
148
76
  navigator.sendBeacon(
149
- `${publicApiUrl}/api/v2/events`,
77
+ `${publicApiUrl}/api/batchevents`,
150
78
  JSON.stringify({
151
- event,
152
79
  payload: {
153
- ...payload,
154
- vouchId
80
+ events: this._batchedEvents
155
81
  },
156
82
  context: {
157
83
  'x-uid-client': client,
158
84
  'x-uid-tab': tab,
159
85
  'x-uid-request': request,
160
86
  'x-uid-visitor': visitor,
161
- 'x-reporting-metadata': this._getReportingMetadata()
87
+ 'x-reporting-metadata': getReportingMetadata(this.host.trackingSource)
162
88
  }
163
89
  })
164
90
  );
91
+
92
+ this._batchedEvents = [];
165
93
  };
166
94
 
167
95
  private _streamEnded = () => {
@@ -171,7 +99,7 @@ class TrackingController implements ReactiveController {
171
99
  if (this._streamLatestTime[key] > this._streamStartTime[key] + MINIMUM_SEND_THRESHOLD) {
172
100
  // Send a video streamed event any time the stream ends to capture the time between starting
173
101
  // the video and the video stopping for any reason (pausing, deleting the embed node or closing the browser)
174
- this._sendTrackingEvent('VIDEO_STREAMED', {
102
+ this._createTrackingEvent('VIDEO_STREAMED', {
175
103
  answerId: id,
176
104
  streamStart: this._streamStartTime[key],
177
105
  streamEnd: this._streamLatestTime[key]
@@ -191,7 +119,7 @@ class TrackingController implements ReactiveController {
191
119
 
192
120
  // Only send loaded event once per session
193
121
  if (!this._hasLoaded[vouchId]) {
194
- this._sendTrackingEvent('VOUCH_LOADED', { vouchId });
122
+ this._createTrackingEvent('VOUCH_LOADED', { vouchId });
195
123
  this._hasLoaded[vouchId] = true;
196
124
  }
197
125
  };
@@ -199,26 +127,21 @@ class TrackingController implements ReactiveController {
199
127
  private _handlePlay = () => {
200
128
  // Only send the video played event once per session
201
129
  if (!this._hasPlayed) {
202
- this._sendTrackingEvent('VIDEO_PLAYED', {
130
+ this._createTrackingEvent('VIDEO_PLAYED', {
203
131
  streamStart: this.host.currentTime
204
132
  });
205
133
  this._hasPlayed = true;
206
134
  }
207
135
  };
208
136
 
209
- private _handleVideoPlay = ({ detail: { id, key, node } }: CustomEvent<VideoEventDetail>) => {
137
+ private _handleVideoPlay = ({ detail: { id, key } }: CustomEvent<VideoEventDetail>) => {
210
138
  // Only increment play count once per session
211
139
  if (!this._answersViewed[key]) {
212
- this._sendTrackingEvent('VOUCH_RESPONSE_VIEWED', {
140
+ this._createTrackingEvent('VOUCH_RESPONSE_VIEWED', {
213
141
  answerId: id
214
142
  });
215
143
  this._answersViewed[key] = true;
216
144
  }
217
-
218
- if (!this._streamStartTime[key]) {
219
- this._streamStartTime[key] = node.currentTime;
220
- this._streamLatestTime[key] = node.currentTime;
221
- }
222
145
  };
223
146
 
224
147
  private _handleVideoTimeUpdate = ({ detail: { id, key, node } }: CustomEvent<VideoEventDetail>) => {
@@ -230,12 +153,17 @@ class TrackingController implements ReactiveController {
230
153
  ) {
231
154
  this._currentlyPlayingVideo = { id, key, node };
232
155
  this._streamLatestTime[key] = node.currentTime;
156
+
157
+ if (!this._streamStartTime[key]) {
158
+ this._streamStartTime[key] = node.currentTime;
159
+ this._streamLatestTime[key] = node.currentTime;
160
+ }
233
161
  }
234
162
  };
235
163
 
236
164
  private _handleVideoPause = ({ detail: { id, key } }: CustomEvent<VideoEventDetail>) => {
237
165
  if (this._streamLatestTime[key] > this._streamStartTime[key] + MINIMUM_SEND_THRESHOLD) {
238
- this._sendTrackingEvent('VIDEO_STREAMED', {
166
+ this._createTrackingEvent('VIDEO_STREAMED', {
239
167
  answerId: id,
240
168
  streamStart: this._streamStartTime[key],
241
169
  streamEnd: this._streamLatestTime[key]
@@ -247,9 +175,7 @@ class TrackingController implements ReactiveController {
247
175
 
248
176
  private _pageUnloading = () => {
249
177
  this._streamEnded();
250
- // This will try to send the same stream event again so we delete the start and latest
251
- // time in stream ended so that there is no times to send and the pause event does nothing
252
- this.host.pause();
178
+ this._sendTrackingEvent();
253
179
  };
254
180
 
255
181
  private _handleVisibilityChange = () => {
@@ -278,7 +204,9 @@ class TrackingController implements ReactiveController {
278
204
  }
279
205
 
280
206
  hostDisconnected() {
281
- this._streamEnded();
207
+ // Send events if DOM node is destroyed
208
+ this._pageUnloading();
209
+
282
210
  if ('onvisibilitychange' in document) {
283
211
  document.removeEventListener('visibilitychange', this._handleVisibilityChange);
284
212
  } else {
@@ -293,3 +221,4 @@ class TrackingController implements ReactiveController {
293
221
  }
294
222
 
295
223
  export { TrackingController };
224
+ export type { TrackingEvent, TrackingPayload };
@@ -0,0 +1,95 @@
1
+ import { TEMPLATE_VERSION } from '@vouchfor/canvas-video';
2
+ import { v4 as uuidv4 } from 'uuid';
3
+
4
+ import type { TrackingPayload } from '.';
5
+ import type { Vouch } from '@vouchfor/media-player';
6
+ import type { Environment } from '~/utils/env';
7
+
8
+ import packageJson from '~/../package.json';
9
+ import { getEnvUrls } from '~/utils/env';
10
+
11
+ function createVisitor(env: Environment) {
12
+ const { publicApiUrl } = getEnvUrls(env);
13
+ const visitorId = uuidv4();
14
+ navigator.sendBeacon(`${publicApiUrl}/api/visitor`, JSON.stringify({ visitorId }));
15
+ return visitorId;
16
+ }
17
+
18
+ function getUids(env: Environment) {
19
+ if (typeof window === 'undefined') {
20
+ return {
21
+ client: null,
22
+ tab: null,
23
+ request: uuidv4()
24
+ };
25
+ }
26
+
27
+ // Persisted for a user for the same device + browser, so we can e.g. search for all logs related to that browser
28
+ let visitorId = window.localStorage?.getItem?.('vouch-uid-visitor');
29
+ // Persisted for a user for the same device + browser, so we can e.g. search for all logs related to that browser
30
+ let clientId = window.localStorage?.getItem?.('vouch-uid-client');
31
+ // Persisted in session storage, so we can search for everything the user has done in a specific tab
32
+ let tabId = window.sessionStorage?.getItem?.('vouch-uid-tab');
33
+ // Not persisted, allows us to search for any logs related to a single FE request
34
+ // E.g. BE should pass this request ID through all other services to be able to group logs
35
+ const requestId = uuidv4();
36
+
37
+ // Cache uids
38
+ if (!visitorId) {
39
+ visitorId = createVisitor(env);
40
+ window.localStorage?.setItem?.('vouch-uid-visitor', visitorId);
41
+ }
42
+
43
+ if (!clientId) {
44
+ clientId = uuidv4();
45
+ window.localStorage?.setItem?.('vouch-uid-client', clientId);
46
+ }
47
+
48
+ if (!tabId) {
49
+ tabId = uuidv4();
50
+ window.sessionStorage?.setItem?.('vouch-uid-tab', tabId);
51
+ }
52
+
53
+ return {
54
+ client: clientId,
55
+ tab: tabId,
56
+ request: requestId,
57
+ visitor: visitorId
58
+ };
59
+ }
60
+
61
+ function findVouchId(payload?: TrackingPayload, vouch?: Vouch) {
62
+ if (payload && 'vouchId' in payload) {
63
+ return payload.vouchId;
64
+ }
65
+ return vouch?.id ?? null;
66
+ }
67
+
68
+ function getReportingMetadata(source = 'embedded_player') {
69
+ const [country, region] = Intl.DateTimeFormat().resolvedOptions().timeZone?.split?.('/') ?? [];
70
+
71
+ const utmParams: any = {};
72
+ [...new URLSearchParams(location.search).entries()].forEach(([key, value]) => {
73
+ if (/utm/.test(key)) {
74
+ const param = key.toLowerCase().replace(/[-_][a-z0-9]/g, (group) => group.slice(-1).toUpperCase());
75
+ utmParams[param] = value;
76
+ }
77
+ });
78
+
79
+ return {
80
+ source,
81
+ time: new Date(),
82
+ region,
83
+ country,
84
+ screenHeight: window.screen.height,
85
+ screenWidth: window.screen.width,
86
+ referrer: document.referrer,
87
+ currentUrl: location.href,
88
+ embedType: 'media-player-embed',
89
+ embedVersion: packageJson.version,
90
+ templateVersion: TEMPLATE_VERSION,
91
+ ...utmParams
92
+ };
93
+ }
94
+
95
+ export { getUids, findVouchId, getReportingMetadata };