appwrite-utils-cli 0.10.86 → 1.0.1

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 (178) hide show
  1. package/.appwrite/.yaml_schemas/appwrite-config.schema.json +380 -0
  2. package/.appwrite/.yaml_schemas/collection.schema.json +255 -0
  3. package/.appwrite/collections/Categories.yaml +182 -0
  4. package/.appwrite/collections/ExampleCollection.yaml +36 -0
  5. package/.appwrite/collections/Posts.yaml +227 -0
  6. package/.appwrite/collections/Users.yaml +149 -0
  7. package/.appwrite/config.yaml +109 -0
  8. package/.appwrite/import/README.md +148 -0
  9. package/.appwrite/import/categories-import.yaml +129 -0
  10. package/.appwrite/import/posts-import.yaml +208 -0
  11. package/.appwrite/import/users-import.yaml +130 -0
  12. package/.appwrite/importData/categories.json +194 -0
  13. package/.appwrite/importData/posts.json +270 -0
  14. package/.appwrite/importData/users.json +220 -0
  15. package/.appwrite/schemas/categories.json +128 -0
  16. package/.appwrite/schemas/exampleCollection.json +52 -0
  17. package/.appwrite/schemas/posts.json +173 -0
  18. package/.appwrite/schemas/users.json +125 -0
  19. package/README.md +260 -33
  20. package/dist/collections/attributes.js +3 -2
  21. package/dist/collections/methods.js +56 -38
  22. package/dist/config/yamlConfig.d.ts +501 -0
  23. package/dist/config/yamlConfig.js +452 -0
  24. package/dist/databases/setup.d.ts +6 -0
  25. package/dist/databases/setup.js +119 -0
  26. package/dist/functions/methods.d.ts +1 -1
  27. package/dist/functions/methods.js +5 -2
  28. package/dist/functions/openapi.d.ts +4 -0
  29. package/dist/functions/openapi.js +60 -0
  30. package/dist/interactiveCLI.d.ts +5 -0
  31. package/dist/interactiveCLI.js +194 -49
  32. package/dist/main.js +91 -30
  33. package/dist/migrations/afterImportActions.js +2 -2
  34. package/dist/migrations/appwriteToX.d.ts +10 -0
  35. package/dist/migrations/appwriteToX.js +15 -4
  36. package/dist/migrations/backup.d.ts +16 -16
  37. package/dist/migrations/dataLoader.d.ts +83 -1
  38. package/dist/migrations/dataLoader.js +4 -4
  39. package/dist/migrations/importController.js +25 -18
  40. package/dist/migrations/importDataActions.js +2 -2
  41. package/dist/migrations/logging.d.ts +9 -1
  42. package/dist/migrations/logging.js +41 -22
  43. package/dist/migrations/migrationHelper.d.ts +4 -4
  44. package/dist/migrations/relationships.js +1 -1
  45. package/dist/migrations/services/DataTransformationService.d.ts +55 -0
  46. package/dist/migrations/services/DataTransformationService.js +158 -0
  47. package/dist/migrations/services/FileHandlerService.d.ts +75 -0
  48. package/dist/migrations/services/FileHandlerService.js +236 -0
  49. package/dist/migrations/services/ImportOrchestrator.d.ts +97 -0
  50. package/dist/migrations/services/ImportOrchestrator.js +488 -0
  51. package/dist/migrations/services/RateLimitManager.d.ts +138 -0
  52. package/dist/migrations/services/RateLimitManager.js +279 -0
  53. package/dist/migrations/services/RelationshipResolver.d.ts +120 -0
  54. package/dist/migrations/services/RelationshipResolver.js +332 -0
  55. package/dist/migrations/services/UserMappingService.d.ts +109 -0
  56. package/dist/migrations/services/UserMappingService.js +277 -0
  57. package/dist/migrations/services/ValidationService.d.ts +74 -0
  58. package/dist/migrations/services/ValidationService.js +260 -0
  59. package/dist/migrations/transfer.d.ts +0 -6
  60. package/dist/migrations/transfer.js +16 -132
  61. package/dist/migrations/yaml/YamlImportConfigLoader.d.ts +384 -0
  62. package/dist/migrations/yaml/YamlImportConfigLoader.js +375 -0
  63. package/dist/migrations/yaml/YamlImportIntegration.d.ts +87 -0
  64. package/dist/migrations/yaml/YamlImportIntegration.js +330 -0
  65. package/dist/migrations/yaml/generateImportSchemas.d.ts +17 -0
  66. package/dist/migrations/yaml/generateImportSchemas.js +575 -0
  67. package/dist/schemas/authUser.d.ts +9 -9
  68. package/dist/shared/attributeManager.d.ts +17 -0
  69. package/dist/shared/attributeManager.js +273 -0
  70. package/dist/shared/confirmationDialogs.d.ts +75 -0
  71. package/dist/shared/confirmationDialogs.js +236 -0
  72. package/dist/shared/functionManager.d.ts +48 -0
  73. package/dist/shared/functionManager.js +322 -0
  74. package/dist/shared/indexManager.d.ts +24 -0
  75. package/dist/shared/indexManager.js +150 -0
  76. package/dist/shared/jsonSchemaGenerator.d.ts +51 -0
  77. package/dist/shared/jsonSchemaGenerator.js +313 -0
  78. package/dist/shared/logging.d.ts +10 -0
  79. package/dist/shared/logging.js +46 -0
  80. package/dist/shared/messageFormatter.d.ts +37 -0
  81. package/dist/shared/messageFormatter.js +152 -0
  82. package/dist/shared/migrationHelpers.d.ts +173 -0
  83. package/dist/shared/migrationHelpers.js +142 -0
  84. package/dist/shared/operationLogger.d.ts +3 -0
  85. package/dist/shared/operationLogger.js +25 -0
  86. package/dist/shared/operationQueue.d.ts +13 -0
  87. package/dist/shared/operationQueue.js +79 -0
  88. package/dist/shared/progressManager.d.ts +62 -0
  89. package/dist/shared/progressManager.js +215 -0
  90. package/dist/shared/schemaGenerator.d.ts +18 -0
  91. package/dist/shared/schemaGenerator.js +523 -0
  92. package/dist/storage/methods.d.ts +3 -1
  93. package/dist/storage/methods.js +144 -55
  94. package/dist/storage/schemas.d.ts +56 -16
  95. package/dist/types.d.ts +2 -2
  96. package/dist/types.js +1 -1
  97. package/dist/users/methods.d.ts +16 -0
  98. package/dist/users/methods.js +276 -0
  99. package/dist/utils/configMigration.d.ts +1 -0
  100. package/dist/utils/configMigration.js +156 -0
  101. package/dist/utils/dataConverters.d.ts +46 -0
  102. package/dist/utils/dataConverters.js +139 -0
  103. package/dist/utils/loadConfigs.d.ts +15 -4
  104. package/dist/utils/loadConfigs.js +377 -51
  105. package/dist/utils/schemaStrings.js +2 -1
  106. package/dist/utils/setupFiles.d.ts +2 -1
  107. package/dist/utils/setupFiles.js +723 -28
  108. package/dist/utils/validationRules.d.ts +43 -0
  109. package/dist/utils/validationRules.js +42 -0
  110. package/dist/utils/yamlConverter.d.ts +48 -0
  111. package/dist/utils/yamlConverter.js +98 -0
  112. package/dist/utilsController.js +65 -43
  113. package/package.json +19 -15
  114. package/src/collections/attributes.ts +3 -2
  115. package/src/collections/methods.ts +85 -51
  116. package/src/config/yamlConfig.ts +488 -0
  117. package/src/{migrations/setupDatabase.ts → databases/setup.ts} +11 -5
  118. package/src/functions/methods.ts +8 -4
  119. package/src/functions/templates/count-docs-in-collection/package.json +25 -0
  120. package/src/functions/templates/count-docs-in-collection/tsconfig.json +28 -0
  121. package/src/functions/templates/typescript-node/package.json +24 -0
  122. package/src/functions/templates/typescript-node/tsconfig.json +28 -0
  123. package/src/functions/templates/uv/README.md +31 -0
  124. package/src/functions/templates/uv/pyproject.toml +29 -0
  125. package/src/interactiveCLI.ts +226 -61
  126. package/src/main.ts +111 -37
  127. package/src/migrations/afterImportActions.ts +2 -2
  128. package/src/migrations/appwriteToX.ts +17 -4
  129. package/src/migrations/dataLoader.ts +4 -4
  130. package/src/migrations/importController.ts +30 -22
  131. package/src/migrations/importDataActions.ts +2 -2
  132. package/src/migrations/relationships.ts +1 -1
  133. package/src/migrations/services/DataTransformationService.ts +196 -0
  134. package/src/migrations/services/FileHandlerService.ts +311 -0
  135. package/src/migrations/services/ImportOrchestrator.ts +669 -0
  136. package/src/migrations/services/RateLimitManager.ts +363 -0
  137. package/src/migrations/services/RelationshipResolver.ts +461 -0
  138. package/src/migrations/services/UserMappingService.ts +345 -0
  139. package/src/migrations/services/ValidationService.ts +349 -0
  140. package/src/migrations/transfer.ts +22 -228
  141. package/src/migrations/yaml/YamlImportConfigLoader.ts +427 -0
  142. package/src/migrations/yaml/YamlImportIntegration.ts +419 -0
  143. package/src/migrations/yaml/generateImportSchemas.ts +589 -0
  144. package/src/shared/attributeManager.ts +429 -0
  145. package/src/shared/confirmationDialogs.ts +327 -0
  146. package/src/shared/functionManager.ts +515 -0
  147. package/src/shared/indexManager.ts +253 -0
  148. package/src/shared/jsonSchemaGenerator.ts +403 -0
  149. package/src/shared/logging.ts +74 -0
  150. package/src/shared/messageFormatter.ts +195 -0
  151. package/src/{migrations/migrationHelper.ts → shared/migrationHelpers.ts} +22 -4
  152. package/src/{migrations/helper.ts → shared/operationLogger.ts} +7 -2
  153. package/src/{migrations/queue.ts → shared/operationQueue.ts} +1 -1
  154. package/src/shared/progressManager.ts +278 -0
  155. package/src/{migrations/schemaStrings.ts → shared/schemaGenerator.ts} +71 -17
  156. package/src/storage/methods.ts +199 -78
  157. package/src/types.ts +2 -2
  158. package/src/{migrations/users.ts → users/methods.ts} +2 -2
  159. package/src/utils/configMigration.ts +212 -0
  160. package/src/utils/loadConfigs.ts +414 -52
  161. package/src/utils/schemaStrings.ts +2 -1
  162. package/src/utils/setupFiles.ts +742 -40
  163. package/src/{migrations → utils}/validationRules.ts +1 -1
  164. package/src/utils/yamlConverter.ts +131 -0
  165. package/src/utilsController.ts +75 -54
  166. package/src/functions/templates/poetry/README.md +0 -30
  167. package/src/functions/templates/poetry/pyproject.toml +0 -16
  168. package/src/migrations/attributes.ts +0 -561
  169. package/src/migrations/backup.ts +0 -205
  170. package/src/migrations/databases.ts +0 -39
  171. package/src/migrations/dbHelpers.ts +0 -92
  172. package/src/migrations/indexes.ts +0 -40
  173. package/src/migrations/logging.ts +0 -29
  174. package/src/migrations/storage.ts +0 -538
  175. /package/src/{migrations → functions}/openapi.ts +0 -0
  176. /package/src/functions/templates/{poetry → uv}/src/__init__.py +0 -0
  177. /package/src/functions/templates/{poetry → uv}/src/index.py +0 -0
  178. /package/src/{migrations/converters.ts → utils/dataConverters.ts} +0 -0
