Open History to see the last commit
1import { fileReferenceFor, isFileSource } from '@tanstack/ai'
2import { FAL_IMAGE_FIELD_OVERRIDES } from './generated/image-field-overrides'
3import type {
4 FalImageFieldName,
5 FalImageFieldOverride,
6} from './generated/image-field-overrides'
7import type {
8 ContentPartSource,
9 ImagePart,
10 MediaInputMetadata,
11} from '@tanstack/ai'
12import type { FalModel, FalModelInput } from '../model-meta'
13
14/**
15 * Convert a content source into a URL string for fal's URL-based input fields.
16 * URL sources pass through; fal storage handles (a storage URL) pass through
17 * after a provider check; base64 data becomes a `data:<mime>;base64,<value>`
18 * URI which fal endpoints accept on the wire.
19 */
20export function contentSourceToFalUrl(source: ContentPartSource): string {
21 if (isFileSource(source)) {
22 // A fal handle is a storage URL; throws when another provider issued it.
23 return fileReferenceFor(source, 'fal')
24 }
25 if (source.type === 'url') return source.value
26 return `data:${source.mimeType};base64,${source.value}`
27}
28
29/**
30 * The image-conditioning fields the mappers may set, narrowed to the ones
31 * that actually exist on the given endpoint's input type. For endpoints
32 * unknown to the installed `@fal-ai/client` this widens to all known field
33 * names.
34 */
35export type FalImageInputFields<TModel extends string> = Partial<
36 Pick<
37 FalModelInput<TModel>,
38 Extract<keyof FalModelInput<TModel>, FalImageFieldName>
39 >
40>
41
42/**
43 * Default field per routing role. Endpoint-specific deviations live in the
44 * generated `FAL_IMAGE_FIELD_OVERRIDES` map (regenerate with
45 * `pnpm generate:fal-image-fields`); these defaults must stay in sync with
46 * `DEFAULTS` in scripts/generate-fal-image-field-map.ts.
47 */
48const DEFAULT_FIELDS = {
49 single: 'image_url',
50 multi: 'image_urls',
51 mask: 'mask_url',
52 control: 'control_image_url',
53 reference: 'reference_image_urls',
54 start: 'start_image_url',
55 end: 'end_image_url',
56} satisfies Required<FalImageFieldOverride>
57
58/**
59 * Field names that accept an array of images. The generator asserts the
60 * SDK types agree with this set, so wrap-vs-scalar decisions stay correct.
61 */
62const LIST_FIELDS = new Set<string>([
63 'image_urls',
64 'input_image_urls',
65 'ref_image_urls',
66 'reference_image_urls',
67])
68
69/** Resolve the per-role field names for a model: defaults + generated overrides. */
70function fieldSpecFor(model: string): Required<FalImageFieldOverride> {
71 const overrides = (
72 FAL_IMAGE_FIELD_OVERRIDES as Record<string, FalImageFieldOverride>
73 )[model]
74 return { ...DEFAULT_FIELDS, ...overrides }
75}
76
77/**
78 * Assign URLs to a field, wrapping or unwrapping based on whether the field
79 * takes an array. When two roles resolve to the same list field (e.g.
80 * sources and references both land on `image_urls` for nano-banana edit)
81 * the values are merged in assignment order; two roles resolving to the
82 * same scalar field is ambiguous and throws. Throws when multiple images
83 * target a scalar field.
84 */
85function assignField(
86 fields: Record<string, unknown>,
87 field: string,
88 urls: Array<string>,
89 model: string,
90 what: string,
91): void {
92 if (urls.length === 0) return
93 const existing = fields[field]
94 if (LIST_FIELDS.has(field)) {
95 fields[field] = Array.isArray(existing) ? [...existing, ...urls] : urls
96 } else if (existing !== undefined) {
97 throw new Error(
98 `fal: multiple inputs map to '${field}' on model ${model}. Drop one of the conflicting inputs or pass the field explicitly via modelOptions.`,
99 )
100 } else if (urls.length === 1) {
101 fields[field] = urls[0]
102 } else {
103 throw new Error(
104 `fal: model ${model} accepts a single ${what} image via '${field}' (received ${urls.length}).`,
105 )
106 }
107}
108
109interface RoleBuckets {
110 sources: Array<string>
111 masks: Array<string>
112 controls: Array<string>
113 references: Array<string>
114 starts: Array<string>
115 ends: Array<string>
116}
117
118function bucketByRole(
119 imageInputs: ReadonlyArray<ImagePart<MediaInputMetadata>>,
120): RoleBuckets {
121 const buckets: RoleBuckets = {
122 sources: [],
123 masks: [],
124 controls: [],
125 references: [],
126 starts: [],
127 ends: [],
128 }
129 for (const part of imageInputs) {
130 const url = imagePartToUrl(part)
131 const role = part.metadata?.role
132 if (role === 'mask') buckets.masks.push(url)
133 else if (role === 'control') buckets.controls.push(url)
134 else if (role === 'reference' || role === 'character')
135 buckets.references.push(url)
136 else if (role === 'start_frame') buckets.starts.push(url)
137 else if (role === 'end_frame') buckets.ends.push(url)
138 else buckets.sources.push(url)
139 }
140 return buckets
141}
142
143/**
144 * Map the prompt's image parts onto fal.ai image-endpoint fields.
145 *
146 * fal endpoints use different field names for image-conditioned generation
147 * (~80% use `image_url` for single; the rest use `image_urls`,
148 * `reference_image_urls`, `mask_url`, `control_image_url`, etc.). Field
149 * names are resolved per endpoint from the generated
150 * `FAL_IMAGE_FIELD_OVERRIDES` map (derived from the fal SDK's endpoint
151 * types), falling back to the defaults above for endpoints the installed
152 * SDK doesn't know:
153 *
154 * - parts with `metadata.role === 'mask'` → spec.mask (single)
155 * - parts with `metadata.role === 'control'` → spec.control (single)
156 * - `role === 'reference' | 'character'` → spec.reference
157 * - `role === 'start_frame' | 'end_frame'` → treated as sources (frame
158 * roles only apply to video generation)
159 * - remaining parts → spec.single / spec.multi
160 *
161 * Users can always override the resulting field shape via `modelOptions`
162 * (spread before these fields), or pass everything through `modelOptions`
163 * directly when the mapping doesn't match an obscure endpoint.
164 */
165export function mapImageInputsToFalFields<TModel extends FalModel>(
166 model: TModel,
167 imageInputs?: ReadonlyArray<ImagePart<MediaInputMetadata>>,
168): FalImageInputFields<TModel> {
169 if (!imageInputs || imageInputs.length === 0) return {}
170
171 const spec = fieldSpecFor(model)
172 const { sources, masks, controls, references, starts, ends } =
173 bucketByRole(imageInputs)
174 // Frame roles aren't meaningful for image generation; treat as the
175 // primary source. The video mapper handles start/end framing.
176 const allSources = [...sources, ...starts, ...ends]
177
178 if (masks.length > 1) {
179 throw new Error(
180 `fal: only one input with metadata.role === 'mask' is supported per request (received ${masks.length}).`,
181 )
182 }
183 if (controls.length > 1) {
184 throw new Error(
185 `fal: only one input with metadata.role === 'control' is supported per request (received ${controls.length}).`,
186 )
187 }
188
189 const fields: Record<string, unknown> = {}
190 const sourceField = allSources.length > 1 ? spec.multi : spec.single
191 assignField(fields, sourceField, allSources, model, 'source')
192 assignField(fields, spec.reference, references, model, 'reference')
193 assignField(fields, spec.mask, masks, model, 'mask')
194 assignField(fields, spec.control, controls, model, 'control')
195
196 return fields as FalImageInputFields<TModel>
197}
198
199/**
200 * Map the prompt's image parts onto fal.ai video-endpoint fields.
201 *
202 * Video endpoints often expose a start frame as `image_url` (76% of i2v
203 * models) plus an optional `end_image_url`. Multi-reference video models
204 * (Kling O3, Seedance reference-to-video) use `reference_image_urls` or
205 * `image_urls`. Field names resolve through the same generated override
206 * map as the image mapper — e.g. `role: 'start_frame'` lands on `image_url`
207 * for Kling/Veo image-to-video and `first_frame_url` for Pixverse. Mapping:
208 *
209 * - `metadata.role === 'start_frame'` → spec.start
210 * - `metadata.role === 'end_frame'` → spec.end
211 * - `metadata.role === 'reference' | 'character'` → spec.reference
212 * - `metadata.role === 'mask' | 'control'` → throws (no video routing)
213 * - remaining parts (no role) → spec.single / spec.multi
214 */
215export function mapImageInputsToFalVideoFields<TModel extends FalModel>(
216 model: TModel,
217 imageInputs?: ReadonlyArray<ImagePart<MediaInputMetadata>>,
218): FalImageInputFields<TModel> {
219 if (!imageInputs || imageInputs.length === 0) return {}
220
221 const spec = fieldSpecFor(model)
222 const { sources, masks, controls, references, starts, ends } =
223 bucketByRole(imageInputs)
224 // Mask / control roles have no video-specific routing; silently repurposing
225 // them as source frames would hide the problem, so reject them instead.
226 if (masks.length > 0 || controls.length > 0) {
227 const role = masks.length > 0 ? 'mask' : 'control'
228 throw new Error(
229 `fal: metadata.role === '${role}' is not supported for video generation on model ${model}. ` +
230 `Remove the role or pass the field explicitly via modelOptions.`,
231 )
232 }
233
234 if (starts.length > 1) {
235 throw new Error(
236 `fal: only one input with metadata.role === 'start_frame' is supported (received ${starts.length}).`,
237 )
238 }
239 if (ends.length > 1) {
240 throw new Error(
241 `fal: only one input with metadata.role === 'end_frame' is supported (received ${ends.length}).`,
242 )
243 }
244
245 const fields: Record<string, unknown> = {}
246 const sourceField = sources.length > 1 ? spec.multi : spec.single
247 assignField(fields, sourceField, sources, model, 'source')
248 assignField(fields, spec.reference, references, model, 'reference')
249 // Frame roles assign last: when an endpoint routes the start frame to its
250 // generic source field (e.g. Kling image-to-video) and an unroled source
251 // was also provided, assignField rejects the ambiguous combination.
252 assignField(fields, spec.start, starts, model, 'start frame')
253 assignField(fields, spec.end, ends, model, 'end frame')
254
255 return fields as FalImageInputFields<TModel>
256}
257
258/**
259 * Convert a TanStack ImagePart into a string suitable for fal's URL-based
260 * input fields.
261 */
262function imagePartToUrl(part: ImagePart<MediaInputMetadata>): string {
263 return contentSourceToFalUrl(part.source)
264}