appwrite-utils-cli 0.10.86 → 1.0.1

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 (178) hide show
  1. package/.appwrite/.yaml_schemas/appwrite-config.schema.json +380 -0
  2. package/.appwrite/.yaml_schemas/collection.schema.json +255 -0
  3. package/.appwrite/collections/Categories.yaml +182 -0
  4. package/.appwrite/collections/ExampleCollection.yaml +36 -0
  5. package/.appwrite/collections/Posts.yaml +227 -0
  6. package/.appwrite/collections/Users.yaml +149 -0
  7. package/.appwrite/config.yaml +109 -0
  8. package/.appwrite/import/README.md +148 -0
  9. package/.appwrite/import/categories-import.yaml +129 -0
  10. package/.appwrite/import/posts-import.yaml +208 -0
  11. package/.appwrite/import/users-import.yaml +130 -0
  12. package/.appwrite/importData/categories.json +194 -0
  13. package/.appwrite/importData/posts.json +270 -0
  14. package/.appwrite/importData/users.json +220 -0
  15. package/.appwrite/schemas/categories.json +128 -0
  16. package/.appwrite/schemas/exampleCollection.json +52 -0
  17. package/.appwrite/schemas/posts.json +173 -0
  18. package/.appwrite/schemas/users.json +125 -0
  19. package/README.md +260 -33
  20. package/dist/collections/attributes.js +3 -2
  21. package/dist/collections/methods.js +56 -38
  22. package/dist/config/yamlConfig.d.ts +501 -0
  23. package/dist/config/yamlConfig.js +452 -0
  24. package/dist/databases/setup.d.ts +6 -0
  25. package/dist/databases/setup.js +119 -0
  26. package/dist/functions/methods.d.ts +1 -1
  27. package/dist/functions/methods.js +5 -2
  28. package/dist/functions/openapi.d.ts +4 -0
  29. package/dist/functions/openapi.js +60 -0
  30. package/dist/interactiveCLI.d.ts +5 -0
  31. package/dist/interactiveCLI.js +194 -49
  32. package/dist/main.js +91 -30
  33. package/dist/migrations/afterImportActions.js +2 -2
  34. package/dist/migrations/appwriteToX.d.ts +10 -0
  35. package/dist/migrations/appwriteToX.js +15 -4
  36. package/dist/migrations/backup.d.ts +16 -16
  37. package/dist/migrations/dataLoader.d.ts +83 -1
  38. package/dist/migrations/dataLoader.js +4 -4
  39. package/dist/migrations/importController.js +25 -18
  40. package/dist/migrations/importDataActions.js +2 -2
  41. package/dist/migrations/logging.d.ts +9 -1
  42. package/dist/migrations/logging.js +41 -22
  43. package/dist/migrations/migrationHelper.d.ts +4 -4
  44. package/dist/migrations/relationships.js +1 -1
  45. package/dist/migrations/services/DataTransformationService.d.ts +55 -0
  46. package/dist/migrations/services/DataTransformationService.js +158 -0
  47. package/dist/migrations/services/FileHandlerService.d.ts +75 -0
  48. package/dist/migrations/services/FileHandlerService.js +236 -0
  49. package/dist/migrations/services/ImportOrchestrator.d.ts +97 -0
  50. package/dist/migrations/services/ImportOrchestrator.js +488 -0
  51. package/dist/migrations/services/RateLimitManager.d.ts +138 -0
  52. package/dist/migrations/services/RateLimitManager.js +279 -0
  53. package/dist/migrations/services/RelationshipResolver.d.ts +120 -0
  54. package/dist/migrations/services/RelationshipResolver.js +332 -0
  55. package/dist/migrations/services/UserMappingService.d.ts +109 -0
  56. package/dist/migrations/services/UserMappingService.js +277 -0
  57. package/dist/migrations/services/ValidationService.d.ts +74 -0
  58. package/dist/migrations/services/ValidationService.js +260 -0
  59. package/dist/migrations/transfer.d.ts +0 -6
  60. package/dist/migrations/transfer.js +16 -132
  61. package/dist/migrations/yaml/YamlImportConfigLoader.d.ts +384 -0
  62. package/dist/migrations/yaml/YamlImportConfigLoader.js +375 -0
  63. package/dist/migrations/yaml/YamlImportIntegration.d.ts +87 -0
  64. package/dist/migrations/yaml/YamlImportIntegration.js +330 -0
  65. package/dist/migrations/yaml/generateImportSchemas.d.ts +17 -0
  66. package/dist/migrations/yaml/generateImportSchemas.js +575 -0
  67. package/dist/schemas/authUser.d.ts +9 -9
  68. package/dist/shared/attributeManager.d.ts +17 -0
  69. package/dist/shared/attributeManager.js +273 -0
  70. package/dist/shared/confirmationDialogs.d.ts +75 -0
  71. package/dist/shared/confirmationDialogs.js +236 -0
  72. package/dist/shared/functionManager.d.ts +48 -0
  73. package/dist/shared/functionManager.js +322 -0
  74. package/dist/shared/indexManager.d.ts +24 -0
  75. package/dist/shared/indexManager.js +150 -0
  76. package/dist/shared/jsonSchemaGenerator.d.ts +51 -0
  77. package/dist/shared/jsonSchemaGenerator.js +313 -0
  78. package/dist/shared/logging.d.ts +10 -0
  79. package/dist/shared/logging.js +46 -0
  80. package/dist/shared/messageFormatter.d.ts +37 -0
  81. package/dist/shared/messageFormatter.js +152 -0
  82. package/dist/shared/migrationHelpers.d.ts +173 -0
  83. package/dist/shared/migrationHelpers.js +142 -0
  84. package/dist/shared/operationLogger.d.ts +3 -0
  85. package/dist/shared/operationLogger.js +25 -0
  86. package/dist/shared/operationQueue.d.ts +13 -0
  87. package/dist/shared/operationQueue.js +79 -0
  88. package/dist/shared/progressManager.d.ts +62 -0
  89. package/dist/shared/progressManager.js +215 -0
  90. package/dist/shared/schemaGenerator.d.ts +18 -0
  91. package/dist/shared/schemaGenerator.js +523 -0
  92. package/dist/storage/methods.d.ts +3 -1
  93. package/dist/storage/methods.js +144 -55
  94. package/dist/storage/schemas.d.ts +56 -16
  95. package/dist/types.d.ts +2 -2
  96. package/dist/types.js +1 -1
  97. package/dist/users/methods.d.ts +16 -0
  98. package/dist/users/methods.js +276 -0
  99. package/dist/utils/configMigration.d.ts +1 -0
  100. package/dist/utils/configMigration.js +156 -0
  101. package/dist/utils/dataConverters.d.ts +46 -0
  102. package/dist/utils/dataConverters.js +139 -0
  103. package/dist/utils/loadConfigs.d.ts +15 -4
  104. package/dist/utils/loadConfigs.js +377 -51
  105. package/dist/utils/schemaStrings.js +2 -1
  106. package/dist/utils/setupFiles.d.ts +2 -1
  107. package/dist/utils/setupFiles.js +723 -28
  108. package/dist/utils/validationRules.d.ts +43 -0
  109. package/dist/utils/validationRules.js +42 -0
  110. package/dist/utils/yamlConverter.d.ts +48 -0
  111. package/dist/utils/yamlConverter.js +98 -0
  112. package/dist/utilsController.js +65 -43
  113. package/package.json +19 -15
  114. package/src/collections/attributes.ts +3 -2
  115. package/src/collections/methods.ts +85 -51
  116. package/src/config/yamlConfig.ts +488 -0
  117. package/src/{migrations/setupDatabase.ts → databases/setup.ts} +11 -5
  118. package/src/functions/methods.ts +8 -4
  119. package/src/functions/templates/count-docs-in-collection/package.json +25 -0
  120. package/src/functions/templates/count-docs-in-collection/tsconfig.json +28 -0
  121. package/src/functions/templates/typescript-node/package.json +24 -0
  122. package/src/functions/templates/typescript-node/tsconfig.json +28 -0
  123. package/src/functions/templates/uv/README.md +31 -0
  124. package/src/functions/templates/uv/pyproject.toml +29 -0
  125. package/src/interactiveCLI.ts +226 -61
  126. package/src/main.ts +111 -37
  127. package/src/migrations/afterImportActions.ts +2 -2
  128. package/src/migrations/appwriteToX.ts +17 -4
  129. package/src/migrations/dataLoader.ts +4 -4
  130. package/src/migrations/importController.ts +30 -22
  131. package/src/migrations/importDataActions.ts +2 -2
  132. package/src/migrations/relationships.ts +1 -1
  133. package/src/migrations/services/DataTransformationService.ts +196 -0
  134. package/src/migrations/services/FileHandlerService.ts +311 -0
  135. package/src/migrations/services/ImportOrchestrator.ts +669 -0
  136. package/src/migrations/services/RateLimitManager.ts +363 -0
  137. package/src/migrations/services/RelationshipResolver.ts +461 -0
  138. package/src/migrations/services/UserMappingService.ts +345 -0
  139. package/src/migrations/services/ValidationService.ts +349 -0
  140. package/src/migrations/transfer.ts +22 -228
  141. package/src/migrations/yaml/YamlImportConfigLoader.ts +427 -0
  142. package/src/migrations/yaml/YamlImportIntegration.ts +419 -0
  143. package/src/migrations/yaml/generateImportSchemas.ts +589 -0
  144. package/src/shared/attributeManager.ts +429 -0
  145. package/src/shared/confirmationDialogs.ts +327 -0
  146. package/src/shared/functionManager.ts +515 -0
  147. package/src/shared/indexManager.ts +253 -0
  148. package/src/shared/jsonSchemaGenerator.ts +403 -0
  149. package/src/shared/logging.ts +74 -0
  150. package/src/shared/messageFormatter.ts +195 -0
  151. package/src/{migrations/migrationHelper.ts → shared/migrationHelpers.ts} +22 -4
  152. package/src/{migrations/helper.ts → shared/operationLogger.ts} +7 -2
  153. package/src/{migrations/queue.ts → shared/operationQueue.ts} +1 -1
  154. package/src/shared/progressManager.ts +278 -0
  155. package/src/{migrations/schemaStrings.ts → shared/schemaGenerator.ts} +71 -17
  156. package/src/storage/methods.ts +199 -78
  157. package/src/types.ts +2 -2
  158. package/src/{migrations/users.ts → users/methods.ts} +2 -2
  159. package/src/utils/configMigration.ts +212 -0
  160. package/src/utils/loadConfigs.ts +414 -52
  161. package/src/utils/schemaStrings.ts +2 -1
  162. package/src/utils/setupFiles.ts +742 -40
  163. package/src/{migrations → utils}/validationRules.ts +1 -1
  164. package/src/utils/yamlConverter.ts +131 -0
  165. package/src/utilsController.ts +75 -54
  166. package/src/functions/templates/poetry/README.md +0 -30
  167. package/src/functions/templates/poetry/pyproject.toml +0 -16
  168. package/src/migrations/attributes.ts +0 -561
  169. package/src/migrations/backup.ts +0 -205
  170. package/src/migrations/databases.ts +0 -39
  171. package/src/migrations/dbHelpers.ts +0 -92
  172. package/src/migrations/indexes.ts +0 -40
  173. package/src/migrations/logging.ts +0 -29
  174. package/src/migrations/storage.ts +0 -538
  175. /package/src/{migrations → functions}/openapi.ts +0 -0
  176. /package/src/functions/templates/{poetry → uv}/src/__init__.py +0 -0
  177. /package/src/functions/templates/{poetry → uv}/src/index.py +0 -0
  178. /package/src/{migrations/converters.ts → utils/dataConverters.ts} +0 -0
