appwrite-utils-cli 1.9.6 → 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 (426) 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 -44
  23. package/src/collections/indexes.ts +350 -352
  24. package/src/collections/methods.ts +714 -815
  25. package/src/collections/tableOperations.ts +57 -21
  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 +409 -0
  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 -405
  129. package/dist/adapters/DatabaseAdapter.d.ts +0 -242
  130. package/dist/adapters/DatabaseAdapter.js +0 -50
  131. package/dist/adapters/LegacyAdapter.d.ts +0 -50
  132. package/dist/adapters/LegacyAdapter.js +0 -612
  133. package/dist/adapters/TablesDBAdapter.d.ts +0 -45
  134. package/dist/adapters/TablesDBAdapter.js +0 -596
  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 -1364
  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 -734
  167. package/dist/collections/tableOperations.d.ts +0 -86
  168. package/dist/collections/tableOperations.js +0 -434
  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 -625
  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/indexManager.d.ts +0 -24
  298. package/dist/shared/indexManager.js +0 -151
  299. package/dist/shared/jsonSchemaGenerator.d.ts +0 -50
  300. package/dist/shared/jsonSchemaGenerator.js +0 -290
  301. package/dist/shared/logging.d.ts +0 -61
  302. package/dist/shared/logging.js +0 -116
  303. package/dist/shared/messageFormatter.d.ts +0 -39
  304. package/dist/shared/messageFormatter.js +0 -162
  305. package/dist/shared/migrationHelpers.d.ts +0 -61
  306. package/dist/shared/migrationHelpers.js +0 -145
  307. package/dist/shared/operationLogger.d.ts +0 -10
  308. package/dist/shared/operationLogger.js +0 -12
  309. package/dist/shared/operationQueue.d.ts +0 -40
  310. package/dist/shared/operationQueue.js +0 -311
  311. package/dist/shared/operationsTable.d.ts +0 -26
  312. package/dist/shared/operationsTable.js +0 -286
  313. package/dist/shared/operationsTableSchema.d.ts +0 -48
  314. package/dist/shared/operationsTableSchema.js +0 -35
  315. package/dist/shared/progressManager.d.ts +0 -62
  316. package/dist/shared/progressManager.js +0 -215
  317. package/dist/shared/pydanticModelGenerator.d.ts +0 -17
  318. package/dist/shared/pydanticModelGenerator.js +0 -615
  319. package/dist/shared/relationshipExtractor.d.ts +0 -56
  320. package/dist/shared/relationshipExtractor.js +0 -138
  321. package/dist/shared/schemaGenerator.d.ts +0 -40
  322. package/dist/shared/schemaGenerator.js +0 -556
  323. package/dist/shared/selectionDialogs.d.ts +0 -214
  324. package/dist/shared/selectionDialogs.js +0 -544
  325. package/dist/storage/backupCompression.d.ts +0 -20
  326. package/dist/storage/backupCompression.js +0 -67
  327. package/dist/storage/methods.d.ts +0 -32
  328. package/dist/storage/methods.js +0 -472
  329. package/dist/storage/schemas.d.ts +0 -842
  330. package/dist/storage/schemas.js +0 -175
  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 -510
  378. package/src/adapters/DatabaseAdapter.ts +0 -318
  379. package/src/adapters/LegacyAdapter.ts +0 -841
  380. package/src/adapters/TablesDBAdapter.ts +0 -815
  381. package/src/config/ConfigManager.ts +0 -817
  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/indexManager.ts +0 -254
  405. package/src/shared/jsonSchemaGenerator.ts +0 -383
  406. package/src/shared/logging.ts +0 -149
  407. package/src/shared/messageFormatter.ts +0 -208
  408. package/src/shared/pydanticModelGenerator.ts +0 -618
  409. package/src/shared/schemaGenerator.ts +0 -644
  410. package/src/utils/ClientFactory.ts +0 -240
  411. package/src/utils/configDiscovery.ts +0 -557
  412. package/src/utils/constantsGenerator.ts +0 -369
  413. package/src/utils/dataConverters.ts +0 -159
  414. package/src/utils/directoryUtils.ts +0 -61
  415. package/src/utils/getClientFromConfig.ts +0 -257
  416. package/src/utils/helperFunctions.ts +0 -228
  417. package/src/utils/pathResolvers.ts +0 -81
  418. package/src/utils/projectConfig.ts +0 -340
  419. package/src/utils/retryFailedPromises.ts +0 -29
  420. package/src/utils/sessionAuth.ts +0 -230
  421. package/src/utils/typeGuards.ts +0 -65
  422. package/src/utils/validationRules.ts +0 -88
  423. package/src/utils/versionDetection.ts +0 -292
  424. package/src/utils/yamlConverter.ts +0 -542
  425. package/src/utils/yamlLoader.ts +0 -371
  426. package/tmp-sync-test/.appwrite/collections/TestCollection.yaml +0 -7
@@ -1,188 +1,201 @@
1
- import inquirer from "inquirer";
2
- import { UtilsController } from "./utilsController.js";
3
- import { fetchAllCollections } from "./collections/methods.js";
4
- import { listBuckets, createBucket } from "./storage/methods.js";
5
- import {
6
- Databases,
7
- Storage,
8
- Client,
9
- type Models,
10
- Compression,
11
- Query,
12
- Functions,
13
- DatabaseType,
14
- } from "node-appwrite";
15
- import {
16
- PermissionToAppwritePermission,
17
- RuntimeSchema,
18
- permissionSchema,
19
- type AppwriteConfig,
20
- type AppwriteFunction,
21
- type ConfigDatabases,
22
- type Runtime,
23
- type Specification,
24
- type FunctionScope,
25
- } from "appwrite-utils";
26
- import { ulid } from "ulidx";
27
- import chalk from "chalk";
28
- import { DateTime } from "luxon";
29
- import {
30
- getFunction,
31
- downloadLatestFunctionDeployment,
32
- listFunctions,
33
- } from "./functions/methods.js";
34
- import { join } from "node:path";
35
- import path from "path";
36
- import fs from "node:fs";
37
- import os from "node:os";
38
- import { MessageFormatter } from "./shared/messageFormatter.js";
39
- import { findAppwriteConfig } from "./utils/loadConfigs.js";
40
- import { findYamlConfig } from "./config/yamlConfig.js";
41
-
42
- // Import command modules
43
- import { configCommands } from "./cli/commands/configCommands.js";
44
- import { databaseCommands } from "./cli/commands/databaseCommands.js";
1
+ import inquirer from "inquirer";
2
+ import { UtilsController } from "./utilsController.js";
3
+ import { fetchAllCollections } from "./collections/methods.js";
4
+ import { listBuckets, createBucket } from "./storage/methods.js";
5
+ import {
6
+ Databases,
7
+ Storage,
8
+ Client,
9
+ type Models,
10
+ Compression,
11
+ Query,
12
+ Functions,
13
+ DatabaseType,
14
+ } from "node-appwrite";
15
+ import {
16
+ PermissionToAppwritePermission,
17
+ RuntimeSchema,
18
+ permissionSchema,
19
+ type AppwriteConfig,
20
+ type AppwriteFunction,
21
+ type ConfigDatabases,
22
+ type Runtime,
23
+ type Specification,
24
+ type FunctionScope,
25
+ } from "appwrite-utils";
26
+ import { ulid } from "ulidx";
27
+ import chalk from "chalk";
28
+ import { DateTime } from "luxon";
29
+ import {
30
+ getFunction,
31
+ downloadLatestFunctionDeployment,
32
+ listFunctions,
33
+ } from "./functions/methods.js";
34
+ import { join } from "node:path";
35
+ import path from "path";
36
+ import fs from "node:fs";
37
+ import os from "node:os";
38
+ import { MessageFormatter, findYamlConfig } from "appwrite-utils-helpers";
39
+ import { findAppwriteConfig } from "./utils/loadConfigs.js";
40
+
41
+ // Import command modules
42
+ import { configCommands } from "./cli/commands/configCommands.js";
43
+ import { databaseCommands } from "./cli/commands/databaseCommands.js";
45
44
  import { functionCommands } from "./cli/commands/functionCommands.js";
46
45
  import { storageCommands } from "./cli/commands/storageCommands.js";
47
- import { transferCommands } from "./cli/commands/transferCommands.js";
48
- import { schemaCommands } from "./cli/commands/schemaCommands.js";
49
-
46
+ import { transferCommands } from "./cli/commands/transferCommands.js";
47
+ import { schemaCommands } from "./cli/commands/schemaCommands.js";
48
+ import { importFileCommands } from "./cli/commands/importFileCommands.js";
49
+
50
50
  enum CHOICES {
51
- MIGRATE_CONFIG = "🔄 Migrate TypeScript config to YAML (.appwrite structure)",
52
- VALIDATE_CONFIG = "✅ Validate configuration (collections/tables conflicts)",
53
- MIGRATE_COLLECTIONS_TO_TABLES = "🔀 Migrate collections to tables format",
54
- CREATE_COLLECTION_CONFIG = "📄 Create collection config file",
55
- CREATE_FUNCTION = "⚡ Create a new function, from scratch or using a template",
56
- DEPLOY_FUNCTION = "🚀 Deploy function(s)",
57
- DELETE_FUNCTION = "🗑️ Delete function",
58
- SETUP_DIRS_FILES = "📁 Setup directories and files",
59
- SETUP_DIRS_FILES_WITH_EXAMPLE_DATA = "📁✨ Setup directories and files with example data",
60
- SYNC_DB = "⬆️ Push local config to Appwrite",
61
- SYNCHRONIZE_CONFIGURATIONS = "🔄 Synchronize configurations - Pull from Appwrite and write to local config",
62
- TRANSFER_DATA = "📦 Transfer data",
63
- COMPREHENSIVE_TRANSFER = "🚀 Comprehensive transfer (users → databases → buckets → functions)",
64
- BACKUP_DATABASE = "💾 Backup database",
65
- WIPE_DATABASE = "🧹 Wipe database",
66
- WIPE_COLLECTIONS = "🧹 Wipe collections",
67
- GENERATE_SCHEMAS = "🏗️ Generate schemas",
68
- GENERATE_CONSTANTS = "📋 Generate cross-language constants (TypeScript, Python, PHP, Dart, etc.)",
69
- IMPORT_DATA = "📥 Import data",
70
- RELOAD_CONFIG = "🔄 Reload configuration files",
51
+ MIGRATE_CONFIG = "🔄 Migrate TypeScript config to YAML (.appwrite structure)",
52
+ VALIDATE_CONFIG = "✅ Validate configuration (collections/tables conflicts)",
53
+ MIGRATE_COLLECTIONS_TO_TABLES = "🔀 Migrate collections to tables format",
54
+ CREATE_COLLECTION_CONFIG = "📄 Create collection config file",
55
+ CREATE_FUNCTION = "⚡ Create a new function, from scratch or using a template",
56
+ DEPLOY_FUNCTION = "🚀 Deploy function(s)",
57
+ DELETE_FUNCTION = "🗑️ Delete function",
58
+ SETUP_DIRS_FILES = "📁 Setup directories and files",
59
+ SETUP_DIRS_FILES_WITH_EXAMPLE_DATA = "📁✨ Setup directories and files with example data",
60
+ SYNC_DB = "⬆️ Push local config to Appwrite",
61
+ SYNCHRONIZE_CONFIGURATIONS = "🔄 Synchronize configurations - Pull from Appwrite and write to local config",
62
+ TRANSFER_DATA = "📦 Transfer data",
63
+ COMPREHENSIVE_TRANSFER = "🚀 Comprehensive transfer (users → databases → buckets → functions)",
64
+ BACKUP_DATABASE = "💾 Backup database",
65
+ WIPE_DATABASE = "🧹 Wipe database",
66
+ WIPE_COLLECTIONS = "🧹 Wipe tables",
67
+ GENERATE_SCHEMAS = "🏗️ Generate schemas",
68
+ GENERATE_CONSTANTS = "📋 Generate cross-language constants (TypeScript, Python, PHP, Dart, etc.)",
69
+ IMPORT_DATA = "📥 Import data",
70
+ IMPORT_FILE = "📄 Import file (CSV/JSON) directly into a table",
71
+ RELOAD_CONFIG = "🔄 Reload configuration files",
71
72
  UPDATE_FUNCTION_SPEC = "⚙️ Update function specifications",
72
73
  MANAGE_BUCKETS = "🪣 Manage storage buckets",
73
74
  EXIT = "👋 Exit",
74
75
  }
