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

client.ts

152 lines5.2 KB

1import { fal } from '@fal-ai/client'
2import { generateId as _generateId, getApiKeyFromEnv } from '@tanstack/ai-utils'
3import { createBillingFetch } from './billing'
4​
5export interface FalClientConfig {
6 apiKey: string
7 proxyUrl?: string
8 /**
9 * Override the underlying fetch used for fal requests. The adapter wraps it to
10 * read the `x-fal-billable-units` header (see ./billing.ts), so usage capture
11 * still works. Defaults to the global `fetch`. Useful for proxying,
12 * instrumentation, or pointing requests at a mock in tests.
13 */
14 fetch?: typeof fetch
16​
17export function getFalApiKeyFromEnv(): string {
18 return getApiKeyFromEnv('FAL_KEY')
20​
21export function configureFalClient(config?: FalClientConfig): void {
22 const apiKey = config?.apiKey ?? getFalApiKeyFromEnv()
23 fal.config({
24 credentials: apiKey,
25 // Wrap the (optionally overridden) fetch to read fal's
26 // `x-fal-billable-units` header off every response so adapters can surface
27 // the billed quantity as `result.usage`. See ./billing.ts.
28 fetch: createBillingFetch(config?.fetch),
29 ...(config?.proxyUrl ? { proxyUrl: config.proxyUrl } : {}),
30 })
32​
33export function generateId(prefix: string): string {
34 return _generateId(prefix)
36​
37/**
38 * Extract a safe file extension from a URL. Strips query strings, URL
39 * fragments, and any trailing slashes, and only returns the extension when
40 * it looks like a real one (2-5 alphanumeric chars). Returns undefined
41 * otherwise so callers can fall back to a default.
42 */
43export function extractUrlExtension(url: string): string | undefined {
44 // Parse via URL when possible so we only look at the pathname and never
45 // mistake a TLD (e.g. the `.com` in `https://x.com/`) for a file extension.
46 let pathname: string
47 try {
48 const parsed = new URL(url)
49 pathname = parsed.pathname
50 } catch {
51 // Fall back to treating the input as a raw path when URL parsing fails
52 // (e.g. the caller passed a bare path). Still strip ?query and #fragment.
53 pathname = url.split('?')[0]?.split('#')[0] ?? url
54 }
55 // Drop trailing slashes so `/path/audio.mp3/` still yields `mp3`.
56 const normalized = pathname.replace(/\/+$/, '')
57 // Require at least one `/` — otherwise we're looking at an empty pathname
58 // (bare-host URLs like `https://x.com/` land here after stripping the
59 // trailing slash).
60 if (!normalized.includes('/')) return undefined
61 const lastSegment = normalized.split('/').pop()
62 if (!lastSegment) return undefined
63 const extension = lastSegment.split('.').pop()
64 if (!extension || extension === lastSegment) return undefined
65 return /^[a-z0-9]{2,5}$/i.test(extension) ? extension : undefined
67​
68/**
69 * Derive a reasonable audio content-type. Prefers the explicit MIME (stripped
70 * of parameters), then an extension-based lookup for common audio formats,
71 * otherwise falls back to audio/mpeg — fal URLs virtually always serve mp3.
72 */
73export function deriveAudioContentType(
74 explicitContentType: string | undefined,
75 url: string,
76): string {
77 const stripped = explicitContentType?.split(';')[0]?.trim()
78 if (stripped) return stripped
79​
80 const ext = extractUrlExtension(url)?.toLowerCase()
81 switch (ext) {
82 case 'mp3':
83 return 'audio/mpeg'
84 case 'wav':
85 return 'audio/wav'
86 case 'ogg':
87 case 'oga':
88 return 'audio/ogg'
89 case 'flac':
90 return 'audio/flac'
91 case 'aac':
92 return 'audio/aac'
93 case 'm4a':
94 case 'mp4':
95 return 'audio/mp4'
96 case 'webm':
97 return 'audio/webm'
98 case undefined:
99 default:
100 return 'audio/mpeg'
101 }
103​
104/**
105 * Decode a `data:` URL into a Blob so fal-client can auto-upload it via
106 * `fal.storage.upload`. fal's inference API rejects data URLs with a 422
107 * "Unsupported data URL", so we convert them before handing them off.
108 *
109 * Supports both base64 and URL-encoded data URLs. Returns `undefined` for
110 * anything that isn't a data URL, so callers can fall through to other
111 * handling (http URLs are passed to fal as-is).
112 */
113export function dataUrlToBlob(value: string): Blob | undefined {
114 if (!value.startsWith('data:')) return undefined
115 const commaIndex = value.indexOf(',')
116 if (commaIndex === -1) return undefined
117​
118 const header = value.slice(5, commaIndex)
119 const payload = value.slice(commaIndex + 1)
120 const isBase64 = /;base64$/i.test(header)
121 const mimeType = header.split(';')[0] || 'application/octet-stream'
122​
123 if (isBase64) {
124 const binary = atob(payload)
125 const bytes = new Uint8Array(binary.length)
126 for (let i = 0; i < binary.length; i += 1) {
127 bytes[i] = binary.charCodeAt(i)
128 }
129 return new Blob([bytes], { type: mimeType })
130 }
131​
132 return new Blob([decodeURIComponent(payload)], { type: mimeType })
134​
135/**
136 * Convert an ArrayBuffer to base64 in a cross-runtime way.
137 *
138 * The naive `btoa(String.fromCharCode(...bytes))` form blows up V8's argument
139 * limit (~65k) on realistic audio payloads, so we either use `Buffer` (Node /
140 * Bun) or walk the byte array in a single loop (browser).
141 */
142export function arrayBufferToBase64(bytes: ArrayBuffer): string {
143 if (typeof Buffer !== 'undefined' && typeof Buffer.from === 'function') {
144 return Buffer.from(bytes).toString('base64')
145 }
146 const view = new Uint8Array(bytes)
147 let binary = ''
148 for (const byte of view) {
149 binary += String.fromCharCode(byte)
150 }
151 return btoa(binary)