CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-istanbul

Comprehensive JavaScript code coverage tool that computes statement, line, function and branch coverage with module loader hooks for transparent instrumentation

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

configuration.mddocs/

Configuration Management

Configuration management loads and manages Istanbul settings from files or objects with validation and defaults. The configuration system supports YAML and JSON formats with comprehensive options for instrumentation, reporting, and hooks.

Capabilities

Configuration Loading

Load Istanbul configuration from files or objects with validation and default values.

const config = {
    /**
     * Loads configuration from a file
     * @param {string} file - Path to configuration file (.json, .yml, .yaml)
     * @param {Object} overrides - Optional overrides to merge with loaded config
     * @returns {Configuration} Configuration instance
     */
    loadFile(file: string, overrides?: Object): Configuration;
    
    /**
     * Loads configuration from an object
     * @param {Object} obj - Configuration object
     * @param {Object} overrides - Optional overrides to merge with config
     * @returns {Configuration} Configuration instance
     */
    loadObject(obj: Object, overrides?: Object): Configuration;
    
    /**
     * Returns the default configuration object
     * @returns {Object} Default configuration with all options
     */
    defaultConfig(): Object;
};

/**
 * Configuration class providing typed access to all Istanbul settings
 */
class Configuration {
    constructor(obj: Object, overrides?: Object);
    
    /** Instrumentation options */
    instrumentation: InstrumentationOptions;
    
    /** Reporting options */  
    reporting: ReportingOptions;
    
    /** Hook options */
    hooks: HookOptions;
    
    /** Coverage threshold checking options */
    check: CheckOptions;
}

Usage Examples:

const { config } = require('istanbul');

// Load configuration from file
const cfg1 = config.loadFile('.istanbul.yml');
const cfg2 = config.loadFile('coverage-config.json');

// Load with overrides
const cfg3 = config.loadFile('.istanbul.yml', {
    reporting: { dir: './custom-coverage' }
});

// Load from object
const cfg4 = config.loadObject({
    instrumentation: {
        'default-excludes': true,
        excludes: ['**/test/**']
    },
    reporting: {
        print: 'summary',
        reports: ['text', 'html']
    }
});

// Get default configuration
const defaults = config.defaultConfig();
console.log('Default config:', JSON.stringify(defaults, null, 2));

Instrumentation Options

Configuration options for code instrumentation behavior.

interface InstrumentationOptions {
    /**
     * Returns the root directory for instrumentation
     * @returns {string} Root directory path
     */
    root(): string;
    
    /**
     * Returns array of file extensions to instrument
     * @returns {string[]} File extensions (e.g., ['.js'])
     */
    extensions(): string[];
    
    /**
     * Returns whether to use default excludes (node_modules, etc.)
     * @returns {boolean} True if default excludes should be used
     */
    defaultExcludes(): boolean;
    
    /**
     * Returns array of exclude patterns
     * @param {boolean} excludeTests - Whether to exclude test files
     * @returns {string[]} Exclude patterns
     */
    excludes(excludeTests?: boolean): string[];
    
    /**
     * Returns whether to copy non-JS files to output directory
     * @returns {boolean} True if non-JS files should be copied
     */
    completeCopy(): boolean;
    
    /**
     * Returns whether to embed source code in coverage objects
     * @returns {boolean} True if source should be embedded
     */
    embedSource(): boolean;
    
    /**
     * Returns the global coverage variable name
     * @returns {string} Coverage variable name
     */
    variable(): string;
    
    /**
     * Returns whether output should be compact (minified)
     * @returns {boolean} True for compact output
     */
    compact(): boolean;
    
    /**
     * Returns whether to preserve comments in instrumented code
     * @returns {boolean} True to preserve comments
     */
    preserveComments(): boolean;
    
    /**
     * Returns whether to save baseline coverage file
     * @returns {boolean} True to save baseline
     */
    saveBaseline(): boolean;
    
    /**
     * Returns path for baseline coverage file
     * @returns {string} Baseline file path
     */
    baselineFile(): string;
    
    /**
     * Returns whether code uses ES6 modules
     * @returns {boolean} True for ES6 module support
     */
    esModules(): boolean;
    
