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