or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-source-map-support

Fixes stack traces for files with source maps

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/source-map-support@0.5.x

To install, run

npx @tessl/cli install tessl/npm-source-map-support@0.5.0

index.mddocs/

Source Map Support

Source Map Support provides source map support for stack traces in Node.js via the V8 stack trace API. It uses the source-map module to replace the paths and line numbers of source-mapped files with their original paths and line numbers, making compile-to-JavaScript languages more of a first-class citizen in the Node.js ecosystem.

Package Information

  • Package Name: source-map-support
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install source-map-support

Core Imports

const sourceMapSupport = require('source-map-support');

ES6 import:

import sourceMapSupport from 'source-map-support';

Convenience imports:

// Auto-install with default options
require('source-map-support/register');

// Auto-install with hookRequire enabled
require('source-map-support/register-hook-require');

For browser environments:

<script src="browser-source-map-support.js"></script>

Basic Usage

const sourceMapSupport = require('source-map-support');

// Install with default options
sourceMapSupport.install();

// Install with custom options
sourceMapSupport.install({
  handleUncaughtExceptions: true,
  environment: 'node',
  hookRequire: false
});

CLI Usage:

node -r source-map-support/register compiled.js

Programmatic Auto-install:

// Simply require the register module
require('source-map-support/register');

// ES6 equivalent
import 'source-map-support/register';

Architecture

Source Map Support is built around several key components that work together to provide seamless source map integration:

  • V8 Stack Trace API Integration: Hooks into Node.js's Error.prepareStackTrace to intercept and modify stack traces before they're formatted
  • Source Map Consumer: Uses the source-map library to parse and query source map files for position mapping
  • File/Map Retrieval System: Extensible handler system for loading source files and source maps from various sources (filesystem, HTTP, inline, custom)
  • Error Formatter: Replaces generated file positions with original source positions and provides source context for better debugging
  • Uncaught Exception Handler: Optionally installs process-level exception handling to format unhandled errors with source-mapped stack traces
  • Environment Detection: Automatically detects Node.js vs browser environments and adapts behavior accordingly

The package works by:

  1. Installing a custom Error.prepareStackTrace function that processes each stack frame
  2. For each frame, checking if source maps are available for the file
  3. If found, mapping the generated position to the original source position
  4. Formatting the final stack trace to show original file paths and line numbers

Capabilities

Install Source Map Support

Installs source map support for stack traces and uncaught exceptions with customizable options.

/**
 * Installs source map support for stack traces and uncaught exceptions
 * @param {Object} [options] - Configuration options
 * @param {boolean} [options.handleUncaughtExceptions=true] - Whether to handle uncaught exceptions
 * @param {Function} [options.retrieveSourceMap] - Custom source map retrieval function
 * @param {Function} [options.retrieveFile] - Custom file retrieval function
 * @param {boolean} [options.overrideRetrieveSourceMap=false] - Replace default source map handlers
 * @param {boolean} [options.overrideRetrieveFile=false] - Replace default file handlers
 * @param {string} [options.environment='auto'] - Environment type: 'node', 'browser', or 'auto'
 * @param {boolean} [options.hookRequire=false] - Monitor source files for inline source maps
 * @param {boolean} [options.emptyCacheBetweenOperations=false] - Reset caches between operations
 */
function install(options);

Usage Examples:

const sourceMapSupport = require('source-map-support');

// Basic installation
sourceMapSupport.install();

// Custom configuration
sourceMapSupport.install({
  handleUncaughtExceptions: false,
  environment: 'node',
  hookRequire: true,
  retrieveSourceMap: function(source) {
    // Custom logic to retrieve source maps
    return { url: 'custom.map', map: mapContent };
  }
});

Wrap Call Site

Wraps a V8 CallSite object to provide source-mapped information for stack traces.

/**
 * Wraps a V8 CallSite object to provide source-mapped information
 * @param {CallSite} frame - V8 CallSite object
 * @param {Object} [state] - State object for tracking position information
 * @returns {CallSite} Modified CallSite object with source-mapped information
 */
function wrapCallSite(frame, state);

Get Error Source

Extracts source information from error stack traces, providing formatted source location and code snippets.

/**
 * Extracts source information from error stack traces
 * @param {Error} error - Error object with stack trace
 * @returns {string|null} Formatted source location and code snippet, or null if unavailable
 */
function getErrorSource(error);

Usage Example:

const sourceMapSupport = require('source-map-support');

