appwrite-utils-cli 1.11.0 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (250) hide show
  1. package/{src/adapters/index.ts → dist/adapters/index.d.ts} +0 -1
  2. package/dist/adapters/index.js +10 -0
  3. package/dist/backups/operations/bucketBackup.d.ts +19 -0
  4. package/dist/backups/operations/bucketBackup.js +197 -0
  5. package/dist/backups/operations/collectionBackup.d.ts +30 -0
  6. package/dist/backups/operations/collectionBackup.js +201 -0
  7. package/dist/backups/operations/comprehensiveBackup.d.ts +25 -0
  8. package/dist/backups/operations/comprehensiveBackup.js +238 -0
  9. package/dist/backups/schemas/bucketManifest.d.ts +93 -0
  10. package/dist/backups/schemas/bucketManifest.js +33 -0
  11. package/dist/backups/schemas/comprehensiveManifest.d.ts +108 -0
  12. package/dist/backups/schemas/comprehensiveManifest.js +32 -0
  13. package/dist/backups/tracking/centralizedTracking.d.ts +34 -0
  14. package/dist/backups/tracking/centralizedTracking.js +274 -0
  15. package/dist/cli/commands/configCommands.d.ts +8 -0
  16. package/dist/cli/commands/configCommands.js +210 -0
  17. package/dist/cli/commands/databaseCommands.d.ts +14 -0
  18. package/dist/cli/commands/databaseCommands.js +696 -0
  19. package/dist/cli/commands/functionCommands.d.ts +7 -0
  20. package/dist/cli/commands/functionCommands.js +330 -0
  21. package/dist/cli/commands/importFileCommands.d.ts +7 -0
  22. package/dist/cli/commands/importFileCommands.js +674 -0
  23. package/dist/cli/commands/schemaCommands.d.ts +7 -0
  24. package/dist/cli/commands/schemaCommands.js +169 -0
  25. package/dist/cli/commands/storageCommands.d.ts +5 -0
  26. package/dist/cli/commands/storageCommands.js +142 -0
  27. package/dist/cli/commands/transferCommands.d.ts +5 -0
  28. package/dist/cli/commands/transferCommands.js +382 -0
  29. package/dist/collections/columns.d.ts +13 -0
  30. package/dist/collections/columns.js +1339 -0
  31. package/dist/collections/indexes.d.ts +12 -0
  32. package/dist/collections/indexes.js +215 -0
  33. package/dist/collections/methods.d.ts +19 -0
  34. package/dist/collections/methods.js +605 -0
  35. package/dist/collections/tableOperations.d.ts +87 -0
  36. package/dist/collections/tableOperations.js +466 -0
  37. package/dist/collections/transferOperations.d.ts +8 -0
  38. package/dist/collections/transferOperations.js +411 -0
  39. package/dist/collections/wipeOperations.d.ts +17 -0
  40. package/dist/collections/wipeOperations.js +306 -0
  41. package/dist/databases/methods.d.ts +6 -0
  42. package/dist/databases/methods.js +35 -0
  43. package/dist/databases/setup.d.ts +5 -0
  44. package/dist/databases/setup.js +45 -0
  45. package/dist/examples/yamlTerminologyExample.d.ts +42 -0
  46. package/dist/examples/yamlTerminologyExample.js +272 -0
  47. package/dist/functions/deployments.d.ts +4 -0
  48. package/dist/functions/deployments.js +146 -0
  49. package/dist/functions/fnConfigDiscovery.d.ts +3 -0
  50. package/dist/functions/fnConfigDiscovery.js +108 -0
  51. package/dist/functions/methods.d.ts +16 -0
  52. package/dist/functions/methods.js +174 -0
  53. package/dist/init.d.ts +2 -0
  54. package/dist/init.js +57 -0
  55. package/dist/interactiveCLI.d.ts +36 -0
  56. package/dist/interactiveCLI.js +952 -0
  57. package/dist/main.d.ts +2 -0
  58. package/dist/main.js +1125 -0
  59. package/dist/migrations/afterImportActions.d.ts +17 -0
  60. package/dist/migrations/afterImportActions.js +305 -0
  61. package/dist/migrations/appwriteToX.d.ts +211 -0
  62. package/dist/migrations/appwriteToX.js +493 -0
  63. package/dist/migrations/comprehensiveTransfer.d.ts +147 -0
  64. package/dist/migrations/comprehensiveTransfer.js +1315 -0
  65. package/dist/migrations/dataLoader.d.ts +755 -0
  66. package/dist/migrations/dataLoader.js +1272 -0
  67. package/dist/migrations/importController.d.ts +25 -0
  68. package/dist/migrations/importController.js +283 -0
  69. package/dist/migrations/importDataActions.d.ts +50 -0
  70. package/dist/migrations/importDataActions.js +230 -0
  71. package/dist/migrations/relationships.d.ts +29 -0
  72. package/dist/migrations/relationships.js +203 -0
  73. package/dist/migrations/services/DataTransformationService.d.ts +55 -0
  74. package/dist/migrations/services/DataTransformationService.js +158 -0
  75. package/dist/migrations/services/FileHandlerService.d.ts +75 -0
  76. package/dist/migrations/services/FileHandlerService.js +236 -0
  77. package/dist/migrations/services/ImportOrchestrator.d.ts +99 -0
  78. package/dist/migrations/services/ImportOrchestrator.js +493 -0
  79. package/dist/migrations/services/RateLimitManager.d.ts +138 -0
  80. package/dist/migrations/services/RateLimitManager.js +279 -0
  81. package/dist/migrations/services/RelationshipResolver.d.ts +120 -0
  82. package/dist/migrations/services/RelationshipResolver.js +332 -0
  83. package/dist/migrations/services/UserMappingService.d.ts +109 -0
  84. package/dist/migrations/services/UserMappingService.js +277 -0
  85. package/dist/migrations/services/ValidationService.d.ts +74 -0
  86. package/dist/migrations/services/ValidationService.js +260 -0
  87. package/dist/migrations/transfer.d.ts +30 -0
  88. package/dist/migrations/transfer.js +661 -0
  89. package/dist/migrations/yaml/YamlImportConfigLoader.d.ts +131 -0
  90. package/dist/migrations/yaml/YamlImportConfigLoader.js +383 -0
  91. package/dist/migrations/yaml/YamlImportIntegration.d.ts +93 -0
  92. package/dist/migrations/yaml/YamlImportIntegration.js +341 -0
  93. package/dist/migrations/yaml/generateImportSchemas.d.ts +30 -0
  94. package/dist/migrations/yaml/generateImportSchemas.js +1327 -0
  95. package/dist/schemas/authUser.d.ts +24 -0
  96. package/dist/schemas/authUser.js +17 -0
  97. package/dist/setup.d.ts +2 -0
  98. package/{src/setup.ts → dist/setup.js} +0 -3
  99. package/dist/setupCommands.d.ts +58 -0
  100. package/dist/setupCommands.js +489 -0
  101. package/dist/setupController.d.ts +9 -0
  102. package/dist/setupController.js +34 -0
  103. package/dist/shared/backupMetadataSchema.d.ts +94 -0
  104. package/dist/shared/backupMetadataSchema.js +38 -0
  105. package/dist/shared/backupTracking.d.ts +18 -0
  106. package/dist/shared/backupTracking.js +176 -0
  107. package/dist/shared/confirmationDialogs.d.ts +75 -0
  108. package/dist/shared/confirmationDialogs.js +236 -0
  109. package/dist/shared/migrationHelpers.d.ts +61 -0
  110. package/dist/shared/migrationHelpers.js +145 -0
  111. package/{src/shared/operationLogger.ts → dist/shared/operationLogger.d.ts} +1 -11
  112. package/dist/shared/operationLogger.js +12 -0
  113. package/dist/shared/operationQueue.d.ts +40 -0
  114. package/dist/shared/operationQueue.js +310 -0
  115. package/dist/shared/operationsTable.d.ts +26 -0
  116. package/dist/shared/operationsTable.js +287 -0
  117. package/dist/shared/operationsTableSchema.d.ts +48 -0
  118. package/dist/shared/operationsTableSchema.js +35 -0
  119. package/dist/shared/progressManager.d.ts +62 -0
  120. package/dist/shared/progressManager.js +215 -0
  121. package/dist/shared/relationshipExtractor.d.ts +56 -0
  122. package/dist/shared/relationshipExtractor.js +138 -0
  123. package/dist/shared/selectionDialogs.d.ts +220 -0
  124. package/dist/shared/selectionDialogs.js +588 -0
  125. package/dist/storage/backupCompression.d.ts +20 -0
  126. package/dist/storage/backupCompression.js +67 -0
  127. package/dist/storage/methods.d.ts +44 -0
  128. package/dist/storage/methods.js +475 -0
  129. package/dist/storage/schemas.d.ts +842 -0
  130. package/dist/storage/schemas.js +175 -0
  131. package/dist/tables/indexManager.d.ts +65 -0
  132. package/dist/tables/indexManager.js +294 -0
  133. package/{src/types.ts → dist/types.d.ts} +1 -6
  134. package/dist/types.js +3 -0
  135. package/dist/users/methods.d.ts +16 -0
  136. package/dist/users/methods.js +276 -0
  137. package/dist/utils/configMigration.d.ts +1 -0
  138. package/dist/utils/configMigration.js +261 -0
  139. package/dist/utils/index.js +2 -0
  140. package/dist/utils/loadConfigs.d.ts +50 -0
  141. package/dist/utils/loadConfigs.js +357 -0
  142. package/dist/utils/setupFiles.d.ts +4 -0
  143. package/dist/utils/setupFiles.js +1190 -0
  144. package/dist/utilsController.d.ts +114 -0
  145. package/dist/utilsController.js +898 -0
  146. package/package.json +6 -3
  147. package/CHANGELOG.md +0 -35
  148. package/CONFIG_TODO.md +0 -1189
  149. package/SELECTION_DIALOGS.md +0 -146
  150. package/SERVICE_IMPLEMENTATION_REPORT.md +0 -462
  151. package/scripts/copy-templates.ts +0 -23
  152. package/src/backups/operations/bucketBackup.ts +0 -277
  153. package/src/backups/operations/collectionBackup.ts +0 -310
  154. package/src/backups/operations/comprehensiveBackup.ts +0 -342
  155. package/src/backups/schemas/bucketManifest.ts +0 -78
  156. package/src/backups/schemas/comprehensiveManifest.ts +0 -76
  157. package/src/backups/tracking/centralizedTracking.ts +0 -352
  158. package/src/cli/commands/configCommands.ts +0 -265
  159. package/src/cli/commands/databaseCommands.ts +0 -931
  160. package/src/cli/commands/functionCommands.ts +0 -419
  161. package/src/cli/commands/importFileCommands.ts +0 -815
  162. package/src/cli/commands/schemaCommands.ts +0 -200
  163. package/src/cli/commands/storageCommands.ts +0 -151
  164. package/src/cli/commands/transferCommands.ts +0 -454
  165. package/src/collections/attributes.ts.backup +0 -1555
  166. package/src/collections/columns.ts +0 -2025
  167. package/src/collections/indexes.ts +0 -350
  168. package/src/collections/methods.ts +0 -714
  169. package/src/collections/tableOperations.ts +0 -542
  170. package/src/collections/transferOperations.ts +0 -589
  171. package/src/collections/wipeOperations.ts +0 -449
  172. package/src/databases/methods.ts +0 -49
  173. package/src/databases/setup.ts +0 -77
  174. package/src/examples/yamlTerminologyExample.ts +0 -346
  175. package/src/functions/deployments.ts +0 -221
  176. package/src/functions/fnConfigDiscovery.ts +0 -103
  177. package/src/functions/methods.ts +0 -284
  178. package/src/init.ts +0 -62
  179. package/src/interactiveCLI.ts +0 -1201
  180. package/src/main.ts +0 -1517
  181. package/src/migrations/afterImportActions.ts +0 -579
  182. package/src/migrations/appwriteToX.ts +0 -668
  183. package/src/migrations/comprehensiveTransfer.ts +0 -2285
  184. package/src/migrations/dataLoader.ts +0 -1729
  185. package/src/migrations/importController.ts +0 -440
  186. package/src/migrations/importDataActions.ts +0 -315
  187. package/src/migrations/relationships.ts +0 -333
  188. package/src/migrations/services/DataTransformationService.ts +0 -196
  189. package/src/migrations/services/FileHandlerService.ts +0 -311
  190. package/src/migrations/services/ImportOrchestrator.ts +0 -675
  191. package/src/migrations/services/RateLimitManager.ts +0 -363
  192. package/src/migrations/services/RelationshipResolver.ts +0 -461
  193. package/src/migrations/services/UserMappingService.ts +0 -345
  194. package/src/migrations/services/ValidationService.ts +0 -349
  195. package/src/migrations/transfer.ts +0 -1113
  196. package/src/migrations/yaml/YamlImportConfigLoader.ts +0 -439
  197. package/src/migrations/yaml/YamlImportIntegration.ts +0 -446
  198. package/src/migrations/yaml/generateImportSchemas.ts +0 -1354
  199. package/src/schemas/authUser.ts +0 -23
  200. package/src/setupCommands.ts +0 -602
  201. package/src/setupController.ts +0 -43
  202. package/src/shared/backupMetadataSchema.ts +0 -93
  203. package/src/shared/backupTracking.ts +0 -211
  204. package/src/shared/confirmationDialogs.ts +0 -327
  205. package/src/shared/migrationHelpers.ts +0 -232
  206. package/src/shared/operationQueue.ts +0 -376
  207. package/src/shared/operationsTable.ts +0 -338
  208. package/src/shared/operationsTableSchema.ts +0 -60
  209. package/src/shared/progressManager.ts +0 -278
  210. package/src/shared/relationshipExtractor.ts +0 -214
  211. package/src/shared/selectionDialogs.ts +0 -802
  212. package/src/storage/backupCompression.ts +0 -88
  213. package/src/storage/methods.ts +0 -711
  214. package/src/storage/schemas.ts +0 -205
  215. package/src/tables/indexManager.ts +0 -409
  216. package/src/types/node-appwrite-tablesdb.d.ts +0 -44
  217. package/src/users/methods.ts +0 -358
  218. package/src/utils/configMigration.ts +0 -348
  219. package/src/utils/loadConfigs.ts +0 -457
  220. package/src/utils/setupFiles.ts +0 -1236
  221. package/src/utilsController.ts +0 -1263
  222. package/tests/README.md +0 -497
  223. package/tests/adapters/AdapterFactory.test.ts +0 -277
  224. package/tests/integration/syncOperations.test.ts +0 -463
  225. package/tests/jest.config.js +0 -25
  226. package/tests/migration/configMigration.test.ts +0 -546
  227. package/tests/setup.ts +0 -62
  228. package/tests/testUtils.ts +0 -340
  229. package/tests/utils/loadConfigs.test.ts +0 -350
  230. package/tests/validation/configValidation.test.ts +0 -412
  231. package/tsconfig.json +0 -44
  232. /package/{src → dist}/functions/templates/count-docs-in-collection/README.md +0 -0
  233. /package/{src → dist}/functions/templates/count-docs-in-collection/src/main.ts +0 -0
  234. /package/{src → dist}/functions/templates/count-docs-in-collection/src/request.ts +0 -0
  235. /package/{src → dist}/functions/templates/hono-typescript/README.md +0 -0
  236. /package/{src → dist}/functions/templates/hono-typescript/src/adapters/request.ts +0 -0
  237. /package/{src → dist}/functions/templates/hono-typescript/src/adapters/response.ts +0 -0
  238. /package/{src → dist}/functions/templates/hono-typescript/src/app.ts +0 -0
  239. /package/{src → dist}/functions/templates/hono-typescript/src/context.ts +0 -0
  240. /package/{src → dist}/functions/templates/hono-typescript/src/main.ts +0 -0
  241. /package/{src → dist}/functions/templates/hono-typescript/src/middleware/appwrite.ts +0 -0
  242. /package/{src → dist}/functions/templates/typescript-node/README.md +0 -0
  243. /package/{src → dist}/functions/templates/typescript-node/src/context.ts +0 -0
  244. /package/{src → dist}/functions/templates/typescript-node/src/main.ts +0 -0
  245. /package/{src → dist}/functions/templates/uv/README.md +0 -0
  246. /package/{src → dist}/functions/templates/uv/pyproject.toml +0 -0
  247. /package/{src → dist}/functions/templates/uv/src/__init__.py +0 -0
  248. /package/{src → dist}/functions/templates/uv/src/context.py +0 -0
  249. /package/{src → dist}/functions/templates/uv/src/main.py +0 -0
  250. /package/{src/utils/index.ts → dist/utils/index.d.ts} +0 -0
