import { config, HTTPError, SDKError, ValidationError } from '@lifi/sdk'; import type { ExtendedRequestInit } from '../types/request.js'; import { wait } from './utils.js'; import { version } from '../config/version.js'; export const requestSettings = { retries: 1, }; const stripExtendRequestInitProperties = ({ retries, ...rest }: ExtendedRequestInit): RequestInit => ({ ...rest, }); export const request = async ( url: RequestInfo | URL, options: ExtendedRequestInit = { retries: requestSettings.retries, skipTrackingHeaders: false, }, ): Promise => { const { userId, integrator, widgetVersion, apiKey } = config.get(); if (!integrator) { throw new SDKError( new ValidationError( 'You need to provide the Integrator property. Please see Nimbus documentation', ), ); } options.retries = options.retries ?? requestSettings.retries; try { if (!options.skipTrackingHeaders) { if (apiKey) { options.headers = { ...options.headers, 'x-lifi-api-key': apiKey, }; } if (userId) { options.headers = { ...options.headers, 'x-lifi-userid': userId, }; } if (widgetVersion) { options.headers = { ...options.headers, 'x-lifi-widget': widgetVersion, }; } if (version) { options.headers = { ...options.headers, 'x-lifi-sdk': version, }; } options.headers = { ...options.headers, 'x-lifi-integrator': integrator, }; } const response: Response = await fetch( url, stripExtendRequestInitProperties(options), ); if (!response.ok) { throw new HTTPError(response, url, options); } return await response.json(); } catch (error) { if (options.retries > 0 && (error as HTTPError).status === 500) { await wait(500); return request(url, { ...options, retries: options.retries - 1 }); } await (error as HTTPError).buildAdditionalDetails?.(); throw new SDKError(error as HTTPError); } };