@algolia/client-common 5.2.3 → 5.2.4-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/common.cjs +714 -0
  2. package/dist/common.cjs.map +1 -0
  3. package/dist/common.d.cts +438 -0
  4. package/dist/common.d.ts +438 -0
  5. package/dist/common.esm.js +653 -0
  6. package/dist/common.esm.js.map +1 -0
  7. package/package.json +17 -6
  8. package/dist/client-common.cjs +0 -783
  9. package/dist/client-common.esm.node.js +0 -747
  10. package/dist/index.d.ts +0 -10
  11. package/dist/index.d.ts.map +0 -1
  12. package/dist/src/cache/createBrowserLocalStorageCache.d.ts +0 -3
  13. package/dist/src/cache/createBrowserLocalStorageCache.d.ts.map +0 -1
  14. package/dist/src/cache/createFallbackableCache.d.ts +0 -3
  15. package/dist/src/cache/createFallbackableCache.d.ts.map +0 -1
  16. package/dist/src/cache/createMemoryCache.d.ts +0 -3
  17. package/dist/src/cache/createMemoryCache.d.ts.map +0 -1
  18. package/dist/src/cache/createNullCache.d.ts +0 -3
  19. package/dist/src/cache/createNullCache.d.ts.map +0 -1
  20. package/dist/src/cache/index.d.ts +0 -5
  21. package/dist/src/cache/index.d.ts.map +0 -1
  22. package/dist/src/constants.d.ts +0 -7
  23. package/dist/src/constants.d.ts.map +0 -1
  24. package/dist/src/createAlgoliaAgent.d.ts +0 -3
  25. package/dist/src/createAlgoliaAgent.d.ts.map +0 -1
  26. package/dist/src/createAuth.d.ts +0 -6
  27. package/dist/src/createAuth.d.ts.map +0 -1
  28. package/dist/src/createEchoRequester.d.ts +0 -7
  29. package/dist/src/createEchoRequester.d.ts.map +0 -1
  30. package/dist/src/createIterablePromise.d.ts +0 -13
  31. package/dist/src/createIterablePromise.d.ts.map +0 -1
  32. package/dist/src/getAlgoliaAgent.d.ts +0 -8
  33. package/dist/src/getAlgoliaAgent.d.ts.map +0 -1
  34. package/dist/src/transporter/createStatefulHost.d.ts +0 -3
  35. package/dist/src/transporter/createStatefulHost.d.ts.map +0 -1
  36. package/dist/src/transporter/createTransporter.d.ts +0 -3
  37. package/dist/src/transporter/createTransporter.d.ts.map +0 -1
  38. package/dist/src/transporter/errors.d.ts +0 -38
  39. package/dist/src/transporter/errors.d.ts.map +0 -1
  40. package/dist/src/transporter/helpers.d.ts +0 -9
  41. package/dist/src/transporter/helpers.d.ts.map +0 -1
  42. package/dist/src/transporter/index.d.ts +0 -7
  43. package/dist/src/transporter/index.d.ts.map +0 -1
  44. package/dist/src/transporter/responses.d.ts +0 -5
  45. package/dist/src/transporter/responses.d.ts.map +0 -1
  46. package/dist/src/transporter/stackTrace.d.ts +0 -4
  47. package/dist/src/transporter/stackTrace.d.ts.map +0 -1
  48. package/dist/src/types/cache.d.ts +0 -61
  49. package/dist/src/types/cache.d.ts.map +0 -1
  50. package/dist/src/types/createClient.d.ts +0 -12
  51. package/dist/src/types/createClient.d.ts.map +0 -1
  52. package/dist/src/types/createIterablePromise.d.ts +0 -36
  53. package/dist/src/types/createIterablePromise.d.ts.map +0 -1
  54. package/dist/src/types/host.d.ts +0 -37
  55. package/dist/src/types/host.d.ts.map +0 -1
  56. package/dist/src/types/index.d.ts +0 -7
  57. package/dist/src/types/index.d.ts.map +0 -1
  58. package/dist/src/types/requester.d.ts +0 -66
  59. package/dist/src/types/requester.d.ts.map +0 -1
  60. package/dist/src/types/transporter.d.ts +0 -128
  61. package/dist/src/types/transporter.d.ts.map +0 -1
