Skip to content

Commit

Permalink
support ssl for monocart cli
Browse files Browse the repository at this point in the history
  • Loading branch information
cenfun committed Jan 13, 2024
1 parent e32c4fb commit 9268eab
Show file tree
Hide file tree
Showing 4 changed files with 116 additions and 39 deletions.
148 changes: 111 additions & 37 deletions lib/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,37 @@
const fs = require('fs');
const path = require('path');
const http = require('http');
const https = require('https');
const net = require('net');
const os = require('os');
const EC = require('eight-colors');
const KSR = require('koa-static-resolver');
const Koa = require('koa');
const CG = require('console-grid');

const { program } = require('./packages/monocart-vendor.js');
const defaultOptions = require('./default/options.js');
const version = require('../package.json').version;

const getInternalIps = () => {
const n = os.networkInterfaces();
// console.log(n);
const list = [];
for (const k in n) {
const inter = n[k];
for (const j in inter) {
const item = inter[j];
if (item.family === 'IPv4' && !item.internal) {
const a = item.address;
if (a.startsWith('192.') || a.startsWith('10.')) {
list.push(a);
}
}
}
}
return list;
};


const generatePort = (startPort) => {
return new Promise((resolve) => {
Expand All @@ -29,36 +54,71 @@ const generatePort = (startPort) => {
});
};

const showIpInfo = (protocol, port) => {
const ips = getInternalIps();
CG({
options: {
headerVisible: false
},
columns: [{
id: 'type'
}, {
id: 'url',
formatter: (v) => {
return EC.green(v);
}
}],
rows: [{
url: `${protocol}://localhost:${port}`,
type: 'Local'
}, ... ips.map((ip) => {
return {
url: `${protocol}://${ip}:${port}`,
type: 'Internal'
};
})]
});
};

const openUrl = async (p) => {
const open = await import('open');
await open.default(p);
};

const createServer = (app, options) => {

const serveReport = async (list, openReport) => {
if (!list.length) {
list.push(defaultOptions.outputFile);
if (options.ssl) {
const [keyPath, certPath] = options.ssl.split(',');
const serverOptions = {
key: fs.readFileSync(path.resolve(keyPath)),
cert: fs.readFileSync(path.resolve(certPath))
};
return https.createServer(serverOptions, app.callback());
}

return http.createServer(app.callback());

};

const serveReport = async (p, options) => {

if (!p) {
p = defaultOptions.outputFile;
}

const dirs = [];
let filename = '';
const dirs = list.filter((item) => {
if (fs.existsSync(item)) {
return true;
}
EC.logRed(`the path does not exists: ${item}`);
return false;
}).map((item) => {
const stat = fs.statSync(item);
if (fs.existsSync(p)) {
const stat = fs.statSync(p);
if (stat.isDirectory()) {
return item;
dirs.push(p);
} else if (stat.isFile()) {
filename = path.basename(p);
dirs.push(path.dirname(p));
}

if (!filename) {
filename = path.basename(item);
}

return path.dirname(item);
});
} else {
EC.logRed(`The path does not exists: ${p}`);
}

dirs.push('./');

Expand All @@ -75,36 +135,50 @@ const serveReport = async (list, openReport) => {
maxAge: 1
}));

const server = http.createServer(app.callback());
const server = createServer(app, options);

const port = await generatePort(8090);
const protocol = options.ssl ? 'https' : 'http';

const url = `http://localhost:${port}/${filename}`;
const url = `${protocol}://localhost:${port}/${filename}`;

server.listen(port, function() {
EC.logCyan(`${new Date().toLocaleString()} server listening on ${url}`);
if (openReport) {
showIpInfo(protocol, port);
if (options.open) {
openUrl(url);
}
});

};

const start = function() {
const args = process.argv.slice(2);
const command = args.shift();
// console.log(command, args);
if (command === 'show' || command === 'show-report') {
serveReport(args, true);
return;
}
program
.name('monocart')
.description('CLI to serve monocart reporter')
.version(version);

program.command('show-report')
.alias('show')
.description('Show report')
.argument('[path]', 'Report dir or html path')
.option('-s, --ssl <key,cert>', 'Start ssl server')
.action((str, options) => {
options.open = true;
serveReport(str, options);
});

if (command === 'serve' || command === 'serve-report') {
serveReport(args, false);
return;
}
program.command('serve-report')
.alias('serve')
.description('Serve report')
.argument('[path]', 'Report dir or html path')
.option('-s, --ssl [path]', 'Start ssl server')
.action((str, options) => {
serveReport(str, options);
});

EC.logRed(`Not found command: ${command}`);
};
program.addHelpText('after', `
Starts ${EC.cyan('https')} with option --ssl:
monocart show-report path-to/index.html ${EC.cyan('--ssl path-to/key,path-to/cert')}
`);

start();
program.parse();
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@
"eslint": "^8.56.0",
"eslint-config-plus": "^1.0.6",
"eslint-plugin-html": "^7.1.0",
"eslint-plugin-vue": "^9.20.0",
"eslint-plugin-vue": "^9.20.1",
"stylelint": "^15.11.0",
"stylelint-config-plus": "^1.0.4",
"vine-ui": "^3.1.13"
Expand Down
1 change: 1 addition & 0 deletions packages/vendor/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"dependencies": {},
"devDependencies": {
"@babel/code-frame": "^7.23.5",
"commander": "^11.1.0",
"sanitize-filename": "^1.6.3",
"stack-utils": "^2.0.6",
"ws": "^8.16.0"
Expand Down
4 changes: 3 additions & 1 deletion packages/vendor/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ import StackUtils from 'stack-utils';
import { codeFrameColumns } from '@babel/code-frame';
import WebSocket, { WebSocketServer } from 'ws';
import sanitize from 'sanitize-filename';
import { program } from 'commander';

export {
StackUtils,
codeFrameColumns,
WebSocket,
WebSocketServer,
sanitize
sanitize,
program
};

0 comments on commit 9268eab

Please sign in to comment.