polyv-live-cli
Version:
CLI tool for managing PolyV live streaming services.
438 lines (433 loc) • 19.1 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractCommands = extractCommands;
exports.main = main;
exports.loadAndValidateConfig = loadAndValidateConfig;
exports.getVersion = getVersion;
const commander_1 = require("commander");
const fs_1 = require("fs");
const path_1 = require("path");
const errors_1 = require("./utils/errors");
const manager_1 = require("./config/manager");
const config_1 = require("./types/config");
const channel_commands_1 = require("./commands/channel.commands");
const stream_commands_1 = require("./commands/stream.commands");
const monitor_commands_1 = require("./commands/monitor.commands");
const account_commands_1 = require("./commands/account.commands");
const use_commands_1 = require("./commands/use.commands");
process.on('uncaughtException', errors_1.handleUncaughtError);
process.on('unhandledRejection', errors_1.handleUnhandledRejection);
function getVersion() {
try {
const packagePath = (0, path_1.join)(__dirname, '..', 'package.json');
const packageJson = JSON.parse((0, fs_1.readFileSync)(packagePath, 'utf8'));
return packageJson.version;
}
catch (error) {
console.error('Failed to read version from package.json');
return '1.0.0';
}
}
async function loadAndValidateConfig(program) {
try {
const options = program.opts();
const configResult = await manager_1.configManager.load({
cliOptions: options,
});
if (configResult.config.debug) {
console.log('Configuration loaded successfully');
console.log(`Environment: ${configResult.config.environment}`);
console.log(`Base URL: ${configResult.config.baseUrl}`);
console.log(`Timeout: ${configResult.config.timeout}ms`);
console.log(`Max Retries: ${configResult.config.maxRetries}`);
console.log(`Loaded .env files: ${configResult.loadedEnvFiles.length}`);
if (configResult.loadedEnvFiles.length > 0) {
configResult.loadedEnvFiles.forEach(file => console.log(` - ${file}`));
}
}
return configResult.config;
}
catch (error) {
const args = process.argv.slice(2);
const isHelpOrVersion = args.some(arg => arg === '--help' || arg === '-h' || arg === '--version' || arg === '-v');
if (isHelpOrVersion) {
return null;
}
throw error;
}
}
function showQuickHelp() {
console.log(`Usage: polyv-live-cli [options] [command]
CLI tool for managing PolyV live streaming services
Commands:
account Manage account configurations
use Switch session account
channel Manage live channels
stream Stream operations
monitor Live monitoring dashboard
Quick Start:
$ polyv-live-cli account add <name> --app-id <id> --app-secret <secret> # Add account
$ polyv-live-cli use <name> # Switch to account
$ polyv-live-cli channel list -a <name> # Use specific account (short)
$ polyv-live-cli channel --help # Channel operations
$ polyv-live-cli stream --help # Stream operations
Run 'polyv-live-cli --help' for full help or 'polyv-live-cli <command> --help' for command help.`);
}
async function main() {
const program = new commander_1.Command();
program
.name('polyv-live-cli')
.description('CLI tool for managing PolyV live streaming services')
.version(getVersion(), '-v, --version', 'display version number')
.helpOption('-h, --help', 'display help for command');
program.configureHelp({
helpWidth: 80,
sortSubcommands: true,
});
program
.option('--appId <id>', 'PolyV application ID')
.option('--appSecret <secret>', 'PolyV application secret')
.option('--userId <id>', 'PolyV user ID (optional)')
.option('-a, --account <name>', 'use specific account configuration')
.option('--verbose', 'show authentication source information');
program
.option(`--${config_1.CONFIG_CLI_OPTIONS.ENVIRONMENT} <env>`, 'environment (development|production|test)')
.option(`--${config_1.CONFIG_CLI_OPTIONS.DEBUG}`, 'enable debug mode')
.option(`--${config_1.CONFIG_CLI_OPTIONS.TIMEOUT} <ms>`, 'API timeout in milliseconds')
.option(`--${config_1.CONFIG_CLI_OPTIONS.BASE_URL} <url>`, 'API base URL')
.option(`--${config_1.CONFIG_CLI_OPTIONS.MAX_RETRIES} <num>`, 'maximum retry attempts')
.option(`--${config_1.CONFIG_CLI_OPTIONS.CONFIG_PATH} <path>`, 'custom configuration file path');
(0, account_commands_1.registerAccountCommands)(program);
(0, use_commands_1.registerUseCommand)(program);
(0, channel_commands_1.registerChannelCommands)(program);
(0, stream_commands_1.registerStreamCommands)(program);
(0, monitor_commands_1.registerMonitorCommands)(program);
function getAllRegisteredCommands() {
const topLevel = [];
const subCommands = new Map();
if (program.commands && Array.isArray(program.commands)) {
program.commands.forEach(cmd => {
topLevel.push(cmd.name());
if (cmd.commands && cmd.commands.length > 0) {
const subCmdNames = cmd.commands.map((subcmd) => subcmd.name());
subCommands.set(cmd.name(), subCmdNames);
}
});
}
return { topLevel, subCommands };
}
program.addHelpText('after', `
Quick Start:
$ polyv-live-cli account add <name> --app-id <id> --app-secret <secret> # Add account
$ polyv-live-cli use <name> # Switch to account
$ polyv-live-cli channel --help # Channel operations
$ polyv-live-cli stream --help # Stream operations
$ polyv-live-cli monitor --help # Live monitoring dashboard
Authentication:
- Use 'polyv-live-cli account add' to add accounts
- Use 'polyv-live-cli use <name>' to switch accounts
- Or use -a <name> or --account <name> to specify account for single command
- Or use --appId and --appSecret parameters
- Or set POLYV_APP_ID and POLYV_APP_SECRET environment variables
`);
let unknownCommand = null;
program.on('command:*', (args) => {
unknownCommand = args[0] || null;
});
program.exitOverride();
const args = process.argv.slice(2);
const isHelpOrVersion = args.some(arg => arg === '--help' || arg === '-h' || arg === '--version' || arg === '-v');
if (args.length === 0) {
showQuickHelp();
return;
}
const hasValidCommand = args.includes('channel') || args.includes('stream') || args.includes('monitor') || args.includes('account') || args.includes('use');
if (hasValidCommand) {
try {
program.parse();
return;
}
catch (err) {
if (err.code === 'commander.help' || err.code === 'commander.helpDisplayed' || err.code === 'commander.version') {
process.exit(0);
}
if (err.code && err.code.startsWith('commander.')) {
if (err.message && err.message !== '(outputHelp)') {
console.error(err.message);
}
process.exit(err.exitCode || 1);
}
throw err;
}
}
if (!isHelpOrVersion && args.length > 0) {
const hasGlobalOptions = args.some(arg => arg.startsWith('--appId') || arg.startsWith('--appSecret') || arg.startsWith('--userId') ||
arg.startsWith('--environment') || arg.startsWith('--debug') || arg.startsWith('--timeout') ||
arg.startsWith('--baseUrl') || arg.startsWith('--maxRetries') || arg.startsWith('--config'));
const hasCommands = args.some(arg => arg === 'channel' || arg === 'stream' || arg === 'monitor' || arg === 'account' || arg === 'use' || arg === 'help');
const hasPotentialCommands = args.some(arg => {
if (arg.startsWith('-'))
return false;
const argIndex = args.indexOf(arg);
if (argIndex === 0)
return true;
const prevArg = args[argIndex - 1];
if (!prevArg)
return true;
return !['--appId', '--appSecret', '--userId', '--environment', '--timeout', '--baseUrl', '--maxRetries', '--config'].includes(prevArg);
});
if (hasGlobalOptions && !hasCommands && !hasPotentialCommands) {
let appId = '';
let appSecret = '';
let userId = '';
for (let i = 0; i < args.length; i++) {
if (args[i] === '--appId' && i + 1 < args.length) {
appId = args[i + 1] || '';
}
else if (args[i] === '--appSecret' && i + 1 < args.length) {
appSecret = args[i + 1] || '';
}
else if (args[i] === '--userId' && i + 1 < args.length) {
userId = args[i + 1] || '';
}
}
if (!appId)
appId = process.env['POLYV_APP_ID'] || '';
if (!appSecret)
appSecret = process.env['POLYV_APP_SECRET'] || '';
if (!userId)
userId = process.env['POLYV_USER_ID'] || '';
const hasAuthOptions = appId || appSecret || userId;
if (hasAuthOptions && (!appId || !appSecret)) {
try {
const { authAdapter } = require('./config/auth-adapter');
const authResult = authAdapter.tryGetAuthConfig({});
if (!authResult) {
const statusMessage = authAdapter.getStatusMessage({});
console.error(statusMessage);
process.exit(1);
}
}
catch (error) {
console.error('Auth configuration is incomplete');
process.exit(1);
}
}
}
}
try {
program.parse();
}
catch (err) {
if (err.code === 'commander.help' || err.code === 'commander.helpDisplayed') {
if (isHelpOrVersion) {
process.exit(0);
}
const registeredCommands = getAllRegisteredCommands();
const allKnownCommands = new Set([
...registeredCommands.topLevel,
...Array.from(registeredCommands.subCommands.values()).flat(),
'help'
]);
const potentialUnknownCommand = args.find((arg, index) => {
if (arg.startsWith('-'))
return false;
if (allKnownCommands.has(arg))
return false;
if (index > 0) {
const prevArg = args[index - 1];
if (prevArg && prevArg.startsWith('--'))
return false;
}
return true;
});
if (potentialUnknownCommand) {
try {
await loadAndValidateConfig(program);
}
catch (configError) {
(0, errors_1.logError)(configError instanceof Error ? configError : new Error(String(configError)));
process.exit(1);
}
console.error(`Unknown command: ${potentialUnknownCommand}`);
console.error('Run --help to see available commands');
process.exit(1);
}
const options = program.opts();
const hasAuthOptions = options['appId'] || options['appSecret'] || options['userId'];
if (hasAuthOptions && (!options['appId'] || !options['appSecret'])) {
try {
const { authAdapter } = require('./config/auth-adapter');
const authResult = authAdapter.tryGetAuthConfig(options);
if (!authResult) {
const statusMessage = authAdapter.getStatusMessage(options);
console.error(statusMessage);
process.exit(1);
}
}
catch (error) {
console.error('Auth configuration is incomplete');
process.exit(1);
}
}
showQuickHelp();
process.exit(0);
}
if (err.code === 'commander.version') {
process.exit(0);
}
if (err.code && err.code.startsWith('commander.')) {
if (err.message && err.message !== '(outputHelp)') {
console.error(err.message);
}
process.exit(err.exitCode || 1);
}
throw err;
}
const hasOnlyGlobalOptions = args.every(arg => {
if (arg.startsWith('-')) {
return arg.startsWith('--appId') || arg.startsWith('--appSecret') || arg.startsWith('--userId') ||
arg.startsWith('--environment') || arg.startsWith('--debug') || arg.startsWith('--timeout') ||
arg.startsWith('--baseUrl') || arg.startsWith('--maxRetries') || arg.startsWith('--config');
}
const argIndex = args.indexOf(arg);
if (argIndex > 0) {
const prevArg = args[argIndex - 1];
return prevArg === '--appId' || prevArg === '--appSecret' || prevArg === '--userId' ||
prevArg === '--environment' || prevArg === '--timeout' ||
prevArg === '--baseUrl' || prevArg === '--maxRetries' || prevArg === '--config';
}
return false;
});
if (hasOnlyGlobalOptions) {
const options = program.opts();
const hasAuthOptions = options['appId'] || options['appSecret'] || options['userId'];
if (hasAuthOptions && (!options['appId'] || !options['appSecret'])) {
try {
const { authAdapter } = require('./config/auth-adapter');
const authResult = authAdapter.tryGetAuthConfig(options);
if (!authResult) {
const statusMessage = authAdapter.getStatusMessage(options);
console.error(statusMessage);
process.exit(1);
}
}
catch (error) {
console.error('Auth configuration is incomplete');
process.exit(1);
}
}
showQuickHelp();
return;
}
if (!unknownCommand) {
const registeredCommands = getAllRegisteredCommands();
unknownCommand = args.find((arg, index) => {
if (arg.startsWith('-'))
return false;
if (registeredCommands.topLevel.includes(arg) || arg === 'help')
return false;
for (const [parentCmd, subCmds] of registeredCommands.subCommands) {
if (subCmds.includes(arg)) {
if (index > 0 && args[index - 1] === parentCmd) {
return false;
}
return true;
}
}
if (index > 0) {
const prevArg = args[index - 1];
if (prevArg && prevArg.startsWith('--'))
return false;
}
return true;
}) || null;
}
if (unknownCommand) {
const options = program.opts();
const appId = options['appId'] || process.env['POLYV_APP_ID'];
const appSecret = options['appSecret'] || process.env['POLYV_APP_SECRET'];
const hasAnyAuthOptions = options['appId'] || options['appSecret'] || options['userId'] ||
process.env['POLYV_APP_ID'] || process.env['POLYV_APP_SECRET'] || process.env['POLYV_USER_ID'];
if (hasAnyAuthOptions && (!appId || !appSecret)) {
try {
const { authAdapter } = require('./config/auth-adapter');
const authResult = authAdapter.tryGetAuthConfig(options);
if (!authResult) {
const statusMessage = authAdapter.getStatusMessage(options);
console.error(statusMessage);
process.exit(1);
}
}
catch (error) {
console.error('Auth configuration is incomplete');
process.exit(1);
}
}
if (!hasAnyAuthOptions) {
try {
const { authAdapter } = require('./config/auth-adapter');
const authResult = authAdapter.tryGetAuthConfig(options);
if (!authResult) {
const statusMessage = authAdapter.getStatusMessage(options);
console.error(statusMessage);
process.exit(1);
}
}
catch (error) {
console.error('Auth configuration is incomplete');
process.exit(1);
}
}
console.error(`Unknown command: ${unknownCommand}`);
console.error('Run --help to see available commands');
process.exit(1);
}
if (!isHelpOrVersion) {
const hasActualCommands = args.some(arg => arg === 'channel' || arg === 'stream' || arg === 'monitor' || arg === 'account' || arg === 'use' ||
arg.startsWith('channel ') || arg.startsWith('stream ') || arg.startsWith('monitor ') || arg.startsWith('account ') || arg.startsWith('use '));
if (unknownCommand && !hasActualCommands) {
try {
const config = await loadAndValidateConfig(program);
if (!config) {
console.error(`Unknown command: ${unknownCommand}`);
console.error('Run --help to see available commands');
process.exit(1);
}
}
catch (configError) {
(0, errors_1.logError)(configError instanceof Error ? configError : new Error(String(configError)));
process.exit(1);
}
console.error(`Unknown command: ${unknownCommand}`);
console.error('Run --help to see available commands');
process.exit(1);
}
if (hasActualCommands) {
return;
}
showQuickHelp();
}
}
if (require.main === module) {
main().catch(error => {
(0, errors_1.logError)(error);
process.exit(1);
});
}
function extractCommands(program) {
const topLevel = [];
const subCommands = new Map();
if (program.commands && Array.isArray(program.commands)) {
program.commands.forEach(cmd => {
topLevel.push(cmd.name());
if (cmd.commands && cmd.commands.length > 0) {
const subCmdNames = cmd.commands.map((subcmd) => subcmd.name());
subCommands.set(cmd.name(), subCmdNames);
}
});
}
return { topLevel, subCommands };
}
//# sourceMappingURL=index.js.map