75
-
76
+
77
+ export interface InteractiveCLIOptions {
78
+ useSession?: boolean;
79
+ sessionCookie?: string;
80
+ }
81
+
76
82
  export class InteractiveCLI {
77
83
  private controller: UtilsController | undefined;
78
84
  private isUsingTypeScriptConfig: boolean = false;
79
85
  private lastSelectedCollectionIds: string[] = [];
80
-
81
- constructor(private currentDir: string) {}
82
-
83
- async run(): Promise<void> {
84
- MessageFormatter.banner(
85
- "Appwrite Utils CLI",
86
- "Welcome to Appwrite Utils CLI Tool by Zach Handley"
87
- );
88
- MessageFormatter.info(
89
- "For more information, visit https://github.com/zachhandley/AppwriteUtils"
90
- );
91
-
92
- // Detect configuration type
93
- try {
94
- await this.detectConfigurationType();
95
- } catch (error) {
96
- // Continue if detection fails
97
- this.isUsingTypeScriptConfig = false;
98
- }
99
-
100
- while (true) {
101
- // Build choices array dynamically based on config type
102
- const choices = this.buildChoicesList();
103
-
104
- const { action } = await inquirer.prompt([
105
- {
106
- type: "list",
107
- name: "action",
108
- message: chalk.yellow("What would you like to do?"),
109
- choices,
110
- },
111
- ]);
112
-
113
- switch (action) {
114
- case CHOICES.MIGRATE_CONFIG:
115
- await configCommands.migrateTypeScriptConfig(this);
116
- break;
117
- case CHOICES.VALIDATE_CONFIG:
118
- await configCommands.validateConfiguration(this);
119
- break;
120
- case CHOICES.MIGRATE_COLLECTIONS_TO_TABLES:
121
- await configCommands.migrateCollectionsToTables(this);
122
- break;
123
- case CHOICES.CREATE_COLLECTION_CONFIG:
124
- await configCommands.createCollectionConfig(this);
125
- break;
126
- case CHOICES.CREATE_FUNCTION:
127
- await this.initControllerIfNeeded();
128
- await functionCommands.createFunction(this);
129
- break;
130
- case CHOICES.DEPLOY_FUNCTION:
131
- await this.initControllerIfNeeded();
132
- await functionCommands.deployFunction(this);
133
- break;
134
- case CHOICES.DELETE_FUNCTION:
135
- await this.initControllerIfNeeded();
136
- await functionCommands.deleteFunction(this);
137
- break;
138
- case CHOICES.SETUP_DIRS_FILES:
139
- await schemaCommands.setupDirsFiles(this, false);
140
- break;
141
- case CHOICES.SETUP_DIRS_FILES_WITH_EXAMPLE_DATA:
142
- await schemaCommands.setupDirsFiles(this, true);
143
- break;
144
- case CHOICES.SYNCHRONIZE_CONFIGURATIONS:
145
- await this.initControllerIfNeeded();
146
- await databaseCommands.synchronizeConfigurations(this);
147
- break;
148
- case CHOICES.SYNC_DB:
149
- await this.initControllerIfNeeded();
150
- await databaseCommands.syncDb(this);
151
- break;
152
- case CHOICES.TRANSFER_DATA:
153
- await this.initControllerIfNeeded();
154
- await transferCommands.transferData(this);
155
- break;
156
- case CHOICES.COMPREHENSIVE_TRANSFER:
157
- await transferCommands.comprehensiveTransfer(this);
158
- break;
159
- case CHOICES.BACKUP_DATABASE:
160
- await this.initControllerIfNeeded();
161
- await databaseCommands.backupDatabase(this);
162
- break;
163
- case CHOICES.WIPE_DATABASE:
164
- await this.initControllerIfNeeded();
165
- await databaseCommands.wipeDatabase(this);
166
- break;
167
- case CHOICES.WIPE_COLLECTIONS:
168
- await this.initControllerIfNeeded();
169
- await databaseCommands.wipeCollections(this);
170
- break;
171
- case CHOICES.GENERATE_SCHEMAS:
172
- await this.initControllerIfNeeded();
173
- await schemaCommands.generateSchemas(this);
174
- break;
175
- case CHOICES.GENERATE_CONSTANTS:
176
- await this.initControllerIfNeeded();
177
- await schemaCommands.generateConstants(this);
178
- break;
179
- case CHOICES.IMPORT_DATA:
180
- await this.initControllerIfNeeded();
181
- await schemaCommands.importData(this);
182
- break;
183
- case CHOICES.RELOAD_CONFIG:
184
- await configCommands.reloadConfigWithSessionPreservation(this);
185
- break;
86
+ private options: InteractiveCLIOptions;
87
+
88
+ constructor(private currentDir: string, options: InteractiveCLIOptions = {}) {
89
+ this.options = options;
90
+ }
91
+
92
+ async run(): Promise<void> {
93
+ MessageFormatter.banner(
94
+ "Appwrite Utils CLI",
95
+ "Welcome to Appwrite Utils CLI Tool by Zach Handley"
96
+ );
97
+ MessageFormatter.info(
98
+ "For more information, visit https://github.com/zachhandley/AppwriteUtils"
99
+ );
100
+
101
+ // Detect configuration type
102
+ try {
103
+ await this.detectConfigurationType();
104
+ } catch (error) {
105
+ // Continue if detection fails
106
+ this.isUsingTypeScriptConfig = false;
107
+ }
108
+
109
+ while (true) {
110
+ // Build choices array dynamically based on config type
111
+ const choices = this.buildChoicesList();
112
+
113
+ const { action } = await inquirer.prompt([
114
+ {
115
+ type: "list",
116
+ name: "action",
117
+ message: chalk.yellow("What would you like to do?"),
118
+ choices,
119
+ },
120
+ ]);
121
+
122
+ switch (action) {
123
+ case CHOICES.MIGRATE_CONFIG:
124
+ await configCommands.migrateTypeScriptConfig(this);
125
+ break;
126
+ case CHOICES.VALIDATE_CONFIG:
127
+ await configCommands.validateConfiguration(this);
128
+ break;
129
+ case CHOICES.MIGRATE_COLLECTIONS_TO_TABLES:
130
+ await configCommands.migrateCollectionsToTables(this);
131
+ break;
132
+ case CHOICES.CREATE_COLLECTION_CONFIG:
133
+ await configCommands.createCollectionConfig(this);
134
+ break;
135
+ case CHOICES.CREATE_FUNCTION:
136
+ await this.initControllerIfNeeded();
137
+ await functionCommands.createFunction(this);
138
+ break;
139
+ case CHOICES.DEPLOY_FUNCTION:
140
+ await this.initControllerIfNeeded();
141
+ await functionCommands.deployFunction(this);
142
+ break;
143
+ case CHOICES.DELETE_FUNCTION:
144
+ await this.initControllerIfNeeded();
145
+ await functionCommands.deleteFunction(this);
146
+ break;
147
+ case CHOICES.SETUP_DIRS_FILES:
148
+ await schemaCommands.setupDirsFiles(this, false);
149
+ break;
150
+ case CHOICES.SETUP_DIRS_FILES_WITH_EXAMPLE_DATA:
151
+ await schemaCommands.setupDirsFiles(this, true);
152
+ break;
153
+ case CHOICES.SYNCHRONIZE_CONFIGURATIONS:
154
+ await this.initControllerIfNeeded();
155
+ await databaseCommands.synchronizeConfigurations(this);
156
+ break;
157
+ case CHOICES.SYNC_DB:
158
+ await this.initControllerIfNeeded();
159
+ await databaseCommands.syncDb(this);
160
+ break;
161
+ case CHOICES.TRANSFER_DATA:
162
+ await this.initControllerIfNeeded();
163
+ await transferCommands.transferData(this);
164
+ break;
165
+ case CHOICES.COMPREHENSIVE_TRANSFER:
166
+ await transferCommands.comprehensiveTransfer(this);
167
+ break;
168
+ case CHOICES.BACKUP_DATABASE:
169
+ await this.initControllerIfNeeded();
170
+ await databaseCommands.backupDatabase(this);
171
+ break;
172
+ case CHOICES.WIPE_DATABASE:
173
+ await this.initControllerIfNeeded();
174
+ await databaseCommands.wipeDatabase(this);
175
+ break;
176
+ case CHOICES.WIPE_COLLECTIONS:
177
+ await this.initControllerIfNeeded();
178
+ await databaseCommands.wipeCollections(this);
179
+ break;
180
+ case CHOICES.GENERATE_SCHEMAS:
181
+ await this.initControllerIfNeeded();
182
+ await schemaCommands.generateSchemas(this);
183
+ break;
184
+ case CHOICES.GENERATE_CONSTANTS:
185
+ await this.initControllerIfNeeded();
186
+ await schemaCommands.generateConstants(this);
187
+ break;
188
+ case CHOICES.IMPORT_DATA:
189
+ await this.initControllerIfNeeded();
190
+ await schemaCommands.importData(this);
191
+ break;
192
+ case CHOICES.IMPORT_FILE:
193
+ await this.initControllerIfNeeded();
194
+ await importFileCommands.importFile(this);
195
+ break;
196
+ case CHOICES.RELOAD_CONFIG:
197
+ await configCommands.reloadConfigWithSessionPreservation(this);
198
+ break;
186
199
  case CHOICES.UPDATE_FUNCTION_SPEC:
187
200
  await this.initControllerIfNeeded();
188
201
  await functionCommands.updateFunctionSpec(this);
@@ -190,44 +203,53 @@ export class InteractiveCLI {
190
203
  case CHOICES.MANAGE_BUCKETS:
191
204
  await this.manageBuckets();
192
205
  break;
193
- case CHOICES.EXIT:
194
- MessageFormatter.success("Goodbye!");
195
- process.exit(0);
196
- }
197
- }
198
- }
199
-
206
+ case CHOICES.EXIT:
207
+ MessageFormatter.success("Goodbye!");
208
+ process.exit(0);
209
+ }
210
+ }
211
+ }
212
+
200
213
  private async initControllerIfNeeded(directConfig?: {
201
- appwriteEndpoint: string;
202
- appwriteProject: string;
203
- appwriteKey: string;
204
- }): Promise<void> {
205
- if (!this.controller) {
206
- this.controller = UtilsController.getInstance(this.currentDir, directConfig);
207
- await this.controller.init();
208
- } else {
209
- // Extract session info from existing controller before reinitializing
210
- const sessionInfo = await this.controller.getSessionInfo();
211
- if (sessionInfo.hasSession && directConfig) {
212
- // Create enhanced directConfig with session preservation
213
- const enhancedDirectConfig = {
214
- ...directConfig,
215
- sessionCookie: (this.controller as any).sessionCookie,
216
- sessionMetadata: (this.controller as any).sessionMetadata
217
- };
218
-
219
- // Reinitialize with session preservation
220
- UtilsController.clearInstance();
221
- this.controller = UtilsController.getInstance(this.currentDir, enhancedDirectConfig);
222
- await this.controller.init();
223
- } else if (directConfig) {
224
- // Standard reinitialize without session
225
- UtilsController.clearInstance();
226
- this.controller = UtilsController.getInstance(this.currentDir, directConfig);
227
- await this.controller.init();
228
- }
229
- // If no directConfig provided, keep existing controller
230
- }
214
+ appwriteEndpoint: string;
215
+ appwriteProject: string;
216
+ appwriteKey: string;
217
+ }): Promise<void> {
218
+ if (!this.controller) {
219
+ this.controller = UtilsController.getInstance(this.currentDir, directConfig);
220
+ await this.controller.init({
221
+ useSession: this.options.useSession,
222
+ sessionCookie: this.options.sessionCookie
223
+ });
224
+ } else {
225
+ // Extract session info from existing controller before reinitializing
226
+ const sessionInfo = await this.controller.getSessionInfo();
227
+ if (sessionInfo.hasSession && directConfig) {
228
+ // Create enhanced directConfig with session preservation
229
+ const enhancedDirectConfig = {
230
+ ...directConfig,
231
+ sessionCookie: (this.controller as any).sessionCookie,
232
+ sessionMetadata: (this.controller as any).sessionMetadata
233
+ };
234
+
235
+ // Reinitialize with session preservation
236
+ UtilsController.clearInstance();
237
+ this.controller = UtilsController.getInstance(this.currentDir, enhancedDirectConfig);
238
+ await this.controller.init({
239
+ useSession: this.options.useSession,
240
+ sessionCookie: this.options.sessionCookie
241
+ });
242
+ } else if (directConfig) {
243
+ // Standard reinitialize without session
244
+ UtilsController.clearInstance();
245
+ this.controller = UtilsController.getInstance(this.currentDir, directConfig);
246
+ await this.controller.init({
247
+ useSession: this.options.useSession,
248
+ sessionCookie: this.options.sessionCookie
249
+ });
250
+ }
251
+ // If no directConfig provided, keep existing controller
252
+ }
231
253
  }
232
254
 
233
255
  private async manageBuckets(): Promise<void> {
@@ -254,207 +276,247 @@ export class InteractiveCLI {
254
276
  }
255
277
  }
256
278
  }
