or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-babel--helper-string-parser

A utility package to parse strings and escape sequences in JavaScript and TypeScript code

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@babel/helper-string-parser@7.27.x

To install, run

npx @tessl/cli install tessl/npm-babel--helper-string-parser@7.27.0

index.mddocs/

@babel/helper-string-parser

@babel/helper-string-parser is a utility package that provides essential functionality for parsing string literals and escape sequences in JavaScript and TypeScript code. It handles the complex task of processing string contents including escape sequences, numeric separators, and various string delimiters, making it fundamental to JavaScript tooling infrastructure.

Package Information

  • Package Name: @babel/helper-string-parser
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @babel/helper-string-parser

Core Imports

import { 
  readStringContents, 
  readInt, 
  readCodePoint,
  type StringContentsErrorHandlers,
  type IntErrorHandlers,
  type CodePointErrorHandlers
} from "@babel/helper-string-parser";

For CommonJS:

const { 
  readStringContents, 
  readInt, 
  readCodePoint 
} = require("@babel/helper-string-parser");

Basic Usage

import { readStringContents } from "@babel/helper-string-parser";

// Define error handlers
const errorHandlers = {
  unterminated: (pos, lineStart, curLine) => {
    throw new Error(`Unterminated string at ${pos}`);
  },
  strictNumericEscape: (pos, lineStart, curLine) => {
    throw new Error(`Invalid numeric escape at ${pos}`);
  },
  invalidEscapeSequence: (pos, lineStart, curLine) => {
    throw new Error(`Invalid escape sequence at ${pos}`);
  },
  invalidCodePoint: (pos, lineStart, curLine) => {
    throw new Error(`Invalid code point at ${pos}`);
  },
  numericSeparatorInEscapeSequence: (pos, lineStart, curLine) => {
    throw new Error(`Numeric separator in escape sequence at ${pos}`);
  },
  unexpectedNumericSeparator: (pos, lineStart, curLine) => {
    throw new Error(`Unexpected numeric separator at ${pos}`);
  },
  invalidDigit: (pos, lineStart, curLine, radix) => {
    console.warn(`Invalid digit for radix ${radix} at ${pos}`);
    return false; // Don't continue parsing
  }
};

// Parse a double-quoted string
const input = '"Hello\\nWorld"';
const result = readStringContents(
  "double",  // string type
  input,     // input string
  1,         // position after opening quote
  0,         // line start position
  1,         // current line number
  errorHandlers
);

console.log(result.str); // "Hello\nWorld"
console.log(result.pos); // position after closing quote

Capabilities

String Content Parsing

Parses string contents with escape sequence handling for JavaScript string literals.

/**
 * Reads and parses string contents with escape sequence handling
 * @param type - The type of string delimiter ("single", "double", or "template")
 * @param input - The input string to parse
 * @param pos - Current position in the input string
 * @param lineStart - Position where the current line starts
 * @param curLine - Current line number
 * @param errors - Error handler callbacks for various parsing errors
 * @returns Object containing parsed string, position info, and error details
 */
function readStringContents(
  type: "single" | "double" | "template",
  input: string,
  pos: number,
  lineStart: number,
  curLine: number,
  errors: StringContentsErrorHandlers,
): {
  pos: number;
  str: string;
  firstInvalidLoc: { pos: number; lineStart: number; curLine: number } | null;
  lineStart: number;
  curLine: number;
  containsInvalid?: boolean; // Only present when BABEL_8_BREAKING is not set
};

Integer Parsing

Parses integer values with support for different number bases and numeric separators.

/**
 * Reads and parses integer values with radix support
 * @param input - The input string containing the integer
 * @param pos - Current position in the input
 * @param lineStart - Position where current line starts
 * @param curLine - Current line number
 * @param radix - Number base (2 for binary, 8 for octal, 10 for decimal, 16 for hex)
 * @param len - Expected length of the integer (undefined for variable length)
 * @param forceLen - Whether to enforce the specified length
 * @param allowNumSeparator - Whether to allow numeric separators (_): true allows them, false disallows them, "bail" returns null when encountered
 * @param errors - Error handler callbacks for parsing errors
 * @param bailOnError - Whether to return null instead of throwing on error
 * @returns Object with parsed number and updated position
 */
function readInt(
  input: string,
  pos: number,
  lineStart: number,
  curLine: number,
  radix: number,
  len: number | undefined,
  forceLen: boolean,
  allowNumSeparator: boolean | "bail",
  errors: IntErrorHandlers,
  bailOnError: boolean,
): {
  n: number | null;
  pos: number;
};

