import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { parseRuntimeOverrides } from '~/services/runtimeConfig' async function loadRuntimeConfig(config: unknown) { vi.resetModules() vi.stubGlobal('__CAPGO_CONFIG__', config) const { getRuntimeConfig } = await import('~/services/runtimeConfig') return getRuntimeConfig() } describe('console runtime config (/config.js)', () => { beforeEach(() => { vi.stubEnv('VITE_API_HOST', 'https://api.capgo.app') vi.stubEnv('VITE_APP_URL', 'https://console.capgo.app') vi.stubEnv('VITE_CAPTCHA_KEY', 'build-captcha') vi.stubEnv('VITE_SERVING_POLICY_URL', 'https://plugin.eu.capgo.app/serving_policy/') vi.spyOn(console, 'error').mockImplementation(() => {}) }) afterEach(() => { vi.unstubAllEnvs() vi.unstubAllGlobals() vi.restoreAllMocks() }) it('keeps the build-time values when /config.js is empty or missing', async () => { const expected = { apiHost: 'https://api.capgo.app', appUrl: 'https://console.capgo.app', captchaKey: 'build-captcha', servingPolicyUrl: 'https://plugin.eu.capgo.app/serving_policy/', } expect(await loadRuntimeConfig({})).toEqual(expected) expect(await loadRuntimeConfig(undefined)).toEqual(expected) }) it('uses the self-host values from /config.js', async () => { expect(await loadRuntimeConfig({ apiHost: 'https://api.example.com/', appUrl: 'https://console.example.com/', captchaKey: '', servingPolicyUrl: 'https://plugin.example.com/serving_policy/', })).toEqual({ apiHost: 'https://api.example.com', appUrl: 'https://console.example.com', captchaKey: '', servingPolicyUrl: 'https://plugin.example.com/serving_policy/', }) }) it('overrides only the keys it sets', async () => { const config = await loadRuntimeConfig({ apiHost: 'http://localhost:54321/functions/v1' }) expect(config.apiHost).toBe('http://localhost:54321/functions/v1') expect(config.appUrl).toBe('https://console.capgo.app') expect(config.captchaKey).toBe('build-captcha') }) it('ignores invalid values and logs them', () => { expect(parseRuntimeOverrides({ apiHost: 'javascript:alert(1)', appUrl: 'not a url', captchaKey: 42, unknown: 'x' })).toEqual({}) expect(console.error).toHaveBeenCalledTimes(3) expect(parseRuntimeOverrides('nope')).toEqual({}) expect(parseRuntimeOverrides(null)).toEqual({}) }) it('still follows build-time env changes after the overrides are cached', async () => { await loadRuntimeConfig({ captchaKey: 'self-host' }) const { getRuntimeConfig } = await import('~/services/runtimeConfig') vi.stubEnv('VITE_API_HOST', 'https://api.preprod.capgo.app') expect(getRuntimeConfig()).toMatchObject({ apiHost: 'https://api.preprod.capgo.app', captchaKey: 'self-host' }) }) })