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

xiaomi.test.ts

236 lines7.3 KB

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