@algolia/client-common 5.2.3 → 5.2.4-beta.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 (61) hide show
  1. package/dist/common.cjs +714 -0
  2. package/dist/common.cjs.map +1 -0
  3. package/dist/common.d.cts +438 -0
  4. package/dist/common.d.ts +438 -0
  5. package/dist/common.esm.js +653 -0
  6. package/dist/common.esm.js.map +1 -0
  7. package/package.json +21 -7
  8. package/dist/client-common.cjs +0 -783
  9. package/dist/client-common.esm.node.js +0 -747
  10. package/dist/index.d.ts +0 -10
  11. package/dist/index.d.ts.map +0 -1
  12. package/dist/src/cache/createBrowserLocalStorageCache.d.ts +0 -3
  13. package/dist/src/cache/createBrowserLocalStorageCache.d.ts.map +0 -1
  14. package/dist/src/cache/createFallbackableCache.d.ts +0 -3
  15. package/dist/src/cache/createFallbackableCache.d.ts.map +0 -1
  16. package/dist/src/cache/createMemoryCache.d.ts +0 -3
  17. package/dist/src/cache/createMemoryCache.d.ts.map +0 -1
  18. package/dist/src/cache/createNullCache.d.ts +0 -3
  19. package/dist/src/cache/createNullCache.d.ts.map +0 -1
  20. package/dist/src/cache/index.d.ts +0 -5
  21. package/dist/src/cache/index.d.ts.map +0 -1
  22. package/dist/src/constants.d.ts +0 -7
  23. package/dist/src/constants.d.ts.map +0 -1
  24. package/dist/src/createAlgoliaAgent.d.ts +0 -3
  25. package/dist/src/createAlgoliaAgent.d.ts.map +0 -1
  26. package/dist/src/createAuth.d.ts +0 -6
  27. package/dist/src/createAuth.d.ts.map +0 -1
  28. package/dist/src/createEchoRequester.d.ts +0 -7
  29. package/dist/src/createEchoRequester.d.ts.map +0 -1
  30. package/dist/src/createIterablePromise.d.ts +0 -13
  31. package/dist/src/createIterablePromise.d.ts.map +0 -1
  32. package/dist/src/getAlgoliaAgent.d.ts +0 -8
  33. package/dist/src/getAlgoliaAgent.d.ts.map +0 -1
  34. package/dist/src/transporter/createStatefulHost.d.ts +0 -3
  35. package/dist/src/transporter/createStatefulHost.d.ts.map +0 -1
  36. package/dist/src/transporter/createTransporter.d.ts +0 -3
  37. package/dist/src/transporter/createTransporter.d.ts.map +0 -1
  38. package/dist/src/transporter/errors.d.ts +0 -38
  39. package/dist/src/transporter/errors.d.ts.map +0 -1
  40. package/dist/src/transporter/helpers.d.ts +0 -9
  41. package/dist/src/transporter/helpers.d.ts.map +0 -1
  42. package/dist/src/transporter/index.d.ts +0 -7
  43. package/dist/src/transporter/index.d.ts.map +0 -1
  44. package/dist/src/transporter/responses.d.ts +0 -5
  45. package/dist/src/transporter/responses.d.ts.map +0 -1
  46. package/dist/src/transporter/stackTrace.d.ts +0 -4
  47. package/dist/src/transporter/stackTrace.d.ts.map +0 -1
  48. package/dist/src/types/cache.d.ts +0 -61
  49. package/dist/src/types/cache.d.ts.map +0 -1
  50. package/dist/src/types/createClient.d.ts +0 -12
  51. package/dist/src/types/createClient.d.ts.map +0 -1
  52. package/dist/src/types/createIterablePromise.d.ts +0 -36
  53. package/dist/src/types/createIterablePromise.d.ts.map +0 -1
  54. package/dist/src/types/host.d.ts +0 -37
  55. package/dist/src/types/host.d.ts.map +0 -1
  56. package/dist/src/types/index.d.ts +0 -7
  57. package/dist/src/types/index.d.ts.map +0 -1
  58. package/dist/src/types/requester.d.ts +0 -66
  59. package/dist/src/types/requester.d.ts.map +0 -1
  60. package/dist/src/types/transporter.d.ts +0 -128
  61. package/dist/src/types/transporter.d.ts.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../index.ts","../src/createAuth.ts","../src/createEchoRequester.ts","../src/createIterablePromise.ts","../src/cache/createBrowserLocalStorageCache.ts","../src/cache/createNullCache.ts","../src/cache/createFallbackableCache.ts","../src/cache/createMemoryCache.ts","../src/transporter/createStatefulHost.ts","../src/transporter/errors.ts","../src/transporter/helpers.ts","../src/transporter/responses.ts","../src/transporter/stackTrace.ts","../src/transporter/createTransporter.ts","../src/createAlgoliaAgent.ts","../src/getAlgoliaAgent.ts","../src/constants.ts"],"sourcesContent":["export * from './src/createAuth';\nexport * from './src/createEchoRequester';\nexport * from './src/createIterablePromise';\nexport * from './src/cache';\nexport * from './src/transporter';\nexport * from './src/createAlgoliaAgent';\nexport * from './src/getAlgoliaAgent';\nexport * from './src/types';\nexport * from './src/constants';\n","import type { AuthMode, Headers, QueryParameters } from './types';\n\nexport function createAuth(\n appId: string,\n apiKey: string,\n authMode: AuthMode = 'WithinHeaders',\n): {\n readonly headers: () => Headers;\n readonly queryParameters: () => QueryParameters;\n} {\n const credentials = {\n 'x-algolia-api-key': apiKey,\n 'x-algolia-application-id': appId,\n };\n\n return {\n headers(): Headers {\n return authMode === 'WithinHeaders' ? credentials : {};\n },\n\n queryParameters(): QueryParameters {\n return authMode === 'WithinQueryParameters' ? credentials : {};\n },\n };\n}\n","import type { EchoResponse, EndRequest, Requester, Response } from './types';\n\nexport type EchoRequesterParams = {\n getURL: (url: string) => URL;\n status?: number;\n};\n\nfunction getUrlParams({\n host,\n search,\n pathname,\n}: URL): Pick<EchoResponse, 'algoliaAgent' | 'host' | 'path' | 'searchParams'> {\n const urlSearchParams = search.split('?');\n if (urlSearchParams.length === 1) {\n return {\n host,\n algoliaAgent: '',\n searchParams: undefined,\n path: pathname,\n };\n }\n\n const splitSearchParams = urlSearchParams[1].split('&');\n let algoliaAgent = '';\n const searchParams: Record<string, string> = {};\n\n if (splitSearchParams.length > 0) {\n splitSearchParams.forEach((param) => {\n const [key, value] = param.split('=');\n if (key === 'x-algolia-agent') {\n algoliaAgent = value;\n return;\n }\n\n searchParams[key] = value;\n });\n }\n\n return {\n host,\n algoliaAgent,\n searchParams: Object.keys(searchParams).length === 0 ? undefined : searchParams,\n path: pathname,\n };\n}\n\nexport function createEchoRequester({ getURL, status = 200 }: EchoRequesterParams): Requester {\n function send(request: EndRequest): Promise<Response> {\n const { host, searchParams, algoliaAgent, path } = getUrlParams(getURL(request.url));\n\n const content: EchoResponse = {\n ...request,\n data: request.data ? JSON.parse(request.data) : undefined,\n path,\n host,\n algoliaAgent,\n searchParams,\n };\n\n return Promise.resolve({\n content: JSON.stringify(content),\n isTimedOut: false,\n status,\n });\n }\n\n return { send };\n}\n","import type { CreateIterablePromise } from './types/createIterablePromise';\n\n/**\n * Helper: Returns the promise of a given `func` to iterate on, based on a given `validate` condition.\n *\n * @param createIterator - The createIterator options.\n * @param createIterator.func - The function to run, which returns a promise.\n * @param createIterator.validate - The validator function. It receives the resolved return of `func`.\n * @param createIterator.aggregator - The function that runs right after the `func` method has been executed, allows you to do anything with the response before `validate`.\n * @param createIterator.error - The `validate` condition to throw an error, and its message.\n * @param createIterator.timeout - The function to decide how long to wait between iterations.\n */\nexport function createIterablePromise<TResponse>({\n func,\n validate,\n aggregator,\n error,\n timeout = (): number => 0,\n}: CreateIterablePromise<TResponse>): Promise<TResponse> {\n const retry = (previousResponse?: TResponse): Promise<TResponse> => {\n return new Promise<TResponse>((resolve, reject) => {\n func(previousResponse)\n .then((response) => {\n if (aggregator) {\n aggregator(response);\n }\n\n if (validate(response)) {\n return resolve(response);\n }\n\n if (error && error.validate(response)) {\n return reject(new Error(error.message(response)));\n }\n\n return setTimeout(() => {\n retry(response).then(resolve).catch(reject);\n }, timeout());\n })\n .catch((err) => {\n reject(err);\n });\n });\n };\n\n return retry();\n}\n","import type { BrowserLocalStorageCacheItem, BrowserLocalStorageOptions, Cache, CacheEvents } from '../types';\n\nexport function createBrowserLocalStorageCache(options: BrowserLocalStorageOptions): Cache {\n let storage: Storage;\n // We've changed the namespace to avoid conflicts with v4, as this version is a huge breaking change\n const namespaceKey = `algolia-client-js-${options.key}`;\n\n function getStorage(): Storage {\n if (storage === undefined) {\n storage = options.localStorage || window.localStorage;\n }\n\n return storage;\n }\n\n function getNamespace<TValue>(): Record<string, TValue> {\n return JSON.parse(getStorage().getItem(namespaceKey) || '{}');\n }\n\n function setNamespace(namespace: Record<string, any>): void {\n getStorage().setItem(namespaceKey, JSON.stringify(namespace));\n }\n\n function removeOutdatedCacheItems(): void {\n const timeToLive = options.timeToLive ? options.timeToLive * 1000 : null;\n const namespace = getNamespace<BrowserLocalStorageCacheItem>();\n\n const filteredNamespaceWithoutOldFormattedCacheItems = Object.fromEntries(\n Object.entries(namespace).filter(([, cacheItem]) => {\n return cacheItem.timestamp !== undefined;\n }),\n );\n\n setNamespace(filteredNamespaceWithoutOldFormattedCacheItems);\n\n if (!timeToLive) {\n return;\n }\n\n const filteredNamespaceWithoutExpiredItems = Object.fromEntries(\n Object.entries(filteredNamespaceWithoutOldFormattedCacheItems).filter(([, cacheItem]) => {\n const currentTimestamp = new Date().getTime();\n const isExpired = cacheItem.timestamp + timeToLive < currentTimestamp;\n\n return !isExpired;\n }),\n );\n\n setNamespace(filteredNamespaceWithoutExpiredItems);\n }\n\n return {\n get<TValue>(\n key: Record<string, any> | string,\n defaultValue: () => Promise<TValue>,\n events: CacheEvents<TValue> = {\n miss: () => Promise.resolve(),\n },\n ): Promise<TValue> {\n return Promise.resolve()\n .then(() => {\n removeOutdatedCacheItems();\n\n return getNamespace<Promise<BrowserLocalStorageCacheItem>>()[JSON.stringify(key)];\n })\n .then((value) => {\n return Promise.all([value ? value.value : defaultValue(), value !== undefined]);\n })\n .then(([value, exists]) => {\n return Promise.all([value, exists || events.miss(value)]);\n })\n .then(([value]) => value);\n },\n\n set<TValue>(key: Record<string, any> | string, value: TValue): Promise<TValue> {\n return Promise.resolve().then(() => {\n const namespace = getNamespace();\n\n namespace[JSON.stringify(key)] = {\n timestamp: new Date().getTime(),\n value,\n };\n\n getStorage().setItem(namespaceKey, JSON.stringify(namespace));\n\n return value;\n });\n },\n\n delete(key: Record<string, any> | string): Promise<void> {\n return Promise.resolve().then(() => {\n const namespace = getNamespace();\n\n delete namespace[JSON.stringify(key)];\n\n getStorage().setItem(namespaceKey, JSON.stringify(namespace));\n });\n },\n\n clear(): Promise<void> {\n return Promise.resolve().then(() => {\n getStorage().removeItem(namespaceKey);\n });\n },\n };\n}\n","import type { Cache, CacheEvents } from '../types';\n\nexport function createNullCache(): Cache {\n return {\n get<TValue>(\n _key: Record<string, any> | string,\n defaultValue: () => Promise<TValue>,\n events: CacheEvents<TValue> = {\n miss: (): Promise<void> => Promise.resolve(),\n },\n ): Promise<TValue> {\n const value = defaultValue();\n\n return value.then((result) => Promise.all([result, events.miss(result)])).then(([result]) => result);\n },\n\n set<TValue>(_key: Record<string, any> | string, value: TValue): Promise<TValue> {\n return Promise.resolve(value);\n },\n\n delete(_key: Record<string, any> | string): Promise<void> {\n return Promise.resolve();\n },\n\n clear(): Promise<void> {\n return Promise.resolve();\n },\n };\n}\n","import type { FallbackableCacheOptions, Cache, CacheEvents } from '../types';\n\nimport { createNullCache } from './createNullCache';\n\nexport function createFallbackableCache(options: FallbackableCacheOptions): Cache {\n const caches = [...options.caches];\n const current = caches.shift();\n\n if (current === undefined) {\n return createNullCache();\n }\n\n return {\n get<TValue>(\n key: Record<string, any> | string,\n defaultValue: () => Promise<TValue>,\n events: CacheEvents<TValue> = {\n miss: (): Promise<void> => Promise.resolve(),\n },\n ): Promise<TValue> {\n return current.get(key, defaultValue, events).catch(() => {\n return createFallbackableCache({ caches }).get(key, defaultValue, events);\n });\n },\n\n set<TValue>(key: Record<string, any> | string, value: TValue): Promise<TValue> {\n return current.set(key, value).catch(() => {\n return createFallbackableCache({ caches }).set(key, value);\n });\n },\n\n delete(key: Record<string, any> | string): Promise<void> {\n return current.delete(key).catch(() => {\n return createFallbackableCache({ caches }).delete(key);\n });\n },\n\n clear(): Promise<void> {\n return current.clear().catch(() => {\n return createFallbackableCache({ caches }).clear();\n });\n },\n };\n}\n","import type { Cache, CacheEvents, MemoryCacheOptions } from '../types';\n\nexport function createMemoryCache(options: MemoryCacheOptions = { serializable: true }): Cache {\n let cache: Record<string, any> = {};\n\n return {\n get<TValue>(\n key: Record<string, any> | string,\n defaultValue: () => Promise<TValue>,\n events: CacheEvents<TValue> = {\n miss: (): Promise<void> => Promise.resolve(),\n },\n ): Promise<TValue> {\n const keyAsString = JSON.stringify(key);\n\n if (keyAsString in cache) {\n return Promise.resolve(options.serializable ? JSON.parse(cache[keyAsString]) : cache[keyAsString]);\n }\n\n const promise = defaultValue();\n\n return promise.then((value: TValue) => events.miss(value)).then(() => promise);\n },\n\n set<TValue>(key: Record<string, any> | string, value: TValue): Promise<TValue> {\n cache[JSON.stringify(key)] = options.serializable ? JSON.stringify(value) : value;\n\n return Promise.resolve(value);\n },\n\n delete(key: Record<string, unknown> | string): Promise<void> {\n delete cache[JSON.stringify(key)];\n\n return Promise.resolve();\n },\n\n clear(): Promise<void> {\n cache = {};\n\n return Promise.resolve();\n },\n };\n}\n","import type { Host, StatefulHost } from '../types';\n\n// By default, API Clients at Algolia have expiration delay of 5 mins.\n// In the JavaScript client, we have 2 mins.\nconst EXPIRATION_DELAY = 2 * 60 * 1000;\n\nexport function createStatefulHost(host: Host, status: StatefulHost['status'] = 'up'): StatefulHost {\n const lastUpdate = Date.now();\n\n function isUp(): boolean {\n return status === 'up' || Date.now() - lastUpdate > EXPIRATION_DELAY;\n }\n\n function isTimedOut(): boolean {\n return status === 'timed out' && Date.now() - lastUpdate <= EXPIRATION_DELAY;\n }\n\n return { ...host, status, lastUpdate, isUp, isTimedOut };\n}\n","import type { Response, StackFrame } from '../types';\n\nexport class AlgoliaError extends Error {\n name: string = 'AlgoliaError';\n\n constructor(message: string, name: string) {\n super(message);\n\n if (name) {\n this.name = name;\n }\n }\n}\n\nexport class ErrorWithStackTrace extends AlgoliaError {\n stackTrace: StackFrame[];\n\n constructor(message: string, stackTrace: StackFrame[], name: string) {\n super(message, name);\n // the array and object should be frozen to reflect the stackTrace at the time of the error\n this.stackTrace = stackTrace;\n }\n}\n\nexport class RetryError extends ErrorWithStackTrace {\n constructor(stackTrace: StackFrame[]) {\n super(\n 'Unreachable hosts - your application id may be incorrect. If the error persists, please reach out to the Algolia Support team: https://alg.li/support.',\n stackTrace,\n 'RetryError',\n );\n }\n}\n\nexport class ApiError extends ErrorWithStackTrace {\n status: number;\n\n constructor(message: string, status: number, stackTrace: StackFrame[], name = 'ApiError') {\n super(message, stackTrace, name);\n this.status = status;\n }\n}\n\nexport class DeserializationError extends AlgoliaError {\n response: Response;\n\n constructor(message: string, response: Response) {\n super(message, 'DeserializationError');\n this.response = response;\n }\n}\n\nexport type DetailedErrorWithMessage = {\n message: string;\n label: string;\n};\n\nexport type DetailedErrorWithTypeID = {\n id: string;\n type: string;\n name?: string;\n};\n\nexport type DetailedError = {\n code: string;\n details?: DetailedErrorWithMessage[] | DetailedErrorWithTypeID[];\n};\n\n// DetailedApiError is only used by the ingestion client to return more informative error, other clients will use ApiClient.\nexport class DetailedApiError extends ApiError {\n error: DetailedError;\n\n constructor(message: string, status: number, error: DetailedError, stackTrace: StackFrame[]) {\n super(message, status, stackTrace, 'DetailedApiError');\n this.error = error;\n }\n}\n","import type { Headers, Host, QueryParameters, Request, RequestOptions, Response, StackFrame } from '../types';\n\nimport { ApiError, DeserializationError, DetailedApiError } from './errors';\n\nexport function shuffle<TData>(array: TData[]): TData[] {\n const shuffledArray = array;\n\n for (let c = array.length - 1; c > 0; c--) {\n const b = Math.floor(Math.random() * (c + 1));\n const a = array[c];\n\n shuffledArray[c] = array[b];\n shuffledArray[b] = a;\n }\n\n return shuffledArray;\n}\n\nexport function serializeUrl(host: Host, path: string, queryParameters: QueryParameters): string {\n const queryParametersAsString = serializeQueryParameters(queryParameters);\n let url = `${host.protocol}://${host.url}${host.port ? `:${host.port}` : ''}/${\n path.charAt(0) === '/' ? path.substring(1) : path\n }`;\n\n if (queryParametersAsString.length) {\n url += `?${queryParametersAsString}`;\n }\n\n return url;\n}\n\nexport function serializeQueryParameters(parameters: QueryParameters): string {\n return Object.keys(parameters)\n .filter((key) => parameters[key] !== undefined)\n .sort()\n .map(\n (key) =>\n `${key}=${encodeURIComponent(\n Object.prototype.toString.call(parameters[key]) === '[object Array]'\n ? parameters[key].join(',')\n : parameters[key],\n ).replaceAll('+', '%20')}`,\n )\n .join('&');\n}\n\nexport function serializeData(request: Request, requestOptions: RequestOptions): string | undefined {\n if (request.method === 'GET' || (request.data === undefined && requestOptions.data === undefined)) {\n return undefined;\n }\n\n const data = Array.isArray(request.data) ? request.data : { ...request.data, ...requestOptions.data };\n\n return JSON.stringify(data);\n}\n\nexport function serializeHeaders(\n baseHeaders: Headers,\n requestHeaders: Headers,\n requestOptionsHeaders?: Headers,\n): Headers {\n const headers: Headers = {\n Accept: 'application/json',\n ...baseHeaders,\n ...requestHeaders,\n ...requestOptionsHeaders,\n };\n const serializedHeaders: Headers = {};\n\n Object.keys(headers).forEach((header) => {\n const value = headers[header];\n serializedHeaders[header.toLowerCase()] = value;\n });\n\n return serializedHeaders;\n}\n\nexport function deserializeSuccess<TObject>(response: Response): TObject {\n try {\n return JSON.parse(response.content);\n } catch (e) {\n throw new DeserializationError((e as Error).message, response);\n }\n}\n\nexport function deserializeFailure({ content, status }: Response, stackFrame: StackFrame[]): Error {\n try {\n const parsed = JSON.parse(content);\n if ('error' in parsed) {\n return new DetailedApiError(parsed.message, status, parsed.error, stackFrame);\n }\n return new ApiError(parsed.message, status, stackFrame);\n } catch {\n // ..\n }\n return new ApiError(content, status, stackFrame);\n}\n","import type { Response } from '../types';\n\nexport function isNetworkError({ isTimedOut, status }: Omit<Response, 'content'>): boolean {\n return !isTimedOut && ~~status === 0;\n}\n\nexport function isRetryable({ isTimedOut, status }: Omit<Response, 'content'>): boolean {\n return isTimedOut || isNetworkError({ isTimedOut, status }) || (~~(status / 100) !== 2 && ~~(status / 100) !== 4);\n}\n\nexport function isSuccess({ status }: Pick<Response, 'status'>): boolean {\n return ~~(status / 100) === 2;\n}\n","import type { Headers, StackFrame } from '../types';\n\nexport function stackTraceWithoutCredentials(stackTrace: StackFrame[]): StackFrame[] {\n return stackTrace.map((stackFrame) => stackFrameWithoutCredentials(stackFrame));\n}\n\nexport function stackFrameWithoutCredentials(stackFrame: StackFrame): StackFrame {\n const modifiedHeaders: Headers = stackFrame.request.headers['x-algolia-api-key']\n ? { 'x-algolia-api-key': '*****' }\n : {};\n\n return {\n ...stackFrame,\n request: {\n ...stackFrame.request,\n headers: {\n ...stackFrame.request.headers,\n ...modifiedHeaders,\n },\n },\n };\n}\n","import type {\n EndRequest,\n Host,\n Request,\n RequestOptions,\n Response,\n StackFrame,\n TransporterOptions,\n Transporter,\n QueryParameters,\n} from '../types';\n\nimport { createStatefulHost } from './createStatefulHost';\nimport { RetryError } from './errors';\nimport { deserializeFailure, deserializeSuccess, serializeData, serializeHeaders, serializeUrl } from './helpers';\nimport { isRetryable, isSuccess } from './responses';\nimport { stackTraceWithoutCredentials, stackFrameWithoutCredentials } from './stackTrace';\n\ntype RetryableOptions = {\n hosts: Host[];\n getTimeout: (retryCount: number, timeout: number) => number;\n};\n\nexport function createTransporter({\n hosts,\n hostsCache,\n baseHeaders,\n baseQueryParameters,\n algoliaAgent,\n timeouts,\n requester,\n requestsCache,\n responsesCache,\n}: TransporterOptions): Transporter {\n async function createRetryableOptions(compatibleHosts: Host[]): Promise<RetryableOptions> {\n const statefulHosts = await Promise.all(\n compatibleHosts.map((compatibleHost) => {\n return hostsCache.get(compatibleHost, () => {\n return Promise.resolve(createStatefulHost(compatibleHost));\n });\n }),\n );\n const hostsUp = statefulHosts.filter((host) => host.isUp());\n const hostsTimedOut = statefulHosts.filter((host) => host.isTimedOut());\n\n // Note, we put the hosts that previously timed out on the end of the list.\n const hostsAvailable = [...hostsUp, ...hostsTimedOut];\n const compatibleHostsAvailable = hostsAvailable.length > 0 ? hostsAvailable : compatibleHosts;\n\n return {\n hosts: compatibleHostsAvailable,\n getTimeout(timeoutsCount: number, baseTimeout: number): number {\n /**\n * Imagine that you have 4 hosts, if timeouts will increase\n * on the following way: 1 (timed out) > 4 (timed out) > 5 (200).\n *\n * Note that, the very next request, we start from the previous timeout.\n *\n * 5 (timed out) > 6 (timed out) > 7 ...\n *\n * This strategy may need to be reviewed, but is the strategy on the our\n * current v3 version.\n */\n const timeoutMultiplier =\n hostsTimedOut.length === 0 && timeoutsCount === 0 ? 1 : hostsTimedOut.length + 3 + timeoutsCount;\n\n return timeoutMultiplier * baseTimeout;\n },\n };\n }\n\n async function retryableRequest<TResponse>(\n request: Request,\n requestOptions: RequestOptions,\n isRead = true,\n ): Promise<TResponse> {\n const stackTrace: StackFrame[] = [];\n\n /**\n * First we prepare the payload that do not depend from hosts.\n */\n const data = serializeData(request, requestOptions);\n const headers = serializeHeaders(baseHeaders, request.headers, requestOptions.headers);\n\n // On `GET`, the data is proxied to query parameters.\n const dataQueryParameters: QueryParameters =\n request.method === 'GET'\n ? {\n ...request.data,\n ...requestOptions.data,\n }\n : {};\n\n const queryParameters: QueryParameters = {\n ...baseQueryParameters,\n ...request.queryParameters,\n ...dataQueryParameters,\n };\n\n if (algoliaAgent.value) {\n queryParameters['x-algolia-agent'] = algoliaAgent.value;\n }\n\n if (requestOptions && requestOptions.queryParameters) {\n for (const key of Object.keys(requestOptions.queryParameters)) {\n // We want to keep `undefined` and `null` values,\n // but also avoid stringifying `object`s, as they are\n // handled in the `serializeUrl` step right after.\n if (\n !requestOptions.queryParameters[key] ||\n Object.prototype.toString.call(requestOptions.queryParameters[key]) === '[object Object]'\n ) {\n queryParameters[key] = requestOptions.queryParameters[key];\n } else {\n queryParameters[key] = requestOptions.queryParameters[key].toString();\n }\n }\n }\n\n let timeoutsCount = 0;\n\n const retry = async (\n retryableHosts: Host[],\n getTimeout: (timeoutsCount: number, timeout: number) => number,\n ): Promise<TResponse> => {\n /**\n * We iterate on each host, until there is no host left.\n */\n const host = retryableHosts.pop();\n if (host === undefined) {\n throw new RetryError(stackTraceWithoutCredentials(stackTrace));\n }\n\n const timeout = { ...timeouts, ...requestOptions.timeouts };\n\n const payload: EndRequest = {\n data,\n headers,\n method: request.method,\n url: serializeUrl(host, request.path, queryParameters),\n connectTimeout: getTimeout(timeoutsCount, timeout.connect),\n responseTimeout: getTimeout(timeoutsCount, isRead ? timeout.read : timeout.write),\n };\n\n /**\n * The stackFrame is pushed to the stackTrace so we\n * can have information about onRetry and onFailure\n * decisions.\n */\n const pushToStackTrace = (response: Response): StackFrame => {\n const stackFrame: StackFrame = {\n request: payload,\n response,\n host,\n triesLeft: retryableHosts.length,\n };\n\n stackTrace.push(stackFrame);\n\n return stackFrame;\n };\n\n const response = await requester.send(payload);\n\n if (isRetryable(response)) {\n const stackFrame = pushToStackTrace(response);\n\n // If response is a timeout, we increase the number of timeouts so we can increase the timeout later.\n if (response.isTimedOut) {\n timeoutsCount++;\n }\n /**\n * Failures are individually sent to the logger, allowing\n * the end user to debug / store stack frames even\n * when a retry error does not happen.\n */\n // eslint-disable-next-line no-console -- this will be fixed by exposing a `logger` to the transporter\n console.log('Retryable failure', stackFrameWithoutCredentials(stackFrame));\n\n /**\n * We also store the state of the host in failure cases. If the host, is\n * down it will remain down for the next 2 minutes. In a timeout situation,\n * this host will be added end of the list of hosts on the next request.\n */\n await hostsCache.set(host, createStatefulHost(host, response.isTimedOut ? 'timed out' : 'down'));\n\n return retry(retryableHosts, getTimeout);\n }\n\n if (isSuccess(response)) {\n return deserializeSuccess(response);\n }\n\n pushToStackTrace(response);\n throw deserializeFailure(response, stackTrace);\n };\n\n /**\n * Finally, for each retryable host perform request until we got a non\n * retryable response. Some notes here:\n *\n * 1. The reverse here is applied so we can apply a `pop` later on => more performant.\n * 2. We also get from the retryable options a timeout multiplier that is tailored\n * for the current context.\n */\n const compatibleHosts = hosts.filter(\n (host) => host.accept === 'readWrite' || (isRead ? host.accept === 'read' : host.accept === 'write'),\n );\n const options = await createRetryableOptions(compatibleHosts);\n\n return retry([...options.hosts].reverse(), options.getTimeout);\n }\n\n function createRequest<TResponse>(request: Request, requestOptions: RequestOptions = {}): Promise<TResponse> {\n /**\n * A read request is either a `GET` request, or a request that we make\n * via the `read` transporter (e.g. `search`).\n */\n const isRead = request.useReadTransporter || request.method === 'GET';\n if (!isRead) {\n /**\n * On write requests, no cache mechanisms are applied, and we\n * proxy the request immediately to the requester.\n */\n return retryableRequest<TResponse>(request, requestOptions, isRead);\n }\n\n const createRetryableRequest = (): Promise<TResponse> => {\n /**\n * Then, we prepare a function factory that contains the construction of\n * the retryable request. At this point, we may *not* perform the actual\n * request. But we want to have the function factory ready.\n */\n return retryableRequest<TResponse>(request, requestOptions);\n };\n\n /**\n * Once we have the function factory ready, we need to determine of the\n * request is \"cacheable\" - should be cached. Note that, once again,\n * the user can force this option.\n */\n const cacheable = requestOptions.cacheable || request.cacheable;\n\n /**\n * If is not \"cacheable\", we immediately trigger the retryable request, no\n * need to check cache implementations.\n */\n if (cacheable !== true) {\n return createRetryableRequest();\n }\n\n /**\n * If the request is \"cacheable\", we need to first compute the key to ask\n * the cache implementations if this request is on progress or if the\n * response already exists on the cache.\n */\n const key = {\n request,\n requestOptions,\n transporter: {\n queryParameters: baseQueryParameters,\n headers: baseHeaders,\n },\n };\n\n /**\n * With the computed key, we first ask the responses cache\n * implementation if this request was been resolved before.\n */\n return responsesCache.get(\n key,\n () => {\n /**\n * If the request has never resolved before, we actually ask if there\n * is a current request with the same key on progress.\n */\n return requestsCache.get(key, () =>\n /**\n * Finally, if there is no request in progress with the same key,\n * this `createRetryableRequest()` will actually trigger the\n * retryable request.\n */\n requestsCache\n .set(key, createRetryableRequest())\n .then(\n (response) => Promise.all([requestsCache.delete(key), response]),\n (err) => Promise.all([requestsCache.delete(key), Promise.reject(err)]),\n )\n .then(([_, response]) => response),\n );\n },\n {\n /**\n * Of course, once we get this response back from the server, we\n * tell response cache to actually store the received response\n * to be used later.\n */\n miss: (response) => responsesCache.set(key, response),\n },\n );\n }\n\n return {\n hostsCache,\n requester,\n timeouts,\n algoliaAgent,\n baseHeaders,\n baseQueryParameters,\n hosts,\n request: createRequest,\n requestsCache,\n responsesCache,\n };\n}\n","import type { AlgoliaAgentOptions, AlgoliaAgent } from './types';\n\nexport function createAlgoliaAgent(version: string): AlgoliaAgent {\n const algoliaAgent = {\n value: `Algolia for JavaScript (${version})`,\n add(options: AlgoliaAgentOptions): AlgoliaAgent {\n const addedAlgoliaAgent = `; ${options.segment}${options.version !== undefined ? ` (${options.version})` : ''}`;\n\n if (algoliaAgent.value.indexOf(addedAlgoliaAgent) === -1) {\n algoliaAgent.value = `${algoliaAgent.value}${addedAlgoliaAgent}`;\n }\n\n return algoliaAgent;\n },\n };\n\n return algoliaAgent;\n}\n","import { createAlgoliaAgent } from './createAlgoliaAgent';\nimport type { AlgoliaAgentOptions, AlgoliaAgent } from './types';\n\nexport type GetAlgoliaAgent = {\n algoliaAgents: AlgoliaAgentOptions[];\n client: string;\n version: string;\n};\n\nexport function getAlgoliaAgent({ algoliaAgents, client, version }: GetAlgoliaAgent): AlgoliaAgent {\n const defaultAlgoliaAgent = createAlgoliaAgent(version).add({\n segment: client,\n version,\n });\n\n algoliaAgents.forEach((algoliaAgent) => defaultAlgoliaAgent.add(algoliaAgent));\n\n return defaultAlgoliaAgent;\n}\n","export const DEFAULT_CONNECT_TIMEOUT_BROWSER = 1000;\nexport const DEFAULT_READ_TIMEOUT_BROWSER = 2000;\nexport const DEFAULT_WRITE_TIMEOUT_BROWSER = 30000;\n\nexport const DEFAULT_CONNECT_TIMEOUT_NODE = 2000;\nexport const DEFAULT_READ_TIMEOUT_NODE = 5000;\nexport const DEFAULT_WRITE_TIMEOUT_NODE = 30000;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEO,SAAS,WACd,OACA,QACA,WAAqB,iBAIrB;AACA,QAAM,cAAc;AAAA,IAClB,qBAAqB;AAAA,IACrB,4BAA4B;AAAA,EAC9B;AAEA,SAAO;AAAA,IACL,UAAmB;AACjB,aAAO,aAAa,kBAAkB,cAAc,C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QAAQ,iBAAiB,MAAM,IAAI;AACxD,qBAAa,QAAQ,GAAG,aAAa,KAAK,GAAG,iBAAiB;AAAA,MAChE;AAEA,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT;;;ACRO,SAAS,gBAAgB,EAAE,eAAe,QAAQ,QAAQ,GAAkC;AACjG,QAAM,sBAAsB,mBAAmB,OAAO,EAAE,IAAI;AAAA,IAC1D,SAAS;AAAA,IACT;AAAA,EACF,CAAC;AAED,gBAAc,QAAQ,CAAC,iBAAiB,oBAAoB,IAAI,YAAY,CAAC;AAE7E,SAAO;AACT;;;AClBO,IAAM,kCAAkC;AACxC,IAAM,+BAA+B;AACrC,IAAM,gCAAgC;AAEtC,IAAM,+BAA+B;AACrC,IAAM,4BAA4B;AAClC,IAAM,6BAA6B;","names":["response"]}
@@ -0,0 +1,438 @@
1
+ type Cache = {
2
+ /**
3
+ * Gets the value of the given `key`.
4
+ */
5
+ get: <TValue>(key: Record<string, any> | string, defaultValue: () => Promise<TValue>, events?: CacheEvents<TValue>) => Promise<TValue>;
6
+ /**
7
+ * Sets the given value with the given `key`.
8
+ */
9
+ set: <TValue>(key: Record<string, any> | string, value: TValue) => Promise<TValue>;
10
+ /**
11
+ * Deletes the given `key`.
12
+ */
13
+ delete: (key: Record<string, any> | string) => Promise<void>;
14
+ /**
15
+ * Clears the cache.
16
+ */
17
+ clear: () => Promise<void>;
18
+ };
19
+ type CacheEvents<TValue> = {
20
+ /**
21
+ * The callback when the given `key` is missing from the cache.
22
+ */
23
+ miss: (value: TValue) => Promise<any>;
24
+ };
25
+ type MemoryCacheOptions = {
26
+ /**
27
+ * If keys and values should be serialized using `JSON.stringify`.
28
+ */
29
+ serializable?: boolean;
30
+ };
31
+ type BrowserLocalStorageOptions = {
32
+ /**
33
+ * The cache key.
34
+ */
35
+ key: string;
36
+ /**
37
+ * The time to live for each cached item in seconds.
38
+ */
39
+ timeToLive?: number;
40
+ /**
41
+ * The native local storage implementation.
42
+ */
43
+ localStorage?: Storage;
44
+ };
45
+ type BrowserLocalStorageCacheItem = {
46
+ /**
47
+ * The cache item creation timestamp.
48
+ */
49
+ timestamp: number;
50
+ /**
51
+ * The cache item value.
52
+ */
53
+ value: any;
54
+ };
55
+ type FallbackableCacheOptions = {
56
+ /**
57
+ * List of caches order by priority.
58
+ */
59
+ caches: Cache[];
60
+ };
61
+
62
+ type Host = {
63
+ /**
64
+ * The host URL.
65
+ */
66
+ url: string;
67
+ /**
68
+ * The accepted transporter.
69
+ */
70
+ accept: 'read' | 'readWrite' | 'write';
71
+ /**
72
+ * The protocol of the host URL.
73
+ */
74
+ protocol: 'http' | 'https';
75
+ /**
76
+ * The port of the host URL.
77
+ */
78
+ port?: number;
79
+ };
80
+ type StatefulHost = Host & {
81
+ /**
82
+ * The status of the host.
83
+ */
84
+ status: 'down' | 'timed out' | 'up';
85
+ /**
86
+ * The last update of the host status, used to compare with the expiration delay.
87
+ */
88
+ lastUpdate: number;
89
+ /**
90
+ * Returns whether the host is up or not.
91
+ */
92
+ isUp: () => boolean;
93
+ /**
94
+ * Returns whether the host is timed out or not.
95
+ */
96
+ isTimedOut: () => boolean;
97
+ };
98
+
99
+ /**
100
+ * The method of the request.
101
+ */
102
+ type Method = 'DELETE' | 'GET' | 'PATCH' | 'POST' | 'PUT';
103
+ type Request = {
104
+ method: Method;
105
+ /**
106
+ * The path of the REST API to send the request to.
107
+ */
108
+ path: string;
109
+ queryParameters: QueryParameters;
110
+ data?: Array<Record<string, any>> | Record<string, any>;
111
+ headers: Headers;
112
+ /**
113
+ * If the given request should persist on the cache. Keep in mind,
114
+ * that some methods may have this option enabled by default.
115
+ */
116
+ cacheable?: boolean;
117
+ /**
118
+ * Some POST methods in the Algolia REST API uses the `read` transporter.
119
+ * This information is defined at the spec level.
120
+ */
121
+ useReadTransporter?: boolean;
122
+ };
123
+ type EndRequest = Pick<Request, 'headers' | 'method'> & {
124
+ /**
125
+ * The full URL of the REST API.
126
+ */
127
+ url: string;
128
+ /**
129
+ * The connection timeout, in milliseconds.
130
+ */
131
+ connectTimeout: number;
132
+ /**
133
+ * The response timeout, in milliseconds.
134
+ */
135
+ responseTimeout: number;
136
+ data?: string;
137
+ };
138
+ type Response = {
139
+ /**
140
+ * The body of the response.
141
+ */
142
+ content: string;
143
+ /**
144
+ * Whether the API call is timed out or not.
145
+ */
146
+ isTimedOut: boolean;
147
+ /**
148
+ * The HTTP status code of the response.
149
+ */
150
+ status: number;
151
+ };
152
+ type Requester = {
153
+ /**
154
+ * Sends the given `request` to the server.
155
+ */
156
+ send: (request: EndRequest) => Promise<Response>;
157
+ };
158
+ type EchoResponse = Omit<EndRequest, 'data'> & Pick<Request, 'data' | 'path'> & {
159
+ host: string;
160
+ algoliaAgent: string;
161
+ searchParams?: Record<string, string>;
162
+ };
163
+
164
+ type Headers = Record<string, string>;
165
+ type QueryParameters = Record<string, any>;
166
+ type RequestOptions = Pick<Request, 'cacheable'> & {
167
+ /**
168
+ * Custom timeout for the request. Note that, in normal situations
169
+ * the given timeout will be applied. But the transporter layer may
170
+ * increase this timeout if there is need for it.
171
+ */
172
+ timeouts?: Partial<Timeouts>;
173
+ /**
174
+ * Custom headers for the request. This headers are
175
+ * going to be merged the transporter headers.
176
+ */
177
+ headers?: Headers;
178
+ /**
179
+ * Custom query parameters for the request. This query parameters are
180
+ * going to be merged the transporter query parameters.
181
+ */
182
+ queryParameters?: QueryParameters;
183
+ /**
184
+ * Custom data for the request. This data is
185
+ * going to be merged the transporter data.
186
+ */
187
+ data?: Array<Record<string, any>> | Record<string, any>;
188
+ };
189
+ type StackFrame = {
190
+ request: EndRequest;
191
+ response: Response;
192
+ host: Host;
193
+ triesLeft: number;
194
+ };
195
+ type AlgoliaAgentOptions = {
196
+ /**
197
+ * The segment. Usually the integration name.
198
+ */
199
+ segment: string;
200
+ /**
201
+ * The version. Usually the integration version.
202
+ */
203
+ version?: string;
204
+ };
205
+ type AlgoliaAgent = {
206
+ /**
207
+ * The raw value of the user agent.
208
+ */
209
+ value: string;
210
+ /**
211
+ * Mutates the current user agent adding the given user agent options.
212
+ */
213
+ add: (options: AlgoliaAgentOptions) => AlgoliaAgent;
214
+ };
215
+ type Timeouts = {
216
+ /**
217
+ * Timeout in milliseconds before the connection is established.
218
+ */
219
+ connect: number;
220
+ /**
221
+ * Timeout in milliseconds before reading the response on a read request.
222
+ */
223
+ read: number;
224
+ /**
225
+ * Timeout in milliseconds before reading the response on a write request.
226
+ */
227
+ write: number;
228
+ };
229
+ type TransporterOptions = {
230
+ /**
231
+ * The cache of the hosts. Usually used to persist
232
+ * the state of the host when its down.
233
+ */
234
+ hostsCache: Cache;
235
+ /**
236
+ * The underlying requester used. Should differ
237
+ * depending of the environment where the client
238
+ * will be used.
239
+ */
240
+ requester: Requester;
241
+ /**
242
+ * The cache of the requests. When requests are
243
+ * `cacheable`, the returned promised persists
244
+ * in this cache to shared in similar requests
245
+ * before being resolved.
246
+ */
247
+ requestsCache: Cache;
248
+ /**
249
+ * The cache of the responses. When requests are
250
+ * `cacheable`, the returned responses persists
251
+ * in this cache to shared in similar requests.
252
+ */
253
+ responsesCache: Cache;
254
+ /**
255
+ * The timeouts used by the requester. The transporter
256
+ * layer may increase this timeouts as defined on the
257
+ * retry strategy.
258
+ */
259
+ timeouts: Timeouts;
260
+ /**
261
+ * The hosts used by the requester.
262
+ */
263
+ hosts: Host[];
264
+ /**
265
+ * The headers used by the requester. The transporter
266
+ * layer may add some extra headers during the request
267
+ * for the user agent, and others.
268
+ */
269
+ baseHeaders: Headers;
270
+ /**
271
+ * The query parameters used by the requester. The transporter
272
+ * layer may add some extra headers during the request
273
+ * for the user agent, and others.
274
+ */
275
+ baseQueryParameters: QueryParameters;
276
+ /**
277
+ * The user agent used. Sent on query parameters.
278
+ */
279
+ algoliaAgent: AlgoliaAgent;
280
+ };
281
+ type Transporter = TransporterOptions & {
282
+ /**
283
+ * Performs a request.
284
+ * The `baseRequest` and `baseRequestOptions` will be merged accordingly.
285
+ */
286
+ request: <TResponse>(baseRequest: Request, baseRequestOptions?: RequestOptions) => Promise<TResponse>;
287
+ };
288
+
289
+ type AuthMode = 'WithinHeaders' | 'WithinQueryParameters';
290
+ type OverriddenTransporterOptions = 'baseHeaders' | 'baseQueryParameters' | 'hosts';
291
+ type CreateClientOptions = Omit<TransporterOptions, OverriddenTransporterOptions | 'algoliaAgent'> & Partial<Pick<TransporterOptions, OverriddenTransporterOptions>> & {
292
+ appId: string;
293
+ apiKey: string;
294
+ authMode?: AuthMode;
295
+ algoliaAgents: AlgoliaAgentOptions[];
296
+ };
297
+ type ClientOptions = Partial<Omit<CreateClientOptions, 'apiKey' | 'appId'>>;
298
+
299
+ type IterableOptions<TResponse> = Partial<{
300
+ /**
301
+ * The function that runs right after the API call has been resolved, allows you to do anything with the response before `validate`.
302
+ */
303
+ aggregator: (response: TResponse) => void;
304
+ /**
305
+ * The `validate` condition to throw an error and its message.
306
+ */
307
+ error: {
308
+ /**
309
+ * The function to validate the error condition.
310
+ */
311
+ validate: (response: TResponse) => boolean;
312
+ /**
313
+ * The error message to throw.
314
+ */
315
+ message: (response: TResponse) => string;
316
+ };
317
+ /**
318
+ * The function to decide how long to wait between iterations.
319
+ */
320
+ timeout: () => number;
321
+ }>;
322
+ type CreateIterablePromise<TResponse> = IterableOptions<TResponse> & {
323
+ /**
324
+ * The function to run, which returns a promise.
325
+ *
326
+ * The `previousResponse` parameter (`undefined` on the first call) allows you to build your request with incremental logic, to iterate on `page` or `cursor` for example.
327
+ */
328
+ func: (previousResponse?: TResponse) => Promise<TResponse>;
329
+ /**
330
+ * The validator function. It receive the resolved return of the API call.
331
+ */
332
+ validate: (response: TResponse) => boolean;
333
+ };
334
+
335
+ declare function createAuth(appId: string, apiKey: string, authMode?: AuthMode): {
336
+ readonly headers: () => Headers;
337
+ readonly queryParameters: () => QueryParameters;
338
+ };
339
+
340
+ type EchoRequesterParams = {
341
+ getURL: (url: string) => URL;
342
+ status?: number;
343
+ };
344
+ declare function createEchoRequester({ getURL, status }: EchoRequesterParams): Requester;
345
+
346
+ /**
347
+ * Helper: Returns the promise of a given `func` to iterate on, based on a given `validate` condition.
348
+ *
349
+ * @param createIterator - The createIterator options.
350
+ * @param createIterator.func - The function to run, which returns a promise.
351
+ * @param createIterator.validate - The validator function. It receives the resolved return of `func`.
352
+ * @param createIterator.aggregator - The function that runs right after the `func` method has been executed, allows you to do anything with the response before `validate`.
353
+ * @param createIterator.error - The `validate` condition to throw an error, and its message.
354
+ * @param createIterator.timeout - The function to decide how long to wait between iterations.
355
+ */
356
+ declare function createIterablePromise<TResponse>({ func, validate, aggregator, error, timeout, }: CreateIterablePromise<TResponse>): Promise<TResponse>;
357
+
358
+ declare function createBrowserLocalStorageCache(options: BrowserLocalStorageOptions): Cache;
359
+
360
+ declare function createFallbackableCache(options: FallbackableCacheOptions): Cache;
361
+
362
+ declare function createMemoryCache(options?: MemoryCacheOptions): Cache;
363
+
364
+ declare function createNullCache(): Cache;
365
+
366
+ declare function createTransporter({ hosts, hostsCache, baseHeaders, baseQueryParameters, algoliaAgent, timeouts, requester, requestsCache, responsesCache, }: TransporterOptions): Transporter;
367
+
368
+ declare function createStatefulHost(host: Host, status?: StatefulHost['status']): StatefulHost;
369
+
370
+ declare class AlgoliaError extends Error {
371
+ name: string;
372
+ constructor(message: string, name: string);
373
+ }
374
+ declare class ErrorWithStackTrace extends AlgoliaError {
375
+ stackTrace: StackFrame[];
376
+ constructor(message: string, stackTrace: StackFrame[], name: string);
377
+ }
378
+ declare class RetryError extends ErrorWithStackTrace {
379
+ constructor(stackTrace: StackFrame[]);
380
+ }
381
+ declare class ApiError extends ErrorWithStackTrace {
382
+ status: number;
383
+ constructor(message: string, status: number, stackTrace: StackFrame[], name?: string);
384
+ }
385
+ declare class DeserializationError extends AlgoliaError {
386
+ response: Response;
387
+ constructor(message: string, response: Response);
388
+ }
389
+ type DetailedErrorWithMessage = {
390
+ message: string;
391
+ label: string;
392
+ };
393
+ type DetailedErrorWithTypeID = {
394
+ id: string;
395
+ type: string;
396
+ name?: string;
397
+ };
398
+ type DetailedError = {
399
+ code: string;
400
+ details?: DetailedErrorWithMessage[] | DetailedErrorWithTypeID[];
401
+ };
402
+ declare class DetailedApiError extends ApiError {
403
+ error: DetailedError;
404
+ constructor(message: string, status: number, error: DetailedError, stackTrace: StackFrame[]);
405
+ }
406
+
407
+ declare function shuffle<TData>(array: TData[]): TData[];
408
+ declare function serializeUrl(host: Host, path: string, queryParameters: QueryParameters): string;
409
+ declare function serializeQueryParameters(parameters: QueryParameters): string;
410
+ declare function serializeData(request: Request, requestOptions: RequestOptions): string | undefined;
411
+ declare function serializeHeaders(baseHeaders: Headers, requestHeaders: Headers, requestOptionsHeaders?: Headers): Headers;
412
+ declare function deserializeSuccess<TObject>(response: Response): TObject;
413
+ declare function deserializeFailure({ content, status }: Response, stackFrame: StackFrame[]): Error;
414
+
415
+ declare function isNetworkError({ isTimedOut, status }: Omit<Response, 'content'>): boolean;
416
+ declare function isRetryable({ isTimedOut, status }: Omit<Response, 'content'>): boolean;
417
+ declare function isSuccess({ status }: Pick<Response, 'status'>): boolean;
418
+
419
+ declare function stackTraceWithoutCredentials(stackTrace: StackFrame[]): StackFrame[];
420
+ declare function stackFrameWithoutCredentials(stackFrame: StackFrame): StackFrame;
421
+
422
+ declare function createAlgoliaAgent(version: string): AlgoliaAgent;
423
+
424
+ type GetAlgoliaAgent = {
425
+ algoliaAgents: AlgoliaAgentOptions[];
426
+ client: string;
427
+ version: string;
428
+ };
429
+ declare function getAlgoliaAgent({ algoliaAgents, client, version }: GetAlgoliaAgent): AlgoliaAgent;
430
+
431
+ declare const DEFAULT_CONNECT_TIMEOUT_BROWSER = 1000;
432
+ declare const DEFAULT_READ_TIMEOUT_BROWSER = 2000;
433
+ declare const DEFAULT_WRITE_TIMEOUT_BROWSER = 30000;
434
+ declare const DEFAULT_CONNECT_TIMEOUT_NODE = 2000;
435
+ declare const DEFAULT_READ_TIMEOUT_NODE = 5000;
436
+ declare const DEFAULT_WRITE_TIMEOUT_NODE = 30000;
437
+
438
+ export { type AlgoliaAgent, type AlgoliaAgentOptions, AlgoliaError, ApiError, type AuthMode, type BrowserLocalStorageCacheItem, type BrowserLocalStorageOptions, type Cache, type CacheEvents, type ClientOptions, type CreateClientOptions, type CreateIterablePromise, DEFAULT_CONNECT_TIMEOUT_BROWSER, DEFAULT_CONNECT_TIMEOUT_NODE, DEFAULT_READ_TIMEOUT_BROWSER, DEFAULT_READ_TIMEOUT_NODE, DEFAULT_WRITE_TIMEOUT_BROWSER, DEFAULT_WRITE_TIMEOUT_NODE, DeserializationError, DetailedApiError, type DetailedError, type DetailedErrorWithMessage, type DetailedErrorWithTypeID, type EchoRequesterParams, type EchoResponse, type EndRequest, ErrorWithStackTrace, type FallbackableCacheOptions, type GetAlgoliaAgent, type Headers, type Host, type IterableOptions, type MemoryCacheOptions, type Method, type QueryParameters, type Request, type RequestOptions, type Requester, type Response, RetryError, type StackFrame, type StatefulHost, type Timeouts, type Transporter, type TransporterOptions, createAlgoliaAgent, createAuth, createBrowserLocalStorageCache, createEchoRequester, createFallbackableCache, createIterablePromise, createMemoryCache, createNullCache, createStatefulHost, createTransporter, deserializeFailure, deserializeSuccess, getAlgoliaAgent, isNetworkError, isRetryable, isSuccess, serializeData, serializeHeaders, serializeQueryParameters, serializeUrl, shuffle, stackFrameWithoutCredentials, stackTraceWithoutCredentials };