@algolia/client-personalization 4.14.1 → 5.0.0-alpha.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 (42) hide show
  1. package/dist/builds/browser.d.ts +6 -0
  2. package/dist/builds/browser.d.ts.map +1 -0
  3. package/dist/builds/node.d.ts +6 -0
  4. package/dist/builds/node.d.ts.map +1 -0
  5. package/dist/client-personalization.cjs.js +270 -34
  6. package/dist/client-personalization.esm.browser.js +994 -0
  7. package/dist/client-personalization.esm.node.js +280 -0
  8. package/dist/client-personalization.umd.js +2 -0
  9. package/dist/model/clientMethodProps.d.ts +79 -0
  10. package/dist/model/clientMethodProps.d.ts.map +1 -0
  11. package/dist/model/deleteUserProfileResponse.d.ts +11 -0
  12. package/dist/model/deleteUserProfileResponse.d.ts.map +1 -0
  13. package/dist/model/errorBase.d.ts +7 -0
  14. package/dist/model/errorBase.d.ts.map +1 -0
  15. package/dist/model/eventScoring.d.ts +15 -0
  16. package/dist/model/eventScoring.d.ts.map +1 -0
  17. package/dist/model/facetScoring.d.ts +11 -0
  18. package/dist/model/facetScoring.d.ts.map +1 -0
  19. package/dist/model/getUserTokenResponse.d.ts +15 -0
  20. package/dist/model/getUserTokenResponse.d.ts.map +1 -0
  21. package/dist/model/index.d.ts +9 -0
  22. package/dist/model/index.d.ts.map +1 -0
  23. package/dist/model/personalizationStrategyParams.d.ts +17 -0
  24. package/dist/model/personalizationStrategyParams.d.ts.map +1 -0
  25. package/dist/model/setPersonalizationStrategyResponse.d.ts +7 -0
  26. package/dist/model/setPersonalizationStrategyResponse.d.ts.map +1 -0
  27. package/dist/src/personalizationClient.d.ts +105 -0
  28. package/dist/src/personalizationClient.d.ts.map +1 -0
  29. package/index.d.ts +2 -0
  30. package/index.js +1 -1
  31. package/model/clientMethodProps.ts +85 -0
  32. package/model/deleteUserProfileResponse.ts +12 -0
  33. package/model/errorBase.ts +8 -0
  34. package/model/eventScoring.ts +16 -0
  35. package/model/facetScoring.ts +12 -0
  36. package/model/getUserTokenResponse.ts +16 -0
  37. package/model/index.ts +10 -0
  38. package/model/personalizationStrategyParams.ts +19 -0
  39. package/model/setPersonalizationStrategyResponse.ts +8 -0
  40. package/package.json +25 -13
  41. package/dist/client-personalization.d.ts +0 -93
  42. package/dist/client-personalization.esm.js +0 -43
