@algolia/client-personalization 5.0.0-alpha.1 → 5.0.0-alpha.100

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 (39) hide show
  1. package/dist/builds/browser.d.ts +5 -5
  2. package/dist/builds/browser.d.ts.map +1 -1
  3. package/dist/builds/node.d.ts +5 -5
  4. package/dist/builds/node.d.ts.map +1 -1
  5. package/dist/{client-personalization.cjs.js → client-personalization.cjs} +287 -274
  6. package/dist/client-personalization.esm.browser.js +499 -508
  7. package/dist/client-personalization.esm.node.js +287 -272
  8. package/dist/client-personalization.umd.js +2 -2
  9. package/dist/model/clientMethodProps.d.ts +78 -78
  10. package/dist/model/clientMethodProps.d.ts.map +1 -1
  11. package/dist/model/deleteUserProfileResponse.d.ts +10 -10
  12. package/dist/model/deleteUserProfileResponse.d.ts.map +1 -1
  13. package/dist/model/errorBase.d.ts +6 -6
  14. package/dist/model/errorBase.d.ts.map +1 -1
  15. package/dist/model/eventScoring.d.ts +14 -14
  16. package/dist/model/eventScoring.d.ts.map +1 -1
  17. package/dist/model/facetScoring.d.ts +10 -10
  18. package/dist/model/facetScoring.d.ts.map +1 -1
  19. package/dist/model/getUserTokenResponse.d.ts +14 -14
  20. package/dist/model/getUserTokenResponse.d.ts.map +1 -1
  21. package/dist/model/index.d.ts +8 -8
  22. package/dist/model/index.d.ts.map +1 -1
  23. package/dist/model/personalizationStrategyParams.d.ts +16 -16
  24. package/dist/model/personalizationStrategyParams.d.ts.map +1 -1
  25. package/dist/model/setPersonalizationStrategyResponse.d.ts +6 -6
  26. package/dist/model/setPersonalizationStrategyResponse.d.ts.map +1 -1
  27. package/dist/src/personalizationClient.d.ts +116 -101
  28. package/dist/src/personalizationClient.d.ts.map +1 -1
  29. package/index.js +1 -1
  30. package/model/clientMethodProps.ts +36 -36
  31. package/model/deleteUserProfileResponse.ts +2 -1
  32. package/model/errorBase.ts +1 -1
  33. package/model/eventScoring.ts +3 -1
  34. package/model/facetScoring.ts +2 -1
  35. package/model/getUserTokenResponse.ts +3 -1
  36. package/model/index.ts +1 -1
  37. package/model/personalizationStrategyParams.ts +3 -1
  38. package/model/setPersonalizationStrategyResponse.ts +1 -1
  39. package/package.json +32 -13
@@ -7,53 +7,69 @@ function createAuth(appId, apiKey, authMode = 'WithinHeaders') {
7
7
  headers() {
8
8
  return authMode === 'WithinHeaders' ? credentials : {};
9
9
  },
10
-
11
10
  queryParameters() {
12
11
  return authMode === 'WithinQueryParameters' ? credentials : {};
13
12
  }
14
-
15
13
  };
16
14
  }
17
15
 
18
16
  function createBrowserLocalStorageCache(options) {
19
- let storage; // We've changed the namespace to avoid conflicts with v4, as this version is a huge breaking change
20
-
17
+ let storage;
18
+ // We've changed the namespace to avoid conflicts with v4, as this version is a huge breaking change
21
19
  const namespaceKey = `algolia-client-js-${options.key}`;
22
-
23
20
  function getStorage() {
24
21
  if (storage === undefined) {
25
22
  storage = options.localStorage || window.localStorage;
26
23
  }
27
-
28
24
  return storage;
29
25
  }
30
-
31
26
  function getNamespace() {
32
27
  return JSON.parse(getStorage().getItem(namespaceKey) || '{}');
33
28
  }
34
-
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
+ }
35
49
  return {
36
50
  get(key, defaultValue, events = {
37
51
  miss: () => Promise.resolve()
38
52
  }) {
39
53
  return Promise.resolve().then(() => {
40
- const keyAsString = JSON.stringify(key);
41
- const value = getNamespace()[keyAsString];
42
- return Promise.all([value || defaultValue(), value !== undefined]);
54
+ removeOutdatedCacheItems();
55
+ return getNamespace()[JSON.stringify(key)];
56
+ }).then(value => {
57
+ return Promise.all([value ? value.value : defaultValue(), value !== undefined]);
43
58
  }).then(([value, exists]) => {
44
59
  return Promise.all([value, exists || events.miss(value)]);
45
60
  }).then(([value]) => value);
46
61
  },
47
-
48
62
  set(key, value) {
49
63
  return Promise.resolve().then(() => {
50
64
  const namespace = getNamespace();
51
- namespace[JSON.stringify(key)] = value;
65
+ namespace[JSON.stringify(key)] = {
66
+ timestamp: new Date().getTime(),
67
+ value
68
+ };
52
69
  getStorage().setItem(namespaceKey, JSON.stringify(namespace));
53
70
  return value;
54
71
  });
55
72
  },
56
-
57
73
  delete(key) {
58
74
  return Promise.resolve().then(() => {
59
75
  const namespace = getNamespace();
@@ -61,13 +77,11 @@ function createBrowserLocalStorageCache(options) {
61
77
  getStorage().setItem(namespaceKey, JSON.stringify(namespace));
62
78
  });
63
79
  },
64
-
65
80
  clear() {
66
81
  return Promise.resolve().then(() => {
67
82
  getStorage().removeItem(namespaceKey);
68
83
  });
69
84
  }
70
-
71
85
  };
72
86
  }
73
87
 
@@ -79,30 +93,24 @@ function createNullCache() {
79
93
  const value = defaultValue();
80
94
  return value.then(result => Promise.all([result, events.miss(result)])).then(([result]) => result);
81
95
  },
82
-
83
96
  set(_key, value) {
84
97
  return Promise.resolve(value);
85
98
  },
86
-
87
99
  delete(_key) {
88
100
  return Promise.resolve();
89
101
  },
90
-
91
102
  clear() {
92
103
  return Promise.resolve();
93
104
  }
94
-
95
105
  };
96
106
  }
97
107
 
98
108
  function createFallbackableCache(options) {
99
109
  const caches = [...options.caches];
100
110
  const current = caches.shift();
101
-
102
111
  if (current === undefined) {
103
112
  return createNullCache();
104
113
  }
105
-
106
114
  return {
107
115
  get(key, defaultValue, events = {
108
116
  miss: () => Promise.resolve()
@@ -113,7 +121,6 @@ function createFallbackableCache(options) {
113
121
  }).get(key, defaultValue, events);
114
122
  });
115
123
  },
