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 7 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 @@ -5,15 +5,17 @@
"author": "Salesforce",
"bugs": "https://github.com/forcedotcom/cli/issues",
"dependencies": {
"@lwc/lwc-dev-server": "^7.1.1-6.6.4",
"@lwc/sfdc-lwc-compiler": "^7.1.1-6.6.4",
"@lwrjs/api": "0.13.0-alpha.12",
"@oclif/core": "^3.26.6",
"@salesforce/core": "^7.3.9",
"@salesforce/kit": "^3.1.2",
"@salesforce/lwc-dev-mobile-core": "4.0.0-alpha.1",
"@salesforce/sf-plugins-core": "^9.0.14",
"tar": "^7.2.0",
"lwc": "6.6.4",
"lwr": "0.13.0-alpha.12",
"@lwrjs/api": "0.13.0-alpha.12"
"tar": "^7.2.0"
},
"devDependencies": {
"@oclif/plugin-command-snapshot": "^5.1.9",
Expand All @@ -22,6 +24,7 @@
"@salesforce/plugin-command-reference": "^3.0.88",
"@types/tar": "^6.1.13",
"eslint-plugin-sf-plugin": "^1.18.5",
"esmock": "^2.6.5",
"oclif": "^4.11.3",
"ts-node": "^10.9.2",
"typescript": "^5.4.5"
Expand Down
3 changes: 3 additions & 0 deletions src/commands/lightning/preview/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { SfCommand, Flags } from '@salesforce/sf-plugins-core';
import { Messages, Logger, Org } from '@salesforce/core';
import { PreviewUtils } from '@salesforce/lwc-dev-mobile-core';
import { OrgUtils } from '../../../shared/orgUtils.js';
import { startLWCServer } from '../../../lwc-dev-server/index.js';

Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
const messages = Messages.loadMessages('@salesforce/plugin-lightning-dev', 'lightning.preview.app');
Expand Down Expand Up @@ -55,6 +56,8 @@ export default class LightningPreviewApp extends SfCommand<void> {
const { flags } = await this.parse(LightningPreviewApp);
const logger = await Logger.child(this.ctor.name);

await startLWCServer(process.cwd(), logger);

if (flags['device-type'] === Platform.desktop) {
await this.desktopPreview(logger, flags);
} else if (flags['device-type'] === Platform.ios) {
Expand Down
101 changes: 101 additions & 0 deletions src/lwc-dev-server/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/*
* 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();
} 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;
}
};

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

return lwcDevServer;
}
18 changes: 14 additions & 4 deletions test/commands/lightning/preview/app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { stubSpinner, stubUx } from '@salesforce/sf-plugins-core';
import { Messages } from '@salesforce/core';
import { PreviewUtils } from '@salesforce/lwc-dev-mobile-core';
import { Config } from '@oclif/core';
import esmock from 'esmock';
import LightningPreviewApp from '../../../../src/commands/lightning/preview/app.js';
import { OrgUtils } from '../../../../src/shared/orgUtils.js';

Expand All @@ -22,11 +23,20 @@ describe('lightning preview app', () => {
const testOrgData = new MockTestOrgData();
const testAppId = '06m8b000002vpFSAAY';
const testServerUrl = 'wss://localhost: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 @@ -36,7 +46,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 @@ -50,7 +60,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 @@ -69,9 +79,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
3 changes: 3 additions & 0 deletions test/lwc-dev-server/__mock__/sfdx-project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"packageDirectories": [{}]
}
46 changes: 46 additions & 0 deletions test/lwc-dev-server/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
* Copyright (c) 2024, 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 path from 'node:path';
import { fileURLToPath } from 'node:url';
import { expect } from 'chai';
import { Logger } from '@salesforce/core';
import { LWCServer } from '@lwc/lwc-dev-server';
import esmock from 'esmock';
import * as devServer from '../../src/lwc-dev-server/index.js';
// eslint-disable-next-line no-underscore-dangle
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const logger = {
debug: () => {},
warn: () => {},
trace: () => {},
getLevel: () => 10,
} as Logger;

describe('lwc-dev-server', () => {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Can we have a test which can use a sample sfdx project and start the lwc dev server and stop it successfully? Like a sanity end-2-end test.

const server = {
stopServer: () => {},
} as LWCServer;
let lwcDevServer: typeof devServer;

before(async () => {
lwcDevServer = await esmock<typeof devServer>('../../src/lwc-dev-server/index.js', {
'@lwc/lwc-dev-server': {
startLwcDevServer: async () => server,
},
});
});

it('exports a startLWCServer function', () => {
expect(lwcDevServer.startLWCServer).to.be.a('function');
});

it('calling startLWCServer returns an LWCServer', async () => {
const s = await lwcDevServer.startLWCServer(path.resolve(__dirname, './__mock__'), logger);
expect(s).to.equal(server);
});
});
Loading
Loading