Open History to see the last commit
1import type { BilledUsage, StreamChunk } from '@tanstack/ai'
2
3/**
4 * Billing figures a finished video job reports. `VideoGenerateResult` — what
5 * `useGenerateVideo` hands back as its result — carries only the job id, url
6 * and expiry, so these are read off the terminal `generation:result` chunk
7 * through the hook's `onChunk` instead.
8 */
9export interface VideoBilling {
10 /** Billed quantity paired with the unit it is denominated in. */
11 billed?: BilledUsage
12 /** Provider-reported cost in USD, for providers that report one. */
13 cost?: number
14 /** Token total, for providers that bill media generation as tokens. */
15 totalTokens?: number
16}
17
18function numberField(source: object, key: string): number | undefined {
19 const value: unknown = Reflect.get(source, key)
20 return typeof value === 'number' ? value : undefined
21}
22
23/** Reads `usage.billed` when it carries the `{ quantity, unit }` pair. */
24function billedField(source: object): BilledUsage | undefined {
25 const value: unknown = Reflect.get(source, 'billed')
26 if (typeof value !== 'object' || value === null) return undefined
27 const quantity: unknown = Reflect.get(value, 'quantity')
28 const unit: unknown = Reflect.get(value, 'unit')
29 if (typeof quantity !== 'number' || typeof unit !== 'string') {
30 return undefined
31 }
32 return { quantity, unit }
33}
34
35/**
36 * Reads the usage block off a generation's terminal result chunk, or
37 * `undefined` for every other chunk (and for providers that report no usage).
38 */
39export function readVideoBilling(chunk: StreamChunk): VideoBilling | undefined {
40 if (chunk.type !== 'CUSTOM' || chunk.name !== 'generation:result') {
41 return undefined
42 }
43 const value: unknown = chunk.value
44 if (typeof value !== 'object' || value === null) return undefined
45 const usage: unknown = Reflect.get(value, 'usage')
46 if (typeof usage !== 'object' || usage === null) return undefined
47
48 const billed = billedField(usage)
49 const cost = numberField(usage, 'cost')
50 const totalTokens = numberField(usage, 'totalTokens')
51 if (billed === undefined && cost === undefined && totalTokens === undefined) {
52 return undefined
53 }
54 return {
55 ...(billed !== undefined && { billed }),
56 ...(cost !== undefined && { cost }),
57 ...(totalTokens !== undefined && { totalTokens }),
58 }
59}