@@ -0,0 +1,313 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ import { toCamelCase, toPascalCase } from "../utils/index.js";
4
+ import chalk from "chalk";
5
+ export class JsonSchemaGenerator {
6
+ config;
7
+ appwriteFolderPath;
8
+ relationshipMap = new Map();
9
+ constructor(config, appwriteFolderPath) {
10
+ this.config = config;
11
+ this.appwriteFolderPath = appwriteFolderPath;
12
+ this.extractRelationships();
13
+ }
14
+ extractRelationships() {
15
+ if (!this.config.collections)
16
+ return;
17
+ this.config.collections.forEach((collection) => {
18
+ if (!collection.attributes)
19
+ return;
20
+ collection.attributes.forEach((attr) => {
21
+ if (attr.type === "relationship" && attr.relatedCollection) {
22
+ const relationships = this.relationshipMap.get(collection.name) || [];
23
+ relationships.push({
24
+ attributeKey: attr.key,
25
+ relatedCollection: attr.relatedCollection,
26
+ relationType: attr.relationType,
27
+ isArray: attr.relationType === "oneToMany" || attr.relationType === "manyToMany"
28
+ });
29
+ this.relationshipMap.set(collection.name, relationships);
30
+ }
31
+ });
32
+ });
33
+ }
34
+ attributeToJsonSchemaProperty(attribute) {
35
+ const property = {
36
+ type: "string" // Default type
37
+ };
38
+ // Set description if available
39
+ if (attribute.description) {
40
+ property.description = typeof attribute.description === 'string'
41
+ ? attribute.description
42
+ : JSON.stringify(attribute.description);
43
+ }
44
+ // Handle array attributes
45
+ if (attribute.array) {
46
+ property.type = "array";
47
+ property.items = this.getBaseTypeSchema(attribute);
48
+ }
49
+ else {
50
+ Object.assign(property, this.getBaseTypeSchema(attribute));
51
+ }
52
+ // Set default value (only for attributes that support it)
53
+ if (attribute.type !== "relationship" && "xdefault" in attribute &&
54
+ attribute.xdefault !== undefined && attribute.xdefault !== null) {
55
+ property.default = attribute.xdefault;
56
+ }
57
+ return property;
58
+ }
59
+ getBaseTypeSchema(attribute) {
60
+ const schema = {
61
+ type: "string" // Default type
62
+ };
63
+ switch (attribute.type) {
64
+ case "string":
65
+ schema.type = "string";
66
+ if (attribute.size) {
67
+ schema.maxLength = attribute.size;
68
+ }
69
+ break;
70
+ case "integer":
71
+ schema.type = "integer";
72
+ if (attribute.min !== undefined) {
73
+ schema.minimum = Number(attribute.min);
74
+ }
75
+ if (attribute.max !== undefined) {
76
+ schema.maximum = Number(attribute.max);
77
+ }
78
+ break;
79
+ case "double":
80
+ case "float": // Backward compatibility
81
+ schema.type = "number";
82
+ if (attribute.min !== undefined) {
83
+ schema.minimum = Number(attribute.min);
84
+ }
85
+ if (attribute.max !== undefined) {
86
+ schema.maximum = Number(attribute.max);
87
+ }
88
+ break;
89
+ case "boolean":
90
+ schema.type = "boolean";
91
+ break;
92
+ case "datetime":
93
+ schema.type = "string";
94
+ schema.format = "date-time";
95
+ break;
96
+ case "email":
97
+ schema.type = "string";
98
+ schema.format = "email";
99
+ break;
100
+ case "ip":
101
+ schema.type = "string";
102
+ schema.format = "ipv4";
103
+ break;
104
+ case "url":
105
+ schema.type = "string";
106
+ schema.format = "uri";
107
+ break;
108
+ case "enum":
109
+ schema.type = "string";
110
+ if (attribute.elements) {
111
+ schema.enum = attribute.elements;
112
+ }
113
+ break;
114
+ case "relationship":
115
+ if (attribute.relatedCollection) {
116
+ // For relationships, reference the related collection schema
117
+ schema.$ref = `#/definitions/${toPascalCase(attribute.relatedCollection)}`;
118
+ }
119
+ else {
120
+ schema.type = "string";
121
+ schema.description = "Document ID reference";
122
+ }
123
+ break;
124
+ default:
125
+ schema.type = "string";
126
+ }
127
+ return schema;
128
+ }
129
+ createJsonSchema(collection) {
130
+ const pascalName = toPascalCase(collection.name);
131
+ const schema = {
132
+ $schema: "https://json-schema.org/draft/2020-12/schema",
133
+ $id: `https://example.com/schemas/${toCamelCase(collection.name)}.json`,
134
+ title: pascalName,
135
+ description: collection.description || `Schema for ${collection.name} collection`,
136
+ type: "object",
137
+ properties: {
138
+ // Standard Appwrite document fields
139
+ $id: {
140
+ type: "string",
141
+ description: "Document ID",
142
+ pattern: "^[a-zA-Z0-9][a-zA-Z0-9._-]{0,35}$"
143
+ },
144
+ $createdAt: {
145
+ type: "string",
146
+ format: "date-time",
147
+ description: "Document creation date"
148
+ },
149
+ $updatedAt: {
150
+ type: "string",
151
+ format: "date-time",
152
+ description: "Document last update date"
153
+ },
154
+ $permissions: {
155
+ type: "array",
156
+ items: {
157
+ type: "string"
158
+ },
159
+ description: "Document permissions"
160
+ }
161
+ },
162
+ required: ["$id", "$createdAt", "$updatedAt"],
163
+ additionalProperties: false
164
+ };
165
+ // Add custom attributes
166
+ const requiredFields = [...schema.required];
167
+ if (collection.attributes) {
168
+ collection.attributes.forEach((attribute) => {
169
+ schema.properties[attribute.key] = this.attributeToJsonSchemaProperty(attribute);
170
+ if (attribute.required) {
171
+ requiredFields.push(attribute.key);
172
+ }
173
+ });
174
+ }
175
+ schema.required = requiredFields;
176
+ // Add relationship definitions if any exist
177
+ const relationships = this.relationshipMap.get(collection.name);
178
+ if (relationships && relationships.length > 0) {
179
+ schema.definitions = {};
180
+ relationships.forEach((rel) => {
181
+ const relatedPascalName = toPascalCase(rel.relatedCollection);
182
+ schema.definitions[relatedPascalName] = {
183
+ type: "object",
184
+ properties: {
185
+ $id: { type: "string" },
186
+ $createdAt: { type: "string", format: "date-time" },
187
+ $updatedAt: { type: "string", format: "date-time" }
188
+ },
189
+ additionalProperties: true,
190
+ description: `Reference to ${rel.relatedCollection} document`
191
+ };
192
+ });
193
+ }
194
+ return schema;
195
+ }
196
+ generateJsonSchemas(options = {}) {
197
+ const { outputFormat = "both", outputDirectory = "schemas", verbose = false } = options;
198
+ if (!this.config.collections) {
199
+ if (verbose) {
200
+ console.log(chalk.yellow("No collections found in config"));
201
+ }
202
+ return;
203
+ }
204
+ // Create JSON schemas directory using provided outputDirectory
205
+ const jsonSchemasPath = path.join(this.appwriteFolderPath, outputDirectory);
206
+ if (!fs.existsSync(jsonSchemasPath)) {
207
+ fs.mkdirSync(jsonSchemasPath, { recursive: true });
208
+ }
209
+ if (verbose) {
210
+ console.log(chalk.blue(`Generating JSON schemas for ${this.config.collections.length} collections...`));
211
+ }
212
+ this.config.collections.forEach((collection) => {
213
+ const schema = this.createJsonSchema(collection);
214
+ const camelCaseName = toCamelCase(collection.name);
215
+ // Generate JSON file
216
+ if (outputFormat === "json" || outputFormat === "both") {
217
+ const jsonPath = path.join(jsonSchemasPath, `${camelCaseName}.json`);
218
+ fs.writeFileSync(jsonPath, JSON.stringify(schema, null, 2), { encoding: "utf-8" });
219
+ if (verbose) {
220
+ console.log(chalk.green(`✓ JSON schema written to ${jsonPath}`));
221
+ }
222
+ }
223
+ // Generate TypeScript file
224
+ if (outputFormat === "typescript" || outputFormat === "both") {
225
+ const tsContent = this.generateTypeScriptSchema(schema, collection.name);
226
+ const tsPath = path.join(jsonSchemasPath, `${camelCaseName}.schema.ts`);
227
+ fs.writeFileSync(tsPath, tsContent, { encoding: "utf-8" });
228
+ if (verbose) {
229
+ console.log(chalk.green(`✓ TypeScript schema written to ${tsPath}`));
230
+ }
231
+ }
232
+ });
233
+ // Generate index file only for TypeScript output
234
+ if (outputFormat === "typescript" || outputFormat === "both") {
235
+ this.generateIndexFile(outputFormat, jsonSchemasPath, verbose);
236
+ }
237
+ if (verbose) {
238
+ console.log(chalk.green("✓ JSON schema generation completed"));
239
+ }
240
+ }
241
+ generateTypeScriptSchema(schema, collectionName) {
242
+ const camelName = toCamelCase(collectionName);
243
+ return `// Auto-generated JSON schema for ${collectionName}
244
+ import type { JSONSchema7 } from "json-schema";
245
+
246
+ export const ${camelName}JsonSchema: JSONSchema7 = ${JSON.stringify(schema, null, 2)} as const;
247
+
248
+ export type ${toPascalCase(collectionName)}JsonSchema = typeof ${camelName}JsonSchema;
249
+
250
+ export default ${camelName}JsonSchema;
251
+ `;
252
+ }
253
+ generateIndexFile(outputFormat, jsonSchemasPath, verbose) {
254
+ if (!this.config.collections)
255
+ return;
256
+ const indexPath = path.join(jsonSchemasPath, "index.ts");
257
+ const imports = [];
258
+ const exports = [];
259
+ this.config.collections.forEach((collection) => {
260
+ const camelName = toCamelCase(collection.name);
261
+ const pascalName = toPascalCase(collection.name);
262
+ if (outputFormat === "typescript" || outputFormat === "both") {
263
+ imports.push(`import { ${camelName}JsonSchema } from "./${camelName}.schema.js";`);
264
+ exports.push(` ${camelName}: ${camelName}JsonSchema,`);
265
+ }
266
+ });
267
+ const indexContent = `// Auto-generated index for JSON schemas
268
+ ${imports.join('\n')}
269
+
270
+ export const jsonSchemas = {
271
+ ${exports.join('\n')}
272
+ };
273
+
274
+ export type JsonSchemas = typeof jsonSchemas;
275
+
276
+ // Individual schema exports
277
+ ${this.config.collections.map(collection => {
278
+ const camelName = toCamelCase(collection.name);
279
+ return `export { ${camelName}JsonSchema } from "./${camelName}.schema.js";`;
280
+ }).join('\n')}
281
+
282
+ export default jsonSchemas;
283
+ `;
284
+ fs.writeFileSync(indexPath, indexContent, { encoding: "utf-8" });
285
+ if (verbose) {
286
+ console.log(chalk.green(`✓ Index file written to ${indexPath}`));
287
+ }
288
+ }
289
+ validateSchema(schema) {
290
+ const errors = [];
291
+ // Basic validation
292
+ if (!schema.$schema) {
293
+ errors.push("Missing $schema property");
294
+ }
295
+ if (!schema.title) {
296
+ errors.push("Missing title property");
297
+ }
298
+ if (!schema.properties) {
299
+ errors.push("Missing properties");
300
+ }
301
+ if (!schema.required || !Array.isArray(schema.required)) {
302
+ errors.push("Missing or invalid required array");
303
+ }
304
+ // Validate required Appwrite fields
305
+ const requiredAppwriteFields = ["$id", "$createdAt", "$updatedAt"];
306
+ requiredAppwriteFields.forEach((field) => {
307
+ if (!schema.properties[field]) {
308
+ errors.push(`Missing required Appwrite field: ${field}`);
309
+ }
310
+ });
311
+ return { valid: errors.length === 0, errors };
312
+ }
313
+ }
@@ -0,0 +1,10 @@
1
+ import winston from "winston";
2
+ export interface LoggingConfig {
3
+ enabled: boolean;
4
+ level: string;
5
+ logDirectory?: string;
6
+ console: boolean;
7
+ }
8
+ export declare const configureLogging: (config?: Partial<LoggingConfig>) => void;
9
+ export declare let logger: winston.Logger;
10
+ export declare const updateLogger: () => void;
@@ -0,0 +1,46 @@
1
+ import winston from "winston";
2
+ import fs from "fs";
3
+ import path from "path";
4
+ const DEFAULT_LOGGING_CONFIG = {
5
+ enabled: false,
6
+ level: "info",
7
+ console: false,
8
+ };
9
+ let loggingConfig = DEFAULT_LOGGING_CONFIG;
10
+ export const configureLogging = (config = {}) => {
11
+ loggingConfig = { ...DEFAULT_LOGGING_CONFIG, ...config };
12
+ };
13
+ const createLogger = () => {
14
+ const transports = [];
15
+ // Add console transport if enabled
16
+ if (loggingConfig.console) {
17
+ transports.push(new winston.transports.Console({
18
+ format: winston.format.combine(winston.format.colorize(), winston.format.simple())
19
+ }));
20
+ }
21
+ // Add file transports if logging is enabled
22
+ if (loggingConfig.enabled) {
23
+ const logDir = loggingConfig.logDirectory || path.join(process.cwd(), "zlogs");
24
+ if (!fs.existsSync(logDir)) {
25
+ fs.mkdirSync(logDir, { recursive: true });
26
+ }
27
+ transports.push(new winston.transports.File({
28
+ filename: path.join(logDir, "error.log"),
29
+ level: "error",
30
+ }), new winston.transports.File({
31
+ filename: path.join(logDir, "combined.log"),
32
+ }));
33
+ }
34
+ return winston.createLogger({
35
+ level: loggingConfig.level,
36
+ format: winston.format.combine(winston.format.timestamp(), winston.format.errors({ stack: true }), winston.format.json()),
37
+ defaultMeta: { service: "appwrite-utils-cli" },
38
+ transports,
39
+ silent: !loggingConfig.enabled && !loggingConfig.console,
40
+ });
41
+ };
42
+ export let logger = createLogger();
43
+ // Recreate logger when config changes
44
+ export const updateLogger = () => {
45
+ logger = createLogger();
46
+ };
@@ -0,0 +1,37 @@
1
+ export interface MessageOptions {
2
+ prefix?: string;
3
+ skipLogging?: boolean;
4
+ logLevel?: "info" | "warn" | "error" | "debug";
5
+ }
6
+ export declare class MessageFormatter {
7
+ static success(message: string, options?: MessageOptions): void;
8
+ static error(message: string, error?: Error | string, options?: MessageOptions): void;
9
+ static warning(message: string, options?: MessageOptions): void;
10
+ static info(message: string, options?: MessageOptions): void;
11
+ static step(step: number, total: number, message: string, options?: MessageOptions): void;
12
+ static progress(message: string, options?: MessageOptions): void;
13
+ static debug(message: string, data?: any, options?: MessageOptions): void;
14
+ static banner(title: string, subtitle?: string): void;
15
+ static section(title: string): void;
16
+ static list(items: string[], title?: string): void;
17
+ static table(data: Record<string, string | number>[], headers?: string[]): void;
18
+ static operationSummary(title: string, stats: Record<string, string | number>, duration?: number): void;
19
+ static formatBytes(bytes: number): string;
20
+ static formatDuration(ms: number): string;
21
+ static formatNumber(num: number): string;
22
+ }
23
+ export declare const Messages: {
24
+ readonly CONFIG_NOT_FOUND: "Appwrite configuration not found. Run 'appwrite-migrate setup' first.";
25
+ readonly CONFIG_LOADED: (type: string, path: string) => string;
26
+ readonly DATABASE_CONNECTION_FAILED: "Failed to connect to Appwrite. Check your endpoint and API key.";
27
+ readonly OPERATION_CANCELLED: "Operation cancelled by user.";
28
+ readonly OPERATION_COMPLETED: (operation: string) => string;
29
+ readonly BACKUP_STARTED: (database: string) => string;
30
+ readonly BACKUP_COMPLETED: (database: string, size: number) => string;
31
+ readonly IMPORT_STARTED: (collections: number) => string;
32
+ readonly IMPORT_COMPLETED: (documents: number) => string;
33
+ readonly FUNCTION_DEPLOYED: (name: string) => string;
34
+ readonly FUNCTION_DEPLOYMENT_FAILED: (name: string, error: string) => string;
35
+ readonly TRANSFER_STARTED: (source: string, target: string) => string;
36
+ readonly TRANSFER_COMPLETED: (items: number) => string;
37
+ };
@@ -0,0 +1,152 @@
1
+ import chalk from "chalk";
2
+ import { logger } from "./logging.js";
3
+ export class MessageFormatter {
4
+ static success(message, options = {}) {
5
+ const formatted = `${chalk.green("✅")} ${options.prefix ? `${options.prefix}: ` : ""}${message}`;
6
+ console.log(formatted);
7
+ if (!options.skipLogging) {
8
+ logger.info(`SUCCESS: ${options.prefix ? `${options.prefix}: ` : ""}${message}`);
9
+ }
10
+ }
11
+ static error(message, error, options = {}) {
12
+ const errorDetails = error instanceof Error ? error.message : error;
13
+ const formatted = `${chalk.red("❌")} ${options.prefix ? `${options.prefix}: ` : ""}${message}${errorDetails ? `\n ${chalk.gray(errorDetails)}` : ""}`;
14
+ console.error(formatted);
15
+ if (!options.skipLogging) {
16
+ logger.error(`ERROR: ${options.prefix ? `${options.prefix}: ` : ""}${message}`, {
17
+ error: errorDetails,
18
+ stack: error instanceof Error ? error.stack : undefined,
19
+ });
20
+ }
21
+ }
22
+ static warning(message, options = {}) {
23
+ const formatted = `${chalk.yellow("⚠️")} ${options.prefix ? `${options.prefix}: ` : ""}${message}`;
24
+ console.log(formatted);
25
+ if (!options.skipLogging) {
26
+ logger.warn(`WARNING: ${options.prefix ? `${options.prefix}: ` : ""}${message}`);
27
+ }
28
+ }
29
+ static info(message, options = {}) {
30
+ const formatted = `${chalk.blue("ℹ️")} ${options.prefix ? `${options.prefix}: ` : ""}${message}`;
31
+ console.log(formatted);
32
+ if (!options.skipLogging) {
33
+ logger.info(`INFO: ${options.prefix ? `${options.prefix}: ` : ""}${message}`);
34
+ }
35
+ }
36
+ static step(step, total, message, options = {}) {
37
+ const formatted = `${chalk.cyan(`[${step}/${total}]`)} ${options.prefix ? `${options.prefix}: ` : ""}${message}`;
38
+ console.log(formatted);
39
+ if (!options.skipLogging) {
40
+ logger.info(`STEP ${step}/${total}: ${options.prefix ? `${options.prefix}: ` : ""}${message}`);
41
+ }
42
+ }
43
+ static progress(message, options = {}) {
44
+ const formatted = `${chalk.gray("⏳")} ${options.prefix ? `${options.prefix}: ` : ""}${message}`;
45
+ console.log(formatted);
46
+ if (!options.skipLogging) {
47
+ logger.debug(`PROGRESS: ${options.prefix ? `${options.prefix}: ` : ""}${message}`);
48
+ }
49
+ }
50
+ static debug(message, data, options = {}) {
51
+ if (process.env.NODE_ENV === "development" || process.env.DEBUG) {
52
+ const formatted = `${chalk.magenta("🔍")} ${options.prefix ? `${options.prefix}: ` : ""}${message}`;
53
+ console.log(formatted);
54
+ if (data) {
55
+ console.log(chalk.gray(JSON.stringify(data, null, 2)));
56
+ }
57
+ }
58
+ if (!options.skipLogging) {
59
+ logger.debug(`DEBUG: ${options.prefix ? `${options.prefix}: ` : ""}${message}`, data);
60
+ }
61
+ }
62
+ static banner(title, subtitle) {
63
+ const divider = chalk.cyan("═".repeat(60));
64
+ console.log(`\n${divider}`);
65
+ console.log(chalk.cyan.bold(` ${title}`));
66
+ if (subtitle) {
67
+ console.log(chalk.gray(` ${subtitle}`));
68
+ }
69
+ console.log(`${divider}\n`);
70
+ }
71
+ static section(title) {
72
+ console.log(`\n${chalk.bold.underline(title)}`);
73
+ }
74
+ static list(items, title) {
75
+ if (title) {
76
+ console.log(chalk.bold(title));
77
+ }
78
+ items.forEach((item, index) => {
79
+ console.log(`${chalk.gray(` ${index + 1}.`)} ${item}`);
80
+ });
81
+ }
82
+ static table(data, headers) {
83
+ if (data.length === 0)
84
+ return;
85
+ const keys = headers || Object.keys(data[0]);
86
+ const maxWidths = keys.map(key => Math.max(key.length, ...data.map(row => String(row[key]).length)));
87
+ // Header
88
+ const headerRow = keys.map((key, i) => chalk.bold(key.padEnd(maxWidths[i]))).join(" │ ");
89
+ console.log(`┌─${keys.map((_, i) => "─".repeat(maxWidths[i])).join("─┼─")}─┐`);
90
+ console.log(`│ ${headerRow} │`);
91
+ console.log(`├─${keys.map((_, i) => "─".repeat(maxWidths[i])).join("─┼─")}─┤`);
92
+ // Rows
93
+ data.forEach(row => {
94
+ const dataRow = keys.map((key, i) => String(row[key]).padEnd(maxWidths[i])).join(" │ ");
95
+ console.log(`│ ${dataRow} │`);
96
+ });
97
+ console.log(`└─${keys.map((_, i) => "─".repeat(maxWidths[i])).join("─┴─")}─┘`);
98
+ }
99
+ static operationSummary(title, stats, duration) {
100
+ this.section(`${title} Summary`);
101
+ Object.entries(stats).forEach(([key, value]) => {
102
+ const formattedKey = key.replace(/([A-Z])/g, ' $1').replace(/^./, str => str.toUpperCase());
103
+ console.log(`${chalk.gray("●")} ${formattedKey}: ${chalk.cyan(String(value))}`);
104
+ });
105
+ if (duration) {
106
+ console.log(`${chalk.gray("●")} Duration: ${chalk.cyan(this.formatDuration(duration))}`);
107
+ }
108
+ console.log();
109
+ }
110
+ static formatBytes(bytes) {
111
+ const units = ['B', 'KB', 'MB', 'GB', 'TB'];
112
+ let size = bytes;
113
+ let unitIndex = 0;
114
+ while (size >= 1024 && unitIndex < units.length - 1) {
115
+ size /= 1024;
116
+ unitIndex++;
117
+ }
118
+ return `${size.toFixed(1)} ${units[unitIndex]}`;
119
+ }
120
+ static formatDuration(ms) {
121
+ const seconds = Math.floor(ms / 1000);
122
+ const minutes = Math.floor(seconds / 60);
123
+ const hours = Math.floor(minutes / 60);
124
+ if (hours > 0) {
125
+ return `${hours}h ${minutes % 60}m ${seconds % 60}s`;
126
+ }
127
+ else if (minutes > 0) {
128
+ return `${minutes}m ${seconds % 60}s`;
129
+ }
130
+ else {
131
+ return `${seconds}s`;
132
+ }
133
+ }
134
+ static formatNumber(num) {
135
+ return num.toLocaleString();
136
+ }
137
+ }
138
+ export const Messages = {
139
+ CONFIG_NOT_FOUND: "Appwrite configuration not found. Run 'appwrite-migrate setup' first.",
140
+ CONFIG_LOADED: (type, path) => `Loaded ${type} configuration from ${path}`,
141
+ DATABASE_CONNECTION_FAILED: "Failed to connect to Appwrite. Check your endpoint and API key.",
142
+ OPERATION_CANCELLED: "Operation cancelled by user.",
143
+ OPERATION_COMPLETED: (operation) => `${operation} completed successfully`,
144
+ BACKUP_STARTED: (database) => `Starting backup for database: ${database}`,
145
+ BACKUP_COMPLETED: (database, size) => `Backup completed for ${database} (${MessageFormatter.formatBytes(size)})`,
146
+ IMPORT_STARTED: (collections) => `Starting import process for ${collections} collection(s)`,
147
+ IMPORT_COMPLETED: (documents) => `Import completed. Processed ${MessageFormatter.formatNumber(documents)} documents`,
148
+ FUNCTION_DEPLOYED: (name) => `Function '${name}' deployed successfully`,
149
+ FUNCTION_DEPLOYMENT_FAILED: (name, error) => `Function '${name}' deployment failed: ${error}`,
150
+ TRANSFER_STARTED: (source, target) => `Starting transfer from ${source} to ${target}`,
151
+ TRANSFER_COMPLETED: (items) => `Transfer completed. Moved ${MessageFormatter.formatNumber(items)} items`,
152
+ };