    /**
     * Returns whether to include all source files in coverage
     * @returns {boolean} True to include all sources
     */
    includeAllSources(): boolean;
    
    /**
     * Returns whether to include process ID in coverage filename
     * @returns {boolean} True to include PID
     */
    includePid(): boolean;
}

Configuration Example:

# .istanbul.yml
instrumentation:
    default-excludes: true
    excludes: ['**/test/**', '**/spec/**', '**/*.test.js']
    embed-source: false
    variable: '__coverage__'
    compact: true
    preserve-comments: false
    complete-copy: false
    save-baseline: false
    baseline-file: './coverage/coverage-baseline.json'
    include-all-sources: false
    es-modules: true
    include-pid: false

Reporting Options

Configuration options for coverage report generation.

interface ReportingOptions {
    /**
     * Returns console print mode
     * @returns {'summary'|'detail'|'both'|'none'} Print mode
     */
    print(): 'summary' | 'detail' | 'both' | 'none';
    
    /**
     * Returns array of report formats to generate
     * @returns {string[]} Report format names
     */
    reports(): string[];
    
    /**
     * Returns report output directory
     * @returns {string} Output directory path
     */
    dir(): string;
    
    /**
     * Returns detailed report configuration
     * @returns {Object} Report-specific configuration options
     */
    reportConfig(): Object;
    
    /**
     * Returns coverage watermark thresholds
     * @returns {Object} Watermark configuration
     */
    watermarks(): Object;
}

Configuration Example:

# .istanbul.yml
reporting:
    print: summary
    reports: ['text-summary', 'html', 'lcov']  
    dir: ./coverage
    watermarks:
        statements: [50, 80]
        branches: [50, 80] 
        functions: [50, 80]
        lines: [50, 80]
    clover:
        dir: ./coverage
        file: clover.xml
    html:
        verbose: true
        linkMapper: null
    lcov:
        dir: ./coverage
        file: lcov.info

Hook Options

Configuration options for runtime instrumentation hooks.

interface HookOptions {
    /**
     * Returns whether to hook vm.runInThisContext
     * @returns {boolean} True to hook runInThisContext
     */
    hookRunInContext(): boolean;
    
    /**
     * Returns post-require hook module path
     * @returns {string|null} Module path or null
     */
    postRequireHook(): string | null;
    
    /**
     * Returns whether to handle SIGINT for coverage reporting
     * @returns {boolean} True to handle SIGINT
     */
    handleSigint(): boolean;
}

Configuration Example:

# .istanbul.yml
hooks:
    hook-run-in-context: false
    post-require-hook: null
    handle-sigint: true

Coverage Threshold Options

Configuration options for coverage threshold validation.

interface CheckOptions {
    /**
     * Global coverage thresholds that apply to entire codebase
     */
    global: {
        statements: number;    // Global statement coverage threshold (0-100)
        lines: number;         // Global line coverage threshold (0-100)
        branches: number;      // Global branch coverage threshold (0-100)
        functions: number;     // Global function coverage threshold (0-100)
        excludes: string[];    // File patterns to exclude from global checks
    };
    
    /**
     * Per-file coverage thresholds that apply to each individual file
     */
    each: {
        statements: number;    // Per-file statement coverage threshold (0-100)
        lines: number;         // Per-file line coverage threshold (0-100)
        branches: number;      // Per-file branch coverage threshold (0-100)
        functions: number;     // Per-file function coverage threshold (0-100)
        excludes: string[];    // File patterns to exclude from per-file checks
    };
}

Configuration Example:

# .istanbul.yml
check:
    global:
        statements: 80
        branches: 75
        functions: 85
        lines: 80
        excludes: ['**/test/**']
    each:
        statements: 70
        branches: 65
        functions: 75
        lines: 70
        excludes: ['**/fixtures/**']

Complete Configuration Examples

Basic Configuration (JSON)

{
    "instrumentation": {
        "default-excludes": true,
        "excludes": ["**/test/**", "**/*.test.js"],
        "embed-source": false,
        "variable": "__coverage__",
        "compact": true,
        "preserve-comments": false
    },
    "reporting": {
        "print": "summary", 
        "reports": ["text", "html", "lcov"],
        "dir": "./coverage"
    },
    "hooks": {
        "hook-run-in-context": false,
        "post-require-hook": null,
        "handle-sigint": true
    }
}