116
-
117
124
  set(key, value) {
118
125
  return current.set(key, value).catch(() => {
119
126
  return createFallbackableCache({
@@ -121,7 +128,6 @@ function createFallbackableCache(options) {
121
128
  }).set(key, value);
122
129
  });
123
130
  },
124
-
125
131
  delete(key) {
126
132
  return current.delete(key).catch(() => {
127
133
  return createFallbackableCache({
@@ -129,7 +135,6 @@ function createFallbackableCache(options) {
129
135
  }).delete(key);
130
136
  });
131
137
  },
132
-
133
138
  clear() {
134
139
  return current.clear().catch(() => {
135
140
  return createFallbackableCache({
@@ -137,7 +142,6 @@ function createFallbackableCache(options) {
137
142
  }).clear();
138
143
  });
139
144
  }
140
-
141
145
  };
142
146
  }
143
147
 
@@ -150,30 +154,24 @@ function createMemoryCache(options = {
150
154
  miss: () => Promise.resolve()
151
155
  }) {
152
156
  const keyAsString = JSON.stringify(key);
153
-
154
157
  if (keyAsString in cache) {
155
158
  return Promise.resolve(options.serializable ? JSON.parse(cache[keyAsString]) : cache[keyAsString]);
156
159
  }
157
-
158
160
  const promise = defaultValue();
159
161
  return promise.then(value => events.miss(value)).then(() => promise);
160
162
  },
161
-
162
163
  set(key, value) {
163
164
  cache[JSON.stringify(key)] = options.serializable ? JSON.stringify(value) : value;
164
165
  return Promise.resolve(value);
165
166
  },
166
-
167
167
  delete(key) {
168
168
  delete cache[JSON.stringify(key)];
169
169
  return Promise.resolve();
170
170
  },
171
-
172
171
  clear() {
173
172
  cache = {};
174
173
  return Promise.resolve();
175
174
  }
176
-
177
175
  };
178
176
  }
179
177
 
