Open History to see the last commit
1/**
2 * Recursively strip `null` values from a JSON-shaped value so optional fields
3 * present as `null` in OpenAI-compatible structured output round-trip cleanly
4 * through Zod schemas that expect `undefined` (or absence) instead of `null`.
5 *
6 * Behaviour:
7 * - Top-level `null` becomes `undefined`.
8 * - Object properties whose value is `null` are removed entirely (so
9 * `'key' in result` is `false`). Zod's `.optional()` treats absent keys
10 * the same as `undefined`, which is the round-trip we want; setting the
11 * key to `undefined` would still register the property in `Object.keys`
12 * and break some `.strict()`/`Object.keys`-based callers.
13 * - Array elements recurse via this same function; a `null` element therefore
14 * becomes `undefined` (top-level rule), preserving array length so
15 * positional indices stay stable. Don't rely on element-`null` round-trip.
16 *
17 * Scope: designed for `JSON.parse` output (plain objects, arrays, strings,
18 * numbers, booleans, null). Class instances, `Date`, `Map`, `Set`, etc. are
19 * NOT preserved — they're walked via `Object.entries`, which sees only own
20 * enumerable string-keyed properties. Native built-ins like `Date`/`Map`/`Set`
21 * therefore become `{}`; arbitrary class instances become a plain-object
22 * snapshot of just their own enumerable string properties. Don't pass
23 * non-JSON values.
24 *
25 * Schema-blind: strips EVERY null, including ones a `.nullable()` field
26 * legitimately allows. When the original schema is available, prefer
27 * {@link undoNullWidening}, which only strips the nulls strict-mode widening
28 * synthesized.
29 */
30export function transformNullsToUndefined<T>(obj: T): T {
31 if (obj === null) {
32 return undefined as T
33 }
34
35 if (typeof obj !== 'object') {
36 return obj
37 }
38
39 if (Array.isArray(obj)) {
40 return obj.map((item) => transformNullsToUndefined(item)) as T
41 }
42
43 const result: Record<string, unknown> = {}
44 for (const [key, value] of Object.entries(obj as Record<string, unknown>)) {
45 if (value === null) {
46 continue
47 }
48 result[key] = transformNullsToUndefined(value)
49 }
50 return result as T
51}
52
53/**
54 * Records exactly where strict-mode null-widening synthesized a `null`, so
55 * {@link undoNullWidening} can strip those nulls and leave every other one
56 * untouched. Built by the widening pass itself as it walks the schema (see
57 * `convertSchemaForStructuredOutput` in `@tanstack/ai`), so it can never drift
58 * from what was actually widened — no value-shape guessing required.
59 *
60 * - `widened`: the widening pass added `null` to THIS position's type (an
61 * optional field promoted to `required` + nullable). A `null` here is
62 * synthetic → strip it. Positions a `.nullable()`/`.nullish()` field already
63 * allowed carry no `widened` mark, so their nulls survive.
64 * - `properties` / `items`: descend into a nested object / array to reach
65 * widened positions deeper in the tree. Only objects and arrays the widener
66 * actually recursed into appear here.
67 */
68export type NullWideningMap = {
69 widened?: boolean
70 properties?: Record<string, NullWideningMap>
71 items?: NullWideningMap | Array<NullWideningMap>
72}
73
74function walk(value: unknown, map: NullWideningMap | undefined): unknown {
75 if (value === null) {
76 // Strip only nulls the widening pass synthesized (marked `widened`); keep
77 // every genuine `.nullable()`/`.nullish()` null and every null the map
78 // doesn't describe.
79 return map?.widened ? undefined : null
80 }
81 if (typeof value !== 'object' || !map) return value
82
83 if (Array.isArray(value)) {
84 const { items } = map
85 if (!items) return value
86 // Tuple maps (`items: [a, b, …]`) describe each position separately;
87 // a single `items` map applies to every element.
88 return Array.isArray(items)
89 ? value.map((item, index) => walk(item, items[index]))
90 : value.map((item) => walk(item, items))
91 }
92
93 const { properties } = map
94 if (!properties) return value
95 const result: Record<string, unknown> = {}
96 for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
97 const next = walk(child, properties[key])
98 // A synthesized null collapsed to undefined → omit the key so the field
99 // reads as absent (`key in result === false`), matching how `.optional()`
100 // treats absence.
101 if (next === undefined) continue
102 result[key] = next
103 }
104 return result
105}
106
107/**
108 * Inverse of strict-mode null-widening for structured output.
109 *
110 * To satisfy OpenAI-style strict schemas, optional fields are widened to
111 * `required` with `null` added to their type, so the provider returns `null`
112 * for an absent optional. Validating that `null` against the ORIGINAL schema
113 * fails, because `.optional()` means `T | undefined`, not `T | null`.
114 *
115 * Unlike {@link transformNullsToUndefined}, this consults a {@link
116 * NullWideningMap} recorded by the widening pass and drops ONLY the nulls that
117 * pass actually synthesized. Nulls a `.nullable()`/`.nullish()` field genuinely
118 * allows are preserved, so both `optional` and `nullable` fields round-trip
119 * correctly. With no map, the value is returned untouched.
120 */
121export function undoNullWidening<T>(value: T, map?: NullWideningMap): T {
122 if (!map) return value
123 return walk(value, map) as T
124}