appwrite-utils-cli 1.11.0 → 1.12.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.
Files changed (250) hide show
  1. package/{src/adapters/index.ts → dist/adapters/index.d.ts} +0 -1
  2. package/dist/adapters/index.js +10 -0
  3. package/dist/backups/operations/bucketBackup.d.ts +19 -0
  4. package/dist/backups/operations/bucketBackup.js +197 -0
  5. package/dist/backups/operations/collectionBackup.d.ts +30 -0
  6. package/dist/backups/operations/collectionBackup.js +201 -0
  7. package/dist/backups/operations/comprehensiveBackup.d.ts +25 -0
  8. package/dist/backups/operations/comprehensiveBackup.js +238 -0
  9. package/dist/backups/schemas/bucketManifest.d.ts +93 -0
  10. package/dist/backups/schemas/bucketManifest.js +33 -0
  11. package/dist/backups/schemas/comprehensiveManifest.d.ts +108 -0
  12. package/dist/backups/schemas/comprehensiveManifest.js +32 -0
  13. package/dist/backups/tracking/centralizedTracking.d.ts +34 -0
  14. package/dist/backups/tracking/centralizedTracking.js +274 -0
  15. package/dist/cli/commands/configCommands.d.ts +8 -0
  16. package/dist/cli/commands/configCommands.js +210 -0
  17. package/dist/cli/commands/databaseCommands.d.ts +14 -0
  18. package/dist/cli/commands/databaseCommands.js +696 -0
  19. package/dist/cli/commands/functionCommands.d.ts +7 -0
  20. package/dist/cli/commands/functionCommands.js +330 -0
  21. package/dist/cli/commands/importFileCommands.d.ts +7 -0
  22. package/dist/cli/commands/importFileCommands.js +674 -0
  23. package/dist/cli/commands/schemaCommands.d.ts +7 -0
  24. package/dist/cli/commands/schemaCommands.js +169 -0
  25. package/dist/cli/commands/storageCommands.d.ts +5 -0
  26. package/dist/cli/commands/storageCommands.js +142 -0
  27. package/dist/cli/commands/transferCommands.d.ts +5 -0
  28. package/dist/cli/commands/transferCommands.js +382 -0
  29. package/dist/collections/columns.d.ts +13 -0
  30. package/dist/collections/columns.js +1339 -0
  31. package/dist/collections/indexes.d.ts +12 -0
  32. package/dist/collections/indexes.js +215 -0
  33. package/dist/collections/methods.d.ts +19 -0
  34. package/dist/collections/methods.js +605 -0
  35. package/dist/collections/tableOperations.d.ts +87 -0
  36. package/dist/collections/tableOperations.js +466 -0
  37. package/dist/collections/transferOperations.d.ts +8 -0
  38. package/dist/collections/transferOperations.js +411 -0
  39. package/dist/collections/wipeOperations.d.ts +17 -0
  40. package/dist/collections/wipeOperations.js +306 -0
  41. package/dist/databases/methods.d.ts +6 -0
  42. package/dist/databases/methods.js +35 -0
  43. package/dist/databases/setup.d.ts +5 -0
  44. package/dist/databases/setup.js +45 -0
  45. package/dist/examples/yamlTerminologyExample.d.ts +42 -0
  46. package/dist/examples/yamlTerminologyExample.js +272 -0
  47. package/dist/functions/deployments.d.ts +4 -0
  48. package/dist/functions/deployments.js +146 -0
  49. package/dist/functions/fnConfigDiscovery.d.ts +3 -0
  50. package/dist/functions/fnConfigDiscovery.js +108 -0
  51. package/dist/functions/methods.d.ts +16 -0
  52. package/dist/functions/methods.js +174 -0
  53. package/dist/init.d.ts +2 -0
  54. package/dist/init.js +57 -0
  55. package/dist/interactiveCLI.d.ts +36 -0
  56. package/dist/interactiveCLI.js +952 -0
  57. package/dist/main.d.ts +2 -0
  58. package/dist/main.js +1125 -0
  59. package/dist/migrations/afterImportActions.d.ts +17 -0
  60. package/dist/migrations/afterImportActions.js +305 -0
  61. package/dist/migrations/appwriteToX.d.ts +211 -0
  62. package/dist/migrations/appwriteToX.js +493 -0
  63. package/dist/migrations/comprehensiveTransfer.d.ts +147 -0
  64. package/dist/migrations/comprehensiveTransfer.js +1315 -0
  65. package/dist/migrations/dataLoader.d.ts +755 -0
  66. package/dist/migrations/dataLoader.js +1272 -0
  67. package/dist/migrations/importController.d.ts +25 -0
  68. package/dist/migrations/importController.js +283 -0
  69. package/dist/migrations/importDataActions.d.ts +50 -0
  70. package/dist/migrations/importDataActions.js +230 -0
  71. package/dist/migrations/relationships.d.ts +29 -0
  72. package/dist/migrations/relationships.js +203 -0
  73. package/dist/migrations/services/DataTransformationService.d.ts +55 -0
  74. package/dist/migrations/services/DataTransformationService.js +158 -0
  75. package/dist/migrations/services/FileHandlerService.d.ts +75 -0
  76. package/dist/migrations/services/FileHandlerService.js +236 -0
  77. package/dist/migrations/services/ImportOrchestrator.d.ts +99 -0
  78. package/dist/migrations/services/ImportOrchestrator.js +493 -0
  79. package/dist/migrations/services/RateLimitManager.d.ts +138 -0
  80. package/dist/migrations/services/RateLimitManager.js +279 -0
  81. package/dist/migrations/services/RelationshipResolver.d.ts +120 -0
  82. package/dist/migrations/services/RelationshipResolver.js +332 -0
  83. package/dist/migrations/services/UserMappingService.d.ts +109 -0
  84. package/dist/migrations/services/UserMappingService.js +277 -0
  85. package/dist/migrations/services/ValidationService.d.ts +74 -0
  86. package/dist/migrations/services/ValidationService.js +260 -0
  87. package/dist/migrations/transfer.d.ts +30 -0
  88. package/dist/migrations/transfer.js +661 -0
  89. package/dist/migrations/yaml/YamlImportConfigLoader.d.ts +131 -0
  90. package/dist/migrations/yaml/YamlImportConfigLoader.js +383 -0
  91. package/dist/migrations/yaml/YamlImportIntegration.d.ts +93 -0
  92. package/dist/migrations/yaml/YamlImportIntegration.js +341 -0
  93. package/dist/migrations/yaml/generateImportSchemas.d.ts +30 -0
  94. package/dist/migrations/yaml/generateImportSchemas.js +1327 -0
  95. package/dist/schemas/authUser.d.ts +24 -0
  96. package/dist/schemas/authUser.js +17 -0
  97. package/dist/setup.d.ts +2 -0
  98. package/{src/setup.ts → dist/setup.js} +0 -3
  99. package/dist/setupCommands.d.ts +58 -0
  100. package/dist/setupCommands.js +489 -0
  101. package/dist/setupController.d.ts +9 -0
  102. package/dist/setupController.js +34 -0
  103. package/dist/shared/backupMetadataSchema.d.ts +94 -0
  104. package/dist/shared/backupMetadataSchema.js +38 -0
  105. package/dist/shared/backupTracking.d.ts +18 -0
  106. package/dist/shared/backupTracking.js +176 -0
  107. package/dist/shared/confirmationDialogs.d.ts +75 -0
  108. package/dist/shared/confirmationDialogs.js +236 -0
  109. package/dist/shared/migrationHelpers.d.ts +61 -0
  110. package/dist/shared/migrationHelpers.js +145 -0
  111. package/{src/shared/operationLogger.ts → dist/shared/operationLogger.d.ts} +1 -11
  112. package/dist/shared/operationLogger.js +12 -0
  113. package/dist/shared/operationQueue.d.ts +40 -0
  114. package/dist/shared/operationQueue.js +310 -0
  115. package/dist/shared/operationsTable.d.ts +26 -0
  116. package/dist/shared/operationsTable.js +287 -0
  117. package/dist/shared/operationsTableSchema.d.ts +48 -0
  118. package/dist/shared/operationsTableSchema.js +35 -0
  119. package/dist/shared/progressManager.d.ts +62 -0
  120. package/dist/shared/progressManager.js +215 -0
  121. package/dist/shared/relationshipExtractor.d.ts +56 -0
  122. package/dist/shared/relationshipExtractor.js +138 -0
  123. package/dist/shared/selectionDialogs.d.ts +220 -0
  124. package/dist/shared/selectionDialogs.js +588 -0
  125. package/dist/storage/backupCompression.d.ts +20 -0
  126. package/dist/storage/backupCompression.js +67 -0
  127. package/dist/storage/methods.d.ts +44 -0
  128. package/dist/storage/methods.js +475 -0
  129. package/dist/storage/schemas.d.ts +842 -0
  130. package/dist/storage/schemas.js +175 -0
  131. package/dist/tables/indexManager.d.ts +65 -0
  132. package/dist/tables/indexManager.js +294 -0
  133. package/{src/types.ts → dist/types.d.ts} +1 -6
  134. package/dist/types.js +3 -0
  135. package/dist/users/methods.d.ts +16 -0
  136. package/dist/users/methods.js +276 -0
  137. package/dist/utils/configMigration.d.ts +1 -0
  138. package/dist/utils/configMigration.js +261 -0
  139. package/dist/utils/index.js +2 -0
  140. package/dist/utils/loadConfigs.d.ts +50 -0
  141. package/dist/utils/loadConfigs.js +357 -0
  142. package/dist/utils/setupFiles.d.ts +4 -0
  143. package/dist/utils/setupFiles.js +1190 -0
  144. package/dist/utilsController.d.ts +114 -0
  145. package/dist/utilsController.js +898 -0
  146. package/package.json +6 -3
  147. package/CHANGELOG.md +0 -35
  148. package/CONFIG_TODO.md +0 -1189
  149. package/SELECTION_DIALOGS.md +0 -146
  150. package/SERVICE_IMPLEMENTATION_REPORT.md +0 -462
  151. package/scripts/copy-templates.ts +0 -23
  152. package/src/backups/operations/bucketBackup.ts +0 -277
  153. package/src/backups/operations/collectionBackup.ts +0 -310
  154. package/src/backups/operations/comprehensiveBackup.ts +0 -342
  155. package/src/backups/schemas/bucketManifest.ts +0 -78
  156. package/src/backups/schemas/comprehensiveManifest.ts +0 -76
  157. package/src/backups/tracking/centralizedTracking.ts +0 -352
  158. package/src/cli/commands/configCommands.ts +0 -265
  159. package/src/cli/commands/databaseCommands.ts +0 -931
  160. package/src/cli/commands/functionCommands.ts +0 -419
  161. package/src/cli/commands/importFileCommands.ts +0 -815
  162. package/src/cli/commands/schemaCommands.ts +0 -200
  163. package/src/cli/commands/storageCommands.ts +0 -151
  164. package/src/cli/commands/transferCommands.ts +0 -454
  165. package/src/collections/attributes.ts.backup +0 -1555
  166. package/src/collections/columns.ts +0 -2025
  167. package/src/collections/indexes.ts +0 -350
  168. package/src/collections/methods.ts +0 -714
  169. package/src/collections/tableOperations.ts +0 -542
  170. package/src/collections/transferOperations.ts +0 -589
  171. package/src/collections/wipeOperations.ts +0 -449
  172. package/src/databases/methods.ts +0 -49
  173. package/src/databases/setup.ts +0 -77
  174. package/src/examples/yamlTerminologyExample.ts +0 -346
  175. package/src/functions/deployments.ts +0 -221
  176. package/src/functions/fnConfigDiscovery.ts +0 -103
  177. package/src/functions/methods.ts +0 -284
  178. package/src/init.ts +0 -62
  179. package/src/interactiveCLI.ts +0 -1201
  180. package/src/main.ts +0 -1517
  181. package/src/migrations/afterImportActions.ts +0 -579
  182. package/src/migrations/appwriteToX.ts +0 -668
  183. package/src/migrations/comprehensiveTransfer.ts +0 -2285
  184. package/src/migrations/dataLoader.ts +0 -1729
  185. package/src/migrations/importController.ts +0 -440
  186. package/src/migrations/importDataActions.ts +0 -315
  187. package/src/migrations/relationships.ts +0 -333
  188. package/src/migrations/services/DataTransformationService.ts +0 -196
  189. package/src/migrations/services/FileHandlerService.ts +0 -311
  190. package/src/migrations/services/ImportOrchestrator.ts +0 -675
  191. package/src/migrations/services/RateLimitManager.ts +0 -363
  192. package/src/migrations/services/RelationshipResolver.ts +0 -461
  193. package/src/migrations/services/UserMappingService.ts +0 -345
  194. package/src/migrations/services/ValidationService.ts +0 -349
  195. package/src/migrations/transfer.ts +0 -1113
  196. package/src/migrations/yaml/YamlImportConfigLoader.ts +0 -439
  197. package/src/migrations/yaml/YamlImportIntegration.ts +0 -446
  198. package/src/migrations/yaml/generateImportSchemas.ts +0 -1354
  199. package/src/schemas/authUser.ts +0 -23
  200. package/src/setupCommands.ts +0 -602
  201. package/src/setupController.ts +0 -43
  202. package/src/shared/backupMetadataSchema.ts +0 -93
  203. package/src/shared/backupTracking.ts +0 -211
  204. package/src/shared/confirmationDialogs.ts +0 -327
  205. package/src/shared/migrationHelpers.ts +0 -232
  206. package/src/shared/operationQueue.ts +0 -376
  207. package/src/shared/operationsTable.ts +0 -338
  208. package/src/shared/operationsTableSchema.ts +0 -60
  209. package/src/shared/progressManager.ts +0 -278
  210. package/src/shared/relationshipExtractor.ts +0 -214
  211. package/src/shared/selectionDialogs.ts +0 -802
  212. package/src/storage/backupCompression.ts +0 -88
  213. package/src/storage/methods.ts +0 -711
  214. package/src/storage/schemas.ts +0 -205
  215. package/src/tables/indexManager.ts +0 -409
  216. package/src/types/node-appwrite-tablesdb.d.ts +0 -44
  217. package/src/users/methods.ts +0 -358
  218. package/src/utils/configMigration.ts +0 -348
  219. package/src/utils/loadConfigs.ts +0 -457
  220. package/src/utils/setupFiles.ts +0 -1236
  221. package/src/utilsController.ts +0 -1263
  222. package/tests/README.md +0 -497
  223. package/tests/adapters/AdapterFactory.test.ts +0 -277
  224. package/tests/integration/syncOperations.test.ts +0 -463
  225. package/tests/jest.config.js +0 -25
  226. package/tests/migration/configMigration.test.ts +0 -546
  227. package/tests/setup.ts +0 -62
  228. package/tests/testUtils.ts +0 -340
  229. package/tests/utils/loadConfigs.test.ts +0 -350
  230. package/tests/validation/configValidation.test.ts +0 -412
  231. package/tsconfig.json +0 -44
  232. /package/{src → dist}/functions/templates/count-docs-in-collection/README.md +0 -0
  233. /package/{src → dist}/functions/templates/count-docs-in-collection/src/main.ts +0 -0
  234. /package/{src → dist}/functions/templates/count-docs-in-collection/src/request.ts +0 -0
  235. /package/{src → dist}/functions/templates/hono-typescript/README.md +0 -0
  236. /package/{src → dist}/functions/templates/hono-typescript/src/adapters/request.ts +0 -0
  237. /package/{src → dist}/functions/templates/hono-typescript/src/adapters/response.ts +0 -0
  238. /package/{src → dist}/functions/templates/hono-typescript/src/app.ts +0 -0
  239. /package/{src → dist}/functions/templates/hono-typescript/src/context.ts +0 -0
  240. /package/{src → dist}/functions/templates/hono-typescript/src/main.ts +0 -0
  241. /package/{src → dist}/functions/templates/hono-typescript/src/middleware/appwrite.ts +0 -0
  242. /package/{src → dist}/functions/templates/typescript-node/README.md +0 -0
  243. /package/{src → dist}/functions/templates/typescript-node/src/context.ts +0 -0
  244. /package/{src → dist}/functions/templates/typescript-node/src/main.ts +0 -0
  245. /package/{src → dist}/functions/templates/uv/README.md +0 -0
  246. /package/{src → dist}/functions/templates/uv/pyproject.toml +0 -0
  247. /package/{src → dist}/functions/templates/uv/src/__init__.py +0 -0
  248. /package/{src → dist}/functions/templates/uv/src/context.py +0 -0
  249. /package/{src → dist}/functions/templates/uv/src/main.py +0 -0
  250. /package/{src/utils/index.ts → dist/utils/index.d.ts} +0 -0
