@umituz/react-native-ai-generation-content 1.90.2 → 1.90.3

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 (152) hide show
  1. package/package.json +1 -1
  2. package/src/domain/interfaces/app-services-auth.interface.ts +27 -0
  3. package/src/domain/interfaces/app-services-composite.interface.ts +29 -0
  4. package/src/domain/interfaces/app-services-optional.interface.ts +42 -0
  5. package/src/domain/interfaces/app-services.interface.ts +0 -79
  6. package/src/domains/background/infrastructure/services/job-poller-index.ts +7 -0
  7. package/src/domains/background/infrastructure/services/job-poller-utils.ts +130 -0
  8. package/src/domains/background/infrastructure/utils/polling-interval.util.ts +1 -1
  9. package/src/domains/background/presentation/hooks/use-background-generation.ts +1 -1
  10. package/src/domains/content-moderation/infrastructure/services/content-moderation.service.ts +1 -1
  11. package/src/domains/content-moderation/infrastructure/services/moderators/image.moderator.ts +34 -8
  12. package/src/domains/content-moderation/infrastructure/services/moderators/text.moderator.ts +15 -4
  13. package/src/domains/content-moderation/infrastructure/services/moderators/video.moderator.ts +34 -8
  14. package/src/domains/content-moderation/infrastructure/services/moderators/voice.moderator.ts +19 -8
  15. package/src/domains/creations/domain/types/creation-categories.constants.ts +57 -0
  16. package/src/domains/creations/domain/types/creation-categories.helpers.ts +67 -0
  17. package/src/domains/creations/domain/types/creation-categories.ts +5 -111
  18. package/src/domains/creations/presentation/hooks/creation-validators.ts +31 -29
  19. package/src/domains/creations/presentation/hooks/job-poller-index.ts +10 -0
  20. package/src/domains/creations/presentation/hooks/job-poller-utils.filters.ts +34 -0
  21. package/src/domains/creations/presentation/hooks/job-poller-utils.logger.ts +76 -0
  22. package/src/domains/creations/presentation/hooks/job-poller-utils.stale-handlers.ts +52 -0
  23. package/src/domains/creations/presentation/hooks/job-poller-utils.ts +8 -0
  24. package/src/domains/creations/presentation/screens/CreationsGalleryScreen.tsx +1 -1
  25. package/src/domains/creations/presentation-exports.ts +2 -2
  26. package/src/domains/face-detection/domain/entities/FaceDetection.ts +4 -3
  27. package/src/domains/face-detection/presentation/hooks/useFaceDetection.ts +24 -21
  28. package/src/domains/generation/infrastructure/couple-generation-builder/builder-couple-preparation.ts +58 -0
  29. package/src/domains/generation/infrastructure/couple-generation-builder/builder-couple-prompt.ts +69 -0
  30. package/src/domains/generation/infrastructure/couple-generation-builder/builder-couple-resolution.ts +77 -0
  31. package/src/domains/generation/infrastructure/couple-generation-builder/builder-couple.ts +54 -0
  32. package/src/domains/generation/infrastructure/couple-generation-builder/builder-index.ts +8 -0
  33. package/src/domains/generation/infrastructure/couple-generation-builder/builder-scenario.ts +113 -0
  34. package/src/domains/generation/infrastructure/couple-generation-builder/builder.ts +7 -0
  35. package/src/domains/generation/infrastructure/couple-generation-builder/index.ts +20 -0
  36. package/src/domains/generation/infrastructure/couple-generation-builder/types.ts +44 -0
  37. package/src/domains/generation/infrastructure/couple-generation-builder/utils/builder-end-logger.ts +18 -0
  38. package/src/domains/generation/infrastructure/couple-generation-builder/utils/builder-start-logger.ts +57 -0
  39. package/src/domains/generation/infrastructure/couple-generation-builder/utils/builder-step-logger.ts +106 -0
  40. package/src/domains/generation/infrastructure/couple-generation-builder/utils/index.ts +8 -0
  41. package/src/domains/generation/infrastructure/couple-generation-builder/utils/types.ts +49 -0
  42. package/src/domains/generation/infrastructure/couple-generation-builder/utils.ts +8 -0
  43. package/src/domains/generation/infrastructure/flow/flow-store-actions.ts +105 -0
  44. package/src/domains/generation/infrastructure/flow/flow-store-initial-state.ts +26 -0
  45. package/src/domains/generation/infrastructure/flow/useFlowStore.ts +4 -116
  46. package/src/domains/generation/presentation/useAIGeneration.hook.ts +1 -1
  47. package/src/domains/generation/wizard/infrastructure/strategies/image-generation-strategy-index.ts +7 -0
  48. package/src/domains/generation/wizard/infrastructure/strategies/image-generation.executor.ts +2 -12
  49. package/src/domains/generation/wizard/infrastructure/strategies/image-generation.executor.types.ts +11 -0
  50. package/src/domains/generation/wizard/infrastructure/strategies/image-generation.executor.utils.ts +12 -0
  51. package/src/domains/generation/wizard/infrastructure/strategies/image-generation.strategy.ts +1 -220
  52. package/src/domains/generation/wizard/infrastructure/strategies/image-input-builder.ts +66 -0
  53. package/src/domains/generation/wizard/infrastructure/strategies/image-input-extraction.ts +88 -0
  54. package/src/domains/generation/wizard/infrastructure/strategies/image-input-prompt-builder.ts +75 -0
  55. package/src/domains/generation/wizard/infrastructure/strategies/image-input-style-enhancements.ts +35 -0
  56. package/src/domains/generation/wizard/infrastructure/strategies/image-strategy-factory.ts +42 -0
  57. package/src/domains/generation/wizard/infrastructure/strategies/video-generation-executor-index.ts +11 -0
  58. package/src/domains/generation/wizard/infrastructure/strategies/video-generation-executor.ts +76 -0
  59. package/src/domains/generation/wizard/infrastructure/strategies/video-generation-input-builder.ts +46 -0
  60. package/src/domains/generation/wizard/infrastructure/strategies/video-generation-result-types.ts +17 -0
  61. package/src/domains/generation/wizard/infrastructure/strategies/video-generation-submission.ts +62 -0
  62. package/src/domains/generation/wizard/infrastructure/strategies/video-generation.audio-extractor.ts +27 -0
  63. package/src/domains/generation/wizard/infrastructure/strategies/video-generation.executor.ts +2 -175
  64. package/src/domains/generation/wizard/infrastructure/strategies/video-generation.input-builder.ts +90 -0
  65. package/src/domains/generation/wizard/infrastructure/strategies/video-generation.strategy.ts +3 -108
  66. package/src/domains/generation/wizard/infrastructure/strategies/video-generation.types.ts +0 -129
  67. package/src/domains/generation/wizard/infrastructure/strategies/video-generation.validation.ts +136 -0
  68. package/src/domains/generation/wizard/presentation/hooks/photo-upload/index.ts +39 -0
  69. package/src/domains/generation/wizard/presentation/hooks/photo-upload/types.ts +37 -0
  70. package/src/domains/generation/wizard/presentation/hooks/photo-upload/usePhotoUploadStateLogic.ts +142 -0
  71. package/src/domains/generation/wizard/presentation/hooks/use-video-queue-utils.ts +103 -0
  72. package/src/domains/generation/wizard/presentation/hooks/usePhotoBlockingGeneration.handlers.ts +97 -0
  73. package/src/domains/generation/wizard/presentation/hooks/usePhotoBlockingGeneration.saver.ts +54 -0
  74. package/src/domains/generation/wizard/presentation/hooks/usePhotoBlockingGeneration.ts +22 -87
  75. package/src/domains/generation/wizard/presentation/hooks/usePhotoUploadState.ts +8 -177
  76. package/src/domains/generation/wizard/presentation/hooks/useVideoQueueGeneration.ts +1 -295
  77. package/src/domains/generation/wizard/presentation/hooks/useWizardGeneration.ts +1 -1
  78. package/src/domains/generation/wizard/presentation/hooks/video-queue/index.ts +82 -0
  79. package/src/domains/generation/wizard/presentation/hooks/video-queue/useVideoQueueGenerationCallbacks.ts +120 -0
  80. package/src/domains/generation/wizard/presentation/hooks/video-queue/useVideoQueueGenerationPolling.ts +76 -0
  81. package/src/domains/generation/wizard/presentation/hooks/video-queue/useVideoQueueGenerationRefs.ts +65 -0
  82. package/src/domains/generation/wizard/presentation/hooks/video-queue/useVideoQueueGenerationStart.ts +123 -0
  83. package/src/domains/generation/wizard/presentation/hooks/video-queue-index.ts +9 -0
  84. package/src/domains/image-to-video/domain/types/image-to-video-state.types.ts +11 -4
  85. package/src/domains/text-to-image/domain/types/text-to-image.types.ts +44 -22
  86. package/src/domains/text-to-video/domain/types/request.types.ts +33 -9
  87. package/src/domains/text-to-video/domain/types/state.types.ts +29 -9
  88. package/src/domains/text-to-video/presentation/hooks/useTextToVideoForm.handlers.ts +44 -0
  89. package/src/domains/text-to-video/presentation/hooks/useTextToVideoForm.ts +5 -51
  90. package/src/domains/text-to-video/presentation/hooks/useTextToVideoForm.types.ts +33 -0
  91. package/src/infrastructure/services/generation-orchestrator.service.ts +2 -2
  92. package/src/infrastructure/utils/couple-input-context.ts +13 -0
  93. package/src/infrastructure/utils/couple-input-index.ts +8 -0
  94. package/src/infrastructure/utils/couple-input-refiner.ts +101 -0
  95. package/src/infrastructure/utils/couple-input-resolver.ts +71 -0
  96. package/src/infrastructure/utils/couple-input-types.ts +14 -0
  97. package/src/infrastructure/utils/couple-input.util.ts +3 -176
  98. package/src/infrastructure/utils/photo-generation/photo-preparation.util.ts +1 -1
  99. package/src/infrastructure/validation/base-validator.ts +1 -27
  100. package/src/infrastructure/validation/base-validator.types.ts +32 -0
  101. package/src/presentation/hooks/generation/index.ts +1 -1
  102. package/src/presentation/hooks/generation/orchestrator-abort-logs.ts +48 -0
  103. package/src/presentation/hooks/generation/orchestrator-execution-logs.ts +67 -0
  104. package/src/presentation/hooks/generation/orchestrator-index.ts +14 -0
  105. package/src/presentation/hooks/generation/orchestrator-start-logs.ts +65 -0
  106. package/src/presentation/hooks/generation/orchestrator-state-utils.ts +17 -0
  107. package/src/presentation/hooks/generation/orchestrator-types.ts +55 -0
  108. package/src/presentation/hooks/generation/orchestrator-utils-index.ts +29 -0
  109. package/src/presentation/hooks/generation/orchestrator-utils.ts +25 -0
  110. package/src/presentation/hooks/generation/useDualImageGeneration.ts +1 -1
  111. package/src/presentation/hooks/generation/useImageGeneration.ts +1 -1
  112. package/src/presentation/hooks/generation/useVideoGeneration.ts +1 -1
  113. package/src/shared/hooks/factories/generation-hook-index.ts +12 -0
  114. package/src/shared/hooks/factories/generation-hook-types.ts +47 -0
  115. package/src/shared/hooks/factories/generation-hook-utils.ts +94 -0
  116. package/src/shared/hooks/factories/index.ts +1 -1
  117. package/src/shared/index.ts +1 -1
  118. package/src/shared/utils/calculations/aspect-ratio-calculations.ts +30 -0
  119. package/src/shared/utils/calculations/base64-calculations.ts +26 -0
  120. package/src/shared/utils/calculations/confidence-calculations.ts +21 -0
  121. package/src/shared/utils/calculations/cost-calculations-index.ts +43 -0
  122. package/src/shared/utils/calculations/cost-calculations.ts +25 -0
  123. package/src/shared/utils/calculations/credit-calculations.ts +37 -0
  124. package/src/shared/utils/calculations/index.ts +46 -0
  125. package/src/shared/utils/calculations/math-utilities.ts +32 -0
  126. package/src/shared/utils/calculations/memory-calculations.ts +33 -0
  127. package/src/shared/utils/calculations/pagination-calculations.ts +38 -0
  128. package/src/shared/utils/calculations/percentage-calculations.ts +33 -0
  129. package/src/shared/utils/calculations/time-calculations.ts +99 -0
  130. package/src/shared/utils/credit.ts +1 -1
  131. package/src/shared-kernel/application/hooks/index.ts +8 -0
  132. package/src/shared-kernel/application/hooks/use-feature-state.ts +107 -0
  133. package/src/shared-kernel/application/hooks/use-generation-handler.ts +110 -0
  134. package/src/shared-kernel/base-types/base-callbacks.types.ts +73 -0
  135. package/src/shared-kernel/base-types/base-feature-state.types.ts +77 -0
  136. package/src/shared-kernel/base-types/base-generation.types.ts +69 -0
  137. package/src/shared-kernel/base-types/index.ts +30 -0
  138. package/src/shared-kernel/domain/base-generation-strategy.ts +146 -0
  139. package/src/shared-kernel/domain/index.ts +7 -0
  140. package/src/shared-kernel/index.ts +17 -0
  141. package/src/shared-kernel/infrastructure/validation/common-validators.ts +126 -0
  142. package/src/shared-kernel/infrastructure/validation/common-validators.types.ts +33 -0
  143. package/src/shared-kernel/infrastructure/validation/error-handler.ts +52 -0
  144. package/src/shared-kernel/infrastructure/validation/error-handler.types.ts +38 -0
  145. package/src/shared-kernel/infrastructure/validation/error-handler.utils.ts +79 -0
  146. package/src/shared-kernel/infrastructure/validation/index.ts +28 -0
  147. package/src/domains/background/infrastructure/services/job-poller.service.ts +0 -234
  148. package/src/domains/creations/presentation/hooks/useProcessingJobsPoller.ts +0 -256
  149. package/src/domains/generation/infrastructure/couple-generation-builder.ts +0 -374
  150. package/src/presentation/hooks/generation/orchestrator.ts +0 -276
  151. package/src/shared/hooks/factories/createGenerationHook.ts +0 -253
  152. package/src/shared/utils/calculations.util.ts +0 -366
