@umituz/react-native-ai-fal-provider 2.0.14 → 2.0.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/package.json +1 -1
  2. package/src/domain/entities/error.types.ts +2 -0
  3. package/src/domain/types/provider.types.ts +1 -0
  4. package/src/exports/infrastructure.ts +0 -3
  5. package/src/exports/presentation.ts +0 -9
  6. package/src/index.ts +0 -3
  7. package/src/infrastructure/services/fal-feature-models.ts +3 -1
  8. package/src/infrastructure/services/fal-provider-subscription.ts +35 -13
  9. package/src/infrastructure/services/fal-provider.ts +6 -0
  10. package/src/infrastructure/services/fal-queue-operations.ts +30 -1
  11. package/src/infrastructure/services/fal-status-mapper.ts +2 -0
  12. package/src/infrastructure/services/request-store.ts +30 -2
  13. package/src/infrastructure/utils/cost-tracker.ts +34 -8
  14. package/src/infrastructure/utils/error-mapper.ts +17 -3
  15. package/src/infrastructure/utils/image-feature-builders.util.ts +10 -5
  16. package/src/infrastructure/utils/index.ts +7 -6
  17. package/src/infrastructure/utils/input-validator.util.ts +92 -0
  18. package/src/infrastructure/utils/type-guards.util.ts +7 -3
  19. package/src/infrastructure/utils/video-feature-builders.util.ts +6 -3
  20. package/src/infrastructure/validators/nsfw-validator.ts +62 -4
  21. package/src/presentation/hooks/index.ts +3 -21
  22. package/src/presentation/hooks/use-fal-generation.ts +5 -4
  23. package/src/domain/constants/default-models.constants.README.md +0 -378
  24. package/src/domain/constants/models/image-to-video.README.md +0 -266
  25. package/src/domain/constants/models/index.README.md +0 -269
  26. package/src/domain/constants/models/text-to-image.README.md +0 -237
  27. package/src/domain/constants/models/text-to-text.README.md +0 -249
  28. package/src/domain/constants/models/text-to-video.README.md +0 -259
  29. package/src/domain/constants/models/text-to-voice.README.md +0 -264
  30. package/src/domain/entities/error.types.README.md +0 -292
  31. package/src/domain/entities/fal.types.README.md +0 -460
  32. package/src/domain/types/index.README.md +0 -229
  33. package/src/domain/types/model-selection.types.README.md +0 -311
  34. package/src/exports/registry.ts +0 -39
  35. package/src/index.README.md +0 -420
  36. package/src/infrastructure/builders/image-feature-builder.README.md +0 -435
  37. package/src/infrastructure/builders/index.ts +0 -7
  38. package/src/infrastructure/services/fal-models-service.README.md +0 -293
  39. package/src/infrastructure/services/fal-provider-subscription.README.md +0 -257
  40. package/src/infrastructure/services/fal-provider.README.md +0 -474
  41. package/src/infrastructure/services/fal-status-mapper.README.md +0 -246
  42. package/src/infrastructure/services/nsfw-content-error.README.md +0 -215
  43. package/src/infrastructure/utils/base-builders.util.README.md +0 -313
  44. package/src/infrastructure/utils/cost-tracker-queries.ts +0 -67
  45. package/src/infrastructure/utils/error-categorizer.README.md +0 -395
  46. package/src/infrastructure/utils/error-mapper.README.md +0 -367
  47. package/src/infrastructure/utils/helpers.util.README.md +0 -395
  48. package/src/infrastructure/utils/image-feature-builders.util.README.md +0 -411
  49. package/src/infrastructure/utils/index.README.md +0 -338
  50. package/src/infrastructure/utils/job-metadata/index.README.md +0 -267
  51. package/src/infrastructure/utils/job-metadata/job-metadata-format.util.README.md +0 -209
  52. package/src/infrastructure/utils/job-metadata/job-metadata-lifecycle.util.README.md +0 -311
  53. package/src/infrastructure/utils/job-metadata/job-metadata-queries.util.README.md +0 -332
  54. package/src/infrastructure/utils/job-metadata/job-metadata.types.README.md +0 -446
  55. package/src/infrastructure/utils/job-metadata.README.md +0 -268
  56. package/src/infrastructure/utils/timing-helpers.util.ts +0 -56
  57. package/src/infrastructure/utils/type-guards.util.README.md +0 -371
  58. package/src/infrastructure/validators/index.README.md +0 -205
  59. package/src/infrastructure/validators/nsfw-validator.README.md +0 -309
  60. package/src/presentation/hooks/index.README.md +0 -224
  61. package/src/presentation/hooks/use-fal-generation.README.md +0 -398
  62. package/src/presentation/hooks/use-model-capabilities.ts +0 -99
  63. package/src/presentation/hooks/use-models.README.md +0 -318
  64. package/src/registry/global-capabilities.ts +0 -75
  65. package/src/registry/index.ts +0 -50
  66. package/src/registry/model-registry.service.ts +0 -93
  67. package/src/registry/model-registry.types.ts +0 -106
  68. package/src/registry/models/index.ts +0 -6
  69. package/src/registry/models/sora-2.config.ts +0 -95
