appwrite-utils-cli 0.10.86 → 1.0.2
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.
- package/.appwrite/.yaml_schemas/appwrite-config.schema.json +380 -0
- package/.appwrite/.yaml_schemas/collection.schema.json +255 -0
- package/.appwrite/collections/Categories.yaml +182 -0
- package/.appwrite/collections/ExampleCollection.yaml +36 -0
- package/.appwrite/collections/Posts.yaml +227 -0
- package/.appwrite/collections/Users.yaml +149 -0
- package/.appwrite/config.yaml +109 -0
- package/.appwrite/import/README.md +148 -0
- package/.appwrite/import/categories-import.yaml +129 -0
- package/.appwrite/import/posts-import.yaml +208 -0
- package/.appwrite/import/users-import.yaml +130 -0
- package/.appwrite/importData/categories.json +194 -0
- package/.appwrite/importData/posts.json +270 -0
- package/.appwrite/importData/users.json +220 -0
- package/.appwrite/schemas/categories.json +128 -0
- package/.appwrite/schemas/exampleCollection.json +52 -0
- package/.appwrite/schemas/posts.json +173 -0
- package/.appwrite/schemas/users.json +125 -0
- package/README.md +264 -33
- package/dist/collections/attributes.js +3 -2
- package/dist/collections/methods.js +56 -38
- package/dist/config/yamlConfig.d.ts +501 -0
- package/dist/config/yamlConfig.js +452 -0
- package/dist/databases/setup.d.ts +6 -0
- package/dist/databases/setup.js +119 -0
- package/dist/functions/methods.d.ts +1 -1
- package/dist/functions/methods.js +5 -2
- package/dist/functions/openapi.d.ts +4 -0
- package/dist/functions/openapi.js +60 -0
- package/dist/interactiveCLI.d.ts +5 -0
- package/dist/interactiveCLI.js +194 -49
- package/dist/main.js +91 -30
- package/dist/migrations/afterImportActions.js +2 -2
- package/dist/migrations/appwriteToX.d.ts +10 -0
- package/dist/migrations/appwriteToX.js +15 -4
- package/dist/migrations/backup.d.ts +16 -16
- package/dist/migrations/dataLoader.d.ts +83 -1
- package/dist/migrations/dataLoader.js +4 -4
- package/dist/migrations/importController.js +25 -18
- package/dist/migrations/importDataActions.js +2 -2
- package/dist/migrations/logging.d.ts +9 -1
- package/dist/migrations/logging.js +41 -22
- package/dist/migrations/migrationHelper.d.ts +4 -4
- package/dist/migrations/relationships.js +1 -1
- package/dist/migrations/services/DataTransformationService.d.ts +55 -0
- package/dist/migrations/services/DataTransformationService.js +158 -0
- package/dist/migrations/services/FileHandlerService.d.ts +75 -0
- package/dist/migrations/services/FileHandlerService.js +236 -0
- package/dist/migrations/services/ImportOrchestrator.d.ts +97 -0
- package/dist/migrations/services/ImportOrchestrator.js +488 -0
- package/dist/migrations/services/RateLimitManager.d.ts +138 -0
- package/dist/migrations/services/RateLimitManager.js +279 -0
- package/dist/migrations/services/RelationshipResolver.d.ts +120 -0
- package/dist/migrations/services/RelationshipResolver.js +332 -0
- package/dist/migrations/services/UserMappingService.d.ts +109 -0
- package/dist/migrations/services/UserMappingService.js +277 -0
- package/dist/migrations/services/ValidationService.d.ts +74 -0
- package/dist/migrations/services/ValidationService.js +260 -0
- package/dist/migrations/transfer.d.ts +0 -6
- package/dist/migrations/transfer.js +16 -132
- package/dist/migrations/yaml/YamlImportConfigLoader.d.ts +384 -0
- package/dist/migrations/yaml/YamlImportConfigLoader.js +375 -0
- package/dist/migrations/yaml/YamlImportIntegration.d.ts +87 -0
- package/dist/migrations/yaml/YamlImportIntegration.js +330 -0
- package/dist/migrations/yaml/generateImportSchemas.d.ts +17 -0
- package/dist/migrations/yaml/generateImportSchemas.js +575 -0
- package/dist/schemas/authUser.d.ts +9 -9
- package/dist/shared/attributeManager.d.ts +17 -0
- package/dist/shared/attributeManager.js +273 -0
- package/dist/shared/confirmationDialogs.d.ts +75 -0
- package/dist/shared/confirmationDialogs.js +236 -0
- package/dist/shared/functionManager.d.ts +48 -0
- package/dist/shared/functionManager.js +322 -0
- package/dist/shared/indexManager.d.ts +24 -0
- package/dist/shared/indexManager.js +150 -0
- package/dist/shared/jsonSchemaGenerator.d.ts +51 -0
- package/dist/shared/jsonSchemaGenerator.js +313 -0
- package/dist/shared/logging.d.ts +10 -0
- package/dist/shared/logging.js +46 -0
- package/dist/shared/messageFormatter.d.ts +37 -0
- package/dist/shared/messageFormatter.js +152 -0
- package/dist/shared/migrationHelpers.d.ts +173 -0
- package/dist/shared/migrationHelpers.js +142 -0
- package/dist/shared/operationLogger.d.ts +3 -0
- package/dist/shared/operationLogger.js +25 -0
- package/dist/shared/operationQueue.d.ts +13 -0
- package/dist/shared/operationQueue.js +79 -0
- package/dist/shared/progressManager.d.ts +62 -0
- package/dist/shared/progressManager.js +215 -0
- package/dist/shared/schemaGenerator.d.ts +18 -0
- package/dist/shared/schemaGenerator.js +523 -0
- package/dist/storage/methods.d.ts +3 -1
- package/dist/storage/methods.js +144 -55
- package/dist/storage/schemas.d.ts +56 -16
- package/dist/types.d.ts +2 -2
- package/dist/types.js +1 -1
- package/dist/users/methods.d.ts +16 -0
- package/dist/users/methods.js +276 -0
- package/dist/utils/configMigration.d.ts +1 -0
- package/dist/utils/configMigration.js +262 -0
- package/dist/utils/dataConverters.d.ts +46 -0
- package/dist/utils/dataConverters.js +139 -0
- package/dist/utils/loadConfigs.d.ts +15 -4
- package/dist/utils/loadConfigs.js +379 -51
- package/dist/utils/schemaStrings.js +2 -1
- package/dist/utils/setupFiles.d.ts +2 -1
- package/dist/utils/setupFiles.js +723 -28
- package/dist/utils/validationRules.d.ts +43 -0
- package/dist/utils/validationRules.js +42 -0
- package/dist/utils/yamlConverter.d.ts +48 -0
- package/dist/utils/yamlConverter.js +98 -0
- package/dist/utilsController.js +65 -43
- package/package.json +19 -15
- package/src/collections/attributes.ts +3 -2
- package/src/collections/methods.ts +85 -51
- package/src/config/yamlConfig.ts +488 -0
- package/src/{migrations/setupDatabase.ts → databases/setup.ts} +11 -5
- package/src/functions/methods.ts +8 -4
- package/src/functions/templates/count-docs-in-collection/package.json +25 -0
- package/src/functions/templates/count-docs-in-collection/tsconfig.json +28 -0
- package/src/functions/templates/typescript-node/package.json +24 -0
- package/src/functions/templates/typescript-node/tsconfig.json +28 -0
- package/src/functions/templates/uv/README.md +31 -0
- package/src/functions/templates/uv/pyproject.toml +29 -0
- package/src/interactiveCLI.ts +226 -61
- package/src/main.ts +111 -37
- package/src/migrations/afterImportActions.ts +2 -2
- package/src/migrations/appwriteToX.ts +17 -4
- package/src/migrations/dataLoader.ts +4 -4
- package/src/migrations/importController.ts +30 -22
- package/src/migrations/importDataActions.ts +2 -2
- package/src/migrations/relationships.ts +1 -1
- package/src/migrations/services/DataTransformationService.ts +196 -0
- package/src/migrations/services/FileHandlerService.ts +311 -0
- package/src/migrations/services/ImportOrchestrator.ts +669 -0
- package/src/migrations/services/RateLimitManager.ts +363 -0
- package/src/migrations/services/RelationshipResolver.ts +461 -0
- package/src/migrations/services/UserMappingService.ts +345 -0
- package/src/migrations/services/ValidationService.ts +349 -0
- package/src/migrations/transfer.ts +22 -228
- package/src/migrations/yaml/YamlImportConfigLoader.ts +427 -0
- package/src/migrations/yaml/YamlImportIntegration.ts +419 -0
- package/src/migrations/yaml/generateImportSchemas.ts +589 -0
- package/src/shared/attributeManager.ts +429 -0
- package/src/shared/confirmationDialogs.ts +327 -0
- package/src/shared/functionManager.ts +515 -0
- package/src/shared/indexManager.ts +253 -0
- package/src/shared/jsonSchemaGenerator.ts +403 -0
- package/src/shared/logging.ts +74 -0
- package/src/shared/messageFormatter.ts +195 -0
- package/src/{migrations/migrationHelper.ts → shared/migrationHelpers.ts} +22 -4
- package/src/{migrations/helper.ts → shared/operationLogger.ts} +7 -2
- package/src/{migrations/queue.ts → shared/operationQueue.ts} +1 -1
- package/src/shared/progressManager.ts +278 -0
- package/src/{migrations/schemaStrings.ts → shared/schemaGenerator.ts} +71 -17
- package/src/storage/methods.ts +199 -78
- package/src/types.ts +2 -2
- package/src/{migrations/users.ts → users/methods.ts} +2 -2
- package/src/utils/configMigration.ts +349 -0
- package/src/utils/loadConfigs.ts +416 -52
- package/src/utils/schemaStrings.ts +2 -1
- package/src/utils/setupFiles.ts +742 -40
- package/src/{migrations → utils}/validationRules.ts +1 -1
- package/src/utils/yamlConverter.ts +131 -0
- package/src/utilsController.ts +75 -54
- package/src/functions/templates/poetry/README.md +0 -30
- package/src/functions/templates/poetry/pyproject.toml +0 -16
- package/src/migrations/attributes.ts +0 -561
- package/src/migrations/backup.ts +0 -205
- package/src/migrations/databases.ts +0 -39
- package/src/migrations/dbHelpers.ts +0 -92
- package/src/migrations/indexes.ts +0 -40
- package/src/migrations/logging.ts +0 -29
- package/src/migrations/storage.ts +0 -538
- /package/src/{migrations → functions}/openapi.ts +0 -0
- /package/src/functions/templates/{poetry → uv}/src/__init__.py +0 -0
- /package/src/functions/templates/{poetry → uv}/src/index.py +0 -0
- /package/src/{migrations/converters.ts → utils/dataConverters.ts} +0 -0
@@ -0,0 +1,322 @@
|
|
1
|
+
import { Client, Functions, Runtime } from "node-appwrite";
|
2
|
+
import {} from "appwrite-utils";
|
3
|
+
import { join, relative, resolve, basename } from "node:path";
|
4
|
+
import fs from "node:fs";
|
5
|
+
import chalk from "chalk";
|
6
|
+
import pLimit from "p-limit";
|
7
|
+
import { tryAwaitWithRetry } from "../utils/helperFunctions.js";
|
8
|
+
// Concurrency limits
|
9
|
+
const functionLimit = pLimit(5); // Moderate limit for function operations
|
10
|
+
const queryLimit = pLimit(25); // Higher limit for read operations
|
11
|
+
export class FunctionManager {
|
12
|
+
client;
|
13
|
+
functions;
|
14
|
+
constructor(client) {
|
15
|
+
this.client = client;
|
16
|
+
this.functions = new Functions(client);
|
17
|
+
}
|
18
|
+
/**
|
19
|
+
* Improved function directory detection with multiple strategies
|
20
|
+
*/
|
21
|
+
async findFunctionDirectory(functionName, options = {}) {
|
22
|
+
const { searchPaths = [process.cwd()], caseSensitive = false, allowFuzzyMatch = true, verbose = false } = options;
|
23
|
+
if (verbose) {
|
24
|
+
console.log(chalk.blue(`🔍 Searching for function: ${functionName}`));
|
25
|
+
}
|
26
|
+
// Normalize function name for comparison
|
27
|
+
const normalizedName = caseSensitive ? functionName : functionName.toLowerCase();
|
28
|
+
const nameVariations = this.generateNameVariations(normalizedName);
|
29
|
+
// Strategy 1: Check standard locations first
|
30
|
+
const standardPaths = this.getStandardFunctionPaths(searchPaths, functionName);
|
31
|
+
for (const path of standardPaths) {
|
32
|
+
if (await this.isValidFunctionDirectory(path)) {
|
33
|
+
if (verbose) {
|
34
|
+
console.log(chalk.green(`✓ Found function at standard location: ${path}`));
|
35
|
+
}
|
36
|
+
return path;
|
37
|
+
}
|
38
|
+
}
|
39
|
+
// Strategy 2: Recursive directory search with fuzzy matching
|
40
|
+
if (allowFuzzyMatch) {
|
41
|
+
for (const searchPath of searchPaths) {
|
42
|
+
const foundPath = await this.recursiveDirectorySearch(searchPath, nameVariations, { caseSensitive, verbose });
|
43
|
+
if (foundPath) {
|
44
|
+
if (verbose) {
|
45
|
+
console.log(chalk.green(`✓ Found function via fuzzy search: ${foundPath}`));
|
46
|
+
}
|
47
|
+
return foundPath;
|
48
|
+
}
|
49
|
+
}
|
50
|
+
}
|
51
|
+
if (verbose) {
|
52
|
+
console.log(chalk.yellow(`⚠ Function directory not found: ${functionName}`));
|
53
|
+
}
|
54
|
+
return null;
|
55
|
+
}
|
56
|
+
generateNameVariations(name) {
|
57
|
+
const variations = new Set([
|
58
|
+
name,
|
59
|
+
name.toLowerCase(),
|
60
|
+
name.replace(/\s+/g, "-"),
|
61
|
+
name.replace(/\s+/g, "_"),
|
62
|
+
name.replace(/[^a-z0-9]/gi, ""),
|
63
|
+
name.replace(/[-_\s]+/g, ""),
|
64
|
+
name.replace(/[-_\s]+/g, "-").toLowerCase(),
|
65
|
+
name.replace(/[-_\s]+/g, "_").toLowerCase(),
|
66
|
+
]);
|
67
|
+
return variations;
|
68
|
+
}
|
69
|
+
getStandardFunctionPaths(searchPaths, functionName) {
|
70
|
+
const normalizedName = functionName.toLowerCase().replace(/\s+/g, "-");
|
71
|
+
const paths = [];
|
72
|
+
for (const basePath of searchPaths) {
|
73
|
+
paths.push(join(basePath, "functions", functionName), join(basePath, "functions", normalizedName), join(basePath, "src", "functions", functionName), join(basePath, "src", "functions", normalizedName), join(basePath, functionName), join(basePath, normalizedName), join(basePath, "appwrite", "functions", functionName), join(basePath, "appwrite", "functions", normalizedName));
|
74
|
+
}
|
75
|
+
return paths;
|
76
|
+
}
|
77
|
+
async recursiveDirectorySearch(searchPath, nameVariations, options) {
|
78
|
+
const { caseSensitive, verbose } = options;
|
79
|
+
try {
|
80
|
+
const stats = await fs.promises.stat(searchPath);
|
81
|
+
if (!stats.isDirectory())
|
82
|
+
return null;
|
83
|
+
const entries = await fs.promises.readdir(searchPath, { withFileTypes: true });
|
84
|
+
for (const entry of entries) {
|
85
|
+
if (!entry.isDirectory())
|
86
|
+
continue;
|
87
|
+
// Skip common directories that won't contain functions
|
88
|
+
if (this.shouldSkipDirectory(entry.name))
|
89
|
+
continue;
|
90
|
+
const entryPath = join(searchPath, entry.name);
|
91
|
+
// Check if this directory matches our function name
|
92
|
+
const entryNameToCheck = caseSensitive ? entry.name : entry.name.toLowerCase();
|
93
|
+
if (nameVariations.has(entryNameToCheck)) {
|
94
|
+
if (await this.isValidFunctionDirectory(entryPath)) {
|
95
|
+
return entryPath;
|
96
|
+
}
|
97
|
+
}
|
98
|
+
// Recursively search subdirectories
|
99
|
+
const result = await this.recursiveDirectorySearch(entryPath, nameVariations, options);
|
100
|
+
if (result)
|
101
|
+
return result;
|
102
|
+
}
|
103
|
+
}
|
104
|
+
catch (error) {
|
105
|
+
if (verbose) {
|
106
|
+
console.log(chalk.gray(`Skipping inaccessible directory: ${searchPath}`));
|
107
|
+
}
|
108
|
+
}
|
109
|
+
return null;
|
110
|
+
}
|
111
|
+
shouldSkipDirectory(dirName) {
|
112
|
+
const skipDirs = new Set([
|
113
|
+
'node_modules',
|
114
|
+
'.git',
|
115
|
+
'.vscode',
|
116
|
+
'.idea',
|
117
|
+
'dist',
|
118
|
+
'build',
|
119
|
+
'coverage',
|
120
|
+
'.nyc_output',
|
121
|
+
'tmp',
|
122
|
+
'temp',
|
123
|
+
'.cache',
|
124
|
+
'__pycache__',
|
125
|
+
'.pytest_cache',
|
126
|
+
'venv',
|
127
|
+
'.venv',
|
128
|
+
'env',
|
129
|
+
'.env'
|
130
|
+
]);
|
131
|
+
return skipDirs.has(dirName) || dirName.startsWith('.');
|
132
|
+
}
|
133
|
+
async isValidFunctionDirectory(path) {
|
134
|
+
try {
|
135
|
+
const stats = await fs.promises.stat(path);
|
136
|
+
if (!stats.isDirectory())
|
137
|
+
return false;
|
138
|
+
const files = await fs.promises.readdir(path);
|
139
|
+
// Check for common function indicators
|
140
|
+
const hasPackageJson = files.includes('package.json');
|
141
|
+
const hasMainFile = files.some(file => file.match(/^(index|main|app)\.(js|ts|py)$/i) ||
|
142
|
+
file === 'src' ||
|
143
|
+
file === 'lib');
|
144
|
+
const hasRequirements = files.includes('requirements.txt');
|
145
|
+
const hasPyProject = files.includes('pyproject.toml');
|
146
|
+
return hasPackageJson || hasMainFile || hasRequirements || hasPyProject;
|
147
|
+
}
|
148
|
+
catch {
|
149
|
+
return false;
|
150
|
+
}
|
151
|
+
}
|
152
|
+
/**
|
153
|
+
* Enhanced function deployment with better error handling and validation
|
154
|
+
*/
|
155
|
+
async deployFunction(functionConfig, functionPath, options = {}) {
|
156
|
+
const { activate = true, entrypoint = functionConfig.entrypoint || "index.js", commands = functionConfig.commands || "npm install", ignored = ["node_modules", ".git", ".vscode", ".DS_Store", "__pycache__", ".venv"], verbose = false, forceRedeploy = false } = options;
|
157
|
+
return await functionLimit(async () => {
|
158
|
+
if (verbose) {
|
159
|
+
console.log(chalk.blue(`🚀 Deploying function: ${functionConfig.name}`));
|
160
|
+
console.log(chalk.gray(` Path: ${functionPath}`));
|
161
|
+
console.log(chalk.gray(` Entrypoint: ${entrypoint}`));
|
162
|
+
}
|
163
|
+
// Validate function directory
|
164
|
+
if (!await this.isValidFunctionDirectory(functionPath)) {
|
165
|
+
throw new Error(`Invalid function directory: ${functionPath}`);
|
166
|
+
}
|
167
|
+
// Ensure function exists
|
168
|
+
let functionExists = false;
|
169
|
+
try {
|
170
|
+
await this.getFunction(functionConfig.$id);
|
171
|
+
functionExists = true;
|
172
|
+
}
|
173
|
+
catch (error) {
|
174
|
+
if (verbose) {
|
175
|
+
console.log(chalk.yellow(`Function ${functionConfig.$id} does not exist, creating...`));
|
176
|
+
}
|
177
|
+
}
|
178
|
+
// Create function if it doesn't exist
|
179
|
+
if (!functionExists) {
|
180
|
+
await this.createFunction(functionConfig, { verbose });
|
181
|
+
}
|
182
|
+
else if (forceRedeploy) {
|
183
|
+
await this.updateFunction(functionConfig, { verbose });
|
184
|
+
}
|
185
|
+
// Execute pre-deploy commands if specified
|
186
|
+
if (functionConfig.predeployCommands?.length) {
|
187
|
+
await this.executePredeployCommands(functionConfig.predeployCommands, functionPath, { verbose });
|
188
|
+
}
|
189
|
+
// Deploy the function
|
190
|
+
const deployment = await this.createDeployment(functionConfig.$id, functionPath, { activate, entrypoint, commands, ignored, verbose });
|
191
|
+
if (verbose) {
|
192
|
+
console.log(chalk.green(`✅ Function ${functionConfig.name} deployed successfully`));
|
193
|
+
}
|
194
|
+
return deployment;
|
195
|
+
});
|
196
|
+
}
|
197
|
+
async createFunction(functionConfig, options = {}) {
|
198
|
+
const { verbose = false } = options;
|
199
|
+
if (verbose) {
|
200
|
+
console.log(chalk.blue(`Creating function: ${functionConfig.name}`));
|
201
|
+
}
|
202
|
+
return await tryAwaitWithRetry(async () => {
|
203
|
+
return await this.functions.create(functionConfig.$id, functionConfig.name, functionConfig.runtime, functionConfig.execute || [], functionConfig.events || [], functionConfig.schedule || "", functionConfig.timeout || 15, functionConfig.enabled !== false, functionConfig.logging !== false, functionConfig.entrypoint, functionConfig.commands, functionConfig.scopes || [], functionConfig.installationId, functionConfig.providerRepositoryId, functionConfig.providerBranch, functionConfig.providerSilentMode, functionConfig.providerRootDirectory, functionConfig.templateRepository, functionConfig.templateOwner, functionConfig.templateRootDirectory, functionConfig.templateVersion, functionConfig.specification);
|
204
|
+
});
|
205
|
+
}
|
206
|
+
async updateFunction(functionConfig, options = {}) {
|
207
|
+
const { verbose = false } = options;
|
208
|
+
if (verbose) {
|
209
|
+
console.log(chalk.blue(`Updating function: ${functionConfig.name}`));
|
210
|
+
}
|
211
|
+
return await tryAwaitWithRetry(async () => {
|
212
|
+
return await this.functions.update(functionConfig.$id, functionConfig.name, functionConfig.runtime, functionConfig.execute || [], functionConfig.events || [], functionConfig.schedule || "", functionConfig.timeout || 15, functionConfig.enabled !== false, functionConfig.logging !== false, functionConfig.entrypoint, functionConfig.commands, functionConfig.scopes || [], functionConfig.installationId, functionConfig.providerRepositoryId, functionConfig.providerBranch, functionConfig.providerSilentMode, functionConfig.providerRootDirectory, functionConfig.specification);
|
213
|
+
});
|
214
|
+
}
|
215
|
+
async executePredeployCommands(commands, workingDir, options = {}) {
|
216
|
+
const { verbose = false } = options;
|
217
|
+
const { execSync } = await import("child_process");
|
218
|
+
const { platform } = await import("node:os");
|
219
|
+
if (verbose) {
|
220
|
+
console.log(chalk.blue("Executing pre-deploy commands..."));
|
221
|
+
}
|
222
|
+
const isWindows = platform() === "win32";
|
223
|
+
for (const command of commands) {
|
224
|
+
if (verbose) {
|
225
|
+
console.log(chalk.gray(` $ ${command}`));
|
226
|
+
}
|
227
|
+
try {
|
228
|
+
execSync(command, {
|
229
|
+
cwd: workingDir,
|
230
|
+
stdio: verbose ? "inherit" : "pipe",
|
231
|
+
shell: isWindows ? "cmd.exe" : "/bin/sh",
|
232
|
+
windowsHide: true,
|
233
|
+
});
|
234
|
+
}
|
235
|
+
catch (error) {
|
236
|
+
console.error(chalk.red(`Failed to execute command: ${command}`));
|
237
|
+
throw error;
|
238
|
+
}
|
239
|
+
}
|
240
|
+
if (verbose) {
|
241
|
+
console.log(chalk.green("✓ Pre-deploy commands completed"));
|
242
|
+
}
|
243
|
+
}
|
244
|
+
async createDeployment(functionId, codePath, options = {}) {
|
245
|
+
const { activate = true, entrypoint = "index.js", commands = "npm install", ignored = [], verbose = false } = options;
|
246
|
+
const { InputFile } = await import("node-appwrite/file");
|
247
|
+
const { create: createTarball } = await import("tar");
|
248
|
+
const tarPath = join(process.cwd(), `function-${functionId}-${Date.now()}.tar.gz`);
|
249
|
+
try {
|
250
|
+
if (verbose) {
|
251
|
+
console.log(chalk.blue("Creating deployment archive..."));
|
252
|
+
}
|
253
|
+
// Create tarball
|
254
|
+
await createTarball({
|
255
|
+
gzip: true,
|
256
|
+
file: tarPath,
|
257
|
+
cwd: codePath,
|
258
|
+
filter: (path) => {
|
259
|
+
const relativePath = relative(codePath, join(codePath, path)).toLowerCase();
|
260
|
+
const shouldIgnore = ignored.some(pattern => relativePath.startsWith(pattern.toLowerCase()) ||
|
261
|
+
relativePath.includes(`/${pattern.toLowerCase()}`) ||
|
262
|
+
relativePath.includes(`\\${pattern.toLowerCase()}`));
|
263
|
+
if (shouldIgnore && verbose) {
|
264
|
+
console.log(chalk.gray(` Ignoring: ${path}`));
|
265
|
+
}
|
266
|
+
return !shouldIgnore;
|
267
|
+
},
|
268
|
+
}, ["."]);
|
269
|
+
// Read and upload
|
270
|
+
const fileBuffer = await fs.promises.readFile(tarPath);
|
271
|
+
const fileObject = InputFile.fromBuffer(new Uint8Array(fileBuffer), `function-${functionId}.tar.gz`);
|
272
|
+
if (verbose) {
|
273
|
+
console.log(chalk.blue("Uploading deployment..."));
|
274
|
+
}
|
275
|
+
const deployment = await tryAwaitWithRetry(async () => {
|
276
|
+
return await this.functions.createDeployment(functionId, fileObject, activate, entrypoint, commands);
|
277
|
+
});
|
278
|
+
return deployment;
|
279
|
+
}
|
280
|
+
finally {
|
281
|
+
// Clean up tarball
|
282
|
+
try {
|
283
|
+
await fs.promises.unlink(tarPath);
|
284
|
+
}
|
285
|
+
catch {
|
286
|
+
// Ignore cleanup errors
|
287
|
+
}
|
288
|
+
}
|
289
|
+
}
|
290
|
+
async getFunction(functionId) {
|
291
|
+
return await queryLimit(() => tryAwaitWithRetry(async () => await this.functions.get(functionId)));
|
292
|
+
}
|
293
|
+
async listFunctions() {
|
294
|
+
return await queryLimit(() => tryAwaitWithRetry(async () => await this.functions.list()));
|
295
|
+
}
|
296
|
+
async deleteFunction(functionId) {
|
297
|
+
await functionLimit(() => tryAwaitWithRetry(async () => await this.functions.delete(functionId)));
|
298
|
+
}
|
299
|
+
/**
|
300
|
+
* Validate function configuration
|
301
|
+
*/
|
302
|
+
validateFunctionConfig(functionConfig) {
|
303
|
+
const errors = [];
|
304
|
+
if (!functionConfig.$id) {
|
305
|
+
errors.push("Function ID is required");
|
306
|
+
}
|
307
|
+
if (!functionConfig.name) {
|
308
|
+
errors.push("Function name is required");
|
309
|
+
}
|
310
|
+
if (!functionConfig.runtime) {
|
311
|
+
errors.push("Function runtime is required");
|
312
|
+
}
|
313
|
+
if (!functionConfig.entrypoint) {
|
314
|
+
errors.push("Function entrypoint is required");
|
315
|
+
}
|
316
|
+
// Validate timeout
|
317
|
+
if (functionConfig.timeout && (functionConfig.timeout < 1 || functionConfig.timeout > 900)) {
|
318
|
+
errors.push("Function timeout must be between 1 and 900 seconds");
|
319
|
+
}
|
320
|
+
return { valid: errors.length === 0, errors };
|
321
|
+
}
|
322
|
+
}
|
@@ -0,0 +1,24 @@
|
|
1
|
+
import { type Index, type CollectionCreate } from "appwrite-utils";
|
2
|
+
import { Databases, type Models } from "node-appwrite";
|
3
|
+
export declare const indexesSame: (databaseIndex: Models.Index, configIndex: Index) => boolean;
|
4
|
+
export declare const createOrUpdateIndex: (dbId: string, db: Databases, collectionId: string, index: Index, options?: {
|
5
|
+
verbose?: boolean;
|
6
|
+
forceRecreate?: boolean;
|
7
|
+
}) => Promise<Models.Index | null>;
|
8
|
+
export declare const createOrUpdateIndexes: (dbId: string, db: Databases, collectionId: string, indexes: Index[], options?: {
|
9
|
+
verbose?: boolean;
|
10
|
+
forceRecreate?: boolean;
|
11
|
+
}) => Promise<void>;
|
12
|
+
export declare const createUpdateCollectionIndexes: (db: Databases, dbId: string, collection: Models.Collection, collectionConfig: CollectionCreate, options?: {
|
13
|
+
verbose?: boolean;
|
14
|
+
forceRecreate?: boolean;
|
15
|
+
}) => Promise<void>;
|
16
|
+
export declare const deleteObsoleteIndexes: (db: Databases, dbId: string, collection: Models.Collection, collectionConfig: CollectionCreate, options?: {
|
17
|
+
verbose?: boolean;
|
18
|
+
}) => Promise<void>;
|
19
|
+
export declare const validateIndexConfiguration: (indexes: Index[], options?: {
|
20
|
+
verbose?: boolean;
|
21
|
+
}) => {
|
22
|
+
valid: boolean;
|
23
|
+
errors: string[];
|
24
|
+
};
|
@@ -0,0 +1,150 @@
|
|
1
|
+
import {} from "appwrite-utils";
|
2
|
+
import { Databases, IndexType, Query } from "node-appwrite";
|
3
|
+
import { delay, tryAwaitWithRetry } from "../utils/helperFunctions.js";
|
4
|
+
import chalk from "chalk";
|
5
|
+
import pLimit from "p-limit";
|
6
|
+
// Concurrency limits for different operations
|
7
|
+
const indexLimit = pLimit(3); // Low limit for index operations
|
8
|
+
const queryLimit = pLimit(25); // Higher limit for read operations
|
9
|
+
export const indexesSame = (databaseIndex, configIndex) => {
|
10
|
+
return (databaseIndex.key === configIndex.key &&
|
11
|
+
databaseIndex.type === configIndex.type &&
|
12
|
+
JSON.stringify(databaseIndex.attributes) === JSON.stringify(configIndex.attributes) &&
|
13
|
+
JSON.stringify(databaseIndex.orders) === JSON.stringify(configIndex.orders));
|
14
|
+
};
|
15
|
+
export const createOrUpdateIndex = async (dbId, db, collectionId, index, options = {}) => {
|
16
|
+
const { verbose = false, forceRecreate = false } = options;
|
17
|
+
return await indexLimit(async () => {
|
18
|
+
// Check for existing index
|
19
|
+
const existingIndexes = await queryLimit(() => tryAwaitWithRetry(async () => await db.listIndexes(dbId, collectionId, [Query.equal("key", index.key)])));
|
20
|
+
let shouldCreate = false;
|
21
|
+
let existingIndex;
|
22
|
+
if (existingIndexes.total > 0) {
|
23
|
+
existingIndex = existingIndexes.indexes[0];
|
24
|
+
if (forceRecreate || !indexesSame(existingIndex, index)) {
|
25
|
+
if (verbose) {
|
26
|
+
console.log(chalk.yellow(`⚠ Updating index ${index.key} in collection ${collectionId}`));
|
27
|
+
}
|
28
|
+
// Delete existing index
|
29
|
+
await tryAwaitWithRetry(async () => {
|
30
|
+
await db.deleteIndex(dbId, collectionId, existingIndex.key);
|
31
|
+
});
|
32
|
+
await delay(500); // Wait for deletion to complete
|
33
|
+
shouldCreate = true;
|
34
|
+
}
|
35
|
+
else {
|
36
|
+
if (verbose) {
|
37
|
+
console.log(chalk.green(`✓ Index ${index.key} is up to date`));
|
38
|
+
}
|
39
|
+
return existingIndex;
|
40
|
+
}
|
41
|
+
}
|
42
|
+
else {
|
43
|
+
shouldCreate = true;
|
44
|
+
if (verbose) {
|
45
|
+
console.log(chalk.blue(`+ Creating index ${index.key} in collection ${collectionId}`));
|
46
|
+
}
|
47
|
+
}
|
48
|
+
if (shouldCreate) {
|
49
|
+
const newIndex = await tryAwaitWithRetry(async () => {
|
50
|
+
return await db.createIndex(dbId, collectionId, index.key, index.type, index.attributes, index.orders);
|
51
|
+
});
|
52
|
+
if (verbose) {
|
53
|
+
console.log(chalk.green(`✓ Created index ${index.key}`));
|
54
|
+
}
|
55
|
+
return newIndex;
|
56
|
+
}
|
57
|
+
return null;
|
58
|
+
});
|
59
|
+
};
|
60
|
+
export const createOrUpdateIndexes = async (dbId, db, collectionId, indexes, options = {}) => {
|
61
|
+
const { verbose = false } = options;
|
62
|
+
if (!indexes || indexes.length === 0) {
|
63
|
+
return;
|
64
|
+
}
|
65
|
+
if (verbose) {
|
66
|
+
console.log(chalk.blue(`Processing ${indexes.length} indexes for collection ${collectionId}`));
|
67
|
+
}
|
68
|
+
// Process indexes sequentially to avoid conflicts
|
69
|
+
for (const index of indexes) {
|
70
|
+
try {
|
71
|
+
await createOrUpdateIndex(dbId, db, collectionId, index, options);
|
72
|
+
// Add delay between index operations to prevent rate limiting
|
73
|
+
await delay(250);
|
74
|
+
}
|
75
|
+
catch (error) {
|
76
|
+
console.error(chalk.red(`❌ Failed to process index ${index.key}:`), error);
|
77
|
+
throw error;
|
78
|
+
}
|
79
|
+
}
|
80
|
+
if (verbose) {
|
81
|
+
console.log(chalk.green(`✓ Completed processing indexes for collection ${collectionId}`));
|
82
|
+
}
|
83
|
+
};
|
84
|
+
export const createUpdateCollectionIndexes = async (db, dbId, collection, collectionConfig, options = {}) => {
|
85
|
+
if (!collectionConfig.indexes)
|
86
|
+
return;
|
87
|
+
await createOrUpdateIndexes(dbId, db, collection.$id, collectionConfig.indexes, options);
|
88
|
+
};
|
89
|
+
export const deleteObsoleteIndexes = async (db, dbId, collection, collectionConfig, options = {}) => {
|
90
|
+
const { verbose = false } = options;
|
91
|
+
const configIndexes = collectionConfig.indexes || [];
|
92
|
+
const configIndexKeys = new Set(configIndexes.map(index => index.key));
|
93
|
+
// Get all existing indexes
|
94
|
+
const existingIndexes = await queryLimit(() => tryAwaitWithRetry(async () => await db.listIndexes(dbId, collection.$id)));
|
95
|
+
// Find indexes that exist in the database but not in the config
|
96
|
+
const obsoleteIndexes = existingIndexes.indexes.filter((index) => !configIndexKeys.has(index.key));
|
97
|
+
if (obsoleteIndexes.length === 0) {
|
98
|
+
return;
|
99
|
+
}
|
100
|
+
if (verbose) {
|
101
|
+
console.log(chalk.yellow(`🗑️ Removing ${obsoleteIndexes.length} obsolete indexes from collection ${collection.name}`));
|
102
|
+
}
|
103
|
+
// Process deletions with rate limiting
|
104
|
+
for (const index of obsoleteIndexes) {
|
105
|
+
await indexLimit(async () => {
|
106
|
+
await tryAwaitWithRetry(async () => {
|
107
|
+
await db.deleteIndex(dbId, collection.$id, index.key);
|
108
|
+
});
|
109
|
+
});
|
110
|
+
if (verbose) {
|
111
|
+
console.log(chalk.gray(`🗑️ Deleted obsolete index ${index.key}`));
|
112
|
+
}
|
113
|
+
await delay(250);
|
114
|
+
}
|
115
|
+
};
|
116
|
+
export const validateIndexConfiguration = (indexes, options = {}) => {
|
117
|
+
const { verbose = false } = options;
|
118
|
+
const errors = [];
|
119
|
+
for (const index of indexes) {
|
120
|
+
// Validate required fields
|
121
|
+
if (!index.key) {
|
122
|
+
errors.push(`Index missing required 'key' field`);
|
123
|
+
}
|
124
|
+
if (!index.type) {
|
125
|
+
errors.push(`Index '${index.key}' missing required 'type' field`);
|
126
|
+
}
|
127
|
+
if (!index.attributes || index.attributes.length === 0) {
|
128
|
+
errors.push(`Index '${index.key}' missing required 'attributes' field`);
|
129
|
+
}
|
130
|
+
// Validate index type
|
131
|
+
const validTypes = Object.values(IndexType);
|
132
|
+
if (index.type && !validTypes.includes(index.type)) {
|
133
|
+
errors.push(`Index '${index.key}' has invalid type '${index.type}'. Valid types: ${validTypes.join(', ')}`);
|
134
|
+
}
|
135
|
+
// Validate orders array matches attributes length (if provided)
|
136
|
+
if (index.orders && index.attributes && index.orders.length !== index.attributes.length) {
|
137
|
+
errors.push(`Index '${index.key}' orders array length (${index.orders.length}) does not match attributes array length (${index.attributes.length})`);
|
138
|
+
}
|
139
|
+
// Check for duplicate keys within the same collection
|
140
|
+
const duplicateKeys = indexes.filter(i => i.key === index.key);
|
141
|
+
if (duplicateKeys.length > 1) {
|
142
|
+
errors.push(`Duplicate index key '${index.key}' found`);
|
143
|
+
}
|
144
|
+
}
|
145
|
+
if (verbose && errors.length > 0) {
|
146
|
+
console.log(chalk.red(`❌ Index validation errors:`));
|
147
|
+
errors.forEach(error => console.log(chalk.red(` - ${error}`)));
|
148
|
+
}
|
149
|
+
return { valid: errors.length === 0, errors };
|
150
|
+
};
|
@@ -0,0 +1,51 @@
|
|
1
|
+
import type { AppwriteConfig } from "appwrite-utils";
|
2
|
+
export interface JsonSchemaProperty {
|
3
|
+
type: string | string[];
|
4
|
+
description?: string;
|
5
|
+
format?: string;
|
6
|
+
minimum?: number;
|
7
|
+
maximum?: number;
|
8
|
+
minLength?: number;
|
9
|
+
maxLength?: number;
|
10
|
+
pattern?: string;
|
11
|
+
enum?: any[];
|
12
|
+
items?: JsonSchemaProperty;
|
13
|
+
$ref?: string;
|
14
|
+
properties?: Record<string, JsonSchemaProperty>;
|
15
|
+
additionalProperties?: boolean;
|
16
|
+
required?: string[];
|
17
|
+
default?: any;
|
18
|
+
oneOf?: JsonSchemaProperty[];
|
19
|
+
}
|
20
|
+
export interface JsonSchema {
|
21
|
+
$schema: string;
|
22
|
+
$id: string;
|
23
|
+
title: string;
|
24
|
+
description?: string;
|
25
|
+
type: "object";
|
26
|
+
properties: Record<string, JsonSchemaProperty>;
|
27
|
+
required: string[];
|
28
|
+
additionalProperties: boolean;
|
29
|
+
definitions?: Record<string, JsonSchemaProperty>;
|
30
|
+
}
|
31
|
+
export declare class JsonSchemaGenerator {
|
32
|
+
private config;
|
33
|
+
private appwriteFolderPath;
|
34
|
+
private relationshipMap;
|
35
|
+
constructor(config: AppwriteConfig, appwriteFolderPath: string);
|
36
|
+
private extractRelationships;
|
37
|
+
private attributeToJsonSchemaProperty;
|
38
|
+
private getBaseTypeSchema;
|
39
|
+
private createJsonSchema;
|
40
|
+
generateJsonSchemas(options?: {
|
41
|
+
outputFormat?: "json" | "typescript" | "both";
|
42
|
+
outputDirectory?: string;
|
43
|
+
verbose?: boolean;
|
44
|
+
}): void;
|
45
|
+
private generateTypeScriptSchema;
|
46
|
+
private generateIndexFile;
|
47
|
+
validateSchema(schema: JsonSchema): {
|
48
|
+
valid: boolean;
|
49
|
+
errors: string[];
|
50
|
+
};
|
51
|
+
}
|