@@ -1,783 +0,0 @@
1
- 'use strict';
2
-
3
- function createAuth(appId, apiKey, authMode = 'WithinHeaders') {
4
- const credentials = {
5
- 'x-algolia-api-key': apiKey,
6
- 'x-algolia-application-id': appId
7
- };
8
- return {
9
- headers() {
10
- return authMode === 'WithinHeaders' ? credentials : {};
11
- },
12
- queryParameters() {
13
- return authMode === 'WithinQueryParameters' ? credentials : {};
14
- }
15
- };
16
- }
17
-
18
- function getUrlParams({
19
- host,
20
- search,
21
- pathname
22
- }) {
23
- const urlSearchParams = search.split('?');
24
- if (urlSearchParams.length === 1) {
25
- return {
26
- host,
27
- algoliaAgent: '',
28
- searchParams: undefined,
29
- path: pathname
30
- };
31
- }
32
- const splitSearchParams = urlSearchParams[1].split('&');
33
- let algoliaAgent = '';
34
- const searchParams = {};
35
- if (splitSearchParams.length > 0) {
36
- splitSearchParams.forEach(param => {
37
- const [key, value] = param.split('=');
38
- if (key === 'x-algolia-agent') {
39
- algoliaAgent = value;
40
- return;
41
- }
42
- searchParams[key] = value;
43
- });
44
- }
45
- return {
46
- host,
47
- algoliaAgent,
48
- searchParams: Object.keys(searchParams).length === 0 ? undefined : searchParams,
49
- path: pathname
50
- };
51
- }
52
- function createEchoRequester({
53
- getURL,
54
- status = 200
55
- }) {
56
- function send(request) {
57
- const {
58
- host,
59
- searchParams,
60
- algoliaAgent,
61
- path
62
- } = getUrlParams(getURL(request.url));
63
- const content = {
64
- ...request,
65
- data: request.data ? JSON.parse(request.data) : undefined,
66
- path,
67
- host,
68
- algoliaAgent,
69
- searchParams
70
- };
71
- return Promise.resolve({
72
- content: JSON.stringify(content),
73
- isTimedOut: false,
74
- status
75
- });
76
- }
77
- return {
78
- send
79
- };
80
- }
81
-
82
- /**
83
- * Helper: Returns the promise of a given `func` to iterate on, based on a given `validate` condition.
84
- *
85
- * @param createIterator - The createIterator options.
86
- * @param createIterator.func - The function to run, which returns a promise.
87
- * @param createIterator.validate - The validator function. It receives the resolved return of `func`.
88
- * @param createIterator.aggregator - The function that runs right after the `func` method has been executed, allows you to do anything with the response before `validate`.
89
- * @param createIterator.error - The `validate` condition to throw an error, and its message.
90
- * @param createIterator.timeout - The function to decide how long to wait between iterations.
91
- */
92
- function createIterablePromise({
93
- func,
94
- validate,
95
- aggregator,
96
- error,
97
- timeout = () => 0
98
- }) {
99
- const retry = previousResponse => {
100
- return new Promise((resolve, reject) => {
101
- func(previousResponse).then(response => {
102
- if (aggregator) {
103
- aggregator(response);
104
- }
105
- if (validate(response)) {
106
- return resolve(response);
107
- }
108
- if (error && error.validate(response)) {
109
- return reject(new Error(error.message(response)));
110
- }
111
- return setTimeout(() => {
112
- retry(response).then(resolve).catch(reject);
113
- }, timeout());
114
- }).catch(err => {
115
- reject(err);
116
- });
117
- });
118
- };
119
- return retry();
120
- }
121
-
122
- function createBrowserLocalStorageCache(options) {
123
- let storage;
124
- // We've changed the namespace to avoid conflicts with v4, as this version is a huge breaking change
125
- const namespaceKey = `algolia-client-js-${options.key}`;
126
- function getStorage() {
127
- if (storage === undefined) {
128
- storage = options.localStorage || window.localStorage;
129
- }
130
- return storage;
131
- }
132
- function getNamespace() {
133
- return JSON.parse(getStorage().getItem(namespaceKey) || '{}');
134
- }
135
- function setNamespace(namespace) {
136
- getStorage().setItem(namespaceKey, JSON.stringify(namespace));
137
- }
138
- function removeOutdatedCacheItems() {
139
- const timeToLive = options.timeToLive ? options.timeToLive * 1000 : null;
140
- const namespace = getNamespace();
141
- const filteredNamespaceWithoutOldFormattedCacheItems = Object.fromEntries(Object.entries(namespace).filter(([, cacheItem]) => {
142
- return cacheItem.timestamp !== undefined;
143
- }));
144
- setNamespace(filteredNamespaceWithoutOldFormattedCacheItems);
145
- if (!timeToLive) {
146
- return;
147
- }
148
- const filteredNamespaceWithoutExpiredItems = Object.fromEntries(Object.entries(filteredNamespaceWithoutOldFormattedCacheItems).filter(([, cacheItem]) => {
149
- const currentTimestamp = new Date().getTime();
150
- const isExpired = cacheItem.timestamp + timeToLive < currentTimestamp;
151
- return !isExpired;
152
- }));
153
- setNamespace(filteredNamespaceWithoutExpiredItems);
154
- }
155
- return {
156
- get(key, defaultValue, events = {
157
- miss: () => Promise.resolve()
158
- }) {
159
- return Promise.resolve().then(() => {
160
- removeOutdatedCacheItems();
161
- return getNamespace()[JSON.stringify(key)];
162
- }).then(value => {
163
- return Promise.all([value ? value.value : defaultValue(), value !== undefined]);
164
- }).then(([value, exists]) => {
165
- return Promise.all([value, exists || events.miss(value)]);
166
- }).then(([value]) => value);
167
- },
168
- set(key, value) {
169
- return Promise.resolve().then(() => {
170
- const namespace = getNamespace();
171
- namespace[JSON.stringify(key)] = {
172
- timestamp: new Date().getTime(),
173
- value
174
- };
175
- getStorage().setItem(namespaceKey, JSON.stringify(namespace));
176
- return value;
177
- });
178
- },
179
- delete(key) {
180
- return Promise.resolve().then(() => {
181
- const namespace = getNamespace();
182
- delete namespace[JSON.stringify(key)];
183
- getStorage().setItem(namespaceKey, JSON.stringify(namespace));
184
- });
185
- },
186
- clear() {
187
- return Promise.resolve().then(() => {
188
- getStorage().removeItem(namespaceKey);
189
- });
190
- }
191
- };
192
- }
193
-
194
- function createNullCache() {
195
- return {
196
- get(_key, defaultValue, events = {
197
- miss: () => Promise.resolve()
198
- }) {
199
- const value = defaultValue();
200
- return value.then(result => Promise.all([result, events.miss(result)])).then(([result]) => result);
201
- },
202
- set(_key, value) {
203
- return Promise.resolve(value);
204
- },
205
- delete(_key) {
206
- return Promise.resolve();
207
- },
208
- clear() {
209
- return Promise.resolve();
210
- }
211
- };
212
- }
213
-
214
- function createFallbackableCache(options) {
215
- const caches = [...options.caches];
216
- const current = caches.shift();
217
- if (current === undefined) {
218
- return createNullCache();
219
- }
220
- return {
221
- get(key, defaultValue, events = {
222
- miss: () => Promise.resolve()
223
- }) {
224
- return current.get(key, defaultValue, events).catch(() => {
225
- return createFallbackableCache({
226
- caches
227
- }).get(key, defaultValue, events);
228
- });
229
- },
230
- set(key, value) {
231
- return current.set(key, value).catch(() => {
232
- return createFallbackableCache({
233
- caches
234
- }).set(key, value);
235
- });
236
- },
237
- delete(key) {
238
- return current.delete(key).catch(() => {
239
- return createFallbackableCache({
240
- caches
241
- }).delete(key);
242
- });
243
- },
244
- clear() {
245
- return current.clear().catch(() => {
246
- return createFallbackableCache({
247
- caches
248
- }).clear();
249
- });
250
- }
251
- };
252
- }
253
-
254
- function createMemoryCache(options = {
255
- serializable: true
256
- }) {
257
- let cache = {};
258
- return {
259
- get(key, defaultValue, events = {
260
- miss: () => Promise.resolve()
261
- }) {
262
- const keyAsString = JSON.stringify(key);
263
- if (keyAsString in cache) {
264
- return Promise.resolve(options.serializable ? JSON.parse(cache[keyAsString]) : cache[keyAsString]);
265
- }
266
- const promise = defaultValue();
267
- return promise.then(value => events.miss(value)).then(() => promise);
268
- },
269
- set(key, value) {
270
- cache[JSON.stringify(key)] = options.serializable ? JSON.stringify(value) : value;
271
- return Promise.resolve(value);
272
- },
273
- delete(key) {
274
- delete cache[JSON.stringify(key)];
275
- return Promise.resolve();
276
- },
277
- clear() {
278
- cache = {};
279
- return Promise.resolve();
280
- }
281
- };
282
- }
283
-
284
- // By default, API Clients at Algolia have expiration delay of 5 mins.
285
- // In the JavaScript client, we have 2 mins.
286
- const EXPIRATION_DELAY = 2 * 60 * 1000;
287
- function createStatefulHost(host, status = 'up') {
288
- const lastUpdate = Date.now();
289
- function isUp() {
290
- return status === 'up' || Date.now() - lastUpdate > EXPIRATION_DELAY;
291
- }
292
- function isTimedOut() {
293
- return status === 'timed out' && Date.now() - lastUpdate <= EXPIRATION_DELAY;
294
- }
295
- return {
296
- ...host,
297
- status,
298
- lastUpdate,
299
- isUp,
300
- isTimedOut
301
- };
302
- }
303
-
304
- function _defineProperty(e, r, t) {
305
- return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
306
- value: t,
307
- enumerable: !0,
308
- configurable: !0,
309
- writable: !0
310
- }) : e[r] = t, e;
311
- }
312
- function _toPrimitive(t, r) {
313
- if ("object" != typeof t || !t) return t;
314
- var e = t[Symbol.toPrimitive];
315
- if (void 0 !== e) {
316
- var i = e.call(t, r || "default");
317
- if ("object" != typeof i) return i;
318
- throw new TypeError("@@toPrimitive must return a primitive value.");
319
- }
320
- return ("string" === r ? String : Number)(t);
321
- }
322
- function _toPropertyKey(t) {
323
- var i = _toPrimitive(t, "string");
324
- return "symbol" == typeof i ? i : i + "";
325
- }
326
-
327
- class AlgoliaError extends Error {
328
- constructor(message, name) {
329
- super(message);
330
- _defineProperty(this, "name", 'AlgoliaError');
331
- if (name) {
332
- this.name = name;
333
- }
334
- }
335
- }
336
- class ErrorWithStackTrace extends AlgoliaError {
337
- constructor(message, stackTrace, name) {
338
- super(message, name);
339
- // the array and object should be frozen to reflect the stackTrace at the time of the error
340
- _defineProperty(this, "stackTrace", void 0);
341
- this.stackTrace = stackTrace;
342
- }
343
- }
344
- class RetryError extends ErrorWithStackTrace {
345
- constructor(stackTrace) {
346
- super('Unreachable hosts - your application id may be incorrect. If the error persists, please reach out to the Algolia Support team: https://alg.li/support.', stackTrace, 'RetryError');
347
- }
348
- }
349
- class ApiError extends ErrorWithStackTrace {
350
- constructor(message, status, stackTrace, name = 'ApiError') {
351
- super(message, stackTrace, name);
352
- _defineProperty(this, "status", void 0);
353
- this.status = status;
354
- }
355
- }
356
- class DeserializationError extends AlgoliaError {
357
- constructor(message, response) {
358
- super(message, 'DeserializationError');
359
- _defineProperty(this, "response", void 0);
360
- this.response = response;
361
- }
362
- }
363
- // DetailedApiError is only used by the ingestion client to return more informative error, other clients will use ApiClient.
364
- class DetailedApiError extends ApiError {
365
- constructor(message, status, error, stackTrace) {
366
- super(message, status, stackTrace, 'DetailedApiError');
367
- _defineProperty(this, "error", void 0);
368
- this.error = error;
369
- }
370
- }
371
-
372
- function shuffle(array) {
373
- const shuffledArray = array;
374
- for (let c = array.length - 1; c > 0; c--) {
375
- const b = Math.floor(Math.random() * (c + 1));
376
- const a = array[c];
377
- shuffledArray[c] = array[b];
378
- shuffledArray[b] = a;
379
- }
380
- return shuffledArray;
381
- }
382
- function serializeUrl(host, path, queryParameters) {
383
- const queryParametersAsString = serializeQueryParameters(queryParameters);
384
- let url = `${host.protocol}://${host.url}${host.port ? `:${host.port}` : ''}/${path.charAt(0) === '/' ? path.substring(1) : path}`;
385
- if (queryParametersAsString.length) {
386
- url += `?${queryParametersAsString}`;
387
- }
388
- return url;
389
- }
390
- function serializeQueryParameters(parameters) {
391
- return Object.keys(parameters).filter(key => parameters[key] !== undefined).sort().map(key => `${key}=${encodeURIComponent(Object.prototype.toString.call(parameters[key]) === '[object Array]' ? parameters[key].join(',') : parameters[key]).replaceAll('+', '%20')}`).join('&');
392
- }
393
- function serializeData(request, requestOptions) {
394
- if (request.method === 'GET' || request.data === undefined && requestOptions.data === undefined) {
395
- return undefined;
396
- }
397
- const data = Array.isArray(request.data) ? request.data : {
398
- ...request.data,
399
- ...requestOptions.data
400
- };
401
- return JSON.stringify(data);
402
- }
403
- function serializeHeaders(baseHeaders, requestHeaders, requestOptionsHeaders) {
404
- const headers = {
405
- Accept: 'application/json',
406
- ...baseHeaders,
407
- ...requestHeaders,
408
- ...requestOptionsHeaders
409
- };
410
- const serializedHeaders = {};
411
- Object.keys(headers).forEach(header => {
412
- const value = headers[header];
413
- serializedHeaders[header.toLowerCase()] = value;
414
- });
415
- return serializedHeaders;
416
- }
417
- function deserializeSuccess(response) {
418
- try {
419
- return JSON.parse(response.content);
420
- } catch (e) {
421
- throw new DeserializationError(e.message, response);
422
- }
423
- }
424
- function deserializeFailure({
425
- content,
426
- status
427
- }, stackFrame) {
428
- try {
429
- const parsed = JSON.parse(content);
430
- if ('error' in parsed) {
431
- return new DetailedApiError(parsed.message, status, parsed.error, stackFrame);
432
- }
433
- return new ApiError(parsed.message, status, stackFrame);
434
- } catch {
435
- // ..
436
- }
437
- return new ApiError(content, status, stackFrame);
438
- }
439
-
440
- function isNetworkError({
441
- isTimedOut,
442
- status
443
- }) {
444
- return !isTimedOut && ~~status === 0;
445
- }
446
- function isRetryable({
447
- isTimedOut,
448
- status
449
- }) {
450
- return isTimedOut || isNetworkError({
451
- isTimedOut,
452
- status
453
- }) || ~~(status / 100) !== 2 && ~~(status / 100) !== 4;
454
- }
455
- function isSuccess({
456
- status
457
- }) {
458
- return ~~(status / 100) === 2;
459
- }
460
-
461
- function stackTraceWithoutCredentials(stackTrace) {
462
- return stackTrace.map(stackFrame => stackFrameWithoutCredentials(stackFrame));
463
- }
464
- function stackFrameWithoutCredentials(stackFrame) {
465
- const modifiedHeaders = stackFrame.request.headers['x-algolia-api-key'] ? {
466
- 'x-algolia-api-key': '*****'
467
- } : {};
468
- return {
469
- ...stackFrame,
470
- request: {
471
- ...stackFrame.request,
472
- headers: {
473
- ...stackFrame.request.headers,
474
- ...modifiedHeaders
475
- }
476
- }
477
- };
478
- }
479
-
480
- function createTransporter({
481
- hosts,
482
- hostsCache,
483
- baseHeaders,
484
- baseQueryParameters,
485
- algoliaAgent,
486
- timeouts,
487
- requester,
488
- requestsCache,
489
- responsesCache
490
- }) {
491
- async function createRetryableOptions(compatibleHosts) {
492
- const statefulHosts = await Promise.all(compatibleHosts.map(compatibleHost => {
493
- return hostsCache.get(compatibleHost, () => {
494
- return Promise.resolve(createStatefulHost(compatibleHost));
495
- });
496
- }));
497
- const hostsUp = statefulHosts.filter(host => host.isUp());
498
- const hostsTimedOut = statefulHosts.filter(host => host.isTimedOut());
499
- // Note, we put the hosts that previously timed out on the end of the list.
500
- const hostsAvailable = [...hostsUp, ...hostsTimedOut];
501
- const compatibleHostsAvailable = hostsAvailable.length > 0 ? hostsAvailable : compatibleHosts;
502
- return {
503
- hosts: compatibleHostsAvailable,
504
- getTimeout(timeoutsCount, baseTimeout) {
505
- /**
506
- * Imagine that you have 4 hosts, if timeouts will increase
507
- * on the following way: 1 (timed out) > 4 (timed out) > 5 (200).
508
- *
509
- * Note that, the very next request, we start from the previous timeout.
510
- *
511
- * 5 (timed out) > 6 (timed out) > 7 ...
512
- *
513
- * This strategy may need to be reviewed, but is the strategy on the our
514
- * current v3 version.
515
- */
516
- const timeoutMultiplier = hostsTimedOut.length === 0 && timeoutsCount === 0 ? 1 : hostsTimedOut.length + 3 + timeoutsCount;
517
- return timeoutMultiplier * baseTimeout;
518
- }
519
- };
520
- }
521
- async function retryableRequest(request, requestOptions, isRead = true) {
522
- const stackTrace = [];
523
- /**
524
- * First we prepare the payload that do not depend from hosts.
525
- */
526
- const data = serializeData(request, requestOptions);
527
- const headers = serializeHeaders(baseHeaders, request.headers, requestOptions.headers);
528
- // On `GET`, the data is proxied to query parameters.
529
- const dataQueryParameters = request.method === 'GET' ? {
530
- ...request.data,
531
- ...requestOptions.data
532
- } : {};
533
- const queryParameters = {
534
- ...baseQueryParameters,
535
- ...request.queryParameters,
536
- ...dataQueryParameters
537
- };
538
- if (algoliaAgent.value) {
539
- queryParameters['x-algolia-agent'] = algoliaAgent.value;
540
- }
541
- if (requestOptions && requestOptions.queryParameters) {
542
- for (const key of Object.keys(requestOptions.queryParameters)) {
543
- // We want to keep `undefined` and `null` values,
544
- // but also avoid stringifying `object`s, as they are
545
- // handled in the `serializeUrl` step right after.
546
- if (!requestOptions.queryParameters[key] || Object.prototype.toString.call(requestOptions.queryParameters[key]) === '[object Object]') {
547
- queryParameters[key] = requestOptions.queryParameters[key];
548
- } else {
549
- queryParameters[key] = requestOptions.queryParameters[key].toString();
550
- }
551
- }
552
- }
553
- let timeoutsCount = 0;
554
- const retry = async (retryableHosts, getTimeout) => {
555
- /**
556
- * We iterate on each host, until there is no host left.
557
- */
558
- const host = retryableHosts.pop();
559
- if (host === undefined) {
560
- throw new RetryError(stackTraceWithoutCredentials(stackTrace));
561
- }
562
- const timeout = {
563
- ...timeouts,
564
- ...requestOptions.timeouts
565
- };
566
- const payload = {
567
- data,
568
- headers,
569
- method: request.method,
570
- url: serializeUrl(host, request.path, queryParameters),
571
- connectTimeout: getTimeout(timeoutsCount, timeout.connect),
572
- responseTimeout: getTimeout(timeoutsCount, isRead ? timeout.read : timeout.write)
573
- };
574
- /**
575
- * The stackFrame is pushed to the stackTrace so we
576
- * can have information about onRetry and onFailure
577
- * decisions.
578
- */
579
- const pushToStackTrace = response => {
580
- const stackFrame = {
581
- request: payload,
582
- response,
583
- host,
584
- triesLeft: retryableHosts.length
585
- };
586
- stackTrace.push(stackFrame);
587
- return stackFrame;
588
- };
589
- const response = await requester.send(payload);
590
- if (isRetryable(response)) {
591
- const stackFrame = pushToStackTrace(response);
592
- // If response is a timeout, we increase the number of timeouts so we can increase the timeout later.
593
- if (response.isTimedOut) {
594
- timeoutsCount++;
595
- }
596
- /**
597
- * Failures are individually sent to the logger, allowing
598
- * the end user to debug / store stack frames even
599
- * when a retry error does not happen.
600
- */
601
- // eslint-disable-next-line no-console -- this will be fixed by exposing a `logger` to the transporter
602
- console.log('Retryable failure', stackFrameWithoutCredentials(stackFrame));
603
- /**
604
- * We also store the state of the host in failure cases. If the host, is
605
- * down it will remain down for the next 2 minutes. In a timeout situation,
606
- * this host will be added end of the list of hosts on the next request.
607
- */
608
- await hostsCache.set(host, createStatefulHost(host, response.isTimedOut ? 'timed out' : 'down'));
609
- return retry(retryableHosts, getTimeout);
610
- }
611
- if (isSuccess(response)) {
612
- return deserializeSuccess(response);
613
- }
614
- pushToStackTrace(response);
615
- throw deserializeFailure(response, stackTrace);
616
- };
617
- /**
618
- * Finally, for each retryable host perform request until we got a non
619
- * retryable response. Some notes here:
620
- *
621
- * 1. The reverse here is applied so we can apply a `pop` later on => more performant.
622
- * 2. We also get from the retryable options a timeout multiplier that is tailored
623
- * for the current context.
624
- */
625
- const compatibleHosts = hosts.filter(host => host.accept === 'readWrite' || (isRead ? host.accept === 'read' : host.accept === 'write'));
626
- const options = await createRetryableOptions(compatibleHosts);
627
- return retry([...options.hosts].reverse(), options.getTimeout);
628
- }
629
- function createRequest(request, requestOptions = {}) {
630
- /**
631
- * A read request is either a `GET` request, or a request that we make
632
- * via the `read` transporter (e.g. `search`).
633
- */
634
- const isRead = request.useReadTransporter || request.method === 'GET';
635
- if (!isRead) {
636
- /**
637
- * On write requests, no cache mechanisms are applied, and we
638
- * proxy the request immediately to the requester.
639
- */
640
- return retryableRequest(request, requestOptions, isRead);
641
- }
642
- const createRetryableRequest = () => {
643
- /**
644
- * Then, we prepare a function factory that contains the construction of
645
- * the retryable request. At this point, we may *not* perform the actual
646
- * request. But we want to have the function factory ready.
647
- */
648
- return retryableRequest(request, requestOptions);
649
- };
650
- /**
651
- * Once we have the function factory ready, we need to determine of the
652
- * request is "cacheable" - should be cached. Note that, once again,
653
- * the user can force this option.
654
- */
655
- const cacheable = requestOptions.cacheable || request.cacheable;
656
- /**
657
- * If is not "cacheable", we immediately trigger the retryable request, no
658
- * need to check cache implementations.
659
- */
660
- if (cacheable !== true) {
661
- return createRetryableRequest();
662
- }
663
- /**
664
- * If the request is "cacheable", we need to first compute the key to ask
665
- * the cache implementations if this request is on progress or if the
666
- * response already exists on the cache.
667
- */
668
- const key = {
669
- request,
670
- requestOptions,
671
- transporter: {
672
- queryParameters: baseQueryParameters,
673
- headers: baseHeaders
674
- }
675
- };
676
- /**
677
- * With the computed key, we first ask the responses cache
678
- * implementation if this request was been resolved before.
679
- */
680
- return responsesCache.get(key, () => {
681
- /**
682
- * If the request has never resolved before, we actually ask if there
683
- * is a current request with the same key on progress.
684
- */
685
- return requestsCache.get(key, () =>
686
- /**
687
- * Finally, if there is no request in progress with the same key,
688
- * this `createRetryableRequest()` will actually trigger the
689
- * retryable request.
690
- */
691
- requestsCache.set(key, createRetryableRequest()).then(response => Promise.all([requestsCache.delete(key), response]), err => Promise.all([requestsCache.delete(key), Promise.reject(err)])).then(([_, response]) => response));
692
- }, {
693
- /**
694
- * Of course, once we get this response back from the server, we
695
- * tell response cache to actually store the received response
696
- * to be used later.
697
- */
698
- miss: response => responsesCache.set(key, response)
699
- });
700
- }
701
- return {
702
- hostsCache,
703
- requester,
704
- timeouts,
705
- algoliaAgent,
706
- baseHeaders,
707
- baseQueryParameters,
708
- hosts,
709
- request: createRequest,
710
- requestsCache,
711
- responsesCache
712
- };
713
- }
714
-
715
- function createAlgoliaAgent(version) {
716
- const algoliaAgent = {
717
- value: `Algolia for JavaScript (${version})`,
718
- add(options) {
719
- const addedAlgoliaAgent = `; ${options.segment}${options.version !== undefined ? ` (${options.version})` : ''}`;
720
- if (algoliaAgent.value.indexOf(addedAlgoliaAgent) === -1) {
721
- algoliaAgent.value = `${algoliaAgent.value}${addedAlgoliaAgent}`;
722
- }
723
- return algoliaAgent;
724
- }
725
- };
726
- return algoliaAgent;
727
- }
728
-
729
- function getAlgoliaAgent({
730
- algoliaAgents,
731
- client,
732
- version
733
- }) {
734
- const defaultAlgoliaAgent = createAlgoliaAgent(version).add({
735
- segment: client,
736
- version
737
- });
738
- algoliaAgents.forEach(algoliaAgent => defaultAlgoliaAgent.add(algoliaAgent));
739
- return defaultAlgoliaAgent;
740
- }
741
-
742
- const DEFAULT_CONNECT_TIMEOUT_BROWSER = 1000;
743
- const DEFAULT_READ_TIMEOUT_BROWSER = 2000;
744
- const DEFAULT_WRITE_TIMEOUT_BROWSER = 30000;
745
- const DEFAULT_CONNECT_TIMEOUT_NODE = 2000;
746
- const DEFAULT_READ_TIMEOUT_NODE = 5000;
747
- const DEFAULT_WRITE_TIMEOUT_NODE = 30000;
748
-
749
- exports.AlgoliaError = AlgoliaError;
750
- exports.ApiError = ApiError;
751
- exports.DEFAULT_CONNECT_TIMEOUT_BROWSER = DEFAULT_CONNECT_TIMEOUT_BROWSER;
752
- exports.DEFAULT_CONNECT_TIMEOUT_NODE = DEFAULT_CONNECT_TIMEOUT_NODE;
753
- exports.DEFAULT_READ_TIMEOUT_BROWSER = DEFAULT_READ_TIMEOUT_BROWSER;
754
- exports.DEFAULT_READ_TIMEOUT_NODE = DEFAULT_READ_TIMEOUT_NODE;
755
- exports.DEFAULT_WRITE_TIMEOUT_BROWSER = DEFAULT_WRITE_TIMEOUT_BROWSER;
756
- exports.DEFAULT_WRITE_TIMEOUT_NODE = DEFAULT_WRITE_TIMEOUT_NODE;
757
- exports.DeserializationError = DeserializationError;
758
- exports.DetailedApiError = DetailedApiError;
759
- exports.ErrorWithStackTrace = ErrorWithStackTrace;
760
- exports.RetryError = RetryError;
761
- exports.createAlgoliaAgent = createAlgoliaAgent;
762
- exports.createAuth = createAuth;
763
- exports.createBrowserLocalStorageCache = createBrowserLocalStorageCache;
764
- exports.createEchoRequester = createEchoRequester;
765
- exports.createFallbackableCache = createFallbackableCache;
766
- exports.createIterablePromise = createIterablePromise;
767
- exports.createMemoryCache = createMemoryCache;
768
- exports.createNullCache = createNullCache;
769
- exports.createStatefulHost = createStatefulHost;
770
- exports.createTransporter = createTransporter;
771
- exports.deserializeFailure = deserializeFailure;
772
- exports.deserializeSuccess = deserializeSuccess;
773
- exports.getAlgoliaAgent = getAlgoliaAgent;
774
- exports.isNetworkError = isNetworkError;
775
- exports.isRetryable = isRetryable;
776
- exports.isSuccess = isSuccess;
777
- exports.serializeData = serializeData;
778
- exports.serializeHeaders = serializeHeaders;
779
- exports.serializeQueryParameters = serializeQueryParameters;
780
- exports.serializeUrl = serializeUrl;
781
- exports.shuffle = shuffle;
782
- exports.stackFrameWithoutCredentials = stackFrameWithoutCredentials;
783
- exports.stackTraceWithoutCredentials = stackTraceWithoutCredentials;