Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import { chat, createChatOptions } from '@tanstack/ai'
3import { createCloudflareText } from '@tanstack/ai-cloudflare'
4import type { CloudflareBindingConfig } from '@tanstack/ai-cloudflare'
5
6const LLMOCK_DEFAULT_BASE = process.env.LLMOCK_URL || 'http://127.0.0.1:4010'
7
8/**
9 * Drives the Cloudflare text adapter in binding mode. The stand-in `env.AI`
10 * does what the real binding does with `returnRawResponse` and
11 * `extraHeaders`: it posts the inputs with those headers and returns the raw
12 * response. The companion spec reads aimock's request journal to check that
13 * `defaultHeaders` reach Workers AI and the OpenAI SDK's own headers do not.
14 */
15export const Route = createFileRoute('/api/cloudflare-binding-headers-wire')({
16 server: {
17 handlers: {
18 POST: async ({ request }) => {
19 const testId = new URL(request.url).searchParams.get('testId') ?? ''
20
21 const run = async (
22 model: string,
23 inputs: Record<string, unknown>,
24 options: { extraHeaders?: Record<string, string> },
25 ) =>
26 await fetch(`${LLMOCK_DEFAULT_BASE}/v1/chat/completions`, {
27 method: 'POST',
28 headers: {
29 'content-type': 'application/json',
30 'x-test-id': testId,
31 ...options.extraHeaders,
32 },
33 body: JSON.stringify({ model, ...inputs }),
34 })
35 // ponytail: only `run` is exercised; the real binding type has more.
36 const binding = { run } as unknown as CloudflareBindingConfig['binding']
37
38 const adapter = createCloudflareText('@cf/zai-org/glm-5.3-flash', {
39 binding,
40 defaultHeaders: { 'x-session-affinity': 'ses_e2e' },
41 })
42
43 try {
44 for await (const _ of chat({
45 ...createChatOptions({ adapter }),
46 threadId: 'cloudflare-binding-headers-wire',
47 messages: [
48 {
49 role: 'user',
50 content: '[cloudflare-binding-headers-wire] affinity check',
51 },
52 ],
53 })) {
54 // Drain the stream.
55 }
56 } catch (error) {
57 return Response.json({
58 ok: false,
59 error: error instanceof Error ? error.message : String(error),
60 })
61 }
62
63 return Response.json({ ok: true })
64 },
65 },
66 },
67})