CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-hermes-parser

A JavaScript parser built from the Hermes engine that supports ES6, Flow, and JSX syntax

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

parsing.mddocs/

Core Parsing

Primary parsing functionality that converts JavaScript/Flow/JSX source code into Abstract Syntax Trees with comprehensive configuration options.

Capabilities

Parse Function

Main entry point for parsing JavaScript, Flow, and JSX code into AST structures.

/**
 * Parse JavaScript/Flow/JSX source code into an AST
 * @param code - Source code string to parse
 * @param options - Optional parsing configuration
 * @returns ESTree Program node or Babel File object
 */
function parse(code: string, options?: ParserOptions): Program;

/**
 * Parse JavaScript source code into Babel-compatible AST
 * @param code - Source code string to parse  
 * @param options - Parsing configuration with babel: true
 * @returns Babel File object containing Program and metadata
 */
function parse(code: string, options: {...ParserOptions, babel: true}): BabelFile;

interface BabelFile {
  type: "File";
  program: Program;
  comments?: Comment[];
  tokens?: Token[];
}

Usage Examples:

import { parse } from "hermes-parser";

// Basic parsing (ESTree format)
const ast = parse("const x = 1;");
console.log(ast.type); // "Program"

// Parse with Flow type annotations
const flowCode = `
  function add(x: number, y: number): number {
    return x + y;  
  }
`;
const flowAst = parse(flowCode, { flow: "all" });

// Parse JSX code
const jsxCode = `
  const component = <div className="container">
    <h1>Hello {name}</h1>
  </div>;
`;
const jsxAst = parse(jsxCode);

// Get Babel-compatible AST
const babelAst = parse("const x = 1;", { babel: true });
console.log(babelAst.type); // "File"
console.log(babelAst.program.type); // "Program"

Parser Configuration

Control parsing behavior through the ParserOptions interface.

interface ParserOptions {
  /** Allow return statements outside of functions */
  allowReturnOutsideFunction?: boolean;
  
  /** Output Babel-compatible AST format instead of ESTree */
  babel?: boolean;
  
  /** Flow syntax parsing mode */
  flow?: "all" | "detect";
  
  /** Enable experimental React component syntax */
  enableExperimentalComponentSyntax?: boolean;
  
  /** Enable experimental Flow match syntax */
  enableExperimentalFlowMatchSyntax?: boolean;
  
  /** Target React runtime version for transformations */
  reactRuntimeTarget?: "18" | "19";
  
  /** Filename for source locations in AST nodes */
  sourceFilename?: string;
  
  /** Module type for parsing behavior */
  sourceType?: "module" | "script" | "unambiguous";
  
  /** Include token array in output AST */
  tokens?: boolean;
}

/** Set of valid ParserOptions property names */
const ParserOptionsKeys: ReadonlySet<keyof ParserOptions>;

Configuration Examples:

// Parse with all Flow features enabled
const flowAst = parse(source, {
  flow: "all", // Parse all Flow syntax regardless of pragma
  sourceFilename: "example.js"
});

// Parse with Flow pragma detection
const pragmaAst = parse(source, {
  flow: "detect", // Only parse Flow if @flow pragma present
  sourceType: "module"
});

// Parse for Babel with tokens and experimental features
const fullAst = parse(source, {
  babel: true,
  tokens: true,
  enableExperimentalComponentSyntax: true,
  enableExperimentalFlowMatchSyntax: true
});

// Parse with specific module type
const scriptAst = parse(source, {
  sourceType: "script", // Treat as script, not module
  allowReturnOutsideFunction: true
});

Flow Parsing Modes

Control how Flow type annotations are parsed.

Flow Detection Mode ("detect"):

  • Only parses Flow syntax when @flow pragma is present in the file
  • Ambiguous syntax like foo<T>(x) parsed as comparisons without pragma
  • Default behavior for backward compatibility

Flow All Mode ("all"):

  • Always parses ambiguous syntax as Flow syntax
  • Does not require @flow pragma
  • Recommended for Flow-first codebases
// Without @flow pragma, parsed as two comparisons
const ast1 = parse("foo<T>(x)", { flow: "detect" });

// With @flow pragma, parsed as generic call expression  
const ast2 = parse("// @flow\nfoo<T>(x)", { flow: "detect" });

// Always parsed as generic call expression
const ast3 = parse("foo<T>(x)", { flow: "all" });

Source Type Options

Control how the parser interprets the source code context.

Module ("module"):

  • Treats code as ES6 module with import/export support
  • Strict mode enabled by default
  • Top-level await allowed

Script ("script"):

  • Treats code as traditional script
  • No import/export statements allowed
  • Non-strict mode by default

Unambiguous ("unambiguous"):

  • Automatically detects based on presence of import/export statements
  • Falls back to "script" if no module syntax found
  • Default behavior for maximum compatibility
// Force module parsing
const moduleAst = parse("export const x = 1;", { 
  sourceType: "module" 
});

// Force script parsing
const scriptAst = parse("var x = 1;", { 
  sourceType: "script" 
});

// Auto-detect based on content
const autoAst = parse("import x from 'module';", {
  sourceType: "unambiguous" // Will detect as "module"
});

Error Handling

Parse errors are thrown as enhanced SyntaxError instances with location information.

interface ParseError extends SyntaxError {
  loc: {
    line: number;
    column: number;
  };
}

Error Handling Examples:

try {
  const ast = parse("const = 1;"); // Invalid syntax
} catch (error) {
  if (error instanceof SyntaxError) {
    console.log(error.message); // "'identifier' expected in declaration"
    console.log(error.loc.line); // 1
    console.log(error.loc.column); // 6
  }
}

Output Formats

The parser supports two primary AST formats:

ESTree Format (Default):

  • Standard JavaScript AST format
  • Compatible with most JavaScript tooling
  • Includes range and loc properties for source mapping
  • Parent pointers available for traversal

Babel Format:

  • Babel-compatible AST structure
  • Additional metadata like start, end positions
  • Required for Babel transformation pipelines
  • Includes file-level information and comments

docs

index.md

parsing.md

transformation.md

traversal.md

utilities.md

tile.json