@@ -182,16 +180,14 @@ function createMemoryCache(options = {
182
180
  const EXPIRATION_DELAY = 2 * 60 * 1000;
183
181
  function createStatefulHost(host, status = 'up') {
184
182
  const lastUpdate = Date.now();
185
-
186
183
  function isUp() {
187
184
  return status === 'up' || Date.now() - lastUpdate > EXPIRATION_DELAY;
188
185
  }
189
-
190
186
  function isTimedOut() {
191
187
  return status === 'timed out' && Date.now() - lastUpdate <= EXPIRATION_DELAY;
192
188
  }
193
-
194
- return { ...host,
189
+ return {
190
+ ...host,
195
191
  status,
196
192
  lastUpdate,
197
193
  isUp,
@@ -199,7 +195,22 @@ function createStatefulHost(host, status = 'up') {
199
195
  };
200
196
  }
201
197
 
198
+ function _toPrimitive(t, r) {
199
+ if ("object" != typeof t || !t) return t;
200
+ var e = t[Symbol.toPrimitive];
201
+ if (void 0 !== e) {
202
+ var i = e.call(t, r || "default");
203
+ if ("object" != typeof i) return i;
204
+ throw new TypeError("@@toPrimitive must return a primitive value.");
205
+ }
206
+ return ("string" === r ? String : Number)(t);
207
+ }
208
+ function _toPropertyKey(t) {
209
+ var i = _toPrimitive(t, "string");
210
+ return "symbol" == typeof i ? i : String(i);
211
+ }
202
212
  function _defineProperty(obj, key, value) {
213
+ key = _toPropertyKey(key);
203
214
  if (key in obj) {
204
215
  Object.defineProperty(obj, key, {
205
216
  value: value,
@@ -210,79 +221,71 @@ function _defineProperty(obj, key, value) {
210
221
  } else {
211
222
  obj[key] = value;
212
223
  }
213
-
214
224
  return obj;
215
225
  }
216
226
 
217
227
  class AlgoliaError extends Error {
218
228
  constructor(message, name) {
219
229
  super(message);
220
-
221
230
  _defineProperty(this, "name", 'AlgoliaError');
222
-
223
231
  if (name) {
224
232
  this.name = name;
225
233
  }
226
234
  }
227
-
228
235
  }
229
236
  class ErrorWithStackTrace extends AlgoliaError {
230
237
  constructor(message, stackTrace, name) {
231
- super(message, name); // the array and object should be frozen to reflect the stackTrace at the time of the error
232
-
238
+ super(message, name);
239
+ // the array and object should be frozen to reflect the stackTrace at the time of the error
233
240
  _defineProperty(this, "stackTrace", void 0);
234
-
235
241
  this.stackTrace = stackTrace;
236
242
  }
237
-
238
243
  }
239
244
  class RetryError extends ErrorWithStackTrace {
240
245
  constructor(stackTrace) {
241
- super('Unreachable hosts - your application id may be incorrect. If the error persists, contact support@algolia.com.', stackTrace, 'RetryError');
246
+ super('Unreachable hosts - your application id may be incorrect. If the error persists, please create a ticket at https://support.algolia.com/ sharing steps we can use to reproduce the issue.', stackTrace, 'RetryError');
242
247
  }
243
-
244
248
  }
245
249
  class ApiError extends ErrorWithStackTrace {
246
- constructor(message, status, stackTrace) {
247
- super(message, stackTrace, 'ApiError');
248
-
250
+ constructor(message, status, stackTrace, name = 'ApiError') {
251
+ super(message, stackTrace, name);
249
252
  _defineProperty(this, "status", void 0);
250
-
251
253
  this.status = status;
252
254
  }
253
-
254
255
  }
255
256
  class DeserializationError extends AlgoliaError {
256
257
  constructor(message, response) {
257
258
  super(message, 'DeserializationError');
258
-
259
259
  _defineProperty(this, "response", void 0);
260
-
261
260
  this.response = response;
262
261
  }
263
-
262
+ }
263
+ // DetailedApiError is only used by the ingestion client to return more informative error, other clients will use ApiClient.
264
+ class DetailedApiError extends ApiError {
265
+ constructor(message, status, error, stackTrace) {
266
+ super(message, status, stackTrace, 'DetailedApiError');
267
+ _defineProperty(this, "error", void 0);
268
+ this.error = error;
269
+ }
264
270
  }
265
271
  function serializeUrl(host, path, queryParameters) {
266
272
  const queryParametersAsString = serializeQueryParameters(queryParameters);
267
273
  let url = `${host.protocol}://${host.url}/${path.charAt(0) === '/' ? path.substr(1) : path}`;
268
-
269
274
  if (queryParametersAsString.length) {
270
275
  url += `?${queryParametersAsString}`;
271
276
  }
272
-
273
277
  return url;
274
278
  }
275
279
  function serializeQueryParameters(parameters) {
276
280
  const isObjectOrArray = value => Object.prototype.toString.call(value) === '[object Object]' || Object.prototype.toString.call(value) === '[object Array]';
277
-
278
- return Object.keys(parameters).map(key => `${key}=${isObjectOrArray(parameters[key]) ? JSON.stringify(parameters[key]) : parameters[key]}`).join('&');
281
+ return Object.keys(parameters).map(key => `${key}=${encodeURIComponent(isObjectOrArray(parameters[key]) ? JSON.stringify(parameters[key]) : parameters[key])}`).join('&');
279
282
  }
280
283
  function serializeData(request, requestOptions) {
281
284
  if (request.method === 'GET' || request.data === undefined && requestOptions.data === undefined) {
282
285
  return undefined;
283
286
  }
284
-
285
- const data = Array.isArray(request.data) ? request.data : { ...request.data,
287
+ const data = Array.isArray(request.data) ? request.data : {
288
+ ...request.data,
286
289
  ...requestOptions.data
287
290
  };
288
291
  return JSON.stringify(data);
@@ -312,14 +315,16 @@ function deserializeFailure({
312
315
  content,
313
316
  status
314
317
  }, stackFrame) {
315
- let message = content;
316
-
317
318
  try {
318
- message = JSON.parse(content).message;
319
- } catch (e) {// ..
319
+ const parsed = JSON.parse(content);
320
+ if ('error' in parsed) {
321
+ return new DetailedApiError(parsed.message, status, parsed.error, stackFrame);
322
+ }
323
+ return new ApiError(parsed.message, status, stackFrame);
324
+ } catch (e) {
325
+ // ..
320
326
  }
321
-
322
- return new ApiError(message, status, stackFrame);
327
+ return new ApiError(content, status, stackFrame);
323
328
  }
324
329
 
325
330
  function isNetworkError({
@@ -350,9 +355,12 @@ function stackFrameWithoutCredentials(stackFrame) {
350
355
  const modifiedHeaders = stackFrame.request.headers['x-algolia-api-key'] ? {
351
356
  'x-algolia-api-key': '*****'
352
357
  } : {};
353
- return { ...stackFrame,
354
- request: { ...stackFrame.request,
355
- headers: { ...stackFrame.request.headers,
358
+ return {
359
+ ...stackFrame,
360
+ request: {
361
+ ...stackFrame.request,
362
+ headers: {
363
+ ...stackFrame.request.headers,
356
364
  ...modifiedHeaders
357
365
  }
358
366
  }
@@ -377,51 +385,49 @@ function createTransporter({
377
385
  });
378
386
  }));
379
387
  const hostsUp = statefulHosts.filter(host => host.isUp());
380
- const hostsTimedOut = statefulHosts.filter(host => host.isTimedOut()); // Note, we put the hosts that previously timed out on the end of the list.
381
-
388
+ const hostsTimedOut = statefulHosts.filter(host => host.isTimedOut());
389
+ // Note, we put the hosts that previously timed out on the end of the list.
382
390
  const hostsAvailable = [...hostsUp, ...hostsTimedOut];
383
391
  const compatibleHostsAvailable = hostsAvailable.length > 0 ? hostsAvailable : compatibleHosts;
384
392
  return {
385
393
  hosts: compatibleHostsAvailable,
386
-
387
394
  getTimeout(timeoutsCount, baseTimeout) {
388
- /**
389
- * Imagine that you have 4 hosts, if timeouts will increase
390
- * on the following way: 1 (timed out) > 4 (timed out) > 5 (200).
391
- *
392
- * Note that, the very next request, we start from the previous timeout.
393
- *
394
- * 5 (timed out) > 6 (timed out) > 7 ...
395
- *
396
- * This strategy may need to be reviewed, but is the strategy on the our
397
- * current v3 version.
395
+ /**
396
+ * Imagine that you have 4 hosts, if timeouts will increase
397
+ * on the following way: 1 (timed out) > 4 (timed out) > 5 (200).
398
+ *
399
+ * Note that, the very next request, we start from the previous timeout.
400
+ *
401
+ * 5 (timed out) > 6 (timed out) > 7 ...
402
+ *
403
+ * This strategy may need to be reviewed, but is the strategy on the our
404
+ * current v3 version.
398
405
  */
399
406
  const timeoutMultiplier = hostsTimedOut.length === 0 && timeoutsCount === 0 ? 1 : hostsTimedOut.length + 3 + timeoutsCount;
400
407
  return timeoutMultiplier * baseTimeout;
401
408
  }
402
-
403
409
  };
404
410
  }
405
-
406
411
  async function retryableRequest(request, requestOptions, isRead = true) {
407
412
  const stackTrace = [];
408
- /**
409
- * First we prepare the payload that do not depend from hosts.
413
+ /**
414
+ * First we prepare the payload that do not depend from hosts.
410
415
  */
411
-
412
416
  const data = serializeData(request, requestOptions);
413
- const headers = serializeHeaders(baseHeaders, request.headers, requestOptions.headers); // On `GET`, the data is proxied to query parameters.
414
-
415
- const dataQueryParameters = request.method === 'GET' ? { ...request.data,
417
+ const headers = serializeHeaders(baseHeaders, request.headers, requestOptions.headers);
418
+ // On `GET`, the data is proxied to query parameters.
419
+ const dataQueryParameters = request.method === 'GET' ? {
420
+ ...request.data,
416
421
  ...requestOptions.data
417
422
  } : {};
418
423
  const queryParameters = {
419
- 'x-algolia-agent': algoliaAgent.value,
420
424
  ...baseQueryParameters,
421
425
  ...request.queryParameters,
422
426
  ...dataQueryParameters
423
427
  };
424
-
428
+ if (algoliaAgent.value) {
429
+ queryParameters['x-algolia-agent'] = algoliaAgent.value;
430
+ }
425
431
  if (requestOptions && requestOptions.queryParameters) {
426
432
  for (const key of Object.keys(requestOptions.queryParameters)) {
427
433
  // We want to keep `undefined` and `null` values,
@@ -434,25 +440,19 @@ function createTransporter({
434
440
  }
435
441
  }
436
442
  }
437
-
438
443
  let timeoutsCount = 0;
439
-
440
444
  const retry = async (retryableHosts, getTimeout) => {
441
- /**
442
- * We iterate on each host, until there is no host left.
445
+ /**
446
+ * We iterate on each host, until there is no host left.
443
447
  */
444
448
  const host = retryableHosts.pop();
445
-
446
449
  if (host === undefined) {
447
450
  throw new RetryError(stackTraceWithoutCredentials(stackTrace));
448
451
  }
449
-
450
452
  let responseTimeout = requestOptions.timeout;
451
-
452
453
  if (responseTimeout === undefined) {
453
454
  responseTimeout = isRead ? timeouts.read : timeouts.write;
454
455
  }
455
-
456
456
  const payload = {
457
457
  data,
458
458
  headers,
@@ -461,12 +461,11 @@ function createTransporter({
461
461
  connectTimeout: getTimeout(timeoutsCount, timeouts.connect),
462
462
  responseTimeout: getTimeout(timeoutsCount, responseTimeout)
463
463
  };
464
- /**
465
- * The stackFrame is pushed to the stackTrace so we
466
- * can have information about onRetry and onFailure
467
- * decisions.
464
+ /**
465
+ * The stackFrame is pushed to the stackTrace so we
466
+ * can have information about onRetry and onFailure
467
+ * decisions.
468
468
  */
469
-
470
469
  const pushToStackTrace = response => {
471
470
  const stackFrame = {
472
471
  request: payload,
@@ -477,102 +476,85 @@ function createTransporter({
477
476
  stackTrace.push(stackFrame);
478
477
  return stackFrame;
479
478
  };
480
-
481
479
  const response = await requester.send(payload);
482
-
483
480
  if (isRetryable(response)) {
484
- const stackFrame = pushToStackTrace(response); // If response is a timeout, we increase the number of timeouts so we can increase the timeout later.
485
-
481
+ const stackFrame = pushToStackTrace(response);
482
+ // If response is a timeout, we increase the number of timeouts so we can increase the timeout later.
486
483
  if (response.isTimedOut) {
487
484
  timeoutsCount++;
488
485
  }
489
- /**
490
- * Failures are individually sent to the logger, allowing
491
- * the end user to debug / store stack frames even
492
- * when a retry error does not happen.
486
+ /**
487
+ * Failures are individually sent to the logger, allowing
488
+ * the end user to debug / store stack frames even
489
+ * when a retry error does not happen.
493
490
  */
494
491
  // eslint-disable-next-line no-console -- this will be fixed by exposing a `logger` to the transporter
495
-
496
-
497
492
  console.log('Retryable failure', stackFrameWithoutCredentials(stackFrame));
498
- /**
499
- * We also store the state of the host in failure cases. If the host, is
500
- * down it will remain down for the next 2 minutes. In a timeout situation,
501
- * this host will be added end of the list of hosts on the next request.
493
+ /**
494
+ * We also store the state of the host in failure cases. If the host, is
495
+ * down it will remain down for the next 2 minutes. In a timeout situation,
496
+ * this host will be added end of the list of hosts on the next request.
502
497
  */
503
-
504
498
  await hostsCache.set(host, createStatefulHost(host, response.isTimedOut ? 'timed out' : 'down'));
505
499
  return retry(retryableHosts, getTimeout);
506
500
  }
507
-
508
501
  if (isSuccess(response)) {
509
502
  return deserializeSuccess(response);
510
503
  }
511
-
512
504
  pushToStackTrace(response);
513
505
  throw deserializeFailure(response, stackTrace);
514
506
  };
515
- /**
516
- * Finally, for each retryable host perform request until we got a non
517
- * retryable response. Some notes here:
518
- *
519
- * 1. The reverse here is applied so we can apply a `pop` later on => more performant.
520
- * 2. We also get from the retryable options a timeout multiplier that is tailored
521
- * for the current context.
507
+ /**
508
+ * Finally, for each retryable host perform request until we got a non
509
+ * retryable response. Some notes here:
510
+ *
511
+ * 1. The reverse here is applied so we can apply a `pop` later on => more performant.
512
+ * 2. We also get from the retryable options a timeout multiplier that is tailored
513
+ * for the current context.
522
514
  */
523
-
524
-
525
515
  const compatibleHosts = hosts.filter(host => host.accept === 'readWrite' || (isRead ? host.accept === 'read' : host.accept === 'write'));
526
516
  const options = await createRetryableOptions(compatibleHosts);
527
517
  return retry([...options.hosts].reverse(), options.getTimeout);
528
518
  }
529
-
530
519
  function createRequest(request, requestOptions = {}) {
531
- /**
532
- * A read request is either a `GET` request, or a request that we make
533
- * via the `read` transporter (e.g. `search`).
520
+ /**
521
+ * A read request is either a `GET` request, or a request that we make
522
+ * via the `read` transporter (e.g. `search`).
534
523
  */
535
524
  const isRead = request.useReadTransporter || request.method === 'GET';
536
-
537
525
  if (!isRead) {
538
- /**
539
- * On write requests, no cache mechanisms are applied, and we
540
- * proxy the request immediately to the requester.
526
+ /**
527
+ * On write requests, no cache mechanisms are applied, and we
528
+ * proxy the request immediately to the requester.
541
529
  */
542
530
  return retryableRequest(request, requestOptions, isRead);
543
531
  }
544
-
545
532
  const createRetryableRequest = () => {
546
- /**
547
- * Then, we prepare a function factory that contains the construction of
548
- * the retryable request. At this point, we may *not* perform the actual
549
- * request. But we want to have the function factory ready.
533
+ /**
534
+ * Then, we prepare a function factory that contains the construction of
535
+ * the retryable request. At this point, we may *not* perform the actual
536
+ * request. But we want to have the function factory ready.
550
537
  */
551
538
  return retryableRequest(request, requestOptions);
552
539
  };
553
- /**
554
- * Once we have the function factory ready, we need to determine of the
555
- * request is "cacheable" - should be cached. Note that, once again,
556
- * the user can force this option.
540
+ /**
541
+ * Once we have the function factory ready, we need to determine of the
542
+ * request is "cacheable" - should be cached. Note that, once again,
543
+ * the user can force this option.
557
544
  */
558
-
559
-
560
545
  const cacheable = requestOptions.cacheable || request.cacheable;
561
- /**
562
- * If is not "cacheable", we immediately trigger the retryable request, no
563
- * need to check cache implementations.
546
+ /**
547
+ * If is not "cacheable", we immediately trigger the retryable request, no
548
+ * need to check cache implementations.
564
549
  */
565
-
566
550
  if (cacheable !== true) {
567
551
  return createRetryableRequest();
568
552
  }
569
- /**
570
- * If the request is "cacheable", we need to first compute the key to ask
571
- * the cache implementations if this request is on progress or if the
572
- * response already exists on the cache.
553
+ /**
554
+ * If the request is "cacheable", we need to first compute the key to ask
555
+ * the cache implementations if this request is on progress or if the
556
+ * response already exists on the cache.
573
557
  */
574
-
575
-
576
558
  const key = {
577
559
  request,
578
560
  requestOptions,
@@ -581,33 +563,31 @@ function createTransporter({
581
563
  headers: baseHeaders
582
564
  }
583
565
  };
584
- /**
585
- * With the computed key, we first ask the responses cache
586
- * implementation if this request was been resolved before.
566
+ /**
567
+ * With the computed key, we first ask the responses cache
568
+ * implementation if this request was been resolved before.
587
569
  */
588
-
589
570
  return responsesCache.get(key, () => {
590
- /**
591
- * If the request has never resolved before, we actually ask if there
592
- * is a current request with the same key on progress.
571
+ /**
572
+ * If the request has never resolved before, we actually ask if there
573
+ * is a current request with the same key on progress.
593
574
  */
594
575
  return requestsCache.get(key, () =>
595
- /**
596
- * Finally, if there is no request in progress with the same key,
597
- * this `createRetryableRequest()` will actually trigger the
598
- * retryable request.
576
+ /**
577
+ * Finally, if there is no request in progress with the same key,
578
+ * this `createRetryableRequest()` will actually trigger the
579
+ * retryable request.
599
580
  */
600
581
  requestsCache.set(key, createRetryableRequest()).then(response => Promise.all([requestsCache.delete(key), response]), err => Promise.all([requestsCache.delete(key), Promise.reject(err)])).then(([_, response]) => response));
601
582
  }, {
602
- /**
603
- * Of course, once we get this response back from the server, we
604
- * tell response cache to actually store the received response
605
- * to be used later.
583
+ /**
584
+ * Of course, once we get this response back from the server, we
585
+ * tell response cache to actually store the received response
586
+ * to be used later.
606
587
  */
607
588
  miss: response => responsesCache.set(key, response)
608
589
  });
609
590
  }
610
-
611
591
  return {
612
592
  hostsCache,
613
593
  requester,
@@ -625,17 +605,13 @@ function createTransporter({
625
605
  function createAlgoliaAgent(version) {
626
606
  const algoliaAgent = {
627
607
  value: `Algolia for JavaScript (${version})`,
628
-
629
608
  add(options) {
630
609
  const addedAlgoliaAgent = `; ${options.segment}${options.version !== undefined ? ` (${options.version})` : ''}`;
631
-
632
610
  if (algoliaAgent.value.indexOf(addedAlgoliaAgent) === -1) {
633
611
  algoliaAgent.value = `${algoliaAgent.value}${addedAlgoliaAgent}`;
634
612
  }
635
-
636
613
  return algoliaAgent;
637
614
  }
638
-
639
615
  };
640
616
  return algoliaAgent;
641
617
  }
@@ -657,338 +633,353 @@ const DEFAULT_CONNECT_TIMEOUT_BROWSER = 1000;
657
633
  const DEFAULT_READ_TIMEOUT_BROWSER = 2000;
658
634
  const DEFAULT_WRITE_TIMEOUT_BROWSER = 30000;
659
635
 
660
- function createXhrRequester() {
661
- function send(request) {
662
- return new Promise((resolve) => {
663
- const baseRequester = new XMLHttpRequest();
664
- baseRequester.open(request.method, request.url, true);
665
- Object.keys(request.headers).forEach((key) => baseRequester.setRequestHeader(key, request.headers[key]));
666
- const createTimeout = (timeout, content) => {
667
- return setTimeout(() => {
668
- baseRequester.abort();
669
- resolve({
670
- status: 0,
671
- content,
672
- isTimedOut: true,
673
- });
674
- }, timeout);
675
- };
676
- const connectTimeout = createTimeout(request.connectTimeout, 'Connection timeout');
677
- let responseTimeout;
678
- baseRequester.onreadystatechange = () => {
679
- if (baseRequester.readyState > baseRequester.OPENED &&
680
- responseTimeout === undefined) {
681
- clearTimeout(connectTimeout);
682
- responseTimeout = createTimeout(request.responseTimeout, 'Socket timeout');
683
- }
684
- };
685
- baseRequester.onerror = () => {
686
- // istanbul ignore next
687
- if (baseRequester.status === 0) {
688
- clearTimeout(connectTimeout);
689
- clearTimeout(responseTimeout);
690
- resolve({
691
- content: baseRequester.responseText || 'Network request failed',
692
- status: baseRequester.status,
693
- isTimedOut: false,
694
- });
695
- }
696
- };
697
- baseRequester.onload = () => {
698
- clearTimeout(connectTimeout);
699
- clearTimeout(responseTimeout);
700
- resolve({
701
- content: baseRequester.responseText,
702
- status: baseRequester.status,
703
- isTimedOut: false,
704
- });
705
- };
706
- baseRequester.send(request.data);
707
- });
708
- }
709
- return { send };
636
+ function createXhrRequester() {
637
+ function send(request) {
638
+ return new Promise((resolve) => {
639
+ const baseRequester = new XMLHttpRequest();
640
+ baseRequester.open(request.method, request.url, true);
641
+ Object.keys(request.headers).forEach((key) => baseRequester.setRequestHeader(key, request.headers[key]));
642
+ const createTimeout = (timeout, content) => {
643
+ return setTimeout(() => {
644
+ baseRequester.abort();
645
+ resolve({
646
+ status: 0,
647
+ content,
648
+ isTimedOut: true,
649
+ });
650
+ }, timeout);
651
+ };
652
+ const connectTimeout = createTimeout(request.connectTimeout, 'Connection timeout');
653
+ let responseTimeout;
654
+ baseRequester.onreadystatechange = () => {
655
+ if (baseRequester.readyState > baseRequester.OPENED &&
656
+ responseTimeout === undefined) {
657
+ clearTimeout(connectTimeout);
658
+ responseTimeout = createTimeout(request.responseTimeout, 'Socket timeout');
659
+ }
660
+ };
661
+ baseRequester.onerror = () => {
662
+ // istanbul ignore next
663
+ if (baseRequester.status === 0) {
664
+ clearTimeout(connectTimeout);
665
+ clearTimeout(responseTimeout);
666
+ resolve({
667
+ content: baseRequester.responseText || 'Network request failed',
668
+ status: baseRequester.status,
669
+ isTimedOut: false,
670
+ });
671
+ }
672
+ };
673
+ baseRequester.onload = () => {
674
+ clearTimeout(connectTimeout);
675
+ clearTimeout(responseTimeout);
676
+ resolve({
677
+ content: baseRequester.responseText,
678
+ status: baseRequester.status,
679
+ isTimedOut: false,
680
+ });
681
+ };
682
+ baseRequester.send(request.data);
683
+ });
684
+ }
685
+ return { send };
710
686
  }
711
687
 
712
- // This file is generated, manual changes will be lost - read more on https://github.com/algolia/api-clients-automation.
713
- const apiClientVersion = '5.0.0-alpha.1';
714
- const REGIONS = ['eu', 'us'];
715
- function getDefaultHosts(region) {
716
- const url = 'personalization.{region}.algolia.com'.replace('{region}', region);
717
- return [{ url, accept: 'readWrite', protocol: 'https' }];
718
- }
719
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
720
- function createPersonalizationClient({ appId: appIdOption, apiKey: apiKeyOption, authMode, algoliaAgents, region: regionOption, ...options }) {
721
- const auth = createAuth(appIdOption, apiKeyOption, authMode);
722
- const transporter = createTransporter({
723
- hosts: getDefaultHosts(regionOption),
724
- ...options,
725
- algoliaAgent: getAlgoliaAgent({
726
- algoliaAgents,
727
- client: 'Personalization',
728
- version: apiClientVersion,
729
- }),
730
- baseHeaders: {
731
- 'content-type': 'text/plain',
732
- ...auth.headers(),
733
- ...options.baseHeaders,
734
- },
735
- baseQueryParameters: {
736
- ...auth.queryParameters(),
737
- ...options.baseQueryParameters,
738
- },
739
- });
740
- return {
741
- transporter,
742
- /**
743
- * Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
744
- */
745
- get _ua() {
746
- return transporter.algoliaAgent.value;
747
- },
748
- /**
749
- * Adds a `segment` to the `x-algolia-agent` sent with every requests.
750
- *
751
- * @param segment - The algolia agent (user-agent) segment to add.
752
- * @param version - The version of the agent.
753
- */
754
- addAlgoliaAgent(segment, version) {
755
- transporter.algoliaAgent.add({ segment, version });
756
- },
757
- /**
758
- * This method allow you to send requests to the Algolia REST API.
759
- *
760
- * @summary Send requests to the Algolia REST API.
761
- * @param del - The del object.
762
- * @param del.path - The path of the API endpoint to target, anything after the /1 needs to be specified.
763
- * @param del.parameters - Query parameters to be applied to the current query.
764
- * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
765
- */
766
- del({ path, parameters }, requestOptions) {
767
- if (!path) {
768
- throw new Error('Parameter `path` is required when calling `del`.');
769
- }
770
- const requestPath = '/1{path}'.replace('{path}', path);
771
- const headers = {};
772
- const queryParameters = parameters ? parameters : {};
773
- const request = {
774
- method: 'DELETE',
775
- path: requestPath,
776
- queryParameters,
777
- headers,
778
- };
779
- return transporter.request(request, requestOptions);
780
- },
781
- /**
782
- * Delete the user profile and all its associated data. Returns, as part of the response, a date until which the data can safely be considered as deleted for the given user. This means if you send events for the given user before this date, they will be ignored. Any data received after the deletedUntil date will start building a new user profile. It might take a couple hours for the deletion request to be fully processed.
783
- *
784
- * @summary Delete a user profile.
785
- * @param deleteUserProfile - The deleteUserProfile object.
786
- * @param deleteUserProfile.userToken - UserToken representing the user for which to fetch the Personalization profile.
787
- * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
788
- */
789
- deleteUserProfile({ userToken }, requestOptions) {
790
- if (!userToken) {
791
- throw new Error('Parameter `userToken` is required when calling `deleteUserProfile`.');
792
- }
793
- const requestPath = '/1/profiles/{userToken}'.replace('{userToken}', encodeURIComponent(userToken));
794
- const headers = {};
795
- const queryParameters = {};
796
- const request = {
797
- method: 'DELETE',
798
- path: requestPath,
799
- queryParameters,
800
- headers,
801
- };
802
- return transporter.request(request, requestOptions);
803
- },
804
- /**
805
- * This method allow you to send requests to the Algolia REST API.
806
- *
807
- * @summary Send requests to the Algolia REST API.
808
- * @param get - The get object.
809
- * @param get.path - The path of the API endpoint to target, anything after the /1 needs to be specified.
810
- * @param get.parameters - Query parameters to be applied to the current query.
811
- * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
812
- */
813
- get({ path, parameters }, requestOptions) {
814
- if (!path) {
815
- throw new Error('Parameter `path` is required when calling `get`.');
816
- }
817
- const requestPath = '/1{path}'.replace('{path}', path);
818
- const headers = {};
819
- const queryParameters = parameters ? parameters : {};
820
- const request = {
821
- method: 'GET',
822
- path: requestPath,
823
- queryParameters,
824
- headers,
825
- };
826
- return transporter.request(request, requestOptions);
827
- },
828
- /**
829
- * The strategy contains information on the events and facets that impact user profiles and personalized search results.
830
- *
831
- * @summary Get the current strategy.
832
- * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
833
- */
834
- getPersonalizationStrategy(requestOptions) {
835
- const requestPath = '/1/strategies/personalization';
836
- const headers = {};
837
- const queryParameters = {};
838
- const request = {
839
- method: 'GET',
840
- path: requestPath,
841
- queryParameters,
842
- headers,
843
- };
844
- return transporter.request(request, requestOptions);
845
- },
846
- /**
847
- * Get the user profile built from Personalization strategy. The profile is structured by facet name used in the strategy. Each facet value is mapped to its score. Each score represents the user affinity for a specific facet value given the userToken past events and the Personalization strategy defined. Scores are bounded to 20. The last processed event timestamp is provided using the ISO 8601 format for debugging purposes.
848
- *
849
- * @summary Get a user profile.
850
- * @param getUserTokenProfile - The getUserTokenProfile object.
851
- * @param getUserTokenProfile.userToken - UserToken representing the user for which to fetch the Personalization profile.
852
- * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
853
- */
854
- getUserTokenProfile({ userToken }, requestOptions) {
855
- if (!userToken) {
856
- throw new Error('Parameter `userToken` is required when calling `getUserTokenProfile`.');
857
- }
858
- const requestPath = '/1/profiles/personalization/{userToken}'.replace('{userToken}', encodeURIComponent(userToken));
859
- const headers = {};
860
- const queryParameters = {};
861
- const request = {
862
- method: 'GET',
863
- path: requestPath,
864
- queryParameters,
865
- headers,
866
- };
867
- return transporter.request(request, requestOptions);
868
- },
869
- /**
870
- * This method allow you to send requests to the Algolia REST API.
871
- *
872
- * @summary Send requests to the Algolia REST API.
873
- * @param post - The post object.
874
- * @param post.path - The path of the API endpoint to target, anything after the /1 needs to be specified.
875
- * @param post.parameters - Query parameters to be applied to the current query.
876
- * @param post.body - The parameters to send with the custom request.
877
- * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
878
- */
879
- post({ path, parameters, body }, requestOptions) {
880
- if (!path) {
881
- throw new Error('Parameter `path` is required when calling `post`.');
882
- }
883
- const requestPath = '/1{path}'.replace('{path}', path);
884
- const headers = {};
885
- const queryParameters = parameters ? parameters : {};
886
- const request = {
887
- method: 'POST',
888
- path: requestPath,
889
- queryParameters,
890
- headers,
891
- data: body ? body : {},
892
- };
893
- return transporter.request(request, requestOptions);
894
- },
895
- /**
896
- * This method allow you to send requests to the Algolia REST API.
897
- *
898
- * @summary Send requests to the Algolia REST API.
899
- * @param put - The put object.
900
- * @param put.path - The path of the API endpoint to target, anything after the /1 needs to be specified.
901
- * @param put.parameters - Query parameters to be applied to the current query.
902
- * @param put.body - The parameters to send with the custom request.
903
- * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
904
- */
905
- put({ path, parameters, body }, requestOptions) {
906
- if (!path) {
907
- throw new Error('Parameter `path` is required when calling `put`.');
908
- }
909
- const requestPath = '/1{path}'.replace('{path}', path);
910
- const headers = {};
911
- const queryParameters = parameters ? parameters : {};
912
- const request = {
913
- method: 'PUT',
914
- path: requestPath,
915
- queryParameters,
916
- headers,
917
- data: body ? body : {},
918
- };
919
- return transporter.request(request, requestOptions);
920
- },
921
- /**
922
- * A strategy defines the events and facets that impact user profiles and personalized search results.
923
- *
924
- * @summary Set a new strategy.
925
- * @param personalizationStrategyParams - The personalizationStrategyParams object.
926
- * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
927
- */
928
- setPersonalizationStrategy(personalizationStrategyParams, requestOptions) {
929
- if (!personalizationStrategyParams) {
930
- throw new Error('Parameter `personalizationStrategyParams` is required when calling `setPersonalizationStrategy`.');
931
- }
932
- if (!personalizationStrategyParams.eventScoring) {
933
- throw new Error('Parameter `personalizationStrategyParams.eventScoring` is required when calling `setPersonalizationStrategy`.');
934
- }
935
- if (!personalizationStrategyParams.facetScoring) {
936
- throw new Error('Parameter `personalizationStrategyParams.facetScoring` is required when calling `setPersonalizationStrategy`.');
937
- }
938
- if (!personalizationStrategyParams.personalizationImpact) {
939
- throw new Error('Parameter `personalizationStrategyParams.personalizationImpact` is required when calling `setPersonalizationStrategy`.');
940
- }
941
- const requestPath = '/1/strategies/personalization';
942
- const headers = {};
943
- const queryParameters = {};
944
- const request = {
945
- method: 'POST',
946
- path: requestPath,
947
- queryParameters,
948
- headers,
949
- data: personalizationStrategyParams,
950
- };
951
- return transporter.request(request, requestOptions);
952
- },
953
- };
688
+ // 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.
689
+ const apiClientVersion = '5.0.0-alpha.100';
690
+ const REGIONS = ['eu', 'us'];
691
+ function getDefaultHosts(region) {
692
+ const url = 'personalization.{region}.algolia.com'.replace('{region}', region);
693
+ return [{ url, accept: 'readWrite', protocol: 'https' }];
694
+ }
695
+ // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
696
+ function createPersonalizationClient({ appId: appIdOption, apiKey: apiKeyOption, authMode, algoliaAgents, region: regionOption, ...options }) {
697
+ const auth = createAuth(appIdOption, apiKeyOption, authMode);
698
+ const transporter = createTransporter({
699
+ hosts: getDefaultHosts(regionOption),
700
+ ...options,
701
+ algoliaAgent: getAlgoliaAgent({
702
+ algoliaAgents,
703
+ client: 'Personalization',
704
+ version: apiClientVersion,
705
+ }),
706
+ baseHeaders: {
707
+ 'content-type': 'text/plain',
708
+ ...auth.headers(),
709
+ ...options.baseHeaders,
710
+ },
711
+ baseQueryParameters: {
712
+ ...auth.queryParameters(),
713
+ ...options.baseQueryParameters,
714
+ },
715
+ });
716
+ return {
717
+ transporter,
718
+ /**
719
+ * The `appId` currently in use.
720
+ */
721
+ appId: appIdOption,
722
+ /**
723
+ * Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.
724
+ */
725
+ clearCache() {
726
+ return Promise.all([
727
+ transporter.requestsCache.clear(),
728
+ transporter.responsesCache.clear(),
729
+ ]).then(() => undefined);
730
+ },
731
+ /**
732
+ * Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
733
+ */
734
+ get _ua() {
735
+ return transporter.algoliaAgent.value;
736
+ },
737
+ /**
738
+ * Adds a `segment` to the `x-algolia-agent` sent with every requests.
739
+ *
740
+ * @param segment - The algolia agent (user-agent) segment to add.
741
+ * @param version - The version of the agent.
742
+ */
743
+ addAlgoliaAgent(segment, version) {
744
+ transporter.algoliaAgent.add({ segment, version });
745
+ },
746
+ /**
747
+ * This method allow you to send requests to the Algolia REST API.
748
+ *
749
+ * @param customDelete - The customDelete object.
750
+ * @param customDelete.path - Path of the endpoint, anything after \"/1\" must be specified.
751
+ * @param customDelete.parameters - Query parameters to apply to the current query.
752
+ * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
753
+ */
754
+ customDelete({ path, parameters }, requestOptions) {
755
+ if (!path) {
756
+ throw new Error('Parameter `path` is required when calling `customDelete`.');
757
+ }
758
+ const requestPath = '/1{path}'.replace('{path}', path);
759
+ const headers = {};
760
+ const queryParameters = parameters ? parameters : {};
761
+ const request = {
762
+ method: 'DELETE',
763
+ path: requestPath,
764
+ queryParameters,
765
+ headers,
766
+ };
767
+ return transporter.request(request, requestOptions);
768
+ },
769
+ /**
770
+ * This method allow you to send requests to the Algolia REST API.
771
+ *
772
+ * @param customGet - The customGet object.
773
+ * @param customGet.path - Path of the endpoint, anything after \"/1\" must be specified.
774
+ * @param customGet.parameters - Query parameters to apply to the current query.
775
+ * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
776
+ */
777
+ customGet({ path, parameters }, requestOptions) {
778
+ if (!path) {
779
+ throw new Error('Parameter `path` is required when calling `customGet`.');
780
+ }
781
+ const requestPath = '/1{path}'.replace('{path}', path);
782
+ const headers = {};
783
+ const queryParameters = parameters ? parameters : {};
784
+ const request = {
785
+ method: 'GET',
786
+ path: requestPath,
787
+ queryParameters,
788
+ headers,
789
+ };
790
+ return transporter.request(request, requestOptions);
791
+ },
792
+ /**
793
+ * This method allow you to send requests to the Algolia REST API.
794
+ *
795
+ * @param customPost - The customPost object.
796
+ * @param customPost.path - Path of the endpoint, anything after \"/1\" must be specified.
797
+ * @param customPost.parameters - Query parameters to apply to the current query.
798
+ * @param customPost.body - Parameters to send with the custom request.
799
+ * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
800
+ */
801
+ customPost({ path, parameters, body }, requestOptions) {
802
+ if (!path) {
803
+ throw new Error('Parameter `path` is required when calling `customPost`.');
804
+ }
805
+ const requestPath = '/1{path}'.replace('{path}', path);
806
+ const headers = {};
807
+ const queryParameters = parameters ? parameters : {};
808
+ const request = {
809
+ method: 'POST',
810
+ path: requestPath,
811
+ queryParameters,
812
+ headers,
813
+ data: body ? body : {},
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 customPut - The customPut object.
821
+ * @param customPut.path - Path of the endpoint, anything after \"/1\" must be specified.
822
+ * @param customPut.parameters - Query parameters to apply to the current query.
823
+ * @param customPut.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
+ customPut({ path, parameters, body }, requestOptions) {
827
+ if (!path) {
828
+ throw new Error('Parameter `path` is required when calling `customPut`.');
829
+ }
830
+ const requestPath = '/1{path}'.replace('{path}', path);
831
+ const headers = {};
832
+ const queryParameters = parameters ? parameters : {};
833
+ const request = {
834
+ method: 'PUT',
835
+ path: requestPath,
836
+ queryParameters,
837
+ headers,
838
+ data: body ? body : {},
839
+ };
840
+ return transporter.request(request, requestOptions);
841
+ },
842
+ /**
843
+ * Delete the user profile and all its associated data. Returns, as part of the response, a date until which the data can safely be considered as deleted for the given user. This means if you send events for the given user before this date, they will be ignored. Any data received after the deletedUntil date will start building a new user profile. It might take a couple hours for the deletion request to be fully processed.
844
+ *
845
+ * Required API Key ACLs:
846
+ * - recommendation.
847
+ *
848
+ * @param deleteUserProfile - The deleteUserProfile object.
849
+ * @param deleteUserProfile.userToken - UserToken representing the user for which to fetch the Personalization profile.
850
+ * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
851
+ */
852
+ deleteUserProfile({ userToken }, requestOptions) {
853
+ if (!userToken) {
854
+ throw new Error('Parameter `userToken` is required when calling `deleteUserProfile`.');
855
+ }
856
+ const requestPath = '/1/profiles/{userToken}'.replace('{userToken}', encodeURIComponent(userToken));
857
+ const headers = {};
858
+ const queryParameters = {};
859
+ const request = {
860
+ method: 'DELETE',
861
+ path: requestPath,
862
+ queryParameters,
863
+ headers,
864
+ };
865
+ return transporter.request(request, requestOptions);
866
+ },
867
+ /**
868
+ * The strategy contains information on the events and facets that impact user profiles and personalized search results.
869
+ *
870
+ * Required API Key ACLs:
871
+ * - recommendation.
872
+ *
873
+ * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
874
+ */
875
+ getPersonalizationStrategy(requestOptions) {
876
+ const requestPath = '/1/strategies/personalization';
877
+ const headers = {};
878
+ const queryParameters = {};
879
+ const request = {
880
+ method: 'GET',
881
+ path: requestPath,
882
+ queryParameters,
883
+ headers,
884
+ };
885
+ return transporter.request(request, requestOptions);
886
+ },
887
+ /**
888
+ * Get the user profile built from Personalization strategy. The profile is structured by facet name used in the strategy. Each facet value is mapped to its score. Each score represents the user affinity for a specific facet value given the userToken past events and the Personalization strategy defined. Scores are bounded to 20. The last processed event timestamp is provided using the ISO 8601 format for debugging purposes.
889
+ *
890
+ * Required API Key ACLs:
891
+ * - recommendation.
892
+ *
893
+ * @param getUserTokenProfile - The getUserTokenProfile object.
894
+ * @param getUserTokenProfile.userToken - UserToken representing the user for which to fetch the Personalization profile.
895
+ * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
896
+ */
897
+ getUserTokenProfile({ userToken }, requestOptions) {
898
+ if (!userToken) {
899
+ throw new Error('Parameter `userToken` is required when calling `getUserTokenProfile`.');
900
+ }
901
+ const requestPath = '/1/profiles/personalization/{userToken}'.replace('{userToken}', encodeURIComponent(userToken));
902
+ const headers = {};
903
+ const queryParameters = {};
904
+ const request = {
905
+ method: 'GET',
906
+ path: requestPath,
907
+ queryParameters,
908
+ headers,
909
+ };
910
+ return transporter.request(request, requestOptions);
911
+ },
912
+ /**
913
+ * A strategy defines the events and facets that impact user profiles and personalized search results.
914
+ *
915
+ * Required API Key ACLs:
916
+ * - recommendation.
917
+ *
918
+ * @param personalizationStrategyParams - The personalizationStrategyParams object.
919
+ * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
920
+ */
921
+ setPersonalizationStrategy(personalizationStrategyParams, requestOptions) {
922
+ if (!personalizationStrategyParams) {
923
+ throw new Error('Parameter `personalizationStrategyParams` is required when calling `setPersonalizationStrategy`.');
924
+ }
925
+ if (!personalizationStrategyParams.eventScoring) {
926
+ throw new Error('Parameter `personalizationStrategyParams.eventScoring` is required when calling `setPersonalizationStrategy`.');
927
+ }
928
+ if (!personalizationStrategyParams.facetScoring) {
929
+ throw new Error('Parameter `personalizationStrategyParams.facetScoring` is required when calling `setPersonalizationStrategy`.');
930
+ }
931
+ if (!personalizationStrategyParams.personalizationImpact) {
932
+ throw new Error('Parameter `personalizationStrategyParams.personalizationImpact` is required when calling `setPersonalizationStrategy`.');
933
+ }
934
+ const requestPath = '/1/strategies/personalization';
935
+ const headers = {};
936
+ const queryParameters = {};
937
+ const request = {
938
+ method: 'POST',
939
+ path: requestPath,
940
+ queryParameters,
941
+ headers,
942
+ data: personalizationStrategyParams,
943
+ };
944
+ return transporter.request(request, requestOptions);
945
+ },
946
+ };
954
947
  }
955
948
 
956
- // This file is generated, manual changes will be lost - read more on https://github.com/algolia/api-clients-automation.
957
- function personalizationClient(appId, apiKey, region, options) {
958
- if (!appId || typeof appId !== 'string') {
959
- throw new Error('`appId` is missing.');
960
- }
961
- if (!apiKey || typeof apiKey !== 'string') {
962
- throw new Error('`apiKey` is missing.');
963
- }
964
- if (!region) {
965
- throw new Error('`region` is missing.');
966
- }
967
- if (region && (typeof region !== 'string' || !REGIONS.includes(region))) {
968
- throw new Error(`\`region\` must be one of the following: ${REGIONS.join(', ')}`);
969
- }
970
- return createPersonalizationClient({
971
- appId,
972
- apiKey,
973
- region,
974
- timeouts: {
975
- connect: DEFAULT_CONNECT_TIMEOUT_BROWSER,
976
- read: DEFAULT_READ_TIMEOUT_BROWSER,
977
- write: DEFAULT_WRITE_TIMEOUT_BROWSER,
978
- },
979
- requester: createXhrRequester(),
980
- algoliaAgents: [{ segment: 'Browser' }],
981
- authMode: 'WithinQueryParameters',
982
- responsesCache: createMemoryCache(),
983
- requestsCache: createMemoryCache({ serializable: false }),
984
- hostsCache: createFallbackableCache({
985
- caches: [
986
- createBrowserLocalStorageCache({ key: `${apiClientVersion}-${appId}` }),
987
- createMemoryCache(),
988
- ],
989
- }),
990
- ...options,
991
- });
949
+ // 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.
950
+ function personalizationClient(appId, apiKey, region, options) {
951
+ if (!appId || typeof appId !== 'string') {
952
+ throw new Error('`appId` is missing.');
953
+ }
954
+ if (!apiKey || typeof apiKey !== 'string') {
955
+ throw new Error('`apiKey` is missing.');
956
+ }
957
+ if (!region ||
958
+ (region && (typeof region !== 'string' || !REGIONS.includes(region)))) {
959
+ throw new Error(`\`region\` is required and must be one of the following: ${REGIONS.join(', ')}`);
960
+ }
961
+ return createPersonalizationClient({
962
+ appId,
963
+ apiKey,
964
+ region,
965
+ timeouts: {
966
+ connect: DEFAULT_CONNECT_TIMEOUT_BROWSER,
967
+ read: DEFAULT_READ_TIMEOUT_BROWSER,
968
+ write: DEFAULT_WRITE_TIMEOUT_BROWSER,
969
+ },
970
+ requester: createXhrRequester(),
971
+ algoliaAgents: [{ segment: 'Browser' }],
972
+ authMode: 'WithinQueryParameters',
973
+ responsesCache: createMemoryCache(),
974
+ requestsCache: createMemoryCache({ serializable: false }),
975
+ hostsCache: createFallbackableCache({
976
+ caches: [
977
+ createBrowserLocalStorageCache({ key: `${apiClientVersion}-${appId}` }),
978
+ createMemoryCache(),
979
+ ],
980
+ }),
981
+ ...options,
982
+ });
992
983
  }
993
984
 
994
985
  export { apiClientVersion, personalizationClient };