From 7f11d57e810e26cbc789f79e5a34d0bbaad36e66 Mon Sep 17 00:00:00 2001 From: CristiCanizales Date: Fri, 16 Feb 2024 23:40:07 -0300 Subject: [PATCH] fix: remove lwc local dev server commands --- docs/_articles/en/localdev/lwclocaldev.md | 52 - .../en/localdev/set-up-lwc-local-dev.md | 18 - docs/_articles/ja/localdev/lwclocaldev.md | 43 - .../ja/localdev/set-up-lwc-local-dev.md | 18 - packages/salesforcedx-vscode-lwc/package.json | 79 +- .../package.nls.ja.json | 27 +- .../salesforcedx-vscode-lwc/package.nls.json | 29 +- .../src/commands/commandConstants.ts | 10 - .../src/commands/forceLightningLwcOpen.ts | 32 - .../src/commands/forceLightningLwcPreview.ts | 656 -------- .../src/commands/forceLightningLwcStart.ts | 251 --- .../src/commands/forceLightningLwcStop.ts | 42 - .../src/commands/index.ts | 5 - packages/salesforcedx-vscode-lwc/src/index.ts | 41 - .../src/messages/i18n.ja.ts | 67 - .../src/messages/i18n.ts | 66 - .../src/service/devServerService.ts | 74 - .../src/service/previewService.ts | 55 - .../commands/forceLightningLwcPreview.test.ts | 32 - .../unit/commands/commandConstants.test.ts | 18 - .../unit/service/devServerService.test.ts | 162 -- .../commands/commandUtils.test.ts | 84 - .../commands/forceLightningLwcOpen.test.ts | 58 - .../commands/forceLightningLwcPreview.test.ts | 1431 ----------------- .../commands/forceLightningLwcStart.test.ts | 420 ----- .../commands/forceLightningLwcStop.test.ts | 83 - 26 files changed, 24 insertions(+), 3829 deletions(-) delete mode 100644 docs/_articles/en/localdev/lwclocaldev.md delete mode 100644 docs/_articles/en/localdev/set-up-lwc-local-dev.md delete mode 100644 docs/_articles/ja/localdev/lwclocaldev.md delete mode 100644 docs/_articles/ja/localdev/set-up-lwc-local-dev.md delete mode 100644 packages/salesforcedx-vscode-lwc/src/commands/commandConstants.ts delete mode 100644 packages/salesforcedx-vscode-lwc/src/commands/forceLightningLwcOpen.ts delete mode 100644 packages/salesforcedx-vscode-lwc/src/commands/forceLightningLwcPreview.ts delete mode 100644 packages/salesforcedx-vscode-lwc/src/commands/forceLightningLwcStart.ts delete mode 100644 packages/salesforcedx-vscode-lwc/src/commands/forceLightningLwcStop.ts delete mode 100644 packages/salesforcedx-vscode-lwc/src/service/devServerService.ts delete mode 100644 packages/salesforcedx-vscode-lwc/src/service/previewService.ts delete mode 100644 packages/salesforcedx-vscode-lwc/test/jest/commands/forceLightningLwcPreview.test.ts delete mode 100644 packages/salesforcedx-vscode-lwc/test/unit/commands/commandConstants.test.ts delete mode 100644 packages/salesforcedx-vscode-lwc/test/unit/service/devServerService.test.ts delete mode 100644 packages/salesforcedx-vscode-lwc/test/vscode-integration/commands/commandUtils.test.ts delete mode 100644 packages/salesforcedx-vscode-lwc/test/vscode-integration/commands/forceLightningLwcOpen.test.ts delete mode 100644 packages/salesforcedx-vscode-lwc/test/vscode-integration/commands/forceLightningLwcPreview.test.ts delete mode 100644 packages/salesforcedx-vscode-lwc/test/vscode-integration/commands/forceLightningLwcStart.test.ts delete mode 100644 packages/salesforcedx-vscode-lwc/test/vscode-integration/commands/forceLightningLwcStop.test.ts diff --git a/docs/_articles/en/localdev/lwclocaldev.md b/docs/_articles/en/localdev/lwclocaldev.md deleted file mode 100644 index 38ff2e29f7..0000000000 --- a/docs/_articles/en/localdev/lwclocaldev.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -title: Local Development (Beta) -lang: en ---- - -The Local Development Server is a Salesforce CLI plug-in that configures and runs a Lightning Web Components-enabled server on your computer. You can develop Lightning web components and see live changes without publishing the components to an org. - -**Note**: This plugin does not support the following features: -- `@AuraEnabled` Apex methods -- `CSS` custom properties -- `LightningModal` -- `lwc:if`, `lwc:elseif`, and `lwc:else` directives -- multiple directories and `sfdx` multiple packages - - - -## Run Local Development Salesforce CLI Commands in VS Code - -The Local Development server uses the following Salesforce CLI commands. - -View the commands from VS Code's Command Palette by pressing `command` + `shift` + `p`. If you type "local development," all three commands are visible. - -![VS Code commands for Local Development](./images/vscode_localdev_sfdx_commands.png) - -**SFDX: Open Local Development Home** -If the Local Development server isn't currently running, this command starts the server and opens `localhost:3333` in your web browser. If the server is already running, then the command only opens `localhost:3333` in your browser. - -**SFDX: Start LWC Local Development Server** -This command starts the Local Development server. If you already started the server from VS Code, then VS Code gives the option to open it in the browser or restart it. If you already started the server from the command line, then VS code shows an error in the output console. - -> **Troubleshooting Tip:** If you see an error where the server can't start, it's possible that the port is already in use or a process is still running. If using VS Code, you can kill the process on the server port, by default, `3333`. If running the CLI in a terminal window, close the terminal and terminate any running processes. - -**SFDX: Stop LWC Local Development Server** -This command stops the Local Development server. - -**Preview Lightning Web Components in VS Code** -To preview Lightning web components, right-click any line of code in the component's HTML, CSS, or JavaScript files. You can also right-click any of the HTML, CSS, or JavaScript filenames or the component folder. - -Preview `c-hello` from the HTML code. -![Preview component from HTML.](./images/vscode_localdev_preview_html.png) - -Preview `c-hello` from the HTML file. -![Preview component from file.](./images/vscode_localdev_file_preview.png) - -After you select SFDX: Preview Component Locally, the Command Palette displays a list of preview options. You can choose to preview your component in the desktop browser or in a virtual mobile device (iOS or Android). Mobile previews require additional setup. See ["Set Up Your Dev Environment" in the Lightning Web Components Dev Guide.](https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.install_setup_develop) -![Choose to preview in the desktop browser, an Android emulator, or an iOS simulator.](./images/vscode_localdev_command_palette_preview_options.png) - -Here’s the previewed component on the local development server’s desktop browser. -![Previewed component in a browser.](./images/vscode_localdev_preview.png) - -Here's the previewed component on a virtual mobile device. -![Previewed component in a virtual mobile device.](./images/vscode_localdev_preview_ios.png) diff --git a/docs/_articles/en/localdev/set-up-lwc-local-dev.md b/docs/_articles/en/localdev/set-up-lwc-local-dev.md deleted file mode 100644 index 6b19601444..0000000000 --- a/docs/_articles/en/localdev/set-up-lwc-local-dev.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -title: Set Up LWC Local Development -lang: en ---- - -To set up LWC Local Development, install the server, enable and authorize a Dev Hub org, and create a scratch org. To use the LWC Local Development, you must develop Lightning web components in a Salesforce DX project. - -## Install the LWC Local Development Server - -Run this command from a command-line interface. - -``` -sfdx plugins:install @salesforce/lwc-dev-server -``` - -> **Troubleshooting Tip:** Due to a known issue, it's likely you'll see several errors when you install the plug-in. Run `sfdx plugins --core` to see if the plug-in is installed. If yes, try to start the Local Development server. If successful, you're good to proceed. - -After you select **SFDX: Preview Component Locally**, the Command Palette displays a list of preview options. You can choose to preview your component in the desktop browser or in a virtual mobile device (iOS or Android). Mobile previews require additional setup. See [Preview Lightning Web Components on Mobile](https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.mobile_extensions) in the _Lightning Web Components Dev Guide_. diff --git a/docs/_articles/ja/localdev/lwclocaldev.md b/docs/_articles/ja/localdev/lwclocaldev.md deleted file mode 100644 index dbbb443aaa..0000000000 --- a/docs/_articles/ja/localdev/lwclocaldev.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: ローカル開発 (ベータ) -lang: ja ---- - -ローカルの開発サーバは、コンピュータ上に Lightning Web コンポーネント対応のサーバを構成して実行する Salesforce CLI プラグインです。組織にコンポーネントをリリースすることなく、Lightning Web コンポーネントを開発し、ライブで変更を確認することができます。 - -## VS Code で ローカル開発の Salesforce CLI コマンドを実行する - -ローカルの開発サーバでは、以下の Salesforce CLI コマンドを使用します。 - -`command` + `shift` + `p` を押して VS Code のコマンドパレットから、コマンドを表示します。「local development」と入力すると、3 つのコマンドがすべて表示されます。 - -![VS Code のローカル開発用コマンド](./images/vscode_localdev_sfdx_commands.png) - -**SFDX: Open Local Development Home \(SFDX: ローカルの開発サーバを開く\)** -ローカルの開発サーバが現在起動していない場合、このコマンドはサーバを起動し、Web ブラウザで `localhost:3333` を開きます。サーバが既に起動している場合は、このコマンドは単にブラウザで `localhost:3333` を開きます。 - -**SFDX: Start Local Development Server \(SFDX: ローカルの開発サーバを起動\)** -このコマンドは、ローカルの開発サーバを起動します。VS Code から既にサーバを起動している場合は、VS Code はブラウザで開くか、再起動するかのオプションを提示します。既にコマンドラインからサーバを起動している場合は、VS Code の出力コンソールにエラーが表示されます。 - -> **トラブルシューティングのヒント:** サーバが起動できないエラーが表示された場合、ポートがすでに使用されているか、プロセスがまだ実行中である可能性があります。VS Code を使用している場合は、サーバのポート (デフォルトでは`3333`) のプロセスを強制終了させることができます。ターミナルウィンドウで CLI を実行している場合は、ターミナルを閉じて、実行中のプロセスを終了してください。 - -**SFDX: Stop LWC Local Development Server \(SFDX: ローカルの開発サーバを停止\)** -このコマンドは、ローカルの開発サーバを停止します。 - -**VS Code で Lightning Web コンポーネントをプレビューする** -Lightning Web コンポーネントをプレビューするには、コンポーネントの HTML、CSS、JavaScript ファイル内の任意のコード行を右クリックします。また、HTML、CSS、JavaScript のファイル名やコンポーネントのフォルダを右クリックすることもできます。 - -次の例は HTML コードから`c-hello`をプレビューします。 -![HTMLからコンポーネントをプレビュー](./images/vscode_localdev_preview_html.png) - -次の例は HTML ファイルから `c-hello` をプレビューします。 -![コンポーネントをファイルからプレビューします](./images/vscode_localdev_file_preview.png) - -SFDX: コンポーネントをローカルでプレビュー (SFDX: Preview Component Locally) を選択すると、コマンドパレットにプレビューオプションのリストが表示されます。コンポーネントのプレビューは、デスクトップのブラウザで行うか、仮想のモバイルデバイス (iOS または Android) で行うかを選択できます。モバイルプレビューには追加の設定が必要です。[『Lightning Web コンポーネント開発者ガイド』の「モバイルでの Lightning Web コンポーネントのプレビュー (ベータ)」](https://developer.salesforce.com/docs/component-library/documentation/ja-jp/lwc/lwc.mobile_extensions)を参照してください。 -![デスクトップのブラウザ、Android のエミュレータ、iOS のシミュレータでプレビューするかを選択します](./images/vscode_localdev_command_palette_preview_options.png) - -次の例は、ローカルの開発サーバのデスクトップブラウザでプレビューされたコンポーネントです。 -![ブラウザでプレビューされたコンポーネント](./images/vscode_localdev_preview.png) - -次の例は、仮想モバイルデバイス上でプレビューされたコンポーネントです。 -![仮想モバイルデバイスでプレビューされたコンポーネント](./images/vscode_localdev_preview_ios.png) diff --git a/docs/_articles/ja/localdev/set-up-lwc-local-dev.md b/docs/_articles/ja/localdev/set-up-lwc-local-dev.md deleted file mode 100644 index f9138f076d..0000000000 --- a/docs/_articles/ja/localdev/set-up-lwc-local-dev.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -title: LWC ローカル開発の設定 -lang: ja ---- - -LWC の ローカル開発を設定するには、サーバをインストールし、Dev Hub 組織を有効化して認証し、スクラッチ組織を作成します。LWC のローカル開発を使用するには、Salesforce DX プロジェクト内で Lightning Web コンポーネントを開発する必要があります。 - -## LWC ローカル開発サーバのインストール - -コマンドラインインターフェースから次のコマンドを実行します。 - -``` -sfdx plugins:install @salesforce/lwc-dev-server -``` - -> **トラブルシューティングのヒント:** 既知の問題のため、プラグインをインストールする際にエラーが表示される可能性があります。プラグインがインストールされているかどうかを確認するために、`sfdx plugins --core` を実行してください。インストールされていたら、ローカル開発サーバを起動してみてください。成功すれば、次に進むことができます。 - -**SFDX: Preview Component Locally \(SFDX: コンポーネントをローカルでプレビュー\)** を選択すると、コマンドパレットにプレビューオプションのリストが表示されます。コンポーネントのプレビューをデスクトップのブラウザで行うか、仮想モバイルデバイス (iOS または Android) で行うかを選択できます。モバイルでのプレビューには追加設定が必要です。詳細は、『Lightning Web コンポーネント開発者ガイド』 の[「モバイルでの Lightning Web コンポーネントのプレビュー (ベータ)」](https://developer.salesforce.com/docs/component-library/documentation/ja-jp/lwc/lwc.mobile_extensions)を参照してください。 diff --git a/packages/salesforcedx-vscode-lwc/package.json b/packages/salesforcedx-vscode-lwc/package.json index 1c88afadc7..8c999970d5 100644 --- a/packages/salesforcedx-vscode-lwc/package.json +++ b/packages/salesforcedx-vscode-lwc/package.json @@ -126,8 +126,7 @@ "activationEvents": [ "workspaceContains:sfdx-project.json", "workspaceContains:../workspace-user.xml", - "workspaceContains:**/workspace-user.xml", - "onCommand:sfdx.force.lightning.lwc.start" + "workspaceContains:**/workspace-user.xml" ], "main": "./out/src", "serverPath": [ @@ -160,12 +159,6 @@ ] }, "menus": { - "editor/context": [ - { - "command": "sfdx.force.lightning.lwc.preview", - "when": "sfdx:project_opened && resource =~ /.*\\/lwc\\/[^\\/]+(\\/[^\\/]+\\.(html|css|js))?$/" - } - ], "editor/title": [ { "command": "sfdx.force.lightning.lwc.test.editorTitle.run", @@ -188,12 +181,6 @@ "group": "navigation" } ], - "editor/title/context": [ - { - "command": "sfdx.force.lightning.lwc.preview", - "when": "sfdx:project_opened && resource =~ /.*\\/lwc\\/[^\\/]+(\\/[^\\/]+\\.(html|css|js))?$/" - } - ], "view/title": [ { "command": "sfdx.force.lightning.lwc.test.runAllTests", @@ -232,29 +219,7 @@ "group": "inline" } ], - "explorer/context": [ - { - "command": "sfdx.force.lightning.lwc.preview", - "when": "sfdx:project_opened && resource =~ /.*\\/lwc\\/[^\\/]+(\\/[^\\/]+\\.(html|css|js))?$/" - } - ], "commandPalette": [ - { - "command": "sfdx.force.lightning.lwc.start", - "when": "sfdx:project_opened" - }, - { - "command": "sfdx.force.lightning.lwc.stop", - "when": "sfdx:project_opened" - }, - { - "command": "sfdx.force.lightning.lwc.open", - "when": "sfdx:project_opened" - }, - { - "command": "sfdx.force.lightning.lwc.preview", - "when": "sfdx:project_opened && resource =~ /.*\\/lwc\\/[^\\/]+(\\/[^\\/]+\\.(html|css|js))?$/" - }, { "command": "sfdx.force.lightning.lwc.test.file.run", "when": "false" @@ -306,22 +271,6 @@ ] }, "commands": [ - { - "command": "sfdx.force.lightning.lwc.start", - "title": "%force_lightning_lwc_start_text%" - }, - { - "command": "sfdx.force.lightning.lwc.stop", - "title": "%force_lightning_lwc_stop_text%" - }, - { - "command": "sfdx.force.lightning.lwc.open", - "title": "%force_lightning_lwc_open_text%" - }, - { - "command": "sfdx.force.lightning.lwc.preview", - "title": "%force_lightning_lwc_preview_text%" - }, { "command": "sfdx.force.lightning.lwc.test.runAllTests", "title": "%force_lightning_lwc_test_run_all_tests_text%", @@ -442,30 +391,6 @@ } ] } - ], - "configuration": { - "type": "object", - "title": "%force_lightning_lwc_preferences%", - "properties": { - "salesforcedx-vscode-lwc.preview.rememberDevice": { - "type": "boolean", - "default": true, - "description": "%force_lightning_lwc_remember_device_description%" - }, - "salesforcedx-vscode-lwc.preview.logLevel": { - "type": "string", - "description": "%force_lightning_lwc_mobile_log_level%", - "enum": [ - "trace", - "debug", - "info", - "warn", - "error", - "fatal" - ], - "default": "warn" - } - } - } + ] } } diff --git a/packages/salesforcedx-vscode-lwc/package.nls.ja.json b/packages/salesforcedx-vscode-lwc/package.nls.ja.json index 0d0e13b1c1..2119264249 100644 --- a/packages/salesforcedx-vscode-lwc/package.nls.ja.json +++ b/packages/salesforcedx-vscode-lwc/package.nls.ja.json @@ -1,22 +1,17 @@ { - "force_lightning_lwc_start_text": "SFDX: ローカルの開発サーバを起動", - "force_lightning_lwc_stop_text": "SFDX: ローカルの開発サーバを停止", - "force_lightning_lwc_open_text": "SFDX: ローカルの開発サーバを開く", - "force_lightning_lwc_preview_text": "SFDX: コンポーネントをローカルでプレビュー", - "force_lightning_lwc_test_view_name": "LWC テスト", - "force_lightning_lwc_test_run_all_tests_text": "SFDX: すべての Lightning Web コンポーネントのテストを実行", - "force_lightning_lwc_test_refresh_test_explorer_text": "SFDX: Lightning Web コンポーネントテストエクスプローラを更新", - "force_lightning_lwc_test_navigate_to_test": "SFDX: Lightning Web コンポーネントのテストへ移動", - "force_lightning_lwc_test_file_run_text": "SFDX: Lightning Web コンポーネントのテストファイルを実行", - "force_lightning_lwc_test_file_debug_text": "SFDX: Lightning Web コンポーネントのテストファイルをデバッグ", - "force_lightning_lwc_test_case_run_text": "SFDX: Lightning Web コンポーネントのテストケースを実行", + "force_lightning_lwc_debugger": "Debug: LWC Jest Tests", + "force_lightning_lwc_debugger_desc": "Debug configuration for running LWC jest tests in VSCode.", "force_lightning_lwc_test_case_debug_text": "SFDX: Lightning Web コンポーネントのテストケースをデバッグ", - "force_lightning_lwc_test_run_current_file_text": "SFDX: 現在の Lightning Web コンポーネントのテストファイルを実行", + "force_lightning_lwc_test_case_run_text": "SFDX: Lightning Web コンポーネントのテストケースを実行", "force_lightning_lwc_test_debug_current_file_text": "SFDX: 現在の Lightning Web コンポーネントのテストファイルをデバッグ", + "force_lightning_lwc_test_file_debug_text": "SFDX: Lightning Web コンポーネントのテストファイルをデバッグ", + "force_lightning_lwc_test_file_run_text": "SFDX: Lightning Web コンポーネントのテストファイルを実行", + "force_lightning_lwc_test_navigate_to_test": "SFDX: Lightning Web コンポーネントのテストへ移動", + "force_lightning_lwc_test_refresh_test_explorer_text": "SFDX: Lightning Web コンポーネントテストエクスプローラを更新", + "force_lightning_lwc_test_run_all_tests_text": "SFDX: すべての Lightning Web コンポーネントのテストを実行", + "force_lightning_lwc_test_run_current_file_text": "SFDX: 現在の Lightning Web コンポーネントのテストファイルを実行", "force_lightning_lwc_test_start_watching_text": "SFDX: Lightning Web コンポーネントのテストのウォッチを開始", - "force_lightning_lwc_test_stop_watching_text": "SFDX: Lightning Web コンポーネントのテストのウォッチを停止", "force_lightning_lwc_test_stop_watching_all_tests_text": "SFDX: すべての Lightning Web コンポーネントのテストのウォッチを停止", - "force_lightning_lwc_preferences": "Salesforce Lightning Web Components", - "force_lightning_lwc_remember_device_description": "最後に使用したモバイルデバイスのターゲットを保存する", - "force_lightning_lwc_mobile_log_level": "モバイルプレビューする SFDX コマンドを呼び出す際に使用されるログレベル" + "force_lightning_lwc_test_stop_watching_text": "SFDX: Lightning Web コンポーネントのテストのウォッチを停止", + "force_lightning_lwc_test_view_name": "LWC テスト" } diff --git a/packages/salesforcedx-vscode-lwc/package.nls.json b/packages/salesforcedx-vscode-lwc/package.nls.json index a2f537227e..a68b7adadd 100644 --- a/packages/salesforcedx-vscode-lwc/package.nls.json +++ b/packages/salesforcedx-vscode-lwc/package.nls.json @@ -1,24 +1,17 @@ { - "force_lightning_lwc_start_text": "SFDX: Start Local Development Server", - "force_lightning_lwc_stop_text": "SFDX: Stop Local Development Server", - "force_lightning_lwc_open_text": "SFDX: Open Local Development Server", - "force_lightning_lwc_preview_text": "SFDX: Preview Component Locally", - "force_lightning_lwc_test_view_name": "LWC Tests", - "force_lightning_lwc_test_run_all_tests_text": "SFDX: Run All Lightning Web Component Tests", - "force_lightning_lwc_test_refresh_test_explorer_text": "SFDX: Refresh Lightning Web Component Test Explorer", - "force_lightning_lwc_test_navigate_to_test": "SFDX: Navigate to Lightning Web Component Test", - "force_lightning_lwc_test_file_run_text": "SFDX: Run Lightning Web Component Test File", - "force_lightning_lwc_test_file_debug_text": "SFDX: Debug Lightning Web Component Test File", - "force_lightning_lwc_test_case_run_text": "SFDX: Run Lightning Web Component Test Case", + "force_lightning_lwc_debugger": "Debug: LWC Jest Tests", + "force_lightning_lwc_debugger_desc": "Debug configuration for running LWC jest tests in VSCode.", "force_lightning_lwc_test_case_debug_text": "SFDX: Debug Lightning Web Component Test Case", - "force_lightning_lwc_test_run_current_file_text": "SFDX: Run Current Lightning Web Component Test File", + "force_lightning_lwc_test_case_run_text": "SFDX: Run Lightning Web Component Test Case", "force_lightning_lwc_test_debug_current_file_text": "SFDX: Debug Current Lightning Web Component Test File", + "force_lightning_lwc_test_file_debug_text": "SFDX: Debug Lightning Web Component Test File", + "force_lightning_lwc_test_file_run_text": "SFDX: Run Lightning Web Component Test File", + "force_lightning_lwc_test_navigate_to_test": "SFDX: Navigate to Lightning Web Component Test", + "force_lightning_lwc_test_refresh_test_explorer_text": "SFDX: Refresh Lightning Web Component Test Explorer", + "force_lightning_lwc_test_run_all_tests_text": "SFDX: Run All Lightning Web Component Tests", + "force_lightning_lwc_test_run_current_file_text": "SFDX: Run Current Lightning Web Component Test File", "force_lightning_lwc_test_start_watching_text": "SFDX: Start Watching Lightning Web Component Test", - "force_lightning_lwc_test_stop_watching_text": "SFDX: Stop Watching Lightning Web Component Test", "force_lightning_lwc_test_stop_watching_all_tests_text": "SFDX: Stop Watching All Lightning Web Component Tests", - "force_lightning_lwc_preferences": "Salesforce Lightning Web Components", - "force_lightning_lwc_remember_device_description": "Remember most recently used mobile device target.", - "force_lightning_lwc_mobile_log_level": "Log level used when calling SFDX Preview on Mobile command.", - "force_lightning_lwc_debugger": "Debug: LWC Jest Tests", - "force_lightning_lwc_debugger_desc": "Debug configuration for running LWC jest tests in VSCode." + "force_lightning_lwc_test_stop_watching_text": "SFDX: Stop Watching Lightning Web Component Test", + "force_lightning_lwc_test_view_name": "LWC Tests" } diff --git a/packages/salesforcedx-vscode-lwc/src/commands/commandConstants.ts b/packages/salesforcedx-vscode-lwc/src/commands/commandConstants.ts deleted file mode 100644 index f05b9349fd..0000000000 --- a/packages/salesforcedx-vscode-lwc/src/commands/commandConstants.ts +++ /dev/null @@ -1,10 +0,0 @@ -/* - * Copyright (c) 2019, salesforce.com, inc. - * All rights reserved. - * Licensed under the BSD 3-Clause license. - * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause - */ - -export const DEV_SERVER_DEFAULT_BASE_URL = 'http://localhost:3333'; -export const DEV_SERVER_PREVIEW_ROUTE = 'preview'; -export const DEV_SERVER_BASE_URL_REGEX = '(http://localhost):(d*)/?(.*)'; diff --git a/packages/salesforcedx-vscode-lwc/src/commands/forceLightningLwcOpen.ts b/packages/salesforcedx-vscode-lwc/src/commands/forceLightningLwcOpen.ts deleted file mode 100644 index eb152e3132..0000000000 --- a/packages/salesforcedx-vscode-lwc/src/commands/forceLightningLwcOpen.ts +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2019, salesforce.com, inc. - * All rights reserved. - * Licensed under the BSD 3-Clause license. - * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause - */ - -import * as vscode from 'vscode'; -import { nls } from '../messages'; -import { DevServerService } from '../service/devServerService'; -import { telemetryService } from '../telemetry'; -import { openBrowser, showError } from './commandUtils'; - -const logName = 'force_lightning_lwc_open'; -const commandName = nls.localize('force_lightning_lwc_open_text'); - -export const forceLightningLwcOpen = async () => { - const startTime = process.hrtime(); - - if (DevServerService.instance.isServerHandlerRegistered()) { - try { - await openBrowser(DevServerService.instance.getBaseUrl()); - telemetryService.sendCommandEvent(logName, startTime); - } catch (e) { - showError(e, logName, commandName); - } - } else { - console.log(`${logName}: server was not running, starting...`); - await vscode.commands.executeCommand('sfdx.force.lightning.lwc.start'); - telemetryService.sendCommandEvent(logName, startTime); - } -}; diff --git a/packages/salesforcedx-vscode-lwc/src/commands/forceLightningLwcPreview.ts b/packages/salesforcedx-vscode-lwc/src/commands/forceLightningLwcPreview.ts deleted file mode 100644 index 7a3c3b997a..0000000000 --- a/packages/salesforcedx-vscode-lwc/src/commands/forceLightningLwcPreview.ts +++ /dev/null @@ -1,656 +0,0 @@ -/* - * Copyright (c) 2019, salesforce.com, inc. - * All rights reserved. - * Licensed under the BSD 3-Clause license. - * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause - */ - -import { componentUtil } from '@salesforce/lightning-lsp-common'; -import { - CliCommandExecutor, - CommandOutput, - SfdxCommandBuilder -} from '@salesforce/salesforcedx-utils-vscode'; -import { notificationService } from '@salesforce/salesforcedx-utils-vscode'; -import { - EmptyParametersGatherer, - isSFContainerMode, - SfdxCommandlet, - SfdxWorkspaceChecker -} from '@salesforce/salesforcedx-utils-vscode'; -import * as fs from 'fs'; -import * as path from 'path'; -import * as vscode from 'vscode'; -import { channelService } from '../channel'; -import { nls } from '../messages'; -import { DevServerService } from '../service/devServerService'; -import { PreviewService } from '../service/previewService'; -import { telemetryService } from '../telemetry'; -import { openBrowser, showError } from './commandUtils'; -import { ForceLightningLwcStartExecutor } from './forceLightningLwcStart'; - -enum PreviewPlatformType { - Desktop = 1, - Android, - iOS -} - -export const enum PlatformName { - Desktop = 'Desktop', - Android = 'Android', - iOS = 'iOS' -} - -interface IOSSimulatorDevice { - name: string; - udid: string; - state: string; - runtimeId: string; - isAvailable: boolean; -} - -interface AndroidVirtualDevice { - name: string; - displayName: string; - deviceName: string; - path: string; - target: string; - api: string; -} - -interface PreviewQuickPickItem extends vscode.QuickPickItem { - label: string; - detail: string; - alwaysShow: boolean; - picked: boolean; - id: PreviewPlatformType; - defaultTargetName: string; - platformName: keyof typeof PlatformName; -} - -export interface DeviceQuickPickItem extends vscode.QuickPickItem { - name: string; -} - -export const platformOptions: PreviewQuickPickItem[] = [ - { - label: nls.localize('force_lightning_lwc_preview_desktop_label'), - detail: nls.localize('force_lightning_lwc_preview_desktop_description'), - alwaysShow: true, - picked: true, - id: PreviewPlatformType.Desktop, - platformName: PlatformName.Desktop, - defaultTargetName: '' - }, - { - label: nls.localize('force_lightning_lwc_android_label'), - detail: nls.localize('force_lightning_lwc_android_description'), - alwaysShow: true, - picked: false, - id: PreviewPlatformType.Android, - platformName: PlatformName.Android, - defaultTargetName: 'SFDXEmulator' - }, - { - label: nls.localize('force_lightning_lwc_ios_label'), - detail: nls.localize('force_lightning_lwc_ios_description'), - alwaysShow: true, - picked: false, - id: PreviewPlatformType.iOS, - platformName: PlatformName.iOS, - defaultTargetName: 'SFDXSimulator' - } -]; - -const logName = 'force_lightning_lwc_preview'; -const commandName = nls.localize('force_lightning_lwc_preview_text'); -const sfdxDeviceListCommand = 'force:lightning:local:device:list'; -const sfdxMobilePreviewCommand = 'force:lightning:lwc:preview'; -const androidSuccessString = 'Launching... Opening Browser'; - -export const forceLightningLwcPreview = async (sourceUri: vscode.Uri) => { - const preview = getPreview(); - preview(sourceUri); -}; - -export const getPreview = () => { - if (isSFContainerMode()) { - return lwcPreviewContainerMode; - } else { - return lwcPreview; - } -}; - -const lwcPreviewContainerMode = () => { - const message = nls.localize('force_lightning_lwc_preview_container_mode'); - vscode.window.showErrorMessage(message); - return; -}; - -export const lwcPreview = async (sourceUri: vscode.Uri) => { - const startTime = process.hrtime(); - - if (!sourceUri) { - if (vscode.window.activeTextEditor) { - sourceUri = vscode.window.activeTextEditor.document.uri; - } else { - const message = nls.localize( - 'force_lightning_lwc_preview_file_undefined', - sourceUri - ); - showError(new Error(message), logName, commandName); - return; - } - } - - const resourcePath = sourceUri.fsPath; - if (!resourcePath) { - const message = nls.localize( - 'force_lightning_lwc_preview_file_undefined', - resourcePath - ); - showError(new Error(message), logName, commandName); - return; - } - - if (!fs.existsSync(resourcePath)) { - const message = nls.localize( - 'force_lightning_lwc_preview_file_nonexist', - resourcePath - ); - showError(new Error(message), logName, commandName); - return; - } - - const isSFDX = true; // TODO support non SFDX projects - const isDirectory = fs.lstatSync(resourcePath).isDirectory(); - const componentName = isDirectory - ? componentUtil.moduleFromDirectory(resourcePath, isSFDX) - : componentUtil.moduleFromFile(resourcePath, isSFDX); - if (!componentName) { - const message = nls.localize( - 'force_lightning_lwc_preview_unsupported', - resourcePath - ); - showError(new Error(message), logName, commandName); - return; - } - - await executePreview(startTime, componentName, resourcePath); -}; - -/** - * Performs the action of previewing the LWC. It takes care of prompting the user - * and gathering all info needed to preview the LWC. This includes prompting the user - * to select a platform, a target device, a target native app (or browser), etc. - * Previewing on Android or iOS are handled by the @salesforce/lwc-dev-mobile sfdx package. - * - * @param startTime start time of the preview command - * @param componentName name of the lwc - * @param resourcePath path to the lwc - */ -const executePreview = async ( - startTime: [number, number], - componentName: string, - resourcePath: string -) => { - const commandCancelledMessage = nls.localize( - 'force_lightning_lwc_operation_cancelled' - ); - - // 1. Prompt user to select a platform - const platformSelection = await selectPlatform(); - if (!platformSelection) { - vscode.window.showWarningMessage(commandCancelledMessage); - return; - } - - if (platformSelection.id === PreviewPlatformType.Desktop) { - await startServer(true, componentName, startTime); - return; - } - - // 2. Prompt user to select a target device - let targetDevice: string; - try { - const targetName = await selectTargetDevice(platformSelection); - if (targetName === undefined) { - vscode.window.showInformationMessage(commandCancelledMessage); - return; - } else { - targetDevice = targetName; - } - } catch { - // exception has already been logged - return; - } - - // 3. Determine project root directory and path to the config file - const projectRootDir = getProjectRootDirectory(resourcePath); - const configFilePath = - projectRootDir && path.join(projectRootDir, 'mobile-apps.json'); - - // 4. Prompt user to select a target app (if any) - const targetApp = await selectTargetApp(platformSelection, configFilePath); - if (targetApp === undefined) { - vscode.window.showInformationMessage(commandCancelledMessage); - return; - } - - await startServer(false, componentName, startTime); - - // 5. Preview on mobile device - await executeMobilePreview( - platformSelection, - targetDevice, - targetApp, - projectRootDir, - configFilePath, - componentName, - startTime - ); -}; - -/** - * Starts the lwc server if it is not already running. - * - * @param isDesktop if desktop browser is selected - * @param componentName name of the component to preview - * @param startTime start time of the preview command - */ -const startServer = async ( - isDesktop: boolean, - componentName: string, - startTime: [number, number] -) => { - if (!DevServerService.instance.isServerHandlerRegistered()) { - console.log(`${logName}: server was not running, starting...`); - const preconditionChecker = new SfdxWorkspaceChecker(); - const parameterGatherer = new EmptyParametersGatherer(); - const executor = new ForceLightningLwcStartExecutor({ - openBrowser: isDesktop, - componentName - }); - - const commandlet = new SfdxCommandlet( - preconditionChecker, - parameterGatherer, - executor - ); - - await commandlet.run(); - telemetryService.sendCommandEvent(logName, startTime); - } else if (isDesktop) { - try { - const fullUrl = DevServerService.instance.getComponentPreviewUrl( - componentName - ); - await openBrowser(fullUrl); - telemetryService.sendCommandEvent(logName, startTime); - } catch (e) { - showError(e, logName, commandName); - } - } -}; - -/** - * Prompts the user to select a platform to preview the LWC on. - * @returns the selected platform or undefined if no selection was made. - */ -const selectPlatform = async (): Promise => { - const platformSelection = await vscode.window.showQuickPick(platformOptions, { - placeHolder: nls.localize('force_lightning_lwc_platform_selection') - }); - - return platformSelection; -}; - -/** - * Prompts the user to select a device to preview the LWC on. - * - * @param platformSelection the selected platform - * @returns the name of the selected device or undefined if no selection was made. - */ -const selectTargetDevice = async ( - platformSelection: PreviewQuickPickItem -): Promise => { - const isAndroid = platformSelection.id === PreviewPlatformType.Android; - const lastTarget = PreviewService.instance.getRememberedDevice( - platformSelection.platformName - ); - let target: string | undefined = platformSelection.defaultTargetName; - let createDevicePlaceholderText = isAndroid - ? nls.localize('force_lightning_lwc_android_target_default') - : nls.localize('force_lightning_lwc_ios_target_default'); - - // Remember device setting enabled and previous device retrieved. - if (PreviewService.instance.isRememberedDeviceEnabled() && lastTarget) { - const message = isAndroid - ? 'force_lightning_lwc_android_target_remembered' - : 'force_lightning_lwc_ios_target_remembered'; - createDevicePlaceholderText = nls.localize(message, lastTarget); - target = lastTarget; - } - - const deviceListOutput = new CommandOutput(); - const deviceListCommand = new SfdxCommandBuilder() - .withArg(sfdxDeviceListCommand) - .withFlag('-p', platformSelection.platformName) - .withJson() - .build(); - - let deviceListExecutionExitCode: number | undefined; - const deviceListCancellationTokenSource = new vscode.CancellationTokenSource(); - const deviceListCancellationToken = deviceListCancellationTokenSource.token; - const deviceListExecutor = new CliCommandExecutor(deviceListCommand, {}); - const deviceListExecution = deviceListExecutor.execute( - deviceListCancellationToken - ); - deviceListExecution.processExitSubject.subscribe(exitCode => { - deviceListExecutionExitCode = exitCode; - }); - - const items: DeviceQuickPickItem[] = []; - const createNewDeviceItem: DeviceQuickPickItem = { - label: nls.localize( - 'force_lightning_lwc_preview_create_virtual_device_label' - ), - detail: nls.localize( - 'force_lightning_lwc_preview_create_virtual_device_detail' - ), - name: nls.localize( - 'force_lightning_lwc_preview_create_virtual_device_label' - ) - }; - let targetName: string | undefined; - - try { - const result: string = await deviceListOutput.getCmdResult( - deviceListExecution - ); - - const jsonString: string = result.substring(result.indexOf('{')); - - // populate quick pick list of devices from the parsed JSON data - if (isAndroid) { - const devices: AndroidVirtualDevice[] = JSON.parse(jsonString) - .result as AndroidVirtualDevice[]; - devices.forEach(device => { - const label: string = device.displayName; - const detail: string = `${device.target}, ${device.api}`; - const name: string = device.name; - items.push({ label, detail, name }); - }); - } else { - const devices: IOSSimulatorDevice[] = JSON.parse(jsonString) - .result as IOSSimulatorDevice[]; - devices.forEach(device => { - const label: string = device.name; - const detail: string = device.runtimeId; - const name: string = device.name; - items.push({ label, detail, name }); - }); - } - } catch (e) { - // If device enumeration fails due to exit code 127 - // (i.e. lwc on mobile sfdx plugin is not installed) - // then show an error message and exit. For other reasons, - // silently fail and proceed with an empty list of devices. - const error = String(e) || ''; - if ( - deviceListExecutionExitCode === 127 || - error.includes('not a sfdx command') - ) { - showError( - new Error(nls.localize('force_lightning_lwc_no_mobile_plugin')), - logName, - commandName - ); - throw e; - } - } - - // if there are any devices available, show a pick list. - let selectedItem: DeviceQuickPickItem | undefined; - if (items.length > 0) { - items.unshift(createNewDeviceItem); - - selectedItem = await vscode.window.showQuickPick(items, { - placeHolder: nls.localize( - 'force_lightning_lwc_preview_select_virtual_device' - ) - }); - - if (selectedItem === undefined) { - // user cancelled operation - return undefined; - } else { - targetName = selectedItem.name; - } - } - - // if there are no devices available or user chooses to create - // a new device then show an inputbox and ask for further info. - if (targetName === undefined || selectedItem === createNewDeviceItem) { - targetName = await vscode.window.showInputBox({ - placeHolder: createDevicePlaceholderText - }); - - if (targetName === undefined) { - // user cancelled operation - return undefined; - } - } - - // new target device entered - if (targetName && targetName !== '') { - PreviewService.instance.updateRememberedDevice( - platformSelection.platformName, - targetName - ); - - target = targetName; - } - - return target; -}; - -/** - * Prompts the user to select an app to preview the LWC on. Defaults to browser. - * - * @param platformSelection the selected platform - * @param configFile path to a config file - * @returns the name of the selected device or undefined if user cancels selection. - */ -const selectTargetApp = async ( - platformSelection: PreviewQuickPickItem, - configFile: string | undefined -): Promise => { - let targetApp: string | undefined = 'browser'; - const items: vscode.QuickPickItem[] = []; - const browserItem: vscode.QuickPickItem = { - label: nls.localize('force_lightning_lwc_browserapp_label'), - detail: nls.localize('force_lightning_lwc_browserapp_description') - }; - - if (configFile === undefined || fs.existsSync(configFile) === false) { - return targetApp; - } - - try { - const fileContent = fs.readFileSync(configFile, 'utf8'); - const json = JSON.parse(fileContent); - const appDefinitionsForSelectedPlatform = - platformSelection.id === PreviewPlatformType.Android - ? json.apps.android - : json.apps.ios; - - const apps = Array.from(appDefinitionsForSelectedPlatform); - - apps.forEach(app => { - const label: string = app.name; - const detail: string = app.id; - items.push({ label, detail }); - }); - } catch { - // silengtly fail and default to previewing on browser - } - - // if there are any devices available, show a pick list. - if (items.length > 0) { - items.unshift(browserItem); - - const selectedItem = await vscode.window.showQuickPick(items, { - placeHolder: nls.localize('force_lightning_lwc_preview_select_target_app') - }); - - if (selectedItem) { - // if user did not select the browser option then take the app id - // from the detail property of the selected item - if (selectedItem !== browserItem) { - targetApp = selectedItem.detail; - } - } else { - // user cancelled operation - targetApp = undefined; - } - } - - return targetApp; -}; - -/** - * Prompts the user to select a device to preview the LWC on. - * - * @param platformSelection the selected platform - * @param targetDevice the selected device - * @param targetApp the id of the native app to preview the component in, or browser - * @param projectDir the path to the project root directory - * @param configFile the path to the preview config file - * @param componentName name of the component to preview - * @param startTime start time of the preview command - */ -const executeMobilePreview = async ( - platformSelection: PreviewQuickPickItem, - targetDevice: string, - targetApp: string, - projectDir: string | undefined, - configFile: string | undefined, - componentName: string, - startTime: [number, number] -) => { - const isAndroid = platformSelection.id === PreviewPlatformType.Android; - - let commandBuilder = new SfdxCommandBuilder() - .withDescription(commandName) - .withArg(sfdxMobilePreviewCommand) - .withFlag('-p', platformSelection.platformName) - .withFlag('-t', targetDevice) - .withFlag('-n', componentName) - .withFlag('-a', targetApp); - - if (projectDir) { - commandBuilder = commandBuilder.withFlag('-d', projectDir); - } - - if (configFile && targetApp !== 'browser') { - commandBuilder = commandBuilder.withFlag('-f', configFile); - } - - const previewCommand = commandBuilder - .withFlag('--loglevel', PreviewService.instance.getLogLevel()) - .build(); - - const previewExecutor = new CliCommandExecutor(previewCommand, { - env: { SFDX_JSON_TO_STDOUT: 'true' } - }); - const previewCancellationTokenSource = new vscode.CancellationTokenSource(); - const previewCancellationToken = previewCancellationTokenSource.token; - const previewExecution = previewExecutor.execute(previewCancellationToken); - telemetryService.sendCommandEvent(logName, startTime); - channelService.streamCommandOutput(previewExecution); - channelService.showChannelOutput(); - - previewExecution.processExitSubject.subscribe(async exitCode => { - if (exitCode !== 0) { - const message = isAndroid - ? nls.localize('force_lightning_lwc_android_failure', targetDevice) - : nls.localize('force_lightning_lwc_ios_failure', targetDevice); - showError(new Error(message), logName, commandName); - } else if (!isAndroid) { - notificationService - .showSuccessfulExecution( - previewExecution.command.toString(), - channelService - ) - .catch(); - vscode.window.showInformationMessage( - nls.localize('force_lightning_lwc_ios_start', targetDevice) - ); - } - }); - - // TODO: Remove this when SFDX Plugin launches Android Emulator as separate process. - // listen for Android Emulator finished - if (isAndroid) { - previewExecution.stdoutSubject.subscribe(async data => { - if (data && data.toString().includes(androidSuccessString)) { - notificationService - .showSuccessfulExecution( - previewExecution.command.toString(), - channelService - ) - .catch(); - vscode.window.showInformationMessage( - nls.localize('force_lightning_lwc_android_start', targetDevice) - ); - } - }); - } -}; - -/** - * Given a path, it recursively goes through that directory and upwards, until it finds - * a config file named sfdx-project.json and returns the path to the folder containg it. - * - * @param startPath starting path to search for the config file. - * @returns the path to the folder containing the config file, or undefined if config file not found - */ -export const getProjectRootDirectory = (startPath: string): string | undefined => { - if (!fs.existsSync(startPath)) { - return undefined; - } - - const searchingForFile = 'sfdx-project.json'; - let dir: string | undefined = fs.lstatSync(startPath).isDirectory() - ? startPath - : path.dirname(startPath); - while (dir) { - const fileName = path.join(dir, searchingForFile); - if (fs.existsSync(fileName)) { - return dir; - } else { - dir = directoryLevelUp(dir); - } - } - - // couldn't determine the root dir - return undefined; -}; - -/** - * Given a path to a directory, returns a path that is one level up. - * - * @param directory path to a directory - * @returns path to a directory that is one level up, or undefined if cannot go one level up. - */ -export const directoryLevelUp = (directory: string): string | undefined => { - const levelUp = path.dirname(directory); - - if (levelUp === directory) { - // we're at the root and can't go any further up - return undefined; - } - - return levelUp; -}; diff --git a/packages/salesforcedx-vscode-lwc/src/commands/forceLightningLwcStart.ts b/packages/salesforcedx-vscode-lwc/src/commands/forceLightningLwcStart.ts deleted file mode 100644 index ddea0a0a94..0000000000 --- a/packages/salesforcedx-vscode-lwc/src/commands/forceLightningLwcStart.ts +++ /dev/null @@ -1,251 +0,0 @@ -/* - * Copyright (c) 2019, salesforce.com, inc. - * All rights reserved. - * Licensed under the BSD 3-Clause license. - * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause - */ - -import { - CliCommandExecutor, - Command, - notificationService, - ProgressNotification, - SfdxCommandBuilder -} from '@salesforce/salesforcedx-utils-vscode'; -import { - EmptyParametersGatherer, - SfdxCommandlet, - SfdxCommandletExecutor, - SfdxWorkspaceChecker -} from '@salesforce/salesforcedx-utils-vscode'; -import { ContinueResponse } from '@salesforce/salesforcedx-utils-vscode'; -import { Subject } from 'rxjs/Subject'; -import * as vscode from 'vscode'; -import { channelService } from '../channel'; -import { nls } from '../messages'; -import { DevServerService, ServerHandler } from '../service/devServerService'; -import { openBrowser, showError } from './commandUtils'; - -const logName = 'force_lightning_lwc_start'; -const commandName = nls.localize('force_lightning_lwc_start_text'); - -/** - * Hints for providing a user-friendly error message / action. - * Hints come from the stderr output of lwc-dev-server. (We should move this to lwc-dev-server later) - */ -export const enum errorHints { - SERVER_STARTUP_FALIED = 'Server start up failed', - ADDRESS_IN_USE = 'EADDRINUSE', - INACTIVE_SCRATCH_ORG = 'Error authenticating to your scratch org. Make sure that it is still active' -} - -export interface ForceLightningLwcStartOptions { - /** whether to automatically open the browser after server start */ - openBrowser: boolean; - /** component name to preview in the browser */ - componentName?: string; -} - -export class ForceLightningLwcStartExecutor extends SfdxCommandletExecutor<{}> { - private readonly options: ForceLightningLwcStartOptions; - private errorHint?: string; - - constructor(options: ForceLightningLwcStartOptions = { openBrowser: true }) { - super(); - this.options = options; - } - - public build(): Command { - return ( - new SfdxCommandBuilder() - .withDescription(commandName) - .withArg('force:lightning:lwc:start') - .withLogName(logName) - // .withJson() - .build() - ); - } - - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public execute(response: ContinueResponse<{}>): void { - const startTime = process.hrtime(); - const cancellationTokenSource = new vscode.CancellationTokenSource(); - const cancellationToken = cancellationTokenSource.token; - - const executor = new CliCommandExecutor(this.build(), { - cwd: this.executionCwd, - env: { SFDX_JSON_TO_STDOUT: 'true' } - }); - const execution = executor.execute(cancellationToken); - const executionName = execution.command.toString(); - - const serverHandler: ServerHandler = { - stop: async () => { - return execution.killExecution('SIGTERM'); - } - }; - DevServerService.instance.registerServerHandler(serverHandler); - - channelService.streamCommandOutput(execution); - channelService.showChannelOutput(); - - let serverStarted = false; - let printedError = false; - - const progress = new Subject(); - ProgressNotification.show( - execution, - cancellationTokenSource, - vscode.ProgressLocation.Notification, - progress.asObservable() - ); - - // listen for server startup - execution.stdoutSubject.subscribe(async data => { - if (!serverStarted && data && data.toString().includes('Server up')) { - serverStarted = true; - progress.complete(); - notificationService - .showSuccessfulExecution(executionName, channelService) - .catch(); - - DevServerService.instance.setBaseUrlFromDevServerUpMessage( - data.toString() - ); - - if (this.options.openBrowser) { - await openBrowser( - this.options.componentName - ? DevServerService.instance.getComponentPreviewUrl( - this.options.componentName - ) - : DevServerService.instance.getBaseUrl() - ); - } - - this.logMetric(execution.command.logName, startTime); - } - }); - - execution.stderrSubject.subscribe(async data => { - if (!printedError && data) { - let errorCode = -1; - if (data.toString().includes(errorHints.SERVER_STARTUP_FALIED)) { - errorCode = 1; - } - if (data.toString().includes(errorHints.ADDRESS_IN_USE)) { - errorCode = 98; - } - if (data.toString().includes(errorHints.INACTIVE_SCRATCH_ORG)) { - this.errorHint = errorHints.INACTIVE_SCRATCH_ORG; - } - if (errorCode !== -1) { - this.handleErrors( - cancellationToken, - serverHandler, - serverStarted, - errorCode - ); - progress.complete(); - printedError = true; - } - } - }); - - execution.processExitSubject.subscribe(async exitCode => { - if (!printedError) { - this.handleErrors( - cancellationToken, - serverHandler, - serverStarted, - exitCode - ); - printedError = true; - } - }); - - notificationService.reportExecutionError( - executionName, - execution.processErrorSubject - ); - - cancellationToken.onCancellationRequested(() => { - notificationService.showWarningMessage( - nls.localize('command_canceled', executionName) - ); - channelService.showChannelOutput(); - }); - } - - private handleErrors( - cancellationToken: vscode.CancellationToken, - serverHandler: ServerHandler, - serverStarted: boolean, - exitCode: number | null | undefined - ) { - DevServerService.instance.clearServerHandler(serverHandler); - if (!serverStarted && !cancellationToken.isCancellationRequested) { - let message = nls.localize('force_lightning_lwc_start_failed'); - - if ( - exitCode === 1 && - this.errorHint === errorHints.INACTIVE_SCRATCH_ORG - ) { - message = nls.localize('force_lightning_lwc_inactive_scratch_org'); - } - if (exitCode === 127) { - message = nls.localize('force_lightning_lwc_start_not_found'); - } - if (exitCode === 98) { - message = nls.localize('force_lightning_lwc_start_addr_in_use'); - } - - showError(new Error(message), logName, commandName); - } else if (exitCode !== undefined && exitCode !== null && exitCode > 0) { - const message = nls.localize( - 'force_lightning_lwc_start_exited', - exitCode - ); - showError(new Error(message), logName, commandName); - } - } -} - -export const forceLightningLwcStart = async () => { - if (DevServerService.instance.isServerHandlerRegistered()) { - const warningMessage = nls.localize( - 'force_lightning_lwc_start_already_running' - ); - const openBrowserOption = nls.localize('prompt_option_open_browser'); - const restartOption = nls.localize('prompt_option_restart'); - const response = await notificationService.showWarningMessage( - warningMessage, - openBrowserOption, - restartOption - ); - if (response === openBrowserOption) { - await openBrowser(DevServerService.instance.getBaseUrl()); - return; - } else if (response === restartOption) { - channelService.appendLine( - nls.localize('force_lightning_lwc_stop_in_progress') - ); - await DevServerService.instance.stopServer(); - } else { - console.log('local development server already running, no action taken'); - return; - } - } - - const preconditionChecker = new SfdxWorkspaceChecker(); - const parameterGatherer = new EmptyParametersGatherer(); - const executor = new ForceLightningLwcStartExecutor(); - - const commandlet = new SfdxCommandlet( - preconditionChecker, - parameterGatherer, - executor - ); - - await commandlet.run(); -}; diff --git a/packages/salesforcedx-vscode-lwc/src/commands/forceLightningLwcStop.ts b/packages/salesforcedx-vscode-lwc/src/commands/forceLightningLwcStop.ts deleted file mode 100644 index 09dc942aba..0000000000 --- a/packages/salesforcedx-vscode-lwc/src/commands/forceLightningLwcStop.ts +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2019, salesforce.com, inc. - * All rights reserved. - * Licensed under the BSD 3-Clause license. - * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause - */ - -import { notificationService } from '@salesforce/salesforcedx-utils-vscode'; -import { channelService } from '../channel'; -import { nls } from '../messages'; -import { DevServerService } from '../service/devServerService'; -import { telemetryService } from '../telemetry'; -import { showError } from './commandUtils'; - -const logName = 'force_lightning_lwc_stop'; -const commandName = nls.localize('force_lightning_lwc_stop_text'); - -export const forceLightningLwcStop = async () => { - const startTime = process.hrtime(); - - try { - if (DevServerService.instance.isServerHandlerRegistered()) { - channelService.appendLine( - nls.localize('force_lightning_lwc_stop_in_progress') - ); - await DevServerService.instance.stopServer(); - notificationService - .showSuccessfulExecution( - nls.localize('force_lightning_lwc_stop_text'), - channelService - ) - .catch(); - telemetryService.sendCommandEvent(logName, startTime); - } else { - notificationService.showWarningMessage( - nls.localize('force_lightning_lwc_stop_not_running') - ); - } - } catch (e) { - showError(e, logName, commandName); - } -}; diff --git a/packages/salesforcedx-vscode-lwc/src/commands/index.ts b/packages/salesforcedx-vscode-lwc/src/commands/index.ts index 4b80656b54..3cd17037f1 100644 --- a/packages/salesforcedx-vscode-lwc/src/commands/index.ts +++ b/packages/salesforcedx-vscode-lwc/src/commands/index.ts @@ -4,8 +4,3 @@ * Licensed under the BSD 3-Clause license. * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ - -export { forceLightningLwcStart } from './forceLightningLwcStart'; -export { forceLightningLwcStop } from './forceLightningLwcStop'; -export { forceLightningLwcOpen } from './forceLightningLwcOpen'; -export { forceLightningLwcPreview } from './forceLightningLwcPreview'; diff --git a/packages/salesforcedx-vscode-lwc/src/index.ts b/packages/salesforcedx-vscode-lwc/src/index.ts index d9ded850e5..5ad1281575 100644 --- a/packages/salesforcedx-vscode-lwc/src/index.ts +++ b/packages/salesforcedx-vscode-lwc/src/index.ts @@ -8,23 +8,14 @@ import { shared as lspCommon } from '@salesforce/lightning-lsp-common'; import * as path from 'path'; import { - commands, ConfigurationTarget, - Disposable, ExtensionContext, workspace, WorkspaceConfiguration } from 'vscode'; -import { - forceLightningLwcOpen, - forceLightningLwcPreview, - forceLightningLwcStart, - forceLightningLwcStop -} from './commands'; import { ESLINT_NODEPATH_CONFIG, log, LWC_EXTENSION_NAME } from './constants'; import { createLanguageClient } from './languageClient'; import { metaSupport } from './metasupport'; -import { DevServerService } from './service/devServerService'; import { telemetryService } from './telemetry'; import { activateLwcTestSupport, @@ -72,8 +63,6 @@ export const activate = async (extensionContext: ExtensionContext) => { // If activationMode === always, ignore workspace type and continue activating // register commands - const ourCommands = registerCommands(extensionContext); - extensionContext.subscriptions.push(ourCommands); // If we get here, we either passed autodetect validation or activationMode == always log('Lightning Web Components Extension Activated'); @@ -127,37 +116,7 @@ export const activate = async (extensionContext: ExtensionContext) => { telemetryService.sendExtensionActivationEvent(extensionHRStart); }; -export const deactivate = async () => { - if (DevServerService.instance.isServerHandlerRegistered()) { - await DevServerService.instance.stopServer(); - } - log('Lightning Web Components Extension Deactivated'); - telemetryService.sendExtensionDeactivationEvent(); -}; - const getActivationMode = (): string => { const config = workspace.getConfiguration('salesforcedx-vscode-lightning'); return config.get('activationMode') || 'autodetect'; // default to autodetect }; - -// eslint-disable-next-line @typescript-eslint/no-unused-vars -const registerCommands = (_extensionContext: ExtensionContext): Disposable => { - return Disposable.from( - commands.registerCommand( - 'sfdx.force.lightning.lwc.start', - forceLightningLwcStart - ), - commands.registerCommand( - 'sfdx.force.lightning.lwc.stop', - forceLightningLwcStop - ), - commands.registerCommand( - 'sfdx.force.lightning.lwc.open', - forceLightningLwcOpen - ), - commands.registerCommand( - 'sfdx.force.lightning.lwc.preview', - forceLightningLwcPreview - ) - ); -}; diff --git a/packages/salesforcedx-vscode-lwc/src/messages/i18n.ja.ts b/packages/salesforcedx-vscode-lwc/src/messages/i18n.ja.ts index 108972d05f..78643def10 100644 --- a/packages/salesforcedx-vscode-lwc/src/messages/i18n.ja.ts +++ b/packages/salesforcedx-vscode-lwc/src/messages/i18n.ja.ts @@ -17,36 +17,6 @@ */ export const messages = { command_failure: '%s の実行に失敗しました。', - command_canceled: '%s はキャンセルされました。', - force_lightning_lwc_start_text: 'SFDX: ローカルの開発サーバを起動', - force_lightning_lwc_start_not_found: - 'このコマンドを実行するには、最初に @salesforce/lwc-dev-server プラグインをインストールしてください。詳細は [https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.get_started_local_dev](https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.get_started_local_dev) を参照してください。', - force_lightning_lwc_start_addr_in_use: - 'アドレスが既に使用されているため、ローカルの開発サーバを起動できませんでした。修正するには、次のいずれかの方法を試してください。\n 1) 他のインスタンスで起動しているローカルの開発サーバを停止する。\n2) デフォルトのポートを変更する。[プロジェクトの構成 (任意)](https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.get_started_local_dev_setup).\n 3) 指定したポートで起動しているプロセスを停止する。', - force_lightning_lwc_inactive_scratch_org: - 'スクラッチ組織が有効ではないため、ローカルの開発サーバを起動できませんでした。「SFDX: デフォルトのスクラッチ組織を作成」を実行してスクラッチ組織を作成するか、「SFDX: デフォルトの組織を設定」を実行して有効なスクラッチ組織を選択してください。', - force_lightning_lwc_start_failed: - 'ローカルの開発サーバを起動できませんでした。', - force_lightning_lwc_start_exited: - 'ローカルの開発サーバがエラーコード %s で予期せず終了しました。', - force_lightning_lwc_start_already_running: - 'ローカルの開発サーバは既に起動しています。', - force_lightning_lwc_stop_text: 'SFDX: ローカルの開発サーバを停止', - force_lightning_lwc_stop_not_running: - 'ローカルの開発サーバが起動していません。', - force_lightning_lwc_stop_in_progress: 'ローカルの開発サーバを停止しています', - force_lightning_lwc_preview_text: - 'SFDX: コンポーネントをローカルでプレビュー', - force_lightning_lwc_preview_file_undefined: - 'Lightning Web Component モジュールが見つかりません。ファイルパス %s が正しいか確認してください。', - force_lightning_lwc_preview_file_nonexist: - '%s 内に Lightning Web Component モジュールが見つかりません。モジュールが存在することを確認してください。', - force_lightning_lwc_preview_unsupported: - "ファイルパスが正しくありません。ローカルの開発サーバは Lightning Web Components module '%s.' を認識できません。", - force_lightning_lwc_open_text: 'SFDX: ブラウザでローカルの開発サーバを開く', - prompt_option_open_browser: 'ブラウザを開く', - prompt_option_restart: '再起動', - force_lwc_test_run_description_text: 'LWC テストを実行', force_lightning_lwc_test_navigate_to_test: 'SFDX: Lightning Web Component テストへ移動', no_lwc_jest_found_text: @@ -61,43 +31,6 @@ export const messages = { default_task_name: 'LWC テスト', task_windows_command_prompt_messaging: 'タスク実行時のデフォルトのシェルが cmd.exe に設定されます', - force_lightning_lwc_no_mobile_plugin: - 'このコマンドを実行するには、@salesforce/lwc-dev-mobile プラグインをインストールしてください。', - force_lightning_lwc_platform_selection: - 'コンポーネントをプレビューするプラットフォームを選択', - force_lightning_lwc_android_target_default: - 'Android エミュレータの名前を入力 (デフォルトの場合は空)', - force_lightning_lwc_ios_target_default: - 'iOS シミュレータの名前を入力 (デフォルトの場合は空)', - force_lightning_lwc_android_target_remembered: - "Android エミュレータの名前を入力 ('%s' の場合は空)", - force_lightning_lwc_ios_target_remembered: - "iOS シミュレータの名前を入力 ('%s' の場合は空)", - force_lightning_lwc_operation_cancelled: - 'プレビュー操作がユーザによりキャンセルされました。', - force_lightning_lwc_ios_label: 'iOS シミュレータを使用', - force_lightning_lwc_ios_description: 'iOS 上でコンポーネントをプレビュー', - force_lightning_lwc_android_label: 'Android エミュレータを使用', - force_lightning_lwc_android_description: - 'Android 上でコンポーネントをプレビュー', - force_lightning_lwc_android_failure: - "Android エミュレータ '%s' の起動に失敗しました。", - force_lightning_lwc_ios_failure: - "iOS シミュレータ '%s' の起動に失敗しました。", - force_lightning_lwc_android_start: - "Android エミュレータ '%s' を起動しています。", - force_lightning_lwc_ios_start: "iOS シミュレータ '%s' を起動しています。", - force_lightning_lwc_browserapp_label: 'ブラウザ', - force_lightning_lwc_browserapp_description: 'モバイルブラウザ', - force_lightning_lwc_preview_create_virtual_device_label: '新規...', - force_lightning_lwc_preview_create_virtual_device_detail: - '仮想デバイスを作成', - force_lightning_lwc_preview_select_virtual_device: '仮想デバイスを選択...', - force_lightning_lwc_preview_select_target_app: - 'ターゲットアプリケーションを選択...', - force_lightning_lwc_preview_desktop_label: 'デスクトップブラウザを使用', - force_lightning_lwc_preview_desktop_description: - 'デスクトップブラウザ上でコンポーネントをプレビュー', lwc_output_channel_name: 'LWC Extension', force_lightning_lwc_no_redhat_extension_found: 'Salesforce js-meta.xml IntelliSense を使用するには、Red Hat XML 拡張機能が必要です。', diff --git a/packages/salesforcedx-vscode-lwc/src/messages/i18n.ts b/packages/salesforcedx-vscode-lwc/src/messages/i18n.ts index 237d117490..3385338ecf 100644 --- a/packages/salesforcedx-vscode-lwc/src/messages/i18n.ts +++ b/packages/salesforcedx-vscode-lwc/src/messages/i18n.ts @@ -17,38 +17,6 @@ */ export const messages = { command_failure: '%s failed to run.', - command_canceled: '%s was canceled.', - force_lightning_lwc_start_text: 'SFDX: Start Local Development Server', - force_lightning_lwc_start_not_found: - 'To run this command, install the @salesforce/lwc-dev-server plugin. For more info, see [Set Up LWC Local Development](https://developer.salesforce.com/tools/vscode/en/localdev/set-up-lwc-local-dev).', - force_lightning_lwc_start_addr_in_use: - "The local development server can't start because the address is already in use. To fix, try one of these options:\n 1) Stop the local dev server running on any another instance.\n or 2) Change the default port [Configuration for Projects (Optional)](https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.get_started_local_dev_setup).\n 3) Kill the process running on the specified port.", - force_lightning_lwc_inactive_scratch_org: - 'The local development server can\'t start because your scratch org is not active. Run "SFDX: Create a Default Scratch Org" to create a scratch org, or run "SFDX: Set a Default Org" to select an active scratch org.', - force_lightning_lwc_start_failed: - 'The local development server was not able to start.', - force_lightning_lwc_start_exited: - 'The local development server exited unexpectedly with code %s.', - force_lightning_lwc_start_already_running: - 'The local development server is already running.', - force_lightning_lwc_stop_text: 'SFDX: Stop Local Development Server', - force_lightning_lwc_stop_not_running: - 'The local development server is not running.', - force_lightning_lwc_stop_in_progress: 'Stopping local development server', - force_lightning_lwc_preview_text: 'SFDX: Preview Component Locally', - force_lightning_lwc_preview_file_undefined: - "Can't find the Lightning Web Components module. Check that %s is the correct file path.", - force_lightning_lwc_preview_file_nonexist: - "Can't find the Lightning Web Components module in %s. Check that the module exists.", - force_lightning_lwc_preview_unsupported: - "Something's not right with the filepath. The local development server doesn't recognize the Lightning Web Components module '%s.'", - force_lightning_lwc_preview_container_mode: - 'This command is only available in Salesforce Extensions for desktop because it requires local installs.', - force_lightning_lwc_open_text: - 'SFDX: Open Local Development Server in Browser', - prompt_option_open_browser: 'Open Browser', - prompt_option_restart: 'Restart', - force_lwc_test_run_description_text: 'Run LWC test(s)', force_lightning_lwc_test_navigate_to_test: 'SFDX: Navigate to Lightning Web Component Test', no_lwc_jest_found_text: @@ -63,40 +31,6 @@ export const messages = { default_task_name: 'LWC Test', task_windows_command_prompt_messaging: 'Default shell for running tasks is set to cmd.exe', - force_lightning_lwc_no_mobile_plugin: - 'To run this command, install the @salesforce/lwc-dev-mobile plugin.', - force_lightning_lwc_platform_selection: - 'Select the platform for previewing the component', - force_lightning_lwc_android_target_default: - 'Enter a name for the Android emulator (leave blank for default)', - force_lightning_lwc_ios_target_default: - 'Enter a name for the iOS simulator (leave blank for default)', - force_lightning_lwc_android_target_remembered: - "Enter a name for the Android emulator (leave blank for '%s')", - force_lightning_lwc_ios_target_remembered: - "Enter a name for the iOS simulator (leave blank for '%s')", - force_lightning_lwc_operation_cancelled: - 'Preview operation cancelled by user.', - force_lightning_lwc_ios_label: 'Use iOS Simulator', - force_lightning_lwc_ios_description: 'Preview component on iOS', - force_lightning_lwc_android_label: 'Use Android Emulator', - force_lightning_lwc_android_description: 'Preview component on Android', - force_lightning_lwc_android_failure: "Failed to start Android Emulator '%s'.", - force_lightning_lwc_ios_failure: "Failed to start iOS Simulator '%s'.", - force_lightning_lwc_android_start: "Starting Android Emulator '%s'.", - force_lightning_lwc_ios_start: "Starting iOS Simulator '%s'.", - force_lightning_lwc_browserapp_label: 'Browser', - force_lightning_lwc_browserapp_description: 'Your mobile browser.', - force_lightning_lwc_preview_create_virtual_device_label: 'New...', - force_lightning_lwc_preview_create_virtual_device_detail: - 'Create a Virtual Device', - force_lightning_lwc_preview_select_virtual_device: - 'Select a Virtual Device...', - force_lightning_lwc_preview_select_target_app: - 'Select a Target Application...', - force_lightning_lwc_preview_desktop_label: 'Use Desktop Browser', - force_lightning_lwc_preview_desktop_description: - 'Preview component on desktop browser', lwc_output_channel_name: 'LWC Extension', force_lightning_lwc_no_redhat_extension_found: 'Salesforce js-meta.xml IntelliSense requires the Red Hat XML extension', diff --git a/packages/salesforcedx-vscode-lwc/src/service/devServerService.ts b/packages/salesforcedx-vscode-lwc/src/service/devServerService.ts deleted file mode 100644 index 78ba9724f9..0000000000 --- a/packages/salesforcedx-vscode-lwc/src/service/devServerService.ts +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2019, salesforce.com, inc. - * All rights reserved. - * Licensed under the BSD 3-Clause license. - * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause - */ -import stripAnsi from 'strip-ansi'; -import { - DEV_SERVER_BASE_URL_REGEX, - DEV_SERVER_DEFAULT_BASE_URL, - DEV_SERVER_PREVIEW_ROUTE -} from '../commands/commandConstants'; - -export interface ServerHandler { - stop(): Promise; -} - -export class DevServerService { - private static _instance: DevServerService; - - public static get instance() { - if (DevServerService._instance === undefined) { - DevServerService._instance = new DevServerService(); - } - return DevServerService._instance; - } - - private handlers: Set = new Set(); - private baseUrl: string = DEV_SERVER_DEFAULT_BASE_URL; - - public isServerHandlerRegistered() { - return this.handlers.size > 0; - } - - public registerServerHandler(handler: ServerHandler) { - this.handlers.add(handler); - } - - public clearServerHandler(handler: ServerHandler) { - if (handler) { - this.handlers.delete(handler); - } - } - - public getServerHandlers() { - return [...this.handlers]; - } - - public async stopServer() { - if (this.handlers.size > 0) { - const promises = [...this.handlers].map(handler => handler.stop()); - await Promise.all(promises); - this.handlers.clear(); - console.log('successfully stopped lwc dev server(s)'); - } else { - console.log('lwc dev server was not running'); - } - } - - public getBaseUrl(): string { - return this.baseUrl; - } - - public setBaseUrlFromDevServerUpMessage(data: string) { - const sanitizedData = stripAnsi(data); - if (sanitizedData.match(DEV_SERVER_BASE_URL_REGEX)) { - this.baseUrl = sanitizedData.match(DEV_SERVER_BASE_URL_REGEX)![0]; - } - } - - public getComponentPreviewUrl(componentName: string): string { - return `${this.baseUrl}/${DEV_SERVER_PREVIEW_ROUTE}/${componentName}`; - } -} diff --git a/packages/salesforcedx-vscode-lwc/src/service/previewService.ts b/packages/salesforcedx-vscode-lwc/src/service/previewService.ts deleted file mode 100644 index 0ee3a7894a..0000000000 --- a/packages/salesforcedx-vscode-lwc/src/service/previewService.ts +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2020, salesforce.com, inc. - * All rights reserved. - * Licensed under the BSD 3-Clause license. - * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause - */ -import { PlatformName } from '../commands/forceLightningLwcPreview'; -import { WorkspaceUtils } from '../util/workspaceUtils'; - -export class PreviewService { - private rememberDeviceKey = 'preview.rememberDevice'; - private logLevelKey = 'preview.logLevel'; - private defaultLogLevel = 'warn'; - - private static _instance: PreviewService; - - public static get instance() { - if (PreviewService._instance === undefined) { - PreviewService._instance = new PreviewService(); - } - return PreviewService._instance; - } - - public getRememberedDevice(platform: keyof typeof PlatformName): string { - const store = WorkspaceUtils.instance.getGlobalStore(); - if (store === undefined) { - return ''; - } - - return store.get(`last${platform}Device`) || ''; - } - - public updateRememberedDevice( - platform: keyof typeof PlatformName, - deviceName: string - ): void { - const store = WorkspaceUtils.instance.getGlobalStore(); - if (store !== undefined) { - store.update(`last${platform}Device`, deviceName); - } - } - - public isRememberedDeviceEnabled(): boolean { - return WorkspaceUtils.instance - .getWorkspaceSettings() - .get(this.rememberDeviceKey, false); - } - - public getLogLevel(): string { - return ( - WorkspaceUtils.instance.getWorkspaceSettings().get(this.logLevelKey) || - this.defaultLogLevel - ); - } -} diff --git a/packages/salesforcedx-vscode-lwc/test/jest/commands/forceLightningLwcPreview.test.ts b/packages/salesforcedx-vscode-lwc/test/jest/commands/forceLightningLwcPreview.test.ts deleted file mode 100644 index 265f2a9a4c..0000000000 --- a/packages/salesforcedx-vscode-lwc/test/jest/commands/forceLightningLwcPreview.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2023, salesforce.com, inc. - * All rights reserved. - * Licensed under the BSD 3-Clause license. - * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause - */ - -import { getPreview } from '../../../src/commands/forceLightningLwcPreview'; - -describe('forceLightningLwcPreview', () => { - describe('not in container mode', () => { - it('uses default preview', async () => { - const preview = getPreview(); - expect(preview.name).toBe('lwcPreview'); - }); - }); - - describe('in container mode', () => { - beforeAll(() => { - process.env.SF_CONTAINER_MODE = 'true'; - }); - - afterAll(() => { - delete process.env.SF_CONTAINER_MODE; - }); - - it('uses container mode preview', async () => { - const preview = getPreview(); - expect(preview.name).toBe('lwcPreviewContainerMode'); - }); - }); -}); diff --git a/packages/salesforcedx-vscode-lwc/test/unit/commands/commandConstants.test.ts b/packages/salesforcedx-vscode-lwc/test/unit/commands/commandConstants.test.ts deleted file mode 100644 index 512027d2ae..0000000000 --- a/packages/salesforcedx-vscode-lwc/test/unit/commands/commandConstants.test.ts +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (c) 2019, salesforce.com, inc. - * All rights reserved. - * Licensed under the BSD 3-Clause license. - * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause - */ -import { expect } from 'chai'; -import { - DEV_SERVER_DEFAULT_BASE_URL -} from '../../../src/commands/commandConstants'; - -describe('force:lightning:lwc:start constants', () => { - describe('base url', () => { - it('should include localhost', async () => { - expect(DEV_SERVER_DEFAULT_BASE_URL).to.include('localhost'); - }); - }); -}); diff --git a/packages/salesforcedx-vscode-lwc/test/unit/service/devServerService.test.ts b/packages/salesforcedx-vscode-lwc/test/unit/service/devServerService.test.ts deleted file mode 100644 index 5ddda40b59..0000000000 --- a/packages/salesforcedx-vscode-lwc/test/unit/service/devServerService.test.ts +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright (c) 2019, salesforce.com, inc. - * All rights reserved. - * Licensed under the BSD 3-Clause license. - * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause - */ - -import { expect } from 'chai'; -import * as sinon from 'sinon'; -import { DEV_SERVER_DEFAULT_BASE_URL } from '../../../src/commands/commandConstants'; -import { DevServerService } from '../../../src/service/devServerService'; - -// tslint:disable:no-unused-expression -describe('DevServerService', () => { - describe('get instance', () => { - it('return the same instance', async () => { - const instance = DevServerService.instance; - const instanceAgain = DevServerService.instance; - expect(instance).to.exist; - expect(instance).to.equal(instanceAgain); - }); - }); - - describe('registerServerHandler', () => { - it('registers the handler', () => { - const instance = new DevServerService(); - const handler = { - stop: sinon.spy() - }; - instance.registerServerHandler(handler); - expect(instance.isServerHandlerRegistered()).to.be.true; - }); - }); - - describe('isServerHandlerRegistered', () => { - it('returns false if nothing is registered', () => { - const instance = new DevServerService(); - expect(instance.isServerHandlerRegistered()).to.be.false; - }); - - it('returns true if a handler is registered', () => { - const instance = new DevServerService(); - const handler = { - stop: sinon.spy() - }; - instance.registerServerHandler(handler); - expect(instance.isServerHandlerRegistered()).to.be.true; - }); - }); - - describe('clearServerHandler', () => { - it('clears the server handler', () => { - const instance = new DevServerService(); - const handler = { - stop: sinon.spy() - }; - - instance.registerServerHandler(handler); - expect( - instance.isServerHandlerRegistered(), - 'expected the server handler to be registered' - ).to.be.true; - - instance.clearServerHandler(handler); - expect( - instance.isServerHandlerRegistered(), - 'expected the server handler to be cleared' - ).to.be.false; - }); - - it('clears the specified handler', () => { - const instance = new DevServerService(); - - const handler1 = { - stop: sinon.spy() - }; - const handler2 = { - stop: sinon.spy() - }; - - instance.registerServerHandler(handler1); - instance.registerServerHandler(handler2); - instance.clearServerHandler(handler1); - - const handlers = instance.getServerHandlers(); - - expect(handlers).to.have.lengthOf(1); - expect(handlers[0]).to.equal(handler2); - }); - - it('does not throw an error if handler is not registered', () => { - const instance = new DevServerService(); - const handler = { - stop: sinon.spy() - }; - instance.clearServerHandler(handler); - expect(instance.isServerHandlerRegistered()).to.be.false; - }); - }); - - describe('stopServer', () => { - it('calls `stop` on the handler', async () => { - const instance = new DevServerService(); - const stopMethod = sinon.spy(); - const handler = { stop: stopMethod }; - - instance.registerServerHandler(handler); - await instance.stopServer(); - - sinon.assert.calledOnce(stopMethod); - }); - - it('clears the server handler', async () => { - const instance = new DevServerService(); - const handler = { - stop: sinon.spy() - }; - - instance.registerServerHandler(handler); - await instance.stopServer(); - - expect(instance.isServerHandlerRegistered()).to.be.false; - }); - - it('does not throw an error if nothing is registered', async () => { - const instance = new DevServerService(); - await instance.stopServer(); - expect(instance.isServerHandlerRegistered()).to.be.false; - }); - - it('sets the correct url with port from server startup response', async () => { - const instance = new DevServerService(); - instance.setBaseUrlFromDevServerUpMessage( - 'Server up on http://localhost:1234' - ); - expect(instance.getBaseUrl()).to.equal('http://localhost:1234'); - }); - - it('sets the correct url from server startup response containing ansi codes', async () => { - const instance = new DevServerService(); - instance.setBaseUrlFromDevServerUpMessage( - 'Server up on http://localhost:3334\n' - ); - expect(instance.getBaseUrl()).to.equal('http://localhost:3334'); - }); - - it('keeps the default url with port as fall back', async () => { - const instance = new DevServerService(); - instance.setBaseUrlFromDevServerUpMessage( - 'Sever up with no url information \n some other info' - ); - expect(instance.getBaseUrl()).to.equal(DEV_SERVER_DEFAULT_BASE_URL); - }); - - it('retrieves the correct preview component path', async () => { - const instance = new DevServerService(); - expect(instance.getComponentPreviewUrl('HelloWorld')).to.equal( - 'http://localhost:3333/preview/HelloWorld' - ); - }); - }); -}); diff --git a/packages/salesforcedx-vscode-lwc/test/vscode-integration/commands/commandUtils.test.ts b/packages/salesforcedx-vscode-lwc/test/vscode-integration/commands/commandUtils.test.ts deleted file mode 100644 index f92705d2c1..0000000000 --- a/packages/salesforcedx-vscode-lwc/test/vscode-integration/commands/commandUtils.test.ts +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2019, salesforce.com, inc. - * All rights reserved. - * Licensed under the BSD 3-Clause license. - * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause - */ - -import * as sinon from 'sinon'; -import { showError } from '../../../src/commands/commandUtils'; -import { - ChannelService, - notificationService -} from '@salesforce/salesforcedx-utils-vscode'; -import { telemetryService } from '../../../src/telemetry'; - -describe('command utilities', () => { - describe('showError', () => { - it('should call the telemetry service', async () => { - const spy = sinon.spy(telemetryService, 'sendException'); - - showError( - new Error('test error message'), - 'force_lightning_lwc_start_test', - 'SFDX: Start Local Development Server' - ); - - sinon.assert.calledOnce(spy); - sinon.assert.calledWith( - spy, - `force_lightning_lwc_start_test_error`, - 'test error message' - ); - - spy.restore(); - }); - - it('should call the notification service', () => { - const spy = sinon.spy(notificationService, 'showErrorMessage'); - - showError( - new Error('test error message'), - 'force_lightning_lwc_start_test', - 'SFDX: Start Local Development Server' - ); - - sinon.assert.calledTwice(spy); - sinon.assert.calledWith( - spy, - sinon.match('SFDX: Start Local Development Server') - ); - - spy.restore(); - }); - - it('should send a message to the channel', () => { - const spy = sinon.spy(ChannelService.prototype, 'appendLine'); - - showError( - new Error('test error message'), - 'force_lightning_lwc_start_test', - 'SFDX: Start Local Development Server' - ); - - sinon.assert.calledOnce(spy); - sinon.assert.calledWith(spy, `Error: test error message`); - - spy.restore(); - }); - - it('should show the channel output', () => { - const spy = sinon.spy(ChannelService.prototype, 'showChannelOutput'); - - showError( - new Error('test error message'), - 'force_lightning_lwc_start_test', - 'SFDX: Start Local Development Server' - ); - - sinon.assert.calledOnce(spy); - - spy.restore(); - }); - }); -}); diff --git a/packages/salesforcedx-vscode-lwc/test/vscode-integration/commands/forceLightningLwcOpen.test.ts b/packages/salesforcedx-vscode-lwc/test/vscode-integration/commands/forceLightningLwcOpen.test.ts deleted file mode 100644 index c9a7348cb9..0000000000 --- a/packages/salesforcedx-vscode-lwc/test/vscode-integration/commands/forceLightningLwcOpen.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2019, salesforce.com, inc. - * All rights reserved. - * Licensed under the BSD 3-Clause license. - * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause - */ - -import * as sinon from 'sinon'; -import { SinonSandbox, SinonStub } from 'sinon'; -import * as vscode from 'vscode'; -import { DEV_SERVER_DEFAULT_BASE_URL } from '../../../src/commands/commandConstants'; -import * as commandUtils from '../../../src/commands/commandUtils'; -import { forceLightningLwcOpen } from '../../../src/commands/forceLightningLwcOpen'; -import { DevServerService } from '../../../src/service/devServerService'; - -describe('forceLightningLwcOpen', () => { - let sandbox: SinonSandbox; - let devServiceStub: any; - let openBrowserStub: SinonStub<[string], Thenable>; - - beforeEach(() => { - sandbox = sinon.createSandbox(); - devServiceStub = sinon.createStubInstance(DevServerService); - sandbox.stub(DevServerService, 'instance').get(() => devServiceStub); - openBrowserStub = sandbox.stub(commandUtils, 'openBrowser'); - }); - - afterEach(() => { - sandbox.restore(); - }); - - it('calls openBrowser when a server is already running', async () => { - devServiceStub.isServerHandlerRegistered.returns(true); - devServiceStub.getBaseUrl.returns(DEV_SERVER_DEFAULT_BASE_URL); - - await forceLightningLwcOpen(); - - sinon.assert.calledOnce(openBrowserStub); - sinon.assert.calledWith( - openBrowserStub, - sinon.match(DEV_SERVER_DEFAULT_BASE_URL) - ); - }); - - it('starts the server if it is not running yet', async () => { - devServiceStub.isServerHandlerRegistered.returns(false); - - const executeCommandStub = sandbox.stub(vscode.commands, 'executeCommand'); - - await forceLightningLwcOpen(); - - sinon.assert.calledOnce(executeCommandStub); - sinon.assert.calledWith( - executeCommandStub, - 'sfdx.force.lightning.lwc.start' - ); - }); -}); diff --git a/packages/salesforcedx-vscode-lwc/test/vscode-integration/commands/forceLightningLwcPreview.test.ts b/packages/salesforcedx-vscode-lwc/test/vscode-integration/commands/forceLightningLwcPreview.test.ts deleted file mode 100644 index d11e0439af..0000000000 --- a/packages/salesforcedx-vscode-lwc/test/vscode-integration/commands/forceLightningLwcPreview.test.ts +++ /dev/null @@ -1,1431 +0,0 @@ -/* - * Copyright (c) 2019, salesforce.com, inc. - * All rights reserved. - * Licensed under the BSD 3-Clause license. - * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause - */ - -import { SfdxCommandlet } from '@salesforce/salesforcedx-utils-vscode'; -import { - CliCommandExecution, - CliCommandExecutor, - Command, - CommandBuilder, - CommandExecution, - CommandOutput, - SfdxCommandBuilder -} from '@salesforce/salesforcedx-utils-vscode'; -import { CancellationToken } from '@salesforce/salesforcedx-utils-vscode'; -import { expect } from 'chai'; -import * as fs from 'fs'; -import * as path from 'path'; -import { Subject } from 'rxjs/Subject'; -import * as sinon from 'sinon'; -import { SinonSandbox, SinonStub } from 'sinon'; -import * as vscode from 'vscode'; -import URI from 'vscode-uri'; -import { - DEV_SERVER_PREVIEW_ROUTE, - DEV_SERVER_DEFAULT_BASE_URL -} from '../../../src/commands/commandConstants'; -import * as commandUtils from '../../../src/commands/commandUtils'; -import { - DeviceQuickPickItem, - directoryLevelUp, - getProjectRootDirectory, - lwcPreview, - PlatformName, - platformOptions -} from '../../../src/commands/forceLightningLwcPreview'; -import { nls } from '../../../src/messages'; -import { DevServerService } from '../../../src/service/devServerService'; -import { WorkspaceUtils } from '../../../src/util/workspaceUtils'; -import { - ChannelService, - notificationService -} from '@salesforce/salesforcedx-utils-vscode'; - -const sfdxDeviceListCommand = 'force:lightning:local:device:list'; -const sfdxMobilePreviewCommand = 'force:lightning:lwc:preview'; -const rememberDeviceKey = 'preview.rememberDevice'; -const logLevelKey = 'preview.logLevel'; -const defaultLogLevel = 'warn'; -const androidSuccessString = 'Launching... Opening Browser'; - -const iOSPickedDevice: DeviceQuickPickItem = { - label: 'iPhone 8', - detail: 'iOS 13.3', - name: 'iPhone 8' -}; -const iOSDeviceListJson = ` - { - "status":0, - "result":[ - { - "name":"iPhone 8", - "udid":"6CC16032-2671-4BD2-8FF1-0E314945010C", - "state":"Shutdown", - "runtimeId":"iOS 13.3", - "isAvailable":true - }, - { - "name":"LWCSimulator", - "udid":"09D522C8-DC85-4259-AD15-15D36672D2EA", - "state":"Shutdown", - "runtimeId":"iOS 13.3", - "isAvailable":true - } - ] - } -`; - -const androidPickedDevice: DeviceQuickPickItem = { - label: 'Pixel API 29', - detail: 'Google APIs, API 29', - name: 'Pixel_API_29' -}; -const androidDeviceListJson = ` - { - "status":0, - "result":[ - { - "name":"emu2", - "displayName":"emu2", - "deviceName":"pixel", - "path":"/Users/maliroteh/.android/avd/emu2.avd", - "target":"Default Android System Image", - "api":"API 29" - }, - { - "name":"Pixel_API_29", - "displayName":"Pixel API 29", - "deviceName":"pixel", - "path":"/Users/maliroteh/.android/avd/Pixel_API_29.avd", - "target":"Google APIs", - "api":"API 29" - } - ] - } -`; - -const pickedApp: vscode.QuickPickItem = { - label: 'LWC Test App', - detail: 'com.salesforce.mobile-tooling.lwc-test-app' -}; -const appConfigFileJson = ` -{ - "apps": { - "ios": [ - { - "id": "com.salesforce.mobile-tooling.lwc-test-app", - "name": "LWC Test App", - "get_app_bundle": "configure_test_app.js", - "launch_arguments": [ - { "name": "arg1", "value": "val1" }, - { "name": "arg2", "value": "val2" } - ] - } - ], - "android": [ - { - "id": "com.salesforce.mobile-tooling.lwc-test-app", - "name": "LWC Test App", - "activity": ".MainActivity", - "get_app_bundle": "configure_test_app.js", - "launch_arguments": [ - { "name": "arg1", "value": "val1" }, - { "name": "arg2", "value": "val2" } - ] - } - ] - } -} -`; - -describe('forceLightningLwcPreview - lwcPreview ', () => { - let sandbox: SinonSandbox; - let devServiceStub: any; - let openBrowserStub: SinonStub<[string], Thenable>; - let existsSyncStub: sinon.SinonStub<[fs.PathLike], boolean>; - let lstatSyncStub: sinon.SinonStub; - let showErrorMessageStub: sinon.SinonStub; - let isSFContainerModeStub: sinon.SinonStub; - const root = /^win32/.test(process.platform) ? 'c:\\' : '/var'; - const mockLwcFileDirectory = path.join( - root, - 'project', - 'force-app', - 'main', - 'default', - 'lwc', - 'foo' - ); - const mockLwcFileDirectoryUri = URI.file(mockLwcFileDirectory); - const mockLwcFilePath = path.join(mockLwcFileDirectory, 'foo.js'); - const mockLwcFilePathUri = URI.file(mockLwcFilePath); - const notLwcModulePath = path.join(root, 'foo'); - const notLwcModulePathUri = URI.file(notLwcModulePath); - const nonExistentPath = path.join(root, 'foo'); - const nonExistentPathUri = URI.file(nonExistentPath); - let showQuickPickStub: sinon.SinonStub; - let showInputBoxStub: sinon.SinonStub; - let getConfigurationStub: sinon.SinonStub; - let getGlobalStoreStub: sinon.SinonStub; - let cmdWithArgSpy: sinon.SinonSpy<[string], CommandBuilder>; - let cmdWithFlagSpy: sinon.SinonSpy<[string, string], CommandBuilder>; - let mobileExecutorStub: sinon.SinonStub< - [(CancellationToken | undefined)?], - CliCommandExecution | MockExecution - >; - let commandOutputStub: sinon.SinonStub<[CommandExecution], Promise>; - let mockExecution: MockExecution; - let showWarningMessageSpy: sinon.SinonSpy; - let successInfoMessageSpy: sinon.SinonSpy; - let streamCommandOutputSpy: sinon.SinonSpy; - let appendLineSpy: sinon.SinonSpy; - - const desktopQuickPick = platformOptions[0]; - const androidQuickPick = platformOptions[1]; - const iOSQuickPick = platformOptions[2]; - const rememberedAndroidDevice = 'rememberedAndroid'; - const rememberediOSDevice = 'rememberediOS'; - - class MockMemento implements vscode.Memento { - keys(): readonly string[] { - throw new Error('Method not implemented.'); - } - public get(key: string): T | undefined { - switch (key) { - case `last${PlatformName.Android}Device`: - return (rememberedAndroidDevice as unknown) as T; - case `last${PlatformName.iOS}Device`: - return (rememberediOSDevice as unknown) as T; - default: - return undefined; - } - } - public update(key: string, value: any): Thenable { - return Promise.resolve(); - } - } - - class MockWorkspace implements vscode.WorkspaceConfiguration { - // tslint:disable-next-line:member-access - shouldRemember = false; - // tslint:disable-next-line:member-access - loglevel = defaultLogLevel; - - constructor(shouldRemember: boolean, loglevel?: string) { - this.shouldRemember = shouldRemember; - if (loglevel !== undefined) { - this.loglevel = loglevel; - } - } - - readonly [key: string]: any; - public get(section: string): T | undefined; - public get(section: string, defaultValue: T): T; - public get(section: any, defaultValue?: any) { - switch (section) { - case logLevelKey: - return this.loglevel; - case rememberDeviceKey: - return this.shouldRemember; - default: - return undefined; - } - } - public has(section: string): boolean { - return this.shouldRemember; - } - public inspect( - section: string - ): - | { - key: string; - defaultValue?: T | undefined; - globalValue?: T | undefined; - workspaceValue?: T | undefined; - workspaceFolderValue?: T | undefined; - } - | undefined { - return undefined; - } - public update( - section: string, - value: any, - configurationTarget?: boolean | vscode.ConfigurationTarget | undefined - ): Thenable { - return Promise.resolve(); - } - } - - class MockExecution implements CommandExecution { - public command: Command; - public processExitSubject: Subject; - public processErrorSubject: Subject; - public stdoutSubject: Subject; - public stderrSubject: Subject; - - constructor(command: Command) { - this.command = command; - this.processExitSubject = new Subject(); - this.processErrorSubject = new Subject(); - this.stdoutSubject = new Subject(); - this.stderrSubject = new Subject(); - } - - public killExecution(): Promise { - return Promise.resolve(); - } - } - - beforeEach(() => { - sandbox = sinon.createSandbox(); - devServiceStub = sinon.createStubInstance(DevServerService); - sandbox.stub(DevServerService, 'instance').get(() => devServiceStub); - openBrowserStub = sandbox.stub(commandUtils, 'openBrowser'); - existsSyncStub = sandbox.stub(fs, 'existsSync'); - lstatSyncStub = sandbox.stub(fs, 'lstatSync'); - showErrorMessageStub = sandbox.stub( - notificationService, - 'showErrorMessage' - ); - showQuickPickStub = sandbox.stub(vscode.window, 'showQuickPick'); - showInputBoxStub = sandbox.stub(vscode.window, 'showInputBox'); - getConfigurationStub = sandbox.stub( - WorkspaceUtils.prototype, - 'getWorkspaceSettings' - ); - getGlobalStoreStub = sandbox.stub( - WorkspaceUtils.prototype, - 'getGlobalStore' - ); - cmdWithArgSpy = sandbox.spy(SfdxCommandBuilder.prototype, 'withArg'); - cmdWithFlagSpy = sandbox.spy(SfdxCommandBuilder.prototype, 'withFlag'); - mockExecution = new MockExecution(new SfdxCommandBuilder().build()); - mobileExecutorStub = sinon.stub(CliCommandExecutor.prototype, 'execute'); - mobileExecutorStub.returns(mockExecution); - commandOutputStub = sinon.stub(CommandOutput.prototype, 'getCmdResult'); - commandOutputStub.returns(Promise.resolve('{}')); - showWarningMessageSpy = sandbox.spy(vscode.window, 'showWarningMessage'); - successInfoMessageSpy = sandbox.spy( - vscode.window, - 'showInformationMessage' - ); - streamCommandOutputSpy = sandbox.stub( - ChannelService.prototype, - 'streamCommandOutput' - ); - appendLineSpy = sinon.spy(ChannelService.prototype, 'appendLine'); - }); - - afterEach(() => { - sinon.restore(); - sandbox.restore(); - cmdWithArgSpy.restore(); - cmdWithFlagSpy.restore(); - showWarningMessageSpy.restore(); - successInfoMessageSpy.restore(); - mobileExecutorStub.restore(); - commandOutputStub.restore(); - streamCommandOutputSpy.restore(); - appendLineSpy.restore(); - }); - - function mockFileExists(mockPath: string) { - existsSyncStub.callsFake(fsPath => { - if ( - path.normalize(fsPath.toString()).toLowerCase() === - path.normalize(mockPath).toLowerCase() - ) { - return true; - } else { - return false; - } - }); - } - - it('exists sync called with correct path', async () => { - // Returns false for remembered device settings. - getConfigurationStub.returns(new MockWorkspace(false)); - devServiceStub.isServerHandlerRegistered.returns(true); - mockFileExists(mockLwcFilePath); - - lstatSyncStub.returns({ - isDirectory() { - return false; - } - } as fs.Stats); - showQuickPickStub.resolves(desktopQuickPick); - await lwcPreview(mockLwcFilePathUri); - - sinon.assert.calledOnce(openBrowserStub); - sinon.assert.calledOnce(existsSyncStub); - sinon.assert.calledWith( - existsSyncStub, - /^win32/.test(process.platform) - ? 'c:\\project\\force-app\\main\\default\\lwc\\foo\\foo.js' - : '/var/project/force-app/main/default/lwc/foo/foo.js' - ); - }); - - it('calls openBrowser with the correct url for files', async () => { - devServiceStub.isServerHandlerRegistered.returns(true); - devServiceStub.getBaseUrl.returns(DEV_SERVER_DEFAULT_BASE_URL); - devServiceStub.getComponentPreviewUrl.returns( - 'http://localhost:3333/preview/c/foo' - ); - getConfigurationStub.returns(new MockWorkspace(false)); - existsSyncStub.returns(true); - lstatSyncStub.returns({ - isDirectory() { - return false; - } - } as fs.Stats); - showQuickPickStub.resolves(desktopQuickPick); - - await lwcPreview(mockLwcFilePathUri); - - sinon.assert.calledWith( - devServiceStub.getComponentPreviewUrl, - sinon.match('c/foo') - ); - sinon.assert.calledOnce(openBrowserStub); - sinon.assert.calledWith( - openBrowserStub, - sinon.match( - `${DEV_SERVER_DEFAULT_BASE_URL}/${DEV_SERVER_PREVIEW_ROUTE}/c/foo` - ) - ); - }); - - it('calls openBrowser with the correct url for directories', async () => { - devServiceStub.isServerHandlerRegistered.returns(true); - devServiceStub.getComponentPreviewUrl.returns( - 'http://localhost:3333/preview/c/foo' - ); - mockFileExists(mockLwcFileDirectory); - getConfigurationStub.returns(new MockWorkspace(false)); - existsSyncStub.returns(true); - lstatSyncStub.returns({ - isDirectory() { - return true; - } - } as fs.Stats); - showQuickPickStub.resolves(desktopQuickPick); - - await lwcPreview(mockLwcFileDirectoryUri); - - sinon.assert.calledWith( - devServiceStub.getComponentPreviewUrl, - sinon.match('c/foo') - ); - sinon.assert.calledOnce(openBrowserStub); - sinon.assert.calledWith( - openBrowserStub, - sinon.match('http://localhost:3333/preview/c/foo') - ); - }); - - it('starts the server if it is not running when desktop selected', async () => { - devServiceStub.isServerHandlerRegistered.returns(false); - mockFileExists(mockLwcFilePath); - existsSyncStub.returns(true); - lstatSyncStub.returns({ - isDirectory() { - return true; - } - } as fs.Stats); - showQuickPickStub.resolves(desktopQuickPick); - const commandletStub = sandbox.stub(SfdxCommandlet.prototype, 'run'); - await lwcPreview(mockLwcFilePathUri); - - sinon.assert.calledOnce(commandletStub); - }); - - it('starts the server if it is not running when Android selected', async () => { - await doStartServerTest(true); - }); - - it('starts the server if it is not running when iOS selected', async () => { - await doStartServerTest(false); - }); - - async function doStartServerTest(isAndroid: Boolean) { - const platform = isAndroid ? PlatformName.Android : PlatformName.iOS; - const deviceName = isAndroid ? 'SFDXEmulator' : 'SFDXSimulator'; - devServiceStub.isServerHandlerRegistered.returns(false); - mockFileExists(mockLwcFilePath); - existsSyncStub.returns(true); - lstatSyncStub.returns({ - isDirectory() { - return false; - } - } as fs.Stats); - getConfigurationStub.returns(new MockWorkspace(false)); - getGlobalStoreStub.returns(new MockMemento()); - showQuickPickStub.resolves(isAndroid ? androidQuickPick : iOSQuickPick); - showInputBoxStub.resolves(''); - const commandletStub = sandbox.stub(SfdxCommandlet.prototype, 'run'); - await lwcPreview(mockLwcFilePathUri); - - if (isAndroid) { - mockExecution.stdoutSubject.next(androidSuccessString); - } else { - mockExecution.processExitSubject.next(0); - } - - sinon.assert.calledOnce(showQuickPickStub); - sinon.assert.calledOnce(showInputBoxStub); - sinon.assert.calledOnce(commandletStub); - expect(cmdWithArgSpy.callCount).to.equal(2); - expect(cmdWithArgSpy.getCall(0).args[0]).equals(sfdxDeviceListCommand); - expect(cmdWithArgSpy.getCall(1).args[0]).equals(sfdxMobilePreviewCommand); - expect(cmdWithFlagSpy.callCount).to.equal(7); - expect(cmdWithFlagSpy.getCall(0).args).to.have.same.members([ - '-p', - platform - ]); - expect(cmdWithFlagSpy.getCall(1).args).to.have.same.members([ - '-p', - platform - ]); - expect(cmdWithFlagSpy.getCall(2).args).to.have.same.members([ - '-t', - deviceName - ]); - expect(cmdWithFlagSpy.getCall(3).args).to.have.same.members([ - '-n', - 'c/foo' - ]); - expect(cmdWithFlagSpy.getCall(4).args).to.have.same.members([ - '-a', - 'browser' - ]); - expect(cmdWithFlagSpy.getCall(5).args).to.have.same.members([ - '-d', - mockLwcFileDirectory - ]); - expect(cmdWithFlagSpy.getCall(6).args).to.have.same.members([ - '--loglevel', - 'warn' - ]); - sinon.assert.calledTwice(mobileExecutorStub); // device list + preview - expect(successInfoMessageSpy.callCount).to.equal(1); - expect( - successInfoMessageSpy.calledWith( - isAndroid - ? nls.localize('force_lightning_lwc_android_start', deviceName) - : nls.localize('force_lightning_lwc_ios_start', deviceName) - ) - ); - } - - it('shows an error when source path is not recognized as an lwc module file', async () => { - devServiceStub.isServerHandlerRegistered.returns(true); - mockFileExists(notLwcModulePath); - existsSyncStub.returns(true); - lstatSyncStub.returns({ - isDirectory() { - return false; - } - } as fs.Stats); - showQuickPickStub.resolves(desktopQuickPick); - - await lwcPreview(notLwcModulePathUri); - - sinon.assert.calledWith( - showErrorMessageStub, - sinon.match( - nls.localize( - `force_lightning_lwc_preview_unsupported`, - /^win32/.test(process.platform) ? 'c:\\foo' : '/var/foo' - ) - ) - ); - }); - - it('shows an error when source path does not exist', async () => { - mockFileExists(nonExistentPath); - devServiceStub.isServerHandlerRegistered.returns(true); - existsSyncStub.returns(false); - showQuickPickStub.resolves(desktopQuickPick); - - await lwcPreview(nonExistentPathUri); - - sinon.assert.calledWith( - showErrorMessageStub, - sinon.match( - nls.localize( - `force_lightning_lwc_preview_file_nonexist`, - /^win32/.test(process.platform) ? 'c:\\foo' : '/var/foo' - ) - ) - ); - }); - - it('shows an error message when open browser throws an error', async () => { - devServiceStub.isServerHandlerRegistered.returns(true); - mockFileExists(mockLwcFileDirectory); - existsSyncStub.returns(true); - lstatSyncStub.returns({ - isDirectory() { - return true; - } - } as fs.Stats); - - showQuickPickStub.resolves(desktopQuickPick); - openBrowserStub.throws('test error'); - - await lwcPreview(mockLwcFileDirectoryUri); - - const commandName = nls.localize(`force_lightning_lwc_preview_text`); - sinon.assert.calledTwice(showErrorMessageStub); - sinon.assert.calledWith( - showErrorMessageStub, - sinon.match(nls.localize('command_failure', commandName)) - ); - }); - - it('calls SFDX preview with the correct url for files', async () => { - devServiceStub.isServerHandlerRegistered.returns(true); - existsSyncStub.returns(true); - lstatSyncStub.returns({ - isDirectory() { - return false; - } - } as fs.Stats); - - getConfigurationStub.returns(new MockWorkspace(false)); - getGlobalStoreStub.returns(new MockMemento()); - showQuickPickStub.resolves(androidQuickPick); - showInputBoxStub.resolves(''); - await lwcPreview(mockLwcFilePathUri); - mockExecution.stdoutSubject.next(androidSuccessString); - - sinon.assert.calledOnce(showQuickPickStub); - sinon.assert.calledOnce(showInputBoxStub); - expect(cmdWithArgSpy.callCount).to.equal(2); - expect(cmdWithArgSpy.getCall(0).args[0]).equals(sfdxDeviceListCommand); - expect(cmdWithArgSpy.getCall(1).args[0]).equals(sfdxMobilePreviewCommand); - expect(cmdWithFlagSpy.callCount).to.equal(7); - expect(cmdWithFlagSpy.getCall(0).args).to.have.same.members([ - '-p', - PlatformName.Android - ]); - expect(cmdWithFlagSpy.getCall(1).args).to.have.same.members([ - '-p', - PlatformName.Android - ]); - expect(cmdWithFlagSpy.getCall(2).args).to.have.same.members([ - '-t', - 'SFDXEmulator' - ]); - expect(cmdWithFlagSpy.getCall(3).args).to.have.same.members([ - '-n', - 'c/foo' - ]); - expect(cmdWithFlagSpy.getCall(4).args).to.have.same.members([ - '-a', - 'browser' - ]); - expect(cmdWithFlagSpy.getCall(5).args).to.have.same.members([ - '-d', - mockLwcFileDirectory - ]); - expect(cmdWithFlagSpy.getCall(6).args).to.have.same.members([ - '--loglevel', - 'warn' - ]); - sinon.assert.calledTwice(mobileExecutorStub); // device list + preview - expect(successInfoMessageSpy.callCount).to.equal(1); - }); - - it('calls SFDX preview with the correct url for directories', async () => { - devServiceStub.isServerHandlerRegistered.returns(true); - existsSyncStub.returns(true); - lstatSyncStub.returns({ - isDirectory() { - return true; - } - } as fs.Stats); - - getConfigurationStub.returns(new MockWorkspace(false)); - getGlobalStoreStub.returns(new MockMemento()); - showQuickPickStub.resolves(iOSQuickPick); - showInputBoxStub.resolves(''); - await lwcPreview(mockLwcFileDirectoryUri); - mockExecution.processExitSubject.next(0); - - sinon.assert.calledOnce(showQuickPickStub); - sinon.assert.calledOnce(showInputBoxStub); - expect(cmdWithArgSpy.callCount).to.equal(2); - expect(cmdWithArgSpy.getCall(0).args[0]).equals(sfdxDeviceListCommand); - expect(cmdWithArgSpy.getCall(1).args[0]).equals(sfdxMobilePreviewCommand); - expect(cmdWithFlagSpy.callCount).to.equal(7); - expect(cmdWithFlagSpy.getCall(0).args).to.have.same.members([ - '-p', - PlatformName.iOS - ]); - expect(cmdWithFlagSpy.getCall(1).args).to.have.same.members([ - '-p', - PlatformName.iOS - ]); - expect(cmdWithFlagSpy.getCall(2).args).to.have.same.members([ - '-t', - 'SFDXSimulator' - ]); - expect(cmdWithFlagSpy.getCall(3).args).to.have.same.members([ - '-n', - 'c/foo' - ]); - expect(cmdWithFlagSpy.getCall(4).args).to.have.same.members([ - '-a', - 'browser' - ]); - expect(cmdWithFlagSpy.getCall(5).args).to.have.same.members([ - '-d', - mockLwcFileDirectoryUri.fsPath - ]); - expect(cmdWithFlagSpy.getCall(6).args).to.have.same.members([ - '--loglevel', - 'warn' - ]); - sinon.assert.calledTwice(mobileExecutorStub); // device list + preview - expect(successInfoMessageSpy.callCount).to.equal(1); - }); - - it('shows an error when source path is not recognized as an lwc module file', async () => { - mockFileExists(notLwcModulePath); - existsSyncStub.returns(true); - lstatSyncStub.returns({ - isDirectory() { - return false; - } - } as fs.Stats); - - getConfigurationStub.returns(new MockWorkspace(false)); - getGlobalStoreStub.returns(new MockMemento()); - showQuickPickStub.resolves(androidQuickPick); - showInputBoxStub.resolves('test'); - await lwcPreview(notLwcModulePathUri); - - sinon.assert.calledWith( - showErrorMessageStub, - sinon.match( - nls.localize( - `force_lightning_lwc_preview_unsupported`, - /^win32/.test(process.platform) ? 'c:\\foo' : '/var/foo' - ) - ) - ); - sinon.assert.notCalled(mobileExecutorStub); - expect(successInfoMessageSpy.callCount).to.equal(0); - }); - - it('shows an error when source path does not exist', async () => { - mockFileExists(nonExistentPath); - existsSyncStub.returns(false); - getConfigurationStub.returns(new MockWorkspace(false)); - getGlobalStoreStub.returns(new MockMemento()); - showQuickPickStub.resolves(androidQuickPick); - showInputBoxStub.resolves(undefined); - await lwcPreview(nonExistentPathUri); - - sinon.assert.calledWith( - showErrorMessageStub, - sinon.match( - nls.localize( - `force_lightning_lwc_preview_file_nonexist`, - /^win32/.test(process.platform) ? 'c:\\foo' : '/var/foo' - ) - ) - ); - sinon.assert.notCalled(mobileExecutorStub); - expect(successInfoMessageSpy.callCount).to.equal(0); - }); - - it('calls SFDX preview with specified Android device name', async () => { - await doSpecifiedDeviceTest(true); - }); - - it('calls SFDX preview with specified iOS device name', async () => { - await doSpecifiedDeviceTest(false); - }); - - async function doSpecifiedDeviceTest(isAndroid: Boolean) { - const deviceName = isAndroid ? 'androidtestname' : 'iostestname'; - const platform = isAndroid ? PlatformName.Android : PlatformName.iOS; - devServiceStub.isServerHandlerRegistered.returns(true); - mockFileExists(mockLwcFileDirectory); - existsSyncStub.returns(true); - lstatSyncStub.returns({ - isDirectory() { - return true; - } - } as fs.Stats); - - getConfigurationStub.returns(new MockWorkspace(false)); - getGlobalStoreStub.returns(new MockMemento()); - showQuickPickStub.resolves(isAndroid ? androidQuickPick : iOSQuickPick); - showInputBoxStub.resolves(deviceName); - - await lwcPreview(mockLwcFileDirectoryUri); - if (isAndroid) { - mockExecution.stdoutSubject.next(androidSuccessString); - } else { - mockExecution.processExitSubject.next(0); - } - - sinon.assert.calledOnce(showQuickPickStub); - sinon.assert.calledOnce(showInputBoxStub); - expect(cmdWithFlagSpy.getCall(0).args).to.have.same.members([ - '-p', - platform - ]); - expect(cmdWithFlagSpy.getCall(1).args).to.have.same.members([ - '-p', - platform - ]); - expect(cmdWithFlagSpy.getCall(2).args).to.have.same.members([ - '-t', - deviceName - ]); - sinon.assert.calledTwice(mobileExecutorStub); // device list + preview - expect(successInfoMessageSpy.callCount).to.equal(1); - expect( - successInfoMessageSpy.calledWith( - isAndroid - ? nls.localize('force_lightning_lwc_android_start', deviceName) - : nls.localize('force_lightning_lwc_ios_start', deviceName) - ) - ); - } - - it('calls SFDX preview with remembered Android device name', async () => { - await doRememberedDeviceTest(true); - }); - - it('calls SFDX preview with remembered iOS device name', async () => { - await doRememberedDeviceTest(false); - }); - - async function doRememberedDeviceTest(isAndroid: Boolean) { - devServiceStub.isServerHandlerRegistered.returns(true); - mockFileExists(mockLwcFilePath); - existsSyncStub.returns(true); - lstatSyncStub.returns({ - isDirectory() { - return true; - } - } as fs.Stats); - - getConfigurationStub.returns(new MockWorkspace(true)); - getGlobalStoreStub.returns(new MockMemento()); - showQuickPickStub.resolves(isAndroid ? androidQuickPick : iOSQuickPick); - showInputBoxStub.resolves(''); - await lwcPreview(mockLwcFilePathUri); - - if (isAndroid) { - mockExecution.stdoutSubject.next(androidSuccessString); - } else { - mockExecution.processExitSubject.next(0); - } - - sinon.assert.calledOnce(showQuickPickStub); - sinon.assert.calledOnce(showInputBoxStub); - - const platform = isAndroid ? PlatformName.Android : PlatformName.iOS; - const deviceName = isAndroid - ? rememberedAndroidDevice - : rememberediOSDevice; - - expect(cmdWithFlagSpy.getCall(0).args).to.have.same.members([ - '-p', - platform - ]); - expect(cmdWithFlagSpy.getCall(1).args).to.have.same.members([ - '-p', - platform - ]); - expect(cmdWithFlagSpy.getCall(2).args).to.have.same.members([ - '-t', - deviceName - ]); - sinon.assert.calledTwice(mobileExecutorStub); // device list + preview - expect(successInfoMessageSpy.callCount).to.equal(1); - expect( - successInfoMessageSpy.calledWith( - isAndroid - ? nls.localize('force_lightning_lwc_android_start', deviceName) - : nls.localize('force_lightning_lwc_ios_start', deviceName) - ) - ); - } - - it('shows warning when you cancel Android device name input', async () => { - await doCancelledExecutionTest(true); - }); - - it('shows warning when you cancel iOS device name input', async () => { - await doCancelledExecutionTest(false); - }); - - async function doCancelledExecutionTest(isAndroid: Boolean) { - mockFileExists(mockLwcFilePath); - existsSyncStub.returns(true); - lstatSyncStub.returns({ - isDirectory() { - return true; - } - } as fs.Stats); - - getConfigurationStub.returns(new MockWorkspace(true)); - getGlobalStoreStub.returns(new MockMemento()); - showQuickPickStub.resolves(isAndroid ? androidQuickPick : iOSQuickPick); - // This simulates the user hitting the escape key to cancel input. - showInputBoxStub.resolves(undefined); - await lwcPreview(mockLwcFilePathUri); - - sinon.assert.calledOnce(showQuickPickStub); - sinon.assert.calledOnce(showInputBoxStub); - expect(cmdWithArgSpy.callCount).to.equal(1); - expect(cmdWithFlagSpy.callCount).to.equal(1); - sinon.assert.calledOnce(mobileExecutorStub); // device list only (no preview) - expect( - showWarningMessageSpy.calledWith( - nls.localize('force_lightning_lwc_operation_cancelled') - ) - ); - } - - it('shows error in console when Android SFDX execution fails', async () => { - await doFailedExecutionTest(true); - }); - - it('shows error in console when iOS SFDX execution fails', async () => { - await doFailedExecutionTest(false); - }); - - async function doFailedExecutionTest(isAndroid: Boolean) { - devServiceStub.isServerHandlerRegistered.returns(true); - mockFileExists(mockLwcFilePath); - existsSyncStub.returns(true); - lstatSyncStub.returns({ - isDirectory() { - return false; - } - } as fs.Stats); - - getConfigurationStub.returns(new MockWorkspace(false)); - getGlobalStoreStub.returns(new MockMemento()); - showQuickPickStub.resolves(isAndroid ? androidQuickPick : iOSQuickPick); - showInputBoxStub.resolves(''); - await lwcPreview(mockLwcFilePathUri); - mockExecution.processExitSubject.next(1); - - sinon.assert.calledTwice(mobileExecutorStub); // device list + preview - sinon.assert.calledTwice(showErrorMessageStub); - sinon.assert.calledWith( - showErrorMessageStub, - sinon.match( - isAndroid - ? nls.localize( - 'force_lightning_lwc_android_failure', - androidQuickPick.defaultTargetName - ) - : nls.localize( - 'force_lightning_lwc_ios_failure', - iOSQuickPick.defaultTargetName - ) - ) - ); - sinon.assert.calledOnce(streamCommandOutputSpy); - expect(successInfoMessageSpy.callCount).to.equal(0); - } - - it('shows install message if sfdx plugin is not installed', async () => { - devServiceStub.isServerHandlerRegistered.returns(true); - mockFileExists(mockLwcFilePath); - existsSyncStub.returns(true); - lstatSyncStub.returns({ - isDirectory() { - return false; - } - } as fs.Stats); - - getConfigurationStub.returns(new MockWorkspace(false)); - getGlobalStoreStub.returns(new MockMemento()); - showQuickPickStub.resolves(androidQuickPick); - showInputBoxStub.resolves(''); - - commandOutputStub.returns( - Promise.reject(`${sfdxDeviceListCommand} is not a sfdx command.`) - ); - - await lwcPreview(mockLwcFilePathUri); - - sinon.assert.calledOnce(mobileExecutorStub); // device list only - - sinon.assert.calledWith( - showErrorMessageStub, - sinon.match(nls.localize('force_lightning_lwc_no_mobile_plugin')) - ); - - sinon.assert.notCalled(streamCommandOutputSpy); - sinon.assert.notCalled(successInfoMessageSpy); - - sinon.assert.calledOnce(appendLineSpy); - expect( - appendLineSpy.calledWith( - nls.localize('force_lightning_lwc_no_mobile_plugin') - ) - ); - }); - - it('correct log level is used when the setting is changed', async () => { - devServiceStub.isServerHandlerRegistered.returns(true); - mockFileExists(mockLwcFilePath); - existsSyncStub.returns(true); - lstatSyncStub.returns({ - isDirectory() { - return false; - } - } as fs.Stats); - - getConfigurationStub.returns(new MockWorkspace(false, 'debug')); - getGlobalStoreStub.returns(new MockMemento()); - showQuickPickStub.resolves(androidQuickPick); - showInputBoxStub.resolves(''); - await lwcPreview(mockLwcFilePathUri); - mockExecution.stdoutSubject.next(androidSuccessString); - - sinon.assert.calledOnce(showQuickPickStub); - sinon.assert.calledOnce(showInputBoxStub); - expect(cmdWithArgSpy.callCount).to.equal(2); - expect(cmdWithArgSpy.getCall(0).args[0]).equals(sfdxDeviceListCommand); - expect(cmdWithArgSpy.getCall(1).args[0]).equals(sfdxMobilePreviewCommand); - expect(cmdWithFlagSpy.callCount).to.equal(7); - expect(cmdWithFlagSpy.getCall(0).args).to.have.same.members([ - '-p', - PlatformName.Android - ]); - expect(cmdWithFlagSpy.getCall(1).args).to.have.same.members([ - '-p', - PlatformName.Android - ]); - expect(cmdWithFlagSpy.getCall(2).args).to.have.same.members([ - '-t', - 'SFDXEmulator' - ]); - expect(cmdWithFlagSpy.getCall(3).args).to.have.same.members([ - '-n', - 'c/foo' - ]); - expect(cmdWithFlagSpy.getCall(4).args).to.have.same.members([ - '-a', - 'browser' - ]); - expect(cmdWithFlagSpy.getCall(5).args).to.have.same.members([ - '-d', - mockLwcFileDirectory - ]); - expect(cmdWithFlagSpy.getCall(6).args).to.have.same.members([ - '--loglevel', - 'debug' - ]); - sinon.assert.calledTwice(mobileExecutorStub); // device list + preview - expect(successInfoMessageSpy.callCount).to.equal(1); - }); - - it('Shows device pick list for Android devices', async () => { - await doDeviceListQuickPickTest(true); - }); - - it('Shows device pick list for iOS devices', async () => { - await doDeviceListQuickPickTest(false); - }); - - async function doDeviceListQuickPickTest(isAndroid: Boolean) { - devServiceStub.isServerHandlerRegistered.returns(true); - mockFileExists(mockLwcFileDirectory); - existsSyncStub.returns(true); - lstatSyncStub.returns({ - isDirectory() { - return true; - } - } as fs.Stats); - - getConfigurationStub.returns(new MockWorkspace(false)); - getGlobalStoreStub.returns(new MockMemento()); - showQuickPickStub - .onFirstCall() - .resolves(isAndroid ? androidQuickPick : iOSQuickPick); - showQuickPickStub - .onSecondCall() - .resolves(isAndroid ? androidPickedDevice : iOSPickedDevice); - commandOutputStub.returns( - Promise.resolve(isAndroid ? androidDeviceListJson : iOSDeviceListJson) - ); - - await lwcPreview(mockLwcFileDirectoryUri); - - if (isAndroid) { - mockExecution.stdoutSubject.next(androidSuccessString); - } else { - mockExecution.processExitSubject.next(0); - } - - sinon.assert.calledTwice(showQuickPickStub); // platform + device list - sinon.assert.notCalled(showInputBoxStub); - - const platform = isAndroid ? PlatformName.Android : PlatformName.iOS; - const deviceName = isAndroid - ? androidPickedDevice.name - : iOSPickedDevice.name; - - expect(cmdWithFlagSpy.getCall(0).args).to.have.same.members([ - '-p', - platform - ]); - expect(cmdWithFlagSpy.getCall(1).args).to.have.same.members([ - '-p', - platform - ]); - expect(cmdWithFlagSpy.getCall(2).args).to.have.same.members([ - '-t', - deviceName - ]); - - sinon.assert.calledTwice(mobileExecutorStub); // device list + preview - - expect(successInfoMessageSpy.callCount).to.equal(1); - expect( - successInfoMessageSpy.calledWith( - isAndroid - ? nls.localize('force_lightning_lwc_android_start', deviceName) - : nls.localize('force_lightning_lwc_ios_start', deviceName) - ) - ); - } - - it('Shows input box when choosing New from device pick list for Android devices', async () => { - await doNewDeviceQuickPickTest(true); - }); - - it('Shows input box when choosing New from device pick list for iOS devices', async () => { - await doNewDeviceQuickPickTest(false); - }); - - async function doNewDeviceQuickPickTest(isAndroid: Boolean) { - const deviceName = isAndroid ? 'androidtestname' : 'iostestname'; - const platform = isAndroid ? PlatformName.Android : PlatformName.iOS; - devServiceStub.isServerHandlerRegistered.returns(true); - mockFileExists(mockLwcFileDirectory); - existsSyncStub.returns(true); - lstatSyncStub.returns({ - isDirectory() { - return true; - } - } as fs.Stats); - - getConfigurationStub.returns(new MockWorkspace(false)); - getGlobalStoreStub.returns(new MockMemento()); - showQuickPickStub - .onFirstCall() - .resolves(isAndroid ? androidQuickPick : iOSQuickPick); - showQuickPickStub.onSecondCall().resolvesArg(0); - showInputBoxStub.resolves(deviceName); - commandOutputStub.returns( - Promise.resolve(isAndroid ? androidDeviceListJson : iOSDeviceListJson) - ); - - await lwcPreview(mockLwcFileDirectoryUri); - - if (isAndroid) { - mockExecution.stdoutSubject.next(androidSuccessString); - } else { - mockExecution.processExitSubject.next(0); - } - - sinon.assert.calledTwice(showQuickPickStub); // platform + device list - sinon.assert.calledOnce(showInputBoxStub); - - expect(cmdWithFlagSpy.getCall(0).args).to.have.same.members([ - '-p', - platform - ]); - expect(cmdWithFlagSpy.getCall(1).args).to.have.same.members([ - '-p', - platform - ]); - expect(cmdWithFlagSpy.getCall(2).args).to.have.same.members([ - '-t', - deviceName - ]); - - sinon.assert.calledTwice(mobileExecutorStub); // device list + preview - - expect(successInfoMessageSpy.callCount).to.equal(1); - expect( - successInfoMessageSpy.calledWith( - isAndroid - ? nls.localize('force_lightning_lwc_android_start', deviceName) - : nls.localize('force_lightning_lwc_ios_start', deviceName) - ) - ); - } - - it('Picks an app from app pick list for Android apps', async () => { - await doAppListQuickPickTest(true, pickedApp, false); - }); - - it('Picks an app from app pick list for iOS apps', async () => { - await doAppListQuickPickTest(false, pickedApp, false); - }); - - it('Picks browser from app pick list for Android apps', async () => { - await doAppListQuickPickTest(true, 'browser', true); - }); - - it('Picks browser from app pick list for iOS apps', async () => { - await doAppListQuickPickTest(false, 'browser', true); - }); - - async function doAppListQuickPickTest( - isAndroid: Boolean, - selectedApp: vscode.QuickPickItem | 'browser', - lwcLocationIsDirectory: boolean - ) { - const targetApp = - selectedApp === 'browser' ? 'browser' : selectedApp.detail; - - devServiceStub.isServerHandlerRegistered.returns(true); - if (lwcLocationIsDirectory) { - mockFileExists(mockLwcFileDirectory); - } else { - mockFileExists(mockLwcFilePath); - } - - existsSyncStub.returns(true); - lstatSyncStub.returns({ - isDirectory() { - return lwcLocationIsDirectory; - } - } as fs.Stats); - sinon.stub(fs, 'readFileSync').returns(appConfigFileJson); - - getConfigurationStub.returns(new MockWorkspace(false)); - getGlobalStoreStub.returns(new MockMemento()); - showQuickPickStub - .onFirstCall() - .resolves(isAndroid ? androidQuickPick : iOSQuickPick); - showQuickPickStub - .onSecondCall() - .resolves(isAndroid ? androidPickedDevice : iOSPickedDevice); - if (selectedApp === 'browser') { - showQuickPickStub.onThirdCall().callsFake(args => { - const items = args as vscode.QuickPickItem[]; - return Promise.resolve(items[0]); - }); - } else { - showQuickPickStub.onThirdCall().resolves(selectedApp); - } - commandOutputStub.returns( - Promise.resolve(isAndroid ? androidDeviceListJson : iOSDeviceListJson) - ); - - await lwcPreview( - lwcLocationIsDirectory ? mockLwcFileDirectoryUri : mockLwcFilePathUri - ); - - if (isAndroid) { - mockExecution.stdoutSubject.next(androidSuccessString); - } else { - mockExecution.processExitSubject.next(0); - } - - sinon.assert.calledThrice(showQuickPickStub); // platform + device list + app list - - const platform = isAndroid ? PlatformName.Android : PlatformName.iOS; - const deviceName = isAndroid - ? androidPickedDevice.name - : iOSPickedDevice.name; - const projectRootDir = mockLwcFileDirectoryUri.fsPath; - const configFile = path.join(projectRootDir, 'mobile-apps.json'); - - expect(cmdWithFlagSpy.getCall(0).args).to.have.same.members([ - '-p', - platform - ]); - expect(cmdWithFlagSpy.getCall(1).args).to.have.same.members([ - '-p', - platform - ]); - expect(cmdWithFlagSpy.getCall(2).args).to.have.same.members([ - '-t', - deviceName - ]); - expect(cmdWithFlagSpy.getCall(3).args).to.have.same.members([ - '-n', - 'c/foo' - ]); - expect(cmdWithFlagSpy.getCall(4).args).to.have.same.members([ - '-a', - targetApp - ]); - expect(cmdWithFlagSpy.getCall(5).args).to.have.same.members([ - '-d', - projectRootDir - ]); - - if (selectedApp === 'browser') { - expect(cmdWithFlagSpy.getCall(6).args).to.have.same.members([ - '--loglevel', - 'warn' - ]); - } else { - expect(cmdWithFlagSpy.getCall(6).args).to.have.same.members([ - '-f', - configFile - ]); - expect(cmdWithFlagSpy.getCall(7).args).to.have.same.members([ - '--loglevel', - 'warn' - ]); - } - - sinon.assert.calledTwice(mobileExecutorStub); // device list + preview - - expect(successInfoMessageSpy.callCount).to.equal(1); - expect( - successInfoMessageSpy.calledWith( - isAndroid - ? nls.localize('force_lightning_lwc_android_start', deviceName) - : nls.localize('force_lightning_lwc_ios_start', deviceName) - ) - ); - } - - it('Cancels Preview if user cancels platform selection', async () => { - devServiceStub.isServerHandlerRegistered.returns(true); - devServiceStub.getBaseUrl.returns(DEV_SERVER_DEFAULT_BASE_URL); - devServiceStub.getComponentPreviewUrl.returns( - 'http://localhost:3333/preview/c/foo' - ); - getConfigurationStub.returns(new MockWorkspace(false)); - existsSyncStub.returns(true); - lstatSyncStub.returns({ - isDirectory() { - return false; - } - } as fs.Stats); - showQuickPickStub.resolves(undefined); - - await lwcPreview(mockLwcFilePathUri); - - sinon.assert.calledOnce(showQuickPickStub); // platform - sinon.assert.notCalled(cmdWithFlagSpy); - expect( - showWarningMessageSpy.calledWith( - nls.localize('force_lightning_lwc_operation_cancelled') - ) - ); - }); - - it('Cancels Preview if user cancels selecting target device', async () => { - devServiceStub.isServerHandlerRegistered.returns(true); - devServiceStub.getBaseUrl.returns(DEV_SERVER_DEFAULT_BASE_URL); - devServiceStub.getComponentPreviewUrl.returns( - 'http://localhost:3333/preview/c/foo' - ); - getConfigurationStub.returns(new MockWorkspace(false)); - existsSyncStub.returns(true); - lstatSyncStub.returns({ - isDirectory() { - return false; - } - } as fs.Stats); - showQuickPickStub.onFirstCall().resolves(androidQuickPick); - showQuickPickStub.onSecondCall().resolves(undefined); - - await lwcPreview(mockLwcFilePathUri); - - sinon.assert.calledOnce(showQuickPickStub); // platform - sinon.assert.calledOnce(cmdWithFlagSpy); // device list - expect( - showWarningMessageSpy.calledWith( - nls.localize('force_lightning_lwc_operation_cancelled') - ) - ); - }); - - it('Cancels Preview if user cancels selecting target app', async () => { - devServiceStub.isServerHandlerRegistered.returns(true); - devServiceStub.getBaseUrl.returns(DEV_SERVER_DEFAULT_BASE_URL); - devServiceStub.getComponentPreviewUrl.returns( - 'http://localhost:3333/preview/c/foo' - ); - getConfigurationStub.returns(new MockWorkspace(false)); - existsSyncStub.returns(true); - lstatSyncStub.returns({ - isDirectory() { - return false; - } - } as fs.Stats); - showQuickPickStub.onFirstCall().resolves(androidQuickPick); - showQuickPickStub.onSecondCall().resolves(androidPickedDevice); - showQuickPickStub.onThirdCall().resolves(undefined); - - await lwcPreview(mockLwcFilePathUri); - - sinon.assert.calledOnce(showQuickPickStub); // platform + device list - sinon.assert.calledOnce(cmdWithFlagSpy); // device list - expect( - showWarningMessageSpy.calledWith( - nls.localize('force_lightning_lwc_operation_cancelled') - ) - ); - }); - - it('Directory Level Up', async () => { - expect( - directoryLevelUp(path.normalize('/my/path')) === path.normalize('/my') - ).to.be.true; - expect(directoryLevelUp(path.normalize('/my')) === path.normalize('/')).to - .be.true; - expect(directoryLevelUp(path.normalize('/')) === undefined).to.be.true; - }); - - it('Project Root Directory', async () => { - lstatSyncStub.returns({ - isDirectory() { - return true; - } - } as fs.Stats); - - // returns undefined for invalid path - expect( - getProjectRootDirectory(path.normalize('/invalidpath')) === undefined - ).to.be.true; - - // returns undefined when path is valid but sfdx-project.json not found - existsSyncStub.callsFake( - fsPath => path.normalize(fsPath as string) === path.normalize('/my/path') - ); - - // returns correct path when path is valid and sfdx-project.json is found - existsSyncStub.reset(); - existsSyncStub.callsFake( - fsPath => - path.normalize(fsPath as string) === path.normalize('/my/path') || - path.normalize(fsPath as string) === - path.normalize('/my/sfdx-project.json') - ); - expect( - getProjectRootDirectory(path.normalize('/my/path')) === - path.normalize('/my') - ).to.be.true; - }); -}); diff --git a/packages/salesforcedx-vscode-lwc/test/vscode-integration/commands/forceLightningLwcStart.test.ts b/packages/salesforcedx-vscode-lwc/test/vscode-integration/commands/forceLightningLwcStart.test.ts deleted file mode 100644 index 5baa69ba04..0000000000 --- a/packages/salesforcedx-vscode-lwc/test/vscode-integration/commands/forceLightningLwcStart.test.ts +++ /dev/null @@ -1,420 +0,0 @@ -/* - * Copyright (c) 2019, salesforce.com, inc. - * All rights reserved. - * Licensed under the BSD 3-Clause license. - * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause - */ - -import { SfdxCommandlet } from '@salesforce/salesforcedx-utils-vscode'; -import { - CliCommandExecutor, - Command, - CommandExecution -} from '@salesforce/salesforcedx-utils-vscode'; -import { expect } from 'chai'; -import { Subject } from 'rxjs/Subject'; -import * as sinon from 'sinon'; -import { SinonSandbox, SinonStub } from 'sinon'; -import * as vscode from 'vscode'; -import { DEV_SERVER_DEFAULT_BASE_URL } from '../../../src/commands/commandConstants'; -import * as commandUtils from '../../../src/commands/commandUtils'; -import { - errorHints, - forceLightningLwcStart, - ForceLightningLwcStartExecutor -} from '../../../src/commands/forceLightningLwcStart'; -import { nls } from '../../../src/messages'; -import { DevServerService } from '../../../src/service/devServerService'; -import { - CancellationToken, - CliCommandExecution, - ChannelService, - notificationService -} from '@salesforce/salesforcedx-utils-vscode'; - -class FakeExecution implements CommandExecution { - public command: Command; - public processExitSubject: Subject; - public processErrorSubject: Subject; - public stdoutSubject: Subject; - public stderrSubject: Subject; - private readonly childProcessPid: any; - - constructor(command: Command) { - this.command = command; - this.processExitSubject = new Subject(); - this.processErrorSubject = new Subject(); - this.stdoutSubject = new Subject(); - this.stderrSubject = new Subject(); - this.childProcessPid = ''; - } - - public killExecution(signal?: string): Promise { - return Promise.resolve(); - } -} - -describe('forceLightningLwcStart', () => { - describe('ForceLightningLwcStartExecutor', () => { - describe('build', () => { - it('returns a command with the correct params', () => { - const executor = new ForceLightningLwcStartExecutor(); - const command = executor.build(); - expect(command.toCommand()).to.equal(`sfdx force:lightning:lwc:start`); - }); - - it('returns a command with the correct description', () => { - const executor = new ForceLightningLwcStartExecutor(); - const command = executor.build(); - expect(command.description).to.equal( - nls.localize('force_lightning_lwc_start_text') - ); - }); - - it('returns a command with the correct logName', () => { - const executor = new ForceLightningLwcStartExecutor(); - const command = executor.build(); - expect(command.logName).to.equal('force_lightning_lwc_start'); - }); - }); - - describe('execute', () => { - let sandbox: SinonSandbox; - let appendLineStub: SinonStub; - let notificationServiceStubs: any; - let devServiceStub: any; - let openBrowserStub: SinonStub<[string], Thenable>; - let cliCommandExecutorStub: SinonStub< - [(CancellationToken | undefined)?], - CliCommandExecution | FakeExecution - >; - - beforeEach(() => { - sandbox = sinon.createSandbox(); - - openBrowserStub = sandbox.stub(commandUtils, 'openBrowser'); - - devServiceStub = sinon.createStubInstance(DevServerService); - sandbox.stub(DevServerService, 'instance').get(() => devServiceStub); - - cliCommandExecutorStub = sandbox.stub( - CliCommandExecutor.prototype, - 'execute' - ); - - notificationServiceStubs = {}; - - appendLineStub = sandbox.stub( - ChannelService.prototype, - 'appendLine' as any - ); - - notificationServiceStubs.reportExecutionErrorStub = sandbox.stub( - notificationService, - 'reportExecutionError' - ); - notificationServiceStubs.showErrorMessageStub = sandbox.stub( - notificationService, - 'showErrorMessage' - ); - notificationServiceStubs.showWarningMessageStub = sandbox.stub( - notificationService, - 'showWarningMessage' - ); - notificationServiceStubs.showSuccessfulExecutionStub = sandbox - .stub(notificationService, 'showSuccessfulExecution') - .returns(Promise.resolve()); - }); - - afterEach(() => { - sandbox.restore(); - }); - - it('calls execute on the CliCommandExecutor', () => { - const executor = new ForceLightningLwcStartExecutor(); - const fakeExecution = new FakeExecution(executor.build()); - cliCommandExecutorStub.returns(fakeExecution); - - executor.execute({ type: 'CONTINUE', data: {} }); - - sinon.assert.calledOnce(cliCommandExecutorStub); - }); - - it('registers the server with DevServerService', () => { - const executor = new ForceLightningLwcStartExecutor(); - const fakeExecution = new FakeExecution(executor.build()); - cliCommandExecutorStub.returns(fakeExecution); - - executor.execute({ type: 'CONTINUE', data: {} }); - - sinon.assert.calledOnce(devServiceStub.registerServerHandler); - }); - - it('shows the success message once server is started', () => { - const executor = new ForceLightningLwcStartExecutor(); - const fakeExecution = new FakeExecution(executor.build()); - cliCommandExecutorStub.returns(fakeExecution); - - executor.execute({ type: 'CONTINUE', data: {} }); - - fakeExecution.stdoutSubject.next('foo'); - fakeExecution.stdoutSubject.next('bar'); - sinon.assert.notCalled( - notificationServiceStubs.showSuccessfulExecutionStub - ); - - fakeExecution.stdoutSubject.next('Server up'); - sinon.assert.calledOnce( - notificationServiceStubs.showSuccessfulExecutionStub - ); - }); - - it('shows the error message if server start up failed', () => { - const executor = new ForceLightningLwcStartExecutor(); - const fakeExecution = new FakeExecution(executor.build()); - cliCommandExecutorStub.returns(fakeExecution); - - executor.execute({ type: 'CONTINUE', data: {} }); - - fakeExecution.stderrSubject.next(errorHints.SERVER_STARTUP_FALIED); - sinon.assert.notCalled( - notificationServiceStubs.showSuccessfulExecutionStub - ); - - sinon.assert.calledTwice(notificationServiceStubs.showErrorMessageStub); - sinon.assert.calledWith( - notificationServiceStubs.showErrorMessageStub, - sinon.match( - nls.localize( - 'command_failure', - nls.localize(`force_lightning_lwc_start_text`) - ) - ) - ); - - sinon.assert.calledOnce(appendLineStub); - sinon.assert.calledWith( - appendLineStub, - sinon.match(nls.localize('force_lightning_lwc_start_failed')) - ); - }); - - it('opens the browser once server is started', () => { - const executor = new ForceLightningLwcStartExecutor(); - const fakeExecution = new FakeExecution(executor.build()); - cliCommandExecutorStub.returns(fakeExecution); - devServiceStub.getBaseUrl.returns('http://localhost:3333'); - - executor.execute({ type: 'CONTINUE', data: {} }); - fakeExecution.stdoutSubject.next('Server up on http://localhost:3333'); - - sinon.assert.calledWith( - devServiceStub.setBaseUrlFromDevServerUpMessage, - sinon.match('Server up on http://localhost:3333') - ); - sinon.assert.calledOnce(openBrowserStub); - sinon.assert.calledWith( - openBrowserStub, - sinon.match(DEV_SERVER_DEFAULT_BASE_URL) - ); - }); - - it('opens the browser at the correct port once server is started', () => { - const executor = new ForceLightningLwcStartExecutor(); - const fakeExecution = new FakeExecution(executor.build()); - cliCommandExecutorStub.returns(fakeExecution); - devServiceStub.getBaseUrl.returns('http://localhost:3332'); - - executor.execute({ type: 'CONTINUE', data: {} }); - fakeExecution.stdoutSubject.next( - 'Some details here\n Server up on http://localhost:3332 something\n More details here' - ); - - sinon.assert.calledWith( - devServiceStub.setBaseUrlFromDevServerUpMessage, - sinon.match( - 'Some details here\n Server up on http://localhost:3332 something\n More details here' - ) - ); - sinon.assert.calledOnce(openBrowserStub); - sinon.assert.calledWith( - openBrowserStub, - sinon.match('http://localhost:3332') - ); - }); - - it('opens the browser with default url when Server up message contains no url', () => { - const executor = new ForceLightningLwcStartExecutor(); - const fakeExecution = new FakeExecution(executor.build()); - cliCommandExecutorStub.returns(fakeExecution); - devServiceStub.getBaseUrl.returns(DEV_SERVER_DEFAULT_BASE_URL); - - executor.execute({ type: 'CONTINUE', data: {} }); - fakeExecution.stdoutSubject.next( - 'Some details here\n Server up on -no valid url here- \n More details here' - ); - - sinon.assert.neverCalledWith( - devServiceStub.setBaseUrlFromDevServerUpMessage, - sinon.match('http://localhost:3333') - ); - sinon.assert.calledOnce(openBrowserStub); - sinon.assert.calledWith( - openBrowserStub, - sinon.match('http://localhost:3333') - ); - }); - - it('shows an error when the plugin is not installed', () => { - const executor = new ForceLightningLwcStartExecutor(); - const fakeExecution = new FakeExecution(executor.build()); - cliCommandExecutorStub.returns(fakeExecution); - - executor.execute({ type: 'CONTINUE', data: {} }); - fakeExecution.stdoutSubject.next('foo'); - fakeExecution.processExitSubject.next(127); - - const commandName = nls.localize(`force_lightning_lwc_start_text`); - - sinon.assert.calledTwice(notificationServiceStubs.showErrorMessageStub); - sinon.assert.calledWith( - notificationServiceStubs.showErrorMessageStub, - sinon.match(nls.localize('command_failure', commandName)) - ); - - sinon.assert.calledOnce(appendLineStub); - sinon.assert.calledWith( - appendLineStub, - sinon.match(nls.localize('force_lightning_lwc_start_not_found')) - ); - }); - - it('shows an error when the address is already in use', () => { - const executor = new ForceLightningLwcStartExecutor(); - const fakeExecution = new FakeExecution(executor.build()); - cliCommandExecutorStub.returns(fakeExecution); - - executor.execute({ type: 'CONTINUE', data: {} }); - fakeExecution.processExitSubject.next(98); - - const commandName = nls.localize(`force_lightning_lwc_start_text`); - - sinon.assert.calledTwice(notificationServiceStubs.showErrorMessageStub); - sinon.assert.calledWith( - notificationServiceStubs.showErrorMessageStub, - sinon.match(nls.localize('command_failure', commandName)) - ); - - sinon.assert.calledOnce(appendLineStub); - sinon.assert.calledWith( - appendLineStub, - sinon.match(nls.localize('force_lightning_lwc_start_addr_in_use')) - ); - }); - - it('shows an error when scratch org is inactive', () => { - const executor = new ForceLightningLwcStartExecutor(); - const fakeExecution = new FakeExecution(executor.build()); - cliCommandExecutorStub.returns(fakeExecution); - - executor.execute({ type: 'CONTINUE', data: {} }); - fakeExecution.stderrSubject.next(errorHints.INACTIVE_SCRATCH_ORG); - fakeExecution.processExitSubject.next(1); - - const commandName = nls.localize(`force_lightning_lwc_start_text`); - - sinon.assert.calledTwice(notificationServiceStubs.showErrorMessageStub); - sinon.assert.calledWith( - notificationServiceStubs.showErrorMessageStub, - sinon.match(nls.localize('command_failure', commandName)) - ); - - sinon.assert.calledOnce(appendLineStub); - sinon.assert.calledWith( - appendLineStub, - sinon.match(nls.localize('force_lightning_lwc_inactive_scratch_org')) - ); - }); - - it('shows no error when server is stopping', () => { - const executor = new ForceLightningLwcStartExecutor(); - const fakeExecution = new FakeExecution(executor.build()); - cliCommandExecutorStub.returns(fakeExecution); - - executor.execute({ type: 'CONTINUE', data: {} }); - fakeExecution.stdoutSubject.next('Server up'); - fakeExecution.processExitSubject.next(0); - - sinon.assert.notCalled(notificationServiceStubs.showErrorMessageStub); - sinon.assert.notCalled(appendLineStub); - }); - - it('shows an error message when the process exists before server startup', () => { - const executor = new ForceLightningLwcStartExecutor(); - const fakeExecution = new FakeExecution(executor.build()); - cliCommandExecutorStub.returns(fakeExecution); - - executor.execute({ type: 'CONTINUE', data: {} }); - fakeExecution.stdoutSubject.next('foo'); - fakeExecution.processExitSubject.next(0); - - const commandName = nls.localize(`force_lightning_lwc_start_text`); - - sinon.assert.calledTwice(notificationServiceStubs.showErrorMessageStub); - sinon.assert.calledWith( - notificationServiceStubs.showErrorMessageStub, - sinon.match(nls.localize('command_failure', commandName)) - ); - - sinon.assert.calledOnce(appendLineStub); - sinon.assert.calledWith( - appendLineStub, - sinon.match(nls.localize('force_lightning_lwc_start_failed')) - ); - }); - }); - }); - - describe('forceLightningLwcStart function', () => { - let sandbox: SinonSandbox; - let showWarningStub: SinonStub< - [string, ...string[]], - Thenable - >; - let devServiceStub: any; - let commandletStub: SinonStub<[], Promise>; - - beforeEach(() => { - sandbox = sinon.createSandbox(); - - devServiceStub = sinon.createStubInstance(DevServerService); - sandbox.stub(DevServerService, 'instance').get(() => devServiceStub); - - sandbox.stub(commandUtils, 'openBrowser'); - commandletStub = sandbox.stub(SfdxCommandlet.prototype, 'run'); - showWarningStub = sandbox.stub(notificationService, 'showWarningMessage'); - }); - - afterEach(() => { - sandbox.restore(); - }); - - it('calls run on the commandlet', async () => { - await forceLightningLwcStart(); - sinon.assert.calledOnce(commandletStub); - }); - - it('shows a warning message when the server is already running', async () => { - devServiceStub.isServerHandlerRegistered.returns(true); - showWarningStub.resolves(); - - await forceLightningLwcStart(); - - sinon.assert.calledOnce(showWarningStub); - sinon.assert.calledWith( - showWarningStub, - nls.localize('force_lightning_lwc_start_already_running') - ); - }); - }); -}); diff --git a/packages/salesforcedx-vscode-lwc/test/vscode-integration/commands/forceLightningLwcStop.test.ts b/packages/salesforcedx-vscode-lwc/test/vscode-integration/commands/forceLightningLwcStop.test.ts deleted file mode 100644 index e256f8c636..0000000000 --- a/packages/salesforcedx-vscode-lwc/test/vscode-integration/commands/forceLightningLwcStop.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (c) 2019, salesforce.com, inc. - * All rights reserved. - * Licensed under the BSD 3-Clause license. - * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause - */ - -import * as sinon from 'sinon'; -import * as vscode from 'vscode'; -import { forceLightningLwcStop } from '../../../src/commands/forceLightningLwcStop'; -import { DevServerService } from '../../../src/service/devServerService'; -import { nls } from '../../../src/messages'; -import { - ChannelService, - notificationService -} from '@salesforce/salesforcedx-utils-vscode'; - -describe('forceLightningLwcStop', () => { - let sandbox: sinon.SinonSandbox; - let devService: DevServerService; - let appendLineStub: sinon.SinonStub; - let notificationServiceStubs: { - [key: string]: any; - }; - - beforeEach(() => { - sandbox = sinon.createSandbox(); - devService = new DevServerService(); - sandbox.stub(DevServerService, 'instance').get(() => devService); - - notificationServiceStubs = {}; - - appendLineStub = sandbox.stub( - ChannelService.prototype, - 'appendLine' as any - ); - notificationServiceStubs.showSuccessfulExecutionStub = sandbox - .stub(notificationService, 'showSuccessfulExecution') - .returns(Promise.resolve()); - notificationServiceStubs.showErrorMessageStub = sandbox.stub( - notificationService, - 'showErrorMessage' - ); - }); - - afterEach(() => { - sandbox.restore(); - }); - - it('calls stopServer when a server is already running', async () => { - const stopStub = sinon.stub(); - devService.registerServerHandler({ - stop: stopStub - }); - - await forceLightningLwcStop(); - sinon.assert.calledOnce(stopStub); - }); - - it('shows successful server stop', async () => { - let devServiceStub = sinon.createStubInstance(DevServerService); - devServiceStub.isServerHandlerRegistered.returns(true); - sandbox.stub(DevServerService, 'instance').get(() => devServiceStub); - - await forceLightningLwcStop(); - - sinon.assert.notCalled(notificationServiceStubs.showErrorMessageStub); - - sinon.assert.calledOnce(appendLineStub); - sinon.assert.calledWith( - appendLineStub, - sinon.match(nls.localize('force_lightning_lwc_stop_in_progress')) - ); - - sinon.assert.calledOnce( - notificationServiceStubs.showSuccessfulExecutionStub - ); - sinon.assert.calledWith( - notificationServiceStubs.showSuccessfulExecutionStub, - sinon.match(nls.localize('force_lightning_lwc_stop_text')) - ); - }); -});