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,1213 +1,1263 @@
1
- import {
2
- Client,
3
- Databases,
4
- Query,
5
- Storage,
6
- Users,
7
- type Models,
8
- } from "node-appwrite";
9
- import {
10
- type AppwriteConfig,
11
- type AppwriteFunction,
12
- type Specification,
13
- } from "appwrite-utils";
14
- import {
15
- findAppwriteConfig,
16
- findFunctionsDir,
17
- } from "./utils/loadConfigs.js";
18
- import { normalizeFunctionName, validateFunctionDirectory } from './functions/pathResolution.js';
19
- import { UsersController } from "./users/methods.js";
20
- import { AppwriteToX } from "./migrations/appwriteToX.js";
21
- import { ImportController } from "./migrations/importController.js";
22
- import { ImportDataActions } from "./migrations/importDataActions.js";
23
- import {
24
- ensureDatabasesExist,
25
- wipeOtherDatabases,
26
- ensureCollectionsExist,
27
- } from "./databases/setup.js";
28
- import {
29
- createOrUpdateCollections,
30
- createOrUpdateCollectionsViaAdapter,
31
- wipeDatabase,
32
- generateSchemas,
33
- fetchAllCollections,
34
- wipeCollection,
35
- } from "./collections/methods.js";
36
- import { wipeAllTables, wipeTableRows } from "./collections/methods.js";
37
- import {
38
- backupDatabase,
39
- ensureDatabaseConfigBucketsExist,
40
- wipeDocumentStorage,
41
- } from "./storage/methods.js";
42
- import path from "path";
43
- import {
44
- type AfterImportActions,
45
- type ConverterFunctions,
46
- converterFunctions,
47
- validationRules,
48
- type ValidationRules,
49
- } from "appwrite-utils";
50
- import { afterImportActions } from "./migrations/afterImportActions.js";
51
- import {
52
- transferDatabaseLocalToLocal,
53
- transferDatabaseLocalToRemote,
54
- transferStorageLocalToLocal,
55
- transferStorageLocalToRemote,
56
- transferUsersLocalToRemote,
57
- type TransferOptions,
58
- } from "./migrations/transfer.js";
59
- import { getClient, getClientWithAuth } from "./utils/getClientFromConfig.js";
60
- import { getAdapterFromConfig } from "./utils/getClientFromConfig.js";
61
- import type { DatabaseAdapter } from './adapters/DatabaseAdapter.js';
62
- import { hasSessionAuth, findSessionByEndpointAndProject, isValidSessionCookie, type SessionAuthInfo } from "./utils/sessionAuth.js";
63
- import { fetchAllDatabases } from "./databases/methods.js";
64
- import {
65
- listFunctions,
66
- updateFunctionSpecifications,
67
- } from "./functions/methods.js";
68
- import chalk from "chalk";
69
- import { deployLocalFunction } from "./functions/deployments.js";
70
- import fs from "node:fs";
71
- import { configureLogging, updateLogger, logger } from "./shared/logging.js";
72
- import { MessageFormatter, Messages } from "./shared/messageFormatter.js";
73
- import { SchemaGenerator } from "./shared/schemaGenerator.js";
74
- import { findYamlConfig } from "./config/yamlConfig.js";
75
- import { createImportSchemas } from "./migrations/yaml/generateImportSchemas.js";
76
- import {
77
- validateCollectionsTablesConfig,
78
- reportValidationResults,
79
- validateWithStrictMode,
80
- type ValidationResult
81
- } from "./config/configValidation.js";
82
- import { ConfigManager } from "./config/ConfigManager.js";
83
- import { ClientFactory } from "./utils/ClientFactory.js";
84
- import type { DatabaseSelection, BucketSelection } from "./shared/selectionDialogs.js";
85
- import { clearProcessingState, processQueue } from "./shared/operationQueue.js";
86
-
87
- export interface SetupOptions {
88
- databases?: Models.Database[];
89
- collections?: string[];
90
- doBackup?: boolean;
91
- wipeDatabase?: boolean;
92
- wipeCollections?: boolean;
93
- wipeDocumentStorage?: boolean;
94
- wipeUsers?: boolean;
95
- transferUsers?: boolean;
96
- generateSchemas?: boolean;
97
- importData?: boolean;
98
- checkDuplicates?: boolean;
99
- shouldWriteFile?: boolean;
100
- }
101
-
102
- export class UtilsController {
103
- // ──────────────────────────────────────────────────
104
- // SINGLETON PATTERN
105
- // ──────────────────────────────────────────────────
106
- private static instance: UtilsController | null = null;
107
- private isInitialized: boolean = false;
108
-
109
- /**
110
- * Get the UtilsController singleton instance
111
- */
112
- public static getInstance(
113
- currentUserDir: string,
114
- directConfig?: {
115
- appwriteEndpoint?: string;
116
- appwriteProject?: string;
117
- appwriteKey?: string;
118
- }
119
- ): UtilsController {
120
- // Clear instance if currentUserDir has changed
121
- if (UtilsController.instance &&
122
- UtilsController.instance.currentUserDir !== currentUserDir) {
123
- logger.debug(`Clearing singleton: currentUserDir changed from ${UtilsController.instance.currentUserDir} to ${currentUserDir}`, { prefix: "UtilsController" });
124
- UtilsController.clearInstance();
125
- }
126
-
127
- // Clear instance if directConfig endpoint or project has changed
128
- if (UtilsController.instance && directConfig) {
129
- const existingConfig = UtilsController.instance.config;
130
- if (existingConfig) {
131
- const endpointChanged = directConfig.appwriteEndpoint &&
132
- existingConfig.appwriteEndpoint !== directConfig.appwriteEndpoint;
133
- const projectChanged = directConfig.appwriteProject &&
134
- existingConfig.appwriteProject !== directConfig.appwriteProject;
135
-
136
- if (endpointChanged || projectChanged) {
137
- logger.debug("Clearing singleton: endpoint or project changed", { prefix: "UtilsController" });
138
- UtilsController.clearInstance();
139
- }
140
- }
141
- }
142
-
143
- if (!UtilsController.instance) {
144
- UtilsController.instance = new UtilsController(currentUserDir, directConfig);
145
- }
146
-
147
- return UtilsController.instance;
148
- }
149
-
150
- /**
151
- * Clear the singleton instance (useful for testing)
152
- */
153
- public static clearInstance(): void {
154
- UtilsController.instance = null;
155
- }
156
-
157
- // ──────────────────────────────────────────────────
158
- // INSTANCE FIELDS
159
- // ──────────────────────────────────────────────────
160
- private appwriteFolderPath?: string;
161
- private appwriteConfigPath?: string;
162
- private currentUserDir: string;
163
- public config?: AppwriteConfig;
164
- public appwriteServer?: Client;
165
- public database?: Databases;
166
- public storage?: Storage;
167
- public adapter?: DatabaseAdapter;
168
- public converterDefinitions: ConverterFunctions = converterFunctions;
169
- public validityRuleDefinitions: ValidationRules = validationRules;
170
- public afterImportActionsDefinitions: AfterImportActions = afterImportActions;
171
-
172
- constructor(
173
- currentUserDir: string,
174
- directConfig?: {
175
- appwriteEndpoint?: string;
176
- appwriteProject?: string;
177
- appwriteKey?: string;
178
- }
179
- ) {
180
- this.currentUserDir = currentUserDir;
181
- const basePath = currentUserDir;
182
-
183
- if (directConfig) {
184
- let hasErrors = false;
185
- if (!directConfig.appwriteEndpoint) {
186
- MessageFormatter.error("Appwrite endpoint is required", undefined, { prefix: "Config" });
187
- hasErrors = true;
188
- }
189
- if (!directConfig.appwriteProject) {
190
- MessageFormatter.error("Appwrite project is required", undefined, { prefix: "Config" });
191
- hasErrors = true;
192
- }
193
- // Check authentication: either API key or session auth is required
194
- const hasValidSession = directConfig.appwriteEndpoint && directConfig.appwriteProject &&
195
- hasSessionAuth(directConfig.appwriteEndpoint, directConfig.appwriteProject);
196
-
197
- if (!directConfig.appwriteKey && !hasValidSession) {
198
- MessageFormatter.error(
199
- "Authentication required: provide an API key or login with 'appwrite login'",
200
- undefined,
201
- { prefix: "Config" }
202
- );
203
- hasErrors = true;
204
- } else if (!directConfig.appwriteKey && hasValidSession) {
205
- MessageFormatter.info("Using session authentication (no API key required)", { prefix: "Auth" });
206
- } else if (directConfig.appwriteKey && hasValidSession) {
207
- MessageFormatter.info("API key provided, session authentication also available", { prefix: "Auth" });
208
- }
209
- if (!hasErrors) {
210
- // Only set config if we have all required fields
211
- this.appwriteFolderPath = basePath;
212
- this.config = {
213
- appwriteEndpoint: directConfig.appwriteEndpoint!,
214
- appwriteProject: directConfig.appwriteProject!,
215
- appwriteKey: directConfig.appwriteKey || "",
216
- appwriteClient: null,
217
- apiMode: "auto", // Default to auto-detect for dual API support
218
- authMethod: "auto", // Default to auto-detect authentication method
219
- enableBackups: false,
220
- backupInterval: 0,
221
- backupRetention: 0,
222
- enableBackupCleanup: false,
223
- enableMockData: false,
224
- documentBucketId: "",
225
- usersCollectionName: "",
226
- databases: [],
227
- buckets: [],
228
- functions: [],
229
- logging: {
230
- enabled: false,
231
- level: "info",
232
- console: false,
233
- },
234
- };
235
- }
236
- } else {
237
- // Try to find config file
238
- const appwriteConfigFound = findAppwriteConfig(basePath);
239
- if (!appwriteConfigFound) {
240
- MessageFormatter.warning(
241
- "No appwriteConfig.ts found and no direct configuration provided",
242
- { prefix: "Config" }
243
- );
244
- return;
245
- }
246
- this.appwriteConfigPath = appwriteConfigFound;
247
- this.appwriteFolderPath = appwriteConfigFound; // For YAML configs, findAppwriteConfig already returns the correct directory
248
- }
249
- }
250
-
251
- async init(options: { validate?: boolean; strictMode?: boolean; useSession?: boolean; sessionCookie?: string; preferJson?: boolean } = {}) {
252
- const { validate = false, strictMode = false, preferJson = false } = options;
253
- const configManager = ConfigManager.getInstance();
254
-
255
- // Load config if not already loaded
256
- if (!configManager.hasConfig()) {
257
- await configManager.loadConfig({
258
- configDir: this.currentUserDir,
259
- validate,
260
- strictMode,
261
- preferJson,
262
- });
263
- }
264
-
265
- const config = configManager.getConfig();
266
-
267
- // Configure logging based on config
268
- if (config.logging) {
269
- configureLogging(config.logging);
270
- updateLogger();
271
- }
272
-
273
- // Create client and adapter (session already in config from ConfigManager)
274
- const { client, adapter } = await ClientFactory.createFromConfig(config);
275
-
276
- this.appwriteServer = client;
277
- this.adapter = adapter;
278
- this.config = config;
279
-
280
- // Update config.apiMode from adapter if it's auto or not set
281
- if (adapter && (!config.apiMode || config.apiMode === 'auto')) {
282
- this.config.apiMode = adapter.getApiMode();
283
- logger.debug(`Updated config.apiMode from adapter during init: ${this.config.apiMode}`, { prefix: "UtilsController" });
284
- }
285
-
286
- this.database = new Databases(this.appwriteServer);
287
- this.storage = new Storage(this.appwriteServer);
288
- this.config.appwriteClient = this.appwriteServer;
289
-
290
- // Log only on FIRST initialization to avoid spam
291
- if (!this.isInitialized) {
292
- const apiMode = adapter.getApiMode();
293
- const configApiMode = this.config.apiMode;
294
- MessageFormatter.info(`Database adapter initialized (apiMode: ${apiMode}, config.apiMode: ${configApiMode})`, { prefix: "Adapter" });
295
- this.isInitialized = true;
296
- } else {
297
- logger.debug("Adapter reused from cache", { prefix: "UtilsController" });
298
- }
299
- }
300
-
301
- async reloadConfig() {
302
- const configManager = ConfigManager.getInstance();
303
-
304
- // Session preservation is automatic in ConfigManager
305
- const config = await configManager.reloadConfig();
306
-
307
- // Configure logging based on updated config
308
- if (config.logging) {
309
- configureLogging(config.logging);
310
- updateLogger();
311
- }
312
-
313
- // Recreate client and adapter
314
- const { client, adapter } = await ClientFactory.createFromConfig(config);
315
-
316
- this.appwriteServer = client;
317
- this.adapter = adapter;
318
- this.config = config;
319
- this.database = new Databases(this.appwriteServer);
320
- this.storage = new Storage(this.appwriteServer);
321
- this.config.appwriteClient = this.appwriteServer;
322
-
323
- logger.debug("Config reloaded, adapter refreshed", { prefix: "UtilsController" });
324
- }
325
-
326
-
327
- async ensureDatabaseConfigBucketsExist(databases: Models.Database[] = []) {
328
- await this.init();
329
- if (!this.storage) {
330
- MessageFormatter.error("Storage not initialized", undefined, { prefix: "Controller" });
331
- return;
332
- }
333
- if (!this.config) {
334
- MessageFormatter.error("Config not initialized", undefined, { prefix: "Controller" });
335
- return;
336
- }
337
- await ensureDatabaseConfigBucketsExist(
338
- this.storage,
339
- this.config,
340
- databases
341
- );
342
- }
343
-
344
- async ensureDatabasesExist(databases?: Models.Database[]) {
345
- await this.init();
346
- if (!this.config) {
347
- MessageFormatter.error("Config not initialized", undefined, { prefix: "Controller" });
348
- return;
349
- }
350
- await this.ensureDatabaseConfigBucketsExist(databases);
351
- await ensureDatabasesExist(this.config, databases);
352
- }
353
-
354
- async ensureCollectionsExist(
355
- database: Models.Database,
356
- collections?: Models.Collection[]
357
- ) {
358
- await this.init();
359
- if (!this.config) {
360
- MessageFormatter.error("Config not initialized", undefined, { prefix: "Controller" });
361
- return;
362
- }
363
- await ensureCollectionsExist(this.config, database, collections);
364
- }
365
-
366
- async getDatabasesByIds(ids: string[]) {
367
- await this.init();
368
- if (!this.database) {
369
- MessageFormatter.error("Database not initialized", undefined, { prefix: "Controller" });
370
- return;
371
- }
372
- if (ids.length === 0) return [];
373
- const dbs = await this.database.list([
374
- Query.limit(500),
375
- Query.equal("$id", ids),
376
- ]);
377
- return dbs.databases;
378
- }
379
-
380
- async fetchAllBuckets(): Promise<{ buckets: Models.Bucket[] }> {
381
- await this.init();
382
- if (!this.storage) {
383
- MessageFormatter.warning("Storage not initialized - buckets will be empty", { prefix: "Controller" });
384
- return { buckets: [] };
385
- }
386
-
387
- try {
388
- const result = await this.storage.listBuckets([
389
- Query.limit(1000) // Increase limit to get all buckets
390
- ]);
391
-
392
- MessageFormatter.success(`Found ${result.buckets.length} buckets`, { prefix: "Controller" });
393
- return result;
394
- } catch (error: any) {
395
- MessageFormatter.error(`Failed to fetch buckets: ${error.message || error}`, error instanceof Error ? error : undefined, { prefix: "Controller" });
396
- return { buckets: [] };
397
- }
398
- }
399
-
400
- async wipeOtherDatabases(databasesToKeep: Models.Database[]) {
401
- await this.init();
402
- if (!this.database) {
403
- MessageFormatter.error("Database not initialized", undefined, { prefix: "Controller" });
404
- return;
405
- }
406
- await wipeOtherDatabases(this.database, databasesToKeep);
407
- }
408
-
409
- async wipeUsers() {
410
- await this.init();
411
- if (!this.config || !this.database) {
412
- MessageFormatter.error("Config or database not initialized", undefined, { prefix: "Controller" });
413
- return;
414
- }
415
- const usersController = new UsersController(this.config, this.database);
416
- await usersController.wipeUsers();
417
- }
418
-
419
- async backupDatabase(database: Models.Database, format: 'json' | 'zip' = 'json') {
420
- await this.init();
421
- if (!this.database || !this.storage || !this.config) {
422
- MessageFormatter.error("Database, storage, or config not initialized", undefined, { prefix: "Controller" });
423
- return;
424
- }
425
- await backupDatabase(
426
- this.config,
427
- this.database,
428
- database.$id,
429
- this.storage,
430
- format
431
- );
432
- }
433
-
434
- async listAllFunctions() {
435
- await this.init();
436
- if (!this.appwriteServer) {
437
- MessageFormatter.error("Appwrite server not initialized", undefined, { prefix: "Controller" });
438
- return [];
439
- }
440
- const { functions } = await listFunctions(this.appwriteServer, [
441
- Query.limit(1000),
442
- ]);
443
- return functions;
444
- }
445
-
446
- async findFunctionDirectories() {
447
- if (!this.appwriteFolderPath) {
448
- MessageFormatter.error("Failed to get appwriteFolderPath", undefined, { prefix: "Controller" });
449
- return new Map();
450
- }
451
- const functionsDir = findFunctionsDir(this.appwriteFolderPath);
452
- if (!functionsDir) {
453
- MessageFormatter.error("Failed to find functions directory", undefined, { prefix: "Controller" });
454
- return new Map();
455
- }
456
-
457
- const functionDirMap = new Map<string, string>();
458
- const entries = fs.readdirSync(functionsDir, { withFileTypes: true });
459
-
460
- for (const entry of entries) {
461
- if (entry.isDirectory()) {
462
- const functionPath = path.join(functionsDir, entry.name);
463
-
464
- // Validate it's a function directory
465
- if (!validateFunctionDirectory(functionPath)) {
466
- continue; // Skip invalid directories
467
- }
468
-
469
- // Match with config functions using normalized names
470
- if (this.config?.functions) {
471
- const normalizedEntryName = normalizeFunctionName(entry.name);
472
- const matchingFunc = this.config.functions.find(
473
- (f) => normalizeFunctionName(f.name) === normalizedEntryName
474
- );
475
- if (matchingFunc) {
476
- functionDirMap.set(matchingFunc.name, functionPath);
477
- }
478
- }
479
- }
480
- }
481
- return functionDirMap;
482
- }
483
-
484
- async deployFunction(
485
- functionName: string,
486
- functionPath?: string,
487
- functionConfig?: AppwriteFunction
488
- ) {
489
- await this.init();
490
- if (!this.appwriteServer) {
491
- MessageFormatter.error("Appwrite server not initialized", undefined, { prefix: "Controller" });
492
- return;
493
- }
494
-
495
- if (!functionConfig) {
496
- functionConfig = this.config?.functions?.find(
497
- (f) => f.name === functionName
498
- );
499
- }
500
- if (!functionConfig) {
501
- MessageFormatter.error(`Function ${functionName} not found in config`, undefined, { prefix: "Controller" });
502
- return;
503
- }
504
-
505
- await deployLocalFunction(
506
- this.appwriteServer,
507
- functionName,
508
- functionConfig,
509
- functionPath
510
- );
511
- }
512
-
513
- async syncFunctions() {
514
- await this.init();
515
- if (!this.appwriteServer) {
516
- MessageFormatter.error("Appwrite server not initialized", undefined, { prefix: "Controller" });
517
- return;
518
- }
519
-
520
- const localFunctions = this.config?.functions || [];
521
- const remoteFunctions = await listFunctions(this.appwriteServer, [
522
- Query.limit(1000),
523
- ]);
524
-
525
- for (const localFunction of localFunctions) {
526
- MessageFormatter.progress(`Syncing function ${localFunction.name}...`, { prefix: "Functions" });
527
- await this.deployFunction(localFunction.name);
528
- }
529
-
530
- MessageFormatter.success("All functions synchronized successfully!", { prefix: "Functions" });
531
- }
532
-
533
- async wipeDatabase(database: Models.Database, wipeBucket: boolean = false) {
534
- await this.init();
535
- if (!this.database || !this.config) throw new Error("Database not initialized");
536
- try {
537
- // Session is already in config from ConfigManager
538
- const { adapter, apiMode } = await getAdapterFromConfig(this.config, false);
539
- if (apiMode === 'tablesdb') {
540
- await wipeAllTables(adapter, database.$id);
541
- } else {
542
- await wipeDatabase(this.database, database.$id);
543
- }
544
- } catch {
545
- await wipeDatabase(this.database, database.$id);
546
- }
547
- if (wipeBucket) {
548
- await this.wipeBucketFromDatabase(database);
549
- }
550
- }
551
-
552
- async wipeBucketFromDatabase(database: Models.Database) {
553
- // Check configured bucket in database config
554
- const configuredBucket = this.config?.databases?.find(
555
- (db) => db.$id === database.$id
556
- )?.bucket;
557
- if (configuredBucket?.$id) {
558
- await this.wipeDocumentStorage(configuredBucket.$id);
559
- }
560
-
561
- // Also check for document bucket ID pattern
562
- if (this.config?.documentBucketId) {
563
- const documentBucketId = `${this.config.documentBucketId}_${database.$id
564
- .toLowerCase()
565
- .trim()
566
- .replace(/\s+/g, "")}`;
567
- try {
568
- await this.wipeDocumentStorage(documentBucketId);
569
- } catch (error: any) {
570
- // Ignore if bucket doesn't exist
571
- if (error?.type !== "storage_bucket_not_found") {
572
- throw error;
573
- }
574
- }
575
- }
576
- }
577
-
578
- async wipeCollection(
579
- database: Models.Database,
580
- collection: Models.Collection
581
- ) {
582
- await this.init();
583
- if (!this.database || !this.config) throw new Error("Database not initialized");
584
- try {
585
- // Session is already in config from ConfigManager
586
- const { adapter, apiMode } = await getAdapterFromConfig(this.config, false);
587
- if (apiMode === 'tablesdb') {
588
- await wipeTableRows(adapter, database.$id, collection.$id);
589
- } else {
590
- await wipeCollection(this.database, database.$id, collection.$id);
591
- }
592
- } catch {
593
- await wipeCollection(this.database, database.$id, collection.$id);
594
- }
595
- }
596
-
597
- async wipeDocumentStorage(bucketId: string) {
598
- await this.init();
599
- if (!this.storage) throw new Error("Storage not initialized");
600
- await wipeDocumentStorage(this.storage, bucketId);
601
- }
602
-
603
- async createOrUpdateCollectionsForDatabases(
604
- databases: Models.Database[],
605
- collections: Models.Collection[] = []
606
- ) {
607
- await this.init();
608
- if (!this.database || !this.config)
609
- throw new Error("Database or config not initialized");
610
- for (const database of databases) {
611
- await this.createOrUpdateCollections(database, undefined, collections);
612
- }
613
- }
614
-
615
- async createOrUpdateCollections(
616
- database: Models.Database,
617
- deletedCollections?: { collectionId: string; collectionName: string }[],
618
- collections: Models.Collection[] = []
619
- ) {
620
- await this.init();
621
- if (!this.database || !this.config)
622
- throw new Error("Database or config not initialized");
623
-
624
- // Ensure apiMode is properly set from adapter
625
- if (this.adapter && (!this.config.apiMode || this.config.apiMode === 'auto')) {
626
- this.config.apiMode = this.adapter.getApiMode();
627
- logger.debug(`Updated config.apiMode from adapter: ${this.config.apiMode}`, { prefix: "UtilsController" });
628
- }
629
-
630
- // Ensure we don't carry state between databases in a multi-db push
631
- // This resets processed sets and name->id mapping per database
632
- try {
633
- clearProcessingState();
634
- } catch {}
635
-
636
- // Always prefer adapter path for unified behavior. LegacyAdapter internally translates when needed.
637
- if (this.adapter) {
638
- logger.debug("Using adapter for createOrUpdateCollections (unified path)", {
639
- prefix: "UtilsController",
640
- apiMode: this.adapter.getApiMode()
641
- });
642
- await createOrUpdateCollectionsViaAdapter(
643
- this.adapter,
644
- database.$id,
645
- this.config,
646
- deletedCollections,
647
- collections
648
- );
649
- } else {
650
- // Fallback if adapter is unavailable for some reason
651
- logger.debug("Adapter unavailable, falling back to legacy Databases path", { prefix: "UtilsController" });
652
- await createOrUpdateCollections(
653
- this.database,
654
- database.$id,
655
- this.config,
656
- deletedCollections,
657
- collections
658
- );
659
- }
660
-
661
- // Safety net: Process any remaining queued operations to complete relationship sync
662
- try {
663
- MessageFormatter.info(`🔄 Processing final operation queue for database ${database.$id}`, { prefix: "UtilsController" });
664
- await processQueue(this.adapter || this.database!, database.$id);
665
- MessageFormatter.info(`✅ Operation queue processing completed`, { prefix: "UtilsController" });
666
- } catch (error) {
667
- MessageFormatter.error(`Failed to process operation queue`, error instanceof Error ? error : new Error(String(error)), { prefix: 'UtilsController' });
668
- }
669
- }
670
-
671
- async generateSchemas() {
672
- // Schema generation doesn't need Appwrite connection, just config
673
- if (!this.config) {
674
- MessageFormatter.progress("Loading config from ConfigManager...", { prefix: "Config" });
675
- try {
676
- const configManager = ConfigManager.getInstance();
677
-
678
- // Load config if not already loaded
679
- if (!configManager.hasConfig()) {
680
- await configManager.loadConfig({
681
- configDir: this.currentUserDir,
682
- validate: false,
683
- strictMode: false,
684
- });
685
- }
686
-
687
- this.config = configManager.getConfig();
688
- MessageFormatter.info("Config loaded successfully from ConfigManager", { prefix: "Config" });
689
- } catch (error) {
690
- MessageFormatter.error("Failed to load config", error instanceof Error ? error : undefined, { prefix: "Config" });
691
- return;
692
- }
693
- }
694
-
695
- if (!this.appwriteFolderPath) {
696
- MessageFormatter.error("Failed to get appwriteFolderPath", undefined, { prefix: "Controller" });
697
- return;
698
- }
699
-
700
- await generateSchemas(this.config, this.appwriteFolderPath);
701
- }
702
-
703
- async importData(options: SetupOptions = {}) {
704
- await this.init();
705
- if (!this.database) {
706
- MessageFormatter.error("Database not initialized", undefined, { prefix: "Controller" });
707
- return;
708
- }
709
- if (!this.storage) {
710
- MessageFormatter.error("Storage not initialized", undefined, { prefix: "Controller" });
711
- return;
712
- }
713
- if (!this.config) {
714
- MessageFormatter.error("Config not initialized", undefined, { prefix: "Controller" });
715
- return;
716
- }
717
- if (!this.appwriteFolderPath) {
718
- MessageFormatter.error("Failed to get appwriteFolderPath", undefined, { prefix: "Controller" });
719
- return;
720
- }
721
-
722
- const importDataActions = new ImportDataActions(
723
- this.database,
724
- this.storage,
725
- this.config,
726
- this.converterDefinitions,
727
- this.validityRuleDefinitions,
728
- this.afterImportActionsDefinitions
729
- );
730
-
731
- const importController = new ImportController(
732
- this.config,
733
- this.database,
734
- this.storage,
735
- this.appwriteFolderPath,
736
- importDataActions,
737
- options,
738
- options.databases
739
- );
740
- await importController.run(options.collections);
741
- }
742
-
743
- async synchronizeConfigurations(
744
- databases?: Models.Database[],
745
- config?: AppwriteConfig,
746
- databaseSelections?: DatabaseSelection[],
747
- bucketSelections?: BucketSelection[]
748
- ) {
749
- await this.init();
750
- if (!this.storage) {
751
- MessageFormatter.error("Storage not initialized", undefined, { prefix: "Controller" });
752
- return;
753
- }
754
- const configToUse = config || this.config;
755
- if (!configToUse) {
756
- MessageFormatter.error("Config not initialized", undefined, { prefix: "Controller" });
757
- return;
758
- }
759
- if (!this.appwriteFolderPath) {
760
- MessageFormatter.error("Failed to get appwriteFolderPath", undefined, { prefix: "Controller" });
761
- return;
762
- }
763
-
764
- // If selections are provided, filter the databases accordingly
765
- let filteredDatabases = databases;
766
- if (databaseSelections && databaseSelections.length > 0) {
767
- // Convert selections to Models.Database format
768
- filteredDatabases = [];
769
- const allDatabases = databases ? databases : await fetchAllDatabases(this.database!);
770
-
771
- for (const selection of databaseSelections) {
772
- const database = allDatabases.find(db => db.$id === selection.databaseId);
773
- if (database) {
774
- filteredDatabases.push(database);
775
- } else {
776
- MessageFormatter.warning(`Database with ID ${selection.databaseId} not found`, { prefix: "Controller" });
777
- }
778
- }
779
-
780
- MessageFormatter.info(`Syncing ${filteredDatabases.length} selected databases out of ${allDatabases.length} available`, { prefix: "Controller" });
781
- }
782
-
783
- const appwriteToX = new AppwriteToX(
784
- configToUse,
785
- this.appwriteFolderPath,
786
- this.storage
787
- );
788
- await appwriteToX.toSchemas(filteredDatabases);
789
-
790
- // Update the controller's config with the synchronized collections
791
- this.config = appwriteToX.updatedConfig;
792
-
793
- // Write the updated config back to disk
794
- const generator = new SchemaGenerator(this.config, this.appwriteFolderPath);
795
- const yamlConfigPath = findYamlConfig(this.appwriteFolderPath);
796
- const isYamlProject = !!yamlConfigPath;
797
- await generator.updateConfig(this.config, isYamlProject);
798
-
799
- // Regenerate JSON schemas to reflect any table terminology fixes
800
- try {
801
- MessageFormatter.progress("Regenerating JSON schemas...", { prefix: "Sync" });
802
- await createImportSchemas(this.appwriteFolderPath);
803
- MessageFormatter.success("JSON schemas regenerated successfully", { prefix: "Sync" });
804
- } catch (error) {
805
- // Log error but don't fail the sync process
806
- const errorMessage = error instanceof Error ? error.message : String(error);
807
- MessageFormatter.warning(
808
- `Failed to regenerate JSON schemas, but sync completed: ${errorMessage}`,
809
- { prefix: "Sync" }
810
- );
811
- logger.warn("Schema regeneration failed during sync:", error);
812
- }
813
- }
814
-
815
- async selectivePull(
816
- databaseSelections: DatabaseSelection[],
817
- bucketSelections: BucketSelection[]
818
- ): Promise<void> {
819
- await this.init();
820
- if (!this.database) {
821
- MessageFormatter.error("Database not initialized", undefined, { prefix: "Controller" });
822
- return;
823
- }
824
-
825
- MessageFormatter.progress("Starting selective pull (Appwrite → local config)...", { prefix: "Controller" });
826
-
827
- // Convert database selections to Models.Database format
828
- const selectedDatabases: Models.Database[] = [];
829
-
830
- for (const dbSelection of databaseSelections) {
831
- // Get the full database object from the controller
832
- const databases = await fetchAllDatabases(this.database);
833
- const database = databases.find(db => db.$id === dbSelection.databaseId);
834
-
835
- if (database) {
836
- selectedDatabases.push(database);
837
- MessageFormatter.info(`Selected database: ${database.name} (${database.$id})`, { prefix: "Controller" });
838
-
839
- // Log selected tables for this database
840
- if (dbSelection.tableIds && dbSelection.tableIds.length > 0) {
841
- MessageFormatter.info(` Tables: ${dbSelection.tableIds.join(', ')}`, { prefix: "Controller" });
842
- }
843
- } else {
844
- MessageFormatter.warning(`Database with ID ${dbSelection.databaseId} not found`, { prefix: "Controller" });
845
- }
846
- }
847
-
848
- if (selectedDatabases.length === 0) {
849
- MessageFormatter.warning("No valid databases selected for pull", { prefix: "Controller" });
850
- return;
851
- }
852
-
853
- // Log bucket selections if provided
854
- if (bucketSelections && bucketSelections.length > 0) {
855
- MessageFormatter.info(`Selected ${bucketSelections.length} buckets:`, { prefix: "Controller" });
856
- for (const bucketSelection of bucketSelections) {
857
- const dbInfo = bucketSelection.databaseId ? ` (DB: ${bucketSelection.databaseId})` : '';
858
- MessageFormatter.info(` - ${bucketSelection.bucketName} (${bucketSelection.bucketId})${dbInfo}`, { prefix: "Controller" });
859
- }
860
- }
861
-
862
- // Perform selective sync using the enhanced synchronizeConfigurations method
863
- await this.synchronizeConfigurations(selectedDatabases, this.config, databaseSelections, bucketSelections);
864
-
865
- MessageFormatter.success("Selective pull completed successfully! Remote config pulled to local.", { prefix: "Controller" });
866
- }
867
-
868
- async selectivePush(
869
- databaseSelections: DatabaseSelection[],
870
- bucketSelections: BucketSelection[]
871
- ): Promise<void> {
872
- await this.init();
873
- if (!this.database) {
874
- MessageFormatter.error("Database not initialized", undefined, { prefix: "Controller" });
875
- return;
876
- }
877
-
878
- // Always reload config from disk so pushes use current local YAML/Ts definitions
879
- try {
880
- await this.reloadConfig();
881
- MessageFormatter.info("Reloaded config from disk for push", { prefix: "Controller" });
882
- } catch (e) {
883
- // Non-fatal; continue with existing config
884
- MessageFormatter.warning("Could not reload config; continuing with current in-memory config", { prefix: "Controller" });
885
- }
886
-
887
- MessageFormatter.progress("Starting selective push (local config → Appwrite)...", { prefix: "Controller" });
888
-
889
- // Convert database selections to Models.Database format
890
- const selectedDatabases: Models.Database[] = [];
891
-
892
- for (const dbSelection of databaseSelections) {
893
- // Get the full database object from the controller
894
- const databases = await fetchAllDatabases(this.database);
895
- const database = databases.find(db => db.$id === dbSelection.databaseId);
896
-
897
- if (database) {
898
- selectedDatabases.push(database);
899
- MessageFormatter.info(`Selected database: ${database.name} (${database.$id})`, { prefix: "Controller" });
900
-
901
- // Log selected tables for this database
902
- if (dbSelection.tableIds && dbSelection.tableIds.length > 0) {
903
- MessageFormatter.info(` Tables: ${dbSelection.tableIds.join(', ')}`, { prefix: "Controller" });
904
- }
905
- } else {
906
- MessageFormatter.warning(`Database with ID ${dbSelection.databaseId} not found`, { prefix: "Controller" });
907
- }
908
- }
909
-
910
- if (selectedDatabases.length === 0) {
911
- MessageFormatter.warning("No valid databases selected for push", { prefix: "Controller" });
912
- return;
913
- }
914
-
915
- // Log bucket selections if provided
916
- if (bucketSelections && bucketSelections.length > 0) {
917
- MessageFormatter.info(`Selected ${bucketSelections.length} buckets:`, { prefix: "Controller" });
918
- for (const bucketSelection of bucketSelections) {
919
- const dbInfo = bucketSelection.databaseId ? ` (DB: ${bucketSelection.databaseId})` : '';
920
- MessageFormatter.info(` - ${bucketSelection.bucketName} (${bucketSelection.bucketId})${dbInfo}`, { prefix: "Controller" });
921
- }
922
- }
923
-
924
- // PUSH OPERATION: Push local configuration to Appwrite
925
- // Build database-specific collection mappings from databaseSelections
926
- const databaseCollectionsMap = new Map<string, any[]>();
927
-
928
- // Get all collections/tables from config (they're at the root level, not nested in databases)
929
- const allCollections = this.config?.collections || this.config?.tables || [];
930
-
931
- // Create database-specific collection mapping to preserve relationships
932
- for (const dbSelection of databaseSelections) {
933
- const collectionsForDatabase: any[] = [];
934
-
935
- MessageFormatter.info(`Processing collections for database: ${dbSelection.databaseId}`, { prefix: "Controller" });
936
-
937
- // Filter collections that were selected for THIS specific database
938
- for (const collection of allCollections) {
939
- const collectionId = collection.$id || (collection as any).id;
940
-
941
- // Check if this collection was selected for THIS database
942
- if (dbSelection.tableIds.includes(collectionId)) {
943
- collectionsForDatabase.push(collection);
944
- const source = (collection as any)._isFromTablesDir ? 'tables/' : 'collections/';
945
- MessageFormatter.info(` - Selected collection: ${collection.name || collectionId} for database ${dbSelection.databaseId} [source: ${source}]`, { prefix: "Controller" });
946
- }
947
- }
948
-
949
- databaseCollectionsMap.set(dbSelection.databaseId, collectionsForDatabase);
950
- MessageFormatter.info(`Database ${dbSelection.databaseId}: ${collectionsForDatabase.length} collections selected`, { prefix: "Controller" });
951
- }
952
-
953
- // Calculate total collections for logging
954
- const totalSelectedCollections = Array.from(databaseCollectionsMap.values())
955
- .reduce((total, collections) => total + collections.length, 0);
956
-
957
- MessageFormatter.info(`Pushing ${totalSelectedCollections} selected tables/collections to ${databaseCollectionsMap.size} databases`, { prefix: "Controller" });
958
-
959
- // Ensure databases exist
960
- await this.ensureDatabasesExist(selectedDatabases);
961
- await this.ensureDatabaseConfigBucketsExist(selectedDatabases);
962
-
963
- // Create/update collections with database-specific context
964
- for (const database of selectedDatabases) {
965
- const collectionsForThisDatabase = databaseCollectionsMap.get(database.$id) || [];
966
- if (collectionsForThisDatabase.length > 0) {
967
- MessageFormatter.info(`Pushing ${collectionsForThisDatabase.length} collections to database ${database.$id} (${database.name})`, { prefix: "Controller" });
968
- await this.createOrUpdateCollections(database, undefined, collectionsForThisDatabase);
969
- } else {
970
- MessageFormatter.info(`No collections selected for database ${database.$id} (${database.name})`, { prefix: "Controller" });
971
- }
972
- }
973
-
974
- MessageFormatter.success("Selective push completed successfully! Local config pushed to Appwrite.", { prefix: "Controller" });
975
- }
976
-
977
- async syncDb(
978
- databases: Models.Database[] = [],
979
- collections: Models.Collection[] = []
980
- ) {
981
- await this.init();
982
- if (!this.database) {
983
- MessageFormatter.error("Database not initialized", undefined, { prefix: "Controller" });
984
- return;
985
- }
986
- if (databases.length === 0) {
987
- const allDatabases = await fetchAllDatabases(this.database);
988
- databases = allDatabases;
989
- }
990
- // Ensure DBs exist
991
- await this.ensureDatabasesExist(databases);
992
- await this.ensureDatabaseConfigBucketsExist(databases);
993
-
994
- await this.createOrUpdateCollectionsForDatabases(databases, collections);
995
- }
996
-
997
- getAppwriteFolderPath() {
998
- return this.appwriteFolderPath;
999
- }
1000
-
1001
- async transferData(options: TransferOptions): Promise<void> {
1002
- let sourceClient = this.database;
1003
- let targetClient: Databases | undefined;
1004
- let sourceDatabases: Models.Database[] = [];
1005
- let targetDatabases: Models.Database[] = [];
1006
-
1007
- if (!sourceClient) {
1008
- MessageFormatter.error("Source database not initialized", undefined, { prefix: "Controller" });
1009
- return;
1010
- }
1011
-
1012
- if (options.isRemote) {
1013
- if (
1014
- !options.transferEndpoint ||
1015
- !options.transferProject ||
1016
- !options.transferKey
1017
- ) {
1018
- MessageFormatter.error("Remote transfer options are missing", undefined, { prefix: "Controller" });
1019
- return;
1020
- }
1021
-
1022
- const remoteClient = getClient(
1023
- options.transferEndpoint,
1024
- options.transferProject,
1025
- options.transferKey
1026
- );
1027
-
1028
- targetClient = new Databases(remoteClient);
1029
- sourceDatabases = await fetchAllDatabases(sourceClient);
1030
- targetDatabases = await fetchAllDatabases(targetClient);
1031
- } else {
1032
- targetClient = sourceClient;
1033
- sourceDatabases = targetDatabases = await fetchAllDatabases(sourceClient);
1034
- }
1035
-
1036
- // Always perform database transfer if databases are specified
1037
- if (options.fromDb && options.targetDb) {
1038
- const fromDb = sourceDatabases.find(
1039
- (db) => db.$id === options.fromDb!.$id
1040
- );
1041
- const targetDb = targetDatabases.find(
1042
- (db) => db.$id === options.targetDb!.$id
1043
- );
1044
-
1045
- if (!fromDb || !targetDb) {
1046
- MessageFormatter.error("Source or target database not found", undefined, { prefix: "Controller" });
1047
- return;
1048
- }
1049
-
1050
- if (options.isRemote && targetClient) {
1051
- await transferDatabaseLocalToRemote(
1052
- sourceClient,
1053
- options.transferEndpoint!,
1054
- options.transferProject!,
1055
- options.transferKey!,
1056
- fromDb.$id,
1057
- targetDb.$id
1058
- );
1059
- } else {
1060
- await transferDatabaseLocalToLocal(
1061
- sourceClient,
1062
- fromDb.$id,
1063
- targetDb.$id
1064
- );
1065
- }
1066
- }
1067
-
1068
- if (options.transferUsers) {
1069
- if (!options.isRemote) {
1070
- MessageFormatter.warning(
1071
- "User transfer is only supported for remote transfers. Skipping...",
1072
- { prefix: "Controller" }
1073
- );
1074
- } else if (!this.appwriteServer) {
1075
- MessageFormatter.error("Appwrite server not initialized", undefined, { prefix: "Controller" });
1076
- return;
1077
- } else {
1078
- MessageFormatter.progress("Starting user transfer...", { prefix: "Transfer" });
1079
- const localUsers = new Users(this.appwriteServer);
1080
- await transferUsersLocalToRemote(
1081
- localUsers,
1082
- options.transferEndpoint!,
1083
- options.transferProject!,
1084
- options.transferKey!
1085
- );
1086
- MessageFormatter.success("User transfer completed", { prefix: "Transfer" });
1087
- }
1088
- }
1089
-
1090
- // Handle storage transfer
1091
- if (this.storage && (options.sourceBucket || options.fromDb)) {
1092
- const sourceBucketId =
1093
- options.sourceBucket?.$id ||
1094
- (options.fromDb &&
1095
- this.config?.documentBucketId &&
1096
- `${this.config.documentBucketId}_${options.fromDb.$id
1097
- .toLowerCase()
1098
- .trim()
1099
- .replace(/\s+/g, "")}`);
1100
-
1101
- const targetBucketId =
1102
- options.targetBucket?.$id ||
1103
- (options.targetDb &&
1104
- this.config?.documentBucketId &&
1105
- `${this.config.documentBucketId}_${options.targetDb.$id
1106
- .toLowerCase()
1107
- .trim()
1108
- .replace(/\s+/g, "")}`);
1109
-
1110
- if (sourceBucketId && targetBucketId) {
1111
- MessageFormatter.progress(
1112
- `Starting storage transfer from ${sourceBucketId} to ${targetBucketId}`,
1113
- { prefix: "Transfer" }
1114
- );
1115
-
1116
- if (options.isRemote) {
1117
- await transferStorageLocalToRemote(
1118
- this.storage,
1119
- options.transferEndpoint!,
1120
- options.transferProject!,
1121
- options.transferKey!,
1122
- sourceBucketId,
1123
- targetBucketId
1124
- );
1125
- } else {
1126
- await transferStorageLocalToLocal(
1127
- this.storage,
1128
- sourceBucketId,
1129
- targetBucketId
1130
- );
1131
- }
1132
- }
1133
- }
1134
-
1135
- MessageFormatter.success("Transfer completed", { prefix: "Transfer" });
1136
- }
1137
-
1138
- async updateFunctionSpecifications(
1139
- functionId: string,
1140
- specification: Specification
1141
- ) {
1142
- await this.init();
1143
- if (!this.appwriteServer)
1144
- throw new Error("Appwrite server not initialized");
1145
- MessageFormatter.progress(
1146
- `Updating function specifications for ${functionId} to ${specification}`,
1147
- { prefix: "Functions" }
1148
- );
1149
- await updateFunctionSpecifications(
1150
- this.appwriteServer,
1151
- functionId,
1152
- specification
1153
- );
1154
- MessageFormatter.success(
1155
- `Successfully updated function specifications for ${functionId} to ${specification}`,
1156
- { prefix: "Functions" }
1157
- );
1158
- }
1159
-
1160
- /**
1161
- * Validates the current configuration for collections/tables conflicts
1162
- */
1163
- async validateConfiguration(strictMode: boolean = false): Promise<ValidationResult> {
1164
- await this.init();
1165
- if (!this.config) {
1166
- throw new Error("Configuration not loaded");
1167
- }
1168
-
1169
- MessageFormatter.progress("Validating configuration...", { prefix: "Validation" });
1170
-
1171
- const validation = strictMode
1172
- ? validateWithStrictMode(this.config, strictMode)
1173
- : validateCollectionsTablesConfig(this.config);
1174
-
1175
- reportValidationResults(validation, { verbose: true });
1176
-
1177
- if (validation.isValid) {
1178
- MessageFormatter.success("Configuration validation passed", { prefix: "Validation" });
1179
- } else {
1180
- MessageFormatter.error(`Configuration validation failed with ${validation.errors.length} errors`, undefined, { prefix: "Validation" });
1181
- }
1182
-
1183
- return validation;
1184
- }
1185
-
1186
- /**
1187
- * Get current session information for debugging/logging purposes
1188
- * Delegates to ConfigManager for session info
1189
- */
1190
- public async getSessionInfo(): Promise<{
1191
- hasSession: boolean;
1192
- authMethod?: string;
1193
- email?: string;
1194
- expiresAt?: string;
1195
- }> {
1196
- const configManager = ConfigManager.getInstance();
1197
-
1198
- try {
1199
- const authStatus = await configManager.getAuthStatus();
1200
- return {
1201
- hasSession: authStatus.hasValidSession,
1202
- authMethod: authStatus.authMethod,
1203
- email: authStatus.sessionInfo?.email,
1204
- expiresAt: authStatus.sessionInfo?.expiresAt
1205
- };
1206
- } catch (error) {
1207
- // If config not loaded, return empty status
1208
- return {
1209
- hasSession: false
1210
- };
1211
- }
1212
- }
1213
- }
1
+ import {
2
+ Client,
3
+ Databases,
4
+ Query,
5
+ Storage,
6
+ Users,
7
+ type Models,
8
+ } from "node-appwrite";
9
+ import {
10
+ type AppwriteConfig,
11
+ type AppwriteFunction,
12
+ type Specification,
13
+ } from "appwrite-utils";
14
+ import {
15
+ findAppwriteConfig,
16
+ findFunctionsDir,
17
+ } from "./utils/loadConfigs.js";
18
+ import { normalizeFunctionName, validateFunctionDirectory } from 'appwrite-utils-helpers';
19
+ import { UsersController } from "./users/methods.js";
20
+ import { AppwriteToX } from "./migrations/appwriteToX.js";
21
+ import { ImportController } from "./migrations/importController.js";
22
+ import { ImportDataActions } from "./migrations/importDataActions.js";
23
+ import {
24
+ ensureDatabasesExist,
25
+ wipeOtherDatabases,
26
+ ensureCollectionsExist,
27
+ } from "./databases/setup.js";
28
+ import {
29
+ createOrUpdateCollections,
30
+ createOrUpdateCollectionsViaAdapter,
31
+ wipeDatabase,
32
+ generateSchemas,
33
+ fetchAllCollections,
34
+ wipeCollection,
35
+ } from "./collections/methods.js";
36
+ import { wipeAllTables, wipeTableRows } from "./collections/methods.js";
37
+ import {
38
+ backupDatabase,
39
+ ensureDatabaseConfigBucketsExist,
40
+ ensureGlobalBucketsExist,
41
+ wipeDocumentStorage,
42
+ } from "./storage/methods.js";
43
+ import path from "path";
44
+ import {
45
+ type AfterImportActions,
46
+ type ConverterFunctions,
47
+ converterFunctions,
48
+ validationRules,
49
+ type ValidationRules,
50
+ } from "appwrite-utils";
51
+ import { afterImportActions } from "./migrations/afterImportActions.js";
52
+ import {
53
+ transferDatabaseLocalToLocal,
54
+ transferDatabaseLocalToRemote,
55
+ transferStorageLocalToLocal,
56
+ transferStorageLocalToRemote,
57
+ transferUsersLocalToRemote,
58
+ type TransferOptions,
59
+ } from "./migrations/transfer.js";
60
+ import { getClient, getClientWithAuth } from "appwrite-utils-helpers";
61
+ import { getAdapterFromConfig } from "appwrite-utils-helpers";
62
+ import type { DatabaseAdapter } from 'appwrite-utils-helpers';
63
+ import { hasSessionAuth, findSessionByEndpointAndProject, isValidSessionCookie, type SessionAuthInfo } from "appwrite-utils-helpers";
64
+ import { fetchAllDatabases } from "./databases/methods.js";
65
+ import {
66
+ listFunctions,
67
+ updateFunctionSpecifications,
68
+ } from "./functions/methods.js";
69
+ import chalk from "chalk";
70
+ import { deployLocalFunction } from "./functions/deployments.js";
71
+ import fs from "node:fs";
72
+ import {
73
+ configureLogging,
74
+ updateLogger,
75
+ logger,
76
+ MessageFormatter,
77
+ Messages,
78
+ SchemaGenerator,
79
+ findYamlConfig,
80
+ validateCollectionsTablesConfig,
81
+ reportValidationResults,
82
+ validateWithStrictMode,
83
+ ConfigManager,
84
+ type ValidationResult
85
+ } from "appwrite-utils-helpers";
86
+ import { createImportSchemas } from "./migrations/yaml/generateImportSchemas.js";
87
+ import { ClientFactory } from "appwrite-utils-helpers";
88
+ import type { DatabaseSelection, BucketSelection } from "./shared/selectionDialogs.js";
89
+ import { clearProcessingState, processQueue } from "./shared/operationQueue.js";
90
+
91
+ export interface SetupOptions {
92
+ databases?: Models.Database[];
93
+ collections?: string[];
94
+ doBackup?: boolean;
95
+ wipeDatabase?: boolean;
96
+ wipeCollections?: boolean;
97
+ wipeDocumentStorage?: boolean;
98
+ wipeUsers?: boolean;
99
+ transferUsers?: boolean;
100
+ generateSchemas?: boolean;
101
+ importData?: boolean;
102
+ checkDuplicates?: boolean;
103
+ shouldWriteFile?: boolean;
104
+ }
105
+
106
+ export interface ControllerInitOptions {
107
+ validate?: boolean;
108
+ strictMode?: boolean;
109
+ useSession?: boolean;
110
+ sessionCookie?: string;
111
+ preferJson?: boolean;
112
+ overrides?: {
113
+ appwriteEndpoint?: string;
114
+ appwriteProject?: string;
115
+ appwriteKey?: string;
116
+ };
117
+ }
118
+
119
+ export class UtilsController {
120
+ // ──────────────────────────────────────────────────
121
+ // SINGLETON PATTERN
122
+ // ──────────────────────────────────────────────────
123
+ private static instance: UtilsController | null = null;
124
+ private isInitialized: boolean = false;
125
+
126
+ /**
127
+ * Get the UtilsController singleton instance
128
+ */
129
+ public static getInstance(
130
+ currentUserDir: string,
131
+ directConfig?: {
132
+ appwriteEndpoint?: string;
133
+ appwriteProject?: string;
134
+ appwriteKey?: string;
135
+ }
136
+ ): UtilsController {
137
+ // Clear instance if currentUserDir has changed
138
+ if (UtilsController.instance &&
139
+ UtilsController.instance.currentUserDir !== currentUserDir) {
140
+ logger.debug(`Clearing singleton: currentUserDir changed from ${UtilsController.instance.currentUserDir} to ${currentUserDir}`, { prefix: "UtilsController" });
141
+ UtilsController.clearInstance();
142
+ }
143
+
144
+ // Clear instance if directConfig endpoint or project has changed
145
+ if (UtilsController.instance && directConfig) {
146
+ const existingConfig = UtilsController.instance.config;
147
+ if (existingConfig) {
148
+ const endpointChanged = directConfig.appwriteEndpoint &&
149
+ existingConfig.appwriteEndpoint !== directConfig.appwriteEndpoint;
150
+ const projectChanged = directConfig.appwriteProject &&
151
+ existingConfig.appwriteProject !== directConfig.appwriteProject;
152
+
153
+ if (endpointChanged || projectChanged) {
154
+ logger.debug("Clearing singleton: endpoint or project changed", { prefix: "UtilsController" });
155
+ UtilsController.clearInstance();
156
+ }
157
+ }
158
+ }
159
+
160
+ if (!UtilsController.instance) {
161
+ UtilsController.instance = new UtilsController(currentUserDir, directConfig);
162
+ }
163
+
164
+ return UtilsController.instance;
165
+ }
166
+
167
+ /**
168
+ * Clear the singleton instance (useful for testing)
169
+ */
170
+ public static clearInstance(): void {
171
+ UtilsController.instance = null;
172
+ }
173
+
174
+ // ──────────────────────────────────────────────────
175
+ // INSTANCE FIELDS
176
+ // ──────────────────────────────────────────────────
177
+ private appwriteFolderPath?: string;
178
+ private appwriteConfigPath?: string;
179
+ private currentUserDir: string;
180
+ public config?: AppwriteConfig;
181
+ public appwriteServer?: Client;
182
+ public database?: Databases;
183
+ public storage?: Storage;
184
+ public adapter?: DatabaseAdapter;
185
+ public converterDefinitions: ConverterFunctions = converterFunctions;
186
+ public validityRuleDefinitions: ValidationRules = validationRules;
187
+ public afterImportActionsDefinitions: AfterImportActions = afterImportActions;
188
+
189
+ constructor(
190
+ currentUserDir: string,
191
+ directConfig?: {
192
+ appwriteEndpoint?: string;
193
+ appwriteProject?: string;
194
+ appwriteKey?: string;
195
+ }
196
+ ) {
197
+ this.currentUserDir = currentUserDir;
198
+ const basePath = currentUserDir;
199
+
200
+ if (directConfig) {
201
+ let hasErrors = false;
202
+ if (!directConfig.appwriteEndpoint) {
203
+ MessageFormatter.error("Appwrite endpoint is required", undefined, { prefix: "Config" });
204
+ hasErrors = true;
205
+ }
206
+ if (!directConfig.appwriteProject) {
207
+ MessageFormatter.error("Appwrite project is required", undefined, { prefix: "Config" });
208
+ hasErrors = true;
209
+ }
210
+ // Check authentication: either API key or session auth is required
211
+ const hasValidSession = directConfig.appwriteEndpoint && directConfig.appwriteProject &&
212
+ hasSessionAuth(directConfig.appwriteEndpoint, directConfig.appwriteProject);
213
+
214
+ if (!directConfig.appwriteKey && !hasValidSession) {
215
+ MessageFormatter.error(
216
+ "Authentication required: provide an API key or login with 'appwrite login'",
217
+ undefined,
218
+ { prefix: "Config" }
219
+ );
220
+ hasErrors = true;
221
+ } else if (!directConfig.appwriteKey && hasValidSession) {
222
+ MessageFormatter.info("Using session authentication (no API key required)", { prefix: "Auth" });
223
+ } else if (directConfig.appwriteKey && hasValidSession) {
224
+ MessageFormatter.info("API key provided, session authentication also available", { prefix: "Auth" });
225
+ }
226
+ if (!hasErrors) {
227
+ // Only set config if we have all required fields
228
+ this.appwriteFolderPath = basePath;
229
+ this.config = {
230
+ appwriteEndpoint: directConfig.appwriteEndpoint!,
231
+ appwriteProject: directConfig.appwriteProject!,
232
+ appwriteKey: directConfig.appwriteKey || "",
233
+ appwriteClient: null,
234
+ apiMode: "auto", // Default to auto-detect for dual API support
235
+ authMethod: "auto", // Default to auto-detect authentication method
236
+ enableBackups: false,
237
+ backupInterval: 0,
238
+ backupRetention: 0,
239
+ enableBackupCleanup: false,
240
+ enableMockData: false,
241
+ documentBucketId: "",
242
+ usersCollectionName: "",
243
+ databases: [],
244
+ buckets: [],
245
+ functions: [],
246
+ logging: {
247
+ enabled: false,
248
+ level: "info",
249
+ console: false,
250
+ },
251
+ };
252
+ }
253
+ } else {
254
+ // Try to find config file
255
+ const appwriteConfigFound = findAppwriteConfig(basePath);
256
+ if (!appwriteConfigFound) {
257
+ MessageFormatter.warning(
258
+ "No appwriteConfig.ts found and no direct configuration provided",
259
+ { prefix: "Config" }
260
+ );
261
+ return;
262
+ }
263
+ this.appwriteConfigPath = appwriteConfigFound;
264
+ this.appwriteFolderPath = appwriteConfigFound; // For YAML configs, findAppwriteConfig already returns the correct directory
265
+ }
266
+ }
267
+
268
+ async init(options: ControllerInitOptions = {}) {
269
+ const { validate = false, strictMode = false, preferJson = false, useSession, sessionCookie, overrides } = options;
270
+ const configManager = ConfigManager.getInstance();
271
+
272
+ // Load config if not already loaded
273
+ if (!configManager.hasConfig()) {
274
+ await configManager.loadConfig({
275
+ configDir: this.currentUserDir,
276
+ validate,
277
+ strictMode,
278
+ preferJson,
279
+ useSession,
280
+ explicitSessionCookie: sessionCookie,
281
+ overrides,
282
+ });
283
+ }
284
+
285
+ const config = configManager.getConfig();
286
+
287
+ // Configure logging based on config
288
+ if (config.logging) {
289
+ configureLogging(config.logging);
290
+ updateLogger();
291
+ }
292
+
293
+ // Create client and adapter (session already in config from ConfigManager)
294
+ const { client, adapter } = await ClientFactory.createFromConfig(config);
295
+
296
+ this.appwriteServer = client;
297
+ this.adapter = adapter;
298
+ this.config = config;
299
+
300
+ // Update config.apiMode from adapter if it's auto or not set
301
+ if (adapter && (!config.apiMode || config.apiMode === 'auto')) {
302
+ this.config.apiMode = adapter.getApiMode();
303
+ logger.debug(`Updated config.apiMode from adapter during init: ${this.config.apiMode}`, { prefix: "UtilsController" });
304
+ }
305
+
306
+ this.database = new Databases(this.appwriteServer);
307
+ this.storage = new Storage(this.appwriteServer);
308
+ this.config.appwriteClient = this.appwriteServer;
309
+
310
+ // Log only on FIRST initialization to avoid spam
311
+ if (!this.isInitialized) {
312
+ const apiMode = adapter.getApiMode();
313
+ const configApiMode = this.config.apiMode;
314
+ MessageFormatter.info(`Database adapter initialized (apiMode: ${apiMode}, config.apiMode: ${configApiMode})`, { prefix: "Adapter" });
315
+ this.isInitialized = true;
316
+ } else {
317
+ logger.debug("Adapter reused from cache", { prefix: "UtilsController" });
318
+ }
319
+ }
320
+
321
+ async reloadConfig() {
322
+ const configManager = ConfigManager.getInstance();
323
+
324
+ // Session preservation is automatic in ConfigManager
325
+ const config = await configManager.reloadConfig();
326
+
327
+ // Configure logging based on updated config
328
+ if (config.logging) {
329
+ configureLogging(config.logging);
330
+ updateLogger();
331
+ }
332
+
333
+ // Recreate client and adapter
334
+ const { client, adapter } = await ClientFactory.createFromConfig(config);
335
+
336
+ this.appwriteServer = client;
337
+ this.adapter = adapter;
338
+ this.config = config;
339
+ this.database = new Databases(this.appwriteServer);
340
+ this.storage = new Storage(this.appwriteServer);
341
+ this.config.appwriteClient = this.appwriteServer;
342
+
343
+ logger.debug("Config reloaded, adapter refreshed", { prefix: "UtilsController" });
344
+ }
345
+
346
+
347
+ async ensureDatabaseConfigBucketsExist(databases: Models.Database[] = []) {
348
+ await this.init();
349
+ if (!this.storage) {
350
+ MessageFormatter.error("Storage not initialized", undefined, { prefix: "Controller" });
351
+ return;
352
+ }
353
+ if (!this.config) {
354
+ MessageFormatter.error("Config not initialized", undefined, { prefix: "Controller" });
355
+ return;
356
+ }
357
+ await ensureDatabaseConfigBucketsExist(
358
+ this.storage,
359
+ this.config,
360
+ databases
361
+ );
362
+ }
363
+
364
+ async pushGlobalBuckets(selectedBucketIds?: string[]) {
365
+ await this.init();
366
+ if (!this.storage) {
367
+ MessageFormatter.error("Storage not initialized", undefined, { prefix: "Controller" });
368
+ return;
369
+ }
370
+ if (!this.config) {
371
+ MessageFormatter.error("Config not initialized", undefined, { prefix: "Controller" });
372
+ return;
373
+ }
374
+ await ensureGlobalBucketsExist(this.storage, this.config, selectedBucketIds);
375
+ }
376
+
377
+ async ensureDatabasesExist(databases?: Models.Database[]) {
378
+ await this.init();
379
+ if (!this.config) {
380
+ MessageFormatter.error("Config not initialized", undefined, { prefix: "Controller" });
381
+ return;
382
+ }
383
+ await this.ensureDatabaseConfigBucketsExist(databases);
384
+ await ensureDatabasesExist(this.config, databases);
385
+ }
386
+
387
+ async ensureCollectionsExist(
388
+ database: Models.Database,
389
+ collections?: Models.Collection[]
390
+ ) {
391
+ await this.init();
392
+ if (!this.config) {
393
+ MessageFormatter.error("Config not initialized", undefined, { prefix: "Controller" });
394
+ return;
395
+ }
396
+ await ensureCollectionsExist(this.config, database, collections);
397
+ }
398
+
399
+ async getDatabasesByIds(ids: string[]) {
400
+ await this.init();
401
+ if (!this.database) {
402
+ MessageFormatter.error("Database not initialized", undefined, { prefix: "Controller" });
403
+ return;
404
+ }
405
+ if (ids.length === 0) return [];
406
+ const dbs = await this.database.list([
407
+ Query.limit(500),
408
+ Query.equal("$id", ids),
409
+ ]);
410
+ return dbs.databases;
411
+ }
412
+
413
+ async fetchAllBuckets(): Promise<{ buckets: Models.Bucket[] }> {
414
+ await this.init();
415
+ if (!this.storage) {
416
+ MessageFormatter.warning("Storage not initialized - buckets will be empty", { prefix: "Controller" });
417
+ return { buckets: [] };
418
+ }
419
+
420
+ try {
421
+ const result = await this.storage.listBuckets([
422
+ Query.limit(1000) // Increase limit to get all buckets
423
+ ]);
424
+
425
+ MessageFormatter.success(`Found ${result.buckets.length} buckets`, { prefix: "Controller" });
426
+ return result;
427
+ } catch (error: any) {
428
+ MessageFormatter.error(`Failed to fetch buckets: ${error.message || error}`, error instanceof Error ? error : undefined, { prefix: "Controller" });
429
+ return { buckets: [] };
430
+ }
431
+ }
432
+
433
+ async wipeOtherDatabases(databasesToKeep: Models.Database[]) {
434
+ await this.init();
435
+ if (!this.database) {
436
+ MessageFormatter.error("Database not initialized", undefined, { prefix: "Controller" });
437
+ return;
438
+ }
439
+ await wipeOtherDatabases(this.database, databasesToKeep);
440
+ }
441
+
442
+ async wipeUsers() {
443
+ await this.init();
444
+ if (!this.config || !this.database) {
445
+ MessageFormatter.error("Config or database not initialized", undefined, { prefix: "Controller" });
446
+ return;
447
+ }
448
+ const usersController = new UsersController(this.config, this.database);
449
+ await usersController.wipeUsers();
450
+ }
451
+
452
+ async backupDatabase(database: Models.Database, format: 'json' | 'zip' = 'json') {
453
+ await this.init();
454
+ if (!this.database || !this.storage || !this.config) {
455
+ MessageFormatter.error("Database, storage, or config not initialized", undefined, { prefix: "Controller" });
456
+ return;
457
+ }
458
+ await backupDatabase(
459
+ this.config,
460
+ this.database,
461
+ database.$id,
462
+ this.storage,
463
+ format
464
+ );
465
+ }
466
+
467
+ async listAllFunctions() {
468
+ await this.init();
469
+ if (!this.appwriteServer) {
470
+ MessageFormatter.error("Appwrite server not initialized", undefined, { prefix: "Controller" });
471
+ return [];
472
+ }
473
+ const { functions } = await listFunctions(this.appwriteServer, [
474
+ Query.limit(1000),
475
+ ]);
476
+ return functions;
477
+ }
478
+
479
+ async findFunctionDirectories() {
480
+ if (!this.appwriteFolderPath) {
481
+ MessageFormatter.error("Failed to get appwriteFolderPath", undefined, { prefix: "Controller" });
482
+ return new Map();
483
+ }
484
+ const functionsDir = findFunctionsDir(this.appwriteFolderPath);
485
+ if (!functionsDir) {
486
+ MessageFormatter.error("Failed to find functions directory", undefined, { prefix: "Controller" });
487
+ return new Map();
488
+ }
489
+
490
+ const functionDirMap = new Map<string, string>();
491
+ const entries = fs.readdirSync(functionsDir, { withFileTypes: true });
492
+
493
+ for (const entry of entries) {
494
+ if (entry.isDirectory()) {
495
+ const functionPath = path.join(functionsDir, entry.name);
496
+
497
+ // Validate it's a function directory
498
+ if (!validateFunctionDirectory(functionPath)) {
499
+ continue; // Skip invalid directories
500
+ }
501
+
502
+ // Match with config functions using normalized names
503
+ if (this.config?.functions) {
504
+ const normalizedEntryName = normalizeFunctionName(entry.name);
505
+ const matchingFunc = this.config.functions.find(
506
+ (f) => normalizeFunctionName(f.name) === normalizedEntryName
507
+ );
508
+ if (matchingFunc) {
509
+ functionDirMap.set(matchingFunc.name, functionPath);
510
+ }
511
+ }
512
+ }
513
+ }
514
+ return functionDirMap;
515
+ }
516
+
517
+ async deployFunction(
518
+ functionName: string,
519
+ functionPath?: string,
520
+ functionConfig?: AppwriteFunction
521
+ ) {
522
+ await this.init();
523
+ if (!this.appwriteServer) {
524
+ MessageFormatter.error("Appwrite server not initialized", undefined, { prefix: "Controller" });
525
+ return;
526
+ }
527
+
528
+ if (!functionConfig) {
529
+ functionConfig = this.config?.functions?.find(
530
+ (f) => f.name === functionName
531
+ );
532
+ }
533
+ if (!functionConfig) {
534
+ MessageFormatter.error(`Function ${functionName} not found in config`, undefined, { prefix: "Controller" });
535
+ return;
536
+ }
537
+
538
+ await deployLocalFunction(
539
+ this.appwriteServer,
540
+ functionName,
541
+ functionConfig,
542
+ functionPath,
543
+ this.appwriteFolderPath
544
+ );
545
+ }
546
+
547
+ async syncFunctions() {
548
+ await this.init();
549
+ if (!this.appwriteServer) {
550
+ MessageFormatter.error("Appwrite server not initialized", undefined, { prefix: "Controller" });
551
+ return;
552
+ }
553
+
554
+ const localFunctions = this.config?.functions || [];
555
+ const remoteFunctions = await listFunctions(this.appwriteServer, [
556
+ Query.limit(1000),
557
+ ]);
558
+
559
+ for (const localFunction of localFunctions) {
560
+ MessageFormatter.progress(`Syncing function ${localFunction.name}...`, { prefix: "Functions" });
561
+ await this.deployFunction(localFunction.name);
562
+ }
563
+
564
+ MessageFormatter.success("All functions synchronized successfully!", { prefix: "Functions" });
565
+ }
566
+
567
+ async wipeDatabase(database: Models.Database, wipeBucket: boolean = false) {
568
+ await this.init();
569
+ if (!this.database || !this.config) throw new Error("Database not initialized");
570
+ try {
571
+ // Session is already in config from ConfigManager
572
+ const { adapter, apiMode } = await getAdapterFromConfig(this.config, false);
573
+ if (apiMode === 'tablesdb') {
574
+ await wipeAllTables(adapter, database.$id);
575
+ } else {
576
+ await wipeDatabase(this.database, database.$id);
577
+ }
578
+ } catch {
579
+ await wipeDatabase(this.database, database.$id);
580
+ }
581
+ if (wipeBucket) {
582
+ await this.wipeBucketFromDatabase(database);
583
+ }
584
+ }
585
+
586
+ async wipeBucketFromDatabase(database: Models.Database) {
587
+ // Check configured bucket in database config
588
+ const configuredBucket = this.config?.databases?.find(
589
+ (db) => db.$id === database.$id
590
+ )?.bucket;
591
+ if (configuredBucket?.$id) {
592
+ await this.wipeDocumentStorage(configuredBucket.$id);
593
+ }
594
+
595
+ // Also check for document bucket ID pattern
596
+ if (this.config?.documentBucketId) {
597
+ const documentBucketId = `${this.config.documentBucketId}_${database.$id
598
+ .toLowerCase()
599
+ .trim()
600
+ .replace(/\s+/g, "")}`;
601
+ try {
602
+ await this.wipeDocumentStorage(documentBucketId);
603
+ } catch (error: any) {
604
+ // Ignore if bucket doesn't exist
605
+ if (error?.type !== "storage_bucket_not_found") {
606
+ throw error;
607
+ }
608
+ }
609
+ }
610
+ }
611
+
612
+ async wipeCollection(
613
+ database: Models.Database,
614
+ collection: Models.Collection
615
+ ) {
616
+ await this.init();
617
+ if (!this.database || !this.config) throw new Error("Database not initialized");
618
+ try {
619
+ // Session is already in config from ConfigManager
620
+ const { adapter, apiMode } = await getAdapterFromConfig(this.config, false);
621
+ if (apiMode === 'tablesdb') {
622
+ await wipeTableRows(adapter, database.$id, collection.$id);
623
+ } else {
624
+ await wipeCollection(this.database, database.$id, collection.$id);
625
+ }
626
+ } catch {
627
+ await wipeCollection(this.database, database.$id, collection.$id);
628
+ }
629
+ }
630
+
631
+ async wipeDocumentStorage(bucketId: string) {
632
+ await this.init();
633
+ if (!this.storage) throw new Error("Storage not initialized");
634
+ await wipeDocumentStorage(this.storage, bucketId);
635
+ }
636
+
637
+ async createOrUpdateCollectionsForDatabases(
638
+ databases: Models.Database[],
639
+ collections: Models.Collection[] = []
640
+ ) {
641
+ await this.init();
642
+ if (!this.database || !this.config)
643
+ throw new Error("Database or config not initialized");
644
+ for (const database of databases) {
645
+ await this.createOrUpdateCollections(database, undefined, collections);
646
+ }
647
+ }
648
+
649
+ async createOrUpdateCollections(
650
+ database: Models.Database,
651
+ deletedCollections?: { collectionId: string; collectionName: string }[],
652
+ collections: Models.Collection[] = []
653
+ ) {
654
+ await this.init();
655
+ if (!this.database || !this.config)
656
+ throw new Error("Database or config not initialized");
657
+
658
+ // Ensure apiMode is properly set from adapter
659
+ if (this.adapter && (!this.config.apiMode || this.config.apiMode === 'auto')) {
660
+ this.config.apiMode = this.adapter.getApiMode();
661
+ logger.debug(`Updated config.apiMode from adapter: ${this.config.apiMode}`, { prefix: "UtilsController" });
662
+ }
663
+
664
+ // Ensure we don't carry state between databases in a multi-db push
665
+ // This resets processed sets and name->id mapping per database
666
+ try {
667
+ clearProcessingState();
668
+ } catch {}
669
+
670
+ // Always prefer adapter path for unified behavior. LegacyAdapter internally translates when needed.
671
+ if (this.adapter) {
672
+ logger.debug("Using adapter for createOrUpdateCollections (unified path)", {
673
+ prefix: "UtilsController",
674
+ apiMode: this.adapter.getApiMode()
675
+ });
676
+ await createOrUpdateCollectionsViaAdapter(
677
+ this.adapter,
678
+ database.$id,
679
+ this.config,
680
+ deletedCollections,
681
+ collections
682
+ );
683
+ } else {
684
+ // Fallback if adapter is unavailable for some reason
685
+ logger.debug("Adapter unavailable, falling back to legacy Databases path", { prefix: "UtilsController" });
686
+ await createOrUpdateCollections(
687
+ this.database,
688
+ database.$id,
689
+ this.config,
690
+ deletedCollections,
691
+ collections
692
+ );
693
+ }
694
+
695
+ // Safety net: Process any remaining queued operations to complete relationship sync
696
+ try {
697
+ MessageFormatter.info(`🔄 Processing final operation queue for database ${database.$id}`, { prefix: "UtilsController" });
698
+ await processQueue(this.adapter || this.database!, database.$id);
699
+ MessageFormatter.info(`✅ Operation queue processing completed`, { prefix: "UtilsController" });
700
+ } catch (error) {
701
+ MessageFormatter.error(`Failed to process operation queue`, error instanceof Error ? error : new Error(String(error)), { prefix: 'UtilsController' });
702
+ }
703
+ }
704
+
705
+ async generateSchemas() {
706
+ // Schema generation doesn't need Appwrite connection, just config
707
+ if (!this.config) {
708
+ MessageFormatter.progress("Loading config from ConfigManager...", { prefix: "Config" });
709
+ try {
710
+ const configManager = ConfigManager.getInstance();
711
+
712
+ // Load config if not already loaded
713
+ if (!configManager.hasConfig()) {
714
+ await configManager.loadConfig({
715
+ configDir: this.currentUserDir,
716
+ validate: false,
717
+ strictMode: false,
718
+ });
719
+ }
720
+
721
+ this.config = configManager.getConfig();
722
+ MessageFormatter.info("Config loaded successfully from ConfigManager", { prefix: "Config" });
723
+ } catch (error) {
724
+ MessageFormatter.error("Failed to load config", error instanceof Error ? error : undefined, { prefix: "Config" });
725
+ return;
726
+ }
727
+ }
728
+
729
+ if (!this.appwriteFolderPath) {
730
+ MessageFormatter.error("Failed to get appwriteFolderPath", undefined, { prefix: "Controller" });
731
+ return;
732
+ }
733
+
734
+ await generateSchemas(this.config, this.appwriteFolderPath);
735
+ }
736
+
737
+ async importData(options: SetupOptions = {}) {
738
+ await this.init();
739
+ if (!this.database) {
740
+ MessageFormatter.error("Database not initialized", undefined, { prefix: "Controller" });
741
+ return;
742
+ }
743
+ if (!this.storage) {
744
+ MessageFormatter.error("Storage not initialized", undefined, { prefix: "Controller" });
745
+ return;
746
+ }
747
+ if (!this.config) {
748
+ MessageFormatter.error("Config not initialized", undefined, { prefix: "Controller" });
749
+ return;
750
+ }
751
+ if (!this.appwriteFolderPath) {
752
+ MessageFormatter.error("Failed to get appwriteFolderPath", undefined, { prefix: "Controller" });
753
+ return;
754
+ }
755
+
756
+ const importDataActions = new ImportDataActions(
757
+ this.database,
758
+ this.storage,
759
+ this.config,
760
+ this.converterDefinitions,
761
+ this.validityRuleDefinitions,
762
+ this.afterImportActionsDefinitions
763
+ );
764
+
765
+ const importController = new ImportController(
766
+ this.config,
767
+ this.database,
768
+ this.storage,
769
+ this.appwriteFolderPath,
770
+ importDataActions,
771
+ options,
772
+ options.databases
773
+ );
774
+ await importController.run(options.collections);
775
+ }
776
+
777
+ async synchronizeConfigurations(
778
+ databases?: Models.Database[],
779
+ config?: AppwriteConfig,
780
+ databaseSelections?: DatabaseSelection[],
781
+ bucketSelections?: BucketSelection[]
782
+ ) {
783
+ await this.init();
784
+ if (!this.storage) {
785
+ MessageFormatter.error("Storage not initialized", undefined, { prefix: "Controller" });
786
+ return;
787
+ }
788
+ const configToUse = config || this.config;
789
+ if (!configToUse) {
790
+ MessageFormatter.error("Config not initialized", undefined, { prefix: "Controller" });
791
+ return;
792
+ }
793
+ if (!this.appwriteFolderPath) {
794
+ MessageFormatter.error("Failed to get appwriteFolderPath", undefined, { prefix: "Controller" });
795
+ return;
796
+ }
797
+
798
+ // If selections are provided, filter the databases accordingly
799
+ let filteredDatabases = databases;
800
+ if (databaseSelections && databaseSelections.length > 0) {
801
+ // Convert selections to Models.Database format
802
+ filteredDatabases = [];
803
+ const allDatabases = databases ? databases : await fetchAllDatabases(this.database!);
804
+
805
+ for (const selection of databaseSelections) {
806
+ const database = allDatabases.find(db => db.$id === selection.databaseId);
807
+ if (database) {
808
+ filteredDatabases.push(database);
809
+ } else {
810
+ MessageFormatter.warning(`Database with ID ${selection.databaseId} not found`, { prefix: "Controller" });
811
+ }
812
+ }
813
+
814
+ MessageFormatter.info(`Syncing ${filteredDatabases.length} selected databases out of ${allDatabases.length} available`, { prefix: "Controller" });
815
+ }
816
+
817
+ const appwriteToX = new AppwriteToX(
818
+ configToUse,
819
+ this.appwriteFolderPath,
820
+ this.storage
821
+ );
822
+ await appwriteToX.toSchemas(filteredDatabases);
823
+
824
+ // Update the controller's config with the synchronized collections
825
+ this.config = appwriteToX.updatedConfig;
826
+
827
+ // Write the updated config back to disk
828
+ const generator = new SchemaGenerator(this.config, this.appwriteFolderPath);
829
+ const yamlConfigPath = findYamlConfig(this.appwriteFolderPath);
830
+ const isYamlProject = !!yamlConfigPath;
831
+ await generator.updateConfig(this.config, isYamlProject);
832
+
833
+ // Regenerate JSON schemas to reflect any table terminology fixes
834
+ try {
835
+ MessageFormatter.progress("Regenerating JSON schemas...", { prefix: "Sync" });
836
+ await createImportSchemas(this.appwriteFolderPath);
837
+ MessageFormatter.success("JSON schemas regenerated successfully", { prefix: "Sync" });
838
+ } catch (error) {
839
+ // Log error but don't fail the sync process
840
+ const errorMessage = error instanceof Error ? error.message : String(error);
841
+ MessageFormatter.warning(
842
+ `Failed to regenerate JSON schemas, but sync completed: ${errorMessage}`,
843
+ { prefix: "Sync" }
844
+ );
845
+ logger.warn("Schema regeneration failed during sync:", error);
846
+ }
847
+ }
848
+
849
+ async selectivePull(
850
+ databaseSelections: DatabaseSelection[],
851
+ bucketSelections: BucketSelection[]
852
+ ): Promise<void> {
853
+ await this.init();
854
+ if (!this.database) {
855
+ MessageFormatter.error("Database not initialized", undefined, { prefix: "Controller" });
856
+ return;
857
+ }
858
+
859
+ MessageFormatter.progress("Starting selective pull (Appwrite → local config)...", { prefix: "Controller" });
860
+
861
+ // Convert database selections to Models.Database format
862
+ const selectedDatabases: Models.Database[] = [];
863
+
864
+ for (const dbSelection of databaseSelections) {
865
+ // Get the full database object from the controller
866
+ const databases = await fetchAllDatabases(this.database);
867
+ const database = databases.find(db => db.$id === dbSelection.databaseId);
868
+
869
+ if (database) {
870
+ selectedDatabases.push(database);
871
+ MessageFormatter.info(`Selected database: ${database.name} (${database.$id})`, { prefix: "Controller" });
872
+
873
+ // Log selected tables for this database
874
+ if (dbSelection.tableIds && dbSelection.tableIds.length > 0) {
875
+ MessageFormatter.info(` Tables: ${dbSelection.tableIds.join(', ')}`, { prefix: "Controller" });
876
+ }
877
+ } else {
878
+ MessageFormatter.warning(`Database with ID ${dbSelection.databaseId} not found`, { prefix: "Controller" });
879
+ }
880
+ }
881
+
882
+ if (selectedDatabases.length === 0) {
883
+ MessageFormatter.warning("No valid databases selected for pull", { prefix: "Controller" });
884
+ return;
885
+ }
886
+
887
+ // Log bucket selections if provided
888
+ if (bucketSelections && bucketSelections.length > 0) {
889
+ MessageFormatter.info(`Selected ${bucketSelections.length} buckets:`, { prefix: "Controller" });
890
+ for (const bucketSelection of bucketSelections) {
891
+ const dbInfo = bucketSelection.databaseId ? ` (DB: ${bucketSelection.databaseId})` : '';
892
+ MessageFormatter.info(` - ${bucketSelection.bucketName} (${bucketSelection.bucketId})${dbInfo}`, { prefix: "Controller" });
893
+ }
894
+ }
895
+
896
+ // Perform selective sync using the enhanced synchronizeConfigurations method
897
+ await this.synchronizeConfigurations(selectedDatabases, this.config, databaseSelections, bucketSelections);
898
+
899
+ MessageFormatter.success("Selective pull completed successfully! Remote config pulled to local.", { prefix: "Controller" });
900
+ }
901
+
902
+ async selectivePush(
903
+ databaseSelections: DatabaseSelection[],
904
+ bucketSelections: BucketSelection[]
905
+ ): Promise<void> {
906
+ await this.init();
907
+ if (!this.database) {
908
+ MessageFormatter.error("Database not initialized", undefined, { prefix: "Controller" });
909
+ return;
910
+ }
911
+
912
+ // Always reload config from disk so pushes use current local YAML/Ts definitions
913
+ try {
914
+ await this.reloadConfig();
915
+ MessageFormatter.info("Reloaded config from disk for push", { prefix: "Controller" });
916
+ } catch (e) {
917
+ // Non-fatal; continue with existing config
918
+ MessageFormatter.warning("Could not reload config; continuing with current in-memory config", { prefix: "Controller" });
919
+ }
920
+
921
+ MessageFormatter.progress("Starting selective push (local config → Appwrite)...", { prefix: "Controller" });
922
+
923
+ // Convert database selections to Models.Database format
924
+ const selectedDatabases: Models.Database[] = [];
925
+ const serverDatabases = await fetchAllDatabases(this.database);
926
+ const configuredDatabases = this.config?.databases || [];
927
+
928
+ for (const dbSelection of databaseSelections) {
929
+ // First try to find on server
930
+ const serverDb = serverDatabases.find(db => db.$id === dbSelection.databaseId);
931
+
932
+ if (serverDb) {
933
+ selectedDatabases.push(serverDb);
934
+ MessageFormatter.info(`Selected database: ${serverDb.name} (${serverDb.$id})`, { prefix: "Controller" });
935
+ } else {
936
+ // Database doesn't exist on server - check if it's in local config
937
+ const configDb = configuredDatabases.find((db: any) => db.$id === dbSelection.databaseId);
938
+
939
+ if (configDb) {
940
+ // Create a pseudo-database object that ensureDatabasesExist will create
941
+ const dbId = configDb.$id;
942
+ selectedDatabases.push({
943
+ $id: dbId,
944
+ name: configDb.name || dbId,
945
+ $createdAt: new Date().toISOString(),
946
+ $updatedAt: new Date().toISOString(),
947
+ enabled: true,
948
+ } as Models.Database);
949
+ MessageFormatter.info(`Selected database: ${configDb.name || dbId} (${dbId}) [will be created]`, { prefix: "Controller" });
950
+ } else {
951
+ MessageFormatter.warning(`Database with ID ${dbSelection.databaseId} not found in server or local config`, { prefix: "Controller" });
952
+ continue;
953
+ }
954
+ }
955
+
956
+ // Log selected tables for this database
957
+ if (dbSelection.tableIds && dbSelection.tableIds.length > 0) {
958
+ MessageFormatter.info(` Tables: ${dbSelection.tableIds.join(', ')}`, { prefix: "Controller" });
959
+ }
960
+ }
961
+
962
+ if (selectedDatabases.length === 0 && (!bucketSelections || bucketSelections.length === 0)) {
963
+ MessageFormatter.warning("No valid databases or buckets selected for push", { prefix: "Controller" });
964
+ return;
965
+ }
966
+
967
+ // Push global/root-level buckets if any were selected
968
+ if (bucketSelections && bucketSelections.length > 0) {
969
+ MessageFormatter.info(`Selected ${bucketSelections.length} buckets:`, { prefix: "Controller" });
970
+ for (const bucketSelection of bucketSelections) {
971
+ const dbInfo = bucketSelection.databaseId ? ` (DB: ${bucketSelection.databaseId})` : '';
972
+ MessageFormatter.info(` - ${bucketSelection.bucketName} (${bucketSelection.bucketId})${dbInfo}`, { prefix: "Controller" });
973
+ }
974
+ const selectedGlobalBucketIds = bucketSelections.map(bs => bs.bucketId);
975
+ await this.pushGlobalBuckets(selectedGlobalBucketIds);
976
+ }
977
+
978
+ // Database + tables push
979
+ if (selectedDatabases.length > 0) {
980
+ const databaseCollectionsMap = new Map<string, any[]>();
981
+
982
+ const allCollections = [
983
+ ...(this.config?.collections || []),
984
+ ...(this.config?.tables || [])
985
+ ];
986
+
987
+ for (const dbSelection of databaseSelections) {
988
+ const collectionsForDatabase: any[] = [];
989
+
990
+ for (const collection of allCollections) {
991
+ const collectionId = collection.$id || (collection as any).id;
992
+ if (dbSelection.tableIds.includes(collectionId)) {
993
+ collectionsForDatabase.push(collection);
994
+ const source = (collection as any)._isFromTablesDir ? 'tables/' : 'collections/';
995
+ MessageFormatter.info(` - Selected: ${collection.name || collectionId} → ${dbSelection.databaseId} [${source}]`, { prefix: "Controller" });
996
+ }
997
+ }
998
+
999
+ databaseCollectionsMap.set(dbSelection.databaseId, collectionsForDatabase);
1000
+ }
1001
+
1002
+ const totalSelectedCollections = Array.from(databaseCollectionsMap.values())
1003
+ .reduce((total, collections) => total + collections.length, 0);
1004
+
1005
+ MessageFormatter.info(`Pushing ${totalSelectedCollections} selected tables to ${databaseCollectionsMap.size} databases`, { prefix: "Controller" });
1006
+
1007
+ await this.ensureDatabasesExist(selectedDatabases);
1008
+ await this.ensureDatabaseConfigBucketsExist(selectedDatabases);
1009
+
1010
+ for (const database of selectedDatabases) {
1011
+ const collectionsForThisDatabase = databaseCollectionsMap.get(database.$id) || [];
1012
+ if (collectionsForThisDatabase.length > 0) {
1013
+ MessageFormatter.info(`Pushing ${collectionsForThisDatabase.length} tables to database ${database.$id} (${database.name})`, { prefix: "Controller" });
1014
+ await this.createOrUpdateCollections(database, undefined, collectionsForThisDatabase);
1015
+ } else {
1016
+ MessageFormatter.info(`No tables selected for database ${database.$id} (${database.name})`, { prefix: "Controller" });
1017
+ }
1018
+ }
1019
+ }
1020
+
1021
+ MessageFormatter.success("Selective push completed successfully! Local config pushed to Appwrite.", { prefix: "Controller" });
1022
+ }
1023
+
1024
+ async syncDb(
1025
+ databases: Models.Database[] = [],
1026
+ collections: Models.Collection[] = []
1027
+ ) {
1028
+ await this.init();
1029
+ if (!this.database) {
1030
+ MessageFormatter.error("Database not initialized", undefined, { prefix: "Controller" });
1031
+ return;
1032
+ }
1033
+ if (databases.length === 0) {
1034
+ const allDatabases = await fetchAllDatabases(this.database);
1035
+ databases = allDatabases;
1036
+ }
1037
+ // Ensure DBs exist
1038
+ await this.ensureDatabasesExist(databases);
1039
+ await this.ensureDatabaseConfigBucketsExist(databases);
1040
+
1041
+ await this.createOrUpdateCollectionsForDatabases(databases, collections);
1042
+ }
1043
+
1044
+ getAppwriteFolderPath() {
1045
+ return this.appwriteFolderPath;
1046
+ }
1047
+
1048
+ async transferData(options: TransferOptions): Promise<void> {
1049
+ let sourceClient = this.database;
1050
+ let targetClient: Databases | undefined;
1051
+ let sourceDatabases: Models.Database[] = [];
1052
+ let targetDatabases: Models.Database[] = [];
1053
+
1054
+ if (!sourceClient) {
1055
+ MessageFormatter.error("Source database not initialized", undefined, { prefix: "Controller" });
1056
+ return;
1057
+ }
1058
+
1059
+ if (options.isRemote) {
1060
+ if (
1061
+ !options.transferEndpoint ||
1062
+ !options.transferProject ||
1063
+ !options.transferKey
1064
+ ) {
1065
+ MessageFormatter.error("Remote transfer options are missing", undefined, { prefix: "Controller" });
1066
+ return;
1067
+ }
1068
+
1069
+ const remoteClient = getClient(
1070
+ options.transferEndpoint,
1071
+ options.transferProject,
1072
+ options.transferKey
1073
+ );
1074
+
1075
+ targetClient = new Databases(remoteClient);
1076
+ sourceDatabases = await fetchAllDatabases(sourceClient);
1077
+ targetDatabases = await fetchAllDatabases(targetClient);
1078
+ } else {
1079
+ targetClient = sourceClient;
1080
+ sourceDatabases = targetDatabases = await fetchAllDatabases(sourceClient);
1081
+ }
1082
+
1083
+ // Always perform database transfer if databases are specified
1084
+ if (options.fromDb && options.targetDb) {
1085
+ const fromDb = sourceDatabases.find(
1086
+ (db) => db.$id === options.fromDb!.$id
1087
+ );
1088
+ const targetDb = targetDatabases.find(
1089
+ (db) => db.$id === options.targetDb!.$id
1090
+ );
1091
+
1092
+ if (!fromDb || !targetDb) {
1093
+ MessageFormatter.error("Source or target database not found", undefined, { prefix: "Controller" });
1094
+ return;
1095
+ }
1096
+
1097
+ if (options.isRemote && targetClient) {
1098
+ await transferDatabaseLocalToRemote(
1099
+ sourceClient,
1100
+ options.transferEndpoint!,
1101
+ options.transferProject!,
1102
+ options.transferKey!,
1103
+ fromDb.$id,
1104
+ targetDb.$id,
1105
+ options.collections
1106
+ );
1107
+ } else {
1108
+ await transferDatabaseLocalToLocal(
1109
+ sourceClient,
1110
+ fromDb.$id,
1111
+ targetDb.$id,
1112
+ options.collections,
1113
+ this.adapter
1114
+ );
1115
+ }
1116
+ }
1117
+
1118
+ if (options.transferUsers) {
1119
+ if (!options.isRemote) {
1120
+ MessageFormatter.warning(
1121
+ "User transfer is only supported for remote transfers. Skipping...",
1122
+ { prefix: "Controller" }
1123
+ );
1124
+ } else if (!this.appwriteServer) {
1125
+ MessageFormatter.error("Appwrite server not initialized", undefined, { prefix: "Controller" });
1126
+ return;
1127
+ } else {
1128
+ MessageFormatter.progress("Starting user transfer...", { prefix: "Transfer" });
1129
+ const localUsers = new Users(this.appwriteServer);
1130
+ await transferUsersLocalToRemote(
1131
+ localUsers,
1132
+ options.transferEndpoint!,
1133
+ options.transferProject!,
1134
+ options.transferKey!
1135
+ );
1136
+ MessageFormatter.success("User transfer completed", { prefix: "Transfer" });
1137
+ }
1138
+ }
1139
+
1140
+ // Handle storage transfer
1141
+ if (this.storage && (options.sourceBucket || options.fromDb)) {
1142
+ const sourceBucketId =
1143
+ options.sourceBucket?.$id ||
1144
+ (options.fromDb &&
1145
+ this.config?.documentBucketId &&
1146
+ `${this.config.documentBucketId}_${options.fromDb.$id
1147
+ .toLowerCase()
1148
+ .trim()
1149
+ .replace(/\s+/g, "")}`);
1150
+
1151
+ const targetBucketId =
1152
+ options.targetBucket?.$id ||
1153
+ (options.targetDb &&
1154
+ this.config?.documentBucketId &&
1155
+ `${this.config.documentBucketId}_${options.targetDb.$id
1156
+ .toLowerCase()
1157
+ .trim()
1158
+ .replace(/\s+/g, "")}`);
1159
+
1160
+ if (sourceBucketId && targetBucketId) {
1161
+ MessageFormatter.progress(
1162
+ `Starting storage transfer from ${sourceBucketId} to ${targetBucketId}`,
1163
+ { prefix: "Transfer" }
1164
+ );
1165
+
1166
+ if (options.isRemote) {
1167
+ await transferStorageLocalToRemote(
1168
+ this.storage,
1169
+ options.transferEndpoint!,
1170
+ options.transferProject!,
1171
+ options.transferKey!,
1172
+ sourceBucketId,
1173
+ targetBucketId
1174
+ );
1175
+ } else {
1176
+ await transferStorageLocalToLocal(
1177
+ this.storage,
1178
+ sourceBucketId,
1179
+ targetBucketId
1180
+ );
1181
+ }
1182
+ }
1183
+ }
1184
+
1185
+ MessageFormatter.success("Transfer completed", { prefix: "Transfer" });
1186
+ }
1187
+
1188
+ async updateFunctionSpecifications(
1189
+ functionId: string,
1190
+ specification: Specification
1191
+ ) {
1192
+ await this.init();
1193
+ if (!this.appwriteServer)
1194
+ throw new Error("Appwrite server not initialized");
1195
+ MessageFormatter.progress(
1196
+ `Updating function specifications for ${functionId} to ${specification}`,
1197
+ { prefix: "Functions" }
1198
+ );
1199
+ await updateFunctionSpecifications(
1200
+ this.appwriteServer,
1201
+ functionId,
1202
+ specification
1203
+ );
1204
+ MessageFormatter.success(
1205
+ `Successfully updated function specifications for ${functionId} to ${specification}`,
1206
+ { prefix: "Functions" }
1207
+ );
1208
+ }
1209
+
1210
+ /**
1211
+ * Validates the current configuration for collections/tables conflicts
1212
+ */
1213
+ async validateConfiguration(strictMode: boolean = false): Promise<ValidationResult> {
1214
+ await this.init();
1215
+ if (!this.config) {
1216
+ throw new Error("Configuration not loaded");
1217
+ }
1218
+
1219
+ MessageFormatter.progress("Validating configuration...", { prefix: "Validation" });
1220
+
1221
+ const validation = strictMode
1222
+ ? validateWithStrictMode(this.config, strictMode)
1223
+ : validateCollectionsTablesConfig(this.config);
1224
+
1225
+ reportValidationResults(validation, { verbose: true });
1226
+
1227
+ if (validation.isValid) {
1228
+ MessageFormatter.success("Configuration validation passed", { prefix: "Validation" });
1229
+ } else {
1230
+ MessageFormatter.error(`Configuration validation failed with ${validation.errors.length} errors`, undefined, { prefix: "Validation" });
1231
+ }
1232
+
1233
+ return validation;
1234
+ }
1235
+
1236
+ /**
1237
+ * Get current session information for debugging/logging purposes
1238
+ * Delegates to ConfigManager for session info
1239
+ */
1240
+ public async getSessionInfo(): Promise<{
1241
+ hasSession: boolean;
1242
+ authMethod?: string;
1243
+ email?: string;
1244
+ expiresAt?: string;
1245
+ }> {
1246
+ const configManager = ConfigManager.getInstance();
1247
+
1248
+ try {
1249
+ const authStatus = await configManager.getAuthStatus();
1250
+ return {
1251
+ hasSession: authStatus.hasValidSession,
1252
+ authMethod: authStatus.authMethod,
1253
+ email: authStatus.sessionInfo?.email,
1254
+ expiresAt: authStatus.sessionInfo?.expiresAt
1255
+ };
1256
+ } catch (error) {
1257
+ // If config not loaded, return empty status
1258
+ return {
1259
+ hasSession: false
1260
+ };
1261
+ }
1262
+ }
1263
+ }