Complete programmatic usage documentation for npq.
While npq is designed as a CLI tool, its internal modules can be imported for programmatic usage:
// Main marshall orchestrator
const Marshall = require('npq/lib/marshall');
const marshall = new Marshall({
pkgs: ['express@latest'],
progressManager: null
});
// Run all marshalls and get results
const results = await marshall.run();
// Returns: Array of MarshallResult objects
// Example result structure:
// [
// {
// marshall: 'age',
// status: null,
// errors: [],
// warnings: [],
// data: { 'express@4.18.2': { packageAge: 120, versionAge: 30 } },
// categoryId: 'PackageHealth'
// },
// ...
// ]
// CLI parser
const { CliParser } = require('npq/lib/cli');
const args = CliParser.parseArgsFull();
// Returns: CliArgsFull object
// Example: {
// packages: ['express@latest'],
// packageManager: 'npm',
// dryRun: false,
// plain: false,
// disableAutoContinue: false
// }
// Registry utilities
const PackageRepoUtils = require('npq/lib/helpers/packageRepoUtils');
const utils = new PackageRepoUtils();
// Get package metadata
const packageInfo = await utils.getPackageInfo('express');
// Returns: Full package metadata from npm registry
// Example structure includes: name, versions, time, maintainers, etc.
// Resolve version spec to actual version
const version = await utils.resolvePackageVersion('express', 'latest');
// Returns: '4.18.2' (actual version string)
// Get specific version info
const versionInfo = await utils.getPackageVersionInfo('express', '4.18.2');
// Returns: Specific version metadata including dependencies, scripts, etc.const Marshall = require('npq/lib/marshall');
const PackageRepoUtils = require('npq/lib/helpers/packageRepoUtils');
const { marshallCategories } = require('npq/lib/marshalls/constants');
// Initialize utilities
const packageRepoUtils = new PackageRepoUtils();
// Create marshall instance
const marshall = new Marshall({
pkgs: ['express@latest', 'lodash@^4.17.21'],
progressManager: null,
packageRepoUtils: packageRepoUtils
});
// Run all security checks
const results = await marshall.run();
// Process results
results.forEach(result => {
console.log(`Marshall: ${result.marshall}`);
console.log(`Category: ${result.categoryId}`);
console.log(`Errors: ${result.errors.length}`);
console.log(`Warnings: ${result.warnings.length}`);
// Access per-package data
Object.keys(result.data).forEach(pkg => {
console.log(`Package ${pkg}:`, result.data[pkg]);
});
// Process errors
result.errors.forEach(error => {
console.error(`Error for ${error.pkg}: ${error.message}`);
});
// Process warnings
result.warnings.forEach(warning => {
console.warn(`Warning for ${warning.pkg}: ${warning.message}`);
});
});
// Check if any errors occurred
const hasErrors = results.some(r => r.errors.length > 0);
const hasWarnings = results.some(r => r.warnings.length > 0);
if (hasErrors) {
console.error('Security errors detected - installation blocked');
process.exit(1);
} else if (hasWarnings) {
console.warn('Security warnings detected - review before installing');
}const Marshall = require('npq/lib/marshall');
const ora = require('ora');
// Create spinner for progress indication
const spinner = ora('Running security checks...').start();
const marshall = new Marshall({
pkgs: ['express@latest'],
progressManager: spinner
});
try {
const results = await marshall.run();
spinner.succeed('Security checks completed');
// Process results...
} catch (error) {
spinner.fail('Security checks failed');
throw error;
}Each marshall returns results in a standardized format:
interface MarshallResult {
marshall: string; // Marshall name (e.g., 'age', 'snyk', 'scripts')
status: null | string; // Status (usually null, may contain error state)
errors: Array<{ // Fatal errors that block installation
pkg: string; // Package spec (name@version)
message: string; // Error description
}>;
warnings: Array<{ // Non-fatal warnings
pkg: string;
message: string;
}>;
data: { // Per-package validation data
[packageString: string]: any; // Package-specific data returned by marshall
};
categoryId: string; // Category: 'SupplyChainSecurity', 'PackageHealth', or 'MalwareDetection'
}Example MarshallResult:
// Example result from age marshall
{
marshall: 'age',
status: null,
errors: [
{
pkg: 'new-package@1.0.0',
message: 'Detected a newly published package: created 15 days. Act carefully'
}
],
warnings: [
{
pkg: 'old-package@2.0.0',
message: 'Detected an old package: created 400 days ago'
}
],
data: {
'new-package@1.0.0': {
packageAge: 15,
versionAge: 15,
packageCreated: new Date('2024-01-01'),
versionPublished: new Date('2024-01-01')
},
'old-package@2.0.0': {
packageAge: 400,
versionAge: 400,
packageCreated: new Date('2022-12-01'),
versionPublished: new Date('2022-12-01')
}
},
categoryId: 'PackageHealth'
}// Category constants used in marshall results
const marshallCategories = {
SupplyChainSecurity: {
id: 'SupplyChainSecurity',
title: 'Supply Chain Security'
},
PackageHealth: {
id: 'PackageHealth',
title: 'Package Health'
},
MalwareDetection: {
id: 'MalwareDetection',
title: 'Malware Detection'
}
};
// Access in code
const { marshallCategories } = require('npq/lib/marshalls/constants');
// Usage example
const category = marshallCategories.SupplyChainSecurity;
console.log(category.id); // 'SupplyChainSecurity'
console.log(category.title); // 'Supply Chain Security'// Exit codes returned by npq CLI
type ExitCode = 0 | 1 | -1;
// 0: Success (no errors, or user confirmed installation)
// 1: User aborted operation (Ctrl+C or explicit 'n' response)
// -1: Error occurred (package not found, validation failed, network error, etc.)# In CI/CD scripts
if npq install express --dry-run; then
npm install express
else
echo "Security audit failed"
exit 1
fi
# Check exit code explicitly
npq install package --dry-run
EXIT_CODE=$?
if [ $EXIT_CODE -eq 0 ]; then
echo "Audit passed"
elif [ $EXIT_CODE -eq 1 ]; then
echo "User aborted"
elif [ $EXIT_CODE -eq -1 ]; then
echo "Error occurred"
fi
# Handle in Node.js scripts
const { execSync } = require('child_process');
try {
execSync('npq install express --dry-run', { stdio: 'inherit' });
// Exit code 0 - proceed with installation
execSync('npm install express', { stdio: 'inherit' });
} catch (error) {
if (error.status === 1) {
console.log('User aborted');
} else if (error.status === -1) {
console.error('Security audit failed');
process.exit(1);
}
}Note: Programmatic usage is not officially documented or supported. Use at your own risk. Internal APIs may change without notice.