Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@algolia/client-common

Package Overview
Dependencies
Maintainers
3
Versions
237
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@algolia/client-common - npm Package Compare versions

Comparing version 5.10.0 to 5.10.1

988

dist/common.d.ts

@@ -1,586 +0,450 @@

// src/cache/createBrowserLocalStorageCache.ts
function createBrowserLocalStorageCache(options) {
let storage;
const namespaceKey = `algolia-client-js-${options.key}`;
function getStorage() {
if (storage === void 0) {
storage = options.localStorage || window.localStorage;
}
return storage;
}
function getNamespace() {
return JSON.parse(getStorage().getItem(namespaceKey) || "{}");
}
function setNamespace(namespace) {
getStorage().setItem(namespaceKey, JSON.stringify(namespace));
}
function removeOutdatedCacheItems() {
const timeToLive = options.timeToLive ? options.timeToLive * 1e3 : null;
const namespace = getNamespace();
const filteredNamespaceWithoutOldFormattedCacheItems = Object.fromEntries(
Object.entries(namespace).filter(([, cacheItem]) => {
return cacheItem.timestamp !== void 0;
})
);
setNamespace(filteredNamespaceWithoutOldFormattedCacheItems);
if (!timeToLive) {
return;
}
const filteredNamespaceWithoutExpiredItems = Object.fromEntries(
Object.entries(filteredNamespaceWithoutOldFormattedCacheItems).filter(([, cacheItem]) => {
const currentTimestamp = (/* @__PURE__ */ new Date()).getTime();
const isExpired = cacheItem.timestamp + timeToLive < currentTimestamp;
return !isExpired;
})
);
setNamespace(filteredNamespaceWithoutExpiredItems);
}
return {
get(key, defaultValue, events = {
miss: () => Promise.resolve()
}) {
return Promise.resolve().then(() => {
removeOutdatedCacheItems();
return getNamespace()[JSON.stringify(key)];
}).then((value) => {
return Promise.all([value ? value.value : defaultValue(), value !== void 0]);
}).then(([value, exists]) => {
return Promise.all([value, exists || events.miss(value)]);
}).then(([value]) => value);
},
set(key, value) {
return Promise.resolve().then(() => {
const namespace = getNamespace();
namespace[JSON.stringify(key)] = {
timestamp: (/* @__PURE__ */ new Date()).getTime(),
value
};
getStorage().setItem(namespaceKey, JSON.stringify(namespace));
return value;
});
},
delete(key) {
return Promise.resolve().then(() => {
const namespace = getNamespace();
delete namespace[JSON.stringify(key)];
getStorage().setItem(namespaceKey, JSON.stringify(namespace));
});
},
clear() {
return Promise.resolve().then(() => {
getStorage().removeItem(namespaceKey);
});
}
};
}
type Cache = {
/**
* Gets the value of the given `key`.
*/
get: <TValue>(key: Record<string, any> | string, defaultValue: () => Promise<TValue>, events?: CacheEvents<TValue>) => Promise<TValue>;
/**
* Sets the given value with the given `key`.
*/
set: <TValue>(key: Record<string, any> | string, value: TValue) => Promise<TValue>;
/**
* Deletes the given `key`.
*/
delete: (key: Record<string, any> | string) => Promise<void>;
/**
* Clears the cache.
*/
clear: () => Promise<void>;
};
type CacheEvents<TValue> = {
/**
* The callback when the given `key` is missing from the cache.
*/
miss: (value: TValue) => Promise<any>;
};
type MemoryCacheOptions = {
/**
* If keys and values should be serialized using `JSON.stringify`.
*/
serializable?: boolean;
};
type BrowserLocalStorageOptions = {
/**
* The cache key.
*/
key: string;
/**
* The time to live for each cached item in seconds.
*/
timeToLive?: number;
/**
* The native local storage implementation.
*/
localStorage?: Storage;
};
type BrowserLocalStorageCacheItem = {
/**
* The cache item creation timestamp.
*/
timestamp: number;
/**
* The cache item value.
*/
value: any;
};
type FallbackableCacheOptions = {
/**
* List of caches order by priority.
*/
caches: Cache[];
};
// src/cache/createNullCache.ts
function createNullCache() {
return {
get(_key, defaultValue, events = {
miss: () => Promise.resolve()
}) {
const value = defaultValue();
return value.then((result) => Promise.all([result, events.miss(result)])).then(([result]) => result);
},
set(_key, value) {
return Promise.resolve(value);
},
delete(_key) {
return Promise.resolve();
},
clear() {
return Promise.resolve();
}
};
}
type Host = {
/**
* The host URL.
*/
url: string;
/**
* The accepted transporter.
*/
accept: 'read' | 'readWrite' | 'write';
/**
* The protocol of the host URL.
*/
protocol: 'http' | 'https';
/**
* The port of the host URL.
*/
port?: number;
};
type StatefulHost = Host & {
/**
* The status of the host.
*/
status: 'down' | 'timed out' | 'up';
/**
* The last update of the host status, used to compare with the expiration delay.
*/
lastUpdate: number;
/**
* Returns whether the host is up or not.
*/
isUp: () => boolean;
/**
* Returns whether the host is timed out or not.
*/
isTimedOut: () => boolean;
};
// src/cache/createFallbackableCache.ts
function createFallbackableCache(options) {
const caches = [...options.caches];
const current = caches.shift();
if (current === void 0) {
return createNullCache();
}
return {
get(key, defaultValue, events = {
miss: () => Promise.resolve()
}) {
return current.get(key, defaultValue, events).catch(() => {
return createFallbackableCache({ caches }).get(key, defaultValue, events);
});
},
set(key, value) {
return current.set(key, value).catch(() => {
return createFallbackableCache({ caches }).set(key, value);
});
},
delete(key) {
return current.delete(key).catch(() => {
return createFallbackableCache({ caches }).delete(key);
});
},
clear() {
return current.clear().catch(() => {
return createFallbackableCache({ caches }).clear();
});
}
};
}
declare const LogLevelEnum: Readonly<Record<string, LogLevelType>>;
type LogLevelType = 1 | 2 | 3;
type Logger = {
/**
* Logs debug messages.
*/
debug: (message: string, args?: any) => Promise<void>;
/**
* Logs info messages.
*/
info: (message: string, args?: any) => Promise<void>;
/**
* Logs error messages.
*/
error: (message: string, args?: any) => Promise<void>;
};
// src/cache/createMemoryCache.ts
function createMemoryCache(options = { serializable: true }) {
let cache = {};
return {
get(key, defaultValue, events = {
miss: () => Promise.resolve()
}) {
const keyAsString = JSON.stringify(key);
if (keyAsString in cache) {
return Promise.resolve(options.serializable ? JSON.parse(cache[keyAsString]) : cache[keyAsString]);
}
const promise = defaultValue();
return promise.then((value) => events.miss(value)).then(() => promise);
},
set(key, value) {
cache[JSON.stringify(key)] = options.serializable ? JSON.stringify(value) : value;
return Promise.resolve(value);
},
delete(key) {
delete cache[JSON.stringify(key)];
return Promise.resolve();
},
clear() {
cache = {};
return Promise.resolve();
}
};
}
type Headers = Record<string, string>;
type QueryParameters = Record<string, any>;
/**
* The method of the request.
*/
type Method = 'DELETE' | 'GET' | 'PATCH' | 'POST' | 'PUT';
type Request = {
method: Method;
/**
* The path of the REST API to send the request to.
*/
path: string;
queryParameters: QueryParameters;
data?: Array<Record<string, any>> | Record<string, any>;
headers: Headers;
/**
* If the given request should persist on the cache. Keep in mind,
* that some methods may have this option enabled by default.
*/
cacheable?: boolean;
/**
* Some POST methods in the Algolia REST API uses the `read` transporter.
* This information is defined at the spec level.
*/
useReadTransporter?: boolean;
};
type EndRequest = Pick<Request, 'headers' | 'method'> & {
/**
* The full URL of the REST API.
*/
url: string;
/**
* The connection timeout, in milliseconds.
*/
connectTimeout: number;
/**
* The response timeout, in milliseconds.
*/
responseTimeout: number;
data?: string;
};
type Response = {
/**
* The body of the response.
*/
content: string;
/**
* Whether the API call is timed out or not.
*/
isTimedOut: boolean;
/**
* The HTTP status code of the response.
*/
status: number;
};
type Requester = {
/**
* Sends the given `request` to the server.
*/
send: (request: EndRequest) => Promise<Response>;
};
// src/constants.ts
var DEFAULT_CONNECT_TIMEOUT_BROWSER = 1e3;
var DEFAULT_READ_TIMEOUT_BROWSER = 2e3;
var DEFAULT_WRITE_TIMEOUT_BROWSER = 3e4;
var DEFAULT_CONNECT_TIMEOUT_NODE = 2e3;
var DEFAULT_READ_TIMEOUT_NODE = 5e3;
var DEFAULT_WRITE_TIMEOUT_NODE = 3e4;
type RequestOptions = Pick<Request, 'cacheable'> & {
/**
* Custom timeout for the request. Note that, in normal situations
* the given timeout will be applied. But the transporter layer may
* increase this timeout if there is need for it.
*/
timeouts?: Partial<Timeouts>;
/**
* Custom headers for the request. This headers are
* going to be merged the transporter headers.
*/
headers?: Headers;
/**
* Custom query parameters for the request. This query parameters are
* going to be merged the transporter query parameters.
*/
queryParameters?: QueryParameters;
/**
* Custom data for the request. This data is
* going to be merged the transporter data.
*/
data?: Array<Record<string, any>> | Record<string, any>;
};
type StackFrame = {
request: EndRequest;
response: Response;
host: Host;
triesLeft: number;
};
type AlgoliaAgentOptions = {
/**
* The segment. Usually the integration name.
*/
segment: string;
/**
* The version. Usually the integration version.
*/
version?: string;
};
type AlgoliaAgent = {
/**
* The raw value of the user agent.
*/
value: string;
/**
* Mutates the current user agent adding the given user agent options.
*/
add: (options: AlgoliaAgentOptions) => AlgoliaAgent;
};
type Timeouts = {
/**
* Timeout in milliseconds before the connection is established.
*/
connect: number;
/**
* Timeout in milliseconds before reading the response on a read request.
*/
read: number;
/**
* Timeout in milliseconds before reading the response on a write request.
*/
write: number;
};
type TransporterOptions = {
/**
* The cache of the hosts. Usually used to persist
* the state of the host when its down.
*/
hostsCache: Cache;
/**
* The logger instance to send events of the transporter.
*/
logger: Logger;
/**
* The underlying requester used. Should differ
* depending of the environment where the client
* will be used.
*/
requester: Requester;
/**
* The cache of the requests. When requests are
* `cacheable`, the returned promised persists
* in this cache to shared in similar requests
* before being resolved.
*/
requestsCache: Cache;
/**
* The cache of the responses. When requests are
* `cacheable`, the returned responses persists
* in this cache to shared in similar requests.
*/
responsesCache: Cache;
/**
* The timeouts used by the requester. The transporter
* layer may increase this timeouts as defined on the
* retry strategy.
*/
timeouts: Timeouts;
/**
* The hosts used by the requester.
*/
hosts: Host[];
/**
* The headers used by the requester. The transporter
* layer may add some extra headers during the request
* for the user agent, and others.
*/
baseHeaders: Headers;
/**
* The query parameters used by the requester. The transporter
* layer may add some extra headers during the request
* for the user agent, and others.
*/
baseQueryParameters: QueryParameters;
/**
* The user agent used. Sent on query parameters.
*/
algoliaAgent: AlgoliaAgent;
};
type Transporter = TransporterOptions & {
/**
* Performs a request.
* The `baseRequest` and `baseRequestOptions` will be merged accordingly.
*/
request: <TResponse>(baseRequest: Request, baseRequestOptions?: RequestOptions) => Promise<TResponse>;
};
// src/createAlgoliaAgent.ts
function createAlgoliaAgent(version) {
const algoliaAgent = {
value: `Algolia for JavaScript (${version})`,
add(options) {
const addedAlgoliaAgent = `; ${options.segment}${options.version !== void 0 ? ` (${options.version})` : ""}`;
if (algoliaAgent.value.indexOf(addedAlgoliaAgent) === -1) {
algoliaAgent.value = `${algoliaAgent.value}${addedAlgoliaAgent}`;
}
return algoliaAgent;
}
};
return algoliaAgent;
}
type AuthMode = 'WithinHeaders' | 'WithinQueryParameters';
type OverriddenTransporterOptions = 'baseHeaders' | 'baseQueryParameters' | 'hosts';
type CreateClientOptions = Omit<TransporterOptions, OverriddenTransporterOptions | 'algoliaAgent'> & Partial<Pick<TransporterOptions, OverriddenTransporterOptions>> & {
appId: string;
apiKey: string;
authMode?: AuthMode;
algoliaAgents: AlgoliaAgentOptions[];
};
type ClientOptions = Partial<Omit<CreateClientOptions, 'apiKey' | 'appId'>>;
// src/createAuth.ts
function createAuth(appId, apiKey, authMode = "WithinHeaders") {
const credentials = {
"x-algolia-api-key": apiKey,
"x-algolia-application-id": appId
};
return {
headers() {
return authMode === "WithinHeaders" ? credentials : {};
},
queryParameters() {
return authMode === "WithinQueryParameters" ? credentials : {};
}
};
}
type IterableOptions<TResponse> = Partial<{
/**
* The function that runs right after the API call has been resolved, allows you to do anything with the response before `validate`.
*/
aggregator: (response: TResponse) => void;
/**
* The `validate` condition to throw an error and its message.
*/
error: {
/**
* The function to validate the error condition.
*/
validate: (response: TResponse) => boolean;
/**
* The error message to throw.
*/
message: (response: TResponse) => string;
};
/**
* The function to decide how long to wait between iterations.
*/
timeout: () => number;
}>;
type CreateIterablePromise<TResponse> = IterableOptions<TResponse> & {
/**
* The function to run, which returns a promise.
*
* The `previousResponse` parameter (`undefined` on the first call) allows you to build your request with incremental logic, to iterate on `page` or `cursor` for example.
*/
func: (previousResponse?: TResponse) => Promise<TResponse>;
/**
* The validator function. It receive the resolved return of the API call.
*/
validate: (response: TResponse) => boolean;
};
// src/createIterablePromise.ts
function createIterablePromise({
func,
validate,
aggregator,
error,
timeout = () => 0
}) {
const retry = (previousResponse) => {
return new Promise((resolve, reject) => {
func(previousResponse).then((response) => {
if (aggregator) {
aggregator(response);
}
if (validate(response)) {
return resolve(response);
}
if (error && error.validate(response)) {
return reject(new Error(error.message(response)));
}
return setTimeout(() => {
retry(response).then(resolve).catch(reject);
}, timeout());
}).catch((err) => {
reject(err);
});
});
};
return retry();
}
declare function createBrowserLocalStorageCache(options: BrowserLocalStorageOptions): Cache;
// src/getAlgoliaAgent.ts
function getAlgoliaAgent({ algoliaAgents, client, version }) {
const defaultAlgoliaAgent = createAlgoliaAgent(version).add({
segment: client,
version
});
algoliaAgents.forEach((algoliaAgent) => defaultAlgoliaAgent.add(algoliaAgent));
return defaultAlgoliaAgent;
}
declare function createFallbackableCache(options: FallbackableCacheOptions): Cache;
// src/logger/createNullLogger.ts
function createNullLogger() {
return {
debug(_message, _args) {
return Promise.resolve();
},
info(_message, _args) {
return Promise.resolve();
},
error(_message, _args) {
return Promise.resolve();
}
};
}
declare function createMemoryCache(options?: MemoryCacheOptions): Cache;
// src/transporter/createStatefulHost.ts
var EXPIRATION_DELAY = 2 * 60 * 1e3;
function createStatefulHost(host, status = "up") {
const lastUpdate = Date.now();
function isUp() {
return status === "up" || Date.now() - lastUpdate > EXPIRATION_DELAY;
}
function isTimedOut() {
return status === "timed out" && Date.now() - lastUpdate <= EXPIRATION_DELAY;
}
return { ...host, status, lastUpdate, isUp, isTimedOut };
}
declare function createNullCache(): Cache;
// src/transporter/errors.ts
var AlgoliaError = class extends Error {
name = "AlgoliaError";
constructor(message, name) {
super(message);
if (name) {
this.name = name;
}
}
declare const DEFAULT_CONNECT_TIMEOUT_BROWSER = 1000;
declare const DEFAULT_READ_TIMEOUT_BROWSER = 2000;
declare const DEFAULT_WRITE_TIMEOUT_BROWSER = 30000;
declare const DEFAULT_CONNECT_TIMEOUT_NODE = 2000;
declare const DEFAULT_READ_TIMEOUT_NODE = 5000;
declare const DEFAULT_WRITE_TIMEOUT_NODE = 30000;
declare function createAlgoliaAgent(version: string): AlgoliaAgent;
declare function createAuth(appId: string, apiKey: string, authMode?: AuthMode): {
readonly headers: () => Headers;
readonly queryParameters: () => QueryParameters;
};
var ErrorWithStackTrace = class extends AlgoliaError {
stackTrace;
constructor(message, stackTrace, name) {
super(message, name);
this.stackTrace = stackTrace;
}
/**
* Helper: Returns the promise of a given `func` to iterate on, based on a given `validate` condition.
*
* @param createIterator - The createIterator options.
* @param createIterator.func - The function to run, which returns a promise.
* @param createIterator.validate - The validator function. It receives the resolved return of `func`.
* @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`.
* @param createIterator.error - The `validate` condition to throw an error, and its message.
* @param createIterator.timeout - The function to decide how long to wait between iterations.
*/
declare function createIterablePromise<TResponse>({ func, validate, aggregator, error, timeout, }: CreateIterablePromise<TResponse>): Promise<TResponse>;
type GetAlgoliaAgent = {
algoliaAgents: AlgoliaAgentOptions[];
client: string;
version: string;
};
var RetryError = class extends ErrorWithStackTrace {
constructor(stackTrace) {
super(
"Unreachable hosts - your application id may be incorrect. If the error persists, please reach out to the Algolia Support team: https://alg.li/support.",
stackTrace,
"RetryError"
);
}
};
var ApiError = class extends ErrorWithStackTrace {
status;
constructor(message, status, stackTrace, name = "ApiError") {
super(message, stackTrace, name);
this.status = status;
}
};
var DeserializationError = class extends AlgoliaError {
response;
constructor(message, response) {
super(message, "DeserializationError");
this.response = response;
}
};
var DetailedApiError = class extends ApiError {
error;
constructor(message, status, error, stackTrace) {
super(message, status, stackTrace, "DetailedApiError");
this.error = error;
}
};
declare function getAlgoliaAgent({ algoliaAgents, client, version }: GetAlgoliaAgent): AlgoliaAgent;
// src/transporter/helpers.ts
function shuffle(array) {
const shuffledArray = array;
for (let c = array.length - 1; c > 0; c--) {
const b = Math.floor(Math.random() * (c + 1));
const a = array[c];
shuffledArray[c] = array[b];
shuffledArray[b] = a;
}
return shuffledArray;
declare function createNullLogger(): Logger;
declare function createStatefulHost(host: Host, status?: StatefulHost['status']): StatefulHost;
declare function createTransporter({ hosts, hostsCache, baseHeaders, logger, baseQueryParameters, algoliaAgent, timeouts, requester, requestsCache, responsesCache, }: TransporterOptions): Transporter;
declare class AlgoliaError extends Error {
name: string;
constructor(message: string, name: string);
}
function serializeUrl(host, path, queryParameters) {
const queryParametersAsString = serializeQueryParameters(queryParameters);
let url = `${host.protocol}://${host.url}${host.port ? `:${host.port}` : ""}/${path.charAt(0) === "/" ? path.substring(1) : path}`;
if (queryParametersAsString.length) {
url += `?${queryParametersAsString}`;
}
return url;
declare class ErrorWithStackTrace extends AlgoliaError {
stackTrace: StackFrame[];
constructor(message: string, stackTrace: StackFrame[], name: string);
}
function serializeQueryParameters(parameters) {
return Object.keys(parameters).filter((key) => parameters[key] !== void 0).sort().map(
(key) => `${key}=${encodeURIComponent(
Object.prototype.toString.call(parameters[key]) === "[object Array]" ? parameters[key].join(",") : parameters[key]
).replace(/\+/g, "%20")}`
).join("&");
declare class RetryError extends ErrorWithStackTrace {
constructor(stackTrace: StackFrame[]);
}
function serializeData(request, requestOptions) {
if (request.method === "GET" || request.data === void 0 && requestOptions.data === void 0) {
return void 0;
}
const data = Array.isArray(request.data) ? request.data : { ...request.data, ...requestOptions.data };
return JSON.stringify(data);
declare class ApiError extends ErrorWithStackTrace {
status: number;
constructor(message: string, status: number, stackTrace: StackFrame[], name?: string);
}
function serializeHeaders(baseHeaders, requestHeaders, requestOptionsHeaders) {
const headers = {
Accept: "application/json",
...baseHeaders,
...requestHeaders,
...requestOptionsHeaders
};
const serializedHeaders = {};
Object.keys(headers).forEach((header) => {
const value = headers[header];
serializedHeaders[header.toLowerCase()] = value;
});
return serializedHeaders;
declare class DeserializationError extends AlgoliaError {
response: Response;
constructor(message: string, response: Response);
}
function deserializeSuccess(response) {
try {
return JSON.parse(response.content);
} catch (e) {
throw new DeserializationError(e.message, response);
}
type DetailedErrorWithMessage = {
message: string;
label: string;
};
type DetailedErrorWithTypeID = {
id: string;
type: string;
name?: string;
};
type DetailedError = {
code: string;
details?: DetailedErrorWithMessage[] | DetailedErrorWithTypeID[];
};
declare class DetailedApiError extends ApiError {
error: DetailedError;
constructor(message: string, status: number, error: DetailedError, stackTrace: StackFrame[]);
}
function deserializeFailure({ content, status }, stackFrame) {
try {
const parsed = JSON.parse(content);
if ("error" in parsed) {
return new DetailedApiError(parsed.message, status, parsed.error, stackFrame);
}
return new ApiError(parsed.message, status, stackFrame);
} catch {
}
return new ApiError(content, status, stackFrame);
}
// src/transporter/responses.ts
function isNetworkError({ isTimedOut, status }) {
return !isTimedOut && ~~status === 0;
}
function isRetryable({ isTimedOut, status }) {
return isTimedOut || isNetworkError({ isTimedOut, status }) || ~~(status / 100) !== 2 && ~~(status / 100) !== 4;
}
function isSuccess({ status }) {
return ~~(status / 100) === 2;
}
declare function shuffle<TData>(array: TData[]): TData[];
declare function serializeUrl(host: Host, path: string, queryParameters: QueryParameters): string;
declare function serializeQueryParameters(parameters: QueryParameters): string;
declare function serializeData(request: Request, requestOptions: RequestOptions): string | undefined;
declare function serializeHeaders(baseHeaders: Headers, requestHeaders: Headers, requestOptionsHeaders?: Headers): Headers;
declare function deserializeSuccess<TObject>(response: Response): TObject;
declare function deserializeFailure({ content, status }: Response, stackFrame: StackFrame[]): Error;
// src/transporter/stackTrace.ts
function stackTraceWithoutCredentials(stackTrace) {
return stackTrace.map((stackFrame) => stackFrameWithoutCredentials(stackFrame));
}
function stackFrameWithoutCredentials(stackFrame) {
const modifiedHeaders = stackFrame.request.headers["x-algolia-api-key"] ? { "x-algolia-api-key": "*****" } : {};
return {
...stackFrame,
request: {
...stackFrame.request,
headers: {
...stackFrame.request.headers,
...modifiedHeaders
}
}
};
}
declare function isNetworkError({ isTimedOut, status }: Omit<Response, 'content'>): boolean;
declare function isRetryable({ isTimedOut, status }: Omit<Response, 'content'>): boolean;
declare function isSuccess({ status }: Pick<Response, 'status'>): boolean;
// src/transporter/createTransporter.ts
function createTransporter({
hosts,
hostsCache,
baseHeaders,
logger,
baseQueryParameters,
algoliaAgent,
timeouts,
requester,
requestsCache,
responsesCache
}) {
async function createRetryableOptions(compatibleHosts) {
const statefulHosts = await Promise.all(
compatibleHosts.map((compatibleHost) => {
return hostsCache.get(compatibleHost, () => {
return Promise.resolve(createStatefulHost(compatibleHost));
});
})
);
const hostsUp = statefulHosts.filter((host) => host.isUp());
const hostsTimedOut = statefulHosts.filter((host) => host.isTimedOut());
const hostsAvailable = [...hostsUp, ...hostsTimedOut];
const compatibleHostsAvailable = hostsAvailable.length > 0 ? hostsAvailable : compatibleHosts;
return {
hosts: compatibleHostsAvailable,
getTimeout(timeoutsCount, baseTimeout) {
const timeoutMultiplier = hostsTimedOut.length === 0 && timeoutsCount === 0 ? 1 : hostsTimedOut.length + 3 + timeoutsCount;
return timeoutMultiplier * baseTimeout;
}
};
}
async function retryableRequest(request, requestOptions, isRead = true) {
const stackTrace = [];
const data = serializeData(request, requestOptions);
const headers = serializeHeaders(baseHeaders, request.headers, requestOptions.headers);
const dataQueryParameters = request.method === "GET" ? {
...request.data,
...requestOptions.data
} : {};
const queryParameters = {
...baseQueryParameters,
...request.queryParameters,
...dataQueryParameters
};
if (algoliaAgent.value) {
queryParameters["x-algolia-agent"] = algoliaAgent.value;
}
if (requestOptions && requestOptions.queryParameters) {
for (const key of Object.keys(requestOptions.queryParameters)) {
if (!requestOptions.queryParameters[key] || Object.prototype.toString.call(requestOptions.queryParameters[key]) === "[object Object]") {
queryParameters[key] = requestOptions.queryParameters[key];
} else {
queryParameters[key] = requestOptions.queryParameters[key].toString();
}
}
}
let timeoutsCount = 0;
const retry = async (retryableHosts, getTimeout) => {
const host = retryableHosts.pop();
if (host === void 0) {
throw new RetryError(stackTraceWithoutCredentials(stackTrace));
}
const timeout = { ...timeouts, ...requestOptions.timeouts };
const payload = {
data,
headers,
method: request.method,
url: serializeUrl(host, request.path, queryParameters),
connectTimeout: getTimeout(timeoutsCount, timeout.connect),
responseTimeout: getTimeout(timeoutsCount, isRead ? timeout.read : timeout.write)
};
const pushToStackTrace = (response2) => {
const stackFrame = {
request: payload,
response: response2,
host,
triesLeft: retryableHosts.length
};
stackTrace.push(stackFrame);
return stackFrame;
};
const response = await requester.send(payload);
if (isRetryable(response)) {
const stackFrame = pushToStackTrace(response);
if (response.isTimedOut) {
timeoutsCount++;
}
logger.info("Retryable failure", stackFrameWithoutCredentials(stackFrame));
await hostsCache.set(host, createStatefulHost(host, response.isTimedOut ? "timed out" : "down"));
return retry(retryableHosts, getTimeout);
}
if (isSuccess(response)) {
return deserializeSuccess(response);
}
pushToStackTrace(response);
throw deserializeFailure(response, stackTrace);
};
const compatibleHosts = hosts.filter(
(host) => host.accept === "readWrite" || (isRead ? host.accept === "read" : host.accept === "write")
);
const options = await createRetryableOptions(compatibleHosts);
return retry([...options.hosts].reverse(), options.getTimeout);
}
function createRequest(request, requestOptions = {}) {
const isRead = request.useReadTransporter || request.method === "GET";
if (!isRead) {
return retryableRequest(request, requestOptions, isRead);
}
const createRetryableRequest = () => {
return retryableRequest(request, requestOptions);
};
const cacheable = requestOptions.cacheable || request.cacheable;
if (cacheable !== true) {
return createRetryableRequest();
}
const key = {
request,
requestOptions,
transporter: {
queryParameters: baseQueryParameters,
headers: baseHeaders
}
};
return responsesCache.get(
key,
() => {
return requestsCache.get(
key,
() => (
/**
* Finally, if there is no request in progress with the same key,
* this `createRetryableRequest()` will actually trigger the
* retryable request.
*/
requestsCache.set(key, createRetryableRequest()).then(
(response) => Promise.all([requestsCache.delete(key), response]),
(err) => Promise.all([requestsCache.delete(key), Promise.reject(err)])
).then(([_, response]) => response)
)
);
},
{
/**
* Of course, once we get this response back from the server, we
* tell response cache to actually store the received response
* to be used later.
*/
miss: (response) => responsesCache.set(key, response)
}
);
}
return {
hostsCache,
requester,
timeouts,
logger,
algoliaAgent,
baseHeaders,
baseQueryParameters,
hosts,
request: createRequest,
requestsCache,
responsesCache
};
}
declare function stackTraceWithoutCredentials(stackTrace: StackFrame[]): StackFrame[];
declare function stackFrameWithoutCredentials(stackFrame: StackFrame): StackFrame;
// src/types/logger.ts
var LogLevelEnum = {
Debug: 1,
Info: 2,
Error: 3
};
export { AlgoliaError, ApiError, DEFAULT_CONNECT_TIMEOUT_BROWSER, DEFAULT_CONNECT_TIMEOUT_NODE, DEFAULT_READ_TIMEOUT_BROWSER, DEFAULT_READ_TIMEOUT_NODE, DEFAULT_WRITE_TIMEOUT_BROWSER, DEFAULT_WRITE_TIMEOUT_NODE, DeserializationError, DetailedApiError, ErrorWithStackTrace, LogLevelEnum, RetryError, createAlgoliaAgent, createAuth, createBrowserLocalStorageCache, createFallbackableCache, createIterablePromise, createMemoryCache, createNullCache, createNullLogger, createStatefulHost, createTransporter, deserializeFailure, deserializeSuccess, getAlgoliaAgent, isNetworkError, isRetryable, isSuccess, serializeData, serializeHeaders, serializeQueryParameters, serializeUrl, shuffle, stackFrameWithoutCredentials, stackTraceWithoutCredentials };
export { type AlgoliaAgent, type AlgoliaAgentOptions, AlgoliaError, ApiError, type AuthMode, type BrowserLocalStorageCacheItem, type BrowserLocalStorageOptions, type Cache, type CacheEvents, type ClientOptions, type CreateClientOptions, type CreateIterablePromise, DEFAULT_CONNECT_TIMEOUT_BROWSER, DEFAULT_CONNECT_TIMEOUT_NODE, DEFAULT_READ_TIMEOUT_BROWSER, DEFAULT_READ_TIMEOUT_NODE, DEFAULT_WRITE_TIMEOUT_BROWSER, DEFAULT_WRITE_TIMEOUT_NODE, DeserializationError, DetailedApiError, type DetailedError, type DetailedErrorWithMessage, type DetailedErrorWithTypeID, type EndRequest, ErrorWithStackTrace, type FallbackableCacheOptions, type GetAlgoliaAgent, type Headers, type Host, type IterableOptions, LogLevelEnum, type LogLevelType, type Logger, type MemoryCacheOptions, type Method, type QueryParameters, type Request, type RequestOptions, type Requester, type Response, RetryError, type StackFrame, type StatefulHost, type Timeouts, type Transporter, type TransporterOptions, createAlgoliaAgent, createAuth, createBrowserLocalStorageCache, createFallbackableCache, createIterablePromise, createMemoryCache, createNullCache, createNullLogger, createStatefulHost, createTransporter, deserializeFailure, deserializeSuccess, getAlgoliaAgent, isNetworkError, isRetryable, isSuccess, serializeData, serializeHeaders, serializeQueryParameters, serializeUrl, shuffle, stackFrameWithoutCredentials, stackTraceWithoutCredentials };
{
"name": "@algolia/client-common",
"version": "5.10.0",
"version": "5.10.1",
"description": "Common package for the Algolia JavaScript API client.",

@@ -5,0 +5,0 @@ "repository": {

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc