or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-invariant

Utility function for asserting invariant conditions with environment-aware error message formatting

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/invariant@2.2.x

To install, run

npx @tessl/cli install tessl/npm-invariant@2.2.0

index.mddocs/

Invariant

Invariant is a utility function for asserting invariant conditions in JavaScript applications. It enables developers to create descriptive error messages during development while providing generic error messages in production environments for security and performance optimization.

Package Information

  • Package Name: invariant
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install invariant

Core Imports

const invariant = require('invariant');

For ES6 modules (via bundler with CommonJS interop):

import invariant from 'invariant';
// or
import * as invariant from 'invariant';

Basic Usage

const invariant = require('invariant');

// Assert a condition with a descriptive message
invariant(user.isAuthenticated, 'User must be authenticated to access this resource');

// With %s formatting (only %s placeholders supported)
invariant(user.age >= 18, 'User %s must be at least %s years old', user.name, 18);

// Multiple substitutions (supports up to 6 arguments)
invariant(
  score >= 0 && score <= 100,
  'Score %s for user %s must be between %s and %s',
  score,
  user.name,
  0,
  100
);

Capabilities

Condition Assertion

Asserts that a condition is truthy, throwing an error with environment-aware messaging if the condition fails.

/**
 * Asserts that a condition is truthy, throwing an error if false
 * @param {any} condition - The condition to test
 * @param {string} [format] - Format string with %s placeholders (only %s supported, not full sprintf)
 * @param {any} a - First substitution argument
 * @param {any} b - Second substitution argument  
 * @param {any} c - Third substitution argument
 * @param {any} d - Fourth substitution argument
 * @param {any} e - Fifth substitution argument
 * @param {any} f - Sixth substitution argument
 * @throws {Error} Throws Error when condition is falsy
 * @returns {void}
 */
function invariant(condition, format, a, b, c, d, e, f);

Environment Behavior:

  • Development Mode (NODE_ENV !== 'production'):

    • Requires format parameter - throws Error if format is undefined
    • Provides detailed error messages with %s substitution
    • Error name is "Invariant Violation"
    • Error message contains the formatted string with substitutions
  • Production Mode (NODE_ENV === 'production'):

    • Does not require format parameter
    • Strips detailed error messages for security/performance
    • Provides generic "Minified exception occurred" message when format is undefined
    • Still throws errors to maintain logic consistency

Error Properties:

interface InvariantError extends Error {
  name: string;        // "Invariant Violation" (with format) or "Error" (without format)
  message: string;     // Formatted message or generic production message
  framesToPop: number; // Always 1 (for stack trace optimization)
}

Platform Variants:

  • Node.js Version: Caches process.env.NODE_ENV at module load time for performance
  • Browser Version: Checks process.env.NODE_ENV on each call, designed for browserify + envify transforms

Usage Examples:

// Basic assertion
invariant(condition, 'Something went wrong');

// With single substitution
invariant(user !== null, 'User %s not found', userId);

// With multiple substitutions
invariant(
  price >= minPrice && price <= maxPrice,
  'Product %s price %s must be between %s and %s',
  productName,
  price,
  minPrice,
  maxPrice
);

// Production vs Development behavior
if (process.env.NODE_ENV !== 'production') {
  // Development: requires format parameter
  invariant(condition, 'Detailed error message');
} else {
  // Production: format parameter optional
  invariant(condition); // Throws generic error message
}

Error Handling

The invariant function throws standard JavaScript Error objects:

  • In Development: Detailed error messages with "Invariant Violation" name
  • In Production: Generic error messages to avoid exposing sensitive information
  • All Environments: framesToPop property set to 1 for cleaner stack traces
try {
  invariant(false, 'User %s is not authorized', username);
} catch (error) {
  // Development: error.message = "User alice is not authorized"
  // Production: error.message = "User alice is not authorized" (same, but only if format provided)
  console.error('Invariant violation:', error.message);
}

Build Tool Integration

  • Browserify: Configured with loose-envify transform for process.env.NODE_ENV replacement
  • Environment Variables: Supports NODE_ENV-based dead code elimination in production builds
  • Bundle Optimization: Production builds can strip development-only code paths through static analysis