import { beforeEach, describe, expect, test } from 'bun:test' import { fetchRuntimeVersion, getCachedRuntimeVersion, parseHealthVersion, resetRuntimeVersionCache, } from '../src/admin/components/layout/runtimeVersion' describe('runtimeVersion', () => { beforeEach(() => { resetRuntimeVersionCache() }) test('parseHealthVersion validates and normalizes semver strings', () => { expect(parseHealthVersion({ status: 'healthy', version: '0.84.1' })).toBe('0.84.1') expect(parseHealthVersion({ version: ' v0.84.2-rc.1 ' })).toBe('0.84.2-rc.1') expect(parseHealthVersion({ version: '' })).toBeNull() expect(parseHealthVersion({ version: 'invalid' })).toBeNull() expect(parseHealthVersion(null)).toBeNull() }) test('fetchRuntimeVersion caches resolved backend version across calls', async () => { let calls = 0 const fakeFetch = (async () => { calls += 1 return new Response(JSON.stringify({ status: 'healthy', version: '0.84.1' }), { status: 200, headers: { 'Content-Type': 'application/json' }, }) }) as typeof fetch expect(await fetchRuntimeVersion('0.84.0', fakeFetch)).toBe('0.84.1') expect(getCachedRuntimeVersion()).toBe('0.84.1') expect(await fetchRuntimeVersion('0.84.0', fakeFetch)).toBe('0.84.1') expect(calls).toBe(1) }) test('fetchRuntimeVersion deduplicates concurrent default fetch requests', async () => { const originalFetch = globalThis.fetch let calls = 0 globalThis.fetch = (async () => { calls += 1 await Promise.resolve() return new Response(JSON.stringify({ status: 'healthy', version: '0.84.1' }), { status: 200, headers: { 'Content-Type': 'application/json' }, }) }) as typeof fetch try { const [first, second] = await Promise.all([ fetchRuntimeVersion('0.84.0'), fetchRuntimeVersion('0.84.0'), ]) expect(first).toBe('0.84.1') expect(second).toBe('0.84.1') expect(calls).toBe(1) } finally { globalThis.fetch = originalFetch } }) test('fetchRuntimeVersion falls back without caching errors', async () => { const serverErrorFetch = (async () => new Response('error', { status: 500 })) as typeof fetch expect(await fetchRuntimeVersion('0.84.0', serverErrorFetch)).toBe('0.84.0') expect(getCachedRuntimeVersion()).toBeNull() const networkErrorFetch = (async () => { throw new Error('network down') }) as typeof fetch expect(await fetchRuntimeVersion('0.84.0', networkErrorFetch)).toBe('0.84.0') expect(getCachedRuntimeVersion()).toBeNull() const recoveryFetch = (async () => new Response(JSON.stringify({ status: 'healthy', version: '0.84.2' }), { status: 200, })) as typeof fetch expect(await fetchRuntimeVersion('0.84.0', recoveryFetch)).toBe('0.84.2') expect(getCachedRuntimeVersion()).toBe('0.84.2') }) })