@umituz/react-native-ai-generation-content 1.17.308 → 1.17.310

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.
@@ -1,154 +0,0 @@
1
- /**
2
- * useSingleImageFeature Hook
3
- * Provider-agnostic hook for single image processing features
4
- * App provides processRequest callback with their AI provider
5
- */
6
-
7
- import { useCallback, useState } from "react";
8
- import type {
9
- BaseFeatureState,
10
- BaseFeatureActions,
11
- FeatureProcessResult,
12
- OnProgressCallback,
13
- OnSelectImageCallback,
14
- OnSaveCallback,
15
- } from "./types";
16
-
17
- /**
18
- * Request passed to processRequest callback
19
- */
20
- export interface SingleImageProcessRequest {
21
- readonly imageUri: string;
22
- readonly onProgress: OnProgressCallback;
23
- }
24
-
25
- /**
26
- * Configuration for single image feature
27
- */
28
- export interface UseSingleImageFeatureConfig {
29
- readonly onSelectImage: OnSelectImageCallback;
30
- readonly processRequest: (
31
- request: SingleImageProcessRequest
32
- ) => Promise<FeatureProcessResult>;
33
- readonly onSave?: OnSaveCallback;
34
- readonly onError?: (error: string) => void;
35
- readonly onSuccess?: (url: string) => void;
36
- }
37
-
38
- /**
39
- * State for single image feature
40
- */
41
- export interface SingleImageFeatureState extends BaseFeatureState {
42
- readonly imageUri: string | null;
43
- }
44
-
45
- /**
46
- * Return type for single image feature hook
47
- */
48
- export interface UseSingleImageFeatureReturn
49
- extends SingleImageFeatureState,
50
- BaseFeatureActions {
51
- readonly selectImage: () => Promise<void>;
52
- readonly process: () => Promise<void>;
53
- readonly save: () => Promise<void>;
54
- }
55
-
56
- export function useSingleImageFeature(
57
- config: UseSingleImageFeatureConfig
58
- ): UseSingleImageFeatureReturn {
59
- const [imageUri, setImageUri] = useState<string | null>(null);
60
- const [processedUrl, setProcessedUrl] = useState<string | null>(null);
61
- const [isProcessing, setIsProcessing] = useState(false);
62
- const [progress, setProgress] = useState(0);
63
- const [error, setError] = useState<string | null>(null);
64
-
65
- const selectImage = useCallback(async (): Promise<void> => {
66
- try {
67
- const uri = await config.onSelectImage();
68
- if (uri) {
69
- setImageUri(uri);
70
- setError(null);
71
- setProcessedUrl(null);
72
- }
73
- } catch (err) {
74
- const message = err instanceof Error ? err.message : "error.selectImage";
75
- setError(message);
76
- config.onError?.(message);
77
- }
78
- }, [config]);
79
-
80
- const process = useCallback(async (): Promise<void> => {
81
- if (!imageUri) {
82
- const message = "error.noImage";
83
- setError(message);
84
- config.onError?.(message);
85
- return;
86
- }
87
-
88
- setIsProcessing(true);
89
- setProgress(0);
90
- setError(null);
91
-
92
- try {
93
- const result = await config.processRequest({
94
- imageUri,
95
- onProgress: setProgress,
96
- });
97
-
98
- if (result.success && result.outputUrl) {
99
- setProcessedUrl(result.outputUrl);
100
- config.onSuccess?.(result.outputUrl);
101
- } else {
102
- const message = result.error || "error.processing";
103
- setError(message);
104
- config.onError?.(message);
105
- }
106
- } catch (err) {
107
- const message = err instanceof Error ? err.message : "error.processing";
108
- setError(message);
109
- config.onError?.(message);
110
- } finally {
111
- setIsProcessing(false);
112
- setProgress(0);
113
- }
114
- }, [imageUri, config]);
115
-
116
- const save = useCallback(async (): Promise<void> => {
117
- if (!processedUrl || !config.onSave) {
118
- return;
119
- }
120
-
121
- try {
122
- await config.onSave(processedUrl);
123
- } catch (err) {
124
- const message = err instanceof Error ? err.message : "error.save";
125
- setError(message);
126
- config.onError?.(message);
127
- }
128
- }, [processedUrl, config]);
129
-
130
- const reset = useCallback((): void => {
131
- setImageUri(null);
132
- setProcessedUrl(null);
133
- setIsProcessing(false);
134
- setProgress(0);
135
- setError(null);
136
- }, []);
137
-
138
- const clearError = useCallback((): void => {
139
- setError(null);
140
- }, []);
141
-
142
- return {
143
- imageUri,
144
- processedUrl,
145
- isProcessing,
146
- progress,
147
- error,
148
- selectImage,
149
- process,
150
- save,
151
- reset,
152
- clearError,
153
- };
154
- }
@@ -1,133 +0,0 @@
1
- /**
2
- * Feature State Factory
3
- * Factory functions for creating feature state handlers
4
- * Reduces code duplication across feature hooks
5
- */
6
-
7
- import { useCallback } from "react";
8
-
9
- export interface FeatureStateActions {
10
- reset: () => void;
11
- clearError: () => void;
12
- }
13
-
14
- export interface CreateStateHandlersParams<TState> {
15
- setState: React.Dispatch<React.SetStateAction<TState>>;
16
- initialState: TState;
17
- }
18
-
19
- /**
20
- * Creates reset and clearError handlers for feature state
21
- */
22
- export function createFeatureStateHandlers<TState extends { error: string | null }>({
23
- setState,
24
- initialState,
25
- }: CreateStateHandlersParams<TState>): FeatureStateActions {
26
- const reset = useCallback(() => {
27
- setState(initialState);
28
- }, [setState, initialState]);
29
-
30
- const clearError = useCallback(() => {
31
- setState((prev) => ({
32
- ...prev,
33
- error: null,
34
- }));
35
- }, [setState]);
36
-
37
- return { reset, clearError };
38
- }
39
-
40
- /**
41
- * Creates error handler with logging
42
- */
43
- export interface ErrorHandlerParams {
44
- setError: (error: string | null) => void;
45
- onError?: (error: string) => void;
46
- errorKey: string;
47
- }
48
-
49
- export function createErrorHandler({
50
- setError,
51
- onError,
52
- errorKey,
53
- }: ErrorHandlerParams) {
54
- return useCallback((error: unknown) => {
55
- const message = error instanceof Error ? error.message : errorKey;
56
- setError(message);
57
- onError?.(message);
58
- }, [setError, onError, errorKey]);
59
- }
60
-
61
- /**
62
- * Creates process handler with common logic
63
- */
64
- export interface ProcessHandlerParams<TResult> {
65
- canProcess: () => boolean;
66
- setError: (error: string | null) => void;
67
- setProcessing: (processing: boolean) => void;
68
- onError?: (error: string) => void;
69
- processFn: () => Promise<TResult>;
70
- onSuccess?: (result: TResult) => void;
71
- onProgress?: (progress: number) => void;
72
- }
73
-
74
- export async function executeProcess<TResult>({
75
- canProcess,
76
- setError,
77
- setProcessing,
78
- onError,
79
- processFn,
80
- onSuccess,
81
- onProgress,
82
- }: ProcessHandlerParams<TResult>): Promise<TResult | null> {
83
- if (!canProcess()) {
84
- return null;
85
- }
86
-
87
- setProcessing(true);
88
- setError(null);
89
- onProgress?.(0);
90
-
91
- try {
92
- const result = await processFn();
93
- onProgress?.(100);
94
- onSuccess?.(result);
95
- return result;
96
- } catch (err) {
97
- const message = err instanceof Error ? err.message : "error.processing";
98
- setError(message);
99
- onError?.(message);
100
- return null;
101
- } finally {
102
- setProcessing(false);
103
- }
104
- }
105
-
106
- /**
107
- * Creates save handler
108
- */
109
- export interface SaveHandlerParams {
110
- processedUrl: string | null;
111
- onSave?: (url: string) => Promise<void>;
112
- setError: (error: string | null) => void;
113
- onError?: (error: string) => void;
114
- }
115
-
116
- export async function executeSave({
117
- processedUrl,
118
- onSave,
119
- setError,
120
- onError,
121
- }: SaveHandlerParams): Promise<void> {
122
- if (!processedUrl || !onSave) {
123
- return;
124
- }
125
-
126
- try {
127
- await onSave(processedUrl);
128
- } catch (err) {
129
- const message = err instanceof Error ? err.message : "error.save";
130
- setError(message);
131
- onError?.(message);
132
- }
133
- }
@@ -1,42 +0,0 @@
1
- /**
2
- * Generation Callbacks Types
3
- * Type definitions for unified generation flow
4
- */
5
-
6
- export type CreditType = "image" | "text" | "video" | "audio";
7
-
8
- export interface GenerationExecutionResult<T = unknown> {
9
- success: boolean;
10
- data?: T;
11
- error?: string;
12
- }
13
-
14
- export interface GenerationCallbacksConfig<TRequest, TResult> {
15
- userId: string | null;
16
- isAuthenticated: boolean;
17
- creditBalance: number;
18
- creditCost: number;
19
- creditType: CreditType;
20
- executor: (request: TRequest) => Promise<GenerationExecutionResult<TResult>>;
21
- deductCredit: (type: CreditType) => Promise<void>;
22
- openPaywall: () => void;
23
- showAuthModal?: () => void;
24
- saveCreation?: (result: TResult) => Promise<void>;
25
- onNavigateAfterSuccess?: () => void;
26
- invalidateQueryKeys?: string[];
27
- }
28
-
29
- export interface GenerationCallbacks<TRequest, TResult> {
30
- canAfford: (cost?: number) => boolean;
31
- isAuthenticated: () => boolean;
32
- calculateCost: (multiplier?: number) => number;
33
- execute: (request: TRequest) => Promise<GenerationExecutionResult<TResult>>;
34
- onAuthRequired: () => void;
35
- onCreditsRequired: () => void;
36
- }
37
-
38
- export interface UseGenerationCallbacksBuilderOptions<TRequest, TResult> {
39
- config: GenerationCallbacksConfig<TRequest, TResult>;
40
- onSuccess?: (result: TResult) => void;
41
- onError?: (error: string) => void;
42
- }
@@ -1,61 +0,0 @@
1
- /**
2
- * Photo Generation Types
3
- * Generic types for photo-based AI generation workflows
4
- */
5
-
6
- export interface PhotoGenerationInput<TMetadata = unknown> {
7
- photos: Array<{ uri: string; base64: string }>;
8
- metadata?: TMetadata;
9
- }
10
-
11
- export interface PhotoGenerationResult<TResult = unknown> {
12
- success: boolean;
13
- data?: TResult;
14
- error?: PhotoGenerationError;
15
- }
16
-
17
- export interface PhotoGenerationError {
18
- type: "network_error" | "policy_violation" | "save_failed" | "credit_failed" | "unknown";
19
- message: string;
20
- originalError?: Error;
21
- }
22
-
23
- export interface AlertMessages {
24
- networkError: string;
25
- policyViolation: string;
26
- saveFailed: string;
27
- creditFailed: string;
28
- unknown: string;
29
- }
30
-
31
- export interface PhotoGenerationConfig<TInput, TResult, TSaveInput> {
32
- /** User ID for credit operations - required for credit check/deduct */
33
- userId: string | undefined;
34
- /** Credit cost per generation (default: 1) */
35
- creditCost?: number;
36
- /** Generation function */
37
- generate: (input: TInput, onProgress?: (progress: number) => void) => Promise<TResult>;
38
- /** Save result function */
39
- save?: (result: TResult, input: TInput) => Promise<TSaveInput>;
40
- /** Build metadata for tracking */
41
- buildMetadata?: (input: TInput) => Record<string, unknown>;
42
- /** Called when credits are exhausted */
43
- onCreditsExhausted?: () => void;
44
- /** Success callback */
45
- onSuccess?: (result: TResult) => void;
46
- /** Error callback */
47
- onError?: (error: PhotoGenerationError) => void;
48
- /** Save complete callback */
49
- onSaveComplete?: (saveResult: TSaveInput) => void;
50
- /** Alert messages for errors */
51
- alertMessages: AlertMessages;
52
- }
53
-
54
- export interface PhotoGenerationState<TResult = unknown> {
55
- isGenerating: boolean;
56
- result: TResult | null;
57
- error: PhotoGenerationError | null;
58
- progress: number;
59
- }
60
-
61
- export type PhotoGenerationStatus = "idle" | "validating" | "generating" | "saving" | "success" | "error";
@@ -1,126 +0,0 @@
1
- /**
2
- * Generic Generation Callbacks Builder
3
- * Unified hook for ALL generation types (image, video, audio, text)
4
- */
5
-
6
- import { useCallback, useMemo, useRef } from "react";
7
- import { useQueryClient } from "@umituz/react-native-design-system";
8
- import type {
9
- GenerationExecutionResult,
10
- GenerationCallbacks,
11
- UseGenerationCallbacksBuilderOptions,
12
- } from "./generation-callbacks.types";
13
-
14
- declare const __DEV__: boolean;
15
-
16
- export function useGenerationCallbacksBuilder<TRequest, TResult>(
17
- options: UseGenerationCallbacksBuilderOptions<TRequest, TResult>,
18
- ): { callbacks: GenerationCallbacks<TRequest, TResult> } {
19
- const { config, onSuccess, onError } = options;
20
- const queryClient = useQueryClient();
21
- const isExecutingRef = useRef(false);
22
-
23
- const canAfford = useCallback(
24
- (cost?: number): boolean => {
25
- const actualCost = cost ?? config.creditCost;
26
- return config.creditBalance >= actualCost;
27
- },
28
- [config.creditBalance, config.creditCost],
29
- );
30
-
31
- const isAuthenticated = useCallback(
32
- (): boolean => config.isAuthenticated,
33
- [config.isAuthenticated],
34
- );
35
-
36
- const calculateCost = useCallback(
37
- (multiplier = 1): number => config.creditCost * multiplier,
38
- [config.creditCost],
39
- );
40
-
41
- const onAuthRequired = useCallback(() => {
42
- if (config.showAuthModal) {
43
- config.showAuthModal();
44
- } else {
45
- config.openPaywall();
46
- }
47
- }, [config]);
48
-
49
- const onCreditsRequired = useCallback(() => {
50
- config.openPaywall();
51
- }, [config]);
52
-
53
- const execute = useCallback(
54
- async (request: TRequest): Promise<GenerationExecutionResult<TResult>> => {
55
- if (isExecutingRef.current) {
56
- return { success: false, error: "Generation already in progress" };
57
- }
58
-
59
- if (!config.isAuthenticated || !config.userId) {
60
- onAuthRequired();
61
- return { success: false, error: "Authentication required" };
62
- }
63
-
64
- if (!canAfford()) {
65
- if (typeof __DEV__ !== "undefined" && __DEV__) {
66
-
67
- console.log("[Generation] Insufficient credits", {
68
- balance: config.creditBalance,
69
- cost: config.creditCost,
70
- });
71
- }
72
- onCreditsRequired();
73
- return { success: false, error: "Insufficient credits" };
74
- }
75
-
76
- isExecutingRef.current = true;
77
-
78
- try {
79
- const result = await config.executor(request);
80
-
81
- if (!result.success || !result.data) {
82
- return { success: false, error: result.error || "Generation failed" };
83
- }
84
-
85
- await config.deductCredit(config.creditType);
86
-
87
- if (config.saveCreation) {
88
- try {
89
- await config.saveCreation(result.data);
90
- } catch {
91
- // Silent fail for save
92
- }
93
- }
94
-
95
- const keys = config.invalidateQueryKeys ?? ["creations"];
96
- keys.forEach((key) => queryClient.invalidateQueries({ queryKey: [key] }));
97
-
98
- onSuccess?.(result.data);
99
- config.onNavigateAfterSuccess?.();
100
-
101
- return { success: true, data: result.data };
102
- } catch (error) {
103
- const message = error instanceof Error ? error.message : String(error);
104
- onError?.(message);
105
- return { success: false, error: message };
106
- } finally {
107
- isExecutingRef.current = false;
108
- }
109
- },
110
- [config, canAfford, onAuthRequired, onCreditsRequired, queryClient, onSuccess, onError],
111
- );
112
-
113
- const callbacks = useMemo<GenerationCallbacks<TRequest, TResult>>(
114
- () => ({
115
- canAfford,
116
- isAuthenticated,
117
- calculateCost,
118
- execute,
119
- onAuthRequired,
120
- onCreditsRequired,
121
- }),
122
- [canAfford, isAuthenticated, calculateCost, execute, onAuthRequired, onCreditsRequired],
123
- );
124
-
125
- return { callbacks };
126
- }
@@ -1,77 +0,0 @@
1
- /**
2
- * useGenerationCredits Hook
3
- * Centralized credit management for all AI generation features
4
- * Provides server-side credit validation before generation
5
- */
6
-
7
- import { useCallback } from "react";
8
- import { useDeductCredit } from "@umituz/react-native-subscription";
9
-
10
- export interface UseGenerationCreditsParams {
11
- userId: string | undefined;
12
- onCreditsExhausted?: () => void;
13
- }
14
-
15
- export interface GenerationCreditsError {
16
- type: "no_credits" | "deduct_failed";
17
- message: string;
18
- }
19
-
20
- export interface UseGenerationCreditsReturn {
21
- /** Server-side credit check */
22
- checkCredits: (cost?: number) => Promise<boolean>;
23
- /** Deduct credits after successful generation */
24
- deductCredits: (cost?: number) => Promise<boolean>;
25
- /** Whether credit operation is in progress */
26
- isProcessing: boolean;
27
- /** Execute generation with automatic credit check and deduct */
28
- withCredits: <T>(
29
- generate: () => Promise<T>,
30
- cost?: number,
31
- ) => Promise<T>;
32
- }
33
-
34
- export const useGenerationCredits = ({
35
- userId,
36
- onCreditsExhausted,
37
- }: UseGenerationCreditsParams): UseGenerationCreditsReturn => {
38
- const { checkCredits, deductCredit, isDeducting } = useDeductCredit({
39
- userId,
40
- onCreditsExhausted,
41
- });
42
-
43
- const withCredits = useCallback(
44
- async <T>(generate: () => Promise<T>, cost: number = 1): Promise<T> => {
45
- const hasCredits = await checkCredits(cost);
46
- if (!hasCredits) {
47
- throw new CreditError("no_credits", "Insufficient credits");
48
- }
49
-
50
- const result = await generate();
51
-
52
- await deductCredit(cost);
53
-
54
- return result;
55
- },
56
- [checkCredits, deductCredit],
57
- );
58
-
59
- return {
60
- checkCredits,
61
- deductCredits: deductCredit,
62
- isProcessing: isDeducting,
63
- withCredits,
64
- };
65
- };
66
-
67
- class CreditError extends Error {
68
- constructor(
69
- public type: GenerationCreditsError["type"],
70
- message: string,
71
- ) {
72
- super(message);
73
- this.name = "CreditError";
74
- }
75
- }
76
-
77
- export { CreditError };