Unicode Code Point Parsing

Parses Unicode code points from escape sequences.

/**
 * Reads Unicode code points from escape sequences
 * @param input - Input string containing the escape sequence
 * @param pos - Current position in the input
 * @param lineStart - Position where current line starts
 * @param curLine - Current line number
 * @param throwOnInvalid - Whether to throw errors on invalid sequences
 * @param errors - Error handler callbacks for code point parsing errors
 * @returns Object with parsed code point and updated position
 */
function readCodePoint(
  input: string,
  pos: number,
  lineStart: number,
  curLine: number,
  throwOnInvalid: boolean,
  errors: CodePointErrorHandlers,
): {
  code: number | null;
  pos: number;
};

Types

Error Handler Interfaces

/**
 * Error handlers for integer parsing operations
 */
export type IntErrorHandlers = {
  /** Called when numeric separator appears in escape sequence */
  numericSeparatorInEscapeSequence(pos: number, lineStart: number, curLine: number): void;
  /** Called when numeric separator is positioned incorrectly */
  unexpectedNumericSeparator(pos: number, lineStart: number, curLine: number): void;
  /** Called when an invalid digit is encountered - can return true to continue parsing */
  invalidDigit(pos: number, lineStart: number, curLine: number, radix: number): boolean;
};

/**
 * Error handlers for Unicode code point parsing
 * Extends IntErrorHandlers with additional code point specific handlers
 */
export type CodePointErrorHandlers = IntErrorHandlers & {
  /** Called when an invalid escape sequence is encountered */
  invalidEscapeSequence(pos: number, lineStart: number, curLine: number): void;
  /** Called when an invalid Unicode code point is found */
  invalidCodePoint(pos: number, lineStart: number, curLine: number): void;
};

/**
 * Error handlers for string content parsing
 * Extends CodePointErrorHandlers with string-specific error handling
 */
export type StringContentsErrorHandlers = CodePointErrorHandlers & {
  /** Called when a string is not properly terminated */
  unterminated(initialPos: number, initialLineStart: number, initialCurLine: number): void;
  /** Called when a strict numeric escape is encountered */
  strictNumericEscape(pos: number, lineStart: number, curLine: number): void;
};

Advanced Usage Examples

Parsing Template Literals

import { readStringContents } from "@babel/helper-string-parser";

const templateInput = "`Hello ${name}\nWorld`";
const result = readStringContents(
  "template",
  templateInput,
  1, // start after backtick
  0,
  1,
  errorHandlers
);

// Template literals preserve newlines and handle ${} interpolation
console.log(result.str); // "Hello " (stops at ${)

Parsing Hexadecimal Numbers

import { readInt } from "@babel/helper-string-parser";

const hexInput = "0xFF_AB";
const result = readInt(
  hexInput,
  2, // start after "0x"
  0,
  1,
  16, // hexadecimal radix
  undefined, // variable length
  false,
  true, // allow numeric separators
  errorHandlers,
  false
);

console.log(result.n); // 65451 (0xFFAB)

Error Recovery

import { readInt } from "@babel/helper-string-parser";

const errorHandlers = {
  invalidDigit: (pos, lineStart, curLine, radix) => {
    console.warn(`Skipping invalid digit for base ${radix} at position ${pos}`);
    return true; // Continue parsing
  },
  // ... other handlers
};

// This will skip invalid digits and continue
const result = readInt("123G456", 0, 0, 1, 10, undefined, false, false, errorHandlers, false);

Key Features

  • Multiple String Types: Supports single quotes, double quotes, and template literals
  • Complete Escape Handling: Processes all JavaScript escape sequences (\n, \r, \t, \x, \u, octal)
  • Numeric Parsing: Handles binary, octal, decimal, and hexadecimal number parsing
  • Numeric Separators: Full support for modern numeric separator syntax (_)
  • Unicode Support: Complete Unicode code point parsing including surrogate pairs
  • Position Tracking: Maintains accurate line and column information for error reporting
  • Flexible Error Handling: Callback-based error system for custom error recovery
  • Template Literal Support: Special handling for template string parsing with interpolation
  • Environment Awareness: Responds to BABEL_8_BREAKING environment variable for compatibility

Common Use Cases

  • JavaScript Parsers: Core functionality for parsing string literals in JS/TS parsers
  • Code Transpilers: Essential for tools like Babel that transform JavaScript code
  • Linters and Formatters: String literal validation and processing
  • Template Engines: Processing template literals with escape sequences
  • Build Tools: String processing in build-time code transformations
  • Developer Tools: Any tool that needs to parse JavaScript string syntax accurately