Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import { chat } from '@tanstack/ai'
3import { createAnthropicChat } from '@tanstack/ai-anthropic'
4
5const LLMOCK_DEFAULT_BASE = process.env.LLMOCK_URL || 'http://127.0.0.1:4010'
6// Fake credentials. aimock accepts any value.
7const DUMMY_TOKEN = 'e2e-dummy-bearer-token'
8const DUMMY_KEY = 'sk-ant-e2e-test-dummy-key'
9
10const credentials = {
11 'api-key': { credential: DUMMY_KEY, auth: 'api-key' },
12 bearer: { credential: DUMMY_TOKEN, auth: 'bearer' },
13 oauth: { credential: DUMMY_TOKEN, auth: 'oauth' },
14} as const
15
16/**
17 * Streams one Anthropic chat against the aimock fixture in
18 * `fixtures/anthropic-auth`. A `fetch` wrapper records the headers and the
19 * `system` field that the SDK puts on the wire, then sends the request on to
20 * aimock. `?mode=` picks the credential and its `auth` kind.
21 */
22export const Route = createFileRoute('/api/anthropic-auth-wire')({
23 server: {
24 handlers: {
25 POST: async ({ request }) => {
26 const mode = new URL(request.url).searchParams.get('mode')
27 if (mode !== 'api-key' && mode !== 'bearer' && mode !== 'oauth') {
28 return Response.json({ ok: false, error: `Unknown mode: ${mode}` })
29 }
30
31 let wire: Record<string, unknown> | undefined
32 const { credential, auth } = credentials[mode]
33 const adapter = createAnthropicChat('claude-haiku-4-5', credential, {
34 auth,
35 baseURL: LLMOCK_DEFAULT_BASE,
36 fetch: async (input, init) => {
37 const outgoing = new Request(input, init)
38 const body: unknown = await outgoing.clone().json()
39 wire = {
40 authorization: outgoing.headers.get('authorization'),
41 xApiKey: outgoing.headers.get('x-api-key'),
42 anthropicBeta: outgoing.headers.get('anthropic-beta'),
43 xApp: outgoing.headers.get('x-app'),
44 system:
45 typeof body === 'object' && body !== null && 'system' in body
46 ? body.system
47 : undefined,
48 }
49 return fetch(outgoing)
50 },
51 })
52
53 let text = ''
54 try {
55 for await (const chunk of chat({
56 threadId: 'anthropic-auth-wire',
57 adapter,
58 messages: [{ role: 'user', content: '[anthropic-auth] say hello' }],
59 })) {
60 if (chunk.type === 'TEXT_MESSAGE_CONTENT') text += chunk.delta
61 if (chunk.type === 'RUN_ERROR') {
62 return Response.json({ ok: false, error: chunk.message, wire })
63 }
64 }
65 } catch (error) {
66 return Response.json({
67 ok: false,
68 error: error instanceof Error ? error.message : String(error),
69 })
70 }
71
72 return Response.json({ ok: true, text, wire })
73 },
74 },
75 },
76})