A utility package to parse strings and escape sequences in JavaScript and TypeScript code
npx @tessl/cli install tessl/npm-babel--helper-string-parser@7.27.0@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.
npm install @babel/helper-string-parserimport {
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");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 quoteParses 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
};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;
};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;
};/**
* 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;
};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 ${)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)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);