@@ -1,352 +0,0 @@
1
- import type { DatabaseAdapter } from 'appwrite-utils-helpers';
2
- import { logger } from 'appwrite-utils-helpers';
3
- import { tryAwaitWithRetry } from "appwrite-utils-helpers";
4
- import { Query, ID } from "node-appwrite";
5
- import {
6
- BACKUP_TABLE_ID,
7
- BACKUP_TABLE_NAME,
8
- type BackupMetadata,
9
- type BackupType,
10
- BackupMetadataSchema
11
- } from "../../shared/backupMetadataSchema.js";
12
-
13
- /**
14
- * Centralized backup tracking system
15
- *
16
- * All backups (databases, buckets, comprehensive) are tracked in a single
17
- * database selected by the user, providing a centralized backup registry.
18
- */
19
-
20
- /**
21
- * Checks if backup tracking table exists in database
22
- */
23
- async function tableExists(
24
- db: DatabaseAdapter,
25
- databaseId: string
26
- ): Promise<boolean> {
27
- try {
28
- await db.getTable({ databaseId, tableId: BACKUP_TABLE_ID });
29
- return true;
30
- } catch (error) {
31
- return false;
32
- }
33
- }
34
-
35
- /**
36
- * Creates the centralized backup tracking table with enhanced schema
37
- */
38
- export async function createCentralizedBackupTrackingTable(
39
- db: DatabaseAdapter,
40
- databaseId: string
41
- ): Promise<void> {
42
- // Check if table already exists
43
- const exists = await tableExists(db, databaseId);
44
-
45
- if (exists) {
46
- // Table exists - validate its schema
47
- try {
48
- const tableData = await db.getTable({ databaseId, tableId: BACKUP_TABLE_ID });
49
- const existingAttrs = ((tableData.data as any).attributes || []);
50
-
51
- // Expected attribute keys from our schema
52
- const expectedAttrKeys = [
53
- "backupType", "backupId", "manifestFileId", "format", "sizeBytes",
54
- "databaseId", "bucketId", "comprehensiveBackupId",
55
- "collections", "documents", "fileCount",
56
- "status", "error",
57
- "restoredAt", "restorationStatus", "restorationError"
58
- ];
59
-
60
- // Existing attribute keys
61
- const existingAttrKeys = new Set(existingAttrs.map((a: any) => a.key));
62
-
63
- // Check if they match
64
- const hasAllAttributes = expectedAttrKeys.every(key => existingAttrKeys.has(key));
65
-
66
- // Check if any have wrong sizes (old 10000 vs new 1000)
67
- const hasWrongSizes = existingAttrs.some((a: any) =>
68
- (a.key === 'error' || a.key === 'restorationError') && a.size === 10000
69
- );
70
-
71
- if (!hasAllAttributes || hasWrongSizes) {
72
- logger.warn("Backup table exists but has incorrect schema - recreating", {
73
- tableId: BACKUP_TABLE_ID,
74
- hasAllAttributes,
75
- hasWrongSizes,
76
- existingCount: existingAttrKeys.size,
77
- expectedCount: expectedAttrKeys.length
78
- });
79
-
80
- // Delete the old table
81
- await db.deleteTable({ databaseId, tableId: BACKUP_TABLE_ID });
82
-
83
- logger.info("Old backup table deleted, will recreate with correct schema");
84
- } else {
85
- logger.debug("Backup table exists with correct schema", {
86
- tableId: BACKUP_TABLE_ID,
87
- attributeCount: existingAttrKeys.size
88
- });
89
- return; // Table is good, no need to recreate
90
- }
91
- } catch (error) {
92
- // Error checking table - continue to create
93
- logger.debug("Error checking existing table, will attempt to create", {
94
- error: error instanceof Error ? error.message : String(error)
95
- });
96
- }
97
- }
98
-
99
- // Create table (either first time or after deletion)
100
- logger.info("Creating centralized backup tracking table", {
101
- databaseId,
102
- tableId: BACKUP_TABLE_ID
103
- });
104
-
105
- await tryAwaitWithRetry(async () => {
106
- await db.createTable({
107
- databaseId,
108
- id: BACKUP_TABLE_ID,
109
- name: BACKUP_TABLE_NAME,
110
- permissions: [],
111
- documentSecurity: false,
112
- enabled: true
113
- });
114
- });
115
-
116
- // Define all attributes for the enhanced schema
117
- const attributes = [
118
- // Core backup info
119
- { key: "backupType", type: "enum" as const, elements: ["database", "bucket", "comprehensive"], required: true },
120
- { key: "backupId", type: "string" as const, size: 50, required: true },
121
- { key: "manifestFileId", type: "string" as const, size: 50, required: false },
122
- { key: "format", type: "enum" as const, elements: ["json", "zip"], required: true },
123
- { key: "sizeBytes", type: "integer" as const, required: true },
124
-
125
- // Resource identification (optional, at least one present based on type)
126
- { key: "databaseId", type: "string" as const, size: 50, required: false },
127
- { key: "bucketId", type: "string" as const, size: 50, required: false },
128
- { key: "comprehensiveBackupId", type: "string" as const, size: 50, required: false },
129
-
130
- // Database-specific metrics
131
- { key: "collections", type: "integer" as const, required: false },
132
- { key: "documents", type: "integer" as const, required: false },
133
-
134
- // Bucket-specific metrics
135
- { key: "fileCount", type: "integer" as const, required: false },
136
-
137
- // Status tracking
138
- { key: "status", type: "enum" as const, elements: ["completed", "partial", "failed"], required: true },
139
- { key: "error", type: "string" as const, size: 1000, required: false },
140
-
141
- // Restoration tracking
142
- { key: "restoredAt", type: "string" as const, size: 50, required: false },
143
- { key: "restorationStatus", type: "enum" as const, elements: ["completed", "partial", "failed", "not_restored"], required: false },
144
- { key: "restorationError", type: "string" as const, size: 1000, required: false }
145
- ];
146
-
147
- // Create each attribute with retry logic
148
- // No need to check for existing attributes - table is freshly created or validated above
149
- for (const attr of attributes) {
150
- await tryAwaitWithRetry(async () => {
151
- await db.createAttribute({
152
- databaseId,
153
- tableId: BACKUP_TABLE_ID,
154
- ...attr
155
- });
156
- });
157
- }
158
-
159
- logger.info("Centralized backup tracking table created successfully", {
160
- databaseId,
161
- tableId: BACKUP_TABLE_ID,
162
- attributeCount: attributes.length
163
- });
164
- }
165
-
166
- /**
167
- * Records backup metadata in the centralized tracking table
168
- */
169
- export async function recordCentralizedBackup(
170
- db: DatabaseAdapter,
171
- trackingDatabaseId: string,
172
- metadata: Omit<BackupMetadata, '$id' | '$createdAt' | '$updatedAt'>
173
- ): Promise<BackupMetadata> {
174
- // Ensure tracking table exists with correct schema
175
- await createCentralizedBackupTrackingTable(db, trackingDatabaseId);
176
-
177
- // Create backup record with all fields
178
- // Table is guaranteed to have all attributes after createCentralizedBackupTrackingTable
179
- const result = await db.createRow({
180
- databaseId: trackingDatabaseId,
181
- tableId: BACKUP_TABLE_ID,
182
- id: ID.unique(),
183
- data: {
184
- // Core fields
185
- backupType: metadata.backupType,
186
- backupId: metadata.backupId,
187
- manifestFileId: metadata.manifestFileId || null,
188
- format: metadata.format,
189
- sizeBytes: metadata.sizeBytes,
190
-
191
- // Resource identification
192
- databaseId: metadata.databaseId || null,
193
- bucketId: metadata.bucketId || null,
194
- comprehensiveBackupId: metadata.comprehensiveBackupId || null,
195
-
196
- // Metrics
197
- collections: metadata.collections || null,
198
- documents: metadata.documents || null,
199
- fileCount: metadata.fileCount || null,
200
-
201
- // Status
202
- status: metadata.status,
203
- error: metadata.error || null,
204
-
205
- // Restoration
206
- restoredAt: metadata.restoredAt || null,
207
- restorationStatus: metadata.restorationStatus || 'not_restored',
208
- restorationError: metadata.restorationError || null
209
- }
210
- });
211
-
212
- logger.info("Recorded centralized backup metadata", {
213
- backupType: metadata.backupType,
214
- backupId: metadata.backupId,
215
- trackingDatabaseId
216
- });
217
-
218
- return result.data as BackupMetadata;
219
- }
220
-
221
- /**
222
- * Lists all backups of a specific type, sorted by creation date (newest first)
223
- */
224
- export async function listCentralizedBackups(
225
- db: DatabaseAdapter,
226
- trackingDatabaseId: string,
227
- options?: {
228
- backupType?: BackupType;
229
- resourceId?: string; // databaseId or bucketId
230
- limit?: number;
231
- }
232
- ): Promise<BackupMetadata[]> {
233
- try {
234
- const queries: string[] = [
235
- Query.orderDesc("$createdAt"),
236
- Query.limit(options?.limit || 100)
237
- ];
238
-
239
- // Filter by backup type if specified
240
- if (options?.backupType) {
241
- queries.push(Query.equal("backupType", options.backupType));
242
- }
243
-
244
- // Filter by resource ID if specified
245
- if (options?.resourceId) {
246
- if (options.backupType === 'database') {
247
- queries.push(Query.equal("databaseId", options.resourceId));
248
- } else if (options.backupType === 'bucket') {
249
- queries.push(Query.equal("bucketId", options.resourceId));
250
- }
251
- }
252
-
253
- const result = await db.listRows({
254
- databaseId: trackingDatabaseId,
255
- tableId: BACKUP_TABLE_ID,
256
- queries
257
- });
258
-
259
- return (result.rows || []) as BackupMetadata[];
260
- } catch (error) {
261
- logger.debug("No centralized backup tracking table found", { trackingDatabaseId });
262
- return [];
263
- }
264
- }
265
-
266
- /**
267
- * Gets a specific backup by its backup file ID
268
- */
269
- export async function getCentralizedBackup(
270
- db: DatabaseAdapter,
271
- trackingDatabaseId: string,
272
- backupId: string
273
- ): Promise<BackupMetadata | null> {
274
- try {
275
- const result = await db.listRows({
276
- databaseId: trackingDatabaseId,
277
- tableId: BACKUP_TABLE_ID,
278
- queries: [
279
- Query.equal("backupId", backupId),
280
- Query.limit(1)
281
- ]
282
- });
283
-
284
- if (result.rows && result.rows.length > 0) {
285
- return result.rows[0] as BackupMetadata;
286
- }
287
-
288
- return null;
289
- } catch (error) {
290
- logger.debug("Backup not found", { backupId, trackingDatabaseId });
291
- return null;
292
- }
293
- }
294
-
295
- /**
296
- * Updates restoration status for a backup
297
- */
298
- export async function updateRestorationStatus(
299
- db: DatabaseAdapter,
300
- trackingDatabaseId: string,
301
- backupRecordId: string,
302
- restorationData: {
303
- restoredAt: string;
304
- restorationStatus: 'completed' | 'partial' | 'failed';
305
- restorationError?: string;
306
- }
307
- ): Promise<void> {
308
- await db.updateRow({
309
- databaseId: trackingDatabaseId,
310
- tableId: BACKUP_TABLE_ID,
311
- id: backupRecordId,
312
- data: {
313
- restoredAt: restorationData.restoredAt,
314
- restorationStatus: restorationData.restorationStatus,
315
- restorationError: restorationData.restorationError || null
316
- }
317
- });
318
-
319
- logger.info("Updated restoration status", {
320
- backupRecordId,
321
- restorationStatus: restorationData.restorationStatus
322
- });
323
- }
324
-
325
- /**
326
- * Gets the most recent comprehensive backup
327
- */
328
- export async function getLastComprehensiveBackup(
329
- db: DatabaseAdapter,
330
- trackingDatabaseId: string
331
- ): Promise<BackupMetadata | null> {
332
- try {
333
- const result = await db.listRows({
334
- databaseId: trackingDatabaseId,
335
- tableId: BACKUP_TABLE_ID,
336
- queries: [
337
- Query.equal("backupType", "comprehensive"),
338
- Query.orderDesc("$createdAt"),
339
- Query.limit(1)
340
- ]
341
- });
342
-
343
- if (result.rows && result.rows.length > 0) {
344
- return result.rows[0] as BackupMetadata;
345
- }
346
-
347
- return null;
348
- } catch (error) {
349
- logger.debug("No comprehensive backup found", { trackingDatabaseId });
350
- return null;
351
- }
352
- }
@@ -1,265 +0,0 @@
1
- import inquirer from "inquirer";
2
- import fs from "fs";
3
- import path from "path";
4
- import { MessageFormatter } from 'appwrite-utils-helpers';
5
- import { migrateConfig } from "../../utils/configMigration.js";
6
- import {
7
- validateCollectionsTablesConfig,
8
- reportValidationResults,
9
- ConfigManager,
10
- findAppwriteConfig,
11
- findYamlConfig,
12
- YamlLoader,
13
- resolveCollectionsDir,
14
- resolveTablesDir
15
- } from "appwrite-utils-helpers";
16
- import {
17
- createMigrationPlan,
18
- executeMigrationPlan,
19
- saveMigrationResult,
20
- type MigrationStrategy,
21
- } from 'appwrite-utils-helpers';
22
- import { createEmptyCollection } from "../../utils/setupFiles.js";
23
- import chalk from "chalk";
24
- import type { InteractiveCLI } from "../../interactiveCLI.js";
25
- import { UtilsController } from "../../utilsController.js";
26
-
27
- export const configCommands = {
28
- async migrateTypeScriptConfig(cli: InteractiveCLI): Promise<void> {
29
- try {
30
- MessageFormatter.info("Starting TypeScript to YAML configuration migration...", { prefix: "Migration" });
31
-
32
- // Perform the migration
33
- await migrateConfig((cli as any).currentDir);
34
-
35
- // Clear instances after migration to reload new config
36
- UtilsController.clearInstance();
37
- ConfigManager.resetInstance();
38
-
39
- // Reset the detection flag
40
- (cli as any).isUsingTypeScriptConfig = false;
41
-
42
- // Reset the controller to pick up the new config
43
- (cli as any).controller = undefined;
44
-
45
- MessageFormatter.success("Migration completed successfully!", { prefix: "Migration" });
46
- MessageFormatter.info("Your configuration has been migrated to the .appwrite directory structure", { prefix: "Migration" });
47
- MessageFormatter.info("You can now use YAML configuration for easier management", { prefix: "Migration" });
48
-
49
- } catch (error) {
50
- MessageFormatter.error("Migration failed", error instanceof Error ? error : new Error(String(error)), { prefix: "Migration" });
51
- }
52
- },
53
-
54
- async validateConfiguration(cli: InteractiveCLI): Promise<void> {
55
- try {
56
- MessageFormatter.info("Starting configuration validation...", { prefix: "Validation" });
57
-
58
- await (cli as any).initControllerIfNeeded();
59
- const config = (cli as any).controller?.config;
60
-
61
- if (!config) {
62
- MessageFormatter.error("No configuration found to validate", undefined, { prefix: "Validation" });
63
- return;
64
- }
65
-
66
- const { validateCollectionsTablesConfig, reportValidationResults } = await import("appwrite-utils-helpers");
67
- const validation = validateCollectionsTablesConfig(config);
68
-
69
- reportValidationResults(validation, { verbose: true });
70
-
71
- if (validation.isValid) {
72
- MessageFormatter.success("Configuration validation passed!", { prefix: "Validation" });
73
- } else {
74
- MessageFormatter.error("Configuration validation failed", undefined, { prefix: "Validation" });
75
- }
76
-
77
- } catch (error) {
78
- MessageFormatter.error("Validation failed", error instanceof Error ? error : new Error(String(error)), { prefix: "Validation" });
79
- }
80
- },
81
-
82
- async migrateCollectionsToTables(cli: InteractiveCLI): Promise<void> {
83
- try {
84
- MessageFormatter.info("Starting collections to tables migration...", { prefix: "Migration" });
85
-
86
- await (cli as any).initControllerIfNeeded();
87
-
88
- const currentDir = (cli as any).currentDir;
89
- const yamlConfigPath = findYamlConfig(currentDir);
90
-
91
- // Ensure config is properly loaded with YAML collections
92
- if (!(cli as any).controller?.config) {
93
- MessageFormatter.error("No configuration found", undefined, { prefix: "Migration" });
94
- return;
95
- }
96
-
97
- // Check if collections exist
98
- if (!(cli as any).controller.config.collections || (cli as any).controller.config.collections.length === 0) {
99
- MessageFormatter.error("No collections found in configuration. Please check your YAML files or appwriteConfig.ts", undefined, { prefix: "Migration" });
100
- return;
101
- }
102
-
103
- // Get user's migration strategy preference
104
- const { strategy } = await inquirer.prompt([
105
- {
106
- type: "list",
107
- name: "strategy",
108
- message: "Choose migration strategy:",
109
- choices: [
110
- { name: "Move files (rename collections/ to tables/)", value: "move" },
111
- { name: "Copy files (keep both collections/ and tables/)", value: "copy" },
112
- { name: "Dual format (create both .ts and .yaml versions)", value: "dual" }
113
- ]
114
- }
115
- ]);
116
-
117
- if (yamlConfigPath) {
118
- const appwriteDir = path.dirname(yamlConfigPath);
119
- const collectionsDir = resolveCollectionsDir(appwriteDir);
120
- const tablesDir = resolveTablesDir(appwriteDir);
121
-
122
- if (!fs.existsSync(collectionsDir)) {
123
- MessageFormatter.error(`Collections directory not found: ${collectionsDir}`, undefined, { prefix: "Migration" });
124
- return;
125
- }
126
-
127
- const collectionFiles = fs
128
- .readdirSync(collectionsDir)
129
- .filter(file => file.endsWith(".yaml") || file.endsWith(".yml"));
130
-
131
- if (collectionFiles.length === 0) {
132
- MessageFormatter.error("No YAML collection files found to migrate.", undefined, { prefix: "Migration" });
133
- return;
134
- }
135
-
136
- const { confirmed } = await inquirer.prompt([
137
- {
138
- type: "confirm",
139
- name: "confirmed",
140
- message: `Proceed with migration? This will process ${collectionFiles.length} file(s).`,
141
- default: false
142
- }
143
- ]);
144
-
145
- if (!confirmed) {
146
- MessageFormatter.info("Migration cancelled by user", { prefix: "Migration" });
147
- return;
148
- }
149
-
150
- const yamlLoader = new YamlLoader(appwriteDir);
151
- const result = await yamlLoader.migrateTerminology(
152
- path.relative(appwriteDir, collectionsDir),
153
- path.relative(appwriteDir, tablesDir),
154
- true
155
- );
156
-
157
- if (result.errors.length > 0) {
158
- MessageFormatter.warning(`Migration completed with ${result.errors.length} error(s).`, { prefix: "Migration" });
159
- }
160
-
161
- if (strategy === "move") {
162
- const backupDir = `${collectionsDir}.backup.${Date.now()}`;
163
- fs.renameSync(collectionsDir, backupDir);
164
- MessageFormatter.info(`Collections moved to ${path.basename(backupDir)}`, { prefix: "Migration" });
165
- }
166
-
167
- MessageFormatter.success(`Collections migrated to tables (${result.migrated} converted, ${result.skipped} skipped).`, { prefix: "Migration" });
168
- return;
169
- }
170
-
171
- // Map user-friendly strategy names to internal MigrationStrategy types
172
- const migrationStrategy = strategy === "move" ? "full_migration" :
173
- strategy === "copy" || strategy === "dual" ? "dual_format" : "full_migration";
174
- const plan = createMigrationPlan((cli as any).controller.config, migrationStrategy);
175
-
176
- const { confirmed } = await inquirer.prompt([
177
- {
178
- type: "confirm",
179
- name: "confirmed",
180
- message: `Proceed with migration? This will affect ${plan.collectionsToMigrate?.length || 0} files.`,
181
- default: false
182
- }
183
- ]);
184
-
185
- if (confirmed) {
186
- const result = executeMigrationPlan((cli as any).controller.config, plan);
187
- const configDir = findAppwriteConfig(currentDir) || currentDir;
188
- const outputPath = path.join(configDir, "appwriteConfig.ts");
189
- await saveMigrationResult(result, outputPath, { originalConfigPath: outputPath });
190
-
191
- MessageFormatter.success("Collections to tables migration completed!", { prefix: "Migration" });
192
- } else {
193
- MessageFormatter.info("Migration cancelled by user", { prefix: "Migration" });
194
- }
195
-
196
- } catch (error) {
197
- MessageFormatter.error("Migration failed", error instanceof Error ? error : new Error(String(error)), { prefix: "Migration" });
198
- }
199
- },
200
-
201
- async createCollectionConfig(cli: InteractiveCLI): Promise<void> {
202
- const { collectionName } = await inquirer.prompt([
203
- {
204
- type: "input",
205
- name: "collectionName",
206
- message: chalk.blue("Enter the name of the collection:"),
207
- validate: (input) =>
208
- input.trim() !== "" || "Collection name cannot be empty.",
209
- },
210
- ]);
211
- MessageFormatter.progress(`Creating collection config file for '${collectionName}'...`, { prefix: "Collections" });
212
- createEmptyCollection(collectionName);
213
- MessageFormatter.success(`Collection config file created for '${collectionName}'`, { prefix: "Collections" });
214
- },
215
-
216
- async reloadConfigWithSessionPreservation(cli: InteractiveCLI): Promise<void> {
217
- MessageFormatter.progress("Reloading configuration files with session preservation...", { prefix: "Config" });
218
- try {
219
- const controller = (cli as any).controller;
220
- const UtilsController = (await import("../../utilsController.js")).UtilsController;
221
-
222
- if (controller) {
223
- const sessionInfo = controller.getSessionInfo();
224
-
225
- if (sessionInfo.hasSession) {
226
- // Extract session details for preservation
227
- const sessionData = {
228
- sessionCookie: controller.sessionCookie,
229
- sessionMetadata: controller.sessionMetadata
230
- };
231
-
232
- // Store current config values for potential directConfig creation
233
- const currentConfig = controller.config;
234
- let directConfig: any = undefined;
235
-
236
- if (currentConfig?.appwriteEndpoint && currentConfig?.appwriteProject) {
237
- directConfig = {
238
- appwriteEndpoint: currentConfig.appwriteEndpoint,
239
- appwriteProject: currentConfig.appwriteProject,
240
- appwriteKey: currentConfig.appwriteKey,
241
- ...sessionData // Preserve session
242
- };
243
- }
244
-
245
- // Reinitialize controller with session preservation
246
- UtilsController.clearInstance();
247
- (cli as any).controller = UtilsController.getInstance((cli as any).currentDir, directConfig);
248
- await (cli as any).controller.init();
249
-
250
- MessageFormatter.success("Configuration reloaded with session preserved", { prefix: "Config" });
251
- } else {
252
- // No session to preserve, standard reload
253
- await controller.reloadConfig();
254
- MessageFormatter.success("Configuration files reloaded successfully", { prefix: "Config" });
255
- }
256
- } else {
257
- // Initialize if no controller exists
258
- await (cli as any).initControllerIfNeeded();
259
- MessageFormatter.success("Configuration initialized successfully", { prefix: "Config" });
260
- }
261
- } catch (error) {
262
- MessageFormatter.error("Failed to reload configuration files", error instanceof Error ? error : new Error(String(error)), { prefix: "Config" });
263
- }
264
- }
265
- };