Skip to content

feat(dev-server): integrate with preview app command #49

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
Jun 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .mocharc.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@
"recursive": true,
"reporter": "spec",
"timeout": 600000,
"node-option": ["loader=ts-node/esm"]
"node-option": ["loader=ts-node/esm", "loader=esmock"]
}
2 changes: 0 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,4 @@ FLAG DESCRIPTIONS
This person can be anyone in the world!
```

_See code: [src/commands/hello/world.ts](https://github.com/salesforcecli/plugin-lightning-dev/blob/1.0.25/src/commands/hello/world.ts)_

<!-- commandsstop -->
7 changes: 5 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
"bugs": "https://github.com/forcedotcom/cli/issues",
"dependencies": {
"@lwrjs/api": "0.13.0-alpha.19",
"@lwc/lwc-dev-server": "^7.1.3-6.6.7",
"@lwc/sfdc-lwc-compiler": "^7.1.3-6.6.7",
"@oclif/core": "^3.26.6",
"@salesforce/core": "^7.3.9",
"@salesforce/kit": "^3.1.2",
Expand All @@ -26,6 +28,7 @@
"@types/node-fetch": "^2.6.11",
"@types/tar": "^6.1.13",
"eslint-plugin-sf-plugin": "^1.18.5",
"esmock": "^2.6.5",
"oclif": "^4.12.3",
"ts-node": "^10.9.2",
"typescript": "^5.4.5"
Expand Down Expand Up @@ -203,7 +206,7 @@
"output": []
},
"link-check": {
"command": "node -e \"process.exit(process.env.CI ? 0 : 1)\" || linkinator \"**/*.md\" --skip \"CHANGELOG.md|node_modules|test/|confluence.internal.salesforce.com|world.ts|my.salesforce.com|%s\" --markdown --retry --directory-listing --verbosity error",
"command": "node -e \"process.exit(process.env.CI ? 0 : 1)\" || linkinator \"**/*.md\" --skip \"CHANGELOG.md|node_modules|test/|confluence.internal.salesforce.com|my.salesforce.com|%s\" --markdown --retry --directory-listing --verbosity error",
"files": [
"./*.md",
"./!(CHANGELOG).md",
Expand All @@ -214,4 +217,4 @@
},
"exports": "./lib/index.js",
"type": "module"
}
}
6 changes: 6 additions & 0 deletions src/commands/lightning/preview/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
import { Flags, SfCommand } from '@salesforce/sf-plugins-core';
import chalk from 'chalk';
import { OrgUtils } from '../../../shared/orgUtils.js';
import { startLWCServer } from '../../../lwc-dev-server/index.js';
import { PreviewUtils } from '../../../shared/previewUtils.js';

Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
Expand Down Expand Up @@ -199,6 +200,9 @@ export default class LightningPreviewApp extends SfCommand<void> {

const launchArguments = PreviewUtils.generateDesktopPreviewLaunchArguments(ldpServerUrl, appId, targetOrg);

// Start the LWC Dev Server
await startLWCServer(process.cwd(), logger ? logger : await Logger.child(this.ctor.name));

await this.config.runCommand('org:open', launchArguments);
}

Expand Down Expand Up @@ -276,6 +280,8 @@ export default class LightningPreviewApp extends SfCommand<void> {
}
}

// Start the LWC Dev Server
await startLWCServer(process.cwd(), logger ? logger : await Logger.child(this.ctor.name));
// 7. Launch the native app for previewing (launchMobileApp will show its own spinner)
// eslint-disable-next-line camelcase
appConfig.launch_arguments = PreviewUtils.generateMobileAppPreviewLaunchArguments(ldpServerUrl, appName, appId);
Expand Down
100 changes: 100 additions & 0 deletions src/lwc-dev-server/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
/*
* 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 { existsSync, lstatSync, readFileSync } from 'node:fs';
import path from 'node:path';
import process from 'node:process';
import { LWCServer, LogLevel, ServerConfig, Workspace, startLwcDevServer } from '@lwc/lwc-dev-server';
import { Logger } from '@salesforce/core';

const DEV_SERVER_PORT = 8081;
Copy link
Collaborator

@ravijayaramappa ravijayaramappa Jun 7, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The port needs to be configurable. This a pretty popular port number and we should anticipate that it might not be available. Can we add a new flag to sf lightning preview app command?

Copy link
Contributor

@maliroteh-sf maliroteh-sf Jun 7, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ravijayaramappa we may need to run it by Marcelino to discuss this. For example:

  • Should it be required or optional flag
  • If it is optional and omitted what should we default to
  • What if the user uses a --port flag to pass in a port but lwc.config.json also has a port defined in it. Should we update the content of the config file and overwrite with the new flag?
  • etc.

Maybe we should utilize our slack channel to discuss further with him and the devs?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like that idea of just putting it in the lwc.config.json. So that the user can add it once and forget it. Created W-15962937 to track.


/**
* Map sf cli log level to lwc dev server log level
* https://github.com/salesforcecli/cli/wiki/Code-Your-Plugin#logging-levels
*
* @param cliLogLevel
* @returns number
*/
function mapLogLevel(cliLogLevel: number): number {
switch (cliLogLevel) {
case 10:
return LogLevel.verbose;
case 20:
return LogLevel.debug;
case 30:
return LogLevel.info;
case 40:
return LogLevel.warn;
case 50:
return LogLevel.error;
case 60:
return LogLevel.silent;
default:
return LogLevel.error;
}
}

function createLWCServerConfig(rootDir: string, logger: Logger): ServerConfig {
const sfdxConfig = path.resolve(rootDir, 'sfdx-project.json');

if (!existsSync(sfdxConfig) || !lstatSync(sfdxConfig).isFile()) {
throw new Error(`sfdx-project.json not found in ${rootDir}`);
}

const sfdxConfigJson = readFileSync(sfdxConfig, 'utf-8');
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const { packageDirectories } = JSON.parse(sfdxConfigJson);
const namespacePaths: string[] = [];

for (const dir of packageDirectories) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (dir.path) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-argument
const resolvedDir = path.resolve(rootDir, dir.path, 'main', 'default');
if (existsSync(resolvedDir) && lstatSync(resolvedDir).isDirectory()) {
logger.debug(`Adding ${resolvedDir} to namespace paths`);
namespacePaths.push(resolvedDir);
} else {
logger.warn(`Skipping ${resolvedDir} because it does not exist or is not a directory`);
}
}
}

return {
rootDir,
port: DEV_SERVER_PORT,
protocol: 'wss',
host: 'localhost',
paths: namespacePaths,
workspace: Workspace.SfCli,
targets: ['LEX'], // should this be something else?
logLevel: mapLogLevel(logger.getLevel()),
};
}

export async function startLWCServer(rootDir: string, logger: Logger): Promise<LWCServer> {
const config = createLWCServerConfig(rootDir, logger);
logger.trace(`Starting LWC Dev Server with config: ${JSON.stringify(config)}`);
let lwcDevServer: LWCServer | null = await startLwcDevServer(config);

const cleanup = (): void => {
if (lwcDevServer) {
logger.trace('Stopping LWC Dev Server');
lwcDevServer.stopServer();
lwcDevServer = null;
}
};

[
'exit', // normal exit flow
'SIGINT', // when a user presses ctrl+c
'SIGTERM', // when a user kills the process
].forEach((signal) => process.on(signal, cleanup));

return lwcDevServer;
}
60 changes: 43 additions & 17 deletions test/commands/lightning/preview/app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
} from '@salesforce/lwc-dev-mobile-core';
import { stubSpinner, stubUx } from '@salesforce/sf-plugins-core';
import { expect } from 'chai';
import esmock from 'esmock';
import sinon from 'sinon';
import LightningPreviewApp, {
androidSalesforceAppPreviewConfig,
Expand Down Expand Up @@ -49,11 +50,20 @@ describe('lightning preview app', () => {
'34'
);
const testEmulatorPort = 1234;
let MockedLightningPreviewApp: typeof LightningPreviewApp;

beforeEach(async () => {
stubUx($$.SANDBOX);
stubSpinner($$.SANDBOX);
await $$.stubAuths(testOrgData);
MockedLightningPreviewApp = await esmock<typeof LightningPreviewApp>(
'../../../../src/commands/lightning/preview/app.js',
{
'../../../../src/lwc-dev-server/index.js': {
startLWCServer: async () => ({ stopServer: () => {} }),
},
}
);
});

afterEach(() => {
Expand All @@ -63,7 +73,7 @@ describe('lightning preview app', () => {
it('throws when app not found', async () => {
try {
$$.SANDBOX.stub(OrgUtils, 'getAppId').resolves(undefined);
await LightningPreviewApp.run(['--name', 'blah', '-o', testOrgData.username]);
await MockedLightningPreviewApp.run(['--name', 'blah', '-o', testOrgData.username]);
} catch (err) {
expect(err)
.to.be.an('error')
Expand All @@ -77,7 +87,7 @@ describe('lightning preview app', () => {
$$.SANDBOX.stub(PreviewUtils, 'generateWebSocketUrlForLocalDevServer').throws(
new Error('Cannot determine LDP url.')
);
await LightningPreviewApp.run(['--name', 'Sales', '-o', testOrgData.username]);
await MockedLightningPreviewApp.run(['--name', 'Sales', '-o', testOrgData.username]);
} catch (err) {
expect(err).to.be.an('error').with.property('message', 'Cannot determine LDP url.');
}
Expand All @@ -97,9 +107,9 @@ describe('lightning preview app', () => {
$$.SANDBOX.stub(PreviewUtils, 'generateWebSocketUrlForLocalDevServer').returns(testServerUrl);
const runCmdStub = $$.SANDBOX.stub(Config.prototype, 'runCommand').resolves();
if (appName) {
await LightningPreviewApp.run(['--name', appName, '-o', testOrgData.username]);
await MockedLightningPreviewApp.run(['--name', appName, '-o', testOrgData.username]);
} else {
await LightningPreviewApp.run(['-o', testOrgData.username]);
await MockedLightningPreviewApp.run(['-o', testOrgData.username]);
}

expect(runCmdStub.calledOnce);
Expand Down Expand Up @@ -192,7 +202,10 @@ describe('lightning preview app', () => {
const expectedCertFilePath = '/path/to/cert.pem';
$$.SANDBOX.stub(PreviewUtils, 'generateSelfSignedCert').returns(expectedCertFilePath);

const waitForUserToInstallCertStub = $$.SANDBOX.stub(LightningPreviewApp, 'waitForUserToInstallCert').resolves();
const waitForUserToInstallCertStub = $$.SANDBOX.stub(
MockedLightningPreviewApp,
'waitForUserToInstallCert'
).resolves();

$$.SANDBOX.stub(PreviewUtils, 'verifyMobileAppInstalled').resolves(true);
$$.SANDBOX.stub(PreviewUtils, 'launchMobileApp').resolves();
Expand Down Expand Up @@ -225,10 +238,10 @@ describe('lightning preview app', () => {
const expectedCertFilePath = '/path/to/cert.pem';
$$.SANDBOX.stub(PreviewUtils, 'generateSelfSignedCert').returns(expectedCertFilePath);

$$.SANDBOX.stub(LightningPreviewApp, 'waitForUserToInstallCert').resolves();
$$.SANDBOX.stub(MockedLightningPreviewApp, 'waitForUserToInstallCert').resolves();

const verifyMobileAppInstalledStub = $$.SANDBOX.stub(PreviewUtils, 'verifyMobileAppInstalled').resolves(false);
$$.SANDBOX.stub(LightningPreviewApp.prototype, 'confirm').resolves(false);
$$.SANDBOX.stub(MockedLightningPreviewApp.prototype, 'confirm').resolves(false);

await verifyMobileThrowsWhenUserDeclinesToInstallApp(Platform.ios, verifyMobileAppInstalledStub);
await verifyMobileThrowsWhenUserDeclinesToInstallApp(Platform.android, verifyMobileAppInstalledStub);
Expand All @@ -250,10 +263,10 @@ describe('lightning preview app', () => {
const expectedCertFilePath = '/path/to/cert.pem';
$$.SANDBOX.stub(PreviewUtils, 'generateSelfSignedCert').returns(expectedCertFilePath);

$$.SANDBOX.stub(LightningPreviewApp, 'waitForUserToInstallCert').resolves();
$$.SANDBOX.stub(MockedLightningPreviewApp, 'waitForUserToInstallCert').resolves();

$$.SANDBOX.stub(PreviewUtils, 'verifyMobileAppInstalled').resolves(false);
$$.SANDBOX.stub(LightningPreviewApp.prototype, 'confirm').resolves(true);
$$.SANDBOX.stub(MockedLightningPreviewApp.prototype, 'confirm').resolves(true);

const iosBundlePath = '/path/to/bundle.zip';
const androidBundlePath = '/path/to/bundle.apk';
Expand All @@ -269,15 +282,24 @@ describe('lightning preview app', () => {

async function verifyMobileThrowsWithUnmetRequirements(platform: Platform.ios | Platform.android) {
try {
await LightningPreviewApp.run(['-n', 'Sales', '-o', testOrgData.username, '-t', platform]);
await MockedLightningPreviewApp.run(['-n', 'Sales', '-o', testOrgData.username, '-t', platform]);
} catch (err) {
expect(err).to.be.an('error').with.property('message').that.contains('Requirement blah not met');
}
}

async function verifyMobileThrowsWhenDeviceNotFound(platform: Platform.ios | Platform.android) {
try {
await LightningPreviewApp.run(['-n', 'Sales', '-o', testOrgData.username, '-t', platform, '-i', 'some_device']);
await MockedLightningPreviewApp.run([
'-n',
'Sales',
'-o',
testOrgData.username,
'-t',
platform,
'-i',
'some_device',
]);
} catch (err) {
expect(err)
.to.be.an('error')
Expand All @@ -290,7 +312,7 @@ describe('lightning preview app', () => {
bootStub: sinon.SinonStub
) {
try {
await LightningPreviewApp.run(['-n', 'Sales', '-o', testOrgData.username, '-t', platform]);
await MockedLightningPreviewApp.run(['-n', 'Sales', '-o', testOrgData.username, '-t', platform]);
} catch (err) {
expect(err).to.be.an('error').with.property('message', 'Failed to boot device');

Expand All @@ -308,7 +330,7 @@ describe('lightning preview app', () => {

async function verifyMobileThrowsWhenFailedToGenerateCert(platform: Platform.ios | Platform.android) {
try {
await LightningPreviewApp.run(['-n', 'Sales', '-o', testOrgData.username, '-t', platform]);
await MockedLightningPreviewApp.run(['-n', 'Sales', '-o', testOrgData.username, '-t', platform]);
} catch (err) {
expect(err).to.be.an('error').with.property('message', 'Failed to generate certificate');
}
Expand All @@ -320,7 +342,7 @@ describe('lightning preview app', () => {
waitForUserToInstallCertStub: sinon.SinonStub
) {
const expectedDevice = platform === Platform.ios ? testIOSDevice : testAndroidDevice;
await LightningPreviewApp.run(['-n', 'Sales', '-o', testOrgData.username, '-t', platform]);
await MockedLightningPreviewApp.run(['-n', 'Sales', '-o', testOrgData.username, '-t', platform]);
expect(waitForUserToInstallCertStub.calledWith(platform, expectedDevice, expectedCertFilePath)).to.be.true;
waitForUserToInstallCertStub.resetHistory();
}
Expand All @@ -333,7 +355,7 @@ describe('lightning preview app', () => {
const deviceId = platform === Platform.ios ? testIOSDevice.udid : testAndroidDevice.name;

try {
await LightningPreviewApp.run(['-n', 'Sales', '-o', testOrgData.username, '-t', platform]);
await MockedLightningPreviewApp.run(['-n', 'Sales', '-o', testOrgData.username, '-t', platform]);
} catch (err) {
expect(err)
.to.be.an('error')
Expand Down Expand Up @@ -362,9 +384,13 @@ describe('lightning preview app', () => {
const expectedAppConfig =
platform === Platform.ios ? iOSSalesforceAppPreviewConfig : androidSalesforceAppPreviewConfig;
// eslint-disable-next-line camelcase
expectedAppConfig.launch_arguments = PreviewUtils.generateMobileAppPreviewLaunchArguments(expectedLdpServerUrl);
expectedAppConfig.launch_arguments = PreviewUtils.generateMobileAppPreviewLaunchArguments(
expectedLdpServerUrl,
'Sales',
testAppId
);

await LightningPreviewApp.run(['-n', 'Sales', '-o', testOrgData.username, '-t', platform]);
await MockedLightningPreviewApp.run(['-n', 'Sales', '-o', testOrgData.username, '-t', platform]);
expect(downloadStub.calledOnce).to.be.true;

if (platform === Platform.ios) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
// Intentionally blank file.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
// Intentionally blank file.
7 changes: 7 additions & 0 deletions test/lwc-dev-server/__mocks__/sfdx-project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"packageDirectories": [
{
"path": "force-app"
}
]
}
Loading
Loading