@@ -1,253 +0,0 @@
1
- /**
2
- * Generic Generation Hook Factory
3
- * Creates type-safe generation hooks with error handling, progress tracking, and abort support
4
- */
5
-
6
- import { useState, useCallback, useRef, useEffect } from "react";
7
-
8
- /**
9
- * Generation state
10
- */
11
- export interface GenerationState {
12
- isGenerating: boolean;
13
- progress: number;
14
- error: string | null;
15
- }
16
-
17
- /**
18
- * Generation callbacks
19
- */
20
- export interface GenerationCallbacks<TResult> {
21
- /** Called when generation succeeds */
22
- onSuccess?: (result: TResult) => void;
23
- /** Called when generation fails */
24
- onError?: (error: string) => void;
25
- /** Called on progress update */
26
- onProgress?: (progress: number) => void;
27
- }
28
-
29
- /**
30
- * Generation hook configuration
31
- */
32
- export interface GenerationHookConfig<TRequest, TResult> {
33
- /** Execute the generation request */
34
- execute: (request: TRequest, signal?: AbortSignal) => Promise<TResult>;
35
- /** Optional validation before execution */
36
- validate?: (request: TRequest) => string | null;
37
- /** Optional transform for errors */
38
- transformError?: (error: unknown) => string;
39
- }
40
-
41
- /**
42
- * Generation hook return type
43
- */
44
- export interface GenerationHookReturn<TRequest, TResult> {
45
- generationState: GenerationState;
46
- handleGenerate: (request: TRequest) => Promise<TResult | null>;
47
- setProgress: (progress: number) => void;
48
- setError: (error: string | null) => void;
49
- abort: () => void;
50
- }
51
-
52
- const INITIAL_STATE: GenerationState = {
53
- isGenerating: false,
54
- progress: 0,
55
- error: null,
56
- };
57
-
58
- /**
59
- * Creates a type-safe generation hook
60
- * @param config - Generation hook configuration
61
- * @param callbacks - Generation callbacks
62
- * @returns Generation hook
63
- *
64
- * @example
65
- * ```ts
66
- * const useMyGeneration = createGenerationHook({
67
- * execute: async (request) => {
68
- * return await api.generate(request);
69
- * },
70
- * validate: (request) => {
71
- * if (!request.prompt) return "Prompt is required";
72
- * return null;
73
- * },
74
- * });
75
- *
76
- * // Usage
77
- * const { generationState, handleGenerate } = useMyGeneration({
78
- * onSuccess: (result) => console.log("Success!", result),
79
- * onError: (error) => console.error("Error:", error),
80
- * });
81
- * ```
82
- */
83
- export function createGenerationHook<TRequest, TResult>(
84
- config: GenerationHookConfig<TRequest, TResult>
85
- ) {
86
- return function useGeneration(
87
- callbacks: GenerationCallbacks<TResult> = {}
88
- ): GenerationHookReturn<TRequest, TResult> {
89
- const [generationState, setGenerationState] = useState<GenerationState>(INITIAL_STATE);
90
-
91
- const abortControllerRef = useRef<AbortController | null>(null);
92
- const isMountedRef = useRef(true);
93
-
94
- // Stabilize callbacks
95
- const onSuccessRef = useRef(callbacks.onSuccess);
96
- const onErrorRef = useRef(callbacks.onError);
97
- const onProgressRef = useRef(callbacks.onProgress);
98
-
99
- useEffect(() => {
100
- onSuccessRef.current = callbacks.onSuccess;
101
- onErrorRef.current = callbacks.onError;
102
- onProgressRef.current = callbacks.onProgress;
103
- }, [callbacks.onSuccess, callbacks.onError, callbacks.onProgress]);
104
-
105
- // Cleanup on unmount
106
- useEffect(() => {
107
- isMountedRef.current = true;
108
- return () => {
109
- isMountedRef.current = false;
110
- abortControllerRef.current?.abort();
111
- };
112
- }, []);
113
-
114
- const setProgress = useCallback((progress: number) => {
115
- if (!isMountedRef.current) return;
116
- setGenerationState((prev) => ({ ...prev, progress }));
117
- onProgressRef.current?.(progress);
118
- }, []);
119
-
120
- const setError = useCallback((error: string | null) => {
121
- if (!isMountedRef.current) return;
122
- setGenerationState((prev) => ({ ...prev, error, isGenerating: false }));
123
- if (error) {
124
- onErrorRef.current?.(error);
125
- }
126
- }, []);
127
-
128
- const abort = useCallback(() => {
129
- abortControllerRef.current?.abort();
130
- if (isMountedRef.current) {
131
- setGenerationState((prev) => ({
132
- ...prev,
133
- isGenerating: false,
134
- error: "Generation aborted",
135
- }));
136
- }
137
- }, []);
138
-
139
- const handleGenerate = useCallback(
140
- async (request: TRequest): Promise<TResult | null> => {
141
- // Validate request
142
- if (config.validate) {
143
- const validationError = config.validate(request);
144
- if (validationError) {
145
- setError(validationError);
146
- return null;
147
- }
148
- }
149
-
150
- // Create new AbortController
151
- abortControllerRef.current = new AbortController();
152
-
153
- setGenerationState({
154
- isGenerating: true,
155
- progress: 0,
156
- error: null,
157
- });
158
-
159
- try {
160
- const result = await config.execute(
161
- request,
162
- abortControllerRef.current.signal
163
- );
164
-
165
- if (!isMountedRef.current || abortControllerRef.current.signal.aborted) {
166
- return null;
167
- }
168
-
169
- setGenerationState((prev) => ({
170
- ...prev,
171
- isGenerating: false,
172
- progress: 100
173
- }));
174
-
175
- onSuccessRef.current?.(result);
176
- return result;
177
- } catch (error) {
178
- if (!isMountedRef.current || abortControllerRef.current.signal.aborted) {
179
- return null;
180
- }
181
-
182
- const errorMessage = config.transformError
183
- ? config.transformError(error)
184
- : error instanceof Error
185
- ? error.message
186
- : String(error);
187
-
188
- setError(errorMessage);
189
- return null;
190
- } finally {
191
- abortControllerRef.current = null;
192
- }
193
- },
194
- [config, setError]
195
- );
196
-
197
- return {
198
- generationState,
199
- handleGenerate,
200
- setProgress,
201
- setError,
202
- abort,
203
- };
204
- };
205
- }
206
-
207
- /**
208
- * Creates a generation hook with progress updates
209
- * Useful when the generation API supports progress callbacks
210
- */
211
- export function createGenerationHookWithProgress<TRequest, TResult>(
212
- config: GenerationHookConfig<TRequest, TResult> & {
213
- /** Get progress stream or polling function */
214
- subscribeToProgress?: (
215
- request: TRequest,
216
- onProgress: (progress: number) => void
217
- ) => () => void;
218
- }
219
- ) {
220
- const baseHook = createGenerationHook(config);
221
-
222
- return function useGenerationWithProgress(
223
- callbacks: GenerationCallbacks<TResult> = {}
224
- ): GenerationHookReturn<TRequest, TResult> {
225
- const hookResult = baseHook(callbacks);
226
- const unsubscribeRef = useRef<(() => void) | null>(null);
227
-
228
- const handleGenerateWithProgress = useCallback(
229
- async (request: TRequest): Promise<TResult | null> => {
230
- // Subscribe to progress if available
231
- if (config.subscribeToProgress) {
232
- unsubscribeRef.current = config.subscribeToProgress(
233
- request,
234
- hookResult.setProgress
235
- );
236
- }
237
-
238
- try {
239
- return await hookResult.handleGenerate(request);
240
- } finally {
241
- unsubscribeRef.current?.();
242
- unsubscribeRef.current = null;
243
- }
244
- },
245
- [hookResult, config.subscribeToProgress]
246
- );
247
-
248
- return {
249
- ...hookResult,
250
- handleGenerate: handleGenerateWithProgress,
251
- };
252
- };
253
- }
@@ -1,366 +0,0 @@
1
- /**
2
- * Calculation Utilities
3
- * Centralized calculation operations for better performance and maintainability
4
- */
5
-
6
- /**
7
- * Time & Duration Calculations
8
- */
9
-
10
- /**
11
- * Calculate age in milliseconds from a timestamp
12
- */
13
- export function calculateAgeMs(timestamp: Date | number): number {
14
- const time = typeof timestamp === "number" ? timestamp : timestamp.getTime();
15
- return Date.now() - time;
16
- }
17
-
18
- /**
19
- * Calculate age in seconds from a timestamp
20
- */
21
- export function calculateAgeSeconds(timestamp: Date | number): number {
22
- return Math.floor(calculateAgeMs(timestamp) / 1000);
23
- }
24
-
25
- /**
26
- * Calculate age in minutes from a timestamp
27
- */
28
- export function calculateAgeMinutes(timestamp: Date | number): number {
29
- return Math.floor(calculateAgeSeconds(timestamp) / 60);
30
- }
31
-
32
- /**
33
- * Check if timestamp is older than specified milliseconds
34
- */
35
- export function isOlderThan(timestamp: Date | number, maxAgeMs: number): boolean {
36
- return calculateAgeMs(timestamp) > maxAgeMs;
37
- }
38
-
39
- /**
40
- * Calculate duration between two timestamps in milliseconds
41
- */
42
- export function calculateDurationMs(
43
- startTime: Date | number,
44
- endTime: Date | number = Date.now()
45
- ): number {
46
- const start = typeof startTime === "number" ? startTime : startTime.getTime();
47
- const end = typeof endTime === "number" ? endTime : endTime.getTime();
48
- return end - start;
49
- }
50
-
51
- /**
52
- * Format duration in milliseconds to human-readable string
53
- */
54
- export function formatDuration(ms: number): string {
55
- const seconds = Math.floor(ms / 1000);
56
- const minutes = Math.floor(seconds / 60);
57
- const hours = Math.floor(minutes / 60);
58
-
59
- if (hours > 0) {
60
- return `${hours}h ${minutes % 60}m`;
61
- }
62
- if (minutes > 0) {
63
- return `${minutes}m ${seconds % 60}s`;
64
- }
65
- return `${seconds}s`;
66
- }
67
-
68
- /**
69
- * Polling Calculations
70
- */
71
-
72
- /**
73
- * Calculate polling interval with exponential backoff
74
- */
75
- export function calculatePollingInterval(options: {
76
- attempt: number;
77
- initialIntervalMs: number;
78
- maxIntervalMs: number;
79
- backoffMultiplier: number;
80
- }): number {
81
- const { attempt, initialIntervalMs, maxIntervalMs, backoffMultiplier } = options;
82
-
83
- if (attempt === 0) {
84
- return 0;
85
- }
86
-
87
- const interval = initialIntervalMs * Math.pow(backoffMultiplier, attempt - 1);
88
- return Math.min(interval, maxIntervalMs);
89
- }
90
-
91
- /**
92
- * Calculate estimated total polling time
93
- */
94
- export function calculateEstimatedPollingTime(options: {
95
- maxAttempts: number;
96
- initialIntervalMs: number;
97
- maxIntervalMs: number;
98
- backoffMultiplier: number;
99
- }): number {
100
- let total = 0;
101
- for (let attempt = 1; attempt < options.maxAttempts; attempt++) {
102
- total += calculatePollingInterval({ ...options, attempt });
103
- if (total >= options.maxIntervalMs * options.maxAttempts) {
104
- break;
105
- }
106
- }
107
- return total;
108
- }
109
-
110
- /**
111
- * Progress & Percentage Calculations
112
- */
113
-
114
- /**
115
- * Calculate percentage with bounds checking (0-100)
116
- */
117
- export function calculatePercentage(value: number, total: number): number {
118
- if (total === 0) return 0;
119
- const percentage = (value / total) * 100;
120
- return Math.max(0, Math.min(100, percentage));
121
- }
122
-
123
- /**
124
- * Calculate progress with min/max bounds
125
- */
126
- export function calculateProgress(
127
- current: number,
128
- total: number,
129
- min: number = 0,
130
- max: number = 100
131
- ): number {
132
- if (total === 0) return min;
133
- const percentage = (current / total) * (max - min) + min;
134
- return Math.max(min, Math.min(max, percentage));
135
- }
136
-
137
- /**
138
- * Calculate remaining percentage
139
- */
140
- export function calculateRemaining(current: number, total: number): number {
141
- return Math.max(0, total - current);
142
- }
143
-
144
- /**
145
- * Array & Collection Calculations
146
- */
147
-
148
- /**
149
- * Calculate filtered count with predicate
150
- */
151
- export function calculateFilteredCount<T>(
152
- items: readonly T[],
153
- predicate: (item: T) => boolean
154
- ): number {
155
- return items.reduce((count, item) => (predicate(item) ? count + 1 : count), 0);
156
- }
157
-
158
- /**
159
- * Calculate pagination slice
160
- */
161
- export function calculatePaginationSlice(
162
- totalItems: number,
163
- page: number,
164
- pageSize: number
165
- ): { start: number; end: number; count: number } {
166
- const start = page * pageSize;
167
- const end = Math.min(start + pageSize, totalItems);
168
- const count = end - start;
169
- return { start, end, count };
170
- }
171
-
172
- /**
173
- * Calculate if more items exist for pagination
174
- */
175
- export function calculateHasMore(
176
- currentCount: number,
177
- currentPage: number,
178
- pageSize: number
179
- ): boolean {
180
- return currentCount >= currentPage * pageSize;
181
- }
182
-
183
- /**
184
- * Base64 & Size Calculations
185
- */
186
-
187
- /**
188
- * Calculate base64 size in bytes
189
- */
190
- export function calculateBase64Size(base64: string): number {
191
- // Remove data URI prefix if present
192
- const cleanBase64 = base64.replace(/^data:[^;]+;base64,/, "");
193
- return (cleanBase64.length * 3) / 4;
194
- }
195
-
196
- /**
197
- * Calculate base64 size in megabytes
198
- */
199
- export function calculateBase64SizeMB(base64: string): number {
200
- return calculateBase64Size(base64) / (1024 * 1024);
201
- }
202
-
203
- /**
204
- * Calculate if base64 size is within limit
205
- */
206
- export function isBase64SizeWithinLimit(base64: string, maxSizeMB: number): boolean {
207
- return calculateBase64SizeMB(base64) <= maxSizeMB;
208
- }
209
-
210
- /**
211
- * Confidence Score Calculations
212
- */
213
-
214
- /**
215
- * Calculate confidence score from violations with weights
216
- */
217
- export function calculateConfidenceScore(
218
- violations: readonly { severity: "critical" | "high" | "medium" | "low" }[]
219
- ): number {
220
- if (violations.length === 0) return 1.0;
221
-
222
- const weights = { critical: 1.0, high: 0.75, medium: 0.5, low: 0.25 };
223
- const score = violations.reduce(
224
- (sum, v) => sum + (weights[v.severity] || 0.25),
225
- 0
226
- );
227
-
228
- // Normalize by number of violations, capped at 1.0
229
- return Math.min(1.0, score / Math.max(1, violations.length));
230
- }
231
-
232
- /**
233
- * Credit & Cost Calculations
234
- */
235
-
236
- /**
237
- * Calculate cost in credits based on duration and resolution
238
- */
239
- export function calculateCredits(
240
- durationSeconds: number,
241
- resolutionMultiplier: number = 1,
242
- baseCost: number = 1
243
- ): number {
244
- return Math.ceil((durationSeconds / 60) * resolutionMultiplier * baseCost);
245
- }
246
-
247
- /**
248
- * Calculate resolution multiplier for credits
249
- */
250
- export function calculateResolutionMultiplier(width: number, height: number): number {
251
- const totalPixels = width * height;
252
- const basePixels = 720 * 1280; // HD baseline
253
-
254
- if (totalPixels <= basePixels) return 1;
255
- if (totalPixels <= basePixels * 2) return 1.5;
256
- if (totalPixels <= basePixels * 4) return 2;
257
- return 3;
258
- }
259
-
260
- /**
261
- * Calculate cost to credits conversion
262
- */
263
- export function convertCostToCredits(
264
- cost: number,
265
- creditsPerDollar: number = 100
266
- ): number {
267
- return Math.ceil(cost * creditsPerDollar);
268
- }
269
-
270
- /**
271
- * Aspect Ratio Calculations
272
- */
273
-
274
- /**
275
- * Calculate aspect ratio from dimensions
276
- */
277
- export function calculateAspectRatio(width: number, height: number): number {
278
- return width / height;
279
- }
280
-
281
- /**
282
- * Calculate height from width and aspect ratio
283
- */
284
- export function calculateHeightFromAspectRatio(
285
- width: number,
286
- aspectRatio: number
287
- ): number {
288
- return Math.round(width / aspectRatio);
289
- }
290
-
291
- /**
292
- * Calculate width from height and aspect ratio
293
- */
294
- export function calculateWidthFromAspectRatio(
295
- height: number,
296
- aspectRatio: number
297
- ): number {
298
- return Math.round(height * aspectRatio);
299
- }
300
-
301
- /**
302
- * Memory & Performance Calculations
303
- */
304
-
305
- /**
306
- * Calculate estimated memory usage for image
307
- */
308
- export function calculateImageMemoryUsage(
309
- width: number,
310
- height: number,
311
- bytesPerPixel: number = 4 // RGBA
312
- ): number {
313
- return width * height * bytesPerPixel;
314
- }
315
-
316
- /**
317
- * Calculate estimated memory usage in MB
318
- */
319
- export function calculateMemoryMB(bytes: number): number {
320
- return bytes / (1024 * 1024);
321
- }
322
-
323
- /**
324
- * Calculate safe batch size for processing
325
- */
326
- export function calculateSafeBatchSize(
327
- availableMemoryMB: number,
328
- itemSizeMB: number,
329
- safetyFactor: number = 0.7
330
- ): number {
331
- const safeMemory = availableMemoryMB * safetyFactor;
332
- return Math.max(1, Math.floor(safeMemory / itemSizeMB));
333
- }
334
-
335
- /**
336
- * Utility Functions
337
- */
338
-
339
- /**
340
- * Clamp value between min and max
341
- */
342
- export function clamp(value: number, min: number, max: number): number {
343
- return Math.max(min, Math.min(max, value));
344
- }
345
-
346
- /**
347
- * Linear interpolation between two values
348
- */
349
- export function lerp(start: number, end: number, progress: number): number {
350
- return start + (end - start) * clamp(progress, 0, 1);
351
- }
352
-
353
- /**
354
- * Map value from one range to another
355
- */
356
- export function mapRange(
357
- value: number,
358
- inMin: number,
359
- inMax: number,
360
- outMin: number,
361
- outMax: number
362
- ): number {
363
- const inRange = inMax - inMin;
364
- const outRange = outMax - outMin;
365
- return outMin + ((value - inMin) / inRange) * outRange;
366
- }