@@ -1,398 +0,0 @@
1
- # useFalGeneration Hook
2
-
3
- React hook for managing FAL AI generation operations with state management, error handling, and retry logic.
4
-
5
- **Location:** `src/presentation/hooks/use-fal-generation.ts`
6
-
7
- ## Overview
8
-
9
- The `useFalGeneration` hook provides complete state management for FAL AI generation operations including images, videos, and other content. It handles loading states, errors, cancellation, retry logic, and automatic cleanup.
10
-
11
- ## Purpose
12
-
13
- Simplifies AI generation in React components by:
14
- - Managing all generation states (loading, error, success)
15
- - Providing automatic retry functionality
16
- - Handling request cancellation
17
- - Tracking request lifecycle
18
- - Managing cleanup on unmount
19
-
20
- ## Import
21
-
22
- ```typescript
23
- import { useFalGeneration } from '@umituz/react-native-ai-fal-provider';
24
- ```
25
-
26
- ## Parameters
27
-
28
- **Options:** `UseFalGenerationOptions`
29
-
30
- | Parameter | Type | Required | Description |
31
- |-----------|------|----------|-------------|
32
- | `timeoutMs` | `number` | ❌ No | Maximum time to wait for generation (ms) |
33
- | `onProgress` | `(status: FalQueueStatus) => void` | ❌ No | Callback for status updates during generation |
34
- | `onError` | `(error: FalErrorInfo) => void` | ❌ No | Callback when error occurs |
35
-
36
- **Implementation:** See `src/presentation/hooks/use-fal-generation.ts` for complete type definitions
37
-
38
- ## Return Values
39
-
40
- **Result:** `UseFalGenerationResult<T>`
41
-
42
- | Property | Type | Description |
43
- |----------|------|-------------|
44
- | `data` | `T \| null` | Generated content result |
45
- | `error` | `FalErrorInfo \| null` | Error information if generation failed |
46
- | `isLoading` | `boolean` | True if generation is in progress |
47
- | `isRetryable` | `boolean` | True if error can be retried |
48
- | `requestId` | `string \| null` | Current request ID |
49
- | `isCancelling` | `boolean` | True if cancellation is in progress |
50
- | `generate` | `function` | Start generation function |
51
- | `retry` | `function` | Retry failed generation function |
52
- | `cancel` | `function` | Cancel current generation function |
53
- | `reset` | `function` | Reset all states function |
54
-
55
- **Related:**
56
- - Error types: `src/domain/entities/error.types.ts`
57
- - Queue status types: `src/domain/entities/fal.types.ts`
58
-
59
- ## Methods
60
-
61
- ### generate
62
-
63
- Start AI generation operation.
64
-
65
- **Parameters:**
66
- - `modelEndpoint`: FAL model ID (e.g., 'fal-ai/flux/schnell')
67
- - `input`: Job input object matching model requirements
68
-
69
- **Returns:** `Promise<T | null>` - Generation result or null if failed
70
-
71
- **Usage:**
72
- Call this function to start a generation operation. The hook manages loading states automatically. Use builder functions from `src/infrastructure/utils/` to construct input objects.
73
-
74
- **Related:**
75
- - Input builders: `src/infrastructure/utils/image-feature-builders.util.ts`
76
- - Video builders: `src/infrastructure/utils/video-feature-builders.util.ts`
77
-
78
- ### retry
79
-
80
- Retry the last failed generation operation.
81
-
82
- **Returns:** `Promise<T | null>` - Generation result or null if failed
83
-
84
- **Usage:**
85
- Call this function to retry a failed generation. Uses the same model and input from the last failed attempt. Only works if `isRetryable` is true.
86
-
87
- **Related:**
88
- - Error categorization: `src/infrastructure/utils/error-categorizer.ts`
89
-
90
- ### cancel
91
-
92
- Cancel the current generation operation.
93
-
94
- **Usage:**
95
- Call this function to abort an in-progress generation. Sets `isCancelling` to true and aborts the request. Use for user cancellation or cleanup.
96
-
97
- **Related:**
98
- - Provider cancellation: `src/infrastructure/services/fal-provider.ts`
99
-
100
- ### reset
101
-
102
- Reset all states to initial values.
103
-
104
- **Usage:**
105
- Call this function to clear data, error, and loading states. Use before starting a new generation to ensure clean state.
106
-
107
- ## Usage Guidelines
108
-
109
- ### For Basic Generation
110
-
111
- **Setup:**
112
- 1. Import `useFalGeneration` from package
113
- 2. Destructure required states and methods
114
- 3. Call `generate()` with model ID and input
115
- 4. Handle `data`, `error`, and `isLoading` states
116
-
117
- **State Display:**
118
- - Show loading indicator when `isLoading` is true
119
- - Display error message when `error` is not null
120
- - Render result when `data` is not null
121
- - Check `isRetryable` before showing retry button
122
-
123
- **Related:**
124
- - Model constants: `src/domain/constants/default-models.constants.ts`
125
-
126
- ### For Progress Tracking
127
-
128
- **Progress Callbacks:**
129
- 1. Provide `onProgress` callback in options
130
- 2. Monitor `status.status` for job state
131
- 3. Check `status.queuePosition` for queue information
132
- 4. Display progress to user
133
-
134
- **Status Values:**
135
- - `IN_QUEUE`: Job is queued (10% progress)
136
- - `IN_PROGRESS`: Job is processing (50% progress)
137
- - `COMPLETED`: Job finished (100% progress)
138
-
139
- **Related:**
140
- - Queue status types: `src/domain/entities/fal.types.ts`
141
- - Job format utilities: `src/infrastructure/utils/job-metadata/job-metadata-format.util.ts`
142
-
143
- ### For Error Handling
144
-
145
- **Error Callback:**
146
- 1. Provide `onError` callback in options
147
- 2. Check `error.type` for error category
148
- 3. Use `error.messageKey` for user-facing messages
149
- 4. Check `isRetryable` before allowing retry
150
-
151
- **Error Types:**
152
- - `quota_exceeded`: Credit limit reached
153
- - `rate_limit`: Too many requests
154
- - `authentication`: API key invalid
155
- - `content_policy`: Content violation
156
- - `network`: Network error
157
- - `timeout`: Request timeout
158
- - `unknown`: Unknown error
159
-
160
- **Related:**
161
- - Error types: `src/domain/entities/error.types.ts`
162
- - Error mapper: `src/infrastructure/utils/error-mapper.ts`
163
-
164
- ### For Cancellation
165
-
166
- **Cancellation Flow:**
167
- 1. Check `isLoading` before showing cancel button
168
- 2. Call `cancel()` when user cancels
169
- 3. Monitor `isCancelling` for cancellation state
170
- 4. Show appropriate feedback
171
-
172
- **Best Practices:**
173
- - Always check `isLoading` before enabling cancel
174
- - Disable generation button while cancelling
175
- - Show "Cancelling..." message during cancellation
176
- - Handle cleanup properly
177
-
178
- ### For Retry Logic
179
-
180
- **Retry Flow:**
181
- 1. Check `isRetryable` before showing retry option
182
- 2. Call `retry()` to attempt same generation
183
- 3. Handle retry result in `onError` or `onSuccess`
184
- 4. Limit retry attempts if needed
185
-
186
- **Retryable Errors:**
187
- - Network errors
188
- - Timeout errors
189
- - Rate limit errors
190
- - Temporary server errors
191
-
192
- **Non-Retryable Errors:**
193
- - Authentication errors
194
- - Content policy violations
195
- - Quota exceeded
196
- - Invalid input errors
197
-
198
- **Related:**
199
- - Error categorizer: `src/infrastructure/utils/error-categorizer.ts`
200
-
201
- ### For Cleanup
202
-
203
- **Automatic Cleanup:**
204
- - Hook automatically cancels on unmount
205
- - AbortController is cleaned up
206
- - No manual cleanup required
207
-
208
- **Manual Cleanup:**
209
- 1. Call `cancel()` if needed
210
- 2. Call `reset()` to clear state
211
- 3. Handle cleanup in useEffect if needed
212
-
213
- ## Best Practices
214
-
215
- ### 1. Always Handle Loading State
216
-
217
- Check `isLoading` before allowing actions:
218
- - Disable generate button while loading
219
- - Show loading indicator to user
220
- - Prevent duplicate submissions
221
- - Handle cancellation properly
222
-
223
- ### 2. Provide User Feedback
224
-
225
- Give clear feedback for all states:
226
- - Show loading message with progress
227
- - Display user-friendly error messages
228
- - Show success confirmation
229
- - Indicate retry availability
230
-
231
- ### 3. Use Appropriate Timeouts
232
-
233
- Set timeout based on model type:
234
- - Text-to-image: 2 minutes (120000ms)
235
- - Text-to-video: 5 minutes (300000ms)
236
- - Image features: 1 minute (60000ms)
237
- - Adjust based on your use case
238
-
239
- ### 4. Reset Between Generations
240
-
241
- Clear state before new operations:
242
- - Call `reset()` before new generation
243
- - Ensures clean state
244
- - Prevents stale data display
245
- - Avoids confusion
246
-
247
- ### 5. Handle Errors Gracefully
248
-
249
- Implement comprehensive error handling:
250
- - Check `isRetryable` before retry
251
- - Show user-friendly messages
252
- - Log errors for debugging
253
- - Provide retry option when appropriate
254
-
255
- ## For AI Agents
256
-
257
- ### When Using useFalGeneration
258
-
259
- **DO:**
260
- - Import from package root
261
- - Destructure all needed values
262
- - Handle all states (loading, error, data)
263
- - Use builder functions for inputs
264
- - Check `isRetryable` before retry
265
- - Cancel on unmount (automatic)
266
- - Reset state between generations
267
- - Provide user feedback
268
-
269
- **DON'T:**
270
- - Skip error handling
271
- - Ignore loading states
272
- - Retry without checking `isRetryable`
273
- - Build input objects manually
274
- - Forget to handle cancellation
275
- - Show stale data
276
- - Use undefined types
277
-
278
- ### When Building Components
279
-
280
- **DO:**
281
- - Check all state values before rendering
282
- - Disable buttons appropriately
283
- - Show loading indicators
284
- - Display error messages clearly
285
- - Handle null data gracefully
286
- - Use proper TypeScript types
287
- - Test all error scenarios
288
-
289
- **DON'T:**
290
- - Assume data is always present
291
- - Forget loading states
292
- - Ignore error states
293
- - Allow actions while loading
294
- - Skip null checks
295
- - Use any types
296
- - Ignore edge cases
297
-
298
- ### When Adding Features
299
-
300
- **For New Callback Options:**
301
- 1. Add option to `UseFalGenerationOptions` type
302
- 2. Implement callback in hook logic
303
- 3. Document in this README
304
- 4. Test with various scenarios
305
- 5. Update related hooks if needed
306
-
307
- **For New State Values:**
308
- 1. Add to `UseFalGenerationResult` type
309
- 2. Implement state management in hook
310
- 3. Update TypeScript types
311
- 4. Document usage guidelines
312
- 5. Provide migration guide if breaking
313
-
314
- **For New Methods:**
315
- 1. Add function to return object
316
- 2. Implement with proper error handling
317
- 3. Update TypeScript types
318
- 4. Document in this README
319
- 5. Test thoroughly
320
-
321
- ## Implementation Strategy
322
-
323
- ### State Management
324
-
325
- **Managed States:**
326
- - `data`: Result of generation (null initially)
327
- - `error`: Error information (null initially)
328
- - `isLoading`: Loading state (boolean)
329
- - `isRetryable`: Whether error can be retried (boolean)
330
- - `requestId`: Current request ID (null initially)
331
- - `isCancelling`: Cancellation state (boolean)
332
-
333
- **State Updates:**
334
- - States update automatically during generation
335
- - Reset manually via `reset()` method
336
- - States persist until reset or new generation
337
-
338
- ### Request Tracking
339
-
340
- **Last Request Storage:**
341
- - Stores last model endpoint and input
342
- - Used for retry functionality
343
- - Stored in ref to prevent re-renders
344
- - Updates on each `generate()` call
345
-
346
- **Cleanup:**
347
- - Automatic cleanup on unmount
348
- - AbortController cancellation
349
- - State reset optional
350
- - No memory leaks
351
-
352
- ### Error Handling
353
-
354
- **Error Categorization:**
355
- - Uses error categorizer from `src/infrastructure/utils/error-categorizer.ts`
356
- - Determines if error is retryable
357
- - Provides user-friendly error messages
358
- - Categorizes by error type
359
-
360
- **Error Callback:**
361
- - Called when error occurs
362
- - Receives `FalErrorInfo` object
363
- - Use for user notifications
364
- - Can trigger automatic retry
365
-
366
- ## Implementation Notes
367
-
368
- **Location:** `src/presentation/hooks/use-fal-generation.ts`
369
-
370
- **Dependencies:**
371
- - Uses `falProvider` from `src/infrastructure/services/fal-provider.ts`
372
- - Uses error utilities from `src/infrastructure/utils/error-mapper.ts`
373
- - Uses error categorizer from `src/infrastructure/utils/error-categorizer.ts`
374
- - Integrates with React hooks (useState, useEffect, useRef, useCallback)
375
-
376
- **TypeScript Types:**
377
- - Generic type parameter for result typing
378
- - Strongly typed options and result
379
- - Type-safe error handling
380
- - Proper null handling
381
-
382
- **Import:**
383
- ```typescript
384
- import { useFalGeneration } from '@umituz/react-native-ai-fal-provider';
385
- ```
386
-
387
- **Related:**
388
- - useModels hook: `src/presentation/hooks/use-models.README.md`
389
- - Hooks index: `src/presentation/hooks/index.README.md`
390
- - Provider: `src/infrastructure/services/fal-provider.README.md`
391
-
392
- ## Related Documentation
393
-
394
- - [useModels Hook](./use-models.README.md)
395
- - [React Hooks Index](./index.README.md)
396
- - [FalProvider](../services/fal-provider.README.md)
397
- - [Error Types](../../domain/entities/error.types.README.md)
398
- - [Error Mapper](../utils/error-mapper.README.md)
@@ -1,99 +0,0 @@
1
- /**
2
- * useModelCapabilities Hook
3
- * React hook for accessing model capabilities from the registry
4
- */
5
-
6
- import { useMemo, useCallback } from "react";
7
- import {
8
- getModelConfig,
9
- getModelCapabilities,
10
- getModelCreditCost,
11
- VIDEO_ASPECT_RATIOS,
12
- } from "../../registry";
13
- import type { ResolvedCapabilities, ModelConfig } from "../../registry";
14
-
15
- // =============================================================================
16
- // MAIN HOOK
17
- // =============================================================================
18
-
19
- export interface UseModelCapabilitiesOptions {
20
- modelId: string;
21
- }
22
-
23
- export interface UseModelCapabilitiesReturn {
24
- config: ModelConfig | undefined;
25
- capabilities: ResolvedCapabilities | undefined;
26
- getCreditCost: (duration: number) => number;
27
- defaults: ResolvedCapabilities["defaults"] | undefined;
28
- isAvailable: boolean;
29
- }
30
-
31
- export function useModelCapabilities(
32
- options: UseModelCapabilitiesOptions
33
- ): UseModelCapabilitiesReturn {
34
- const { modelId } = options;
35
-
36
- const config = useMemo(() => getModelConfig(modelId), [modelId]);
37
- const capabilities = useMemo(() => getModelCapabilities(modelId), [modelId]);
38
-
39
- const getCreditCost = useCallback(
40
- (duration: number) => getModelCreditCost(modelId, duration),
41
- [modelId]
42
- );
43
-
44
- return {
45
- config,
46
- capabilities,
47
- getCreditCost,
48
- defaults: capabilities?.defaults,
49
- isAvailable: !!config?.enabled,
50
- };
51
- }
52
-
53
- // =============================================================================
54
- // CONVENIENCE HOOKS
55
- // =============================================================================
56
-
57
- export interface UseVideoDurationsReturn {
58
- durations: ResolvedCapabilities["durations"];
59
- defaultDuration: number;
60
- }
61
-
62
- export function useVideoDurations(modelId: string): UseVideoDurationsReturn {
63
- const { capabilities } = useModelCapabilities({ modelId });
64
-
65
- return {
66
- durations: capabilities?.durations ?? [],
67
- defaultDuration: capabilities?.defaults.duration ?? 4,
68
- };
69
- }
70
-
71
- export interface UseVideoResolutionsReturn {
72
- resolutions: ResolvedCapabilities["resolutions"];
73
- defaultResolution: string;
74
- }
75
-
76
- export function useVideoResolutions(
77
- modelId: string
78
- ): UseVideoResolutionsReturn {
79
- const { capabilities } = useModelCapabilities({ modelId });
80
-
81
- return {
82
- resolutions: capabilities?.resolutions ?? [],
83
- defaultResolution: capabilities?.defaults.resolution ?? "720p",
84
- };
85
- }
86
-
87
- export interface UseAspectRatiosReturn {
88
- aspectRatios: ResolvedCapabilities["aspectRatios"];
89
- defaultAspectRatio: string;
90
- }
91
-
92
- export function useAspectRatios(modelId: string): UseAspectRatiosReturn {
93
- const { capabilities } = useModelCapabilities({ modelId });
94
-
95
- return {
96
- aspectRatios: capabilities?.aspectRatios ?? VIDEO_ASPECT_RATIOS,
97
- defaultAspectRatio: capabilities?.defaults.aspectRatio ?? "16:9",
98
- };
99
- }