Advanced Configuration (YAML)

instrumentation:
    default-excludes: true
    excludes: 
        - '**/test/**'
        - '**/tests/**'
        - '**/*.test.js'
        - '**/*.spec.js'
        - '**/node_modules/**'
    embed-source: false
    variable: '__coverage__'
    compact: true
    preserve-comments: false
    complete-copy: false
    save-baseline: true
    baseline-file: './coverage/baseline.json'
    include-all-sources: true
    es-modules: true

reporting:
    print: both
    reports: ['text-summary', 'html', 'lcov', 'json-summary']
    dir: ./coverage
    watermarks:
        statements: [70, 90]
        branches: [60, 85]
        functions: [75, 95]
        lines: [70, 90]
    html:
        verbose: true
        subdir: html-report
    lcov:
        dir: ./coverage
        file: coverage.lcov
    json-summary:
        file: coverage-summary.json

hooks:
    hook-run-in-context: false
    post-require-hook: './test/coverage-setup.js'
    handle-sigint: true

check:
    global:
        statements: 85
        branches: 80
        functions: 90
        lines: 85
    each:
        statements: 75
        branches: 70
        functions: 80
        lines: 75

Using Configuration Objects

const { config, Instrumenter, Reporter } = require('istanbul');

// Load configuration
const cfg = config.loadFile('./.istanbul.yml');

// Use with instrumenter
const instrumenter = new Instrumenter({
    coverageVariable: cfg.instrumentation.variable(),
    embedSource: cfg.instrumentation.embedSource(),
    preserveComments: cfg.instrumentation.preserveComments(),
    esModules: cfg.instrumentation.esModules()
});

// Use with reporter
const reporter = new Reporter(cfg, cfg.reporting.dir());
cfg.reporting.reports().forEach(format => {
    reporter.add(format);
});

// Access specific options
console.log('Coverage variable:', cfg.instrumentation.variable());
console.log('Report directory:', cfg.reporting.dir());
console.log('Exclude patterns:', cfg.instrumentation.excludes());
console.log('Report formats:', cfg.reporting.reports());

Configuration Validation

Istanbul validates configuration options and provides helpful error messages:

try {
    const cfg = config.loadFile('./invalid-config.yml');
} catch (error) {
    console.error('Configuration error:', error.message);
    // Handle invalid configuration
}

// Check for required values
const cfg = config.loadFile('./.istanbul.yml');
if (!cfg.reporting.dir()) {
    throw new Error('Report directory must be configured');
}

Environment-Specific Configuration

Load different configurations based on environment:

const environment = process.env.NODE_ENV || 'development';
const configFile = `./.istanbul.${environment}.yml`;

let cfg;
try {
    cfg = config.loadFile(configFile);
    console.log(`Loaded ${environment} configuration`);
} catch (error) {
    console.log('Loading default configuration');
    cfg = config.loadFile('./.istanbul.yml');
}

// Override with environment variables
const overrides = {};
if (process.env.COVERAGE_DIR) {
    overrides.reporting = { dir: process.env.COVERAGE_DIR };
}

if (Object.keys(overrides).length > 0) {
    cfg = config.loadObject(cfg, overrides);
}

Programmatic Configuration

Create configuration objects programmatically:

const customConfig = {
    instrumentation: {
        'default-excludes': true,
        'excludes': ['**/test/**'],
        'embed-source': false,
        'variable': '__coverage__',
        'es-modules': true
    },
    reporting: {
        'print': 'summary',
        'reports': ['html', 'lcov'],
        'dir': './coverage'
    },
    hooks: {
        'hook-run-in-context': false,
        'handle-sigint': true
    }
};

const cfg = config.loadObject(customConfig);

// Merge with overrides
const cfg2 = config.loadObject(customConfig, {
    reporting: { dir: './custom-coverage' }
});

docs

cli.md

collection.md

configuration.md

hooks.md

index.md

instrumentation.md

reporting.md

storage.md

tree-summarizer.md

utilities.md

tile.json