import {Currency} from './payment'; export interface SdkEndpoints { checkoutApiBaseUrl: string; widgetsBaseUrl: string; } export class SdkConfig { constructor( public readonly endpointsByKey: Readonly>, ) {} endpointsFor(currency: Currency): SdkEndpoints { return this.endpointsByKey[currency] ?? this.endpointsByKey.general; } } const parseEndpoints = (raw: unknown, keyPath: string): SdkEndpoints => { if (!raw || typeof raw !== 'object') { throw new Error(`Malformed SdkConfig: "${keyPath}" is not an object`); } const endpointsField = (raw as Record).endpoints; if (!endpointsField || typeof endpointsField !== 'object') { throw new Error(`Malformed SdkConfig: "${keyPath}.endpoints" missing`); } const e = endpointsField as Record; const checkout = e.checkoutApiBaseUrl; const widgets = e.widgetsBaseUrl; if (typeof checkout !== 'string' || checkout.length === 0) { throw new Error( `Malformed SdkConfig: "${keyPath}.endpoints.checkoutApiBaseUrl" missing or empty`, ); } if (typeof widgets !== 'string' || widgets.length === 0) { throw new Error( `Malformed SdkConfig: "${keyPath}.endpoints.widgetsBaseUrl" missing or empty`, ); } return {checkoutApiBaseUrl: checkout, widgetsBaseUrl: widgets}; }; export const parseSdkConfig = (json: unknown): SdkConfig => { if (!json || typeof json !== 'object') { throw new Error('Malformed SdkConfig: response is not an object'); } const obj = json as Record; if (!('general' in obj)) { throw new Error('Malformed SdkConfig: missing "general" key'); } const map: Record = {}; for (const key of Object.keys(obj)) { map[key] = parseEndpoints(obj[key], key); } return new SdkConfig(map); };