@@ -0,0 +1,345 @@
1
+ import { z } from "zod";
2
+ import { ID } from "node-appwrite";
3
+ import type {
4
+ AttributeMappings,
5
+ AppwriteConfig,
6
+ } from "appwrite-utils";
7
+ import { AuthUserCreateSchema } from "../../schemas/authUser.js";
8
+ import { logger } from "../../shared/logging.js";
9
+ import type { DataTransformationService } from "./DataTransformationService.js";
10
+
11
+ /**
12
+ * Service responsible for user mapping and deduplication during import.
13
+ * Preserves all existing sophisticated user handling logic from DataLoader.
14
+ * Extracted to provide focused, testable user management operations.
15
+ */
16
+ export class UserMappingService {
17
+ private config: AppwriteConfig;
18
+ private dataTransformationService: DataTransformationService;
19
+
20
+ // Maps to hold email and phone to user ID mappings for uniqueness in User Accounts
21
+ private emailToUserIdMap = new Map<string, string>();
22
+ private phoneToUserIdMap = new Map<string, string>();
23
+ private userIdSet = new Set<string>();
24
+
25
+ // Map to hold the merged user map for relationship resolution
26
+ // Will hold an array of the old user ID's that are mapped to the same new user ID
27
+ // For example, if there are two users with the same email, they will both be mapped to the same new user ID
28
+ // Prevents duplicate users with the other two maps below it and allows me to keep the old ID's
29
+ private mergedUserMap = new Map<string, string[]>();
30
+
31
+ // Map to track existing users
32
+ public userExistsMap = new Map<string, boolean>();
33
+
34
+ constructor(
35
+ config: AppwriteConfig,
36
+ dataTransformationService: DataTransformationService
37
+ ) {
38
+ this.config = config;
39
+ this.dataTransformationService = dataTransformationService;
40
+ }
41
+
42
+ /**
43
+ * Initializes user maps with existing users from the system.
44
+ * Preserves existing user loading logic from DataLoader.
45
+ *
46
+ * @param existingUsers - Array of existing users from the system
47
+ */
48
+ initializeWithExistingUsers(existingUsers: any[]): void {
49
+ // Clear existing maps
50
+ this.emailToUserIdMap.clear();
51
+ this.phoneToUserIdMap.clear();
52
+ this.userIdSet.clear();
53
+ this.userExistsMap.clear();
54
+
55
+ // Iterate over the users and setup our maps ahead of time for email and phone
56
+ for (const user of existingUsers) {
57
+ if (user.email) {
58
+ this.emailToUserIdMap.set(user.email.toLowerCase(), user.$id);
59
+ }
60
+ if (user.phone) {
61
+ this.phoneToUserIdMap.set(user.phone, user.$id);
62
+ }
63
+ this.userExistsMap.set(user.$id, true);
64
+ this.userIdSet.add(user.$id);
65
+ }
66
+
67
+ logger.info(`Initialized user maps with ${existingUsers.length} existing users`);
68
+ }
69
+
70
+ /**
71
+ * Generates a unique ID that doesn't conflict with existing user IDs.
72
+ * Preserves existing unique ID generation logic from DataLoader.
73
+ *
74
+ * @param collectionName - The collection name for context
75
+ * @returns A truly unique ID
76
+ */
77
+ getTrueUniqueUserId(collectionName: string): string {
78
+ let newId = ID.unique();
79
+ let condition =
80
+ this.userExistsMap.has(newId) ||
81
+ this.userIdSet.has(newId) ||
82
+ Array.from(this.emailToUserIdMap.values()).includes(newId) ||
83
+ Array.from(this.phoneToUserIdMap.values()).includes(newId);
84
+
85
+ while (condition) {
86
+ newId = ID.unique();
87
+ condition =
88
+ this.userExistsMap.has(newId) ||
89
+ this.userIdSet.has(newId) ||
90
+ Array.from(this.emailToUserIdMap.values()).includes(newId) ||
91
+ Array.from(this.phoneToUserIdMap.values()).includes(newId);
92
+ }
93
+ return newId;
94
+ }
95
+
96
+ /**
97
+ * Prepares user data by checking for duplicates based on email or phone, adding to a duplicate map if found,
98
+ * and then returning the transformed item without user-specific keys.
99
+ *
100
+ * Preserves existing sophisticated user deduplication logic from DataLoader.
101
+ *
102
+ * @param item - The raw item to be processed.
103
+ * @param attributeMappings - The attribute mappings for the item.
104
+ * @param primaryKeyField - The primary key field name
105
+ * @param newId - The proposed new ID for the user
106
+ * @returns Object containing transformed item, existing ID if duplicate, and user data
107
+ */
108
+ prepareUserData(
109
+ item: any,
110
+ attributeMappings: AttributeMappings,
111
+ primaryKeyField: string,
112
+ newId: string
113
+ ): {
114
+ transformedItem: any;
115
+ existingId: string | undefined;
116
+ userData: {
117
+ rawData: any;
118
+ finalData: z.infer<typeof AuthUserCreateSchema>;
119
+ };
120
+ } {
121
+ // Ensure we have a truly unique ID
122
+ if (
123
+ this.userIdSet.has(newId) ||
124
+ this.userExistsMap.has(newId) ||
125
+ Array.from(this.emailToUserIdMap.values()).includes(newId) ||
126
+ Array.from(this.phoneToUserIdMap.values()).includes(newId)
127
+ ) {
128
+ newId = this.getTrueUniqueUserId("users");
129
+ }
130
+
131
+ let transformedItem = this.dataTransformationService.transformData(item, attributeMappings);
132
+ let userData = AuthUserCreateSchema.safeParse(transformedItem);
133
+
134
+ if (userData.data?.email) {
135
+ userData.data.email = userData.data.email.toLowerCase();
136
+ }
137
+
138
+ if (!userData.success || !(userData.data.email || userData.data.phone)) {
139
+ logger.error(
140
+ `Invalid user data: ${JSON.stringify(
141
+ userData.error?.errors,
142
+ undefined,
143
+ 2
144
+ )} or missing email/phone`
145
+ );
146
+
147
+ const userKeys = ["email", "phone", "name", "labels", "prefs"];
148
+ userKeys.forEach((key) => {
149
+ if (transformedItem.hasOwnProperty(key)) {
150
+ delete transformedItem[key];
151
+ }
152
+ });
153
+
154
+ return {
155
+ transformedItem,
156
+ existingId: undefined,
157
+ userData: {
158
+ rawData: item,
159
+ finalData: transformedItem,
160
+ },
161
+ };
162
+ }
163
+
164
+ const email = userData.data.email?.toLowerCase();
165
+ const phone = userData.data.phone;
166
+ let existingId: string | undefined;
167
+
168
+ // Check for duplicate email and phone
169
+ if (email && this.emailToUserIdMap.has(email)) {
170
+ existingId = this.emailToUserIdMap.get(email);
171
+ if (phone && !this.phoneToUserIdMap.has(phone)) {
172
+ this.phoneToUserIdMap.set(phone, newId);
173
+ }
174
+ } else if (phone && this.phoneToUserIdMap.has(phone)) {
175
+ existingId = this.phoneToUserIdMap.get(phone);
176
+ if (email && !this.emailToUserIdMap.has(email)) {
177
+ this.emailToUserIdMap.set(email, newId);
178
+ }
179
+ } else {
180
+ if (email) this.emailToUserIdMap.set(email, newId);
181
+ if (phone) this.phoneToUserIdMap.set(phone, newId);
182
+ }
183
+
184
+ if (existingId) {
185
+ userData.data.userId = existingId;
186
+ const mergedUsers = this.mergedUserMap.get(existingId) || [];
187
+ mergedUsers.push(`${item[primaryKeyField]}`);
188
+ this.mergedUserMap.set(existingId, mergedUsers);
189
+
190
+ const userKeys = ["email", "phone", "name", "labels", "prefs"];
191
+ userKeys.forEach((key) => {
192
+ if (transformedItem.hasOwnProperty(key)) {
193
+ delete transformedItem[key];
194
+ }
195
+ });
196
+
197
+ return {
198
+ transformedItem: {
199
+ ...transformedItem,
200
+ userId: existingId,
201
+ docId: existingId,
202
+ },
203
+ existingId,
204
+ userData: {
205
+ rawData: item,
206
+ finalData: userData.data,
207
+ },
208
+ };
209
+ } else {
210
+ existingId = newId;
211
+ userData.data.userId = existingId;
212
+ }
213
+
214
+ const userKeys = ["email", "phone", "name", "labels", "prefs"];
215
+ userKeys.forEach((key) => {
216
+ if (transformedItem.hasOwnProperty(key)) {
217
+ delete transformedItem[key];
218
+ }
219
+ });
220
+
221
+ this.userIdSet.add(existingId);
222
+
223
+ return {
224
+ transformedItem: {
225
+ ...transformedItem,
226
+ userId: existingId,
227
+ docId: existingId,
228
+ },
229
+ existingId,
230
+ userData: {
231
+ rawData: item,
232
+ finalData: userData.data,
233
+ },
234
+ };
235
+ }
236
+
237
+ /**
238
+ * Checks if a collection is the users collection based on configuration.
239
+ *
240
+ * @param collectionName - The collection name to check
241
+ * @returns True if this is the users collection
242
+ */
243
+ isUsersCollection(collectionName: string): boolean {
244
+ return !!(
245
+ this.config.usersCollectionName &&
246
+ this.getCollectionKey(this.config.usersCollectionName) ===
247
+ this.getCollectionKey(collectionName)
248
+ );
249
+ }
250
+
251
+ /**
252
+ * Helper method to generate a consistent key for collections.
253
+ * Preserves existing logic from DataLoader.
254
+ */
255
+ private getCollectionKey(name: string): string {
256
+ return name.toLowerCase().replace(" ", "");
257
+ }
258
+
259
+ /**
260
+ * Gets merged user mappings for relationship resolution.
261
+ *
262
+ * @returns Map of merged user IDs to arrays of original IDs
263
+ */
264
+ getMergedUserMap(): Map<string, string[]> {
265
+ return new Map(this.mergedUserMap);
266
+ }
267
+
268
+ /**
269
+ * Finds the new user ID for an old user ID, considering merged users.
270
+ * Preserves existing merged user lookup logic from DataLoader.
271
+ *
272
+ * @param oldId - The old user ID to look up
273
+ * @returns The new user ID if found, otherwise the original ID
274
+ */
275
+ findNewUserIdForOldId(oldId: string): string {
276
+ // Check if this old ID was merged into another user
277
+ for (const [newUserId, oldUserIds] of this.mergedUserMap.entries()) {
278
+ if (oldUserIds.includes(`${oldId}`)) {
279
+ return newUserId;
280
+ }
281
+ }
282
+
283
+ // If not found in merged users, return the original ID
284
+ return oldId;
285
+ }
286
+
287
+ /**
288
+ * Merges user data from duplicate entries.
289
+ * Preserves existing user data merging logic.
290
+ *
291
+ * @param existingUserData - The existing user data
292
+ * @param newUserData - The new user data to merge
293
+ * @returns Merged user data
294
+ */
295
+ mergeUserData(existingUserData: any, newUserData: any): any {
296
+ return this.dataTransformationService.mergeObjects(existingUserData, newUserData);
297
+ }
298
+
299
+ /**
300
+ * Gets statistics about user mapping operations.
301
+ * Useful for import planning and reporting.
302
+ *
303
+ * @returns User mapping statistics
304
+ */
305
+ getStatistics(): {
306
+ totalExistingUsers: number;
307
+ emailMappings: number;
308
+ phoneMappings: number;
309
+ mergedUsers: number;
310
+ totalMergedOldIds: number;
311
+ } {
312
+ let totalMergedOldIds = 0;
313
+ for (const oldIds of this.mergedUserMap.values()) {
314
+ totalMergedOldIds += oldIds.length;
315
+ }
316
+
317
+ return {
318
+ totalExistingUsers: this.userExistsMap.size,
319
+ emailMappings: this.emailToUserIdMap.size,
320
+ phoneMappings: this.phoneToUserIdMap.size,
321
+ mergedUsers: this.mergedUserMap.size,
322
+ totalMergedOldIds,
323
+ };
324
+ }
325
+
326
+ /**
327
+ * Validates user mapping configuration.
328
+ * Ensures the user mapping setup is correct before import.
329
+ *
330
+ * @returns Array of validation errors (empty if valid)
331
+ */
332
+ validateConfiguration(): string[] {
333
+ const errors: string[] = [];
334
+
335
+ if (!this.config.usersCollectionName) {
336
+ errors.push("usersCollectionName is not configured");
337
+ }
338
+
339
+ if (!this.config.documentBucketId) {
340
+ errors.push("documentBucketId is not configured");
341
+ }
342
+
343
+ return errors;
344
+ }
345
+ }
@@ -0,0 +1,349 @@
1
+ import type {
2
+ AttributeMappings,
3
+ ImportDef,
4
+ CollectionCreate,
5
+ } from "appwrite-utils";
6
+ import type { ImportDataActions } from "../importDataActions.js";
7
+ import { logger } from "../../shared/logging.js";
8
+
9
+ /**
10
+ * Service responsible for validation during import operations.
11
+ * Provides centralized validation logic extracted from ImportDataActions and DataLoader.
12
+ */
13
+ export class ValidationService {
14
+ private importDataActions: ImportDataActions;
15
+
16
+ constructor(importDataActions: ImportDataActions) {
17
+ this.importDataActions = importDataActions;
18
+ }
19
+
20
+ /**
21
+ * Validates a single data item based on defined validation rules.
22
+ * Preserves existing validation logic from ImportDataActions.
23
+ *
24
+ * @param item - The data item to validate
25
+ * @param attributeMappings - The attribute mappings for the data item
26
+ * @param context - The context for resolving templated parameters in validation rules
27
+ * @returns True if the item is valid, false otherwise
28
+ */
29
+ validateDataItem(
30
+ item: any,
31
+ attributeMappings: AttributeMappings,
32
+ context: { [key: string]: any }
33
+ ): boolean {
34
+ try {
35
+ return this.importDataActions.validateItem(item, attributeMappings, context);
36
+ } catch (error) {
37
+ logger.error(`Validation error for item: ${JSON.stringify(item, null, 2)}`, error);
38
+ return false;
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Validates an import definition before processing begins.
44
+ * Provides early validation to catch configuration issues.
45
+ *
46
+ * @param importDef - The import definition to validate
47
+ * @returns Array of validation errors (empty if valid)
48
+ */
49
+ validateImportDefinition(importDef: ImportDef): string[] {
50
+ const errors: string[] = [];
51
+
52
+ // Validate required fields
53
+ if (!importDef.filePath) {
54
+ errors.push("filePath is required");
55
+ }
56
+
57
+ if (!importDef.attributeMappings || importDef.attributeMappings.length === 0) {
58
+ errors.push("attributeMappings are required");
59
+ }
60
+
61
+ // Validate attribute mappings
62
+ if (importDef.attributeMappings) {
63
+ for (let i = 0; i < importDef.attributeMappings.length; i++) {
64
+ const mapping = importDef.attributeMappings[i];
65
+
66
+ if (!mapping.targetKey) {
67
+ errors.push(`attributeMappings[${i}]: targetKey is required`);
68
+ }
69
+
70
+ if (!mapping.oldKey && !mapping.oldKeys && mapping.valueToSet === undefined) {
71
+ errors.push(
72
+ `attributeMappings[${i}]: must have either oldKey, oldKeys, or valueToSet`
73
+ );
74
+ }
75
+
76
+ // Validate file data if present
77
+ if (mapping.fileData) {
78
+ if (!mapping.fileData.path) {
79
+ errors.push(`attributeMappings[${i}].fileData: path is required`);
80
+ }
81
+ if (!mapping.fileData.name) {
82
+ errors.push(`attributeMappings[${i}].fileData: name is required`);
83
+ }
84
+ }
85
+
86
+ // Validate converters if present
87
+ if (mapping.converters && !Array.isArray(mapping.converters)) {
88
+ errors.push(`attributeMappings[${i}].converters: must be an array`);
89
+ }
90
+
91
+ // Validate validation actions if present
92
+ if (mapping.validationActions) {
93
+ if (!Array.isArray(mapping.validationActions)) {
94
+ errors.push(`attributeMappings[${i}].validationActions: must be an array`);
95
+ } else {
96
+ for (let j = 0; j < mapping.validationActions.length; j++) {
97
+ const action = mapping.validationActions[j];
98
+ if (!action.action) {
99
+ errors.push(
100
+ `attributeMappings[${i}].validationActions[${j}]: action is required`
101
+ );
102
+ }
103
+ if (!Array.isArray(action.params)) {
104
+ errors.push(
105
+ `attributeMappings[${i}].validationActions[${j}]: params must be an array`
106
+ );
107
+ }
108
+ }
109
+ }
110
+ }
111
+
112
+ // Validate post-import actions if present
113
+ if (mapping.postImportActions) {
114
+ if (!Array.isArray(mapping.postImportActions)) {
115
+ errors.push(`attributeMappings[${i}].postImportActions: must be an array`);
116
+ } else {
117
+ for (let j = 0; j < mapping.postImportActions.length; j++) {
118
+ const action = mapping.postImportActions[j];
119
+ if (!action.action) {
120
+ errors.push(
121
+ `attributeMappings[${i}].postImportActions[${j}]: action is required`
122
+ );
123
+ }
124
+ if (!Array.isArray(action.params)) {
125
+ errors.push(
126
+ `attributeMappings[${i}].postImportActions[${j}]: params must be an array`
127
+ );
128
+ }
129
+ }
130
+ }
131
+ }
132
+ }
133
+ }
134
+
135
+ // Validate ID mappings if present
136
+ if (importDef.idMappings) {
137
+ for (let i = 0; i < importDef.idMappings.length; i++) {
138
+ const idMapping = importDef.idMappings[i];
139
+
140
+ if (!idMapping.sourceField) {
141
+ errors.push(`idMappings[${i}]: sourceField is required`);
142
+ }
143
+ if (!idMapping.targetField) {
144
+ errors.push(`idMappings[${i}]: targetField is required`);
145
+ }
146
+ if (!idMapping.targetCollection) {
147
+ errors.push(`idMappings[${i}]: targetCollection is required`);
148
+ }
149
+ }
150
+ }
151
+
152
+ // Validate update mapping if present
153
+ if (importDef.updateMapping) {
154
+ if (!importDef.updateMapping.originalIdField) {
155
+ errors.push("updateMapping: originalIdField is required");
156
+ }
157
+ if (!importDef.updateMapping.targetField) {
158
+ errors.push("updateMapping: targetField is required");
159
+ }
160
+ }
161
+
162
+ return errors;
163
+ }
164
+
165
+ /**
166
+ * Validates a collection configuration for import compatibility.
167
+ * Ensures the collection has the necessary attributes for import operations.
168
+ *
169
+ * @param collection - The collection to validate
170
+ * @param importDefs - The import definitions that will be used with this collection
171
+ * @returns Array of validation errors (empty if valid)
172
+ */
173
+ validateCollectionForImport(
174
+ collection: CollectionCreate,
175
+ importDefs: ImportDef[]
176
+ ): string[] {
177
+ const errors: string[] = [];
178
+
179
+ if (!collection.name) {
180
+ errors.push("Collection name is required");
181
+ }
182
+
183
+ if (!collection.attributes || collection.attributes.length === 0) {
184
+ errors.push("Collection must have attributes defined");
185
+ }
186
+
187
+ // Validate that target keys in import definitions exist as attributes
188
+ for (const importDef of importDefs) {
189
+ for (const mapping of importDef.attributeMappings) {
190
+ const attributeExists = collection.attributes?.some(
191
+ attr => attr.key === mapping.targetKey
192
+ );
193
+
194
+ if (!attributeExists) {
195
+ errors.push(
196
+ `Attribute '${mapping.targetKey}' referenced in import mapping not found in collection`
197
+ );
198
+ }
199
+ }
200
+ }
201
+
202
+ return errors;
203
+ }
204
+
205
+ /**
206
+ * Validates data consistency across multiple collections.
207
+ * Checks for relationship integrity and data consistency.
208
+ *
209
+ * @param collections - Array of collections to validate
210
+ * @returns Array of validation errors (empty if valid)
211
+ */
212
+ validateCrossCollectionConsistency(
213
+ collections: CollectionCreate[]
214
+ ): string[] {
215
+ const errors: string[] = [];
216
+ const collectionNames = new Set(collections.map(c => c.name));
217
+
218
+ for (const collection of collections) {
219
+ if (!collection.importDefs) continue;
220
+
221
+ for (const importDef of collection.importDefs) {
222
+ if (!importDef.idMappings) continue;
223
+
224
+ for (const idMapping of importDef.idMappings) {
225
+ // Check if target collection exists
226
+ if (!collectionNames.has(idMapping.targetCollection)) {
227
+ errors.push(
228
+ `Collection '${collection.name}' references non-existent target collection '${idMapping.targetCollection}' in ID mapping`
229
+ );
230
+ }
231
+ }
232
+ }
233
+ }
234
+
235
+ return errors;
236
+ }
237
+
238
+ /**
239
+ * Performs comprehensive pre-import validation.
240
+ * Validates all aspects of the import configuration before starting.
241
+ *
242
+ * @param collections - Collections that will be imported
243
+ * @param appwriteFolderPath - Path to the appwrite folder for file validation
244
+ * @returns Validation result with errors and warnings
245
+ */
246
+ performPreImportValidation(
247
+ collections: CollectionCreate[],
248
+ appwriteFolderPath: string
249
+ ): {
250
+ errors: string[];
251
+ warnings: string[];
252
+ isValid: boolean;
253
+ } {
254
+ const errors: string[] = [];
255
+ const warnings: string[] = [];
256
+
257
+ // Validate each collection
258
+ for (const collection of collections) {
259
+ const collectionErrors = this.validateCollectionForImport(
260
+ collection,
261
+ collection.importDefs || []
262
+ );
263
+ errors.push(...collectionErrors.map(err => `${collection.name}: ${err}`));
264
+
265
+ // Validate each import definition
266
+ if (collection.importDefs) {
267
+ for (let i = 0; i < collection.importDefs.length; i++) {
268
+ const importDef = collection.importDefs[i];
269
+ const importDefErrors = this.validateImportDefinition(importDef);
270
+ errors.push(
271
+ ...importDefErrors.map(
272
+ err => `${collection.name}.importDefs[${i}]: ${err}`
273
+ )
274
+ );
275
+
276
+ // Check if import file exists
277
+ try {
278
+ const fs = require("fs");
279
+ const path = require("path");
280
+ const filePath = path.resolve(appwriteFolderPath, importDef.filePath);
281
+ if (!fs.existsSync(filePath)) {
282
+ errors.push(
283
+ `${collection.name}.importDefs[${i}]: Import file not found: ${filePath}`
284
+ );
285
+ }
286
+ } catch (error) {
287
+ warnings.push(
288
+ `${collection.name}.importDefs[${i}]: Could not validate file existence: ${error}`
289
+ );
290
+ }
291
+ }
292
+ }
293
+ }
294
+
295
+ // Validate cross-collection consistency
296
+ const crossCollectionErrors = this.validateCrossCollectionConsistency(collections);
297
+ errors.push(...crossCollectionErrors);
298
+
299
+ return {
300
+ errors,
301
+ warnings,
302
+ isValid: errors.length === 0,
303
+ };
304
+ }
305
+
306
+ /**
307
+ * Validates import progress and data integrity during import.
308
+ * Can be used for periodic validation during long-running imports.
309
+ *
310
+ * @param processedItems - Number of items processed so far
311
+ * @param totalItems - Total number of items to process
312
+ * @param errorCount - Number of errors encountered
313
+ * @returns Validation status with recommendations
314
+ */
315
+ validateImportProgress(
316
+ processedItems: number,
317
+ totalItems: number,
318
+ errorCount: number
319
+ ): {
320
+ status: "healthy" | "warning" | "critical";
321
+ message: string;
322
+ shouldContinue: boolean;
323
+ } {
324
+ const errorRate = errorCount / Math.max(processedItems, 1);
325
+ const progress = processedItems / totalItems;
326
+
327
+ if (errorRate > 0.5) {
328
+ return {
329
+ status: "critical",
330
+ message: `Error rate too high: ${(errorRate * 100).toFixed(1)}%. Consider stopping import.`,
331
+ shouldContinue: false,
332
+ };
333
+ }
334
+
335
+ if (errorRate > 0.1) {
336
+ return {
337
+ status: "warning",
338
+ message: `Elevated error rate: ${(errorRate * 100).toFixed(1)}%. Monitor closely.`,
339
+ shouldContinue: true,
340
+ };
341
+ }
342
+
343
+ return {
344
+ status: "healthy",
345
+ message: `Import progressing normally: ${(progress * 100).toFixed(1)}% complete, ${(errorRate * 100).toFixed(1)}% error rate.`,
346
+ shouldContinue: true,
347
+ };
348
+ }
349
+ }