@njdamstra/appwrite-utils-cli 1.8.9

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 (392) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +1133 -0
  3. package/dist/adapters/AdapterFactory.d.ts +94 -0
  4. package/dist/adapters/AdapterFactory.js +405 -0
  5. package/dist/adapters/DatabaseAdapter.d.ts +233 -0
  6. package/dist/adapters/DatabaseAdapter.js +50 -0
  7. package/dist/adapters/LegacyAdapter.d.ts +50 -0
  8. package/dist/adapters/LegacyAdapter.js +612 -0
  9. package/dist/adapters/TablesDBAdapter.d.ts +45 -0
  10. package/dist/adapters/TablesDBAdapter.js +571 -0
  11. package/dist/adapters/index.d.ts +11 -0
  12. package/dist/adapters/index.js +12 -0
  13. package/dist/backups/operations/bucketBackup.d.ts +19 -0
  14. package/dist/backups/operations/bucketBackup.js +197 -0
  15. package/dist/backups/operations/collectionBackup.d.ts +30 -0
  16. package/dist/backups/operations/collectionBackup.js +201 -0
  17. package/dist/backups/operations/comprehensiveBackup.d.ts +25 -0
  18. package/dist/backups/operations/comprehensiveBackup.js +238 -0
  19. package/dist/backups/schemas/bucketManifest.d.ts +93 -0
  20. package/dist/backups/schemas/bucketManifest.js +33 -0
  21. package/dist/backups/schemas/comprehensiveManifest.d.ts +108 -0
  22. package/dist/backups/schemas/comprehensiveManifest.js +32 -0
  23. package/dist/backups/tracking/centralizedTracking.d.ts +34 -0
  24. package/dist/backups/tracking/centralizedTracking.js +274 -0
  25. package/dist/cli/commands/configCommands.d.ts +8 -0
  26. package/dist/cli/commands/configCommands.js +166 -0
  27. package/dist/cli/commands/databaseCommands.d.ts +13 -0
  28. package/dist/cli/commands/databaseCommands.js +554 -0
  29. package/dist/cli/commands/functionCommands.d.ts +7 -0
  30. package/dist/cli/commands/functionCommands.js +330 -0
  31. package/dist/cli/commands/schemaCommands.d.ts +7 -0
  32. package/dist/cli/commands/schemaCommands.js +169 -0
  33. package/dist/cli/commands/storageCommands.d.ts +5 -0
  34. package/dist/cli/commands/storageCommands.js +143 -0
  35. package/dist/cli/commands/transferCommands.d.ts +5 -0
  36. package/dist/cli/commands/transferCommands.js +384 -0
  37. package/dist/collections/attributes.d.ts +13 -0
  38. package/dist/collections/attributes.js +1364 -0
  39. package/dist/collections/indexes.d.ts +12 -0
  40. package/dist/collections/indexes.js +217 -0
  41. package/dist/collections/methods.d.ts +19 -0
  42. package/dist/collections/methods.js +682 -0
  43. package/dist/collections/tableOperations.d.ts +86 -0
  44. package/dist/collections/tableOperations.js +434 -0
  45. package/dist/collections/transferOperations.d.ts +8 -0
  46. package/dist/collections/transferOperations.js +412 -0
  47. package/dist/collections/wipeOperations.d.ts +16 -0
  48. package/dist/collections/wipeOperations.js +233 -0
  49. package/dist/config/ConfigManager.d.ts +445 -0
  50. package/dist/config/ConfigManager.js +625 -0
  51. package/dist/config/configMigration.d.ts +87 -0
  52. package/dist/config/configMigration.js +390 -0
  53. package/dist/config/configValidation.d.ts +66 -0
  54. package/dist/config/configValidation.js +358 -0
  55. package/dist/config/index.d.ts +8 -0
  56. package/dist/config/index.js +7 -0
  57. package/dist/config/services/ConfigDiscoveryService.d.ts +126 -0
  58. package/dist/config/services/ConfigDiscoveryService.js +374 -0
  59. package/dist/config/services/ConfigLoaderService.d.ts +129 -0
  60. package/dist/config/services/ConfigLoaderService.js +540 -0
  61. package/dist/config/services/ConfigMergeService.d.ts +208 -0
  62. package/dist/config/services/ConfigMergeService.js +308 -0
  63. package/dist/config/services/ConfigValidationService.d.ts +214 -0
  64. package/dist/config/services/ConfigValidationService.js +310 -0
  65. package/dist/config/services/SessionAuthService.d.ts +225 -0
  66. package/dist/config/services/SessionAuthService.js +456 -0
  67. package/dist/config/services/__tests__/ConfigMergeService.test.d.ts +1 -0
  68. package/dist/config/services/__tests__/ConfigMergeService.test.js +271 -0
  69. package/dist/config/services/index.d.ts +13 -0
  70. package/dist/config/services/index.js +10 -0
  71. package/dist/config/yamlConfig.d.ts +722 -0
  72. package/dist/config/yamlConfig.js +702 -0
  73. package/dist/databases/methods.d.ts +6 -0
  74. package/dist/databases/methods.js +35 -0
  75. package/dist/databases/setup.d.ts +5 -0
  76. package/dist/databases/setup.js +45 -0
  77. package/dist/examples/yamlTerminologyExample.d.ts +42 -0
  78. package/dist/examples/yamlTerminologyExample.js +272 -0
  79. package/dist/functions/deployments.d.ts +4 -0
  80. package/dist/functions/deployments.js +146 -0
  81. package/dist/functions/fnConfigDiscovery.d.ts +3 -0
  82. package/dist/functions/fnConfigDiscovery.js +108 -0
  83. package/dist/functions/methods.d.ts +16 -0
  84. package/dist/functions/methods.js +162 -0
  85. package/dist/functions/pathResolution.d.ts +37 -0
  86. package/dist/functions/pathResolution.js +185 -0
  87. package/dist/functions/templates/count-docs-in-collection/README.md +54 -0
  88. package/dist/functions/templates/count-docs-in-collection/src/main.ts +159 -0
  89. package/dist/functions/templates/count-docs-in-collection/src/request.ts +9 -0
  90. package/dist/functions/templates/hono-typescript/README.md +286 -0
  91. package/dist/functions/templates/hono-typescript/src/adapters/request.ts +74 -0
  92. package/dist/functions/templates/hono-typescript/src/adapters/response.ts +106 -0
  93. package/dist/functions/templates/hono-typescript/src/app.ts +180 -0
  94. package/dist/functions/templates/hono-typescript/src/context.ts +103 -0
  95. package/dist/functions/templates/hono-typescript/src/index.ts +54 -0
  96. package/dist/functions/templates/hono-typescript/src/middleware/appwrite.ts +119 -0
  97. package/dist/functions/templates/typescript-node/README.md +32 -0
  98. package/dist/functions/templates/typescript-node/src/context.ts +103 -0
  99. package/dist/functions/templates/typescript-node/src/index.ts +29 -0
  100. package/dist/functions/templates/uv/README.md +31 -0
  101. package/dist/functions/templates/uv/pyproject.toml +30 -0
  102. package/dist/functions/templates/uv/src/__init__.py +0 -0
  103. package/dist/functions/templates/uv/src/context.py +125 -0
  104. package/dist/functions/templates/uv/src/index.py +46 -0
  105. package/dist/init.d.ts +2 -0
  106. package/dist/init.js +57 -0
  107. package/dist/interactiveCLI.d.ts +31 -0
  108. package/dist/interactiveCLI.js +898 -0
  109. package/dist/main.d.ts +2 -0
  110. package/dist/main.js +1172 -0
  111. package/dist/migrations/afterImportActions.d.ts +17 -0
  112. package/dist/migrations/afterImportActions.js +306 -0
  113. package/dist/migrations/appwriteToX.d.ts +211 -0
  114. package/dist/migrations/appwriteToX.js +491 -0
  115. package/dist/migrations/comprehensiveTransfer.d.ts +147 -0
  116. package/dist/migrations/comprehensiveTransfer.js +1317 -0
  117. package/dist/migrations/dataLoader.d.ts +753 -0
  118. package/dist/migrations/dataLoader.js +1250 -0
  119. package/dist/migrations/importController.d.ts +23 -0
  120. package/dist/migrations/importController.js +268 -0
  121. package/dist/migrations/importDataActions.d.ts +50 -0
  122. package/dist/migrations/importDataActions.js +230 -0
  123. package/dist/migrations/relationships.d.ts +29 -0
  124. package/dist/migrations/relationships.js +204 -0
  125. package/dist/migrations/services/DataTransformationService.d.ts +55 -0
  126. package/dist/migrations/services/DataTransformationService.js +158 -0
  127. package/dist/migrations/services/FileHandlerService.d.ts +75 -0
  128. package/dist/migrations/services/FileHandlerService.js +236 -0
  129. package/dist/migrations/services/ImportOrchestrator.d.ts +97 -0
  130. package/dist/migrations/services/ImportOrchestrator.js +485 -0
  131. package/dist/migrations/services/RateLimitManager.d.ts +138 -0
  132. package/dist/migrations/services/RateLimitManager.js +279 -0
  133. package/dist/migrations/services/RelationshipResolver.d.ts +120 -0
  134. package/dist/migrations/services/RelationshipResolver.js +332 -0
  135. package/dist/migrations/services/UserMappingService.d.ts +109 -0
  136. package/dist/migrations/services/UserMappingService.js +277 -0
  137. package/dist/migrations/services/ValidationService.d.ts +74 -0
  138. package/dist/migrations/services/ValidationService.js +260 -0
  139. package/dist/migrations/transfer.d.ts +26 -0
  140. package/dist/migrations/transfer.js +608 -0
  141. package/dist/migrations/yaml/YamlImportConfigLoader.d.ts +131 -0
  142. package/dist/migrations/yaml/YamlImportConfigLoader.js +383 -0
  143. package/dist/migrations/yaml/YamlImportIntegration.d.ts +93 -0
  144. package/dist/migrations/yaml/YamlImportIntegration.js +341 -0
  145. package/dist/migrations/yaml/generateImportSchemas.d.ts +30 -0
  146. package/dist/migrations/yaml/generateImportSchemas.js +1327 -0
  147. package/dist/schemas/authUser.d.ts +24 -0
  148. package/dist/schemas/authUser.js +17 -0
  149. package/dist/setup.d.ts +2 -0
  150. package/dist/setup.js +5 -0
  151. package/dist/setupCommands.d.ts +58 -0
  152. package/dist/setupCommands.js +490 -0
  153. package/dist/setupController.d.ts +9 -0
  154. package/dist/setupController.js +34 -0
  155. package/dist/shared/attributeMapper.d.ts +20 -0
  156. package/dist/shared/attributeMapper.js +203 -0
  157. package/dist/shared/backupMetadataSchema.d.ts +94 -0
  158. package/dist/shared/backupMetadataSchema.js +38 -0
  159. package/dist/shared/backupTracking.d.ts +18 -0
  160. package/dist/shared/backupTracking.js +176 -0
  161. package/dist/shared/confirmationDialogs.d.ts +75 -0
  162. package/dist/shared/confirmationDialogs.js +236 -0
  163. package/dist/shared/errorUtils.d.ts +54 -0
  164. package/dist/shared/errorUtils.js +95 -0
  165. package/dist/shared/functionManager.d.ts +48 -0
  166. package/dist/shared/functionManager.js +336 -0
  167. package/dist/shared/indexManager.d.ts +24 -0
  168. package/dist/shared/indexManager.js +151 -0
  169. package/dist/shared/jsonSchemaGenerator.d.ts +50 -0
  170. package/dist/shared/jsonSchemaGenerator.js +290 -0
  171. package/dist/shared/logging.d.ts +61 -0
  172. package/dist/shared/logging.js +116 -0
  173. package/dist/shared/messageFormatter.d.ts +39 -0
  174. package/dist/shared/messageFormatter.js +162 -0
  175. package/dist/shared/migrationHelpers.d.ts +61 -0
  176. package/dist/shared/migrationHelpers.js +145 -0
  177. package/dist/shared/operationLogger.d.ts +10 -0
  178. package/dist/shared/operationLogger.js +12 -0
  179. package/dist/shared/operationQueue.d.ts +40 -0
  180. package/dist/shared/operationQueue.js +311 -0
  181. package/dist/shared/operationsTable.d.ts +26 -0
  182. package/dist/shared/operationsTable.js +286 -0
  183. package/dist/shared/operationsTableSchema.d.ts +48 -0
  184. package/dist/shared/operationsTableSchema.js +35 -0
  185. package/dist/shared/progressManager.d.ts +62 -0
  186. package/dist/shared/progressManager.js +215 -0
  187. package/dist/shared/pydanticModelGenerator.d.ts +17 -0
  188. package/dist/shared/pydanticModelGenerator.js +615 -0
  189. package/dist/shared/relationshipExtractor.d.ts +56 -0
  190. package/dist/shared/relationshipExtractor.js +138 -0
  191. package/dist/shared/schemaGenerator.d.ts +40 -0
  192. package/dist/shared/schemaGenerator.js +556 -0
  193. package/dist/shared/selectionDialogs.d.ts +214 -0
  194. package/dist/shared/selectionDialogs.js +544 -0
  195. package/dist/storage/backupCompression.d.ts +20 -0
  196. package/dist/storage/backupCompression.js +67 -0
  197. package/dist/storage/methods.d.ts +32 -0
  198. package/dist/storage/methods.js +472 -0
  199. package/dist/storage/schemas.d.ts +842 -0
  200. package/dist/storage/schemas.js +175 -0
  201. package/dist/types.d.ts +4 -0
  202. package/dist/types.js +3 -0
  203. package/dist/users/methods.d.ts +16 -0
  204. package/dist/users/methods.js +277 -0
  205. package/dist/utils/ClientFactory.d.ts +87 -0
  206. package/dist/utils/ClientFactory.js +212 -0
  207. package/dist/utils/configDiscovery.d.ts +78 -0
  208. package/dist/utils/configDiscovery.js +472 -0
  209. package/dist/utils/configMigration.d.ts +1 -0
  210. package/dist/utils/configMigration.js +261 -0
  211. package/dist/utils/constantsGenerator.d.ts +31 -0
  212. package/dist/utils/constantsGenerator.js +321 -0
  213. package/dist/utils/dataConverters.d.ts +46 -0
  214. package/dist/utils/dataConverters.js +139 -0
  215. package/dist/utils/directoryUtils.d.ts +22 -0
  216. package/dist/utils/directoryUtils.js +59 -0
  217. package/dist/utils/getClientFromConfig.d.ts +39 -0
  218. package/dist/utils/getClientFromConfig.js +199 -0
  219. package/dist/utils/helperFunctions.d.ts +63 -0
  220. package/dist/utils/helperFunctions.js +156 -0
  221. package/dist/utils/index.d.ts +2 -0
  222. package/dist/utils/index.js +2 -0
  223. package/dist/utils/loadConfigs.d.ts +50 -0
  224. package/dist/utils/loadConfigs.js +358 -0
  225. package/dist/utils/pathResolvers.d.ts +53 -0
  226. package/dist/utils/pathResolvers.js +72 -0
  227. package/dist/utils/projectConfig.d.ts +119 -0
  228. package/dist/utils/projectConfig.js +171 -0
  229. package/dist/utils/retryFailedPromises.d.ts +2 -0
  230. package/dist/utils/retryFailedPromises.js +23 -0
  231. package/dist/utils/sessionAuth.d.ts +48 -0
  232. package/dist/utils/sessionAuth.js +164 -0
  233. package/dist/utils/setupFiles.d.ts +4 -0
  234. package/dist/utils/setupFiles.js +1192 -0
  235. package/dist/utils/typeGuards.d.ts +35 -0
  236. package/dist/utils/typeGuards.js +57 -0
  237. package/dist/utils/validationRules.d.ts +43 -0
  238. package/dist/utils/validationRules.js +42 -0
  239. package/dist/utils/versionDetection.d.ts +58 -0
  240. package/dist/utils/versionDetection.js +251 -0
  241. package/dist/utils/yamlConverter.d.ts +100 -0
  242. package/dist/utils/yamlConverter.js +428 -0
  243. package/dist/utils/yamlLoader.d.ts +70 -0
  244. package/dist/utils/yamlLoader.js +267 -0
  245. package/dist/utilsController.d.ts +106 -0
  246. package/dist/utilsController.js +863 -0
  247. package/package.json +75 -0
  248. package/scripts/copy-templates.ts +23 -0
  249. package/src/adapters/AdapterFactory.ts +510 -0
  250. package/src/adapters/DatabaseAdapter.ts +306 -0
  251. package/src/adapters/LegacyAdapter.ts +841 -0
  252. package/src/adapters/TablesDBAdapter.ts +773 -0
  253. package/src/adapters/index.ts +37 -0
  254. package/src/backups/operations/bucketBackup.ts +277 -0
  255. package/src/backups/operations/collectionBackup.ts +310 -0
  256. package/src/backups/operations/comprehensiveBackup.ts +342 -0
  257. package/src/backups/schemas/bucketManifest.ts +78 -0
  258. package/src/backups/schemas/comprehensiveManifest.ts +76 -0
  259. package/src/backups/tracking/centralizedTracking.ts +352 -0
  260. package/src/cli/commands/configCommands.ts +201 -0
  261. package/src/cli/commands/databaseCommands.ts +749 -0
  262. package/src/cli/commands/functionCommands.ts +418 -0
  263. package/src/cli/commands/schemaCommands.ts +200 -0
  264. package/src/cli/commands/storageCommands.ts +152 -0
  265. package/src/cli/commands/transferCommands.ts +457 -0
  266. package/src/collections/attributes.ts +2054 -0
  267. package/src/collections/attributes.ts.backup +1555 -0
  268. package/src/collections/indexes.ts +352 -0
  269. package/src/collections/methods.ts +745 -0
  270. package/src/collections/tableOperations.ts +506 -0
  271. package/src/collections/transferOperations.ts +590 -0
  272. package/src/collections/wipeOperations.ts +346 -0
  273. package/src/config/ConfigManager.ts +808 -0
  274. package/src/config/README.md +274 -0
  275. package/src/config/configMigration.ts +575 -0
  276. package/src/config/configValidation.ts +445 -0
  277. package/src/config/index.ts +10 -0
  278. package/src/config/services/ConfigDiscoveryService.ts +463 -0
  279. package/src/config/services/ConfigLoaderService.ts +740 -0
  280. package/src/config/services/ConfigMergeService.ts +388 -0
  281. package/src/config/services/ConfigValidationService.ts +394 -0
  282. package/src/config/services/SessionAuthService.ts +565 -0
  283. package/src/config/services/__tests__/ConfigMergeService.test.ts +351 -0
  284. package/src/config/services/index.ts +29 -0
  285. package/src/config/yamlConfig.ts +761 -0
  286. package/src/databases/methods.ts +49 -0
  287. package/src/databases/setup.ts +77 -0
  288. package/src/examples/yamlTerminologyExample.ts +346 -0
  289. package/src/functions/deployments.ts +220 -0
  290. package/src/functions/fnConfigDiscovery.ts +103 -0
  291. package/src/functions/methods.ts +271 -0
  292. package/src/functions/pathResolution.ts +227 -0
  293. package/src/functions/templates/count-docs-in-collection/README.md +54 -0
  294. package/src/functions/templates/count-docs-in-collection/src/main.ts +159 -0
  295. package/src/functions/templates/count-docs-in-collection/src/request.ts +9 -0
  296. package/src/functions/templates/hono-typescript/README.md +286 -0
  297. package/src/functions/templates/hono-typescript/src/adapters/request.ts +74 -0
  298. package/src/functions/templates/hono-typescript/src/adapters/response.ts +106 -0
  299. package/src/functions/templates/hono-typescript/src/app.ts +180 -0
  300. package/src/functions/templates/hono-typescript/src/context.ts +103 -0
  301. package/src/functions/templates/hono-typescript/src/index.ts +54 -0
  302. package/src/functions/templates/hono-typescript/src/middleware/appwrite.ts +119 -0
  303. package/src/functions/templates/typescript-node/README.md +32 -0
  304. package/src/functions/templates/typescript-node/src/context.ts +103 -0
  305. package/src/functions/templates/typescript-node/src/index.ts +29 -0
  306. package/src/functions/templates/uv/README.md +31 -0
  307. package/src/functions/templates/uv/pyproject.toml +30 -0
  308. package/src/functions/templates/uv/src/__init__.py +0 -0
  309. package/src/functions/templates/uv/src/context.py +125 -0
  310. package/src/functions/templates/uv/src/index.py +46 -0
  311. package/src/init.ts +62 -0
  312. package/src/interactiveCLI.ts +1136 -0
  313. package/src/main.ts +1661 -0
  314. package/src/migrations/afterImportActions.ts +580 -0
  315. package/src/migrations/appwriteToX.ts +664 -0
  316. package/src/migrations/comprehensiveTransfer.ts +2285 -0
  317. package/src/migrations/dataLoader.ts +1702 -0
  318. package/src/migrations/importController.ts +428 -0
  319. package/src/migrations/importDataActions.ts +315 -0
  320. package/src/migrations/relationships.ts +334 -0
  321. package/src/migrations/services/DataTransformationService.ts +196 -0
  322. package/src/migrations/services/FileHandlerService.ts +311 -0
  323. package/src/migrations/services/ImportOrchestrator.ts +666 -0
  324. package/src/migrations/services/RateLimitManager.ts +363 -0
  325. package/src/migrations/services/RelationshipResolver.ts +461 -0
  326. package/src/migrations/services/UserMappingService.ts +345 -0
  327. package/src/migrations/services/ValidationService.ts +349 -0
  328. package/src/migrations/transfer.ts +1068 -0
  329. package/src/migrations/yaml/YamlImportConfigLoader.ts +439 -0
  330. package/src/migrations/yaml/YamlImportIntegration.ts +446 -0
  331. package/src/migrations/yaml/generateImportSchemas.ts +1354 -0
  332. package/src/schemas/authUser.ts +23 -0
  333. package/src/setup.ts +8 -0
  334. package/src/setupCommands.ts +603 -0
  335. package/src/setupController.ts +43 -0
  336. package/src/shared/attributeMapper.ts +229 -0
  337. package/src/shared/backupMetadataSchema.ts +93 -0
  338. package/src/shared/backupTracking.ts +211 -0
  339. package/src/shared/confirmationDialogs.ts +327 -0
  340. package/src/shared/errorUtils.ts +110 -0
  341. package/src/shared/functionManager.ts +525 -0
  342. package/src/shared/indexManager.ts +254 -0
  343. package/src/shared/jsonSchemaGenerator.ts +383 -0
  344. package/src/shared/logging.ts +149 -0
  345. package/src/shared/messageFormatter.ts +208 -0
  346. package/src/shared/migrationHelpers.ts +232 -0
  347. package/src/shared/operationLogger.ts +20 -0
  348. package/src/shared/operationQueue.ts +377 -0
  349. package/src/shared/operationsTable.ts +338 -0
  350. package/src/shared/operationsTableSchema.ts +60 -0
  351. package/src/shared/progressManager.ts +278 -0
  352. package/src/shared/pydanticModelGenerator.ts +618 -0
  353. package/src/shared/relationshipExtractor.ts +214 -0
  354. package/src/shared/schemaGenerator.ts +644 -0
  355. package/src/shared/selectionDialogs.ts +749 -0
  356. package/src/storage/backupCompression.ts +88 -0
  357. package/src/storage/methods.ts +698 -0
  358. package/src/storage/schemas.ts +205 -0
  359. package/src/types/node-appwrite-tablesdb.d.ts +44 -0
  360. package/src/types.ts +9 -0
  361. package/src/users/methods.ts +359 -0
  362. package/src/utils/ClientFactory.ts +240 -0
  363. package/src/utils/configDiscovery.ts +557 -0
  364. package/src/utils/configMigration.ts +348 -0
  365. package/src/utils/constantsGenerator.ts +369 -0
  366. package/src/utils/dataConverters.ts +159 -0
  367. package/src/utils/directoryUtils.ts +61 -0
  368. package/src/utils/getClientFromConfig.ts +257 -0
  369. package/src/utils/helperFunctions.ts +228 -0
  370. package/src/utils/index.ts +2 -0
  371. package/src/utils/loadConfigs.ts +449 -0
  372. package/src/utils/pathResolvers.ts +81 -0
  373. package/src/utils/projectConfig.ts +299 -0
  374. package/src/utils/retryFailedPromises.ts +29 -0
  375. package/src/utils/sessionAuth.ts +230 -0
  376. package/src/utils/setupFiles.ts +1238 -0
  377. package/src/utils/typeGuards.ts +65 -0
  378. package/src/utils/validationRules.ts +88 -0
  379. package/src/utils/versionDetection.ts +292 -0
  380. package/src/utils/yamlConverter.ts +542 -0
  381. package/src/utils/yamlLoader.ts +371 -0
  382. package/src/utilsController.ts +1203 -0
  383. package/tests/README.md +497 -0
  384. package/tests/adapters/AdapterFactory.test.ts +277 -0
  385. package/tests/integration/syncOperations.test.ts +463 -0
  386. package/tests/jest.config.js +25 -0
  387. package/tests/migration/configMigration.test.ts +546 -0
  388. package/tests/setup.ts +62 -0
  389. package/tests/testUtils.ts +340 -0
  390. package/tests/utils/loadConfigs.test.ts +350 -0
  391. package/tests/validation/configValidation.test.ts +412 -0
  392. package/tsconfig.json +44 -0
