instantsearch.js 4.54.1 → 4.55.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/cjs/components/Hits/Hits.js +16 -7
  2. package/cjs/components/InfiniteHits/InfiniteHits.js +13 -2
  3. package/cjs/connectors/autocomplete/connectAutocomplete.js +1 -1
  4. package/cjs/connectors/geo-search/connectGeoSearch.js +1 -1
  5. package/cjs/connectors/hierarchical-menu/connectHierarchicalMenu.js +1 -1
  6. package/cjs/connectors/hits/connectHits.js +1 -1
  7. package/cjs/connectors/infinite-hits/connectInfiniteHits.js +39 -31
  8. package/cjs/connectors/menu/connectMenu.js +1 -1
  9. package/cjs/connectors/numeric-menu/connectNumericMenu.js +1 -1
  10. package/cjs/connectors/rating-menu/connectRatingMenu.js +7 -3
  11. package/cjs/connectors/refinement-list/connectRefinementList.js +1 -1
  12. package/cjs/connectors/toggle-refinement/connectToggleRefinement.js +14 -4
  13. package/cjs/helpers/insights.js +3 -4
  14. package/cjs/lib/InstantSearch.js +18 -2
  15. package/cjs/lib/insights/listener.js +43 -36
  16. package/cjs/lib/routers/history.js +1 -0
  17. package/cjs/lib/stateMappings/simple.js +1 -0
  18. package/cjs/lib/stateMappings/singleIndex.js +1 -0
  19. package/cjs/lib/utils/createSendEventForFacet.js +12 -2
  20. package/cjs/lib/utils/createSendEventForHits.js +34 -11
  21. package/cjs/lib/version.js +1 -1
  22. package/cjs/middlewares/createInsightsMiddleware.js +135 -33
  23. package/cjs/middlewares/createMetadataMiddleware.js +17 -5
  24. package/cjs/middlewares/createRouterMiddleware.js +5 -1
  25. package/cjs/widgets/hits/hits.js +1 -2
  26. package/cjs/widgets/infinite-hits/infinite-hits.js +1 -2
  27. package/dist/instantsearch.development.d.ts +67 -8
  28. package/dist/instantsearch.development.js +433 -251
  29. package/dist/instantsearch.development.js.map +1 -1
  30. package/dist/instantsearch.production.d.ts +67 -8
  31. package/dist/instantsearch.production.min.d.ts +67 -8
  32. package/dist/instantsearch.production.min.js +2 -2
  33. package/dist/instantsearch.production.min.js.map +1 -1
  34. package/es/components/Hits/Hits.d.ts +5 -5
  35. package/es/components/Hits/Hits.js +15 -5
  36. package/es/components/InfiniteHits/InfiniteHits.d.ts +3 -2
  37. package/es/components/InfiniteHits/InfiniteHits.js +13 -2
  38. package/es/connectors/autocomplete/connectAutocomplete.js +1 -1
  39. package/es/connectors/geo-search/connectGeoSearch.js +1 -1
  40. package/es/connectors/hierarchical-menu/connectHierarchicalMenu.js +1 -1
  41. package/es/connectors/hits/connectHits.js +1 -1
  42. package/es/connectors/infinite-hits/connectInfiniteHits.js +39 -31
  43. package/es/connectors/menu/connectMenu.js +1 -1
  44. package/es/connectors/numeric-menu/connectNumericMenu.js +1 -1
  45. package/es/connectors/rating-menu/connectRatingMenu.js +7 -3
  46. package/es/connectors/refinement-list/connectRefinementList.js +1 -1
  47. package/es/connectors/toggle-refinement/connectToggleRefinement.js +13 -3
  48. package/es/helpers/insights.d.ts +2 -1
  49. package/es/helpers/insights.js +3 -3
  50. package/es/lib/InstantSearch.d.ts +11 -1
  51. package/es/lib/InstantSearch.js +18 -2
  52. package/es/lib/insights/listener.d.ts +10 -6
  53. package/es/lib/insights/listener.js +42 -36
  54. package/es/lib/routers/history.d.ts +1 -0
  55. package/es/lib/routers/history.js +1 -0
  56. package/es/lib/stateMappings/simple.js +1 -0
  57. package/es/lib/stateMappings/singleIndex.js +1 -0
  58. package/es/lib/utils/createSendEventForFacet.js +12 -2
  59. package/es/lib/utils/createSendEventForHits.d.ts +8 -0
  60. package/es/lib/utils/createSendEventForHits.js +33 -11
  61. package/es/lib/version.d.ts +1 -1
  62. package/es/lib/version.js +1 -1
  63. package/es/middlewares/createInsightsMiddleware.d.ts +12 -12
  64. package/es/middlewares/createInsightsMiddleware.js +136 -34
  65. package/es/middlewares/createMetadataMiddleware.d.ts +3 -1
  66. package/es/middlewares/createMetadataMiddleware.js +17 -5
  67. package/es/middlewares/createRouterMiddleware.js +5 -1
  68. package/es/types/insights.d.ts +19 -1
  69. package/es/types/middleware.d.ts +16 -0
  70. package/es/types/router.d.ts +8 -0
  71. package/es/widgets/hits/hits.js +2 -3
  72. package/es/widgets/infinite-hits/infinite-hits.js +2 -3
  73. package/package.json +6 -6
