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

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 (171) hide show
  1. package/package.json +3 -3
  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/domain/interfaces/index.ts +3 -0
  7. package/src/domains/background/infrastructure/services/job-poller-index.ts +7 -0
  8. package/src/domains/background/infrastructure/services/job-poller-utils.ts +127 -0
  9. package/src/domains/background/infrastructure/services/job-poller.service.ts +85 -140
  10. package/src/domains/background/infrastructure/utils/polling-interval.util.ts +1 -1
  11. package/src/domains/background/presentation/hooks/use-background-generation.ts +1 -1
  12. package/src/domains/content-moderation/index.ts +7 -13
  13. package/src/domains/content-moderation/infrastructure/services/content-moderation.service.ts +1 -1
  14. package/src/domains/content-moderation/infrastructure/services/moderators/image.moderator.ts +34 -8
  15. package/src/domains/content-moderation/infrastructure/services/moderators/text.moderator.ts +15 -4
  16. package/src/domains/content-moderation/infrastructure/services/moderators/video.moderator.ts +34 -8
  17. package/src/domains/content-moderation/infrastructure/services/moderators/voice.moderator.ts +19 -8
  18. package/src/domains/content-moderation/infrastructure/services/pattern-matcher.service.ts +1 -2
  19. package/src/domains/creations/domain/types/creation-categories.constants.ts +57 -0
  20. package/src/domains/creations/domain/types/creation-categories.helpers.ts +67 -0
  21. package/src/domains/creations/domain/types/creation-categories.ts +7 -114
  22. package/src/domains/creations/domain/utils/creation-display.util.ts +1 -1
  23. package/src/domains/creations/domain/utils/status-helpers.ts +1 -1
  24. package/src/domains/creations/presentation/hooks/creation-validators.ts +31 -29
  25. package/src/domains/creations/presentation/hooks/job-poller-index.ts +10 -0
  26. package/src/domains/creations/presentation/hooks/job-poller-utils.filters.ts +34 -0
  27. package/src/domains/creations/presentation/hooks/job-poller-utils.logger.ts +76 -0
  28. package/src/domains/creations/presentation/hooks/job-poller-utils.stale-handlers.ts +52 -0
  29. package/src/domains/creations/presentation/hooks/job-poller-utils.ts +8 -0
  30. package/src/domains/creations/presentation/hooks/useCreations.ts +1 -1
  31. package/src/domains/creations/presentation/hooks/useProcessingJobsPoller.ts +18 -235
  32. package/src/domains/creations/presentation/screens/CreationsGalleryScreen.tsx +1 -2
  33. package/src/domains/creations/presentation-exports.ts +2 -2
  34. package/src/domains/face-detection/domain/entities/FaceDetection.ts +4 -3
  35. package/src/domains/face-detection/presentation/hooks/useFaceDetection.ts +24 -21
  36. package/src/domains/generation/infrastructure/appearance-analysis/index.ts +5 -0
  37. package/src/domains/generation/infrastructure/couple-generation-builder/builder-couple-preparation.ts +58 -0
  38. package/src/domains/generation/infrastructure/couple-generation-builder/builder-couple-prompt.ts +69 -0
  39. package/src/domains/generation/infrastructure/couple-generation-builder/builder-couple-resolution.ts +77 -0
  40. package/src/domains/generation/infrastructure/couple-generation-builder/builder-couple.ts +54 -0
  41. package/src/domains/generation/infrastructure/couple-generation-builder/builder-index.ts +8 -0
  42. package/src/domains/generation/infrastructure/couple-generation-builder/builder-scenario.ts +112 -0
  43. package/src/domains/generation/infrastructure/couple-generation-builder/builder.ts +7 -0
  44. package/src/domains/generation/infrastructure/couple-generation-builder/index.ts +20 -0
  45. package/src/domains/generation/infrastructure/couple-generation-builder/types.ts +44 -0
  46. package/src/domains/generation/infrastructure/couple-generation-builder/utils/builder-end-logger.ts +18 -0
  47. package/src/domains/generation/infrastructure/couple-generation-builder/utils/builder-start-logger.ts +57 -0
  48. package/src/domains/generation/infrastructure/couple-generation-builder/utils/builder-step-logger.ts +106 -0
  49. package/src/domains/generation/infrastructure/couple-generation-builder/utils/index.ts +8 -0
  50. package/src/domains/generation/infrastructure/couple-generation-builder/utils/types.ts +49 -0
  51. package/src/domains/generation/infrastructure/couple-generation-builder/utils.ts +8 -0
  52. package/src/domains/generation/infrastructure/flow/flow-store-actions.ts +105 -0
  53. package/src/domains/generation/infrastructure/flow/flow-store-initial-state.ts +26 -0
  54. package/src/domains/generation/infrastructure/flow/useFlowStore.ts +4 -116
  55. package/src/domains/generation/presentation/useAIGeneration.hook.ts +1 -1
  56. package/src/domains/generation/wizard/infrastructure/strategies/image-generation-strategy-index.ts +7 -0
  57. package/src/domains/generation/wizard/infrastructure/strategies/image-generation.executor.ts +2 -12
  58. package/src/domains/generation/wizard/infrastructure/strategies/image-generation.executor.types.ts +11 -0
  59. package/src/domains/generation/wizard/infrastructure/strategies/image-generation.executor.utils.ts +12 -0
  60. package/src/domains/generation/wizard/infrastructure/strategies/image-generation.strategy.ts +1 -220
  61. package/src/domains/generation/wizard/infrastructure/strategies/image-input-builder.ts +66 -0
  62. package/src/domains/generation/wizard/infrastructure/strategies/image-input-extraction.ts +88 -0
  63. package/src/domains/generation/wizard/infrastructure/strategies/image-input-prompt-builder.ts +74 -0
  64. package/src/domains/generation/wizard/infrastructure/strategies/image-input-style-enhancements.ts +35 -0
  65. package/src/domains/generation/wizard/infrastructure/strategies/image-strategy-factory.ts +41 -0
  66. package/src/domains/generation/wizard/infrastructure/strategies/video-generation-executor-index.ts +10 -0
  67. package/src/domains/generation/wizard/infrastructure/strategies/video-generation-executor.ts +76 -0
  68. package/src/domains/generation/wizard/infrastructure/strategies/video-generation-input-builder.ts +46 -0
  69. package/src/domains/generation/wizard/infrastructure/strategies/video-generation-result-types.ts +17 -0
  70. package/src/domains/generation/wizard/infrastructure/strategies/video-generation-submission.ts +61 -0
  71. package/src/domains/generation/wizard/infrastructure/strategies/video-generation.audio-extractor.ts +27 -0
  72. package/src/domains/generation/wizard/infrastructure/strategies/video-generation.executor.ts +2 -176
  73. package/src/domains/generation/wizard/infrastructure/strategies/video-generation.input-builder.ts +90 -0
  74. package/src/domains/generation/wizard/infrastructure/strategies/video-generation.strategy.ts +3 -108
  75. package/src/domains/generation/wizard/infrastructure/strategies/video-generation.types.ts +0 -130
  76. package/src/domains/generation/wizard/infrastructure/strategies/video-generation.validation.ts +136 -0
  77. package/src/domains/generation/wizard/presentation/hooks/photo-upload/index.ts +40 -0
  78. package/src/domains/generation/wizard/presentation/hooks/photo-upload/types.ts +37 -0
  79. package/src/domains/generation/wizard/presentation/hooks/photo-upload/usePhotoUploadStateLogic.ts +142 -0
  80. package/src/domains/generation/wizard/presentation/hooks/use-video-queue-utils.ts +102 -0
  81. package/src/domains/generation/wizard/presentation/hooks/usePhotoBlockingGeneration.handlers.ts +97 -0
  82. package/src/domains/generation/wizard/presentation/hooks/usePhotoBlockingGeneration.saver.ts +54 -0
  83. package/src/domains/generation/wizard/presentation/hooks/usePhotoBlockingGeneration.ts +22 -87
  84. package/src/domains/generation/wizard/presentation/hooks/usePhotoUploadState.ts +8 -177
  85. package/src/domains/generation/wizard/presentation/hooks/useVideoQueueGeneration.ts +1 -295
  86. package/src/domains/generation/wizard/presentation/hooks/useWizardGeneration.ts +1 -1
  87. package/src/domains/generation/wizard/presentation/hooks/video-queue/index.ts +77 -0
  88. package/src/domains/generation/wizard/presentation/hooks/video-queue/use-video-queue-utils.ts +123 -0
  89. package/src/domains/generation/wizard/presentation/hooks/video-queue/useVideoQueueGenerationCallbacks.ts +119 -0
  90. package/src/domains/generation/wizard/presentation/hooks/video-queue/useVideoQueueGenerationPolling.ts +75 -0
  91. package/src/domains/generation/wizard/presentation/hooks/video-queue/useVideoQueueGenerationRefs.ts +65 -0
  92. package/src/domains/generation/wizard/presentation/hooks/video-queue/useVideoQueueGenerationStart.ts +123 -0
  93. package/src/domains/generation/wizard/presentation/hooks/video-queue-index.ts +9 -0
  94. package/src/domains/image-to-video/domain/types/image-to-video-state.types.ts +11 -4
  95. package/src/domains/text-to-image/domain/constants/index.ts +5 -6
  96. package/src/domains/text-to-image/domain/types/text-to-image.types.ts +43 -22
  97. package/src/domains/text-to-video/domain/types/request.types.ts +32 -9
  98. package/src/domains/text-to-video/domain/types/state.types.ts +22 -22
  99. package/src/domains/text-to-video/presentation/hooks/useTextToVideoForm.handlers.ts +44 -0
  100. package/src/domains/text-to-video/presentation/hooks/useTextToVideoForm.ts +5 -51
  101. package/src/domains/text-to-video/presentation/hooks/useTextToVideoForm.types.ts +33 -0
  102. package/src/exports/features.ts +1 -1
  103. package/src/infrastructure/services/generation-orchestrator.service.ts +2 -2
  104. package/src/infrastructure/utils/couple-input-context.ts +13 -0
  105. package/src/infrastructure/utils/couple-input-index.ts +9 -0
  106. package/src/infrastructure/utils/couple-input-photorealistic.ts +40 -0
  107. package/src/infrastructure/utils/couple-input-refiner.ts +101 -0
  108. package/src/infrastructure/utils/couple-input-resolver.ts +71 -0
  109. package/src/infrastructure/utils/couple-input-types.ts +11 -0
  110. package/src/infrastructure/utils/couple-input.util.ts +3 -176
  111. package/src/infrastructure/utils/photo-generation/photo-preparation.util.ts +1 -1
  112. package/src/infrastructure/validation/base-validator.ts +3 -26
  113. package/src/infrastructure/validation/base-validator.types.ts +32 -0
  114. package/src/presentation/hooks/generation/index.ts +1 -1
  115. package/src/presentation/hooks/generation/orchestrator-abort-logs.ts +48 -0
  116. package/src/presentation/hooks/generation/orchestrator-execution-logs.ts +67 -0
  117. package/src/presentation/hooks/generation/orchestrator-index.ts +14 -0
  118. package/src/presentation/hooks/generation/orchestrator-start-logs.ts +65 -0
  119. package/src/presentation/hooks/generation/orchestrator-state-utils.ts +17 -0
  120. package/src/presentation/hooks/generation/orchestrator-types.ts +55 -0
  121. package/src/presentation/hooks/generation/orchestrator-utils-index.ts +29 -0
  122. package/src/presentation/hooks/generation/orchestrator-utils.ts +25 -0
  123. package/src/presentation/hooks/generation/useDualImageGeneration.ts +1 -1
  124. package/src/presentation/hooks/generation/useImageGeneration.ts +1 -1
  125. package/src/presentation/hooks/generation/useVideoGeneration.ts +1 -1
  126. package/src/shared/hooks/factories/generation-hook-index.ts +12 -0
  127. package/src/shared/hooks/factories/generation-hook-types.ts +47 -0
  128. package/src/shared/hooks/factories/generation-hook-utils.ts +94 -0
  129. package/src/shared/hooks/factories/index.ts +1 -1
  130. package/src/shared/index.ts +1 -1
  131. package/src/shared/utils/calculations/aspect-ratio-calculations.ts +30 -0
  132. package/src/shared/utils/calculations/base64-calculations.ts +26 -0
  133. package/src/shared/utils/calculations/confidence-calculations.ts +21 -0
  134. package/src/shared/utils/calculations/cost-calculations-index.ts +43 -0
  135. package/src/shared/utils/calculations/cost-calculations.ts +25 -0
  136. package/src/shared/utils/calculations/credit-calculations.ts +37 -0
  137. package/src/shared/utils/calculations/index.ts +46 -0
  138. package/src/shared/utils/calculations/math-utilities.ts +32 -0
  139. package/src/shared/utils/calculations/memory-calculations.ts +33 -0
  140. package/src/shared/utils/calculations/pagination-calculations.ts +38 -0
  141. package/src/shared/utils/calculations/percentage-calculations.ts +33 -0
  142. package/src/shared/utils/calculations/time-calculations.ts +99 -0
  143. package/src/shared/utils/credit.ts +1 -1
  144. package/src/shared-kernel/application/hooks/index.ts +8 -0
  145. package/src/shared-kernel/application/hooks/use-feature-state.ts +106 -0
  146. package/src/shared-kernel/application/hooks/use-generation-handler.ts +110 -0
  147. package/src/shared-kernel/base-types/base-callbacks.types.ts +73 -0
  148. package/src/shared-kernel/base-types/base-feature-state.types.ts +77 -0
  149. package/src/shared-kernel/base-types/base-generation.types.ts +69 -0
  150. package/src/shared-kernel/base-types/index.ts +30 -0
  151. package/src/shared-kernel/domain/base-generation-strategy.ts +146 -0
  152. package/src/shared-kernel/domain/index.ts +7 -0
  153. package/src/shared-kernel/index.ts +17 -0
  154. package/src/shared-kernel/infrastructure/validation/common-validators.ts +126 -0
  155. package/src/shared-kernel/infrastructure/validation/common-validators.types.ts +33 -0
  156. package/src/shared-kernel/infrastructure/validation/error-handler.ts +52 -0
  157. package/src/shared-kernel/infrastructure/validation/error-handler.types.ts +38 -0
  158. package/src/shared-kernel/infrastructure/validation/error-handler.utils.ts +79 -0
  159. package/src/shared-kernel/infrastructure/validation/index.ts +70 -0
  160. package/src/domains/content-moderation/infrastructure/services/index.ts +0 -8
  161. package/src/domains/creations/domain/constants/index.ts +0 -12
  162. package/src/domains/creations/domain/utils/index.ts +0 -12
  163. package/src/domains/generation/infrastructure/couple-generation-builder.ts +0 -374
  164. package/src/domains/image-to-video/domain/index.ts +0 -2
  165. package/src/domains/image-to-video/infrastructure/index.ts +0 -1
  166. package/src/domains/image-to-video/presentation/index.ts +0 -5
  167. package/src/domains/text-to-video/domain/index.ts +0 -1
  168. package/src/domains/text-to-video/presentation/index.ts +0 -7
  169. package/src/presentation/hooks/generation/orchestrator.ts +0 -276
  170. package/src/shared/hooks/factories/createGenerationHook.ts +0 -253
  171. package/src/shared/utils/calculations.util.ts +0 -366
