npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@bernierllc/license-manager

v0.1.0

Published

Pure license management utilities for adding and validating license headers

Downloads

82

Readme

@bernierllc/license-manager

Pure license management utilities for adding and validating license headers across different file types.

Features

  • File Type Detection: Automatically detects file types and applies appropriate license formats
  • Multiple License Formats: Supports C-style comments, Python docstrings, HTML comments, and more
  • License Validation: Validates existing license headers for compliance
  • Directory Scanning: Scans entire directories for license compliance
  • Customizable Templates: Configurable license templates and file type mappings
  • Dry Run Mode: Preview changes without modifying files
  • Comprehensive Testing: Full test coverage with mocked file system

Installation

npm install @bernierllc/license-manager

Quick Start

import { LicenseManager } from '@bernierllc/license-manager';

const licenseManager = new LicenseManager();

// Add license header to a file
const success = licenseManager.addLicenseHeader('src/my-file.js');

// Validate existing license header
const validation = licenseManager.validateLicenseHeader('src/my-file.js');
console.log('Has license:', validation.hasLicense);
console.log('Is valid:', validation.isValid);

// Scan directory for compliance
const scanResult = licenseManager.scanDirectory('./src');
console.log('Compliance rate:', scanResult.complianceRate);

API Reference

LicenseManager

Main class for license management operations.

Constructor

new LicenseManager(config?: Partial<LicenseTemplateConfig>)

Creates a new license manager instance with optional custom configuration.

Methods

detectFileType(filePath: string): FileType

Detects the file type based on file extension.

const fileType = licenseManager.detectFileType('src/component.tsx');
// Returns: 'tsx'
getLicenseTemplate(fileType: FileType, options?: LicenseHeaderOptions): LicenseTemplate

Gets the appropriate license template for a file type.

const template = licenseManager.getLicenseTemplate('js', {
  copyrightYear: 2024,
  companyName: 'My Company'
});
generateLicenseHeader(filePath: string, options?: LicenseHeaderOptions): string

Generates a license header for a specific file.

const header = licenseManager.generateLicenseHeader('src/file.js');
// Returns: "/*\nCopyright (c) 2025 Bernier LLC\n...\n*/\n\n"
validateLicenseHeader(filePath: string, options?: LicenseHeaderOptions): LicenseValidationResult

Validates if a file has the correct license header.

const result = licenseManager.validateLicenseHeader('src/file.js');
console.log(result.hasLicense); // boolean
console.log(result.isValid); // boolean
console.log(result.errors); // string[]
addLicenseHeader(filePath: string, options?: LicenseHeaderOptions): boolean

Adds a license header to a file if it doesn't already have one.

const success = licenseManager.addLicenseHeader('src/file.js', {
  dryRun: true // Preview without writing
});
scanDirectory(dirPath: string, options?: LicenseHeaderOptions): LicenseScanResult

Scans a directory for license compliance.

const result = licenseManager.scanDirectory('./src');
console.log(`Compliance: ${result.complianceRate}%`);
console.log(`Files with license: ${result.filesWithLicense}`);
console.log(`Files missing license: ${result.filesWithoutLicense}`);
getConfig(): LicenseTemplateConfig

Returns the current configuration.

updateConfig(newConfig: Partial<LicenseTemplateConfig>): void

Updates the configuration.

Supported File Types

The license manager supports a wide range of file types with appropriate license formats:

C-Style Comments (/* */)

  • JavaScript (.js, .jsx)
  • TypeScript (.ts, .tsx)
  • CSS (.css)
  • SQL (.sql)
  • Shell scripts (.sh, .bash)
  • C/C++ (.c, .cpp, .h, .hpp)
  • Java (.java)
  • PHP (.php)
  • Ruby (.rb)
  • Go (.go)
  • Rust (.rs)
  • Swift (.swift)
  • Kotlin (.kt)
  • Scala (.scala)
  • And many more...

