Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

reactor.test.ts

267 lines8.6 KB

1import { describe, expect, it } from 'vitest'
2​
3import { findDanglingRefs } from '#/server/ingest/bundle.ts'
4import { classifyAndBundle } from '#/server/ingest/sync.ts'
5​
6import {
7 REACTOR_PRICING_URL,
8 extractOpenApiFromHtml,
9 modelApiPageUrl,
10 provider,
11} from './reactor.ts'
12​
13const MINI_SPEC = {
14 openapi: '3.1.0',
15 info: { title: 'helios', version: 'v1.0.1' },
16 paths: {
17 '/events/set_prompt': {
18 post: {
19 operationId: 'set_prompt',
20 summary: 'Set the prompt',
21 requestBody: {
22 required: true,
23 content: {
24 'application/json': {
25 schema: {
26 type: 'object',
27 required: ['prompt'],
28 properties: { prompt: { type: 'string' } },
29 },
30 },
31 },
32 },
33 responses: {
34 '200': {
35 description: 'ok',
36 content: {
37 'application/json': {
38 schema: {
39 type: 'object',
40 properties: { prompt: { type: 'string' } },
41 },
42 },
43 },
44 },
45 },
46 },
47 },
48 '/events/start': {
49 post: {
50 operationId: 'start',
51 requestBody: {
52 required: true,
53 content: {
54 'application/json': {
55 schema: { type: 'object', properties: {} },
56 },
57 },
58 },
59 responses: { '202': { description: 'accepted' } },
60 },
61 },
62 },
63 components: { schemas: {} },
65​
66function htmlWithSpec(spec: unknown): string {
67 const chunk = JSON.stringify(JSON.stringify(spec))
68 return `<!doctype html><script>self.__next_f.push([1,${chunk}])</script>`
70​
71describe('extractOpenApiFromHtml', () => {
72 it('reads the OpenAPI document out of a Next.js RSC string chunk', () => {
73 const extracted = extractOpenApiFromHtml(htmlWithSpec(MINI_SPEC))
74 expect(extracted?.info?.title).toBe('helios')
75 expect(extracted?.paths?.['/events/set_prompt']?.post).toBeDefined()
76 })
77​
78 it('returns null when the page has no spec chunk', () => {
79 expect(extractOpenApiFromHtml('<html>nope</html>')).toBeNull()
80 })
81})
82​
83describe('reactor classify', () => {
84 it('maps namespaced model command paths and drops platform', () => {
85 expect(provider.classify('/reactor/helios', {})).toBe('video')
86 expect(provider.classify('/reactor/helios/events/set_prompt', {})).toBe(
87 'video',
88 )
89 expect(provider.classify('/x2/events/set_prompt', {})).toBe('video')
90 expect(
91 provider.classify('/reactor/happy-oyster-adventure/create_world', {}),
92 ).toBe('video')
93 expect(provider.classify('/tokens', {})).toBeNull()
94 expect(provider.classify('/sessions', {})).toBeNull()
95 expect(provider.classify('/pricing', {})).toBeNull()
96 })
97})
98​
99describe('reactor listModels', () => {
100 it('does not skip when REACTOR_API_KEY is absent (GET /pricing is public)', async () => {
101 const original = globalThis.fetch
102 globalThis.fetch = ((url: string) => {
103 expect(String(url)).toBe(REACTOR_PRICING_URL)
104 return Promise.resolve(
105 new Response(
106 JSON.stringify({
107 models: [
108 {
109 id: 'helios-id',
110 name: 'helios',
111 rate: { amount_per_sec: 17, unit: 'credits' },
112 },
113 {
114 name: 'x2',
115 rate: {
116 amount_per_sec: 17,
117 amount_per_sec_usd: '0.0017',
118 currency_code: 'USD',
119 unit: 'credits',
120 },
121 },
122 { name: 'happy-oyster' },
123 ],
124 }),
125 { status: 200, headers: { 'content-type': 'application/json' } },
126 ),
127 )
128 }) as typeof fetch
129 try {
130 const result = await provider.listModels({})
131 expect(result.skipped).toBeUndefined()
132 const ids = result.models.map((m) => m.rawId)
133 expect(ids).toContain('reactor/helios')
134 expect(ids).toContain('x2')
135 expect(ids).not.toContain('reactor/happy-oyster')
136 expect(ids).toContain('reactor/happy-oyster-adventure')
137 expect(new Set(ids).size).toBe(ids.length)
138 expect(result.models.every((m) => m.activity === 'video')).toBe(true)
139 expect(
140 result.models.find((m) => m.rawId === 'reactor/helios')?.pricing,
141 ).toBeUndefined()
142 expect(
143 result.models.find((m) => m.rawId === 'x2')?.pricing,
144 ).toMatchObject({
145 price: { '*': [{ var: 'video_seconds' }, 0.0017] },
146 })
147 } finally {
148 globalThis.fetch = original
149 }
150 })
151​
152 it('falls back to the curated catalog when /pricing fails', async () => {
153 const original = globalThis.fetch
154 globalThis.fetch = () =>
155 Promise.resolve(new Response('nope', { status: 500 }))
156 try {
157 const result = await provider.listModels({})
158 expect(result.skipped).toBeUndefined()
159 expect(result.models.map((m) => m.rawId)).toEqual(
160 expect.arrayContaining([
161 'reactor/helios',
162 'reactor/fast-h3',
163 'x2',
164 'reactor/happy-oyster-director',
165 ]),
166 )
167 } finally {
168 globalThis.fetch = original
169 }
170 })
171})
172​
173describe('reactor fetchSpec', () => {
174 it('extracts upstream OpenAPI from model API pages and namespaces paths', async () => {
175 const original = globalThis.fetch
176 const calls: Array<string> = []
177 globalThis.fetch = ((url: string) => {
178 const href = String(url)
179 calls.push(href)
180 if (href === modelApiPageUrl('helios')) {
181 return Promise.resolve(
182 new Response(htmlWithSpec(MINI_SPEC), {
183 status: 200,
184 headers: { 'content-type': 'text/html' },
185 }),
186 )
187 }
188 return Promise.resolve(new Response('not found', { status: 404 }))
189 }) as typeof fetch
190 try {
191 const fetched = await provider.fetchSpec({})
192 expect(calls).toContain(modelApiPageUrl('helios'))
193 expect(calls).toContain(modelApiPageUrl('ltx'))
194 expect(fetched.outputStrategy).toBe('post-200')
195 expect(fetched.warnings?.length).toBeGreaterThan(0)
196​
197 const heliosSource = fetched.sources.find((s) =>
198 s.url.includes('helios/api#reactor/helios'),
199 )
200 expect(heliosSource?.hash).toMatch(/^[0-9a-f]{64}$/)
201​
202 const { endpoints, warnings } = classifyAndBundle(provider, fetched)
203 expect(warnings).toEqual([])
204 const byId = new Map(endpoints.map((e) => [e.dbId, e]))
205 expect(byId.get('reactor/reactor/helios')?.activity).toBe('video')
206 expect(
207 byId.get('reactor/reactor/helios/events/set_prompt')?.activity,
208 ).toBe('video')
209 expect(byId.get('reactor/reactor/helios/events/start')?.activity).toBe(
210 'video',
211 )
212 expect(endpoints.every((e) => e.derivation === 'upstream-spec')).toBe(
213 true,
214 )
215​
216 for (const endpoint of endpoints) {
217 expect(endpoint.input ?? endpoint.output, endpoint.dbId).toBeDefined()
218 if (endpoint.input) expect(findDanglingRefs(endpoint.input)).toEqual([])
219 if (endpoint.output) {
220 expect(findDanglingRefs(endpoint.output)).toEqual([])
221 }
222 }
223​
224 const setPrompt = byId.get('reactor/reactor/helios/events/set_prompt')
225 expect(setPrompt?.input?.required).toEqual(['prompt'])
226​
227 const envelope = byId.get('reactor/reactor/helios')
228 expect(Array.isArray(envelope?.input?.oneOf)).toBe(true)
229 } finally {
230 globalThis.fetch = original
231 }
232 })
233​
234 it('hashes the extracted OpenAPI, not the surrounding HTML', async () => {
235 const original = globalThis.fetch
236 let n = 0
237 globalThis.fetch = ((url: string) => {
238 if (String(url) !== modelApiPageUrl('helios')) {
239 return Promise.resolve(new Response('not found', { status: 404 }))
240 }
241 n += 1
242 const html = htmlWithSpec(MINI_SPEC) + `<!-- ${String(n)} -->`
243 return Promise.resolve(new Response(html, { status: 200 }))
244 }) as typeof fetch
245 try {
246 const a = await provider.fetchSpec({})
247 const b = await provider.fetchSpec({})
248 const hashA = a.sources.find((s) => s.url.includes('helios'))?.hash
249 const hashB = b.sources.find((s) => s.url.includes('helios'))?.hash
250 expect(hashA).toBe(hashB)
251 } finally {
252 globalThis.fetch = original
253 }
254 })
255})
256​
257describe('reactor seed metadata', () => {
258 it('exports the isolation-required fields', () => {
259 expect(provider.id).toBe('reactor')
260 expect(provider.displayName).toBe('Reactor')
261 expect(provider.authEnvVar).toBe('REACTOR_API_KEY')
262 expect(provider.defaultDerivation).toBe('upstream-spec')
263 expect(provider.specGrain).toBe('model')
264 expect(provider.specSourceUrl).toMatch(/^https:\/\//)
265 expect(provider.modelsEndpoint).toBe(REACTOR_PRICING_URL)
266 })
267})