@@ -0,0 +1,203 @@
1
+ import { Databases, Query } from "node-appwrite";
2
+ import { fetchAllCollections } from "../collections/methods.js";
3
+ import { logger, MessageFormatter } from "appwrite-utils-helpers";
4
+ /**
5
+ * Finds collections that have defined relationship attributes.
6
+ */
7
+ export const findCollectionsWithRelationships = (config) => {
8
+ const toReturn = new Map();
9
+ if (!config.collections) {
10
+ return toReturn;
11
+ }
12
+ for (const collection of config.collections) {
13
+ if (collection.attributes) {
14
+ for (const attribute of collection.attributes) {
15
+ if (attribute.type === "relationship" &&
16
+ attribute.twoWay &&
17
+ attribute.side === "parent") {
18
+ toReturn.set(collection.name, toReturn.get(collection.name) || []);
19
+ toReturn
20
+ .get(collection.name)
21
+ ?.push(attribute);
22
+ }
23
+ }
24
+ }
25
+ }
26
+ return toReturn;
27
+ };
28
+ export async function resolveAndUpdateRelationships(dbId, database, config) {
29
+ const collections = await fetchAllCollections(dbId, database);
30
+ const collectionsWithRelationships = findCollectionsWithRelationships(config);
31
+ // Process each collection sequentially
32
+ for (const collection of collections) {
33
+ MessageFormatter.processing(`Processing collection: ${collection.name} (${collection.$id})`, { prefix: "Migration" });
34
+ const relAttributeMap = collectionsWithRelationships.get(collection.name); // Get the relationship attributes for the collections
35
+ if (!relAttributeMap) {
36
+ MessageFormatter.info(`No mapping found for collection: ${collection.name}, skipping...`, { prefix: "Migration" });
37
+ continue;
38
+ }
39
+ await processCollection(dbId, database, collection, relAttributeMap);
40
+ }
41
+ MessageFormatter.success(`Completed relationship resolution and update for database ID: ${dbId}`, { prefix: "Migration" });
42
+ }
43
+ async function processCollection(dbId, database, collection, relAttributeMap) {
44
+ let after; // For pagination
45
+ let hasMore = true;
46
+ while (hasMore) {
47
+ const response = await database.listDocuments(dbId, collection.$id, [
48
+ Query.limit(100), // Fetch documents in batches of 100
49
+ ...(after ? [Query.cursorAfter(after)] : []),
50
+ ]);
51
+ const documents = response.documents;
52
+ MessageFormatter.info(`Fetched ${documents.length} documents from collection: ${collection.name}`, { prefix: "Migration" });
53
+ if (documents.length > 0) {
54
+ const updates = await prepareDocumentUpdates(database, dbId, collection.name, documents, relAttributeMap);
55
+ // Execute updates for the current batch
56
+ await executeUpdatesInBatches(dbId, database, updates);
57
+ }
58
+ if (documents.length === 100) {
59
+ after = documents[documents.length - 1].$id; // Prepare for the next page
60
+ }
61
+ else {
62
+ hasMore = false; // No more documents to fetch
63
+ }
64
+ }
65
+ }
66
+ async function findDocumentsByOriginalId(database, dbId, targetCollection, targetKey, originalId) {
67
+ const relatedCollectionId = targetCollection.$id;
68
+ const collection = await database.listCollections(dbId, [
69
+ Query.equal("$id", relatedCollectionId),
70
+ ]);
71
+ if (collection.total === 0) {
72
+ MessageFormatter.warning(`Collection ${relatedCollectionId} doesn't exist, skipping...`, { prefix: "Migration" });
73
+ return undefined;
74
+ }
75
+ const targetAttr = collection.collections[0].attributes.find(
76
+ // @ts-ignore
77
+ (attr) => attr.key === targetKey);
78
+ if (!targetAttr) {
79
+ MessageFormatter.warning(`Attribute ${targetKey} not found in collection ${relatedCollectionId}, skipping...`, { prefix: "Migration" });
80
+ return undefined;
81
+ }
82
+ let queries = [];
83
+ if (targetAttr.array) {
84
+ // @ts-ignore
85
+ queries.push(Query.contains(targetKey, originalId));
86
+ }
87
+ else {
88
+ queries.push(Query.equal(targetKey, originalId));
89
+ }
90
+ const response = await database.listDocuments(dbId, relatedCollectionId, [
91
+ ...queries,
92
+ Query.limit(500), // Adjust the limit based on your needs or implement pagination
93
+ ]);
94
+ if (response.documents.length < 0) {
95
+ return undefined;
96
+ }
97
+ else if (response.documents.length > 0) {
98
+ return response.documents;
99
+ }
100
+ else {
101
+ return undefined;
102
+ }
103
+ }
104
+ async function prepareDocumentUpdates(database, dbId, collectionName, documents, relationships) {
105
+ MessageFormatter.processing(`Preparing updates for collection: ${collectionName}`, { prefix: "Migration" });
106
+ const updates = [];
107
+ const thisCollection = (await database.listCollections(dbId, [Query.equal("name", collectionName)])).collections[0];
108
+ const thisCollectionId = thisCollection?.$id;
109
+ if (!thisCollectionId) {
110
+ MessageFormatter.warning(`No collection found with name: ${collectionName}`, { prefix: "Migration" });
111
+ return [];
112
+ }
113
+ for (const doc of documents) {
114
+ let updatePayload = {};
115
+ for (const rel of relationships) {
116
+ // Skip if not dealing with the parent side of a two-way relationship
117
+ if (rel.twoWay && rel.side !== "parent") {
118
+ MessageFormatter.info("Skipping non-parent side of two-way relationship...", { prefix: "Migration" });
119
+ continue;
120
+ }
121
+ const isSingleReference = rel.relationType === "oneToOne" || rel.relationType === "manyToOne";
122
+ const originalIdField = rel.importMapping?.originalIdField;
123
+ const targetField = rel.importMapping?.targetField || originalIdField; // Use originalIdField if targetField is not specified
124
+ if (!originalIdField) {
125
+ MessageFormatter.warning("Missing originalIdField in importMapping, skipping...", { prefix: "Migration" });
126
+ continue;
127
+ }
128
+ const originalId = doc[originalIdField];
129
+ if (!originalId) {
130
+ continue;
131
+ }
132
+ const relatedCollection = (await database.listCollections(dbId, [
133
+ Query.equal("name", rel.relatedCollection),
134
+ ])).collections[0];
135
+ if (!relatedCollection) {
136
+ MessageFormatter.warning(`Related collection ${rel.relatedCollection} not found, skipping...`, { prefix: "Migration" });
137
+ continue;
138
+ }
139
+ const foundDocuments = await findDocumentsByOriginalId(database, dbId, relatedCollection, targetField, String(originalId));
140
+ if (foundDocuments && foundDocuments.length > 0) {
141
+ const relationshipKey = rel.key;
142
+ const existingRefs = doc[relationshipKey] || [];
143
+ let existingRefIds = [];
144
+ if (Array.isArray(existingRefs)) {
145
+ // @ts-ignore
146
+ existingRefIds = existingRefs.map((ref) => ref.$id);
147
+ }
148
+ else if (existingRefs) {
149
+ // @ts-ignore
150
+ existingRefIds = [existingRefs.$id];
151
+ }
152
+ const newRefs = foundDocuments.map((fd) => fd.$id);
153
+ const allRefs = [...new Set([...existingRefIds, ...newRefs])]; // Combine and remove duplicates
154
+ // Update logic based on the relationship cardinality
155
+ updatePayload[relationshipKey] = isSingleReference
156
+ ? newRefs[0] || existingRefIds[0]
157
+ : allRefs;
158
+ MessageFormatter.info(`Updating ${relationshipKey} with ${allRefs.length} refs`, { prefix: "Migration" });
159
+ }
160
+ }
161
+ if (Object.keys(updatePayload).length > 0) {
162
+ updates.push({
163
+ collectionId: thisCollectionId,
164
+ documentId: doc.$id,
165
+ updatePayload: updatePayload,
166
+ });
167
+ }
168
+ }
169
+ return updates;
170
+ }
171
+ async function processInBatches(items, batchSize, processFunction) {
172
+ const maxParallelBatches = 25; // Adjust this value to control the number of parallel batches
173
+ let currentIndex = 0;
174
+ let activeBatchPromises = [];
175
+ while (currentIndex < items.length) {
176
+ // While there's still data to process and we haven't reached our parallel limit
177
+ while (currentIndex < items.length &&
178
+ activeBatchPromises.length < maxParallelBatches) {
179
+ const batch = items.slice(currentIndex, currentIndex + batchSize);
180
+ currentIndex += batchSize;
181
+ // Add new batch processing promise to the array
182
+ activeBatchPromises.push(processFunction(batch));
183
+ }
184
+ // Wait for one of the batch processes to complete
185
+ await Promise.race(activeBatchPromises).then(() => {
186
+ // Remove the resolved promise from the activeBatchPromises array
187
+ activeBatchPromises = activeBatchPromises.filter((p) => p !== Promise.race(activeBatchPromises));
188
+ });
189
+ }
190
+ // After processing all batches, ensure all active promises are resolved
191
+ await Promise.all(activeBatchPromises);
192
+ }
193
+ async function executeUpdatesInBatches(dbId, database, updates) {
194
+ const batchSize = 25; // Adjust based on your rate limit and performance testing
195
+ for (let i = 0; i < updates.length; i += batchSize) {
196
+ const batch = updates.slice(i, i + batchSize);
197
+ await Promise.all(batch.map((update) => database
198
+ .updateDocument(dbId, update.collectionId, update.documentId, update.updatePayload)
199
+ .catch((error) => {
200
+ logger.error(`Error updating doc ${update.documentId} in ${dbId}, update payload: ${JSON.stringify(update.updatePayload, undefined, 4)}, error: ${error}`);
201
+ })));
202
+ }
203
+ }
@@ -0,0 +1,55 @@
1
+ import type { AttributeMappings, ConfigDatabase, CollectionCreate } from "appwrite-utils";
2
+ import type { ImportDataActions } from "../importDataActions.js";
3
+ /**
4
+ * Service responsible for data transformation during import.
5
+ * Extracted from DataLoader to provide focused, testable transformation logic.
6
+ */
7
+ export declare class DataTransformationService {
8
+ private importDataActions;
9
+ constructor(importDataActions: ImportDataActions);
10
+ /**
11
+ * Transforms the given item based on the provided attribute mappings.
12
+ * This method applies conversion rules to the item's attributes as defined in the attribute mappings.
13
+ *
14
+ * Preserves existing transformation logic from DataLoader.
15
+ *
16
+ * @param item - The item to be transformed.
17
+ * @param attributeMappings - The mappings that define how each attribute should be transformed.
18
+ * @returns The transformed item.
19
+ */
20
+ transformData(item: any, attributeMappings: AttributeMappings): any;
21
+ /**
22
+ * Creates a context object for data transformation.
23
+ * Preserves existing context creation logic from DataLoader.
24
+ *
25
+ * @param db - The database configuration
26
+ * @param collection - The collection configuration
27
+ * @param item - The raw item data
28
+ * @param docId - The document ID
29
+ * @returns Context object for transformation
30
+ */
31
+ createContext(db: ConfigDatabase, collection: CollectionCreate, item: any, docId: string): any;
32
+ /**
33
+ * Merges two objects by updating the source object with the target object's values.
34
+ * Preserves existing merge logic from DataLoader.
35
+ *
36
+ * It iterates through the target object's keys and updates the source object if:
37
+ * - The source object has the key.
38
+ * - The target object's value for that key is not null, undefined, or an empty string.
39
+ * - If the target object has an array value, it concatenates the values and removes duplicates.
40
+ *
41
+ * @param source - The source object to be updated.
42
+ * @param update - The target object with values to update the source object.
43
+ * @returns The updated source object.
44
+ */
45
+ mergeObjects(source: any, update: any): any;
46
+ /**
47
+ * Validates the transformed data item using existing validation logic.
48
+ *
49
+ * @param transformedData - The transformed data to validate
50
+ * @param attributeMappings - The attribute mappings containing validation rules
51
+ * @param context - The context for validation
52
+ * @returns True if valid, false otherwise
53
+ */
54
+ validateTransformedData(transformedData: any, attributeMappings: AttributeMappings, context: any): boolean;
55
+ }
@@ -0,0 +1,158 @@
1
+ import { convertObjectByAttributeMappings } from "appwrite-utils-helpers";
2
+ import { logger } from 'appwrite-utils-helpers';
3
+ /**
4
+ * Service responsible for data transformation during import.
5
+ * Extracted from DataLoader to provide focused, testable transformation logic.
6
+ */
7
+ export class DataTransformationService {
8
+ importDataActions;
9
+ constructor(importDataActions) {
10
+ this.importDataActions = importDataActions;
11
+ }
12
+ /**
13
+ * Transforms the given item based on the provided attribute mappings.
14
+ * This method applies conversion rules to the item's attributes as defined in the attribute mappings.
15
+ *
16
+ * Preserves existing transformation logic from DataLoader.
17
+ *
18
+ * @param item - The item to be transformed.
19
+ * @param attributeMappings - The mappings that define how each attribute should be transformed.
20
+ * @returns The transformed item.
21
+ */
22
+ transformData(item, attributeMappings) {
23
+ try {
24
+ // Convert the item using the attribute mappings provided
25
+ const convertedItem = convertObjectByAttributeMappings(item, attributeMappings);
26
+ // Run additional converter functions on the converted item, if any
27
+ return this.importDataActions.runConverterFunctions(convertedItem, attributeMappings);
28
+ }
29
+ catch (error) {
30
+ logger.error(`Error transforming data for item: ${JSON.stringify(item, null, 2)}`, error);
31
+ throw error;
32
+ }
33
+ }
34
+ /**
35
+ * Creates a context object for data transformation.
36
+ * Preserves existing context creation logic from DataLoader.
37
+ *
38
+ * @param db - The database configuration
39
+ * @param collection - The collection configuration
40
+ * @param item - The raw item data
41
+ * @param docId - The document ID
42
+ * @returns Context object for transformation
43
+ */
44
+ createContext(db, collection, item, docId) {
45
+ return {
46
+ ...item, // Spread the item data for easy access to its properties
47
+ dbId: db.$id,
48
+ dbName: db.name,
49
+ collId: collection.$id,
50
+ collName: collection.name,
51
+ docId: docId,
52
+ createdDoc: {}, // Initially empty, to be updated when the document is created
53
+ };
54
+ }
55
+ /**
56
+ * Merges two objects by updating the source object with the target object's values.
57
+ * Preserves existing merge logic from DataLoader.
58
+ *
59
+ * It iterates through the target object's keys and updates the source object if:
60
+ * - The source object has the key.
61
+ * - The target object's value for that key is not null, undefined, or an empty string.
62
+ * - If the target object has an array value, it concatenates the values and removes duplicates.
63
+ *
64
+ * @param source - The source object to be updated.
65
+ * @param update - The target object with values to update the source object.
66
+ * @returns The updated source object.
67
+ */
68
+ mergeObjects(source, update) {
69
+ // Create a new object to hold the merged result
70
+ const result = { ...source };
71
+ // Loop through the keys of the object we care about
72
+ for (const [key, value] of Object.entries(source)) {
73
+ // Check if the key exists in the target object
74
+ if (!Object.hasOwn(update, key)) {
75
+ // If the key doesn't exist, we can just skip it
76
+ continue;
77
+ }
78
+ if (update[key] === value) {
79
+ continue;
80
+ }
81
+ // If the value ain't here, we can just do whatever man
82
+ if (value === undefined || value === null || value === "") {
83
+ // If the update key is defined
84
+ if (update[key] !== undefined &&
85
+ update[key] !== null &&
86
+ update[key] !== "") {
87
+ // might as well use it eh?
88
+ result[key] = update[key];
89
+ }
90
+ // ELSE if the value is an array, because it would then not be === to those things above
91
+ }
92
+ else if (Array.isArray(value)) {
93
+ // Get the update value
94
+ const updateValue = update[key];
95
+ // If the update value is an array, concatenate and remove duplicates
96
+ // and poopy data
97
+ if (Array.isArray(updateValue)) {
98
+ result[key] = [...new Set([...value, ...updateValue])].filter((item) => item !== null && item !== undefined && item !== "");
99
+ }
100
+ else {
101
+ // If the update value is not an array, just use it
102
+ result[key] = [...value, updateValue].filter((item) => item !== null && item !== undefined && item !== "");
103
+ }
104
+ }
105
+ else if (typeof value === "object" && !Array.isArray(value)) {
106
+ // If the value is an object, we need to merge it
107
+ if (typeof update[key] === "object" && !Array.isArray(update[key])) {
108
+ result[key] = this.mergeObjects(value, update[key]);
109
+ }
110
+ }
111
+ else {
112
+ // Finally, the source value is defined, and not an array, so we don't care about the update value
113
+ continue;
114
+ }
115
+ }
116
+ // Because the objects should technically always be validated FIRST, we can assume the update keys are also defined on the source object
117
+ for (const [key, value] of Object.entries(update)) {
118
+ if (value === undefined || value === null || value === "") {
119
+ continue;
120
+ }
121
+ else if (!Object.hasOwn(source, key)) {
122
+ result[key] = value;
123
+ }
124
+ else if (typeof source[key] === "object" &&
125
+ typeof value === "object" &&
126
+ !Array.isArray(source[key]) &&
127
+ !Array.isArray(value)) {
128
+ result[key] = this.mergeObjects(source[key], value);
129
+ }
130
+ else if (Array.isArray(source[key]) && Array.isArray(value)) {
131
+ result[key] = [...new Set([...source[key], ...value])].filter((item) => item !== null && item !== undefined && item !== "");
132
+ }
133
+ else if (source[key] === undefined ||
134
+ source[key] === null ||
135
+ source[key] === "") {
136
+ result[key] = value;
137
+ }
138
+ }
139
+ return result;
140
+ }
141
+ /**
142
+ * Validates the transformed data item using existing validation logic.
143
+ *
144
+ * @param transformedData - The transformed data to validate
145
+ * @param attributeMappings - The attribute mappings containing validation rules
146
+ * @param context - The context for validation
147
+ * @returns True if valid, false otherwise
148
+ */
149
+ validateTransformedData(transformedData, attributeMappings, context) {
150
+ try {
151
+ return this.importDataActions.validateItem(transformedData, attributeMappings, context);
152
+ }
153
+ catch (error) {
154
+ logger.error(`Validation error for transformed data: ${JSON.stringify(transformedData, null, 2)}`, error);
155
+ return false;
156
+ }
157
+ }
158
+ }
@@ -0,0 +1,75 @@
1
+ import type { AttributeMappings, AppwriteConfig } from "appwrite-utils";
2
+ import type { ImportDataActions } from "../importDataActions.js";
3
+ import { RateLimitManager } from "./RateLimitManager.js";
4
+ /**
5
+ * Service responsible for file handling during import.
6
+ * Preserves all existing file handling capabilities including URL support.
7
+ * Extracted from DataLoader to provide focused, testable file operations.
8
+ */
9
+ export declare class FileHandlerService {
10
+ private appwriteFolderPath;
11
+ private config;
12
+ private importDataActions;
13
+ private rateLimitManager;
14
+ constructor(appwriteFolderPath: string, config: AppwriteConfig, importDataActions: ImportDataActions, rateLimitManager?: RateLimitManager);
15
+ /**
16
+ * Generates attribute mappings with post-import actions based on the provided attribute mappings.
17
+ * This method checks each mapping for a fileData attribute and adds a post-import action to create a file
18
+ * and update the field with the file's ID if necessary.
19
+ *
20
+ * Preserves existing file handling logic from DataLoader.
21
+ *
22
+ * @param attributeMappings - The attribute mappings from the import definition.
23
+ * @param context - The context object containing information about the database, collection, and document.
24
+ * @param item - The item being imported, used for resolving template paths in fileData mappings.
25
+ * @returns The attribute mappings updated with any necessary post-import actions.
26
+ */
27
+ getAttributeMappingsWithFileActions(attributeMappings: AttributeMappings, context: any, item: any): AttributeMappings;
28
+ /**
29
+ * Resolves local file path, searching in subdirectories if needed.
30
+ * Preserves existing file search logic from DataLoader.
31
+ *
32
+ * @param mappingFilePath - The relative file path from the mapping
33
+ * @returns Resolved absolute file path
34
+ */
35
+ private resolveLocalFilePath;
36
+ /**
37
+ * Executes file-related post-import actions with rate limiting.
38
+ * Wraps the existing createFileAndUpdateField action with proper error handling and rate limiting.
39
+ *
40
+ * @param context - The context containing document and collection information
41
+ * @param postImportActions - The post-import actions to execute
42
+ */
43
+ executeFileActions(context: any, postImportActions: any[]): Promise<void>;
44
+ /**
45
+ * Executes a single file action with proper error handling.
46
+ *
47
+ * @param action - The file action to execute
48
+ * @param context - The context for template resolution
49
+ */
50
+ private executeFileAction;
51
+ /**
52
+ * Validates that file paths exist before import begins.
53
+ * Provides early validation to catch file issues before processing starts.
54
+ *
55
+ * @param attributeMappings - The attribute mappings to validate
56
+ * @param context - The context for template resolution
57
+ * @param item - The item for template resolution
58
+ * @returns Array of validation errors (empty if all valid)
59
+ */
60
+ validateFilePaths(attributeMappings: AttributeMappings, context: any, item: any): string[];
61
+ /**
62
+ * Gets file statistics for import planning.
63
+ * Helps estimate import time and resource requirements.
64
+ *
65
+ * @param attributeMappings - The attribute mappings to analyze
66
+ * @param items - The items that will be imported
67
+ * @returns File statistics object
68
+ */
69
+ getFileStatistics(attributeMappings: AttributeMappings, items: any[]): {
70
+ totalFiles: number;
71
+ urlFiles: number;
72
+ localFiles: number;
73
+ estimatedSize: number;
74
+ };
75
+ }