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,1315 @@
1
+ import { converterFunctions, tryAwaitWithRetry, parseAttribute, objectNeedsUpdate, } from "appwrite-utils";
2
+ import { Client, Databases, Storage, Users, Functions, Teams, Query, AppwriteException, } from "node-appwrite";
3
+ import { InputFile } from "node-appwrite/file";
4
+ import { MessageFormatter, getClient } from "appwrite-utils-helpers";
5
+ import { processQueue, queuedOperations } from "../shared/operationQueue.js";
6
+ import { ProgressManager } from "../shared/progressManager.js";
7
+ import { transferDatabaseLocalToLocal, transferDatabaseLocalToRemote, transferStorageLocalToLocal, transferStorageLocalToRemote, transferUsersLocalToRemote, } from "./transfer.js";
8
+ import { deployLocalFunction } from "../functions/deployments.js";
9
+ import { listFunctions, downloadLatestFunctionDeployment, } from "../functions/methods.js";
10
+ import pLimit from "p-limit";
11
+ import chalk from "chalk";
12
+ import { join } from "node:path";
13
+ import fs from "node:fs";
14
+ import { getAdapter, mapToCreateAttributeParams } from "appwrite-utils-helpers";
15
+ export class ComprehensiveTransfer {
16
+ options;
17
+ sourceClient;
18
+ targetClient;
19
+ sourceUsers;
20
+ targetUsers;
21
+ sourceTeams;
22
+ targetTeams;
23
+ sourceDatabases;
24
+ targetDatabases;
25
+ sourceStorage;
26
+ targetStorage;
27
+ sourceFunctions;
28
+ targetFunctions;
29
+ limit;
30
+ userLimit;
31
+ fileLimit;
32
+ results;
33
+ startTime;
34
+ tempDir;
35
+ cachedMaxFileSize; // Cache successful maximumFileSize for subsequent buckets
36
+ sourceAdapter;
37
+ targetAdapter;
38
+ constructor(options) {
39
+ this.options = options;
40
+ this.sourceClient = getClient(options.sourceEndpoint, options.sourceProject, options.sourceKey);
41
+ this.targetClient = getClient(options.targetEndpoint, options.targetProject, options.targetKey);
42
+ this.sourceUsers = new Users(this.sourceClient);
43
+ this.targetUsers = new Users(this.targetClient);
44
+ this.sourceTeams = new Teams(this.sourceClient);
45
+ this.targetTeams = new Teams(this.targetClient);
46
+ this.sourceDatabases = new Databases(this.sourceClient);
47
+ this.targetDatabases = new Databases(this.targetClient);
48
+ this.sourceStorage = new Storage(this.sourceClient);
49
+ this.targetStorage = new Storage(this.targetClient);
50
+ this.sourceFunctions = new Functions(this.sourceClient);
51
+ this.targetFunctions = new Functions(this.targetClient);
52
+ const baseLimit = options.concurrencyLimit || 10;
53
+ this.limit = pLimit(baseLimit);
54
+ // Different rate limits for different operations to prevent API throttling
55
+ // Users: Half speed (more sensitive operations)
56
+ // Files: Quarter speed (most bandwidth intensive)
57
+ this.userLimit = pLimit(Math.max(1, Math.floor(baseLimit / 2)));
58
+ this.fileLimit = pLimit(Math.max(1, Math.floor(baseLimit / 4)));
59
+ this.results = {
60
+ users: { transferred: 0, skipped: 0, failed: 0 },
61
+ teams: { transferred: 0, skipped: 0, failed: 0 },
62
+ databases: { transferred: 0, skipped: 0, failed: 0 },
63
+ buckets: { transferred: 0, skipped: 0, failed: 0 },
64
+ functions: { transferred: 0, skipped: 0, failed: 0 },
65
+ totalTime: 0,
66
+ };
67
+ this.startTime = Date.now();
68
+ this.tempDir = join(process.cwd(), ".appwrite-transfer-temp");
69
+ }
70
+ async execute() {
71
+ try {
72
+ MessageFormatter.info("Starting comprehensive transfer", {
73
+ prefix: "Transfer",
74
+ });
75
+ // Initialize adapters for unified API (TablesDB or legacy via adapter)
76
+ const source = await getAdapter(this.options.sourceEndpoint, this.options.sourceProject, this.options.sourceKey, 'auto');
77
+ const target = await getAdapter(this.options.targetEndpoint, this.options.targetProject, this.options.targetKey, 'auto');
78
+ this.sourceAdapter = source.adapter;
79
+ this.targetAdapter = target.adapter;
80
+ if (this.options.dryRun) {
81
+ MessageFormatter.info("DRY RUN MODE - No actual changes will be made", {
82
+ prefix: "Transfer",
83
+ });
84
+ }
85
+ // Show rate limiting configuration
86
+ const baseLimit = this.options.concurrencyLimit || 10;
87
+ const userLimit = Math.max(1, Math.floor(baseLimit / 2));
88
+ const fileLimit = Math.max(1, Math.floor(baseLimit / 4));
89
+ MessageFormatter.info(`Rate limits: General=${baseLimit}, Users=${userLimit}, Files=${fileLimit}`, { prefix: "Transfer" });
90
+ // Ensure temp directory exists
91
+ if (!fs.existsSync(this.tempDir)) {
92
+ fs.mkdirSync(this.tempDir, { recursive: true });
93
+ }
94
+ // Execute transfers in the correct order
95
+ if (this.options.transferUsers !== false) {
96
+ await this.transferAllUsers();
97
+ }
98
+ if (this.options.transferTeams !== false) {
99
+ await this.transferAllTeams();
100
+ }
101
+ if (this.options.transferDatabases !== false) {
102
+ await this.transferAllDatabases();
103
+ }
104
+ if (this.options.transferBuckets !== false) {
105
+ await this.transferAllBuckets();
106
+ }
107
+ if (this.options.transferFunctions !== false) {
108
+ await this.transferAllFunctions();
109
+ }
110
+ this.results.totalTime = Date.now() - this.startTime;
111
+ this.printSummary();
112
+ return this.results;
113
+ }
114
+ catch (error) {
115
+ MessageFormatter.error("Comprehensive transfer failed", error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
116
+ throw error;
117
+ }
118
+ finally {
119
+ // Clean up temp directory
120
+ if (fs.existsSync(this.tempDir)) {
121
+ fs.rmSync(this.tempDir, { recursive: true, force: true });
122
+ }
123
+ }
124
+ }
125
+ async transferAllUsers() {
126
+ MessageFormatter.info("Starting user transfer phase", {
127
+ prefix: "Transfer",
128
+ });
129
+ if (this.options.dryRun) {
130
+ const usersList = await this.sourceUsers.list([Query.limit(1)]);
131
+ MessageFormatter.info(`DRY RUN: Would transfer ${usersList.total} users`, { prefix: "Transfer" });
132
+ return;
133
+ }
134
+ try {
135
+ // Use the existing user transfer function
136
+ // Note: The rate limiting is handled at the API level, not per-user
137
+ // since user operations are already sequential in the existing implementation
138
+ await transferUsersLocalToRemote(this.sourceUsers, this.options.targetEndpoint, this.options.targetProject, this.options.targetKey);
139
+ // Get actual count for results
140
+ const usersList = await this.sourceUsers.list([Query.limit(1)]);
141
+ this.results.users.transferred = usersList.total;
142
+ MessageFormatter.success(`User transfer completed`, {
143
+ prefix: "Transfer",
144
+ });
145
+ }
146
+ catch (error) {
147
+ MessageFormatter.error("User transfer failed", error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
148
+ this.results.users.failed = 1;
149
+ }
150
+ }
151
+ async transferAllTeams() {
152
+ MessageFormatter.info("Starting team transfer phase", {
153
+ prefix: "Transfer",
154
+ });
155
+ try {
156
+ // Fetch all teams from source with pagination
157
+ const allSourceTeams = await this.fetchAllTeams(this.sourceTeams);
158
+ const allTargetTeams = await this.fetchAllTeams(this.targetTeams);
159
+ if (this.options.dryRun) {
160
+ let totalMemberships = 0;
161
+ for (const team of allSourceTeams) {
162
+ const memberships = await this.sourceTeams.listMemberships(team.$id, [
163
+ Query.limit(1),
164
+ ]);
165
+ totalMemberships += memberships.total;
166
+ }
167
+ MessageFormatter.info(`DRY RUN: Would transfer ${allSourceTeams.length} teams with ${totalMemberships} memberships`, { prefix: "Transfer" });
168
+ return;
169
+ }
170
+ const transferTasks = allSourceTeams.map((team) => this.limit(async () => {
171
+ try {
172
+ // Check if team exists in target
173
+ const existingTeam = allTargetTeams.find((tt) => tt.$id === team.$id);
174
+ if (!existingTeam) {
175
+ // Fetch all memberships to extract unique roles before creating team
176
+ MessageFormatter.info(`Fetching memberships for team ${team.name} to extract roles`, { prefix: "Transfer" });
177
+ const memberships = await this.fetchAllMemberships(team.$id);
178
+ // Extract unique roles from all memberships
179
+ const allRoles = new Set();
180
+ memberships.forEach((membership) => {
181
+ membership.roles.forEach((role) => allRoles.add(role));
182
+ });
183
+ const uniqueRoles = Array.from(allRoles);
184
+ MessageFormatter.info(`Found ${uniqueRoles.length} unique roles for team ${team.name}: ${uniqueRoles.join(", ")}`, { prefix: "Transfer" });
185
+ // Create team in target with the collected roles
186
+ await this.targetTeams.create(team.$id, team.name, uniqueRoles);
187
+ MessageFormatter.success(`Created team: ${team.name} with roles: ${uniqueRoles.join(", ")}`, { prefix: "Transfer" });
188
+ }
189
+ else {
190
+ MessageFormatter.info(`Team ${team.name} already exists, updating if needed`, { prefix: "Transfer" });
191
+ // Update team if needed
192
+ if (existingTeam.name !== team.name) {
193
+ await this.targetTeams.updateName(team.$id, team.name);
194
+ MessageFormatter.success(`Updated team name: ${team.name}`, {
195
+ prefix: "Transfer",
196
+ });
197
+ }
198
+ }
199
+ // Transfer team memberships
200
+ await this.transferTeamMemberships(team.$id);
201
+ this.results.teams.transferred++;
202
+ MessageFormatter.success(`Team ${team.name} transferred successfully`, { prefix: "Transfer" });
203
+ }
204
+ catch (error) {
205
+ MessageFormatter.error(`Team ${team.name} transfer failed`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
206
+ this.results.teams.failed++;
207
+ }
208
+ }));
209
+ await Promise.all(transferTasks);
210
+ MessageFormatter.success("Team transfer phase completed", {
211
+ prefix: "Transfer",
212
+ });
213
+ }
214
+ catch (error) {
215
+ MessageFormatter.error("Team transfer phase failed", error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
216
+ }
217
+ }
218
+ async transferAllDatabases() {
219
+ MessageFormatter.info("Starting database transfer phase", {
220
+ prefix: "Transfer",
221
+ });
222
+ try {
223
+ const sourceDatabases = await this.sourceDatabases.list();
224
+ const targetDatabases = await this.targetDatabases.list();
225
+ if (this.options.dryRun) {
226
+ MessageFormatter.info(`DRY RUN: Would transfer ${sourceDatabases.databases.length} databases`, { prefix: "Transfer" });
227
+ return;
228
+ }
229
+ // Phase 1: Create all databases and collections (structure only)
230
+ MessageFormatter.info("Phase 1: Creating database structures (databases, collections, attributes, indexes)", { prefix: "Transfer" });
231
+ const structureCreationTasks = sourceDatabases.databases.map((db) => this.limit(async () => {
232
+ try {
233
+ // Check if database exists in target
234
+ const existingDb = targetDatabases.databases.find((tdb) => tdb.$id === db.$id);
235
+ if (!existingDb) {
236
+ // Create database in target
237
+ await this.targetDatabases.create(db.$id, db.name, db.enabled);
238
+ MessageFormatter.success(`Created database: ${db.name}`, {
239
+ prefix: "Transfer",
240
+ });
241
+ }
242
+ // Create collections, attributes, and indexes WITHOUT transferring documents
243
+ await this.createDatabaseStructure(db.$id);
244
+ MessageFormatter.success(`Database structure created: ${db.name}`, {
245
+ prefix: "Transfer",
246
+ });
247
+ }
248
+ catch (error) {
249
+ MessageFormatter.error(`Database structure creation failed for ${db.name}`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
250
+ this.results.databases.failed++;
251
+ }
252
+ }));
253
+ await Promise.all(structureCreationTasks);
254
+ // Phase 2: Transfer all documents after all structures are created
255
+ MessageFormatter.info("Phase 2: Transferring documents to all collections", { prefix: "Transfer" });
256
+ const documentTransferTasks = sourceDatabases.databases.map((db) => this.limit(async () => {
257
+ try {
258
+ // Transfer documents for this database
259
+ await this.transferDatabaseDocuments(db.$id);
260
+ this.results.databases.transferred++;
261
+ MessageFormatter.success(`Database documents transferred: ${db.name}`, { prefix: "Transfer" });
262
+ }
263
+ catch (error) {
264
+ MessageFormatter.error(`Document transfer failed for ${db.name}`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
265
+ this.results.databases.failed++;
266
+ }
267
+ }));
268
+ await Promise.all(documentTransferTasks);
269
+ MessageFormatter.success("Database transfer phase completed", {
270
+ prefix: "Transfer",
271
+ });
272
+ }
273
+ catch (error) {
274
+ MessageFormatter.error("Database transfer phase failed", error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
275
+ }
276
+ }
277
+ /**
278
+ * Phase 1: Create database structure (collections, attributes, indexes) without transferring documents
279
+ */
280
+ async createDatabaseStructure(dbId) {
281
+ MessageFormatter.info(`Creating database structure for ${dbId}`, {
282
+ prefix: "Transfer",
283
+ });
284
+ try {
285
+ // Get all collections from source database
286
+ const sourceCollections = await this.fetchAllCollections(dbId, this.sourceDatabases);
287
+ MessageFormatter.info(`Found ${sourceCollections.length} collections in source database ${dbId}`, { prefix: "Transfer" });
288
+ // Process each collection
289
+ for (const collection of sourceCollections) {
290
+ MessageFormatter.info(`Processing collection: ${collection.name} (${collection.$id})`, { prefix: "Transfer" });
291
+ try {
292
+ // Create or update collection in target
293
+ let targetCollection;
294
+ const existingCollection = await tryAwaitWithRetry(async () => this.targetDatabases.listCollections(dbId, [
295
+ Query.equal("$id", collection.$id),
296
+ ]));
297
+ if (existingCollection.collections.length > 0) {
298
+ targetCollection = existingCollection.collections[0];
299
+ MessageFormatter.info(`Collection ${collection.name} exists in target database`, { prefix: "Transfer" });
300
+ // Update collection if needed
301
+ if (targetCollection.name !== collection.name ||
302
+ JSON.stringify(targetCollection.$permissions) !==
303
+ JSON.stringify(collection.$permissions) ||
304
+ targetCollection.documentSecurity !==
305
+ collection.documentSecurity ||
306
+ targetCollection.enabled !== collection.enabled) {
307
+ targetCollection = await tryAwaitWithRetry(async () => this.targetDatabases.updateCollection(dbId, collection.$id, collection.name, collection.$permissions, collection.documentSecurity, collection.enabled));
308
+ MessageFormatter.success(`Collection ${collection.name} updated`, { prefix: "Transfer" });
309
+ }
310
+ }
311
+ else {
312
+ MessageFormatter.info(`Creating collection ${collection.name} in target database...`, { prefix: "Transfer" });
313
+ targetCollection = await tryAwaitWithRetry(async () => this.targetDatabases.createCollection(dbId, collection.$id, collection.name, collection.$permissions, collection.documentSecurity, collection.enabled));
314
+ MessageFormatter.success(`Collection ${collection.name} created`, {
315
+ prefix: "Transfer",
316
+ });
317
+ }
318
+ // Handle attributes with enhanced status checking
319
+ MessageFormatter.info(`Creating attributes for collection ${collection.name} with enhanced monitoring...`, { prefix: "Transfer" });
320
+ const attributesToCreate = collection.attributes.map((attr) => parseAttribute(attr));
321
+ const attributesSuccess = await this.createCollectionAttributesWithStatusCheck(this.targetDatabases, dbId, targetCollection, attributesToCreate);
322
+ if (!attributesSuccess) {
323
+ MessageFormatter.error(`Failed to create some attributes for collection ${collection.name}`, undefined, { prefix: "Transfer" });
324
+ MessageFormatter.error(`Skipping index creation and document transfer for collection ${collection.name} due to attribute failures`, undefined, { prefix: "Transfer" });
325
+ // Skip indexes and document transfer if attributes failed
326
+ continue;
327
+ }
328
+ else {
329
+ MessageFormatter.success(`All attributes created successfully for collection ${collection.name}`, { prefix: "Transfer" });
330
+ }
331
+ // Handle indexes with enhanced status checking
332
+ MessageFormatter.info(`Creating indexes for collection ${collection.name} with enhanced monitoring...`, { prefix: "Transfer" });
333
+ let indexesSuccess = true;
334
+ // Check if indexes need to be created ahead of time
335
+ if (collection.indexes.some((index) => !targetCollection.indexes.some((ti) => ti.key === index.key ||
336
+ ti.attributes.sort().join(",") ===
337
+ index.attributes.sort().join(","))) ||
338
+ collection.indexes.length !== targetCollection.indexes.length) {
339
+ indexesSuccess = await this.createCollectionIndexesWithStatusCheck(dbId, this.targetDatabases, targetCollection.$id, targetCollection, collection.indexes);
340
+ }
341
+ if (!indexesSuccess) {
342
+ MessageFormatter.error(`Failed to create some indexes for collection ${collection.name}`, undefined, { prefix: "Transfer" });
343
+ MessageFormatter.warning(`Proceeding with document transfer despite index failures for collection ${collection.name}`, { prefix: "Transfer" });
344
+ }
345
+ else {
346
+ MessageFormatter.success(`All indexes created successfully for collection ${collection.name}`, { prefix: "Transfer" });
347
+ }
348
+ MessageFormatter.success(`Structure complete for collection ${collection.name}`, { prefix: "Transfer" });
349
+ }
350
+ catch (error) {
351
+ MessageFormatter.error(`Error processing collection ${collection.name}`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
352
+ }
353
+ }
354
+ // After processing all collections' attributes and indexes, process any queued
355
+ // relationship attributes so dependencies are resolved within this phase.
356
+ if (queuedOperations.length > 0) {
357
+ MessageFormatter.info(`Processing ${queuedOperations.length} queued relationship operations`, { prefix: "Transfer" });
358
+ await processQueue(this.targetDatabases, dbId);
359
+ }
360
+ else {
361
+ MessageFormatter.info("No queued relationship operations to process", {
362
+ prefix: "Transfer",
363
+ });
364
+ }
365
+ }
366
+ catch (error) {
367
+ MessageFormatter.error(`Failed to create database structure for ${dbId}`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
368
+ throw error;
369
+ }
370
+ }
371
+ /**
372
+ * Phase 2: Transfer documents to all collections in the database
373
+ */
374
+ async transferDatabaseDocuments(dbId) {
375
+ MessageFormatter.info(`Transferring documents for database ${dbId}`, {
376
+ prefix: "Transfer",
377
+ });
378
+ try {
379
+ // Get all collections from source database
380
+ const sourceCollections = await this.fetchAllCollections(dbId, this.sourceDatabases);
381
+ MessageFormatter.info(`Transferring documents for ${sourceCollections.length} collections in database ${dbId}`, { prefix: "Transfer" });
382
+ // Process each collection
383
+ for (const collection of sourceCollections) {
384
+ MessageFormatter.info(`Transferring documents for collection: ${collection.name} (${collection.$id})`, { prefix: "Transfer" });
385
+ try {
386
+ // Transfer documents
387
+ await this.transferDocumentsBetweenDatabases(this.sourceDatabases, this.targetDatabases, dbId, dbId, collection.$id, collection.$id);
388
+ MessageFormatter.success(`Documents transferred for collection ${collection.name}`, { prefix: "Transfer" });
389
+ }
390
+ catch (error) {
391
+ MessageFormatter.error(`Error transferring documents for collection ${collection.name}`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
392
+ }
393
+ }
394
+ }
395
+ catch (error) {
396
+ MessageFormatter.error(`Failed to transfer documents for database ${dbId}`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
397
+ throw error;
398
+ }
399
+ }
400
+ async transferAllBuckets() {
401
+ MessageFormatter.info("Starting bucket transfer phase", {
402
+ prefix: "Transfer",
403
+ });
404
+ try {
405
+ // Get all buckets from source with pagination
406
+ const allSourceBuckets = await this.fetchAllBuckets(this.sourceStorage);
407
+ const allTargetBuckets = await this.fetchAllBuckets(this.targetStorage);
408
+ if (this.options.dryRun) {
409
+ let totalFiles = 0;
410
+ for (const bucket of allSourceBuckets) {
411
+ const files = await this.sourceStorage.listFiles(bucket.$id, [
412
+ Query.limit(1),
413
+ ]);
414
+ totalFiles += files.total;
415
+ }
416
+ MessageFormatter.info(`DRY RUN: Would transfer ${allSourceBuckets.length} buckets with ${totalFiles} files`, { prefix: "Transfer" });
417
+ return;
418
+ }
419
+ const transferTasks = allSourceBuckets.map((bucket) => this.limit(async () => {
420
+ try {
421
+ // Check if bucket exists in target
422
+ const existingBucket = allTargetBuckets.find((tb) => tb.$id === bucket.$id);
423
+ if (!existingBucket) {
424
+ // Create bucket with fallback strategy for maximumFileSize
425
+ await this.createBucketWithFallback(bucket);
426
+ MessageFormatter.success(`Created bucket: ${bucket.name}`, {
427
+ prefix: "Transfer",
428
+ });
429
+ }
430
+ else {
431
+ // Compare bucket permissions and update if needed
432
+ const sourcePermissions = JSON.stringify(bucket.$permissions?.sort() || []);
433
+ const targetPermissions = JSON.stringify(existingBucket.$permissions?.sort() || []);
434
+ if (sourcePermissions !== targetPermissions ||
435
+ existingBucket.name !== bucket.name ||
436
+ existingBucket.fileSecurity !== bucket.fileSecurity ||
437
+ existingBucket.enabled !== bucket.enabled) {
438
+ MessageFormatter.warning(`Bucket ${bucket.name} exists but has different settings. Updating to match source.`, { prefix: "Transfer" });
439
+ try {
440
+ await this.targetStorage.updateBucket(bucket.$id, bucket.name, bucket.$permissions, bucket.fileSecurity, bucket.enabled, bucket.maximumFileSize, bucket.allowedFileExtensions, bucket.compression, bucket.encryption, bucket.antivirus);
441
+ MessageFormatter.success(`Updated bucket ${bucket.name} to match source`, { prefix: "Transfer" });
442
+ }
443
+ catch (updateError) {
444
+ MessageFormatter.error(`Failed to update bucket ${bucket.name}`, updateError instanceof Error
445
+ ? updateError
446
+ : new Error(String(updateError)), { prefix: "Transfer" });
447
+ }
448
+ }
449
+ else {
450
+ MessageFormatter.info(`Bucket ${bucket.name} already exists with matching settings`, { prefix: "Transfer" });
451
+ }
452
+ }
453
+ // Transfer bucket files with enhanced validation
454
+ await this.transferBucketFiles(bucket.$id, bucket.$id);
455
+ this.results.buckets.transferred++;
456
+ MessageFormatter.success(`Bucket ${bucket.name} transferred successfully`, { prefix: "Transfer" });
457
+ }
458
+ catch (error) {
459
+ MessageFormatter.error(`Bucket ${bucket.name} transfer failed`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
460
+ this.results.buckets.failed++;
461
+ }
462
+ }));
463
+ await Promise.all(transferTasks);
464
+ MessageFormatter.success("Bucket transfer phase completed", {
465
+ prefix: "Transfer",
466
+ });
467
+ }
468
+ catch (error) {
469
+ MessageFormatter.error("Bucket transfer phase failed", error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
470
+ }
471
+ }
472
+ async createBucketWithFallback(bucket) {
473
+ // Determine the optimal size to try first
474
+ let sizeToTry;
475
+ if (this.cachedMaxFileSize) {
476
+ // Use cached size if it's smaller than or equal to the bucket's original size
477
+ if (bucket.maximumFileSize >= this.cachedMaxFileSize) {
478
+ sizeToTry = this.cachedMaxFileSize;
479
+ MessageFormatter.info(`Bucket ${bucket.name}: Using cached maximumFileSize ${sizeToTry} (${(sizeToTry / 1_000_000_000).toFixed(1)}GB)`, { prefix: "Transfer" });
480
+ }
481
+ else {
482
+ // Original size is smaller than cached size, try original first
483
+ sizeToTry = bucket.maximumFileSize;
484
+ }
485
+ }
486
+ else {
487
+ // No cached size yet, try original size first
488
+ sizeToTry = bucket.maximumFileSize;
489
+ }
490
+ // Try the optimal size first
491
+ try {
492
+ await this.targetStorage.createBucket(bucket.$id, bucket.name, bucket.$permissions, bucket.fileSecurity, bucket.enabled, sizeToTry, bucket.allowedFileExtensions, bucket.compression, bucket.encryption, bucket.antivirus);
493
+ // Success - cache this size if it's not already cached or is smaller than cached
494
+ if (!this.cachedMaxFileSize || sizeToTry < this.cachedMaxFileSize) {
495
+ this.cachedMaxFileSize = sizeToTry;
496
+ MessageFormatter.info(`Bucket ${bucket.name}: Cached successful maximumFileSize ${sizeToTry} (${(sizeToTry / 1_000_000_000).toFixed(1)}GB)`, { prefix: "Transfer" });
497
+ }
498
+ // Log if we used a different size than original
499
+ if (sizeToTry !== bucket.maximumFileSize) {
500
+ MessageFormatter.warning(`Bucket ${bucket.name}: maximumFileSize used ${sizeToTry} instead of original ${bucket.maximumFileSize} (${(sizeToTry / 1_000_000_000).toFixed(1)}GB)`, { prefix: "Transfer" });
501
+ }
502
+ return; // Success, exit the function
503
+ }
504
+ catch (error) {
505
+ const err = error instanceof Error ? error : new Error(String(error));
506
+ // Check if the error is related to maximumFileSize validation
507
+ if (err.message.includes("maximumFileSize") ||
508
+ err.message.includes("valid range")) {
509
+ MessageFormatter.warning(`Bucket ${bucket.name}: Failed with maximumFileSize ${sizeToTry}, falling back to smaller sizes...`, { prefix: "Transfer" });
510
+ // Continue to fallback logic below
511
+ }
512
+ else {
513
+ // Different error, don't retry
514
+ throw err;
515
+ }
516
+ }
517
+ // Fallback to progressively smaller sizes
518
+ const fallbackSizes = [
519
+ 5_000_000_000, // 5GB
520
+ 2_500_000_000, // 2.5GB
521
+ 2_000_000_000, // 2GB
522
+ 1_000_000_000, // 1GB
523
+ 500_000_000, // 500MB
524
+ 100_000_000, // 100MB
525
+ ];
526
+ // Remove sizes that are larger than or equal to the already-tried size
527
+ const validSizes = fallbackSizes
528
+ .filter((size) => size < sizeToTry)
529
+ .sort((a, b) => b - a); // Sort descending
530
+ let lastError = null;
531
+ for (const fileSize of validSizes) {
532
+ try {
533
+ await this.targetStorage.createBucket(bucket.$id, bucket.name, bucket.$permissions, bucket.fileSecurity, bucket.enabled, fileSize, bucket.allowedFileExtensions, bucket.compression, bucket.encryption, bucket.antivirus);
534
+ // Success - cache this size if it's not already cached or is smaller than cached
535
+ if (!this.cachedMaxFileSize || fileSize < this.cachedMaxFileSize) {
536
+ this.cachedMaxFileSize = fileSize;
537
+ MessageFormatter.info(`Bucket ${bucket.name}: Cached successful maximumFileSize ${fileSize} (${(fileSize / 1_000_000_000).toFixed(1)}GB)`, { prefix: "Transfer" });
538
+ }
539
+ // Log if we had to reduce the file size
540
+ if (fileSize !== bucket.maximumFileSize) {
541
+ MessageFormatter.warning(`Bucket ${bucket.name}: maximumFileSize reduced from ${bucket.maximumFileSize} to ${fileSize} (${(fileSize / 1_000_000_000).toFixed(1)}GB)`, { prefix: "Transfer" });
542
+ }
543
+ return; // Success, exit the function
544
+ }
545
+ catch (error) {
546
+ lastError = error instanceof Error ? error : new Error(String(error));
547
+ // Check if the error is related to maximumFileSize validation
548
+ if (lastError.message.includes("maximumFileSize") ||
549
+ lastError.message.includes("valid range")) {
550
+ MessageFormatter.warning(`Bucket ${bucket.name}: Failed with maximumFileSize ${fileSize}, trying smaller size...`, { prefix: "Transfer" });
551
+ continue; // Try next smaller size
552
+ }
553
+ else {
554
+ // Different error, don't retry
555
+ throw lastError;
556
+ }
557
+ }
558
+ }
559
+ // If we get here, all fallback sizes failed
560
+ MessageFormatter.error(`Bucket ${bucket.name}: All fallback file sizes failed. Last error: ${lastError?.message}`, lastError || undefined, { prefix: "Transfer" });
561
+ throw lastError || new Error("All fallback file sizes failed");
562
+ }
563
+ async transferBucketFiles(sourceBucketId, targetBucketId) {
564
+ let lastFileId;
565
+ let transferredFiles = 0;
566
+ while (true) {
567
+ const queries = [Query.limit(50)]; // Smaller batch size for better rate limiting
568
+ if (lastFileId) {
569
+ queries.push(Query.cursorAfter(lastFileId));
570
+ }
571
+ const files = await this.sourceStorage.listFiles(sourceBucketId, queries);
572
+ if (files.files.length === 0)
573
+ break;
574
+ // Process files with rate limiting
575
+ const fileTasks = files.files.map((file) => this.fileLimit(async () => {
576
+ try {
577
+ // Check if file already exists and compare permissions
578
+ let existingFile = null;
579
+ try {
580
+ existingFile = await this.targetStorage.getFile(targetBucketId, file.$id);
581
+ // Compare permissions between source and target file
582
+ const sourcePermissions = JSON.stringify(file.$permissions?.sort() || []);
583
+ const targetPermissions = JSON.stringify(existingFile.$permissions?.sort() || []);
584
+ if (sourcePermissions !== targetPermissions) {
585
+ MessageFormatter.warning(`File ${file.name} (${file.$id}) exists but has different permissions. Source: ${sourcePermissions}, Target: ${targetPermissions}`, { prefix: "Transfer" });
586
+ // Update file permissions to match source
587
+ try {
588
+ await this.targetStorage.updateFile(targetBucketId, file.$id, file.name, file.$permissions);
589
+ MessageFormatter.success(`Updated file ${file.name} permissions to match source`, { prefix: "Transfer" });
590
+ }
591
+ catch (updateError) {
592
+ MessageFormatter.error(`Failed to update permissions for file ${file.name}`, updateError instanceof Error
593
+ ? updateError
594
+ : new Error(String(updateError)), { prefix: "Transfer" });
595
+ }
596
+ }
597
+ else {
598
+ MessageFormatter.info(`File ${file.name} already exists with matching permissions, skipping`, { prefix: "Transfer" });
599
+ }
600
+ return;
601
+ }
602
+ catch (error) {
603
+ // File doesn't exist, proceed with transfer
604
+ }
605
+ // Download file with validation
606
+ const fileData = await this.validateAndDownloadFile(sourceBucketId, file.$id);
607
+ if (!fileData) {
608
+ MessageFormatter.warning(`File ${file.name} failed validation, skipping`, { prefix: "Transfer" });
609
+ return;
610
+ }
611
+ // Upload file to target
612
+ const fileToCreate = InputFile.fromBuffer(new Uint8Array(fileData), file.name);
613
+ await this.targetStorage.createFile(targetBucketId, file.$id, fileToCreate, file.$permissions);
614
+ transferredFiles++;
615
+ MessageFormatter.success(`Transferred file: ${file.name}`, {
616
+ prefix: "Transfer",
617
+ });
618
+ }
619
+ catch (error) {
620
+ MessageFormatter.error(`Failed to transfer file ${file.name}`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
621
+ }
622
+ }));
623
+ await Promise.all(fileTasks);
624
+ if (files.files.length < 50)
625
+ break;
626
+ lastFileId = files.files[files.files.length - 1].$id;
627
+ }
628
+ MessageFormatter.info(`Transferred ${transferredFiles} files from bucket ${sourceBucketId}`, { prefix: "Transfer" });
629
+ }
630
+ async validateAndDownloadFile(bucketId, fileId) {
631
+ let attempts = 3;
632
+ while (attempts > 0) {
633
+ try {
634
+ const fileData = await this.sourceStorage.getFileDownload(bucketId, fileId);
635
+ // Basic validation - ensure file is not empty and not too large
636
+ if (fileData.byteLength === 0) {
637
+ MessageFormatter.warning(`File ${fileId} is empty`, {
638
+ prefix: "Transfer",
639
+ });
640
+ return null;
641
+ }
642
+ if (fileData.byteLength > 50 * 1024 * 1024) {
643
+ // 50MB limit
644
+ MessageFormatter.warning(`File ${fileId} is too large (${fileData.byteLength} bytes)`, { prefix: "Transfer" });
645
+ return null;
646
+ }
647
+ return fileData;
648
+ }
649
+ catch (error) {
650
+ attempts--;
651
+ MessageFormatter.warning(`Error downloading file ${fileId}, attempts left: ${attempts}`, { prefix: "Transfer" });
652
+ if (attempts === 0) {
653
+ MessageFormatter.error(`Failed to download file ${fileId} after all attempts`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
654
+ return null;
655
+ }
656
+ // Wait before retry
657
+ await new Promise((resolve) => setTimeout(resolve, 1000 * (4 - attempts)));
658
+ }
659
+ }
660
+ return null;
661
+ }
662
+ async transferAllFunctions() {
663
+ MessageFormatter.info("Starting function transfer phase", {
664
+ prefix: "Transfer",
665
+ });
666
+ try {
667
+ const sourceFunctions = await listFunctions(this.sourceClient, [
668
+ Query.limit(1000),
669
+ ]);
670
+ const targetFunctions = await listFunctions(this.targetClient, [
671
+ Query.limit(1000),
672
+ ]);
673
+ if (this.options.dryRun) {
674
+ MessageFormatter.info(`DRY RUN: Would transfer ${sourceFunctions.functions.length} functions`, { prefix: "Transfer" });
675
+ return;
676
+ }
677
+ const transferTasks = sourceFunctions.functions.map((func) => this.limit(async () => {
678
+ try {
679
+ // Check if function exists in target
680
+ const existingFunc = targetFunctions.functions.find((tf) => tf.$id === func.$id);
681
+ if (existingFunc) {
682
+ MessageFormatter.info(`Function ${func.name} already exists, skipping creation`, { prefix: "Transfer" });
683
+ this.results.functions.skipped++;
684
+ return;
685
+ }
686
+ // Download function from source
687
+ const functionPath = await this.downloadFunction(func);
688
+ if (!functionPath) {
689
+ MessageFormatter.error(`Failed to download function ${func.name}`, undefined, { prefix: "Transfer" });
690
+ this.results.functions.failed++;
691
+ return;
692
+ }
693
+ // Deploy function to target
694
+ const functionConfig = {
695
+ $id: func.$id,
696
+ name: func.name,
697
+ runtime: func.runtime,
698
+ execute: func.execute,
699
+ events: func.events,
700
+ enabled: func.enabled,
701
+ logging: func.logging,
702
+ entrypoint: func.entrypoint,
703
+ commands: func.commands,
704
+ scopes: func.scopes,
705
+ timeout: func.timeout,
706
+ schedule: func.schedule,
707
+ installationId: func.installationId,
708
+ providerRepositoryId: func.providerRepositoryId,
709
+ providerBranch: func.providerBranch,
710
+ providerSilentMode: func.providerSilentMode,
711
+ providerRootDirectory: func.providerRootDirectory,
712
+ specification: func.specification,
713
+ dirPath: functionPath,
714
+ };
715
+ await deployLocalFunction(this.targetClient, func.name, functionConfig, undefined, this.tempDir);
716
+ this.results.functions.transferred++;
717
+ MessageFormatter.success(`Function ${func.name} transferred successfully`, { prefix: "Transfer" });
718
+ }
719
+ catch (error) {
720
+ MessageFormatter.error(`Function ${func.name} transfer failed`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
721
+ this.results.functions.failed++;
722
+ }
723
+ }));
724
+ await Promise.all(transferTasks);
725
+ MessageFormatter.success("Function transfer phase completed", {
726
+ prefix: "Transfer",
727
+ });
728
+ }
729
+ catch (error) {
730
+ MessageFormatter.error("Function transfer phase failed", error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
731
+ }
732
+ }
733
+ async downloadFunction(func) {
734
+ try {
735
+ const { path } = await downloadLatestFunctionDeployment(this.sourceClient, func.$id, this.tempDir);
736
+ return path;
737
+ }
738
+ catch (error) {
739
+ MessageFormatter.error(`Failed to download function ${func.name}`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
740
+ return null;
741
+ }
742
+ }
743
+ /**
744
+ * Helper method to fetch all collections from a database
745
+ */
746
+ async fetchAllCollections(dbId, databases) {
747
+ const collections = [];
748
+ let lastId;
749
+ while (true) {
750
+ const queries = [Query.limit(100)];
751
+ if (lastId) {
752
+ queries.push(Query.cursorAfter(lastId));
753
+ }
754
+ const result = await tryAwaitWithRetry(async () => databases.listCollections(dbId, queries));
755
+ if (result.collections.length === 0) {
756
+ break;
757
+ }
758
+ collections.push(...result.collections);
759
+ if (result.collections.length < 100) {
760
+ break;
761
+ }
762
+ lastId = result.collections[result.collections.length - 1].$id;
763
+ }
764
+ return collections;
765
+ }
766
+ /**
767
+ * Helper method to fetch all buckets with pagination
768
+ */
769
+ async fetchAllBuckets(storage) {
770
+ const buckets = [];
771
+ let lastId;
772
+ while (true) {
773
+ const queries = [Query.limit(100)];
774
+ if (lastId) {
775
+ queries.push(Query.cursorAfter(lastId));
776
+ }
777
+ const result = await tryAwaitWithRetry(async () => storage.listBuckets(queries));
778
+ if (result.buckets.length === 0) {
779
+ break;
780
+ }
781
+ buckets.push(...result.buckets);
782
+ if (result.buckets.length < 100) {
783
+ break;
784
+ }
785
+ lastId = result.buckets[result.buckets.length - 1].$id;
786
+ }
787
+ return buckets;
788
+ }
789
+ /**
790
+ * Helper method to parse attribute objects (simplified version of parseAttribute)
791
+ */
792
+ parseAttribute(attr) {
793
+ // This is a simplified version - in production you'd use the actual parseAttribute from appwrite-utils
794
+ return {
795
+ key: attr.key,
796
+ type: attr.type,
797
+ size: attr.size,
798
+ required: attr.required,
799
+ array: attr.array,
800
+ default: attr.default,
801
+ format: attr.format,
802
+ elements: attr.elements,
803
+ min: attr.min,
804
+ max: attr.max,
805
+ relatedCollection: attr.relatedCollection,
806
+ relationType: attr.relationType,
807
+ twoWay: attr.twoWay,
808
+ twoWayKey: attr.twoWayKey,
809
+ onDelete: attr.onDelete,
810
+ side: attr.side,
811
+ };
812
+ }
813
+ /**
814
+ * Helper method to create collection attributes with status checking
815
+ */
816
+ async createCollectionAttributesWithStatusCheck(databases, dbId, collection, attributes) {
817
+ if (!this.targetAdapter) {
818
+ throw new Error('Target adapter not initialized');
819
+ }
820
+ try {
821
+ // Create non-relationship attributes first
822
+ const nonRel = (attributes || []).filter((a) => a.type !== 'relationship');
823
+ for (const attr of nonRel) {
824
+ const params = mapToCreateAttributeParams(attr, { databaseId: dbId, tableId: collection.$id });
825
+ await this.targetAdapter.createAttribute(params);
826
+ // Small delay between creations
827
+ await new Promise((r) => setTimeout(r, 150));
828
+ }
829
+ // Wait for attributes to become available
830
+ for (const attr of nonRel) {
831
+ const maxWait = 60000; // 60s
832
+ const start = Date.now();
833
+ let lastStatus = '';
834
+ while (Date.now() - start < maxWait) {
835
+ try {
836
+ const tableRes = await this.targetAdapter.getTable({ databaseId: dbId, tableId: collection.$id });
837
+ const cols = tableRes.attributes || tableRes.columns || [];
838
+ const col = cols.find((c) => c.key === attr.key);
839
+ if (col) {
840
+ if (col.status === 'available')
841
+ break;
842
+ if (col.status === 'failed' || col.status === 'stuck') {
843
+ throw new Error(col.error || `Attribute ${attr.key} failed`);
844
+ }
845
+ lastStatus = col.status;
846
+ }
847
+ await new Promise((r) => setTimeout(r, 2000));
848
+ }
849
+ catch {
850
+ await new Promise((r) => setTimeout(r, 2000));
851
+ }
852
+ }
853
+ if (Date.now() - start >= maxWait) {
854
+ MessageFormatter.warning(`Attribute ${attr.key} did not become available within 60s (last status: ${lastStatus})`, { prefix: 'Attributes' });
855
+ }
856
+ }
857
+ // Create relationship attributes
858
+ const rels = (attributes || []).filter((a) => a.type === 'relationship');
859
+ for (const attr of rels) {
860
+ const params = mapToCreateAttributeParams(attr, { databaseId: dbId, tableId: collection.$id });
861
+ await this.targetAdapter.createAttribute(params);
862
+ await new Promise((r) => setTimeout(r, 150));
863
+ }
864
+ return true;
865
+ }
866
+ catch (e) {
867
+ MessageFormatter.error('Failed creating attributes via adapter', e instanceof Error ? e : new Error(String(e)), { prefix: 'Attributes' });
868
+ return false;
869
+ }
870
+ }
871
+ /**
872
+ * Helper method to create collection indexes with status checking
873
+ */
874
+ async createCollectionIndexesWithStatusCheck(dbId, databases, collectionId, collection, indexes) {
875
+ if (!this.targetAdapter) {
876
+ throw new Error('Target adapter not initialized');
877
+ }
878
+ try {
879
+ for (const idx of indexes || []) {
880
+ await this.targetAdapter.createIndex({
881
+ databaseId: dbId,
882
+ tableId: collectionId,
883
+ key: idx.key,
884
+ type: idx.type,
885
+ attributes: idx.attributes,
886
+ orders: idx.orders || []
887
+ });
888
+ await new Promise((r) => setTimeout(r, 150));
889
+ }
890
+ return true;
891
+ }
892
+ catch (e) {
893
+ MessageFormatter.error('Failed creating indexes via adapter', e instanceof Error ? e : new Error(String(e)), { prefix: 'Indexes' });
894
+ return false;
895
+ }
896
+ }
897
+ /**
898
+ * Helper method to transfer documents between databases using bulk operations with content and permission-based filtering
899
+ */
900
+ async transferDocumentsBetweenDatabases(sourceDb, targetDb, sourceDbId, targetDbId, sourceCollectionId, targetCollectionId) {
901
+ MessageFormatter.info(`Transferring documents from ${sourceCollectionId} to ${targetCollectionId} with bulk operations, content comparison, and permission filtering`, { prefix: "Transfer" });
902
+ let lastId;
903
+ let totalTransferred = 0;
904
+ let totalSkipped = 0;
905
+ let totalUpdated = 0;
906
+ // Check if bulk operations are supported
907
+ const bulkEnabled = false;
908
+ // Temporarily disable to see if it fixes my permissions issues
909
+ const supportsBulk = bulkEnabled ? this.options.targetEndpoint.includes("cloud.appwrite.io") : false;
910
+ if (supportsBulk) {
911
+ MessageFormatter.info(`Using bulk operations for enhanced performance`, {
912
+ prefix: "Transfer",
913
+ });
914
+ }
915
+ while (true) {
916
+ // Fetch source documents in larger batches (1000 instead of 50)
917
+ const queries = [Query.limit(1000)];
918
+ if (lastId) {
919
+ queries.push(Query.cursorAfter(lastId));
920
+ }
921
+ const sourceDocuments = await tryAwaitWithRetry(async () => sourceDb.listDocuments(sourceDbId, sourceCollectionId, queries));
922
+ if (sourceDocuments.documents.length === 0) {
923
+ break;
924
+ }
925
+ MessageFormatter.info(`Processing batch of ${sourceDocuments.documents.length} source documents`, { prefix: "Transfer" });
926
+ // Extract document IDs from the current batch
927
+ const sourceDocIds = sourceDocuments.documents.map((doc) => doc.$id);
928
+ // Fetch existing documents from target in a single query
929
+ const existingTargetDocs = await this.fetchTargetDocumentsBatch(targetDb, targetDbId, targetCollectionId, sourceDocIds);
930
+ // Create a map for quick lookup of existing documents
931
+ const existingDocsMap = new Map();
932
+ existingTargetDocs.forEach((doc) => {
933
+ existingDocsMap.set(doc.$id, doc);
934
+ });
935
+ // Filter documents based on existence, content comparison, and permission comparison
936
+ const documentsToTransfer = [];
937
+ const documentsToUpdate = [];
938
+ for (const sourceDoc of sourceDocuments.documents) {
939
+ const existingTargetDoc = existingDocsMap.get(sourceDoc.$id);
940
+ if (!existingTargetDoc) {
941
+ // Document doesn't exist in target, needs to be transferred
942
+ documentsToTransfer.push(sourceDoc);
943
+ }
944
+ else {
945
+ // Document exists, compare both content and permissions
946
+ const sourcePermissions = Array.from(new Set(sourceDoc.$permissions || [])).sort();
947
+ const targetPermissions = Array.from(new Set(existingTargetDoc.$permissions || [])).sort();
948
+ const permissionsDiffer = sourcePermissions.join(",") !== targetPermissions.join(",") ||
949
+ sourcePermissions.length !== targetPermissions.length;
950
+ // Use objectNeedsUpdate to compare document content (excluding system fields)
951
+ const contentDiffers = objectNeedsUpdate(existingTargetDoc, sourceDoc);
952
+ if (contentDiffers && permissionsDiffer) {
953
+ // Both content and permissions differ
954
+ documentsToUpdate.push({
955
+ doc: sourceDoc,
956
+ targetDoc: existingTargetDoc,
957
+ reason: "content and permissions differ",
958
+ });
959
+ }
960
+ else if (contentDiffers) {
961
+ // Only content differs
962
+ documentsToUpdate.push({
963
+ doc: sourceDoc,
964
+ targetDoc: existingTargetDoc,
965
+ reason: "content differs",
966
+ });
967
+ }
968
+ else if (permissionsDiffer) {
969
+ // Only permissions differ
970
+ documentsToUpdate.push({
971
+ doc: sourceDoc,
972
+ targetDoc: existingTargetDoc,
973
+ reason: "permissions differ",
974
+ });
975
+ }
976
+ else {
977
+ // Document exists with identical content AND permissions, skip
978
+ totalSkipped++;
979
+ }
980
+ }
981
+ }
982
+ MessageFormatter.info(`Batch analysis: ${documentsToTransfer.length} to create, ${documentsToUpdate.length} to update, ${totalSkipped} skipped so far`, { prefix: "Transfer" });
983
+ // Process new documents with bulk operations if supported and available
984
+ if (documentsToTransfer.length > 0) {
985
+ if (supportsBulk && documentsToTransfer.length >= 10) {
986
+ // Use bulk operations for large batches
987
+ await this.transferDocumentsBulk(targetDb, targetDbId, targetCollectionId, documentsToTransfer);
988
+ totalTransferred += documentsToTransfer.length;
989
+ }
990
+ else {
991
+ // Use individual transfers for smaller batches or non-bulk endpoints
992
+ const transferCount = await this.transferDocumentsIndividual(targetDb, targetDbId, targetCollectionId, documentsToTransfer);
993
+ totalTransferred += transferCount;
994
+ }
995
+ }
996
+ // Process document updates (always individual since bulk update with permissions needs special handling)
997
+ if (documentsToUpdate.length > 0) {
998
+ const updateCount = await this.updateDocumentsIndividual(targetDb, targetDbId, targetCollectionId, documentsToUpdate);
999
+ totalUpdated += updateCount;
1000
+ }
1001
+ if (sourceDocuments.documents.length < 1000) {
1002
+ break;
1003
+ }
1004
+ lastId =
1005
+ sourceDocuments.documents[sourceDocuments.documents.length - 1].$id;
1006
+ }
1007
+ MessageFormatter.info(`Transfer complete: ${totalTransferred} new, ${totalUpdated} updated, ${totalSkipped} skipped from ${sourceCollectionId} to ${targetCollectionId}`, { prefix: "Transfer" });
1008
+ }
1009
+ /**
1010
+ * Fetch target documents by IDs in batches to check existence and permissions
1011
+ */
1012
+ async fetchTargetDocumentsBatch(targetDb, targetDbId, targetCollectionId, docIds) {
1013
+ const documents = [];
1014
+ // Split IDs into chunks of 100 for Query.equal limitations
1015
+ const idChunks = this.chunkArray(docIds, 100);
1016
+ for (const chunk of idChunks) {
1017
+ try {
1018
+ const result = await tryAwaitWithRetry(async () => targetDb.listDocuments(targetDbId, targetCollectionId, [
1019
+ Query.equal("$id", chunk),
1020
+ Query.limit(100),
1021
+ ]));
1022
+ documents.push(...result.documents);
1023
+ }
1024
+ catch (error) {
1025
+ // If query fails, fall back to individual gets (less efficient but more reliable)
1026
+ MessageFormatter.warning(`Batch query failed for ${chunk.length} documents, falling back to individual checks`, { prefix: "Transfer" });
1027
+ for (const docId of chunk) {
1028
+ try {
1029
+ const doc = await targetDb.getDocument(targetDbId, targetCollectionId, docId);
1030
+ documents.push(doc);
1031
+ }
1032
+ catch (getError) {
1033
+ // Document doesn't exist, which is fine
1034
+ }
1035
+ }
1036
+ }
1037
+ }
1038
+ return documents;
1039
+ }
1040
+ /**
1041
+ * Transfer documents using bulk operations with proper batch size handling
1042
+ */
1043
+ async transferDocumentsBulk(targetDb, targetDbId, targetCollectionId, documents) {
1044
+ // Prepare documents for bulk upsert
1045
+ const preparedDocs = documents.map((doc) => {
1046
+ const { $id, $createdAt, $updatedAt, $permissions, $databaseId, $collectionId, $sequence, ...docData } = doc;
1047
+ return {
1048
+ $id,
1049
+ $permissions,
1050
+ ...docData,
1051
+ };
1052
+ });
1053
+ // Process in smaller chunks for bulk operations (1000 for Pro, 100 for Free tier)
1054
+ const batchSizes = [1000, 100]; // Start with Pro plan, fallback to Free
1055
+ let processed = false;
1056
+ for (const maxBatchSize of batchSizes) {
1057
+ const documentBatches = this.chunkArray(preparedDocs, maxBatchSize);
1058
+ try {
1059
+ for (const batch of documentBatches) {
1060
+ await this.bulkUpsertDocuments(this.targetClient, targetDbId, targetCollectionId, batch);
1061
+ MessageFormatter.success(`✅ Bulk upserted ${batch.length} documents`, { prefix: "Transfer" });
1062
+ }
1063
+ processed = true;
1064
+ break; // Success, exit batch size loop
1065
+ }
1066
+ catch (error) {
1067
+ MessageFormatter.warning(`Bulk upsert with batch size ${maxBatchSize} failed, trying smaller size...`, { prefix: "Transfer" });
1068
+ continue; // Try next smaller batch size
1069
+ }
1070
+ }
1071
+ if (!processed) {
1072
+ MessageFormatter.warning(`All bulk operations failed, falling back to individual transfers`, { prefix: "Transfer" });
1073
+ // Fall back to individual transfers
1074
+ await this.transferDocumentsIndividual(targetDb, targetDbId, targetCollectionId, documents);
1075
+ }
1076
+ }
1077
+ /**
1078
+ * Direct HTTP implementation of bulk upsert API
1079
+ */
1080
+ async bulkUpsertDocuments(client, dbId, collectionId, documents) {
1081
+ const apiPath = `/databases/${dbId}/collections/${collectionId}/documents`;
1082
+ const url = new URL(client.config.endpoint + apiPath);
1083
+ const headers = {
1084
+ "Content-Type": "application/json",
1085
+ "X-Appwrite-Project": client.config.project,
1086
+ "X-Appwrite-Key": client.config.key,
1087
+ };
1088
+ const response = await fetch(url.toString(), {
1089
+ method: "PUT",
1090
+ headers,
1091
+ body: JSON.stringify({ documents }),
1092
+ });
1093
+ if (!response.ok) {
1094
+ const errorData = await response
1095
+ .json()
1096
+ .catch(() => ({ message: "Unknown error" }));
1097
+ throw new Error(`Bulk upsert failed: ${response.status} - ${errorData.message || "Unknown error"}`);
1098
+ }
1099
+ return await response.json();
1100
+ }
1101
+ /**
1102
+ * Transfer documents individually with rate limiting
1103
+ */
1104
+ async transferDocumentsIndividual(targetDb, targetDbId, targetCollectionId, documents) {
1105
+ let successCount = 0;
1106
+ const transferTasks = documents.map((doc) => this.limit(async () => {
1107
+ try {
1108
+ const { $id, $createdAt, $updatedAt, $permissions, $databaseId, $collectionId, $sequence, ...docData } = doc;
1109
+ await tryAwaitWithRetry(async () => targetDb.createDocument(targetDbId, targetCollectionId, doc.$id, docData, doc.$permissions));
1110
+ successCount++;
1111
+ }
1112
+ catch (error) {
1113
+ if (error instanceof AppwriteException &&
1114
+ error.message.includes("already exists")) {
1115
+ try {
1116
+ // Update it! It's here because it needs an update or a create
1117
+ const { $id, $createdAt, $updatedAt, $permissions, $databaseId, $collectionId, $sequence, ...docData } = doc;
1118
+ await tryAwaitWithRetry(async () => targetDb.updateDocument(targetDbId, targetCollectionId, doc.$id, docData, doc.$permissions));
1119
+ successCount++;
1120
+ }
1121
+ catch (updateError) {
1122
+ // just send the error to the formatter
1123
+ MessageFormatter.error(`Failed to transfer document ${doc.$id}`, updateError instanceof Error
1124
+ ? updateError
1125
+ : new Error(String(updateError)), { prefix: "Transfer" });
1126
+ }
1127
+ }
1128
+ MessageFormatter.error(`Failed to transfer document ${doc.$id}`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
1129
+ }
1130
+ }));
1131
+ await Promise.all(transferTasks);
1132
+ return successCount;
1133
+ }
1134
+ /**
1135
+ * Update documents individually with content and/or permission changes
1136
+ */
1137
+ async updateDocumentsIndividual(targetDb, targetDbId, targetCollectionId, documentPairs) {
1138
+ let successCount = 0;
1139
+ const updateTasks = documentPairs.map(({ doc, targetDoc, reason }) => this.limit(async () => {
1140
+ try {
1141
+ const { $id, $createdAt, $updatedAt, $permissions, $databaseId, $collectionId, $sequence, ...docData } = doc;
1142
+ await tryAwaitWithRetry(async () => targetDb.updateDocument(targetDbId, targetCollectionId, doc.$id, docData, $permissions));
1143
+ successCount++;
1144
+ }
1145
+ catch (error) {
1146
+ MessageFormatter.error(`Failed to update document ${doc.$id} (${reason})`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
1147
+ }
1148
+ }));
1149
+ await Promise.all(updateTasks);
1150
+ return successCount;
1151
+ }
1152
+ /**
1153
+ * Utility method to chunk arrays
1154
+ */
1155
+ chunkArray(array, size) {
1156
+ const chunks = [];
1157
+ for (let i = 0; i < array.length; i += size) {
1158
+ chunks.push(array.slice(i, i + size));
1159
+ }
1160
+ return chunks;
1161
+ }
1162
+ /**
1163
+ * Helper method to fetch all teams with pagination
1164
+ */
1165
+ async fetchAllTeams(teams) {
1166
+ const teamsList = [];
1167
+ let lastId;
1168
+ while (true) {
1169
+ const queries = [Query.limit(100)];
1170
+ if (lastId) {
1171
+ queries.push(Query.cursorAfter(lastId));
1172
+ }
1173
+ const result = await tryAwaitWithRetry(async () => teams.list(queries));
1174
+ if (result.teams.length === 0) {
1175
+ break;
1176
+ }
1177
+ teamsList.push(...result.teams);
1178
+ if (result.teams.length < 100) {
1179
+ break;
1180
+ }
1181
+ lastId = result.teams[result.teams.length - 1].$id;
1182
+ }
1183
+ return teamsList;
1184
+ }
1185
+ /**
1186
+ * Helper method to fetch all memberships for a team with pagination
1187
+ */
1188
+ async fetchAllMemberships(teamId) {
1189
+ const membershipsList = [];
1190
+ let lastId;
1191
+ while (true) {
1192
+ const queries = [Query.limit(100)];
1193
+ if (lastId) {
1194
+ queries.push(Query.cursorAfter(lastId));
1195
+ }
1196
+ const result = await tryAwaitWithRetry(async () => this.sourceTeams.listMemberships(teamId, queries));
1197
+ if (result.memberships.length === 0) {
1198
+ break;
1199
+ }
1200
+ membershipsList.push(...result.memberships);
1201
+ if (result.memberships.length < 100) {
1202
+ break;
1203
+ }
1204
+ lastId = result.memberships[result.memberships.length - 1].$id;
1205
+ }
1206
+ return membershipsList;
1207
+ }
1208
+ /**
1209
+ * Helper method to transfer team memberships
1210
+ */
1211
+ async transferTeamMemberships(teamId) {
1212
+ MessageFormatter.info(`Transferring memberships for team ${teamId}`, {
1213
+ prefix: "Transfer",
1214
+ });
1215
+ try {
1216
+ // Fetch all memberships for this team
1217
+ const memberships = await this.fetchAllMemberships(teamId);
1218
+ if (memberships.length === 0) {
1219
+ MessageFormatter.info(`No memberships found for team ${teamId}`, {
1220
+ prefix: "Transfer",
1221
+ });
1222
+ return;
1223
+ }
1224
+ MessageFormatter.info(`Found ${memberships.length} memberships for team ${teamId}`, { prefix: "Transfer" });
1225
+ let totalTransferred = 0;
1226
+ // Transfer memberships with rate limiting
1227
+ const transferTasks = memberships.map((membership) => this.userLimit(async () => {
1228
+ // Use userLimit for team operations (more sensitive)
1229
+ try {
1230
+ // Check if membership already exists and compare roles
1231
+ let existingMembership = null;
1232
+ try {
1233
+ existingMembership = await this.targetTeams.getMembership(teamId, membership.$id);
1234
+ // Compare roles between source and target membership
1235
+ const sourceRoles = JSON.stringify(membership.roles?.sort() || []);
1236
+ const targetRoles = JSON.stringify(existingMembership.roles?.sort() || []);
1237
+ if (sourceRoles !== targetRoles) {
1238
+ MessageFormatter.warning(`Membership ${membership.$id} exists but has different roles. Source: ${sourceRoles}, Target: ${targetRoles}`, { prefix: "Transfer" });
1239
+ // Update membership roles to match source
1240
+ try {
1241
+ await this.targetTeams.updateMembership(teamId, membership.$id, membership.roles);
1242
+ MessageFormatter.success(`Updated membership ${membership.$id} roles to match source`, { prefix: "Transfer" });
1243
+ }
1244
+ catch (updateError) {
1245
+ MessageFormatter.error(`Failed to update roles for membership ${membership.$id}`, updateError instanceof Error
1246
+ ? updateError
1247
+ : new Error(String(updateError)), { prefix: "Transfer" });
1248
+ }
1249
+ }
1250
+ else {
1251
+ MessageFormatter.info(`Membership ${membership.$id} already exists with matching roles, skipping`, { prefix: "Transfer" });
1252
+ }
1253
+ return;
1254
+ }
1255
+ catch (error) {
1256
+ // Membership doesn't exist, proceed with creation
1257
+ }
1258
+ // Get user data from target (users should already be transferred)
1259
+ let userData = null;
1260
+ try {
1261
+ userData = await this.targetUsers.get(membership.userId);
1262
+ }
1263
+ catch (error) {
1264
+ MessageFormatter.warning(`User ${membership.userId} not found in target, membership ${membership.$id} may fail`, { prefix: "Transfer" });
1265
+ }
1266
+ // Create membership using the comprehensive user data
1267
+ await tryAwaitWithRetry(async () => this.targetTeams.createMembership(teamId, membership.roles, userData?.email || membership.userEmail, // Use target user email if available, fallback to membership email
1268
+ membership.userId, // User ID
1269
+ userData?.phone || undefined, // Use target user phone if available
1270
+ undefined, // Invitation URL placeholder
1271
+ userData?.name || membership.userName // Use target user name if available, fallback to membership name
1272
+ ));
1273
+ totalTransferred++;
1274
+ MessageFormatter.success(`Transferred membership ${membership.$id} for user ${userData?.name || membership.userName}`, { prefix: "Transfer" });
1275
+ }
1276
+ catch (error) {
1277
+ MessageFormatter.error(`Failed to transfer membership ${membership.$id}`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
1278
+ }
1279
+ }));
1280
+ await Promise.all(transferTasks);
1281
+ MessageFormatter.info(`Transferred ${totalTransferred} memberships for team ${teamId}`, { prefix: "Transfer" });
1282
+ }
1283
+ catch (error) {
1284
+ MessageFormatter.error(`Failed to transfer memberships for team ${teamId}`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
1285
+ }
1286
+ }
1287
+ printSummary() {
1288
+ const duration = Math.round((Date.now() - this.startTime) / 1000);
1289
+ MessageFormatter.info("=== COMPREHENSIVE TRANSFER SUMMARY ===", {
1290
+ prefix: "Transfer",
1291
+ });
1292
+ MessageFormatter.info(`Total Time: ${duration}s`, { prefix: "Transfer" });
1293
+ MessageFormatter.info(`Users: ${this.results.users.transferred} transferred, ${this.results.users.skipped} skipped, ${this.results.users.failed} failed`, { prefix: "Transfer" });
1294
+ MessageFormatter.info(`Teams: ${this.results.teams.transferred} transferred, ${this.results.teams.skipped} skipped, ${this.results.teams.failed} failed`, { prefix: "Transfer" });
1295
+ MessageFormatter.info(`Databases: ${this.results.databases.transferred} transferred, ${this.results.databases.skipped} skipped, ${this.results.databases.failed} failed`, { prefix: "Transfer" });
1296
+ MessageFormatter.info(`Buckets: ${this.results.buckets.transferred} transferred, ${this.results.buckets.skipped} skipped, ${this.results.buckets.failed} failed`, { prefix: "Transfer" });
1297
+ MessageFormatter.info(`Functions: ${this.results.functions.transferred} transferred, ${this.results.functions.skipped} skipped, ${this.results.functions.failed} failed`, { prefix: "Transfer" });
1298
+ const totalTransferred = this.results.users.transferred +
1299
+ this.results.teams.transferred +
1300
+ this.results.databases.transferred +
1301
+ this.results.buckets.transferred +
1302
+ this.results.functions.transferred;
1303
+ const totalFailed = this.results.users.failed +
1304
+ this.results.teams.failed +
1305
+ this.results.databases.failed +
1306
+ this.results.buckets.failed +
1307
+ this.results.functions.failed;
1308
+ if (totalFailed === 0) {
1309
+ MessageFormatter.success(`All ${totalTransferred} items transferred successfully!`, { prefix: "Transfer" });
1310
+ }
1311
+ else {
1312
+ MessageFormatter.warning(`${totalTransferred} items transferred, ${totalFailed} failed`, { prefix: "Transfer" });
1313
+ }
1314
+ }
1315
+ }