@@ -0,0 +1,43 @@
1
+ /**
2
+ * General Cost & Value Calculations
3
+ */
4
+
5
+ export {
6
+ calculatePercentage,
7
+ calculateProgress,
8
+ calculateRemaining,
9
+ } from "./percentage-calculations";
10
+
11
+ export {
12
+ calculateFilteredCount,
13
+ calculatePaginationSlice,
14
+ calculateHasMore,
15
+ } from "./pagination-calculations";
16
+
17
+ export {
18
+ calculateBase64Size,
19
+ calculateBase64SizeMB,
20
+ isBase64SizeWithinLimit,
21
+ } from "./base64-calculations";
22
+
23
+ export {
24
+ calculateConfidenceScore,
25
+ } from "./confidence-calculations";
26
+
27
+ export {
28
+ calculateAspectRatio,
29
+ calculateHeightFromAspectRatio,
30
+ calculateWidthFromAspectRatio,
31
+ } from "./aspect-ratio-calculations";
32
+
33
+ export {
34
+ calculateImageMemoryUsage,
35
+ calculateMemoryMB,
36
+ calculateSafeBatchSize,
37
+ } from "./memory-calculations";
38
+
39
+ export {
40
+ clamp,
41
+ lerp,
42
+ mapRange,
43
+ } from "./math-utilities";
@@ -0,0 +1,25 @@
1
+ /**
2
+ * General Cost & Value Calculations
3
+ */
4
+
5
+ export {
6
+ calculatePercentage,
7
+ calculateProgress,
8
+ calculateRemaining,
9
+ calculateFilteredCount,
10
+ calculatePaginationSlice,
11
+ calculateHasMore,
12
+ calculateBase64Size,
13
+ calculateBase64SizeMB,
14
+ isBase64SizeWithinLimit,
15
+ calculateConfidenceScore,
16
+ calculateAspectRatio,
17
+ calculateHeightFromAspectRatio,
18
+ calculateWidthFromAspectRatio,
19
+ calculateImageMemoryUsage,
20
+ calculateMemoryMB,
21
+ calculateSafeBatchSize,
22
+ clamp,
23
+ lerp,
24
+ mapRange,
25
+ } from "./cost-calculations-index";
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Credit & Cost Calculations
3
+ */
4
+
5
+ /**
6
+ * Calculate cost in credits based on duration and resolution
7
+ */
8
+ export function calculateCredits(
9
+ durationSeconds: number,
10
+ resolutionMultiplier: number = 1,
11
+ baseCost: number = 1
12
+ ): number {
13
+ return Math.ceil((durationSeconds / 60) * resolutionMultiplier * baseCost);
14
+ }
15
+
16
+ /**
17
+ * Calculate resolution multiplier for credits
18
+ */
19
+ export function calculateResolutionMultiplier(width: number, height: number): number {
20
+ const totalPixels = width * height;
21
+ const basePixels = 720 * 1280; // HD baseline
22
+
23
+ if (totalPixels <= basePixels) return 1;
24
+ if (totalPixels <= basePixels * 2) return 1.5;
25
+ if (totalPixels <= basePixels * 4) return 2;
26
+ return 3;
27
+ }
28
+
29
+ /**
30
+ * Calculate cost to credits conversion
31
+ */
32
+ export function convertCostToCredits(
33
+ cost: number,
34
+ creditsPerDollar: number = 100
35
+ ): number {
36
+ return Math.ceil(cost * creditsPerDollar);
37
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Calculation Utilities
3
+ * Centralized calculation operations for better performance and maintainability
4
+ */
5
+
6
+ // Credit & Cost Calculations
7
+ export {
8
+ calculateCredits,
9
+ calculateResolutionMultiplier,
10
+ convertCostToCredits,
11
+ } from "./credit-calculations";
12
+
13
+ // Time & Duration Calculations
14
+ export {
15
+ calculateAgeMs,
16
+ calculateAgeSeconds,
17
+ calculateAgeMinutes,
18
+ isOlderThan,
19
+ calculateDurationMs,
20
+ formatDuration,
21
+ calculatePollingInterval,
22
+ calculateEstimatedPollingTime,
23
+ } from "./time-calculations";
24
+
25
+ // General Cost & Value Calculations
26
+ export {
27
+ calculatePercentage,
28
+ calculateProgress,
29
+ calculateRemaining,
30
+ calculateFilteredCount,
31
+ calculatePaginationSlice,
32
+ calculateHasMore,
33
+ calculateBase64Size,
34
+ calculateBase64SizeMB,
35
+ isBase64SizeWithinLimit,
36
+ calculateConfidenceScore,
37
+ calculateAspectRatio,
38
+ calculateHeightFromAspectRatio,
39
+ calculateWidthFromAspectRatio,
40
+ calculateImageMemoryUsage,
41
+ calculateMemoryMB,
42
+ calculateSafeBatchSize,
43
+ clamp,
44
+ lerp,
45
+ mapRange,
46
+ } from "./cost-calculations";
@@ -0,0 +1,32 @@
1
+ /**
2
+ * General Math Utilities
3
+ */
4
+
5
+ /**
6
+ * Clamp value between min and max
7
+ */
8
+ export function clamp(value: number, min: number, max: number): number {
9
+ return Math.max(min, Math.min(max, value));
10
+ }
11
+
12
+ /**
13
+ * Linear interpolation between two values
14
+ */
15
+ export function lerp(start: number, end: number, progress: number): number {
16
+ return start + (end - start) * clamp(progress, 0, 1);
17
+ }
18
+
19
+ /**
20
+ * Map value from one range to another
21
+ */
22
+ export function mapRange(
23
+ value: number,
24
+ inMin: number,
25
+ inMax: number,
26
+ outMin: number,
27
+ outMax: number
28
+ ): number {
29
+ const inRange = inMax - inMin;
30
+ const outRange = outMax - outMin;
31
+ return outMin + ((value - inMin) / inRange) * outRange;
32
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Memory Usage Calculations
3
+ */
4
+
5
+ /**
6
+ * Calculate estimated memory usage for image
7
+ */
8
+ export function calculateImageMemoryUsage(
9
+ width: number,
10
+ height: number,
11
+ bytesPerPixel: number = 4 // RGBA
12
+ ): number {
13
+ return width * height * bytesPerPixel;
14
+ }
15
+
16
+ /**
17
+ * Calculate estimated memory usage in MB
18
+ */
19
+ export function calculateMemoryMB(bytes: number): number {
20
+ return bytes / (1024 * 1024);
21
+ }
22
+
23
+ /**
24
+ * Calculate safe batch size for processing
25
+ */
26
+ export function calculateSafeBatchSize(
27
+ availableMemoryMB: number,
28
+ itemSizeMB: number,
29
+ safetyFactor: number = 0.7
30
+ ): number {
31
+ const safeMemory = availableMemoryMB * safetyFactor;
32
+ return Math.max(1, Math.floor(safeMemory / itemSizeMB));
33
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Pagination Calculations
3
+ */
4
+
5
+ /**
6
+ * Calculate filtered count with predicate
7
+ */
8
+ export function calculateFilteredCount<T>(
9
+ items: readonly T[],
10
+ predicate: (item: T) => boolean
11
+ ): number {
12
+ return items.reduce((count, item) => (predicate(item) ? count + 1 : count), 0);
13
+ }
14
+
15
+ /**
16
+ * Calculate pagination slice
17
+ */
18
+ export function calculatePaginationSlice(
19
+ totalItems: number,
20
+ page: number,
21
+ pageSize: number
22
+ ): { start: number; end: number; count: number } {
23
+ const start = page * pageSize;
24
+ const end = Math.min(start + pageSize, totalItems);
25
+ const count = end - start;
26
+ return { start, end, count };
27
+ }
28
+
29
+ /**
30
+ * Calculate if more items exist for pagination
31
+ */
32
+ export function calculateHasMore(
33
+ currentCount: number,
34
+ currentPage: number,
35
+ pageSize: number
36
+ ): boolean {
37
+ return currentCount >= currentPage * pageSize;
38
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Percentage & Progress Calculations
3
+ */
4
+
5
+ /**
6
+ * Calculate percentage with bounds checking (0-100)
7
+ */
8
+ export function calculatePercentage(value: number, total: number): number {
9
+ if (total === 0) return 0;
10
+ const percentage = (value / total) * 100;
11
+ return Math.max(0, Math.min(100, percentage));
12
+ }
13
+
14
+ /**
15
+ * Calculate progress with min/max bounds
16
+ */
17
+ export function calculateProgress(
18
+ current: number,
19
+ total: number,
20
+ min: number = 0,
21
+ max: number = 100
22
+ ): number {
23
+ if (total === 0) return min;
24
+ const percentage = (current / total) * (max - min) + min;
25
+ return Math.max(min, Math.min(max, percentage));
26
+ }
27
+
28
+ /**
29
+ * Calculate remaining percentage
30
+ */
31
+ export function calculateRemaining(current: number, total: number): number {
32
+ return Math.max(0, total - current);
33
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Time & Duration Calculations
3
+ */
4
+
5
+ /**
6
+ * Calculate age in milliseconds from a timestamp
7
+ */
8
+ export function calculateAgeMs(timestamp: Date | number): number {
9
+ const time = typeof timestamp === "number" ? timestamp : timestamp.getTime();
10
+ return Date.now() - time;
11
+ }
12
+
13
+ /**
14
+ * Calculate age in seconds from a timestamp
15
+ */
16
+ export function calculateAgeSeconds(timestamp: Date | number): number {
17
+ return Math.floor(calculateAgeMs(timestamp) / 1000);
18
+ }
19
+
20
+ /**
21
+ * Calculate age in minutes from a timestamp
22
+ */
23
+ export function calculateAgeMinutes(timestamp: Date | number): number {
24
+ return Math.floor(calculateAgeSeconds(timestamp) / 60);
25
+ }
26
+
27
+ /**
28
+ * Check if timestamp is older than specified milliseconds
29
+ */
30
+ export function isOlderThan(timestamp: Date | number, maxAgeMs: number): boolean {
31
+ return calculateAgeMs(timestamp) > maxAgeMs;
32
+ }
33
+
34
+ /**
35
+ * Calculate duration between two timestamps in milliseconds
36
+ */
37
+ export function calculateDurationMs(
38
+ startTime: Date | number,
39
+ endTime: Date | number = Date.now()
40
+ ): number {
41
+ const start = typeof startTime === "number" ? startTime : startTime.getTime();
42
+ const end = typeof endTime === "number" ? endTime : endTime.getTime();
43
+ return end - start;
44
+ }
45
+
46
+ /**
47
+ * Format duration in milliseconds to human-readable string
48
+ */
49
+ export function formatDuration(ms: number): string {
50
+ const seconds = Math.floor(ms / 1000);
51
+ const minutes = Math.floor(seconds / 60);
52
+ const hours = Math.floor(minutes / 60);
53
+
54
+ if (hours > 0) {
55
+ return `${hours}h ${minutes % 60}m`;
56
+ }
57
+ if (minutes > 0) {
58
+ return `${minutes}m ${seconds % 60}s`;
59
+ }
60
+ return `${seconds}s`;
61
+ }
62
+
63
+ /**
64
+ * Calculate polling interval with exponential backoff
65
+ */
66
+ export function calculatePollingInterval(options: {
67
+ attempt: number;
68
+ initialIntervalMs: number;
69
+ maxIntervalMs: number;
70
+ backoffMultiplier: number;
71
+ }): number {
72
+ const { attempt, initialIntervalMs, maxIntervalMs, backoffMultiplier } = options;
73
+
74
+ if (attempt === 0) {
75
+ return 0;
76
+ }
77
+
78
+ const interval = initialIntervalMs * Math.pow(backoffMultiplier, attempt - 1);
79
+ return Math.min(interval, maxIntervalMs);
80
+ }
81
+
82
+ /**
83
+ * Calculate estimated total polling time
84
+ */
85
+ export function calculateEstimatedPollingTime(options: {
86
+ maxAttempts: number;
87
+ initialIntervalMs: number;
88
+ maxIntervalMs: number;
89
+ backoffMultiplier: number;
90
+ }): number {
91
+ let total = 0;
92
+ for (let attempt = 1; attempt < options.maxAttempts; attempt++) {
93
+ total += calculatePollingInterval({ ...options, attempt });
94
+ if (total >= options.maxIntervalMs * options.maxAttempts) {
95
+ break;
96
+ }
97
+ }
98
+ return total;
99
+ }
@@ -3,7 +3,7 @@
3
3
  * Provides consistent credit calculation operations
4
4
  */
5
5
 
6
- import { calculateCredits as calculateCreditsFromDuration } from "./calculations.util";
6
+ import { calculateCredits as calculateCreditsFromDuration } from "./calculations";
7
7
 
8
8
  /**
9
9
  * Validates if a value is a valid credit amount
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Shared application hooks
3
+ * Exports all shared hooks for use across domains
4
+ */
5
+
6
+ export { useFeatureState } from './use-feature-state';
7
+ export type { GenerationHandlerConfig } from './use-generation-handler';
8
+ export { useGenerationHandler } from './use-generation-handler';
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Shared hook for managing feature state
3
+ * Eliminates duplicate state management across domains
4
+ */
5
+
6
+ import { useState, useCallback, useReducer } from 'react';
7
+ import type {
8
+ BaseFeatureState,
9
+ FeatureStateAction,
10
+ } from '../../base-types';
11
+
12
+ /**
13
+ * Hook for managing feature state with consistent patterns
14
+ * Reduces state management duplication across domains
15
+ */
16
+ export function useFeatureState<TOutput = string>() {
17
+ const [state, dispatch] = useReducer(
18
+ (currentState: BaseFeatureState<TOutput>, action: FeatureStateAction<TOutput>) => {
19
+ switch (action.type) {
20
+ case 'START':
21
+ return {
22
+ ...currentState,
23
+ isProcessing: true,
24
+ progress: 0,
25
+ error: null,
26
+ startedAt: Date.now(),
27
+ jobId: action.jobId,
28
+ } as BaseFeatureState<TOutput> & { startedAt: number; jobId?: string };
29
+
30
+ case 'PROGRESS':
31
+ return {
32
+ ...currentState,
33
+ progress: action.progress,
34
+ progressInfo: {
35
+ progress: action.progress,
36
+ status: action.status,
37
+ },
38
+ };
39
+
40
+ case 'SUCCESS':
41
+ return {
42
+ ...currentState,
43
+ isProcessing: false,
44
+ progress: 1,
45
+ output: action.output,
46
+ completedAt: Date.now(),
47
+ } as BaseFeatureState<TOutput> & { completedAt: number };
48
+
49
+ case 'ERROR':
50
+ return {
51
+ ...currentState,
52
+ isProcessing: false,
53
+ error: action.error,
54
+ };
55
+
56
+ case 'RESET':
57
+ return {
58
+ isProcessing: false,
59
+ progress: 0,
60
+ error: null,
61
+ output: null,
62
+ };
63
+
64
+ default:
65
+ return currentState;
66
+ }
67
+ },
68
+ useState<BaseFeatureState<TOutput>>(() => ({
69
+ isProcessing: false,
70
+ progress: 0,
71
+ error: null,
72
+ output: null,
73
+ }))[0]
74
+ );
75
+
76
+ const startProcessing = useCallback((jobId?: string) => {
77
+ dispatch({ type: 'START', jobId });
78
+ }, []);
79
+
80
+ const updateProgress = useCallback((progress: number, status?: string) => {
81
+ dispatch({ type: 'PROGRESS', progress, status });
82
+ }, []);
83
+
84
+ const setSuccess = useCallback((output: TOutput, metadata?: Record<string, unknown>) => {
85
+ dispatch({ type: 'SUCCESS', output, metadata });
86
+ }, []);
87
+
88
+ const setError = useCallback((error: string) => {
89
+ dispatch({ type: 'ERROR', error });
90
+ }, []);
91
+
92
+ const reset = useCallback(() => {
93
+ dispatch({ type: 'RESET' });
94
+ }, []);
95
+
96
+ return {
97
+ state,
98
+ actions: {
99
+ startProcessing,
100
+ updateProgress,
101
+ setSuccess,
102
+ setError,
103
+ reset,
104
+ },
105
+ };
106
+ }
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Shared hook for handling generation operations
3
+ * Eliminates duplicate generation logic across domains
4
+ */
5
+
6
+ import { useCallback } from 'react';
7
+ import type {
8
+ BaseGenerationCallbacks,
9
+ BaseGenerationResult,
10
+ GenerationProgress,
11
+ } from '../../base-types';
12
+
13
+ /**
14
+ * Configuration for generation handler
15
+ */
16
+ export interface GenerationHandlerConfig<TInput, TOutput> {
17
+ /** Function to execute the generation */
18
+ executeGeneration: (input: TInput) => Promise<BaseGenerationResult<TOutput>>;
19
+ /** Optional validation function */
20
+ validateInput?: (input: TInput) => boolean | Promise<boolean>;
21
+ /** Callbacks for generation lifecycle */
22
+ callbacks?: BaseGenerationCallbacks<TOutput>;
23
+ }
24
+
25
+ /**
26
+ * Hook for handling generation operations with consistent patterns
27
+ * Reduces generation logic duplication across domains
28
+ */
29
+ export function useGenerationHandler<TInput, TOutput = string>(
30
+ config: GenerationHandlerConfig<TInput, TOutput>
31
+ ) {
32
+ const { executeGeneration, validateInput, callbacks } = config;
33
+
34
+ const handleGeneration = useCallback(
35
+ async (input: TInput): Promise<BaseGenerationResult<TOutput>> => {
36
+ try {
37
+ // Call onCreditCheck if provided
38
+ if (callbacks?.onCreditCheck) {
39
+ const hasCredits = await callbacks.onCreditCheck();
40
+ if (!hasCredits) {
41
+ callbacks.onShowPaywall?.();
42
+ return {
43
+ success: false,
44
+ error: 'Insufficient credits',
45
+ requestId: '',
46
+ };
47
+ }
48
+ }
49
+
50
+ // Validate input if validator provided
51
+ if (validateInput) {
52
+ const isValid = await validateInput(input);
53
+ if (!isValid) {
54
+ const error = new Error('Invalid input');
55
+ callbacks?.onError?.(error);
56
+ return {
57
+ success: false,
58
+ error: error.message,
59
+ requestId: '',
60
+ };
61
+ }
62
+ }
63
+
64
+ // Call onStart callback
65
+ callbacks?.onStart?.();
66
+
67
+ // Execute generation
68
+ const result = await executeGeneration(input);
69
+
70
+ // Handle result
71
+ if (result.success) {
72
+ callbacks?.onSuccess?.(result);
73
+ callbacks?.onCreditsConsumed?.(1); // Default credit cost
74
+ } else {
75
+ const error = new Error(result.error || 'Generation failed');
76
+ callbacks?.onError?.(error);
77
+ }
78
+
79
+ // Call onComplete
80
+ callbacks?.onComplete?.();
81
+
82
+ return result;
83
+ } catch (error) {
84
+ const err = error instanceof Error ? error : new Error('Unknown error');
85
+ callbacks?.onError?.(err);
86
+ callbacks?.onComplete?.();
87
+
88
+ return {
89
+ success: false,
90
+ error: err.message,
91
+ requestId: '',
92
+ };
93
+ }
94
+ },
95
+ [executeGeneration, validateInput, callbacks]
96
+ );
97
+
98
+ const handleProgress = useCallback(
99
+ (progress: number, status?: string) => {
100
+ const progressInfo: GenerationProgress = { progress, status };
101
+ callbacks?.onProgress?.(progressInfo);
102
+ },
103
+ [callbacks]
104
+ );
105
+
106
+ return {
107
+ handleGeneration,
108
+ handleProgress,
109
+ };
110
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Base callback types for AI generation operations
3
+ * Shared across all generation domains
4
+ */
5
+
6
+ import type { BaseGenerationResult, GenerationProgress } from './base-generation.types';
7
+
8
+ /**
9
+ * Credit-related callbacks for premium features
10
+ */
11
+ export interface CreditCallbacks {
12
+ /** Called when credit check is needed before generation */
13
+ onCreditCheck?: () => Promise<boolean>;
14
+ /** Called when user needs to see paywall */
15
+ onShowPaywall?: () => void;
16
+ /** Called when credits are successfully consumed */
17
+ onCreditsConsumed?: (amount: number) => void;
18
+ }
19
+
20
+ /**
21
+ * Progress callbacks for long-running operations
22
+ */
23
+ export interface ProgressCallbacks {
24
+ /** Called when generation progress updates */
25
+ onProgress?: (progress: GenerationProgress) => void;
26
+ /** Called when operation starts */
27
+ onStart?: () => void;
28
+ /** Called when operation completes (success or failure) */
29
+ onComplete?: () => void;
30
+ }
31
+
32
+ /**
33
+ * Result callbacks for generation operations
34
+ */
35
+ export interface ResultCallbacks<TData = string> {
36
+ /** Called when generation succeeds */
37
+ onSuccess?: (result: BaseGenerationResult<TData>) => void;
38
+ /** Called when generation fails */
39
+ onError?: (error: Error) => void;
40
+ /** Called when generation is cancelled */
41
+ onCancel?: () => void;
42
+ }
43
+
44
+ /**
45
+ * Combined callbacks for generation operations
46
+ * Includes all callback types in a single interface
47
+ */
48
+ export interface BaseGenerationCallbacks<TData = string>
49
+ extends CreditCallbacks,
50
+ ProgressCallbacks,
51
+ ResultCallbacks<TData> {}
52
+
53
+ /**
54
+ * Validation callbacks for input validation
55
+ */
56
+ export interface ValidationCallbacks {
57
+ /** Called when validation fails */
58
+ onValidationFailed?: (errors: Record<string, string>) => void;
59
+ /** Called when input is invalid */
60
+ onInvalidInput?: (field: string, reason: string) => void;
61
+ }
62
+
63
+ /**
64
+ * Lifecycle callbacks for feature components
65
+ */
66
+ export interface LifecycleCallbacks {
67
+ /** Called when component mounts */
68
+ onMount?: () => void;
69
+ /** Called when component unmounts */
70
+ onUnmount?: () => void;
71
+ /** Called when component updates */
72
+ onUpdate?: (prevProps: unknown, nextProps: unknown) => void;
73
+ }