@@ -0,0 +1,994 @@
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
+
11
+ queryParameters() {
12
+ return authMode === 'WithinQueryParameters' ? credentials : {};
13
+ }
14
+
15
+ };
16
+ }
17
+
18
+ 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
+
21
+ const namespaceKey = `algolia-client-js-${options.key}`;
22
+
23
+ function getStorage() {
24
+ if (storage === undefined) {
25
+ storage = options.localStorage || window.localStorage;
26
+ }
27
+
28
+ return storage;
29
+ }
30
+
31
+ function getNamespace() {
32
+ return JSON.parse(getStorage().getItem(namespaceKey) || '{}');
33
+ }
34
+
35
+ return {
36
+ get(key, defaultValue, events = {
37
+ miss: () => Promise.resolve()
38
+ }) {
39
+ return Promise.resolve().then(() => {
40
+ const keyAsString = JSON.stringify(key);
41
+ const value = getNamespace()[keyAsString];
42
+ return Promise.all([value || defaultValue(), value !== undefined]);
43
+ }).then(([value, exists]) => {
44
+ return Promise.all([value, exists || events.miss(value)]);
45
+ }).then(([value]) => value);
46
+ },
47
+
48
+ set(key, value) {
49
+ return Promise.resolve().then(() => {
50
+ const namespace = getNamespace();
51
+ namespace[JSON.stringify(key)] = value;
52
+ getStorage().setItem(namespaceKey, JSON.stringify(namespace));
53
+ return value;
54
+ });
55
+ },
56
+
57
+ delete(key) {
58
+ return Promise.resolve().then(() => {
59
+ const namespace = getNamespace();
60
+ delete namespace[JSON.stringify(key)];
61
+ getStorage().setItem(namespaceKey, JSON.stringify(namespace));
62
+ });
63
+ },
64
+
65
+ clear() {
66
+ return Promise.resolve().then(() => {
67
+ getStorage().removeItem(namespaceKey);
68
+ });
69
+ }
70
+
71
+ };
72
+ }
73
+
74
+ function createNullCache() {
75
+ return {
76
+ get(_key, defaultValue, events = {
77
+ miss: () => Promise.resolve()
78
+ }) {
79
+ const value = defaultValue();
80
+ return value.then(result => Promise.all([result, events.miss(result)])).then(([result]) => result);
81
+ },
82
+
83
+ set(_key, value) {
84
+ return Promise.resolve(value);
85
+ },
86
+
87
+ delete(_key) {
88
+ return Promise.resolve();
89
+ },
90
+
91
+ clear() {
92
+ return Promise.resolve();
93
+ }
94
+
95
+ };
96
+ }
97
+
98
+ function createFallbackableCache(options) {
99
+ const caches = [...options.caches];
100
+ const current = caches.shift();
101
+
102
+ if (current === undefined) {
103
+ return createNullCache();
104
+ }
105
+
106
+ return {
107
+ get(key, defaultValue, events = {
108
+ miss: () => Promise.resolve()
109
+ }) {
110
+ return current.get(key, defaultValue, events).catch(() => {
111
+ return createFallbackableCache({
112
+ caches
113
+ }).get(key, defaultValue, events);
114
+ });
115
+ },
116
+
117
+ set(key, value) {
118
+ return current.set(key, value).catch(() => {
119
+ return createFallbackableCache({
120
+ caches
121
+ }).set(key, value);
122
+ });
123
+ },
124
+
125
+ delete(key) {
126
+ return current.delete(key).catch(() => {
127
+ return createFallbackableCache({
128
+ caches
129
+ }).delete(key);
130
+ });
131
+ },
132
+
133
+ clear() {
134
+ return current.clear().catch(() => {
135
+ return createFallbackableCache({
136
+ caches
137
+ }).clear();
138
+ });
139
+ }
140
+
141
+ };
142
+ }
143
+
144
+ function createMemoryCache(options = {
145
+ serializable: true
146
+ }) {
147
+ let cache = {};
148
+ return {
149
+ get(key, defaultValue, events = {
150
+ miss: () => Promise.resolve()
151
+ }) {
152
+ const keyAsString = JSON.stringify(key);
153
+
154
+ if (keyAsString in cache) {
155
+ return Promise.resolve(options.serializable ? JSON.parse(cache[keyAsString]) : cache[keyAsString]);
156
+ }
157
+
158
+ const promise = defaultValue();
159
+ return promise.then(value => events.miss(value)).then(() => promise);
160
+ },
161
+
162
+ set(key, value) {
163
+ cache[JSON.stringify(key)] = options.serializable ? JSON.stringify(value) : value;
164
+ return Promise.resolve(value);
165
+ },
166
+
167
+ delete(key) {
168
+ delete cache[JSON.stringify(key)];
169
+ return Promise.resolve();
170
+ },
171
+
172
+ clear() {
173
+ cache = {};
174
+ return Promise.resolve();
175
+ }
176
+
177
+ };
178
+ }
179
+
180
+ // By default, API Clients at Algolia have expiration delay of 5 mins.
181
+ // In the JavaScript client, we have 2 mins.
182
+ const EXPIRATION_DELAY = 2 * 60 * 1000;
183
+ function createStatefulHost(host, status = 'up') {
184
+ const lastUpdate = Date.now();
185
+
186
+ function isUp() {
187
+ return status === 'up' || Date.now() - lastUpdate > EXPIRATION_DELAY;
188
+ }
189
+
190
+ function isTimedOut() {
191
+ return status === 'timed out' && Date.now() - lastUpdate <= EXPIRATION_DELAY;
192
+ }
193
+
194
+ return { ...host,
195
+ status,
196
+ lastUpdate,
197
+ isUp,
198
+ isTimedOut
199
+ };
200
+ }
201
+
202
+ function _defineProperty(obj, key, value) {
203
+ if (key in obj) {
204
+ Object.defineProperty(obj, key, {
205
+ value: value,
206
+ enumerable: true,
207
+ configurable: true,
208
+ writable: true
209
+ });
210
+ } else {
211
+ obj[key] = value;
212
+ }
213
+
214
+ return obj;
215
+ }
216
+
217
+ class AlgoliaError extends Error {
218
+ constructor(message, name) {
219
+ super(message);
220
+
221
+ _defineProperty(this, "name", 'AlgoliaError');
222
+
223
+ if (name) {
224
+ this.name = name;
225
+ }
226
+ }
227
+
228
+ }
229
+ class ErrorWithStackTrace extends AlgoliaError {
230
+ 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
+
233
+ _defineProperty(this, "stackTrace", void 0);
234
+
235
+ this.stackTrace = stackTrace;
236
+ }
237
+
238
+ }
239
+ class RetryError extends ErrorWithStackTrace {
240
+ constructor(stackTrace) {
241
+ super('Unreachable hosts - your application id may be incorrect. If the error persists, contact support@algolia.com.', stackTrace, 'RetryError');
242
+ }
243
+
244
+ }
245
+ class ApiError extends ErrorWithStackTrace {
246
+ constructor(message, status, stackTrace) {
247
+ super(message, stackTrace, 'ApiError');
248
+
249
+ _defineProperty(this, "status", void 0);
250
+
251
+ this.status = status;
252
+ }
253
+
254
+ }
255
+ class DeserializationError extends AlgoliaError {
256
+ constructor(message, response) {
257
+ super(message, 'DeserializationError');
258
+
259
+ _defineProperty(this, "response", void 0);
260
+
261
+ this.response = response;
262
+ }
263
+
264
+ }
265
+ function serializeUrl(host, path, queryParameters) {
266
+ const queryParametersAsString = serializeQueryParameters(queryParameters);
267
+ let url = `${host.protocol}://${host.url}/${path.charAt(0) === '/' ? path.substr(1) : path}`;
268
+
269
+ if (queryParametersAsString.length) {
270
+ url += `?${queryParametersAsString}`;
271
+ }
272
+
273
+ return url;
274
+ }
275
+ function serializeQueryParameters(parameters) {
276
+ 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('&');
279
+ }
280
+ function serializeData(request, requestOptions) {
281
+ if (request.method === 'GET' || request.data === undefined && requestOptions.data === undefined) {
282
+ return undefined;
283
+ }
284
+
285
+ const data = Array.isArray(request.data) ? request.data : { ...request.data,
286
+ ...requestOptions.data
287
+ };
288
+ return JSON.stringify(data);
289
+ }
290
+ function serializeHeaders(baseHeaders, requestHeaders, requestOptionsHeaders) {
291
+ const headers = {
292
+ Accept: 'application/json',
293
+ ...baseHeaders,
294
+ ...requestHeaders,
295
+ ...requestOptionsHeaders
296
+ };
297
+ const serializedHeaders = {};
298
+ Object.keys(headers).forEach(header => {
299
+ const value = headers[header];
300
+ serializedHeaders[header.toLowerCase()] = value;
301
+ });
302
+ return serializedHeaders;
303
+ }
304
+ function deserializeSuccess(response) {
305
+ try {
306
+ return JSON.parse(response.content);
307
+ } catch (e) {
308
+ throw new DeserializationError(e.message, response);
309
+ }
310
+ }
311
+ function deserializeFailure({
312
+ content,
313
+ status
314
+ }, stackFrame) {
315
+ let message = content;
316
+
317
+ try {
318
+ message = JSON.parse(content).message;
319
+ } catch (e) {// ..
320
+ }
321
+
322
+ return new ApiError(message, status, stackFrame);
323
+ }
324
+
325
+ function isNetworkError({
326
+ isTimedOut,
327
+ status
328
+ }) {
329
+ return !isTimedOut && ~~status === 0;
330
+ }
331
+ function isRetryable({
332
+ isTimedOut,
333
+ status
334
+ }) {
335
+ return isTimedOut || isNetworkError({
336
+ isTimedOut,
337
+ status
338
+ }) || ~~(status / 100) !== 2 && ~~(status / 100) !== 4;
339
+ }
340
+ function isSuccess({
341
+ status
342
+ }) {
343
+ return ~~(status / 100) === 2;
344
+ }
345
+
346
+ function stackTraceWithoutCredentials(stackTrace) {
347
+ return stackTrace.map(stackFrame => stackFrameWithoutCredentials(stackFrame));
348
+ }
349
+ function stackFrameWithoutCredentials(stackFrame) {
350
+ const modifiedHeaders = stackFrame.request.headers['x-algolia-api-key'] ? {
351
+ 'x-algolia-api-key': '*****'
352
+ } : {};
353
+ return { ...stackFrame,
354
+ request: { ...stackFrame.request,
355
+ headers: { ...stackFrame.request.headers,
356
+ ...modifiedHeaders
357
+ }
358
+ }
359
+ };
360
+ }
361
+
362
+ function createTransporter({
363
+ hosts,
364
+ hostsCache,
365
+ baseHeaders,
366
+ baseQueryParameters,
367
+ algoliaAgent,
368
+ timeouts,
369
+ requester,
370
+ requestsCache,
371
+ responsesCache
372
+ }) {
373
+ async function createRetryableOptions(compatibleHosts) {
374
+ const statefulHosts = await Promise.all(compatibleHosts.map(compatibleHost => {
375
+ return hostsCache.get(compatibleHost, () => {
376
+ return Promise.resolve(createStatefulHost(compatibleHost));
377
+ });
378
+ }));
379
+ 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
+
382
+ const hostsAvailable = [...hostsUp, ...hostsTimedOut];
383
+ const compatibleHostsAvailable = hostsAvailable.length > 0 ? hostsAvailable : compatibleHosts;
384
+ return {
385
+ hosts: compatibleHostsAvailable,
386
+
387
+ 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.
398
+ */
399
+ const timeoutMultiplier = hostsTimedOut.length === 0 && timeoutsCount === 0 ? 1 : hostsTimedOut.length + 3 + timeoutsCount;
400
+ return timeoutMultiplier * baseTimeout;
401
+ }
402
+
403
+ };
404
+ }
405
+
406
+ async function retryableRequest(request, requestOptions, isRead = true) {
407
+ const stackTrace = [];
408
+ /**
409
+ * First we prepare the payload that do not depend from hosts.
410
+ */
411
+
412
+ 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,
416
+ ...requestOptions.data
417
+ } : {};
418
+ const queryParameters = {
419
+ 'x-algolia-agent': algoliaAgent.value,
420
+ ...baseQueryParameters,
421
+ ...request.queryParameters,
422
+ ...dataQueryParameters
423
+ };
424
+
425
+ if (requestOptions && requestOptions.queryParameters) {
426
+ for (const key of Object.keys(requestOptions.queryParameters)) {
427
+ // We want to keep `undefined` and `null` values,
428
+ // but also avoid stringifying `object`s, as they are
429
+ // handled in the `serializeUrl` step right after.
430
+ if (!requestOptions.queryParameters[key] || Object.prototype.toString.call(requestOptions.queryParameters[key]) === '[object Object]') {
431
+ queryParameters[key] = requestOptions.queryParameters[key];
432
+ } else {
433
+ queryParameters[key] = requestOptions.queryParameters[key].toString();
434
+ }
435
+ }
436
+ }
437
+
438
+ let timeoutsCount = 0;
439
+
440
+ const retry = async (retryableHosts, getTimeout) => {
441
+ /**
442
+ * We iterate on each host, until there is no host left.
443
+ */
444
+ const host = retryableHosts.pop();
445
+
446
+ if (host === undefined) {
447
+ throw new RetryError(stackTraceWithoutCredentials(stackTrace));
448
+ }
449
+
450
+ let responseTimeout = requestOptions.timeout;
451
+
452
+ if (responseTimeout === undefined) {
453
+ responseTimeout = isRead ? timeouts.read : timeouts.write;
454
+ }
455
+
456
+ const payload = {
457
+ data,
458
+ headers,
459
+ method: request.method,
460
+ url: serializeUrl(host, request.path, queryParameters),
461
+ connectTimeout: getTimeout(timeoutsCount, timeouts.connect),
462
+ responseTimeout: getTimeout(timeoutsCount, responseTimeout)
463
+ };
464
+ /**
465
+ * The stackFrame is pushed to the stackTrace so we
466
+ * can have information about onRetry and onFailure
467
+ * decisions.
468
+ */
469
+
470
+ const pushToStackTrace = response => {
471
+ const stackFrame = {
472
+ request: payload,
473
+ response,
474
+ host,
475
+ triesLeft: retryableHosts.length
476
+ };
477
+ stackTrace.push(stackFrame);
478
+ return stackFrame;
479
+ };
480
+
481
+ const response = await requester.send(payload);
482
+
483
+ 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
+
486
+ if (response.isTimedOut) {
487
+ timeoutsCount++;
488
+ }
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.
493
+ */
494
+ // eslint-disable-next-line no-console -- this will be fixed by exposing a `logger` to the transporter
495
+
496
+
497
+ 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.
502
+ */
503
+
504
+ await hostsCache.set(host, createStatefulHost(host, response.isTimedOut ? 'timed out' : 'down'));
505
+ return retry(retryableHosts, getTimeout);
506
+ }
507
+
508
+ if (isSuccess(response)) {
509
+ return deserializeSuccess(response);
510
+ }
511
+
512
+ pushToStackTrace(response);
513
+ throw deserializeFailure(response, stackTrace);
514
+ };
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.
522
+ */
523
+
524
+
525
+ const compatibleHosts = hosts.filter(host => host.accept === 'readWrite' || (isRead ? host.accept === 'read' : host.accept === 'write'));
526
+ const options = await createRetryableOptions(compatibleHosts);
527
+ return retry([...options.hosts].reverse(), options.getTimeout);
528
+ }
529
+
530
+ 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`).
534
+ */
535
+ const isRead = request.useReadTransporter || request.method === 'GET';
536
+
537
+ if (!isRead) {
538
+ /**
539
+ * On write requests, no cache mechanisms are applied, and we
540
+ * proxy the request immediately to the requester.
541
+ */
542
+ return retryableRequest(request, requestOptions, isRead);
543
+ }
544
+
545
+ 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.
550
+ */
551
+ return retryableRequest(request, requestOptions);
552
+ };
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.
557
+ */
558
+
559
+
560
+ 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.
564
+ */
565
+
566
+ if (cacheable !== true) {
567
+ return createRetryableRequest();
568
+ }
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.
573
+ */
574
+
575
+
576
+ const key = {
577
+ request,
578
+ requestOptions,
579
+ transporter: {
580
+ queryParameters: baseQueryParameters,
581
+ headers: baseHeaders
582
+ }
583
+ };
584
+ /**
585
+ * With the computed key, we first ask the responses cache
586
+ * implementation if this request was been resolved before.
587
+ */
588
+
589
+ 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.
593
+ */
594
+ 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.
599
+ */
600
+ 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
+ }, {
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.
606
+ */
607
+ miss: response => responsesCache.set(key, response)
608
+ });
609
+ }
610
+
611
+ return {
612
+ hostsCache,
613
+ requester,
614
+ timeouts,
615
+ algoliaAgent,
616
+ baseHeaders,
617
+ baseQueryParameters,
618
+ hosts,
619
+ request: createRequest,
620
+ requestsCache,
621
+ responsesCache
622
+ };
623
+ }
624
+
625
+ function createAlgoliaAgent(version) {
626
+ const algoliaAgent = {
627
+ value: `Algolia for JavaScript (${version})`,
628
+
629
+ add(options) {
630
+ const addedAlgoliaAgent = `; ${options.segment}${options.version !== undefined ? ` (${options.version})` : ''}`;
631
+
632
+ if (algoliaAgent.value.indexOf(addedAlgoliaAgent) === -1) {
633
+ algoliaAgent.value = `${algoliaAgent.value}${addedAlgoliaAgent}`;
634
+ }
635
+
636
+ return algoliaAgent;
637
+ }
638
+
639
+ };
640
+ return algoliaAgent;
641
+ }
642
+
643
+ function getAlgoliaAgent({
644
+ algoliaAgents,
645
+ client,
646
+ version
647
+ }) {
648
+ const defaultAlgoliaAgent = createAlgoliaAgent(version).add({
649
+ segment: client,
650
+ version
651
+ });
652
+ algoliaAgents.forEach(algoliaAgent => defaultAlgoliaAgent.add(algoliaAgent));
653
+ return defaultAlgoliaAgent;
654
+ }
655
+
656
+ const DEFAULT_CONNECT_TIMEOUT_BROWSER = 1000;
657
+ const DEFAULT_READ_TIMEOUT_BROWSER = 2000;
658
+ const DEFAULT_WRITE_TIMEOUT_BROWSER = 30000;
659
+
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 };
710
+ }
711
+
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.2';
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
+ };
954
+ }
955
+
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
+ });
992
+ }
993
+
994
+ export { apiClientVersion, personalizationClient };