appwrite-utils-cli 1.9.7 → 1.11.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 (425) hide show
  1. package/CONFIG_TODO.md +1189 -1189
  2. package/README.md +1004 -1004
  3. package/SELECTION_DIALOGS.md +145 -145
  4. package/SERVICE_IMPLEMENTATION_REPORT.md +462 -462
  5. package/package.json +6 -3
  6. package/scripts/copy-templates.ts +23 -23
  7. package/src/adapters/index.ts +11 -37
  8. package/src/backups/operations/bucketBackup.ts +277 -277
  9. package/src/backups/operations/collectionBackup.ts +310 -310
  10. package/src/backups/operations/comprehensiveBackup.ts +342 -342
  11. package/src/backups/schemas/bucketManifest.ts +78 -78
  12. package/src/backups/schemas/comprehensiveManifest.ts +76 -76
  13. package/src/backups/tracking/centralizedTracking.ts +352 -352
  14. package/src/cli/commands/configCommands.ts +265 -201
  15. package/src/cli/commands/databaseCommands.ts +931 -879
  16. package/src/cli/commands/functionCommands.ts +333 -332
  17. package/src/cli/commands/importFileCommands.ts +815 -0
  18. package/src/cli/commands/schemaCommands.ts +141 -141
  19. package/src/cli/commands/storageCommands.ts +2 -3
  20. package/src/cli/commands/transferCommands.ts +454 -457
  21. package/src/collections/attributes.ts.backup +1555 -1555
  22. package/src/collections/{attributes.ts → columns.ts} +15 -10
  23. package/src/collections/indexes.ts +350 -352
  24. package/src/collections/methods.ts +714 -700
  25. package/src/collections/tableOperations.ts +29 -8
  26. package/src/collections/transferOperations.ts +376 -377
  27. package/src/collections/wipeOperations.ts +449 -346
  28. package/src/databases/methods.ts +49 -49
  29. package/src/databases/setup.ts +77 -77
  30. package/src/examples/yamlTerminologyExample.ts +346 -346
  31. package/src/functions/deployments.ts +221 -220
  32. package/src/functions/fnConfigDiscovery.ts +2 -2
  33. package/src/functions/methods.ts +284 -284
  34. package/src/functions/templates/count-docs-in-collection/README.md +53 -53
  35. package/src/functions/templates/count-docs-in-collection/src/main.ts +159 -159
  36. package/src/functions/templates/count-docs-in-collection/src/request.ts +8 -8
  37. package/src/functions/templates/hono-typescript/README.md +285 -285
  38. package/src/functions/templates/hono-typescript/src/adapters/request.ts +73 -73
  39. package/src/functions/templates/hono-typescript/src/adapters/response.ts +105 -105
  40. package/src/functions/templates/hono-typescript/src/app.ts +179 -179
  41. package/src/functions/templates/hono-typescript/src/context.ts +102 -102
  42. package/src/functions/templates/hono-typescript/src/{index.ts → main.ts} +53 -53
  43. package/src/functions/templates/hono-typescript/src/middleware/appwrite.ts +118 -118
  44. package/src/functions/templates/typescript-node/README.md +31 -31
  45. package/src/functions/templates/typescript-node/src/context.ts +102 -102
  46. package/src/functions/templates/typescript-node/src/{index.ts → main.ts} +29 -29
  47. package/src/functions/templates/uv/README.md +30 -30
  48. package/src/functions/templates/uv/pyproject.toml +29 -29
  49. package/src/functions/templates/uv/src/context.py +124 -124
  50. package/src/functions/templates/uv/src/{index.py → main.py} +45 -45
  51. package/src/init.ts +62 -62
  52. package/src/interactiveCLI.ts +1095 -1030
  53. package/src/main.ts +1517 -1670
  54. package/src/migrations/afterImportActions.ts +579 -580
  55. package/src/migrations/appwriteToX.ts +634 -630
  56. package/src/migrations/comprehensiveTransfer.ts +2149 -2149
  57. package/src/migrations/dataLoader.ts +1729 -1702
  58. package/src/migrations/importController.ts +440 -428
  59. package/src/migrations/importDataActions.ts +315 -315
  60. package/src/migrations/relationships.ts +333 -334
  61. package/src/migrations/services/DataTransformationService.ts +195 -195
  62. package/src/migrations/services/FileHandlerService.ts +310 -310
  63. package/src/migrations/services/ImportOrchestrator.ts +674 -665
  64. package/src/migrations/services/RateLimitManager.ts +362 -362
  65. package/src/migrations/services/RelationshipResolver.ts +460 -460
  66. package/src/migrations/services/UserMappingService.ts +344 -344
  67. package/src/migrations/services/ValidationService.ts +333 -333
  68. package/src/migrations/transfer.ts +987 -942
  69. package/src/migrations/yaml/YamlImportConfigLoader.ts +438 -438
  70. package/src/migrations/yaml/YamlImportIntegration.ts +438 -438
  71. package/src/migrations/yaml/generateImportSchemas.ts +1347 -1347
  72. package/src/schemas/authUser.ts +23 -23
  73. package/src/setup.ts +8 -8
  74. package/src/setupCommands.ts +5 -6
  75. package/src/setupController.ts +42 -42
  76. package/src/shared/backupMetadataSchema.ts +93 -93
  77. package/src/shared/backupTracking.ts +211 -211
  78. package/src/shared/confirmationDialogs.ts +326 -326
  79. package/src/shared/migrationHelpers.ts +232 -232
  80. package/src/shared/operationLogger.ts +20 -20
  81. package/src/shared/operationQueue.ts +326 -327
  82. package/src/shared/operationsTable.ts +338 -338
  83. package/src/shared/operationsTableSchema.ts +60 -60
  84. package/src/shared/progressManager.ts +277 -277
  85. package/src/shared/relationshipExtractor.ts +214 -214
  86. package/src/shared/selectionDialogs.ts +775 -722
  87. package/src/storage/backupCompression.ts +88 -88
  88. package/src/storage/methods.ts +695 -682
  89. package/src/storage/schemas.ts +205 -205
  90. package/src/tables/indexManager.ts +408 -408
  91. package/src/types/node-appwrite-tablesdb.d.ts +43 -43
  92. package/src/types.ts +9 -9
  93. package/src/users/methods.ts +358 -359
  94. package/src/utils/configMigration.ts +347 -347
  95. package/src/utils/index.ts +2 -2
  96. package/src/utils/loadConfigs.ts +457 -449
  97. package/src/utils/setupFiles.ts +1236 -1238
  98. package/src/utilsController.ts +1263 -1213
  99. package/tests/README.md +496 -496
  100. package/tests/adapters/AdapterFactory.test.ts +276 -276
  101. package/tests/integration/syncOperations.test.ts +462 -462
  102. package/tests/jest.config.js +24 -24
  103. package/tests/migration/configMigration.test.ts +545 -545
  104. package/tests/setup.ts +61 -61
  105. package/tests/testUtils.ts +339 -339
  106. package/tests/utils/loadConfigs.test.ts +349 -349
  107. package/tests/validation/configValidation.test.ts +411 -411
  108. package/tsconfig.json +44 -44
  109. package/.appwrite/.yaml_schemas/appwrite-config.schema.json +0 -380
  110. package/.appwrite/.yaml_schemas/collection.schema.json +0 -255
  111. package/.appwrite/collections/Categories.yaml +0 -182
  112. package/.appwrite/collections/ExampleCollection.yaml +0 -36
  113. package/.appwrite/collections/Posts.yaml +0 -227
  114. package/.appwrite/collections/Users.yaml +0 -149
  115. package/.appwrite/config.yaml +0 -109
  116. package/.appwrite/import/README.md +0 -148
  117. package/.appwrite/import/categories-import.yaml +0 -129
  118. package/.appwrite/import/posts-import.yaml +0 -208
  119. package/.appwrite/import/users-import.yaml +0 -130
  120. package/.appwrite/importData/categories.json +0 -194
  121. package/.appwrite/importData/posts.json +0 -270
  122. package/.appwrite/importData/users.json +0 -220
  123. package/.appwrite/schemas/categories.json +0 -128
  124. package/.appwrite/schemas/exampleCollection.json +0 -52
  125. package/.appwrite/schemas/posts.json +0 -173
  126. package/.appwrite/schemas/users.json +0 -125
  127. package/dist/adapters/AdapterFactory.d.ts +0 -94
  128. package/dist/adapters/AdapterFactory.js +0 -420
  129. package/dist/adapters/DatabaseAdapter.d.ts +0 -243
  130. package/dist/adapters/DatabaseAdapter.js +0 -50
  131. package/dist/adapters/LegacyAdapter.d.ts +0 -50
  132. package/dist/adapters/LegacyAdapter.js +0 -615
  133. package/dist/adapters/TablesDBAdapter.d.ts +0 -45
  134. package/dist/adapters/TablesDBAdapter.js +0 -611
  135. package/dist/adapters/index.d.ts +0 -11
  136. package/dist/adapters/index.js +0 -12
  137. package/dist/backups/operations/bucketBackup.d.ts +0 -19
  138. package/dist/backups/operations/bucketBackup.js +0 -197
  139. package/dist/backups/operations/collectionBackup.d.ts +0 -30
  140. package/dist/backups/operations/collectionBackup.js +0 -201
  141. package/dist/backups/operations/comprehensiveBackup.d.ts +0 -25
  142. package/dist/backups/operations/comprehensiveBackup.js +0 -238
  143. package/dist/backups/schemas/bucketManifest.d.ts +0 -93
  144. package/dist/backups/schemas/bucketManifest.js +0 -33
  145. package/dist/backups/schemas/comprehensiveManifest.d.ts +0 -108
  146. package/dist/backups/schemas/comprehensiveManifest.js +0 -32
  147. package/dist/backups/tracking/centralizedTracking.d.ts +0 -34
  148. package/dist/backups/tracking/centralizedTracking.js +0 -274
  149. package/dist/cli/commands/configCommands.d.ts +0 -8
  150. package/dist/cli/commands/configCommands.js +0 -166
  151. package/dist/cli/commands/databaseCommands.d.ts +0 -14
  152. package/dist/cli/commands/databaseCommands.js +0 -644
  153. package/dist/cli/commands/functionCommands.d.ts +0 -7
  154. package/dist/cli/commands/functionCommands.js +0 -330
  155. package/dist/cli/commands/schemaCommands.d.ts +0 -7
  156. package/dist/cli/commands/schemaCommands.js +0 -169
  157. package/dist/cli/commands/storageCommands.d.ts +0 -5
  158. package/dist/cli/commands/storageCommands.js +0 -143
  159. package/dist/cli/commands/transferCommands.d.ts +0 -5
  160. package/dist/cli/commands/transferCommands.js +0 -384
  161. package/dist/collections/attributes.d.ts +0 -13
  162. package/dist/collections/attributes.js +0 -1333
  163. package/dist/collections/indexes.d.ts +0 -12
  164. package/dist/collections/indexes.js +0 -217
  165. package/dist/collections/methods.d.ts +0 -19
  166. package/dist/collections/methods.js +0 -587
  167. package/dist/collections/tableOperations.d.ts +0 -86
  168. package/dist/collections/tableOperations.js +0 -447
  169. package/dist/collections/transferOperations.d.ts +0 -8
  170. package/dist/collections/transferOperations.js +0 -412
  171. package/dist/collections/wipeOperations.d.ts +0 -16
  172. package/dist/collections/wipeOperations.js +0 -233
  173. package/dist/config/ConfigManager.d.ts +0 -450
  174. package/dist/config/ConfigManager.js +0 -650
  175. package/dist/config/configMigration.d.ts +0 -87
  176. package/dist/config/configMigration.js +0 -390
  177. package/dist/config/configValidation.d.ts +0 -66
  178. package/dist/config/configValidation.js +0 -358
  179. package/dist/config/index.d.ts +0 -8
  180. package/dist/config/index.js +0 -7
  181. package/dist/config/services/ConfigDiscoveryService.d.ts +0 -122
  182. package/dist/config/services/ConfigDiscoveryService.js +0 -322
  183. package/dist/config/services/ConfigLoaderService.d.ts +0 -129
  184. package/dist/config/services/ConfigLoaderService.js +0 -535
  185. package/dist/config/services/ConfigMergeService.d.ts +0 -208
  186. package/dist/config/services/ConfigMergeService.js +0 -308
  187. package/dist/config/services/ConfigValidationService.d.ts +0 -214
  188. package/dist/config/services/ConfigValidationService.js +0 -310
  189. package/dist/config/services/SessionAuthService.d.ts +0 -225
  190. package/dist/config/services/SessionAuthService.js +0 -456
  191. package/dist/config/services/__tests__/ConfigMergeService.test.d.ts +0 -1
  192. package/dist/config/services/__tests__/ConfigMergeService.test.js +0 -271
  193. package/dist/config/services/index.d.ts +0 -13
  194. package/dist/config/services/index.js +0 -10
  195. package/dist/config/yamlConfig.d.ts +0 -722
  196. package/dist/config/yamlConfig.js +0 -702
  197. package/dist/databases/methods.d.ts +0 -6
  198. package/dist/databases/methods.js +0 -35
  199. package/dist/databases/setup.d.ts +0 -5
  200. package/dist/databases/setup.js +0 -45
  201. package/dist/examples/yamlTerminologyExample.d.ts +0 -42
  202. package/dist/examples/yamlTerminologyExample.js +0 -272
  203. package/dist/functions/deployments.d.ts +0 -4
  204. package/dist/functions/deployments.js +0 -146
  205. package/dist/functions/fnConfigDiscovery.d.ts +0 -3
  206. package/dist/functions/fnConfigDiscovery.js +0 -108
  207. package/dist/functions/methods.d.ts +0 -16
  208. package/dist/functions/methods.js +0 -174
  209. package/dist/functions/pathResolution.d.ts +0 -37
  210. package/dist/functions/pathResolution.js +0 -185
  211. package/dist/functions/templates/count-docs-in-collection/README.md +0 -54
  212. package/dist/functions/templates/count-docs-in-collection/package.json +0 -25
  213. package/dist/functions/templates/count-docs-in-collection/src/main.ts +0 -159
  214. package/dist/functions/templates/count-docs-in-collection/src/request.ts +0 -9
  215. package/dist/functions/templates/count-docs-in-collection/tsconfig.json +0 -28
  216. package/dist/functions/templates/hono-typescript/README.md +0 -286
  217. package/dist/functions/templates/hono-typescript/package.json +0 -26
  218. package/dist/functions/templates/hono-typescript/src/adapters/request.ts +0 -74
  219. package/dist/functions/templates/hono-typescript/src/adapters/response.ts +0 -106
  220. package/dist/functions/templates/hono-typescript/src/app.ts +0 -180
  221. package/dist/functions/templates/hono-typescript/src/context.ts +0 -103
  222. package/dist/functions/templates/hono-typescript/src/index.ts +0 -54
  223. package/dist/functions/templates/hono-typescript/src/middleware/appwrite.ts +0 -119
  224. package/dist/functions/templates/hono-typescript/tsconfig.json +0 -20
  225. package/dist/functions/templates/typescript-node/README.md +0 -32
  226. package/dist/functions/templates/typescript-node/package.json +0 -25
  227. package/dist/functions/templates/typescript-node/src/context.ts +0 -103
  228. package/dist/functions/templates/typescript-node/src/index.ts +0 -29
  229. package/dist/functions/templates/typescript-node/tsconfig.json +0 -28
  230. package/dist/functions/templates/uv/README.md +0 -31
  231. package/dist/functions/templates/uv/pyproject.toml +0 -30
  232. package/dist/functions/templates/uv/src/__init__.py +0 -0
  233. package/dist/functions/templates/uv/src/context.py +0 -125
  234. package/dist/functions/templates/uv/src/index.py +0 -46
  235. package/dist/init.d.ts +0 -2
  236. package/dist/init.js +0 -57
  237. package/dist/interactiveCLI.d.ts +0 -31
  238. package/dist/interactiveCLI.js +0 -898
  239. package/dist/main.d.ts +0 -2
  240. package/dist/main.js +0 -1180
  241. package/dist/migrations/afterImportActions.d.ts +0 -17
  242. package/dist/migrations/afterImportActions.js +0 -306
  243. package/dist/migrations/appwriteToX.d.ts +0 -211
  244. package/dist/migrations/appwriteToX.js +0 -491
  245. package/dist/migrations/comprehensiveTransfer.d.ts +0 -147
  246. package/dist/migrations/comprehensiveTransfer.js +0 -1317
  247. package/dist/migrations/dataLoader.d.ts +0 -753
  248. package/dist/migrations/dataLoader.js +0 -1250
  249. package/dist/migrations/importController.d.ts +0 -23
  250. package/dist/migrations/importController.js +0 -268
  251. package/dist/migrations/importDataActions.d.ts +0 -50
  252. package/dist/migrations/importDataActions.js +0 -230
  253. package/dist/migrations/relationships.d.ts +0 -29
  254. package/dist/migrations/relationships.js +0 -204
  255. package/dist/migrations/services/DataTransformationService.d.ts +0 -55
  256. package/dist/migrations/services/DataTransformationService.js +0 -158
  257. package/dist/migrations/services/FileHandlerService.d.ts +0 -75
  258. package/dist/migrations/services/FileHandlerService.js +0 -236
  259. package/dist/migrations/services/ImportOrchestrator.d.ts +0 -97
  260. package/dist/migrations/services/ImportOrchestrator.js +0 -485
  261. package/dist/migrations/services/RateLimitManager.d.ts +0 -138
  262. package/dist/migrations/services/RateLimitManager.js +0 -279
  263. package/dist/migrations/services/RelationshipResolver.d.ts +0 -120
  264. package/dist/migrations/services/RelationshipResolver.js +0 -332
  265. package/dist/migrations/services/UserMappingService.d.ts +0 -109
  266. package/dist/migrations/services/UserMappingService.js +0 -277
  267. package/dist/migrations/services/ValidationService.d.ts +0 -74
  268. package/dist/migrations/services/ValidationService.js +0 -260
  269. package/dist/migrations/transfer.d.ts +0 -26
  270. package/dist/migrations/transfer.js +0 -608
  271. package/dist/migrations/yaml/YamlImportConfigLoader.d.ts +0 -131
  272. package/dist/migrations/yaml/YamlImportConfigLoader.js +0 -383
  273. package/dist/migrations/yaml/YamlImportIntegration.d.ts +0 -93
  274. package/dist/migrations/yaml/YamlImportIntegration.js +0 -341
  275. package/dist/migrations/yaml/generateImportSchemas.d.ts +0 -30
  276. package/dist/migrations/yaml/generateImportSchemas.js +0 -1327
  277. package/dist/schemas/authUser.d.ts +0 -24
  278. package/dist/schemas/authUser.js +0 -17
  279. package/dist/setup.d.ts +0 -2
  280. package/dist/setup.js +0 -5
  281. package/dist/setupCommands.d.ts +0 -58
  282. package/dist/setupCommands.js +0 -490
  283. package/dist/setupController.d.ts +0 -9
  284. package/dist/setupController.js +0 -34
  285. package/dist/shared/attributeMapper.d.ts +0 -20
  286. package/dist/shared/attributeMapper.js +0 -203
  287. package/dist/shared/backupMetadataSchema.d.ts +0 -94
  288. package/dist/shared/backupMetadataSchema.js +0 -38
  289. package/dist/shared/backupTracking.d.ts +0 -18
  290. package/dist/shared/backupTracking.js +0 -176
  291. package/dist/shared/confirmationDialogs.d.ts +0 -75
  292. package/dist/shared/confirmationDialogs.js +0 -236
  293. package/dist/shared/errorUtils.d.ts +0 -54
  294. package/dist/shared/errorUtils.js +0 -95
  295. package/dist/shared/functionManager.d.ts +0 -48
  296. package/dist/shared/functionManager.js +0 -348
  297. package/dist/shared/jsonSchemaGenerator.d.ts +0 -50
  298. package/dist/shared/jsonSchemaGenerator.js +0 -290
  299. package/dist/shared/logging.d.ts +0 -61
  300. package/dist/shared/logging.js +0 -116
  301. package/dist/shared/messageFormatter.d.ts +0 -39
  302. package/dist/shared/messageFormatter.js +0 -162
  303. package/dist/shared/migrationHelpers.d.ts +0 -61
  304. package/dist/shared/migrationHelpers.js +0 -145
  305. package/dist/shared/operationLogger.d.ts +0 -10
  306. package/dist/shared/operationLogger.js +0 -12
  307. package/dist/shared/operationQueue.d.ts +0 -40
  308. package/dist/shared/operationQueue.js +0 -311
  309. package/dist/shared/operationsTable.d.ts +0 -26
  310. package/dist/shared/operationsTable.js +0 -286
  311. package/dist/shared/operationsTableSchema.d.ts +0 -48
  312. package/dist/shared/operationsTableSchema.js +0 -35
  313. package/dist/shared/progressManager.d.ts +0 -62
  314. package/dist/shared/progressManager.js +0 -215
  315. package/dist/shared/pydanticModelGenerator.d.ts +0 -17
  316. package/dist/shared/pydanticModelGenerator.js +0 -615
  317. package/dist/shared/relationshipExtractor.d.ts +0 -56
  318. package/dist/shared/relationshipExtractor.js +0 -138
  319. package/dist/shared/schemaGenerator.d.ts +0 -40
  320. package/dist/shared/schemaGenerator.js +0 -556
  321. package/dist/shared/selectionDialogs.d.ts +0 -214
  322. package/dist/shared/selectionDialogs.js +0 -544
  323. package/dist/storage/backupCompression.d.ts +0 -20
  324. package/dist/storage/backupCompression.js +0 -67
  325. package/dist/storage/methods.d.ts +0 -32
  326. package/dist/storage/methods.js +0 -472
  327. package/dist/storage/schemas.d.ts +0 -842
  328. package/dist/storage/schemas.js +0 -175
  329. package/dist/tables/indexManager.d.ts +0 -65
  330. package/dist/tables/indexManager.js +0 -294
  331. package/dist/types.d.ts +0 -4
  332. package/dist/types.js +0 -3
  333. package/dist/users/methods.d.ts +0 -16
  334. package/dist/users/methods.js +0 -277
  335. package/dist/utils/ClientFactory.d.ts +0 -87
  336. package/dist/utils/ClientFactory.js +0 -212
  337. package/dist/utils/configDiscovery.d.ts +0 -78
  338. package/dist/utils/configDiscovery.js +0 -472
  339. package/dist/utils/configMigration.d.ts +0 -1
  340. package/dist/utils/configMigration.js +0 -261
  341. package/dist/utils/constantsGenerator.d.ts +0 -31
  342. package/dist/utils/constantsGenerator.js +0 -321
  343. package/dist/utils/dataConverters.d.ts +0 -46
  344. package/dist/utils/dataConverters.js +0 -139
  345. package/dist/utils/directoryUtils.d.ts +0 -22
  346. package/dist/utils/directoryUtils.js +0 -59
  347. package/dist/utils/getClientFromConfig.d.ts +0 -39
  348. package/dist/utils/getClientFromConfig.js +0 -199
  349. package/dist/utils/helperFunctions.d.ts +0 -63
  350. package/dist/utils/helperFunctions.js +0 -156
  351. package/dist/utils/index.d.ts +0 -2
  352. package/dist/utils/index.js +0 -2
  353. package/dist/utils/loadConfigs.d.ts +0 -50
  354. package/dist/utils/loadConfigs.js +0 -358
  355. package/dist/utils/pathResolvers.d.ts +0 -53
  356. package/dist/utils/pathResolvers.js +0 -72
  357. package/dist/utils/projectConfig.d.ts +0 -122
  358. package/dist/utils/projectConfig.js +0 -206
  359. package/dist/utils/retryFailedPromises.d.ts +0 -2
  360. package/dist/utils/retryFailedPromises.js +0 -23
  361. package/dist/utils/sessionAuth.d.ts +0 -48
  362. package/dist/utils/sessionAuth.js +0 -164
  363. package/dist/utils/setupFiles.d.ts +0 -4
  364. package/dist/utils/setupFiles.js +0 -1192
  365. package/dist/utils/typeGuards.d.ts +0 -35
  366. package/dist/utils/typeGuards.js +0 -57
  367. package/dist/utils/validationRules.d.ts +0 -43
  368. package/dist/utils/validationRules.js +0 -42
  369. package/dist/utils/versionDetection.d.ts +0 -58
  370. package/dist/utils/versionDetection.js +0 -251
  371. package/dist/utils/yamlConverter.d.ts +0 -100
  372. package/dist/utils/yamlConverter.js +0 -428
  373. package/dist/utils/yamlLoader.d.ts +0 -70
  374. package/dist/utils/yamlLoader.js +0 -267
  375. package/dist/utilsController.d.ts +0 -107
  376. package/dist/utilsController.js +0 -873
  377. package/src/adapters/AdapterFactory.ts +0 -529
  378. package/src/adapters/DatabaseAdapter.ts +0 -319
  379. package/src/adapters/LegacyAdapter.ts +0 -844
  380. package/src/adapters/TablesDBAdapter.ts +0 -823
  381. package/src/config/ConfigManager.ts +0 -849
  382. package/src/config/README.md +0 -274
  383. package/src/config/configMigration.ts +0 -575
  384. package/src/config/configValidation.ts +0 -445
  385. package/src/config/index.ts +0 -10
  386. package/src/config/services/ConfigDiscoveryService.ts +0 -410
  387. package/src/config/services/ConfigLoaderService.ts +0 -732
  388. package/src/config/services/ConfigMergeService.ts +0 -388
  389. package/src/config/services/ConfigValidationService.ts +0 -394
  390. package/src/config/services/SessionAuthService.ts +0 -565
  391. package/src/config/services/__tests__/ConfigMergeService.test.ts +0 -351
  392. package/src/config/services/index.ts +0 -29
  393. package/src/config/yamlConfig.ts +0 -761
  394. package/src/functions/pathResolution.ts +0 -227
  395. package/src/functions/templates/count-docs-in-collection/package.json +0 -25
  396. package/src/functions/templates/count-docs-in-collection/tsconfig.json +0 -28
  397. package/src/functions/templates/hono-typescript/package.json +0 -26
  398. package/src/functions/templates/hono-typescript/tsconfig.json +0 -20
  399. package/src/functions/templates/typescript-node/package.json +0 -25
  400. package/src/functions/templates/typescript-node/tsconfig.json +0 -28
  401. package/src/shared/attributeMapper.ts +0 -229
  402. package/src/shared/errorUtils.ts +0 -110
  403. package/src/shared/functionManager.ts +0 -537
  404. package/src/shared/jsonSchemaGenerator.ts +0 -383
  405. package/src/shared/logging.ts +0 -149
  406. package/src/shared/messageFormatter.ts +0 -208
  407. package/src/shared/pydanticModelGenerator.ts +0 -618
  408. package/src/shared/schemaGenerator.ts +0 -644
  409. package/src/utils/ClientFactory.ts +0 -240
  410. package/src/utils/configDiscovery.ts +0 -557
  411. package/src/utils/constantsGenerator.ts +0 -369
  412. package/src/utils/dataConverters.ts +0 -159
  413. package/src/utils/directoryUtils.ts +0 -61
  414. package/src/utils/getClientFromConfig.ts +0 -257
  415. package/src/utils/helperFunctions.ts +0 -228
  416. package/src/utils/pathResolvers.ts +0 -81
  417. package/src/utils/projectConfig.ts +0 -340
  418. package/src/utils/retryFailedPromises.ts +0 -29
  419. package/src/utils/sessionAuth.ts +0 -230
  420. package/src/utils/typeGuards.ts +0 -65
  421. package/src/utils/validationRules.ts +0 -88
  422. package/src/utils/versionDetection.ts +0 -292
  423. package/src/utils/yamlConverter.ts +0 -542
  424. package/src/utils/yamlLoader.ts +0 -371
  425. package/tmp-sync-test/.appwrite/collections/TestCollection.yaml +0 -7
