From 7bc80b2927b78def257bc459a147734429861e09 Mon Sep 17 00:00:00 2001 From: root Date: Mon, 22 Dec 2025 11:26:50 +0000 Subject: [PATCH] migrate: codebase from javascript to typescript --- CHANGELOG.md | 4 + README.md | 4 +- docs/examples/databases/upsert-document.md | 3 +- index.js | 147 -- index.ts | 152 ++ install.ps1 | 7 +- install.sh | 3 +- lib/client.js | 254 --- lib/client.ts | 259 +++ lib/commands/{account.js => account.ts} | 1070 ++++----- lib/commands/console.js | 127 -- lib/commands/console.ts | 112 + lib/commands/{databases.js => databases.ts} | 1954 +++++++---------- lib/commands/{functions.js => functions.ts} | 907 ++++---- lib/commands/{generic.js => generic.ts} | 86 +- lib/commands/graphql.js | 126 -- lib/commands/graphql.ts | 110 + lib/commands/{health.js => health.ts} | 452 ++-- lib/commands/{init.js => init.ts} | 134 +- lib/commands/{locale.js => locale.ts} | 196 +- lib/commands/{messaging.js => messaging.ts} | 1636 ++++++-------- lib/commands/{migrations.js => migrations.ts} | 440 ++-- lib/commands/organizations.js | 48 - lib/commands/organizations.ts | 46 + lib/commands/{project.js => project.ts} | 186 +- lib/commands/{projects.js => projects.ts} | 1430 +++++------- lib/commands/{proxy.js => proxy.ts} | 234 +- lib/commands/{pull.js => pull.ts} | 98 +- lib/commands/{push.js => push.ts} | 426 ++-- lib/commands/{run.js => run.ts} | 116 +- lib/commands/{sites.js => sites.ts} | 868 +++----- lib/commands/{storage.js => storage.ts} | 508 ++--- lib/commands/{tables-db.js => tables-db.ts} | 1943 +++++++--------- lib/commands/{teams.js => teams.ts} | 398 ++-- lib/commands/{tokens.js => tokens.ts} | 169 +- lib/commands/{types.js => types.ts} | 72 +- lib/commands/{update.js => update.ts} | 52 +- lib/commands/{users.js => users.ts} | 1070 ++++----- lib/commands/{vcs.js => vcs.ts} | 292 +-- lib/config.js | 825 ------- lib/config.ts | 854 +++++++ lib/emulation/{docker.js => docker.ts} | 77 +- lib/emulation/utils.js | 186 -- lib/emulation/utils.ts | 193 ++ lib/exception.js | 9 - lib/exception.ts | 20 + lib/{id.js => id.ts} | 10 +- lib/{paginate.js => paginate.ts} | 29 +- lib/parser.js | 250 --- lib/parser.ts | 238 ++ lib/{questions.js => questions.ts} | 304 ++- lib/sdks.js | 60 - lib/sdks.ts | 55 + lib/{spinner.js => spinner.ts} | 80 +- lib/type-generation/attribute.js | 19 - lib/type-generation/attribute.ts | 17 + .../languages/{csharp.js => csharp.ts} | 116 +- .../languages/{dart.js => dart.ts} | 180 +- .../languages/{java.js => java.ts} | 114 +- lib/type-generation/languages/javascript.js | 111 - lib/type-generation/languages/javascript.ts | 111 + lib/type-generation/languages/kotlin.js | 94 - lib/type-generation/languages/kotlin.ts | 96 + lib/type-generation/languages/language.js | 125 -- lib/type-generation/languages/language.ts | 119 + .../languages/{php.js => php.ts} | 108 +- .../languages/{swift.js => swift.ts} | 116 +- lib/type-generation/languages/typescript.js | 116 - lib/type-generation/languages/typescript.ts | 116 + lib/types.ts | 150 ++ lib/{utils.js => utils.ts} | 154 +- lib/validations.js | 17 - lib/validations.ts | 17 + package.json | 33 +- scoop/appwrite.config.json | 6 +- tsconfig.json | 30 + 76 files changed, 9572 insertions(+), 11722 deletions(-) delete mode 100644 index.js create mode 100644 index.ts delete mode 100644 lib/client.js create mode 100644 lib/client.ts rename lib/commands/{account.js => account.ts} (63%) delete mode 100644 lib/commands/console.js create mode 100644 lib/commands/console.ts rename lib/commands/{databases.js => databases.ts} (61%) rename lib/commands/{functions.js => functions.ts} (63%) rename lib/commands/{generic.js => generic.ts} (80%) delete mode 100644 lib/commands/graphql.js create mode 100644 lib/commands/graphql.ts rename lib/commands/{health.js => health.ts} (57%) rename lib/commands/{init.js => init.ts} (84%) rename lib/commands/{locale.js => locale.ts} (54%) rename lib/commands/{messaging.js => messaging.ts} (59%) rename lib/commands/{migrations.js => migrations.ts} (62%) delete mode 100644 lib/commands/organizations.js create mode 100644 lib/commands/organizations.ts rename lib/commands/{project.js => project.ts} (56%) rename lib/commands/{projects.js => projects.ts} (61%) rename lib/commands/{proxy.js => proxy.ts} (57%) rename lib/commands/{pull.js => pull.ts} (84%) rename lib/commands/{push.js => push.ts} (86%) rename lib/commands/{run.js => run.ts} (76%) rename lib/commands/{sites.js => sites.ts} (63%) rename lib/commands/{storage.js => storage.ts} (63%) rename lib/commands/{tables-db.js => tables-db.ts} (60%) rename lib/commands/{teams.js => teams.ts} (60%) rename lib/commands/{tokens.js => tokens.ts} (54%) rename lib/commands/{types.js => types.ts} (71%) rename lib/commands/{update.js => update.ts} (83%) rename lib/commands/{users.js => users.ts} (60%) rename lib/commands/{vcs.js => vcs.ts} (63%) delete mode 100644 lib/config.js create mode 100644 lib/config.ts rename lib/emulation/{docker.js => docker.ts} (79%) delete mode 100644 lib/emulation/utils.js create mode 100644 lib/emulation/utils.ts delete mode 100644 lib/exception.js create mode 100644 lib/exception.ts rename lib/{id.js => id.ts} (83%) rename lib/{paginate.js => paginate.ts} (68%) delete mode 100644 lib/parser.js create mode 100644 lib/parser.ts rename lib/{questions.js => questions.ts} (78%) delete mode 100644 lib/sdks.js create mode 100644 lib/sdks.ts rename lib/{spinner.js => spinner.ts} (53%) delete mode 100644 lib/type-generation/attribute.js create mode 100644 lib/type-generation/attribute.ts rename lib/type-generation/languages/{csharp.js => csharp.ts} (71%) rename lib/type-generation/languages/{dart.js => dart.ts} (60%) rename lib/type-generation/languages/{java.js => java.ts} (57%) delete mode 100644 lib/type-generation/languages/javascript.js create mode 100644 lib/type-generation/languages/javascript.ts delete mode 100644 lib/type-generation/languages/kotlin.js create mode 100644 lib/type-generation/languages/kotlin.ts delete mode 100644 lib/type-generation/languages/language.js create mode 100644 lib/type-generation/languages/language.ts rename lib/type-generation/languages/{php.js => php.ts} (53%) rename lib/type-generation/languages/{swift.js => swift.ts} (76%) delete mode 100644 lib/type-generation/languages/typescript.js create mode 100644 lib/type-generation/languages/typescript.ts create mode 100644 lib/types.ts rename lib/{utils.js => utils.ts} (62%) delete mode 100644 lib/validations.js create mode 100644 lib/validations.ts create mode 100644 tsconfig.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f1f02bb..fbc157e9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Change Log +## 13.0.0-rc.1 + +* Migrates codebase from JavaScript to TypeScript + ## 12.0.1 Fix type generation for `point`, `lineString` and `polygon` columns diff --git a/README.md b/README.md index 93b631ad..f1cdf543 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ Once the installation is complete, you can verify the install using ```sh $ appwrite -v -12.0.1 +13.0.0-rc.1 ``` ### Install using prebuilt binaries @@ -60,7 +60,7 @@ $ scoop install https://raw.githubusercontent.com/appwrite/sdk-for-cli/master/sc Once the installation completes, you can verify your install using ``` $ appwrite -v -12.0.1 +13.0.0-rc.1 ``` ## Getting Started diff --git a/docs/examples/databases/upsert-document.md b/docs/examples/databases/upsert-document.md index 558ffeb5..8b1e1382 100644 --- a/docs/examples/databases/upsert-document.md +++ b/docs/examples/databases/upsert-document.md @@ -1,5 +1,4 @@ appwrite databases upsert-document \ --database-id \ --collection-id \ - --document-id \ - --data '{ "key": "value" }' + --document-id diff --git a/index.js b/index.js deleted file mode 100644 index 4b2297d5..00000000 --- a/index.js +++ /dev/null @@ -1,147 +0,0 @@ -#! /usr/bin/env node - -/** Required to set max width of the help commands */ -const oldWidth = process.stdout.columns -process.stdout.columns = 100 -/** ---------------------------------------------- */ - -const program = require("commander"); -const chalk = require("chalk"); -const { version } = require("./package.json"); -const { commandDescriptions, cliConfig } = require("./lib/parser"); -const { client } = require("./lib/commands/generic"); -const { getLatestVersion, compareVersions } = require("./lib/utils"); -const inquirer = require("inquirer"); -const { login, logout, whoami, migrate, register } = require("./lib/commands/generic"); -const { init } = require("./lib/commands/init"); -const { types } = require("./lib/commands/types"); -const { pull } = require("./lib/commands/pull"); -const { run } = require("./lib/commands/run"); -const { push, deploy } = require("./lib/commands/push"); -const { update } = require("./lib/commands/update"); -const { account } = require("./lib/commands/account"); -const { console } = require("./lib/commands/console"); -const { databases } = require("./lib/commands/databases"); -const { functions } = require("./lib/commands/functions"); -const { graphql } = require("./lib/commands/graphql"); -const { health } = require("./lib/commands/health"); -const { locale } = require("./lib/commands/locale"); -const { messaging } = require("./lib/commands/messaging"); -const { migrations } = require("./lib/commands/migrations"); -const { project } = require("./lib/commands/project"); -const { projects } = require("./lib/commands/projects"); -const { proxy } = require("./lib/commands/proxy"); -const { sites } = require("./lib/commands/sites"); -const { storage } = require("./lib/commands/storage"); -const { tablesDB } = require("./lib/commands/tables-db"); -const { teams } = require("./lib/commands/teams"); -const { tokens } = require("./lib/commands/tokens"); -const { users } = require("./lib/commands/users"); -const { vcs } = require("./lib/commands/vcs"); - -inquirer.registerPrompt('search-list', require('inquirer-search-list')); - -/** - * Check for updates and show version information - */ -async function checkVersion() { - process.stdout.write(chalk.bold(`appwrite version ${version}`) + '\n'); - - try { - const latestVersion = await getLatestVersion(); - const comparison = compareVersions(version, latestVersion); - - if (comparison > 0) { - // Current version is older than latest - process.stdout.write(chalk.yellow(`\nāš ļø A newer version is available: ${chalk.bold(latestVersion)}`) + '\n'); - process.stdout.write(chalk.cyan(`šŸ’” Run '${chalk.bold('appwrite update')}' to update to the latest version.`) + '\n'); - } else if (comparison === 0) { - process.stdout.write(chalk.green('\nāœ… You are running the latest version!') + '\n'); - } else { - // Current version is newer than latest (pre-release/dev) - process.stdout.write(chalk.blue('\nšŸš€ You are running a pre-release or development version.') + '\n'); - } - } catch (error) { - // Silently fail version check, just show current version - process.stdout.write(chalk.gray('\n(Unable to check for updates)') + '\n'); - } -} - -// Intercept version flag before Commander.js processes it -if (process.argv.includes('-v') || process.argv.includes('--version')) { - (async () => { - await checkVersion(); - process.exit(0); - })(); - return; -} - -program - .description(commandDescriptions['main']) - .configureHelp({ - helpWidth: process.stdout.columns || 80, - sortSubcommands: true, - }) - .helpOption('-h, --help', "Display help for command") - .version(version, "-v, --version", "Output the version number") - .option("-V, --verbose", "Show complete error log") - .option("-j, --json", "Output in JSON format") - .hook('preAction', migrate) - .option("-f,--force", "Flag to confirm all warnings") - .option("-a,--all", "Flag to push all resources") - .option("--id [id...]", "Flag to pass a list of ids for a given action") - .option("--report", "Enable reporting in case of CLI errors") - .on("option:json", () => { - cliConfig.json = true; - }) - .on("option:verbose", () => { - cliConfig.verbose = true; - }) - .on("option:report", function() { - cliConfig.report = true; - cliConfig.reportData = { data: this }; - }) - .on("option:force", () => { - cliConfig.force = true; - }) - .on("option:all", () => { - cliConfig.all = true; - }) - .on("option:id", function() { - cliConfig.ids = this.opts().id; - }) - .showSuggestionAfterError() - .addCommand(whoami) - .addCommand(register) - .addCommand(login) - .addCommand(init) - .addCommand(pull) - .addCommand(push) - .addCommand(types) - .addCommand(deploy) - .addCommand(run) - .addCommand(update) - .addCommand(logout) - .addCommand(account) - .addCommand(console) - .addCommand(databases) - .addCommand(functions) - .addCommand(graphql) - .addCommand(health) - .addCommand(locale) - .addCommand(messaging) - .addCommand(migrations) - .addCommand(project) - .addCommand(projects) - .addCommand(proxy) - .addCommand(sites) - .addCommand(storage) - .addCommand(tablesDB) - .addCommand(teams) - .addCommand(tokens) - .addCommand(users) - .addCommand(vcs) - .addCommand(client) - .parse(process.argv); - -process.stdout.columns = oldWidth; diff --git a/index.ts b/index.ts new file mode 100644 index 00000000..54d01fd9 --- /dev/null +++ b/index.ts @@ -0,0 +1,152 @@ +#! /usr/bin/env node + +/** Required to set max width of the help commands */ +const oldWidth = process.stdout.columns; +process.stdout.columns = 100; +/** ---------------------------------------------- */ + +import program = require('commander'); +import chalk = require('chalk'); +const { version } = require('../package.json'); +import { commandDescriptions, cliConfig } from './lib/parser'; +import { client } from './lib/commands/generic'; +import { getLatestVersion, compareVersions } from './lib/utils'; +import inquirer = require('inquirer'); +import { login, logout, whoami, migrate, register } from './lib/commands/generic'; +import { init } from './lib/commands/init'; +import { types } from './lib/commands/types'; +import { pull } from './lib/commands/pull'; +import { run } from './lib/commands/run'; +import { push, deploy } from './lib/commands/push'; +import { update } from './lib/commands/update'; +import { account } from './lib/commands/account'; +import { console } from './lib/commands/console'; +import { databases } from './lib/commands/databases'; +import { functions } from './lib/commands/functions'; +import { graphql } from './lib/commands/graphql'; +import { health } from './lib/commands/health'; +import { locale } from './lib/commands/locale'; +import { messaging } from './lib/commands/messaging'; +import { migrations } from './lib/commands/migrations'; +import { project } from './lib/commands/project'; +import { projects } from './lib/commands/projects'; +import { proxy } from './lib/commands/proxy'; +import { sites } from './lib/commands/sites'; +import { storage } from './lib/commands/storage'; +import { tablesDB } from './lib/commands/tables-db'; +import { teams } from './lib/commands/teams'; +import { tokens } from './lib/commands/tokens'; +import { users } from './lib/commands/users'; +import { vcs } from './lib/commands/vcs'; + +inquirer.registerPrompt('search-list', require('inquirer-search-list')); + +/** + * Check for updates and show version information + */ +async function checkVersion(): Promise { + process.stdout.write(chalk.bold(`appwrite version ${version}`) + '\n'); + + try { + const latestVersion = await getLatestVersion(); + const comparison = compareVersions(version, latestVersion); + + if (comparison > 0) { + // Current version is older than latest + process.stdout.write( + chalk.yellow(`\nāš ļø A newer version is available: ${chalk.bold(latestVersion)}`) + '\n' + ); + process.stdout.write( + chalk.cyan( + `šŸ’” Run '${chalk.bold('appwrite update')}' to update to the latest version.` + ) + '\n' + ); + } else if (comparison === 0) { + process.stdout.write(chalk.green('\nāœ… You are running the latest version!') + '\n'); + } else { + // Current version is newer than latest (pre-release/dev) + process.stdout.write(chalk.blue('\nšŸš€ You are running a pre-release or development version.') + '\n'); + } + } catch (error) { + // Silently fail version check, just show current version + process.stdout.write(chalk.gray('\n(Unable to check for updates)') + '\n'); + } +} + +// Intercept version flag before Commander.js processes it +if (process.argv.includes('-v') || process.argv.includes('--version')) { + (async () => { + await checkVersion(); + process.exit(0); + })(); +} else { + program + .description(commandDescriptions['main']) + .configureHelp({ + helpWidth: process.stdout.columns || 80, + sortSubcommands: true, + }) + .helpOption('-h, --help', 'Display help for command') + .version(version, '-v, --version', 'Output the version number') + .option('-V, --verbose', 'Show complete error log') + .option('-j, --json', 'Output in JSON format') + .hook('preAction', migrate) + .option('-f,--force', 'Flag to confirm all warnings') + .option('-a,--all', 'Flag to push all resources') + .option('--id [id...]', 'Flag to pass a list of ids for a given action') + .option('--report', 'Enable reporting in case of CLI errors') + .on('option:json', () => { + cliConfig.json = true; + }) + .on('option:verbose', () => { + cliConfig.verbose = true; + }) + .on('option:report', function () { + cliConfig.report = true; + cliConfig.reportData = { data: this }; + }) + .on('option:force', () => { + cliConfig.force = true; + }) + .on('option:all', () => { + cliConfig.all = true; + }) + .on('option:id', function () { + cliConfig.ids = (this as any).opts().id; + }) + .showSuggestionAfterError() + .addCommand(whoami) + .addCommand(register) + .addCommand(login) + .addCommand(init) + .addCommand(pull) + .addCommand(push) + .addCommand(types) + .addCommand(deploy) + .addCommand(run) + .addCommand(update) + .addCommand(logout) + .addCommand(account) + .addCommand(console) + .addCommand(databases) + .addCommand(functions) + .addCommand(graphql) + .addCommand(health) + .addCommand(locale) + .addCommand(messaging) + .addCommand(migrations) + .addCommand(project) + .addCommand(projects) + .addCommand(proxy) + .addCommand(sites) + .addCommand(storage) + .addCommand(tablesDB) + .addCommand(teams) + .addCommand(tokens) + .addCommand(users) + .addCommand(vcs) + .addCommand(client) + .parse(process.argv); + + process.stdout.columns = oldWidth; +} diff --git a/install.ps1 b/install.ps1 index 347b4f30..d21f8f52 100644 --- a/install.ps1 +++ b/install.ps1 @@ -13,8 +13,8 @@ # You can use "View source" of this page to see the full script. # REPO -$GITHUB_x64_URL = "https://github.com/appwrite/sdk-for-cli/releases/download/12.0.1/appwrite-cli-win-x64.exe" -$GITHUB_arm64_URL = "https://github.com/appwrite/sdk-for-cli/releases/download/12.0.1/appwrite-cli-win-arm64.exe" +$GITHUB_x64_URL = "https://github.com/appwrite/sdk-for-cli/releases/download/13.0.0-rc.1/appwrite-cli-win-x64.exe" +$GITHUB_arm64_URL = "https://github.com/appwrite/sdk-for-cli/releases/download/13.0.0-rc.1/appwrite-cli-win-arm64.exe" $APPWRITE_BINARY_NAME = "appwrite.exe" @@ -41,7 +41,6 @@ function Greeting { Write-Host "Welcome to the Appwrite CLI install shield." } - function CheckSystemInfo { Write-Host "[1/4] Getting System Info ..." if ((Get-ExecutionPolicy) -gt 'RemoteSigned' -or (Get-ExecutionPolicy) -eq 'ByPass') { @@ -66,7 +65,6 @@ function DownloadBinary { Move-Item $APPWRITE_DOWNLOAD_DIR $APPWRITE_INSTALL_PATH } - function Install { Write-Host "[3/4] Starting installation ..." @@ -89,7 +87,6 @@ function InstallCompleted { Write-Host "As first step, you can login to your Appwrite account using 'appwrite login'" } - Greeting CheckSystemInfo DownloadBinary diff --git a/install.sh b/install.sh index 8620db85..8732228a 100644 --- a/install.sh +++ b/install.sh @@ -39,7 +39,6 @@ RED='\033[0;31m' GREEN='\033[0;32m' NC='\033[0m' # No Color - greeting() { echo -e "${RED}" cat << "EOF" @@ -97,7 +96,7 @@ printSuccess() { downloadBinary() { echo "[2/4] Downloading executable for $OS ($ARCH) ..." - GITHUB_LATEST_VERSION="12.0.1" + GITHUB_LATEST_VERSION="13.0.0-rc.1" GITHUB_FILE="appwrite-cli-${OS}-${ARCH}" GITHUB_URL="https://github.com/$GITHUB_REPOSITORY_NAME/releases/download/$GITHUB_LATEST_VERSION/$GITHUB_FILE" diff --git a/lib/client.js b/lib/client.js deleted file mode 100644 index 02937a6f..00000000 --- a/lib/client.js +++ /dev/null @@ -1,254 +0,0 @@ -const os = require('os'); -const https = require("https"); -const { fetch, FormData, Agent } = require("undici"); -const JSONbig = require("json-bigint")({ storeAsString: false }); -const AppwriteException = require("./exception.js"); -const { globalConfig } = require("./config.js"); -const chalk = require("chalk"); - -class Client { - CHUNK_SIZE = 5*1024*1024; // 5MB - - constructor() { - this.endpoint = 'https://cloud.appwrite.io/v1'; - this.headers = { - 'content-type': '', - 'x-sdk-name': 'Command Line', - 'x-sdk-platform': 'console', - 'x-sdk-language': 'cli', - 'x-sdk-version': '12.0.1', - 'user-agent' : `AppwriteCLI/12.0.1 (${os.type()} ${os.version()}; ${os.arch()})`, - 'X-Appwrite-Response-Format' : '1.8.0', - }; - } - - /** - * Set Cookie - * - * Your cookie - * - * @param {string} cookie - * - * @return self - */ - setCookie(cookie) { - this.addHeader("cookie", cookie); - - return this; - } - - /** - * Set Project - * - * Your project ID - * - * @param {string} project - * - * @return self - */ - setProject(project) { - this.addHeader('X-Appwrite-Project', project); - - return this; - } - - /** - * Set Key - * - * Your secret API key - * - * @param {string} key - * - * @return self - */ - setKey(key) { - this.addHeader('X-Appwrite-Key', key); - - return this; - } - - /** - * Set JWT - * - * Your secret JSON Web Token - * - * @param {string} jwt - * - * @return self - */ - setJWT(jwt) { - this.addHeader('X-Appwrite-JWT', jwt); - - return this; - } - - /** - * Set Locale - * - * @param {string} locale - * - * @return self - */ - setLocale(locale) { - this.addHeader('X-Appwrite-Locale', locale); - - return this; - } - - /** - * Set Mode - * - * @param {string} mode - * - * @return self - */ - setMode(mode) { - this.addHeader('X-Appwrite-Mode', mode); - - return this; - } - - /** - * Set self signed. - * - * @param {bool} status - * - * @return this - */ - setSelfSigned(status) { - this.selfSigned = status; - - return this; - } - - /** - * Set endpoint. - * - * @param {string} endpoint - * - * @return this - */ - setEndpoint(endpoint) { - if (!endpoint.startsWith('http://') && !endpoint.startsWith('https://')) { - throw new AppwriteException('Invalid endpoint URL: ' + endpoint); - } - - this.endpoint = endpoint; - return this; - } - - /** - * @param {string} key - * @param {string} value - */ - addHeader(key, value) { - this.headers[key.toLowerCase()] = value; - - return this; - } - - async call(method, path = "", headers = {}, params = {}, responseType = "json") { - headers = {...this.headers, ...headers}; - const url = new URL(this.endpoint + path); - - let body = undefined; - - if (method.toUpperCase() === "GET") { - url.search = new URLSearchParams(Client.flatten(params)).toString(); - } else if (headers["content-type"]?.toLowerCase().startsWith("multipart/form-data")) { - delete headers["content-type"]; - const formData = new FormData(); - - const flatParams = Client.flatten(params); - - for (const [key, value] of Object.entries(flatParams)) { - if (value && value.type && value.type === "file") { - formData.append(key, value.file, value.filename); - } else { - formData.append(key, value); - } - } - - body = formData; - } else { - body = JSONbig.stringify(params); - } - - let response = undefined; - try { - response = await fetch(url.toString(), { - method: method.toUpperCase(), - headers, - body, - dispatcher: new Agent({ - connect: { - rejectUnauthorized: !this.selfSigned, - }, - }), - }); - } catch (error) { - throw new AppwriteException(error.message); - } - - if (response.status >= 400) { - const text = await response.text(); - let json = undefined; - try { - json = JSON.parse(text); - } catch (error) { - throw new AppwriteException(text, response.status, "", text); - } - - if (path !== '/account' && json.code === 401 && json.type === 'user_more_factors_required') { - console.log(`${chalk.cyan.bold("ℹ Info")} ${chalk.cyan("Unusable account found, removing...")}`); - - const current = globalConfig.getCurrentSession(); - globalConfig.setCurrentSession(''); - globalConfig.removeSession(current); - } - throw new AppwriteException(json.message, json.code, json.type, text); - } - - if (responseType === "arraybuffer") { - const data = await response.arrayBuffer(); - return data; - } - - let cookies = response.headers.getSetCookie(); - if (cookies && cookies.length > 0) { - for (const cookie of cookies) { - if (cookie.startsWith('a_session_console=')) { - globalConfig.setCookie(cookie); - } - } - } - - const text = await response.text(); - let json = undefined; - try { - json = JSONbig.parse(text); - } catch (error) { - return text; - } - return json; - } - - static flatten(data, prefix = '') { - let output = {}; - - for (const key in data) { - let value = data[key]; - let finalKey = prefix ? prefix + '[' + key +']' : key; - - if (Array.isArray(value)) { - output = Object.assign(output, Client.flatten(value, finalKey)); // @todo: handle name collision here if needed - } else { - output[finalKey] = value; - } - } - - return output; - } -} - -module.exports = Client; diff --git a/lib/client.ts b/lib/client.ts new file mode 100644 index 00000000..9d6833d9 --- /dev/null +++ b/lib/client.ts @@ -0,0 +1,259 @@ +import os = require('os'); +import { fetch, FormData, Agent } from 'undici'; +import JSONbig = require('json-bigint'); +import AppwriteException = require('./exception'); +import { globalConfig } from './config'; +import chalk = require('chalk'); +import type { Headers, RequestParams, ResponseType, FileUpload } from './types'; + +const JSONBigInt = JSONbig({ storeAsString: false }); + +class Client { + private readonly CHUNK_SIZE = 5 * 1024 * 1024; // 5MB + private endpoint: string; + private headers: Headers; + private selfSigned: boolean; + + constructor() { + this.endpoint = 'https://cloud.appwrite.io/v1'; + this.selfSigned = false; + this.headers = { + 'content-type': '', + 'x-sdk-name': 'Command Line', + 'x-sdk-platform': 'console', + 'x-sdk-language': 'cli', + 'x-sdk-version': '13.0.0-rc.1', + 'user-agent': `AppwriteCLI/13.0.0-rc.1 (${os.type()} ${os.version()}; ${os.arch()})`, + 'X-Appwrite-Response-Format': '1.8.0', + }; + } + + /** + * Set Cookie + * + * Your cookie + * + * @param {string} cookie + * + * @return self + */ + setCookie(cookie: string): this { + this.addHeader('cookie', cookie); + return this; + } + + /** + * Set Project + * + * Your project ID + * + * @param {string} project + * + * @return self + */ + setProject(project: string): this { + this.addHeader('X-Appwrite-Project', project); + return this; + } + + /** + * Set Key + * + * Your secret API key + * + * @param {string} key + * + * @return self + */ + setKey(key: string): this { + this.addHeader('X-Appwrite-Key', key); + return this; + } + + /** + * Set JWT + * + * Your secret JSON Web Token + * + * @param {string} jwt + * + * @return self + */ + setJWT(jwt: string): this { + this.addHeader('X-Appwrite-JWT', jwt); + return this; + } + + /** + * Set Locale + * + * @param {string} locale + * + * @return self + */ + setLocale(locale: string): this { + this.addHeader('X-Appwrite-Locale', locale); + return this; + } + + /** + * Set Mode + * + * @param {string} mode + * + * @return self + */ + setMode(mode: string): this { + this.addHeader('X-Appwrite-Mode', mode); + return this; + } + + /** + * Set self signed. + * + * @param {bool} status + * + * @return this + */ + setSelfSigned(status: boolean): this { + this.selfSigned = status; + return this; + } + + /** + * Set endpoint. + * + * @param {string} endpoint + * + * @return this + */ + setEndpoint(endpoint: string): this { + if (!endpoint.startsWith('http://') && !endpoint.startsWith('https://')) { + throw new AppwriteException('Invalid endpoint URL: ' + endpoint); + } + + this.endpoint = endpoint; + return this; + } + + /** + * @param {string} key + * @param {string} value + */ + addHeader(key: string, value: string): this { + this.headers[key.toLowerCase()] = value; + return this; + } + + async call( + method: string, + path: string = '', + headers: Headers = {}, + params: RequestParams = {}, + responseType: ResponseType = 'json' + ): Promise { + const mergedHeaders: Headers = { ...this.headers, ...headers }; + const url = new URL(this.endpoint + path); + + let body: FormData | string | undefined = undefined; + + if (method.toUpperCase() === 'GET') { + url.search = new URLSearchParams(Client.flatten(params) as Record).toString(); + } else if (mergedHeaders['content-type']?.toLowerCase().startsWith('multipart/form-data')) { + delete mergedHeaders['content-type']; + const formData = new FormData(); + + const flatParams = Client.flatten(params); + + for (const [key, value] of Object.entries(flatParams)) { + if (value && typeof value === 'object' && 'type' in value && value.type === 'file') { + const fileUpload = value as FileUpload; + formData.append(key, fileUpload.file as any, fileUpload.filename); + } else { + formData.append(key, value as string); + } + } + + body = formData; + } else { + body = JSONBigInt.stringify(params); + } + + let response: Awaited> | undefined = undefined; + try { + response = await fetch(url.toString(), { + method: method.toUpperCase(), + headers: mergedHeaders, + body, + dispatcher: new Agent({ + connect: { + rejectUnauthorized: !this.selfSigned, + }, + }), + }); + } catch (error) { + throw new AppwriteException((error as Error).message); + } + + if (response.status >= 400) { + const text = await response.text(); + let json: { message?: string; code?: number; type?: string } | undefined = undefined; + try { + json = JSON.parse(text); + } catch (error) { + throw new AppwriteException(text, response.status, '', text); + } + + if (path !== '/account' && json.code === 401 && json.type === 'user_more_factors_required') { + console.log(`${chalk.cyan.bold('ℹ Info')} ${chalk.cyan('Unusable account found, removing...')}`); + + const current = globalConfig.getCurrentSession(); + globalConfig.setCurrentSession(''); + globalConfig.removeSession(current); + } + throw new AppwriteException(json.message || text, json.code, json.type, text); + } + + if (responseType === 'arraybuffer') { + const data = await response.arrayBuffer(); + return data as T; + } + + const cookies = response.headers.getSetCookie(); + if (cookies && cookies.length > 0) { + for (const cookie of cookies) { + if (cookie.startsWith('a_session_console=')) { + globalConfig.setCookie(cookie); + } + } + } + + const text = await response.text(); + let json: T | undefined = undefined; + try { + json = JSONBigInt.parse(text); + } catch (error) { + return text as T; + } + return json as T; + } + + static flatten(data: RequestParams, prefix: string = ''): Record { + let output: Record = {}; + + for (const key in data) { + const value = data[key]; + const finalKey = prefix ? prefix + '[' + key + ']' : key; + + if (Array.isArray(value)) { + output = { ...output, ...Client.flatten(value as unknown as RequestParams, finalKey) }; + } else { + output[finalKey] = value; + } + } + + return output; + } +} + +export = Client; diff --git a/lib/commands/account.js b/lib/commands/account.ts similarity index 63% rename from lib/commands/account.js rename to lib/commands/account.ts index edc7b7a7..98a88fd3 100644 --- a/lib/commands/account.js +++ b/lib/commands/account.ts @@ -1,31 +1,27 @@ -const fs = require('fs'); -const pathLib = require('path'); -const tar = require("tar"); -const ignore = require("ignore"); -const { promisify } = require('util'); -const libClient = require('../client.js'); -const { getAllFiles, showConsoleLink } = require('../utils.js'); -const { Command } = require('commander'); -const { sdkForProject, sdkForConsole } = require('../sdks') -const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } = require('../parser') -const { localConfig, globalConfig } = require("../config"); -const { File } = require('undici'); -const { ReadableStream } = require('stream/web'); - -/** - * @param {fs.ReadStream} readStream - * @returns {ReadableStream} - */ -function convertReadStreamToReadableStream(readStream) { +import fs = require('fs'); +import pathLib = require('path'); +import tar = require('tar'); +import ignore = require('ignore'); +import { promisify } from 'util'; +import Client from '../client'; +import { getAllFiles, showConsoleLink } from '../utils'; +import { Command } from 'commander'; +import { sdkForProject, sdkForConsole } from '../sdks'; +import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } from '../parser'; +import { localConfig, globalConfig } from '../config'; +import { File } from 'undici'; +import { ReadableStream } from 'stream/web'; + +function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ start(controller) { - readStream.on("data", (chunk) => { + readStream.on("data", (chunk: Buffer) => { controller.enqueue(chunk); }); readStream.on("end", () => { controller.close(); }); - readStream.on("error", (err) => { + readStream.on("error", (err: Error) => { controller.error(err); }); }, @@ -35,21 +31,18 @@ function convertReadStreamToReadableStream(readStream) { }); } -const account = new Command("account").description(commandDescriptions['account'] ?? '').configureHelp({ +export const account = new Command("account").description(commandDescriptions['account'] ?? '').configureHelp({ helpWidth: process.stdout.columns || 80 }) -/** - * @typedef {Object} AccountGetRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {AccountGetRequestParams} params - */ -const accountGet = async ({parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface AccountGetRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const accountGet = async ({parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: AccountGetRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account'; @@ -61,7 +54,7 @@ const accountGet = async ({parseOutput = true, overrideForCli = false, sdk = und }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('account', 'get'); } else { parse(response) @@ -71,21 +64,17 @@ const accountGet = async ({parseOutput = true, overrideForCli = false, sdk = und return response; } -/** - * @typedef {Object} AccountCreateRequestParams - * @property {string} userId User ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} email User email. - * @property {string} password New user password. Must be between 8 and 256 chars. - * @property {string} name User name. Max length: 128 chars. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {AccountCreateRequestParams} params - */ -const accountCreate = async ({userId,email,password,name,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface AccountCreateRequestParams { + userId: string; + email: string; + password: string; + name?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const accountCreate = async ({userId,email,password,name,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountCreateRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account'; @@ -116,17 +105,13 @@ const accountCreate = async ({userId,email,password,name,parseOutput = true, ove return response; } -/** - * @typedef {Object} AccountDeleteRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountDeleteRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountDeleteRequestParams} params - */ -const accountDelete = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountDelete = async ({parseOutput = true, overrideForCli = false, sdk = undefined}: AccountDeleteRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account'; @@ -145,19 +130,15 @@ const accountDelete = async ({parseOutput = true, overrideForCli = false, sdk = return response; } -/** - * @typedef {Object} AccountUpdateEmailRequestParams - * @property {string} email User email. - * @property {string} password User password. Must be at least 8 chars. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountUpdateEmailRequestParams { + email: string; + password: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountUpdateEmailRequestParams} params - */ -const accountUpdateEmail = async ({email,password,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountUpdateEmail = async ({email,password,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountUpdateEmailRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/email'; @@ -182,19 +163,15 @@ const accountUpdateEmail = async ({email,password,parseOutput = true, overrideFo return response; } -/** - * @typedef {Object} AccountListIdentitiesRequestParams - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: userId, provider, providerUid, providerEmail, providerAccessTokenExpiry - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountListIdentitiesRequestParams { + queries?: string[]; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountListIdentitiesRequestParams} params - */ -const accountListIdentities = async ({queries,total,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountListIdentities = async ({queries,total,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountListIdentitiesRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/identities'; @@ -218,18 +195,14 @@ const accountListIdentities = async ({queries,total,parseOutput = true, override return response; } -/** - * @typedef {Object} AccountDeleteIdentityRequestParams - * @property {string} identityId Identity ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountDeleteIdentityRequestParams { + identityId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountDeleteIdentityRequestParams} params - */ -const accountDeleteIdentity = async ({identityId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountDeleteIdentity = async ({identityId,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountDeleteIdentityRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/identities/{identityId}'.replace('{identityId}', identityId); @@ -248,17 +221,13 @@ const accountDeleteIdentity = async ({identityId,parseOutput = true, overrideFor return response; } -/** - * @typedef {Object} AccountCreateJWTRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountCreateJWTRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountCreateJWTRequestParams} params - */ -const accountCreateJWT = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountCreateJWT = async ({parseOutput = true, overrideForCli = false, sdk = undefined}: AccountCreateJWTRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/jwts'; @@ -277,19 +246,15 @@ const accountCreateJWT = async ({parseOutput = true, overrideForCli = false, sdk return response; } -/** - * @typedef {Object} AccountListLogsRequestParams - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Only supported methods are limit and offset - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountListLogsRequestParams { + queries?: string[]; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountListLogsRequestParams} params - */ -const accountListLogs = async ({queries,total,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountListLogs = async ({queries,total,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountListLogsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/logs'; @@ -313,18 +278,14 @@ const accountListLogs = async ({queries,total,parseOutput = true, overrideForCli return response; } -/** - * @typedef {Object} AccountUpdateMFARequestParams - * @property {boolean} mfa Enable or disable MFA. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountUpdateMFARequestParams { + mfa: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountUpdateMFARequestParams} params - */ -const accountUpdateMFA = async ({mfa,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountUpdateMFA = async ({mfa,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountUpdateMFARequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/mfa'; @@ -346,18 +307,14 @@ const accountUpdateMFA = async ({mfa,parseOutput = true, overrideForCli = false, return response; } -/** - * @typedef {Object} AccountCreateMFAAuthenticatorRequestParams - * @property {AuthenticatorType} type Type of authenticator. Must be 'totp' - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountCreateMFAAuthenticatorRequestParams { + type: AuthenticatorType; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountCreateMFAAuthenticatorRequestParams} params - */ -const accountCreateMFAAuthenticator = async ({type,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountCreateMFAAuthenticator = async ({type,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountCreateMFAAuthenticatorRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/mfa/authenticators/{type}'.replace('{type}', type); @@ -376,19 +333,15 @@ const accountCreateMFAAuthenticator = async ({type,parseOutput = true, overrideF return response; } -/** - * @typedef {Object} AccountUpdateMFAAuthenticatorRequestParams - * @property {AuthenticatorType} type Type of authenticator. - * @property {string} otp Valid verification token. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountUpdateMFAAuthenticatorRequestParams { + type: AuthenticatorType; + otp: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountUpdateMFAAuthenticatorRequestParams} params - */ -const accountUpdateMFAAuthenticator = async ({type,otp,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountUpdateMFAAuthenticator = async ({type,otp,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountUpdateMFAAuthenticatorRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/mfa/authenticators/{type}'.replace('{type}', type); @@ -410,18 +363,14 @@ const accountUpdateMFAAuthenticator = async ({type,otp,parseOutput = true, overr return response; } -/** - * @typedef {Object} AccountDeleteMFAAuthenticatorRequestParams - * @property {AuthenticatorType} type Type of authenticator. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountDeleteMFAAuthenticatorRequestParams { + type: AuthenticatorType; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountDeleteMFAAuthenticatorRequestParams} params - */ -const accountDeleteMFAAuthenticator = async ({type,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountDeleteMFAAuthenticator = async ({type,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountDeleteMFAAuthenticatorRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/mfa/authenticators/{type}'.replace('{type}', type); @@ -440,18 +389,14 @@ const accountDeleteMFAAuthenticator = async ({type,parseOutput = true, overrideF return response; } -/** - * @typedef {Object} AccountCreateMFAChallengeRequestParams - * @property {AuthenticationFactor} factor Factor used for verification. Must be one of following: 'email', 'phone', 'totp', 'recoveryCode'. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountCreateMFAChallengeRequestParams { + factor: AuthenticationFactor; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountCreateMFAChallengeRequestParams} params - */ -const accountCreateMFAChallenge = async ({factor,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountCreateMFAChallenge = async ({factor,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountCreateMFAChallengeRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/mfa/challenges'; @@ -473,19 +418,15 @@ const accountCreateMFAChallenge = async ({factor,parseOutput = true, overrideFor return response; } -/** - * @typedef {Object} AccountUpdateMFAChallengeRequestParams - * @property {string} challengeId ID of the challenge. - * @property {string} otp Valid verification token. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountUpdateMFAChallengeRequestParams { + challengeId: string; + otp: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountUpdateMFAChallengeRequestParams} params - */ -const accountUpdateMFAChallenge = async ({challengeId,otp,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountUpdateMFAChallenge = async ({challengeId,otp,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountUpdateMFAChallengeRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/mfa/challenges'; @@ -510,17 +451,13 @@ const accountUpdateMFAChallenge = async ({challengeId,otp,parseOutput = true, ov return response; } -/** - * @typedef {Object} AccountListMFAFactorsRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountListMFAFactorsRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountListMFAFactorsRequestParams} params - */ -const accountListMFAFactors = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountListMFAFactors = async ({parseOutput = true, overrideForCli = false, sdk = undefined}: AccountListMFAFactorsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/mfa/factors'; @@ -538,17 +475,13 @@ const accountListMFAFactors = async ({parseOutput = true, overrideForCli = false return response; } -/** - * @typedef {Object} AccountGetMFARecoveryCodesRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountGetMFARecoveryCodesRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountGetMFARecoveryCodesRequestParams} params - */ -const accountGetMFARecoveryCodes = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountGetMFARecoveryCodes = async ({parseOutput = true, overrideForCli = false, sdk = undefined}: AccountGetMFARecoveryCodesRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/mfa/recovery-codes'; @@ -566,17 +499,13 @@ const accountGetMFARecoveryCodes = async ({parseOutput = true, overrideForCli = return response; } -/** - * @typedef {Object} AccountCreateMFARecoveryCodesRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountCreateMFARecoveryCodesRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountCreateMFARecoveryCodesRequestParams} params - */ -const accountCreateMFARecoveryCodes = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountCreateMFARecoveryCodes = async ({parseOutput = true, overrideForCli = false, sdk = undefined}: AccountCreateMFARecoveryCodesRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/mfa/recovery-codes'; @@ -595,17 +524,13 @@ const accountCreateMFARecoveryCodes = async ({parseOutput = true, overrideForCli return response; } -/** - * @typedef {Object} AccountUpdateMFARecoveryCodesRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountUpdateMFARecoveryCodesRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountUpdateMFARecoveryCodesRequestParams} params - */ -const accountUpdateMFARecoveryCodes = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountUpdateMFARecoveryCodes = async ({parseOutput = true, overrideForCli = false, sdk = undefined}: AccountUpdateMFARecoveryCodesRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/mfa/recovery-codes'; @@ -624,18 +549,14 @@ const accountUpdateMFARecoveryCodes = async ({parseOutput = true, overrideForCli return response; } -/** - * @typedef {Object} AccountUpdateNameRequestParams - * @property {string} name User name. Max length: 128 chars. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountUpdateNameRequestParams { + name: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountUpdateNameRequestParams} params - */ -const accountUpdateName = async ({name,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountUpdateName = async ({name,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountUpdateNameRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/name'; @@ -657,19 +578,15 @@ const accountUpdateName = async ({name,parseOutput = true, overrideForCli = fals return response; } -/** - * @typedef {Object} AccountUpdatePasswordRequestParams - * @property {string} password New user password. Must be at least 8 chars. - * @property {string} oldPassword Current user password. Must be at least 8 chars. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountUpdatePasswordRequestParams { + password: string; + oldPassword?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountUpdatePasswordRequestParams} params - */ -const accountUpdatePassword = async ({password,oldPassword,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountUpdatePassword = async ({password,oldPassword,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountUpdatePasswordRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/password'; @@ -694,19 +611,15 @@ const accountUpdatePassword = async ({password,oldPassword,parseOutput = true, o return response; } -/** - * @typedef {Object} AccountUpdatePhoneRequestParams - * @property {string} phone Phone number. Format this number with a leading '+' and a country code, e.g., +16175551212. - * @property {string} password User password. Must be at least 8 chars. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountUpdatePhoneRequestParams { + phone: string; + password: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountUpdatePhoneRequestParams} params - */ -const accountUpdatePhone = async ({phone,password,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountUpdatePhone = async ({phone,password,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountUpdatePhoneRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/phone'; @@ -731,17 +644,13 @@ const accountUpdatePhone = async ({phone,password,parseOutput = true, overrideFo return response; } -/** - * @typedef {Object} AccountGetPrefsRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountGetPrefsRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountGetPrefsRequestParams} params - */ -const accountGetPrefs = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountGetPrefs = async ({parseOutput = true, overrideForCli = false, sdk = undefined}: AccountGetPrefsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/prefs'; @@ -759,18 +668,14 @@ const accountGetPrefs = async ({parseOutput = true, overrideForCli = false, sdk return response; } -/** - * @typedef {Object} AccountUpdatePrefsRequestParams - * @property {object} prefs Prefs key-value JSON object. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountUpdatePrefsRequestParams { + prefs: object; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountUpdatePrefsRequestParams} params - */ -const accountUpdatePrefs = async ({prefs,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountUpdatePrefs = async ({prefs,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountUpdatePrefsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/prefs'; @@ -792,19 +697,15 @@ const accountUpdatePrefs = async ({prefs,parseOutput = true, overrideForCli = fa return response; } -/** - * @typedef {Object} AccountCreateRecoveryRequestParams - * @property {string} email User email. - * @property {string} url URL to redirect the user back to your app from the recovery email. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountCreateRecoveryRequestParams { + email: string; + url: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountCreateRecoveryRequestParams} params - */ -const accountCreateRecovery = async ({email,url,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountCreateRecovery = async ({email,url,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountCreateRecoveryRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/recovery'; @@ -829,20 +730,16 @@ const accountCreateRecovery = async ({email,url,parseOutput = true, overrideForC return response; } -/** - * @typedef {Object} AccountUpdateRecoveryRequestParams - * @property {string} userId User ID. - * @property {string} secret Valid reset token. - * @property {string} password New user password. Must be between 8 and 256 chars. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {AccountUpdateRecoveryRequestParams} params - */ -const accountUpdateRecovery = async ({userId,secret,password,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface AccountUpdateRecoveryRequestParams { + userId: string; + secret: string; + password: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const accountUpdateRecovery = async ({userId,secret,password,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountUpdateRecoveryRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/recovery'; @@ -870,17 +767,14 @@ const accountUpdateRecovery = async ({userId,secret,password,parseOutput = true, return response; } -/** - * @typedef {Object} AccountListSessionsRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountListSessionsRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {AccountListSessionsRequestParams} params - */ -const accountListSessions = async ({parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const accountListSessions = async ({parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: AccountListSessionsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/sessions'; @@ -892,7 +786,7 @@ const accountListSessions = async ({parseOutput = true, overrideForCli = false, }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('account', 'listSessions'); } else { parse(response) @@ -902,17 +796,13 @@ const accountListSessions = async ({parseOutput = true, overrideForCli = false, return response; } -/** - * @typedef {Object} AccountDeleteSessionsRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountDeleteSessionsRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountDeleteSessionsRequestParams} params - */ -const accountDeleteSessions = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountDeleteSessions = async ({parseOutput = true, overrideForCli = false, sdk = undefined}: AccountDeleteSessionsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/sessions'; @@ -931,17 +821,13 @@ const accountDeleteSessions = async ({parseOutput = true, overrideForCli = false return response; } -/** - * @typedef {Object} AccountCreateAnonymousSessionRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountCreateAnonymousSessionRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountCreateAnonymousSessionRequestParams} params - */ -const accountCreateAnonymousSession = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountCreateAnonymousSession = async ({parseOutput = true, overrideForCli = false, sdk = undefined}: AccountCreateAnonymousSessionRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/sessions/anonymous'; @@ -960,19 +846,15 @@ const accountCreateAnonymousSession = async ({parseOutput = true, overrideForCli return response; } -/** - * @typedef {Object} AccountCreateEmailPasswordSessionRequestParams - * @property {string} email User email. - * @property {string} password User password. Must be at least 8 chars. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountCreateEmailPasswordSessionRequestParams { + email: string; + password: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountCreateEmailPasswordSessionRequestParams} params - */ -const accountCreateEmailPasswordSession = async ({email,password,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountCreateEmailPasswordSession = async ({email,password,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountCreateEmailPasswordSessionRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/sessions/email'; @@ -997,19 +879,15 @@ const accountCreateEmailPasswordSession = async ({email,password,parseOutput = t return response; } -/** - * @typedef {Object} AccountUpdateMagicURLSessionRequestParams - * @property {string} userId User ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} secret Valid verification token. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountUpdateMagicURLSessionRequestParams { + userId: string; + secret: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountUpdateMagicURLSessionRequestParams} params - */ -const accountUpdateMagicURLSession = async ({userId,secret,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountUpdateMagicURLSession = async ({userId,secret,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountUpdateMagicURLSessionRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/sessions/magic-url'; @@ -1034,21 +912,17 @@ const accountUpdateMagicURLSession = async ({userId,secret,parseOutput = true, o return response; } -/** - * @typedef {Object} AccountCreateOAuth2SessionRequestParams - * @property {OAuthProvider} provider OAuth2 Provider. Currently, supported providers are: amazon, apple, auth0, authentik, autodesk, bitbucket, bitly, box, dailymotion, discord, disqus, dropbox, etsy, facebook, figma, github, gitlab, google, linkedin, microsoft, notion, oidc, okta, paypal, paypalSandbox, podio, salesforce, slack, spotify, stripe, tradeshift, tradeshiftBox, twitch, wordpress, yahoo, yammer, yandex, zoho, zoom. - * @property {string} success URL to redirect back to your app after a successful login attempt. Only URLs from hostnames in your project's platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. - * @property {string} failure URL to redirect back to your app after a failed login attempt. Only URLs from hostnames in your project's platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. - * @property {string[]} scopes A list of custom OAuth2 scopes. Check each provider internal docs for a list of supported scopes. Maximum of 100 scopes are allowed, each 4096 characters long. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {AccountCreateOAuth2SessionRequestParams} params - */ -const accountCreateOAuth2Session = async ({provider,success,failure,scopes,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface AccountCreateOAuth2SessionRequestParams { + provider: OAuthProvider; + success?: string; + failure?: string; + scopes?: string[]; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const accountCreateOAuth2Session = async ({provider,success,failure,scopes,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountCreateOAuth2SessionRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/sessions/oauth2/{provider}'.replace('{provider}', provider); @@ -1075,19 +949,15 @@ const accountCreateOAuth2Session = async ({provider,success,failure,scopes,parse return response; } -/** - * @typedef {Object} AccountUpdatePhoneSessionRequestParams - * @property {string} userId User ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} secret Valid verification token. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountUpdatePhoneSessionRequestParams { + userId: string; + secret: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountUpdatePhoneSessionRequestParams} params - */ -const accountUpdatePhoneSession = async ({userId,secret,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountUpdatePhoneSession = async ({userId,secret,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountUpdatePhoneSessionRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/sessions/phone'; @@ -1112,19 +982,15 @@ const accountUpdatePhoneSession = async ({userId,secret,parseOutput = true, over return response; } -/** - * @typedef {Object} AccountCreateSessionRequestParams - * @property {string} userId User ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} secret Secret of a token generated by login methods. For example, the 'createMagicURLToken' or 'createPhoneToken' methods. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountCreateSessionRequestParams { + userId: string; + secret: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountCreateSessionRequestParams} params - */ -const accountCreateSession = async ({userId,secret,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountCreateSession = async ({userId,secret,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountCreateSessionRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/sessions/token'; @@ -1149,18 +1015,14 @@ const accountCreateSession = async ({userId,secret,parseOutput = true, overrideF return response; } -/** - * @typedef {Object} AccountGetSessionRequestParams - * @property {string} sessionId Session ID. Use the string 'current' to get the current device session. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountGetSessionRequestParams { + sessionId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountGetSessionRequestParams} params - */ -const accountGetSession = async ({sessionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountGetSession = async ({sessionId,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountGetSessionRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/sessions/{sessionId}'.replace('{sessionId}', sessionId); @@ -1178,18 +1040,14 @@ const accountGetSession = async ({sessionId,parseOutput = true, overrideForCli = return response; } -/** - * @typedef {Object} AccountUpdateSessionRequestParams - * @property {string} sessionId Session ID. Use the string 'current' to update the current device session. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountUpdateSessionRequestParams { + sessionId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountUpdateSessionRequestParams} params - */ -const accountUpdateSession = async ({sessionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountUpdateSession = async ({sessionId,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountUpdateSessionRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/sessions/{sessionId}'.replace('{sessionId}', sessionId); @@ -1208,18 +1066,14 @@ const accountUpdateSession = async ({sessionId,parseOutput = true, overrideForCl return response; } -/** - * @typedef {Object} AccountDeleteSessionRequestParams - * @property {string} sessionId Session ID. Use the string 'current' to delete the current device session. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountDeleteSessionRequestParams { + sessionId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountDeleteSessionRequestParams} params - */ -const accountDeleteSession = async ({sessionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountDeleteSession = async ({sessionId,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountDeleteSessionRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/sessions/{sessionId}'.replace('{sessionId}', sessionId); @@ -1238,17 +1092,13 @@ const accountDeleteSession = async ({sessionId,parseOutput = true, overrideForCl return response; } -/** - * @typedef {Object} AccountUpdateStatusRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountUpdateStatusRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountUpdateStatusRequestParams} params - */ -const accountUpdateStatus = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountUpdateStatus = async ({parseOutput = true, overrideForCli = false, sdk = undefined}: AccountUpdateStatusRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/status'; @@ -1267,20 +1117,16 @@ const accountUpdateStatus = async ({parseOutput = true, overrideForCli = false, return response; } -/** - * @typedef {Object} AccountCreatePushTargetRequestParams - * @property {string} targetId Target ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} identifier The target identifier (token, email, phone etc.) - * @property {string} providerId Provider ID. Message will be sent to this target from the specified provider ID. If no provider ID is set the first setup provider will be used. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {AccountCreatePushTargetRequestParams} params - */ -const accountCreatePushTarget = async ({targetId,identifier,providerId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface AccountCreatePushTargetRequestParams { + targetId: string; + identifier: string; + providerId?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const accountCreatePushTarget = async ({targetId,identifier,providerId,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountCreatePushTargetRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/targets/push'; @@ -1308,19 +1154,15 @@ const accountCreatePushTarget = async ({targetId,identifier,providerId,parseOutp return response; } -/** - * @typedef {Object} AccountUpdatePushTargetRequestParams - * @property {string} targetId Target ID. - * @property {string} identifier The target identifier (token, email, phone etc.) - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountUpdatePushTargetRequestParams { + targetId: string; + identifier: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountUpdatePushTargetRequestParams} params - */ -const accountUpdatePushTarget = async ({targetId,identifier,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountUpdatePushTarget = async ({targetId,identifier,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountUpdatePushTargetRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/targets/{targetId}/push'.replace('{targetId}', targetId); @@ -1342,18 +1184,14 @@ const accountUpdatePushTarget = async ({targetId,identifier,parseOutput = true, return response; } -/** - * @typedef {Object} AccountDeletePushTargetRequestParams - * @property {string} targetId Target ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountDeletePushTargetRequestParams { + targetId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountDeletePushTargetRequestParams} params - */ -const accountDeletePushTarget = async ({targetId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountDeletePushTarget = async ({targetId,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountDeletePushTargetRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/targets/{targetId}/push'.replace('{targetId}', targetId); @@ -1372,20 +1210,16 @@ const accountDeletePushTarget = async ({targetId,parseOutput = true, overrideFor return response; } -/** - * @typedef {Object} AccountCreateEmailTokenRequestParams - * @property {string} userId User ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. If the email address has never been used, a new account is created using the provided userId. Otherwise, if the email address is already attached to an account, the user ID is ignored. - * @property {string} email User email. - * @property {boolean} phrase Toggle for security phrase. If enabled, email will be send with a randomly generated phrase and the phrase will also be included in the response. Confirming phrases match increases the security of your authentication flow. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {AccountCreateEmailTokenRequestParams} params - */ -const accountCreateEmailToken = async ({userId,email,phrase,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface AccountCreateEmailTokenRequestParams { + userId: string; + email: string; + phrase?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const accountCreateEmailToken = async ({userId,email,phrase,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountCreateEmailTokenRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/tokens/email'; @@ -1413,21 +1247,17 @@ const accountCreateEmailToken = async ({userId,email,phrase,parseOutput = true, return response; } -/** - * @typedef {Object} AccountCreateMagicURLTokenRequestParams - * @property {string} userId Unique Id. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. If the email address has never been used, a new account is created using the provided userId. Otherwise, if the email address is already attached to an account, the user ID is ignored. - * @property {string} email User email. - * @property {string} url URL to redirect the user back to your app from the magic URL login. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. - * @property {boolean} phrase Toggle for security phrase. If enabled, email will be send with a randomly generated phrase and the phrase will also be included in the response. Confirming phrases match increases the security of your authentication flow. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {AccountCreateMagicURLTokenRequestParams} params - */ -const accountCreateMagicURLToken = async ({userId,email,url,phrase,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface AccountCreateMagicURLTokenRequestParams { + userId: string; + email: string; + url?: string; + phrase?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const accountCreateMagicURLToken = async ({userId,email,url,phrase,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountCreateMagicURLTokenRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/tokens/magic-url'; @@ -1458,21 +1288,17 @@ const accountCreateMagicURLToken = async ({userId,email,url,phrase,parseOutput = return response; } -/** - * @typedef {Object} AccountCreateOAuth2TokenRequestParams - * @property {OAuthProvider} provider OAuth2 Provider. Currently, supported providers are: amazon, apple, auth0, authentik, autodesk, bitbucket, bitly, box, dailymotion, discord, disqus, dropbox, etsy, facebook, figma, github, gitlab, google, linkedin, microsoft, notion, oidc, okta, paypal, paypalSandbox, podio, salesforce, slack, spotify, stripe, tradeshift, tradeshiftBox, twitch, wordpress, yahoo, yammer, yandex, zoho, zoom. - * @property {string} success URL to redirect back to your app after a successful login attempt. Only URLs from hostnames in your project's platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. - * @property {string} failure URL to redirect back to your app after a failed login attempt. Only URLs from hostnames in your project's platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. - * @property {string[]} scopes A list of custom OAuth2 scopes. Check each provider internal docs for a list of supported scopes. Maximum of 100 scopes are allowed, each 4096 characters long. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {AccountCreateOAuth2TokenRequestParams} params - */ -const accountCreateOAuth2Token = async ({provider,success,failure,scopes,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface AccountCreateOAuth2TokenRequestParams { + provider: OAuthProvider; + success?: string; + failure?: string; + scopes?: string[]; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const accountCreateOAuth2Token = async ({provider,success,failure,scopes,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountCreateOAuth2TokenRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/tokens/oauth2/{provider}'.replace('{provider}', provider); @@ -1499,19 +1325,15 @@ const accountCreateOAuth2Token = async ({provider,success,failure,scopes,parseOu return response; } -/** - * @typedef {Object} AccountCreatePhoneTokenRequestParams - * @property {string} userId Unique Id. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. If the phone number has never been used, a new account is created using the provided userId. Otherwise, if the phone number is already attached to an account, the user ID is ignored. - * @property {string} phone Phone number. Format this number with a leading '+' and a country code, e.g., +16175551212. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountCreatePhoneTokenRequestParams { + userId: string; + phone: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountCreatePhoneTokenRequestParams} params - */ -const accountCreatePhoneToken = async ({userId,phone,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountCreatePhoneToken = async ({userId,phone,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountCreatePhoneTokenRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/tokens/phone'; @@ -1536,18 +1358,14 @@ const accountCreatePhoneToken = async ({userId,phone,parseOutput = true, overrid return response; } -/** - * @typedef {Object} AccountCreateEmailVerificationRequestParams - * @property {string} url URL to redirect the user back to your app from the verification email. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountCreateEmailVerificationRequestParams { + url: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountCreateEmailVerificationRequestParams} params - */ -const accountCreateEmailVerification = async ({url,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountCreateEmailVerification = async ({url,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountCreateEmailVerificationRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/verifications/email'; @@ -1569,18 +1387,14 @@ const accountCreateEmailVerification = async ({url,parseOutput = true, overrideF return response; } -/** - * @typedef {Object} AccountCreateVerificationRequestParams - * @property {string} url URL to redirect the user back to your app from the verification email. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountCreateVerificationRequestParams { + url: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountCreateVerificationRequestParams} params - */ -const accountCreateVerification = async ({url,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountCreateVerification = async ({url,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountCreateVerificationRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/verifications/email'; @@ -1602,19 +1416,15 @@ const accountCreateVerification = async ({url,parseOutput = true, overrideForCli return response; } -/** - * @typedef {Object} AccountUpdateEmailVerificationRequestParams - * @property {string} userId User ID. - * @property {string} secret Valid verification token. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountUpdateEmailVerificationRequestParams { + userId: string; + secret: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountUpdateEmailVerificationRequestParams} params - */ -const accountUpdateEmailVerification = async ({userId,secret,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountUpdateEmailVerification = async ({userId,secret,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountUpdateEmailVerificationRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/verifications/email'; @@ -1639,19 +1449,15 @@ const accountUpdateEmailVerification = async ({userId,secret,parseOutput = true, return response; } -/** - * @typedef {Object} AccountUpdateVerificationRequestParams - * @property {string} userId User ID. - * @property {string} secret Valid verification token. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountUpdateVerificationRequestParams { + userId: string; + secret: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountUpdateVerificationRequestParams} params - */ -const accountUpdateVerification = async ({userId,secret,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountUpdateVerification = async ({userId,secret,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountUpdateVerificationRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/verifications/email'; @@ -1676,17 +1482,13 @@ const accountUpdateVerification = async ({userId,secret,parseOutput = true, over return response; } -/** - * @typedef {Object} AccountCreatePhoneVerificationRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountCreatePhoneVerificationRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountCreatePhoneVerificationRequestParams} params - */ -const accountCreatePhoneVerification = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountCreatePhoneVerification = async ({parseOutput = true, overrideForCli = false, sdk = undefined}: AccountCreatePhoneVerificationRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/verifications/phone'; @@ -1705,19 +1507,15 @@ const accountCreatePhoneVerification = async ({parseOutput = true, overrideForCl return response; } -/** - * @typedef {Object} AccountUpdatePhoneVerificationRequestParams - * @property {string} userId User ID. - * @property {string} secret Valid verification token. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface AccountUpdatePhoneVerificationRequestParams { + userId: string; + secret: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {AccountUpdatePhoneVerificationRequestParams} params - */ -const accountUpdatePhoneVerification = async ({userId,secret,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const accountUpdatePhoneVerification = async ({userId,secret,parseOutput = true, overrideForCli = false, sdk = undefined}: AccountUpdatePhoneVerificationRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/account/verifications/phone'; @@ -1773,7 +1571,7 @@ account .command(`list-identities`) .description(`Get the list of identities for the currently logged in user.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: userId, provider, providerUid, providerEmail, providerAccessTokenExpiry`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(accountListIdentities)) account @@ -1791,13 +1589,13 @@ account .command(`list-logs`) .description(`Get the list of latest security activity logs for the currently logged in user. Each log returns user IP address, location and date and time of log.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Only supported methods are limit and offset`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(accountListLogs)) account .command(`update-mfa`) .description(`Enable or disable MFA on an account.`) - .requiredOption(`--mfa [value]`, `Enable or disable MFA.`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--mfa [value]`, `Enable or disable MFA.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(accountUpdateMFA)) account @@ -2000,7 +1798,7 @@ account .description(`Sends the user an email with a secret key for creating a session. If the email address has never been used, a **new account is created** using the provided 'userId'. Otherwise, if the email address is already attached to an account, the **user ID is ignored**. Then, the user will receive an email with the one-time password. Use the returned user ID and secret and submit a request to the [POST /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) endpoint to complete the login process. The secret sent to the user's email is valid for 15 minutes. A user is limited to 10 active sessions at a time by default. [Learn more about session limits](https://appwrite.io/docs/authentication-security#limits). `) .requiredOption(`--user-id `, `User ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. If the email address has never been used, a new account is created using the provided userId. Otherwise, if the email address is already attached to an account, the user ID is ignored.`) .requiredOption(`--email `, `User email.`) - .option(`--phrase [value]`, `Toggle for security phrase. If enabled, email will be send with a randomly generated phrase and the phrase will also be included in the response. Confirming phrases match increases the security of your authentication flow.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--phrase [value]`, `Toggle for security phrase. If enabled, email will be send with a randomly generated phrase and the phrase will also be included in the response. Confirming phrases match increases the security of your authentication flow.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(accountCreateEmailToken)) account @@ -2009,7 +1807,7 @@ account .requiredOption(`--user-id `, `Unique Id. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. If the email address has never been used, a new account is created using the provided userId. Otherwise, if the email address is already attached to an account, the user ID is ignored.`) .requiredOption(`--email `, `User email.`) .option(`--url `, `URL to redirect the user back to your app from the magic URL login. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API.`) - .option(`--phrase [value]`, `Toggle for security phrase. If enabled, email will be send with a randomly generated phrase and the phrase will also be included in the response. Confirming phrases match increases the security of your authentication flow.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--phrase [value]`, `Toggle for security phrase. If enabled, email will be send with a randomly generated phrase and the phrase will also be included in the response. Confirming phrases match increases the security of your authentication flow.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(accountCreateMagicURLToken)) account @@ -2066,56 +1864,4 @@ account .requiredOption(`--secret `, `Valid verification token.`) .action(actionRunner(accountUpdatePhoneVerification)) -module.exports = { - account, - accountGet, - accountCreate, - accountDelete, - accountUpdateEmail, - accountListIdentities, - accountDeleteIdentity, - accountCreateJWT, - accountListLogs, - accountUpdateMFA, - accountCreateMFAAuthenticator, - accountUpdateMFAAuthenticator, - accountDeleteMFAAuthenticator, - accountCreateMFAChallenge, - accountUpdateMFAChallenge, - accountListMFAFactors, - accountGetMFARecoveryCodes, - accountCreateMFARecoveryCodes, - accountUpdateMFARecoveryCodes, - accountUpdateName, - accountUpdatePassword, - accountUpdatePhone, - accountGetPrefs, - accountUpdatePrefs, - accountCreateRecovery, - accountUpdateRecovery, - accountListSessions, - accountDeleteSessions, - accountCreateAnonymousSession, - accountCreateEmailPasswordSession, - accountUpdateMagicURLSession, - accountCreateOAuth2Session, - accountUpdatePhoneSession, - accountCreateSession, - accountGetSession, - accountUpdateSession, - accountDeleteSession, - accountUpdateStatus, - accountCreatePushTarget, - accountUpdatePushTarget, - accountDeletePushTarget, - accountCreateEmailToken, - accountCreateMagicURLToken, - accountCreateOAuth2Token, - accountCreatePhoneToken, - accountCreateEmailVerification, - accountCreateVerification, - accountUpdateEmailVerification, - accountUpdateVerification, - accountCreatePhoneVerification, - accountUpdatePhoneVerification -}; + diff --git a/lib/commands/console.js b/lib/commands/console.js deleted file mode 100644 index 967d2aad..00000000 --- a/lib/commands/console.js +++ /dev/null @@ -1,127 +0,0 @@ -const fs = require('fs'); -const pathLib = require('path'); -const tar = require("tar"); -const ignore = require("ignore"); -const { promisify } = require('util'); -const libClient = require('../client.js'); -const { getAllFiles, showConsoleLink } = require('../utils.js'); -const { Command } = require('commander'); -const { sdkForProject, sdkForConsole } = require('../sdks') -const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } = require('../parser') -const { localConfig, globalConfig } = require("../config"); -const { File } = require('undici'); -const { ReadableStream } = require('stream/web'); - -/** - * @param {fs.ReadStream} readStream - * @returns {ReadableStream} - */ -function convertReadStreamToReadableStream(readStream) { - return new ReadableStream({ - start(controller) { - readStream.on("data", (chunk) => { - controller.enqueue(chunk); - }); - readStream.on("end", () => { - controller.close(); - }); - readStream.on("error", (err) => { - controller.error(err); - }); - }, - cancel() { - readStream.destroy(); - }, - }); -} - -const console = new Command("console").description(commandDescriptions['console'] ?? '').configureHelp({ - helpWidth: process.stdout.columns || 80 -}) - -/** - * @typedef {Object} ConsoleGetResourceRequestParams - * @property {string} value Resource value. - * @property {ConsoleResourceType} type Resource type. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ConsoleGetResourceRequestParams} params - */ -const consoleGetResource = async ({value,type,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { - let client = !sdk ? await sdkForProject() : - sdk; - let apiPath = '/console/resources'; - let payload = {}; - if (typeof value !== 'undefined') { - payload['value'] = value; - } - if (typeof type !== 'undefined') { - payload['type'] = type; - } - - let response = undefined; - - response = await client.call('get', apiPath, { - }, payload); - - if (parseOutput) { - if(console) { - showConsoleLink('console', 'getResource'); - } else { - parse(response) - } - } - - return response; - -} -/** - * @typedef {Object} ConsoleVariablesRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ConsoleVariablesRequestParams} params - */ -const consoleVariables = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : - sdk; - let apiPath = '/console/variables'; - let payload = {}; - - let response = undefined; - - response = await client.call('get', apiPath, { - }, payload); - - if (parseOutput) { - parse(response) - } - - return response; - -} -console - .command(`get-resource`) - .description(`Check if a resource ID is available.`) - .requiredOption(`--value `, `Resource value.`) - .requiredOption(`--type `, `Resource type.`) - .option(`--console`, `Get the resource console url`) - .action(actionRunner(consoleGetResource)) - -console - .command(`variables`) - .description(`Get all Environment Variables that are relevant for the console.`) - .action(actionRunner(consoleVariables)) - -module.exports = { - console, - consoleGetResource, - consoleVariables -}; diff --git a/lib/commands/console.ts b/lib/commands/console.ts new file mode 100644 index 00000000..e9ad93c7 --- /dev/null +++ b/lib/commands/console.ts @@ -0,0 +1,112 @@ +import fs = require('fs'); +import pathLib = require('path'); +import tar = require('tar'); +import ignore = require('ignore'); +import { promisify } from 'util'; +import Client from '../client'; +import { getAllFiles, showConsoleLink } from '../utils'; +import { Command } from 'commander'; +import { sdkForProject, sdkForConsole } from '../sdks'; +import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } from '../parser'; +import { localConfig, globalConfig } from '../config'; +import { File } from 'undici'; +import { ReadableStream } from 'stream/web'; + +function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { + return new ReadableStream({ + start(controller) { + readStream.on("data", (chunk: Buffer) => { + controller.enqueue(chunk); + }); + readStream.on("end", () => { + controller.close(); + }); + readStream.on("error", (err: Error) => { + controller.error(err); + }); + }, + cancel() { + readStream.destroy(); + }, + }); +} + +export const console = new Command("console").description(commandDescriptions['console'] ?? '').configureHelp({ + helpWidth: process.stdout.columns || 80 +}) + +interface ConsoleGetResourceRequestParams { + value: string; + type: ConsoleResourceType; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const consoleGetResource = async ({value,type,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: ConsoleGetResourceRequestParams): Promise => { + let client = !sdk ? await sdkForProject() : + sdk; + let apiPath = '/console/resources'; + let payload = {}; + if (typeof value !== 'undefined') { + payload['value'] = value; + } + if (typeof type !== 'undefined') { + payload['type'] = type; + } + + let response = undefined; + + response = await client.call('get', apiPath, { + }, payload); + + if (parseOutput) { + if(showConsole) { + showConsoleLink('console', 'getResource'); + } else { + parse(response) + } + } + + return response; + +} +interface ConsoleVariablesRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const consoleVariables = async ({parseOutput = true, overrideForCli = false, sdk = undefined}: ConsoleVariablesRequestParams): Promise => { + let client = !sdk ? await sdkForProject() : + sdk; + let apiPath = '/console/variables'; + let payload = {}; + + let response = undefined; + + response = await client.call('get', apiPath, { + }, payload); + + if (parseOutput) { + parse(response) + } + + return response; + +} +console + .command(`get-resource`) + .description(`Check if a resource ID is available.`) + .requiredOption(`--value `, `Resource value.`) + .requiredOption(`--type `, `Resource type.`) + .option(`--console`, `Get the resource console url`) + .action(actionRunner(consoleGetResource)) + +console + .command(`variables`) + .description(`Get all Environment Variables that are relevant for the console.`) + .action(actionRunner(consoleVariables)) + + diff --git a/lib/commands/databases.js b/lib/commands/databases.ts similarity index 61% rename from lib/commands/databases.js rename to lib/commands/databases.ts index d1a12681..83de0290 100644 --- a/lib/commands/databases.js +++ b/lib/commands/databases.ts @@ -1,31 +1,27 @@ -const fs = require('fs'); -const pathLib = require('path'); -const tar = require("tar"); -const ignore = require("ignore"); -const { promisify } = require('util'); -const libClient = require('../client.js'); -const { getAllFiles, showConsoleLink } = require('../utils.js'); -const { Command } = require('commander'); -const { sdkForProject, sdkForConsole } = require('../sdks') -const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } = require('../parser') -const { localConfig, globalConfig } = require("../config"); -const { File } = require('undici'); -const { ReadableStream } = require('stream/web'); - -/** - * @param {fs.ReadStream} readStream - * @returns {ReadableStream} - */ -function convertReadStreamToReadableStream(readStream) { +import fs = require('fs'); +import pathLib = require('path'); +import tar = require('tar'); +import ignore = require('ignore'); +import { promisify } from 'util'; +import Client from '../client'; +import { getAllFiles, showConsoleLink } from '../utils'; +import { Command } from 'commander'; +import { sdkForProject, sdkForConsole } from '../sdks'; +import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } from '../parser'; +import { localConfig, globalConfig } from '../config'; +import { File } from 'undici'; +import { ReadableStream } from 'stream/web'; + +function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ start(controller) { - readStream.on("data", (chunk) => { + readStream.on("data", (chunk: Buffer) => { controller.enqueue(chunk); }); readStream.on("end", () => { controller.close(); }); - readStream.on("error", (err) => { + readStream.on("error", (err: Error) => { controller.error(err); }); }, @@ -35,24 +31,21 @@ function convertReadStreamToReadableStream(readStream) { }); } -const databases = new Command("databases").description(commandDescriptions['databases'] ?? '').configureHelp({ +export const databases = new Command("databases").description(commandDescriptions['databases'] ?? '').configureHelp({ helpWidth: process.stdout.columns || 80 }) -/** - * @typedef {Object} DatabasesListRequestParams - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name - * @property {string} search Search term to filter your list results. Max length: 256 chars. - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesListRequestParams { + queries?: string[]; + search?: string; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {DatabasesListRequestParams} params - */ -const databasesList = async ({queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const databasesList = async ({queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: DatabasesListRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases'; @@ -73,7 +66,7 @@ const databasesList = async ({queries,search,total,parseOutput = true, overrideF }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('databases', 'list'); } else { parse(response) @@ -83,20 +76,16 @@ const databasesList = async ({queries,search,total,parseOutput = true, overrideF return response; } -/** - * @typedef {Object} DatabasesCreateRequestParams - * @property {string} databaseId Unique Id. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} name Database name. Max length: 128 chars. - * @property {boolean} enabled Is the database enabled? When set to 'disabled', users cannot access the database but Server SDKs with an API key can still read and write to the database. No data is lost when this is toggled. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesCreateRequestParams { + databaseId: string; + name: string; + enabled?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesCreateRequestParams} params - */ -const databasesCreate = async ({databaseId,name,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesCreate = async ({databaseId,name,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesCreateRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases'; @@ -124,18 +113,15 @@ const databasesCreate = async ({databaseId,name,enabled,parseOutput = true, over return response; } -/** - * @typedef {Object} DatabasesListTransactionsRequestParams - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesListTransactionsRequestParams { + queries?: string[]; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {DatabasesListTransactionsRequestParams} params - */ -const databasesListTransactions = async ({queries,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const databasesListTransactions = async ({queries,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: DatabasesListTransactionsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/transactions'; @@ -150,7 +136,7 @@ const databasesListTransactions = async ({queries,parseOutput = true, overrideFo }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('databases', 'listTransactions'); } else { parse(response) @@ -160,18 +146,14 @@ const databasesListTransactions = async ({queries,parseOutput = true, overrideFo return response; } -/** - * @typedef {Object} DatabasesCreateTransactionRequestParams - * @property {number} ttl Seconds before the transaction expires. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesCreateTransactionRequestParams { + ttl?: number; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesCreateTransactionRequestParams} params - */ -const databasesCreateTransaction = async ({ttl,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesCreateTransaction = async ({ttl,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesCreateTransactionRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/transactions'; @@ -193,18 +175,15 @@ const databasesCreateTransaction = async ({ttl,parseOutput = true, overrideForCl return response; } -/** - * @typedef {Object} DatabasesGetTransactionRequestParams - * @property {string} transactionId Transaction ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesGetTransactionRequestParams { + transactionId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {DatabasesGetTransactionRequestParams} params - */ -const databasesGetTransaction = async ({transactionId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const databasesGetTransaction = async ({transactionId,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: DatabasesGetTransactionRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/transactions/{transactionId}'.replace('{transactionId}', transactionId); @@ -216,7 +195,7 @@ const databasesGetTransaction = async ({transactionId,parseOutput = true, overri }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('databases', 'getTransaction', transactionId); } else { parse(response) @@ -226,20 +205,16 @@ const databasesGetTransaction = async ({transactionId,parseOutput = true, overri return response; } -/** - * @typedef {Object} DatabasesUpdateTransactionRequestParams - * @property {string} transactionId Transaction ID. - * @property {boolean} commit Commit transaction? - * @property {boolean} rollback Rollback transaction? - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesUpdateTransactionRequestParams { + transactionId: string; + commit?: boolean; + rollback?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesUpdateTransactionRequestParams} params - */ -const databasesUpdateTransaction = async ({transactionId,commit,rollback,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesUpdateTransaction = async ({transactionId,commit,rollback,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesUpdateTransactionRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/transactions/{transactionId}'.replace('{transactionId}', transactionId); @@ -264,18 +239,14 @@ const databasesUpdateTransaction = async ({transactionId,commit,rollback,parseOu return response; } -/** - * @typedef {Object} DatabasesDeleteTransactionRequestParams - * @property {string} transactionId Transaction ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesDeleteTransactionRequestParams { + transactionId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesDeleteTransactionRequestParams} params - */ -const databasesDeleteTransaction = async ({transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesDeleteTransaction = async ({transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesDeleteTransactionRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/transactions/{transactionId}'.replace('{transactionId}', transactionId); @@ -294,19 +265,15 @@ const databasesDeleteTransaction = async ({transactionId,parseOutput = true, ove return response; } -/** - * @typedef {Object} DatabasesCreateOperationsRequestParams - * @property {string} transactionId Transaction ID. - * @property {object[]} operations Array of staged operations. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesCreateOperationsRequestParams { + transactionId: string; + operations?: object[]; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesCreateOperationsRequestParams} params - */ -const databasesCreateOperations = async ({transactionId,operations,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesCreateOperations = async ({transactionId,operations,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesCreateOperationsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/transactions/{transactionId}/operations'.replace('{transactionId}', transactionId); @@ -329,18 +296,15 @@ const databasesCreateOperations = async ({transactionId,operations,parseOutput = return response; } -/** - * @typedef {Object} DatabasesListUsageRequestParams - * @property {UsageRange} range Date range. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesListUsageRequestParams { + range?: UsageRange; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {DatabasesListUsageRequestParams} params - */ -const databasesListUsage = async ({range,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const databasesListUsage = async ({range,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: DatabasesListUsageRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/usage'; @@ -355,7 +319,7 @@ const databasesListUsage = async ({range,parseOutput = true, overrideForCli = fa }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('databases', 'listUsage'); } else { parse(response) @@ -365,18 +329,15 @@ const databasesListUsage = async ({range,parseOutput = true, overrideForCli = fa return response; } -/** - * @typedef {Object} DatabasesGetRequestParams - * @property {string} databaseId Database ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesGetRequestParams { + databaseId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {DatabasesGetRequestParams} params - */ -const databasesGet = async ({databaseId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const databasesGet = async ({databaseId,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: DatabasesGetRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}'.replace('{databaseId}', databaseId); @@ -388,7 +349,7 @@ const databasesGet = async ({databaseId,parseOutput = true, overrideForCli = fal }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('databases', 'get', databaseId); } else { parse(response) @@ -398,20 +359,16 @@ const databasesGet = async ({databaseId,parseOutput = true, overrideForCli = fal return response; } -/** - * @typedef {Object} DatabasesUpdateRequestParams - * @property {string} databaseId Database ID. - * @property {string} name Database name. Max length: 128 chars. - * @property {boolean} enabled Is database enabled? When set to 'disabled', users cannot access the database but Server SDKs with an API key can still read and write to the database. No data is lost when this is toggled. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesUpdateRequestParams { + databaseId: string; + name: string; + enabled?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesUpdateRequestParams} params - */ -const databasesUpdate = async ({databaseId,name,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesUpdate = async ({databaseId,name,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesUpdateRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}'.replace('{databaseId}', databaseId); @@ -436,18 +393,14 @@ const databasesUpdate = async ({databaseId,name,enabled,parseOutput = true, over return response; } -/** - * @typedef {Object} DatabasesDeleteRequestParams - * @property {string} databaseId Database ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesDeleteRequestParams { + databaseId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesDeleteRequestParams} params - */ -const databasesDelete = async ({databaseId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesDelete = async ({databaseId,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesDeleteRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}'.replace('{databaseId}', databaseId); @@ -466,21 +419,18 @@ const databasesDelete = async ({databaseId,parseOutput = true, overrideForCli = return response; } -/** - * @typedef {Object} DatabasesListCollectionsRequestParams - * @property {string} databaseId Database ID. - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name, enabled, documentSecurity - * @property {string} search Search term to filter your list results. Max length: 256 chars. - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesListCollectionsRequestParams { + databaseId: string; + queries?: string[]; + search?: string; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {DatabasesListCollectionsRequestParams} params - */ -const databasesListCollections = async ({databaseId,queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const databasesListCollections = async ({databaseId,queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: DatabasesListCollectionsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections'.replace('{databaseId}', databaseId); @@ -501,7 +451,7 @@ const databasesListCollections = async ({databaseId,queries,search,total,parseOu }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('databases', 'listCollections', databaseId); } else { parse(response) @@ -511,23 +461,21 @@ const databasesListCollections = async ({databaseId,queries,search,total,parseOu return response; } -/** - * @typedef {Object} DatabasesCreateCollectionRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Unique Id. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} name Collection name. Max length: 128 chars. - * @property {string[]} permissions An array of permissions strings. By default, no user is granted with any permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - * @property {boolean} documentSecurity Enables configuring permissions for individual documents. A user needs one of document or collection level permissions to access a document. [Learn more about permissions](https://appwrite.io/docs/permissions). - * @property {boolean} enabled Is collection enabled? When set to 'disabled', users cannot access the collection but Server SDKs with and API key can still read and write to the collection. No data is lost when this is toggled. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesCreateCollectionRequestParams { + databaseId: string; + collectionId: string; + name: string; + permissions?: string[]; + documentSecurity?: boolean; + enabled?: boolean; + attributes?: object[]; + indexes?: object[]; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesCreateCollectionRequestParams} params - */ -const databasesCreateCollection = async ({databaseId,collectionId,name,permissions,documentSecurity,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesCreateCollection = async ({databaseId,collectionId,name,permissions,documentSecurity,enabled,attributes,indexes,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesCreateCollectionRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections'.replace('{databaseId}', databaseId); @@ -548,6 +496,14 @@ const databasesCreateCollection = async ({databaseId,collectionId,name,permissio if (typeof enabled !== 'undefined') { payload['enabled'] = enabled; } + attributes = attributes === true ? [] : attributes; + if (typeof attributes !== 'undefined') { + payload['attributes'] = attributes; + } + indexes = indexes === true ? [] : indexes; + if (typeof indexes !== 'undefined') { + payload['indexes'] = indexes; + } let response = undefined; @@ -562,19 +518,16 @@ const databasesCreateCollection = async ({databaseId,collectionId,name,permissio return response; } -/** - * @typedef {Object} DatabasesGetCollectionRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesGetCollectionRequestParams { + databaseId: string; + collectionId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {DatabasesGetCollectionRequestParams} params - */ -const databasesGetCollection = async ({databaseId,collectionId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const databasesGetCollection = async ({databaseId,collectionId,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: DatabasesGetCollectionRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); @@ -586,7 +539,7 @@ const databasesGetCollection = async ({databaseId,collectionId,parseOutput = tru }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('databases', 'getCollection', databaseId, collectionId); } else { parse(response) @@ -596,23 +549,19 @@ const databasesGetCollection = async ({databaseId,collectionId,parseOutput = tru return response; } -/** - * @typedef {Object} DatabasesUpdateCollectionRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. - * @property {string} name Collection name. Max length: 128 chars. - * @property {string[]} permissions An array of permission strings. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions). - * @property {boolean} documentSecurity Enables configuring permissions for individual documents. A user needs one of document or collection level permissions to access a document. [Learn more about permissions](https://appwrite.io/docs/permissions). - * @property {boolean} enabled Is collection enabled? When set to 'disabled', users cannot access the collection but Server SDKs with and API key can still read and write to the collection. No data is lost when this is toggled. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesUpdateCollectionRequestParams { + databaseId: string; + collectionId: string; + name: string; + permissions?: string[]; + documentSecurity?: boolean; + enabled?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesUpdateCollectionRequestParams} params - */ -const databasesUpdateCollection = async ({databaseId,collectionId,name,permissions,documentSecurity,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesUpdateCollection = async ({databaseId,collectionId,name,permissions,documentSecurity,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesUpdateCollectionRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); @@ -644,19 +593,15 @@ const databasesUpdateCollection = async ({databaseId,collectionId,name,permissio return response; } -/** - * @typedef {Object} DatabasesDeleteCollectionRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesDeleteCollectionRequestParams { + databaseId: string; + collectionId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesDeleteCollectionRequestParams} params - */ -const databasesDeleteCollection = async ({databaseId,collectionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesDeleteCollection = async ({databaseId,collectionId,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesDeleteCollectionRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); @@ -675,21 +620,18 @@ const databasesDeleteCollection = async ({databaseId,collectionId,parseOutput = return response; } -/** - * @typedef {Object} DatabasesListAttributesRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: key, type, size, required, array, status, error - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesListAttributesRequestParams { + databaseId: string; + collectionId: string; + queries?: string[]; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {DatabasesListAttributesRequestParams} params - */ -const databasesListAttributes = async ({databaseId,collectionId,queries,total,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const databasesListAttributes = async ({databaseId,collectionId,queries,total,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: DatabasesListAttributesRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); @@ -707,7 +649,7 @@ const databasesListAttributes = async ({databaseId,collectionId,queries,total,pa }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('databases', 'listAttributes', databaseId, collectionId); } else { parse(response) @@ -717,23 +659,19 @@ const databasesListAttributes = async ({databaseId,collectionId,queries,total,pa return response; } -/** - * @typedef {Object} DatabasesCreateBooleanAttributeRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection). - * @property {string} key Attribute Key. - * @property {boolean} required Is attribute required? - * @property {boolean} xdefault Default value for attribute when not provided. Cannot be set when attribute is required. - * @property {boolean} array Is attribute an array? - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesCreateBooleanAttributeRequestParams { + databaseId: string; + collectionId: string; + key: string; + required: boolean; + xdefault?: boolean; + array?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesCreateBooleanAttributeRequestParams} params - */ -const databasesCreateBooleanAttribute = async ({databaseId,collectionId,key,required,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesCreateBooleanAttribute = async ({databaseId,collectionId,key,required,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesCreateBooleanAttributeRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/boolean'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); @@ -764,23 +702,19 @@ const databasesCreateBooleanAttribute = async ({databaseId,collectionId,key,requ return response; } -/** - * @typedef {Object} DatabasesUpdateBooleanAttributeRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#createCollection). - * @property {string} key Attribute Key. - * @property {boolean} required Is attribute required? - * @property {boolean} xdefault Default value for attribute when not provided. Cannot be set when attribute is required. - * @property {string} newKey New attribute key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesUpdateBooleanAttributeRequestParams { + databaseId: string; + collectionId: string; + key: string; + required: boolean; + xdefault: boolean; + newKey?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesUpdateBooleanAttributeRequestParams} params - */ -const databasesUpdateBooleanAttribute = async ({databaseId,collectionId,key,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesUpdateBooleanAttribute = async ({databaseId,collectionId,key,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesUpdateBooleanAttributeRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/boolean/{key}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{key}', key); @@ -808,23 +742,19 @@ const databasesUpdateBooleanAttribute = async ({databaseId,collectionId,key,requ return response; } -/** - * @typedef {Object} DatabasesCreateDatetimeAttributeRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#createCollection). - * @property {string} key Attribute Key. - * @property {boolean} required Is attribute required? - * @property {string} xdefault Default value for the attribute in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. Cannot be set when attribute is required. - * @property {boolean} array Is attribute an array? - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesCreateDatetimeAttributeRequestParams { + databaseId: string; + collectionId: string; + key: string; + required: boolean; + xdefault?: string; + array?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesCreateDatetimeAttributeRequestParams} params - */ -const databasesCreateDatetimeAttribute = async ({databaseId,collectionId,key,required,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesCreateDatetimeAttribute = async ({databaseId,collectionId,key,required,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesCreateDatetimeAttributeRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/datetime'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); @@ -855,23 +785,19 @@ const databasesCreateDatetimeAttribute = async ({databaseId,collectionId,key,req return response; } -/** - * @typedef {Object} DatabasesUpdateDatetimeAttributeRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. - * @property {string} key Attribute Key. - * @property {boolean} required Is attribute required? - * @property {string} xdefault Default value for attribute when not provided. Cannot be set when attribute is required. - * @property {string} newKey New attribute key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesUpdateDatetimeAttributeRequestParams { + databaseId: string; + collectionId: string; + key: string; + required: boolean; + xdefault: string; + newKey?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesUpdateDatetimeAttributeRequestParams} params - */ -const databasesUpdateDatetimeAttribute = async ({databaseId,collectionId,key,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesUpdateDatetimeAttribute = async ({databaseId,collectionId,key,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesUpdateDatetimeAttributeRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/datetime/{key}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{key}', key); @@ -899,23 +825,19 @@ const databasesUpdateDatetimeAttribute = async ({databaseId,collectionId,key,req return response; } -/** - * @typedef {Object} DatabasesCreateEmailAttributeRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. - * @property {string} key Attribute Key. - * @property {boolean} required Is attribute required? - * @property {string} xdefault Default value for attribute when not provided. Cannot be set when attribute is required. - * @property {boolean} array Is attribute an array? - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesCreateEmailAttributeRequestParams { + databaseId: string; + collectionId: string; + key: string; + required: boolean; + xdefault?: string; + array?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesCreateEmailAttributeRequestParams} params - */ -const databasesCreateEmailAttribute = async ({databaseId,collectionId,key,required,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesCreateEmailAttribute = async ({databaseId,collectionId,key,required,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesCreateEmailAttributeRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/email'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); @@ -946,23 +868,19 @@ const databasesCreateEmailAttribute = async ({databaseId,collectionId,key,requir return response; } -/** - * @typedef {Object} DatabasesUpdateEmailAttributeRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. - * @property {string} key Attribute Key. - * @property {boolean} required Is attribute required? - * @property {string} xdefault Default value for attribute when not provided. Cannot be set when attribute is required. - * @property {string} newKey New Attribute Key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesUpdateEmailAttributeRequestParams { + databaseId: string; + collectionId: string; + key: string; + required: boolean; + xdefault: string; + newKey?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesUpdateEmailAttributeRequestParams} params - */ -const databasesUpdateEmailAttribute = async ({databaseId,collectionId,key,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesUpdateEmailAttribute = async ({databaseId,collectionId,key,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesUpdateEmailAttributeRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/email/{key}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{key}', key); @@ -990,24 +908,20 @@ const databasesUpdateEmailAttribute = async ({databaseId,collectionId,key,requir return response; } -/** - * @typedef {Object} DatabasesCreateEnumAttributeRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. - * @property {string} key Attribute Key. - * @property {string[]} elements Array of enum values. - * @property {boolean} required Is attribute required? - * @property {string} xdefault Default value for attribute when not provided. Cannot be set when attribute is required. - * @property {boolean} array Is attribute an array? - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesCreateEnumAttributeRequestParams { + databaseId: string; + collectionId: string; + key: string; + elements: string[]; + required: boolean; + xdefault?: string; + array?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesCreateEnumAttributeRequestParams} params - */ -const databasesCreateEnumAttribute = async ({databaseId,collectionId,key,elements,required,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesCreateEnumAttribute = async ({databaseId,collectionId,key,elements,required,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesCreateEnumAttributeRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/enum'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); @@ -1042,24 +956,20 @@ const databasesCreateEnumAttribute = async ({databaseId,collectionId,key,element return response; } -/** - * @typedef {Object} DatabasesUpdateEnumAttributeRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. - * @property {string} key Attribute Key. - * @property {string[]} elements Updated list of enum values. - * @property {boolean} required Is attribute required? - * @property {string} xdefault Default value for attribute when not provided. Cannot be set when attribute is required. - * @property {string} newKey New Attribute Key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesUpdateEnumAttributeRequestParams { + databaseId: string; + collectionId: string; + key: string; + elements: string[]; + required: boolean; + xdefault: string; + newKey?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesUpdateEnumAttributeRequestParams} params - */ -const databasesUpdateEnumAttribute = async ({databaseId,collectionId,key,elements,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesUpdateEnumAttribute = async ({databaseId,collectionId,key,elements,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesUpdateEnumAttributeRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/enum/{key}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{key}', key); @@ -1091,25 +1001,21 @@ const databasesUpdateEnumAttribute = async ({databaseId,collectionId,key,element return response; } -/** - * @typedef {Object} DatabasesCreateFloatAttributeRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. - * @property {string} key Attribute Key. - * @property {boolean} required Is attribute required? - * @property {number} min Minimum value. - * @property {number} max Maximum value. - * @property {number} xdefault Default value. Cannot be set when required. - * @property {boolean} array Is attribute an array? - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesCreateFloatAttributeRequestParams { + databaseId: string; + collectionId: string; + key: string; + required: boolean; + min?: number; + max?: number; + xdefault?: number; + array?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesCreateFloatAttributeRequestParams} params - */ -const databasesCreateFloatAttribute = async ({databaseId,collectionId,key,required,min,max,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesCreateFloatAttribute = async ({databaseId,collectionId,key,required,min,max,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesCreateFloatAttributeRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/float'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); @@ -1146,25 +1052,21 @@ const databasesCreateFloatAttribute = async ({databaseId,collectionId,key,requir return response; } -/** - * @typedef {Object} DatabasesUpdateFloatAttributeRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. - * @property {string} key Attribute Key. - * @property {boolean} required Is attribute required? - * @property {number} xdefault Default value. Cannot be set when required. - * @property {number} min Minimum value. - * @property {number} max Maximum value. - * @property {string} newKey New Attribute Key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesUpdateFloatAttributeRequestParams { + databaseId: string; + collectionId: string; + key: string; + required: boolean; + xdefault: number; + min?: number; + max?: number; + newKey?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesUpdateFloatAttributeRequestParams} params - */ -const databasesUpdateFloatAttribute = async ({databaseId,collectionId,key,required,xdefault,min,max,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesUpdateFloatAttribute = async ({databaseId,collectionId,key,required,xdefault,min,max,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesUpdateFloatAttributeRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/float/{key}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{key}', key); @@ -1198,25 +1100,21 @@ const databasesUpdateFloatAttribute = async ({databaseId,collectionId,key,requir return response; } -/** - * @typedef {Object} DatabasesCreateIntegerAttributeRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. - * @property {string} key Attribute Key. - * @property {boolean} required Is attribute required? - * @property {number} min Minimum value - * @property {number} max Maximum value - * @property {number} xdefault Default value. Cannot be set when attribute is required. - * @property {boolean} array Is attribute an array? - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesCreateIntegerAttributeRequestParams { + databaseId: string; + collectionId: string; + key: string; + required: boolean; + min?: number; + max?: number; + xdefault?: number; + array?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesCreateIntegerAttributeRequestParams} params - */ -const databasesCreateIntegerAttribute = async ({databaseId,collectionId,key,required,min,max,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesCreateIntegerAttribute = async ({databaseId,collectionId,key,required,min,max,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesCreateIntegerAttributeRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/integer'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); @@ -1253,25 +1151,21 @@ const databasesCreateIntegerAttribute = async ({databaseId,collectionId,key,requ return response; } -/** - * @typedef {Object} DatabasesUpdateIntegerAttributeRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. - * @property {string} key Attribute Key. - * @property {boolean} required Is attribute required? - * @property {number} xdefault Default value. Cannot be set when attribute is required. - * @property {number} min Minimum value - * @property {number} max Maximum value - * @property {string} newKey New Attribute Key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesUpdateIntegerAttributeRequestParams { + databaseId: string; + collectionId: string; + key: string; + required: boolean; + xdefault: number; + min?: number; + max?: number; + newKey?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesUpdateIntegerAttributeRequestParams} params - */ -const databasesUpdateIntegerAttribute = async ({databaseId,collectionId,key,required,xdefault,min,max,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesUpdateIntegerAttribute = async ({databaseId,collectionId,key,required,xdefault,min,max,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesUpdateIntegerAttributeRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/integer/{key}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{key}', key); @@ -1305,23 +1199,19 @@ const databasesUpdateIntegerAttribute = async ({databaseId,collectionId,key,requ return response; } -/** - * @typedef {Object} DatabasesCreateIpAttributeRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. - * @property {string} key Attribute Key. - * @property {boolean} required Is attribute required? - * @property {string} xdefault Default value. Cannot be set when attribute is required. - * @property {boolean} array Is attribute an array? - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesCreateIpAttributeRequestParams { + databaseId: string; + collectionId: string; + key: string; + required: boolean; + xdefault?: string; + array?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesCreateIpAttributeRequestParams} params - */ -const databasesCreateIpAttribute = async ({databaseId,collectionId,key,required,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesCreateIpAttribute = async ({databaseId,collectionId,key,required,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesCreateIpAttributeRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/ip'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); @@ -1352,23 +1242,19 @@ const databasesCreateIpAttribute = async ({databaseId,collectionId,key,required, return response; } -/** - * @typedef {Object} DatabasesUpdateIpAttributeRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. - * @property {string} key Attribute Key. - * @property {boolean} required Is attribute required? - * @property {string} xdefault Default value. Cannot be set when attribute is required. - * @property {string} newKey New Attribute Key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesUpdateIpAttributeRequestParams { + databaseId: string; + collectionId: string; + key: string; + required: boolean; + xdefault: string; + newKey?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesUpdateIpAttributeRequestParams} params - */ -const databasesUpdateIpAttribute = async ({databaseId,collectionId,key,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesUpdateIpAttribute = async ({databaseId,collectionId,key,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesUpdateIpAttributeRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/ip/{key}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{key}', key); @@ -1396,22 +1282,18 @@ const databasesUpdateIpAttribute = async ({databaseId,collectionId,key,required, return response; } -/** - * @typedef {Object} DatabasesCreateLineAttributeRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection). - * @property {string} key Attribute Key. - * @property {boolean} required Is attribute required? - * @property {any[]} xdefault Default value for attribute when not provided, two-dimensional array of coordinate pairs, [[longitude, latitude], [longitude, latitude], …], listing the vertices of the line in order. Cannot be set when attribute is required. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesCreateLineAttributeRequestParams { + databaseId: string; + collectionId: string; + key: string; + required: boolean; + xdefault?: any[]; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesCreateLineAttributeRequestParams} params - */ -const databasesCreateLineAttribute = async ({databaseId,collectionId,key,required,xdefault,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesCreateLineAttribute = async ({databaseId,collectionId,key,required,xdefault,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesCreateLineAttributeRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/line'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); @@ -1440,23 +1322,19 @@ const databasesCreateLineAttribute = async ({databaseId,collectionId,key,require return response; } -/** - * @typedef {Object} DatabasesUpdateLineAttributeRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#createCollection). - * @property {string} key Attribute Key. - * @property {boolean} required Is attribute required? - * @property {any[]} xdefault Default value for attribute when not provided, two-dimensional array of coordinate pairs, [[longitude, latitude], [longitude, latitude], …], listing the vertices of the line in order. Cannot be set when attribute is required. - * @property {string} newKey New attribute key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesUpdateLineAttributeRequestParams { + databaseId: string; + collectionId: string; + key: string; + required: boolean; + xdefault?: any[]; + newKey?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesUpdateLineAttributeRequestParams} params - */ -const databasesUpdateLineAttribute = async ({databaseId,collectionId,key,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesUpdateLineAttribute = async ({databaseId,collectionId,key,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesUpdateLineAttributeRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/line/{key}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{key}', key); @@ -1485,22 +1363,18 @@ const databasesUpdateLineAttribute = async ({databaseId,collectionId,key,require return response; } -/** - * @typedef {Object} DatabasesCreatePointAttributeRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection). - * @property {string} key Attribute Key. - * @property {boolean} required Is attribute required? - * @property {any[]} xdefault Default value for attribute when not provided, array of two numbers [longitude, latitude], representing a single coordinate. Cannot be set when attribute is required. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesCreatePointAttributeRequestParams { + databaseId: string; + collectionId: string; + key: string; + required: boolean; + xdefault?: any[]; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesCreatePointAttributeRequestParams} params - */ -const databasesCreatePointAttribute = async ({databaseId,collectionId,key,required,xdefault,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesCreatePointAttribute = async ({databaseId,collectionId,key,required,xdefault,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesCreatePointAttributeRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/point'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); @@ -1529,23 +1403,19 @@ const databasesCreatePointAttribute = async ({databaseId,collectionId,key,requir return response; } -/** - * @typedef {Object} DatabasesUpdatePointAttributeRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#createCollection). - * @property {string} key Attribute Key. - * @property {boolean} required Is attribute required? - * @property {any[]} xdefault Default value for attribute when not provided, array of two numbers [longitude, latitude], representing a single coordinate. Cannot be set when attribute is required. - * @property {string} newKey New attribute key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesUpdatePointAttributeRequestParams { + databaseId: string; + collectionId: string; + key: string; + required: boolean; + xdefault?: any[]; + newKey?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesUpdatePointAttributeRequestParams} params - */ -const databasesUpdatePointAttribute = async ({databaseId,collectionId,key,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesUpdatePointAttribute = async ({databaseId,collectionId,key,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesUpdatePointAttributeRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/point/{key}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{key}', key); @@ -1574,22 +1444,18 @@ const databasesUpdatePointAttribute = async ({databaseId,collectionId,key,requir return response; } -/** - * @typedef {Object} DatabasesCreatePolygonAttributeRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection). - * @property {string} key Attribute Key. - * @property {boolean} required Is attribute required? - * @property {any[]} xdefault Default value for attribute when not provided, three-dimensional array where the outer array holds one or more linear rings, [[[longitude, latitude], …], …], the first ring is the exterior boundary, any additional rings are interior holes, and each ring must start and end with the same coordinate pair. Cannot be set when attribute is required. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesCreatePolygonAttributeRequestParams { + databaseId: string; + collectionId: string; + key: string; + required: boolean; + xdefault?: any[]; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesCreatePolygonAttributeRequestParams} params - */ -const databasesCreatePolygonAttribute = async ({databaseId,collectionId,key,required,xdefault,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesCreatePolygonAttribute = async ({databaseId,collectionId,key,required,xdefault,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesCreatePolygonAttributeRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/polygon'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); @@ -1618,23 +1484,19 @@ const databasesCreatePolygonAttribute = async ({databaseId,collectionId,key,requ return response; } -/** - * @typedef {Object} DatabasesUpdatePolygonAttributeRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#createCollection). - * @property {string} key Attribute Key. - * @property {boolean} required Is attribute required? - * @property {any[]} xdefault Default value for attribute when not provided, three-dimensional array where the outer array holds one or more linear rings, [[[longitude, latitude], …], …], the first ring is the exterior boundary, any additional rings are interior holes, and each ring must start and end with the same coordinate pair. Cannot be set when attribute is required. - * @property {string} newKey New attribute key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesUpdatePolygonAttributeRequestParams { + databaseId: string; + collectionId: string; + key: string; + required: boolean; + xdefault?: any[]; + newKey?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesUpdatePolygonAttributeRequestParams} params - */ -const databasesUpdatePolygonAttribute = async ({databaseId,collectionId,key,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesUpdatePolygonAttribute = async ({databaseId,collectionId,key,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesUpdatePolygonAttributeRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/polygon/{key}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{key}', key); @@ -1663,25 +1525,21 @@ const databasesUpdatePolygonAttribute = async ({databaseId,collectionId,key,requ return response; } -/** - * @typedef {Object} DatabasesCreateRelationshipAttributeRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. - * @property {string} relatedCollectionId Related Collection ID. - * @property {RelationshipType} type Relation type - * @property {boolean} twoWay Is Two Way? - * @property {string} key Attribute Key. - * @property {string} twoWayKey Two Way Attribute Key. - * @property {RelationMutate} onDelete Constraints option - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesCreateRelationshipAttributeRequestParams { + databaseId: string; + collectionId: string; + relatedCollectionId: string; + type: RelationshipType; + twoWay?: boolean; + key?: string; + twoWayKey?: string; + onDelete?: RelationMutate; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesCreateRelationshipAttributeRequestParams} params - */ -const databasesCreateRelationshipAttribute = async ({databaseId,collectionId,relatedCollectionId,type,twoWay,key,twoWayKey,onDelete,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesCreateRelationshipAttribute = async ({databaseId,collectionId,relatedCollectionId,type,twoWay,key,twoWayKey,onDelete,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesCreateRelationshipAttributeRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/relationship'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); @@ -1718,25 +1576,21 @@ const databasesCreateRelationshipAttribute = async ({databaseId,collectionId,rel return response; } -/** - * @typedef {Object} DatabasesCreateStringAttributeRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection). - * @property {string} key Attribute Key. - * @property {number} size Attribute size for text attributes, in number of characters. - * @property {boolean} required Is attribute required? - * @property {string} xdefault Default value for attribute when not provided. Cannot be set when attribute is required. - * @property {boolean} array Is attribute an array? - * @property {boolean} encrypt Toggle encryption for the attribute. Encryption enhances security by not storing any plain text values in the database. However, encrypted attributes cannot be queried. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesCreateStringAttributeRequestParams { + databaseId: string; + collectionId: string; + key: string; + size: number; + required: boolean; + xdefault?: string; + array?: boolean; + encrypt?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesCreateStringAttributeRequestParams} params - */ -const databasesCreateStringAttribute = async ({databaseId,collectionId,key,size,required,xdefault,array,encrypt,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesCreateStringAttribute = async ({databaseId,collectionId,key,size,required,xdefault,array,encrypt,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesCreateStringAttributeRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/string'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); @@ -1773,24 +1627,20 @@ const databasesCreateStringAttribute = async ({databaseId,collectionId,key,size, return response; } -/** - * @typedef {Object} DatabasesUpdateStringAttributeRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection). - * @property {string} key Attribute Key. - * @property {boolean} required Is attribute required? - * @property {string} xdefault Default value for attribute when not provided. Cannot be set when attribute is required. - * @property {number} size Maximum size of the string attribute. - * @property {string} newKey New Attribute Key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesUpdateStringAttributeRequestParams { + databaseId: string; + collectionId: string; + key: string; + required: boolean; + xdefault: string; + size?: number; + newKey?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesUpdateStringAttributeRequestParams} params - */ -const databasesUpdateStringAttribute = async ({databaseId,collectionId,key,required,xdefault,size,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesUpdateStringAttribute = async ({databaseId,collectionId,key,required,xdefault,size,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesUpdateStringAttributeRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/string/{key}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{key}', key); @@ -1821,23 +1671,19 @@ const databasesUpdateStringAttribute = async ({databaseId,collectionId,key,requi return response; } -/** - * @typedef {Object} DatabasesCreateUrlAttributeRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. - * @property {string} key Attribute Key. - * @property {boolean} required Is attribute required? - * @property {string} xdefault Default value for attribute when not provided. Cannot be set when attribute is required. - * @property {boolean} array Is attribute an array? - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesCreateUrlAttributeRequestParams { + databaseId: string; + collectionId: string; + key: string; + required: boolean; + xdefault?: string; + array?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesCreateUrlAttributeRequestParams} params - */ -const databasesCreateUrlAttribute = async ({databaseId,collectionId,key,required,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesCreateUrlAttribute = async ({databaseId,collectionId,key,required,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesCreateUrlAttributeRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/url'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); @@ -1868,23 +1714,19 @@ const databasesCreateUrlAttribute = async ({databaseId,collectionId,key,required return response; } -/** - * @typedef {Object} DatabasesUpdateUrlAttributeRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. - * @property {string} key Attribute Key. - * @property {boolean} required Is attribute required? - * @property {string} xdefault Default value for attribute when not provided. Cannot be set when attribute is required. - * @property {string} newKey New Attribute Key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesUpdateUrlAttributeRequestParams { + databaseId: string; + collectionId: string; + key: string; + required: boolean; + xdefault: string; + newKey?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesUpdateUrlAttributeRequestParams} params - */ -const databasesUpdateUrlAttribute = async ({databaseId,collectionId,key,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesUpdateUrlAttribute = async ({databaseId,collectionId,key,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesUpdateUrlAttributeRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/url/{key}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{key}', key); @@ -1912,20 +1754,16 @@ const databasesUpdateUrlAttribute = async ({databaseId,collectionId,key,required return response; } -/** - * @typedef {Object} DatabasesGetAttributeRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. - * @property {string} key Attribute Key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesGetAttributeRequestParams { + databaseId: string; + collectionId: string; + key: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesGetAttributeRequestParams} params - */ -const databasesGetAttribute = async ({databaseId,collectionId,key,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesGetAttribute = async ({databaseId,collectionId,key,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesGetAttributeRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/{key}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{key}', key); @@ -1943,20 +1781,16 @@ const databasesGetAttribute = async ({databaseId,collectionId,key,parseOutput = return response; } -/** - * @typedef {Object} DatabasesDeleteAttributeRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. - * @property {string} key Attribute Key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesDeleteAttributeRequestParams { + databaseId: string; + collectionId: string; + key: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesDeleteAttributeRequestParams} params - */ -const databasesDeleteAttribute = async ({databaseId,collectionId,key,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesDeleteAttribute = async ({databaseId,collectionId,key,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesDeleteAttributeRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/{key}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{key}', key); @@ -1975,22 +1809,18 @@ const databasesDeleteAttribute = async ({databaseId,collectionId,key,parseOutput return response; } -/** - * @typedef {Object} DatabasesUpdateRelationshipAttributeRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. - * @property {string} key Attribute Key. - * @property {RelationMutate} onDelete Constraints option - * @property {string} newKey New Attribute Key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesUpdateRelationshipAttributeRequestParams { + databaseId: string; + collectionId: string; + key: string; + onDelete?: RelationMutate; + newKey?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesUpdateRelationshipAttributeRequestParams} params - */ -const databasesUpdateRelationshipAttribute = async ({databaseId,collectionId,key,onDelete,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesUpdateRelationshipAttribute = async ({databaseId,collectionId,key,onDelete,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesUpdateRelationshipAttributeRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/{key}/relationship'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{key}', key); @@ -2015,22 +1845,19 @@ const databasesUpdateRelationshipAttribute = async ({databaseId,collectionId,key return response; } -/** - * @typedef {Object} DatabasesListDocumentsRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection). - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. - * @property {string} transactionId Transaction ID to read uncommitted changes within the transaction. - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesListDocumentsRequestParams { + databaseId: string; + collectionId: string; + queries?: string[]; + transactionId?: string; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {DatabasesListDocumentsRequestParams} params - */ -const databasesListDocuments = async ({databaseId,collectionId,queries,transactionId,total,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const databasesListDocuments = async ({databaseId,collectionId,queries,transactionId,total,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: DatabasesListDocumentsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); @@ -2051,7 +1878,7 @@ const databasesListDocuments = async ({databaseId,collectionId,queries,transacti }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('databases', 'listDocuments', databaseId, collectionId); } else { parse(response) @@ -2061,23 +1888,19 @@ const databasesListDocuments = async ({databaseId,collectionId,queries,transacti return response; } -/** - * @typedef {Object} DatabasesCreateDocumentRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection). Make sure to define attributes before creating documents. - * @property {string} documentId Document ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {object} data Document data as JSON object. - * @property {string[]} permissions An array of permissions strings. By default, only the current user is granted all permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - * @property {string} transactionId Transaction ID for staging the operation. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesCreateDocumentRequestParams { + databaseId: string; + collectionId: string; + documentId: string; + data: object; + permissions?: string[]; + transactionId?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesCreateDocumentRequestParams} params - */ -const databasesCreateDocument = async ({databaseId,collectionId,documentId,data,permissions,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesCreateDocument = async ({databaseId,collectionId,documentId,data,permissions,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesCreateDocumentRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); @@ -2109,21 +1932,17 @@ const databasesCreateDocument = async ({databaseId,collectionId,documentId,data, return response; } -/** - * @typedef {Object} DatabasesCreateDocumentsRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection). Make sure to define attributes before creating documents. - * @property {object[]} documents Array of documents data as JSON objects. - * @property {string} transactionId Transaction ID for staging the operation. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesCreateDocumentsRequestParams { + databaseId: string; + collectionId: string; + documents: object[]; + transactionId?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesCreateDocumentsRequestParams} params - */ -const databasesCreateDocuments = async ({databaseId,collectionId,documents,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesCreateDocuments = async ({databaseId,collectionId,documents,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesCreateDocumentsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); @@ -2149,21 +1968,17 @@ const databasesCreateDocuments = async ({databaseId,collectionId,documents,trans return response; } -/** - * @typedef {Object} DatabasesUpsertDocumentsRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. - * @property {object[]} documents Array of document data as JSON objects. May contain partial documents. - * @property {string} transactionId Transaction ID for staging the operation. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesUpsertDocumentsRequestParams { + databaseId: string; + collectionId: string; + documents: object[]; + transactionId?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesUpsertDocumentsRequestParams} params - */ -const databasesUpsertDocuments = async ({databaseId,collectionId,documents,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesUpsertDocuments = async ({databaseId,collectionId,documents,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesUpsertDocumentsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); @@ -2189,22 +2004,18 @@ const databasesUpsertDocuments = async ({databaseId,collectionId,documents,trans return response; } -/** - * @typedef {Object} DatabasesUpdateDocumentsRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. - * @property {object} data Document data as JSON object. Include only attribute and value pairs to be updated. - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. - * @property {string} transactionId Transaction ID for staging the operation. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesUpdateDocumentsRequestParams { + databaseId: string; + collectionId: string; + data?: object; + queries?: string[]; + transactionId?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesUpdateDocumentsRequestParams} params - */ -const databasesUpdateDocuments = async ({databaseId,collectionId,data,queries,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesUpdateDocuments = async ({databaseId,collectionId,data,queries,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesUpdateDocumentsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); @@ -2233,21 +2044,17 @@ const databasesUpdateDocuments = async ({databaseId,collectionId,data,queries,tr return response; } -/** - * @typedef {Object} DatabasesDeleteDocumentsRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection). - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. - * @property {string} transactionId Transaction ID for staging the operation. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesDeleteDocumentsRequestParams { + databaseId: string; + collectionId: string; + queries?: string[]; + transactionId?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesDeleteDocumentsRequestParams} params - */ -const databasesDeleteDocuments = async ({databaseId,collectionId,queries,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesDeleteDocuments = async ({databaseId,collectionId,queries,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesDeleteDocumentsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); @@ -2273,22 +2080,19 @@ const databasesDeleteDocuments = async ({databaseId,collectionId,queries,transac return response; } -/** - * @typedef {Object} DatabasesGetDocumentRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection). - * @property {string} documentId Document ID. - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. - * @property {string} transactionId Transaction ID to read uncommitted changes within the transaction. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesGetDocumentRequestParams { + databaseId: string; + collectionId: string; + documentId: string; + queries?: string[]; + transactionId?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {DatabasesGetDocumentRequestParams} params - */ -const databasesGetDocument = async ({databaseId,collectionId,documentId,queries,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const databasesGetDocument = async ({databaseId,collectionId,documentId,queries,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: DatabasesGetDocumentRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{documentId}', documentId); @@ -2306,7 +2110,7 @@ const databasesGetDocument = async ({databaseId,collectionId,documentId,queries, }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('databases', 'getDocument', databaseId, collectionId, documentId); } else { parse(response) @@ -2316,23 +2120,19 @@ const databasesGetDocument = async ({databaseId,collectionId,documentId,queries, return response; } -/** - * @typedef {Object} DatabasesUpsertDocumentRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. - * @property {string} documentId Document ID. - * @property {object} data Document data as JSON object. Include all required attributes of the document to be created or updated. - * @property {string[]} permissions An array of permissions strings. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions). - * @property {string} transactionId Transaction ID for staging the operation. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesUpsertDocumentRequestParams { + databaseId: string; + collectionId: string; + documentId: string; + data?: object; + permissions?: string[]; + transactionId?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesUpsertDocumentRequestParams} params - */ -const databasesUpsertDocument = async ({databaseId,collectionId,documentId,data,permissions,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesUpsertDocument = async ({databaseId,collectionId,documentId,data,permissions,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesUpsertDocumentRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{documentId}', documentId); @@ -2361,23 +2161,19 @@ const databasesUpsertDocument = async ({databaseId,collectionId,documentId,data, return response; } -/** - * @typedef {Object} DatabasesUpdateDocumentRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. - * @property {string} documentId Document ID. - * @property {object} data Document data as JSON object. Include only attribute and value pairs to be updated. - * @property {string[]} permissions An array of permissions strings. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions). - * @property {string} transactionId Transaction ID for staging the operation. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesUpdateDocumentRequestParams { + databaseId: string; + collectionId: string; + documentId: string; + data?: object; + permissions?: string[]; + transactionId?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesUpdateDocumentRequestParams} params - */ -const databasesUpdateDocument = async ({databaseId,collectionId,documentId,data,permissions,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesUpdateDocument = async ({databaseId,collectionId,documentId,data,permissions,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesUpdateDocumentRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{documentId}', documentId); @@ -2406,21 +2202,17 @@ const databasesUpdateDocument = async ({databaseId,collectionId,documentId,data, return response; } -/** - * @typedef {Object} DatabasesDeleteDocumentRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection). - * @property {string} documentId Document ID. - * @property {string} transactionId Transaction ID for staging the operation. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesDeleteDocumentRequestParams { + databaseId: string; + collectionId: string; + documentId: string; + transactionId?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesDeleteDocumentRequestParams} params - */ -const databasesDeleteDocument = async ({databaseId,collectionId,documentId,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesDeleteDocument = async ({databaseId,collectionId,documentId,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesDeleteDocumentRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{documentId}', documentId); @@ -2442,21 +2234,17 @@ const databasesDeleteDocument = async ({databaseId,collectionId,documentId,trans return response; } -/** - * @typedef {Object} DatabasesListDocumentLogsRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. - * @property {string} documentId Document ID. - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Only supported methods are limit and offset - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesListDocumentLogsRequestParams { + databaseId: string; + collectionId: string; + documentId: string; + queries?: string[]; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesListDocumentLogsRequestParams} params - */ -const databasesListDocumentLogs = async ({databaseId,collectionId,documentId,queries,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesListDocumentLogs = async ({databaseId,collectionId,documentId,queries,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesListDocumentLogsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/logs'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{documentId}', documentId); @@ -2477,24 +2265,20 @@ const databasesListDocumentLogs = async ({databaseId,collectionId,documentId,que return response; } -/** - * @typedef {Object} DatabasesDecrementDocumentAttributeRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. - * @property {string} documentId Document ID. - * @property {string} attribute Attribute key. - * @property {number} value Value to increment the attribute by. The value must be a number. - * @property {number} min Minimum value for the attribute. If the current value is lesser than this value, an exception will be thrown. - * @property {string} transactionId Transaction ID for staging the operation. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesDecrementDocumentAttributeRequestParams { + databaseId: string; + collectionId: string; + documentId: string; + attribute: string; + value?: number; + min?: number; + transactionId?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesDecrementDocumentAttributeRequestParams} params - */ -const databasesDecrementDocumentAttribute = async ({databaseId,collectionId,documentId,attribute,value,min,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesDecrementDocumentAttribute = async ({databaseId,collectionId,documentId,attribute,value,min,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesDecrementDocumentAttributeRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/decrement'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{documentId}', documentId).replace('{attribute}', attribute); @@ -2522,24 +2306,20 @@ const databasesDecrementDocumentAttribute = async ({databaseId,collectionId,docu return response; } -/** - * @typedef {Object} DatabasesIncrementDocumentAttributeRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. - * @property {string} documentId Document ID. - * @property {string} attribute Attribute key. - * @property {number} value Value to increment the attribute by. The value must be a number. - * @property {number} max Maximum value for the attribute. If the current value is greater than this value, an error will be thrown. - * @property {string} transactionId Transaction ID for staging the operation. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesIncrementDocumentAttributeRequestParams { + databaseId: string; + collectionId: string; + documentId: string; + attribute: string; + value?: number; + max?: number; + transactionId?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesIncrementDocumentAttributeRequestParams} params - */ -const databasesIncrementDocumentAttribute = async ({databaseId,collectionId,documentId,attribute,value,max,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesIncrementDocumentAttribute = async ({databaseId,collectionId,documentId,attribute,value,max,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesIncrementDocumentAttributeRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/increment'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{documentId}', documentId).replace('{attribute}', attribute); @@ -2567,21 +2347,18 @@ const databasesIncrementDocumentAttribute = async ({databaseId,collectionId,docu return response; } -/** - * @typedef {Object} DatabasesListIndexesRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection). - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: key, type, status, attributes, error - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesListIndexesRequestParams { + databaseId: string; + collectionId: string; + queries?: string[]; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {DatabasesListIndexesRequestParams} params - */ -const databasesListIndexes = async ({databaseId,collectionId,queries,total,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const databasesListIndexes = async ({databaseId,collectionId,queries,total,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: DatabasesListIndexesRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/indexes'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); @@ -2599,7 +2376,7 @@ const databasesListIndexes = async ({databaseId,collectionId,queries,total,parse }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('databases', 'listIndexes', databaseId, collectionId); } else { parse(response) @@ -2609,24 +2386,20 @@ const databasesListIndexes = async ({databaseId,collectionId,queries,total,parse return response; } -/** - * @typedef {Object} DatabasesCreateIndexRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection). - * @property {string} key Index Key. - * @property {IndexType} type Index type. - * @property {string[]} attributes Array of attributes to index. Maximum of 100 attributes are allowed, each 32 characters long. - * @property {string[]} orders Array of index orders. Maximum of 100 orders are allowed. - * @property {number[]} lengths Length of index. Maximum of 100 - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesCreateIndexRequestParams { + databaseId: string; + collectionId: string; + key: string; + type: IndexType; + attributes: string[]; + orders?: string[]; + lengths?: number[]; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesCreateIndexRequestParams} params - */ -const databasesCreateIndex = async ({databaseId,collectionId,key,type,attributes,orders,lengths,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesCreateIndex = async ({databaseId,collectionId,key,type,attributes,orders,lengths,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesCreateIndexRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/indexes'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); @@ -2663,20 +2436,16 @@ const databasesCreateIndex = async ({databaseId,collectionId,key,type,attributes return response; } -/** - * @typedef {Object} DatabasesGetIndexRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection). - * @property {string} key Index Key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesGetIndexRequestParams { + databaseId: string; + collectionId: string; + key: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesGetIndexRequestParams} params - */ -const databasesGetIndex = async ({databaseId,collectionId,key,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesGetIndex = async ({databaseId,collectionId,key,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesGetIndexRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/indexes/{key}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{key}', key); @@ -2694,20 +2463,16 @@ const databasesGetIndex = async ({databaseId,collectionId,key,parseOutput = true return response; } -/** - * @typedef {Object} DatabasesDeleteIndexRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection). - * @property {string} key Index Key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesDeleteIndexRequestParams { + databaseId: string; + collectionId: string; + key: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesDeleteIndexRequestParams} params - */ -const databasesDeleteIndex = async ({databaseId,collectionId,key,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesDeleteIndex = async ({databaseId,collectionId,key,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesDeleteIndexRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/indexes/{key}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{key}', key); @@ -2726,20 +2491,16 @@ const databasesDeleteIndex = async ({databaseId,collectionId,key,parseOutput = t return response; } -/** - * @typedef {Object} DatabasesListCollectionLogsRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Only supported methods are limit and offset - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesListCollectionLogsRequestParams { + databaseId: string; + collectionId: string; + queries?: string[]; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesListCollectionLogsRequestParams} params - */ -const databasesListCollectionLogs = async ({databaseId,collectionId,queries,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesListCollectionLogs = async ({databaseId,collectionId,queries,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesListCollectionLogsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/logs'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); @@ -2760,20 +2521,16 @@ const databasesListCollectionLogs = async ({databaseId,collectionId,queries,pars return response; } -/** - * @typedef {Object} DatabasesGetCollectionUsageRequestParams - * @property {string} databaseId Database ID. - * @property {string} collectionId Collection ID. - * @property {UsageRange} range Date range. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesGetCollectionUsageRequestParams { + databaseId: string; + collectionId: string; + range?: UsageRange; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesGetCollectionUsageRequestParams} params - */ -const databasesGetCollectionUsage = async ({databaseId,collectionId,range,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesGetCollectionUsage = async ({databaseId,collectionId,range,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesGetCollectionUsageRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/usage'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); @@ -2794,19 +2551,15 @@ const databasesGetCollectionUsage = async ({databaseId,collectionId,range,parseO return response; } -/** - * @typedef {Object} DatabasesListLogsRequestParams - * @property {string} databaseId Database ID. - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Only supported methods are limit and offset - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesListLogsRequestParams { + databaseId: string; + queries?: string[]; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesListLogsRequestParams} params - */ -const databasesListLogs = async ({databaseId,queries,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesListLogs = async ({databaseId,queries,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesListLogsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/logs'.replace('{databaseId}', databaseId); @@ -2827,19 +2580,15 @@ const databasesListLogs = async ({databaseId,queries,parseOutput = true, overrid return response; } -/** - * @typedef {Object} DatabasesGetUsageRequestParams - * @property {string} databaseId Database ID. - * @property {UsageRange} range Date range. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface DatabasesGetUsageRequestParams { + databaseId: string; + range?: UsageRange; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {DatabasesGetUsageRequestParams} params - */ -const databasesGetUsage = async ({databaseId,range,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const databasesGetUsage = async ({databaseId,range,parseOutput = true, overrideForCli = false, sdk = undefined}: DatabasesGetUsageRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/databases/{databaseId}/usage'.replace('{databaseId}', databaseId); @@ -2865,7 +2614,7 @@ databases .description(`[**DEPRECATED** - This command is deprecated. Please use 'tables-db list' instead] Get a list of all databases from the current Appwrite project. You can use the search parameter to filter your results.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name`) .option(`--search `, `Search term to filter your list results. Max length: 256 chars.`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--console`, `Get the resource console url`) .action(actionRunner(databasesList)) @@ -2874,7 +2623,7 @@ databases .description(`[**DEPRECATED** - This command is deprecated. Please use 'tables-db create' instead] Create a new Database. `) .requiredOption(`--database-id `, `Unique Id. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars.`) .requiredOption(`--name `, `Database name. Max length: 128 chars.`) - .option(`--enabled [value]`, `Is the database enabled? When set to 'disabled', users cannot access the database but Server SDKs with an API key can still read and write to the database. No data is lost when this is toggled.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Is the database enabled? When set to 'disabled', users cannot access the database but Server SDKs with an API key can still read and write to the database. No data is lost when this is toggled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(databasesCreate)) databases @@ -2901,8 +2650,8 @@ databases .command(`update-transaction`) .description(`Update a transaction, to either commit or roll back its operations.`) .requiredOption(`--transaction-id `, `Transaction ID.`) - .option(`--commit [value]`, `Commit transaction?`, (value) => value === undefined ? true : parseBool(value)) - .option(`--rollback [value]`, `Rollback transaction?`, (value) => value === undefined ? true : parseBool(value)) + .option(`--commit [value]`, `Commit transaction?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--rollback [value]`, `Rollback transaction?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(databasesUpdateTransaction)) databases @@ -2937,7 +2686,7 @@ databases .description(`[**DEPRECATED** - This command is deprecated. Please use 'tables-db update' instead] Update a database by its unique ID.`) .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--name `, `Database name. Max length: 128 chars.`) - .option(`--enabled [value]`, `Is database enabled? When set to 'disabled', users cannot access the database but Server SDKs with an API key can still read and write to the database. No data is lost when this is toggled.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Is database enabled? When set to 'disabled', users cannot access the database but Server SDKs with an API key can still read and write to the database. No data is lost when this is toggled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(databasesUpdate)) databases @@ -2952,7 +2701,7 @@ databases .requiredOption(`--database-id `, `Database ID.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name, enabled, documentSecurity`) .option(`--search `, `Search term to filter your list results. Max length: 256 chars.`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--console`, `Get the resource console url`) .action(actionRunner(databasesListCollections)) @@ -2963,8 +2712,10 @@ databases .requiredOption(`--collection-id `, `Unique Id. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars.`) .requiredOption(`--name `, `Collection name. Max length: 128 chars.`) .option(`--permissions [permissions...]`, `An array of permissions strings. By default, no user is granted with any permissions. [Learn more about permissions](https://appwrite.io/docs/permissions).`) - .option(`--document-security [value]`, `Enables configuring permissions for individual documents. A user needs one of document or collection level permissions to access a document. [Learn more about permissions](https://appwrite.io/docs/permissions).`, (value) => value === undefined ? true : parseBool(value)) - .option(`--enabled [value]`, `Is collection enabled? When set to 'disabled', users cannot access the collection but Server SDKs with and API key can still read and write to the collection. No data is lost when this is toggled.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--document-security [value]`, `Enables configuring permissions for individual documents. A user needs one of document or collection level permissions to access a document. [Learn more about permissions](https://appwrite.io/docs/permissions).`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Is collection enabled? When set to 'disabled', users cannot access the collection but Server SDKs with and API key can still read and write to the collection. No data is lost when this is toggled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--attributes [attributes...]`, `Array of attribute definitions to create. Each attribute should contain: key (string), type (string: string, integer, float, boolean, datetime), size (integer, required for string type), required (boolean, optional), default (mixed, optional), array (boolean, optional), and type-specific options.`) + .option(`--indexes [indexes...]`, `Array of index definitions to create. Each index should contain: key (string), type (string: key, fulltext, unique, spatial), attributes (array of attribute keys), orders (array of ASC/DESC, optional), and lengths (array of integers, optional).`) .action(actionRunner(databasesCreateCollection)) databases @@ -2982,8 +2733,8 @@ databases .requiredOption(`--collection-id `, `Collection ID.`) .requiredOption(`--name `, `Collection name. Max length: 128 chars.`) .option(`--permissions [permissions...]`, `An array of permission strings. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions).`) - .option(`--document-security [value]`, `Enables configuring permissions for individual documents. A user needs one of document or collection level permissions to access a document. [Learn more about permissions](https://appwrite.io/docs/permissions).`, (value) => value === undefined ? true : parseBool(value)) - .option(`--enabled [value]`, `Is collection enabled? When set to 'disabled', users cannot access the collection but Server SDKs with and API key can still read and write to the collection. No data is lost when this is toggled.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--document-security [value]`, `Enables configuring permissions for individual documents. A user needs one of document or collection level permissions to access a document. [Learn more about permissions](https://appwrite.io/docs/permissions).`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Is collection enabled? When set to 'disabled', users cannot access the collection but Server SDKs with and API key can still read and write to the collection. No data is lost when this is toggled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(databasesUpdateCollection)) databases @@ -2999,7 +2750,7 @@ databases .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--collection-id `, `Collection ID.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: key, type, size, required, array, status, error`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--console`, `Get the resource console url`) .action(actionRunner(databasesListAttributes)) @@ -3009,9 +2760,9 @@ databases .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--collection-id `, `Collection ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection).`) .requiredOption(`--key `, `Attribute Key.`) - .requiredOption(`--required [value]`, `Is attribute required?`, (value) => value === undefined ? true : parseBool(value)) - .option(`--xdefault [value]`, `Default value for attribute when not provided. Cannot be set when attribute is required.`, (value) => value === undefined ? true : parseBool(value)) - .option(`--array [value]`, `Is attribute an array?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is attribute required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--xdefault [value]`, `Default value for attribute when not provided. Cannot be set when attribute is required.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--array [value]`, `Is attribute an array?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(databasesCreateBooleanAttribute)) databases @@ -3020,8 +2771,8 @@ databases .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--collection-id `, `Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#createCollection).`) .requiredOption(`--key `, `Attribute Key.`) - .requiredOption(`--required [value]`, `Is attribute required?`, (value) => value === undefined ? true : parseBool(value)) - .option(`--xdefault [value]`, `Default value for attribute when not provided. Cannot be set when attribute is required.`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is attribute required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--xdefault [value]`, `Default value for attribute when not provided. Cannot be set when attribute is required.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--new-key `, `New attribute key.`) .action(actionRunner(databasesUpdateBooleanAttribute)) @@ -3031,9 +2782,9 @@ databases .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--collection-id `, `Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#createCollection).`) .requiredOption(`--key `, `Attribute Key.`) - .requiredOption(`--required [value]`, `Is attribute required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is attribute required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value for the attribute in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. Cannot be set when attribute is required.`) - .option(`--array [value]`, `Is attribute an array?`, (value) => value === undefined ? true : parseBool(value)) + .option(`--array [value]`, `Is attribute an array?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(databasesCreateDatetimeAttribute)) databases @@ -3042,7 +2793,7 @@ databases .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--collection-id `, `Collection ID.`) .requiredOption(`--key `, `Attribute Key.`) - .requiredOption(`--required [value]`, `Is attribute required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is attribute required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value for attribute when not provided. Cannot be set when attribute is required.`) .option(`--new-key `, `New attribute key.`) .action(actionRunner(databasesUpdateDatetimeAttribute)) @@ -3053,9 +2804,9 @@ databases .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--collection-id `, `Collection ID.`) .requiredOption(`--key `, `Attribute Key.`) - .requiredOption(`--required [value]`, `Is attribute required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is attribute required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value for attribute when not provided. Cannot be set when attribute is required.`) - .option(`--array [value]`, `Is attribute an array?`, (value) => value === undefined ? true : parseBool(value)) + .option(`--array [value]`, `Is attribute an array?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(databasesCreateEmailAttribute)) databases @@ -3064,7 +2815,7 @@ databases .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--collection-id `, `Collection ID.`) .requiredOption(`--key `, `Attribute Key.`) - .requiredOption(`--required [value]`, `Is attribute required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is attribute required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value for attribute when not provided. Cannot be set when attribute is required.`) .option(`--new-key `, `New Attribute Key.`) .action(actionRunner(databasesUpdateEmailAttribute)) @@ -3076,9 +2827,9 @@ databases .requiredOption(`--collection-id `, `Collection ID.`) .requiredOption(`--key `, `Attribute Key.`) .requiredOption(`--elements [elements...]`, `Array of enum values.`) - .requiredOption(`--required [value]`, `Is attribute required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is attribute required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value for attribute when not provided. Cannot be set when attribute is required.`) - .option(`--array [value]`, `Is attribute an array?`, (value) => value === undefined ? true : parseBool(value)) + .option(`--array [value]`, `Is attribute an array?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(databasesCreateEnumAttribute)) databases @@ -3088,7 +2839,7 @@ databases .requiredOption(`--collection-id `, `Collection ID.`) .requiredOption(`--key `, `Attribute Key.`) .requiredOption(`--elements [elements...]`, `Updated list of enum values.`) - .requiredOption(`--required [value]`, `Is attribute required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is attribute required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value for attribute when not provided. Cannot be set when attribute is required.`) .option(`--new-key `, `New Attribute Key.`) .action(actionRunner(databasesUpdateEnumAttribute)) @@ -3099,11 +2850,11 @@ databases .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--collection-id `, `Collection ID.`) .requiredOption(`--key `, `Attribute Key.`) - .requiredOption(`--required [value]`, `Is attribute required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is attribute required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--min `, `Minimum value.`, parseInteger) .option(`--max `, `Maximum value.`, parseInteger) .option(`--xdefault `, `Default value. Cannot be set when required.`, parseInteger) - .option(`--array [value]`, `Is attribute an array?`, (value) => value === undefined ? true : parseBool(value)) + .option(`--array [value]`, `Is attribute an array?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(databasesCreateFloatAttribute)) databases @@ -3112,7 +2863,7 @@ databases .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--collection-id `, `Collection ID.`) .requiredOption(`--key `, `Attribute Key.`) - .requiredOption(`--required [value]`, `Is attribute required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is attribute required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value. Cannot be set when required.`, parseInteger) .option(`--min `, `Minimum value.`, parseInteger) .option(`--max `, `Maximum value.`, parseInteger) @@ -3125,11 +2876,11 @@ databases .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--collection-id `, `Collection ID.`) .requiredOption(`--key `, `Attribute Key.`) - .requiredOption(`--required [value]`, `Is attribute required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is attribute required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--min `, `Minimum value`, parseInteger) .option(`--max `, `Maximum value`, parseInteger) .option(`--xdefault `, `Default value. Cannot be set when attribute is required.`, parseInteger) - .option(`--array [value]`, `Is attribute an array?`, (value) => value === undefined ? true : parseBool(value)) + .option(`--array [value]`, `Is attribute an array?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(databasesCreateIntegerAttribute)) databases @@ -3138,7 +2889,7 @@ databases .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--collection-id `, `Collection ID.`) .requiredOption(`--key `, `Attribute Key.`) - .requiredOption(`--required [value]`, `Is attribute required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is attribute required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value. Cannot be set when attribute is required.`, parseInteger) .option(`--min `, `Minimum value`, parseInteger) .option(`--max `, `Maximum value`, parseInteger) @@ -3151,9 +2902,9 @@ databases .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--collection-id `, `Collection ID.`) .requiredOption(`--key `, `Attribute Key.`) - .requiredOption(`--required [value]`, `Is attribute required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is attribute required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value. Cannot be set when attribute is required.`) - .option(`--array [value]`, `Is attribute an array?`, (value) => value === undefined ? true : parseBool(value)) + .option(`--array [value]`, `Is attribute an array?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(databasesCreateIpAttribute)) databases @@ -3162,7 +2913,7 @@ databases .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--collection-id `, `Collection ID.`) .requiredOption(`--key `, `Attribute Key.`) - .requiredOption(`--required [value]`, `Is attribute required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is attribute required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value. Cannot be set when attribute is required.`) .option(`--new-key `, `New Attribute Key.`) .action(actionRunner(databasesUpdateIpAttribute)) @@ -3173,7 +2924,7 @@ databases .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--collection-id `, `Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection).`) .requiredOption(`--key `, `Attribute Key.`) - .requiredOption(`--required [value]`, `Is attribute required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is attribute required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value for attribute when not provided, two-dimensional array of coordinate pairs, [[longitude, latitude], [longitude, latitude], …], listing the vertices of the line in order. Cannot be set when attribute is required.`) .action(actionRunner(databasesCreateLineAttribute)) @@ -3183,7 +2934,7 @@ databases .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--collection-id `, `Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#createCollection).`) .requiredOption(`--key `, `Attribute Key.`) - .requiredOption(`--required [value]`, `Is attribute required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is attribute required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value for attribute when not provided, two-dimensional array of coordinate pairs, [[longitude, latitude], [longitude, latitude], …], listing the vertices of the line in order. Cannot be set when attribute is required.`) .option(`--new-key `, `New attribute key.`) .action(actionRunner(databasesUpdateLineAttribute)) @@ -3194,7 +2945,7 @@ databases .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--collection-id `, `Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection).`) .requiredOption(`--key `, `Attribute Key.`) - .requiredOption(`--required [value]`, `Is attribute required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is attribute required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value for attribute when not provided, array of two numbers [longitude, latitude], representing a single coordinate. Cannot be set when attribute is required.`) .action(actionRunner(databasesCreatePointAttribute)) @@ -3204,7 +2955,7 @@ databases .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--collection-id `, `Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#createCollection).`) .requiredOption(`--key `, `Attribute Key.`) - .requiredOption(`--required [value]`, `Is attribute required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is attribute required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value for attribute when not provided, array of two numbers [longitude, latitude], representing a single coordinate. Cannot be set when attribute is required.`) .option(`--new-key `, `New attribute key.`) .action(actionRunner(databasesUpdatePointAttribute)) @@ -3215,7 +2966,7 @@ databases .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--collection-id `, `Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection).`) .requiredOption(`--key `, `Attribute Key.`) - .requiredOption(`--required [value]`, `Is attribute required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is attribute required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value for attribute when not provided, three-dimensional array where the outer array holds one or more linear rings, [[[longitude, latitude], …], …], the first ring is the exterior boundary, any additional rings are interior holes, and each ring must start and end with the same coordinate pair. Cannot be set when attribute is required.`) .action(actionRunner(databasesCreatePolygonAttribute)) @@ -3225,7 +2976,7 @@ databases .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--collection-id `, `Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#createCollection).`) .requiredOption(`--key `, `Attribute Key.`) - .requiredOption(`--required [value]`, `Is attribute required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is attribute required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value for attribute when not provided, three-dimensional array where the outer array holds one or more linear rings, [[[longitude, latitude], …], …], the first ring is the exterior boundary, any additional rings are interior holes, and each ring must start and end with the same coordinate pair. Cannot be set when attribute is required.`) .option(`--new-key `, `New attribute key.`) .action(actionRunner(databasesUpdatePolygonAttribute)) @@ -3237,7 +2988,7 @@ databases .requiredOption(`--collection-id `, `Collection ID.`) .requiredOption(`--related-collection-id `, `Related Collection ID.`) .requiredOption(`--type `, `Relation type`) - .option(`--two-way [value]`, `Is Two Way?`, (value) => value === undefined ? true : parseBool(value)) + .option(`--two-way [value]`, `Is Two Way?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--key `, `Attribute Key.`) .option(`--two-way-key `, `Two Way Attribute Key.`) .option(`--on-delete `, `Constraints option`) @@ -3250,10 +3001,10 @@ databases .requiredOption(`--collection-id `, `Collection ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection).`) .requiredOption(`--key `, `Attribute Key.`) .requiredOption(`--size `, `Attribute size for text attributes, in number of characters.`, parseInteger) - .requiredOption(`--required [value]`, `Is attribute required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is attribute required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value for attribute when not provided. Cannot be set when attribute is required.`) - .option(`--array [value]`, `Is attribute an array?`, (value) => value === undefined ? true : parseBool(value)) - .option(`--encrypt [value]`, `Toggle encryption for the attribute. Encryption enhances security by not storing any plain text values in the database. However, encrypted attributes cannot be queried.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--array [value]`, `Is attribute an array?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--encrypt [value]`, `Toggle encryption for the attribute. Encryption enhances security by not storing any plain text values in the database. However, encrypted attributes cannot be queried.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(databasesCreateStringAttribute)) databases @@ -3262,7 +3013,7 @@ databases .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--collection-id `, `Collection ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection).`) .requiredOption(`--key `, `Attribute Key.`) - .requiredOption(`--required [value]`, `Is attribute required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is attribute required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value for attribute when not provided. Cannot be set when attribute is required.`) .option(`--size `, `Maximum size of the string attribute.`, parseInteger) .option(`--new-key `, `New Attribute Key.`) @@ -3274,9 +3025,9 @@ databases .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--collection-id `, `Collection ID.`) .requiredOption(`--key `, `Attribute Key.`) - .requiredOption(`--required [value]`, `Is attribute required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is attribute required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value for attribute when not provided. Cannot be set when attribute is required.`) - .option(`--array [value]`, `Is attribute an array?`, (value) => value === undefined ? true : parseBool(value)) + .option(`--array [value]`, `Is attribute an array?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(databasesCreateUrlAttribute)) databases @@ -3285,7 +3036,7 @@ databases .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--collection-id `, `Collection ID.`) .requiredOption(`--key `, `Attribute Key.`) - .requiredOption(`--required [value]`, `Is attribute required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is attribute required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value for attribute when not provided. Cannot be set when attribute is required.`) .option(`--new-key `, `New Attribute Key.`) .action(actionRunner(databasesUpdateUrlAttribute)) @@ -3323,7 +3074,7 @@ databases .requiredOption(`--collection-id `, `Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection).`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long.`) .option(`--transaction-id `, `Transaction ID to read uncommitted changes within the transaction.`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--console`, `Get the resource console url`) .action(actionRunner(databasesListDocuments)) @@ -3392,7 +3143,7 @@ databases .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--collection-id `, `Collection ID.`) .requiredOption(`--document-id `, `Document ID.`) - .requiredOption(`--data `, `Document data as JSON object. Include all required attributes of the document to be created or updated.`) + .option(`--data `, `Document data as JSON object. Include all required attributes of the document to be created or updated.`) .option(`--permissions [permissions...]`, `An array of permissions strings. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions).`) .option(`--transaction-id `, `Transaction ID for staging the operation.`) .action(actionRunner(databasesUpsertDocument)) @@ -3456,7 +3207,7 @@ databases .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--collection-id `, `Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection).`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: key, type, status, attributes, error`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--console`, `Get the resource console url`) .action(actionRunner(databasesListIndexes)) @@ -3518,73 +3269,4 @@ databases .option(`--range `, `Date range.`) .action(actionRunner(databasesGetUsage)) -module.exports = { - databases, - databasesList, - databasesCreate, - databasesListTransactions, - databasesCreateTransaction, - databasesGetTransaction, - databasesUpdateTransaction, - databasesDeleteTransaction, - databasesCreateOperations, - databasesListUsage, - databasesGet, - databasesUpdate, - databasesDelete, - databasesListCollections, - databasesCreateCollection, - databasesGetCollection, - databasesUpdateCollection, - databasesDeleteCollection, - databasesListAttributes, - databasesCreateBooleanAttribute, - databasesUpdateBooleanAttribute, - databasesCreateDatetimeAttribute, - databasesUpdateDatetimeAttribute, - databasesCreateEmailAttribute, - databasesUpdateEmailAttribute, - databasesCreateEnumAttribute, - databasesUpdateEnumAttribute, - databasesCreateFloatAttribute, - databasesUpdateFloatAttribute, - databasesCreateIntegerAttribute, - databasesUpdateIntegerAttribute, - databasesCreateIpAttribute, - databasesUpdateIpAttribute, - databasesCreateLineAttribute, - databasesUpdateLineAttribute, - databasesCreatePointAttribute, - databasesUpdatePointAttribute, - databasesCreatePolygonAttribute, - databasesUpdatePolygonAttribute, - databasesCreateRelationshipAttribute, - databasesCreateStringAttribute, - databasesUpdateStringAttribute, - databasesCreateUrlAttribute, - databasesUpdateUrlAttribute, - databasesGetAttribute, - databasesDeleteAttribute, - databasesUpdateRelationshipAttribute, - databasesListDocuments, - databasesCreateDocument, - databasesCreateDocuments, - databasesUpsertDocuments, - databasesUpdateDocuments, - databasesDeleteDocuments, - databasesGetDocument, - databasesUpsertDocument, - databasesUpdateDocument, - databasesDeleteDocument, - databasesListDocumentLogs, - databasesDecrementDocumentAttribute, - databasesIncrementDocumentAttribute, - databasesListIndexes, - databasesCreateIndex, - databasesGetIndex, - databasesDeleteIndex, - databasesListCollectionLogs, - databasesGetCollectionUsage, - databasesListLogs, - databasesGetUsage -}; + diff --git a/lib/commands/functions.js b/lib/commands/functions.ts similarity index 63% rename from lib/commands/functions.js rename to lib/commands/functions.ts index 9e41c110..e592c00b 100644 --- a/lib/commands/functions.js +++ b/lib/commands/functions.ts @@ -1,31 +1,27 @@ -const fs = require('fs'); -const pathLib = require('path'); -const tar = require("tar"); -const ignore = require("ignore"); -const { promisify } = require('util'); -const libClient = require('../client.js'); -const { getAllFiles, showConsoleLink } = require('../utils.js'); -const { Command } = require('commander'); -const { sdkForProject, sdkForConsole } = require('../sdks') -const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } = require('../parser') -const { localConfig, globalConfig } = require("../config"); -const { File } = require('undici'); -const { ReadableStream } = require('stream/web'); - -/** - * @param {fs.ReadStream} readStream - * @returns {ReadableStream} - */ -function convertReadStreamToReadableStream(readStream) { +import fs = require('fs'); +import pathLib = require('path'); +import tar = require('tar'); +import ignore = require('ignore'); +import { promisify } from 'util'; +import Client from '../client'; +import { getAllFiles, showConsoleLink } from '../utils'; +import { Command } from 'commander'; +import { sdkForProject, sdkForConsole } from '../sdks'; +import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } from '../parser'; +import { localConfig, globalConfig } from '../config'; +import { File } from 'undici'; +import { ReadableStream } from 'stream/web'; + +function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ start(controller) { - readStream.on("data", (chunk) => { + readStream.on("data", (chunk: Buffer) => { controller.enqueue(chunk); }); readStream.on("end", () => { controller.close(); }); - readStream.on("error", (err) => { + readStream.on("error", (err: Error) => { controller.error(err); }); }, @@ -35,24 +31,21 @@ function convertReadStreamToReadableStream(readStream) { }); } -const functions = new Command("functions").description(commandDescriptions['functions'] ?? '').configureHelp({ +export const functions = new Command("functions").description(commandDescriptions['functions'] ?? '').configureHelp({ helpWidth: process.stdout.columns || 80 }) -/** - * @typedef {Object} FunctionsListRequestParams - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name, enabled, runtime, deploymentId, schedule, scheduleNext, schedulePrevious, timeout, entrypoint, commands, installationId - * @property {string} search Search term to filter your list results. Max length: 256 chars. - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {FunctionsListRequestParams} params - */ -const functionsList = async ({queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface FunctionsListRequestParams { + queries?: string[]; + search?: string; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const functionsList = async ({queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: FunctionsListRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/functions'; @@ -73,7 +66,7 @@ const functionsList = async ({queries,search,total,parseOutput = true, overrideF }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('functions', 'list'); } else { parse(response) @@ -83,35 +76,31 @@ const functionsList = async ({queries,search,total,parseOutput = true, overrideF return response; } -/** - * @typedef {Object} FunctionsCreateRequestParams - * @property {string} functionId Function ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} name Function name. Max length: 128 chars. - * @property {Runtime} runtime Execution runtime. - * @property {string[]} execute An array of role strings with execution permissions. By default no user is granted with any execute permissions. [learn more about roles](https://appwrite.io/docs/permissions#permission-roles). Maximum of 100 roles are allowed, each 64 characters long. - * @property {string[]} events Events list. Maximum of 100 events are allowed. - * @property {string} schedule Schedule CRON syntax. - * @property {number} timeout Function maximum execution time in seconds. - * @property {boolean} enabled Is function enabled? When set to 'disabled', users cannot access the function but Server SDKs with and API key can still access the function. No data is lost when this is toggled. - * @property {boolean} logging When disabled, executions will exclude logs and errors, and will be slightly faster. - * @property {string} entrypoint Entrypoint File. This path is relative to the "providerRootDirectory". - * @property {string} commands Build Commands. - * @property {string[]} scopes List of scopes allowed for API key auto-generated for every execution. Maximum of 100 scopes are allowed. - * @property {string} installationId Appwrite Installation ID for VCS (Version Control System) deployment. - * @property {string} providerRepositoryId Repository ID of the repo linked to the function. - * @property {string} providerBranch Production branch for the repo linked to the function. - * @property {boolean} providerSilentMode Is the VCS (Version Control System) connection in silent mode for the repo linked to the function? In silent mode, comments will not be made on commits and pull requests. - * @property {string} providerRootDirectory Path to function code in the linked repo. - * @property {string} specification Runtime specification for the function and builds. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {FunctionsCreateRequestParams} params - */ -const functionsCreate = async ({functionId,name,runtime,execute,events,schedule,timeout,enabled,logging,entrypoint,commands,scopes,installationId,providerRepositoryId,providerBranch,providerSilentMode,providerRootDirectory,specification,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface FunctionsCreateRequestParams { + functionId: string; + name: string; + runtime: Runtime; + execute?: string[]; + events?: string[]; + schedule?: string; + timeout?: number; + enabled?: boolean; + logging?: boolean; + entrypoint?: string; + commands?: string; + scopes?: string[]; + installationId?: string; + providerRepositoryId?: string; + providerBranch?: string; + providerSilentMode?: boolean; + providerRootDirectory?: string; + specification?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const functionsCreate = async ({functionId,name,runtime,execute,events,schedule,timeout,enabled,logging,entrypoint,commands,scopes,installationId,providerRepositoryId,providerBranch,providerSilentMode,providerRootDirectory,specification,parseOutput = true, overrideForCli = false, sdk = undefined}: FunctionsCreateRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/functions'; @@ -187,17 +176,13 @@ const functionsCreate = async ({functionId,name,runtime,execute,events,schedule, return response; } -/** - * @typedef {Object} FunctionsListRuntimesRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {FunctionsListRuntimesRequestParams} params - */ -const functionsListRuntimes = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface FunctionsListRuntimesRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const functionsListRuntimes = async ({parseOutput = true, overrideForCli = false, sdk = undefined}: FunctionsListRuntimesRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/functions/runtimes'; @@ -215,17 +200,14 @@ const functionsListRuntimes = async ({parseOutput = true, overrideForCli = false return response; } -/** - * @typedef {Object} FunctionsListSpecificationsRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {FunctionsListSpecificationsRequestParams} params - */ -const functionsListSpecifications = async ({parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface FunctionsListSpecificationsRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const functionsListSpecifications = async ({parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: FunctionsListSpecificationsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/functions/specifications'; @@ -237,7 +219,7 @@ const functionsListSpecifications = async ({parseOutput = true, overrideForCli = }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('functions', 'listSpecifications'); } else { parse(response) @@ -247,22 +229,19 @@ const functionsListSpecifications = async ({parseOutput = true, overrideForCli = return response; } -/** - * @typedef {Object} FunctionsListTemplatesRequestParams - * @property {string[]} runtimes List of runtimes allowed for filtering function templates. Maximum of 100 runtimes are allowed. - * @property {string[]} useCases List of use cases allowed for filtering function templates. Maximum of 100 use cases are allowed. - * @property {number} limit Limit the number of templates returned in the response. Default limit is 25, and maximum limit is 5000. - * @property {number} offset Offset the list of returned templates. Maximum offset is 5000. - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {FunctionsListTemplatesRequestParams} params - */ -const functionsListTemplates = async ({runtimes,useCases,limit,offset,total,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface FunctionsListTemplatesRequestParams { + runtimes?: string[]; + useCases?: string[]; + limit?: number; + offset?: number; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const functionsListTemplates = async ({runtimes,useCases,limit,offset,total,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: FunctionsListTemplatesRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/functions/templates'; @@ -289,7 +268,7 @@ const functionsListTemplates = async ({runtimes,useCases,limit,offset,total,pars }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('functions', 'listTemplates'); } else { parse(response) @@ -299,18 +278,15 @@ const functionsListTemplates = async ({runtimes,useCases,limit,offset,total,pars return response; } -/** - * @typedef {Object} FunctionsGetTemplateRequestParams - * @property {string} templateId Template ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {FunctionsGetTemplateRequestParams} params - */ -const functionsGetTemplate = async ({templateId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface FunctionsGetTemplateRequestParams { + templateId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const functionsGetTemplate = async ({templateId,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: FunctionsGetTemplateRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/functions/templates/{templateId}'.replace('{templateId}', templateId); @@ -322,7 +298,7 @@ const functionsGetTemplate = async ({templateId,parseOutput = true, overrideForC }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('functions', 'getTemplate', templateId); } else { parse(response) @@ -332,18 +308,15 @@ const functionsGetTemplate = async ({templateId,parseOutput = true, overrideForC return response; } -/** - * @typedef {Object} FunctionsListUsageRequestParams - * @property {UsageRange} range Date range. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {FunctionsListUsageRequestParams} params - */ -const functionsListUsage = async ({range,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface FunctionsListUsageRequestParams { + range?: UsageRange; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const functionsListUsage = async ({range,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: FunctionsListUsageRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/functions/usage'; @@ -358,7 +331,7 @@ const functionsListUsage = async ({range,parseOutput = true, overrideForCli = fa }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('functions', 'listUsage'); } else { parse(response) @@ -368,18 +341,15 @@ const functionsListUsage = async ({range,parseOutput = true, overrideForCli = fa return response; } -/** - * @typedef {Object} FunctionsGetRequestParams - * @property {string} functionId Function ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {FunctionsGetRequestParams} params - */ -const functionsGet = async ({functionId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface FunctionsGetRequestParams { + functionId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const functionsGet = async ({functionId,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: FunctionsGetRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/functions/{functionId}'.replace('{functionId}', functionId); @@ -391,7 +361,7 @@ const functionsGet = async ({functionId,parseOutput = true, overrideForCli = fal }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('functions', 'get', functionId); } else { parse(response) @@ -401,35 +371,31 @@ const functionsGet = async ({functionId,parseOutput = true, overrideForCli = fal return response; } -/** - * @typedef {Object} FunctionsUpdateRequestParams - * @property {string} functionId Function ID. - * @property {string} name Function name. Max length: 128 chars. - * @property {Runtime} runtime Execution runtime. - * @property {string[]} execute An array of role strings with execution permissions. By default no user is granted with any execute permissions. [learn more about roles](https://appwrite.io/docs/permissions#permission-roles). Maximum of 100 roles are allowed, each 64 characters long. - * @property {string[]} events Events list. Maximum of 100 events are allowed. - * @property {string} schedule Schedule CRON syntax. - * @property {number} timeout Maximum execution time in seconds. - * @property {boolean} enabled Is function enabled? When set to 'disabled', users cannot access the function but Server SDKs with and API key can still access the function. No data is lost when this is toggled. - * @property {boolean} logging When disabled, executions will exclude logs and errors, and will be slightly faster. - * @property {string} entrypoint Entrypoint File. This path is relative to the "providerRootDirectory". - * @property {string} commands Build Commands. - * @property {string[]} scopes List of scopes allowed for API Key auto-generated for every execution. Maximum of 100 scopes are allowed. - * @property {string} installationId Appwrite Installation ID for VCS (Version Controle System) deployment. - * @property {string} providerRepositoryId Repository ID of the repo linked to the function - * @property {string} providerBranch Production branch for the repo linked to the function - * @property {boolean} providerSilentMode Is the VCS (Version Control System) connection in silent mode for the repo linked to the function? In silent mode, comments will not be made on commits and pull requests. - * @property {string} providerRootDirectory Path to function code in the linked repo. - * @property {string} specification Runtime specification for the function and builds. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {FunctionsUpdateRequestParams} params - */ -const functionsUpdate = async ({functionId,name,runtime,execute,events,schedule,timeout,enabled,logging,entrypoint,commands,scopes,installationId,providerRepositoryId,providerBranch,providerSilentMode,providerRootDirectory,specification,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface FunctionsUpdateRequestParams { + functionId: string; + name: string; + runtime?: Runtime; + execute?: string[]; + events?: string[]; + schedule?: string; + timeout?: number; + enabled?: boolean; + logging?: boolean; + entrypoint?: string; + commands?: string; + scopes?: string[]; + installationId?: string; + providerRepositoryId?: string; + providerBranch?: string; + providerSilentMode?: boolean; + providerRootDirectory?: string; + specification?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const functionsUpdate = async ({functionId,name,runtime,execute,events,schedule,timeout,enabled,logging,entrypoint,commands,scopes,installationId,providerRepositoryId,providerBranch,providerSilentMode,providerRootDirectory,specification,parseOutput = true, overrideForCli = false, sdk = undefined}: FunctionsUpdateRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/functions/{functionId}'.replace('{functionId}', functionId); @@ -502,18 +468,14 @@ const functionsUpdate = async ({functionId,name,runtime,execute,events,schedule, return response; } -/** - * @typedef {Object} FunctionsDeleteRequestParams - * @property {string} functionId Function ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {FunctionsDeleteRequestParams} params - */ -const functionsDelete = async ({functionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface FunctionsDeleteRequestParams { + functionId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const functionsDelete = async ({functionId,parseOutput = true, overrideForCli = false, sdk = undefined}: FunctionsDeleteRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/functions/{functionId}'.replace('{functionId}', functionId); @@ -532,19 +494,15 @@ const functionsDelete = async ({functionId,parseOutput = true, overrideForCli = return response; } -/** - * @typedef {Object} FunctionsUpdateFunctionDeploymentRequestParams - * @property {string} functionId Function ID. - * @property {string} deploymentId Deployment ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {FunctionsUpdateFunctionDeploymentRequestParams} params - */ -const functionsUpdateFunctionDeployment = async ({functionId,deploymentId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface FunctionsUpdateFunctionDeploymentRequestParams { + functionId: string; + deploymentId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const functionsUpdateFunctionDeployment = async ({functionId,deploymentId,parseOutput = true, overrideForCli = false, sdk = undefined}: FunctionsUpdateFunctionDeploymentRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/functions/{functionId}/deployment'.replace('{functionId}', functionId); @@ -566,21 +524,18 @@ const functionsUpdateFunctionDeployment = async ({functionId,deploymentId,parseO return response; } -/** - * @typedef {Object} FunctionsListDeploymentsRequestParams - * @property {string} functionId Function ID. - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: buildSize, sourceSize, totalSize, buildDuration, status, activate, type - * @property {string} search Search term to filter your list results. Max length: 256 chars. - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {FunctionsListDeploymentsRequestParams} params - */ -const functionsListDeployments = async ({functionId,queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface FunctionsListDeploymentsRequestParams { + functionId: string; + queries?: string[]; + search?: string; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const functionsListDeployments = async ({functionId,queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: FunctionsListDeploymentsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/functions/{functionId}/deployments'.replace('{functionId}', functionId); @@ -601,7 +556,7 @@ const functionsListDeployments = async ({functionId,queries,search,total,parseOu }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('functions', 'listDeployments', functionId); } else { parse(response) @@ -611,23 +566,19 @@ const functionsListDeployments = async ({functionId,queries,search,total,parseOu return response; } -/** - * @typedef {Object} FunctionsCreateDeploymentRequestParams - * @property {string} functionId Function ID. - * @property {string} code Gzip file with your code package. When used with the Appwrite CLI, pass the path to your code directory, and the CLI will automatically package your code. Use a path that is within the current directory. - * @property {boolean} activate Automatically activate the deployment when it is finished building. - * @property {string} entrypoint Entrypoint File. - * @property {string} commands Build Commands. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - * @property {CallableFunction} onProgress - */ - -/** - * @param {FunctionsCreateDeploymentRequestParams} params - */ -const functionsCreateDeployment = async ({functionId,code,activate,entrypoint,commands,parseOutput = true, overrideForCli = false, sdk = undefined,onProgress = () => {}}) => { +interface FunctionsCreateDeploymentRequestParams { + functionId: string; + code: string; + activate: boolean; + entrypoint?: string; + commands?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + onProgress?: (progress: number) => void; +} + +export const functionsCreateDeployment = async ({functionId,code,activate,entrypoint,commands,parseOutput = true, overrideForCli = false, sdk = undefined,onProgress = () => {}}: FunctionsCreateDeploymentRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/functions/{functionId}/deployments'.replace('{functionId}', functionId); @@ -775,20 +726,16 @@ const functionsCreateDeployment = async ({functionId,code,activate,entrypoint,co return response; } -/** - * @typedef {Object} FunctionsCreateDuplicateDeploymentRequestParams - * @property {string} functionId Function ID. - * @property {string} deploymentId Deployment ID. - * @property {string} buildId Build unique ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {FunctionsCreateDuplicateDeploymentRequestParams} params - */ -const functionsCreateDuplicateDeployment = async ({functionId,deploymentId,buildId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface FunctionsCreateDuplicateDeploymentRequestParams { + functionId: string; + deploymentId: string; + buildId?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const functionsCreateDuplicateDeployment = async ({functionId,deploymentId,buildId,parseOutput = true, overrideForCli = false, sdk = undefined}: FunctionsCreateDuplicateDeploymentRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/functions/{functionId}/deployments/duplicate'.replace('{functionId}', functionId); @@ -813,24 +760,20 @@ const functionsCreateDuplicateDeployment = async ({functionId,deploymentId,build return response; } -/** - * @typedef {Object} FunctionsCreateTemplateDeploymentRequestParams - * @property {string} functionId Function ID. - * @property {string} repository Repository name of the template. - * @property {string} owner The name of the owner of the template. - * @property {string} rootDirectory Path to function code in the template repo. - * @property {TemplateReferenceType} type Type for the reference provided. Can be commit, branch, or tag - * @property {string} reference Reference value, can be a commit hash, branch name, or release tag - * @property {boolean} activate Automatically activate the deployment when it is finished building. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {FunctionsCreateTemplateDeploymentRequestParams} params - */ -const functionsCreateTemplateDeployment = async ({functionId,repository,owner,rootDirectory,type,reference,activate,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface FunctionsCreateTemplateDeploymentRequestParams { + functionId: string; + repository: string; + owner: string; + rootDirectory: string; + type: TemplateReferenceType; + reference: string; + activate?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const functionsCreateTemplateDeployment = async ({functionId,repository,owner,rootDirectory,type,reference,activate,parseOutput = true, overrideForCli = false, sdk = undefined}: FunctionsCreateTemplateDeploymentRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/functions/{functionId}/deployments/template'.replace('{functionId}', functionId); @@ -867,21 +810,17 @@ const functionsCreateTemplateDeployment = async ({functionId,repository,owner,ro return response; } -/** - * @typedef {Object} FunctionsCreateVcsDeploymentRequestParams - * @property {string} functionId Function ID. - * @property {VCSReferenceType} type Type of reference passed. Allowed values are: branch, commit - * @property {string} reference VCS reference to create deployment from. Depending on type this can be: branch name, commit hash - * @property {boolean} activate Automatically activate the deployment when it is finished building. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {FunctionsCreateVcsDeploymentRequestParams} params - */ -const functionsCreateVcsDeployment = async ({functionId,type,reference,activate,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface FunctionsCreateVcsDeploymentRequestParams { + functionId: string; + type: VCSReferenceType; + reference: string; + activate?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const functionsCreateVcsDeployment = async ({functionId,type,reference,activate,parseOutput = true, overrideForCli = false, sdk = undefined}: FunctionsCreateVcsDeploymentRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/functions/{functionId}/deployments/vcs'.replace('{functionId}', functionId); @@ -909,19 +848,16 @@ const functionsCreateVcsDeployment = async ({functionId,type,reference,activate, return response; } -/** - * @typedef {Object} FunctionsGetDeploymentRequestParams - * @property {string} functionId Function ID. - * @property {string} deploymentId Deployment ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {FunctionsGetDeploymentRequestParams} params - */ -const functionsGetDeployment = async ({functionId,deploymentId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface FunctionsGetDeploymentRequestParams { + functionId: string; + deploymentId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const functionsGetDeployment = async ({functionId,deploymentId,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: FunctionsGetDeploymentRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/functions/{functionId}/deployments/{deploymentId}'.replace('{functionId}', functionId).replace('{deploymentId}', deploymentId); @@ -933,7 +869,7 @@ const functionsGetDeployment = async ({functionId,deploymentId,parseOutput = tru }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('functions', 'getDeployment', functionId, deploymentId); } else { parse(response) @@ -943,19 +879,15 @@ const functionsGetDeployment = async ({functionId,deploymentId,parseOutput = tru return response; } -/** - * @typedef {Object} FunctionsDeleteDeploymentRequestParams - * @property {string} functionId Function ID. - * @property {string} deploymentId Deployment ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {FunctionsDeleteDeploymentRequestParams} params - */ -const functionsDeleteDeployment = async ({functionId,deploymentId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface FunctionsDeleteDeploymentRequestParams { + functionId: string; + deploymentId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const functionsDeleteDeployment = async ({functionId,deploymentId,parseOutput = true, overrideForCli = false, sdk = undefined}: FunctionsDeleteDeploymentRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/functions/{functionId}/deployments/{deploymentId}'.replace('{functionId}', functionId).replace('{deploymentId}', deploymentId); @@ -974,21 +906,18 @@ const functionsDeleteDeployment = async ({functionId,deploymentId,parseOutput = return response; } -/** - * @typedef {Object} FunctionsGetDeploymentDownloadRequestParams - * @property {string} functionId Function ID. - * @property {string} deploymentId Deployment ID. - * @property {DeploymentDownloadType} type Deployment file to download. Can be: "source", "output". - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - * @property {string} destination - */ - -/** - * @param {FunctionsGetDeploymentDownloadRequestParams} params - */ -const functionsGetDeploymentDownload = async ({functionId,deploymentId,type,parseOutput = true, overrideForCli = false, sdk = undefined, destination, console}) => { +interface FunctionsGetDeploymentDownloadRequestParams { + functionId: string; + deploymentId: string; + type?: DeploymentDownloadType; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + destination?: string; + console?: boolean; +} + +export const functionsGetDeploymentDownload = async ({functionId,deploymentId,type,parseOutput = true, overrideForCli = false, sdk = undefined, destination, console: showConsole}: FunctionsGetDeploymentDownloadRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/functions/{functionId}/deployments/{deploymentId}/download'.replace('{functionId}', functionId).replace('{deploymentId}', deploymentId); @@ -1014,7 +943,7 @@ const functionsGetDeploymentDownload = async ({functionId,deploymentId,type,pars fs.writeFileSync(destination, response); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('functions', 'getDeploymentDownload', functionId, deploymentId); } else { parse(response) @@ -1024,19 +953,15 @@ const functionsGetDeploymentDownload = async ({functionId,deploymentId,type,pars return response; } -/** - * @typedef {Object} FunctionsUpdateDeploymentStatusRequestParams - * @property {string} functionId Function ID. - * @property {string} deploymentId Deployment ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {FunctionsUpdateDeploymentStatusRequestParams} params - */ -const functionsUpdateDeploymentStatus = async ({functionId,deploymentId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface FunctionsUpdateDeploymentStatusRequestParams { + functionId: string; + deploymentId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const functionsUpdateDeploymentStatus = async ({functionId,deploymentId,parseOutput = true, overrideForCli = false, sdk = undefined}: FunctionsUpdateDeploymentStatusRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/functions/{functionId}/deployments/{deploymentId}/status'.replace('{functionId}', functionId).replace('{deploymentId}', deploymentId); @@ -1055,20 +980,17 @@ const functionsUpdateDeploymentStatus = async ({functionId,deploymentId,parseOut return response; } -/** - * @typedef {Object} FunctionsListExecutionsRequestParams - * @property {string} functionId Function ID. - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: trigger, status, responseStatusCode, duration, requestMethod, requestPath, deploymentId - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {FunctionsListExecutionsRequestParams} params - */ -const functionsListExecutions = async ({functionId,queries,total,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface FunctionsListExecutionsRequestParams { + functionId: string; + queries?: string[]; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const functionsListExecutions = async ({functionId,queries,total,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: FunctionsListExecutionsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/functions/{functionId}/executions'.replace('{functionId}', functionId); @@ -1086,7 +1008,7 @@ const functionsListExecutions = async ({functionId,queries,total,parseOutput = t }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('functions', 'listExecutions', functionId); } else { parse(response) @@ -1096,24 +1018,20 @@ const functionsListExecutions = async ({functionId,queries,total,parseOutput = t return response; } -/** - * @typedef {Object} FunctionsCreateExecutionRequestParams - * @property {string} functionId Function ID. - * @property {string} body HTTP body of execution. Default value is empty string. - * @property {boolean} async Execute code in the background. Default value is false. - * @property {string} xpath HTTP path of execution. Path can include query params. Default value is / - * @property {ExecutionMethod} method HTTP method of execution. Default value is POST. - * @property {object} headers HTTP headers of execution. Defaults to empty. - * @property {string} scheduledAt Scheduled execution time in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. DateTime value must be in future with precision in minutes. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {FunctionsCreateExecutionRequestParams} params - */ -const functionsCreateExecution = async ({functionId,body,async,xpath,method,headers,scheduledAt,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface FunctionsCreateExecutionRequestParams { + functionId: string; + body?: string; + async?: boolean; + xpath?: string; + method?: ExecutionMethod; + headers?: object; + scheduledAt?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const functionsCreateExecution = async ({functionId,body,async,xpath,method,headers,scheduledAt,parseOutput = true, overrideForCli = false, sdk = undefined}: FunctionsCreateExecutionRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/functions/{functionId}/executions'.replace('{functionId}', functionId); @@ -1150,19 +1068,16 @@ const functionsCreateExecution = async ({functionId,body,async,xpath,method,head return response; } -/** - * @typedef {Object} FunctionsGetExecutionRequestParams - * @property {string} functionId Function ID. - * @property {string} executionId Execution ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {FunctionsGetExecutionRequestParams} params - */ -const functionsGetExecution = async ({functionId,executionId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface FunctionsGetExecutionRequestParams { + functionId: string; + executionId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const functionsGetExecution = async ({functionId,executionId,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: FunctionsGetExecutionRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/functions/{functionId}/executions/{executionId}'.replace('{functionId}', functionId).replace('{executionId}', executionId); @@ -1174,7 +1089,7 @@ const functionsGetExecution = async ({functionId,executionId,parseOutput = true, }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('functions', 'getExecution', functionId, executionId); } else { parse(response) @@ -1184,19 +1099,15 @@ const functionsGetExecution = async ({functionId,executionId,parseOutput = true, return response; } -/** - * @typedef {Object} FunctionsDeleteExecutionRequestParams - * @property {string} functionId Function ID. - * @property {string} executionId Execution ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {FunctionsDeleteExecutionRequestParams} params - */ -const functionsDeleteExecution = async ({functionId,executionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface FunctionsDeleteExecutionRequestParams { + functionId: string; + executionId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const functionsDeleteExecution = async ({functionId,executionId,parseOutput = true, overrideForCli = false, sdk = undefined}: FunctionsDeleteExecutionRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/functions/{functionId}/executions/{executionId}'.replace('{functionId}', functionId).replace('{executionId}', executionId); @@ -1215,19 +1126,15 @@ const functionsDeleteExecution = async ({functionId,executionId,parseOutput = tr return response; } -/** - * @typedef {Object} FunctionsGetUsageRequestParams - * @property {string} functionId Function ID. - * @property {UsageRange} range Date range. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {FunctionsGetUsageRequestParams} params - */ -const functionsGetUsage = async ({functionId,range,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface FunctionsGetUsageRequestParams { + functionId: string; + range?: UsageRange; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const functionsGetUsage = async ({functionId,range,parseOutput = true, overrideForCli = false, sdk = undefined}: FunctionsGetUsageRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/functions/{functionId}/usage'.replace('{functionId}', functionId); @@ -1248,18 +1155,14 @@ const functionsGetUsage = async ({functionId,range,parseOutput = true, overrideF return response; } -/** - * @typedef {Object} FunctionsListVariablesRequestParams - * @property {string} functionId Function unique ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {FunctionsListVariablesRequestParams} params - */ -const functionsListVariables = async ({functionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface FunctionsListVariablesRequestParams { + functionId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const functionsListVariables = async ({functionId,parseOutput = true, overrideForCli = false, sdk = undefined}: FunctionsListVariablesRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/functions/{functionId}/variables'.replace('{functionId}', functionId); @@ -1277,21 +1180,17 @@ const functionsListVariables = async ({functionId,parseOutput = true, overrideFo return response; } -/** - * @typedef {Object} FunctionsCreateVariableRequestParams - * @property {string} functionId Function unique ID. - * @property {string} key Variable key. Max length: 255 chars. - * @property {string} value Variable value. Max length: 8192 chars. - * @property {boolean} secret Secret variables can be updated or deleted, but only functions can read them during build and runtime. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {FunctionsCreateVariableRequestParams} params - */ -const functionsCreateVariable = async ({functionId,key,value,secret,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface FunctionsCreateVariableRequestParams { + functionId: string; + key: string; + value: string; + secret?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const functionsCreateVariable = async ({functionId,key,value,secret,parseOutput = true, overrideForCli = false, sdk = undefined}: FunctionsCreateVariableRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/functions/{functionId}/variables'.replace('{functionId}', functionId); @@ -1319,19 +1218,15 @@ const functionsCreateVariable = async ({functionId,key,value,secret,parseOutput return response; } -/** - * @typedef {Object} FunctionsGetVariableRequestParams - * @property {string} functionId Function unique ID. - * @property {string} variableId Variable unique ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {FunctionsGetVariableRequestParams} params - */ -const functionsGetVariable = async ({functionId,variableId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface FunctionsGetVariableRequestParams { + functionId: string; + variableId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const functionsGetVariable = async ({functionId,variableId,parseOutput = true, overrideForCli = false, sdk = undefined}: FunctionsGetVariableRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/functions/{functionId}/variables/{variableId}'.replace('{functionId}', functionId).replace('{variableId}', variableId); @@ -1349,22 +1244,18 @@ const functionsGetVariable = async ({functionId,variableId,parseOutput = true, o return response; } -/** - * @typedef {Object} FunctionsUpdateVariableRequestParams - * @property {string} functionId Function unique ID. - * @property {string} variableId Variable unique ID. - * @property {string} key Variable key. Max length: 255 chars. - * @property {string} value Variable value. Max length: 8192 chars. - * @property {boolean} secret Secret variables can be updated or deleted, but only functions can read them during build and runtime. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {FunctionsUpdateVariableRequestParams} params - */ -const functionsUpdateVariable = async ({functionId,variableId,key,value,secret,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface FunctionsUpdateVariableRequestParams { + functionId: string; + variableId: string; + key: string; + value?: string; + secret?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const functionsUpdateVariable = async ({functionId,variableId,key,value,secret,parseOutput = true, overrideForCli = false, sdk = undefined}: FunctionsUpdateVariableRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/functions/{functionId}/variables/{variableId}'.replace('{functionId}', functionId).replace('{variableId}', variableId); @@ -1392,19 +1283,15 @@ const functionsUpdateVariable = async ({functionId,variableId,key,value,secret,p return response; } -/** - * @typedef {Object} FunctionsDeleteVariableRequestParams - * @property {string} functionId Function unique ID. - * @property {string} variableId Variable unique ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {FunctionsDeleteVariableRequestParams} params - */ -const functionsDeleteVariable = async ({functionId,variableId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface FunctionsDeleteVariableRequestParams { + functionId: string; + variableId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const functionsDeleteVariable = async ({functionId,variableId,parseOutput = true, overrideForCli = false, sdk = undefined}: FunctionsDeleteVariableRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/functions/{functionId}/variables/{variableId}'.replace('{functionId}', functionId).replace('{variableId}', variableId); @@ -1428,7 +1315,7 @@ functions .description(`Get a list of all the project's functions. You can use the query params to filter your results.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name, enabled, runtime, deploymentId, schedule, scheduleNext, schedulePrevious, timeout, entrypoint, commands, installationId`) .option(`--search `, `Search term to filter your list results. Max length: 256 chars.`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--console`, `Get the resource console url`) .action(actionRunner(functionsList)) @@ -1442,15 +1329,15 @@ functions .option(`--events [events...]`, `Events list. Maximum of 100 events are allowed.`) .option(`--schedule `, `Schedule CRON syntax.`) .option(`--timeout `, `Function maximum execution time in seconds.`, parseInteger) - .option(`--enabled [value]`, `Is function enabled? When set to 'disabled', users cannot access the function but Server SDKs with and API key can still access the function. No data is lost when this is toggled.`, (value) => value === undefined ? true : parseBool(value)) - .option(`--logging [value]`, `When disabled, executions will exclude logs and errors, and will be slightly faster.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Is function enabled? When set to 'disabled', users cannot access the function but Server SDKs with and API key can still access the function. No data is lost when this is toggled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--logging [value]`, `When disabled, executions will exclude logs and errors, and will be slightly faster.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--entrypoint `, `Entrypoint File. This path is relative to the "providerRootDirectory".`) .option(`--commands `, `Build Commands.`) .option(`--scopes [scopes...]`, `List of scopes allowed for API key auto-generated for every execution. Maximum of 100 scopes are allowed.`) .option(`--installation-id `, `Appwrite Installation ID for VCS (Version Control System) deployment.`) .option(`--provider-repository-id `, `Repository ID of the repo linked to the function.`) .option(`--provider-branch `, `Production branch for the repo linked to the function.`) - .option(`--provider-silent-mode [value]`, `Is the VCS (Version Control System) connection in silent mode for the repo linked to the function? In silent mode, comments will not be made on commits and pull requests.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--provider-silent-mode [value]`, `Is the VCS (Version Control System) connection in silent mode for the repo linked to the function? In silent mode, comments will not be made on commits and pull requests.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--provider-root-directory `, `Path to function code in the linked repo.`) .option(`--specification `, `Runtime specification for the function and builds.`) .action(actionRunner(functionsCreate)) @@ -1473,7 +1360,7 @@ functions .option(`--use-cases [use-cases...]`, `List of use cases allowed for filtering function templates. Maximum of 100 use cases are allowed.`) .option(`--limit `, `Limit the number of templates returned in the response. Default limit is 25, and maximum limit is 5000.`, parseInteger) .option(`--offset `, `Offset the list of returned templates. Maximum offset is 5000.`, parseInteger) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--console`, `Get the resource console url`) .action(actionRunner(functionsListTemplates)) @@ -1508,15 +1395,15 @@ functions .option(`--events [events...]`, `Events list. Maximum of 100 events are allowed.`) .option(`--schedule `, `Schedule CRON syntax.`) .option(`--timeout `, `Maximum execution time in seconds.`, parseInteger) - .option(`--enabled [value]`, `Is function enabled? When set to 'disabled', users cannot access the function but Server SDKs with and API key can still access the function. No data is lost when this is toggled.`, (value) => value === undefined ? true : parseBool(value)) - .option(`--logging [value]`, `When disabled, executions will exclude logs and errors, and will be slightly faster.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Is function enabled? When set to 'disabled', users cannot access the function but Server SDKs with and API key can still access the function. No data is lost when this is toggled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--logging [value]`, `When disabled, executions will exclude logs and errors, and will be slightly faster.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--entrypoint `, `Entrypoint File. This path is relative to the "providerRootDirectory".`) .option(`--commands `, `Build Commands.`) .option(`--scopes [scopes...]`, `List of scopes allowed for API Key auto-generated for every execution. Maximum of 100 scopes are allowed.`) .option(`--installation-id `, `Appwrite Installation ID for VCS (Version Controle System) deployment.`) .option(`--provider-repository-id `, `Repository ID of the repo linked to the function`) .option(`--provider-branch `, `Production branch for the repo linked to the function`) - .option(`--provider-silent-mode [value]`, `Is the VCS (Version Control System) connection in silent mode for the repo linked to the function? In silent mode, comments will not be made on commits and pull requests.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--provider-silent-mode [value]`, `Is the VCS (Version Control System) connection in silent mode for the repo linked to the function? In silent mode, comments will not be made on commits and pull requests.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--provider-root-directory `, `Path to function code in the linked repo.`) .option(`--specification `, `Runtime specification for the function and builds.`) .action(actionRunner(functionsUpdate)) @@ -1540,7 +1427,7 @@ functions .requiredOption(`--function-id `, `Function ID.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: buildSize, sourceSize, totalSize, buildDuration, status, activate, type`) .option(`--search `, `Search term to filter your list results. Max length: 256 chars.`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--console`, `Get the resource console url`) .action(actionRunner(functionsListDeployments)) @@ -1549,7 +1436,7 @@ functions .description(`Create a new function code deployment. Use this endpoint to upload a new version of your code function. To execute your newly uploaded code, you'll need to update the function's deployment to use your new deployment UID. This endpoint accepts a tar.gz file compressed with your code. Make sure to include any dependencies your code has within the compressed file. You can learn more about code packaging in the [Appwrite Cloud Functions tutorial](https://appwrite.io/docs/functions). Use the "command" param to set the entrypoint used to execute your code.`) .requiredOption(`--function-id `, `Function ID.`) .requiredOption(`--code `, `Gzip file with your code package. When used with the Appwrite CLI, pass the path to your code directory, and the CLI will automatically package your code. Use a path that is within the current directory.`) - .requiredOption(`--activate [value]`, `Automatically activate the deployment when it is finished building.`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--activate [value]`, `Automatically activate the deployment when it is finished building.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--entrypoint `, `Entrypoint File.`) .option(`--commands `, `Build Commands.`) .action(actionRunner(functionsCreateDeployment)) @@ -1571,7 +1458,7 @@ functions .requiredOption(`--root-directory `, `Path to function code in the template repo.`) .requiredOption(`--type `, `Type for the reference provided. Can be commit, branch, or tag`) .requiredOption(`--reference `, `Reference value, can be a commit hash, branch name, or release tag`) - .option(`--activate [value]`, `Automatically activate the deployment when it is finished building.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--activate [value]`, `Automatically activate the deployment when it is finished building.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(functionsCreateTemplateDeployment)) functions @@ -1580,7 +1467,7 @@ functions .requiredOption(`--function-id `, `Function ID.`) .requiredOption(`--type `, `Type of reference passed. Allowed values are: branch, commit`) .requiredOption(`--reference `, `VCS reference to create deployment from. Depending on type this can be: branch name, commit hash`) - .option(`--activate [value]`, `Automatically activate the deployment when it is finished building.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--activate [value]`, `Automatically activate the deployment when it is finished building.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(functionsCreateVcsDeployment)) functions @@ -1620,7 +1507,7 @@ functions .description(`Get a list of all the current user function execution logs. You can use the query params to filter your results.`) .requiredOption(`--function-id `, `Function ID.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: trigger, status, responseStatusCode, duration, requestMethod, requestPath, deploymentId`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--console`, `Get the resource console url`) .action(actionRunner(functionsListExecutions)) @@ -1629,7 +1516,7 @@ functions .description(`Trigger a function execution. The returned object will return you the current execution status. You can ping the 'Get Execution' endpoint to get updates on the current execution status. Once this endpoint is called, your function execution process will start asynchronously.`) .requiredOption(`--function-id `, `Function ID.`) .option(`--body `, `HTTP body of execution. Default value is empty string.`) - .option(`--async [value]`, `Execute code in the background. Default value is false.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--async [value]`, `Execute code in the background. Default value is false.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xpath `, `HTTP path of execution. Path can include query params. Default value is /`) .option(`--method `, `HTTP method of execution. Default value is POST.`) .option(`--headers `, `HTTP headers of execution. Defaults to empty.`) @@ -1670,7 +1557,7 @@ functions .requiredOption(`--function-id `, `Function unique ID.`) .requiredOption(`--key `, `Variable key. Max length: 255 chars.`) .requiredOption(`--value `, `Variable value. Max length: 8192 chars.`) - .option(`--secret [value]`, `Secret variables can be updated or deleted, but only functions can read them during build and runtime.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--secret [value]`, `Secret variables can be updated or deleted, but only functions can read them during build and runtime.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(functionsCreateVariable)) functions @@ -1687,7 +1574,7 @@ functions .requiredOption(`--variable-id `, `Variable unique ID.`) .requiredOption(`--key `, `Variable key. Max length: 255 chars.`) .option(`--value `, `Variable value. Max length: 8192 chars.`) - .option(`--secret [value]`, `Secret variables can be updated or deleted, but only functions can read them during build and runtime.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--secret [value]`, `Secret variables can be updated or deleted, but only functions can read them during build and runtime.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(functionsUpdateVariable)) functions @@ -1697,36 +1584,4 @@ functions .requiredOption(`--variable-id `, `Variable unique ID.`) .action(actionRunner(functionsDeleteVariable)) -module.exports = { - functions, - functionsList, - functionsCreate, - functionsListRuntimes, - functionsListSpecifications, - functionsListTemplates, - functionsGetTemplate, - functionsListUsage, - functionsGet, - functionsUpdate, - functionsDelete, - functionsUpdateFunctionDeployment, - functionsListDeployments, - functionsCreateDeployment, - functionsCreateDuplicateDeployment, - functionsCreateTemplateDeployment, - functionsCreateVcsDeployment, - functionsGetDeployment, - functionsDeleteDeployment, - functionsGetDeploymentDownload, - functionsUpdateDeploymentStatus, - functionsListExecutions, - functionsCreateExecution, - functionsGetExecution, - functionsDeleteExecution, - functionsGetUsage, - functionsListVariables, - functionsCreateVariable, - functionsGetVariable, - functionsUpdateVariable, - functionsDeleteVariable -}; + diff --git a/lib/commands/generic.js b/lib/commands/generic.ts similarity index 80% rename from lib/commands/generic.js rename to lib/commands/generic.ts index d269dcc5..5dfc962d 100644 --- a/lib/commands/generic.js +++ b/lib/commands/generic.ts @@ -1,16 +1,24 @@ -const inquirer = require("inquirer"); -const { Command } = require("commander"); -const Client = require("../client"); -const { sdkForConsole } = require("../sdks"); -const { globalConfig, localConfig } = require("../config"); -const { actionRunner, success, parseBool, commandDescriptions, error, parse, hint, log, drawTable, cliConfig } = require("../parser"); -const ID = require("../id"); -const { questionsLogin, questionsLogout, questionsListFactors, questionsMFAChallenge } = require("../questions"); -const { accountUpdateMFAChallenge, accountCreateMFAChallenge, accountGet, accountCreateEmailPasswordSession, accountDeleteSession } = require("./account"); +import inquirer from 'inquirer'; +import { Command } from 'commander'; +import Client from '../client'; +import { sdkForConsole } from '../sdks'; +import { globalConfig, localConfig } from '../config'; +import { actionRunner, success, parseBool, commandDescriptions, error, parse, hint, log, drawTable, cliConfig } from '../parser'; +import ID from '../id'; +import { questionsLogin, questionsLogout, questionsListFactors, questionsMFAChallenge } from '../questions'; +import { accountUpdateMFAChallenge, accountCreateMFAChallenge, accountGet, accountCreateEmailPasswordSession, accountDeleteSession } from './account'; const DEFAULT_ENDPOINT = 'https://cloud.appwrite.io/v1'; -const loginCommand = async ({ email, password, endpoint, mfa, code }) => { +interface LoginCommandOptions { + email?: string; + password?: string; + endpoint?: string; + mfa?: string; + code?: string; +} + +export const loginCommand = async ({ email, password, endpoint, mfa, code }: LoginCommandOptions): Promise => { const oldCurrent = globalConfig.getCurrentSession(); const configEndpoint = (endpoint ?? globalConfig.getEndpoint()) || DEFAULT_ENDPOINT; @@ -67,8 +75,8 @@ const loginCommand = async ({ email, password, endpoint, mfa, code }) => { sdk: client, parseOutput: false }); - } catch (error) { - if (error.response === 'user_more_factors_required') { + } catch (err: any) { + if (err.response === 'user_more_factors_required') { const { factor } = mfa ? { factor: mfa } : await inquirer.prompt(questionsListFactors); const challenge = await accountCreateMFAChallenge({ @@ -93,10 +101,10 @@ const loginCommand = async ({ email, password, endpoint, mfa, code }) => { } else { globalConfig.removeSession(id); globalConfig.setCurrentSession(oldCurrent); - if (endpoint !== DEFAULT_ENDPOINT && error.response === 'user_invalid_credentials') { + if (endpoint !== DEFAULT_ENDPOINT && err.response === 'user_invalid_credentials') { log('Use the --endpoint option for self-hosted instances') } - throw error; + throw err; } } @@ -104,7 +112,7 @@ const loginCommand = async ({ email, password, endpoint, mfa, code }) => { hint("Next you can create or link to your project using 'appwrite init project'"); }; -const whoami = new Command("whoami") +export const whoami = new Command("whoami") .description(commandDescriptions['whoami']) .action(actionRunner(async () => { if (globalConfig.getEndpoint() === '' || globalConfig.getCookie() === '') { @@ -144,13 +152,13 @@ const whoami = new Command("whoami") drawTable(data) })); -const register = new Command("register") +export const register = new Command("register") .description(commandDescriptions['register']) .action(actionRunner(async () => { log('Visit https://cloud.appwrite.io/register to create an account') })); -const login = new Command("login") +export const login = new Command("login") .description(commandDescriptions['login']) .option(`--email [email]`, `User email`) .option(`--password [password]`, `User password`) @@ -162,7 +170,7 @@ const login = new Command("login") }) .action(actionRunner(loginCommand)); -const deleteSession = async (accountId) => { +const deleteSession = async (accountId: string): Promise => { try { let client = await sdkForConsole(); @@ -178,7 +186,7 @@ const deleteSession = async (accountId) => { } } -const logout = new Command("logout") +export const logout = new Command("logout") .description(commandDescriptions['logout']) .configureHelp({ helpWidth: process.stdout.columns || 80 @@ -210,8 +218,8 @@ const logout = new Command("logout") const remainingSessions = globalConfig.getSessions(); - if (remainingSessions.length > 0 && remainingSessions.filter(session => session.id === current).length !== 1) { - const accountId = remainingSessions [0].id; + if (remainingSessions.length > 0 && remainingSessions.filter((session: any) => session.id === current).length !== 1) { + const accountId = remainingSessions[0].id; globalConfig.setCurrentSession(accountId); success(`Current account is ${accountId}`); @@ -222,7 +230,16 @@ const logout = new Command("logout") success("Logging out"); })); -const client = new Command("client") +interface ClientCommandOptions { + selfSigned?: boolean; + endpoint?: string; + projectId?: string; + key?: string; + debug?: boolean; + reset?: boolean; +} + +export const client = new Command("client") .description(commandDescriptions['client']) .configureHelp({ helpWidth: process.stdout.columns || 80 @@ -233,7 +250,7 @@ const client = new Command("client") .option("-k, --key ", "Set your Appwrite server's API key") .option("-d, --debug", "Print CLI debug information") .option("-r, --reset", "Reset the CLI configuration") - .action(actionRunner(async ({ selfSigned, endpoint, projectId, key, debug, reset }, command) => { + .action(actionRunner(async ({ selfSigned, endpoint, projectId, key, debug, reset }: ClientCommandOptions, command: Command) => { if (selfSigned == undefined && endpoint == undefined && projectId == undefined && key == undefined && debug == undefined && reset == undefined) { command.help() } @@ -257,12 +274,12 @@ const client = new Command("client") throw new Error(); } - let client = new Client().setEndpoint(endpoint); - client.setProject('console'); + let clientInstance = new Client().setEndpoint(endpoint); + clientInstance.setProject('console'); if (selfSigned || globalConfig.getSelfSigned()) { - client.setSelfSigned(true); + clientInstance.setSelfSigned(true); } - let response = await client.call('GET', '/health/version'); + let response = await clientInstance.call('GET', '/health/version'); if (!response.version) { throw new Error(); } @@ -289,7 +306,7 @@ const client = new Command("client") if (reset !== undefined) { const sessions = globalConfig.getSessions(); - for (let accountId of sessions.map(session => session.id)) { + for (let accountId of sessions.map((session: any) => session.id)) { globalConfig.setCurrentSession(accountId); await deleteSession(accountId); } @@ -298,7 +315,7 @@ const client = new Command("client") success("Setting client") })); -const migrate = async () => { +export const migrate = async (): Promise => { if (!globalConfig.has('endpoint') || !globalConfig.has('cookie')) { return; } @@ -317,14 +334,5 @@ const migrate = async () => { globalConfig.setCurrentSession(id); globalConfig.delete('endpoint'); globalConfig.delete('cookie'); - } -module.exports = { - loginCommand, - whoami, - register, - login, - logout, - migrate, - client -}; + diff --git a/lib/commands/graphql.js b/lib/commands/graphql.js deleted file mode 100644 index b0cf7e40..00000000 --- a/lib/commands/graphql.js +++ /dev/null @@ -1,126 +0,0 @@ -const fs = require('fs'); -const pathLib = require('path'); -const tar = require("tar"); -const ignore = require("ignore"); -const { promisify } = require('util'); -const libClient = require('../client.js'); -const { getAllFiles, showConsoleLink } = require('../utils.js'); -const { Command } = require('commander'); -const { sdkForProject, sdkForConsole } = require('../sdks') -const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } = require('../parser') -const { localConfig, globalConfig } = require("../config"); -const { File } = require('undici'); -const { ReadableStream } = require('stream/web'); - -/** - * @param {fs.ReadStream} readStream - * @returns {ReadableStream} - */ -function convertReadStreamToReadableStream(readStream) { - return new ReadableStream({ - start(controller) { - readStream.on("data", (chunk) => { - controller.enqueue(chunk); - }); - readStream.on("end", () => { - controller.close(); - }); - readStream.on("error", (err) => { - controller.error(err); - }); - }, - cancel() { - readStream.destroy(); - }, - }); -} - -const graphql = new Command("graphql").description(commandDescriptions['graphql'] ?? '').configureHelp({ - helpWidth: process.stdout.columns || 80 -}) - -/** - * @typedef {Object} GraphqlQueryRequestParams - * @property {object} query The query or queries to execute. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {GraphqlQueryRequestParams} params - */ -const graphqlQuery = async ({query,parseOutput = true, overrideForCli = false, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : - sdk; - let apiPath = '/graphql'; - let payload = {}; - if (typeof query !== 'undefined') { - payload['query'] = JSON.parse(query); - } - - let response = undefined; - - response = await client.call('post', apiPath, { - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - }, payload); - - if (parseOutput) { - parse(response) - } - - return response; - -} -/** - * @typedef {Object} GraphqlMutationRequestParams - * @property {object} query The query or queries to execute. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {GraphqlMutationRequestParams} params - */ -const graphqlMutation = async ({query,parseOutput = true, overrideForCli = false, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : - sdk; - let apiPath = '/graphql/mutation'; - let payload = {}; - if (typeof query !== 'undefined') { - payload['query'] = JSON.parse(query); - } - - let response = undefined; - - response = await client.call('post', apiPath, { - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - }, payload); - - if (parseOutput) { - parse(response) - } - - return response; - -} -graphql - .command(`query`) - .description(`Execute a GraphQL mutation.`) - .requiredOption(`--query `, `The query or queries to execute.`) - .action(actionRunner(graphqlQuery)) - -graphql - .command(`mutation`) - .description(`Execute a GraphQL mutation.`) - .requiredOption(`--query `, `The query or queries to execute.`) - .action(actionRunner(graphqlMutation)) - -module.exports = { - graphql, - graphqlQuery, - graphqlMutation -}; diff --git a/lib/commands/graphql.ts b/lib/commands/graphql.ts new file mode 100644 index 00000000..04d0f74b --- /dev/null +++ b/lib/commands/graphql.ts @@ -0,0 +1,110 @@ +import fs = require('fs'); +import pathLib = require('path'); +import tar = require('tar'); +import ignore = require('ignore'); +import { promisify } from 'util'; +import Client from '../client'; +import { getAllFiles, showConsoleLink } from '../utils'; +import { Command } from 'commander'; +import { sdkForProject, sdkForConsole } from '../sdks'; +import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } from '../parser'; +import { localConfig, globalConfig } from '../config'; +import { File } from 'undici'; +import { ReadableStream } from 'stream/web'; + +function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { + return new ReadableStream({ + start(controller) { + readStream.on("data", (chunk: Buffer) => { + controller.enqueue(chunk); + }); + readStream.on("end", () => { + controller.close(); + }); + readStream.on("error", (err: Error) => { + controller.error(err); + }); + }, + cancel() { + readStream.destroy(); + }, + }); +} + +export const graphql = new Command("graphql").description(commandDescriptions['graphql'] ?? '').configureHelp({ + helpWidth: process.stdout.columns || 80 +}) + +interface GraphqlQueryRequestParams { + query: object; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const graphqlQuery = async ({query,parseOutput = true, overrideForCli = false, sdk = undefined}: GraphqlQueryRequestParams): Promise => { + let client = !sdk ? await sdkForProject() : + sdk; + let apiPath = '/graphql'; + let payload = {}; + if (typeof query !== 'undefined') { + payload['query'] = JSON.parse(query); + } + + let response = undefined; + + response = await client.call('post', apiPath, { + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + }, payload); + + if (parseOutput) { + parse(response) + } + + return response; + +} +interface GraphqlMutationRequestParams { + query: object; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const graphqlMutation = async ({query,parseOutput = true, overrideForCli = false, sdk = undefined}: GraphqlMutationRequestParams): Promise => { + let client = !sdk ? await sdkForProject() : + sdk; + let apiPath = '/graphql/mutation'; + let payload = {}; + if (typeof query !== 'undefined') { + payload['query'] = JSON.parse(query); + } + + let response = undefined; + + response = await client.call('post', apiPath, { + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + }, payload); + + if (parseOutput) { + parse(response) + } + + return response; + +} +graphql + .command(`query`) + .description(`Execute a GraphQL mutation.`) + .requiredOption(`--query `, `The query or queries to execute.`) + .action(actionRunner(graphqlQuery)) + +graphql + .command(`mutation`) + .description(`Execute a GraphQL mutation.`) + .requiredOption(`--query `, `The query or queries to execute.`) + .action(actionRunner(graphqlMutation)) + + diff --git a/lib/commands/health.js b/lib/commands/health.ts similarity index 57% rename from lib/commands/health.js rename to lib/commands/health.ts index 6798870d..7852de79 100644 --- a/lib/commands/health.js +++ b/lib/commands/health.ts @@ -1,31 +1,27 @@ -const fs = require('fs'); -const pathLib = require('path'); -const tar = require("tar"); -const ignore = require("ignore"); -const { promisify } = require('util'); -const libClient = require('../client.js'); -const { getAllFiles, showConsoleLink } = require('../utils.js'); -const { Command } = require('commander'); -const { sdkForProject, sdkForConsole } = require('../sdks') -const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } = require('../parser') -const { localConfig, globalConfig } = require("../config"); -const { File } = require('undici'); -const { ReadableStream } = require('stream/web'); - -/** - * @param {fs.ReadStream} readStream - * @returns {ReadableStream} - */ -function convertReadStreamToReadableStream(readStream) { +import fs = require('fs'); +import pathLib = require('path'); +import tar = require('tar'); +import ignore = require('ignore'); +import { promisify } from 'util'; +import Client from '../client'; +import { getAllFiles, showConsoleLink } from '../utils'; +import { Command } from 'commander'; +import { sdkForProject, sdkForConsole } from '../sdks'; +import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } from '../parser'; +import { localConfig, globalConfig } from '../config'; +import { File } from 'undici'; +import { ReadableStream } from 'stream/web'; + +function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ start(controller) { - readStream.on("data", (chunk) => { + readStream.on("data", (chunk: Buffer) => { controller.enqueue(chunk); }); readStream.on("end", () => { controller.close(); }); - readStream.on("error", (err) => { + readStream.on("error", (err: Error) => { controller.error(err); }); }, @@ -35,21 +31,17 @@ function convertReadStreamToReadableStream(readStream) { }); } -const health = new Command("health").description(commandDescriptions['health'] ?? '').configureHelp({ +export const health = new Command("health").description(commandDescriptions['health'] ?? '').configureHelp({ helpWidth: process.stdout.columns || 80 }) -/** - * @typedef {Object} HealthGetRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {HealthGetRequestParams} params - */ -const healthGet = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface HealthGetRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const healthGet = async ({parseOutput = true, overrideForCli = false, sdk = undefined}: HealthGetRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/health'; @@ -67,17 +59,13 @@ const healthGet = async ({parseOutput = true, overrideForCli = false, sdk = unde return response; } -/** - * @typedef {Object} HealthGetAntivirusRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface HealthGetAntivirusRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {HealthGetAntivirusRequestParams} params - */ -const healthGetAntivirus = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const healthGetAntivirus = async ({parseOutput = true, overrideForCli = false, sdk = undefined}: HealthGetAntivirusRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/health/anti-virus'; @@ -95,17 +83,13 @@ const healthGetAntivirus = async ({parseOutput = true, overrideForCli = false, s return response; } -/** - * @typedef {Object} HealthGetCacheRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface HealthGetCacheRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {HealthGetCacheRequestParams} params - */ -const healthGetCache = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const healthGetCache = async ({parseOutput = true, overrideForCli = false, sdk = undefined}: HealthGetCacheRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/health/cache'; @@ -123,18 +107,14 @@ const healthGetCache = async ({parseOutput = true, overrideForCli = false, sdk = return response; } -/** - * @typedef {Object} HealthGetCertificateRequestParams - * @property {string} domain string - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface HealthGetCertificateRequestParams { + domain?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {HealthGetCertificateRequestParams} params - */ -const healthGetCertificate = async ({domain,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const healthGetCertificate = async ({domain,parseOutput = true, overrideForCli = false, sdk = undefined}: HealthGetCertificateRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/health/certificate'; @@ -155,17 +135,13 @@ const healthGetCertificate = async ({domain,parseOutput = true, overrideForCli = return response; } -/** - * @typedef {Object} HealthGetDBRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface HealthGetDBRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {HealthGetDBRequestParams} params - */ -const healthGetDB = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const healthGetDB = async ({parseOutput = true, overrideForCli = false, sdk = undefined}: HealthGetDBRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/health/db'; @@ -183,17 +159,13 @@ const healthGetDB = async ({parseOutput = true, overrideForCli = false, sdk = un return response; } -/** - * @typedef {Object} HealthGetPubSubRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface HealthGetPubSubRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {HealthGetPubSubRequestParams} params - */ -const healthGetPubSub = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const healthGetPubSub = async ({parseOutput = true, overrideForCli = false, sdk = undefined}: HealthGetPubSubRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/health/pubsub'; @@ -211,18 +183,14 @@ const healthGetPubSub = async ({parseOutput = true, overrideForCli = false, sdk return response; } -/** - * @typedef {Object} HealthGetQueueBuildsRequestParams - * @property {number} threshold Queue size threshold. When hit (equal or higher), endpoint returns server error. Default value is 5000. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface HealthGetQueueBuildsRequestParams { + threshold?: number; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {HealthGetQueueBuildsRequestParams} params - */ -const healthGetQueueBuilds = async ({threshold,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const healthGetQueueBuilds = async ({threshold,parseOutput = true, overrideForCli = false, sdk = undefined}: HealthGetQueueBuildsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/health/queue/builds'; @@ -243,18 +211,14 @@ const healthGetQueueBuilds = async ({threshold,parseOutput = true, overrideForCl return response; } -/** - * @typedef {Object} HealthGetQueueCertificatesRequestParams - * @property {number} threshold Queue size threshold. When hit (equal or higher), endpoint returns server error. Default value is 5000. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface HealthGetQueueCertificatesRequestParams { + threshold?: number; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {HealthGetQueueCertificatesRequestParams} params - */ -const healthGetQueueCertificates = async ({threshold,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const healthGetQueueCertificates = async ({threshold,parseOutput = true, overrideForCli = false, sdk = undefined}: HealthGetQueueCertificatesRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/health/queue/certificates'; @@ -275,19 +239,15 @@ const healthGetQueueCertificates = async ({threshold,parseOutput = true, overrid return response; } -/** - * @typedef {Object} HealthGetQueueDatabasesRequestParams - * @property {string} name Queue name for which to check the queue size - * @property {number} threshold Queue size threshold. When hit (equal or higher), endpoint returns server error. Default value is 5000. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface HealthGetQueueDatabasesRequestParams { + name?: string; + threshold?: number; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {HealthGetQueueDatabasesRequestParams} params - */ -const healthGetQueueDatabases = async ({name,threshold,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const healthGetQueueDatabases = async ({name,threshold,parseOutput = true, overrideForCli = false, sdk = undefined}: HealthGetQueueDatabasesRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/health/queue/databases'; @@ -311,18 +271,14 @@ const healthGetQueueDatabases = async ({name,threshold,parseOutput = true, overr return response; } -/** - * @typedef {Object} HealthGetQueueDeletesRequestParams - * @property {number} threshold Queue size threshold. When hit (equal or higher), endpoint returns server error. Default value is 5000. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface HealthGetQueueDeletesRequestParams { + threshold?: number; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {HealthGetQueueDeletesRequestParams} params - */ -const healthGetQueueDeletes = async ({threshold,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const healthGetQueueDeletes = async ({threshold,parseOutput = true, overrideForCli = false, sdk = undefined}: HealthGetQueueDeletesRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/health/queue/deletes'; @@ -343,19 +299,15 @@ const healthGetQueueDeletes = async ({threshold,parseOutput = true, overrideForC return response; } -/** - * @typedef {Object} HealthGetFailedJobsRequestParams - * @property {Name} name The name of the queue - * @property {number} threshold Queue size threshold. When hit (equal or higher), endpoint returns server error. Default value is 5000. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface HealthGetFailedJobsRequestParams { + name: Name; + threshold?: number; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {HealthGetFailedJobsRequestParams} params - */ -const healthGetFailedJobs = async ({name,threshold,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const healthGetFailedJobs = async ({name,threshold,parseOutput = true, overrideForCli = false, sdk = undefined}: HealthGetFailedJobsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/health/queue/failed/{name}'.replace('{name}', name); @@ -376,18 +328,14 @@ const healthGetFailedJobs = async ({name,threshold,parseOutput = true, overrideF return response; } -/** - * @typedef {Object} HealthGetQueueFunctionsRequestParams - * @property {number} threshold Queue size threshold. When hit (equal or higher), endpoint returns server error. Default value is 5000. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface HealthGetQueueFunctionsRequestParams { + threshold?: number; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {HealthGetQueueFunctionsRequestParams} params - */ -const healthGetQueueFunctions = async ({threshold,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const healthGetQueueFunctions = async ({threshold,parseOutput = true, overrideForCli = false, sdk = undefined}: HealthGetQueueFunctionsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/health/queue/functions'; @@ -408,18 +356,14 @@ const healthGetQueueFunctions = async ({threshold,parseOutput = true, overrideFo return response; } -/** - * @typedef {Object} HealthGetQueueLogsRequestParams - * @property {number} threshold Queue size threshold. When hit (equal or higher), endpoint returns server error. Default value is 5000. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface HealthGetQueueLogsRequestParams { + threshold?: number; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {HealthGetQueueLogsRequestParams} params - */ -const healthGetQueueLogs = async ({threshold,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const healthGetQueueLogs = async ({threshold,parseOutput = true, overrideForCli = false, sdk = undefined}: HealthGetQueueLogsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/health/queue/logs'; @@ -440,18 +384,14 @@ const healthGetQueueLogs = async ({threshold,parseOutput = true, overrideForCli return response; } -/** - * @typedef {Object} HealthGetQueueMailsRequestParams - * @property {number} threshold Queue size threshold. When hit (equal or higher), endpoint returns server error. Default value is 5000. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface HealthGetQueueMailsRequestParams { + threshold?: number; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {HealthGetQueueMailsRequestParams} params - */ -const healthGetQueueMails = async ({threshold,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const healthGetQueueMails = async ({threshold,parseOutput = true, overrideForCli = false, sdk = undefined}: HealthGetQueueMailsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/health/queue/mails'; @@ -472,18 +412,14 @@ const healthGetQueueMails = async ({threshold,parseOutput = true, overrideForCli return response; } -/** - * @typedef {Object} HealthGetQueueMessagingRequestParams - * @property {number} threshold Queue size threshold. When hit (equal or higher), endpoint returns server error. Default value is 5000. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface HealthGetQueueMessagingRequestParams { + threshold?: number; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {HealthGetQueueMessagingRequestParams} params - */ -const healthGetQueueMessaging = async ({threshold,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const healthGetQueueMessaging = async ({threshold,parseOutput = true, overrideForCli = false, sdk = undefined}: HealthGetQueueMessagingRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/health/queue/messaging'; @@ -504,18 +440,14 @@ const healthGetQueueMessaging = async ({threshold,parseOutput = true, overrideFo return response; } -/** - * @typedef {Object} HealthGetQueueMigrationsRequestParams - * @property {number} threshold Queue size threshold. When hit (equal or higher), endpoint returns server error. Default value is 5000. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface HealthGetQueueMigrationsRequestParams { + threshold?: number; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {HealthGetQueueMigrationsRequestParams} params - */ -const healthGetQueueMigrations = async ({threshold,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const healthGetQueueMigrations = async ({threshold,parseOutput = true, overrideForCli = false, sdk = undefined}: HealthGetQueueMigrationsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/health/queue/migrations'; @@ -536,18 +468,14 @@ const healthGetQueueMigrations = async ({threshold,parseOutput = true, overrideF return response; } -/** - * @typedef {Object} HealthGetQueueStatsResourcesRequestParams - * @property {number} threshold Queue size threshold. When hit (equal or higher), endpoint returns server error. Default value is 5000. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface HealthGetQueueStatsResourcesRequestParams { + threshold?: number; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {HealthGetQueueStatsResourcesRequestParams} params - */ -const healthGetQueueStatsResources = async ({threshold,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const healthGetQueueStatsResources = async ({threshold,parseOutput = true, overrideForCli = false, sdk = undefined}: HealthGetQueueStatsResourcesRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/health/queue/stats-resources'; @@ -568,18 +496,14 @@ const healthGetQueueStatsResources = async ({threshold,parseOutput = true, overr return response; } -/** - * @typedef {Object} HealthGetQueueUsageRequestParams - * @property {number} threshold Queue size threshold. When hit (equal or higher), endpoint returns server error. Default value is 5000. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface HealthGetQueueUsageRequestParams { + threshold?: number; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {HealthGetQueueUsageRequestParams} params - */ -const healthGetQueueUsage = async ({threshold,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const healthGetQueueUsage = async ({threshold,parseOutput = true, overrideForCli = false, sdk = undefined}: HealthGetQueueUsageRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/health/queue/stats-usage'; @@ -600,18 +524,14 @@ const healthGetQueueUsage = async ({threshold,parseOutput = true, overrideForCli return response; } -/** - * @typedef {Object} HealthGetQueueWebhooksRequestParams - * @property {number} threshold Queue size threshold. When hit (equal or higher), endpoint returns server error. Default value is 5000. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface HealthGetQueueWebhooksRequestParams { + threshold?: number; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {HealthGetQueueWebhooksRequestParams} params - */ -const healthGetQueueWebhooks = async ({threshold,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const healthGetQueueWebhooks = async ({threshold,parseOutput = true, overrideForCli = false, sdk = undefined}: HealthGetQueueWebhooksRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/health/queue/webhooks'; @@ -632,17 +552,13 @@ const healthGetQueueWebhooks = async ({threshold,parseOutput = true, overrideFor return response; } -/** - * @typedef {Object} HealthGetStorageRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface HealthGetStorageRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {HealthGetStorageRequestParams} params - */ -const healthGetStorage = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const healthGetStorage = async ({parseOutput = true, overrideForCli = false, sdk = undefined}: HealthGetStorageRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/health/storage'; @@ -660,17 +576,13 @@ const healthGetStorage = async ({parseOutput = true, overrideForCli = false, sdk return response; } -/** - * @typedef {Object} HealthGetStorageLocalRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface HealthGetStorageLocalRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {HealthGetStorageLocalRequestParams} params - */ -const healthGetStorageLocal = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const healthGetStorageLocal = async ({parseOutput = true, overrideForCli = false, sdk = undefined}: HealthGetStorageLocalRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/health/storage/local'; @@ -688,17 +600,13 @@ const healthGetStorageLocal = async ({parseOutput = true, overrideForCli = false return response; } -/** - * @typedef {Object} HealthGetTimeRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface HealthGetTimeRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {HealthGetTimeRequestParams} params - */ -const healthGetTime = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const healthGetTime = async ({parseOutput = true, overrideForCli = false, sdk = undefined}: HealthGetTimeRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/health/time'; @@ -842,28 +750,4 @@ health .description(`Check the Appwrite server time is synced with Google remote NTP server. We use this technology to smoothly handle leap seconds with no disruptive events. The [Network Time Protocol](https://en.wikipedia.org/wiki/Network_Time_Protocol) (NTP) is used by hundreds of millions of computers and devices to synchronize their clocks over the Internet. If your computer sets its own clock, it likely uses NTP.`) .action(actionRunner(healthGetTime)) -module.exports = { - health, - healthGet, - healthGetAntivirus, - healthGetCache, - healthGetCertificate, - healthGetDB, - healthGetPubSub, - healthGetQueueBuilds, - healthGetQueueCertificates, - healthGetQueueDatabases, - healthGetQueueDeletes, - healthGetFailedJobs, - healthGetQueueFunctions, - healthGetQueueLogs, - healthGetQueueMails, - healthGetQueueMessaging, - healthGetQueueMigrations, - healthGetQueueStatsResources, - healthGetQueueUsage, - healthGetQueueWebhooks, - healthGetStorage, - healthGetStorageLocal, - healthGetTime -}; + diff --git a/lib/commands/init.js b/lib/commands/init.ts similarity index 84% rename from lib/commands/init.js rename to lib/commands/init.ts index 0f653a19..ab03fa2a 100644 --- a/lib/commands/init.js +++ b/lib/commands/init.ts @@ -1,18 +1,17 @@ -const fs = require("fs"); -const path = require("path"); -const childProcess = require('child_process'); -const { Command } = require("commander"); -const inquirer = require("inquirer"); -const { fetch } = require("undici"); -const { projectsCreate, projectsGet } = require("./projects"); -const { storageCreateBucket } = require("./storage"); -const { messagingCreateTopic } = require("./messaging"); -const { functionsCreate } = require("./functions"); -const { databasesCreateCollection } = require("./databases"); -const { pullResources } = require("./pull"); -const ID = require("../id"); -const { localConfig, globalConfig } = require("../config"); -const { +import fs = require('fs'); +import path = require('path'); +import childProcess = require('child_process'); +import { Command } from 'commander'; +import inquirer from 'inquirer'; +import { projectsCreate, projectsGet } from './projects'; +import { storageCreateBucket } from './storage'; +import { messagingCreateTopic } from './messaging'; +import { functionsCreate } from './functions'; +import { databasesCreateCollection } from './databases'; +import { pullResources } from './pull'; +import ID from '../id'; +import { localConfig, globalConfig } from '../config'; +import { questionsCreateFunction, questionsCreateFunctionSelectTemplate, questionsCreateSite, @@ -24,15 +23,15 @@ const { questionsInitProjectAutopull, questionsInitResources, questionsCreateTeam -} = require("../questions"); -const { cliConfig, success, log, hint, error, actionRunner, commandDescriptions } = require("../parser"); -const { accountGet } = require("./account"); -const { sitesListTemplates } = require("./sites"); -const { sdkForConsole } = require("../sdks"); -const { isCloud } = require('../utils'); - -const initResources = async () => { - const actions = { +} from '../questions'; +import { cliConfig, success, log, hint, error, actionRunner, commandDescriptions } from '../parser'; +import { accountGet } from './account'; +import { sitesListTemplates } from './sites'; +import { sdkForConsole } from '../sdks'; +import { isCloud } from '../utils'; + +const initResources = async (): Promise => { + const actions: Record Promise> = { function: initFunction, site: initSite, table: initTable, @@ -50,8 +49,14 @@ const initResources = async () => { } }; -const initProject = async ({ organizationId, projectId, projectName } = {}) => { - let response = {}; +interface InitProjectOptions { + organizationId?: string; + projectId?: string; + projectName?: string; +} + +const initProject = async ({ organizationId, projectId, projectName }: InitProjectOptions = {}): Promise => { + let response: any = {}; try { if (globalConfig.getEndpoint() === '' || globalConfig.getCookie() === '') { @@ -68,7 +73,7 @@ const initProject = async ({ organizationId, projectId, projectName } = {}) => { process.exit(1); } - let answers = {}; + let answers: any = {}; if (!organizationId && !projectId && !projectName) { answers = await inquirer.prompt(questionsInitProject) @@ -86,7 +91,7 @@ const initProject = async ({ organizationId, projectId, projectName } = {}) => { try { await projectsGet({ projectId, parseOutput: false }); - } catch (e) { + } catch (e: any) { if (e.code === 404) { answers.start = 'new'; answers.id = answers.project; @@ -137,7 +142,7 @@ const initProject = async ({ organizationId, projectId, projectName } = {}) => { hint("Next you can use 'appwrite init' to create resources in your project, or use 'appwrite pull' and 'appwrite push' to synchronize your project.") } -const initBucket = async () => { +const initBucket = async (): Promise => { const answers = await inquirer.prompt(questionsCreateBucket) localConfig.addBucket({ @@ -150,7 +155,7 @@ const initBucket = async () => { log("Next you can use 'appwrite push bucket' to deploy the changes."); }; -const initTeam = async () => { +const initTeam = async (): Promise => { const answers = await inquirer.prompt(questionsCreateTeam) localConfig.addTeam({ @@ -162,7 +167,7 @@ const initTeam = async () => { log("Next you can use 'appwrite push team' to deploy the changes."); }; -const initTable = async () => { +const initTable = async (): Promise => { const answers = await inquirer.prompt(questionsCreateTable) const newDatabase = (answers.method ?? '').toLowerCase() !== 'existing'; @@ -196,7 +201,7 @@ const initTable = async () => { log("Next you can use 'appwrite push table' to deploy the changes."); }; -const initCollection = async () => { +const initCollection = async (): Promise => { const answers = await inquirer.prompt(questionsCreateCollection) const newDatabase = (answers.method ?? '').toLowerCase() !== 'existing'; @@ -229,7 +234,7 @@ const initCollection = async () => { log("Next you can use 'appwrite push collection' to deploy the changes."); }; -const initTopic = async () => { +const initTopic = async (): Promise => { const answers = await inquirer.prompt(questionsCreateMessagingTopic) localConfig.addMessagingTopic({ @@ -242,7 +247,7 @@ const initTopic = async () => { log("Next you can use 'appwrite push topic' to deploy the changes."); }; -const initFunction = async () => { +const initFunction = async (): Promise => { process.chdir(localConfig.configDirectoryPath) // TODO: Add CI/CD support (ID, name, runtime) @@ -273,11 +278,11 @@ const initFunction = async () => { log(`Installation command for this runtime not found. You will be asked to configure the install command when you first push the function.`); } - fs.mkdirSync(functionDir, "777"); - fs.mkdirSync(templatesDir, "777"); + fs.mkdirSync(functionDir, { mode: 0o777 }); + fs.mkdirSync(templatesDir, { mode: 0o777 }); const repo = "https://github.com/appwrite/templates"; const api = `https://api.github.com/repos/appwrite/templates/contents/${answers.runtime.name}` - let selected = { template: 'starter' }; + let selected: { template: string } = { template: 'starter' }; const sparse = (selected ? `${answers.runtime.name}/${selected.template}` : answers.runtime.name).toLowerCase(); @@ -295,20 +300,20 @@ const initFunction = async () => { try { childProcess.execSync(gitInitCommands, { stdio: 'pipe', cwd: templatesDir }); childProcess.execSync(gitPullCommands, { stdio: 'pipe', cwd: templatesDir }); - } catch (error) { + } catch (err: any) { /* Specialised errors with recommended actions to take */ - if (error.message.includes('error: unknown option')) { - throw new Error(`${error.message} \n\nSuggestion: Try updating your git to the latest version, then trying to run this command again.`) - } else if (error.message.includes('is not recognized as an internal or external command,') || error.message.includes('command not found')) { - throw new Error(`${error.message} \n\nSuggestion: It appears that git is not installed, try installing git then trying to run this command again.`) + if (err.message.includes('error: unknown option')) { + throw new Error(`${err.message} \n\nSuggestion: Try updating your git to the latest version, then trying to run this command again.`) + } else if (err.message.includes('is not recognized as an internal or external command,') || err.message.includes('command not found')) { + throw new Error(`${err.message} \n\nSuggestion: It appears that git is not installed, try installing git then trying to run this command again.`) } else { - throw error; + throw err; } } fs.rmSync(path.join(templatesDir, ".git"), { recursive: true }); if (!selected) { - const templates = []; + const templates: string[] = []; templates.push(...fs.readdirSync(runtimeDir, { withFileTypes: true }) .filter(item => item.isDirectory() && item.name !== 'starter') .map(dirent => dirent.name)); @@ -319,10 +324,10 @@ const initFunction = async () => { } } - const copyRecursiveSync = (src, dest) => { + const copyRecursiveSync = (src: string, dest: string): void => { let exists = fs.existsSync(src); let stats = exists && fs.statSync(src); - let isDirectory = exists && stats.isDirectory(); + let isDirectory = exists && stats && stats.isDirectory(); if (isDirectory) { if (!fs.existsSync(dest)) { fs.mkdirSync(dest); @@ -369,7 +374,7 @@ const initFunction = async () => { log("Next you can use 'appwrite run function' to develop a function locally. To deploy the function, use 'appwrite push function'"); } -const initSite = async () => { +const initSite = async (): Promise => { process.chdir(localConfig.configDirectoryPath) const answers = await inquirer.prompt(questionsCreateSite); @@ -390,7 +395,7 @@ const initSite = async () => { throw new Error(`( ${siteName} ) already exists in the current directory. Please choose another name.`); } - let templateDetails; + let templateDetails: any; try { const response = await sitesListTemplates({ frameworks: [answers.framework.key], @@ -402,12 +407,12 @@ const initSite = async () => { throw new Error(`No starter template found for framework ${answers.framework.key}`); } templateDetails = response.templates[0]; - } catch (error) { - throw new Error(`Failed to fetch template for framework ${answers.framework.key}: ${error.message}`); + } catch (err: any) { + throw new Error(`Failed to fetch template for framework ${answers.framework.key}: ${err.message}`); } - fs.mkdirSync(siteDir, "777"); - fs.mkdirSync(templatesDir, "777"); + fs.mkdirSync(siteDir, { mode: 0o777 }); + fs.mkdirSync(templatesDir, { mode: 0o777 }); const repo = `https://github.com/${templateDetails.providerOwner}/${templateDetails.providerRepositoryId}`; let selected = { template: templateDetails.frameworks[0].providerRootDirectory }; @@ -451,23 +456,23 @@ const initSite = async () => { /* Execute the child process but do not print any std output */ try { childProcess.execSync(gitCloneCommands, { stdio: 'pipe', cwd: templatesDir }); - } catch (error) { + } catch (err: any) { /* Specialised errors with recommended actions to take */ - if (error.message.includes('error: unknown option')) { - throw new Error(`${error.message} \n\nSuggestion: Try updating your git to the latest version, then trying to run this command again.`) - } else if (error.message.includes('is not recognized as an internal or external command,') || error.message.includes('command not found')) { - throw new Error(`${error.message} \n\nSuggestion: It appears that git is not installed, try installing git then trying to run this command again.`) + if (err.message.includes('error: unknown option')) { + throw new Error(`${err.message} \n\nSuggestion: Try updating your git to the latest version, then trying to run this command again.`) + } else if (err.message.includes('is not recognized as an internal or external command,') || err.message.includes('command not found')) { + throw new Error(`${err.message} \n\nSuggestion: It appears that git is not installed, try installing git then trying to run this command again.`) } else { - throw error; + throw err; } } fs.rmSync(path.join(templatesDir, ".git"), { recursive: true }); - const copyRecursiveSync = (src, dest) => { + const copyRecursiveSync = (src: string, dest: string): void => { let exists = fs.existsSync(src); let stats = exists && fs.statSync(src); - let isDirectory = exists && stats.isDirectory(); + let isDirectory = exists && stats && stats.isDirectory(); if (isDirectory) { if (!fs.existsSync(dest)) { fs.mkdirSync(dest); @@ -491,9 +496,9 @@ const initSite = async () => { newReadmeFile.splice(1, 2); fs.writeFileSync(readmePath, newReadmeFile.join('\n')); - let vars = (templateDetails.variables ?? []).map(variable => { + let vars = (templateDetails.variables ?? []).map((variable: any) => { let value = variable.value; - const replacements = { + const replacements: Record = { '{apiEndpoint}': globalConfig.getEndpoint(), '{projectId}': localConfig.getProject().projectId, '{projectName}': localConfig.getProject().projectName, @@ -551,7 +556,7 @@ const initSite = async () => { log("Next you can use 'appwrite push site' to deploy the changes."); }; -const init = new Command("init") +export const init = new Command("init") .description(commandDescriptions['init']) .action(actionRunner(initResources)); @@ -605,6 +610,3 @@ init .description("Init a new Appwrite topic") .action(actionRunner(initTopic)); -module.exports = { - init, -}; diff --git a/lib/commands/locale.js b/lib/commands/locale.ts similarity index 54% rename from lib/commands/locale.js rename to lib/commands/locale.ts index db1a70d9..e80a44a5 100644 --- a/lib/commands/locale.js +++ b/lib/commands/locale.ts @@ -1,31 +1,27 @@ -const fs = require('fs'); -const pathLib = require('path'); -const tar = require("tar"); -const ignore = require("ignore"); -const { promisify } = require('util'); -const libClient = require('../client.js'); -const { getAllFiles, showConsoleLink } = require('../utils.js'); -const { Command } = require('commander'); -const { sdkForProject, sdkForConsole } = require('../sdks') -const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } = require('../parser') -const { localConfig, globalConfig } = require("../config"); -const { File } = require('undici'); -const { ReadableStream } = require('stream/web'); - -/** - * @param {fs.ReadStream} readStream - * @returns {ReadableStream} - */ -function convertReadStreamToReadableStream(readStream) { +import fs = require('fs'); +import pathLib = require('path'); +import tar = require('tar'); +import ignore = require('ignore'); +import { promisify } from 'util'; +import Client from '../client'; +import { getAllFiles, showConsoleLink } from '../utils'; +import { Command } from 'commander'; +import { sdkForProject, sdkForConsole } from '../sdks'; +import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } from '../parser'; +import { localConfig, globalConfig } from '../config'; +import { File } from 'undici'; +import { ReadableStream } from 'stream/web'; + +function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ start(controller) { - readStream.on("data", (chunk) => { + readStream.on("data", (chunk: Buffer) => { controller.enqueue(chunk); }); readStream.on("end", () => { controller.close(); }); - readStream.on("error", (err) => { + readStream.on("error", (err: Error) => { controller.error(err); }); }, @@ -35,21 +31,17 @@ function convertReadStreamToReadableStream(readStream) { }); } -const locale = new Command("locale").description(commandDescriptions['locale'] ?? '').configureHelp({ +export const locale = new Command("locale").description(commandDescriptions['locale'] ?? '').configureHelp({ helpWidth: process.stdout.columns || 80 }) -/** - * @typedef {Object} LocaleGetRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {LocaleGetRequestParams} params - */ -const localeGet = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface LocaleGetRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const localeGet = async ({parseOutput = true, overrideForCli = false, sdk = undefined}: LocaleGetRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/locale'; @@ -67,17 +59,13 @@ const localeGet = async ({parseOutput = true, overrideForCli = false, sdk = unde return response; } -/** - * @typedef {Object} LocaleListCodesRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {LocaleListCodesRequestParams} params - */ -const localeListCodes = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface LocaleListCodesRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const localeListCodes = async ({parseOutput = true, overrideForCli = false, sdk = undefined}: LocaleListCodesRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/locale/codes'; @@ -95,17 +83,13 @@ const localeListCodes = async ({parseOutput = true, overrideForCli = false, sdk return response; } -/** - * @typedef {Object} LocaleListContinentsRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {LocaleListContinentsRequestParams} params - */ -const localeListContinents = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface LocaleListContinentsRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const localeListContinents = async ({parseOutput = true, overrideForCli = false, sdk = undefined}: LocaleListContinentsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/locale/continents'; @@ -123,17 +107,13 @@ const localeListContinents = async ({parseOutput = true, overrideForCli = false, return response; } -/** - * @typedef {Object} LocaleListCountriesRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {LocaleListCountriesRequestParams} params - */ -const localeListCountries = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface LocaleListCountriesRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const localeListCountries = async ({parseOutput = true, overrideForCli = false, sdk = undefined}: LocaleListCountriesRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/locale/countries'; @@ -151,17 +131,13 @@ const localeListCountries = async ({parseOutput = true, overrideForCli = false, return response; } -/** - * @typedef {Object} LocaleListCountriesEURequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {LocaleListCountriesEURequestParams} params - */ -const localeListCountriesEU = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface LocaleListCountriesEURequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const localeListCountriesEU = async ({parseOutput = true, overrideForCli = false, sdk = undefined}: LocaleListCountriesEURequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/locale/countries/eu'; @@ -179,17 +155,13 @@ const localeListCountriesEU = async ({parseOutput = true, overrideForCli = false return response; } -/** - * @typedef {Object} LocaleListCountriesPhonesRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {LocaleListCountriesPhonesRequestParams} params - */ -const localeListCountriesPhones = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface LocaleListCountriesPhonesRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const localeListCountriesPhones = async ({parseOutput = true, overrideForCli = false, sdk = undefined}: LocaleListCountriesPhonesRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/locale/countries/phones'; @@ -207,17 +179,13 @@ const localeListCountriesPhones = async ({parseOutput = true, overrideForCli = f return response; } -/** - * @typedef {Object} LocaleListCurrenciesRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {LocaleListCurrenciesRequestParams} params - */ -const localeListCurrencies = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface LocaleListCurrenciesRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const localeListCurrencies = async ({parseOutput = true, overrideForCli = false, sdk = undefined}: LocaleListCurrenciesRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/locale/currencies'; @@ -235,17 +203,13 @@ const localeListCurrencies = async ({parseOutput = true, overrideForCli = false, return response; } -/** - * @typedef {Object} LocaleListLanguagesRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {LocaleListLanguagesRequestParams} params - */ -const localeListLanguages = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface LocaleListLanguagesRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const localeListLanguages = async ({parseOutput = true, overrideForCli = false, sdk = undefined}: LocaleListLanguagesRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/locale/languages'; @@ -303,14 +267,4 @@ locale .description(`List of all languages classified by ISO 639-1 including 2-letter code, name in English, and name in the respective language.`) .action(actionRunner(localeListLanguages)) -module.exports = { - locale, - localeGet, - localeListCodes, - localeListContinents, - localeListCountries, - localeListCountriesEU, - localeListCountriesPhones, - localeListCurrencies, - localeListLanguages -}; + diff --git a/lib/commands/messaging.js b/lib/commands/messaging.ts similarity index 59% rename from lib/commands/messaging.js rename to lib/commands/messaging.ts index fc4a400b..92d4c854 100644 --- a/lib/commands/messaging.js +++ b/lib/commands/messaging.ts @@ -1,31 +1,27 @@ -const fs = require('fs'); -const pathLib = require('path'); -const tar = require("tar"); -const ignore = require("ignore"); -const { promisify } = require('util'); -const libClient = require('../client.js'); -const { getAllFiles, showConsoleLink } = require('../utils.js'); -const { Command } = require('commander'); -const { sdkForProject, sdkForConsole } = require('../sdks') -const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } = require('../parser') -const { localConfig, globalConfig } = require("../config"); -const { File } = require('undici'); -const { ReadableStream } = require('stream/web'); - -/** - * @param {fs.ReadStream} readStream - * @returns {ReadableStream} - */ -function convertReadStreamToReadableStream(readStream) { +import fs = require('fs'); +import pathLib = require('path'); +import tar = require('tar'); +import ignore = require('ignore'); +import { promisify } from 'util'; +import Client from '../client'; +import { getAllFiles, showConsoleLink } from '../utils'; +import { Command } from 'commander'; +import { sdkForProject, sdkForConsole } from '../sdks'; +import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } from '../parser'; +import { localConfig, globalConfig } from '../config'; +import { File } from 'undici'; +import { ReadableStream } from 'stream/web'; + +function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ start(controller) { - readStream.on("data", (chunk) => { + readStream.on("data", (chunk: Buffer) => { controller.enqueue(chunk); }); readStream.on("end", () => { controller.close(); }); - readStream.on("error", (err) => { + readStream.on("error", (err: Error) => { controller.error(err); }); }, @@ -35,24 +31,21 @@ function convertReadStreamToReadableStream(readStream) { }); } -const messaging = new Command("messaging").description(commandDescriptions['messaging'] ?? '').configureHelp({ +export const messaging = new Command("messaging").description(commandDescriptions['messaging'] ?? '').configureHelp({ helpWidth: process.stdout.columns || 80 }) -/** - * @typedef {Object} MessagingListMessagesRequestParams - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: scheduledAt, deliveredAt, deliveredTotal, status, description, providerType - * @property {string} search Search term to filter your list results. Max length: 256 chars. - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingListMessagesRequestParams} params - */ -const messagingListMessages = async ({queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface MessagingListMessagesRequestParams { + queries?: string[]; + search?: string; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const messagingListMessages = async ({queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: MessagingListMessagesRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/messages'; @@ -73,7 +66,7 @@ const messagingListMessages = async ({queries,search,total,parseOutput = true, o }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('messaging', 'listMessages'); } else { parse(response) @@ -83,29 +76,25 @@ const messagingListMessages = async ({queries,search,total,parseOutput = true, o return response; } -/** - * @typedef {Object} MessagingCreateEmailRequestParams - * @property {string} messageId Message ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} subject Email Subject. - * @property {string} content Email Content. - * @property {string[]} topics List of Topic IDs. - * @property {string[]} users List of User IDs. - * @property {string[]} targets List of Targets IDs. - * @property {string[]} cc Array of target IDs to be added as CC. - * @property {string[]} bcc Array of target IDs to be added as BCC. - * @property {string[]} attachments Array of compound ID strings of bucket IDs and file IDs to be attached to the email. They should be formatted as <BUCKET_ID>:<FILE_ID>. - * @property {boolean} draft Is message a draft - * @property {boolean} html Is content of type HTML - * @property {string} scheduledAt Scheduled delivery time for message in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. DateTime value must be in future. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingCreateEmailRequestParams} params - */ -const messagingCreateEmail = async ({messageId,subject,content,topics,users,targets,cc,bcc,attachments,draft,html,scheduledAt,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingCreateEmailRequestParams { + messageId: string; + subject: string; + content: string; + topics?: string[]; + users?: string[]; + targets?: string[]; + cc?: string[]; + bcc?: string[]; + attachments?: string[]; + draft?: boolean; + html?: boolean; + scheduledAt?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingCreateEmail = async ({messageId,subject,content,topics,users,targets,cc,bcc,attachments,draft,html,scheduledAt,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingCreateEmailRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/messages/email'; @@ -166,29 +155,25 @@ const messagingCreateEmail = async ({messageId,subject,content,topics,users,targ return response; } -/** - * @typedef {Object} MessagingUpdateEmailRequestParams - * @property {string} messageId Message ID. - * @property {string[]} topics List of Topic IDs. - * @property {string[]} users List of User IDs. - * @property {string[]} targets List of Targets IDs. - * @property {string} subject Email Subject. - * @property {string} content Email Content. - * @property {boolean} draft Is message a draft - * @property {boolean} html Is content of type HTML - * @property {string[]} cc Array of target IDs to be added as CC. - * @property {string[]} bcc Array of target IDs to be added as BCC. - * @property {string} scheduledAt Scheduled delivery time for message in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. DateTime value must be in future. - * @property {string[]} attachments Array of compound ID strings of bucket IDs and file IDs to be attached to the email. They should be formatted as <BUCKET_ID>:<FILE_ID>. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingUpdateEmailRequestParams} params - */ -const messagingUpdateEmail = async ({messageId,topics,users,targets,subject,content,draft,html,cc,bcc,scheduledAt,attachments,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingUpdateEmailRequestParams { + messageId: string; + topics?: string[]; + users?: string[]; + targets?: string[]; + subject?: string; + content?: string; + draft?: boolean; + html?: boolean; + cc?: string[]; + bcc?: string[]; + scheduledAt?: string; + attachments?: string[]; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingUpdateEmail = async ({messageId,topics,users,targets,subject,content,draft,html,cc,bcc,scheduledAt,attachments,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingUpdateEmailRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/messages/email/{messageId}'.replace('{messageId}', messageId); @@ -246,36 +231,32 @@ const messagingUpdateEmail = async ({messageId,topics,users,targets,subject,cont return response; } -/** - * @typedef {Object} MessagingCreatePushRequestParams - * @property {string} messageId Message ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} title Title for push notification. - * @property {string} body Body for push notification. - * @property {string[]} topics List of Topic IDs. - * @property {string[]} users List of User IDs. - * @property {string[]} targets List of Targets IDs. - * @property {object} data Additional key-value pair data for push notification. - * @property {string} action Action for push notification. - * @property {string} image Image for push notification. Must be a compound bucket ID to file ID of a jpeg, png, or bmp image in Appwrite Storage. It should be formatted as <BUCKET_ID>:<FILE_ID>. - * @property {string} icon Icon for push notification. Available only for Android and Web Platform. - * @property {string} sound Sound for push notification. Available only for Android and iOS Platform. - * @property {string} color Color for push notification. Available only for Android Platform. - * @property {string} tag Tag for push notification. Available only for Android Platform. - * @property {number} badge Badge for push notification. Available only for iOS Platform. - * @property {boolean} draft Is message a draft - * @property {string} scheduledAt Scheduled delivery time for message in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. DateTime value must be in future. - * @property {boolean} contentAvailable If set to true, the notification will be delivered in the background. Available only for iOS Platform. - * @property {boolean} critical If set to true, the notification will be marked as critical. This requires the app to have the critical notification entitlement. Available only for iOS Platform. - * @property {MessagePriority} priority Set the notification priority. "normal" will consider device state and may not deliver notifications immediately. "high" will always attempt to immediately deliver the notification. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingCreatePushRequestParams} params - */ -const messagingCreatePush = async ({messageId,title,body,topics,users,targets,data,action,image,icon,sound,color,tag,badge,draft,scheduledAt,contentAvailable,critical,priority,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingCreatePushRequestParams { + messageId: string; + title?: string; + body?: string; + topics?: string[]; + users?: string[]; + targets?: string[]; + data?: object; + action?: string; + image?: string; + icon?: string; + sound?: string; + color?: string; + tag?: string; + badge?: number; + draft?: boolean; + scheduledAt?: string; + contentAvailable?: boolean; + critical?: boolean; + priority?: MessagePriority; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingCreatePush = async ({messageId,title,body,topics,users,targets,data,action,image,icon,sound,color,tag,badge,draft,scheduledAt,contentAvailable,critical,priority,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingCreatePushRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/messages/push'; @@ -354,36 +335,32 @@ const messagingCreatePush = async ({messageId,title,body,topics,users,targets,da return response; } -/** - * @typedef {Object} MessagingUpdatePushRequestParams - * @property {string} messageId Message ID. - * @property {string[]} topics List of Topic IDs. - * @property {string[]} users List of User IDs. - * @property {string[]} targets List of Targets IDs. - * @property {string} title Title for push notification. - * @property {string} body Body for push notification. - * @property {object} data Additional Data for push notification. - * @property {string} action Action for push notification. - * @property {string} image Image for push notification. Must be a compound bucket ID to file ID of a jpeg, png, or bmp image in Appwrite Storage. It should be formatted as <BUCKET_ID>:<FILE_ID>. - * @property {string} icon Icon for push notification. Available only for Android and Web platforms. - * @property {string} sound Sound for push notification. Available only for Android and iOS platforms. - * @property {string} color Color for push notification. Available only for Android platforms. - * @property {string} tag Tag for push notification. Available only for Android platforms. - * @property {number} badge Badge for push notification. Available only for iOS platforms. - * @property {boolean} draft Is message a draft - * @property {string} scheduledAt Scheduled delivery time for message in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. DateTime value must be in future. - * @property {boolean} contentAvailable If set to true, the notification will be delivered in the background. Available only for iOS Platform. - * @property {boolean} critical If set to true, the notification will be marked as critical. This requires the app to have the critical notification entitlement. Available only for iOS Platform. - * @property {MessagePriority} priority Set the notification priority. "normal" will consider device battery state and may send notifications later. "high" will always attempt to immediately deliver the notification. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingUpdatePushRequestParams} params - */ -const messagingUpdatePush = async ({messageId,topics,users,targets,title,body,data,action,image,icon,sound,color,tag,badge,draft,scheduledAt,contentAvailable,critical,priority,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingUpdatePushRequestParams { + messageId: string; + topics?: string[]; + users?: string[]; + targets?: string[]; + title?: string; + body?: string; + data?: object; + action?: string; + image?: string; + icon?: string; + sound?: string; + color?: string; + tag?: string; + badge?: number; + draft?: boolean; + scheduledAt?: string; + contentAvailable?: boolean; + critical?: boolean; + priority?: MessagePriority; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingUpdatePush = async ({messageId,topics,users,targets,title,body,data,action,image,icon,sound,color,tag,badge,draft,scheduledAt,contentAvailable,critical,priority,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingUpdatePushRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/messages/push/{messageId}'.replace('{messageId}', messageId); @@ -459,24 +436,20 @@ const messagingUpdatePush = async ({messageId,topics,users,targets,title,body,da return response; } -/** - * @typedef {Object} MessagingCreateSMSRequestParams - * @property {string} messageId Message ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} content SMS Content. - * @property {string[]} topics List of Topic IDs. - * @property {string[]} users List of User IDs. - * @property {string[]} targets List of Targets IDs. - * @property {boolean} draft Is message a draft - * @property {string} scheduledAt Scheduled delivery time for message in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. DateTime value must be in future. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingCreateSMSRequestParams} params - */ -const messagingCreateSMS = async ({messageId,content,topics,users,targets,draft,scheduledAt,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingCreateSMSRequestParams { + messageId: string; + content: string; + topics?: string[]; + users?: string[]; + targets?: string[]; + draft?: boolean; + scheduledAt?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingCreateSMS = async ({messageId,content,topics,users,targets,draft,scheduledAt,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingCreateSMSRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/messages/sms'; @@ -519,24 +492,20 @@ const messagingCreateSMS = async ({messageId,content,topics,users,targets,draft, return response; } -/** - * @typedef {Object} MessagingUpdateSMSRequestParams - * @property {string} messageId Message ID. - * @property {string[]} topics List of Topic IDs. - * @property {string[]} users List of User IDs. - * @property {string[]} targets List of Targets IDs. - * @property {string} content Email Content. - * @property {boolean} draft Is message a draft - * @property {string} scheduledAt Scheduled delivery time for message in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. DateTime value must be in future. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingUpdateSMSRequestParams} params - */ -const messagingUpdateSMS = async ({messageId,topics,users,targets,content,draft,scheduledAt,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingUpdateSMSRequestParams { + messageId: string; + topics?: string[]; + users?: string[]; + targets?: string[]; + content?: string; + draft?: boolean; + scheduledAt?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingUpdateSMS = async ({messageId,topics,users,targets,content,draft,scheduledAt,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingUpdateSMSRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/messages/sms/{messageId}'.replace('{messageId}', messageId); @@ -576,18 +545,15 @@ const messagingUpdateSMS = async ({messageId,topics,users,targets,content,draft, return response; } -/** - * @typedef {Object} MessagingGetMessageRequestParams - * @property {string} messageId Message ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface MessagingGetMessageRequestParams { + messageId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {MessagingGetMessageRequestParams} params - */ -const messagingGetMessage = async ({messageId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const messagingGetMessage = async ({messageId,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: MessagingGetMessageRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/messages/{messageId}'.replace('{messageId}', messageId); @@ -599,7 +565,7 @@ const messagingGetMessage = async ({messageId,parseOutput = true, overrideForCli }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('messaging', 'getMessage', messageId); } else { parse(response) @@ -609,18 +575,14 @@ const messagingGetMessage = async ({messageId,parseOutput = true, overrideForCli return response; } -/** - * @typedef {Object} MessagingDeleteRequestParams - * @property {string} messageId Message ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface MessagingDeleteRequestParams { + messageId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {MessagingDeleteRequestParams} params - */ -const messagingDelete = async ({messageId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const messagingDelete = async ({messageId,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingDeleteRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/messages/{messageId}'.replace('{messageId}', messageId); @@ -639,20 +601,17 @@ const messagingDelete = async ({messageId,parseOutput = true, overrideForCli = f return response; } -/** - * @typedef {Object} MessagingListMessageLogsRequestParams - * @property {string} messageId Message ID. - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Only supported methods are limit and offset - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingListMessageLogsRequestParams} params - */ -const messagingListMessageLogs = async ({messageId,queries,total,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface MessagingListMessageLogsRequestParams { + messageId: string; + queries?: string[]; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const messagingListMessageLogs = async ({messageId,queries,total,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: MessagingListMessageLogsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/messages/{messageId}/logs'.replace('{messageId}', messageId); @@ -670,7 +629,7 @@ const messagingListMessageLogs = async ({messageId,queries,total,parseOutput = t }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('messaging', 'listMessageLogs', messageId); } else { parse(response) @@ -680,20 +639,16 @@ const messagingListMessageLogs = async ({messageId,queries,total,parseOutput = t return response; } -/** - * @typedef {Object} MessagingListTargetsRequestParams - * @property {string} messageId Message ID. - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: userId, providerId, identifier, providerType - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingListTargetsRequestParams} params - */ -const messagingListTargets = async ({messageId,queries,total,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingListTargetsRequestParams { + messageId: string; + queries?: string[]; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingListTargets = async ({messageId,queries,total,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingListTargetsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/messages/{messageId}/targets'.replace('{messageId}', messageId); @@ -717,20 +672,17 @@ const messagingListTargets = async ({messageId,queries,total,parseOutput = true, return response; } -/** - * @typedef {Object} MessagingListProvidersRequestParams - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name, provider, type, enabled - * @property {string} search Search term to filter your list results. Max length: 256 chars. - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingListProvidersRequestParams} params - */ -const messagingListProviders = async ({queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface MessagingListProvidersRequestParams { + queries?: string[]; + search?: string; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const messagingListProviders = async ({queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: MessagingListProvidersRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/providers'; @@ -751,7 +703,7 @@ const messagingListProviders = async ({queries,search,total,parseOutput = true, }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('messaging', 'listProviders'); } else { parse(response) @@ -761,25 +713,21 @@ const messagingListProviders = async ({queries,search,total,parseOutput = true, return response; } -/** - * @typedef {Object} MessagingCreateAPNSProviderRequestParams - * @property {string} providerId Provider ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} name Provider name. - * @property {string} authKey APNS authentication key. - * @property {string} authKeyId APNS authentication key ID. - * @property {string} teamId APNS team ID. - * @property {string} bundleId APNS bundle ID. - * @property {boolean} sandbox Use APNS sandbox environment. - * @property {boolean} enabled Set as enabled. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingCreateAPNSProviderRequestParams} params - */ -const messagingCreateAPNSProvider = async ({providerId,name,authKey,authKeyId,teamId,bundleId,sandbox,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingCreateAPNSProviderRequestParams { + providerId: string; + name: string; + authKey?: string; + authKeyId?: string; + teamId?: string; + bundleId?: string; + sandbox?: boolean; + enabled?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingCreateAPNSProvider = async ({providerId,name,authKey,authKeyId,teamId,bundleId,sandbox,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingCreateAPNSProviderRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/providers/apns'; @@ -822,25 +770,21 @@ const messagingCreateAPNSProvider = async ({providerId,name,authKey,authKeyId,te return response; } -/** - * @typedef {Object} MessagingUpdateAPNSProviderRequestParams - * @property {string} providerId Provider ID. - * @property {string} name Provider name. - * @property {boolean} enabled Set as enabled. - * @property {string} authKey APNS authentication key. - * @property {string} authKeyId APNS authentication key ID. - * @property {string} teamId APNS team ID. - * @property {string} bundleId APNS bundle ID. - * @property {boolean} sandbox Use APNS sandbox environment. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingUpdateAPNSProviderRequestParams} params - */ -const messagingUpdateAPNSProvider = async ({providerId,name,enabled,authKey,authKeyId,teamId,bundleId,sandbox,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingUpdateAPNSProviderRequestParams { + providerId: string; + name?: string; + enabled?: boolean; + authKey?: string; + authKeyId?: string; + teamId?: string; + bundleId?: string; + sandbox?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingUpdateAPNSProvider = async ({providerId,name,enabled,authKey,authKeyId,teamId,bundleId,sandbox,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingUpdateAPNSProviderRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/providers/apns/{providerId}'.replace('{providerId}', providerId); @@ -880,21 +824,17 @@ const messagingUpdateAPNSProvider = async ({providerId,name,enabled,authKey,auth return response; } -/** - * @typedef {Object} MessagingCreateFCMProviderRequestParams - * @property {string} providerId Provider ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} name Provider name. - * @property {object} serviceAccountJSON FCM service account JSON. - * @property {boolean} enabled Set as enabled. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingCreateFCMProviderRequestParams} params - */ -const messagingCreateFCMProvider = async ({providerId,name,serviceAccountJSON,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingCreateFCMProviderRequestParams { + providerId: string; + name: string; + serviceAccountJSON?: object; + enabled?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingCreateFCMProvider = async ({providerId,name,serviceAccountJSON,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingCreateFCMProviderRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/providers/fcm'; @@ -925,21 +865,17 @@ const messagingCreateFCMProvider = async ({providerId,name,serviceAccountJSON,en return response; } -/** - * @typedef {Object} MessagingUpdateFCMProviderRequestParams - * @property {string} providerId Provider ID. - * @property {string} name Provider name. - * @property {boolean} enabled Set as enabled. - * @property {object} serviceAccountJSON FCM service account JSON. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingUpdateFCMProviderRequestParams} params - */ -const messagingUpdateFCMProvider = async ({providerId,name,enabled,serviceAccountJSON,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingUpdateFCMProviderRequestParams { + providerId: string; + name?: string; + enabled?: boolean; + serviceAccountJSON?: object; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingUpdateFCMProvider = async ({providerId,name,enabled,serviceAccountJSON,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingUpdateFCMProviderRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/providers/fcm/{providerId}'.replace('{providerId}', providerId); @@ -967,27 +903,23 @@ const messagingUpdateFCMProvider = async ({providerId,name,enabled,serviceAccoun return response; } -/** - * @typedef {Object} MessagingCreateMailgunProviderRequestParams - * @property {string} providerId Provider ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} name Provider name. - * @property {string} apiKey Mailgun API Key. - * @property {string} domain Mailgun Domain. - * @property {boolean} isEuRegion Set as EU region. - * @property {string} fromName Sender Name. - * @property {string} fromEmail Sender email address. - * @property {string} replyToName Name set in the reply to field for the mail. Default value is sender name. Reply to name must have reply to email as well. - * @property {string} replyToEmail Email set in the reply to field for the mail. Default value is sender email. Reply to email must have reply to name as well. - * @property {boolean} enabled Set as enabled. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingCreateMailgunProviderRequestParams} params - */ -const messagingCreateMailgunProvider = async ({providerId,name,apiKey,domain,isEuRegion,fromName,fromEmail,replyToName,replyToEmail,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingCreateMailgunProviderRequestParams { + providerId: string; + name: string; + apiKey?: string; + domain?: string; + isEuRegion?: boolean; + fromName?: string; + fromEmail?: string; + replyToName?: string; + replyToEmail?: string; + enabled?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingCreateMailgunProvider = async ({providerId,name,apiKey,domain,isEuRegion,fromName,fromEmail,replyToName,replyToEmail,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingCreateMailgunProviderRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/providers/mailgun'; @@ -1036,27 +968,23 @@ const messagingCreateMailgunProvider = async ({providerId,name,apiKey,domain,isE return response; } -/** - * @typedef {Object} MessagingUpdateMailgunProviderRequestParams - * @property {string} providerId Provider ID. - * @property {string} name Provider name. - * @property {string} apiKey Mailgun API Key. - * @property {string} domain Mailgun Domain. - * @property {boolean} isEuRegion Set as EU region. - * @property {boolean} enabled Set as enabled. - * @property {string} fromName Sender Name. - * @property {string} fromEmail Sender email address. - * @property {string} replyToName Name set in the reply to field for the mail. Default value is sender name. - * @property {string} replyToEmail Email set in the reply to field for the mail. Default value is sender email. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingUpdateMailgunProviderRequestParams} params - */ -const messagingUpdateMailgunProvider = async ({providerId,name,apiKey,domain,isEuRegion,enabled,fromName,fromEmail,replyToName,replyToEmail,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingUpdateMailgunProviderRequestParams { + providerId: string; + name?: string; + apiKey?: string; + domain?: string; + isEuRegion?: boolean; + enabled?: boolean; + fromName?: string; + fromEmail?: string; + replyToName?: string; + replyToEmail?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingUpdateMailgunProvider = async ({providerId,name,apiKey,domain,isEuRegion,enabled,fromName,fromEmail,replyToName,replyToEmail,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingUpdateMailgunProviderRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/providers/mailgun/{providerId}'.replace('{providerId}', providerId); @@ -1102,23 +1030,19 @@ const messagingUpdateMailgunProvider = async ({providerId,name,apiKey,domain,isE return response; } -/** - * @typedef {Object} MessagingCreateMsg91ProviderRequestParams - * @property {string} providerId Provider ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} name Provider name. - * @property {string} templateId Msg91 template ID - * @property {string} senderId Msg91 sender ID. - * @property {string} authKey Msg91 auth key. - * @property {boolean} enabled Set as enabled. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingCreateMsg91ProviderRequestParams} params - */ -const messagingCreateMsg91Provider = async ({providerId,name,templateId,senderId,authKey,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingCreateMsg91ProviderRequestParams { + providerId: string; + name: string; + templateId?: string; + senderId?: string; + authKey?: string; + enabled?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingCreateMsg91Provider = async ({providerId,name,templateId,senderId,authKey,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingCreateMsg91ProviderRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/providers/msg91'; @@ -1155,23 +1079,19 @@ const messagingCreateMsg91Provider = async ({providerId,name,templateId,senderId return response; } -/** - * @typedef {Object} MessagingUpdateMsg91ProviderRequestParams - * @property {string} providerId Provider ID. - * @property {string} name Provider name. - * @property {boolean} enabled Set as enabled. - * @property {string} templateId Msg91 template ID. - * @property {string} senderId Msg91 sender ID. - * @property {string} authKey Msg91 auth key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingUpdateMsg91ProviderRequestParams} params - */ -const messagingUpdateMsg91Provider = async ({providerId,name,enabled,templateId,senderId,authKey,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingUpdateMsg91ProviderRequestParams { + providerId: string; + name?: string; + enabled?: boolean; + templateId?: string; + senderId?: string; + authKey?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingUpdateMsg91Provider = async ({providerId,name,enabled,templateId,senderId,authKey,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingUpdateMsg91ProviderRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/providers/msg91/{providerId}'.replace('{providerId}', providerId); @@ -1205,25 +1125,21 @@ const messagingUpdateMsg91Provider = async ({providerId,name,enabled,templateId, return response; } -/** - * @typedef {Object} MessagingCreateResendProviderRequestParams - * @property {string} providerId Provider ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} name Provider name. - * @property {string} apiKey Resend API key. - * @property {string} fromName Sender Name. - * @property {string} fromEmail Sender email address. - * @property {string} replyToName Name set in the reply to field for the mail. Default value is sender name. - * @property {string} replyToEmail Email set in the reply to field for the mail. Default value is sender email. - * @property {boolean} enabled Set as enabled. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingCreateResendProviderRequestParams} params - */ -const messagingCreateResendProvider = async ({providerId,name,apiKey,fromName,fromEmail,replyToName,replyToEmail,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingCreateResendProviderRequestParams { + providerId: string; + name: string; + apiKey?: string; + fromName?: string; + fromEmail?: string; + replyToName?: string; + replyToEmail?: string; + enabled?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingCreateResendProvider = async ({providerId,name,apiKey,fromName,fromEmail,replyToName,replyToEmail,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingCreateResendProviderRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/providers/resend'; @@ -1266,25 +1182,21 @@ const messagingCreateResendProvider = async ({providerId,name,apiKey,fromName,fr return response; } -/** - * @typedef {Object} MessagingUpdateResendProviderRequestParams - * @property {string} providerId Provider ID. - * @property {string} name Provider name. - * @property {boolean} enabled Set as enabled. - * @property {string} apiKey Resend API key. - * @property {string} fromName Sender Name. - * @property {string} fromEmail Sender email address. - * @property {string} replyToName Name set in the Reply To field for the mail. Default value is Sender Name. - * @property {string} replyToEmail Email set in the Reply To field for the mail. Default value is Sender Email. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingUpdateResendProviderRequestParams} params - */ -const messagingUpdateResendProvider = async ({providerId,name,enabled,apiKey,fromName,fromEmail,replyToName,replyToEmail,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingUpdateResendProviderRequestParams { + providerId: string; + name?: string; + enabled?: boolean; + apiKey?: string; + fromName?: string; + fromEmail?: string; + replyToName?: string; + replyToEmail?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingUpdateResendProvider = async ({providerId,name,enabled,apiKey,fromName,fromEmail,replyToName,replyToEmail,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingUpdateResendProviderRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/providers/resend/{providerId}'.replace('{providerId}', providerId); @@ -1324,25 +1236,21 @@ const messagingUpdateResendProvider = async ({providerId,name,enabled,apiKey,fro return response; } -/** - * @typedef {Object} MessagingCreateSendgridProviderRequestParams - * @property {string} providerId Provider ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} name Provider name. - * @property {string} apiKey Sendgrid API key. - * @property {string} fromName Sender Name. - * @property {string} fromEmail Sender email address. - * @property {string} replyToName Name set in the reply to field for the mail. Default value is sender name. - * @property {string} replyToEmail Email set in the reply to field for the mail. Default value is sender email. - * @property {boolean} enabled Set as enabled. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingCreateSendgridProviderRequestParams} params - */ -const messagingCreateSendgridProvider = async ({providerId,name,apiKey,fromName,fromEmail,replyToName,replyToEmail,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingCreateSendgridProviderRequestParams { + providerId: string; + name: string; + apiKey?: string; + fromName?: string; + fromEmail?: string; + replyToName?: string; + replyToEmail?: string; + enabled?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingCreateSendgridProvider = async ({providerId,name,apiKey,fromName,fromEmail,replyToName,replyToEmail,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingCreateSendgridProviderRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/providers/sendgrid'; @@ -1385,25 +1293,21 @@ const messagingCreateSendgridProvider = async ({providerId,name,apiKey,fromName, return response; } -/** - * @typedef {Object} MessagingUpdateSendgridProviderRequestParams - * @property {string} providerId Provider ID. - * @property {string} name Provider name. - * @property {boolean} enabled Set as enabled. - * @property {string} apiKey Sendgrid API key. - * @property {string} fromName Sender Name. - * @property {string} fromEmail Sender email address. - * @property {string} replyToName Name set in the Reply To field for the mail. Default value is Sender Name. - * @property {string} replyToEmail Email set in the Reply To field for the mail. Default value is Sender Email. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingUpdateSendgridProviderRequestParams} params - */ -const messagingUpdateSendgridProvider = async ({providerId,name,enabled,apiKey,fromName,fromEmail,replyToName,replyToEmail,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingUpdateSendgridProviderRequestParams { + providerId: string; + name?: string; + enabled?: boolean; + apiKey?: string; + fromName?: string; + fromEmail?: string; + replyToName?: string; + replyToEmail?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingUpdateSendgridProvider = async ({providerId,name,enabled,apiKey,fromName,fromEmail,replyToName,replyToEmail,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingUpdateSendgridProviderRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/providers/sendgrid/{providerId}'.replace('{providerId}', providerId); @@ -1443,31 +1347,27 @@ const messagingUpdateSendgridProvider = async ({providerId,name,enabled,apiKey,f return response; } -/** - * @typedef {Object} MessagingCreateSMTPProviderRequestParams - * @property {string} providerId Provider ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} name Provider name. - * @property {string} host SMTP hosts. Either a single hostname or multiple semicolon-delimited hostnames. You can also specify a different port for each host such as 'smtp1.example.com:25;smtp2.example.com'. You can also specify encryption type, for example: 'tls://smtp1.example.com:587;ssl://smtp2.example.com:465"'. Hosts will be tried in order. - * @property {number} port The default SMTP server port. - * @property {string} username Authentication username. - * @property {string} password Authentication password. - * @property {SmtpEncryption} encryption Encryption type. Can be omitted, 'ssl', or 'tls' - * @property {boolean} autoTLS Enable SMTP AutoTLS feature. - * @property {string} mailer The value to use for the X-Mailer header. - * @property {string} fromName Sender Name. - * @property {string} fromEmail Sender email address. - * @property {string} replyToName Name set in the reply to field for the mail. Default value is sender name. - * @property {string} replyToEmail Email set in the reply to field for the mail. Default value is sender email. - * @property {boolean} enabled Set as enabled. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingCreateSMTPProviderRequestParams} params - */ -const messagingCreateSMTPProvider = async ({providerId,name,host,port,username,password,encryption,autoTLS,mailer,fromName,fromEmail,replyToName,replyToEmail,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingCreateSMTPProviderRequestParams { + providerId: string; + name: string; + host: string; + port?: number; + username?: string; + password?: string; + encryption?: SmtpEncryption; + autoTLS?: boolean; + mailer?: string; + fromName?: string; + fromEmail?: string; + replyToName?: string; + replyToEmail?: string; + enabled?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingCreateSMTPProvider = async ({providerId,name,host,port,username,password,encryption,autoTLS,mailer,fromName,fromEmail,replyToName,replyToEmail,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingCreateSMTPProviderRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/providers/smtp'; @@ -1528,31 +1428,27 @@ const messagingCreateSMTPProvider = async ({providerId,name,host,port,username,p return response; } -/** - * @typedef {Object} MessagingUpdateSMTPProviderRequestParams - * @property {string} providerId Provider ID. - * @property {string} name Provider name. - * @property {string} host SMTP hosts. Either a single hostname or multiple semicolon-delimited hostnames. You can also specify a different port for each host such as 'smtp1.example.com:25;smtp2.example.com'. You can also specify encryption type, for example: 'tls://smtp1.example.com:587;ssl://smtp2.example.com:465"'. Hosts will be tried in order. - * @property {number} port SMTP port. - * @property {string} username Authentication username. - * @property {string} password Authentication password. - * @property {SmtpEncryption} encryption Encryption type. Can be 'ssl' or 'tls' - * @property {boolean} autoTLS Enable SMTP AutoTLS feature. - * @property {string} mailer The value to use for the X-Mailer header. - * @property {string} fromName Sender Name. - * @property {string} fromEmail Sender email address. - * @property {string} replyToName Name set in the Reply To field for the mail. Default value is Sender Name. - * @property {string} replyToEmail Email set in the Reply To field for the mail. Default value is Sender Email. - * @property {boolean} enabled Set as enabled. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingUpdateSMTPProviderRequestParams} params - */ -const messagingUpdateSMTPProvider = async ({providerId,name,host,port,username,password,encryption,autoTLS,mailer,fromName,fromEmail,replyToName,replyToEmail,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingUpdateSMTPProviderRequestParams { + providerId: string; + name?: string; + host?: string; + port?: number; + username?: string; + password?: string; + encryption?: SmtpEncryption; + autoTLS?: boolean; + mailer?: string; + fromName?: string; + fromEmail?: string; + replyToName?: string; + replyToEmail?: string; + enabled?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingUpdateSMTPProvider = async ({providerId,name,host,port,username,password,encryption,autoTLS,mailer,fromName,fromEmail,replyToName,replyToEmail,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingUpdateSMTPProviderRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/providers/smtp/{providerId}'.replace('{providerId}', providerId); @@ -1610,23 +1506,19 @@ const messagingUpdateSMTPProvider = async ({providerId,name,host,port,username,p return response; } -/** - * @typedef {Object} MessagingCreateTelesignProviderRequestParams - * @property {string} providerId Provider ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} name Provider name. - * @property {string} from Sender Phone number. Format this number with a leading '+' and a country code, e.g., +16175551212. - * @property {string} customerId Telesign customer ID. - * @property {string} apiKey Telesign API key. - * @property {boolean} enabled Set as enabled. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingCreateTelesignProviderRequestParams} params - */ -const messagingCreateTelesignProvider = async ({providerId,name,from,customerId,apiKey,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingCreateTelesignProviderRequestParams { + providerId: string; + name: string; + from?: string; + customerId?: string; + apiKey?: string; + enabled?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingCreateTelesignProvider = async ({providerId,name,from,customerId,apiKey,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingCreateTelesignProviderRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/providers/telesign'; @@ -1663,23 +1555,19 @@ const messagingCreateTelesignProvider = async ({providerId,name,from,customerId, return response; } -/** - * @typedef {Object} MessagingUpdateTelesignProviderRequestParams - * @property {string} providerId Provider ID. - * @property {string} name Provider name. - * @property {boolean} enabled Set as enabled. - * @property {string} customerId Telesign customer ID. - * @property {string} apiKey Telesign API key. - * @property {string} from Sender number. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingUpdateTelesignProviderRequestParams} params - */ -const messagingUpdateTelesignProvider = async ({providerId,name,enabled,customerId,apiKey,from,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingUpdateTelesignProviderRequestParams { + providerId: string; + name?: string; + enabled?: boolean; + customerId?: string; + apiKey?: string; + from?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingUpdateTelesignProvider = async ({providerId,name,enabled,customerId,apiKey,from,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingUpdateTelesignProviderRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/providers/telesign/{providerId}'.replace('{providerId}', providerId); @@ -1713,23 +1601,19 @@ const messagingUpdateTelesignProvider = async ({providerId,name,enabled,customer return response; } -/** - * @typedef {Object} MessagingCreateTextmagicProviderRequestParams - * @property {string} providerId Provider ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} name Provider name. - * @property {string} from Sender Phone number. Format this number with a leading '+' and a country code, e.g., +16175551212. - * @property {string} username Textmagic username. - * @property {string} apiKey Textmagic apiKey. - * @property {boolean} enabled Set as enabled. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingCreateTextmagicProviderRequestParams} params - */ -const messagingCreateTextmagicProvider = async ({providerId,name,from,username,apiKey,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingCreateTextmagicProviderRequestParams { + providerId: string; + name: string; + from?: string; + username?: string; + apiKey?: string; + enabled?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingCreateTextmagicProvider = async ({providerId,name,from,username,apiKey,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingCreateTextmagicProviderRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/providers/textmagic'; @@ -1766,23 +1650,19 @@ const messagingCreateTextmagicProvider = async ({providerId,name,from,username,a return response; } -/** - * @typedef {Object} MessagingUpdateTextmagicProviderRequestParams - * @property {string} providerId Provider ID. - * @property {string} name Provider name. - * @property {boolean} enabled Set as enabled. - * @property {string} username Textmagic username. - * @property {string} apiKey Textmagic apiKey. - * @property {string} from Sender number. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingUpdateTextmagicProviderRequestParams} params - */ -const messagingUpdateTextmagicProvider = async ({providerId,name,enabled,username,apiKey,from,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingUpdateTextmagicProviderRequestParams { + providerId: string; + name?: string; + enabled?: boolean; + username?: string; + apiKey?: string; + from?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingUpdateTextmagicProvider = async ({providerId,name,enabled,username,apiKey,from,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingUpdateTextmagicProviderRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/providers/textmagic/{providerId}'.replace('{providerId}', providerId); @@ -1816,23 +1696,19 @@ const messagingUpdateTextmagicProvider = async ({providerId,name,enabled,usernam return response; } -/** - * @typedef {Object} MessagingCreateTwilioProviderRequestParams - * @property {string} providerId Provider ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} name Provider name. - * @property {string} from Sender Phone number. Format this number with a leading '+' and a country code, e.g., +16175551212. - * @property {string} accountSid Twilio account secret ID. - * @property {string} authToken Twilio authentication token. - * @property {boolean} enabled Set as enabled. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingCreateTwilioProviderRequestParams} params - */ -const messagingCreateTwilioProvider = async ({providerId,name,from,accountSid,authToken,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingCreateTwilioProviderRequestParams { + providerId: string; + name: string; + from?: string; + accountSid?: string; + authToken?: string; + enabled?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingCreateTwilioProvider = async ({providerId,name,from,accountSid,authToken,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingCreateTwilioProviderRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/providers/twilio'; @@ -1869,23 +1745,19 @@ const messagingCreateTwilioProvider = async ({providerId,name,from,accountSid,au return response; } -/** - * @typedef {Object} MessagingUpdateTwilioProviderRequestParams - * @property {string} providerId Provider ID. - * @property {string} name Provider name. - * @property {boolean} enabled Set as enabled. - * @property {string} accountSid Twilio account secret ID. - * @property {string} authToken Twilio authentication token. - * @property {string} from Sender number. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingUpdateTwilioProviderRequestParams} params - */ -const messagingUpdateTwilioProvider = async ({providerId,name,enabled,accountSid,authToken,from,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingUpdateTwilioProviderRequestParams { + providerId: string; + name?: string; + enabled?: boolean; + accountSid?: string; + authToken?: string; + from?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingUpdateTwilioProvider = async ({providerId,name,enabled,accountSid,authToken,from,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingUpdateTwilioProviderRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/providers/twilio/{providerId}'.replace('{providerId}', providerId); @@ -1919,23 +1791,19 @@ const messagingUpdateTwilioProvider = async ({providerId,name,enabled,accountSid return response; } -/** - * @typedef {Object} MessagingCreateVonageProviderRequestParams - * @property {string} providerId Provider ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} name Provider name. - * @property {string} from Sender Phone number. Format this number with a leading '+' and a country code, e.g., +16175551212. - * @property {string} apiKey Vonage API key. - * @property {string} apiSecret Vonage API secret. - * @property {boolean} enabled Set as enabled. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingCreateVonageProviderRequestParams} params - */ -const messagingCreateVonageProvider = async ({providerId,name,from,apiKey,apiSecret,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingCreateVonageProviderRequestParams { + providerId: string; + name: string; + from?: string; + apiKey?: string; + apiSecret?: string; + enabled?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingCreateVonageProvider = async ({providerId,name,from,apiKey,apiSecret,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingCreateVonageProviderRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/providers/vonage'; @@ -1972,23 +1840,19 @@ const messagingCreateVonageProvider = async ({providerId,name,from,apiKey,apiSec return response; } -/** - * @typedef {Object} MessagingUpdateVonageProviderRequestParams - * @property {string} providerId Provider ID. - * @property {string} name Provider name. - * @property {boolean} enabled Set as enabled. - * @property {string} apiKey Vonage API key. - * @property {string} apiSecret Vonage API secret. - * @property {string} from Sender number. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingUpdateVonageProviderRequestParams} params - */ -const messagingUpdateVonageProvider = async ({providerId,name,enabled,apiKey,apiSecret,from,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingUpdateVonageProviderRequestParams { + providerId: string; + name?: string; + enabled?: boolean; + apiKey?: string; + apiSecret?: string; + from?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingUpdateVonageProvider = async ({providerId,name,enabled,apiKey,apiSecret,from,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingUpdateVonageProviderRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/providers/vonage/{providerId}'.replace('{providerId}', providerId); @@ -2022,18 +1886,15 @@ const messagingUpdateVonageProvider = async ({providerId,name,enabled,apiKey,api return response; } -/** - * @typedef {Object} MessagingGetProviderRequestParams - * @property {string} providerId Provider ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface MessagingGetProviderRequestParams { + providerId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {MessagingGetProviderRequestParams} params - */ -const messagingGetProvider = async ({providerId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const messagingGetProvider = async ({providerId,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: MessagingGetProviderRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/providers/{providerId}'.replace('{providerId}', providerId); @@ -2045,7 +1906,7 @@ const messagingGetProvider = async ({providerId,parseOutput = true, overrideForC }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('messaging', 'getProvider', providerId); } else { parse(response) @@ -2055,18 +1916,14 @@ const messagingGetProvider = async ({providerId,parseOutput = true, overrideForC return response; } -/** - * @typedef {Object} MessagingDeleteProviderRequestParams - * @property {string} providerId Provider ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface MessagingDeleteProviderRequestParams { + providerId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {MessagingDeleteProviderRequestParams} params - */ -const messagingDeleteProvider = async ({providerId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const messagingDeleteProvider = async ({providerId,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingDeleteProviderRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/providers/{providerId}'.replace('{providerId}', providerId); @@ -2085,20 +1942,16 @@ const messagingDeleteProvider = async ({providerId,parseOutput = true, overrideF return response; } -/** - * @typedef {Object} MessagingListProviderLogsRequestParams - * @property {string} providerId Provider ID. - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Only supported methods are limit and offset - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingListProviderLogsRequestParams} params - */ -const messagingListProviderLogs = async ({providerId,queries,total,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingListProviderLogsRequestParams { + providerId: string; + queries?: string[]; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingListProviderLogs = async ({providerId,queries,total,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingListProviderLogsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/providers/{providerId}/logs'.replace('{providerId}', providerId); @@ -2122,20 +1975,16 @@ const messagingListProviderLogs = async ({providerId,queries,total,parseOutput = return response; } -/** - * @typedef {Object} MessagingListSubscriberLogsRequestParams - * @property {string} subscriberId Subscriber ID. - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Only supported methods are limit and offset - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingListSubscriberLogsRequestParams} params - */ -const messagingListSubscriberLogs = async ({subscriberId,queries,total,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingListSubscriberLogsRequestParams { + subscriberId: string; + queries?: string[]; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingListSubscriberLogs = async ({subscriberId,queries,total,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingListSubscriberLogsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/subscribers/{subscriberId}/logs'.replace('{subscriberId}', subscriberId); @@ -2159,20 +2008,17 @@ const messagingListSubscriberLogs = async ({subscriberId,queries,total,parseOutp return response; } -/** - * @typedef {Object} MessagingListTopicsRequestParams - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name, description, emailTotal, smsTotal, pushTotal - * @property {string} search Search term to filter your list results. Max length: 256 chars. - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingListTopicsRequestParams} params - */ -const messagingListTopics = async ({queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface MessagingListTopicsRequestParams { + queries?: string[]; + search?: string; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const messagingListTopics = async ({queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: MessagingListTopicsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/topics'; @@ -2193,7 +2039,7 @@ const messagingListTopics = async ({queries,search,total,parseOutput = true, ove }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('messaging', 'listTopics'); } else { parse(response) @@ -2203,20 +2049,16 @@ const messagingListTopics = async ({queries,search,total,parseOutput = true, ove return response; } -/** - * @typedef {Object} MessagingCreateTopicRequestParams - * @property {string} topicId Topic ID. Choose a custom Topic ID or a new Topic ID. - * @property {string} name Topic Name. - * @property {string[]} subscribe An array of role strings with subscribe permission. By default all users are granted with any subscribe permission. [learn more about roles](https://appwrite.io/docs/permissions#permission-roles). Maximum of 100 roles are allowed, each 64 characters long. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingCreateTopicRequestParams} params - */ -const messagingCreateTopic = async ({topicId,name,subscribe,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingCreateTopicRequestParams { + topicId: string; + name: string; + subscribe?: string[]; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingCreateTopic = async ({topicId,name,subscribe,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingCreateTopicRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/topics'; @@ -2245,18 +2087,15 @@ const messagingCreateTopic = async ({topicId,name,subscribe,parseOutput = true, return response; } -/** - * @typedef {Object} MessagingGetTopicRequestParams - * @property {string} topicId Topic ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface MessagingGetTopicRequestParams { + topicId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {MessagingGetTopicRequestParams} params - */ -const messagingGetTopic = async ({topicId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const messagingGetTopic = async ({topicId,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: MessagingGetTopicRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/topics/{topicId}'.replace('{topicId}', topicId); @@ -2268,7 +2107,7 @@ const messagingGetTopic = async ({topicId,parseOutput = true, overrideForCli = f }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('messaging', 'getTopic', topicId); } else { parse(response) @@ -2278,20 +2117,16 @@ const messagingGetTopic = async ({topicId,parseOutput = true, overrideForCli = f return response; } -/** - * @typedef {Object} MessagingUpdateTopicRequestParams - * @property {string} topicId Topic ID. - * @property {string} name Topic Name. - * @property {string[]} subscribe An array of role strings with subscribe permission. By default all users are granted with any subscribe permission. [learn more about roles](https://appwrite.io/docs/permissions#permission-roles). Maximum of 100 roles are allowed, each 64 characters long. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingUpdateTopicRequestParams} params - */ -const messagingUpdateTopic = async ({topicId,name,subscribe,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingUpdateTopicRequestParams { + topicId: string; + name?: string; + subscribe?: string[]; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingUpdateTopic = async ({topicId,name,subscribe,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingUpdateTopicRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/topics/{topicId}'.replace('{topicId}', topicId); @@ -2317,18 +2152,14 @@ const messagingUpdateTopic = async ({topicId,name,subscribe,parseOutput = true, return response; } -/** - * @typedef {Object} MessagingDeleteTopicRequestParams - * @property {string} topicId Topic ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface MessagingDeleteTopicRequestParams { + topicId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {MessagingDeleteTopicRequestParams} params - */ -const messagingDeleteTopic = async ({topicId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const messagingDeleteTopic = async ({topicId,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingDeleteTopicRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/topics/{topicId}'.replace('{topicId}', topicId); @@ -2347,20 +2178,16 @@ const messagingDeleteTopic = async ({topicId,parseOutput = true, overrideForCli return response; } -/** - * @typedef {Object} MessagingListTopicLogsRequestParams - * @property {string} topicId Topic ID. - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Only supported methods are limit and offset - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingListTopicLogsRequestParams} params - */ -const messagingListTopicLogs = async ({topicId,queries,total,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingListTopicLogsRequestParams { + topicId: string; + queries?: string[]; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingListTopicLogs = async ({topicId,queries,total,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingListTopicLogsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/topics/{topicId}/logs'.replace('{topicId}', topicId); @@ -2384,21 +2211,18 @@ const messagingListTopicLogs = async ({topicId,queries,total,parseOutput = true, return response; } -/** - * @typedef {Object} MessagingListSubscribersRequestParams - * @property {string} topicId Topic ID. The topic ID subscribed to. - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name, provider, type, enabled - * @property {string} search Search term to filter your list results. Max length: 256 chars. - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingListSubscribersRequestParams} params - */ -const messagingListSubscribers = async ({topicId,queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface MessagingListSubscribersRequestParams { + topicId: string; + queries?: string[]; + search?: string; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const messagingListSubscribers = async ({topicId,queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: MessagingListSubscribersRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/topics/{topicId}/subscribers'.replace('{topicId}', topicId); @@ -2419,7 +2243,7 @@ const messagingListSubscribers = async ({topicId,queries,search,total,parseOutpu }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('messaging', 'listSubscribers', topicId); } else { parse(response) @@ -2429,20 +2253,16 @@ const messagingListSubscribers = async ({topicId,queries,search,total,parseOutpu return response; } -/** - * @typedef {Object} MessagingCreateSubscriberRequestParams - * @property {string} topicId Topic ID. The topic ID to subscribe to. - * @property {string} subscriberId Subscriber ID. Choose a custom Subscriber ID or a new Subscriber ID. - * @property {string} targetId Target ID. The target ID to link to the specified Topic ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MessagingCreateSubscriberRequestParams} params - */ -const messagingCreateSubscriber = async ({topicId,subscriberId,targetId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MessagingCreateSubscriberRequestParams { + topicId: string; + subscriberId: string; + targetId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const messagingCreateSubscriber = async ({topicId,subscriberId,targetId,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingCreateSubscriberRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/topics/{topicId}/subscribers'.replace('{topicId}', topicId); @@ -2467,19 +2287,15 @@ const messagingCreateSubscriber = async ({topicId,subscriberId,targetId,parseOut return response; } -/** - * @typedef {Object} MessagingGetSubscriberRequestParams - * @property {string} topicId Topic ID. The topic ID subscribed to. - * @property {string} subscriberId Subscriber ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface MessagingGetSubscriberRequestParams { + topicId: string; + subscriberId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {MessagingGetSubscriberRequestParams} params - */ -const messagingGetSubscriber = async ({topicId,subscriberId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const messagingGetSubscriber = async ({topicId,subscriberId,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingGetSubscriberRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}'.replace('{topicId}', topicId).replace('{subscriberId}', subscriberId); @@ -2497,19 +2313,15 @@ const messagingGetSubscriber = async ({topicId,subscriberId,parseOutput = true, return response; } -/** - * @typedef {Object} MessagingDeleteSubscriberRequestParams - * @property {string} topicId Topic ID. The topic ID subscribed to. - * @property {string} subscriberId Subscriber ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface MessagingDeleteSubscriberRequestParams { + topicId: string; + subscriberId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {MessagingDeleteSubscriberRequestParams} params - */ -const messagingDeleteSubscriber = async ({topicId,subscriberId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const messagingDeleteSubscriber = async ({topicId,subscriberId,parseOutput = true, overrideForCli = false, sdk = undefined}: MessagingDeleteSubscriberRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}'.replace('{topicId}', topicId).replace('{subscriberId}', subscriberId); @@ -2533,7 +2345,7 @@ messaging .description(`Get a list of all messages from the current Appwrite project.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: scheduledAt, deliveredAt, deliveredTotal, status, description, providerType`) .option(`--search `, `Search term to filter your list results. Max length: 256 chars.`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--console`, `Get the resource console url`) .action(actionRunner(messagingListMessages)) @@ -2549,8 +2361,8 @@ messaging .option(`--cc [cc...]`, `Array of target IDs to be added as CC.`) .option(`--bcc [bcc...]`, `Array of target IDs to be added as BCC.`) .option(`--attachments [attachments...]`, `Array of compound ID strings of bucket IDs and file IDs to be attached to the email. They should be formatted as :.`) - .option(`--draft [value]`, `Is message a draft`, (value) => value === undefined ? true : parseBool(value)) - .option(`--html [value]`, `Is content of type HTML`, (value) => value === undefined ? true : parseBool(value)) + .option(`--draft [value]`, `Is message a draft`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--html [value]`, `Is content of type HTML`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--scheduled-at `, `Scheduled delivery time for message in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. DateTime value must be in future.`) .action(actionRunner(messagingCreateEmail)) @@ -2563,8 +2375,8 @@ messaging .option(`--targets [targets...]`, `List of Targets IDs.`) .option(`--subject `, `Email Subject.`) .option(`--content `, `Email Content.`) - .option(`--draft [value]`, `Is message a draft`, (value) => value === undefined ? true : parseBool(value)) - .option(`--html [value]`, `Is content of type HTML`, (value) => value === undefined ? true : parseBool(value)) + .option(`--draft [value]`, `Is message a draft`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--html [value]`, `Is content of type HTML`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--cc [cc...]`, `Array of target IDs to be added as CC.`) .option(`--bcc [bcc...]`, `Array of target IDs to be added as BCC.`) .option(`--scheduled-at `, `Scheduled delivery time for message in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. DateTime value must be in future.`) @@ -2588,10 +2400,10 @@ messaging .option(`--color `, `Color for push notification. Available only for Android Platform.`) .option(`--tag `, `Tag for push notification. Available only for Android Platform.`) .option(`--badge `, `Badge for push notification. Available only for iOS Platform.`, parseInteger) - .option(`--draft [value]`, `Is message a draft`, (value) => value === undefined ? true : parseBool(value)) + .option(`--draft [value]`, `Is message a draft`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--scheduled-at `, `Scheduled delivery time for message in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. DateTime value must be in future.`) - .option(`--content-available [value]`, `If set to true, the notification will be delivered in the background. Available only for iOS Platform.`, (value) => value === undefined ? true : parseBool(value)) - .option(`--critical [value]`, `If set to true, the notification will be marked as critical. This requires the app to have the critical notification entitlement. Available only for iOS Platform.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--content-available [value]`, `If set to true, the notification will be delivered in the background. Available only for iOS Platform.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--critical [value]`, `If set to true, the notification will be marked as critical. This requires the app to have the critical notification entitlement. Available only for iOS Platform.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--priority `, `Set the notification priority. "normal" will consider device state and may not deliver notifications immediately. "high" will always attempt to immediately deliver the notification.`) .action(actionRunner(messagingCreatePush)) @@ -2612,10 +2424,10 @@ messaging .option(`--color `, `Color for push notification. Available only for Android platforms.`) .option(`--tag `, `Tag for push notification. Available only for Android platforms.`) .option(`--badge `, `Badge for push notification. Available only for iOS platforms.`, parseInteger) - .option(`--draft [value]`, `Is message a draft`, (value) => value === undefined ? true : parseBool(value)) + .option(`--draft [value]`, `Is message a draft`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--scheduled-at `, `Scheduled delivery time for message in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. DateTime value must be in future.`) - .option(`--content-available [value]`, `If set to true, the notification will be delivered in the background. Available only for iOS Platform.`, (value) => value === undefined ? true : parseBool(value)) - .option(`--critical [value]`, `If set to true, the notification will be marked as critical. This requires the app to have the critical notification entitlement. Available only for iOS Platform.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--content-available [value]`, `If set to true, the notification will be delivered in the background. Available only for iOS Platform.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--critical [value]`, `If set to true, the notification will be marked as critical. This requires the app to have the critical notification entitlement. Available only for iOS Platform.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--priority `, `Set the notification priority. "normal" will consider device battery state and may send notifications later. "high" will always attempt to immediately deliver the notification.`) .action(actionRunner(messagingUpdatePush)) @@ -2627,7 +2439,7 @@ messaging .option(`--topics [topics...]`, `List of Topic IDs.`) .option(`--users [users...]`, `List of User IDs.`) .option(`--targets [targets...]`, `List of Targets IDs.`) - .option(`--draft [value]`, `Is message a draft`, (value) => value === undefined ? true : parseBool(value)) + .option(`--draft [value]`, `Is message a draft`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--scheduled-at `, `Scheduled delivery time for message in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. DateTime value must be in future.`) .action(actionRunner(messagingCreateSMS)) @@ -2639,7 +2451,7 @@ messaging .option(`--users [users...]`, `List of User IDs.`) .option(`--targets [targets...]`, `List of Targets IDs.`) .option(`--content `, `Email Content.`) - .option(`--draft [value]`, `Is message a draft`, (value) => value === undefined ? true : parseBool(value)) + .option(`--draft [value]`, `Is message a draft`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--scheduled-at `, `Scheduled delivery time for message in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. DateTime value must be in future.`) .action(actionRunner(messagingUpdateSMS)) @@ -2661,7 +2473,7 @@ messaging .description(`Get the message activity logs listed by its unique ID.`) .requiredOption(`--message-id `, `Message ID.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Only supported methods are limit and offset`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--console`, `Get the resource console url`) .action(actionRunner(messagingListMessageLogs)) @@ -2670,7 +2482,7 @@ messaging .description(`Get a list of the targets associated with a message.`) .requiredOption(`--message-id `, `Message ID.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: userId, providerId, identifier, providerType`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(messagingListTargets)) messaging @@ -2678,7 +2490,7 @@ messaging .description(`Get a list of all providers from the current Appwrite project.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name, provider, type, enabled`) .option(`--search `, `Search term to filter your list results. Max length: 256 chars.`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--console`, `Get the resource console url`) .action(actionRunner(messagingListProviders)) @@ -2691,8 +2503,8 @@ messaging .option(`--auth-key-id `, `APNS authentication key ID.`) .option(`--team-id `, `APNS team ID.`) .option(`--bundle-id `, `APNS bundle ID.`) - .option(`--sandbox [value]`, `Use APNS sandbox environment.`, (value) => value === undefined ? true : parseBool(value)) - .option(`--enabled [value]`, `Set as enabled.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--sandbox [value]`, `Use APNS sandbox environment.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Set as enabled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(messagingCreateAPNSProvider)) messaging @@ -2700,12 +2512,12 @@ messaging .description(`Update a Apple Push Notification service provider by its unique ID.`) .requiredOption(`--provider-id `, `Provider ID.`) .option(`--name `, `Provider name.`) - .option(`--enabled [value]`, `Set as enabled.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Set as enabled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--auth-key `, `APNS authentication key.`) .option(`--auth-key-id `, `APNS authentication key ID.`) .option(`--team-id `, `APNS team ID.`) .option(`--bundle-id `, `APNS bundle ID.`) - .option(`--sandbox [value]`, `Use APNS sandbox environment.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--sandbox [value]`, `Use APNS sandbox environment.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(messagingUpdateAPNSProvider)) messaging @@ -2714,7 +2526,7 @@ messaging .requiredOption(`--provider-id `, `Provider ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars.`) .requiredOption(`--name `, `Provider name.`) .option(`--service-account-json `, `FCM service account JSON.`) - .option(`--enabled [value]`, `Set as enabled.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Set as enabled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(messagingCreateFCMProvider)) messaging @@ -2722,7 +2534,7 @@ messaging .description(`Update a Firebase Cloud Messaging provider by its unique ID.`) .requiredOption(`--provider-id `, `Provider ID.`) .option(`--name `, `Provider name.`) - .option(`--enabled [value]`, `Set as enabled.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Set as enabled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--service-account-json `, `FCM service account JSON.`) .action(actionRunner(messagingUpdateFCMProvider)) @@ -2733,12 +2545,12 @@ messaging .requiredOption(`--name `, `Provider name.`) .option(`--api-key `, `Mailgun API Key.`) .option(`--domain `, `Mailgun Domain.`) - .option(`--is-eu-region [value]`, `Set as EU region.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--is-eu-region [value]`, `Set as EU region.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--from-name `, `Sender Name.`) .option(`--from-email `, `Sender email address.`) .option(`--reply-to-name `, `Name set in the reply to field for the mail. Default value is sender name. Reply to name must have reply to email as well.`) .option(`--reply-to-email `, `Email set in the reply to field for the mail. Default value is sender email. Reply to email must have reply to name as well.`) - .option(`--enabled [value]`, `Set as enabled.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Set as enabled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(messagingCreateMailgunProvider)) messaging @@ -2748,8 +2560,8 @@ messaging .option(`--name `, `Provider name.`) .option(`--api-key `, `Mailgun API Key.`) .option(`--domain `, `Mailgun Domain.`) - .option(`--is-eu-region [value]`, `Set as EU region.`, (value) => value === undefined ? true : parseBool(value)) - .option(`--enabled [value]`, `Set as enabled.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--is-eu-region [value]`, `Set as EU region.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Set as enabled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--from-name `, `Sender Name.`) .option(`--from-email `, `Sender email address.`) .option(`--reply-to-name `, `Name set in the reply to field for the mail. Default value is sender name.`) @@ -2764,7 +2576,7 @@ messaging .option(`--template-id `, `Msg91 template ID`) .option(`--sender-id `, `Msg91 sender ID.`) .option(`--auth-key `, `Msg91 auth key.`) - .option(`--enabled [value]`, `Set as enabled.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Set as enabled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(messagingCreateMsg91Provider)) messaging @@ -2772,7 +2584,7 @@ messaging .description(`Update a MSG91 provider by its unique ID.`) .requiredOption(`--provider-id `, `Provider ID.`) .option(`--name `, `Provider name.`) - .option(`--enabled [value]`, `Set as enabled.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Set as enabled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--template-id `, `Msg91 template ID.`) .option(`--sender-id `, `Msg91 sender ID.`) .option(`--auth-key `, `Msg91 auth key.`) @@ -2788,7 +2600,7 @@ messaging .option(`--from-email `, `Sender email address.`) .option(`--reply-to-name `, `Name set in the reply to field for the mail. Default value is sender name.`) .option(`--reply-to-email `, `Email set in the reply to field for the mail. Default value is sender email.`) - .option(`--enabled [value]`, `Set as enabled.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Set as enabled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(messagingCreateResendProvider)) messaging @@ -2796,7 +2608,7 @@ messaging .description(`Update a Resend provider by its unique ID.`) .requiredOption(`--provider-id `, `Provider ID.`) .option(`--name `, `Provider name.`) - .option(`--enabled [value]`, `Set as enabled.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Set as enabled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--api-key `, `Resend API key.`) .option(`--from-name `, `Sender Name.`) .option(`--from-email `, `Sender email address.`) @@ -2814,7 +2626,7 @@ messaging .option(`--from-email `, `Sender email address.`) .option(`--reply-to-name `, `Name set in the reply to field for the mail. Default value is sender name.`) .option(`--reply-to-email `, `Email set in the reply to field for the mail. Default value is sender email.`) - .option(`--enabled [value]`, `Set as enabled.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Set as enabled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(messagingCreateSendgridProvider)) messaging @@ -2822,7 +2634,7 @@ messaging .description(`Update a Sendgrid provider by its unique ID.`) .requiredOption(`--provider-id `, `Provider ID.`) .option(`--name `, `Provider name.`) - .option(`--enabled [value]`, `Set as enabled.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Set as enabled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--api-key `, `Sendgrid API key.`) .option(`--from-name `, `Sender Name.`) .option(`--from-email `, `Sender email address.`) @@ -2840,13 +2652,13 @@ messaging .option(`--username `, `Authentication username.`) .option(`--password `, `Authentication password.`) .option(`--encryption `, `Encryption type. Can be omitted, 'ssl', or 'tls'`) - .option(`--auto-tls [value]`, `Enable SMTP AutoTLS feature.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--auto-tls [value]`, `Enable SMTP AutoTLS feature.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--mailer `, `The value to use for the X-Mailer header.`) .option(`--from-name `, `Sender Name.`) .option(`--from-email `, `Sender email address.`) .option(`--reply-to-name `, `Name set in the reply to field for the mail. Default value is sender name.`) .option(`--reply-to-email `, `Email set in the reply to field for the mail. Default value is sender email.`) - .option(`--enabled [value]`, `Set as enabled.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Set as enabled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(messagingCreateSMTPProvider)) messaging @@ -2859,13 +2671,13 @@ messaging .option(`--username `, `Authentication username.`) .option(`--password `, `Authentication password.`) .option(`--encryption `, `Encryption type. Can be 'ssl' or 'tls'`) - .option(`--auto-tls [value]`, `Enable SMTP AutoTLS feature.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--auto-tls [value]`, `Enable SMTP AutoTLS feature.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--mailer `, `The value to use for the X-Mailer header.`) .option(`--from-name `, `Sender Name.`) .option(`--from-email `, `Sender email address.`) .option(`--reply-to-name `, `Name set in the Reply To field for the mail. Default value is Sender Name.`) .option(`--reply-to-email `, `Email set in the Reply To field for the mail. Default value is Sender Email.`) - .option(`--enabled [value]`, `Set as enabled.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Set as enabled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(messagingUpdateSMTPProvider)) messaging @@ -2876,7 +2688,7 @@ messaging .option(`--from `, `Sender Phone number. Format this number with a leading '+' and a country code, e.g., +16175551212.`) .option(`--customer-id `, `Telesign customer ID.`) .option(`--api-key `, `Telesign API key.`) - .option(`--enabled [value]`, `Set as enabled.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Set as enabled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(messagingCreateTelesignProvider)) messaging @@ -2884,7 +2696,7 @@ messaging .description(`Update a Telesign provider by its unique ID.`) .requiredOption(`--provider-id `, `Provider ID.`) .option(`--name `, `Provider name.`) - .option(`--enabled [value]`, `Set as enabled.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Set as enabled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--customer-id `, `Telesign customer ID.`) .option(`--api-key `, `Telesign API key.`) .option(`--from `, `Sender number.`) @@ -2898,7 +2710,7 @@ messaging .option(`--from `, `Sender Phone number. Format this number with a leading '+' and a country code, e.g., +16175551212.`) .option(`--username `, `Textmagic username.`) .option(`--api-key `, `Textmagic apiKey.`) - .option(`--enabled [value]`, `Set as enabled.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Set as enabled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(messagingCreateTextmagicProvider)) messaging @@ -2906,7 +2718,7 @@ messaging .description(`Update a Textmagic provider by its unique ID.`) .requiredOption(`--provider-id `, `Provider ID.`) .option(`--name `, `Provider name.`) - .option(`--enabled [value]`, `Set as enabled.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Set as enabled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--username `, `Textmagic username.`) .option(`--api-key `, `Textmagic apiKey.`) .option(`--from `, `Sender number.`) @@ -2920,7 +2732,7 @@ messaging .option(`--from `, `Sender Phone number. Format this number with a leading '+' and a country code, e.g., +16175551212.`) .option(`--account-sid `, `Twilio account secret ID.`) .option(`--auth-token `, `Twilio authentication token.`) - .option(`--enabled [value]`, `Set as enabled.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Set as enabled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(messagingCreateTwilioProvider)) messaging @@ -2928,7 +2740,7 @@ messaging .description(`Update a Twilio provider by its unique ID.`) .requiredOption(`--provider-id `, `Provider ID.`) .option(`--name `, `Provider name.`) - .option(`--enabled [value]`, `Set as enabled.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Set as enabled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--account-sid `, `Twilio account secret ID.`) .option(`--auth-token `, `Twilio authentication token.`) .option(`--from `, `Sender number.`) @@ -2942,7 +2754,7 @@ messaging .option(`--from `, `Sender Phone number. Format this number with a leading '+' and a country code, e.g., +16175551212.`) .option(`--api-key `, `Vonage API key.`) .option(`--api-secret `, `Vonage API secret.`) - .option(`--enabled [value]`, `Set as enabled.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Set as enabled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(messagingCreateVonageProvider)) messaging @@ -2950,7 +2762,7 @@ messaging .description(`Update a Vonage provider by its unique ID.`) .requiredOption(`--provider-id `, `Provider ID.`) .option(`--name `, `Provider name.`) - .option(`--enabled [value]`, `Set as enabled.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Set as enabled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--api-key `, `Vonage API key.`) .option(`--api-secret `, `Vonage API secret.`) .option(`--from `, `Sender number.`) @@ -2974,7 +2786,7 @@ messaging .description(`Get the provider activity logs listed by its unique ID.`) .requiredOption(`--provider-id `, `Provider ID.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Only supported methods are limit and offset`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(messagingListProviderLogs)) messaging @@ -2982,7 +2794,7 @@ messaging .description(`Get the subscriber activity logs listed by its unique ID.`) .requiredOption(`--subscriber-id `, `Subscriber ID.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Only supported methods are limit and offset`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(messagingListSubscriberLogs)) messaging @@ -2990,7 +2802,7 @@ messaging .description(`Get a list of all topics from the current Appwrite project.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name, description, emailTotal, smsTotal, pushTotal`) .option(`--search `, `Search term to filter your list results. Max length: 256 chars.`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--console`, `Get the resource console url`) .action(actionRunner(messagingListTopics)) @@ -3028,7 +2840,7 @@ messaging .description(`Get the topic activity logs listed by its unique ID.`) .requiredOption(`--topic-id `, `Topic ID.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Only supported methods are limit and offset`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(messagingListTopicLogs)) messaging @@ -3037,7 +2849,7 @@ messaging .requiredOption(`--topic-id `, `Topic ID. The topic ID subscribed to.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name, provider, type, enabled`) .option(`--search `, `Search term to filter your list results. Max length: 256 chars.`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--console`, `Get the resource console url`) .action(actionRunner(messagingListSubscribers)) @@ -3063,54 +2875,4 @@ messaging .requiredOption(`--subscriber-id `, `Subscriber ID.`) .action(actionRunner(messagingDeleteSubscriber)) -module.exports = { - messaging, - messagingListMessages, - messagingCreateEmail, - messagingUpdateEmail, - messagingCreatePush, - messagingUpdatePush, - messagingCreateSMS, - messagingUpdateSMS, - messagingGetMessage, - messagingDelete, - messagingListMessageLogs, - messagingListTargets, - messagingListProviders, - messagingCreateAPNSProvider, - messagingUpdateAPNSProvider, - messagingCreateFCMProvider, - messagingUpdateFCMProvider, - messagingCreateMailgunProvider, - messagingUpdateMailgunProvider, - messagingCreateMsg91Provider, - messagingUpdateMsg91Provider, - messagingCreateResendProvider, - messagingUpdateResendProvider, - messagingCreateSendgridProvider, - messagingUpdateSendgridProvider, - messagingCreateSMTPProvider, - messagingUpdateSMTPProvider, - messagingCreateTelesignProvider, - messagingUpdateTelesignProvider, - messagingCreateTextmagicProvider, - messagingUpdateTextmagicProvider, - messagingCreateTwilioProvider, - messagingUpdateTwilioProvider, - messagingCreateVonageProvider, - messagingUpdateVonageProvider, - messagingGetProvider, - messagingDeleteProvider, - messagingListProviderLogs, - messagingListSubscriberLogs, - messagingListTopics, - messagingCreateTopic, - messagingGetTopic, - messagingUpdateTopic, - messagingDeleteTopic, - messagingListTopicLogs, - messagingListSubscribers, - messagingCreateSubscriber, - messagingGetSubscriber, - messagingDeleteSubscriber -}; + diff --git a/lib/commands/migrations.js b/lib/commands/migrations.ts similarity index 62% rename from lib/commands/migrations.js rename to lib/commands/migrations.ts index 9f2093d9..b2c6a740 100644 --- a/lib/commands/migrations.js +++ b/lib/commands/migrations.ts @@ -1,31 +1,27 @@ -const fs = require('fs'); -const pathLib = require('path'); -const tar = require("tar"); -const ignore = require("ignore"); -const { promisify } = require('util'); -const libClient = require('../client.js'); -const { getAllFiles, showConsoleLink } = require('../utils.js'); -const { Command } = require('commander'); -const { sdkForProject, sdkForConsole } = require('../sdks') -const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } = require('../parser') -const { localConfig, globalConfig } = require("../config"); -const { File } = require('undici'); -const { ReadableStream } = require('stream/web'); - -/** - * @param {fs.ReadStream} readStream - * @returns {ReadableStream} - */ -function convertReadStreamToReadableStream(readStream) { +import fs = require('fs'); +import pathLib = require('path'); +import tar = require('tar'); +import ignore = require('ignore'); +import { promisify } from 'util'; +import Client from '../client'; +import { getAllFiles, showConsoleLink } from '../utils'; +import { Command } from 'commander'; +import { sdkForProject, sdkForConsole } from '../sdks'; +import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } from '../parser'; +import { localConfig, globalConfig } from '../config'; +import { File } from 'undici'; +import { ReadableStream } from 'stream/web'; + +function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ start(controller) { - readStream.on("data", (chunk) => { + readStream.on("data", (chunk: Buffer) => { controller.enqueue(chunk); }); readStream.on("end", () => { controller.close(); }); - readStream.on("error", (err) => { + readStream.on("error", (err: Error) => { controller.error(err); }); }, @@ -35,24 +31,20 @@ function convertReadStreamToReadableStream(readStream) { }); } -const migrations = new Command("migrations").description(commandDescriptions['migrations'] ?? '').configureHelp({ +export const migrations = new Command("migrations").description(commandDescriptions['migrations'] ?? '').configureHelp({ helpWidth: process.stdout.columns || 80 }) -/** - * @typedef {Object} MigrationsListRequestParams - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/databases#querying-documents). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: status, stage, source, destination, resources, statusCounters, resourceData, errors - * @property {string} search Search term to filter your list results. Max length: 256 chars. - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MigrationsListRequestParams} params - */ -const migrationsList = async ({queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MigrationsListRequestParams { + queries?: string[]; + search?: string; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const migrationsList = async ({queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined}: MigrationsListRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/migrations'; @@ -79,21 +71,17 @@ const migrationsList = async ({queries,search,total,parseOutput = true, override return response; } -/** - * @typedef {Object} MigrationsCreateAppwriteMigrationRequestParams - * @property {string[]} resources List of resources to migrate - * @property {string} endpoint Source Appwrite endpoint - * @property {string} projectId Source Project ID - * @property {string} apiKey Source API Key - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MigrationsCreateAppwriteMigrationRequestParams} params - */ -const migrationsCreateAppwriteMigration = async ({resources,endpoint,projectId,apiKey,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MigrationsCreateAppwriteMigrationRequestParams { + resources: string[]; + endpoint: string; + projectId: string; + apiKey: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const migrationsCreateAppwriteMigration = async ({resources,endpoint,projectId,apiKey,parseOutput = true, overrideForCli = false, sdk = undefined}: MigrationsCreateAppwriteMigrationRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/migrations/appwrite'; @@ -125,21 +113,17 @@ const migrationsCreateAppwriteMigration = async ({resources,endpoint,projectId,a return response; } -/** - * @typedef {Object} MigrationsGetAppwriteReportRequestParams - * @property {string[]} resources List of resources to migrate - * @property {string} endpoint Source's Appwrite Endpoint - * @property {string} projectID Source's Project ID - * @property {string} key Source's API Key - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MigrationsGetAppwriteReportRequestParams} params - */ -const migrationsGetAppwriteReport = async ({resources,endpoint,projectID,key,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MigrationsGetAppwriteReportRequestParams { + resources: string[]; + endpoint: string; + projectID: string; + key: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const migrationsGetAppwriteReport = async ({resources,endpoint,projectID,key,parseOutput = true, overrideForCli = false, sdk = undefined}: MigrationsGetAppwriteReportRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/migrations/appwrite/report'; @@ -169,26 +153,22 @@ const migrationsGetAppwriteReport = async ({resources,endpoint,projectID,key,par return response; } -/** - * @typedef {Object} MigrationsCreateCSVExportRequestParams - * @property {string} resourceId Composite ID in the format {databaseId:collectionId}, identifying a collection within a database to export. - * @property {string} filename The name of the file to be created for the export, excluding the .csv extension. - * @property {string[]} columns List of attributes to export. If empty, all attributes will be exported. You can use the '*' wildcard to export all attributes from the collection. - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK to filter documents to export. [Learn more about queries](https://appwrite.io/docs/databases#querying-documents). Maximum of 100 queries are allowed, each 4096 characters long. - * @property {string} delimiter The character that separates each column value. Default is comma. - * @property {string} enclosure The character that encloses each column value. Default is double quotes. - * @property {string} escape The escape character for the enclosure character. Default is double quotes. - * @property {boolean} header Whether to include the header row with column names. Default is true. - * @property {boolean} notify Set to true to receive an email when the export is complete. Default is true. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MigrationsCreateCSVExportRequestParams} params - */ -const migrationsCreateCSVExport = async ({resourceId,filename,columns,queries,delimiter,enclosure,escape,header,notify,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MigrationsCreateCSVExportRequestParams { + resourceId: string; + filename: string; + columns?: string[]; + queries?: string[]; + delimiter?: string; + enclosure?: string; + escape?: string; + header?: boolean; + notify?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const migrationsCreateCSVExport = async ({resourceId,filename,columns,queries,delimiter,enclosure,escape,header,notify,parseOutput = true, overrideForCli = false, sdk = undefined}: MigrationsCreateCSVExportRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/migrations/csv/exports'; @@ -236,21 +216,17 @@ const migrationsCreateCSVExport = async ({resourceId,filename,columns,queries,de return response; } -/** - * @typedef {Object} MigrationsCreateCSVImportRequestParams - * @property {string} bucketId Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). - * @property {string} fileId File ID. - * @property {string} resourceId Composite ID in the format {databaseId:collectionId}, identifying a collection within a database. - * @property {boolean} internalFile Is the file stored in an internal bucket? - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MigrationsCreateCSVImportRequestParams} params - */ -const migrationsCreateCSVImport = async ({bucketId,fileId,resourceId,internalFile,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MigrationsCreateCSVImportRequestParams { + bucketId: string; + fileId: string; + resourceId: string; + internalFile?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const migrationsCreateCSVImport = async ({bucketId,fileId,resourceId,internalFile,parseOutput = true, overrideForCli = false, sdk = undefined}: MigrationsCreateCSVImportRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/migrations/csv/imports'; @@ -281,19 +257,15 @@ const migrationsCreateCSVImport = async ({bucketId,fileId,resourceId,internalFil return response; } -/** - * @typedef {Object} MigrationsCreateFirebaseMigrationRequestParams - * @property {string[]} resources List of resources to migrate - * @property {string} serviceAccount JSON of the Firebase service account credentials - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MigrationsCreateFirebaseMigrationRequestParams} params - */ -const migrationsCreateFirebaseMigration = async ({resources,serviceAccount,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MigrationsCreateFirebaseMigrationRequestParams { + resources: string[]; + serviceAccount: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const migrationsCreateFirebaseMigration = async ({resources,serviceAccount,parseOutput = true, overrideForCli = false, sdk = undefined}: MigrationsCreateFirebaseMigrationRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/migrations/firebase'; @@ -319,19 +291,15 @@ const migrationsCreateFirebaseMigration = async ({resources,serviceAccount,parse return response; } -/** - * @typedef {Object} MigrationsGetFirebaseReportRequestParams - * @property {string[]} resources List of resources to migrate - * @property {string} serviceAccount JSON of the Firebase service account credentials - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MigrationsGetFirebaseReportRequestParams} params - */ -const migrationsGetFirebaseReport = async ({resources,serviceAccount,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MigrationsGetFirebaseReportRequestParams { + resources: string[]; + serviceAccount: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const migrationsGetFirebaseReport = async ({resources,serviceAccount,parseOutput = true, overrideForCli = false, sdk = undefined}: MigrationsGetFirebaseReportRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/migrations/firebase/report'; @@ -355,25 +323,21 @@ const migrationsGetFirebaseReport = async ({resources,serviceAccount,parseOutput return response; } -/** - * @typedef {Object} MigrationsCreateNHostMigrationRequestParams - * @property {string[]} resources List of resources to migrate - * @property {string} subdomain Source's Subdomain - * @property {string} region Source's Region - * @property {string} adminSecret Source's Admin Secret - * @property {string} database Source's Database Name - * @property {string} username Source's Database Username - * @property {string} password Source's Database Password - * @property {number} port Source's Database Port - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MigrationsCreateNHostMigrationRequestParams} params - */ -const migrationsCreateNHostMigration = async ({resources,subdomain,region,adminSecret,database,username,password,port,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MigrationsCreateNHostMigrationRequestParams { + resources: string[]; + subdomain: string; + region: string; + adminSecret: string; + database: string; + username: string; + password: string; + port?: number; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const migrationsCreateNHostMigration = async ({resources,subdomain,region,adminSecret,database,username,password,port,parseOutput = true, overrideForCli = false, sdk = undefined}: MigrationsCreateNHostMigrationRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/migrations/nhost'; @@ -417,25 +381,21 @@ const migrationsCreateNHostMigration = async ({resources,subdomain,region,adminS return response; } -/** - * @typedef {Object} MigrationsGetNHostReportRequestParams - * @property {string[]} resources List of resources to migrate. - * @property {string} subdomain Source's Subdomain. - * @property {string} region Source's Region. - * @property {string} adminSecret Source's Admin Secret. - * @property {string} database Source's Database Name. - * @property {string} username Source's Database Username. - * @property {string} password Source's Database Password. - * @property {number} port Source's Database Port. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MigrationsGetNHostReportRequestParams} params - */ -const migrationsGetNHostReport = async ({resources,subdomain,region,adminSecret,database,username,password,port,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MigrationsGetNHostReportRequestParams { + resources: string[]; + subdomain: string; + region: string; + adminSecret: string; + database: string; + username: string; + password: string; + port?: number; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const migrationsGetNHostReport = async ({resources,subdomain,region,adminSecret,database,username,password,port,parseOutput = true, overrideForCli = false, sdk = undefined}: MigrationsGetNHostReportRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/migrations/nhost/report'; @@ -477,24 +437,20 @@ const migrationsGetNHostReport = async ({resources,subdomain,region,adminSecret, return response; } -/** - * @typedef {Object} MigrationsCreateSupabaseMigrationRequestParams - * @property {string[]} resources List of resources to migrate - * @property {string} endpoint Source's Supabase Endpoint - * @property {string} apiKey Source's API Key - * @property {string} databaseHost Source's Database Host - * @property {string} username Source's Database Username - * @property {string} password Source's Database Password - * @property {number} port Source's Database Port - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MigrationsCreateSupabaseMigrationRequestParams} params - */ -const migrationsCreateSupabaseMigration = async ({resources,endpoint,apiKey,databaseHost,username,password,port,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MigrationsCreateSupabaseMigrationRequestParams { + resources: string[]; + endpoint: string; + apiKey: string; + databaseHost: string; + username: string; + password: string; + port?: number; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const migrationsCreateSupabaseMigration = async ({resources,endpoint,apiKey,databaseHost,username,password,port,parseOutput = true, overrideForCli = false, sdk = undefined}: MigrationsCreateSupabaseMigrationRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/migrations/supabase'; @@ -535,24 +491,20 @@ const migrationsCreateSupabaseMigration = async ({resources,endpoint,apiKey,data return response; } -/** - * @typedef {Object} MigrationsGetSupabaseReportRequestParams - * @property {string[]} resources List of resources to migrate - * @property {string} endpoint Source's Supabase Endpoint. - * @property {string} apiKey Source's API Key. - * @property {string} databaseHost Source's Database Host. - * @property {string} username Source's Database Username. - * @property {string} password Source's Database Password. - * @property {number} port Source's Database Port. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MigrationsGetSupabaseReportRequestParams} params - */ -const migrationsGetSupabaseReport = async ({resources,endpoint,apiKey,databaseHost,username,password,port,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MigrationsGetSupabaseReportRequestParams { + resources: string[]; + endpoint: string; + apiKey: string; + databaseHost: string; + username: string; + password: string; + port?: number; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const migrationsGetSupabaseReport = async ({resources,endpoint,apiKey,databaseHost,username,password,port,parseOutput = true, overrideForCli = false, sdk = undefined}: MigrationsGetSupabaseReportRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/migrations/supabase/report'; @@ -591,18 +543,14 @@ const migrationsGetSupabaseReport = async ({resources,endpoint,apiKey,databaseHo return response; } -/** - * @typedef {Object} MigrationsGetRequestParams - * @property {string} migrationId Migration unique ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MigrationsGetRequestParams} params - */ -const migrationsGet = async ({migrationId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MigrationsGetRequestParams { + migrationId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const migrationsGet = async ({migrationId,parseOutput = true, overrideForCli = false, sdk = undefined}: MigrationsGetRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/migrations/{migrationId}'.replace('{migrationId}', migrationId); @@ -620,18 +568,14 @@ const migrationsGet = async ({migrationId,parseOutput = true, overrideForCli = f return response; } -/** - * @typedef {Object} MigrationsRetryRequestParams - * @property {string} migrationId Migration unique ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MigrationsRetryRequestParams} params - */ -const migrationsRetry = async ({migrationId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MigrationsRetryRequestParams { + migrationId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const migrationsRetry = async ({migrationId,parseOutput = true, overrideForCli = false, sdk = undefined}: MigrationsRetryRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/migrations/{migrationId}'.replace('{migrationId}', migrationId); @@ -650,18 +594,14 @@ const migrationsRetry = async ({migrationId,parseOutput = true, overrideForCli = return response; } -/** - * @typedef {Object} MigrationsDeleteRequestParams - * @property {string} migrationId Migration ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {MigrationsDeleteRequestParams} params - */ -const migrationsDelete = async ({migrationId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface MigrationsDeleteRequestParams { + migrationId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const migrationsDelete = async ({migrationId,parseOutput = true, overrideForCli = false, sdk = undefined}: MigrationsDeleteRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/migrations/{migrationId}'.replace('{migrationId}', migrationId); @@ -685,7 +625,7 @@ migrations .description(`List all migrations in the current project. This endpoint returns a list of all migrations including their status, progress, and any errors that occurred during the migration process.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/databases#querying-documents). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: status, stage, source, destination, resources, statusCounters, resourceData, errors`) .option(`--search `, `Search term to filter your list results. Max length: 256 chars.`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(migrationsList)) migrations @@ -716,8 +656,8 @@ migrations .option(`--delimiter `, `The character that separates each column value. Default is comma.`) .option(`--enclosure `, `The character that encloses each column value. Default is double quotes.`) .option(`--escape `, `The escape character for the enclosure character. Default is double quotes.`) - .option(`--header [value]`, `Whether to include the header row with column names. Default is true.`, (value) => value === undefined ? true : parseBool(value)) - .option(`--notify [value]`, `Set to true to receive an email when the export is complete. Default is true.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--header [value]`, `Whether to include the header row with column names. Default is true.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--notify [value]`, `Set to true to receive an email when the export is complete. Default is true.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(migrationsCreateCSVExport)) migrations @@ -726,7 +666,7 @@ migrations .requiredOption(`--bucket-id `, `Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket).`) .requiredOption(`--file-id `, `File ID.`) .requiredOption(`--resource-id `, `Composite ID in the format {databaseId:collectionId}, identifying a collection within a database.`) - .option(`--internal-file [value]`, `Is the file stored in an internal bucket?`, (value) => value === undefined ? true : parseBool(value)) + .option(`--internal-file [value]`, `Is the file stored in an internal bucket?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(migrationsCreateCSVImport)) migrations @@ -811,20 +751,4 @@ migrations .requiredOption(`--migration-id `, `Migration ID.`) .action(actionRunner(migrationsDelete)) -module.exports = { - migrations, - migrationsList, - migrationsCreateAppwriteMigration, - migrationsGetAppwriteReport, - migrationsCreateCSVExport, - migrationsCreateCSVImport, - migrationsCreateFirebaseMigration, - migrationsGetFirebaseReport, - migrationsCreateNHostMigration, - migrationsGetNHostReport, - migrationsCreateSupabaseMigration, - migrationsGetSupabaseReport, - migrationsGet, - migrationsRetry, - migrationsDelete -}; + diff --git a/lib/commands/organizations.js b/lib/commands/organizations.js deleted file mode 100644 index a341d312..00000000 --- a/lib/commands/organizations.js +++ /dev/null @@ -1,48 +0,0 @@ -const { sdkForProject } = require('../sdks') -const { parse } = require('../parser') -const { showConsoleLink } = require('../utils.js'); - -/** - * @typedef {Object} OrganizationsListRequestParams - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name, total, billingPlan - * @property {string} search Search term to filter your list results. Max length: 256 chars. - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {OrganizationsListRequestParams} params - */ -const organizationsList = async ({queries, search, parseOutput = true, sdk = undefined, console}) => { - let client = !sdk ? await sdkForProject() : - sdk; - let apiPath = '/organizations'; - let payload = {}; - if (typeof queries !== 'undefined') { - payload['queries'] = queries; - } - if (typeof search !== 'undefined') { - payload['search'] = search; - } - - let response = undefined; - - response = await client.call('get', apiPath, { - 'content-type': 'application/json', - }, payload); - - if (parseOutput) { - if(console) { - showConsoleLink('organizations', 'list'); - } else { - parse(response) - } - } - - return response; - -} - -module.exports = { - organizationsList -} \ No newline at end of file diff --git a/lib/commands/organizations.ts b/lib/commands/organizations.ts new file mode 100644 index 00000000..977873a4 --- /dev/null +++ b/lib/commands/organizations.ts @@ -0,0 +1,46 @@ +import { sdkForProject } from '../sdks'; +import { parse } from '../parser'; +import { showConsoleLink } from '../utils'; +import Client from '../client'; + +interface OrganizationsListRequestParams { + queries?: string[]; + search?: string; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const organizationsList = async ({ + queries, + search, + parseOutput = true, + sdk = undefined, + console: showConsole +}: OrganizationsListRequestParams): Promise => { + let client = !sdk ? await sdkForProject() : sdk; + let apiPath = '/organizations'; + let payload: Record = {}; + + if (typeof queries !== 'undefined') { + payload['queries'] = queries; + } + if (typeof search !== 'undefined') { + payload['search'] = search; + } + + let response = await client.call('get', apiPath, { + 'content-type': 'application/json', + }, payload); + + if (parseOutput) { + if(showConsole) { + showConsoleLink('organizations', 'list'); + } else { + parse(response) + } + } + + return response; +} + diff --git a/lib/commands/project.js b/lib/commands/project.ts similarity index 56% rename from lib/commands/project.js rename to lib/commands/project.ts index cb9ebbc8..9e6f33d7 100644 --- a/lib/commands/project.js +++ b/lib/commands/project.ts @@ -1,31 +1,27 @@ -const fs = require('fs'); -const pathLib = require('path'); -const tar = require("tar"); -const ignore = require("ignore"); -const { promisify } = require('util'); -const libClient = require('../client.js'); -const { getAllFiles, showConsoleLink } = require('../utils.js'); -const { Command } = require('commander'); -const { sdkForProject, sdkForConsole } = require('../sdks') -const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } = require('../parser') -const { localConfig, globalConfig } = require("../config"); -const { File } = require('undici'); -const { ReadableStream } = require('stream/web'); - -/** - * @param {fs.ReadStream} readStream - * @returns {ReadableStream} - */ -function convertReadStreamToReadableStream(readStream) { +import fs = require('fs'); +import pathLib = require('path'); +import tar = require('tar'); +import ignore = require('ignore'); +import { promisify } from 'util'; +import Client from '../client'; +import { getAllFiles, showConsoleLink } from '../utils'; +import { Command } from 'commander'; +import { sdkForProject, sdkForConsole } from '../sdks'; +import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } from '../parser'; +import { localConfig, globalConfig } from '../config'; +import { File } from 'undici'; +import { ReadableStream } from 'stream/web'; + +function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ start(controller) { - readStream.on("data", (chunk) => { + readStream.on("data", (chunk: Buffer) => { controller.enqueue(chunk); }); readStream.on("end", () => { controller.close(); }); - readStream.on("error", (err) => { + readStream.on("error", (err: Error) => { controller.error(err); }); }, @@ -35,24 +31,20 @@ function convertReadStreamToReadableStream(readStream) { }); } -const project = new Command("project").description(commandDescriptions['project'] ?? '').configureHelp({ +export const project = new Command("project").description(commandDescriptions['project'] ?? '').configureHelp({ helpWidth: process.stdout.columns || 80 }) -/** - * @typedef {Object} ProjectGetUsageRequestParams - * @property {string} startDate Starting date for the usage - * @property {string} endDate End date for the usage - * @property {ProjectUsageRange} period Period used - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProjectGetUsageRequestParams} params - */ -const projectGetUsage = async ({startDate,endDate,period,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProjectGetUsageRequestParams { + startDate: string; + endDate: string; + period?: ProjectUsageRange; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const projectGetUsage = async ({startDate,endDate,period,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectGetUsageRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/project/usage'; @@ -79,17 +71,13 @@ const projectGetUsage = async ({startDate,endDate,period,parseOutput = true, ove return response; } -/** - * @typedef {Object} ProjectListVariablesRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProjectListVariablesRequestParams} params - */ -const projectListVariables = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProjectListVariablesRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const projectListVariables = async ({parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectListVariablesRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/project/variables'; @@ -107,20 +95,16 @@ const projectListVariables = async ({parseOutput = true, overrideForCli = false, return response; } -/** - * @typedef {Object} ProjectCreateVariableRequestParams - * @property {string} key Variable key. Max length: 255 chars. - * @property {string} value Variable value. Max length: 8192 chars. - * @property {boolean} secret Secret variables can be updated or deleted, but only projects can read them during build and runtime. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProjectCreateVariableRequestParams} params - */ -const projectCreateVariable = async ({key,value,secret,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProjectCreateVariableRequestParams { + key: string; + value: string; + secret?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const projectCreateVariable = async ({key,value,secret,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectCreateVariableRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/project/variables'; @@ -148,18 +132,14 @@ const projectCreateVariable = async ({key,value,secret,parseOutput = true, overr return response; } -/** - * @typedef {Object} ProjectGetVariableRequestParams - * @property {string} variableId Variable unique ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProjectGetVariableRequestParams} params - */ -const projectGetVariable = async ({variableId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProjectGetVariableRequestParams { + variableId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const projectGetVariable = async ({variableId,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectGetVariableRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/project/variables/{variableId}'.replace('{variableId}', variableId); @@ -177,21 +157,17 @@ const projectGetVariable = async ({variableId,parseOutput = true, overrideForCli return response; } -/** - * @typedef {Object} ProjectUpdateVariableRequestParams - * @property {string} variableId Variable unique ID. - * @property {string} key Variable key. Max length: 255 chars. - * @property {string} value Variable value. Max length: 8192 chars. - * @property {boolean} secret Secret variables can be updated or deleted, but only projects can read them during build and runtime. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProjectUpdateVariableRequestParams} params - */ -const projectUpdateVariable = async ({variableId,key,value,secret,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProjectUpdateVariableRequestParams { + variableId: string; + key: string; + value?: string; + secret?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const projectUpdateVariable = async ({variableId,key,value,secret,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectUpdateVariableRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/project/variables/{variableId}'.replace('{variableId}', variableId); @@ -219,18 +195,14 @@ const projectUpdateVariable = async ({variableId,key,value,secret,parseOutput = return response; } -/** - * @typedef {Object} ProjectDeleteVariableRequestParams - * @property {string} variableId Variable unique ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProjectDeleteVariableRequestParams} params - */ -const projectDeleteVariable = async ({variableId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProjectDeleteVariableRequestParams { + variableId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const projectDeleteVariable = async ({variableId,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectDeleteVariableRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/project/variables/{variableId}'.replace('{variableId}', variableId); @@ -267,7 +239,7 @@ project .description(`Create a new project variable. This variable will be accessible in all Appwrite Functions at runtime.`) .requiredOption(`--key `, `Variable key. Max length: 255 chars.`) .requiredOption(`--value `, `Variable value. Max length: 8192 chars.`) - .option(`--secret [value]`, `Secret variables can be updated or deleted, but only projects can read them during build and runtime.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--secret [value]`, `Secret variables can be updated or deleted, but only projects can read them during build and runtime.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(projectCreateVariable)) project @@ -282,7 +254,7 @@ project .requiredOption(`--variable-id `, `Variable unique ID.`) .requiredOption(`--key `, `Variable key. Max length: 255 chars.`) .option(`--value `, `Variable value. Max length: 8192 chars.`) - .option(`--secret [value]`, `Secret variables can be updated or deleted, but only projects can read them during build and runtime.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--secret [value]`, `Secret variables can be updated or deleted, but only projects can read them during build and runtime.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(projectUpdateVariable)) project @@ -291,12 +263,4 @@ project .requiredOption(`--variable-id `, `Variable unique ID.`) .action(actionRunner(projectDeleteVariable)) -module.exports = { - project, - projectGetUsage, - projectListVariables, - projectCreateVariable, - projectGetVariable, - projectUpdateVariable, - projectDeleteVariable -}; + diff --git a/lib/commands/projects.js b/lib/commands/projects.ts similarity index 61% rename from lib/commands/projects.js rename to lib/commands/projects.ts index 607ca9a6..f8b2c8c5 100644 --- a/lib/commands/projects.js +++ b/lib/commands/projects.ts @@ -1,31 +1,27 @@ -const fs = require('fs'); -const pathLib = require('path'); -const tar = require("tar"); -const ignore = require("ignore"); -const { promisify } = require('util'); -const libClient = require('../client.js'); -const { getAllFiles, showConsoleLink } = require('../utils.js'); -const { Command } = require('commander'); -const { sdkForProject, sdkForConsole } = require('../sdks') -const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } = require('../parser') -const { localConfig, globalConfig } = require("../config"); -const { File } = require('undici'); -const { ReadableStream } = require('stream/web'); - -/** - * @param {fs.ReadStream} readStream - * @returns {ReadableStream} - */ -function convertReadStreamToReadableStream(readStream) { +import fs = require('fs'); +import pathLib = require('path'); +import tar = require('tar'); +import ignore = require('ignore'); +import { promisify } from 'util'; +import Client from '../client'; +import { getAllFiles, showConsoleLink } from '../utils'; +import { Command } from 'commander'; +import { sdkForProject, sdkForConsole } from '../sdks'; +import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } from '../parser'; +import { localConfig, globalConfig } from '../config'; +import { File } from 'undici'; +import { ReadableStream } from 'stream/web'; + +function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ start(controller) { - readStream.on("data", (chunk) => { + readStream.on("data", (chunk: Buffer) => { controller.enqueue(chunk); }); readStream.on("end", () => { controller.close(); }); - readStream.on("error", (err) => { + readStream.on("error", (err: Error) => { controller.error(err); }); }, @@ -35,24 +31,21 @@ function convertReadStreamToReadableStream(readStream) { }); } -const projects = new Command("projects").description(commandDescriptions['projects'] ?? '').configureHelp({ +export const projects = new Command("projects").description(commandDescriptions['projects'] ?? '').configureHelp({ helpWidth: process.stdout.columns || 80 }) -/** - * @typedef {Object} ProjectsListRequestParams - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name, teamId - * @property {string} search Search term to filter your list results. Max length: 256 chars. - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProjectsListRequestParams} params - */ -const projectsList = async ({queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface ProjectsListRequestParams { + queries?: string[]; + search?: string; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const projectsList = async ({queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: ProjectsListRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects'; @@ -73,7 +66,7 @@ const projectsList = async ({queries,search,total,parseOutput = true, overrideFo }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('projects', 'list'); } else { parse(response) @@ -83,30 +76,26 @@ const projectsList = async ({queries,search,total,parseOutput = true, overrideFo return response; } -/** - * @typedef {Object} ProjectsCreateRequestParams - * @property {string} projectId Unique Id. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, and hyphen. Can't start with a special char. Max length is 36 chars. - * @property {string} name Project name. Max length: 128 chars. - * @property {string} teamId Team unique ID. - * @property {Region} region Project Region. - * @property {string} description Project description. Max length: 256 chars. - * @property {string} logo Project logo. - * @property {string} url Project URL. - * @property {string} legalName Project legal Name. Max length: 256 chars. - * @property {string} legalCountry Project legal Country. Max length: 256 chars. - * @property {string} legalState Project legal State. Max length: 256 chars. - * @property {string} legalCity Project legal City. Max length: 256 chars. - * @property {string} legalAddress Project legal Address. Max length: 256 chars. - * @property {string} legalTaxId Project legal Tax ID. Max length: 256 chars. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProjectsCreateRequestParams} params - */ -const projectsCreate = async ({projectId,name,teamId,region,description,logo,url,legalName,legalCountry,legalState,legalCity,legalAddress,legalTaxId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProjectsCreateRequestParams { + projectId: string; + name: string; + teamId: string; + region?: Region; + description?: string; + logo?: string; + url?: string; + legalName?: string; + legalCountry?: string; + legalState?: string; + legalCity?: string; + legalAddress?: string; + legalTaxId?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const projectsCreate = async ({projectId,name,teamId,region,description,logo,url,legalName,legalCountry,legalState,legalCity,legalAddress,legalTaxId,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsCreateRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects'; @@ -164,18 +153,15 @@ const projectsCreate = async ({projectId,name,teamId,region,description,logo,url return response; } -/** - * @typedef {Object} ProjectsGetRequestParams - * @property {string} projectId Project unique ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface ProjectsGetRequestParams { + projectId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {ProjectsGetRequestParams} params - */ -const projectsGet = async ({projectId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const projectsGet = async ({projectId,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: ProjectsGetRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}'.replace('{projectId}', projectId); @@ -187,7 +173,7 @@ const projectsGet = async ({projectId,parseOutput = true, overrideForCli = false }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('projects', 'get', projectId); } else { parse(response) @@ -197,28 +183,24 @@ const projectsGet = async ({projectId,parseOutput = true, overrideForCli = false return response; } -/** - * @typedef {Object} ProjectsUpdateRequestParams - * @property {string} projectId Project unique ID. - * @property {string} name Project name. Max length: 128 chars. - * @property {string} description Project description. Max length: 256 chars. - * @property {string} logo Project logo. - * @property {string} url Project URL. - * @property {string} legalName Project legal name. Max length: 256 chars. - * @property {string} legalCountry Project legal country. Max length: 256 chars. - * @property {string} legalState Project legal state. Max length: 256 chars. - * @property {string} legalCity Project legal city. Max length: 256 chars. - * @property {string} legalAddress Project legal address. Max length: 256 chars. - * @property {string} legalTaxId Project legal tax ID. Max length: 256 chars. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProjectsUpdateRequestParams} params - */ -const projectsUpdate = async ({projectId,name,description,logo,url,legalName,legalCountry,legalState,legalCity,legalAddress,legalTaxId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProjectsUpdateRequestParams { + projectId: string; + name: string; + description?: string; + logo?: string; + url?: string; + legalName?: string; + legalCountry?: string; + legalState?: string; + legalCity?: string; + legalAddress?: string; + legalTaxId?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const projectsUpdate = async ({projectId,name,description,logo,url,legalName,legalCountry,legalState,legalCity,legalAddress,legalTaxId,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsUpdateRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}'.replace('{projectId}', projectId); @@ -267,18 +249,14 @@ const projectsUpdate = async ({projectId,name,description,logo,url,legalName,leg return response; } -/** - * @typedef {Object} ProjectsDeleteRequestParams - * @property {string} projectId Project unique ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface ProjectsDeleteRequestParams { + projectId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {ProjectsDeleteRequestParams} params - */ -const projectsDelete = async ({projectId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const projectsDelete = async ({projectId,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsDeleteRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}'.replace('{projectId}', projectId); @@ -297,20 +275,16 @@ const projectsDelete = async ({projectId,parseOutput = true, overrideForCli = fa return response; } -/** - * @typedef {Object} ProjectsUpdateAPIStatusRequestParams - * @property {string} projectId Project unique ID. - * @property {Api} api API name. - * @property {boolean} status API status. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProjectsUpdateAPIStatusRequestParams} params - */ -const projectsUpdateAPIStatus = async ({projectId,api,status,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProjectsUpdateAPIStatusRequestParams { + projectId: string; + api: Api; + status: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const projectsUpdateAPIStatus = async ({projectId,api,status,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsUpdateAPIStatusRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/api'.replace('{projectId}', projectId); @@ -335,19 +309,15 @@ const projectsUpdateAPIStatus = async ({projectId,api,status,parseOutput = true, return response; } -/** - * @typedef {Object} ProjectsUpdateAPIStatusAllRequestParams - * @property {string} projectId Project unique ID. - * @property {boolean} status API status. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface ProjectsUpdateAPIStatusAllRequestParams { + projectId: string; + status: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {ProjectsUpdateAPIStatusAllRequestParams} params - */ -const projectsUpdateAPIStatusAll = async ({projectId,status,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const projectsUpdateAPIStatusAll = async ({projectId,status,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsUpdateAPIStatusAllRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/api/all'.replace('{projectId}', projectId); @@ -369,19 +339,15 @@ const projectsUpdateAPIStatusAll = async ({projectId,status,parseOutput = true, return response; } -/** - * @typedef {Object} ProjectsUpdateAuthDurationRequestParams - * @property {string} projectId Project unique ID. - * @property {number} duration Project session length in seconds. Max length: 31536000 seconds. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface ProjectsUpdateAuthDurationRequestParams { + projectId: string; + duration: number; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {ProjectsUpdateAuthDurationRequestParams} params - */ -const projectsUpdateAuthDuration = async ({projectId,duration,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const projectsUpdateAuthDuration = async ({projectId,duration,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsUpdateAuthDurationRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/auth/duration'.replace('{projectId}', projectId); @@ -403,19 +369,15 @@ const projectsUpdateAuthDuration = async ({projectId,duration,parseOutput = true return response; } -/** - * @typedef {Object} ProjectsUpdateAuthLimitRequestParams - * @property {string} projectId Project unique ID. - * @property {number} limit Set the max number of users allowed in this project. Use 0 for unlimited. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface ProjectsUpdateAuthLimitRequestParams { + projectId: string; + limit: number; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {ProjectsUpdateAuthLimitRequestParams} params - */ -const projectsUpdateAuthLimit = async ({projectId,limit,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const projectsUpdateAuthLimit = async ({projectId,limit,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsUpdateAuthLimitRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/auth/limit'.replace('{projectId}', projectId); @@ -437,19 +399,15 @@ const projectsUpdateAuthLimit = async ({projectId,limit,parseOutput = true, over return response; } -/** - * @typedef {Object} ProjectsUpdateAuthSessionsLimitRequestParams - * @property {string} projectId Project unique ID. - * @property {number} limit Set the max number of users allowed in this project. Value allowed is between 1-100. Default is 10 - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface ProjectsUpdateAuthSessionsLimitRequestParams { + projectId: string; + limit: number; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {ProjectsUpdateAuthSessionsLimitRequestParams} params - */ -const projectsUpdateAuthSessionsLimit = async ({projectId,limit,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const projectsUpdateAuthSessionsLimit = async ({projectId,limit,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsUpdateAuthSessionsLimitRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/auth/max-sessions'.replace('{projectId}', projectId); @@ -471,21 +429,17 @@ const projectsUpdateAuthSessionsLimit = async ({projectId,limit,parseOutput = tr return response; } -/** - * @typedef {Object} ProjectsUpdateMembershipsPrivacyRequestParams - * @property {string} projectId Project unique ID. - * @property {boolean} userName Set to true to show userName to members of a team. - * @property {boolean} userEmail Set to true to show email to members of a team. - * @property {boolean} mfa Set to true to show mfa to members of a team. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProjectsUpdateMembershipsPrivacyRequestParams} params - */ -const projectsUpdateMembershipsPrivacy = async ({projectId,userName,userEmail,mfa,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProjectsUpdateMembershipsPrivacyRequestParams { + projectId: string; + userName: boolean; + userEmail: boolean; + mfa: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const projectsUpdateMembershipsPrivacy = async ({projectId,userName,userEmail,mfa,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsUpdateMembershipsPrivacyRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/auth/memberships-privacy'.replace('{projectId}', projectId); @@ -513,19 +467,15 @@ const projectsUpdateMembershipsPrivacy = async ({projectId,userName,userEmail,mf return response; } -/** - * @typedef {Object} ProjectsUpdateMockNumbersRequestParams - * @property {string} projectId Project unique ID. - * @property {object[]} numbers An array of mock numbers and their corresponding verification codes (OTPs). Each number should be a valid E.164 formatted phone number. Maximum of 10 numbers are allowed. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface ProjectsUpdateMockNumbersRequestParams { + projectId: string; + numbers: object[]; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {ProjectsUpdateMockNumbersRequestParams} params - */ -const projectsUpdateMockNumbers = async ({projectId,numbers,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const projectsUpdateMockNumbers = async ({projectId,numbers,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsUpdateMockNumbersRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/auth/mock-numbers'.replace('{projectId}', projectId); @@ -548,19 +498,15 @@ const projectsUpdateMockNumbers = async ({projectId,numbers,parseOutput = true, return response; } -/** - * @typedef {Object} ProjectsUpdateAuthPasswordDictionaryRequestParams - * @property {string} projectId Project unique ID. - * @property {boolean} enabled Set whether or not to enable checking user's password against most commonly used passwords. Default is false. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface ProjectsUpdateAuthPasswordDictionaryRequestParams { + projectId: string; + enabled: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {ProjectsUpdateAuthPasswordDictionaryRequestParams} params - */ -const projectsUpdateAuthPasswordDictionary = async ({projectId,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const projectsUpdateAuthPasswordDictionary = async ({projectId,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsUpdateAuthPasswordDictionaryRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/auth/password-dictionary'.replace('{projectId}', projectId); @@ -582,19 +528,15 @@ const projectsUpdateAuthPasswordDictionary = async ({projectId,enabled,parseOutp return response; } -/** - * @typedef {Object} ProjectsUpdateAuthPasswordHistoryRequestParams - * @property {string} projectId Project unique ID. - * @property {number} limit Set the max number of passwords to store in user history. User can't choose a new password that is already stored in the password history list. Max number of passwords allowed in history is20. Default value is 0 - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface ProjectsUpdateAuthPasswordHistoryRequestParams { + projectId: string; + limit: number; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {ProjectsUpdateAuthPasswordHistoryRequestParams} params - */ -const projectsUpdateAuthPasswordHistory = async ({projectId,limit,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const projectsUpdateAuthPasswordHistory = async ({projectId,limit,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsUpdateAuthPasswordHistoryRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/auth/password-history'.replace('{projectId}', projectId); @@ -616,19 +558,15 @@ const projectsUpdateAuthPasswordHistory = async ({projectId,limit,parseOutput = return response; } -/** - * @typedef {Object} ProjectsUpdatePersonalDataCheckRequestParams - * @property {string} projectId Project unique ID. - * @property {boolean} enabled Set whether or not to check a password for similarity with personal data. Default is false. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface ProjectsUpdatePersonalDataCheckRequestParams { + projectId: string; + enabled: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {ProjectsUpdatePersonalDataCheckRequestParams} params - */ -const projectsUpdatePersonalDataCheck = async ({projectId,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const projectsUpdatePersonalDataCheck = async ({projectId,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsUpdatePersonalDataCheckRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/auth/personal-data'.replace('{projectId}', projectId); @@ -650,19 +588,15 @@ const projectsUpdatePersonalDataCheck = async ({projectId,enabled,parseOutput = return response; } -/** - * @typedef {Object} ProjectsUpdateSessionAlertsRequestParams - * @property {string} projectId Project unique ID. - * @property {boolean} alerts Set to true to enable session emails. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface ProjectsUpdateSessionAlertsRequestParams { + projectId: string; + alerts: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {ProjectsUpdateSessionAlertsRequestParams} params - */ -const projectsUpdateSessionAlerts = async ({projectId,alerts,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const projectsUpdateSessionAlerts = async ({projectId,alerts,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsUpdateSessionAlertsRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/auth/session-alerts'.replace('{projectId}', projectId); @@ -684,19 +618,15 @@ const projectsUpdateSessionAlerts = async ({projectId,alerts,parseOutput = true, return response; } -/** - * @typedef {Object} ProjectsUpdateSessionInvalidationRequestParams - * @property {string} projectId Project unique ID. - * @property {boolean} enabled Update authentication session invalidation status. Use this endpoint to enable or disable session invalidation on password change - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface ProjectsUpdateSessionInvalidationRequestParams { + projectId: string; + enabled: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {ProjectsUpdateSessionInvalidationRequestParams} params - */ -const projectsUpdateSessionInvalidation = async ({projectId,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const projectsUpdateSessionInvalidation = async ({projectId,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsUpdateSessionInvalidationRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/auth/session-invalidation'.replace('{projectId}', projectId); @@ -718,20 +648,16 @@ const projectsUpdateSessionInvalidation = async ({projectId,enabled,parseOutput return response; } -/** - * @typedef {Object} ProjectsUpdateAuthStatusRequestParams - * @property {string} projectId Project unique ID. - * @property {AuthMethod} method Auth Method. Possible values: email-password,magic-url,email-otp,anonymous,invites,jwt,phone - * @property {boolean} status Set the status of this auth method. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProjectsUpdateAuthStatusRequestParams} params - */ -const projectsUpdateAuthStatus = async ({projectId,method,status,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProjectsUpdateAuthStatusRequestParams { + projectId: string; + method: AuthMethod; + status: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const projectsUpdateAuthStatus = async ({projectId,method,status,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsUpdateAuthStatusRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/auth/{method}'.replace('{projectId}', projectId).replace('{method}', method); @@ -753,19 +679,16 @@ const projectsUpdateAuthStatus = async ({projectId,method,status,parseOutput = t return response; } -/** - * @typedef {Object} ProjectsListDevKeysRequestParams - * @property {string} projectId Project unique ID. - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: accessedAt, expire - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface ProjectsListDevKeysRequestParams { + projectId: string; + queries?: string[]; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {ProjectsListDevKeysRequestParams} params - */ -const projectsListDevKeys = async ({projectId,queries,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const projectsListDevKeys = async ({projectId,queries,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: ProjectsListDevKeysRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/dev-keys'.replace('{projectId}', projectId); @@ -780,7 +703,7 @@ const projectsListDevKeys = async ({projectId,queries,parseOutput = true, overri }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('projects', 'listDevKeys', projectId); } else { parse(response) @@ -790,20 +713,16 @@ const projectsListDevKeys = async ({projectId,queries,parseOutput = true, overri return response; } -/** - * @typedef {Object} ProjectsCreateDevKeyRequestParams - * @property {string} projectId Project unique ID. - * @property {string} name Key name. Max length: 128 chars. - * @property {string} expire Expiration time in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProjectsCreateDevKeyRequestParams} params - */ -const projectsCreateDevKey = async ({projectId,name,expire,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProjectsCreateDevKeyRequestParams { + projectId: string; + name: string; + expire: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const projectsCreateDevKey = async ({projectId,name,expire,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsCreateDevKeyRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/dev-keys'.replace('{projectId}', projectId); @@ -828,19 +747,16 @@ const projectsCreateDevKey = async ({projectId,name,expire,parseOutput = true, o return response; } -/** - * @typedef {Object} ProjectsGetDevKeyRequestParams - * @property {string} projectId Project unique ID. - * @property {string} keyId Key unique ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface ProjectsGetDevKeyRequestParams { + projectId: string; + keyId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {ProjectsGetDevKeyRequestParams} params - */ -const projectsGetDevKey = async ({projectId,keyId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const projectsGetDevKey = async ({projectId,keyId,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: ProjectsGetDevKeyRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/dev-keys/{keyId}'.replace('{projectId}', projectId).replace('{keyId}', keyId); @@ -852,7 +768,7 @@ const projectsGetDevKey = async ({projectId,keyId,parseOutput = true, overrideFo }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('projects', 'getDevKey', projectId, keyId); } else { parse(response) @@ -862,21 +778,17 @@ const projectsGetDevKey = async ({projectId,keyId,parseOutput = true, overrideFo return response; } -/** - * @typedef {Object} ProjectsUpdateDevKeyRequestParams - * @property {string} projectId Project unique ID. - * @property {string} keyId Key unique ID. - * @property {string} name Key name. Max length: 128 chars. - * @property {string} expire Expiration time in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProjectsUpdateDevKeyRequestParams} params - */ -const projectsUpdateDevKey = async ({projectId,keyId,name,expire,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProjectsUpdateDevKeyRequestParams { + projectId: string; + keyId: string; + name: string; + expire: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const projectsUpdateDevKey = async ({projectId,keyId,name,expire,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsUpdateDevKeyRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/dev-keys/{keyId}'.replace('{projectId}', projectId).replace('{keyId}', keyId); @@ -901,19 +813,15 @@ const projectsUpdateDevKey = async ({projectId,keyId,name,expire,parseOutput = t return response; } -/** - * @typedef {Object} ProjectsDeleteDevKeyRequestParams - * @property {string} projectId Project unique ID. - * @property {string} keyId Key unique ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface ProjectsDeleteDevKeyRequestParams { + projectId: string; + keyId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {ProjectsDeleteDevKeyRequestParams} params - */ -const projectsDeleteDevKey = async ({projectId,keyId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const projectsDeleteDevKey = async ({projectId,keyId,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsDeleteDevKeyRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/dev-keys/{keyId}'.replace('{projectId}', projectId).replace('{keyId}', keyId); @@ -932,20 +840,16 @@ const projectsDeleteDevKey = async ({projectId,keyId,parseOutput = true, overrid return response; } -/** - * @typedef {Object} ProjectsCreateJWTRequestParams - * @property {string} projectId Project unique ID. - * @property {string[]} scopes List of scopes allowed for JWT key. Maximum of 100 scopes are allowed. - * @property {number} duration Time in seconds before JWT expires. Default duration is 900 seconds, and maximum is 3600 seconds. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProjectsCreateJWTRequestParams} params - */ -const projectsCreateJWT = async ({projectId,scopes,duration,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProjectsCreateJWTRequestParams { + projectId: string; + scopes: string[]; + duration?: number; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const projectsCreateJWT = async ({projectId,scopes,duration,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsCreateJWTRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/jwts'.replace('{projectId}', projectId); @@ -971,19 +875,16 @@ const projectsCreateJWT = async ({projectId,scopes,duration,parseOutput = true, return response; } -/** - * @typedef {Object} ProjectsListKeysRequestParams - * @property {string} projectId Project unique ID. - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface ProjectsListKeysRequestParams { + projectId: string; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {ProjectsListKeysRequestParams} params - */ -const projectsListKeys = async ({projectId,total,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const projectsListKeys = async ({projectId,total,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: ProjectsListKeysRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/keys'.replace('{projectId}', projectId); @@ -998,7 +899,7 @@ const projectsListKeys = async ({projectId,total,parseOutput = true, overrideFor }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('projects', 'listKeys', projectId); } else { parse(response) @@ -1008,21 +909,17 @@ const projectsListKeys = async ({projectId,total,parseOutput = true, overrideFor return response; } -/** - * @typedef {Object} ProjectsCreateKeyRequestParams - * @property {string} projectId Project unique ID. - * @property {string} name Key name. Max length: 128 chars. - * @property {string[]} scopes Key scopes list. Maximum of 100 scopes are allowed. - * @property {string} expire Expiration time in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. Use null for unlimited expiration. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProjectsCreateKeyRequestParams} params - */ -const projectsCreateKey = async ({projectId,name,scopes,expire,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProjectsCreateKeyRequestParams { + projectId: string; + name: string; + scopes: string[]; + expire?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const projectsCreateKey = async ({projectId,name,scopes,expire,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsCreateKeyRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/keys'.replace('{projectId}', projectId); @@ -1051,19 +948,16 @@ const projectsCreateKey = async ({projectId,name,scopes,expire,parseOutput = tru return response; } -/** - * @typedef {Object} ProjectsGetKeyRequestParams - * @property {string} projectId Project unique ID. - * @property {string} keyId Key unique ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface ProjectsGetKeyRequestParams { + projectId: string; + keyId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {ProjectsGetKeyRequestParams} params - */ -const projectsGetKey = async ({projectId,keyId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const projectsGetKey = async ({projectId,keyId,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: ProjectsGetKeyRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/keys/{keyId}'.replace('{projectId}', projectId).replace('{keyId}', keyId); @@ -1075,7 +969,7 @@ const projectsGetKey = async ({projectId,keyId,parseOutput = true, overrideForCl }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('projects', 'getKey', projectId, keyId); } else { parse(response) @@ -1085,22 +979,18 @@ const projectsGetKey = async ({projectId,keyId,parseOutput = true, overrideForCl return response; } -/** - * @typedef {Object} ProjectsUpdateKeyRequestParams - * @property {string} projectId Project unique ID. - * @property {string} keyId Key unique ID. - * @property {string} name Key name. Max length: 128 chars. - * @property {string[]} scopes Key scopes list. Maximum of 100 events are allowed. - * @property {string} expire Expiration time in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. Use null for unlimited expiration. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProjectsUpdateKeyRequestParams} params - */ -const projectsUpdateKey = async ({projectId,keyId,name,scopes,expire,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProjectsUpdateKeyRequestParams { + projectId: string; + keyId: string; + name: string; + scopes: string[]; + expire?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const projectsUpdateKey = async ({projectId,keyId,name,scopes,expire,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsUpdateKeyRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/keys/{keyId}'.replace('{projectId}', projectId).replace('{keyId}', keyId); @@ -1129,19 +1019,15 @@ const projectsUpdateKey = async ({projectId,keyId,name,scopes,expire,parseOutput return response; } -/** - * @typedef {Object} ProjectsDeleteKeyRequestParams - * @property {string} projectId Project unique ID. - * @property {string} keyId Key unique ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface ProjectsDeleteKeyRequestParams { + projectId: string; + keyId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {ProjectsDeleteKeyRequestParams} params - */ -const projectsDeleteKey = async ({projectId,keyId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const projectsDeleteKey = async ({projectId,keyId,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsDeleteKeyRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/keys/{keyId}'.replace('{projectId}', projectId).replace('{keyId}', keyId); @@ -1160,22 +1046,18 @@ const projectsDeleteKey = async ({projectId,keyId,parseOutput = true, overrideFo return response; } -/** - * @typedef {Object} ProjectsUpdateOAuth2RequestParams - * @property {string} projectId Project unique ID. - * @property {OAuthProvider} provider Provider Name - * @property {string} appId Provider app ID. Max length: 256 chars. - * @property {string} secret Provider secret key. Max length: 512 chars. - * @property {boolean} enabled Provider status. Set to 'false' to disable new session creation. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProjectsUpdateOAuth2RequestParams} params - */ -const projectsUpdateOAuth2 = async ({projectId,provider,appId,secret,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProjectsUpdateOAuth2RequestParams { + projectId: string; + provider: OAuthProvider; + appId?: string; + secret?: string; + enabled?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const projectsUpdateOAuth2 = async ({projectId,provider,appId,secret,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsUpdateOAuth2RequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/oauth2'.replace('{projectId}', projectId); @@ -1206,19 +1088,16 @@ const projectsUpdateOAuth2 = async ({projectId,provider,appId,secret,enabled,par return response; } -/** - * @typedef {Object} ProjectsListPlatformsRequestParams - * @property {string} projectId Project unique ID. - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface ProjectsListPlatformsRequestParams { + projectId: string; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {ProjectsListPlatformsRequestParams} params - */ -const projectsListPlatforms = async ({projectId,total,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const projectsListPlatforms = async ({projectId,total,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: ProjectsListPlatformsRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/platforms'.replace('{projectId}', projectId); @@ -1233,7 +1112,7 @@ const projectsListPlatforms = async ({projectId,total,parseOutput = true, overri }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('projects', 'listPlatforms', projectId); } else { parse(response) @@ -1243,23 +1122,19 @@ const projectsListPlatforms = async ({projectId,total,parseOutput = true, overri return response; } -/** - * @typedef {Object} ProjectsCreatePlatformRequestParams - * @property {string} projectId Project unique ID. - * @property {PlatformType} type Platform type. Possible values are: web, flutter-web, flutter-ios, flutter-android, flutter-linux, flutter-macos, flutter-windows, apple-ios, apple-macos, apple-watchos, apple-tvos, android, unity, react-native-ios, react-native-android. - * @property {string} name Platform name. Max length: 128 chars. - * @property {string} key Package name for Android or bundle ID for iOS or macOS. Max length: 256 chars. - * @property {string} store App store or Google Play store ID. Max length: 256 chars. - * @property {string} hostname Platform client hostname. Max length: 256 chars. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProjectsCreatePlatformRequestParams} params - */ -const projectsCreatePlatform = async ({projectId,type,name,key,store,hostname,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProjectsCreatePlatformRequestParams { + projectId: string; + type: PlatformType; + name: string; + key?: string; + store?: string; + hostname?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const projectsCreatePlatform = async ({projectId,type,name,key,store,hostname,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsCreatePlatformRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/platforms'.replace('{projectId}', projectId); @@ -1293,19 +1168,16 @@ const projectsCreatePlatform = async ({projectId,type,name,key,store,hostname,pa return response; } -/** - * @typedef {Object} ProjectsGetPlatformRequestParams - * @property {string} projectId Project unique ID. - * @property {string} platformId Platform unique ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface ProjectsGetPlatformRequestParams { + projectId: string; + platformId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {ProjectsGetPlatformRequestParams} params - */ -const projectsGetPlatform = async ({projectId,platformId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const projectsGetPlatform = async ({projectId,platformId,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: ProjectsGetPlatformRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/platforms/{platformId}'.replace('{projectId}', projectId).replace('{platformId}', platformId); @@ -1317,7 +1189,7 @@ const projectsGetPlatform = async ({projectId,platformId,parseOutput = true, ove }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('projects', 'getPlatform', projectId, platformId); } else { parse(response) @@ -1327,23 +1199,19 @@ const projectsGetPlatform = async ({projectId,platformId,parseOutput = true, ove return response; } -/** - * @typedef {Object} ProjectsUpdatePlatformRequestParams - * @property {string} projectId Project unique ID. - * @property {string} platformId Platform unique ID. - * @property {string} name Platform name. Max length: 128 chars. - * @property {string} key Package name for android or bundle ID for iOS. Max length: 256 chars. - * @property {string} store App store or Google Play store ID. Max length: 256 chars. - * @property {string} hostname Platform client URL. Max length: 256 chars. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProjectsUpdatePlatformRequestParams} params - */ -const projectsUpdatePlatform = async ({projectId,platformId,name,key,store,hostname,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProjectsUpdatePlatformRequestParams { + projectId: string; + platformId: string; + name: string; + key?: string; + store?: string; + hostname?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const projectsUpdatePlatform = async ({projectId,platformId,name,key,store,hostname,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsUpdatePlatformRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/platforms/{platformId}'.replace('{projectId}', projectId).replace('{platformId}', platformId); @@ -1374,19 +1242,15 @@ const projectsUpdatePlatform = async ({projectId,platformId,name,key,store,hostn return response; } -/** - * @typedef {Object} ProjectsDeletePlatformRequestParams - * @property {string} projectId Project unique ID. - * @property {string} platformId Platform unique ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface ProjectsDeletePlatformRequestParams { + projectId: string; + platformId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {ProjectsDeletePlatformRequestParams} params - */ -const projectsDeletePlatform = async ({projectId,platformId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const projectsDeletePlatform = async ({projectId,platformId,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsDeletePlatformRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/platforms/{platformId}'.replace('{projectId}', projectId).replace('{platformId}', platformId); @@ -1405,20 +1269,16 @@ const projectsDeletePlatform = async ({projectId,platformId,parseOutput = true, return response; } -/** - * @typedef {Object} ProjectsUpdateServiceStatusRequestParams - * @property {string} projectId Project unique ID. - * @property {ApiService} service Service name. - * @property {boolean} status Service status. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProjectsUpdateServiceStatusRequestParams} params - */ -const projectsUpdateServiceStatus = async ({projectId,service,status,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProjectsUpdateServiceStatusRequestParams { + projectId: string; + service: ApiService; + status: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const projectsUpdateServiceStatus = async ({projectId,service,status,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsUpdateServiceStatusRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/service'.replace('{projectId}', projectId); @@ -1443,19 +1303,15 @@ const projectsUpdateServiceStatus = async ({projectId,service,status,parseOutput return response; } -/** - * @typedef {Object} ProjectsUpdateServiceStatusAllRequestParams - * @property {string} projectId Project unique ID. - * @property {boolean} status Service status. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface ProjectsUpdateServiceStatusAllRequestParams { + projectId: string; + status: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {ProjectsUpdateServiceStatusAllRequestParams} params - */ -const projectsUpdateServiceStatusAll = async ({projectId,status,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const projectsUpdateServiceStatusAll = async ({projectId,status,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsUpdateServiceStatusAllRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/service/all'.replace('{projectId}', projectId); @@ -1477,27 +1333,23 @@ const projectsUpdateServiceStatusAll = async ({projectId,status,parseOutput = tr return response; } -/** - * @typedef {Object} ProjectsUpdateSMTPRequestParams - * @property {string} projectId Project unique ID. - * @property {boolean} enabled Enable custom SMTP service - * @property {string} senderName Name of the email sender - * @property {string} senderEmail Email of the sender - * @property {string} replyTo Reply to email - * @property {string} host SMTP server host name - * @property {number} port SMTP server port - * @property {string} username SMTP server username - * @property {string} password SMTP server password - * @property {SMTPSecure} secure Does SMTP server use secure connection - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProjectsUpdateSMTPRequestParams} params - */ -const projectsUpdateSMTP = async ({projectId,enabled,senderName,senderEmail,replyTo,host,port,username,password,secure,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProjectsUpdateSMTPRequestParams { + projectId: string; + enabled: boolean; + senderName?: string; + senderEmail?: string; + replyTo?: string; + host?: string; + port?: number; + username?: string; + password?: string; + secure?: SMTPSecure; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const projectsUpdateSMTP = async ({projectId,enabled,senderName,senderEmail,replyTo,host,port,username,password,secure,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsUpdateSMTPRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/smtp'.replace('{projectId}', projectId); @@ -1543,27 +1395,23 @@ const projectsUpdateSMTP = async ({projectId,enabled,senderName,senderEmail,repl return response; } -/** - * @typedef {Object} ProjectsCreateSMTPTestRequestParams - * @property {string} projectId Project unique ID. - * @property {string[]} emails Array of emails to send test email to. Maximum of 10 emails are allowed. - * @property {string} senderName Name of the email sender - * @property {string} senderEmail Email of the sender - * @property {string} host SMTP server host name - * @property {string} replyTo Reply to email - * @property {number} port SMTP server port - * @property {string} username SMTP server username - * @property {string} password SMTP server password - * @property {SMTPSecure} secure Does SMTP server use secure connection - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProjectsCreateSMTPTestRequestParams} params - */ -const projectsCreateSMTPTest = async ({projectId,emails,senderName,senderEmail,host,replyTo,port,username,password,secure,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProjectsCreateSMTPTestRequestParams { + projectId: string; + emails: string[]; + senderName: string; + senderEmail: string; + host: string; + replyTo?: string; + port?: number; + username?: string; + password?: string; + secure?: SMTPSecure; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const projectsCreateSMTPTest = async ({projectId,emails,senderName,senderEmail,host,replyTo,port,username,password,secure,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsCreateSMTPTestRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/smtp/tests'.replace('{projectId}', projectId); @@ -1610,19 +1458,15 @@ const projectsCreateSMTPTest = async ({projectId,emails,senderName,senderEmail,h return response; } -/** - * @typedef {Object} ProjectsUpdateTeamRequestParams - * @property {string} projectId Project unique ID. - * @property {string} teamId Team ID of the team to transfer project to. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface ProjectsUpdateTeamRequestParams { + projectId: string; + teamId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {ProjectsUpdateTeamRequestParams} params - */ -const projectsUpdateTeam = async ({projectId,teamId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const projectsUpdateTeam = async ({projectId,teamId,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsUpdateTeamRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/team'.replace('{projectId}', projectId); @@ -1644,20 +1488,16 @@ const projectsUpdateTeam = async ({projectId,teamId,parseOutput = true, override return response; } -/** - * @typedef {Object} ProjectsGetEmailTemplateRequestParams - * @property {string} projectId Project unique ID. - * @property {EmailTemplateType} type Template type - * @property {EmailTemplateLocale} locale Template locale - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProjectsGetEmailTemplateRequestParams} params - */ -const projectsGetEmailTemplate = async ({projectId,type,locale,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProjectsGetEmailTemplateRequestParams { + projectId: string; + type: EmailTemplateType; + locale: EmailTemplateLocale; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const projectsGetEmailTemplate = async ({projectId,type,locale,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsGetEmailTemplateRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/templates/email/{type}/{locale}'.replace('{projectId}', projectId).replace('{type}', type).replace('{locale}', locale); @@ -1675,25 +1515,21 @@ const projectsGetEmailTemplate = async ({projectId,type,locale,parseOutput = tru return response; } -/** - * @typedef {Object} ProjectsUpdateEmailTemplateRequestParams - * @property {string} projectId Project unique ID. - * @property {EmailTemplateType} type Template type - * @property {EmailTemplateLocale} locale Template locale - * @property {string} subject Email Subject - * @property {string} message Template message - * @property {string} senderName Name of the email sender - * @property {string} senderEmail Email of the sender - * @property {string} replyTo Reply to email - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProjectsUpdateEmailTemplateRequestParams} params - */ -const projectsUpdateEmailTemplate = async ({projectId,type,locale,subject,message,senderName,senderEmail,replyTo,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProjectsUpdateEmailTemplateRequestParams { + projectId: string; + type: EmailTemplateType; + locale: EmailTemplateLocale; + subject: string; + message: string; + senderName?: string; + senderEmail?: string; + replyTo?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const projectsUpdateEmailTemplate = async ({projectId,type,locale,subject,message,senderName,senderEmail,replyTo,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsUpdateEmailTemplateRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/templates/email/{type}/{locale}'.replace('{projectId}', projectId).replace('{type}', type).replace('{locale}', locale); @@ -1727,20 +1563,16 @@ const projectsUpdateEmailTemplate = async ({projectId,type,locale,subject,messag return response; } -/** - * @typedef {Object} ProjectsDeleteEmailTemplateRequestParams - * @property {string} projectId Project unique ID. - * @property {EmailTemplateType} type Template type - * @property {EmailTemplateLocale} locale Template locale - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProjectsDeleteEmailTemplateRequestParams} params - */ -const projectsDeleteEmailTemplate = async ({projectId,type,locale,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProjectsDeleteEmailTemplateRequestParams { + projectId: string; + type: EmailTemplateType; + locale: EmailTemplateLocale; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const projectsDeleteEmailTemplate = async ({projectId,type,locale,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsDeleteEmailTemplateRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/templates/email/{type}/{locale}'.replace('{projectId}', projectId).replace('{type}', type).replace('{locale}', locale); @@ -1759,20 +1591,16 @@ const projectsDeleteEmailTemplate = async ({projectId,type,locale,parseOutput = return response; } -/** - * @typedef {Object} ProjectsGetSMSTemplateRequestParams - * @property {string} projectId Project unique ID. - * @property {SmsTemplateType} type Template type - * @property {SmsTemplateLocale} locale Template locale - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProjectsGetSMSTemplateRequestParams} params - */ -const projectsGetSMSTemplate = async ({projectId,type,locale,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProjectsGetSMSTemplateRequestParams { + projectId: string; + type: SmsTemplateType; + locale: SmsTemplateLocale; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const projectsGetSMSTemplate = async ({projectId,type,locale,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsGetSMSTemplateRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/templates/sms/{type}/{locale}'.replace('{projectId}', projectId).replace('{type}', type).replace('{locale}', locale); @@ -1790,21 +1618,17 @@ const projectsGetSMSTemplate = async ({projectId,type,locale,parseOutput = true, return response; } -/** - * @typedef {Object} ProjectsUpdateSMSTemplateRequestParams - * @property {string} projectId Project unique ID. - * @property {SmsTemplateType} type Template type - * @property {SmsTemplateLocale} locale Template locale - * @property {string} message Template message - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProjectsUpdateSMSTemplateRequestParams} params - */ -const projectsUpdateSMSTemplate = async ({projectId,type,locale,message,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProjectsUpdateSMSTemplateRequestParams { + projectId: string; + type: SmsTemplateType; + locale: SmsTemplateLocale; + message: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const projectsUpdateSMSTemplate = async ({projectId,type,locale,message,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsUpdateSMSTemplateRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/templates/sms/{type}/{locale}'.replace('{projectId}', projectId).replace('{type}', type).replace('{locale}', locale); @@ -1826,20 +1650,16 @@ const projectsUpdateSMSTemplate = async ({projectId,type,locale,message,parseOut return response; } -/** - * @typedef {Object} ProjectsDeleteSMSTemplateRequestParams - * @property {string} projectId Project unique ID. - * @property {SmsTemplateType} type Template type - * @property {SmsTemplateLocale} locale Template locale - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProjectsDeleteSMSTemplateRequestParams} params - */ -const projectsDeleteSMSTemplate = async ({projectId,type,locale,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProjectsDeleteSMSTemplateRequestParams { + projectId: string; + type: SmsTemplateType; + locale: SmsTemplateLocale; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const projectsDeleteSMSTemplate = async ({projectId,type,locale,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsDeleteSMSTemplateRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/templates/sms/{type}/{locale}'.replace('{projectId}', projectId).replace('{type}', type).replace('{locale}', locale); @@ -1858,19 +1678,16 @@ const projectsDeleteSMSTemplate = async ({projectId,type,locale,parseOutput = tr return response; } -/** - * @typedef {Object} ProjectsListWebhooksRequestParams - * @property {string} projectId Project unique ID. - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface ProjectsListWebhooksRequestParams { + projectId: string; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {ProjectsListWebhooksRequestParams} params - */ -const projectsListWebhooks = async ({projectId,total,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const projectsListWebhooks = async ({projectId,total,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: ProjectsListWebhooksRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/webhooks'.replace('{projectId}', projectId); @@ -1885,7 +1702,7 @@ const projectsListWebhooks = async ({projectId,total,parseOutput = true, overrid }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('projects', 'listWebhooks', projectId); } else { parse(response) @@ -1895,25 +1712,21 @@ const projectsListWebhooks = async ({projectId,total,parseOutput = true, overrid return response; } -/** - * @typedef {Object} ProjectsCreateWebhookRequestParams - * @property {string} projectId Project unique ID. - * @property {string} name Webhook name. Max length: 128 chars. - * @property {string[]} events Events list. Maximum of 100 events are allowed. - * @property {string} url Webhook URL. - * @property {boolean} security Certificate verification, false for disabled or true for enabled. - * @property {boolean} enabled Enable or disable a webhook. - * @property {string} httpUser Webhook HTTP user. Max length: 256 chars. - * @property {string} httpPass Webhook HTTP password. Max length: 256 chars. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProjectsCreateWebhookRequestParams} params - */ -const projectsCreateWebhook = async ({projectId,name,events,url,security,enabled,httpUser,httpPass,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProjectsCreateWebhookRequestParams { + projectId: string; + name: string; + events: string[]; + url: string; + security: boolean; + enabled?: boolean; + httpUser?: string; + httpPass?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const projectsCreateWebhook = async ({projectId,name,events,url,security,enabled,httpUser,httpPass,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsCreateWebhookRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/webhooks'.replace('{projectId}', projectId); @@ -1954,19 +1767,16 @@ const projectsCreateWebhook = async ({projectId,name,events,url,security,enabled return response; } -/** - * @typedef {Object} ProjectsGetWebhookRequestParams - * @property {string} projectId Project unique ID. - * @property {string} webhookId Webhook unique ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface ProjectsGetWebhookRequestParams { + projectId: string; + webhookId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {ProjectsGetWebhookRequestParams} params - */ -const projectsGetWebhook = async ({projectId,webhookId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const projectsGetWebhook = async ({projectId,webhookId,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: ProjectsGetWebhookRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/webhooks/{webhookId}'.replace('{projectId}', projectId).replace('{webhookId}', webhookId); @@ -1978,7 +1788,7 @@ const projectsGetWebhook = async ({projectId,webhookId,parseOutput = true, overr }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('projects', 'getWebhook', projectId, webhookId); } else { parse(response) @@ -1988,26 +1798,22 @@ const projectsGetWebhook = async ({projectId,webhookId,parseOutput = true, overr return response; } -/** - * @typedef {Object} ProjectsUpdateWebhookRequestParams - * @property {string} projectId Project unique ID. - * @property {string} webhookId Webhook unique ID. - * @property {string} name Webhook name. Max length: 128 chars. - * @property {string[]} events Events list. Maximum of 100 events are allowed. - * @property {string} url Webhook URL. - * @property {boolean} security Certificate verification, false for disabled or true for enabled. - * @property {boolean} enabled Enable or disable a webhook. - * @property {string} httpUser Webhook HTTP user. Max length: 256 chars. - * @property {string} httpPass Webhook HTTP password. Max length: 256 chars. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProjectsUpdateWebhookRequestParams} params - */ -const projectsUpdateWebhook = async ({projectId,webhookId,name,events,url,security,enabled,httpUser,httpPass,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProjectsUpdateWebhookRequestParams { + projectId: string; + webhookId: string; + name: string; + events: string[]; + url: string; + security: boolean; + enabled?: boolean; + httpUser?: string; + httpPass?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const projectsUpdateWebhook = async ({projectId,webhookId,name,events,url,security,enabled,httpUser,httpPass,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsUpdateWebhookRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/webhooks/{webhookId}'.replace('{projectId}', projectId).replace('{webhookId}', webhookId); @@ -2048,19 +1854,15 @@ const projectsUpdateWebhook = async ({projectId,webhookId,name,events,url,securi return response; } -/** - * @typedef {Object} ProjectsDeleteWebhookRequestParams - * @property {string} projectId Project unique ID. - * @property {string} webhookId Webhook unique ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface ProjectsDeleteWebhookRequestParams { + projectId: string; + webhookId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {ProjectsDeleteWebhookRequestParams} params - */ -const projectsDeleteWebhook = async ({projectId,webhookId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const projectsDeleteWebhook = async ({projectId,webhookId,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsDeleteWebhookRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/webhooks/{webhookId}'.replace('{projectId}', projectId).replace('{webhookId}', webhookId); @@ -2079,19 +1881,15 @@ const projectsDeleteWebhook = async ({projectId,webhookId,parseOutput = true, ov return response; } -/** - * @typedef {Object} ProjectsUpdateWebhookSignatureRequestParams - * @property {string} projectId Project unique ID. - * @property {string} webhookId Webhook unique ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface ProjectsUpdateWebhookSignatureRequestParams { + projectId: string; + webhookId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {ProjectsUpdateWebhookSignatureRequestParams} params - */ -const projectsUpdateWebhookSignature = async ({projectId,webhookId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const projectsUpdateWebhookSignature = async ({projectId,webhookId,parseOutput = true, overrideForCli = false, sdk = undefined}: ProjectsUpdateWebhookSignatureRequestParams): Promise => { let client = !sdk ? await sdkForConsole() : sdk; let apiPath = '/projects/{projectId}/webhooks/{webhookId}/signature'.replace('{projectId}', projectId).replace('{webhookId}', webhookId); @@ -2115,7 +1913,7 @@ projects .description(`Get a list of all projects. You can use the query params to filter your results. `) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name, teamId`) .option(`--search `, `Search term to filter your list results. Max length: 256 chars.`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--console`, `Get the resource console url`) .action(actionRunner(projectsList)) @@ -2171,14 +1969,14 @@ projects .description(`Update the status of a specific API type. Use this endpoint to enable or disable API types such as REST, GraphQL and Realtime.`) .requiredOption(`--project-id `, `Project unique ID.`) .requiredOption(`--api `, `API name.`) - .requiredOption(`--status [value]`, `API status.`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--status [value]`, `API status.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(projectsUpdateAPIStatus)) projects .command(`update-api-status-all`) .description(`Update the status of all API types. Use this endpoint to enable or disable API types such as REST, GraphQL and Realtime all at once.`) .requiredOption(`--project-id `, `Project unique ID.`) - .requiredOption(`--status [value]`, `API status.`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--status [value]`, `API status.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(projectsUpdateAPIStatusAll)) projects @@ -2206,9 +2004,9 @@ projects .command(`update-memberships-privacy`) .description(`Update project membership privacy settings. Use this endpoint to control what user information is visible to other team members, such as user name, email, and MFA status. `) .requiredOption(`--project-id `, `Project unique ID.`) - .requiredOption(`--user-name [value]`, `Set to true to show userName to members of a team.`, (value) => value === undefined ? true : parseBool(value)) - .requiredOption(`--user-email [value]`, `Set to true to show email to members of a team.`, (value) => value === undefined ? true : parseBool(value)) - .requiredOption(`--mfa [value]`, `Set to true to show mfa to members of a team.`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--user-name [value]`, `Set to true to show userName to members of a team.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .requiredOption(`--user-email [value]`, `Set to true to show email to members of a team.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .requiredOption(`--mfa [value]`, `Set to true to show mfa to members of a team.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(projectsUpdateMembershipsPrivacy)) projects @@ -2222,7 +2020,7 @@ projects .command(`update-auth-password-dictionary`) .description(`Enable or disable checking user passwords against common passwords dictionary. This helps ensure users don't use common and insecure passwords. `) .requiredOption(`--project-id `, `Project unique ID.`) - .requiredOption(`--enabled [value]`, `Set whether or not to enable checking user's password against most commonly used passwords. Default is false.`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--enabled [value]`, `Set whether or not to enable checking user's password against most commonly used passwords. Default is false.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(projectsUpdateAuthPasswordDictionary)) projects @@ -2236,21 +2034,21 @@ projects .command(`update-personal-data-check`) .description(`Enable or disable checking user passwords against their personal data. This helps prevent users from using personal information in their passwords. `) .requiredOption(`--project-id `, `Project unique ID.`) - .requiredOption(`--enabled [value]`, `Set whether or not to check a password for similarity with personal data. Default is false.`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--enabled [value]`, `Set whether or not to check a password for similarity with personal data. Default is false.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(projectsUpdatePersonalDataCheck)) projects .command(`update-session-alerts`) .description(`Enable or disable session email alerts. When enabled, users will receive email notifications when new sessions are created.`) .requiredOption(`--project-id `, `Project unique ID.`) - .requiredOption(`--alerts [value]`, `Set to true to enable session emails.`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--alerts [value]`, `Set to true to enable session emails.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(projectsUpdateSessionAlerts)) projects .command(`update-session-invalidation`) .description(`Invalidate all existing sessions. An optional auth security setting for projects, and enabled by default for console project.`) .requiredOption(`--project-id `, `Project unique ID.`) - .requiredOption(`--enabled [value]`, `Update authentication session invalidation status. Use this endpoint to enable or disable session invalidation on password change`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--enabled [value]`, `Update authentication session invalidation status. Use this endpoint to enable or disable session invalidation on password change`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(projectsUpdateSessionInvalidation)) projects @@ -2258,7 +2056,7 @@ projects .description(`Update the status of a specific authentication method. Use this endpoint to enable or disable different authentication methods such as email, magic urls or sms in your project. `) .requiredOption(`--project-id `, `Project unique ID.`) .requiredOption(`--method `, `Auth Method. Possible values: email-password,magic-url,email-otp,anonymous,invites,jwt,phone`) - .requiredOption(`--status [value]`, `Set the status of this auth method.`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--status [value]`, `Set the status of this auth method.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(projectsUpdateAuthStatus)) projects @@ -2313,7 +2111,7 @@ projects .command(`list-keys`) .description(`Get a list of all API keys from the current project. `) .requiredOption(`--project-id `, `Project unique ID.`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--console`, `Get the resource console url`) .action(actionRunner(projectsListKeys)) @@ -2358,14 +2156,14 @@ projects .requiredOption(`--provider `, `Provider Name`) .option(`--app-id `, `Provider app ID. Max length: 256 chars.`) .option(`--secret `, `Provider secret key. Max length: 512 chars.`) - .option(`--enabled [value]`, `Provider status. Set to 'false' to disable new session creation.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Provider status. Set to 'false' to disable new session creation.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(projectsUpdateOAuth2)) projects .command(`list-platforms`) .description(`Get a list of all platforms in the project. This endpoint returns an array of all platforms and their configurations. `) .requiredOption(`--project-id `, `Project unique ID.`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--console`, `Get the resource console url`) .action(actionRunner(projectsListPlatforms)) @@ -2411,21 +2209,21 @@ projects .description(`Update the status of a specific service. Use this endpoint to enable or disable a service in your project. `) .requiredOption(`--project-id `, `Project unique ID.`) .requiredOption(`--service `, `Service name.`) - .requiredOption(`--status [value]`, `Service status.`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--status [value]`, `Service status.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(projectsUpdateServiceStatus)) projects .command(`update-service-status-all`) .description(`Update the status of all services. Use this endpoint to enable or disable all optional services at once. `) .requiredOption(`--project-id `, `Project unique ID.`) - .requiredOption(`--status [value]`, `Service status.`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--status [value]`, `Service status.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(projectsUpdateServiceStatusAll)) projects .command(`update-smtp`) .description(`Update the SMTP configuration for your project. Use this endpoint to configure your project's SMTP provider with your custom settings for sending transactional emails. `) .requiredOption(`--project-id `, `Project unique ID.`) - .requiredOption(`--enabled [value]`, `Enable custom SMTP service`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--enabled [value]`, `Enable custom SMTP service`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--sender-name `, `Name of the email sender`) .option(`--sender-email `, `Email of the sender`) .option(`--reply-to `, `Reply to email`) @@ -2516,7 +2314,7 @@ projects .command(`list-webhooks`) .description(`Get a list of all webhooks belonging to the project. You can use the query params to filter your results. `) .requiredOption(`--project-id `, `Project unique ID.`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--console`, `Get the resource console url`) .action(actionRunner(projectsListWebhooks)) @@ -2527,8 +2325,8 @@ projects .requiredOption(`--name `, `Webhook name. Max length: 128 chars.`) .requiredOption(`--events [events...]`, `Events list. Maximum of 100 events are allowed.`) .requiredOption(`--url `, `Webhook URL.`) - .requiredOption(`--security [value]`, `Certificate verification, false for disabled or true for enabled.`, (value) => value === undefined ? true : parseBool(value)) - .option(`--enabled [value]`, `Enable or disable a webhook.`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--security [value]`, `Certificate verification, false for disabled or true for enabled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Enable or disable a webhook.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--http-user `, `Webhook HTTP user. Max length: 256 chars.`) .option(`--http-pass `, `Webhook HTTP password. Max length: 256 chars.`) .action(actionRunner(projectsCreateWebhook)) @@ -2549,8 +2347,8 @@ projects .requiredOption(`--name `, `Webhook name. Max length: 128 chars.`) .requiredOption(`--events [events...]`, `Events list. Maximum of 100 events are allowed.`) .requiredOption(`--url `, `Webhook URL.`) - .requiredOption(`--security [value]`, `Certificate verification, false for disabled or true for enabled.`, (value) => value === undefined ? true : parseBool(value)) - .option(`--enabled [value]`, `Enable or disable a webhook.`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--security [value]`, `Certificate verification, false for disabled or true for enabled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Enable or disable a webhook.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--http-user `, `Webhook HTTP user. Max length: 256 chars.`) .option(`--http-pass `, `Webhook HTTP password. Max length: 256 chars.`) .action(actionRunner(projectsUpdateWebhook)) @@ -2569,58 +2367,4 @@ projects .requiredOption(`--webhook-id `, `Webhook unique ID.`) .action(actionRunner(projectsUpdateWebhookSignature)) -module.exports = { - projects, - projectsList, - projectsCreate, - projectsGet, - projectsUpdate, - projectsDelete, - projectsUpdateAPIStatus, - projectsUpdateAPIStatusAll, - projectsUpdateAuthDuration, - projectsUpdateAuthLimit, - projectsUpdateAuthSessionsLimit, - projectsUpdateMembershipsPrivacy, - projectsUpdateMockNumbers, - projectsUpdateAuthPasswordDictionary, - projectsUpdateAuthPasswordHistory, - projectsUpdatePersonalDataCheck, - projectsUpdateSessionAlerts, - projectsUpdateSessionInvalidation, - projectsUpdateAuthStatus, - projectsListDevKeys, - projectsCreateDevKey, - projectsGetDevKey, - projectsUpdateDevKey, - projectsDeleteDevKey, - projectsCreateJWT, - projectsListKeys, - projectsCreateKey, - projectsGetKey, - projectsUpdateKey, - projectsDeleteKey, - projectsUpdateOAuth2, - projectsListPlatforms, - projectsCreatePlatform, - projectsGetPlatform, - projectsUpdatePlatform, - projectsDeletePlatform, - projectsUpdateServiceStatus, - projectsUpdateServiceStatusAll, - projectsUpdateSMTP, - projectsCreateSMTPTest, - projectsUpdateTeam, - projectsGetEmailTemplate, - projectsUpdateEmailTemplate, - projectsDeleteEmailTemplate, - projectsGetSMSTemplate, - projectsUpdateSMSTemplate, - projectsDeleteSMSTemplate, - projectsListWebhooks, - projectsCreateWebhook, - projectsGetWebhook, - projectsUpdateWebhook, - projectsDeleteWebhook, - projectsUpdateWebhookSignature -}; + diff --git a/lib/commands/proxy.js b/lib/commands/proxy.ts similarity index 57% rename from lib/commands/proxy.js rename to lib/commands/proxy.ts index dd864ffc..fb48eaf0 100644 --- a/lib/commands/proxy.js +++ b/lib/commands/proxy.ts @@ -1,31 +1,27 @@ -const fs = require('fs'); -const pathLib = require('path'); -const tar = require("tar"); -const ignore = require("ignore"); -const { promisify } = require('util'); -const libClient = require('../client.js'); -const { getAllFiles, showConsoleLink } = require('../utils.js'); -const { Command } = require('commander'); -const { sdkForProject, sdkForConsole } = require('../sdks') -const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } = require('../parser') -const { localConfig, globalConfig } = require("../config"); -const { File } = require('undici'); -const { ReadableStream } = require('stream/web'); - -/** - * @param {fs.ReadStream} readStream - * @returns {ReadableStream} - */ -function convertReadStreamToReadableStream(readStream) { +import fs = require('fs'); +import pathLib = require('path'); +import tar = require('tar'); +import ignore = require('ignore'); +import { promisify } from 'util'; +import Client from '../client'; +import { getAllFiles, showConsoleLink } from '../utils'; +import { Command } from 'commander'; +import { sdkForProject, sdkForConsole } from '../sdks'; +import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } from '../parser'; +import { localConfig, globalConfig } from '../config'; +import { File } from 'undici'; +import { ReadableStream } from 'stream/web'; + +function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ start(controller) { - readStream.on("data", (chunk) => { + readStream.on("data", (chunk: Buffer) => { controller.enqueue(chunk); }); readStream.on("end", () => { controller.close(); }); - readStream.on("error", (err) => { + readStream.on("error", (err: Error) => { controller.error(err); }); }, @@ -35,24 +31,20 @@ function convertReadStreamToReadableStream(readStream) { }); } -const proxy = new Command("proxy").description(commandDescriptions['proxy'] ?? '').configureHelp({ +export const proxy = new Command("proxy").description(commandDescriptions['proxy'] ?? '').configureHelp({ helpWidth: process.stdout.columns || 80 }) -/** - * @typedef {Object} ProxyListRulesRequestParams - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/databases#querying-documents). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: domain, type, trigger, deploymentResourceType, deploymentResourceId, deploymentId, deploymentVcsProviderBranch - * @property {string} search Search term to filter your list results. Max length: 256 chars. - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProxyListRulesRequestParams} params - */ -const proxyListRules = async ({queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProxyListRulesRequestParams { + queries?: string[]; + search?: string; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const proxyListRules = async ({queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined}: ProxyListRulesRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/proxy/rules'; @@ -79,18 +71,14 @@ const proxyListRules = async ({queries,search,total,parseOutput = true, override return response; } -/** - * @typedef {Object} ProxyCreateAPIRuleRequestParams - * @property {string} domain Domain name. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProxyCreateAPIRuleRequestParams} params - */ -const proxyCreateAPIRule = async ({domain,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProxyCreateAPIRuleRequestParams { + domain: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const proxyCreateAPIRule = async ({domain,parseOutput = true, overrideForCli = false, sdk = undefined}: ProxyCreateAPIRuleRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/proxy/rules/api'; @@ -112,20 +100,16 @@ const proxyCreateAPIRule = async ({domain,parseOutput = true, overrideForCli = f return response; } -/** - * @typedef {Object} ProxyCreateFunctionRuleRequestParams - * @property {string} domain Domain name. - * @property {string} functionId ID of function to be executed. - * @property {string} branch Name of VCS branch to deploy changes automatically - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProxyCreateFunctionRuleRequestParams} params - */ -const proxyCreateFunctionRule = async ({domain,functionId,branch,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProxyCreateFunctionRuleRequestParams { + domain: string; + functionId: string; + branch?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const proxyCreateFunctionRule = async ({domain,functionId,branch,parseOutput = true, overrideForCli = false, sdk = undefined}: ProxyCreateFunctionRuleRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/proxy/rules/function'; @@ -153,22 +137,18 @@ const proxyCreateFunctionRule = async ({domain,functionId,branch,parseOutput = t return response; } -/** - * @typedef {Object} ProxyCreateRedirectRuleRequestParams - * @property {string} domain Domain name. - * @property {string} url Target URL of redirection - * @property {StatusCode} statusCode Status code of redirection - * @property {string} resourceId ID of parent resource. - * @property {ProxyResourceType} resourceType Type of parent resource. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProxyCreateRedirectRuleRequestParams} params - */ -const proxyCreateRedirectRule = async ({domain,url,statusCode,resourceId,resourceType,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProxyCreateRedirectRuleRequestParams { + domain: string; + url: string; + statusCode: StatusCode; + resourceId: string; + resourceType: ProxyResourceType; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const proxyCreateRedirectRule = async ({domain,url,statusCode,resourceId,resourceType,parseOutput = true, overrideForCli = false, sdk = undefined}: ProxyCreateRedirectRuleRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/proxy/rules/redirect'; @@ -202,20 +182,16 @@ const proxyCreateRedirectRule = async ({domain,url,statusCode,resourceId,resourc return response; } -/** - * @typedef {Object} ProxyCreateSiteRuleRequestParams - * @property {string} domain Domain name. - * @property {string} siteId ID of site to be executed. - * @property {string} branch Name of VCS branch to deploy changes automatically - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProxyCreateSiteRuleRequestParams} params - */ -const proxyCreateSiteRule = async ({domain,siteId,branch,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProxyCreateSiteRuleRequestParams { + domain: string; + siteId: string; + branch?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const proxyCreateSiteRule = async ({domain,siteId,branch,parseOutput = true, overrideForCli = false, sdk = undefined}: ProxyCreateSiteRuleRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/proxy/rules/site'; @@ -243,18 +219,14 @@ const proxyCreateSiteRule = async ({domain,siteId,branch,parseOutput = true, ove return response; } -/** - * @typedef {Object} ProxyGetRuleRequestParams - * @property {string} ruleId Rule ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProxyGetRuleRequestParams} params - */ -const proxyGetRule = async ({ruleId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProxyGetRuleRequestParams { + ruleId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const proxyGetRule = async ({ruleId,parseOutput = true, overrideForCli = false, sdk = undefined}: ProxyGetRuleRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/proxy/rules/{ruleId}'.replace('{ruleId}', ruleId); @@ -272,18 +244,14 @@ const proxyGetRule = async ({ruleId,parseOutput = true, overrideForCli = false, return response; } -/** - * @typedef {Object} ProxyDeleteRuleRequestParams - * @property {string} ruleId Rule ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProxyDeleteRuleRequestParams} params - */ -const proxyDeleteRule = async ({ruleId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProxyDeleteRuleRequestParams { + ruleId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const proxyDeleteRule = async ({ruleId,parseOutput = true, overrideForCli = false, sdk = undefined}: ProxyDeleteRuleRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/proxy/rules/{ruleId}'.replace('{ruleId}', ruleId); @@ -302,18 +270,14 @@ const proxyDeleteRule = async ({ruleId,parseOutput = true, overrideForCli = fals return response; } -/** - * @typedef {Object} ProxyUpdateRuleVerificationRequestParams - * @property {string} ruleId Rule ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {ProxyUpdateRuleVerificationRequestParams} params - */ -const proxyUpdateRuleVerification = async ({ruleId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface ProxyUpdateRuleVerificationRequestParams { + ruleId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const proxyUpdateRuleVerification = async ({ruleId,parseOutput = true, overrideForCli = false, sdk = undefined}: ProxyUpdateRuleVerificationRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/proxy/rules/{ruleId}/verification'.replace('{ruleId}', ruleId); @@ -337,7 +301,7 @@ proxy .description(`Get a list of all the proxy rules. You can use the query params to filter your results.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/databases#querying-documents). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: domain, type, trigger, deploymentResourceType, deploymentResourceId, deploymentId, deploymentVcsProviderBranch`) .option(`--search `, `Search term to filter your list results. Max length: 256 chars.`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(proxyListRules)) proxy @@ -390,14 +354,4 @@ proxy .requiredOption(`--rule-id `, `Rule ID.`) .action(actionRunner(proxyUpdateRuleVerification)) -module.exports = { - proxy, - proxyListRules, - proxyCreateAPIRule, - proxyCreateFunctionRule, - proxyCreateRedirectRule, - proxyCreateSiteRule, - proxyGetRule, - proxyDeleteRule, - proxyUpdateRuleVerification -}; + diff --git a/lib/commands/pull.js b/lib/commands/pull.ts similarity index 84% rename from lib/commands/pull.js rename to lib/commands/pull.ts index 8e43f135..3c306cc5 100644 --- a/lib/commands/pull.js +++ b/lib/commands/pull.ts @@ -1,25 +1,39 @@ -const fs = require("fs"); -const chalk = require('chalk'); -const tar = require("tar"); -const { Command } = require("commander"); -const inquirer = require("inquirer"); -const { messagingListTopics } = require("./messaging"); -const { teamsList } = require("./teams"); -const { projectsGet } = require("./projects"); -const { functionsList, functionsGetDeploymentDownload, functionsListDeployments } = require("./functions"); -const { sitesList, sitesGetDeploymentDownload, sitesListDeployments } = require("./sites"); -const { databasesGet, databasesListCollections, databasesList } = require("./databases"); -const { tablesDBList, tablesDBGet, tablesDBListTables } = require("./tables-db"); -const { storageListBuckets } = require("./storage"); -const { localConfig } = require("../config"); -const { paginate } = require("../paginate"); -const { questionsPullCollection, questionsPullFunctions, questionsPullFunctionsCode, questionsPullSites, questionsPullSitesCode, questionsPullResources } = require("../questions"); -const { cliConfig, success, log, warn, actionRunner, commandDescriptions } = require("../parser"); - -const pullResources = async ({ +import fs = require('fs'); +import chalk from 'chalk'; +import tar = require('tar'); +import { Command } from 'commander'; +import inquirer from 'inquirer'; +import { messagingListTopics } from './messaging'; +import { teamsList } from './teams'; +import { projectsGet } from './projects'; +import { functionsList, functionsGetDeploymentDownload, functionsListDeployments } from './functions'; +import { sitesList, sitesGetDeploymentDownload, sitesListDeployments } from './sites'; +import { databasesGet, databasesListCollections, databasesList } from './databases'; +import { tablesDBList, tablesDBGet, tablesDBListTables } from './tables-db'; +import { storageListBuckets } from './storage'; +import { localConfig } from '../config'; +import { paginate } from '../paginate'; +import { questionsPullCollection, questionsPullFunctions, questionsPullFunctionsCode, questionsPullSites, questionsPullSitesCode, questionsPullResources } from '../questions'; +import { cliConfig, success, log, warn, actionRunner, commandDescriptions } from '../parser'; + +interface PullResourcesOptions { + skipDeprecated?: boolean; +} + +interface PullFunctionsOptions { + code?: boolean; + withVariables?: boolean; +} + +interface PullSitesOptions { + code?: boolean; + withVariables?: boolean; +} + +export const pullResources = async ({ skipDeprecated = false -} = {}) => { - const actions = { +}: PullResourcesOptions = {}): Promise => { + const actions: Record Promise> = { settings: pullSettings, functions: pullFunctions, sites: pullSites, @@ -49,7 +63,7 @@ const pullResources = async ({ } }; -const pullSettings = async () => { +const pullSettings = async (): Promise => { log("Pulling project settings ..."); try { @@ -66,7 +80,7 @@ const pullSettings = async () => { } } -const pullFunctions = async ({ code, withVariables }) => { +const pullFunctions = async ({ code, withVariables }: PullFunctionsOptions = {}): Promise => { process.chdir(localConfig.configDirectoryPath) log("Fetching functions ..."); @@ -86,7 +100,7 @@ const pullFunctions = async ({ code, withVariables }) => { ? (await paginate(functionsList, { parseOutput: false }, 100, 'functions')).functions : (await inquirer.prompt(questionsPullFunctions)).functions; - let allowCodePull = cliConfig.force === true ? true : null; + let allowCodePull: boolean | null = cliConfig.force === true ? true : null; for (let func of functions) { total++; @@ -121,7 +135,7 @@ const pullFunctions = async ({ code, withVariables }) => { continue; } - let deploymentId = null; + let deploymentId: string | null = null; try { const fetchResponse = await functionsListDeployments({ @@ -172,14 +186,14 @@ const pullFunctions = async ({ code, withVariables }) => { } catch { } - fs.writeFileSync(envFileLocation, holdingVars.map(r => `${r.key}=${r.value}\n`).join('')) + fs.writeFileSync(envFileLocation, holdingVars.map((r: any) => `${r.key}=${r.value}\n`).join('')) } } success(`Successfully pulled ${chalk.bold(total)} functions.`); } -const pullSites = async ({ code, withVariables }) => { +const pullSites = async ({ code, withVariables }: PullSitesOptions = {}): Promise => { process.chdir(localConfig.configDirectoryPath) log("Fetching sites ..."); @@ -199,7 +213,7 @@ const pullSites = async ({ code, withVariables }) => { ? (await paginate(sitesList, { parseOutput: false }, 100, 'sites')).sites : (await inquirer.prompt(questionsPullSites)).sites; - let allowCodePull = cliConfig.force === true ? true : null; + let allowCodePull: boolean | null = cliConfig.force === true ? true : null; for (let site of sites) { total++; @@ -234,7 +248,7 @@ const pullSites = async ({ code, withVariables }) => { continue; } - let deploymentId = null; + let deploymentId: string | null = null; try { const fetchResponse = await sitesListDeployments({ @@ -285,14 +299,14 @@ const pullSites = async ({ code, withVariables }) => { } catch { } - fs.writeFileSync(envFileLocation, holdingVars.map(r => `${r.key}=${r.value}\n`).join('')) + fs.writeFileSync(envFileLocation, holdingVars.map((r: any) => `${r.key}=${r.value}\n`).join('')) } } success(`Successfully pulled ${chalk.bold(total)} sites.`); } -const pullCollection = async () => { +const pullCollection = async (): Promise => { warn("appwrite pull collection has been deprecated. Please consider using 'appwrite pull tables' instead"); log("Fetching collections ..."); let totalDatabases = 0; @@ -308,11 +322,11 @@ const pullCollection = async () => { return; } - let databases = cliConfig.ids; + let databases: string[] = cliConfig.ids; if (databases.length === 0) { if (cliConfig.all) { - databases = (await paginate(databasesList, { parseOutput: false }, 100, 'databases')).databases.map(database => database.$id); + databases = (await paginate(databasesList, { parseOutput: false }, 100, 'databases')).databases.map((database: any) => database.$id); } else { databases = (await inquirer.prompt(questionsPullCollection)).databases; } @@ -347,7 +361,7 @@ const pullCollection = async () => { success(`Successfully pulled ${chalk.bold(totalCollections)} collections from ${chalk.bold(totalDatabases)} databases.`); } -const pullTable = async () => { +const pullTable = async (): Promise => { log("Fetching tables ..."); let totalTablesDBs = 0; let totalTables = 0; @@ -362,11 +376,11 @@ const pullTable = async () => { return; } - let databases = cliConfig.ids; + let databases: string[] = cliConfig.ids; if (databases.length === 0) { if (cliConfig.all) { - databases = (await paginate(tablesDBList, { parseOutput: false }, 100, 'databases')).databases.map(database => database.$id); + databases = (await paginate(tablesDBList, { parseOutput: false }, 100, 'databases')).databases.map((database: any) => database.$id); } else { databases = (await inquirer.prompt(questionsPullCollection)).databases; } @@ -401,7 +415,7 @@ const pullTable = async () => { success(`Successfully pulled ${chalk.bold(totalTables)} tables from ${chalk.bold(totalTablesDBs)} tableDBs.`); } -const pullBucket = async () => { +const pullBucket = async (): Promise => { log("Fetching buckets ..."); let total = 0; @@ -426,7 +440,7 @@ const pullBucket = async () => { success(`Successfully pulled ${chalk.bold(total)} buckets.`); } -const pullTeam = async () => { +const pullTeam = async (): Promise => { log("Fetching teams ..."); let total = 0; @@ -451,7 +465,7 @@ const pullTeam = async () => { success(`Successfully pulled ${chalk.bold(total)} teams.`); } -const pullMessagingTopic = async () => { +const pullMessagingTopic = async (): Promise => { log("Fetching topics ..."); let total = 0; @@ -476,7 +490,7 @@ const pullMessagingTopic = async () => { success(`Successfully pulled ${chalk.bold(total)} topics.`); } -const pull = new Command("pull") +export const pull = new Command("pull") .description(commandDescriptions['pull']) .action(actionRunner(() => pullResources({ skipDeprecated: true }))); @@ -541,7 +555,3 @@ pull .description("Pull your Appwrite messaging topics") .action(actionRunner(pullMessagingTopic)) -module.exports = { - pull, - pullResources -}; diff --git a/lib/commands/push.js b/lib/commands/push.ts similarity index 86% rename from lib/commands/push.js rename to lib/commands/push.ts index 162d4be5..d59f88f4 100644 --- a/lib/commands/push.js +++ b/lib/commands/push.ts @@ -1,22 +1,22 @@ -const fs = require('fs'); -const path = require('path'); -const { parse: parseDotenv } = require('dotenv'); -const chalk = require('chalk'); -const inquirer = require("inquirer"); -const JSONbig = require("json-bigint")({ storeAsString: false }); -const { Command } = require("commander"); -const ID = require("../id"); -const { localConfig, globalConfig, KeysAttributes, KeysFunction, KeysSite, whitelistKeys, KeysTopics, KeysStorage, KeysTeams, KeysCollection, KeysTable } = require("../config"); -const { Spinner, SPINNER_ARC, SPINNER_DOTS } = require('../spinner'); -const { paginate } = require('../paginate'); -const { questionsPushBuckets, questionsPushTeams, questionsPushFunctions, questionsPushSites, questionsGetEntrypoint, questionsPushCollections, questionsPushTables, questionPushChanges, questionPushChangesConfirmation, questionsPushMessagingTopics, questionsPushResources } = require("../questions"); -const { cliConfig, actionRunner, success, warn, log, hint, error, commandDescriptions, drawTable } = require("../parser"); -const { proxyCreateFunctionRule, proxyCreateSiteRule, proxyListRules } = require('./proxy'); -const { consoleVariables } = require('./console'); -const { sdkForConsole } = require('../sdks') -const { functionsGet, functionsCreate, functionsUpdate, functionsCreateDeployment, functionsGetDeployment, functionsListVariables, functionsDeleteVariable, functionsCreateVariable } = require('./functions'); -const { sitesGet, sitesCreate, sitesUpdate, sitesCreateDeployment, sitesGetDeployment, sitesCreateVariable, sitesListVariables, sitesDeleteVariable } = require('./sites'); -const { +import fs = require('fs'); +import path = require('path'); +import { parse as parseDotenv } from 'dotenv'; +import chalk from 'chalk'; +import inquirer from "inquirer"; +import JSONbig from "json-bigint"; +import { Command } from "commander"; +import ID from "../id"; +import { localConfig, globalConfig, KeysAttributes, KeysFunction, KeysSite, whitelistKeys, KeysTopics, KeysStorage, KeysTeams, KeysCollection, KeysTable } from "../config"; +import { Spinner, SPINNER_ARC, SPINNER_DOTS } from '../spinner'; +import { paginate } from '../paginate'; +import { questionsPushBuckets, questionsPushTeams, questionsPushFunctions, questionsPushSites, questionsGetEntrypoint, questionsPushCollections, questionsPushTables, questionPushChanges, questionPushChangesConfirmation, questionsPushMessagingTopics, questionsPushResources } from "../questions"; +import { cliConfig, actionRunner, success, warn, log, hint, error, commandDescriptions, drawTable } from "../parser"; +import { proxyCreateFunctionRule, proxyCreateSiteRule, proxyListRules } from './proxy'; +import { consoleVariables } from './console'; +import { sdkForConsole } from '../sdks'; +import { functionsGet, functionsCreate, functionsUpdate, functionsCreateDeployment, functionsGetDeployment, functionsListVariables, functionsDeleteVariable, functionsCreateVariable } from './functions'; +import { sitesGet, sitesCreate, sitesUpdate, sitesCreateDeployment, sitesGetDeployment, sitesCreateVariable, sitesListVariables, sitesDeleteVariable } from './sites'; +import { databasesGet, databasesCreate, databasesUpdate, @@ -54,8 +54,8 @@ const { databasesListAttributes, databasesListIndexes, databasesUpdateCollection -} = require("./databases"); -const { +} from "./databases"; +import { tablesDBCreate, tablesDBGet, tablesDBUpdate, @@ -66,19 +66,19 @@ const { tablesDBDelete, tablesDBListTables, tablesDBDeleteTable -} = require("./tables-db"); -const { +} from "./tables-db"; +import { storageGetBucket, storageUpdateBucket, storageCreateBucket -} = require("./storage"); -const { +} from "./storage"; +import { messagingGetTopic, messagingUpdateTopic, messagingCreateTopic -} = require("./messaging"); -const { +} from "./messaging"; +import { teamsGet, teamsUpdateName, teamsCreate -} = require("./teams"); -const { +} from "./teams"; +import { projectsGet, projectsUpdate, projectsUpdateServiceStatus, @@ -91,8 +91,10 @@ const { projectsUpdatePersonalDataCheck, projectsUpdateSessionAlerts, projectsUpdateMockNumbers, -} = require("./projects"); -const { checkDeployConditions } = require('../utils'); +} from "./projects"; +import { checkDeployConditions } from '../utils'; + +const JSONbigNative = JSONbig({ storeAsString: false }); const STEP_SIZE = 100; // Resources const POLL_DEBOUNCE = 2000; // Milliseconds @@ -103,8 +105,17 @@ let pollMaxDebounces = POLL_DEFAULT_VALUE; const changeableKeys = ['status', 'required', 'xdefault', 'elements', 'min', 'max', 'default', 'error']; -const awaitPools = { - wipeAttributes: async (databaseId, collectionId, iteration = 1) => { +interface AwaitPools { + wipeAttributes: (databaseId: string, collectionId: string, iteration?: number) => Promise; + wipeIndexes: (databaseId: string, collectionId: string, iteration?: number) => Promise; + deleteAttributes: (databaseId: string, collectionId: string, attributeKeys: any[], iteration?: number) => Promise; + expectAttributes: (databaseId: string, collectionId: string, attributeKeys: string[], iteration?: number) => Promise; + deleteIndexes: (databaseId: string, collectionId: string, indexesKeys: any[], iteration?: number) => Promise; + expectIndexes: (databaseId: string, collectionId: string, indexKeys: string[], iteration?: number) => Promise; +} + +const awaitPools: AwaitPools = { + wipeAttributes: async (databaseId: string, collectionId: string, iteration: number = 1): Promise => { if (iteration > pollMaxDebounces) { return false; } @@ -137,7 +148,7 @@ const awaitPools = { iteration + 1 ); }, - wipeIndexes: async (databaseId, collectionId, iteration = 1) => { + wipeIndexes: async (databaseId: string, collectionId: string, iteration: number = 1): Promise => { if (iteration > pollMaxDebounces) { return false; } @@ -170,7 +181,7 @@ const awaitPools = { iteration + 1 ); }, - deleteAttributes: async (databaseId, collectionId, attributeKeys, iteration = 1) => { + deleteAttributes: async (databaseId: string, collectionId: string, attributeKeys: any[], iteration: number = 1): Promise => { if (iteration > pollMaxDebounces) { return false; } @@ -190,7 +201,7 @@ const awaitPools = { parseOutput: false }, 100, 'attributes'); - const ready = attributeKeys.filter(attribute => attributes.includes(attribute.key)); + const ready = attributeKeys.filter((attribute: any) => attributes.includes(attribute.key)); if (ready.length === 0) { return true; @@ -205,7 +216,7 @@ const awaitPools = { iteration + 1 ); }, - expectAttributes: async (databaseId, collectionId, attributeKeys, iteration = 1) => { + expectAttributes: async (databaseId: string, collectionId: string, attributeKeys: string[], iteration: number = 1): Promise => { if (iteration > pollMaxDebounces) { return false; } @@ -226,7 +237,7 @@ const awaitPools = { }, 100, 'attributes'); const ready = attributes - .filter(attribute => { + .filter((attribute: any) => { if (attributeKeys.includes(attribute.key)) { if (['stuck', 'failed'].includes(attribute.status)) { throw new Error(`Attribute '${attribute.key}' failed!`); @@ -237,7 +248,7 @@ const awaitPools = { return false; }) - .map(attribute => attribute.key); + .map((attribute: any) => attribute.key); if (ready.length === attributeKeys.length) { return true; @@ -252,13 +263,13 @@ const awaitPools = { iteration + 1 ); }, - deleteIndexes: async (databaseId, collectionId, indexesKeys, iteration = 1) => { + deleteIndexes: async (databaseId: string, collectionId: string, indexesKeys: any[], iteration: number = 1): Promise => { if (iteration > pollMaxDebounces) { return false; } if (pollMaxDebounces === POLL_DEFAULT_VALUE) { - let steps = Math.max(1, Math.ceil(attributeKeys.length / STEP_SIZE)); + let steps = Math.max(1, Math.ceil(indexesKeys.length / STEP_SIZE)); if (steps > 1 && iteration === 1) { pollMaxDebounces *= steps; @@ -272,7 +283,7 @@ const awaitPools = { parseOutput: false }, 100, 'indexes'); - const ready = indexesKeys.filter(index => indexes.includes(index.key)); + const ready = indexesKeys.filter((index: any) => indexes.includes(index.key)); if (ready.length === 0) { return true; @@ -287,7 +298,7 @@ const awaitPools = { iteration + 1 ); }, - expectIndexes: async (databaseId, collectionId, indexKeys, iteration = 1) => { + expectIndexes: async (databaseId: string, collectionId: string, indexKeys: string[], iteration: number = 1): Promise => { if (iteration > pollMaxDebounces) { return false; } @@ -308,7 +319,7 @@ const awaitPools = { }, 100, 'indexes'); const ready = indexes - .filter((index) => { + .filter((index: any) => { if (indexKeys.includes(index.key)) { if (['stuck', 'failed'].includes(index.status)) { throw new Error(`Index '${index.key}' failed!`); @@ -319,7 +330,7 @@ const awaitPools = { return false; }) - .map(index => index.key); + .map((index: any) => index.key); if (ready.length >= indexKeys.length) { return true; @@ -336,12 +347,12 @@ const awaitPools = { }, } -const getConfirmation = async () => { +const getConfirmation = async (): Promise => { if (cliConfig.force) { return true; } - async function fixConfirmation() { + async function fixConfirmation(): Promise { const answers = await inquirer.prompt(questionPushChangesConfirmation); if (answers.changes !== 'YES' && answers.changes !== 'NO') { return await fixConfirmation(); @@ -364,15 +375,15 @@ const getConfirmation = async () => { return false; }; -const isEmpty = (value) => (value === null || value === undefined || (typeof value === "string" && value.trim().length === 0) || (Array.isArray(value) && value.length === 0)); +const isEmpty = (value: any): boolean => (value === null || value === undefined || (typeof value === "string" && value.trim().length === 0) || (Array.isArray(value) && value.length === 0)); -const approveChanges = async (resource, resourceGetFunction, keys, resourceName, resourcePlural, skipKeys = [], secondId = '', secondResourceName = '') => { +const approveChanges = async (resource: any[], resourceGetFunction: Function, keys: Set, resourceName: string, resourcePlural: string, skipKeys: string[] = [], secondId: string = '', secondResourceName: string = ''): Promise => { log('Checking for changes ...'); - const changes = []; + const changes: any[] = []; await Promise.all(resource.map(async (localResource) => { try { - const options = { + const options: Record = { [resourceName]: localResource['$id'], parseOutput: false, }; @@ -397,7 +408,7 @@ const approveChanges = async (resource, resourceGetFunction, keys, resourceName, changes.push({ id: localResource['$id'], key, - remote: chalk.red(value.join('\n')), + remote: chalk.red((value as string[]).join('\n')), local: chalk.green(localResource[key].join('\n')) }) } @@ -410,7 +421,7 @@ const approveChanges = async (resource, resourceGetFunction, keys, resourceName, }) } } - } catch (e) { + } catch (e: any) { if (Number(e.code) !== 404) { throw e; } @@ -430,8 +441,8 @@ const approveChanges = async (resource, resourceGetFunction, keys, resourceName, return false; } -const getObjectChanges = (remote, local, index, what) => { - const changes = []; +const getObjectChanges = (remote: any, local: any, index: string, what: string): any[] => { + const changes: any[] = []; if (remote[index] && local[index]) { for (let [service, status] of Object.entries(remote[index])) { @@ -453,7 +464,7 @@ const getObjectChanges = (remote, local, index, what) => { return changes; } -const createAttribute = (databaseId, collectionId, attribute) => { +const createAttribute = (databaseId: string, collectionId: string, attribute: any): Promise => { switch (attribute.type) { case 'string': switch (attribute.format) { @@ -600,7 +611,7 @@ const createAttribute = (databaseId, collectionId, attribute) => { } } -const updateAttribute = (databaseId, collectionId, attribute) => { +const updateAttribute = (databaseId: string, collectionId: string, attribute: any): Promise => { switch (attribute.type) { case 'string': switch (attribute.format) { @@ -745,7 +756,7 @@ const updateAttribute = (databaseId, collectionId, attribute) => { throw new Error(`Unsupported attribute type: ${attribute.type}`); } } -const deleteAttribute = async (collection, attribute, isIndex = false) => { +const deleteAttribute = async (collection: any, attribute: any, isIndex: boolean = false): Promise => { log(`Deleting ${isIndex ? 'index' : 'attribute'} ${attribute.key} of ${collection.name} ( ${collection['$id']} )`); if (isIndex) { @@ -766,7 +777,7 @@ const deleteAttribute = async (collection, attribute, isIndex = false) => { }); } -const isEqual = (a, b) => { +const isEqual = (a: any, b: any): boolean => { if (a === b) return true; if (a && b && typeof a === 'object' && typeof b === 'object') { @@ -793,7 +804,7 @@ const isEqual = (a, b) => { return false; }; -const compareAttribute = (remote, local, reason, key) => { +const compareAttribute = (remote: any, local: any, reason: string, key: string): string => { if (isEmpty(remote) && isEmpty(local)) { return reason; } @@ -811,17 +822,18 @@ const compareAttribute = (remote, local, reason, key) => { return reason } +interface AttributeChange { + key: string; + attribute: any; + reason: string; + action: string; +} /** * Check if attribute non-changeable fields has been changed * If so return the differences as an object. - * @param remote - * @param local - * @param collection - * @param recreating when true will check only non-changeable keys - * @returns {undefined|{reason: string, action: *, attribute, key: string}} */ -const checkAttributeChanges = (remote, local, collection, recreating = true) => { +const checkAttributeChanges = (remote: any, local: any, collection: any, recreating: boolean = true): AttributeChange | undefined => { if (local === undefined) { return undefined; } @@ -855,36 +867,32 @@ const checkAttributeChanges = (remote, local, collection, recreating = true) => /** * Check if attributes contain the given attribute - * @param attribute - * @param attributes - * @returns {*} */ -const attributesContains = (attribute, attributes) => attributes.find((attr) => attr.key === attribute.key); -const generateChangesObject = (attribute, collection, isAdding) => { +const attributesContains = (attribute: any, attributes: any[]): any => attributes.find((attr) => attr.key === attribute.key); + +const generateChangesObject = (attribute: any, collection: any, isAdding: boolean): AttributeChange => { return { key: `${chalk.yellow(attribute.key)} in ${collection.name} (${collection['$id']})`, attribute: attribute, reason: isAdding ? 'Field isn\'t present on the remote server' : 'Field isn\'t present on the appwrite.config.json file', action: isAdding ? chalk.green('adding') : chalk.red('deleting') }; - }; /** * Filter deleted and recreated attributes, * return list of attributes to create - * @returns {Promise<*|*[]>} */ -const attributesToCreate = async (remoteAttributes, localAttributes, collection, isIndex = false) => { +const attributesToCreate = async (remoteAttributes: any[], localAttributes: any[], collection: any, isIndex: boolean = false): Promise => { const deleting = remoteAttributes.filter((attribute) => !attributesContains(attribute, localAttributes)).map((attr) => generateChangesObject(attr, collection, false)); const adding = localAttributes.filter((attribute) => !attributesContains(attribute, remoteAttributes)).map((attr) => generateChangesObject(attr, collection, true)); - const conflicts = remoteAttributes.map((attribute) => checkAttributeChanges(attribute, attributesContains(attribute, localAttributes), collection)).filter(attribute => attribute !== undefined); + const conflicts = remoteAttributes.map((attribute) => checkAttributeChanges(attribute, attributesContains(attribute, localAttributes), collection)).filter(attribute => attribute !== undefined) as AttributeChange[]; const changes = remoteAttributes.map((attribute) => checkAttributeChanges(attribute, attributesContains(attribute, localAttributes), collection, false)) .filter(attribute => attribute !== undefined) - .filter(attribute => conflicts.filter(attr => attribute.key === attr.key).length !== 1); + .filter(attribute => conflicts.filter(attr => attribute!.key === attr.key).length !== 1) as AttributeChange[]; - let changedAttributes = []; + let changedAttributes: any[] = []; const changing = [...deleting, ...adding, ...conflicts, ...changes] if (changing.length === 0) { return changedAttributes; @@ -928,7 +936,7 @@ const attributesToCreate = async (remoteAttributes, localAttributes, collection, const deletingAttributes = deleting.map((change) => change.attribute); await Promise.all(deletingAttributes.map((attribute) => deleteAttribute(collection, attribute, isIndex))); - const attributeKeys = [...remoteAttributes.map(attribute => attribute.key), ...deletingAttributes.map(attribute => attribute.key)] + const attributeKeys = [...remoteAttributes.map((attribute: any) => attribute.key), ...deletingAttributes.map((attribute: any) => attribute.key)] if (attributeKeys.length) { const deleteAttributesPoolStatus = await awaitPools.deleteAttributes(collection['databaseId'], collection['$id'], attributeKeys); @@ -940,7 +948,8 @@ const attributesToCreate = async (remoteAttributes, localAttributes, collection, return localAttributes.filter((attribute) => !attributesContains(attribute, remoteAttributes)); } -const createIndexes = async (indexes, collection) => { + +const createIndexes = async (indexes: any[], collection: any): Promise => { log(`Creating indexes ...`) for (let index of indexes) { @@ -958,7 +967,7 @@ const createIndexes = async (indexes, collection) => { const result = await awaitPools.expectIndexes( collection['databaseId'], collection['$id'], - indexes.map(index => index.key) + indexes.map((index: any) => index.key) ); if (!result) { @@ -967,7 +976,8 @@ const createIndexes = async (indexes, collection) => { success(`Created ${indexes.length} indexes`); } -const createAttributes = async (attributes, collection) => { + +const createAttributes = async (attributes: any[], collection: any): Promise => { for (let attribute of attributes) { if (attribute.side !== 'child') { await createAttribute(collection['databaseId'], collection['$id'], attribute); @@ -977,7 +987,7 @@ const createAttributes = async (attributes, collection) => { const result = await awaitPools.expectAttributes( collection['databaseId'], collection['$id'], - collection.attributes.filter(attribute => attribute.side !== 'child').map(attribute => attribute.key) + collection.attributes.filter((attribute: any) => attribute.side !== 'child').map((attribute: any) => attribute.key) ); if (!result) { @@ -986,7 +996,8 @@ const createAttributes = async (attributes, collection) => { success(`Created ${attributes.length} attributes`); } -const createColumns = async (columns, table) => { + +const createColumns = async (columns: any[], table: any): Promise => { for (let column of columns) { if (column.side !== 'child') { await createAttribute(table['databaseId'], table['$id'], column); @@ -996,7 +1007,7 @@ const createColumns = async (columns, table) => { const result = await awaitPools.expectAttributes( table['databaseId'], table['$id'], - table.columns.filter(column => column.side !== 'child').map(column => column.key) + table.columns.filter((column: any) => column.side !== 'child').map((column: any) => column.key) ); if (!result) { @@ -1006,8 +1017,8 @@ const createColumns = async (columns, table) => { success(`Created ${columns.length} columns`); } -const pushResources = async () => { - const actions = { +const pushResources = async (): Promise => { + const actions: Record Promise> = { settings: pushSettings, functions: pushFunction, sites: pushSite, @@ -1032,7 +1043,7 @@ const pushResources = async () => { } }; -const pushSettings = async () => { +const pushSettings = async (): Promise => { checkDeployConditions(localConfig); try { @@ -1045,7 +1056,7 @@ const pushSettings = async () => { const localSettings = localConfig.getProject().projectSettings ?? {}; log('Checking for changes ...'); - const changes = []; + const changes: any[] = []; changes.push(...(getObjectChanges(remoteSettings, localSettings, 'services', 'Service'))); changes.push(...(getObjectChanges(remoteSettings['auth'] ?? {}, localSettings['auth'] ?? {}, 'methods', 'Auth method'))); @@ -1122,17 +1133,25 @@ const pushSettings = async () => { } } -const pushSite = async({ siteId, async, code, withVariables } = { returnOnZero: false }) => { +interface PushSiteOptions { + siteId?: string; + async?: boolean; + code?: boolean; + withVariables?: boolean; + returnOnZero?: boolean; +} + +const pushSite = async({ siteId, async: asyncDeploy, code, withVariables }: PushSiteOptions = { returnOnZero: false }): Promise => { process.chdir(localConfig.configDirectoryPath) - const siteIds = []; + const siteIds: string[] = []; if(siteId) { siteIds.push(siteId); } else if (cliConfig.all) { checkDeployConditions(localConfig); const sites = localConfig.getSites(); - siteIds.push(...sites.map((site) => { + siteIds.push(...sites.map((site: any) => { return site.$id; })); } @@ -1150,9 +1169,9 @@ const pushSite = async({ siteId, async, code, withVariables } = { returnOnZero: return; } - let sites = siteIds.map((id) => { + let sites = siteIds.map((id: string) => { const sites = localConfig.getSites(); - const site = sites.find((s) => s.$id === id); + const site = sites.find((s: any) => s.$id === id); if (!site) { throw new Error("Site '" + id + "' not found.") @@ -1167,8 +1186,8 @@ const pushSite = async({ siteId, async, code, withVariables } = { returnOnZero: if (!site.buildCommand) { log(`Site ${site.name} is missing build command.`); - const answers = await inquirer.prompt(questionsGetBuildCommand) - site.buildCommand = answers.buildCommand; + const answers = await inquirer.prompt(questionsGetEntrypoint) + site.buildCommand = answers.entrypoint; localConfig.addSite(site); } } @@ -1182,11 +1201,11 @@ const pushSite = async({ siteId, async, code, withVariables } = { returnOnZero: Spinner.start(false); let successfullyPushed = 0; let successfullyDeployed = 0; - const failedDeployments = []; - const errors = []; + const failedDeployments: any[] = []; + const errors: any[] = []; - await Promise.all(sites.map(async (site) => { - let response = {}; + await Promise.all(sites.map(async (site: any) => { + let response: any = {}; const ignore = site.ignore ? 'appwrite.config.json' : '.gitignore'; let siteExists = false; @@ -1226,7 +1245,7 @@ const pushSite = async({ siteId, async, code, withVariables } = { returnOnZero: vars: JSON.stringify(response.vars), parseOutput: false }); - } catch (e) { + } catch (e: any) { if (Number(e.code) === 404) { siteExists = false; @@ -1280,7 +1299,7 @@ const pushSite = async({ siteId, async, code, withVariables } = { returnOnZero: } updaterRow.update({ status: 'Created' }); - } catch (e) { + } catch (e: any) { errors.push(e) updaterRow.fail({ errorMessage: e.message ?? 'General error occurs please try again' }); return; @@ -1295,7 +1314,7 @@ const pushSite = async({ siteId, async, code, withVariables } = { returnOnZero: parseOutput: false }, 100, 'variables'); - await Promise.all(variables.map(async variable => { + await Promise.all(variables.map(async (variable: any) => { await sitesDeleteVariable({ siteId: site['$id'], variableId: variable['$id'], @@ -1304,7 +1323,7 @@ const pushSite = async({ siteId, async, code, withVariables } = { returnOnZero: })); const envFileLocation = `${site['path']}/.env`; - let envVariables = []; + let envVariables: Array<{key: string; value: string}> = []; try { if (fs.existsSync(envFileLocation)) { const envObject = parseDotenv(fs.readFileSync(envFileLocation, 'utf8')); @@ -1314,7 +1333,7 @@ const pushSite = async({ siteId, async, code, withVariables } = { returnOnZero: // Handle parsing errors gracefully envVariables = []; } - await Promise.all(envVariables.map(async variable => { + await Promise.all(envVariables.map(async (variable) => { await sitesCreateVariable({ siteId: site['$id'], key: variable.key, @@ -1349,7 +1368,7 @@ const pushSite = async({ siteId, async, code, withVariables } = { returnOnZero: updaterRow.update({ status: 'Pushed' }); deploymentCreated = true; successfullyPushed++; - } catch (e) { + } catch (e: any) { errors.push(e); switch (e.code) { @@ -1361,7 +1380,7 @@ const pushSite = async({ siteId, async, code, withVariables } = { returnOnZero: } } - if (deploymentCreated && !async) { + if (deploymentCreated && !asyncDeploy) { try { const deploymentId = response['$id']; updaterRow.update({ status: 'Deploying', end: 'Checking deployment status...' }) @@ -1408,7 +1427,7 @@ const pushSite = async({ siteId, async, code, withVariables } = { returnOnZero: pollChecks++; await new Promise(resolve => setTimeout(resolve, POLL_DEBOUNCE * 1.5)); } - } catch (e) { + } catch (e: any) { errors.push(e); updaterRow.fail({ errorMessage: e.message ?? 'Unknown error occurred. Please try again' }) } @@ -1426,7 +1445,7 @@ const pushSite = async({ siteId, async, code, withVariables } = { returnOnZero: error(`Deployment of ${name} has failed. Check at ${failUrl} for more details\n`); }); - if (!async) { + if (!asyncDeploy) { if (successfullyPushed === 0) { error('No sites were pushed.'); } else if (successfullyDeployed !== successfullyPushed) { @@ -1445,17 +1464,25 @@ const pushSite = async({ siteId, async, code, withVariables } = { returnOnZero: } } -const pushFunction = async ({ functionId, async, code, withVariables } = { returnOnZero: false }) => { +interface PushFunctionOptions { + functionId?: string; + async?: boolean; + code?: boolean; + withVariables?: boolean; + returnOnZero?: boolean; +} + +const pushFunction = async ({ functionId, async: asyncDeploy, code, withVariables }: PushFunctionOptions = { returnOnZero: false }): Promise => { process.chdir(localConfig.configDirectoryPath) - const functionIds = []; + const functionIds: string[] = []; if (functionId) { functionIds.push(functionId); } else if (cliConfig.all) { checkDeployConditions(localConfig); const functions = localConfig.getFunctions(); - functionIds.push(...functions.map((func) => { + functionIds.push(...functions.map((func: any) => { return func.$id; })); } @@ -1473,9 +1500,9 @@ const pushFunction = async ({ functionId, async, code, withVariables } = { retur return; } - let functions = functionIds.map((id) => { + let functions = functionIds.map((id: string) => { const functions = localConfig.getFunctions(); - const func = functions.find((f) => f.$id === id); + const func = functions.find((f: any) => f.$id === id); if (!func) { throw new Error("Function '" + id + "' not found.") @@ -1505,11 +1532,11 @@ const pushFunction = async ({ functionId, async, code, withVariables } = { retur Spinner.start(false); let successfullyPushed = 0; let successfullyDeployed = 0; - const failedDeployments = []; - const errors = []; + const failedDeployments: any[] = []; + const errors: any[] = []; - await Promise.all(functions.map(async (func) => { - let response = {}; + await Promise.all(functions.map(async (func: any) => { + let response: any = {}; const ignore = func.ignore ? 'appwrite.config.json' : '.gitignore'; let functionExists = false; @@ -1547,7 +1574,7 @@ const pushFunction = async ({ functionId, async, code, withVariables } = { retur vars: JSON.stringify(response.vars), parseOutput: false }); - } catch (e) { + } catch (e: any) { if (Number(e.code) === 404) { functionExists = false; @@ -1601,7 +1628,7 @@ const pushFunction = async ({ functionId, async, code, withVariables } = { retur } updaterRow.update({ status: 'Created' }); - } catch (e) { + } catch (e: any) { errors.push(e) updaterRow.fail({ errorMessage: e.message ?? 'General error occurs please try again' }); return; @@ -1616,7 +1643,7 @@ const pushFunction = async ({ functionId, async, code, withVariables } = { retur parseOutput: false }, 100, 'variables'); - await Promise.all(variables.map(async variable => { + await Promise.all(variables.map(async (variable: any) => { await functionsDeleteVariable({ functionId: func['$id'], variableId: variable['$id'], @@ -1625,7 +1652,7 @@ const pushFunction = async ({ functionId, async, code, withVariables } = { retur })); const envFileLocation = `${func['path']}/.env`; - let envVariables = []; + let envVariables: Array<{key: string; value: string}> = []; try { if (fs.existsSync(envFileLocation)) { const envObject = parseDotenv(fs.readFileSync(envFileLocation, 'utf8')); @@ -1635,7 +1662,7 @@ const pushFunction = async ({ functionId, async, code, withVariables } = { retur // Handle parsing errors gracefully envVariables = []; } - await Promise.all(envVariables.map(async variable => { + await Promise.all(envVariables.map(async (variable) => { await functionsCreateVariable({ functionId: func['$id'], variableId: ID.unique(), @@ -1669,7 +1696,7 @@ const pushFunction = async ({ functionId, async, code, withVariables } = { retur updaterRow.update({ status: 'Pushed' }); deploymentCreated = true; successfullyPushed++; - } catch (e) { + } catch (e: any) { errors.push(e); switch (e.code) { @@ -1681,7 +1708,7 @@ const pushFunction = async ({ functionId, async, code, withVariables } = { retur } } - if (deploymentCreated && !async) { + if (deploymentCreated && !asyncDeploy) { try { const deploymentId = response['$id']; updaterRow.update({ status: 'Deploying', end: 'Checking deployment status...' }) @@ -1694,7 +1721,6 @@ const pushFunction = async ({ functionId, async, code, withVariables } = { retur parseOutput: false }); - const status = response['status']; if (status === 'ready') { successfullyDeployed++; @@ -1729,7 +1755,7 @@ const pushFunction = async ({ functionId, async, code, withVariables } = { retur pollChecks++; await new Promise(resolve => setTimeout(resolve, POLL_DEBOUNCE * 1.5)); } - } catch (e) { + } catch (e: any) { errors.push(e); updaterRow.fail({ errorMessage: e.message ?? 'Unknown error occurred. Please try again' }) } @@ -1747,7 +1773,7 @@ const pushFunction = async ({ functionId, async, code, withVariables } = { retur error(`Deployment of ${name} has failed. Check at ${failUrl} for more details\n`); }); - if (!async) { + if (!asyncDeploy) { if (successfullyPushed === 0) { error('No functions were pushed.'); } else if (successfullyDeployed !== successfullyPushed) { @@ -1766,7 +1792,12 @@ const pushFunction = async ({ functionId, async, code, withVariables } = { retur } } -const checkAndApplyTablesDBChanges = async () => { +interface TablesDBChangesResult { + applied: boolean; + resyncNeeded: boolean; +} + +const checkAndApplyTablesDBChanges = async (): Promise => { log('Checking for tablesDB changes ...'); const localTablesDBs = localConfig.getTablesDBs(); @@ -1776,14 +1807,14 @@ const checkAndApplyTablesDBChanges = async () => { return { applied: false, resyncNeeded: false }; } - const changes = []; - const toCreate = []; - const toUpdate = []; - const toDelete = []; + const changes: any[] = []; + const toCreate: any[] = []; + const toUpdate: any[] = []; + const toDelete: any[] = []; // Check for deletions - remote DBs that aren't in local config for (const remoteDB of remoteTablesDBs) { - const localDB = localTablesDBs.find(db => db.$id === remoteDB.$id); + const localDB = localTablesDBs.find((db: any) => db.$id === remoteDB.$id); if (!localDB) { toDelete.push(remoteDB); changes.push({ @@ -1798,7 +1829,7 @@ const checkAndApplyTablesDBChanges = async () => { // Check for additions and updates for (const localDB of localTablesDBs) { - const remoteDB = remoteTablesDBs.find(db => db.$id === localDB.$id); + const remoteDB = remoteTablesDBs.find((db: any) => db.$id === localDB.$id); if (!remoteDB) { toCreate.push(localDB); @@ -1871,7 +1902,7 @@ const checkAndApplyTablesDBChanges = async () => { }); success(`Deleted ${db.name} ( ${db.$id} )`); needsResync = true; - } catch (e) { + } catch (e: any) { error(`Failed to delete database ${db.name} ( ${db.$id} ): ${e.message}`); throw new Error(`Database sync failed during deletion of ${db.$id}. Some changes may have been applied.`); } @@ -1888,7 +1919,7 @@ const checkAndApplyTablesDBChanges = async () => { parseOutput: false }); success(`Created ${db.name} ( ${db.$id} )`); - } catch (e) { + } catch (e: any) { error(`Failed to create database ${db.name} ( ${db.$id} ): ${e.message}`); throw new Error(`Database sync failed during creation of ${db.$id}. Some changes may have been applied.`); } @@ -1905,7 +1936,7 @@ const checkAndApplyTablesDBChanges = async () => { parseOutput: false }); success(`Updated ${db.name} ( ${db.$id} )`); - } catch (e) { + } catch (e: any) { error(`Failed to update database ${db.name} ( ${db.$id} ): ${e.message}`); throw new Error(`Database sync failed during update of ${db.$id}. Some changes may have been applied.`); } @@ -1918,8 +1949,13 @@ const checkAndApplyTablesDBChanges = async () => { return { applied: true, resyncNeeded: needsResync }; }; -const pushTable = async ({ returnOnZero, attempts } = { returnOnZero: false }) => { - const tables = []; +interface PushTableOptions { + returnOnZero?: boolean; + attempts?: number; +} + +const pushTable = async ({ returnOnZero, attempts }: PushTableOptions = { returnOnZero: false }): Promise => { + const tables: any[] = []; if (attempts) { pollMaxDebounces = attempts; @@ -1932,13 +1968,13 @@ const pushTable = async ({ returnOnZero, attempts } = { returnOnZero: false }) = const remoteTablesDBs = (await paginate(tablesDBList, { parseOutput: false }, 100, 'databases')).databases; const localTablesDBs = localConfig.getTablesDBs(); - const remoteDatabaseIds = new Set(remoteTablesDBs.map(db => db.$id)); + const remoteDatabaseIds = new Set(remoteTablesDBs.map((db: any) => db.$id)); const localTables = localConfig.getTables(); - const validTables = localTables.filter(table => remoteDatabaseIds.has(table.databaseId)); + const validTables = localTables.filter((table: any) => remoteDatabaseIds.has(table.databaseId)); localConfig.set('tables', validTables); - const validTablesDBs = localTablesDBs.filter(db => remoteDatabaseIds.has(db.$id)); + const validTablesDBs = localTablesDBs.filter((db: any) => remoteDatabaseIds.has(db.$id)); localConfig.set('tablesDB', validTablesDBs); success('Configuration resynced successfully.'); @@ -1948,7 +1984,7 @@ const pushTable = async ({ returnOnZero, attempts } = { returnOnZero: false }) = log('Checking for deleted tables ...'); const localTablesDBs = localConfig.getTablesDBs(); const localTables = localConfig.getTables(); - const tablesToDelete = []; + const tablesToDelete: any[] = []; for (const db of localTablesDBs) { try { @@ -1958,7 +1994,7 @@ const pushTable = async ({ returnOnZero, attempts } = { returnOnZero: false }) = }, 100, 'tables'); for (const remoteTable of remoteTables) { - const localTable = localTables.find(t => t.$id === remoteTable.$id && t.databaseId === db.$id); + const localTable = localTables.find((t: any) => t.$id === remoteTable.$id && t.databaseId === db.$id); if (!localTable) { tablesToDelete.push({ ...remoteTable, @@ -1974,7 +2010,7 @@ const pushTable = async ({ returnOnZero, attempts } = { returnOnZero: false }) = if (tablesToDelete.length > 0) { log('Found tables that exist remotely but not locally:'); - const deletionChanges = tablesToDelete.map(table => ({ + const deletionChanges = tablesToDelete.map((table: any) => ({ id: table.$id, action: chalk.red('deleting'), key: 'Table', @@ -1994,7 +2030,7 @@ const pushTable = async ({ returnOnZero, attempts } = { returnOnZero: false }) = parseOutput: false }); success(`Deleted ${table.name} ( ${table.$id} )`); - } catch (e) { + } catch (e: any) { error(`Failed to delete table ${table.name} ( ${table.$id} ): ${e.message}`); } } @@ -2011,10 +2047,10 @@ const pushTable = async ({ returnOnZero, attempts } = { returnOnZero: false }) = const answers = await inquirer.prompt(questionsPushTables) if (answers.tables) { const configTables = new Map(); - localConfig.getTables().forEach((c) => { + localConfig.getTables().forEach((c: any) => { configTables.set(`${c['databaseId']}|${c['$id']}`, c); }); - answers.tables.forEach((a) => { + answers.tables.forEach((a: any) => { const table = configTables.get(a); tables.push(table); }) @@ -2033,7 +2069,7 @@ const pushTable = async ({ returnOnZero, attempts } = { returnOnZero: false }) = let tablesChanged = new Set(); // Parallel tables actions - await Promise.all(tables.map(async (table) => { + await Promise.all(tables.map(async (table: any) => { try { const remoteTable = await tablesDBGetTable({ databaseId: table['databaseId'], @@ -2041,7 +2077,7 @@ const pushTable = async ({ returnOnZero, attempts } = { returnOnZero: false }) = parseOutput: false, }); - const changes = []; + const changes: string[] = []; if (remoteTable.name !== table.name) changes.push('name'); if (remoteTable.rowSecurity !== table.rowSecurity) changes.push('rowSecurity'); if (remoteTable.enabled !== table.enabled) changes.push('enabled'); @@ -2063,8 +2099,7 @@ const pushTable = async ({ returnOnZero, attempts } = { returnOnZero: false }) = table.remoteVersion = remoteTable; table.isExisted = true; - } catch - (e) { + } catch (e: any) { if (Number(e.code) === 404) { log(`Table ${table.name} does not exist in the project. Creating ... `); await tablesDBCreateTable({ @@ -2118,9 +2153,14 @@ const pushTable = async ({ returnOnZero, attempts } = { returnOnZero: false }) = success(`Successfully pushed ${tablesChanged.size} tables`); } -const pushCollection = async ({ returnOnZero, attempts } = { returnOnZero: false }) => { +interface PushCollectionOptions { + returnOnZero?: boolean; + attempts?: number; +} + +const pushCollection = async ({ returnOnZero, attempts }: PushCollectionOptions = { returnOnZero: false }): Promise => { warn("appwrite push collection has been deprecated. Please consider using 'appwrite push tables' instead"); - const collections = []; + const collections: any[] = []; if (attempts) { pollMaxDebounces = attempts; @@ -2133,10 +2173,10 @@ const pushCollection = async ({ returnOnZero, attempts } = { returnOnZero: false const answers = await inquirer.prompt(questionsPushCollections) if (answers.collections) { const configCollections = new Map(); - localConfig.getCollections().forEach((c) => { + localConfig.getCollections().forEach((c: any) => { configCollections.set(`${c['databaseId']}|${c['$id']}`, c); }); - answers.collections.forEach((a) => { + answers.collections.forEach((a: any) => { const collection = configCollections.get(a); collections.push(collection); }) @@ -2149,10 +2189,10 @@ const pushCollection = async ({ returnOnZero, attempts } = { returnOnZero: false return; } - const databases = Array.from(new Set(collections.map(collection => collection['databaseId']))); + const databases = Array.from(new Set(collections.map((collection: any) => collection['databaseId']))); // Parallel db actions - await Promise.all(databases.map(async (databaseId) => { + await Promise.all(databases.map(async (databaseId: any) => { const localDatabase = localConfig.getDatabase(databaseId); try { @@ -2181,12 +2221,11 @@ const pushCollection = async ({ returnOnZero, attempts } = { returnOnZero: false } })); - if (!(await approveChanges(collections, databasesGetCollection, KeysCollection, 'collectionId', 'collections', ['attributes', 'indexes'], 'databaseId', 'databaseId',))) { return; } // Parallel collection actions - await Promise.all(collections.map(async (collection) => { + await Promise.all(collections.map(async (collection: any) => { try { const remoteCollection = await databasesGetCollection({ databaseId: collection['databaseId'], @@ -2207,8 +2246,7 @@ const pushCollection = async ({ returnOnZero, attempts } = { returnOnZero: false collection.remoteVersion = remoteCollection; collection.isExisted = true; - } catch - (e) { + } catch (e: any) { if (Number(e.code) === 404) { log(`Collection ${collection.name} does not exist in the project. Creating ... `); await databasesCreateCollection({ @@ -2260,15 +2298,19 @@ const pushCollection = async ({ returnOnZero, attempts } = { returnOnZero: false success(`Successfully pushed ${numberOfCollections} collections`); } -const pushBucket = async ({ returnOnZero } = { returnOnZero: false }) => { - let response = {}; +interface PushBucketOptions { + returnOnZero?: boolean; +} + +const pushBucket = async ({ returnOnZero }: PushBucketOptions = { returnOnZero: false }): Promise => { + let response: any = {}; - let bucketIds = []; + let bucketIds: string[] = []; const configBuckets = localConfig.getBuckets(); if (cliConfig.all) { checkDeployConditions(localConfig); - bucketIds.push(...configBuckets.map((b) => b.$id)); + bucketIds.push(...configBuckets.map((b: any) => b.$id)); } if (bucketIds.length === 0) { @@ -2284,10 +2326,10 @@ const pushBucket = async ({ returnOnZero } = { returnOnZero: false }) => { return; } - let buckets = []; + let buckets: any[] = []; for (const bucketId of bucketIds) { - const idBuckets = configBuckets.filter((b) => b.$id === bucketId); + const idBuckets = configBuckets.filter((b: any) => b.$id === bucketId); buckets.push(...idBuckets); } @@ -2319,7 +2361,7 @@ const pushBucket = async ({ returnOnZero } = { returnOnZero: false }) => { compression: bucket.compression, parseOutput: false }); - } catch (e) { + } catch (e: any) { if (Number(e.code) === 404) { log(`Bucket ${bucket.name} does not exist in the project. Creating ... `); @@ -2345,15 +2387,19 @@ const pushBucket = async ({ returnOnZero } = { returnOnZero: false }) => { success(`Successfully pushed ${buckets.length} buckets.`); } -const pushTeam = async ({ returnOnZero } = { returnOnZero: false }) => { - let response = {}; +interface PushTeamOptions { + returnOnZero?: boolean; +} + +const pushTeam = async ({ returnOnZero }: PushTeamOptions = { returnOnZero: false }): Promise => { + let response: any = {}; - let teamIds = []; + let teamIds: string[] = []; const configTeams = localConfig.getTeams(); if (cliConfig.all) { checkDeployConditions(localConfig); - teamIds.push(...configTeams.map((t) => t.$id)); + teamIds.push(...configTeams.map((t: any) => t.$id)); } if (teamIds.length === 0) { @@ -2369,10 +2415,10 @@ const pushTeam = async ({ returnOnZero } = { returnOnZero: false }) => { return; } - let teams = []; + let teams: any[] = []; for (const teamId of teamIds) { - const idTeams = configTeams.filter((t) => t.$id === teamId); + const idTeams = configTeams.filter((t: any) => t.$id === teamId); teams.push(...idTeams); } @@ -2380,7 +2426,6 @@ const pushTeam = async ({ returnOnZero } = { returnOnZero: false }) => { return; } - log('Pushing teams ...'); for (let team of teams) { @@ -2397,7 +2442,7 @@ const pushTeam = async ({ returnOnZero } = { returnOnZero: false }) => { name: team.name, parseOutput: false }); - } catch (e) { + } catch (e: any) { if (Number(e.code) === 404) { log(`Team ${team.name} does not exist in the project. Creating ... `); @@ -2415,15 +2460,19 @@ const pushTeam = async ({ returnOnZero } = { returnOnZero: false }) => { success(`Successfully pushed ${teams.length} teams.`); } -const pushMessagingTopic = async ({ returnOnZero } = { returnOnZero: false }) => { - let response = {}; +interface PushMessagingTopicOptions { + returnOnZero?: boolean; +} + +const pushMessagingTopic = async ({ returnOnZero }: PushMessagingTopicOptions = { returnOnZero: false }): Promise => { + let response: any = {}; - let topicsIds = []; + let topicsIds: string[] = []; const configTopics = localConfig.getMessagingTopics(); if (cliConfig.all) { checkDeployConditions(localConfig); - topicsIds.push(...configTopics.map((b) => b.$id)); + topicsIds.push(...configTopics.map((b: any) => b.$id)); } if (topicsIds.length === 0) { @@ -2439,10 +2488,10 @@ const pushMessagingTopic = async ({ returnOnZero } = { returnOnZero: false }) => return; } - let topics = []; + let topics: any[] = []; for (const topicId of topicsIds) { - const idTopic = configTopics.filter((b) => b.$id === topicId); + const idTopic = configTopics.filter((b: any) => b.$id === topicId); topics.push(...idTopic); } @@ -2468,7 +2517,7 @@ const pushMessagingTopic = async ({ returnOnZero } = { returnOnZero: false }) => subscribe: topic.subscribe, parseOutput: false }); - } catch (e) { + } catch (e: any) { if (Number(e.code) === 404) { log(`Topic ${topic.name} does not exist in the project. Creating ... `); @@ -2489,7 +2538,7 @@ const pushMessagingTopic = async ({ returnOnZero } = { returnOnZero: false }) => success(`Successfully pushed ${topics.length} topics.`); } -const push = new Command("push") +export const push = new Command("push") .description(commandDescriptions['push']) .action(actionRunner(pushResources)); @@ -2558,13 +2607,8 @@ push .description("Push messaging topics in the current project.") .action(actionRunner(pushMessagingTopic)); -const deploy = new Command("deploy") +export const deploy = new Command("deploy") .description('Removed. Use appwrite push instead') .action(actionRunner(async () => { warn("appwrite deploy has been removed. Please use 'appwrite push' instead"); })); - -module.exports = { - push, - deploy -} diff --git a/lib/commands/run.js b/lib/commands/run.ts similarity index 76% rename from lib/commands/run.js rename to lib/commands/run.ts index 3338bda6..8caf2feb 100644 --- a/lib/commands/run.js +++ b/lib/commands/run.ts @@ -1,23 +1,31 @@ -const Tail = require('tail').Tail; -const { parse: parseDotenv } = require('dotenv'); -const chalk = require('chalk'); -const ignore = require("ignore"); -const tar = require("tar"); -const fs = require("fs"); -const chokidar = require('chokidar'); -const inquirer = require("inquirer"); -const path = require("path"); -const { Command } = require("commander"); -const { localConfig, globalConfig } = require("../config"); -const { paginate } = require('../paginate'); -const { functionsListVariables } = require('./functions'); -const { questionsRunFunctions } = require("../questions"); -const { actionRunner, success, log, warn, error, hint, commandDescriptions, drawTable } = require("../parser"); -const { systemHasCommand, isPortTaken, getAllFiles } = require('../utils'); -const { runtimeNames, systemTools, JwtManager, Queue } = require('../emulation/utils'); -const { dockerStop, dockerCleanup, dockerStart, dockerBuild, dockerPull } = require('../emulation/docker'); - -const runFunction = async ({ port, functionId, withVariables, reload, userId } = {}) => { +import { Tail } from 'tail'; +import { parse as parseDotenv } from 'dotenv'; +import chalk from 'chalk'; +import ignore = require('ignore'); +import tar = require('tar'); +import fs = require('fs'); +import chokidar from 'chokidar'; +import inquirer from 'inquirer'; +import path = require('path'); +import { Command } from 'commander'; +import { localConfig, globalConfig } from '../config'; +import { paginate } from '../paginate'; +import { functionsListVariables } from './functions'; +import { questionsRunFunctions } from '../questions'; +import { actionRunner, success, log, warn, error, hint, commandDescriptions, drawTable } from '../parser'; +import { systemHasCommand, isPortTaken, getAllFiles } from '../utils'; +import { runtimeNames, systemTools, JwtManager, Queue } from '../emulation/utils'; +import { dockerStop, dockerCleanup, dockerStart, dockerBuild, dockerPull } from '../emulation/docker'; + +interface RunFunctionOptions { + port?: string | number; + functionId?: string; + withVariables?: boolean; + reload?: boolean; + userId?: string; +} + +const runFunction = async ({ port, functionId, withVariables, reload, userId }: RunFunctionOptions = {}): Promise => { // Selection if(!functionId) { const answers = await inquirer.prompt(questionsRunFunctions[0]); @@ -25,7 +33,7 @@ const runFunction = async ({ port, functionId, withVariables, reload, userId } = } const functions = localConfig.getFunctions(); - const func = functions.find((f) => f.$id === functionId); + const func = functions.find((f: any) => f.$id === functionId); if (!func) { throw new Error("Function '" + functionId + "' not found.") } @@ -34,34 +42,35 @@ const runFunction = async ({ port, functionId, withVariables, reload, userId } = const tool = systemTools[runtimeName]; // Configuration: Port + let portNum: number | null = null; if(port) { - port = +port; + portNum = +port; } - if(isNaN(port)) { - port = null; + if(isNaN(portNum!)) { + portNum = null; } - if(port) { - const taken = await isPortTaken(port); + if(portNum) { + const taken = await isPortTaken(portNum); if(taken) { - error(`Port ${port} is already in use by another process.`); + error(`Port ${portNum} is already in use by another process.`); return; } } - if(!port) { + if(!portNum) { let portFound = false; - port = 3000; - while(port < 3100) { - const taken = await isPortTaken(port); + portNum = 3000; + while(portNum < 3100) { + const taken = await isPortTaken(portNum); if(!taken) { portFound = true; break; } - port++; + portNum++; } if(!portFound) { @@ -112,8 +121,8 @@ const runFunction = async ({ port, functionId, withVariables, reload, userId } = fs.writeFileSync(errorsPath, ''); } - const userVariables = {}; - const allVariables = {}; + const userVariables: Record = {}; + const allVariables: Record = {}; if(withVariables) { try { @@ -122,11 +131,11 @@ const runFunction = async ({ port, functionId, withVariables, reload, userId } = parseOutput: false }, 100, 'variables'); - remoteVariables.forEach((v) => { + remoteVariables.forEach((v: any) => { allVariables[v.key] = v.value; userVariables[v.key] = v.value; }); - } catch(err) { + } catch(err: any) { warn("Remote variables not fetched. Production environment variables will not be available. Reason: " + err.message); } } @@ -152,11 +161,11 @@ const runFunction = async ({ port, functionId, withVariables, reload, userId } = try { await JwtManager.setup(userId, func.scopes ?? []); - } catch(err) { + } catch(err: any) { warn("Dynamic API key not generated. Header x-appwrite-key will not be set. Reason: " + err.message); } - const headers = {}; + const headers: Record = {}; headers['x-appwrite-key'] = JwtManager.functionJwt ?? ''; headers['x-appwrite-trigger'] = 'http'; headers['x-appwrite-event'] = ''; @@ -167,16 +176,16 @@ const runFunction = async ({ port, functionId, withVariables, reload, userId } = if(Object.keys(userVariables).length > 0) { drawTable(Object.keys(userVariables).map((key) => ({ key, - value: userVariables[key].split("").filter((_, i) => i < 16).map(() => "*").join("") + value: userVariables[key].split("").filter((_: string, i: number) => i < 16).map(() => "*").join("") }))); } await dockerPull(func); - new Tail(logsPath).on("line", function(data) { + new Tail(logsPath).on("line", function(data: string) { process.stdout.write(chalk.white(`${data}\n`)); }); - new Tail(errorsPath).on("line", function(data) { + new Tail(errorsPath).on("line", function(data: string) { process.stdout.write(chalk.white(`${data}\n`)); }); @@ -194,7 +203,7 @@ const runFunction = async ({ port, functionId, withVariables, reload, userId } = chokidar.watch('.', { cwd: path.join(localConfig.getDirname(), func.path), ignoreInitial: true, - ignored: (xpath) => { + ignored: (xpath: string) => { const relativePath = path.relative(functionPath, xpath); if(!relativePath) { @@ -202,18 +211,18 @@ const runFunction = async ({ port, functionId, withVariables, reload, userId } = } return ignorer.ignores(relativePath); } - }).on('all', async (_event, filePath) => { + }).on('all', async (_event: string, filePath: string) => { Queue.push(filePath); }); } - Queue.events.on('reload', async ({ files }) => { + Queue.events.on('reload', async ({ files }: { files: string[] }) => { Queue.lock(); try { await dockerStop(func.$id); - const dependencyFile = files.find((filePath) => tool.dependencyFiles.includes(filePath)); + const dependencyFile = files.find((filePath: string) => tool.dependencyFiles.includes(filePath)); if(tool.isCompiled || dependencyFile) { log(`Rebuilding the function due to file changes ...`); await dockerBuild(func, allVariables); @@ -223,7 +232,7 @@ const runFunction = async ({ port, functionId, withVariables, reload, userId } = return; } - await dockerStart(func, allVariables, port); + await dockerStart(func, allVariables, portNum!); } else { log('Hot-swapping function.. Files with change are ' + files.join(', ')); @@ -247,7 +256,7 @@ const runFunction = async ({ port, functionId, withVariables, reload, userId } = file: buildPath }); - const ignorer = ignore(); + const ignorer = ignore.default(); ignorer.add('.appwrite'); if (func.ignore) { ignorer.add(func.ignore); @@ -255,7 +264,7 @@ const runFunction = async ({ port, functionId, withVariables, reload, userId } = ignorer.add(fs.readFileSync(path.join(functionPath, '.gitignore')).toString()); } - const filesToCopy = getAllFiles(functionPath).map((file) => path.relative(functionPath, file)).filter((file) => !ignorer.ignores(file)); + const filesToCopy = getAllFiles(functionPath).map((file: string) => path.relative(functionPath, file)).filter((file: string) => !ignorer.ignores(file)); for(const f of filesToCopy) { const filePath = path.join(hotSwapPath, f); if (fs.existsSync(filePath)) { @@ -279,7 +288,7 @@ const runFunction = async ({ port, functionId, withVariables, reload, userId } = file: buildPath }, ['.']); - await dockerStart(func, allVariables, port); + await dockerStart(func, allVariables, portNum!); } } catch(err) { console.error(err); @@ -300,17 +309,17 @@ const runFunction = async ({ port, functionId, withVariables, reload, userId } = log('Starting function using Docker ...'); hint('Function automatically restarts when you edit your code.'); - await dockerStart(func, allVariables, port); + await dockerStart(func, allVariables, portNum!); Queue.unlock(); } -const run = new Command("run") +export const run = new Command("run") .description(commandDescriptions['run']) .configureHelp({ helpWidth: process.stdout.columns || 80 }) - .action(actionRunner(async (_options, command) => { + .action(actionRunner(async (_options: any, command: Command) => { command.help(); })); @@ -325,6 +334,3 @@ run .option(`--no-reload`, `Prevent live reloading of server when changes are made to function files`) .action(actionRunner(runFunction)); -module.exports = { - run -} diff --git a/lib/commands/sites.js b/lib/commands/sites.ts similarity index 63% rename from lib/commands/sites.js rename to lib/commands/sites.ts index c4144224..f213f386 100644 --- a/lib/commands/sites.js +++ b/lib/commands/sites.ts @@ -1,31 +1,27 @@ -const fs = require('fs'); -const pathLib = require('path'); -const tar = require("tar"); -const ignore = require("ignore"); -const { promisify } = require('util'); -const libClient = require('../client.js'); -const { getAllFiles, showConsoleLink } = require('../utils.js'); -const { Command } = require('commander'); -const { sdkForProject, sdkForConsole } = require('../sdks') -const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } = require('../parser') -const { localConfig, globalConfig } = require("../config"); -const { File } = require('undici'); -const { ReadableStream } = require('stream/web'); - -/** - * @param {fs.ReadStream} readStream - * @returns {ReadableStream} - */ -function convertReadStreamToReadableStream(readStream) { +import fs = require('fs'); +import pathLib = require('path'); +import tar = require('tar'); +import ignore = require('ignore'); +import { promisify } from 'util'; +import Client from '../client'; +import { getAllFiles, showConsoleLink } from '../utils'; +import { Command } from 'commander'; +import { sdkForProject, sdkForConsole } from '../sdks'; +import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } from '../parser'; +import { localConfig, globalConfig } from '../config'; +import { File } from 'undici'; +import { ReadableStream } from 'stream/web'; + +function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ start(controller) { - readStream.on("data", (chunk) => { + readStream.on("data", (chunk: Buffer) => { controller.enqueue(chunk); }); readStream.on("end", () => { controller.close(); }); - readStream.on("error", (err) => { + readStream.on("error", (err: Error) => { controller.error(err); }); }, @@ -35,24 +31,21 @@ function convertReadStreamToReadableStream(readStream) { }); } -const sites = new Command("sites").description(commandDescriptions['sites'] ?? '').configureHelp({ +export const sites = new Command("sites").description(commandDescriptions['sites'] ?? '').configureHelp({ helpWidth: process.stdout.columns || 80 }) -/** - * @typedef {Object} SitesListRequestParams - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name, enabled, framework, deploymentId, buildCommand, installCommand, outputDirectory, installationId - * @property {string} search Search term to filter your list results. Max length: 256 chars. - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {SitesListRequestParams} params - */ -const sitesList = async ({queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface SitesListRequestParams { + queries?: string[]; + search?: string; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const sitesList = async ({queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: SitesListRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/sites'; @@ -73,7 +66,7 @@ const sitesList = async ({queries,search,total,parseOutput = true, overrideForCl }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('sites', 'list'); } else { parse(response) @@ -83,35 +76,31 @@ const sitesList = async ({queries,search,total,parseOutput = true, overrideForCl return response; } -/** - * @typedef {Object} SitesCreateRequestParams - * @property {string} siteId Site ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} name Site name. Max length: 128 chars. - * @property {Framework} framework Sites framework. - * @property {BuildRuntime} buildRuntime Runtime to use during build step. - * @property {boolean} enabled Is site enabled? When set to 'disabled', users cannot access the site but Server SDKs with and API key can still access the site. No data is lost when this is toggled. - * @property {boolean} logging When disabled, request logs will exclude logs and errors, and site responses will be slightly faster. - * @property {number} timeout Maximum request time in seconds. - * @property {string} installCommand Install Command. - * @property {string} buildCommand Build Command. - * @property {string} outputDirectory Output Directory for site. - * @property {Adapter} adapter Framework adapter defining rendering strategy. Allowed values are: static, ssr - * @property {string} installationId Appwrite Installation ID for VCS (Version Control System) deployment. - * @property {string} fallbackFile Fallback file for single page application sites. - * @property {string} providerRepositoryId Repository ID of the repo linked to the site. - * @property {string} providerBranch Production branch for the repo linked to the site. - * @property {boolean} providerSilentMode Is the VCS (Version Control System) connection in silent mode for the repo linked to the site? In silent mode, comments will not be made on commits and pull requests. - * @property {string} providerRootDirectory Path to site code in the linked repo. - * @property {string} specification Framework specification for the site and builds. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {SitesCreateRequestParams} params - */ -const sitesCreate = async ({siteId,name,framework,buildRuntime,enabled,logging,timeout,installCommand,buildCommand,outputDirectory,adapter,installationId,fallbackFile,providerRepositoryId,providerBranch,providerSilentMode,providerRootDirectory,specification,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface SitesCreateRequestParams { + siteId: string; + name: string; + framework: Framework; + buildRuntime: BuildRuntime; + enabled?: boolean; + logging?: boolean; + timeout?: number; + installCommand?: string; + buildCommand?: string; + outputDirectory?: string; + adapter?: Adapter; + installationId?: string; + fallbackFile?: string; + providerRepositoryId?: string; + providerBranch?: string; + providerSilentMode?: boolean; + providerRootDirectory?: string; + specification?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const sitesCreate = async ({siteId,name,framework,buildRuntime,enabled,logging,timeout,installCommand,buildCommand,outputDirectory,adapter,installationId,fallbackFile,providerRepositoryId,providerBranch,providerSilentMode,providerRootDirectory,specification,parseOutput = true, overrideForCli = false, sdk = undefined}: SitesCreateRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/sites'; @@ -184,17 +173,14 @@ const sitesCreate = async ({siteId,name,framework,buildRuntime,enabled,logging,t return response; } -/** - * @typedef {Object} SitesListFrameworksRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {SitesListFrameworksRequestParams} params - */ -const sitesListFrameworks = async ({parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface SitesListFrameworksRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const sitesListFrameworks = async ({parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: SitesListFrameworksRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/sites/frameworks'; @@ -206,7 +192,7 @@ const sitesListFrameworks = async ({parseOutput = true, overrideForCli = false, }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('sites', 'listFrameworks'); } else { parse(response) @@ -216,17 +202,14 @@ const sitesListFrameworks = async ({parseOutput = true, overrideForCli = false, return response; } -/** - * @typedef {Object} SitesListSpecificationsRequestParams - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {SitesListSpecificationsRequestParams} params - */ -const sitesListSpecifications = async ({parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface SitesListSpecificationsRequestParams { + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const sitesListSpecifications = async ({parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: SitesListSpecificationsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/sites/specifications'; @@ -238,7 +221,7 @@ const sitesListSpecifications = async ({parseOutput = true, overrideForCli = fal }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('sites', 'listSpecifications'); } else { parse(response) @@ -248,21 +231,18 @@ const sitesListSpecifications = async ({parseOutput = true, overrideForCli = fal return response; } -/** - * @typedef {Object} SitesListTemplatesRequestParams - * @property {string[]} frameworks List of frameworks allowed for filtering site templates. Maximum of 100 frameworks are allowed. - * @property {string[]} useCases List of use cases allowed for filtering site templates. Maximum of 100 use cases are allowed. - * @property {number} limit Limit the number of templates returned in the response. Default limit is 25, and maximum limit is 5000. - * @property {number} offset Offset the list of returned templates. Maximum offset is 5000. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {SitesListTemplatesRequestParams} params - */ -const sitesListTemplates = async ({frameworks,useCases,limit,offset,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface SitesListTemplatesRequestParams { + frameworks?: string[]; + useCases?: string[]; + limit?: number; + offset?: number; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const sitesListTemplates = async ({frameworks,useCases,limit,offset,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: SitesListTemplatesRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/sites/templates'; @@ -286,7 +266,7 @@ const sitesListTemplates = async ({frameworks,useCases,limit,offset,parseOutput }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('sites', 'listTemplates'); } else { parse(response) @@ -296,18 +276,15 @@ const sitesListTemplates = async ({frameworks,useCases,limit,offset,parseOutput return response; } -/** - * @typedef {Object} SitesGetTemplateRequestParams - * @property {string} templateId Template ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {SitesGetTemplateRequestParams} params - */ -const sitesGetTemplate = async ({templateId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface SitesGetTemplateRequestParams { + templateId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const sitesGetTemplate = async ({templateId,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: SitesGetTemplateRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/sites/templates/{templateId}'.replace('{templateId}', templateId); @@ -319,7 +296,7 @@ const sitesGetTemplate = async ({templateId,parseOutput = true, overrideForCli = }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('sites', 'getTemplate', templateId); } else { parse(response) @@ -329,18 +306,15 @@ const sitesGetTemplate = async ({templateId,parseOutput = true, overrideForCli = return response; } -/** - * @typedef {Object} SitesListUsageRequestParams - * @property {UsageRange} range Date range. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {SitesListUsageRequestParams} params - */ -const sitesListUsage = async ({range,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface SitesListUsageRequestParams { + range?: UsageRange; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const sitesListUsage = async ({range,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: SitesListUsageRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/sites/usage'; @@ -355,7 +329,7 @@ const sitesListUsage = async ({range,parseOutput = true, overrideForCli = false, }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('sites', 'listUsage'); } else { parse(response) @@ -365,18 +339,15 @@ const sitesListUsage = async ({range,parseOutput = true, overrideForCli = false, return response; } -/** - * @typedef {Object} SitesGetRequestParams - * @property {string} siteId Site ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {SitesGetRequestParams} params - */ -const sitesGet = async ({siteId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface SitesGetRequestParams { + siteId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const sitesGet = async ({siteId,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: SitesGetRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/sites/{siteId}'.replace('{siteId}', siteId); @@ -388,7 +359,7 @@ const sitesGet = async ({siteId,parseOutput = true, overrideForCli = false, sdk }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('sites', 'get', siteId); } else { parse(response) @@ -398,35 +369,31 @@ const sitesGet = async ({siteId,parseOutput = true, overrideForCli = false, sdk return response; } -/** - * @typedef {Object} SitesUpdateRequestParams - * @property {string} siteId Site ID. - * @property {string} name Site name. Max length: 128 chars. - * @property {Framework} framework Sites framework. - * @property {boolean} enabled Is site enabled? When set to 'disabled', users cannot access the site but Server SDKs with and API key can still access the site. No data is lost when this is toggled. - * @property {boolean} logging When disabled, request logs will exclude logs and errors, and site responses will be slightly faster. - * @property {number} timeout Maximum request time in seconds. - * @property {string} installCommand Install Command. - * @property {string} buildCommand Build Command. - * @property {string} outputDirectory Output Directory for site. - * @property {BuildRuntime} buildRuntime Runtime to use during build step. - * @property {Adapter} adapter Framework adapter defining rendering strategy. Allowed values are: static, ssr - * @property {string} fallbackFile Fallback file for single page application sites. - * @property {string} installationId Appwrite Installation ID for VCS (Version Control System) deployment. - * @property {string} providerRepositoryId Repository ID of the repo linked to the site. - * @property {string} providerBranch Production branch for the repo linked to the site. - * @property {boolean} providerSilentMode Is the VCS (Version Control System) connection in silent mode for the repo linked to the site? In silent mode, comments will not be made on commits and pull requests. - * @property {string} providerRootDirectory Path to site code in the linked repo. - * @property {string} specification Framework specification for the site and builds. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {SitesUpdateRequestParams} params - */ -const sitesUpdate = async ({siteId,name,framework,enabled,logging,timeout,installCommand,buildCommand,outputDirectory,buildRuntime,adapter,fallbackFile,installationId,providerRepositoryId,providerBranch,providerSilentMode,providerRootDirectory,specification,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface SitesUpdateRequestParams { + siteId: string; + name: string; + framework: Framework; + enabled?: boolean; + logging?: boolean; + timeout?: number; + installCommand?: string; + buildCommand?: string; + outputDirectory?: string; + buildRuntime?: BuildRuntime; + adapter?: Adapter; + fallbackFile?: string; + installationId?: string; + providerRepositoryId?: string; + providerBranch?: string; + providerSilentMode?: boolean; + providerRootDirectory?: string; + specification?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const sitesUpdate = async ({siteId,name,framework,enabled,logging,timeout,installCommand,buildCommand,outputDirectory,buildRuntime,adapter,fallbackFile,installationId,providerRepositoryId,providerBranch,providerSilentMode,providerRootDirectory,specification,parseOutput = true, overrideForCli = false, sdk = undefined}: SitesUpdateRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/sites/{siteId}'.replace('{siteId}', siteId); @@ -496,18 +463,14 @@ const sitesUpdate = async ({siteId,name,framework,enabled,logging,timeout,instal return response; } -/** - * @typedef {Object} SitesDeleteRequestParams - * @property {string} siteId Site ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {SitesDeleteRequestParams} params - */ -const sitesDelete = async ({siteId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface SitesDeleteRequestParams { + siteId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const sitesDelete = async ({siteId,parseOutput = true, overrideForCli = false, sdk = undefined}: SitesDeleteRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/sites/{siteId}'.replace('{siteId}', siteId); @@ -526,19 +489,15 @@ const sitesDelete = async ({siteId,parseOutput = true, overrideForCli = false, s return response; } -/** - * @typedef {Object} SitesUpdateSiteDeploymentRequestParams - * @property {string} siteId Site ID. - * @property {string} deploymentId Deployment ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {SitesUpdateSiteDeploymentRequestParams} params - */ -const sitesUpdateSiteDeployment = async ({siteId,deploymentId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface SitesUpdateSiteDeploymentRequestParams { + siteId: string; + deploymentId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const sitesUpdateSiteDeployment = async ({siteId,deploymentId,parseOutput = true, overrideForCli = false, sdk = undefined}: SitesUpdateSiteDeploymentRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/sites/{siteId}/deployment'.replace('{siteId}', siteId); @@ -560,21 +519,18 @@ const sitesUpdateSiteDeployment = async ({siteId,deploymentId,parseOutput = true return response; } -/** - * @typedef {Object} SitesListDeploymentsRequestParams - * @property {string} siteId Site ID. - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: buildSize, sourceSize, totalSize, buildDuration, status, activate, type - * @property {string} search Search term to filter your list results. Max length: 256 chars. - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {SitesListDeploymentsRequestParams} params - */ -const sitesListDeployments = async ({siteId,queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface SitesListDeploymentsRequestParams { + siteId: string; + queries?: string[]; + search?: string; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const sitesListDeployments = async ({siteId,queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: SitesListDeploymentsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/sites/{siteId}/deployments'.replace('{siteId}', siteId); @@ -595,7 +551,7 @@ const sitesListDeployments = async ({siteId,queries,search,total,parseOutput = t }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('sites', 'listDeployments', siteId); } else { parse(response) @@ -605,24 +561,20 @@ const sitesListDeployments = async ({siteId,queries,search,total,parseOutput = t return response; } -/** - * @typedef {Object} SitesCreateDeploymentRequestParams - * @property {string} siteId Site ID. - * @property {string} code Gzip file with your code package. When used with the Appwrite CLI, pass the path to your code directory, and the CLI will automatically package your code. Use a path that is within the current directory. - * @property {boolean} activate Automatically activate the deployment when it is finished building. - * @property {string} installCommand Install Commands. - * @property {string} buildCommand Build Commands. - * @property {string} outputDirectory Output Directory. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - * @property {CallableFunction} onProgress - */ - -/** - * @param {SitesCreateDeploymentRequestParams} params - */ -const sitesCreateDeployment = async ({siteId,code,activate,installCommand,buildCommand,outputDirectory,parseOutput = true, overrideForCli = false, sdk = undefined,onProgress = () => {}}) => { +interface SitesCreateDeploymentRequestParams { + siteId: string; + code: string; + activate: boolean; + installCommand?: string; + buildCommand?: string; + outputDirectory?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + onProgress?: (progress: number) => void; +} + +export const sitesCreateDeployment = async ({siteId,code,activate,installCommand,buildCommand,outputDirectory,parseOutput = true, overrideForCli = false, sdk = undefined,onProgress = () => {}}: SitesCreateDeploymentRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/sites/{siteId}/deployments'.replace('{siteId}', siteId); @@ -773,19 +725,15 @@ const sitesCreateDeployment = async ({siteId,code,activate,installCommand,buildC return response; } -/** - * @typedef {Object} SitesCreateDuplicateDeploymentRequestParams - * @property {string} siteId Site ID. - * @property {string} deploymentId Deployment ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {SitesCreateDuplicateDeploymentRequestParams} params - */ -const sitesCreateDuplicateDeployment = async ({siteId,deploymentId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface SitesCreateDuplicateDeploymentRequestParams { + siteId: string; + deploymentId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const sitesCreateDuplicateDeployment = async ({siteId,deploymentId,parseOutput = true, overrideForCli = false, sdk = undefined}: SitesCreateDuplicateDeploymentRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/sites/{siteId}/deployments/duplicate'.replace('{siteId}', siteId); @@ -807,24 +755,20 @@ const sitesCreateDuplicateDeployment = async ({siteId,deploymentId,parseOutput = return response; } -/** - * @typedef {Object} SitesCreateTemplateDeploymentRequestParams - * @property {string} siteId Site ID. - * @property {string} repository Repository name of the template. - * @property {string} owner The name of the owner of the template. - * @property {string} rootDirectory Path to site code in the template repo. - * @property {TemplateReferenceType} type Type for the reference provided. Can be commit, branch, or tag - * @property {string} reference Reference value, can be a commit hash, branch name, or release tag - * @property {boolean} activate Automatically activate the deployment when it is finished building. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {SitesCreateTemplateDeploymentRequestParams} params - */ -const sitesCreateTemplateDeployment = async ({siteId,repository,owner,rootDirectory,type,reference,activate,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface SitesCreateTemplateDeploymentRequestParams { + siteId: string; + repository: string; + owner: string; + rootDirectory: string; + type: TemplateReferenceType; + reference: string; + activate?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const sitesCreateTemplateDeployment = async ({siteId,repository,owner,rootDirectory,type,reference,activate,parseOutput = true, overrideForCli = false, sdk = undefined}: SitesCreateTemplateDeploymentRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/sites/{siteId}/deployments/template'.replace('{siteId}', siteId); @@ -861,21 +805,17 @@ const sitesCreateTemplateDeployment = async ({siteId,repository,owner,rootDirect return response; } -/** - * @typedef {Object} SitesCreateVcsDeploymentRequestParams - * @property {string} siteId Site ID. - * @property {VCSReferenceType} type Type of reference passed. Allowed values are: branch, commit - * @property {string} reference VCS reference to create deployment from. Depending on type this can be: branch name, commit hash - * @property {boolean} activate Automatically activate the deployment when it is finished building. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {SitesCreateVcsDeploymentRequestParams} params - */ -const sitesCreateVcsDeployment = async ({siteId,type,reference,activate,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface SitesCreateVcsDeploymentRequestParams { + siteId: string; + type: VCSReferenceType; + reference: string; + activate?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const sitesCreateVcsDeployment = async ({siteId,type,reference,activate,parseOutput = true, overrideForCli = false, sdk = undefined}: SitesCreateVcsDeploymentRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/sites/{siteId}/deployments/vcs'.replace('{siteId}', siteId); @@ -903,19 +843,16 @@ const sitesCreateVcsDeployment = async ({siteId,type,reference,activate,parseOut return response; } -/** - * @typedef {Object} SitesGetDeploymentRequestParams - * @property {string} siteId Site ID. - * @property {string} deploymentId Deployment ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {SitesGetDeploymentRequestParams} params - */ -const sitesGetDeployment = async ({siteId,deploymentId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface SitesGetDeploymentRequestParams { + siteId: string; + deploymentId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const sitesGetDeployment = async ({siteId,deploymentId,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: SitesGetDeploymentRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/sites/{siteId}/deployments/{deploymentId}'.replace('{siteId}', siteId).replace('{deploymentId}', deploymentId); @@ -927,7 +864,7 @@ const sitesGetDeployment = async ({siteId,deploymentId,parseOutput = true, overr }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('sites', 'getDeployment', siteId, deploymentId); } else { parse(response) @@ -937,19 +874,15 @@ const sitesGetDeployment = async ({siteId,deploymentId,parseOutput = true, overr return response; } -/** - * @typedef {Object} SitesDeleteDeploymentRequestParams - * @property {string} siteId Site ID. - * @property {string} deploymentId Deployment ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {SitesDeleteDeploymentRequestParams} params - */ -const sitesDeleteDeployment = async ({siteId,deploymentId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface SitesDeleteDeploymentRequestParams { + siteId: string; + deploymentId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const sitesDeleteDeployment = async ({siteId,deploymentId,parseOutput = true, overrideForCli = false, sdk = undefined}: SitesDeleteDeploymentRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/sites/{siteId}/deployments/{deploymentId}'.replace('{siteId}', siteId).replace('{deploymentId}', deploymentId); @@ -968,21 +901,18 @@ const sitesDeleteDeployment = async ({siteId,deploymentId,parseOutput = true, ov return response; } -/** - * @typedef {Object} SitesGetDeploymentDownloadRequestParams - * @property {string} siteId Site ID. - * @property {string} deploymentId Deployment ID. - * @property {DeploymentDownloadType} type Deployment file to download. Can be: "source", "output". - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - * @property {string} destination - */ - -/** - * @param {SitesGetDeploymentDownloadRequestParams} params - */ -const sitesGetDeploymentDownload = async ({siteId,deploymentId,type,parseOutput = true, overrideForCli = false, sdk = undefined, destination, console}) => { +interface SitesGetDeploymentDownloadRequestParams { + siteId: string; + deploymentId: string; + type?: DeploymentDownloadType; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + destination?: string; + console?: boolean; +} + +export const sitesGetDeploymentDownload = async ({siteId,deploymentId,type,parseOutput = true, overrideForCli = false, sdk = undefined, destination, console: showConsole}: SitesGetDeploymentDownloadRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/sites/{siteId}/deployments/{deploymentId}/download'.replace('{siteId}', siteId).replace('{deploymentId}', deploymentId); @@ -1008,7 +938,7 @@ const sitesGetDeploymentDownload = async ({siteId,deploymentId,type,parseOutput fs.writeFileSync(destination, response); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('sites', 'getDeploymentDownload', siteId, deploymentId); } else { parse(response) @@ -1018,19 +948,15 @@ const sitesGetDeploymentDownload = async ({siteId,deploymentId,type,parseOutput return response; } -/** - * @typedef {Object} SitesUpdateDeploymentStatusRequestParams - * @property {string} siteId Site ID. - * @property {string} deploymentId Deployment ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {SitesUpdateDeploymentStatusRequestParams} params - */ -const sitesUpdateDeploymentStatus = async ({siteId,deploymentId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface SitesUpdateDeploymentStatusRequestParams { + siteId: string; + deploymentId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const sitesUpdateDeploymentStatus = async ({siteId,deploymentId,parseOutput = true, overrideForCli = false, sdk = undefined}: SitesUpdateDeploymentStatusRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/sites/{siteId}/deployments/{deploymentId}/status'.replace('{siteId}', siteId).replace('{deploymentId}', deploymentId); @@ -1049,20 +975,16 @@ const sitesUpdateDeploymentStatus = async ({siteId,deploymentId,parseOutput = tr return response; } -/** - * @typedef {Object} SitesListLogsRequestParams - * @property {string} siteId Site ID. - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: trigger, status, responseStatusCode, duration, requestMethod, requestPath, deploymentId - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {SitesListLogsRequestParams} params - */ -const sitesListLogs = async ({siteId,queries,total,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface SitesListLogsRequestParams { + siteId: string; + queries?: string[]; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const sitesListLogs = async ({siteId,queries,total,parseOutput = true, overrideForCli = false, sdk = undefined}: SitesListLogsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/sites/{siteId}/logs'.replace('{siteId}', siteId); @@ -1086,19 +1008,16 @@ const sitesListLogs = async ({siteId,queries,total,parseOutput = true, overrideF return response; } -/** - * @typedef {Object} SitesGetLogRequestParams - * @property {string} siteId Site ID. - * @property {string} logId Log ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {SitesGetLogRequestParams} params - */ -const sitesGetLog = async ({siteId,logId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface SitesGetLogRequestParams { + siteId: string; + logId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const sitesGetLog = async ({siteId,logId,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: SitesGetLogRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/sites/{siteId}/logs/{logId}'.replace('{siteId}', siteId).replace('{logId}', logId); @@ -1110,7 +1029,7 @@ const sitesGetLog = async ({siteId,logId,parseOutput = true, overrideForCli = fa }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('sites', 'getLog', siteId, logId); } else { parse(response) @@ -1120,19 +1039,15 @@ const sitesGetLog = async ({siteId,logId,parseOutput = true, overrideForCli = fa return response; } -/** - * @typedef {Object} SitesDeleteLogRequestParams - * @property {string} siteId Site ID. - * @property {string} logId Log ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {SitesDeleteLogRequestParams} params - */ -const sitesDeleteLog = async ({siteId,logId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface SitesDeleteLogRequestParams { + siteId: string; + logId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const sitesDeleteLog = async ({siteId,logId,parseOutput = true, overrideForCli = false, sdk = undefined}: SitesDeleteLogRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/sites/{siteId}/logs/{logId}'.replace('{siteId}', siteId).replace('{logId}', logId); @@ -1151,19 +1066,15 @@ const sitesDeleteLog = async ({siteId,logId,parseOutput = true, overrideForCli = return response; } -/** - * @typedef {Object} SitesGetUsageRequestParams - * @property {string} siteId Site ID. - * @property {UsageRange} range Date range. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {SitesGetUsageRequestParams} params - */ -const sitesGetUsage = async ({siteId,range,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface SitesGetUsageRequestParams { + siteId: string; + range?: UsageRange; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const sitesGetUsage = async ({siteId,range,parseOutput = true, overrideForCli = false, sdk = undefined}: SitesGetUsageRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/sites/{siteId}/usage'.replace('{siteId}', siteId); @@ -1184,18 +1095,14 @@ const sitesGetUsage = async ({siteId,range,parseOutput = true, overrideForCli = return response; } -/** - * @typedef {Object} SitesListVariablesRequestParams - * @property {string} siteId Site unique ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {SitesListVariablesRequestParams} params - */ -const sitesListVariables = async ({siteId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface SitesListVariablesRequestParams { + siteId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const sitesListVariables = async ({siteId,parseOutput = true, overrideForCli = false, sdk = undefined}: SitesListVariablesRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/sites/{siteId}/variables'.replace('{siteId}', siteId); @@ -1213,21 +1120,17 @@ const sitesListVariables = async ({siteId,parseOutput = true, overrideForCli = f return response; } -/** - * @typedef {Object} SitesCreateVariableRequestParams - * @property {string} siteId Site unique ID. - * @property {string} key Variable key. Max length: 255 chars. - * @property {string} value Variable value. Max length: 8192 chars. - * @property {boolean} secret Secret variables can be updated or deleted, but only sites can read them during build and runtime. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {SitesCreateVariableRequestParams} params - */ -const sitesCreateVariable = async ({siteId,key,value,secret,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface SitesCreateVariableRequestParams { + siteId: string; + key: string; + value: string; + secret?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const sitesCreateVariable = async ({siteId,key,value,secret,parseOutput = true, overrideForCli = false, sdk = undefined}: SitesCreateVariableRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/sites/{siteId}/variables'.replace('{siteId}', siteId); @@ -1255,19 +1158,15 @@ const sitesCreateVariable = async ({siteId,key,value,secret,parseOutput = true, return response; } -/** - * @typedef {Object} SitesGetVariableRequestParams - * @property {string} siteId Site unique ID. - * @property {string} variableId Variable unique ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {SitesGetVariableRequestParams} params - */ -const sitesGetVariable = async ({siteId,variableId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface SitesGetVariableRequestParams { + siteId: string; + variableId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const sitesGetVariable = async ({siteId,variableId,parseOutput = true, overrideForCli = false, sdk = undefined}: SitesGetVariableRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/sites/{siteId}/variables/{variableId}'.replace('{siteId}', siteId).replace('{variableId}', variableId); @@ -1285,22 +1184,18 @@ const sitesGetVariable = async ({siteId,variableId,parseOutput = true, overrideF return response; } -/** - * @typedef {Object} SitesUpdateVariableRequestParams - * @property {string} siteId Site unique ID. - * @property {string} variableId Variable unique ID. - * @property {string} key Variable key. Max length: 255 chars. - * @property {string} value Variable value. Max length: 8192 chars. - * @property {boolean} secret Secret variables can be updated or deleted, but only sites can read them during build and runtime. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {SitesUpdateVariableRequestParams} params - */ -const sitesUpdateVariable = async ({siteId,variableId,key,value,secret,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface SitesUpdateVariableRequestParams { + siteId: string; + variableId: string; + key: string; + value?: string; + secret?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const sitesUpdateVariable = async ({siteId,variableId,key,value,secret,parseOutput = true, overrideForCli = false, sdk = undefined}: SitesUpdateVariableRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/sites/{siteId}/variables/{variableId}'.replace('{siteId}', siteId).replace('{variableId}', variableId); @@ -1328,19 +1223,15 @@ const sitesUpdateVariable = async ({siteId,variableId,key,value,secret,parseOutp return response; } -/** - * @typedef {Object} SitesDeleteVariableRequestParams - * @property {string} siteId Site unique ID. - * @property {string} variableId Variable unique ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {SitesDeleteVariableRequestParams} params - */ -const sitesDeleteVariable = async ({siteId,variableId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface SitesDeleteVariableRequestParams { + siteId: string; + variableId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const sitesDeleteVariable = async ({siteId,variableId,parseOutput = true, overrideForCli = false, sdk = undefined}: SitesDeleteVariableRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/sites/{siteId}/variables/{variableId}'.replace('{siteId}', siteId).replace('{variableId}', variableId); @@ -1364,7 +1255,7 @@ sites .description(`Get a list of all the project's sites. You can use the query params to filter your results.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name, enabled, framework, deploymentId, buildCommand, installCommand, outputDirectory, installationId`) .option(`--search `, `Search term to filter your list results. Max length: 256 chars.`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--console`, `Get the resource console url`) .action(actionRunner(sitesList)) @@ -1375,8 +1266,8 @@ sites .requiredOption(`--name `, `Site name. Max length: 128 chars.`) .requiredOption(`--framework `, `Sites framework.`) .requiredOption(`--build-runtime `, `Runtime to use during build step.`) - .option(`--enabled [value]`, `Is site enabled? When set to 'disabled', users cannot access the site but Server SDKs with and API key can still access the site. No data is lost when this is toggled.`, (value) => value === undefined ? true : parseBool(value)) - .option(`--logging [value]`, `When disabled, request logs will exclude logs and errors, and site responses will be slightly faster.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Is site enabled? When set to 'disabled', users cannot access the site but Server SDKs with and API key can still access the site. No data is lost when this is toggled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--logging [value]`, `When disabled, request logs will exclude logs and errors, and site responses will be slightly faster.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--timeout `, `Maximum request time in seconds.`, parseInteger) .option(`--install-command `, `Install Command.`) .option(`--build-command `, `Build Command.`) @@ -1386,7 +1277,7 @@ sites .option(`--fallback-file `, `Fallback file for single page application sites.`) .option(`--provider-repository-id `, `Repository ID of the repo linked to the site.`) .option(`--provider-branch `, `Production branch for the repo linked to the site.`) - .option(`--provider-silent-mode [value]`, `Is the VCS (Version Control System) connection in silent mode for the repo linked to the site? In silent mode, comments will not be made on commits and pull requests.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--provider-silent-mode [value]`, `Is the VCS (Version Control System) connection in silent mode for the repo linked to the site? In silent mode, comments will not be made on commits and pull requests.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--provider-root-directory `, `Path to site code in the linked repo.`) .option(`--specification `, `Framework specification for the site and builds.`) .action(actionRunner(sitesCreate)) @@ -1440,8 +1331,8 @@ sites .requiredOption(`--site-id `, `Site ID.`) .requiredOption(`--name `, `Site name. Max length: 128 chars.`) .requiredOption(`--framework `, `Sites framework.`) - .option(`--enabled [value]`, `Is site enabled? When set to 'disabled', users cannot access the site but Server SDKs with and API key can still access the site. No data is lost when this is toggled.`, (value) => value === undefined ? true : parseBool(value)) - .option(`--logging [value]`, `When disabled, request logs will exclude logs and errors, and site responses will be slightly faster.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Is site enabled? When set to 'disabled', users cannot access the site but Server SDKs with and API key can still access the site. No data is lost when this is toggled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--logging [value]`, `When disabled, request logs will exclude logs and errors, and site responses will be slightly faster.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--timeout `, `Maximum request time in seconds.`, parseInteger) .option(`--install-command `, `Install Command.`) .option(`--build-command `, `Build Command.`) @@ -1452,7 +1343,7 @@ sites .option(`--installation-id `, `Appwrite Installation ID for VCS (Version Control System) deployment.`) .option(`--provider-repository-id `, `Repository ID of the repo linked to the site.`) .option(`--provider-branch `, `Production branch for the repo linked to the site.`) - .option(`--provider-silent-mode [value]`, `Is the VCS (Version Control System) connection in silent mode for the repo linked to the site? In silent mode, comments will not be made on commits and pull requests.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--provider-silent-mode [value]`, `Is the VCS (Version Control System) connection in silent mode for the repo linked to the site? In silent mode, comments will not be made on commits and pull requests.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--provider-root-directory `, `Path to site code in the linked repo.`) .option(`--specification `, `Framework specification for the site and builds.`) .action(actionRunner(sitesUpdate)) @@ -1476,7 +1367,7 @@ sites .requiredOption(`--site-id `, `Site ID.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: buildSize, sourceSize, totalSize, buildDuration, status, activate, type`) .option(`--search `, `Search term to filter your list results. Max length: 256 chars.`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--console`, `Get the resource console url`) .action(actionRunner(sitesListDeployments)) @@ -1485,7 +1376,7 @@ sites .description(`Create a new site code deployment. Use this endpoint to upload a new version of your site code. To activate your newly uploaded code, you'll need to update the site's deployment to use your new deployment ID.`) .requiredOption(`--site-id `, `Site ID.`) .requiredOption(`--code `, `Gzip file with your code package. When used with the Appwrite CLI, pass the path to your code directory, and the CLI will automatically package your code. Use a path that is within the current directory.`) - .requiredOption(`--activate [value]`, `Automatically activate the deployment when it is finished building.`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--activate [value]`, `Automatically activate the deployment when it is finished building.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--install-command `, `Install Commands.`) .option(`--build-command `, `Build Commands.`) .option(`--output-directory `, `Output Directory.`) @@ -1507,7 +1398,7 @@ sites .requiredOption(`--root-directory `, `Path to site code in the template repo.`) .requiredOption(`--type `, `Type for the reference provided. Can be commit, branch, or tag`) .requiredOption(`--reference `, `Reference value, can be a commit hash, branch name, or release tag`) - .option(`--activate [value]`, `Automatically activate the deployment when it is finished building.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--activate [value]`, `Automatically activate the deployment when it is finished building.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(sitesCreateTemplateDeployment)) sites @@ -1516,7 +1407,7 @@ sites .requiredOption(`--site-id `, `Site ID.`) .requiredOption(`--type `, `Type of reference passed. Allowed values are: branch, commit`) .requiredOption(`--reference `, `VCS reference to create deployment from. Depending on type this can be: branch name, commit hash`) - .option(`--activate [value]`, `Automatically activate the deployment when it is finished building.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--activate [value]`, `Automatically activate the deployment when it is finished building.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(sitesCreateVcsDeployment)) sites @@ -1556,7 +1447,7 @@ sites .description(`Get a list of all site logs. You can use the query params to filter your results.`) .requiredOption(`--site-id `, `Site ID.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: trigger, status, responseStatusCode, duration, requestMethod, requestPath, deploymentId`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(sitesListLogs)) sites @@ -1593,7 +1484,7 @@ sites .requiredOption(`--site-id `, `Site unique ID.`) .requiredOption(`--key `, `Variable key. Max length: 255 chars.`) .requiredOption(`--value `, `Variable value. Max length: 8192 chars.`) - .option(`--secret [value]`, `Secret variables can be updated or deleted, but only sites can read them during build and runtime.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--secret [value]`, `Secret variables can be updated or deleted, but only sites can read them during build and runtime.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(sitesCreateVariable)) sites @@ -1610,7 +1501,7 @@ sites .requiredOption(`--variable-id `, `Variable unique ID.`) .requiredOption(`--key `, `Variable key. Max length: 255 chars.`) .option(`--value `, `Variable value. Max length: 8192 chars.`) - .option(`--secret [value]`, `Secret variables can be updated or deleted, but only sites can read them during build and runtime.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--secret [value]`, `Secret variables can be updated or deleted, but only sites can read them during build and runtime.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(sitesUpdateVariable)) sites @@ -1620,35 +1511,4 @@ sites .requiredOption(`--variable-id `, `Variable unique ID.`) .action(actionRunner(sitesDeleteVariable)) -module.exports = { - sites, - sitesList, - sitesCreate, - sitesListFrameworks, - sitesListSpecifications, - sitesListTemplates, - sitesGetTemplate, - sitesListUsage, - sitesGet, - sitesUpdate, - sitesDelete, - sitesUpdateSiteDeployment, - sitesListDeployments, - sitesCreateDeployment, - sitesCreateDuplicateDeployment, - sitesCreateTemplateDeployment, - sitesCreateVcsDeployment, - sitesGetDeployment, - sitesDeleteDeployment, - sitesGetDeploymentDownload, - sitesUpdateDeploymentStatus, - sitesListLogs, - sitesGetLog, - sitesDeleteLog, - sitesGetUsage, - sitesListVariables, - sitesCreateVariable, - sitesGetVariable, - sitesUpdateVariable, - sitesDeleteVariable -}; + diff --git a/lib/commands/storage.js b/lib/commands/storage.ts similarity index 63% rename from lib/commands/storage.js rename to lib/commands/storage.ts index c951e7a0..a39f4919 100644 --- a/lib/commands/storage.js +++ b/lib/commands/storage.ts @@ -1,31 +1,27 @@ -const fs = require('fs'); -const pathLib = require('path'); -const tar = require("tar"); -const ignore = require("ignore"); -const { promisify } = require('util'); -const libClient = require('../client.js'); -const { getAllFiles, showConsoleLink } = require('../utils.js'); -const { Command } = require('commander'); -const { sdkForProject, sdkForConsole } = require('../sdks') -const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } = require('../parser') -const { localConfig, globalConfig } = require("../config"); -const { File } = require('undici'); -const { ReadableStream } = require('stream/web'); - -/** - * @param {fs.ReadStream} readStream - * @returns {ReadableStream} - */ -function convertReadStreamToReadableStream(readStream) { +import fs = require('fs'); +import pathLib = require('path'); +import tar = require('tar'); +import ignore = require('ignore'); +import { promisify } from 'util'; +import Client from '../client'; +import { getAllFiles, showConsoleLink } from '../utils'; +import { Command } from 'commander'; +import { sdkForProject, sdkForConsole } from '../sdks'; +import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } from '../parser'; +import { localConfig, globalConfig } from '../config'; +import { File } from 'undici'; +import { ReadableStream } from 'stream/web'; + +function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ start(controller) { - readStream.on("data", (chunk) => { + readStream.on("data", (chunk: Buffer) => { controller.enqueue(chunk); }); readStream.on("end", () => { controller.close(); }); - readStream.on("error", (err) => { + readStream.on("error", (err: Error) => { controller.error(err); }); }, @@ -35,24 +31,21 @@ function convertReadStreamToReadableStream(readStream) { }); } -const storage = new Command("storage").description(commandDescriptions['storage'] ?? '').configureHelp({ +export const storage = new Command("storage").description(commandDescriptions['storage'] ?? '').configureHelp({ helpWidth: process.stdout.columns || 80 }) -/** - * @typedef {Object} StorageListBucketsRequestParams - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: enabled, name, fileSecurity, maximumFileSize, encryption, antivirus, transformations - * @property {string} search Search term to filter your list results. Max length: 256 chars. - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {StorageListBucketsRequestParams} params - */ -const storageListBuckets = async ({queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface StorageListBucketsRequestParams { + queries?: string[]; + search?: string; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const storageListBuckets = async ({queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: StorageListBucketsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/storage/buckets'; @@ -73,7 +66,7 @@ const storageListBuckets = async ({queries,search,total,parseOutput = true, over }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('storage', 'listBuckets'); } else { parse(response) @@ -83,28 +76,24 @@ const storageListBuckets = async ({queries,search,total,parseOutput = true, over return response; } -/** - * @typedef {Object} StorageCreateBucketRequestParams - * @property {string} bucketId Unique Id. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} name Bucket name - * @property {string[]} permissions An array of permission strings. By default, no user is granted with any permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - * @property {boolean} fileSecurity Enables configuring permissions for individual file. A user needs one of file or bucket level permissions to access a file. [Learn more about permissions](https://appwrite.io/docs/permissions). - * @property {boolean} enabled Is bucket enabled? When set to 'disabled', users cannot access the files in this bucket but Server SDKs with and API key can still access the bucket. No files are lost when this is toggled. - * @property {number} maximumFileSize Maximum file size allowed in bytes. Maximum allowed value is 30MB. - * @property {string[]} allowedFileExtensions Allowed file extensions. Maximum of 100 extensions are allowed, each 64 characters long. - * @property {Compression} compression Compression algorithm choosen for compression. Can be one of none, [gzip](https://en.wikipedia.org/wiki/Gzip), or [zstd](https://en.wikipedia.org/wiki/Zstd), For file size above 20MB compression is skipped even if it's enabled - * @property {boolean} encryption Is encryption enabled? For file size above 20MB encryption is skipped even if it's enabled - * @property {boolean} antivirus Is virus scanning enabled? For file size above 20MB AntiVirus scanning is skipped even if it's enabled - * @property {boolean} transformations Are image transformations enabled? - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {StorageCreateBucketRequestParams} params - */ -const storageCreateBucket = async ({bucketId,name,permissions,fileSecurity,enabled,maximumFileSize,allowedFileExtensions,compression,encryption,antivirus,transformations,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface StorageCreateBucketRequestParams { + bucketId: string; + name: string; + permissions?: string[]; + fileSecurity?: boolean; + enabled?: boolean; + maximumFileSize?: number; + allowedFileExtensions?: string[]; + compression?: Compression; + encryption?: boolean; + antivirus?: boolean; + transformations?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const storageCreateBucket = async ({bucketId,name,permissions,fileSecurity,enabled,maximumFileSize,allowedFileExtensions,compression,encryption,antivirus,transformations,parseOutput = true, overrideForCli = false, sdk = undefined}: StorageCreateBucketRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/storage/buckets'; @@ -158,18 +147,15 @@ const storageCreateBucket = async ({bucketId,name,permissions,fileSecurity,enabl return response; } -/** - * @typedef {Object} StorageGetBucketRequestParams - * @property {string} bucketId Bucket unique ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {StorageGetBucketRequestParams} params - */ -const storageGetBucket = async ({bucketId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface StorageGetBucketRequestParams { + bucketId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const storageGetBucket = async ({bucketId,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: StorageGetBucketRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/storage/buckets/{bucketId}'.replace('{bucketId}', bucketId); @@ -181,7 +167,7 @@ const storageGetBucket = async ({bucketId,parseOutput = true, overrideForCli = f }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('storage', 'getBucket', bucketId); } else { parse(response) @@ -191,28 +177,24 @@ const storageGetBucket = async ({bucketId,parseOutput = true, overrideForCli = f return response; } -/** - * @typedef {Object} StorageUpdateBucketRequestParams - * @property {string} bucketId Bucket unique ID. - * @property {string} name Bucket name - * @property {string[]} permissions An array of permission strings. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions). - * @property {boolean} fileSecurity Enables configuring permissions for individual file. A user needs one of file or bucket level permissions to access a file. [Learn more about permissions](https://appwrite.io/docs/permissions). - * @property {boolean} enabled Is bucket enabled? When set to 'disabled', users cannot access the files in this bucket but Server SDKs with and API key can still access the bucket. No files are lost when this is toggled. - * @property {number} maximumFileSize Maximum file size allowed in bytes. Maximum allowed value is 30MB. - * @property {string[]} allowedFileExtensions Allowed file extensions. Maximum of 100 extensions are allowed, each 64 characters long. - * @property {Compression} compression Compression algorithm choosen for compression. Can be one of none, [gzip](https://en.wikipedia.org/wiki/Gzip), or [zstd](https://en.wikipedia.org/wiki/Zstd), For file size above 20MB compression is skipped even if it's enabled - * @property {boolean} encryption Is encryption enabled? For file size above 20MB encryption is skipped even if it's enabled - * @property {boolean} antivirus Is virus scanning enabled? For file size above 20MB AntiVirus scanning is skipped even if it's enabled - * @property {boolean} transformations Are image transformations enabled? - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {StorageUpdateBucketRequestParams} params - */ -const storageUpdateBucket = async ({bucketId,name,permissions,fileSecurity,enabled,maximumFileSize,allowedFileExtensions,compression,encryption,antivirus,transformations,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface StorageUpdateBucketRequestParams { + bucketId: string; + name: string; + permissions?: string[]; + fileSecurity?: boolean; + enabled?: boolean; + maximumFileSize?: number; + allowedFileExtensions?: string[]; + compression?: Compression; + encryption?: boolean; + antivirus?: boolean; + transformations?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const storageUpdateBucket = async ({bucketId,name,permissions,fileSecurity,enabled,maximumFileSize,allowedFileExtensions,compression,encryption,antivirus,transformations,parseOutput = true, overrideForCli = false, sdk = undefined}: StorageUpdateBucketRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/storage/buckets/{bucketId}'.replace('{bucketId}', bucketId); @@ -263,18 +245,14 @@ const storageUpdateBucket = async ({bucketId,name,permissions,fileSecurity,enabl return response; } -/** - * @typedef {Object} StorageDeleteBucketRequestParams - * @property {string} bucketId Bucket unique ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {StorageDeleteBucketRequestParams} params - */ -const storageDeleteBucket = async ({bucketId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface StorageDeleteBucketRequestParams { + bucketId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const storageDeleteBucket = async ({bucketId,parseOutput = true, overrideForCli = false, sdk = undefined}: StorageDeleteBucketRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/storage/buckets/{bucketId}'.replace('{bucketId}', bucketId); @@ -293,21 +271,18 @@ const storageDeleteBucket = async ({bucketId,parseOutput = true, overrideForCli return response; } -/** - * @typedef {Object} StorageListFilesRequestParams - * @property {string} bucketId Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name, signature, mimeType, sizeOriginal, chunksTotal, chunksUploaded - * @property {string} search Search term to filter your list results. Max length: 256 chars. - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {StorageListFilesRequestParams} params - */ -const storageListFiles = async ({bucketId,queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface StorageListFilesRequestParams { + bucketId: string; + queries?: string[]; + search?: string; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const storageListFiles = async ({bucketId,queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: StorageListFilesRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/storage/buckets/{bucketId}/files'.replace('{bucketId}', bucketId); @@ -328,7 +303,7 @@ const storageListFiles = async ({bucketId,queries,search,total,parseOutput = tru }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('storage', 'listFiles', bucketId); } else { parse(response) @@ -338,22 +313,18 @@ const storageListFiles = async ({bucketId,queries,search,total,parseOutput = tru return response; } -/** - * @typedef {Object} StorageCreateFileRequestParams - * @property {string} bucketId Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). - * @property {string} fileId File ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} file Binary file. Appwrite SDKs provide helpers to handle file input. [Learn about file input](https://appwrite.io/docs/products/storage/upload-download#input-file). - * @property {string[]} permissions An array of permission strings. By default, only the current user is granted all permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - * @property {CallableFunction} onProgress - */ - -/** - * @param {StorageCreateFileRequestParams} params - */ -const storageCreateFile = async ({bucketId,fileId,file,permissions,parseOutput = true, overrideForCli = false, sdk = undefined,onProgress = () => {}}) => { +interface StorageCreateFileRequestParams { + bucketId: string; + fileId: string; + file: string; + permissions?: string[]; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + onProgress?: (progress: number) => void; +} + +export const storageCreateFile = async ({bucketId,fileId,file,permissions,parseOutput = true, overrideForCli = false, sdk = undefined,onProgress = () => {}}: StorageCreateFileRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/storage/buckets/{bucketId}/files'.replace('{bucketId}', bucketId); @@ -470,19 +441,16 @@ const storageCreateFile = async ({bucketId,fileId,file,permissions,parseOutput = return response; } -/** - * @typedef {Object} StorageGetFileRequestParams - * @property {string} bucketId Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). - * @property {string} fileId File ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {StorageGetFileRequestParams} params - */ -const storageGetFile = async ({bucketId,fileId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface StorageGetFileRequestParams { + bucketId: string; + fileId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const storageGetFile = async ({bucketId,fileId,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: StorageGetFileRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replace('{bucketId}', bucketId).replace('{fileId}', fileId); @@ -494,7 +462,7 @@ const storageGetFile = async ({bucketId,fileId,parseOutput = true, overrideForCl }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('storage', 'getFile', bucketId, fileId); } else { parse(response) @@ -504,21 +472,17 @@ const storageGetFile = async ({bucketId,fileId,parseOutput = true, overrideForCl return response; } -/** - * @typedef {Object} StorageUpdateFileRequestParams - * @property {string} bucketId Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). - * @property {string} fileId File unique ID. - * @property {string} name Name of the file - * @property {string[]} permissions An array of permission string. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions). - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {StorageUpdateFileRequestParams} params - */ -const storageUpdateFile = async ({bucketId,fileId,name,permissions,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface StorageUpdateFileRequestParams { + bucketId: string; + fileId: string; + name?: string; + permissions?: string[]; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const storageUpdateFile = async ({bucketId,fileId,name,permissions,parseOutput = true, overrideForCli = false, sdk = undefined}: StorageUpdateFileRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replace('{bucketId}', bucketId).replace('{fileId}', fileId); @@ -544,19 +508,15 @@ const storageUpdateFile = async ({bucketId,fileId,name,permissions,parseOutput = return response; } -/** - * @typedef {Object} StorageDeleteFileRequestParams - * @property {string} bucketId Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). - * @property {string} fileId File ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {StorageDeleteFileRequestParams} params - */ -const storageDeleteFile = async ({bucketId,fileId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface StorageDeleteFileRequestParams { + bucketId: string; + fileId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const storageDeleteFile = async ({bucketId,fileId,parseOutput = true, overrideForCli = false, sdk = undefined}: StorageDeleteFileRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replace('{bucketId}', bucketId).replace('{fileId}', fileId); @@ -575,21 +535,17 @@ const storageDeleteFile = async ({bucketId,fileId,parseOutput = true, overrideFo return response; } -/** - * @typedef {Object} StorageGetFileDownloadRequestParams - * @property {string} bucketId Storage bucket ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). - * @property {string} fileId File ID. - * @property {string} token File token for accessing this file. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - * @property {string} destination - */ - -/** - * @param {StorageGetFileDownloadRequestParams} params - */ -const storageGetFileDownload = async ({bucketId,fileId,token,parseOutput = true, overrideForCli = false, sdk = undefined, destination}) => { +interface StorageGetFileDownloadRequestParams { + bucketId: string; + fileId: string; + token?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + destination?: string; +} + +export const storageGetFileDownload = async ({bucketId,fileId,token,parseOutput = true, overrideForCli = false, sdk = undefined, destination}: StorageGetFileDownloadRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replace('{bucketId}', bucketId).replace('{fileId}', fileId); @@ -621,32 +577,28 @@ const storageGetFileDownload = async ({bucketId,fileId,token,parseOutput = true, return response; } -/** - * @typedef {Object} StorageGetFilePreviewRequestParams - * @property {string} bucketId Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). - * @property {string} fileId File ID - * @property {number} width Resize preview image width, Pass an integer between 0 to 4000. - * @property {number} height Resize preview image height, Pass an integer between 0 to 4000. - * @property {ImageGravity} gravity Image crop gravity. Can be one of center,top-left,top,top-right,left,right,bottom-left,bottom,bottom-right - * @property {number} quality Preview image quality. Pass an integer between 0 to 100. Defaults to keep existing image quality. - * @property {number} borderWidth Preview image border in pixels. Pass an integer between 0 to 100. Defaults to 0. - * @property {string} borderColor Preview image border color. Use a valid HEX color, no # is needed for prefix. - * @property {number} borderRadius Preview image border radius in pixels. Pass an integer between 0 to 4000. - * @property {number} opacity Preview image opacity. Only works with images having an alpha channel (like png). Pass a number between 0 to 1. - * @property {number} rotation Preview image rotation in degrees. Pass an integer between -360 and 360. - * @property {string} background Preview image background color. Only works with transparent images (png). Use a valid HEX color, no # is needed for prefix. - * @property {ImageFormat} output Output format type (jpeg, jpg, png, gif and webp). - * @property {string} token File token for accessing this file. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - * @property {string} destination - */ - -/** - * @param {StorageGetFilePreviewRequestParams} params - */ -const storageGetFilePreview = async ({bucketId,fileId,width,height,gravity,quality,borderWidth,borderColor,borderRadius,opacity,rotation,background,output,token,parseOutput = true, overrideForCli = false, sdk = undefined, destination}) => { +interface StorageGetFilePreviewRequestParams { + bucketId: string; + fileId: string; + width?: number; + height?: number; + gravity?: ImageGravity; + quality?: number; + borderWidth?: number; + borderColor?: string; + borderRadius?: number; + opacity?: number; + rotation?: number; + background?: string; + output?: ImageFormat; + token?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + destination?: string; +} + +export const storageGetFilePreview = async ({bucketId,fileId,width,height,gravity,quality,borderWidth,borderColor,borderRadius,opacity,rotation,background,output,token,parseOutput = true, overrideForCli = false, sdk = undefined, destination}: StorageGetFilePreviewRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replace('{bucketId}', bucketId).replace('{fileId}', fileId); @@ -711,21 +663,17 @@ const storageGetFilePreview = async ({bucketId,fileId,width,height,gravity,quali return response; } -/** - * @typedef {Object} StorageGetFileViewRequestParams - * @property {string} bucketId Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). - * @property {string} fileId File ID. - * @property {string} token File token for accessing this file. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - * @property {string} destination - */ - -/** - * @param {StorageGetFileViewRequestParams} params - */ -const storageGetFileView = async ({bucketId,fileId,token,parseOutput = true, overrideForCli = false, sdk = undefined, destination}) => { +interface StorageGetFileViewRequestParams { + bucketId: string; + fileId: string; + token?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + destination?: string; +} + +export const storageGetFileView = async ({bucketId,fileId,token,parseOutput = true, overrideForCli = false, sdk = undefined, destination}: StorageGetFileViewRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replace('{bucketId}', bucketId).replace('{fileId}', fileId); @@ -757,18 +705,14 @@ const storageGetFileView = async ({bucketId,fileId,token,parseOutput = true, ove return response; } -/** - * @typedef {Object} StorageGetUsageRequestParams - * @property {UsageRange} range Date range. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {StorageGetUsageRequestParams} params - */ -const storageGetUsage = async ({range,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface StorageGetUsageRequestParams { + range?: UsageRange; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const storageGetUsage = async ({range,parseOutput = true, overrideForCli = false, sdk = undefined}: StorageGetUsageRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/storage/usage'; @@ -789,19 +733,16 @@ const storageGetUsage = async ({range,parseOutput = true, overrideForCli = false return response; } -/** - * @typedef {Object} StorageGetBucketUsageRequestParams - * @property {string} bucketId Bucket ID. - * @property {UsageRange} range Date range. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {StorageGetBucketUsageRequestParams} params - */ -const storageGetBucketUsage = async ({bucketId,range,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface StorageGetBucketUsageRequestParams { + bucketId: string; + range?: UsageRange; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const storageGetBucketUsage = async ({bucketId,range,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: StorageGetBucketUsageRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/storage/{bucketId}/usage'.replace('{bucketId}', bucketId); @@ -816,7 +757,7 @@ const storageGetBucketUsage = async ({bucketId,range,parseOutput = true, overrid }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('storage', 'getBucketUsage', bucketId); } else { parse(response) @@ -831,7 +772,7 @@ storage .description(`Get a list of all the storage buckets. You can use the query params to filter your results.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: enabled, name, fileSecurity, maximumFileSize, encryption, antivirus, transformations`) .option(`--search `, `Search term to filter your list results. Max length: 256 chars.`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--console`, `Get the resource console url`) .action(actionRunner(storageListBuckets)) @@ -841,14 +782,14 @@ storage .requiredOption(`--bucket-id `, `Unique Id. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars.`) .requiredOption(`--name `, `Bucket name`) .option(`--permissions [permissions...]`, `An array of permission strings. By default, no user is granted with any permissions. [Learn more about permissions](https://appwrite.io/docs/permissions).`) - .option(`--file-security [value]`, `Enables configuring permissions for individual file. A user needs one of file or bucket level permissions to access a file. [Learn more about permissions](https://appwrite.io/docs/permissions).`, (value) => value === undefined ? true : parseBool(value)) - .option(`--enabled [value]`, `Is bucket enabled? When set to 'disabled', users cannot access the files in this bucket but Server SDKs with and API key can still access the bucket. No files are lost when this is toggled.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--file-security [value]`, `Enables configuring permissions for individual file. A user needs one of file or bucket level permissions to access a file. [Learn more about permissions](https://appwrite.io/docs/permissions).`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Is bucket enabled? When set to 'disabled', users cannot access the files in this bucket but Server SDKs with and API key can still access the bucket. No files are lost when this is toggled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--maximum-file-size `, `Maximum file size allowed in bytes. Maximum allowed value is 30MB.`, parseInteger) .option(`--allowed-file-extensions [allowed-file-extensions...]`, `Allowed file extensions. Maximum of 100 extensions are allowed, each 64 characters long.`) .option(`--compression `, `Compression algorithm choosen for compression. Can be one of none, [gzip](https://en.wikipedia.org/wiki/Gzip), or [zstd](https://en.wikipedia.org/wiki/Zstd), For file size above 20MB compression is skipped even if it's enabled`) - .option(`--encryption [value]`, `Is encryption enabled? For file size above 20MB encryption is skipped even if it's enabled`, (value) => value === undefined ? true : parseBool(value)) - .option(`--antivirus [value]`, `Is virus scanning enabled? For file size above 20MB AntiVirus scanning is skipped even if it's enabled`, (value) => value === undefined ? true : parseBool(value)) - .option(`--transformations [value]`, `Are image transformations enabled?`, (value) => value === undefined ? true : parseBool(value)) + .option(`--encryption [value]`, `Is encryption enabled? For file size above 20MB encryption is skipped even if it's enabled`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--antivirus [value]`, `Is virus scanning enabled? For file size above 20MB AntiVirus scanning is skipped even if it's enabled`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--transformations [value]`, `Are image transformations enabled?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(storageCreateBucket)) storage @@ -864,14 +805,14 @@ storage .requiredOption(`--bucket-id `, `Bucket unique ID.`) .requiredOption(`--name `, `Bucket name`) .option(`--permissions [permissions...]`, `An array of permission strings. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions).`) - .option(`--file-security [value]`, `Enables configuring permissions for individual file. A user needs one of file or bucket level permissions to access a file. [Learn more about permissions](https://appwrite.io/docs/permissions).`, (value) => value === undefined ? true : parseBool(value)) - .option(`--enabled [value]`, `Is bucket enabled? When set to 'disabled', users cannot access the files in this bucket but Server SDKs with and API key can still access the bucket. No files are lost when this is toggled.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--file-security [value]`, `Enables configuring permissions for individual file. A user needs one of file or bucket level permissions to access a file. [Learn more about permissions](https://appwrite.io/docs/permissions).`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Is bucket enabled? When set to 'disabled', users cannot access the files in this bucket but Server SDKs with and API key can still access the bucket. No files are lost when this is toggled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--maximum-file-size `, `Maximum file size allowed in bytes. Maximum allowed value is 30MB.`, parseInteger) .option(`--allowed-file-extensions [allowed-file-extensions...]`, `Allowed file extensions. Maximum of 100 extensions are allowed, each 64 characters long.`) .option(`--compression `, `Compression algorithm choosen for compression. Can be one of none, [gzip](https://en.wikipedia.org/wiki/Gzip), or [zstd](https://en.wikipedia.org/wiki/Zstd), For file size above 20MB compression is skipped even if it's enabled`) - .option(`--encryption [value]`, `Is encryption enabled? For file size above 20MB encryption is skipped even if it's enabled`, (value) => value === undefined ? true : parseBool(value)) - .option(`--antivirus [value]`, `Is virus scanning enabled? For file size above 20MB AntiVirus scanning is skipped even if it's enabled`, (value) => value === undefined ? true : parseBool(value)) - .option(`--transformations [value]`, `Are image transformations enabled?`, (value) => value === undefined ? true : parseBool(value)) + .option(`--encryption [value]`, `Is encryption enabled? For file size above 20MB encryption is skipped even if it's enabled`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--antivirus [value]`, `Is virus scanning enabled? For file size above 20MB AntiVirus scanning is skipped even if it's enabled`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--transformations [value]`, `Are image transformations enabled?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(storageUpdateBucket)) storage @@ -886,7 +827,7 @@ storage .requiredOption(`--bucket-id `, `Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket).`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name, signature, mimeType, sizeOriginal, chunksTotal, chunksUploaded`) .option(`--search `, `Search term to filter your list results. Max length: 256 chars.`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--console`, `Get the resource console url`) .action(actionRunner(storageListFiles)) @@ -975,21 +916,4 @@ storage .option(`--console`, `Get the resource console url`) .action(actionRunner(storageGetBucketUsage)) -module.exports = { - storage, - storageListBuckets, - storageCreateBucket, - storageGetBucket, - storageUpdateBucket, - storageDeleteBucket, - storageListFiles, - storageCreateFile, - storageGetFile, - storageUpdateFile, - storageDeleteFile, - storageGetFileDownload, - storageGetFilePreview, - storageGetFileView, - storageGetUsage, - storageGetBucketUsage -}; + diff --git a/lib/commands/tables-db.js b/lib/commands/tables-db.ts similarity index 60% rename from lib/commands/tables-db.js rename to lib/commands/tables-db.ts index 21914d27..28a314f1 100644 --- a/lib/commands/tables-db.js +++ b/lib/commands/tables-db.ts @@ -1,31 +1,27 @@ -const fs = require('fs'); -const pathLib = require('path'); -const tar = require("tar"); -const ignore = require("ignore"); -const { promisify } = require('util'); -const libClient = require('../client.js'); -const { getAllFiles, showConsoleLink } = require('../utils.js'); -const { Command } = require('commander'); -const { sdkForProject, sdkForConsole } = require('../sdks') -const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } = require('../parser') -const { localConfig, globalConfig } = require("../config"); -const { File } = require('undici'); -const { ReadableStream } = require('stream/web'); - -/** - * @param {fs.ReadStream} readStream - * @returns {ReadableStream} - */ -function convertReadStreamToReadableStream(readStream) { +import fs = require('fs'); +import pathLib = require('path'); +import tar = require('tar'); +import ignore = require('ignore'); +import { promisify } from 'util'; +import Client from '../client'; +import { getAllFiles, showConsoleLink } from '../utils'; +import { Command } from 'commander'; +import { sdkForProject, sdkForConsole } from '../sdks'; +import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } from '../parser'; +import { localConfig, globalConfig } from '../config'; +import { File } from 'undici'; +import { ReadableStream } from 'stream/web'; + +function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ start(controller) { - readStream.on("data", (chunk) => { + readStream.on("data", (chunk: Buffer) => { controller.enqueue(chunk); }); readStream.on("end", () => { controller.close(); }); - readStream.on("error", (err) => { + readStream.on("error", (err: Error) => { controller.error(err); }); }, @@ -35,24 +31,21 @@ function convertReadStreamToReadableStream(readStream) { }); } -const tablesDB = new Command("tables-db").description(commandDescriptions['tables-db'] ?? '').configureHelp({ +export const tablesDB = new Command("tables-db").description(commandDescriptions['tables-db'] ?? '').configureHelp({ helpWidth: process.stdout.columns || 80 }) -/** - * @typedef {Object} TablesDBListRequestParams - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following columns: name - * @property {string} search Search term to filter your list results. Max length: 256 chars. - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBListRequestParams { + queries?: string[]; + search?: string; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {TablesDBListRequestParams} params - */ -const tablesDBList = async ({queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const tablesDBList = async ({queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: TablesDBListRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb'; @@ -73,7 +66,7 @@ const tablesDBList = async ({queries,search,total,parseOutput = true, overrideFo }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('tablesDB', 'list'); } else { parse(response) @@ -83,20 +76,16 @@ const tablesDBList = async ({queries,search,total,parseOutput = true, overrideFo return response; } -/** - * @typedef {Object} TablesDBCreateRequestParams - * @property {string} databaseId Unique Id. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} name Database name. Max length: 128 chars. - * @property {boolean} enabled Is the database enabled? When set to 'disabled', users cannot access the database but Server SDKs with an API key can still read and write to the database. No data is lost when this is toggled. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBCreateRequestParams { + databaseId: string; + name: string; + enabled?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBCreateRequestParams} params - */ -const tablesDBCreate = async ({databaseId,name,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBCreate = async ({databaseId,name,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBCreateRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb'; @@ -124,18 +113,15 @@ const tablesDBCreate = async ({databaseId,name,enabled,parseOutput = true, overr return response; } -/** - * @typedef {Object} TablesDBListTransactionsRequestParams - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBListTransactionsRequestParams { + queries?: string[]; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {TablesDBListTransactionsRequestParams} params - */ -const tablesDBListTransactions = async ({queries,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const tablesDBListTransactions = async ({queries,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: TablesDBListTransactionsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/transactions'; @@ -150,7 +136,7 @@ const tablesDBListTransactions = async ({queries,parseOutput = true, overrideFor }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('tablesDB', 'listTransactions'); } else { parse(response) @@ -160,18 +146,14 @@ const tablesDBListTransactions = async ({queries,parseOutput = true, overrideFor return response; } -/** - * @typedef {Object} TablesDBCreateTransactionRequestParams - * @property {number} ttl Seconds before the transaction expires. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBCreateTransactionRequestParams { + ttl?: number; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBCreateTransactionRequestParams} params - */ -const tablesDBCreateTransaction = async ({ttl,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBCreateTransaction = async ({ttl,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBCreateTransactionRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/transactions'; @@ -193,18 +175,15 @@ const tablesDBCreateTransaction = async ({ttl,parseOutput = true, overrideForCli return response; } -/** - * @typedef {Object} TablesDBGetTransactionRequestParams - * @property {string} transactionId Transaction ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBGetTransactionRequestParams { + transactionId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {TablesDBGetTransactionRequestParams} params - */ -const tablesDBGetTransaction = async ({transactionId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const tablesDBGetTransaction = async ({transactionId,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: TablesDBGetTransactionRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/transactions/{transactionId}'.replace('{transactionId}', transactionId); @@ -216,7 +195,7 @@ const tablesDBGetTransaction = async ({transactionId,parseOutput = true, overrid }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('tablesDB', 'getTransaction', transactionId); } else { parse(response) @@ -226,20 +205,16 @@ const tablesDBGetTransaction = async ({transactionId,parseOutput = true, overrid return response; } -/** - * @typedef {Object} TablesDBUpdateTransactionRequestParams - * @property {string} transactionId Transaction ID. - * @property {boolean} commit Commit transaction? - * @property {boolean} rollback Rollback transaction? - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBUpdateTransactionRequestParams { + transactionId: string; + commit?: boolean; + rollback?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBUpdateTransactionRequestParams} params - */ -const tablesDBUpdateTransaction = async ({transactionId,commit,rollback,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBUpdateTransaction = async ({transactionId,commit,rollback,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBUpdateTransactionRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/transactions/{transactionId}'.replace('{transactionId}', transactionId); @@ -264,18 +239,14 @@ const tablesDBUpdateTransaction = async ({transactionId,commit,rollback,parseOut return response; } -/** - * @typedef {Object} TablesDBDeleteTransactionRequestParams - * @property {string} transactionId Transaction ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBDeleteTransactionRequestParams { + transactionId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBDeleteTransactionRequestParams} params - */ -const tablesDBDeleteTransaction = async ({transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBDeleteTransaction = async ({transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBDeleteTransactionRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/transactions/{transactionId}'.replace('{transactionId}', transactionId); @@ -294,19 +265,15 @@ const tablesDBDeleteTransaction = async ({transactionId,parseOutput = true, over return response; } -/** - * @typedef {Object} TablesDBCreateOperationsRequestParams - * @property {string} transactionId Transaction ID. - * @property {object[]} operations Array of staged operations. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBCreateOperationsRequestParams { + transactionId: string; + operations?: object[]; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBCreateOperationsRequestParams} params - */ -const tablesDBCreateOperations = async ({transactionId,operations,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBCreateOperations = async ({transactionId,operations,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBCreateOperationsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/transactions/{transactionId}/operations'.replace('{transactionId}', transactionId); @@ -329,18 +296,15 @@ const tablesDBCreateOperations = async ({transactionId,operations,parseOutput = return response; } -/** - * @typedef {Object} TablesDBListUsageRequestParams - * @property {UsageRange} range Date range. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBListUsageRequestParams { + range?: UsageRange; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {TablesDBListUsageRequestParams} params - */ -const tablesDBListUsage = async ({range,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const tablesDBListUsage = async ({range,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: TablesDBListUsageRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/usage'; @@ -355,7 +319,7 @@ const tablesDBListUsage = async ({range,parseOutput = true, overrideForCli = fal }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('tablesDB', 'listUsage'); } else { parse(response) @@ -365,18 +329,15 @@ const tablesDBListUsage = async ({range,parseOutput = true, overrideForCli = fal return response; } -/** - * @typedef {Object} TablesDBGetRequestParams - * @property {string} databaseId Database ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBGetRequestParams { + databaseId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {TablesDBGetRequestParams} params - */ -const tablesDBGet = async ({databaseId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const tablesDBGet = async ({databaseId,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: TablesDBGetRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}'.replace('{databaseId}', databaseId); @@ -388,7 +349,7 @@ const tablesDBGet = async ({databaseId,parseOutput = true, overrideForCli = fals }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('tablesDB', 'get', databaseId); } else { parse(response) @@ -398,20 +359,16 @@ const tablesDBGet = async ({databaseId,parseOutput = true, overrideForCli = fals return response; } -/** - * @typedef {Object} TablesDBUpdateRequestParams - * @property {string} databaseId Database ID. - * @property {string} name Database name. Max length: 128 chars. - * @property {boolean} enabled Is database enabled? When set to 'disabled', users cannot access the database but Server SDKs with an API key can still read and write to the database. No data is lost when this is toggled. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBUpdateRequestParams { + databaseId: string; + name: string; + enabled?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBUpdateRequestParams} params - */ -const tablesDBUpdate = async ({databaseId,name,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBUpdate = async ({databaseId,name,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBUpdateRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}'.replace('{databaseId}', databaseId); @@ -436,18 +393,14 @@ const tablesDBUpdate = async ({databaseId,name,enabled,parseOutput = true, overr return response; } -/** - * @typedef {Object} TablesDBDeleteRequestParams - * @property {string} databaseId Database ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBDeleteRequestParams { + databaseId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBDeleteRequestParams} params - */ -const tablesDBDelete = async ({databaseId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBDelete = async ({databaseId,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBDeleteRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}'.replace('{databaseId}', databaseId); @@ -466,21 +419,18 @@ const tablesDBDelete = async ({databaseId,parseOutput = true, overrideForCli = f return response; } -/** - * @typedef {Object} TablesDBListTablesRequestParams - * @property {string} databaseId Database ID. - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following columns: name, enabled, rowSecurity - * @property {string} search Search term to filter your list results. Max length: 256 chars. - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBListTablesRequestParams { + databaseId: string; + queries?: string[]; + search?: string; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {TablesDBListTablesRequestParams} params - */ -const tablesDBListTables = async ({databaseId,queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const tablesDBListTables = async ({databaseId,queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: TablesDBListTablesRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables'.replace('{databaseId}', databaseId); @@ -501,7 +451,7 @@ const tablesDBListTables = async ({databaseId,queries,search,total,parseOutput = }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('tablesDB', 'listTables', databaseId); } else { parse(response) @@ -511,23 +461,21 @@ const tablesDBListTables = async ({databaseId,queries,search,total,parseOutput = return response; } -/** - * @typedef {Object} TablesDBCreateTableRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Unique Id. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} name Table name. Max length: 128 chars. - * @property {string[]} permissions An array of permissions strings. By default, no user is granted with any permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - * @property {boolean} rowSecurity Enables configuring permissions for individual rows. A user needs one of row or table level permissions to access a row. [Learn more about permissions](https://appwrite.io/docs/permissions). - * @property {boolean} enabled Is table enabled? When set to 'disabled', users cannot access the table but Server SDKs with and API key can still read and write to the table. No data is lost when this is toggled. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBCreateTableRequestParams { + databaseId: string; + tableId: string; + name: string; + permissions?: string[]; + rowSecurity?: boolean; + enabled?: boolean; + columns?: object[]; + indexes?: object[]; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBCreateTableRequestParams} params - */ -const tablesDBCreateTable = async ({databaseId,tableId,name,permissions,rowSecurity,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBCreateTable = async ({databaseId,tableId,name,permissions,rowSecurity,enabled,columns,indexes,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBCreateTableRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables'.replace('{databaseId}', databaseId); @@ -548,6 +496,14 @@ const tablesDBCreateTable = async ({databaseId,tableId,name,permissions,rowSecur if (typeof enabled !== 'undefined') { payload['enabled'] = enabled; } + columns = columns === true ? [] : columns; + if (typeof columns !== 'undefined') { + payload['columns'] = columns; + } + indexes = indexes === true ? [] : indexes; + if (typeof indexes !== 'undefined') { + payload['indexes'] = indexes; + } let response = undefined; @@ -562,19 +518,16 @@ const tablesDBCreateTable = async ({databaseId,tableId,name,permissions,rowSecur return response; } -/** - * @typedef {Object} TablesDBGetTableRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBGetTableRequestParams { + databaseId: string; + tableId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {TablesDBGetTableRequestParams} params - */ -const tablesDBGetTable = async ({databaseId,tableId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const tablesDBGetTable = async ({databaseId,tableId,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: TablesDBGetTableRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}'.replace('{databaseId}', databaseId).replace('{tableId}', tableId); @@ -586,7 +539,7 @@ const tablesDBGetTable = async ({databaseId,tableId,parseOutput = true, override }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('tablesDB', 'getTable', databaseId, tableId); } else { parse(response) @@ -596,23 +549,19 @@ const tablesDBGetTable = async ({databaseId,tableId,parseOutput = true, override return response; } -/** - * @typedef {Object} TablesDBUpdateTableRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. - * @property {string} name Table name. Max length: 128 chars. - * @property {string[]} permissions An array of permission strings. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions). - * @property {boolean} rowSecurity Enables configuring permissions for individual rows. A user needs one of row or table-level permissions to access a row. [Learn more about permissions](https://appwrite.io/docs/permissions). - * @property {boolean} enabled Is table enabled? When set to 'disabled', users cannot access the table but Server SDKs with and API key can still read and write to the table. No data is lost when this is toggled. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBUpdateTableRequestParams { + databaseId: string; + tableId: string; + name: string; + permissions?: string[]; + rowSecurity?: boolean; + enabled?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBUpdateTableRequestParams} params - */ -const tablesDBUpdateTable = async ({databaseId,tableId,name,permissions,rowSecurity,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBUpdateTable = async ({databaseId,tableId,name,permissions,rowSecurity,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBUpdateTableRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}'.replace('{databaseId}', databaseId).replace('{tableId}', tableId); @@ -644,19 +593,15 @@ const tablesDBUpdateTable = async ({databaseId,tableId,name,permissions,rowSecur return response; } -/** - * @typedef {Object} TablesDBDeleteTableRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBDeleteTableRequestParams { + databaseId: string; + tableId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBDeleteTableRequestParams} params - */ -const tablesDBDeleteTable = async ({databaseId,tableId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBDeleteTable = async ({databaseId,tableId,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBDeleteTableRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}'.replace('{databaseId}', databaseId).replace('{tableId}', tableId); @@ -675,21 +620,18 @@ const tablesDBDeleteTable = async ({databaseId,tableId,parseOutput = true, overr return response; } -/** - * @typedef {Object} TablesDBListColumnsRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following columns: key, type, size, required, array, status, error - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBListColumnsRequestParams { + databaseId: string; + tableId: string; + queries?: string[]; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {TablesDBListColumnsRequestParams} params - */ -const tablesDBListColumns = async ({databaseId,tableId,queries,total,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const tablesDBListColumns = async ({databaseId,tableId,queries,total,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: TablesDBListColumnsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/columns'.replace('{databaseId}', databaseId).replace('{tableId}', tableId); @@ -707,7 +649,7 @@ const tablesDBListColumns = async ({databaseId,tableId,queries,total,parseOutput }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('tablesDB', 'listColumns', databaseId, tableId); } else { parse(response) @@ -717,23 +659,19 @@ const tablesDBListColumns = async ({databaseId,tableId,queries,total,parseOutput return response; } -/** - * @typedef {Object} TablesDBCreateBooleanColumnRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable). - * @property {string} key Column Key. - * @property {boolean} required Is column required? - * @property {boolean} xdefault Default value for column when not provided. Cannot be set when column is required. - * @property {boolean} array Is column an array? - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBCreateBooleanColumnRequestParams { + databaseId: string; + tableId: string; + key: string; + required: boolean; + xdefault?: boolean; + array?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBCreateBooleanColumnRequestParams} params - */ -const tablesDBCreateBooleanColumn = async ({databaseId,tableId,key,required,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBCreateBooleanColumn = async ({databaseId,tableId,key,required,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBCreateBooleanColumnRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/columns/boolean'.replace('{databaseId}', databaseId).replace('{tableId}', tableId); @@ -764,23 +702,19 @@ const tablesDBCreateBooleanColumn = async ({databaseId,tableId,key,required,xdef return response; } -/** - * @typedef {Object} TablesDBUpdateBooleanColumnRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable). - * @property {string} key Column Key. - * @property {boolean} required Is column required? - * @property {boolean} xdefault Default value for column when not provided. Cannot be set when column is required. - * @property {string} newKey New Column Key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBUpdateBooleanColumnRequestParams { + databaseId: string; + tableId: string; + key: string; + required: boolean; + xdefault: boolean; + newKey?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBUpdateBooleanColumnRequestParams} params - */ -const tablesDBUpdateBooleanColumn = async ({databaseId,tableId,key,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBUpdateBooleanColumn = async ({databaseId,tableId,key,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBUpdateBooleanColumnRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/columns/boolean/{key}'.replace('{databaseId}', databaseId).replace('{tableId}', tableId).replace('{key}', key); @@ -808,23 +742,19 @@ const tablesDBUpdateBooleanColumn = async ({databaseId,tableId,key,required,xdef return response; } -/** - * @typedef {Object} TablesDBCreateDatetimeColumnRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. - * @property {string} key Column Key. - * @property {boolean} required Is column required? - * @property {string} xdefault Default value for the column in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. Cannot be set when column is required. - * @property {boolean} array Is column an array? - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBCreateDatetimeColumnRequestParams { + databaseId: string; + tableId: string; + key: string; + required: boolean; + xdefault?: string; + array?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBCreateDatetimeColumnRequestParams} params - */ -const tablesDBCreateDatetimeColumn = async ({databaseId,tableId,key,required,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBCreateDatetimeColumn = async ({databaseId,tableId,key,required,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBCreateDatetimeColumnRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/columns/datetime'.replace('{databaseId}', databaseId).replace('{tableId}', tableId); @@ -855,23 +785,19 @@ const tablesDBCreateDatetimeColumn = async ({databaseId,tableId,key,required,xde return response; } -/** - * @typedef {Object} TablesDBUpdateDatetimeColumnRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. - * @property {string} key Column Key. - * @property {boolean} required Is column required? - * @property {string} xdefault Default value for column when not provided. Cannot be set when column is required. - * @property {string} newKey New Column Key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBUpdateDatetimeColumnRequestParams { + databaseId: string; + tableId: string; + key: string; + required: boolean; + xdefault: string; + newKey?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBUpdateDatetimeColumnRequestParams} params - */ -const tablesDBUpdateDatetimeColumn = async ({databaseId,tableId,key,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBUpdateDatetimeColumn = async ({databaseId,tableId,key,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBUpdateDatetimeColumnRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/columns/datetime/{key}'.replace('{databaseId}', databaseId).replace('{tableId}', tableId).replace('{key}', key); @@ -899,23 +825,19 @@ const tablesDBUpdateDatetimeColumn = async ({databaseId,tableId,key,required,xde return response; } -/** - * @typedef {Object} TablesDBCreateEmailColumnRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. - * @property {string} key Column Key. - * @property {boolean} required Is column required? - * @property {string} xdefault Default value for column when not provided. Cannot be set when column is required. - * @property {boolean} array Is column an array? - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBCreateEmailColumnRequestParams { + databaseId: string; + tableId: string; + key: string; + required: boolean; + xdefault?: string; + array?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBCreateEmailColumnRequestParams} params - */ -const tablesDBCreateEmailColumn = async ({databaseId,tableId,key,required,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBCreateEmailColumn = async ({databaseId,tableId,key,required,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBCreateEmailColumnRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/columns/email'.replace('{databaseId}', databaseId).replace('{tableId}', tableId); @@ -946,23 +868,19 @@ const tablesDBCreateEmailColumn = async ({databaseId,tableId,key,required,xdefau return response; } -/** - * @typedef {Object} TablesDBUpdateEmailColumnRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. - * @property {string} key Column Key. - * @property {boolean} required Is column required? - * @property {string} xdefault Default value for column when not provided. Cannot be set when column is required. - * @property {string} newKey New Column Key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBUpdateEmailColumnRequestParams { + databaseId: string; + tableId: string; + key: string; + required: boolean; + xdefault: string; + newKey?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBUpdateEmailColumnRequestParams} params - */ -const tablesDBUpdateEmailColumn = async ({databaseId,tableId,key,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBUpdateEmailColumn = async ({databaseId,tableId,key,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBUpdateEmailColumnRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/columns/email/{key}'.replace('{databaseId}', databaseId).replace('{tableId}', tableId).replace('{key}', key); @@ -990,24 +908,20 @@ const tablesDBUpdateEmailColumn = async ({databaseId,tableId,key,required,xdefau return response; } -/** - * @typedef {Object} TablesDBCreateEnumColumnRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. - * @property {string} key Column Key. - * @property {string[]} elements Array of enum values. - * @property {boolean} required Is column required? - * @property {string} xdefault Default value for column when not provided. Cannot be set when column is required. - * @property {boolean} array Is column an array? - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBCreateEnumColumnRequestParams { + databaseId: string; + tableId: string; + key: string; + elements: string[]; + required: boolean; + xdefault?: string; + array?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBCreateEnumColumnRequestParams} params - */ -const tablesDBCreateEnumColumn = async ({databaseId,tableId,key,elements,required,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBCreateEnumColumn = async ({databaseId,tableId,key,elements,required,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBCreateEnumColumnRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/columns/enum'.replace('{databaseId}', databaseId).replace('{tableId}', tableId); @@ -1042,24 +956,20 @@ const tablesDBCreateEnumColumn = async ({databaseId,tableId,key,elements,require return response; } -/** - * @typedef {Object} TablesDBUpdateEnumColumnRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. - * @property {string} key Column Key. - * @property {string[]} elements Updated list of enum values. - * @property {boolean} required Is column required? - * @property {string} xdefault Default value for column when not provided. Cannot be set when column is required. - * @property {string} newKey New Column Key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBUpdateEnumColumnRequestParams { + databaseId: string; + tableId: string; + key: string; + elements: string[]; + required: boolean; + xdefault: string; + newKey?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBUpdateEnumColumnRequestParams} params - */ -const tablesDBUpdateEnumColumn = async ({databaseId,tableId,key,elements,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBUpdateEnumColumn = async ({databaseId,tableId,key,elements,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBUpdateEnumColumnRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/columns/enum/{key}'.replace('{databaseId}', databaseId).replace('{tableId}', tableId).replace('{key}', key); @@ -1091,25 +1001,21 @@ const tablesDBUpdateEnumColumn = async ({databaseId,tableId,key,elements,require return response; } -/** - * @typedef {Object} TablesDBCreateFloatColumnRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. - * @property {string} key Column Key. - * @property {boolean} required Is column required? - * @property {number} min Minimum value - * @property {number} max Maximum value - * @property {number} xdefault Default value. Cannot be set when required. - * @property {boolean} array Is column an array? - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBCreateFloatColumnRequestParams { + databaseId: string; + tableId: string; + key: string; + required: boolean; + min?: number; + max?: number; + xdefault?: number; + array?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBCreateFloatColumnRequestParams} params - */ -const tablesDBCreateFloatColumn = async ({databaseId,tableId,key,required,min,max,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBCreateFloatColumn = async ({databaseId,tableId,key,required,min,max,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBCreateFloatColumnRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/columns/float'.replace('{databaseId}', databaseId).replace('{tableId}', tableId); @@ -1146,25 +1052,21 @@ const tablesDBCreateFloatColumn = async ({databaseId,tableId,key,required,min,ma return response; } -/** - * @typedef {Object} TablesDBUpdateFloatColumnRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. - * @property {string} key Column Key. - * @property {boolean} required Is column required? - * @property {number} xdefault Default value. Cannot be set when required. - * @property {number} min Minimum value - * @property {number} max Maximum value - * @property {string} newKey New Column Key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBUpdateFloatColumnRequestParams { + databaseId: string; + tableId: string; + key: string; + required: boolean; + xdefault: number; + min?: number; + max?: number; + newKey?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBUpdateFloatColumnRequestParams} params - */ -const tablesDBUpdateFloatColumn = async ({databaseId,tableId,key,required,xdefault,min,max,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBUpdateFloatColumn = async ({databaseId,tableId,key,required,xdefault,min,max,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBUpdateFloatColumnRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/columns/float/{key}'.replace('{databaseId}', databaseId).replace('{tableId}', tableId).replace('{key}', key); @@ -1198,25 +1100,21 @@ const tablesDBUpdateFloatColumn = async ({databaseId,tableId,key,required,xdefau return response; } -/** - * @typedef {Object} TablesDBCreateIntegerColumnRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. - * @property {string} key Column Key. - * @property {boolean} required Is column required? - * @property {number} min Minimum value - * @property {number} max Maximum value - * @property {number} xdefault Default value. Cannot be set when column is required. - * @property {boolean} array Is column an array? - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBCreateIntegerColumnRequestParams { + databaseId: string; + tableId: string; + key: string; + required: boolean; + min?: number; + max?: number; + xdefault?: number; + array?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBCreateIntegerColumnRequestParams} params - */ -const tablesDBCreateIntegerColumn = async ({databaseId,tableId,key,required,min,max,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBCreateIntegerColumn = async ({databaseId,tableId,key,required,min,max,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBCreateIntegerColumnRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/columns/integer'.replace('{databaseId}', databaseId).replace('{tableId}', tableId); @@ -1253,25 +1151,21 @@ const tablesDBCreateIntegerColumn = async ({databaseId,tableId,key,required,min, return response; } -/** - * @typedef {Object} TablesDBUpdateIntegerColumnRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. - * @property {string} key Column Key. - * @property {boolean} required Is column required? - * @property {number} xdefault Default value. Cannot be set when column is required. - * @property {number} min Minimum value - * @property {number} max Maximum value - * @property {string} newKey New Column Key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBUpdateIntegerColumnRequestParams { + databaseId: string; + tableId: string; + key: string; + required: boolean; + xdefault: number; + min?: number; + max?: number; + newKey?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBUpdateIntegerColumnRequestParams} params - */ -const tablesDBUpdateIntegerColumn = async ({databaseId,tableId,key,required,xdefault,min,max,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBUpdateIntegerColumn = async ({databaseId,tableId,key,required,xdefault,min,max,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBUpdateIntegerColumnRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/columns/integer/{key}'.replace('{databaseId}', databaseId).replace('{tableId}', tableId).replace('{key}', key); @@ -1305,23 +1199,19 @@ const tablesDBUpdateIntegerColumn = async ({databaseId,tableId,key,required,xdef return response; } -/** - * @typedef {Object} TablesDBCreateIpColumnRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. - * @property {string} key Column Key. - * @property {boolean} required Is column required? - * @property {string} xdefault Default value. Cannot be set when column is required. - * @property {boolean} array Is column an array? - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBCreateIpColumnRequestParams { + databaseId: string; + tableId: string; + key: string; + required: boolean; + xdefault?: string; + array?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBCreateIpColumnRequestParams} params - */ -const tablesDBCreateIpColumn = async ({databaseId,tableId,key,required,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBCreateIpColumn = async ({databaseId,tableId,key,required,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBCreateIpColumnRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/columns/ip'.replace('{databaseId}', databaseId).replace('{tableId}', tableId); @@ -1352,23 +1242,19 @@ const tablesDBCreateIpColumn = async ({databaseId,tableId,key,required,xdefault, return response; } -/** - * @typedef {Object} TablesDBUpdateIpColumnRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. - * @property {string} key Column Key. - * @property {boolean} required Is column required? - * @property {string} xdefault Default value. Cannot be set when column is required. - * @property {string} newKey New Column Key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBUpdateIpColumnRequestParams { + databaseId: string; + tableId: string; + key: string; + required: boolean; + xdefault: string; + newKey?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBUpdateIpColumnRequestParams} params - */ -const tablesDBUpdateIpColumn = async ({databaseId,tableId,key,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBUpdateIpColumn = async ({databaseId,tableId,key,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBUpdateIpColumnRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/columns/ip/{key}'.replace('{databaseId}', databaseId).replace('{tableId}', tableId).replace('{key}', key); @@ -1396,22 +1282,18 @@ const tablesDBUpdateIpColumn = async ({databaseId,tableId,key,required,xdefault, return response; } -/** - * @typedef {Object} TablesDBCreateLineColumnRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. You can create a new table using the TablesDB service [server integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable). - * @property {string} key Column Key. - * @property {boolean} required Is column required? - * @property {any[]} xdefault Default value for column when not provided, two-dimensional array of coordinate pairs, [[longitude, latitude], [longitude, latitude], …], listing the vertices of the line in order. Cannot be set when column is required. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBCreateLineColumnRequestParams { + databaseId: string; + tableId: string; + key: string; + required: boolean; + xdefault?: any[]; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBCreateLineColumnRequestParams} params - */ -const tablesDBCreateLineColumn = async ({databaseId,tableId,key,required,xdefault,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBCreateLineColumn = async ({databaseId,tableId,key,required,xdefault,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBCreateLineColumnRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/columns/line'.replace('{databaseId}', databaseId).replace('{tableId}', tableId); @@ -1440,23 +1322,19 @@ const tablesDBCreateLineColumn = async ({databaseId,tableId,key,required,xdefaul return response; } -/** - * @typedef {Object} TablesDBUpdateLineColumnRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. You can create a new table using the TablesDB service [server integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable). - * @property {string} key Column Key. - * @property {boolean} required Is column required? - * @property {any[]} xdefault Default value for column when not provided, two-dimensional array of coordinate pairs, [[longitude, latitude], [longitude, latitude], …], listing the vertices of the line in order. Cannot be set when column is required. - * @property {string} newKey New Column Key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBUpdateLineColumnRequestParams { + databaseId: string; + tableId: string; + key: string; + required: boolean; + xdefault?: any[]; + newKey?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBUpdateLineColumnRequestParams} params - */ -const tablesDBUpdateLineColumn = async ({databaseId,tableId,key,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBUpdateLineColumn = async ({databaseId,tableId,key,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBUpdateLineColumnRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/columns/line/{key}'.replace('{databaseId}', databaseId).replace('{tableId}', tableId).replace('{key}', key); @@ -1485,22 +1363,18 @@ const tablesDBUpdateLineColumn = async ({databaseId,tableId,key,required,xdefaul return response; } -/** - * @typedef {Object} TablesDBCreatePointColumnRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. You can create a new table using the TablesDB service [server integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable). - * @property {string} key Column Key. - * @property {boolean} required Is column required? - * @property {any[]} xdefault Default value for column when not provided, array of two numbers [longitude, latitude], representing a single coordinate. Cannot be set when column is required. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBCreatePointColumnRequestParams { + databaseId: string; + tableId: string; + key: string; + required: boolean; + xdefault?: any[]; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBCreatePointColumnRequestParams} params - */ -const tablesDBCreatePointColumn = async ({databaseId,tableId,key,required,xdefault,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBCreatePointColumn = async ({databaseId,tableId,key,required,xdefault,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBCreatePointColumnRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/columns/point'.replace('{databaseId}', databaseId).replace('{tableId}', tableId); @@ -1529,23 +1403,19 @@ const tablesDBCreatePointColumn = async ({databaseId,tableId,key,required,xdefau return response; } -/** - * @typedef {Object} TablesDBUpdatePointColumnRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. You can create a new table using the TablesDB service [server integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable). - * @property {string} key Column Key. - * @property {boolean} required Is column required? - * @property {any[]} xdefault Default value for column when not provided, array of two numbers [longitude, latitude], representing a single coordinate. Cannot be set when column is required. - * @property {string} newKey New Column Key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBUpdatePointColumnRequestParams { + databaseId: string; + tableId: string; + key: string; + required: boolean; + xdefault?: any[]; + newKey?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBUpdatePointColumnRequestParams} params - */ -const tablesDBUpdatePointColumn = async ({databaseId,tableId,key,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBUpdatePointColumn = async ({databaseId,tableId,key,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBUpdatePointColumnRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/columns/point/{key}'.replace('{databaseId}', databaseId).replace('{tableId}', tableId).replace('{key}', key); @@ -1574,22 +1444,18 @@ const tablesDBUpdatePointColumn = async ({databaseId,tableId,key,required,xdefau return response; } -/** - * @typedef {Object} TablesDBCreatePolygonColumnRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. You can create a new table using the TablesDB service [server integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable). - * @property {string} key Column Key. - * @property {boolean} required Is column required? - * @property {any[]} xdefault Default value for column when not provided, three-dimensional array where the outer array holds one or more linear rings, [[[longitude, latitude], …], …], the first ring is the exterior boundary, any additional rings are interior holes, and each ring must start and end with the same coordinate pair. Cannot be set when column is required. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBCreatePolygonColumnRequestParams { + databaseId: string; + tableId: string; + key: string; + required: boolean; + xdefault?: any[]; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBCreatePolygonColumnRequestParams} params - */ -const tablesDBCreatePolygonColumn = async ({databaseId,tableId,key,required,xdefault,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBCreatePolygonColumn = async ({databaseId,tableId,key,required,xdefault,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBCreatePolygonColumnRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/columns/polygon'.replace('{databaseId}', databaseId).replace('{tableId}', tableId); @@ -1618,23 +1484,19 @@ const tablesDBCreatePolygonColumn = async ({databaseId,tableId,key,required,xdef return response; } -/** - * @typedef {Object} TablesDBUpdatePolygonColumnRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. You can create a new table using the TablesDB service [server integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable). - * @property {string} key Column Key. - * @property {boolean} required Is column required? - * @property {any[]} xdefault Default value for column when not provided, three-dimensional array where the outer array holds one or more linear rings, [[[longitude, latitude], …], …], the first ring is the exterior boundary, any additional rings are interior holes, and each ring must start and end with the same coordinate pair. Cannot be set when column is required. - * @property {string} newKey New Column Key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBUpdatePolygonColumnRequestParams { + databaseId: string; + tableId: string; + key: string; + required: boolean; + xdefault?: any[]; + newKey?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBUpdatePolygonColumnRequestParams} params - */ -const tablesDBUpdatePolygonColumn = async ({databaseId,tableId,key,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBUpdatePolygonColumn = async ({databaseId,tableId,key,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBUpdatePolygonColumnRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/columns/polygon/{key}'.replace('{databaseId}', databaseId).replace('{tableId}', tableId).replace('{key}', key); @@ -1663,25 +1525,21 @@ const tablesDBUpdatePolygonColumn = async ({databaseId,tableId,key,required,xdef return response; } -/** - * @typedef {Object} TablesDBCreateRelationshipColumnRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. - * @property {string} relatedTableId Related Table ID. - * @property {RelationshipType} type Relation type - * @property {boolean} twoWay Is Two Way? - * @property {string} key Column Key. - * @property {string} twoWayKey Two Way Column Key. - * @property {RelationMutate} onDelete Constraints option - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBCreateRelationshipColumnRequestParams { + databaseId: string; + tableId: string; + relatedTableId: string; + type: RelationshipType; + twoWay?: boolean; + key?: string; + twoWayKey?: string; + onDelete?: RelationMutate; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBCreateRelationshipColumnRequestParams} params - */ -const tablesDBCreateRelationshipColumn = async ({databaseId,tableId,relatedTableId,type,twoWay,key,twoWayKey,onDelete,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBCreateRelationshipColumn = async ({databaseId,tableId,relatedTableId,type,twoWay,key,twoWayKey,onDelete,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBCreateRelationshipColumnRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/columns/relationship'.replace('{databaseId}', databaseId).replace('{tableId}', tableId); @@ -1718,25 +1576,21 @@ const tablesDBCreateRelationshipColumn = async ({databaseId,tableId,relatedTable return response; } -/** - * @typedef {Object} TablesDBCreateStringColumnRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable). - * @property {string} key Column Key. - * @property {number} size Column size for text columns, in number of characters. - * @property {boolean} required Is column required? - * @property {string} xdefault Default value for column when not provided. Cannot be set when column is required. - * @property {boolean} array Is column an array? - * @property {boolean} encrypt Toggle encryption for the column. Encryption enhances security by not storing any plain text values in the database. However, encrypted columns cannot be queried. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBCreateStringColumnRequestParams { + databaseId: string; + tableId: string; + key: string; + size: number; + required: boolean; + xdefault?: string; + array?: boolean; + encrypt?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBCreateStringColumnRequestParams} params - */ -const tablesDBCreateStringColumn = async ({databaseId,tableId,key,size,required,xdefault,array,encrypt,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBCreateStringColumn = async ({databaseId,tableId,key,size,required,xdefault,array,encrypt,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBCreateStringColumnRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/columns/string'.replace('{databaseId}', databaseId).replace('{tableId}', tableId); @@ -1773,24 +1627,20 @@ const tablesDBCreateStringColumn = async ({databaseId,tableId,key,size,required, return response; } -/** - * @typedef {Object} TablesDBUpdateStringColumnRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable). - * @property {string} key Column Key. - * @property {boolean} required Is column required? - * @property {string} xdefault Default value for column when not provided. Cannot be set when column is required. - * @property {number} size Maximum size of the string column. - * @property {string} newKey New Column Key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBUpdateStringColumnRequestParams { + databaseId: string; + tableId: string; + key: string; + required: boolean; + xdefault: string; + size?: number; + newKey?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBUpdateStringColumnRequestParams} params - */ -const tablesDBUpdateStringColumn = async ({databaseId,tableId,key,required,xdefault,size,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBUpdateStringColumn = async ({databaseId,tableId,key,required,xdefault,size,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBUpdateStringColumnRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/columns/string/{key}'.replace('{databaseId}', databaseId).replace('{tableId}', tableId).replace('{key}', key); @@ -1821,23 +1671,19 @@ const tablesDBUpdateStringColumn = async ({databaseId,tableId,key,required,xdefa return response; } -/** - * @typedef {Object} TablesDBCreateUrlColumnRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. - * @property {string} key Column Key. - * @property {boolean} required Is column required? - * @property {string} xdefault Default value for column when not provided. Cannot be set when column is required. - * @property {boolean} array Is column an array? - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBCreateUrlColumnRequestParams { + databaseId: string; + tableId: string; + key: string; + required: boolean; + xdefault?: string; + array?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBCreateUrlColumnRequestParams} params - */ -const tablesDBCreateUrlColumn = async ({databaseId,tableId,key,required,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBCreateUrlColumn = async ({databaseId,tableId,key,required,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBCreateUrlColumnRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/columns/url'.replace('{databaseId}', databaseId).replace('{tableId}', tableId); @@ -1868,23 +1714,19 @@ const tablesDBCreateUrlColumn = async ({databaseId,tableId,key,required,xdefault return response; } -/** - * @typedef {Object} TablesDBUpdateUrlColumnRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. - * @property {string} key Column Key. - * @property {boolean} required Is column required? - * @property {string} xdefault Default value for column when not provided. Cannot be set when column is required. - * @property {string} newKey New Column Key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBUpdateUrlColumnRequestParams { + databaseId: string; + tableId: string; + key: string; + required: boolean; + xdefault: string; + newKey?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBUpdateUrlColumnRequestParams} params - */ -const tablesDBUpdateUrlColumn = async ({databaseId,tableId,key,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBUpdateUrlColumn = async ({databaseId,tableId,key,required,xdefault,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBUpdateUrlColumnRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/columns/url/{key}'.replace('{databaseId}', databaseId).replace('{tableId}', tableId).replace('{key}', key); @@ -1912,20 +1754,17 @@ const tablesDBUpdateUrlColumn = async ({databaseId,tableId,key,required,xdefault return response; } -/** - * @typedef {Object} TablesDBGetColumnRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. - * @property {string} key Column Key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBGetColumnRequestParams { + databaseId: string; + tableId: string; + key: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {TablesDBGetColumnRequestParams} params - */ -const tablesDBGetColumn = async ({databaseId,tableId,key,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const tablesDBGetColumn = async ({databaseId,tableId,key,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: TablesDBGetColumnRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/columns/{key}'.replace('{databaseId}', databaseId).replace('{tableId}', tableId).replace('{key}', key); @@ -1937,7 +1776,7 @@ const tablesDBGetColumn = async ({databaseId,tableId,key,parseOutput = true, ove }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('tablesDB', 'getColumn', databaseId, tableId); } else { parse(response) @@ -1947,20 +1786,16 @@ const tablesDBGetColumn = async ({databaseId,tableId,key,parseOutput = true, ove return response; } -/** - * @typedef {Object} TablesDBDeleteColumnRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. - * @property {string} key Column Key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBDeleteColumnRequestParams { + databaseId: string; + tableId: string; + key: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBDeleteColumnRequestParams} params - */ -const tablesDBDeleteColumn = async ({databaseId,tableId,key,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBDeleteColumn = async ({databaseId,tableId,key,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBDeleteColumnRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/columns/{key}'.replace('{databaseId}', databaseId).replace('{tableId}', tableId).replace('{key}', key); @@ -1979,22 +1814,18 @@ const tablesDBDeleteColumn = async ({databaseId,tableId,key,parseOutput = true, return response; } -/** - * @typedef {Object} TablesDBUpdateRelationshipColumnRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. - * @property {string} key Column Key. - * @property {RelationMutate} onDelete Constraints option - * @property {string} newKey New Column Key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBUpdateRelationshipColumnRequestParams { + databaseId: string; + tableId: string; + key: string; + onDelete?: RelationMutate; + newKey?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBUpdateRelationshipColumnRequestParams} params - */ -const tablesDBUpdateRelationshipColumn = async ({databaseId,tableId,key,onDelete,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBUpdateRelationshipColumn = async ({databaseId,tableId,key,onDelete,newKey,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBUpdateRelationshipColumnRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/columns/{key}/relationship'.replace('{databaseId}', databaseId).replace('{tableId}', tableId).replace('{key}', key); @@ -2019,21 +1850,18 @@ const tablesDBUpdateRelationshipColumn = async ({databaseId,tableId,key,onDelete return response; } -/** - * @typedef {Object} TablesDBListIndexesRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable). - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following columns: key, type, status, attributes, error - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBListIndexesRequestParams { + databaseId: string; + tableId: string; + queries?: string[]; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {TablesDBListIndexesRequestParams} params - */ -const tablesDBListIndexes = async ({databaseId,tableId,queries,total,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const tablesDBListIndexes = async ({databaseId,tableId,queries,total,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: TablesDBListIndexesRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/indexes'.replace('{databaseId}', databaseId).replace('{tableId}', tableId); @@ -2051,7 +1879,7 @@ const tablesDBListIndexes = async ({databaseId,tableId,queries,total,parseOutput }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('tablesDB', 'listIndexes', databaseId, tableId); } else { parse(response) @@ -2061,24 +1889,20 @@ const tablesDBListIndexes = async ({databaseId,tableId,queries,total,parseOutput return response; } -/** - * @typedef {Object} TablesDBCreateIndexRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable). - * @property {string} key Index Key. - * @property {IndexType} type Index type. - * @property {string[]} columns Array of columns to index. Maximum of 100 columns are allowed, each 32 characters long. - * @property {string[]} orders Array of index orders. Maximum of 100 orders are allowed. - * @property {number[]} lengths Length of index. Maximum of 100 - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBCreateIndexRequestParams { + databaseId: string; + tableId: string; + key: string; + type: IndexType; + columns: string[]; + orders?: string[]; + lengths?: number[]; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBCreateIndexRequestParams} params - */ -const tablesDBCreateIndex = async ({databaseId,tableId,key,type,columns,orders,lengths,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBCreateIndex = async ({databaseId,tableId,key,type,columns,orders,lengths,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBCreateIndexRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/indexes'.replace('{databaseId}', databaseId).replace('{tableId}', tableId); @@ -2115,20 +1939,16 @@ const tablesDBCreateIndex = async ({databaseId,tableId,key,type,columns,orders,l return response; } -/** - * @typedef {Object} TablesDBGetIndexRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable). - * @property {string} key Index Key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBGetIndexRequestParams { + databaseId: string; + tableId: string; + key: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBGetIndexRequestParams} params - */ -const tablesDBGetIndex = async ({databaseId,tableId,key,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBGetIndex = async ({databaseId,tableId,key,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBGetIndexRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/indexes/{key}'.replace('{databaseId}', databaseId).replace('{tableId}', tableId).replace('{key}', key); @@ -2146,20 +1966,16 @@ const tablesDBGetIndex = async ({databaseId,tableId,key,parseOutput = true, over return response; } -/** - * @typedef {Object} TablesDBDeleteIndexRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. You can create a new table using the TablesDB service [server integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable). - * @property {string} key Index Key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBDeleteIndexRequestParams { + databaseId: string; + tableId: string; + key: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBDeleteIndexRequestParams} params - */ -const tablesDBDeleteIndex = async ({databaseId,tableId,key,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBDeleteIndex = async ({databaseId,tableId,key,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBDeleteIndexRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/indexes/{key}'.replace('{databaseId}', databaseId).replace('{tableId}', tableId).replace('{key}', key); @@ -2178,20 +1994,17 @@ const tablesDBDeleteIndex = async ({databaseId,tableId,key,parseOutput = true, o return response; } -/** - * @typedef {Object} TablesDBListTableLogsRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Only supported methods are limit and offset - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBListTableLogsRequestParams { + databaseId: string; + tableId: string; + queries?: string[]; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {TablesDBListTableLogsRequestParams} params - */ -const tablesDBListTableLogs = async ({databaseId,tableId,queries,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const tablesDBListTableLogs = async ({databaseId,tableId,queries,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: TablesDBListTableLogsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/logs'.replace('{databaseId}', databaseId).replace('{tableId}', tableId); @@ -2206,7 +2019,7 @@ const tablesDBListTableLogs = async ({databaseId,tableId,queries,parseOutput = t }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('tablesDB', 'listTableLogs', databaseId, tableId); } else { parse(response) @@ -2216,22 +2029,19 @@ const tablesDBListTableLogs = async ({databaseId,tableId,queries,parseOutput = t return response; } -/** - * @typedef {Object} TablesDBListRowsRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. You can create a new table using the TablesDB service [server integration](https://appwrite.io/docs/products/databases/tables#create-table). - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. - * @property {string} transactionId Transaction ID to read uncommitted changes within the transaction. - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBListRowsRequestParams { + databaseId: string; + tableId: string; + queries?: string[]; + transactionId?: string; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {TablesDBListRowsRequestParams} params - */ -const tablesDBListRows = async ({databaseId,tableId,queries,transactionId,total,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const tablesDBListRows = async ({databaseId,tableId,queries,transactionId,total,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: TablesDBListRowsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows'.replace('{databaseId}', databaseId).replace('{tableId}', tableId); @@ -2252,7 +2062,7 @@ const tablesDBListRows = async ({databaseId,tableId,queries,transactionId,total, }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('tablesDB', 'listRows', databaseId, tableId); } else { parse(response) @@ -2262,23 +2072,19 @@ const tablesDBListRows = async ({databaseId,tableId,queries,transactionId,total, return response; } -/** - * @typedef {Object} TablesDBCreateRowRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable). Make sure to define columns before creating rows. - * @property {string} rowId Row ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {object} data Row data as JSON object. - * @property {string[]} permissions An array of permissions strings. By default, only the current user is granted all permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - * @property {string} transactionId Transaction ID for staging the operation. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBCreateRowRequestParams { + databaseId: string; + tableId: string; + rowId: string; + data: object; + permissions?: string[]; + transactionId?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBCreateRowRequestParams} params - */ -const tablesDBCreateRow = async ({databaseId,tableId,rowId,data,permissions,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBCreateRow = async ({databaseId,tableId,rowId,data,permissions,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBCreateRowRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows'.replace('{databaseId}', databaseId).replace('{tableId}', tableId); @@ -2310,21 +2116,17 @@ const tablesDBCreateRow = async ({databaseId,tableId,rowId,data,permissions,tran return response; } -/** - * @typedef {Object} TablesDBCreateRowsRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable). Make sure to define columns before creating rows. - * @property {object[]} rows Array of rows data as JSON objects. - * @property {string} transactionId Transaction ID for staging the operation. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBCreateRowsRequestParams { + databaseId: string; + tableId: string; + rows: object[]; + transactionId?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBCreateRowsRequestParams} params - */ -const tablesDBCreateRows = async ({databaseId,tableId,rows,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBCreateRows = async ({databaseId,tableId,rows,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBCreateRowsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows'.replace('{databaseId}', databaseId).replace('{tableId}', tableId); @@ -2350,21 +2152,17 @@ const tablesDBCreateRows = async ({databaseId,tableId,rows,transactionId,parseOu return response; } -/** - * @typedef {Object} TablesDBUpsertRowsRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. - * @property {object[]} rows Array of row data as JSON objects. May contain partial rows. - * @property {string} transactionId Transaction ID for staging the operation. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBUpsertRowsRequestParams { + databaseId: string; + tableId: string; + rows: object[]; + transactionId?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBUpsertRowsRequestParams} params - */ -const tablesDBUpsertRows = async ({databaseId,tableId,rows,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBUpsertRows = async ({databaseId,tableId,rows,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBUpsertRowsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows'.replace('{databaseId}', databaseId).replace('{tableId}', tableId); @@ -2390,22 +2188,18 @@ const tablesDBUpsertRows = async ({databaseId,tableId,rows,transactionId,parseOu return response; } -/** - * @typedef {Object} TablesDBUpdateRowsRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. - * @property {object} data Row data as JSON object. Include only column and value pairs to be updated. - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. - * @property {string} transactionId Transaction ID for staging the operation. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBUpdateRowsRequestParams { + databaseId: string; + tableId: string; + data?: object; + queries?: string[]; + transactionId?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBUpdateRowsRequestParams} params - */ -const tablesDBUpdateRows = async ({databaseId,tableId,data,queries,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBUpdateRows = async ({databaseId,tableId,data,queries,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBUpdateRowsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows'.replace('{databaseId}', databaseId).replace('{tableId}', tableId); @@ -2434,21 +2228,17 @@ const tablesDBUpdateRows = async ({databaseId,tableId,data,queries,transactionId return response; } -/** - * @typedef {Object} TablesDBDeleteRowsRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable). - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. - * @property {string} transactionId Transaction ID for staging the operation. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBDeleteRowsRequestParams { + databaseId: string; + tableId: string; + queries?: string[]; + transactionId?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBDeleteRowsRequestParams} params - */ -const tablesDBDeleteRows = async ({databaseId,tableId,queries,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBDeleteRows = async ({databaseId,tableId,queries,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBDeleteRowsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows'.replace('{databaseId}', databaseId).replace('{tableId}', tableId); @@ -2474,22 +2264,19 @@ const tablesDBDeleteRows = async ({databaseId,tableId,queries,transactionId,pars return response; } -/** - * @typedef {Object} TablesDBGetRowRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable). - * @property {string} rowId Row ID. - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. - * @property {string} transactionId Transaction ID to read uncommitted changes within the transaction. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBGetRowRequestParams { + databaseId: string; + tableId: string; + rowId: string; + queries?: string[]; + transactionId?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {TablesDBGetRowRequestParams} params - */ -const tablesDBGetRow = async ({databaseId,tableId,rowId,queries,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const tablesDBGetRow = async ({databaseId,tableId,rowId,queries,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: TablesDBGetRowRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}'.replace('{databaseId}', databaseId).replace('{tableId}', tableId).replace('{rowId}', rowId); @@ -2507,7 +2294,7 @@ const tablesDBGetRow = async ({databaseId,tableId,rowId,queries,transactionId,pa }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('tablesDB', 'getRow', databaseId, tableId, rowId); } else { parse(response) @@ -2517,23 +2304,19 @@ const tablesDBGetRow = async ({databaseId,tableId,rowId,queries,transactionId,pa return response; } -/** - * @typedef {Object} TablesDBUpsertRowRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. - * @property {string} rowId Row ID. - * @property {object} data Row data as JSON object. Include all required columns of the row to be created or updated. - * @property {string[]} permissions An array of permissions strings. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions). - * @property {string} transactionId Transaction ID for staging the operation. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBUpsertRowRequestParams { + databaseId: string; + tableId: string; + rowId: string; + data?: object; + permissions?: string[]; + transactionId?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBUpsertRowRequestParams} params - */ -const tablesDBUpsertRow = async ({databaseId,tableId,rowId,data,permissions,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBUpsertRow = async ({databaseId,tableId,rowId,data,permissions,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBUpsertRowRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}'.replace('{databaseId}', databaseId).replace('{tableId}', tableId).replace('{rowId}', rowId); @@ -2562,23 +2345,19 @@ const tablesDBUpsertRow = async ({databaseId,tableId,rowId,data,permissions,tran return response; } -/** - * @typedef {Object} TablesDBUpdateRowRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. - * @property {string} rowId Row ID. - * @property {object} data Row data as JSON object. Include only columns and value pairs to be updated. - * @property {string[]} permissions An array of permissions strings. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions). - * @property {string} transactionId Transaction ID for staging the operation. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBUpdateRowRequestParams { + databaseId: string; + tableId: string; + rowId: string; + data?: object; + permissions?: string[]; + transactionId?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBUpdateRowRequestParams} params - */ -const tablesDBUpdateRow = async ({databaseId,tableId,rowId,data,permissions,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBUpdateRow = async ({databaseId,tableId,rowId,data,permissions,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBUpdateRowRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}'.replace('{databaseId}', databaseId).replace('{tableId}', tableId).replace('{rowId}', rowId); @@ -2607,21 +2386,17 @@ const tablesDBUpdateRow = async ({databaseId,tableId,rowId,data,permissions,tran return response; } -/** - * @typedef {Object} TablesDBDeleteRowRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable). - * @property {string} rowId Row ID. - * @property {string} transactionId Transaction ID for staging the operation. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBDeleteRowRequestParams { + databaseId: string; + tableId: string; + rowId: string; + transactionId?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBDeleteRowRequestParams} params - */ -const tablesDBDeleteRow = async ({databaseId,tableId,rowId,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBDeleteRow = async ({databaseId,tableId,rowId,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBDeleteRowRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}'.replace('{databaseId}', databaseId).replace('{tableId}', tableId).replace('{rowId}', rowId); @@ -2643,21 +2418,18 @@ const tablesDBDeleteRow = async ({databaseId,tableId,rowId,transactionId,parseOu return response; } -/** - * @typedef {Object} TablesDBListRowLogsRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. - * @property {string} rowId Row ID. - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Only supported methods are limit and offset - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBListRowLogsRequestParams { + databaseId: string; + tableId: string; + rowId: string; + queries?: string[]; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {TablesDBListRowLogsRequestParams} params - */ -const tablesDBListRowLogs = async ({databaseId,tableId,rowId,queries,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const tablesDBListRowLogs = async ({databaseId,tableId,rowId,queries,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: TablesDBListRowLogsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/logs'.replace('{databaseId}', databaseId).replace('{tableId}', tableId).replace('{rowId}', rowId); @@ -2672,7 +2444,7 @@ const tablesDBListRowLogs = async ({databaseId,tableId,rowId,queries,parseOutput }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('tablesDB', 'listRowLogs', databaseId, tableId, rowId); } else { parse(response) @@ -2682,24 +2454,20 @@ const tablesDBListRowLogs = async ({databaseId,tableId,rowId,queries,parseOutput return response; } -/** - * @typedef {Object} TablesDBDecrementRowColumnRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. - * @property {string} rowId Row ID. - * @property {string} column Column key. - * @property {number} value Value to increment the column by. The value must be a number. - * @property {number} min Minimum value for the column. If the current value is lesser than this value, an exception will be thrown. - * @property {string} transactionId Transaction ID for staging the operation. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBDecrementRowColumnRequestParams { + databaseId: string; + tableId: string; + rowId: string; + column: string; + value?: number; + min?: number; + transactionId?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBDecrementRowColumnRequestParams} params - */ -const tablesDBDecrementRowColumn = async ({databaseId,tableId,rowId,column,value,min,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBDecrementRowColumn = async ({databaseId,tableId,rowId,column,value,min,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBDecrementRowColumnRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/decrement'.replace('{databaseId}', databaseId).replace('{tableId}', tableId).replace('{rowId}', rowId).replace('{column}', column); @@ -2727,24 +2495,20 @@ const tablesDBDecrementRowColumn = async ({databaseId,tableId,rowId,column,value return response; } -/** - * @typedef {Object} TablesDBIncrementRowColumnRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. - * @property {string} rowId Row ID. - * @property {string} column Column key. - * @property {number} value Value to increment the column by. The value must be a number. - * @property {number} max Maximum value for the column. If the current value is greater than this value, an error will be thrown. - * @property {string} transactionId Transaction ID for staging the operation. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBIncrementRowColumnRequestParams { + databaseId: string; + tableId: string; + rowId: string; + column: string; + value?: number; + max?: number; + transactionId?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBIncrementRowColumnRequestParams} params - */ -const tablesDBIncrementRowColumn = async ({databaseId,tableId,rowId,column,value,max,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBIncrementRowColumn = async ({databaseId,tableId,rowId,column,value,max,transactionId,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBIncrementRowColumnRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/increment'.replace('{databaseId}', databaseId).replace('{tableId}', tableId).replace('{rowId}', rowId).replace('{column}', column); @@ -2772,20 +2536,17 @@ const tablesDBIncrementRowColumn = async ({databaseId,tableId,rowId,column,value return response; } -/** - * @typedef {Object} TablesDBGetTableUsageRequestParams - * @property {string} databaseId Database ID. - * @property {string} tableId Table ID. - * @property {UsageRange} range Date range. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBGetTableUsageRequestParams { + databaseId: string; + tableId: string; + range?: UsageRange; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {TablesDBGetTableUsageRequestParams} params - */ -const tablesDBGetTableUsage = async ({databaseId,tableId,range,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const tablesDBGetTableUsage = async ({databaseId,tableId,range,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: TablesDBGetTableUsageRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/usage'.replace('{databaseId}', databaseId).replace('{tableId}', tableId); @@ -2800,7 +2561,7 @@ const tablesDBGetTableUsage = async ({databaseId,tableId,range,parseOutput = tru }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('tablesDB', 'getTableUsage', databaseId, tableId); } else { parse(response) @@ -2810,19 +2571,15 @@ const tablesDBGetTableUsage = async ({databaseId,tableId,range,parseOutput = tru return response; } -/** - * @typedef {Object} TablesDBGetUsageRequestParams - * @property {string} databaseId Database ID. - * @property {UsageRange} range Date range. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface TablesDBGetUsageRequestParams { + databaseId: string; + range?: UsageRange; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {TablesDBGetUsageRequestParams} params - */ -const tablesDBGetUsage = async ({databaseId,range,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const tablesDBGetUsage = async ({databaseId,range,parseOutput = true, overrideForCli = false, sdk = undefined}: TablesDBGetUsageRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tablesdb/{databaseId}/usage'.replace('{databaseId}', databaseId); @@ -2848,7 +2605,7 @@ tablesDB .description(`Get a list of all databases from the current Appwrite project. You can use the search parameter to filter your results.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following columns: name`) .option(`--search `, `Search term to filter your list results. Max length: 256 chars.`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--console`, `Get the resource console url`) .action(actionRunner(tablesDBList)) @@ -2857,7 +2614,7 @@ tablesDB .description(`Create a new Database. `) .requiredOption(`--database-id `, `Unique Id. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars.`) .requiredOption(`--name `, `Database name. Max length: 128 chars.`) - .option(`--enabled [value]`, `Is the database enabled? When set to 'disabled', users cannot access the database but Server SDKs with an API key can still read and write to the database. No data is lost when this is toggled.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Is the database enabled? When set to 'disabled', users cannot access the database but Server SDKs with an API key can still read and write to the database. No data is lost when this is toggled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(tablesDBCreate)) tablesDB @@ -2884,8 +2641,8 @@ tablesDB .command(`update-transaction`) .description(`Update a transaction, to either commit or roll back its operations.`) .requiredOption(`--transaction-id `, `Transaction ID.`) - .option(`--commit [value]`, `Commit transaction?`, (value) => value === undefined ? true : parseBool(value)) - .option(`--rollback [value]`, `Rollback transaction?`, (value) => value === undefined ? true : parseBool(value)) + .option(`--commit [value]`, `Commit transaction?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--rollback [value]`, `Rollback transaction?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(tablesDBUpdateTransaction)) tablesDB @@ -2920,7 +2677,7 @@ tablesDB .description(`Update a database by its unique ID.`) .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--name `, `Database name. Max length: 128 chars.`) - .option(`--enabled [value]`, `Is database enabled? When set to 'disabled', users cannot access the database but Server SDKs with an API key can still read and write to the database. No data is lost when this is toggled.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Is database enabled? When set to 'disabled', users cannot access the database but Server SDKs with an API key can still read and write to the database. No data is lost when this is toggled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(tablesDBUpdate)) tablesDB @@ -2935,7 +2692,7 @@ tablesDB .requiredOption(`--database-id `, `Database ID.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following columns: name, enabled, rowSecurity`) .option(`--search `, `Search term to filter your list results. Max length: 256 chars.`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--console`, `Get the resource console url`) .action(actionRunner(tablesDBListTables)) @@ -2946,8 +2703,10 @@ tablesDB .requiredOption(`--table-id `, `Unique Id. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars.`) .requiredOption(`--name `, `Table name. Max length: 128 chars.`) .option(`--permissions [permissions...]`, `An array of permissions strings. By default, no user is granted with any permissions. [Learn more about permissions](https://appwrite.io/docs/permissions).`) - .option(`--row-security [value]`, `Enables configuring permissions for individual rows. A user needs one of row or table level permissions to access a row. [Learn more about permissions](https://appwrite.io/docs/permissions).`, (value) => value === undefined ? true : parseBool(value)) - .option(`--enabled [value]`, `Is table enabled? When set to 'disabled', users cannot access the table but Server SDKs with and API key can still read and write to the table. No data is lost when this is toggled.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--row-security [value]`, `Enables configuring permissions for individual rows. A user needs one of row or table level permissions to access a row. [Learn more about permissions](https://appwrite.io/docs/permissions).`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Is table enabled? When set to 'disabled', users cannot access the table but Server SDKs with and API key can still read and write to the table. No data is lost when this is toggled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--columns [columns...]`, `Array of column definitions to create. Each column should contain: key (string), type (string: string, integer, float, boolean, datetime, relationship), size (integer, required for string type), required (boolean, optional), default (mixed, optional), array (boolean, optional), and type-specific options.`) + .option(`--indexes [indexes...]`, `Array of index definitions to create. Each index should contain: key (string), type (string: key, fulltext, unique, spatial), attributes (array of column keys), orders (array of ASC/DESC, optional), and lengths (array of integers, optional).`) .action(actionRunner(tablesDBCreateTable)) tablesDB @@ -2965,8 +2724,8 @@ tablesDB .requiredOption(`--table-id `, `Table ID.`) .requiredOption(`--name `, `Table name. Max length: 128 chars.`) .option(`--permissions [permissions...]`, `An array of permission strings. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions).`) - .option(`--row-security [value]`, `Enables configuring permissions for individual rows. A user needs one of row or table-level permissions to access a row. [Learn more about permissions](https://appwrite.io/docs/permissions).`, (value) => value === undefined ? true : parseBool(value)) - .option(`--enabled [value]`, `Is table enabled? When set to 'disabled', users cannot access the table but Server SDKs with and API key can still read and write to the table. No data is lost when this is toggled.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--row-security [value]`, `Enables configuring permissions for individual rows. A user needs one of row or table-level permissions to access a row. [Learn more about permissions](https://appwrite.io/docs/permissions).`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--enabled [value]`, `Is table enabled? When set to 'disabled', users cannot access the table but Server SDKs with and API key can still read and write to the table. No data is lost when this is toggled.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(tablesDBUpdateTable)) tablesDB @@ -2982,7 +2741,7 @@ tablesDB .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--table-id `, `Table ID.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following columns: key, type, size, required, array, status, error`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--console`, `Get the resource console url`) .action(actionRunner(tablesDBListColumns)) @@ -2992,9 +2751,9 @@ tablesDB .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--table-id `, `Table ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable).`) .requiredOption(`--key `, `Column Key.`) - .requiredOption(`--required [value]`, `Is column required?`, (value) => value === undefined ? true : parseBool(value)) - .option(`--xdefault [value]`, `Default value for column when not provided. Cannot be set when column is required.`, (value) => value === undefined ? true : parseBool(value)) - .option(`--array [value]`, `Is column an array?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is column required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--xdefault [value]`, `Default value for column when not provided. Cannot be set when column is required.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--array [value]`, `Is column an array?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(tablesDBCreateBooleanColumn)) tablesDB @@ -3003,8 +2762,8 @@ tablesDB .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--table-id `, `Table ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable).`) .requiredOption(`--key `, `Column Key.`) - .requiredOption(`--required [value]`, `Is column required?`, (value) => value === undefined ? true : parseBool(value)) - .option(`--xdefault [value]`, `Default value for column when not provided. Cannot be set when column is required.`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is column required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--xdefault [value]`, `Default value for column when not provided. Cannot be set when column is required.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--new-key `, `New Column Key.`) .action(actionRunner(tablesDBUpdateBooleanColumn)) @@ -3014,9 +2773,9 @@ tablesDB .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--table-id `, `Table ID.`) .requiredOption(`--key `, `Column Key.`) - .requiredOption(`--required [value]`, `Is column required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is column required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value for the column in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. Cannot be set when column is required.`) - .option(`--array [value]`, `Is column an array?`, (value) => value === undefined ? true : parseBool(value)) + .option(`--array [value]`, `Is column an array?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(tablesDBCreateDatetimeColumn)) tablesDB @@ -3025,7 +2784,7 @@ tablesDB .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--table-id `, `Table ID.`) .requiredOption(`--key `, `Column Key.`) - .requiredOption(`--required [value]`, `Is column required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is column required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value for column when not provided. Cannot be set when column is required.`) .option(`--new-key `, `New Column Key.`) .action(actionRunner(tablesDBUpdateDatetimeColumn)) @@ -3036,9 +2795,9 @@ tablesDB .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--table-id `, `Table ID.`) .requiredOption(`--key `, `Column Key.`) - .requiredOption(`--required [value]`, `Is column required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is column required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value for column when not provided. Cannot be set when column is required.`) - .option(`--array [value]`, `Is column an array?`, (value) => value === undefined ? true : parseBool(value)) + .option(`--array [value]`, `Is column an array?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(tablesDBCreateEmailColumn)) tablesDB @@ -3047,7 +2806,7 @@ tablesDB .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--table-id `, `Table ID.`) .requiredOption(`--key `, `Column Key.`) - .requiredOption(`--required [value]`, `Is column required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is column required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value for column when not provided. Cannot be set when column is required.`) .option(`--new-key `, `New Column Key.`) .action(actionRunner(tablesDBUpdateEmailColumn)) @@ -3059,9 +2818,9 @@ tablesDB .requiredOption(`--table-id `, `Table ID.`) .requiredOption(`--key `, `Column Key.`) .requiredOption(`--elements [elements...]`, `Array of enum values.`) - .requiredOption(`--required [value]`, `Is column required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is column required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value for column when not provided. Cannot be set when column is required.`) - .option(`--array [value]`, `Is column an array?`, (value) => value === undefined ? true : parseBool(value)) + .option(`--array [value]`, `Is column an array?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(tablesDBCreateEnumColumn)) tablesDB @@ -3071,7 +2830,7 @@ tablesDB .requiredOption(`--table-id `, `Table ID.`) .requiredOption(`--key `, `Column Key.`) .requiredOption(`--elements [elements...]`, `Updated list of enum values.`) - .requiredOption(`--required [value]`, `Is column required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is column required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value for column when not provided. Cannot be set when column is required.`) .option(`--new-key `, `New Column Key.`) .action(actionRunner(tablesDBUpdateEnumColumn)) @@ -3082,11 +2841,11 @@ tablesDB .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--table-id `, `Table ID.`) .requiredOption(`--key `, `Column Key.`) - .requiredOption(`--required [value]`, `Is column required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is column required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--min `, `Minimum value`, parseInteger) .option(`--max `, `Maximum value`, parseInteger) .option(`--xdefault `, `Default value. Cannot be set when required.`, parseInteger) - .option(`--array [value]`, `Is column an array?`, (value) => value === undefined ? true : parseBool(value)) + .option(`--array [value]`, `Is column an array?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(tablesDBCreateFloatColumn)) tablesDB @@ -3095,7 +2854,7 @@ tablesDB .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--table-id `, `Table ID.`) .requiredOption(`--key `, `Column Key.`) - .requiredOption(`--required [value]`, `Is column required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is column required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value. Cannot be set when required.`, parseInteger) .option(`--min `, `Minimum value`, parseInteger) .option(`--max `, `Maximum value`, parseInteger) @@ -3108,11 +2867,11 @@ tablesDB .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--table-id `, `Table ID.`) .requiredOption(`--key `, `Column Key.`) - .requiredOption(`--required [value]`, `Is column required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is column required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--min `, `Minimum value`, parseInteger) .option(`--max `, `Maximum value`, parseInteger) .option(`--xdefault `, `Default value. Cannot be set when column is required.`, parseInteger) - .option(`--array [value]`, `Is column an array?`, (value) => value === undefined ? true : parseBool(value)) + .option(`--array [value]`, `Is column an array?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(tablesDBCreateIntegerColumn)) tablesDB @@ -3121,7 +2880,7 @@ tablesDB .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--table-id `, `Table ID.`) .requiredOption(`--key `, `Column Key.`) - .requiredOption(`--required [value]`, `Is column required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is column required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value. Cannot be set when column is required.`, parseInteger) .option(`--min `, `Minimum value`, parseInteger) .option(`--max `, `Maximum value`, parseInteger) @@ -3134,9 +2893,9 @@ tablesDB .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--table-id `, `Table ID.`) .requiredOption(`--key `, `Column Key.`) - .requiredOption(`--required [value]`, `Is column required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is column required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value. Cannot be set when column is required.`) - .option(`--array [value]`, `Is column an array?`, (value) => value === undefined ? true : parseBool(value)) + .option(`--array [value]`, `Is column an array?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(tablesDBCreateIpColumn)) tablesDB @@ -3145,7 +2904,7 @@ tablesDB .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--table-id `, `Table ID.`) .requiredOption(`--key `, `Column Key.`) - .requiredOption(`--required [value]`, `Is column required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is column required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value. Cannot be set when column is required.`) .option(`--new-key `, `New Column Key.`) .action(actionRunner(tablesDBUpdateIpColumn)) @@ -3156,7 +2915,7 @@ tablesDB .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--table-id `, `Table ID. You can create a new table using the TablesDB service [server integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable).`) .requiredOption(`--key `, `Column Key.`) - .requiredOption(`--required [value]`, `Is column required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is column required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value for column when not provided, two-dimensional array of coordinate pairs, [[longitude, latitude], [longitude, latitude], …], listing the vertices of the line in order. Cannot be set when column is required.`) .action(actionRunner(tablesDBCreateLineColumn)) @@ -3166,7 +2925,7 @@ tablesDB .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--table-id `, `Table ID. You can create a new table using the TablesDB service [server integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable).`) .requiredOption(`--key `, `Column Key.`) - .requiredOption(`--required [value]`, `Is column required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is column required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value for column when not provided, two-dimensional array of coordinate pairs, [[longitude, latitude], [longitude, latitude], …], listing the vertices of the line in order. Cannot be set when column is required.`) .option(`--new-key `, `New Column Key.`) .action(actionRunner(tablesDBUpdateLineColumn)) @@ -3177,7 +2936,7 @@ tablesDB .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--table-id `, `Table ID. You can create a new table using the TablesDB service [server integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable).`) .requiredOption(`--key `, `Column Key.`) - .requiredOption(`--required [value]`, `Is column required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is column required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value for column when not provided, array of two numbers [longitude, latitude], representing a single coordinate. Cannot be set when column is required.`) .action(actionRunner(tablesDBCreatePointColumn)) @@ -3187,7 +2946,7 @@ tablesDB .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--table-id `, `Table ID. You can create a new table using the TablesDB service [server integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable).`) .requiredOption(`--key `, `Column Key.`) - .requiredOption(`--required [value]`, `Is column required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is column required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value for column when not provided, array of two numbers [longitude, latitude], representing a single coordinate. Cannot be set when column is required.`) .option(`--new-key `, `New Column Key.`) .action(actionRunner(tablesDBUpdatePointColumn)) @@ -3198,7 +2957,7 @@ tablesDB .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--table-id `, `Table ID. You can create a new table using the TablesDB service [server integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable).`) .requiredOption(`--key `, `Column Key.`) - .requiredOption(`--required [value]`, `Is column required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is column required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value for column when not provided, three-dimensional array where the outer array holds one or more linear rings, [[[longitude, latitude], …], …], the first ring is the exterior boundary, any additional rings are interior holes, and each ring must start and end with the same coordinate pair. Cannot be set when column is required.`) .action(actionRunner(tablesDBCreatePolygonColumn)) @@ -3208,7 +2967,7 @@ tablesDB .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--table-id `, `Table ID. You can create a new table using the TablesDB service [server integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable).`) .requiredOption(`--key `, `Column Key.`) - .requiredOption(`--required [value]`, `Is column required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is column required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value for column when not provided, three-dimensional array where the outer array holds one or more linear rings, [[[longitude, latitude], …], …], the first ring is the exterior boundary, any additional rings are interior holes, and each ring must start and end with the same coordinate pair. Cannot be set when column is required.`) .option(`--new-key `, `New Column Key.`) .action(actionRunner(tablesDBUpdatePolygonColumn)) @@ -3220,7 +2979,7 @@ tablesDB .requiredOption(`--table-id `, `Table ID.`) .requiredOption(`--related-table-id `, `Related Table ID.`) .requiredOption(`--type `, `Relation type`) - .option(`--two-way [value]`, `Is Two Way?`, (value) => value === undefined ? true : parseBool(value)) + .option(`--two-way [value]`, `Is Two Way?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--key `, `Column Key.`) .option(`--two-way-key `, `Two Way Column Key.`) .option(`--on-delete `, `Constraints option`) @@ -3233,10 +2992,10 @@ tablesDB .requiredOption(`--table-id `, `Table ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable).`) .requiredOption(`--key `, `Column Key.`) .requiredOption(`--size `, `Column size for text columns, in number of characters.`, parseInteger) - .requiredOption(`--required [value]`, `Is column required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is column required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value for column when not provided. Cannot be set when column is required.`) - .option(`--array [value]`, `Is column an array?`, (value) => value === undefined ? true : parseBool(value)) - .option(`--encrypt [value]`, `Toggle encryption for the column. Encryption enhances security by not storing any plain text values in the database. However, encrypted columns cannot be queried.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--array [value]`, `Is column an array?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) + .option(`--encrypt [value]`, `Toggle encryption for the column. Encryption enhances security by not storing any plain text values in the database. However, encrypted columns cannot be queried.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(tablesDBCreateStringColumn)) tablesDB @@ -3245,7 +3004,7 @@ tablesDB .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--table-id `, `Table ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable).`) .requiredOption(`--key `, `Column Key.`) - .requiredOption(`--required [value]`, `Is column required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is column required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value for column when not provided. Cannot be set when column is required.`) .option(`--size `, `Maximum size of the string column.`, parseInteger) .option(`--new-key `, `New Column Key.`) @@ -3257,9 +3016,9 @@ tablesDB .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--table-id `, `Table ID.`) .requiredOption(`--key `, `Column Key.`) - .requiredOption(`--required [value]`, `Is column required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is column required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value for column when not provided. Cannot be set when column is required.`) - .option(`--array [value]`, `Is column an array?`, (value) => value === undefined ? true : parseBool(value)) + .option(`--array [value]`, `Is column an array?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(tablesDBCreateUrlColumn)) tablesDB @@ -3268,7 +3027,7 @@ tablesDB .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--table-id `, `Table ID.`) .requiredOption(`--key `, `Column Key.`) - .requiredOption(`--required [value]`, `Is column required?`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--required [value]`, `Is column required?`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--xdefault `, `Default value for column when not provided. Cannot be set when column is required.`) .option(`--new-key `, `New Column Key.`) .action(actionRunner(tablesDBUpdateUrlColumn)) @@ -3306,7 +3065,7 @@ tablesDB .requiredOption(`--database-id `, `Database ID.`) .requiredOption(`--table-id `, `Table ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/references/cloud/server-dart/tablesDB#createTable).`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following columns: key, type, status, attributes, error`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--console`, `Get the resource console url`) .action(actionRunner(tablesDBListIndexes)) @@ -3354,7 +3113,7 @@ tablesDB .requiredOption(`--table-id `, `Table ID. You can create a new table using the TablesDB service [server integration](https://appwrite.io/docs/products/databases/tables#create-table).`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long.`) .option(`--transaction-id `, `Transaction ID to read uncommitted changes within the transaction.`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--console`, `Get the resource console url`) .action(actionRunner(tablesDBListRows)) @@ -3498,72 +3257,4 @@ tablesDB .option(`--range `, `Date range.`) .action(actionRunner(tablesDBGetUsage)) -module.exports = { - tablesDB, - tablesDBList, - tablesDBCreate, - tablesDBListTransactions, - tablesDBCreateTransaction, - tablesDBGetTransaction, - tablesDBUpdateTransaction, - tablesDBDeleteTransaction, - tablesDBCreateOperations, - tablesDBListUsage, - tablesDBGet, - tablesDBUpdate, - tablesDBDelete, - tablesDBListTables, - tablesDBCreateTable, - tablesDBGetTable, - tablesDBUpdateTable, - tablesDBDeleteTable, - tablesDBListColumns, - tablesDBCreateBooleanColumn, - tablesDBUpdateBooleanColumn, - tablesDBCreateDatetimeColumn, - tablesDBUpdateDatetimeColumn, - tablesDBCreateEmailColumn, - tablesDBUpdateEmailColumn, - tablesDBCreateEnumColumn, - tablesDBUpdateEnumColumn, - tablesDBCreateFloatColumn, - tablesDBUpdateFloatColumn, - tablesDBCreateIntegerColumn, - tablesDBUpdateIntegerColumn, - tablesDBCreateIpColumn, - tablesDBUpdateIpColumn, - tablesDBCreateLineColumn, - tablesDBUpdateLineColumn, - tablesDBCreatePointColumn, - tablesDBUpdatePointColumn, - tablesDBCreatePolygonColumn, - tablesDBUpdatePolygonColumn, - tablesDBCreateRelationshipColumn, - tablesDBCreateStringColumn, - tablesDBUpdateStringColumn, - tablesDBCreateUrlColumn, - tablesDBUpdateUrlColumn, - tablesDBGetColumn, - tablesDBDeleteColumn, - tablesDBUpdateRelationshipColumn, - tablesDBListIndexes, - tablesDBCreateIndex, - tablesDBGetIndex, - tablesDBDeleteIndex, - tablesDBListTableLogs, - tablesDBListRows, - tablesDBCreateRow, - tablesDBCreateRows, - tablesDBUpsertRows, - tablesDBUpdateRows, - tablesDBDeleteRows, - tablesDBGetRow, - tablesDBUpsertRow, - tablesDBUpdateRow, - tablesDBDeleteRow, - tablesDBListRowLogs, - tablesDBDecrementRowColumn, - tablesDBIncrementRowColumn, - tablesDBGetTableUsage, - tablesDBGetUsage -}; + diff --git a/lib/commands/teams.js b/lib/commands/teams.ts similarity index 60% rename from lib/commands/teams.js rename to lib/commands/teams.ts index 9e3e3851..0f10a3ae 100644 --- a/lib/commands/teams.js +++ b/lib/commands/teams.ts @@ -1,31 +1,27 @@ -const fs = require('fs'); -const pathLib = require('path'); -const tar = require("tar"); -const ignore = require("ignore"); -const { promisify } = require('util'); -const libClient = require('../client.js'); -const { getAllFiles, showConsoleLink } = require('../utils.js'); -const { Command } = require('commander'); -const { sdkForProject, sdkForConsole } = require('../sdks') -const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } = require('../parser') -const { localConfig, globalConfig } = require("../config"); -const { File } = require('undici'); -const { ReadableStream } = require('stream/web'); - -/** - * @param {fs.ReadStream} readStream - * @returns {ReadableStream} - */ -function convertReadStreamToReadableStream(readStream) { +import fs = require('fs'); +import pathLib = require('path'); +import tar = require('tar'); +import ignore = require('ignore'); +import { promisify } from 'util'; +import Client from '../client'; +import { getAllFiles, showConsoleLink } from '../utils'; +import { Command } from 'commander'; +import { sdkForProject, sdkForConsole } from '../sdks'; +import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } from '../parser'; +import { localConfig, globalConfig } from '../config'; +import { File } from 'undici'; +import { ReadableStream } from 'stream/web'; + +function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ start(controller) { - readStream.on("data", (chunk) => { + readStream.on("data", (chunk: Buffer) => { controller.enqueue(chunk); }); readStream.on("end", () => { controller.close(); }); - readStream.on("error", (err) => { + readStream.on("error", (err: Error) => { controller.error(err); }); }, @@ -35,24 +31,21 @@ function convertReadStreamToReadableStream(readStream) { }); } -const teams = new Command("teams").description(commandDescriptions['teams'] ?? '').configureHelp({ +export const teams = new Command("teams").description(commandDescriptions['teams'] ?? '').configureHelp({ helpWidth: process.stdout.columns || 80 }) -/** - * @typedef {Object} TeamsListRequestParams - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name, total, billingPlan - * @property {string} search Search term to filter your list results. Max length: 256 chars. - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {TeamsListRequestParams} params - */ -const teamsList = async ({queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface TeamsListRequestParams { + queries?: string[]; + search?: string; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const teamsList = async ({queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: TeamsListRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/teams'; @@ -73,7 +66,7 @@ const teamsList = async ({queries,search,total,parseOutput = true, overrideForCl }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('teams', 'list'); } else { parse(response) @@ -83,20 +76,16 @@ const teamsList = async ({queries,search,total,parseOutput = true, overrideForCl return response; } -/** - * @typedef {Object} TeamsCreateRequestParams - * @property {string} teamId Team ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} name Team name. Max length: 128 chars. - * @property {string[]} roles Array of strings. Use this param to set the roles in the team for the user who created it. The default role is **owner**. A role can be any string. Learn more about [roles and permissions](https://appwrite.io/docs/permissions). Maximum of 100 roles are allowed, each 32 characters long. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {TeamsCreateRequestParams} params - */ -const teamsCreate = async ({teamId,name,roles,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface TeamsCreateRequestParams { + teamId: string; + name: string; + roles?: string[]; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const teamsCreate = async ({teamId,name,roles,parseOutput = true, overrideForCli = false, sdk = undefined}: TeamsCreateRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/teams'; @@ -125,18 +114,15 @@ const teamsCreate = async ({teamId,name,roles,parseOutput = true, overrideForCli return response; } -/** - * @typedef {Object} TeamsGetRequestParams - * @property {string} teamId Team ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {TeamsGetRequestParams} params - */ -const teamsGet = async ({teamId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface TeamsGetRequestParams { + teamId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const teamsGet = async ({teamId,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: TeamsGetRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/teams/{teamId}'.replace('{teamId}', teamId); @@ -148,7 +134,7 @@ const teamsGet = async ({teamId,parseOutput = true, overrideForCli = false, sdk }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('teams', 'get', teamId); } else { parse(response) @@ -158,19 +144,15 @@ const teamsGet = async ({teamId,parseOutput = true, overrideForCli = false, sdk return response; } -/** - * @typedef {Object} TeamsUpdateNameRequestParams - * @property {string} teamId Team ID. - * @property {string} name New team name. Max length: 128 chars. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {TeamsUpdateNameRequestParams} params - */ -const teamsUpdateName = async ({teamId,name,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface TeamsUpdateNameRequestParams { + teamId: string; + name: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const teamsUpdateName = async ({teamId,name,parseOutput = true, overrideForCli = false, sdk = undefined}: TeamsUpdateNameRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/teams/{teamId}'.replace('{teamId}', teamId); @@ -192,18 +174,14 @@ const teamsUpdateName = async ({teamId,name,parseOutput = true, overrideForCli = return response; } -/** - * @typedef {Object} TeamsDeleteRequestParams - * @property {string} teamId Team ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {TeamsDeleteRequestParams} params - */ -const teamsDelete = async ({teamId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface TeamsDeleteRequestParams { + teamId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const teamsDelete = async ({teamId,parseOutput = true, overrideForCli = false, sdk = undefined}: TeamsDeleteRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/teams/{teamId}'.replace('{teamId}', teamId); @@ -222,20 +200,16 @@ const teamsDelete = async ({teamId,parseOutput = true, overrideForCli = false, s return response; } -/** - * @typedef {Object} TeamsListLogsRequestParams - * @property {string} teamId Team ID. - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Only supported methods are limit and offset - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {TeamsListLogsRequestParams} params - */ -const teamsListLogs = async ({teamId,queries,total,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface TeamsListLogsRequestParams { + teamId: string; + queries?: string[]; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const teamsListLogs = async ({teamId,queries,total,parseOutput = true, overrideForCli = false, sdk = undefined}: TeamsListLogsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/teams/{teamId}/logs'.replace('{teamId}', teamId); @@ -259,21 +233,17 @@ const teamsListLogs = async ({teamId,queries,total,parseOutput = true, overrideF return response; } -/** - * @typedef {Object} TeamsListMembershipsRequestParams - * @property {string} teamId Team ID. - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: userId, teamId, invited, joined, confirm, roles - * @property {string} search Search term to filter your list results. Max length: 256 chars. - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {TeamsListMembershipsRequestParams} params - */ -const teamsListMemberships = async ({teamId,queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface TeamsListMembershipsRequestParams { + teamId: string; + queries?: string[]; + search?: string; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const teamsListMemberships = async ({teamId,queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined}: TeamsListMembershipsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/teams/{teamId}/memberships'.replace('{teamId}', teamId); @@ -300,24 +270,20 @@ const teamsListMemberships = async ({teamId,queries,search,total,parseOutput = t return response; } -/** - * @typedef {Object} TeamsCreateMembershipRequestParams - * @property {string} teamId Team ID. - * @property {string[]} roles Array of strings. Use this param to set the user roles in the team. A role can be any string. Learn more about [roles and permissions](https://appwrite.io/docs/permissions). Maximum of 100 roles are allowed, each 32 characters long. - * @property {string} email Email of the new team member. - * @property {string} userId ID of the user to be added to a team. - * @property {string} phone Phone number. Format this number with a leading '+' and a country code, e.g., +16175551212. - * @property {string} url URL to redirect the user back to your app from the invitation email. This parameter is not required when an API key is supplied. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. - * @property {string} name Name of the new team member. Max length: 128 chars. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {TeamsCreateMembershipRequestParams} params - */ -const teamsCreateMembership = async ({teamId,roles,email,userId,phone,url,name,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface TeamsCreateMembershipRequestParams { + teamId: string; + roles: string[]; + email?: string; + userId?: string; + phone?: string; + url?: string; + name?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const teamsCreateMembership = async ({teamId,roles,email,userId,phone,url,name,parseOutput = true, overrideForCli = false, sdk = undefined}: TeamsCreateMembershipRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/teams/{teamId}/memberships'.replace('{teamId}', teamId); @@ -355,19 +321,15 @@ const teamsCreateMembership = async ({teamId,roles,email,userId,phone,url,name,p return response; } -/** - * @typedef {Object} TeamsGetMembershipRequestParams - * @property {string} teamId Team ID. - * @property {string} membershipId Membership ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {TeamsGetMembershipRequestParams} params - */ -const teamsGetMembership = async ({teamId,membershipId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface TeamsGetMembershipRequestParams { + teamId: string; + membershipId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const teamsGetMembership = async ({teamId,membershipId,parseOutput = true, overrideForCli = false, sdk = undefined}: TeamsGetMembershipRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/teams/{teamId}/memberships/{membershipId}'.replace('{teamId}', teamId).replace('{membershipId}', membershipId); @@ -385,20 +347,16 @@ const teamsGetMembership = async ({teamId,membershipId,parseOutput = true, overr return response; } -/** - * @typedef {Object} TeamsUpdateMembershipRequestParams - * @property {string} teamId Team ID. - * @property {string} membershipId Membership ID. - * @property {string[]} roles An array of strings. Use this param to set the user's roles in the team. A role can be any string. Learn more about [roles and permissions](https://appwrite.io/docs/permissions). Maximum of 100 roles are allowed, each 32 characters long. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {TeamsUpdateMembershipRequestParams} params - */ -const teamsUpdateMembership = async ({teamId,membershipId,roles,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface TeamsUpdateMembershipRequestParams { + teamId: string; + membershipId: string; + roles: string[]; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const teamsUpdateMembership = async ({teamId,membershipId,roles,parseOutput = true, overrideForCli = false, sdk = undefined}: TeamsUpdateMembershipRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/teams/{teamId}/memberships/{membershipId}'.replace('{teamId}', teamId).replace('{membershipId}', membershipId); @@ -421,19 +379,15 @@ const teamsUpdateMembership = async ({teamId,membershipId,roles,parseOutput = tr return response; } -/** - * @typedef {Object} TeamsDeleteMembershipRequestParams - * @property {string} teamId Team ID. - * @property {string} membershipId Membership ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {TeamsDeleteMembershipRequestParams} params - */ -const teamsDeleteMembership = async ({teamId,membershipId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface TeamsDeleteMembershipRequestParams { + teamId: string; + membershipId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const teamsDeleteMembership = async ({teamId,membershipId,parseOutput = true, overrideForCli = false, sdk = undefined}: TeamsDeleteMembershipRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/teams/{teamId}/memberships/{membershipId}'.replace('{teamId}', teamId).replace('{membershipId}', membershipId); @@ -452,21 +406,17 @@ const teamsDeleteMembership = async ({teamId,membershipId,parseOutput = true, ov return response; } -/** - * @typedef {Object} TeamsUpdateMembershipStatusRequestParams - * @property {string} teamId Team ID. - * @property {string} membershipId Membership ID. - * @property {string} userId User ID. - * @property {string} secret Secret key. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {TeamsUpdateMembershipStatusRequestParams} params - */ -const teamsUpdateMembershipStatus = async ({teamId,membershipId,userId,secret,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface TeamsUpdateMembershipStatusRequestParams { + teamId: string; + membershipId: string; + userId: string; + secret: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const teamsUpdateMembershipStatus = async ({teamId,membershipId,userId,secret,parseOutput = true, overrideForCli = false, sdk = undefined}: TeamsUpdateMembershipStatusRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/teams/{teamId}/memberships/{membershipId}/status'.replace('{teamId}', teamId).replace('{membershipId}', membershipId); @@ -491,18 +441,14 @@ const teamsUpdateMembershipStatus = async ({teamId,membershipId,userId,secret,pa return response; } -/** - * @typedef {Object} TeamsGetPrefsRequestParams - * @property {string} teamId Team ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {TeamsGetPrefsRequestParams} params - */ -const teamsGetPrefs = async ({teamId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface TeamsGetPrefsRequestParams { + teamId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const teamsGetPrefs = async ({teamId,parseOutput = true, overrideForCli = false, sdk = undefined}: TeamsGetPrefsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/teams/{teamId}/prefs'.replace('{teamId}', teamId); @@ -520,19 +466,15 @@ const teamsGetPrefs = async ({teamId,parseOutput = true, overrideForCli = false, return response; } -/** - * @typedef {Object} TeamsUpdatePrefsRequestParams - * @property {string} teamId Team ID. - * @property {object} prefs Prefs key-value JSON object. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {TeamsUpdatePrefsRequestParams} params - */ -const teamsUpdatePrefs = async ({teamId,prefs,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface TeamsUpdatePrefsRequestParams { + teamId: string; + prefs: object; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const teamsUpdatePrefs = async ({teamId,prefs,parseOutput = true, overrideForCli = false, sdk = undefined}: TeamsUpdatePrefsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/teams/{teamId}/prefs'.replace('{teamId}', teamId); @@ -559,7 +501,7 @@ teams .description(`Get a list of all the teams in which the current user is a member. You can use the parameters to filter your results.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name, total, billingPlan`) .option(`--search `, `Search term to filter your list results. Max length: 256 chars.`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--console`, `Get the resource console url`) .action(actionRunner(teamsList)) @@ -596,7 +538,7 @@ teams .description(`Get the team activity logs list by its unique ID.`) .requiredOption(`--team-id `, `Team ID.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Only supported methods are limit and offset`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(teamsListLogs)) teams @@ -605,7 +547,7 @@ teams .requiredOption(`--team-id `, `Team ID.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: userId, teamId, invited, joined, confirm, roles`) .option(`--search `, `Search term to filter your list results. Max length: 256 chars.`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(teamsListMemberships)) teams @@ -664,20 +606,4 @@ teams .requiredOption(`--prefs `, `Prefs key-value JSON object.`) .action(actionRunner(teamsUpdatePrefs)) -module.exports = { - teams, - teamsList, - teamsCreate, - teamsGet, - teamsUpdateName, - teamsDelete, - teamsListLogs, - teamsListMemberships, - teamsCreateMembership, - teamsGetMembership, - teamsUpdateMembership, - teamsDeleteMembership, - teamsUpdateMembershipStatus, - teamsGetPrefs, - teamsUpdatePrefs -}; + diff --git a/lib/commands/tokens.js b/lib/commands/tokens.ts similarity index 54% rename from lib/commands/tokens.js rename to lib/commands/tokens.ts index fa681a92..4292ce13 100644 --- a/lib/commands/tokens.js +++ b/lib/commands/tokens.ts @@ -1,31 +1,27 @@ -const fs = require('fs'); -const pathLib = require('path'); -const tar = require("tar"); -const ignore = require("ignore"); -const { promisify } = require('util'); -const libClient = require('../client.js'); -const { getAllFiles, showConsoleLink } = require('../utils.js'); -const { Command } = require('commander'); -const { sdkForProject, sdkForConsole } = require('../sdks') -const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } = require('../parser') -const { localConfig, globalConfig } = require("../config"); -const { File } = require('undici'); -const { ReadableStream } = require('stream/web'); - -/** - * @param {fs.ReadStream} readStream - * @returns {ReadableStream} - */ -function convertReadStreamToReadableStream(readStream) { +import fs = require('fs'); +import pathLib = require('path'); +import tar = require('tar'); +import ignore = require('ignore'); +import { promisify } from 'util'; +import Client from '../client'; +import { getAllFiles, showConsoleLink } from '../utils'; +import { Command } from 'commander'; +import { sdkForProject, sdkForConsole } from '../sdks'; +import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } from '../parser'; +import { localConfig, globalConfig } from '../config'; +import { File } from 'undici'; +import { ReadableStream } from 'stream/web'; + +function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ start(controller) { - readStream.on("data", (chunk) => { + readStream.on("data", (chunk: Buffer) => { controller.enqueue(chunk); }); readStream.on("end", () => { controller.close(); }); - readStream.on("error", (err) => { + readStream.on("error", (err: Error) => { controller.error(err); }); }, @@ -35,25 +31,22 @@ function convertReadStreamToReadableStream(readStream) { }); } -const tokens = new Command("tokens").description(commandDescriptions['tokens'] ?? '').configureHelp({ +export const tokens = new Command("tokens").description(commandDescriptions['tokens'] ?? '').configureHelp({ helpWidth: process.stdout.columns || 80 }) -/** - * @typedef {Object} TokensListRequestParams - * @property {string} bucketId Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). - * @property {string} fileId File unique ID. - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: expire - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {TokensListRequestParams} params - */ -const tokensList = async ({bucketId,fileId,queries,total,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface TokensListRequestParams { + bucketId: string; + fileId: string; + queries?: string[]; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const tokensList = async ({bucketId,fileId,queries,total,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: TokensListRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tokens/buckets/{bucketId}/files/{fileId}'.replace('{bucketId}', bucketId).replace('{fileId}', fileId); @@ -71,7 +64,7 @@ const tokensList = async ({bucketId,fileId,queries,total,parseOutput = true, ove }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('tokens', 'list', bucketId, fileId); } else { parse(response) @@ -81,20 +74,16 @@ const tokensList = async ({bucketId,fileId,queries,total,parseOutput = true, ove return response; } -/** - * @typedef {Object} TokensCreateFileTokenRequestParams - * @property {string} bucketId Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). - * @property {string} fileId File unique ID. - * @property {string} expire Token expiry date - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {TokensCreateFileTokenRequestParams} params - */ -const tokensCreateFileToken = async ({bucketId,fileId,expire,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface TokensCreateFileTokenRequestParams { + bucketId: string; + fileId: string; + expire?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const tokensCreateFileToken = async ({bucketId,fileId,expire,parseOutput = true, overrideForCli = false, sdk = undefined}: TokensCreateFileTokenRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tokens/buckets/{bucketId}/files/{fileId}'.replace('{bucketId}', bucketId).replace('{fileId}', fileId); @@ -116,18 +105,15 @@ const tokensCreateFileToken = async ({bucketId,fileId,expire,parseOutput = true, return response; } -/** - * @typedef {Object} TokensGetRequestParams - * @property {string} tokenId Token ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {TokensGetRequestParams} params - */ -const tokensGet = async ({tokenId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface TokensGetRequestParams { + tokenId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const tokensGet = async ({tokenId,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: TokensGetRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tokens/{tokenId}'.replace('{tokenId}', tokenId); @@ -139,7 +125,7 @@ const tokensGet = async ({tokenId,parseOutput = true, overrideForCli = false, sd }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('tokens', 'get', tokenId); } else { parse(response) @@ -149,19 +135,15 @@ const tokensGet = async ({tokenId,parseOutput = true, overrideForCli = false, sd return response; } -/** - * @typedef {Object} TokensUpdateRequestParams - * @property {string} tokenId Token unique ID. - * @property {string} expire File token expiry date - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {TokensUpdateRequestParams} params - */ -const tokensUpdate = async ({tokenId,expire,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface TokensUpdateRequestParams { + tokenId: string; + expire?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const tokensUpdate = async ({tokenId,expire,parseOutput = true, overrideForCli = false, sdk = undefined}: TokensUpdateRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tokens/{tokenId}'.replace('{tokenId}', tokenId); @@ -183,18 +165,14 @@ const tokensUpdate = async ({tokenId,expire,parseOutput = true, overrideForCli = return response; } -/** - * @typedef {Object} TokensDeleteRequestParams - * @property {string} tokenId Token ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {TokensDeleteRequestParams} params - */ -const tokensDelete = async ({tokenId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface TokensDeleteRequestParams { + tokenId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const tokensDelete = async ({tokenId,parseOutput = true, overrideForCli = false, sdk = undefined}: TokensDeleteRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/tokens/{tokenId}'.replace('{tokenId}', tokenId); @@ -219,7 +197,7 @@ tokens .requiredOption(`--bucket-id `, `Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket).`) .requiredOption(`--file-id `, `File unique ID.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: expire`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--console`, `Get the resource console url`) .action(actionRunner(tokensList)) @@ -251,11 +229,4 @@ tokens .requiredOption(`--token-id `, `Token ID.`) .action(actionRunner(tokensDelete)) -module.exports = { - tokens, - tokensList, - tokensCreateFileToken, - tokensGet, - tokensUpdate, - tokensDelete -}; + diff --git a/lib/commands/types.js b/lib/commands/types.ts similarity index 71% rename from lib/commands/types.js rename to lib/commands/types.ts index 78428f1e..f03ce624 100644 --- a/lib/commands/types.js +++ b/lib/commands/types.ts @@ -1,24 +1,22 @@ -const ejs = require("ejs"); -const fs = require("fs"); -const path = require("path"); -const { LanguageMeta, detectLanguage } = require("../type-generation/languages/language"); -const { Command, Option, Argument } = require("commander"); -const { localConfig } = require("../config"); -const { success, log, warn, actionRunner } = require("../parser"); -const { PHP } = require("../type-generation/languages/php"); -const { TypeScript } = require("../type-generation/languages/typescript"); -const { Kotlin } = require("../type-generation/languages/kotlin"); -const { Swift } = require("../type-generation/languages/swift"); -const { Java } = require("../type-generation/languages/java"); -const { Dart } = require("../type-generation/languages/dart"); -const { JavaScript } = require("../type-generation/languages/javascript"); -const { CSharp } = require("../type-generation/languages/csharp"); - -/** - * @param {string} language - * @returns {import("../type-generation/languages/language").LanguageMeta} - */ -function createLanguageMeta(language) { +import ejs = require('ejs'); +import fs = require('fs'); +import path = require('path'); +import { LanguageMeta, detectLanguage, Collection } from '../type-generation/languages/language'; +import { Command, Option, Argument } from 'commander'; +import { localConfig } from '../config'; +import { success, log, warn, actionRunner } from '../parser'; +import { PHP } from '../type-generation/languages/php'; +import { TypeScript } from '../type-generation/languages/typescript'; +import { Kotlin } from '../type-generation/languages/kotlin'; +import { Swift } from '../type-generation/languages/swift'; +import { Java } from '../type-generation/languages/java'; +import { Dart } from '../type-generation/languages/dart'; +import { JavaScript } from '../type-generation/languages/javascript'; +import { CSharp } from '../type-generation/languages/csharp'; + +type SupportedLanguage = 'ts' | 'js' | 'php' | 'kotlin' | 'swift' | 'java' | 'dart' | 'cs'; + +function createLanguageMeta(language: SupportedLanguage): LanguageMeta { switch (language) { case "ts": return new TypeScript(); @@ -47,7 +45,7 @@ const templateHelpers = { toSnakeCase: LanguageMeta.toSnakeCase, toKebabCase: LanguageMeta.toKebabCase, toUpperSnakeCase: LanguageMeta.toUpperSnakeCase -} +}; const typesOutputArgument = new Argument( "", @@ -67,7 +65,12 @@ const typesStrictOption = new Option( ) .default(false); -const typesCommand = actionRunner(async (rawOutputDirectory, {language, strict}) => { +interface TypesOptions { + language: string; + strict: boolean; +} + +const typesCommand = actionRunner(async (rawOutputDirectory: string, {language, strict}: TypesOptions) => { if (language === "auto") { language = detectLanguage(); log(`Detected language: ${language}`); @@ -77,13 +80,13 @@ const typesCommand = actionRunner(async (rawOutputDirectory, {language, strict}) warn(`Strict mode enabled: Field names will be converted to follow ${language} conventions`); } - const meta = createLanguageMeta(language); + const meta = createLanguageMeta(language as SupportedLanguage); const rawOutputPath = rawOutputDirectory; const outputExt = path.extname(rawOutputPath); const isFileOutput = !!outputExt; let outputDirectory = rawOutputPath; - let singleFileDestination = null; + let singleFileDestination: string | null = null; if (isFileOutput) { if (meta.isSingleFile()) { @@ -102,7 +105,7 @@ const typesCommand = actionRunner(async (rawOutputDirectory, {language, strict}) // Try tables first, fallback to collections let tables = localConfig.getTables(); - let collections = []; + let collections: any[] = []; let dataSource = 'tables'; if (tables.length === 0) { @@ -116,7 +119,7 @@ const typesCommand = actionRunner(async (rawOutputDirectory, {language, strict}) } // Use tables if available, otherwise use collections - let dataItems = tables.length > 0 ? tables : collections; + let dataItems: any[] = tables.length > 0 ? tables : collections; const itemType = tables.length > 0 ? 'tables' : 'collections'; // Normalize tables data: rename 'columns' to 'attributes' for template compatibility @@ -125,7 +128,7 @@ const typesCommand = actionRunner(async (rawOutputDirectory, {language, strict}) const { columns, ...rest } = table; return { ...rest, - attributes: (columns || []).map(column => { + attributes: (columns || []).map((column: any) => { if (column.relatedTable) { const { relatedTable, ...columnRest } = column; return { @@ -139,12 +142,12 @@ const typesCommand = actionRunner(async (rawOutputDirectory, {language, strict}) }); } - log(`Found ${dataItems.length} ${itemType}: ${dataItems.map(c => c.name).join(", ")}`); + log(`Found ${dataItems.length} ${itemType}: ${dataItems.map((c: any) => c.name).join(", ")}`); // Use columns if available, otherwise use attributes const resourceType = tables.length > 0 ? 'columns' : 'attributes'; - const totalAttributes = dataItems.reduce((count, item) => count + (item.attributes || []).length, 0); + const totalAttributes = dataItems.reduce((count: number, item: any) => count + (item.attributes || []).length, 0); log(`Found ${totalAttributes} ${resourceType} across all ${itemType}`); const templater = ejs.compile(meta.getTemplate()); @@ -154,7 +157,7 @@ const typesCommand = actionRunner(async (rawOutputDirectory, {language, strict}) collections: dataItems, strict, ...templateHelpers, - getType: meta.getType, + getType: meta.getType.bind(meta), }); const destination = singleFileDestination || path.join(outputDirectory, meta.getFileName()); @@ -168,10 +171,10 @@ const typesCommand = actionRunner(async (rawOutputDirectory, {language, strict}) collection: item, strict, ...templateHelpers, - getType: meta.getType, + getType: meta.getType.bind(meta), }); - const destination = path.join(outputDirectory, meta.getFileName(item)); + const destination = path.join(outputDirectory, meta.getFileName(item as Collection)); fs.writeFileSync(destination, content); log(`Added types for ${item.name} to ${destination}`); @@ -181,11 +184,10 @@ const typesCommand = actionRunner(async (rawOutputDirectory, {language, strict}) success(`Generated types for all the listed ${itemType}`); }); -const types = new Command("types") +export const types = new Command("types") .description("Generate types for your Appwrite project") .addArgument(typesOutputArgument) .addOption(typesLanguageOption) .addOption(typesStrictOption) .action(actionRunner(typesCommand)); -module.exports = { types }; diff --git a/lib/commands/update.js b/lib/commands/update.ts similarity index 83% rename from lib/commands/update.js rename to lib/commands/update.ts index 2c7cfc57..f0b7b5b6 100644 --- a/lib/commands/update.js +++ b/lib/commands/update.ts @@ -1,18 +1,17 @@ -const fs = require("fs"); -const path = require("path"); -const { spawn } = require("child_process"); -const { Command } = require("commander"); -const { fetch } = require("undici"); -const chalk = require("chalk"); -const inquirer = require("inquirer"); -const { success, log, warn, error, hint, actionRunner, commandDescriptions } = require("../parser"); -const { getLatestVersion, compareVersions } = require("../utils"); -const { version } = require("../../package.json"); +import fs = require('fs'); +import path = require('path'); +import { spawn } from 'child_process'; +import { Command } from 'commander'; +import chalk from 'chalk'; +import inquirer from 'inquirer'; +import { success, log, warn, error, hint, actionRunner, commandDescriptions } from '../parser'; +import { getLatestVersion, compareVersions } from '../utils'; +const { version } = require('../../../package.json'); /** * Check if the CLI was installed via npm */ -const isInstalledViaNpm = () => { +const isInstalledViaNpm = (): boolean => { try { const scriptPath = process.argv[1]; @@ -36,7 +35,7 @@ const isInstalledViaNpm = () => { /** * Check if the CLI was installed via Homebrew */ -const isInstalledViaHomebrew = () => { +const isInstalledViaHomebrew = (): boolean => { try { const scriptPath = process.argv[1]; return scriptPath.includes('/opt/homebrew/') || scriptPath.includes('/usr/local/Cellar/'); @@ -45,12 +44,10 @@ const isInstalledViaHomebrew = () => { } }; - - /** * Execute command and return promise */ -const execCommand = (command, args = [], options = {}) => { +const execCommand = (command: string, args: string[] = [], options: any = {}): Promise => { return new Promise((resolve, reject) => { const child = spawn(command, args, { stdio: 'inherit', @@ -75,13 +72,13 @@ const execCommand = (command, args = [], options = {}) => { /** * Update via npm */ -const updateViaNpm = async () => { +const updateViaNpm = async (): Promise => { try { await execCommand('npm', ['install', '-g', 'appwrite-cli@latest']); console.log(""); success("Updated to latest version via npm!"); hint("Run 'appwrite --version' to verify the new version."); - } catch (e) { + } catch (e: any) { if (e.message.includes('EEXIST') || e.message.includes('file already exists')) { console.log(""); success("Latest version is already installed via npm!"); @@ -97,13 +94,13 @@ const updateViaNpm = async () => { /** * Update via Homebrew */ -const updateViaHomebrew = async () => { +const updateViaHomebrew = async (): Promise => { try { await execCommand('brew', ['upgrade', 'appwrite']); console.log(""); success("Updated to latest version via Homebrew!"); hint("Run 'appwrite --version' to verify the new version."); - } catch (e) { + } catch (e: any) { if (e.message.includes('already installed') || e.message.includes('up-to-date')) { console.log(""); success("Latest version is already installed via Homebrew!"); @@ -119,7 +116,7 @@ const updateViaHomebrew = async () => { /** * Show manual update instructions */ -const showManualInstructions = (latestVersion) => { +const showManualInstructions = (latestVersion: string): void => { log("Manual update options:"); console.log(""); @@ -138,7 +135,7 @@ const showManualInstructions = (latestVersion) => { /** * Show interactive menu for choosing update method */ -const chooseUpdateMethod = async (latestVersion) => { +const chooseUpdateMethod = async (latestVersion: string): Promise => { const choices = [ { name: 'NPM', value: 'npm' }, { name: 'Homebrew', value: 'homebrew' }, @@ -167,10 +164,14 @@ const chooseUpdateMethod = async (latestVersion) => { } }; +interface UpdateOptions { + manual?: boolean; +} + /** * Main update function */ -const updateCli = async ({ manual } = {}) => { +const updateCli = async ({ manual }: UpdateOptions = {}): Promise => { try { const latestVersion = await getLatestVersion(); @@ -201,18 +202,15 @@ const updateCli = async ({ manual } = {}) => { await chooseUpdateMethod(latestVersion); } - } catch (e) { + } catch (e: any) { console.log(""); error(`Failed to check for updates: ${e.message}`); hint("You can manually check for updates at: https://github.com/appwrite-cli/releases"); } }; -const update = new Command("update") +export const update = new Command("update") .description("Update the Appwrite CLI to the latest version") .option("--manual", "Show manual update instructions instead of auto-updating") .action(actionRunner(updateCli)); -module.exports = { - update -}; diff --git a/lib/commands/users.js b/lib/commands/users.ts similarity index 60% rename from lib/commands/users.js rename to lib/commands/users.ts index e28f6806..6d9d21ea 100644 --- a/lib/commands/users.js +++ b/lib/commands/users.ts @@ -1,31 +1,27 @@ -const fs = require('fs'); -const pathLib = require('path'); -const tar = require("tar"); -const ignore = require("ignore"); -const { promisify } = require('util'); -const libClient = require('../client.js'); -const { getAllFiles, showConsoleLink } = require('../utils.js'); -const { Command } = require('commander'); -const { sdkForProject, sdkForConsole } = require('../sdks') -const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } = require('../parser') -const { localConfig, globalConfig } = require("../config"); -const { File } = require('undici'); -const { ReadableStream } = require('stream/web'); - -/** - * @param {fs.ReadStream} readStream - * @returns {ReadableStream} - */ -function convertReadStreamToReadableStream(readStream) { +import fs = require('fs'); +import pathLib = require('path'); +import tar = require('tar'); +import ignore = require('ignore'); +import { promisify } from 'util'; +import Client from '../client'; +import { getAllFiles, showConsoleLink } from '../utils'; +import { Command } from 'commander'; +import { sdkForProject, sdkForConsole } from '../sdks'; +import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } from '../parser'; +import { localConfig, globalConfig } from '../config'; +import { File } from 'undici'; +import { ReadableStream } from 'stream/web'; + +function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ start(controller) { - readStream.on("data", (chunk) => { + readStream.on("data", (chunk: Buffer) => { controller.enqueue(chunk); }); readStream.on("end", () => { controller.close(); }); - readStream.on("error", (err) => { + readStream.on("error", (err: Error) => { controller.error(err); }); }, @@ -35,24 +31,21 @@ function convertReadStreamToReadableStream(readStream) { }); } -const users = new Command("users").description(commandDescriptions['users'] ?? '').configureHelp({ +export const users = new Command("users").description(commandDescriptions['users'] ?? '').configureHelp({ helpWidth: process.stdout.columns || 80 }) -/** - * @typedef {Object} UsersListRequestParams - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name, email, phone, status, passwordUpdate, registration, emailVerification, phoneVerification, labels - * @property {string} search Search term to filter your list results. Max length: 256 chars. - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {UsersListRequestParams} params - */ -const usersList = async ({queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +interface UsersListRequestParams { + queries?: string[]; + search?: string; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} + +export const usersList = async ({queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: UsersListRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users'; @@ -73,7 +66,7 @@ const usersList = async ({queries,search,total,parseOutput = true, overrideForCl }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('users', 'list'); } else { parse(response) @@ -83,22 +76,18 @@ const usersList = async ({queries,search,total,parseOutput = true, overrideForCl return response; } -/** - * @typedef {Object} UsersCreateRequestParams - * @property {string} userId User ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} email User email. - * @property {string} phone Phone number. Format this number with a leading '+' and a country code, e.g., +16175551212. - * @property {string} password Plain text user password. Must be at least 8 chars. - * @property {string} name User name. Max length: 128 chars. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {UsersCreateRequestParams} params - */ -const usersCreate = async ({userId,email,phone,password,name,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface UsersCreateRequestParams { + userId: string; + email?: string; + phone?: string; + password?: string; + name?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const usersCreate = async ({userId,email,phone,password,name,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersCreateRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users'; @@ -132,21 +121,17 @@ const usersCreate = async ({userId,email,phone,password,name,parseOutput = true, return response; } -/** - * @typedef {Object} UsersCreateArgon2UserRequestParams - * @property {string} userId User ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} email User email. - * @property {string} password User password hashed using Argon2. - * @property {string} name User name. Max length: 128 chars. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {UsersCreateArgon2UserRequestParams} params - */ -const usersCreateArgon2User = async ({userId,email,password,name,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface UsersCreateArgon2UserRequestParams { + userId: string; + email: string; + password: string; + name?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const usersCreateArgon2User = async ({userId,email,password,name,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersCreateArgon2UserRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/argon2'; @@ -177,21 +162,17 @@ const usersCreateArgon2User = async ({userId,email,password,name,parseOutput = t return response; } -/** - * @typedef {Object} UsersCreateBcryptUserRequestParams - * @property {string} userId User ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} email User email. - * @property {string} password User password hashed using Bcrypt. - * @property {string} name User name. Max length: 128 chars. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {UsersCreateBcryptUserRequestParams} params - */ -const usersCreateBcryptUser = async ({userId,email,password,name,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface UsersCreateBcryptUserRequestParams { + userId: string; + email: string; + password: string; + name?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const usersCreateBcryptUser = async ({userId,email,password,name,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersCreateBcryptUserRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/bcrypt'; @@ -222,20 +203,16 @@ const usersCreateBcryptUser = async ({userId,email,password,name,parseOutput = t return response; } -/** - * @typedef {Object} UsersListIdentitiesRequestParams - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: userId, provider, providerUid, providerEmail, providerAccessTokenExpiry - * @property {string} search Search term to filter your list results. Max length: 256 chars. - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {UsersListIdentitiesRequestParams} params - */ -const usersListIdentities = async ({queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface UsersListIdentitiesRequestParams { + queries?: string[]; + search?: string; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const usersListIdentities = async ({queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersListIdentitiesRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/identities'; @@ -262,18 +239,14 @@ const usersListIdentities = async ({queries,search,total,parseOutput = true, ove return response; } -/** - * @typedef {Object} UsersDeleteIdentityRequestParams - * @property {string} identityId Identity ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface UsersDeleteIdentityRequestParams { + identityId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {UsersDeleteIdentityRequestParams} params - */ -const usersDeleteIdentity = async ({identityId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const usersDeleteIdentity = async ({identityId,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersDeleteIdentityRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/identities/{identityId}'.replace('{identityId}', identityId); @@ -292,21 +265,17 @@ const usersDeleteIdentity = async ({identityId,parseOutput = true, overrideForCl return response; } -/** - * @typedef {Object} UsersCreateMD5UserRequestParams - * @property {string} userId User ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} email User email. - * @property {string} password User password hashed using MD5. - * @property {string} name User name. Max length: 128 chars. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {UsersCreateMD5UserRequestParams} params - */ -const usersCreateMD5User = async ({userId,email,password,name,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface UsersCreateMD5UserRequestParams { + userId: string; + email: string; + password: string; + name?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const usersCreateMD5User = async ({userId,email,password,name,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersCreateMD5UserRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/md5'; @@ -337,21 +306,17 @@ const usersCreateMD5User = async ({userId,email,password,name,parseOutput = true return response; } -/** - * @typedef {Object} UsersCreatePHPassUserRequestParams - * @property {string} userId User ID. Choose a custom ID or pass the string 'ID.unique()'to auto generate it. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} email User email. - * @property {string} password User password hashed using PHPass. - * @property {string} name User name. Max length: 128 chars. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {UsersCreatePHPassUserRequestParams} params - */ -const usersCreatePHPassUser = async ({userId,email,password,name,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface UsersCreatePHPassUserRequestParams { + userId: string; + email: string; + password: string; + name?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const usersCreatePHPassUser = async ({userId,email,password,name,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersCreatePHPassUserRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/phpass'; @@ -382,26 +347,22 @@ const usersCreatePHPassUser = async ({userId,email,password,name,parseOutput = t return response; } -/** - * @typedef {Object} UsersCreateScryptUserRequestParams - * @property {string} userId User ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} email User email. - * @property {string} password User password hashed using Scrypt. - * @property {string} passwordSalt Optional salt used to hash password. - * @property {number} passwordCpu Optional CPU cost used to hash password. - * @property {number} passwordMemory Optional memory cost used to hash password. - * @property {number} passwordParallel Optional parallelization cost used to hash password. - * @property {number} passwordLength Optional hash length used to hash password. - * @property {string} name User name. Max length: 128 chars. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {UsersCreateScryptUserRequestParams} params - */ -const usersCreateScryptUser = async ({userId,email,password,passwordSalt,passwordCpu,passwordMemory,passwordParallel,passwordLength,name,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface UsersCreateScryptUserRequestParams { + userId: string; + email: string; + password: string; + passwordSalt: string; + passwordCpu: number; + passwordMemory: number; + passwordParallel: number; + passwordLength: number; + name?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const usersCreateScryptUser = async ({userId,email,password,passwordSalt,passwordCpu,passwordMemory,passwordParallel,passwordLength,name,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersCreateScryptUserRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/scrypt'; @@ -447,24 +408,20 @@ const usersCreateScryptUser = async ({userId,email,password,passwordSalt,passwor return response; } -/** - * @typedef {Object} UsersCreateScryptModifiedUserRequestParams - * @property {string} userId User ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} email User email. - * @property {string} password User password hashed using Scrypt Modified. - * @property {string} passwordSalt Salt used to hash password. - * @property {string} passwordSaltSeparator Salt separator used to hash password. - * @property {string} passwordSignerKey Signer key used to hash password. - * @property {string} name User name. Max length: 128 chars. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {UsersCreateScryptModifiedUserRequestParams} params - */ -const usersCreateScryptModifiedUser = async ({userId,email,password,passwordSalt,passwordSaltSeparator,passwordSignerKey,name,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface UsersCreateScryptModifiedUserRequestParams { + userId: string; + email: string; + password: string; + passwordSalt: string; + passwordSaltSeparator: string; + passwordSignerKey: string; + name?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const usersCreateScryptModifiedUser = async ({userId,email,password,passwordSalt,passwordSaltSeparator,passwordSignerKey,name,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersCreateScryptModifiedUserRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/scrypt-modified'; @@ -504,22 +461,18 @@ const usersCreateScryptModifiedUser = async ({userId,email,password,passwordSalt return response; } -/** - * @typedef {Object} UsersCreateSHAUserRequestParams - * @property {string} userId User ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {string} email User email. - * @property {string} password User password hashed using SHA. - * @property {PasswordHash} passwordVersion Optional SHA version used to hash password. Allowed values are: 'sha1', 'sha224', 'sha256', 'sha384', 'sha512/224', 'sha512/256', 'sha512', 'sha3-224', 'sha3-256', 'sha3-384', 'sha3-512' - * @property {string} name User name. Max length: 128 chars. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {UsersCreateSHAUserRequestParams} params - */ -const usersCreateSHAUser = async ({userId,email,password,passwordVersion,name,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface UsersCreateSHAUserRequestParams { + userId: string; + email: string; + password: string; + passwordVersion?: PasswordHash; + name?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const usersCreateSHAUser = async ({userId,email,password,passwordVersion,name,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersCreateSHAUserRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/sha'; @@ -553,18 +506,14 @@ const usersCreateSHAUser = async ({userId,email,password,passwordVersion,name,pa return response; } -/** - * @typedef {Object} UsersGetUsageRequestParams - * @property {UsageRange} range Date range. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface UsersGetUsageRequestParams { + range?: UsageRange; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {UsersGetUsageRequestParams} params - */ -const usersGetUsage = async ({range,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const usersGetUsage = async ({range,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersGetUsageRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/usage'; @@ -585,18 +534,15 @@ const usersGetUsage = async ({range,parseOutput = true, overrideForCli = false, return response; } -/** - * @typedef {Object} UsersGetRequestParams - * @property {string} userId User ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface UsersGetRequestParams { + userId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {UsersGetRequestParams} params - */ -const usersGet = async ({userId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const usersGet = async ({userId,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: UsersGetRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/{userId}'.replace('{userId}', userId); @@ -608,7 +554,7 @@ const usersGet = async ({userId,parseOutput = true, overrideForCli = false, sdk }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('users', 'get', userId); } else { parse(response) @@ -618,18 +564,14 @@ const usersGet = async ({userId,parseOutput = true, overrideForCli = false, sdk return response; } -/** - * @typedef {Object} UsersDeleteRequestParams - * @property {string} userId User ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface UsersDeleteRequestParams { + userId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {UsersDeleteRequestParams} params - */ -const usersDelete = async ({userId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const usersDelete = async ({userId,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersDeleteRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/{userId}'.replace('{userId}', userId); @@ -648,19 +590,15 @@ const usersDelete = async ({userId,parseOutput = true, overrideForCli = false, s return response; } -/** - * @typedef {Object} UsersUpdateEmailRequestParams - * @property {string} userId User ID. - * @property {string} email User email. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface UsersUpdateEmailRequestParams { + userId: string; + email: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {UsersUpdateEmailRequestParams} params - */ -const usersUpdateEmail = async ({userId,email,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const usersUpdateEmail = async ({userId,email,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersUpdateEmailRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/{userId}/email'.replace('{userId}', userId); @@ -682,20 +620,16 @@ const usersUpdateEmail = async ({userId,email,parseOutput = true, overrideForCli return response; } -/** - * @typedef {Object} UsersCreateJWTRequestParams - * @property {string} userId User ID. - * @property {string} sessionId Session ID. Use the string 'recent' to use the most recent session. Defaults to the most recent session. - * @property {number} duration Time in seconds before JWT expires. Default duration is 900 seconds, and maximum is 3600 seconds. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {UsersCreateJWTRequestParams} params - */ -const usersCreateJWT = async ({userId,sessionId,duration,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface UsersCreateJWTRequestParams { + userId: string; + sessionId?: string; + duration?: number; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const usersCreateJWT = async ({userId,sessionId,duration,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersCreateJWTRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/{userId}/jwts'.replace('{userId}', userId); @@ -720,19 +654,15 @@ const usersCreateJWT = async ({userId,sessionId,duration,parseOutput = true, ove return response; } -/** - * @typedef {Object} UsersUpdateLabelsRequestParams - * @property {string} userId User ID. - * @property {string[]} labels Array of user labels. Replaces the previous labels. Maximum of 1000 labels are allowed, each up to 36 alphanumeric characters long. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface UsersUpdateLabelsRequestParams { + userId: string; + labels: string[]; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {UsersUpdateLabelsRequestParams} params - */ -const usersUpdateLabels = async ({userId,labels,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const usersUpdateLabels = async ({userId,labels,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersUpdateLabelsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/{userId}/labels'.replace('{userId}', userId); @@ -755,20 +685,16 @@ const usersUpdateLabels = async ({userId,labels,parseOutput = true, overrideForC return response; } -/** - * @typedef {Object} UsersListLogsRequestParams - * @property {string} userId User ID. - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Only supported methods are limit and offset - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {UsersListLogsRequestParams} params - */ -const usersListLogs = async ({userId,queries,total,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface UsersListLogsRequestParams { + userId: string; + queries?: string[]; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const usersListLogs = async ({userId,queries,total,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersListLogsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/{userId}/logs'.replace('{userId}', userId); @@ -792,21 +718,17 @@ const usersListLogs = async ({userId,queries,total,parseOutput = true, overrideF return response; } -/** - * @typedef {Object} UsersListMembershipsRequestParams - * @property {string} userId User ID. - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: userId, teamId, invited, joined, confirm, roles - * @property {string} search Search term to filter your list results. Max length: 256 chars. - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {UsersListMembershipsRequestParams} params - */ -const usersListMemberships = async ({userId,queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface UsersListMembershipsRequestParams { + userId: string; + queries?: string[]; + search?: string; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const usersListMemberships = async ({userId,queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersListMembershipsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/{userId}/memberships'.replace('{userId}', userId); @@ -833,19 +755,15 @@ const usersListMemberships = async ({userId,queries,search,total,parseOutput = t return response; } -/** - * @typedef {Object} UsersUpdateMFARequestParams - * @property {string} userId User ID. - * @property {boolean} mfa Enable or disable MFA. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface UsersUpdateMFARequestParams { + userId: string; + mfa: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {UsersUpdateMFARequestParams} params - */ -const usersUpdateMFA = async ({userId,mfa,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const usersUpdateMFA = async ({userId,mfa,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersUpdateMFARequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/{userId}/mfa'.replace('{userId}', userId); @@ -867,19 +785,15 @@ const usersUpdateMFA = async ({userId,mfa,parseOutput = true, overrideForCli = f return response; } -/** - * @typedef {Object} UsersDeleteMFAAuthenticatorRequestParams - * @property {string} userId User ID. - * @property {AuthenticatorType} type Type of authenticator. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface UsersDeleteMFAAuthenticatorRequestParams { + userId: string; + type: AuthenticatorType; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {UsersDeleteMFAAuthenticatorRequestParams} params - */ -const usersDeleteMFAAuthenticator = async ({userId,type,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const usersDeleteMFAAuthenticator = async ({userId,type,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersDeleteMFAAuthenticatorRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/{userId}/mfa/authenticators/{type}'.replace('{userId}', userId).replace('{type}', type); @@ -898,18 +812,14 @@ const usersDeleteMFAAuthenticator = async ({userId,type,parseOutput = true, over return response; } -/** - * @typedef {Object} UsersListMFAFactorsRequestParams - * @property {string} userId User ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface UsersListMFAFactorsRequestParams { + userId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {UsersListMFAFactorsRequestParams} params - */ -const usersListMFAFactors = async ({userId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const usersListMFAFactors = async ({userId,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersListMFAFactorsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/{userId}/mfa/factors'.replace('{userId}', userId); @@ -927,18 +837,14 @@ const usersListMFAFactors = async ({userId,parseOutput = true, overrideForCli = return response; } -/** - * @typedef {Object} UsersGetMFARecoveryCodesRequestParams - * @property {string} userId User ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface UsersGetMFARecoveryCodesRequestParams { + userId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {UsersGetMFARecoveryCodesRequestParams} params - */ -const usersGetMFARecoveryCodes = async ({userId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const usersGetMFARecoveryCodes = async ({userId,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersGetMFARecoveryCodesRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/{userId}/mfa/recovery-codes'.replace('{userId}', userId); @@ -956,18 +862,14 @@ const usersGetMFARecoveryCodes = async ({userId,parseOutput = true, overrideForC return response; } -/** - * @typedef {Object} UsersUpdateMFARecoveryCodesRequestParams - * @property {string} userId User ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface UsersUpdateMFARecoveryCodesRequestParams { + userId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {UsersUpdateMFARecoveryCodesRequestParams} params - */ -const usersUpdateMFARecoveryCodes = async ({userId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const usersUpdateMFARecoveryCodes = async ({userId,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersUpdateMFARecoveryCodesRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/{userId}/mfa/recovery-codes'.replace('{userId}', userId); @@ -986,18 +888,14 @@ const usersUpdateMFARecoveryCodes = async ({userId,parseOutput = true, overrideF return response; } -/** - * @typedef {Object} UsersCreateMFARecoveryCodesRequestParams - * @property {string} userId User ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface UsersCreateMFARecoveryCodesRequestParams { + userId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {UsersCreateMFARecoveryCodesRequestParams} params - */ -const usersCreateMFARecoveryCodes = async ({userId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const usersCreateMFARecoveryCodes = async ({userId,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersCreateMFARecoveryCodesRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/{userId}/mfa/recovery-codes'.replace('{userId}', userId); @@ -1016,19 +914,15 @@ const usersCreateMFARecoveryCodes = async ({userId,parseOutput = true, overrideF return response; } -/** - * @typedef {Object} UsersUpdateNameRequestParams - * @property {string} userId User ID. - * @property {string} name User name. Max length: 128 chars. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface UsersUpdateNameRequestParams { + userId: string; + name: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {UsersUpdateNameRequestParams} params - */ -const usersUpdateName = async ({userId,name,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const usersUpdateName = async ({userId,name,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersUpdateNameRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/{userId}/name'.replace('{userId}', userId); @@ -1050,19 +944,15 @@ const usersUpdateName = async ({userId,name,parseOutput = true, overrideForCli = return response; } -/** - * @typedef {Object} UsersUpdatePasswordRequestParams - * @property {string} userId User ID. - * @property {string} password New user password. Must be at least 8 chars. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface UsersUpdatePasswordRequestParams { + userId: string; + password: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {UsersUpdatePasswordRequestParams} params - */ -const usersUpdatePassword = async ({userId,password,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const usersUpdatePassword = async ({userId,password,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersUpdatePasswordRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/{userId}/password'.replace('{userId}', userId); @@ -1084,19 +974,15 @@ const usersUpdatePassword = async ({userId,password,parseOutput = true, override return response; } -/** - * @typedef {Object} UsersUpdatePhoneRequestParams - * @property {string} userId User ID. - * @property {string} number User phone number. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface UsersUpdatePhoneRequestParams { + userId: string; + number: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {UsersUpdatePhoneRequestParams} params - */ -const usersUpdatePhone = async ({userId,number,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const usersUpdatePhone = async ({userId,number,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersUpdatePhoneRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/{userId}/phone'.replace('{userId}', userId); @@ -1118,18 +1004,14 @@ const usersUpdatePhone = async ({userId,number,parseOutput = true, overrideForCl return response; } -/** - * @typedef {Object} UsersGetPrefsRequestParams - * @property {string} userId User ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface UsersGetPrefsRequestParams { + userId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {UsersGetPrefsRequestParams} params - */ -const usersGetPrefs = async ({userId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const usersGetPrefs = async ({userId,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersGetPrefsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/{userId}/prefs'.replace('{userId}', userId); @@ -1147,19 +1029,15 @@ const usersGetPrefs = async ({userId,parseOutput = true, overrideForCli = false, return response; } -/** - * @typedef {Object} UsersUpdatePrefsRequestParams - * @property {string} userId User ID. - * @property {object} prefs Prefs key-value JSON object. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface UsersUpdatePrefsRequestParams { + userId: string; + prefs: object; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {UsersUpdatePrefsRequestParams} params - */ -const usersUpdatePrefs = async ({userId,prefs,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const usersUpdatePrefs = async ({userId,prefs,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersUpdatePrefsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/{userId}/prefs'.replace('{userId}', userId); @@ -1181,19 +1059,16 @@ const usersUpdatePrefs = async ({userId,prefs,parseOutput = true, overrideForCli return response; } -/** - * @typedef {Object} UsersListSessionsRequestParams - * @property {string} userId User ID. - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface UsersListSessionsRequestParams { + userId: string; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; + console?: boolean; +} -/** - * @param {UsersListSessionsRequestParams} params - */ -const usersListSessions = async ({userId,total,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { +export const usersListSessions = async ({userId,total,parseOutput = true, overrideForCli = false, sdk = undefined, console: showConsole}: UsersListSessionsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/{userId}/sessions'.replace('{userId}', userId); @@ -1208,7 +1083,7 @@ const usersListSessions = async ({userId,total,parseOutput = true, overrideForCl }, payload); if (parseOutput) { - if(console) { + if(showConsole) { showConsoleLink('users', 'listSessions', userId); } else { parse(response) @@ -1218,18 +1093,14 @@ const usersListSessions = async ({userId,total,parseOutput = true, overrideForCl return response; } -/** - * @typedef {Object} UsersCreateSessionRequestParams - * @property {string} userId User ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface UsersCreateSessionRequestParams { + userId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {UsersCreateSessionRequestParams} params - */ -const usersCreateSession = async ({userId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const usersCreateSession = async ({userId,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersCreateSessionRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/{userId}/sessions'.replace('{userId}', userId); @@ -1248,18 +1119,14 @@ const usersCreateSession = async ({userId,parseOutput = true, overrideForCli = f return response; } -/** - * @typedef {Object} UsersDeleteSessionsRequestParams - * @property {string} userId User ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface UsersDeleteSessionsRequestParams { + userId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {UsersDeleteSessionsRequestParams} params - */ -const usersDeleteSessions = async ({userId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const usersDeleteSessions = async ({userId,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersDeleteSessionsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/{userId}/sessions'.replace('{userId}', userId); @@ -1278,19 +1145,15 @@ const usersDeleteSessions = async ({userId,parseOutput = true, overrideForCli = return response; } -/** - * @typedef {Object} UsersDeleteSessionRequestParams - * @property {string} userId User ID. - * @property {string} sessionId Session ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface UsersDeleteSessionRequestParams { + userId: string; + sessionId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {UsersDeleteSessionRequestParams} params - */ -const usersDeleteSession = async ({userId,sessionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const usersDeleteSession = async ({userId,sessionId,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersDeleteSessionRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/{userId}/sessions/{sessionId}'.replace('{userId}', userId).replace('{sessionId}', sessionId); @@ -1309,19 +1172,15 @@ const usersDeleteSession = async ({userId,sessionId,parseOutput = true, override return response; } -/** - * @typedef {Object} UsersUpdateStatusRequestParams - * @property {string} userId User ID. - * @property {boolean} status User Status. To activate the user pass 'true' and to block the user pass 'false'. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface UsersUpdateStatusRequestParams { + userId: string; + status: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {UsersUpdateStatusRequestParams} params - */ -const usersUpdateStatus = async ({userId,status,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const usersUpdateStatus = async ({userId,status,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersUpdateStatusRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/{userId}/status'.replace('{userId}', userId); @@ -1343,20 +1202,16 @@ const usersUpdateStatus = async ({userId,status,parseOutput = true, overrideForC return response; } -/** - * @typedef {Object} UsersListTargetsRequestParams - * @property {string} userId User ID. - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: userId, providerId, identifier, providerType - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {UsersListTargetsRequestParams} params - */ -const usersListTargets = async ({userId,queries,total,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface UsersListTargetsRequestParams { + userId: string; + queries?: string[]; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const usersListTargets = async ({userId,queries,total,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersListTargetsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/{userId}/targets'.replace('{userId}', userId); @@ -1380,23 +1235,19 @@ const usersListTargets = async ({userId,queries,total,parseOutput = true, overri return response; } -/** - * @typedef {Object} UsersCreateTargetRequestParams - * @property {string} userId User ID. - * @property {string} targetId Target ID. Choose a custom ID or generate a random ID with 'ID.unique()'. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. - * @property {MessagingProviderType} providerType The target provider type. Can be one of the following: 'email', 'sms' or 'push'. - * @property {string} identifier The target identifier (token, email, phone etc.) - * @property {string} providerId Provider ID. Message will be sent to this target from the specified provider ID. If no provider ID is set the first setup provider will be used. - * @property {string} name Target name. Max length: 128 chars. For example: My Awesome App Galaxy S23. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {UsersCreateTargetRequestParams} params - */ -const usersCreateTarget = async ({userId,targetId,providerType,identifier,providerId,name,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface UsersCreateTargetRequestParams { + userId: string; + targetId: string; + providerType: MessagingProviderType; + identifier: string; + providerId?: string; + name?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const usersCreateTarget = async ({userId,targetId,providerType,identifier,providerId,name,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersCreateTargetRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/{userId}/targets'.replace('{userId}', userId); @@ -1430,19 +1281,15 @@ const usersCreateTarget = async ({userId,targetId,providerType,identifier,provid return response; } -/** - * @typedef {Object} UsersGetTargetRequestParams - * @property {string} userId User ID. - * @property {string} targetId Target ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface UsersGetTargetRequestParams { + userId: string; + targetId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {UsersGetTargetRequestParams} params - */ -const usersGetTarget = async ({userId,targetId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const usersGetTarget = async ({userId,targetId,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersGetTargetRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/{userId}/targets/{targetId}'.replace('{userId}', userId).replace('{targetId}', targetId); @@ -1460,22 +1307,18 @@ const usersGetTarget = async ({userId,targetId,parseOutput = true, overrideForCl return response; } -/** - * @typedef {Object} UsersUpdateTargetRequestParams - * @property {string} userId User ID. - * @property {string} targetId Target ID. - * @property {string} identifier The target identifier (token, email, phone etc.) - * @property {string} providerId Provider ID. Message will be sent to this target from the specified provider ID. If no provider ID is set the first setup provider will be used. - * @property {string} name Target name. Max length: 128 chars. For example: My Awesome App Galaxy S23. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {UsersUpdateTargetRequestParams} params - */ -const usersUpdateTarget = async ({userId,targetId,identifier,providerId,name,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface UsersUpdateTargetRequestParams { + userId: string; + targetId: string; + identifier?: string; + providerId?: string; + name?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const usersUpdateTarget = async ({userId,targetId,identifier,providerId,name,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersUpdateTargetRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/{userId}/targets/{targetId}'.replace('{userId}', userId).replace('{targetId}', targetId); @@ -1503,19 +1346,15 @@ const usersUpdateTarget = async ({userId,targetId,identifier,providerId,name,par return response; } -/** - * @typedef {Object} UsersDeleteTargetRequestParams - * @property {string} userId User ID. - * @property {string} targetId Target ID. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface UsersDeleteTargetRequestParams { + userId: string; + targetId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {UsersDeleteTargetRequestParams} params - */ -const usersDeleteTarget = async ({userId,targetId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const usersDeleteTarget = async ({userId,targetId,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersDeleteTargetRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/{userId}/targets/{targetId}'.replace('{userId}', userId).replace('{targetId}', targetId); @@ -1534,20 +1373,16 @@ const usersDeleteTarget = async ({userId,targetId,parseOutput = true, overrideFo return response; } -/** - * @typedef {Object} UsersCreateTokenRequestParams - * @property {string} userId User ID. - * @property {number} length Token length in characters. The default length is 6 characters - * @property {number} expire Token expiration period in seconds. The default expiration is 15 minutes. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {UsersCreateTokenRequestParams} params - */ -const usersCreateToken = async ({userId,length,expire,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface UsersCreateTokenRequestParams { + userId: string; + length?: number; + expire?: number; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const usersCreateToken = async ({userId,length,expire,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersCreateTokenRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/{userId}/tokens'.replace('{userId}', userId); @@ -1572,19 +1407,15 @@ const usersCreateToken = async ({userId,length,expire,parseOutput = true, overri return response; } -/** - * @typedef {Object} UsersUpdateEmailVerificationRequestParams - * @property {string} userId User ID. - * @property {boolean} emailVerification User email verification status. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface UsersUpdateEmailVerificationRequestParams { + userId: string; + emailVerification: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {UsersUpdateEmailVerificationRequestParams} params - */ -const usersUpdateEmailVerification = async ({userId,emailVerification,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const usersUpdateEmailVerification = async ({userId,emailVerification,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersUpdateEmailVerificationRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/{userId}/verification'.replace('{userId}', userId); @@ -1606,19 +1437,15 @@ const usersUpdateEmailVerification = async ({userId,emailVerification,parseOutpu return response; } -/** - * @typedef {Object} UsersUpdatePhoneVerificationRequestParams - * @property {string} userId User ID. - * @property {boolean} phoneVerification User phone verification status. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ +interface UsersUpdatePhoneVerificationRequestParams { + userId: string; + phoneVerification: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} -/** - * @param {UsersUpdatePhoneVerificationRequestParams} params - */ -const usersUpdatePhoneVerification = async ({userId,phoneVerification,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +export const usersUpdatePhoneVerification = async ({userId,phoneVerification,parseOutput = true, overrideForCli = false, sdk = undefined}: UsersUpdatePhoneVerificationRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/users/{userId}/verification/phone'.replace('{userId}', userId); @@ -1645,7 +1472,7 @@ users .description(`Get a list of all the project's users. You can use the query params to filter your results.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name, email, phone, status, passwordUpdate, registration, emailVerification, phoneVerification, labels`) .option(`--search `, `Search term to filter your list results. Max length: 256 chars.`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--console`, `Get the resource console url`) .action(actionRunner(usersList)) @@ -1682,7 +1509,7 @@ users .description(`Get identities for all users.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: userId, provider, providerUid, providerEmail, providerAccessTokenExpiry`) .option(`--search `, `Search term to filter your list results. Max length: 256 chars.`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(usersListIdentities)) users @@ -1791,7 +1618,7 @@ users .description(`Get the user activity logs list by its unique ID.`) .requiredOption(`--user-id `, `User ID.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Only supported methods are limit and offset`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(usersListLogs)) users @@ -1800,14 +1627,14 @@ users .requiredOption(`--user-id `, `User ID.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: userId, teamId, invited, joined, confirm, roles`) .option(`--search `, `Search term to filter your list results. Max length: 256 chars.`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(usersListMemberships)) users .command(`update-mfa`) .description(`Enable or disable MFA on a user account.`) .requiredOption(`--user-id `, `User ID.`) - .requiredOption(`--mfa [value]`, `Enable or disable MFA.`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--mfa [value]`, `Enable or disable MFA.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(usersUpdateMFA)) users @@ -1879,7 +1706,7 @@ users .command(`list-sessions`) .description(`Get the user sessions list by its unique ID.`) .requiredOption(`--user-id `, `User ID.`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .option(`--console`, `Get the resource console url`) .action(actionRunner(usersListSessions)) @@ -1906,7 +1733,7 @@ users .command(`update-status`) .description(`Update the user status by its unique ID. Use this endpoint as an alternative to deleting a user if you want to keep user's ID reserved.`) .requiredOption(`--user-id `, `User ID.`) - .requiredOption(`--status [value]`, `User Status. To activate the user pass 'true' and to block the user pass 'false'.`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--status [value]`, `User Status. To activate the user pass 'true' and to block the user pass 'false'.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(usersUpdateStatus)) users @@ -1914,7 +1741,7 @@ users .description(`List the messaging targets that are associated with a user.`) .requiredOption(`--user-id `, `User ID.`) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: userId, providerId, identifier, providerType`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(usersListTargets)) users @@ -1964,59 +1791,14 @@ users .command(`update-email-verification`) .description(`Update the user email verification status by its unique ID.`) .requiredOption(`--user-id `, `User ID.`) - .requiredOption(`--email-verification [value]`, `User email verification status.`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--email-verification [value]`, `User email verification status.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(usersUpdateEmailVerification)) users .command(`update-phone-verification`) .description(`Update the user phone verification status by its unique ID.`) .requiredOption(`--user-id `, `User ID.`) - .requiredOption(`--phone-verification [value]`, `User phone verification status.`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--phone-verification [value]`, `User phone verification status.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(usersUpdatePhoneVerification)) -module.exports = { - users, - usersList, - usersCreate, - usersCreateArgon2User, - usersCreateBcryptUser, - usersListIdentities, - usersDeleteIdentity, - usersCreateMD5User, - usersCreatePHPassUser, - usersCreateScryptUser, - usersCreateScryptModifiedUser, - usersCreateSHAUser, - usersGetUsage, - usersGet, - usersDelete, - usersUpdateEmail, - usersCreateJWT, - usersUpdateLabels, - usersListLogs, - usersListMemberships, - usersUpdateMFA, - usersDeleteMFAAuthenticator, - usersListMFAFactors, - usersGetMFARecoveryCodes, - usersUpdateMFARecoveryCodes, - usersCreateMFARecoveryCodes, - usersUpdateName, - usersUpdatePassword, - usersUpdatePhone, - usersGetPrefs, - usersUpdatePrefs, - usersListSessions, - usersCreateSession, - usersDeleteSessions, - usersDeleteSession, - usersUpdateStatus, - usersListTargets, - usersCreateTarget, - usersGetTarget, - usersUpdateTarget, - usersDeleteTarget, - usersCreateToken, - usersUpdateEmailVerification, - usersUpdatePhoneVerification -}; + diff --git a/lib/commands/vcs.js b/lib/commands/vcs.ts similarity index 63% rename from lib/commands/vcs.js rename to lib/commands/vcs.ts index 475646d0..7b5de57d 100644 --- a/lib/commands/vcs.js +++ b/lib/commands/vcs.ts @@ -1,31 +1,27 @@ -const fs = require('fs'); -const pathLib = require('path'); -const tar = require("tar"); -const ignore = require("ignore"); -const { promisify } = require('util'); -const libClient = require('../client.js'); -const { getAllFiles, showConsoleLink } = require('../utils.js'); -const { Command } = require('commander'); -const { sdkForProject, sdkForConsole } = require('../sdks') -const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } = require('../parser') -const { localConfig, globalConfig } = require("../config"); -const { File } = require('undici'); -const { ReadableStream } = require('stream/web'); - -/** - * @param {fs.ReadStream} readStream - * @returns {ReadableStream} - */ -function convertReadStreamToReadableStream(readStream) { +import fs = require('fs'); +import pathLib = require('path'); +import tar = require('tar'); +import ignore = require('ignore'); +import { promisify } from 'util'; +import Client from '../client'; +import { getAllFiles, showConsoleLink } from '../utils'; +import { Command } from 'commander'; +import { sdkForProject, sdkForConsole } from '../sdks'; +import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log, warn } from '../parser'; +import { localConfig, globalConfig } from '../config'; +import { File } from 'undici'; +import { ReadableStream } from 'stream/web'; + +function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ start(controller) { - readStream.on("data", (chunk) => { + readStream.on("data", (chunk: Buffer) => { controller.enqueue(chunk); }); readStream.on("end", () => { controller.close(); }); - readStream.on("error", (err) => { + readStream.on("error", (err: Error) => { controller.error(err); }); }, @@ -35,25 +31,21 @@ function convertReadStreamToReadableStream(readStream) { }); } -const vcs = new Command("vcs").description(commandDescriptions['vcs'] ?? '').configureHelp({ +export const vcs = new Command("vcs").description(commandDescriptions['vcs'] ?? '').configureHelp({ helpWidth: process.stdout.columns || 80 }) -/** - * @typedef {Object} VcsCreateRepositoryDetectionRequestParams - * @property {string} installationId Installation Id - * @property {string} providerRepositoryId Repository Id - * @property {VCSDetectionType} type Detector type. Must be one of the following: runtime, framework - * @property {string} providerRootDirectory Path to Root Directory - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {VcsCreateRepositoryDetectionRequestParams} params - */ -const vcsCreateRepositoryDetection = async ({installationId,providerRepositoryId,type,providerRootDirectory,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface VcsCreateRepositoryDetectionRequestParams { + installationId: string; + providerRepositoryId: string; + type: VCSDetectionType; + providerRootDirectory?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const vcsCreateRepositoryDetection = async ({installationId,providerRepositoryId,type,providerRootDirectory,parseOutput = true, overrideForCli = false, sdk = undefined}: VcsCreateRepositoryDetectionRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/vcs/github/installations/{installationId}/detections'.replace('{installationId}', installationId); @@ -81,21 +73,17 @@ const vcsCreateRepositoryDetection = async ({installationId,providerRepositoryId return response; } -/** - * @typedef {Object} VcsListRepositoriesRequestParams - * @property {string} installationId Installation Id - * @property {VCSDetectionType} type Detector type. Must be one of the following: runtime, framework - * @property {string} search Search term to filter your list results. Max length: 256 chars. - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Only supported methods are limit and offset - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {VcsListRepositoriesRequestParams} params - */ -const vcsListRepositories = async ({installationId,type,search,queries,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface VcsListRepositoriesRequestParams { + installationId: string; + type: VCSDetectionType; + search?: string; + queries?: string[]; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const vcsListRepositories = async ({installationId,type,search,queries,parseOutput = true, overrideForCli = false, sdk = undefined}: VcsListRepositoriesRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/vcs/github/installations/{installationId}/providerRepositories'.replace('{installationId}', installationId); @@ -122,20 +110,16 @@ const vcsListRepositories = async ({installationId,type,search,queries,parseOutp return response; } -/** - * @typedef {Object} VcsCreateRepositoryRequestParams - * @property {string} installationId Installation Id - * @property {string} name Repository name (slug) - * @property {boolean} xprivate Mark repository public or private - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {VcsCreateRepositoryRequestParams} params - */ -const vcsCreateRepository = async ({installationId,name,xprivate,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface VcsCreateRepositoryRequestParams { + installationId: string; + name: string; + xprivate: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const vcsCreateRepository = async ({installationId,name,xprivate,parseOutput = true, overrideForCli = false, sdk = undefined}: VcsCreateRepositoryRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/vcs/github/installations/{installationId}/providerRepositories'.replace('{installationId}', installationId); @@ -160,19 +144,15 @@ const vcsCreateRepository = async ({installationId,name,xprivate,parseOutput = t return response; } -/** - * @typedef {Object} VcsGetRepositoryRequestParams - * @property {string} installationId Installation Id - * @property {string} providerRepositoryId Repository Id - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {VcsGetRepositoryRequestParams} params - */ -const vcsGetRepository = async ({installationId,providerRepositoryId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface VcsGetRepositoryRequestParams { + installationId: string; + providerRepositoryId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const vcsGetRepository = async ({installationId,providerRepositoryId,parseOutput = true, overrideForCli = false, sdk = undefined}: VcsGetRepositoryRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/vcs/github/installations/{installationId}/providerRepositories/{providerRepositoryId}'.replace('{installationId}', installationId).replace('{providerRepositoryId}', providerRepositoryId); @@ -190,19 +170,15 @@ const vcsGetRepository = async ({installationId,providerRepositoryId,parseOutput return response; } -/** - * @typedef {Object} VcsListRepositoryBranchesRequestParams - * @property {string} installationId Installation Id - * @property {string} providerRepositoryId Repository Id - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {VcsListRepositoryBranchesRequestParams} params - */ -const vcsListRepositoryBranches = async ({installationId,providerRepositoryId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface VcsListRepositoryBranchesRequestParams { + installationId: string; + providerRepositoryId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const vcsListRepositoryBranches = async ({installationId,providerRepositoryId,parseOutput = true, overrideForCli = false, sdk = undefined}: VcsListRepositoryBranchesRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/vcs/github/installations/{installationId}/providerRepositories/{providerRepositoryId}/branches'.replace('{installationId}', installationId).replace('{providerRepositoryId}', providerRepositoryId); @@ -220,21 +196,17 @@ const vcsListRepositoryBranches = async ({installationId,providerRepositoryId,pa return response; } -/** - * @typedef {Object} VcsGetRepositoryContentsRequestParams - * @property {string} installationId Installation Id - * @property {string} providerRepositoryId Repository Id - * @property {string} providerRootDirectory Path to get contents of nested directory - * @property {string} providerReference Git reference (branch, tag, commit) to get contents from - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {VcsGetRepositoryContentsRequestParams} params - */ -const vcsGetRepositoryContents = async ({installationId,providerRepositoryId,providerRootDirectory,providerReference,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface VcsGetRepositoryContentsRequestParams { + installationId: string; + providerRepositoryId: string; + providerRootDirectory?: string; + providerReference?: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const vcsGetRepositoryContents = async ({installationId,providerRepositoryId,providerRootDirectory,providerReference,parseOutput = true, overrideForCli = false, sdk = undefined}: VcsGetRepositoryContentsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/vcs/github/installations/{installationId}/providerRepositories/{providerRepositoryId}/contents'.replace('{installationId}', installationId).replace('{providerRepositoryId}', providerRepositoryId); @@ -258,20 +230,16 @@ const vcsGetRepositoryContents = async ({installationId,providerRepositoryId,pro return response; } -/** - * @typedef {Object} VcsUpdateExternalDeploymentsRequestParams - * @property {string} installationId Installation Id - * @property {string} repositoryId VCS Repository Id - * @property {string} providerPullRequestId GitHub Pull Request Id - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {VcsUpdateExternalDeploymentsRequestParams} params - */ -const vcsUpdateExternalDeployments = async ({installationId,repositoryId,providerPullRequestId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface VcsUpdateExternalDeploymentsRequestParams { + installationId: string; + repositoryId: string; + providerPullRequestId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const vcsUpdateExternalDeployments = async ({installationId,repositoryId,providerPullRequestId,parseOutput = true, overrideForCli = false, sdk = undefined}: VcsUpdateExternalDeploymentsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/vcs/github/installations/{installationId}/repositories/{repositoryId}'.replace('{installationId}', installationId).replace('{repositoryId}', repositoryId); @@ -293,20 +261,16 @@ const vcsUpdateExternalDeployments = async ({installationId,repositoryId,provide return response; } -/** - * @typedef {Object} VcsListInstallationsRequestParams - * @property {string[]} queries Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: provider, organization - * @property {string} search Search term to filter your list results. Max length: 256 chars. - * @property {boolean} total When set to false, the total count returned will be 0 and will not be calculated. - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {VcsListInstallationsRequestParams} params - */ -const vcsListInstallations = async ({queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface VcsListInstallationsRequestParams { + queries?: string[]; + search?: string; + total?: boolean; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const vcsListInstallations = async ({queries,search,total,parseOutput = true, overrideForCli = false, sdk = undefined}: VcsListInstallationsRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/vcs/installations'; @@ -333,18 +297,14 @@ const vcsListInstallations = async ({queries,search,total,parseOutput = true, ov return response; } -/** - * @typedef {Object} VcsGetInstallationRequestParams - * @property {string} installationId Installation Id - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {VcsGetInstallationRequestParams} params - */ -const vcsGetInstallation = async ({installationId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface VcsGetInstallationRequestParams { + installationId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const vcsGetInstallation = async ({installationId,parseOutput = true, overrideForCli = false, sdk = undefined}: VcsGetInstallationRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/vcs/installations/{installationId}'.replace('{installationId}', installationId); @@ -362,18 +322,14 @@ const vcsGetInstallation = async ({installationId,parseOutput = true, overrideFo return response; } -/** - * @typedef {Object} VcsDeleteInstallationRequestParams - * @property {string} installationId Installation Id - * @property {boolean} overrideForCli - * @property {boolean} parseOutput - * @property {libClient | undefined} sdk - */ - -/** - * @param {VcsDeleteInstallationRequestParams} params - */ -const vcsDeleteInstallation = async ({installationId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { +interface VcsDeleteInstallationRequestParams { + installationId: string; + overrideForCli?: boolean; + parseOutput?: boolean; + sdk?: Client; +} + +export const vcsDeleteInstallation = async ({installationId,parseOutput = true, overrideForCli = false, sdk = undefined}: VcsDeleteInstallationRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/vcs/installations/{installationId}'.replace('{installationId}', installationId); @@ -415,7 +371,7 @@ vcs .description(`Create a new GitHub repository through your installation. This endpoint allows you to create either a public or private repository by specifying a name and visibility setting. The repository will be created under your GitHub user account or organization, depending on your installation type. The GitHub installation must be properly configured and have the necessary permissions for repository creation.`) .requiredOption(`--installation-id `, `Installation Id`) .requiredOption(`--name `, `Repository name (slug)`) - .requiredOption(`--xprivate [value]`, `Mark repository public or private`, (value) => value === undefined ? true : parseBool(value)) + .requiredOption(`--xprivate [value]`, `Mark repository public or private`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(vcsCreateRepository)) vcs @@ -454,7 +410,7 @@ vcs .description(`List all VCS installations configured for the current project. This endpoint returns a list of installations including their provider, organization, and other configuration details. `) .option(`--queries [queries...]`, `Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: provider, organization`) .option(`--search `, `Search term to filter your list results. Max length: 256 chars.`) - .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value) => value === undefined ? true : parseBool(value)) + .option(`--total [value]`, `When set to false, the total count returned will be 0 and will not be calculated.`, (value: string | undefined) => value === undefined ? true : parseBool(value)) .action(actionRunner(vcsListInstallations)) vcs @@ -469,16 +425,4 @@ vcs .requiredOption(`--installation-id `, `Installation Id`) .action(actionRunner(vcsDeleteInstallation)) -module.exports = { - vcs, - vcsCreateRepositoryDetection, - vcsListRepositories, - vcsCreateRepository, - vcsGetRepository, - vcsListRepositoryBranches, - vcsGetRepositoryContents, - vcsUpdateExternalDeployments, - vcsListInstallations, - vcsGetInstallation, - vcsDeleteInstallation -}; + diff --git a/lib/config.js b/lib/config.js deleted file mode 100644 index a8c76678..00000000 --- a/lib/config.js +++ /dev/null @@ -1,825 +0,0 @@ -const os = require('os'); -const fs = require("fs"); -const _path = require("path"); -const process = require("process"); -const JSONbig = require("json-bigint")({ storeAsString: false }); - -const KeysVars = new Set(["key", "value"]); -const KeysSite = new Set(["path", "$id", "name", "enabled", "logging", "timeout", "framework", "buildRuntime", "adapter", "installCommand", "buildCommand", "outputDirectory", "fallbackFile", "specification", "vars"]); -const KeysFunction = new Set(["path", "$id", "execute", "name", "enabled", "logging", "runtime", "specification", "scopes", "events", "schedule", "timeout", "entrypoint", "commands", "vars"]); -const KeysDatabase = new Set(["$id", "name", "enabled"]); -const KeysCollection = new Set(["$id", "$permissions", "databaseId", "name", "enabled", "documentSecurity", "attributes", "indexes"]); -const KeysTable = new Set(["$id", "$permissions", "databaseId", "name", "enabled", "rowSecurity", "columns", "indexes"]); -const KeysStorage = new Set(["$id", "$permissions", "fileSecurity", "name", "enabled", "maximumFileSize", "allowedFileExtensions", "compression", "encryption", "antivirus"]); -const KeysTopics = new Set(["$id", "name", "subscribe"]); -const KeysTeams = new Set(["$id", "name"]); -const KeysAttributes = new Set([ - "key", - "type", - "required", - "array", - "size", - "default", - // integer and float - "min", - "max", - // email, enum, URL, IP, and datetime - "format", - // enum - "elements", - // relationship - "relatedCollection", - "relationType", - "twoWay", - "twoWayKey", - "onDelete", - "side", - // Indexes - "attributes", - "orders", - // Strings - "encrypt", -]); -const KeysColumns = new Set([ - "key", - "type", - "required", - "array", - "size", - "default", - // integer and float - "min", - "max", - // email, enum, URL, IP, and datetime - "format", - // enum - "elements", - // relationship - "relatedTable", - "relationType", - "twoWay", - "twoWayKey", - "onDelete", - "side", - // Indexes - "columns", - "orders", - // Strings - "encrypt", -]); -const KeyIndexes = new Set(["key", "type", "status", "attributes", "orders"]); -const KeyIndexesColumns = new Set(["key", "type", "status", "columns", "orders"]); - -function whitelistKeys(value, keys, nestedKeys = {}) { - if (Array.isArray(value)) { - const newValue = []; - - for (const item of value) { - newValue.push(whitelistKeys(item, keys, nestedKeys)); - } - - return newValue; - } - - const newValue = {}; - Object.keys(value).forEach((key) => { - if (keys.has(key)) { - if (nestedKeys[key]) { - newValue[key] = whitelistKeys(value[key], nestedKeys[key]); - } else { - newValue[key] = value[key]; - } - } - }); - return newValue; -} - -class Config { - constructor(path) { - this.path = path; - this.read(); - } - - read() { - try { - const file = fs.readFileSync(this.path).toString(); - this.data = JSONbig.parse(file); - } catch (e) { - this.data = {}; - } - } - - write() { - let dir = _path.dirname(this.path) - if (!fs.existsSync(dir)) { - fs.mkdirSync(dir, { recursive: true }); - } - fs.writeFileSync(this.path, JSONbig.stringify(this.data, null, 4), { mode: 0o600 }); - } - - get(key) { - return this.data[key]; - } - - set(key, value) { - this.data[key] = value; - this.write(); - } - - delete(key) { - delete this.data[key]; - this.write(); - } - - clear() { - this.data = {}; - this.write(); - } - - has(key) { - return this.data[key] !== undefined; - } - - keys() { - return Object.keys(this.data); - } - - values() { - return Object.values(this.data); - } - - toString() { - return JSONbig.stringify(this.data, null, 4); - } - - _getDBEntities(entityType) { - if (!this.has(entityType)) { - return []; - } - return this.get(entityType); - } - - _getDBEntity(entityType, $id) { - if (!this.has(entityType)) { - return {}; - } - - let entities = this.get(entityType); - for (let i = 0; i < entities.length; i++) { - if (entities[i]['$id'] == $id) { - return entities[i]; - } - } - - return {}; - } - - _addDBEntity(entityType, props, keysSet, nestedKeys = {}) { - props = whitelistKeys(props, keysSet, nestedKeys); - - if (!this.has(entityType)) { - this.set(entityType, []); - } - - let entities = this.get(entityType); - for (let i = 0; i < entities.length; i++) { - if (entities[i]['$id'] == props['$id']) { - entities[i] = props; - this.set(entityType, entities); - return; - } - } - entities.push(props); - this.set(entityType, entities); - } -} - -class Local extends Config { - static CONFIG_FILE_PATH = "appwrite.config.json"; - static CONFIG_FILE_PATH_LEGACY = "appwrite.json"; - configDirectoryPath = "" - - constructor(path = Local.CONFIG_FILE_PATH, legacyPath = Local.CONFIG_FILE_PATH_LEGACY) { - let absolutePath = Local.findConfigFile(path) || Local.findConfigFile(legacyPath); - - if (!absolutePath) { - absolutePath = `${process.cwd()}/${path}`; - } - - super(absolutePath); - this.configDirectoryPath = _path.dirname(absolutePath); - } - - static findConfigFile(filename) { - let currentPath = process.cwd(); - - while (true) { - const filePath = `${currentPath}/${filename}`; - - if (fs.existsSync(filePath)) { - return filePath; - } - - const parentDirectory = _path.dirname(currentPath); - if (parentDirectory === currentPath) { - break; - } - currentPath = parentDirectory; - } - - return null; - } - - getDirname() { - return _path.dirname(this.path) - } - - getEndpoint() { - return this.get('endpoint') || ''; - } - - setEndpoint(endpoint) { - this.set('endpoint', endpoint); - } - - getSites() { - if (!this.has("sites")) { - return []; - } - return this.get("sites"); - } - - getSite($id) { - if (!this.has("sites")) { - return {}; - } - - let sites = this.get("sites"); - for (let i = 0; i < sites.length; i++) { - if (sites[i]['$id'] == $id) { - return sites[i]; - } - } - - return {}; - } - - addSite(props) { - props = whitelistKeys(props, KeysSite, { - vars: KeysVars - }); - - if (!this.has("sites")) { - this.set("sites", []); - } - - let sites = this.get("sites"); - for (let i = 0; i < sites.length; i++) { - if (sites[i]['$id'] == props['$id']) { - sites[i] = { - ...sites[i], - ...props - }; - this.set("sites", sites); - return; - } - } - - sites.push(props); - this.set("sites", sites); - } - - getFunctions() { - if (!this.has("functions")) { - return []; - } - return this.get("functions"); - } - - getFunction($id) { - if (!this.has("functions")) { - return {}; - } - - let functions = this.get("functions"); - for (let i = 0; i < functions.length; i++) { - if (functions[i]['$id'] == $id) { - return functions[i]; - } - } - - return {}; - } - - addFunction(props) { - props = whitelistKeys(props, KeysFunction, { - vars: KeysVars - }); - - if (!this.has("functions")) { - this.set("functions", []); - } - - let functions = this.get("functions"); - for (let i = 0; i < functions.length; i++) { - if (functions[i]['$id'] == props['$id']) { - functions[i] = { - ...functions[i], - ...props - }; - this.set("functions", functions); - return; - } - } - - functions.push(props); - this.set("functions", functions); - } - - getCollections() { - if (!this.has("collections")) { - return []; - } - return this.get("collections"); - } - - getCollection($id) { - if (!this.has("collections")) { - return {}; - } - - let collections = this.get("collections"); - for (let i = 0; i < collections.length; i++) { - if (collections[i]['$id'] == $id) { - return collections[i]; - } - } - - return {}; - } - - addCollection(props) { - props = whitelistKeys(props, KeysCollection, { - attributes: KeysAttributes, - indexes: KeyIndexes - }); - - if (!this.has("collections")) { - this.set("collections", []); - } - - let collections = this.get("collections"); - for (let i = 0; i < collections.length; i++) { - if (collections[i]['$id'] == props['$id'] && collections[i]['databaseId'] == props['databaseId']) { - collections[i] = props; - this.set("collections", collections); - return; - } - } - collections.push(props); - this.set("collections", collections); - } - - getTables() { - if (!this.has("tables")) { - return []; - } - return this.get("tables"); - } - - getTable($id) { - if (!this.has("tables")) { - return {}; - } - - let tables = this.get("tables"); - for (let i = 0; i < tables.length; i++) { - if (tables[i]['$id'] == $id) { - return tables[i]; - } - } - - return {}; - } - - addTable(props) { - props = whitelistKeys(props, KeysTable, { - columns: KeysColumns, - indexes: KeyIndexesColumns - }); - - if (!this.has("tables")) { - this.set("tables", []); - } - - let tables = this.get("tables"); - for (let i = 0; i < tables.length; i++) { - if (tables[i]['$id'] == props['$id'] && tables[i]['databaseId'] == props['databaseId']) { - tables[i] = props; - this.set("tables", tables); - return; - } - } - tables.push(props); - this.set("tables", tables); - } - - getBuckets() { - if (!this.has("buckets")) { - return []; - } - return this.get("buckets"); - } - - getBucket($id) { - if (!this.has("buckets")) { - return {}; - } - - let buckets = this.get("buckets"); - for (let i = 0; i < buckets.length; i++) { - if (buckets[i]['$id'] == $id) { - return buckets[i]; - } - } - - return {}; - } - - addBucket(props) { - props = whitelistKeys(props, KeysStorage); - - if (!this.has("buckets")) { - this.set("buckets", []); - } - - let buckets = this.get("buckets"); - for (let i = 0; i < buckets.length; i++) { - if (buckets[i]['$id'] == props['$id']) { - buckets[i] = props; - this.set("buckets", buckets); - return; - } - } - buckets.push(props); - this.set("buckets", buckets); - } - - getMessagingTopics() { - if (!this.has("topics")) { - return []; - } - return this.get("topics"); - } - - getMessagingTopic($id) { - if (!this.has("topics")) { - return {}; - } - - let topic = this.get("topics"); - for (let i = 0; i < topic.length; i++) { - if (topic[i]['$id'] == $id) { - return topic[i]; - } - } - - return {}; - } - - addMessagingTopic(props) { - props = whitelistKeys(props, KeysTopics); - - if (!this.has("topics")) { - this.set("topics", []); - } - - let topics = this.get("topics"); - for (let i = 0; i < topics.length; i++) { - if (topics[i]['$id'] === props['$id']) { - topics[i] = props; - this.set("topics", topics); - return; - } - } - topics.push(props); - this.set("topics", topics); - } - - getTablesDBs() { - return this._getDBEntities("tablesDB"); - } - - getTablesDB($id) { - return this._getDBEntity("tablesDB", $id); - } - - addTablesDB(props) { - this._addDBEntity("tablesDB", props, KeysDatabase); - } - - getDatabases() { - return this._getDBEntities("databases"); - } - - getDatabase($id) { - return this._getDBEntity("databases", $id); - } - - addDatabase(props) { - this._addDBEntity("databases", props, KeysDatabase); - } - - getTeams() { - if (!this.has("teams")) { - return []; - } - return this.get("teams"); - } - - getTeam($id) { - if (!this.has("teams")) { - return {}; - } - - let teams = this.get("teams"); - for (let i = 0; i < teams.length; i++) { - if (teams[i]['$id'] == $id) { - return teams[i]; - } - } - - return {}; - } - - addTeam(props) { - props = whitelistKeys(props, KeysTeams); - if (!this.has("teams")) { - this.set("teams", []); - } - - let teams = this.get("teams"); - for (let i = 0; i < teams.length; i++) { - if (teams[i]['$id'] == props['$id']) { - teams[i] = props; - this.set("teams", teams); - return; - } - } - teams.push(props); - this.set("teams", teams); - } - - getProject() { - if (!this.has("projectId")) { - return {}; - } - - return { - projectId: this.get("projectId"), - projectName: this.get("projectName"), - projectSettings: this.get('settings') - }; - } - - setProject(projectId, projectName = '', projectSettings = undefined) { - this.set("projectId", projectId); - - if (projectName !== '') { - this.set("projectName", projectName); - } - - if (projectSettings === undefined) { - return; - } - - this.set('settings', this.createSettingsObject(projectSettings)); - } - - createSettingsObject(projectSettings) { - return { - services: { - account: projectSettings.serviceStatusForAccount, - avatars: projectSettings.serviceStatusForAvatars, - databases: projectSettings.serviceStatusForDatabases, - locale: projectSettings.serviceStatusForLocale, - health: projectSettings.serviceStatusForHealth, - storage: projectSettings.serviceStatusForStorage, - teams: projectSettings.serviceStatusForTeams, - users: projectSettings.serviceStatusForUsers, - sites: projectSettings.serviceStatusForSites, - functions: projectSettings.serviceStatusForFunctions, - graphql: projectSettings.serviceStatusForGraphql, - messaging: projectSettings.serviceStatusForMessaging, - }, - auth: { - methods: { - jwt: projectSettings.authJWT, - phone: projectSettings.authPhone, - invites: projectSettings.authInvites, - anonymous: projectSettings.authAnonymous, - "email-otp": projectSettings.authEmailOtp, - "magic-url": projectSettings.authUsersAuthMagicURL, - "email-password": projectSettings.authEmailPassword - }, - security: { - duration: projectSettings.authDuration, - limit: projectSettings.authLimit, - sessionsLimit: projectSettings.authSessionsLimit, - passwordHistory: projectSettings.authPasswordHistory, - passwordDictionary: projectSettings.authPasswordDictionary, - personalDataCheck: projectSettings.authPersonalDataCheck, - sessionAlerts: projectSettings.authSessionAlerts, - mockNumbers: projectSettings.authMockNumbers - }, - } - }; - } -} - -class Global extends Config { - static CONFIG_FILE_PATH = ".appwrite/prefs.json"; - - static PREFERENCE_CURRENT = "current"; - static PREFERENCE_ENDPOINT = "endpoint"; - static PREFERENCE_EMAIL = "email"; - static PREFERENCE_SELF_SIGNED = "selfSigned"; - static PREFERENCE_COOKIE = "cookie"; - static PREFERENCE_PROJECT = "project"; - static PREFERENCE_KEY = "key"; - static PREFERENCE_LOCALE = "locale"; - static PREFERENCE_MODE = "mode"; - - static IGNORE_ATTRIBUTES = [Global.PREFERENCE_CURRENT, Global.PREFERENCE_SELF_SIGNED, Global.PREFERENCE_ENDPOINT, Global.PREFERENCE_COOKIE, Global.PREFERENCE_PROJECT, Global.PREFERENCE_KEY, Global.PREFERENCE_LOCALE, Global.PREFERENCE_MODE]; - - static MODE_ADMIN = "admin"; - static MODE_DEFAULT = "default"; - - static PROJECT_CONSOLE = "console"; - - constructor(path = Global.CONFIG_FILE_PATH) { - const homeDir = os.homedir(); - super(`${homeDir}/${path}`); - } - - getCurrentSession() { - if (!this.has(Global.PREFERENCE_CURRENT)) { - return ""; - } - return this.get(Global.PREFERENCE_CURRENT); - } - - setCurrentSession(session) { - if (session !== undefined) { - this.set(Global.PREFERENCE_CURRENT, session); - } - } - - getSessionIds() { - return Object.keys(this.data).filter((key) => !Global.IGNORE_ATTRIBUTES.includes(key)); - } - - getSessions() { - const sessions = Object.keys(this.data).filter((key) => !Global.IGNORE_ATTRIBUTES.includes(key)) - const current = this.getCurrentSession(); - - const sessionMap = new Map(); - - sessions.forEach((sessionId) => { - const email = this.data[sessionId][Global.PREFERENCE_EMAIL]; - const endpoint = this.data[sessionId][Global.PREFERENCE_ENDPOINT]; - const key = `${email}|${endpoint}`; - - if (sessionId === current || !sessionMap.has(key)) { - sessionMap.set(key, { - id: sessionId, - endpoint: this.data[sessionId][Global.PREFERENCE_ENDPOINT], - email: this.data[sessionId][Global.PREFERENCE_EMAIL] - }); - } - }); - - return Array.from(sessionMap.values()); - } - - addSession(session, data) { - this.set(session, data); - } - - removeSession(session) { - this.delete(session); - } - - getEmail() { - if (!this.hasFrom(Global.PREFERENCE_EMAIL)) { - return ""; - } - - return this.getFrom(Global.PREFERENCE_EMAIL); - } - - setEmail(email) { - this.setTo(Global.PREFERENCE_EMAIL, email); - } - - getEndpoint() { - if (!this.hasFrom(Global.PREFERENCE_ENDPOINT)) { - return ""; - } - - return this.getFrom(Global.PREFERENCE_ENDPOINT); - } - - setEndpoint(endpoint) { - this.setTo(Global.PREFERENCE_ENDPOINT, endpoint); - } - - getSelfSigned() { - if (!this.hasFrom(Global.PREFERENCE_SELF_SIGNED)) { - return false; - } - return this.getFrom(Global.PREFERENCE_SELF_SIGNED); - } - - setSelfSigned(selfSigned) { - this.setTo(Global.PREFERENCE_SELF_SIGNED, selfSigned); - } - - getCookie() { - if (!this.hasFrom(Global.PREFERENCE_COOKIE)) { - return ""; - } - return this.getFrom(Global.PREFERENCE_COOKIE); - } - - setCookie(cookie) { - this.setTo(Global.PREFERENCE_COOKIE, cookie); - } - - getProject() { - if (!this.hasFrom(Global.PREFERENCE_PROJECT)) { - return ""; - } - return this.getFrom(Global.PREFERENCE_PROJECT); - } - - setProject(project) { - this.setTo(Global.PREFERENCE_PROJECT, project); - } - - getKey() { - if (!this.hasFrom(Global.PREFERENCE_KEY)) { - return ""; - } - return this.getFrom(Global.PREFERENCE_KEY); - } - - setKey(key) { - this.setTo(Global.PREFERENCE_KEY, key); - } - - hasFrom(key) { - const current = this.getCurrentSession(); - - if (current) { - const config = this.get(current) ?? {}; - - return config[key] !== undefined; - } - } - - getFrom(key) { - const current = this.getCurrentSession(); - - if (current) { - const config = this.get(current) ?? {}; - - return config[key]; - } - } - - setTo(key, value) { - const current = this.getCurrentSession(); - - if (current) { - const config = this.get(current); - - config[key] = value; - this.write(); - } - } -} - -module.exports = { - localConfig: new Local(), - globalConfig: new Global(), - KeysAttributes, - KeysSite, - KeysFunction, - KeysTopics, - KeysStorage, - KeysTeams, - KeysCollection, - KeysTable, - whitelistKeys -}; diff --git a/lib/config.ts b/lib/config.ts new file mode 100644 index 00000000..c076c557 --- /dev/null +++ b/lib/config.ts @@ -0,0 +1,854 @@ +import os = require('os'); +import fs = require('fs'); +import _path = require('path'); +import process = require('process'); +import JSONbig = require('json-bigint'); +import type { ConfigData, SessionData, GlobalConfigData, ProjectConfigData } from './types'; + +const JSONBigInt = JSONbig({ storeAsString: false }); + +const KeysVars = new Set(['key', 'value']); +const KeysSite = new Set(['path', '$id', 'name', 'enabled', 'logging', 'timeout', 'framework', 'buildRuntime', 'adapter', 'installCommand', 'buildCommand', 'outputDirectory', 'fallbackFile', 'specification', 'vars']); +const KeysFunction = new Set(['path', '$id', 'execute', 'name', 'enabled', 'logging', 'runtime', 'specification', 'scopes', 'events', 'schedule', 'timeout', 'entrypoint', 'commands', 'vars']); +const KeysDatabase = new Set(['$id', 'name', 'enabled']); +const KeysCollection = new Set(['$id', '$permissions', 'databaseId', 'name', 'enabled', 'documentSecurity', 'attributes', 'indexes']); +const KeysTable = new Set(['$id', '$permissions', 'databaseId', 'name', 'enabled', 'rowSecurity', 'columns', 'indexes']); +const KeysStorage = new Set(['$id', '$permissions', 'fileSecurity', 'name', 'enabled', 'maximumFileSize', 'allowedFileExtensions', 'compression', 'encryption', 'antivirus']); +const KeysTopics = new Set(['$id', 'name', 'subscribe']); +const KeysTeams = new Set(['$id', 'name']); +const KeysAttributes = new Set([ + 'key', + 'type', + 'required', + 'array', + 'size', + 'default', + // integer and float + 'min', + 'max', + // email, enum, URL, IP, and datetime + 'format', + // enum + 'elements', + // relationship + 'relatedCollection', + 'relationType', + 'twoWay', + 'twoWayKey', + 'onDelete', + 'side', + // Indexes + 'attributes', + 'orders', + // Strings + 'encrypt', +]); +const KeysColumns = new Set([ + 'key', + 'type', + 'required', + 'array', + 'size', + 'default', + // integer and float + 'min', + 'max', + // email, enum, URL, IP, and datetime + 'format', + // enum + 'elements', + // relationship + 'relatedTable', + 'relationType', + 'twoWay', + 'twoWayKey', + 'onDelete', + 'side', + // Indexes + 'columns', + 'orders', + // Strings + 'encrypt', +]); +const KeyIndexes = new Set(['key', 'type', 'status', 'attributes', 'orders']); +const KeyIndexesColumns = new Set(['key', 'type', 'status', 'columns', 'orders']); + +function whitelistKeys( + value: T, + keys: Set, + nestedKeys: Record> = {} +): T { + if (Array.isArray(value)) { + const newValue: any[] = []; + + for (const item of value) { + newValue.push(whitelistKeys(item, keys, nestedKeys)); + } + + return newValue as T; + } + + const newValue: Record = {}; + Object.keys(value as any).forEach((key) => { + if (keys.has(key)) { + if (nestedKeys[key]) { + newValue[key] = whitelistKeys((value as any)[key], nestedKeys[key]); + } else { + newValue[key] = (value as any)[key]; + } + } + }); + return newValue as T; +} + +class Config { + protected path: string; + protected data: T; + + constructor(path: string) { + this.path = path; + this.data = {} as T; + this.read(); + } + + read(): void { + try { + const file = fs.readFileSync(this.path).toString(); + this.data = JSONBigInt.parse(file); + } catch (e) { + this.data = {} as T; + } + } + + write(): void { + const dir = _path.dirname(this.path); + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true }); + } + fs.writeFileSync(this.path, JSONBigInt.stringify(this.data, null, 4), { mode: 0o600 }); + } + + get(key: K): T[K]; + get(key: string): any { + return this.data[key as keyof T]; + } + + set(key: K, value: T[K]): void; + set(key: string, value: any): void { + (this.data as any)[key] = value; + this.write(); + } + + delete(key: string): void { + delete (this.data as any)[key]; + this.write(); + } + + clear(): void { + this.data = {} as T; + this.write(); + } + + has(key: string): boolean { + return this.data[key as keyof T] !== undefined; + } + + keys(): string[] { + return Object.keys(this.data); + } + + values(): unknown[] { + return Object.values(this.data); + } + + toString(): string { + return JSONBigInt.stringify(this.data, null, 4); + } + + protected _getDBEntities(entityType: string): any[] { + if (!this.has(entityType)) { + return []; + } + return this.get(entityType); + } + + protected _getDBEntity(entityType: string, $id: string): any { + if (!this.has(entityType)) { + return {}; + } + + const entities = this.get(entityType); + for (let i = 0; i < entities.length; i++) { + if (entities[i]['$id'] == $id) { + return entities[i]; + } + } + + return {}; + } + + protected _addDBEntity( + entityType: string, + props: any, + keysSet: Set, + nestedKeys: Record> = {} + ): void { + props = whitelistKeys(props, keysSet, nestedKeys); + + if (!this.has(entityType)) { + this.set(entityType, []); + } + + const entities = this.get(entityType); + for (let i = 0; i < entities.length; i++) { + if (entities[i]['$id'] == props['$id']) { + entities[i] = props; + this.set(entityType, entities); + return; + } + } + entities.push(props); + this.set(entityType, entities); + } +} + +class Local extends Config { + static CONFIG_FILE_PATH = 'appwrite.config.json'; + static CONFIG_FILE_PATH_LEGACY = 'appwrite.json'; + configDirectoryPath = ''; + + constructor(path: string = Local.CONFIG_FILE_PATH, legacyPath: string = Local.CONFIG_FILE_PATH_LEGACY) { + let absolutePath = Local.findConfigFile(path) || Local.findConfigFile(legacyPath); + + if (!absolutePath) { + absolutePath = `${process.cwd()}/${path}`; + } + + super(absolutePath); + this.configDirectoryPath = _path.dirname(absolutePath); + } + + static findConfigFile(filename: string): string | null { + let currentPath = process.cwd(); + + while (true) { + const filePath = `${currentPath}/${filename}`; + + if (fs.existsSync(filePath)) { + return filePath; + } + + const parentDirectory = _path.dirname(currentPath); + if (parentDirectory === currentPath) { + break; + } + currentPath = parentDirectory; + } + + return null; + } + + getDirname(): string { + return _path.dirname(this.path); + } + + getEndpoint(): string { + return this.get('endpoint' as any) || ''; + } + + setEndpoint(endpoint: string): void { + this.set('endpoint' as any, endpoint); + } + + getSites(): any[] { + if (!this.has('sites')) { + return []; + } + return this.get('sites' as any); + } + + getSite($id: string): any { + if (!this.has('sites')) { + return {}; + } + + const sites = this.get('sites' as any); + for (let i = 0; i < sites.length; i++) { + if (sites[i]['$id'] == $id) { + return sites[i]; + } + } + + return {}; + } + + addSite(props: any): void { + props = whitelistKeys(props, KeysSite, { + vars: KeysVars, + }); + + if (!this.has('sites')) { + this.set('sites' as any, []); + } + + const sites = this.get('sites' as any); + for (let i = 0; i < sites.length; i++) { + if (sites[i]['$id'] == props['$id']) { + sites[i] = { + ...sites[i], + ...props, + }; + this.set('sites' as any, sites); + return; + } + } + + sites.push(props); + this.set('sites' as any, sites); + } + + getFunctions(): any[] { + if (!this.has('functions')) { + return []; + } + return this.get('functions' as any); + } + + getFunction($id: string): any { + if (!this.has('functions')) { + return {}; + } + + const functions = this.get('functions' as any); + for (let i = 0; i < functions.length; i++) { + if (functions[i]['$id'] == $id) { + return functions[i]; + } + } + + return {}; + } + + addFunction(props: any): void { + props = whitelistKeys(props, KeysFunction, { + vars: KeysVars, + }); + + if (!this.has('functions')) { + this.set('functions' as any, []); + } + + const functions = this.get('functions' as any); + for (let i = 0; i < functions.length; i++) { + if (functions[i]['$id'] == props['$id']) { + functions[i] = { + ...functions[i], + ...props, + }; + this.set('functions' as any, functions); + return; + } + } + + functions.push(props); + this.set('functions' as any, functions); + } + + getCollections(): any[] { + if (!this.has('collections')) { + return []; + } + return this.get('collections' as any); + } + + getCollection($id: string): any { + if (!this.has('collections')) { + return {}; + } + + const collections = this.get('collections' as any); + for (let i = 0; i < collections.length; i++) { + if (collections[i]['$id'] == $id) { + return collections[i]; + } + } + + return {}; + } + + addCollection(props: any): void { + props = whitelistKeys(props, KeysCollection, { + attributes: KeysAttributes, + indexes: KeyIndexes, + }); + + if (!this.has('collections')) { + this.set('collections' as any, []); + } + + const collections = this.get('collections' as any); + for (let i = 0; i < collections.length; i++) { + if (collections[i]['$id'] == props['$id'] && collections[i]['databaseId'] == props['databaseId']) { + collections[i] = props; + this.set('collections' as any, collections); + return; + } + } + collections.push(props); + this.set('collections' as any, collections); + } + + getTables(): any[] { + if (!this.has('tables')) { + return []; + } + return this.get('tables' as any); + } + + getTable($id: string): any { + if (!this.has('tables')) { + return {}; + } + + const tables = this.get('tables' as any); + for (let i = 0; i < tables.length; i++) { + if (tables[i]['$id'] == $id) { + return tables[i]; + } + } + + return {}; + } + + addTable(props: any): void { + props = whitelistKeys(props, KeysTable, { + columns: KeysColumns, + indexes: KeyIndexesColumns, + }); + + if (!this.has('tables')) { + this.set('tables' as any, []); + } + + const tables = this.get('tables' as any); + for (let i = 0; i < tables.length; i++) { + if (tables[i]['$id'] == props['$id'] && tables[i]['databaseId'] == props['databaseId']) { + tables[i] = props; + this.set('tables' as any, tables); + return; + } + } + tables.push(props); + this.set('tables' as any, tables); + } + + getBuckets(): any[] { + if (!this.has('buckets')) { + return []; + } + return this.get('buckets' as any); + } + + getBucket($id: string): any { + if (!this.has('buckets')) { + return {}; + } + + const buckets = this.get('buckets' as any); + for (let i = 0; i < buckets.length; i++) { + if (buckets[i]['$id'] == $id) { + return buckets[i]; + } + } + + return {}; + } + + addBucket(props: any): void { + props = whitelistKeys(props, KeysStorage); + + if (!this.has('buckets')) { + this.set('buckets' as any, []); + } + + const buckets = this.get('buckets' as any); + for (let i = 0; i < buckets.length; i++) { + if (buckets[i]['$id'] == props['$id']) { + buckets[i] = props; + this.set('buckets' as any, buckets); + return; + } + } + buckets.push(props); + this.set('buckets' as any, buckets); + } + + getMessagingTopics(): any[] { + if (!this.has('topics')) { + return []; + } + return this.get('topics' as any); + } + + getMessagingTopic($id: string): any { + if (!this.has('topics')) { + return {}; + } + + const topic = this.get('topics' as any); + for (let i = 0; i < topic.length; i++) { + if (topic[i]['$id'] == $id) { + return topic[i]; + } + } + + return {}; + } + + addMessagingTopic(props: any): void { + props = whitelistKeys(props, KeysTopics); + + if (!this.has('topics')) { + this.set('topics' as any, []); + } + + const topics = this.get('topics' as any); + for (let i = 0; i < topics.length; i++) { + if (topics[i]['$id'] === props['$id']) { + topics[i] = props; + this.set('topics' as any, topics); + return; + } + } + topics.push(props); + this.set('topics' as any, topics); + } + + getTablesDBs(): any[] { + return this._getDBEntities('tablesDB'); + } + + getTablesDB($id: string): any { + return this._getDBEntity('tablesDB', $id); + } + + addTablesDB(props: any): void { + this._addDBEntity('tablesDB', props, KeysDatabase); + } + + getDatabases(): any[] { + return this._getDBEntities('databases'); + } + + getDatabase($id: string): any { + return this._getDBEntity('databases', $id); + } + + addDatabase(props: any): void { + this._addDBEntity('databases', props, KeysDatabase); + } + + getTeams(): any[] { + if (!this.has('teams')) { + return []; + } + return this.get('teams' as any); + } + + getTeam($id: string): any { + if (!this.has('teams')) { + return {}; + } + + const teams = this.get('teams' as any); + for (let i = 0; i < teams.length; i++) { + if (teams[i]['$id'] == $id) { + return teams[i]; + } + } + + return {}; + } + + addTeam(props: any): void { + props = whitelistKeys(props, KeysTeams); + if (!this.has('teams')) { + this.set('teams' as any, []); + } + + const teams = this.get('teams' as any); + for (let i = 0; i < teams.length; i++) { + if (teams[i]['$id'] == props['$id']) { + teams[i] = props; + this.set('teams' as any, teams); + return; + } + } + teams.push(props); + this.set('teams' as any, teams); + } + + getProject(): { projectId?: string; projectName?: string; projectSettings?: any } { + if (!this.has('projectId')) { + return {}; + } + + return { + projectId: this.get('projectId' as any), + projectName: this.get('projectName' as any), + projectSettings: this.get('settings' as any), + }; + } + + setProject(projectId: string, projectName: string = '', projectSettings: any = undefined): void { + this.set('projectId' as any, projectId); + + if (projectName !== '') { + this.set('projectName' as any, projectName); + } + + if (projectSettings === undefined) { + return; + } + + this.set('settings' as any, this.createSettingsObject(projectSettings)); + } + + createSettingsObject(projectSettings: any): any { + return { + services: { + account: projectSettings.serviceStatusForAccount, + avatars: projectSettings.serviceStatusForAvatars, + databases: projectSettings.serviceStatusForDatabases, + locale: projectSettings.serviceStatusForLocale, + health: projectSettings.serviceStatusForHealth, + storage: projectSettings.serviceStatusForStorage, + teams: projectSettings.serviceStatusForTeams, + users: projectSettings.serviceStatusForUsers, + sites: projectSettings.serviceStatusForSites, + functions: projectSettings.serviceStatusForFunctions, + graphql: projectSettings.serviceStatusForGraphql, + messaging: projectSettings.serviceStatusForMessaging, + }, + auth: { + methods: { + jwt: projectSettings.authJWT, + phone: projectSettings.authPhone, + invites: projectSettings.authInvites, + anonymous: projectSettings.authAnonymous, + 'email-otp': projectSettings.authEmailOtp, + 'magic-url': projectSettings.authUsersAuthMagicURL, + 'email-password': projectSettings.authEmailPassword, + }, + security: { + duration: projectSettings.authDuration, + limit: projectSettings.authLimit, + sessionsLimit: projectSettings.authSessionsLimit, + passwordHistory: projectSettings.authPasswordHistory, + passwordDictionary: projectSettings.authPasswordDictionary, + personalDataCheck: projectSettings.authPersonalDataCheck, + sessionAlerts: projectSettings.authSessionAlerts, + mockNumbers: projectSettings.authMockNumbers, + }, + }, + }; + } +} + +class Global extends Config { + static CONFIG_FILE_PATH = '.appwrite/prefs.json'; + + static PREFERENCE_CURRENT = 'current'; + static PREFERENCE_ENDPOINT = 'endpoint'; + static PREFERENCE_EMAIL = 'email'; + static PREFERENCE_SELF_SIGNED = 'selfSigned'; + static PREFERENCE_COOKIE = 'cookie'; + static PREFERENCE_PROJECT = 'project'; + static PREFERENCE_KEY = 'key'; + static PREFERENCE_LOCALE = 'locale'; + static PREFERENCE_MODE = 'mode'; + + static IGNORE_ATTRIBUTES = [ + Global.PREFERENCE_CURRENT, + Global.PREFERENCE_SELF_SIGNED, + Global.PREFERENCE_ENDPOINT, + Global.PREFERENCE_COOKIE, + Global.PREFERENCE_PROJECT, + Global.PREFERENCE_KEY, + Global.PREFERENCE_LOCALE, + Global.PREFERENCE_MODE, + ]; + + static MODE_ADMIN = 'admin'; + static MODE_DEFAULT = 'default'; + + static PROJECT_CONSOLE = 'console'; + + constructor(path: string = Global.CONFIG_FILE_PATH) { + const homeDir = os.homedir(); + super(`${homeDir}/${path}`); + } + + getCurrentSession(): string { + if (!this.has(Global.PREFERENCE_CURRENT)) { + return ''; + } + return this.get(Global.PREFERENCE_CURRENT as any); + } + + setCurrentSession(session: string): void { + if (session !== undefined) { + this.set(Global.PREFERENCE_CURRENT as any, session); + } + } + + getSessionIds(): string[] { + return Object.keys(this.data).filter((key) => !Global.IGNORE_ATTRIBUTES.includes(key)); + } + + getSessions(): Array<{ id: string; endpoint: string; email: string }> { + const sessions = Object.keys(this.data).filter((key) => !Global.IGNORE_ATTRIBUTES.includes(key)); + const current = this.getCurrentSession(); + + const sessionMap = new Map(); + + sessions.forEach((sessionId) => { + const sessionData = (this.data as any)[sessionId]; + const email = sessionData[Global.PREFERENCE_EMAIL]; + const endpoint = sessionData[Global.PREFERENCE_ENDPOINT]; + const key = `${email}|${endpoint}`; + + if (sessionId === current || !sessionMap.has(key)) { + sessionMap.set(key, { + id: sessionId, + endpoint: sessionData[Global.PREFERENCE_ENDPOINT], + email: sessionData[Global.PREFERENCE_EMAIL], + }); + } + }); + + return Array.from(sessionMap.values()); + } + + addSession(session: string, data: SessionData): void { + this.set(session as any, data as any); + } + + removeSession(session: string): void { + this.delete(session); + } + + getEmail(): string { + if (!this.hasFrom(Global.PREFERENCE_EMAIL)) { + return ''; + } + + return this.getFrom(Global.PREFERENCE_EMAIL); + } + + setEmail(email: string): void { + this.setTo(Global.PREFERENCE_EMAIL, email); + } + + getEndpoint(): string { + if (!this.hasFrom(Global.PREFERENCE_ENDPOINT)) { + return ''; + } + + return this.getFrom(Global.PREFERENCE_ENDPOINT); + } + + setEndpoint(endpoint: string): void { + this.setTo(Global.PREFERENCE_ENDPOINT, endpoint); + } + + getSelfSigned(): boolean { + if (!this.hasFrom(Global.PREFERENCE_SELF_SIGNED)) { + return false; + } + return this.getFrom(Global.PREFERENCE_SELF_SIGNED); + } + + setSelfSigned(selfSigned: boolean): void { + this.setTo(Global.PREFERENCE_SELF_SIGNED, selfSigned); + } + + getCookie(): string { + if (!this.hasFrom(Global.PREFERENCE_COOKIE)) { + return ''; + } + return this.getFrom(Global.PREFERENCE_COOKIE); + } + + setCookie(cookie: string): void { + this.setTo(Global.PREFERENCE_COOKIE, cookie); + } + + getProject(): string { + if (!this.hasFrom(Global.PREFERENCE_PROJECT)) { + return ''; + } + return this.getFrom(Global.PREFERENCE_PROJECT); + } + + setProject(project: string): void { + this.setTo(Global.PREFERENCE_PROJECT, project); + } + + getKey(): string { + if (!this.hasFrom(Global.PREFERENCE_KEY)) { + return ''; + } + return this.getFrom(Global.PREFERENCE_KEY); + } + + setKey(key: string): void { + this.setTo(Global.PREFERENCE_KEY, key); + } + + hasFrom(key: string): boolean { + const current = this.getCurrentSession(); + + if (current) { + const config = this.get(current as any) ?? {}; + + return (config as any)[key] !== undefined; + } + return false; + } + + getFrom(key: string): any { + const current = this.getCurrentSession(); + + if (current) { + const config = this.get(current as any) ?? {}; + + return (config as any)[key]; + } + } + + setTo(key: string, value: any): void { + const current = this.getCurrentSession(); + + if (current) { + const config = this.get(current as any); + + (config as any)[key] = value; + this.write(); + } + } +} + +export const localConfig = new Local(); +export const globalConfig = new Global(); +export { + KeysAttributes, + KeysSite, + KeysFunction, + KeysTopics, + KeysStorage, + KeysTeams, + KeysCollection, + KeysTable, + whitelistKeys, +}; diff --git a/lib/emulation/docker.js b/lib/emulation/docker.ts similarity index 79% rename from lib/emulation/docker.js rename to lib/emulation/docker.ts index 0b774d86..8acd672b 100644 --- a/lib/emulation/docker.js +++ b/lib/emulation/docker.ts @@ -1,16 +1,24 @@ -const tar = require("tar"); -const ignore = require("ignore"); -const net = require('net'); -const chalk = require('chalk'); -const childProcess = require('child_process'); -const { localConfig } = require("../config"); -const path = require('path'); -const fs = require('fs'); -const { log, error, success, hint } = require("../parser"); -const { openRuntimesVersion, systemTools, Queue } = require("./utils"); -const { getAllFiles } = require("../utils"); - -async function dockerStop(id) { +import ignore = require('ignore'); +import net = require('net'); +import chalk from 'chalk'; +import childProcess = require('child_process'); +import { localConfig } from '../config'; +import path = require('path'); +import fs = require('fs'); +import { log, error, success } from '../parser'; +import { openRuntimesVersion, systemTools, Queue } from './utils'; +import { getAllFiles } from '../utils'; + +interface FunctionConfig { + $id: string; + runtime: string; + path: string; + entrypoint: string; + commands: string; + ignore?: string; +} + +export async function dockerStop(id: string): Promise { const stopProcess = childProcess.spawn('docker', ['rm', '--force', id], { stdio: 'pipe', env: { @@ -19,10 +27,10 @@ async function dockerStop(id) { } }); - await new Promise((res) => { stopProcess.on('close', res) }); + await new Promise((res) => { stopProcess.on('close', res) }); } -async function dockerPull(func) { +export async function dockerPull(func: FunctionConfig): Promise { const runtimeChunks = func.runtime.split("-"); const runtimeVersion = runtimeChunks.pop(); const runtimeName = runtimeChunks.join("-"); @@ -38,10 +46,10 @@ async function dockerPull(func) { } }); - await new Promise((res) => { pullProcess.on('close', res) }); + await new Promise((res) => { pullProcess.on('close', res) }); } -async function dockerBuild(func, variables) { +export async function dockerBuild(func: FunctionConfig, variables: Record): Promise { const runtimeChunks = func.runtime.split("-"); const runtimeVersion = runtimeChunks.pop(); const runtimeName = runtimeChunks.join("-"); @@ -51,7 +59,7 @@ async function dockerBuild(func, variables) { const id = func.$id; - const ignorer = ignore(); + const ignorer = ignore.default(); ignorer.add('.appwrite'); if (func.ignore) { ignorer.add(func.ignore); @@ -76,7 +84,7 @@ async function dockerBuild(func, variables) { fs.copyFileSync(sourcePath, filePath); } - const params = [ 'run' ]; + const params: string[] = [ 'run' ]; params.push('--name', id); params.push('-v', `${tmpBuildPath}/:/mnt/code:rw`); params.push('-e', 'OPEN_RUNTIMES_ENV=development'); @@ -91,7 +99,7 @@ async function dockerBuild(func, variables) { const buildProcess = childProcess.spawn('docker', params, { stdio: 'pipe', - pwd: functionDir, + cwd: functionDir, env: { ...process.env, DOCKER_CLI_HINTS: 'false' @@ -117,7 +125,7 @@ async function dockerBuild(func, variables) { } }, 100); - await new Promise((res) => { buildProcess.on('close', res) }); + await new Promise((res) => { buildProcess.on('close', res) }); clearInterval(killInterval); if(!Queue.isEmpty()) { @@ -132,14 +140,14 @@ async function dockerBuild(func, variables) { const copyProcess = childProcess.spawn('docker', ['cp', `${id}:/mnt/code/code.tar.gz`, copyPath], { stdio: 'pipe', - pwd: functionDir, + cwd: functionDir, env: { ...process.env, DOCKER_CLI_HINTS: 'false' } }); - await new Promise((res) => { copyProcess.on('close', res) }); + await new Promise((res) => { copyProcess.on('close', res) }); await dockerStop(id); @@ -151,7 +159,7 @@ async function dockerBuild(func, variables) { fs.rmSync(tmpBuildPath, { recursive: true, force: true }); } -async function dockerStart(func, variables, port) { +export async function dockerStart(func: FunctionConfig, variables: Record, port: number): Promise { // Pack function files const functionDir = path.join(localConfig.getDirname(), func.path); @@ -164,7 +172,7 @@ async function dockerStart(func, variables, port) { const id = func.$id; - const params = [ 'run' ]; + const params: string[] = [ 'run' ]; params.push('--rm'); params.push('--name', id); params.push('-p', `${port}:3000`); @@ -182,7 +190,7 @@ async function dockerStart(func, variables, port) { const startProcess = childProcess.spawn('docker', params, { stdio: 'pipe', - pwd: functionDir, + cwd: functionDir, env: { ...process.env, DOCKER_CLI_HINTS: 'false' @@ -199,15 +207,15 @@ async function dockerStart(func, variables, port) { try { await waitUntilPortOpen(port); - } catch(err) { - error("Failed to start function with error: " + err.message ? err.message : err.toString()); + } catch(err: any) { + error("Failed to start function with error: " + (err.message ? err.message : err.toString())); return; } success(`Visit http://localhost:${port}/ to execute your function.`); } -async function dockerCleanup(functionId) { +export async function dockerCleanup(functionId: string): Promise { await dockerStop(functionId); const func = localConfig.getFunction(functionId); @@ -222,7 +230,7 @@ async function dockerCleanup(functionId) { } } -function waitUntilPortOpen(port, iteration = 0) { +function waitUntilPortOpen(port: number, iteration: number = 0): Promise { return new Promise((resolve, reject) => { const client = new net.Socket(); @@ -246,7 +254,7 @@ function waitUntilPortOpen(port, iteration = 0) { if(iteration > 100) { reject(err); } else { - await new Promise((res) => setTimeout(res, 100)); + await new Promise((res) => setTimeout(res, 100)); waitUntilPortOpen(port, iteration + 1).then(resolve).catch(reject); } }); @@ -255,10 +263,3 @@ function waitUntilPortOpen(port, iteration = 0) { }); } -module.exports = { - dockerPull, - dockerBuild, - dockerStart, - dockerCleanup, - dockerStop, -} diff --git a/lib/emulation/utils.js b/lib/emulation/utils.js deleted file mode 100644 index 53ef6118..00000000 --- a/lib/emulation/utils.js +++ /dev/null @@ -1,186 +0,0 @@ -const EventEmitter = require('node:events'); -const { projectsCreateJWT } = require('../commands/projects'); -const { localConfig } = require("../config"); -const { usersGet, usersCreateJWT } = require("../commands/users"); -const { log } = require("../parser"); - -const openRuntimesVersion = 'v4'; - -const runtimeNames = { - 'node': 'Node.js', - 'php': 'PHP', - 'ruby': 'Ruby', - 'python': 'Python', - 'python-ml': 'Python (ML)', - 'deno': 'Deno', - 'dart': 'Dart', - 'dotnet': '.NET', - 'java': 'Java', - 'swift': 'Swift', - 'kotlin': 'Kotlin', - 'bun': 'Bun', - 'go': 'Go', -}; - -const systemTools = { - 'node': { - isCompiled: false, - startCommand: "sh helpers/server.sh", - dependencyFiles: [ "package.json", "package-lock.json" ] - }, - 'php': { - isCompiled: false, - startCommand: "sh helpers/server.sh", - dependencyFiles: [ "composer.json", "composer.lock" ] - }, - 'ruby': { - isCompiled: false, - startCommand: "sh helpers/server.sh", - dependencyFiles: [ "Gemfile", "Gemfile.lock" ] - }, - 'python': { - isCompiled: false, - startCommand: "sh helpers/server.sh", - dependencyFiles: [ "requirements.txt", "requirements.lock" ] - }, - 'python-ml': { - isCompiled: false, - startCommand: "sh helpers/server.sh", - dependencyFiles: [ "requirements.txt", "requirements.lock" ] - }, - 'deno': { - isCompiled: false, - startCommand: "sh helpers/server.sh", - dependencyFiles: [ ] - }, - 'dart': { - isCompiled: true, - startCommand: "sh helpers/server.sh", - dependencyFiles: [ ] - }, - 'dotnet': { - isCompiled: true, - startCommand: "sh helpers/server.sh", - dependencyFiles: [ ] - }, - 'java': { - isCompiled: true, - startCommand: "sh helpers/server.sh", - dependencyFiles: [ ] - }, - 'swift': { - isCompiled: true, - startCommand: "sh helpers/server.sh", - dependencyFiles: [ ] - }, - 'kotlin': { - isCompiled: true, - startCommand: "sh helpers/server.sh", - dependencyFiles: [ ] - }, - 'bun': { - isCompiled: false, - startCommand: "sh helpers/server.sh", - dependencyFiles: [ "package.json", "package-lock.json", "bun.lockb" ] - }, - 'go': { - isCompiled: true, - startCommand: "sh helpers/server.sh", - dependencyFiles: [ ] - }, -}; - -const JwtManager = { - userJwt: null, - functionJwt: null, - - timerWarn: null, - timerError: null, - - async setup(userId = null, projectScopes = []) { - if(this.timerWarn) { - clearTimeout(this.timerWarn); - } - - if(this.timerError) { - clearTimeout(this.timerError); - } - - this.timerWarn = setTimeout(() => { - log("Warning: Authorized JWT will expire in 5 minutes. Please stop and re-run the command to refresh tokens for 1 hour."); - }, 1000 * 60 * 55); // 55 mins - - this.timerError = setTimeout(() => { - log("Warning: Authorized JWT just expired. Please stop and re-run the command to obtain new tokens with 1 hour validity."); - log("Some Appwrite API communication is not authorized now.") - }, 1000 * 60 * 60); // 60 mins - - if(userId) { - await usersGet({ - userId, - parseOutput: false - }); - const userResponse = await usersCreateJWT({ - userId, - duration: 60*60, - parseOutput: false - }); - this.userJwt = userResponse.jwt; - } - - const functionResponse = await projectsCreateJWT({ - projectId: localConfig.getProject().projectId, - scopes: projectScopes, - duration: 60*60, - parseOutput: false - }); - this.functionJwt = functionResponse.jwt; - } -}; - -const Queue = { - files: [], - locked: false, - events: new EventEmitter(), - debounce: null, - push(file) { - if(!this.files.includes(file)) { - this.files.push(file); - } - - if(!this.locked) { - this._trigger(); - } - }, - lock() { - this.files = []; - this.locked = true; - }, - isEmpty() { - return this.files.length === 0 - }, - unlock() { - this.locked = false; - if(this.files.length > 0) { - this._trigger(); - } - }, - _trigger() { - if(this.debounce) { - return; - } - - this.debounce = setTimeout(() => { - this.events.emit('reload', { files: this.files }); - this.debounce = null; - }, 300); - } -}; - -module.exports = { - openRuntimesVersion, - runtimeNames, - systemTools, - JwtManager, - Queue -} diff --git a/lib/emulation/utils.ts b/lib/emulation/utils.ts new file mode 100644 index 00000000..787b4dfc --- /dev/null +++ b/lib/emulation/utils.ts @@ -0,0 +1,193 @@ +import { EventEmitter } from 'node:events'; +import { projectsCreateJWT } from '../commands/projects'; +import { localConfig } from '../config'; +import { usersGet, usersCreateJWT } from '../commands/users'; +import { log } from '../parser'; + +export const openRuntimesVersion = 'v4'; + +export const runtimeNames: Record = { + node: 'Node.js', + php: 'PHP', + ruby: 'Ruby', + python: 'Python', + 'python-ml': 'Python (ML)', + deno: 'Deno', + dart: 'Dart', + dotnet: '.NET', + java: 'Java', + swift: 'Swift', + kotlin: 'Kotlin', + bun: 'Bun', + go: 'Go', +}; + +interface SystemTool { + isCompiled: boolean; + startCommand: string; + dependencyFiles: string[]; +} + +export const systemTools: Record = { + node: { + isCompiled: false, + startCommand: 'sh helpers/server.sh', + dependencyFiles: ['package.json', 'package-lock.json'], + }, + php: { + isCompiled: false, + startCommand: 'sh helpers/server.sh', + dependencyFiles: ['composer.json', 'composer.lock'], + }, + ruby: { + isCompiled: false, + startCommand: 'sh helpers/server.sh', + dependencyFiles: ['Gemfile', 'Gemfile.lock'], + }, + python: { + isCompiled: false, + startCommand: 'sh helpers/server.sh', + dependencyFiles: ['requirements.txt', 'requirements.lock'], + }, + 'python-ml': { + isCompiled: false, + startCommand: 'sh helpers/server.sh', + dependencyFiles: ['requirements.txt', 'requirements.lock'], + }, + deno: { + isCompiled: false, + startCommand: 'sh helpers/server.sh', + dependencyFiles: [], + }, + dart: { + isCompiled: true, + startCommand: 'sh helpers/server.sh', + dependencyFiles: [], + }, + dotnet: { + isCompiled: true, + startCommand: 'sh helpers/server.sh', + dependencyFiles: [], + }, + java: { + isCompiled: true, + startCommand: 'sh helpers/server.sh', + dependencyFiles: [], + }, + swift: { + isCompiled: true, + startCommand: 'sh helpers/server.sh', + dependencyFiles: [], + }, + kotlin: { + isCompiled: true, + startCommand: 'sh helpers/server.sh', + dependencyFiles: [], + }, + bun: { + isCompiled: false, + startCommand: 'sh helpers/server.sh', + dependencyFiles: ['package.json', 'package-lock.json', 'bun.lockb'], + }, + go: { + isCompiled: true, + startCommand: 'sh helpers/server.sh', + dependencyFiles: [], + }, +}; + +export const JwtManager = { + userJwt: null as string | null, + functionJwt: null as string | null, + + timerWarn: null as NodeJS.Timeout | null, + timerError: null as NodeJS.Timeout | null, + + async setup(userId: string | null = null, projectScopes: string[] = []): Promise { + if (this.timerWarn) { + clearTimeout(this.timerWarn); + } + + if (this.timerError) { + clearTimeout(this.timerError); + } + + this.timerWarn = setTimeout(() => { + log('Warning: Authorized JWT will expire in 5 minutes. Please stop and re-run the command to refresh tokens for 1 hour.'); + }, 1000 * 60 * 55); // 55 mins + + this.timerError = setTimeout(() => { + log('Warning: Authorized JWT just expired. Please stop and re-run the command to obtain new tokens with 1 hour validity.'); + log('Some Appwrite API communication is not authorized now.'); + }, 1000 * 60 * 60); // 60 mins + + if (userId) { + await usersGet({ + userId, + parseOutput: false, + }); + const userResponse: any = await usersCreateJWT({ + userId, + duration: 60 * 60, + parseOutput: false, + }); + this.userJwt = userResponse.jwt; + } + + const functionResponse: any = await projectsCreateJWT({ + projectId: localConfig.getProject().projectId!, + scopes: projectScopes, + duration: 60 * 60, + parseOutput: false, + }); + this.functionJwt = functionResponse.jwt; + }, +}; + +interface QueueReloadEvent { + files: string[]; +} + +export const Queue = { + files: [] as string[], + locked: false, + events: new EventEmitter(), + debounce: null as NodeJS.Timeout | null, + + push(file: string): void { + if (!this.files.includes(file)) { + this.files.push(file); + } + + if (!this.locked) { + this._trigger(); + } + }, + + lock(): void { + this.files = []; + this.locked = true; + }, + + isEmpty(): boolean { + return this.files.length === 0; + }, + + unlock(): void { + this.locked = false; + if (this.files.length > 0) { + this._trigger(); + } + }, + + _trigger(): void { + if (this.debounce) { + return; + } + + this.debounce = setTimeout(() => { + this.events.emit('reload', { files: this.files } as QueueReloadEvent); + this.debounce = null; + }, 300); + }, +}; diff --git a/lib/exception.js b/lib/exception.js deleted file mode 100644 index 6d962de7..00000000 --- a/lib/exception.js +++ /dev/null @@ -1,9 +0,0 @@ -class AppwriteException extends Error { - constructor(message, code, response) { - super(message); - this.code = code; - this.response = response; - } -} - -module.exports = AppwriteException; \ No newline at end of file diff --git a/lib/exception.ts b/lib/exception.ts new file mode 100644 index 00000000..6bdd66d8 --- /dev/null +++ b/lib/exception.ts @@ -0,0 +1,20 @@ +class AppwriteException extends Error { + public code?: number; + public type?: string; + public response?: string; + + constructor(message: string, code?: number, type?: string, response?: string) { + super(message); + this.name = 'AppwriteException'; + this.code = code; + this.type = type; + this.response = response; + + // Maintains proper stack trace for where our error was thrown (only available on V8) + if (Error.captureStackTrace) { + Error.captureStackTrace(this, AppwriteException); + } + } +} + +export = AppwriteException; diff --git a/lib/id.js b/lib/id.ts similarity index 83% rename from lib/id.js rename to lib/id.ts index b628463d..abcaea4b 100644 --- a/lib/id.js +++ b/lib/id.ts @@ -1,7 +1,7 @@ class ID { // Generate an hex ID based on timestamp // Recreated from https://www.php.net/manual/en/function.uniqid.php - static #hexTimestamp() { + static #hexTimestamp(): string { const now = new Date(); const sec = Math.floor(now.getTime() / 1000); const msec = now.getMilliseconds(); @@ -11,11 +11,11 @@ class ID { return hexTimestamp; } - static custom(id) { - return id + static custom(id: string): string { + return id; } - static unique(padding = 7) { + static unique(padding: number = 7): string { // Generate a unique ID with padding to have a longer ID const baseId = ID.#hexTimestamp(); let randomPadding = ''; @@ -27,4 +27,4 @@ class ID { } } -module.exports = ID; +export = ID; diff --git a/lib/paginate.js b/lib/paginate.ts similarity index 68% rename from lib/paginate.js rename to lib/paginate.ts index 1d511e51..38665663 100644 --- a/lib/paginate.js +++ b/lib/paginate.ts @@ -1,6 +1,21 @@ -const paginate = async (action, args = {}, limit = 100, wrapper = '', queries = []) => { +interface PaginateArgs { + [key: string]: any; +} + +interface PaginateResponse { + [key: string]: T; + total: number; +} + +export const paginate = async ( + action: (args: PaginateArgs) => Promise, + args: PaginateArgs = {}, + limit: number = 100, + wrapper: string = '', + queries: string[] = [] +): Promise> => { let pageNumber = 0; - let results = []; + let results: T[] = []; let total = 0; while (true) { @@ -12,8 +27,8 @@ const paginate = async (action, args = {}, limit = 100, wrapper = '', queries = queries: [ ...queries, JSON.stringify({ method: 'limit', values: [limit] }), - JSON.stringify({ method: 'offset', values: [offset] }) - ] + JSON.stringify({ method: 'offset', values: [offset] }), + ], }); if (wrapper === '') { @@ -44,9 +59,5 @@ const paginate = async (action, args = {}, limit = 100, wrapper = '', queries = return { [wrapper]: results, total, - }; -} - -module.exports = { - paginate + } as PaginateResponse; }; diff --git a/lib/parser.js b/lib/parser.js deleted file mode 100644 index 8de61e4a..00000000 --- a/lib/parser.js +++ /dev/null @@ -1,250 +0,0 @@ -const chalk = require('chalk'); -const commander = require('commander'); -const Table = require('cli-table3'); -const { description } = require('../package.json'); -const { globalConfig } = require("./config.js"); -const os = require('os'); -const Client = require("./client"); -const { isCloud } = require("./utils"); - -const cliConfig = { - verbose: false, - json: false, - force: false, - all: false, - ids: [], - report: false, - reportData: {} -}; - -const parse = (data) => { - if (cliConfig.json) { - drawJSON(data); - return; - } - - for (let key in data) { - if (data[key] === null) { - console.log(`${chalk.yellow.bold(key)} : null`); - } else if (Array.isArray(data[key])) { - console.log(`${chalk.yellow.bold.underline(key)}`); - if (typeof data[key][0] === 'object') { - drawTable(data[key]); - } else { - drawJSON(data[key]); - } - } else if (typeof data[key] === 'object') { - if (data[key]?.constructor?.name === 'BigNumber') { - console.log(`${chalk.yellow.bold(key)} : ${data[key]}`); - } else { - console.log(`${chalk.yellow.bold.underline(key)}`) - drawTable([data[key]]); - } - } else { - console.log(`${chalk.yellow.bold(key)} : ${data[key]}`); - } - } -} - -const drawTable = (data) => { - if (data.length == 0) { - console.log("[]") - return; - } - - // Create an object with all the keys in it - let obj = data.reduce((res, item) => ({ ...res, ...item })); - // Get those keys as an array - let keys = Object.keys(obj); - // Create an object with all keys set to the default value '' - let def = keys.reduce((result, key) => { - result[key] = '-' - return result; - }, {}); - // Use object destrucuring to replace all default values with the ones we have - data = data.map((item) => ({ ...def, ...item })); - - let columns = Object.keys(data[0]); - - let table = new Table({ - head: columns.map(c => chalk.cyan.italic.bold(c)), - chars: { - 'top': ' ', - 'top-mid': ' ', - 'top-left': ' ', - 'top-right': ' ', - 'bottom': ' ', - 'bottom-mid': ' ', - 'bottom-left': ' ', - 'bottom-right': ' ', - 'left': ' ', - 'left-mid': ' ', - 'mid': chalk.cyan('─'), - 'mid-mid': chalk.cyan('┼'), - 'right': ' ', - 'right-mid': ' ', - 'middle': chalk.cyan('│') - } - }); - - data.forEach(row => { - let rowValues = []; - for (let key in row) { - if (row[key] === null) { - rowValues.push("-"); - } else if (Array.isArray(row[key])) { - rowValues.push(JSON.stringify(row[key])); - } else if (typeof row[key] === 'object') { - rowValues.push(JSON.stringify(row[key])); - } else { - rowValues.push(row[key]); - } - } - table.push(rowValues); - }); - console.log(table.toString()); -} - -const drawJSON = (data) => { - console.log(JSON.stringify(data, null, 2)); -} - -const parseError = (err) => { - if (cliConfig.report) { - (async () => { - let appwriteVersion = 'unknown'; - const endpoint = globalConfig.getEndpoint(); - - try { - const client = new Client().setEndpoint(endpoint); - const res = await client.call('get', '/health/version'); - appwriteVersion = res.version; - } catch { - } - - const version = '12.0.1'; - const stepsToReproduce = `Running \`appwrite ${cliConfig.reportData.data.args.join(' ')}\``; - const yourEnvironment = `CLI version: ${version}\nOperation System: ${os.type()}\nAppwrite version: ${appwriteVersion}\nIs Cloud: ${isCloud()}`; - - const stack = '```\n' + err.stack + '\n```'; - - const githubIssueUrl = new URL('https://github.com/appwrite/appwrite/issues/new'); - githubIssueUrl.searchParams.append('labels', 'bug'); - githubIssueUrl.searchParams.append('template', 'bug.yaml'); - githubIssueUrl.searchParams.append('title', `šŸ› Bug Report: ${err.message}`); - githubIssueUrl.searchParams.append('actual-behavior', `CLI Error:\n${stack}`); - githubIssueUrl.searchParams.append('steps-to-reproduce', stepsToReproduce); - githubIssueUrl.searchParams.append('environment', yourEnvironment); - - log(`To report this error you can:\n - Create a support ticket in our Discord server https://appwrite.io/discord \n - Create an issue in our Github\n ${githubIssueUrl.href}\n`); - - - error('\n Stack Trace: \n'); - console.error(err); - process.exit(1); - })() - } else { - if (cliConfig.verbose) { - console.error(err); - } else { - log('For detailed error pass the --verbose or --report flag'); - error(err.message); - } - process.exit(1); - } - -} - -const actionRunner = (fn) => { - return (...args) => { - if (cliConfig.all && (Array.isArray(cliConfig.ids) && cliConfig.ids.length !== 0)) { - error(`The '--all' and '--id' flags cannot be used together.`); - process.exit(1); - } - return fn(...args).catch(parseError) - }; -} - -const parseInteger = (value) => { - const parsedValue = parseInt(value, 10); - if (isNaN(parsedValue)) { - throw new commander.InvalidArgumentError('Not a number.'); - } - return parsedValue; -} - -const parseBool = (value) => { - if (value === 'true') return true; - if (value === 'false') return false; - throw new commander.InvalidArgumentError('Not a boolean.'); -} - -const log = (message) => { - console.log(`${chalk.cyan.bold("ℹ Info:")} ${chalk.cyan(message ?? "")}`); -} - -const warn = (message) => { - console.log(`${chalk.yellow.bold("ℹ Warning:")} ${chalk.yellow(message ?? "")}`); -} - -const hint = (message) => { - console.log(`${chalk.cyan.bold("♄ Hint:")} ${chalk.cyan(message ?? "")}`); -} - -const success = (message) => { - console.log(`${chalk.green.bold("āœ“ Success:")} ${chalk.green(message ?? "")}`); -} - -const error = (message) => { - console.error(`${chalk.red.bold("āœ— Error:")} ${chalk.red(message ?? "")}`); -} - -const logo = "\n _ _ _ ___ __ _____\n \/_\\ _ __ _ ____ ___ __(_) |_ ___ \/ __\\ \/ \/ \\_ \\\n \/\/_\\\\| '_ \\| '_ \\ \\ \/\\ \/ \/ '__| | __\/ _ \\ \/ \/ \/ \/ \/ \/\\\/\n \/ _ \\ |_) | |_) \\ V V \/| | | | || __\/ \/ \/___\/ \/___\/\\\/ \/_\n \\_\/ \\_\/ .__\/| .__\/ \\_\/\\_\/ |_| |_|\\__\\___| \\____\/\\____\/\\____\/\n |_| |_|\n\n"; - -const commandDescriptions = { - "account": `The account command allows you to authenticate and manage a user account.`, - "graphql": `The graphql command allows you to query and mutate any resource type on your Appwrite server.`, - "avatars": `The avatars command aims to help you complete everyday tasks related to your app image, icons, and avatars.`, - "databases": `(Legacy) The databases command allows you to create structured collections of documents and query and filter lists of documents.`, - 'tables-db': `The tables-db command allows you to create structured tables of columns and query and filter lists of rows.`, - "init": `The init command provides a convenient wrapper for creating and initializing projects, functions, collections, buckets, teams, and messaging-topics in Appwrite.`, - "push": `The push command provides a convenient wrapper for pushing your functions, collections, buckets, teams, and messaging-topics.`, - "run": `The run command allows you to run the project locally to allow easy development and quick debugging.`, - "functions": `The functions command allows you to view, create, and manage your Cloud Functions.`, - "health": `The health command allows you to both validate and monitor your Appwrite server's health.`, - "pull": `The pull command helps you pull your Appwrite project, functions, collections, buckets, teams, and messaging-topics`, - "locale": `The locale command allows you to customize your app based on your users' location.`, - "sites": `The sites command allows you to view, create and manage your Appwrite Sites.`, - "storage": `The storage command allows you to manage your project files.`, - "teams": `The teams command allows you to group users of your project to enable them to share read and write access to your project resources.`, - "update": `The update command allows you to update the Appwrite CLI to the latest version.`, - "users": `The users command allows you to manage your project users.`, - "projects": `The projects command allows you to manage your projects, add platforms, manage API keys, Dev Keys etc.`, - "project": `The project command allows you to manage project related resources like usage, variables, etc.`, - "client": `The client command allows you to configure your CLI`, - "login": `The login command allows you to authenticate and manage a user account.`, - "logout": `The logout command allows you to log out of your Appwrite account.`, - "whoami": `The whomai command gives information about the currently logged-in user.`, - "register": `Outputs the link to create an Appwrite account.`, - "console" : `The console command gives you access to the APIs used by the Appwrite Console.`, - "messaging": `The messaging command allows you to manage topics and targets and send messages.`, - "migrations": `The migrations command allows you to migrate data between services.`, - "vcs": `The vcs command allows you to interact with VCS providers and manage your code repositories.`, - "main": chalk.redBright(`${logo}${description}`), -} - -module.exports = { - drawTable, - parse, - actionRunner, - parseInteger, - parseBool, - log, - warn, - hint, - success, - error, - commandDescriptions, - cliConfig, - drawTable -} diff --git a/lib/parser.ts b/lib/parser.ts new file mode 100644 index 00000000..f9fecb7b --- /dev/null +++ b/lib/parser.ts @@ -0,0 +1,238 @@ +import chalk = require('chalk'); +import commander = require('commander'); +import Table = require('cli-table3'); +const { description } = require('../../package.json'); +import { globalConfig } from './config'; +import os = require('os'); +import Client = require('./client'); +import { isCloud } from './utils'; +import type { CliConfig } from './types'; + +const cliConfig: CliConfig = { + verbose: false, + json: false, + force: false, + all: false, + ids: [], + report: false, + reportData: {}, +}; + +export const parse = (data: Record): void => { + if (cliConfig.json) { + drawJSON(data); + return; + } + + for (const key in data) { + if (data[key] === null) { + console.log(`${chalk.yellow.bold(key)} : null`); + } else if (Array.isArray(data[key])) { + console.log(`${chalk.yellow.bold.underline(key)}`); + if (typeof data[key][0] === 'object') { + drawTable(data[key]); + } else { + drawJSON(data[key]); + } + } else if (typeof data[key] === 'object') { + if (data[key]?.constructor?.name === 'BigNumber') { + console.log(`${chalk.yellow.bold(key)} : ${data[key]}`); + } else { + console.log(`${chalk.yellow.bold.underline(key)}`); + drawTable([data[key]]); + } + } else { + console.log(`${chalk.yellow.bold(key)} : ${data[key]}`); + } + } +}; + +export const drawTable = (data: Array>): void => { + if (data.length == 0) { + console.log('[]'); + return; + } + + // Create an object with all the keys in it + const obj = data.reduce((res, item) => ({ ...res, ...item }), {}); + // Get those keys as an array + const keys = Object.keys(obj); + // Create an object with all keys set to the default value '' + const def = keys.reduce((result: Record, key) => { + result[key] = '-'; + return result; + }, {}); + // Use object destructuring to replace all default values with the ones we have + data = data.map((item) => ({ ...def, ...item })); + + const columns = Object.keys(data[0]); + + const table = new Table({ + head: columns.map((c) => chalk.cyan.italic.bold(c)), + chars: { + top: ' ', + 'top-mid': ' ', + 'top-left': ' ', + 'top-right': ' ', + bottom: ' ', + 'bottom-mid': ' ', + 'bottom-left': ' ', + 'bottom-right': ' ', + left: ' ', + 'left-mid': ' ', + mid: chalk.cyan('─'), + 'mid-mid': chalk.cyan('┼'), + right: ' ', + 'right-mid': ' ', + middle: chalk.cyan('│'), + }, + }); + + data.forEach((row) => { + const rowValues: any[] = []; + for (const key in row) { + if (row[key] === null) { + rowValues.push('-'); + } else if (Array.isArray(row[key])) { + rowValues.push(JSON.stringify(row[key])); + } else if (typeof row[key] === 'object') { + rowValues.push(JSON.stringify(row[key])); + } else { + rowValues.push(row[key]); + } + } + table.push(rowValues); + }); + console.log(table.toString()); +}; + +export const drawJSON = (data: any): void => { + console.log(JSON.stringify(data, null, 2)); +}; + +export const parseError = (err: Error): void => { + if (cliConfig.report) { + (async () => { + let appwriteVersion = 'unknown'; + const endpoint = globalConfig.getEndpoint(); + + try { + const client = new Client().setEndpoint(endpoint); + const res = await client.call<{ version: string }>('get', '/health/version'); + appwriteVersion = res.version; + } catch { + // Silently fail + } + + const version = '13.0.0-rc.1'; + const stepsToReproduce = `Running \`appwrite ${(cliConfig.reportData as any).data.args.join(' ')}\``; + const yourEnvironment = `CLI version: ${version}\nOperation System: ${os.type()}\nAppwrite version: ${appwriteVersion}\nIs Cloud: ${isCloud()}`; + + const stack = '```\n' + (err.stack || err.message) + '\n```'; + + const githubIssueUrl = new URL('https://github.com/appwrite/appwrite/issues/new'); + githubIssueUrl.searchParams.append('labels', 'bug'); + githubIssueUrl.searchParams.append('template', 'bug.yaml'); + githubIssueUrl.searchParams.append('title', `šŸ› Bug Report: ${err.message}`); + githubIssueUrl.searchParams.append('actual-behavior', `CLI Error:\n${stack}`); + githubIssueUrl.searchParams.append('steps-to-reproduce', stepsToReproduce); + githubIssueUrl.searchParams.append('environment', yourEnvironment); + + log( + `To report this error you can:\n - Create a support ticket in our Discord server https://appwrite.io/discord \n - Create an issue in our Github\n ${githubIssueUrl.href}\n` + ); + + error('\n Stack Trace: \n'); + console.error(err); + process.exit(1); + })(); + } else { + if (cliConfig.verbose) { + console.error(err); + } else { + log('For detailed error pass the --verbose or --report flag'); + error(err.message); + } + process.exit(1); + } +}; + +export const actionRunner = Promise>(fn: T): ((...args: Parameters) => Promise) => { + return (...args: Parameters) => { + if (cliConfig.all && Array.isArray(cliConfig.ids) && cliConfig.ids.length !== 0) { + error(`The '--all' and '--id' flags cannot be used together.`); + process.exit(1); + } + return fn(...args).catch(parseError); + }; +}; + +export const parseInteger = (value: string): number => { + const parsedValue = parseInt(value, 10); + if (isNaN(parsedValue)) { + throw new commander.InvalidArgumentError('Not a number.'); + } + return parsedValue; +}; + +export const parseBool = (value: string): boolean => { + if (value === 'true') return true; + if (value === 'false') return false; + throw new commander.InvalidArgumentError('Not a boolean.'); +}; + +export const log = (message?: string): void => { + console.log(`${chalk.cyan.bold('ℹ Info:')} ${chalk.cyan(message ?? '')}`); +}; + +export const warn = (message?: string): void => { + console.log(`${chalk.yellow.bold('ℹ Warning:')} ${chalk.yellow(message ?? '')}`); +}; + +export const hint = (message?: string): void => { + console.log(`${chalk.cyan.bold('♄ Hint:')} ${chalk.cyan(message ?? '')}`); +}; + +export const success = (message?: string): void => { + console.log(`${chalk.green.bold('āœ“ Success:')} ${chalk.green(message ?? '')}`); +}; + +export const error = (message?: string): void => { + console.error(`${chalk.red.bold('āœ— Error:')} ${chalk.red(message ?? '')}`); +}; + +export const logo = "\n _ _ _ ___ __ _____\n \/_\\ _ __ _ ____ ___ __(_) |_ ___ \/ __\\ \/ \/ \\_ \\\n \/\/_\\\\| '_ \\| '_ \\ \\ \/\\ \/ \/ '__| | __\/ _ \\ \/ \/ \/ \/ \/ \/\\\/\n \/ _ \\ |_) | |_) \\ V V \/| | | | || __\/ \/ \/___\/ \/___\/\\\/ \/_\n \\_\/ \\_\/ .__\/| .__\/ \\_\/\\_\/ |_| |_|\\__\\___| \\____\/\\____\/\\____\/\n |_| |_|\n\n"; + +export const commandDescriptions: Record = { + account: `The account command allows you to authenticate and manage a user account.`, + graphql: `The graphql command allows you to query and mutate any resource type on your Appwrite server.`, + avatars: `The avatars command aims to help you complete everyday tasks related to your app image, icons, and avatars.`, + databases: `(Legacy) The databases command allows you to create structured collections of documents and query and filter lists of documents.`, + 'tables-db': `The tables-db command allows you to create structured tables of columns and query and filter lists of rows.`, + init: `The init command provides a convenient wrapper for creating and initializing projects, functions, collections, buckets, teams, and messaging-topics in Appwrite.`, + push: `The push command provides a convenient wrapper for pushing your functions, collections, buckets, teams, and messaging-topics.`, + run: `The run command allows you to run the project locally to allow easy development and quick debugging.`, + functions: `The functions command allows you to view, create, and manage your Cloud Functions.`, + health: `The health command allows you to both validate and monitor your Appwrite server's health.`, + pull: `The pull command helps you pull your Appwrite project, functions, collections, buckets, teams, and messaging-topics`, + locale: `The locale command allows you to customize your app based on your users' location.`, + sites: `The sites command allows you to view, create and manage your Appwrite Sites.`, + storage: `The storage command allows you to manage your project files.`, + teams: `The teams command allows you to group users of your project to enable them to share read and write access to your project resources.`, + update: `The update command allows you to update the Appwrite CLI to the latest version.`, + users: `The users command allows you to manage your project users.`, + projects: `The projects command allows you to manage your projects, add platforms, manage API keys, Dev Keys etc.`, + project: `The project command allows you to manage project related resources like usage, variables, etc.`, + client: `The client command allows you to configure your CLI`, + login: `The login command allows you to authenticate and manage a user account.`, + logout: `The logout command allows you to log out of your Appwrite account.`, + whoami: `The whomai command gives information about the currently logged-in user.`, + register: `Outputs the link to create an Appwrite account.`, + console: `The console command gives you access to the APIs used by the Appwrite Console.`, + messaging: `The messaging command allows you to manage topics and targets and send messages.`, + migrations: `The migrations command allows you to migrate data between services.`, + vcs: `The vcs command allows you to interact with VCS providers and manage your code repositories.`, + main: chalk.redBright(`${logo}${description}`), +}; + +export { cliConfig }; diff --git a/lib/questions.js b/lib/questions.ts similarity index 78% rename from lib/questions.js rename to lib/questions.ts index 33e68d5a..f314ba45 100644 --- a/lib/questions.js +++ b/lib/questions.ts @@ -1,23 +1,50 @@ -const chalk = require("chalk"); -const Client = require("./client"); -const { localConfig, globalConfig } = require('./config'); -const { projectsList } = require('./commands/projects'); -const { organizationsList } = require('./commands/organizations'); -const { teamsList } = require('./commands/teams'); -const { functionsListRuntimes, functionsListSpecifications, functionsList } = require('./commands/functions'); -const { accountListMFAFactors } = require("./commands/account"); -const { sdkForConsole } = require("./sdks"); -const { validateRequired } = require("./validations"); -const { paginate } = require('./paginate'); -const { isPortTaken } = require('./utils'); -const { databasesList } = require('./commands/databases'); -const { checkDeployConditions, isCloud } = require('./utils'); -const JSONbig = require("json-bigint")({ storeAsString: false }); -const { sitesListFrameworks, sitesListSpecifications, sitesList } = require('./commands/sites'); - -const whenOverride = (answers) => answers.override === undefined ? true : answers.override; - -const getIgnores = (runtime) => { +import chalk from 'chalk'; +import Client from './client'; +import { localConfig, globalConfig } from './config'; +import { projectsList } from './commands/projects'; +import { organizationsList } from './commands/organizations'; +import { teamsList } from './commands/teams'; +import { functionsListRuntimes, functionsListSpecifications, functionsList } from './commands/functions'; +import { accountListMFAFactors } from './commands/account'; +import { sdkForConsole } from './sdks'; +import { validateRequired } from './validations'; +import { paginate } from './paginate'; +import { isPortTaken, checkDeployConditions, isCloud } from './utils'; +import { databasesList } from './commands/databases'; +import JSONbig from 'json-bigint'; +import { sitesListFrameworks, sitesListSpecifications, sitesList } from './commands/sites'; + +const JSONbigConfig = JSONbig({ storeAsString: false }); + +interface Answers { + override?: boolean; + method?: string; + start?: string; + organization?: string; + [key: string]: any; +} + +interface Choice { + name: string; + value: any; + disabled?: boolean | string; + current?: boolean; +} + +interface Question { + type: string; + name: string; + message: string; + default?: any; + when?: ((answers: Answers) => boolean | Promise) | boolean; + choices?: (() => Promise | Choice[]) | Choice[]; + validate?: (value: any) => boolean | string | Promise; + mask?: string; +} + +const whenOverride = (answers: Answers): boolean => answers.override === undefined ? true : answers.override; + +const getIgnores = (runtime: string): string[] => { const languge = runtime.split("-").slice(0, -1).join("-"); switch (languge) { @@ -51,7 +78,7 @@ const getIgnores = (runtime) => { return []; }; -const getEntrypoint = (runtime) => { +const getEntrypoint = (runtime: string): string | undefined => { const languge = runtime.split("-").slice(0, -1).join("-"); switch (languge) { @@ -89,7 +116,7 @@ const getEntrypoint = (runtime) => { return undefined; }; -const getInstallCommand = (runtime) => { +const getInstallCommand = (runtime: string): string | undefined => { const languge = runtime.split("-").slice(0, -1).join("-"); switch (languge) { @@ -122,7 +149,7 @@ const getInstallCommand = (runtime) => { return undefined; }; -const questionsInitProject = [ +export const questionsInitProject: Question[] = [ { type: "confirm", name: "override", @@ -158,7 +185,7 @@ const questionsInitProject = [ ? await paginate(organizationsList, { parseOutput: false, sdk: client }, 100, 'teams') : await paginate(teamsList, { parseOutput: false, sdk: client }, 100, 'teams'); - let choices = teams.map((team, idx) => { + let choices = teams.map((team: any, idx: number) => { return { name: `${team.name} (${team['$id']})`, value: team['$id'] @@ -178,20 +205,20 @@ const questionsInitProject = [ name: "project", message: "What would you like to name your project?", default: "My Awesome Project", - when: (answer) => answer.start !== 'existing' + when: (answer: Answers) => answer.start !== 'existing' }, { type: "input", name: "id", message: "What ID would you like to have for your project?", default: "unique()", - when: (answer) => answer.start !== 'existing' + when: (answer: Answers) => answer.start !== 'existing' }, { type: "search-list", name: "project", message: "Choose your Appwrite project.", - choices: async (answers) => { + choices: async (answers: Answers) => { const queries = [ JSON.stringify({ method: 'equal', attribute: 'teamId', values: [answers.organization] }), JSON.stringify({ method: 'orderDesc', attribute: '$id' }) @@ -199,7 +226,7 @@ const questionsInitProject = [ const { projects } = await paginate(projectsList, { parseOutput: false }, 100, 'projects', queries); - let choices = projects.map((project) => { + let choices = projects.map((project: any) => { return { name: `${project.name} (${project['$id']})`, value: { @@ -215,7 +242,7 @@ const questionsInitProject = [ return choices; }, - when: (answer) => answer.start === 'existing' + when: (answer: Answers) => answer.start === 'existing' }, { type: "list", @@ -228,18 +255,19 @@ const questionsInitProject = [ if (!regions.length) { throw new Error("No regions found. Please check your network or Appwrite Cloud availability."); } - return regions.filter(region => !region.disabled).map(region => ({ + return regions.filter((region: any) => !region.disabled).map((region: any) => ({ name: `${region.name} (${region.$id})`, value: region.$id })); }, - when: (answer) => { + when: (answer: Answers) => { if (answer.start === 'existing') return false; return isCloud(); } } ]; -const questionsInitProjectAutopull = [ + +export const questionsInitProjectAutopull: Question[] = [ { type: "confirm", name: "autopull", @@ -247,7 +275,8 @@ const questionsInitProjectAutopull = [ `Would you like to pull all resources from project you just linked?` }, ]; -const questionsPullResources = [ + +export const questionsPullResources: Question[] = [ { type: "list", name: "resource", @@ -262,21 +291,21 @@ const questionsPullResources = [ { name: `Collections ${chalk.blackBright(`(Legacy Databases)`)}`, value: 'collections' } ] } -] +]; -const questionsPullFunctions = [ +export const questionsPullFunctions: Question[] = [ { type: "checkbox", name: "functions", message: "Which functions would you like to pull?", - validate: (value) => validateRequired('function', value), + validate: (value: any) => validateRequired('function', value), choices: async () => { const { functions } = await paginate(functionsList, { parseOutput: false }, 100, 'functions'); if (functions.length === 0) { throw "We couldn't find any functions in your Appwrite project"; } - return functions.map(func => { + return functions.map((func: any) => { return { name: `${func.name} (${func.$id})`, value: { ...func } @@ -286,7 +315,7 @@ const questionsPullFunctions = [ } ]; -const questionsPullFunctionsCode = [ +export const questionsPullFunctionsCode: Question[] = [ { type: "confirm", name: "override", @@ -294,19 +323,19 @@ const questionsPullFunctionsCode = [ }, ]; -const questionsPullSites = [ +export const questionsPullSites: Question[] = [ { type: "checkbox", name: "sites", message: "Which sites would you like to pull?", - validate: (value) => validateRequired('site', value), + validate: (value: any) => validateRequired('site', value), choices: async () => { const { sites } = await paginate(sitesList, { parseOutput: false }, 100, 'sites'); if (sites.length === 0) { throw "We couldn't find any sites in your Appwrite project"; } - return sites.map(site => { + return sites.map((site: any) => { return { name: `${site.name} (${site.$id})`, value: { ...site } @@ -316,7 +345,7 @@ const questionsPullSites = [ } ]; -const questionsPullSitesCode = [ +export const questionsPullSitesCode: Question[] = [ { type: "confirm", name: "override", @@ -324,7 +353,7 @@ const questionsPullSitesCode = [ }, ]; -const questionsCreateFunction = [ +export const questionsCreateFunction: Question[] = [ { type: "input", name: "name", @@ -346,7 +375,7 @@ const questionsCreateFunction = [ parseOutput: false }) let runtimes = response["runtimes"] - let choices = runtimes.map((runtime, idx) => { + let choices = runtimes.map((runtime: any, idx: number) => { return { name: `${runtime.name} (${runtime['$id']})`, value: { @@ -370,7 +399,7 @@ const questionsCreateFunction = [ parseOutput: false }) let specifications = response["specifications"] - let choices = specifications.map((spec, idx) => { + let choices = specifications.map((spec: any, idx: number) => { return { name: `${spec.cpus} CPU, ${spec.memory}MB RAM`, value: spec.slug, @@ -382,7 +411,7 @@ const questionsCreateFunction = [ } ]; -const questionsCreateFunctionSelectTemplate = (templates) => { +export const questionsCreateFunctionSelectTemplate = (templates: string[]): Question[] => { return [ { type: "search-list", @@ -397,9 +426,7 @@ const questionsCreateFunctionSelectTemplate = (templates) => { ]; }; - - -const questionsCreateBucket = [ +export const questionsCreateBucket: Question[] = [ { type: "input", name: "bucket", @@ -420,7 +447,7 @@ const questionsCreateBucket = [ } ]; -const questionsCreateTeam = [ +export const questionsCreateTeam: Question[] = [ { type: "input", name: "bucket", @@ -435,7 +462,7 @@ const questionsCreateTeam = [ } ]; -const questionsCreateCollection = [ +export const questionsCreateCollection: Question[] = [ { type: "list", name: "method", @@ -452,7 +479,7 @@ const questionsCreateCollection = [ choices: async () => { const databases = localConfig.getDatabases(); - let choices = databases.map((database, idx) => { + let choices = databases.map((database: any, idx: number) => { return { name: `${database.name} (${database.$id})`, value: database.$id @@ -465,21 +492,21 @@ const questionsCreateCollection = [ return choices; }, - when: (answers) => (answers.method ?? '').toLowerCase() === 'existing' + when: (answers: Answers) => (answers.method ?? '').toLowerCase() === 'existing' }, { type: "input", name: "databaseName", message: "What would you like to name your database?", default: "My Awesome Database", - when: (answers) => (answers.method ?? '').toLowerCase() !== 'existing' + when: (answers: Answers) => (answers.method ?? '').toLowerCase() !== 'existing' }, { type: "input", name: "databaseId", message: "What ID would you like to have for your database?", default: "unique()", - when: (answers) => (answers.method ?? '').toLowerCase() !== 'existing' + when: (answers: Answers) => (answers.method ?? '').toLowerCase() !== 'existing' }, { type: "input", @@ -501,7 +528,7 @@ const questionsCreateCollection = [ } ]; -const questionsCreateTable = [ +export const questionsCreateTable: Question[] = [ { type: "list", name: "method", @@ -518,7 +545,7 @@ const questionsCreateTable = [ choices: async () => { const databases = localConfig.getTablesDBs(); - let choices = databases.map((database, idx) => { + let choices = databases.map((database: any, idx: number) => { return { name: `${database.name} (${database.$id})`, value: database.$id @@ -531,21 +558,21 @@ const questionsCreateTable = [ return choices; }, - when: (answers) => (answers.method ?? '').toLowerCase() === 'existing' + when: (answers: Answers) => (answers.method ?? '').toLowerCase() === 'existing' }, { type: "input", name: "databaseName", message: "What would you like to name your database?", default: "My Awesome Database", - when: (answers) => (answers.method ?? '').toLowerCase() !== 'existing' + when: (answers: Answers) => (answers.method ?? '').toLowerCase() !== 'existing' }, { type: "input", name: "databaseId", message: "What ID would you like to have for your database?", default: "unique()", - when: (answers) => (answers.method ?? '').toLowerCase() !== 'existing' + when: (answers: Answers) => (answers.method ?? '').toLowerCase() !== 'existing' }, { type: "input", @@ -567,7 +594,7 @@ const questionsCreateTable = [ } ]; -const questionsCreateMessagingTopic = [ +export const questionsCreateMessagingTopic: Question[] = [ { type: "input", name: "topic", @@ -582,12 +609,12 @@ const questionsCreateMessagingTopic = [ } ]; -const questionsPullCollection = [ +export const questionsPullCollection: Question[] = [ { type: "checkbox", name: "databases", message: "From which database would you like to pull collections?", - validate: (value) => validateRequired('collection', value), + validate: (value: any) => validateRequired('collection', value), choices: async () => { let response = await databasesList({ parseOutput: false @@ -597,7 +624,7 @@ const questionsPullCollection = [ if (databases.length <= 0) { throw new Error("No databases found. Please create one in project console.") } - let choices = databases.map((database, idx) => { + let choices = databases.map((database: any, idx: number) => { return { name: `${database.name} (${database.$id})`, value: database.$id @@ -608,7 +635,7 @@ const questionsPullCollection = [ } ]; -const questionsLogin = [ +export const questionsLogin: Question[] = [ { type: "list", name: "method", @@ -623,26 +650,26 @@ const questionsLogin = [ type: "input", name: "email", message: "Enter your email", - validate(value) { + validate(value: string) { if (!value) { return "Please enter your email"; } return true; }, - when: (answers) => answers.method !== 'select' + when: (answers: Answers) => answers.method !== 'select' }, { type: "password", name: "password", message: "Enter your password", mask: "*", - validate(value) { + validate(value: string) { if (!value) { return "Please enter your password"; } return true; }, - when: (answers) => answers.method !== 'select' + when: (answers: Answers) => answers.method !== 'select' }, { type: "search-list", @@ -652,11 +679,11 @@ const questionsLogin = [ const sessions = globalConfig.getSessions(); const current = globalConfig.getCurrentSession(); - const data = []; + const data: Choice[] = []; - const longestEmail = sessions.reduce((prev, current) => (prev && (prev.email ?? '').length > (current.email ?? '').length) ? prev : current).email.length; + const longestEmail = sessions.reduce((prev: any, current: any) => (prev && (prev.email ?? '').length > (current.email ?? '').length) ? prev : current).email.length; - sessions.forEach((session) => { + sessions.forEach((session: any) => { if (session.email) { data.push({ current: current === session.id, @@ -668,16 +695,17 @@ const questionsLogin = [ return data.sort((a, b) => Number(b.current) - Number(a.current)) }, - when: (answers) => answers.method === 'select' + when: (answers: Answers) => answers.method === 'select' }, ]; -const questionGetEndpoint = [ + +export const questionGetEndpoint: Question[] = [ { type: "input", name: "endpoint", message: "Enter the endpoint of your Appwrite server", default: "http://localhost/v1", - async validate(value) { + async validate(value: string) { if (!value) { return "Please enter a valid endpoint."; } @@ -696,21 +724,21 @@ const questionGetEndpoint = [ } ]; -const questionsLogout = [ +export const questionsLogout: Question[] = [ { type: "checkbox", name: "accounts", message: "Select accounts to logout from", - validate: (value) => validateRequired('account', value), + validate: (value: any) => validateRequired('account', value), choices() { const sessions = globalConfig.getSessions(); const current = globalConfig.getCurrentSession(); - const data = []; + const data: Choice[] = []; - const longestEmail = sessions.reduce((prev, current) => (prev && (prev.email ?? '').length > (current.email ?? '').length) ? prev : current).email.length; + const longestEmail = sessions.reduce((prev: any, current: any) => (prev && (prev.email ?? '').length > (current.email ?? '').length) ? prev : current).email.length; - sessions.forEach((session) => { + sessions.forEach((session: any) => { if (session.email) { data.push({ current: current === session.id, @@ -725,7 +753,7 @@ const questionsLogout = [ } ]; -const questionsPushResources = [ +export const questionsPushResources: Question[] = [ { type: "list", name: "resource", @@ -742,7 +770,7 @@ const questionsPushResources = [ } ]; -const questionsInitResources = [ +export const questionsInitResources: Question[] = [ { type: "list", name: "resource", @@ -759,17 +787,17 @@ const questionsInitResources = [ } ]; -const questionsPushSites = [ +export const questionsPushSites: Question[] = [ { type: "checkbox", name: "sites", message: "Which sites would you like to push?", - validate: (value) => validateRequired('site', value), + validate: (value: any) => validateRequired('site', value), when: () => localConfig.getSites().length > 0, choices: () => { let sites = localConfig.getSites(); checkDeployConditions(localConfig) - let choices = sites.map((site, idx) => { + let choices = sites.map((site: any, idx: number) => { return { name: `${site.name} (${site.$id})`, value: site.$id @@ -780,17 +808,17 @@ const questionsPushSites = [ }, ]; -const questionsPushFunctions = [ +export const questionsPushFunctions: Question[] = [ { type: "checkbox", name: "functions", message: "Which functions would you like to push?", - validate: (value) => validateRequired('function', value), + validate: (value: any) => validateRequired('function', value), when: () => localConfig.getFunctions().length > 0, choices: () => { let functions = localConfig.getFunctions(); checkDeployConditions(localConfig) - let choices = functions.map((func, idx) => { + let choices = functions.map((func: any, idx: number) => { return { name: `${func.name} (${func.$id})`, value: func.$id @@ -799,20 +827,20 @@ const questionsPushFunctions = [ return choices; } }, -] +]; -const questionsPushCollections = [ +export const questionsPushCollections: Question[] = [ { type: "checkbox", name: "collections", message: "Which collections would you like to push?", - validate: (value) => validateRequired('collection', value), + validate: (value: any) => validateRequired('collection', value), when: () => localConfig.getCollections().length > 0, choices: () => { let collections = localConfig.getCollections(); checkDeployConditions(localConfig) - return collections.map(collection => { + return collections.map((collection: any) => { return { name: `${collection.name} (${collection['databaseId']} - ${collection['$id']})`, value: `${collection['databaseId']}|${collection['$id']}` @@ -822,18 +850,18 @@ const questionsPushCollections = [ } ]; -const questionsPushTables = [ +export const questionsPushTables: Question[] = [ { type: "checkbox", name: "tables", message: "Which tables would you like to push?", - validate: (value) => validateRequired('table', value), + validate: (value: any) => validateRequired('table', value), when: () => localConfig.getTables().length > 0, choices: () => { let tables = localConfig.getTables(); checkDeployConditions(localConfig) - return tables.map(table => { + return tables.map((table: any) => { return { name: `${table.name} (${table['databaseId']} - ${table['$id']})`, value: `${table['databaseId']}|${table['$id']}` @@ -843,7 +871,7 @@ const questionsPushTables = [ } ]; -const questionPushChanges = [ +export const questionPushChanges: Question[] = [ { type: "input", name: "changes", @@ -851,7 +879,7 @@ const questionPushChanges = [ } ]; -const questionPushChangesConfirmation = [ +export const questionPushChangesConfirmation: Question[] = [ { type: "input", name: "changes", @@ -859,18 +887,18 @@ const questionPushChangesConfirmation = [ } ]; -const questionsPushBuckets = [ +export const questionsPushBuckets: Question[] = [ { type: "checkbox", name: "buckets", message: "Which buckets would you like to push?", - validate: (value) => validateRequired('bucket', value), + validate: (value: any) => validateRequired('bucket', value), when: () => localConfig.getBuckets().length > 0, choices: () => { let buckets = localConfig.getBuckets(); checkDeployConditions(localConfig) - return buckets.map(bucket => { + return buckets.map((bucket: any) => { return { name: `${bucket.name} (${bucket['$id']})`, value: bucket.$id @@ -878,19 +906,19 @@ const questionsPushBuckets = [ }); } } -] +]; -const questionsPushMessagingTopics = [ +export const questionsPushMessagingTopics: Question[] = [ { type: "checkbox", name: "topics", message: "Which messaging topic would you like to push?", - validate: (value) => validateRequired('topics', value), + validate: (value: any) => validateRequired('topics', value), when: () => localConfig.getMessagingTopics().length > 0, choices: () => { let topics = localConfig.getMessagingTopics(); - return topics.map(topic => { + return topics.map((topic: any) => { return { name: `${topic.name} (${topic['$id']})`, value: topic.$id @@ -898,35 +926,35 @@ const questionsPushMessagingTopics = [ }); } } -] +]; -const questionsGetEntrypoint = [ +export const questionsGetEntrypoint: Question[] = [ { type: "input", name: "entrypoint", message: "Enter the entrypoint", default: null, - validate(value) { + validate(value: string) { if (!value) { return "Please enter your entrypoint"; } return true; } }, -] +]; -const questionsPushTeams = [ +export const questionsPushTeams: Question[] = [ { type: "checkbox", name: "teams", message: "Which teams would you like to push?", - validate: (value) => validateRequired('team', value), + validate: (value: any) => validateRequired('team', value), when: () => localConfig.getTeams().length > 0, choices: () => { let teams = localConfig.getTeams(); checkDeployConditions(localConfig); - return teams.map(team => { + return teams.map((team: any) => { return { name: `${team.name} (${team['$id']})`, value: team.$id @@ -936,7 +964,7 @@ const questionsPushTeams = [ }, ]; -const questionsListFactors = [ +export const questionsListFactors: Question[] = [ { type: "list", name: "factor", @@ -972,12 +1000,12 @@ const questionsListFactors = [ } ]; -const questionsMFAChallenge = [ +export const questionsMFAChallenge: Question[] = [ { type: "input", name: "otp", message: "Enter OTP", - validate(value) { + validate(value: string) { if (!value) { return "Please enter OTP"; } @@ -986,18 +1014,18 @@ const questionsMFAChallenge = [ } ]; -const questionsRunFunctions = [ +export const questionsRunFunctions: Question[] = [ { type: "list", name: "function", message: "Which function would you like to develop locally?", - validate: (value) => validateRequired('function', value), + validate: (value: any) => validateRequired('function', value), choices: () => { let functions = localConfig.getFunctions(); if (functions.length === 0) { throw new Error("No functions found. Use 'appwrite pull functions' to synchronize existing one, or use 'appwrite init function' to create a new one."); } - let choices = functions.map((func, idx) => { + let choices = functions.map((func: any, idx: number) => { return { name: `${func.name} (${func.$id})`, value: func.$id @@ -1008,7 +1036,7 @@ const questionsRunFunctions = [ } ]; -const questionsCreateSite = [ +export const questionsCreateSite: Question[] = [ { type: "input", name: "name", @@ -1030,7 +1058,7 @@ const questionsCreateSite = [ parseOutput: false }); let frameworks = response["frameworks"]; - let choices = frameworks.map((framework) => { + let choices = frameworks.map((framework: any) => { return { name: `${framework.name} (${framework.key})`, value: framework, @@ -1048,7 +1076,7 @@ const questionsCreateSite = [ parseOutput: false }); let specifications = response["specifications"]; - let choices = specifications.map((spec) => { + let choices = specifications.map((spec: any) => { return { name: `${spec.cpus} CPU, ${spec.memory}MB RAM`, value: spec.slug, @@ -1060,39 +1088,3 @@ const questionsCreateSite = [ } ]; -module.exports = { - questionsInitProject, - questionsInitProjectAutopull, - questionsCreateFunction, - questionsCreateFunctionSelectTemplate, - questionsCreateBucket, - questionsCreateCollection, - questionsCreateTable, - questionsCreateMessagingTopic, - questionsPullFunctions, - questionsPullFunctionsCode, - questionsPullSites, - questionsPullSitesCode, - questionsLogin, - questionsPullResources, - questionsLogout, - questionsPullCollection, - questionsPushResources, - questionsPushFunctions, - questionsPushSites, - questionsPushCollections, - questionsPushBuckets, - questionsPushMessagingTopics, - questionsPushTeams, - questionsGetEntrypoint, - questionsListFactors, - questionsMFAChallenge, - questionsRunFunctions, - questionGetEndpoint, - questionsInitResources, - questionsCreateTeam, - questionPushChanges, - questionPushChangesConfirmation, - questionsCreateSite, - questionsPushTables -}; diff --git a/lib/sdks.js b/lib/sdks.js deleted file mode 100644 index 1c5eb092..00000000 --- a/lib/sdks.js +++ /dev/null @@ -1,60 +0,0 @@ -const Client = require("./client"); -const { globalConfig, localConfig } = require("./config"); - -const sdkForConsole = async (requiresAuth = true) => { - let client = new Client(); - let endpoint = globalConfig.getEndpoint(); - let cookie = globalConfig.getCookie() - let selfSigned = globalConfig.getSelfSigned() - - if (requiresAuth && cookie === "") { - throw new Error("Session not found. Please run `appwrite login` to create a session"); - } - - client - .setEndpoint(endpoint) - .setCookie(cookie) - .setProject("console") - .setSelfSigned(selfSigned) - .setLocale("en-US"); - - return client; -}; - -const sdkForProject = async () => { - let client = new Client(); - let endpoint = localConfig.getEndpoint() || globalConfig.getEndpoint(); - let project = localConfig.getProject().projectId ? localConfig.getProject().projectId : globalConfig.getProject(); - let key = globalConfig.getKey(); - let cookie = globalConfig.getCookie() - let selfSigned = globalConfig.getSelfSigned() - - if (!project) { - throw new Error("Project is not set. Please run `appwrite init project` to initialize the current directory with an Appwrite project."); - } - - client - .setEndpoint(endpoint) - .setProject(project) - .setSelfSigned(selfSigned) - .setLocale("en-US"); - - if (cookie) { - return client - .setCookie(cookie) - .setMode("admin"); - } - - if (key) { - return client - .setKey(key) - .setMode("default"); - } - - throw new Error("Session not found. Please run `appwrite login` to create a session."); -}; - -module.exports = { - sdkForConsole, - sdkForProject, -}; diff --git a/lib/sdks.ts b/lib/sdks.ts new file mode 100644 index 00000000..62e5de04 --- /dev/null +++ b/lib/sdks.ts @@ -0,0 +1,55 @@ +import Client = require('./client'); +import { globalConfig, localConfig } from './config'; + +export const sdkForConsole = async (requiresAuth: boolean = true): Promise => { + const client = new Client(); + const endpoint = globalConfig.getEndpoint(); + const cookie = globalConfig.getCookie(); + const selfSigned = globalConfig.getSelfSigned(); + + if (requiresAuth && cookie === '') { + throw new Error('Session not found. Please run `appwrite login` to create a session'); + } + + client + .setEndpoint(endpoint) + .setCookie(cookie) + .setProject('console') + .setSelfSigned(selfSigned) + .setLocale('en-US'); + + return client; +}; + +export const sdkForProject = async (): Promise => { + const client = new Client(); + const endpoint = localConfig.getEndpoint() || globalConfig.getEndpoint(); + const project = localConfig.getProject().projectId ? localConfig.getProject().projectId : globalConfig.getProject(); + const key = globalConfig.getKey(); + const cookie = globalConfig.getCookie(); + const selfSigned = globalConfig.getSelfSigned(); + + if (!project) { + throw new Error('Project is not set. Please run `appwrite init project` to initialize the current directory with an Appwrite project.'); + } + + client + .setEndpoint(endpoint) + .setProject(project) + .setSelfSigned(selfSigned) + .setLocale('en-US'); + + if (cookie) { + return client + .setCookie(cookie) + .setMode('admin'); + } + + if (key) { + return client + .setKey(key) + .setMode('default'); + } + + throw new Error('Session not found. Please run `appwrite login` to create a session.'); +}; diff --git a/lib/spinner.js b/lib/spinner.ts similarity index 53% rename from lib/spinner.js rename to lib/spinner.ts index bcc7e6bf..b99036e8 100644 --- a/lib/spinner.js +++ b/lib/spinner.ts @@ -1,43 +1,61 @@ -const progress = require('cli-progress'); -const chalk = require('chalk'); +import progress = require('cli-progress'); +import chalk = require('chalk'); const SPINNER_ARC = 'arc'; const SPINNER_DOTS = 'dots'; -const spinners = { +interface SpinnerConfig { + interval: number; + frames: string[]; +} + +interface SpinnerPayload { + status: string; + resource: string; + id: string; + prefix?: string; + end?: string; + errorMessage?: string; +} + +const spinners: Record = { [SPINNER_ARC]: { - "interval": 100, - "frames": ["ā—œ", "ā— ", "ā—", "ā—ž", "ā—”", "ā—Ÿ"] + interval: 100, + frames: ['ā—œ', 'ā— ', 'ā—', 'ā—ž', 'ā—”', 'ā—Ÿ'], }, [SPINNER_DOTS]: { - "interval": 80, - "frames": ["ā ‹", "ā ™", "ā ¹", "ā ø", "ā ¼", "ā “", "ā ¦", "ā §", "ā ‡", "ā "] - } -} + interval: 80, + frames: ['ā ‹', 'ā ™', 'ā ¹', 'ā ø', 'ā ¼', 'ā “', 'ā ¦', 'ā §', 'ā ‡', 'ā '], + }, +}; class Spinner { - static start(clearOnComplete = true, hideCursor = true) { + static updatesBar: progress.MultiBar; + private bar: progress.SingleBar; + private spinnerInterval?: NodeJS.Timeout; + + static start(clearOnComplete: boolean = true, hideCursor: boolean = true): void { Spinner.updatesBar = new progress.MultiBar({ - format: this.#formatter, + format: this.formatter, hideCursor, clearOnComplete, stopOnComplete: true, linewrap: true, - noTTYOutput: true + noTTYOutput: true, }); } - static stop() { + static stop(): void { Spinner.updatesBar.stop(); } - static #formatter(options, params, payload) { + static formatter(options: any, params: any, payload: SpinnerPayload): string { const status = payload.status.padEnd(12); const middle = `${payload.resource} (${payload.id})`.padEnd(40); let prefix = chalk.cyan(payload.prefix ?? 'ā§—'); let start = chalk.cyan(status); - let end = chalk.yellow(payload.end); + let end = chalk.yellow(payload.end ?? ''); if (status.toLowerCase().trim() === 'pushed') { start = chalk.greenBright.bold(status); @@ -51,32 +69,31 @@ class Spinner { } else if (status.toLowerCase().trim() === 'error') { start = chalk.red.bold(status); prefix = chalk.red.bold('āœ—'); - end = chalk.red(payload.errorMessage); + end = chalk.red(payload.errorMessage ?? ''); } - return Spinner.#line(prefix, start, middle, end); + return Spinner.line(prefix, start, middle, end); } - static #line(prefix, start, middle, end, separator = '•') { + static line(prefix: string, start: string, middle: string, end: string, separator: string = '•'): string { return `${prefix} ${start} ${separator} ${middle} ${!end ? '' : separator} ${end}`; - } - constructor(payload, total = 100, startValue = 0) { - this.bar = Spinner.updatesBar.create(total, startValue, payload) + constructor(payload: SpinnerPayload, total: number = 100, startValue: number = 0) { + this.bar = Spinner.updatesBar.create(total, startValue, payload); } - update(payload) { + update(payload: Partial): this { this.bar.update(payload); return this; } - fail(payload) { + fail(payload: Partial): void { this.stopSpinner(); this.update({ status: 'Error', ...payload }); } - startSpinner(name) { + startSpinner(name: string): void { let spinnerFrame = 1; const spinner = spinners[name] ?? spinners['dots']; @@ -86,19 +103,16 @@ class Spinner { }, spinner.interval); } - stopSpinner() { - clearInterval(this.spinnerInterval); + stopSpinner(): void { + if (this.spinnerInterval) { + clearInterval(this.spinnerInterval); + } } - replaceSpinner(name) { + replaceSpinner(name: string): void { this.stopSpinner(); this.startSpinner(name); } } - -module.exports = { - Spinner, - SPINNER_ARC, - SPINNER_DOTS -} +export { Spinner, SPINNER_ARC, SPINNER_DOTS }; diff --git a/lib/type-generation/attribute.js b/lib/type-generation/attribute.js deleted file mode 100644 index e36d0558..00000000 --- a/lib/type-generation/attribute.js +++ /dev/null @@ -1,19 +0,0 @@ -const AttributeType = { - STRING: "string", - INTEGER: "integer", - FLOAT: "double", - BOOLEAN: "boolean", - DATETIME: "datetime", - EMAIL: "email", - IP: "ip", - URL: "url", - ENUM: "enum", - RELATIONSHIP: "relationship", - POINT: "point", - LINESTRING: "linestring", - POLYGON: "polygon", -}; - - module.exports = { - AttributeType, - }; diff --git a/lib/type-generation/attribute.ts b/lib/type-generation/attribute.ts new file mode 100644 index 00000000..62f1f06d --- /dev/null +++ b/lib/type-generation/attribute.ts @@ -0,0 +1,17 @@ +export const AttributeType = { + STRING: 'string', + INTEGER: 'integer', + FLOAT: 'double', + BOOLEAN: 'boolean', + DATETIME: 'datetime', + EMAIL: 'email', + IP: 'ip', + URL: 'url', + ENUM: 'enum', + RELATIONSHIP: 'relationship', + POINT: 'point', + LINESTRING: 'linestring', + POLYGON: 'polygon', +} as const; + +export type AttributeTypeValue = typeof AttributeType[keyof typeof AttributeType]; diff --git a/lib/type-generation/languages/csharp.js b/lib/type-generation/languages/csharp.ts similarity index 71% rename from lib/type-generation/languages/csharp.js rename to lib/type-generation/languages/csharp.ts index ff85bf67..8533ca41 100644 --- a/lib/type-generation/languages/csharp.js +++ b/lib/type-generation/languages/csharp.ts @@ -1,61 +1,64 @@ -/** @typedef {import('../attribute').Attribute} Attribute */ -const { AttributeType } = require('../attribute'); -const { LanguageMeta } = require("./language"); +import { AttributeType } from '../attribute'; +import { LanguageMeta, Attribute, Collection } from './language'; -class CSharp extends LanguageMeta { - getType(attribute, collections, collectionName) { - let type = ""; - switch (attribute.type) { - case AttributeType.STRING: - case AttributeType.EMAIL: - case AttributeType.DATETIME: - type = "string"; - if (attribute.format === AttributeType.ENUM) { - type = LanguageMeta.toPascalCase(collectionName) + LanguageMeta.toPascalCase(attribute.key); +export class CSharp extends LanguageMeta { + getType(attribute: Attribute, collections?: Collection[], collectionName?: string): string { + let type = ''; + switch (attribute.type) { + case AttributeType.STRING: + case AttributeType.EMAIL: + case AttributeType.DATETIME: + type = 'string'; + if (attribute.format === AttributeType.ENUM) { + type = LanguageMeta.toPascalCase(collectionName!) + LanguageMeta.toPascalCase(attribute.key); + } + break; + case AttributeType.INTEGER: + type = 'long'; + break; + case AttributeType.FLOAT: + type = 'double'; + break; + case AttributeType.BOOLEAN: + type = 'bool'; + break; + case AttributeType.RELATIONSHIP: + const relatedCollection = collections?.find((c) => c.$id === attribute.relatedCollection); + if (!relatedCollection) { + throw new Error(`Related collection with ID '${attribute.relatedCollection}' not found.`); + } + type = LanguageMeta.toPascalCase(relatedCollection.name); + if ( + (attribute.relationType === 'oneToMany' && attribute.side === 'parent') || + (attribute.relationType === 'manyToOne' && attribute.side === 'child') || + attribute.relationType === 'manyToMany' + ) { + type = `List<${type}>`; + } + break; + case AttributeType.POINT: + type = 'List'; + break; + case AttributeType.LINESTRING: + type = 'List>'; + break; + case AttributeType.POLYGON: + type = 'List>>'; + break; + default: + throw new Error(`Unknown attribute type: ${attribute.type}`); } - break; - case AttributeType.INTEGER: - type = "long"; - break; - case AttributeType.FLOAT: - type = "double"; - break; - case AttributeType.BOOLEAN: - type = "bool"; - break; - case AttributeType.RELATIONSHIP: - const relatedCollection = collections.find(c => c.$id === attribute.relatedCollection); - if (!relatedCollection) { - throw new Error(`Related collection with ID '${attribute.relatedCollection}' not found.`); + if (attribute.array) { + type = `List<${type}>`; } - type = LanguageMeta.toPascalCase(relatedCollection.name); - if ((attribute.relationType === 'oneToMany' && attribute.side === 'parent') || (attribute.relationType === 'manyToOne' && attribute.side === 'child') || attribute.relationType === 'manyToMany') { - type = `List<${type}>`; + if (!attribute.required) { + type += '?'; } - break; - case AttributeType.POINT: - type = "List"; - break; - case AttributeType.LINESTRING: - type = "List>"; - break; - case AttributeType.POLYGON: - type = "List>>"; - break; - default: - throw new Error(`Unknown attribute type: ${attribute.type}`); - } - if (attribute.array) { - type = `List<${type}>`; + return type; } - if (!attribute.required) { - type += "?"; - } - return type; - } - getTemplate() { - return `/// This file is auto-generated by the Appwrite CLI. + getTemplate(): string { + return `/// This file is auto-generated by the Appwrite CLI. /// You can regenerate it by running \`appwrite ${process.argv.slice(2).join(' ')}\`. #nullable enable @@ -169,11 +172,10 @@ public class <%= toPascalCase(collection.name) %> } } `; - } + } - getFileName(collection) { - return LanguageMeta.toPascalCase(collection.name) + ".cs"; - } + getFileName(collection: Collection): string { + return LanguageMeta.toPascalCase(collection.name) + '.cs'; + } } -module.exports = { CSharp }; diff --git a/lib/type-generation/languages/dart.js b/lib/type-generation/languages/dart.ts similarity index 60% rename from lib/type-generation/languages/dart.js rename to lib/type-generation/languages/dart.ts index d48ca486..07dacded 100644 --- a/lib/type-generation/languages/dart.js +++ b/lib/type-generation/languages/dart.ts @@ -1,98 +1,101 @@ -/** @typedef {import('../attribute').Attribute} Attribute */ -const { AttributeType } = require('../attribute'); -const { LanguageMeta } = require("./language"); -const fs = require('fs'); -const path = require('path'); - -class Dart extends LanguageMeta { - getPackageName() { - const pubspecPath = path.join(process.cwd(), 'pubspec.yaml'); - if (fs.existsSync(pubspecPath)) { - const pubspecContent = fs.readFileSync(pubspecPath, 'utf8'); - const lines = pubspecContent.split('\n'); - - const dependenciesIndex = lines.findIndex(line => line.trim() === 'dependencies:'); - - if (dependenciesIndex !== -1) { - const indent = lines[dependenciesIndex].search(/\S|$/); - const dependencies = []; - for (let i = dependenciesIndex + 1; i < lines.length; i++) { - const line = lines[i]; - if (line.trim() === '') continue; - - const lineIndent = line.search(/\S|$/); - if (lineIndent <= indent && line.trim() !== '') { - break; +import fs = require('fs'); +import path = require('path'); +import { AttributeType } from '../attribute'; +import { LanguageMeta, Attribute, Collection } from './language'; + +export class Dart extends LanguageMeta { + getPackageName(): string { + const pubspecPath = path.join(process.cwd(), 'pubspec.yaml'); + if (fs.existsSync(pubspecPath)) { + const pubspecContent = fs.readFileSync(pubspecPath, 'utf8'); + const lines = pubspecContent.split('\n'); + + const dependenciesIndex = lines.findIndex((line) => line.trim() === 'dependencies:'); + + if (dependenciesIndex !== -1) { + const indent = lines[dependenciesIndex].search(/\S|$/); + const dependencies: string[] = []; + for (let i = dependenciesIndex + 1; i < lines.length; i++) { + const line = lines[i]; + if (line.trim() === '') continue; + + const lineIndent = line.search(/\S|$/); + if (lineIndent <= indent && line.trim() !== '') { + break; + } + + dependencies.push(line.trim()); } - dependencies.push(line.trim()); - } - - if (dependencies.some(dep => dep.startsWith('dart_appwrite:'))) { - return 'dart_appwrite'; - } - if (dependencies.some(dep => dep.startsWith('appwrite:'))) { - return 'appwrite'; + if (dependencies.some((dep) => dep.startsWith('dart_appwrite:'))) { + return 'dart_appwrite'; + } + if (dependencies.some((dep) => dep.startsWith('appwrite:'))) { + return 'appwrite'; + } } } - } - return 'appwrite'; - } + return 'appwrite'; + } - getType(attribute, collections, collectionName) { - let type = ""; - switch (attribute.type) { - case AttributeType.STRING: - case AttributeType.EMAIL: - case AttributeType.DATETIME: - type = "String"; - if (attribute.format === AttributeType.ENUM) { - type = LanguageMeta.toPascalCase(collectionName) + LanguageMeta.toPascalCase(attribute.key); + getType(attribute: Attribute, collections?: Collection[], collectionName?: string): string { + let type = ''; + switch (attribute.type) { + case AttributeType.STRING: + case AttributeType.EMAIL: + case AttributeType.DATETIME: + type = 'String'; + if (attribute.format === AttributeType.ENUM) { + type = LanguageMeta.toPascalCase(collectionName!) + LanguageMeta.toPascalCase(attribute.key); + } + break; + case AttributeType.INTEGER: + type = 'int'; + break; + case AttributeType.FLOAT: + type = 'double'; + break; + case AttributeType.BOOLEAN: + type = 'bool'; + break; + case AttributeType.RELATIONSHIP: + const relatedCollection = collections?.find((c) => c.$id === attribute.relatedCollection); + if (!relatedCollection) { + throw new Error(`Related collection with ID '${attribute.relatedCollection}' not found.`); + } + type = LanguageMeta.toPascalCase(relatedCollection.name); + if ( + (attribute.relationType === 'oneToMany' && attribute.side === 'parent') || + (attribute.relationType === 'manyToOne' && attribute.side === 'child') || + attribute.relationType === 'manyToMany' + ) { + type = `List<${type}>`; + } + break; + case AttributeType.POINT: + type = 'List'; + break; + case AttributeType.LINESTRING: + type = 'List>'; + break; + case AttributeType.POLYGON: + type = 'List>>'; + break; + default: + throw new Error(`Unknown attribute type: ${attribute.type}`); } - break; - case AttributeType.INTEGER: - type = "int"; - break; - case AttributeType.FLOAT: - type = "double"; - break; - case AttributeType.BOOLEAN: - type = "bool"; - break; - case AttributeType.RELATIONSHIP: - const relatedCollection = collections.find(c => c.$id === attribute.relatedCollection); - if (!relatedCollection) { - throw new Error(`Related collection with ID '${attribute.relatedCollection}' not found.`); + if (attribute.array) { + type = `List<${type}>`; } - type = LanguageMeta.toPascalCase(relatedCollection.name); - if ((attribute.relationType === 'oneToMany' && attribute.side === 'parent') || (attribute.relationType === 'manyToOne' && attribute.side === 'child') || attribute.relationType === 'manyToMany') { - type = `List<${type}>`; + if (!attribute.required) { + type += '?'; } - break; - case AttributeType.POINT: - type = "List"; - break; - case AttributeType.LINESTRING: - type = "List>"; - break; - case AttributeType.POLYGON: - type = "List>>"; - break; - default: - throw new Error(`Unknown attribute type: ${attribute.type}`); - } - if (attribute.array) { - type = `List<${type}>`; + return type; } - if (!attribute.required) { - type += "?"; - } - return type; - } - getTemplate() { - return `// This file is auto-generated by the Appwrite CLI. + getTemplate(): string { + return `// This file is auto-generated by the Appwrite CLI. // You can regenerate it by running \`appwrite ${process.argv.slice(2).join(' ')}\`. <% const __relatedImportsSeen = new Set(); const sortedAttributes = collection.attributes.slice().sort((a, b) => { @@ -192,11 +195,10 @@ map['<%= attribute.key %>'] != null ? <%- toPascalCase(collections.find(c => c.$ } } `; - } + } - getFileName(collection) { - return LanguageMeta.toSnakeCase(collection.name) + ".dart"; - } + getFileName(collection: Collection): string { + return LanguageMeta.toSnakeCase(collection.name) + '.dart'; + } } -module.exports = { Dart }; \ No newline at end of file diff --git a/lib/type-generation/languages/java.js b/lib/type-generation/languages/java.ts similarity index 57% rename from lib/type-generation/languages/java.js rename to lib/type-generation/languages/java.ts index e45f22e5..d2aa6a22 100644 --- a/lib/type-generation/languages/java.js +++ b/lib/type-generation/languages/java.ts @@ -1,58 +1,61 @@ -/** @typedef {import('../attribute').Attribute} Attribute */ -const { AttributeType } = require('../attribute'); -const { LanguageMeta } = require("./language"); - -class Java extends LanguageMeta { - getType(attribute, collections, collectionName) { - let type = ""; - switch (attribute.type) { - case AttributeType.STRING: - case AttributeType.EMAIL: - case AttributeType.DATETIME: - type = "String"; - if (attribute.format === AttributeType.ENUM) { - type = LanguageMeta.toPascalCase(collectionName) + LanguageMeta.toPascalCase(attribute.key); +import { AttributeType } from '../attribute'; +import { LanguageMeta, Attribute, Collection } from './language'; + +export class Java extends LanguageMeta { + getType(attribute: Attribute, collections?: Collection[], collectionName?: string): string { + let type = ''; + switch (attribute.type) { + case AttributeType.STRING: + case AttributeType.EMAIL: + case AttributeType.DATETIME: + type = 'String'; + if (attribute.format === AttributeType.ENUM) { + type = LanguageMeta.toPascalCase(collectionName!) + LanguageMeta.toPascalCase(attribute.key); + } + break; + case AttributeType.INTEGER: + type = 'Integer'; + break; + case AttributeType.FLOAT: + type = 'Double'; + break; + case AttributeType.BOOLEAN: + type = 'Boolean'; + break; + case AttributeType.RELATIONSHIP: + const relatedCollection = collections?.find((c) => c.$id === attribute.relatedCollection); + if (!relatedCollection) { + throw new Error(`Related collection with ID '${attribute.relatedCollection}' not found.`); + } + type = LanguageMeta.toPascalCase(relatedCollection.name); + if ( + (attribute.relationType === 'oneToMany' && attribute.side === 'parent') || + (attribute.relationType === 'manyToOne' && attribute.side === 'child') || + attribute.relationType === 'manyToMany' + ) { + type = 'List<' + type + '>'; + } + break; + case AttributeType.POINT: + type = 'List'; + break; + case AttributeType.LINESTRING: + type = 'List>'; + break; + case AttributeType.POLYGON: + type = 'List>>'; + break; + default: + throw new Error(`Unknown attribute type: ${attribute.type}`); } - break; - case AttributeType.INTEGER: - type = "int"; - break; - case AttributeType.FLOAT: - type = "double"; - break; - case AttributeType.BOOLEAN: - type = "boolean"; - break; - case AttributeType.RELATIONSHIP: - const relatedCollection = collections.find(c => c.$id === attribute.relatedCollection); - if (!relatedCollection) { - throw new Error(`Related collection with ID '${attribute.relatedCollection}' not found.`); + if (attribute.array) { + type = 'List<' + type + '>'; } - type = LanguageMeta.toPascalCase(relatedCollection.name); - if ((attribute.relationType === 'oneToMany' && attribute.side === 'parent') || (attribute.relationType === 'manyToOne' && attribute.side === 'child') || attribute.relationType === 'manyToMany') { - type = "List<" + type + ">"; - } - break; - case AttributeType.POINT: - type = "List"; - break; - case AttributeType.LINESTRING: - type = "List>"; - break; - case AttributeType.POLYGON: - type = "List>>"; - break; - default: - throw new Error(`Unknown attribute type: ${attribute.type}`); - } - if (attribute.array) { - type = "List<" + type + ">"; + return type; } - return type; - } - getTemplate() { - return `package io.appwrite.models; + getTemplate(): string { + return `package io.appwrite.models; /** * This file is auto-generated by the Appwrite CLI. @@ -129,11 +132,10 @@ public class <%- toPascalCase(collection.name) %> { } } `; - } + } - getFileName(collection) { - return LanguageMeta.toPascalCase(collection.name) + ".java"; - } + getFileName(collection: Collection): string { + return LanguageMeta.toPascalCase(collection.name) + '.java'; + } } -module.exports = { Java }; diff --git a/lib/type-generation/languages/javascript.js b/lib/type-generation/languages/javascript.js deleted file mode 100644 index 1d19cfb4..00000000 --- a/lib/type-generation/languages/javascript.js +++ /dev/null @@ -1,111 +0,0 @@ -/** @typedef {import('../attribute').Attribute} Attribute */ -const fs = require("fs"); -const path = require("path"); - -const { AttributeType } = require('../attribute'); -const { LanguageMeta } = require("./language"); - -class JavaScript extends LanguageMeta { - getType(attribute, collections) { - let type = "" - switch (attribute.type) { - case AttributeType.STRING: - case AttributeType.EMAIL: - case AttributeType.DATETIME: - case AttributeType.IP: - case AttributeType.URL: - type = "string"; - if (attribute.format === AttributeType.ENUM) { - type = LanguageMeta.toPascalCase(attribute.key); - } - break; - case AttributeType.INTEGER: - type = "number"; - break; - case AttributeType.FLOAT: - type = "number"; - break; - case AttributeType.BOOLEAN: - type = "boolean"; - break; - case AttributeType.RELATIONSHIP: - const relatedCollection = collections.find(c => c.$id === attribute.relatedCollection); - if (!relatedCollection) { - throw new Error(`Related collection with ID '${attribute.relatedCollection}' not found.`); - } - type = LanguageMeta.toPascalCase(relatedCollection.name); - if ((attribute.relationType === 'oneToMany' && attribute.side === 'parent') || (attribute.relationType === 'manyToOne' && attribute.side === 'child') || attribute.relationType === 'manyToMany') { - type = `${type}[]`; - } - break; - case AttributeType.POINT: - type = "number[]"; - break; - case AttributeType.LINESTRING: - type = "number[][]"; - break; - case AttributeType.POLYGON: - type = "number[][][]"; - break; - default: - throw new Error(`Unknown attribute type: ${attribute.type}`); - } - if (attribute.array) { - type += "[]"; - } - if (!attribute.required && attribute.default === null) { - type += " | null"; - } - return type; - } - - isSingleFile() { - return true; - } - - _getAppwriteDependency() { - if (fs.existsSync(path.resolve(process.cwd(), 'package.json'))) { - const packageJsonRaw = fs.readFileSync(path.resolve(process.cwd(), 'package.json')); - const packageJson = JSON.parse(packageJsonRaw.toString('utf-8')); - return packageJson.dependencies['node-appwrite'] ? 'node-appwrite' : 'appwrite'; - } - - return "appwrite"; - } - - getTemplate() { - return `/** - * @typedef {import('${this._getAppwriteDependency()}').Models.Row} Row - */ - -// This file is auto-generated by the Appwrite CLI. -// You can regenerate it by running \`appwrite ${process.argv.slice(2).join(' ')}\`. - -<% for (const collection of collections) { -%> -<% for (const attribute of collection.attributes) { -%> -<% if (attribute.format === 'enum') { -%> -/** - * @typedef {"<%- attribute.elements.join('"|"') %>"} <%- toPascalCase(attribute.key) %> - */ - -<% } -%> -<% } -%> -<% } -%> -<% for (const [index, collection] of Object.entries(collections)) { %>/** - * @typedef {Row & { -<% for (const attribute of collection.attributes) { -%> - * <%- strict ? toCamelCase(attribute.key) : attribute.key %>: <%- getType(attribute, collections) %>; -<% } -%> - * }} <%- toPascalCase(collection.name) %> - */ -<% if (index < collections.length - 1) { %> -<% } -%> -<% } %>`; - } - - getFileName(_) { - return "appwrite-types.js"; - } -} - -module.exports = { JavaScript }; \ No newline at end of file diff --git a/lib/type-generation/languages/javascript.ts b/lib/type-generation/languages/javascript.ts new file mode 100644 index 00000000..4da31622 --- /dev/null +++ b/lib/type-generation/languages/javascript.ts @@ -0,0 +1,111 @@ +import fs = require('fs'); +import path = require('path'); +import { AttributeType } from '../attribute'; +import { LanguageMeta, Attribute, Collection } from './language'; + +export class JavaScript extends LanguageMeta { + getType(attribute: Attribute, collections?: Collection[]): string { + let type = ''; + switch (attribute.type) { + case AttributeType.STRING: + case AttributeType.EMAIL: + case AttributeType.DATETIME: + case AttributeType.IP: + case AttributeType.URL: + type = 'string'; + if (attribute.format === AttributeType.ENUM) { + type = LanguageMeta.toPascalCase(attribute.key); + } + break; + case AttributeType.INTEGER: + type = 'number'; + break; + case AttributeType.FLOAT: + type = 'number'; + break; + case AttributeType.BOOLEAN: + type = 'boolean'; + break; + case AttributeType.RELATIONSHIP: + const relatedCollection = collections?.find((c) => c.$id === attribute.relatedCollection); + if (!relatedCollection) { + throw new Error(`Related collection with ID '${attribute.relatedCollection}' not found.`); + } + type = LanguageMeta.toPascalCase(relatedCollection.name); + if ( + (attribute.relationType === 'oneToMany' && attribute.side === 'parent') || + (attribute.relationType === 'manyToOne' && attribute.side === 'child') || + attribute.relationType === 'manyToMany' + ) { + type = `${type}[]`; + } + break; + case AttributeType.POINT: + type = 'number[]'; + break; + case AttributeType.LINESTRING: + type = 'number[][]'; + break; + case AttributeType.POLYGON: + type = 'number[][][]'; + break; + default: + throw new Error(`Unknown attribute type: ${attribute.type}`); + } + if (attribute.array) { + type += '[]'; + } + if (!attribute.required && attribute.default === null) { + type += ' | null'; + } + return type; + } + + isSingleFile(): boolean { + return true; + } + + private _getAppwriteDependency(): string { + if (fs.existsSync(path.resolve(process.cwd(), 'package.json'))) { + const packageJsonRaw = fs.readFileSync(path.resolve(process.cwd(), 'package.json')); + const packageJson = JSON.parse(packageJsonRaw.toString('utf-8')); + return packageJson.dependencies && packageJson.dependencies['node-appwrite'] ? 'node-appwrite' : 'appwrite'; + } + + return 'appwrite'; + } + + getTemplate(): string { + return `/** + * @typedef {import('${this._getAppwriteDependency()}').Models.Row} Row + */ + +// This file is auto-generated by the Appwrite CLI. +// You can regenerate it by running \`appwrite ${process.argv.slice(2).join(' ')}\`. + +<% for (const collection of collections) { -%> +<% for (const attribute of collection.attributes) { -%> +<% if (attribute.format === 'enum') { -%> +/** + * @typedef {"<%- attribute.elements.join('"|"') %>"} <%- toPascalCase(attribute.key) %> + */ + +<% } -%> +<% } -%> +<% } -%> +<% for (const [index, collection] of Object.entries(collections)) { %>/** + * @typedef {Row & { +<% for (const attribute of collection.attributes) { -%> + * <%- strict ? toCamelCase(attribute.key) : attribute.key %>: <%- getType(attribute, collections) %>; +<% } -%> + * }} <%- toPascalCase(collection.name) %> + */ +<% if (index < collections.length - 1) { %> +<% } -%> +<% } %>`; + } + + getFileName(_: Collection | undefined): string { + return 'appwrite-types.js'; + } +} diff --git a/lib/type-generation/languages/kotlin.js b/lib/type-generation/languages/kotlin.js deleted file mode 100644 index 8cecd74b..00000000 --- a/lib/type-generation/languages/kotlin.js +++ /dev/null @@ -1,94 +0,0 @@ -/** @typedef {import('../attribute').Attribute} Attribute */ -const { AttributeType } = require('../attribute'); -const { LanguageMeta } = require("./language"); - -class Kotlin extends LanguageMeta { - getType(attribute, collections, collectionName) { - let type = ""; - switch (attribute.type) { - case AttributeType.STRING: - case AttributeType.EMAIL: - case AttributeType.DATETIME: - type = "String"; - if (attribute.format === AttributeType.ENUM) { - type = LanguageMeta.toPascalCase(collectionName) + LanguageMeta.toPascalCase(attribute.key); - } - break; - case AttributeType.INTEGER: - type = "Int"; - break; - case AttributeType.FLOAT: - type = "Float"; - break; - case AttributeType.BOOLEAN: - type = "Boolean"; - break; - case AttributeType.RELATIONSHIP: - const relatedCollection = collections.find(c => c.$id === attribute.relatedCollection); - if (!relatedCollection) { - throw new Error(`Related collection with ID '${attribute.relatedCollection}' not found.`); - } - type = LanguageMeta.toPascalCase(relatedCollection.name); - if ((attribute.relationType === 'oneToMany' && attribute.side === 'parent') || (attribute.relationType === 'manyToOne' && attribute.side === 'child') || attribute.relationType === 'manyToMany') { - type = `List<${type}>`; - } - break; - case AttributeType.POINT: - type = "List"; - break; - case AttributeType.LINESTRING: - type = "List>"; - break; - case AttributeType.POLYGON: - type = "List>>"; - break; - default: - throw new Error(`Unknown attribute type: ${attribute.type}`); - } - if (attribute.array) { - type = "List<" + type + ">"; - } - if (!attribute.required && attribute.default === null) { - type += "?"; - } - return type; - } - - getTemplate() { - return `package io.appwrite.models - -<% for (const attribute of collection.attributes) { -%> -<% if (attribute.type === 'relationship') { -%> -import <%- toPascalCase(collections.find(c => c.$id === attribute.relatedCollection).name) %> - -<% } -%> -<% } -%> -/** - * This file is auto-generated by the Appwrite CLI. - * You can regenerate it by running \`appwrite ${process.argv.slice(2).join(' ')}\`. - */ - -<% for (const attribute of collection.attributes) { -%> -<% if (attribute.format === 'enum') { -%> -enum class <%- toPascalCase(collection.name) %><%- toPascalCase(attribute.key) %> { -<% for (const [index, element] of Object.entries(attribute.elements)) { -%> - <%- strict ? toUpperSnakeCase(element) : element %><%- index < attribute.elements.length - 1 ? ',' : '' %> -<% } -%> -} - -<% } -%> -<% } -%> -data class <%- toPascalCase(collection.name) %>( -<% for (const [index, attribute] of Object.entries(collection.attributes)) { -%> - val <%- strict ? toCamelCase(attribute.key) : attribute.key %>: <%- getType(attribute, collections, collection.name) %><% if (index < collection.attributes.length - 1) { %>,<% } %> -<% } -%> -) -`; - } - - getFileName(collection) { - return LanguageMeta.toPascalCase(collection.name) + ".kt"; - } -} - -module.exports = { Kotlin }; diff --git a/lib/type-generation/languages/kotlin.ts b/lib/type-generation/languages/kotlin.ts new file mode 100644 index 00000000..a2dbf173 --- /dev/null +++ b/lib/type-generation/languages/kotlin.ts @@ -0,0 +1,96 @@ +import { AttributeType } from '../attribute'; +import { LanguageMeta, Attribute, Collection } from './language'; + +export class Kotlin extends LanguageMeta { + getType(attribute: Attribute, collections?: Collection[], collectionName?: string): string { + let type = ''; + switch (attribute.type) { + case AttributeType.STRING: + case AttributeType.EMAIL: + case AttributeType.DATETIME: + type = 'String'; + if (attribute.format === AttributeType.ENUM) { + type = LanguageMeta.toPascalCase(collectionName!) + LanguageMeta.toPascalCase(attribute.key); + } + break; + case AttributeType.INTEGER: + type = 'Int'; + break; + case AttributeType.FLOAT: + type = 'Float'; + break; + case AttributeType.BOOLEAN: + type = 'Boolean'; + break; + case AttributeType.RELATIONSHIP: + const relatedCollection = collections?.find((c) => c.$id === attribute.relatedCollection); + if (!relatedCollection) { + throw new Error(`Related collection with ID '${attribute.relatedCollection}' not found.`); + } + type = LanguageMeta.toPascalCase(relatedCollection.name); + if ( + (attribute.relationType === 'oneToMany' && attribute.side === 'parent') || + (attribute.relationType === 'manyToOne' && attribute.side === 'child') || + attribute.relationType === 'manyToMany' + ) { + type = `List<${type}>`; + } + break; + case AttributeType.POINT: + type = 'List'; + break; + case AttributeType.LINESTRING: + type = 'List>'; + break; + case AttributeType.POLYGON: + type = 'List>>'; + break; + default: + throw new Error(`Unknown attribute type: ${attribute.type}`); + } + if (attribute.array) { + type = 'List<' + type + '>'; + } + if (!attribute.required && attribute.default === null) { + type += '?'; + } + return type; + } + + getTemplate(): string { + return `package io.appwrite.models + +<% for (const attribute of collection.attributes) { -%> +<% if (attribute.type === 'relationship') { -%> +import <%- toPascalCase(collections.find(c => c.$id === attribute.relatedCollection).name) %> + +<% } -%> +<% } -%> +/** + * This file is auto-generated by the Appwrite CLI. + * You can regenerate it by running \`appwrite ${process.argv.slice(2).join(' ')}\`. + */ + +<% for (const attribute of collection.attributes) { -%> +<% if (attribute.format === 'enum') { -%> +enum class <%- toPascalCase(collection.name) %><%- toPascalCase(attribute.key) %> { +<% for (const [index, element] of Object.entries(attribute.elements)) { -%> + <%- strict ? toUpperSnakeCase(element) : element %><%- index < attribute.elements.length - 1 ? ',' : '' %> +<% } -%> +} + +<% } -%> +<% } -%> +data class <%- toPascalCase(collection.name) %>( +<% for (const [index, attribute] of Object.entries(collection.attributes)) { -%> + val <%- strict ? toCamelCase(attribute.key) : attribute.key %>: <%- getType(attribute, collections, collection.name) %><% if (index < collection.attributes.length - 1) { %>,<% } %> +<% } -%> +) +`; + } + + getFileName(collection: Collection): string { + return LanguageMeta.toPascalCase(collection.name) + '.kt'; + } +} + diff --git a/lib/type-generation/languages/language.js b/lib/type-generation/languages/language.js deleted file mode 100644 index 96ba0bba..00000000 --- a/lib/type-generation/languages/language.js +++ /dev/null @@ -1,125 +0,0 @@ -/** @typedef {import('../attribute').Attribute} Attribute */ -/** @typedef {import('../collection').Collection} Collection */ - -const fs = require("fs"); -const path = require("path"); - -class LanguageMeta { - constructor() { - if (new.target === LanguageMeta) { - throw new TypeError("Abstract classes can't be instantiated."); - } - } - - static toKebabCase(string) { - return string - .replace(/[^a-zA-Z0-9\s-_]/g, "") // Remove invalid characters - .replace(/([a-z])([A-Z])/g, "$1-$2") // Add hyphen between camelCase - .replace(/([A-Z])([A-Z][a-z])/g, "$1-$2") // Add hyphen between PascalCase - .replace(/[_\s]+/g, "-") // Replace spaces and underscores with hyphens - .replace(/^-+|-+$/g, "") // Remove leading and trailing hyphens - .replace(/--+/g, "-") // Replace multiple hyphens with a single hyphen - .toLowerCase(); - } - - static toSnakeCase(string) { - return this.toKebabCase(string).replace(/-/g, "_"); - } - - static toUpperSnakeCase(string) { - return this.toSnakeCase(string).toUpperCase(); - } - - static toCamelCase(string) { - return this.toKebabCase(string).replace(/-([a-z0-9])/g, (g) => - g[1].toUpperCase() - ); - } - - static toPascalCase(string) { - return this.toCamelCase(string).replace(/^./, (g) => g.toUpperCase()); - } - - /** - * Get the type literal of the given attribute. - * - * @abstract - * @param {Attribute} attribute - * @return {string} - */ - getType(attribute) { - throw new TypeError("Stub."); - } - - /** - * Returns true if the language uses a single file for all types. - * - * @returns {boolean} - */ - isSingleFile() { - return false; - } - - /** - * Get the EJS template used to generate the types for this language. - * - * @abstract - * @returns {string} - */ - getTemplate() { - throw new TypeError("Stub."); - } - - /** - * Get the file extension used by files of this language. - * - * @abstract - * @param {Collection|undefined} collection - * @returns {string} - */ - getFileName(collection) { - throw new TypeError("Stub."); - } -} - -const existsFiles = (...files) => - files.some((file) => fs.existsSync(path.join(process.cwd(), file))); - -/** - * @returns {string} - */ -function detectLanguage() { - if (existsFiles("tsconfig.json", "deno.json")) { - return "ts"; - } - if (existsFiles("package.json")) { - return "js"; - } - if (existsFiles("composer.json")) { - return "php"; - } - if (existsFiles("requirements.txt", "Pipfile", "pyproject.toml")) { - return "python"; - } - if (existsFiles("Gemfile", "Rakefile")) { - return "ruby"; - } - if (existsFiles("build.gradle.kts")) { - return "kotlin"; - } - if (existsFiles("build.gradle", "pom.xml")) { - return "java"; - } - if (existsFiles("*.csproj")) { - return "dotnet"; - } - if (existsFiles("Package.swift")) { - return "swift"; - } - if (existsFiles("pubspec.yaml")) { - return "dart"; - } - throw new Error("Could not detect language, please specify with -l"); -} - -module.exports = { LanguageMeta, detectLanguage }; diff --git a/lib/type-generation/languages/language.ts b/lib/type-generation/languages/language.ts new file mode 100644 index 00000000..4b6a84e6 --- /dev/null +++ b/lib/type-generation/languages/language.ts @@ -0,0 +1,119 @@ +import fs = require('fs'); +import path = require('path'); + +export interface Attribute { + key: string; + type: string; + required?: boolean; + array?: boolean; + default?: any; + format?: string; + elements?: string[]; + relatedCollection?: string; + relationType?: string; + side?: string; +} + +export interface Collection { + $id: string; + name: string; + attributes: Attribute[]; +} + +export abstract class LanguageMeta { + constructor() { + if (new.target === LanguageMeta) { + throw new TypeError("Abstract classes can't be instantiated."); + } + } + + static toKebabCase(string: string): string { + return string + .replace(/[^a-zA-Z0-9\s-_]/g, '') // Remove invalid characters + .replace(/([a-z])([A-Z])/g, '$1-$2') // Add hyphen between camelCase + .replace(/([A-Z])([A-Z][a-z])/g, '$1-$2') // Add hyphen between PascalCase + .replace(/[_\s]+/g, '-') // Replace spaces and underscores with hyphens + .replace(/^-+|-+$/g, '') // Remove leading and trailing hyphens + .replace(/--+/g, '-') // Replace multiple hyphens with a single hyphen + .toLowerCase(); + } + + static toSnakeCase(string: string): string { + return this.toKebabCase(string).replace(/-/g, '_'); + } + + static toUpperSnakeCase(string: string): string { + return this.toSnakeCase(string).toUpperCase(); + } + + static toCamelCase(string: string): string { + return this.toKebabCase(string).replace(/-([a-z0-9])/g, (g) => g[1].toUpperCase()); + } + + static toPascalCase(string: string): string { + return this.toCamelCase(string).replace(/^./, (g) => g.toUpperCase()); + } + + /** + * Get the type literal of the given attribute. + */ + abstract getType(attribute: Attribute, collections?: Collection[], collectionName?: string): string; + + /** + * Returns true if the language uses a single file for all types. + */ + isSingleFile(): boolean { + return false; + } + + /** + * Get the EJS template used to generate the types for this language. + */ + abstract getTemplate(): string; + + /** + * Get the file extension used by files of this language. + */ + abstract getFileName(collection?: Collection): string; +} + +const existsFiles = (...files: string[]): boolean => + files.some((file) => fs.existsSync(path.join(process.cwd(), file))); + +export function detectLanguage(): string { + if (existsFiles('tsconfig.json', 'deno.json')) { + return 'ts'; + } + if (existsFiles('package.json')) { + return 'js'; + } + if (existsFiles('composer.json')) { + return 'php'; + } + if (existsFiles('requirements.txt', 'Pipfile', 'pyproject.toml')) { + return 'python'; + } + if (existsFiles('Gemfile', 'Rakefile')) { + return 'ruby'; + } + if (existsFiles('build.gradle.kts')) { + return 'kotlin'; + } + if (existsFiles('build.gradle', 'pom.xml')) { + return 'java'; + } + try { + if (fs.readdirSync(process.cwd()).some((file) => file.endsWith('.csproj'))) { + return 'dotnet'; + } + } catch { + // Directory not readable, skip .csproj detection + } + if (existsFiles('Package.swift')) { + return 'swift'; + } + if (existsFiles('pubspec.yaml')) { + return 'dart'; + } + throw new Error('Could not detect language, please specify with -l'); +} diff --git a/lib/type-generation/languages/php.js b/lib/type-generation/languages/php.ts similarity index 53% rename from lib/type-generation/languages/php.js rename to lib/type-generation/languages/php.ts index d316796f..942f0225 100644 --- a/lib/type-generation/languages/php.js +++ b/lib/type-generation/languages/php.ts @@ -1,57 +1,60 @@ -/** @typedef {import('../attribute').Attribute} Attribute */ -const { AttributeType } = require('../attribute'); -const { LanguageMeta } = require("./language"); +import { AttributeType } from '../attribute'; +import { LanguageMeta, Attribute, Collection } from './language'; -class PHP extends LanguageMeta { - getType(attribute, collections, collectionName) { - if (attribute.array) { - return "array"; - } - let type = "" - switch (attribute.type) { - case AttributeType.STRING: - case AttributeType.EMAIL: - case AttributeType.DATETIME: - type = "string"; - if (attribute.format === AttributeType.ENUM) { - type = LanguageMeta.toPascalCase(collectionName) + LanguageMeta.toPascalCase(attribute.key); +export class PHP extends LanguageMeta { + getType(attribute: Attribute, collections?: Collection[], collectionName?: string): string { + if (attribute.array) { + return 'array'; } - break; - case AttributeType.INTEGER: - type = "int"; - break; - case AttributeType.FLOAT: - type = "float"; - break; - case AttributeType.BOOLEAN: - type = "bool"; - break; - case AttributeType.RELATIONSHIP: - const relatedCollection = collections.find(c => c.$id === attribute.relatedCollection); - if (!relatedCollection) { - throw new Error(`Related collection with ID '${attribute.relatedCollection}' not found.`); + let type = ''; + switch (attribute.type) { + case AttributeType.STRING: + case AttributeType.EMAIL: + case AttributeType.DATETIME: + type = 'string'; + if (attribute.format === AttributeType.ENUM) { + type = LanguageMeta.toPascalCase(collectionName!) + LanguageMeta.toPascalCase(attribute.key); + } + break; + case AttributeType.INTEGER: + type = 'int'; + break; + case AttributeType.FLOAT: + type = 'float'; + break; + case AttributeType.BOOLEAN: + type = 'bool'; + break; + case AttributeType.RELATIONSHIP: + const relatedCollection = collections?.find((c) => c.$id === attribute.relatedCollection); + if (!relatedCollection) { + throw new Error(`Related collection with ID '${attribute.relatedCollection}' not found.`); + } + type = LanguageMeta.toPascalCase(relatedCollection.name); + if ( + (attribute.relationType === 'oneToMany' && attribute.side === 'parent') || + (attribute.relationType === 'manyToOne' && attribute.side === 'child') || + attribute.relationType === 'manyToMany' + ) { + type = 'array'; + } + break; + case AttributeType.POINT: + case AttributeType.LINESTRING: + case AttributeType.POLYGON: + type = 'array'; + break; + default: + throw new Error(`Unknown attribute type: ${attribute.type}`); } - type = LanguageMeta.toPascalCase(relatedCollection.name); - if ((attribute.relationType === 'oneToMany' && attribute.side === 'parent') || (attribute.relationType === 'manyToOne' && attribute.side === 'child') || attribute.relationType === 'manyToMany') { - type = "array"; + if (!attribute.required && attribute.default === null) { + type += '|null'; } - break; - case AttributeType.POINT: - case AttributeType.LINESTRING: - case AttributeType.POLYGON: - type = "array"; - break; - default: - throw new Error(`Unknown attribute type: ${attribute.type}`); - } - if (!attribute.required && attribute.default === null) { - type += "|null"; + return type; } - return type; - } - getTemplate() { - return ` { <% } -%> } `; - } + } - getFileName(collection) { - return LanguageMeta.toPascalCase(collection.name) + ".php"; - } + getFileName(collection: Collection): string { + return LanguageMeta.toPascalCase(collection.name) + '.php'; + } } -module.exports = { PHP }; diff --git a/lib/type-generation/languages/swift.js b/lib/type-generation/languages/swift.ts similarity index 76% rename from lib/type-generation/languages/swift.js rename to lib/type-generation/languages/swift.ts index 8cb25748..4910dc4f 100644 --- a/lib/type-generation/languages/swift.js +++ b/lib/type-generation/languages/swift.ts @@ -1,61 +1,64 @@ -/** @typedef {import('../attribute').Attribute} Attribute */ -const { AttributeType } = require('../attribute'); -const { LanguageMeta } = require("./language"); +import { AttributeType } from '../attribute'; +import { LanguageMeta, Attribute, Collection } from './language'; -class Swift extends LanguageMeta { - getType(attribute, collections, collectionName) { - let type = ""; - switch (attribute.type) { - case AttributeType.STRING: - case AttributeType.EMAIL: - case AttributeType.DATETIME: - type = "String"; - if (attribute.format === AttributeType.ENUM) { - type = LanguageMeta.toPascalCase(collectionName) + LanguageMeta.toPascalCase(attribute.key); +export class Swift extends LanguageMeta { + getType(attribute: Attribute, collections?: Collection[], collectionName?: string): string { + let type = ''; + switch (attribute.type) { + case AttributeType.STRING: + case AttributeType.EMAIL: + case AttributeType.DATETIME: + type = 'String'; + if (attribute.format === AttributeType.ENUM) { + type = LanguageMeta.toPascalCase(collectionName!) + LanguageMeta.toPascalCase(attribute.key); + } + break; + case AttributeType.INTEGER: + type = 'Int'; + break; + case AttributeType.FLOAT: + type = 'Double'; + break; + case AttributeType.BOOLEAN: + type = 'Bool'; + break; + case AttributeType.RELATIONSHIP: + const relatedCollection = collections?.find((c) => c.$id === attribute.relatedCollection); + if (!relatedCollection) { + throw new Error(`Related collection with ID '${attribute.relatedCollection}' not found.`); + } + type = LanguageMeta.toPascalCase(relatedCollection.name); + if ( + (attribute.relationType === 'oneToMany' && attribute.side === 'parent') || + (attribute.relationType === 'manyToOne' && attribute.side === 'child') || + attribute.relationType === 'manyToMany' + ) { + type = `[${type}]`; + } + break; + case AttributeType.POINT: + type = '[Double]'; + break; + case AttributeType.LINESTRING: + type = '[[Double]]'; + break; + case AttributeType.POLYGON: + type = '[[[Double]]]'; + break; + default: + throw new Error(`Unknown attribute type: ${attribute.type}`); } - break; - case AttributeType.INTEGER: - type = "Int"; - break; - case AttributeType.FLOAT: - type = "Double"; - break; - case AttributeType.BOOLEAN: - type = "Bool"; - break; - case AttributeType.RELATIONSHIP: - const relatedCollection = collections.find(c => c.$id === attribute.relatedCollection); - if (!relatedCollection) { - throw new Error(`Related collection with ID '${attribute.relatedCollection}' not found.`); + if (attribute.array) { + type = '[' + type + ']'; } - type = LanguageMeta.toPascalCase(relatedCollection.name); - if ((attribute.relationType === 'oneToMany' && attribute.side === 'parent') || (attribute.relationType === 'manyToOne' && attribute.side === 'child') || attribute.relationType === 'manyToMany') { - type = `[${type}]`; + if (!attribute.required && attribute.default === null) { + type += '?'; } - break; - case AttributeType.POINT: - type = "[Double]"; - break; - case AttributeType.LINESTRING: - type = "[[Double]]"; - break; - case AttributeType.POLYGON: - type = "[[[Double]]]"; - break; - default: - throw new Error(`Unknown attribute type: ${attribute.type}`); + return type; } - if (attribute.array) { - type = "[" + type + "]"; - } - if (!attribute.required && attribute.default === null) { - type += "?"; - } - return type; - } - getTemplate() { - return `import Foundation + getTemplate(): string { + return `import Foundation /// This file is auto-generated by the Appwrite CLI. /// You can regenerate it by running \`appwrite ${process.argv.slice(2).join(' ')}\`. @@ -168,11 +171,10 @@ public class <%- toPascalCase(collection.name) %>: Codable { ) } }`; - } + } - getFileName(collection) { - return LanguageMeta.toPascalCase(collection.name) + ".swift"; - } + getFileName(collection: Collection): string { + return LanguageMeta.toPascalCase(collection.name) + '.swift'; + } } -module.exports = { Swift }; diff --git a/lib/type-generation/languages/typescript.js b/lib/type-generation/languages/typescript.js deleted file mode 100644 index d3fdd67b..00000000 --- a/lib/type-generation/languages/typescript.js +++ /dev/null @@ -1,116 +0,0 @@ -/** @typedef {import('../attribute').Attribute} Attribute */ -const fs = require("fs"); -const path = require("path"); - -const { AttributeType } = require('../attribute'); -const { LanguageMeta } = require("./language"); - -class TypeScript extends LanguageMeta { - getType(attribute, collections, collectionName) { - let type = "" - switch (attribute.type) { - case AttributeType.STRING: - case AttributeType.EMAIL: - case AttributeType.DATETIME: - case AttributeType.IP: - case AttributeType.URL: - type = "string"; - if (attribute.format === AttributeType.ENUM) { - type = LanguageMeta.toPascalCase(collectionName) + LanguageMeta.toPascalCase(attribute.key); - } - break; - case AttributeType.INTEGER: - type = "number"; - break; - case AttributeType.FLOAT: - type = "number"; - break; - case AttributeType.BOOLEAN: - type = "boolean"; - break; - case AttributeType.RELATIONSHIP: - const relatedCollection = collections.find(c => c.$id === attribute.relatedCollection); - if (!relatedCollection) { - throw new Error(`Related collection with ID '${attribute.relatedCollection}' not found.`); - } - type = LanguageMeta.toPascalCase(relatedCollection.name); - if ((attribute.relationType === 'oneToMany' && attribute.side === 'parent') || (attribute.relationType === 'manyToOne' && attribute.side === 'child') || attribute.relationType === 'manyToMany') { - type = `${type}[]`; - } - break; - case AttributeType.POINT: - type = "Array"; - break; - case AttributeType.LINESTRING: - type = "Array>"; - break; - case AttributeType.POLYGON: - type = "Array>>"; - break; - default: - throw new Error(`Unknown attribute type: ${attribute.type}`); - } - if (attribute.array) { - type += "[]"; - } - if (!attribute.required && attribute.default === null) { - type += " | null"; - } - return type; - } - - isSingleFile() { - return true; - } - - _getAppwriteDependency() { - if (fs.existsSync(path.resolve(process.cwd(), 'package.json'))) { - const packageJsonRaw = fs.readFileSync(path.resolve(process.cwd(), 'package.json')); - const packageJson = JSON.parse(packageJsonRaw.toString('utf-8')); - return packageJson.dependencies['node-appwrite'] ? 'node-appwrite' : 'appwrite'; - } - - if (fs.existsSync(path.resolve(process.cwd(), 'deno.json'))) { - return "https://deno.land/x/appwrite/mod.ts"; - } - - return "appwrite"; - } - - getTemplate() { - return `import type { Models } from '${this._getAppwriteDependency()}'; - -// This file is auto-generated by the Appwrite CLI. -// You can regenerate it by running \`appwrite ${process.argv.slice(2).join(' ')}\`. - -<% for (const collection of collections) { -%> -<% for (const attribute of collection.attributes) { -%> -<% if (attribute.format === 'enum') { -%> -export enum <%- toPascalCase(collection.name) %><%- toPascalCase(attribute.key) %> { -<% const entries = Object.entries(attribute.elements); -%> -<% for (let i = 0; i < entries.length; i++) { -%> - <%- toUpperSnakeCase(entries[i][1]) %> = "<%- entries[i][1] %>"<% if (i !== entries.length - 1) { %>,<% } %> -<% } -%> -} - -<% } -%> -<% } -%> -<% } -%> -<% for (const [index, collection] of Object.entries(collections)) { -%> -export type <%- toPascalCase(collection.name) %> = Models.Row & { -<% for (const attribute of collection.attributes) { -%> -<% const propertyName = strict ? toCamelCase(attribute.key) : attribute.key; -%> -<% const isValidIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(propertyName); -%> - <% if (isValidIdentifier) { %><%- propertyName %><% } else { %>"<%- propertyName %>"<% } %>: <%- getType(attribute, collections, collection.name) %>; -<% } -%> -}<% if (index < collections.length - 1) { %> -<% } %> -<% } -%>`; - } - - getFileName(_) { - return "appwrite.d.ts"; - } -} - -module.exports = { TypeScript }; diff --git a/lib/type-generation/languages/typescript.ts b/lib/type-generation/languages/typescript.ts new file mode 100644 index 00000000..b28f2c0d --- /dev/null +++ b/lib/type-generation/languages/typescript.ts @@ -0,0 +1,116 @@ +import fs = require('fs'); +import path = require('path'); +import { AttributeType } from '../attribute'; +import { LanguageMeta, Attribute, Collection } from './language'; + +export class TypeScript extends LanguageMeta { + getType(attribute: Attribute, collections?: Collection[], collectionName?: string): string { + let type = ''; + switch (attribute.type) { + case AttributeType.STRING: + case AttributeType.EMAIL: + case AttributeType.DATETIME: + case AttributeType.IP: + case AttributeType.URL: + type = 'string'; + if (attribute.format === AttributeType.ENUM) { + type = LanguageMeta.toPascalCase(collectionName!) + LanguageMeta.toPascalCase(attribute.key); + } + break; + case AttributeType.INTEGER: + type = 'number'; + break; + case AttributeType.FLOAT: + type = 'number'; + break; + case AttributeType.BOOLEAN: + type = 'boolean'; + break; + case AttributeType.RELATIONSHIP: + const relatedCollection = collections?.find((c) => c.$id === attribute.relatedCollection); + if (!relatedCollection) { + throw new Error(`Related collection with ID '${attribute.relatedCollection}' not found.`); + } + type = LanguageMeta.toPascalCase(relatedCollection.name); + if ( + (attribute.relationType === 'oneToMany' && attribute.side === 'parent') || + (attribute.relationType === 'manyToOne' && attribute.side === 'child') || + attribute.relationType === 'manyToMany' + ) { + type = `${type}[]`; + } + break; + case AttributeType.POINT: + type = 'Array'; + break; + case AttributeType.LINESTRING: + type = 'Array>'; + break; + case AttributeType.POLYGON: + type = 'Array>>'; + break; + default: + throw new Error(`Unknown attribute type: ${attribute.type}`); + } + if (attribute.array) { + type += '[]'; + } + if (!attribute.required && attribute.default === null) { + type += ' | null'; + } + return type; + } + + isSingleFile(): boolean { + return true; + } + + private _getAppwriteDependency(): string { + if (fs.existsSync(path.resolve(process.cwd(), 'package.json'))) { + const packageJsonRaw = fs.readFileSync(path.resolve(process.cwd(), 'package.json')); + const packageJson = JSON.parse(packageJsonRaw.toString('utf-8')); + return packageJson.dependencies && packageJson.dependencies['node-appwrite'] ? 'node-appwrite' : 'appwrite'; + } + + if (fs.existsSync(path.resolve(process.cwd(), 'deno.json'))) { + return 'https://deno.land/x/appwrite/mod.ts'; + } + + return 'appwrite'; + } + + getTemplate(): string { + return `import type { Models } from '${this._getAppwriteDependency()}'; + +// This file is auto-generated by the Appwrite CLI. +// You can regenerate it by running \`appwrite ${process.argv.slice(2).join(' ')}\`. + +<% for (const collection of collections) { -%> +<% for (const attribute of collection.attributes) { -%> +<% if (attribute.format === 'enum') { -%> +export enum <%- toPascalCase(collection.name) %><%- toPascalCase(attribute.key) %> { +<% const entries = Object.entries(attribute.elements); -%> +<% for (let i = 0; i < entries.length; i++) { -%> + <%- toUpperSnakeCase(entries[i][1]) %> = "<%- entries[i][1] %>"<% if (i !== entries.length - 1) { %>,<% } %> +<% } -%> +} + +<% } -%> +<% } -%> +<% } -%> +<% for (const [index, collection] of Object.entries(collections)) { -%> +export type <%- toPascalCase(collection.name) %> = Models.Row & { +<% for (const attribute of collection.attributes) { -%> +<% const propertyName = strict ? toCamelCase(attribute.key) : attribute.key; -%> +<% const isValidIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(propertyName); -%> + <% if (isValidIdentifier) { %><%- propertyName %><% } else { %>"<%- propertyName %>"<% } %>: <%- getType(attribute, collections, collection.name) %>; +<% } -%> +}<% if (index < collections.length - 1) { %> +<% } %> +<% } -%>`; + } + + getFileName(_: Collection | undefined): string { + return 'appwrite.d.ts'; + } +} diff --git a/lib/types.ts b/lib/types.ts new file mode 100644 index 00000000..dee317a9 --- /dev/null +++ b/lib/types.ts @@ -0,0 +1,150 @@ +export interface CliConfig { + verbose: boolean; + json: boolean; + force: boolean; + all: boolean; + ids: string[]; + report: boolean; + reportData: Record; +} + +export interface Headers { + [key: string]: string; +} + +export interface RequestParams { + [key: string]: unknown; +} + +export interface FileUpload { + type: 'file'; + file: Buffer | ReadableStream; + filename: string; +} + +export type ResponseType = 'json' | 'arraybuffer'; + +export interface ConfigData { + [key: string]: unknown; +} + +export interface SessionData { + endpoint: string; + email?: string; + phone?: string; + cookie?: string; +} + +export interface GlobalConfigData { + sessions: { + [key: string]: SessionData; + }; + current: string; + cookie?: string; +} + +export interface ProjectConfigData { + projectId?: string; + projectName?: string; + functions?: FunctionConfig[]; + collections?: CollectionConfig[]; + databases?: DatabaseConfig[]; + buckets?: BucketConfig[]; + teams?: TeamConfig[]; + topics?: TopicConfig[]; +} + +export interface FunctionConfig { + $id: string; + name: string; + runtime: string; + path: string; + entrypoint: string; + execute?: string[]; + enabled?: boolean; + logging?: boolean; + events?: string[]; + schedule?: string; + timeout?: number; + vars?: Record; + commands?: string; + scopes?: string[]; + specification?: string; +} + +export interface CollectionConfig { + $id: string; + $permissions?: string[]; + databaseId: string; + name: string; + enabled?: boolean; + documentSecurity?: boolean; + attributes?: AttributeConfig[]; + indexes?: IndexConfig[]; +} + +export interface AttributeConfig { + key: string; + type: string; + required?: boolean; + array?: boolean; + size?: number; + default?: unknown; + min?: number; + max?: number; + format?: string; + elements?: string[]; + relatedCollection?: string; + relationType?: string; + twoWay?: boolean; + twoWayKey?: string; + onDelete?: string; + side?: string; + encrypt?: boolean; +} + +export interface IndexConfig { + key: string; + type: string; + status?: string; + attributes?: string[]; + orders?: string[]; +} + +export interface DatabaseConfig { + $id: string; + name: string; + enabled?: boolean; +} + +export interface BucketConfig { + $id: string; + $permissions?: string[]; + name: string; + enabled?: boolean; + fileSecurity?: boolean; + maximumFileSize?: number; + allowedFileExtensions?: string[]; + compression?: string; + encryption?: boolean; + antivirus?: boolean; +} + +export interface TeamConfig { + $id: string; + name: string; +} + +export interface TopicConfig { + $id: string; + name: string; + subscribe?: string[]; +} + +export interface CommandDescription { + [key: string]: string; +} + +export interface ParsedData { + [key: string]: unknown; +} diff --git a/lib/utils.js b/lib/utils.ts similarity index 62% rename from lib/utils.js rename to lib/utils.ts index ee9f22f2..92180a74 100644 --- a/lib/utils.js +++ b/lib/utils.ts @@ -1,50 +1,50 @@ -const fs = require("fs"); -const path = require("path"); -const net = require("net"); -const childProcess = require('child_process'); -const chalk = require('chalk'); -const { fetch } = require("undici"); -const { localConfig, globalConfig } = require("./config"); +import fs = require('fs'); +import path = require('path'); +import net = require('net'); +import childProcess = require('child_process'); +import chalk = require('chalk'); +import { fetch } from 'undici'; +import { localConfig, globalConfig } from './config'; /** * Get the latest version from npm registry */ -async function getLatestVersion() { +export async function getLatestVersion(): Promise { try { const response = await fetch('https://registry.npmjs.org/appwrite-cli/latest'); if (!response.ok) { throw new Error(`HTTP ${response.status}`); } - const data = await response.json(); + const data = await response.json() as { version: string }; return data.version; } catch (e) { - throw new Error(`Failed to fetch latest version: ${e.message}`); + throw new Error(`Failed to fetch latest version: ${(e as Error).message}`); } } /** * Compare versions using semantic versioning */ -function compareVersions(current, latest) { +export function compareVersions(current: string, latest: string): number { const currentParts = current.split('.').map(Number); const latestParts = latest.split('.').map(Number); - + for (let i = 0; i < Math.max(currentParts.length, latestParts.length); i++) { const currentPart = currentParts[i] || 0; const latestPart = latestParts[i] || 0; - - if (latestPart > currentPart) return 1; // Latest is newer + + if (latestPart > currentPart) return 1; // Latest is newer if (latestPart < currentPart) return -1; // Current is newer } - + return 0; // Same version } -function getAllFiles(folder) { - const files = []; +export function getAllFiles(folder: string): string[] { + const files: string[] = []; for (const pathDir of fs.readdirSync(folder)) { const pathAbsolute = path.join(folder, pathDir); - let stats; + let stats: fs.Stats; try { stats = fs.statSync(pathAbsolute); } catch (error) { @@ -59,16 +59,20 @@ function getAllFiles(folder) { return files; } -async function isPortTaken(port) { - const taken = await new Promise((res, rej) => { - const tester = net.createServer() - .once('error', function (err) { - if (err.code != 'EADDRINUSE') return rej(err) - res(true) +export async function isPortTaken(port: number): Promise { + const taken = await new Promise((res, rej) => { + const tester = net + .createServer() + .once('error', function (err: NodeJS.ErrnoException) { + if (err.code != 'EADDRINUSE') return rej(err); + res(true); }) - .once('listening', function() { - tester.once('close', function() { res(false) }) - .close() + .once('listening', function () { + tester + .once('close', function () { + res(false); + }) + .close(); }) .listen(port); }); @@ -76,14 +80,17 @@ async function isPortTaken(port) { return taken; } -function systemHasCommand(command) { - const isUsingWindows = process.platform == 'win32' +export function systemHasCommand(command: string): boolean { + const isUsingWindows = process.platform == 'win32'; - try { - if(isUsingWindows) { - childProcess.execSync('where ' + command, { stdio: 'pipe' }) + try { + if (isUsingWindows) { + childProcess.execSync('where ' + command, { stdio: 'pipe' }); } else { - childProcess.execSync(`[[ $(${command} --version) ]] || { exit 1; } && echo "OK"`, { stdio: 'pipe', shell: '/bin/bash' }); + childProcess.execSync(`[[ $(${command} --version) ]] || { exit 1; } && echo "OK"`, { + stdio: 'pipe', + shell: '/bin/bash', + }); } } catch (error) { console.log(error); @@ -93,13 +100,15 @@ function systemHasCommand(command) { return true; } -const checkDeployConditions = (localConfig) => { +export const checkDeployConditions = (localConfig: any): void => { if (Object.keys(localConfig.data).length === 0) { - throw new Error("No appwrite.config.json file found in the current directory. Please run this command again in the folder containing your appwrite.config.json file, or run 'appwrite init project' to link current directory to an Appwrite project."); + throw new Error( + "No appwrite.config.json file found in the current directory. Please run this command again in the folder containing your appwrite.config.json file, or run 'appwrite init project' to link current directory to an Appwrite project." + ); } -} +}; -function showConsoleLink(serviceName, action, ...ids) { +export function showConsoleLink(serviceName: string, action: string, ...ids: string[]): void { const projectId = localConfig.getProject().projectId; const url = new URL(globalConfig.getEndpoint().replace('/v1', '/console')); @@ -107,43 +116,43 @@ function showConsoleLink(serviceName, action, ...ids) { action = action.toLowerCase(); switch (serviceName) { - case "account": + case 'account': url.pathname = url.pathname.replace(`/project-${projectId}`, ''); url.pathname += getAccountPath(action); break; - case "databases": + case 'databases': url.pathname += getDatabasePath(action, ids); break; - case "functions": + case 'functions': url.pathname += getFunctionsPath(action, ids); break; - case "messaging": + case 'messaging': url.pathname += getMessagingPath(action, ids); break; - case "projects": + case 'projects': url.pathname = url.pathname.replace(`/project-${projectId}`, ''); url.pathname += getProjectsPath(action, ids); break; - case "storage": + case 'storage': url.pathname += getBucketsPath(action, ids); break; - case "teams": + case 'teams': url.pathname += getTeamsPath(action, ids); break; - case "organizations": + case 'organizations': url.pathname += getOrganizationsPath(action, ids); break; - case "users": + case 'users': url.pathname += getUsersPath(action, ids); break; default: return; } - console.log(`${chalk.green.bold("āœ“ Success:")} ${chalk.green(url)}`); + console.log(`${chalk.green.bold('āœ“ Success:')} ${chalk.green(url.toString())}`); } -function getAccountPath(action) { +function getAccountPath(action: string): string { let path = '/account'; if (action === 'listsessions') { @@ -153,10 +162,9 @@ function getAccountPath(action) { return path; } -function getDatabasePath(action, ids) { +function getDatabasePath(action: string, ids: string[]): string { let path = '/databases'; - if (['get', 'listcollections', 'getcollection', 'listattributes', 'listdocuments', 'getdocument', 'listindexes', 'getdatabaseusage'].includes(action)) { path += `/database-${ids[0]}`; } @@ -179,11 +187,10 @@ function getDatabasePath(action, ids) { path += `/document-${ids[2]}`; } - return path; } -function getFunctionsPath(action, ids) { +function getFunctionsPath(action: string, ids: string[]): string { let path = '/functions'; if (action !== 'list') { @@ -191,20 +198,20 @@ function getFunctionsPath(action, ids) { } if (action === 'getdeployment') { - path += `/deployment-${ids[1]}` + path += `/deployment-${ids[1]}`; } if (action === 'getexecution' || action === 'listexecution') { - path += `/executions` + path += `/executions`; } if (action === 'getfunctionusage') { - path += `/usage` + path += `/usage`; } return path; } -function getMessagingPath(action, ids) { +function getMessagingPath(action: string, ids: string[]): string { let path = '/messaging'; if (['getmessage', 'listmessagelogs'].includes(action)) { @@ -230,7 +237,7 @@ function getMessagingPath(action, ids) { return path; } -function getProjectsPath(action, ids) { +function getProjectsPath(action: string, ids: string[]): string { let path = ''; if (action !== 'list') { @@ -238,15 +245,15 @@ function getProjectsPath(action, ids) { } if (['listkeys', 'getkey'].includes(action)) { - path += '/overview/keys' + path += '/overview/keys'; } if (['listplatforms', 'getplatform'].includes(action)) { - path += '/overview/platforms' + path += '/overview/platforms'; } if (['listwebhooks', 'getwebhook'].includes(action)) { - path += '/settings/webhooks' + path += '/settings/webhooks'; } if (['getplatform', 'getkey', 'getwebhook'].includes(action)) { @@ -256,7 +263,7 @@ function getProjectsPath(action, ids) { return path; } -function getBucketsPath(action, ids) { +function getBucketsPath(action: string, ids: string[]): string { let path = '/storage'; if (action !== 'listbuckets') { @@ -264,17 +271,17 @@ function getBucketsPath(action, ids) { } if (action === 'getbucketusage') { - path += `/usage` + path += `/usage`; } if (action === 'getfile') { - path += `/file-${ids[1]}` + path += `/file-${ids[1]}`; } return path; } -function getTeamsPath(action, ids) { +function getTeamsPath(action: string, ids: string[]): string { let path = '/auth/teams'; if (action !== 'list') { @@ -284,7 +291,7 @@ function getTeamsPath(action, ids) { return path; } -function getOrganizationsPath(action, ids) { +function getOrganizationsPath(action: string, ids: string[]): string { let path = `/organization-${ids[0]}`; if (action === 'list') { @@ -294,7 +301,7 @@ function getOrganizationsPath(action, ids) { return path; } -function getUsersPath(action, ids) { +function getUsersPath(action: string, ids: string[]): string { let path = '/auth'; if (action !== 'list') { @@ -308,19 +315,8 @@ function getUsersPath(action, ids) { return path; } -function isCloud() { - const endpoint = globalConfig.getEndpoint() || "https://cloud.appwrite.io/v1"; +export function isCloud(): boolean { + const endpoint = globalConfig.getEndpoint() || 'https://cloud.appwrite.io/v1'; const hostname = new URL(endpoint).hostname; return hostname.endsWith('appwrite.io'); } - -module.exports = { - getAllFiles, - isPortTaken, - systemHasCommand, - checkDeployConditions, - showConsoleLink, - isCloud, - getLatestVersion, - compareVersions -}; diff --git a/lib/validations.js b/lib/validations.js deleted file mode 100644 index bfae5ba3..00000000 --- a/lib/validations.js +++ /dev/null @@ -1,17 +0,0 @@ -const validateRequired = (resource, value) => { - if (Array.isArray(value)) { - if (value.length <= 0) { - return `Please select at least one ${resource}`; - } - } else { - if (value === undefined || value === null || value === 0 || (typeof value === "string" && value.trim() === '')) { - return `${resource} is required`; - } - } - - return true; -} - -module.exports = { - validateRequired -} diff --git a/lib/validations.ts b/lib/validations.ts new file mode 100644 index 00000000..9720c9af --- /dev/null +++ b/lib/validations.ts @@ -0,0 +1,17 @@ +export const validateRequired = (resource: string, value: any): string | true => { + if (Array.isArray(value)) { + if (value.length <= 0) { + return `Please select at least one ${resource}`; + } + } else { + if ( + value === undefined || + value === null || + (typeof value === 'string' && value.trim() === '') + ) { + return `${resource} is required`; + } + } + + return true; +}; diff --git a/package.json b/package.json index f2878153..fefbaf51 100644 --- a/package.json +++ b/package.json @@ -2,24 +2,27 @@ "name": "appwrite-cli", "homepage": "https://appwrite.io/support", "description": "Appwrite is an open-source self-hosted backend server that abstract and simplify complex and repetitive development tasks behind a very simple REST API", - "version": "12.0.1", + "version": "13.0.0-rc.1", "license": "BSD-3-Clause", - "main": "index.js", + "main": "dist/index.js", + "types": "dist/index.d.ts", "bin": { - "appwrite": "index.js" + "appwrite": "dist/index.js" }, "repository": { "type": "git", "url": "https://github.com/appwrite/sdk-for-cli" }, "scripts": { + "build": "tsc", + "prepublishOnly": "npm run build", "test": "echo \"Error: no test specified\" && exit 1", - "linux-x64": "pkg -t node18-linux-x64 -o build/appwrite-cli-linux-x64 package.json", - "linux-arm64": "pkg -t node18-linux-arm64 -o build/appwrite-cli-linux-arm64 package.json", - "mac-x64": "pkg -t node18-macos-x64 -o build/appwrite-cli-darwin-x64 package.json", - "mac-arm64": "pkg -t node18-macos-arm64 -o build/appwrite-cli-darwin-arm64 package.json", - "windows-x64": "pkg -t node18-win-x64 -o build/appwrite-cli-win-x64.exe package.json", - "windows-arm64": "pkg -t node18-win-arm64 -o build/appwrite-cli-win-arm64.exe package.json" + "linux-x64": "npm run build && pkg -t node18-linux-x64 -o build/appwrite-cli-linux-x64 package.json", + "linux-arm64": "npm run build && pkg -t node18-linux-arm64 -o build/appwrite-cli-linux-arm64 package.json", + "mac-x64": "npm run build && pkg -t node18-macos-x64 -o build/appwrite-cli-darwin-x64 package.json", + "mac-arm64": "npm run build && pkg -t node18-macos-arm64 -o build/appwrite-cli-darwin-arm64 package.json", + "windows-x64": "npm run build && pkg -t node18-win-x64 -o build/appwrite-cli-win-x64.exe package.json", + "windows-arm64": "npm run build && pkg -t node18-win-arm64 -o build/appwrite-cli-win-arm64.exe package.json" }, "dependencies": { "undici": "^5.28.2", @@ -39,12 +42,18 @@ "dotenv": "^16.4.5" }, "devDependencies": { - "@yao-pkg/pkg": "^6.9.0" + "@yao-pkg/pkg": "^6.9.0", + "@types/node": "^18.19.0", + "@types/inquirer": "^8.2.10", + "@types/cli-progress": "^3.11.5", + "@types/tar": "^6.1.11", + "@types/json-bigint": "^1.0.4", + "typescript": "^5.3.3" }, "pkg": { "scripts": [ - "index.js", - "lib/**/*.js" + "dist/index.js", + "dist/lib/**/*.js" ] } } diff --git a/scoop/appwrite.config.json b/scoop/appwrite.config.json index 298461ab..257a560d 100644 --- a/scoop/appwrite.config.json +++ b/scoop/appwrite.config.json @@ -1,12 +1,12 @@ { "$schema": "https://raw.githubusercontent.com/ScoopInstaller/Scoop/master/schema.json", - "version": "12.0.1", + "version": "13.0.0-rc.1", "description": "The Appwrite CLI is a command-line application that allows you to interact with Appwrite and perform server-side tasks using your terminal.", "homepage": "https://github.com/appwrite/sdk-for-cli", "license": "BSD-3-Clause", "architecture": { "64bit": { - "url": "https://github.com/appwrite/sdk-for-cli/releases/download/12.0.1/appwrite-cli-win-x64.exe", + "url": "https://github.com/appwrite/sdk-for-cli/releases/download/13.0.0-rc.1/appwrite-cli-win-x64.exe", "bin": [ [ "appwrite-cli-win-x64.exe", @@ -15,7 +15,7 @@ ] }, "arm64": { - "url": "https://github.com/appwrite/sdk-for-cli/releases/download/12.0.1/appwrite-cli-win-arm64.exe", + "url": "https://github.com/appwrite/sdk-for-cli/releases/download/13.0.0-rc.1/appwrite-cli-win-arm64.exe", "bin": [ [ "appwrite-cli-win-arm64.exe", diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 00000000..ce8e4dac --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,30 @@ +{ + "compilerOptions": { + "target": "ES2020", + "module": "commonjs", + "lib": ["ES2020"], + "outDir": "./dist", + "rootDir": "./", + "strict": false, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "resolveJsonModule": true, + "declaration": true, + "declarationMap": true, + "sourceMap": true, + "moduleResolution": "node", + "allowSyntheticDefaultImports": true, + "types": ["node"], + "noEmitOnError": false, + "noImplicitAny": false + }, + "include": [ + "**/*.ts" + ], + "exclude": [ + "node_modules", + "dist", + "build" + ] +}