@algolia/recommend 5.2.2 → 5.2.4-beta.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.
Files changed (221) hide show
  1. package/README.md +2 -2
  2. package/dist/browser.d.ts +1300 -0
  3. package/dist/builds/browser.js +398 -0
  4. package/dist/builds/browser.js.map +1 -0
  5. package/dist/builds/browser.min.js +2 -0
  6. package/dist/builds/browser.min.js.map +1 -0
  7. package/dist/builds/browser.umd.js +12 -0
  8. package/dist/builds/node.cjs +416 -0
  9. package/dist/builds/node.cjs.map +1 -0
  10. package/dist/builds/node.js +396 -0
  11. package/dist/builds/node.js.map +1 -0
  12. package/dist/node.d.cts +1300 -0
  13. package/dist/node.d.ts +1300 -0
  14. package/dist/src/recommendClient.cjs +385 -0
  15. package/dist/src/recommendClient.cjs.map +1 -0
  16. package/dist/src/recommendClient.js +359 -0
  17. package/dist/src/recommendClient.js.map +1 -0
  18. package/index.d.ts +1 -1
  19. package/index.js +1 -1
  20. package/model/booleanString.ts +3 -0
  21. package/model/ignorePlurals.ts +2 -1
  22. package/model/index.ts +1 -0
  23. package/package.json +27 -27
  24. package/dist/builds/browser.d.ts +0 -24
  25. package/dist/builds/browser.d.ts.map +0 -1
  26. package/dist/builds/node.d.ts +0 -24
  27. package/dist/builds/node.d.ts.map +0 -1
  28. package/dist/model/advancedSyntaxFeatures.d.ts +0 -2
  29. package/dist/model/advancedSyntaxFeatures.d.ts.map +0 -1
  30. package/dist/model/alternativesAsExact.d.ts +0 -2
  31. package/dist/model/alternativesAsExact.d.ts.map +0 -1
  32. package/dist/model/aroundPrecision.d.ts +0 -6
  33. package/dist/model/aroundPrecision.d.ts.map +0 -1
  34. package/dist/model/aroundRadius.d.ts +0 -6
  35. package/dist/model/aroundRadius.d.ts.map +0 -1
  36. package/dist/model/aroundRadiusAll.d.ts +0 -5
  37. package/dist/model/aroundRadiusAll.d.ts.map +0 -1
  38. package/dist/model/autoFacetFilter.d.ts +0 -14
  39. package/dist/model/autoFacetFilter.d.ts.map +0 -1
  40. package/dist/model/baseRecommendRequest.d.ts +0 -17
  41. package/dist/model/baseRecommendRequest.d.ts.map +0 -1
  42. package/dist/model/baseSearchParams.d.ts +0 -4
  43. package/dist/model/baseSearchParams.d.ts.map +0 -1
  44. package/dist/model/baseSearchParamsWithoutQuery.d.ts +0 -116
  45. package/dist/model/baseSearchParamsWithoutQuery.d.ts.map +0 -1
  46. package/dist/model/baseSearchResponse.d.ts +0 -94
  47. package/dist/model/baseSearchResponse.d.ts.map +0 -1
  48. package/dist/model/boughtTogetherQuery.d.ts +0 -4
  49. package/dist/model/boughtTogetherQuery.d.ts.map +0 -1
  50. package/dist/model/clientMethodProps.d.ts +0 -135
  51. package/dist/model/clientMethodProps.d.ts.map +0 -1
  52. package/dist/model/condition.d.ts +0 -14
  53. package/dist/model/condition.d.ts.map +0 -1
  54. package/dist/model/consequence.d.ts +0 -18
  55. package/dist/model/consequence.d.ts.map +0 -1
  56. package/dist/model/deletedAtResponse.d.ts +0 -14
  57. package/dist/model/deletedAtResponse.d.ts.map +0 -1
  58. package/dist/model/distinct.d.ts +0 -5
  59. package/dist/model/distinct.d.ts.map +0 -1
  60. package/dist/model/errorBase.d.ts +0 -7
  61. package/dist/model/errorBase.d.ts.map +0 -1
  62. package/dist/model/exactOnSingleWordQuery.d.ts +0 -5
  63. package/dist/model/exactOnSingleWordQuery.d.ts.map +0 -1
  64. package/dist/model/exhaustive.d.ts +0 -26
  65. package/dist/model/exhaustive.d.ts.map +0 -1
  66. package/dist/model/facetFilters.d.ts +0 -5
  67. package/dist/model/facetFilters.d.ts.map +0 -1
  68. package/dist/model/facetOrdering.d.ts +0 -13
  69. package/dist/model/facetOrdering.d.ts.map +0 -1
  70. package/dist/model/facetStats.d.ts +0 -19
  71. package/dist/model/facetStats.d.ts.map +0 -1
  72. package/dist/model/facets.d.ts +0 -10
  73. package/dist/model/facets.d.ts.map +0 -1
  74. package/dist/model/fallbackParams.d.ts +0 -3
  75. package/dist/model/fallbackParams.d.ts.map +0 -1
  76. package/dist/model/fbtModel.d.ts +0 -5
  77. package/dist/model/fbtModel.d.ts.map +0 -1
  78. package/dist/model/frequentlyBoughtTogether.d.ts +0 -9
  79. package/dist/model/frequentlyBoughtTogether.d.ts.map +0 -1
  80. package/dist/model/getRecommendTaskResponse.d.ts +0 -5
  81. package/dist/model/getRecommendTaskResponse.d.ts.map +0 -1
  82. package/dist/model/getRecommendationsParams.d.ts +0 -11
  83. package/dist/model/getRecommendationsParams.d.ts.map +0 -1
  84. package/dist/model/getRecommendationsResponse.d.ts +0 -5
  85. package/dist/model/getRecommendationsResponse.d.ts.map +0 -1
  86. package/dist/model/hideConsequenceObject.d.ts +0 -10
  87. package/dist/model/hideConsequenceObject.d.ts.map +0 -1
  88. package/dist/model/highlightResult.d.ts +0 -5
  89. package/dist/model/highlightResult.d.ts.map +0 -1
  90. package/dist/model/highlightResultOption.d.ts +0 -20
  91. package/dist/model/highlightResultOption.d.ts.map +0 -1
  92. package/dist/model/ignorePlurals.d.ts +0 -6
  93. package/dist/model/ignorePlurals.d.ts.map +0 -1
  94. package/dist/model/index.d.ts +0 -94
  95. package/dist/model/index.d.ts.map +0 -1
  96. package/dist/model/indexSettingsAsSearchParams.d.ts +0 -160
  97. package/dist/model/indexSettingsAsSearchParams.d.ts.map +0 -1
  98. package/dist/model/lookingSimilar.d.ts +0 -11
  99. package/dist/model/lookingSimilar.d.ts.map +0 -1
  100. package/dist/model/lookingSimilarModel.d.ts +0 -5
  101. package/dist/model/lookingSimilarModel.d.ts.map +0 -1
  102. package/dist/model/lookingSimilarQuery.d.ts +0 -4
  103. package/dist/model/lookingSimilarQuery.d.ts.map +0 -1
  104. package/dist/model/matchLevel.d.ts +0 -5
  105. package/dist/model/matchLevel.d.ts.map +0 -1
  106. package/dist/model/matchedGeoLocation.d.ts +0 -15
  107. package/dist/model/matchedGeoLocation.d.ts.map +0 -1
  108. package/dist/model/mode.d.ts +0 -5
  109. package/dist/model/mode.d.ts.map +0 -1
  110. package/dist/model/numericFilters.d.ts +0 -5
  111. package/dist/model/numericFilters.d.ts.map +0 -1
  112. package/dist/model/optionalFilters.d.ts +0 -5
  113. package/dist/model/optionalFilters.d.ts.map +0 -1
  114. package/dist/model/paramsConsequence.d.ts +0 -19
  115. package/dist/model/paramsConsequence.d.ts.map +0 -1
  116. package/dist/model/personalization.d.ts +0 -15
  117. package/dist/model/personalization.d.ts.map +0 -1
  118. package/dist/model/promoteConsequenceObject.d.ts +0 -14
  119. package/dist/model/promoteConsequenceObject.d.ts.map +0 -1
  120. package/dist/model/queryType.d.ts +0 -5
  121. package/dist/model/queryType.d.ts.map +0 -1
  122. package/dist/model/range.d.ts +0 -14
  123. package/dist/model/range.d.ts.map +0 -1
  124. package/dist/model/rankingInfo.d.ts +0 -54
  125. package/dist/model/rankingInfo.d.ts.map +0 -1
  126. package/dist/model/reRankingApplyFilter.d.ts +0 -5
  127. package/dist/model/reRankingApplyFilter.d.ts.map +0 -1
  128. package/dist/model/recommendHit.d.ts +0 -27
  129. package/dist/model/recommendHit.d.ts.map +0 -1
  130. package/dist/model/recommendModels.d.ts +0 -2
  131. package/dist/model/recommendModels.d.ts.map +0 -1
  132. package/dist/model/recommendRule.d.ts +0 -24
  133. package/dist/model/recommendRule.d.ts.map +0 -1
  134. package/dist/model/recommendationsHit.d.ts +0 -4
  135. package/dist/model/recommendationsHit.d.ts.map +0 -1
  136. package/dist/model/recommendationsHits.d.ts +0 -5
  137. package/dist/model/recommendationsHits.d.ts.map +0 -1
  138. package/dist/model/recommendationsRequest.d.ts +0 -8
  139. package/dist/model/recommendationsRequest.d.ts.map +0 -1
  140. package/dist/model/recommendationsResults.d.ts +0 -5
  141. package/dist/model/recommendationsResults.d.ts.map +0 -1
  142. package/dist/model/recommendedForYou.d.ts +0 -7
  143. package/dist/model/recommendedForYou.d.ts.map +0 -1
  144. package/dist/model/recommendedForYouModel.d.ts +0 -5
  145. package/dist/model/recommendedForYouModel.d.ts.map +0 -1
  146. package/dist/model/recommendedForYouQuery.d.ts +0 -4
  147. package/dist/model/recommendedForYouQuery.d.ts.map +0 -1
  148. package/dist/model/redirect.d.ts +0 -8
  149. package/dist/model/redirect.d.ts.map +0 -1
  150. package/dist/model/redirectRuleIndexData.d.ts +0 -7
  151. package/dist/model/redirectRuleIndexData.d.ts.map +0 -1
  152. package/dist/model/redirectRuleIndexMetadata.d.ts +0 -21
  153. package/dist/model/redirectRuleIndexMetadata.d.ts.map +0 -1
  154. package/dist/model/redirectURL.d.ts +0 -7
  155. package/dist/model/redirectURL.d.ts.map +0 -1
  156. package/dist/model/relatedModel.d.ts +0 -5
  157. package/dist/model/relatedModel.d.ts.map +0 -1
  158. package/dist/model/relatedProducts.d.ts +0 -11
  159. package/dist/model/relatedProducts.d.ts.map +0 -1
  160. package/dist/model/relatedQuery.d.ts +0 -4
  161. package/dist/model/relatedQuery.d.ts.map +0 -1
  162. package/dist/model/removeStopWords.d.ts +0 -6
  163. package/dist/model/removeStopWords.d.ts.map +0 -1
  164. package/dist/model/removeWordsIfNoResults.d.ts +0 -5
  165. package/dist/model/removeWordsIfNoResults.d.ts.map +0 -1
  166. package/dist/model/renderingContent.d.ts +0 -10
  167. package/dist/model/renderingContent.d.ts.map +0 -1
  168. package/dist/model/ruleMetadata.d.ts +0 -10
  169. package/dist/model/ruleMetadata.d.ts.map +0 -1
  170. package/dist/model/searchPagination.d.ts +0 -19
  171. package/dist/model/searchPagination.d.ts.map +0 -1
  172. package/dist/model/searchParams.d.ts +0 -3
  173. package/dist/model/searchParams.d.ts.map +0 -1
  174. package/dist/model/searchParamsObject.d.ts +0 -7
  175. package/dist/model/searchParamsObject.d.ts.map +0 -1
  176. package/dist/model/searchParamsQuery.d.ts +0 -7
  177. package/dist/model/searchParamsQuery.d.ts.map +0 -1
  178. package/dist/model/searchRecommendRulesParams.d.ts +0 -38
  179. package/dist/model/searchRecommendRulesParams.d.ts.map +0 -1
  180. package/dist/model/searchRecommendRulesResponse.d.ts +0 -20
  181. package/dist/model/searchRecommendRulesResponse.d.ts.map +0 -1
  182. package/dist/model/semanticSearch.d.ts +0 -10
  183. package/dist/model/semanticSearch.d.ts.map +0 -1
  184. package/dist/model/snippetResult.d.ts +0 -5
  185. package/dist/model/snippetResult.d.ts.map +0 -1
  186. package/dist/model/snippetResultOption.d.ts +0 -12
  187. package/dist/model/snippetResultOption.d.ts.map +0 -1
  188. package/dist/model/sortRemainingBy.d.ts +0 -5
  189. package/dist/model/sortRemainingBy.d.ts.map +0 -1
  190. package/dist/model/supportedLanguage.d.ts +0 -5
  191. package/dist/model/supportedLanguage.d.ts.map +0 -1
  192. package/dist/model/tagFilters.d.ts +0 -5
  193. package/dist/model/tagFilters.d.ts.map +0 -1
  194. package/dist/model/taskStatus.d.ts +0 -5
  195. package/dist/model/taskStatus.d.ts.map +0 -1
  196. package/dist/model/trendingFacetHit.d.ts +0 -18
  197. package/dist/model/trendingFacetHit.d.ts.map +0 -1
  198. package/dist/model/trendingFacets.d.ts +0 -11
  199. package/dist/model/trendingFacets.d.ts.map +0 -1
  200. package/dist/model/trendingFacetsModel.d.ts +0 -5
  201. package/dist/model/trendingFacetsModel.d.ts.map +0 -1
  202. package/dist/model/trendingFacetsQuery.d.ts +0 -4
  203. package/dist/model/trendingFacetsQuery.d.ts.map +0 -1
  204. package/dist/model/trendingItems.d.ts +0 -15
  205. package/dist/model/trendingItems.d.ts.map +0 -1
  206. package/dist/model/trendingItemsModel.d.ts +0 -5
  207. package/dist/model/trendingItemsModel.d.ts.map +0 -1
  208. package/dist/model/trendingItemsQuery.d.ts +0 -4
  209. package/dist/model/trendingItemsQuery.d.ts.map +0 -1
  210. package/dist/model/typoTolerance.d.ts +0 -6
  211. package/dist/model/typoTolerance.d.ts.map +0 -1
  212. package/dist/model/typoToleranceEnum.d.ts +0 -5
  213. package/dist/model/typoToleranceEnum.d.ts.map +0 -1
  214. package/dist/model/value.d.ts +0 -13
  215. package/dist/model/value.d.ts.map +0 -1
  216. package/dist/recommend.cjs +0 -394
  217. package/dist/recommend.esm.browser.js +0 -1079
  218. package/dist/recommend.esm.node.js +0 -391
  219. package/dist/recommend.umd.js +0 -2
  220. package/dist/src/recommendClient.d.ts +0 -132
  221. package/dist/src/recommendClient.d.ts.map +0 -1
