@umituz/react-native-ai-generation-content 1.65.11 → 1.66.0

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umituz/react-native-ai-generation-content",
3
- "version": "1.65.11",
3
+ "version": "1.66.0",
4
4
  "description": "Provider-agnostic AI generation orchestration for React Native with result preview components",
5
5
  "main": "src/index.ts",
6
6
  "types": "src/index.ts",
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Creation Display Utilities
3
+ * Single Responsibility: UI display helpers (icons, titles, text)
4
+ */
5
+
6
+ import type { CreationTypeId } from "../types";
7
+
8
+ /**
9
+ * Icon name type for design system
10
+ */
11
+ export type IconName = "image" | "film" | "mic" | "sparkles" | "color-palette" | "brush";
12
+
13
+ /**
14
+ * Get icon name for creation type
15
+ */
16
+ export function getTypeIcon(type: CreationTypeId): IconName {
17
+ switch (type) {
18
+ case "text-to-video":
19
+ case "image-to-video":
20
+ return "film";
21
+ case "style-transfer":
22
+ case "colorization":
23
+ return "color-palette";
24
+ case "ai-brush":
25
+ case "inpainting":
26
+ return "brush";
27
+ default:
28
+ return "image";
29
+ }
30
+ }
31
+
32
+ /**
33
+ * Get i18n key for creation type
34
+ */
35
+ export function getTypeTextKey(type: CreationTypeId): string {
36
+ return `creations.types.${type}`;
37
+ }
38
+
39
+ /**
40
+ * Get formatted type text (fallback)
41
+ */
42
+ export function getTypeText(type: CreationTypeId): string {
43
+ return type.split("-").map(word =>
44
+ word.charAt(0).toUpperCase() + word.slice(1)
45
+ ).join(" ");
46
+ }
47
+
48
+ /**
49
+ * Get creation title from prompt or type
50
+ */
51
+ export function getCreationTitle(
52
+ prompt?: string,
53
+ type?: CreationTypeId,
54
+ maxLength: number = 50
55
+ ): string {
56
+ if (prompt && prompt.length > 0) {
57
+ return prompt.length > maxLength
58
+ ? prompt.substring(0, maxLength) + "..."
59
+ : prompt;
60
+ }
61
+
62
+ if (type) {
63
+ return getTypeText(type);
64
+ }
65
+
66
+ return "Untitled Creation";
67
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Creation Format Utilities
3
+ * Single Responsibility: Text formatting
4
+ */
5
+
6
+ /**
7
+ * Truncate text with ellipsis
8
+ */
9
+ export function truncateText(text: string, maxLength: number): string {
10
+ if (text.length <= maxLength) return text;
11
+ return text.substring(0, maxLength - 3) + "...";
12
+ }
@@ -1,140 +1,12 @@
1
1
  /**
2
2
  * Creation Helpers
3
- * Utility functions for creation data manipulation
3
+ * Central export point for creation utility functions
4
+ * @deprecated Individual utilities split into focused modules for better maintainability
4
5
  */
5
6
 
6
- import { generateUUID } from "@umituz/react-native-design-system";
7
- import type { CreationTypeId } from "../types";
8
-
9
- /**
10
- * Generate a unique creation ID using UUID v4
11
- */
12
- export function generateCreationId(): string {
13
- return generateUUID();
14
- }
15
-
16
- /**
17
- * Icon name type for design system
18
- */
19
- export type IconName = "image" | "film" | "mic" | "sparkles" | "color-palette" | "brush";
20
-
21
- /**
22
- * Get icon name for creation type
23
- */
24
- export function getTypeIcon(type: CreationTypeId): IconName {
25
- switch (type) {
26
- case "text-to-video":
27
- case "image-to-video":
28
- return "film";
29
- case "style-transfer":
30
- case "colorization":
31
- return "color-palette";
32
- case "ai-brush":
33
- case "inpainting":
34
- return "brush";
35
- default:
36
- return "image";
37
- }
38
- }
39
-
40
- /**
41
- * Get i18n key for creation type
42
- */
43
- export function getTypeTextKey(type: CreationTypeId): string {
44
- return `creations.types.${type}`;
45
- }
46
-
47
- /**
48
- * Get formatted type text (fallback)
49
- */
50
- export function getTypeText(type: CreationTypeId): string {
51
- return type.split("-").map(word =>
52
- word.charAt(0).toUpperCase() + word.slice(1)
53
- ).join(" ");
54
- }
55
-
56
- /**
57
- * Get creation title from prompt or type
58
- */
59
- export function getCreationTitle(
60
- prompt?: string,
61
- type?: CreationTypeId,
62
- maxLength: number = 50
63
- ): string {
64
- if (prompt && prompt.length > 0) {
65
- return prompt.length > maxLength
66
- ? prompt.substring(0, maxLength) + "..."
67
- : prompt;
68
- }
69
-
70
- if (type) {
71
- return getTypeText(type);
72
- }
73
-
74
- return "Untitled Creation";
75
- }
76
-
77
- /**
78
- * Filter creations by search query (client-side)
79
- */
80
- export function filterBySearch<T extends { prompt?: string; type?: string; provider?: string }>(
81
- items: T[],
82
- searchQuery?: string,
83
- ): T[] {
84
- if (!searchQuery || searchQuery.trim().length === 0) {
85
- return items;
86
- }
87
-
88
- const query = searchQuery.toLowerCase().trim();
89
-
90
- return items.filter((item) =>
91
- item.prompt?.toLowerCase().includes(query) ||
92
- item.type?.toLowerCase().includes(query) ||
93
- item.provider?.toLowerCase().includes(query)
94
- );
95
- }
96
-
97
- /**
98
- * Sort creations by field
99
- */
100
- export function sortCreations<T extends Record<string, unknown>>(
101
- items: T[],
102
- field: keyof T,
103
- order: "asc" | "desc" = "desc"
104
- ): T[] {
105
- return [...items].sort((a, b) => {
106
- const aVal = a[field] as unknown;
107
- const bVal = b[field] as unknown;
108
-
109
- if (aVal === undefined && bVal === undefined) return 0;
110
- if (aVal === undefined) return 1;
111
- if (bVal === undefined) return -1;
112
-
113
- if (typeof aVal === "string" && typeof bVal === "string") {
114
- return order === "desc"
115
- ? bVal.localeCompare(aVal)
116
- : aVal.localeCompare(bVal);
117
- }
118
-
119
- if (typeof aVal === "number" && typeof bVal === "number") {
120
- return order === "desc" ? bVal - aVal : aVal - bVal;
121
- }
122
-
123
- // Handle Date objects
124
- if (aVal instanceof Date && bVal instanceof Date) {
125
- return order === "desc"
126
- ? bVal.getTime() - aVal.getTime()
127
- : aVal.getTime() - bVal.getTime();
128
- }
129
-
130
- return 0;
131
- });
132
- }
133
-
134
- /**
135
- * Truncate text with ellipsis
136
- */
137
- export function truncateText(text: string, maxLength: number): string {
138
- if (text.length <= maxLength) return text;
139
- return text.substring(0, maxLength - 3) + "...";
140
- }
7
+ // Re-export all utilities for backward compatibility
8
+ export * from "./creation-id.util";
9
+ export * from "./creation-display.util";
10
+ export * from "./creation-search.util";
11
+ export * from "./creation-sort.util";
12
+ export * from "./creation-format.util";
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Creation ID Utilities
3
+ * Single Responsibility: ID generation
4
+ */
5
+
6
+ import { generateUUID } from "@umituz/react-native-design-system";
7
+
8
+ /**
9
+ * Generate a unique creation ID using UUID v4
10
+ */
11
+ export function generateCreationId(): string {
12
+ return generateUUID();
13
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Creation Search Utilities
3
+ * Single Responsibility: Filtering and searching
4
+ */
5
+
6
+ /**
7
+ * Filter creations by search query (client-side)
8
+ */
9
+ export function filterBySearch<T extends { prompt?: string; type?: string; provider?: string }>(
10
+ items: T[],
11
+ searchQuery?: string,
12
+ ): T[] {
13
+ if (!searchQuery || searchQuery.trim().length === 0) {
14
+ return items;
15
+ }
16
+
17
+ const query = searchQuery.toLowerCase().trim();
18
+
19
+ return items.filter((item) =>
20
+ item.prompt?.toLowerCase().includes(query) ||
21
+ item.type?.toLowerCase().includes(query) ||
22
+ item.provider?.toLowerCase().includes(query)
23
+ );
24
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Creation Sort Utilities
3
+ * Single Responsibility: Sorting operations
4
+ */
5
+
6
+ /**
7
+ * Sort creations by field
8
+ */
9
+ export function sortCreations<T extends Record<string, unknown>>(
10
+ items: T[],
11
+ field: keyof T,
12
+ order: "asc" | "desc" = "desc"
13
+ ): T[] {
14
+ return [...items].sort((a, b) => {
15
+ const aVal = a[field] as unknown;
16
+ const bVal = b[field] as unknown;
17
+
18
+ if (aVal === undefined && bVal === undefined) return 0;
19
+ if (aVal === undefined) return 1;
20
+ if (bVal === undefined) return -1;
21
+
22
+ if (typeof aVal === "string" && typeof bVal === "string") {
23
+ return order === "desc"
24
+ ? bVal.localeCompare(aVal)
25
+ : aVal.localeCompare(bVal);
26
+ }
27
+
28
+ if (typeof aVal === "number" && typeof bVal === "number") {
29
+ return order === "desc" ? bVal - aVal : aVal - bVal;
30
+ }
31
+
32
+ // Handle Date objects
33
+ if (aVal instanceof Date && bVal instanceof Date) {
34
+ return order === "desc"
35
+ ? bVal.getTime() - aVal.getTime()
36
+ : aVal.getTime() - bVal.getTime();
37
+ }
38
+
39
+ return 0;
40
+ });
41
+ }
@@ -1,155 +1,53 @@
1
- import { getDocs, getDoc, query, orderBy, onSnapshot, where } from "firebase/firestore";
2
1
  import { type FirestorePathResolver } from "@umituz/react-native-firebase";
3
2
  import type { DocumentMapper } from "../../domain/value-objects/CreationsConfig";
4
- import type { Creation, CreationDocument } from "../../domain/entities/Creation";
3
+ import type { Creation } from "../../domain/entities/Creation";
5
4
  import type { CreationsSubscriptionCallback, UnsubscribeFunction } from "../../domain/repositories/ICreationsRepository";
6
- import { CREATION_FIELDS } from "../../domain/constants";
7
-
8
- declare const __DEV__: boolean;
5
+ import { CreationsQuery } from "./CreationsQuery";
6
+ import { CreationsSubscription } from "./CreationsSubscription";
9
7
 
10
8
  /**
11
- * Handles fetching creations from Firestore
12
- * Single Responsibility: Read operations
9
+ * CreationsFetcher
10
+ * Orchestrates read operations for creations
11
+ * Delegates to specialized classes for queries and subscriptions
12
+ *
13
+ * Architecture: Facade pattern
14
+ * - Query operations → CreationsQuery
15
+ * - Subscription operations → CreationsSubscription
13
16
  */
14
17
  export class CreationsFetcher {
18
+ private readonly query: CreationsQuery;
19
+ private readonly subscription: CreationsSubscription;
20
+
15
21
  constructor(
16
- private readonly pathResolver: FirestorePathResolver,
17
- private readonly documentMapper: DocumentMapper,
18
- ) { }
22
+ pathResolver: FirestorePathResolver,
23
+ documentMapper: DocumentMapper,
24
+ ) {
25
+ this.query = new CreationsQuery(pathResolver, documentMapper);
26
+ this.subscription = new CreationsSubscription(pathResolver, documentMapper);
27
+ }
19
28
 
29
+ /**
30
+ * Get all creations for a user
31
+ */
20
32
  async getAll(userId: string): Promise<Creation[]> {
21
- const userCollection = this.pathResolver.getUserCollection(userId);
22
- if (!userCollection) return [];
23
-
24
- try {
25
- // Optimized query: Server-side filtering for non-deleted items
26
- // Requires composite index: (deletedAt ASC, createdAt DESC)
27
- const q = query(
28
- userCollection,
29
- where(CREATION_FIELDS.DELETED_AT, "==", null),
30
- orderBy(CREATION_FIELDS.CREATED_AT, "desc")
31
- );
32
- const snapshot = await getDocs(q);
33
-
34
- // Map documents to domain entities
35
- // No client-side filtering needed - server already filtered deleted items
36
- const creations = snapshot.docs.map((docSnap) => {
37
- const data = docSnap.data() as CreationDocument;
38
- return this.documentMapper(docSnap.id, data);
39
- });
40
-
41
- if (__DEV__) {
42
- console.log("[CreationsFetcher] Fetched creations:", {
43
- count: creations.length,
44
- hasDeletedFilter: true,
45
- });
46
- }
47
-
48
- return creations;
49
- } catch (error) {
50
- if (__DEV__) {
51
- console.error("[CreationsFetcher] getAll() error:", error);
52
- }
53
- return [];
54
- }
33
+ return this.query.getAll(userId);
55
34
  }
56
35
 
36
+ /**
37
+ * Get a single creation by ID
38
+ */
57
39
  async getById(userId: string, id: string): Promise<Creation | null> {
58
- const docRef = this.pathResolver.getDocRef(userId, id);
59
- if (!docRef) return null;
60
-
61
- try {
62
- const docSnap = await getDoc(docRef);
63
-
64
- if (!docSnap.exists()) {
65
- return null;
66
- }
67
-
68
- const data = docSnap.data() as CreationDocument;
69
- return this.documentMapper(docSnap.id, data);
70
- } catch (error) {
71
- if (__DEV__) {
72
- console.error("[CreationsFetcher] getById() error:", error);
73
- }
74
- return null;
75
- }
40
+ return this.query.getById(userId, id);
76
41
  }
77
42
 
78
43
  /**
79
- * Subscribes to realtime updates for user's creations
80
- *
81
- * PERFORMANCE OPTIMIZATION:
82
- * - Server-side filtering with where clause (80% data reduction)
83
- * - No client-side filtering needed
84
- * - Requires Firestore composite index: (deletedAt ASC, createdAt DESC)
85
- *
86
- * @param userId - User ID to query
87
- * @param onData - Callback for data updates
88
- * @param onError - Optional error callback
89
- * @returns Unsubscribe function
44
+ * Subscribe to realtime updates for user's creations
90
45
  */
91
46
  subscribeToAll(
92
47
  userId: string,
93
48
  onData: CreationsSubscriptionCallback,
94
49
  onError?: (error: Error) => void,
95
50
  ): UnsubscribeFunction {
96
- const userCollection = this.pathResolver.getUserCollection(userId);
97
- if (!userCollection) {
98
- const error = new Error(`[CreationsFetcher] Cannot subscribe: Invalid user collection for userId: ${userId}`);
99
- if (__DEV__) {
100
- console.error(error.message);
101
- }
102
- // Return empty array immediately
103
- onData([]);
104
- // Report error to callback
105
- onError?.(error);
106
- // Return no-op unsubscribe function (no listener was created)
107
- return () => {
108
- if (__DEV__) {
109
- console.log("[CreationsFetcher] No-op unsubscribe called (no listener was created)");
110
- }
111
- };
112
- }
113
-
114
- // Optimized query with server-side filtering
115
- // This prevents downloading deleted items entirely
116
- const q = query(
117
- userCollection,
118
- where(CREATION_FIELDS.DELETED_AT, "==", null),
119
- orderBy(CREATION_FIELDS.CREATED_AT, "desc")
120
- );
121
-
122
- return onSnapshot(
123
- q,
124
- { includeMetadataChanges: false }, // Ignore metadata-only changes for performance
125
- (snapshot) => {
126
- // Map documents to domain entities
127
- // Server already filtered - no client filtering needed
128
- const creations = snapshot.docs.map((docSnap) => {
129
- const data = docSnap.data() as CreationDocument;
130
- return this.documentMapper(docSnap.id, data);
131
- });
132
-
133
- if (__DEV__) {
134
- console.log("[CreationsFetcher] Realtime sync:", {
135
- count: creations.length,
136
- serverFiltered: true,
137
- hasChanges: snapshot.docChanges().length,
138
- });
139
- }
140
-
141
- onData(creations);
142
- },
143
- (error: Error) => {
144
- if (__DEV__) {
145
- console.error("[CreationsFetcher] Realtime subscription error:", {
146
- error: error.message,
147
- code: (error as { code?: string }).code,
148
- userId,
149
- });
150
- }
151
- onError?.(error);
152
- },
153
- );
51
+ return this.subscription.subscribeToAll(userId, onData, onError);
154
52
  }
155
53
  }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * CreationsQuery
3
+ * Handles read operations (getAll, getById) for creations
4
+ * Single Responsibility: Firestore query operations
5
+ */
6
+
7
+ import { getDocs, getDoc, query, orderBy, where } from "firebase/firestore";
8
+ import { type FirestorePathResolver } from "@umituz/react-native-firebase";
9
+ import type { DocumentMapper } from "../../domain/value-objects/CreationsConfig";
10
+ import type { Creation, CreationDocument } from "../../domain/entities/Creation";
11
+ import { CREATION_FIELDS } from "../../domain/constants";
12
+
13
+ declare const __DEV__: boolean;
14
+
15
+ /**
16
+ * Handles query operations for creations
17
+ */
18
+ export class CreationsQuery {
19
+ constructor(
20
+ private readonly pathResolver: FirestorePathResolver,
21
+ private readonly documentMapper: DocumentMapper,
22
+ ) { }
23
+
24
+ /**
25
+ * Get all creations for a user
26
+ * Optimized query: Server-side filtering for non-deleted items
27
+ */
28
+ async getAll(userId: string): Promise<Creation[]> {
29
+ const userCollection = this.pathResolver.getUserCollection(userId);
30
+ if (!userCollection) return [];
31
+
32
+ try {
33
+ const q = query(
34
+ userCollection,
35
+ where(CREATION_FIELDS.DELETED_AT, "==", null),
36
+ orderBy(CREATION_FIELDS.CREATED_AT, "desc")
37
+ );
38
+ const snapshot = await getDocs(q);
39
+
40
+ const creations = snapshot.docs.map((docSnap) => {
41
+ const data = docSnap.data() as CreationDocument;
42
+ return this.documentMapper(docSnap.id, data);
43
+ });
44
+
45
+ if (__DEV__) {
46
+ console.log("[CreationsQuery] Fetched creations:", {
47
+ count: creations.length,
48
+ hasDeletedFilter: true,
49
+ });
50
+ }
51
+
52
+ return creations;
53
+ } catch (error) {
54
+ if (__DEV__) {
55
+ console.error("[CreationsQuery] getAll() error:", error);
56
+ }
57
+ return [];
58
+ }
59
+ }
60
+
61
+ /**
62
+ * Get a single creation by ID
63
+ */
64
+ async getById(userId: string, id: string): Promise<Creation | null> {
65
+ const docRef = this.pathResolver.getDocRef(userId, id);
66
+ if (!docRef) return null;
67
+
68
+ try {
69
+ const docSnap = await getDoc(docRef);
70
+
71
+ if (!docSnap.exists()) {
72
+ return null;
73
+ }
74
+
75
+ const data = docSnap.data() as CreationDocument;
76
+ return this.documentMapper(docSnap.id, data);
77
+ } catch (error) {
78
+ if (__DEV__) {
79
+ console.error("[CreationsQuery] getById() error:", error);
80
+ }
81
+ return null;
82
+ }
83
+ }
84
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * CreationsSubscription
3
+ * Handles realtime subscription operations for creations
4
+ * Single Responsibility: Firestore realtime listeners
5
+ */
6
+
7
+ import { query, orderBy, onSnapshot, where } from "firebase/firestore";
8
+ import { type FirestorePathResolver } from "@umituz/react-native-firebase";
9
+ import type { DocumentMapper } from "../../domain/value-objects/CreationsConfig";
10
+ import type { Creation, CreationDocument } from "../../domain/entities/Creation";
11
+ import type { CreationsSubscriptionCallback, UnsubscribeFunction } from "../../domain/repositories/ICreationsRepository";
12
+ import { CREATION_FIELDS } from "../../domain/constants";
13
+
14
+ declare const __DEV__: boolean;
15
+
16
+ /**
17
+ * Handles realtime subscriptions for creations
18
+ * Optimized with server-side filtering (80% data reduction)
19
+ */
20
+ export class CreationsSubscription {
21
+ constructor(
22
+ private readonly pathResolver: FirestorePathResolver,
23
+ private readonly documentMapper: DocumentMapper,
24
+ ) { }
25
+
26
+ subscribeToAll(
27
+ userId: string,
28
+ onData: CreationsSubscriptionCallback,
29
+ onError?: (error: Error) => void,
30
+ ): UnsubscribeFunction {
31
+ const userCollection = this.pathResolver.getUserCollection(userId);
32
+
33
+ if (!userCollection) {
34
+ const error = new Error(`[CreationsSubscription] Invalid user collection: ${userId}`);
35
+ if (__DEV__) console.error(error.message);
36
+ onData([]);
37
+ onError?.(error);
38
+ return () => { if (__DEV__) console.log("[CreationsSubscription] No-op unsubscribe"); };
39
+ }
40
+
41
+ const q = query(
42
+ userCollection,
43
+ where(CREATION_FIELDS.DELETED_AT, "==", null),
44
+ orderBy(CREATION_FIELDS.CREATED_AT, "desc")
45
+ );
46
+
47
+ return onSnapshot(
48
+ q,
49
+ { includeMetadataChanges: false },
50
+ (snapshot) => {
51
+ const creations = snapshot.docs.map((docSnap) => {
52
+ const data = docSnap.data() as CreationDocument;
53
+ return this.documentMapper(docSnap.id, data);
54
+ });
55
+
56
+ if (__DEV__) {
57
+ console.log("[CreationsSubscription] Sync:", creations.length, "items");
58
+ }
59
+
60
+ onData(creations);
61
+ },
62
+ (error: Error) => {
63
+ if (__DEV__) {
64
+ console.error("[CreationsSubscription] Error:", error.message);
65
+ }
66
+ onError?.(error);
67
+ },
68
+ );
69
+ }
70
+ }
@@ -1,14 +1,14 @@
1
1
  /**
2
2
  * Creation Delete Operations
3
+ * Single Responsibility: Delete/restore operations with centralized error handling
3
4
  */
4
5
 
5
6
  import { updateDoc, deleteDoc } from "firebase/firestore";
6
7
  import { type FirestorePathResolver } from "@umituz/react-native-firebase";
7
-
8
- declare const __DEV__: boolean;
8
+ import { logOperationError, logOperationSuccess, logInvalidRef } from "./creation-error-handler.util";
9
9
 
10
10
  /**
11
- * Soft deletes a creation
11
+ * Soft deletes a creation by setting deletedAt timestamp
12
12
  */
13
13
  export async function deleteCreation(
14
14
  pathResolver: FirestorePathResolver,
@@ -16,37 +16,25 @@ export async function deleteCreation(
16
16
  creationId: string
17
17
  ): Promise<boolean> {
18
18
  const docRef = pathResolver.getDocRef(userId, creationId);
19
+ const context = { userId, creationId };
20
+
19
21
  if (!docRef) {
20
- if (__DEV__) {
21
- console.error("[CreationDelete] Cannot delete: Invalid document reference", {
22
- userId,
23
- creationId,
24
- });
25
- }
22
+ logInvalidRef("Delete", context);
26
23
  return false;
27
24
  }
28
25
 
29
26
  try {
30
27
  await updateDoc(docRef, { deletedAt: new Date() });
31
- if (__DEV__) {
32
- console.log("[CreationDelete] Soft deleted successfully", { userId, creationId });
33
- }
28
+ logOperationSuccess("Delete", context);
34
29
  return true;
35
30
  } catch (error) {
36
- if (__DEV__) {
37
- console.error("[CreationDelete] Soft delete failed", {
38
- userId,
39
- creationId,
40
- error: error instanceof Error ? error.message : String(error),
41
- code: (error as { code?: string })?.code,
42
- });
43
- }
31
+ logOperationError("Delete", context, error);
44
32
  return false;
45
33
  }
46
34
  }
47
35
 
48
36
  /**
49
- * Hard deletes a creation
37
+ * Permanently deletes a creation from Firestore
50
38
  */
51
39
  export async function hardDeleteCreation(
52
40
  pathResolver: FirestorePathResolver,
@@ -54,37 +42,25 @@ export async function hardDeleteCreation(
54
42
  creationId: string
55
43
  ): Promise<boolean> {
56
44
  const docRef = pathResolver.getDocRef(userId, creationId);
45
+ const context = { userId, creationId };
46
+
57
47
  if (!docRef) {
58
- if (__DEV__) {
59
- console.error("[CreationDelete] Cannot hard delete: Invalid document reference", {
60
- userId,
61
- creationId,
62
- });
63
- }
48
+ logInvalidRef("HardDelete", context);
64
49
  return false;
65
50
  }
66
51
 
67
52
  try {
68
53
  await deleteDoc(docRef);
69
- if (__DEV__) {
70
- console.log("[CreationDelete] Hard deleted successfully", { userId, creationId });
71
- }
54
+ logOperationSuccess("HardDelete", context);
72
55
  return true;
73
56
  } catch (error) {
74
- if (__DEV__) {
75
- console.error("[CreationDelete] Hard delete failed", {
76
- userId,
77
- creationId,
78
- error: error instanceof Error ? error.message : String(error),
79
- code: (error as { code?: string })?.code,
80
- });
81
- }
57
+ logOperationError("HardDelete", context, error);
82
58
  return false;
83
59
  }
84
60
  }
85
61
 
86
62
  /**
87
- * Restores a soft-deleted creation
63
+ * Restores a soft-deleted creation by clearing deletedAt
88
64
  */
89
65
  export async function restoreCreation(
90
66
  pathResolver: FirestorePathResolver,
@@ -92,31 +68,19 @@ export async function restoreCreation(
92
68
  creationId: string
93
69
  ): Promise<boolean> {
94
70
  const docRef = pathResolver.getDocRef(userId, creationId);
71
+ const context = { userId, creationId };
72
+
95
73
  if (!docRef) {
96
- if (__DEV__) {
97
- console.error("[CreationDelete] Cannot restore: Invalid document reference", {
98
- userId,
99
- creationId,
100
- });
101
- }
74
+ logInvalidRef("Restore", context);
102
75
  return false;
103
76
  }
104
77
 
105
78
  try {
106
79
  await updateDoc(docRef, { deletedAt: null });
107
- if (__DEV__) {
108
- console.log("[CreationDelete] Restored successfully", { userId, creationId });
109
- }
80
+ logOperationSuccess("Restore", context);
110
81
  return true;
111
82
  } catch (error) {
112
- if (__DEV__) {
113
- console.error("[CreationDelete] Restore failed", {
114
- userId,
115
- creationId,
116
- error: error instanceof Error ? error.message : String(error),
117
- code: (error as { code?: string })?.code,
118
- });
119
- }
83
+ logOperationError("Restore", context, error);
120
84
  return false;
121
85
  }
122
86
  }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Creation Error Handler Utility
3
+ * Single Responsibility: Centralized error logging
4
+ */
5
+
6
+ declare const __DEV__: boolean;
7
+
8
+ export function logOperationError(
9
+ operation: string,
10
+ context: { userId: string; creationId: string },
11
+ error: unknown
12
+ ): void {
13
+ if (!__DEV__) return;
14
+
15
+ console.error(`[Creation${operation}] Failed:`, {
16
+ ...context,
17
+ error: error instanceof Error ? error.message : String(error),
18
+ code: (error as { code?: string })?.code,
19
+ });
20
+ }
21
+
22
+ export function logOperationSuccess(
23
+ operation: string,
24
+ context: { userId: string; creationId: string }
25
+ ): void {
26
+ if (!__DEV__) return;
27
+ console.log(`[Creation${operation}] Success:`, context);
28
+ }
29
+
30
+ export function logInvalidRef(
31
+ operation: string,
32
+ context: { userId: string; creationId: string }
33
+ ): void {
34
+ if (!__DEV__) return;
35
+ console.error(`[Creation${operation}] Invalid document reference:`, context);
36
+ }
@@ -49,57 +49,56 @@ export function useProcessingJobsPoller(
49
49
  [creations],
50
50
  );
51
51
 
52
- const pollJob = useCallback(
53
- async (creation: Creation) => {
54
- if (!userId || !creation.requestId || !creation.model) return;
55
- if (pollingRef.current.has(creation.id)) return;
56
-
57
- const provider = providerRegistry.getActiveProvider();
58
- if (!provider || !provider.isInitialized()) return;
59
-
60
- pollingRef.current.add(creation.id);
61
-
62
- try {
63
- if (typeof __DEV__ !== "undefined" && __DEV__) {
64
- console.log("[ProcessingJobsPoller] Checking status:", creation.id);
65
- }
66
-
67
- const status = await provider.getJobStatus(creation.model, creation.requestId);
68
-
69
- if (typeof __DEV__ !== "undefined" && __DEV__) {
70
- console.log("[ProcessingJobsPoller] Status:", creation.id, status.status);
71
- }
72
-
73
- if (status.status === QUEUE_STATUS.COMPLETED) {
74
- const result = await provider.getJobResult<FalResult>(creation.model, creation.requestId);
75
- const urls = extractResultUrl(result);
76
- if (typeof __DEV__ !== "undefined" && __DEV__) console.log("[ProcessingJobsPoller] Completed:", creation.id, urls);
77
-
78
- const uri = urls.videoUrl || urls.imageUrl || "";
79
- await repository.update(userId, creation.id, {
80
- status: CREATION_STATUS.COMPLETED,
81
- uri,
82
- output: urls,
83
- });
84
- } else if (status.status === QUEUE_STATUS.FAILED) {
85
- if (typeof __DEV__ !== "undefined" && __DEV__) console.log("[ProcessingJobsPoller] Failed:", creation.id);
86
-
87
- await repository.update(userId, creation.id, {
88
- status: CREATION_STATUS.FAILED,
89
- metadata: { error: "Generation failed" },
90
- });
91
- }
92
- // If still IN_PROGRESS or IN_QUEUE, we'll check again next interval
93
- } catch (error) {
94
- if (typeof __DEV__ !== "undefined" && __DEV__) {
95
- console.error("[ProcessingJobsPoller] Poll error:", creation.id, error);
96
- }
97
- } finally {
98
- pollingRef.current.delete(creation.id);
52
+ // Use ref for stable function reference to prevent effect re-runs
53
+ const pollJobRef = useRef<(creation: Creation) => Promise<void>>();
54
+
55
+ pollJobRef.current = async (creation: Creation) => {
56
+ if (!userId || !creation.requestId || !creation.model) return;
57
+ if (pollingRef.current.has(creation.id)) return;
58
+
59
+ const provider = providerRegistry.getActiveProvider();
60
+ if (!provider || !provider.isInitialized()) return;
61
+
62
+ pollingRef.current.add(creation.id);
63
+
64
+ try {
65
+ if (typeof __DEV__ !== "undefined" && __DEV__) {
66
+ console.log("[ProcessingJobsPoller] Checking status:", creation.id);
99
67
  }
100
- },
101
- [userId, repository],
102
- );
68
+
69
+ const status = await provider.getJobStatus(creation.model, creation.requestId);
70
+
71
+ if (typeof __DEV__ !== "undefined" && __DEV__) {
72
+ console.log("[ProcessingJobsPoller] Status:", creation.id, status.status);
73
+ }
74
+
75
+ if (status.status === QUEUE_STATUS.COMPLETED) {
76
+ const result = await provider.getJobResult<FalResult>(creation.model, creation.requestId);
77
+ const urls = extractResultUrl(result);
78
+ if (typeof __DEV__ !== "undefined" && __DEV__) console.log("[ProcessingJobsPoller] Completed:", creation.id, urls);
79
+
80
+ const uri = urls.videoUrl || urls.imageUrl || "";
81
+ await repository.update(userId, creation.id, {
82
+ status: CREATION_STATUS.COMPLETED,
83
+ uri,
84
+ output: urls,
85
+ });
86
+ } else if (status.status === QUEUE_STATUS.FAILED) {
87
+ if (typeof __DEV__ !== "undefined" && __DEV__) console.log("[ProcessingJobsPoller] Failed:", creation.id);
88
+
89
+ await repository.update(userId, creation.id, {
90
+ status: CREATION_STATUS.FAILED,
91
+ metadata: { error: "Generation failed" },
92
+ });
93
+ }
94
+ } catch (error) {
95
+ if (typeof __DEV__ !== "undefined" && __DEV__) {
96
+ console.error("[ProcessingJobsPoller] Poll error:", creation.id, error);
97
+ }
98
+ } finally {
99
+ pollingRef.current.delete(creation.id);
100
+ }
101
+ };
103
102
 
104
103
  useEffect(() => {
105
104
  if (!enabled || !userId || processingJobs.length === 0) {
@@ -111,11 +110,11 @@ export function useProcessingJobsPoller(
111
110
  }
112
111
 
113
112
  // Initial poll
114
- processingJobs.forEach((job) => void pollJob(job));
113
+ processingJobs.forEach((job) => pollJobRef.current?.(job));
115
114
 
116
115
  // Set up interval polling
117
116
  intervalRef.current = setInterval(() => {
118
- processingJobs.forEach((job) => void pollJob(job));
117
+ processingJobs.forEach((job) => pollJobRef.current?.(job));
119
118
  }, DEFAULT_POLL_INTERVAL_MS);
120
119
 
121
120
  return () => {
@@ -128,7 +127,7 @@ export function useProcessingJobsPoller(
128
127
  intervalRef.current = null;
129
128
  }
130
129
  };
131
- }, [enabled, userId, processingJobs, pollJob]);
130
+ }, [enabled, userId, processingJobs]);
132
131
 
133
132
  return {
134
133
  processingCount: processingJobs.length,