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,315 +0,0 @@
1
- import { type Databases, type Storage } from "node-appwrite";
2
- import type { AppwriteConfig } from "appwrite-utils";
3
- import {
4
- validationRules,
5
- type ValidationRules,
6
- type AttributeMappings,
7
- } from "appwrite-utils";
8
- import { converterFunctions, type ConverterFunctions } from "appwrite-utils";
9
- import { convertObjectBySchema } from "appwrite-utils-helpers";
10
- import { type AfterImportActions } from "appwrite-utils";
11
- import { afterImportActions } from "./afterImportActions.js";
12
- import { logger } from "appwrite-utils-helpers";
13
- import { tryAwaitWithRetry } from "appwrite-utils-helpers";
14
-
15
- export class ImportDataActions {
16
- private db: Databases;
17
- private storage: Storage;
18
- private config: AppwriteConfig;
19
- private converterDefinitions: ConverterFunctions;
20
- private validityRuleDefinitions: ValidationRules;
21
- private afterImportActionsDefinitions: AfterImportActions;
22
-
23
- constructor(
24
- db: Databases,
25
- storage: Storage,
26
- config: AppwriteConfig,
27
- converterDefinitions: ConverterFunctions,
28
- validityRuleDefinitions: ValidationRules,
29
- afterImportActionsDefinitions: AfterImportActions
30
- ) {
31
- this.db = db;
32
- this.storage = storage;
33
- this.config = config;
34
- this.converterDefinitions = converterDefinitions;
35
- this.validityRuleDefinitions = validityRuleDefinitions;
36
- this.afterImportActionsDefinitions = afterImportActionsDefinitions;
37
- }
38
-
39
- /**
40
- * Runs converter functions on the item based on the provided attribute mappings.
41
- *
42
- * @param item - The item to be transformed.
43
- * @param attributeMappings - The mappings that define how each attribute should be transformed.
44
- * @returns The transformed item.
45
- */
46
- runConverterFunctions(item: any, attributeMappings: AttributeMappings) {
47
- const conversionSchema = attributeMappings.reduce((schema, mapping) => {
48
- schema[mapping.targetKey] = (originalValue: any) => {
49
- if (!mapping.converters) {
50
- return originalValue;
51
- }
52
- return mapping.converters?.reduce((value, converterName) => {
53
- let shouldProcessAsArray = false;
54
- if (
55
- (converterName.includes("[Arr]") ||
56
- converterName.includes("[arr]")) &&
57
- Array.isArray(value)
58
- ) {
59
- shouldProcessAsArray = true;
60
- converterName = converterName
61
- .replace("[Arr]", "")
62
- .replace("[arr]", "");
63
- } else if (
64
- (!Array.isArray(value) && converterName.includes("[Arr]")) ||
65
- converterName.includes("[arr]")
66
- ) {
67
- converterName = converterName
68
- .replace("[Arr]", "")
69
- .replace("[arr]", "");
70
- }
71
- const converterFunction =
72
- converterFunctions[
73
- converterName as keyof typeof converterFunctions
74
- ];
75
- if (converterFunction) {
76
- if (Array.isArray(value) && !shouldProcessAsArray) {
77
- return value.map((item) => converterFunction(item));
78
- } else {
79
- return converterFunction(value);
80
- }
81
- } else {
82
- logger.warn(
83
- `Converter function '${converterName}' is not defined.`
84
- );
85
- return value;
86
- }
87
- }, originalValue);
88
- };
89
- return schema;
90
- }, {} as Record<string, (value: any) => any>);
91
-
92
- // Convert the item using the constructed schema
93
- const convertedItem = convertObjectBySchema(item, conversionSchema);
94
- // Merge the converted item back into the original item object
95
- Object.assign(item, convertedItem);
96
- return item;
97
- }
98
-
99
- /**
100
- * Validates a single data item based on defined validation rules.
101
- * @param item The data item to validate.
102
- * @param attributeMap The attribute mappings for the data item.
103
- * @param context The context for resolving templated parameters in validation rules.
104
- * @returns A promise that resolves to true if the item is valid, false otherwise.
105
- */
106
- validateItem(
107
- item: any,
108
- attributeMap: AttributeMappings,
109
- context: { [key: string]: any }
110
- ): boolean {
111
- for (const mapping of attributeMap) {
112
- const { validationActions } = mapping;
113
- if (
114
- !validationActions ||
115
- !Array.isArray(validationActions) ||
116
- !validationActions.length
117
- ) {
118
- return true; // Assume items without validation actions as valid.
119
- }
120
- for (const ruleDef of validationActions) {
121
- const { action, params } = ruleDef;
122
- const validationRule =
123
- validationRules[action as keyof typeof validationRules];
124
-
125
- if (!validationRule) {
126
- logger.warn(`Validation rule '${action}' is not defined.`);
127
- continue; // Optionally, consider undefined rules as a validation failure.
128
- }
129
-
130
- // Resolve templated parameters
131
- const resolvedParams = params.map((param: any) =>
132
- this.resolveTemplate(param, context, item)
133
- );
134
-
135
- // Apply the validation rule
136
- let isValid = false;
137
- if (Array.isArray(item)) {
138
- isValid = item.every((item) =>
139
- (validationRule as any)(item, ...resolvedParams)
140
- );
141
- } else {
142
- isValid = (validationRule as any)(item, ...resolvedParams);
143
- }
144
- if (!isValid) {
145
- logger.error(
146
- `Validation failed for rule '${action}' with params ${params.join(
147
- ", "
148
- )}`
149
- );
150
- return false; // Stop validation on first failure
151
- }
152
- }
153
- }
154
-
155
- return true; // The item passed all validations
156
- }
157
-
158
- async executeAfterImportActions(
159
- item: any,
160
- attributeMap: AttributeMappings,
161
- context: { [key: string]: any }
162
- ): Promise<void> {
163
- for (const mapping of attributeMap) {
164
- const { postImportActions } = mapping;
165
- if (!postImportActions || !Array.isArray(postImportActions)) {
166
- continue; // Skip to the next attribute if no actions are defined
167
- }
168
- for (const actionDef of postImportActions) {
169
- const { action, params } = actionDef;
170
- console.log(
171
- `Executing post-import action '${action}' for attribute '${
172
- mapping.targetKey
173
- }' with params ${params.join(", ")}...`
174
- );
175
- try {
176
- await tryAwaitWithRetry(
177
- async () => await this.executeAction(action, params, context, item)
178
- );
179
- } catch (error) {
180
- logger.error(
181
- `Failed to execute post-import action '${action}' for attribute '${mapping.targetKey}':`,
182
- error
183
- );
184
- }
185
- }
186
- }
187
- }
188
-
189
- async executeAction(
190
- actionName: string,
191
- params: any[], // Accepts any type, including objects
192
- context: { [key: string]: any },
193
- item: any
194
- ): Promise<void> {
195
- const actionMethod =
196
- afterImportActions[actionName as keyof typeof afterImportActions];
197
- if (typeof actionMethod === "function") {
198
- try {
199
- // Resolve parameters, handling both strings and objects
200
- const resolvedParams = params.map((param) => {
201
- // Directly resolve each param, whether it's an object or a string
202
- return this.resolveTemplate(param, context, item);
203
- });
204
-
205
- // Execute the action with resolved parameters
206
- // Parameters are passed as-is, with objects treated as single parameters
207
- console.log(
208
- `Executing action '${actionName}' from context with params:`,
209
- resolvedParams
210
- );
211
- logger.info(
212
- `Executing action '${actionName}' from context: ${JSON.stringify(
213
- context,
214
- null,
215
- 2
216
- )} with params:`,
217
- resolvedParams
218
- );
219
- await (actionMethod as any)(this.config, ...resolvedParams);
220
- } catch (error: any) {
221
- logger.error(
222
- `Error executing action '${actionName}' with context:`,
223
- context,
224
- error
225
- );
226
- throw new Error(
227
- `Execution failed for action '${actionName}': ${error.message}`
228
- );
229
- }
230
- } else {
231
- logger.warn(`Action '${actionName}' is not defined.`);
232
- throw new Error(`Action '${actionName}' is not defined.`);
233
- }
234
- }
235
-
236
- /**
237
- * Resolves a templated string or object using the provided context and current data item.
238
- * If the template is a string that starts and ends with "{}", it replaces it with the corresponding value from item or context.
239
- * If the template is an object, it recursively resolves its properties.
240
- * @param template The templated string or object.
241
- * @param context The context for resolving the template.
242
- * @param item The current data item being processed.
243
- */
244
- resolveTemplate(
245
- template: any,
246
- context: { [key: string]: any },
247
- item: any
248
- ): any {
249
- // Function to recursively resolve paths, including handling [any] notation
250
- const resolvePath = (path: string, currentContext: any): any => {
251
- const anyKeyRegex = /\[any\]/g;
252
- let pathParts = path.split(".").filter(Boolean);
253
-
254
- return pathParts.reduce((acc, part, index) => {
255
- // Handle [any] part by iterating over all elements if it's an object or an array
256
- if (part === "[any]") {
257
- if (Array.isArray(acc)) {
258
- return acc
259
- .map((item) => item[pathParts[index + 1]])
260
- .filter((item) => item !== undefined);
261
- } else if (typeof acc === "object") {
262
- return Object.values(acc)
263
- .map((item: any) => item[pathParts[index + 1]])
264
- .filter((item) => item !== undefined);
265
- }
266
- } else {
267
- return acc?.[part];
268
- }
269
- }, currentContext);
270
- };
271
-
272
- if (typeof template === "string") {
273
- // Matches placeholders in the template
274
- const regex = /\{([^}]+)\}/g;
275
- let match;
276
- let resolvedString = template;
277
- while ((match = regex.exec(template)) !== null) {
278
- const path = match[1];
279
- // Resolve the path, handling [any] notation and arrays/objects
280
- const resolvedValue = resolvePath(path, { ...context, ...item });
281
- if (resolvedValue !== undefined) {
282
- // If it's an array (from [any] notation), join the values; adjust as needed
283
- const value = Array.isArray(resolvedValue)
284
- ? resolvedValue.join(", ")
285
- : resolvedValue;
286
- resolvedString = resolvedString.replace(match[0], value);
287
- } else {
288
- logger.warn(
289
- `Failed to resolve ${template} in context: `,
290
- JSON.stringify({ ...context, ...item }, null, 2)
291
- );
292
- }
293
- }
294
- // console.log(`Resolved string: ${resolvedString}`);
295
- return resolvedString;
296
- } else if (typeof template === "object" && template !== null) {
297
- // Recursively resolve templates for each property in the object
298
- const resolvedObject: any = Array.isArray(template) ? [] : {};
299
- for (const key in template) {
300
- const resolvedValue = this.resolveTemplate(
301
- template[key],
302
- context,
303
- item
304
- );
305
- if (resolvedValue !== undefined) {
306
- // Only assign if resolvedValue is not undefined
307
- resolvedObject[key] = resolvedValue;
308
- }
309
- }
310
- return resolvedObject;
311
- }
312
- // console.log(`Template is not a string or object: ${template}`);
313
- return template;
314
- }
315
- }
@@ -1,333 +0,0 @@
1
- import { Databases, Query, type Models } from "node-appwrite";
2
- import { fetchAllCollections } from "../collections/methods.js";
3
- import type {
4
- AppwriteConfig,
5
- Attribute,
6
- RelationshipAttribute,
7
- } from "appwrite-utils";
8
- import { logger, MessageFormatter } from "appwrite-utils-helpers";
9
-
10
- /**
11
- * Finds collections that have defined relationship attributes.
12
- */
13
- export const findCollectionsWithRelationships = (config: AppwriteConfig) => {
14
- const toReturn = new Map<string, RelationshipAttribute[]>();
15
- if (!config.collections) {
16
- return toReturn;
17
- }
18
- for (const collection of config.collections) {
19
- if (collection.attributes) {
20
- for (const attribute of collection.attributes) {
21
- if (
22
- attribute.type === "relationship" &&
23
- attribute.twoWay &&
24
- attribute.side === "parent"
25
- ) {
26
- toReturn.set(collection.name, toReturn.get(collection.name) || []);
27
- toReturn
28
- .get(collection.name)
29
- ?.push(attribute as RelationshipAttribute);
30
- }
31
- }
32
- }
33
- }
34
- return toReturn;
35
- };
36
-
37
- export async function resolveAndUpdateRelationships(
38
- dbId: string,
39
- database: Databases,
40
- config: AppwriteConfig
41
- ) {
42
- const collections = await fetchAllCollections(dbId, database);
43
- const collectionsWithRelationships = findCollectionsWithRelationships(config);
44
-
45
- // Process each collection sequentially
46
- for (const collection of collections) {
47
- MessageFormatter.processing(
48
- `Processing collection: ${collection.name} (${collection.$id})`,
49
- { prefix: "Migration" }
50
- );
51
- const relAttributeMap = collectionsWithRelationships.get(
52
- collection.name
53
- ) as RelationshipAttribute[]; // Get the relationship attributes for the collections
54
-
55
- if (!relAttributeMap) {
56
- MessageFormatter.info(
57
- `No mapping found for collection: ${collection.name}, skipping...`,
58
- { prefix: "Migration" }
59
- );
60
- continue;
61
- }
62
-
63
- await processCollection(dbId, database, collection, relAttributeMap);
64
- }
65
- MessageFormatter.success(
66
- `Completed relationship resolution and update for database ID: ${dbId}`,
67
- { prefix: "Migration" }
68
- );
69
- }
70
-
71
- async function processCollection(
72
- dbId: string,
73
- database: Databases,
74
- collection: Models.Collection,
75
- relAttributeMap: RelationshipAttribute[]
76
- ) {
77
- let after; // For pagination
78
- let hasMore = true;
79
-
80
- while (hasMore) {
81
- const response: Models.DocumentList<Models.Document> =
82
- await database.listDocuments(dbId, collection.$id, [
83
- Query.limit(100), // Fetch documents in batches of 100
84
- ...(after ? [Query.cursorAfter(after)] : []),
85
- ]);
86
-
87
- const documents = response.documents;
88
- MessageFormatter.info(
89
- `Fetched ${documents.length} documents from collection: ${collection.name}`,
90
- { prefix: "Migration" }
91
- );
92
-
93
- if (documents.length > 0) {
94
- const updates = await prepareDocumentUpdates(
95
- database,
96
- dbId,
97
- collection.name,
98
- documents,
99
- relAttributeMap
100
- );
101
-
102
- // Execute updates for the current batch
103
- await executeUpdatesInBatches(dbId, database, updates);
104
- }
105
-
106
- if (documents.length === 100) {
107
- after = documents[documents.length - 1].$id; // Prepare for the next page
108
- } else {
109
- hasMore = false; // No more documents to fetch
110
- }
111
- }
112
- }
113
-
114
- async function findDocumentsByOriginalId(
115
- database: Databases,
116
- dbId: string,
117
- targetCollection: Models.Collection,
118
- targetKey: string,
119
- originalId: string | string[]
120
- ): Promise<Models.Document[] | undefined> {
121
- const relatedCollectionId = targetCollection.$id;
122
- const collection = await database.listCollections(dbId, [
123
- Query.equal("$id", relatedCollectionId),
124
- ]);
125
- if (collection.total === 0) {
126
- MessageFormatter.warning(
127
- `Collection ${relatedCollectionId} doesn't exist, skipping...`,
128
- { prefix: "Migration" }
129
- );
130
- return undefined;
131
- }
132
- const targetAttr = collection.collections[0].attributes.find(
133
- // @ts-ignore
134
- (attr) => attr.key === targetKey
135
- ) as any;
136
- if (!targetAttr) {
137
- MessageFormatter.warning(
138
- `Attribute ${targetKey} not found in collection ${relatedCollectionId}, skipping...`,
139
- { prefix: "Migration" }
140
- );
141
- return undefined;
142
- }
143
- let queries: string[] = [];
144
- if (targetAttr.array) {
145
- // @ts-ignore
146
- queries.push(Query.contains(targetKey, originalId));
147
- } else {
148
- queries.push(Query.equal(targetKey, originalId));
149
- }
150
- const response = await database.listDocuments(dbId, relatedCollectionId, [
151
- ...queries,
152
- Query.limit(500), // Adjust the limit based on your needs or implement pagination
153
- ]);
154
-
155
- if (response.documents.length < 0) {
156
- return undefined;
157
- } else if (response.documents.length > 0) {
158
- return response.documents;
159
- } else {
160
- return undefined;
161
- }
162
- }
163
-
164
- async function prepareDocumentUpdates(
165
- database: Databases,
166
- dbId: string,
167
- collectionName: string,
168
- documents: Models.Document[],
169
- relationships: RelationshipAttribute[]
170
- ): Promise<{ collectionId: string; documentId: string; updatePayload: any }[]> {
171
- MessageFormatter.processing(`Preparing updates for collection: ${collectionName}`, { prefix: "Migration" });
172
- const updates: {
173
- collectionId: string;
174
- documentId: string;
175
- updatePayload: any;
176
- }[] = [];
177
-
178
- const thisCollection = (
179
- await database.listCollections(dbId, [Query.equal("name", collectionName)])
180
- ).collections[0];
181
- const thisCollectionId = thisCollection?.$id;
182
-
183
- if (!thisCollectionId) {
184
- MessageFormatter.warning(`No collection found with name: ${collectionName}`, { prefix: "Migration" });
185
- return [];
186
- }
187
-
188
- for (const doc of documents) {
189
- let updatePayload: { [key: string]: any } = {};
190
-
191
- for (const rel of relationships) {
192
- // Skip if not dealing with the parent side of a two-way relationship
193
- if (rel.twoWay && rel.side !== "parent") {
194
- MessageFormatter.info("Skipping non-parent side of two-way relationship...", { prefix: "Migration" });
195
- continue;
196
- }
197
-
198
- const isSingleReference =
199
- rel.relationType === "oneToOne" || rel.relationType === "manyToOne";
200
- const originalIdField = rel.importMapping?.originalIdField;
201
- const targetField = rel.importMapping?.targetField || originalIdField; // Use originalIdField if targetField is not specified
202
- if (!originalIdField) {
203
- MessageFormatter.warning("Missing originalIdField in importMapping, skipping...", { prefix: "Migration" });
204
- continue;
205
- }
206
- const originalId = doc[originalIdField as keyof typeof doc];
207
- if (!originalId) {
208
- continue;
209
- }
210
-
211
- const relatedCollection = (
212
- await database.listCollections(dbId, [
213
- Query.equal("name", rel.relatedCollection),
214
- ])
215
- ).collections[0];
216
-
217
- if (!relatedCollection) {
218
- MessageFormatter.warning(
219
- `Related collection ${rel.relatedCollection} not found, skipping...`,
220
- { prefix: "Migration" }
221
- );
222
- continue;
223
- }
224
-
225
- const foundDocuments = await findDocumentsByOriginalId(
226
- database,
227
- dbId,
228
- relatedCollection,
229
- targetField!,
230
- String(originalId)
231
- );
232
-
233
- if (foundDocuments && foundDocuments.length > 0) {
234
- const relationshipKey = rel.key;
235
- const existingRefs = doc[relationshipKey as keyof typeof doc] || [];
236
- let existingRefIds: string[] = [];
237
- if (Array.isArray(existingRefs)) {
238
- // @ts-ignore
239
- existingRefIds = existingRefs.map((ref) => ref.$id);
240
- } else if (existingRefs) {
241
- // @ts-ignore
242
- existingRefIds = [existingRefs.$id];
243
- }
244
-
245
- const newRefs = foundDocuments.map((fd) => fd.$id);
246
- const allRefs = [...new Set([...existingRefIds, ...newRefs])]; // Combine and remove duplicates
247
-
248
- // Update logic based on the relationship cardinality
249
- updatePayload[relationshipKey] = isSingleReference
250
- ? newRefs[0] || existingRefIds[0]
251
- : allRefs;
252
- MessageFormatter.info(`Updating ${relationshipKey} with ${allRefs.length} refs`, { prefix: "Migration" });
253
- }
254
- }
255
-
256
- if (Object.keys(updatePayload).length > 0) {
257
- updates.push({
258
- collectionId: thisCollectionId,
259
- documentId: doc.$id,
260
- updatePayload: updatePayload,
261
- });
262
- }
263
- }
264
-
265
- return updates;
266
- }
267
-
268
- async function processInBatches<T>(
269
- items: T[],
270
- batchSize: number,
271
- processFunction: (batch: T[]) => Promise<void>
272
- ) {
273
- const maxParallelBatches = 25; // Adjust this value to control the number of parallel batches
274
- let currentIndex = 0;
275
- let activeBatchPromises: Promise<void>[] = [];
276
-
277
- while (currentIndex < items.length) {
278
- // While there's still data to process and we haven't reached our parallel limit
279
- while (
280
- currentIndex < items.length &&
281
- activeBatchPromises.length < maxParallelBatches
282
- ) {
283
- const batch = items.slice(currentIndex, currentIndex + batchSize);
284
- currentIndex += batchSize;
285
- // Add new batch processing promise to the array
286
- activeBatchPromises.push(processFunction(batch));
287
- }
288
-
289
- // Wait for one of the batch processes to complete
290
- await Promise.race(activeBatchPromises).then(() => {
291
- // Remove the resolved promise from the activeBatchPromises array
292
- activeBatchPromises = activeBatchPromises.filter(
293
- (p) => p !== Promise.race(activeBatchPromises)
294
- );
295
- });
296
- }
297
-
298
- // After processing all batches, ensure all active promises are resolved
299
- await Promise.all(activeBatchPromises);
300
- }
301
-
302
- async function executeUpdatesInBatches(
303
- dbId: string,
304
- database: Databases,
305
- updates: { collectionId: string; documentId: string; updatePayload: any }[]
306
- ) {
307
- const batchSize = 25; // Adjust based on your rate limit and performance testing
308
- for (let i = 0; i < updates.length; i += batchSize) {
309
- const batch = updates.slice(i, i + batchSize);
310
- await Promise.all(
311
- batch.map((update) =>
312
- database
313
- .updateDocument(
314
- dbId,
315
- update.collectionId,
316
- update.documentId,
317
- update.updatePayload
318
- )
319
- .catch((error) => {
320
- logger.error(
321
- `Error updating doc ${
322
- update.documentId
323
- } in ${dbId}, update payload: ${JSON.stringify(
324
- update.updatePayload,
325
- undefined,
326
- 4
327
- )}, error: ${error}`
328
- );
329
- })
330
- )
331
- );
332
- }
333
- }