/** * Alert Logic axios extension - an API Client with automatic service discovery, local caching, and retry functionality baked in. * * An instance of the client can be constructed manually, but in general you should just use the global instance `AlDefaultClient`. * * Most use cases can be handled by using one of the client's convenience methods, which includes support for local caching and retries: * * `.rawGet( config )` - executes a GET request and resolves with the full response descriptor from axios * `.get( config )` - executes a GET request and resolves with the response payload from axios, as Type. * `.rawPost( config )` - executes a POST request and resolves with the full response descriptor from axios * `.post( config )` - executes a POST request and resolves with the response payload from axios, as Type. * `.rawPut( config )` - executes a PUT request and resolves with the full response descriptor from axios * `.put( config )` - executes a PUT request and resolves with the response payload from axios, as Type. * `.rawDelete( config )` - executes a DELETE request and resolves with the full response descriptor from axios * `.delete( config )` - executes a DELETE request and resolves with the response payload from axios, as Type. * * Alternatively, a request can be normalized and dispatched without caching or retry logic using this method: * * ``` * let normalizedRequest = AlDefaultClient.normalizeRequest( config ); * let response = await AlDefaultClient.doRequest( method, normalizedRequest ); * ``` */ import { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'; import { AlLocationContext, AlLocationDescriptor } from '../abstract'; import { AlTriggerStream } from "../common/utility"; import { APIExecutionLogItem, APIExecutionLogSummary, APIRequestParams } from './types'; import { AIMSSessionDescriptor } from '../aims-client/types'; /** * A dictionary of resolved endpoints, keyed by environment, account, service, and residency. * Residency may be US, EMEA, or default (which corresponds with the legacy "infer from primary account's default location" logic. */ declare type AlEndpointsDictionary = { [environment: string]: { [accountId: string]: { [serviceId: string]: { [residency: string]: string; }; }; }; }; export declare class AlApiClient { /** * The following list of services are the ones whose endpoints will be resolved by default. Added globally/commonly used services here for optimized API performance. */ protected static defaultServiceList: string[]; /** * The following list of services are the ones whose endpoints will need to be determined for the current context active residency location. */ protected static resolveByResidencyServiceList: string[]; protected static defaultServiceParams: APIRequestParams; protected static defaultResidency: string; events: AlTriggerStream; verbose: boolean; collectRequestLog: boolean; mockMode: boolean; mockRequests: any[]; defaultAccountId: string; private storage; private instance; private lastError; private endpointsGuard; private endpointCache; private endpointsStackWhitelist; private globalServiceParams; private transientReadCache; private executionRequestLog; private beforeRequest?; constructor(); /** * Resets internal state back to its factory defaults. */ reset(): AlApiClient; /** * Flushes the caches keys if they are present in the config request params. */ flushCacheKeysFromConfig(config: APIRequestParams): void; /** * Get the full url from a config api request. * Note: This method is intended to be used as a helper from outside, * we need to normalize here. */ fromConfigToFullUrl(config: APIRequestParams): Promise; /** * This allows the host to set global parameters that will be used for every request, either for Axios or the @al/client service layer. * Most notably, setting `noEndpointsResolution` to true will suppress endpoints resolution for all requests, and cause default endpoint values to be used. */ setGlobalParameters(parameters: APIRequestParams): AlApiClient; /** * GET - Return Cache, or Call for updated data */ rawGet(config: APIRequestParams): Promise>; get(config: APIRequestParams): Promise; /** * @deprecated * Alias for GET utility method */ fetch(config: APIRequestParams): Promise; /** * POST - clears cache and posts for new/merged data */ rawPost(config: APIRequestParams): Promise>; post(config: APIRequestParams): Promise; /** * Form data submission */ rawForm(config: APIRequestParams): Promise>; form(config: APIRequestParams): Promise; /** * PUT - replaces data */ rawPut(config: APIRequestParams): Promise>; put(config: APIRequestParams): Promise; /** * @deprecated * Alias for PUT utility method */ set(config: APIRequestParams): Promise; /** * Delete data */ rawDelete(config: APIRequestParams): Promise>; delete(config: APIRequestParams): Promise; executeRequest(options: APIRequestParams): Promise>; /** * Perform a request collecting all details related to the request, if * collectRequestLog is active. * @param method The method of the request. [POST PUT DELETE GET] * @param normalizedParams The normalized APIRequestParams object. */ doRequest(normalizedParams: APIRequestParams): Promise>; /** * Returns a summary of requests based in the internal log array. */ getExecutionSummary(): APIExecutionLogSummary; /** * Retrieve a reference to the last HTTP error response received. */ getLastError(): AxiosResponse; /** * @deprecated * * Provides a concise way to manipulate the AlLocatorService without importing it directly... * * @param {array} locations An array of locator descriptors. * @param {string|boolean} actingUri The URI to use to calculate the current location and location context; defaults to window.location.origin. * @param {AlLocationContext} The effective location context. See @al/common for more information. */ setLocations(locations: AlLocationDescriptor[], actingUri?: string | boolean, context?: AlLocationContext): void; /** * @deprecated * * Provides a concise way to set location context without importing AlLocatorService directly. * * @param {string} environment Should be 'production', 'integration', or 'development' * @param {string} residency Should be 'US' or 'EMEA' * @param {string} locationId If provided, should be one of the locations service location codes, e.g., defender-us-denver * @param {string} accessibleLocations If provided, should be a list of accessible locations service location codes. */ setLocationContext(environment: string, residency?: string, locationId?: string, accessibleLocations?: string[]): void; /** * @deprecated */ resolveLocation(locTypeId: string, path?: string, context?: AlLocationContext): string; /** * Use HTTP Basic Auth * Optionally supply an mfa code if the user account is enrolled for Multi-Factor Authentication * * There are two variants of this method: one which executes directly against AIMS, and the other which * is levied against a gestalt lambda proxied through console.account. * * Under ordinary circumstances, you should *not* be calling this directly -- instead, you should use the top-level * `authenticate` method on @al/session's ALSession instance. */ authenticate(user: string, pass: string, mfa_code?: string, ignoreWarning?: boolean, payloadExtras?: any): Promise; authenticateViaGestalt(user: string, pass: string, ignoreWarning?: boolean, payloadExtras?: any): Promise; /** * Authenticate with an mfa code and a temporary session token. * Used when a user inputs correct username:password but does not include mfa code when they are enrolled for Multi-Factor Authentication * The session token can be used to complete authentication without re-entering the username and password, but must be used within 3 minutes (token expires) * * There are two variants of this method: one which executes directly against AIMS, and the other which * is levied against a gestalt lambda proxied through console.account. * * Under ordinary circumstances, you should *not* be calling this directly -- instead, you should use the top-level * `authenticateWithMFASessionToken` method on @al/session's ALSession instance. */ authenticateWithMFASessionToken(sessionToken: string, mfa_code: string, ignoreWarning?: boolean): Promise; authenticateWithMFAViaGestalt(sessionToken: string, mfaCode: string): Promise; acceptTermsOfService(sessionToken: string, ignoreWarning?: boolean, acceptTOS?: boolean): Promise; acceptTermsOfServiceViaGestalt(sessionToken: string, acceptTOS?: boolean): Promise; /** * Converts a string input to its base64 encoded equivalent. */ base64Encode(data: string): string; normalizeRequest(config: APIRequestParams): Promise; getCachedData(): any; getExecutionRequestLog(): APIExecutionLogItem[]; mergeCacheData(cachedData: any): void; isResponse(instance?: any): instance is AxiosResponse; logResponse(response: AxiosResponse, includeCurl?: boolean): void; requestToCurlCommand(config: AxiosRequestConfig, prettify?: boolean): string; simulateHttpError(request: Promise, status: number, statusText: string, data: any, headers?: any): Promise; /** * Resolves accumulated endpoints data for the given account. * * Update Feb 2021 * --------------- * This has been overhauled to deal with services whose endpoints now must be determined for the current context residency (selected datacenter location in UI). * The reason for this is to cater for scenarios where a parent account manages children that are located across different geographical locations to one another and therefore * any data retrieval for views in the UI where child account roll-ups exist must be fetched from the appropriate location. * The previous implementation ALWAYS calculated service endpoints for the default location of the primary account for the logged in user and so any roll ups for views for child accounts never worked eva!!! * */ resolveDefaultEndpoints(accountId: string, serviceList: string[]): Promise; resolveResidencyAwareEndpoints(accountId: string, serviceList: string[]): Promise; lookupDefaultServiceEndpoint(accountId: string, serviceName: string): string; setBeforeRequest(handler?: { (): Promise; }): void; protected getGestaltAuthenticationURL(): string; protected calculateRequestURL(params: APIRequestParams): Promise; /** * This method (and its partner, getServiceEndpoints) uses running promise sequences to retrieve endpoints (using the multiple endpoint lookup action) * in such a way that * a) most basic services will be retrieved in a single call * b) the initial call is guaranteed to included the service a request is being formed for * c) only one outstanding call to the endpoints service will be issued, per account, at a given time * * @returns The resolved base URL of the given endpoint. */ protected prepare(requestParams: APIRequestParams): Promise; protected fallbackResolveEndpoints(accountId: string, serviceList: string[], residency: string): AlEndpointsDictionary; /** * Instantiate a properly configured axios client for services */ protected getAxiosInstance(): AxiosInstance; protected onRequestResponse: (response: AxiosResponse) => Promise; protected onRequestError: (errorResponse: AxiosResponse) => Promise; /** * Inner request method. If automatic retry is enabled via the retry_count property of the request config, this method * will catch errors of status code 0/3XX/5XX and retry them at staggered intervals (by default, a factorial delay based on number of retries). * If any of these requests succeed, the outer promise will be satisfied using the successful result. */ protected axiosRequest(config: APIRequestParams, attemptIndex?: number): Promise>; /** * Utility method to determine whether a given response is a retryable error. */ protected isRetryableError(error: AxiosResponse, config: APIRequestParams, attemptIndex: number): boolean; protected isRequestTimeout(error: any, config: APIRequestParams): number; /** * Generates a random cache-busting parameter */ protected generateCacheBuster(attemptIndex: number): string; /** * Normalize query parameters from config api request. */ private normalizeQueryParams; /** * */ private getCachedValue; private setCachedValue; private deleteCachedValue; /** * Are we running in a browser? */ private isBrowserBased; private log; private normalizeErrorMessage; /** * Performs a shallow merge from any number of source objects to a single target object, and returns that target object. * Essentially a cheap-and-easy replacement for Object.assign. */ private merge; } export declare const AlDefaultClient: AlApiClient; export {};