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

extract-fal-pricing.test.ts

475 lines14.6 KB

1import { describe, expect, it, vi } from 'vitest'
2​
3import { verifyExamples } from '@modelschemas/rate-card'
4​
5import { NANO_BANANA_2 } from '../../../packages/rate-card/src/fixtures/nano-banana-2.ts'
6​
7import {
8 FAL_PRICING_EXTRACT_CRONS,
9 FAL_PRICING_EXTRACT_CAP,
10 FAL_PRICING_EXTRACT_MODEL,
11 FAL_PRICING_FETCH_CAP,
12 FAL_PRICING_FETCH_FAIL_ABORT,
13 checkExtractedCard,
14 isRetryableLlmsStatus,
15 extractRateCardWithGrok,
16 isStubPricingSection,
17 pricingSection,
18 pricingSectionHash,
19 resumeIndex,
20 shouldSkipExtract,
21} from './extract-fal-pricing.ts'
22import { parseFalUnitRate } from './fal-unit-rate.ts'
23import { SPEC_SYNC_SHARD_CRONS } from './sync.ts'
24​
25/** A fetch mock answering successive chat calls with these contents. */
26function grokReplies(...replies: Array<unknown>) {
27 const mock = vi.fn<typeof fetch>()
28 for (const reply of replies) {
29 const content = typeof reply === 'string' ? reply : JSON.stringify(reply)
30 mock.mockResolvedValueOnce(
31 new Response(JSON.stringify({ choices: [{ message: { content } }] }), {
32 status: 200,
33 }),
34 )
35 }
36 return mock
38​
39const NANO_LLMS = `# Nano Banana 2
40​
41## Overview
42​
43- **Endpoint**: \`https://fal.run/fal-ai/nano-banana-2\`
44​
45## Pricing
46​
47Your request will cost **$0.08** per image. For **$1.00**, you can run this model **12** times. 2K and 4K outputs will be charged at **1.5** times and **2** times the standard rate, respectively. 0.5K (512px) resolution outputs will be charged at **0.75** times the standard rate. If web search is used, an additional $0.015 will be charged. If high thinking is used, an additional $0.002 will be charged. **Note: Pricing is subject to change.**
48​
49For more details, see [fal.ai pricing](https://fal.ai/pricing).
50​
51## API Information
52​
53This model can be used via our HTTP API.
55​
56describe('pricingSection', () => {
57 it('cuts the Pricing heading from llms.txt and ignores sibling sections', () => {
58 const section = pricingSection(NANO_LLMS)
59 expect(section.startsWith('## Pricing')).toBe(true)
60 expect(section).toContain('$0.08')
61 expect(section).not.toContain('API Information')
62 expect(section).not.toContain('Nano Banana 2 is')
63 })
64​
65 it('is empty when the heading is absent', () => {
66 expect(pricingSection('# Title\n\n## Overview\n\nNope.\n')).toBe('')
67 })
68})
69​
70describe('isStubPricingSection', () => {
71 it('treats empty, boilerplate, and zero-dollar sections as stubs', () => {
72 expect(isStubPricingSection('')).toBe(true)
73 expect(
74 isStubPricingSection(
75 '## Pricing\n\nFor more details, see [fal.ai pricing](https://fal.ai/pricing).',
76 ),
77 ).toBe(true)
78 expect(
79 isStubPricingSection(
80 '## Pricing\n\nYour request will cost **$0.00** per image.',
81 ),
82 ).toBe(true)
83 })
84​
85 it('keeps a section that names a positive price', () => {
86 expect(isStubPricingSection(pricingSection(NANO_LLMS))).toBe(false)
87 })
88​
89 it('keeps bold and suffix-$ prices the old regex missed (#70)', () => {
90 expect(isStubPricingSection('- **Price**: $**0.04** per images')).toBe(
91 false,
92 )
93 expect(isStubPricingSection('- **Price**: **0.17** $ per second')).toBe(
94 false,
95 )
96 })
97})
98​
99describe('pricingSectionHash', () => {
100 it('hashes the Pricing section, not the rest of the file', async () => {
101 const a = await pricingSectionHash(pricingSection(NANO_LLMS))
102 const b = await pricingSectionHash(
103 pricingSection(NANO_LLMS.replace('Nano Banana 2', 'Renamed')),
104 )
105 const c = await pricingSectionHash(
106 pricingSection(NANO_LLMS.replace('$0.08', '$0.09')),
107 )
108 expect(a).toMatch(/^[0-9a-f]{64}$/)
109 expect(a).toBe(b)
110 expect(c).not.toBe(a)
111 })
112})
113​
114describe('resumeIndex', () => {
115 const ids = ['a/one', 'b/two', 'c/three']
116​
117 it('starts at 0 with no cursor and wraps past the tail', () => {
118 expect(resumeIndex(ids, null)).toBe(0)
119 expect(resumeIndex(ids, 'c/three')).toBe(0)
120 expect(resumeIndex(ids, 'b/two')).toBe(2)
121 })
122​
123 it('resumes after a cursor that left the roster', () => {
124 expect(resumeIndex(ids, 'a/two')).toBe(1)
125 expect(resumeIndex(ids, 'z/gone')).toBe(0)
126 })
127})
128​
129describe('shouldSkipExtract', () => {
130 const hash = 'a'.repeat(64)
131 const now = 1_781_150_000
132​
133 it('skips an unchanged hash and re-extracts after expiresAt', () => {
134 expect(
135 shouldSkipExtract({
136 storedHash: hash,
137 sectionHash: hash,
138 hasCard: true,
139 stub: false,
140 expiresAt: undefined,
141 now,
142 }),
143 ).toBe(true)
144 expect(
145 shouldSkipExtract({
146 storedHash: hash,
147 sectionHash: 'b'.repeat(64),
148 hasCard: true,
149 stub: false,
150 expiresAt: undefined,
151 now,
152 }),
153 ).toBe(false)
154 expect(
155 shouldSkipExtract({
156 storedHash: hash,
157 sectionHash: hash,
158 hasCard: true,
159 stub: false,
160 expiresAt: '2020-01-01T00:00:00.000Z',
161 now,
162 }),
163 ).toBe(false)
164 expect(
165 shouldSkipExtract({
166 storedHash: hash,
167 sectionHash: hash,
168 hasCard: true,
169 stub: false,
170 expiresAt: '2099-01-01T00:00:00.000Z',
171 now,
172 }),
173 ).toBe(true)
174 })
175​
176 it('retries an unchanged hash whose card is still null unless it is a stub (#84)', () => {
177 const base = { storedHash: hash, sectionHash: hash, expiresAt: undefined }
178 expect(
179 shouldSkipExtract({ ...base, hasCard: false, stub: false, now }),
180 ).toBe(false)
181 expect(
182 shouldSkipExtract({ ...base, hasCard: false, stub: true, now }),
183 ).toBe(true)
184 })
185})
186​
187describe('FAL_PRICING_EXTRACT_CRONS', () => {
188 it('is six hourly daytime shards, none of them a spec-sync shard', () => {
189 expect([...FAL_PRICING_EXTRACT_CRONS]).toEqual([
190 '0 6 * * *',
191 '0 7 * * *',
192 '0 8 * * *',
193 '0 9 * * *',
194 '0 10 * * *',
195 '0 11 * * *',
196 ])
197 expect(FAL_PRICING_FETCH_CAP).toBe(250)
198 expect(FAL_PRICING_EXTRACT_CAP).toBe(40)
199 expect(FAL_PRICING_FETCH_FAIL_ABORT).toBe(8)
200 expect(FAL_PRICING_EXTRACT_MODEL).toBe('grok-4-fast')
201 for (const cron of FAL_PRICING_EXTRACT_CRONS) {
202 expect(
203 (SPEC_SYNC_SHARD_CRONS as ReadonlyArray<string>).includes(cron),
204 ).toBe(false)
205 expect(cron).not.toBe('*/15 * * * *')
206 }
207 // Six shards x 250 fetches covers the FAL roster in one calendar day.
208 expect(
209 FAL_PRICING_EXTRACT_CRONS.length * FAL_PRICING_FETCH_CAP,
210 ).toBeGreaterThanOrEqual(1500)
211 })
212​
213 it('keeps wrangler.jsonc in lockstep', async () => {
214 const fs = await import('node:fs/promises')
215 const raw = await fs.readFile('wrangler.jsonc', 'utf8')
216 for (const cron of FAL_PRICING_EXTRACT_CRONS) {
217 expect(raw).toContain(`"${cron}"`)
218 }
219 expect(raw).toContain('"*/15 * * * *"')
220 for (const cron of SPEC_SYNC_SHARD_CRONS) {
221 expect(raw).toContain(`"${cron}"`)
222 }
223 })
224})
225​
226describe('isRetryableLlmsStatus', () => {
227 it('retries network, 408, 429, and 5xx; 404 is done', () => {
228 expect(isRetryableLlmsStatus(0)).toBe(true)
229 expect(isRetryableLlmsStatus(408)).toBe(true)
230 expect(isRetryableLlmsStatus(429)).toBe(true)
231 expect(isRetryableLlmsStatus(500)).toBe(true)
232 expect(isRetryableLlmsStatus(503)).toBe(true)
233 expect(isRetryableLlmsStatus(404)).toBe(false)
234 expect(isRetryableLlmsStatus(400)).toBe(false)
235 })
236})
237​
238describe('extractRateCardWithGrok', () => {
239 const args = {
240 pricingText: pricingSection(NANO_LLMS),
241 requestProperties: new Set([
242 'num_images',
243 'resolution',
244 'enable_web_search',
245 'thinking_level',
246 ]),
247 sourceUrl: NANO_BANANA_2.source.url,
248 sourceHash: 'c'.repeat(64),
249 now: 1_781_150_000,
250 apiKey: 'xai-test',
251 }
252​
253 it('stamps source and accepts a verified card', async () => {
254 const { source: _source, ...body } = NANO_BANANA_2
255 const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(
256 new Response(
257 JSON.stringify({
258 choices: [{ message: { content: JSON.stringify(body) } }],
259 }),
260 { status: 200 },
261 ),
262 )
263 vi.stubGlobal('fetch', fetchMock)
264 try {
265 const card = await extractRateCardWithGrok(args)
266 expect(card).not.toBeNull()
267 expect(card).not.toBe('unverified')
268 if (card === null || card === 'unverified') return
269 expect(card.source.hash).toBe(args.sourceHash)
270 expect(card.source.url).toBe(args.sourceUrl)
271 expect(fetchMock.mock.calls[0]?.[0]).toBe(
272 'https://api.x.ai/v1/chat/completions',
273 )
274 const init = fetchMock.mock.calls[0]?.[1]
275 expect(init?.method).toBe('POST')
276 const payload = JSON.parse(String(init?.body)) as {
277 model: string
278 }
279 expect(payload.model).toBe(FAL_PRICING_EXTRACT_MODEL)
280 } finally {
281 vi.unstubAllGlobals()
282 }
283 })
284​
285 it('returns unverified only for a section that names no price', async () => {
286 const fetchMock = grokReplies({ unverified: true })
287 vi.stubGlobal('fetch', fetchMock)
288 try {
289 await expect(
290 extractRateCardWithGrok({
291 ...args,
292 pricingText:
293 '## Pricing\n\nSee [fal.ai pricing](https://fal.ai/pricing).',
294 }),
295 ).resolves.toBe('unverified')
296 expect(fetchMock).toHaveBeenCalledTimes(1)
297 } finally {
298 vi.unstubAllGlobals()
299 }
300 })
301​
302 it('sends a priced section back once when the model says unverified (#88)', async () => {
303 const { source: _source, ...body } = NANO_BANANA_2
304 const fetchMock = grokReplies({ unverified: true }, body)
305 vi.stubGlobal('fetch', fetchMock)
306 try {
307 const card = await extractRateCardWithGrok(args)
308 expect(card).toMatchObject({ price: NANO_BANANA_2.price })
309 expect(fetchMock).toHaveBeenCalledTimes(2)
310 const retry = JSON.parse(String(fetchMock.mock.calls[1]?.[1]?.body)) as {
311 model: string
312 messages: Array<{ role: string; content: string }>
313 }
314 expect(retry.model).toBe(FAL_PRICING_EXTRACT_MODEL)
315 expect(retry.messages.map((m) => m.role)).toEqual([
316 'system',
317 'user',
318 'assistant',
319 'user',
320 ])
321 expect(retry.messages[3]?.content).toContain('$0.08')
322 } finally {
323 vi.unstubAllGlobals()
324 }
325 })
326​
327 it('returns null when a priced section is refused twice', async () => {
328 const { source: _source, ...body } = NANO_BANANA_2
329 for (const reply of [{ unverified: true }, { ...body, examples: [] }]) {
330 const fetchMock = grokReplies(reply, reply)
331 vi.stubGlobal('fetch', fetchMock)
332 try {
333 await expect(extractRateCardWithGrok(args)).resolves.toBeNull()
334 expect(fetchMock).toHaveBeenCalledTimes(2)
335 } finally {
336 vi.unstubAllGlobals()
337 }
338 }
339 })
340​
341 it('returns null when verifyExamples fails on both turns', async () => {
342 const { source: _source, examples, ...body } = NANO_BANANA_2
343 const first = examples[0]
344 const bad = {
345 ...body,
346 examples: first
347 ? [{ ...first, usd: 999 }]
348 : [{ params: {}, usd: 999, quote: 'nope' }],
349 }
350 const fetchMock = grokReplies(bad, bad)
351 vi.stubGlobal('fetch', fetchMock)
352 try {
353 await expect(extractRateCardWithGrok(args)).resolves.toBeNull()
354 const retry = JSON.parse(String(fetchMock.mock.calls[1]?.[1]?.body)) as {
355 messages: Array<{ content: string }>
356 }
357 expect(retry.messages[3]?.content).toContain('verifyExamples failed')
358 } finally {
359 vi.unstubAllGlobals()
360 }
361 })
362​
363 it('rejects a request-bound param the input schema does not have', async () => {
364 const { source: _source, ...body } = NANO_BANANA_2
365 const invented = {
366 ...body,
367 inputs: {
368 ...body.inputs,
369 num_images: { param: 'image_count', kind: 'number', default: 1 },
370 },
371 }
372 vi.stubGlobal('fetch', grokReplies(invented, invented))
373 try {
374 await expect(extractRateCardWithGrok(args)).resolves.toBeNull()
375 } finally {
376 vi.unstubAllGlobals()
377 }
378 })
379​
380 it('fails closed on a non-card payload', async () => {
381 vi.stubGlobal('fetch', grokReplies({ nope: true }, 'not json'))
382 try {
383 await expect(extractRateCardWithGrok(args)).resolves.toBeNull()
384 } finally {
385 vi.unstubAllGlobals()
386 }
387 })
388})
389​
390describe('checkExtractedCard', () => {
391 const base = {
392 requestProperties: new Set(['resolution', 'duration']),
393 sourceUrl:
394 'https://fal.ai/models/fal-ai/wan-25-preview/text-to-video/llms.txt',
395 sourceHash: 'd'.repeat(64),
396 now: 1_781_150_000,
397 }
398​
399 /** Live fal-ai/wan-25-preview/text-to-video, read 2026-09-30. */
400 const WAN_TABLE = `## Pricing
401​
402Your request will cost **$0.05** per second for **480p**, **$0.10** per second for **720p**, **$0.15** per second for **1080p**.
403​
404For more details, see [fal.ai pricing](https://fal.ai/pricing).`
405​
406 it('accepts a lookup calculator for a per-second resolution table', () => {
407 // The fast path refuses several rates by design — this is leftover work.
408 expect(parseFalUnitRate(WAN_TABLE)).toBeNull()
409 const reply = {
410 inputs: {
411 resolution: {
412 param: 'resolution',
413 kind: 'enum',
414 bound: 'request',
415 values: ['480p', '720p', '1080p'],
416 default: '1080p',
417 },
418 seconds: { param: 'seconds', kind: 'number', bound: 'usage' },
419 },
420 tables: { rate: { '480p': 0.05, '720p': 0.1, '1080p': 0.15 } },
421 price: {
422 '*': [
423 { var: 'seconds' },
424 { lookup: { table: 'rate', keys: [{ var: 'resolution' }] } },
425 ],
426 },
427 examples: [
428 {
429 params: { resolution: '480p', seconds: 1 },
430 usd: 0.05,
431 quote: 'Your request will cost **$0.05** per second for **480p**',
432 },
433 {
434 params: { resolution: '720p', seconds: 1 },
435 usd: 0.1,
436 quote: '**$0.10** per second for **720p**',
437 },
438 {
439 params: { seconds: 1 },
440 usd: 0.15,
441 quote: '**$0.15** per second for **1080p**',
442 },
443 ],
444 }
445 const card = checkExtractedCard(JSON.stringify(reply), {
446 ...base,
447 pricingText: WAN_TABLE,
448 })
449 if (card === 'unverified' || 'error' in card) {
450 throw new Error(JSON.stringify(card))
451 }
452 expect(card.source.hash).toBe(base.sourceHash)
453 expect(verifyExamples(card).every((r) => r.ok)).toBe(true)
454 expect(card.price).toMatchObject({
455 '*': [{ var: 'seconds' }, { lookup: {} }],
456 })
457 })
458​
459 it('refuses unverified for the table but allows it for a zero-price stub', () => {
460 const refused = checkExtractedCard('{"unverified":true}', {
461 ...base,
462 pricingText: WAN_TABLE,
463 })
464 expect(
465 typeof refused === 'object' && 'error' in refused && refused.error,
466 ).toContain('$0.05')
467 expect(
468 checkExtractedCard('{"unverified":true}', {
469 ...base,
470 pricingText:
471 '## Pricing\n\nYour request will cost **$0.00** per image.',
472 }),
473 ).toBe('unverified')
474 })
475})