@@ -0,0 +1,2054 @@
1
+ import { Query, type Databases, type Models } from "node-appwrite";
2
+ import {
3
+ attributeSchema,
4
+ parseAttribute,
5
+ type Attribute,
6
+ } from "@njdamstra/appwrite-utils";
7
+ import {
8
+ nameToIdMapping,
9
+ enqueueOperation,
10
+ markAttributeProcessed,
11
+ isAttributeProcessed,
12
+ } from "../shared/operationQueue.js";
13
+ import {
14
+ delay,
15
+ tryAwaitWithRetry,
16
+ calculateExponentialBackoff,
17
+ } from "../utils/helperFunctions.js";
18
+ import chalk from "chalk";
19
+ import { Decimal } from "decimal.js";
20
+ import type { DatabaseAdapter, CreateAttributeParams, UpdateAttributeParams, DeleteAttributeParams } from "../adapters/DatabaseAdapter.js";
21
+ import { logger } from "../shared/logging.js";
22
+ import { MessageFormatter } from "../shared/messageFormatter.js";
23
+ import { isDatabaseAdapter } from "../utils/typeGuards.js";
24
+
25
+ // Extreme values that Appwrite may return, which should be treated as undefined
26
+ const EXTREME_MIN_INTEGER = -9223372036854776000;
27
+ const EXTREME_MAX_INTEGER = 9223372036854776000;
28
+ const EXTREME_MIN_FLOAT = -1.7976931348623157e308;
29
+ const EXTREME_MAX_FLOAT = 1.7976931348623157e308;
30
+
31
+ /**
32
+ * Type guard to check if an attribute has min/max properties
33
+ */
34
+ const hasMinMaxProperties = (
35
+ attribute: Attribute
36
+ ): attribute is Attribute & { min?: number; max?: number } => {
37
+ return (
38
+ attribute.type === "integer" ||
39
+ attribute.type === "double" ||
40
+ attribute.type === "float"
41
+ );
42
+ };
43
+
44
+ /**
45
+ * Normalizes min/max values for integer and float attributes using Decimal.js for precision
46
+ * Validates that min < max and handles extreme database values
47
+ */
48
+ const normalizeMinMaxValues = (
49
+ attribute: Attribute
50
+ ): { min?: number; max?: number } => {
51
+ if (!hasMinMaxProperties(attribute)) {
52
+ logger.debug(
53
+ `Attribute '${attribute.key}' does not have min/max properties`,
54
+ {
55
+ type: attribute.type,
56
+ operation: "normalizeMinMaxValues",
57
+ }
58
+ );
59
+ return {};
60
+ }
61
+
62
+ const { type, min, max } = attribute;
63
+ let normalizedMin = min;
64
+ let normalizedMax = max;
65
+
66
+ logger.debug(`Normalizing min/max values for attribute '${attribute.key}'`, {
67
+ type,
68
+ originalMin: min,
69
+ originalMax: max,
70
+ operation: "normalizeMinMaxValues",
71
+ });
72
+
73
+ // Handle min value - only filter out extreme database values
74
+ if (normalizedMin !== undefined && normalizedMin !== null) {
75
+ const minValue = Number(normalizedMin);
76
+ const originalMin = normalizedMin;
77
+
78
+ // Check if it's an extreme database value (but don't filter out large numbers)
79
+ if (type === 'integer') {
80
+ if (minValue === EXTREME_MIN_INTEGER) {
81
+ logger.debug(`Min value normalized to undefined for attribute '${attribute.key}'`, {
82
+ type,
83
+ originalValue: originalMin,
84
+ numericValue: minValue,
85
+ reason: 'extreme_database_value',
86
+ extremeValue: EXTREME_MIN_INTEGER,
87
+ operation: 'normalizeMinMaxValues'
88
+ });
89
+ normalizedMin = undefined;
90
+ }
91
+ } else { // float/double
92
+ if (minValue === EXTREME_MIN_FLOAT) {
93
+ logger.debug(`Min value normalized to undefined for attribute '${attribute.key}'`, {
94
+ type,
95
+ originalValue: originalMin,
96
+ numericValue: minValue,
97
+ reason: 'extreme_database_value',
98
+ extremeValue: EXTREME_MIN_FLOAT,
99
+ operation: 'normalizeMinMaxValues'
100
+ });
101
+ normalizedMin = undefined;
102
+ }
103
+ }
104
+ }
105
+
106
+ // Handle max value - only filter out extreme database values
107
+ if (normalizedMax !== undefined && normalizedMax !== null) {
108
+ const maxValue = Number(normalizedMax);
109
+ const originalMax = normalizedMax;
110
+
111
+ // Check if it's an extreme database value (but don't filter out large numbers)
112
+ if (type === 'integer') {
113
+ if (maxValue === EXTREME_MAX_INTEGER) {
114
+ logger.debug(`Max value normalized to undefined for attribute '${attribute.key}'`, {
115
+ type,
116
+ originalValue: originalMax,
117
+ numericValue: maxValue,
118
+ reason: 'extreme_database_value',
119
+ extremeValue: EXTREME_MAX_INTEGER,
120
+ operation: 'normalizeMinMaxValues'
121
+ });
122
+ normalizedMax = undefined;
123
+ }
124
+ } else { // float/double
125
+ if (maxValue === EXTREME_MAX_FLOAT) {
126
+ logger.debug(`Max value normalized to undefined for attribute '${attribute.key}'`, {
127
+ type,
128
+ originalValue: originalMax,
129
+ numericValue: maxValue,
130
+ reason: 'extreme_database_value',
131
+ extremeValue: EXTREME_MAX_FLOAT,
132
+ operation: 'normalizeMinMaxValues'
133
+ });
134
+ normalizedMax = undefined;
135
+ }
136
+ }
137
+ }
138
+
139
+ // Validate that min < max using multiple comparison methods for reliability
140
+ if (normalizedMin !== undefined && normalizedMax !== undefined &&
141
+ normalizedMin !== null && normalizedMax !== null) {
142
+
143
+ logger.debug(`Validating min/max values for attribute '${attribute.key}'`, {
144
+ type,
145
+ normalizedMin,
146
+ normalizedMax,
147
+ normalizedMinType: typeof normalizedMin,
148
+ normalizedMaxType: typeof normalizedMax,
149
+ operation: 'normalizeMinMaxValues'
150
+ });
151
+
152
+ // Use multiple validation approaches to ensure reliability
153
+ let needsSwap = false;
154
+ let comparisonMethod = '';
155
+
156
+ try {
157
+ // Method 1: Direct number comparison (most reliable for normal numbers)
158
+ const minNum = Number(normalizedMin);
159
+ const maxNum = Number(normalizedMax);
160
+
161
+ if (!isNaN(minNum) && !isNaN(maxNum)) {
162
+ needsSwap = minNum >= maxNum;
163
+ comparisonMethod = 'direct_number_comparison';
164
+ logger.debug(`Direct number comparison: ${minNum} >= ${maxNum} = ${needsSwap}`, {
165
+ operation: 'normalizeMinMaxValues'
166
+ });
167
+ }
168
+
169
+ // Method 2: Fallback to string comparison for very large numbers
170
+ if (!needsSwap && (isNaN(minNum) || isNaN(maxNum) || Math.abs(minNum) > Number.MAX_SAFE_INTEGER || Math.abs(maxNum) > Number.MAX_SAFE_INTEGER)) {
171
+ const minStr = normalizedMin.toString();
172
+ const maxStr = normalizedMax.toString();
173
+
174
+ // Simple string length and lexicographical comparison for very large numbers
175
+ if (minStr.length !== maxStr.length) {
176
+ needsSwap = minStr.length > maxStr.length;
177
+ } else {
178
+ needsSwap = minStr >= maxStr;
179
+ }
180
+ comparisonMethod = 'string_comparison_fallback';
181
+ logger.debug(`String comparison fallback: '${minStr}' >= '${maxStr}' = ${needsSwap}`, {
182
+ operation: 'normalizeMinMaxValues'
183
+ });
184
+ }
185
+
186
+ // Method 3: Final validation using Decimal.js as last resort
187
+ if (!needsSwap && (typeof normalizedMin === 'string' || typeof normalizedMax === 'string')) {
188
+ try {
189
+ const minDecimal = new Decimal(normalizedMin.toString());
190
+ const maxDecimal = new Decimal(normalizedMax.toString());
191
+ needsSwap = minDecimal.greaterThanOrEqualTo(maxDecimal);
192
+ comparisonMethod = 'decimal_js_fallback';
193
+ logger.debug(`Decimal.js fallback: ${normalizedMin} >= ${normalizedMax} = ${needsSwap}`, {
194
+ operation: 'normalizeMinMaxValues'
195
+ });
196
+ } catch (decimalError) {
197
+ logger.warn(`Decimal.js comparison failed for attribute '${attribute.key}': ${decimalError instanceof Error ? decimalError.message : String(decimalError)}`, {
198
+ operation: 'normalizeMinMaxValues'
199
+ });
200
+ }
201
+ }
202
+
203
+ // Log final validation result
204
+ if (needsSwap) {
205
+ logger.error(`Invalid min/max values detected for attribute '${attribute.key}': min (${normalizedMin}) must be less than max (${normalizedMax})`, {
206
+ type,
207
+ min: normalizedMin,
208
+ max: normalizedMax,
209
+ comparisonMethod,
210
+ operation: 'normalizeMinMaxValues'
211
+ });
212
+
213
+ // Swap values to ensure min < max (graceful handling)
214
+ logger.warn(`Swapping min/max values for attribute '${attribute.key}' to fix validation`, {
215
+ type,
216
+ originalMin: normalizedMin,
217
+ originalMax: normalizedMax,
218
+ newMin: normalizedMax,
219
+ newMax: normalizedMin,
220
+ comparisonMethod,
221
+ operation: 'normalizeMinMaxValues'
222
+ });
223
+
224
+ const temp = normalizedMin;
225
+ normalizedMin = normalizedMax;
226
+ normalizedMax = temp;
227
+ } else {
228
+ logger.debug(`Min/max validation passed for attribute '${attribute.key}'`, {
229
+ type,
230
+ min: normalizedMin,
231
+ max: normalizedMax,
232
+ comparisonMethod,
233
+ operation: 'normalizeMinMaxValues'
234
+ });
235
+ }
236
+
237
+ } catch (error) {
238
+ logger.error(`Critical error during min/max validation for attribute '${attribute.key}'`, {
239
+ type,
240
+ min: normalizedMin,
241
+ max: normalizedMax,
242
+ error: error instanceof Error ? error.message : String(error),
243
+ operation: 'normalizeMinMaxValues'
244
+ });
245
+
246
+ // If all comparison methods fail, set both to undefined to avoid API errors
247
+ normalizedMin = undefined;
248
+ normalizedMax = undefined;
249
+ }
250
+ }
251
+
252
+ const result = { min: normalizedMin, max: normalizedMax };
253
+ logger.debug(
254
+ `Min/max normalization complete for attribute '${attribute.key}'`,
255
+ {
256
+ type,
257
+ result,
258
+ operation: "normalizeMinMaxValues",
259
+ }
260
+ );
261
+
262
+ return result;
263
+ };
264
+
265
+ /**
266
+ * Normalizes an attribute for comparison by handling extreme database values
267
+ * This is used when comparing database attributes with config attributes
268
+ */
269
+ const normalizeAttributeForComparison = (attribute: Attribute): Attribute => {
270
+ const normalized: any = { ...attribute };
271
+
272
+ // Ignore defaults on required attributes to prevent false positives
273
+ if (normalized.required === true && "xdefault" in normalized) {
274
+ delete normalized.xdefault;
275
+ }
276
+
277
+ // Normalize min/max for numeric types
278
+ if (hasMinMaxProperties(attribute)) {
279
+ const { min, max } = normalizeMinMaxValues(attribute);
280
+ normalized.min = min;
281
+ normalized.max = max;
282
+ }
283
+
284
+ // Remove xdefault if null/undefined to ensure consistent comparison
285
+ // Appwrite sets xdefault: null for required attributes, but config files omit it
286
+ if (
287
+ "xdefault" in normalized &&
288
+ (normalized.xdefault === null || normalized.xdefault === undefined)
289
+ ) {
290
+ delete normalized.xdefault;
291
+ }
292
+
293
+ return normalized;
294
+ };
295
+
296
+ /**
297
+ * Helper function to create an attribute using either the adapter or legacy API
298
+ */
299
+ const createAttributeViaAdapter = async (
300
+ db: Databases | DatabaseAdapter,
301
+ dbId: string,
302
+ collectionId: string,
303
+ attribute: Attribute
304
+ ): Promise<void> => {
305
+ const startTime = Date.now();
306
+ const adapterType = isDatabaseAdapter(db) ? "adapter" : "legacy";
307
+
308
+ logger.info(`Creating attribute '${attribute.key}' via ${adapterType}`, {
309
+ type: attribute.type,
310
+ dbId,
311
+ collectionId,
312
+ adapterType,
313
+ operation: "createAttributeViaAdapter",
314
+ });
315
+
316
+ if (isDatabaseAdapter(db)) {
317
+ // Use the adapter's unified createAttribute method
318
+ const params: CreateAttributeParams = {
319
+ databaseId: dbId,
320
+ tableId: collectionId,
321
+ key: attribute.key,
322
+ type: attribute.type,
323
+ required: attribute.required || false,
324
+ array: attribute.array || false,
325
+ ...((attribute as any).size && { size: (attribute as any).size }),
326
+ ...((attribute as any).xdefault !== undefined &&
327
+ !attribute.required && { default: (attribute as any).xdefault }),
328
+ ...((attribute as any).encrypt && {
329
+ encrypt: (attribute as any).encrypt,
330
+ }),
331
+ ...((attribute as any).min !== undefined && {
332
+ min: (attribute as any).min,
333
+ }),
334
+ ...((attribute as any).max !== undefined && {
335
+ max: (attribute as any).max,
336
+ }),
337
+ ...((attribute as any).elements && {
338
+ elements: (attribute as any).elements,
339
+ }),
340
+ ...((attribute as any).relatedCollection && {
341
+ relatedCollection: (attribute as any).relatedCollection,
342
+ }),
343
+ ...((attribute as any).relationType && {
344
+ relationType: (attribute as any).relationType,
345
+ }),
346
+ ...((attribute as any).twoWay !== undefined && {
347
+ twoWay: (attribute as any).twoWay,
348
+ }),
349
+ ...((attribute as any).onDelete && {
350
+ onDelete: (attribute as any).onDelete,
351
+ }),
352
+ ...((attribute as any).twoWayKey && {
353
+ twoWayKey: (attribute as any).twoWayKey,
354
+ }),
355
+ };
356
+
357
+ logger.debug(`Adapter create parameters for '${attribute.key}'`, {
358
+ params,
359
+ operation: "createAttributeViaAdapter",
360
+ });
361
+
362
+ await db.createAttribute(params);
363
+
364
+ const duration = Date.now() - startTime;
365
+ logger.info(
366
+ `Successfully created attribute '${attribute.key}' via adapter`,
367
+ {
368
+ duration,
369
+ operation: "createAttributeViaAdapter",
370
+ }
371
+ );
372
+ } else {
373
+ // Use legacy type-specific methods
374
+ logger.debug(`Using legacy creation for attribute '${attribute.key}'`, {
375
+ operation: "createAttributeViaAdapter",
376
+ });
377
+ await createLegacyAttribute(db, dbId, collectionId, attribute);
378
+
379
+ const duration = Date.now() - startTime;
380
+ logger.info(
381
+ `Successfully created attribute '${attribute.key}' via legacy`,
382
+ {
383
+ duration,
384
+ operation: "createAttributeViaAdapter",
385
+ }
386
+ );
387
+ }
388
+ };
389
+
390
+ /**
391
+ * Helper function to update an attribute using either the adapter or legacy API
392
+ */
393
+ const updateAttributeViaAdapter = async (
394
+ db: Databases | DatabaseAdapter,
395
+ dbId: string,
396
+ collectionId: string,
397
+ attribute: Attribute
398
+ ): Promise<void> => {
399
+ if (isDatabaseAdapter(db)) {
400
+ // Use the adapter's unified updateAttribute method
401
+ const params: UpdateAttributeParams = {
402
+ databaseId: dbId,
403
+ tableId: collectionId,
404
+ key: attribute.key,
405
+ type: attribute.type,
406
+ required: attribute.required || false,
407
+ array: attribute.array || false,
408
+ size: (attribute as any).size,
409
+ min: (attribute as any).min,
410
+ max: (attribute as any).max,
411
+ encrypt: (attribute as any).encrypt,
412
+ elements: (attribute as any).elements,
413
+ relatedCollection: (attribute as any).relatedCollection,
414
+ relationType: (attribute as any).relationType,
415
+ twoWay: (attribute as any).twoWay,
416
+ twoWayKey: (attribute as any).twoWayKey,
417
+ onDelete: (attribute as any).onDelete
418
+ };
419
+ if (!attribute.required && (attribute as any).xdefault !== undefined) {
420
+ params.default = (attribute as any).xdefault;
421
+ }
422
+ await db.updateAttribute(params);
423
+ } else {
424
+ // Use legacy type-specific methods
425
+ await updateLegacyAttribute(db, dbId, collectionId, attribute);
426
+ }
427
+ };
428
+
429
+ /**
430
+ * Legacy attribute creation using type-specific methods
431
+ */
432
+ const createLegacyAttribute = async (
433
+ db: Databases,
434
+ dbId: string,
435
+ collectionId: string,
436
+ attribute: Attribute
437
+ ): Promise<void> => {
438
+ const startTime = Date.now();
439
+ const { min: normalizedMin, max: normalizedMax } =
440
+ normalizeMinMaxValues(attribute);
441
+
442
+ logger.info(`Creating legacy attribute '${attribute.key}'`, {
443
+ type: attribute.type,
444
+ dbId,
445
+ collectionId,
446
+ normalizedMin,
447
+ normalizedMax,
448
+ operation: "createLegacyAttribute",
449
+ });
450
+
451
+ switch (attribute.type) {
452
+ case "string":
453
+ const stringParams = {
454
+ size: (attribute as any).size || 255,
455
+ required: attribute.required || false,
456
+ defaultValue:
457
+ (attribute as any).xdefault !== undefined && !attribute.required
458
+ ? (attribute as any).xdefault
459
+ : undefined,
460
+ array: attribute.array || false,
461
+ encrypt: (attribute as any).encrypt,
462
+ };
463
+ logger.debug(`Creating string attribute '${attribute.key}'`, {
464
+ ...stringParams,
465
+ operation: "createLegacyAttribute",
466
+ });
467
+ await db.createStringAttribute(
468
+ dbId,
469
+ collectionId,
470
+ attribute.key,
471
+ stringParams.size,
472
+ stringParams.required,
473
+ stringParams.defaultValue,
474
+ stringParams.array,
475
+ stringParams.encrypt
476
+ );
477
+ break;
478
+ case "integer":
479
+ const integerParams = {
480
+ required: attribute.required || false,
481
+ min:
482
+ normalizedMin !== undefined
483
+ ? parseInt(String(normalizedMin))
484
+ : undefined,
485
+ max:
486
+ normalizedMax !== undefined
487
+ ? parseInt(String(normalizedMax))
488
+ : undefined,
489
+ defaultValue:
490
+ (attribute as any).xdefault !== undefined && !attribute.required
491
+ ? (attribute as any).xdefault
492
+ : undefined,
493
+ array: attribute.array || false,
494
+ };
495
+ logger.debug(`Creating integer attribute '${attribute.key}'`, {
496
+ ...integerParams,
497
+ operation: "createLegacyAttribute",
498
+ });
499
+ await db.createIntegerAttribute(
500
+ dbId,
501
+ collectionId,
502
+ attribute.key,
503
+ integerParams.required,
504
+ integerParams.min,
505
+ integerParams.max,
506
+ integerParams.defaultValue,
507
+ integerParams.array
508
+ );
509
+ break;
510
+ case "double":
511
+ case "float":
512
+ await db.createFloatAttribute(
513
+ dbId,
514
+ collectionId,
515
+ attribute.key,
516
+ attribute.required || false,
517
+ normalizedMin !== undefined ? Number(normalizedMin) : undefined,
518
+ normalizedMax !== undefined ? Number(normalizedMax) : undefined,
519
+ (attribute as any).xdefault !== undefined && !attribute.required
520
+ ? (attribute as any).xdefault
521
+ : undefined,
522
+ attribute.array || false
523
+ );
524
+ break;
525
+ case "boolean":
526
+ await db.createBooleanAttribute(
527
+ dbId,
528
+ collectionId,
529
+ attribute.key,
530
+ attribute.required || false,
531
+ (attribute as any).xdefault !== undefined && !attribute.required
532
+ ? (attribute as any).xdefault
533
+ : undefined,
534
+ attribute.array || false
535
+ );
536
+ break;
537
+ case "datetime":
538
+ await db.createDatetimeAttribute(
539
+ dbId,
540
+ collectionId,
541
+ attribute.key,
542
+ attribute.required || false,
543
+ (attribute as any).xdefault !== undefined && !attribute.required
544
+ ? (attribute as any).xdefault
545
+ : undefined,
546
+ attribute.array || false
547
+ );
548
+ break;
549
+ case "email":
550
+ await db.createEmailAttribute(
551
+ dbId,
552
+ collectionId,
553
+ attribute.key,
554
+ attribute.required || false,
555
+ (attribute as any).xdefault !== undefined && !attribute.required
556
+ ? (attribute as any).xdefault
557
+ : undefined,
558
+ attribute.array || false
559
+ );
560
+ break;
561
+ case "ip":
562
+ await db.createIpAttribute(
563
+ dbId,
564
+ collectionId,
565
+ attribute.key,
566
+ attribute.required || false,
567
+ (attribute as any).xdefault !== undefined && !attribute.required
568
+ ? (attribute as any).xdefault
569
+ : undefined,
570
+ attribute.array || false
571
+ );
572
+ break;
573
+ case "url":
574
+ await db.createUrlAttribute(
575
+ dbId,
576
+ collectionId,
577
+ attribute.key,
578
+ attribute.required || false,
579
+ (attribute as any).xdefault !== undefined && !attribute.required
580
+ ? (attribute as any).xdefault
581
+ : undefined,
582
+ attribute.array || false
583
+ );
584
+ break;
585
+ case "enum":
586
+ await db.createEnumAttribute(
587
+ dbId,
588
+ collectionId,
589
+ attribute.key,
590
+ (attribute as any).elements || [],
591
+ attribute.required || false,
592
+ (attribute as any).xdefault !== undefined && !attribute.required
593
+ ? (attribute as any).xdefault
594
+ : undefined,
595
+ attribute.array || false
596
+ );
597
+ break;
598
+ case "relationship":
599
+ await db.createRelationshipAttribute(
600
+ dbId,
601
+ collectionId,
602
+ (attribute as any).relatedCollection!,
603
+ (attribute as any).relationType!,
604
+ (attribute as any).twoWay,
605
+ attribute.key,
606
+ (attribute as any).twoWayKey,
607
+ (attribute as any).onDelete
608
+ );
609
+ break;
610
+ default:
611
+ const error = new Error(
612
+ `Unsupported attribute type: ${(attribute as any).type}`
613
+ );
614
+ logger.error(
615
+ `Unsupported attribute type for '${(attribute as any).key}'`,
616
+ {
617
+ type: (attribute as any).type,
618
+ supportedTypes: [
619
+ "string",
620
+ "integer",
621
+ "double",
622
+ "float",
623
+ "boolean",
624
+ "datetime",
625
+ "email",
626
+ "ip",
627
+ "url",
628
+ "enum",
629
+ "relationship",
630
+ ],
631
+ operation: "createLegacyAttribute",
632
+ }
633
+ );
634
+ throw error;
635
+ }
636
+
637
+ const duration = Date.now() - startTime;
638
+ logger.info(`Successfully created legacy attribute '${attribute.key}'`, {
639
+ type: attribute.type,
640
+ duration,
641
+ operation: "createLegacyAttribute",
642
+ });
643
+ };
644
+
645
+ /**
646
+ * Legacy attribute update using type-specific methods
647
+ */
648
+ const updateLegacyAttribute = async (
649
+ db: Databases,
650
+ dbId: string,
651
+ collectionId: string,
652
+ attribute: Attribute
653
+ ): Promise<void> => {
654
+ console.log(`DEBUG updateLegacyAttribute before normalizeMinMaxValues:`, {
655
+ key: attribute.key,
656
+ type: attribute.type,
657
+ min: (attribute as any).min,
658
+ max: (attribute as any).max
659
+ });
660
+
661
+ const { min: normalizedMin, max: normalizedMax } =
662
+ normalizeMinMaxValues(attribute);
663
+
664
+
665
+
666
+ switch (attribute.type) {
667
+ case "string":
668
+ await db.updateStringAttribute(
669
+ dbId,
670
+ collectionId,
671
+ attribute.key,
672
+ attribute.required || false,
673
+ !attribute.required && (attribute as any).xdefault !== undefined
674
+ ? (attribute as any).xdefault
675
+ : null,
676
+ attribute.size
677
+ );
678
+ break;
679
+ case "integer":
680
+ await db.updateIntegerAttribute(
681
+ dbId,
682
+ collectionId,
683
+ attribute.key,
684
+ attribute.required || false,
685
+ !attribute.required && (attribute as any).xdefault !== undefined
686
+ ? (attribute as any).xdefault
687
+ : null,
688
+ normalizedMin !== undefined
689
+ ? parseInt(String(normalizedMin))
690
+ : undefined,
691
+ normalizedMax !== undefined
692
+ ? parseInt(String(normalizedMax))
693
+ : undefined
694
+ );
695
+ break;
696
+ case "double":
697
+ case "float":
698
+ const minParam = normalizedMin !== undefined ? Number(normalizedMin) : undefined;
699
+ const maxParam = normalizedMax !== undefined ? Number(normalizedMax) : undefined;
700
+
701
+
702
+
703
+ await db.updateFloatAttribute(
704
+ dbId,
705
+ collectionId,
706
+ attribute.key,
707
+ attribute.required || false,
708
+ minParam,
709
+ maxParam,
710
+ !attribute.required && (attribute as any).xdefault !== undefined
711
+ ? (attribute as any).xdefault
712
+ : null
713
+ );
714
+ break;
715
+ case "boolean":
716
+ await db.updateBooleanAttribute(
717
+ dbId,
718
+ collectionId,
719
+ attribute.key,
720
+ attribute.required || false,
721
+ !attribute.required && (attribute as any).xdefault !== undefined
722
+ ? (attribute as any).xdefault
723
+ : null
724
+ );
725
+ break;
726
+ case "datetime":
727
+ await db.updateDatetimeAttribute(
728
+ dbId,
729
+ collectionId,
730
+ attribute.key,
731
+ attribute.required || false,
732
+ !attribute.required && (attribute as any).xdefault !== undefined
733
+ ? (attribute as any).xdefault
734
+ : null
735
+ );
736
+ break;
737
+ case "email":
738
+ await db.updateEmailAttribute(
739
+ dbId,
740
+ collectionId,
741
+ attribute.key,
742
+ attribute.required || false,
743
+ !attribute.required && (attribute as any).xdefault !== undefined
744
+ ? (attribute as any).xdefault
745
+ : null
746
+ );
747
+ break;
748
+ case "ip":
749
+ await db.updateIpAttribute(
750
+ dbId,
751
+ collectionId,
752
+ attribute.key,
753
+ attribute.required || false,
754
+ !attribute.required && (attribute as any).xdefault !== undefined
755
+ ? (attribute as any).xdefault
756
+ : null
757
+ );
758
+ break;
759
+ case "url":
760
+ await db.updateUrlAttribute(
761
+ dbId,
762
+ collectionId,
763
+ attribute.key,
764
+ attribute.required || false,
765
+ !attribute.required && (attribute as any).xdefault !== undefined
766
+ ? (attribute as any).xdefault
767
+ : null
768
+ );
769
+ break;
770
+ case "enum":
771
+ await db.updateEnumAttribute(
772
+ dbId,
773
+ collectionId,
774
+ attribute.key,
775
+ (attribute as any).elements || [],
776
+ attribute.required || false,
777
+ !attribute.required && (attribute as any).xdefault !== undefined
778
+ ? (attribute as any).xdefault
779
+ : null
780
+ );
781
+ break;
782
+ case "relationship":
783
+ await db.updateRelationshipAttribute(
784
+ dbId,
785
+ collectionId,
786
+ attribute.key,
787
+ (attribute as any).onDelete
788
+ );
789
+ break;
790
+ default:
791
+ throw new Error(
792
+ `Unsupported attribute type for update: ${(attribute as any).type}`
793
+ );
794
+ }
795
+ };
796
+
797
+ // Interface for attribute with status (fixing the type issue)
798
+ interface AttributeWithStatus {
799
+ key: string;
800
+ type: string;
801
+ status: "available" | "processing" | "deleting" | "stuck" | "failed";
802
+ error: string;
803
+ required: boolean;
804
+ array?: boolean;
805
+ $createdAt: string;
806
+ $updatedAt: string;
807
+ [key: string]: any; // For type-specific fields
808
+ }
809
+
810
+ /**
811
+ * Wait for attribute to become available, with retry logic for stuck attributes and exponential backoff
812
+ */
813
+ const waitForAttributeAvailable = async (
814
+ db: Databases | DatabaseAdapter,
815
+ dbId: string,
816
+ collectionId: string,
817
+ attributeKey: string,
818
+ maxWaitTime: number = 60000, // 1 minute
819
+ retryCount: number = 0,
820
+ maxRetries: number = 5
821
+ ): Promise<boolean> => {
822
+ const startTime = Date.now();
823
+ let checkInterval = 2000; // Start with 2 seconds
824
+
825
+ logger.info(`Waiting for attribute '${attributeKey}' to become available`, {
826
+ dbId,
827
+ collectionId,
828
+ maxWaitTime,
829
+ retryCount,
830
+ maxRetries,
831
+ operation: "waitForAttributeAvailable",
832
+ });
833
+
834
+ // Calculate exponential backoff: 2s, 4s, 8s, 16s, 30s (capped at 30s)
835
+ if (retryCount > 0) {
836
+ const exponentialDelay = calculateExponentialBackoff(retryCount);
837
+ await delay(exponentialDelay);
838
+ }
839
+
840
+ while (Date.now() - startTime < maxWaitTime) {
841
+ try {
842
+ const collection = isDatabaseAdapter(db)
843
+ ? (await db.getTable({ databaseId: dbId, tableId: collectionId })).data
844
+ : await db.getCollection(dbId, collectionId);
845
+ const attribute = (collection.attributes as any[]).find(
846
+ (attr: AttributeWithStatus) => attr.key === attributeKey
847
+ ) as AttributeWithStatus | undefined;
848
+
849
+ if (!attribute) {
850
+ MessageFormatter.error(`Attribute '${attributeKey}' not found`);
851
+ return false;
852
+ }
853
+
854
+ const statusInfo = {
855
+ attributeKey,
856
+ status: attribute.status,
857
+ error: attribute.error,
858
+ dbId,
859
+ collectionId,
860
+ waitTime: Date.now() - startTime,
861
+ operation: "waitForAttributeAvailable",
862
+ };
863
+
864
+ switch (attribute.status) {
865
+ case "available":
866
+ logger.info(
867
+ `Attribute '${attributeKey}' became available`,
868
+ statusInfo
869
+ );
870
+ return true;
871
+
872
+ case "failed":
873
+ logger.error(`Attribute '${attributeKey}' failed`, statusInfo);
874
+ return false;
875
+
876
+ case "stuck":
877
+ logger.warn(`Attribute '${attributeKey}' is stuck`, statusInfo);
878
+ return false;
879
+
880
+ case "processing":
881
+ // Continue waiting
882
+ logger.debug(
883
+ `Attribute '${attributeKey}' still processing`,
884
+ statusInfo
885
+ );
886
+ break;
887
+
888
+ case "deleting":
889
+ MessageFormatter.info(
890
+ chalk.yellow(`Attribute '${attributeKey}' is being deleted`)
891
+ );
892
+ logger.warn(
893
+ `Attribute '${attributeKey}' is being deleted`,
894
+ statusInfo
895
+ );
896
+ break;
897
+
898
+ default:
899
+ MessageFormatter.info(
900
+ chalk.yellow(
901
+ `Unknown status '${attribute.status}' for attribute '${attributeKey}'`
902
+ )
903
+ );
904
+ logger.warn(
905
+ `Unknown status for attribute '${attributeKey}'`,
906
+ statusInfo
907
+ );
908
+ break;
909
+ }
910
+
911
+ await delay(checkInterval);
912
+ } catch (error) {
913
+ const errorMessage =
914
+ error instanceof Error ? error.message : String(error);
915
+ MessageFormatter.error(
916
+ `Error checking attribute status: ${errorMessage}`
917
+ );
918
+
919
+ logger.error("Error checking attribute status", {
920
+ attributeKey,
921
+ dbId,
922
+ collectionId,
923
+ error: errorMessage,
924
+ waitTime: Date.now() - startTime,
925
+ operation: "waitForAttributeAvailable",
926
+ });
927
+
928
+ return false;
929
+ }
930
+ }
931
+
932
+ // Timeout reached
933
+ MessageFormatter.info(
934
+ chalk.yellow(
935
+ `⏰ Timeout waiting for attribute '${attributeKey}' (${maxWaitTime}ms)`
936
+ )
937
+ );
938
+
939
+ // If we have retries left and this isn't the last retry, try recreating
940
+ if (retryCount < maxRetries) {
941
+ MessageFormatter.info(
942
+ chalk.yellow(
943
+ `🔄 Retrying attribute creation (attempt ${
944
+ retryCount + 1
945
+ }/${maxRetries})`
946
+ )
947
+ );
948
+ return false; // Signal that we need to retry
949
+ }
950
+
951
+ return false;
952
+ };
953
+
954
+ /**
955
+ * Wait for all attributes in a collection to become available
956
+ */
957
+ const waitForAllAttributesAvailable = async (
958
+ db: Databases | DatabaseAdapter,
959
+ dbId: string,
960
+ collectionId: string,
961
+ attributeKeys: string[],
962
+ maxWaitTime: number = 60000
963
+ ): Promise<string[]> => {
964
+ MessageFormatter.info(
965
+ chalk.blue(
966
+ `Waiting for ${attributeKeys.length} attributes to become available...`
967
+ )
968
+ );
969
+
970
+ const failedAttributes: string[] = [];
971
+
972
+ for (const attributeKey of attributeKeys) {
973
+ const success = await waitForAttributeAvailable(
974
+ db,
975
+ dbId,
976
+ collectionId,
977
+ attributeKey,
978
+ maxWaitTime
979
+ );
980
+ if (!success) {
981
+ failedAttributes.push(attributeKey);
982
+ }
983
+ }
984
+
985
+ return failedAttributes;
986
+ };
987
+
988
+ /**
989
+ * Delete collection and recreate with retry logic
990
+ */
991
+ const deleteAndRecreateCollection = async (
992
+ db: Databases | DatabaseAdapter,
993
+ dbId: string,
994
+ collection: Models.Collection,
995
+ retryCount: number
996
+ ): Promise<Models.Collection | null> => {
997
+ try {
998
+ MessageFormatter.info(
999
+ chalk.yellow(
1000
+ `🗑️ Deleting collection '${collection.name}' for retry ${retryCount}`
1001
+ )
1002
+ );
1003
+
1004
+ // Delete the collection
1005
+ if (isDatabaseAdapter(db)) {
1006
+ await db.deleteTable({ databaseId: dbId, tableId: collection.$id });
1007
+ } else {
1008
+ await db.deleteCollection(dbId, collection.$id);
1009
+ }
1010
+ MessageFormatter.warning(`Deleted collection '${collection.name}'`);
1011
+
1012
+ // Wait a bit before recreating
1013
+ await delay(2000);
1014
+
1015
+ // Recreate the collection
1016
+ MessageFormatter.info(`🔄 Recreating collection '${collection.name}'`);
1017
+ const newCollection = isDatabaseAdapter(db)
1018
+ ? (
1019
+ await db.createTable({
1020
+ databaseId: dbId,
1021
+ id: collection.$id,
1022
+ name: collection.name,
1023
+ permissions: collection.$permissions,
1024
+ documentSecurity: collection.documentSecurity,
1025
+ enabled: collection.enabled,
1026
+ })
1027
+ ).data
1028
+ : await db.createCollection(
1029
+ dbId,
1030
+ collection.$id,
1031
+ collection.name,
1032
+ collection.$permissions,
1033
+ collection.documentSecurity,
1034
+ collection.enabled
1035
+ );
1036
+
1037
+ MessageFormatter.success(`✅ Recreated collection '${collection.name}'`);
1038
+ return newCollection;
1039
+ } catch (error) {
1040
+ MessageFormatter.info(
1041
+ chalk.red(
1042
+ `Failed to delete/recreate collection '${collection.name}': ${error}`
1043
+ )
1044
+ );
1045
+ return null;
1046
+ }
1047
+ };
1048
+
1049
+ /**
1050
+ * Get the fields that should be compared for a specific attribute type
1051
+ * Only returns fields that are valid for the given type to avoid false positives
1052
+ */
1053
+ const getComparableFields = (type: string): string[] => {
1054
+ const baseFields = ["key", "type", "array", "required", "xdefault"];
1055
+
1056
+ switch (type) {
1057
+ case "string":
1058
+ return [...baseFields, "size", "encrypt"];
1059
+
1060
+ case "integer":
1061
+ case "double":
1062
+ case "float":
1063
+ return [...baseFields, "min", "max"];
1064
+
1065
+ case "enum":
1066
+ return [...baseFields, "elements"];
1067
+
1068
+ case "relationship":
1069
+ return [
1070
+ ...baseFields,
1071
+ "relationType",
1072
+ "twoWay",
1073
+ "twoWayKey",
1074
+ "onDelete",
1075
+ "relatedCollection",
1076
+ ];
1077
+
1078
+ case "boolean":
1079
+ case "datetime":
1080
+ case "email":
1081
+ case "ip":
1082
+ case "url":
1083
+ return baseFields;
1084
+
1085
+ default:
1086
+ // Fallback to all fields for unknown types
1087
+ return [
1088
+ "key",
1089
+ "type",
1090
+ "array",
1091
+ "encrypt",
1092
+ "required",
1093
+ "size",
1094
+ "min",
1095
+ "max",
1096
+ "xdefault",
1097
+ "elements",
1098
+ "relationType",
1099
+ "twoWay",
1100
+ "twoWayKey",
1101
+ "onDelete",
1102
+ "relatedCollection",
1103
+ ];
1104
+ }
1105
+ };
1106
+
1107
+ const attributesSame = (
1108
+ databaseAttribute: Attribute,
1109
+ configAttribute: Attribute
1110
+ ): boolean => {
1111
+ // Normalize both attributes for comparison (handle extreme database values)
1112
+ const normalizedDbAttr = normalizeAttributeForComparison(databaseAttribute);
1113
+ const normalizedConfigAttr = normalizeAttributeForComparison(configAttribute);
1114
+
1115
+ // Use type-specific field list to avoid false positives from irrelevant fields
1116
+ const attributesToCheck = getComparableFields(normalizedConfigAttr.type);
1117
+ const fieldsToCheck = attributesToCheck.filter((attr) => {
1118
+ if (attr !== "xdefault") {
1119
+ return true;
1120
+ }
1121
+ const dbRequired = Boolean((normalizedDbAttr as any).required);
1122
+ const configRequired = Boolean((normalizedConfigAttr as any).required);
1123
+ return !(dbRequired || configRequired);
1124
+ });
1125
+
1126
+ const differences: string[] = [];
1127
+
1128
+ const result = fieldsToCheck.every((attr) => {
1129
+ // Check if both objects have the attribute
1130
+ const dbHasAttr = attr in normalizedDbAttr;
1131
+ const configHasAttr = attr in normalizedConfigAttr;
1132
+
1133
+ // If both have the attribute, compare values
1134
+ if (dbHasAttr && configHasAttr) {
1135
+ const dbValue = normalizedDbAttr[attr as keyof typeof normalizedDbAttr];
1136
+ const configValue =
1137
+ normalizedConfigAttr[attr as keyof typeof normalizedConfigAttr];
1138
+
1139
+ // Consider undefined and null as equivalent
1140
+ if (
1141
+ (dbValue === undefined || dbValue === null) &&
1142
+ (configValue === undefined || configValue === null)
1143
+ ) {
1144
+ return true;
1145
+ }
1146
+
1147
+ // Normalize booleans: treat undefined and false as equivalent
1148
+ if (typeof dbValue === "boolean" || typeof configValue === "boolean") {
1149
+ const boolMatch = Boolean(dbValue) === Boolean(configValue);
1150
+ if (!boolMatch) {
1151
+ differences.push(`${attr}: db=${dbValue} config=${configValue}`);
1152
+ }
1153
+ return boolMatch;
1154
+ }
1155
+ // For numeric comparisons, compare numbers if both are numeric-like
1156
+ if (
1157
+ (typeof dbValue === "number" ||
1158
+ (typeof dbValue === "string" &&
1159
+ dbValue !== "" &&
1160
+ !isNaN(Number(dbValue)))) &&
1161
+ (typeof configValue === "number" ||
1162
+ (typeof configValue === "string" &&
1163
+ configValue !== "" &&
1164
+ !isNaN(Number(configValue))))
1165
+ ) {
1166
+ const numMatch = Number(dbValue) === Number(configValue);
1167
+ if (!numMatch) {
1168
+ differences.push(`${attr}: db=${dbValue} config=${configValue}`);
1169
+ }
1170
+ return numMatch;
1171
+ }
1172
+
1173
+ // For array comparisons (e.g., enum elements), use order-independent equality
1174
+ if (Array.isArray(dbValue) && Array.isArray(configValue)) {
1175
+ const arrayMatch =
1176
+ dbValue.length === configValue.length &&
1177
+ dbValue.every((val) => configValue.includes(val));
1178
+ if (!arrayMatch) {
1179
+ differences.push(
1180
+ `${attr}: db=${JSON.stringify(dbValue)} config=${JSON.stringify(
1181
+ configValue
1182
+ )}`
1183
+ );
1184
+ }
1185
+ return arrayMatch;
1186
+ }
1187
+
1188
+ const match = dbValue === configValue;
1189
+ if (!match) {
1190
+ differences.push(
1191
+ `${attr}: db=${JSON.stringify(dbValue)} config=${JSON.stringify(
1192
+ configValue
1193
+ )}`
1194
+ );
1195
+ }
1196
+ return match;
1197
+ }
1198
+
1199
+ // If neither has the attribute, consider it the same
1200
+ if (!dbHasAttr && !configHasAttr) {
1201
+ return true;
1202
+ }
1203
+
1204
+ // If one has the attribute and the other doesn't, check if it's undefined or null
1205
+ if (dbHasAttr && !configHasAttr) {
1206
+ const dbValue = normalizedDbAttr[attr as keyof typeof normalizedDbAttr];
1207
+ // Consider default-false booleans as equal to missing in config
1208
+ if (typeof dbValue === "boolean") {
1209
+ const match = dbValue === false; // missing in config equals false in db
1210
+ if (!match) {
1211
+ differences.push(`${attr}: db=${dbValue} config=<missing>`);
1212
+ }
1213
+ return match;
1214
+ }
1215
+ const match = dbValue === undefined || dbValue === null;
1216
+ if (!match) {
1217
+ differences.push(
1218
+ `${attr}: db=${JSON.stringify(dbValue)} config=<missing>`
1219
+ );
1220
+ }
1221
+ return match;
1222
+ }
1223
+
1224
+ if (!dbHasAttr && configHasAttr) {
1225
+ const configValue =
1226
+ normalizedConfigAttr[attr as keyof typeof normalizedConfigAttr];
1227
+ // Consider default-false booleans as equal to missing in db
1228
+ if (typeof configValue === "boolean") {
1229
+ const match = configValue === false; // missing in db equals false in config
1230
+ if (!match) {
1231
+ differences.push(`${attr}: db=<missing> config=${configValue}`);
1232
+ }
1233
+ return match;
1234
+ }
1235
+ const match = configValue === undefined || configValue === null;
1236
+ if (!match) {
1237
+ differences.push(
1238
+ `${attr}: db=<missing> config=${JSON.stringify(configValue)}`
1239
+ );
1240
+ }
1241
+ return match;
1242
+ }
1243
+
1244
+ // If we reach here, the attributes are different
1245
+ differences.push(`${attr}: unexpected comparison state`);
1246
+ return false;
1247
+ });
1248
+
1249
+ if (!result && differences.length > 0) {
1250
+ logger.debug(
1251
+ `Attribute mismatch detected for '${normalizedConfigAttr.key}'`,
1252
+ {
1253
+ differences,
1254
+ dbAttribute: normalizedDbAttr,
1255
+ configAttribute: normalizedConfigAttr,
1256
+ operation: "attributesSame",
1257
+ }
1258
+ );
1259
+ }
1260
+
1261
+ return result;
1262
+ };
1263
+
1264
+ /**
1265
+ * Enhanced attribute creation with proper status monitoring and retry logic
1266
+ */
1267
+ export const createOrUpdateAttributeWithStatusCheck = async (
1268
+ db: Databases | DatabaseAdapter,
1269
+ dbId: string,
1270
+ collection: Models.Collection,
1271
+ attribute: Attribute,
1272
+ retryCount: number = 0,
1273
+ maxRetries: number = 5
1274
+ ): Promise<boolean> => {
1275
+ try {
1276
+ // First, try to create/update the attribute using existing logic
1277
+ const result = await createOrUpdateAttribute(
1278
+ db,
1279
+ dbId,
1280
+ collection,
1281
+ attribute
1282
+ );
1283
+
1284
+ // If the attribute was queued (relationship dependency unresolved),
1285
+ // skip status polling and retry logic — the queue will handle it later.
1286
+ if (result === "queued") {
1287
+ MessageFormatter.info(
1288
+ chalk.yellow(
1289
+ `⏭️ Deferred relationship attribute '${attribute.key}' — queued for later once dependencies are available`
1290
+ )
1291
+ );
1292
+ return true;
1293
+ }
1294
+
1295
+ // If collection creation failed, return false to indicate failure
1296
+ if (result === "error") {
1297
+ MessageFormatter.error(
1298
+ `Failed to create collection for attribute '${attribute.key}'`
1299
+ );
1300
+ return false;
1301
+ }
1302
+
1303
+ // Now wait for the attribute to become available
1304
+ const success = await waitForAttributeAvailable(
1305
+ db,
1306
+ dbId,
1307
+ collection.$id,
1308
+ attribute.key,
1309
+ 60000, // 1 minute timeout
1310
+ retryCount,
1311
+ maxRetries
1312
+ );
1313
+
1314
+ if (success) {
1315
+ return true;
1316
+ }
1317
+
1318
+ // If not successful and we have retries left, delete specific attribute and try again
1319
+ if (retryCount < maxRetries) {
1320
+ MessageFormatter.info(
1321
+ chalk.yellow(
1322
+ `Attribute '${attribute.key}' failed/stuck, deleting and retrying...`
1323
+ )
1324
+ );
1325
+
1326
+ // Try to delete the specific stuck attribute instead of the entire collection
1327
+ try {
1328
+ if (isDatabaseAdapter(db)) {
1329
+ await db.deleteAttribute({
1330
+ databaseId: dbId,
1331
+ tableId: collection.$id,
1332
+ key: attribute.key,
1333
+ });
1334
+ } else {
1335
+ await db.deleteAttribute(dbId, collection.$id, attribute.key);
1336
+ }
1337
+ MessageFormatter.info(
1338
+ chalk.yellow(
1339
+ `Deleted stuck attribute '${attribute.key}', will retry creation`
1340
+ )
1341
+ );
1342
+
1343
+ // Wait a bit before retry
1344
+ await delay(3000);
1345
+
1346
+ // Get fresh collection data
1347
+ const freshCollection = isDatabaseAdapter(db)
1348
+ ? (await db.getTable({ databaseId: dbId, tableId: collection.$id }))
1349
+ .data
1350
+ : await db.getCollection(dbId, collection.$id);
1351
+
1352
+ // Retry with the same collection (attribute should be gone now)
1353
+ return await createOrUpdateAttributeWithStatusCheck(
1354
+ db,
1355
+ dbId,
1356
+ freshCollection,
1357
+ attribute,
1358
+ retryCount + 1,
1359
+ maxRetries
1360
+ );
1361
+ } catch (deleteError) {
1362
+ MessageFormatter.info(
1363
+ chalk.red(
1364
+ `Failed to delete stuck attribute '${attribute.key}': ${deleteError}`
1365
+ )
1366
+ );
1367
+
1368
+ // If attribute deletion fails, only then try collection recreation as last resort
1369
+ if (retryCount >= maxRetries - 1) {
1370
+ MessageFormatter.info(
1371
+ chalk.yellow(
1372
+ `Last resort: Recreating collection for attribute '${attribute.key}'`
1373
+ )
1374
+ );
1375
+
1376
+ // Get fresh collection data
1377
+ const freshCollection = isDatabaseAdapter(db)
1378
+ ? (await db.getTable({ databaseId: dbId, tableId: collection.$id }))
1379
+ .data
1380
+ : await db.getCollection(dbId, collection.$id);
1381
+
1382
+ // Delete and recreate collection
1383
+ const newCollection = await deleteAndRecreateCollection(
1384
+ db,
1385
+ dbId,
1386
+ freshCollection,
1387
+ retryCount + 1
1388
+ );
1389
+
1390
+ if (newCollection) {
1391
+ // Retry with the new collection
1392
+ return await createOrUpdateAttributeWithStatusCheck(
1393
+ db,
1394
+ dbId,
1395
+ newCollection,
1396
+ attribute,
1397
+ retryCount + 1,
1398
+ maxRetries
1399
+ );
1400
+ }
1401
+ } else {
1402
+ // Continue to next retry without collection recreation
1403
+ return await createOrUpdateAttributeWithStatusCheck(
1404
+ db,
1405
+ dbId,
1406
+ collection,
1407
+ attribute,
1408
+ retryCount + 1,
1409
+ maxRetries
1410
+ );
1411
+ }
1412
+ }
1413
+ }
1414
+
1415
+ MessageFormatter.info(
1416
+ chalk.red(
1417
+ `❌ Failed to create attribute '${attribute.key}' after ${
1418
+ maxRetries + 1
1419
+ } attempts`
1420
+ )
1421
+ );
1422
+ return false;
1423
+ } catch (error) {
1424
+ MessageFormatter.info(
1425
+ chalk.red(`Error creating attribute '${attribute.key}': ${error}`)
1426
+ );
1427
+
1428
+ if (retryCount < maxRetries) {
1429
+ MessageFormatter.info(
1430
+ chalk.yellow(`Retrying attribute '${attribute.key}' due to error...`)
1431
+ );
1432
+
1433
+ // Wait a bit before retry
1434
+ await delay(2000);
1435
+
1436
+ return await createOrUpdateAttributeWithStatusCheck(
1437
+ db,
1438
+ dbId,
1439
+ collection,
1440
+ attribute,
1441
+ retryCount + 1,
1442
+ maxRetries
1443
+ );
1444
+ }
1445
+
1446
+ return false;
1447
+ }
1448
+ };
1449
+
1450
+ export const createOrUpdateAttribute = async (
1451
+ db: Databases | DatabaseAdapter,
1452
+ dbId: string,
1453
+ collection: Models.Collection,
1454
+ attribute: Attribute
1455
+ ): Promise<"queued" | "processed" | "error"> => {
1456
+ let action = "create";
1457
+ let foundAttribute: Attribute | undefined;
1458
+ const updateEnabled = true;
1459
+ let finalAttribute: any = attribute;
1460
+ try {
1461
+ const collectionAttr = collection.attributes.find(
1462
+ (attr: any) => attr.key === attribute.key
1463
+ ) as unknown as any;
1464
+ foundAttribute = parseAttribute(collectionAttr);
1465
+ } catch (error) {
1466
+ foundAttribute = undefined;
1467
+ }
1468
+
1469
+ // If attribute exists but type changed, delete it so we can recreate with new type
1470
+ if (
1471
+ foundAttribute &&
1472
+ foundAttribute.type !== attribute.type
1473
+ ) {
1474
+ MessageFormatter.info(
1475
+ chalk.yellow(
1476
+ `Attribute '${attribute.key}' type changed from '${foundAttribute.type}' to '${attribute.type}'. Recreating attribute.`
1477
+ )
1478
+ );
1479
+ try {
1480
+ if (isDatabaseAdapter(db)) {
1481
+ await db.deleteAttribute({
1482
+ databaseId: dbId,
1483
+ tableId: collection.$id,
1484
+ key: attribute.key
1485
+ });
1486
+ } else {
1487
+ await db.deleteAttribute(dbId, collection.$id, attribute.key);
1488
+ }
1489
+ // Remove from local collection metadata so downstream logic treats it as new
1490
+ collection.attributes = collection.attributes.filter(
1491
+ (attr: any) => attr.key !== attribute.key
1492
+ );
1493
+ foundAttribute = undefined;
1494
+ } catch (deleteError) {
1495
+ MessageFormatter.error(
1496
+ `Failed to delete attribute '${attribute.key}' before recreation: ${deleteError}`
1497
+ );
1498
+ return "error";
1499
+ }
1500
+ }
1501
+
1502
+ if (
1503
+ foundAttribute &&
1504
+ attributesSame(foundAttribute, attribute) &&
1505
+ updateEnabled
1506
+ ) {
1507
+ // No need to do anything, they are the same
1508
+ return "processed";
1509
+ } else if (
1510
+ foundAttribute &&
1511
+ !attributesSame(foundAttribute, attribute) &&
1512
+ updateEnabled
1513
+ ) {
1514
+ // MessageFormatter.info(
1515
+ // `Updating attribute with same key ${attribute.key} but different values`
1516
+ // );
1517
+
1518
+ // DEBUG: Log before object merge to detect corruption
1519
+ if ((attribute.key === 'conversationType' || attribute.key === 'messageStreakCount')) {
1520
+ console.log(`[DEBUG] MERGE - key="${attribute.key}"`, {
1521
+ found: {
1522
+ elements: (foundAttribute as any)?.elements,
1523
+ min: (foundAttribute as any)?.min,
1524
+ max: (foundAttribute as any)?.max
1525
+ },
1526
+ desired: {
1527
+ elements: (attribute as any)?.elements,
1528
+ min: (attribute as any)?.min,
1529
+ max: (attribute as any)?.max
1530
+ }
1531
+ });
1532
+ }
1533
+
1534
+ finalAttribute = {
1535
+ ...foundAttribute,
1536
+ ...attribute,
1537
+ };
1538
+
1539
+ // DEBUG: Log after object merge to detect corruption
1540
+ if ((finalAttribute.key === 'conversationType' || finalAttribute.key === 'messageStreakCount')) {
1541
+ console.log(`[DEBUG] AFTER_MERGE - key="${finalAttribute.key}"`, {
1542
+ merged: {
1543
+ elements: finalAttribute?.elements,
1544
+ min: (finalAttribute as any)?.min,
1545
+ max: (finalAttribute as any)?.max
1546
+ }
1547
+ });
1548
+ }
1549
+ action = "update";
1550
+ } else if (
1551
+ !updateEnabled &&
1552
+ foundAttribute &&
1553
+ !attributesSame(foundAttribute, attribute)
1554
+ ) {
1555
+ if (isDatabaseAdapter(db)) {
1556
+ await db.deleteAttribute({
1557
+ databaseId: dbId,
1558
+ tableId: collection.$id,
1559
+ key: attribute.key,
1560
+ });
1561
+ } else {
1562
+ await db.deleteAttribute(dbId, collection.$id, attribute.key);
1563
+ }
1564
+ MessageFormatter.info(
1565
+ `Deleted attribute: ${attribute.key} to recreate it because they diff (update disabled temporarily)`
1566
+ );
1567
+ return "processed";
1568
+ }
1569
+
1570
+ // Relationship attribute logic with adjustments
1571
+ let collectionFoundViaRelatedCollection: Models.Collection | undefined;
1572
+ let relatedCollectionId: string | undefined;
1573
+ if (
1574
+ finalAttribute.type === "relationship" &&
1575
+ finalAttribute.relatedCollection
1576
+ ) {
1577
+ // First try treating relatedCollection as an ID directly
1578
+ try {
1579
+ const byIdCollection = isDatabaseAdapter(db)
1580
+ ? (
1581
+ await db.getTable({
1582
+ databaseId: dbId,
1583
+ tableId: finalAttribute.relatedCollection,
1584
+ })
1585
+ ).data
1586
+ : await db.getCollection(dbId, finalAttribute.relatedCollection);
1587
+ collectionFoundViaRelatedCollection = byIdCollection;
1588
+ relatedCollectionId = byIdCollection.$id;
1589
+ // Cache by name for subsequent lookups
1590
+ nameToIdMapping.set(byIdCollection.name, byIdCollection.$id);
1591
+ } catch (_) {
1592
+ // Not an ID or not found — fall back to name-based resolution below
1593
+ }
1594
+
1595
+ if (
1596
+ !collectionFoundViaRelatedCollection &&
1597
+ nameToIdMapping.has(finalAttribute.relatedCollection)
1598
+ ) {
1599
+ relatedCollectionId = nameToIdMapping.get(
1600
+ finalAttribute.relatedCollection
1601
+ );
1602
+ try {
1603
+ collectionFoundViaRelatedCollection = isDatabaseAdapter(db)
1604
+ ? (
1605
+ await db.getTable({
1606
+ databaseId: dbId,
1607
+ tableId: relatedCollectionId!,
1608
+ })
1609
+ ).data
1610
+ : await db.getCollection(dbId, relatedCollectionId!);
1611
+ } catch (e) {
1612
+ // MessageFormatter.info(
1613
+ // `Collection not found: ${finalAttribute.relatedCollection} when nameToIdMapping was set`
1614
+ // );
1615
+ collectionFoundViaRelatedCollection = undefined;
1616
+ }
1617
+ } else if (!collectionFoundViaRelatedCollection) {
1618
+ const collectionsPulled = isDatabaseAdapter(db)
1619
+ ? await db.listTables({
1620
+ databaseId: dbId,
1621
+ queries: [Query.equal("name", finalAttribute.relatedCollection)],
1622
+ })
1623
+ : await db.listCollections(dbId, [
1624
+ Query.equal("name", finalAttribute.relatedCollection),
1625
+ ]);
1626
+ if (collectionsPulled.total && collectionsPulled.total > 0) {
1627
+ collectionFoundViaRelatedCollection = isDatabaseAdapter(db)
1628
+ ? (collectionsPulled as any).tables?.[0]
1629
+ : (collectionsPulled as any).collections?.[0];
1630
+ relatedCollectionId = collectionFoundViaRelatedCollection?.$id;
1631
+ if (relatedCollectionId) {
1632
+ nameToIdMapping.set(
1633
+ finalAttribute.relatedCollection,
1634
+ relatedCollectionId
1635
+ );
1636
+ }
1637
+ }
1638
+ }
1639
+ // ONLY queue relationship attributes that have actual unresolved dependencies
1640
+ if (!(relatedCollectionId && collectionFoundViaRelatedCollection)) {
1641
+ MessageFormatter.info(
1642
+ chalk.yellow(
1643
+ `⏳ Queueing relationship attribute '${finalAttribute.key}' - related collection '${finalAttribute.relatedCollection}' not found yet`
1644
+ )
1645
+ );
1646
+ enqueueOperation({
1647
+ type: "attribute",
1648
+ collectionId: collection.$id,
1649
+ collection: collection,
1650
+ attribute,
1651
+ dependencies: [finalAttribute.relatedCollection],
1652
+ });
1653
+ return "queued";
1654
+ }
1655
+ }
1656
+ finalAttribute = parseAttribute(finalAttribute);
1657
+
1658
+ // Ensure collection/table exists - create it if it doesn't
1659
+ try {
1660
+ await (isDatabaseAdapter(db)
1661
+ ? db.getTable({ databaseId: dbId, tableId: collection.$id })
1662
+ : db.getCollection(dbId, collection.$id));
1663
+ } catch (error) {
1664
+ // Collection doesn't exist - create it
1665
+ if (
1666
+ (error as any).code === 404 ||
1667
+ (error instanceof Error &&
1668
+ (error.message.includes("collection_not_found") ||
1669
+ error.message.includes(
1670
+ "Collection with the requested ID could not be found"
1671
+ )))
1672
+ ) {
1673
+ MessageFormatter.info(
1674
+ `Collection '${collection.name}' doesn't exist, creating it first...`
1675
+ );
1676
+
1677
+ try {
1678
+ if (isDatabaseAdapter(db)) {
1679
+ await db.createTable({
1680
+ databaseId: dbId,
1681
+ id: collection.$id,
1682
+ name: collection.name,
1683
+ permissions: collection.$permissions || [],
1684
+ documentSecurity: collection.documentSecurity ?? false,
1685
+ enabled: collection.enabled ?? true,
1686
+ });
1687
+ } else {
1688
+ await db.createCollection(
1689
+ dbId,
1690
+ collection.$id,
1691
+ collection.name,
1692
+ collection.$permissions || [],
1693
+ collection.documentSecurity ?? false,
1694
+ collection.enabled ?? true
1695
+ );
1696
+ }
1697
+
1698
+ MessageFormatter.success(`Created collection '${collection.name}'`);
1699
+ await delay(500); // Wait for collection to be ready
1700
+ } catch (createError) {
1701
+ MessageFormatter.error(
1702
+ `Failed to create collection '${collection.name}'`,
1703
+ createError instanceof Error
1704
+ ? createError
1705
+ : new Error(String(createError))
1706
+ );
1707
+ return "error";
1708
+ }
1709
+ } else {
1710
+ // Other error - re-throw
1711
+ throw error;
1712
+ }
1713
+ }
1714
+
1715
+ // Use adapter-based attribute creation/update
1716
+ if (action === "create") {
1717
+ await tryAwaitWithRetry(
1718
+ async () =>
1719
+ await createAttributeViaAdapter(
1720
+ db,
1721
+ dbId,
1722
+ collection.$id,
1723
+ finalAttribute
1724
+ )
1725
+ );
1726
+ } else {
1727
+ console.log(`Updating attribute '${finalAttribute.key}'...`);
1728
+ if (finalAttribute.type === "double" || finalAttribute.type === "integer") {
1729
+ console.log("finalAttribute:", finalAttribute);
1730
+ }
1731
+ await tryAwaitWithRetry(
1732
+ async () =>
1733
+ await updateAttributeViaAdapter(
1734
+ db,
1735
+ dbId,
1736
+ collection.$id,
1737
+ finalAttribute
1738
+ )
1739
+ );
1740
+ }
1741
+ return "processed";
1742
+ };
1743
+
1744
+ /**
1745
+ * Enhanced collection attribute creation with proper status monitoring
1746
+ */
1747
+ export const createUpdateCollectionAttributesWithStatusCheck = async (
1748
+ db: Databases | DatabaseAdapter,
1749
+ dbId: string,
1750
+ collection: Models.Collection,
1751
+ attributes: Attribute[]
1752
+ ): Promise<boolean> => {
1753
+ const existingAttributes: Attribute[] =
1754
+ collection.attributes.map((attr) => parseAttribute(attr as any)) || [];
1755
+
1756
+ const attributesToRemove = existingAttributes.filter(
1757
+ (attr) => !attributes.some((a) => a.key === attr.key)
1758
+ );
1759
+ const indexesToRemove = collection.indexes.filter((index) =>
1760
+ attributesToRemove.some((attr) => index.attributes.includes(attr.key))
1761
+ );
1762
+
1763
+ // Handle attribute removal first
1764
+ if (attributesToRemove.length > 0) {
1765
+ if (indexesToRemove.length > 0) {
1766
+ MessageFormatter.info(
1767
+ chalk.red(
1768
+ `Removing indexes as they rely on an attribute that is being removed: ${indexesToRemove
1769
+ .map((index) => index.key)
1770
+ .join(", ")}`
1771
+ )
1772
+ );
1773
+ for (const index of indexesToRemove) {
1774
+ await tryAwaitWithRetry(async () => {
1775
+ if (isDatabaseAdapter(db)) {
1776
+ await db.deleteIndex({
1777
+ databaseId: dbId,
1778
+ tableId: collection.$id,
1779
+ key: index.key,
1780
+ });
1781
+ } else {
1782
+ await db.deleteIndex(dbId, collection.$id, index.key);
1783
+ }
1784
+ });
1785
+ await delay(500); // Longer delay for deletions
1786
+ }
1787
+ }
1788
+ for (const attr of attributesToRemove) {
1789
+ MessageFormatter.info(
1790
+ chalk.red(
1791
+ `Removing attribute: ${attr.key} as it is no longer in the collection`
1792
+ )
1793
+ );
1794
+ await tryAwaitWithRetry(async () => {
1795
+ if (isDatabaseAdapter(db)) {
1796
+ await db.deleteAttribute({
1797
+ databaseId: dbId,
1798
+ tableId: collection.$id,
1799
+ key: attr.key,
1800
+ });
1801
+ } else {
1802
+ await db.deleteAttribute(dbId, collection.$id, attr.key);
1803
+ }
1804
+ });
1805
+ await delay(500); // Longer delay for deletions
1806
+ }
1807
+ }
1808
+
1809
+ // First, get fresh collection data and determine which attributes actually need processing
1810
+ let currentCollection = collection;
1811
+ try {
1812
+ currentCollection = isDatabaseAdapter(db)
1813
+ ? (await db.getTable({ databaseId: dbId, tableId: collection.$id })).data
1814
+ : await db.getCollection(dbId, collection.$id);
1815
+ } catch (error) {
1816
+ MessageFormatter.info(
1817
+ chalk.yellow(`Warning: Could not refresh collection data: ${error}`)
1818
+ );
1819
+ }
1820
+
1821
+ const existingAttributesMap = new Map<string, Attribute>();
1822
+ try {
1823
+ const parsedAttributes = currentCollection.attributes.map((attr) =>
1824
+ parseAttribute(attr as any)
1825
+ );
1826
+ parsedAttributes.forEach((attr) =>
1827
+ existingAttributesMap.set(attr.key, attr)
1828
+ );
1829
+ } catch (error) {
1830
+ MessageFormatter.info(
1831
+ chalk.yellow(`Warning: Could not parse existing attributes: ${error}`)
1832
+ );
1833
+ }
1834
+
1835
+ // Filter to only attributes that need processing (new, changed, or not yet processed)
1836
+ const attributesToProcess = attributes.filter((attribute) => {
1837
+ // Skip if already processed in this session
1838
+ if (isAttributeProcessed(dbId, currentCollection.$id, attribute.key)) {
1839
+ return false;
1840
+ }
1841
+
1842
+ const existing = existingAttributesMap.get(attribute.key);
1843
+ if (!existing) {
1844
+ MessageFormatter.info(`➕ ${attribute.key}`);
1845
+ return true;
1846
+ }
1847
+
1848
+ const needsUpdate = !attributesSame(existing, parseAttribute(attribute));
1849
+ if (needsUpdate) {
1850
+ MessageFormatter.info(`🔄 ${attribute.key}`);
1851
+ } else {
1852
+ MessageFormatter.info(chalk.gray(`✅ ${attribute.key}`));
1853
+ }
1854
+ return needsUpdate;
1855
+ });
1856
+
1857
+ if (attributesToProcess.length === 0) {
1858
+ return true;
1859
+ }
1860
+
1861
+ let remainingAttributes = [...attributesToProcess];
1862
+ let overallRetryCount = 0;
1863
+ const maxOverallRetries = 3;
1864
+
1865
+ while (
1866
+ remainingAttributes.length > 0 &&
1867
+ overallRetryCount < maxOverallRetries
1868
+ ) {
1869
+ const attributesToProcessThisRound = [...remainingAttributes];
1870
+ remainingAttributes = []; // Reset for next iteration
1871
+
1872
+ for (const attribute of attributesToProcessThisRound) {
1873
+ const success = await createOrUpdateAttributeWithStatusCheck(
1874
+ db,
1875
+ dbId,
1876
+ currentCollection,
1877
+ attribute
1878
+ );
1879
+
1880
+ if (success) {
1881
+ // Mark this specific attribute as processed
1882
+ markAttributeProcessed(dbId, currentCollection.$id, attribute.key);
1883
+
1884
+ // Get updated collection data for next iteration
1885
+ try {
1886
+ currentCollection = isDatabaseAdapter(db)
1887
+ ? ((
1888
+ await db.getTable({ databaseId: dbId, tableId: collection.$id })
1889
+ ).data as Models.Collection)
1890
+ : await db.getCollection({
1891
+ databaseId: dbId,
1892
+ collectionId: collection.$id,
1893
+ });
1894
+ } catch (error) {
1895
+ MessageFormatter.info(
1896
+ chalk.yellow(`Warning: Could not refresh collection data: ${error}`)
1897
+ );
1898
+ }
1899
+
1900
+ // Add delay between successful attributes
1901
+ await delay(1000);
1902
+ } else {
1903
+ MessageFormatter.info(chalk.red(`❌ ${attribute.key}`));
1904
+ remainingAttributes.push(attribute); // Add back to retry list
1905
+ }
1906
+ }
1907
+
1908
+ if (remainingAttributes.length === 0) {
1909
+ return true;
1910
+ }
1911
+
1912
+ overallRetryCount++;
1913
+
1914
+ if (overallRetryCount < maxOverallRetries) {
1915
+ MessageFormatter.info(
1916
+ chalk.yellow(
1917
+ `⏳ Retrying ${remainingAttributes.length} failed attributes...`
1918
+ )
1919
+ );
1920
+ await delay(5000);
1921
+
1922
+ // Refresh collection data before retry
1923
+ try {
1924
+ currentCollection = isDatabaseAdapter(db)
1925
+ ? ((await db.getTable({ databaseId: dbId, tableId: collection.$id }))
1926
+ .data as Models.Collection)
1927
+ : await db.getCollection(dbId, collection.$id);
1928
+ } catch (error) {
1929
+ // Silently continue if refresh fails
1930
+ }
1931
+ }
1932
+ }
1933
+
1934
+ // If we get here, some attributes still failed after all retries
1935
+ if (attributesToProcess.length > 0) {
1936
+ MessageFormatter.info(
1937
+ chalk.red(
1938
+ `\n❌ Failed to create ${
1939
+ attributesToProcess.length
1940
+ } attributes after ${maxOverallRetries} attempts: ${attributesToProcess
1941
+ .map((a) => a.key)
1942
+ .join(", ")}`
1943
+ )
1944
+ );
1945
+ MessageFormatter.info(
1946
+ chalk.red(
1947
+ `This may indicate a fundamental issue with the attribute definitions or Appwrite instance`
1948
+ )
1949
+ );
1950
+ return false;
1951
+ }
1952
+
1953
+ MessageFormatter.info(
1954
+ chalk.green(
1955
+ `\n✅ Successfully created all ${attributes.length} attributes for collection: ${collection.name}`
1956
+ )
1957
+ );
1958
+ return true;
1959
+ };
1960
+
1961
+ export const createUpdateCollectionAttributes = async (
1962
+ db: Databases | DatabaseAdapter,
1963
+ dbId: string,
1964
+ collection: Models.Collection,
1965
+ attributes: Attribute[]
1966
+ ): Promise<void> => {
1967
+ MessageFormatter.info(
1968
+ chalk.green(
1969
+ `Creating/Updating attributes for collection: ${collection.name}`
1970
+ )
1971
+ );
1972
+
1973
+ const existingAttributes: Attribute[] =
1974
+ collection.attributes.map((attr) => parseAttribute(attr as any)) || [];
1975
+
1976
+ const attributesToRemove = existingAttributes.filter(
1977
+ (attr) => !attributes.some((a) => a.key === attr.key)
1978
+ );
1979
+ const indexesToRemove = collection.indexes.filter((index) =>
1980
+ attributesToRemove.some((attr) => index.attributes.includes(attr.key))
1981
+ );
1982
+
1983
+ if (attributesToRemove.length > 0) {
1984
+ if (indexesToRemove.length > 0) {
1985
+ MessageFormatter.info(
1986
+ chalk.red(
1987
+ `Removing indexes as they rely on an attribute that is being removed: ${indexesToRemove
1988
+ .map((index) => index.key)
1989
+ .join(", ")}`
1990
+ )
1991
+ );
1992
+ for (const index of indexesToRemove) {
1993
+ await tryAwaitWithRetry(async () => {
1994
+ if (isDatabaseAdapter(db)) {
1995
+ await db.deleteIndex({
1996
+ databaseId: dbId,
1997
+ tableId: collection.$id,
1998
+ key: index.key,
1999
+ });
2000
+ } else {
2001
+ await db.deleteIndex(dbId, collection.$id, index.key);
2002
+ }
2003
+ });
2004
+ await delay(100);
2005
+ }
2006
+ }
2007
+ for (const attr of attributesToRemove) {
2008
+ MessageFormatter.info(
2009
+ chalk.red(
2010
+ `Removing attribute: ${attr.key} as it is no longer in the collection`
2011
+ )
2012
+ );
2013
+ await tryAwaitWithRetry(async () => {
2014
+ if (isDatabaseAdapter(db)) {
2015
+ await db.deleteAttribute({
2016
+ databaseId: dbId,
2017
+ tableId: collection.$id,
2018
+ key: attr.key,
2019
+ });
2020
+ } else {
2021
+ await db.deleteAttribute(dbId, collection.$id, attr.key);
2022
+ }
2023
+ });
2024
+ await delay(50);
2025
+ }
2026
+ }
2027
+
2028
+ const batchSize = 3;
2029
+ for (let i = 0; i < attributes.length; i += batchSize) {
2030
+ const batch = attributes.slice(i, i + batchSize);
2031
+ const attributePromises = batch.map((attribute) =>
2032
+ tryAwaitWithRetry(
2033
+ async () =>
2034
+ await createOrUpdateAttribute(db, dbId, collection, attribute)
2035
+ )
2036
+ );
2037
+
2038
+ const results = await Promise.allSettled(attributePromises);
2039
+ results.forEach((result) => {
2040
+ if (result.status === "rejected") {
2041
+ MessageFormatter.error(
2042
+ "An attribute promise was rejected:",
2043
+ result.reason
2044
+ );
2045
+ }
2046
+ });
2047
+
2048
+ // Add delay after each batch
2049
+ await delay(200);
2050
+ }
2051
+ MessageFormatter.info(
2052
+ `Finished creating/updating attributes for collection: ${collection.name}`
2053
+ );
2054
+ };