@algolia/client-common 5.56.0 → 5.57.0

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.
package/dist/common.d.cts CHANGED
@@ -261,6 +261,10 @@ type Logger = {
261
261
  * Logs info messages.
262
262
  */
263
263
  info: (message: string, args?: any | undefined) => Promise<void>;
264
+ /**
265
+ * Logs warning messages. When not implemented, warnings fall back to `console.warn` so they stay visible with the default no-op logger.
266
+ */
267
+ warn?: (message: string, args?: any | undefined) => Promise<void>;
264
268
  /**
265
269
  * Logs error messages.
266
270
  */
@@ -401,6 +405,12 @@ type TransporterOptions = {
401
405
  */
402
406
  compress?: (data: string) => Promise<Uint8Array>;
403
407
  compression?: 'gzip';
408
+ /**
409
+ * Where the generated Request-ID is sent: as the `Request-ID` header, or as the
410
+ * `x-algolia-request-id` query parameter. When undefined, no Request-ID is sent.
411
+ * A caller-supplied Request-ID is never overwritten.
412
+ */
413
+ requestIdChannel?: 'headers' | 'queryParameters' | undefined;
404
414
  };
405
415
  type Transporter = TransporterOptions & {
406
416
  /**
@@ -513,11 +523,16 @@ declare function getAlgoliaAgent({ algoliaAgents, client, version }: GetAlgoliaA
513
523
 
514
524
  declare function createNullLogger(): Logger;
515
525
 
526
+ /**
527
+ * Prefers the logger's optional `warn` method and falls back to `console.warn`, so warnings stay visible with the default no-op logger.
528
+ */
529
+ declare function logWarning(logger: Logger, message: string): void;
530
+
516
531
  declare const COMPRESSION_THRESHOLD = 750;
517
532
 
518
533
  declare function createStatefulHost(host: Host, status?: StatefulHost['status']): StatefulHost;
519
534
 
520
- declare function createTransporter({ hosts, hostsCache, baseHeaders, logger, baseQueryParameters, algoliaAgent, timeouts, requester, requestsCache, responsesCache, compress, compression, }: TransporterOptions): TransporterWithHttpInfo;
535
+ declare function createTransporter({ hosts, hostsCache, baseHeaders, logger, baseQueryParameters, algoliaAgent, timeouts, requester, requestsCache, responsesCache, compress, compression, requestIdChannel, }: TransporterOptions): TransporterWithHttpInfo;
521
536
 
522
537
  declare class AlgoliaError extends Error {
523
538
  name: string;
@@ -534,18 +549,20 @@ declare class IndexAlreadyExistsError extends AlgoliaError {
534
549
  }
535
550
  declare class ErrorWithStackTrace extends AlgoliaError {
536
551
  stackTrace: StackFrame[];
537
- constructor(message: string, stackTrace: StackFrame[], name: string);
552
+ correlationId?: string | undefined;
553
+ constructor(message: string, stackTrace: StackFrame[], name: string, correlationId?: string | undefined);
538
554
  }
539
555
  declare class RetryError extends ErrorWithStackTrace {
540
- constructor(stackTrace: StackFrame[]);
556
+ constructor(stackTrace: StackFrame[], correlationId?: string | undefined);
541
557
  }
542
558
  declare class ApiError extends ErrorWithStackTrace {
543
559
  status: number;
544
- constructor(message: string, status: number, stackTrace: StackFrame[], name?: string);
560
+ constructor(message: string, status: number, stackTrace: StackFrame[], name?: string, correlationId?: string | undefined);
545
561
  }
546
562
  declare class DeserializationError extends AlgoliaError {
547
563
  response: Response;
548
- constructor(message: string, response: Response);
564
+ correlationId?: string | undefined;
565
+ constructor(message: string, response: Response, correlationId?: string | undefined);
549
566
  }
550
567
  type DetailedErrorWithMessage = {
551
568
  message: string;
@@ -562,7 +579,7 @@ type DetailedError = {
562
579
  };
563
580
  declare class DetailedApiError extends ApiError {
564
581
  error: DetailedError;
565
- constructor(message: string, status: number, error: DetailedError, stackTrace: StackFrame[]);
582
+ constructor(message: string, status: number, error: DetailedError, stackTrace: StackFrame[], correlationId?: string | undefined);
566
583
  }
567
584
 
568
585
  declare function shuffle<TData>(array: TData[]): TData[];
@@ -572,7 +589,18 @@ declare function serializeData(request: Request, requestOptions: RequestOptions)
572
589
  declare function serializeHeaders(baseHeaders: Headers, requestHeaders: Headers, requestOptionsHeaders?: Headers | undefined): Headers;
573
590
  declare function deserializeSuccess<TObject>(response: Response): TObject;
574
591
  declare function deserializeSuccessWithHttpInfo<TData>(response: Response): AlgoliaHttpResponse<TData>;
575
- declare function deserializeFailure({ content, status }: Response, stackFrame: StackFrame[]): Error;
592
+ declare function getCorrelationId(headers: Headers | undefined): string | undefined;
593
+ declare function getLastCorrelationId(stackTrace: StackFrame[]): string | undefined;
594
+ declare function deserializeFailure(response: Response, stackFrame: StackFrame[]): Error;
595
+
596
+ declare function generateRequestId(): string;
597
+ /**
598
+ * Returns request options carrying a Request-ID on the transporter's channel, so that every
599
+ * request a multi-request helper performs shares the same ID. Returns the options unchanged
600
+ * when the channel is off or when a Request-ID is already supplied. Never apply ahead of a
601
+ * cacheable operation: the ID enters the cache key and defeats caching and deduplication.
602
+ */
603
+ declare function withRequestId(transporter: Pick<Transporter, 'requestIdChannel' | 'baseHeaders' | 'baseQueryParameters'>, requestOptions?: RequestOptions | undefined): RequestOptions | undefined;
576
604
 
577
605
  declare function isNetworkError({ isTimedOut, status }: Omit<Response, 'content'>): boolean;
578
606
  declare function isRetryable({ isTimedOut, status }: Omit<Response, 'content'>): boolean;
@@ -583,4 +611,4 @@ declare function stackFrameWithoutCredentials(stackFrame: StackFrame): StackFram
583
611
 
584
612
  declare function validateRequired(field: string, method: string, value: unknown): void;
585
613
 
586
- export { type AlgoliaAgent, type AlgoliaAgentOptions, AlgoliaError, type AlgoliaHttpResponse, ApiError, type AuthMode, type BrowserLocalStorageCacheItem, type BrowserLocalStorageOptions, COMPRESSION_THRESHOLD, type Cache, type CacheEvents, type ChunkedHelperOptions, type ClientOptions, type CreateClientOptions, type CreateIterablePromise, DEFAULT_CONNECT_TIMEOUT_BROWSER, DEFAULT_CONNECT_TIMEOUT_NODE, DEFAULT_READ_TIMEOUT_BROWSER, DEFAULT_READ_TIMEOUT_NODE, DEFAULT_REPLACE_ALL_OBJECTS_MAX_RETRIES, DEFAULT_WRITE_TIMEOUT_BROWSER, DEFAULT_WRITE_TIMEOUT_NODE, DeserializationError, DetailedApiError, type DetailedError, type DetailedErrorWithMessage, type DetailedErrorWithTypeID, type EndRequest, ErrorWithStackTrace, type FallbackableCacheOptions, type GetAlgoliaAgent, type Headers, type Host, IndexAlreadyExistsError, IndexNotFoundError, IndicesInSameAppError, type IterableOptions, LogLevelEnum, type LogLevelType, type Logger, type MemoryCacheOptions, type Method, type QueryParameters, type Request, type RequestOptions, type Requester, type Response, RetryError, type ServerSentEvent, type StackFrame, type StatefulHost, type StreamEvent, type Timeouts, type Transporter, type TransporterOptions, type TransporterWithHttpInfo, createAlgoliaAgent, createAuth, createBrowserLocalStorageCache, createFallbackableCache, createIterablePromise, createMemoryCache, createNullCache, createNullLogger, createStatefulHost, createTransporter, deserializeFailure, deserializeSuccess, deserializeSuccessWithHttpInfo, getAlgoliaAgent, isNetworkError, isRetryable, isSuccess, iterSSEEvents, serializeData, serializeHeaders, serializeQueryParameters, serializeUrl, shuffle, stackFrameWithoutCredentials, stackTraceWithoutCredentials, validateRequired };
614
+ export { type AlgoliaAgent, type AlgoliaAgentOptions, AlgoliaError, type AlgoliaHttpResponse, ApiError, type AuthMode, type BrowserLocalStorageCacheItem, type BrowserLocalStorageOptions, COMPRESSION_THRESHOLD, type Cache, type CacheEvents, type ChunkedHelperOptions, type ClientOptions, type CreateClientOptions, type CreateIterablePromise, DEFAULT_CONNECT_TIMEOUT_BROWSER, DEFAULT_CONNECT_TIMEOUT_NODE, DEFAULT_READ_TIMEOUT_BROWSER, DEFAULT_READ_TIMEOUT_NODE, DEFAULT_REPLACE_ALL_OBJECTS_MAX_RETRIES, DEFAULT_WRITE_TIMEOUT_BROWSER, DEFAULT_WRITE_TIMEOUT_NODE, DeserializationError, DetailedApiError, type DetailedError, type DetailedErrorWithMessage, type DetailedErrorWithTypeID, type EndRequest, ErrorWithStackTrace, type FallbackableCacheOptions, type GetAlgoliaAgent, type Headers, type Host, IndexAlreadyExistsError, IndexNotFoundError, IndicesInSameAppError, type IterableOptions, LogLevelEnum, type LogLevelType, type Logger, type MemoryCacheOptions, type Method, type QueryParameters, type Request, type RequestOptions, type Requester, type Response, RetryError, type ServerSentEvent, type StackFrame, type StatefulHost, type StreamEvent, type Timeouts, type Transporter, type TransporterOptions, type TransporterWithHttpInfo, createAlgoliaAgent, createAuth, createBrowserLocalStorageCache, createFallbackableCache, createIterablePromise, createMemoryCache, createNullCache, createNullLogger, createStatefulHost, createTransporter, deserializeFailure, deserializeSuccess, deserializeSuccessWithHttpInfo, generateRequestId, getAlgoliaAgent, getCorrelationId, getLastCorrelationId, isNetworkError, isRetryable, isSuccess, iterSSEEvents, logWarning, serializeData, serializeHeaders, serializeQueryParameters, serializeUrl, shuffle, stackFrameWithoutCredentials, stackTraceWithoutCredentials, validateRequired, withRequestId };
package/dist/common.d.ts CHANGED
@@ -261,6 +261,10 @@ type Logger = {
261
261
  * Logs info messages.
262
262
  */
263
263
  info: (message: string, args?: any | undefined) => Promise<void>;
264
+ /**
265
+ * Logs warning messages. When not implemented, warnings fall back to `console.warn` so they stay visible with the default no-op logger.
266
+ */
267
+ warn?: (message: string, args?: any | undefined) => Promise<void>;
264
268
  /**
265
269
  * Logs error messages.
266
270
  */
@@ -401,6 +405,12 @@ type TransporterOptions = {
401
405
  */
402
406
  compress?: (data: string) => Promise<Uint8Array>;
403
407
  compression?: 'gzip';
408
+ /**
409
+ * Where the generated Request-ID is sent: as the `Request-ID` header, or as the
410
+ * `x-algolia-request-id` query parameter. When undefined, no Request-ID is sent.
411
+ * A caller-supplied Request-ID is never overwritten.
412
+ */
413
+ requestIdChannel?: 'headers' | 'queryParameters' | undefined;
404
414
  };
405
415
  type Transporter = TransporterOptions & {
406
416
  /**
@@ -513,11 +523,16 @@ declare function getAlgoliaAgent({ algoliaAgents, client, version }: GetAlgoliaA
513
523
 
514
524
  declare function createNullLogger(): Logger;
515
525
 
526
+ /**
527
+ * Prefers the logger's optional `warn` method and falls back to `console.warn`, so warnings stay visible with the default no-op logger.
528
+ */
529
+ declare function logWarning(logger: Logger, message: string): void;
530
+
516
531
  declare const COMPRESSION_THRESHOLD = 750;
517
532
 
518
533
  declare function createStatefulHost(host: Host, status?: StatefulHost['status']): StatefulHost;
519
534
 
520
- declare function createTransporter({ hosts, hostsCache, baseHeaders, logger, baseQueryParameters, algoliaAgent, timeouts, requester, requestsCache, responsesCache, compress, compression, }: TransporterOptions): TransporterWithHttpInfo;
535
+ declare function createTransporter({ hosts, hostsCache, baseHeaders, logger, baseQueryParameters, algoliaAgent, timeouts, requester, requestsCache, responsesCache, compress, compression, requestIdChannel, }: TransporterOptions): TransporterWithHttpInfo;
521
536
 
522
537
  declare class AlgoliaError extends Error {
523
538
  name: string;
@@ -534,18 +549,20 @@ declare class IndexAlreadyExistsError extends AlgoliaError {
534
549
  }
535
550
  declare class ErrorWithStackTrace extends AlgoliaError {
536
551
  stackTrace: StackFrame[];
537
- constructor(message: string, stackTrace: StackFrame[], name: string);
552
+ correlationId?: string | undefined;
553
+ constructor(message: string, stackTrace: StackFrame[], name: string, correlationId?: string | undefined);
538
554
  }
539
555
  declare class RetryError extends ErrorWithStackTrace {
540
- constructor(stackTrace: StackFrame[]);
556
+ constructor(stackTrace: StackFrame[], correlationId?: string | undefined);
541
557
  }
542
558
  declare class ApiError extends ErrorWithStackTrace {
543
559
  status: number;
544
- constructor(message: string, status: number, stackTrace: StackFrame[], name?: string);
560
+ constructor(message: string, status: number, stackTrace: StackFrame[], name?: string, correlationId?: string | undefined);
545
561
  }
546
562
  declare class DeserializationError extends AlgoliaError {
547
563
  response: Response;
548
- constructor(message: string, response: Response);
564
+ correlationId?: string | undefined;
565
+ constructor(message: string, response: Response, correlationId?: string | undefined);
549
566
  }
550
567
  type DetailedErrorWithMessage = {
551
568
  message: string;
@@ -562,7 +579,7 @@ type DetailedError = {
562
579
  };
563
580
  declare class DetailedApiError extends ApiError {
564
581
  error: DetailedError;
565
- constructor(message: string, status: number, error: DetailedError, stackTrace: StackFrame[]);
582
+ constructor(message: string, status: number, error: DetailedError, stackTrace: StackFrame[], correlationId?: string | undefined);
566
583
  }
567
584
 
568
585
  declare function shuffle<TData>(array: TData[]): TData[];
@@ -572,7 +589,18 @@ declare function serializeData(request: Request, requestOptions: RequestOptions)
572
589
  declare function serializeHeaders(baseHeaders: Headers, requestHeaders: Headers, requestOptionsHeaders?: Headers | undefined): Headers;
573
590
  declare function deserializeSuccess<TObject>(response: Response): TObject;
574
591
  declare function deserializeSuccessWithHttpInfo<TData>(response: Response): AlgoliaHttpResponse<TData>;
575
- declare function deserializeFailure({ content, status }: Response, stackFrame: StackFrame[]): Error;
592
+ declare function getCorrelationId(headers: Headers | undefined): string | undefined;
593
+ declare function getLastCorrelationId(stackTrace: StackFrame[]): string | undefined;
594
+ declare function deserializeFailure(response: Response, stackFrame: StackFrame[]): Error;
595
+
596
+ declare function generateRequestId(): string;
597
+ /**
598
+ * Returns request options carrying a Request-ID on the transporter's channel, so that every
599
+ * request a multi-request helper performs shares the same ID. Returns the options unchanged
600
+ * when the channel is off or when a Request-ID is already supplied. Never apply ahead of a
601
+ * cacheable operation: the ID enters the cache key and defeats caching and deduplication.
602
+ */
603
+ declare function withRequestId(transporter: Pick<Transporter, 'requestIdChannel' | 'baseHeaders' | 'baseQueryParameters'>, requestOptions?: RequestOptions | undefined): RequestOptions | undefined;
576
604
 
577
605
  declare function isNetworkError({ isTimedOut, status }: Omit<Response, 'content'>): boolean;
578
606
  declare function isRetryable({ isTimedOut, status }: Omit<Response, 'content'>): boolean;
@@ -583,4 +611,4 @@ declare function stackFrameWithoutCredentials(stackFrame: StackFrame): StackFram
583
611
 
584
612
  declare function validateRequired(field: string, method: string, value: unknown): void;
585
613
 
586
- export { type AlgoliaAgent, type AlgoliaAgentOptions, AlgoliaError, type AlgoliaHttpResponse, ApiError, type AuthMode, type BrowserLocalStorageCacheItem, type BrowserLocalStorageOptions, COMPRESSION_THRESHOLD, type Cache, type CacheEvents, type ChunkedHelperOptions, type ClientOptions, type CreateClientOptions, type CreateIterablePromise, DEFAULT_CONNECT_TIMEOUT_BROWSER, DEFAULT_CONNECT_TIMEOUT_NODE, DEFAULT_READ_TIMEOUT_BROWSER, DEFAULT_READ_TIMEOUT_NODE, DEFAULT_REPLACE_ALL_OBJECTS_MAX_RETRIES, DEFAULT_WRITE_TIMEOUT_BROWSER, DEFAULT_WRITE_TIMEOUT_NODE, DeserializationError, DetailedApiError, type DetailedError, type DetailedErrorWithMessage, type DetailedErrorWithTypeID, type EndRequest, ErrorWithStackTrace, type FallbackableCacheOptions, type GetAlgoliaAgent, type Headers, type Host, IndexAlreadyExistsError, IndexNotFoundError, IndicesInSameAppError, type IterableOptions, LogLevelEnum, type LogLevelType, type Logger, type MemoryCacheOptions, type Method, type QueryParameters, type Request, type RequestOptions, type Requester, type Response, RetryError, type ServerSentEvent, type StackFrame, type StatefulHost, type StreamEvent, type Timeouts, type Transporter, type TransporterOptions, type TransporterWithHttpInfo, createAlgoliaAgent, createAuth, createBrowserLocalStorageCache, createFallbackableCache, createIterablePromise, createMemoryCache, createNullCache, createNullLogger, createStatefulHost, createTransporter, deserializeFailure, deserializeSuccess, deserializeSuccessWithHttpInfo, getAlgoliaAgent, isNetworkError, isRetryable, isSuccess, iterSSEEvents, serializeData, serializeHeaders, serializeQueryParameters, serializeUrl, shuffle, stackFrameWithoutCredentials, stackTraceWithoutCredentials, validateRequired };
614
+ export { type AlgoliaAgent, type AlgoliaAgentOptions, AlgoliaError, type AlgoliaHttpResponse, ApiError, type AuthMode, type BrowserLocalStorageCacheItem, type BrowserLocalStorageOptions, COMPRESSION_THRESHOLD, type Cache, type CacheEvents, type ChunkedHelperOptions, type ClientOptions, type CreateClientOptions, type CreateIterablePromise, DEFAULT_CONNECT_TIMEOUT_BROWSER, DEFAULT_CONNECT_TIMEOUT_NODE, DEFAULT_READ_TIMEOUT_BROWSER, DEFAULT_READ_TIMEOUT_NODE, DEFAULT_REPLACE_ALL_OBJECTS_MAX_RETRIES, DEFAULT_WRITE_TIMEOUT_BROWSER, DEFAULT_WRITE_TIMEOUT_NODE, DeserializationError, DetailedApiError, type DetailedError, type DetailedErrorWithMessage, type DetailedErrorWithTypeID, type EndRequest, ErrorWithStackTrace, type FallbackableCacheOptions, type GetAlgoliaAgent, type Headers, type Host, IndexAlreadyExistsError, IndexNotFoundError, IndicesInSameAppError, type IterableOptions, LogLevelEnum, type LogLevelType, type Logger, type MemoryCacheOptions, type Method, type QueryParameters, type Request, type RequestOptions, type Requester, type Response, RetryError, type ServerSentEvent, type StackFrame, type StatefulHost, type StreamEvent, type Timeouts, type Transporter, type TransporterOptions, type TransporterWithHttpInfo, createAlgoliaAgent, createAuth, createBrowserLocalStorageCache, createFallbackableCache, createIterablePromise, createMemoryCache, createNullCache, createNullLogger, createStatefulHost, createTransporter, deserializeFailure, deserializeSuccess, deserializeSuccessWithHttpInfo, generateRequestId, getAlgoliaAgent, getCorrelationId, getLastCorrelationId, isNetworkError, isRetryable, isSuccess, iterSSEEvents, logWarning, serializeData, serializeHeaders, serializeQueryParameters, serializeUrl, shuffle, stackFrameWithoutCredentials, stackTraceWithoutCredentials, validateRequired, withRequestId };
package/dist/common.js CHANGED
@@ -264,6 +264,16 @@ function createNullLogger() {
264
264
  };
265
265
  }
266
266
 
267
+ // src/logger/logWarning.ts
268
+ function logWarning(logger, message) {
269
+ if (logger.warn) {
270
+ void Promise.resolve(logger.warn(message)).catch(() => {
271
+ });
272
+ } else {
273
+ console.warn(message);
274
+ }
275
+ }
276
+
267
277
  // src/sse.ts
268
278
  var MAX_LINE_BUFFER_SIZE = 10 * 1024 * 1024;
269
279
  async function* readableStreamToAsyncIterable(stream) {
@@ -466,38 +476,43 @@ var IndexAlreadyExistsError = class extends AlgoliaError {
466
476
  };
467
477
  var ErrorWithStackTrace = class extends AlgoliaError {
468
478
  stackTrace;
469
- constructor(message, stackTrace, name) {
470
- super(message, name);
479
+ correlationId;
480
+ constructor(message, stackTrace, name, correlationId) {
481
+ super(correlationId ? `${message} (Correlation-ID: ${correlationId})` : message, name);
471
482
  this.stackTrace = stackTrace;
483
+ this.correlationId = correlationId;
472
484
  }
473
485
  };
474
486
  var RetryError = class extends ErrorWithStackTrace {
475
- constructor(stackTrace) {
487
+ constructor(stackTrace, correlationId) {
476
488
  super(
477
489
  "Unreachable hosts - your application id may be incorrect. If the error persists, please visit our help center https://alg.li/support-unreachable-hosts or reach out to the Algolia Support team: https://alg.li/support",
478
490
  stackTrace,
479
- "RetryError"
491
+ "RetryError",
492
+ correlationId
480
493
  );
481
494
  }
482
495
  };
483
496
  var ApiError = class extends ErrorWithStackTrace {
484
497
  status;
485
- constructor(message, status, stackTrace, name = "ApiError") {
486
- super(message, stackTrace, name);
498
+ constructor(message, status, stackTrace, name = "ApiError", correlationId) {
499
+ super(message, stackTrace, name, correlationId);
487
500
  this.status = status;
488
501
  }
489
502
  };
490
503
  var DeserializationError = class extends AlgoliaError {
491
504
  response;
492
- constructor(message, response) {
493
- super(message, "DeserializationError");
505
+ correlationId;
506
+ constructor(message, response, correlationId) {
507
+ super(correlationId ? `${message} (Correlation-ID: ${correlationId})` : message, "DeserializationError");
494
508
  this.response = response;
509
+ this.correlationId = correlationId;
495
510
  }
496
511
  };
497
512
  var DetailedApiError = class extends ApiError {
498
513
  error;
499
- constructor(message, status, error, stackTrace) {
500
- super(message, status, stackTrace, "DetailedApiError");
514
+ constructor(message, status, error, stackTrace, correlationId) {
515
+ super(message, status, stackTrace, "DetailedApiError", correlationId);
501
516
  this.error = error;
502
517
  }
503
518
  };
@@ -556,7 +571,7 @@ function deserializeSuccess(response) {
556
571
  try {
557
572
  return JSON.parse(response.content);
558
573
  } catch (e) {
559
- throw new DeserializationError(e.message, response);
574
+ throw new DeserializationError(e.message, response, getCorrelationId(response.headers));
560
575
  }
561
576
  }
562
577
  function deserializeSuccessWithHttpInfo(response) {
@@ -567,16 +582,72 @@ function deserializeSuccessWithHttpInfo(response) {
567
582
  data: deserializeSuccess(response)
568
583
  };
569
584
  }
570
- function deserializeFailure({ content, status }, stackFrame) {
585
+ function getCorrelationId(headers) {
586
+ if (!headers) {
587
+ return void 0;
588
+ }
589
+ if (headers["correlation-id"] !== void 0) {
590
+ return headers["correlation-id"];
591
+ }
592
+ const header = Object.keys(headers).find((key) => key.toLowerCase() === "correlation-id");
593
+ return header === void 0 ? void 0 : headers[header];
594
+ }
595
+ function getLastCorrelationId(stackTrace) {
596
+ for (let i = stackTrace.length - 1; i >= 0; i--) {
597
+ const correlationId = getCorrelationId(stackTrace[i].response.headers);
598
+ if (correlationId !== void 0) {
599
+ return correlationId;
600
+ }
601
+ }
602
+ return void 0;
603
+ }
604
+ function deserializeFailure(response, stackFrame) {
605
+ const { content, status } = response;
606
+ const correlationId = getCorrelationId(response.headers);
571
607
  try {
572
608
  const parsed = JSON.parse(content);
573
609
  if ("error" in parsed) {
574
- return new DetailedApiError(parsed.message, status, parsed.error, stackFrame);
610
+ return new DetailedApiError(parsed.message, status, parsed.error, stackFrame, correlationId);
575
611
  }
576
- return new ApiError(parsed.message, status, stackFrame);
612
+ return new ApiError(parsed.message, status, stackFrame, "ApiError", correlationId);
577
613
  } catch {
578
614
  }
579
- return new ApiError(content, status, stackFrame);
615
+ return new ApiError(content, status, stackFrame, "ApiError", correlationId);
616
+ }
617
+
618
+ // src/transporter/requestId.ts
619
+ var BASE62_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
620
+ var REQUEST_ID_LENGTH = 11;
621
+ function generateRequestId() {
622
+ var _a;
623
+ let requestId = "";
624
+ if (typeof ((_a = globalThis.crypto) == null ? void 0 : _a.getRandomValues) === "function") {
625
+ const bytes = new Uint8Array(REQUEST_ID_LENGTH);
626
+ globalThis.crypto.getRandomValues(bytes);
627
+ for (const byte of bytes) {
628
+ requestId += BASE62_CHARS[byte % BASE62_CHARS.length];
629
+ }
630
+ return requestId;
631
+ }
632
+ for (let i = 0; i < REQUEST_ID_LENGTH; i++) {
633
+ requestId += BASE62_CHARS[Math.floor(Math.random() * BASE62_CHARS.length)];
634
+ }
635
+ return requestId;
636
+ }
637
+ function hasRequestId(headers, queryParameters) {
638
+ return headers !== void 0 && Object.keys(headers).some((header) => header.toLowerCase() === "request-id") || queryParameters !== void 0 && Object.keys(queryParameters).some((parameter) => parameter.toLowerCase() === "x-algolia-request-id");
639
+ }
640
+ function withRequestId(transporter, requestOptions) {
641
+ if (transporter.requestIdChannel === void 0 || hasRequestId(transporter.baseHeaders, transporter.baseQueryParameters) || hasRequestId(requestOptions == null ? void 0 : requestOptions.headers, requestOptions == null ? void 0 : requestOptions.queryParameters)) {
642
+ return requestOptions;
643
+ }
644
+ if (transporter.requestIdChannel === "headers") {
645
+ return { ...requestOptions, headers: { ...requestOptions == null ? void 0 : requestOptions.headers, "request-id": generateRequestId() } };
646
+ }
647
+ return {
648
+ ...requestOptions,
649
+ queryParameters: { ...requestOptions == null ? void 0 : requestOptions.queryParameters, "x-algolia-request-id": generateRequestId() }
650
+ };
580
651
  }
581
652
 
582
653
  // src/transporter/responses.ts
@@ -621,8 +692,19 @@ function createTransporter({
621
692
  requestsCache,
622
693
  responsesCache,
623
694
  compress,
624
- compression
695
+ compression,
696
+ requestIdChannel
625
697
  }) {
698
+ function injectRequestId(headers, queryParameters) {
699
+ if (requestIdChannel === void 0 || headers["request-id"] !== void 0 || Object.keys(queryParameters).some((parameter) => parameter.toLowerCase() === "x-algolia-request-id")) {
700
+ return;
701
+ }
702
+ if (requestIdChannel === "headers") {
703
+ headers["request-id"] = generateRequestId();
704
+ } else {
705
+ queryParameters["x-algolia-request-id"] = generateRequestId();
706
+ }
707
+ }
626
708
  async function createRetryableOptions(compatibleHosts) {
627
709
  const statefulHosts = await Promise.all(
628
710
  compatibleHosts.map((compatibleHost) => {
@@ -677,11 +759,12 @@ function createTransporter({
677
759
  }
678
760
  }
679
761
  }
762
+ injectRequestId(headers, queryParameters);
680
763
  let timeoutsCount = 0;
681
764
  const retry = async (retryableHosts, getTimeout) => {
682
765
  const host = retryableHosts.pop();
683
766
  if (host === void 0) {
684
- throw new RetryError(stackTraceWithoutCredentials(stackTrace));
767
+ throw new RetryError(stackTraceWithoutCredentials(stackTrace), getLastCorrelationId(stackTrace));
685
768
  }
686
769
  const timeout = { ...timeouts, ...requestOptions.timeouts };
687
770
  const payload = {
@@ -805,6 +888,7 @@ function createTransporter({
805
888
  }
806
889
  }
807
890
  }
891
+ injectRequestId(headers, queryParameters);
808
892
  const isRead = request.useReadTransporter || request.method === "GET";
809
893
  const compatibleHosts = hosts.filter(
810
894
  (host2) => host2.accept === "readWrite" || (isRead ? host2.accept === "read" : host2.accept === "write")
@@ -834,6 +918,7 @@ function createTransporter({
834
918
  algoliaAgent,
835
919
  baseHeaders,
836
920
  baseQueryParameters,
921
+ requestIdChannel,
837
922
  hosts,
838
923
  request: createRequest,
839
924
  requestWithHttpInfo: createRequestWithHttpInfo,
@@ -888,11 +973,15 @@ export {
888
973
  deserializeFailure,
889
974
  deserializeSuccess,
890
975
  deserializeSuccessWithHttpInfo,
976
+ generateRequestId,
891
977
  getAlgoliaAgent,
978
+ getCorrelationId,
979
+ getLastCorrelationId,
892
980
  isNetworkError,
893
981
  isRetryable,
894
982
  isSuccess,
895
983
  iterSSEEvents,
984
+ logWarning,
896
985
  serializeData,
897
986
  serializeHeaders,
898
987
  serializeQueryParameters,
@@ -900,6 +989,7 @@ export {
900
989
  shuffle,
901
990
  stackFrameWithoutCredentials,
902
991
  stackTraceWithoutCredentials,
903
- validateRequired
992
+ validateRequired,
993
+ withRequestId
904
994
  };
905
995
  //# sourceMappingURL=common.js.map