@@ -1,1250 +0,0 @@
1
- import { AttributeMappingsSchema, CollectionCreateSchema, importDefSchema, } from "appwrite-utils";
2
- import path from "path";
3
- import fs from "fs";
4
- import { convertObjectByAttributeMappings } from "../utils/dataConverters.js";
5
- import { z } from "zod";
6
- import { checkForCollection } from "../collections/methods.js";
7
- import { ID, Users } from "node-appwrite";
8
- import { logger } from "../shared/logging.js";
9
- import { findOrCreateOperation, updateOperation } from "../shared/migrationHelpers.js";
10
- import { AuthUserCreateSchema } from "../schemas/authUser.js";
11
- import { LegacyAdapter } from "../adapters/LegacyAdapter.js";
12
- import { UsersController } from "../users/methods.js";
13
- import { finalizeByAttributeMap } from "../utils/helperFunctions.js";
14
- import { isEmpty } from "es-toolkit/compat";
15
- import { MessageFormatter } from "../shared/messageFormatter.js";
16
- // Define a schema for the structure of collection import data using Zod for validation
17
- export const CollectionImportDataSchema = z.object({
18
- // Optional collection creation schema
19
- collection: CollectionCreateSchema.optional(),
20
- // Array of data objects each containing rawData, finalData, context, and an import definition
21
- data: z.array(z.object({
22
- rawData: z.any(), // The initial raw data
23
- finalData: z.any(), // The transformed data ready for import
24
- context: z.any(), // Additional context for the data transformation
25
- importDef: importDefSchema.optional(), // The import definition schema
26
- })),
27
- });
28
- // DataLoader class to handle the loading of data into collections
29
- export class DataLoader {
30
- // Private member variables to hold configuration and state
31
- appwriteFolderPath;
32
- importDataActions;
33
- database;
34
- usersController;
35
- config;
36
- // Map to hold the import data for each collection by name
37
- importMap = new Map();
38
- // Map to track old to new ID mappings for each collection, if applicable
39
- oldIdToNewIdPerCollectionMap = new Map();
40
- // Map to hold the import operation ID for each collection
41
- collectionImportOperations = new Map();
42
- // Map to hold the merged user map for relationship resolution
43
- // Will hold an array of the old user ID's that are mapped to the same new user ID
44
- // For example, if there are two users with the same email, they will both be mapped to the same new user ID
45
- // Prevents duplicate users with the other two maps below it and allows me to keep the old ID's
46
- mergedUserMap = new Map();
47
- // Maps to hold email and phone to user ID mappings for unique-ness in User Accounts
48
- emailToUserIdMap = new Map();
49
- phoneToUserIdMap = new Map();
50
- userIdSet = new Set();
51
- userExistsMap = new Map();
52
- shouldWriteFile = false;
53
- // Constructor to initialize the DataLoader with necessary configurations
54
- constructor(appwriteFolderPath, importDataActions, database, config, shouldWriteFile) {
55
- this.appwriteFolderPath = appwriteFolderPath;
56
- this.importDataActions = importDataActions;
57
- this.database = database;
58
- this.usersController = new UsersController(config, database);
59
- this.config = config;
60
- this.shouldWriteFile = shouldWriteFile || false;
61
- }
62
- // Helper method to generate a consistent key for collections
63
- getCollectionKey(name) {
64
- return name.toLowerCase().replace(" ", "");
65
- }
66
- /**
67
- * Merges two objects by updating the source object with the target object's values.
68
- * It iterates through the target object's keys and updates the source object if:
69
- * - The source object has the key.
70
- * - The target object's value for that key is not null, undefined, or an empty string.
71
- * - If the target object has an array value, it concatenates the values and removes duplicates.
72
- *
73
- * @param source - The source object to be updated.
74
- * @param target - The target object with values to update the source object.
75
- * @returns The updated source object.
76
- */
77
- mergeObjects(source, update) {
78
- // Create a new object to hold the merged result
79
- const result = { ...source };
80
- // Loop through the keys of the object we care about
81
- for (const [key, value] of Object.entries(source)) {
82
- // Check if the key exists in the target object
83
- if (!Object.hasOwn(update, key)) {
84
- // If the key doesn't exist, we can just skip it like bad cheese
85
- continue;
86
- }
87
- if (update[key] === value) {
88
- continue;
89
- }
90
- // If the value ain't here, we can just do whatever man
91
- if (value === undefined || value === null || value === "") {
92
- // If the update key is defined
93
- if (update[key] !== undefined &&
94
- update[key] !== null &&
95
- update[key] !== "") {
96
- // might as well use it eh?
97
- result[key] = update[key];
98
- }
99
- // ELSE if the value is an array, because it would then not be === to those things above
100
- }
101
- else if (Array.isArray(value)) {
102
- // Get the update value
103
- const updateValue = update[key];
104
- // If the update value is an array, concatenate and remove duplicates
105
- // and poopy data
106
- if (Array.isArray(updateValue)) {
107
- result[key] = [...new Set([...value, ...updateValue])].filter((item) => item !== null && item !== undefined && item !== "");
108
- }
109
- else {
110
- // If the update value is not an array, just use it
111
- result[key] = [...value, updateValue].filter((item) => item !== null && item !== undefined && item !== "");
112
- }
113
- }
114
- else if (typeof value === "object" && !Array.isArray(value)) {
115
- // If the value is an object, we need to merge it
116
- if (typeof update[key] === "object" && !Array.isArray(update[key])) {
117
- result[key] = this.mergeObjects(value, update[key]);
118
- }
119
- }
120
- else {
121
- // Finally, the source value is defined, and not an array, so we don't care about the update value
122
- continue;
123
- }
124
- }
125
- // Because the objects should technically always be validated FIRST, we can assume the update keys are also defined on the source object
126
- for (const [key, value] of Object.entries(update)) {
127
- if (value === undefined || value === null || value === "") {
128
- continue;
129
- }
130
- else if (!Object.hasOwn(source, key)) {
131
- result[key] = value;
132
- }
133
- else if (typeof source[key] === "object" &&
134
- typeof value === "object" &&
135
- !Array.isArray(source[key]) &&
136
- !Array.isArray(value)) {
137
- result[key] = this.mergeObjects(source[key], value);
138
- }
139
- else if (Array.isArray(source[key]) && Array.isArray(value)) {
140
- result[key] = [...new Set([...source[key], ...value])].filter((item) => item !== null && item !== undefined && item !== "");
141
- }
142
- else if (source[key] === undefined ||
143
- source[key] === null ||
144
- source[key] === "") {
145
- result[key] = value;
146
- }
147
- }
148
- return result;
149
- }
150
- // Method to load data from a file specified in the import definition
151
- loadData(importDef) {
152
- // Simply join appwriteFolderPath with the importDef.filePath
153
- const filePath = path.resolve(this.appwriteFolderPath, importDef.filePath);
154
- MessageFormatter.info(`Loading data from: ${filePath}`, { prefix: "Data" });
155
- if (!fs.existsSync(filePath)) {
156
- MessageFormatter.error(`File not found: ${filePath}`, undefined, { prefix: "Data" });
157
- return [];
158
- }
159
- // Read the file and parse the JSON data
160
- const rawData = fs.readFileSync(filePath, "utf8");
161
- const parsedData = importDef.basePath
162
- ? JSON.parse(rawData)[importDef.basePath]
163
- : JSON.parse(rawData);
164
- MessageFormatter.success(`Loaded ${parsedData?.length || 0} items from ${filePath}`, { prefix: "Data" });
165
- return parsedData;
166
- }
167
- // Helper method to check if a new ID already exists in the old-to-new ID map
168
- checkMapValuesForId(newId, collectionName) {
169
- const oldIdMap = this.oldIdToNewIdPerCollectionMap.get(collectionName);
170
- for (const [key, value] of oldIdMap?.entries() || []) {
171
- if (value === newId) {
172
- return key;
173
- }
174
- }
175
- return false;
176
- }
177
- // Method to generate a unique ID that doesn't conflict with existing IDs
178
- getTrueUniqueId(collectionName) {
179
- let newId = ID.unique();
180
- let condition = this.checkMapValuesForId(newId, collectionName) ||
181
- this.userExistsMap.has(newId) ||
182
- this.userIdSet.has(newId) ||
183
- this.importMap
184
- .get(this.getCollectionKey("users"))
185
- ?.data.some((user) => user.finalData.docId === newId || user.finalData.userId === newId);
186
- while (condition) {
187
- newId = ID.unique();
188
- condition =
189
- this.checkMapValuesForId(newId, collectionName) ||
190
- this.userExistsMap.has(newId) ||
191
- this.userIdSet.has(newId) ||
192
- this.importMap
193
- .get(this.getCollectionKey("users"))
194
- ?.data.some((user) => user.finalData.docId === newId || user.finalData.userId === newId);
195
- }
196
- return newId;
197
- }
198
- // Method to create a context object for data transformation
199
- createContext(db, collection, item, docId) {
200
- return {
201
- ...item, // Spread the item data for easy access to its properties
202
- dbId: db.$id,
203
- dbName: db.name,
204
- collId: collection.$id,
205
- collName: collection.name,
206
- docId: docId,
207
- createdDoc: {}, // Initially null, to be updated when the document is created
208
- };
209
- }
210
- /**
211
- * Transforms the given item based on the provided attribute mappings.
212
- * This method applies conversion rules to the item's attributes as defined in the attribute mappings.
213
- *
214
- * @param item - The item to be transformed.
215
- * @param attributeMappings - The mappings that define how each attribute should be transformed.
216
- * @returns The transformed item.
217
- */
218
- transformData(item, attributeMappings) {
219
- // Convert the item using the attribute mappings provided
220
- const convertedItem = convertObjectByAttributeMappings(item, attributeMappings);
221
- // Run additional converter functions on the converted item, if any
222
- return this.importDataActions.runConverterFunctions(convertedItem, attributeMappings);
223
- }
224
- async setupMaps(dbId) {
225
- // Initialize the users collection in the import map
226
- this.importMap.set(this.getCollectionKey("users"), {
227
- data: [],
228
- });
229
- for (const db of this.config.databases) {
230
- if (db.$id !== dbId) {
231
- continue;
232
- }
233
- if (!this.config.collections) {
234
- continue;
235
- }
236
- for (let index = 0; index < this.config.collections.length; index++) {
237
- const collectionConfig = this.config.collections[index];
238
- let collection = CollectionCreateSchema.parse(collectionConfig);
239
- // Check if the collection exists in the database
240
- const collectionExists = await checkForCollection(this.database, db.$id, collection);
241
- if (!collectionExists) {
242
- logger.error(`No collection found for ${collection.name}`);
243
- continue;
244
- }
245
- else if (!collection.name) {
246
- logger.error(`Collection ${collection.name} has no name`);
247
- continue;
248
- }
249
- // Update the collection ID with the existing one
250
- collectionConfig.$id = collectionExists.$id;
251
- collection.$id = collectionExists.$id;
252
- this.config.collections[index] = collectionConfig;
253
- // Find or create an import operation for the collection
254
- const adapter = new LegacyAdapter(this.database.client);
255
- const collectionImportOperation = await findOrCreateOperation(adapter, dbId, "importData", collection.$id);
256
- // Store the operation ID in the map
257
- this.collectionImportOperations.set(this.getCollectionKey(collection.name), collectionImportOperation.$id);
258
- // Initialize the collection in the import map
259
- this.importMap.set(this.getCollectionKey(collection.name), {
260
- collection: collection,
261
- data: [],
262
- });
263
- }
264
- }
265
- }
266
- async getAllUsers() {
267
- const users = new UsersController(this.config, this.database);
268
- const allUsers = await users.getAllUsers();
269
- // Iterate over the users and setup our maps ahead of time for email and phone
270
- for (const user of allUsers) {
271
- if (user.email) {
272
- this.emailToUserIdMap.set(user.email.toLowerCase(), user.$id);
273
- }
274
- if (user.phone) {
275
- this.phoneToUserIdMap.set(user.phone, user.$id);
276
- }
277
- this.userExistsMap.set(user.$id, true);
278
- this.userIdSet.add(user.$id);
279
- let importData = this.importMap.get(this.getCollectionKey("users"));
280
- if (!importData) {
281
- importData = {
282
- data: [],
283
- };
284
- }
285
- importData.data.push({
286
- finalData: {
287
- ...user,
288
- email: user.email?.toLowerCase(),
289
- userId: user.$id,
290
- docId: user.$id,
291
- },
292
- context: {
293
- ...user,
294
- email: user.email?.toLowerCase(),
295
- userId: user.$id,
296
- docId: user.$id,
297
- },
298
- rawData: user,
299
- });
300
- this.importMap.set(this.getCollectionKey("users"), importData);
301
- }
302
- return allUsers;
303
- }
304
- // Main method to start the data loading process for a given database ID
305
- async start(dbId) {
306
- MessageFormatter.divider();
307
- MessageFormatter.info(`Starting data setup for database: ${dbId}`, { prefix: "Data" });
308
- MessageFormatter.divider();
309
- await this.setupMaps(dbId);
310
- const allUsers = await this.getAllUsers();
311
- MessageFormatter.info(`Fetched ${allUsers.length} users, waiting a few seconds to let the program catch up...`, { prefix: "Data" });
312
- await new Promise((resolve) => setTimeout(resolve, 5000));
313
- // Iterate over the configured databases to find the matching one
314
- for (const db of this.config.databases) {
315
- if (db.$id !== dbId) {
316
- continue;
317
- }
318
- if (!this.config.collections) {
319
- continue;
320
- }
321
- // Iterate over the configured collections to process each
322
- for (const collectionConfig of this.config.collections) {
323
- const collection = collectionConfig;
324
- // Determine if this is the users collection
325
- let isUsersCollection = this.getCollectionKey(this.config.usersCollectionName) ===
326
- this.getCollectionKey(collection.name);
327
- const collectionDefs = collection.importDefs;
328
- if (!collectionDefs || !collectionDefs.length) {
329
- continue;
330
- }
331
- // Process create and update definitions for the collection
332
- const createDefs = collection.importDefs.filter((def) => def.type === "create" || !def.type);
333
- const updateDefs = collection.importDefs.filter((def) => def.type === "update");
334
- for (const createDef of createDefs) {
335
- if (!isUsersCollection || !createDef.createUsers) {
336
- await this.prepareCreateData(db, collection, createDef);
337
- }
338
- else {
339
- // Special handling for users collection if needed
340
- await this.prepareUserCollectionCreateData(db, collection, createDef);
341
- }
342
- }
343
- for (const updateDef of updateDefs) {
344
- if (!this.importMap.has(this.getCollectionKey(collection.name))) {
345
- logger.error(`No data found for collection ${collection.name} for updateDef but it says it's supposed to have one...`);
346
- continue;
347
- }
348
- // Prepare the update data for the collection
349
- this.prepareUpdateData(db, collection, updateDef);
350
- }
351
- }
352
- MessageFormatter.info("Running update references", { prefix: "Data" });
353
- // this.dealWithMergedUsers();
354
- this.updateOldReferencesForNew();
355
- MessageFormatter.success("Done running update references", { prefix: "Data" });
356
- }
357
- // for (const collection of this.config.collections) {
358
- // this.resolveDataItemRelationships(collection);
359
- // }
360
- MessageFormatter.divider();
361
- MessageFormatter.success(`Data setup for database: ${dbId} completed`, { prefix: "Data" });
362
- MessageFormatter.divider();
363
- if (this.shouldWriteFile) {
364
- this.writeMapsToJsonFile();
365
- }
366
- }
367
- /**
368
- * Deals with merged users by iterating through all collections in the configuration.
369
- * We have merged users if there are duplicate emails or phones in the import data.
370
- * This function will iterate through all collections that are the same name as the
371
- * users collection and pull out their primaryKeyField's. It will then loop through
372
- * each collection and find any documents that have a
373
- *
374
- * @return {void} This function does not return anything.
375
- */
376
- // dealWithMergedUsers() {
377
- // const usersCollectionKey = this.getCollectionKey(
378
- // this.config.usersCollectionName
379
- // );
380
- // const usersCollectionData = this.importMap.get(usersCollectionKey);
381
- // if (!this.config.collections) {
382
- // console.log("No collections found in configuration.");
383
- // return;
384
- // }
385
- // let needsUpdate = false;
386
- // let numUpdates = 0;
387
- // for (const collectionConfig of this.config.collections) {
388
- // const collectionKey = this.getCollectionKey(collectionConfig.name);
389
- // const collectionData = this.importMap.get(collectionKey);
390
- // const collectionImportDefs = collectionConfig.importDefs;
391
- // const collectionIdMappings = collectionImportDefs
392
- // .map((importDef) => importDef.idMappings)
393
- // .flat()
394
- // .filter((idMapping) => idMapping !== undefined && idMapping !== null);
395
- // if (!collectionData || !collectionData.data) continue;
396
- // for (const dataItem of collectionData.data) {
397
- // for (const idMapping of collectionIdMappings) {
398
- // // We know it's the users collection here
399
- // if (this.getCollectionKey(idMapping.targetCollection) === usersCollectionKey) {
400
- // const targetFieldKey = idMapping.targetFieldToMatch || idMapping.targetField;
401
- // if (targetFieldKey === )
402
- // const targetValue = dataItem.finalData[targetFieldKey];
403
- // const targetCollectionData = this.importMap.get(this.getCollectionKey(idMapping.targetCollection));
404
- // if (!targetCollectionData || !targetCollectionData.data) continue;
405
- // const foundData = targetCollectionData.data.filter(({ context }) => {
406
- // const targetValue = context[targetFieldKey];
407
- // const isMatch = `${targetValue}` === `${valueToMatch}`;
408
- // return isMatch && targetValue !== undefined && targetValue !== null;
409
- // });
410
- // }
411
- // }
412
- // }
413
- // }
414
- // }
415
- /**
416
- * Gets the value to match for a given key in the final data or context.
417
- * @param finalData - The final data object.
418
- * @param context - The context object.
419
- * @param key - The key to get the value for.
420
- * @returns The value to match for from finalData or Context
421
- */
422
- getValueFromData(finalData, context, key) {
423
- if (context[key] !== undefined &&
424
- context[key] !== null &&
425
- context[key] !== "") {
426
- return context[key];
427
- }
428
- return finalData[key];
429
- }
430
- updateOldReferencesForNew() {
431
- if (!this.config.collections) {
432
- return;
433
- }
434
- for (const collectionConfig of this.config.collections) {
435
- const collectionKey = this.getCollectionKey(collectionConfig.name);
436
- const collectionData = this.importMap.get(collectionKey);
437
- if (!collectionData || !collectionData.data)
438
- continue;
439
- MessageFormatter.processing(`Updating references for collection: ${collectionConfig.name}`, { prefix: "Data" });
440
- let needsUpdate = false;
441
- // Iterate over each data item in the current collection
442
- for (let i = 0; i < collectionData.data.length; i++) {
443
- if (collectionConfig.importDefs) {
444
- for (const importDef of collectionConfig.importDefs) {
445
- if (importDef.idMappings) {
446
- for (const idMapping of importDef.idMappings) {
447
- const targetCollectionKey = this.getCollectionKey(idMapping.targetCollection);
448
- const fieldToSetKey = idMapping.fieldToSet || idMapping.sourceField;
449
- const targetFieldKey = idMapping.targetFieldToMatch || idMapping.targetField;
450
- const sourceValue = this.getValueFromData(collectionData.data[i].finalData, collectionData.data[i].context, idMapping.sourceField);
451
- // Skip if value to match is missing or empty
452
- if (!sourceValue ||
453
- isEmpty(sourceValue) ||
454
- sourceValue === null)
455
- continue;
456
- const isFieldToSetArray = collectionConfig.attributes.find((attribute) => attribute.key === fieldToSetKey)?.array;
457
- const targetCollectionData = this.importMap.get(targetCollectionKey);
458
- if (!targetCollectionData || !targetCollectionData.data)
459
- continue;
460
- // Handle cases where sourceValue is an array
461
- const sourceValues = Array.isArray(sourceValue)
462
- ? sourceValue.map((sourceValue) => `${sourceValue}`)
463
- : [`${sourceValue}`];
464
- let newData = [];
465
- for (const valueToMatch of sourceValues) {
466
- // Find matching data in the target collection
467
- const foundData = targetCollectionData.data.filter(({ context, finalData }) => {
468
- const targetValue = this.getValueFromData(finalData, context, targetFieldKey);
469
- const isMatch = `${targetValue}` === `${valueToMatch}`;
470
- // Ensure the targetValue is defined and not null
471
- return (isMatch &&
472
- targetValue !== undefined &&
473
- targetValue !== null);
474
- });
475
- if (foundData.length) {
476
- newData.push(...foundData.map((data) => {
477
- const newValue = this.getValueFromData(data.finalData, data.context, idMapping.targetField);
478
- return newValue;
479
- }));
480
- }
481
- else {
482
- logger.info(`No data found for collection: ${targetCollectionKey} with value: ${valueToMatch} for field: ${fieldToSetKey} -- idMapping: ${JSON.stringify(idMapping, null, 2)}`);
483
- }
484
- continue;
485
- }
486
- const getCurrentDataFiltered = (currentData) => {
487
- if (Array.isArray(currentData.finalData[fieldToSetKey])) {
488
- return currentData.finalData[fieldToSetKey].filter((data) => !sourceValues.includes(`${data}`));
489
- }
490
- return currentData.finalData[fieldToSetKey];
491
- };
492
- // Get the current data to be updated
493
- const currentDataFiltered = getCurrentDataFiltered(collectionData.data[i]);
494
- if (newData.length) {
495
- needsUpdate = true;
496
- // Handle cases where current data is an array
497
- if (isFieldToSetArray) {
498
- if (!currentDataFiltered) {
499
- // Set new data if current data is undefined
500
- collectionData.data[i].finalData[fieldToSetKey] =
501
- Array.isArray(newData) ? newData : [newData];
502
- }
503
- else {
504
- if (Array.isArray(currentDataFiltered)) {
505
- // Convert current data to array and merge if new data is non-empty array
506
- collectionData.data[i].finalData[fieldToSetKey] = [
507
- ...new Set([...currentDataFiltered, ...newData].filter((value) => value !== null &&
508
- value !== undefined &&
509
- value !== "")),
510
- ];
511
- }
512
- else {
513
- // Merge arrays if new data is non-empty array and filter for uniqueness
514
- collectionData.data[i].finalData[fieldToSetKey] = [
515
- ...new Set([
516
- ...(Array.isArray(currentDataFiltered)
517
- ? currentDataFiltered
518
- : [currentDataFiltered]),
519
- ...newData,
520
- ].filter((value) => value !== null &&
521
- value !== undefined &&
522
- value !== "" &&
523
- !sourceValues.includes(`${value}`))),
524
- ];
525
- }
526
- }
527
- }
528
- else {
529
- if (!currentDataFiltered) {
530
- // Set new data if current data is undefined
531
- collectionData.data[i].finalData[fieldToSetKey] =
532
- Array.isArray(newData) ? newData[0] : newData;
533
- }
534
- else if (Array.isArray(newData) && newData.length > 0) {
535
- // Convert current data to array and merge if new data is non-empty array, then filter for uniqueness
536
- // and take the first value, because it's an array and the attribute is not an array
537
- collectionData.data[i].finalData[fieldToSetKey] = [
538
- ...new Set([currentDataFiltered, ...newData].filter((value) => value !== null &&
539
- value !== undefined &&
540
- value !== "" &&
541
- !sourceValues.includes(`${value}`))),
542
- ].slice(0, 1)[0];
543
- }
544
- else if (!Array.isArray(newData) &&
545
- newData !== undefined) {
546
- // Simply update the field if new data is not an array and defined
547
- collectionData.data[i].finalData[fieldToSetKey] = newData;
548
- }
549
- }
550
- }
551
- }
552
- }
553
- }
554
- }
555
- }
556
- // Update the import map if any changes were made
557
- if (needsUpdate) {
558
- this.importMap.set(collectionKey, collectionData);
559
- }
560
- }
561
- }
562
- writeMapsToJsonFile() {
563
- const outputDir = path.resolve(process.cwd(), "zlogs");
564
- // Ensure the logs directory exists
565
- if (!fs.existsSync(outputDir)) {
566
- fs.mkdirSync(outputDir);
567
- }
568
- // Helper function to write data to a file
569
- const writeToFile = (fileName, data) => {
570
- const outputFile = path.join(outputDir, fileName);
571
- fs.writeFile(outputFile, JSON.stringify(data, null, 2), "utf8", (err) => {
572
- if (err) {
573
- MessageFormatter.error(`Error writing data to ${fileName}`, err instanceof Error ? err : new Error(String(err)), { prefix: "Data" });
574
- return;
575
- }
576
- MessageFormatter.success(`Data successfully written to ${fileName}`, { prefix: "Data" });
577
- });
578
- };
579
- // Convert Maps to arrays of entries for serialization
580
- const oldIdToNewIdPerCollectionMap = Array.from(this.oldIdToNewIdPerCollectionMap.entries()).map(([key, value]) => {
581
- return {
582
- collection: key,
583
- data: Array.from(value.entries()),
584
- };
585
- });
586
- const mergedUserMap = Array.from(this.mergedUserMap.entries());
587
- // Write each part to a separate file
588
- writeToFile("oldIdToNewIdPerCollectionMap.json", oldIdToNewIdPerCollectionMap);
589
- writeToFile("mergedUserMap.json", mergedUserMap);
590
- // Write each collection's data to a separate file
591
- this.importMap.forEach((value, key) => {
592
- const data = {
593
- collection: key,
594
- data: value.data.map((item) => {
595
- return {
596
- finalData: item.finalData,
597
- context: item.context,
598
- };
599
- }),
600
- };
601
- writeToFile(`${key}.json`, data);
602
- });
603
- }
604
- /**
605
- * Prepares user data by checking for duplicates based on email or phone, adding to a duplicate map if found,
606
- * and then returning the transformed item without user-specific keys.
607
- *
608
- * @param item - The raw item to be processed.
609
- * @param attributeMappings - The attribute mappings for the item.
610
- * @returns The transformed item with user-specific keys removed.
611
- */
612
- prepareUserData(item, attributeMappings, primaryKeyField, newId) {
613
- if (this.userIdSet.has(newId) ||
614
- this.userExistsMap.has(newId) ||
615
- Array.from(this.emailToUserIdMap.values()).includes(newId) ||
616
- Array.from(this.phoneToUserIdMap.values()).includes(newId)) {
617
- newId = this.getTrueUniqueId(this.getCollectionKey("users"));
618
- }
619
- let transformedItem = this.transformData(item, attributeMappings);
620
- let userData = AuthUserCreateSchema.safeParse(transformedItem);
621
- if (userData.data?.email) {
622
- userData.data.email = userData.data.email.toLowerCase();
623
- }
624
- if (!userData.success || !(userData.data.email || userData.data.phone)) {
625
- logger.error(`Invalid user data: ${JSON.stringify(userData.error?.issues, undefined, 2)} or missing email/phone`);
626
- const userKeys = ["email", "phone", "name", "labels", "prefs"];
627
- userKeys.forEach((key) => {
628
- if (transformedItem.hasOwnProperty(key)) {
629
- delete transformedItem[key];
630
- }
631
- });
632
- return {
633
- transformedItem,
634
- existingId: undefined,
635
- userData: {
636
- rawData: item,
637
- finalData: transformedItem,
638
- },
639
- };
640
- }
641
- const email = userData.data.email?.toLowerCase();
642
- const phone = userData.data.phone;
643
- let existingId;
644
- // Check for duplicate email and phone
645
- if (email && this.emailToUserIdMap.has(email)) {
646
- existingId = this.emailToUserIdMap.get(email);
647
- if (phone && !this.phoneToUserIdMap.has(phone)) {
648
- this.phoneToUserIdMap.set(phone, newId);
649
- }
650
- }
651
- else if (phone && this.phoneToUserIdMap.has(phone)) {
652
- existingId = this.phoneToUserIdMap.get(phone);
653
- if (email && !this.emailToUserIdMap.has(email)) {
654
- this.emailToUserIdMap.set(email, newId);
655
- }
656
- }
657
- else {
658
- if (email)
659
- this.emailToUserIdMap.set(email, newId);
660
- if (phone)
661
- this.phoneToUserIdMap.set(phone, newId);
662
- }
663
- if (existingId) {
664
- userData.data.userId = existingId;
665
- const mergedUsers = this.mergedUserMap.get(existingId) || [];
666
- mergedUsers.push(`${item[primaryKeyField]}`);
667
- this.mergedUserMap.set(existingId, mergedUsers);
668
- const userFound = this.importMap
669
- .get(this.getCollectionKey("users"))
670
- ?.data.find((userDataExisting) => {
671
- let userIdToMatch;
672
- if (userDataExisting?.finalData?.userId) {
673
- userIdToMatch = userDataExisting?.finalData?.userId;
674
- }
675
- else if (userDataExisting?.finalData?.docId) {
676
- userIdToMatch = userDataExisting?.finalData?.docId;
677
- }
678
- else if (userDataExisting?.context?.userId) {
679
- userIdToMatch = userDataExisting.context.userId;
680
- }
681
- else if (userDataExisting?.context?.docId) {
682
- userIdToMatch = userDataExisting.context.docId;
683
- }
684
- return userIdToMatch === existingId;
685
- });
686
- if (userFound) {
687
- userFound.finalData.userId = existingId;
688
- userFound.finalData.docId = existingId;
689
- this.userIdSet.add(existingId);
690
- transformedItem = {
691
- ...transformedItem,
692
- userId: existingId,
693
- docId: existingId,
694
- };
695
- }
696
- const userKeys = ["email", "phone", "name", "labels", "prefs"];
697
- userKeys.forEach((key) => {
698
- if (transformedItem.hasOwnProperty(key)) {
699
- delete transformedItem[key];
700
- }
701
- });
702
- return {
703
- transformedItem,
704
- existingId,
705
- userData: {
706
- rawData: userFound?.rawData,
707
- finalData: userFound?.finalData,
708
- },
709
- };
710
- }
711
- else {
712
- existingId = newId;
713
- userData.data.userId = existingId;
714
- }
715
- const userKeys = ["email", "phone", "name", "labels", "prefs"];
716
- userKeys.forEach((key) => {
717
- if (transformedItem.hasOwnProperty(key)) {
718
- delete transformedItem[key];
719
- }
720
- });
721
- const usersMap = this.importMap.get(this.getCollectionKey("users"));
722
- const userDataToAdd = {
723
- rawData: item,
724
- finalData: userData.data,
725
- context: {},
726
- };
727
- this.importMap.set(this.getCollectionKey("users"), {
728
- data: [...(usersMap?.data || []), userDataToAdd],
729
- });
730
- this.userIdSet.add(existingId);
731
- return {
732
- transformedItem,
733
- existingId,
734
- userData: userDataToAdd,
735
- };
736
- }
737
- /**
738
- * Prepares the data for creating user collection documents.
739
- * This involves loading the data, transforming it according to the import definition,
740
- * and handling the creation of new unique IDs for each item.
741
- *
742
- * @param db - The database configuration.
743
- * @param collection - The collection configuration.
744
- * @param importDef - The import definition containing the attribute mappings and other relevant info.
745
- */
746
- async prepareUserCollectionCreateData(db, collection, importDef) {
747
- // Load the raw data based on the import definition
748
- const rawData = this.loadData(importDef);
749
- let operationId = this.collectionImportOperations.get(this.getCollectionKey(collection.name));
750
- // Initialize a new map for old ID to new ID mappings
751
- const oldIdToNewIdMap = new Map();
752
- // Retrieve or initialize the collection-specific old ID to new ID map
753
- const collectionOldIdToNewIdMap = this.oldIdToNewIdPerCollectionMap.get(this.getCollectionKey(collection.name)) ||
754
- this.oldIdToNewIdPerCollectionMap
755
- .set(this.getCollectionKey(collection.name), oldIdToNewIdMap)
756
- .get(this.getCollectionKey(collection.name));
757
- const adapter = new LegacyAdapter(this.database.client);
758
- if (!operationId) {
759
- const collectionImportOperation = await findOrCreateOperation(adapter, db.$id, "importData", collection.$id);
760
- // Store the operation ID in the map
761
- this.collectionImportOperations.set(this.getCollectionKey(collection.name), collectionImportOperation.$id);
762
- operationId = collectionImportOperation.$id;
763
- }
764
- if (operationId) {
765
- await updateOperation(adapter, db.$id, operationId, {
766
- status: "ready",
767
- total: rawData.length,
768
- });
769
- }
770
- // Retrieve the current user data and the current collection data from the import map
771
- const currentUserData = this.importMap.get(this.getCollectionKey("users"));
772
- const currentData = this.importMap.get(this.getCollectionKey(collection.name));
773
- // Log errors if the necessary data is not found in the import map
774
- if (!currentUserData) {
775
- logger.error(`No data found for collection ${"users"} for createDef but it says it's supposed to have one...`);
776
- return;
777
- }
778
- else if (!currentData) {
779
- logger.error(`No data found for collection ${collection.name} for createDef but it says it's supposed to have one...`);
780
- return;
781
- }
782
- // Iterate through each item in the raw data
783
- for (const item of rawData) {
784
- // Prepare user data, check for duplicates, and remove user-specific keys
785
- let { transformedItem, existingId, userData } = this.prepareUserData(item, importDef.attributeMappings, importDef.primaryKeyField, this.getTrueUniqueId(this.getCollectionKey("users")));
786
- logger.info(`In create user -- transformedItem: ${JSON.stringify(transformedItem, null, 2)}`);
787
- // Generate a new unique ID for the item or use existing ID
788
- if (!existingId && !userData.finalData?.userId) {
789
- // No existing user ID, generate a new unique ID
790
- existingId = this.getTrueUniqueId(this.getCollectionKey(collection.name));
791
- transformedItem = {
792
- ...transformedItem,
793
- userId: existingId,
794
- docId: existingId,
795
- };
796
- }
797
- else if (!existingId && userData.finalData?.userId) {
798
- // Existing user ID, use it as the new ID
799
- existingId = userData.finalData.userId;
800
- transformedItem = {
801
- ...transformedItem,
802
- userId: existingId,
803
- docId: existingId,
804
- };
805
- }
806
- // Create a context object for the item, including the new ID
807
- let context = this.createContext(db, collection, item, existingId);
808
- // Merge the transformed data into the context
809
- context = { ...context, ...transformedItem, ...userData.finalData };
810
- // If a primary key field is defined, handle the ID mapping and check for duplicates
811
- if (importDef.primaryKeyField) {
812
- const oldId = item[importDef.primaryKeyField];
813
- // Check if the oldId already exists to handle potential duplicates
814
- if (this.oldIdToNewIdPerCollectionMap
815
- .get(this.getCollectionKey(collection.name))
816
- ?.has(`${oldId}`)) {
817
- // Found a duplicate oldId, now decide how to merge or handle these duplicates
818
- for (const data of currentData.data) {
819
- if (data.finalData.docId === oldId ||
820
- data.finalData.userId === oldId ||
821
- data.context.docId === oldId ||
822
- data.context.userId === oldId) {
823
- transformedItem = this.mergeObjects(data.finalData, transformedItem);
824
- }
825
- }
826
- }
827
- else {
828
- // No duplicate found, simply map the oldId to the new itemId
829
- collectionOldIdToNewIdMap?.set(`${oldId}`, `${existingId}`);
830
- }
831
- }
832
- // Handle merging for currentUserData
833
- for (let i = 0; i < currentUserData.data.length; i++) {
834
- const currentUserDataItem = currentUserData.data[i];
835
- const samePhones = currentUserDataItem.finalData.phone &&
836
- transformedItem.phone &&
837
- currentUserDataItem.finalData.phone === transformedItem.phone;
838
- const sameEmails = currentUserDataItem.finalData.email &&
839
- transformedItem.email &&
840
- currentUserDataItem.finalData.email === transformedItem.email;
841
- if ((currentUserDataItem.finalData.docId === existingId ||
842
- currentUserDataItem.finalData.userId === existingId) &&
843
- (samePhones || sameEmails) &&
844
- currentUserDataItem.finalData &&
845
- userData.finalData) {
846
- const userDataMerged = this.mergeObjects(currentUserData.data[i].finalData, userData.finalData);
847
- currentUserData.data[i].finalData = userDataMerged;
848
- this.importMap.set(this.getCollectionKey("users"), currentUserData);
849
- }
850
- }
851
- // Update the attribute mappings with any actions that need to be performed post-import
852
- // We added the basePath to get the folder from the filePath
853
- const mappingsWithActions = this.getAttributeMappingsWithActions(importDef.attributeMappings, context, transformedItem);
854
- // Update the import definition with the new attribute mappings
855
- const newImportDef = {
856
- ...importDef,
857
- attributeMappings: mappingsWithActions,
858
- };
859
- const updatedData = this.importMap.get(this.getCollectionKey(collection.name));
860
- let foundData = false;
861
- for (let i = 0; i < updatedData.data.length; i++) {
862
- if (updatedData.data[i].finalData.docId === existingId ||
863
- updatedData.data[i].finalData.userId === existingId ||
864
- updatedData.data[i].context.docId === existingId ||
865
- updatedData.data[i].context.userId === existingId) {
866
- updatedData.data[i].finalData = this.mergeObjects(updatedData.data[i].finalData, transformedItem);
867
- updatedData.data[i].context = this.mergeObjects(updatedData.data[i].context, context);
868
- const mergedImportDef = {
869
- ...updatedData.data[i].importDef,
870
- idMappings: [
871
- ...(updatedData.data[i].importDef?.idMappings || []),
872
- ...(newImportDef.idMappings || []),
873
- ],
874
- attributeMappings: [
875
- ...(updatedData.data[i].importDef?.attributeMappings || []),
876
- ...(newImportDef.attributeMappings || []),
877
- ],
878
- };
879
- updatedData.data[i].importDef = mergedImportDef;
880
- this.importMap.set(this.getCollectionKey(collection.name), updatedData);
881
- this.oldIdToNewIdPerCollectionMap.set(this.getCollectionKey(collection.name), collectionOldIdToNewIdMap);
882
- foundData = true;
883
- }
884
- }
885
- if (!foundData) {
886
- // Add new data to the associated collection
887
- updatedData.data.push({
888
- rawData: item,
889
- context: context,
890
- importDef: newImportDef,
891
- finalData: transformedItem,
892
- });
893
- this.importMap.set(this.getCollectionKey(collection.name), updatedData);
894
- this.oldIdToNewIdPerCollectionMap.set(this.getCollectionKey(collection.name), collectionOldIdToNewIdMap);
895
- }
896
- }
897
- }
898
- /**
899
- * Prepares the data for creating documents in a collection.
900
- * This involves loading the data, transforming it, and handling ID mappings.
901
- *
902
- * @param db - The database configuration.
903
- * @param collection - The collection configuration.
904
- * @param importDef - The import definition containing the attribute mappings and other relevant info.
905
- */
906
- async prepareCreateData(db, collection, importDef) {
907
- // Load the raw data based on the import definition
908
- const rawData = this.loadData(importDef);
909
- let operationId = this.collectionImportOperations.get(this.getCollectionKey(collection.name));
910
- const adapter = new LegacyAdapter(this.database.client);
911
- if (!operationId) {
912
- const collectionImportOperation = await findOrCreateOperation(adapter, db.$id, "importData", collection.$id);
913
- // Store the operation ID in the map
914
- this.collectionImportOperations.set(this.getCollectionKey(collection.name), collectionImportOperation.$id);
915
- operationId = collectionImportOperation.$id;
916
- }
917
- if (operationId) {
918
- await updateOperation(adapter, db.$id, operationId, {
919
- status: "ready",
920
- total: rawData.length,
921
- });
922
- }
923
- // Initialize a new map for old ID to new ID mappings
924
- const oldIdToNewIdMapNew = new Map();
925
- // Retrieve or initialize the collection-specific old ID to new ID map
926
- const collectionOldIdToNewIdMap = this.oldIdToNewIdPerCollectionMap.get(this.getCollectionKey(collection.name)) ||
927
- this.oldIdToNewIdPerCollectionMap
928
- .set(this.getCollectionKey(collection.name), oldIdToNewIdMapNew)
929
- .get(this.getCollectionKey(collection.name));
930
- const isRegions = collection.name.toLowerCase() === "regions";
931
- // Iterate through each item in the raw data
932
- for (const item of rawData) {
933
- // Generate a new unique ID for the item
934
- const itemIdNew = this.getTrueUniqueId(this.getCollectionKey(collection.name));
935
- if (isRegions) {
936
- logger.info(`Creating region: ${JSON.stringify(item, null, 2)}`);
937
- }
938
- // Retrieve the current collection data from the import map
939
- const currentData = this.importMap.get(this.getCollectionKey(collection.name));
940
- // Create a context object for the item, including the new ID
941
- let context = this.createContext(db, collection, item, itemIdNew);
942
- // Transform the item data based on the attribute mappings
943
- let transformedData = this.transformData(item, importDef.attributeMappings);
944
- // If a primary key field is defined, handle the ID mapping and check for duplicates
945
- if (importDef.primaryKeyField) {
946
- const oldId = item[importDef.primaryKeyField];
947
- if (collectionOldIdToNewIdMap?.has(`${oldId}`)) {
948
- logger.error(`Collection ${collection.name} has multiple documents with the same primary key ${oldId}`);
949
- continue;
950
- }
951
- collectionOldIdToNewIdMap?.set(`${oldId}`, `${itemIdNew}`);
952
- }
953
- // Merge the transformed data into the context
954
- context = { ...context, ...transformedData };
955
- // Validate the item before proceeding
956
- const isValid = this.importDataActions.validateItem(transformedData, importDef.attributeMappings, context);
957
- if (!isValid) {
958
- continue;
959
- }
960
- // Update the attribute mappings with any actions that need to be performed post-import
961
- // We added the basePath to get the folder from the filePath
962
- const mappingsWithActions = this.getAttributeMappingsWithActions(importDef.attributeMappings, context, transformedData);
963
- // Update the import definition with the new attribute mappings
964
- const newImportDef = {
965
- ...importDef,
966
- attributeMappings: mappingsWithActions,
967
- };
968
- // If the current collection data exists, add the item with its context and final data
969
- if (currentData && currentData.data) {
970
- currentData.data.push({
971
- rawData: item,
972
- context: context,
973
- importDef: newImportDef,
974
- finalData: transformedData,
975
- });
976
- this.importMap.set(this.getCollectionKey(collection.name), currentData);
977
- this.oldIdToNewIdPerCollectionMap.set(this.getCollectionKey(collection.name), collectionOldIdToNewIdMap);
978
- }
979
- else {
980
- logger.error(`No data found for collection ${collection.name} for createDef but it says it's supposed to have one...`);
981
- continue;
982
- }
983
- }
984
- }
985
- /**
986
- * Prepares the data for updating documents within a collection.
987
- * This method loads the raw data based on the import definition, transforms it according to the attribute mappings,
988
- * finds the new ID for each item based on the primary key or update mapping, and then validates the transformed data.
989
- * If the data is valid, it updates the import definition with any post-import actions and adds the item to the current collection data.
990
- *
991
- * @param db - The database configuration.
992
- * @param collection - The collection configuration.
993
- * @param importDef - The import definition containing the attribute mappings and other relevant info.
994
- */
995
- async prepareUpdateData(db, collection, importDef) {
996
- const currentData = this.importMap.get(this.getCollectionKey(collection.name));
997
- const oldIdToNewIdMap = this.oldIdToNewIdPerCollectionMap.get(this.getCollectionKey(collection.name));
998
- if (!(currentData?.data && currentData?.data.length > 0) &&
999
- !oldIdToNewIdMap) {
1000
- logger.error(`No data found for collection ${collection.name} for updateDef but it says it's supposed to have one...`);
1001
- return;
1002
- }
1003
- const rawData = this.loadData(importDef);
1004
- const operationId = this.collectionImportOperations.get(this.getCollectionKey(collection.name));
1005
- if (!operationId) {
1006
- throw new Error(`No import operation found for collection ${collection.name}`);
1007
- }
1008
- for (const item of rawData) {
1009
- let transformedData = this.transformData(item, importDef.attributeMappings);
1010
- let newId;
1011
- let oldId;
1012
- let itemDataToUpdate;
1013
- // Try to find itemDataToUpdate using updateMapping
1014
- if (importDef.updateMapping) {
1015
- oldId =
1016
- item[importDef.updateMapping.originalIdField] ||
1017
- transformedData[importDef.updateMapping.originalIdField];
1018
- if (oldId) {
1019
- itemDataToUpdate = currentData?.data.find(({ context, finalData }) => {
1020
- const targetField = importDef.updateMapping.targetField ??
1021
- importDef.updateMapping.originalIdField;
1022
- return (`${context[targetField]}` === `${oldId}` ||
1023
- `${finalData[targetField]}` === `${oldId}`);
1024
- });
1025
- if (itemDataToUpdate) {
1026
- newId = itemDataToUpdate.context.docId;
1027
- }
1028
- }
1029
- }
1030
- // If updateMapping is not defined or did not find the item, use primaryKeyField
1031
- if (!itemDataToUpdate && importDef.primaryKeyField) {
1032
- oldId =
1033
- item[importDef.primaryKeyField] ||
1034
- transformedData[importDef.primaryKeyField];
1035
- if (oldId && oldId.length > 0) {
1036
- newId = oldIdToNewIdMap?.get(`${oldId}`);
1037
- if (!newId &&
1038
- this.getCollectionKey(this.config.usersCollectionName) ===
1039
- this.getCollectionKey(collection.name)) {
1040
- for (const [key, value] of this.mergedUserMap.entries()) {
1041
- if (value.includes(`${oldId}`)) {
1042
- newId = key;
1043
- break;
1044
- }
1045
- }
1046
- }
1047
- }
1048
- if (oldId && !itemDataToUpdate) {
1049
- itemDataToUpdate = currentData?.data.find((data) => `${data.context[importDef.primaryKeyField]}` === `${oldId}`);
1050
- }
1051
- }
1052
- if (!oldId) {
1053
- logger.error(`No old ID found (to update another document with) in prepareUpdateData for ${collection.name}, ${JSON.stringify(item, null, 2)}`);
1054
- continue;
1055
- }
1056
- if (!newId && !itemDataToUpdate) {
1057
- logger.error(`No new id && no data found for collection ${collection.name} for updateDef ${JSON.stringify(item, null, 2)} but it says it's supposed to have one...`);
1058
- continue;
1059
- }
1060
- else if (itemDataToUpdate) {
1061
- newId =
1062
- itemDataToUpdate.finalData.docId || itemDataToUpdate.context.docId;
1063
- if (!newId) {
1064
- logger.error(`No new id found for collection ${collection.name} for updateDef ${JSON.stringify(item, null, 2)} but has itemDataToUpdate ${JSON.stringify(itemDataToUpdate, null, 2)} but it says it's supposed to have one...`);
1065
- continue;
1066
- }
1067
- }
1068
- if (!itemDataToUpdate || !newId) {
1069
- logger.error(`No data or ID (docId) found for collection ${collection.name} for updateDef ${JSON.stringify(item, null, 2)} but it says it's supposed to have one...`);
1070
- continue;
1071
- }
1072
- transformedData = this.mergeObjects(itemDataToUpdate.finalData, transformedData);
1073
- // Create a context object for the item, including the new ID and transformed data
1074
- let context = itemDataToUpdate.context;
1075
- context = this.mergeObjects(context, transformedData);
1076
- // Validate the item before proceeding
1077
- const isValid = this.importDataActions.validateItem(item, importDef.attributeMappings, context);
1078
- if (!isValid) {
1079
- logger.info(`Skipping item: ${JSON.stringify(item, null, 2)} because it's invalid`);
1080
- continue;
1081
- }
1082
- // Update the attribute mappings with any actions that need to be performed post-import
1083
- // We added the basePath to get the folder from the filePath
1084
- const mappingsWithActions = this.getAttributeMappingsWithActions(importDef.attributeMappings, context, transformedData);
1085
- // Update the import definition with the new attribute mappings
1086
- const newImportDef = {
1087
- ...importDef,
1088
- attributeMappings: mappingsWithActions,
1089
- };
1090
- if (itemDataToUpdate) {
1091
- itemDataToUpdate.finalData = this.mergeObjects(itemDataToUpdate.finalData, transformedData);
1092
- itemDataToUpdate.context = context;
1093
- // Fix: Ensure we properly merge the attribute mappings and their actions
1094
- const mergedAttributeMappings = newImportDef.attributeMappings.map((newMapping) => {
1095
- const existingMapping = itemDataToUpdate.importDef?.attributeMappings.find((m) => m.targetKey === newMapping.targetKey);
1096
- return {
1097
- ...newMapping,
1098
- postImportActions: [
1099
- ...(existingMapping?.postImportActions || []),
1100
- ...(newMapping.postImportActions || []),
1101
- ],
1102
- };
1103
- });
1104
- itemDataToUpdate.importDef = {
1105
- ...newImportDef,
1106
- attributeMappings: mergedAttributeMappings,
1107
- };
1108
- // Debug logging
1109
- if (mergedAttributeMappings.some((m) => m.postImportActions?.length > 0)) {
1110
- logger.info(`Post-import actions for ${collection.name}: ${JSON.stringify(mergedAttributeMappings
1111
- .filter((m) => m.postImportActions?.length > 0)
1112
- .map((m) => ({
1113
- targetKey: m.targetKey,
1114
- actions: m.postImportActions,
1115
- })), null, 2)}`);
1116
- }
1117
- }
1118
- else {
1119
- currentData.data.push({
1120
- rawData: item,
1121
- context: context,
1122
- importDef: newImportDef,
1123
- finalData: transformedData,
1124
- });
1125
- }
1126
- // Since we're modifying currentData in place, we ensure no duplicates are added
1127
- this.importMap.set(this.getCollectionKey(collection.name), currentData);
1128
- }
1129
- }
1130
- updateReferencesBasedOnAttributeMappings() {
1131
- if (!this.config.collections) {
1132
- return;
1133
- }
1134
- this.config.collections.forEach((collectionConfig) => {
1135
- const collectionName = collectionConfig.name;
1136
- const collectionData = this.importMap.get(this.getCollectionKey(collectionName));
1137
- if (!collectionData) {
1138
- logger.error(`No data found for collection ${collectionName}`);
1139
- return;
1140
- }
1141
- collectionData.data.forEach((dataItem) => {
1142
- collectionConfig.importDefs.forEach((importDef) => {
1143
- if (!importDef.idMappings)
1144
- return; // Skip collections without idMappings
1145
- importDef.idMappings.forEach((mapping) => {
1146
- if (mapping && mapping.targetField) {
1147
- const idsToUpdate = Array.isArray(dataItem[mapping.targetField])
1148
- ? dataItem[mapping.targetField]
1149
- : [dataItem[mapping.targetField]];
1150
- const updatedIds = idsToUpdate.map((id) => this.getMergedId(id, mapping.targetCollection));
1151
- // Update the dataItem with the new IDs
1152
- dataItem[mapping.targetField] =
1153
- Array.isArray(dataItem[mapping.targetField])
1154
- ? updatedIds
1155
- : updatedIds[0];
1156
- }
1157
- });
1158
- });
1159
- });
1160
- });
1161
- }
1162
- getMergedId(oldId, relatedCollectionName) {
1163
- // Retrieve the old to new ID map for the related collection
1164
- const oldToNewIdMap = this.oldIdToNewIdPerCollectionMap.get(this.getCollectionKey(relatedCollectionName));
1165
- // If there's a mapping for the old ID, return the new ID
1166
- if (oldToNewIdMap && oldToNewIdMap.has(`${oldId}`)) {
1167
- return oldToNewIdMap.get(`${oldId}`); // The non-null assertion (!) is used because we checked if the map has the key
1168
- }
1169
- // If no mapping is found, return the old ID as a fallback
1170
- return oldId;
1171
- }
1172
- /**
1173
- * Generates attribute mappings with post-import actions based on the provided attribute mappings.
1174
- * This method checks each mapping for a fileData attribute and adds a post-import action to create a file
1175
- * and update the field with the file's ID if necessary.
1176
- *
1177
- * @param attributeMappings - The attribute mappings from the import definition.
1178
- * @param context - The context object containing information about the database, collection, and document.
1179
- * @param item - The item being imported, used for resolving template paths in fileData mappings.
1180
- * @returns The attribute mappings updated with any necessary post-import actions.
1181
- */
1182
- getAttributeMappingsWithActions(attributeMappings, context, item) {
1183
- // Iterate over each attribute mapping to check for fileData attributes
1184
- return attributeMappings.map((mapping) => {
1185
- if (mapping.fileData) {
1186
- // Resolve the file path using the provided template, context, and item
1187
- let mappingFilePath = this.importDataActions.resolveTemplate(mapping.fileData.path, context, item);
1188
- // Ensure the file path is absolute if it doesn't start with "http"
1189
- if (!mappingFilePath.toLowerCase().startsWith("http")) {
1190
- // First try the direct path
1191
- let fullPath = path.resolve(this.appwriteFolderPath, mappingFilePath);
1192
- // If file doesn't exist, search in subdirectories
1193
- if (!fs.existsSync(fullPath)) {
1194
- const findFileInDir = (dir) => {
1195
- const files = fs.readdirSync(dir);
1196
- for (const file of files) {
1197
- const filePath = path.join(dir, file);
1198
- const stat = fs.statSync(filePath);
1199
- if (stat.isDirectory()) {
1200
- // Recursively search subdirectories
1201
- const found = findFileInDir(filePath);
1202
- if (found)
1203
- return found;
1204
- }
1205
- else if (file === path.basename(mappingFilePath)) {
1206
- return filePath;
1207
- }
1208
- }
1209
- return null;
1210
- };
1211
- const foundPath = findFileInDir(this.appwriteFolderPath);
1212
- if (foundPath) {
1213
- mappingFilePath = foundPath;
1214
- }
1215
- else {
1216
- logger.warn(`File not found in any subdirectory: ${mappingFilePath}`);
1217
- // Keep the original resolved path as fallback
1218
- mappingFilePath = fullPath;
1219
- }
1220
- }
1221
- else {
1222
- mappingFilePath = fullPath;
1223
- }
1224
- }
1225
- // Define the after-import action to create a file and update the field
1226
- const afterImportAction = {
1227
- action: "createFileAndUpdateField",
1228
- params: [
1229
- "{dbId}",
1230
- "{collId}",
1231
- "{docId}",
1232
- mapping.targetKey,
1233
- `${this.config.documentBucketId}_${context.dbName
1234
- .toLowerCase()
1235
- .replace(" ", "")}`, // Assuming 'images' is your bucket ID
1236
- mappingFilePath,
1237
- mapping.fileData.name,
1238
- ],
1239
- };
1240
- // Add the after-import action to the mapping's postImportActions array
1241
- const postImportActions = mapping.postImportActions
1242
- ? [...mapping.postImportActions, afterImportAction]
1243
- : [afterImportAction];
1244
- return { ...mapping, postImportActions };
1245
- }
1246
- // Return the mapping unchanged if no fileData attribute is found
1247
- return mapping;
1248
- });
1249
- }
1250
- }