@algolia/recommend 5.53.0 → 5.54.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/README.md +4 -4
- package/dist/browser.d.ts +1 -1
- package/dist/builds/browser.js +21 -59
- package/dist/builds/browser.js.map +1 -1
- package/dist/builds/browser.min.js +5 -1
- package/dist/builds/browser.min.js.map +1 -1
- package/dist/builds/browser.umd.js +7 -3
- package/dist/builds/fetch.js +21 -59
- package/dist/builds/fetch.js.map +1 -1
- package/dist/builds/node.cjs +20 -58
- package/dist/builds/node.cjs.map +1 -1
- package/dist/builds/node.js +21 -59
- package/dist/builds/node.js.map +1 -1
- package/dist/builds/worker.js +21 -59
- package/dist/builds/worker.js.map +1 -1
- package/dist/fetch.d.ts +1 -1
- package/dist/node.d.cts +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/src/recommendClient.cjs +20 -58
- package/dist/src/recommendClient.cjs.map +1 -1
- package/dist/src/recommendClient.js +21 -59
- package/dist/src/recommendClient.js.map +1 -1
- package/dist/worker.d.ts +1 -1
- package/package.json +6 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../client-common/src/cache/createBrowserLocalStorageCache.ts","../../../client-common/src/cache/createNullCache.ts","../../../client-common/src/cache/createFallbackableCache.ts","../../../client-common/src/cache/createMemoryCache.ts","../../../client-common/src/constants.ts","../../../client-common/src/createAlgoliaAgent.ts","../../../client-common/src/createAuth.ts","../../../client-common/src/createIterablePromise.ts","../../../client-common/src/getAlgoliaAgent.ts","../../../client-common/src/logger/createNullLogger.ts","../../../client-common/src/transporter/compress.ts","../../../client-common/src/transporter/createStatefulHost.ts","../../../client-common/src/transporter/errors.ts","../../../client-common/src/transporter/helpers.ts","../../../client-common/src/transporter/responses.ts","../../../client-common/src/transporter/stackTrace.ts","../../../client-common/src/transporter/createTransporter.ts","../../../client-common/src/types/logger.ts","../../../requester-browser-xhr/src/createXhrRequester.ts","../../src/recommendClient.ts","../../builds/browser.ts"],"sourcesContent":["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 yieldToMain(): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, 0));\n }\n\n function getFilteredNamespace(): {\n namespace: Record<string, BrowserLocalStorageCacheItem>;\n changed: boolean;\n } {\n const timeToLive = options.timeToLive ? options.timeToLive * 1000 : null;\n const namespace = getNamespace<BrowserLocalStorageCacheItem>();\n const currentTime = new Date().getTime();\n let changed = false;\n\n const filtered = Object.fromEntries(\n Object.entries(namespace).filter(([, cacheItem]) => {\n if (!cacheItem || cacheItem.timestamp === undefined) {\n changed = true;\n return false;\n }\n\n if (!timeToLive) {\n return true;\n }\n\n if (cacheItem.timestamp + timeToLive < currentTime) {\n changed = true;\n return false;\n }\n\n return true;\n }),\n );\n\n return { namespace: filtered, changed };\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 yieldToMain().then(() => {\n const { namespace, changed } = getFilteredNamespace();\n const cachedItem = namespace[JSON.stringify(key)];\n\n if (changed) {\n setNamespace(namespace);\n }\n\n if (cachedItem) {\n return cachedItem.value as TValue;\n }\n\n return defaultValue().then((value) => events.miss(value).then(() => value));\n });\n },\n\n set<TValue>(key: Record<string, any> | string, value: TValue): Promise<TValue> {\n return yieldToMain().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 yieldToMain().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 { Cache, CacheEvents, FallbackableCacheOptions } from '../types';\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","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","import type { AlgoliaAgent, AlgoliaAgentOptions } 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 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 { 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 | undefined): Promise<TResponse> => {\n return new Promise<TResponse>((resolve, reject) => {\n func(previousResponse)\n .then(async (response) => {\n if (aggregator) {\n await aggregator(response);\n }\n\n if (await validate(response)) {\n return resolve(response);\n }\n\n if (error && (await error.validate(response))) {\n return reject(new Error(await error.message(response)));\n }\n\n return setTimeout(\n () => {\n retry(response).then(resolve).catch(reject);\n },\n await timeout(),\n );\n })\n .catch((err) => {\n reject(err);\n });\n });\n };\n\n return retry();\n}\n","import { createAlgoliaAgent } from './createAlgoliaAgent';\nimport type { AlgoliaAgent, AlgoliaAgentOptions } 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","import type { Logger } from '../types/logger';\n\nexport function createNullLogger(): Logger {\n return {\n debug(_message: string, _args?: any | undefined): Promise<void> {\n return Promise.resolve();\n },\n info(_message: string, _args?: any | undefined): Promise<void> {\n return Promise.resolve();\n },\n error(_message: string, _args?: any | undefined): Promise<void> {\n return Promise.resolve();\n },\n };\n}\n","export const COMPRESSION_THRESHOLD = 750;\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 override 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 IndexNotFoundError extends AlgoliaError {\n constructor(indexName: string) {\n super(`${indexName} does not exist`, 'IndexNotFoundError');\n }\n}\n\nexport class IndicesInSameAppError extends AlgoliaError {\n constructor() {\n super('Indices are in the same application. Use operationIndex instead.', 'IndicesInSameAppError');\n }\n}\n\nexport class IndexAlreadyExistsError extends AlgoliaError {\n constructor(indexName: string) {\n super(`${indexName} index already exists.`, 'IndexAlreadyExistsError');\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 visit our help center https://alg.li/support-unreachable-hosts or 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 | undefined;\n};\n\nexport type DetailedError = {\n code: string;\n details?: DetailedErrorWithMessage[] | DetailedErrorWithTypeID[] | undefined;\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';\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 ).replace(/\\+/g, '%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 | undefined,\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 QueryParameters,\n Request,\n RequestOptions,\n Response,\n StackFrame,\n Transporter,\n TransporterOptions,\n} from '../types';\nimport { COMPRESSION_THRESHOLD } from './compress';\nimport { createStatefulHost } from './createStatefulHost';\nimport { RetryError } from './errors';\nimport { deserializeFailure, deserializeSuccess, serializeData, serializeHeaders, serializeUrl } from './helpers';\nimport { isRetryable, isSuccess } from './responses';\nimport { stackFrameWithoutCredentials, stackTraceWithoutCredentials } 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 logger,\n baseQueryParameters,\n algoliaAgent,\n timeouts,\n requester,\n requestsCache,\n responsesCache,\n compress,\n compression,\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: boolean,\n ): Promise<TResponse> {\n const stackTrace: StackFrame[] = [];\n\n /**\n * First we prepare the payload that do not depend from hosts.\n */\n const serializedData = serializeData(request, requestOptions);\n const headers = serializeHeaders(baseHeaders, request.headers, requestOptions.headers);\n\n const wantsCompression =\n compression === 'gzip' &&\n serializedData !== undefined &&\n serializedData.length > COMPRESSION_THRESHOLD &&\n (request.method === 'POST' || request.method === 'PUT');\n\n if (wantsCompression && compress === undefined) {\n logger.info('Compression is disabled because no compress method is available.');\n }\n\n const shouldCompress = wantsCompression && compress !== undefined;\n const data = shouldCompress ? await compress(serializedData) : serializedData;\n if (shouldCompress) {\n headers['content-encoding'] = 'gzip';\n }\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 logger.info('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 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, isRead);\n };\n\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\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 logger,\n algoliaAgent,\n baseHeaders,\n baseQueryParameters,\n hosts,\n request: createRequest,\n requestsCache,\n responsesCache,\n };\n}\n","export const LogLevelEnum: Readonly<Record<string, LogLevelType>> = {\n Debug: 1,\n Info: 2,\n Error: 3,\n};\n\nexport type LogLevelType = 1 | 2 | 3;\n\nexport type Logger = {\n /**\n * Logs debug messages.\n */\n debug: (message: string, args?: any | undefined) => Promise<void>;\n\n /**\n * Logs info messages.\n */\n info: (message: string, args?: any | undefined) => Promise<void>;\n\n /**\n * Logs error messages.\n */\n error: (message: string, args?: any | undefined) => Promise<void>;\n};\n","import type { EndRequest, Requester, Response } from '@algolia/client-common';\n\ntype Timeout = ReturnType<typeof setTimeout>;\n\nexport function createXhrRequester(): Requester {\n function send(request: EndRequest): Promise<Response> {\n return new Promise((resolve) => {\n const baseRequester = new XMLHttpRequest();\n baseRequester.open(request.method, request.url, true);\n\n Object.keys(request.headers).forEach((key) => baseRequester.setRequestHeader(key, request.headers[key]));\n\n const createTimeout = (timeout: number, content: string): Timeout => {\n return setTimeout(() => {\n baseRequester.abort();\n\n resolve({\n status: 0,\n content,\n isTimedOut: true,\n });\n }, timeout);\n };\n\n const connectTimeout = createTimeout(request.connectTimeout, 'Connection timeout');\n\n let responseTimeout: Timeout | undefined;\n\n baseRequester.onreadystatechange = (): void => {\n if (baseRequester.readyState > baseRequester.OPENED && responseTimeout === undefined) {\n clearTimeout(connectTimeout);\n\n responseTimeout = createTimeout(request.responseTimeout, 'Socket timeout');\n }\n };\n\n baseRequester.onerror = (): void => {\n // istanbul ignore next\n if (baseRequester.status === 0) {\n clearTimeout(connectTimeout);\n clearTimeout(responseTimeout!);\n\n resolve({\n content: baseRequester.responseText || 'Network request failed',\n status: baseRequester.status,\n isTimedOut: false,\n });\n }\n };\n\n baseRequester.onload = (): void => {\n clearTimeout(connectTimeout);\n clearTimeout(responseTimeout!);\n\n resolve({\n content: baseRequester.responseText,\n status: baseRequester.status,\n isTimedOut: false,\n });\n };\n\n baseRequester.send(request.data as XMLHttpRequestBodyInit | null | undefined);\n });\n }\n\n return { send };\n}\n","// 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.\n\nimport type {\n CreateClientOptions,\n Headers,\n Host,\n QueryParameters,\n Request,\n RequestOptions,\n} from '@algolia/client-common';\nimport { createAuth, createTransporter, getAlgoliaAgent, shuffle } from '@algolia/client-common';\n\nimport type { DeletedAtResponse } from '../model/deletedAtResponse';\nimport type { GetRecommendTaskResponse } from '../model/getRecommendTaskResponse';\nimport type { GetRecommendationsParams } from '../model/getRecommendationsParams';\nimport type { GetRecommendationsResponse } from '../model/getRecommendationsResponse';\nimport type { RecommendRule } from '../model/recommendRule';\nimport type { RecommendUpdatedAtResponse } from '../model/recommendUpdatedAtResponse';\nimport type { SearchRecommendRulesResponse } from '../model/searchRecommendRulesResponse';\n\nimport type {\n BatchRecommendRulesProps,\n CustomDeleteProps,\n CustomGetProps,\n CustomPostProps,\n CustomPutProps,\n DeleteRecommendRuleProps,\n GetRecommendRuleProps,\n GetRecommendStatusProps,\n LegacyGetRecommendationsParams,\n SearchRecommendRulesProps,\n} from '../model/clientMethodProps';\n\nexport const apiClientVersion = '5.53.0';\n\nfunction getDefaultHosts(appId: string): Host[] {\n return (\n [\n {\n url: `${appId}-dsn.algolia.net`,\n accept: 'read',\n protocol: 'https',\n },\n {\n url: `${appId}.algolia.net`,\n accept: 'write',\n protocol: 'https',\n },\n ] as Host[]\n ).concat(\n shuffle([\n {\n url: `${appId}-1.algolianet.com`,\n accept: 'readWrite',\n protocol: 'https',\n },\n {\n url: `${appId}-2.algolianet.com`,\n accept: 'readWrite',\n protocol: 'https',\n },\n {\n url: `${appId}-3.algolianet.com`,\n accept: 'readWrite',\n protocol: 'https',\n },\n ]),\n );\n}\n\nexport function createRecommendClient({\n appId: appIdOption,\n apiKey: apiKeyOption,\n authMode,\n algoliaAgents,\n ...options\n}: CreateClientOptions) {\n const auth = createAuth(appIdOption, apiKeyOption, authMode);\n const transporter = createTransporter({\n hosts: getDefaultHosts(appIdOption),\n ...options,\n algoliaAgent: getAlgoliaAgent({\n algoliaAgents,\n client: 'Recommend',\n version: apiClientVersion,\n }),\n baseHeaders: {\n 'content-type': 'text/plain',\n ...auth.headers(),\n ...options.baseHeaders,\n },\n baseQueryParameters: {\n ...auth.queryParameters(),\n ...options.baseQueryParameters,\n },\n });\n\n return {\n transporter,\n\n /**\n * The `appId` currently in use.\n */\n appId: appIdOption,\n\n /**\n * The `apiKey` currently in use.\n */\n apiKey: apiKeyOption,\n\n /**\n * Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.\n */\n clearCache(): Promise<void> {\n return Promise.all([transporter.requestsCache.clear(), transporter.responsesCache.clear()]).then(() => undefined);\n },\n\n /**\n * Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.\n */\n get _ua(): string {\n return transporter.algoliaAgent.value;\n },\n\n /**\n * Adds a `segment` to the `x-algolia-agent` sent with every requests.\n *\n * @param segment - The algolia agent (user-agent) segment to add.\n * @param version - The version of the agent.\n */\n addAlgoliaAgent(segment: string, version?: string | undefined): void {\n transporter.algoliaAgent.add({ segment, version });\n },\n\n /**\n * Helper method to switch the API key used to authenticate the requests.\n *\n * @param params - Method params.\n * @param params.apiKey - The new API Key to use.\n */\n setClientApiKey({ apiKey }: { apiKey: string }): void {\n if (!authMode || authMode === 'WithinHeaders') {\n transporter.baseHeaders['x-algolia-api-key'] = apiKey;\n } else {\n transporter.baseQueryParameters['x-algolia-api-key'] = apiKey;\n }\n },\n\n /**\n * Create or update a batch of Recommend Rules Each Recommend Rule is created or updated, depending on whether a Recommend Rule with the same `objectID` already exists. You may also specify `true` for `clearExistingRules`, in which case the batch will atomically replace all the existing Recommend Rules. Recommend Rules are similar to Search Rules, except that the conditions and consequences apply to a [source item](/doc/guides/algolia-recommend/overview/#recommend-models) instead of a query. The main differences are the following: - Conditions `pattern` and `anchoring` are unavailable. - Condition `filters` triggers if the source item matches the specified filters. - Condition `filters` accepts numeric filters. - Consequence `params` only covers filtering parameters. - Consequence `automaticFacetFilters` doesn\\'t require a facet value placeholder (it tries to match the data source item\\'s attributes instead).\n *\n * Required API Key ACLs:\n * - editSettings\n * @param batchRecommendRules - The batchRecommendRules object.\n * @param batchRecommendRules.indexName - Name of the index on which to perform the operation.\n * @param batchRecommendRules.model - [Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models).\n * @param batchRecommendRules.recommendRule - The recommendRule object.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n batchRecommendRules(\n { indexName, model, recommendRule }: BatchRecommendRulesProps,\n requestOptions?: RequestOptions,\n ): Promise<RecommendUpdatedAtResponse> {\n if (!indexName) {\n throw new Error('Parameter `indexName` is required when calling `batchRecommendRules`.');\n }\n\n if (!model) {\n throw new Error('Parameter `model` is required when calling `batchRecommendRules`.');\n }\n\n const requestPath = '/1/indexes/{indexName}/{model}/recommend/rules/batch'\n .replace('{indexName}', encodeURIComponent(indexName))\n .replace('{model}', encodeURIComponent(model));\n const headers: Headers = {};\n const queryParameters: QueryParameters = {};\n\n const request: Request = {\n method: 'POST',\n path: requestPath,\n queryParameters,\n headers,\n data: recommendRule ? recommendRule : {},\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * This method lets you send requests to the Algolia REST API.\n * @param customDelete - The customDelete object.\n * @param customDelete.path - Path of the endpoint, for example `1/newFeature`.\n * @param customDelete.parameters - Query parameters to apply to the current query.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n customDelete(\n { path, parameters }: CustomDeleteProps,\n requestOptions?: RequestOptions,\n ): Promise<Record<string, unknown>> {\n if (!path) {\n throw new Error('Parameter `path` is required when calling `customDelete`.');\n }\n\n const requestPath = '/{path}'.replace('{path}', path);\n const headers: Headers = {};\n const queryParameters: QueryParameters = parameters ? parameters : {};\n\n const request: Request = {\n method: 'DELETE',\n path: requestPath,\n queryParameters,\n headers,\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * This method lets you send requests to the Algolia REST API.\n * @param customGet - The customGet object.\n * @param customGet.path - Path of the endpoint, for example `1/newFeature`.\n * @param customGet.parameters - Query parameters to apply to the current query.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n customGet({ path, parameters }: CustomGetProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>> {\n if (!path) {\n throw new Error('Parameter `path` is required when calling `customGet`.');\n }\n\n const requestPath = '/{path}'.replace('{path}', path);\n const headers: Headers = {};\n const queryParameters: QueryParameters = parameters ? parameters : {};\n\n const request: Request = {\n method: 'GET',\n path: requestPath,\n queryParameters,\n headers,\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * This method lets you send requests to the Algolia REST API.\n * @param customPost - The customPost object.\n * @param customPost.path - Path of the endpoint, for example `1/newFeature`.\n * @param customPost.parameters - Query parameters to apply to the current query.\n * @param customPost.body - Parameters to send with the custom request.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n customPost(\n { path, parameters, body }: CustomPostProps,\n requestOptions?: RequestOptions,\n ): Promise<Record<string, unknown>> {\n if (!path) {\n throw new Error('Parameter `path` is required when calling `customPost`.');\n }\n\n const requestPath = '/{path}'.replace('{path}', path);\n const headers: Headers = {};\n const queryParameters: QueryParameters = parameters ? parameters : {};\n\n const request: Request = {\n method: 'POST',\n path: requestPath,\n queryParameters,\n headers,\n data: body ? body : {},\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * This method lets you send requests to the Algolia REST API.\n * @param customPut - The customPut object.\n * @param customPut.path - Path of the endpoint, for example `1/newFeature`.\n * @param customPut.parameters - Query parameters to apply to the current query.\n * @param customPut.body - Parameters to send with the custom request.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n customPut(\n { path, parameters, body }: CustomPutProps,\n requestOptions?: RequestOptions,\n ): Promise<Record<string, unknown>> {\n if (!path) {\n throw new Error('Parameter `path` is required when calling `customPut`.');\n }\n\n const requestPath = '/{path}'.replace('{path}', path);\n const headers: Headers = {};\n const queryParameters: QueryParameters = parameters ? parameters : {};\n\n const request: Request = {\n method: 'PUT',\n path: requestPath,\n queryParameters,\n headers,\n data: body ? body : {},\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * Deletes a Recommend rule from a recommendation scenario.\n *\n * Required API Key ACLs:\n * - editSettings\n * @param deleteRecommendRule - The deleteRecommendRule object.\n * @param deleteRecommendRule.indexName - Name of the index on which to perform the operation.\n * @param deleteRecommendRule.model - [Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models).\n * @param deleteRecommendRule.objectID - Unique record identifier.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n deleteRecommendRule(\n { indexName, model, objectID }: DeleteRecommendRuleProps,\n requestOptions?: RequestOptions,\n ): Promise<DeletedAtResponse> {\n if (!indexName) {\n throw new Error('Parameter `indexName` is required when calling `deleteRecommendRule`.');\n }\n\n if (!model) {\n throw new Error('Parameter `model` is required when calling `deleteRecommendRule`.');\n }\n\n if (!objectID) {\n throw new Error('Parameter `objectID` is required when calling `deleteRecommendRule`.');\n }\n\n const requestPath = '/1/indexes/{indexName}/{model}/recommend/rules/{objectID}'\n .replace('{indexName}', encodeURIComponent(indexName))\n .replace('{model}', encodeURIComponent(model))\n .replace('{objectID}', encodeURIComponent(objectID));\n const headers: Headers = {};\n const queryParameters: QueryParameters = {};\n\n const request: Request = {\n method: 'DELETE',\n path: requestPath,\n queryParameters,\n headers,\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * Retrieves a Recommend rule that you previously created in the Algolia dashboard.\n *\n * Required API Key ACLs:\n * - settings\n * @param getRecommendRule - The getRecommendRule object.\n * @param getRecommendRule.indexName - Name of the index on which to perform the operation.\n * @param getRecommendRule.model - [Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models).\n * @param getRecommendRule.objectID - Unique record identifier.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n getRecommendRule(\n { indexName, model, objectID }: GetRecommendRuleProps,\n requestOptions?: RequestOptions,\n ): Promise<RecommendRule> {\n if (!indexName) {\n throw new Error('Parameter `indexName` is required when calling `getRecommendRule`.');\n }\n\n if (!model) {\n throw new Error('Parameter `model` is required when calling `getRecommendRule`.');\n }\n\n if (!objectID) {\n throw new Error('Parameter `objectID` is required when calling `getRecommendRule`.');\n }\n\n const requestPath = '/1/indexes/{indexName}/{model}/recommend/rules/{objectID}'\n .replace('{indexName}', encodeURIComponent(indexName))\n .replace('{model}', encodeURIComponent(model))\n .replace('{objectID}', encodeURIComponent(objectID));\n const headers: Headers = {};\n const queryParameters: QueryParameters = {};\n\n const request: Request = {\n method: 'GET',\n path: requestPath,\n queryParameters,\n headers,\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * Checks the status of a given task. Deleting a Recommend rule is asynchronous. When you delete a rule, a task is created on a queue and completed depending on the load on the server. The API response includes a task ID that you can use to check the status.\n *\n * Required API Key ACLs:\n * - editSettings\n * @param getRecommendStatus - The getRecommendStatus object.\n * @param getRecommendStatus.indexName - Name of the index on which to perform the operation.\n * @param getRecommendStatus.model - [Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models).\n * @param getRecommendStatus.taskID - Unique task identifier.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n getRecommendStatus(\n { indexName, model, taskID }: GetRecommendStatusProps,\n requestOptions?: RequestOptions,\n ): Promise<GetRecommendTaskResponse> {\n if (!indexName) {\n throw new Error('Parameter `indexName` is required when calling `getRecommendStatus`.');\n }\n\n if (!model) {\n throw new Error('Parameter `model` is required when calling `getRecommendStatus`.');\n }\n\n if (!taskID) {\n throw new Error('Parameter `taskID` is required when calling `getRecommendStatus`.');\n }\n\n const requestPath = '/1/indexes/{indexName}/{model}/task/{taskID}'\n .replace('{indexName}', encodeURIComponent(indexName))\n .replace('{model}', encodeURIComponent(model))\n .replace('{taskID}', encodeURIComponent(taskID));\n const headers: Headers = {};\n const queryParameters: QueryParameters = {};\n\n const request: Request = {\n method: 'GET',\n path: requestPath,\n queryParameters,\n headers,\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * Retrieves recommendations from selected AI models.\n *\n * Required API Key ACLs:\n * - search\n * @param getRecommendationsParams - The getRecommendationsParams object.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n getRecommendations(\n getRecommendationsParams: GetRecommendationsParams | LegacyGetRecommendationsParams,\n requestOptions?: RequestOptions,\n ): Promise<GetRecommendationsResponse> {\n if (getRecommendationsParams && Array.isArray(getRecommendationsParams)) {\n const newSignatureRequest: GetRecommendationsParams = {\n requests: getRecommendationsParams,\n };\n\n getRecommendationsParams = newSignatureRequest;\n }\n\n if (!getRecommendationsParams) {\n throw new Error('Parameter `getRecommendationsParams` is required when calling `getRecommendations`.');\n }\n\n if (!getRecommendationsParams.requests) {\n throw new Error('Parameter `getRecommendationsParams.requests` is required when calling `getRecommendations`.');\n }\n\n const requestPath = '/1/indexes/*/recommendations';\n const headers: Headers = {};\n const queryParameters: QueryParameters = {};\n\n const request: Request = {\n method: 'POST',\n path: requestPath,\n queryParameters,\n headers,\n data: getRecommendationsParams,\n useReadTransporter: true,\n cacheable: true,\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * Searches for Recommend rules. Use an empty query to list all rules for this recommendation scenario.\n *\n * Required API Key ACLs:\n * - settings\n * @param searchRecommendRules - The searchRecommendRules object.\n * @param searchRecommendRules.indexName - Name of the index on which to perform the operation.\n * @param searchRecommendRules.model - [Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models).\n * @param searchRecommendRules.searchRecommendRulesParams - The searchRecommendRulesParams object.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n searchRecommendRules(\n { indexName, model, searchRecommendRulesParams }: SearchRecommendRulesProps,\n requestOptions?: RequestOptions,\n ): Promise<SearchRecommendRulesResponse> {\n if (!indexName) {\n throw new Error('Parameter `indexName` is required when calling `searchRecommendRules`.');\n }\n\n if (!model) {\n throw new Error('Parameter `model` is required when calling `searchRecommendRules`.');\n }\n\n const requestPath = '/1/indexes/{indexName}/{model}/recommend/rules/search'\n .replace('{indexName}', encodeURIComponent(indexName))\n .replace('{model}', encodeURIComponent(model));\n const headers: Headers = {};\n const queryParameters: QueryParameters = {};\n\n const request: Request = {\n method: 'POST',\n path: requestPath,\n queryParameters,\n headers,\n data: searchRecommendRulesParams ? searchRecommendRulesParams : {},\n useReadTransporter: true,\n cacheable: true,\n };\n\n return transporter.request(request, requestOptions);\n },\n };\n}\n","// 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.\n\nimport {\n createBrowserLocalStorageCache,\n createFallbackableCache,\n createMemoryCache,\n createNullLogger,\n} from '@algolia/client-common';\nimport { createXhrRequester } from '@algolia/requester-browser-xhr';\n\nimport type { ClientOptions } from '@algolia/client-common';\n\nimport { apiClientVersion, createRecommendClient } from '../src/recommendClient';\n\nexport { apiClientVersion } from '../src/recommendClient';\n\nexport * from '../model';\n\nexport function recommendClient(appId: string, apiKey: string, options?: ClientOptions | undefined): RecommendClient {\n if (!appId || typeof appId !== 'string') {\n throw new Error('`appId` is missing.');\n }\n\n if (!apiKey || typeof apiKey !== 'string') {\n throw new Error('`apiKey` is missing.');\n }\n\n const { compression: _compression, ...browserOptions } = options || {};\n\n return createRecommendClient({\n appId,\n apiKey,\n timeouts: {\n connect: 1000,\n read: 2000,\n write: 30000,\n },\n logger: createNullLogger(),\n requester: createXhrRequester(),\n algoliaAgents: [{ segment: 'Browser' }],\n authMode: 'WithinQueryParameters',\n responsesCache: createMemoryCache(),\n requestsCache: createMemoryCache({ serializable: false }),\n hostsCache: createFallbackableCache({\n caches: [createBrowserLocalStorageCache({ key: `${apiClientVersion}-${appId}` }), createMemoryCache()],\n }),\n ...browserOptions,\n });\n}\n\nexport type RecommendClient = ReturnType<typeof createRecommendClient>;\n"],"mappings":"AAEO,SAASA,EAA+BC,EAA4C,CACzF,IAAIC,EAEEC,EAAe,qBAAqBF,EAAQ,GAAG,GAErD,SAASG,GAAsB,CAC7B,OAAIF,IAAY,SACdA,EAAUD,EAAQ,cAAgB,OAAO,cAGpCC,CACT,CAEA,SAASG,GAA+C,CACtD,OAAO,KAAK,MAAMD,EAAW,EAAE,QAAQD,CAAY,GAAK,IAAI,CAC9D,CAEA,SAASG,EAAaC,EAAsC,CAC1DH,EAAW,EAAE,QAAQD,EAAc,KAAK,UAAUI,CAAS,CAAC,CAC9D,CAEA,SAASC,GAA6B,CACpC,OAAO,IAAI,QAASC,GAAY,WAAWA,EAAS,CAAC,CAAC,CACxD,CAEA,SAASC,GAGP,CACA,IAAMC,EAAaV,EAAQ,WAAaA,EAAQ,WAAa,IAAO,KAC9DM,EAAYF,EAA2C,EACvDO,EAAc,IAAI,KAAK,EAAE,QAAQ,EACnCC,EAAU,GAsBd,MAAO,CAAE,UApBQ,OAAO,YACtB,OAAO,QAAQN,CAAS,EAAE,OAAO,CAAC,CAAC,CAAEO,CAAS,IACxC,CAACA,GAAaA,EAAU,YAAc,QAKrCH,GAIDG,EAA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Ae,CAAC,CAAE,QAAS,SAAU,CAAC,EACtC,SAAU,wBACV,eAAgBC,EAAkB,EAClC,cAAeA,EAAkB,CAAE,aAAc,EAAM,CAAC,EACxD,WAAYC,EAAwB,CAClC,OAAQ,CAACC,EAA+B,CAAE,IAAK,GAAGC,CAAgB,IAAIX,CAAK,EAAG,CAAC,EAAGQ,EAAkB,CAAC,CACvG,CAAC,EACD,GAAGJ,CACL,CAAC,CACH","names":["createBrowserLocalStorageCache","options","storage","namespaceKey","getStorage","getNamespace","setNamespace","namespace","yieldToMain","resolve","getFilteredNamespace","timeToLive","currentTime","changed","cacheItem","key","defaultValue","events","cachedItem","value","createNullCache","_key","result","createFallbackableCache","caches","current","createMemoryCache","cache","keyAsString","promise","createAlgoliaAgent","version","algoliaAgent","options","addedAlgoliaAgent","createAuth","appId","apiKey","authMode","credentials","getAlgoliaAgent","algoliaAgents","client","version","defaultAlgoliaAgent","createAlgoliaAgent","algoliaAgent","createNullLogger","_message","_args","COMPRESSION_THRESHOLD","EXPIRATION_DELAY","createStatefulHost","host","status","lastUpdate","isUp","isTimedOut","AlgoliaError","message","name","ErrorWithStackTrace","AlgoliaError","message","stackTrace","name","RetryError","ApiError","status","DeserializationError","response","DetailedApiError","error","shuffle","array","shuffledArray","c","b","serializeUrl","host","path","queryParameters","queryParametersAsString","serializeQueryParameters","url","parameters","key","serializeData","request","requestOptions","data","serializeHeaders","baseHeaders","requestHeaders","requestOptionsHeaders","headers","serializedHeaders","header","value","deserializeSuccess","deserializeFailure","content","stackFrame","parsed","isNetworkError","isTimedOut","isRetryable","isSuccess","stackTraceWithoutCredentials","stackFrameWithoutCredentials","modifiedHeaders","createTransporter","hosts","hostsCache","logger","baseQueryParameters","algoliaAgent","timeouts","requester","requestsCache","responsesCache","compress","compression","createRetryableOptions","compatibleHosts","statefulHosts","compatibleHost","createStatefulHost","hostsUp","hostsTimedOut","hostsAvailable","timeoutsCount","baseTimeout","retryableRequest","isRead","serializedData","wantsCompression","COMPRESSION_THRESHOLD","shouldCompress","dataQueryParameters","retry","retryableHosts","getTimeout","timeout","payload","pushToStackTrace","options","createRequest","createRetryableRequest","err","_","createXhrRequester","send","request","resolve","baseRequester","key","createTimeout","timeout","content","connectTimeout","responseTimeout","apiClientVersion","getDefaultHosts","appId","shuffle","createRecommendClient","appIdOption","apiKeyOption","authMode","algoliaAgents","options","auth","createAuth","transporter","createTransporter","getAlgoliaAgent","segment","version","apiKey","indexName","model","recommendRule","requestOptions","request","path","parameters","body","objectID","taskID","getRecommendationsParams","searchRecommendRulesParams","recommendClient","appId","apiKey","options","_compression","browserOptions","createRecommendClient","createNullLogger","m","createMemoryCache","createFallbackableCache","createBrowserLocalStorageCache","apiClientVersion"]}
|
|
1
|
+
{"version":3,"sources":["../../../client-common/src/cache/createBrowserLocalStorageCache.ts","../../../client-common/src/cache/createNullCache.ts","../../../client-common/src/cache/createFallbackableCache.ts","../../../client-common/src/cache/createMemoryCache.ts","../../../client-common/src/constants.ts","../../../client-common/src/createAlgoliaAgent.ts","../../../client-common/src/createAuth.ts","../../../client-common/src/createIterablePromise.ts","../../../client-common/src/getAlgoliaAgent.ts","../../../client-common/src/logger/createNullLogger.ts","../../../client-common/src/sse.ts","../../../client-common/src/transporter/compress.ts","../../../client-common/src/transporter/createStatefulHost.ts","../../../client-common/src/transporter/errors.ts","../../../client-common/src/transporter/helpers.ts","../../../client-common/src/transporter/responses.ts","../../../client-common/src/transporter/stackTrace.ts","../../../client-common/src/transporter/createTransporter.ts","../../../client-common/src/types/logger.ts","../../../client-common/src/validateParam.ts","../../../requester-browser-xhr/src/createXhrRequester.ts","../../src/recommendClient.ts","../../builds/browser.ts"],"sourcesContent":["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 yieldToMain(): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, 0));\n }\n\n function getFilteredNamespace(): {\n namespace: Record<string, BrowserLocalStorageCacheItem>;\n changed: boolean;\n } {\n const timeToLive = options.timeToLive ? options.timeToLive * 1000 : null;\n const namespace = getNamespace<BrowserLocalStorageCacheItem>();\n const currentTime = new Date().getTime();\n let changed = false;\n\n const filtered = Object.fromEntries(\n Object.entries(namespace).filter(([, cacheItem]) => {\n if (!cacheItem || cacheItem.timestamp === undefined) {\n changed = true;\n return false;\n }\n\n if (!timeToLive) {\n return true;\n }\n\n if (cacheItem.timestamp + timeToLive < currentTime) {\n changed = true;\n return false;\n }\n\n return true;\n }),\n );\n\n return { namespace: filtered, changed };\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 yieldToMain().then(() => {\n const { namespace, changed } = getFilteredNamespace();\n const cachedItem = namespace[JSON.stringify(key)];\n\n if (changed) {\n setNamespace(namespace);\n }\n\n if (cachedItem) {\n return cachedItem.value as TValue;\n }\n\n return defaultValue().then((value) => events.miss(value).then(() => value));\n });\n },\n\n set<TValue>(key: Record<string, any> | string, value: TValue): Promise<TValue> {\n return yieldToMain().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 yieldToMain().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 { Cache, CacheEvents, FallbackableCacheOptions } from '../types';\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","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","import type { AlgoliaAgent, AlgoliaAgentOptions } 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 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 { 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 | undefined): Promise<TResponse> => {\n return new Promise<TResponse>((resolve, reject) => {\n func(previousResponse)\n .then(async (response) => {\n if (aggregator) {\n await aggregator(response);\n }\n\n if (await validate(response)) {\n return resolve(response);\n }\n\n if (error && (await error.validate(response))) {\n return reject(new Error(await error.message(response)));\n }\n\n return setTimeout(\n () => {\n retry(response).then(resolve).catch(reject);\n },\n await timeout(),\n );\n })\n .catch((err) => {\n reject(err);\n });\n });\n };\n\n return retry();\n}\n","import { createAlgoliaAgent } from './createAlgoliaAgent';\nimport type { AlgoliaAgent, AlgoliaAgentOptions } 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","import type { Logger } from '../types/logger';\n\nexport function createNullLogger(): Logger {\n return {\n debug(_message: string, _args?: any | undefined): Promise<void> {\n return Promise.resolve();\n },\n info(_message: string, _args?: any | undefined): Promise<void> {\n return Promise.resolve();\n },\n error(_message: string, _args?: any | undefined): Promise<void> {\n return Promise.resolve();\n },\n };\n}\n","/**\n * WHATWG-compliant Server-Sent Events parser.\n *\n * Three-layer architecture:\n * 1. iterLines() — byte chunking → line decoding\n * 2. SSEDecoder — line → SSE event decoding\n * 3. iterSSEEvents — top-level composer (exported)\n *\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation\n */\n\nconst MAX_LINE_BUFFER_SIZE = 10 * 1024 * 1024; // 10MB\n\n// ─── Types ──────────────────────────────────────────────────────────────────\n\nexport type ServerSentEvent = {\n /** Concatenated data: field values, joined by '\\n'. */\n data: string;\n /** Event type from the event: field. Defaults to \"\" (empty string). */\n event: string;\n /** Last event ID. Persists across dispatches until changed. */\n id: string | null;\n /** Reconnection time in ms. Persists across dispatches until changed. */\n retry: number | null;\n};\n\n/**\n * Wrapper for a parsed SSE event, yielded by the typed `*Stream` methods.\n *\n * - `data` is the JSON-parsed payload when parsing succeeds, `null` otherwise.\n * - `raw` is the original {@link ServerSentEvent} (always present).\n * - `error` is set when JSON parsing of `event.data` failed.\n */\nexport type StreamEvent<T = Record<string, unknown>> = {\n /** Parsed data from the event, or `null` if parsing failed. */\n data: T | null;\n /** The original, unparsed SSE event. */\n raw: ServerSentEvent;\n /** The error that occurred while parsing `event.data`, if any. */\n error?: Error;\n};\n\n// ─── Helpers ────────────────────────────────────────────────────────────────\n\n/**\n * Converts a ReadableStream into an AsyncIterable via getReader().\n * Fallback for environments where ReadableStream lacks Symbol.asyncIterator.\n */\nasync function* readableStreamToAsyncIterable(stream: ReadableStream<Uint8Array>): AsyncGenerator<Uint8Array> {\n const reader = stream.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) return;\n yield value;\n }\n } finally {\n reader.releaseLock();\n }\n}\n\n/**\n * Normalizes the input to an AsyncIterable<Uint8Array>.\n * Prefers Symbol.asyncIterator if available; falls back to getReader().\n */\nfunction toAsyncIterable(stream: ReadableStream<Uint8Array> | AsyncIterable<Uint8Array>): AsyncIterable<Uint8Array> {\n if (Symbol.asyncIterator in stream) {\n return stream as AsyncIterable<Uint8Array>;\n }\n return readableStreamToAsyncIterable(stream as ReadableStream<Uint8Array>);\n}\n\n// ─── Layer 1: Byte stream → Lines ──────────────────────────────────────────\n\n/**\n * Yields individual lines from a byte stream.\n *\n * Handles \\r, \\n, and \\r\\n line endings, including \\r\\n split across chunks.\n * Uses offset tracking within each decoded chunk to avoid O(n²) buffer growth.\n * Strips BOM (U+FEFF) from the very first line.\n * Throws if the internal line buffer exceeds 10MB.\n */\nasync function* iterLines(stream: ReadableStream<Uint8Array> | AsyncIterable<Uint8Array>): AsyncGenerator<string> {\n const decoder = new TextDecoder('utf-8');\n const buffer: string[] = [];\n let bufferSize = 0;\n let trailingCR = false;\n let isFirstLine = true;\n\n for await (const chunk of toAsyncIterable(stream)) {\n const text = decoder.decode(chunk, { stream: true });\n let offset = 0;\n\n // Handle \\r\\n split across chunks: if the previous chunk ended with \\r\n // and this one starts with \\n, skip the \\n (it's the second half of \\r\\n)\n if (trailingCR) {\n trailingCR = false;\n if (text.length > 0 && text[0] === '\\n') {\n offset = 1;\n }\n }\n\n while (offset < text.length) {\n const crIdx = text.indexOf('\\r', offset);\n const lfIdx = text.indexOf('\\n', offset);\n\n // No more line endings in this chunk — buffer the rest\n if (crIdx === -1 && lfIdx === -1) {\n const remaining = text.slice(offset);\n buffer.push(remaining);\n bufferSize += remaining.length;\n if (bufferSize > MAX_LINE_BUFFER_SIZE) {\n throw new Error('SSE line buffer exceeded 10MB');\n }\n break;\n }\n\n let endIdx: number;\n let skipLen: number;\n\n if (crIdx !== -1 && (lfIdx === -1 || crIdx < lfIdx)) {\n // \\r found before \\n (or no \\n at all)\n endIdx = crIdx;\n if (crIdx + 1 < text.length) {\n // Peek ahead: \\r\\n or bare \\r\n skipLen = text[crIdx + 1] === '\\n' ? 2 : 1;\n } else {\n // \\r at end of chunk — might be \\r\\n split across chunks\n trailingCR = true;\n skipLen = 1;\n }\n } else {\n // \\n found before \\r (or no \\r at all)\n // Safe: at least one of crIdx/lfIdx is != -1, and we're in the else\n // branch, so lfIdx must be != -1\n endIdx = lfIdx;\n skipLen = 1;\n }\n\n const segment = text.slice(offset, endIdx);\n buffer.push(segment);\n\n let line = buffer.length === 1 ? buffer[0]! : buffer.join('');\n buffer.length = 0;\n bufferSize = 0;\n\n // Strip BOM from the very first line only\n if (isFirstLine) {\n if (line.startsWith('\\uFEFF')) {\n line = line.slice(1);\n }\n isFirstLine = false;\n }\n\n yield line;\n offset = endIdx + skipLen;\n }\n }\n\n // Flush TextDecoder (handles any remaining bytes from multi-byte sequences)\n const remaining = decoder.decode();\n if (remaining) {\n buffer.push(remaining);\n }\n\n // Yield any remaining buffered content as the final line\n if (buffer.length > 0) {\n let line = buffer.join('');\n if (isFirstLine && line.startsWith('\\uFEFF')) {\n line = line.slice(1);\n }\n yield line;\n }\n}\n\n// ─── Layer 2: Lines → SSE Events ──────────────────────────────────────────\n\n/**\n * Stateful SSE event decoder. Feed lines one at a time via decode().\n * Returns a ServerSentEvent on blank lines (dispatch), null otherwise.\n *\n * Per WHATWG spec §9.2.6:\n * - lastEventId persists across dispatches\n * - retry persists across dispatches (global reconnection setting)\n * - eventType resets after every blank line (even when data is empty)\n * - data buffer resets after dispatch\n * - id field containing NULL (\\0) is ignored entirely\n * - retry field must be ASCII digits only\n */\nclass SSEDecoder {\n private data: string[] = [];\n private eventType = '';\n private lastEventId: string | null = null;\n private retry: number | null = null;\n\n decode(line: string): ServerSentEvent | null {\n // Blank line → dispatch event or reset\n if (line === '') {\n return this.dispatch();\n }\n\n // Comment line (starts with ':')\n if (line[0] === ':') {\n return null;\n }\n\n // Parse field:value\n const colonIdx = line.indexOf(':');\n let field: string;\n let value: string;\n\n if (colonIdx === -1) {\n // No colon → field is entire line, value is empty\n field = line;\n value = '';\n } else {\n field = line.slice(0, colonIdx);\n value = line.slice(colonIdx + 1);\n // Strip exactly ONE leading space (if present)\n if (value[0] === ' ') {\n value = value.slice(1);\n }\n }\n\n switch (field) {\n case 'data':\n this.data.push(value);\n break;\n case 'event':\n this.eventType = value;\n break;\n case 'id':\n // Ignore if value contains NULL character (security: WHATWG spec)\n if (!value.includes('\\0')) {\n this.lastEventId = value;\n }\n break;\n case 'retry':\n // Must consist of ASCII digits only (no negatives, no whitespace)\n if (/^[0-9]+$/.test(value)) {\n this.retry = parseInt(value, 10);\n }\n break;\n // Unknown fields: ignore silently\n }\n\n return null;\n }\n\n private dispatch(): ServerSentEvent | null {\n // eventType resets on every blank line per WHATWG spec,\n // regardless of whether we actually dispatch an event\n const currentEventType = this.eventType;\n this.eventType = '';\n\n // Suppress dispatch when no data: lines were received\n if (this.data.length === 0) {\n return null;\n }\n\n const event: ServerSentEvent = {\n data: this.data.join('\\n'),\n event: currentEventType,\n id: this.lastEventId,\n retry: this.retry,\n };\n\n // Reset data buffer; lastEventId and retry persist across dispatches\n this.data = [];\n\n return event;\n }\n}\n\n// ─── Layer 3: Top-level composer ──────────────────────────────────────────\n\n/**\n * Parses a byte stream as WHATWG Server-Sent Events.\n *\n * Accepts both ReadableStream<Uint8Array> (browser fetch) and\n * AsyncIterable<Uint8Array> (Node.js streams / Buffer chunks).\n *\n * @example\n * ```ts\n * const response = await fetch(url);\n * for await (const event of iterSSEEvents(response.body!)) {\n * console.log(event.event, event.data);\n * }\n * ```\n */\nexport async function* iterSSEEvents(\n stream: ReadableStream<Uint8Array> | AsyncIterable<Uint8Array>,\n): AsyncGenerator<ServerSentEvent> {\n const decoder = new SSEDecoder();\n for await (const line of iterLines(stream)) {\n const event = decoder.decode(line);\n if (event !== null) {\n yield event;\n }\n }\n}\n","export const COMPRESSION_THRESHOLD = 750;\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 override 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 IndexNotFoundError extends AlgoliaError {\n constructor(indexName: string) {\n super(`${indexName} does not exist`, 'IndexNotFoundError');\n }\n}\n\nexport class IndicesInSameAppError extends AlgoliaError {\n constructor() {\n super('Indices are in the same application. Use operationIndex instead.', 'IndicesInSameAppError');\n }\n}\n\nexport class IndexAlreadyExistsError extends AlgoliaError {\n constructor(indexName: string) {\n super(`${indexName} index already exists.`, 'IndexAlreadyExistsError');\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 visit our help center https://alg.li/support-unreachable-hosts or 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 | undefined;\n};\n\nexport type DetailedError = {\n code: string;\n details?: DetailedErrorWithMessage[] | DetailedErrorWithTypeID[] | undefined;\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';\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 ).replace(/\\+/g, '%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 | undefined,\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 // Handle 204 No Content and other empty responses\n if (response.status === 204 || response.content.length === 0) {\n return undefined as unknown as TObject;\n }\n\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 { ServerSentEvent } from '../sse';\nimport { iterSSEEvents } from '../sse';\nimport type {\n EndRequest,\n Host,\n QueryParameters,\n Request,\n RequestOptions,\n Response,\n StackFrame,\n Transporter,\n TransporterOptions,\n} from '../types';\nimport { COMPRESSION_THRESHOLD } from './compress';\nimport { createStatefulHost } from './createStatefulHost';\nimport { RetryError } from './errors';\nimport { deserializeFailure, deserializeSuccess, serializeData, serializeHeaders, serializeUrl } from './helpers';\nimport { isRetryable, isSuccess } from './responses';\nimport { stackFrameWithoutCredentials, stackTraceWithoutCredentials } 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 logger,\n baseQueryParameters,\n algoliaAgent,\n timeouts,\n requester,\n requestsCache,\n responsesCache,\n compress,\n compression,\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: boolean,\n ): Promise<TResponse> {\n const stackTrace: StackFrame[] = [];\n\n /**\n * First we prepare the payload that do not depend from hosts.\n */\n const serializedData = serializeData(request, requestOptions);\n const headers = serializeHeaders(baseHeaders, request.headers, requestOptions.headers);\n\n const wantsCompression =\n compression === 'gzip' &&\n serializedData !== undefined &&\n serializedData.length > COMPRESSION_THRESHOLD &&\n (request.method === 'POST' || request.method === 'PUT');\n\n if (wantsCompression && compress === undefined) {\n logger.info('Compression is disabled because no compress method is available.');\n }\n\n const shouldCompress = wantsCompression && compress !== undefined;\n const data = shouldCompress ? await compress(serializedData) : serializedData;\n if (shouldCompress) {\n headers['content-encoding'] = 'gzip';\n }\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 logger.info('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 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, isRead);\n };\n\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\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 async function* requestStream(\n request: Request,\n requestOptions: RequestOptions = {},\n ): AsyncGenerator<ServerSentEvent> {\n if (!requester.sendStream) {\n throw new Error('This requester does not support streaming');\n }\n\n const data = serializeData(request, requestOptions);\n const headers = serializeHeaders(baseHeaders, request.headers, requestOptions.headers);\n headers['accept'] = 'text/event-stream';\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 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 const isRead = request.useReadTransporter || request.method === 'GET';\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 const host = options.hosts[0];\n if (!host) {\n throw new RetryError([]);\n }\n\n const timeout = { ...timeouts, ...requestOptions.timeouts };\n const payload: EndRequest = {\n data,\n headers,\n method: request.method,\n url: serializeUrl(host, request.path, queryParameters),\n connectTimeout: timeout.connect,\n responseTimeout: isRead ? timeout.read : timeout.write,\n };\n\n const stream = await requester.sendStream(payload);\n yield* iterSSEEvents(stream);\n }\n\n return {\n hostsCache,\n requester,\n timeouts,\n logger,\n algoliaAgent,\n baseHeaders,\n baseQueryParameters,\n hosts,\n request: createRequest,\n requestStream,\n requestsCache,\n responsesCache,\n };\n}\n","export const LogLevelEnum: Readonly<Record<string, LogLevelType>> = {\n Debug: 1,\n Info: 2,\n Error: 3,\n};\n\nexport type LogLevelType = 1 | 2 | 3;\n\nexport type Logger = {\n /**\n * Logs debug messages.\n */\n debug: (message: string, args?: any | undefined) => Promise<void>;\n\n /**\n * Logs info messages.\n */\n info: (message: string, args?: any | undefined) => Promise<void>;\n\n /**\n * Logs error messages.\n */\n error: (message: string, args?: any | undefined) => Promise<void>;\n};\n","export function validateRequired(field: string, method: string, value: unknown): void {\n if (value === null || value === undefined || (typeof value === 'string' && value.length === 0)) {\n throw new Error(`Parameter \\`${field}\\` is required when calling \\`${method}\\`.`);\n }\n}\n","import type { EndRequest, Requester, Response } from '@algolia/client-common';\n\ntype Timeout = ReturnType<typeof setTimeout>;\n\nexport function createXhrRequester(): Requester {\n function send(request: EndRequest): Promise<Response> {\n return new Promise((resolve) => {\n const baseRequester = new XMLHttpRequest();\n baseRequester.open(request.method, request.url, true);\n\n Object.keys(request.headers).forEach((key) => baseRequester.setRequestHeader(key, request.headers[key]));\n\n const createTimeout = (timeout: number, content: string): Timeout => {\n return setTimeout(() => {\n baseRequester.abort();\n\n resolve({\n status: 0,\n content,\n isTimedOut: true,\n });\n }, timeout);\n };\n\n const connectTimeout = createTimeout(request.connectTimeout, 'Connection timeout');\n\n let responseTimeout: Timeout | undefined;\n\n baseRequester.onreadystatechange = (): void => {\n if (baseRequester.readyState > baseRequester.OPENED && responseTimeout === undefined) {\n clearTimeout(connectTimeout);\n\n responseTimeout = createTimeout(request.responseTimeout, 'Socket timeout');\n }\n };\n\n baseRequester.onerror = (): void => {\n // istanbul ignore next\n if (baseRequester.status === 0) {\n clearTimeout(connectTimeout);\n clearTimeout(responseTimeout!);\n\n resolve({\n content: baseRequester.responseText || 'Network request failed',\n status: baseRequester.status,\n isTimedOut: false,\n });\n }\n };\n\n baseRequester.onload = (): void => {\n clearTimeout(connectTimeout);\n clearTimeout(responseTimeout!);\n\n resolve({\n content: baseRequester.responseText,\n status: baseRequester.status,\n isTimedOut: false,\n });\n };\n\n baseRequester.send(request.data as XMLHttpRequestBodyInit | null | undefined);\n });\n }\n\n return { send };\n}\n","// 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.\n\nimport type {\n CreateClientOptions,\n Headers,\n Host,\n QueryParameters,\n Request,\n RequestOptions,\n} from '@algolia/client-common';\nimport { createAuth, createTransporter, getAlgoliaAgent, shuffle, validateRequired } from '@algolia/client-common';\n\nimport type { DeletedAtResponse } from '../model/deletedAtResponse';\nimport type { GetRecommendTaskResponse } from '../model/getRecommendTaskResponse';\nimport type { GetRecommendationsParams } from '../model/getRecommendationsParams';\nimport type { GetRecommendationsResponse } from '../model/getRecommendationsResponse';\nimport type { RecommendRule } from '../model/recommendRule';\nimport type { RecommendUpdatedAtResponse } from '../model/recommendUpdatedAtResponse';\nimport type { SearchRecommendRulesResponse } from '../model/searchRecommendRulesResponse';\n\nimport type {\n BatchRecommendRulesProps,\n CustomDeleteProps,\n CustomGetProps,\n CustomPostProps,\n CustomPutProps,\n DeleteRecommendRuleProps,\n GetRecommendRuleProps,\n GetRecommendStatusProps,\n LegacyGetRecommendationsParams,\n SearchRecommendRulesProps,\n} from '../model/clientMethodProps';\n\nexport const apiClientVersion = '5.54.0';\n\nfunction getDefaultHosts(appId: string): Host[] {\n return (\n [\n {\n url: `${appId}-dsn.algolia.net`,\n accept: 'read',\n protocol: 'https',\n },\n {\n url: `${appId}.algolia.net`,\n accept: 'write',\n protocol: 'https',\n },\n ] as Host[]\n ).concat(\n shuffle([\n {\n url: `${appId}-1.algolianet.com`,\n accept: 'readWrite',\n protocol: 'https',\n },\n {\n url: `${appId}-2.algolianet.com`,\n accept: 'readWrite',\n protocol: 'https',\n },\n {\n url: `${appId}-3.algolianet.com`,\n accept: 'readWrite',\n protocol: 'https',\n },\n ]),\n );\n}\n\nexport function createRecommendClient({\n appId: appIdOption,\n apiKey: apiKeyOption,\n authMode,\n algoliaAgents,\n ...options\n}: CreateClientOptions) {\n const auth = createAuth(appIdOption, apiKeyOption, authMode);\n const transporter = createTransporter({\n hosts: getDefaultHosts(appIdOption),\n ...options,\n algoliaAgent: getAlgoliaAgent({\n algoliaAgents,\n client: 'Recommend',\n version: apiClientVersion,\n }),\n baseHeaders: {\n 'content-type': 'text/plain',\n ...auth.headers(),\n ...options.baseHeaders,\n },\n baseQueryParameters: {\n ...auth.queryParameters(),\n ...options.baseQueryParameters,\n },\n });\n\n return {\n transporter,\n\n /**\n * The `appId` currently in use.\n */\n appId: appIdOption,\n\n /**\n * The `apiKey` currently in use.\n */\n apiKey: apiKeyOption,\n\n /**\n * Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.\n */\n clearCache(): Promise<void> {\n return Promise.all([transporter.requestsCache.clear(), transporter.responsesCache.clear()]).then(() => undefined);\n },\n\n /**\n * Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.\n */\n get _ua(): string {\n return transporter.algoliaAgent.value;\n },\n\n /**\n * Adds a `segment` to the `x-algolia-agent` sent with every requests.\n *\n * @param segment - The algolia agent (user-agent) segment to add.\n * @param version - The version of the agent.\n */\n addAlgoliaAgent(segment: string, version?: string | undefined): void {\n transporter.algoliaAgent.add({ segment, version });\n },\n\n /**\n * Helper method to switch the API key used to authenticate the requests.\n *\n * @param params - Method params.\n * @param params.apiKey - The new API Key to use.\n */\n setClientApiKey({ apiKey }: { apiKey: string }): void {\n if (!authMode || authMode === 'WithinHeaders') {\n transporter.baseHeaders['x-algolia-api-key'] = apiKey;\n } else {\n transporter.baseQueryParameters['x-algolia-api-key'] = apiKey;\n }\n },\n\n /**\n * Create or update a batch of Recommend Rules Each Recommend Rule is created or updated, depending on whether a Recommend Rule with the same `objectID` already exists. You may also specify `true` for `clearExistingRules`, in which case the batch will atomically replace all the existing Recommend Rules. Recommend Rules are similar to Search Rules, except that the conditions and consequences apply to a [source item](/doc/guides/algolia-recommend/overview/#recommend-models) instead of a query. The main differences are the following: - Conditions `pattern` and `anchoring` are unavailable. - Condition `filters` triggers if the source item matches the specified filters. - Condition `filters` accepts numeric filters. - Consequence `params` only covers filtering parameters. - Consequence `automaticFacetFilters` doesn\\'t require a facet value placeholder (it tries to match the data source item\\'s attributes instead).\n *\n * Required API Key ACLs:\n * - editSettings\n * @param batchRecommendRules - The batchRecommendRules object.\n * @param batchRecommendRules.indexName - Name of the index on which to perform the operation.\n * @param batchRecommendRules.model - [Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models).\n * @param batchRecommendRules.recommendRule - The recommendRule object.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n batchRecommendRules(\n { indexName, model, recommendRule }: BatchRecommendRulesProps,\n requestOptions?: RequestOptions,\n ): Promise<RecommendUpdatedAtResponse> {\n validateRequired('indexName', 'batchRecommendRules', indexName);\n\n validateRequired('model', 'batchRecommendRules', model);\n\n const requestPath = '/1/indexes/{indexName}/{model}/recommend/rules/batch'\n .replace('{indexName}', encodeURIComponent(indexName))\n .replace('{model}', encodeURIComponent(model));\n const headers: Headers = {};\n const queryParameters: QueryParameters = {};\n\n const request: Request = {\n method: 'POST',\n path: requestPath,\n queryParameters,\n headers,\n data: recommendRule ? recommendRule : {},\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * This method lets you send requests to the Algolia REST API.\n * @param customDelete - The customDelete object.\n * @param customDelete.path - Path of the endpoint, for example `1/newFeature`.\n * @param customDelete.parameters - Query parameters to apply to the current query.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n customDelete(\n { path, parameters }: CustomDeleteProps,\n requestOptions?: RequestOptions,\n ): Promise<Record<string, unknown>> {\n validateRequired('path', 'customDelete', path);\n\n const requestPath = '/{path}'.replace('{path}', path);\n const headers: Headers = {};\n const queryParameters: QueryParameters = parameters ? parameters : {};\n\n const request: Request = {\n method: 'DELETE',\n path: requestPath,\n queryParameters,\n headers,\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * This method lets you send requests to the Algolia REST API.\n * @param customGet - The customGet object.\n * @param customGet.path - Path of the endpoint, for example `1/newFeature`.\n * @param customGet.parameters - Query parameters to apply to the current query.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n customGet({ path, parameters }: CustomGetProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>> {\n validateRequired('path', 'customGet', path);\n\n const requestPath = '/{path}'.replace('{path}', path);\n const headers: Headers = {};\n const queryParameters: QueryParameters = parameters ? parameters : {};\n\n const request: Request = {\n method: 'GET',\n path: requestPath,\n queryParameters,\n headers,\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * This method lets you send requests to the Algolia REST API.\n * @param customPost - The customPost object.\n * @param customPost.path - Path of the endpoint, for example `1/newFeature`.\n * @param customPost.parameters - Query parameters to apply to the current query.\n * @param customPost.body - Parameters to send with the custom request.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n customPost(\n { path, parameters, body }: CustomPostProps,\n requestOptions?: RequestOptions,\n ): Promise<Record<string, unknown>> {\n validateRequired('path', 'customPost', path);\n\n const requestPath = '/{path}'.replace('{path}', path);\n const headers: Headers = {};\n const queryParameters: QueryParameters = parameters ? parameters : {};\n\n const request: Request = {\n method: 'POST',\n path: requestPath,\n queryParameters,\n headers,\n data: body ? body : {},\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * This method lets you send requests to the Algolia REST API.\n * @param customPut - The customPut object.\n * @param customPut.path - Path of the endpoint, for example `1/newFeature`.\n * @param customPut.parameters - Query parameters to apply to the current query.\n * @param customPut.body - Parameters to send with the custom request.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n customPut(\n { path, parameters, body }: CustomPutProps,\n requestOptions?: RequestOptions,\n ): Promise<Record<string, unknown>> {\n validateRequired('path', 'customPut', path);\n\n const requestPath = '/{path}'.replace('{path}', path);\n const headers: Headers = {};\n const queryParameters: QueryParameters = parameters ? parameters : {};\n\n const request: Request = {\n method: 'PUT',\n path: requestPath,\n queryParameters,\n headers,\n data: body ? body : {},\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * Deletes a Recommend rule from a recommendation scenario.\n *\n * Required API Key ACLs:\n * - editSettings\n * @param deleteRecommendRule - The deleteRecommendRule object.\n * @param deleteRecommendRule.indexName - Name of the index on which to perform the operation.\n * @param deleteRecommendRule.model - [Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models).\n * @param deleteRecommendRule.objectID - Unique record identifier.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n deleteRecommendRule(\n { indexName, model, objectID }: DeleteRecommendRuleProps,\n requestOptions?: RequestOptions,\n ): Promise<DeletedAtResponse> {\n validateRequired('indexName', 'deleteRecommendRule', indexName);\n\n validateRequired('model', 'deleteRecommendRule', model);\n\n validateRequired('objectID', 'deleteRecommendRule', objectID);\n\n const requestPath = '/1/indexes/{indexName}/{model}/recommend/rules/{objectID}'\n .replace('{indexName}', encodeURIComponent(indexName))\n .replace('{model}', encodeURIComponent(model))\n .replace('{objectID}', encodeURIComponent(objectID));\n const headers: Headers = {};\n const queryParameters: QueryParameters = {};\n\n const request: Request = {\n method: 'DELETE',\n path: requestPath,\n queryParameters,\n headers,\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * Retrieves a Recommend rule that you previously created in the Algolia dashboard.\n *\n * Required API Key ACLs:\n * - settings\n * @param getRecommendRule - The getRecommendRule object.\n * @param getRecommendRule.indexName - Name of the index on which to perform the operation.\n * @param getRecommendRule.model - [Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models).\n * @param getRecommendRule.objectID - Unique record identifier.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n getRecommendRule(\n { indexName, model, objectID }: GetRecommendRuleProps,\n requestOptions?: RequestOptions,\n ): Promise<RecommendRule> {\n validateRequired('indexName', 'getRecommendRule', indexName);\n\n validateRequired('model', 'getRecommendRule', model);\n\n validateRequired('objectID', 'getRecommendRule', objectID);\n\n const requestPath = '/1/indexes/{indexName}/{model}/recommend/rules/{objectID}'\n .replace('{indexName}', encodeURIComponent(indexName))\n .replace('{model}', encodeURIComponent(model))\n .replace('{objectID}', encodeURIComponent(objectID));\n const headers: Headers = {};\n const queryParameters: QueryParameters = {};\n\n const request: Request = {\n method: 'GET',\n path: requestPath,\n queryParameters,\n headers,\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * Checks the status of a given task. Deleting a Recommend rule is asynchronous. When you delete a rule, a task is created on a queue and completed depending on the load on the server. The API response includes a task ID that you can use to check the status.\n *\n * Required API Key ACLs:\n * - editSettings\n * @param getRecommendStatus - The getRecommendStatus object.\n * @param getRecommendStatus.indexName - Name of the index on which to perform the operation.\n * @param getRecommendStatus.model - [Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models).\n * @param getRecommendStatus.taskID - Unique task identifier.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n getRecommendStatus(\n { indexName, model, taskID }: GetRecommendStatusProps,\n requestOptions?: RequestOptions,\n ): Promise<GetRecommendTaskResponse> {\n validateRequired('indexName', 'getRecommendStatus', indexName);\n\n validateRequired('model', 'getRecommendStatus', model);\n\n validateRequired('taskID', 'getRecommendStatus', taskID);\n\n const requestPath = '/1/indexes/{indexName}/{model}/task/{taskID}'\n .replace('{indexName}', encodeURIComponent(indexName))\n .replace('{model}', encodeURIComponent(model))\n .replace('{taskID}', encodeURIComponent(taskID));\n const headers: Headers = {};\n const queryParameters: QueryParameters = {};\n\n const request: Request = {\n method: 'GET',\n path: requestPath,\n queryParameters,\n headers,\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * Retrieves recommendations from selected AI models.\n *\n * Required API Key ACLs:\n * - search\n * @param getRecommendationsParams - The getRecommendationsParams object.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n getRecommendations(\n getRecommendationsParams: GetRecommendationsParams | LegacyGetRecommendationsParams,\n requestOptions?: RequestOptions,\n ): Promise<GetRecommendationsResponse> {\n if (getRecommendationsParams && Array.isArray(getRecommendationsParams)) {\n const newSignatureRequest: GetRecommendationsParams = {\n requests: getRecommendationsParams,\n };\n\n getRecommendationsParams = newSignatureRequest;\n }\n\n validateRequired('getRecommendationsParams', 'getRecommendations', getRecommendationsParams);\n\n validateRequired('getRecommendationsParams.requests', 'getRecommendations', getRecommendationsParams.requests);\n\n const requestPath = '/1/indexes/*/recommendations';\n const headers: Headers = {};\n const queryParameters: QueryParameters = {};\n\n const request: Request = {\n method: 'POST',\n path: requestPath,\n queryParameters,\n headers,\n data: getRecommendationsParams,\n useReadTransporter: true,\n cacheable: true,\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * Searches for Recommend rules. Use an empty query to list all rules for this recommendation scenario.\n *\n * Required API Key ACLs:\n * - settings\n * @param searchRecommendRules - The searchRecommendRules object.\n * @param searchRecommendRules.indexName - Name of the index on which to perform the operation.\n * @param searchRecommendRules.model - [Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models).\n * @param searchRecommendRules.searchRecommendRulesParams - The searchRecommendRulesParams object.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n searchRecommendRules(\n { indexName, model, searchRecommendRulesParams }: SearchRecommendRulesProps,\n requestOptions?: RequestOptions,\n ): Promise<SearchRecommendRulesResponse> {\n validateRequired('indexName', 'searchRecommendRules', indexName);\n\n validateRequired('model', 'searchRecommendRules', model);\n\n const requestPath = '/1/indexes/{indexName}/{model}/recommend/rules/search'\n .replace('{indexName}', encodeURIComponent(indexName))\n .replace('{model}', encodeURIComponent(model));\n const headers: Headers = {};\n const queryParameters: QueryParameters = {};\n\n const request: Request = {\n method: 'POST',\n path: requestPath,\n queryParameters,\n headers,\n data: searchRecommendRulesParams ? searchRecommendRulesParams : {},\n useReadTransporter: true,\n cacheable: true,\n };\n\n return transporter.request(request, requestOptions);\n },\n };\n}\n","// 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.\n\nimport {\n createBrowserLocalStorageCache,\n createFallbackableCache,\n createMemoryCache,\n createNullLogger,\n} from '@algolia/client-common';\nimport { createXhrRequester } from '@algolia/requester-browser-xhr';\n\nimport type { ClientOptions } from '@algolia/client-common';\n\nimport { apiClientVersion, createRecommendClient } from '../src/recommendClient';\n\nexport { apiClientVersion } from '../src/recommendClient';\n\nexport * from '../model';\n\nexport function recommendClient(appId: string, apiKey: string, options?: ClientOptions | undefined): RecommendClient {\n if (!appId || typeof appId !== 'string') {\n throw new Error('`appId` is missing.');\n }\n\n if (!apiKey || typeof apiKey !== 'string') {\n throw new Error('`apiKey` is missing.');\n }\n\n const { compression: _compression, ...browserOptions } = options || {};\n\n return createRecommendClient({\n appId,\n apiKey,\n timeouts: {\n connect: 1000,\n read: 2000,\n write: 30000,\n },\n logger: createNullLogger(),\n requester: createXhrRequester(),\n algoliaAgents: [{ segment: 'Browser' }],\n authMode: 'WithinQueryParameters',\n responsesCache: createMemoryCache(),\n requestsCache: createMemoryCache({ serializable: false }),\n hostsCache: createFallbackableCache({\n caches: [createBrowserLocalStorageCache({ key: `${apiClientVersion}-${appId}` }), createMemoryCache()],\n }),\n ...browserOptions,\n });\n}\n\nexport type RecommendClient = ReturnType<typeof createRecommendClient>;\n"],"mappings":"AAEO,SAASA,EAA+BC,EAA4C,CACzF,IAAIC,EAEEC,EAAe,qBAAqBF,EAAQ,GAAG,GAErD,SAASG,GAAsB,CAC7B,OAAIF,IAAY,SACdA,EAAUD,EAAQ,cAAgB,OAAO,cAGpCC,CACT,CAEA,SAASG,GAA+C,CACtD,OAAO,KAAK,MAAMD,EAAW,EAAE,QAAQD,CAAY,GAAK,IAAI,CAC9D,CAEA,SAASG,EAAaC,EAAsC,CAC1DH,EAAW,EAAE,QAAQD,EAAc,KAAK,UAAUI,CAAS,CAAC,CAC9D,CAEA,SAASC,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b,EAEA,OAAOjB,EAAY,QAAQW,EAASF,CAAc,CACpD,EAaA,qBACE,CAAE,UAAAH,EAAW,MAAAC,EAAO,2BAAAW,CAA2B,EAC/CT,EACuC,CACvCC,EAAiB,YAAa,uBAAwBJ,CAAS,EAE/DI,EAAiB,QAAS,uBAAwBH,CAAK,EAQvD,IAAMI,EAAmB,CACvB,OAAQ,OACR,KARkB,wDACjB,QAAQ,cAAe,mBAAmBL,CAAS,CAAC,EACpD,QAAQ,UAAW,mBAAmBC,CAAK,CAAC,EAO7C,gBALuC,CAAC,EAMxC,QAPuB,CAAC,EAQxB,KAAMW,GAA0D,CAAC,EACjE,mBAAoB,GACpB,UAAW,EACb,EAEA,OAAOlB,EAAY,QAAQW,EAASF,CAAc,CACpD,CACF,CACF,CCpdO,SAASU,GAAgBC,EAAeC,EAAgBC,EAAsD,CACnH,GAAI,CAACF,GAAS,OAAOA,GAAU,SAC7B,MAAM,IAAI,MAAM,qBAAqB,EAGvC,GAAI,CAACC,GAAU,OAAOA,GAAW,SAC/B,MAAM,IAAI,MAAM,sBAAsB,EAGxC,GAAM,CAAE,YAAaE,EAAc,GAAGC,CAAe,EAAIF,GAAW,CAAC,EAErE,OAAOG,GAAsB,CAC3B,MAAAL,EACA,OAAAC,EACA,SAAU,CACR,QAAS,IACT,KAAM,IACN,MAAO,GACT,EACA,OAAQK,GAAiB,EACzB,UAAWC,GAAmB,EAC9B,cAAe,CAAC,CAAE,QAAS,SAAU,CAAC,EACtC,SAAU,wBACV,eAAgBC,EAAkB,EAClC,cAAeA,EAAkB,CAAE,aAAc,EAAM,CAAC,EACxD,WAAYC,EAAwB,CAClC,OAAQ,CAACC,EAA+B,CAAE,IAAK,GAAGC,CAAgB,IAAIX,CAAK,EAAG,CAAC,EAAGQ,EAAkB,CAAC,CACvG,CAAC,EACD,GAAGJ,CACL,CAAC,CACH","names":["createBrowserLocalStorageCache","options","storage","namespaceKey","getStorage","getNamespace","setNamespace","namespace","yieldToMain","resolve","getFilteredNamespace","timeToLive","currentTime","changed","cacheItem","key","defaultValue","events","cachedItem","value","createNullCache","_key","result","createFallbackableCache","caches","current","createMemoryCache","cache","keyAsString","promise","createAlgoliaAgent","version","algoliaAgent","options","addedAlgoliaAgent","createAuth","appId","apiKey","authMode","credentials","getAlgoliaAgent","algoliaAgents","client","version","defaultAlgoliaAgent","createAlgoliaAgent","algoliaAgent","createNullLogger","_message","_args","MAX_LINE_BUFFER_SIZE","readableStreamToAsyncIterable","stream","reader","done","value","toAsyncIterable","iterLines","decoder","buffer","bufferSize","trailingCR","isFirstLine","chunk","text","offset","crIdx","lfIdx","remaining","endIdx","skipLen","segment","line","SSEDecoder","colonIdx","field","currentEventType","event","iterSSEEvents","COMPRESSION_THRESHOLD","EXPIRATION_DELAY","createStatefulHost","host","status","lastUpdate","isUp","isTimedOut","AlgoliaError","message","name","ErrorWithStackTrace","AlgoliaError","message","stackTrace","name","RetryError","ApiError","status","DeserializationError","response","DetailedApiError","error","shuffle","array","shuffledArray","c","b","a","serializeUrl","host","path","queryParameters","queryParametersAsString","serializeQueryParameters","url","parameters","key","serializeData","request","requestOptions","data","serializeHeaders","baseHeaders","requestHeaders","requestOptionsHeaders","headers","serializedHeaders","header","value","deserializeSuccess","e","deserializeFailure","content","stackFrame","parsed","isNetworkError","isTimedOut","isRetryable","isSuccess","stackTraceWithoutCredentials","stackFrameWithoutCredentials","modifiedHeaders","createTransporter","hosts","hostsCache","logger","baseQueryParameters","algoliaAgent","timeouts","requester","requestsCache","responsesCache","compress","compression","createRetryableOptions","compatibleHosts","statefulHosts","compatibleHost","createStatefulHost","hostsUp","hostsTimedOut","hostsAvailable","timeoutsCount","baseTimeout","retryableRequest","isRead","serializedData","wantsCompression","COMPRESSION_THRESHOLD","shouldCompress","dataQueryParameters","retry","retryableHosts","getTimeout","timeout","payload","pushToStackTrace","options","createRequest","createRetryableRequest","err","_","requestStream","stream","iterSSEEvents","validateRequired","field","method","value","createXhrRequester","send","request","resolve","baseRequester","key","createTimeout","timeout","content","connectTimeout","responseTimeout","apiClientVersion","getDefaultHosts","appId","shuffle","createRecommendClient","appIdOption","apiKeyOption","authMode","algoliaAgents","options","auth","createAuth","transporter","createTransporter","getAlgoliaAgent","segment","version","apiKey","indexName","model","recommendRule","requestOptions","validateRequired","request","path","parameters","body","objectID","taskID","getRecommendationsParams","searchRecommendRulesParams","recommendClient","appId","apiKey","options","_compression","browserOptions","createRecommendClient","createNullLogger","m","createMemoryCache","createFallbackableCache","createBrowserLocalStorageCache","apiClientVersion"]}
|
|
@@ -4,9 +4,13 @@
|
|
|
4
4
|
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["@algolia/recommend"] = {}));
|
|
5
5
|
})(this, (function (exports) { 'use strict';
|
|
6
6
|
|
|
7
|
-
function z(r){let e,o=`algolia-client-js-${r.key}`;function t(){return e===void 0&&(e=r.localStorage||window.localStorage),e}function a(){return JSON.parse(t().getItem(o)||"{}")}function u(n){t().setItem(o,JSON.stringify(n));}function m(){return new Promise(n=>setTimeout(n,0))}function s(){let n=r.timeToLive?r.timeToLive*1e3:null,i=a(),c=new Date().getTime(),p=false;return {namespace:Object.fromEntries(Object.entries(i).filter(([,l])=>!l||l.timestamp===void 0||n&&l.timestamp+n<c?(p=true,false):true)),changed:p}}return {get(n,i,c={miss:()=>Promise.resolve()}){return m().then(()=>{let{namespace:p,changed:P}=s(),l=p[JSON.stringify(n)];return P&&u(p),l?l.value:i().then(f=>c.miss(f).then(()=>f))})},set(n,i){return m().then(()=>{let c=a();return c[JSON.stringify(n)]={timestamp:new Date().getTime(),value:i},t().setItem(o,JSON.stringify(c)),i})},delete(n){return m().then(()=>{let i=a();delete i[JSON.stringify(n)],t().setItem(o,JSON.stringify(i));})},clear(){return Promise.resolve().then(()=>{t().removeItem(o);})}}}function te(){return {get(r,e,o={miss:()=>Promise.resolve()}){return e().then(a=>Promise.all([a,o.miss(a)])).then(([a])=>a)},set(r,e){return Promise.resolve(e)},delete(r){return Promise.resolve()},clear(){return Promise.resolve()}}}function v(r){let e=[...r.caches],o=e.shift();return o===void 0?te():{get(t,a,u={miss:()=>Promise.resolve()}){return o.get(t,a,u).catch(()=>v({caches:e}).get(t,a,u))},set(t,a){return o.set(t,a).catch(()=>v({caches:e}).set(t,a))},delete(t){return o.delete(t).catch(()=>v({caches:e}).delete(t))},clear(){return o.clear().catch(()=>v({caches:e}).clear())}}}function O(r={serializable:true}){let e={};return {get(o,t,a={miss:()=>Promise.resolve()}){let u=JSON.stringify(o);if(u in e)return Promise.resolve(r.serializable?JSON.parse(e[u]):e[u]);let m=t();return m.then(s=>a.miss(s)).then(()=>m)},set(o,t){return e[JSON.stringify(o)]=r.serializable?JSON.stringify(t):t,Promise.resolve(t)},delete(o){return delete e[JSON.stringify(o)],Promise.resolve()},clear(){return e={},Promise.resolve()}}}function oe(r){let e={value:`Algolia for JavaScript (${r})`,add(o){let t=`; ${o.segment}${o.version!==void 0?` (${o.version})`:""}`;return e.value.indexOf(t)===-1&&(e.value=`${e.value}${t}`),e}};return e}function J(r,e,o="WithinHeaders"){let t={"x-algolia-api-key":e,"x-algolia-application-id":r};return {headers(){return o==="WithinHeaders"?t:{}},queryParameters(){return o==="WithinQueryParameters"?t:{}}}}function Q({algoliaAgents:r,client:e,version:o}){let t=oe(o).add({segment:e,version:o});return r.forEach(a=>t.add(a)),t}function M(){return {debug(r,e){return Promise.resolve()},info(r,e){return Promise.resolve()},error(r,e){return Promise.resolve()}}}var se=750,j=120*1e3;function W(r,e="up"){let o=Date.now();function t(){return e==="up"||Date.now()-o>j}function a(){return e==="timed out"&&Date.now()-o<=j}return {...r,status:e,lastUpdate:o,isUp:t,isTimedOut:a}}var F=class extends Error{name="AlgoliaError";constructor(r,e){super(r),e&&(this.name=e);}};var B=class extends F{stackTrace;constructor(r,e,o){super(r,o),this.stackTrace=e;}},ne=class extends B{constructor(r){super("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",r,"RetryError");}},U=class extends B{status;constructor(r,e,o,t="ApiError"){super(r,o,t),this.status=e;}},ae=class extends F{response;constructor(r,e){super(r,"DeserializationError"),this.response=e;}},ie=class extends U{error;constructor(r,e,o,t){super(r,e,t,"DetailedApiError"),this.error=o;}};function X(r){let e=r;for(let o=r.length-1;o>0;o--){let t=Math.floor(Math.random()*(o+1)),a=r[o];e[o]=r[t],e[t]=a;}return e}function me(r,e,o){let t=ce(o),a=`${r.protocol}://${r.url}${r.port?`:${r.port}`:""}/${e.charAt(0)==="/"?e.substring(1):e}`;return t.length&&(a+=`?${t}`),a}function ce(r){return Object.keys(r).filter(e=>r[e]!==void 0).sort().map(e=>`${e}=${encodeURIComponent(Object.prototype.toString.call(r[e])==="[object Array]"?r[e].join(","):r[e]).replace(/\+/g,"%20")}`).join("&")}function ue(r,e){if(r.method==="GET"||r.data===void 0&&e.data===void 0)return;let o=Array.isArray(r.data)?r.data:{...r.data,...e.data};return JSON.stringify(o)}function le(r,e,o){let t={Accept:"application/json",...r,...e,...o},a={};return Object.keys(t).forEach(u=>{let m=t[u];a[u.toLowerCase()]=m;}),a}function de(r){try{return JSON.parse(r.content)}catch(e){throw new ae(e.message,r)}}function pe({content:r,status:e},o){try{let t=JSON.parse(r);return "error"in t?new ie(t.message,e,t.error,o):new U(t.message,e,o)}catch{}return new U(r,e,o)}function fe({isTimedOut:r,status:e}){return !r&&~~e===0}function he({isTimedOut:r,status:e}){return r||fe({isTimedOut:r,status:e})||~~(e/100)!==2&&~~(e/100)!==4}function Re({status:r}){return ~~(r/100)===2}function Pe(r){return r.map(e=>K(e))}function K(r){let e=r.request.headers["x-algolia-api-key"]?{"x-algolia-api-key":"*****"}:{};return {...r,request:{...r.request,headers:{...r.request.headers,...e}}}}function V({hosts:r,hostsCache:e,baseHeaders:o,logger:t,baseQueryParameters:a,algoliaAgent:u,timeouts:m,requester:s,requestsCache:n,responsesCache:i,compress:c,compression:p}){async function P(h){let R=await Promise.all(h.map(d=>e.get(d,()=>Promise.resolve(W(d))))),E=R.filter(d=>d.isUp()),y=R.filter(d=>d.isTimedOut()),w=[...E,...y];return {hosts:w.length>0?w:h,getTimeout(d,T){return (y.length===0&&d===0?1:y.length+3+d)*T}}}async function l(h,R,E){let y=[],w=ue(h,R),x=le(o,h.headers,R.headers),d=p==="gzip"&&w!==void 0&&w.length>se&&(h.method==="POST"||h.method==="PUT");d&&c===void 0&&t.info("Compression is disabled because no compress method is available.");let T=d&&c!==void 0,_=T?await c(w):w;T&&(x["content-encoding"]="gzip");let ee=h.method==="GET"?{...h.data,...R.data}:{},S={...a,...h.queryParameters,...ee};if(u.value&&(S["x-algolia-agent"]=u.value),R&&R.queryParameters)for(let g of Object.keys(R.queryParameters))!R.queryParameters[g]||Object.prototype.toString.call(R.queryParameters[g])==="[object Object]"?S[g]=R.queryParameters[g]:S[g]=R.queryParameters[g].toString();let b=0,k=async(g,N)=>{let A=g.pop();if(A===void 0)throw new ne(Pe(y));let D={...m,...R.timeouts},L={data:_,headers:x,method:h.method,url:me(A,h.path,S),connectTimeout:N(b,D.connect),responseTimeout:N(b,E?D.read:D.write)},$=I=>{let G={request:L,response:I,host:A,triesLeft:g.length};return y.push(G),G},q=await s.send(L);if(he(q)){let I=$(q);return q.isTimedOut&&b++,t.info("Retryable failure",K(I)),await e.set(A,W(A,q.isTimedOut?"timed out":"down")),k(g,N)}if(Re(q))return de(q);throw $(q),pe(q,y)},re=r.filter(g=>g.accept==="readWrite"||(E?g.accept==="read":g.accept==="write")),H=await P(re);return k([...H.hosts].reverse(),H.getTimeout)}function f(h,R={}){let E=()=>l(h,R,y),y=h.useReadTransporter||h.method==="GET";if((R.cacheable||h.cacheable)!==true)return E();let x={request:h,requestOptions:R,transporter:{queryParameters:a,headers:o}};return i.get(x,()=>n.get(x,()=>n.set(x,E()).then(d=>Promise.all([n.delete(x),d]),d=>Promise.all([n.delete(x),Promise.reject(d)])).then(([d,T])=>T)),{miss:d=>i.set(x,d)})}return {hostsCache:e,requester:s,timeouts:m,logger:t,algoliaAgent:u,baseHeaders:o,baseQueryParameters:a,hosts:r,request:f,requestsCache:n,responsesCache:i}}function Y(){function r(e){return new Promise(o=>{let t=new XMLHttpRequest;t.open(e.method,e.url,true),Object.keys(e.headers).forEach(s=>t.setRequestHeader(s,e.headers[s]));let a=(s,n)=>setTimeout(()=>{t.abort(),o({status:0,content:n,isTimedOut:true});},s),u=a(e.connectTimeout,"Connection timeout"),m;t.onreadystatechange=()=>{t.readyState>t.OPENED&&m===void 0&&(clearTimeout(u),m=a(e.responseTimeout,"Socket timeout"));},t.onerror=()=>{t.status===0&&(clearTimeout(u),clearTimeout(m),o({content:t.responseText||"Network request failed",status:t.status,isTimedOut:false}));},t.onload=()=>{clearTimeout(u),clearTimeout(m),o({content:t.responseText,status:t.status,isTimedOut:false});},t.send(e.data);})}return {send:r}}var C="5.53.0";function ge(r){return [{url:`${r}-dsn.algolia.net`,accept:"read",protocol:"https"},{url:`${r}.algolia.net`,accept:"write",protocol:"https"}].concat(X([{url:`${r}-1.algolianet.com`,accept:"readWrite",protocol:"https"},{url:`${r}-2.algolianet.com`,accept:"readWrite",protocol:"https"},{url:`${r}-3.algolianet.com`,accept:"readWrite",protocol:"https"}]))}function Z({appId:r,apiKey:e,authMode:o,algoliaAgents:t,...a}){let u=J(r,e,o),m=V({hosts:ge(r),...a,algoliaAgent:Q({algoliaAgents:t,client:"Recommend",version:C}),baseHeaders:{"content-type":"text/plain",...u.headers(),...a.baseHeaders},baseQueryParameters:{...u.queryParameters(),...a.baseQueryParameters}});return {transporter:m,appId:r,apiKey:e,clearCache(){return Promise.all([m.requestsCache.clear(),m.responsesCache.clear()]).then(()=>{})},get _ua(){return m.algoliaAgent.value},addAlgoliaAgent(s,n){m.algoliaAgent.add({segment:s,version:n});},setClientApiKey({apiKey:s}){!o||o==="WithinHeaders"?m.baseHeaders["x-algolia-api-key"]=s:m.baseQueryParameters["x-algolia-api-key"]=s;},batchRecommendRules({indexName:s,model:n,recommendRule:i},c){if(!s)throw new Error("Parameter `indexName` is required when calling `batchRecommendRules`.");if(!n)throw new Error("Parameter `model` is required when calling `batchRecommendRules`.");let f={method:"POST",path:"/1/indexes/{indexName}/{model}/recommend/rules/batch".replace("{indexName}",encodeURIComponent(s)).replace("{model}",encodeURIComponent(n)),queryParameters:{},headers:{},data:i||{}};return m.request(f,c)},customDelete({path:s,parameters:n},i){if(!s)throw new Error("Parameter `path` is required when calling `customDelete`.");let l={method:"DELETE",path:"/{path}".replace("{path}",s),queryParameters:n||{},headers:{}};return m.request(l,i)},customGet({path:s,parameters:n},i){if(!s)throw new Error("Parameter `path` is required when calling `customGet`.");let l={method:"GET",path:"/{path}".replace("{path}",s),queryParameters:n||{},headers:{}};return m.request(l,i)},customPost({path:s,parameters:n,body:i},c){if(!s)throw new Error("Parameter `path` is required when calling `customPost`.");let f={method:"POST",path:"/{path}".replace("{path}",s),queryParameters:n||{},headers:{},data:i||{}};return m.request(f,c)},customPut({path:s,parameters:n,body:i},c){if(!s)throw new Error("Parameter `path` is required when calling `customPut`.");let f={method:"PUT",path:"/{path}".replace("{path}",s),queryParameters:n||{},headers:{},data:i||{}};return m.request(f,c)},deleteRecommendRule({indexName:s,model:n,objectID:i},c){if(!s)throw new Error("Parameter `indexName` is required when calling `deleteRecommendRule`.");if(!n)throw new Error("Parameter `model` is required when calling `deleteRecommendRule`.");if(!i)throw new Error("Parameter `objectID` is required when calling `deleteRecommendRule`.");let f={method:"DELETE",path:"/1/indexes/{indexName}/{model}/recommend/rules/{objectID}".replace("{indexName}",encodeURIComponent(s)).replace("{model}",encodeURIComponent(n)).replace("{objectID}",encodeURIComponent(i)),queryParameters:{},headers:{}};return m.request(f,c)},getRecommendRule({indexName:s,model:n,objectID:i},c){if(!s)throw new Error("Parameter `indexName` is required when calling `getRecommendRule`.");if(!n)throw new Error("Parameter `model` is required when calling `getRecommendRule`.");if(!i)throw new Error("Parameter `objectID` is required when calling `getRecommendRule`.");let f={method:"GET",path:"/1/indexes/{indexName}/{model}/recommend/rules/{objectID}".replace("{indexName}",encodeURIComponent(s)).replace("{model}",encodeURIComponent(n)).replace("{objectID}",encodeURIComponent(i)),queryParameters:{},headers:{}};return m.request(f,c)},getRecommendStatus({indexName:s,model:n,taskID:i},c){if(!s)throw new Error("Parameter `indexName` is required when calling `getRecommendStatus`.");if(!n)throw new Error("Parameter `model` is required when calling `getRecommendStatus`.");if(!i)throw new Error("Parameter `taskID` is required when calling `getRecommendStatus`.");let f={method:"GET",path:"/1/indexes/{indexName}/{model}/task/{taskID}".replace("{indexName}",encodeURIComponent(s)).replace("{model}",encodeURIComponent(n)).replace("{taskID}",encodeURIComponent(i)),queryParameters:{},headers:{}};return m.request(f,c)},getRecommendations(s,n){if(s&&Array.isArray(s)&&(s={requests:s}),!s)throw new Error("Parameter `getRecommendationsParams` is required when calling `getRecommendations`.");if(!s.requests)throw new Error("Parameter `getRecommendationsParams.requests` is required when calling `getRecommendations`.");let P={method:"POST",path:"/1/indexes/*/recommendations",queryParameters:{},headers:{},data:s,useReadTransporter:true,cacheable:true};return m.request(P,n)},searchRecommendRules({indexName:s,model:n,searchRecommendRulesParams:i},c){if(!s)throw new Error("Parameter `indexName` is required when calling `searchRecommendRules`.");if(!n)throw new Error("Parameter `model` is required when calling `searchRecommendRules`.");let f={method:"POST",path:"/1/indexes/{indexName}/{model}/recommend/rules/search".replace("{indexName}",encodeURIComponent(s)).replace("{model}",encodeURIComponent(n)),queryParameters:{},headers:{},data:i||{},useReadTransporter:true,cacheable:true};return m.request(f,c)}}}function qt(r,e,o){if(!r||typeof r!="string")throw new Error("`appId` is missing.");if(!e||typeof e!="string")throw new Error("`apiKey` is missing.");let{compression:t,...a}=o||{};return Z({appId:r,apiKey:e,timeouts:{connect:1e3,read:2e3,write:3e4},logger:M(),requester:Y(),algoliaAgents:[{segment:"Browser"}],authMode:"WithinQueryParameters",responsesCache:O(),requestsCache:O({serializable:false}),hostsCache:v({caches:[z({key:`${C}-${r}`}),O()]}),...a})}
|
|
7
|
+
function V(e){let t,r=`algolia-client-js-${e.key}`;function o(){return t===void 0&&(t=e.localStorage||window.localStorage),t}function i(){return JSON.parse(o().getItem(r)||"{}")}function d(s){o().setItem(r,JSON.stringify(s));}function c(){return new Promise(s=>setTimeout(s,0))}function n(){let s=e.timeToLive?e.timeToLive*1e3:null,a=i(),m=new Date().getTime(),f=false;return {namespace:Object.fromEntries(Object.entries(a).filter(([,p])=>!p||p.timestamp===void 0||s&&p.timestamp+s<m?(f=true,false):true)),changed:f}}return {get(s,a,m={miss:()=>Promise.resolve()}){return c().then(()=>{let{namespace:f,changed:R}=n(),p=f[JSON.stringify(s)];return R&&d(f),p?p.value:a().then(x=>m.miss(x).then(()=>x))})},set(s,a){return c().then(()=>{let m=i();return m[JSON.stringify(s)]={timestamp:new Date().getTime(),value:a},o().setItem(r,JSON.stringify(m)),a})},delete(s){return c().then(()=>{let a=i();delete a[JSON.stringify(s)],o().setItem(r,JSON.stringify(a));})},clear(){return Promise.resolve().then(()=>{o().removeItem(r);})}}}function ce(){return {get(e,t,r={miss:()=>Promise.resolve()}){return t().then(i=>Promise.all([i,r.miss(i)])).then(([i])=>i)},set(e,t){return Promise.resolve(t)},delete(e){return Promise.resolve()},clear(){return Promise.resolve()}}}function C(e){let t=[...e.caches],r=t.shift();return r===void 0?ce():{get(o,i,d={miss:()=>Promise.resolve()}){return r.get(o,i,d).catch(()=>C({caches:t}).get(o,i,d))},set(o,i){return r.set(o,i).catch(()=>C({caches:t}).set(o,i))},delete(o){return r.delete(o).catch(()=>C({caches:t}).delete(o))},clear(){return r.clear().catch(()=>C({caches:t}).clear())}}}function k(e={serializable:true}){let t={};return {get(r,o,i={miss:()=>Promise.resolve()}){let d=JSON.stringify(r);if(d in t)return Promise.resolve(e.serializable?JSON.parse(t[d]):t[d]);let c=o();return c.then(n=>i.miss(n)).then(()=>c)},set(r,o){return t[JSON.stringify(r)]=e.serializable?JSON.stringify(o):o,Promise.resolve(o)},delete(r){return delete t[JSON.stringify(r)],Promise.resolve()},clear(){return t={},Promise.resolve()}}}function me(e){let t={value:`Algolia for JavaScript (${e})`,add(r){let o=`; ${r.segment}${r.version!==void 0?` (${r.version})`:""}`;return t.value.indexOf(o)===-1&&(t.value=`${t.value}${o}`),t}};return t}function Y(e,t,r="WithinHeaders"){let o={"x-algolia-api-key":t,"x-algolia-application-id":e};return {headers(){return r==="WithinHeaders"?o:{}},queryParameters(){return r==="WithinQueryParameters"?o:{}}}}function Z({algoliaAgents:e,client:t,version:r}){let o=me(r).add({segment:t,version:r});return e.forEach(i=>o.add(i)),o}function ee(){return {debug(e,t){return Promise.resolve()},info(e,t){return Promise.resolve()},error(e,t){return Promise.resolve()}}}var ue=10*1024*1024;async function*le(e){let t=e.getReader();try{for(;;){let{done:r,value:o}=await t.read();if(r)return;yield o;}}finally{t.releaseLock();}}function de(e){return Symbol.asyncIterator in e?e:le(e)}async function*pe(e){let t=new TextDecoder("utf-8"),r=[],o=0,i=false,d=true;for await(let n of de(e)){let s=t.decode(n,{stream:true}),a=0;for(i&&(i=false,s.length>0&&s[0]===`
|
|
8
|
+
`&&(a=1));a<s.length;){let m=s.indexOf("\r",a),f=s.indexOf(`
|
|
9
|
+
`,a);if(m===-1&&f===-1){let u=s.slice(a);if(r.push(u),o+=u.length,o>ue)throw new Error("SSE line buffer exceeded 10MB");break}let R,p;m!==-1&&(f===-1||m<f)?(R=m,m+1<s.length?p=s[m+1]===`
|
|
10
|
+
`?2:1:(i=true,p=1)):(R=f,p=1);let x=s.slice(a,R);r.push(x);let A=r.length===1?r[0]:r.join("");r.length=0,o=0,d&&(A.startsWith("\uFEFF")&&(A=A.slice(1)),d=false),yield A,a=R+p;}}let c=t.decode();if(c&&r.push(c),r.length>0){let n=r.join("");d&&n.startsWith("\uFEFF")&&(n=n.slice(1)),yield n;}}var fe=class{data=[];eventType="";lastEventId=null;retry=null;decode(e){if(e==="")return this.dispatch();if(e[0]===":")return null;let t=e.indexOf(":"),r,o;switch(t===-1?(r=e,o=""):(r=e.slice(0,t),o=e.slice(t+1),o[0]===" "&&(o=o.slice(1))),r){case "data":this.data.push(o);break;case "event":this.eventType=o;break;case "id":o.includes("\0")||(this.lastEventId=o);break;case "retry":/^[0-9]+$/.test(o)&&(this.retry=parseInt(o,10));break}return null}dispatch(){let e=this.eventType;if(this.eventType="",this.data.length===0)return null;let t={data:this.data.join(`
|
|
11
|
+
`),event:e,id:this.lastEventId,retry:this.retry};return this.data=[],t}};async function*he(e){let t=new fe;for await(let r of pe(e)){let o=t.decode(r);o!==null&&(yield o);}}var Re=750,J=120*1e3;function M(e,t="up"){let r=Date.now();function o(){return t==="up"||Date.now()-r>J}function i(){return t==="timed out"&&Date.now()-r<=J}return {...e,status:t,lastUpdate:r,isUp:o,isTimedOut:i}}var te=class extends Error{name="AlgoliaError";constructor(e,t){super(e),t&&(this.name=t);}};var re=class extends te{stackTrace;constructor(e,t,r){super(e,r),this.stackTrace=t;}},Q=class extends re{constructor(e){super("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",e,"RetryError");}},j=class extends re{status;constructor(e,t,r,o="ApiError"){super(e,r,o),this.status=t;}},xe=class extends te{response;constructor(e,t){super(e,"DeserializationError"),this.response=t;}},ge=class extends j{error;constructor(e,t,r,o){super(e,t,o,"DetailedApiError"),this.error=r;}};function oe(e){let t=e;for(let r=e.length-1;r>0;r--){let o=Math.floor(Math.random()*(r+1)),i=e[r];t[r]=e[o],t[o]=i;}return t}function B(e,t,r){let o=ye(r),i=`${e.protocol}://${e.url}${e.port?`:${e.port}`:""}/${t.charAt(0)==="/"?t.substring(1):t}`;return o.length&&(i+=`?${o}`),i}function ye(e){return Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${t}=${encodeURIComponent(Object.prototype.toString.call(e[t])==="[object Array]"?e[t].join(","):e[t]).replace(/\+/g,"%20")}`).join("&")}function X(e,t){if(e.method==="GET"||e.data===void 0&&t.data===void 0)return;let r=Array.isArray(e.data)?e.data:{...e.data,...t.data};return JSON.stringify(r)}function K(e,t,r){let o={Accept:"application/json",...e,...t,...r},i={};return Object.keys(o).forEach(d=>{let c=o[d];i[d.toLowerCase()]=c;}),i}function Pe(e){if(!(e.status===204||e.content.length===0))try{return JSON.parse(e.content)}catch(t){throw new xe(t.message,e)}}function Te({content:e,status:t},r){try{let o=JSON.parse(e);return "error"in o?new ge(o.message,t,o.error,r):new j(o.message,t,r)}catch{}return new j(e,t,r)}function ve({isTimedOut:e,status:t}){return !e&&~~t===0}function Ee({isTimedOut:e,status:t}){return e||ve({isTimedOut:e,status:t})||~~(t/100)!==2&&~~(t/100)!==4}function qe({status:e}){return ~~(e/100)===2}function we(e){return e.map(t=>se(t))}function se(e){let t=e.request.headers["x-algolia-api-key"]?{"x-algolia-api-key":"*****"}:{};return {...e,request:{...e.request,headers:{...e.request.headers,...t}}}}function ne({hosts:e,hostsCache:t,baseHeaders:r,logger:o,baseQueryParameters:i,algoliaAgent:d,timeouts:c,requester:n,requestsCache:s,responsesCache:a,compress:m,compression:f}){async function R(u){let l=await Promise.all(u.map(h=>t.get(h,()=>Promise.resolve(M(h))))),q=l.filter(h=>h.isUp()),T=l.filter(h=>h.isTimedOut()),E=[...q,...T];return {hosts:E.length>0?E:u,getTimeout(h,w){return (T.length===0&&h===0?1:T.length+3+h)*w}}}async function p(u,l,q){let T=[],E=X(u,l),y=K(r,u.headers,l.headers),h=f==="gzip"&&E!==void 0&&E.length>Re&&(u.method==="POST"||u.method==="PUT");h&&m===void 0&&o.info("Compression is disabled because no compress method is available.");let w=h&&m!==void 0,_=w?await m(E):E;w&&(y["content-encoding"]="gzip");let N=u.method==="GET"?{...u.data,...l.data}:{},S={...i,...u.queryParameters,...N};if(d.value&&(S["x-algolia-agent"]=d.value),l&&l.queryParameters)for(let P of Object.keys(l.queryParameters))!l.queryParameters[P]||Object.prototype.toString.call(l.queryParameters[P])==="[object Object]"?S[P]=l.queryParameters[P]:S[P]=l.queryParameters[P].toString();let I=0,D=async(P,L)=>{let O=P.pop();if(O===void 0)throw new Q(we(T));let H={...c,...l.timeouts},W={data:_,headers:y,method:u.method,url:B(O,u.path,S),connectTimeout:L(I,H.connect),responseTimeout:L(I,q?H.read:H.write)},F=$=>{let z={request:W,response:$,host:O,triesLeft:P.length};return T.push(z),z},b=await n.send(W);if(Ee(b)){let $=F(b);return b.isTimedOut&&I++,o.info("Retryable failure",se($)),await t.set(O,M(O,b.isTimedOut?"timed out":"down")),D(P,L)}if(qe(b))return Pe(b);throw F(b),Te(b,T)},v=e.filter(P=>P.accept==="readWrite"||(q?P.accept==="read":P.accept==="write")),G=await R(v);return D([...G.hosts].reverse(),G.getTimeout)}function x(u,l={}){let q=()=>p(u,l,T),T=u.useReadTransporter||u.method==="GET";if((l.cacheable||u.cacheable)!==true)return q();let y={request:u,requestOptions:l,transporter:{queryParameters:i,headers:r}};return a.get(y,()=>s.get(y,()=>s.set(y,q()).then(h=>Promise.all([s.delete(y),h]),h=>Promise.all([s.delete(y),Promise.reject(h)])).then(([h,w])=>w)),{miss:h=>a.set(y,h)})}async function*A(u,l={}){if(!n.sendStream)throw new Error("This requester does not support streaming");let q=X(u,l),T=K(r,u.headers,l.headers);T.accept="text/event-stream";let E=u.method==="GET"?{...u.data,...l.data}:{},y={...i,...u.queryParameters,...E};if(d.value&&(y["x-algolia-agent"]=d.value),l&&l.queryParameters)for(let v of Object.keys(l.queryParameters))!l.queryParameters[v]||Object.prototype.toString.call(l.queryParameters[v])==="[object Object]"?y[v]=l.queryParameters[v]:y[v]=l.queryParameters[v].toString();let h=u.useReadTransporter||u.method==="GET",w=e.filter(v=>v.accept==="readWrite"||(h?v.accept==="read":v.accept==="write")),N=(await R(w)).hosts[0];if(!N)throw new Q([]);let S={...c,...l.timeouts},I={data:q,headers:T,method:u.method,url:B(N,u.path,y),connectTimeout:S.connect,responseTimeout:h?S.read:S.write},D=await n.sendStream(I);yield*he(D);}return {hostsCache:t,requester:n,timeouts:c,logger:o,algoliaAgent:d,baseHeaders:r,baseQueryParameters:i,hosts:e,request:x,requestStream:A,requestsCache:s,responsesCache:a}}function g(e,t,r){if(r==null||typeof r=="string"&&r.length===0)throw new Error(`Parameter \`${e}\` is required when calling \`${t}\`.`)}function ae(){function e(t){return new Promise(r=>{let o=new XMLHttpRequest;o.open(t.method,t.url,true),Object.keys(t.headers).forEach(n=>o.setRequestHeader(n,t.headers[n]));let i=(n,s)=>setTimeout(()=>{o.abort(),r({status:0,content:s,isTimedOut:true});},n),d=i(t.connectTimeout,"Connection timeout"),c;o.onreadystatechange=()=>{o.readyState>o.OPENED&&c===void 0&&(clearTimeout(d),c=i(t.responseTimeout,"Socket timeout"));},o.onerror=()=>{o.status===0&&(clearTimeout(d),clearTimeout(c),r({content:o.responseText||"Network request failed",status:o.status,isTimedOut:false}));},o.onload=()=>{clearTimeout(d),clearTimeout(c),r({content:o.responseText,status:o.status,isTimedOut:false});},o.send(t.data);})}return {send:e}}var U="5.54.0";function Se(e){return [{url:`${e}-dsn.algolia.net`,accept:"read",protocol:"https"},{url:`${e}.algolia.net`,accept:"write",protocol:"https"}].concat(oe([{url:`${e}-1.algolianet.com`,accept:"readWrite",protocol:"https"},{url:`${e}-2.algolianet.com`,accept:"readWrite",protocol:"https"},{url:`${e}-3.algolianet.com`,accept:"readWrite",protocol:"https"}]))}function ie({appId:e,apiKey:t,authMode:r,algoliaAgents:o,...i}){let d=Y(e,t,r),c=ne({hosts:Se(e),...i,algoliaAgent:Z({algoliaAgents:o,client:"Recommend",version:U}),baseHeaders:{"content-type":"text/plain",...d.headers(),...i.baseHeaders},baseQueryParameters:{...d.queryParameters(),...i.baseQueryParameters}});return {transporter:c,appId:e,apiKey:t,clearCache(){return Promise.all([c.requestsCache.clear(),c.responsesCache.clear()]).then(()=>{})},get _ua(){return c.algoliaAgent.value},addAlgoliaAgent(n,s){c.algoliaAgent.add({segment:n,version:s});},setClientApiKey({apiKey:n}){!r||r==="WithinHeaders"?c.baseHeaders["x-algolia-api-key"]=n:c.baseQueryParameters["x-algolia-api-key"]=n;},batchRecommendRules({indexName:n,model:s,recommendRule:a},m){g("indexName","batchRecommendRules",n),g("model","batchRecommendRules",s);let x={method:"POST",path:"/1/indexes/{indexName}/{model}/recommend/rules/batch".replace("{indexName}",encodeURIComponent(n)).replace("{model}",encodeURIComponent(s)),queryParameters:{},headers:{},data:a||{}};return c.request(x,m)},customDelete({path:n,parameters:s},a){g("path","customDelete",n);let p={method:"DELETE",path:"/{path}".replace("{path}",n),queryParameters:s||{},headers:{}};return c.request(p,a)},customGet({path:n,parameters:s},a){g("path","customGet",n);let p={method:"GET",path:"/{path}".replace("{path}",n),queryParameters:s||{},headers:{}};return c.request(p,a)},customPost({path:n,parameters:s,body:a},m){g("path","customPost",n);let x={method:"POST",path:"/{path}".replace("{path}",n),queryParameters:s||{},headers:{},data:a||{}};return c.request(x,m)},customPut({path:n,parameters:s,body:a},m){g("path","customPut",n);let x={method:"PUT",path:"/{path}".replace("{path}",n),queryParameters:s||{},headers:{},data:a||{}};return c.request(x,m)},deleteRecommendRule({indexName:n,model:s,objectID:a},m){g("indexName","deleteRecommendRule",n),g("model","deleteRecommendRule",s),g("objectID","deleteRecommendRule",a);let x={method:"DELETE",path:"/1/indexes/{indexName}/{model}/recommend/rules/{objectID}".replace("{indexName}",encodeURIComponent(n)).replace("{model}",encodeURIComponent(s)).replace("{objectID}",encodeURIComponent(a)),queryParameters:{},headers:{}};return c.request(x,m)},getRecommendRule({indexName:n,model:s,objectID:a},m){g("indexName","getRecommendRule",n),g("model","getRecommendRule",s),g("objectID","getRecommendRule",a);let x={method:"GET",path:"/1/indexes/{indexName}/{model}/recommend/rules/{objectID}".replace("{indexName}",encodeURIComponent(n)).replace("{model}",encodeURIComponent(s)).replace("{objectID}",encodeURIComponent(a)),queryParameters:{},headers:{}};return c.request(x,m)},getRecommendStatus({indexName:n,model:s,taskID:a},m){g("indexName","getRecommendStatus",n),g("model","getRecommendStatus",s),g("taskID","getRecommendStatus",a);let x={method:"GET",path:"/1/indexes/{indexName}/{model}/task/{taskID}".replace("{indexName}",encodeURIComponent(n)).replace("{model}",encodeURIComponent(s)).replace("{taskID}",encodeURIComponent(a)),queryParameters:{},headers:{}};return c.request(x,m)},getRecommendations(n,s){n&&Array.isArray(n)&&(n={requests:n}),g("getRecommendationsParams","getRecommendations",n),g("getRecommendationsParams.requests","getRecommendations",n.requests);let R={method:"POST",path:"/1/indexes/*/recommendations",queryParameters:{},headers:{},data:n,useReadTransporter:true,cacheable:true};return c.request(R,s)},searchRecommendRules({indexName:n,model:s,searchRecommendRulesParams:a},m){g("indexName","searchRecommendRules",n),g("model","searchRecommendRules",s);let x={method:"POST",path:"/1/indexes/{indexName}/{model}/recommend/rules/search".replace("{indexName}",encodeURIComponent(n)).replace("{model}",encodeURIComponent(s)),queryParameters:{},headers:{},data:a||{},useReadTransporter:true,cacheable:true};return c.request(x,m)}}}function Or(e,t,r){if(!e||typeof e!="string")throw new Error("`appId` is missing.");if(!t||typeof t!="string")throw new Error("`apiKey` is missing.");let{compression:o,...i}=r||{};return ie({appId:e,apiKey:t,timeouts:{connect:1e3,read:2e3,write:3e4},logger:ee(),requester:ae(),algoliaAgents:[{segment:"Browser"}],authMode:"WithinQueryParameters",responsesCache:k(),requestsCache:k({serializable:false}),hostsCache:C({caches:[V({key:`${U}-${e}`}),k()]}),...i})}
|
|
8
12
|
|
|
9
|
-
exports.apiClientVersion =
|
|
10
|
-
exports.recommendClient =
|
|
13
|
+
exports.apiClientVersion = U;
|
|
14
|
+
exports.recommendClient = Or;
|
|
11
15
|
|
|
12
16
|
}));
|