@webiny/cli 0.0.0-ee-vpcs.549378cf03

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Webiny
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,7 @@
1
+ # webiny-cli
2
+ [![](https://img.shields.io/npm/dw/webiny-cli.svg)](https://www.npmjs.com/package/webiny-cli)
3
+ [![](https://img.shields.io/npm/v/webiny-cli.svg)](https://www.npmjs.com/package/webiny-cli)
4
+ [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)
5
+ [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com)
6
+
7
+ A pluggable tool to run commands within a Webiny project.
package/bin.js ADDED
@@ -0,0 +1,38 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ const chalk = require("chalk");
5
+ const execa = require("execa");
6
+ const semver = require("semver");
7
+ const currentNodeVersion = process.versions.node;
8
+
9
+ (async () => {
10
+ if (!semver.satisfies(currentNodeVersion, ">=14")) {
11
+ console.error(
12
+ chalk.red(
13
+ [
14
+ `You are running Node.js ${currentNodeVersion}, but Webiny requires version 14 or higher.`,
15
+ `Please switch to one of the required versions and try again.`,
16
+ `For more information, please visit https://docs.webiny.com/docs/tutorials/install-webiny#prerequisites.`
17
+ ].join(" ")
18
+ )
19
+ );
20
+ process.exit(1);
21
+ }
22
+
23
+ try {
24
+ const { stdout } = await execa("yarn", ["--version"]);
25
+ if (!semver.satisfies(stdout, ">=2")) {
26
+ console.error(chalk.red(`"@webiny/cli" requires yarn >=2!`));
27
+ process.exit(1);
28
+ }
29
+ } catch (err) {
30
+ console.error(chalk.red(`"@webiny/cli" requires yarn >=2!`));
31
+ console.log(
32
+ `Run ${chalk.blue("yarn set version berry")} to install a compatible version of yarn.`
33
+ );
34
+ process.exit(1);
35
+ }
36
+
37
+ require("./cli");
38
+ })();
package/cli.js ADDED
@@ -0,0 +1,86 @@
1
+ #!/usr/bin/env node
2
+ const yargs = require("yargs");
3
+
4
+ // Disable help processing until after plugins are imported.
5
+ yargs.help(false);
6
+
7
+ // Loads environment variables from multiple sources.
8
+ require("./utils/loadEnvVariables");
9
+
10
+ const { blue, red } = require("chalk");
11
+ const context = require("./context");
12
+ const { createCommands } = require("./commands");
13
+
14
+ yargs
15
+ .usage("Usage: $0 <command> [options]")
16
+ .demandCommand(1)
17
+ .recommendCommands()
18
+ .scriptName("webiny")
19
+ .epilogue(
20
+ `To find more information, docs and tutorials, see ${blue("https://www.webiny.com/docs")}.`
21
+ )
22
+ .epilogue(`Want to contribute? ${blue("https://github.com/webiny/webiny-js")}.`)
23
+ .fail(function (msg, error, yargs) {
24
+ if (msg) {
25
+ if (msg.includes("Not enough non-option arguments")) {
26
+ console.log();
27
+ context.error(red("Command was not invoked as expected!"));
28
+ context.info(
29
+ `Some non-optional arguments are missing. See the usage examples printed below.`
30
+ );
31
+ console.log();
32
+ yargs.showHelp();
33
+ return;
34
+ }
35
+
36
+ if (msg.includes("Missing required argument")) {
37
+ const args = msg
38
+ .split(":")[1]
39
+ .split(",")
40
+ .map(v => v.trim());
41
+
42
+ console.log();
43
+ context.error(red("Command was not invoked as expected!"));
44
+ context.info(
45
+ `Missing required argument(s): ${args
46
+ .map(arg => red(arg))
47
+ .join(", ")}. See the usage examples printed below.`
48
+ );
49
+ console.log();
50
+ yargs.showHelp();
51
+ return;
52
+ }
53
+ console.log();
54
+ context.error(red("Command execution was aborted!"));
55
+ context.error(msg);
56
+ console.log();
57
+
58
+ process.exit(1);
59
+ }
60
+
61
+ if (error) {
62
+ context.error(error.message);
63
+ // Unfortunately, yargs doesn't provide passed args here, so we had to do it via process.argv.
64
+ if (process.argv.includes("--debug")) {
65
+ context.debug(error);
66
+ }
67
+
68
+ console.log();
69
+ const plugins = context.plugins.byType("cli-command-error");
70
+ for (let i = 0; i < plugins.length; i++) {
71
+ const plugin = plugins[i];
72
+ plugin.handle({
73
+ error,
74
+ context
75
+ });
76
+ }
77
+ }
78
+
79
+ process.exit(1);
80
+ });
81
+
82
+ (async () => {
83
+ await createCommands(yargs, context);
84
+ // Enable help and run the CLI.
85
+ yargs.help().argv;
86
+ })();
@@ -0,0 +1,20 @@
1
+ const run = require("./run");
2
+ const telemetry = require("./telemetry");
3
+ const upgrade = require("./upgrade");
4
+
5
+ module.exports.createCommands = async (yargs, context) => {
6
+ context.plugins.register(run, telemetry, upgrade);
7
+
8
+ try {
9
+ const wcp = require("./wcp");
10
+ context.plugins.register(wcp);
11
+ } catch {
12
+ // Skip WCP command
13
+ }
14
+
15
+ await context.loadUserPlugins();
16
+
17
+ context.plugins.byType("cli-command").forEach(plugin => {
18
+ plugin.create({ yargs, context });
19
+ });
20
+ };
@@ -0,0 +1,38 @@
1
+ const camelCase = require("camelcase");
2
+ const findUp = require("find-up");
3
+ const path = require("path");
4
+
5
+ module.exports = {
6
+ type: "cli-command",
7
+ name: "cli-command-run",
8
+ create({ yargs, context }) {
9
+ yargs.command(
10
+ "run <command> [options]",
11
+ `Run command defined in webiny.config.{js,ts}.\nNote: run from folder containing webiny.config.{js,ts} file.`,
12
+ yargs => {
13
+ yargs.positional("command", {
14
+ describe: `Command to run in webiny.config.{js,ts}`,
15
+ type: "string"
16
+ });
17
+ },
18
+ async argv => {
19
+ const configFile = findUp.sync(["webiny.config.ts", "webiny.config.js"]);
20
+ let config = context.import(configFile);
21
+
22
+ const command = camelCase(argv.command);
23
+ if (typeof config === "function") {
24
+ config = config({
25
+ options: { ...argv, cwd: path.dirname(configFile) },
26
+ context
27
+ });
28
+ }
29
+
30
+ if (config.commands && typeof config.commands[command] === "function") {
31
+ return await config.commands[command]({ ...argv }, context);
32
+ }
33
+
34
+ throw Error(`Command "${command}" is not defined in "${configFile}"!`);
35
+ }
36
+ );
37
+ }
38
+ };
@@ -0,0 +1,31 @@
1
+ const telemetry = require("@webiny/telemetry/cli");
2
+
3
+ module.exports = {
4
+ type: "cli-command",
5
+ name: "cli-command-telemetry",
6
+ create({ yargs, context }) {
7
+ yargs.command("enable-telemetry", "Enable anonymous telemetry.", async () => {
8
+ telemetry.enable();
9
+ await telemetry.sendEvent({ event: "enable-telemetry" });
10
+ context.info(
11
+ `Webiny telemetry is now ${context.info.hl(
12
+ "enabled"
13
+ )}! Thank you for helping us in making Webiny better!`
14
+ );
15
+ context.info(
16
+ `For more information, please visit the following link: https://www.webiny.com/telemetry.`
17
+ );
18
+ });
19
+
20
+ yargs.command("disable-telemetry", "Disable anonymous telemetry.", async () => {
21
+ await telemetry.sendEvent({ event: "disable-telemetry" });
22
+ telemetry.disable();
23
+ context.info(`Webiny telemetry is now ${context.info.hl("disabled")}!`);
24
+ context.info(
25
+ `Note that, in order to complete the process, you will also need to re-deploy your project, using the ${context.info.hl(
26
+ "yarn webiny deploy"
27
+ )} command.`
28
+ );
29
+ });
30
+ }
31
+ };
@@ -0,0 +1,107 @@
1
+ const { red } = require("chalk");
2
+ const execa = require("execa");
3
+ const semver = require("semver");
4
+
5
+ module.exports = [
6
+ {
7
+ type: "cli-command",
8
+ name: "cli-command-upgrade",
9
+ create({ yargs, context }) {
10
+ yargs.example("$0 upgrade");
11
+ yargs.command(
12
+ "upgrade",
13
+ `Run an upgrade script for currently installed version of Webiny`,
14
+ yargs => {
15
+ yargs.option("skip-checks", {
16
+ describe: "Do not perform CLI version and Git tree checks.",
17
+ type: "boolean",
18
+ default: false
19
+ });
20
+ yargs.option("debug", {
21
+ default: false,
22
+ describe: `Turn on debug logs`,
23
+ type: "boolean"
24
+ });
25
+ yargs.option("use-version", {
26
+ describe:
27
+ "Use upgrade script for a specific version. Should only be used for development/testing purposes.",
28
+ type: "string"
29
+ });
30
+ },
31
+ async argv => {
32
+ if (!argv.skipChecks) {
33
+ // Before doing any upgrading, there must not be any active changes in the current branch.
34
+ let gitStatus = "";
35
+ try {
36
+ let { stdout } = execa.sync("git", ["status", "--porcelain"]);
37
+ gitStatus = stdout.trim();
38
+ } catch {}
39
+
40
+ if (gitStatus) {
41
+ console.error(
42
+ red(
43
+ "This git repository has untracked files or uncommitted changes:"
44
+ ) +
45
+ "\n\n" +
46
+ gitStatus
47
+ .split("\n")
48
+ .map(line => line.match(/ .*/g)[0].trim())
49
+ .join("\n") +
50
+ "\n\n" +
51
+ red(
52
+ "Remove untracked files, stash or commit any changes, and try again."
53
+ )
54
+ );
55
+ process.exit(1);
56
+ }
57
+ }
58
+
59
+ const defaultUpgradeTargetVersion = semver.coerce(context.version).version;
60
+
61
+ const command = [
62
+ "https://github.com/webiny/webiny-upgrades",
63
+ argv.useVersion || defaultUpgradeTargetVersion
64
+ ];
65
+
66
+ if (yargs.argv.debug) {
67
+ context.debug("npx", ...command);
68
+ }
69
+
70
+ const npx = execa("npx", command, {
71
+ env: {
72
+ FORCE_COLOR: true
73
+ }
74
+ });
75
+
76
+ npx.stdout.on("data", data => {
77
+ const lines = data.toString().replace(/\n$/, "").split("\n");
78
+ for (let i = 0; i < lines.length; i++) {
79
+ const line = lines[i];
80
+ try {
81
+ const json = JSON.parse(line);
82
+ if (json.type === "error") {
83
+ context.error(
84
+ "An error occurred while performing the upgrade."
85
+ );
86
+ console.log(json.message);
87
+ if (yargs.argv.debug) {
88
+ context.debug(json.data.stack);
89
+ }
90
+ }
91
+ } catch {
92
+ // Not JSON, let's just print the line then.
93
+ console.log(line);
94
+ }
95
+ }
96
+ });
97
+
98
+ npx.stderr.on("data", data => {
99
+ console.log(data.toString());
100
+ });
101
+
102
+ await npx;
103
+ }
104
+ );
105
+ }
106
+ }
107
+ ];
@@ -0,0 +1,133 @@
1
+ const { encrypt, decrypt } = require("@webiny/wcp");
2
+ const { getUser, getProjectEnvironment, updateUserLastActiveOn } = require("./utils");
3
+
4
+ /**
5
+ * The two environment variables we set via these hooks are the following:
6
+ * - WCP_PROJECT_ENVIRONMENT - contains encrypted data about the deployed project environment
7
+ * - WCP_PROJECT_ENVIRONMENT_API_KEY - for easier access, we also set the API key
8
+ */
9
+
10
+ /**
11
+ * There are multiple ways the hooks below prepare the WCP-enabled project for deployment.
12
+ * 1. If `WCP_PROJECT_ENVIRONMENT` metadata env var is defined, we decrypt it, retrieve the
13
+ * API key from it, and assign it as the `WCP_PROJECT_ENVIRONMENT_API_KEY` env var.
14
+ * 2. If `WCP_PROJECT_ENVIRONMENT_API_KEY` env var is defined, then we use that as the
15
+ * project environment API key. We use that to load the project environment data
16
+ * and to also assign the `WCP_PROJECT_ENVIRONMENT` metadata env var.
17
+ * 3. If none of the above is defined, we retrieve (or create) the project environment,
18
+ * retrieve its API key and again assign it as `WCP_PROJECT_ENVIRONMENT_API_KEY` env var.
19
+ * As in 2), we also assign the `WCP_PROJECT_ENVIRONMENT` metadata env var.
20
+ */
21
+
22
+ let projectEnvironment;
23
+
24
+ const getEnvironmentHookHandler = async (args, context) => {
25
+ // If the project isn't linked with WCP, do nothing.
26
+ const wcpProjectId = context.project.config.id || process.env.WCP_PROJECT_ID;
27
+ if (!wcpProjectId) {
28
+ return;
29
+ }
30
+
31
+ // For development purposes, we allow setting the WCP_PROJECT_ENVIRONMENT env var directly.
32
+ if (process.env.WCP_PROJECT_ENVIRONMENT) {
33
+ // If we have WCP_PROJECT_ENVIRONMENT env var, we set the WCP_PROJECT_ENVIRONMENT_API_KEY too.
34
+ const decryptedProjectEnvironment = decrypt(process.env.WCP_PROJECT_ENVIRONMENT);
35
+ process.env.WCP_PROJECT_ENVIRONMENT_API_KEY = decryptedProjectEnvironment.apiKey;
36
+ return;
37
+ }
38
+
39
+ // The `id` has the orgId/projectId structure, for example `my-org-x/my-project-y`.
40
+ const [orgId, projectId] = wcpProjectId.split("/");
41
+
42
+ const apiKey = process.env.WCP_PROJECT_ENVIRONMENT_API_KEY;
43
+
44
+ let projectEnvironment;
45
+ if (apiKey) {
46
+ projectEnvironment = await getProjectEnvironment({ apiKey });
47
+ } else {
48
+ const isValidId = orgId && projectId;
49
+ if (!isValidId) {
50
+ throw new Error(
51
+ `It seems the project ID, specified in "webiny.project.ts" file, is invalid.`
52
+ );
53
+ }
54
+
55
+ // If there is no API key, that means we need to retrieve the currently logged-in user.
56
+ const user = await getUser();
57
+ const project = user.projects.find(item => item.id === projectId);
58
+ if (!project) {
59
+ throw new Error(
60
+ `It seems you don't belong to the current project or the current project has been deleted.`
61
+ );
62
+ }
63
+
64
+ projectEnvironment = await getProjectEnvironment({
65
+ orgId,
66
+ projectId,
67
+ userId: user.id,
68
+ environmentId: args.env
69
+ });
70
+ }
71
+
72
+ if (projectEnvironment.org.id !== orgId) {
73
+ throw new Error(
74
+ `Cannot proceed with the deployment because the "${projectEnvironment.name}" project environment doesn't belong to the "${orgId}" organization. Please check your WCP project ID (currently set to "${wcpProjectId}").`
75
+ );
76
+ }
77
+
78
+ if (projectEnvironment.project.id !== projectId) {
79
+ throw new Error(
80
+ `Cannot proceed with the deployment because the "${projectEnvironment.name}" project environment doesn't belong to the "${wcpProjectId}" project. Please check your WCP project ID (currently set to "${wcpProjectId}").`
81
+ );
82
+ }
83
+
84
+ if (projectEnvironment && projectEnvironment.status !== "enabled") {
85
+ throw new Error(
86
+ `Cannot proceed with the deployment because the "${projectEnvironment.name}" project environment has been disabled.`
87
+ );
88
+ }
89
+
90
+ // Assign `WCP_PROJECT_ENVIRONMENT` and `WCP_PROJECT_ENVIRONMENT_API_KEY`
91
+ const wcpProjectEnvironment = {
92
+ id: projectEnvironment.id,
93
+ apiKey: projectEnvironment.apiKey,
94
+ org: { id: projectEnvironment.org.id },
95
+ project: { id: projectEnvironment.project.id }
96
+ };
97
+
98
+ process.env.WCP_PROJECT_ENVIRONMENT = encrypt(wcpProjectEnvironment);
99
+ process.env.WCP_PROJECT_ENVIRONMENT_API_KEY = projectEnvironment.apiKey;
100
+ };
101
+
102
+ const updateLastActiveOnHookHandler = async () => {
103
+ if (!projectEnvironment) {
104
+ return;
105
+ }
106
+
107
+ // Is this a user environment? If so, let's update his "last active" field.
108
+ if (projectEnvironment.user) {
109
+ await updateUserLastActiveOn();
110
+ }
111
+ };
112
+
113
+ // Export hooks plugins for deploy and watch commands.
114
+ module.exports = () => [
115
+ // Deploy hook handlers.
116
+ {
117
+ type: "hook-before-deploy",
118
+ name: "hook-before-deploy-environment-get-environment",
119
+ hook: getEnvironmentHookHandler
120
+ },
121
+ {
122
+ type: "hook-before-deploy",
123
+ name: "hook-before-deploy-update-last-active-on",
124
+ hook: updateLastActiveOnHookHandler
125
+ },
126
+
127
+ // Watch hook handlers.
128
+ {
129
+ type: "hook-before-watch",
130
+ name: "hook-before-watch-environment-get-environment",
131
+ hook: getEnvironmentHookHandler
132
+ }
133
+ ];
@@ -0,0 +1,8 @@
1
+ const { command: login } = require("./login");
2
+ const { command: logout } = require("./logout");
3
+ const { command: whoami } = require("./whoami");
4
+ const { command: project } = require("./project");
5
+
6
+ const hooks = require("./hooks");
7
+
8
+ module.exports = [login(), logout(), whoami(), project(), hooks()];