coveo.analytics 2.21.27 → 2.22.2

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.
@@ -1,5 +1,4 @@
1
- import { fetch } from 'cross-fetch';
2
- import AsyncStorage from '@react-native-async-storage/async-storage';
1
+ import { fetch as fetch$1 } from 'cross-fetch';
3
2
 
4
3
  /*! *****************************************************************************
5
4
  Copyright (c) Microsoft Corporation.
@@ -64,7 +63,7 @@ class AnalyticsFetchClient {
64
63
  body: JSON.stringify(payload),
65
64
  };
66
65
  const _a = Object.assign(Object.assign({}, defaultOptions), (preprocessRequest ? yield preprocessRequest(defaultOptions, 'analyticsFetch') : {})), { url } = _a, fetchData = __rest(_a, ["url"]);
67
- const response = yield fetch(url, fetchData);
66
+ const response = yield fetch$1(url, fetchData);
68
67
  if (response.ok) {
69
68
  const visit = (yield response.json());
70
69
  if (visit.visitorId) {
@@ -87,7 +86,7 @@ class AnalyticsFetchClient {
87
86
  return __awaiter(this, void 0, void 0, function* () {
88
87
  const { baseUrl } = this.opts;
89
88
  const url = `${baseUrl}/analytics/visit`;
90
- yield fetch(url, { headers: this.getHeaders(), method: 'DELETE' });
89
+ yield fetch$1(url, { headers: this.getHeaders(), method: 'DELETE' });
91
90
  });
92
91
  }
93
92
  shouldAppendVisitorId(eventType) {
@@ -106,29 +105,2160 @@ class AnalyticsFetchClient {
106
105
  }
107
106
  }
108
107
 
109
- class ReactNativeStorage {
108
+ function hasWindow() {
109
+ return typeof window !== 'undefined';
110
+ }
111
+ function hasNavigator() {
112
+ return typeof navigator !== 'undefined';
113
+ }
114
+ function hasDocument() {
115
+ return typeof document !== 'undefined';
116
+ }
117
+ function hasLocalStorage() {
118
+ try {
119
+ return typeof localStorage !== 'undefined';
120
+ }
121
+ catch (error) {
122
+ return false;
123
+ }
124
+ }
125
+ function hasSessionStorage() {
126
+ try {
127
+ return typeof sessionStorage !== 'undefined';
128
+ }
129
+ catch (error) {
130
+ return false;
131
+ }
132
+ }
133
+ function hasCookieStorage() {
134
+ return hasNavigator() && navigator.cookieEnabled;
135
+ }
136
+ function hasCrypto() {
137
+ return typeof crypto !== 'undefined';
138
+ }
139
+ function hasCryptoRandomValues() {
140
+ return hasCrypto() && typeof crypto.getRandomValues !== 'undefined';
141
+ }
142
+
143
+ const uuidv4 = (a) => {
144
+ if (!!a) {
145
+ return (Number(a) ^ (getRandomValues(new Uint8Array(1))[0] % 16 >> (Number(a) / 4))).toString(16);
146
+ }
147
+ return (`${1e7}` + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, uuidv4);
148
+ };
149
+ const getRandomValues = (rnds) => {
150
+ if (hasCryptoRandomValues()) {
151
+ return crypto.getRandomValues(rnds);
152
+ }
153
+ for (var i = 0, r = 0; i < rnds.length; i++) {
154
+ if ((i & 0x03) === 0) {
155
+ r = Math.random() * 0x100000000;
156
+ }
157
+ rnds[i] = (r >>> ((i & 0x03) << 3)) & 0xff;
158
+ }
159
+ return rnds;
160
+ };
161
+
162
+ const eventTypesForDefaultValues = [EventType.click, EventType.custom, EventType.search, EventType.view];
163
+ const addDefaultValues = (eventType, payload) => {
164
+ return eventTypesForDefaultValues.indexOf(eventType) !== -1
165
+ ? Object.assign({ language: hasDocument() ? document.documentElement.lang : 'unknown', userAgent: hasNavigator() ? navigator.userAgent : 'unknown' }, payload) : payload;
166
+ };
167
+
168
+ class Cookie {
169
+ static set(name, value, expiration) {
170
+ var domain, domainParts, date, expires, host;
171
+ if (expiration) {
172
+ date = new Date();
173
+ date.setTime(date.getTime() + expiration);
174
+ expires = '; expires=' + date.toGMTString();
175
+ }
176
+ else {
177
+ expires = '';
178
+ }
179
+ host = location.hostname;
180
+ if (host.indexOf('.') === -1) {
181
+ document.cookie = name + '=' + value + expires + '; path=/';
182
+ }
183
+ else {
184
+ domainParts = host.split('.');
185
+ domainParts.shift();
186
+ domain = '.' + domainParts.join('.');
187
+ writeCookie({ name, value, expires, domain });
188
+ if (Cookie.get(name) == null || Cookie.get(name) != value) {
189
+ domain = '.' + host;
190
+ writeCookie({ name, value, expires, domain });
191
+ }
192
+ }
193
+ }
194
+ static get(name) {
195
+ var cookiePrefix = name + '=';
196
+ var cookieArray = document.cookie.split(';');
197
+ for (var i = 0; i < cookieArray.length; i++) {
198
+ var cookie = cookieArray[i];
199
+ cookie = cookie.replace(/^\s+/, '');
200
+ if (cookie.indexOf(cookiePrefix) == 0) {
201
+ return cookie.substring(cookiePrefix.length, cookie.length);
202
+ }
203
+ }
204
+ return null;
205
+ }
206
+ static erase(name) {
207
+ Cookie.set(name, '', -1);
208
+ }
209
+ }
210
+ function writeCookie(details) {
211
+ const { name, value, expires, domain } = details;
212
+ document.cookie = `${name}=${value}${expires}; path=/; domain=${domain}; SameSite=Lax`;
213
+ }
214
+
215
+ function getAvailableStorage() {
216
+ if (hasLocalStorage()) {
217
+ return localStorage;
218
+ }
219
+ if (hasCookieStorage()) {
220
+ return new CookieStorage();
221
+ }
222
+ if (hasSessionStorage()) {
223
+ return sessionStorage;
224
+ }
225
+ return new NullStorage();
226
+ }
227
+ class CookieStorage {
228
+ getItem(key) {
229
+ return Cookie.get(`${CookieStorage.prefix}${key}`);
230
+ }
231
+ removeItem(key) {
232
+ Cookie.erase(`${CookieStorage.prefix}${key}`);
233
+ }
234
+ setItem(key, data) {
235
+ Cookie.set(`${CookieStorage.prefix}${key}`, data);
236
+ }
237
+ }
238
+ CookieStorage.prefix = 'coveo_';
239
+ class CookieAndLocalStorage {
240
+ constructor() {
241
+ this.cookieStorage = new CookieStorage();
242
+ }
243
+ getItem(key) {
244
+ return localStorage.getItem(key) || this.cookieStorage.getItem(key);
245
+ }
246
+ removeItem(key) {
247
+ this.cookieStorage.removeItem(key);
248
+ localStorage.removeItem(key);
249
+ }
250
+ setItem(key, data) {
251
+ localStorage.setItem(key, data);
252
+ this.cookieStorage.setItem(key, data);
253
+ }
254
+ }
255
+ class NullStorage {
110
256
  getItem(key) {
257
+ return null;
258
+ }
259
+ removeItem(key) {
260
+ }
261
+ setItem(key, data) {
262
+ }
263
+ }
264
+
265
+ const STORE_KEY = '__coveo.analytics.history';
266
+ const MAX_NUMBER_OF_HISTORY_ELEMENTS = 20;
267
+ const MIN_THRESHOLD_FOR_DUPLICATE_VALUE = 1000 * 60;
268
+ const MAX_VALUE_SIZE = 75;
269
+ class HistoryStore {
270
+ constructor(store) {
271
+ this.store = store || getAvailableStorage();
272
+ }
273
+ addElement(elem) {
274
+ elem.internalTime = new Date().getTime();
275
+ elem = this.cropQueryElement(this.stripEmptyQuery(elem));
276
+ let currentHistory = this.getHistoryWithInternalTime();
277
+ if (currentHistory != null) {
278
+ if (this.isValidEntry(elem)) {
279
+ this.setHistory([elem].concat(currentHistory));
280
+ }
281
+ }
282
+ else {
283
+ this.setHistory([elem]);
284
+ }
285
+ }
286
+ addElementAsync(elem) {
111
287
  return __awaiter(this, void 0, void 0, function* () {
112
- return AsyncStorage.getItem(key);
288
+ elem.internalTime = new Date().getTime();
289
+ elem = this.cropQueryElement(this.stripEmptyQuery(elem));
290
+ let currentHistory = yield this.getHistoryWithInternalTimeAsync();
291
+ if (currentHistory != null) {
292
+ if (this.isValidEntry(elem)) {
293
+ this.setHistory([elem].concat(currentHistory));
294
+ }
295
+ }
296
+ else {
297
+ this.setHistory([elem]);
298
+ }
113
299
  });
114
300
  }
115
- setItem(key, data) {
301
+ getHistory() {
302
+ const history = this.getHistoryWithInternalTime();
303
+ return this.stripEmptyQueries(this.stripInternalTime(history));
304
+ }
305
+ getHistoryAsync() {
116
306
  return __awaiter(this, void 0, void 0, function* () {
117
- return AsyncStorage.setItem(key, data);
307
+ const history = yield this.getHistoryWithInternalTimeAsync();
308
+ return this.stripEmptyQueries(this.stripInternalTime(history));
118
309
  });
119
310
  }
120
- removeItem(key) {
311
+ getHistoryWithInternalTime() {
312
+ try {
313
+ const elements = this.store.getItem(STORE_KEY);
314
+ if (elements && typeof elements === 'string') {
315
+ return JSON.parse(elements);
316
+ }
317
+ else {
318
+ return [];
319
+ }
320
+ }
321
+ catch (e) {
322
+ return [];
323
+ }
324
+ }
325
+ getHistoryWithInternalTimeAsync() {
121
326
  return __awaiter(this, void 0, void 0, function* () {
122
- AsyncStorage.removeItem(key);
327
+ try {
328
+ const elements = yield this.store.getItem(STORE_KEY);
329
+ if (elements) {
330
+ return JSON.parse(elements);
331
+ }
332
+ else {
333
+ return [];
334
+ }
335
+ }
336
+ catch (e) {
337
+ return [];
338
+ }
123
339
  });
124
340
  }
341
+ setHistory(history) {
342
+ try {
343
+ this.store.setItem(STORE_KEY, JSON.stringify(history.slice(0, MAX_NUMBER_OF_HISTORY_ELEMENTS)));
344
+ }
345
+ catch (e) {
346
+ }
347
+ }
348
+ clear() {
349
+ try {
350
+ this.store.removeItem(STORE_KEY);
351
+ }
352
+ catch (e) {
353
+ }
354
+ }
355
+ getMostRecentElement() {
356
+ let currentHistory = this.getHistoryWithInternalTime();
357
+ if (currentHistory != null) {
358
+ const sorted = currentHistory.sort((first, second) => {
359
+ return (second.internalTime || 0) - (first.internalTime || 0);
360
+ });
361
+ return sorted[0];
362
+ }
363
+ return null;
364
+ }
365
+ cropQueryElement(part) {
366
+ if (part.name && part.value && part.name.toLowerCase() === 'query') {
367
+ part.value = part.value.slice(0, MAX_VALUE_SIZE);
368
+ }
369
+ return part;
370
+ }
371
+ isValidEntry(elem) {
372
+ let lastEntry = this.getMostRecentElement();
373
+ if (lastEntry && lastEntry.value == elem.value) {
374
+ return (elem.internalTime || 0) - (lastEntry.internalTime || 0) > MIN_THRESHOLD_FOR_DUPLICATE_VALUE;
375
+ }
376
+ return true;
377
+ }
378
+ stripInternalTime(history) {
379
+ return history.map((part) => {
380
+ const { name, time, value } = part;
381
+ return { name, time, value };
382
+ });
383
+ }
384
+ stripEmptyQuery(part) {
385
+ const { name, time, value } = part;
386
+ if (name && typeof value === 'string' && name.toLowerCase() === 'query' && value.trim() === '') {
387
+ return { name, time };
388
+ }
389
+ return part;
390
+ }
391
+ stripEmptyQueries(history) {
392
+ return history.map((part) => this.stripEmptyQuery(part));
393
+ }
125
394
  }
126
395
 
127
- class ReactNativeRuntime {
128
- constructor(clientOptions) {
129
- this.storage = new ReactNativeStorage();
396
+ var history = /*#__PURE__*/Object.freeze({
397
+ __proto__: null,
398
+ STORE_KEY: STORE_KEY,
399
+ MAX_NUMBER_OF_HISTORY_ELEMENTS: MAX_NUMBER_OF_HISTORY_ELEMENTS,
400
+ MIN_THRESHOLD_FOR_DUPLICATE_VALUE: MIN_THRESHOLD_FOR_DUPLICATE_VALUE,
401
+ MAX_VALUE_SIZE: MAX_VALUE_SIZE,
402
+ HistoryStore: HistoryStore,
403
+ 'default': HistoryStore
404
+ });
405
+
406
+ const enhanceViewEvent = (eventType, payload) => __awaiter(void 0, void 0, void 0, function* () {
407
+ if (eventType === EventType.view) {
408
+ yield addPageViewToHistory(payload.contentIdValue);
409
+ return Object.assign({ location: window.location.toString(), referrer: document.referrer, title: document.title }, payload);
410
+ }
411
+ return payload;
412
+ });
413
+ const addPageViewToHistory = (pageViewValue) => __awaiter(void 0, void 0, void 0, function* () {
414
+ const store = new HistoryStore();
415
+ const historyElement = {
416
+ name: 'PageView',
417
+ value: pageViewValue,
418
+ time: JSON.stringify(new Date()),
419
+ };
420
+ yield store.addElementAsync(historyElement);
421
+ });
422
+
423
+ const keysOf = Object.keys;
424
+
425
+ const ticketKeysMapping = {
426
+ id: 'svc_ticket_id',
427
+ subject: 'svc_ticket_subject',
428
+ description: 'svc_ticket_description',
429
+ category: 'svc_ticket_category',
430
+ productId: 'svc_ticket_product_id',
431
+ custom: 'svc_ticket_custom',
432
+ };
433
+ const ticketKeysMappingValues = keysOf(ticketKeysMapping).map((key) => ticketKeysMapping[key]);
434
+ const ticketSubKeysMatchGroup = [...ticketKeysMappingValues].join('|');
435
+ const ticketKeyRegex = new RegExp(`^(${ticketSubKeysMatchGroup}$)`);
436
+ const serviceActionsKeysMapping = {
437
+ svcAction: 'svc_action',
438
+ svcActionData: 'svc_action_data',
439
+ };
440
+ const convertTicketToMeasurementProtocol = (ticket) => {
441
+ return keysOf(ticket)
442
+ .filter((key) => ticket[key] !== undefined)
443
+ .reduce((mappedTicket, key) => {
444
+ const newKey = ticketKeysMapping[key] || key;
445
+ return Object.assign(Object.assign({}, mappedTicket), { [newKey]: ticket[key] });
446
+ }, {});
447
+ };
448
+ const isTicketKey = (key) => ticketKeyRegex.test(key);
449
+ const isServiceKey = [isTicketKey];
450
+
451
+ const productKeysMapping = {
452
+ id: 'id',
453
+ name: 'nm',
454
+ brand: 'br',
455
+ category: 'ca',
456
+ variant: 'va',
457
+ price: 'pr',
458
+ quantity: 'qt',
459
+ coupon: 'cc',
460
+ position: 'ps',
461
+ group: 'group',
462
+ };
463
+ const impressionKeysMapping = {
464
+ id: 'id',
465
+ name: 'nm',
466
+ brand: 'br',
467
+ category: 'ca',
468
+ variant: 'va',
469
+ position: 'ps',
470
+ price: 'pr',
471
+ group: 'group',
472
+ };
473
+ const productActionsKeysMapping = {
474
+ action: 'pa',
475
+ list: 'pal',
476
+ listSource: 'pls',
477
+ };
478
+ const transactionActionsKeysMapping = {
479
+ id: 'ti',
480
+ revenue: 'tr',
481
+ tax: 'tt',
482
+ shipping: 'ts',
483
+ coupon: 'tcc',
484
+ affiliation: 'ta',
485
+ step: 'cos',
486
+ option: 'col',
487
+ };
488
+ const coveoCommerceExtensionKeys = [
489
+ 'loyaltyCardId',
490
+ 'loyaltyTier',
491
+ 'thirdPartyPersona',
492
+ 'companyName',
493
+ 'favoriteStore',
494
+ 'storeName',
495
+ 'userIndustry',
496
+ 'userRole',
497
+ 'userDepartment',
498
+ 'businessUnit',
499
+ ];
500
+ const quoteActionsKeysMapping = {
501
+ id: 'quoteId',
502
+ affiliation: 'quoteAffiliation',
503
+ };
504
+ const reviewActionsKeysMapping = {
505
+ id: 'reviewId',
506
+ rating: 'reviewRating',
507
+ comment: 'reviewComment',
508
+ };
509
+ const commerceActionKeysMappingPerAction = {
510
+ add: productActionsKeysMapping,
511
+ bookmark_add: productActionsKeysMapping,
512
+ bookmark_remove: productActionsKeysMapping,
513
+ click: productActionsKeysMapping,
514
+ checkout: productActionsKeysMapping,
515
+ checkout_option: productActionsKeysMapping,
516
+ detail: productActionsKeysMapping,
517
+ impression: productActionsKeysMapping,
518
+ remove: productActionsKeysMapping,
519
+ refund: Object.assign(Object.assign({}, productActionsKeysMapping), transactionActionsKeysMapping),
520
+ purchase: Object.assign(Object.assign({}, productActionsKeysMapping), transactionActionsKeysMapping),
521
+ quickview: productActionsKeysMapping,
522
+ quote: Object.assign(Object.assign({}, productActionsKeysMapping), quoteActionsKeysMapping),
523
+ review: Object.assign(Object.assign({}, productActionsKeysMapping), reviewActionsKeysMapping),
524
+ };
525
+ const productKeysMappingValues = keysOf(productKeysMapping).map((key) => productKeysMapping[key]);
526
+ const impressionKeysMappingValues = keysOf(impressionKeysMapping).map((key) => impressionKeysMapping[key]);
527
+ const productActionsKeysMappingValues = keysOf(productActionsKeysMapping).map((key) => productActionsKeysMapping[key]);
528
+ const transactionActionsKeysMappingValues = keysOf(transactionActionsKeysMapping).map((key) => transactionActionsKeysMapping[key]);
529
+ const reviewKeysMappingValues = keysOf(reviewActionsKeysMapping).map((key) => reviewActionsKeysMapping[key]);
530
+ const quoteKeysMappingValues = keysOf(quoteActionsKeysMapping).map((key) => quoteActionsKeysMapping[key]);
531
+ const productSubKeysMatchGroup = [...productKeysMappingValues, 'custom'].join('|');
532
+ const impressionSubKeysMatchGroup = [...impressionKeysMappingValues, 'custom'].join('|');
533
+ const productPrefixMatchGroup = '(pr[0-9]+)';
534
+ const impressionPrefixMatchGroup = '(il[0-9]+pi[0-9]+)';
535
+ const productKeyRegex = new RegExp(`^${productPrefixMatchGroup}(${productSubKeysMatchGroup})$`);
536
+ const impressionKeyRegex = new RegExp(`^(${impressionPrefixMatchGroup}(${impressionSubKeysMatchGroup}))|(il[0-9]+nm)$`);
537
+ const productActionsKeyRegex = new RegExp(`^(${productActionsKeysMappingValues.join('|')})$`);
538
+ const transactionActionsKeyRegex = new RegExp(`^(${transactionActionsKeysMappingValues.join('|')})$`);
539
+ const customProductKeyRegex = new RegExp(`^${productPrefixMatchGroup}custom$`);
540
+ const customImpressionKeyRegex = new RegExp(`^${impressionPrefixMatchGroup}custom$`);
541
+ const coveoCommerceExtensionKeysRegex = new RegExp(`^(${[...coveoCommerceExtensionKeys, ...reviewKeysMappingValues, ...quoteKeysMappingValues].join('|')})$`);
542
+ const isProductKey = (key) => productKeyRegex.test(key);
543
+ const isImpressionKey = (key) => impressionKeyRegex.test(key);
544
+ const isProductActionsKey = (key) => productActionsKeyRegex.test(key);
545
+ const isTransactionActionsKeyRegex = (key) => transactionActionsKeyRegex.test(key);
546
+ const isCoveoCommerceExtensionKey = (key) => coveoCommerceExtensionKeysRegex.test(key);
547
+ const isCommerceKey = [
548
+ isImpressionKey,
549
+ isProductKey,
550
+ isProductActionsKey,
551
+ isTransactionActionsKeyRegex,
552
+ isCoveoCommerceExtensionKey,
553
+ ];
554
+ const isCustomCommerceKey = [customProductKeyRegex, customImpressionKeyRegex];
555
+
556
+ const globalParamKeysMapping = {
557
+ anonymizeIp: 'aip',
558
+ };
559
+ const eventKeysMapping = {
560
+ eventCategory: 'ec',
561
+ eventAction: 'ea',
562
+ eventLabel: 'el',
563
+ eventValue: 'ev',
564
+ page: 'dp',
565
+ visitorId: 'cid',
566
+ clientId: 'cid',
567
+ userId: 'uid',
568
+ currencyCode: 'cu',
569
+ };
570
+ const contextInformationMapping = {
571
+ hitType: 't',
572
+ pageViewId: 'pid',
573
+ encoding: 'de',
574
+ location: 'dl',
575
+ referrer: 'dr',
576
+ screenColor: 'sd',
577
+ screenResolution: 'sr',
578
+ title: 'dt',
579
+ userAgent: 'ua',
580
+ language: 'ul',
581
+ eventId: 'z',
582
+ time: 'tm',
583
+ };
584
+ const coveoExtensionsKeys = [
585
+ 'contentId',
586
+ 'contentIdKey',
587
+ 'contentType',
588
+ 'searchHub',
589
+ 'tab',
590
+ 'searchUid',
591
+ 'permanentId',
592
+ 'contentLocale',
593
+ ];
594
+ const baseMeasurementProtocolKeysMapping = Object.assign(Object.assign(Object.assign(Object.assign({}, globalParamKeysMapping), eventKeysMapping), contextInformationMapping), coveoExtensionsKeys.reduce((all, key) => (Object.assign(Object.assign({}, all), { [key]: key })), {}));
595
+
596
+ const measurementProtocolKeysMapping = Object.assign(Object.assign({}, baseMeasurementProtocolKeysMapping), serviceActionsKeysMapping);
597
+ const convertKeysToMeasurementProtocol = (params) => {
598
+ const keysMappingForAction = (!!params.action && commerceActionKeysMappingPerAction[params.action]) || {};
599
+ return keysOf(params).reduce((mappedKeys, key) => {
600
+ const newKey = keysMappingForAction[key] || measurementProtocolKeysMapping[key] || key;
601
+ return Object.assign(Object.assign({}, mappedKeys), { [newKey]: params[key] });
602
+ }, {});
603
+ };
604
+ const measurementProtocolKeysMappingValues = keysOf(measurementProtocolKeysMapping).map((key) => measurementProtocolKeysMapping[key]);
605
+ const isKnownMeasurementProtocolKey = (key) => measurementProtocolKeysMappingValues.indexOf(key) !== -1;
606
+ const isCustomKey = (key) => key === 'custom';
607
+ const isMeasurementProtocolKey = (key) => {
608
+ return [...isCommerceKey, ...isServiceKey, isKnownMeasurementProtocolKey, isCustomKey].some((test) => test(key));
609
+ };
610
+ const convertCustomMeasurementProtocolKeys = (data) => {
611
+ return keysOf(data).reduce((all, current) => {
612
+ const match = getFirstCustomMeasurementProtocolKeyMatch(current);
613
+ if (match) {
614
+ return Object.assign(Object.assign({}, all), convertCustomObject(match, data[current]));
615
+ }
616
+ else {
617
+ return Object.assign(Object.assign({}, all), { [current]: data[current] });
618
+ }
619
+ }, {});
620
+ };
621
+ const getFirstCustomMeasurementProtocolKeyMatch = (key) => {
622
+ let matchedKey = undefined;
623
+ [...isCustomCommerceKey].every((regex) => {
624
+ var _a;
625
+ matchedKey = (_a = regex.exec(key)) === null || _a === void 0 ? void 0 : _a[1];
626
+ return !Boolean(matchedKey);
627
+ });
628
+ return matchedKey;
629
+ };
630
+ const convertCustomObject = (prefix, customData) => {
631
+ return keysOf(customData).reduce((allCustom, currentCustomKey) => (Object.assign(Object.assign({}, allCustom), { [`${prefix}${currentCustomKey}`]: customData[currentCustomKey] })), {});
632
+ };
633
+
634
+ class AnalyticsBeaconClient {
635
+ constructor(opts) {
636
+ this.opts = opts;
637
+ }
638
+ sendEvent(eventType, payload) {
639
+ return __awaiter(this, void 0, void 0, function* () {
640
+ if (!navigator.sendBeacon) {
641
+ throw new Error(`navigator.sendBeacon is not supported in this browser. Consider adding a polyfill like "sendbeacon-polyfill".`);
642
+ }
643
+ const { baseUrl, preprocessRequest } = this.opts;
644
+ const parsedRequestData = this.encodeForEventType(eventType, payload);
645
+ const paramsFragments = yield this.getQueryParamsForEventType(eventType);
646
+ const defaultOptions = {
647
+ url: `${baseUrl}/analytics/${eventType}?${paramsFragments}`,
648
+ body: new Blob([parsedRequestData], {
649
+ type: 'application/x-www-form-urlencoded',
650
+ }),
651
+ };
652
+ const { url, body } = Object.assign(Object.assign({}, defaultOptions), (preprocessRequest ? yield preprocessRequest(defaultOptions, 'analyticsBeacon') : {}));
653
+ console.log(`Sending beacon for "${eventType}" with: `, JSON.stringify(payload));
654
+ navigator.sendBeacon(url, body);
655
+ return;
656
+ });
657
+ }
658
+ deleteHttpCookieVisitorId() {
659
+ return Promise.resolve();
660
+ }
661
+ encodeForEventType(eventType, payload) {
662
+ return this.isEventTypeLegacy(eventType)
663
+ ? this.encodeForLegacyType(eventType, payload)
664
+ : this.encodeForFormUrlEncoded(Object.assign({ access_token: this.opts.token }, payload));
665
+ }
666
+ getQueryParamsForEventType(eventType) {
667
+ return __awaiter(this, void 0, void 0, function* () {
668
+ const { token, visitorIdProvider } = this.opts;
669
+ const visitorId = yield visitorIdProvider.getCurrentVisitorId();
670
+ return [
671
+ token && this.isEventTypeLegacy(eventType) ? `access_token=${token}` : '',
672
+ visitorId ? `visitorId=${visitorId}` : '',
673
+ 'discardVisitInfo=true',
674
+ ]
675
+ .filter((p) => !!p)
676
+ .join('&');
677
+ });
678
+ }
679
+ isEventTypeLegacy(eventType) {
680
+ return [EventType.click, EventType.custom, EventType.search, EventType.view].indexOf(eventType) !== -1;
681
+ }
682
+ encodeForLegacyType(eventType, payload) {
683
+ return `${eventType}Event=${encodeURIComponent(JSON.stringify(payload))}`;
684
+ }
685
+ encodeForFormUrlEncoded(payload) {
686
+ return Object.keys(payload)
687
+ .filter((key) => !!payload[key])
688
+ .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(this.encodeValue(payload[key]))}`)
689
+ .join('&');
690
+ }
691
+ encodeValue(value) {
692
+ return typeof value === 'number' || typeof value === 'string' || typeof value === 'boolean'
693
+ ? value
694
+ : JSON.stringify(value);
695
+ }
696
+ }
697
+
698
+ class NoopAnalyticsClient {
699
+ sendEvent(_, __) {
700
+ return __awaiter(this, void 0, void 0, function* () {
701
+ return Promise.resolve();
702
+ });
703
+ }
704
+ deleteHttpCookieVisitorId() {
705
+ return __awaiter(this, void 0, void 0, function* () {
706
+ return Promise.resolve();
707
+ });
708
+ }
709
+ }
710
+
711
+ class BrowserRuntime {
712
+ constructor(clientOptions, getUnprocessedRequests) {
713
+ if (hasLocalStorage() && hasCookieStorage()) {
714
+ this.storage = new CookieAndLocalStorage();
715
+ }
716
+ else if (hasLocalStorage()) {
717
+ this.storage = localStorage;
718
+ }
719
+ else {
720
+ console.warn('BrowserRuntime detected no valid storage available.', this);
721
+ this.storage = new NullStorage();
722
+ }
723
+ this.client = new AnalyticsFetchClient(clientOptions);
724
+ this.beaconClient = new AnalyticsBeaconClient(clientOptions);
725
+ window.addEventListener('beforeunload', () => {
726
+ const requests = getUnprocessedRequests();
727
+ for (let { eventType, payload } of requests) {
728
+ this.beaconClient.sendEvent(eventType, payload);
729
+ }
730
+ });
731
+ }
732
+ }
733
+ class NodeJSRuntime {
734
+ constructor(clientOptions, storage) {
735
+ this.storage = storage || new NullStorage();
130
736
  this.client = new AnalyticsFetchClient(clientOptions);
131
737
  }
738
+ }
739
+ class NoopRuntime {
740
+ constructor() {
741
+ this.storage = new NullStorage();
742
+ this.client = new NoopAnalyticsClient();
743
+ }
744
+ }
745
+
746
+ const API_KEY_PREFIX = 'xx';
747
+ const isApiKey = (token) => (token === null || token === void 0 ? void 0 : token.startsWith(API_KEY_PREFIX)) || false;
748
+
749
+ const ReactNativeRuntimeWarning = `
750
+ We've detected you're using React Native but have not provided the corresponding runtime,
751
+ for an optimal experience please use the "coveo.analytics/react-native" subpackage.
752
+ Follow the Readme on how to set it up: https://github.com/coveo/coveo.analytics.js#using-react-native
753
+ `;
754
+ function isReactNative() {
755
+ return typeof navigator != 'undefined' && navigator.product == 'ReactNative';
756
+ }
757
+
758
+ const doNotTrackValues = ['1', 1, 'yes', true];
759
+ function doNotTrack() {
760
+ return (hasNavigator() &&
761
+ [
762
+ navigator.globalPrivacyControl,
763
+ navigator.doNotTrack,
764
+ navigator.msDoNotTrack,
765
+ window.doNotTrack,
766
+ ].some((value) => doNotTrackValues.indexOf(value) !== -1));
767
+ }
768
+
769
+ const Version = 'v15';
770
+ const Endpoints = {
771
+ default: 'https://analytics.cloud.coveo.com/rest/ua',
772
+ production: 'https://analytics.cloud.coveo.com/rest/ua',
773
+ hipaa: 'https://analyticshipaa.cloud.coveo.com/rest/ua',
774
+ };
775
+ function buildBaseUrl(endpoint = Endpoints.default, apiVersion = Version) {
776
+ const endpointIsCoveoProxy = endpoint.indexOf('.cloud.coveo.com') !== -1;
777
+ return `${endpoint}${endpointIsCoveoProxy ? '' : '/rest'}/${apiVersion}`;
778
+ }
779
+ class CoveoAnalyticsClient {
780
+ constructor(opts) {
781
+ if (!opts) {
782
+ throw new Error('You have to pass options to this constructor');
783
+ }
784
+ this.options = Object.assign(Object.assign({}, this.defaultOptions), opts);
785
+ this.visitorId = '';
786
+ this.bufferedRequests = [];
787
+ this.beforeSendHooks = [enhanceViewEvent, addDefaultValues].concat(this.options.beforeSendHooks);
788
+ this.afterSendHooks = this.options.afterSendHooks;
789
+ this.eventTypeMapping = {};
790
+ const clientsOptions = {
791
+ baseUrl: this.baseUrl,
792
+ token: this.options.token,
793
+ visitorIdProvider: this,
794
+ preprocessRequest: this.options.preprocessRequest,
795
+ };
796
+ this.runtime = this.options.runtimeEnvironment || this.initRuntime(clientsOptions);
797
+ if (doNotTrack()) {
798
+ this.clear();
799
+ this.runtime.storage = new NullStorage();
800
+ }
801
+ }
802
+ get defaultOptions() {
803
+ return {
804
+ endpoint: Endpoints.default,
805
+ token: '',
806
+ version: Version,
807
+ beforeSendHooks: [],
808
+ afterSendHooks: [],
809
+ };
810
+ }
811
+ initRuntime(clientsOptions) {
812
+ if (hasWindow() && hasDocument()) {
813
+ return new BrowserRuntime(clientsOptions, () => {
814
+ const copy = [...this.bufferedRequests];
815
+ this.bufferedRequests = [];
816
+ return copy;
817
+ });
818
+ }
819
+ else if (isReactNative()) {
820
+ console.warn(ReactNativeRuntimeWarning);
821
+ }
822
+ return new NodeJSRuntime(clientsOptions);
823
+ }
824
+ get storage() {
825
+ return this.runtime.storage;
826
+ }
827
+ determineVisitorId() {
828
+ return __awaiter(this, void 0, void 0, function* () {
829
+ try {
830
+ return (yield this.storage.getItem('visitorId')) || uuidv4();
831
+ }
832
+ catch (err) {
833
+ console.log('Could not get visitor ID from the current runtime environment storage. Using a random ID instead.', err);
834
+ return uuidv4();
835
+ }
836
+ });
837
+ }
838
+ getCurrentVisitorId() {
839
+ return __awaiter(this, void 0, void 0, function* () {
840
+ if (!this.visitorId) {
841
+ const id = yield this.determineVisitorId();
842
+ yield this.setCurrentVisitorId(id);
843
+ }
844
+ return this.visitorId;
845
+ });
846
+ }
847
+ setCurrentVisitorId(visitorId) {
848
+ return __awaiter(this, void 0, void 0, function* () {
849
+ this.visitorId = visitorId;
850
+ yield this.storage.setItem('visitorId', visitorId);
851
+ });
852
+ }
853
+ getParameters(eventType, ...payload) {
854
+ return __awaiter(this, void 0, void 0, function* () {
855
+ return yield this.resolveParameters(eventType, ...payload);
856
+ });
857
+ }
858
+ getPayload(eventType, ...payload) {
859
+ return __awaiter(this, void 0, void 0, function* () {
860
+ const parametersToSend = yield this.resolveParameters(eventType, ...payload);
861
+ return yield this.resolvePayloadForParameters(eventType, parametersToSend);
862
+ });
863
+ }
864
+ get currentVisitorId() {
865
+ const visitorId = this.visitorId || this.storage.getItem('visitorId');
866
+ if (typeof visitorId !== 'string') {
867
+ this.setCurrentVisitorId(uuidv4());
868
+ }
869
+ return this.visitorId;
870
+ }
871
+ set currentVisitorId(visitorId) {
872
+ this.visitorId = visitorId;
873
+ this.storage.setItem('visitorId', visitorId);
874
+ }
875
+ resolveParameters(eventType, ...payload) {
876
+ return __awaiter(this, void 0, void 0, function* () {
877
+ const { variableLengthArgumentsNames = [], addVisitorIdParameter = false, usesMeasurementProtocol = false, addClientIdParameter = false, } = this.eventTypeMapping[eventType] || {};
878
+ const processVariableArgumentNamesStep = (currentPayload) => variableLengthArgumentsNames.length > 0
879
+ ? this.parseVariableArgumentsPayload(variableLengthArgumentsNames, currentPayload)
880
+ : currentPayload[0];
881
+ const addVisitorIdStep = (currentPayload) => __awaiter(this, void 0, void 0, function* () {
882
+ return (Object.assign(Object.assign({}, currentPayload), { visitorId: addVisitorIdParameter ? yield this.getCurrentVisitorId() : '' }));
883
+ });
884
+ const addClientIdStep = (currentPayload) => __awaiter(this, void 0, void 0, function* () {
885
+ if (addClientIdParameter) {
886
+ return Object.assign(Object.assign({}, currentPayload), { clientId: yield this.getCurrentVisitorId() });
887
+ }
888
+ return currentPayload;
889
+ });
890
+ const setAnonymousUserStep = (currentPayload) => usesMeasurementProtocol ? this.ensureAnonymousUserWhenUsingApiKey(currentPayload) : currentPayload;
891
+ const processBeforeSendHooksStep = (currentPayload) => this.beforeSendHooks.reduce((promisePayload, current) => __awaiter(this, void 0, void 0, function* () {
892
+ const payload = yield promisePayload;
893
+ return yield current(eventType, payload);
894
+ }), currentPayload);
895
+ const parametersToSend = yield [
896
+ processVariableArgumentNamesStep,
897
+ addVisitorIdStep,
898
+ addClientIdStep,
899
+ setAnonymousUserStep,
900
+ processBeforeSendHooksStep,
901
+ ].reduce((payloadPromise, step) => __awaiter(this, void 0, void 0, function* () {
902
+ const payload = yield payloadPromise;
903
+ return yield step(payload);
904
+ }), Promise.resolve(payload));
905
+ return parametersToSend;
906
+ });
907
+ }
908
+ resolvePayloadForParameters(eventType, parameters) {
909
+ return __awaiter(this, void 0, void 0, function* () {
910
+ const { usesMeasurementProtocol = false } = this.eventTypeMapping[eventType] || {};
911
+ const cleanPayloadStep = (currentPayload) => this.removeEmptyPayloadValues(currentPayload, eventType);
912
+ const validateParams = (currentPayload) => this.validateParams(currentPayload);
913
+ const processMeasurementProtocolConversionStep = (currentPayload) => usesMeasurementProtocol ? convertKeysToMeasurementProtocol(currentPayload) : currentPayload;
914
+ const removeUnknownParameters = (currentPayload) => usesMeasurementProtocol ? this.removeUnknownParameters(currentPayload) : currentPayload;
915
+ const processCustomParameters = (currentPayload) => usesMeasurementProtocol ? this.processCustomParameters(currentPayload) : currentPayload;
916
+ const payloadToSend = yield [
917
+ cleanPayloadStep,
918
+ validateParams,
919
+ processMeasurementProtocolConversionStep,
920
+ removeUnknownParameters,
921
+ processCustomParameters,
922
+ ].reduce((payloadPromise, step) => __awaiter(this, void 0, void 0, function* () {
923
+ const payload = yield payloadPromise;
924
+ return yield step(payload);
925
+ }), Promise.resolve(parameters));
926
+ return payloadToSend;
927
+ });
928
+ }
929
+ sendEvent(eventType, ...payload) {
930
+ return __awaiter(this, void 0, void 0, function* () {
931
+ const { newEventType: eventTypeToSend = eventType } = this.eventTypeMapping[eventType] || {};
932
+ const parametersToSend = yield this.resolveParameters(eventType, ...payload);
933
+ const payloadToSend = yield this.resolvePayloadForParameters(eventType, parametersToSend);
934
+ this.bufferedRequests.push({
935
+ eventType: eventTypeToSend,
936
+ payload: payloadToSend,
937
+ });
938
+ yield Promise.all(this.afterSendHooks.map((hook) => hook(eventType, parametersToSend)));
939
+ yield this.deferExecution();
940
+ return yield this.sendFromBufferWithFetch();
941
+ });
942
+ }
943
+ deferExecution() {
944
+ return new Promise((resolve) => setTimeout(resolve, 0));
945
+ }
946
+ sendFromBufferWithFetch() {
947
+ return __awaiter(this, void 0, void 0, function* () {
948
+ const popped = this.bufferedRequests.shift();
949
+ if (popped) {
950
+ const { eventType, payload } = popped;
951
+ return this.runtime.client.sendEvent(eventType, payload);
952
+ }
953
+ });
954
+ }
955
+ clear() {
956
+ this.storage.removeItem('visitorId');
957
+ const store = new HistoryStore();
958
+ store.clear();
959
+ }
960
+ deleteHttpOnlyVisitorId() {
961
+ this.runtime.client.deleteHttpCookieVisitorId();
962
+ }
963
+ sendSearchEvent(request) {
964
+ return __awaiter(this, void 0, void 0, function* () {
965
+ return this.sendEvent(EventType.search, request);
966
+ });
967
+ }
968
+ sendClickEvent(request) {
969
+ return __awaiter(this, void 0, void 0, function* () {
970
+ return this.sendEvent(EventType.click, request);
971
+ });
972
+ }
973
+ sendCustomEvent(request) {
974
+ return __awaiter(this, void 0, void 0, function* () {
975
+ return this.sendEvent(EventType.custom, request);
976
+ });
977
+ }
978
+ sendViewEvent(request) {
979
+ return __awaiter(this, void 0, void 0, function* () {
980
+ return this.sendEvent(EventType.view, request);
981
+ });
982
+ }
983
+ getVisit() {
984
+ return __awaiter(this, void 0, void 0, function* () {
985
+ const response = yield fetch(`${this.baseUrl}/analytics/visit`);
986
+ const visit = (yield response.json());
987
+ this.visitorId = visit.visitorId;
988
+ return visit;
989
+ });
990
+ }
991
+ getHealth() {
992
+ return __awaiter(this, void 0, void 0, function* () {
993
+ const response = yield fetch(`${this.baseUrl}/analytics/monitoring/health`);
994
+ return (yield response.json());
995
+ });
996
+ }
997
+ registerBeforeSendEventHook(hook) {
998
+ this.beforeSendHooks.push(hook);
999
+ }
1000
+ registerAfterSendEventHook(hook) {
1001
+ this.afterSendHooks.push(hook);
1002
+ }
1003
+ addEventTypeMapping(eventType, eventConfig) {
1004
+ this.eventTypeMapping[eventType] = eventConfig;
1005
+ }
1006
+ parseVariableArgumentsPayload(fieldsOrder, payload) {
1007
+ const parsedArguments = {};
1008
+ for (let i = 0, length = payload.length; i < length; i++) {
1009
+ const currentArgument = payload[i];
1010
+ if (typeof currentArgument === 'string') {
1011
+ parsedArguments[fieldsOrder[i]] = currentArgument;
1012
+ }
1013
+ else if (typeof currentArgument === 'object') {
1014
+ return Object.assign(Object.assign({}, parsedArguments), currentArgument);
1015
+ }
1016
+ }
1017
+ return parsedArguments;
1018
+ }
1019
+ isKeyAllowedEmpty(evtType, key) {
1020
+ const keysThatCanBeEmpty = {
1021
+ [EventType.search]: ['queryText'],
1022
+ };
1023
+ const match = keysThatCanBeEmpty[evtType] || [];
1024
+ return match.indexOf(key) !== -1;
1025
+ }
1026
+ removeEmptyPayloadValues(payload, eventType) {
1027
+ const isNotEmptyValue = (value) => typeof value !== 'undefined' && value !== null && value !== '';
1028
+ return Object.keys(payload)
1029
+ .filter((key) => this.isKeyAllowedEmpty(eventType, key) || isNotEmptyValue(payload[key]))
1030
+ .reduce((newPayload, key) => (Object.assign(Object.assign({}, newPayload), { [key]: payload[key] })), {});
1031
+ }
1032
+ removeUnknownParameters(payload) {
1033
+ const newPayload = Object.keys(payload)
1034
+ .filter((key) => {
1035
+ if (isMeasurementProtocolKey(key)) {
1036
+ return true;
1037
+ }
1038
+ else {
1039
+ console.log(key, 'is not processed by coveoua');
1040
+ }
1041
+ })
1042
+ .reduce((newPayload, key) => (Object.assign(Object.assign({}, newPayload), { [key]: payload[key] })), {});
1043
+ return newPayload;
1044
+ }
1045
+ processCustomParameters(payload) {
1046
+ const { custom } = payload, rest = __rest(payload, ["custom"]);
1047
+ const lowercasedCustom = this.lowercaseKeys(custom);
1048
+ const newPayload = convertCustomMeasurementProtocolKeys(rest);
1049
+ return Object.assign(Object.assign({}, lowercasedCustom), newPayload);
1050
+ }
1051
+ lowercaseKeys(custom) {
1052
+ const keys = Object.keys(custom || {});
1053
+ return keys.reduce((all, key) => (Object.assign(Object.assign({}, all), { [key.toLowerCase()]: custom[key] })), {});
1054
+ }
1055
+ validateParams(payload) {
1056
+ const { anonymizeIp } = payload, rest = __rest(payload, ["anonymizeIp"]);
1057
+ if (anonymizeIp !== undefined) {
1058
+ if (['0', 'false', 'undefined', 'null', '{}', '[]', ''].indexOf(`${anonymizeIp}`.toLowerCase()) == -1) {
1059
+ rest['anonymizeIp'] = 1;
1060
+ }
1061
+ }
1062
+ return rest;
1063
+ }
1064
+ ensureAnonymousUserWhenUsingApiKey(payload) {
1065
+ const { userId } = payload, rest = __rest(payload, ["userId"]);
1066
+ if (isApiKey(this.options.token) && !userId) {
1067
+ rest['userId'] = 'anonymous';
1068
+ return rest;
1069
+ }
1070
+ else {
1071
+ return payload;
1072
+ }
1073
+ }
1074
+ get baseUrl() {
1075
+ return buildBaseUrl(this.options.endpoint, this.options.version);
1076
+ }
1077
+ }
1078
+
1079
+ class ReactNativeRuntime {
1080
+ constructor(options) {
1081
+ var _a;
1082
+ const visitorIdKey = (_a = options.visitorIdKey) !== null && _a !== void 0 ? _a : 'visitorId';
1083
+ this.storage = options.storage;
1084
+ this.client = new AnalyticsFetchClient({
1085
+ preprocessRequest: options.preprocessRequest,
1086
+ token: options.token,
1087
+ baseUrl: buildBaseUrl(options.endpoint, options.version),
1088
+ visitorIdProvider: {
1089
+ getCurrentVisitorId: () => __awaiter(this, void 0, void 0, function* () { return (yield this.storage.getItem(visitorIdKey)) || uuidv4(); }),
1090
+ setCurrentVisitorId: (visitorId) => this.storage.setItem(visitorIdKey, visitorId),
1091
+ },
1092
+ });
1093
+ }
1094
+ }
1095
+
1096
+ var InsightEvents;
1097
+ (function (InsightEvents) {
1098
+ InsightEvents["contextChanged"] = "contextChanged";
1099
+ InsightEvents["expandToFullUI"] = "expandToFullUI";
1100
+ })(InsightEvents || (InsightEvents = {}));
1101
+
1102
+ var SearchPageEvents;
1103
+ (function (SearchPageEvents) {
1104
+ SearchPageEvents["interfaceLoad"] = "interfaceLoad";
1105
+ SearchPageEvents["interfaceChange"] = "interfaceChange";
1106
+ SearchPageEvents["didyoumeanAutomatic"] = "didyoumeanAutomatic";
1107
+ SearchPageEvents["didyoumeanClick"] = "didyoumeanClick";
1108
+ SearchPageEvents["resultsSort"] = "resultsSort";
1109
+ SearchPageEvents["searchboxSubmit"] = "searchboxSubmit";
1110
+ SearchPageEvents["searchboxClear"] = "searchboxClear";
1111
+ SearchPageEvents["searchboxAsYouType"] = "searchboxAsYouType";
1112
+ SearchPageEvents["breadcrumbFacet"] = "breadcrumbFacet";
1113
+ SearchPageEvents["breadcrumbResetAll"] = "breadcrumbResetAll";
1114
+ SearchPageEvents["documentQuickview"] = "documentQuickview";
1115
+ SearchPageEvents["documentOpen"] = "documentOpen";
1116
+ SearchPageEvents["omniboxAnalytics"] = "omniboxAnalytics";
1117
+ SearchPageEvents["omniboxFromLink"] = "omniboxFromLink";
1118
+ SearchPageEvents["searchFromLink"] = "searchFromLink";
1119
+ SearchPageEvents["triggerNotify"] = "notify";
1120
+ SearchPageEvents["triggerExecute"] = "execute";
1121
+ SearchPageEvents["triggerQuery"] = "query";
1122
+ SearchPageEvents["undoTriggerQuery"] = "undoQuery";
1123
+ SearchPageEvents["triggerRedirect"] = "redirect";
1124
+ SearchPageEvents["pagerResize"] = "pagerResize";
1125
+ SearchPageEvents["pagerNumber"] = "pagerNumber";
1126
+ SearchPageEvents["pagerNext"] = "pagerNext";
1127
+ SearchPageEvents["pagerPrevious"] = "pagerPrevious";
1128
+ SearchPageEvents["pagerScrolling"] = "pagerScrolling";
1129
+ SearchPageEvents["staticFilterClearAll"] = "staticFilterClearAll";
1130
+ SearchPageEvents["staticFilterSelect"] = "staticFilterSelect";
1131
+ SearchPageEvents["staticFilterDeselect"] = "staticFilterDeselect";
1132
+ SearchPageEvents["facetClearAll"] = "facetClearAll";
1133
+ SearchPageEvents["facetSearch"] = "facetSearch";
1134
+ SearchPageEvents["facetSelect"] = "facetSelect";
1135
+ SearchPageEvents["facetSelectAll"] = "facetSelectAll";
1136
+ SearchPageEvents["facetDeselect"] = "facetDeselect";
1137
+ SearchPageEvents["facetExclude"] = "facetExclude";
1138
+ SearchPageEvents["facetUnexclude"] = "facetUnexclude";
1139
+ SearchPageEvents["facetUpdateSort"] = "facetUpdateSort";
1140
+ SearchPageEvents["facetShowMore"] = "showMoreFacetResults";
1141
+ SearchPageEvents["facetShowLess"] = "showLessFacetResults";
1142
+ SearchPageEvents["queryError"] = "query";
1143
+ SearchPageEvents["queryErrorBack"] = "errorBack";
1144
+ SearchPageEvents["queryErrorClear"] = "errorClearQuery";
1145
+ SearchPageEvents["queryErrorRetry"] = "errorRetry";
1146
+ SearchPageEvents["recommendation"] = "recommendation";
1147
+ SearchPageEvents["recommendationInterfaceLoad"] = "recommendationInterfaceLoad";
1148
+ SearchPageEvents["recommendationOpen"] = "recommendationOpen";
1149
+ SearchPageEvents["likeSmartSnippet"] = "likeSmartSnippet";
1150
+ SearchPageEvents["dislikeSmartSnippet"] = "dislikeSmartSnippet";
1151
+ SearchPageEvents["expandSmartSnippet"] = "expandSmartSnippet";
1152
+ SearchPageEvents["collapseSmartSnippet"] = "collapseSmartSnippet";
1153
+ SearchPageEvents["openSmartSnippetFeedbackModal"] = "openSmartSnippetFeedbackModal";
1154
+ SearchPageEvents["closeSmartSnippetFeedbackModal"] = "closeSmartSnippetFeedbackModal";
1155
+ SearchPageEvents["sendSmartSnippetReason"] = "sendSmartSnippetReason";
1156
+ SearchPageEvents["expandSmartSnippetSuggestion"] = "expandSmartSnippetSuggestion";
1157
+ SearchPageEvents["collapseSmartSnippetSuggestion"] = "collapseSmartSnippetSuggestion";
1158
+ SearchPageEvents["showMoreSmartSnippetSuggestion"] = "showMoreSmartSnippetSuggestion";
1159
+ SearchPageEvents["showLessSmartSnippetSuggestion"] = "showLessSmartSnippetSuggestion";
1160
+ SearchPageEvents["openSmartSnippetSource"] = "openSmartSnippetSource";
1161
+ SearchPageEvents["openSmartSnippetSuggestionSource"] = "openSmartSnippetSuggestionSource";
1162
+ SearchPageEvents["openSmartSnippetInlineLink"] = "openSmartSnippetInlineLink";
1163
+ SearchPageEvents["openSmartSnippetSuggestionInlineLink"] = "openSmartSnippetSuggestionInlineLink";
1164
+ SearchPageEvents["recentQueryClick"] = "recentQueriesClick";
1165
+ SearchPageEvents["clearRecentQueries"] = "clearRecentQueries";
1166
+ SearchPageEvents["recentResultClick"] = "recentResultClick";
1167
+ SearchPageEvents["clearRecentResults"] = "clearRecentResults";
1168
+ SearchPageEvents["noResultsBack"] = "noResultsBack";
1169
+ SearchPageEvents["showMoreFoldedResults"] = "showMoreFoldedResults";
1170
+ SearchPageEvents["showLessFoldedResults"] = "showLessFoldedResults";
1171
+ })(SearchPageEvents || (SearchPageEvents = {}));
1172
+ const CustomEventsTypes = {
1173
+ [SearchPageEvents.triggerNotify]: 'queryPipelineTriggers',
1174
+ [SearchPageEvents.triggerExecute]: 'queryPipelineTriggers',
1175
+ [SearchPageEvents.triggerQuery]: 'queryPipelineTriggers',
1176
+ [SearchPageEvents.triggerRedirect]: 'queryPipelineTriggers',
1177
+ [SearchPageEvents.queryError]: 'errors',
1178
+ [SearchPageEvents.queryErrorBack]: 'errors',
1179
+ [SearchPageEvents.queryErrorClear]: 'errors',
1180
+ [SearchPageEvents.queryErrorRetry]: 'errors',
1181
+ [SearchPageEvents.pagerNext]: 'getMoreResults',
1182
+ [SearchPageEvents.pagerPrevious]: 'getMoreResults',
1183
+ [SearchPageEvents.pagerNumber]: 'getMoreResults',
1184
+ [SearchPageEvents.pagerResize]: 'getMoreResults',
1185
+ [SearchPageEvents.pagerScrolling]: 'getMoreResults',
1186
+ [SearchPageEvents.facetSearch]: 'facet',
1187
+ [SearchPageEvents.facetShowLess]: 'facet',
1188
+ [SearchPageEvents.facetShowMore]: 'facet',
1189
+ [SearchPageEvents.recommendation]: 'recommendation',
1190
+ [SearchPageEvents.likeSmartSnippet]: 'smartSnippet',
1191
+ [SearchPageEvents.dislikeSmartSnippet]: 'smartSnippet',
1192
+ [SearchPageEvents.expandSmartSnippet]: 'smartSnippet',
1193
+ [SearchPageEvents.collapseSmartSnippet]: 'smartSnippet',
1194
+ [SearchPageEvents.openSmartSnippetFeedbackModal]: 'smartSnippet',
1195
+ [SearchPageEvents.closeSmartSnippetFeedbackModal]: 'smartSnippet',
1196
+ [SearchPageEvents.sendSmartSnippetReason]: 'smartSnippet',
1197
+ [SearchPageEvents.expandSmartSnippetSuggestion]: 'smartSnippetSuggestions',
1198
+ [SearchPageEvents.collapseSmartSnippetSuggestion]: 'smartSnippetSuggestions',
1199
+ [SearchPageEvents.showMoreSmartSnippetSuggestion]: 'smartSnippetSuggestions',
1200
+ [SearchPageEvents.showLessSmartSnippetSuggestion]: 'smartSnippetSuggestions',
1201
+ [SearchPageEvents.clearRecentQueries]: 'recentQueries',
1202
+ [SearchPageEvents.recentResultClick]: 'recentlyClickedDocuments',
1203
+ [SearchPageEvents.clearRecentResults]: 'recentlyClickedDocuments',
1204
+ [SearchPageEvents.showLessFoldedResults]: 'folding',
1205
+ [InsightEvents.expandToFullUI]: 'interface',
1206
+ };
1207
+
1208
+ class NoopAnalytics {
1209
+ constructor() {
1210
+ this.runtime = new NoopRuntime();
1211
+ this.currentVisitorId = '';
1212
+ }
1213
+ getPayload() {
1214
+ return Promise.resolve();
1215
+ }
1216
+ getParameters() {
1217
+ return Promise.resolve();
1218
+ }
1219
+ sendEvent() {
1220
+ return Promise.resolve();
1221
+ }
1222
+ sendSearchEvent() {
1223
+ return Promise.resolve();
1224
+ }
1225
+ sendClickEvent() {
1226
+ return Promise.resolve();
1227
+ }
1228
+ sendCustomEvent() {
1229
+ return Promise.resolve();
1230
+ }
1231
+ sendViewEvent() {
1232
+ return Promise.resolve();
1233
+ }
1234
+ getVisit() {
1235
+ return Promise.resolve({ id: '', visitorId: '' });
1236
+ }
1237
+ getHealth() {
1238
+ return Promise.resolve({ status: '' });
1239
+ }
1240
+ registerBeforeSendEventHook() { }
1241
+ registerAfterSendEventHook() { }
1242
+ addEventTypeMapping() { }
1243
+ }
1244
+
1245
+ function filterConsecutiveRepeatedValues(rawData) {
1246
+ let prev = '';
1247
+ return rawData.filter((value) => {
1248
+ const isDifferent = value !== prev;
1249
+ prev = value;
1250
+ return isDifferent;
1251
+ });
1252
+ }
1253
+ function removeSemicolons(rawData) {
1254
+ return rawData.map((value) => {
1255
+ return value.replace(/;/g, '');
1256
+ });
1257
+ }
1258
+ function getDataString(data) {
1259
+ const ANALYTICS_LENGTH_LIMIT = 256;
1260
+ const formattedData = data.join(';');
1261
+ if (formattedData.length <= ANALYTICS_LENGTH_LIMIT) {
1262
+ return formattedData;
1263
+ }
1264
+ return getDataString(data.slice(1));
1265
+ }
1266
+ const formatArrayForCoveoCustomData = (rawData) => {
1267
+ const dataWithoutSemicolons = removeSemicolons(rawData);
1268
+ const dataWithoutRepeatedValues = filterConsecutiveRepeatedValues(dataWithoutSemicolons);
1269
+ return getDataString(dataWithoutRepeatedValues);
1270
+ };
1271
+
1272
+ function formatOmniboxMetadata(meta) {
1273
+ const partialQueries = typeof meta.partialQueries === 'string'
1274
+ ? meta.partialQueries
1275
+ : formatArrayForCoveoCustomData(meta.partialQueries);
1276
+ const suggestions = typeof meta.suggestions === 'string' ? meta.suggestions : formatArrayForCoveoCustomData(meta.suggestions);
1277
+ return Object.assign(Object.assign({}, meta), { partialQueries,
1278
+ suggestions });
1279
+ }
1280
+
1281
+ class CoveoSearchPageClient {
1282
+ constructor(opts, provider) {
1283
+ this.opts = opts;
1284
+ this.provider = provider;
1285
+ const shouldDisableAnalytics = opts.enableAnalytics === false || doNotTrack();
1286
+ this.coveoAnalyticsClient = shouldDisableAnalytics ? new NoopAnalytics() : new CoveoAnalyticsClient(opts);
1287
+ }
1288
+ disable() {
1289
+ if (this.coveoAnalyticsClient instanceof CoveoAnalyticsClient) {
1290
+ this.coveoAnalyticsClient.clear();
1291
+ }
1292
+ this.coveoAnalyticsClient = new NoopAnalytics();
1293
+ }
1294
+ enable() {
1295
+ this.coveoAnalyticsClient = new CoveoAnalyticsClient(this.opts);
1296
+ }
1297
+ makeInterfaceLoad() {
1298
+ return this.makeSearchEvent(SearchPageEvents.interfaceLoad);
1299
+ }
1300
+ logInterfaceLoad() {
1301
+ return this.makeInterfaceLoad().log();
1302
+ }
1303
+ makeRecommendationInterfaceLoad() {
1304
+ return this.makeSearchEvent(SearchPageEvents.recommendationInterfaceLoad);
1305
+ }
1306
+ logRecommendationInterfaceLoad() {
1307
+ return this.makeRecommendationInterfaceLoad().log();
1308
+ }
1309
+ makeRecommendation() {
1310
+ return this.makeCustomEvent(SearchPageEvents.recommendation);
1311
+ }
1312
+ logRecommendation() {
1313
+ return this.makeRecommendation().log();
1314
+ }
1315
+ makeRecommendationOpen(info, identifier) {
1316
+ return this.makeClickEvent(SearchPageEvents.recommendationOpen, info, identifier);
1317
+ }
1318
+ logRecommendationOpen(info, identifier) {
1319
+ return this.makeRecommendationOpen(info, identifier).log();
1320
+ }
1321
+ makeStaticFilterClearAll(meta) {
1322
+ return this.makeSearchEvent(SearchPageEvents.staticFilterClearAll, meta);
1323
+ }
1324
+ logStaticFilterClearAll(meta) {
1325
+ return this.makeStaticFilterClearAll(meta).log();
1326
+ }
1327
+ makeStaticFilterSelect(meta) {
1328
+ return this.makeSearchEvent(SearchPageEvents.staticFilterSelect, meta);
1329
+ }
1330
+ logStaticFilterSelect(meta) {
1331
+ return this.makeStaticFilterSelect(meta).log();
1332
+ }
1333
+ makeStaticFilterDeselect(meta) {
1334
+ return this.makeSearchEvent(SearchPageEvents.staticFilterDeselect, meta);
1335
+ }
1336
+ logStaticFilterDeselect(meta) {
1337
+ return this.makeStaticFilterDeselect(meta).log();
1338
+ }
1339
+ makeFetchMoreResults() {
1340
+ return this.makeCustomEvent(SearchPageEvents.pagerScrolling, { type: 'getMoreResults' });
1341
+ }
1342
+ logFetchMoreResults() {
1343
+ return this.makeFetchMoreResults().log();
1344
+ }
1345
+ makeInterfaceChange(metadata) {
1346
+ return this.makeSearchEvent(SearchPageEvents.interfaceChange, metadata);
1347
+ }
1348
+ logInterfaceChange(metadata) {
1349
+ return this.makeInterfaceChange(metadata).log();
1350
+ }
1351
+ makeDidYouMeanAutomatic() {
1352
+ return this.makeSearchEvent(SearchPageEvents.didyoumeanAutomatic);
1353
+ }
1354
+ logDidYouMeanAutomatic() {
1355
+ return this.makeDidYouMeanAutomatic().log();
1356
+ }
1357
+ makeDidYouMeanClick() {
1358
+ return this.makeSearchEvent(SearchPageEvents.didyoumeanClick);
1359
+ }
1360
+ logDidYouMeanClick() {
1361
+ return this.makeDidYouMeanClick().log();
1362
+ }
1363
+ makeResultsSort(metadata) {
1364
+ return this.makeSearchEvent(SearchPageEvents.resultsSort, metadata);
1365
+ }
1366
+ logResultsSort(metadata) {
1367
+ return this.makeResultsSort(metadata).log();
1368
+ }
1369
+ makeSearchboxSubmit() {
1370
+ return this.makeSearchEvent(SearchPageEvents.searchboxSubmit);
1371
+ }
1372
+ logSearchboxSubmit() {
1373
+ return this.makeSearchboxSubmit().log();
1374
+ }
1375
+ makeSearchboxClear() {
1376
+ return this.makeSearchEvent(SearchPageEvents.searchboxClear);
1377
+ }
1378
+ logSearchboxClear() {
1379
+ return this.makeSearchboxClear().log();
1380
+ }
1381
+ makeSearchboxAsYouType() {
1382
+ return this.makeSearchEvent(SearchPageEvents.searchboxAsYouType);
1383
+ }
1384
+ logSearchboxAsYouType() {
1385
+ return this.makeSearchboxAsYouType().log();
1386
+ }
1387
+ makeBreadcrumbFacet(metadata) {
1388
+ return this.makeSearchEvent(SearchPageEvents.breadcrumbFacet, metadata);
1389
+ }
1390
+ logBreadcrumbFacet(metadata) {
1391
+ return this.makeBreadcrumbFacet(metadata).log();
1392
+ }
1393
+ makeBreadcrumbResetAll() {
1394
+ return this.makeSearchEvent(SearchPageEvents.breadcrumbResetAll);
1395
+ }
1396
+ logBreadcrumbResetAll() {
1397
+ return this.makeBreadcrumbResetAll().log();
1398
+ }
1399
+ makeDocumentQuickview(info, identifier) {
1400
+ return this.makeClickEvent(SearchPageEvents.documentQuickview, info, identifier);
1401
+ }
1402
+ logDocumentQuickview(info, identifier) {
1403
+ return this.makeDocumentQuickview(info, identifier).log();
1404
+ }
1405
+ makeDocumentOpen(info, identifier) {
1406
+ return this.makeClickEvent(SearchPageEvents.documentOpen, info, identifier);
1407
+ }
1408
+ logDocumentOpen(info, identifier) {
1409
+ return this.makeDocumentOpen(info, identifier).log();
1410
+ }
1411
+ makeOmniboxAnalytics(meta) {
1412
+ return this.makeSearchEvent(SearchPageEvents.omniboxAnalytics, formatOmniboxMetadata(meta));
1413
+ }
1414
+ logOmniboxAnalytics(meta) {
1415
+ return this.makeOmniboxAnalytics(meta).log();
1416
+ }
1417
+ makeOmniboxFromLink(meta) {
1418
+ return this.makeSearchEvent(SearchPageEvents.omniboxFromLink, formatOmniboxMetadata(meta));
1419
+ }
1420
+ logOmniboxFromLink(meta) {
1421
+ return this.makeOmniboxFromLink(meta).log();
1422
+ }
1423
+ makeSearchFromLink() {
1424
+ return this.makeSearchEvent(SearchPageEvents.searchFromLink);
1425
+ }
1426
+ logSearchFromLink() {
1427
+ return this.makeSearchFromLink().log();
1428
+ }
1429
+ makeTriggerNotify(meta) {
1430
+ return this.makeCustomEvent(SearchPageEvents.triggerNotify, meta);
1431
+ }
1432
+ logTriggerNotify(meta) {
1433
+ return this.makeTriggerNotify(meta).log();
1434
+ }
1435
+ makeTriggerExecute(meta) {
1436
+ return this.makeCustomEvent(SearchPageEvents.triggerExecute, meta);
1437
+ }
1438
+ logTriggerExecute(meta) {
1439
+ return this.makeTriggerExecute(meta).log();
1440
+ }
1441
+ makeTriggerQuery() {
1442
+ return this.makeCustomEvent(SearchPageEvents.triggerQuery, { query: this.provider.getSearchEventRequestPayload().queryText }, 'queryPipelineTriggers');
1443
+ }
1444
+ logTriggerQuery() {
1445
+ return this.makeTriggerQuery().log();
1446
+ }
1447
+ makeUndoTriggerQuery(meta) {
1448
+ return this.makeSearchEvent(SearchPageEvents.undoTriggerQuery, meta);
1449
+ }
1450
+ logUndoTriggerQuery(meta) {
1451
+ return this.makeUndoTriggerQuery(meta).log();
1452
+ }
1453
+ makeTriggerRedirect(meta) {
1454
+ return this.makeCustomEvent(SearchPageEvents.triggerRedirect, Object.assign(Object.assign({}, meta), { query: this.provider.getSearchEventRequestPayload().queryText }));
1455
+ }
1456
+ logTriggerRedirect(meta) {
1457
+ return this.makeTriggerRedirect(meta).log();
1458
+ }
1459
+ makePagerResize(meta) {
1460
+ return this.makeCustomEvent(SearchPageEvents.pagerResize, meta);
1461
+ }
1462
+ logPagerResize(meta) {
1463
+ return this.makePagerResize(meta).log();
1464
+ }
1465
+ makePagerNumber(meta) {
1466
+ return this.makeCustomEvent(SearchPageEvents.pagerNumber, meta);
1467
+ }
1468
+ logPagerNumber(meta) {
1469
+ return this.makePagerNumber(meta).log();
1470
+ }
1471
+ makePagerNext(meta) {
1472
+ return this.makeCustomEvent(SearchPageEvents.pagerNext, meta);
1473
+ }
1474
+ logPagerNext(meta) {
1475
+ return this.makePagerNext(meta).log();
1476
+ }
1477
+ makePagerPrevious(meta) {
1478
+ return this.makeCustomEvent(SearchPageEvents.pagerPrevious, meta);
1479
+ }
1480
+ logPagerPrevious(meta) {
1481
+ return this.makePagerPrevious(meta).log();
1482
+ }
1483
+ makePagerScrolling() {
1484
+ return this.makeCustomEvent(SearchPageEvents.pagerScrolling);
1485
+ }
1486
+ logPagerScrolling() {
1487
+ return this.makePagerScrolling().log();
1488
+ }
1489
+ makeFacetClearAll(meta) {
1490
+ return this.makeSearchEvent(SearchPageEvents.facetClearAll, meta);
1491
+ }
1492
+ logFacetClearAll(meta) {
1493
+ return this.makeFacetClearAll(meta).log();
1494
+ }
1495
+ makeFacetSearch(meta) {
1496
+ return this.makeSearchEvent(SearchPageEvents.facetSearch, meta);
1497
+ }
1498
+ logFacetSearch(meta) {
1499
+ return this.makeFacetSearch(meta).log();
1500
+ }
1501
+ makeFacetSelect(meta) {
1502
+ return this.makeSearchEvent(SearchPageEvents.facetSelect, meta);
1503
+ }
1504
+ logFacetSelect(meta) {
1505
+ return this.makeFacetSelect(meta).log();
1506
+ }
1507
+ makeFacetDeselect(meta) {
1508
+ return this.makeSearchEvent(SearchPageEvents.facetDeselect, meta);
1509
+ }
1510
+ logFacetDeselect(meta) {
1511
+ return this.makeFacetDeselect(meta).log();
1512
+ }
1513
+ makeFacetExclude(meta) {
1514
+ return this.makeSearchEvent(SearchPageEvents.facetExclude, meta);
1515
+ }
1516
+ logFacetExclude(meta) {
1517
+ return this.makeFacetExclude(meta).log();
1518
+ }
1519
+ makeFacetUnexclude(meta) {
1520
+ return this.makeSearchEvent(SearchPageEvents.facetUnexclude, meta);
1521
+ }
1522
+ logFacetUnexclude(meta) {
1523
+ return this.makeFacetUnexclude(meta).log();
1524
+ }
1525
+ makeFacetSelectAll(meta) {
1526
+ return this.makeSearchEvent(SearchPageEvents.facetSelectAll, meta);
1527
+ }
1528
+ logFacetSelectAll(meta) {
1529
+ return this.makeFacetSelectAll(meta).log();
1530
+ }
1531
+ makeFacetUpdateSort(meta) {
1532
+ return this.makeSearchEvent(SearchPageEvents.facetUpdateSort, meta);
1533
+ }
1534
+ logFacetUpdateSort(meta) {
1535
+ return this.makeFacetUpdateSort(meta).log();
1536
+ }
1537
+ makeFacetShowMore(meta) {
1538
+ return this.makeCustomEvent(SearchPageEvents.facetShowMore, meta);
1539
+ }
1540
+ logFacetShowMore(meta) {
1541
+ return this.makeFacetShowMore(meta).log();
1542
+ }
1543
+ makeFacetShowLess(meta) {
1544
+ return this.makeCustomEvent(SearchPageEvents.facetShowLess, meta);
1545
+ }
1546
+ logFacetShowLess(meta) {
1547
+ return this.makeFacetShowLess(meta).log();
1548
+ }
1549
+ makeQueryError(meta) {
1550
+ return this.makeCustomEvent(SearchPageEvents.queryError, meta);
1551
+ }
1552
+ logQueryError(meta) {
1553
+ return this.makeQueryError(meta).log();
1554
+ }
1555
+ makeQueryErrorBack() {
1556
+ return {
1557
+ description: this.makeDescription(SearchPageEvents.queryErrorBack),
1558
+ log: () => __awaiter(this, void 0, void 0, function* () {
1559
+ yield this.logCustomEvent(SearchPageEvents.queryErrorBack);
1560
+ return this.logSearchEvent(SearchPageEvents.queryErrorBack);
1561
+ }),
1562
+ };
1563
+ }
1564
+ logQueryErrorBack() {
1565
+ return this.makeQueryErrorBack().log();
1566
+ }
1567
+ makeQueryErrorRetry() {
1568
+ return {
1569
+ description: this.makeDescription(SearchPageEvents.queryErrorRetry),
1570
+ log: () => __awaiter(this, void 0, void 0, function* () {
1571
+ yield this.logCustomEvent(SearchPageEvents.queryErrorRetry);
1572
+ return this.logSearchEvent(SearchPageEvents.queryErrorRetry);
1573
+ }),
1574
+ };
1575
+ }
1576
+ logQueryErrorRetry() {
1577
+ return this.makeQueryErrorRetry().log();
1578
+ }
1579
+ makeQueryErrorClear() {
1580
+ return {
1581
+ description: this.makeDescription(SearchPageEvents.queryErrorClear),
1582
+ log: () => __awaiter(this, void 0, void 0, function* () {
1583
+ yield this.logCustomEvent(SearchPageEvents.queryErrorClear);
1584
+ return this.logSearchEvent(SearchPageEvents.queryErrorClear);
1585
+ }),
1586
+ };
1587
+ }
1588
+ logQueryErrorClear() {
1589
+ return this.makeQueryErrorClear().log();
1590
+ }
1591
+ makeLikeSmartSnippet() {
1592
+ return this.makeCustomEvent(SearchPageEvents.likeSmartSnippet);
1593
+ }
1594
+ logLikeSmartSnippet() {
1595
+ return this.makeLikeSmartSnippet().log();
1596
+ }
1597
+ makeDislikeSmartSnippet() {
1598
+ return this.makeCustomEvent(SearchPageEvents.dislikeSmartSnippet);
1599
+ }
1600
+ logDislikeSmartSnippet() {
1601
+ return this.makeDislikeSmartSnippet().log();
1602
+ }
1603
+ makeExpandSmartSnippet() {
1604
+ return this.makeCustomEvent(SearchPageEvents.expandSmartSnippet);
1605
+ }
1606
+ logExpandSmartSnippet() {
1607
+ return this.makeExpandSmartSnippet().log();
1608
+ }
1609
+ makeCollapseSmartSnippet() {
1610
+ return this.makeCustomEvent(SearchPageEvents.collapseSmartSnippet);
1611
+ }
1612
+ logCollapseSmartSnippet() {
1613
+ return this.makeCollapseSmartSnippet().log();
1614
+ }
1615
+ makeOpenSmartSnippetFeedbackModal() {
1616
+ return this.makeCustomEvent(SearchPageEvents.openSmartSnippetFeedbackModal);
1617
+ }
1618
+ logOpenSmartSnippetFeedbackModal() {
1619
+ return this.makeOpenSmartSnippetFeedbackModal().log();
1620
+ }
1621
+ makeCloseSmartSnippetFeedbackModal() {
1622
+ return this.makeCustomEvent(SearchPageEvents.closeSmartSnippetFeedbackModal);
1623
+ }
1624
+ logCloseSmartSnippetFeedbackModal() {
1625
+ return this.makeCloseSmartSnippetFeedbackModal().log();
1626
+ }
1627
+ makeSmartSnippetFeedbackReason(reason, details) {
1628
+ return this.makeCustomEvent(SearchPageEvents.sendSmartSnippetReason, { reason, details });
1629
+ }
1630
+ logSmartSnippetFeedbackReason(reason, details) {
1631
+ return this.makeSmartSnippetFeedbackReason(reason, details).log();
1632
+ }
1633
+ makeExpandSmartSnippetSuggestion(snippet) {
1634
+ return this.makeCustomEvent(SearchPageEvents.expandSmartSnippetSuggestion, 'documentId' in snippet ? snippet : { documentId: snippet });
1635
+ }
1636
+ logExpandSmartSnippetSuggestion(snippet) {
1637
+ return this.makeExpandSmartSnippetSuggestion(snippet).log();
1638
+ }
1639
+ makeCollapseSmartSnippetSuggestion(snippet) {
1640
+ return this.makeCustomEvent(SearchPageEvents.collapseSmartSnippetSuggestion, 'documentId' in snippet ? snippet : { documentId: snippet });
1641
+ }
1642
+ logCollapseSmartSnippetSuggestion(snippet) {
1643
+ return this.makeCollapseSmartSnippetSuggestion(snippet).log();
1644
+ }
1645
+ makeShowMoreSmartSnippetSuggestion(snippet) {
1646
+ return this.makeCustomEvent(SearchPageEvents.showMoreSmartSnippetSuggestion, snippet);
1647
+ }
1648
+ logShowMoreSmartSnippetSuggestion(snippet) {
1649
+ return this.makeShowMoreSmartSnippetSuggestion(snippet).log();
1650
+ }
1651
+ makeShowLessSmartSnippetSuggestion(snippet) {
1652
+ return this.makeCustomEvent(SearchPageEvents.showLessSmartSnippetSuggestion, snippet);
1653
+ }
1654
+ logShowLessSmartSnippetSuggestion(snippet) {
1655
+ return this.makeShowLessSmartSnippetSuggestion(snippet).log();
1656
+ }
1657
+ makeOpenSmartSnippetSource(info, identifier) {
1658
+ return this.makeClickEvent(SearchPageEvents.openSmartSnippetSource, info, identifier);
1659
+ }
1660
+ logOpenSmartSnippetSource(info, identifier) {
1661
+ return this.makeOpenSmartSnippetSource(info, identifier).log();
1662
+ }
1663
+ makeOpenSmartSnippetSuggestionSource(info, snippet) {
1664
+ return this.makeClickEvent(SearchPageEvents.openSmartSnippetSuggestionSource, info, { contentIDKey: snippet.documentId.contentIdKey, contentIDValue: snippet.documentId.contentIdValue }, snippet);
1665
+ }
1666
+ logOpenSmartSnippetSuggestionSource(info, snippet) {
1667
+ return this.makeOpenSmartSnippetSuggestionSource(info, snippet).log();
1668
+ }
1669
+ makeOpenSmartSnippetInlineLink(info, identifierAndLink) {
1670
+ return this.makeClickEvent(SearchPageEvents.openSmartSnippetInlineLink, info, { contentIDKey: identifierAndLink.contentIDKey, contentIDValue: identifierAndLink.contentIDValue }, identifierAndLink);
1671
+ }
1672
+ logOpenSmartSnippetInlineLink(info, identifierAndLink) {
1673
+ return this.makeOpenSmartSnippetInlineLink(info, identifierAndLink).log();
1674
+ }
1675
+ makeOpenSmartSnippetSuggestionInlineLink(info, snippetAndLink) {
1676
+ return this.makeClickEvent(SearchPageEvents.openSmartSnippetSuggestionInlineLink, info, {
1677
+ contentIDKey: snippetAndLink.documentId.contentIdKey,
1678
+ contentIDValue: snippetAndLink.documentId.contentIdValue,
1679
+ }, snippetAndLink);
1680
+ }
1681
+ logOpenSmartSnippetSuggestionInlineLink(info, snippetAndLink) {
1682
+ return this.makeOpenSmartSnippetSuggestionInlineLink(info, snippetAndLink).log();
1683
+ }
1684
+ makeRecentQueryClick() {
1685
+ return this.makeSearchEvent(SearchPageEvents.recentQueryClick);
1686
+ }
1687
+ logRecentQueryClick() {
1688
+ return this.makeRecentQueryClick().log();
1689
+ }
1690
+ makeClearRecentQueries() {
1691
+ return this.makeCustomEvent(SearchPageEvents.clearRecentQueries);
1692
+ }
1693
+ logClearRecentQueries() {
1694
+ return this.makeClearRecentQueries().log();
1695
+ }
1696
+ makeRecentResultClick(info, identifier) {
1697
+ return this.makeCustomEvent(SearchPageEvents.recentResultClick, { info, identifier });
1698
+ }
1699
+ logRecentResultClick(info, identifier) {
1700
+ return this.makeRecentResultClick(info, identifier).log();
1701
+ }
1702
+ makeClearRecentResults() {
1703
+ return this.makeCustomEvent(SearchPageEvents.clearRecentResults);
1704
+ }
1705
+ logClearRecentResults() {
1706
+ return this.makeClearRecentResults().log();
1707
+ }
1708
+ makeNoResultsBack() {
1709
+ return this.makeSearchEvent(SearchPageEvents.noResultsBack);
1710
+ }
1711
+ logNoResultsBack() {
1712
+ return this.makeNoResultsBack().log();
1713
+ }
1714
+ makeShowMoreFoldedResults(info, identifier) {
1715
+ return this.makeClickEvent(SearchPageEvents.showMoreFoldedResults, info, identifier);
1716
+ }
1717
+ logShowMoreFoldedResults(info, identifier) {
1718
+ return this.makeShowMoreFoldedResults(info, identifier).log();
1719
+ }
1720
+ makeShowLessFoldedResults() {
1721
+ return this.makeCustomEvent(SearchPageEvents.showLessFoldedResults);
1722
+ }
1723
+ logShowLessFoldedResults() {
1724
+ return this.makeShowLessFoldedResults().log();
1725
+ }
1726
+ makeCustomEvent(event, metadata, eventType = CustomEventsTypes[event]) {
1727
+ const customData = Object.assign(Object.assign({}, this.provider.getBaseMetadata()), metadata);
1728
+ return {
1729
+ description: this.makeDescription(event, metadata),
1730
+ log: () => __awaiter(this, void 0, void 0, function* () {
1731
+ const payload = Object.assign(Object.assign({}, (yield this.getBaseCustomEventRequest(customData))), { eventType, eventValue: event });
1732
+ return this.coveoAnalyticsClient.sendCustomEvent(payload);
1733
+ }),
1734
+ };
1735
+ }
1736
+ logCustomEvent(event, metadata, eventType = CustomEventsTypes[event]) {
1737
+ return this.makeCustomEvent(event, metadata, eventType).log();
1738
+ }
1739
+ makeCustomEventWithType(eventValue, eventType, metadata) {
1740
+ const customData = Object.assign(Object.assign({}, this.provider.getBaseMetadata()), metadata);
1741
+ return {
1742
+ description: { actionCause: eventValue, customData },
1743
+ log: () => __awaiter(this, void 0, void 0, function* () {
1744
+ const payload = Object.assign(Object.assign({}, (yield this.getBaseCustomEventRequest(customData))), { eventType,
1745
+ eventValue });
1746
+ return this.coveoAnalyticsClient.sendCustomEvent(payload);
1747
+ }),
1748
+ };
1749
+ }
1750
+ logCustomEventWithType(eventValue, eventType, metadata) {
1751
+ return this.makeCustomEventWithType(eventValue, eventType, metadata).log();
1752
+ }
1753
+ logSearchEvent(event, metadata) {
1754
+ return __awaiter(this, void 0, void 0, function* () {
1755
+ return this.coveoAnalyticsClient.sendSearchEvent(yield this.getBaseSearchEventRequest(event, metadata));
1756
+ });
1757
+ }
1758
+ makeDescription(actionCause, metadata) {
1759
+ return { actionCause, customData: Object.assign(Object.assign({}, this.provider.getBaseMetadata()), metadata) };
1760
+ }
1761
+ makeSearchEvent(event, metadata) {
1762
+ return {
1763
+ description: this.makeDescription(event, metadata),
1764
+ log: () => this.logSearchEvent(event, metadata),
1765
+ };
1766
+ }
1767
+ logClickEvent(event, info, identifier, metadata) {
1768
+ return __awaiter(this, void 0, void 0, function* () {
1769
+ const payload = Object.assign(Object.assign(Object.assign({}, info), (yield this.getBaseEventRequest(Object.assign(Object.assign({}, identifier), metadata)))), { searchQueryUid: this.provider.getSearchUID(), queryPipeline: this.provider.getPipeline(), actionCause: event });
1770
+ return this.coveoAnalyticsClient.sendClickEvent(payload);
1771
+ });
1772
+ }
1773
+ makeClickEvent(event, info, identifier, metadata) {
1774
+ return {
1775
+ description: this.makeDescription(event, Object.assign(Object.assign({}, identifier), metadata)),
1776
+ log: () => this.logClickEvent(event, info, identifier, metadata),
1777
+ };
1778
+ }
1779
+ getBaseSearchEventRequest(event, metadata) {
1780
+ return __awaiter(this, void 0, void 0, function* () {
1781
+ return Object.assign(Object.assign(Object.assign({}, (yield this.getBaseEventRequest(metadata))), this.provider.getSearchEventRequestPayload()), { searchQueryUid: this.provider.getSearchUID(), queryPipeline: this.provider.getPipeline(), actionCause: event });
1782
+ });
1783
+ }
1784
+ getBaseCustomEventRequest(metadata) {
1785
+ return __awaiter(this, void 0, void 0, function* () {
1786
+ return Object.assign(Object.assign({}, (yield this.getBaseEventRequest(metadata))), { lastSearchQueryUid: this.provider.getSearchUID() });
1787
+ });
1788
+ }
1789
+ getBaseEventRequest(metadata) {
1790
+ return __awaiter(this, void 0, void 0, function* () {
1791
+ const customData = Object.assign(Object.assign({}, this.provider.getBaseMetadata()), metadata);
1792
+ return Object.assign(Object.assign(Object.assign({}, this.getOrigins()), this.getSplitTestRun()), { customData, language: this.provider.getLanguage(), facetState: this.provider.getFacetState ? this.provider.getFacetState() : [], anonymous: this.provider.getIsAnonymous(), clientId: yield this.getClientId() });
1793
+ });
1794
+ }
1795
+ getOrigins() {
1796
+ var _a, _b;
1797
+ return {
1798
+ originContext: (_b = (_a = this.provider).getOriginContext) === null || _b === void 0 ? void 0 : _b.call(_a),
1799
+ originLevel1: this.provider.getOriginLevel1(),
1800
+ originLevel2: this.provider.getOriginLevel2(),
1801
+ originLevel3: this.provider.getOriginLevel3(),
1802
+ };
1803
+ }
1804
+ getClientId() {
1805
+ return this.coveoAnalyticsClient instanceof CoveoAnalyticsClient
1806
+ ? this.coveoAnalyticsClient.getCurrentVisitorId()
1807
+ : undefined;
1808
+ }
1809
+ getSplitTestRun() {
1810
+ const splitTestRunName = this.provider.getSplitTestRunName ? this.provider.getSplitTestRunName() : '';
1811
+ const splitTestRunVersion = this.provider.getSplitTestRunVersion ? this.provider.getSplitTestRunVersion() : '';
1812
+ return Object.assign(Object.assign({}, (splitTestRunName && { splitTestRunName })), (splitTestRunVersion && { splitTestRunVersion }));
1813
+ }
1814
+ }
1815
+
1816
+ const getFormattedLocation = (location) => `${location.protocol}//${location.hostname}${location.pathname.indexOf('/') === 0 ? location.pathname : `/${location.pathname}`}${location.search}`;
1817
+
1818
+ const BasePluginEventTypes = {
1819
+ pageview: 'pageview',
1820
+ event: 'event',
1821
+ };
1822
+ class BasePlugin {
1823
+ constructor({ client, uuidGenerator = uuidv4 }) {
1824
+ this.actionData = {};
1825
+ this.client = client;
1826
+ this.uuidGenerator = uuidGenerator;
1827
+ this.pageViewId = uuidGenerator();
1828
+ this.nextPageViewId = this.pageViewId;
1829
+ this.currentLocation = getFormattedLocation(window.location);
1830
+ this.lastReferrer = document.referrer;
1831
+ this.addHooks();
1832
+ }
1833
+ setAction(action, options) {
1834
+ this.action = action;
1835
+ this.actionData = options;
1836
+ }
1837
+ clearData() {
1838
+ this.clearPluginData();
1839
+ this.action = undefined;
1840
+ this.actionData = {};
1841
+ }
1842
+ getLocationInformation(eventType, payload) {
1843
+ return Object.assign({ hitType: eventType }, this.getNextValues(eventType, payload));
1844
+ }
1845
+ updateLocationInformation(eventType, payload) {
1846
+ this.updateLocationForNextPageView(eventType, payload);
1847
+ }
1848
+ getDefaultContextInformation(eventType) {
1849
+ const documentContext = {
1850
+ title: document.title,
1851
+ encoding: document.characterSet,
1852
+ };
1853
+ const screenContext = {
1854
+ screenResolution: `${screen.width}x${screen.height}`,
1855
+ screenColor: `${screen.colorDepth}-bit`,
1856
+ };
1857
+ const navigatorContext = {
1858
+ language: navigator.language,
1859
+ userAgent: navigator.userAgent,
1860
+ };
1861
+ const eventContext = {
1862
+ time: Date.now().toString(),
1863
+ eventId: this.uuidGenerator(),
1864
+ };
1865
+ return Object.assign(Object.assign(Object.assign(Object.assign({}, eventContext), screenContext), navigatorContext), documentContext);
1866
+ }
1867
+ updateLocationForNextPageView(eventType, payload) {
1868
+ const { pageViewId, referrer, location } = this.getNextValues(eventType, payload);
1869
+ this.lastReferrer = referrer;
1870
+ this.pageViewId = pageViewId;
1871
+ this.currentLocation = location;
1872
+ if (eventType === BasePluginEventTypes.pageview) {
1873
+ this.nextPageViewId = this.uuidGenerator();
1874
+ this.hasSentFirstPageView = true;
1875
+ }
1876
+ }
1877
+ getNextValues(eventType, payload) {
1878
+ return {
1879
+ pageViewId: eventType === BasePluginEventTypes.pageview ? this.nextPageViewId : this.pageViewId,
1880
+ referrer: eventType === BasePluginEventTypes.pageview && this.hasSentFirstPageView
1881
+ ? this.currentLocation
1882
+ : this.lastReferrer,
1883
+ location: eventType === BasePluginEventTypes.pageview
1884
+ ? this.getCurrentLocationFromPayload(payload)
1885
+ : this.currentLocation,
1886
+ };
1887
+ }
1888
+ getCurrentLocationFromPayload(payload) {
1889
+ if (!!payload.page) {
1890
+ const removeStartingSlash = (page) => page.replace(/^\/?(.*)$/, '/$1');
1891
+ const extractHostnamePart = (location) => location.split('/').slice(0, 3).join('/');
1892
+ return `${extractHostnamePart(this.currentLocation)}${removeStartingSlash(payload.page)}`;
1893
+ }
1894
+ else {
1895
+ return getFormattedLocation(window.location);
1896
+ }
1897
+ }
1898
+ }
1899
+
1900
+ const SVCPluginEventTypes = Object.assign({}, BasePluginEventTypes);
1901
+ const allSVCEventTypes = Object.keys(SVCPluginEventTypes).map((key) => SVCPluginEventTypes[key]);
1902
+ class SVCPlugin extends BasePlugin {
1903
+ constructor({ client, uuidGenerator = uuidv4 }) {
1904
+ super({ client, uuidGenerator });
1905
+ this.ticket = {};
1906
+ }
1907
+ addHooks() {
1908
+ this.addHooksForEvent();
1909
+ this.addHooksForPageView();
1910
+ this.addHooksForSVCEvents();
1911
+ }
1912
+ setTicket(ticket) {
1913
+ this.ticket = ticket;
1914
+ }
1915
+ clearPluginData() {
1916
+ this.ticket = {};
1917
+ }
1918
+ addHooksForSVCEvents() {
1919
+ this.client.registerBeforeSendEventHook((eventType, ...[payload]) => {
1920
+ return allSVCEventTypes.indexOf(eventType) !== -1 ? this.addSVCDataToPayload(eventType, payload) : payload;
1921
+ });
1922
+ this.client.registerAfterSendEventHook((eventType, ...[payload]) => {
1923
+ if (allSVCEventTypes.indexOf(eventType) !== -1) {
1924
+ this.updateLocationInformation(eventType, payload);
1925
+ }
1926
+ return payload;
1927
+ });
1928
+ }
1929
+ addHooksForPageView() {
1930
+ this.client.addEventTypeMapping(SVCPluginEventTypes.pageview, {
1931
+ newEventType: EventType.collect,
1932
+ variableLengthArgumentsNames: ['page'],
1933
+ addVisitorIdParameter: true,
1934
+ usesMeasurementProtocol: true,
1935
+ });
1936
+ }
1937
+ addHooksForEvent() {
1938
+ this.client.addEventTypeMapping(SVCPluginEventTypes.event, {
1939
+ newEventType: EventType.collect,
1940
+ variableLengthArgumentsNames: ['eventCategory', 'eventAction', 'eventLabel', 'eventValue'],
1941
+ addVisitorIdParameter: true,
1942
+ usesMeasurementProtocol: true,
1943
+ });
1944
+ }
1945
+ addSVCDataToPayload(eventType, payload) {
1946
+ var _a;
1947
+ const svcPayload = Object.assign(Object.assign(Object.assign(Object.assign({}, this.getLocationInformation(eventType, payload)), this.getDefaultContextInformation(eventType)), (this.action ? { svcAction: this.action } : {})), (Object.keys((_a = this.actionData) !== null && _a !== void 0 ? _a : {}).length > 0 ? { svcActionData: this.actionData } : {}));
1948
+ const ticketPayload = this.getTicketPayload();
1949
+ this.clearData();
1950
+ return Object.assign(Object.assign(Object.assign({}, ticketPayload), svcPayload), payload);
1951
+ }
1952
+ getTicketPayload() {
1953
+ return convertTicketToMeasurementProtocol(this.ticket);
1954
+ }
1955
+ }
1956
+ SVCPlugin.Id = 'svc';
1957
+
1958
+ var CaseAssistEvents;
1959
+ (function (CaseAssistEvents) {
1960
+ CaseAssistEvents["click"] = "click";
1961
+ CaseAssistEvents["flowStart"] = "flowStart";
1962
+ })(CaseAssistEvents || (CaseAssistEvents = {}));
1963
+ var CaseAssistActions;
1964
+ (function (CaseAssistActions) {
1965
+ CaseAssistActions["enterInterface"] = "ticket_create_start";
1966
+ CaseAssistActions["fieldUpdate"] = "ticket_field_update";
1967
+ CaseAssistActions["fieldSuggestionClick"] = "ticket_classification_click";
1968
+ CaseAssistActions["suggestionClick"] = "suggestion_click";
1969
+ CaseAssistActions["suggestionRate"] = "suggestion_rate";
1970
+ CaseAssistActions["nextCaseStep"] = "ticket_next_stage";
1971
+ CaseAssistActions["caseCancelled"] = "ticket_cancel";
1972
+ CaseAssistActions["caseSolved"] = "ticket_cancel";
1973
+ CaseAssistActions["caseCreated"] = "ticket_create";
1974
+ })(CaseAssistActions || (CaseAssistActions = {}));
1975
+ var CaseCancelledReasons;
1976
+ (function (CaseCancelledReasons) {
1977
+ CaseCancelledReasons["quit"] = "Quit";
1978
+ CaseCancelledReasons["solved"] = "Solved";
1979
+ })(CaseCancelledReasons || (CaseCancelledReasons = {}));
1980
+
1981
+ class CaseAssistClient {
1982
+ constructor(options, provider) {
1983
+ var _a;
1984
+ this.options = options;
1985
+ this.provider = provider;
1986
+ const analyticsEnabled = ((_a = options.enableAnalytics) !== null && _a !== void 0 ? _a : true) && !doNotTrack();
1987
+ this.coveoAnalyticsClient = analyticsEnabled ? new CoveoAnalyticsClient(options) : new NoopAnalytics();
1988
+ this.svc = new SVCPlugin({ client: this.coveoAnalyticsClient });
1989
+ }
1990
+ disable() {
1991
+ if (this.coveoAnalyticsClient instanceof CoveoAnalyticsClient) {
1992
+ this.coveoAnalyticsClient.clear();
1993
+ }
1994
+ this.coveoAnalyticsClient = new NoopAnalytics();
1995
+ this.svc = new SVCPlugin({ client: this.coveoAnalyticsClient });
1996
+ }
1997
+ enable() {
1998
+ this.coveoAnalyticsClient = new CoveoAnalyticsClient(this.options);
1999
+ this.svc = new SVCPlugin({ client: this.coveoAnalyticsClient });
2000
+ }
2001
+ logEnterInterface(meta) {
2002
+ this.svc.setAction(CaseAssistActions.enterInterface);
2003
+ this.svc.setTicket(meta.ticket);
2004
+ return this.sendFlowStartEvent();
2005
+ }
2006
+ logUpdateCaseField(meta) {
2007
+ this.svc.setAction(CaseAssistActions.fieldUpdate, {
2008
+ fieldName: meta.fieldName,
2009
+ });
2010
+ this.svc.setTicket(meta.ticket);
2011
+ return this.sendClickEvent();
2012
+ }
2013
+ logSelectFieldSuggestion(meta) {
2014
+ this.svc.setAction(CaseAssistActions.fieldSuggestionClick, meta.suggestion);
2015
+ this.svc.setTicket(meta.ticket);
2016
+ return this.sendClickEvent();
2017
+ }
2018
+ logSelectDocumentSuggestion(meta) {
2019
+ this.svc.setAction(CaseAssistActions.suggestionClick, meta.suggestion);
2020
+ this.svc.setTicket(meta.ticket);
2021
+ return this.sendClickEvent();
2022
+ }
2023
+ logRateDocumentSuggestion(meta) {
2024
+ this.svc.setAction(CaseAssistActions.suggestionRate, Object.assign({ rate: meta.rating }, meta.suggestion));
2025
+ this.svc.setTicket(meta.ticket);
2026
+ return this.sendClickEvent();
2027
+ }
2028
+ logMoveToNextCaseStep(meta) {
2029
+ this.svc.setAction(CaseAssistActions.nextCaseStep, {
2030
+ stage: meta === null || meta === void 0 ? void 0 : meta.stage,
2031
+ });
2032
+ this.svc.setTicket(meta.ticket);
2033
+ return this.sendClickEvent();
2034
+ }
2035
+ logCaseCancelled(meta) {
2036
+ this.svc.setAction(CaseAssistActions.caseCancelled, {
2037
+ reason: CaseCancelledReasons.quit,
2038
+ });
2039
+ this.svc.setTicket(meta.ticket);
2040
+ return this.sendClickEvent();
2041
+ }
2042
+ logCaseSolved(meta) {
2043
+ this.svc.setAction(CaseAssistActions.caseSolved, {
2044
+ reason: CaseCancelledReasons.solved,
2045
+ });
2046
+ this.svc.setTicket(meta.ticket);
2047
+ return this.sendClickEvent();
2048
+ }
2049
+ logCaseCreated(meta) {
2050
+ this.svc.setAction(CaseAssistActions.caseCreated);
2051
+ this.svc.setTicket(meta.ticket);
2052
+ return this.sendClickEvent();
2053
+ }
2054
+ sendFlowStartEvent() {
2055
+ return this.coveoAnalyticsClient.sendEvent('event', 'svc', CaseAssistEvents.flowStart, this.provider
2056
+ ? {
2057
+ searchHub: this.provider.getOriginLevel1(),
2058
+ }
2059
+ : null);
2060
+ }
2061
+ sendClickEvent() {
2062
+ return this.coveoAnalyticsClient.sendEvent('event', 'svc', CaseAssistEvents.click, this.provider
2063
+ ? {
2064
+ searchHub: this.provider.getOriginLevel1(),
2065
+ }
2066
+ : null);
2067
+ }
2068
+ }
2069
+
2070
+ const extractContextFromMetadata = (meta) => {
2071
+ const context = {};
2072
+ if (meta.caseContext) {
2073
+ Object.keys(meta.caseContext).forEach((contextKey) => {
2074
+ var _a;
2075
+ const value = (_a = meta.caseContext) === null || _a === void 0 ? void 0 : _a[contextKey];
2076
+ if (value) {
2077
+ const keyToBeSent = `context_${contextKey}`;
2078
+ context[keyToBeSent] = value;
2079
+ }
2080
+ });
2081
+ }
2082
+ return context;
2083
+ };
2084
+ const generateMetadataToSend = (metadata, includeContext = true) => {
2085
+ const { caseContext, caseId, caseNumber } = metadata, metadataWithoutContext = __rest(metadata, ["caseContext", "caseId", "caseNumber"]);
2086
+ const context = extractContextFromMetadata(metadata);
2087
+ return Object.assign(Object.assign(Object.assign({ CaseId: caseId, CaseNumber: caseNumber }, metadataWithoutContext), (!!context.context_Case_Subject && { CaseSubject: context.context_Case_Subject })), (includeContext && context));
2088
+ };
2089
+ class CoveoInsightClient {
2090
+ constructor(opts, provider) {
2091
+ this.opts = opts;
2092
+ this.provider = provider;
2093
+ const shouldDisableAnalytics = opts.enableAnalytics === false || doNotTrack();
2094
+ this.coveoAnalyticsClient = shouldDisableAnalytics ? new NoopAnalytics() : new CoveoAnalyticsClient(opts);
2095
+ }
2096
+ disable() {
2097
+ if (this.coveoAnalyticsClient instanceof CoveoAnalyticsClient) {
2098
+ this.coveoAnalyticsClient.clear();
2099
+ }
2100
+ this.coveoAnalyticsClient = new NoopAnalytics();
2101
+ }
2102
+ enable() {
2103
+ this.coveoAnalyticsClient = new CoveoAnalyticsClient(this.opts);
2104
+ }
2105
+ logInterfaceLoad(metadata) {
2106
+ if (metadata) {
2107
+ const metadataToSend = generateMetadataToSend(metadata);
2108
+ return this.logSearchEvent(SearchPageEvents.interfaceLoad, metadataToSend);
2109
+ }
2110
+ return this.logSearchEvent(SearchPageEvents.interfaceLoad);
2111
+ }
2112
+ logInterfaceChange(metadata) {
2113
+ const metadataToSend = generateMetadataToSend(metadata);
2114
+ return this.logSearchEvent(SearchPageEvents.interfaceChange, metadataToSend);
2115
+ }
2116
+ logStaticFilterDeselect(metadata) {
2117
+ const metadataToSend = generateMetadataToSend(metadata);
2118
+ return this.logSearchEvent(SearchPageEvents.staticFilterDeselect, metadataToSend);
2119
+ }
2120
+ logFetchMoreResults(metadata) {
2121
+ if (metadata) {
2122
+ const metadataToSend = generateMetadataToSend(metadata);
2123
+ return this.logCustomEvent(SearchPageEvents.pagerScrolling, Object.assign(Object.assign({}, metadataToSend), { type: 'getMoreResults' }));
2124
+ }
2125
+ return this.logCustomEvent(SearchPageEvents.pagerScrolling, { type: 'getMoreResults' });
2126
+ }
2127
+ logBreadcrumbFacet(metadata) {
2128
+ const metadataToSend = generateMetadataToSend(metadata);
2129
+ return this.logSearchEvent(SearchPageEvents.breadcrumbFacet, metadataToSend);
2130
+ }
2131
+ logBreadcrumbResetAll(metadata) {
2132
+ if (metadata) {
2133
+ const metadataToSend = generateMetadataToSend(metadata);
2134
+ return this.logSearchEvent(SearchPageEvents.breadcrumbResetAll, metadataToSend);
2135
+ }
2136
+ return this.logSearchEvent(SearchPageEvents.breadcrumbResetAll);
2137
+ }
2138
+ logFacetSelect(metadata) {
2139
+ const metadataToSend = generateMetadataToSend(metadata);
2140
+ return this.logSearchEvent(SearchPageEvents.facetSelect, metadataToSend);
2141
+ }
2142
+ logFacetDeselect(metadata) {
2143
+ const metadataToSend = generateMetadataToSend(metadata);
2144
+ return this.logSearchEvent(SearchPageEvents.facetDeselect, metadataToSend);
2145
+ }
2146
+ logFacetUpdateSort(metadata) {
2147
+ const metadataToSend = generateMetadataToSend(metadata);
2148
+ return this.logSearchEvent(SearchPageEvents.facetUpdateSort, metadataToSend);
2149
+ }
2150
+ logFacetClearAll(metadata) {
2151
+ const metadataToSend = generateMetadataToSend(metadata);
2152
+ return this.logSearchEvent(SearchPageEvents.facetClearAll, metadataToSend);
2153
+ }
2154
+ logFacetShowMore(metadata) {
2155
+ const metadataToSend = generateMetadataToSend(metadata, false);
2156
+ return this.logCustomEvent(SearchPageEvents.facetShowMore, metadataToSend);
2157
+ }
2158
+ logFacetShowLess(metadata) {
2159
+ const metadataToSend = generateMetadataToSend(metadata, false);
2160
+ return this.logCustomEvent(SearchPageEvents.facetShowLess, metadataToSend);
2161
+ }
2162
+ logQueryError(metadata) {
2163
+ const metadataToSend = generateMetadataToSend(metadata, false);
2164
+ return this.logCustomEvent(SearchPageEvents.queryError, metadataToSend);
2165
+ }
2166
+ logPagerNumber(metadata) {
2167
+ const metadataToSend = generateMetadataToSend(metadata, false);
2168
+ return this.logCustomEvent(SearchPageEvents.pagerNumber, metadataToSend);
2169
+ }
2170
+ logPagerNext(metadata) {
2171
+ const metadataToSend = generateMetadataToSend(metadata, false);
2172
+ return this.logCustomEvent(SearchPageEvents.pagerNext, metadataToSend);
2173
+ }
2174
+ logPagerPrevious(metadata) {
2175
+ const metadataToSend = generateMetadataToSend(metadata, false);
2176
+ return this.logCustomEvent(SearchPageEvents.pagerPrevious, metadataToSend);
2177
+ }
2178
+ logDidYouMeanAutomatic(metadata) {
2179
+ if (metadata) {
2180
+ const metadataToSend = generateMetadataToSend(metadata);
2181
+ return this.logSearchEvent(SearchPageEvents.didyoumeanAutomatic, metadataToSend);
2182
+ }
2183
+ return this.logSearchEvent(SearchPageEvents.didyoumeanAutomatic);
2184
+ }
2185
+ logDidYouMeanClick(metadata) {
2186
+ if (metadata) {
2187
+ const metadataToSend = generateMetadataToSend(metadata);
2188
+ return this.logSearchEvent(SearchPageEvents.didyoumeanClick, metadataToSend);
2189
+ }
2190
+ return this.logSearchEvent(SearchPageEvents.didyoumeanClick);
2191
+ }
2192
+ logResultsSort(metadata) {
2193
+ const metadataToSend = generateMetadataToSend(metadata);
2194
+ return this.logSearchEvent(SearchPageEvents.resultsSort, metadataToSend);
2195
+ }
2196
+ logSearchboxSubmit(metadata) {
2197
+ if (metadata) {
2198
+ const metadataToSend = generateMetadataToSend(metadata);
2199
+ return this.logSearchEvent(SearchPageEvents.searchboxSubmit, metadataToSend);
2200
+ }
2201
+ return this.logSearchEvent(SearchPageEvents.searchboxSubmit);
2202
+ }
2203
+ logContextChanged(metadata) {
2204
+ const metadataToSend = generateMetadataToSend(metadata);
2205
+ return this.logSearchEvent(InsightEvents.contextChanged, metadataToSend);
2206
+ }
2207
+ logExpandToFullUI(metadata) {
2208
+ const metadataToSend = generateMetadataToSend(metadata);
2209
+ return this.logCustomEvent(InsightEvents.expandToFullUI, metadataToSend);
2210
+ }
2211
+ logDocumentOpen(info, identifier, metadata) {
2212
+ return this.logClickEvent(SearchPageEvents.documentOpen, info, identifier, metadata ? generateMetadataToSend(metadata, false) : undefined);
2213
+ }
2214
+ logCustomEvent(event, metadata) {
2215
+ return __awaiter(this, void 0, void 0, function* () {
2216
+ const customData = Object.assign(Object.assign({}, this.provider.getBaseMetadata()), metadata);
2217
+ const payload = Object.assign(Object.assign({}, (yield this.getBaseCustomEventRequest(customData))), { eventType: CustomEventsTypes[event], eventValue: event });
2218
+ return this.coveoAnalyticsClient.sendCustomEvent(payload);
2219
+ });
2220
+ }
2221
+ logSearchEvent(event, metadata) {
2222
+ return __awaiter(this, void 0, void 0, function* () {
2223
+ return this.coveoAnalyticsClient.sendSearchEvent(yield this.getBaseSearchEventRequest(event, metadata));
2224
+ });
2225
+ }
2226
+ logClickEvent(event, info, identifier, metadata) {
2227
+ return __awaiter(this, void 0, void 0, function* () {
2228
+ const payload = Object.assign(Object.assign(Object.assign({}, info), (yield this.getBaseEventRequest(Object.assign(Object.assign({}, identifier), metadata)))), { searchQueryUid: this.provider.getSearchUID(), queryPipeline: this.provider.getPipeline(), actionCause: event });
2229
+ return this.coveoAnalyticsClient.sendClickEvent(payload);
2230
+ });
2231
+ }
2232
+ getBaseCustomEventRequest(metadata) {
2233
+ return __awaiter(this, void 0, void 0, function* () {
2234
+ return Object.assign(Object.assign({}, (yield this.getBaseEventRequest(metadata))), { lastSearchQueryUid: this.provider.getSearchUID() });
2235
+ });
2236
+ }
2237
+ getBaseSearchEventRequest(event, metadata) {
2238
+ return __awaiter(this, void 0, void 0, function* () {
2239
+ return Object.assign(Object.assign(Object.assign({}, (yield this.getBaseEventRequest(metadata))), this.provider.getSearchEventRequestPayload()), { searchQueryUid: this.provider.getSearchUID(), queryPipeline: this.provider.getPipeline(), actionCause: event });
2240
+ });
2241
+ }
2242
+ getBaseEventRequest(metadata) {
2243
+ return __awaiter(this, void 0, void 0, function* () {
2244
+ const customData = Object.assign(Object.assign({}, this.provider.getBaseMetadata()), metadata);
2245
+ return Object.assign(Object.assign({}, this.getOrigins()), { customData, language: this.provider.getLanguage(), facetState: this.provider.getFacetState ? this.provider.getFacetState() : [], anonymous: this.provider.getIsAnonymous(), clientId: yield this.getClientId() });
2246
+ });
2247
+ }
2248
+ getOrigins() {
2249
+ var _a, _b;
2250
+ return {
2251
+ originContext: (_b = (_a = this.provider).getOriginContext) === null || _b === void 0 ? void 0 : _b.call(_a),
2252
+ originLevel1: this.provider.getOriginLevel1(),
2253
+ originLevel2: this.provider.getOriginLevel2(),
2254
+ originLevel3: this.provider.getOriginLevel3(),
2255
+ };
2256
+ }
2257
+ getClientId() {
2258
+ return this.coveoAnalyticsClient instanceof CoveoAnalyticsClient
2259
+ ? this.coveoAnalyticsClient.getCurrentVisitorId()
2260
+ : undefined;
2261
+ }
132
2262
  }
133
2263
 
134
- export { ReactNativeRuntime, ReactNativeStorage };
2264
+ export { CaseAssistClient, CoveoAnalyticsClient, CoveoInsightClient, CoveoSearchPageClient, ReactNativeRuntime, history };