Open History to see the last commit
1/**
2 * Deterministic rate-card evaluator. ~100 lines of JSONLogic over
3 * the closed vocabulary in `card.ts` — smaller than json-logic-js,
4 * no `eval`, and it refuses instead of coercing: an unknown op, an unbound
5 * input, a missing table key or a non-numeric operand throws, and so does a
6 * price that is not a finite positive number. A refusal is an honest
7 * "unknown"; a made-up number is a wrong price.
8 */
9import { CORE_OPS, currencyWrapper } from './card.ts'
10import type {
11 CoreOp,
12 Expr,
13 RateCard,
14 RateCardEstimate,
15 RateCardExample,
16 Table,
17} from './card.ts'
18
19export type RateCardErrorCode =
20 | 'unknown-op'
21 | 'unbound-var'
22 | 'bad-input'
23 | 'missing-key'
24 | 'not-a-number'
25 | 'not-comparable'
26 | 'bad-result'
27 | 'estimate-unavailable'
28 | 'unknown-usage-key'
29 | 'mixed-usage'
30
31export class RateCardError extends Error {
32 /**
33 * @param input The card input (its key in `card.inputs`) the caller did
34 * not supply, on `bad-input` "required" and `estimate-unavailable`.
35 */
36 constructor(
37 readonly code: RateCardErrorCode,
38 message: string,
39 readonly input?: string,
40 ) {
41 super(message)
42 this.name = 'RateCardError'
43 }
44}
45
46type Vars = Record<string, unknown>
47
48/**
49 * A card's currency and the expression that yields the amount in it. Safe
50 * on a card that was never parsed: a malformed wrapper, or no price at
51 * all, throws `unknown-op` rather than naming a currency it cannot vouch
52 * for.
53 */
54export function cardPrice(card: Pick<RateCard, 'price'>): {
55 currency: string
56 expr: Expr
57} {
58 const loose = card as { price?: unknown; currency?: unknown } | null
59 const raw = loose?.price
60 const wrapper = currencyWrapper(raw)
61 if (raw == null || wrapper === 'malformed') {
62 throw new RateCardError(
63 'unknown-op',
64 `price is not an expression or { currency: [code, expr] }: ${JSON.stringify(raw)}`,
65 )
66 }
67 // The schema refuses this key; an unparsed card meant as another
68 // currency must not be read as USD here either.
69 if (loose?.currency !== undefined) {
70 throw new RateCardError(
71 'unknown-op',
72 'currency is stated by wrapping price, not by a top-level key',
73 )
74 }
75 return wrapper === null
76 ? { currency: 'USD', expr: raw }
77 : { currency: wrapper.currency, expr: wrapper.expr as Expr }
78}
79
80/** The ISO-4217 code a card's amounts are in: USD unless its price says. */
81export function cardCurrency(card: Pick<RateCard, 'price'>): string {
82 return cardPrice(card).currency
83}
84
85export const isRecord = (v: unknown): v is Record<string, unknown> =>
86 typeof v === 'object' && v !== null && !Array.isArray(v)
87
88const isCoreOp = (op: string): op is CoreOp =>
89 (CORE_OPS as readonly string[]).includes(op)
90
91/** `{var: 'image_size.width'}` walks dotted paths. */
92function readVar(vars: Vars, path: string): unknown {
93 let value: unknown = vars
94 for (const key of path.split('.')) {
95 if (!isRecord(value) || !(key in value)) return undefined
96 value = value[key]
97 }
98 return value
99}
100
101/**
102 * `==` is strict, unlike JSONLogic's loose `==`: a number against a string
103 * (Kling's `duration` "5" is bound as 5) refuses instead of quietly taking
104 * the wrong branch.
105 */
106function same(a: unknown, b: unknown): boolean {
107 const kind = (v: unknown) =>
108 typeof v === 'number' || typeof v === 'string' || typeof v === 'boolean'
109 ? typeof v
110 : undefined
111 if (kind(a) === undefined || kind(a) !== kind(b)) {
112 throw new RateCardError(
113 'not-comparable',
114 `${JSON.stringify(a)} vs ${JSON.stringify(b)}`,
115 )
116 }
117 return a === b
118}
119
120const truthy = (v: unknown): boolean =>
121 Array.isArray(v) ? v.length > 0 : Boolean(v)
122
123function lookup(
124 tables: Record<string, Table>,
125 table: string,
126 path: string[],
127): number | undefined {
128 let node: number | Table | undefined = tables[table]
129 for (const key of path) {
130 node = typeof node === 'object' ? node[key] : undefined
131 }
132 return typeof node === 'number' ? node : undefined
133}
134
135function evalExpr(
136 expr: Expr,
137 vars: Vars,
138 tables: Record<string, Table>,
139): unknown {
140 if (typeof expr !== 'object') return expr
141 const ev = (e: Expr) => evalExpr(e, vars, tables)
142 const num = (e: Expr): number => {
143 const v = ev(e)
144 if (typeof v !== 'number' || !Number.isFinite(v)) {
145 throw new RateCardError(
146 'not-a-number',
147 `${JSON.stringify(e)} → ${JSON.stringify(v)}`,
148 )
149 }
150 return v
151 }
152
153 if ('lookup' in expr) {
154 const { table, keys, default: fallback } = expr.lookup
155 const path = keys.map((k) => {
156 const key = ev(k)
157 if (typeof key === 'string') return key
158 if (typeof key === 'number') return String(key)
159 throw new RateCardError(
160 'missing-key',
161 `${table}: key ${JSON.stringify(key)}`,
162 )
163 })
164 const hit = lookup(tables, table, path)
165 if (hit !== undefined) return hit
166 if (fallback !== undefined) return ev(fallback)
167 throw new RateCardError('missing-key', `${table}[${path.join('][')}]`)
168 }
169
170 const keys = Object.keys(expr)
171 const op = keys[0]
172 if (keys.length !== 1 || op === undefined || !isCoreOp(op)) {
173 throw new RateCardError('unknown-op', keys.join(','))
174 }
175 const raw = expr[op]
176 const args: Expr[] = Array.isArray(raw) ? raw : raw === undefined ? [] : [raw]
177 const arg = (i: number): Expr => {
178 const e = args[i]
179 if (e === undefined) {
180 throw new RateCardError('unknown-op', `${op}: missing operand ${i}`)
181 }
182 return e
183 }
184 const name = (e: Expr): string => {
185 if (typeof e !== 'string') {
186 throw new RateCardError('unbound-var', JSON.stringify(e))
187 }
188 return e
189 }
190
191 switch (op) {
192 case 'var': {
193 const v = readVar(vars, name(arg(0)))
194 if (v === undefined) throw new RateCardError('unbound-var', name(arg(0)))
195 return v
196 }
197 case 'missing':
198 return args.map(name).filter((n) => readVar(vars, n) === undefined)
199 case '+':
200 return args.reduce<number>((sum, e) => sum + num(e), 0)
201 case '*':
202 return args.reduce<number>((product, e) => product * num(e), 1)
203 case '-':
204 return args.length === 1 ? -num(arg(0)) : num(arg(0)) - num(arg(1))
205 case '/':
206 return num(arg(0)) / num(arg(1))
207 case 'max':
208 return Math.max(...args.map(num))
209 case 'min':
210 return Math.min(...args.map(num))
211 case 'ceil':
212 return Math.ceil(num(arg(0)))
213 case 'floor':
214 return Math.floor(num(arg(0)))
215 case '==':
216 return same(ev(arg(0)), ev(arg(1)))
217 case '!=':
218 return !same(ev(arg(0)), ev(arg(1)))
219 case '<':
220 return num(arg(0)) < num(arg(1))
221 case '<=':
222 return num(arg(0)) <= num(arg(1))
223 case '>':
224 return num(arg(0)) > num(arg(1))
225 case '>=':
226 return num(arg(0)) >= num(arg(1))
227 case 'and': {
228 let last: unknown = true
229 for (const e of args) {
230 last = ev(e)
231 if (!truthy(last)) return last
232 }
233 return last
234 }
235 case 'or': {
236 let last: unknown = false
237 for (const e of args) {
238 last = ev(e)
239 if (truthy(last)) return last
240 }
241 return last
242 }
243 case 'if': {
244 // [cond, then, cond, then, ..., else]
245 for (let i = 0; i + 1 < args.length; i += 2) {
246 if (truthy(ev(arg(i)))) return ev(arg(i + 1))
247 }
248 return args.length % 2 === 1 ? ev(arg(args.length - 1)) : null
249 }
250 }
251}
252
253const isNumeric = (v: unknown): v is number | string =>
254 (typeof v === 'number' && Number.isFinite(v)) ||
255 (typeof v === 'string' && v.trim() !== '' && Number.isFinite(Number(v)))
256
257/**
258 * Bind every input from `vars` by param name, with defaults; the param of
259 * each input that took one is appended to `defaulted`. Never applies an
260 * `estimate`: a number input with one but no value throws `required` here
261 * (see `priceDetailed`).
262 */
263export function bindInputs(
264 card: Pick<RateCard, 'inputs'>,
265 params: Vars,
266 defaulted: string[] = [],
267): Vars {
268 const vars: Vars = {}
269 for (const [name, input] of Object.entries(card.inputs)) {
270 const raw = params[input.param]
271 const orDefault = (fallback: unknown) => {
272 if (raw == null && fallback !== undefined) defaulted.push(input.param)
273 return raw ?? fallback
274 }
275 const bad = (why: string, value?: unknown) =>
276 new RateCardError(
277 'bad-input',
278 `${name} (${input.param}): ${why}${value === undefined ? '' : ` ${JSON.stringify(value)}`}`,
279 why === 'required' ? name : undefined,
280 )
281 switch (input.kind) {
282 case 'count':
283 if (raw === undefined) {
284 vars[name] = 0
285 defaulted.push(input.param)
286 } else if (Array.isArray(raw)) vars[name] = raw.length
287 else throw bad('expected a list, got', raw)
288 break
289 case 'number': {
290 const value = orDefault(input.default)
291 if (value === undefined) throw bad('required')
292 // Enum-typed durations arrive as strings ("5").
293 if (!isNumeric(value)) throw bad('not a number:', value)
294 vars[name] = Number(value)
295 break
296 }
297 case 'boolean': {
298 const value = orDefault(input.default)
299 if (value === undefined) throw bad('required')
300 if (typeof value !== 'boolean')
301 throw bad('expected a boolean, got', value)
302 vars[name] = value
303 break
304 }
305 case 'enum': {
306 const value = orDefault(input.default)
307 if (value === undefined) throw bad('required')
308 if (typeof value !== 'string' || !input.values.includes(value)) {
309 throw bad(`not one of ${input.values.join('|')}:`, value)
310 }
311 vars[name] = value
312 break
313 }
314 case 'dimensions': {
315 const value = orDefault(input.default)
316 if (
317 isRecord(value) &&
318 isNumeric(value.width) &&
319 isNumeric(value.height)
320 ) {
321 vars[name] = {
322 width: Number(value.width),
323 height: Number(value.height),
324 }
325 break
326 }
327 const pixels =
328 typeof value === 'string' ? /^(\d+)x(\d+)$/.exec(value) : null
329 if (pixels) {
330 vars[name] = { width: Number(pixels[1]), height: Number(pixels[2]) }
331 break
332 }
333 if (typeof value === 'string' && input.levels?.includes(value)) {
334 vars[name] = { level: value }
335 break
336 }
337 const preset =
338 typeof value === 'string' ? input.presets?.[value] : undefined
339 if (!preset) throw bad('unknown size:', value)
340 vars[name] = { width: preset[0], height: preset[1] }
341 break
342 }
343 }
344 }
345 return vars
346}
347
348/**
349 * The amount for this call, as billed, in the card's currency
350 * (`cardCurrency(card)`; USD unless the card says otherwise). Never add
351 * or compare amounts from cards in different currencies. Request-bound
352 * levers read `request`;
353 * usage-bound levers read `usage`. A usage key on the request body, or a
354 * request field in usage, is not read. Omit `usage` only when every
355 * usage-bound input has a default (or the card has none); token cards that
356 * require `input_tokens` / `output_tokens` throw `bad-input` without them.
357 * Never estimates: an omitted input that carries an `estimate` throws
358 * `required` like any other — call `priceDetailed` to get a labelled
359 * estimate. Throws `RateCardError` rather than returning a number it
360 * cannot stand behind.
361 */
362export function price(
363 card: RateCard,
364 request: Vars = {},
365 usage: Vars = {},
366): number {
367 return evaluate(card, request, usage, false).amount
368}
369
370export interface PriceResult {
371 /** The price, in `currency`. */
372 amount: number
373 /** ISO-4217 code `amount` is in. */
374 currency: string
375 /** `amount` again when `currency` is USD; absent for any other currency. */
376 usd?: number
377 /**
378 * Params of inputs the caller omitted whose value came from the card's
379 * published `estimate`. Empty means every input was supplied (or a plain
380 * default), so `amount` is the price as billed.
381 */
382 estimated: string[]
383 /**
384 * Params of inputs the caller omitted that took the card's `default` (an
385 * omitted count input counts as an empty list). The card assumes these
386 * values; it did not get them.
387 */
388 defaulted: string[]
389 /**
390 * Request keys the card does not read. Request-bound cards get full
391 * request bodies, so these do not change the price.
392 */
393 ignored: string[]
394}
395
396/** Read each input's param from the request or usage object by bound. */
397function collect(inputs: RateCard['inputs'], request: Vars, usage: Vars): Vars {
398 const vars: Vars = {}
399 for (const input of Object.values(inputs)) {
400 const from = input.bound === 'usage' ? usage : request
401 if (input.param in from) vars[input.param] = from[input.param]
402 }
403 return vars
404}
405
406/**
407 * The request and usage keys a card reads, its estimate inputs included,
408 * in card order.
409 */
410export function cardParams(card: Pick<RateCard, 'inputs'>): {
411 request: string[]
412 usage: string[]
413} {
414 const request = new Set<string>()
415 const usage = new Set<string>()
416 const add = (input: RateCardEstimate['inputs'][string]) =>
417 (input.bound === 'usage' ? usage : request).add(input.param)
418 for (const input of Object.values(card.inputs)) {
419 add(input)
420 if (input.kind === 'number' && input.estimate) {
421 Object.values(input.estimate.inputs).forEach(add)
422 }
423 }
424 return { request: [...request], usage: [...usage] }
425}
426
427/**
428 * `price`, but an omitted input that carries an `estimate` is estimated
429 * by it and named in `estimated`. An estimate that cannot be made for this
430 * request throws `estimate-unavailable` naming the input to pass instead.
431 * A usage key the card does not read throws `unknown-usage-key`, because a
432 * dropped usage count is a wrong price. A request key the card does not
433 * read is named in `ignored`.
434 */
435export function priceDetailed(
436 card: RateCard,
437 request: Vars = {},
438 usage: Vars = {},
439): PriceResult {
440 const params = cardParams(card)
441 const unknown = Object.keys(usage).filter(
442 (key) => !params.usage.includes(key),
443 )
444 if (unknown.length > 0) {
445 const reads = [
446 ...params.request.map((param) => `request.${param}`),
447 ...params.usage.map((param) => `usage.${param}`),
448 ]
449 throw new RateCardError(
450 'unknown-usage-key',
451 `${unknown.map((key) => `usage.${key}`).join(', ')}: not read by this card; it reads ${reads.join(', ') || 'no inputs'}`,
452 )
453 }
454 return {
455 ...evaluate(card, request, usage, true),
456 ignored: Object.keys(request).filter(
457 (key) => !params.request.includes(key),
458 ),
459 }
460}
461
462function evaluate(
463 card: RateCard,
464 request: Vars,
465 usage: Vars,
466 estimates: boolean,
467): Omit<PriceResult, 'ignored'> {
468 const given = collect(card.inputs, request, usage)
469 const estimated: string[] = []
470 const defaulted: string[] = []
471 const direct: RateCard['inputs'] = {}
472 const pending: Array<[string, string, RateCardEstimate]> = []
473 for (const [name, input] of Object.entries(card.inputs)) {
474 if (
475 estimates &&
476 input.kind === 'number' &&
477 input.estimate &&
478 !(input.param in given)
479 ) {
480 pending.push([name, input.param, input.estimate])
481 estimated.push(input.param)
482 } else {
483 direct[name] = input
484 }
485 }
486 const vars = bindInputs({ inputs: direct }, given, defaulted)
487 for (const [name, param, estimate] of pending) {
488 try {
489 const own = bindInputs(
490 estimate,
491 collect(estimate.inputs, request, usage),
492 defaulted,
493 )
494 const value = evalExpr(estimate.value, { ...vars, ...own }, card.tables)
495 if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
496 throw new RateCardError(
497 'bad-result',
498 `estimate evaluated to ${JSON.stringify(value)}`,
499 )
500 }
501 vars[name] = value
502 } catch (error) {
503 if (!(error instanceof RateCardError)) throw error
504 throw new RateCardError(
505 'estimate-unavailable',
506 `${name} (${param}): not supplied, and cannot be estimated for this request: ${error.message}`,
507 name,
508 )
509 }
510 }
511 const { currency, expr } = cardPrice(card)
512 const amount = evalExpr(expr, vars, card.tables)
513 // A source-published free card has a literal zero price. A paid formula that
514 // evaluates to zero still signals an invalid or missing billable quantity.
515 if (
516 typeof amount !== 'number' ||
517 !Number.isFinite(amount) ||
518 amount < 0 ||
519 (amount === 0 && expr !== 0)
520 ) {
521 throw new RateCardError(
522 'bad-result',
523 `price evaluated to ${JSON.stringify(amount)}`,
524 )
525 }
526 return {
527 amount,
528 currency,
529 ...(currency === 'USD' && { usd: amount }),
530 estimated,
531 defaulted,
532 }
533}
534
535/** Relative tolerance when reproducing a source's worked example. */
536const EXAMPLE_TOLERANCE = 0.01
537
538export type ExampleResult = {
539 example: RateCardExample
540 ok: boolean
541 usd?: number
542 error?: string
543}
544
545/** Every worked example must reproduce within 1% or the card is rejected. */
546export function verifyExamples(card: RateCard): ExampleResult[] {
547 return card.examples.map((example) => {
548 try {
549 // Examples are a flat bag; each lever is read from request or usage
550 // by bound, so the same dict in both slots is correct.
551 const usd = price(card, example.params, example.params)
552 const ok = Math.abs(usd - example.usd) <= example.usd * EXAMPLE_TOLERANCE
553 return ok
554 ? { example, ok, usd }
555 : { example, ok, usd, error: `expected ${example.usd}, got ${usd}` }
556 } catch (error) {
557 const message =
558 error instanceof RateCardError
559 ? `${error.code}: ${error.message}`
560 : String(error)
561 return { example, ok: false, error: message }
562 }
563 })
564}