Open History to see the last commit
1import { describe, expect, it, vi } from 'vitest'
2import { ByokMissingError, byokMissing } from '@tanstack/ai/byok'
3import {
4 fetchServerSentEvents,
5 fetcherToConnectionAdapter,
6} from '../src/connection-adapters'
7import type { ChatFetcher } from '../src/types'
8
9describe('runContext.headers', () => {
10 it('merges BYOK headers onto the fetch request', async () => {
11 const fetchClient = vi.fn<typeof fetch>(async () => byokMissing('openai'))
12 const connection = fetchServerSentEvents('/api/chat', { fetchClient })
13 const runContext = {
14 threadId: 't1',
15 runId: 'r1',
16 headers: { 'x-byok-openai': 'sk-live' },
17 }
18 await expect(async () => {
19 for await (const _chunk of connection.connect(
20 [],
21 {},
22 undefined,
23 runContext,
24 )) {
25 void _chunk
26 }
27 }).rejects.toBeInstanceOf(ByokMissingError)
28 const init = fetchClient.mock.calls[0]![1]
29 const headers = new Headers(init?.headers)
30 expect(headers.get('x-byok-openai')).toBe('sk-live')
31 const body = JSON.parse(String(init?.body)) as { forwardedProps?: unknown }
32 expect(JSON.stringify(body)).not.toContain('sk-live')
33 })
34
35 it('passes headers into a ChatFetcher', async () => {
36 const fetcher = vi.fn<ChatFetcher>(async () => byokMissing('openai'))
37 const adapter = fetcherToConnectionAdapter(fetcher)
38 const abort = new AbortController()
39 await expect(async () => {
40 for await (const _chunk of adapter.connect([], {}, abort.signal, {
41 threadId: 't1',
42 runId: 'r1',
43 headers: { 'x-byok-openai': 'sk-live' },
44 })) {
45 void _chunk
46 }
47 }).rejects.toThrow()
48 expect(fetcher.mock.calls[0]![1]).toMatchObject({
49 headers: { 'x-byok-openai': 'sk-live' },
50 })
51 })
52
53 it('does not throw when a custom connect ignores headers', async () => {
54 async function* connect() {
55 return
56 }
57 const adapter = { connect }
58 await expect(
59 (async () => {
60 for await (const _chunk of adapter.connect()) {
61 void _chunk
62 }
63 })(),
64 ).resolves.toBeUndefined()
65 })
66})