Python Docstrings (""")

  • Python (.py)

HTML Comments ()

  • HTML (.html)

No License Required

  • Log files (.log)
  • Lock files (.lock)
  • Source maps (.map)

Configuration

LicenseTemplateConfig

interface LicenseTemplateConfig {
  templates: Record<string, LicenseTemplate>;
  defaultTemplate: string;
  fileTypeMapping: Record<FileType, string>;
  excludePatterns: string[];
  includePatterns: string[];
}

Custom Configuration Example

const customConfig: Partial<LicenseTemplateConfig> = {
  templates: {
    'mit': {
      text: 'MIT License\nCopyright (c) 2025 Your Company',
      format: 'c-style',
      startDelimiter: '/*',
      endDelimiter: '*/'
    }
  },
  fileTypeMapping: {
    'js': 'mit',
    'ts': 'mit'
  },
  excludePatterns: [
    'node_modules/**',
    'dist/**',
    'build/**'
  ]
};

const licenseManager = new LicenseManager(customConfig);

License Header Options

LicenseHeaderOptions

interface LicenseHeaderOptions {
  copyrightYear?: number;
  companyName?: string;
  licenseType?: 'limited-use' | 'mit' | 'apache' | 'gpl' | 'custom';
  customText?: string;
  skipFiles?: string[];
  includeFiles?: string[];
  dryRun?: boolean;
}

Options Example

const options: LicenseHeaderOptions = {
  copyrightYear: 2024,
  companyName: 'My Company',
  dryRun: true, // Preview changes
  skipFiles: ['generated.js', 'vendor/**']
};

licenseManager.addLicenseHeader('src/file.js', options);

Examples

Add License to Single File

import { LicenseManager } from '@bernierllc/license-manager';

const licenseManager = new LicenseManager();

// Add license header
const success = licenseManager.addLicenseHeader('src/my-component.tsx');
if (success) {
  console.log('License header added successfully');
} else {
  console.log('Failed to add license header');
}

Validate License Compliance

const validation = licenseManager.validateLicenseHeader('src/file.js');

if (!validation.hasLicense) {
  console.log('❌ No license header found');
  console.log('Expected:', validation.expectedText);
} else if (!validation.isValid) {
  console.log('⚠️  Invalid license header');
  validation.errors.forEach(error => console.log(`  - ${error}`));
} else {
  console.log('✅ Valid license header');
}

Scan Project for Compliance

const scanResult = licenseManager.scanDirectory('./src');

console.log(`📊 License Compliance Report`);
console.log(`Total files: ${scanResult.totalFiles}`);
console.log(`Files with license: ${scanResult.filesWithLicense}`);
console.log(`Files without license: ${scanResult.filesWithoutLicense}`);
console.log(`Compliance rate: ${scanResult.complianceRate.toFixed(1)}%`);

if (scanResult.summary.missing.length > 0) {
  console.log('\n❌ Files missing license:');
  scanResult.summary.missing.forEach(file => console.log(`  - ${file}`));
}

if (scanResult.summary.invalid.length > 0) {
  console.log('\n⚠️  Files with invalid license:');
  scanResult.summary.invalid.forEach(file => console.log(`  - ${file}`));
}

Batch Add Licenses

const files = [
  'src/components/Button.tsx',
  'src/utils/helpers.ts',
  'src/styles/main.css'
];

files.forEach(file => {
  const success = licenseManager.addLicenseHeader(file, { dryRun: false });
  console.log(`${file}: ${success ? '✅' : '❌'}`);
});

Custom License Template

const customManager = new LicenseManager({
  templates: {
    'custom': {
      text: `/*
Copyright (c) 2025 Custom Company

This software is proprietary and confidential.
Unauthorized copying is prohibited.
*/`,
      format: 'c-style',
      startDelimiter: '/*',
      endDelimiter: '*/'
    }
  },
  fileTypeMapping: {
    'js': 'custom',
    'ts': 'custom'
  }
});

Testing

The package includes comprehensive tests with mocked file system:

npm test

Test Coverage

  • File type detection
  • License template generation
  • License validation
  • File operations (read/write)
  • Directory scanning
  • Configuration management
  • Error handling

Error Handling

The license manager provides detailed error information:

const validation = licenseManager.validateLicenseHeader('src/file.js');

if (validation.errors.length > 0) {
  console.log('Validation errors:');
  validation.errors.forEach(error => console.log(`  - ${error}`));
}

if (validation.warnings.length > 0) {
  console.log('Validation warnings:');
  validation.warnings.forEach(warning => console.log(`  - ${warning}`));
}

Best Practices

  1. Use Dry Run First: Always test with dryRun: true before making changes
  2. Exclude Generated Files: Configure exclude patterns for build outputs
  3. Customize for Your Project: Update company name and copyright year
  4. Regular Compliance Checks: Scan your project regularly for license compliance
  5. Handle Errors Gracefully: Check return values and handle file system errors

Contributing

This package is part of the Bernier LLC tools ecosystem. Please follow the project's contribution guidelines.

License

This package is licensed under the same terms as the project it's delivered for. See the license header in source files for details.