@@ -1,7 +1,34 @@
1
1
  import { h } from 'preact';
2
- import { readDataAttributes, hasDataAttributes } from "../../helpers/insights.js";
3
- import { deserializePayload } from "../utils/index.js";
4
- var findInsightsTarget = function findInsightsTarget(startElement, endElement, validator) {
2
+ import { readDataAttributes } from "../../helpers/insights.js";
3
+ import { deserializePayload, warning } from "../utils/index.js";
4
+ export var createInsightsEventHandler = function createInsightsEventHandler(_ref) {
5
+ var insights = _ref.insights,
6
+ sendEvent = _ref.sendEvent;
7
+ return function (event) {
8
+ // new way, e.g. bindEvent("click", hit, "Hit clicked")
9
+ var insightsThroughSendEvent = findInsightsTarget(event.target, event.currentTarget, function (element) {
10
+ return element.hasAttribute('data-insights-event');
11
+ });
12
+ if (insightsThroughSendEvent) {
13
+ var payload = parseInsightsEvent(insightsThroughSendEvent);
14
+ payload.forEach(function (single) {
15
+ return sendEvent(single);
16
+ });
17
+ }
18
+
19
+ // old way, e.g. instantsearch.insights("clickedObjectIDsAfterSearch", { .. })
20
+ var insightsThroughFunction = findInsightsTarget(event.target, event.currentTarget, function (element) {
21
+ return element.hasAttribute('data-insights-method') && element.hasAttribute('data-insights-payload');
22
+ });
23
+ if (insightsThroughFunction) {
24
+ var _readDataAttributes = readDataAttributes(insightsThroughFunction),
25
+ method = _readDataAttributes.method,
26
+ _payload = _readDataAttributes.payload;
27
+ insights(method, _payload);
28
+ }
29
+ };
30
+ };
31
+ function findInsightsTarget(startElement, endElement, validator) {
5
32
  var element = startElement;
6
33
  while (element && !validator(element)) {
7
34
  if (element === endElement) {
@@ -10,8 +37,8 @@ var findInsightsTarget = function findInsightsTarget(startElement, endElement, v
10
37
  element = element.parentElement;
11
38
  }
12
39
  return element;
13
- };
14
- var parseInsightsEvent = function parseInsightsEvent(element) {
40
+ }
41
+ function parseInsightsEvent(element) {
15
42
  var serializedPayload = element.getAttribute('data-insights-event');
16
43
  if (typeof serializedPayload !== 'string') {
17
44
  throw new Error('The insights middleware expects `data-insights-event` to be a base64-encoded JSON string.');
@@ -21,38 +48,17 @@ var parseInsightsEvent = function parseInsightsEvent(element) {
21
48
  } catch (error) {
22
49
  throw new Error('The insights middleware was unable to parse `data-insights-event`.');
23
50
  }
24
- };
25
- var insightsListener = function insightsListener(BaseComponent) {
26
- function WithInsightsListener(props) {
27
- var handleClick = function handleClick(event) {
28
- if (props.sendEvent) {
29
- // new way with insights middleware
30
- var targetWithEvent = findInsightsTarget(event.target, event.currentTarget, function (element) {
31
- return element.hasAttribute('data-insights-event');
32
- });
33
- if (targetWithEvent) {
34
- var payload = parseInsightsEvent(targetWithEvent);
35
- payload.forEach(function (single) {
36
- return props.sendEvent(single);
37
- });
38
- }
39
- }
51
+ }
40
52
 
41
- // old way, e.g. instantsearch.insights("clickedObjectIDsAfterSearch", { .. })
42
- var insightsTarget = findInsightsTarget(event.target, event.currentTarget, function (element) {
43
- return hasDataAttributes(element);
44
- });
45
- if (insightsTarget) {
46
- var _readDataAttributes = readDataAttributes(insightsTarget),
47
- method = _readDataAttributes.method,
48
- _payload = _readDataAttributes.payload;
49
- props.insights(method, _payload);
50
- }
51
- };
53
+ /**
54
+ * @deprecated use `sendEvent` directly instead
55
+ */
56
+ export default function withInsightsListener(BaseComponent) {
57
+ process.env.NODE_ENV === 'development' ? warning(false, 'The `withInsightsListener` function is deprecated and will be removed in the next major version. Please use `sendEvent` directly instead.') : void 0;
58
+ return function WithInsightsListener(props) {
59
+ var handleClick = createInsightsEventHandler(props);
52
60
  return h("div", {
53
61
  onClick: handleClick
54
62
  }, h(BaseComponent, props));
55
- }
56
- return WithInsightsListener;
57
- };
58
- export default insightsListener;
63
+ };
64
+ }
@@ -20,6 +20,7 @@ export type BrowserHistoryArgs<TRouteState> = {
20
20
  push?: (url: string) => void;
21
21
  };
22
22
  declare class BrowserHistory<TRouteState> implements Router<TRouteState> {
23
+ $$type: string;
23
24
  /**
24
25
  * Transforms a UI state into a title for the page.
25
26
  */
@@ -31,6 +31,7 @@ var BrowserHistory = /*#__PURE__*/function () {
31
31
  dispose = _ref.dispose,
32
32
  push = _ref.push;
33
33
  _classCallCheck(this, BrowserHistory);
34
+ _defineProperty(this, "$$type", 'ais.browser');
34
35
  _defineProperty(this, "windowTitle", void 0);
35
36
  _defineProperty(this, "writeDelay", void 0);
36
37
  _defineProperty(this, "_createURL", void 0);
@@ -18,6 +18,7 @@ function getIndexStateWithoutConfigure(uiState) {
18
18
  // which excludes "configure" as this function does.
19
19
  export default function simpleStateMapping() {
20
20
  return {
21
+ $$type: 'ais.simple',
21
22
  stateToRoute: function stateToRoute(uiState) {
22
23
  return Object.keys(uiState).reduce(function (state, indexId) {
23
24
  return _objectSpread(_objectSpread({}, state), {}, _defineProperty({}, indexId, getIndexStateWithoutConfigure(uiState[indexId])));
@@ -12,6 +12,7 @@ function getIndexStateWithoutConfigure(uiState) {
12
12
  }
13
13
  export default function singleIndexStateMapping(indexName) {
14
14
  return {
15
+ $$type: 'ais.singleIndex',
15
16
  stateToRoute: function stateToRoute(uiState) {
16
17
  return getIndexStateWithoutConfigure(uiState[indexName] || {});
17
18
  },
@@ -1,4 +1,10 @@
1
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); }
2
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
3
+ 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."); }
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); }
5
+ 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; }
6
+ 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; } }
7
+ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
2
8
  import { isFacetRefined } from "./isFacetRefined.js";
3
9
  export function createSendEventForFacet(_ref) {
4
10
  var instantSearchInstance = _ref.instantSearchInstance,
@@ -9,10 +15,13 @@ export function createSendEventForFacet(_ref) {
9
15
  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
10
16
  args[_key] = arguments[_key];
11
17
  }
12
- var eventType = args[0],
13
- facetValue = args[1],
18
+ var facetValue = args[1],
14
19
  _args$ = args[2],
15
20
  eventName = _args$ === void 0 ? 'Filter Applied' : _args$;
21
+ var _args$0$split = args[0].split(':'),
22
+ _args$0$split2 = _slicedToArray(_args$0$split, 2),
23
+ eventType = _args$0$split2[0],
24
+ eventModifier = _args$0$split2[1];
16
25
  var attribute = typeof attr === 'string' ? attr : attr(facetValue);
17
26
  if (args.length === 1 && _typeof(args[0]) === 'object') {
18
27
  instantSearchInstance.sendEventToInsights(args[0]);
@@ -23,6 +32,7 @@ export function createSendEventForFacet(_ref) {
23
32
  insightsMethod: 'clickedFilters',
24
33
  widgetType: widgetType,
25
34
  eventType: eventType,
35
+ eventModifier: eventModifier,
26
36
  payload: {
27
37
  eventName: eventName,
28
38
  index: helper.getIndex(),
@@ -1,3 +1,4 @@
1
+ import type { InsightsEvent } from '../../middlewares/createInsightsMiddleware';
1
2
  import type { InstantSearch, Hit } from '../../types';
2
3
  type BuiltInSendEventForHits = (eventType: string, hits: Hit | Hit[], eventName?: string) => void;
3
4
  type CustomSendEventForHits = (customPayload: any) => void;
@@ -5,6 +6,13 @@ export type SendEventForHits = BuiltInSendEventForHits & CustomSendEventForHits;
5
6
  export type BuiltInBindEventForHits = (eventType: string, hits: Hit | Hit[], eventName?: string) => string;
6
7
  export type CustomBindEventForHits = (customPayload: any) => string;
7
8
  export type BindEventForHits = BuiltInBindEventForHits & CustomBindEventForHits;
9
+ export declare function _buildEventPayloadsForHits({ index, widgetType, methodName, args, instantSearchInstance, }: {
10
+ widgetType: string;
11
+ index: string;
12
+ methodName: 'sendEvent' | 'bindEvent';
13
+ args: any[];
14
+ instantSearchInstance: InstantSearch;
15
+ }): InsightsEvent[];
8
16
  export declare function createSendEventForHits({ instantSearchInstance, index, widgetType, }: {
9
17
  instantSearchInstance: InstantSearch;
10
18
  index: string;
@@ -1,3 +1,9 @@
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; }
1
7
  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); }
2
8
  import { serializePayload } from "./serializer.js";
3
9
  function chunk(arr) {
@@ -8,7 +14,7 @@ function chunk(arr) {
8
14
  }
9
15
  return chunks;
10
16
  }
11
- var buildPayloads = function buildPayloads(_ref) {
17
+ export function _buildEventPayloadsForHits(_ref) {
12
18
  var index = _ref.index,
13
19
  widgetType = _ref.widgetType,
14
20
  methodName = _ref.methodName,
@@ -18,7 +24,10 @@ var buildPayloads = function buildPayloads(_ref) {
18
24
  if (args.length === 1 && _typeof(args[0]) === 'object') {
19
25
  return [args[0]];
20
26
  }
21
- var eventType = args[0];
27
+ var _args$0$split = args[0].split(':'),
28
+ _args$0$split2 = _slicedToArray(_args$0$split, 2),
29
+ eventType = _args$0$split2[0],
30
+ eventModifier = _args$0$split2[1];
22
31
  var hits = args[1];
23
32
  var eventName = args[2];
24
33
  if (!hits) {
@@ -65,7 +74,8 @@ var buildPayloads = function buildPayloads(_ref) {
65
74
  index: index,
66
75
  objectIDs: objectIDsByChunk[i]
67
76
  },
68
- hits: batch
77
+ hits: batch,
78
+ eventModifier: eventModifier
69
79
  };
70
80
  });
71
81
  } else if (eventType === 'click') {
@@ -75,13 +85,14 @@ var buildPayloads = function buildPayloads(_ref) {
75
85
  widgetType: widgetType,
76
86
  eventType: eventType,
77
87
  payload: {
78
- eventName: eventName,
88
+ eventName: eventName || 'Hit Clicked',
79
89
  index: index,
80
90
  queryID: queryID,
81
91
  objectIDs: objectIDsByChunk[i],
82
92
  positions: positionsByChunk[i]
83
93
  },
84
- hits: batch
94
+ hits: batch,
95
+ eventModifier: eventModifier
85
96
  };
86
97
  });
87
98
  } else if (eventType === 'conversion') {
@@ -91,12 +102,13 @@ var buildPayloads = function buildPayloads(_ref) {
91
102
  widgetType: widgetType,
92
103
  eventType: eventType,
93
104
  payload: {
94
- eventName: eventName,
105
+ eventName: eventName || 'Hit Converted',
95
106
  index: index,
96
107
  queryID: queryID,
97
108
  objectIDs: objectIDsByChunk[i]
98
109
  },
99
- hits: batch
110
+ hits: batch,
111
+ eventModifier: eventModifier
100
112
  };
101
113
  });
102
114
  } else if (process.env.NODE_ENV === 'development') {
@@ -104,16 +116,18 @@ var buildPayloads = function buildPayloads(_ref) {
104
116
  } else {
105
117
  return [];
106
118
  }
107
- };
119
+ }
108
120
  export function createSendEventForHits(_ref2) {
109
121
  var instantSearchInstance = _ref2.instantSearchInstance,
110
122
  index = _ref2.index,
111
123
  widgetType = _ref2.widgetType;
124
+ var sentEvents = {};
125
+ var timer = undefined;
112
126
  var sendEventForHits = function sendEventForHits() {
113
127
  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
114
128
  args[_key] = arguments[_key];
115
129
  }
116
- var payloads = buildPayloads({
130
+ var payloads = _buildEventPayloadsForHits({
117
131
  widgetType: widgetType,
118
132
  index: index,
119
133
  methodName: 'sendEvent',
@@ -121,8 +135,16 @@ export function createSendEventForHits(_ref2) {
121
135
  instantSearchInstance: instantSearchInstance
122
136
  });
123
137
  payloads.forEach(function (payload) {
124
- return instantSearchInstance.sendEventToInsights(payload);
138
+ if (payload.eventType === 'click' && payload.eventModifier === 'internal' && sentEvents[payload.eventType]) {
139
+ return;
140
+ }
141
+ sentEvents[payload.eventType] = true;
142
+ instantSearchInstance.sendEventToInsights(payload);
125
143
  });
144
+ clearTimeout(timer);
145
+ timer = setTimeout(function () {
146
+ sentEvents = {};
147
+ }, 0);
126
148
  };
127
149
  return sendEventForHits;
128
150
  }
@@ -134,7 +156,7 @@ export function createBindEventForHits(_ref3) {
134
156
  for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
135
157
  args[_key2] = arguments[_key2];
136
158
  }
137
- var payloads = buildPayloads({
159
+ var payloads = _buildEventPayloadsForHits({
138
160
  widgetType: widgetType,
139
161
  index: index,
140
162
  methodName: 'bindEvent',
@@ -1,2 +1,2 @@
1
- declare const _default: "4.54.1";
1
+ declare const _default: "4.55.0";
2
2
  export default _default;
package/es/lib/version.js CHANGED
@@ -1 +1 @@
1
- export default '4.54.1';
1
+ export default '4.55.0';
@@ -1,21 +1,21 @@
1
- import type { InsightsClient, InsightsClientMethod, InternalMiddleware, Hit } from '../types';
2
- export type InsightsEvent = {
3
- insightsMethod?: InsightsClientMethod;
4
- payload: any;
5
- widgetType: string;
6
- eventType: string;
7
- hits?: Hit[];
8
- attribute?: string;
9
- };
10
- export type InsightsProps<TInsightsClient extends null | InsightsClient = InsightsClient | null> = {
11
- insightsClient: TInsightsClient;
1
+ import type { InsightsClient, InsightsEvent as _InsightsEvent, InsightsMethod, InternalMiddleware } from '../types';
2
+ type ProvidedInsightsClient = InsightsClient | null | undefined;
3
+ export type InsightsEvent<TMethod extends InsightsMethod = InsightsMethod> = _InsightsEvent<TMethod>;
4
+ export type InsightsProps<TInsightsClient extends ProvidedInsightsClient = ProvidedInsightsClient> = {
5
+ insightsClient?: TInsightsClient;
12
6
  insightsInitParams?: {
13
7
  userHasOptedOut?: boolean;
14
8
  useCookie?: boolean;
9
+ anonymousUserToken?: boolean;
15
10
  cookieDuration?: number;
16
11
  region?: 'de' | 'us';
17
12
  };
18
13
  onEvent?: (event: InsightsEvent, insightsClient: TInsightsClient) => void;
19
14
  };
15
+ export type InsightsClientWithGlobals = InsightsClient & {
16
+ shouldAddScript?: boolean;
17
+ version?: string;
18
+ };
20
19
  export type CreateInsightsMiddleware = typeof createInsightsMiddleware;
21
- export declare function createInsightsMiddleware<TInsightsClient extends null | InsightsClient>(props: InsightsProps<TInsightsClient>): InternalMiddleware;
20
+ export declare function createInsightsMiddleware<TInsightsClient extends ProvidedInsightsClient>(props?: InsightsProps<TInsightsClient>): InternalMiddleware;
21
+ export {};
@@ -6,37 +6,71 @@ function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _ty
6
6
  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); }
7
7
  function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
8
8
  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."); }
9
- 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); }
10
- 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; }
11
9
  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; } }
12
10
  function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
11
+ function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
12
+ 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."); }
13
+ 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); }
14
+ function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
15
+ function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
16
+ 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
17
  import { getInsightsAnonymousUserTokenInternal } from "../helpers/index.js";
14
- import { warning, noop, getAppIdAndApiKey, find } from "../lib/utils/index.js";
15
- export function createInsightsMiddleware(props) {
16
- var _ref = props || {},
17
- _insightsClient = _ref.insightsClient,
18
- insightsInitParams = _ref.insightsInitParams,
19
- onEvent = _ref.onEvent;
20
- if (_insightsClient !== null && !_insightsClient) {
21
- if (process.env.NODE_ENV === 'development') {
22
- throw new Error("The `insightsClient` option is required if you want userToken to be automatically set in search calls. If you don't want this behaviour, set it to `null`.");
23
- } else {
24
- throw new Error('The `insightsClient` option is required. To disable, set it to `null`.');
25
- }
18
+ import { warning, noop, getAppIdAndApiKey, find, safelyRunOnBrowser } from "../lib/utils/index.js";
19
+ var ALGOLIA_INSIGHTS_VERSION = '2.6.0';
20
+ var ALGOLIA_INSIGHTS_SRC = "https://cdn.jsdelivr.net/npm/search-insights@".concat(ALGOLIA_INSIGHTS_VERSION, "/dist/search-insights.min.js");
21
+ export function createInsightsMiddleware() {
22
+ var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
23
+ var _insightsClient = props.insightsClient,
24
+ insightsInitParams = props.insightsInitParams,
25
+ onEvent = props.onEvent,
26
+ _props$$$internal = props.$$internal,
27
+ $$internal = _props$$$internal === void 0 ? false : _props$$$internal;
28
+ var potentialInsightsClient = _insightsClient;
29
+ if (!_insightsClient && _insightsClient !== null) {
30
+ safelyRunOnBrowser(function (_ref) {
31
+ var window = _ref.window;
32
+ var pointer = window.AlgoliaAnalyticsObject || 'aa';
33
+ if (typeof pointer === 'string') {
34
+ potentialInsightsClient = window[pointer];
35
+ }
36
+ if (!potentialInsightsClient) {
37
+ window.AlgoliaAnalyticsObject = pointer;
38
+ if (!window[pointer]) {
39
+ window[pointer] = function () {
40
+ if (!window[pointer].queue) {
41
+ window[pointer].queue = [];
42
+ }
43
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
44
+ args[_key] = arguments[_key];
45
+ }
46
+ window[pointer].queue.push(args);
47
+ };
48
+ window[pointer].version = ALGOLIA_INSIGHTS_VERSION;
49
+ window[pointer].shouldAddScript = true;
50
+ }
51
+ potentialInsightsClient = window[pointer];
52
+ }
53
+ });
26
54
  }
27
- var hasInsightsClient = Boolean(_insightsClient);
28
- var insightsClient = _insightsClient === null ? noop : _insightsClient;
55
+ // if still no insightsClient was found, we use a noop
56
+ var insightsClient = potentialInsightsClient || noop;
29
57
  return function (_ref2) {
30
58
  var instantSearchInstance = _ref2.instantSearchInstance;
59
+ // remove existing default insights middleware
60
+ // user-provided insights middleware takes precedence
61
+ var existingInsightsMiddlewares = instantSearchInstance.middleware.filter(function (m) {
62
+ return m.instance.$$type === 'ais.insights' && m.instance.$$internal;
63
+ }).map(function (m) {
64
+ return m.creator;
65
+ });
66
+ instantSearchInstance.unuse.apply(instantSearchInstance, _toConsumableArray(existingInsightsMiddlewares));
31
67
  var _getAppIdAndApiKey = getAppIdAndApiKey(instantSearchInstance.client),
32
68
  _getAppIdAndApiKey2 = _slicedToArray(_getAppIdAndApiKey, 2),
33
69
  appId = _getAppIdAndApiKey2[0],
34
70
  apiKey = _getAppIdAndApiKey2[1];
35
71
 
36
72
  // search-insights.js also throws an error so dev-only clarification is sufficient
37
- if (process.env.NODE_ENV === 'development' && !(appId && apiKey)) {
38
- throw new Error('[insights middleware]: could not extract Algolia credentials from searchClient');
39
- }
73
+ process.env.NODE_ENV === 'development' ? warning(Boolean(appId && apiKey), 'could not extract Algolia credentials from searchClient in insights middleware.') : void 0;
40
74
  var queuedUserToken = undefined;
41
75
  var userTokenBeforeInit = undefined;
42
76
  if (Array.isArray(insightsClient.queue)) {
@@ -66,15 +100,39 @@ export function createInsightsMiddleware(props) {
66
100
  // Otherwise, the `init` call might override it with anonymous user token.
67
101
  userTokenBeforeInit = userToken;
68
102
  });
69
- insightsClient('init', _objectSpread({
70
- appId: appId,
71
- apiKey: apiKey
72
- }, insightsInitParams));
103
+
104
+ // Only `init` if the `insightsInitParams` option is passed or
105
+ // if the `insightsClient` version doesn't supports optional `init` calling.
106
+ if (insightsInitParams || !isModernInsightsClient(insightsClient)) {
107
+ insightsClient('init', _objectSpread({
108
+ appId: appId,
109
+ apiKey: apiKey,
110
+ partial: true
111
+ }, insightsInitParams));
112
+ }
73
113
  var initialParameters;
74
114
  var helper;
75
115
  return {
116
+ $$type: 'ais.insights',
117
+ $$internal: $$internal,
76
118
  onStateChange: function onStateChange() {},
77
- subscribe: function subscribe() {},
119
+ subscribe: function subscribe() {
120
+ if (!insightsClient.shouldAddScript) return;
121
+ var errorMessage = '[insights middleware]: could not load search-insights.js. Please load it manually following https://alg.li/insights-init';
122
+ try {
123
+ var script = document.createElement('script');
124
+ script.async = true;
125
+ script.src = ALGOLIA_INSIGHTS_SRC;
126
+ script.onerror = function () {
127
+ instantSearchInstance.emit('error', new Error(errorMessage));
128
+ };
129
+ document.body.appendChild(script);
130
+ insightsClient.shouldAddScript = false;
131
+ } catch (cause) {
132
+ insightsClient.shouldAddScript = false;
133
+ instantSearchInstance.emit('error', new Error(errorMessage));
134
+ }
135
+ },
78
136
  started: function started() {
79
137
  insightsClient('addAlgoliaAgent', 'insights-middleware');
80
138
  helper = instantSearchInstance.helper;
@@ -85,15 +143,23 @@ export function createInsightsMiddleware(props) {
85
143
  helper.overrideStateWithoutTriggeringChangeEvent(_objectSpread(_objectSpread({}, helper.state), {}, {
86
144
  clickAnalytics: true
87
145
  }));
88
- instantSearchInstance.scheduleSearch();
146
+ if (!$$internal) {
147
+ instantSearchInstance.scheduleSearch();
148
+ }
89
149
  var setUserTokenToSearch = function setUserTokenToSearch(userToken) {
150
+ if (!userToken) {
151
+ return;
152
+ }
153
+ var existingToken = helper.state.userToken;
90
154
  helper.overrideStateWithoutTriggeringChangeEvent(_objectSpread(_objectSpread({}, helper.state), {}, {
91
155
  userToken: userToken
92
156
  }));
93
- instantSearchInstance.scheduleSearch();
157
+ if (existingToken && existingToken !== userToken) {
158
+ instantSearchInstance.scheduleSearch();
159
+ }
94
160
  };
95
161
  var anonymousUserToken = getInsightsAnonymousUserTokenInternal();
96
- if (hasInsightsClient && anonymousUserToken) {
162
+ if (anonymousUserToken) {
97
163
  // When `aa('init', { ... })` is called, it creates an anonymous user token in cookie.
98
164
  // We can set it as userToken.
99
165
  setUserTokenToSearch(anonymousUserToken);
@@ -102,8 +168,10 @@ export function createInsightsMiddleware(props) {
102
168
  // We consider the `userToken` coming from a `init` call to have a higher
103
169
  // importance than the one coming from the queue.
104
170
  if (userTokenBeforeInit) {
171
+ setUserTokenToSearch(userTokenBeforeInit);
105
172
  insightsClient('setUserToken', userTokenBeforeInit);
106
173
  } else if (queuedUserToken) {
174
+ setUserTokenToSearch(queuedUserToken);
107
175
  insightsClient('setUserToken', queuedUserToken);
108
176
  }
109
177
 
@@ -111,16 +179,31 @@ export function createInsightsMiddleware(props) {
111
179
  insightsClient('onUserTokenChange', setUserTokenToSearch, {
112
180
  immediate: true
113
181
  });
182
+ var insightsClientWithLocalCredentials = insightsClient;
183
+ if (isModernInsightsClient(insightsClient)) {
184
+ insightsClientWithLocalCredentials = function insightsClientWithLocalCredentials(method, payload) {
185
+ var extraParams = {
186
+ headers: {
187
+ 'X-Algolia-Application-Id': appId,
188
+ 'X-Algolia-API-Key': apiKey
189
+ }
190
+ };
191
+
192
+ // @ts-ignore we are calling this only when we know that the client actually is correct
193
+ return insightsClient(method, payload, extraParams);
194
+ };
195
+ }
114
196
  instantSearchInstance.sendEventToInsights = function (event) {
115
197
  if (onEvent) {
116
- onEvent(event, _insightsClient);
198
+ onEvent(event, insightsClientWithLocalCredentials);
117
199
  } else if (event.insightsMethod) {
118
- var hasUserToken = Boolean(helper.state.userToken);
119
- if (hasUserToken) {
120
- insightsClient(event.insightsMethod, event.payload);
121
- } else {
122
- process.env.NODE_ENV === 'development' ? warning(false, "\nCannot send event to Algolia Insights because `userToken` is not set.\n\nSee documentation: https://www.algolia.com/doc/guides/building-search-ui/going-further/send-insights-events/js/#setting-the-usertoken\n") : void 0;
200
+ // Source is used to differentiate events sent by instantsearch from those sent manually.
201
+ event.payload.algoliaSource = ['instantsearch'];
202
+ if (event.eventModifier === 'internal') {
203
+ event.payload.algoliaSource.push('instantsearch-internal');
123
204
  }
205
+ insightsClientWithLocalCredentials(event.insightsMethod, event.payload);
206
+ process.env.NODE_ENV === 'development' ? warning(Boolean(helper.state.userToken), "\nCannot send event to Algolia Insights because `userToken` is not set.\n\nSee documentation: https://www.algolia.com/doc/guides/building-search-ui/going-further/send-insights-events/js/#setting-the-usertoken\n") : void 0;
124
207
  } else {
125
208
  process.env.NODE_ENV === 'development' ? warning(false, 'Cannot send event to Algolia Insights because `insightsMethod` option is missing.') : void 0;
126
209
  }
@@ -130,10 +213,29 @@ export function createInsightsMiddleware(props) {
130
213
  insightsClient('onUserTokenChange', undefined);
131
214
  instantSearchInstance.sendEventToInsights = noop;
132
215
  if (helper && initialParameters) {
133
- helper.setState(_objectSpread(_objectSpread({}, helper.state), initialParameters));
216
+ helper.overrideStateWithoutTriggeringChangeEvent(_objectSpread(_objectSpread({}, helper.state), initialParameters));
134
217
  instantSearchInstance.scheduleSearch();
135
218
  }
136
219
  }
137
220
  };
138
221
  };
222
+ }
223
+
224
+ /**
225
+ * Determines if a given insights `client` supports the optional call to `init`
226
+ * and the ability to set credentials via extra parameters when sending events.
227
+ */
228
+ function isModernInsightsClient(client) {
229
+ var _split$map = (client.version || '').split('.').map(Number),
230
+ _split$map2 = _slicedToArray(_split$map, 2),
231
+ major = _split$map2[0],
232
+ minor = _split$map2[1];
233
+
234
+ /* eslint-disable @typescript-eslint/naming-convention */
235
+ var v3 = major >= 3;
236
+ var v2_6 = major === 2 && minor >= 6;
237
+ var v1_10 = major === 1 && minor >= 10;
238
+ /* eslint-enable @typescript-eslint/naming-convention */
239
+
240
+ return v3 || v2_6 || v1_10;
139
241
  }
@@ -7,4 +7,6 @@ export declare function isMetadataEnabled(): boolean;
7
7
  * - widget name
8
8
  * - connector name
9
9
  */
10
- export declare function createMetadataMiddleware(): InternalMiddleware;
10
+ export declare function createMetadataMiddleware({ $$internal, }?: {
11
+ $$internal?: boolean;
12
+ }): InternalMiddleware;