Command-line interface for designing and building Swagger-compliant APIs in Node.js
—
Internal modules and utilities for programmatic usage of Swagger CLI functionality in Node.js applications.
Interactive command-line interface utilities for prompts, validation, and command execution.
const cli = require('swagger/lib/util/cli');/**
* Require answers to questions, prompting user for missing values
* @param {Object[]} questions - Array of question objects
* @param {Object} results - Existing results object (optional)
* @param {Function} cb - Callback function with completed results
*/
function requireAnswers(questions, results, cb);
/**
* Update answers with new defaults and re-prompt
* @param {Object[]} questions - Array of question objects
* @param {Object} results - Existing results object
* @param {Function} cb - Callback function with updated results
*/
function updateAnswers(questions, results, cb);
/**
* Single choice selection from list
* @param {string} prompt - Prompt message
* @param {string[]} choices - Array of choice options
* @param {Function} cb - Callback function with selected choice
*/
function chooseOne(prompt, choices, cb);
/**
* Confirmation prompt
* @param {string} prompt - Prompt message
* @param {boolean} defaultBool - Default value (optional, default: true)
* @param {Function} cb - Callback function with boolean result
*/
function confirm(prompt, defaultBool, cb);
/**
* Text input prompt
* @param {string} prompt - Prompt message
* @param {string} defaultValue - Default value (optional)
* @param {Function} cb - Callback function with input value
*/
function prompt(prompt, defaultValue, cb);Usage Examples:
const cli = require('swagger/lib/util/cli');
// Interactive question flow
const questions = [
{ name: 'name', message: 'Project name?' },
{ name: 'framework', message: 'Framework?', type: 'list', choices: ['express', 'hapi'] }
];
cli.requireAnswers(questions, function(answers) {
console.log('Project:', answers.name, 'Framework:', answers.framework);
});
// Confirmation prompt
cli.confirm('Delete existing files?', false, function(confirmed) {
if (confirmed) {
console.log('Proceeding with deletion...');
}
});
// Choice selection
cli.chooseOne('Select environment:', ['development', 'staging', 'production'], function(env) {
console.log('Selected environment:', env);
});/**
* Execute command with error handling and output formatting
* @param {Function} command - Command function to execute
* @param {string} header - Optional header for output
* @returns {Function} Wrapped command function
*/
function execute(command, header);
/**
* Print output and exit process
* @param {Error} err - Error object (if any)
* @param {*} output - Output to print
* @param {number} code - Exit code (optional)
*/
function printAndExit(err, output, code);
/**
* Validate commander.js app configuration
* @param {Object} app - Commander.js app instance
*/
function validate(app);
/**
* Get package version
* @returns {string} Package version string
*/
function version();Event-based feedback system for capturing and displaying command output and progress messages.
const feedback = require('swagger/lib/util/feedback');/**
* Listen for feedback events
* @param {Function} cb - Callback function receiving feedback messages
*/
function on(cb);
/**
* Emit feedback message
* @param {string} string - Message string (supports util.format formatting)
* @param {...*} args - Additional formatting arguments
*/
function emit(string, ...args);Usage Examples:
const feedback = require('swagger/lib/util/feedback');
// Listen for feedback
feedback.on(function(message) {
console.log('[FEEDBACK]', message);
});
// Emit messages
feedback.emit('Starting operation...');
feedback.emit('Processing %d files in %s', 5, '/path/to/dir');
feedback.emit('Operation completed successfully');Programmatic access to project management functionality.
const project = require('swagger/lib/commands/project/project');/**
* Create new Swagger project
* @param {string} name - Project name
* @param {Object} options - Creation options
* @param {string} options.framework - Target framework
* @param {Function} cb - Callback function
*/
function create(name, options, cb);
/**
* Start project development server
* @param {string} directory - Project directory
* @param {Object} options - Server options
* @param {Function} cb - Callback function
*/
function start(directory, options, cb);
/**
* Verify project configuration
* @param {string} directory - Project directory
* @param {Object} options - Verification options
* @param {Function} cb - Callback function
*/
function verify(directory, options, cb);
/**
* Launch Swagger editor
* @param {string} directory - Project directory
* @param {Object} options - Editor options
* @param {Function} cb - Callback function
*/
function edit(directory, options, cb);
/**
* Open project in browser
* @param {string} directory - Project directory
* @param {Object} options - Browser options
* @param {Function} cb - Callback function
*/
function open(directory, options, cb);
/**
* Run project tests
* @param {string} directory - Project directory or test file
* @param {Object} options - Test options
* @param {Function} cb - Callback function
*/
function test(directory, options, cb);
/**
* Generate test templates
* @param {string} directory - Project directory
* @param {Object} options - Generation options
* @param {Function} cb - Callback function
*/
function generateTest(directory, options, cb);/**
* Read and parse project configuration
* @param {string} directory - Project directory
* @param {Object} options - Read options
* @param {Function} cb - Callback function with project object
*/
function read(directory, options, cb);
// Configuration constants
const frameworks = {
connect: { source: 'connect' },
express: { source: 'connect', overlay: 'express' },
hapi: { source: 'connect', overlay: 'hapi' },
restify: { source: 'connect', overlay: 'restify' },
sails: { source: 'sails' }
};
const assertiontypes = ['expect', 'should', 'assert'];
const testmodules = ['supertest', 'request'];Usage Examples:
const project = require('swagger/lib/commands/project/project');
// Create project programmatically
project.create('my-api', { framework: 'express' }, function(err, result) {
if (err) {
console.error('Project creation failed:', err);
} else {
console.log('Project created:', result);
}
});
// Read project configuration
project.read('./my-api', {}, function(err, projectConfig) {
if (err) {
console.error('Failed to read project:', err);
} else {
console.log('Project name:', projectConfig.api.name);
console.log('Project host:', projectConfig.api.host);
console.log('Swagger file:', projectConfig.api.swaggerFile);
}
});Direct access to command functionality for validation and conversion.
const { convert, validate } = require('swagger/lib/commands/commands');/**
* Validate Swagger document
* @param {string} file - File path or null for stdin
* @param {Object} options - Validation options
* @param {boolean} options.json - Output as JSON
* @param {Function} cb - Callback function
*/
function validate(file, options, cb);/**
* Convert Swagger 1.2 to 2.0
* @param {string} filePath - Main resource listing file
* @param {string[]} apiDeclarations - API declaration files
* @param {Object} options - Conversion options
* @param {string} options.outputFile - Output file path
* @param {Function} cb - Callback function
*/
function convert(filePath, apiDeclarations, options, cb);Utilities for validating Swagger documents programmatically.
const spec = require('swagger/lib/util/spec');/**
* Validate Swagger specification document
* @param {Object} swagger - Swagger specification object
* @param {Object} options - Validation options
* @param {boolean} options.json - Output as JSON format
* @param {Function} cb - Callback function with validation results
*/
function validateSwagger(swagger, options, cb);Usage Examples:
const spec = require('swagger/lib/util/spec');
const fs = require('fs');
const yaml = require('js-yaml');
// Load and validate YAML Swagger file
const swaggerDoc = yaml.safeLoad(fs.readFileSync('./api/swagger/swagger.yaml', 'utf8'));
spec.validateSwagger(swaggerDoc, {}, function(err, results) {
if (err) {
console.error('Validation failed:', err);
} else {
console.log('Validation results:', results);
}
});
// Get JSON formatted results
spec.validateSwagger(swaggerDoc, { json: true }, function(err, jsonResults) {
if (err) {
console.error('Validation failed:', err);
} else {
console.log('JSON Results:', jsonResults);
}
});Cross-platform browser launching utilities for opening URLs.
const browser = require('swagger/lib/util/browser');/**
* Open URL in system default browser
* @param {string} url - URL to open
* @param {Function} cb - Callback function
* @param {string} platform - Platform override for testing (optional)
*/
function open(url, cb, platform);Usage Examples:
const browser = require('swagger/lib/util/browser');
// Open Swagger documentation
browser.open('https://swagger.io/docs/', function(err) {
if (err) {
console.error('Failed to open browser:', err);
} else {
console.log('Browser opened successfully');
}
});
// Open local development server
browser.open('http://localhost:10010', function(err) {
if (err) {
console.error('Could not open local server:', err);
}
});Network connectivity and port checking utilities.
const net = require('swagger/lib/util/net');/**
* Check if a port is open and available
* @param {number} port - Port number to check
* @param {number} timeout - Connection timeout in milliseconds (optional)
* @param {Function} cb - Callback function with boolean result
*/
function isPortOpen(port, timeout, cb);Usage Examples:
const net = require('swagger/lib/util/net');
// Check if default Swagger port is available
net.isPortOpen(10010, function(err, isOpen) {
if (err) {
console.error('Port check failed:', err);
} else if (isOpen) {
console.log('Port 10010 is available');
} else {
console.log('Port 10010 is in use');
}
});
// Check with custom timeout
net.isPortOpen(8080, 5000, function(err, isOpen) {
if (err) {
console.error('Port check timed out:', err);
} else {
console.log('Port 8080 status:', isOpen ? 'available' : 'in use');
}
});Access to configuration constants and environment variable handling.
const config = require('swagger/config');const config = {
rootDir: string, // Root directory path (swagger package directory)
userHome: string, // User home directory
debug: boolean, // Debug mode flag (from DEBUG env var)
nodeModules: string, // Node modules path
swagger: {
fileName: string, // Default Swagger file path ('api/swagger/swagger.yaml')
editorDir: string, // Swagger editor directory
editorConfig: { // Editor configuration object
analytics: Object, // Analytics configuration
disableCodeGen: boolean, // Code generation toggle
disableNewUserIntro: boolean, // New user intro toggle
examplesFolder: string, // Examples directory path
exampleFiles: Array, // Example files list
autocompleteExtension: Object, // Autocomplete settings
useBackendForStorage: boolean, // Backend storage toggle
backendEndpoint: string, // Backend API endpoint
backendHealthCheckTimeout: number, // Health check timeout
useYamlBackend: boolean, // YAML backend toggle
disableFileMenu: boolean, // File menu toggle
enableTryIt: boolean, // Try-it functionality toggle
headerBranding: boolean, // Header branding toggle
brandingCssClass: string, // CSS class for branding
schemaUrl: string, // Schema validation URL
importProxyUrl: string // Import proxy URL
}
},
project: {
port: number, // Default project port (10010 or PORT env var)
skeletonsDir: string // Project templates directory
}
};Usage Examples:
const config = require('swagger/config');
console.log('Swagger CLI root:', config.rootDir);
console.log('Default project port:', config.project.port);
console.log('Swagger file location:', config.swagger.fileName);
// Check debug mode
if (config.debug) {
console.log('Debug mode is enabled');
}All programmatic APIs use Node.js error-first callback conventions:
function(err, result) {
if (err) {
// Handle error
console.error('Operation failed:', err.message);
} else {
// Process result
console.log('Operation succeeded:', result);
}
}Common error types:
Install with Tessl CLI
npx tessl i tessl/npm-swagger