From 13312b5463dd8dd136cb2f319f570186cae86b3d Mon Sep 17 00:00:00 2001 From: Torsten Dittmann Date: Wed, 3 Jul 2024 17:12:48 +0200 Subject: [PATCH] feat: 1.6.x preview --- README.md | 4 +- docs/examples/functions/create-build.md | 2 +- docs/examples/functions/create-execution.md | 1 + docs/examples/functions/create.md | 1 + docs/examples/functions/delete-execution.md | 3 + .../functions/update-deployment-build.md | 3 + docs/examples/functions/update.md | 1 + docs/examples/projects/create-j-w-t.md | 4 + docs/examples/projects/update-mock-numbers.md | 3 + .../projects/update-session-alerts.md | 3 + docs/examples/users/create-j-w-t.md | 4 + docs/examples/vcs/get-repository-contents.md | 4 + index.js | 41 +- install.ps1 | 2 +- install.sh | 2 +- lib/client.js | 16 +- lib/commands/account.js | 458 +++-- lib/commands/assistant.js | 13 +- lib/commands/avatars.js | 172 +- lib/commands/console.js | 13 +- lib/commands/databases.js | 517 ++++-- lib/commands/deploy.js | 940 ---------- lib/commands/functions.js | 410 +++-- lib/commands/generic.js | 260 ++- lib/commands/graphql.js | 22 +- lib/commands/health.js | 211 ++- lib/commands/init.js | 405 +++-- lib/commands/locale.js | 76 +- lib/commands/messaging.js | 490 ++++-- lib/commands/migrations.js | 148 +- lib/commands/project.js | 58 +- lib/commands/projects.js | 593 +++++-- lib/commands/proxy.js | 49 +- lib/commands/pull.js | 231 +++ lib/commands/push.js | 1518 +++++++++++++++++ lib/commands/run.js | 282 +++ lib/commands/storage.js | 236 ++- lib/commands/teams.js | 152 +- lib/commands/users.js | 458 +++-- lib/commands/vcs.js | 131 +- lib/config.js | 208 ++- lib/emulation/docker.js | 187 ++ lib/emulation/utils.js | 177 ++ lib/id.js | 30 + lib/paginate.js | 3 +- lib/parser.js | 81 +- lib/questions.js | 532 +++++- lib/sdks.js | 2 +- lib/spinner.js | 103 ++ lib/utils.js | 246 ++- lib/validations.js | 17 + package.json | 6 +- 52 files changed, 6984 insertions(+), 2545 deletions(-) create mode 100644 docs/examples/functions/delete-execution.md create mode 100644 docs/examples/functions/update-deployment-build.md create mode 100644 docs/examples/projects/create-j-w-t.md create mode 100644 docs/examples/projects/update-mock-numbers.md create mode 100644 docs/examples/projects/update-session-alerts.md create mode 100644 docs/examples/users/create-j-w-t.md create mode 100644 docs/examples/vcs/get-repository-contents.md delete mode 100644 lib/commands/deploy.js create mode 100644 lib/commands/pull.js create mode 100644 lib/commands/push.js create mode 100644 lib/commands/run.js create mode 100644 lib/emulation/docker.js create mode 100644 lib/emulation/utils.js create mode 100644 lib/id.js create mode 100644 lib/spinner.js create mode 100644 lib/validations.js diff --git a/README.md b/README.md index c9568fb..883bc89 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,12 @@ # Appwrite Command Line SDK ![License](https://img.shields.io/github/license/appwrite/sdk-for-cli.svg?style=flat-square) -![Version](https://img.shields.io/badge/api%20version-1.5.6-blue.svg?style=flat-square) +![Version](https://img.shields.io/badge/api%20version-1.5.7-blue.svg?style=flat-square) [![Build Status](https://img.shields.io/travis/com/appwrite/sdk-generator?style=flat-square)](https://travis-ci.com/appwrite/sdk-generator) [![Twitter Account](https://img.shields.io/twitter/follow/appwrite?color=00acee&label=twitter&style=flat-square)](https://twitter.com/appwrite) [![Discord](https://img.shields.io/discord/564160730845151244?label=discord&style=flat-square)](https://appwrite.io/discord) -**This SDK is compatible with Appwrite server version 1.5.x. For older versions, please check [previous releases](https://github.com/appwrite/sdk-for-cli/releases).** +**This SDK is compatible with Appwrite server version 1.6.x. For older versions, please check [previous releases](https://github.com/appwrite/sdk-for-cli/releases).** Appwrite is an open-source backend as a service server that abstract and simplify complex and repetitive development tasks behind a very simple to use REST API. Appwrite aims to help you develop your apps faster and in a more secure way. Use the Command Line SDK to integrate your app with the Appwrite server to easily start interacting with all of Appwrite backend APIs and tools. For full API documentation and tutorials go to [https://appwrite.io/docs](https://appwrite.io/docs) diff --git a/docs/examples/functions/create-build.md b/docs/examples/functions/create-build.md index 98d087b..5a99f7a 100644 --- a/docs/examples/functions/create-build.md +++ b/docs/examples/functions/create-build.md @@ -1,4 +1,4 @@ appwrite functions createBuild \ --functionId \ --deploymentId \ - --buildId + diff --git a/docs/examples/functions/create-execution.md b/docs/examples/functions/create-execution.md index 1efb701..febe88c 100644 --- a/docs/examples/functions/create-execution.md +++ b/docs/examples/functions/create-execution.md @@ -5,3 +5,4 @@ appwrite functions createExecution \ + diff --git a/docs/examples/functions/create.md b/docs/examples/functions/create.md index cfc3c9c..c75658e 100644 --- a/docs/examples/functions/create.md +++ b/docs/examples/functions/create.md @@ -19,3 +19,4 @@ appwrite functions create \ + diff --git a/docs/examples/functions/delete-execution.md b/docs/examples/functions/delete-execution.md new file mode 100644 index 0000000..2926b5a --- /dev/null +++ b/docs/examples/functions/delete-execution.md @@ -0,0 +1,3 @@ +appwrite functions deleteExecution \ + --functionId \ + --executionId diff --git a/docs/examples/functions/update-deployment-build.md b/docs/examples/functions/update-deployment-build.md new file mode 100644 index 0000000..ddaf1e5 --- /dev/null +++ b/docs/examples/functions/update-deployment-build.md @@ -0,0 +1,3 @@ +appwrite functions updateDeploymentBuild \ + --functionId \ + --deploymentId diff --git a/docs/examples/functions/update.md b/docs/examples/functions/update.md index 6f42584..8bad859 100644 --- a/docs/examples/functions/update.md +++ b/docs/examples/functions/update.md @@ -15,3 +15,4 @@ appwrite functions update \ + diff --git a/docs/examples/projects/create-j-w-t.md b/docs/examples/projects/create-j-w-t.md new file mode 100644 index 0000000..d703d36 --- /dev/null +++ b/docs/examples/projects/create-j-w-t.md @@ -0,0 +1,4 @@ +appwrite projects createJWT \ + --projectId \ + --scopes one two three \ + diff --git a/docs/examples/projects/update-mock-numbers.md b/docs/examples/projects/update-mock-numbers.md new file mode 100644 index 0000000..733cc16 --- /dev/null +++ b/docs/examples/projects/update-mock-numbers.md @@ -0,0 +1,3 @@ +appwrite projects updateMockNumbers \ + --projectId \ + --numbers one two three diff --git a/docs/examples/projects/update-session-alerts.md b/docs/examples/projects/update-session-alerts.md new file mode 100644 index 0000000..bd23b74 --- /dev/null +++ b/docs/examples/projects/update-session-alerts.md @@ -0,0 +1,3 @@ +appwrite projects updateSessionAlerts \ + --projectId \ + --alerts false diff --git a/docs/examples/users/create-j-w-t.md b/docs/examples/users/create-j-w-t.md new file mode 100644 index 0000000..220086b --- /dev/null +++ b/docs/examples/users/create-j-w-t.md @@ -0,0 +1,4 @@ +appwrite users createJWT \ + --userId \ + + diff --git a/docs/examples/vcs/get-repository-contents.md b/docs/examples/vcs/get-repository-contents.md new file mode 100644 index 0000000..7d378d7 --- /dev/null +++ b/docs/examples/vcs/get-repository-contents.md @@ -0,0 +1,4 @@ +appwrite vcs getRepositoryContents \ + --installationId \ + --providerRepositoryId \ + diff --git a/index.js b/index.js index 630b9b1..a1db573 100644 --- a/index.js +++ b/index.js @@ -10,9 +10,12 @@ const chalk = require("chalk"); const { version } = require("./package.json"); const { commandDescriptions, cliConfig } = require("./lib/parser"); const { client } = require("./lib/commands/generic"); -const { login, logout } = require("./lib/commands/generic"); +const inquirer = require("inquirer"); +const { login, logout, whoami, migrate, register } = require("./lib/commands/generic"); const { init } = require("./lib/commands/init"); -const { deploy } = require("./lib/commands/deploy"); +const { pull } = require("./lib/commands/pull"); +const { run } = require("./lib/commands/run"); +const { push } = require("./lib/commands/push"); const { account } = require("./lib/commands/account"); const { avatars } = require("./lib/commands/avatars"); const { assistant } = require("./lib/commands/assistant"); @@ -32,6 +35,8 @@ const { teams } = require("./lib/commands/teams"); const { users } = require("./lib/commands/users"); const { vcs } = require("./lib/commands/vcs"); +inquirer.registerPrompt('search-list', require('inquirer-search-list')); + program .description(commandDescriptions['main']) .configureHelp({ @@ -39,18 +44,40 @@ program sortSubcommands: true }) .version(version, "-v, --version") - .option("--verbose", "Show complete error log") - .option("--json", "Output in JSON format") + .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 list of ids for a giving 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(deploy) + .addCommand(pull) + .addCommand(push) + .addCommand(run) .addCommand(logout) .addCommand(account) .addCommand(avatars) @@ -72,5 +99,5 @@ program .addCommand(vcs) .addCommand(client) .parse(process.argv); - -process.stdout.columns = oldWidth; \ No newline at end of file + +process.stdout.columns = oldWidth; diff --git a/install.ps1 b/install.ps1 index 0c9310b..14ad4a8 100644 --- a/install.ps1 +++ b/install.ps1 @@ -85,8 +85,8 @@ function CleanUp { function InstallCompleted { Write-Host "[4/4] Finishing Installation ... " cleanup - Write-Host "🤘 May the force be with you." Write-Host "To get started with Appwrite CLI, please visit https://appwrite.io/docs/command-line" + Write-Host "As first step, you can login to your Appwrite account using 'appwrite login'" } diff --git a/install.sh b/install.sh index 70f8948..b870292 100644 --- a/install.sh +++ b/install.sh @@ -145,8 +145,8 @@ cleanup() { installCompleted() { echo "[4/4] Wrapping up installation ... " cleanup - printf "🤘 May the force be with you. \n" echo "🚀 To get started with Appwrite CLI, please visit https://appwrite.io/docs/command-line" + echo "As first step, you can login to your Appwrite account using 'appwrite login'" } # Installation Starts here diff --git a/lib/client.js b/lib/client.js index 1fd7c26..81e827f 100644 --- a/lib/client.js +++ b/lib/client.js @@ -4,10 +4,11 @@ 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 = { @@ -182,6 +183,11 @@ class Client { }, }), }); + + const warnings = response.headers.get('x-appwrite-warning'); + if (warnings) { + warnings.split(';').forEach((warning) => console.warn(warning)); + } } catch (error) { throw new AppwriteException(error.message); } @@ -194,6 +200,14 @@ class Client { } 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, json); } diff --git a/lib/commands/account.js b/lib/commands/account.js index d6f07c6..1de3c98 100644 --- a/lib/commands/account.js +++ b/lib/commands/account.js @@ -4,7 +4,7 @@ const tar = require("tar"); const ignore = require("ignore"); const { promisify } = require('util'); const libClient = require('../client.js'); -const { getAllFiles } = require('../utils.js'); +const { getAllFiles, showConsoleLink } = require('../utils.js'); const { Command } = require('commander'); const { sdkForProject, sdkForConsole } = require('../sdks') const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log } = require('../parser') @@ -41,6 +41,7 @@ const account = new Command("account").description(commandDescriptions['account' /** * @typedef {Object} AccountGetRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -48,8 +49,9 @@ const account = new Command("account").description(commandDescriptions['account' /** * @param {AccountGetRequestParams} params */ -const accountGet = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountGet = async ({parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account'; let payload = {}; @@ -60,11 +62,16 @@ const accountGet = async ({ parseOutput = true, sdk = undefined}) => { }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('account', 'get'); + } else { + parse(response) + success() + } } - + return response; + } /** @@ -73,6 +80,7 @@ const accountGet = async ({ parseOutput = true, sdk = undefined}) => { * @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 */ @@ -80,8 +88,9 @@ const accountGet = async ({ parseOutput = true, sdk = undefined}) => { /** * @param {AccountCreateRequestParams} params */ -const accountCreate = async ({ userId, email, password, name, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountCreate = async ({userId,email,password,name,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account'; let payload = {}; if (typeof userId !== 'undefined') { @@ -107,12 +116,14 @@ const accountCreate = async ({ userId, email, password, name, parseOutput = true parse(response) success() } - + return response; + } /** * @typedef {Object} AccountDeleteRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -120,8 +131,9 @@ const accountCreate = async ({ userId, email, password, name, parseOutput = true /** * @param {AccountDeleteRequestParams} params */ -const accountDelete = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountDelete = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account'; let payload = {}; @@ -135,14 +147,16 @@ const accountDelete = async ({ parseOutput = true, sdk = undefined}) => { parse(response) success() } - + 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 */ @@ -150,8 +164,9 @@ const accountDelete = async ({ parseOutput = true, sdk = undefined}) => { /** * @param {AccountUpdateEmailRequestParams} params */ -const accountUpdateEmail = async ({ email, password, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountUpdateEmail = async ({email,password,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/email'; let payload = {}; if (typeof email !== 'undefined') { @@ -171,13 +186,15 @@ const accountUpdateEmail = async ({ email, password, parseOutput = true, sdk = u parse(response) success() } - + 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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -185,8 +202,9 @@ const accountUpdateEmail = async ({ email, password, parseOutput = true, sdk = u /** * @param {AccountListIdentitiesRequestParams} params */ -const accountListIdentities = async ({ queries, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountListIdentities = async ({queries,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/identities'; let payload = {}; if (typeof queries !== 'undefined') { @@ -203,13 +221,15 @@ const accountListIdentities = async ({ queries, parseOutput = true, sdk = undefi parse(response) success() } - + return response; + } /** * @typedef {Object} AccountDeleteIdentityRequestParams * @property {string} identityId Identity ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -217,8 +237,9 @@ const accountListIdentities = async ({ queries, parseOutput = true, sdk = undefi /** * @param {AccountDeleteIdentityRequestParams} params */ -const accountDeleteIdentity = async ({ identityId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountDeleteIdentity = async ({identityId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/identities/{identityId}'.replace('{identityId}', identityId); let payload = {}; @@ -232,12 +253,14 @@ const accountDeleteIdentity = async ({ identityId, parseOutput = true, sdk = und parse(response) success() } - + return response; + } /** * @typedef {Object} AccountCreateJWTRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -245,9 +268,10 @@ const accountDeleteIdentity = async ({ identityId, parseOutput = true, sdk = und /** * @param {AccountCreateJWTRequestParams} params */ -const accountCreateJWT = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; - let apiPath = '/account/jwt'; +const accountCreateJWT = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; + let apiPath = '/account/jwts'; let payload = {}; let response = undefined; @@ -260,13 +284,15 @@ const accountCreateJWT = async ({ parseOutput = true, sdk = undefined}) => { parse(response) success() } - + 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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -274,8 +300,9 @@ const accountCreateJWT = async ({ parseOutput = true, sdk = undefined}) => { /** * @param {AccountListLogsRequestParams} params */ -const accountListLogs = async ({ queries, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountListLogs = async ({queries,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/logs'; let payload = {}; if (typeof queries !== 'undefined') { @@ -292,13 +319,15 @@ const accountListLogs = async ({ queries, parseOutput = true, sdk = undefined}) parse(response) success() } - + return response; + } /** * @typedef {Object} AccountUpdateMFARequestParams * @property {boolean} mfa Enable or disable MFA. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -306,8 +335,9 @@ const accountListLogs = async ({ queries, parseOutput = true, sdk = undefined}) /** * @param {AccountUpdateMFARequestParams} params */ -const accountUpdateMFA = async ({ mfa, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountUpdateMFA = async ({mfa,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/mfa'; let payload = {}; if (typeof mfa !== 'undefined') { @@ -324,13 +354,15 @@ const accountUpdateMFA = async ({ mfa, parseOutput = true, sdk = undefined}) => parse(response) success() } - + return response; + } /** * @typedef {Object} AccountCreateMfaAuthenticatorRequestParams * @property {AuthenticatorType} type Type of authenticator. Must be 'totp' + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -338,8 +370,9 @@ const accountUpdateMFA = async ({ mfa, parseOutput = true, sdk = undefined}) => /** * @param {AccountCreateMfaAuthenticatorRequestParams} params */ -const accountCreateMfaAuthenticator = async ({ type, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountCreateMfaAuthenticator = async ({type,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/mfa/authenticators/{type}'.replace('{type}', type); let payload = {}; @@ -353,14 +386,16 @@ const accountCreateMfaAuthenticator = async ({ type, parseOutput = true, sdk = u parse(response) success() } - + 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 */ @@ -368,8 +403,9 @@ const accountCreateMfaAuthenticator = async ({ type, parseOutput = true, sdk = u /** * @param {AccountUpdateMfaAuthenticatorRequestParams} params */ -const accountUpdateMfaAuthenticator = async ({ type, otp, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountUpdateMfaAuthenticator = async ({type,otp,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/mfa/authenticators/{type}'.replace('{type}', type); let payload = {}; if (typeof otp !== 'undefined') { @@ -386,14 +422,16 @@ const accountUpdateMfaAuthenticator = async ({ type, otp, parseOutput = true, sd parse(response) success() } - + return response; + } /** * @typedef {Object} AccountDeleteMfaAuthenticatorRequestParams * @property {AuthenticatorType} type Type of authenticator. * @property {string} otp Valid verification token. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -401,8 +439,9 @@ const accountUpdateMfaAuthenticator = async ({ type, otp, parseOutput = true, sd /** * @param {AccountDeleteMfaAuthenticatorRequestParams} params */ -const accountDeleteMfaAuthenticator = async ({ type, otp, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountDeleteMfaAuthenticator = async ({type,otp,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/mfa/authenticators/{type}'.replace('{type}', type); let payload = {}; if (typeof otp !== 'undefined') { @@ -419,13 +458,15 @@ const accountDeleteMfaAuthenticator = async ({ type, otp, parseOutput = true, sd parse(response) success() } - + 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 */ @@ -433,8 +474,9 @@ const accountDeleteMfaAuthenticator = async ({ type, otp, parseOutput = true, sd /** * @param {AccountCreateMfaChallengeRequestParams} params */ -const accountCreateMfaChallenge = async ({ factor, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountCreateMfaChallenge = async ({factor,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/mfa/challenge'; let payload = {}; if (typeof factor !== 'undefined') { @@ -451,14 +493,16 @@ const accountCreateMfaChallenge = async ({ factor, parseOutput = true, sdk = und parse(response) success() } - + 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 */ @@ -466,8 +510,9 @@ const accountCreateMfaChallenge = async ({ factor, parseOutput = true, sdk = und /** * @param {AccountUpdateMfaChallengeRequestParams} params */ -const accountUpdateMfaChallenge = async ({ challengeId, otp, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountUpdateMfaChallenge = async ({challengeId,otp,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/mfa/challenge'; let payload = {}; if (typeof challengeId !== 'undefined') { @@ -487,12 +532,14 @@ const accountUpdateMfaChallenge = async ({ challengeId, otp, parseOutput = true, parse(response) success() } - + return response; + } /** * @typedef {Object} AccountListMfaFactorsRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -500,8 +547,9 @@ const accountUpdateMfaChallenge = async ({ challengeId, otp, parseOutput = true, /** * @param {AccountListMfaFactorsRequestParams} params */ -const accountListMfaFactors = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountListMfaFactors = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/mfa/factors'; let payload = {}; @@ -515,12 +563,14 @@ const accountListMfaFactors = async ({ parseOutput = true, sdk = undefined}) => parse(response) success() } - + return response; + } /** * @typedef {Object} AccountGetMfaRecoveryCodesRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -528,8 +578,9 @@ const accountListMfaFactors = async ({ parseOutput = true, sdk = undefined}) => /** * @param {AccountGetMfaRecoveryCodesRequestParams} params */ -const accountGetMfaRecoveryCodes = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountGetMfaRecoveryCodes = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/mfa/recovery-codes'; let payload = {}; @@ -543,12 +594,14 @@ const accountGetMfaRecoveryCodes = async ({ parseOutput = true, sdk = undefined} parse(response) success() } - + return response; + } /** * @typedef {Object} AccountCreateMfaRecoveryCodesRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -556,8 +609,9 @@ const accountGetMfaRecoveryCodes = async ({ parseOutput = true, sdk = undefined} /** * @param {AccountCreateMfaRecoveryCodesRequestParams} params */ -const accountCreateMfaRecoveryCodes = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountCreateMfaRecoveryCodes = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/mfa/recovery-codes'; let payload = {}; @@ -571,12 +625,14 @@ const accountCreateMfaRecoveryCodes = async ({ parseOutput = true, sdk = undefin parse(response) success() } - + return response; + } /** * @typedef {Object} AccountUpdateMfaRecoveryCodesRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -584,8 +640,9 @@ const accountCreateMfaRecoveryCodes = async ({ parseOutput = true, sdk = undefin /** * @param {AccountUpdateMfaRecoveryCodesRequestParams} params */ -const accountUpdateMfaRecoveryCodes = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountUpdateMfaRecoveryCodes = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/mfa/recovery-codes'; let payload = {}; @@ -599,13 +656,15 @@ const accountUpdateMfaRecoveryCodes = async ({ parseOutput = true, sdk = undefin parse(response) success() } - + return response; + } /** * @typedef {Object} AccountUpdateNameRequestParams * @property {string} name User name. Max length: 128 chars. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -613,8 +672,9 @@ const accountUpdateMfaRecoveryCodes = async ({ parseOutput = true, sdk = undefin /** * @param {AccountUpdateNameRequestParams} params */ -const accountUpdateName = async ({ name, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountUpdateName = async ({name,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/name'; let payload = {}; if (typeof name !== 'undefined') { @@ -631,14 +691,16 @@ const accountUpdateName = async ({ name, parseOutput = true, sdk = undefined}) = parse(response) success() } - + 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 */ @@ -646,8 +708,9 @@ const accountUpdateName = async ({ name, parseOutput = true, sdk = undefined}) = /** * @param {AccountUpdatePasswordRequestParams} params */ -const accountUpdatePassword = async ({ password, oldPassword, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountUpdatePassword = async ({password,oldPassword,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/password'; let payload = {}; if (typeof password !== 'undefined') { @@ -667,14 +730,16 @@ const accountUpdatePassword = async ({ password, oldPassword, parseOutput = true parse(response) success() } - + 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 */ @@ -682,8 +747,9 @@ const accountUpdatePassword = async ({ password, oldPassword, parseOutput = true /** * @param {AccountUpdatePhoneRequestParams} params */ -const accountUpdatePhone = async ({ phone, password, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountUpdatePhone = async ({phone,password,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/phone'; let payload = {}; if (typeof phone !== 'undefined') { @@ -703,12 +769,14 @@ const accountUpdatePhone = async ({ phone, password, parseOutput = true, sdk = u parse(response) success() } - + return response; + } /** * @typedef {Object} AccountGetPrefsRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -716,8 +784,9 @@ const accountUpdatePhone = async ({ phone, password, parseOutput = true, sdk = u /** * @param {AccountGetPrefsRequestParams} params */ -const accountGetPrefs = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountGetPrefs = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/prefs'; let payload = {}; @@ -731,13 +800,15 @@ const accountGetPrefs = async ({ parseOutput = true, sdk = undefined}) => { parse(response) success() } - + return response; + } /** * @typedef {Object} AccountUpdatePrefsRequestParams * @property {object} prefs Prefs key-value JSON object. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -745,8 +816,9 @@ const accountGetPrefs = async ({ parseOutput = true, sdk = undefined}) => { /** * @param {AccountUpdatePrefsRequestParams} params */ -const accountUpdatePrefs = async ({ prefs, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountUpdatePrefs = async ({prefs,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/prefs'; let payload = {}; if (typeof prefs !== 'undefined') { @@ -763,14 +835,16 @@ const accountUpdatePrefs = async ({ prefs, parseOutput = true, sdk = undefined}) parse(response) success() } - + 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 */ @@ -778,8 +852,9 @@ const accountUpdatePrefs = async ({ prefs, parseOutput = true, sdk = undefined}) /** * @param {AccountCreateRecoveryRequestParams} params */ -const accountCreateRecovery = async ({ email, url, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountCreateRecovery = async ({email,url,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/recovery'; let payload = {}; if (typeof email !== 'undefined') { @@ -799,8 +874,9 @@ const accountCreateRecovery = async ({ email, url, parseOutput = true, sdk = und parse(response) success() } - + return response; + } /** @@ -808,6 +884,7 @@ const accountCreateRecovery = async ({ email, url, parseOutput = true, sdk = und * @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 */ @@ -815,8 +892,9 @@ const accountCreateRecovery = async ({ email, url, parseOutput = true, sdk = und /** * @param {AccountUpdateRecoveryRequestParams} params */ -const accountUpdateRecovery = async ({ userId, secret, password, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountUpdateRecovery = async ({userId,secret,password,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/recovery'; let payload = {}; if (typeof userId !== 'undefined') { @@ -839,12 +917,14 @@ const accountUpdateRecovery = async ({ userId, secret, password, parseOutput = t parse(response) success() } - + return response; + } /** * @typedef {Object} AccountListSessionsRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -852,8 +932,9 @@ const accountUpdateRecovery = async ({ userId, secret, password, parseOutput = t /** * @param {AccountListSessionsRequestParams} params */ -const accountListSessions = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountListSessions = async ({parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/sessions'; let payload = {}; @@ -864,15 +945,21 @@ const accountListSessions = async ({ parseOutput = true, sdk = undefined}) => { }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('account', 'listSessions'); + } else { + parse(response) + success() + } } - + return response; + } /** * @typedef {Object} AccountDeleteSessionsRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -880,8 +967,9 @@ const accountListSessions = async ({ parseOutput = true, sdk = undefined}) => { /** * @param {AccountDeleteSessionsRequestParams} params */ -const accountDeleteSessions = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountDeleteSessions = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/sessions'; let payload = {}; @@ -895,12 +983,14 @@ const accountDeleteSessions = async ({ parseOutput = true, sdk = undefined}) => parse(response) success() } - + return response; + } /** * @typedef {Object} AccountCreateAnonymousSessionRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -908,8 +998,9 @@ const accountDeleteSessions = async ({ parseOutput = true, sdk = undefined}) => /** * @param {AccountCreateAnonymousSessionRequestParams} params */ -const accountCreateAnonymousSession = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountCreateAnonymousSession = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/sessions/anonymous'; let payload = {}; @@ -923,14 +1014,16 @@ const accountCreateAnonymousSession = async ({ parseOutput = true, sdk = undefin parse(response) success() } - + 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 */ @@ -938,8 +1031,9 @@ const accountCreateAnonymousSession = async ({ parseOutput = true, sdk = undefin /** * @param {AccountCreateEmailPasswordSessionRequestParams} params */ -const accountCreateEmailPasswordSession = async ({ email, password, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountCreateEmailPasswordSession = async ({email,password,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/sessions/email'; let payload = {}; if (typeof email !== 'undefined') { @@ -959,14 +1053,16 @@ const accountCreateEmailPasswordSession = async ({ email, password, parseOutput parse(response) success() } - + 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 */ @@ -974,8 +1070,9 @@ const accountCreateEmailPasswordSession = async ({ email, password, parseOutput /** * @param {AccountUpdateMagicURLSessionRequestParams} params */ -const accountUpdateMagicURLSession = async ({ userId, secret, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountUpdateMagicURLSession = async ({userId,secret,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/sessions/magic-url'; let payload = {}; if (typeof userId !== 'undefined') { @@ -995,8 +1092,9 @@ const accountUpdateMagicURLSession = async ({ userId, secret, parseOutput = true parse(response) success() } - + return response; + } /** @@ -1005,6 +1103,7 @@ const accountUpdateMagicURLSession = async ({ userId, secret, parseOutput = true * @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 */ @@ -1012,8 +1111,9 @@ const accountUpdateMagicURLSession = async ({ userId, secret, parseOutput = true /** * @param {AccountCreateOAuth2SessionRequestParams} params */ -const accountCreateOAuth2Session = async ({ provider, success, failure, scopes, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountCreateOAuth2Session = async ({provider,success,failure,scopes,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/sessions/oauth2/{provider}'.replace('{provider}', provider); let payload = {}; if (typeof success !== 'undefined') { @@ -1036,14 +1136,16 @@ const accountCreateOAuth2Session = async ({ provider, success, failure, scopes, parse(response) success() } - + 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 */ @@ -1051,8 +1153,9 @@ const accountCreateOAuth2Session = async ({ provider, success, failure, scopes, /** * @param {AccountUpdatePhoneSessionRequestParams} params */ -const accountUpdatePhoneSession = async ({ userId, secret, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountUpdatePhoneSession = async ({userId,secret,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/sessions/phone'; let payload = {}; if (typeof userId !== 'undefined') { @@ -1072,14 +1175,16 @@ const accountUpdatePhoneSession = async ({ userId, secret, parseOutput = true, s parse(response) success() } - + 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 */ @@ -1087,8 +1192,9 @@ const accountUpdatePhoneSession = async ({ userId, secret, parseOutput = true, s /** * @param {AccountCreateSessionRequestParams} params */ -const accountCreateSession = async ({ userId, secret, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountCreateSession = async ({userId,secret,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/sessions/token'; let payload = {}; if (typeof userId !== 'undefined') { @@ -1108,13 +1214,15 @@ const accountCreateSession = async ({ userId, secret, parseOutput = true, sdk = parse(response) success() } - + 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 */ @@ -1122,8 +1230,9 @@ const accountCreateSession = async ({ userId, secret, parseOutput = true, sdk = /** * @param {AccountGetSessionRequestParams} params */ -const accountGetSession = async ({ sessionId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountGetSession = async ({sessionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/sessions/{sessionId}'.replace('{sessionId}', sessionId); let payload = {}; @@ -1137,13 +1246,15 @@ const accountGetSession = async ({ sessionId, parseOutput = true, sdk = undefine parse(response) success() } - + 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 */ @@ -1151,8 +1262,9 @@ const accountGetSession = async ({ sessionId, parseOutput = true, sdk = undefine /** * @param {AccountUpdateSessionRequestParams} params */ -const accountUpdateSession = async ({ sessionId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountUpdateSession = async ({sessionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/sessions/{sessionId}'.replace('{sessionId}', sessionId); let payload = {}; @@ -1166,13 +1278,15 @@ const accountUpdateSession = async ({ sessionId, parseOutput = true, sdk = undef parse(response) success() } - + 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 */ @@ -1180,8 +1294,9 @@ const accountUpdateSession = async ({ sessionId, parseOutput = true, sdk = undef /** * @param {AccountDeleteSessionRequestParams} params */ -const accountDeleteSession = async ({ sessionId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountDeleteSession = async ({sessionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/sessions/{sessionId}'.replace('{sessionId}', sessionId); let payload = {}; @@ -1195,12 +1310,14 @@ const accountDeleteSession = async ({ sessionId, parseOutput = true, sdk = undef parse(response) success() } - + return response; + } /** * @typedef {Object} AccountUpdateStatusRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -1208,8 +1325,9 @@ const accountDeleteSession = async ({ sessionId, parseOutput = true, sdk = undef /** * @param {AccountUpdateStatusRequestParams} params */ -const accountUpdateStatus = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountUpdateStatus = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/status'; let payload = {}; @@ -1223,8 +1341,9 @@ const accountUpdateStatus = async ({ parseOutput = true, sdk = undefined}) => { parse(response) success() } - + return response; + } /** @@ -1232,6 +1351,7 @@ const accountUpdateStatus = async ({ parseOutput = true, sdk = undefined}) => { * @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 */ @@ -1239,8 +1359,9 @@ const accountUpdateStatus = async ({ parseOutput = true, sdk = undefined}) => { /** * @param {AccountCreatePushTargetRequestParams} params */ -const accountCreatePushTarget = async ({ targetId, identifier, providerId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountCreatePushTarget = async ({targetId,identifier,providerId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/targets/push'; let payload = {}; if (typeof targetId !== 'undefined') { @@ -1263,14 +1384,16 @@ const accountCreatePushTarget = async ({ targetId, identifier, providerId, parse parse(response) success() } - + 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 */ @@ -1278,8 +1401,9 @@ const accountCreatePushTarget = async ({ targetId, identifier, providerId, parse /** * @param {AccountUpdatePushTargetRequestParams} params */ -const accountUpdatePushTarget = async ({ targetId, identifier, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountUpdatePushTarget = async ({targetId,identifier,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/targets/{targetId}/push'.replace('{targetId}', targetId); let payload = {}; if (typeof identifier !== 'undefined') { @@ -1296,13 +1420,15 @@ const accountUpdatePushTarget = async ({ targetId, identifier, parseOutput = tru parse(response) success() } - + return response; + } /** * @typedef {Object} AccountDeletePushTargetRequestParams * @property {string} targetId Target ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -1310,8 +1436,9 @@ const accountUpdatePushTarget = async ({ targetId, identifier, parseOutput = tru /** * @param {AccountDeletePushTargetRequestParams} params */ -const accountDeletePushTarget = async ({ targetId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountDeletePushTarget = async ({targetId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/targets/{targetId}/push'.replace('{targetId}', targetId); let payload = {}; @@ -1325,8 +1452,9 @@ const accountDeletePushTarget = async ({ targetId, parseOutput = true, sdk = und parse(response) success() } - + return response; + } /** @@ -1334,6 +1462,7 @@ const accountDeletePushTarget = async ({ targetId, parseOutput = true, sdk = und * @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 {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 */ @@ -1341,8 +1470,9 @@ const accountDeletePushTarget = async ({ targetId, parseOutput = true, sdk = und /** * @param {AccountCreateEmailTokenRequestParams} params */ -const accountCreateEmailToken = async ({ userId, email, phrase, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountCreateEmailToken = async ({userId,email,phrase,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/tokens/email'; let payload = {}; if (typeof userId !== 'undefined') { @@ -1365,8 +1495,9 @@ const accountCreateEmailToken = async ({ userId, email, phrase, parseOutput = tr parse(response) success() } - + return response; + } /** @@ -1375,6 +1506,7 @@ const accountCreateEmailToken = async ({ userId, email, phrase, parseOutput = tr * @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 */ @@ -1382,8 +1514,9 @@ const accountCreateEmailToken = async ({ userId, email, phrase, parseOutput = tr /** * @param {AccountCreateMagicURLTokenRequestParams} params */ -const accountCreateMagicURLToken = async ({ userId, email, url, phrase, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountCreateMagicURLToken = async ({userId,email,url,phrase,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/tokens/magic-url'; let payload = {}; if (typeof userId !== 'undefined') { @@ -1409,8 +1542,9 @@ const accountCreateMagicURLToken = async ({ userId, email, url, phrase, parseOut parse(response) success() } - + return response; + } /** @@ -1419,6 +1553,7 @@ const accountCreateMagicURLToken = async ({ userId, email, url, phrase, parseOut * @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 */ @@ -1426,8 +1561,9 @@ const accountCreateMagicURLToken = async ({ userId, email, url, phrase, parseOut /** * @param {AccountCreateOAuth2TokenRequestParams} params */ -const accountCreateOAuth2Token = async ({ provider, success, failure, scopes, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountCreateOAuth2Token = async ({provider,success,failure,scopes,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/tokens/oauth2/{provider}'.replace('{provider}', provider); let payload = {}; if (typeof success !== 'undefined') { @@ -1450,14 +1586,16 @@ const accountCreateOAuth2Token = async ({ provider, success, failure, scopes, pa parse(response) success() } - + 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. * @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 */ @@ -1465,8 +1603,9 @@ const accountCreateOAuth2Token = async ({ provider, success, failure, scopes, pa /** * @param {AccountCreatePhoneTokenRequestParams} params */ -const accountCreatePhoneToken = async ({ userId, phone, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountCreatePhoneToken = async ({userId,phone,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/tokens/phone'; let payload = {}; if (typeof userId !== 'undefined') { @@ -1486,13 +1625,15 @@ const accountCreatePhoneToken = async ({ userId, phone, parseOutput = true, sdk parse(response) success() } - + 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 */ @@ -1500,8 +1641,9 @@ const accountCreatePhoneToken = async ({ userId, phone, parseOutput = true, sdk /** * @param {AccountCreateVerificationRequestParams} params */ -const accountCreateVerification = async ({ url, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountCreateVerification = async ({url,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/verification'; let payload = {}; if (typeof url !== 'undefined') { @@ -1518,14 +1660,16 @@ const accountCreateVerification = async ({ url, parseOutput = true, sdk = undefi parse(response) success() } - + 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 */ @@ -1533,8 +1677,9 @@ const accountCreateVerification = async ({ url, parseOutput = true, sdk = undefi /** * @param {AccountUpdateVerificationRequestParams} params */ -const accountUpdateVerification = async ({ userId, secret, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountUpdateVerification = async ({userId,secret,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/verification'; let payload = {}; if (typeof userId !== 'undefined') { @@ -1554,12 +1699,14 @@ const accountUpdateVerification = async ({ userId, secret, parseOutput = true, s parse(response) success() } - + return response; + } /** * @typedef {Object} AccountCreatePhoneVerificationRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -1567,8 +1714,9 @@ const accountUpdateVerification = async ({ userId, secret, parseOutput = true, s /** * @param {AccountCreatePhoneVerificationRequestParams} params */ -const accountCreatePhoneVerification = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountCreatePhoneVerification = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/verification/phone'; let payload = {}; @@ -1582,14 +1730,16 @@ const accountCreatePhoneVerification = async ({ parseOutput = true, sdk = undefi parse(response) success() } - + 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 */ @@ -1597,8 +1747,9 @@ const accountCreatePhoneVerification = async ({ parseOutput = true, sdk = undefi /** * @param {AccountUpdatePhoneVerificationRequestParams} params */ -const accountUpdatePhoneVerification = async ({ userId, secret, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const accountUpdatePhoneVerification = async ({userId,secret,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/account/verification/phone'; let payload = {}; if (typeof userId !== 'undefined') { @@ -1618,13 +1769,15 @@ const accountUpdatePhoneVerification = async ({ userId, secret, parseOutput = tr parse(response) success() } - + return response; + } account .command(`get`) .description(`Get the currently logged in user.`) + .option(`--console`, `Get the resource console url`) .action(actionRunner(accountGet)) account @@ -1685,7 +1838,7 @@ account account .command(`updateMfaAuthenticator`) - .description(`Verify an authenticator app after adding it using the [add authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) method. add `) + .description(`Verify an authenticator app after adding it using the [add authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) method.`) .requiredOption(`--type `, `Type of authenticator.`) .requiredOption(`--otp `, `Valid verification token.`) .action(actionRunner(accountUpdateMfaAuthenticator)) @@ -1779,6 +1932,7 @@ account account .command(`listSessions`) .description(`Get the list of active sessions across different devices for the currently logged in user.`) + .option(`--console`, `Get the resource console url`) .action(actionRunner(accountListSessions)) account @@ -1980,4 +2134,4 @@ module.exports = { accountUpdateVerification, accountCreatePhoneVerification, accountUpdatePhoneVerification -}; \ No newline at end of file +}; diff --git a/lib/commands/assistant.js b/lib/commands/assistant.js index 1d2300e..3a1da8a 100644 --- a/lib/commands/assistant.js +++ b/lib/commands/assistant.js @@ -4,7 +4,7 @@ const tar = require("tar"); const ignore = require("ignore"); const { promisify } = require('util'); const libClient = require('../client.js'); -const { getAllFiles } = require('../utils.js'); +const { getAllFiles, showConsoleLink } = require('../utils.js'); const { Command } = require('commander'); const { sdkForProject, sdkForConsole } = require('../sdks') const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log } = require('../parser') @@ -42,6 +42,7 @@ const assistant = new Command("assistant").description(commandDescriptions['assi /** * @typedef {Object} AssistantChatRequestParams * @property {string} prompt Prompt. A string containing questions asked to the AI assistant. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -49,8 +50,9 @@ const assistant = new Command("assistant").description(commandDescriptions['assi /** * @param {AssistantChatRequestParams} params */ -const assistantChat = async ({ prompt, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const assistantChat = async ({prompt,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/console/assistant'; let payload = {}; if (typeof prompt !== 'undefined') { @@ -67,8 +69,9 @@ const assistantChat = async ({ prompt, parseOutput = true, sdk = undefined}) => parse(response) success() } - + return response; + } assistant @@ -80,4 +83,4 @@ assistant module.exports = { assistant, assistantChat -}; \ No newline at end of file +}; diff --git a/lib/commands/avatars.js b/lib/commands/avatars.js index c40d77c..4d423d6 100644 --- a/lib/commands/avatars.js +++ b/lib/commands/avatars.js @@ -4,7 +4,7 @@ const tar = require("tar"); const ignore = require("ignore"); const { promisify } = require('util'); const libClient = require('../client.js'); -const { getAllFiles } = require('../utils.js'); +const { getAllFiles, showConsoleLink } = require('../utils.js'); const { Command } = require('commander'); const { sdkForProject, sdkForConsole } = require('../sdks') const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log } = require('../parser') @@ -45,6 +45,7 @@ const avatars = new Command("avatars").description(commandDescriptions['avatars' * @property {number} width Image width. Pass an integer between 0 to 2000. Defaults to 100. * @property {number} height Image height. Pass an integer between 0 to 2000. Defaults to 100. * @property {number} quality Image quality. Pass an integer between 0 to 100. Defaults to 100. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk * @property {string} destination @@ -53,8 +54,9 @@ const avatars = new Command("avatars").description(commandDescriptions['avatars' /** * @param {AvatarsGetBrowserRequestParams} params */ -const avatarsGetBrowser = async ({ code, width, height, quality, parseOutput = true, sdk = undefined, destination}) => { - let client = !sdk ? await sdkForProject() : sdk; +const avatarsGetBrowser = async ({code,width,height,quality,parseOutput = true, overrideForCli = false, sdk = undefined, destination}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/avatars/browsers/{code}'.replace('{code}', code); let payload = {}; if (typeof width !== 'undefined') { @@ -66,10 +68,12 @@ const avatarsGetBrowser = async ({ code, width, height, quality, parseOutput = t if (typeof quality !== 'undefined') { payload['quality'] = quality; } - payload['project'] = localConfig.getProject().projectId - payload['key'] = globalConfig.getKey(); - const queryParams = new URLSearchParams(payload); - apiPath = `${globalConfig.getEndpoint()}${apiPath}?${queryParams.toString()}`; + if (!overrideForCli) { + payload['project'] = localConfig.getProject().projectId + payload['key'] = globalConfig.getKey(); + const queryParams = new URLSearchParams(payload); + apiPath = `${globalConfig.getEndpoint()}${apiPath}?${queryParams.toString()}`; + } let response = undefined; @@ -77,14 +81,18 @@ const avatarsGetBrowser = async ({ code, width, height, quality, parseOutput = t 'content-type': 'application/json', }, payload, 'arraybuffer'); - fs.writeFileSync(destination, response); + if (overrideForCli) { + response = Buffer.from(response); + } + fs.writeFileSync(destination, response); if (parseOutput) { parse(response) success() } - + return response; + } /** @@ -93,6 +101,7 @@ const avatarsGetBrowser = async ({ code, width, height, quality, parseOutput = t * @property {number} width Image width. Pass an integer between 0 to 2000. Defaults to 100. * @property {number} height Image height. Pass an integer between 0 to 2000. Defaults to 100. * @property {number} quality Image quality. Pass an integer between 0 to 100. Defaults to 100. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk * @property {string} destination @@ -101,8 +110,9 @@ const avatarsGetBrowser = async ({ code, width, height, quality, parseOutput = t /** * @param {AvatarsGetCreditCardRequestParams} params */ -const avatarsGetCreditCard = async ({ code, width, height, quality, parseOutput = true, sdk = undefined, destination}) => { - let client = !sdk ? await sdkForProject() : sdk; +const avatarsGetCreditCard = async ({code,width,height,quality,parseOutput = true, overrideForCli = false, sdk = undefined, destination}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/avatars/credit-cards/{code}'.replace('{code}', code); let payload = {}; if (typeof width !== 'undefined') { @@ -114,10 +124,12 @@ const avatarsGetCreditCard = async ({ code, width, height, quality, parseOutput if (typeof quality !== 'undefined') { payload['quality'] = quality; } - payload['project'] = localConfig.getProject().projectId - payload['key'] = globalConfig.getKey(); - const queryParams = new URLSearchParams(payload); - apiPath = `${globalConfig.getEndpoint()}${apiPath}?${queryParams.toString()}`; + if (!overrideForCli) { + payload['project'] = localConfig.getProject().projectId + payload['key'] = globalConfig.getKey(); + const queryParams = new URLSearchParams(payload); + apiPath = `${globalConfig.getEndpoint()}${apiPath}?${queryParams.toString()}`; + } let response = undefined; @@ -125,19 +137,24 @@ const avatarsGetCreditCard = async ({ code, width, height, quality, parseOutput 'content-type': 'application/json', }, payload, 'arraybuffer'); - fs.writeFileSync(destination, response); + if (overrideForCli) { + response = Buffer.from(response); + } + fs.writeFileSync(destination, response); if (parseOutput) { parse(response) success() } - + return response; + } /** * @typedef {Object} AvatarsGetFaviconRequestParams * @property {string} url Website URL which you want to fetch the favicon from. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk * @property {string} destination @@ -146,17 +163,20 @@ const avatarsGetCreditCard = async ({ code, width, height, quality, parseOutput /** * @param {AvatarsGetFaviconRequestParams} params */ -const avatarsGetFavicon = async ({ url, parseOutput = true, sdk = undefined, destination}) => { - let client = !sdk ? await sdkForProject() : sdk; +const avatarsGetFavicon = async ({url,parseOutput = true, overrideForCli = false, sdk = undefined, destination}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/avatars/favicon'; let payload = {}; if (typeof url !== 'undefined') { payload['url'] = url; } - payload['project'] = localConfig.getProject().projectId - payload['key'] = globalConfig.getKey(); - const queryParams = new URLSearchParams(payload); - apiPath = `${globalConfig.getEndpoint()}${apiPath}?${queryParams.toString()}`; + if (!overrideForCli) { + payload['project'] = localConfig.getProject().projectId + payload['key'] = globalConfig.getKey(); + const queryParams = new URLSearchParams(payload); + apiPath = `${globalConfig.getEndpoint()}${apiPath}?${queryParams.toString()}`; + } let response = undefined; @@ -164,14 +184,18 @@ const avatarsGetFavicon = async ({ url, parseOutput = true, sdk = undefined, des 'content-type': 'application/json', }, payload, 'arraybuffer'); - fs.writeFileSync(destination, response); + if (overrideForCli) { + response = Buffer.from(response); + } + fs.writeFileSync(destination, response); if (parseOutput) { parse(response) success() } - + return response; + } /** @@ -180,6 +204,7 @@ const avatarsGetFavicon = async ({ url, parseOutput = true, sdk = undefined, des * @property {number} width Image width. Pass an integer between 0 to 2000. Defaults to 100. * @property {number} height Image height. Pass an integer between 0 to 2000. Defaults to 100. * @property {number} quality Image quality. Pass an integer between 0 to 100. Defaults to 100. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk * @property {string} destination @@ -188,8 +213,9 @@ const avatarsGetFavicon = async ({ url, parseOutput = true, sdk = undefined, des /** * @param {AvatarsGetFlagRequestParams} params */ -const avatarsGetFlag = async ({ code, width, height, quality, parseOutput = true, sdk = undefined, destination}) => { - let client = !sdk ? await sdkForProject() : sdk; +const avatarsGetFlag = async ({code,width,height,quality,parseOutput = true, overrideForCli = false, sdk = undefined, destination}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/avatars/flags/{code}'.replace('{code}', code); let payload = {}; if (typeof width !== 'undefined') { @@ -201,10 +227,12 @@ const avatarsGetFlag = async ({ code, width, height, quality, parseOutput = true if (typeof quality !== 'undefined') { payload['quality'] = quality; } - payload['project'] = localConfig.getProject().projectId - payload['key'] = globalConfig.getKey(); - const queryParams = new URLSearchParams(payload); - apiPath = `${globalConfig.getEndpoint()}${apiPath}?${queryParams.toString()}`; + if (!overrideForCli) { + payload['project'] = localConfig.getProject().projectId + payload['key'] = globalConfig.getKey(); + const queryParams = new URLSearchParams(payload); + apiPath = `${globalConfig.getEndpoint()}${apiPath}?${queryParams.toString()}`; + } let response = undefined; @@ -212,14 +240,18 @@ const avatarsGetFlag = async ({ code, width, height, quality, parseOutput = true 'content-type': 'application/json', }, payload, 'arraybuffer'); - fs.writeFileSync(destination, response); + if (overrideForCli) { + response = Buffer.from(response); + } + fs.writeFileSync(destination, response); if (parseOutput) { parse(response) success() } - + return response; + } /** @@ -227,6 +259,7 @@ const avatarsGetFlag = async ({ code, width, height, quality, parseOutput = true * @property {string} url Image URL which you want to crop. * @property {number} width Resize preview image width, Pass an integer between 0 to 2000. Defaults to 400. * @property {number} height Resize preview image height, Pass an integer between 0 to 2000. Defaults to 400. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk * @property {string} destination @@ -235,8 +268,9 @@ const avatarsGetFlag = async ({ code, width, height, quality, parseOutput = true /** * @param {AvatarsGetImageRequestParams} params */ -const avatarsGetImage = async ({ url, width, height, parseOutput = true, sdk = undefined, destination}) => { - let client = !sdk ? await sdkForProject() : sdk; +const avatarsGetImage = async ({url,width,height,parseOutput = true, overrideForCli = false, sdk = undefined, destination}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/avatars/image'; let payload = {}; if (typeof url !== 'undefined') { @@ -248,10 +282,12 @@ const avatarsGetImage = async ({ url, width, height, parseOutput = true, sdk = u if (typeof height !== 'undefined') { payload['height'] = height; } - payload['project'] = localConfig.getProject().projectId - payload['key'] = globalConfig.getKey(); - const queryParams = new URLSearchParams(payload); - apiPath = `${globalConfig.getEndpoint()}${apiPath}?${queryParams.toString()}`; + if (!overrideForCli) { + payload['project'] = localConfig.getProject().projectId + payload['key'] = globalConfig.getKey(); + const queryParams = new URLSearchParams(payload); + apiPath = `${globalConfig.getEndpoint()}${apiPath}?${queryParams.toString()}`; + } let response = undefined; @@ -259,14 +295,18 @@ const avatarsGetImage = async ({ url, width, height, parseOutput = true, sdk = u 'content-type': 'application/json', }, payload, 'arraybuffer'); - fs.writeFileSync(destination, response); + if (overrideForCli) { + response = Buffer.from(response); + } + fs.writeFileSync(destination, response); if (parseOutput) { parse(response) success() } - + return response; + } /** @@ -275,6 +315,7 @@ const avatarsGetImage = async ({ url, width, height, parseOutput = true, sdk = u * @property {number} width Image width. Pass an integer between 0 to 2000. Defaults to 100. * @property {number} height Image height. Pass an integer between 0 to 2000. Defaults to 100. * @property {string} background Changes background color. By default a random color will be picked and stay will persistent to the given name. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk * @property {string} destination @@ -283,8 +324,9 @@ const avatarsGetImage = async ({ url, width, height, parseOutput = true, sdk = u /** * @param {AvatarsGetInitialsRequestParams} params */ -const avatarsGetInitials = async ({ name, width, height, background, parseOutput = true, sdk = undefined, destination}) => { - let client = !sdk ? await sdkForProject() : sdk; +const avatarsGetInitials = async ({name,width,height,background,parseOutput = true, overrideForCli = false, sdk = undefined, destination}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/avatars/initials'; let payload = {}; if (typeof name !== 'undefined') { @@ -299,10 +341,12 @@ const avatarsGetInitials = async ({ name, width, height, background, parseOutput if (typeof background !== 'undefined') { payload['background'] = background; } - payload['project'] = localConfig.getProject().projectId - payload['key'] = globalConfig.getKey(); - const queryParams = new URLSearchParams(payload); - apiPath = `${globalConfig.getEndpoint()}${apiPath}?${queryParams.toString()}`; + if (!overrideForCli) { + payload['project'] = localConfig.getProject().projectId + payload['key'] = globalConfig.getKey(); + const queryParams = new URLSearchParams(payload); + apiPath = `${globalConfig.getEndpoint()}${apiPath}?${queryParams.toString()}`; + } let response = undefined; @@ -310,14 +354,18 @@ const avatarsGetInitials = async ({ name, width, height, background, parseOutput 'content-type': 'application/json', }, payload, 'arraybuffer'); - fs.writeFileSync(destination, response); + if (overrideForCli) { + response = Buffer.from(response); + } + fs.writeFileSync(destination, response); if (parseOutput) { parse(response) success() } - + return response; + } /** @@ -326,6 +374,7 @@ const avatarsGetInitials = async ({ name, width, height, background, parseOutput * @property {number} size QR code size. Pass an integer between 1 to 1000. Defaults to 400. * @property {number} margin Margin from edge. Pass an integer between 0 to 10. Defaults to 1. * @property {boolean} download Return resulting image with 'Content-Disposition: attachment ' headers for the browser to start downloading it. Pass 0 for no header, or 1 for otherwise. Default value is set to 0. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk * @property {string} destination @@ -334,8 +383,9 @@ const avatarsGetInitials = async ({ name, width, height, background, parseOutput /** * @param {AvatarsGetQRRequestParams} params */ -const avatarsGetQR = async ({ text, size, margin, download, parseOutput = true, sdk = undefined, destination}) => { - let client = !sdk ? await sdkForProject() : sdk; +const avatarsGetQR = async ({text,size,margin,download,parseOutput = true, overrideForCli = false, sdk = undefined, destination}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/avatars/qr'; let payload = {}; if (typeof text !== 'undefined') { @@ -350,10 +400,12 @@ const avatarsGetQR = async ({ text, size, margin, download, parseOutput = true, if (typeof download !== 'undefined') { payload['download'] = download; } - payload['project'] = localConfig.getProject().projectId - payload['key'] = globalConfig.getKey(); - const queryParams = new URLSearchParams(payload); - apiPath = `${globalConfig.getEndpoint()}${apiPath}?${queryParams.toString()}`; + if (!overrideForCli) { + payload['project'] = localConfig.getProject().projectId + payload['key'] = globalConfig.getKey(); + const queryParams = new URLSearchParams(payload); + apiPath = `${globalConfig.getEndpoint()}${apiPath}?${queryParams.toString()}`; + } let response = undefined; @@ -361,14 +413,18 @@ const avatarsGetQR = async ({ text, size, margin, download, parseOutput = true, 'content-type': 'application/json', }, payload, 'arraybuffer'); - fs.writeFileSync(destination, response); + if (overrideForCli) { + response = Buffer.from(response); + } + fs.writeFileSync(destination, response); if (parseOutput) { parse(response) success() } - + return response; + } avatars @@ -446,4 +502,4 @@ module.exports = { avatarsGetImage, avatarsGetInitials, avatarsGetQR -}; \ No newline at end of file +}; diff --git a/lib/commands/console.js b/lib/commands/console.js index 7c894ff..ef46397 100644 --- a/lib/commands/console.js +++ b/lib/commands/console.js @@ -4,7 +4,7 @@ const tar = require("tar"); const ignore = require("ignore"); const { promisify } = require('util'); const libClient = require('../client.js'); -const { getAllFiles } = require('../utils.js'); +const { getAllFiles, showConsoleLink } = require('../utils.js'); const { Command } = require('commander'); const { sdkForProject, sdkForConsole } = require('../sdks') const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log } = require('../parser') @@ -41,6 +41,7 @@ const console = new Command("console").description(commandDescriptions['console' /** * @typedef {Object} ConsoleVariablesRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -48,8 +49,9 @@ const console = new Command("console").description(commandDescriptions['console' /** * @param {ConsoleVariablesRequestParams} params */ -const consoleVariables = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const consoleVariables = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/console/variables'; let payload = {}; @@ -63,8 +65,9 @@ const consoleVariables = async ({ parseOutput = true, sdk = undefined}) => { parse(response) success() } - + return response; + } console @@ -75,4 +78,4 @@ console module.exports = { console, consoleVariables -}; \ No newline at end of file +}; diff --git a/lib/commands/databases.js b/lib/commands/databases.js index 80aa3b4..d2b989b 100644 --- a/lib/commands/databases.js +++ b/lib/commands/databases.js @@ -4,7 +4,7 @@ const tar = require("tar"); const ignore = require("ignore"); const { promisify } = require('util'); const libClient = require('../client.js'); -const { getAllFiles } = require('../utils.js'); +const { getAllFiles, showConsoleLink } = require('../utils.js'); const { Command } = require('commander'); const { sdkForProject, sdkForConsole } = require('../sdks') const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log } = require('../parser') @@ -43,6 +43,7 @@ const databases = new Command("databases").description(commandDescriptions['data * @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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -50,8 +51,9 @@ const databases = new Command("databases").description(commandDescriptions['data /** * @param {DatabasesListRequestParams} params */ -const databasesList = async ({ queries, search, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesList = async ({queries,search,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases'; let payload = {}; if (typeof queries !== 'undefined') { @@ -68,11 +70,16 @@ const databasesList = async ({ queries, search, parseOutput = true, sdk = undefi }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('databases', 'list'); + } else { + parse(response) + success() + } } - + return response; + } /** @@ -80,6 +87,7 @@ const databasesList = async ({ queries, search, parseOutput = true, sdk = undefi * @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 */ @@ -87,8 +95,9 @@ const databasesList = async ({ queries, search, parseOutput = true, sdk = undefi /** * @param {DatabasesCreateRequestParams} params */ -const databasesCreate = async ({ databaseId, name, enabled, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesCreate = async ({databaseId,name,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases'; let payload = {}; if (typeof databaseId !== 'undefined') { @@ -111,13 +120,15 @@ const databasesCreate = async ({ databaseId, name, enabled, parseOutput = true, parse(response) success() } - + return response; + } /** * @typedef {Object} DatabasesGetUsageRequestParams * @property {DatabaseUsageRange} range 'Date range. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -125,8 +136,9 @@ const databasesCreate = async ({ databaseId, name, enabled, parseOutput = true, /** * @param {DatabasesGetUsageRequestParams} params */ -const databasesGetUsage = async ({ range, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesGetUsage = async ({range,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/usage'; let payload = {}; if (typeof range !== 'undefined') { @@ -143,13 +155,15 @@ const databasesGetUsage = async ({ range, parseOutput = true, sdk = undefined}) parse(response) success() } - + return response; + } /** * @typedef {Object} DatabasesGetRequestParams * @property {string} databaseId Database ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -157,8 +171,9 @@ const databasesGetUsage = async ({ range, parseOutput = true, sdk = undefined}) /** * @param {DatabasesGetRequestParams} params */ -const databasesGet = async ({ databaseId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesGet = async ({databaseId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}'.replace('{databaseId}', databaseId); let payload = {}; @@ -169,11 +184,16 @@ const databasesGet = async ({ databaseId, parseOutput = true, sdk = undefined}) }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('databases', 'get', databaseId); + } else { + parse(response) + success() + } } - + return response; + } /** @@ -181,6 +201,7 @@ const databasesGet = async ({ databaseId, parseOutput = true, sdk = undefined}) * @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 */ @@ -188,8 +209,9 @@ const databasesGet = async ({ databaseId, parseOutput = true, sdk = undefined}) /** * @param {DatabasesUpdateRequestParams} params */ -const databasesUpdate = async ({ databaseId, name, enabled, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesUpdate = async ({databaseId,name,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}'.replace('{databaseId}', databaseId); let payload = {}; if (typeof name !== 'undefined') { @@ -209,13 +231,15 @@ const databasesUpdate = async ({ databaseId, name, enabled, parseOutput = true, parse(response) success() } - + return response; + } /** * @typedef {Object} DatabasesDeleteRequestParams * @property {string} databaseId Database ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -223,8 +247,9 @@ const databasesUpdate = async ({ databaseId, name, enabled, parseOutput = true, /** * @param {DatabasesDeleteRequestParams} params */ -const databasesDelete = async ({ databaseId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesDelete = async ({databaseId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}'.replace('{databaseId}', databaseId); let payload = {}; @@ -238,8 +263,9 @@ const databasesDelete = async ({ databaseId, parseOutput = true, sdk = undefined parse(response) success() } - + return response; + } /** @@ -247,6 +273,7 @@ const databasesDelete = async ({ databaseId, parseOutput = true, sdk = undefined * @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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -254,8 +281,9 @@ const databasesDelete = async ({ databaseId, parseOutput = true, sdk = undefined /** * @param {DatabasesListCollectionsRequestParams} params */ -const databasesListCollections = async ({ databaseId, queries, search, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesListCollections = async ({databaseId,queries,search,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections'.replace('{databaseId}', databaseId); let payload = {}; if (typeof queries !== 'undefined') { @@ -272,11 +300,16 @@ const databasesListCollections = async ({ databaseId, queries, search, parseOutp }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('databases', 'listCollections', databaseId); + } else { + parse(response) + success() + } } - + return response; + } /** @@ -287,6 +320,7 @@ const databasesListCollections = async ({ databaseId, queries, search, parseOutp * @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 */ @@ -294,8 +328,9 @@ const databasesListCollections = async ({ databaseId, queries, search, parseOutp /** * @param {DatabasesCreateCollectionRequestParams} params */ -const databasesCreateCollection = async ({ databaseId, collectionId, name, permissions, documentSecurity, enabled, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesCreateCollection = async ({databaseId,collectionId,name,permissions,documentSecurity,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections'.replace('{databaseId}', databaseId); let payload = {}; if (typeof collectionId !== 'undefined') { @@ -325,14 +360,16 @@ const databasesCreateCollection = async ({ databaseId, collectionId, name, permi parse(response) success() } - + 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 */ @@ -340,8 +377,9 @@ const databasesCreateCollection = async ({ databaseId, collectionId, name, permi /** * @param {DatabasesGetCollectionRequestParams} params */ -const databasesGetCollection = async ({ databaseId, collectionId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesGetCollection = async ({databaseId,collectionId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); let payload = {}; @@ -352,11 +390,16 @@ const databasesGetCollection = async ({ databaseId, collectionId, parseOutput = }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('databases', 'getCollection', databaseId, collectionId); + } else { + parse(response) + success() + } } - + return response; + } /** @@ -367,6 +410,7 @@ const databasesGetCollection = async ({ databaseId, collectionId, parseOutput = * @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 */ @@ -374,8 +418,9 @@ const databasesGetCollection = async ({ databaseId, collectionId, parseOutput = /** * @param {DatabasesUpdateCollectionRequestParams} params */ -const databasesUpdateCollection = async ({ databaseId, collectionId, name, permissions, documentSecurity, enabled, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesUpdateCollection = async ({databaseId,collectionId,name,permissions,documentSecurity,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); let payload = {}; if (typeof name !== 'undefined') { @@ -402,14 +447,16 @@ const databasesUpdateCollection = async ({ databaseId, collectionId, name, permi parse(response) success() } - + 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 */ @@ -417,8 +464,9 @@ const databasesUpdateCollection = async ({ databaseId, collectionId, name, permi /** * @param {DatabasesDeleteCollectionRequestParams} params */ -const databasesDeleteCollection = async ({ databaseId, collectionId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesDeleteCollection = async ({databaseId,collectionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); let payload = {}; @@ -432,8 +480,9 @@ const databasesDeleteCollection = async ({ databaseId, collectionId, parseOutput parse(response) success() } - + return response; + } /** @@ -441,6 +490,7 @@ const databasesDeleteCollection = async ({ databaseId, collectionId, parseOutput * @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, size, required, array, status, error + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -448,8 +498,9 @@ const databasesDeleteCollection = async ({ databaseId, collectionId, parseOutput /** * @param {DatabasesListAttributesRequestParams} params */ -const databasesListAttributes = async ({ databaseId, collectionId, queries, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesListAttributes = async ({databaseId,collectionId,queries,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); let payload = {}; if (typeof queries !== 'undefined') { @@ -463,11 +514,16 @@ const databasesListAttributes = async ({ databaseId, collectionId, queries, pars }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('databases', 'listAttributes', databaseId, collectionId); + } else { + parse(response) + success() + } } - + return response; + } /** @@ -478,6 +534,7 @@ const databasesListAttributes = async ({ databaseId, collectionId, queries, pars * @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 */ @@ -485,8 +542,9 @@ const databasesListAttributes = async ({ databaseId, collectionId, queries, pars /** * @param {DatabasesCreateBooleanAttributeRequestParams} params */ -const databasesCreateBooleanAttribute = async ({ databaseId, collectionId, key, required, xdefault, array, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesCreateBooleanAttribute = async ({databaseId,collectionId,key,required,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/boolean'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); let payload = {}; if (typeof key !== 'undefined') { @@ -512,8 +570,9 @@ const databasesCreateBooleanAttribute = async ({ databaseId, collectionId, key, parse(response) success() } - + return response; + } /** @@ -523,6 +582,7 @@ const databasesCreateBooleanAttribute = async ({ databaseId, collectionId, key, * @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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -530,8 +590,9 @@ const databasesCreateBooleanAttribute = async ({ databaseId, collectionId, key, /** * @param {DatabasesUpdateBooleanAttributeRequestParams} params */ -const databasesUpdateBooleanAttribute = async ({ databaseId, collectionId, key, required, xdefault, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesUpdateBooleanAttribute = async ({databaseId,collectionId,key,required,xdefault,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/boolean/{key}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{key}', key); let payload = {}; if (typeof required !== 'undefined') { @@ -551,8 +612,9 @@ const databasesUpdateBooleanAttribute = async ({ databaseId, collectionId, key, parse(response) success() } - + return response; + } /** @@ -563,6 +625,7 @@ const databasesUpdateBooleanAttribute = async ({ databaseId, collectionId, 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 */ @@ -570,8 +633,9 @@ const databasesUpdateBooleanAttribute = async ({ databaseId, collectionId, key, /** * @param {DatabasesCreateDatetimeAttributeRequestParams} params */ -const databasesCreateDatetimeAttribute = async ({ databaseId, collectionId, key, required, xdefault, array, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesCreateDatetimeAttribute = async ({databaseId,collectionId,key,required,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/datetime'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); let payload = {}; if (typeof key !== 'undefined') { @@ -597,8 +661,9 @@ const databasesCreateDatetimeAttribute = async ({ databaseId, collectionId, key, parse(response) success() } - + return response; + } /** @@ -608,6 +673,7 @@ const databasesCreateDatetimeAttribute = async ({ databaseId, collectionId, key, * @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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -615,8 +681,9 @@ const databasesCreateDatetimeAttribute = async ({ databaseId, collectionId, key, /** * @param {DatabasesUpdateDatetimeAttributeRequestParams} params */ -const databasesUpdateDatetimeAttribute = async ({ databaseId, collectionId, key, required, xdefault, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesUpdateDatetimeAttribute = async ({databaseId,collectionId,key,required,xdefault,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/datetime/{key}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{key}', key); let payload = {}; if (typeof required !== 'undefined') { @@ -636,8 +703,9 @@ const databasesUpdateDatetimeAttribute = async ({ databaseId, collectionId, key, parse(response) success() } - + return response; + } /** @@ -648,6 +716,7 @@ const databasesUpdateDatetimeAttribute = async ({ databaseId, collectionId, 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 */ @@ -655,8 +724,9 @@ const databasesUpdateDatetimeAttribute = async ({ databaseId, collectionId, key, /** * @param {DatabasesCreateEmailAttributeRequestParams} params */ -const databasesCreateEmailAttribute = async ({ databaseId, collectionId, key, required, xdefault, array, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesCreateEmailAttribute = async ({databaseId,collectionId,key,required,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/email'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); let payload = {}; if (typeof key !== 'undefined') { @@ -682,8 +752,9 @@ const databasesCreateEmailAttribute = async ({ databaseId, collectionId, key, re parse(response) success() } - + return response; + } /** @@ -693,6 +764,7 @@ const databasesCreateEmailAttribute = async ({ databaseId, collectionId, key, re * @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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -700,8 +772,9 @@ const databasesCreateEmailAttribute = async ({ databaseId, collectionId, key, re /** * @param {DatabasesUpdateEmailAttributeRequestParams} params */ -const databasesUpdateEmailAttribute = async ({ databaseId, collectionId, key, required, xdefault, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesUpdateEmailAttribute = async ({databaseId,collectionId,key,required,xdefault,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/email/{key}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{key}', key); let payload = {}; if (typeof required !== 'undefined') { @@ -721,8 +794,9 @@ const databasesUpdateEmailAttribute = async ({ databaseId, collectionId, key, re parse(response) success() } - + return response; + } /** @@ -734,6 +808,7 @@ const databasesUpdateEmailAttribute = async ({ databaseId, collectionId, key, re * @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 */ @@ -741,8 +816,9 @@ const databasesUpdateEmailAttribute = async ({ databaseId, collectionId, key, re /** * @param {DatabasesCreateEnumAttributeRequestParams} params */ -const databasesCreateEnumAttribute = async ({ databaseId, collectionId, key, elements, required, xdefault, array, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesCreateEnumAttribute = async ({databaseId,collectionId,key,elements,required,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/enum'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); let payload = {}; if (typeof key !== 'undefined') { @@ -772,8 +848,9 @@ const databasesCreateEnumAttribute = async ({ databaseId, collectionId, key, ele parse(response) success() } - + return response; + } /** @@ -784,6 +861,7 @@ const databasesCreateEnumAttribute = async ({ databaseId, collectionId, key, ele * @property {string[]} elements Array of elements in enumerated type. Uses length of longest element to determine size. Maximum of 100 elements are allowed, each 255 characters long. * @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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -791,8 +869,9 @@ const databasesCreateEnumAttribute = async ({ databaseId, collectionId, key, ele /** * @param {DatabasesUpdateEnumAttributeRequestParams} params */ -const databasesUpdateEnumAttribute = async ({ databaseId, collectionId, key, elements, required, xdefault, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesUpdateEnumAttribute = async ({databaseId,collectionId,key,elements,required,xdefault,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/enum/{key}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{key}', key); let payload = {}; elements = elements === true ? [] : elements; @@ -816,8 +895,9 @@ const databasesUpdateEnumAttribute = async ({ databaseId, collectionId, key, ele parse(response) success() } - + return response; + } /** @@ -830,6 +910,7 @@ const databasesUpdateEnumAttribute = async ({ databaseId, collectionId, key, ele * @property {number} max Maximum value to enforce on new documents * @property {number} 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 */ @@ -837,8 +918,9 @@ const databasesUpdateEnumAttribute = async ({ databaseId, collectionId, key, ele /** * @param {DatabasesCreateFloatAttributeRequestParams} params */ -const databasesCreateFloatAttribute = async ({ databaseId, collectionId, key, required, min, max, xdefault, array, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesCreateFloatAttribute = async ({databaseId,collectionId,key,required,min,max,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/float'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); let payload = {}; if (typeof key !== 'undefined') { @@ -870,8 +952,9 @@ const databasesCreateFloatAttribute = async ({ databaseId, collectionId, key, re parse(response) success() } - + return response; + } /** @@ -883,6 +966,7 @@ const databasesCreateFloatAttribute = async ({ databaseId, collectionId, key, re * @property {number} min Minimum value to enforce on new documents * @property {number} max Maximum value to enforce on new documents * @property {number} xdefault Default value for attribute when not provided. Cannot be set when attribute is required. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -890,8 +974,9 @@ const databasesCreateFloatAttribute = async ({ databaseId, collectionId, key, re /** * @param {DatabasesUpdateFloatAttributeRequestParams} params */ -const databasesUpdateFloatAttribute = async ({ databaseId, collectionId, key, required, min, max, xdefault, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesUpdateFloatAttribute = async ({databaseId,collectionId,key,required,min,max,xdefault,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/float/{key}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{key}', key); let payload = {}; if (typeof required !== 'undefined') { @@ -917,8 +1002,9 @@ const databasesUpdateFloatAttribute = async ({ databaseId, collectionId, key, re parse(response) success() } - + return response; + } /** @@ -931,6 +1017,7 @@ const databasesUpdateFloatAttribute = async ({ databaseId, collectionId, key, re * @property {number} max Maximum value to enforce on new documents * @property {number} 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 */ @@ -938,8 +1025,9 @@ const databasesUpdateFloatAttribute = async ({ databaseId, collectionId, key, re /** * @param {DatabasesCreateIntegerAttributeRequestParams} params */ -const databasesCreateIntegerAttribute = async ({ databaseId, collectionId, key, required, min, max, xdefault, array, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesCreateIntegerAttribute = async ({databaseId,collectionId,key,required,min,max,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/integer'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); let payload = {}; if (typeof key !== 'undefined') { @@ -971,8 +1059,9 @@ const databasesCreateIntegerAttribute = async ({ databaseId, collectionId, key, parse(response) success() } - + return response; + } /** @@ -984,6 +1073,7 @@ const databasesCreateIntegerAttribute = async ({ databaseId, collectionId, key, * @property {number} min Minimum value to enforce on new documents * @property {number} max Maximum value to enforce on new documents * @property {number} xdefault Default value for attribute when not provided. Cannot be set when attribute is required. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -991,8 +1081,9 @@ const databasesCreateIntegerAttribute = async ({ databaseId, collectionId, key, /** * @param {DatabasesUpdateIntegerAttributeRequestParams} params */ -const databasesUpdateIntegerAttribute = async ({ databaseId, collectionId, key, required, min, max, xdefault, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesUpdateIntegerAttribute = async ({databaseId,collectionId,key,required,min,max,xdefault,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/integer/{key}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{key}', key); let payload = {}; if (typeof required !== 'undefined') { @@ -1018,8 +1109,9 @@ const databasesUpdateIntegerAttribute = async ({ databaseId, collectionId, key, parse(response) success() } - + return response; + } /** @@ -1030,6 +1122,7 @@ const databasesUpdateIntegerAttribute = async ({ databaseId, collectionId, 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 */ @@ -1037,8 +1130,9 @@ const databasesUpdateIntegerAttribute = async ({ databaseId, collectionId, key, /** * @param {DatabasesCreateIpAttributeRequestParams} params */ -const databasesCreateIpAttribute = async ({ databaseId, collectionId, key, required, xdefault, array, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesCreateIpAttribute = async ({databaseId,collectionId,key,required,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/ip'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); let payload = {}; if (typeof key !== 'undefined') { @@ -1064,8 +1158,9 @@ const databasesCreateIpAttribute = async ({ databaseId, collectionId, key, requi parse(response) success() } - + return response; + } /** @@ -1075,6 +1170,7 @@ const databasesCreateIpAttribute = async ({ databaseId, collectionId, key, requi * @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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -1082,8 +1178,9 @@ const databasesCreateIpAttribute = async ({ databaseId, collectionId, key, requi /** * @param {DatabasesUpdateIpAttributeRequestParams} params */ -const databasesUpdateIpAttribute = async ({ databaseId, collectionId, key, required, xdefault, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesUpdateIpAttribute = async ({databaseId,collectionId,key,required,xdefault,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/ip/{key}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{key}', key); let payload = {}; if (typeof required !== 'undefined') { @@ -1103,8 +1200,9 @@ const databasesUpdateIpAttribute = async ({ databaseId, collectionId, key, requi parse(response) success() } - + return response; + } /** @@ -1117,6 +1215,7 @@ const databasesUpdateIpAttribute = async ({ databaseId, collectionId, key, requi * @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 */ @@ -1124,8 +1223,9 @@ const databasesUpdateIpAttribute = async ({ databaseId, collectionId, key, requi /** * @param {DatabasesCreateRelationshipAttributeRequestParams} params */ -const databasesCreateRelationshipAttribute = async ({ databaseId, collectionId, relatedCollectionId, type, twoWay, key, twoWayKey, onDelete, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesCreateRelationshipAttribute = async ({databaseId,collectionId,relatedCollectionId,type,twoWay,key,twoWayKey,onDelete,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/relationship'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); let payload = {}; if (typeof relatedCollectionId !== 'undefined') { @@ -1157,8 +1257,9 @@ const databasesCreateRelationshipAttribute = async ({ databaseId, collectionId, parse(response) success() } - + return response; + } /** @@ -1171,6 +1272,7 @@ const databasesCreateRelationshipAttribute = async ({ databaseId, collectionId, * @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 */ @@ -1178,8 +1280,9 @@ const databasesCreateRelationshipAttribute = async ({ databaseId, collectionId, /** * @param {DatabasesCreateStringAttributeRequestParams} params */ -const databasesCreateStringAttribute = async ({ databaseId, collectionId, key, size, required, xdefault, array, encrypt, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesCreateStringAttribute = async ({databaseId,collectionId,key,size,required,xdefault,array,encrypt,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/string'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); let payload = {}; if (typeof key !== 'undefined') { @@ -1211,8 +1314,9 @@ const databasesCreateStringAttribute = async ({ databaseId, collectionId, key, s parse(response) success() } - + return response; + } /** @@ -1222,6 +1326,7 @@ const databasesCreateStringAttribute = async ({ databaseId, collectionId, key, s * @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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -1229,8 +1334,9 @@ const databasesCreateStringAttribute = async ({ databaseId, collectionId, key, s /** * @param {DatabasesUpdateStringAttributeRequestParams} params */ -const databasesUpdateStringAttribute = async ({ databaseId, collectionId, key, required, xdefault, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesUpdateStringAttribute = async ({databaseId,collectionId,key,required,xdefault,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/string/{key}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{key}', key); let payload = {}; if (typeof required !== 'undefined') { @@ -1250,8 +1356,9 @@ const databasesUpdateStringAttribute = async ({ databaseId, collectionId, key, r parse(response) success() } - + return response; + } /** @@ -1262,6 +1369,7 @@ const databasesUpdateStringAttribute = async ({ databaseId, collectionId, key, r * @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 */ @@ -1269,8 +1377,9 @@ const databasesUpdateStringAttribute = async ({ databaseId, collectionId, key, r /** * @param {DatabasesCreateUrlAttributeRequestParams} params */ -const databasesCreateUrlAttribute = async ({ databaseId, collectionId, key, required, xdefault, array, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesCreateUrlAttribute = async ({databaseId,collectionId,key,required,xdefault,array,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/url'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); let payload = {}; if (typeof key !== 'undefined') { @@ -1296,8 +1405,9 @@ const databasesCreateUrlAttribute = async ({ databaseId, collectionId, key, requ parse(response) success() } - + return response; + } /** @@ -1307,6 +1417,7 @@ const databasesCreateUrlAttribute = async ({ databaseId, collectionId, key, requ * @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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -1314,8 +1425,9 @@ const databasesCreateUrlAttribute = async ({ databaseId, collectionId, key, requ /** * @param {DatabasesUpdateUrlAttributeRequestParams} params */ -const databasesUpdateUrlAttribute = async ({ databaseId, collectionId, key, required, xdefault, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesUpdateUrlAttribute = async ({databaseId,collectionId,key,required,xdefault,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/url/{key}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{key}', key); let payload = {}; if (typeof required !== 'undefined') { @@ -1335,8 +1447,9 @@ const databasesUpdateUrlAttribute = async ({ databaseId, collectionId, key, requ parse(response) success() } - + return response; + } /** @@ -1344,6 +1457,7 @@ const databasesUpdateUrlAttribute = async ({ databaseId, collectionId, key, requ * @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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -1351,8 +1465,9 @@ const databasesUpdateUrlAttribute = async ({ databaseId, collectionId, key, requ /** * @param {DatabasesGetAttributeRequestParams} params */ -const databasesGetAttribute = async ({ databaseId, collectionId, key, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesGetAttribute = async ({databaseId,collectionId,key,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/{key}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{key}', key); let payload = {}; @@ -1366,8 +1481,9 @@ const databasesGetAttribute = async ({ databaseId, collectionId, key, parseOutpu parse(response) success() } - + return response; + } /** @@ -1375,6 +1491,7 @@ const databasesGetAttribute = async ({ databaseId, collectionId, key, parseOutpu * @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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -1382,8 +1499,9 @@ const databasesGetAttribute = async ({ databaseId, collectionId, key, parseOutpu /** * @param {DatabasesDeleteAttributeRequestParams} params */ -const databasesDeleteAttribute = async ({ databaseId, collectionId, key, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesDeleteAttribute = async ({databaseId,collectionId,key,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/{key}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{key}', key); let payload = {}; @@ -1397,8 +1515,9 @@ const databasesDeleteAttribute = async ({ databaseId, collectionId, key, parseOu parse(response) success() } - + return response; + } /** @@ -1407,6 +1526,7 @@ const databasesDeleteAttribute = async ({ databaseId, collectionId, key, parseOu * @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 {RelationMutate} onDelete Constraints option + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -1414,8 +1534,9 @@ const databasesDeleteAttribute = async ({ databaseId, collectionId, key, parseOu /** * @param {DatabasesUpdateRelationshipAttributeRequestParams} params */ -const databasesUpdateRelationshipAttribute = async ({ databaseId, collectionId, key, onDelete, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesUpdateRelationshipAttribute = async ({databaseId,collectionId,key,onDelete,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/{key}/relationship'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{key}', key); let payload = {}; if (typeof onDelete !== 'undefined') { @@ -1432,8 +1553,9 @@ const databasesUpdateRelationshipAttribute = async ({ databaseId, collectionId, parse(response) success() } - + return response; + } /** @@ -1441,6 +1563,7 @@ const databasesUpdateRelationshipAttribute = async ({ databaseId, collectionId, * @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 {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -1448,8 +1571,9 @@ const databasesUpdateRelationshipAttribute = async ({ databaseId, collectionId, /** * @param {DatabasesListDocumentsRequestParams} params */ -const databasesListDocuments = async ({ databaseId, collectionId, queries, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesListDocuments = async ({databaseId,collectionId,queries,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); let payload = {}; if (typeof queries !== 'undefined') { @@ -1463,11 +1587,16 @@ const databasesListDocuments = async ({ databaseId, collectionId, queries, parse }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('databases', 'listDocuments', databaseId, collectionId); + } else { + parse(response) + success() + } } - + return response; + } /** @@ -1477,6 +1606,7 @@ const databasesListDocuments = async ({ databaseId, collectionId, queries, parse * @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 {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -1484,8 +1614,9 @@ const databasesListDocuments = async ({ databaseId, collectionId, queries, parse /** * @param {DatabasesCreateDocumentRequestParams} params */ -const databasesCreateDocument = async ({ databaseId, collectionId, documentId, data, permissions, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesCreateDocument = async ({databaseId,collectionId,documentId,data,permissions,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); let payload = {}; if (typeof documentId !== 'undefined') { @@ -1509,8 +1640,9 @@ const databasesCreateDocument = async ({ databaseId, collectionId, documentId, d parse(response) success() } - + return response; + } /** @@ -1519,6 +1651,7 @@ const databasesCreateDocument = async ({ databaseId, collectionId, documentId, d * @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 {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -1526,8 +1659,9 @@ const databasesCreateDocument = async ({ databaseId, collectionId, documentId, d /** * @param {DatabasesGetDocumentRequestParams} params */ -const databasesGetDocument = async ({ databaseId, collectionId, documentId, queries, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesGetDocument = async ({databaseId,collectionId,documentId,queries,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{documentId}', documentId); let payload = {}; if (typeof queries !== 'undefined') { @@ -1541,11 +1675,16 @@ const databasesGetDocument = async ({ databaseId, collectionId, documentId, quer }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('databases', 'getDocument', databaseId, collectionId, documentId); + } else { + parse(response) + success() + } } - + return response; + } /** @@ -1555,6 +1694,7 @@ const databasesGetDocument = async ({ databaseId, collectionId, documentId, quer * @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 {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -1562,8 +1702,9 @@ const databasesGetDocument = async ({ databaseId, collectionId, documentId, quer /** * @param {DatabasesUpdateDocumentRequestParams} params */ -const databasesUpdateDocument = async ({ databaseId, collectionId, documentId, data, permissions, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesUpdateDocument = async ({databaseId,collectionId,documentId,data,permissions,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{documentId}', documentId); let payload = {}; if (typeof data !== 'undefined') { @@ -1584,8 +1725,9 @@ const databasesUpdateDocument = async ({ databaseId, collectionId, documentId, d parse(response) success() } - + return response; + } /** @@ -1593,6 +1735,7 @@ const databasesUpdateDocument = async ({ databaseId, collectionId, documentId, d * @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 {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -1600,8 +1743,9 @@ const databasesUpdateDocument = async ({ databaseId, collectionId, documentId, d /** * @param {DatabasesDeleteDocumentRequestParams} params */ -const databasesDeleteDocument = async ({ databaseId, collectionId, documentId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesDeleteDocument = async ({databaseId,collectionId,documentId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{documentId}', documentId); let payload = {}; @@ -1615,8 +1759,9 @@ const databasesDeleteDocument = async ({ databaseId, collectionId, documentId, p parse(response) success() } - + return response; + } /** @@ -1625,6 +1770,7 @@ const databasesDeleteDocument = async ({ databaseId, collectionId, documentId, p * @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 */ @@ -1632,8 +1778,9 @@ const databasesDeleteDocument = async ({ databaseId, collectionId, documentId, p /** * @param {DatabasesListDocumentLogsRequestParams} params */ -const databasesListDocumentLogs = async ({ databaseId, collectionId, documentId, queries, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesListDocumentLogs = async ({databaseId,collectionId,documentId,queries,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/logs'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{documentId}', documentId); let payload = {}; if (typeof queries !== 'undefined') { @@ -1650,8 +1797,9 @@ const databasesListDocumentLogs = async ({ databaseId, collectionId, documentId, parse(response) success() } - + return response; + } /** @@ -1659,6 +1807,7 @@ const databasesListDocumentLogs = async ({ databaseId, collectionId, documentId, * @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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -1666,8 +1815,9 @@ const databasesListDocumentLogs = async ({ databaseId, collectionId, documentId, /** * @param {DatabasesListIndexesRequestParams} params */ -const databasesListIndexes = async ({ databaseId, collectionId, queries, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesListIndexes = async ({databaseId,collectionId,queries,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/indexes'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); let payload = {}; if (typeof queries !== 'undefined') { @@ -1681,11 +1831,16 @@ const databasesListIndexes = async ({ databaseId, collectionId, queries, parseOu }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('databases', 'listIndexes', databaseId, collectionId); + } else { + parse(response) + success() + } } - + return response; + } /** @@ -1696,6 +1851,7 @@ const databasesListIndexes = async ({ databaseId, collectionId, queries, parseOu * @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 {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -1703,8 +1859,9 @@ const databasesListIndexes = async ({ databaseId, collectionId, queries, parseOu /** * @param {DatabasesCreateIndexRequestParams} params */ -const databasesCreateIndex = async ({ databaseId, collectionId, key, type, attributes, orders, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesCreateIndex = async ({databaseId,collectionId,key,type,attributes,orders,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/indexes'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); let payload = {}; if (typeof key !== 'undefined') { @@ -1732,8 +1889,9 @@ const databasesCreateIndex = async ({ databaseId, collectionId, key, type, attri parse(response) success() } - + return response; + } /** @@ -1741,6 +1899,7 @@ const databasesCreateIndex = async ({ databaseId, collectionId, key, type, attri * @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 */ @@ -1748,8 +1907,9 @@ const databasesCreateIndex = async ({ databaseId, collectionId, key, type, attri /** * @param {DatabasesGetIndexRequestParams} params */ -const databasesGetIndex = async ({ databaseId, collectionId, key, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesGetIndex = async ({databaseId,collectionId,key,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/indexes/{key}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{key}', key); let payload = {}; @@ -1763,8 +1923,9 @@ const databasesGetIndex = async ({ databaseId, collectionId, key, parseOutput = parse(response) success() } - + return response; + } /** @@ -1772,6 +1933,7 @@ const databasesGetIndex = async ({ databaseId, collectionId, key, parseOutput = * @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 */ @@ -1779,8 +1941,9 @@ const databasesGetIndex = async ({ databaseId, collectionId, key, parseOutput = /** * @param {DatabasesDeleteIndexRequestParams} params */ -const databasesDeleteIndex = async ({ databaseId, collectionId, key, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesDeleteIndex = async ({databaseId,collectionId,key,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/indexes/{key}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{key}', key); let payload = {}; @@ -1794,8 +1957,9 @@ const databasesDeleteIndex = async ({ databaseId, collectionId, key, parseOutput parse(response) success() } - + return response; + } /** @@ -1803,6 +1967,7 @@ const databasesDeleteIndex = async ({ databaseId, collectionId, key, parseOutput * @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 */ @@ -1810,8 +1975,9 @@ const databasesDeleteIndex = async ({ databaseId, collectionId, key, parseOutput /** * @param {DatabasesListCollectionLogsRequestParams} params */ -const databasesListCollectionLogs = async ({ databaseId, collectionId, queries, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesListCollectionLogs = async ({databaseId,collectionId,queries,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/logs'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); let payload = {}; if (typeof queries !== 'undefined') { @@ -1828,8 +1994,9 @@ const databasesListCollectionLogs = async ({ databaseId, collectionId, queries, parse(response) success() } - + return response; + } /** @@ -1837,6 +2004,7 @@ const databasesListCollectionLogs = async ({ databaseId, collectionId, queries, * @property {string} databaseId Database ID. * @property {string} collectionId Collection ID. * @property {DatabaseUsageRange} range Date range. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -1844,8 +2012,9 @@ const databasesListCollectionLogs = async ({ databaseId, collectionId, queries, /** * @param {DatabasesGetCollectionUsageRequestParams} params */ -const databasesGetCollectionUsage = async ({ databaseId, collectionId, range, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesGetCollectionUsage = async ({databaseId,collectionId,range,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/usage'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); let payload = {}; if (typeof range !== 'undefined') { @@ -1862,14 +2031,16 @@ const databasesGetCollectionUsage = async ({ databaseId, collectionId, range, pa parse(response) success() } - + 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 */ @@ -1877,8 +2048,9 @@ const databasesGetCollectionUsage = async ({ databaseId, collectionId, range, pa /** * @param {DatabasesListLogsRequestParams} params */ -const databasesListLogs = async ({ databaseId, queries, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesListLogs = async ({databaseId,queries,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/logs'.replace('{databaseId}', databaseId); let payload = {}; if (typeof queries !== 'undefined') { @@ -1895,14 +2067,16 @@ const databasesListLogs = async ({ databaseId, queries, parseOutput = true, sdk parse(response) success() } - + return response; + } /** * @typedef {Object} DatabasesGetDatabaseUsageRequestParams * @property {string} databaseId Database ID. * @property {DatabaseUsageRange} range 'Date range. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -1910,8 +2084,9 @@ const databasesListLogs = async ({ databaseId, queries, parseOutput = true, sdk /** * @param {DatabasesGetDatabaseUsageRequestParams} params */ -const databasesGetDatabaseUsage = async ({ databaseId, range, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const databasesGetDatabaseUsage = async ({databaseId,range,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/databases/{databaseId}/usage'.replace('{databaseId}', databaseId); let payload = {}; if (typeof range !== 'undefined') { @@ -1925,11 +2100,16 @@ const databasesGetDatabaseUsage = async ({ databaseId, range, parseOutput = true }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('databases', 'getDatabaseUsage', databaseId); + } else { + parse(response) + success() + } } - + return response; + } databases @@ -1937,6 +2117,7 @@ databases .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 attributes: name`) .option(`--search `, `Search term to filter your list results. Max length: 256 chars.`) + .option(`--console`, `Get the resource console url`) .action(actionRunner(databasesList)) databases @@ -1957,6 +2138,7 @@ databases .command(`get`) .description(`Get a database by its unique ID. This endpoint response returns a JSON object with the database metadata.`) .requiredOption(`--databaseId `, `Database ID.`) + .option(`--console`, `Get the resource console url`) .action(actionRunner(databasesGet)) databases @@ -1979,6 +2161,7 @@ databases .requiredOption(`--databaseId `, `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(`--console`, `Get the resource console url`) .action(actionRunner(databasesListCollections)) databases @@ -1997,6 +2180,7 @@ databases .description(`Get a collection by its unique ID. This endpoint response returns a JSON object with the collection metadata.`) .requiredOption(`--databaseId `, `Database ID.`) .requiredOption(`--collectionId `, `Collection ID.`) + .option(`--console`, `Get the resource console url`) .action(actionRunner(databasesGetCollection)) databases @@ -2023,6 +2207,7 @@ databases .requiredOption(`--databaseId `, `Database ID.`) .requiredOption(`--collectionId `, `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, size, required, array, status, error`) + .option(`--console`, `Get the resource console url`) .action(actionRunner(databasesListAttributes)) databases @@ -2270,6 +2455,7 @@ databases .requiredOption(`--databaseId `, `Database ID.`) .requiredOption(`--collectionId `, `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(`--console`, `Get the resource console url`) .action(actionRunner(databasesListDocuments)) databases @@ -2289,6 +2475,7 @@ databases .requiredOption(`--collectionId `, `Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection).`) .requiredOption(`--documentId `, `Document 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.`) + .option(`--console`, `Get the resource console url`) .action(actionRunner(databasesGetDocument)) databases @@ -2324,6 +2511,7 @@ databases .requiredOption(`--databaseId `, `Database ID.`) .requiredOption(`--collectionId `, `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(`--console`, `Get the resource console url`) .action(actionRunner(databasesListIndexes)) databases @@ -2381,6 +2569,7 @@ databases .description(``) .requiredOption(`--databaseId `, `Database ID.`) .option(`--range `, `'Date range.`) + .option(`--console`, `Get the resource console url`) .action(actionRunner(databasesGetDatabaseUsage)) module.exports = { @@ -2433,4 +2622,4 @@ module.exports = { databasesGetCollectionUsage, databasesListLogs, databasesGetDatabaseUsage -}; \ No newline at end of file +}; diff --git a/lib/commands/deploy.js b/lib/commands/deploy.js deleted file mode 100644 index 3ae7a17..0000000 --- a/lib/commands/deploy.js +++ /dev/null @@ -1,940 +0,0 @@ -const inquirer = require("inquirer"); -const JSONbig = require("json-bigint")({ storeAsString: false }); -const { Command } = require("commander"); -const { localConfig } = require("../config"); -const { paginate } = require('../paginate'); -const { questionsDeployBuckets, questionsDeployTeams, questionsDeployFunctions, questionsGetEntrypoint, questionsDeployCollections, questionsConfirmDeployCollections } = require("../questions"); -const { actionRunner, success, log, error, commandDescriptions } = require("../parser"); -const { functionsGet, functionsCreate, functionsUpdate, functionsCreateDeployment, functionsUpdateDeployment, functionsListVariables, functionsDeleteVariable, functionsCreateVariable } = require('./functions'); -const { - databasesGet, - databasesCreate, - databasesUpdate, - databasesCreateBooleanAttribute, - databasesGetCollection, - databasesCreateCollection, - databasesCreateStringAttribute, - databasesCreateIntegerAttribute, - databasesCreateFloatAttribute, - databasesCreateEmailAttribute, - databasesCreateDatetimeAttribute, - databasesCreateIndex, - databasesCreateUrlAttribute, - databasesCreateIpAttribute, - databasesCreateEnumAttribute, - databasesCreateRelationshipAttribute, - databasesDeleteAttribute, - databasesListAttributes, - databasesListIndexes, - databasesDeleteIndex, - databasesUpdateCollection -} = require("./databases"); -const { - storageGetBucket, storageUpdateBucket, storageCreateBucket -} = require("./storage"); -const { - teamsGet, - teamsUpdateName, - teamsCreate -} = require("./teams"); -const { checkDeployConditions } = require('../utils'); - -const STEP_SIZE = 100; // Resources -const POOL_DEBOUNCE = 2000; // Milliseconds - -let poolMaxDebounces = 30; - -const awaitPools = { - wipeAttributes: async (databaseId, collectionId, iteration = 1) => { - if (iteration > poolMaxDebounces) { - return false; - } - - const { total } = await databasesListAttributes({ - databaseId, - collectionId, - queries: [JSON.stringify({ method: 'limit', values: [1] })], - parseOutput: false - }); - - if (total === 0) { - return true; - } - - let steps = Math.max(1, Math.ceil(total / STEP_SIZE)); - if (steps > 1 && iteration === 1) { - poolMaxDebounces *= steps; - - log('Found a large number of attributes, increasing timeout to ' + (poolMaxDebounces * POOL_DEBOUNCE / 1000 / 60) + ' minutes') - } - - await new Promise(resolve => setTimeout(resolve, POOL_DEBOUNCE)); - - return await awaitPools.wipeAttributes( - databaseId, - collectionId, - iteration + 1 - ); - }, - wipeIndexes: async (databaseId, collectionId, iteration = 1) => { - if (iteration > poolMaxDebounces) { - return false; - } - - const { total } = await databasesListIndexes({ - databaseId, - collectionId, - queries: [JSON.stringify({ method: 'limit', values: [1] })], - parseOutput: false - }); - - if (total === 0) { - return true; - } - - let steps = Math.max(1, Math.ceil(total / STEP_SIZE)); - if (steps > 1 && iteration === 1) { - poolMaxDebounces *= steps; - - log('Found a large number of indexes, increasing timeout to ' + (poolMaxDebounces * POOL_DEBOUNCE / 1000 / 60) + ' minutes') - } - - await new Promise(resolve => setTimeout(resolve, POOL_DEBOUNCE)); - - return await awaitPools.wipeIndexes( - databaseId, - collectionId, - iteration + 1 - ); - }, - wipeVariables: async (functionId, iteration = 1) => { - if (iteration > poolMaxDebounces) { - return false; - } - - const { total } = await functionsListVariables({ - functionId, - queries: ['limit(1)'], - parseOutput: false - }); - - if (total === 0) { - return true; - } - - let steps = Math.max(1, Math.ceil(total / STEP_SIZE)); - if (steps > 1 && iteration === 1) { - poolMaxDebounces *= steps; - - log('Found a large number of variables, increasing timeout to ' + (poolMaxDebounces * POOL_DEBOUNCE / 1000 / 60) + ' minutes') - } - - await new Promise(resolve => setTimeout(resolve, POOL_DEBOUNCE)); - - return await awaitPools.wipeVariables( - functionId, - iteration + 1 - ); - }, - expectAttributes: async (databaseId, collectionId, attributeKeys, iteration = 1) => { - if (iteration > poolMaxDebounces) { - return false; - } - - let steps = Math.max(1, Math.ceil(attributeKeys.length / STEP_SIZE)); - if (steps > 1 && iteration === 1) { - poolMaxDebounces *= steps; - - log('Creating a large number of attributes, increasing timeout to ' + (poolMaxDebounces * POOL_DEBOUNCE / 1000 / 60) + ' minutes') - } - - const { attributes } = await paginate(databasesListAttributes, { - databaseId, - collectionId, - parseOutput: false - }, 100, 'attributes'); - - const ready = attributes - .filter(attribute => { - if (attributeKeys.includes(attribute.key)) { - if (['stuck', 'failed'].includes(attribute.status)) { - throw new Error(`Attribute '${attribute.key}' failed!`); - } - - return attribute.status === 'available'; - } - - return false; - }) - .map(attribute => attribute.key); - - if (ready.length === attributeKeys.length) { - return true; - } - - await new Promise(resolve => setTimeout(resolve, POOL_DEBOUNCE)); - - return await awaitPools.expectAttributes( - databaseId, - collectionId, - attributeKeys, - iteration + 1 - ); - }, - expectIndexes: async (databaseId, collectionId, indexKeys, iteration = 1) => { - if (iteration > poolMaxDebounces) { - return false; - } - - let steps = Math.max(1, Math.ceil(indexKeys.length / STEP_SIZE)); - if (steps > 1 && iteration === 1) { - poolMaxDebounces *= steps; - - log('Creating a large number of indexes, increasing timeout to ' + (poolMaxDebounces * POOL_DEBOUNCE / 1000 / 60) + ' minutes') - } - - const { indexes } = await paginate(databasesListIndexes, { - databaseId, - collectionId, - parseOutput: false - }, 100, 'indexes'); - - const ready = indexes - .filter((index) => { - if (indexKeys.includes(index.key)) { - if (['stuck', 'failed'].includes(index.status)) { - throw new Error(`Index '${index.key}' failed!`); - } - - return index.status === 'available'; - } - - return false; - }) - .map(index => index.key); - - if (ready.length >= indexKeys.length) { - return true; - } - - await new Promise(resolve => setTimeout(resolve, POOL_DEBOUNCE)); - - return await awaitPools.expectIndexes( - databaseId, - collectionId, - indexKeys, - iteration + 1 - ); - }, -} - -const deploy = new Command("deploy") - .description(commandDescriptions['deploy']) - .configureHelp({ - helpWidth: process.stdout.columns || 80 - }) - .action(actionRunner(async (_options, command) => { - command.help() - })); - -const deployFunction = async ({ functionId, all, yes } = {}) => { - let response = {}; - - const functionIds = []; - - if (functionId) { - functionIds.push(functionId); - } else if (all) { - const functions = localConfig.getFunctions(); - checkDeployConditions(localConfig); - if (functions.length === 0) { - throw new Error("No functions found in the current directory."); - } - functionIds.push(...functions.map((func, idx) => { - return func.$id; - })); - } - - if (functionIds.length <= 0) { - const answers = await inquirer.prompt(questionsDeployFunctions[0]); - functionIds.push(...answers.functions); - } - - let functions = functionIds.map((id) => { - const functions = localConfig.getFunctions(); - const func = functions.find((f) => f.$id === id); - - if (!func) { - throw new Error("Function '" + id + "' not found.") - } - - return func; - }); - - for (let func of functions) { - log(`Deploying function ${func.name} ( ${func['$id']} )`) - - try { - response = await functionsGet({ - functionId: func['$id'], - parseOutput: false, - }); - - if (response.runtime !== func.runtime) { - throw new Error(`Runtime missmatch! (local=${func.runtime},remote=${response.runtime}) Please delete remote function or update your appwrite.json`); - } - - response = await functionsUpdate({ - functionId: func['$id'], - name: func.name, - execute: func.execute, - events: func.events, - schedule: func.schedule, - timeout: func.timeout, - enabled: func.enabled, - logging: func.logging, - entrypoint: func.entrypoint, - commands: func.commands, - vars: JSON.stringify(response.vars), - parseOutput: false - }); - } catch (e) { - if (e.code == 404) { - log(`Function ${func.name} ( ${func['$id']} ) does not exist in the project. Creating ... `); - response = await functionsCreate({ - functionId: func.$id || 'unique()', - name: func.name, - runtime: func.runtime, - execute: func.execute, - events: func.events, - schedule: func.schedule, - timeout: func.timeout, - enabled: func.enabled, - logging: func.logging, - entrypoint: func.entrypoint, - commands: func.commands, - vars: JSON.stringify(func.vars), - parseOutput: false - }); - - localConfig.updateFunction(func['$id'], { - "$id": response['$id'], - }); - - func["$id"] = response['$id']; - log(`Function ${func.name} created.`); - } else { - throw e; - } - } - - if (func.variables) { - // Delete existing variables - - const { total } = await functionsListVariables({ - functionId: func['$id'], - queries: [JSON.stringify({ method: 'limit', values: [1] })], - parseOutput: false - }); - - let deployVariables = yes; - - if (total === 0) { - deployVariables = true; - } else if (total > 0 && !yes) { - const variableAnswers = await inquirer.prompt(questionsDeployFunctions[1]) - deployVariables = variableAnswers.override.toLowerCase() === "yes"; - } - - if (!deployVariables) { - log(`Skipping variables for ${func.name} ( ${func['$id']} )`); - } else { - log(`Deploying variables for ${func.name} ( ${func['$id']} )`); - - const { variables } = await paginate(functionsListVariables, { - functionId: func['$id'], - parseOutput: false - }, 100, 'variables'); - - await Promise.all(variables.map(async variable => { - await functionsDeleteVariable({ - functionId: func['$id'], - variableId: variable['$id'], - parseOutput: false - }); - })); - - let result = await awaitPools.wipeVariables(func['$id']); - if (!result) { - throw new Error("Variable deletion timed out."); - } - - // Deploy local variables - await Promise.all(Object.keys(func.variables).map(async localVariableKey => { - await functionsCreateVariable({ - functionId: func['$id'], - key: localVariableKey, - value: func.variables[localVariableKey], - parseOutput: false - }); - })); - } - } - - // Create tag - if (!func.entrypoint) { - const answers = await inquirer.prompt(questionsGetEntrypoint) - func.entrypoint = answers.entrypoint; - localConfig.updateFunction(func['$id'], func); - } - - try { - response = await functionsCreateDeployment({ - functionId: func['$id'], - entrypoint: func.entrypoint, - commands: func.commands, - code: func.path, - activate: true, - parseOutput: false - }) - - success(`Deployed ${func.name} ( ${func['$id']} )`); - - } catch (e) { - switch (e.code) { - case 'ENOENT': - error(`Function ${func.name} ( ${func['$id']} ) not found in the current directory. Skipping ...`); - break; - default: - throw e; - } - } - } - - success(`Deployed ${functions.length} functions`); -} - -const createAttribute = async (databaseId, collectionId, attribute) => { - switch (attribute.type) { - case 'string': - switch (attribute.format) { - case 'email': - return await databasesCreateEmailAttribute({ - databaseId, - collectionId, - key: attribute.key, - required: attribute.required, - xdefault: attribute.default, - array: attribute.array, - parseOutput: false - }) - case 'url': - return await databasesCreateUrlAttribute({ - databaseId, - collectionId, - key: attribute.key, - required: attribute.required, - xdefault: attribute.default, - array: attribute.array, - parseOutput: false - }) - case 'ip': - return await databasesCreateIpAttribute({ - databaseId, - collectionId, - key: attribute.key, - required: attribute.required, - xdefault: attribute.default, - array: attribute.array, - parseOutput: false - }) - case 'enum': - return await databasesCreateEnumAttribute({ - databaseId, - collectionId, - key: attribute.key, - elements: attribute.elements, - required: attribute.required, - xdefault: attribute.default, - array: attribute.array, - parseOutput: false - }) - default: - return await databasesCreateStringAttribute({ - databaseId, - collectionId, - key: attribute.key, - size: attribute.size, - required: attribute.required, - xdefault: attribute.default, - array: attribute.array, - parseOutput: false - }) - - } - case 'integer': - return await databasesCreateIntegerAttribute({ - databaseId, - collectionId, - key: attribute.key, - required: attribute.required, - min: attribute.min, - max: attribute.max, - xdefault: attribute.default, - array: attribute.array, - parseOutput: false - }) - case 'double': - return databasesCreateFloatAttribute({ - databaseId, - collectionId, - key: attribute.key, - required: attribute.required, - min: attribute.min, - max: attribute.max, - xdefault: attribute.default, - array: attribute.array, - parseOutput: false - }) - case 'boolean': - return databasesCreateBooleanAttribute({ - databaseId, - collectionId, - key: attribute.key, - required: attribute.required, - xdefault: attribute.default, - array: attribute.array, - parseOutput: false - }) - case 'datetime': - return databasesCreateDatetimeAttribute({ - databaseId, - collectionId, - key: attribute.key, - required: attribute.required, - xdefault: attribute.default, - array: attribute.array, - parseOutput: false - }) - case 'relationship': - return databasesCreateRelationshipAttribute({ - databaseId, - collectionId, - relatedCollectionId: attribute.relatedCollection, - type: attribute.relationType, - twoWay: attribute.twoWay, - key: attribute.key, - twoWayKey: attribute.twoWayKey, - onDelete: attribute.onDelete, - parseOutput: false - }) - } -} - -const deployCollection = async ({ all, yes } = {}) => { - let response = {}; - - const collections = []; - - if (all) { - checkDeployConditions(localConfig); - if (localConfig.getCollections().length === 0) { - throw new Error("No collections found in the current directory. Run `appwrite init collection` to fetch all your collections."); - } - collections.push(...localConfig.getCollections()); - } else { - const answers = await inquirer.prompt(questionsDeployCollections[0]) - const configCollections = new Map(); - localConfig.getCollections().forEach((c) => { - configCollections.set(`${c['databaseId']}|${c['$id']}`, c); - }); - answers.collections.forEach((a) => { - const collection = configCollections.get(a); - collections.push(collection); - }) - } - - for (let collection of collections) { - log(`Deploying collection ${collection.name} ( ${collection['databaseId']} - ${collection['$id']} )`) - - let databaseId; - - const localDatabase = localConfig.getDatabase(collection.databaseId); - - try { - const database = await databasesGet({ - databaseId: collection.databaseId, - parseOutput: false, - }); - - databaseId = database.$id; - - if (database.name !== (localDatabase.name ?? collection.databaseId)) { - await databasesUpdate({ - databaseId: collection.databaseId, - name: localDatabase.name ?? collection.databaseId, - parseOutput: false - }) - - success(`Updated ${localDatabase.name} ( ${collection.databaseId} )`); - } - } catch (err) { - log(`Database ${collection.databaseId} not found. Creating it now...`); - - const database = await databasesCreate({ - databaseId: collection.databaseId, - name: localDatabase.name ?? collection.databaseId, - parseOutput: false, - }); - - databaseId = database.$id; - } - - try { - response = await databasesGetCollection({ - databaseId, - collectionId: collection['$id'], - parseOutput: false, - }) - - log(`Collection ${collection.name} ( ${collection['$id']} ) already exists.`); - - if (!yes) { - const answers = await inquirer.prompt(questionsDeployCollections[1]) - if (answers.override.toLowerCase() !== "yes") { - log(`Received "${answers.override}". Skipping ${collection.name} ( ${collection['$id']} )`); - continue; - } - } - - log(`Deleting indexes and attributes ... `); - - const { indexes } = await paginate(databasesListIndexes, { - databaseId, - collectionId: collection['$id'], - parseOutput: false - }, 100, 'indexes'); - - await Promise.all(indexes.map(async index => { - await databasesDeleteIndex({ - databaseId, - collectionId: collection['$id'], - key: index.key, - parseOutput: false - }); - })); - - let result = await awaitPools.wipeIndexes(databaseId, collection['$id']); - if (!result) { - throw new Error("Index deletion timed out."); - } - - const { attributes } = await paginate(databasesListAttributes, { - databaseId, - collectionId: collection['$id'], - parseOutput: false - }, 100, 'attributes'); - - await Promise.all(attributes.map(async attribute => { - await databasesDeleteAttribute({ - databaseId, - collectionId: collection['$id'], - key: attribute.key, - parseOutput: false - }); - })); - - const deleteAttributesPoolStatus = await awaitPools.wipeAttributes(databaseId, collection['$id']); - if (!deleteAttributesPoolStatus) { - throw new Error("Attribute deletion timed out."); - } - - await databasesUpdateCollection({ - databaseId, - collectionId: collection['$id'], - name: collection.name, - documentSecurity: collection.documentSecurity, - permissions: collection['$permissions'], - enabled: collection.enabled, - parseOutput: false - }) - } catch (e) { - if (e.code == 404) { - log(`Collection ${collection.name} does not exist in the project. Creating ... `); - response = await databasesCreateCollection({ - databaseId, - collectionId: collection['$id'], - name: collection.name, - documentSecurity: collection.documentSecurity, - permissions: collection['$permissions'], - parseOutput: false - }) - - } else { - throw e; - } - } - - // Create all non-relationship attributes first - const attributes = collection.attributes.filter(attribute => attribute.type !== 'relationship'); - - await Promise.all(attributes.map(attribute => { - return createAttribute(databaseId, collection['$id'], attribute); - })); - - let result = await awaitPools.expectAttributes( - databaseId, - collection['$id'], - attributes.map(attribute => attribute.key) - ); - - if (!result) { - throw new Error("Attribute creation timed out."); - } - - success(`Created ${attributes.length} non-relationship attributes`); - - log(`Creating indexes ...`) - - await Promise.all(collection.indexes.map(async index => { - await databasesCreateIndex({ - databaseId, - collectionId: collection['$id'], - key: index.key, - type: index.type, - attributes: index.attributes, - orders: index.orders, - parseOutput: false - }); - })); - - result = await awaitPools.expectIndexes( - databaseId, - collection['$id'], - collection.indexes.map(attribute => attribute.key) - ); - - if (!result) { - throw new Error("Index creation timed out."); - } - - success(`Created ${collection.indexes.length} indexes`); - - success(`Deployed ${collection.name} ( ${collection['$id']} )`); - } - - // Create the relationship attributes - for (let collection of collections) { - const relationships = collection.attributes.filter(attribute => - attribute.type === 'relationship' && attribute.side === 'parent' - ); - - if (relationships.length === 0) { - continue; - } - - log(`Deploying relationships for collection ${collection.name} ( ${collection['$id']} )`); - - await Promise.all(relationships.map(attribute => { - return createAttribute(collection['databaseId'], collection['$id'], attribute); - })); - - let result = await awaitPools.expectAttributes( - collection['databaseId'], - collection['$id'], - relationships.map(attribute => attribute.key) - ); - - if (!result) { - throw new Error("Attribute creation timed out."); - } - - success(`Created ${relationships.length} relationship attributes`); - } -} - -const deployBucket = async ({ all, yes } = {}) => { - let response = {}; - - let bucketIds = []; - const configBuckets = localConfig.getBuckets(); - - if (all) { - checkDeployConditions(localConfig); - bucketIds.push(...configBuckets.map((b) => b.$id)); - } - - if (bucketIds.length === 0) { - const answers = await inquirer.prompt(questionsDeployBuckets[0]) - bucketIds.push(...answers.buckets); - } - - let buckets = []; - - for (const bucketId of bucketIds) { - const idBuckets = configBuckets.filter((b) => b.$id === bucketId); - buckets.push(...idBuckets); - } - - for (let bucket of buckets) { - log(`Deploying bucket ${bucket.name} ( ${bucket['$id']} )`) - - try { - response = await storageGetBucket({ - bucketId: bucket['$id'], - parseOutput: false, - }) - log(`Bucket ${bucket.name} ( ${bucket['$id']} ) already exists.`); - - if (!yes) { - const answers = await inquirer.prompt(questionsDeployBuckets[1]) - if (answers.override.toLowerCase() !== "yes") { - log(`Received "${answers.override}". Skipping ${bucket.name} ( ${bucket['$id']} )`); - continue; - } - } - - log(`Updating bucket ...`) - - await storageUpdateBucket({ - bucketId: bucket['$id'], - name: bucket.name, - permissions: bucket['$permissions'], - fileSecurity: bucket.fileSecurity, - enabled: bucket.enabled, - maximumFileSize: bucket.maximumFileSize, - allowedFileExtensions: bucket.allowedFileExtensions, - compression: bucket.compression, - encryption: bucket.encryption, - antivirus: bucket.antivirus, - compression: bucket.compression, - parseOutput: false - }); - - success(`Deployed ${bucket.name} ( ${bucket['$id']} )`); - } catch (e) { - if (e.code == 404) { - log(`Bucket ${bucket.name} does not exist in the project. Creating ... `); - - response = await storageCreateBucket({ - bucketId: bucket['$id'], - name: bucket.name, - permissions: bucket['$permissions'], - fileSecurity: bucket.fileSecurity, - enabled: bucket.enabled, - maximumFileSize: bucket.maximumFileSize, - allowedFileExtensions: bucket.allowedFileExtensions, - compression: bucket.compression, - encryption: bucket.encryption, - antivirus: bucket.antivirus, - parseOutput: false - }) - - success(`Deployed ${bucket.name} ( ${bucket['$id']} )`); - } else { - throw e; - } - } - } -} - -const deployTeam = async ({ all, yes } = {}) => { - let response = {}; - - let teamIds = []; - const configTeams = localConfig.getTeams(); - - if (all) { - checkDeployConditions(localConfig); - teamIds.push(...configTeams.map((t) => t.$id)); - } - - if (teamIds.length === 0) { - const answers = await inquirer.prompt(questionsDeployTeams[0]) - teamIds.push(...answers.teams); - } - - let teams = []; - - for (const teamId of teamIds) { - const idTeams = configTeams.filter((t) => t.$id === teamId); - teams.push(...idTeams); - } - - for (let team of teams) { - log(`Deploying team ${team.name} ( ${team['$id']} )`) - - try { - response = await teamsGet({ - teamId: team['$id'], - parseOutput: false, - }) - log(`Team ${team.name} ( ${team['$id']} ) already exists.`); - - if (!yes) { - const answers = await inquirer.prompt(questionsDeployTeams[1]) - if (answers.override.toLowerCase() !== "yes") { - log(`Received "${answers.override}". Skipping ${team.name} ( ${team['$id']} )`); - continue; - } - } - - log(`Updating team ...`) - - await teamsUpdateName({ - teamId: team['$id'], - name: team.name, - parseOutput: false - }); - - success(`Deployed ${team.name} ( ${team['$id']} )`); - } catch (e) { - if (e.code == 404) { - log(`Team ${team.name} does not exist in the project. Creating ... `); - - response = await teamsCreate({ - teamId: team['$id'], - name: team.name, - parseOutput: false - }) - - success(`Deployed ${team.name} ( ${team['$id']} )`); - } else { - throw e; - } - } - } -} - -deploy - .command("function") - .description("Deploy functions in the current directory.") - .option(`--functionId `, `Function ID`) - .option(`--all`, `Flag to deploy all functions`) - .option(`--yes`, `Flag to confirm all warnings`) - .action(actionRunner(deployFunction)); - -deploy - .command("collection") - .description("Deploy collections in the current project.") - .option(`--all`, `Flag to deploy all collections`) - .option(`--yes`, `Flag to confirm all warnings`) - .action(actionRunner(deployCollection)); - -deploy - .command("bucket") - .description("Deploy buckets in the current project.") - .option(`--all`, `Flag to deploy all buckets`) - .option(`--yes`, `Flag to confirm all warnings`) - .action(actionRunner(deployBucket)); - -deploy - .command("team") - .description("Deploy teams in the current project.") - .option(`--all`, `Flag to deploy all teams`) - .option(`--yes`, `Flag to confirm all warnings`) - .action(actionRunner(deployTeam)); - -module.exports = { - deploy -} diff --git a/lib/commands/functions.js b/lib/commands/functions.js index 360c7a9..f169303 100644 --- a/lib/commands/functions.js +++ b/lib/commands/functions.js @@ -4,7 +4,7 @@ const tar = require("tar"); const ignore = require("ignore"); const { promisify } = require('util'); const libClient = require('../client.js'); -const { getAllFiles } = require('../utils.js'); +const { getAllFiles, showConsoleLink } = require('../utils.js'); const { Command } = require('commander'); const { sdkForProject, sdkForConsole } = require('../sdks') const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log } = require('../parser') @@ -43,6 +43,7 @@ const functions = new Command("functions").description(commandDescriptions['func * @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, deployment, schedule, scheduleNext, schedulePrevious, timeout, entrypoint, commands, installationId * @property {string} search Search term to filter your list results. Max length: 256 chars. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -50,8 +51,9 @@ const functions = new Command("functions").description(commandDescriptions['func /** * @param {FunctionsListRequestParams} params */ -const functionsList = async ({ queries, search, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const functionsList = async ({queries,search,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/functions'; let payload = {}; if (typeof queries !== 'undefined') { @@ -68,11 +70,16 @@ const functionsList = async ({ queries, search, parseOutput = true, sdk = undefi }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('functions', 'list'); + } else { + parse(response) + success() + } } - + return response; + } /** @@ -88,6 +95,7 @@ const functionsList = async ({ queries, search, parseOutput = true, sdk = undefi * @property {boolean} logging Whether executions will be logged. When set to false, executions will not be logged, but will reduce resource used by your Appwrite project. * @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. @@ -97,6 +105,7 @@ const functionsList = async ({ queries, search, parseOutput = true, sdk = undefi * @property {string} templateOwner The name of the owner of the template. * @property {string} templateRootDirectory Path to function code in the template repo. * @property {string} templateBranch Production branch for the repo linked to the function template. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -104,8 +113,9 @@ const functionsList = async ({ queries, search, parseOutput = true, sdk = undefi /** * @param {FunctionsCreateRequestParams} params */ -const functionsCreate = async ({ functionId, name, runtime, execute, events, schedule, timeout, enabled, logging, entrypoint, commands, installationId, providerRepositoryId, providerBranch, providerSilentMode, providerRootDirectory, templateRepository, templateOwner, templateRootDirectory, templateBranch, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const functionsCreate = async ({functionId,name,runtime,execute,events,schedule,timeout,enabled,logging,entrypoint,commands,scopes,installationId,providerRepositoryId,providerBranch,providerSilentMode,providerRootDirectory,templateRepository,templateOwner,templateRootDirectory,templateBranch,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/functions'; let payload = {}; if (typeof functionId !== 'undefined') { @@ -143,6 +153,10 @@ const functionsCreate = async ({ functionId, name, runtime, execute, events, sch if (typeof commands !== 'undefined') { payload['commands'] = commands; } + scopes = scopes === true ? [] : scopes; + if (typeof scopes !== 'undefined') { + payload['scopes'] = scopes; + } if (typeof installationId !== 'undefined') { payload['installationId'] = installationId; } @@ -181,12 +195,14 @@ const functionsCreate = async ({ functionId, name, runtime, execute, events, sch parse(response) success() } - + return response; + } /** * @typedef {Object} FunctionsListRuntimesRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -194,8 +210,9 @@ const functionsCreate = async ({ functionId, name, runtime, execute, events, sch /** * @param {FunctionsListRuntimesRequestParams} params */ -const functionsListRuntimes = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const functionsListRuntimes = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/functions/runtimes'; let payload = {}; @@ -209,13 +226,15 @@ const functionsListRuntimes = async ({ parseOutput = true, sdk = undefined}) => parse(response) success() } - + return response; + } /** * @typedef {Object} FunctionsGetUsageRequestParams * @property {FunctionUsageRange} range Date range. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -223,8 +242,9 @@ const functionsListRuntimes = async ({ parseOutput = true, sdk = undefined}) => /** * @param {FunctionsGetUsageRequestParams} params */ -const functionsGetUsage = async ({ range, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const functionsGetUsage = async ({range,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/functions/usage'; let payload = {}; if (typeof range !== 'undefined') { @@ -241,13 +261,15 @@ const functionsGetUsage = async ({ range, parseOutput = true, sdk = undefined}) parse(response) success() } - + return response; + } /** * @typedef {Object} FunctionsGetRequestParams * @property {string} functionId Function ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -255,8 +277,9 @@ const functionsGetUsage = async ({ range, parseOutput = true, sdk = undefined}) /** * @param {FunctionsGetRequestParams} params */ -const functionsGet = async ({ functionId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const functionsGet = async ({functionId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/functions/{functionId}'.replace('{functionId}', functionId); let payload = {}; @@ -267,11 +290,16 @@ const functionsGet = async ({ functionId, parseOutput = true, sdk = undefined}) }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('functions', 'get', functionId); + } else { + parse(response) + success() + } } - + return response; + } /** @@ -287,11 +315,13 @@ const functionsGet = async ({ functionId, parseOutput = true, sdk = undefined}) * @property {boolean} logging Whether executions will be logged. When set to false, executions will not be logged, but will reduce resource used by your Appwrite project. * @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 {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -299,8 +329,9 @@ const functionsGet = async ({ functionId, parseOutput = true, sdk = undefined}) /** * @param {FunctionsUpdateRequestParams} params */ -const functionsUpdate = async ({ functionId, name, runtime, execute, events, schedule, timeout, enabled, logging, entrypoint, commands, installationId, providerRepositoryId, providerBranch, providerSilentMode, providerRootDirectory, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const functionsUpdate = async ({functionId,name,runtime,execute,events,schedule,timeout,enabled,logging,entrypoint,commands,scopes,installationId,providerRepositoryId,providerBranch,providerSilentMode,providerRootDirectory,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/functions/{functionId}'.replace('{functionId}', functionId); let payload = {}; if (typeof name !== 'undefined') { @@ -335,6 +366,10 @@ const functionsUpdate = async ({ functionId, name, runtime, execute, events, sch if (typeof commands !== 'undefined') { payload['commands'] = commands; } + scopes = scopes === true ? [] : scopes; + if (typeof scopes !== 'undefined') { + payload['scopes'] = scopes; + } if (typeof installationId !== 'undefined') { payload['installationId'] = installationId; } @@ -361,13 +396,15 @@ const functionsUpdate = async ({ functionId, name, runtime, execute, events, sch parse(response) success() } - + return response; + } /** * @typedef {Object} FunctionsDeleteRequestParams * @property {string} functionId Function ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -375,8 +412,9 @@ const functionsUpdate = async ({ functionId, name, runtime, execute, events, sch /** * @param {FunctionsDeleteRequestParams} params */ -const functionsDelete = async ({ functionId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const functionsDelete = async ({functionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/functions/{functionId}'.replace('{functionId}', functionId); let payload = {}; @@ -390,8 +428,9 @@ const functionsDelete = async ({ functionId, parseOutput = true, sdk = undefined parse(response) success() } - + return response; + } /** @@ -399,6 +438,7 @@ const functionsDelete = async ({ functionId, parseOutput = true, sdk = undefined * @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: size, buildId, activate, entrypoint, commands * @property {string} search Search term to filter your list results. Max length: 256 chars. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -406,8 +446,9 @@ const functionsDelete = async ({ functionId, parseOutput = true, sdk = undefined /** * @param {FunctionsListDeploymentsRequestParams} params */ -const functionsListDeployments = async ({ functionId, queries, search, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const functionsListDeployments = async ({functionId,queries,search,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/functions/{functionId}/deployments'.replace('{functionId}', functionId); let payload = {}; if (typeof queries !== 'undefined') { @@ -424,11 +465,16 @@ const functionsListDeployments = async ({ functionId, queries, search, parseOutp }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('functions', 'listDeployments', functionId); + } else { + parse(response) + success() + } } - + return response; + } /** @@ -438,6 +484,7 @@ const functionsListDeployments = async ({ functionId, queries, search, parseOutp * @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 @@ -446,8 +493,9 @@ const functionsListDeployments = async ({ functionId, queries, search, parseOutp /** * @param {FunctionsCreateDeploymentRequestParams} params */ -const functionsCreateDeployment = async ({ functionId, code, activate, entrypoint, commands, parseOutput = true, sdk = undefined, onProgress = () => {}}) => { - let client = !sdk ? await sdkForProject() : sdk; +const functionsCreateDeployment = async ({functionId,code,activate,entrypoint,commands,parseOutput = true, overrideForCli = false, sdk = undefined,onProgress = () => {}}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/functions/{functionId}/deployments'.replace('{functionId}', functionId); let payload = {}; if (typeof entrypoint !== 'undefined') { @@ -460,19 +508,19 @@ const functionsCreateDeployment = async ({ functionId, code, activate, entrypoin if (!fs.lstatSync(folderPath).isDirectory()) { throw new Error('The path is not a directory.'); } - + const ignorer = ignore(); const func = localConfig.getFunction(functionId); + ignorer.add('.appwrite'); + if (func.ignore) { ignorer.add(func.ignore); - log('Ignoring files using configuration from appwrite.json'); } else if (fs.existsSync(pathLib.join(code, '.gitignore'))) { ignorer.add(fs.readFileSync(pathLib.join(code, '.gitignore')).toString()); - log('Ignoring files in .gitignore'); } - + const files = getAllFiles(code).map((file) => pathLib.relative(code, file)).filter((file) => !ignorer.ignores(file)); await tar @@ -502,7 +550,7 @@ const functionsCreateDeployment = async ({ functionId, code, activate, entrypoin } const size = code.size; - + const apiHeaders = { 'content-type': 'multipart/form-data', }; @@ -529,7 +577,7 @@ const functionsCreateDeployment = async ({ functionId, code, activate, entrypoin } let uploadableChunkTrimmed; - + if(currentPosition + 1 >= client.CHUNK_SIZE) { uploadableChunkTrimmed = uploadableChunk; } else { @@ -582,8 +630,8 @@ const functionsCreateDeployment = async ({ functionId, code, activate, entrypoin await uploadChunk(true); } - fs.unlinkSync(filePath); - + await fs.unlink(filePath,()=>{}); + if (parseOutput) { parse(response) success() @@ -596,6 +644,7 @@ const functionsCreateDeployment = async ({ functionId, code, activate, entrypoin * @typedef {Object} FunctionsGetDeploymentRequestParams * @property {string} functionId Function ID. * @property {string} deploymentId Deployment ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -603,8 +652,9 @@ const functionsCreateDeployment = async ({ functionId, code, activate, entrypoin /** * @param {FunctionsGetDeploymentRequestParams} params */ -const functionsGetDeployment = async ({ functionId, deploymentId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const functionsGetDeployment = async ({functionId,deploymentId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/functions/{functionId}/deployments/{deploymentId}'.replace('{functionId}', functionId).replace('{deploymentId}', deploymentId); let payload = {}; @@ -615,17 +665,23 @@ const functionsGetDeployment = async ({ functionId, deploymentId, parseOutput = }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('functions', 'getDeployment', functionId, deploymentId); + } else { + parse(response) + success() + } } - + return response; + } /** * @typedef {Object} FunctionsUpdateDeploymentRequestParams * @property {string} functionId Function ID. * @property {string} deploymentId Deployment ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -633,8 +689,9 @@ const functionsGetDeployment = async ({ functionId, deploymentId, parseOutput = /** * @param {FunctionsUpdateDeploymentRequestParams} params */ -const functionsUpdateDeployment = async ({ functionId, deploymentId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const functionsUpdateDeployment = async ({functionId,deploymentId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/functions/{functionId}/deployments/{deploymentId}'.replace('{functionId}', functionId).replace('{deploymentId}', deploymentId); let payload = {}; @@ -648,14 +705,16 @@ const functionsUpdateDeployment = async ({ functionId, deploymentId, parseOutput parse(response) success() } - + 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 */ @@ -663,8 +722,9 @@ const functionsUpdateDeployment = async ({ functionId, deploymentId, parseOutput /** * @param {FunctionsDeleteDeploymentRequestParams} params */ -const functionsDeleteDeployment = async ({ functionId, deploymentId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const functionsDeleteDeployment = async ({functionId,deploymentId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/functions/{functionId}/deployments/{deploymentId}'.replace('{functionId}', functionId).replace('{deploymentId}', deploymentId); let payload = {}; @@ -678,8 +738,9 @@ const functionsDeleteDeployment = async ({ functionId, deploymentId, parseOutput parse(response) success() } - + return response; + } /** @@ -687,6 +748,7 @@ const functionsDeleteDeployment = async ({ functionId, deploymentId, parseOutput * @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 */ @@ -694,10 +756,14 @@ const functionsDeleteDeployment = async ({ functionId, deploymentId, parseOutput /** * @param {FunctionsCreateBuildRequestParams} params */ -const functionsCreateBuild = async ({ functionId, deploymentId, buildId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; - let apiPath = '/functions/{functionId}/deployments/{deploymentId}/builds/{buildId}'.replace('{functionId}', functionId).replace('{deploymentId}', deploymentId).replace('{buildId}', buildId); +const functionsCreateBuild = async ({functionId,deploymentId,buildId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; + let apiPath = '/functions/{functionId}/deployments/{deploymentId}/build'.replace('{functionId}', functionId).replace('{deploymentId}', deploymentId); let payload = {}; + if (typeof buildId !== 'undefined') { + payload['buildId'] = buildId; + } let response = undefined; @@ -709,14 +775,49 @@ const functionsCreateBuild = async ({ functionId, deploymentId, buildId, parseOu parse(response) success() } - + + return response; + +} + +/** + * @typedef {Object} FunctionsUpdateDeploymentBuildRequestParams + * @property {string} functionId Function ID. + * @property {string} deploymentId Deployment ID. + * @property {boolean} overrideForCli + * @property {boolean} parseOutput + * @property {libClient | undefined} sdk + */ + +/** + * @param {FunctionsUpdateDeploymentBuildRequestParams} params + */ +const functionsUpdateDeploymentBuild = async ({functionId,deploymentId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; + let apiPath = '/functions/{functionId}/deployments/{deploymentId}/build'.replace('{functionId}', functionId).replace('{deploymentId}', deploymentId); + let payload = {}; + + let response = undefined; + + response = await client.call('patch', apiPath, { + 'content-type': 'application/json', + }, payload); + + if (parseOutput) { + parse(response) + success() + } + return response; + } /** * @typedef {Object} FunctionsDownloadDeploymentRequestParams * @property {string} functionId Function ID. * @property {string} deploymentId Deployment ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk * @property {string} destination @@ -725,14 +826,17 @@ const functionsCreateBuild = async ({ functionId, deploymentId, buildId, parseOu /** * @param {FunctionsDownloadDeploymentRequestParams} params */ -const functionsDownloadDeployment = async ({ functionId, deploymentId, parseOutput = true, sdk = undefined, destination}) => { - let client = !sdk ? await sdkForProject() : sdk; +const functionsDownloadDeployment = async ({functionId,deploymentId,parseOutput = true, overrideForCli = false, sdk = undefined, destination}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/functions/{functionId}/deployments/{deploymentId}/download'.replace('{functionId}', functionId).replace('{deploymentId}', deploymentId); let payload = {}; - payload['project'] = localConfig.getProject().projectId - payload['key'] = globalConfig.getKey(); - const queryParams = new URLSearchParams(payload); - apiPath = `${globalConfig.getEndpoint()}${apiPath}?${queryParams.toString()}`; + if (!overrideForCli) { + payload['project'] = localConfig.getProject().projectId + payload['key'] = globalConfig.getKey(); + const queryParams = new URLSearchParams(payload); + apiPath = `${globalConfig.getEndpoint()}${apiPath}?${queryParams.toString()}`; + } let response = undefined; @@ -740,21 +844,26 @@ const functionsDownloadDeployment = async ({ functionId, deploymentId, parseOutp 'content-type': 'application/json', }, payload, 'arraybuffer'); - fs.writeFileSync(destination, response); + if (overrideForCli) { + response = Buffer.from(response); + } + fs.writeFileSync(destination, response); if (parseOutput) { parse(response) success() } - + 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 + * @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 {string} search Search term to filter your list results. Max length: 256 chars. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -762,8 +871,9 @@ const functionsDownloadDeployment = async ({ functionId, deploymentId, parseOutp /** * @param {FunctionsListExecutionsRequestParams} params */ -const functionsListExecutions = async ({ functionId, queries, search, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const functionsListExecutions = async ({functionId,queries,search,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/functions/{functionId}/executions'.replace('{functionId}', functionId); let payload = {}; if (typeof queries !== 'undefined') { @@ -780,11 +890,16 @@ const functionsListExecutions = async ({ functionId, queries, search, parseOutpu }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('functions', 'listExecutions', functionId); + } else { + parse(response) + success() + } } - + return response; + } /** @@ -795,6 +910,8 @@ const functionsListExecutions = async ({ functionId, queries, search, parseOutpu * @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 GET. * @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. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -802,8 +919,9 @@ const functionsListExecutions = async ({ functionId, queries, search, parseOutpu /** * @param {FunctionsCreateExecutionRequestParams} params */ -const functionsCreateExecution = async ({ functionId, body, async, xpath, method, headers, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const functionsCreateExecution = async ({functionId,body,async,xpath,method,headers,scheduledAt,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/functions/{functionId}/executions'.replace('{functionId}', functionId); let payload = {}; if (typeof body !== 'undefined') { @@ -821,6 +939,9 @@ const functionsCreateExecution = async ({ functionId, body, async, xpath, method if (typeof headers !== 'undefined') { payload['headers'] = JSON.parse(headers); } + if (typeof scheduledAt !== 'undefined') { + payload['scheduledAt'] = scheduledAt; + } let response = undefined; @@ -832,14 +953,16 @@ const functionsCreateExecution = async ({ functionId, body, async, xpath, method parse(response) success() } - + 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 */ @@ -847,8 +970,9 @@ const functionsCreateExecution = async ({ functionId, body, async, xpath, method /** * @param {FunctionsGetExecutionRequestParams} params */ -const functionsGetExecution = async ({ functionId, executionId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const functionsGetExecution = async ({functionId,executionId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/functions/{functionId}/executions/{executionId}'.replace('{functionId}', functionId).replace('{executionId}', executionId); let payload = {}; @@ -858,18 +982,57 @@ const functionsGetExecution = async ({ functionId, executionId, parseOutput = tr 'content-type': 'application/json', }, payload); + if (parseOutput) { + if(console) { + showConsoleLink('functions', 'getExecution', functionId, executionId); + } else { + parse(response) + success() + } + } + + 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}) => { + let client = !sdk ? await sdkForProject() : + sdk; + let apiPath = '/functions/{functionId}/executions/{executionId}'.replace('{functionId}', functionId).replace('{executionId}', executionId); + let payload = {}; + + let response = undefined; + + response = await client.call('delete', apiPath, { + 'content-type': 'application/json', + }, payload); + if (parseOutput) { parse(response) success() } - + return response; + } /** * @typedef {Object} FunctionsGetFunctionUsageRequestParams * @property {string} functionId Function ID. * @property {FunctionUsageRange} range Date range. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -877,8 +1040,9 @@ const functionsGetExecution = async ({ functionId, executionId, parseOutput = tr /** * @param {FunctionsGetFunctionUsageRequestParams} params */ -const functionsGetFunctionUsage = async ({ functionId, range, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const functionsGetFunctionUsage = async ({functionId,range,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/functions/{functionId}/usage'.replace('{functionId}', functionId); let payload = {}; if (typeof range !== 'undefined') { @@ -892,16 +1056,22 @@ const functionsGetFunctionUsage = async ({ functionId, range, parseOutput = true }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('functions', 'getFunctionUsage', functionId); + } else { + parse(response) + success() + } } - + return response; + } /** * @typedef {Object} FunctionsListVariablesRequestParams * @property {string} functionId Function unique ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -909,8 +1079,9 @@ const functionsGetFunctionUsage = async ({ functionId, range, parseOutput = true /** * @param {FunctionsListVariablesRequestParams} params */ -const functionsListVariables = async ({ functionId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const functionsListVariables = async ({functionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/functions/{functionId}/variables'.replace('{functionId}', functionId); let payload = {}; @@ -924,8 +1095,9 @@ const functionsListVariables = async ({ functionId, parseOutput = true, sdk = un parse(response) success() } - + return response; + } /** @@ -933,6 +1105,7 @@ const functionsListVariables = async ({ functionId, parseOutput = true, sdk = un * @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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -940,8 +1113,9 @@ const functionsListVariables = async ({ functionId, parseOutput = true, sdk = un /** * @param {FunctionsCreateVariableRequestParams} params */ -const functionsCreateVariable = async ({ functionId, key, value, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const functionsCreateVariable = async ({functionId,key,value,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/functions/{functionId}/variables'.replace('{functionId}', functionId); let payload = {}; if (typeof key !== 'undefined') { @@ -961,14 +1135,16 @@ const functionsCreateVariable = async ({ functionId, key, value, parseOutput = t parse(response) success() } - + 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 */ @@ -976,8 +1152,9 @@ const functionsCreateVariable = async ({ functionId, key, value, parseOutput = t /** * @param {FunctionsGetVariableRequestParams} params */ -const functionsGetVariable = async ({ functionId, variableId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const functionsGetVariable = async ({functionId,variableId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/functions/{functionId}/variables/{variableId}'.replace('{functionId}', functionId).replace('{variableId}', variableId); let payload = {}; @@ -991,8 +1168,9 @@ const functionsGetVariable = async ({ functionId, variableId, parseOutput = true parse(response) success() } - + return response; + } /** @@ -1001,6 +1179,7 @@ const functionsGetVariable = async ({ functionId, variableId, parseOutput = true * @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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -1008,8 +1187,9 @@ const functionsGetVariable = async ({ functionId, variableId, parseOutput = true /** * @param {FunctionsUpdateVariableRequestParams} params */ -const functionsUpdateVariable = async ({ functionId, variableId, key, value, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const functionsUpdateVariable = async ({functionId,variableId,key,value,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/functions/{functionId}/variables/{variableId}'.replace('{functionId}', functionId).replace('{variableId}', variableId); let payload = {}; if (typeof key !== 'undefined') { @@ -1029,14 +1209,16 @@ const functionsUpdateVariable = async ({ functionId, variableId, key, value, par parse(response) success() } - + 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 */ @@ -1044,8 +1226,9 @@ const functionsUpdateVariable = async ({ functionId, variableId, key, value, par /** * @param {FunctionsDeleteVariableRequestParams} params */ -const functionsDeleteVariable = async ({ functionId, variableId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const functionsDeleteVariable = async ({functionId,variableId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/functions/{functionId}/variables/{variableId}'.replace('{functionId}', functionId).replace('{variableId}', variableId); let payload = {}; @@ -1059,8 +1242,9 @@ const functionsDeleteVariable = async ({ functionId, variableId, parseOutput = t parse(response) success() } - + return response; + } functions @@ -1068,6 +1252,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, deployment, schedule, scheduleNext, schedulePrevious, timeout, entrypoint, commands, installationId`) .option(`--search `, `Search term to filter your list results. Max length: 256 chars.`) + .option(`--console`, `Get the resource console url`) .action(actionRunner(functionsList)) functions @@ -1084,6 +1269,7 @@ functions .option(`--logging `, `Whether executions will be logged. When set to false, executions will not be logged, but will reduce resource used by your Appwrite project.`, parseBool) .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(`--installationId `, `Appwrite Installation ID for VCS (Version Control System) deployment.`) .option(`--providerRepositoryId `, `Repository ID of the repo linked to the function.`) .option(`--providerBranch `, `Production branch for the repo linked to the function.`) @@ -1110,6 +1296,7 @@ functions .command(`get`) .description(`Get a function by its unique ID.`) .requiredOption(`--functionId `, `Function ID.`) + .option(`--console`, `Get the resource console url`) .action(actionRunner(functionsGet)) functions @@ -1126,6 +1313,7 @@ functions .option(`--logging `, `Whether executions will be logged. When set to false, executions will not be logged, but will reduce resource used by your Appwrite project.`, parseBool) .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(`--installationId `, `Appwrite Installation ID for VCS (Version Controle System) deployment.`) .option(`--providerRepositoryId `, `Repository ID of the repo linked to the function`) .option(`--providerBranch `, `Production branch for the repo linked to the function`) @@ -1145,6 +1333,7 @@ functions .requiredOption(`--functionId `, `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: size, buildId, activate, entrypoint, commands`) .option(`--search `, `Search term to filter your list results. Max length: 256 chars.`) + .option(`--console`, `Get the resource console url`) .action(actionRunner(functionsListDeployments)) functions @@ -1162,6 +1351,7 @@ functions .description(`Get a code deployment by its unique ID.`) .requiredOption(`--functionId `, `Function ID.`) .requiredOption(`--deploymentId `, `Deployment ID.`) + .option(`--console`, `Get the resource console url`) .action(actionRunner(functionsGetDeployment)) functions @@ -1180,12 +1370,19 @@ functions functions .command(`createBuild`) - .description(`Create a new build for an Appwrite Function deployment. This endpoint can be used to retry a failed build.`) + .description(``) .requiredOption(`--functionId `, `Function ID.`) .requiredOption(`--deploymentId `, `Deployment ID.`) - .requiredOption(`--buildId `, `Build unique ID.`) + .option(`--buildId `, `Build unique ID.`) .action(actionRunner(functionsCreateBuild)) +functions + .command(`updateDeploymentBuild`) + .description(``) + .requiredOption(`--functionId `, `Function ID.`) + .requiredOption(`--deploymentId `, `Deployment ID.`) + .action(actionRunner(functionsUpdateDeploymentBuild)) + functions .command(`downloadDeployment`) .description(`Get a Deployment's contents by its unique ID. This endpoint supports range requests for partial or streaming file download.`) @@ -1198,8 +1395,9 @@ functions .command(`listExecutions`) .description(`Get a list of all the current user function execution logs. You can use the query params to filter your results.`) .requiredOption(`--functionId `, `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`) + .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(`--search `, `Search term to filter your list results. Max length: 256 chars.`) + .option(`--console`, `Get the resource console url`) .action(actionRunner(functionsListExecutions)) functions @@ -1211,6 +1409,7 @@ functions .option(`--xpath `, `HTTP path of execution. Path can include query params. Default value is /`) .option(`--method `, `HTTP method of execution. Default value is GET.`) .option(`--headers `, `HTTP headers of execution. Defaults to empty.`) + .option(`--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.`) .action(actionRunner(functionsCreateExecution)) functions @@ -1218,13 +1417,22 @@ functions .description(`Get a function execution log by its unique ID.`) .requiredOption(`--functionId `, `Function ID.`) .requiredOption(`--executionId `, `Execution ID.`) + .option(`--console`, `Get the resource console url`) .action(actionRunner(functionsGetExecution)) +functions + .command(`deleteExecution`) + .description(`Delete a function execution by its unique ID. `) + .requiredOption(`--functionId `, `Function ID.`) + .requiredOption(`--executionId `, `Execution ID.`) + .action(actionRunner(functionsDeleteExecution)) + functions .command(`getFunctionUsage`) .description(``) .requiredOption(`--functionId `, `Function ID.`) .option(`--range `, `Date range.`) + .option(`--console`, `Get the resource console url`) .action(actionRunner(functionsGetFunctionUsage)) functions @@ -1279,14 +1487,16 @@ module.exports = { functionsUpdateDeployment, functionsDeleteDeployment, functionsCreateBuild, + functionsUpdateDeploymentBuild, functionsDownloadDeployment, functionsListExecutions, functionsCreateExecution, functionsGetExecution, + functionsDeleteExecution, functionsGetFunctionUsage, functionsListVariables, functionsCreateVariable, functionsGetVariable, functionsUpdateVariable, functionsDeleteVariable -}; \ No newline at end of file +}; diff --git a/lib/commands/generic.js b/lib/commands/generic.js index b29b2b6..c6b1a4c 100644 --- a/lib/commands/generic.js +++ b/lib/commands/generic.js @@ -3,20 +3,44 @@ const { Command } = require("commander"); const Client = require("../client"); const { sdkForConsole } = require("../sdks"); const { globalConfig, localConfig } = require("../config"); -const { actionRunner, success, parseBool, commandDescriptions, log, parse } = require("../parser"); -const { questionsLogin, questionsListFactors, questionsMfaChallenge } = require("../questions"); -const { accountUpdateMfaChallenge, accountCreateMfaChallenge, accountGet, accountCreateEmailPasswordSession, accountDeleteSession } = require("./account"); +const { actionRunner, success, parseBool, commandDescriptions, error, parse, log, drawTable, cliConfig } = require("../parser"); +const ID = require("../id"); +const { questionsLogin, questionsLogout, questionsListFactors, questionsMfaChallenge } = require("../questions"); +const { accountUpdateMfaChallenge, accountCreateMfaChallenge, accountGet, accountCreateEmailPasswordSession, accountDeleteSession } = require("./account"); -const login = new Command("login") - .description(commandDescriptions['login']) - .configureHelp({ - helpWidth: process.stdout.columns || 80 - }) - .action(actionRunner(async () => { - const answers = await inquirer.prompt(questionsLogin) +const DEFAULT_ENDPOINT = 'https://cloud.appwrite.io/v1'; - let client = await sdkForConsole(false); +const loginCommand = async ({ email, password, endpoint, mfa, code }) => { + const oldCurrent = globalConfig.getCurrentSession(); + let configEndpoint = endpoint ?? DEFAULT_ENDPOINT; + + const answers = email && password ? { email, password } : await inquirer.prompt(questionsLogin); + + if (answers.method === 'select') { + const accountId = answers.accountId; + + if (!globalConfig.getSessionIds().includes(accountId)) { + throw Error('Session ID not found'); + } + + globalConfig.setCurrentSession(accountId); + success(`Current account is ${accountId}`); + + return; + } + + const id = ID.unique(); + + globalConfig.addSession(id, {}); + globalConfig.setCurrentSession(id); + globalConfig.setEndpoint(configEndpoint); + globalConfig.setEmail(answers.email); + let client = await sdkForConsole(false); + + let account; + + try { await accountCreateEmailPasswordSession({ email: answers.email, password: answers.password, @@ -26,6 +50,57 @@ const login = new Command("login") client.setCookie(globalConfig.getCookie()); + account = await accountGet({ + sdk: client, + parseOutput: false + }); + } catch (error) { + if (error.response === 'user_more_factors_required') { + const { factor } = mfa ? { factor: mfa } : await inquirer.prompt(questionsListFactors); + + const challenge = await accountCreateMfaChallenge({ + factor, + parseOutput: false, + sdk: client + }); + + const { otp } = code ? { otp: code } : await inquirer.prompt(questionsMfaChallenge); + + await accountUpdateMfaChallenge({ + challengeId: challenge.$id, + otp, + parseOutput: false, + sdk: client + }); + + account = await accountGet({ + sdk: client, + parseOutput: false + }); + } else { + globalConfig.removeSession(id); + globalConfig.setCurrentSession(oldCurrent); + if(endpoint !== DEFAULT_ENDPOINT && error.response === 'user_invalid_credentials'){ + log('Use the --endpoint option for self-hosted instances') + } + throw error; + } + } + + success("Signed in as user with ID: " + account.$id); + log("Next you can create or link to your project using 'appwrite init project'"); +}; + +const whoami = new Command("whoami") + .description(commandDescriptions['whoami']) + .action(actionRunner(async () => { + if (globalConfig.getEndpoint() === '' || globalConfig.getCookie() === '') { + error("No user is signed in. To sign in, run: appwrite login "); + return; + } + + let client = await sdkForConsole(false); + let account; try { @@ -33,43 +108,49 @@ const login = new Command("login") sdk: client, parseOutput: false }); - } catch(error) { - if (error.response === 'user_more_factors_required') { - const { factor } = await inquirer.prompt(questionsListFactors); - - const challenge = await accountCreateMfaChallenge({ - factor, - parseOutput: false, - sdk: client - }); - - const { otp } = await inquirer.prompt(questionsMfaChallenge); - - await accountUpdateMfaChallenge({ - challengeId: challenge.$id, - otp, - parseOutput: false, - sdk: client - }); - - account = await accountGet({ - sdk: client, - parseOutput: false - }); - } else { - throw error; + } catch (error) { + error("No user is signed in. To sign in, run: appwrite login"); + return; + } + + const data = [ + { + 'ID': account.$id, + 'Name': account.name, + 'Email': account.email, + 'MFA enabled': account.mfa ? 'Yes' : 'No', + 'Endpoint': globalConfig.getEndpoint() } + ]; + + if(cliConfig.json) { + console.log(data); + return; } - success("Signed in as user with ID: " + account.$id); + drawTable(data) })); -const logout = new Command("logout") - .description(commandDescriptions['logout']) +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") + .description(commandDescriptions['login']) + .option(`--email [email]`, `User email`) + .option(`--password [password]`, `User password`) + .option(`--endpoint [endpoint]`, `Appwrite endpoint for self hosted instances`) + .option(`--mfa [factor]`, `Multi-factor authentication login factor: totp, email, phone or recoveryCode`) + .option(`--code [code]`, `Multi-factor code`) .configureHelp({ helpWidth: process.stdout.columns || 80 }) - .action(actionRunner(async () => { + .action(actionRunner(loginCommand)); + +const deleteSession = async (accountId) => { + try { let client = await sdkForConsole(); await accountDeleteSession({ @@ -78,8 +159,51 @@ const logout = new Command("logout") sdk: client }) - globalConfig.setCookie(""); - success() + globalConfig.removeSession(accountId); + } catch (e) { + error('Unable to log out, removing locally saved session information') + } + globalConfig.removeSession(accountId); +} + +const logout = new Command("logout") + .description(commandDescriptions['logout']) + .configureHelp({ + helpWidth: process.stdout.columns || 80 + }) + .action(actionRunner(async () => { + const sessions = globalConfig.getSessions(); + const current = globalConfig.getCurrentSession(); + + if (current === '') { + return; + } + if (sessions.length === 1) { + await deleteSession(current); + success(); + + return; + } + + const answers = await inquirer.prompt(questionsLogout); + + if (answers.accounts) { + for (let accountId of answers.accounts) { + globalConfig.setCurrentSession(accountId); + await deleteSession(accountId); + } + } + + const remainingSessions = globalConfig.getSessions(); + + if (remainingSessions .length > 0 && remainingSessions .filter(session => session.id === current).length !== 1) { + const accountId = remainingSessions [0].id; + globalConfig.setCurrentSession(accountId); + + success(`Current account is ${accountId}`); + } + + success(); })); const client = new Command("client") @@ -87,12 +211,12 @@ const client = new Command("client") .configureHelp({ helpWidth: process.stdout.columns || 80 }) - .option("--selfSigned ", "Configure the CLI to use a self-signed certificate ( true or false )", parseBool) - .option("--endpoint ", "Set your Appwrite server endpoint") - .option("--projectId ", "Set your Appwrite project ID") - .option("--key ", "Set your Appwrite server's API key") - .option("--debug", "Print CLI debug information") - .option("--reset", "Reset the CLI configuration") + .option("-ss, --selfSigned ", "Configure the CLI to use a self-signed certificate ( true or false )", parseBool) + .option("-e, --endpoint ", "Set your Appwrite server endpoint") + .option("-p, --projectId ", "Set your Appwrite project ID") + .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) => { if (selfSigned == undefined && endpoint == undefined && projectId == undefined && key == undefined && debug == undefined && reset == undefined) { command.help() @@ -111,6 +235,7 @@ const client = new Command("client") if (endpoint !== undefined) { try { + const id = ID.unique(); let url = new URL(endpoint); if (url.protocol !== "http:" && url.protocol !== "https:") { throw new Error(); @@ -125,7 +250,8 @@ const client = new Command("client") if (!response.version) { throw new Error(); } - + globalConfig.setCurrentSession(id); + globalConfig.addSession(id, {}); globalConfig.setEndpoint(endpoint); } catch (_) { throw new Error("Invalid endpoint or your Appwrite server is not running as expected."); @@ -145,18 +271,44 @@ const client = new Command("client") } if (reset !== undefined) { - globalConfig.setEndpoint(""); - globalConfig.setKey(""); - globalConfig.setCookie(""); - globalConfig.setSelfSigned(""); - localConfig.setProject("", ""); + const sessions = globalConfig.getSessions(); + + for (let accountId of sessions.map(session => session.id)) { + globalConfig.setCurrentSession(accountId); + await deleteSession(accountId); + } } success() })); +const migrate = async () => { + if (!globalConfig.has('endpoint') || !globalConfig.has('cookie')) { + return; + } + + const endpoint = globalConfig.get('endpoint'); + const cookie = globalConfig.get('cookie'); + + const id = ID.unique(); + const data = { + endpoint, + cookie, + email: 'legacy' + }; + + globalConfig.addSession(id, data); + 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 index 2d4c360..8c6a90b 100644 --- a/lib/commands/graphql.js +++ b/lib/commands/graphql.js @@ -4,7 +4,7 @@ const tar = require("tar"); const ignore = require("ignore"); const { promisify } = require('util'); const libClient = require('../client.js'); -const { getAllFiles } = require('../utils.js'); +const { getAllFiles, showConsoleLink } = require('../utils.js'); const { Command } = require('commander'); const { sdkForProject, sdkForConsole } = require('../sdks') const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log } = require('../parser') @@ -42,6 +42,7 @@ const graphql = new Command("graphql").description(commandDescriptions['graphql' /** * @typedef {Object} GraphqlQueryRequestParams * @property {object} query The query or queries to execute. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -49,8 +50,9 @@ const graphql = new Command("graphql").description(commandDescriptions['graphql' /** * @param {GraphqlQueryRequestParams} params */ -const graphqlQuery = async ({ query, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +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') { @@ -68,13 +70,15 @@ const graphqlQuery = async ({ query, parseOutput = true, sdk = undefined}) => { parse(response) success() } - + return response; + } /** * @typedef {Object} GraphqlMutationRequestParams * @property {object} query The query or queries to execute. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -82,8 +86,9 @@ const graphqlQuery = async ({ query, parseOutput = true, sdk = undefined}) => { /** * @param {GraphqlMutationRequestParams} params */ -const graphqlMutation = async ({ query, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +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') { @@ -101,8 +106,9 @@ const graphqlMutation = async ({ query, parseOutput = true, sdk = undefined}) => parse(response) success() } - + return response; + } graphql @@ -121,4 +127,4 @@ module.exports = { graphql, graphqlQuery, graphqlMutation -}; \ No newline at end of file +}; diff --git a/lib/commands/health.js b/lib/commands/health.js index e0f6d08..9f028ee 100644 --- a/lib/commands/health.js +++ b/lib/commands/health.js @@ -4,7 +4,7 @@ const tar = require("tar"); const ignore = require("ignore"); const { promisify } = require('util'); const libClient = require('../client.js'); -const { getAllFiles } = require('../utils.js'); +const { getAllFiles, showConsoleLink } = require('../utils.js'); const { Command } = require('commander'); const { sdkForProject, sdkForConsole } = require('../sdks') const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log } = require('../parser') @@ -41,6 +41,7 @@ const health = new Command("health").description(commandDescriptions['health']). /** * @typedef {Object} HealthGetRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -48,8 +49,9 @@ const health = new Command("health").description(commandDescriptions['health']). /** * @param {HealthGetRequestParams} params */ -const healthGet = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const healthGet = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/health'; let payload = {}; @@ -63,12 +65,14 @@ const healthGet = async ({ parseOutput = true, sdk = undefined}) => { parse(response) success() } - + return response; + } /** * @typedef {Object} HealthGetAntivirusRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -76,8 +80,9 @@ const healthGet = async ({ parseOutput = true, sdk = undefined}) => { /** * @param {HealthGetAntivirusRequestParams} params */ -const healthGetAntivirus = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const healthGetAntivirus = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/health/anti-virus'; let payload = {}; @@ -91,12 +96,14 @@ const healthGetAntivirus = async ({ parseOutput = true, sdk = undefined}) => { parse(response) success() } - + return response; + } /** * @typedef {Object} HealthGetCacheRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -104,8 +111,9 @@ const healthGetAntivirus = async ({ parseOutput = true, sdk = undefined}) => { /** * @param {HealthGetCacheRequestParams} params */ -const healthGetCache = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const healthGetCache = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/health/cache'; let payload = {}; @@ -119,13 +127,15 @@ const healthGetCache = async ({ parseOutput = true, sdk = undefined}) => { parse(response) success() } - + return response; + } /** * @typedef {Object} HealthGetCertificateRequestParams * @property {string} domain string + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -133,8 +143,9 @@ const healthGetCache = async ({ parseOutput = true, sdk = undefined}) => { /** * @param {HealthGetCertificateRequestParams} params */ -const healthGetCertificate = async ({ domain, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const healthGetCertificate = async ({domain,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/health/certificate'; let payload = {}; if (typeof domain !== 'undefined') { @@ -151,12 +162,14 @@ const healthGetCertificate = async ({ domain, parseOutput = true, sdk = undefine parse(response) success() } - + return response; + } /** * @typedef {Object} HealthGetDBRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -164,8 +177,9 @@ const healthGetCertificate = async ({ domain, parseOutput = true, sdk = undefine /** * @param {HealthGetDBRequestParams} params */ -const healthGetDB = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const healthGetDB = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/health/db'; let payload = {}; @@ -179,12 +193,14 @@ const healthGetDB = async ({ parseOutput = true, sdk = undefined}) => { parse(response) success() } - + return response; + } /** * @typedef {Object} HealthGetPubSubRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -192,8 +208,9 @@ const healthGetDB = async ({ parseOutput = true, sdk = undefined}) => { /** * @param {HealthGetPubSubRequestParams} params */ -const healthGetPubSub = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const healthGetPubSub = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/health/pubsub'; let payload = {}; @@ -207,12 +224,14 @@ const healthGetPubSub = async ({ parseOutput = true, sdk = undefined}) => { parse(response) success() } - + return response; + } /** * @typedef {Object} HealthGetQueueRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -220,8 +239,9 @@ const healthGetPubSub = async ({ parseOutput = true, sdk = undefined}) => { /** * @param {HealthGetQueueRequestParams} params */ -const healthGetQueue = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const healthGetQueue = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/health/queue'; let payload = {}; @@ -235,13 +255,15 @@ const healthGetQueue = async ({ parseOutput = true, sdk = undefined}) => { parse(response) success() } - + 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 */ @@ -249,8 +271,9 @@ const healthGetQueue = async ({ parseOutput = true, sdk = undefined}) => { /** * @param {HealthGetQueueBuildsRequestParams} params */ -const healthGetQueueBuilds = async ({ threshold, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const healthGetQueueBuilds = async ({threshold,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/health/queue/builds'; let payload = {}; if (typeof threshold !== 'undefined') { @@ -267,13 +290,15 @@ const healthGetQueueBuilds = async ({ threshold, parseOutput = true, sdk = undef parse(response) success() } - + 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 */ @@ -281,8 +306,9 @@ const healthGetQueueBuilds = async ({ threshold, parseOutput = true, sdk = undef /** * @param {HealthGetQueueCertificatesRequestParams} params */ -const healthGetQueueCertificates = async ({ threshold, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const healthGetQueueCertificates = async ({threshold,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/health/queue/certificates'; let payload = {}; if (typeof threshold !== 'undefined') { @@ -299,14 +325,16 @@ const healthGetQueueCertificates = async ({ threshold, parseOutput = true, sdk = parse(response) success() } - + 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 */ @@ -314,8 +342,9 @@ const healthGetQueueCertificates = async ({ threshold, parseOutput = true, sdk = /** * @param {HealthGetQueueDatabasesRequestParams} params */ -const healthGetQueueDatabases = async ({ name, threshold, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const healthGetQueueDatabases = async ({name,threshold,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/health/queue/databases'; let payload = {}; if (typeof name !== 'undefined') { @@ -335,13 +364,15 @@ const healthGetQueueDatabases = async ({ name, threshold, parseOutput = true, sd parse(response) success() } - + 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 */ @@ -349,8 +380,9 @@ const healthGetQueueDatabases = async ({ name, threshold, parseOutput = true, sd /** * @param {HealthGetQueueDeletesRequestParams} params */ -const healthGetQueueDeletes = async ({ threshold, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const healthGetQueueDeletes = async ({threshold,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/health/queue/deletes'; let payload = {}; if (typeof threshold !== 'undefined') { @@ -367,14 +399,16 @@ const healthGetQueueDeletes = async ({ threshold, parseOutput = true, sdk = unde parse(response) success() } - + 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 */ @@ -382,8 +416,9 @@ const healthGetQueueDeletes = async ({ threshold, parseOutput = true, sdk = unde /** * @param {HealthGetFailedJobsRequestParams} params */ -const healthGetFailedJobs = async ({ name, threshold, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const healthGetFailedJobs = async ({name,threshold,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/health/queue/failed/{name}'.replace('{name}', name); let payload = {}; if (typeof threshold !== 'undefined') { @@ -400,13 +435,15 @@ const healthGetFailedJobs = async ({ name, threshold, parseOutput = true, sdk = parse(response) success() } - + 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 */ @@ -414,8 +451,9 @@ const healthGetFailedJobs = async ({ name, threshold, parseOutput = true, sdk = /** * @param {HealthGetQueueFunctionsRequestParams} params */ -const healthGetQueueFunctions = async ({ threshold, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const healthGetQueueFunctions = async ({threshold,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/health/queue/functions'; let payload = {}; if (typeof threshold !== 'undefined') { @@ -432,13 +470,15 @@ const healthGetQueueFunctions = async ({ threshold, parseOutput = true, sdk = un parse(response) success() } - + 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 */ @@ -446,8 +486,9 @@ const healthGetQueueFunctions = async ({ threshold, parseOutput = true, sdk = un /** * @param {HealthGetQueueLogsRequestParams} params */ -const healthGetQueueLogs = async ({ threshold, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const healthGetQueueLogs = async ({threshold,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/health/queue/logs'; let payload = {}; if (typeof threshold !== 'undefined') { @@ -464,13 +505,15 @@ const healthGetQueueLogs = async ({ threshold, parseOutput = true, sdk = undefin parse(response) success() } - + 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 */ @@ -478,8 +521,9 @@ const healthGetQueueLogs = async ({ threshold, parseOutput = true, sdk = undefin /** * @param {HealthGetQueueMailsRequestParams} params */ -const healthGetQueueMails = async ({ threshold, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const healthGetQueueMails = async ({threshold,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/health/queue/mails'; let payload = {}; if (typeof threshold !== 'undefined') { @@ -496,13 +540,15 @@ const healthGetQueueMails = async ({ threshold, parseOutput = true, sdk = undefi parse(response) success() } - + 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 */ @@ -510,8 +556,9 @@ const healthGetQueueMails = async ({ threshold, parseOutput = true, sdk = undefi /** * @param {HealthGetQueueMessagingRequestParams} params */ -const healthGetQueueMessaging = async ({ threshold, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const healthGetQueueMessaging = async ({threshold,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/health/queue/messaging'; let payload = {}; if (typeof threshold !== 'undefined') { @@ -528,13 +575,15 @@ const healthGetQueueMessaging = async ({ threshold, parseOutput = true, sdk = un parse(response) success() } - + 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 */ @@ -542,8 +591,9 @@ const healthGetQueueMessaging = async ({ threshold, parseOutput = true, sdk = un /** * @param {HealthGetQueueMigrationsRequestParams} params */ -const healthGetQueueMigrations = async ({ threshold, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const healthGetQueueMigrations = async ({threshold,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/health/queue/migrations'; let payload = {}; if (typeof threshold !== 'undefined') { @@ -560,13 +610,15 @@ const healthGetQueueMigrations = async ({ threshold, parseOutput = true, sdk = u parse(response) success() } - + 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 */ @@ -574,8 +626,9 @@ const healthGetQueueMigrations = async ({ threshold, parseOutput = true, sdk = u /** * @param {HealthGetQueueUsageRequestParams} params */ -const healthGetQueueUsage = async ({ threshold, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const healthGetQueueUsage = async ({threshold,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/health/queue/usage'; let payload = {}; if (typeof threshold !== 'undefined') { @@ -592,13 +645,15 @@ const healthGetQueueUsage = async ({ threshold, parseOutput = true, sdk = undefi parse(response) success() } - + return response; + } /** * @typedef {Object} HealthGetQueueUsageDumpRequestParams * @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 */ @@ -606,8 +661,9 @@ const healthGetQueueUsage = async ({ threshold, parseOutput = true, sdk = undefi /** * @param {HealthGetQueueUsageDumpRequestParams} params */ -const healthGetQueueUsageDump = async ({ threshold, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const healthGetQueueUsageDump = async ({threshold,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/health/queue/usage-dump'; let payload = {}; if (typeof threshold !== 'undefined') { @@ -624,13 +680,15 @@ const healthGetQueueUsageDump = async ({ threshold, parseOutput = true, sdk = un parse(response) success() } - + 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 */ @@ -638,8 +696,9 @@ const healthGetQueueUsageDump = async ({ threshold, parseOutput = true, sdk = un /** * @param {HealthGetQueueWebhooksRequestParams} params */ -const healthGetQueueWebhooks = async ({ threshold, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const healthGetQueueWebhooks = async ({threshold,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/health/queue/webhooks'; let payload = {}; if (typeof threshold !== 'undefined') { @@ -656,12 +715,14 @@ const healthGetQueueWebhooks = async ({ threshold, parseOutput = true, sdk = und parse(response) success() } - + return response; + } /** * @typedef {Object} HealthGetStorageRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -669,8 +730,9 @@ const healthGetQueueWebhooks = async ({ threshold, parseOutput = true, sdk = und /** * @param {HealthGetStorageRequestParams} params */ -const healthGetStorage = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const healthGetStorage = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/health/storage'; let payload = {}; @@ -684,12 +746,14 @@ const healthGetStorage = async ({ parseOutput = true, sdk = undefined}) => { parse(response) success() } - + return response; + } /** * @typedef {Object} HealthGetStorageLocalRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -697,8 +761,9 @@ const healthGetStorage = async ({ parseOutput = true, sdk = undefined}) => { /** * @param {HealthGetStorageLocalRequestParams} params */ -const healthGetStorageLocal = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const healthGetStorageLocal = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/health/storage/local'; let payload = {}; @@ -712,12 +777,14 @@ const healthGetStorageLocal = async ({ parseOutput = true, sdk = undefined}) => parse(response) success() } - + return response; + } /** * @typedef {Object} HealthGetTimeRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -725,8 +792,9 @@ const healthGetStorageLocal = async ({ parseOutput = true, sdk = undefined}) => /** * @param {HealthGetTimeRequestParams} params */ -const healthGetTime = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const healthGetTime = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/health/time'; let payload = {}; @@ -740,8 +808,9 @@ const healthGetTime = async ({ parseOutput = true, sdk = undefined}) => { parse(response) success() } - + return response; + } health @@ -900,4 +969,4 @@ module.exports = { healthGetStorage, healthGetStorageLocal, healthGetTime -}; \ No newline at end of file +}; diff --git a/lib/commands/init.js b/lib/commands/init.js index 706ed97..ebd74e8 100644 --- a/lib/commands/init.js +++ b/lib/commands/init.js @@ -3,58 +3,188 @@ const path = require("path"); const childProcess = require('child_process'); const { Command } = require("commander"); const inquirer = require("inquirer"); -const { teamsCreate, teamsList } = require("./teams"); -const { projectsCreate } = require("./projects"); +const { fetch } = require("undici"); +const { projectsCreate, projectsGet } = require("./projects"); +const { storageCreateBucket } = require("./storage"); +const { messagingCreateTopic } = require("./messaging"); const { functionsCreate } = require("./functions"); -const { databasesGet, databasesListCollections, databasesList } = require("./databases"); -const { storageListBuckets } = require("./storage"); +const { databasesCreateCollection } = require("./databases"); +const ID = require("../id"); +const { localConfig, globalConfig } = require("../config"); +const { + questionsCreateFunction, + questionsCreateFunctionSelectTemplate, + questionsCreateBucket, + questionsCreateMessagingTopic, + questionsCreateCollection, + questionsInitProject, + questionsInitResources, + questionsCreateTeam +} = require("../questions"); +const { success, log, error, actionRunner, commandDescriptions } = require("../parser"); +const { accountGet } = require("./account"); const { sdkForConsole } = require("../sdks"); -const { localConfig } = require("../config"); -const { paginate } = require("../paginate"); -const { questionsInitProject, questionsInitFunction, questionsInitCollection } = require("../questions"); -const { success, log, actionRunner, commandDescriptions } = require("../parser"); -const init = new Command("init") - .description(commandDescriptions['init']) - .configureHelp({ - helpWidth: process.stdout.columns || 80 - }) - .action(actionRunner(async (_options, command) => { - command.help(); - })); - -const initProject = async () => { - let response = {} - const answers = await inquirer.prompt(questionsInitProject) - if (!answers.project) process.exit(1) - - let sdk = await sdkForConsole(); - if (answers.start === "new") { - response = await teamsCreate({ - teamId: 'unique()', - name: answers.project, - sdk, - parseOutput: false - }) +const initResources = async () => { + const actions = { + function: initFunction, + collection: initCollection, + bucket: initBucket, + team: initTeam, + message: initTopic + } + + const answers = await inquirer.prompt(questionsInitResources[0]); + + const action = actions[answers.resource]; + if (action !== undefined) { + await action({ returnOnZero: true }); + } +}; + +const initProject = async ({ organizationId, projectId, projectName } = {}) => { + let response = {}; + + try { + if (globalConfig.getEndpoint() === '' || globalConfig.getCookie() === '') { + throw ''; + } + const client = await sdkForConsole(); + + await accountGet({ + parseOutput: false, + sdk: client + }); + } catch (e) { + error('Error Session not found. Please run `appwrite login` to create a session'); + process.exit(1); + } + + let answers = {}; + + if (!organizationId && !projectId && !projectName) { + answers = await inquirer.prompt(questionsInitProject) + if (answers.override === false) { + process.exit(1) + } + } else { + answers.start = 'existing'; + answers.project = {}; + answers.organization = {}; + + answers.organization = organizationId ?? (await inquirer.prompt(questionsInitProject[2])).organization; + answers.project.name = projectName ?? (await inquirer.prompt(questionsInitProject[3])).project; + answers.project = projectId ?? (await inquirer.prompt(questionsInitProject[4])).id; + + try { + await projectsGet({ projectId, parseOutput: false }); + } catch (e) { + if (e.code === 404) { + answers.start = 'new'; + answers.id = answers.project; + answers.project = answers.project.name; + } else { + throw e; + } + } + } - let teamId = response['$id']; + if (answers.start === 'new') { response = await projectsCreate({ projectId: answers.id, name: answers.project, - teamId, + teamId: answers.organization, parseOutput: false }) - localConfig.setProject(response['$id'], response.name); + localConfig.setProject(response['$id']); } else { - localConfig.setProject(answers.project.id, answers.project.name); + localConfig.setProject(answers.project); + } + + success(`Project successfully ${answers.start === 'existing' ? 'linked' : 'created'}. Details are now stored in appwrite.json file.`); + + log("Next you can use 'appwrite init' to create resources in your project, or use 'appwrite pull' and 'appwite push' to synchronize your project.") + + if(answers.start === 'existing') { + log("Since you connected to an existing project, we highly recommend to run 'appwrite pull all' to synchronize all of your existing resources."); } - success(); } +const initBucket = async () => { + const answers = await inquirer.prompt(questionsCreateBucket) + + localConfig.addBucket({ + $id: answers.id === 'unique()' ? ID.unique() : answers.id, + name: answers.bucket, + fileSecurity: answers.fileSecurity.toLowerCase() === 'yes', + enabled: true, + }); + success(); + log("Next you can use 'appwrite push bucket' to deploy the changes."); +}; + +const initTeam = async () => { + const answers = await inquirer.prompt(questionsCreateTeam) + + localConfig.addTeam({ + $id: answers.id === 'unique()' ? ID.unique() : answers.id, + name: answers.bucket, + }); + + success(); + log("Next you can use 'appwrite push team' to deploy the changes."); +}; + +const initCollection = async () => { + const answers = await inquirer.prompt(questionsCreateCollection) + const newDatabase = (answers.method ?? '').toLowerCase() !== 'existing'; + + if (!newDatabase) { + answers.databaseId = answers.database; + answers.databaseName = localConfig.getDatabase(answers.database).name; + } + + const databaseId = answers.databaseId === 'unique()' ? ID.unique() : answers.databaseId; + + if (newDatabase || !localConfig.getDatabase(answers.databaseId)) { + localConfig.addDatabase({ + $id: databaseId, + name: answers.databaseName, + enabled: true + }); + } + + localConfig.addCollection({ + $id: answers.id === 'unique()' ? ID.unique() : answers.id, + databaseId: databaseId, + name: answers.collection, + documentSecurity: answers.documentSecurity.toLowerCase() === 'yes', + attributes: [], + indexes: [], + enabled: true, + }); + + success(); + log("Next you can use 'appwrite push collection' to deploy the changes."); +}; + +const initTopic = async () => { + const answers = await inquirer.prompt(questionsCreateMessagingTopic) + + localConfig.addMessagingTopic({ + $id: answers.id === 'unique()' ? ID.unique() : answers.id, + name: answers.topic, + + }); + + success(); + log("Next you can use 'appwrite push topic' to deploy the changes."); +}; + const initFunction = async () => { // TODO: Add CI/CD support (ID, name, runtime) - const answers = await inquirer.prompt(questionsInitFunction) + const answers = await inquirer.prompt(questionsCreateFunction) const functionFolder = path.join(process.cwd(), 'functions'); if (!fs.existsSync(functionFolder)) { @@ -63,34 +193,46 @@ const initFunction = async () => { }); } - const functionDir = path.join(functionFolder, answers.name); + const functionId = answers.id === 'unique()' ? ID.unique() : answers.id; + const functionDir = path.join(functionFolder, functionId); + const templatesDir = path.join(functionFolder, `${functionId}-templates`); + const runtimeDir = path.join(templatesDir, answers.runtime.name); if (fs.existsSync(functionDir)) { - throw new Error(`( ${answers.name} ) already exists in the current directory. Please choose another name.`); + throw new Error(`( ${functionId} ) already exists in the current directory. Please choose another name.`); } if (!answers.runtime.entrypoint) { - log(`Entrypoint for this runtime not found. You will be asked to configure entrypoint when you first deploy the function.`); + log(`Entrypoint for this runtime not found. You will be asked to configure entrypoint when you first push the function.`); } if (!answers.runtime.commands) { - log(`Installation command for this runtime not found. You will be asked to configure the install command when you first deploy the function.`); + log(`Installation command for this runtime not found. You will be asked to configure the install command when you first push the function.`); } - let response = await functionsCreate({ - functionId: answers.id, - name: answers.name, - runtime: answers.runtime.id, - entrypoint: answers.runtime.entrypoint || '', - commands: answers.runtime.commands || '', - parseOutput: false - }) fs.mkdirSync(functionDir, "777"); + fs.mkdirSync(templatesDir, "777"); + const repo = "https://github.com/appwrite/templates"; + const api = `https://api.github.com/repos/appwrite/templates/contents/${answers.runtime.name}` + const templates = ['starter']; + let selected = undefined; + + try { + const res = await fetch(api); + templates.push(...(await res.json()).map((template) => template.name)); - let gitInitCommands = "git clone -b v3 --single-branch --depth 1 --sparse https://github.com/appwrite/functions-starter ."; // depth prevents fetching older commits reducing the amount fetched + selected = await inquirer.prompt(questionsCreateFunctionSelectTemplate(templates)) + } catch { + // Not a problem will go with directory pulling + log('Loading templates...'); + } + + const sparse = (selected ? `${answers.runtime.name}/${selected.template}` : answers.runtime.name).toLowerCase(); - let gitPullCommands = `git sparse-checkout add ${answers.runtime.id}`; + let gitInitCommands = `git clone --single-branch --depth 1 --sparse ${repo} .`; // depth prevents fetching older commits reducing the amount fetched + + let gitPullCommands = `git sparse-checkout add ${sparse}`; /* Force use CMD as powershell does not support && */ if (process.platform === 'win32') { @@ -100,8 +242,8 @@ const initFunction = async () => { /* Execute the child process but do not print any std output */ try { - childProcess.execSync(gitInitCommands, { stdio: 'pipe', cwd: functionDir }); - childProcess.execSync(gitPullCommands, { stdio: 'pipe', cwd: functionDir }); + childProcess.execSync(gitInitCommands, { stdio: 'pipe', cwd: templatesDir }); + childProcess.execSync(gitPullCommands, { stdio: 'pipe', cwd: templatesDir }); } catch (error) { /* Specialised errors with recommended actions to take */ if (error.message.includes('error: unknown option')) { @@ -113,7 +255,18 @@ const initFunction = async () => { } } - fs.rmSync(path.join(functionDir, ".git"), { recursive: true }); + fs.rmSync(path.join(templatesDir, ".git"), { recursive: true }); + if (!selected) { + templates.push(...fs.readdirSync(runtimeDir, { withFileTypes: true }) + .filter(item => item.isDirectory() && item.name !== 'starter') + .map(dirent => dirent.name)); + selected = { template: 'starter' }; + + if (templates.length > 1) { + selected = await inquirer.prompt(questionsCreateFunctionSelectTemplate(templates)) + } + } + const copyRecursiveSync = (src, dest) => { let exists = fs.existsSync(src); let stats = exists && fs.statSync(src); @@ -130,11 +283,11 @@ const initFunction = async () => { fs.copyFileSync(src, dest); } }; - copyRecursiveSync(path.join(functionDir, answers.runtime.id), functionDir); + copyRecursiveSync(path.join(runtimeDir, selected.template), functionDir); - fs.rmSync(`${functionDir}/${answers.runtime.id}`, { recursive: true, force: true }); + fs.rmSync(templatesDir, { recursive: true, force: true }); - const readmePath = path.join(process.cwd(), 'functions', answers.name, 'README.md'); + const readmePath = path.join(process.cwd(), 'functions', functionId, 'README.md'); const readmeFile = fs.readFileSync(readmePath).toString(); const newReadmeFile = readmeFile.split('\n'); newReadmeFile[0] = `# ${answers.name}`; @@ -142,125 +295,67 @@ const initFunction = async () => { fs.writeFileSync(readmePath, newReadmeFile.join('\n')); let data = { - $id: response['$id'], - name: response.name, - runtime: response.runtime, - execute: response.execute, - events: response.events, - schedule: response.schedule, - timeout: response.timeout, - enabled: response.enabled, - logging: response.logging, - entrypoint: response.entrypoint, - commands: response.commands, + $id: functionId, + name: answers.name, + runtime: answers.runtime.id, + execute: [], + events: [], + schedule: "", + timeout: 15, + enabled: true, + logging: true, + entrypoint: answers.runtime.entrypoint || '', + commands: answers.runtime.commands || '', ignore: answers.runtime.ignore || null, - path: `functions/${answers.name}`, + path: `functions/${functionId}`, }; localConfig.addFunction(data); success(); + log("Next you can use 'appwrite run function' to develop a function locally. To deploy the function, use 'appwrite push function'"); } -const initCollection = async ({ all, databaseId } = {}) => { - const databaseIds = []; - - if (databaseId) { - databaseIds.push(databaseId); - } else if (all) { - let allDatabases = await databasesList({ - parseOutput: false - }) - - databaseIds.push(...allDatabases.databases.map((d) => d.$id)); - } - - if (databaseIds.length <= 0) { - let answers = await inquirer.prompt(questionsInitCollection) - if (!answers.databases) process.exit(1) - databaseIds.push(...answers.databases); - } - - for (const databaseId of databaseIds) { - const database = await databasesGet({ - databaseId, - parseOutput: false - }); - - localConfig.addDatabase(database); - - const { collections, total } = await paginate(databasesListCollections, { - databaseId, - parseOutput: false - }, 100, 'collections'); - - log(`Found ${total} collections`); - - collections.forEach(async collection => { - log(`Fetching ${collection.name} ...`); - localConfig.addCollection({ - ...collection, - '$createdAt': undefined, - '$updatedAt': undefined, - }); - }); - } - - success(); -} - -const initBucket = async () => { - const { buckets } = await paginate(storageListBuckets, { parseOutput: false }, 100, 'buckets'); - - log(`Found ${buckets.length} buckets`); - - buckets.forEach(async bucket => { - log(`Fetching ${bucket.name} ...`); - localConfig.addBucket(bucket); - }); - - success(); -} - -const initTeam = async () => { - const { teams } = await paginate(teamsList, { parseOutput: false }, 100, 'teams'); - - log(`Found ${teams.length} teams`); - - teams.forEach(async team => { - log(`Fetching ${team.name} ...`); - const { total, $updatedAt, $createdAt, prefs, ...rest } = team; - localConfig.addTeam(rest); - }); - - success(); -} +const init = new Command("init") + .description(commandDescriptions['init']) + .action(actionRunner(initResources)); init .command("project") - .description("Initialise your Appwrite project") + .description("Init a new Appwrite project") + .option("--organizationId ", "Appwrite organization ID") + .option("--projectId ", "Appwrite project ID") + .option("--projectName ", "Appwrite project ID") .action(actionRunner(initProject)); init .command("function") - .description("Initialise your Appwrite cloud function") - .action(actionRunner(initFunction)) - -init - .command("collection") - .description("Initialise your Appwrite collections") - .option(`--databaseId `, `Database ID`) - .option(`--all`, `Flag to initialize all databases`) - .action(actionRunner(initCollection)) + .alias("functions") + .description("Init a new Appwrite function") + .action(actionRunner(initFunction)); init .command("bucket") - .description("Initialise your Appwrite buckets") - .action(actionRunner(initBucket)) + .alias("buckets") + .description("Init a new Appwrite bucket") + .action(actionRunner(initBucket)); init .command("team") - .description("Initialise your Appwrite teams") - .action(actionRunner(initTeam)) + .alias("teams") + .description("Init a new Appwrite team") + .action(actionRunner(initTeam)); + +init + .command("collection") + .alias("collections") + .description("Init a new Appwrite collection") + .action(actionRunner(initCollection)); + +init + .command("topic") + .alias("topics") + .description("Init a new Appwrite topic") + .action(actionRunner(initTopic)); module.exports = { init, diff --git a/lib/commands/locale.js b/lib/commands/locale.js index 50a9421..ef02bf9 100644 --- a/lib/commands/locale.js +++ b/lib/commands/locale.js @@ -4,7 +4,7 @@ const tar = require("tar"); const ignore = require("ignore"); const { promisify } = require('util'); const libClient = require('../client.js'); -const { getAllFiles } = require('../utils.js'); +const { getAllFiles, showConsoleLink } = require('../utils.js'); const { Command } = require('commander'); const { sdkForProject, sdkForConsole } = require('../sdks') const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log } = require('../parser') @@ -41,6 +41,7 @@ const locale = new Command("locale").description(commandDescriptions['locale']). /** * @typedef {Object} LocaleGetRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -48,8 +49,9 @@ const locale = new Command("locale").description(commandDescriptions['locale']). /** * @param {LocaleGetRequestParams} params */ -const localeGet = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const localeGet = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/locale'; let payload = {}; @@ -63,12 +65,14 @@ const localeGet = async ({ parseOutput = true, sdk = undefined}) => { parse(response) success() } - + return response; + } /** * @typedef {Object} LocaleListCodesRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -76,8 +80,9 @@ const localeGet = async ({ parseOutput = true, sdk = undefined}) => { /** * @param {LocaleListCodesRequestParams} params */ -const localeListCodes = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const localeListCodes = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/locale/codes'; let payload = {}; @@ -91,12 +96,14 @@ const localeListCodes = async ({ parseOutput = true, sdk = undefined}) => { parse(response) success() } - + return response; + } /** * @typedef {Object} LocaleListContinentsRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -104,8 +111,9 @@ const localeListCodes = async ({ parseOutput = true, sdk = undefined}) => { /** * @param {LocaleListContinentsRequestParams} params */ -const localeListContinents = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const localeListContinents = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/locale/continents'; let payload = {}; @@ -119,12 +127,14 @@ const localeListContinents = async ({ parseOutput = true, sdk = undefined}) => { parse(response) success() } - + return response; + } /** * @typedef {Object} LocaleListCountriesRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -132,8 +142,9 @@ const localeListContinents = async ({ parseOutput = true, sdk = undefined}) => { /** * @param {LocaleListCountriesRequestParams} params */ -const localeListCountries = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const localeListCountries = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/locale/countries'; let payload = {}; @@ -147,12 +158,14 @@ const localeListCountries = async ({ parseOutput = true, sdk = undefined}) => { parse(response) success() } - + return response; + } /** * @typedef {Object} LocaleListCountriesEURequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -160,8 +173,9 @@ const localeListCountries = async ({ parseOutput = true, sdk = undefined}) => { /** * @param {LocaleListCountriesEURequestParams} params */ -const localeListCountriesEU = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const localeListCountriesEU = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/locale/countries/eu'; let payload = {}; @@ -175,12 +189,14 @@ const localeListCountriesEU = async ({ parseOutput = true, sdk = undefined}) => parse(response) success() } - + return response; + } /** * @typedef {Object} LocaleListCountriesPhonesRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -188,8 +204,9 @@ const localeListCountriesEU = async ({ parseOutput = true, sdk = undefined}) => /** * @param {LocaleListCountriesPhonesRequestParams} params */ -const localeListCountriesPhones = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const localeListCountriesPhones = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/locale/countries/phones'; let payload = {}; @@ -203,12 +220,14 @@ const localeListCountriesPhones = async ({ parseOutput = true, sdk = undefined}) parse(response) success() } - + return response; + } /** * @typedef {Object} LocaleListCurrenciesRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -216,8 +235,9 @@ const localeListCountriesPhones = async ({ parseOutput = true, sdk = undefined}) /** * @param {LocaleListCurrenciesRequestParams} params */ -const localeListCurrencies = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const localeListCurrencies = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/locale/currencies'; let payload = {}; @@ -231,12 +251,14 @@ const localeListCurrencies = async ({ parseOutput = true, sdk = undefined}) => { parse(response) success() } - + return response; + } /** * @typedef {Object} LocaleListLanguagesRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -244,8 +266,9 @@ const localeListCurrencies = async ({ parseOutput = true, sdk = undefined}) => { /** * @param {LocaleListLanguagesRequestParams} params */ -const localeListLanguages = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const localeListLanguages = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/locale/languages'; let payload = {}; @@ -259,8 +282,9 @@ const localeListLanguages = async ({ parseOutput = true, sdk = undefined}) => { parse(response) success() } - + return response; + } locale @@ -313,4 +337,4 @@ module.exports = { localeListCountriesPhones, localeListCurrencies, localeListLanguages -}; \ No newline at end of file +}; diff --git a/lib/commands/messaging.js b/lib/commands/messaging.js index f61ac9e..4093463 100644 --- a/lib/commands/messaging.js +++ b/lib/commands/messaging.js @@ -4,7 +4,7 @@ const tar = require("tar"); const ignore = require("ignore"); const { promisify } = require('util'); const libClient = require('../client.js'); -const { getAllFiles } = require('../utils.js'); +const { getAllFiles, showConsoleLink } = require('../utils.js'); const { Command } = require('commander'); const { sdkForProject, sdkForConsole } = require('../sdks') const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log } = require('../parser') @@ -43,6 +43,7 @@ const messaging = new Command("messaging").description(commandDescriptions['mess * @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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -50,8 +51,9 @@ const messaging = new Command("messaging").description(commandDescriptions['mess /** * @param {MessagingListMessagesRequestParams} params */ -const messagingListMessages = async ({ queries, search, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingListMessages = async ({queries,search,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/messages'; let payload = {}; if (typeof queries !== 'undefined') { @@ -68,11 +70,16 @@ const messagingListMessages = async ({ queries, search, parseOutput = true, sdk }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('messaging', 'listMessages'); + } else { + parse(response) + success() + } } - + return response; + } /** @@ -89,6 +96,7 @@ const messagingListMessages = async ({ queries, search, parseOutput = true, sdk * @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 */ @@ -96,8 +104,9 @@ const messagingListMessages = async ({ queries, search, parseOutput = true, sdk /** * @param {MessagingCreateEmailRequestParams} params */ -const messagingCreateEmail = async ({ messageId, subject, content, topics, users, targets, cc, bcc, attachments, draft, html, scheduledAt, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingCreateEmail = async ({messageId,subject,content,topics,users,targets,cc,bcc,attachments,draft,html,scheduledAt,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/messages/email'; let payload = {}; if (typeof messageId !== 'undefined') { @@ -153,8 +162,9 @@ const messagingCreateEmail = async ({ messageId, subject, content, topics, users parse(response) success() } - + return response; + } /** @@ -171,6 +181,7 @@ const messagingCreateEmail = async ({ messageId, subject, content, topics, users * @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 */ @@ -178,8 +189,9 @@ const messagingCreateEmail = async ({ messageId, subject, content, topics, users /** * @param {MessagingUpdateEmailRequestParams} params */ -const messagingUpdateEmail = async ({ messageId, topics, users, targets, subject, content, draft, html, cc, bcc, scheduledAt, attachments, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingUpdateEmail = async ({messageId,topics,users,targets,subject,content,draft,html,cc,bcc,scheduledAt,attachments,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/messages/email/{messageId}'.replace('{messageId}', messageId); let payload = {}; topics = topics === true ? [] : topics; @@ -232,8 +244,9 @@ const messagingUpdateEmail = async ({ messageId, topics, users, targets, subject parse(response) success() } - + return response; + } /** @@ -254,6 +267,7 @@ const messagingUpdateEmail = async ({ messageId, topics, users, targets, subject * @property {string} 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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -261,8 +275,9 @@ const messagingUpdateEmail = async ({ messageId, topics, users, targets, subject /** * @param {MessagingCreatePushRequestParams} params */ -const messagingCreatePush = async ({ messageId, title, body, topics, users, targets, data, action, image, icon, sound, color, tag, badge, draft, scheduledAt, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingCreatePush = async ({messageId,title,body,topics,users,targets,data,action,image,icon,sound,color,tag,badge,draft,scheduledAt,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/messages/push'; let payload = {}; if (typeof messageId !== 'undefined') { @@ -327,8 +342,9 @@ const messagingCreatePush = async ({ messageId, title, body, topics, users, targ parse(response) success() } - + return response; + } /** @@ -349,6 +365,7 @@ const messagingCreatePush = async ({ messageId, title, body, topics, users, targ * @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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -356,8 +373,9 @@ const messagingCreatePush = async ({ messageId, title, body, topics, users, targ /** * @param {MessagingUpdatePushRequestParams} params */ -const messagingUpdatePush = async ({ messageId, topics, users, targets, title, body, data, action, image, icon, sound, color, tag, badge, draft, scheduledAt, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingUpdatePush = async ({messageId,topics,users,targets,title,body,data,action,image,icon,sound,color,tag,badge,draft,scheduledAt,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/messages/push/{messageId}'.replace('{messageId}', messageId); let payload = {}; topics = topics === true ? [] : topics; @@ -419,8 +437,9 @@ const messagingUpdatePush = async ({ messageId, topics, users, targets, title, b parse(response) success() } - + return response; + } /** @@ -432,6 +451,7 @@ const messagingUpdatePush = async ({ messageId, topics, users, targets, title, b * @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 */ @@ -439,8 +459,9 @@ const messagingUpdatePush = async ({ messageId, topics, users, targets, title, b /** * @param {MessagingCreateSmsRequestParams} params */ -const messagingCreateSms = async ({ messageId, content, topics, users, targets, draft, scheduledAt, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingCreateSms = async ({messageId,content,topics,users,targets,draft,scheduledAt,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/messages/sms'; let payload = {}; if (typeof messageId !== 'undefined') { @@ -478,8 +499,9 @@ const messagingCreateSms = async ({ messageId, content, topics, users, targets, parse(response) success() } - + return response; + } /** @@ -491,6 +513,7 @@ const messagingCreateSms = async ({ messageId, content, topics, users, targets, * @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 */ @@ -498,8 +521,9 @@ const messagingCreateSms = async ({ messageId, content, topics, users, targets, /** * @param {MessagingUpdateSmsRequestParams} params */ -const messagingUpdateSms = async ({ messageId, topics, users, targets, content, draft, scheduledAt, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingUpdateSms = async ({messageId,topics,users,targets,content,draft,scheduledAt,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/messages/sms/{messageId}'.replace('{messageId}', messageId); let payload = {}; topics = topics === true ? [] : topics; @@ -534,13 +558,15 @@ const messagingUpdateSms = async ({ messageId, topics, users, targets, content, parse(response) success() } - + return response; + } /** * @typedef {Object} MessagingGetMessageRequestParams * @property {string} messageId Message ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -548,8 +574,9 @@ const messagingUpdateSms = async ({ messageId, topics, users, targets, content, /** * @param {MessagingGetMessageRequestParams} params */ -const messagingGetMessage = async ({ messageId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingGetMessage = async ({messageId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/messages/{messageId}'.replace('{messageId}', messageId); let payload = {}; @@ -560,16 +587,22 @@ const messagingGetMessage = async ({ messageId, parseOutput = true, sdk = undefi }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('messaging', 'getMessage', messageId); + } else { + parse(response) + success() + } } - + return response; + } /** * @typedef {Object} MessagingDeleteRequestParams * @property {string} messageId Message ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -577,8 +610,9 @@ const messagingGetMessage = async ({ messageId, parseOutput = true, sdk = undefi /** * @param {MessagingDeleteRequestParams} params */ -const messagingDelete = async ({ messageId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingDelete = async ({messageId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/messages/{messageId}'.replace('{messageId}', messageId); let payload = {}; @@ -592,14 +626,16 @@ const messagingDelete = async ({ messageId, parseOutput = true, sdk = undefined} parse(response) success() } - + 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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -607,8 +643,9 @@ const messagingDelete = async ({ messageId, parseOutput = true, sdk = undefined} /** * @param {MessagingListMessageLogsRequestParams} params */ -const messagingListMessageLogs = async ({ messageId, queries, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingListMessageLogs = async ({messageId,queries,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/messages/{messageId}/logs'.replace('{messageId}', messageId); let payload = {}; if (typeof queries !== 'undefined') { @@ -622,17 +659,23 @@ const messagingListMessageLogs = async ({ messageId, queries, parseOutput = true }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('messaging', 'listMessageLogs', messageId); + } else { + parse(response) + success() + } } - + 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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -640,8 +683,9 @@ const messagingListMessageLogs = async ({ messageId, queries, parseOutput = true /** * @param {MessagingListTargetsRequestParams} params */ -const messagingListTargets = async ({ messageId, queries, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingListTargets = async ({messageId,queries,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/messages/{messageId}/targets'.replace('{messageId}', messageId); let payload = {}; if (typeof queries !== 'undefined') { @@ -658,14 +702,16 @@ const messagingListTargets = async ({ messageId, queries, parseOutput = true, sd parse(response) success() } - + 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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -673,8 +719,9 @@ const messagingListTargets = async ({ messageId, queries, parseOutput = true, sd /** * @param {MessagingListProvidersRequestParams} params */ -const messagingListProviders = async ({ queries, search, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingListProviders = async ({queries,search,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/providers'; let payload = {}; if (typeof queries !== 'undefined') { @@ -691,11 +738,16 @@ const messagingListProviders = async ({ queries, search, parseOutput = true, sdk }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('messaging', 'listProviders'); + } else { + parse(response) + success() + } } - + return response; + } /** @@ -708,6 +760,7 @@ const messagingListProviders = async ({ queries, search, parseOutput = true, sdk * @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 */ @@ -715,8 +768,9 @@ const messagingListProviders = async ({ queries, search, parseOutput = true, sdk /** * @param {MessagingCreateApnsProviderRequestParams} params */ -const messagingCreateApnsProvider = async ({ providerId, name, authKey, authKeyId, teamId, bundleId, sandbox, enabled, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingCreateApnsProvider = async ({providerId,name,authKey,authKeyId,teamId,bundleId,sandbox,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/providers/apns'; let payload = {}; if (typeof providerId !== 'undefined') { @@ -754,8 +808,9 @@ const messagingCreateApnsProvider = async ({ providerId, name, authKey, authKeyI parse(response) success() } - + return response; + } /** @@ -768,6 +823,7 @@ const messagingCreateApnsProvider = async ({ providerId, name, authKey, authKeyI * @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 */ @@ -775,8 +831,9 @@ const messagingCreateApnsProvider = async ({ providerId, name, authKey, authKeyI /** * @param {MessagingUpdateApnsProviderRequestParams} params */ -const messagingUpdateApnsProvider = async ({ providerId, name, enabled, authKey, authKeyId, teamId, bundleId, sandbox, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingUpdateApnsProvider = async ({providerId,name,enabled,authKey,authKeyId,teamId,bundleId,sandbox,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/providers/apns/{providerId}'.replace('{providerId}', providerId); let payload = {}; if (typeof name !== 'undefined') { @@ -811,8 +868,9 @@ const messagingUpdateApnsProvider = async ({ providerId, name, enabled, authKey, parse(response) success() } - + return response; + } /** @@ -821,6 +879,7 @@ const messagingUpdateApnsProvider = async ({ providerId, name, enabled, authKey, * @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 */ @@ -828,8 +887,9 @@ const messagingUpdateApnsProvider = async ({ providerId, name, enabled, authKey, /** * @param {MessagingCreateFcmProviderRequestParams} params */ -const messagingCreateFcmProvider = async ({ providerId, name, serviceAccountJSON, enabled, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingCreateFcmProvider = async ({providerId,name,serviceAccountJSON,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/providers/fcm'; let payload = {}; if (typeof providerId !== 'undefined') { @@ -855,8 +915,9 @@ const messagingCreateFcmProvider = async ({ providerId, name, serviceAccountJSON parse(response) success() } - + return response; + } /** @@ -865,6 +926,7 @@ const messagingCreateFcmProvider = async ({ providerId, name, serviceAccountJSON * @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 */ @@ -872,8 +934,9 @@ const messagingCreateFcmProvider = async ({ providerId, name, serviceAccountJSON /** * @param {MessagingUpdateFcmProviderRequestParams} params */ -const messagingUpdateFcmProvider = async ({ providerId, name, enabled, serviceAccountJSON, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingUpdateFcmProvider = async ({providerId,name,enabled,serviceAccountJSON,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/providers/fcm/{providerId}'.replace('{providerId}', providerId); let payload = {}; if (typeof name !== 'undefined') { @@ -896,8 +959,9 @@ const messagingUpdateFcmProvider = async ({ providerId, name, enabled, serviceAc parse(response) success() } - + return response; + } /** @@ -912,6 +976,7 @@ const messagingUpdateFcmProvider = async ({ providerId, name, enabled, serviceAc * @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 */ @@ -919,8 +984,9 @@ const messagingUpdateFcmProvider = async ({ providerId, name, enabled, serviceAc /** * @param {MessagingCreateMailgunProviderRequestParams} params */ -const messagingCreateMailgunProvider = async ({ providerId, name, apiKey, domain, isEuRegion, fromName, fromEmail, replyToName, replyToEmail, enabled, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingCreateMailgunProvider = async ({providerId,name,apiKey,domain,isEuRegion,fromName,fromEmail,replyToName,replyToEmail,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/providers/mailgun'; let payload = {}; if (typeof providerId !== 'undefined') { @@ -964,8 +1030,9 @@ const messagingCreateMailgunProvider = async ({ providerId, name, apiKey, domain parse(response) success() } - + return response; + } /** @@ -980,6 +1047,7 @@ const messagingCreateMailgunProvider = async ({ providerId, name, apiKey, domain * @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 */ @@ -987,8 +1055,9 @@ const messagingCreateMailgunProvider = async ({ providerId, name, apiKey, domain /** * @param {MessagingUpdateMailgunProviderRequestParams} params */ -const messagingUpdateMailgunProvider = async ({ providerId, name, apiKey, domain, isEuRegion, enabled, fromName, fromEmail, replyToName, replyToEmail, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingUpdateMailgunProvider = async ({providerId,name,apiKey,domain,isEuRegion,enabled,fromName,fromEmail,replyToName,replyToEmail,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/providers/mailgun/{providerId}'.replace('{providerId}', providerId); let payload = {}; if (typeof name !== 'undefined') { @@ -1029,8 +1098,9 @@ const messagingUpdateMailgunProvider = async ({ providerId, name, apiKey, domain parse(response) success() } - + return response; + } /** @@ -1041,6 +1111,7 @@ const messagingUpdateMailgunProvider = async ({ providerId, name, apiKey, domain * @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 */ @@ -1048,8 +1119,9 @@ const messagingUpdateMailgunProvider = async ({ providerId, name, apiKey, domain /** * @param {MessagingCreateMsg91ProviderRequestParams} params */ -const messagingCreateMsg91Provider = async ({ providerId, name, templateId, senderId, authKey, enabled, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingCreateMsg91Provider = async ({providerId,name,templateId,senderId,authKey,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/providers/msg91'; let payload = {}; if (typeof providerId !== 'undefined') { @@ -1081,8 +1153,9 @@ const messagingCreateMsg91Provider = async ({ providerId, name, templateId, send parse(response) success() } - + return response; + } /** @@ -1093,6 +1166,7 @@ const messagingCreateMsg91Provider = async ({ providerId, name, templateId, send * @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 */ @@ -1100,8 +1174,9 @@ const messagingCreateMsg91Provider = async ({ providerId, name, templateId, send /** * @param {MessagingUpdateMsg91ProviderRequestParams} params */ -const messagingUpdateMsg91Provider = async ({ providerId, name, enabled, templateId, senderId, authKey, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingUpdateMsg91Provider = async ({providerId,name,enabled,templateId,senderId,authKey,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/providers/msg91/{providerId}'.replace('{providerId}', providerId); let payload = {}; if (typeof name !== 'undefined') { @@ -1130,8 +1205,9 @@ const messagingUpdateMsg91Provider = async ({ providerId, name, enabled, templat parse(response) success() } - + return response; + } /** @@ -1144,6 +1220,7 @@ const messagingUpdateMsg91Provider = async ({ providerId, name, enabled, templat * @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 */ @@ -1151,8 +1228,9 @@ const messagingUpdateMsg91Provider = async ({ providerId, name, enabled, templat /** * @param {MessagingCreateSendgridProviderRequestParams} params */ -const messagingCreateSendgridProvider = async ({ providerId, name, apiKey, fromName, fromEmail, replyToName, replyToEmail, enabled, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingCreateSendgridProvider = async ({providerId,name,apiKey,fromName,fromEmail,replyToName,replyToEmail,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/providers/sendgrid'; let payload = {}; if (typeof providerId !== 'undefined') { @@ -1190,8 +1268,9 @@ const messagingCreateSendgridProvider = async ({ providerId, name, apiKey, fromN parse(response) success() } - + return response; + } /** @@ -1204,6 +1283,7 @@ const messagingCreateSendgridProvider = async ({ providerId, name, apiKey, fromN * @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 */ @@ -1211,8 +1291,9 @@ const messagingCreateSendgridProvider = async ({ providerId, name, apiKey, fromN /** * @param {MessagingUpdateSendgridProviderRequestParams} params */ -const messagingUpdateSendgridProvider = async ({ providerId, name, enabled, apiKey, fromName, fromEmail, replyToName, replyToEmail, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingUpdateSendgridProvider = async ({providerId,name,enabled,apiKey,fromName,fromEmail,replyToName,replyToEmail,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/providers/sendgrid/{providerId}'.replace('{providerId}', providerId); let payload = {}; if (typeof name !== 'undefined') { @@ -1247,8 +1328,9 @@ const messagingUpdateSendgridProvider = async ({ providerId, name, enabled, apiK parse(response) success() } - + return response; + } /** @@ -1267,6 +1349,7 @@ const messagingUpdateSendgridProvider = async ({ providerId, name, enabled, apiK * @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 */ @@ -1274,8 +1357,9 @@ const messagingUpdateSendgridProvider = async ({ providerId, name, enabled, apiK /** * @param {MessagingCreateSmtpProviderRequestParams} params */ -const messagingCreateSmtpProvider = async ({ providerId, name, host, port, username, password, encryption, autoTLS, mailer, fromName, fromEmail, replyToName, replyToEmail, enabled, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingCreateSmtpProvider = async ({providerId,name,host,port,username,password,encryption,autoTLS,mailer,fromName,fromEmail,replyToName,replyToEmail,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/providers/smtp'; let payload = {}; if (typeof providerId !== 'undefined') { @@ -1331,8 +1415,9 @@ const messagingCreateSmtpProvider = async ({ providerId, name, host, port, usern parse(response) success() } - + return response; + } /** @@ -1351,6 +1436,7 @@ const messagingCreateSmtpProvider = async ({ providerId, name, host, port, usern * @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 */ @@ -1358,8 +1444,9 @@ const messagingCreateSmtpProvider = async ({ providerId, name, host, port, usern /** * @param {MessagingUpdateSmtpProviderRequestParams} params */ -const messagingUpdateSmtpProvider = async ({ providerId, name, host, port, username, password, encryption, autoTLS, mailer, fromName, fromEmail, replyToName, replyToEmail, enabled, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingUpdateSmtpProvider = async ({providerId,name,host,port,username,password,encryption,autoTLS,mailer,fromName,fromEmail,replyToName,replyToEmail,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/providers/smtp/{providerId}'.replace('{providerId}', providerId); let payload = {}; if (typeof name !== 'undefined') { @@ -1412,8 +1499,9 @@ const messagingUpdateSmtpProvider = async ({ providerId, name, host, port, usern parse(response) success() } - + return response; + } /** @@ -1424,6 +1512,7 @@ const messagingUpdateSmtpProvider = async ({ providerId, name, host, port, usern * @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 */ @@ -1431,8 +1520,9 @@ const messagingUpdateSmtpProvider = async ({ providerId, name, host, port, usern /** * @param {MessagingCreateTelesignProviderRequestParams} params */ -const messagingCreateTelesignProvider = async ({ providerId, name, from, customerId, apiKey, enabled, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingCreateTelesignProvider = async ({providerId,name,from,customerId,apiKey,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/providers/telesign'; let payload = {}; if (typeof providerId !== 'undefined') { @@ -1464,8 +1554,9 @@ const messagingCreateTelesignProvider = async ({ providerId, name, from, custome parse(response) success() } - + return response; + } /** @@ -1476,6 +1567,7 @@ const messagingCreateTelesignProvider = async ({ providerId, name, from, custome * @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 */ @@ -1483,8 +1575,9 @@ const messagingCreateTelesignProvider = async ({ providerId, name, from, custome /** * @param {MessagingUpdateTelesignProviderRequestParams} params */ -const messagingUpdateTelesignProvider = async ({ providerId, name, enabled, customerId, apiKey, from, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingUpdateTelesignProvider = async ({providerId,name,enabled,customerId,apiKey,from,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/providers/telesign/{providerId}'.replace('{providerId}', providerId); let payload = {}; if (typeof name !== 'undefined') { @@ -1513,8 +1606,9 @@ const messagingUpdateTelesignProvider = async ({ providerId, name, enabled, cust parse(response) success() } - + return response; + } /** @@ -1525,6 +1619,7 @@ const messagingUpdateTelesignProvider = async ({ providerId, name, enabled, cust * @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 */ @@ -1532,8 +1627,9 @@ const messagingUpdateTelesignProvider = async ({ providerId, name, enabled, cust /** * @param {MessagingCreateTextmagicProviderRequestParams} params */ -const messagingCreateTextmagicProvider = async ({ providerId, name, from, username, apiKey, enabled, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingCreateTextmagicProvider = async ({providerId,name,from,username,apiKey,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/providers/textmagic'; let payload = {}; if (typeof providerId !== 'undefined') { @@ -1565,8 +1661,9 @@ const messagingCreateTextmagicProvider = async ({ providerId, name, from, userna parse(response) success() } - + return response; + } /** @@ -1577,6 +1674,7 @@ const messagingCreateTextmagicProvider = async ({ providerId, name, from, userna * @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 */ @@ -1584,8 +1682,9 @@ const messagingCreateTextmagicProvider = async ({ providerId, name, from, userna /** * @param {MessagingUpdateTextmagicProviderRequestParams} params */ -const messagingUpdateTextmagicProvider = async ({ providerId, name, enabled, username, apiKey, from, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingUpdateTextmagicProvider = async ({providerId,name,enabled,username,apiKey,from,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/providers/textmagic/{providerId}'.replace('{providerId}', providerId); let payload = {}; if (typeof name !== 'undefined') { @@ -1614,8 +1713,9 @@ const messagingUpdateTextmagicProvider = async ({ providerId, name, enabled, use parse(response) success() } - + return response; + } /** @@ -1626,6 +1726,7 @@ const messagingUpdateTextmagicProvider = async ({ providerId, name, enabled, use * @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 */ @@ -1633,8 +1734,9 @@ const messagingUpdateTextmagicProvider = async ({ providerId, name, enabled, use /** * @param {MessagingCreateTwilioProviderRequestParams} params */ -const messagingCreateTwilioProvider = async ({ providerId, name, from, accountSid, authToken, enabled, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingCreateTwilioProvider = async ({providerId,name,from,accountSid,authToken,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/providers/twilio'; let payload = {}; if (typeof providerId !== 'undefined') { @@ -1666,8 +1768,9 @@ const messagingCreateTwilioProvider = async ({ providerId, name, from, accountSi parse(response) success() } - + return response; + } /** @@ -1678,6 +1781,7 @@ const messagingCreateTwilioProvider = async ({ providerId, name, from, accountSi * @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 */ @@ -1685,8 +1789,9 @@ const messagingCreateTwilioProvider = async ({ providerId, name, from, accountSi /** * @param {MessagingUpdateTwilioProviderRequestParams} params */ -const messagingUpdateTwilioProvider = async ({ providerId, name, enabled, accountSid, authToken, from, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingUpdateTwilioProvider = async ({providerId,name,enabled,accountSid,authToken,from,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/providers/twilio/{providerId}'.replace('{providerId}', providerId); let payload = {}; if (typeof name !== 'undefined') { @@ -1715,8 +1820,9 @@ const messagingUpdateTwilioProvider = async ({ providerId, name, enabled, accoun parse(response) success() } - + return response; + } /** @@ -1727,6 +1833,7 @@ const messagingUpdateTwilioProvider = async ({ providerId, name, enabled, accoun * @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 */ @@ -1734,8 +1841,9 @@ const messagingUpdateTwilioProvider = async ({ providerId, name, enabled, accoun /** * @param {MessagingCreateVonageProviderRequestParams} params */ -const messagingCreateVonageProvider = async ({ providerId, name, from, apiKey, apiSecret, enabled, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingCreateVonageProvider = async ({providerId,name,from,apiKey,apiSecret,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/providers/vonage'; let payload = {}; if (typeof providerId !== 'undefined') { @@ -1767,8 +1875,9 @@ const messagingCreateVonageProvider = async ({ providerId, name, from, apiKey, a parse(response) success() } - + return response; + } /** @@ -1779,6 +1888,7 @@ const messagingCreateVonageProvider = async ({ providerId, name, from, apiKey, a * @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 */ @@ -1786,8 +1896,9 @@ const messagingCreateVonageProvider = async ({ providerId, name, from, apiKey, a /** * @param {MessagingUpdateVonageProviderRequestParams} params */ -const messagingUpdateVonageProvider = async ({ providerId, name, enabled, apiKey, apiSecret, from, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingUpdateVonageProvider = async ({providerId,name,enabled,apiKey,apiSecret,from,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/providers/vonage/{providerId}'.replace('{providerId}', providerId); let payload = {}; if (typeof name !== 'undefined') { @@ -1816,13 +1927,15 @@ const messagingUpdateVonageProvider = async ({ providerId, name, enabled, apiKey parse(response) success() } - + return response; + } /** * @typedef {Object} MessagingGetProviderRequestParams * @property {string} providerId Provider ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -1830,8 +1943,9 @@ const messagingUpdateVonageProvider = async ({ providerId, name, enabled, apiKey /** * @param {MessagingGetProviderRequestParams} params */ -const messagingGetProvider = async ({ providerId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingGetProvider = async ({providerId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/providers/{providerId}'.replace('{providerId}', providerId); let payload = {}; @@ -1842,16 +1956,22 @@ const messagingGetProvider = async ({ providerId, parseOutput = true, sdk = unde }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('messaging', 'getProvider', providerId); + } else { + parse(response) + success() + } } - + return response; + } /** * @typedef {Object} MessagingDeleteProviderRequestParams * @property {string} providerId Provider ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -1859,8 +1979,9 @@ const messagingGetProvider = async ({ providerId, parseOutput = true, sdk = unde /** * @param {MessagingDeleteProviderRequestParams} params */ -const messagingDeleteProvider = async ({ providerId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingDeleteProvider = async ({providerId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/providers/{providerId}'.replace('{providerId}', providerId); let payload = {}; @@ -1874,14 +1995,16 @@ const messagingDeleteProvider = async ({ providerId, parseOutput = true, sdk = u parse(response) success() } - + 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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -1889,8 +2012,9 @@ const messagingDeleteProvider = async ({ providerId, parseOutput = true, sdk = u /** * @param {MessagingListProviderLogsRequestParams} params */ -const messagingListProviderLogs = async ({ providerId, queries, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingListProviderLogs = async ({providerId,queries,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/providers/{providerId}/logs'.replace('{providerId}', providerId); let payload = {}; if (typeof queries !== 'undefined') { @@ -1907,14 +2031,16 @@ const messagingListProviderLogs = async ({ providerId, queries, parseOutput = tr parse(response) success() } - + 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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -1922,8 +2048,9 @@ const messagingListProviderLogs = async ({ providerId, queries, parseOutput = tr /** * @param {MessagingListSubscriberLogsRequestParams} params */ -const messagingListSubscriberLogs = async ({ subscriberId, queries, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingListSubscriberLogs = async ({subscriberId,queries,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/subscribers/{subscriberId}/logs'.replace('{subscriberId}', subscriberId); let payload = {}; if (typeof queries !== 'undefined') { @@ -1940,14 +2067,16 @@ const messagingListSubscriberLogs = async ({ subscriberId, queries, parseOutput parse(response) success() } - + 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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -1955,8 +2084,9 @@ const messagingListSubscriberLogs = async ({ subscriberId, queries, parseOutput /** * @param {MessagingListTopicsRequestParams} params */ -const messagingListTopics = async ({ queries, search, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingListTopics = async ({queries,search,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/topics'; let payload = {}; if (typeof queries !== 'undefined') { @@ -1973,11 +2103,16 @@ const messagingListTopics = async ({ queries, search, parseOutput = true, sdk = }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('messaging', 'listTopics'); + } else { + parse(response) + success() + } } - + return response; + } /** @@ -1985,6 +2120,7 @@ const messagingListTopics = async ({ queries, search, parseOutput = true, sdk = * @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 */ @@ -1992,8 +2128,9 @@ const messagingListTopics = async ({ queries, search, parseOutput = true, sdk = /** * @param {MessagingCreateTopicRequestParams} params */ -const messagingCreateTopic = async ({ topicId, name, subscribe, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingCreateTopic = async ({topicId,name,subscribe,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/topics'; let payload = {}; if (typeof topicId !== 'undefined') { @@ -2017,13 +2154,15 @@ const messagingCreateTopic = async ({ topicId, name, subscribe, parseOutput = tr parse(response) success() } - + return response; + } /** * @typedef {Object} MessagingGetTopicRequestParams * @property {string} topicId Topic ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -2031,8 +2170,9 @@ const messagingCreateTopic = async ({ topicId, name, subscribe, parseOutput = tr /** * @param {MessagingGetTopicRequestParams} params */ -const messagingGetTopic = async ({ topicId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingGetTopic = async ({topicId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/topics/{topicId}'.replace('{topicId}', topicId); let payload = {}; @@ -2043,11 +2183,16 @@ const messagingGetTopic = async ({ topicId, parseOutput = true, sdk = undefined} }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('messaging', 'getTopic', topicId); + } else { + parse(response) + success() + } } - + return response; + } /** @@ -2055,6 +2200,7 @@ const messagingGetTopic = async ({ topicId, parseOutput = true, sdk = undefined} * @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 */ @@ -2062,8 +2208,9 @@ const messagingGetTopic = async ({ topicId, parseOutput = true, sdk = undefined} /** * @param {MessagingUpdateTopicRequestParams} params */ -const messagingUpdateTopic = async ({ topicId, name, subscribe, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingUpdateTopic = async ({topicId,name,subscribe,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/topics/{topicId}'.replace('{topicId}', topicId); let payload = {}; if (typeof name !== 'undefined') { @@ -2084,13 +2231,15 @@ const messagingUpdateTopic = async ({ topicId, name, subscribe, parseOutput = tr parse(response) success() } - + return response; + } /** * @typedef {Object} MessagingDeleteTopicRequestParams * @property {string} topicId Topic ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -2098,8 +2247,9 @@ const messagingUpdateTopic = async ({ topicId, name, subscribe, parseOutput = tr /** * @param {MessagingDeleteTopicRequestParams} params */ -const messagingDeleteTopic = async ({ topicId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingDeleteTopic = async ({topicId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/topics/{topicId}'.replace('{topicId}', topicId); let payload = {}; @@ -2113,14 +2263,16 @@ const messagingDeleteTopic = async ({ topicId, parseOutput = true, sdk = undefin parse(response) success() } - + 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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -2128,8 +2280,9 @@ const messagingDeleteTopic = async ({ topicId, parseOutput = true, sdk = undefin /** * @param {MessagingListTopicLogsRequestParams} params */ -const messagingListTopicLogs = async ({ topicId, queries, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingListTopicLogs = async ({topicId,queries,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/topics/{topicId}/logs'.replace('{topicId}', topicId); let payload = {}; if (typeof queries !== 'undefined') { @@ -2146,8 +2299,9 @@ const messagingListTopicLogs = async ({ topicId, queries, parseOutput = true, sd parse(response) success() } - + return response; + } /** @@ -2155,6 +2309,7 @@ const messagingListTopicLogs = async ({ topicId, queries, parseOutput = true, sd * @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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -2162,8 +2317,9 @@ const messagingListTopicLogs = async ({ topicId, queries, parseOutput = true, sd /** * @param {MessagingListSubscribersRequestParams} params */ -const messagingListSubscribers = async ({ topicId, queries, search, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingListSubscribers = async ({topicId,queries,search,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/topics/{topicId}/subscribers'.replace('{topicId}', topicId); let payload = {}; if (typeof queries !== 'undefined') { @@ -2180,11 +2336,16 @@ const messagingListSubscribers = async ({ topicId, queries, search, parseOutput }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('messaging', 'listSubscribers', topicId); + } else { + parse(response) + success() + } } - + return response; + } /** @@ -2192,6 +2353,7 @@ const messagingListSubscribers = async ({ topicId, queries, search, parseOutput * @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 */ @@ -2199,8 +2361,9 @@ const messagingListSubscribers = async ({ topicId, queries, search, parseOutput /** * @param {MessagingCreateSubscriberRequestParams} params */ -const messagingCreateSubscriber = async ({ topicId, subscriberId, targetId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingCreateSubscriber = async ({topicId,subscriberId,targetId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/topics/{topicId}/subscribers'.replace('{topicId}', topicId); let payload = {}; if (typeof subscriberId !== 'undefined') { @@ -2220,14 +2383,16 @@ const messagingCreateSubscriber = async ({ topicId, subscriberId, targetId, pars parse(response) success() } - + 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 */ @@ -2235,8 +2400,9 @@ const messagingCreateSubscriber = async ({ topicId, subscriberId, targetId, pars /** * @param {MessagingGetSubscriberRequestParams} params */ -const messagingGetSubscriber = async ({ topicId, subscriberId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingGetSubscriber = async ({topicId,subscriberId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}'.replace('{topicId}', topicId).replace('{subscriberId}', subscriberId); let payload = {}; @@ -2250,14 +2416,16 @@ const messagingGetSubscriber = async ({ topicId, subscriberId, parseOutput = tru parse(response) success() } - + 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 */ @@ -2265,8 +2433,9 @@ const messagingGetSubscriber = async ({ topicId, subscriberId, parseOutput = tru /** * @param {MessagingDeleteSubscriberRequestParams} params */ -const messagingDeleteSubscriber = async ({ topicId, subscriberId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const messagingDeleteSubscriber = async ({topicId,subscriberId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}'.replace('{topicId}', topicId).replace('{subscriberId}', subscriberId); let payload = {}; @@ -2280,8 +2449,9 @@ const messagingDeleteSubscriber = async ({ topicId, subscriberId, parseOutput = parse(response) success() } - + return response; + } messaging @@ -2289,6 +2459,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(`--console`, `Get the resource console url`) .action(actionRunner(messagingListMessages)) messaging @@ -2395,6 +2566,7 @@ messaging .command(`getMessage`) .description(`Get a message by its unique ID. `) .requiredOption(`--messageId `, `Message ID.`) + .option(`--console`, `Get the resource console url`) .action(actionRunner(messagingGetMessage)) messaging @@ -2408,6 +2580,7 @@ messaging .description(`Get the message activity logs listed by its unique ID.`) .requiredOption(`--messageId `, `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(`--console`, `Get the resource console url`) .action(actionRunner(messagingListMessageLogs)) messaging @@ -2422,6 +2595,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(`--console`, `Get the resource console url`) .action(actionRunner(messagingListProviders)) messaging @@ -2676,6 +2850,7 @@ messaging .command(`getProvider`) .description(`Get a provider by its unique ID. `) .requiredOption(`--providerId `, `Provider ID.`) + .option(`--console`, `Get the resource console url`) .action(actionRunner(messagingGetProvider)) messaging @@ -2703,6 +2878,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(`--console`, `Get the resource console url`) .action(actionRunner(messagingListTopics)) messaging @@ -2717,6 +2893,7 @@ messaging .command(`getTopic`) .description(`Get a topic by its unique ID. `) .requiredOption(`--topicId `, `Topic ID.`) + .option(`--console`, `Get the resource console url`) .action(actionRunner(messagingGetTopic)) messaging @@ -2746,6 +2923,7 @@ messaging .requiredOption(`--topicId `, `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(`--console`, `Get the resource console url`) .action(actionRunner(messagingListSubscribers)) messaging @@ -2818,4 +2996,4 @@ module.exports = { messagingCreateSubscriber, messagingGetSubscriber, messagingDeleteSubscriber -}; \ No newline at end of file +}; diff --git a/lib/commands/migrations.js b/lib/commands/migrations.js index 2ddb16c..02e5db3 100644 --- a/lib/commands/migrations.js +++ b/lib/commands/migrations.js @@ -4,7 +4,7 @@ const tar = require("tar"); const ignore = require("ignore"); const { promisify } = require('util'); const libClient = require('../client.js'); -const { getAllFiles } = require('../utils.js'); +const { getAllFiles, showConsoleLink } = require('../utils.js'); const { Command } = require('commander'); const { sdkForProject, sdkForConsole } = require('../sdks') const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log } = require('../parser') @@ -43,6 +43,7 @@ const migrations = new Command("migrations").description(commandDescriptions['mi * @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, resources, statusCounters, resourceData, errors * @property {string} search Search term to filter your list results. Max length: 256 chars. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -50,8 +51,9 @@ const migrations = new Command("migrations").description(commandDescriptions['mi /** * @param {MigrationsListRequestParams} params */ -const migrationsList = async ({ queries, search, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const migrationsList = async ({queries,search,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/migrations'; let payload = {}; if (typeof queries !== 'undefined') { @@ -71,8 +73,9 @@ const migrationsList = async ({ queries, search, parseOutput = true, sdk = undef parse(response) success() } - + return response; + } /** @@ -81,6 +84,7 @@ const migrationsList = async ({ queries, search, parseOutput = true, sdk = undef * @property {string} endpoint Source's Appwrite Endpoint * @property {string} projectId Source's Project ID * @property {string} apiKey Source's API Key + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -88,8 +92,9 @@ const migrationsList = async ({ queries, search, parseOutput = true, sdk = undef /** * @param {MigrationsCreateAppwriteMigrationRequestParams} params */ -const migrationsCreateAppwriteMigration = async ({ resources, endpoint, projectId, apiKey, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const migrationsCreateAppwriteMigration = async ({resources,endpoint,projectId,apiKey,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/migrations/appwrite'; let payload = {}; resources = resources === true ? [] : resources; @@ -116,8 +121,9 @@ const migrationsCreateAppwriteMigration = async ({ resources, endpoint, projectI parse(response) success() } - + return response; + } /** @@ -126,6 +132,7 @@ const migrationsCreateAppwriteMigration = async ({ resources, endpoint, projectI * @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 */ @@ -133,8 +140,9 @@ const migrationsCreateAppwriteMigration = async ({ resources, endpoint, projectI /** * @param {MigrationsGetAppwriteReportRequestParams} params */ -const migrationsGetAppwriteReport = async ({ resources, endpoint, projectID, key, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const migrationsGetAppwriteReport = async ({resources,endpoint,projectID,key,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/migrations/appwrite/report'; let payload = {}; if (typeof resources !== 'undefined') { @@ -160,14 +168,16 @@ const migrationsGetAppwriteReport = async ({ resources, endpoint, projectID, key parse(response) success() } - + 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 */ @@ -175,8 +185,9 @@ const migrationsGetAppwriteReport = async ({ resources, endpoint, projectID, key /** * @param {MigrationsCreateFirebaseMigrationRequestParams} params */ -const migrationsCreateFirebaseMigration = async ({ resources, serviceAccount, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const migrationsCreateFirebaseMigration = async ({resources,serviceAccount,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/migrations/firebase'; let payload = {}; resources = resources === true ? [] : resources; @@ -197,12 +208,14 @@ const migrationsCreateFirebaseMigration = async ({ resources, serviceAccount, pa parse(response) success() } - + return response; + } /** * @typedef {Object} MigrationsDeleteFirebaseAuthRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -210,8 +223,9 @@ const migrationsCreateFirebaseMigration = async ({ resources, serviceAccount, pa /** * @param {MigrationsDeleteFirebaseAuthRequestParams} params */ -const migrationsDeleteFirebaseAuth = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const migrationsDeleteFirebaseAuth = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/migrations/firebase/deauthorize'; let payload = {}; @@ -225,14 +239,16 @@ const migrationsDeleteFirebaseAuth = async ({ parseOutput = true, sdk = undefine parse(response) success() } - + return response; + } /** * @typedef {Object} MigrationsCreateFirebaseOAuthMigrationRequestParams * @property {string[]} resources List of resources to migrate * @property {string} projectId Project ID of the Firebase Project + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -240,8 +256,9 @@ const migrationsDeleteFirebaseAuth = async ({ parseOutput = true, sdk = undefine /** * @param {MigrationsCreateFirebaseOAuthMigrationRequestParams} params */ -const migrationsCreateFirebaseOAuthMigration = async ({ resources, projectId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const migrationsCreateFirebaseOAuthMigration = async ({resources,projectId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/migrations/firebase/oauth'; let payload = {}; resources = resources === true ? [] : resources; @@ -262,12 +279,14 @@ const migrationsCreateFirebaseOAuthMigration = async ({ resources, projectId, pa parse(response) success() } - + return response; + } /** * @typedef {Object} MigrationsListFirebaseProjectsRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -275,8 +294,9 @@ const migrationsCreateFirebaseOAuthMigration = async ({ resources, projectId, pa /** * @param {MigrationsListFirebaseProjectsRequestParams} params */ -const migrationsListFirebaseProjects = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const migrationsListFirebaseProjects = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/migrations/firebase/projects'; let payload = {}; @@ -290,14 +310,16 @@ const migrationsListFirebaseProjects = async ({ parseOutput = true, sdk = undefi parse(response) success() } - + 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 */ @@ -305,8 +327,9 @@ const migrationsListFirebaseProjects = async ({ parseOutput = true, sdk = undefi /** * @param {MigrationsGetFirebaseReportRequestParams} params */ -const migrationsGetFirebaseReport = async ({ resources, serviceAccount, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const migrationsGetFirebaseReport = async ({resources,serviceAccount,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/migrations/firebase/report'; let payload = {}; if (typeof resources !== 'undefined') { @@ -326,14 +349,16 @@ const migrationsGetFirebaseReport = async ({ resources, serviceAccount, parseOut parse(response) success() } - + return response; + } /** * @typedef {Object} MigrationsGetFirebaseReportOAuthRequestParams * @property {string[]} resources List of resources to migrate * @property {string} projectId Project ID + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -341,8 +366,9 @@ const migrationsGetFirebaseReport = async ({ resources, serviceAccount, parseOut /** * @param {MigrationsGetFirebaseReportOAuthRequestParams} params */ -const migrationsGetFirebaseReportOAuth = async ({ resources, projectId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const migrationsGetFirebaseReportOAuth = async ({resources,projectId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/migrations/firebase/report/oauth'; let payload = {}; if (typeof resources !== 'undefined') { @@ -362,8 +388,9 @@ const migrationsGetFirebaseReportOAuth = async ({ resources, projectId, parseOut parse(response) success() } - + return response; + } /** @@ -376,6 +403,7 @@ const migrationsGetFirebaseReportOAuth = async ({ resources, projectId, parseOut * @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 */ @@ -383,8 +411,9 @@ const migrationsGetFirebaseReportOAuth = async ({ resources, projectId, parseOut /** * @param {MigrationsCreateNHostMigrationRequestParams} params */ -const migrationsCreateNHostMigration = async ({ resources, subdomain, region, adminSecret, database, username, password, port, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const migrationsCreateNHostMigration = async ({resources,subdomain,region,adminSecret,database,username,password,port,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/migrations/nhost'; let payload = {}; resources = resources === true ? [] : resources; @@ -423,8 +452,9 @@ const migrationsCreateNHostMigration = async ({ resources, subdomain, region, ad parse(response) success() } - + return response; + } /** @@ -437,6 +467,7 @@ const migrationsCreateNHostMigration = async ({ resources, subdomain, region, ad * @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 */ @@ -444,8 +475,9 @@ const migrationsCreateNHostMigration = async ({ resources, subdomain, region, ad /** * @param {MigrationsGetNHostReportRequestParams} params */ -const migrationsGetNHostReport = async ({ resources, subdomain, region, adminSecret, database, username, password, port, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const migrationsGetNHostReport = async ({resources,subdomain,region,adminSecret,database,username,password,port,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/migrations/nhost/report'; let payload = {}; if (typeof resources !== 'undefined') { @@ -483,8 +515,9 @@ const migrationsGetNHostReport = async ({ resources, subdomain, region, adminSec parse(response) success() } - + return response; + } /** @@ -496,6 +529,7 @@ const migrationsGetNHostReport = async ({ resources, subdomain, region, adminSec * @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 */ @@ -503,8 +537,9 @@ const migrationsGetNHostReport = async ({ resources, subdomain, region, adminSec /** * @param {MigrationsCreateSupabaseMigrationRequestParams} params */ -const migrationsCreateSupabaseMigration = async ({ resources, endpoint, apiKey, databaseHost, username, password, port, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const migrationsCreateSupabaseMigration = async ({resources,endpoint,apiKey,databaseHost,username,password,port,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/migrations/supabase'; let payload = {}; resources = resources === true ? [] : resources; @@ -540,8 +575,9 @@ const migrationsCreateSupabaseMigration = async ({ resources, endpoint, apiKey, parse(response) success() } - + return response; + } /** @@ -553,6 +589,7 @@ const migrationsCreateSupabaseMigration = async ({ resources, endpoint, apiKey, * @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 */ @@ -560,8 +597,9 @@ const migrationsCreateSupabaseMigration = async ({ resources, endpoint, apiKey, /** * @param {MigrationsGetSupabaseReportRequestParams} params */ -const migrationsGetSupabaseReport = async ({ resources, endpoint, apiKey, databaseHost, username, password, port, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const migrationsGetSupabaseReport = async ({resources,endpoint,apiKey,databaseHost,username,password,port,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/migrations/supabase/report'; let payload = {}; if (typeof resources !== 'undefined') { @@ -596,13 +634,15 @@ const migrationsGetSupabaseReport = async ({ resources, endpoint, apiKey, databa parse(response) success() } - + return response; + } /** * @typedef {Object} MigrationsGetRequestParams * @property {string} migrationId Migration unique ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -610,8 +650,9 @@ const migrationsGetSupabaseReport = async ({ resources, endpoint, apiKey, databa /** * @param {MigrationsGetRequestParams} params */ -const migrationsGet = async ({ migrationId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const migrationsGet = async ({migrationId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/migrations/{migrationId}'.replace('{migrationId}', migrationId); let payload = {}; @@ -625,13 +666,15 @@ const migrationsGet = async ({ migrationId, parseOutput = true, sdk = undefined} parse(response) success() } - + return response; + } /** * @typedef {Object} MigrationsRetryRequestParams * @property {string} migrationId Migration unique ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -639,8 +682,9 @@ const migrationsGet = async ({ migrationId, parseOutput = true, sdk = undefined} /** * @param {MigrationsRetryRequestParams} params */ -const migrationsRetry = async ({ migrationId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const migrationsRetry = async ({migrationId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/migrations/{migrationId}'.replace('{migrationId}', migrationId); let payload = {}; @@ -654,13 +698,15 @@ const migrationsRetry = async ({ migrationId, parseOutput = true, sdk = undefine parse(response) success() } - + return response; + } /** * @typedef {Object} MigrationsDeleteRequestParams * @property {string} migrationId Migration ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -668,8 +714,9 @@ const migrationsRetry = async ({ migrationId, parseOutput = true, sdk = undefine /** * @param {MigrationsDeleteRequestParams} params */ -const migrationsDelete = async ({ migrationId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const migrationsDelete = async ({migrationId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/migrations/{migrationId}'.replace('{migrationId}', migrationId); let payload = {}; @@ -683,8 +730,9 @@ const migrationsDelete = async ({ migrationId, parseOutput = true, sdk = undefin parse(response) success() } - + return response; + } migrations @@ -836,4 +884,4 @@ module.exports = { migrationsGet, migrationsRetry, migrationsDelete -}; \ No newline at end of file +}; diff --git a/lib/commands/project.js b/lib/commands/project.js index 126827c..1251a64 100644 --- a/lib/commands/project.js +++ b/lib/commands/project.js @@ -4,7 +4,7 @@ const tar = require("tar"); const ignore = require("ignore"); const { promisify } = require('util'); const libClient = require('../client.js'); -const { getAllFiles } = require('../utils.js'); +const { getAllFiles, showConsoleLink } = require('../utils.js'); const { Command } = require('commander'); const { sdkForProject, sdkForConsole } = require('../sdks') const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log } = require('../parser') @@ -44,6 +44,7 @@ const project = new Command("project").description(commandDescriptions['project' * @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 */ @@ -51,8 +52,9 @@ const project = new Command("project").description(commandDescriptions['project' /** * @param {ProjectGetUsageRequestParams} params */ -const projectGetUsage = async ({ startDate, endDate, period, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const projectGetUsage = async ({startDate,endDate,period,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/project/usage'; let payload = {}; if (typeof startDate !== 'undefined') { @@ -75,12 +77,14 @@ const projectGetUsage = async ({ startDate, endDate, period, parseOutput = true, parse(response) success() } - + return response; + } /** * @typedef {Object} ProjectListVariablesRequestParams + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -88,8 +92,9 @@ const projectGetUsage = async ({ startDate, endDate, period, parseOutput = true, /** * @param {ProjectListVariablesRequestParams} params */ -const projectListVariables = async ({ parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const projectListVariables = async ({parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/project/variables'; let payload = {}; @@ -103,14 +108,16 @@ const projectListVariables = async ({ parseOutput = true, sdk = undefined}) => { parse(response) success() } - + 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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -118,8 +125,9 @@ const projectListVariables = async ({ parseOutput = true, sdk = undefined}) => { /** * @param {ProjectCreateVariableRequestParams} params */ -const projectCreateVariable = async ({ key, value, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const projectCreateVariable = async ({key,value,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/project/variables'; let payload = {}; if (typeof key !== 'undefined') { @@ -139,13 +147,15 @@ const projectCreateVariable = async ({ key, value, parseOutput = true, sdk = und parse(response) success() } - + return response; + } /** * @typedef {Object} ProjectGetVariableRequestParams * @property {string} variableId Variable unique ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -153,8 +163,9 @@ const projectCreateVariable = async ({ key, value, parseOutput = true, sdk = und /** * @param {ProjectGetVariableRequestParams} params */ -const projectGetVariable = async ({ variableId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const projectGetVariable = async ({variableId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/project/variables/{variableId}'.replace('{variableId}', variableId); let payload = {}; @@ -168,8 +179,9 @@ const projectGetVariable = async ({ variableId, parseOutput = true, sdk = undefi parse(response) success() } - + return response; + } /** @@ -177,6 +189,7 @@ const projectGetVariable = async ({ variableId, parseOutput = true, sdk = undefi * @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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -184,8 +197,9 @@ const projectGetVariable = async ({ variableId, parseOutput = true, sdk = undefi /** * @param {ProjectUpdateVariableRequestParams} params */ -const projectUpdateVariable = async ({ variableId, key, value, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const projectUpdateVariable = async ({variableId,key,value,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/project/variables/{variableId}'.replace('{variableId}', variableId); let payload = {}; if (typeof key !== 'undefined') { @@ -205,13 +219,15 @@ const projectUpdateVariable = async ({ variableId, key, value, parseOutput = tru parse(response) success() } - + return response; + } /** * @typedef {Object} ProjectDeleteVariableRequestParams * @property {string} variableId Variable unique ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -219,8 +235,9 @@ const projectUpdateVariable = async ({ variableId, key, value, parseOutput = tru /** * @param {ProjectDeleteVariableRequestParams} params */ -const projectDeleteVariable = async ({ variableId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const projectDeleteVariable = async ({variableId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/project/variables/{variableId}'.replace('{variableId}', variableId); let payload = {}; @@ -234,8 +251,9 @@ const projectDeleteVariable = async ({ variableId, parseOutput = true, sdk = und parse(response) success() } - + return response; + } project @@ -286,4 +304,4 @@ module.exports = { projectGetVariable, projectUpdateVariable, projectDeleteVariable -}; \ No newline at end of file +}; diff --git a/lib/commands/projects.js b/lib/commands/projects.js index e613579..5b5c153 100644 --- a/lib/commands/projects.js +++ b/lib/commands/projects.js @@ -4,7 +4,7 @@ const tar = require("tar"); const ignore = require("ignore"); const { promisify } = require('util'); const libClient = require('../client.js'); -const { getAllFiles } = require('../utils.js'); +const { getAllFiles, showConsoleLink } = require('../utils.js'); const { Command } = require('commander'); const { sdkForProject, sdkForConsole } = require('../sdks') const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log } = require('../parser') @@ -43,6 +43,7 @@ const projects = new Command("projects").description(commandDescriptions['projec * @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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -50,8 +51,9 @@ const projects = new Command("projects").description(commandDescriptions['projec /** * @param {ProjectsListRequestParams} params */ -const projectsList = async ({ queries, search, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsList = async ({queries,search,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects'; let payload = {}; if (typeof queries !== 'undefined') { @@ -68,11 +70,16 @@ const projectsList = async ({ queries, search, parseOutput = true, sdk = undefin }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('projects', 'list'); + } else { + parse(response) + success() + } } - + return response; + } /** @@ -90,6 +97,7 @@ const projectsList = async ({ queries, search, parseOutput = true, sdk = undefin * @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 */ @@ -97,8 +105,9 @@ const projectsList = async ({ queries, search, parseOutput = true, sdk = undefin /** * @param {ProjectsCreateRequestParams} params */ -const projectsCreate = async ({ projectId, name, teamId, region, description, logo, url, legalName, legalCountry, legalState, legalCity, legalAddress, legalTaxId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsCreate = async ({projectId,name,teamId,region,description,logo,url,legalName,legalCountry,legalState,legalCity,legalAddress,legalTaxId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects'; let payload = {}; if (typeof projectId !== 'undefined') { @@ -151,13 +160,15 @@ const projectsCreate = async ({ projectId, name, teamId, region, description, lo parse(response) success() } - + return response; + } /** * @typedef {Object} ProjectsGetRequestParams * @property {string} projectId Project unique ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -165,8 +176,9 @@ const projectsCreate = async ({ projectId, name, teamId, region, description, lo /** * @param {ProjectsGetRequestParams} params */ -const projectsGet = async ({ projectId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsGet = async ({projectId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}'.replace('{projectId}', projectId); let payload = {}; @@ -177,11 +189,16 @@ const projectsGet = async ({ projectId, parseOutput = true, sdk = undefined}) => }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('projects', 'get', projectId); + } else { + parse(response) + success() + } } - + return response; + } /** @@ -197,6 +214,7 @@ const projectsGet = async ({ projectId, parseOutput = true, sdk = undefined}) => * @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 */ @@ -204,8 +222,9 @@ const projectsGet = async ({ projectId, parseOutput = true, sdk = undefined}) => /** * @param {ProjectsUpdateRequestParams} params */ -const projectsUpdate = async ({ projectId, name, description, logo, url, legalName, legalCountry, legalState, legalCity, legalAddress, legalTaxId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsUpdate = async ({projectId,name,description,logo,url,legalName,legalCountry,legalState,legalCity,legalAddress,legalTaxId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}'.replace('{projectId}', projectId); let payload = {}; if (typeof name !== 'undefined') { @@ -249,13 +268,15 @@ const projectsUpdate = async ({ projectId, name, description, logo, url, legalNa parse(response) success() } - + return response; + } /** * @typedef {Object} ProjectsDeleteRequestParams * @property {string} projectId Project unique ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -263,8 +284,9 @@ const projectsUpdate = async ({ projectId, name, description, logo, url, legalNa /** * @param {ProjectsDeleteRequestParams} params */ -const projectsDelete = async ({ projectId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsDelete = async ({projectId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}'.replace('{projectId}', projectId); let payload = {}; @@ -278,8 +300,9 @@ const projectsDelete = async ({ projectId, parseOutput = true, sdk = undefined}) parse(response) success() } - + return response; + } /** @@ -287,6 +310,7 @@ const projectsDelete = async ({ projectId, parseOutput = true, sdk = undefined}) * @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 */ @@ -294,8 +318,9 @@ const projectsDelete = async ({ projectId, parseOutput = true, sdk = undefined}) /** * @param {ProjectsUpdateApiStatusRequestParams} params */ -const projectsUpdateApiStatus = async ({ projectId, api, status, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsUpdateApiStatus = async ({projectId,api,status,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/api'.replace('{projectId}', projectId); let payload = {}; if (typeof api !== 'undefined') { @@ -315,14 +340,16 @@ const projectsUpdateApiStatus = async ({ projectId, api, status, parseOutput = t parse(response) success() } - + 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 */ @@ -330,8 +357,9 @@ const projectsUpdateApiStatus = async ({ projectId, api, status, parseOutput = t /** * @param {ProjectsUpdateApiStatusAllRequestParams} params */ -const projectsUpdateApiStatusAll = async ({ projectId, status, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsUpdateApiStatusAll = async ({projectId,status,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/api/all'.replace('{projectId}', projectId); let payload = {}; if (typeof status !== 'undefined') { @@ -348,14 +376,16 @@ const projectsUpdateApiStatusAll = async ({ projectId, status, parseOutput = tru parse(response) success() } - + 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 */ @@ -363,8 +393,9 @@ const projectsUpdateApiStatusAll = async ({ projectId, status, parseOutput = tru /** * @param {ProjectsUpdateAuthDurationRequestParams} params */ -const projectsUpdateAuthDuration = async ({ projectId, duration, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsUpdateAuthDuration = async ({projectId,duration,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/auth/duration'.replace('{projectId}', projectId); let payload = {}; if (typeof duration !== 'undefined') { @@ -381,14 +412,16 @@ const projectsUpdateAuthDuration = async ({ projectId, duration, parseOutput = t parse(response) success() } - + 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 */ @@ -396,8 +429,9 @@ const projectsUpdateAuthDuration = async ({ projectId, duration, parseOutput = t /** * @param {ProjectsUpdateAuthLimitRequestParams} params */ -const projectsUpdateAuthLimit = async ({ projectId, limit, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsUpdateAuthLimit = async ({projectId,limit,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/auth/limit'.replace('{projectId}', projectId); let payload = {}; if (typeof limit !== 'undefined') { @@ -414,14 +448,16 @@ const projectsUpdateAuthLimit = async ({ projectId, limit, parseOutput = true, s parse(response) success() } - + 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 */ @@ -429,8 +465,9 @@ const projectsUpdateAuthLimit = async ({ projectId, limit, parseOutput = true, s /** * @param {ProjectsUpdateAuthSessionsLimitRequestParams} params */ -const projectsUpdateAuthSessionsLimit = async ({ projectId, limit, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsUpdateAuthSessionsLimit = async ({projectId,limit,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/auth/max-sessions'.replace('{projectId}', projectId); let payload = {}; if (typeof limit !== 'undefined') { @@ -447,14 +484,53 @@ const projectsUpdateAuthSessionsLimit = async ({ projectId, limit, parseOutput = parse(response) success() } - + + 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 + */ + +/** + * @param {ProjectsUpdateMockNumbersRequestParams} params + */ +const projectsUpdateMockNumbers = async ({projectId,numbers,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; + let apiPath = '/projects/{projectId}/auth/mock-numbers'.replace('{projectId}', projectId); + let payload = {}; + numbers = numbers === true ? [] : numbers; + if (typeof numbers !== 'undefined') { + payload['numbers'] = numbers; + } + + let response = undefined; + + response = await client.call('patch', apiPath, { + 'content-type': 'application/json', + }, payload); + + if (parseOutput) { + parse(response) + success() + } + 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 */ @@ -462,8 +538,9 @@ const projectsUpdateAuthSessionsLimit = async ({ projectId, limit, parseOutput = /** * @param {ProjectsUpdateAuthPasswordDictionaryRequestParams} params */ -const projectsUpdateAuthPasswordDictionary = async ({ projectId, enabled, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsUpdateAuthPasswordDictionary = async ({projectId,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/auth/password-dictionary'.replace('{projectId}', projectId); let payload = {}; if (typeof enabled !== 'undefined') { @@ -480,14 +557,16 @@ const projectsUpdateAuthPasswordDictionary = async ({ projectId, enabled, parseO parse(response) success() } - + 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 */ @@ -495,8 +574,9 @@ const projectsUpdateAuthPasswordDictionary = async ({ projectId, enabled, parseO /** * @param {ProjectsUpdateAuthPasswordHistoryRequestParams} params */ -const projectsUpdateAuthPasswordHistory = async ({ projectId, limit, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsUpdateAuthPasswordHistory = async ({projectId,limit,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/auth/password-history'.replace('{projectId}', projectId); let payload = {}; if (typeof limit !== 'undefined') { @@ -513,14 +593,16 @@ const projectsUpdateAuthPasswordHistory = async ({ projectId, limit, parseOutput parse(response) success() } - + 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 */ @@ -528,8 +610,9 @@ const projectsUpdateAuthPasswordHistory = async ({ projectId, limit, parseOutput /** * @param {ProjectsUpdatePersonalDataCheckRequestParams} params */ -const projectsUpdatePersonalDataCheck = async ({ projectId, enabled, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsUpdatePersonalDataCheck = async ({projectId,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/auth/personal-data'.replace('{projectId}', projectId); let payload = {}; if (typeof enabled !== 'undefined') { @@ -546,8 +629,45 @@ const projectsUpdatePersonalDataCheck = async ({ projectId, enabled, parseOutput parse(response) success() } - + 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 + */ + +/** + * @param {ProjectsUpdateSessionAlertsRequestParams} params + */ +const projectsUpdateSessionAlerts = async ({projectId,alerts,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; + let apiPath = '/projects/{projectId}/auth/session-alerts'.replace('{projectId}', projectId); + let payload = {}; + if (typeof alerts !== 'undefined') { + payload['alerts'] = alerts; + } + + let response = undefined; + + response = await client.call('patch', apiPath, { + 'content-type': 'application/json', + }, payload); + + if (parseOutput) { + parse(response) + success() + } + + return response; + } /** @@ -555,6 +675,7 @@ const projectsUpdatePersonalDataCheck = async ({ projectId, enabled, parseOutput * @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 */ @@ -562,8 +683,9 @@ const projectsUpdatePersonalDataCheck = async ({ projectId, enabled, parseOutput /** * @param {ProjectsUpdateAuthStatusRequestParams} params */ -const projectsUpdateAuthStatus = async ({ projectId, method, status, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsUpdateAuthStatus = async ({projectId,method,status,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/auth/{method}'.replace('{projectId}', projectId).replace('{method}', method); let payload = {}; if (typeof status !== 'undefined') { @@ -580,13 +702,56 @@ const projectsUpdateAuthStatus = async ({ projectId, method, status, parseOutput parse(response) success() } - + + 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}) => { + let client = !sdk ? await sdkForConsole() : + sdk; + let apiPath = '/projects/{projectId}/jwts'.replace('{projectId}', projectId); + let payload = {}; + scopes = scopes === true ? [] : scopes; + if (typeof scopes !== 'undefined') { + payload['scopes'] = scopes; + } + if (typeof duration !== 'undefined') { + payload['duration'] = duration; + } + + let response = undefined; + + response = await client.call('post', apiPath, { + 'content-type': 'application/json', + }, payload); + + if (parseOutput) { + parse(response) + success() + } + return response; + } /** * @typedef {Object} ProjectsListKeysRequestParams * @property {string} projectId Project unique ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -594,8 +759,9 @@ const projectsUpdateAuthStatus = async ({ projectId, method, status, parseOutput /** * @param {ProjectsListKeysRequestParams} params */ -const projectsListKeys = async ({ projectId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsListKeys = async ({projectId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/keys'.replace('{projectId}', projectId); let payload = {}; @@ -606,11 +772,16 @@ const projectsListKeys = async ({ projectId, parseOutput = true, sdk = undefined }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('projects', 'listKeys', projectId); + } else { + parse(response) + success() + } } - + return response; + } /** @@ -619,6 +790,7 @@ const projectsListKeys = async ({ projectId, parseOutput = true, sdk = undefined * @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 */ @@ -626,8 +798,9 @@ const projectsListKeys = async ({ projectId, parseOutput = true, sdk = undefined /** * @param {ProjectsCreateKeyRequestParams} params */ -const projectsCreateKey = async ({ projectId, name, scopes, expire, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsCreateKey = async ({projectId,name,scopes,expire,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/keys'.replace('{projectId}', projectId); let payload = {}; if (typeof name !== 'undefined') { @@ -651,14 +824,16 @@ const projectsCreateKey = async ({ projectId, name, scopes, expire, parseOutput parse(response) success() } - + 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 */ @@ -666,8 +841,9 @@ const projectsCreateKey = async ({ projectId, name, scopes, expire, parseOutput /** * @param {ProjectsGetKeyRequestParams} params */ -const projectsGetKey = async ({ projectId, keyId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsGetKey = async ({projectId,keyId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/keys/{keyId}'.replace('{projectId}', projectId).replace('{keyId}', keyId); let payload = {}; @@ -678,11 +854,16 @@ const projectsGetKey = async ({ projectId, keyId, parseOutput = true, sdk = unde }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('projects', 'getKey', projectId, keyId); + } else { + parse(response) + success() + } } - + return response; + } /** @@ -692,6 +873,7 @@ const projectsGetKey = async ({ projectId, keyId, parseOutput = true, sdk = unde * @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 */ @@ -699,8 +881,9 @@ const projectsGetKey = async ({ projectId, keyId, parseOutput = true, sdk = unde /** * @param {ProjectsUpdateKeyRequestParams} params */ -const projectsUpdateKey = async ({ projectId, keyId, name, scopes, expire, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsUpdateKey = async ({projectId,keyId,name,scopes,expire,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/keys/{keyId}'.replace('{projectId}', projectId).replace('{keyId}', keyId); let payload = {}; if (typeof name !== 'undefined') { @@ -724,14 +907,16 @@ const projectsUpdateKey = async ({ projectId, keyId, name, scopes, expire, parse parse(response) success() } - + 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 */ @@ -739,8 +924,9 @@ const projectsUpdateKey = async ({ projectId, keyId, name, scopes, expire, parse /** * @param {ProjectsDeleteKeyRequestParams} params */ -const projectsDeleteKey = async ({ projectId, keyId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsDeleteKey = async ({projectId,keyId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/keys/{keyId}'.replace('{projectId}', projectId).replace('{keyId}', keyId); let payload = {}; @@ -754,8 +940,9 @@ const projectsDeleteKey = async ({ projectId, keyId, parseOutput = true, sdk = u parse(response) success() } - + return response; + } /** @@ -765,6 +952,7 @@ const projectsDeleteKey = async ({ projectId, keyId, parseOutput = true, sdk = u * @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 */ @@ -772,8 +960,9 @@ const projectsDeleteKey = async ({ projectId, keyId, parseOutput = true, sdk = u /** * @param {ProjectsUpdateOAuth2RequestParams} params */ -const projectsUpdateOAuth2 = async ({ projectId, provider, appId, secret, enabled, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsUpdateOAuth2 = async ({projectId,provider,appId,secret,enabled,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/oauth2'.replace('{projectId}', projectId); let payload = {}; if (typeof provider !== 'undefined') { @@ -799,13 +988,15 @@ const projectsUpdateOAuth2 = async ({ projectId, provider, appId, secret, enable parse(response) success() } - + return response; + } /** * @typedef {Object} ProjectsListPlatformsRequestParams * @property {string} projectId Project unique ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -813,8 +1004,9 @@ const projectsUpdateOAuth2 = async ({ projectId, provider, appId, secret, enable /** * @param {ProjectsListPlatformsRequestParams} params */ -const projectsListPlatforms = async ({ projectId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsListPlatforms = async ({projectId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/platforms'.replace('{projectId}', projectId); let payload = {}; @@ -825,11 +1017,16 @@ const projectsListPlatforms = async ({ projectId, parseOutput = true, sdk = unde }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('projects', 'listPlatforms', projectId); + } else { + parse(response) + success() + } } - + return response; + } /** @@ -840,6 +1037,7 @@ const projectsListPlatforms = async ({ projectId, parseOutput = true, sdk = unde * @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 */ @@ -847,8 +1045,9 @@ const projectsListPlatforms = async ({ projectId, parseOutput = true, sdk = unde /** * @param {ProjectsCreatePlatformRequestParams} params */ -const projectsCreatePlatform = async ({ projectId, type, name, key, store, hostname, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsCreatePlatform = async ({projectId,type,name,key,store,hostname,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/platforms'.replace('{projectId}', projectId); let payload = {}; if (typeof type !== 'undefined') { @@ -877,14 +1076,16 @@ const projectsCreatePlatform = async ({ projectId, type, name, key, store, hostn parse(response) success() } - + 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 */ @@ -892,8 +1093,9 @@ const projectsCreatePlatform = async ({ projectId, type, name, key, store, hostn /** * @param {ProjectsGetPlatformRequestParams} params */ -const projectsGetPlatform = async ({ projectId, platformId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsGetPlatform = async ({projectId,platformId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/platforms/{platformId}'.replace('{projectId}', projectId).replace('{platformId}', platformId); let payload = {}; @@ -904,11 +1106,16 @@ const projectsGetPlatform = async ({ projectId, platformId, parseOutput = true, }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('projects', 'getPlatform', projectId, platformId); + } else { + parse(response) + success() + } } - + return response; + } /** @@ -919,6 +1126,7 @@ const projectsGetPlatform = async ({ projectId, platformId, parseOutput = true, * @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 */ @@ -926,8 +1134,9 @@ const projectsGetPlatform = async ({ projectId, platformId, parseOutput = true, /** * @param {ProjectsUpdatePlatformRequestParams} params */ -const projectsUpdatePlatform = async ({ projectId, platformId, name, key, store, hostname, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsUpdatePlatform = async ({projectId,platformId,name,key,store,hostname,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/platforms/{platformId}'.replace('{projectId}', projectId).replace('{platformId}', platformId); let payload = {}; if (typeof name !== 'undefined') { @@ -953,14 +1162,16 @@ const projectsUpdatePlatform = async ({ projectId, platformId, name, key, store, parse(response) success() } - + 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 */ @@ -968,8 +1179,9 @@ const projectsUpdatePlatform = async ({ projectId, platformId, name, key, store, /** * @param {ProjectsDeletePlatformRequestParams} params */ -const projectsDeletePlatform = async ({ projectId, platformId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsDeletePlatform = async ({projectId,platformId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/platforms/{platformId}'.replace('{projectId}', projectId).replace('{platformId}', platformId); let payload = {}; @@ -983,8 +1195,9 @@ const projectsDeletePlatform = async ({ projectId, platformId, parseOutput = tru parse(response) success() } - + return response; + } /** @@ -992,6 +1205,7 @@ const projectsDeletePlatform = async ({ projectId, platformId, parseOutput = tru * @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 */ @@ -999,8 +1213,9 @@ const projectsDeletePlatform = async ({ projectId, platformId, parseOutput = tru /** * @param {ProjectsUpdateServiceStatusRequestParams} params */ -const projectsUpdateServiceStatus = async ({ projectId, service, status, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsUpdateServiceStatus = async ({projectId,service,status,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/service'.replace('{projectId}', projectId); let payload = {}; if (typeof service !== 'undefined') { @@ -1020,14 +1235,16 @@ const projectsUpdateServiceStatus = async ({ projectId, service, status, parseOu parse(response) success() } - + 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 */ @@ -1035,8 +1252,9 @@ const projectsUpdateServiceStatus = async ({ projectId, service, status, parseOu /** * @param {ProjectsUpdateServiceStatusAllRequestParams} params */ -const projectsUpdateServiceStatusAll = async ({ projectId, status, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsUpdateServiceStatusAll = async ({projectId,status,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/service/all'.replace('{projectId}', projectId); let payload = {}; if (typeof status !== 'undefined') { @@ -1053,8 +1271,9 @@ const projectsUpdateServiceStatusAll = async ({ projectId, status, parseOutput = parse(response) success() } - + return response; + } /** @@ -1069,6 +1288,7 @@ const projectsUpdateServiceStatusAll = async ({ projectId, status, parseOutput = * @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 */ @@ -1076,8 +1296,9 @@ const projectsUpdateServiceStatusAll = async ({ projectId, status, parseOutput = /** * @param {ProjectsUpdateSmtpRequestParams} params */ -const projectsUpdateSmtp = async ({ projectId, enabled, senderName, senderEmail, replyTo, host, port, username, password, secure, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsUpdateSmtp = async ({projectId,enabled,senderName,senderEmail,replyTo,host,port,username,password,secure,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/smtp'.replace('{projectId}', projectId); let payload = {}; if (typeof enabled !== 'undefined') { @@ -1118,8 +1339,9 @@ const projectsUpdateSmtp = async ({ projectId, enabled, senderName, senderEmail, parse(response) success() } - + return response; + } /** @@ -1134,6 +1356,7 @@ const projectsUpdateSmtp = async ({ projectId, enabled, senderName, senderEmail, * @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 */ @@ -1141,8 +1364,9 @@ const projectsUpdateSmtp = async ({ projectId, enabled, senderName, senderEmail, /** * @param {ProjectsCreateSmtpTestRequestParams} params */ -const projectsCreateSmtpTest = async ({ projectId, emails, senderName, senderEmail, host, replyTo, port, username, password, secure, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsCreateSmtpTest = async ({projectId,emails,senderName,senderEmail,host,replyTo,port,username,password,secure,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/smtp/tests'.replace('{projectId}', projectId); let payload = {}; emails = emails === true ? [] : emails; @@ -1184,14 +1408,16 @@ const projectsCreateSmtpTest = async ({ projectId, emails, senderName, senderEma parse(response) success() } - + 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 */ @@ -1199,8 +1425,9 @@ const projectsCreateSmtpTest = async ({ projectId, emails, senderName, senderEma /** * @param {ProjectsUpdateTeamRequestParams} params */ -const projectsUpdateTeam = async ({ projectId, teamId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsUpdateTeam = async ({projectId,teamId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/team'.replace('{projectId}', projectId); let payload = {}; if (typeof teamId !== 'undefined') { @@ -1217,8 +1444,9 @@ const projectsUpdateTeam = async ({ projectId, teamId, parseOutput = true, sdk = parse(response) success() } - + return response; + } /** @@ -1226,6 +1454,7 @@ const projectsUpdateTeam = async ({ projectId, teamId, parseOutput = true, sdk = * @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 */ @@ -1233,8 +1462,9 @@ const projectsUpdateTeam = async ({ projectId, teamId, parseOutput = true, sdk = /** * @param {ProjectsGetEmailTemplateRequestParams} params */ -const projectsGetEmailTemplate = async ({ projectId, type, locale, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsGetEmailTemplate = async ({projectId,type,locale,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/templates/email/{type}/{locale}'.replace('{projectId}', projectId).replace('{type}', type).replace('{locale}', locale); let payload = {}; @@ -1248,8 +1478,9 @@ const projectsGetEmailTemplate = async ({ projectId, type, locale, parseOutput = parse(response) success() } - + return response; + } /** @@ -1262,6 +1493,7 @@ const projectsGetEmailTemplate = async ({ projectId, type, locale, parseOutput = * @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 */ @@ -1269,8 +1501,9 @@ const projectsGetEmailTemplate = async ({ projectId, type, locale, parseOutput = /** * @param {ProjectsUpdateEmailTemplateRequestParams} params */ -const projectsUpdateEmailTemplate = async ({ projectId, type, locale, subject, message, senderName, senderEmail, replyTo, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsUpdateEmailTemplate = async ({projectId,type,locale,subject,message,senderName,senderEmail,replyTo,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/templates/email/{type}/{locale}'.replace('{projectId}', projectId).replace('{type}', type).replace('{locale}', locale); let payload = {}; if (typeof subject !== 'undefined') { @@ -1299,8 +1532,9 @@ const projectsUpdateEmailTemplate = async ({ projectId, type, locale, subject, m parse(response) success() } - + return response; + } /** @@ -1308,6 +1542,7 @@ const projectsUpdateEmailTemplate = async ({ projectId, type, locale, subject, m * @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 */ @@ -1315,8 +1550,9 @@ const projectsUpdateEmailTemplate = async ({ projectId, type, locale, subject, m /** * @param {ProjectsDeleteEmailTemplateRequestParams} params */ -const projectsDeleteEmailTemplate = async ({ projectId, type, locale, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsDeleteEmailTemplate = async ({projectId,type,locale,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/templates/email/{type}/{locale}'.replace('{projectId}', projectId).replace('{type}', type).replace('{locale}', locale); let payload = {}; @@ -1330,8 +1566,9 @@ const projectsDeleteEmailTemplate = async ({ projectId, type, locale, parseOutpu parse(response) success() } - + return response; + } /** @@ -1339,6 +1576,7 @@ const projectsDeleteEmailTemplate = async ({ projectId, type, locale, parseOutpu * @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 */ @@ -1346,8 +1584,9 @@ const projectsDeleteEmailTemplate = async ({ projectId, type, locale, parseOutpu /** * @param {ProjectsGetSmsTemplateRequestParams} params */ -const projectsGetSmsTemplate = async ({ projectId, type, locale, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsGetSmsTemplate = async ({projectId,type,locale,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/templates/sms/{type}/{locale}'.replace('{projectId}', projectId).replace('{type}', type).replace('{locale}', locale); let payload = {}; @@ -1361,8 +1600,9 @@ const projectsGetSmsTemplate = async ({ projectId, type, locale, parseOutput = t parse(response) success() } - + return response; + } /** @@ -1371,6 +1611,7 @@ const projectsGetSmsTemplate = async ({ projectId, type, locale, parseOutput = t * @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 */ @@ -1378,8 +1619,9 @@ const projectsGetSmsTemplate = async ({ projectId, type, locale, parseOutput = t /** * @param {ProjectsUpdateSmsTemplateRequestParams} params */ -const projectsUpdateSmsTemplate = async ({ projectId, type, locale, message, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsUpdateSmsTemplate = async ({projectId,type,locale,message,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/templates/sms/{type}/{locale}'.replace('{projectId}', projectId).replace('{type}', type).replace('{locale}', locale); let payload = {}; if (typeof message !== 'undefined') { @@ -1396,8 +1638,9 @@ const projectsUpdateSmsTemplate = async ({ projectId, type, locale, message, par parse(response) success() } - + return response; + } /** @@ -1405,6 +1648,7 @@ const projectsUpdateSmsTemplate = async ({ projectId, type, locale, message, par * @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 */ @@ -1412,8 +1656,9 @@ const projectsUpdateSmsTemplate = async ({ projectId, type, locale, message, par /** * @param {ProjectsDeleteSmsTemplateRequestParams} params */ -const projectsDeleteSmsTemplate = async ({ projectId, type, locale, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsDeleteSmsTemplate = async ({projectId,type,locale,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/templates/sms/{type}/{locale}'.replace('{projectId}', projectId).replace('{type}', type).replace('{locale}', locale); let payload = {}; @@ -1427,13 +1672,15 @@ const projectsDeleteSmsTemplate = async ({ projectId, type, locale, parseOutput parse(response) success() } - + return response; + } /** * @typedef {Object} ProjectsListWebhooksRequestParams * @property {string} projectId Project unique ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -1441,8 +1688,9 @@ const projectsDeleteSmsTemplate = async ({ projectId, type, locale, parseOutput /** * @param {ProjectsListWebhooksRequestParams} params */ -const projectsListWebhooks = async ({ projectId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsListWebhooks = async ({projectId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/webhooks'.replace('{projectId}', projectId); let payload = {}; @@ -1453,11 +1701,16 @@ const projectsListWebhooks = async ({ projectId, parseOutput = true, sdk = undef }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('projects', 'listWebhooks', projectId); + } else { + parse(response) + success() + } } - + return response; + } /** @@ -1470,6 +1723,7 @@ const projectsListWebhooks = async ({ projectId, parseOutput = true, sdk = undef * @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 */ @@ -1477,8 +1731,9 @@ const projectsListWebhooks = async ({ projectId, parseOutput = true, sdk = undef /** * @param {ProjectsCreateWebhookRequestParams} params */ -const projectsCreateWebhook = async ({ projectId, name, events, url, security, enabled, httpUser, httpPass, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsCreateWebhook = async ({projectId,name,events,url,security,enabled,httpUser,httpPass,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/webhooks'.replace('{projectId}', projectId); let payload = {}; if (typeof name !== 'undefined') { @@ -1514,14 +1769,16 @@ const projectsCreateWebhook = async ({ projectId, name, events, url, security, e parse(response) success() } - + 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 */ @@ -1529,8 +1786,9 @@ const projectsCreateWebhook = async ({ projectId, name, events, url, security, e /** * @param {ProjectsGetWebhookRequestParams} params */ -const projectsGetWebhook = async ({ projectId, webhookId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsGetWebhook = async ({projectId,webhookId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/webhooks/{webhookId}'.replace('{projectId}', projectId).replace('{webhookId}', webhookId); let payload = {}; @@ -1541,11 +1799,16 @@ const projectsGetWebhook = async ({ projectId, webhookId, parseOutput = true, sd }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('projects', 'getWebhook', projectId, webhookId); + } else { + parse(response) + success() + } } - + return response; + } /** @@ -1559,6 +1822,7 @@ const projectsGetWebhook = async ({ projectId, webhookId, parseOutput = true, sd * @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 */ @@ -1566,8 +1830,9 @@ const projectsGetWebhook = async ({ projectId, webhookId, parseOutput = true, sd /** * @param {ProjectsUpdateWebhookRequestParams} params */ -const projectsUpdateWebhook = async ({ projectId, webhookId, name, events, url, security, enabled, httpUser, httpPass, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsUpdateWebhook = async ({projectId,webhookId,name,events,url,security,enabled,httpUser,httpPass,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/webhooks/{webhookId}'.replace('{projectId}', projectId).replace('{webhookId}', webhookId); let payload = {}; if (typeof name !== 'undefined') { @@ -1603,14 +1868,16 @@ const projectsUpdateWebhook = async ({ projectId, webhookId, name, events, url, parse(response) success() } - + 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 */ @@ -1618,8 +1885,9 @@ const projectsUpdateWebhook = async ({ projectId, webhookId, name, events, url, /** * @param {ProjectsDeleteWebhookRequestParams} params */ -const projectsDeleteWebhook = async ({ projectId, webhookId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsDeleteWebhook = async ({projectId,webhookId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/webhooks/{webhookId}'.replace('{projectId}', projectId).replace('{webhookId}', webhookId); let payload = {}; @@ -1633,14 +1901,16 @@ const projectsDeleteWebhook = async ({ projectId, webhookId, parseOutput = true, parse(response) success() } - + 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 */ @@ -1648,8 +1918,9 @@ const projectsDeleteWebhook = async ({ projectId, webhookId, parseOutput = true, /** * @param {ProjectsUpdateWebhookSignatureRequestParams} params */ -const projectsUpdateWebhookSignature = async ({ projectId, webhookId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForConsole() : sdk; +const projectsUpdateWebhookSignature = async ({projectId,webhookId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForConsole() : + sdk; let apiPath = '/projects/{projectId}/webhooks/{webhookId}/signature'.replace('{projectId}', projectId).replace('{webhookId}', webhookId); let payload = {}; @@ -1663,8 +1934,9 @@ const projectsUpdateWebhookSignature = async ({ projectId, webhookId, parseOutpu parse(response) success() } - + return response; + } projects @@ -1672,6 +1944,7 @@ projects .description(``) .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(`--console`, `Get the resource console url`) .action(actionRunner(projectsList)) projects @@ -1696,6 +1969,7 @@ projects .command(`get`) .description(``) .requiredOption(`--projectId `, `Project unique ID.`) + .option(`--console`, `Get the resource console url`) .action(actionRunner(projectsGet)) projects @@ -1756,6 +2030,13 @@ projects .requiredOption(`--limit `, `Set the max number of users allowed in this project. Value allowed is between 1-100. Default is 10`, parseInteger) .action(actionRunner(projectsUpdateAuthSessionsLimit)) +projects + .command(`updateMockNumbers`) + .description(``) + .requiredOption(`--projectId `, `Project unique ID.`) + .requiredOption(`--numbers [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.`) + .action(actionRunner(projectsUpdateMockNumbers)) + projects .command(`updateAuthPasswordDictionary`) .description(``) @@ -1777,6 +2058,13 @@ projects .requiredOption(`--enabled `, `Set whether or not to check a password for similarity with personal data. Default is false.`, parseBool) .action(actionRunner(projectsUpdatePersonalDataCheck)) +projects + .command(`updateSessionAlerts`) + .description(``) + .requiredOption(`--projectId `, `Project unique ID.`) + .requiredOption(`--alerts `, `Set to true to enable session emails.`, parseBool) + .action(actionRunner(projectsUpdateSessionAlerts)) + projects .command(`updateAuthStatus`) .description(``) @@ -1785,10 +2073,19 @@ projects .requiredOption(`--status `, `Set the status of this auth method.`, parseBool) .action(actionRunner(projectsUpdateAuthStatus)) +projects + .command(`createJWT`) + .description(``) + .requiredOption(`--projectId `, `Project unique ID.`) + .requiredOption(`--scopes [scopes...]`, `List of scopes allowed for JWT key. Maximum of 100 scopes are allowed.`) + .option(`--duration `, `Time in seconds before JWT expires. Default duration is 900 seconds, and maximum is 3600 seconds.`, parseInteger) + .action(actionRunner(projectsCreateJWT)) + projects .command(`listKeys`) .description(``) .requiredOption(`--projectId `, `Project unique ID.`) + .option(`--console`, `Get the resource console url`) .action(actionRunner(projectsListKeys)) projects @@ -1805,6 +2102,7 @@ projects .description(``) .requiredOption(`--projectId `, `Project unique ID.`) .requiredOption(`--keyId `, `Key unique ID.`) + .option(`--console`, `Get the resource console url`) .action(actionRunner(projectsGetKey)) projects @@ -1838,6 +2136,7 @@ projects .command(`listPlatforms`) .description(``) .requiredOption(`--projectId `, `Project unique ID.`) + .option(`--console`, `Get the resource console url`) .action(actionRunner(projectsListPlatforms)) projects @@ -1856,6 +2155,7 @@ projects .description(``) .requiredOption(`--projectId `, `Project unique ID.`) .requiredOption(`--platformId `, `Platform unique ID.`) + .option(`--console`, `Get the resource console url`) .action(actionRunner(projectsGetPlatform)) projects @@ -1986,6 +2286,7 @@ projects .command(`listWebhooks`) .description(``) .requiredOption(`--projectId `, `Project unique ID.`) + .option(`--console`, `Get the resource console url`) .action(actionRunner(projectsListWebhooks)) projects @@ -2006,6 +2307,7 @@ projects .description(``) .requiredOption(`--projectId `, `Project unique ID.`) .requiredOption(`--webhookId `, `Webhook unique ID.`) + .option(`--console`, `Get the resource console url`) .action(actionRunner(projectsGetWebhook)) projects @@ -2048,10 +2350,13 @@ module.exports = { projectsUpdateAuthDuration, projectsUpdateAuthLimit, projectsUpdateAuthSessionsLimit, + projectsUpdateMockNumbers, projectsUpdateAuthPasswordDictionary, projectsUpdateAuthPasswordHistory, projectsUpdatePersonalDataCheck, + projectsUpdateSessionAlerts, projectsUpdateAuthStatus, + projectsCreateJWT, projectsListKeys, projectsCreateKey, projectsGetKey, @@ -2080,4 +2385,4 @@ module.exports = { projectsUpdateWebhook, projectsDeleteWebhook, projectsUpdateWebhookSignature -}; \ No newline at end of file +}; diff --git a/lib/commands/proxy.js b/lib/commands/proxy.js index ed11a14..0c6eb08 100644 --- a/lib/commands/proxy.js +++ b/lib/commands/proxy.js @@ -4,7 +4,7 @@ const tar = require("tar"); const ignore = require("ignore"); const { promisify } = require('util'); const libClient = require('../client.js'); -const { getAllFiles } = require('../utils.js'); +const { getAllFiles, showConsoleLink } = require('../utils.js'); const { Command } = require('commander'); const { sdkForProject, sdkForConsole } = require('../sdks') const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log } = require('../parser') @@ -43,6 +43,7 @@ const proxy = new Command("proxy").description(commandDescriptions['proxy']).con * @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, resourceType, resourceId, url * @property {string} search Search term to filter your list results. Max length: 256 chars. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -50,8 +51,9 @@ const proxy = new Command("proxy").description(commandDescriptions['proxy']).con /** * @param {ProxyListRulesRequestParams} params */ -const proxyListRules = async ({ queries, search, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const proxyListRules = async ({queries,search,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/proxy/rules'; let payload = {}; if (typeof queries !== 'undefined') { @@ -71,8 +73,9 @@ const proxyListRules = async ({ queries, search, parseOutput = true, sdk = undef parse(response) success() } - + return response; + } /** @@ -80,6 +83,7 @@ const proxyListRules = async ({ queries, search, parseOutput = true, sdk = undef * @property {string} domain Domain name. * @property {ResourceType} resourceType Action definition for the rule. Possible values are "api", "function" * @property {string} resourceId ID of resource for the action type. If resourceType is "api", leave empty. If resourceType is "function", provide ID of the function. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -87,8 +91,9 @@ const proxyListRules = async ({ queries, search, parseOutput = true, sdk = undef /** * @param {ProxyCreateRuleRequestParams} params */ -const proxyCreateRule = async ({ domain, resourceType, resourceId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const proxyCreateRule = async ({domain,resourceType,resourceId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/proxy/rules'; let payload = {}; if (typeof domain !== 'undefined') { @@ -111,13 +116,15 @@ const proxyCreateRule = async ({ domain, resourceType, resourceId, parseOutput = parse(response) success() } - + return response; + } /** * @typedef {Object} ProxyGetRuleRequestParams * @property {string} ruleId Rule ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -125,8 +132,9 @@ const proxyCreateRule = async ({ domain, resourceType, resourceId, parseOutput = /** * @param {ProxyGetRuleRequestParams} params */ -const proxyGetRule = async ({ ruleId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const proxyGetRule = async ({ruleId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/proxy/rules/{ruleId}'.replace('{ruleId}', ruleId); let payload = {}; @@ -140,13 +148,15 @@ const proxyGetRule = async ({ ruleId, parseOutput = true, sdk = undefined}) => { parse(response) success() } - + return response; + } /** * @typedef {Object} ProxyDeleteRuleRequestParams * @property {string} ruleId Rule ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -154,8 +164,9 @@ const proxyGetRule = async ({ ruleId, parseOutput = true, sdk = undefined}) => { /** * @param {ProxyDeleteRuleRequestParams} params */ -const proxyDeleteRule = async ({ ruleId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const proxyDeleteRule = async ({ruleId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/proxy/rules/{ruleId}'.replace('{ruleId}', ruleId); let payload = {}; @@ -169,13 +180,15 @@ const proxyDeleteRule = async ({ ruleId, parseOutput = true, sdk = undefined}) = parse(response) success() } - + return response; + } /** * @typedef {Object} ProxyUpdateRuleVerificationRequestParams * @property {string} ruleId Rule ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -183,8 +196,9 @@ const proxyDeleteRule = async ({ ruleId, parseOutput = true, sdk = undefined}) = /** * @param {ProxyUpdateRuleVerificationRequestParams} params */ -const proxyUpdateRuleVerification = async ({ ruleId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const proxyUpdateRuleVerification = async ({ruleId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/proxy/rules/{ruleId}/verification'.replace('{ruleId}', ruleId); let payload = {}; @@ -198,8 +212,9 @@ const proxyUpdateRuleVerification = async ({ ruleId, parseOutput = true, sdk = u parse(response) success() } - + return response; + } proxy @@ -242,4 +257,4 @@ module.exports = { proxyGetRule, proxyDeleteRule, proxyUpdateRuleVerification -}; \ No newline at end of file +}; diff --git a/lib/commands/pull.js b/lib/commands/pull.js new file mode 100644 index 0000000..cea0331 --- /dev/null +++ b/lib/commands/pull.js @@ -0,0 +1,231 @@ +const fs = require("fs"); +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, functionsDownloadDeployment } = require("./functions"); +const { databasesGet, databasesListCollections, databasesList } = require("./databases"); +const { storageListBuckets } = require("./storage"); +const { localConfig } = require("../config"); +const { paginate } = require("../paginate"); +const { questionsPullCollection, questionsPullFunctions, questionsPullResources } = require("../questions"); +const { cliConfig, success, log, actionRunner, commandDescriptions } = require("../parser"); + +const pullResources = async () => { + const actions = { + project: pullProject, + functions: pullFunctions, + collections: pullCollection, + buckets: pullBucket, + teams: pullTeam, + messages: pullMessagingTopic + } + + if (cliConfig.all) { + for (let action of Object.values(actions)) { + await action(); + } + } else { + const answers = await inquirer.prompt(questionsPullResources[0]); + + const action = actions[answers.resource]; + if (action !== undefined) { + await action({ returnOnZero: true }); + } + } +}; + +const pullProject = async () => { + try { + let response = await projectsGet({ + parseOutput: false, + projectId: localConfig.getProject().projectId + + }) + + localConfig.setProject(response.$id, response.name, response); + + success(); + } catch (e) { + throw e; + } +} + +const pullFunctions = async () => { + const localFunctions = localConfig.getFunctions(); + + const functions = cliConfig.all + ? (await paginate(functionsList, { parseOutput: false }, 100, 'functions')).functions + : (await inquirer.prompt(questionsPullFunctions)).functions; + + log(`Pulling ${functions.length} functions`); + + for (let func of functions) { + const functionExistLocally = localFunctions.find((localFunc) => localFunc['$id'] === func['$id']) !== undefined; + + if (functionExistLocally) { + localConfig.updateFunction(func['$id'], func); + } else { + func['path'] = `functions/${func['$id']}`; + localConfig.addFunction(func); + localFunctions.push(func); + } + + const localFunction = localFunctions.find((localFunc) => localFunc['$id'] === func['$id']); + + if (localFunction['deployment'] === '') { + continue + } + + const compressedFileName = `${func['$id']}-${+new Date()}.tar.gz` + + await functionsDownloadDeployment({ + functionId: func['$id'], + deploymentId: func['deployment'], + destination: compressedFileName, + overrideForCli: true, + parseOutput: false + }) + + if (!fs.existsSync(localFunction['path'])) { + fs.mkdirSync(localFunction['path'], { recursive: true }); + } + + tar.extract({ + sync: true, + cwd: localFunction['path'], + file: compressedFileName, + strict: false, + }); + + fs.rmSync(compressedFileName); + success(`Pulled ${func['name']} code and settings`) + } +} + +const pullCollection = async () => { + let databases = cliConfig.ids; + + if (databases.length === 0) { + if (cliConfig.all) { + databases = (await paginate(databasesList, { parseOutput: false }, 100, 'databases')).databases.map(database => database.$id); + } else { + databases = (await inquirer.prompt(questionsPullCollection)).databases; + } + } + + for (const databaseId of databases) { + const database = await databasesGet({ + databaseId, + parseOutput: false + }); + + localConfig.addDatabase(database); + + const { collections, total } = await paginate(databasesListCollections, { + databaseId, + parseOutput: false + }, 100, 'collections'); + + log(`Found ${total} collections`); + + collections.map(async collection => { + log(`Fetching ${collection.name} ...`); + localConfig.addCollection({ + ...collection, + '$createdAt': undefined, + '$updatedAt': undefined + }); + }); + } + + success(); +} + +const pullBucket = async () => { + const { buckets } = await paginate(storageListBuckets, { parseOutput: false }, 100, 'buckets'); + + log(`Found ${buckets.length} buckets`); + + buckets.forEach(bucket => localConfig.addBucket(bucket)); + + success(); +} + +const pullTeam = async () => { + const { teams } = await paginate(teamsList, { parseOutput: false }, 100, 'teams'); + + log(`Found ${teams.length} teams`); + + teams.forEach(team => { + const { total, $updatedAt, $createdAt, prefs, ...rest } = team; + localConfig.addTeam(rest); + }); + + success(); +} + +const pullMessagingTopic = async () => { + const { topics } = await paginate(messagingListTopics, { parseOutput: false }, 100, 'topics'); + + log(`Found ${topics.length} topics`); + + topics.forEach(topic => { + localConfig.addMessagingTopic(topic); + }); + + success(); +} + +const pull = new Command("pull") + .description(commandDescriptions['pull']) + .action(actionRunner(pullResources)); + +pull + .command("all") + .description("Pull all resource.") + .action(actionRunner(() => { + cliConfig.all = true; + return pullResources(); + })); + +pull + .command("project") + .description("Pull your Appwrite project name, services and auth settings") + .action(actionRunner(pullProject)); + +pull + .command("function") + .alias("functions") + .description("Pulling your Appwrite cloud function") + .action(actionRunner(pullFunctions)) + +pull + .command("collection") + .alias("collections") + .description("Pulling your Appwrite collections") + .action(actionRunner(pullCollection)) + +pull + .command("bucket") + .alias("buckets") + .description("Pulling your Appwrite buckets") + .action(actionRunner(pullBucket)) + +pull + .command("team") + .alias("teams") + .description("Pulling your Appwrite teams") + .action(actionRunner(pullTeam)) + +pull + .command("topic") + .alias("topics") + .description("Initialise your Appwrite messaging topics") + .action(actionRunner(pullMessagingTopic)) + +module.exports = { + pull, +}; diff --git a/lib/commands/push.js b/lib/commands/push.js new file mode 100644 index 0000000..1349b73 --- /dev/null +++ b/lib/commands/push.js @@ -0,0 +1,1518 @@ +const chalk = require('chalk'); +const inquirer = require("inquirer"); +const JSONbig = require("json-bigint")({ storeAsString: false }); +const { Command } = require("commander"); +const { localConfig, globalConfig } = require("../config"); +const { Spinner, SPINNER_ARC, SPINNER_DOTS } = require('../spinner'); +const { paginate } = require('../paginate'); +const { questionsPushBuckets, questionsPushTeams, questionsPushFunctions, questionsGetEntrypoint, questionsPushCollections, questionsConfirmPushCollections, questionsPushMessagingTopics, questionsPushResources } = require("../questions"); +const { cliConfig, actionRunner, success, log, error, commandDescriptions, drawTable } = require("../parser"); +const { proxyListRules } = require('./proxy'); +const { functionsGet, functionsCreate, functionsUpdate, functionsCreateDeployment, functionsUpdateDeployment, functionsGetDeployment, functionsListVariables, functionsDeleteVariable, functionsCreateVariable } = require('./functions'); +const { + databasesGet, + databasesCreate, + databasesUpdate, + databasesCreateBooleanAttribute, + databasesGetCollection, + databasesCreateCollection, + databasesCreateStringAttribute, + databasesCreateIntegerAttribute, + databasesCreateFloatAttribute, + databasesCreateEmailAttribute, + databasesCreateDatetimeAttribute, + databasesCreateIndex, + databasesCreateUrlAttribute, + databasesCreateIpAttribute, + databasesCreateEnumAttribute, + databasesUpdateBooleanAttribute, + databasesUpdateStringAttribute, + databasesUpdateIntegerAttribute, + databasesUpdateFloatAttribute, + databasesUpdateEmailAttribute, + databasesUpdateDatetimeAttribute, + databasesUpdateUrlAttribute, + databasesUpdateIpAttribute, + databasesUpdateEnumAttribute, + databasesUpdateRelationshipAttribute, + databasesCreateRelationshipAttribute, + databasesDeleteAttribute, + databasesListAttributes, + databasesListIndexes, + databasesUpdateCollection +} = require("./databases"); +const { + storageGetBucket, storageUpdateBucket, storageCreateBucket +} = require("./storage"); +const { + messagingGetTopic, messagingUpdateTopic, messagingCreateTopic +} = require("./messaging"); +const { + teamsGet, + teamsUpdateName, + teamsCreate +} = require("./teams"); +const { + projectsUpdate, + projectsUpdateServiceStatus, + projectsUpdateAuthStatus, + projectsUpdateAuthDuration, + projectsUpdateAuthLimit, + projectsUpdateAuthSessionsLimit, + projectsUpdateAuthPasswordDictionary, + projectsUpdateAuthPasswordHistory, + projectsUpdatePersonalDataCheck, +} = require("./projects"); +const { checkDeployConditions } = require('../utils'); + +const STEP_SIZE = 100; // Resources +const POLL_DEBOUNCE = 2000; // Milliseconds +const POLL_MAX_DEBOUNCE = 30; // Times + +let pollMaxDebounces = 30; + +const changeableKeys = ['status', 'required', 'xdefault', 'elements', 'min', 'max', 'default', 'error']; + +const awaitPools = { + wipeAttributes: async (databaseId, collectionId, iteration = 1) => { + if (iteration > pollMaxDebounces) { + return false; + } + + const { total } = await databasesListAttributes({ + databaseId, + collectionId, + queries: [JSON.stringify({ method: 'limit', values: [1] })], + parseOutput: false + }); + + if (total === 0) { + return true; + } + + let steps = Math.max(1, Math.ceil(total / STEP_SIZE)); + if (steps > 1 && iteration === 1) { + pollMaxDebounces *= steps; + + log('Found a large number of attributes, increasing timeout to ' + (pollMaxDebounces * POLL_DEBOUNCE / 1000 / 60) + ' minutes') + } + + await new Promise(resolve => setTimeout(resolve, POLL_DEBOUNCE)); + + return await awaitPools.wipeAttributes( + databaseId, + collectionId, + iteration + 1 + ); + }, + wipeIndexes: async (databaseId, collectionId, iteration = 1) => { + if (iteration > pollMaxDebounces) { + return false; + } + + const { total } = await databasesListIndexes({ + databaseId, + collectionId, + queries: [JSON.stringify({ method: 'limit', values: [1] })], + parseOutput: false + }); + + if (total === 0) { + return true; + } + + let steps = Math.max(1, Math.ceil(total / STEP_SIZE)); + if (steps > 1 && iteration === 1) { + pollMaxDebounces *= steps; + + log('Found a large number of indexes, increasing timeout to ' + (pollMaxDebounces * POLL_DEBOUNCE / 1000 / 60) + ' minutes') + } + + await new Promise(resolve => setTimeout(resolve, POLL_DEBOUNCE)); + + return await awaitPools.wipeIndexes( + databaseId, + collectionId, + iteration + 1 + ); + }, + wipeVariables: async (functionId, iteration = 1) => { + if (iteration > pollMaxDebounces) { + return false; + } + + const { total } = await functionsListVariables({ + functionId, + queries: ['limit(1)'], + parseOutput: false + }); + + if (total === 0) { + return true; + } + + let steps = Math.max(1, Math.ceil(total / STEP_SIZE)); + if (steps > 1 && iteration === 1) { + pollMaxDebounces *= steps; + + log('Found a large number of variables, increasing timeout to ' + (pollMaxDebounces * POLL_DEBOUNCE / 1000 / 60) + ' minutes') + } + + await new Promise(resolve => setTimeout(resolve, POLL_DEBOUNCE)); + + return await awaitPools.wipeVariables( + functionId, + iteration + 1 + ); + }, + deleteAttributes: async (databaseId, collectionId, attributeKeys, iteration = 1) => { + if (iteration > pollMaxDebounces) { + return false; + } + + let steps = Math.max(1, Math.ceil(attributeKeys.length / STEP_SIZE)); + if (steps > 1 && iteration === 1) { + pollMaxDebounces *= steps; + + log('Found a large number of attributes to be deleted. Increasing timeout to ' + (pollMaxDebounces * POLL_DEBOUNCE / 1000 / 60) + ' minutes') + } + + const { attributes } = await paginate(databasesListAttributes, { + databaseId, + collectionId, + parseOutput: false + }, 100, 'attributes'); + + const ready = attributeKeys.filter(attribute => attributes.includes(attribute.key)); + + if (ready.length === 0) { + return true; + } + + await new Promise(resolve => setTimeout(resolve, POLL_DEBOUNCE)); + + return await awaitPools.expectAttributes( + databaseId, + collectionId, + attributeKeys, + iteration + 1 + ); + }, + expectAttributes: async (databaseId, collectionId, attributeKeys, iteration = 1) => { + if (iteration > pollMaxDebounces) { + return false; + } + + let steps = Math.max(1, Math.ceil(attributeKeys.length / STEP_SIZE)); + if (steps > 1 && iteration === 1) { + pollMaxDebounces *= steps; + + log('Creating a large number of attributes, increasing timeout to ' + (pollMaxDebounces * POLL_DEBOUNCE / 1000 / 60) + ' minutes') + } + + const { attributes } = await paginate(databasesListAttributes, { + databaseId, + collectionId, + parseOutput: false + }, 100, 'attributes'); + + const ready = attributes + .filter(attribute => { + if (attributeKeys.includes(attribute.key)) { + if (['stuck', 'failed'].includes(attribute.status)) { + throw new Error(`Attribute '${attribute.key}' failed!`); + } + + return attribute.status === 'available'; + } + + return false; + }) + .map(attribute => attribute.key); + + if (ready.length === attributeKeys.length) { + return true; + } + + await new Promise(resolve => setTimeout(resolve, POLL_DEBOUNCE)); + + return await awaitPools.expectAttributes( + databaseId, + collectionId, + attributeKeys, + iteration + 1 + ); + }, + expectIndexes: async (databaseId, collectionId, indexKeys, iteration = 1) => { + if (iteration > pollMaxDebounces) { + return false; + } + + let steps = Math.max(1, Math.ceil(indexKeys.length / STEP_SIZE)); + if (steps > 1 && iteration === 1) { + pollMaxDebounces *= steps; + + log('Creating a large number of indexes, increasing timeout to ' + (pollMaxDebounces * POLL_DEBOUNCE / 1000 / 60) + ' minutes') + } + + const { indexes } = await paginate(databasesListIndexes, { + databaseId, + collectionId, + parseOutput: false + }, 100, 'indexes'); + + const ready = indexes + .filter((index) => { + if (indexKeys.includes(index.key)) { + if (['stuck', 'failed'].includes(index.status)) { + throw new Error(`Index '${index.key}' failed!`); + } + + return index.status === 'available'; + } + + return false; + }) + .map(index => index.key); + + if (ready.length >= indexKeys.length) { + return true; + } + + await new Promise(resolve => setTimeout(resolve, POLL_DEBOUNCE)); + + return await awaitPools.expectIndexes( + databaseId, + collectionId, + indexKeys, + iteration + 1 + ); + }, +} + +const createAttribute = async (databaseId, collectionId, attribute) => { + switch (attribute.type) { + case 'string': + switch (attribute.format) { + case 'email': + return await databasesCreateEmailAttribute({ + databaseId, + collectionId, + key: attribute.key, + required: attribute.required, + xdefault: attribute.default, + array: attribute.array, + parseOutput: false + }) + case 'url': + return await databasesCreateUrlAttribute({ + databaseId, + collectionId, + key: attribute.key, + required: attribute.required, + xdefault: attribute.default, + array: attribute.array, + parseOutput: false + }) + case 'ip': + return await databasesCreateIpAttribute({ + databaseId, + collectionId, + key: attribute.key, + required: attribute.required, + xdefault: attribute.default, + array: attribute.array, + parseOutput: false + }) + case 'enum': + return await databasesCreateEnumAttribute({ + databaseId, + collectionId, + key: attribute.key, + elements: attribute.elements, + required: attribute.required, + xdefault: attribute.default, + array: attribute.array, + parseOutput: false + }) + default: + return await databasesCreateStringAttribute({ + databaseId, + collectionId, + key: attribute.key, + size: attribute.size, + required: attribute.required, + xdefault: attribute.default, + array: attribute.array, + parseOutput: false + }) + + } + case 'integer': + return await databasesCreateIntegerAttribute({ + databaseId, + collectionId, + key: attribute.key, + required: attribute.required, + min: parseInt(attribute.min.toString()), + max: parseInt(attribute.max.toString()), + xdefault: attribute.default, + array: attribute.array, + parseOutput: false + }) + case 'double': + return databasesCreateFloatAttribute({ + databaseId, + collectionId, + key: attribute.key, + required: attribute.required, + min: parseFloat(attribute.min.toString()), + max: parseFloat(attribute.max.toString()), + xdefault: attribute.default, + array: attribute.array, + parseOutput: false + }) + case 'boolean': + return databasesCreateBooleanAttribute({ + databaseId, + collectionId, + key: attribute.key, + required: attribute.required, + xdefault: attribute.default, + array: attribute.array, + parseOutput: false + }) + case 'datetime': + return databasesCreateDatetimeAttribute({ + databaseId, + collectionId, + key: attribute.key, + required: attribute.required, + xdefault: attribute.default, + array: attribute.array, + parseOutput: false + }) + case 'relationship': + return databasesCreateRelationshipAttribute({ + databaseId, + collectionId, + relatedCollectionId: attribute.relatedCollection, + type: attribute.relationType, + twoWay: attribute.twoWay, + key: attribute.key, + twoWayKey: attribute.twoWayKey, + onDelete: attribute.onDelete, + parseOutput: false + }) + } +} + +const updateAttribute = async (databaseId, collectionId, attribute) => { + switch (attribute.type) { + case 'string': + switch (attribute.format) { + case 'email': + return await databasesUpdateEmailAttribute({ + databaseId, + collectionId, + key: attribute.key, + required: attribute.required, + xdefault: attribute.default, + array: attribute.array, + parseOutput: false + }) + case 'url': + return await databasesUpdateUrlAttribute({ + databaseId, + collectionId, + key: attribute.key, + required: attribute.required, + xdefault: attribute.default, + array: attribute.array, + parseOutput: false + }) + case 'ip': + return await databasesUpdateIpAttribute({ + databaseId, + collectionId, + key: attribute.key, + required: attribute.required, + xdefault: attribute.default, + array: attribute.array, + parseOutput: false + }) + case 'enum': + return await databasesUpdateEnumAttribute({ + databaseId, + collectionId, + key: attribute.key, + elements: attribute.elements, + required: attribute.required, + xdefault: attribute.default, + array: attribute.array, + parseOutput: false + }) + default: + return await databasesUpdateStringAttribute({ + databaseId, + collectionId, + key: attribute.key, + size: attribute.size, + required: attribute.required, + xdefault: attribute.default, + array: attribute.array, + parseOutput: false + }) + + } + case 'integer': + return await databasesUpdateIntegerAttribute({ + databaseId, + collectionId, + key: attribute.key, + required: attribute.required, + min: parseInt(attribute.min.toString()), + max: parseInt(attribute.max.toString()), + xdefault: attribute.default, + array: attribute.array, + parseOutput: false + }) + case 'double': + return databasesUpdateFloatAttribute({ + databaseId, + collectionId, + key: attribute.key, + required: attribute.required, + min: parseFloat(attribute.min.toString()), + max: parseFloat(attribute.max.toString()), + xdefault: attribute.default, + array: attribute.array, + parseOutput: false + }) + case 'boolean': + return databasesUpdateBooleanAttribute({ + databaseId, + collectionId, + key: attribute.key, + required: attribute.required, + xdefault: attribute.default, + array: attribute.array, + parseOutput: false + }) + case 'datetime': + return databasesUpdateDatetimeAttribute({ + databaseId, + collectionId, + key: attribute.key, + required: attribute.required, + xdefault: attribute.default, + array: attribute.array, + parseOutput: false + }) + case 'relationship': + return databasesUpdateRelationshipAttribute({ + databaseId, + collectionId, + relatedCollectionId: attribute.relatedCollection, + type: attribute.relationType, + twoWay: attribute.twoWay, + key: attribute.key, + twoWayKey: attribute.twoWayKey, + onDelete: attribute.onDelete, + parseOutput: false + }) + } +} +const deleteAttribute = async (collection, attribute) => { + log(`Deleting attribute ${attribute.key} of ${collection.name} ( ${collection['$id']} )`); + + await databasesDeleteAttribute({ + databaseId: collection['databaseId'], + collectionId: collection['$id'], + key: attribute.key, + parseOutput: false + }); +} + + +/** + * Check if attribute non-changeable fields has been changed + * If so return the differences as an object. + * @param remote + * @param local + * @param collection + * @param recraeting when true will check only non-changeable keys + * @returns {undefined|{reason: string, action: *, attribute, key: string}} + */ +const checkAttributeChanges = (remote, local, collection, recraeting = true) => { + if (local === undefined) { + return undefined; + } + + const keyName = `${chalk.yellow(local.key)} in ${collection.name} (${collection['$id']})`; + const action = chalk.cyan(recraeting ? 'recreating' : 'changing'); + let reason = ''; + let attribute = remote; + + for (let key of Object.keys(remote)) { + if (changeableKeys.includes(key)) { + if (!recraeting) { + if (remote[key] !== local[key]) { + const bol = reason === '' ? '' : '\n'; + reason += `${bol}${key} changed from ${chalk.red(remote[key])} to ${chalk.green(local[key])}`; + attribute = local; + } + } + continue; + } + + if (!recraeting) { + continue; + } + + if (remote[key] !== local[key]) { + const bol = reason === '' ? '' : '\n'; + reason += `${bol}${key} changed from ${chalk.red(remote[key])} to ${chalk.green(local[key])}`; + } + } + + return reason === '' ? undefined : { key: keyName, attribute, reason, action }; +} + +/** + * 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) => { + return { + key: `${chalk.yellow(attribute.key)} in ${collection.name} (${collection['$id']})`, + attribute: attribute, + reason: isAdding ? 'Field doesn\'t exist on the remote server' : 'Field doesn\'t exist in appwrite.json file', + action: isAdding ? chalk.green('adding') : chalk.red('deleting') + }; + +}; + +/** + * Filter deleted and recreated attributes, + * return list of attributes to create + * @param remoteAttributes + * @param localAttributes + * @param collection + * @returns {Promise<*|*[]>} + */ +const attributesToCreate = async (remoteAttributes, localAttributes, collection) => { + + 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 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); + + let changedAttributes = []; + const changing = [...deleting, ...adding, ...conflicts, ...changes] + if (changing.length === 0) { + return changedAttributes; + } + + log(!cliConfig.force ? 'There are pending changes in your collection deployment' : 'List of applied changes'); + + drawTable(changing.map((change) => { + return { Key: change.key, Action: change.action, Reason: change.reason, }; + })); + + if (!cliConfig.force) { + if (deleting.length > 0) { + log(`Attribute deletion will cause ${chalk.red('loss of data')}`); + } + if (conflicts.length > 0) { + log(`Attribute recreation will cause ${chalk.red('loss of data')}`); + } + + const answers = await inquirer.prompt(questionsPushCollections[1]); + + if (answers.changes.toLowerCase() !== 'yes') { + return changedAttributes; + } + } + + if (conflicts.length > 0) { + changedAttributes = conflicts.map((change) => change.attribute); + await Promise.all(changedAttributes.map((changed) => deleteAttribute(collection, changed))); + remoteAttributes = remoteAttributes.filter((attribute) => !attributesContains(attribute, changedAttributes)) + } + + if (changes.length > 0) { + changedAttributes = changes.map((change) => change.attribute); + await Promise.all(changedAttributes.map((changed) => updateAttribute(collection['databaseId'],collection['$id'], changed))); + } + + const deletingAttributes = deleting.map((change) => change.attribute); + await Promise.all(deletingAttributes.map((attribute) => deleteAttribute(collection, attribute))); + const attributeKeys = [...remoteAttributes.map(attribute => attribute.key), ...deletingAttributes.map(attribute => attribute.key)] + + if (attributeKeys.length) { + const deleteAttributesPoolStatus = await awaitPools.deleteAttributes(collection['databaseId'], collection['$id'], attributeKeys); + + if (!deleteAttributesPoolStatus) { + throw new Error("Attribute deletion timed out."); + } + } + + return localAttributes.filter((attribute) => !attributesContains(attribute, remoteAttributes)); +} +const createIndexes = async (indexes, collection) => { + log(`Creating indexes ...`) + + for (let index of indexes) { + await databasesCreateIndex({ + databaseId: collection['databaseId'], + collectionId: collection['$id'], + key: index.key, + type: index.type, + attributes: index.attributes, + orders: index.orders, + parseOutput: false + }); + } + + const result = await awaitPools.expectIndexes( + collection['databaseId'], + collection['$id'], + indexes.map(index => index.key) + ); + + if (!result) { + throw new Error("Index creation timed out."); + } + + success(`Created ${indexes.length} indexes`); +} +const createAttributes = async (attributes, collection) => { + for (let attribute of attributes) { + if (attribute.side !== 'child') { + await createAttribute(collection['databaseId'], collection['$id'], attribute); + } + } + + const result = await awaitPools.expectAttributes( + collection['databaseId'], + collection['$id'], + collection.attributes.map(attribute => attribute.key) + ); + + if (!result) { + throw new Error(`Attribute creation timed out.`); + } + + success(`Created ${attributes.length} attributes`); +} + +const pushResources = async () => { + const actions = { + project: pushProject, + functions: pushFunction, + collections: pushCollection, + buckets: pushBucket, + teams: pushTeam, + messages: pushMessagingTopic + } + + if (cliConfig.all) { + for (let action of Object.values(actions)) { + await action({ returnOnZero: true }); + } + } else { + const answers = await inquirer.prompt(questionsPushResources[0]); + + const action = actions[answers.resource]; + if (action !== undefined) { + await action({ returnOnZero: true }); + } + } +}; + +const pushProject = async () => { + try { + const projectId = localConfig.getProject().projectId; + const projectName = localConfig.getProject().projectName; + const settings = localConfig.getProject().projectSettings ?? {}; + + log(`Updating project ${projectId}`); + + if (projectName) { + await projectsUpdate({ + projectId, + name: projectName, + parseOutput: false + }); + } + + if (settings.services) { + log('Updating service statuses'); + for (let [service, status] of Object.entries(settings.services)) { + await projectsUpdateServiceStatus({ + projectId, + service, + status, + parseOutput: false + }); + } + } + + if (settings.auth) { + if (settings.auth.security) { + log('Updating auth security settings'); + await projectsUpdateAuthDuration({ projectId, duration: settings.auth.security.duration, parseOutput: false }); + await projectsUpdateAuthLimit({ projectId, limit: settings.auth.security.limit, parseOutput: false }); + await projectsUpdateAuthSessionsLimit({ projectId, limit: settings.auth.security.sessionsLimit, parseOutput: false }); + await projectsUpdateAuthPasswordDictionary({ projectId, enabled: settings.auth.security.passwordDictionary, parseOutput: false }); + await projectsUpdateAuthPasswordHistory({ projectId, limit: settings.auth.security.passwordHistory, parseOutput: false }); + await projectsUpdatePersonalDataCheck({ projectId, enabled: settings.auth.security.personalDataCheck, parseOutput: false }); + } + + if (settings.auth.methods) { + log('Updating auth login methods'); + + for (let [method, status] of Object.entries(settings.auth.methods)) { + await projectsUpdateAuthStatus({ + projectId, + method, + status, + parseOutput: false + }); + } + } + } + + success("Project configuration updated."); + } catch (e) { + throw e; + } +} + +const pushFunction = async ({ functionId, async, returnOnZero } = { returnOnZero: false }) => { + let response = {}; + + const functionIds = []; + + if (functionId) { + functionIds.push(functionId); + } else if (cliConfig.all) { + checkDeployConditions(localConfig); + const functions = localConfig.getFunctions(); + if (functions.length === 0) { + if (returnOnZero) { + log('No functions found, skipping'); + return; + } + throw new Error("No functions found in the current directory. Use 'appwrite pull functions' to synchronize existing one, or use 'appwrite init function' to create a new one."); + } + functionIds.push(...functions.map((func) => { + return func.$id; + })); + } + + if (functionIds.length <= 0) { + const answers = await inquirer.prompt(questionsPushFunctions[0]); + functionIds.push(...answers.functions); + } + + let functions = functionIds.map((id) => { + const functions = localConfig.getFunctions(); + const func = functions.find((f) => f.$id === id); + + if (!func) { + throw new Error("Function '" + id + "' not found.") + } + + return func; + }); + + log('Validating functions'); + // Validation is done BEFORE pushing so the deployment process can be run in async with progress update + for (let func of functions) { + + if (!func.entrypoint) { + log(`Function ${func.name} does not have an endpoint`); + const answers = await inquirer.prompt(questionsGetEntrypoint) + func.entrypoint = answers.entrypoint; + localConfig.updateFunction(func['$id'], func); + } + + if (func.variables) { + func.pushVariables = cliConfig.force; + + try { + const { total } = await functionsListVariables({ + functionId: func['$id'], + queries: [JSON.stringify({ method: 'limit', values: [1] })], + parseOutput: false + }); + + if (total === 0) { + func.pushVariables = true; + } else if (total > 0 && !func.pushVariables) { + log(`The function ${func.name} has remote variables setup`); + const variableAnswers = await inquirer.prompt(questionsPushFunctions[1]) + func.pushVariables = variableAnswers.override.toLowerCase() === "yes"; + } + } catch (e) { + if (e.code != 404) { + throw e.message; + } + } + } + } + + + log('All functions are validated'); + log('Pushing functions\n'); + + Spinner.start(false); + let successfullyPushed = 0; + let successfullyDeployed = 0; + const failedDeployments = []; + + await Promise.all(functions.map(async (func) => { + const ignore = func.ignore ? 'appwrite.json' : '.gitignore'; + let functionExists = false; + let deploymentCreated = false; + + const updaterRow = new Spinner({ status: '', resource: func.name, id: func['$id'], end: `Ignoring using: ${ignore}` }); + + updaterRow.update({ status: 'Getting' }).startSpinner(SPINNER_DOTS); + + try { + response = await functionsGet({ + functionId: func['$id'], + parseOutput: false, + }); + functionExists = true; + if (response.runtime !== func.runtime) { + updaterRow.fail({ errorMessage: `Runtime mismatch! (local=${func.runtime},remote=${response.runtime}) Please delete remote function or update your appwrite.json` }) + return; + } + + updaterRow.update({ status: 'Updating' }).replaceSpinner(SPINNER_ARC); + + response = await functionsUpdate({ + functionId: func['$id'], + name: func.name, + execute: func.execute, + events: func.events, + schedule: func.schedule, + timeout: func.timeout, + enabled: func.enabled, + logging: func.logging, + entrypoint: func.entrypoint, + commands: func.commands, + providerRepositoryId: func.providerRepositoryId ?? "", + installationId: func.installationId ?? '', + providerBranch: func.providerBranch ?? '', + providerRootDirectory: func.providerRootDirectory ?? '', + providerSilentMode: func.providerSilentMode ?? false, + vars: JSON.stringify(response.vars), + parseOutput: false + }); + } catch (e) { + + if (Number(e.code) === 404) { + functionExists = false; + } else { + updaterRow.fail({ errorMessage: e.message ?? 'General error occurs please try again' }); + return; + } + } + + if (!functionExists) { + updaterRow.update({ status: 'Creating' }).replaceSpinner(SPINNER_DOTS); + + try { + response = await functionsCreate({ + functionId: func.$id || 'unique()', + name: func.name, + runtime: func.runtime, + execute: func.execute, + events: func.events, + schedule: func.schedule, + timeout: func.timeout, + enabled: func.enabled, + logging: func.logging, + entrypoint: func.entrypoint, + commands: func.commands, + vars: JSON.stringify(func.vars), + parseOutput: false + }); + + localConfig.updateFunction(func['$id'], { + "$id": response['$id'], + }); + func["$id"] = response['$id']; + updaterRow.update({ status: 'Created' }); + } catch (e) { + updaterRow.fail({ errorMessage: e.message ?? 'General error occurs please try again' }); + return; + } + } + + if (func.variables) { + if (!func.pushVariables) { + updaterRow.update({ end: 'Skipping variables' }); + } else { + updaterRow.update({ end: 'Pushing variables' }); + + const { variables } = await paginate(functionsListVariables, { + functionId: func['$id'], + parseOutput: false + }, 100, 'variables'); + + await Promise.all(variables.map(async variable => { + await functionsDeleteVariable({ + functionId: func['$id'], + variableId: variable['$id'], + parseOutput: false + }); + })); + + let result = await awaitPools.wipeVariables(func['$id']); + if (!result) { + updaterRow.fail({ errorMessage: 'Variable deletion timed out' }) + return; + } + + // Push local variables + await Promise.all(Object.keys(func.variables).map(async localVariableKey => { + await functionsCreateVariable({ + functionId: func['$id'], + key: localVariableKey, + value: func.variables[localVariableKey], + parseOutput: false + }); + })); + } + } + + try { + updaterRow.update({ status: 'Pushing' }).replaceSpinner(SPINNER_ARC); + response = await functionsCreateDeployment({ + functionId: func['$id'], + entrypoint: func.entrypoint, + commands: func.commands, + code: func.path, + activate: true, + parseOutput: false + }) + + updaterRow.update({ status: 'Pushed' }); + deploymentCreated = true; + successfullyPushed++; + } catch (e) { + switch (e.code) { + case 'ENOENT': + updaterRow.fail({ errorMessage: 'Not found in the current directory. Skipping...' }) + break; + default: + updaterRow.fail({ errorMessage: e.message ?? 'An unknown error occurred. Please try again.' }) + } + } + + if (deploymentCreated && !async) { + try { + const deploymentId = response['$id']; + updaterRow.update({ status: 'Deploying', end: 'Checking deployment status...' }) + let pollChecks = 0; + + while (true) { + if (pollChecks >= POLL_MAX_DEBOUNCE) { + updaterRow.update({ end: 'Deployment is taking too long. Please check the console for more details.' }) + break; + } + + response = await functionsGetDeployment({ + functionId: func['$id'], + deploymentId: deploymentId, + parseOutput: false + }); + + + const status = response['status']; + if (status === 'ready') { + successfullyDeployed++; + + let url = ''; + const res = await proxyListRules({ + parseOutput: false, + queries: [ + JSON.stringify({ method: 'limit', values: [1] }), + JSON.stringify({ method: 'equal', "attribute": "resourceType", "values": ["function"] }), + JSON.stringify({ method: 'equal', "attribute": "resourceId", "values": [func['$id']] }) + ], + }); + + if (Number(res.total) === 1) { + url = res.rules[0].domain; + } + + updaterRow.update({ status: 'Deployed', end: url }); + + break; + } else if (status === 'failed') { + failedDeployments.push({ name: func['name'], $id: func['$id'], deployment: response['$id'] }); + updaterRow.fail({ errorMessage: `Failed to deploy` }); + + break; + } else { + updaterRow.update({ status: 'Deploying', end: `Current status: ${status}` }) + } + + pollChecks++; + await new Promise(resolve => setTimeout(resolve, POLL_DEBOUNCE)); + } + } catch (e) { + updaterRow.fail({ errorMessage: e.message ?? 'Unknown error occurred. Please try again' }) + } + } + + updaterRow.stopSpinner(); + })); + + Spinner.stop(); + console.log('\n'); + + failedDeployments.forEach((failed) => { + const { name, deployment, $id } = failed; + const failUrl = `${globalConfig.getEndpoint().replace('/v1', '')}/console/project-${localConfig.getProject().projectId}/functions/function-${$id}/deployment-${deployment}`; + + error(`Deployment of ${name} has failed. Check at ${failUrl} for more details\n`); + }) + + let message = chalk.green(`Pushed and deployed ${successfullyPushed} functions`); + + if (!async) { + if (successfullyDeployed < successfullyPushed) { + message = `${chalk.green(`Pushed and deployed ${successfullyPushed} functions.`)} ${chalk.red(`${successfullyPushed - successfullyDeployed} failed to deploy`)}`; + } else { + if (successfullyPushed === 0) { + message = chalk.red(`Error pushing ${functions.length} functions`) + } + } + } + log(message); +} + +const pushCollection = async ({ returnOnZero } = { returnOnZero: false }) => { + const collections = []; + + if (cliConfig.all) { + checkDeployConditions(localConfig); + if (localConfig.getCollections().length === 0) { + if (returnOnZero) { + log('No collections found, skipping'); + return; + } + + throw new Error("No collections found in the current directory. Use 'appwrite pull collections' to synchronize existing one, or use 'appwrite init collection' to create a new one."); + } + collections.push(...localConfig.getCollections()); + } else { + const answers = await inquirer.prompt(questionsPushCollections[0]) + const configCollections = new Map(); + localConfig.getCollections().forEach((c) => { + configCollections.set(`${c['databaseId']}|${c['$id']}`, c); + }); + answers.collections.forEach((a) => { + const collection = configCollections.get(a); + collections.push(collection); + }) + } + const databases = Array.from(new Set(collections.map(collection => collection['databaseId']))); + log('Checking for databases and collection changes'); + + // Parallel db actions + await Promise.all(databases.map(async (databaseId) => { + const localDatabase = localConfig.getDatabase(databaseId); + + try { + const database = await databasesGet({ + databaseId: databaseId, + parseOutput: false, + }); + + if (database.name !== (localDatabase.name ?? databaseId)) { + await databasesUpdate({ + databaseId: databaseId, + name: localDatabase.name ?? databaseId, + parseOutput: false + }) + + success(`Updated ${localDatabase.name} ( ${databaseId} ) name`); + } + } catch (err) { + log(`Database ${databaseId} not found. Creating it now...`); + + await databasesCreate({ + databaseId: databaseId, + name: localDatabase.name ?? databaseId, + parseOutput: false, + }); + } + })); + + // Parallel collection actions + await Promise.all(collections.map(async (collection) => { + try { + const remoteCollection = await databasesGetCollection({ + databaseId: collection['databaseId'], + collectionId: collection['$id'], + parseOutput: false, + }); + + if (remoteCollection.name !== collection.name) { + await databasesUpdateCollection({ + databaseId: collection['databaseId'], + collectionId: collection['$id'], + name: collection.name, + name: collection.name, + parseOutput: false + }) + + success(`Updated ${collection.name} ( ${collection['$id']} ) name`); + } + collection.remoteVersion = remoteCollection; + + collection.isExisted = true; + } catch + (e) { + if (Number(e.code) === 404) { + log(`Collection ${collection.name} does not exist in the project. Creating ... `); + await databasesCreateCollection({ + databaseId: collection['databaseId'], + collectionId: collection['$id'], + name: collection.name, + documentSecurity: collection.documentSecurity, + permissions: collection['$permissions'], + parseOutput: false + }) + } else { + throw e; + } + } + })) + + // Serialize attribute actions + for (let collection of collections) { + let attributes = collection.attributes; + + if (collection.isExisted) { + attributes = await attributesToCreate(collection.remoteVersion.attributes, collection.attributes, collection); + + if (Array.isArray(attributes) && attributes.length <= 0) { + continue; + } + } + + log(`Pushing collection ${collection.name} ( ${collection['databaseId']} - ${collection['$id']} ) attributes`) + + try { + await createAttributes(attributes, collection) + } catch (e) { + throw e; + } + + try { + await createIndexes(collection.indexes, collection); + } catch (e) { + throw e; + } + + success(`Pushed ${collection.name} ( ${collection['$id']} )`); + } +} + +const pushBucket = async ({ returnOnZero } = { returnOnZero: false }) => { + let response = {}; + + let bucketIds = []; + const configBuckets = localConfig.getBuckets(); + + if (cliConfig.all) { + checkDeployConditions(localConfig); + if (configBuckets.length === 0) { + if (returnOnZero) { + log('No buckets found, skipping'); + return; + } + throw new Error("No buckets found in the current directory. Use 'appwrite pull buckets' to synchronize existing one, or use 'appwrite init bucket' to create a new one."); + } + bucketIds.push(...configBuckets.map((b) => b.$id)); + } + + if (bucketIds.length === 0) { + const answers = await inquirer.prompt(questionsPushBuckets[0]) + bucketIds.push(...answers.buckets); + } + + let buckets = []; + + for (const bucketId of bucketIds) { + const idBuckets = configBuckets.filter((b) => b.$id === bucketId); + buckets.push(...idBuckets); + } + + for (let bucket of buckets) { + log(`Pushing bucket ${bucket.name} ( ${bucket['$id']} )`) + + try { + response = await storageGetBucket({ + bucketId: bucket['$id'], + parseOutput: false, + }) + + log(`Updating bucket ...`) + + await storageUpdateBucket({ + bucketId: bucket['$id'], + name: bucket.name, + permissions: bucket['$permissions'], + fileSecurity: bucket.fileSecurity, + enabled: bucket.enabled, + maximumFileSize: bucket.maximumFileSize, + allowedFileExtensions: bucket.allowedFileExtensions, + encryption: bucket.encryption, + antivirus: bucket.antivirus, + compression: bucket.compression, + parseOutput: false + }); + + success(`Pushed ${bucket.name} ( ${bucket['$id']} )`); + } catch (e) { + if (Number(e.code) === 404) { + log(`Bucket ${bucket.name} does not exist in the project. Creating ... `); + + response = await storageCreateBucket({ + bucketId: bucket['$id'], + name: bucket.name, + permissions: bucket['$permissions'], + fileSecurity: bucket.fileSecurity, + enabled: bucket.enabled, + maximumFileSize: bucket.maximumFileSize, + allowedFileExtensions: bucket.allowedFileExtensions, + compression: bucket.compression, + encryption: bucket.encryption, + antivirus: bucket.antivirus, + parseOutput: false + }) + + success(`Pushed ${bucket.name} ( ${bucket['$id']} )`); + } else { + throw e; + } + } + } +} + +const pushTeam = async ({ returnOnZero } = { returnOnZero: false }) => { + let response = {}; + + let teamIds = []; + const configTeams = localConfig.getTeams(); + + if (cliConfig.all) { + checkDeployConditions(localConfig); + if (configTeams.length === 0) { + if (returnOnZero) { + log('No teams found, skipping'); + return; + } + throw new Error("No teams found in the current directory. Use 'appwrite pull teams' to synchronize existing one, or use 'appwrite init team' to create a new one."); + } + teamIds.push(...configTeams.map((t) => t.$id)); + } + + if (teamIds.length === 0) { + const answers = await inquirer.prompt(questionsPushTeams[0]) + teamIds.push(...answers.teams); + } + + let teams = []; + + for (const teamId of teamIds) { + const idTeams = configTeams.filter((t) => t.$id === teamId); + teams.push(...idTeams); + } + + for (let team of teams) { + log(`Pushing team ${team.name} ( ${team['$id']} )`) + + try { + response = await teamsGet({ + teamId: team['$id'], + parseOutput: false, + }) + + log(`Updating team ...`) + + await teamsUpdateName({ + teamId: team['$id'], + name: team.name, + parseOutput: false + }); + + success(`Pushed ${team.name} ( ${team['$id']} )`); + } catch (e) { + if (Number(e.code) === 404) { + log(`Team ${team.name} does not exist in the project. Creating ... `); + + response = await teamsCreate({ + teamId: team['$id'], + name: team.name, + parseOutput: false + }) + + success(`Pushed ${team.name} ( ${team['$id']} )`); + } else { + throw e; + } + } + } +} + +const pushMessagingTopic = async ({ returnOnZero } = { returnOnZero: false }) => { + let response = {}; + + let topicsIds = []; + const configTopics = localConfig.getMessagingTopics(); + let overrideExisting = cliConfig.force; + + if (cliConfig.all) { + checkDeployConditions(localConfig); + if (configTopics.length === 0) { + if (returnOnZero) { + log('No topics found, skipping'); + return; + } + throw new Error("No topics found in the current directory. Use 'appwrite pull topics' to synchronize existing one, or use 'appwrite init topic' to create a new one."); + } + topicsIds.push(...configTopics.map((b) => b.$id)); + } + + if (topicsIds.length === 0) { + const answers = await inquirer.prompt(questionsPushMessagingTopics[0]) + topicsIds.push(...answers.topics); + } + + let topics = []; + + for (const topicId of topicsIds) { + const idTopic = configTopics.filter((b) => b.$id === topicId); + topics.push(...idTopic); + } + + if (!cliConfig.force) { + const answers = await inquirer.prompt(questionsPushMessagingTopics[1]) + if (answers.override.toLowerCase() === "yes") { + overrideExisting = true; + } + } + + for (let topic of topics) { + log(`Pushing topic ${topic.name} ( ${topic['$id']} )`) + + try { + response = await messagingGetTopic({ + topicId: topic['$id'], + parseOutput: false + }) + log(`Topic ${topic.name} ( ${topic['$id']} ) already exists.`); + + if (!overrideExisting) { + log(`Skipping ${topic.name} ( ${topic['$id']} )`); + continue; + } + + log(`Updating Topic ...`) + + await messagingUpdateTopic({ + topicId: topic['$id'], + name: topic.name, + subscribe: topic.subscribe, + parseOutput: false + }); + + success(`Pushed ${topic.name} ( ${topic['$id']} )`); + } catch (e) { + if (Number(e.code) === 404) { + log(`Topic ${topic.name} does not exist in the project. Creating ... `); + + response = await messagingCreateTopic({ + topicId: topic['$id'], + name: topic.name, + subscribe: topic.subscribe, + parseOutput: false + }) + + success(`Created ${topic.name} ( ${topic['$id']} )`); + } else { + throw e; + } + } + } +} + +const push = new Command("push") + .description(commandDescriptions['push']) + .action(actionRunner(pushResources)); + +push + .command("all") + .description("Push all resource.") + .action(actionRunner(() => { + cliConfig.all = true; + return pushResources(); + })); + +push + .command("project") + .description("Push project name, services and auth settings") + .action(actionRunner(pushProject)); + +push + .command("function") + .alias("functions") + .description("Push functions in the current directory.") + .option(`-f, --functionId `, `Function ID`) + .option(`-A, --async`, `Don't wait for functions deployments status`) + .action(actionRunner(pushFunction)); + +push + .command("collection") + .alias("collections") + .description("Push collections in the current project.") + .action(actionRunner(pushCollection)); + +push + .command("bucket") + .alias("buckets") + .description("Push buckets in the current project.") + .action(actionRunner(pushBucket)); + +push + .command("team") + .alias("teams") + .description("Push teams in the current project.") + .action(actionRunner(pushTeam)); + +push + .command("topic") + .alias("topics") + .description("Push messaging topics in the current project.") + .action(actionRunner(pushMessagingTopic)); + +module.exports = { + push +} diff --git a/lib/commands/run.js b/lib/commands/run.js new file mode 100644 index 0000000..5d05e21 --- /dev/null +++ b/lib/commands/run.js @@ -0,0 +1,282 @@ +const Tail = require('tail').Tail; +const EventEmitter = require('node:events'); +const ignore = require("ignore"); +const tar = require("tar"); +const fs = require("fs"); +const ID = require("../id"); +const childProcess = require('child_process'); +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 { usersGet, usersCreateJWT } = require('./users'); +const { projectsCreateJWT } = require('./projects'); +const { questionsRunFunctions } = require("../questions"); +const { actionRunner, success, log, error, commandDescriptions, drawTable } = require("../parser"); +const { systemHasCommand, isPortTaken, getAllFiles } = require('../utils'); +const { openRuntimesVersion, runtimeNames, systemTools, JwtManager, Queue } = require('../emulation/utils'); +const { dockerStop, dockerCleanup, dockerStart, dockerBuild, dockerPull, dockerStopActive } = require('../emulation/docker'); + +const runFunction = async ({ port, functionId, noVariables, noReload, userId } = {}) => { + // Selection + if(!functionId) { + const answers = await inquirer.prompt(questionsRunFunctions[0]); + functionId = answers.function; + } + + const functions = localConfig.getFunctions(); + const func = functions.find((f) => f.$id === functionId); + if (!func) { + throw new Error("Function '" + functionId + "' not found.") + } + + const runtimeName = func.runtime.split("-").slice(0, -1).join("-"); + const tool = systemTools[runtimeName]; + + // Configuration: Port + if(port) { + port = +port; + } + + if(isNaN(port)) { + port = null; + } + + if(port) { + const taken = await isPortTaken(port); + + if(taken) { + error(`Port ${port} is already in use by another process.`); + return; + } + } + + if(!port) { + let portFound = false; + port = 3000; + while(port < 3100) { + const taken = await isPortTaken(port); + if(!taken) { + portFound = true; + break; + } + + port++; + } + + if(!portFound) { + error('Could not find an available port. Please select a port with `appwrite run --port YOUR_PORT` command.'); + return; + } + } + + // Configuration: Engine + if(!systemHasCommand('docker')) { + return error("Docker Engine is required for local development. Please install Docker using: https://docs.docker.com/engine/install/"); + } + + // Settings + const settings = { + runtime: func.runtime, + entrypoint: func.entrypoint, + path: func.path, + commands: func.commands, + }; + + log("Local function configuration:"); + drawTable([settings]); + log('If you wish to change your local settings, update the appwrite.json file and rerun the `appwrite run` command.'); + + await dockerCleanup(); + + process.on('SIGINT', async () => { + log('Cleaning up ...'); + await dockerCleanup(); + success(); + process.exit(); + }); + + const logsPath = path.join(process.cwd(), func.path, '.appwrite/logs.txt'); + const errorsPath = path.join(process.cwd(), func.path, '.appwrite/errors.txt'); + + if(!fs.existsSync(path.dirname(logsPath))) { + fs.mkdirSync(path.dirname(logsPath), { recursive: true }); + } + + if (!fs.existsSync(logsPath)) { + fs.writeFileSync(logsPath, ''); + } + + if (!fs.existsSync(errorsPath)) { + fs.writeFileSync(errorsPath, ''); + } + + const variables = {}; + if(!noVariables) { + if (globalConfig.getEndpoint() === '' || globalConfig.getCookie() === '') { + error("No user is signed in. To sign in, run: appwrite login. Function will run locally, but will not have your function's environment variables set."); + } else { + try { + const { variables: remoteVariables } = await paginate(functionsListVariables, { + functionId: func['$id'], + parseOutput: false + }, 100, 'variables'); + + remoteVariables.forEach((v) => { + variables[v.key] = v.value; + }); + } catch(err) { + log("Could not fetch remote variables: " + err.message); + log("Function will run locally, but will not have your function's environment variables set."); + } + } + } + + variables['APPWRITE_FUNCTION_API_ENDPOINT'] = globalConfig.getFrom('endpoint'); + variables['APPWRITE_FUNCTION_ID'] = func.$id; + variables['APPWRITE_FUNCTION_NAME'] = func.name; + variables['APPWRITE_FUNCTION_DEPLOYMENT'] = ''; // TODO: Implement when relevant + variables['APPWRITE_FUNCTION_PROJECT_ID'] = localConfig.getProject().projectId; + variables['APPWRITE_FUNCTION_RUNTIME_NAME'] = runtimeNames[runtimeName] ?? ''; + variables['APPWRITE_FUNCTION_RUNTIME_VERSION'] = func.runtime; + + await JwtManager.setup(userId); + + const headers = {}; + headers['x-appwrite-key'] = JwtManager.functionJwt ?? ''; + headers['x-appwrite-trigger'] = 'http'; + headers['x-appwrite-event'] = ''; + headers['x-appwrite-user-id'] = userId ?? ''; + headers['x-appwrite-user-jwt'] = JwtManager.userJwt ?? ''; + variables['OPEN_RUNTIMES_HEADERS'] = JSON.stringify(headers); + + await dockerPull(func); + await dockerBuild(func, variables); + await dockerStart(func, variables, port); + + new Tail(logsPath).on("line", function(data) { + console.log(data); + }); + new Tail(errorsPath).on("line", function(data) { + console.log(data); + }); + + if(!noReload) { + chokidar.watch('.', { + cwd: path.join(process.cwd(), func.path), + ignoreInitial: true, + ignored: [ ...(func.ignore ?? []), 'code.tar.gz', '.appwrite', '.appwrite/', '.appwrite/*', '.appwrite/**', '.appwrite/*.*', '.appwrite/**/*.*' ] + }).on('all', async (_event, filePath) => { + Queue.push(filePath); + }); + } + + Queue.events.on('reload', async ({ files }) => { + Queue.lock(); + + log('Live-reloading due to file changes: '); + for(const file of files) { + log(`- ${file}`); + } + + try { + log('Stopping the function ...'); + + await dockerStopActive(); + + const dependencyFile = files.find((filePath) => tool.dependencyFiles.includes(filePath)); + if(tool.isCompiled || dependencyFile) { + log(`Rebuilding the function due to cange in ${dependencyFile} ...`); + await dockerBuild(func, variables); + await dockerStart(func, variables, port); + } else { + log('Hot-swapping function files ...'); + + const functionPath = path.join(process.cwd(), func.path); + const hotSwapPath = path.join(functionPath, '.appwrite/hot-swap'); + const buildPath = path.join(functionPath, '.appwrite/build.tar.gz'); + + // Prepare temp folder + if (!fs.existsSync(hotSwapPath)) { + fs.mkdirSync(hotSwapPath, { recursive: true }); + } else { + fs.rmSync(hotSwapPath, { recursive: true, force: true }); + fs.mkdirSync(hotSwapPath, { recursive: true }); + } + + await tar + .extract({ + gzip: true, + sync: true, + cwd: hotSwapPath, + file: buildPath + }); + + const ignorer = ignore(); + ignorer.add('.appwrite'); + if (func.ignore) { + ignorer.add(func.ignore); + } + + const filesToCopy = getAllFiles(functionPath).map((file) => path.relative(functionPath, file)).filter((file) => !ignorer.ignores(file)); + for(const f of filesToCopy) { + const filePath = path.join(hotSwapPath, f); + if (fs.existsSync(filePath)) { + fs.rmSync(filePath, { force: true }); + } + + const fileDir = path.dirname(filePath); + if (!fs.existsSync(fileDir)) { + fs.mkdirSync(fileDir, { recursive: true }); + } + + const sourcePath = path.join(functionPath, f); + fs.copyFileSync(sourcePath, filePath); + } + + await tar + .create({ + gzip: true, + sync: true, + cwd: hotSwapPath, + file: buildPath + }, ['.']); + + fs.rmSync(hotSwapPath, { recursive: true, force: true }); + + await dockerStart(func, variables, port); + } + } catch(err) { + console.error(err); + } finally { + Queue.unlock(); + } + }); +} + +const run = new Command("run") + .description(commandDescriptions['run']) + .configureHelp({ + helpWidth: process.stdout.columns || 80 + }) + .action(actionRunner(async (_options, command) => { + command.help(); + })); + +run + .command("function") + .alias("functions") + .description("Run functions in the current directory.") + .option(`--functionId `, `Function ID`) + .option(`--port `, `Local port`) + .option(`--userId `, `ID of user to impersonate`) + .option(`--noVariables`, `Prevent pulling variables from function settings`) + .option(`--noReload`, `Prevent live reloading of server when changes are made to function files`) + .action(actionRunner(runFunction)); + +module.exports = { + run +} diff --git a/lib/commands/storage.js b/lib/commands/storage.js index 2358c98..4dca398 100644 --- a/lib/commands/storage.js +++ b/lib/commands/storage.js @@ -4,7 +4,7 @@ const tar = require("tar"); const ignore = require("ignore"); const { promisify } = require('util'); const libClient = require('../client.js'); -const { getAllFiles } = require('../utils.js'); +const { getAllFiles, showConsoleLink } = require('../utils.js'); const { Command } = require('commander'); const { sdkForProject, sdkForConsole } = require('../sdks') const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log } = require('../parser') @@ -43,6 +43,7 @@ const storage = new Command("storage").description(commandDescriptions['storage' * @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 * @property {string} search Search term to filter your list results. Max length: 256 chars. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -50,8 +51,9 @@ const storage = new Command("storage").description(commandDescriptions['storage' /** * @param {StorageListBucketsRequestParams} params */ -const storageListBuckets = async ({ queries, search, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const storageListBuckets = async ({queries,search,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/storage/buckets'; let payload = {}; if (typeof queries !== 'undefined') { @@ -68,11 +70,16 @@ const storageListBuckets = async ({ queries, search, parseOutput = true, sdk = u }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('storage', 'listBuckets'); + } else { + parse(response) + success() + } } - + return response; + } /** @@ -87,6 +94,7 @@ const storageListBuckets = async ({ queries, search, parseOutput = true, sdk = u * @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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -94,8 +102,9 @@ const storageListBuckets = async ({ queries, search, parseOutput = true, sdk = u /** * @param {StorageCreateBucketRequestParams} params */ -const storageCreateBucket = async ({ bucketId, name, permissions, fileSecurity, enabled, maximumFileSize, allowedFileExtensions, compression, encryption, antivirus, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const storageCreateBucket = async ({bucketId,name,permissions,fileSecurity,enabled,maximumFileSize,allowedFileExtensions,compression,encryption,antivirus,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/storage/buckets'; let payload = {}; if (typeof bucketId !== 'undefined') { @@ -141,13 +150,15 @@ const storageCreateBucket = async ({ bucketId, name, permissions, fileSecurity, parse(response) success() } - + return response; + } /** * @typedef {Object} StorageGetBucketRequestParams * @property {string} bucketId Bucket unique ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -155,8 +166,9 @@ const storageCreateBucket = async ({ bucketId, name, permissions, fileSecurity, /** * @param {StorageGetBucketRequestParams} params */ -const storageGetBucket = async ({ bucketId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const storageGetBucket = async ({bucketId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/storage/buckets/{bucketId}'.replace('{bucketId}', bucketId); let payload = {}; @@ -167,11 +179,16 @@ const storageGetBucket = async ({ bucketId, parseOutput = true, sdk = undefined} }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('storage', 'getBucket', bucketId); + } else { + parse(response) + success() + } } - + return response; + } /** @@ -186,6 +203,7 @@ const storageGetBucket = async ({ bucketId, parseOutput = true, sdk = undefined} * @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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -193,8 +211,9 @@ const storageGetBucket = async ({ bucketId, parseOutput = true, sdk = undefined} /** * @param {StorageUpdateBucketRequestParams} params */ -const storageUpdateBucket = async ({ bucketId, name, permissions, fileSecurity, enabled, maximumFileSize, allowedFileExtensions, compression, encryption, antivirus, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const storageUpdateBucket = async ({bucketId,name,permissions,fileSecurity,enabled,maximumFileSize,allowedFileExtensions,compression,encryption,antivirus,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/storage/buckets/{bucketId}'.replace('{bucketId}', bucketId); let payload = {}; if (typeof name !== 'undefined') { @@ -237,13 +256,15 @@ const storageUpdateBucket = async ({ bucketId, name, permissions, fileSecurity, parse(response) success() } - + return response; + } /** * @typedef {Object} StorageDeleteBucketRequestParams * @property {string} bucketId Bucket unique ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -251,8 +272,9 @@ const storageUpdateBucket = async ({ bucketId, name, permissions, fileSecurity, /** * @param {StorageDeleteBucketRequestParams} params */ -const storageDeleteBucket = async ({ bucketId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const storageDeleteBucket = async ({bucketId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/storage/buckets/{bucketId}'.replace('{bucketId}', bucketId); let payload = {}; @@ -266,8 +288,9 @@ const storageDeleteBucket = async ({ bucketId, parseOutput = true, sdk = undefin parse(response) success() } - + return response; + } /** @@ -275,6 +298,7 @@ const storageDeleteBucket = async ({ bucketId, parseOutput = true, sdk = undefin * @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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -282,8 +306,9 @@ const storageDeleteBucket = async ({ bucketId, parseOutput = true, sdk = undefin /** * @param {StorageListFilesRequestParams} params */ -const storageListFiles = async ({ bucketId, queries, search, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const storageListFiles = async ({bucketId,queries,search,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/storage/buckets/{bucketId}/files'.replace('{bucketId}', bucketId); let payload = {}; if (typeof queries !== 'undefined') { @@ -300,19 +325,25 @@ const storageListFiles = async ({ bucketId, queries, search, parseOutput = true, }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('storage', 'listFiles', bucketId); + } else { + parse(response) + success() + } } - + 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/storage#file-input). + * @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 @@ -321,8 +352,9 @@ const storageListFiles = async ({ bucketId, queries, search, parseOutput = true, /** * @param {StorageCreateFileRequestParams} params */ -const storageCreateFile = async ({ bucketId, fileId, file, permissions, parseOutput = true, sdk = undefined, onProgress = () => {}}) => { - let client = !sdk ? await sdkForProject() : sdk; +const storageCreateFile = async ({bucketId,fileId,file,permissions,parseOutput = true, overrideForCli = false, sdk = undefined,onProgress = () => {}}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/storage/buckets/{bucketId}/files'.replace('{bucketId}', bucketId); let payload = {}; if (typeof fileId !== 'undefined') { @@ -342,7 +374,7 @@ const storageCreateFile = async ({ bucketId, fileId, file, permissions, parseOut } const size = file.size; - + const apiHeaders = { 'content-type': 'multipart/form-data', }; @@ -377,7 +409,7 @@ const storageCreateFile = async ({ bucketId, fileId, file, permissions, parseOut } let uploadableChunkTrimmed; - + if(currentPosition + 1 >= client.CHUNK_SIZE) { uploadableChunkTrimmed = uploadableChunk; } else { @@ -430,7 +462,7 @@ const storageCreateFile = async ({ bucketId, fileId, file, permissions, parseOut await uploadChunk(true); } - + if (parseOutput) { parse(response) success() @@ -443,6 +475,7 @@ const storageCreateFile = async ({ bucketId, fileId, file, permissions, parseOut * @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 */ @@ -450,8 +483,9 @@ const storageCreateFile = async ({ bucketId, fileId, file, permissions, parseOut /** * @param {StorageGetFileRequestParams} params */ -const storageGetFile = async ({ bucketId, fileId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const storageGetFile = async ({bucketId,fileId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replace('{bucketId}', bucketId).replace('{fileId}', fileId); let payload = {}; @@ -462,11 +496,16 @@ const storageGetFile = async ({ bucketId, fileId, parseOutput = true, sdk = unde }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('storage', 'getFile', bucketId, fileId); + } else { + parse(response) + success() + } } - + return response; + } /** @@ -475,6 +514,7 @@ const storageGetFile = async ({ bucketId, fileId, parseOutput = true, sdk = unde * @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 */ @@ -482,8 +522,9 @@ const storageGetFile = async ({ bucketId, fileId, parseOutput = true, sdk = unde /** * @param {StorageUpdateFileRequestParams} params */ -const storageUpdateFile = async ({ bucketId, fileId, name, permissions, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const storageUpdateFile = async ({bucketId,fileId,name,permissions,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replace('{bucketId}', bucketId).replace('{fileId}', fileId); let payload = {}; if (typeof name !== 'undefined') { @@ -504,14 +545,16 @@ const storageUpdateFile = async ({ bucketId, fileId, name, permissions, parseOut parse(response) success() } - + 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 */ @@ -519,8 +562,9 @@ const storageUpdateFile = async ({ bucketId, fileId, name, permissions, parseOut /** * @param {StorageDeleteFileRequestParams} params */ -const storageDeleteFile = async ({ bucketId, fileId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const storageDeleteFile = async ({bucketId,fileId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replace('{bucketId}', bucketId).replace('{fileId}', fileId); let payload = {}; @@ -534,14 +578,16 @@ const storageDeleteFile = async ({ bucketId, fileId, parseOutput = true, sdk = u parse(response) success() } - + 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 {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk * @property {string} destination @@ -550,14 +596,17 @@ const storageDeleteFile = async ({ bucketId, fileId, parseOutput = true, sdk = u /** * @param {StorageGetFileDownloadRequestParams} params */ -const storageGetFileDownload = async ({ bucketId, fileId, parseOutput = true, sdk = undefined, destination}) => { - let client = !sdk ? await sdkForProject() : sdk; +const storageGetFileDownload = async ({bucketId,fileId,parseOutput = true, overrideForCli = false, sdk = undefined, destination}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replace('{bucketId}', bucketId).replace('{fileId}', fileId); let payload = {}; - payload['project'] = localConfig.getProject().projectId - payload['key'] = globalConfig.getKey(); - const queryParams = new URLSearchParams(payload); - apiPath = `${globalConfig.getEndpoint()}${apiPath}?${queryParams.toString()}`; + if (!overrideForCli) { + payload['project'] = localConfig.getProject().projectId + payload['key'] = globalConfig.getKey(); + const queryParams = new URLSearchParams(payload); + apiPath = `${globalConfig.getEndpoint()}${apiPath}?${queryParams.toString()}`; + } let response = undefined; @@ -565,14 +614,18 @@ const storageGetFileDownload = async ({ bucketId, fileId, parseOutput = true, sd 'content-type': 'application/json', }, payload, 'arraybuffer'); - fs.writeFileSync(destination, response); + if (overrideForCli) { + response = Buffer.from(response); + } + fs.writeFileSync(destination, response); if (parseOutput) { parse(response) success() } - + return response; + } /** @@ -590,6 +643,7 @@ const storageGetFileDownload = async ({ bucketId, fileId, parseOutput = true, sd * @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 {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk * @property {string} destination @@ -598,8 +652,9 @@ const storageGetFileDownload = async ({ bucketId, fileId, parseOutput = true, sd /** * @param {StorageGetFilePreviewRequestParams} params */ -const storageGetFilePreview = async ({ bucketId, fileId, width, height, gravity, quality, borderWidth, borderColor, borderRadius, opacity, rotation, background, output, parseOutput = true, sdk = undefined, destination}) => { - let client = !sdk ? await sdkForProject() : sdk; +const storageGetFilePreview = async ({bucketId,fileId,width,height,gravity,quality,borderWidth,borderColor,borderRadius,opacity,rotation,background,output,parseOutput = true, overrideForCli = false, sdk = undefined, destination}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replace('{bucketId}', bucketId).replace('{fileId}', fileId); let payload = {}; if (typeof width !== 'undefined') { @@ -635,10 +690,12 @@ const storageGetFilePreview = async ({ bucketId, fileId, width, height, gravity, if (typeof output !== 'undefined') { payload['output'] = output; } - payload['project'] = localConfig.getProject().projectId - payload['key'] = globalConfig.getKey(); - const queryParams = new URLSearchParams(payload); - apiPath = `${globalConfig.getEndpoint()}${apiPath}?${queryParams.toString()}`; + if (!overrideForCli) { + payload['project'] = localConfig.getProject().projectId + payload['key'] = globalConfig.getKey(); + const queryParams = new URLSearchParams(payload); + apiPath = `${globalConfig.getEndpoint()}${apiPath}?${queryParams.toString()}`; + } let response = undefined; @@ -646,20 +703,25 @@ const storageGetFilePreview = async ({ bucketId, fileId, width, height, gravity, 'content-type': 'application/json', }, payload, 'arraybuffer'); - fs.writeFileSync(destination, response); + if (overrideForCli) { + response = Buffer.from(response); + } + fs.writeFileSync(destination, response); if (parseOutput) { parse(response) success() } - + 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 {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk * @property {string} destination @@ -668,14 +730,17 @@ const storageGetFilePreview = async ({ bucketId, fileId, width, height, gravity, /** * @param {StorageGetFileViewRequestParams} params */ -const storageGetFileView = async ({ bucketId, fileId, parseOutput = true, sdk = undefined, destination}) => { - let client = !sdk ? await sdkForProject() : sdk; +const storageGetFileView = async ({bucketId,fileId,parseOutput = true, overrideForCli = false, sdk = undefined, destination}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replace('{bucketId}', bucketId).replace('{fileId}', fileId); let payload = {}; - payload['project'] = localConfig.getProject().projectId - payload['key'] = globalConfig.getKey(); - const queryParams = new URLSearchParams(payload); - apiPath = `${globalConfig.getEndpoint()}${apiPath}?${queryParams.toString()}`; + if (!overrideForCli) { + payload['project'] = localConfig.getProject().projectId + payload['key'] = globalConfig.getKey(); + const queryParams = new URLSearchParams(payload); + apiPath = `${globalConfig.getEndpoint()}${apiPath}?${queryParams.toString()}`; + } let response = undefined; @@ -683,19 +748,24 @@ const storageGetFileView = async ({ bucketId, fileId, parseOutput = true, sdk = 'content-type': 'application/json', }, payload, 'arraybuffer'); - fs.writeFileSync(destination, response); + if (overrideForCli) { + response = Buffer.from(response); + } + fs.writeFileSync(destination, response); if (parseOutput) { parse(response) success() } - + return response; + } /** * @typedef {Object} StorageGetUsageRequestParams * @property {StorageUsageRange} range Date range. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -703,8 +773,9 @@ const storageGetFileView = async ({ bucketId, fileId, parseOutput = true, sdk = /** * @param {StorageGetUsageRequestParams} params */ -const storageGetUsage = async ({ range, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const storageGetUsage = async ({range,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/storage/usage'; let payload = {}; if (typeof range !== 'undefined') { @@ -721,14 +792,16 @@ const storageGetUsage = async ({ range, parseOutput = true, sdk = undefined}) => parse(response) success() } - + return response; + } /** * @typedef {Object} StorageGetBucketUsageRequestParams * @property {string} bucketId Bucket ID. * @property {StorageUsageRange} range Date range. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -736,8 +809,9 @@ const storageGetUsage = async ({ range, parseOutput = true, sdk = undefined}) => /** * @param {StorageGetBucketUsageRequestParams} params */ -const storageGetBucketUsage = async ({ bucketId, range, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const storageGetBucketUsage = async ({bucketId,range,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/storage/{bucketId}/usage'.replace('{bucketId}', bucketId); let payload = {}; if (typeof range !== 'undefined') { @@ -751,11 +825,16 @@ const storageGetBucketUsage = async ({ bucketId, range, parseOutput = true, sdk }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('storage', 'getBucketUsage', bucketId); + } else { + parse(response) + success() + } } - + return response; + } storage @@ -763,6 +842,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`) .option(`--search `, `Search term to filter your list results. Max length: 256 chars.`) + .option(`--console`, `Get the resource console url`) .action(actionRunner(storageListBuckets)) storage @@ -784,6 +864,7 @@ storage .command(`getBucket`) .description(`Get a storage bucket by its unique ID. This endpoint response returns a JSON object with the storage bucket metadata.`) .requiredOption(`--bucketId `, `Bucket unique ID.`) + .option(`--console`, `Get the resource console url`) .action(actionRunner(storageGetBucket)) storage @@ -813,6 +894,7 @@ storage .requiredOption(`--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).`) .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(`--console`, `Get the resource console url`) .action(actionRunner(storageListFiles)) storage @@ -820,7 +902,7 @@ storage .description(`Create a new file. Before using this route, you should create a new bucket resource using either a [server integration](https://appwrite.io/docs/server/storage#storageCreateBucket) API or directly from your Appwrite console. Larger files should be uploaded using multiple requests with the [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) header to send a partial request with a maximum supported chunk of '5MB'. The 'content-range' header values should always be in bytes. When the first request is sent, the server will return the **File** object, and the subsequent part request must include the file's **id** in 'x-appwrite-id' header to allow the server to know that the partial upload is for the existing file and not for a new one. If you're creating a new file using one of the Appwrite SDKs, all the chunking logic will be managed by the SDK internally. `) .requiredOption(`--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).`) .requiredOption(`--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.`) - .requiredOption(`--file `, `Binary file. Appwrite SDKs provide helpers to handle file input. [Learn about file input](https://appwrite.io/docs/storage#file-input).`) + .requiredOption(`--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).`) .option(`--permissions [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).`) .action(actionRunner(storageCreateFile)) @@ -829,6 +911,7 @@ storage .description(`Get a file by its unique ID. This endpoint response returns a JSON object with the file metadata.`) .requiredOption(`--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).`) .requiredOption(`--fileId `, `File ID.`) + .option(`--console`, `Get the resource console url`) .action(actionRunner(storageGetFile)) storage @@ -893,6 +976,7 @@ storage .description(``) .requiredOption(`--bucketId `, `Bucket ID.`) .option(`--range `, `Date range.`) + .option(`--console`, `Get the resource console url`) .action(actionRunner(storageGetBucketUsage)) module.exports = { @@ -912,4 +996,4 @@ module.exports = { storageGetFileView, storageGetUsage, storageGetBucketUsage -}; \ No newline at end of file +}; diff --git a/lib/commands/teams.js b/lib/commands/teams.js index 37261de..39f1848 100644 --- a/lib/commands/teams.js +++ b/lib/commands/teams.js @@ -4,7 +4,7 @@ const tar = require("tar"); const ignore = require("ignore"); const { promisify } = require('util'); const libClient = require('../client.js'); -const { getAllFiles } = require('../utils.js'); +const { getAllFiles, showConsoleLink } = require('../utils.js'); const { Command } = require('commander'); const { sdkForProject, sdkForConsole } = require('../sdks') const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log } = require('../parser') @@ -43,6 +43,7 @@ const teams = new Command("teams").description(commandDescriptions['teams']).con * @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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -50,8 +51,9 @@ const teams = new Command("teams").description(commandDescriptions['teams']).con /** * @param {TeamsListRequestParams} params */ -const teamsList = async ({ queries, search, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const teamsList = async ({queries,search,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/teams'; let payload = {}; if (typeof queries !== 'undefined') { @@ -68,11 +70,16 @@ const teamsList = async ({ queries, search, parseOutput = true, sdk = undefined} }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('teams', 'list'); + } else { + parse(response) + success() + } } - + return response; + } /** @@ -80,6 +87,7 @@ const teamsList = async ({ queries, search, parseOutput = true, sdk = undefined} * @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 */ @@ -87,8 +95,9 @@ const teamsList = async ({ queries, search, parseOutput = true, sdk = undefined} /** * @param {TeamsCreateRequestParams} params */ -const teamsCreate = async ({ teamId, name, roles, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const teamsCreate = async ({teamId,name,roles,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/teams'; let payload = {}; if (typeof teamId !== 'undefined') { @@ -112,13 +121,15 @@ const teamsCreate = async ({ teamId, name, roles, parseOutput = true, sdk = unde parse(response) success() } - + return response; + } /** * @typedef {Object} TeamsGetRequestParams * @property {string} teamId Team ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -126,8 +137,9 @@ const teamsCreate = async ({ teamId, name, roles, parseOutput = true, sdk = unde /** * @param {TeamsGetRequestParams} params */ -const teamsGet = async ({ teamId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const teamsGet = async ({teamId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/teams/{teamId}'.replace('{teamId}', teamId); let payload = {}; @@ -138,17 +150,23 @@ const teamsGet = async ({ teamId, parseOutput = true, sdk = undefined}) => { }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('teams', 'get', teamId); + } else { + parse(response) + success() + } } - + 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 */ @@ -156,8 +174,9 @@ const teamsGet = async ({ teamId, parseOutput = true, sdk = undefined}) => { /** * @param {TeamsUpdateNameRequestParams} params */ -const teamsUpdateName = async ({ teamId, name, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const teamsUpdateName = async ({teamId,name,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/teams/{teamId}'.replace('{teamId}', teamId); let payload = {}; if (typeof name !== 'undefined') { @@ -174,13 +193,15 @@ const teamsUpdateName = async ({ teamId, name, parseOutput = true, sdk = undefin parse(response) success() } - + return response; + } /** * @typedef {Object} TeamsDeleteRequestParams * @property {string} teamId Team ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -188,8 +209,9 @@ const teamsUpdateName = async ({ teamId, name, parseOutput = true, sdk = undefin /** * @param {TeamsDeleteRequestParams} params */ -const teamsDelete = async ({ teamId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const teamsDelete = async ({teamId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/teams/{teamId}'.replace('{teamId}', teamId); let payload = {}; @@ -203,14 +225,16 @@ const teamsDelete = async ({ teamId, parseOutput = true, sdk = undefined}) => { parse(response) success() } - + 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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -218,8 +242,9 @@ const teamsDelete = async ({ teamId, parseOutput = true, sdk = undefined}) => { /** * @param {TeamsListLogsRequestParams} params */ -const teamsListLogs = async ({ teamId, queries, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const teamsListLogs = async ({teamId,queries,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/teams/{teamId}/logs'.replace('{teamId}', teamId); let payload = {}; if (typeof queries !== 'undefined') { @@ -236,8 +261,9 @@ const teamsListLogs = async ({ teamId, queries, parseOutput = true, sdk = undefi parse(response) success() } - + return response; + } /** @@ -245,6 +271,7 @@ const teamsListLogs = async ({ teamId, queries, parseOutput = true, sdk = undefi * @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 * @property {string} search Search term to filter your list results. Max length: 256 chars. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -252,8 +279,9 @@ const teamsListLogs = async ({ teamId, queries, parseOutput = true, sdk = undefi /** * @param {TeamsListMembershipsRequestParams} params */ -const teamsListMemberships = async ({ teamId, queries, search, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const teamsListMemberships = async ({teamId,queries,search,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/teams/{teamId}/memberships'.replace('{teamId}', teamId); let payload = {}; if (typeof queries !== 'undefined') { @@ -273,8 +301,9 @@ const teamsListMemberships = async ({ teamId, queries, search, parseOutput = tru parse(response) success() } - + return response; + } /** @@ -284,8 +313,9 @@ const teamsListMemberships = async ({ teamId, queries, search, parseOutput = tru * @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. 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} 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 */ @@ -293,8 +323,9 @@ const teamsListMemberships = async ({ teamId, queries, search, parseOutput = tru /** * @param {TeamsCreateMembershipRequestParams} params */ -const teamsCreateMembership = async ({ teamId, roles, email, userId, phone, url, name, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const teamsCreateMembership = async ({teamId,roles,email,userId,phone,url,name,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/teams/{teamId}/memberships'.replace('{teamId}', teamId); let payload = {}; if (typeof email !== 'undefined') { @@ -327,14 +358,16 @@ const teamsCreateMembership = async ({ teamId, roles, email, userId, phone, url, parse(response) success() } - + 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 */ @@ -342,8 +375,9 @@ const teamsCreateMembership = async ({ teamId, roles, email, userId, phone, url, /** * @param {TeamsGetMembershipRequestParams} params */ -const teamsGetMembership = async ({ teamId, membershipId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const teamsGetMembership = async ({teamId,membershipId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/teams/{teamId}/memberships/{membershipId}'.replace('{teamId}', teamId).replace('{membershipId}', membershipId); let payload = {}; @@ -357,8 +391,9 @@ const teamsGetMembership = async ({ teamId, membershipId, parseOutput = true, sd parse(response) success() } - + return response; + } /** @@ -366,6 +401,7 @@ const teamsGetMembership = async ({ teamId, membershipId, parseOutput = true, sd * @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 */ @@ -373,8 +409,9 @@ const teamsGetMembership = async ({ teamId, membershipId, parseOutput = true, sd /** * @param {TeamsUpdateMembershipRequestParams} params */ -const teamsUpdateMembership = async ({ teamId, membershipId, roles, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const teamsUpdateMembership = async ({teamId,membershipId,roles,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/teams/{teamId}/memberships/{membershipId}'.replace('{teamId}', teamId).replace('{membershipId}', membershipId); let payload = {}; roles = roles === true ? [] : roles; @@ -392,14 +429,16 @@ const teamsUpdateMembership = async ({ teamId, membershipId, roles, parseOutput parse(response) success() } - + 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 */ @@ -407,8 +446,9 @@ const teamsUpdateMembership = async ({ teamId, membershipId, roles, parseOutput /** * @param {TeamsDeleteMembershipRequestParams} params */ -const teamsDeleteMembership = async ({ teamId, membershipId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const teamsDeleteMembership = async ({teamId,membershipId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/teams/{teamId}/memberships/{membershipId}'.replace('{teamId}', teamId).replace('{membershipId}', membershipId); let payload = {}; @@ -422,8 +462,9 @@ const teamsDeleteMembership = async ({ teamId, membershipId, parseOutput = true, parse(response) success() } - + return response; + } /** @@ -432,6 +473,7 @@ const teamsDeleteMembership = async ({ teamId, membershipId, parseOutput = true, * @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 */ @@ -439,8 +481,9 @@ const teamsDeleteMembership = async ({ teamId, membershipId, parseOutput = true, /** * @param {TeamsUpdateMembershipStatusRequestParams} params */ -const teamsUpdateMembershipStatus = async ({ teamId, membershipId, userId, secret, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const teamsUpdateMembershipStatus = async ({teamId,membershipId,userId,secret,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/teams/{teamId}/memberships/{membershipId}/status'.replace('{teamId}', teamId).replace('{membershipId}', membershipId); let payload = {}; if (typeof userId !== 'undefined') { @@ -460,13 +503,15 @@ const teamsUpdateMembershipStatus = async ({ teamId, membershipId, userId, secre parse(response) success() } - + return response; + } /** * @typedef {Object} TeamsGetPrefsRequestParams * @property {string} teamId Team ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -474,8 +519,9 @@ const teamsUpdateMembershipStatus = async ({ teamId, membershipId, userId, secre /** * @param {TeamsGetPrefsRequestParams} params */ -const teamsGetPrefs = async ({ teamId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const teamsGetPrefs = async ({teamId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/teams/{teamId}/prefs'.replace('{teamId}', teamId); let payload = {}; @@ -489,14 +535,16 @@ const teamsGetPrefs = async ({ teamId, parseOutput = true, sdk = undefined}) => parse(response) success() } - + 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 */ @@ -504,8 +552,9 @@ const teamsGetPrefs = async ({ teamId, parseOutput = true, sdk = undefined}) => /** * @param {TeamsUpdatePrefsRequestParams} params */ -const teamsUpdatePrefs = async ({ teamId, prefs, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const teamsUpdatePrefs = async ({teamId,prefs,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/teams/{teamId}/prefs'.replace('{teamId}', teamId); let payload = {}; if (typeof prefs !== 'undefined') { @@ -522,8 +571,9 @@ const teamsUpdatePrefs = async ({ teamId, prefs, parseOutput = true, sdk = undef parse(response) success() } - + return response; + } teams @@ -531,6 +581,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(`--console`, `Get the resource console url`) .action(actionRunner(teamsList)) teams @@ -545,6 +596,7 @@ teams .command(`get`) .description(`Get a team by its ID. All team members have read access for this resource.`) .requiredOption(`--teamId `, `Team ID.`) + .option(`--console`, `Get the resource console url`) .action(actionRunner(teamsGet)) teams @@ -583,7 +635,7 @@ teams .option(`--email `, `Email of the new team member.`) .option(`--userId `, `ID of the user to be added to a team.`) .option(`--phone `, `Phone number. Format this number with a leading '+' and a country code, e.g., +16175551212.`) - .option(`--url `, `URL to redirect the user back to your app from the invitation 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.`) + .option(`--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.`) .option(`--name `, `Name of the new team member. Max length: 128 chars.`) .action(actionRunner(teamsCreateMembership)) @@ -647,4 +699,4 @@ module.exports = { teamsUpdateMembershipStatus, teamsGetPrefs, teamsUpdatePrefs -}; \ No newline at end of file +}; diff --git a/lib/commands/users.js b/lib/commands/users.js index d412d27..42f4ea3 100644 --- a/lib/commands/users.js +++ b/lib/commands/users.js @@ -4,7 +4,7 @@ const tar = require("tar"); const ignore = require("ignore"); const { promisify } = require('util'); const libClient = require('../client.js'); -const { getAllFiles } = require('../utils.js'); +const { getAllFiles, showConsoleLink } = require('../utils.js'); const { Command } = require('commander'); const { sdkForProject, sdkForConsole } = require('../sdks') const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log } = require('../parser') @@ -43,6 +43,7 @@ const users = new Command("users").description(commandDescriptions['users']).con * @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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -50,8 +51,9 @@ const users = new Command("users").description(commandDescriptions['users']).con /** * @param {UsersListRequestParams} params */ -const usersList = async ({ queries, search, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersList = async ({queries,search,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users'; let payload = {}; if (typeof queries !== 'undefined') { @@ -68,11 +70,16 @@ const usersList = async ({ queries, search, parseOutput = true, sdk = undefined} }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('users', 'list'); + } else { + parse(response) + success() + } } - + return response; + } /** @@ -82,6 +89,7 @@ const usersList = async ({ queries, search, parseOutput = true, sdk = undefined} * @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 */ @@ -89,8 +97,9 @@ const usersList = async ({ queries, search, parseOutput = true, sdk = undefined} /** * @param {UsersCreateRequestParams} params */ -const usersCreate = async ({ userId, email, phone, password, name, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersCreate = async ({userId,email,phone,password,name,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users'; let payload = {}; if (typeof userId !== 'undefined') { @@ -119,8 +128,9 @@ const usersCreate = async ({ userId, email, phone, password, name, parseOutput = parse(response) success() } - + return response; + } /** @@ -129,6 +139,7 @@ const usersCreate = async ({ userId, email, phone, password, name, parseOutput = * @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 */ @@ -136,8 +147,9 @@ const usersCreate = async ({ userId, email, phone, password, name, parseOutput = /** * @param {UsersCreateArgon2UserRequestParams} params */ -const usersCreateArgon2User = async ({ userId, email, password, name, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersCreateArgon2User = async ({userId,email,password,name,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/argon2'; let payload = {}; if (typeof userId !== 'undefined') { @@ -163,8 +175,9 @@ const usersCreateArgon2User = async ({ userId, email, password, name, parseOutpu parse(response) success() } - + return response; + } /** @@ -173,6 +186,7 @@ const usersCreateArgon2User = async ({ userId, email, password, name, parseOutpu * @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 */ @@ -180,8 +194,9 @@ const usersCreateArgon2User = async ({ userId, email, password, name, parseOutpu /** * @param {UsersCreateBcryptUserRequestParams} params */ -const usersCreateBcryptUser = async ({ userId, email, password, name, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersCreateBcryptUser = async ({userId,email,password,name,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/bcrypt'; let payload = {}; if (typeof userId !== 'undefined') { @@ -207,14 +222,16 @@ const usersCreateBcryptUser = async ({ userId, email, password, name, parseOutpu parse(response) success() } - + 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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -222,8 +239,9 @@ const usersCreateBcryptUser = async ({ userId, email, password, name, parseOutpu /** * @param {UsersListIdentitiesRequestParams} params */ -const usersListIdentities = async ({ queries, search, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersListIdentities = async ({queries,search,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/identities'; let payload = {}; if (typeof queries !== 'undefined') { @@ -243,13 +261,15 @@ const usersListIdentities = async ({ queries, search, parseOutput = true, sdk = parse(response) success() } - + return response; + } /** * @typedef {Object} UsersDeleteIdentityRequestParams * @property {string} identityId Identity ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -257,8 +277,9 @@ const usersListIdentities = async ({ queries, search, parseOutput = true, sdk = /** * @param {UsersDeleteIdentityRequestParams} params */ -const usersDeleteIdentity = async ({ identityId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersDeleteIdentity = async ({identityId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/identities/{identityId}'.replace('{identityId}', identityId); let payload = {}; @@ -272,8 +293,9 @@ const usersDeleteIdentity = async ({ identityId, parseOutput = true, sdk = undef parse(response) success() } - + return response; + } /** @@ -282,6 +304,7 @@ const usersDeleteIdentity = async ({ identityId, parseOutput = true, sdk = undef * @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 */ @@ -289,8 +312,9 @@ const usersDeleteIdentity = async ({ identityId, parseOutput = true, sdk = undef /** * @param {UsersCreateMD5UserRequestParams} params */ -const usersCreateMD5User = async ({ userId, email, password, name, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersCreateMD5User = async ({userId,email,password,name,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/md5'; let payload = {}; if (typeof userId !== 'undefined') { @@ -316,8 +340,9 @@ const usersCreateMD5User = async ({ userId, email, password, name, parseOutput = parse(response) success() } - + return response; + } /** @@ -326,6 +351,7 @@ const usersCreateMD5User = async ({ userId, email, password, name, parseOutput = * @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 */ @@ -333,8 +359,9 @@ const usersCreateMD5User = async ({ userId, email, password, name, parseOutput = /** * @param {UsersCreatePHPassUserRequestParams} params */ -const usersCreatePHPassUser = async ({ userId, email, password, name, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersCreatePHPassUser = async ({userId,email,password,name,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/phpass'; let payload = {}; if (typeof userId !== 'undefined') { @@ -360,8 +387,9 @@ const usersCreatePHPassUser = async ({ userId, email, password, name, parseOutpu parse(response) success() } - + return response; + } /** @@ -375,6 +403,7 @@ const usersCreatePHPassUser = async ({ userId, email, password, name, parseOutpu * @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 */ @@ -382,8 +411,9 @@ const usersCreatePHPassUser = async ({ userId, email, password, name, parseOutpu /** * @param {UsersCreateScryptUserRequestParams} params */ -const usersCreateScryptUser = async ({ userId, email, password, passwordSalt, passwordCpu, passwordMemory, passwordParallel, passwordLength, name, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersCreateScryptUser = async ({userId,email,password,passwordSalt,passwordCpu,passwordMemory,passwordParallel,passwordLength,name,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/scrypt'; let payload = {}; if (typeof userId !== 'undefined') { @@ -424,8 +454,9 @@ const usersCreateScryptUser = async ({ userId, email, password, passwordSalt, pa parse(response) success() } - + return response; + } /** @@ -437,6 +468,7 @@ const usersCreateScryptUser = async ({ userId, email, password, passwordSalt, pa * @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 */ @@ -444,8 +476,9 @@ const usersCreateScryptUser = async ({ userId, email, password, passwordSalt, pa /** * @param {UsersCreateScryptModifiedUserRequestParams} params */ -const usersCreateScryptModifiedUser = async ({ userId, email, password, passwordSalt, passwordSaltSeparator, passwordSignerKey, name, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersCreateScryptModifiedUser = async ({userId,email,password,passwordSalt,passwordSaltSeparator,passwordSignerKey,name,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/scrypt-modified'; let payload = {}; if (typeof userId !== 'undefined') { @@ -480,8 +513,9 @@ const usersCreateScryptModifiedUser = async ({ userId, email, password, password parse(response) success() } - + return response; + } /** @@ -491,6 +525,7 @@ const usersCreateScryptModifiedUser = async ({ userId, email, password, password * @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 */ @@ -498,8 +533,9 @@ const usersCreateScryptModifiedUser = async ({ userId, email, password, password /** * @param {UsersCreateSHAUserRequestParams} params */ -const usersCreateSHAUser = async ({ userId, email, password, passwordVersion, name, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersCreateSHAUser = async ({userId,email,password,passwordVersion,name,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/sha'; let payload = {}; if (typeof userId !== 'undefined') { @@ -528,13 +564,15 @@ const usersCreateSHAUser = async ({ userId, email, password, passwordVersion, na parse(response) success() } - + return response; + } /** * @typedef {Object} UsersGetUsageRequestParams * @property {UserUsageRange} range Date range. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -542,8 +580,9 @@ const usersCreateSHAUser = async ({ userId, email, password, passwordVersion, na /** * @param {UsersGetUsageRequestParams} params */ -const usersGetUsage = async ({ range, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersGetUsage = async ({range,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/usage'; let payload = {}; if (typeof range !== 'undefined') { @@ -560,13 +599,15 @@ const usersGetUsage = async ({ range, parseOutput = true, sdk = undefined}) => { parse(response) success() } - + return response; + } /** * @typedef {Object} UsersGetRequestParams * @property {string} userId User ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -574,8 +615,9 @@ const usersGetUsage = async ({ range, parseOutput = true, sdk = undefined}) => { /** * @param {UsersGetRequestParams} params */ -const usersGet = async ({ userId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersGet = async ({userId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/{userId}'.replace('{userId}', userId); let payload = {}; @@ -586,16 +628,22 @@ const usersGet = async ({ userId, parseOutput = true, sdk = undefined}) => { }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('users', 'get', userId); + } else { + parse(response) + success() + } } - + return response; + } /** * @typedef {Object} UsersDeleteRequestParams * @property {string} userId User ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -603,8 +651,9 @@ const usersGet = async ({ userId, parseOutput = true, sdk = undefined}) => { /** * @param {UsersDeleteRequestParams} params */ -const usersDelete = async ({ userId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersDelete = async ({userId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/{userId}'.replace('{userId}', userId); let payload = {}; @@ -618,14 +667,16 @@ const usersDelete = async ({ userId, parseOutput = true, sdk = undefined}) => { parse(response) success() } - + 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 */ @@ -633,8 +684,9 @@ const usersDelete = async ({ userId, parseOutput = true, sdk = undefined}) => { /** * @param {UsersUpdateEmailRequestParams} params */ -const usersUpdateEmail = async ({ userId, email, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersUpdateEmail = async ({userId,email,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/{userId}/email'.replace('{userId}', userId); let payload = {}; if (typeof email !== 'undefined') { @@ -651,14 +703,56 @@ const usersUpdateEmail = async ({ userId, email, parseOutput = true, sdk = undef parse(response) success() } - + + 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}) => { + let client = !sdk ? await sdkForProject() : + sdk; + let apiPath = '/users/{userId}/jwts'.replace('{userId}', userId); + let payload = {}; + if (typeof sessionId !== 'undefined') { + payload['sessionId'] = sessionId; + } + if (typeof duration !== 'undefined') { + payload['duration'] = duration; + } + + let response = undefined; + + response = await client.call('post', apiPath, { + 'content-type': 'application/json', + }, payload); + + if (parseOutput) { + parse(response) + success() + } + 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 */ @@ -666,8 +760,9 @@ const usersUpdateEmail = async ({ userId, email, parseOutput = true, sdk = undef /** * @param {UsersUpdateLabelsRequestParams} params */ -const usersUpdateLabels = async ({ userId, labels, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersUpdateLabels = async ({userId,labels,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/{userId}/labels'.replace('{userId}', userId); let payload = {}; labels = labels === true ? [] : labels; @@ -685,14 +780,16 @@ const usersUpdateLabels = async ({ userId, labels, parseOutput = true, sdk = und parse(response) success() } - + 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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -700,8 +797,9 @@ const usersUpdateLabels = async ({ userId, labels, parseOutput = true, sdk = und /** * @param {UsersListLogsRequestParams} params */ -const usersListLogs = async ({ userId, queries, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersListLogs = async ({userId,queries,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/{userId}/logs'.replace('{userId}', userId); let payload = {}; if (typeof queries !== 'undefined') { @@ -718,13 +816,15 @@ const usersListLogs = async ({ userId, queries, parseOutput = true, sdk = undefi parse(response) success() } - + return response; + } /** * @typedef {Object} UsersListMembershipsRequestParams * @property {string} userId User ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -732,8 +832,9 @@ const usersListLogs = async ({ userId, queries, parseOutput = true, sdk = undefi /** * @param {UsersListMembershipsRequestParams} params */ -const usersListMemberships = async ({ userId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersListMemberships = async ({userId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/{userId}/memberships'.replace('{userId}', userId); let payload = {}; @@ -747,14 +848,16 @@ const usersListMemberships = async ({ userId, parseOutput = true, sdk = undefine parse(response) success() } - + 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 */ @@ -762,8 +865,9 @@ const usersListMemberships = async ({ userId, parseOutput = true, sdk = undefine /** * @param {UsersUpdateMfaRequestParams} params */ -const usersUpdateMfa = async ({ userId, mfa, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersUpdateMfa = async ({userId,mfa,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/{userId}/mfa'.replace('{userId}', userId); let payload = {}; if (typeof mfa !== 'undefined') { @@ -780,14 +884,16 @@ const usersUpdateMfa = async ({ userId, mfa, parseOutput = true, sdk = undefined parse(response) success() } - + 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 */ @@ -795,8 +901,9 @@ const usersUpdateMfa = async ({ userId, mfa, parseOutput = true, sdk = undefined /** * @param {UsersDeleteMfaAuthenticatorRequestParams} params */ -const usersDeleteMfaAuthenticator = async ({ userId, type, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersDeleteMfaAuthenticator = async ({userId,type,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/{userId}/mfa/authenticators/{type}'.replace('{userId}', userId).replace('{type}', type); let payload = {}; @@ -810,13 +917,15 @@ const usersDeleteMfaAuthenticator = async ({ userId, type, parseOutput = true, s parse(response) success() } - + return response; + } /** * @typedef {Object} UsersListMfaFactorsRequestParams * @property {string} userId User ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -824,8 +933,9 @@ const usersDeleteMfaAuthenticator = async ({ userId, type, parseOutput = true, s /** * @param {UsersListMfaFactorsRequestParams} params */ -const usersListMfaFactors = async ({ userId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersListMfaFactors = async ({userId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/{userId}/mfa/factors'.replace('{userId}', userId); let payload = {}; @@ -839,13 +949,15 @@ const usersListMfaFactors = async ({ userId, parseOutput = true, sdk = undefined parse(response) success() } - + return response; + } /** * @typedef {Object} UsersGetMfaRecoveryCodesRequestParams * @property {string} userId User ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -853,8 +965,9 @@ const usersListMfaFactors = async ({ userId, parseOutput = true, sdk = undefined /** * @param {UsersGetMfaRecoveryCodesRequestParams} params */ -const usersGetMfaRecoveryCodes = async ({ userId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersGetMfaRecoveryCodes = async ({userId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/{userId}/mfa/recovery-codes'.replace('{userId}', userId); let payload = {}; @@ -868,13 +981,15 @@ const usersGetMfaRecoveryCodes = async ({ userId, parseOutput = true, sdk = unde parse(response) success() } - + return response; + } /** * @typedef {Object} UsersUpdateMfaRecoveryCodesRequestParams * @property {string} userId User ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -882,8 +997,9 @@ const usersGetMfaRecoveryCodes = async ({ userId, parseOutput = true, sdk = unde /** * @param {UsersUpdateMfaRecoveryCodesRequestParams} params */ -const usersUpdateMfaRecoveryCodes = async ({ userId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersUpdateMfaRecoveryCodes = async ({userId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/{userId}/mfa/recovery-codes'.replace('{userId}', userId); let payload = {}; @@ -897,13 +1013,15 @@ const usersUpdateMfaRecoveryCodes = async ({ userId, parseOutput = true, sdk = u parse(response) success() } - + return response; + } /** * @typedef {Object} UsersCreateMfaRecoveryCodesRequestParams * @property {string} userId User ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -911,8 +1029,9 @@ const usersUpdateMfaRecoveryCodes = async ({ userId, parseOutput = true, sdk = u /** * @param {UsersCreateMfaRecoveryCodesRequestParams} params */ -const usersCreateMfaRecoveryCodes = async ({ userId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersCreateMfaRecoveryCodes = async ({userId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/{userId}/mfa/recovery-codes'.replace('{userId}', userId); let payload = {}; @@ -926,14 +1045,16 @@ const usersCreateMfaRecoveryCodes = async ({ userId, parseOutput = true, sdk = u parse(response) success() } - + 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 */ @@ -941,8 +1062,9 @@ const usersCreateMfaRecoveryCodes = async ({ userId, parseOutput = true, sdk = u /** * @param {UsersUpdateNameRequestParams} params */ -const usersUpdateName = async ({ userId, name, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersUpdateName = async ({userId,name,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/{userId}/name'.replace('{userId}', userId); let payload = {}; if (typeof name !== 'undefined') { @@ -959,14 +1081,16 @@ const usersUpdateName = async ({ userId, name, parseOutput = true, sdk = undefin parse(response) success() } - + 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 */ @@ -974,8 +1098,9 @@ const usersUpdateName = async ({ userId, name, parseOutput = true, sdk = undefin /** * @param {UsersUpdatePasswordRequestParams} params */ -const usersUpdatePassword = async ({ userId, password, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersUpdatePassword = async ({userId,password,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/{userId}/password'.replace('{userId}', userId); let payload = {}; if (typeof password !== 'undefined') { @@ -992,14 +1117,16 @@ const usersUpdatePassword = async ({ userId, password, parseOutput = true, sdk = parse(response) success() } - + 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 */ @@ -1007,8 +1134,9 @@ const usersUpdatePassword = async ({ userId, password, parseOutput = true, sdk = /** * @param {UsersUpdatePhoneRequestParams} params */ -const usersUpdatePhone = async ({ userId, number, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersUpdatePhone = async ({userId,number,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/{userId}/phone'.replace('{userId}', userId); let payload = {}; if (typeof number !== 'undefined') { @@ -1025,13 +1153,15 @@ const usersUpdatePhone = async ({ userId, number, parseOutput = true, sdk = unde parse(response) success() } - + return response; + } /** * @typedef {Object} UsersGetPrefsRequestParams * @property {string} userId User ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -1039,8 +1169,9 @@ const usersUpdatePhone = async ({ userId, number, parseOutput = true, sdk = unde /** * @param {UsersGetPrefsRequestParams} params */ -const usersGetPrefs = async ({ userId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersGetPrefs = async ({userId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/{userId}/prefs'.replace('{userId}', userId); let payload = {}; @@ -1054,14 +1185,16 @@ const usersGetPrefs = async ({ userId, parseOutput = true, sdk = undefined}) => parse(response) success() } - + 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 */ @@ -1069,8 +1202,9 @@ const usersGetPrefs = async ({ userId, parseOutput = true, sdk = undefined}) => /** * @param {UsersUpdatePrefsRequestParams} params */ -const usersUpdatePrefs = async ({ userId, prefs, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersUpdatePrefs = async ({userId,prefs,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/{userId}/prefs'.replace('{userId}', userId); let payload = {}; if (typeof prefs !== 'undefined') { @@ -1087,13 +1221,15 @@ const usersUpdatePrefs = async ({ userId, prefs, parseOutput = true, sdk = undef parse(response) success() } - + return response; + } /** * @typedef {Object} UsersListSessionsRequestParams * @property {string} userId User ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -1101,8 +1237,9 @@ const usersUpdatePrefs = async ({ userId, prefs, parseOutput = true, sdk = undef /** * @param {UsersListSessionsRequestParams} params */ -const usersListSessions = async ({ userId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersListSessions = async ({userId,parseOutput = true, overrideForCli = false, sdk = undefined, console}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/{userId}/sessions'.replace('{userId}', userId); let payload = {}; @@ -1113,16 +1250,22 @@ const usersListSessions = async ({ userId, parseOutput = true, sdk = undefined}) }, payload); if (parseOutput) { - parse(response) - success() + if(console) { + showConsoleLink('users', 'listSessions', userId); + } else { + parse(response) + success() + } } - + 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 */ @@ -1130,8 +1273,9 @@ const usersListSessions = async ({ userId, parseOutput = true, sdk = undefined}) /** * @param {UsersCreateSessionRequestParams} params */ -const usersCreateSession = async ({ userId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersCreateSession = async ({userId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/{userId}/sessions'.replace('{userId}', userId); let payload = {}; @@ -1145,13 +1289,15 @@ const usersCreateSession = async ({ userId, parseOutput = true, sdk = undefined} parse(response) success() } - + return response; + } /** * @typedef {Object} UsersDeleteSessionsRequestParams * @property {string} userId User ID. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -1159,8 +1305,9 @@ const usersCreateSession = async ({ userId, parseOutput = true, sdk = undefined} /** * @param {UsersDeleteSessionsRequestParams} params */ -const usersDeleteSessions = async ({ userId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersDeleteSessions = async ({userId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/{userId}/sessions'.replace('{userId}', userId); let payload = {}; @@ -1174,14 +1321,16 @@ const usersDeleteSessions = async ({ userId, parseOutput = true, sdk = undefined parse(response) success() } - + 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 */ @@ -1189,8 +1338,9 @@ const usersDeleteSessions = async ({ userId, parseOutput = true, sdk = undefined /** * @param {UsersDeleteSessionRequestParams} params */ -const usersDeleteSession = async ({ userId, sessionId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersDeleteSession = async ({userId,sessionId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/{userId}/sessions/{sessionId}'.replace('{userId}', userId).replace('{sessionId}', sessionId); let payload = {}; @@ -1204,14 +1354,16 @@ const usersDeleteSession = async ({ userId, sessionId, parseOutput = true, sdk = parse(response) success() } - + 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 */ @@ -1219,8 +1371,9 @@ const usersDeleteSession = async ({ userId, sessionId, parseOutput = true, sdk = /** * @param {UsersUpdateStatusRequestParams} params */ -const usersUpdateStatus = async ({ userId, status, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersUpdateStatus = async ({userId,status,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/{userId}/status'.replace('{userId}', userId); let payload = {}; if (typeof status !== 'undefined') { @@ -1237,14 +1390,16 @@ const usersUpdateStatus = async ({ userId, status, parseOutput = true, sdk = und parse(response) success() } - + 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: name, email, phone, status, passwordUpdate, registration, emailVerification, phoneVerification, labels + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -1252,8 +1407,9 @@ const usersUpdateStatus = async ({ userId, status, parseOutput = true, sdk = und /** * @param {UsersListTargetsRequestParams} params */ -const usersListTargets = async ({ userId, queries, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersListTargets = async ({userId,queries,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/{userId}/targets'.replace('{userId}', userId); let payload = {}; if (typeof queries !== 'undefined') { @@ -1270,8 +1426,9 @@ const usersListTargets = async ({ userId, queries, parseOutput = true, sdk = und parse(response) success() } - + return response; + } /** @@ -1282,6 +1439,7 @@ const usersListTargets = async ({ userId, queries, parseOutput = true, sdk = und * @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 */ @@ -1289,8 +1447,9 @@ const usersListTargets = async ({ userId, queries, parseOutput = true, sdk = und /** * @param {UsersCreateTargetRequestParams} params */ -const usersCreateTarget = async ({ userId, targetId, providerType, identifier, providerId, name, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersCreateTarget = async ({userId,targetId,providerType,identifier,providerId,name,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/{userId}/targets'.replace('{userId}', userId); let payload = {}; if (typeof targetId !== 'undefined') { @@ -1319,14 +1478,16 @@ const usersCreateTarget = async ({ userId, targetId, providerType, identifier, p parse(response) success() } - + 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 */ @@ -1334,8 +1495,9 @@ const usersCreateTarget = async ({ userId, targetId, providerType, identifier, p /** * @param {UsersGetTargetRequestParams} params */ -const usersGetTarget = async ({ userId, targetId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersGetTarget = async ({userId,targetId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/{userId}/targets/{targetId}'.replace('{userId}', userId).replace('{targetId}', targetId); let payload = {}; @@ -1349,8 +1511,9 @@ const usersGetTarget = async ({ userId, targetId, parseOutput = true, sdk = unde parse(response) success() } - + return response; + } /** @@ -1360,6 +1523,7 @@ const usersGetTarget = async ({ userId, targetId, parseOutput = true, sdk = unde * @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 */ @@ -1367,8 +1531,9 @@ const usersGetTarget = async ({ userId, targetId, parseOutput = true, sdk = unde /** * @param {UsersUpdateTargetRequestParams} params */ -const usersUpdateTarget = async ({ userId, targetId, identifier, providerId, name, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersUpdateTarget = async ({userId,targetId,identifier,providerId,name,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/{userId}/targets/{targetId}'.replace('{userId}', userId).replace('{targetId}', targetId); let payload = {}; if (typeof identifier !== 'undefined') { @@ -1391,14 +1556,16 @@ const usersUpdateTarget = async ({ userId, targetId, identifier, providerId, nam parse(response) success() } - + 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 */ @@ -1406,8 +1573,9 @@ const usersUpdateTarget = async ({ userId, targetId, identifier, providerId, nam /** * @param {UsersDeleteTargetRequestParams} params */ -const usersDeleteTarget = async ({ userId, targetId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersDeleteTarget = async ({userId,targetId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/{userId}/targets/{targetId}'.replace('{userId}', userId).replace('{targetId}', targetId); let payload = {}; @@ -1421,8 +1589,9 @@ const usersDeleteTarget = async ({ userId, targetId, parseOutput = true, sdk = u parse(response) success() } - + return response; + } /** @@ -1430,6 +1599,7 @@ const usersDeleteTarget = async ({ userId, targetId, parseOutput = true, sdk = u * @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 */ @@ -1437,8 +1607,9 @@ const usersDeleteTarget = async ({ userId, targetId, parseOutput = true, sdk = u /** * @param {UsersCreateTokenRequestParams} params */ -const usersCreateToken = async ({ userId, length, expire, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersCreateToken = async ({userId,length,expire,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/{userId}/tokens'.replace('{userId}', userId); let payload = {}; if (typeof length !== 'undefined') { @@ -1458,14 +1629,16 @@ const usersCreateToken = async ({ userId, length, expire, parseOutput = true, sd parse(response) success() } - + 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 */ @@ -1473,8 +1646,9 @@ const usersCreateToken = async ({ userId, length, expire, parseOutput = true, sd /** * @param {UsersUpdateEmailVerificationRequestParams} params */ -const usersUpdateEmailVerification = async ({ userId, emailVerification, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersUpdateEmailVerification = async ({userId,emailVerification,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/{userId}/verification'.replace('{userId}', userId); let payload = {}; if (typeof emailVerification !== 'undefined') { @@ -1491,14 +1665,16 @@ const usersUpdateEmailVerification = async ({ userId, emailVerification, parseOu parse(response) success() } - + 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 */ @@ -1506,8 +1682,9 @@ const usersUpdateEmailVerification = async ({ userId, emailVerification, parseOu /** * @param {UsersUpdatePhoneVerificationRequestParams} params */ -const usersUpdatePhoneVerification = async ({ userId, phoneVerification, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const usersUpdatePhoneVerification = async ({userId,phoneVerification,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/users/{userId}/verification/phone'.replace('{userId}', userId); let payload = {}; if (typeof phoneVerification !== 'undefined') { @@ -1524,8 +1701,9 @@ const usersUpdatePhoneVerification = async ({ userId, phoneVerification, parseOu parse(response) success() } - + return response; + } users @@ -1533,6 +1711,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(`--console`, `Get the resource console url`) .action(actionRunner(usersList)) users @@ -1640,6 +1819,7 @@ users .command(`get`) .description(`Get a user by its unique ID.`) .requiredOption(`--userId `, `User ID.`) + .option(`--console`, `Get the resource console url`) .action(actionRunner(usersGet)) users @@ -1655,6 +1835,14 @@ users .requiredOption(`--email `, `User email.`) .action(actionRunner(usersUpdateEmail)) +users + .command(`createJWT`) + .description(`Use this endpoint to create a JSON Web Token for user by its unique ID. You can use the resulting JWT to authenticate on behalf of the user. The JWT secret will become invalid if the session it uses gets deleted.`) + .requiredOption(`--userId `, `User ID.`) + .option(`--sessionId `, `Session ID. Use the string 'recent' to use the most recent session. Defaults to the most recent session.`) + .option(`--duration `, `Time in seconds before JWT expires. Default duration is 900 seconds, and maximum is 3600 seconds.`, parseInteger) + .action(actionRunner(usersCreateJWT)) + users .command(`updateLabels`) .description(`Update the user labels by its unique ID. Labels can be used to grant access to resources. While teams are a way for user's to share access to a resource, labels can be defined by the developer to grant access without an invitation. See the [Permissions docs](https://appwrite.io/docs/permissions) for more info.`) @@ -1751,6 +1939,7 @@ users .command(`listSessions`) .description(`Get the user sessions list by its unique ID.`) .requiredOption(`--userId `, `User ID.`) + .option(`--console`, `Get the resource console url`) .action(actionRunner(usersListSessions)) users @@ -1860,6 +2049,7 @@ module.exports = { usersGet, usersDelete, usersUpdateEmail, + usersCreateJWT, usersUpdateLabels, usersListLogs, usersListMemberships, @@ -1887,4 +2077,4 @@ module.exports = { usersCreateToken, usersUpdateEmailVerification, usersUpdatePhoneVerification -}; \ No newline at end of file +}; diff --git a/lib/commands/vcs.js b/lib/commands/vcs.js index 65a0d7f..44ae4ce 100644 --- a/lib/commands/vcs.js +++ b/lib/commands/vcs.js @@ -4,7 +4,7 @@ const tar = require("tar"); const ignore = require("ignore"); const { promisify } = require('util'); const libClient = require('../client.js'); -const { getAllFiles } = require('../utils.js'); +const { getAllFiles, showConsoleLink } = require('../utils.js'); const { Command } = require('commander'); const { sdkForProject, sdkForConsole } = require('../sdks') const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log } = require('../parser') @@ -43,6 +43,7 @@ const vcs = new Command("vcs").description(commandDescriptions['vcs']).configure * @typedef {Object} VcsListRepositoriesRequestParams * @property {string} installationId Installation Id * @property {string} search Search term to filter your list results. Max length: 256 chars. + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -50,8 +51,9 @@ const vcs = new Command("vcs").description(commandDescriptions['vcs']).configure /** * @param {VcsListRepositoriesRequestParams} params */ -const vcsListRepositories = async ({ installationId, search, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const vcsListRepositories = async ({installationId,search,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/vcs/github/installations/{installationId}/providerRepositories'.replace('{installationId}', installationId); let payload = {}; if (typeof search !== 'undefined') { @@ -68,8 +70,9 @@ const vcsListRepositories = async ({ installationId, search, parseOutput = true, parse(response) success() } - + return response; + } /** @@ -77,6 +80,7 @@ const vcsListRepositories = async ({ installationId, search, parseOutput = true, * @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 */ @@ -84,8 +88,9 @@ const vcsListRepositories = async ({ installationId, search, parseOutput = true, /** * @param {VcsCreateRepositoryRequestParams} params */ -const vcsCreateRepository = async ({ installationId, name, xprivate, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const vcsCreateRepository = async ({installationId,name,xprivate,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/vcs/github/installations/{installationId}/providerRepositories'.replace('{installationId}', installationId); let payload = {}; if (typeof name !== 'undefined') { @@ -105,14 +110,16 @@ const vcsCreateRepository = async ({ installationId, name, xprivate, parseOutput parse(response) success() } - + 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 */ @@ -120,8 +127,9 @@ const vcsCreateRepository = async ({ installationId, name, xprivate, parseOutput /** * @param {VcsGetRepositoryRequestParams} params */ -const vcsGetRepository = async ({ installationId, providerRepositoryId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const vcsGetRepository = async ({installationId,providerRepositoryId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/vcs/github/installations/{installationId}/providerRepositories/{providerRepositoryId}'.replace('{installationId}', installationId).replace('{providerRepositoryId}', providerRepositoryId); let payload = {}; @@ -135,14 +143,16 @@ const vcsGetRepository = async ({ installationId, providerRepositoryId, parseOut parse(response) success() } - + 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 */ @@ -150,8 +160,9 @@ const vcsGetRepository = async ({ installationId, providerRepositoryId, parseOut /** * @param {VcsListRepositoryBranchesRequestParams} params */ -const vcsListRepositoryBranches = async ({ installationId, providerRepositoryId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const vcsListRepositoryBranches = async ({installationId,providerRepositoryId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/vcs/github/installations/{installationId}/providerRepositories/{providerRepositoryId}/branches'.replace('{installationId}', installationId).replace('{providerRepositoryId}', providerRepositoryId); let payload = {}; @@ -165,8 +176,46 @@ const vcsListRepositoryBranches = async ({ installationId, providerRepositoryId, parse(response) success() } - + + 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 {boolean} overrideForCli + * @property {boolean} parseOutput + * @property {libClient | undefined} sdk + */ + +/** + * @param {VcsGetRepositoryContentsRequestParams} params + */ +const vcsGetRepositoryContents = async ({installationId,providerRepositoryId,providerRootDirectory,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; + let apiPath = '/vcs/github/installations/{installationId}/providerRepositories/{providerRepositoryId}/contents'.replace('{installationId}', installationId).replace('{providerRepositoryId}', providerRepositoryId); + let payload = {}; + if (typeof providerRootDirectory !== 'undefined') { + payload['providerRootDirectory'] = providerRootDirectory; + } + + let response = undefined; + + response = await client.call('get', apiPath, { + 'content-type': 'application/json', + }, payload); + + if (parseOutput) { + parse(response) + success() + } + return response; + } /** @@ -174,6 +223,7 @@ const vcsListRepositoryBranches = async ({ installationId, providerRepositoryId, * @property {string} installationId Installation Id * @property {string} providerRepositoryId Repository Id * @property {string} providerRootDirectory Path to Root Directory + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -181,8 +231,9 @@ const vcsListRepositoryBranches = async ({ installationId, providerRepositoryId, /** * @param {VcsCreateRepositoryDetectionRequestParams} params */ -const vcsCreateRepositoryDetection = async ({ installationId, providerRepositoryId, providerRootDirectory, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const vcsCreateRepositoryDetection = async ({installationId,providerRepositoryId,providerRootDirectory,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/vcs/github/installations/{installationId}/providerRepositories/{providerRepositoryId}/detection'.replace('{installationId}', installationId).replace('{providerRepositoryId}', providerRepositoryId); let payload = {}; if (typeof providerRootDirectory !== 'undefined') { @@ -199,8 +250,9 @@ const vcsCreateRepositoryDetection = async ({ installationId, providerRepository parse(response) success() } - + return response; + } /** @@ -208,6 +260,7 @@ const vcsCreateRepositoryDetection = async ({ installationId, providerRepository * @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 */ @@ -215,8 +268,9 @@ const vcsCreateRepositoryDetection = async ({ installationId, providerRepository /** * @param {VcsUpdateExternalDeploymentsRequestParams} params */ -const vcsUpdateExternalDeployments = async ({ installationId, repositoryId, providerPullRequestId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const vcsUpdateExternalDeployments = async ({installationId,repositoryId,providerPullRequestId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/vcs/github/installations/{installationId}/repositories/{repositoryId}'.replace('{installationId}', installationId).replace('{repositoryId}', repositoryId); let payload = {}; if (typeof providerPullRequestId !== 'undefined') { @@ -233,14 +287,16 @@ const vcsUpdateExternalDeployments = async ({ installationId, repositoryId, prov parse(response) success() } - + 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} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -248,8 +304,9 @@ const vcsUpdateExternalDeployments = async ({ installationId, repositoryId, prov /** * @param {VcsListInstallationsRequestParams} params */ -const vcsListInstallations = async ({ queries, search, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const vcsListInstallations = async ({queries,search,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/vcs/installations'; let payload = {}; if (typeof queries !== 'undefined') { @@ -269,13 +326,15 @@ const vcsListInstallations = async ({ queries, search, parseOutput = true, sdk = parse(response) success() } - + return response; + } /** * @typedef {Object} VcsGetInstallationRequestParams * @property {string} installationId Installation Id + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -283,8 +342,9 @@ const vcsListInstallations = async ({ queries, search, parseOutput = true, sdk = /** * @param {VcsGetInstallationRequestParams} params */ -const vcsGetInstallation = async ({ installationId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const vcsGetInstallation = async ({installationId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/vcs/installations/{installationId}'.replace('{installationId}', installationId); let payload = {}; @@ -298,13 +358,15 @@ const vcsGetInstallation = async ({ installationId, parseOutput = true, sdk = un parse(response) success() } - + return response; + } /** * @typedef {Object} VcsDeleteInstallationRequestParams * @property {string} installationId Installation Id + * @property {boolean} overrideForCli * @property {boolean} parseOutput * @property {libClient | undefined} sdk */ @@ -312,8 +374,9 @@ const vcsGetInstallation = async ({ installationId, parseOutput = true, sdk = un /** * @param {VcsDeleteInstallationRequestParams} params */ -const vcsDeleteInstallation = async ({ installationId, parseOutput = true, sdk = undefined}) => { - let client = !sdk ? await sdkForProject() : sdk; +const vcsDeleteInstallation = async ({installationId,parseOutput = true, overrideForCli = false, sdk = undefined}) => { + let client = !sdk ? await sdkForProject() : + sdk; let apiPath = '/vcs/installations/{installationId}'.replace('{installationId}', installationId); let payload = {}; @@ -327,8 +390,9 @@ const vcsDeleteInstallation = async ({ installationId, parseOutput = true, sdk = parse(response) success() } - + return response; + } vcs @@ -360,6 +424,14 @@ vcs .requiredOption(`--providerRepositoryId `, `Repository Id`) .action(actionRunner(vcsListRepositoryBranches)) +vcs + .command(`getRepositoryContents`) + .description(``) + .requiredOption(`--installationId `, `Installation Id`) + .requiredOption(`--providerRepositoryId `, `Repository Id`) + .option(`--providerRootDirectory `, `Path to get contents of nested directory`) + .action(actionRunner(vcsGetRepositoryContents)) + vcs .command(`createRepositoryDetection`) .description(``) @@ -401,9 +473,10 @@ module.exports = { vcsCreateRepository, vcsGetRepository, vcsListRepositoryBranches, + vcsGetRepositoryContents, vcsCreateRepositoryDetection, vcsUpdateExternalDeployments, vcsListInstallations, vcsGetInstallation, vcsDeleteInstallation -}; \ No newline at end of file +}; diff --git a/lib/config.js b/lib/config.js index 2f69a8f..ca66b52 100644 --- a/lib/config.js +++ b/lib/config.js @@ -204,6 +204,45 @@ class Local extends Config { 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) { + 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); + } + getDatabases() { if (!this.has("databases")) { return []; @@ -283,26 +322,75 @@ class Local extends Config { } getProject() { - if (!this.has("projectId") || !this.has("projectName")) { + if (!this.has("projectId")) { return {}; } return { projectId: this.get("projectId"), projectName: this.get("projectName"), + projectSettings: this.get('projectSettings') }; } - setProject(projectId, projectName) { + setProject(projectId, projectName = '', projectSettings = undefined) { this.set("projectId", projectId); - this.set("projectName", projectName); + + if (projectName !== '') { + this.set("projectName", projectName); + } + + if (projectSettings === undefined) { + return; + } + + const settings = { + 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, + 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 + } + } + }; + + this.set('projectSettings', settings) } + } 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"; @@ -310,6 +398,8 @@ class Global extends Config { 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"; @@ -320,59 +410,141 @@ class Global extends Config { 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)) + + return sessions.map((session) => { + + return { + id: session, + endpoint: this.data[session][Global.PREFERENCE_ENDPOINT], + email: this.data[session][Global.PREFERENCE_EMAIL] + } + }) + } + + 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.has(Global.PREFERENCE_ENDPOINT)) { + if (!this.hasFrom(Global.PREFERENCE_ENDPOINT)) { return ""; } - return this.get(Global.PREFERENCE_ENDPOINT); + + return this.getFrom(Global.PREFERENCE_ENDPOINT); } setEndpoint(endpoint) { - this.set(Global.PREFERENCE_ENDPOINT, endpoint); + this.setTo(Global.PREFERENCE_ENDPOINT, endpoint); } getSelfSigned() { - if (!this.has(Global.PREFERENCE_SELF_SIGNED)) { + if (!this.hasFrom(Global.PREFERENCE_SELF_SIGNED)) { return false; } - return this.get(Global.PREFERENCE_SELF_SIGNED); + return this.getFrom(Global.PREFERENCE_SELF_SIGNED); } setSelfSigned(selfSigned) { - this.set(Global.PREFERENCE_SELF_SIGNED, selfSigned); + this.setTo(Global.PREFERENCE_SELF_SIGNED, selfSigned); } getCookie() { - if (!this.has(Global.PREFERENCE_COOKIE)) { + if (!this.hasFrom(Global.PREFERENCE_COOKIE)) { return ""; } - return this.get(Global.PREFERENCE_COOKIE); + return this.getFrom(Global.PREFERENCE_COOKIE); } setCookie(cookie) { - this.set(Global.PREFERENCE_COOKIE, cookie); + this.setTo(Global.PREFERENCE_COOKIE, cookie); } getProject() { - if (!this.has(Global.PREFERENCE_PROJECT)) { + if (!this.hasFrom(Global.PREFERENCE_PROJECT)) { return ""; } - return this.get(Global.PREFERENCE_PROJECT); + return this.getFrom(Global.PREFERENCE_PROJECT); } setProject(project) { - this.set(Global.PREFERENCE_PROJECT, project); + this.setTo(Global.PREFERENCE_PROJECT, project); } getKey() { - if (!this.has(Global.PREFERENCE_KEY)) { + if (!this.hasFrom(Global.PREFERENCE_KEY)) { return ""; } - return this.get(Global.PREFERENCE_KEY); + return this.getFrom(Global.PREFERENCE_KEY); } setKey(key) { - this.set(Global.PREFERENCE_KEY, 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(); + } } } diff --git a/lib/emulation/docker.js b/lib/emulation/docker.js new file mode 100644 index 0000000..fe50339 --- /dev/null +++ b/lib/emulation/docker.js @@ -0,0 +1,187 @@ +const childProcess = require('child_process'); +const { localConfig } = require("../config"); +const path = require('path'); +const fs = require('fs'); +const { log,success } = require("../parser"); +const { openRuntimesVersion, systemTools } = require("./utils"); +const ID = require("../id"); + +const activeDockerIds = {}; + +async function dockerStop(id) { + delete activeDockerIds[id]; + const stopProcess = childProcess.spawn('docker', ['rm', '--force', id], { + stdio: 'pipe', + }); + + await new Promise((res) => { stopProcess.on('close', res) }); +} + +async function dockerPull(func) { + log('Pulling Docker image of function runtime ...'); + + const runtimeChunks = func.runtime.split("-"); + const runtimeVersion = runtimeChunks.pop(); + const runtimeName = runtimeChunks.join("-"); + const imageName = `openruntimes/${runtimeName}:${openRuntimesVersion}-${runtimeVersion}`; + + const pullProcess = childProcess.spawn('docker', ['pull', imageName], { + stdio: 'pipe', + pwd: path.join(process.cwd(), func.path) + }); + + pullProcess.stderr.on('data', (data) => { + process.stderr.write(`\n${data}$ `); + }); + + await new Promise((res) => { pullProcess.on('close', res) }); +} + +async function dockerBuild(func, variables) { + log('Building function using Docker ...'); + + const runtimeChunks = func.runtime.split("-"); + const runtimeVersion = runtimeChunks.pop(); + const runtimeName = runtimeChunks.join("-"); + const imageName = `openruntimes/${runtimeName}:${openRuntimesVersion}-${runtimeVersion}`; + + const functionDir = path.join(process.cwd(), func.path); + + const id = ID.unique(); + + const params = [ 'run' ]; + params.push('--name', id); + params.push('-v', `${functionDir}/:/mnt/code:rw`); + params.push('-e', 'APPWRITE_ENV=development'); + params.push('-e', 'OPEN_RUNTIMES_ENV=development'); + params.push('-e', 'OPEN_RUNTIMES_SECRET='); + params.push('-e', `OPEN_RUNTIMES_ENTRYPOINT=${func.entrypoint}`); + + for(const k of Object.keys(variables)) { + params.push('-e', `${k}=${variables[k]}`); + } + + params.push(imageName, 'sh', '-c', `helpers/build.sh "${func.commands}"`); + + const buildProcess = childProcess.spawn('docker', params, { + stdio: 'pipe', + pwd: functionDir + }); + + buildProcess.stdout.on('data', (data) => { + process.stdout.write(`\n${data}`); + }); + + buildProcess.stderr.on('data', (data) => { + process.stderr.write(`\n${data}`); + }); + + await new Promise((res) => { buildProcess.on('close', res) }); + + const copyPath = path.join(process.cwd(), func.path, '.appwrite', 'build.tar.gz'); + const copyDir = path.dirname(copyPath); + if (!fs.existsSync(copyDir)) { + fs.mkdirSync(copyDir, { recursive: true }); + } + + const copyProcess = childProcess.spawn('docker', ['cp', `${id}:/mnt/code/code.tar.gz`, copyPath], { + stdio: 'pipe', + pwd: functionDir + }); + + await new Promise((res) => { copyProcess.on('close', res) }); + + const cleanupProcess = childProcess.spawn('docker', ['rm', '--force', id], { + stdio: 'pipe', + pwd: functionDir + }); + + await new Promise((res) => { cleanupProcess.on('close', res) }); + + delete activeDockerIds[id]; + + const tempPath = path.join(process.cwd(), func.path, 'code.tar.gz'); + if (fs.existsSync(tempPath)) { + fs.rmSync(tempPath, { force: true }); + } +} + +async function dockerStart(func, variables, port) { + log('Starting function using Docker ...'); + + log("Permissions, events, CRON and timeouts dont apply when running locally."); + + log('💡 Hint: Function automatically restarts when you edit your code.'); + + success(`Visit http://localhost:${port}/ to execute your function.`); + + + const runtimeChunks = func.runtime.split("-"); + const runtimeVersion = runtimeChunks.pop(); + const runtimeName = runtimeChunks.join("-"); + const imageName = `openruntimes/${runtimeName}:${openRuntimesVersion}-${runtimeVersion}`; + + const tool = systemTools[runtimeName]; + + const functionDir = path.join(process.cwd(), func.path); + + const id = ID.unique(); + + const params = [ 'run' ]; + params.push('--rm'); + params.push('-d'); + params.push('--name', id); + params.push('-p', `${port}:3000`); + params.push('-e', 'APPWRITE_ENV=development'); + params.push('-e', 'OPEN_RUNTIMES_ENV=development'); + params.push('-e', 'OPEN_RUNTIMES_SECRET='); + + for(const k of Object.keys(variables)) { + params.push('-e', `${k}=${variables[k]}`); + } + + params.push('-v', `${functionDir}/.appwrite/logs.txt:/mnt/logs/dev_logs.log:rw`); + params.push('-v', `${functionDir}/.appwrite/errors.txt:/mnt/logs/dev_errors.log:rw`); + params.push('-v', `${functionDir}/.appwrite/build.tar.gz:/mnt/code/code.tar.gz:ro`); + params.push(imageName, 'sh', '-c', `helpers/start.sh "${tool.startCommand}"`); + + childProcess.spawn('docker', params, { + stdio: 'pipe', + pwd: functionDir + }); + + activeDockerIds[id] = true; +} + +async function dockerCleanup() { + await dockerStop(); + + const functions = localConfig.getFunctions(); + for(const func of functions) { + const appwritePath = path.join(process.cwd(), func.path, '.appwrite'); + if (fs.existsSync(appwritePath)) { + fs.rmSync(appwritePath, { recursive: true, force: true }); + } + + const tempPath = path.join(process.cwd(), func.path, 'code.tar.gz'); + if (fs.existsSync(tempPath)) { + fs.rmSync(tempPath, { force: true }); + } + } +} + +async function dockerStopActive() { + const ids = Object.keys(activeDockerIds); + for await (const id of ids) { + await dockerStop(id); + } +} + +module.exports = { + dockerStop, + dockerPull, + dockerBuild, + dockerStart, + dockerCleanup, + dockerStopActive, +} diff --git a/lib/emulation/utils.js b/lib/emulation/utils.js new file mode 100644 index 0000000..d36d5cd --- /dev/null +++ b/lib/emulation/utils.js @@ -0,0 +1,177 @@ +const EventEmitter = require('node:events'); +const { projectsCreateJWT } = require('../commands/projects'); +const { localConfig } = require("../config"); + + +const openRuntimesVersion = 'v3'; + +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' +}; + +const systemTools = { + 'node': { + isCompiled: false, + startCommand: "node src/server.js", + dependencyFiles: [ "package.json", "package-lock.json" ] + }, + 'php': { + isCompiled: false, + startCommand: "php src/server.php", + dependencyFiles: [ "composer.json", "composer.lock" ] + }, + 'ruby': { + isCompiled: false, + startCommand: "bundle exec puma -b tcp://0.0.0.0:3000 -e production", + dependencyFiles: [ "Gemfile", "Gemfile.lock" ] + }, + 'python': { + isCompiled: false, + startCommand: "python3 src/server.py", + dependencyFiles: [ "requirements.txt", "requirements.lock" ] + }, + 'python-ml': { + isCompiled: false, + startCommand: "python3 src/server.py", + dependencyFiles: [ "requirements.txt", "requirements.lock" ] + }, + 'deno': { + isCompiled: false, + startCommand: "deno start", + dependencyFiles: [ ] + }, + 'dart': { + isCompiled: true, + startCommand: "src/function/server", + dependencyFiles: [ ] + }, + 'dotnet': { + isCompiled: true, + startCommand: "dotnet src/function/DotNetRuntime.dll", + dependencyFiles: [ ] + }, + 'java': { + isCompiled: true, + startCommand: "java -jar src/function/java-runtime-1.0.0.jar", + dependencyFiles: [ ] + }, + 'swift': { + isCompiled: true, + startCommand: "src/function/Runtime serve --env production --hostname 0.0.0.0 --port 3000", + dependencyFiles: [ ] + }, + 'kotlin': { + isCompiled: true, + startCommand: "java -jar src/function/kotlin-runtime-1.0.0.jar", + dependencyFiles: [ ] + }, + 'bun': { + isCompiled: false, + startCommand: "bun src/server.ts", + dependencyFiles: [ "package.json", "package-lock.json", "bun.lockb" ] + }, +}; + +const JwtManager = { + userJwt: null, + functionJwt: null, + + timerWarn: null, + timerError: null, + + async setup(userId = null) { + 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, + // TODO: Once we have endpoint for this, use it + scopes: ["sessions.write","users.read","users.write","teams.read","teams.write","databases.read","databases.write","collections.read","collections.write","attributes.read","attributes.write","indexes.read","indexes.write","documents.read","documents.write","files.read","files.write","buckets.read","buckets.write","functions.read","functions.write","execution.read","execution.write","locale.read","avatars.read","health.read","providers.read","providers.write","messages.read","messages.write","topics.read","topics.write","subscribers.read","subscribers.write","targets.read","targets.write","rules.read","rules.write","migrations.read","migrations.write","vcs.read","vcs.write","assistant.read"], + 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; + }, + 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/id.js b/lib/id.js new file mode 100644 index 0000000..b628463 --- /dev/null +++ b/lib/id.js @@ -0,0 +1,30 @@ +class ID { + // Generate an hex ID based on timestamp + // Recreated from https://www.php.net/manual/en/function.uniqid.php + static #hexTimestamp() { + const now = new Date(); + const sec = Math.floor(now.getTime() / 1000); + const msec = now.getMilliseconds(); + + // Convert to hexadecimal + const hexTimestamp = sec.toString(16) + msec.toString(16).padStart(5, '0'); + return hexTimestamp; + } + + static custom(id) { + return id + } + + static unique(padding = 7) { + // Generate a unique ID with padding to have a longer ID + const baseId = ID.#hexTimestamp(); + let randomPadding = ''; + for (let i = 0; i < padding; i++) { + const randomHexDigit = Math.floor(Math.random() * 16).toString(16); + randomPadding += randomHexDigit; + } + return baseId + randomPadding; + } +} + +module.exports = ID; diff --git a/lib/paginate.js b/lib/paginate.js index 8c57fa7..c78814a 100644 --- a/lib/paginate.js +++ b/lib/paginate.js @@ -5,7 +5,6 @@ const paginate = async (action, args = {}, limit = 100, wrapper = '') => { while (true) { const offset = pageNumber * limit; - // Merge the limit and offset into the args const response = await action({ ...args, @@ -48,4 +47,4 @@ const paginate = async (action, args = {}, limit = 100, wrapper = '') => { module.exports = { paginate -}; \ No newline at end of file +}; diff --git a/lib/parser.js b/lib/parser.js index 717bdd6..8c64db2 100644 --- a/lib/parser.js +++ b/lib/parser.js @@ -2,10 +2,18 @@ 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 cliConfig = { - verbose: false, - json: false + verbose: false, + json: false, + force: false, + all: false, + ids: [], + report: false, + reportData: {} }; const parse = (data) => { @@ -110,17 +118,60 @@ const drawJSON = (data) => { } const parseError = (err) => { - if(cliConfig.verbose) { - console.error(err); - } + if (cliConfig.report) { + (async () => { + let appwriteVersion = 'unknown'; + const endpoint = globalConfig.getEndpoint(); + const isCloud = endpoint.includes('cloud.appwrite.io') ? 'Yes' : 'No'; + + try { + const client = new Client().setEndpoint(endpoint); + const res = await client.call('get', '/health/version'); + appwriteVersion = res.version; + } catch { + } + + const version = '5.0.5'; + 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(err.message); - process.exit(1) + 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) => fn(...args).catch(parseError); + 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) => { @@ -156,10 +207,12 @@ const commandDescriptions = { "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": `The databases command allows you to create structured collections of documents, query and filter lists of documents.`, - "deploy": `The deploy command provides a convenient wrapper for deploying your functions and collections.`, + "init": `The init command provides a convenient wrapper for creating and initializing project, functions, collections, buckets, teams and messaging in Appwrite.`, + "push": `The push command provides a convenient wrapper for pushing your functions, collections, buckets, teams and messaging.`, + "run": `The run command allows you to run project locally to allow easy development and quick debugging.`, "functions": `The functions command allows you view, create and manage your Cloud Functions.`, "health": `The health command allows you to both validate and monitor your Appwrite server's health.`, - "init": `The init command helps you initialize your Appwrite project, functions and collections`, + "pull": `The pull command helps you pull your Appwrite project, functions, collections, buckets, teams and messaging`, "locale": `The locale command allows you to customize your app based on your users' location.`, "projects": `The projects command allows you to view, create and manage your Appwrite projects.`, "storage": `The storage command allows you to manage your project files.`, @@ -168,6 +221,8 @@ const commandDescriptions = { "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 logout of your Appwrite account.`, + "whoami": `The whoami command gives information about the currently logged in user.`, + "register": `Outputs the link to create an Appwrite account..`, "console" : `The console command allows gives you access to the APIs used by the Appwrite console.`, "assistant": `The assistant command allows you to interact with the Appwrite Assistant AI`, "messaging": `The messaging command allows you to send messages.`, @@ -179,6 +234,7 @@ const commandDescriptions = { } module.exports = { + drawTable, parse, actionRunner, parseInteger, @@ -187,5 +243,6 @@ module.exports = { success, error, commandDescriptions, - cliConfig -} \ No newline at end of file + cliConfig, + drawTable +} diff --git a/lib/questions.js b/lib/questions.js index 7f26b13..d003f9d 100644 --- a/lib/questions.js +++ b/lib/questions.js @@ -1,15 +1,22 @@ -const { localConfig } = require('./config'); +const chalk = require("chalk"); +const Client = require("./client"); +const { localConfig, globalConfig } = require('./config'); const { projectsList } = require('./commands/projects'); -const { functionsListRuntimes } = require('./commands/functions'); +const { teamsList } = require('./commands/teams'); +const { functionsListRuntimes, 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 } = require('./utils'); const JSONbig = require("json-bigint")({ storeAsString: false }); +const whenOverride = (answers) => answers.override === undefined ? true : answers.override; + const getIgnores = (runtime) => { - const languge = runtime.split('-')[0]; + const languge = runtime.split("-").slice(0, -1).join("-"); switch (languge) { case 'cpp': @@ -29,6 +36,7 @@ const getIgnores = (runtime) => { case 'php': return ['vendor']; case 'python': + case 'python-ml': return ['__pypackages__']; case 'ruby': return ['vendor']; @@ -42,7 +50,7 @@ const getIgnores = (runtime) => { }; const getEntrypoint = (runtime) => { - const languge = runtime.split('-')[0]; + const languge = runtime.split("-").slice(0, -1).join("-"); switch (languge) { case 'dart': @@ -56,6 +64,7 @@ const getEntrypoint = (runtime) => { case 'php': return 'src/index.php'; case 'python': + case 'python-ml': return 'src/main.py'; case 'ruby': return 'lib/main.rb'; @@ -77,7 +86,7 @@ const getEntrypoint = (runtime) => { }; const getInstallCommand = (runtime) => { - const languge = runtime.split('-')[0]; + const languge = runtime.split("-").slice(0, -1).join("-"); switch (languge) { case 'dart': @@ -91,6 +100,7 @@ const getInstallCommand = (runtime) => { case 'php': return 'composer install'; case 'python': + case 'python-ml': return 'pip install -r requirements.txt'; case 'ruby': return 'bundle install'; @@ -113,7 +123,7 @@ const questionsInitProject = [ type: "confirm", name: "override", message: - `An Appwrite project ( ${localConfig.getProject()['projectName']} ) is already associated with the current directory. Would you like to override`, + `An Appwrite project ( ${localConfig.getProject()['projectId']} ) is already associated with the current directory. Would you like to override`, when() { return Object.keys(localConfig.getProject()).length !== 0; } @@ -121,61 +131,72 @@ const questionsInitProject = [ { type: "list", name: "start", - when(answers) { - if (answers.override == undefined) { - return true - } - return answers.override; - }, + when: whenOverride, message: "How would you like to start?", choices: [ { - name: "Create a new Appwrite project", - value: "new", + name: "Create new project", + value: "new" }, { - name: "Link this directory to an existing Appwrite project", - value: "existing", - }, - ], + name: "Link directory to an existing project", + value: "existing" + } + ] + }, + { + type: "search-list", + name: "organization", + message: "Choose your organization", + choices: async () => { + let client = await sdkForConsole(true); + const { teams } = await paginate(teamsList, { parseOutput: false, sdk: client }, 100, 'teams'); + + let choices = teams.map((team, idx) => { + return { + name: `${team.name} (${team['$id']})`, + value: team['$id'] + } + }) + + if (choices.length == 0) { + throw new Error(`No organizations found. Please create a new organization at ${globalConfig.getEndpoint().replace('/v1', '/console/onboarding')}`) + } + + return choices; + }, + when: whenOverride }, { type: "input", name: "project", message: "What would you like to name your project?", default: "My Awesome Project", - when(answers) { - return answers.start == "new"; - }, + when: (answer) => answer.start !== 'existing' }, { type: "input", name: "id", message: "What ID would you like to have for your project?", default: "unique()", - when(answers) { - return answers.start == "new"; - }, + when: (answer) => answer.start !== 'existing' }, { - type: "list", + type: "search-list", name: "project", message: "Choose your Appwrite project.", - when(answers) { - return answers.start == "existing"; - }, - choices: async () => { - let response = await projectsList({ - parseOutput: false - }) - let projects = response["projects"] - let choices = projects.map((project, idx) => { + choices: async (answers) => { + const queries = [ + JSON.stringify({ method: 'equal', attribute: 'teamId', values: [answers.organization.id] }), + JSON.stringify({ method: 'orderDesc', attribute: 'Id' }) + ] + + const { projects } = await paginate(projectsList, { parseOutput: false, queries, }, 100, 'projects'); + + let choices = projects.map((project) => { return { name: `${project.name} (${project['$id']})`, - value: { - name: project.name, - id: project['$id'] - } + value: project['$id'] } }) @@ -184,11 +205,50 @@ const questionsInitProject = [ } return choices; + }, + when: (answer) => answer.start === 'existing' + } +]; +const questionsPullResources = [ + { + type: "list", + name: "resource", + message: "Which resources would you like to pull?", + choices: [ + { name: 'Project', value: 'project' }, + { name: 'Functions', value: 'functions' }, + { name: 'Collections', value: 'collections' }, + { name: 'Buckets', value: 'buckets' }, + { name: 'Teams', value: 'teams' }, + { name: 'Topics', value: 'messages' } + ] + } +] + +const questionsPullFunctions = [ + { + type: "checkbox", + name: "functions", + message: "Which functions would you like to pull?", + validate: (value) => 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 { + name: `${func.name} (${func.$id})`, + value: func + } + }); } } ]; -const questionsInitFunction = [ +const questionsCreateFunction = [ { type: "input", name: "name", @@ -215,9 +275,10 @@ const questionsInitFunction = [ name: `${runtime.name} (${runtime['$id']})`, value: { id: runtime['$id'], + name: runtime['$id'].split('-')[0], entrypoint: getEntrypoint(runtime['$id']), ignore: getIgnores(runtime['$id']), - commands : getInstallCommand(runtime['$id']) + commands: getInstallCommand(runtime['$id']) }, } }) @@ -226,11 +287,146 @@ const questionsInitFunction = [ } ]; -const questionsInitCollection = [ +const questionsCreateFunctionSelectTemplate = (templates) => { + return [ + { + type: "search-list", + name: "template", + message: "What template would you like to use?", + choices: templates.map((template) => { + const name = `${template[0].toUpperCase()}${template.split('').slice(1).join('')}`.replace(/[-_]/g, ' '); + + return { value: template, name } + }) + } + ]; +}; + + + +const questionsCreateBucket = [ + { + type: "input", + name: "bucket", + message: "What would you like to name your bucket?", + default: "My Awesome Bucket" + }, + { + type: "input", + name: "id", + message: "What ID would you like to have for your bucket?", + default: "unique()" + }, + { + type: "list", + name: "fileSecurity", + message: "Enable File-Security configuring permissions for individual file", + choices: ["No", "Yes"] + } +]; + +const questionsCreateTeam = [ + { + type: "input", + name: "bucket", + message: "What would you like to name your team?", + default: "My Awesome Team" + }, + { + type: "input", + name: "id", + message: "What ID would you like to have for your team?", + default: "unique()" + } +]; + +const questionsCreateCollection = [ + { + type: "list", + name: "method", + message: "What database would you like to use for your collection", + choices: ["New", "Existing"], + when: async () => { + return localConfig.getDatabases().length !== 0; + } + }, + { + type: "search-list", + name: "database", + message: "Choose the collection database", + choices: async () => { + const databases = localConfig.getDatabases(); + + let choices = databases.map((database, idx) => { + return { + name: `${database.name} (${database.$id})`, + value: database.$id + } + }) + + if (choices.length === 0) { + throw new Error("No databases found. Please create one in project console.") + } + + return choices; + }, + when: (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' + }, + { + type: "input", + name: "databaseId", + message: "What ID would you like to have for your database?", + default: "unique()", + when: (answers) => (answers.method ?? '').toLowerCase() !== 'existing' + }, + { + type: "input", + name: "collection", + message: "What would you like to name your collection?", + default: "My Awesome Collection" + }, + { + type: "input", + name: "id", + message: "What ID would you like to have for your collection?", + default: "unique()" + }, + { + type: "list", + name: "documentSecurity", + message: "Enable Document-Security for configuring permissions for individual documents", + choices: ["No", "Yes"] + } +]; + +const questionsCreateMessagingTopic = [ + { + type: "input", + name: "topic", + message: "What would you like to name your messaging topic?", + default: "My Awesome Topic" + }, + { + type: "input", + name: "id", + message: "What ID would you like to have for your messaging topic?", + default: "unique()" + } +]; + +const questionsPullCollection = [ { type: "checkbox", name: "databases", - message: "From which database would you like to init collections?", + message: "From which database would you like to pull collections?", + validate: (value) => validateRequired('collection', value), choices: async () => { let response = await databasesList({ parseOutput: false @@ -252,6 +448,16 @@ const questionsInitCollection = [ ]; const questionsLogin = [ + { + type: "list", + name: "method", + message: "You're already logged in, what you like to do?", + choices: [ + { name: 'Login to a different account', value: 'login' }, + { name: 'Change to a different existed account', value: 'select' } + ], + when: () => globalConfig.getCurrentSession() !== '' + }, { type: "input", name: "email", @@ -262,6 +468,7 @@ const questionsLogin = [ } return true; }, + when: (answers) => answers.method !== 'select' }, { type: "password", @@ -273,20 +480,132 @@ const questionsLogin = [ return "Please enter your password"; } return true; - } + }, + when: (answers) => answers.method !== 'select' + }, + { + type: "search-list", + name: "accountId", + message: "Select an account to use", + choices() { + const sessions = globalConfig.getSessions(); + const current = globalConfig.getCurrentSession(); + + const data = []; + + const longestEmail = sessions.reduce((prev, current) => (prev && (prev.email ?? '').length > (current.email ?? '').length) ? prev : current).email.length; + + sessions.forEach((session) => { + if (session.email) { + data.push({ + current: current === session.id, + value: session.id, + name: `${session.email.padEnd(longestEmail)} ${current === session.id ? chalk.green.bold('current') : ' '.repeat(6)} ${session.endpoint}`, + }); + } + }) + + return data.sort((a, b) => Number(b.current) - Number(a.current)) + }, + when: (answers) => answers.method === 'select' }, ]; +const questionGetEndpoint = [ + { + type: "input", + name: "endpoint", + message: "Enter the endpoint of your Appwrite server", + default: "http://localhost/v1", + async validate(value) { + if (!value) { + return "Please enter a valid endpoint."; + } + let client = new Client().setEndpoint(value); + try { + let response = await client.call('get', '/health/version'); + if (response.version) { + return true; + } else { + throw new Error(); + } + } catch (error) { + return "Invalid endpoint or your Appwrite server is not running as expected."; + } + } + } +]; -const questionsDeployFunctions = [ +const questionsLogout = [ + { + type: "checkbox", + name: "accounts", + message: "Select accounts to logout from", + validate: (value) => validateRequired('account', value), + choices() { + const sessions = globalConfig.getSessions(); + const current = globalConfig.getCurrentSession(); + + const data = []; + + const longestEmail = sessions.reduce((prev, current) => (prev && (prev.email ?? '').length > (current.email ?? '').length) ? prev : current).email.length; + + sessions.forEach((session) => { + if (session.email) { + data.push({ + current: current === session.id, + value: session.id, + name: `${session.email.padEnd(longestEmail)} ${current === session.id ? chalk.green.bold('current') : ' '.repeat(6)} ${session.endpoint}`, + }); + } + }) + + return data.sort((a, b) => Number(b.current) - Number(a.current)) + } + } +]; + +const questionsPushResources = [ + { + type: "list", + name: "resource", + message: "Which resources would you like to push?", + choices: [ + { name: 'Project', value: 'project' }, + { name: 'Functions', value: 'functions' }, + { name: 'Collections', value: 'collections' }, + { name: 'Buckets', value: 'buckets' }, + { name: 'Teams', value: 'teams' }, + { name: 'Topics', value: 'messages' } + ] + } +]; + +const questionsInitResources = [ + { + type: "list", + name: "resource", + message: "Which resource would you create?", + choices: [ + { name: 'Function', value: 'function' }, + { name: 'Collection', value: 'collection' }, + { name: 'Bucket', value: 'bucket' }, + { name: 'Team', value: 'team' }, + { name: 'Topic', value: 'message' } + ] + } +]; + +const questionsPushFunctions = [ { type: "checkbox", name: "functions", - message: "Which functions would you like to deploy?", + message: "Which functions would you like to push?", + validate: (value) => validateRequired('function', value), choices: () => { let functions = localConfig.getFunctions(); checkDeployConditions(localConfig) if (functions.length === 0) { - throw new Error("No functions found in the current directory."); + throw new Error("No functions found in the current directory Use 'appwrite pull functions' to synchronize existing one, or use 'appwrite init function' to create a new one."); } let choices = functions.map((func, idx) => { return { @@ -304,17 +623,18 @@ const questionsDeployFunctions = [ }, ] -const questionsDeployCollections = [ +const questionsPushCollections = [ { type: "checkbox", name: "collections", - message: "Which collections would you like to deploy?", + message: "Which collections would you like to push?", + validate: (value) => validateRequired('collection', value), choices: () => { let collections = localConfig.getCollections(); checkDeployConditions(localConfig) if (collections.length === 0) { - throw new Error("No collections found in the current directory. Run `appwrite init collection` to fetch all your collections."); + throw new Error("No collections found in the current directory. Use 'appwrite pull collections' to synchronize existing one, or use 'appwrite init collection' to create a new one."); } return collections.map(collection => { return { @@ -326,21 +646,22 @@ const questionsDeployCollections = [ }, { type: "input", - name: "override", - message: 'Are you sure you want to override this collection? This can lead to loss of data! Type "YES" to confirm.' - }, + name: "changes", + message: `Would you like to apply these changes? Type "YES" to confirm.` + } ] -const questionsDeployBuckets = [ +const questionsPushBuckets = [ { type: "checkbox", name: "buckets", - message: "Which buckets would you like to deploy?", + message: "Which buckets would you like to push?", + validate: (value) => validateRequired('bucket', value), choices: () => { let buckets = localConfig.getBuckets(); checkDeployConditions(localConfig) if (buckets.length === 0) { - throw new Error("No buckets found in the current directory. Run `appwrite init bucket` to fetch all your buckets."); + throw new Error("No buckets found in the current directory. Use 'appwrite pull buckets' to synchronize existing one, or use 'appwrite init bucket' to create a new one."); } return buckets.map(bucket => { return { @@ -349,12 +670,32 @@ const questionsDeployBuckets = [ } }); } + } +] + +const questionsPushMessagingTopics = [ + { + type: "checkbox", + name: "topics", + message: "Which messaging topic would you like to push?", + choices: () => { + let topics = localConfig.getMessagingTopics(); + if (topics.length === 0) { + throw new Error("No topics found in the current directory. Use 'appwrite pull topics' to synchronize existing one, or use 'appwrite init topic' to create a new one."); + } + return topics.map(topic => { + return { + name: `${topic.name} (${topic['$id']})`, + value: topic.$id + } + }); + } }, { type: "input", name: "override", - message: 'Are you sure you want to override this bucket? This can lead to loss of data! Type "YES" to confirm.' - }, + message: 'Would you like to override existing topics? This can lead to loss of data! Type "YES" to confirm.' + } ] const questionsGetEntrypoint = [ @@ -372,16 +713,17 @@ const questionsGetEntrypoint = [ }, ] -const questionsDeployTeams = [ +const questionsPushTeams = [ { type: "checkbox", name: "teams", - message: "Which teams would you like to deploy?", + message: "Which teams would you like to push?", + validate: (value) => validateRequired('team', value), choices: () => { let teams = localConfig.getTeams(); checkDeployConditions(localConfig); if (teams.length === 0) { - throw new Error("No teams found in the current directory. Run `appwrite init team` to fetch all your teams."); + throw new Error("No teams found in the current directory. Use 'appwrite pull teams' to synchronize existing one, or use 'appwrite init team' to create a new one."); } return teams.map(team => { return { @@ -391,43 +733,38 @@ const questionsDeployTeams = [ }); } }, - { - type: "input", - name: "override", - message: 'Are you sure you want to override this team? This can lead to loss of data! Type "YES" to confirm.' - }, ]; const questionsListFactors = [ { type: "list", name: "factor", - message: "Your account is protected by multiple factors. Which factor would you like to use to authenticate?", + message: "Your account is protected by multi-factor authentication. Please choose one for verification.", choices: async () => { let client = await sdkForConsole(false); const factors = await accountListMfaFactors({ sdk: client, parseOutput: false }); - + const choices = [ { - name: `TOTP (Time-based One-time Password)`, + name: `Authenticator app (Get a code from a third-party authenticator app)`, value: 'totp' }, { - name: `E-mail`, + name: `Email (Get a security code at your Appwrite email address)`, value: 'email' }, { - name: `Phone (SMS)`, + name: `SMS (Get a security code on your Appwrite phone number)`, value: 'phone' }, { - name: `Recovery code`, + name: `Recovery code (Use one of your recovery codes for verification)`, value: 'recoveryCode' } - ].filter((ch) => factors[ch.value] === true); + ].filter((ch) => factors[ch.value] === true); return choices; } @@ -448,16 +785,51 @@ const questionsMfaChallenge = [ } ]; +const questionsRunFunctions = [ + { + type: "list", + name: "function", + message: "Which function would you like to develop locally?", + validate: (value) => validateRequired('function', value), + choices: () => { + let functions = localConfig.getFunctions(); + if (functions.length === 0) { + throw new Error("No functions found in the current directory. Use 'appwrite pull functions' to synchronize existing one, or use 'appwrite init function' to create a new one."); + } + let choices = functions.map((func, idx) => { + return { + name: `${func.name} (${func.$id})`, + value: func.$id + } + }) + return choices; + } + } +]; + module.exports = { questionsInitProject, + questionsCreateFunction, + questionsCreateFunctionSelectTemplate, + questionsCreateBucket, + questionsCreateCollection, + questionsCreateMessagingTopic, + questionsPullFunctions, questionsLogin, - questionsInitFunction, - questionsInitCollection, - questionsDeployFunctions, - questionsDeployCollections, - questionsDeployBuckets, - questionsDeployTeams, + questionsPullResources, + questionsLogout, + questionsPullCollection, + questionsPushResources, + questionsPushFunctions, + questionsPushCollections, + questionsPushBuckets, + questionsPushMessagingTopics, + questionsPushTeams, questionsGetEntrypoint, questionsListFactors, - questionsMfaChallenge + questionsMfaChallenge, + questionsRunFunctions, + questionGetEndpoint, + questionsInitResources, + questionsCreateTeam }; diff --git a/lib/sdks.js b/lib/sdks.js index fe8afb8..48957b4 100644 --- a/lib/sdks.js +++ b/lib/sdks.js @@ -68,7 +68,7 @@ const sdkForProject = async () => { } if (!project) { - throw new Error("Project is not set. Please run `appwrite init project` to initialize the current directory with an Appwrite project."); + throw new Error("Project is not set. Please run `appwrite init` to initialize the current directory with an Appwrite project."); } client diff --git a/lib/spinner.js b/lib/spinner.js new file mode 100644 index 0000000..2f5b3ad --- /dev/null +++ b/lib/spinner.js @@ -0,0 +1,103 @@ +const progress = require('cli-progress'); +const chalk = require('chalk'); + +const SPINNER_ARC = 'arc'; +const SPINNER_DOTS = 'dots'; + +const spinners = { + [SPINNER_ARC]: { + "interval": 100, + "frames": ["◜", "◠", "◝", "◞", "◡", "◟"] + }, + [SPINNER_DOTS]: { + "interval": 80, + "frames": ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"] + } +} + +class Spinner { + static start(clearOnComplete = true, hideCursor = true) { + Spinner.updatesBar = new progress.MultiBar({ + format: this.#formatter, + hideCursor, + clearOnComplete, + stopOnComplete: true, + noTTYOutput: true + }); + } + + static stop() { + Spinner.updatesBar.stop(); + } + + static #formatter(options, params, payload) { + 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); + + if (status.toLowerCase().trim() === 'pushed') { + start = chalk.greenBright.bold(status); + prefix = chalk.greenBright.bold('✓'); + end = ''; + } else if (status.toLowerCase().trim() === 'deploying') { + start = chalk.cyanBright.bold(status); + } else if (status.toLowerCase().trim() === 'deployed') { + start = chalk.green.bold(status); + prefix = chalk.green.bold('✓'); + } else if (status.toLowerCase().trim() === 'error') { + start = chalk.red.bold(status); + prefix = chalk.red.bold('✗'); + end = chalk.red(payload.errorMessage); + } + + return Spinner.#line(prefix, start, middle, end); + } + + static #line(prefix, start, middle, end, separator = '•') { + return `${prefix} ${start} ${separator} ${middle} ${!end ? '' : separator} ${end}`; + + } + + constructor(payload, total = 100, startValue = 0) { + this.bar = Spinner.updatesBar.create(total, startValue, payload) + } + + update(payload) { + this.bar.update(payload); + return this; + } + + fail(payload) { + this.stopSpinner(); + this.update({ status: 'Error', ...payload }); + } + + startSpinner(name) { + let spinnerFrame = 1; + const spinner = spinners[name] ?? spinners['dots']; + + this.spinnerInterval = setInterval(() => { + if (spinnerFrame === spinner.frames.length) spinnerFrame = 1; + this.bar.update({ prefix: spinner.frames[spinnerFrame++] }); + }, spinner.interval); + } + + stopSpinner() { + clearInterval(this.spinnerInterval); + } + + replaceSpinner(name) { + this.stopSpinner(); + this.startSpinner(name); + } +} + + +module.exports = { + Spinner, + SPINNER_ARC, + SPINNER_DOTS +} diff --git a/lib/utils.js b/lib/utils.js index bc06aaf..a2cf3e3 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -1,9 +1,13 @@ const fs = require("fs"); const path = require("path"); +const net = require("net"); +const childProcess = require('child_process'); +const { localConfig, globalConfig } = require("./config"); +const { success } = require('./parser') function getAllFiles(folder) { const files = []; - for(const pathDir of fs.readdirSync(folder)) { + for (const pathDir of fs.readdirSync(folder)) { const pathAbsolute = path.join(folder, pathDir); if (fs.statSync(pathAbsolute).isDirectory()) { files.push(...getAllFiles(pathAbsolute)); @@ -14,13 +18,247 @@ 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) + }) + .once('listening', function() { + tester.once('close', function() { res(false) }) + .close() + }) + .listen(port); + }); + + return taken; +} + +function systemHasCommand(command) { + const isUsingWindows = process.platform == 'win32' + + try { + if(isUsingWindows) { + childProcess.execSync('where ' + command, { stdio: 'pipe' }) + } else { + childProcess.execSync(`[[ $(${command} --version) ]] || { exit 1; } && echo "OK"`, { stdio: 'pipe', shell: '/bin/bash' }); + } + } catch (error) { + console.log(error); + return false; + } + + return true; +} + const checkDeployConditions = (localConfig) => { if (Object.keys(localConfig.data).length === 0) { - throw new Error("No appwrite.json file found in the current directory. This command must be run in the folder holding your appwrite.json file. Please run this command again in the folder containing your appwrite.json file, or run appwrite init project."); + throw new Error("No appwrite.json file found in the current directory. Please run this command again in the folder containing your appwrite.json file, or run 'appwrite init project' to link current directory to an Appwrite project."); + } +} + +function showConsoleLink(serviceName, action, ...ids) { + const projectId = localConfig.getProject().projectId; + + const url = new URL(globalConfig.getEndpoint().replace('/v1', '/console')); + url.pathname += `/project-${projectId}`; + action = action.toLowerCase(); + + switch (serviceName) { + case "account": + url.pathname = url.pathname.replace(`/project-${projectId}`, ''); + url.pathname += getAccountPath(action); + break; + case "databases": + url.pathname += getDatabasePath(action, ids); + break; + case "functions": + url.pathname += getFunctionsPath(action, ids); + break; + case "messaging": + url.pathname += getMessagingPath(action, ids); + break; + case "projects": + url.pathname = url.pathname.replace(`/project-${projectId}`, ''); + url.pathname += getProjectsPath(action, ids); + break; + case "storage": + url.pathname += getBucketsPath(action, ids); + break; + case "teams": + url.pathname += getTeamsPath(action, ids); + break; + case "users": + url.pathname += getUsersPath(action, ids); + break; + default: + return; + } + + + success(url); +} + +function getAccountPath(action) { + let path = '/account'; + + if (action === 'listsessions') { + path += '/sessions'; + } + + return path; +} + +function getDatabasePath(action, ids) { + let path = '/databases'; + + + if (['get', 'listcollections', 'getcollection', 'listattributes', 'listdocuments', 'getdocument', 'listindexes', 'getdatabaseusage'].includes(action)) { + path += `/database-${ids[0]}`; + } + + if (action === 'getdatabaseusage') { + path += `/usage`; + } + + if (['getcollection', 'listattributes', 'listdocuments', 'getdocument', 'listindexes'].includes(action)) { + path += `/collection-${ids[1]}`; + } + + if (action === 'listattributes') { + path += '/attributes'; + } + if (action === 'listindexes') { + path += '/indexes'; + } + if (action === 'getdocument') { + path += `/document-${ids[2]}`; + } + + + return path; +} + +function getFunctionsPath(action, ids) { + let path = '/functions'; + + if (action !== 'list') { + path += `/function-${ids[0]}`; + } + + if (action === 'getdeployment') { + path += `/deployment-${ids[1]}` + } + + if (action === 'getexecution' || action === 'listexecution') { + path += `/executions` + } + if (action === 'getfunctionusage') { + path += `/usage` + } + + return path; +} + +function getMessagingPath(action, ids) { + let path = '/messaging'; + + if (['getmessage', 'listmessagelogs'].includes(action)) { + path += `/message-${ids[0]}`; + } + + if (['listproviders', 'getprovider'].includes(action)) { + path += `/providers`; + } + + if (action === 'getprovider') { + path += `/provider-${ids[0]}`; + } + + if (['listtopics', 'gettopic'].includes(action)) { + path += `/topics`; + } + + if (action === 'gettopic') { + path += `/topic-${ids[0]}`; } + + return path; +} + +function getProjectsPath(action, ids) { + let path = ''; + + if (action !== 'list') { + path += `/project-${ids[0]}`; + } + + if (['listkeys', 'getkey'].includes(action)) { + path += '/overview/keys' + } + + if (['listplatforms', 'getplatform'].includes(action)) { + path += '/overview/platforms' + } + + if (['listwebhooks', 'getwebhook'].includes(action)) { + path += '/settings/webhooks' + } + + if (['getplatform', 'getkey', 'getwebhook'].includes(action)) { + path += `/${ids[1]}`; + } + + return path; +} + +function getBucketsPath(action, ids) { + let path = '/storage'; + + if (action !== 'listbuckets') { + path += `/bucket-${ids[0]}`; + } + + if (action === 'getbucketusage') { + path += `/usage` + } + + if (action === 'getfile') { + path += `/file-${ids[1]}` + } + + return path; +} + +function getTeamsPath(action, ids) { + let path = '/auth/teams'; + + if (action !== 'list') { + path += `/team-${ids[0]}`; + } + + return path; +} + +function getUsersPath(action, ids) { + let path = '/auth'; + + if (action !== 'list') { + path += `/user-${ids[0]}`; + } + + if (action === 'listsessions') { + path += 'sessions'; + } + + return path; } module.exports = { getAllFiles, - checkDeployConditions -}; \ No newline at end of file + isPortTaken, + systemHasCommand, + checkDeployConditions, + showConsoleLink +}; diff --git a/lib/validations.js b/lib/validations.js new file mode 100644 index 0000000..bfae5ba --- /dev/null +++ b/lib/validations.js @@ -0,0 +1,17 @@ +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/package.json b/package.json index 7a87f62..ec468d1 100644 --- a/package.json +++ b/package.json @@ -24,13 +24,17 @@ "dependencies": { "undici": "^5.28.2", "chalk": "4.1.2", + "cli-progress": "^3.12.0", "cli-table3": "^0.6.2", "commander": "^9.2.0", "form-data": "^4.0.0", "json-bigint": "^1.0.0", "inquirer": "^8.2.4", + "inquirer-search-list": "^1.2.6", "tar": "^6.1.11", - "ignore": "^5.2.0" + "ignore": "^5.2.0", + "chokidar": "^3.6.0", + "tail": "^2.2.6" }, "devDependencies": { "pkg": "5.8.1"