// See https://github.com/microsoft/TypeScript/issues/29729 for why LiteralUnion // eslint-disable-next-line @typescript-eslint/naming-convention type LiteralUnion = T | (U & { _?: never }); export type Environment = LiteralUnion<'dev' | 'go' | 'next' | 'qa' | 'stage' | 'test'>; export type EnvironmentValues = Partial>; export function getValueForEnvironment( values: EnvironmentValues, defaultEnvironment: Environment = 'qa', hostname: string = window.location.hostname ) { const keys = Object.keys(values) as (keyof typeof values)[]; const key = detectEnvironment(keys, defaultEnvironment, hostname); return values[key]; } function detectEnvironment( keys: Environment[], defaultEnvironment: Environment, hostname: string ): Environment { if (isTestEnvironment()) { return 'test'; } if (isLocalHost(hostname)) { return 'dev'; } for (const key of keys) { if ( hostname.indexOf(`${key}.servicetitan.com`) >= 0 || (key.endsWith('.st.dev') && hostname.indexOf(key) >= 0) ) { return key; } } return defaultEnvironment; } function isLocalHost(hostname: string) { return ['localhost', '127.0.0.1', 'app-web'].some(host => hostname.indexOf(host) >= 0); } function isTestEnvironment() { return process.env.NODE_ENV === 'test'; }