257
-
258
- private async selectDatabases(
259
- databases: Models.Database[],
260
- message: string,
261
- multiSelect = true
262
- ): Promise<Models.Database[]> {
263
- await this.initControllerIfNeeded();
264
- const configDatabases = this.getLocalDatabases();
265
- const allDatabases = [...databases, ...configDatabases]
266
- .reduce((acc, db) => {
267
- // Local config takes precedence - if a database with same name or ID exists, use local version
268
- const existingIndex = acc.findIndex((d) => d.name === db.name || d.$id === db.$id);
269
- if (existingIndex >= 0) {
270
- if (configDatabases.some((cdb) => cdb.name === db.name || cdb.$id === db.$id)) {
271
- acc[existingIndex] = db; // Replace with local version
272
- }
273
- } else {
274
- acc.push(db);
275
- }
276
- return acc;
277
- }, [] as Models.Database[]);
278
-
279
- const hasLocalAndRemote =
280
- allDatabases.some((db) =>
281
- configDatabases.some((c) => c.name === db.name || c.$id === db.$id)
282
- ) &&
283
- allDatabases.some(
284
- (db) => !configDatabases.some((c) => c.name === db.name || c.$id === db.$id)
285
- );
286
-
287
- const choices = allDatabases
288
- .sort((a, b) => a.name.localeCompare(b.name))
289
- .map((db) => ({
290
- name:
291
- db.name +
292
- (hasLocalAndRemote
293
- ? configDatabases.some((c) => c.name === db.name || c.$id === db.$id)
294
- ? " (Local)"
295
- : " (Remote)"
296
- : ""),
297
- value: db,
298
- }));
299
-
300
- const { selectedDatabases } = await inquirer.prompt([
301
- {
302
- type: multiSelect ? "checkbox" : "list",
303
- name: "selectedDatabases",
304
- message: chalk.blue(message),
305
- choices,
306
- loop: true,
307
- pageSize: 10,
308
- },
309
- ]);
310
-
311
- return selectedDatabases;
312
- }
313
-
314
- private async selectCollections(
315
- database: Models.Database,
316
- databasesClient: Databases,
317
- message: string,
318
- multiSelect = true,
319
- preferLocal = false,
320
- shouldFilterByDatabase = false
321
- ): Promise<Models.Collection[]> {
322
- await this.initControllerIfNeeded();
323
-
324
- const configCollections = this.getLocalCollections();
325
- let remoteCollections: Models.Collection[] = [];
326
-
327
- const dbExists = await databasesClient.list([
328
- Query.equal("name", database.name),
329
- ]);
330
- if (dbExists.total === 0) {
331
- MessageFormatter.warning(
332
- `Database "${database.name}" does not exist, using only local collection/table options`,
333
- { prefix: "Database" }
334
- );
335
- shouldFilterByDatabase = false;
336
- } else {
337
- remoteCollections = await fetchAllCollections(
338
- database.$id,
339
- databasesClient
340
- );
341
- }
342
-
343
- let allCollections = preferLocal
344
- ? remoteCollections.reduce(
345
- (acc, remoteCollection) => {
346
- if (!acc.some((c) => c.name === remoteCollection.name || c.$id === remoteCollection.$id)) {
347
- acc.push(remoteCollection);
348
- }
349
- return acc;
350
- },
351
- [...configCollections]
352
- )
353
- : [
354
- ...remoteCollections,
355
- ...configCollections.filter(
356
- (c) => !remoteCollections.some((rc) => rc.name === c.name || rc.$id === c.$id)
357
- ),
358
- ];
359
-
360
- if (shouldFilterByDatabase) {
361
- // Show collections that EITHER exist in the remote database OR have matching local databaseId metadata
362
- allCollections = allCollections.filter((c: any) => {
363
- // Include if it exists remotely in this database
364
- const existsInRemoteDb = remoteCollections.some((rc) => rc.name === c.name || rc.$id === c.$id);
365
-
366
- // Include if local metadata claims it belongs to this database
367
- const hasMatchingLocalMetadata = c.databaseId === database.$id;
368
-
369
- return existsInRemoteDb || hasMatchingLocalMetadata;
370
- });
371
- }
372
-
373
- // Filter out system tables (those starting with underscore)
374
- allCollections = allCollections.filter(
375
- (collection) => !collection.$id.startsWith('_')
376
- );
377
-
378
- const hasLocalAndRemote =
379
- allCollections.some((coll) =>
380
- configCollections.some((c) => c.name === coll.name || c.$id === coll.$id)
381
- ) &&
382
- allCollections.some(
383
- (coll) => !configCollections.some((c) => c.name === coll.name || c.$id === coll.$id)
384
- );
385
-
386
- // Enhanced choice display with type indicators
387
- const choices = allCollections
388
- .sort((a, b) => {
389
- // Sort by type first (collections before tables), then by name
390
- const aIsTable = (a as any)._isFromTablesDir || false;
391
- const bIsTable = (b as any)._isFromTablesDir || false;
392
-
393
- if (aIsTable !== bIsTable) {
394
- return aIsTable ? 1 : -1; // Collections first, then tables
395
- }
396
-
397
- return a.name.localeCompare(b.name);
398
- })
399
- .map((collection) => {
400
- const localCollection = configCollections.find((c) => c.name === collection.name || c.$id === collection.$id);
401
- const isLocal = !!localCollection;
402
- const isTable = localCollection?._isFromTablesDir || (collection as any)._isFromTablesDir || false;
403
- const sourceFolder = localCollection?._sourceFolder || (collection as any)._sourceFolder || 'collections';
404
-
405
- let typeIndicator = '';
406
- let locationIndicator = '';
407
-
408
- // Type indicator
409
- if (isTable) {
410
- typeIndicator = chalk.cyan('[Table]');
411
- } else {
412
- typeIndicator = chalk.green('[Collection]');
413
- }
414
-
415
- // Location indicator
416
- if (hasLocalAndRemote) {
417
- if (isLocal) {
418
- locationIndicator = chalk.gray(`(Local/${sourceFolder})`);
419
- } else {
420
- locationIndicator = chalk.gray('(Remote)');
421
- }
422
- } else if (isLocal) {
423
- locationIndicator = chalk.gray(`(${sourceFolder}/)`);
424
- }
425
-
426
- // Database indicator for tables with explicit databaseId
427
- let dbIndicator = '';
428
- if (isTable && collection.databaseId && shouldFilterByDatabase) {
429
- const matchesCurrentDb = collection.databaseId === database.$id;
430
- if (!matchesCurrentDb) {
431
- dbIndicator = chalk.yellow(` [DB: ${collection.databaseId}]`);
432
- }
433
- }
434
-
435
- return {
436
- name: `${typeIndicator} ${collection.name} ${locationIndicator}${dbIndicator}`,
437
- value: collection,
438
- };
439
- });
440
-
441
- const { selectedCollections } = await inquirer.prompt([
442
- {
443
- type: multiSelect ? "checkbox" : "list",
444
- name: "selectedCollections",
445
- message: chalk.blue(message),
446
- choices,
447
- loop: true,
448
- pageSize: 15, // Increased page size to accommodate additional info
449
- },
450
- ]);
451
-
452
- return selectedCollections;
453
- }
454
-
455
- /**
456
- * Enhanced collection/table selection with better guidance for mixed scenarios
457
- */
279
+
280
+ private async selectDatabases(
281
+ databases: Models.Database[],
282
+ message: string,
283
+ multiSelect = true
284
+ ): Promise<Models.Database[]> {
285
+ await this.initControllerIfNeeded();
286
+ const configDatabases = this.getLocalDatabases();
287
+ const allDatabases = [...databases, ...configDatabases]
288
+ .reduce((acc, db) => {
289
+ // Local config takes precedence - if a database with same name or ID exists, use local version
290
+ const existingIndex = acc.findIndex((d) => d.name === db.name || d.$id === db.$id);
291
+ if (existingIndex >= 0) {
292
+ if (configDatabases.some((cdb) => cdb.name === db.name || cdb.$id === db.$id)) {
293
+ acc[existingIndex] = db; // Replace with local version
294
+ }
295
+ } else {
296
+ acc.push(db);
297
+ }
298
+ return acc;
299
+ }, [] as Models.Database[]);
300
+
301
+ const hasLocalAndRemote =
302
+ allDatabases.some((db) =>
303
+ configDatabases.some((c) => c.name === db.name || c.$id === db.$id)
304
+ ) &&
305
+ allDatabases.some(
306
+ (db) => !configDatabases.some((c) => c.name === db.name || c.$id === db.$id)
307
+ );
308
+
309
+ const choices = allDatabases
310
+ .sort((a, b) => a.name.localeCompare(b.name))
311
+ .map((db) => ({
312
+ name:
313
+ db.name +
314
+ (hasLocalAndRemote
315
+ ? configDatabases.some((c) => c.name === db.name || c.$id === db.$id)
316
+ ? " (Local)"
317
+ : " (Remote)"
318
+ : ""),
319
+ value: db,
320
+ }));
321
+
322
+ const { selectedDatabases } = await inquirer.prompt([
323
+ {
324
+ type: multiSelect ? "checkbox" : "list",
325
+ name: "selectedDatabases",
326
+ message: chalk.blue(message),
327
+ choices,
328
+ loop: true,
329
+ pageSize: 10,
330
+ },
331
+ ]);
332
+
333
+ // "list" type returns a single value, "checkbox" returns an array — normalize to array
334
+ return Array.isArray(selectedDatabases) ? selectedDatabases : [selectedDatabases];
335
+ }
336
+
337
+ private async selectCollections(
338
+ database: Models.Database,
339
+ databasesClient: Databases,
340
+ message: string,
341
+ multiSelect = true,
342
+ preferLocal = false,
343
+ shouldFilterByDatabase = false
344
+ ): Promise<Models.Collection[]> {
345
+ await this.initControllerIfNeeded();
346
+
347
+ const configCollections = this.getLocalCollections();
348
+ let remoteCollections: Models.Collection[] = [];
349
+
350
+ const dbExists = await databasesClient.list([
351
+ Query.equal("name", database.name),
352
+ ]);
353
+ if (dbExists.total === 0) {
354
+ MessageFormatter.warning(
355
+ `Database "${database.name}" does not exist, using only local collection/table options`,
356
+ { prefix: "Database" }
357
+ );
358
+ shouldFilterByDatabase = false;
359
+ } else {
360
+ remoteCollections = await fetchAllCollections(
361
+ database.$id,
362
+ databasesClient
363
+ );
364
+ }
365
+
366
+ let allCollections = preferLocal
367
+ ? remoteCollections.reduce(
368
+ (acc, remoteCollection) => {
369
+ if (!acc.some((c) => c.name === remoteCollection.name || c.$id === remoteCollection.$id)) {
370
+ acc.push(remoteCollection);
371
+ }
372
+ return acc;
373
+ },
374
+ [...configCollections]
375
+ )
376
+ : [
377
+ ...remoteCollections,
378
+ ...configCollections.filter(
379
+ (c) => !remoteCollections.some((rc) => rc.name === c.name || rc.$id === c.$id)
380
+ ),
381
+ ];
382
+
383
+ if (shouldFilterByDatabase) {
384
+ // Show collections that EITHER exist in the remote database OR have matching local databaseId metadata
385
+ allCollections = allCollections.filter((c: any) => {
386
+ // Include if it exists remotely in this database
387
+ const existsInRemoteDb = remoteCollections.some((rc) => rc.name === c.name || rc.$id === c.$id);
388
+
389
+ // Include if local metadata claims it belongs to this database
390
+ const hasMatchingLocalMetadata = c.databaseId === database.$id;
391
+
392
+ return existsInRemoteDb || hasMatchingLocalMetadata;
393
+ });
394
+ }
395
+
396
+ // Filter out system tables (those starting with underscore)
397
+ allCollections = allCollections.filter(
398
+ (collection) => !collection.$id.startsWith('_')
399
+ );
400
+
401
+ const hasLocalAndRemote =
402
+ allCollections.some((coll) =>
403
+ configCollections.some((c) => c.name === coll.name || c.$id === coll.$id)
404
+ ) &&
405
+ allCollections.some(
406
+ (coll) => !configCollections.some((c) => c.name === coll.name || c.$id === coll.$id)
407
+ );
408
+
409
+ const getCollectionId = (collection: Models.Collection) => collection.$id || collection.name;
410
+ const localCollectionIds = new Set(configCollections.map((c) => c.$id || c.name));
411
+ const localCollections = allCollections.filter((collection) =>
412
+ localCollectionIds.has(getCollectionId(collection))
413
+ );
414
+
415
+ // Enhanced choice display with type indicators
416
+ const choices: { name: string; value: Models.Collection | string }[] = allCollections
417
+ .sort((a, b) => {
418
+ // Sort by type first (collections before tables), then by name
419
+ const aIsTable = (a as any)._isFromTablesDir || false;
420
+ const bIsTable = (b as any)._isFromTablesDir || false;
421
+
422
+ if (aIsTable !== bIsTable) {
423
+ return aIsTable ? 1 : -1; // Collections first, then tables
424
+ }
425
+
426
+ return a.name.localeCompare(b.name);
427
+ })
428
+ .map((collection) => {
429
+ const localCollection = configCollections.find((c) => c.name === collection.name || c.$id === collection.$id);
430
+ const isLocal = !!localCollection;
431
+ const isTable = localCollection?._isFromTablesDir || (collection as any)._isFromTablesDir || false;
432
+ const sourceFolder = localCollection?._sourceFolder || (collection as any)._sourceFolder || 'collections';
433
+
434
+ let typeIndicator = '';
435
+ let locationIndicator = '';
436
+
437
+ // Type indicator
438
+ if (isTable) {
439
+ typeIndicator = chalk.cyan('[Table]');
440
+ } else {
441
+ typeIndicator = chalk.green('[Collection]');
442
+ }
443
+
444
+ // Location indicator
445
+ if (hasLocalAndRemote) {
446
+ if (isLocal) {
447
+ locationIndicator = chalk.gray(`(Local/${sourceFolder})`);
448
+ } else {
449
+ locationIndicator = chalk.gray('(Remote)');
450
+ }
451
+ } else if (isLocal) {
452
+ locationIndicator = chalk.gray(`(${sourceFolder}/)`);
453
+ }
454
+
455
+ // Database indicator for tables with explicit databaseId
456
+ let dbIndicator = '';
457
+ if (isTable && collection.databaseId && shouldFilterByDatabase) {
458
+ const matchesCurrentDb = collection.databaseId === database.$id;
459
+ if (!matchesCurrentDb) {
460
+ dbIndicator = chalk.yellow(` [DB: ${collection.databaseId}]`);
461
+ }
462
+ }
463
+
464
+ return {
465
+ name: `${typeIndicator} ${collection.name} ${locationIndicator}${dbIndicator}`,
466
+ value: collection,
467
+ };
468
+ });
469
+
470
+ if (multiSelect && localCollections.length > 1) {
471
+ choices.unshift({
472
+ name: chalk.green.bold(`📋 Select All Local Items (${localCollections.length})`),
473
+ value: "__SELECT_ALL_LOCAL__"
474
+ });
475
+ }
476
+
477
+ if (multiSelect && allCollections.length > 1) {
478
+ choices.unshift({
479
+ name: chalk.green.bold(`📋 Select All Shown (${allCollections.length})`),
480
+ value: "__SELECT_ALL__"
481
+ });
482
+ }
483
+
484
+ const { selectedCollections } = await inquirer.prompt([
485
+ {
486
+ type: multiSelect ? "checkbox" : "list",
487
+ name: "selectedCollections",
488
+ message: chalk.blue(message),
489
+ choices,
490
+ loop: true,
491
+ pageSize: 15, // Increased page size to accommodate additional info
492
+ validate: (input: any[]) => {
493
+ if (!multiSelect) return true;
494
+ if (input.includes("__SELECT_ALL__") && input.length > 1) {
495
+ return "Cannot select 'Select All' with individual items.";
496
+ }
497
+ if (input.includes("__SELECT_ALL_LOCAL__") && input.length > 1) {
498
+ return "Cannot select 'Select All Local' with individual items.";
499
+ }
500
+ return true;
501
+ }
502
+ },
503
+ ]);
504
+
505
+ if (multiSelect && Array.isArray(selectedCollections)) {
506
+ if (selectedCollections.includes("__SELECT_ALL__")) {
507
+ return allCollections;
508
+ }
509
+ if (selectedCollections.includes("__SELECT_ALL_LOCAL__")) {
510
+ return localCollections;
511
+ }
512
+ }
513
+
514
+ return selectedCollections;
515
+ }
516
+
517
+ /**
518
+ * Enhanced collection/table selection with better guidance for mixed scenarios
519
+ */
458
520
  private async selectCollectionsAndTables(
459
521
  database: Models.Database,
460
522
  databasesClient: Databases,
@@ -463,33 +525,33 @@ export class InteractiveCLI {
463
525
  preferLocal = false,
464
526
  shouldFilterByDatabase = false
465
527
  ): Promise<Models.Collection[]> {
466
- const configCollections = this.getLocalCollections();
467
- const collectionsCount = configCollections.filter(c => !c._isFromTablesDir).length;
468
- const tablesCount = configCollections.filter(c => c._isFromTablesDir).length;
469
- const totalCount = collectionsCount + tablesCount;
470
-
471
- // Provide context about what's available
472
- if (collectionsCount > 0 && tablesCount > 0) {
473
- MessageFormatter.info(`\n📋 ${totalCount} total items available:`, { prefix: "Collections" });
474
- MessageFormatter.info(` Collections: ${collectionsCount} (from collections/ folder)`, { prefix: "Collections" });
475
- MessageFormatter.info(` Tables: ${tablesCount} (from tables/ folder)`, { prefix: "Collections" });
476
- } else if (collectionsCount > 0) {
477
- MessageFormatter.info(`📁 ${collectionsCount} collections available from collections/ folder`, { prefix: "Collections" });
478
- } else if (tablesCount > 0) {
479
- MessageFormatter.info(`📊 ${tablesCount} tables available from tables/ folder`, { prefix: "Collections" });
480
- }
481
-
528
+ const configCollections = this.getLocalCollections();
529
+ const collectionsCount = configCollections.filter(c => !c._isFromTablesDir).length;
530
+ const tablesCount = configCollections.filter(c => c._isFromTablesDir).length;
531
+ const totalCount = collectionsCount + tablesCount;
532
+
533
+ // Provide context about what's available
534
+ if (collectionsCount > 0 && tablesCount > 0) {
535
+ MessageFormatter.info(`\n${totalCount} total tables available:`, { prefix: "Tables" });
536
+ MessageFormatter.info(` From collections/ folder: ${collectionsCount}`, { prefix: "Tables" });
537
+ MessageFormatter.info(` From tables/ folder: ${tablesCount}`, { prefix: "Tables" });
538
+ } else if (collectionsCount > 0) {
539
+ MessageFormatter.info(`${collectionsCount} tables available from collections/ folder`, { prefix: "Tables" });
540
+ } else if (tablesCount > 0) {
541
+ MessageFormatter.info(`${tablesCount} tables available from tables/ folder`, { prefix: "Tables" });
542
+ }
543
+
482
544
  // Show current database context clearly before view mode selection
483
- MessageFormatter.info(`DB: ${database.name}`, { prefix: "Collections" });
545
+ MessageFormatter.info(`DB: ${database.name}`, { prefix: "Tables" });
484
546
 
485
547
  // Ask user if they want to filter by database, show all, or reuse previous selection
486
548
  const choices: { name: string; value: string }[] = [
487
549
  {
488
- name: `Show all available collections/tables (${totalCount} total) - You can push any collection to any database`,
550
+ name: `Show all available tables (${totalCount} total) - You can push any table to any database`,
489
551
  value: "all"
490
552
  },
491
553
  {
492
- name: `Filter by database "${database.name}" - Show only related collections/tables`,
554
+ name: `Filter by database "${database.name}" - Show only related tables`,
493
555
  value: "filter"
494
556
  }
495
557
  ];
@@ -504,7 +566,7 @@ export class InteractiveCLI {
504
566
  {
505
567
  type: "list",
506
568
  name: "filterChoice",
507
- message: chalk.blue("How would you like to view collections/tables?"),
569
+ message: chalk.blue("How would you like to view tables?"),
508
570
  choices,
509
571
  default: choices[0]?.value || "all"
510
572
  }
@@ -524,22 +586,22 @@ export class InteractiveCLI {
524
586
 
525
587
  // User's choice overrides the parameter
526
588
  const userWantsFiltering = filterChoice === "filter";
527
-
528
- // Show appropriate informational message
529
- if (userWantsFiltering) {
530
- MessageFormatter.info(`ℹ️ Showing collections/tables related to database "${database.name}"`, { prefix: "Collections" });
531
- if (tablesCount > 0) {
532
- const filteredTables = configCollections.filter(c =>
533
- c._isFromTablesDir && (!c.databaseId || c.databaseId === database.$id)
534
- ).length;
535
- if (filteredTables !== tablesCount) {
536
- MessageFormatter.info(` ${filteredTables}/${tablesCount} tables match this database`, { prefix: "Collections" });
537
- }
538
- }
539
- } else {
540
- MessageFormatter.info(`ℹ️ Showing all available collections/tables - you can push any collection to any database\n`, { prefix: "Collections" });
541
- }
542
-
589
+
590
+ // Show appropriate informational message
591
+ if (userWantsFiltering) {
592
+ MessageFormatter.info(`Showing tables related to database "${database.name}"`, { prefix: "Tables" });
593
+ if (tablesCount > 0) {
594
+ const filteredTables = configCollections.filter(c =>
595
+ c._isFromTablesDir && (!c.databaseId || c.databaseId === database.$id)
596
+ ).length;
597
+ if (filteredTables !== tablesCount) {
598
+ MessageFormatter.info(` ${filteredTables}/${tablesCount} tables match this database`, { prefix: "Tables" });
599
+ }
600
+ }
601
+ } else {
602
+ MessageFormatter.info(`Showing all available tables - you can push any table to any database\n`, { prefix: "Tables" });
603
+ }
604
+
543
605
  const result = await this.selectCollections(
544
606
  database,
545
607
  databasesClient,
@@ -552,585 +614,588 @@ export class InteractiveCLI {
552
614
  this.lastSelectedCollectionIds = (result || []).map((c: any) => c.$id || c.id);
553
615
  return result;
554
616
  }
555
-
556
- private getTemplateDefaults(template: string) {
557
- const defaults = {
558
- "typescript-node": {
559
- runtime: "node-21.0" as Runtime,
560
- entrypoint: "src/index.ts",
561
- commands: "npm install && npm run build",
562
- specification: "s-0.5vcpu-512mb" as Specification,
563
- },
564
- "hono-typescript": {
565
- runtime: "node-21.0" as Runtime,
566
- entrypoint: "src/index.ts",
567
- commands: "npm install && npm run build",
568
- specification: "s-0.5vcpu-512mb" as Specification,
569
- },
570
- "uv": {
571
- runtime: "python-3.12" as Runtime,
572
- entrypoint: "src/index.py",
573
- commands: "uv sync && uv build",
574
- specification: "s-0.5vcpu-512mb" as Specification,
575
- },
576
- "count-docs-in-collection": {
577
- runtime: "node-21.0" as Runtime,
578
- entrypoint: "src/main.ts",
579
- commands: "npm install && npm run build",
580
- specification: "s-1vcpu-512mb" as Specification,
581
- },
582
- };
583
-
584
- return defaults[template as keyof typeof defaults] || {
585
- runtime: "node-21.0" as Runtime,
586
- entrypoint: "",
587
- commands: "",
588
- specification: "s-0.5vcpu-512mb" as Specification,
589
- };
590
- }
591
-
592
-
593
- private async findFunctionInSubdirectories(
594
- basePaths: string[],
595
- functionName: string
596
- ): Promise<string | null> {
597
- // Common locations to check first
598
- const commonPaths = basePaths.flatMap((basePath) => [
599
- join(basePath, "functions", functionName),
600
- join(basePath, functionName),
601
- join(basePath, functionName.toLowerCase()),
602
- join(basePath, functionName.toLowerCase().replace(/\s+/g, "")),
603
- ]);
604
-
605
- // Create different variations of the function name for comparison
606
- const functionNameVariations = new Set([
607
- functionName.toLowerCase(),
608
- functionName.toLowerCase().replace(/\s+/g, ""),
609
- functionName.toLowerCase().replace(/[^a-z0-9]/g, ""),
610
- functionName.toLowerCase().replace(/[-_\s]+/g, ""),
611
- ]);
612
-
613
- // Check common locations first
614
- for (const path of commonPaths) {
615
- try {
616
- const stats = await fs.promises.stat(path);
617
- if (stats.isDirectory()) {
618
- MessageFormatter.success(`Found function at common location: ${path}`, { prefix: "Functions" });
619
- return path;
620
- }
621
- } catch (error) {
622
- // Path doesn't exist, continue to next
623
- }
624
- }
625
-
626
- // If not found in common locations, do recursive search
627
- MessageFormatter.info("Function not found in common locations, searching subdirectories...", { prefix: "Functions" });
628
-
629
- const queue = [...basePaths];
630
- const searched = new Set<string>();
631
-
632
- while (queue.length > 0) {
633
- const currentPath = queue.shift()!;
634
-
635
- if (searched.has(currentPath)) continue;
636
- searched.add(currentPath);
637
-
638
- try {
639
- const entries = await fs.promises.readdir(currentPath, {
640
- withFileTypes: true,
641
- });
642
-
643
- for (const entry of entries) {
644
- const fullPath = join(currentPath, entry.name);
645
-
646
- // Skip node_modules and hidden directories
647
- if (
648
- entry.isDirectory() &&
649
- !entry.name.startsWith(".") &&
650
- entry.name !== "node_modules"
651
- ) {
652
- const entryNameVariations = new Set([
653
- entry.name.toLowerCase(),
654
- entry.name.toLowerCase().replace(/\s+/g, ""),
655
- entry.name.toLowerCase().replace(/[^a-z0-9]/g, ""),
656
- entry.name.toLowerCase().replace(/[-_\s]+/g, ""),
657
- ]);
658
-
659
- // Check if any variation of the entry name matches any variation of the function name
660
- const hasMatch = [...functionNameVariations].some((fnVar) =>
661
- [...entryNameVariations].includes(fnVar)
662
- );
663
-
664
- if (hasMatch) {
665
- MessageFormatter.success(`Found function at: ${fullPath}`, { prefix: "Functions" });
666
- return fullPath;
667
- }
668
-
669
- queue.push(fullPath);
670
- }
671
- }
672
- } catch (error) {
673
- MessageFormatter.warning(`Error reading directory ${currentPath}: ${error}`, { prefix: "Functions" });
674
- }
675
- }
676
-
677
- return null;
678
- }
679
-
680
-
681
- private async selectFunctions(
682
- message: string,
683
- multiple: boolean = true,
684
- includeRemote: boolean = false
685
- ): Promise<AppwriteFunction[]> {
686
- const remoteFunctions = includeRemote
687
- ? await listFunctions(this.controller!.appwriteServer!, [
688
- Query.limit(1000),
689
- ])
690
- : { functions: [] };
691
- const localFunctions = this.getLocalFunctions();
692
-
693
- // Combine functions, preferring local ones
694
- const allFunctions = [
695
- ...localFunctions,
696
- ...remoteFunctions.functions.filter(
697
- (rf: any) => !localFunctions.some((lf) => lf.name === rf.name || lf.$id === rf.$id)
698
- ),
699
- ];
700
-
701
- const { selectedFunctions } = await inquirer.prompt([
702
- {
703
- type: multiple ? "checkbox" : "list",
704
- name: "selectedFunctions",
705
- message,
706
- choices: allFunctions.map((f) => ({
707
- name: `${f.name} (${f.$id})${
708
- localFunctions.some((lf) => lf.name === f.name || lf.$id === f.$id)
709
- ? " (Local)"
710
- : " (Remote)"
711
- }`,
712
- value: f,
713
- })),
714
- loop: true,
715
- },
716
- ]);
717
-
718
- return multiple ? selectedFunctions : [selectedFunctions];
719
- }
720
-
721
- private getLocalFunctions(): AppwriteFunction[] {
722
- const configFunctions = this.controller!.config?.functions || [];
723
- return configFunctions.map((f) => ({
724
- $id: f.$id || ulid(),
725
- $createdAt: DateTime.now().toISO(),
726
- $updatedAt: DateTime.now().toISO(),
727
- name: f.name,
728
- runtime: f.runtime,
729
- execute: f.execute || ["any"],
730
- events: f.events || [],
731
- schedule: f.schedule || "",
732
- timeout: f.timeout || 15,
733
- ignore: f.ignore,
734
- enabled: f.enabled !== false,
735
- logging: f.logging !== false,
736
- entrypoint: f.entrypoint || "src/index.ts",
737
- commands: f.commands || "npm install",
738
- scopes: f.scopes || [], // Add scopes
739
- path: f.dirPath || `functions/${f.name}`,
740
- dirPath: f.dirPath, // Preserve original dirPath
741
- installationId: f.installationId || "",
742
- providerRepositoryId: f.providerRepositoryId || "",
743
- providerBranch: f.providerBranch || "",
744
- providerSilentMode: f.providerSilentMode || false,
745
- providerRootDirectory: f.providerRootDirectory || "",
746
- ...(f.specification ? { specification: f.specification } : {}),
747
- ...(f.predeployCommands
748
- ? { predeployCommands: f.predeployCommands }
749
- : {}),
750
- ...(f.deployDir ? { deployDir: f.deployDir } : {}),
751
- }));
752
- }
753
- private async selectBuckets(
754
- buckets: Models.Bucket[],
755
- message: string,
756
- multiSelect = true
757
- ): Promise<Models.Bucket[]> {
758
- const choices = buckets.map((bucket) => ({
759
- name: bucket.name,
760
- value: bucket,
761
- }));
762
-
763
- const { selectedBuckets } = await inquirer.prompt([
764
- {
765
- type: multiSelect ? "checkbox" : "list",
766
- name: "selectedBuckets",
767
- message: chalk.blue(message),
768
- choices,
769
- loop: false,
770
- pageSize: 10,
771
- },
772
- ]);
773
-
774
- return selectedBuckets;
775
- }
776
-
777
-
778
- private async configureBuckets(
779
- config: AppwriteConfig,
780
- databases?: ConfigDatabases
781
- ): Promise<AppwriteConfig> {
782
- const { storage } = this.controller!;
783
- if (!storage) {
784
- throw new Error(
785
- "Storage is not initialized. Is the config file correct and created?"
786
- );
787
- }
788
-
789
- const allBuckets = await listBuckets(storage);
790
-
791
- // If there are no buckets, ask to create one for each database
792
- if (allBuckets.total === 0) {
793
- const databasesToUse = databases ?? config.databases;
794
- for (const database of databasesToUse) {
795
- // If database has bucket config in local config, use that
796
- const localDatabase = this.controller!.config?.databases.find(
797
- (db) => db.name === database.name
798
- );
799
- if (localDatabase?.bucket) {
800
- database.bucket = localDatabase.bucket;
801
- continue;
802
- }
803
- const { wantCreateBucket } = await inquirer.prompt([
804
- {
805
- type: "confirm",
806
- name: "wantCreateBucket",
807
- message: chalk.blue(
808
- `There are no buckets. Do you want to create a bucket for the database "${database.name}"?`
809
- ),
810
- default: true,
811
- },
812
- ]);
813
- if (wantCreateBucket) {
814
- const createdBucket = await this.createNewBucket(
815
- storage,
816
- database.name
817
- );
818
- database.bucket = {
819
- ...createdBucket,
820
- compression: createdBucket.compression as Compression,
821
- };
822
- }
823
- }
824
- return config;
825
- }
826
-
827
- // Configure global buckets
828
- let globalBuckets: Models.Bucket[] = [];
829
- if (allBuckets.total > 0) {
830
- globalBuckets = await this.selectBuckets(
831
- allBuckets.buckets,
832
- "Select global buckets (buckets that are not associated with any specific database):",
833
- true
834
- );
835
-
836
- config.buckets = globalBuckets.map((bucket) => ({
837
- $id: bucket.$id,
838
- name: bucket.name,
839
- enabled: bucket.enabled,
840
- maximumFileSize: bucket.maximumFileSize,
841
- allowedFileExtensions: bucket.allowedFileExtensions,
842
- compression: bucket.compression as Compression,
843
- encryption: bucket.encryption,
844
- antivirus: bucket.antivirus,
845
- }));
846
- } else {
847
- config.buckets = [];
848
- }
849
-
850
- // Configure database-specific buckets
851
- for (const database of config.databases) {
852
- const { assignBucket } = await inquirer.prompt([
853
- {
854
- type: "confirm",
855
- name: "assignBucket",
856
- message: `Do you want to assign or create a bucket for the database "${database.name}"?`,
857
- default: false,
858
- },
859
- ]);
860
-
861
- if (assignBucket) {
862
- const { action } = await inquirer.prompt([
863
- {
864
- type: "list",
865
- name: "action",
866
- message: `Choose an action for the database "${database.name}":`,
867
- choices: [
868
- { name: "Assign existing bucket", value: "assign" },
869
- { name: "Create new bucket", value: "create" },
870
- ],
871
- },
872
- ]);
873
-
874
- if (action === "assign") {
875
- const selectedBuckets = await this.selectBuckets(
876
- allBuckets.buckets.filter(
877
- (b) => !globalBuckets.some((gb) => gb.$id === b.$id)
878
- ),
879
- `Select a bucket for the database "${database.name}":`,
880
- false // multiSelect = false
881
- );
882
-
883
- if (selectedBuckets.length > 0) {
884
- const selectedBucket = selectedBuckets[0];
885
- database.bucket = {
886
- $id: selectedBucket.$id,
887
- name: selectedBucket.name,
888
- enabled: selectedBucket.enabled,
889
- maximumFileSize: selectedBucket.maximumFileSize,
890
- allowedFileExtensions: selectedBucket.allowedFileExtensions,
891
- compression: selectedBucket.compression as Compression,
892
- encryption: selectedBucket.encryption,
893
- antivirus: selectedBucket.antivirus,
894
- permissions: selectedBucket.$permissions.map((p) =>
895
- permissionSchema.parse(p)
896
- ),
897
- };
898
- }
899
- } else if (action === "create") {
900
- const createdBucket = await this.createNewBucket(
901
- storage,
902
- database.name
903
- );
904
- database.bucket = {
905
- ...createdBucket,
906
- compression: createdBucket.compression as Compression,
907
- };
908
- }
909
- }
910
- }
911
-
912
- return config;
913
- }
914
-
915
- private async createNewBucket(
916
- storage: Storage,
917
- databaseName: string
918
- ): Promise<Models.Bucket> {
919
- const {
920
- bucketName,
921
- bucketEnabled,
922
- bucketMaximumFileSize,
923
- bucketAllowedFileExtensions,
924
- bucketFileSecurity,
925
- bucketCompression,
926
- bucketCompressionType,
927
- bucketEncryption,
928
- bucketAntivirus,
929
- bucketId,
930
- } = await inquirer.prompt([
931
- {
932
- type: "input",
933
- name: "bucketName",
934
- message: `Enter the name of the bucket for database "${databaseName}":`,
935
- default: `${databaseName}-bucket`,
936
- },
937
- {
938
- type: "confirm",
939
- name: "bucketEnabled",
940
- message: "Is the bucket enabled?",
941
- default: true,
942
- },
943
- {
944
- type: "confirm",
945
- name: "bucketFileSecurity",
946
- message: "Do you want to enable file security for the bucket?",
947
- default: false,
948
- },
949
- {
950
- type: "number",
951
- name: "bucketMaximumFileSize",
952
- message: "Enter the maximum file size for the bucket (MB):",
953
- default: 1000000,
954
- },
955
- {
956
- type: "input",
957
- name: "bucketAllowedFileExtensions",
958
- message:
959
- "Enter the allowed file extensions for the bucket (comma separated):",
960
- default: "",
961
- },
962
- {
963
- type: "confirm",
964
- name: "bucketCompression",
965
- message: "Do you want to enable compression for the bucket?",
966
- default: false,
967
- },
968
- {
969
- type: "list",
970
- name: "bucketCompressionType",
971
- message: "Select the compression type for the bucket:",
972
- choices: Object.values(Compression),
973
- default: Compression.None,
974
- when: (answers) => answers.bucketCompression,
975
- },
976
- {
977
- type: "confirm",
978
- name: "bucketEncryption",
979
- message: "Do you want to enable encryption for the bucket?",
980
- default: false,
981
- },
982
- {
983
- type: "confirm",
984
- name: "bucketAntivirus",
985
- message: "Do you want to enable antivirus for the bucket?",
986
- default: false,
987
- },
988
- {
989
- type: "input",
990
- name: "bucketId",
991
- message: "Enter the ID of the bucket (or empty for auto-generation):",
992
- },
993
- ]);
994
-
995
- return await createBucket(
996
- storage,
997
- {
998
- name: bucketName,
999
- $permissions: [],
1000
- enabled: bucketEnabled,
1001
- fileSecurity: bucketFileSecurity,
1002
- maximumFileSize: bucketMaximumFileSize * 1024 * 1024,
1003
- allowedFileExtensions:
1004
- bucketAllowedFileExtensions.length > 0
1005
- ? bucketAllowedFileExtensions?.split(",")
1006
- : [],
1007
- compression: bucketCompressionType as Compression,
1008
- encryption: bucketEncryption,
1009
- antivirus: bucketAntivirus,
1010
- },
1011
- bucketId.length > 0 ? bucketId : ulid()
1012
- );
1013
- }
1014
-
1015
-
1016
-
1017
- private getLocalCollections(): (Models.Collection & {
1018
- _isFromTablesDir?: boolean;
1019
- _sourceFolder?: string;
1020
- databaseId?: string;
1021
- })[] {
1022
- const configCollections = this.controller!.config?.collections || [];
1023
- // @ts-expect-error - appwrite invalid types
1024
- return configCollections.map((c) => ({
1025
- $id: c.$id || ulid(),
1026
- $createdAt: DateTime.now().toISO(),
1027
- $updatedAt: DateTime.now().toISO(),
1028
- name: c.name,
1029
- enabled: c.enabled || true,
1030
- documentSecurity: c.documentSecurity || false,
1031
- attributes: c.attributes || [],
1032
- indexes: c.indexes || [],
1033
- $permissions: PermissionToAppwritePermission(c.$permissions) || [],
1034
- databaseId: c.databaseId,
1035
- _isFromTablesDir: (c as any)._isFromTablesDir || false,
1036
- _sourceFolder: (c as any)._isFromTablesDir ? 'tables' : 'collections',
1037
- }));
1038
- }
1039
-
1040
- private getLocalDatabases(): Models.Database[] {
1041
- const configDatabases = this.controller!.config?.databases || [];
1042
- return configDatabases.map((db) => ({
1043
- $id: db.$id || ulid(),
1044
- $createdAt: DateTime.now().toISO(),
1045
- $updatedAt: DateTime.now().toISO(),
1046
- name: db.name,
1047
- enabled: true,
1048
- type: "tablesdb" as DatabaseType,
1049
- }));
1050
- }
1051
-
1052
-
1053
- /**
1054
- * Extract session information from current controller for preservation
1055
- */
1056
- private async extractSessionFromController(): Promise<{
1057
- appwriteEndpoint: string;
1058
- appwriteProject: string;
1059
- appwriteKey?: string;
1060
- sessionCookie?: string;
1061
- sessionMetadata?: any;
1062
- } | undefined> {
1063
- if (!this.controller?.config) {
1064
- return undefined;
1065
- }
1066
-
1067
- const sessionInfo = await this.controller.getSessionInfo();
1068
- const config = this.controller.config;
1069
-
1070
- if (!config.appwriteEndpoint || !config.appwriteProject) {
1071
- return undefined;
1072
- }
1073
-
1074
- const result: any = {
1075
- appwriteEndpoint: config.appwriteEndpoint,
1076
- appwriteProject: config.appwriteProject,
1077
- appwriteKey: config.appwriteKey
1078
- };
1079
-
1080
- // Add session data if available
1081
- if (sessionInfo.hasSession) {
1082
- result.sessionCookie = (this.controller as any).sessionCookie;
1083
- result.sessionMetadata = (this.controller as any).sessionMetadata;
1084
- }
1085
-
1086
- return result;
1087
- }
1088
-
1089
-
1090
- private async detectConfigurationType(): Promise<void> {
1091
- try {
1092
- // Check for YAML config first
1093
- const yamlConfigPath = findYamlConfig(this.currentDir);
1094
- if (yamlConfigPath) {
1095
- this.isUsingTypeScriptConfig = false;
1096
- MessageFormatter.info("Using YAML configuration", { prefix: "Config" });
1097
- return;
1098
- }
1099
-
1100
- // Then check for TypeScript config
1101
- const configPath = findAppwriteConfig(this.currentDir);
1102
- if (configPath) {
1103
- const tsConfigPath = join(configPath, 'appwriteConfig.ts');
1104
- if (fs.existsSync(tsConfigPath)) {
1105
- this.isUsingTypeScriptConfig = true;
1106
- MessageFormatter.info("TypeScript configuration detected", { prefix: "Config" });
1107
- MessageFormatter.info("Consider migrating to YAML for better organization", { prefix: "Config" });
1108
- return;
1109
- }
1110
- }
1111
-
1112
- // No config found
1113
- this.isUsingTypeScriptConfig = false;
1114
- MessageFormatter.info("No configuration file found", { prefix: "Config" });
1115
- } catch (error) {
1116
- // Silently handle detection errors and continue
1117
- this.isUsingTypeScriptConfig = false;
1118
- }
1119
- }
1120
-
1121
- private buildChoicesList(): string[] {
1122
- const allChoices = Object.values(CHOICES);
1123
-
1124
- if (this.isUsingTypeScriptConfig) {
1125
- // Place migration option at the top when TS config is detected
1126
- return [
1127
- CHOICES.MIGRATE_CONFIG,
1128
- ...allChoices.filter(choice => choice !== CHOICES.MIGRATE_CONFIG)
1129
- ];
1130
- } else {
1131
- // Hide migration option when using YAML config
1132
- return allChoices.filter(choice => choice !== CHOICES.MIGRATE_CONFIG);
1133
- }
1134
- }
1135
-
1136
- }
617
+
618
+ private getTemplateDefaults(template: string) {
619
+ const defaults = {
620
+ "typescript-node": {
621
+ runtime: "node-21.0" as Runtime,
622
+ entrypoint: "src/main.ts",
623
+ commands: "npm install && npm run build",
624
+ specification: "s-0.5vcpu-512mb" as Specification,
625
+ },
626
+ "hono-typescript": {
627
+ runtime: "node-21.0" as Runtime,
628
+ entrypoint: "src/main.ts",
629
+ commands: "npm install && npm run build",
630
+ specification: "s-0.5vcpu-512mb" as Specification,
631
+ },
632
+ "uv": {
633
+ runtime: "python-3.12" as Runtime,
634
+ entrypoint: "src/main.py",
635
+ commands: "uv sync && uv build",
636
+ specification: "s-0.5vcpu-512mb" as Specification,
637
+ },
638
+ "count-docs-in-collection": {
639
+ runtime: "node-21.0" as Runtime,
640
+ entrypoint: "src/main.ts",
641
+ commands: "npm install && npm run build",
642
+ specification: "s-1vcpu-512mb" as Specification,
643
+ },
644
+ };
645
+
646
+ return defaults[template as keyof typeof defaults] || {
647
+ runtime: "node-21.0" as Runtime,
648
+ entrypoint: "",
649
+ commands: "",
650
+ specification: "s-0.5vcpu-512mb" as Specification,
651
+ };
652
+ }
653
+
654
+
655
+ private async findFunctionInSubdirectories(
656
+ basePaths: string[],
657
+ functionName: string
658
+ ): Promise<string | null> {
659
+ // Common locations to check first
660
+ const commonPaths = basePaths.flatMap((basePath) => [
661
+ join(basePath, "functions", functionName),
662
+ join(basePath, functionName),
663
+ join(basePath, functionName.toLowerCase()),
664
+ join(basePath, functionName.toLowerCase().replace(/\s+/g, "")),
665
+ ]);
666
+
667
+ // Create different variations of the function name for comparison
668
+ const functionNameVariations = new Set([
669
+ functionName.toLowerCase(),
670
+ functionName.toLowerCase().replace(/\s+/g, ""),
671
+ functionName.toLowerCase().replace(/[^a-z0-9]/g, ""),
672
+ functionName.toLowerCase().replace(/[-_\s]+/g, ""),
673
+ ]);
674
+
675
+ // Check common locations first
676
+ for (const path of commonPaths) {
677
+ try {
678
+ const stats = await fs.promises.stat(path);
679
+ if (stats.isDirectory()) {
680
+ MessageFormatter.success(`Found function at common location: ${path}`, { prefix: "Functions" });
681
+ return path;
682
+ }
683
+ } catch (error) {
684
+ // Path doesn't exist, continue to next
685
+ }
686
+ }
687
+
688
+ // If not found in common locations, do recursive search
689
+ MessageFormatter.info("Function not found in common locations, searching subdirectories...", { prefix: "Functions" });
690
+
691
+ const queue = [...basePaths];
692
+ const searched = new Set<string>();
693
+
694
+ while (queue.length > 0) {
695
+ const currentPath = queue.shift()!;
696
+
697
+ if (searched.has(currentPath)) continue;
698
+ searched.add(currentPath);
699
+
700
+ try {
701
+ const entries = await fs.promises.readdir(currentPath, {
702
+ withFileTypes: true,
703
+ });
704
+
705
+ for (const entry of entries) {
706
+ const fullPath = join(currentPath, entry.name);
707
+
708
+ // Skip node_modules and hidden directories
709
+ if (
710
+ entry.isDirectory() &&
711
+ !entry.name.startsWith(".") &&
712
+ entry.name !== "node_modules"
713
+ ) {
714
+ const entryNameVariations = new Set([
715
+ entry.name.toLowerCase(),
716
+ entry.name.toLowerCase().replace(/\s+/g, ""),
717
+ entry.name.toLowerCase().replace(/[^a-z0-9]/g, ""),
718
+ entry.name.toLowerCase().replace(/[-_\s]+/g, ""),
719
+ ]);
720
+
721
+ // Check if any variation of the entry name matches any variation of the function name
722
+ const hasMatch = [...functionNameVariations].some((fnVar) =>
723
+ [...entryNameVariations].includes(fnVar)
724
+ );
725
+
726
+ if (hasMatch) {
727
+ MessageFormatter.success(`Found function at: ${fullPath}`, { prefix: "Functions" });
728
+ return fullPath;
729
+ }
730
+
731
+ queue.push(fullPath);
732
+ }
733
+ }
734
+ } catch (error) {
735
+ MessageFormatter.warning(`Error reading directory ${currentPath}: ${error}`, { prefix: "Functions" });
736
+ }
737
+ }
738
+
739
+ return null;
740
+ }
741
+
742
+
743
+ private async selectFunctions(
744
+ message: string,
745
+ multiple: boolean = true,
746
+ includeRemote: boolean = false
747
+ ): Promise<AppwriteFunction[]> {
748
+ const remoteFunctions = includeRemote
749
+ ? await listFunctions(this.controller!.appwriteServer!, [
750
+ Query.limit(1000),
751
+ ])
752
+ : { functions: [] };
753
+ const localFunctions = this.getLocalFunctions();
754
+
755
+ // Combine functions, preferring local ones
756
+ const allFunctions = [
757
+ ...localFunctions,
758
+ ...remoteFunctions.functions.filter(
759
+ (rf: any) => !localFunctions.some((lf) => lf.name === rf.name || lf.$id === rf.$id)
760
+ ),
761
+ ];
762
+
763
+ const { selectedFunctions } = await inquirer.prompt([
764
+ {
765
+ type: multiple ? "checkbox" : "list",
766
+ name: "selectedFunctions",
767
+ message,
768
+ choices: allFunctions.map((f) => ({
769
+ name: `${f.name} (${f.$id})${
770
+ localFunctions.some((lf) => lf.name === f.name || lf.$id === f.$id)
771
+ ? " (Local)"
772
+ : " (Remote)"
773
+ }`,
774
+ value: f,
775
+ })),
776
+ loop: true,
777
+ },
778
+ ]);
779
+
780
+ return multiple ? selectedFunctions : [selectedFunctions];
781
+ }
782
+
783
+ private getLocalFunctions(): AppwriteFunction[] {
784
+ const configFunctions = this.controller!.config?.functions || [];
785
+ return configFunctions.map((f) => ({
786
+ $id: f.$id || ulid(),
787
+ $createdAt: DateTime.now().toISO(),
788
+ $updatedAt: DateTime.now().toISO(),
789
+ name: f.name,
790
+ runtime: f.runtime,
791
+ execute: f.execute || ["any"],
792
+ events: f.events || [],
793
+ schedule: f.schedule || "",
794
+ timeout: f.timeout || 15,
795
+ ignore: f.ignore,
796
+ enabled: f.enabled !== false,
797
+ logging: f.logging !== false,
798
+ entrypoint: f.entrypoint || "src/main.ts",
799
+ commands: f.commands || "npm install",
800
+ scopes: f.scopes || [], // Add scopes
801
+ path: f.dirPath || `functions/${f.name}`,
802
+ dirPath: f.dirPath, // Preserve original dirPath
803
+ installationId: f.installationId || "",
804
+ providerRepositoryId: f.providerRepositoryId || "",
805
+ providerBranch: f.providerBranch || "",
806
+ providerSilentMode: f.providerSilentMode || false,
807
+ providerRootDirectory: f.providerRootDirectory || "",
808
+ ...(f.specification ? { specification: f.specification } : {}),
809
+ ...(f.predeployCommands
810
+ ? { predeployCommands: f.predeployCommands }
811
+ : {}),
812
+ ...(f.deployDir ? { deployDir: f.deployDir } : {}),
813
+ }));
814
+ }
815
+ private async selectBuckets(
816
+ buckets: Models.Bucket[],
817
+ message: string,
818
+ multiSelect = true
819
+ ): Promise<Models.Bucket[]> {
820
+ const choices = buckets.map((bucket) => ({
821
+ name: bucket.name,
822
+ value: bucket,
823
+ }));
824
+
825
+ const { selectedBuckets } = await inquirer.prompt([
826
+ {
827
+ type: multiSelect ? "checkbox" : "list",
828
+ name: "selectedBuckets",
829
+ message: chalk.blue(message),
830
+ choices,
831
+ loop: false,
832
+ pageSize: 10,
833
+ },
834
+ ]);
835
+
836
+ return selectedBuckets;
837
+ }
838
+
839
+
840
+ private async configureBuckets(
841
+ config: AppwriteConfig,
842
+ databases?: ConfigDatabases
843
+ ): Promise<AppwriteConfig> {
844
+ const { storage } = this.controller!;
845
+ if (!storage) {
846
+ throw new Error(
847
+ "Storage is not initialized. Is the config file correct and created?"
848
+ );
849
+ }
850
+
851
+ const allBuckets = await listBuckets(storage);
852
+
853
+ // If there are no buckets, ask to create one for each database
854
+ if (allBuckets.total === 0) {
855
+ const databasesToUse = databases ?? config.databases;
856
+ for (const database of databasesToUse) {
857
+ // If database has bucket config in local config, use that
858
+ const localDatabase = this.controller!.config?.databases.find(
859
+ (db) => db.name === database.name
860
+ );
861
+ if (localDatabase?.bucket) {
862
+ database.bucket = localDatabase.bucket;
863
+ continue;
864
+ }
865
+ const { wantCreateBucket } = await inquirer.prompt([
866
+ {
867
+ type: "confirm",
868
+ name: "wantCreateBucket",
869
+ message: chalk.blue(
870
+ `There are no buckets. Do you want to create a bucket for the database "${database.name}"?`
871
+ ),
872
+ default: true,
873
+ },
874
+ ]);
875
+ if (wantCreateBucket) {
876
+ const createdBucket = await this.createNewBucket(
877
+ storage,
878
+ database.name
879
+ );
880
+ database.bucket = {
881
+ ...createdBucket,
882
+ compression: createdBucket.compression as Compression,
883
+ };
884
+ }
885
+ }
886
+ return config;
887
+ }
888
+
889
+ // Configure global buckets
890
+ let globalBuckets: Models.Bucket[] = [];
891
+ if (allBuckets.total > 0) {
892
+ globalBuckets = await this.selectBuckets(
893
+ allBuckets.buckets,
894
+ "Select global buckets (buckets that are not associated with any specific database):",
895
+ true
896
+ );
897
+
898
+ config.buckets = globalBuckets.map((bucket) => ({
899
+ $id: bucket.$id,
900
+ name: bucket.name,
901
+ enabled: bucket.enabled,
902
+ maximumFileSize: bucket.maximumFileSize,
903
+ allowedFileExtensions: bucket.allowedFileExtensions,
904
+ compression: bucket.compression as Compression,
905
+ encryption: bucket.encryption,
906
+ antivirus: bucket.antivirus,
907
+ }));
908
+ } else {
909
+ config.buckets = [];
910
+ }
911
+
912
+ // Configure database-specific buckets
913
+ for (const database of config.databases) {
914
+ const { assignBucket } = await inquirer.prompt([
915
+ {
916
+ type: "confirm",
917
+ name: "assignBucket",
918
+ message: `Do you want to assign or create a bucket for the database "${database.name}"?`,
919
+ default: false,
920
+ },
921
+ ]);
922
+
923
+ if (assignBucket) {
924
+ const { action } = await inquirer.prompt([
925
+ {
926
+ type: "list",
927
+ name: "action",
928
+ message: `Choose an action for the database "${database.name}":`,
929
+ choices: [
930
+ { name: "Assign existing bucket", value: "assign" },
931
+ { name: "Create new bucket", value: "create" },
932
+ ],
933
+ },
934
+ ]);
935
+
936
+ if (action === "assign") {
937
+ const selectedBuckets = await this.selectBuckets(
938
+ allBuckets.buckets.filter(
939
+ (b) => !globalBuckets.some((gb) => gb.$id === b.$id)
940
+ ),
941
+ `Select a bucket for the database "${database.name}":`,
942
+ false // multiSelect = false
943
+ );
944
+
945
+ if (selectedBuckets.length > 0) {
946
+ const selectedBucket = selectedBuckets[0];
947
+ database.bucket = {
948
+ $id: selectedBucket.$id,
949
+ name: selectedBucket.name,
950
+ enabled: selectedBucket.enabled,
951
+ maximumFileSize: selectedBucket.maximumFileSize,
952
+ allowedFileExtensions: selectedBucket.allowedFileExtensions,
953
+ compression: selectedBucket.compression as Compression,
954
+ encryption: selectedBucket.encryption,
955
+ antivirus: selectedBucket.antivirus,
956
+ permissions: selectedBucket.$permissions.map((p) =>
957
+ permissionSchema.parse(p)
958
+ ),
959
+ };
960
+ }
961
+ } else if (action === "create") {
962
+ const createdBucket = await this.createNewBucket(
963
+ storage,
964
+ database.name
965
+ );
966
+ database.bucket = {
967
+ ...createdBucket,
968
+ compression: createdBucket.compression as Compression,
969
+ };
970
+ }
971
+ }
972
+ }
973
+
974
+ return config;
975
+ }
976
+
977
+ private async createNewBucket(
978
+ storage: Storage,
979
+ databaseName: string
980
+ ): Promise<Models.Bucket> {
981
+ const {
982
+ bucketName,
983
+ bucketEnabled,
984
+ bucketMaximumFileSize,
985
+ bucketAllowedFileExtensions,
986
+ bucketFileSecurity,
987
+ bucketCompression,
988
+ bucketCompressionType,
989
+ bucketEncryption,
990
+ bucketAntivirus,
991
+ bucketId,
992
+ } = await inquirer.prompt([
993
+ {
994
+ type: "input",
995
+ name: "bucketName",
996
+ message: `Enter the name of the bucket for database "${databaseName}":`,
997
+ default: `${databaseName}-bucket`,
998
+ },
999
+ {
1000
+ type: "confirm",
1001
+ name: "bucketEnabled",
1002
+ message: "Is the bucket enabled?",
1003
+ default: true,
1004
+ },
1005
+ {
1006
+ type: "confirm",
1007
+ name: "bucketFileSecurity",
1008
+ message: "Do you want to enable file security for the bucket?",
1009
+ default: false,
1010
+ },
1011
+ {
1012
+ type: "number",
1013
+ name: "bucketMaximumFileSize",
1014
+ message: "Enter the maximum file size for the bucket (MB):",
1015
+ default: 1000000,
1016
+ },
1017
+ {
1018
+ type: "input",
1019
+ name: "bucketAllowedFileExtensions",
1020
+ message:
1021
+ "Enter the allowed file extensions for the bucket (comma separated):",
1022
+ default: "",
1023
+ },
1024
+ {
1025
+ type: "confirm",
1026
+ name: "bucketCompression",
1027
+ message: "Do you want to enable compression for the bucket?",
1028
+ default: false,
1029
+ },
1030
+ {
1031
+ type: "list",
1032
+ name: "bucketCompressionType",
1033
+ message: "Select the compression type for the bucket:",
1034
+ choices: Object.values(Compression),
1035
+ default: Compression.None,
1036
+ when: (answers) => answers.bucketCompression,
1037
+ },
1038
+ {
1039
+ type: "confirm",
1040
+ name: "bucketEncryption",
1041
+ message: "Do you want to enable encryption for the bucket?",
1042
+ default: false,
1043
+ },
1044
+ {
1045
+ type: "confirm",
1046
+ name: "bucketAntivirus",
1047
+ message: "Do you want to enable antivirus for the bucket?",
1048
+ default: false,
1049
+ },
1050
+ {
1051
+ type: "input",
1052
+ name: "bucketId",
1053
+ message: "Enter the ID of the bucket (or empty for auto-generation):",
1054
+ },
1055
+ ]);
1056
+
1057
+ return await createBucket(
1058
+ storage,
1059
+ {
1060
+ name: bucketName,
1061
+ $permissions: [],
1062
+ enabled: bucketEnabled,
1063
+ fileSecurity: bucketFileSecurity,
1064
+ maximumFileSize: bucketMaximumFileSize * 1024 * 1024,
1065
+ allowedFileExtensions:
1066
+ bucketAllowedFileExtensions.length > 0
1067
+ ? bucketAllowedFileExtensions?.split(",")
1068
+ : [],
1069
+ compression: bucketCompressionType as Compression,
1070
+ encryption: bucketEncryption,
1071
+ antivirus: bucketAntivirus,
1072
+ },
1073
+ bucketId.length > 0 ? bucketId : ulid()
1074
+ );
1075
+ }
1076
+
1077
+
1078
+
1079
+ private getLocalCollections(): (Models.Collection & {
1080
+ _isFromTablesDir?: boolean;
1081
+ _sourceFolder?: string;
1082
+ databaseId?: string;
1083
+ })[] {
1084
+ const configCollections = [
1085
+ ...(this.controller!.config?.collections || []),
1086
+ ...(this.controller!.config?.tables || [])
1087
+ ];
1088
+ // @ts-expect-error - appwrite invalid types
1089
+ return configCollections.map((c) => ({
1090
+ $id: c.$id || ulid(),
1091
+ $createdAt: DateTime.now().toISO(),
1092
+ $updatedAt: DateTime.now().toISO(),
1093
+ name: c.name,
1094
+ enabled: c.enabled || true,
1095
+ documentSecurity: c.documentSecurity || false,
1096
+ attributes: c.attributes || [],
1097
+ indexes: c.indexes || [],
1098
+ $permissions: PermissionToAppwritePermission(c.$permissions) || [],
1099
+ databaseId: c.databaseId,
1100
+ _isFromTablesDir: (c as any)._isFromTablesDir || false,
1101
+ _sourceFolder: (c as any)._isFromTablesDir ? 'tables' : 'collections',
1102
+ }));
1103
+ }
1104
+
1105
+ private getLocalDatabases(): Models.Database[] {
1106
+ const configDatabases = this.controller!.config?.databases || [];
1107
+ return configDatabases.map((db) => ({
1108
+ $id: db.$id || ulid(),
1109
+ $createdAt: DateTime.now().toISO(),
1110
+ $updatedAt: DateTime.now().toISO(),
1111
+ name: db.name,
1112
+ enabled: true,
1113
+ type: "tablesdb" as DatabaseType,
1114
+ }));
1115
+ }
1116
+
1117
+
1118
+ /**
1119
+ * Extract session information from current controller for preservation
1120
+ */
1121
+ private async extractSessionFromController(): Promise<{
1122
+ appwriteEndpoint: string;
1123
+ appwriteProject: string;
1124
+ appwriteKey?: string;
1125
+ sessionCookie?: string;
1126
+ sessionMetadata?: any;
1127
+ } | undefined> {
1128
+ if (!this.controller?.config) {
1129
+ return undefined;
1130
+ }
1131
+
1132
+ const sessionInfo = await this.controller.getSessionInfo();
1133
+ const config = this.controller.config;
1134
+
1135
+ if (!config.appwriteEndpoint || !config.appwriteProject) {
1136
+ return undefined;
1137
+ }
1138
+
1139
+ const result: any = {
1140
+ appwriteEndpoint: config.appwriteEndpoint,
1141
+ appwriteProject: config.appwriteProject,
1142
+ appwriteKey: config.appwriteKey
1143
+ };
1144
+
1145
+ // Add session data if available
1146
+ if (sessionInfo.hasSession) {
1147
+ result.sessionCookie = (this.controller as any).sessionCookie;
1148
+ result.sessionMetadata = (this.controller as any).sessionMetadata;
1149
+ }
1150
+
1151
+ return result;
1152
+ }
1153
+
1154
+
1155
+ private async detectConfigurationType(): Promise<void> {
1156
+ try {
1157
+ // Check for YAML config first
1158
+ const yamlConfigPath = findYamlConfig(this.currentDir);
1159
+ if (yamlConfigPath) {
1160
+ this.isUsingTypeScriptConfig = false;
1161
+ MessageFormatter.info("Using YAML configuration", { prefix: "Config" });
1162
+ return;
1163
+ }
1164
+
1165
+ // Then check for TypeScript config
1166
+ const configPath = findAppwriteConfig(this.currentDir);
1167
+ if (configPath) {
1168
+ const tsConfigPath = join(configPath, 'appwriteConfig.ts');
1169
+ if (fs.existsSync(tsConfigPath)) {
1170
+ this.isUsingTypeScriptConfig = true;
1171
+ MessageFormatter.info("TypeScript configuration detected", { prefix: "Config" });
1172
+ MessageFormatter.info("Consider migrating to YAML for better organization", { prefix: "Config" });
1173
+ return;
1174
+ }
1175
+ }
1176
+
1177
+ // No config found
1178
+ this.isUsingTypeScriptConfig = false;
1179
+ MessageFormatter.info("No configuration file found", { prefix: "Config" });
1180
+ } catch (error) {
1181
+ // Silently handle detection errors and continue
1182
+ this.isUsingTypeScriptConfig = false;
1183
+ }
1184
+ }
1185
+
1186
+ private buildChoicesList(): string[] {
1187
+ const allChoices = Object.values(CHOICES);
1188
+
1189
+ if (this.isUsingTypeScriptConfig) {
1190
+ // Place migration option at the top when TS config is detected
1191
+ return [
1192
+ CHOICES.MIGRATE_CONFIG,
1193
+ ...allChoices.filter(choice => choice !== CHOICES.MIGRATE_CONFIG)
1194
+ ];
1195
+ } else {
1196
+ // Hide migration option when using YAML config
1197
+ return allChoices.filter(choice => choice !== CHOICES.MIGRATE_CONFIG);
1198
+ }
1199
+ }
1200
+
1201
+ }