@algolia/autocomplete-plugin-algolia-insights 1.8.3 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { AutocompletePlugin } from '@algolia/autocomplete-js';
1
+ import { AutocompletePlugin } from '@algolia/autocomplete-shared';
2
2
  import { InsightsClient, OnActiveParams, OnItemsChangeParams, OnSelectParams } from './types';
3
3
  export declare type CreateAlgoliaInsightsPluginParams = {
4
4
  /**
@@ -6,7 +6,7 @@ export declare type CreateAlgoliaInsightsPluginParams = {
6
6
  *
7
7
  * @link https://www.algolia.com/doc/ui-libraries/autocomplete/api-reference/autocomplete-plugin-algolia-insights/createAlgoliaInsightsPlugin/#param-insightsclient
8
8
  */
9
- insightsClient: InsightsClient;
9
+ insightsClient?: InsightsClient;
10
10
  /**
11
11
  * Hook to send an Insights event when the items change.
12
12
  *
@@ -1,32 +1,28 @@
1
+ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
1
2
  function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
2
-
3
3
  function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
4
-
5
4
  function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
6
-
7
5
  function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
8
-
9
6
  function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
10
-
11
- function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
12
-
7
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
13
8
  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
14
-
15
9
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
16
-
17
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
18
-
19
- import { createRef, debounce, isEqual, noop } from '@algolia/autocomplete-shared';
10
+ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
11
+ function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
12
+ function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
13
+ import { createRef, debounce, isEqual, noop, safelyRunOnBrowser } from '@algolia/autocomplete-shared';
20
14
  import { createClickedEvent } from './createClickedEvent';
21
15
  import { createSearchInsightsApi } from './createSearchInsightsApi';
22
16
  import { createViewedEvents } from './createViewedEvents';
23
17
  import { isAlgoliaInsightsHit } from './isAlgoliaInsightsHit';
24
18
  var VIEW_EVENT_DELAY = 400;
19
+ var ALGOLIA_INSIGHTS_VERSION = '2.4.0';
20
+ var ALGOLIA_INSIGHTS_SRC = "https://cdn.jsdelivr.net/npm/search-insights@".concat(ALGOLIA_INSIGHTS_VERSION, "/dist/search-insights.min.js");
25
21
  var sendViewedObjectIDs = debounce(function (_ref) {
26
22
  var onItemsChange = _ref.onItemsChange,
27
- items = _ref.items,
28
- insights = _ref.insights,
29
- state = _ref.state;
23
+ items = _ref.items,
24
+ insights = _ref.insights,
25
+ state = _ref.state;
30
26
  onItemsChange({
31
27
  insights: insights,
32
28
  insightsEvents: createViewedEvents({
@@ -41,31 +37,53 @@ var sendViewedObjectIDs = debounce(function (_ref) {
41
37
  }, VIEW_EVENT_DELAY);
42
38
  export function createAlgoliaInsightsPlugin(options) {
43
39
  var _getOptions = getOptions(options),
44
- insightsClient = _getOptions.insightsClient,
45
- onItemsChange = _getOptions.onItemsChange,
46
- onSelectEvent = _getOptions.onSelect,
47
- onActiveEvent = _getOptions.onActive;
48
-
40
+ providedInsightsClient = _getOptions.insightsClient,
41
+ onItemsChange = _getOptions.onItemsChange,
42
+ onSelectEvent = _getOptions.onSelect,
43
+ onActiveEvent = _getOptions.onActive;
44
+ var insightsClient = providedInsightsClient;
45
+ if (!providedInsightsClient) {
46
+ safelyRunOnBrowser(function (_ref2) {
47
+ var window = _ref2.window;
48
+ var pointer = window.AlgoliaAnalyticsObject || 'aa';
49
+ if (typeof pointer === 'string') {
50
+ insightsClient = window[pointer];
51
+ }
52
+ if (!insightsClient) {
53
+ window.AlgoliaAnalyticsObject = pointer;
54
+ if (!window[pointer]) {
55
+ window[pointer] = function () {
56
+ if (!window[pointer].queue) {
57
+ window[pointer].queue = [];
58
+ }
59
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
60
+ args[_key] = arguments[_key];
61
+ }
62
+ window[pointer].queue.push(args);
63
+ };
64
+ }
65
+ window[pointer].version = ALGOLIA_INSIGHTS_VERSION;
66
+ insightsClient = window[pointer];
67
+ loadInsights(window);
68
+ }
69
+ });
70
+ }
49
71
  var insights = createSearchInsightsApi(insightsClient);
50
72
  var previousItems = createRef([]);
51
- var debouncedOnStateChange = debounce(function (_ref2) {
52
- var state = _ref2.state;
53
-
73
+ var debouncedOnStateChange = debounce(function (_ref3) {
74
+ var state = _ref3.state;
54
75
  if (!state.isOpen) {
55
76
  return;
56
77
  }
57
-
58
78
  var items = state.collections.reduce(function (acc, current) {
59
79
  return [].concat(_toConsumableArray(acc), _toConsumableArray(current.items));
60
80
  }, []).filter(isAlgoliaInsightsHit);
61
-
62
81
  if (!isEqual(previousItems.current.map(function (x) {
63
82
  return x.objectID;
64
83
  }), items.map(function (x) {
65
84
  return x.objectID;
66
85
  }))) {
67
86
  previousItems.current = items;
68
-
69
87
  if (items.length > 0) {
70
88
  sendViewedObjectIDs({
71
89
  onItemsChange: onItemsChange,
@@ -78,10 +96,10 @@ export function createAlgoliaInsightsPlugin(options) {
78
96
  }, 0);
79
97
  return {
80
98
  name: 'aa.algoliaInsightsPlugin',
81
- subscribe: function subscribe(_ref3) {
82
- var setContext = _ref3.setContext,
83
- onSelect = _ref3.onSelect,
84
- onActive = _ref3.onActive;
99
+ subscribe: function subscribe(_ref4) {
100
+ var setContext = _ref4.setContext,
101
+ onSelect = _ref4.onSelect,
102
+ onActive = _ref4.onActive;
85
103
  insightsClient('addAlgoliaAgent', 'insights-plugin');
86
104
  setContext({
87
105
  algoliaInsightsPlugin: {
@@ -91,15 +109,13 @@ export function createAlgoliaInsightsPlugin(options) {
91
109
  insights: insights
92
110
  }
93
111
  });
94
- onSelect(function (_ref4) {
95
- var item = _ref4.item,
96
- state = _ref4.state,
97
- event = _ref4.event;
98
-
112
+ onSelect(function (_ref5) {
113
+ var item = _ref5.item,
114
+ state = _ref5.state,
115
+ event = _ref5.event;
99
116
  if (!isAlgoliaInsightsHit(item)) {
100
117
  return;
101
118
  }
102
-
103
119
  onSelectEvent({
104
120
  state: state,
105
121
  event: event,
@@ -113,15 +129,13 @@ export function createAlgoliaInsightsPlugin(options) {
113
129
  }))]
114
130
  });
115
131
  });
116
- onActive(function (_ref5) {
117
- var item = _ref5.item,
118
- state = _ref5.state,
119
- event = _ref5.event;
120
-
132
+ onActive(function (_ref6) {
133
+ var item = _ref6.item,
134
+ state = _ref6.state,
135
+ event = _ref6.event;
121
136
  if (!isAlgoliaInsightsHit(item)) {
122
137
  return;
123
138
  }
124
-
125
139
  onActiveEvent({
126
140
  state: state,
127
141
  event: event,
@@ -136,8 +150,8 @@ export function createAlgoliaInsightsPlugin(options) {
136
150
  });
137
151
  });
138
152
  },
139
- onStateChange: function onStateChange(_ref6) {
140
- var state = _ref6.state;
153
+ onStateChange: function onStateChange(_ref7) {
154
+ var state = _ref7.state;
141
155
  debouncedOnStateChange({
142
156
  state: state
143
157
  });
@@ -145,19 +159,42 @@ export function createAlgoliaInsightsPlugin(options) {
145
159
  __autocomplete_pluginOptions: options
146
160
  };
147
161
  }
148
-
149
162
  function getOptions(options) {
150
163
  return _objectSpread({
151
- onItemsChange: function onItemsChange(_ref7) {
152
- var insights = _ref7.insights,
153
- insightsEvents = _ref7.insightsEvents;
154
- insights.viewedObjectIDs.apply(insights, _toConsumableArray(insightsEvents));
155
- },
156
- onSelect: function onSelect(_ref8) {
164
+ onItemsChange: function onItemsChange(_ref8) {
157
165
  var insights = _ref8.insights,
158
- insightsEvents = _ref8.insightsEvents;
159
- insights.clickedObjectIDsAfterSearch.apply(insights, _toConsumableArray(insightsEvents));
166
+ insightsEvents = _ref8.insightsEvents;
167
+ insights.viewedObjectIDs.apply(insights, _toConsumableArray(insightsEvents.map(function (event) {
168
+ return _objectSpread(_objectSpread({}, event), {}, {
169
+ algoliaSource: [].concat(_toConsumableArray(event.algoliaSource || []), ['autocomplete-internal'])
170
+ });
171
+ })));
172
+ },
173
+ onSelect: function onSelect(_ref9) {
174
+ var insights = _ref9.insights,
175
+ insightsEvents = _ref9.insightsEvents;
176
+ insights.clickedObjectIDsAfterSearch.apply(insights, _toConsumableArray(insightsEvents.map(function (event) {
177
+ return _objectSpread(_objectSpread({}, event), {}, {
178
+ algoliaSource: [].concat(_toConsumableArray(event.algoliaSource || []), ['autocomplete-internal'])
179
+ });
180
+ })));
160
181
  },
161
182
  onActive: noop
162
183
  }, options);
184
+ }
185
+ function loadInsights(environment) {
186
+ var errorMessage = "[Autocomplete]: Could not load search-insights.js. Please load it manually following https://alg.li/insights-autocomplete";
187
+ try {
188
+ var script = environment.document.createElement('script');
189
+ script.async = true;
190
+ script.src = ALGOLIA_INSIGHTS_SRC;
191
+ script.onerror = function () {
192
+ // eslint-disable-next-line no-console
193
+ console.error(errorMessage);
194
+ };
195
+ document.body.appendChild(script);
196
+ } catch (cause) {
197
+ // eslint-disable-next-line no-console
198
+ console.error(errorMessage);
199
+ }
163
200
  }
@@ -1,7 +1,9 @@
1
- import { AlgoliaInsightsHit, ClickedObjectIDsAfterSearchParams } from './types';
1
+ import type { AlgoliaInsightsHit, ClickedObjectIDsAfterSearchParams, InsightsParamsWithItems } from './types';
2
2
  declare type CreateClickedEventParams = {
3
3
  item: AlgoliaInsightsHit;
4
4
  items: AlgoliaInsightsHit[];
5
5
  };
6
- export declare function createClickedEvent({ item, items, }: CreateClickedEventParams): Omit<ClickedObjectIDsAfterSearchParams, 'eventName'>;
6
+ export declare function createClickedEvent({ item, items, }: CreateClickedEventParams): Omit<InsightsParamsWithItems<ClickedObjectIDsAfterSearchParams>, 'eventName'> & {
7
+ algoliaSource?: string[];
8
+ };
7
9
  export {};
@@ -1,12 +1,13 @@
1
1
  export function createClickedEvent(_ref) {
2
2
  var item = _ref.item,
3
- items = _ref.items;
3
+ items = _ref.items;
4
4
  return {
5
5
  index: item.__autocomplete_indexName,
6
- objectIDs: [item.objectID],
6
+ items: [item],
7
7
  positions: [1 + items.findIndex(function (x) {
8
8
  return x.objectID === item.objectID;
9
9
  })],
10
- queryID: item.__autocomplete_queryID
10
+ queryID: item.__autocomplete_queryID,
11
+ algoliaSource: ['autocomplete']
11
12
  };
12
13
  }
@@ -1,4 +1,4 @@
1
- import { ClickedFiltersParams, ClickedObjectIDsAfterSearchParams, ClickedObjectIDsParams, ConvertedFiltersParams, ConvertedObjectIDsAfterSearchParams, ConvertedObjectIDsParams, InsightsClient, ViewedFiltersParams, ViewedObjectIDsParams } from './types';
1
+ import { ClickedFiltersParams, ClickedObjectIDsAfterSearchParams, ClickedObjectIDsParams, ConvertedFiltersParams, ConvertedObjectIDsAfterSearchParams, ConvertedObjectIDsParams, InsightsClient, InsightsParamsWithItems, ViewedFiltersParams, ViewedObjectIDsParams } from './types';
2
2
  export declare function createSearchInsightsApi(searchInsights: InsightsClient): {
3
3
  /**
4
4
  * Initializes Insights with Algolia credentials.
@@ -13,13 +13,13 @@ export declare function createSearchInsightsApi(searchInsights: InsightsClient):
13
13
  *
14
14
  * @link https://www.algolia.com/doc/api-reference/api-methods/clicked-object-ids-after-search/
15
15
  */
16
- clickedObjectIDsAfterSearch(...params: ClickedObjectIDsAfterSearchParams[]): void;
16
+ clickedObjectIDsAfterSearch(...params: Array<InsightsParamsWithItems<ClickedObjectIDsAfterSearchParams>>): void;
17
17
  /**
18
18
  * Sends click events to capture clicked items.
19
19
  *
20
20
  * @link https://www.algolia.com/doc/api-reference/api-methods/clicked-object-ids/
21
21
  */
22
- clickedObjectIDs(...params: ClickedObjectIDsParams[]): void;
22
+ clickedObjectIDs(...params: Array<InsightsParamsWithItems<ClickedObjectIDsParams>>): void;
23
23
  /**
24
24
  * Sends click events to capture the filters a user clicks on.
25
25
  *
@@ -31,13 +31,13 @@ export declare function createSearchInsightsApi(searchInsights: InsightsClient):
31
31
  *
32
32
  * @link https://www.algolia.com/doc/api-reference/api-methods/converted-object-ids-after-search/
33
33
  */
34
- convertedObjectIDsAfterSearch(...params: ConvertedObjectIDsAfterSearchParams[]): void;
34
+ convertedObjectIDsAfterSearch(...params: Array<InsightsParamsWithItems<ConvertedObjectIDsAfterSearchParams>>): void;
35
35
  /**
36
36
  * Sends conversion events to capture clicked items.
37
37
  *
38
38
  * @link https://www.algolia.com/doc/api-reference/api-methods/converted-object-ids/
39
39
  */
40
- convertedObjectIDs(...params: ConvertedObjectIDsParams[]): void;
40
+ convertedObjectIDs(...params: Array<InsightsParamsWithItems<ConvertedObjectIDsParams>>): void;
41
41
  /**
42
42
  * Sends conversion events to capture the filters a user uses when converting.
43
43
  *
@@ -49,7 +49,7 @@ export declare function createSearchInsightsApi(searchInsights: InsightsClient):
49
49
  *
50
50
  * @link https://www.algolia.com/doc/api-reference/api-methods/viewed-object-ids/
51
51
  */
52
- viewedObjectIDs(...params: ViewedObjectIDsParams[]): void;
52
+ viewedObjectIDs(...params: Array<InsightsParamsWithItems<ViewedObjectIDsParams>>): void;
53
53
  /**
54
54
  * Sends view events to capture the filters a user uses when viewing.
55
55
  *
@@ -1,35 +1,60 @@
1
+ var _excluded = ["items"],
2
+ _excluded2 = ["items"];
3
+ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
1
4
  function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
2
-
3
5
  function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
4
-
5
6
  function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
6
-
7
7
  function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
8
-
9
8
  function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
10
-
11
- function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
12
-
9
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
10
+ function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
11
+ function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
13
12
  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
14
-
15
13
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
16
-
17
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
18
-
14
+ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
15
+ function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
16
+ function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
17
+ import { isModernInsightsClient } from './isModernInsightsClient';
19
18
  function chunk(item) {
20
19
  var chunkSize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 20;
21
20
  var chunks = [];
22
-
23
21
  for (var i = 0; i < item.objectIDs.length; i += chunkSize) {
24
22
  chunks.push(_objectSpread(_objectSpread({}, item), {}, {
25
23
  objectIDs: item.objectIDs.slice(i, i + chunkSize)
26
24
  }));
27
25
  }
28
-
29
26
  return chunks;
30
27
  }
31
-
28
+ function mapToInsightsParamsApi(params) {
29
+ return params.map(function (_ref) {
30
+ var items = _ref.items,
31
+ param = _objectWithoutProperties(_ref, _excluded);
32
+ return _objectSpread(_objectSpread({}, param), {}, {
33
+ objectIDs: (items === null || items === void 0 ? void 0 : items.map(function (_ref2) {
34
+ var objectID = _ref2.objectID;
35
+ return objectID;
36
+ })) || param.objectIDs
37
+ });
38
+ });
39
+ }
32
40
  export function createSearchInsightsApi(searchInsights) {
41
+ var canSendHeaders = isModernInsightsClient(searchInsights);
42
+ function sendToInsights(method, payloads, items) {
43
+ if (canSendHeaders && typeof items !== 'undefined') {
44
+ var _items$0$__autocomple = items[0].__autocomplete_algoliaCredentials,
45
+ appId = _items$0$__autocomple.appId,
46
+ apiKey = _items$0$__autocomple.apiKey;
47
+ var headers = {
48
+ 'X-Algolia-Application-Id': appId,
49
+ 'X-Algolia-API-Key': apiKey
50
+ };
51
+ searchInsights.apply(void 0, [method].concat(_toConsumableArray(payloads), [{
52
+ headers: headers
53
+ }]));
54
+ } else {
55
+ searchInsights.apply(void 0, [method].concat(_toConsumableArray(payloads)));
56
+ }
57
+ }
33
58
  return {
34
59
  /**
35
60
  * Initializes Insights with Algolia credentials.
@@ -40,14 +65,12 @@ export function createSearchInsightsApi(searchInsights) {
40
65
  apiKey: apiKey
41
66
  });
42
67
  },
43
-
44
68
  /**
45
69
  * Sets the user token to attach to events.
46
70
  */
47
71
  setUserToken: function setUserToken(userToken) {
48
72
  searchInsights('setUserToken', userToken);
49
73
  },
50
-
51
74
  /**
52
75
  * Sends click events to capture a query and its clicked items and positions.
53
76
  *
@@ -57,12 +80,10 @@ export function createSearchInsightsApi(searchInsights) {
57
80
  for (var _len = arguments.length, params = new Array(_len), _key = 0; _key < _len; _key++) {
58
81
  params[_key] = arguments[_key];
59
82
  }
60
-
61
83
  if (params.length > 0) {
62
- searchInsights.apply(void 0, ['clickedObjectIDsAfterSearch'].concat(params));
84
+ sendToInsights('clickedObjectIDsAfterSearch', mapToInsightsParamsApi(params), params[0].items);
63
85
  }
64
86
  },
65
-
66
87
  /**
67
88
  * Sends click events to capture clicked items.
68
89
  *
@@ -72,12 +93,10 @@ export function createSearchInsightsApi(searchInsights) {
72
93
  for (var _len2 = arguments.length, params = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
73
94
  params[_key2] = arguments[_key2];
74
95
  }
75
-
76
96
  if (params.length > 0) {
77
- searchInsights.apply(void 0, ['clickedObjectIDs'].concat(params));
97
+ sendToInsights('clickedObjectIDs', mapToInsightsParamsApi(params), params[0].items);
78
98
  }
79
99
  },
80
-
81
100
  /**
82
101
  * Sends click events to capture the filters a user clicks on.
83
102
  *
@@ -87,12 +106,10 @@ export function createSearchInsightsApi(searchInsights) {
87
106
  for (var _len3 = arguments.length, params = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
88
107
  params[_key3] = arguments[_key3];
89
108
  }
90
-
91
109
  if (params.length > 0) {
92
110
  searchInsights.apply(void 0, ['clickedFilters'].concat(params));
93
111
  }
94
112
  },
95
-
96
113
  /**
97
114
  * Sends conversion events to capture a query and its clicked items.
98
115
  *
@@ -102,12 +119,10 @@ export function createSearchInsightsApi(searchInsights) {
102
119
  for (var _len4 = arguments.length, params = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
103
120
  params[_key4] = arguments[_key4];
104
121
  }
105
-
106
122
  if (params.length > 0) {
107
- searchInsights.apply(void 0, ['convertedObjectIDsAfterSearch'].concat(params));
123
+ sendToInsights('convertedObjectIDsAfterSearch', mapToInsightsParamsApi(params), params[0].items);
108
124
  }
109
125
  },
110
-
111
126
  /**
112
127
  * Sends conversion events to capture clicked items.
113
128
  *
@@ -117,12 +132,10 @@ export function createSearchInsightsApi(searchInsights) {
117
132
  for (var _len5 = arguments.length, params = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
118
133
  params[_key5] = arguments[_key5];
119
134
  }
120
-
121
135
  if (params.length > 0) {
122
- searchInsights.apply(void 0, ['convertedObjectIDs'].concat(params));
136
+ sendToInsights('convertedObjectIDs', mapToInsightsParamsApi(params), params[0].items);
123
137
  }
124
138
  },
125
-
126
139
  /**
127
140
  * Sends conversion events to capture the filters a user uses when converting.
128
141
  *
@@ -132,12 +145,10 @@ export function createSearchInsightsApi(searchInsights) {
132
145
  for (var _len6 = arguments.length, params = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
133
146
  params[_key6] = arguments[_key6];
134
147
  }
135
-
136
148
  if (params.length > 0) {
137
149
  searchInsights.apply(void 0, ['convertedFilters'].concat(params));
138
150
  }
139
151
  },
140
-
141
152
  /**
142
153
  * Sends view events to capture clicked items.
143
154
  *
@@ -147,16 +158,28 @@ export function createSearchInsightsApi(searchInsights) {
147
158
  for (var _len7 = arguments.length, params = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
148
159
  params[_key7] = arguments[_key7];
149
160
  }
150
-
151
161
  if (params.length > 0) {
152
- params.reduce(function (acc, param) {
153
- return [].concat(_toConsumableArray(acc), _toConsumableArray(chunk(param)));
154
- }, []).forEach(function (param) {
155
- return searchInsights('viewedObjectIDs', param);
162
+ params.reduce(function (acc, _ref3) {
163
+ var items = _ref3.items,
164
+ param = _objectWithoutProperties(_ref3, _excluded2);
165
+ return [].concat(_toConsumableArray(acc), _toConsumableArray(chunk(_objectSpread(_objectSpread({}, param), {}, {
166
+ objectIDs: (items === null || items === void 0 ? void 0 : items.map(function (_ref4) {
167
+ var objectID = _ref4.objectID;
168
+ return objectID;
169
+ })) || param.objectIDs
170
+ })).map(function (payload) {
171
+ return {
172
+ items: items,
173
+ payload: payload
174
+ };
175
+ })));
176
+ }, []).forEach(function (_ref5) {
177
+ var items = _ref5.items,
178
+ payload = _ref5.payload;
179
+ return sendToInsights('viewedObjectIDs', [payload], items);
156
180
  });
157
181
  }
158
182
  },
159
-
160
183
  /**
161
184
  * Sends view events to capture the filters a user uses when viewing.
162
185
  *
@@ -166,7 +189,6 @@ export function createSearchInsightsApi(searchInsights) {
166
189
  for (var _len8 = arguments.length, params = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {
167
190
  params[_key8] = arguments[_key8];
168
191
  }
169
-
170
192
  if (params.length > 0) {
171
193
  searchInsights.apply(void 0, ['viewedFilters'].concat(params));
172
194
  }
@@ -1,6 +1,6 @@
1
- import { AlgoliaInsightsHit, ViewedObjectIDsParams } from './types';
1
+ import { AlgoliaInsightsHit, InsightsParamsWithItems, ViewedObjectIDsParams } from './types';
2
2
  declare type CreateViewedEventsParams = {
3
3
  items: AlgoliaInsightsHit[];
4
4
  };
5
- export declare function createViewedEvents({ items, }: CreateViewedEventsParams): Array<Omit<ViewedObjectIDsParams, 'eventName'>>;
5
+ export declare function createViewedEvents({ items, }: CreateViewedEventsParams): Array<Omit<InsightsParamsWithItems<ViewedObjectIDsParams>, 'eventName'>>;
6
6
  export {};
@@ -1,16 +1,16 @@
1
1
  export function createViewedEvents(_ref) {
2
2
  var items = _ref.items;
3
- var objectIDsByIndexName = items.reduce(function (acc, current) {
3
+ var itemsByIndexName = items.reduce(function (acc, current) {
4
4
  var _acc$current$__autoco;
5
-
6
- acc[current.__autocomplete_indexName] = ((_acc$current$__autoco = acc[current.__autocomplete_indexName]) !== null && _acc$current$__autoco !== void 0 ? _acc$current$__autoco : []).concat(current.objectID);
5
+ acc[current.__autocomplete_indexName] = ((_acc$current$__autoco = acc[current.__autocomplete_indexName]) !== null && _acc$current$__autoco !== void 0 ? _acc$current$__autoco : []).concat(current);
7
6
  return acc;
8
7
  }, {});
9
- return Object.keys(objectIDsByIndexName).map(function (indexName) {
10
- var objectIDs = objectIDsByIndexName[indexName];
8
+ return Object.keys(itemsByIndexName).map(function (indexName) {
9
+ var items = itemsByIndexName[indexName];
11
10
  return {
12
11
  index: indexName,
13
- objectIDs: objectIDs
12
+ items: items,
13
+ algoliaSource: ['autocomplete']
14
14
  };
15
15
  });
16
16
  }
@@ -1,2 +1,2 @@
1
- export type { AutocompleteInsightsApi } from './types/AutocompleteInsightsApi';
1
+ export * from './types';
2
2
  export * from './createAlgoliaInsightsPlugin';
package/dist/esm/index.js CHANGED
@@ -1,2 +1,2 @@
1
- export * from './createAlgoliaInsightsPlugin';
2
- export {};
1
+ export * from './types';
2
+ export * from './createAlgoliaInsightsPlugin';
@@ -0,0 +1,6 @@
1
+ import type { InsightsClient } from './types';
2
+ /**
3
+ * Determines if a given insights `client` supports the optional call to `init`
4
+ * and the ability to set credentials via extra parameters when sending events.
5
+ */
6
+ export declare function isModernInsightsClient(client: InsightsClient): boolean;
@@ -0,0 +1,23 @@
1
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
2
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
3
+ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
4
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
5
+ function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
6
+ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
7
+ /**
8
+ * Determines if a given insights `client` supports the optional call to `init`
9
+ * and the ability to set credentials via extra parameters when sending events.
10
+ */
11
+ export function isModernInsightsClient(client) {
12
+ var _split$map = (client.version || '').split('.').map(Number),
13
+ _split$map2 = _slicedToArray(_split$map, 2),
14
+ major = _split$map2[0],
15
+ minor = _split$map2[1];
16
+
17
+ /* eslint-disable @typescript-eslint/camelcase */
18
+ var v3 = major >= 3;
19
+ var v2_4 = major === 2 && minor >= 4;
20
+ var v1_10 = major === 1 && minor >= 10;
21
+ return v3 || v2_4 || v1_10;
22
+ /* eslint-enable @typescript-eslint/camelcase */
23
+ }
@@ -2,4 +2,8 @@ export declare type AlgoliaInsightsHit = {
2
2
  objectID: string;
3
3
  __autocomplete_indexName: string;
4
4
  __autocomplete_queryID: string;
5
+ __autocomplete_algoliaCredentials: {
6
+ appId: string;
7
+ apiKey: string;
8
+ };
5
9
  };
@@ -1,5 +1,15 @@
1
1
  import { createSearchInsightsApi } from '../createSearchInsightsApi';
2
+ import type { AlgoliaInsightsHit } from './AlgoliaInsightsHit';
2
3
  export declare type AutocompleteInsightsApi = ReturnType<typeof createSearchInsightsApi>;
4
+ export declare type InsightsParamsWithItems<TParams extends {
5
+ objectIDs: string[];
6
+ }> = Omit<TParams, 'objectIDs'> & {
7
+ items: AlgoliaInsightsHit[];
8
+ /**
9
+ * @deprecated use `items` instead
10
+ */
11
+ objectIDs?: string[];
12
+ };
3
13
  export declare type ClickedObjectIDsAfterSearchParams = {
4
14
  eventName: string;
5
15
  index: string;