try {
  // Some code that might throw
  throw new Error('Something went wrong');
} catch (error) {
  const sourceInfo = sourceMapSupport.getErrorSource(error);
  if (sourceInfo) {
    console.log('Source context:', sourceInfo);
  }
}

Map Source Position

Maps a generated source position to the original source position using available source maps.

/**
 * Maps a generated source position to original source position
 * @param {Object} position - Position object with source, line, column properties
 * @param {string} position.source - Source file path or URL
 * @param {number} position.line - Line number (1-based)
 * @param {number} position.column - Column number (0-based)
 * @returns {Object} Object with mapped original position information
 */
function mapSourcePosition(position);

Usage Example:

const sourceMapSupport = require('source-map-support');

const originalPosition = sourceMapSupport.mapSourcePosition({
  source: '/path/to/compiled.js',
  line: 15,
  column: 10
});

console.log(originalPosition);
// {
//   source: '/path/to/original.ts',
//   line: 23,
//   column: 5,
//   name: 'originalFunction'
// }

Retrieve Source Map

Retrieves the source map for a given source file, supporting both inline and external source maps.

/**
 * Retrieves source map for a given source file
 * @param {string} source - Source file path or URL
 * @returns {Object|null} Object with url and map properties, or null if no source map found
 */
function retrieveSourceMap(source);

Usage Example:

const sourceMapSupport = require('source-map-support');

const sourceMap = sourceMapSupport.retrieveSourceMap('/path/to/compiled.js');
if (sourceMap) {
  console.log('Source map URL:', sourceMap.url);
  console.log('Source map data:', sourceMap.map);
}

Reset Retrieve Handlers

Resets file and source map retrieval handlers to their original state, useful for testing or dynamic configuration.

/**
 * Resets file and source map retrieval handlers to their original state
 */
function resetRetrieveHandlers();

Types

/**
 * Configuration options for install()
 */
interface InstallOptions {
  /** Whether to handle uncaught exceptions (default: true) */
  handleUncaughtExceptions: boolean;
  /** Custom source map retrieval function */
  retrieveSourceMap: (source: string) => { url: string, map: string } | null;
  /** Custom file retrieval function */
  retrieveFile: (path: string) => string | null;
  /** Replace default source map handlers (default: false) */
  overrideRetrieveSourceMap: boolean;
  /** Replace default file handlers (default: false) */
  overrideRetrieveFile: boolean;
  /** Environment type: 'node', 'browser', or 'auto' (default: 'auto') */
  environment: 'node' | 'browser' | 'auto';
  /** Monitor source files for inline source maps (default: false) */
  hookRequire: boolean;
  /** Reset caches between operations (default: false) */
  emptyCacheBetweenOperations: boolean;
}

/**
 * Position object for source mapping
 */
interface Position {
  /** Source file path or URL */
  source: string;
  /** Line number (1-based) */
  line: number;
  /** Column number (0-based) */
  column: number;
}

/**
 * Mapped position result
 */
interface MappedPosition {
  /** Original source file path */
  source: string;
  /** Original line number */
  line: number;
  /** Original column number */
  column: number;
  /** Original symbol name, if available */
  name?: string;
}

/**
 * Source map retrieval result
 */
interface SourceMapResult {
  /** URL or path to the source map */
  url: string;
  /** Source map content as string or parsed object */
  map: string | Object;
}

Error Handling

The module provides enhanced error stack traces by:

  • Detecting source mapping URLs in generated files (//# sourceMappingURL=...)
  • Loading and parsing source maps (inline or external)
  • Mapping generated positions to original positions
  • Formatting stack traces to show original file locations
  • Providing source code context for errors when available

Common source map URL formats supported:

  • External files: //# sourceMappingURL=path/to/file.map
  • Inline maps: //# sourceMappingURL=data:application/json;charset=utf-8;base64,<base64-encoded-map>

Platform-Specific Behavior

Node.js Environment

  • Uses filesystem APIs to read source map files
  • Supports both absolute and relative paths
  • Integrates with Node.js process and module systems
  • Handles uncaught exceptions when enabled

Browser Environment

  • Uses XMLHttpRequest for loading external source maps
  • Supports both relative and absolute URLs
  • Works with bundled browser-source-map-support.js file
  • Compatible with AMD/RequireJS

Auto-Detection

The package automatically detects the environment based on available globals:

  • Node.js: Presence of process and require
  • Browser: Presence of window and XMLHttpRequest