Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

Switch the CLI to using yargs (#2250)

Ivan Starkov84db426a5750
diff --git a/packages/cli/bin.js b/packages/cli/bin.js
deleted file mode 100755
index daa3da9f5f..0000000000
--- a/packages/cli/bin.js
+++ /dev/null
@@ -1,11 +0,0 @@
-#!/usr/bin/env node --experimental-specifier-resolution=node --no-warnings
-/* eslint-disable-next-line */
-import { main } from "./lib/cli";
-
-try {
- await main();
- process.exit(0);
-} catch (error) {
- console.error(error);
- process.exit(1);
-}
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 9652e8443b..b0deb4a695 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -6,7 +6,7 @@
"homepage": "https://webstudio.is",
"type": "module",
"bin": {
- "webstudio": "./bin.js"
+ "webstudio": "./lib/bin.js"
},
"files": [
"lib/*",
@@ -19,7 +19,8 @@
"typecheck": "tsc",
"checks": "pnpm typecheck",
"build:templates": "tsx ./templates/build.ts",
- "build": "build-package"
+ "build": "rm -rf ./lib && esbuild ./src/**/*.ts --outdir=./lib",
+ "local-run": "tsx --no-warnings ./src/bin.ts"
},
"license": "AGPL-3.0-or-later",
"dependencies": {
@@ -33,13 +34,15 @@
"env-paths": "^3.0.0",
"ora": "^7.0.1",
"p-limit": "^4.0.0",
- "strip-indent": "^4.0.0"
+ "strip-indent": "^4.0.0",
+ "yargs": "^17.7.2"
},
"devDependencies": {
"@types/node": "^18.13.0",
"@webstudio-is/form-handlers": "workspace:^",
"@webstudio-is/scripts": "workspace:^",
"@webstudio-is/tsconfig": "workspace:^",
+ "esbuild": "^0.18.18",
"tsx": "^3.12.6",
"typescript": "5.2.2"
}
diff --git a/packages/cli/src/args.ts b/packages/cli/src/args.ts
index 6d4a0ecb86..6aa3c16f6a 100644
--- a/packages/cli/src/args.ts
+++ b/packages/cli/src/args.ts
@@ -1,58 +1,3 @@
-import { parseArgs } from "node:util";
-import stripIndent from "strip-indent";
-
-export const showHelp = () =>
- console.info(
- stripIndent(`
- Usage:
- $ webstudio commands [flags...]
-
- Commands:
- link Link to an existing webstudio project
- sync Sync the linked webstudio project with the latest build
- build Build the linked webstudio project with a remix template.
-
- Flags:
- --help -h Show this help message
- --version -v Show the version of this script
-`)
- );
-
-type DefaultArgs = Pick<
- ReturnType<
- typeof parseArgs<{
- options: typeof CLI_ARGS_OPTIONS;
- }>
- >,
- "values"
->;
-
-type Commands = "link" | "sync" | "build";
-
-export type Command = (
- args: DefaultArgs & { positionals: string[] }
-) => Promise<void>;
-
-export type SupportedCommands = {
- [key in Commands]: Command;
-} & { [key: string]: Command };
-
-export const CLI_ARGS_OPTIONS = {
- version: {
- type: "boolean" as const,
- short: "v",
- },
- help: {
- type: "boolean" as const,
- short: "h",
- },
- type: {
- type: "string" as const,
- short: "t",
- default: "defaults",
- },
-};
-
export type File = {
name: string;
content: string;
diff --git a/packages/cli/src/bin.ts b/packages/cli/src/bin.ts
new file mode 100644
index 0000000000..435506e3bc
--- /dev/null
+++ b/packages/cli/src/bin.ts
@@ -0,0 +1,5 @@
+#!/usr/bin/env node --experimental-specifier-resolution=node --no-warnings
+// pnpm tsx --no-warnings ./src/bin.ts
+import { main } from "./cli";
+
+await main();
diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts
index 8f2d450b29..c38eb80a57 100644
--- a/packages/cli/src/cli.ts
+++ b/packages/cli/src/cli.ts
@@ -1,50 +1,55 @@
-import { parseArgs } from "node:util";
import { exit, argv } from "node:process";
+// eslint-disable-next-line import/no-internal-modules
+import { hideBin } from "yargs/helpers";
import { GLOBAL_CONFIG_FILE } from "./config";
import { ensureFileInPath } from "./fs-utils";
import { link } from "./commands/link";
import { sync } from "./commands/sync";
-import { build } from "./commands/build";
-import { showHelp, CLI_ARGS_OPTIONS } from "./args";
-import type { SupportedCommands } from "./args";
-import packageJSON from "../package.json" assert { type: "json" };
-
-const commands: SupportedCommands = {
- link,
- sync,
- build,
-};
+import { build, buildOptions } from "./commands/build";
+import makeCLI from "yargs";
+import packageJson from "../package.json" assert { type: "json" };
+import type { CommonYargsArgv } from "./commands/yargs-types";
export const main = async () => {
try {
await ensureFileInPath(GLOBAL_CONFIG_FILE, "{}");
- const args = parseArgs({
- args: argv.slice(2),
- options: CLI_ARGS_OPTIONS,
- allowPositionals: true,
- });
+ const cmd: CommonYargsArgv = makeCLI(hideBin(argv))
+ .strict()
+ .fail(function (msg, err, yargs) {
+ if (err) {
+ throw err; // preserve stack
+ }
+ // eslint-disable-next-line no-console
+ console.error(msg);
+ // eslint-disable-next-line no-console
+ console.error(yargs.help());
- if (args.values?.version) {
- console.info(packageJSON.version);
- return;
- }
+ process.exit(1);
+ })
+ .wrap(null)
+ .option("v", {
+ describe: "Show version number",
+ alias: "version",
+ type: "boolean",
+ })
+ .option("h", {
+ describe: "Show version number",
+ alias: "help",
+ type: "boolean",
+ })
+ .scriptName("webstudio")
+ .demandCommand(1, "Command is required");
- if (args.values?.help) {
- showHelp();
- return;
- }
+ cmd.version(packageJson.version).alias("v", "version");
- const commandId = argv[2];
- const command = commands[commandId];
- if (command === undefined) {
- throw new Error(`No command provided`);
- }
+ cmd.command(["build"], "build the project", buildOptions, build);
+ cmd.command(["link"], "link the project from your workspace", {}, link);
+ cmd.command(["sync"], "sync your project", {}, sync);
- await command({ ...args, positionals: args.positionals.slice(1) });
+ await cmd.parse();
} catch (error) {
console.error(error);
- showHelp();
exit(1);
}
};
diff --git a/packages/cli/src/commands/build.ts b/packages/cli/src/commands/build.ts
index 6b63279138..b9c8ecb735 100644
--- a/packages/cli/src/commands/build.ts
+++ b/packages/cli/src/commands/build.ts
@@ -1,18 +1,33 @@
import { access } from "node:fs/promises";
-import type { Command } from "../args";
import { prebuild } from "../prebuild";
import { LOCAL_DATA_FILE } from "../config";
+import type {
+ CommonYargsArgv,
+ StrictYargsOptionsToInterface,
+} from "./yargs-types";
-export const build: Command = async () => {
+export const buildOptions = (yargs: CommonYargsArgv) =>
+ yargs.option("assets", {
+ type: "boolean",
+ default: true,
+ describe: "Download assets",
+ });
+
+// @todo: use options.assets to define if we need to download assets
+export const build = async (
+ options: StrictYargsOptionsToInterface<typeof buildOptions>
+) => {
try {
await access(LOCAL_DATA_FILE);
- await prebuild();
} catch (error: unknown) {
- if (error instanceof Error && "code" in error && error.code === "ENONET") {
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") {
throw new Error(
`You need to link a webstudio project before building it. Run \`webstudio link\` to link a project.`
);
}
+
throw error;
}
+
+ await prebuild();
};
diff --git a/packages/cli/src/commands/link.ts b/packages/cli/src/commands/link.ts
index 9de5be2dff..ddbc0c77a1 100644
--- a/packages/cli/src/commands/link.ts
+++ b/packages/cli/src/commands/link.ts
@@ -3,10 +3,9 @@ import { join } from "node:path";
import * as readline from "node:readline/promises";
import { readFile, writeFile } from "node:fs/promises";
import { GLOBAL_CONFIG_FILE, LOCAL_CONFIG_FILE } from "../config";
-import type { Command } from "../args";
import { ensureFileInPath } from "../fs-utils";
-export const link: Command = async () => {
+export const link = async () => {
const rl = readline.createInterface({ input: stdin, output: stdout });
const shareLink = await rl.question(`Paste share link (with build access): `);
diff --git a/packages/cli/src/commands/sync.ts b/packages/cli/src/commands/sync.ts
index d4c8eb7cc3..1e476139bb 100644
--- a/packages/cli/src/commands/sync.ts
+++ b/packages/cli/src/commands/sync.ts
@@ -4,7 +4,6 @@ import { join } from "node:path";
import ora from "ora";
import { loadProjectDataById } from "@webstudio-is/http-client";
-import type { Command } from "../args";
import { ensureFileInPath, loadJSONFile } from "../fs-utils";
import {
GLOBAL_CONFIG_FILE,
@@ -14,7 +13,7 @@ import {
LOCAL_DATA_FILE,
} from "../config";
-export const sync: Command = async () => {
+export const sync = async () => {
const spinner = ora("Syncing project data").start();
spinner.text = "Loading project data from config file";
diff --git a/packages/cli/src/commands/yargs-types.ts b/packages/cli/src/commands/yargs-types.ts
new file mode 100644
index 0000000000..04683d6817
--- /dev/null
+++ b/packages/cli/src/commands/yargs-types.ts
@@ -0,0 +1,65 @@
+/*
+https://github.com/cloudflare/workers-sdk/blob/975cbd9b949a1685856e16b4f88400fc04dca38c/packages/wrangler/src/yargs-types.ts#L7
+
+Copyright (c) 2020 Cloudflare, Inc. <[email protected]>
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+*/
+
+import type { ArgumentsCamelCase, Argv } from "yargs";
+
+/**
+ * Yargs options included in every wrangler command.
+ */
+export interface CommonYargsOptions {
+ v: boolean | undefined;
+ h: boolean | undefined;
+ // t: string | undefined;
+}
+
+export type CommonYargsArgv = Argv<CommonYargsOptions>;
+
+export type YargvToInterface<T> = T extends Argv<infer P>
+ ? ArgumentsCamelCase<P>
+ : never;
+
+// See http://stackoverflow.com/questions/51465182/how-to-remove-index-signature-using-mapped-types
+type RemoveIndex<T> = {
+ [K in keyof T as string extends K
+ ? never
+ : number extends K
+ ? never
+ : K]: T[K];
+};
+
+/**
+ * Given some Yargs Options function factory, extract the interface
+ * that corresponds to the yargs arguments, remove index types, and only allow camelCase
+ */
+export type StrictYargsOptionsToInterface<
+ T extends (yargs: CommonYargsArgv) => Argv,
+> = T extends (yargs: CommonYargsArgv) => Argv<infer P>
+ ? RemoveIndex<ArgumentsCamelCase<P>>
+ : never;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 2e83aa3fe2..319ddb23c7 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -483,6 +483,9 @@ importers:
strip-indent:
specifier: ^4.0.0
version: 4.0.0
+ yargs:
+ specifier: ^17.7.2
+ version: 17.7.2
devDependencies:
'@types/node':
specifier: ^18.13.0
@@ -496,6 +499,9 @@ importers:
'@webstudio-is/tsconfig':
specifier: workspace:^
version: link:../tsconfig
+ esbuild:
+ specifier: ^0.18.18
+ version: 0.18.18
tsx:
specifier: ^3.12.6
version: 3.12.6
@@ -6260,7 +6266,7 @@ packages:
'@sentry/utils': 7.47.0
react: 18.2.0
tslib: 1.14.1
- yargs: 17.7.1
+ yargs: 17.7.2
transitivePeerDependencies:
- encoding
- supports-color
@@ -11508,7 +11514,7 @@ packages:
jest-util: 29.6.3
jest-validate: 29.6.3
prompts: 2.4.2
- yargs: 17.7.1
+ yargs: 17.7.2
transitivePeerDependencies:
- '@types/node'
- babel-plugin-macros
@@ -15782,7 +15788,7 @@ packages:
resolution: {integrity: sha512-DINP+5T3ruZwOWMNd5mJMiM3h5YvwZEoRL+NAKZf+e93/5Vy1P0R5eWeaynCWcqprPNm4ceV5CPgjqo1u48big==}
hasBin: true
dependencies:
- yargs: 17.7.1
+ yargs: 17.7.2
dev: false
@@ -16751,8 +16757,8 @@ packages:
y18n: 5.0.8
yargs-parser: 20.2.9
- resolution: {integrity: sha512-cwiTb08Xuv5fqF4AovYacTFNxk62th7LKJ6BL9IGUpTJrWoU7/7WdQGTP2SjKf1dUNBGzDd28p/Yfs/GI6JrLw==}
+ resolution: {integrity: sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==}
engines: {node: '>=12'}
dependencies:
cliui: 8.0.1