@algolia/monitoring 1.0.0-alpha.3

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