@@ -1,1079 +0,0 @@
1
- function createAuth(appId, apiKey, authMode = 'WithinHeaders') {
2
- const credentials = {
3
- 'x-algolia-api-key': apiKey,
4
- 'x-algolia-application-id': appId
5
- };
6
- return {
7
- headers() {
8
- return authMode === 'WithinHeaders' ? credentials : {};
9
- },
10
- queryParameters() {
11
- return authMode === 'WithinQueryParameters' ? credentials : {};
12
- }
13
- };
14
- }
15
-
16
- function createBrowserLocalStorageCache(options) {
17
- let storage;
18
- // We've changed the namespace to avoid conflicts with v4, as this version is a huge breaking change
19
- const namespaceKey = `algolia-client-js-${options.key}`;
20
- function getStorage() {
21
- if (storage === undefined) {
22
- storage = options.localStorage || window.localStorage;
23
- }
24
- return storage;
25
- }
26
- function getNamespace() {
27
- return JSON.parse(getStorage().getItem(namespaceKey) || '{}');
28
- }
29
- function setNamespace(namespace) {
30
- getStorage().setItem(namespaceKey, JSON.stringify(namespace));
31
- }
32
- function removeOutdatedCacheItems() {
33
- const timeToLive = options.timeToLive ? options.timeToLive * 1000 : null;
34
- const namespace = getNamespace();
35
- const filteredNamespaceWithoutOldFormattedCacheItems = Object.fromEntries(Object.entries(namespace).filter(([, cacheItem]) => {
36
- return cacheItem.timestamp !== undefined;
37
- }));
38
- setNamespace(filteredNamespaceWithoutOldFormattedCacheItems);
39
- if (!timeToLive) {
40
- return;
41
- }
42
- const filteredNamespaceWithoutExpiredItems = Object.fromEntries(Object.entries(filteredNamespaceWithoutOldFormattedCacheItems).filter(([, cacheItem]) => {
43
- const currentTimestamp = new Date().getTime();
44
- const isExpired = cacheItem.timestamp + timeToLive < currentTimestamp;
45
- return !isExpired;
46
- }));
47
- setNamespace(filteredNamespaceWithoutExpiredItems);
48
- }
49
- return {
50
- get(key, defaultValue, events = {
51
- miss: () => Promise.resolve()
52
- }) {
53
- return Promise.resolve().then(() => {
54
- removeOutdatedCacheItems();
55
- return getNamespace()[JSON.stringify(key)];
56
- }).then(value => {
57
- return Promise.all([value ? value.value : defaultValue(), value !== undefined]);
58
- }).then(([value, exists]) => {
59
- return Promise.all([value, exists || events.miss(value)]);
60
- }).then(([value]) => value);
61
- },
62
- set(key, value) {
63
- return Promise.resolve().then(() => {
64
- const namespace = getNamespace();
65
- namespace[JSON.stringify(key)] = {
66
- timestamp: new Date().getTime(),
67
- value
68
- };
69
- getStorage().setItem(namespaceKey, JSON.stringify(namespace));
70
- return value;
71
- });
72
- },
73
- delete(key) {
74
- return Promise.resolve().then(() => {
75
- const namespace = getNamespace();
76
- delete namespace[JSON.stringify(key)];
77
- getStorage().setItem(namespaceKey, JSON.stringify(namespace));
78
- });
79
- },
80
- clear() {
81
- return Promise.resolve().then(() => {
82
- getStorage().removeItem(namespaceKey);
83
- });
84
- }
85
- };
86
- }
87
-
88
- function createNullCache() {
89
- return {
90
- get(_key, defaultValue, events = {
91
- miss: () => Promise.resolve()
92
- }) {
93
- const value = defaultValue();
94
- return value.then(result => Promise.all([result, events.miss(result)])).then(([result]) => result);
95
- },
96
- set(_key, value) {
97
- return Promise.resolve(value);
98
- },
99
- delete(_key) {
100
- return Promise.resolve();
101
- },
102
- clear() {
103
- return Promise.resolve();
104
- }
105
- };
106
- }
107
-
108
- function createFallbackableCache(options) {
109
- const caches = [...options.caches];
110
- const current = caches.shift();
111
- if (current === undefined) {
112
- return createNullCache();
113
- }
114
- return {
115
- get(key, defaultValue, events = {
116
- miss: () => Promise.resolve()
117
- }) {
118
- return current.get(key, defaultValue, events).catch(() => {
119
- return createFallbackableCache({
120
- caches
121
- }).get(key, defaultValue, events);
122
- });
123
- },
124
- set(key, value) {
125
- return current.set(key, value).catch(() => {
126
- return createFallbackableCache({
127
- caches
128
- }).set(key, value);
129
- });
130
- },
131
- delete(key) {
132
- return current.delete(key).catch(() => {
133
- return createFallbackableCache({
134
- caches
135
- }).delete(key);
136
- });
137
- },
138
- clear() {
139
- return current.clear().catch(() => {
140
- return createFallbackableCache({
141
- caches
142
- }).clear();
143
- });
144
- }
145
- };
146
- }
147
-
148
- function createMemoryCache(options = {
149
- serializable: true
150
- }) {
151
- let cache = {};
152
- return {
153
- get(key, defaultValue, events = {
154
- miss: () => Promise.resolve()
155
- }) {
156
- const keyAsString = JSON.stringify(key);
157
- if (keyAsString in cache) {
158
- return Promise.resolve(options.serializable ? JSON.parse(cache[keyAsString]) : cache[keyAsString]);
159
- }
160
- const promise = defaultValue();
161
- return promise.then(value => events.miss(value)).then(() => promise);
162
- },
163
- set(key, value) {
164
- cache[JSON.stringify(key)] = options.serializable ? JSON.stringify(value) : value;
165
- return Promise.resolve(value);
166
- },
167
- delete(key) {
168
- delete cache[JSON.stringify(key)];
169
- return Promise.resolve();
170
- },
171
- clear() {
172
- cache = {};
173
- return Promise.resolve();
174
- }
175
- };
176
- }
177
-
178
- // By default, API Clients at Algolia have expiration delay of 5 mins.
179
- // In the JavaScript client, we have 2 mins.
180
- const EXPIRATION_DELAY = 2 * 60 * 1000;
181
- function createStatefulHost(host, status = 'up') {
182
- const lastUpdate = Date.now();
183
- function isUp() {
184
- return status === 'up' || Date.now() - lastUpdate > EXPIRATION_DELAY;
185
- }
186
- function isTimedOut() {
187
- return status === 'timed out' && Date.now() - lastUpdate <= EXPIRATION_DELAY;
188
- }
189
- return {
190
- ...host,
191
- status,
192
- lastUpdate,
193
- isUp,
194
- isTimedOut
195
- };
196
- }
197
-
198
- function _defineProperty(e, r, t) {
199
- return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
200
- value: t,
201
- enumerable: !0,
202
- configurable: !0,
203
- writable: !0
204
- }) : e[r] = t, e;
205
- }
206
- function _toPrimitive(t, r) {
207
- if ("object" != typeof t || !t) return t;
208
- var e = t[Symbol.toPrimitive];
209
- if (void 0 !== e) {
210
- var i = e.call(t, r || "default");
211
- if ("object" != typeof i) return i;
212
- throw new TypeError("@@toPrimitive must return a primitive value.");
213
- }
214
- return ("string" === r ? String : Number)(t);
215
- }
216
- function _toPropertyKey(t) {
217
- var i = _toPrimitive(t, "string");
218
- return "symbol" == typeof i ? i : i + "";
219
- }
220
-
221
- class AlgoliaError extends Error {
222
- constructor(message, name) {
223
- super(message);
224
- _defineProperty(this, "name", 'AlgoliaError');
225
- if (name) {
226
- this.name = name;
227
- }
228
- }
229
- }
230
- class ErrorWithStackTrace extends AlgoliaError {
231
- constructor(message, stackTrace, name) {
232
- super(message, name);
233
- // the array and object should be frozen to reflect the stackTrace at the time of the error
234
- _defineProperty(this, "stackTrace", void 0);
235
- this.stackTrace = stackTrace;
236
- }
237
- }
238
- class RetryError extends ErrorWithStackTrace {
239
- constructor(stackTrace) {
240
- super('Unreachable hosts - your application id may be incorrect. If the error persists, please reach out to the Algolia Support team: https://alg.li/support.', stackTrace, 'RetryError');
241
- }
242
- }
243
- class ApiError extends ErrorWithStackTrace {
244
- constructor(message, status, stackTrace, name = 'ApiError') {
245
- super(message, stackTrace, name);
246
- _defineProperty(this, "status", void 0);
247
- this.status = status;
248
- }
249
- }
250
- class DeserializationError extends AlgoliaError {
251
- constructor(message, response) {
252
- super(message, 'DeserializationError');
253
- _defineProperty(this, "response", void 0);
254
- this.response = response;
255
- }
256
- }
257
- // DetailedApiError is only used by the ingestion client to return more informative error, other clients will use ApiClient.
258
- class DetailedApiError extends ApiError {
259
- constructor(message, status, error, stackTrace) {
260
- super(message, status, stackTrace, 'DetailedApiError');
261
- _defineProperty(this, "error", void 0);
262
- this.error = error;
263
- }
264
- }
265
-
266
- function shuffle(array) {
267
- const shuffledArray = array;
268
- for (let c = array.length - 1; c > 0; c--) {
269
- const b = Math.floor(Math.random() * (c + 1));
270
- const a = array[c];
271
- shuffledArray[c] = array[b];
272
- shuffledArray[b] = a;
273
- }
274
- return shuffledArray;
275
- }
276
- function serializeUrl(host, path, queryParameters) {
277
- const queryParametersAsString = serializeQueryParameters(queryParameters);
278
- let url = `${host.protocol}://${host.url}${host.port ? `:${host.port}` : ''}/${path.charAt(0) === '/' ? path.substring(1) : path}`;
279
- if (queryParametersAsString.length) {
280
- url += `?${queryParametersAsString}`;
281
- }
282
- return url;
283
- }
284
- function serializeQueryParameters(parameters) {
285
- return Object.keys(parameters).filter(key => parameters[key] !== undefined).sort().map(key => `${key}=${encodeURIComponent(Object.prototype.toString.call(parameters[key]) === '[object Array]' ? parameters[key].join(',') : parameters[key]).replaceAll('+', '%20')}`).join('&');
286
- }
287
- function serializeData(request, requestOptions) {
288
- if (request.method === 'GET' || request.data === undefined && requestOptions.data === undefined) {
289
- return undefined;
290
- }
291
- const data = Array.isArray(request.data) ? request.data : {
292
- ...request.data,
293
- ...requestOptions.data
294
- };
295
- return JSON.stringify(data);
296
- }
297
- function serializeHeaders(baseHeaders, requestHeaders, requestOptionsHeaders) {
298
- const headers = {
299
- Accept: 'application/json',
300
- ...baseHeaders,
301
- ...requestHeaders,
302
- ...requestOptionsHeaders
303
- };
304
- const serializedHeaders = {};
305
- Object.keys(headers).forEach(header => {
306
- const value = headers[header];
307
- serializedHeaders[header.toLowerCase()] = value;
308
- });
309
- return serializedHeaders;
310
- }
311
- function deserializeSuccess(response) {
312
- try {
313
- return JSON.parse(response.content);
314
- } catch (e) {
315
- throw new DeserializationError(e.message, response);
316
- }
317
- }
318
- function deserializeFailure({
319
- content,
320
- status
321
- }, stackFrame) {
322
- try {
323
- const parsed = JSON.parse(content);
324
- if ('error' in parsed) {
325
- return new DetailedApiError(parsed.message, status, parsed.error, stackFrame);
326
- }
327
- return new ApiError(parsed.message, status, stackFrame);
328
- } catch {
329
- // ..
330
- }
331
- return new ApiError(content, status, stackFrame);
332
- }
333
-
334
- function isNetworkError({
335
- isTimedOut,
336
- status
337
- }) {
338
- return !isTimedOut && ~~status === 0;
339
- }
340
- function isRetryable({
341
- isTimedOut,
342
- status
343
- }) {
344
- return isTimedOut || isNetworkError({
345
- isTimedOut,
346
- status
347
- }) || ~~(status / 100) !== 2 && ~~(status / 100) !== 4;
348
- }
349
- function isSuccess({
350
- status
351
- }) {
352
- return ~~(status / 100) === 2;
353
- }
354
-
355
- function stackTraceWithoutCredentials(stackTrace) {
356
- return stackTrace.map(stackFrame => stackFrameWithoutCredentials(stackFrame));
357
- }
358
- function stackFrameWithoutCredentials(stackFrame) {
359
- const modifiedHeaders = stackFrame.request.headers['x-algolia-api-key'] ? {
360
- 'x-algolia-api-key': '*****'
361
- } : {};
362
- return {
363
- ...stackFrame,
364
- request: {
365
- ...stackFrame.request,
366
- headers: {
367
- ...stackFrame.request.headers,
368
- ...modifiedHeaders
369
- }
370
- }
371
- };
372
- }
373
-
374
- function createTransporter({
375
- hosts,
376
- hostsCache,
377
- baseHeaders,
378
- baseQueryParameters,
379
- algoliaAgent,
380
- timeouts,
381
- requester,
382
- requestsCache,
383
- responsesCache
384
- }) {
385
- async function createRetryableOptions(compatibleHosts) {
386
- const statefulHosts = await Promise.all(compatibleHosts.map(compatibleHost => {
387
- return hostsCache.get(compatibleHost, () => {
388
- return Promise.resolve(createStatefulHost(compatibleHost));
389
- });
390
- }));
391
- const hostsUp = statefulHosts.filter(host => host.isUp());
392
- const hostsTimedOut = statefulHosts.filter(host => host.isTimedOut());
393
- // Note, we put the hosts that previously timed out on the end of the list.
394
- const hostsAvailable = [...hostsUp, ...hostsTimedOut];
395
- const compatibleHostsAvailable = hostsAvailable.length > 0 ? hostsAvailable : compatibleHosts;
396
- return {
397
- hosts: compatibleHostsAvailable,
398
- getTimeout(timeoutsCount, baseTimeout) {
399
- /**
400
- * Imagine that you have 4 hosts, if timeouts will increase
401
- * on the following way: 1 (timed out) > 4 (timed out) > 5 (200).
402
- *
403
- * Note that, the very next request, we start from the previous timeout.
404
- *
405
- * 5 (timed out) > 6 (timed out) > 7 ...
406
- *
407
- * This strategy may need to be reviewed, but is the strategy on the our
408
- * current v3 version.
409
- */
410
- const timeoutMultiplier = hostsTimedOut.length === 0 && timeoutsCount === 0 ? 1 : hostsTimedOut.length + 3 + timeoutsCount;
411
- return timeoutMultiplier * baseTimeout;
412
- }
413
- };
414
- }
415
- async function retryableRequest(request, requestOptions, isRead = true) {
416
- const stackTrace = [];
417
- /**
418
- * First we prepare the payload that do not depend from hosts.
419
- */
420
- const data = serializeData(request, requestOptions);
421
- const headers = serializeHeaders(baseHeaders, request.headers, requestOptions.headers);
422
- // On `GET`, the data is proxied to query parameters.
423
- const dataQueryParameters = request.method === 'GET' ? {
424
- ...request.data,
425
- ...requestOptions.data
426
- } : {};
427
- const queryParameters = {
428
- ...baseQueryParameters,
429
- ...request.queryParameters,
430
- ...dataQueryParameters
431
- };
432
- if (algoliaAgent.value) {
433
- queryParameters['x-algolia-agent'] = algoliaAgent.value;
434
- }
435
- if (requestOptions && requestOptions.queryParameters) {
436
- for (const key of Object.keys(requestOptions.queryParameters)) {
437
- // We want to keep `undefined` and `null` values,
438
- // but also avoid stringifying `object`s, as they are
439
- // handled in the `serializeUrl` step right after.
440
- if (!requestOptions.queryParameters[key] || Object.prototype.toString.call(requestOptions.queryParameters[key]) === '[object Object]') {
441
- queryParameters[key] = requestOptions.queryParameters[key];
442
- } else {
443
- queryParameters[key] = requestOptions.queryParameters[key].toString();
444
- }
445
- }
446
- }
447
- let timeoutsCount = 0;
448
- const retry = async (retryableHosts, getTimeout) => {
449
- /**
450
- * We iterate on each host, until there is no host left.
451
- */
452
- const host = retryableHosts.pop();
453
- if (host === undefined) {
454
- throw new RetryError(stackTraceWithoutCredentials(stackTrace));
455
- }
456
- const timeout = {
457
- ...timeouts,
458
- ...requestOptions.timeouts
459
- };
460
- const payload = {
461
- data,
462
- headers,
463
- method: request.method,
464
- url: serializeUrl(host, request.path, queryParameters),
465
- connectTimeout: getTimeout(timeoutsCount, timeout.connect),
466
- responseTimeout: getTimeout(timeoutsCount, isRead ? timeout.read : timeout.write)
467
- };
468
- /**
469
- * The stackFrame is pushed to the stackTrace so we
470
- * can have information about onRetry and onFailure
471
- * decisions.
472
- */
473
- const pushToStackTrace = response => {
474
- const stackFrame = {
475
- request: payload,
476
- response,
477
- host,
478
- triesLeft: retryableHosts.length
479
- };
480
- stackTrace.push(stackFrame);
481
- return stackFrame;
482
- };
483
- const response = await requester.send(payload);
484
- if (isRetryable(response)) {
485
- const stackFrame = pushToStackTrace(response);
486
- // If response is a timeout, we increase the number of timeouts so we can increase the timeout later.
487
- if (response.isTimedOut) {
488
- timeoutsCount++;
489
- }
490
- /**
491
- * Failures are individually sent to the logger, allowing
492
- * the end user to debug / store stack frames even
493
- * when a retry error does not happen.
494
- */
495
- // eslint-disable-next-line no-console -- this will be fixed by exposing a `logger` to the transporter
496
- console.log('Retryable failure', stackFrameWithoutCredentials(stackFrame));
497
- /**
498
- * We also store the state of the host in failure cases. If the host, is
499
- * down it will remain down for the next 2 minutes. In a timeout situation,
500
- * this host will be added end of the list of hosts on the next request.
501
- */
502
- await hostsCache.set(host, createStatefulHost(host, response.isTimedOut ? 'timed out' : 'down'));
503
- return retry(retryableHosts, getTimeout);
504
- }
505
- if (isSuccess(response)) {
506
- return deserializeSuccess(response);
507
- }
508
- pushToStackTrace(response);
509
- throw deserializeFailure(response, stackTrace);
510
- };
511
- /**
512
- * Finally, for each retryable host perform request until we got a non
513
- * retryable response. Some notes here:
514
- *
515
- * 1. The reverse here is applied so we can apply a `pop` later on => more performant.
516
- * 2. We also get from the retryable options a timeout multiplier that is tailored
517
- * for the current context.
518
- */
519
- const compatibleHosts = hosts.filter(host => host.accept === 'readWrite' || (isRead ? host.accept === 'read' : host.accept === 'write'));
520
- const options = await createRetryableOptions(compatibleHosts);
521
- return retry([...options.hosts].reverse(), options.getTimeout);
522
- }
523
- function createRequest(request, requestOptions = {}) {
524
- /**
525
- * A read request is either a `GET` request, or a request that we make
526
- * via the `read` transporter (e.g. `search`).
527
- */
528
- const isRead = request.useReadTransporter || request.method === 'GET';
529
- if (!isRead) {
530
- /**
531
- * On write requests, no cache mechanisms are applied, and we
532
- * proxy the request immediately to the requester.
533
- */
534
- return retryableRequest(request, requestOptions, isRead);
535
- }
536
- const createRetryableRequest = () => {
537
- /**
538
- * Then, we prepare a function factory that contains the construction of
539
- * the retryable request. At this point, we may *not* perform the actual
540
- * request. But we want to have the function factory ready.
541
- */
542
- return retryableRequest(request, requestOptions);
543
- };
544
- /**
545
- * Once we have the function factory ready, we need to determine of the
546
- * request is "cacheable" - should be cached. Note that, once again,
547
- * the user can force this option.
548
- */
549
- const cacheable = requestOptions.cacheable || request.cacheable;
550
- /**
551
- * If is not "cacheable", we immediately trigger the retryable request, no
552
- * need to check cache implementations.
553
- */
554
- if (cacheable !== true) {
555
- return createRetryableRequest();
556
- }
557
- /**
558
- * If the request is "cacheable", we need to first compute the key to ask
559
- * the cache implementations if this request is on progress or if the
560
- * response already exists on the cache.
561
- */
562
- const key = {
563
- request,
564
- requestOptions,
565
- transporter: {
566
- queryParameters: baseQueryParameters,
567
- headers: baseHeaders
568
- }
569
- };
570
- /**
571
- * With the computed key, we first ask the responses cache
572
- * implementation if this request was been resolved before.
573
- */
574
- return responsesCache.get(key, () => {
575
- /**
576
- * If the request has never resolved before, we actually ask if there
577
- * is a current request with the same key on progress.
578
- */
579
- return requestsCache.get(key, () =>
580
- /**
581
- * Finally, if there is no request in progress with the same key,
582
- * this `createRetryableRequest()` will actually trigger the
583
- * retryable request.
584
- */
585
- requestsCache.set(key, createRetryableRequest()).then(response => Promise.all([requestsCache.delete(key), response]), err => Promise.all([requestsCache.delete(key), Promise.reject(err)])).then(([_, response]) => response));
586
- }, {
587
- /**
588
- * Of course, once we get this response back from the server, we
589
- * tell response cache to actually store the received response
590
- * to be used later.
591
- */
592
- miss: response => responsesCache.set(key, response)
593
- });
594
- }
595
- return {
596
- hostsCache,
597
- requester,
598
- timeouts,
599
- algoliaAgent,
600
- baseHeaders,
601
- baseQueryParameters,
602
- hosts,
603
- request: createRequest,
604
- requestsCache,
605
- responsesCache
606
- };
607
- }
608
-
609
- function createAlgoliaAgent(version) {
610
- const algoliaAgent = {
611
- value: `Algolia for JavaScript (${version})`,
612
- add(options) {
613
- const addedAlgoliaAgent = `; ${options.segment}${options.version !== undefined ? ` (${options.version})` : ''}`;
614
- if (algoliaAgent.value.indexOf(addedAlgoliaAgent) === -1) {
615
- algoliaAgent.value = `${algoliaAgent.value}${addedAlgoliaAgent}`;
616
- }
617
- return algoliaAgent;
618
- }
619
- };
620
- return algoliaAgent;
621
- }
622
-
623
- function getAlgoliaAgent({
624
- algoliaAgents,
625
- client,
626
- version
627
- }) {
628
- const defaultAlgoliaAgent = createAlgoliaAgent(version).add({
629
- segment: client,
630
- version
631
- });
632
- algoliaAgents.forEach(algoliaAgent => defaultAlgoliaAgent.add(algoliaAgent));
633
- return defaultAlgoliaAgent;
634
- }
635
-
636
- const DEFAULT_CONNECT_TIMEOUT_BROWSER = 1000;
637
- const DEFAULT_READ_TIMEOUT_BROWSER = 2000;
638
- const DEFAULT_WRITE_TIMEOUT_BROWSER = 30000;
639
-
640
- function createXhrRequester() {
641
- function send(request) {
642
- return new Promise((resolve) => {
643
- const baseRequester = new XMLHttpRequest();
644
- baseRequester.open(request.method, request.url, true);
645
- Object.keys(request.headers).forEach((key) => baseRequester.setRequestHeader(key, request.headers[key]));
646
- const createTimeout = (timeout, content) => {
647
- return setTimeout(() => {
648
- baseRequester.abort();
649
- resolve({
650
- status: 0,
651
- content,
652
- isTimedOut: true,
653
- });
654
- }, timeout);
655
- };
656
- const connectTimeout = createTimeout(request.connectTimeout, 'Connection timeout');
657
- let responseTimeout;
658
- baseRequester.onreadystatechange = () => {
659
- if (baseRequester.readyState > baseRequester.OPENED && responseTimeout === undefined) {
660
- clearTimeout(connectTimeout);
661
- responseTimeout = createTimeout(request.responseTimeout, 'Socket timeout');
662
- }
663
- };
664
- baseRequester.onerror = () => {
665
- // istanbul ignore next
666
- if (baseRequester.status === 0) {
667
- clearTimeout(connectTimeout);
668
- clearTimeout(responseTimeout);
669
- resolve({
670
- content: baseRequester.responseText || 'Network request failed',
671
- status: baseRequester.status,
672
- isTimedOut: false,
673
- });
674
- }
675
- };
676
- baseRequester.onload = () => {
677
- clearTimeout(connectTimeout);
678
- clearTimeout(responseTimeout);
679
- resolve({
680
- content: baseRequester.responseText,
681
- status: baseRequester.status,
682
- isTimedOut: false,
683
- });
684
- };
685
- baseRequester.send(request.data);
686
- });
687
- }
688
- return { send };
689
- }
690
-
691
- // Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT.
692
- const apiClientVersion = '5.2.2';
693
- function getDefaultHosts(appId) {
694
- return [
695
- {
696
- url: `${appId}-dsn.algolia.net`,
697
- accept: 'read',
698
- protocol: 'https',
699
- },
700
- {
701
- url: `${appId}.algolia.net`,
702
- accept: 'write',
703
- protocol: 'https',
704
- },
705
- ].concat(shuffle([
706
- {
707
- url: `${appId}-1.algolianet.com`,
708
- accept: 'readWrite',
709
- protocol: 'https',
710
- },
711
- {
712
- url: `${appId}-2.algolianet.com`,
713
- accept: 'readWrite',
714
- protocol: 'https',
715
- },
716
- {
717
- url: `${appId}-3.algolianet.com`,
718
- accept: 'readWrite',
719
- protocol: 'https',
720
- },
721
- ]));
722
- }
723
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
724
- function createRecommendClient({ appId: appIdOption, apiKey: apiKeyOption, authMode, algoliaAgents, ...options }) {
725
- const auth = createAuth(appIdOption, apiKeyOption, authMode);
726
- const transporter = createTransporter({
727
- hosts: getDefaultHosts(appIdOption),
728
- ...options,
729
- algoliaAgent: getAlgoliaAgent({
730
- algoliaAgents,
731
- client: 'Recommend',
732
- version: apiClientVersion,
733
- }),
734
- baseHeaders: {
735
- 'content-type': 'text/plain',
736
- ...auth.headers(),
737
- ...options.baseHeaders,
738
- },
739
- baseQueryParameters: {
740
- ...auth.queryParameters(),
741
- ...options.baseQueryParameters,
742
- },
743
- });
744
- return {
745
- transporter,
746
- /**
747
- * The `appId` currently in use.
748
- */
749
- appId: appIdOption,
750
- /**
751
- * Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.
752
- */
753
- clearCache() {
754
- return Promise.all([transporter.requestsCache.clear(), transporter.responsesCache.clear()]).then(() => undefined);
755
- },
756
- /**
757
- * Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
758
- */
759
- get _ua() {
760
- return transporter.algoliaAgent.value;
761
- },
762
- /**
763
- * Adds a `segment` to the `x-algolia-agent` sent with every requests.
764
- *
765
- * @param segment - The algolia agent (user-agent) segment to add.
766
- * @param version - The version of the agent.
767
- */
768
- addAlgoliaAgent(segment, version) {
769
- transporter.algoliaAgent.add({ segment, version });
770
- },
771
- /**
772
- * This method allow you to send requests to the Algolia REST API.
773
- *
774
- * @param customDelete - The customDelete object.
775
- * @param customDelete.path - Path of the endpoint, anything after \"/1\" must be specified.
776
- * @param customDelete.parameters - Query parameters to apply to the current query.
777
- * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
778
- */
779
- customDelete({ path, parameters }, requestOptions) {
780
- if (!path) {
781
- throw new Error('Parameter `path` is required when calling `customDelete`.');
782
- }
783
- const requestPath = '/{path}'.replace('{path}', path);
784
- const headers = {};
785
- const queryParameters = parameters ? parameters : {};
786
- const request = {
787
- method: 'DELETE',
788
- path: requestPath,
789
- queryParameters,
790
- headers,
791
- };
792
- return transporter.request(request, requestOptions);
793
- },
794
- /**
795
- * This method allow you to send requests to the Algolia REST API.
796
- *
797
- * @param customGet - The customGet object.
798
- * @param customGet.path - Path of the endpoint, anything after \"/1\" must be specified.
799
- * @param customGet.parameters - Query parameters to apply to the current query.
800
- * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
801
- */
802
- customGet({ path, parameters }, requestOptions) {
803
- if (!path) {
804
- throw new Error('Parameter `path` is required when calling `customGet`.');
805
- }
806
- const requestPath = '/{path}'.replace('{path}', path);
807
- const headers = {};
808
- const queryParameters = parameters ? parameters : {};
809
- const request = {
810
- method: 'GET',
811
- path: requestPath,
812
- queryParameters,
813
- headers,
814
- };
815
- return transporter.request(request, requestOptions);
816
- },
817
- /**
818
- * This method allow you to send requests to the Algolia REST API.
819
- *
820
- * @param customPost - The customPost object.
821
- * @param customPost.path - Path of the endpoint, anything after \"/1\" must be specified.
822
- * @param customPost.parameters - Query parameters to apply to the current query.
823
- * @param customPost.body - Parameters to send with the custom request.
824
- * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
825
- */
826
- customPost({ path, parameters, body }, requestOptions) {
827
- if (!path) {
828
- throw new Error('Parameter `path` is required when calling `customPost`.');
829
- }
830
- const requestPath = '/{path}'.replace('{path}', path);
831
- const headers = {};
832
- const queryParameters = parameters ? parameters : {};
833
- const request = {
834
- method: 'POST',
835
- path: requestPath,
836
- queryParameters,
837
- headers,
838
- data: body ? body : {},
839
- };
840
- return transporter.request(request, requestOptions);
841
- },
842
- /**
843
- * This method allow you to send requests to the Algolia REST API.
844
- *
845
- * @param customPut - The customPut object.
846
- * @param customPut.path - Path of the endpoint, anything after \"/1\" must be specified.
847
- * @param customPut.parameters - Query parameters to apply to the current query.
848
- * @param customPut.body - Parameters to send with the custom request.
849
- * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
850
- */
851
- customPut({ path, parameters, body }, requestOptions) {
852
- if (!path) {
853
- throw new Error('Parameter `path` is required when calling `customPut`.');
854
- }
855
- const requestPath = '/{path}'.replace('{path}', path);
856
- const headers = {};
857
- const queryParameters = parameters ? parameters : {};
858
- const request = {
859
- method: 'PUT',
860
- path: requestPath,
861
- queryParameters,
862
- headers,
863
- data: body ? body : {},
864
- };
865
- return transporter.request(request, requestOptions);
866
- },
867
- /**
868
- * Deletes a Recommend rule from a recommendation scenario.
869
- *
870
- * Required API Key ACLs:
871
- * - editSettings.
872
- *
873
- * @param deleteRecommendRule - The deleteRecommendRule object.
874
- * @param deleteRecommendRule.indexName - Name of the index on which to perform the operation.
875
- * @param deleteRecommendRule.model - [Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models).
876
- * @param deleteRecommendRule.objectID - Unique record identifier.
877
- * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
878
- */
879
- deleteRecommendRule({ indexName, model, objectID }, requestOptions) {
880
- if (!indexName) {
881
- throw new Error('Parameter `indexName` is required when calling `deleteRecommendRule`.');
882
- }
883
- if (!model) {
884
- throw new Error('Parameter `model` is required when calling `deleteRecommendRule`.');
885
- }
886
- if (!objectID) {
887
- throw new Error('Parameter `objectID` is required when calling `deleteRecommendRule`.');
888
- }
889
- const requestPath = '/1/indexes/{indexName}/{model}/recommend/rules/{objectID}'
890
- .replace('{indexName}', encodeURIComponent(indexName))
891
- .replace('{model}', encodeURIComponent(model))
892
- .replace('{objectID}', encodeURIComponent(objectID));
893
- const headers = {};
894
- const queryParameters = {};
895
- const request = {
896
- method: 'DELETE',
897
- path: requestPath,
898
- queryParameters,
899
- headers,
900
- };
901
- return transporter.request(request, requestOptions);
902
- },
903
- /**
904
- * Retrieves a Recommend rule that you previously created in the Algolia dashboard.
905
- *
906
- * Required API Key ACLs:
907
- * - settings.
908
- *
909
- * @param getRecommendRule - The getRecommendRule object.
910
- * @param getRecommendRule.indexName - Name of the index on which to perform the operation.
911
- * @param getRecommendRule.model - [Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models).
912
- * @param getRecommendRule.objectID - Unique record identifier.
913
- * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
914
- */
915
- getRecommendRule({ indexName, model, objectID }, requestOptions) {
916
- if (!indexName) {
917
- throw new Error('Parameter `indexName` is required when calling `getRecommendRule`.');
918
- }
919
- if (!model) {
920
- throw new Error('Parameter `model` is required when calling `getRecommendRule`.');
921
- }
922
- if (!objectID) {
923
- throw new Error('Parameter `objectID` is required when calling `getRecommendRule`.');
924
- }
925
- const requestPath = '/1/indexes/{indexName}/{model}/recommend/rules/{objectID}'
926
- .replace('{indexName}', encodeURIComponent(indexName))
927
- .replace('{model}', encodeURIComponent(model))
928
- .replace('{objectID}', encodeURIComponent(objectID));
929
- const headers = {};
930
- const queryParameters = {};
931
- const request = {
932
- method: 'GET',
933
- path: requestPath,
934
- queryParameters,
935
- headers,
936
- };
937
- return transporter.request(request, requestOptions);
938
- },
939
- /**
940
- * Checks the status of a given task. Deleting a Recommend rule is asynchronous. When you delete a rule, a task is created on a queue and completed depending on the load on the server. The API response includes a task ID that you can use to check the status.
941
- *
942
- * Required API Key ACLs:
943
- * - editSettings.
944
- *
945
- * @param getRecommendStatus - The getRecommendStatus object.
946
- * @param getRecommendStatus.indexName - Name of the index on which to perform the operation.
947
- * @param getRecommendStatus.model - [Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models).
948
- * @param getRecommendStatus.taskID - Unique task identifier.
949
- * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
950
- */
951
- getRecommendStatus({ indexName, model, taskID }, requestOptions) {
952
- if (!indexName) {
953
- throw new Error('Parameter `indexName` is required when calling `getRecommendStatus`.');
954
- }
955
- if (!model) {
956
- throw new Error('Parameter `model` is required when calling `getRecommendStatus`.');
957
- }
958
- if (!taskID) {
959
- throw new Error('Parameter `taskID` is required when calling `getRecommendStatus`.');
960
- }
961
- const requestPath = '/1/indexes/{indexName}/{model}/task/{taskID}'
962
- .replace('{indexName}', encodeURIComponent(indexName))
963
- .replace('{model}', encodeURIComponent(model))
964
- .replace('{taskID}', encodeURIComponent(taskID));
965
- const headers = {};
966
- const queryParameters = {};
967
- const request = {
968
- method: 'GET',
969
- path: requestPath,
970
- queryParameters,
971
- headers,
972
- };
973
- return transporter.request(request, requestOptions);
974
- },
975
- /**
976
- * Retrieves recommendations from selected AI models.
977
- *
978
- * Required API Key ACLs:
979
- * - search.
980
- *
981
- * @param getRecommendationsParams - The getRecommendationsParams object.
982
- * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
983
- */
984
- getRecommendations(getRecommendationsParams, requestOptions) {
985
- if (getRecommendationsParams && Array.isArray(getRecommendationsParams)) {
986
- const newSignatureRequest = {
987
- requests: getRecommendationsParams,
988
- };
989
- // eslint-disable-next-line no-param-reassign
990
- getRecommendationsParams = newSignatureRequest;
991
- }
992
- if (!getRecommendationsParams) {
993
- throw new Error('Parameter `getRecommendationsParams` is required when calling `getRecommendations`.');
994
- }
995
- if (!getRecommendationsParams.requests) {
996
- throw new Error('Parameter `getRecommendationsParams.requests` is required when calling `getRecommendations`.');
997
- }
998
- const requestPath = '/1/indexes/*/recommendations';
999
- const headers = {};
1000
- const queryParameters = {};
1001
- const request = {
1002
- method: 'POST',
1003
- path: requestPath,
1004
- queryParameters,
1005
- headers,
1006
- data: getRecommendationsParams,
1007
- useReadTransporter: true,
1008
- cacheable: true,
1009
- };
1010
- return transporter.request(request, requestOptions);
1011
- },
1012
- /**
1013
- * Searches for Recommend rules. Use an empty query to list all rules for this recommendation scenario.
1014
- *
1015
- * Required API Key ACLs:
1016
- * - settings.
1017
- *
1018
- * @param searchRecommendRules - The searchRecommendRules object.
1019
- * @param searchRecommendRules.indexName - Name of the index on which to perform the operation.
1020
- * @param searchRecommendRules.model - [Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models).
1021
- * @param searchRecommendRules.searchRecommendRulesParams - The searchRecommendRulesParams object.
1022
- * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
1023
- */
1024
- searchRecommendRules({ indexName, model, searchRecommendRulesParams }, requestOptions) {
1025
- if (!indexName) {
1026
- throw new Error('Parameter `indexName` is required when calling `searchRecommendRules`.');
1027
- }
1028
- if (!model) {
1029
- throw new Error('Parameter `model` is required when calling `searchRecommendRules`.');
1030
- }
1031
- const requestPath = '/1/indexes/{indexName}/{model}/recommend/rules/search'
1032
- .replace('{indexName}', encodeURIComponent(indexName))
1033
- .replace('{model}', encodeURIComponent(model));
1034
- const headers = {};
1035
- const queryParameters = {};
1036
- const request = {
1037
- method: 'POST',
1038
- path: requestPath,
1039
- queryParameters,
1040
- headers,
1041
- data: searchRecommendRulesParams ? searchRecommendRulesParams : {},
1042
- useReadTransporter: true,
1043
- cacheable: true,
1044
- };
1045
- return transporter.request(request, requestOptions);
1046
- },
1047
- };
1048
- }
1049
-
1050
- // Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT.
1051
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
1052
- function recommendClient(appId, apiKey, options) {
1053
- if (!appId || typeof appId !== 'string') {
1054
- throw new Error('`appId` is missing.');
1055
- }
1056
- if (!apiKey || typeof apiKey !== 'string') {
1057
- throw new Error('`apiKey` is missing.');
1058
- }
1059
- return createRecommendClient({
1060
- appId,
1061
- apiKey,
1062
- timeouts: {
1063
- connect: DEFAULT_CONNECT_TIMEOUT_BROWSER,
1064
- read: DEFAULT_READ_TIMEOUT_BROWSER,
1065
- write: DEFAULT_WRITE_TIMEOUT_BROWSER,
1066
- },
1067
- requester: createXhrRequester(),
1068
- algoliaAgents: [{ segment: 'Browser' }],
1069
- authMode: 'WithinQueryParameters',
1070
- responsesCache: createMemoryCache(),
1071
- requestsCache: createMemoryCache({ serializable: false }),
1072
- hostsCache: createFallbackableCache({
1073
- caches: [createBrowserLocalStorageCache({ key: `${apiClientVersion}-${appId}` }), createMemoryCache()],
1074
- }),
1075
- ...options,
1076
- });
1077
- }
1078
-
1079
- export { apiClientVersion, recommendClient };