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

xiaomi.test.ts

295 lines9.6 KB

1import { requestUrl } from '#/lib/text.ts'
2import { readFileSync } from 'node:fs'
3import { Validator } from '@cfworker/json-schema'
4import { price } from '@modelschemas/rate-card'
5import { afterEach, describe, expect, it, vi } from 'vitest'
6import {
7 htmlTables,
8 nativeSchemas,
9 xiaomiSpec,
10 XIAOMI_SCHEMA_URLS,
11 XIAOMI_MODELS,
12 XIAOMI_PRICING,
13 XIAOMI_THINKING,
14} from '../xiaomi-docs.ts'
15import { parseXiaomiModels, parseXiaomiPricing, provider } from './xiaomi.ts'
16​
17const fixture = (name: string) =>
18 readFileSync(
19 new URL(`../fixtures/xiaomi/${name}.txt`, import.meta.url),
20 'utf8',
21 )
22const catalog = fixture('model.md')
23const pricing = fixture('pay-as-you-go.md')
24const pricingSource = {
25 url: XIAOMI_PRICING,
26 hash: 'fixture',
27 extractedAt: '2026-10-09T00:00:00Z',
29afterEach(() => vi.unstubAllGlobals())
30function mockDocs(failedUrl?: string, modelDocument = catalog, status = 503) {
31 const requested: Array<string> = []
32 vi.stubGlobal('fetch', (input: string | URL | Request) => {
33 const url = requestUrl(input)
34 requested.push(url)
35 if (!url.startsWith('https://mimo.mi.com/static/docs/'))
36 throw new Error(`unexpected source ${url}`)
37 return Promise.resolve(
38 url === failedUrl
39 ? new Response('unavailable', {
40 status,
41 ...(status === 404 ? { statusText: 'Not Found' } : {}),
42 })
43 : new Response(
44 url === XIAOMI_MODELS
45 ? modelDocument
46 : fixture(url.split('/').at(-1) ?? ''),
47 ),
48 )
49 })
50 return requested
52​
53describe('Xiaomi native documentation', () => {
54 it('expands model table spans without copying a neighboring model fact', () => {
55 const models = parseXiaomiModels(catalog)
56 expect(models).toHaveLength(9)
57 expect(
58 models.find((model) => model.rawId === 'mimo-v2.6-pro-ultraspeed'),
59 ).toMatchObject({
60 contextWindow: 1_000_000,
61 maxOutput: 128_000,
62 capabilities: ['reasoning', 'streaming', 'tools', 'structured_outputs'],
63 })
64 expect(
65 models.find((model) => model.rawId === 'mimo-v2.5-tts-voicedesign'),
66 ).toMatchObject({ contextWindow: 8000, maxOutput: 8000, activity: 'audio' })
67 expect(() =>
68 htmlTables('<table><tr><td rowspan="3">one</td></tr></table>'),
69 ).toThrow(/rowspan/)
70 })
71​
72 it('uses USD real-time rates without domestic prices or batch discounts', () => {
73 const cards = parseXiaomiPricing(pricing, pricingSource)
74 const pro = cards.get('mimo-v2.6-pro')
75 const asr = cards.get('mimo-v2.5-asr')
76 expect(pro).toBeDefined()
77 expect(asr).toBeDefined()
78 if (!pro || !asr) throw new Error('fixture omitted prices')
79 expect(
80 price(pro, {}, { input_tokens: 1_000_000, output_tokens: 1_000_000 }),
81 ).toBeCloseTo(1.305)
82 expect(price(asr, {}, { audio_seconds: 3600 })).toBeCloseTo(0.074)
83 expect(cards.has('mimo-v2.5-tts')).toBe(false)
84 expect(() =>
85 parseXiaomiPricing(pricing.replace('$0.435', 'unknown'), pricingSource),
86 ).toThrow(/unreadable/)
87 expect(() =>
88 parseXiaomiPricing(
89 pricing.split('### Overseas Pricing')[0] ?? '',
90 pricingSource,
91 ),
92 ).toThrow(/overseas/)
93 expect(() =>
94 parseXiaomiPricing(
95 pricing.replaceAll('Input (Cache Hit)', 'Wrong column'),
96 pricingSource,
97 ),
98 ).toThrow(/headers/)
99 })
100​
101 it('extracts only first-party model facts and keeps unsourced prices null', async () => {
102 const urls = mockDocs()
103 const listed = await provider.listModels({})
104 expect(new Set(urls)).toEqual(
105 new Set([
106 XIAOMI_MODELS,
107 XIAOMI_PRICING,
108 XIAOMI_THINKING,
109 XIAOMI_SCHEMA_URLS[0],
110 ]),
111 )
112 expect(
113 listed.models.find((model) => model.rawId === 'mimo-v2.6-pro'),
114 ).toMatchObject({
115 reasoning: { mode: 'toggle', mandatory: false },
116 modalities: {
117 input: ['text', 'image', 'audio', 'video'],
118 output: ['text'],
119 },
120 })
121 expect(
122 listed.models.find((model) => model.rawId === 'mimo-v2.5-tts'),
123 ).toMatchObject({
124 pricing: null,
125 reasoning: null,
126 absent: { pricing: 'cleared' },
127 })
128 expect(
129 listed.models.find((model) => model.rawId === 'mimo-v2.5-pro')
130 ?.modalities,
131 ).toBeNull()
132 expect(listed.docsFailures).toEqual({ failed: 0, skipped: 0, first: [] })
133 })
134​
135 it('keeps every model when the chat docs page 404s', async () => {
136 const chatUrl = XIAOMI_SCHEMA_URLS[0]
137 if (!chatUrl) throw new Error('missing chat schema source URL')
138 mockDocs(chatUrl, catalog, 404)
139 const listed = await provider.listModels({})
140 expect(listed.models).toHaveLength(9)
141 for (const model of listed.models)
142 expect(model.absent?.modalities).toBe('unavailable')
143 expect(listed.docsFailures?.failed).toBe(1)
144 expect(listed.docsFailures?.first[0]?.source).toBe(chatUrl)
145 expect(listed.docsFailures?.first[0]?.error).toContain(chatUrl)
146 expect(listed.docsFailures?.first[0]?.error).toContain('404')
147 expect(
148 listed.models.find((model) => model.rawId === 'mimo-v2.6-pro'),
149 ).toMatchObject({
150 reasoning: { mode: 'toggle', mandatory: false },
151 })
152 expect(
153 listed.models.find((model) => model.rawId === 'mimo-v2.5-tts')?.absent
154 ?.pricing,
155 ).toBe('cleared')
156 })
157​
158 it('does not clear prices when the pricing page 404s', async () => {
159 mockDocs(XIAOMI_PRICING, catalog, 404)
160 const listed = await provider.listModels({})
161 expect(listed.models).toHaveLength(9)
162 for (const model of listed.models)
163 expect(model.absent?.pricing).toBe('unavailable')
164 expect(
165 listed.models.find((model) => model.rawId === 'mimo-v2.5-tts')?.absent
166 ?.pricing,
167 ).toBe('unavailable')
168 expect(listed.docsFailures?.first[0]?.source).toBe(XIAOMI_PRICING)
169 expect(
170 listed.models.find((model) => model.rawId === 'mimo-v2.6-pro'),
171 ).toMatchObject({
172 reasoning: { mode: 'toggle', mandatory: false },
173 modalities: {
174 input: ['text', 'image', 'audio', 'video'],
175 output: ['text'],
176 },
177 })
178 })
179​
180 it('keeps stored reasoning when the thinking page 404s', async () => {
181 mockDocs(XIAOMI_THINKING, catalog, 404)
182 const listed = await provider.listModels({})
183 expect(listed.models).toHaveLength(9)
184 for (const model of listed.models)
185 expect(model.absent?.reasoning).toBe('unavailable')
186 expect(listed.docsFailures?.first[0]?.source).toBe(XIAOMI_THINKING)
187 })
188​
189 it('fails a fetch or malformed source rather than returning a successful empty listing', async () => {
190 mockDocs(XIAOMI_MODELS)
191 await expect(provider.listModels({})).rejects.toThrow(/503/)
192 expect(() => parseXiaomiModels('<html>login</html>')).toThrow()
193 expect(() =>
194 parseXiaomiModels(catalog.replaceAll('Context Window:', 'Unrecognized:')),
195 ).toThrow(/limits/)
196 expect(() =>
197 parseXiaomiModels(
198 catalog.replaceAll('Context Window: 1M', 'Context Window: 0'),
199 ),
200 ).toThrow(/invalid token/)
201 })
202​
203 it('keeps a newly listed model with an unsourced price null', async () => {
204 const added = catalog.replace(
205 '`mimo-v2.6-pro`</span>',
206 '`mimo-v2.6-pro` `mimo-unpriced-test`</span>',
207 )
208 mockDocs(undefined, added)
209 const listed = await provider.listModels({})
210 const addedModel = listed.models.find(
211 (model) => model.rawId === 'mimo-unpriced-test',
212 )
213 expect(addedModel).toMatchObject({ pricing: null })
214 expect(addedModel?.absent?.pricing).toBeUndefined()
215 })
216​
217 it('converts native schema variants and real shared paths, including audio branches', async () => {
218 mockDocs()
219 const result = await provider.fetchSpec({})
220 const spec = result.specs[0]
221 expect(Object.keys(spec?.paths ?? {})).toEqual([
222 '/v1/chat/completions',
223 '/v1/responses',
224 '/anthropic/v1/messages',
225 ])
226 expect(result.sources.map((source) => source.url)).toEqual(
227 XIAOMI_SCHEMA_URLS,
228 )
229 const request = spec?.paths?.['/v1/chat/completions']?.post
230 ?.requestBody as { content: { 'application/json': { schema: object } } }
231 const validator = new Validator(request.content['application/json'].schema)
232 expect(
233 validator.validate({
234 model: 'mimo-v2.6-pro',
235 messages: [{ role: 'user', content: 'Hello' }],
236 }).valid,
237 ).toBe(true)
238 expect(
239 validator.validate({
240 model: 'invented',
241 messages: [{ role: 'user', content: 'Hello' }],
242 }).valid,
243 ).toBe(false)
244 expect(
245 validator.validate({
246 model: 'mimo-v2.6-pro',
247 messages: [{ role: 'invented', content: 'Hello' }],
248 }).valid,
249 ).toBe(false)
250 expect(
251 validator.validate({
252 model: 'mimo-v2.5-asr',
253 messages: [
254 {
255 role: 'user',
256 content: [
257 {
258 type: 'input_audio',
259 input_audio: { data: 'base64', format: 'wav' },
260 },
261 ],
262 },
263 ],
264 }).valid,
265 ).toBe(true)
266 expect(
267 provider.generationEndpointId?.({
268 rawId: 'mimo-v2.5-asr',
269 activity: 'audio',
270 }),
271 ).toBeNull()
272 })
273​
274 it('rejects malformed native trees and unknown types without generic schema fallbacks', () => {
275 expect(() => nativeSchemas('<InlineSchemaV2 schema={`broken`} />')).toThrow(
276 /JSON/,
277 )
278 expect(() =>
279 nativeSchemas(
280 '<InlineSchemaV2 schema={`[{"name":"x","type":"invented","isBold":true}]`} />',
281 ),
282 ).toThrow(/unsupported/)
283 expect(() =>
284 xiaomiSpec([
285 {
286 text: fixture('openai-api-post.md').replace(
287 '## Request Address',
288 '## Missing',
289 ),
290 url: 'test',
291 },
292 ]),
293 ).toThrow(/address/)
294 })
295})