or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-babel--helper-wrap-function

Helper to wrap functions inside function calls while preserving behavior, scope, and context for Babel AST transformations.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@babel/helper-wrap-function@7.28.x

To install, run

npx @tessl/cli install tessl/npm-babel--helper-wrap-function@7.28.0

index.mddocs/

@babel/helper-wrap-function

@babel/helper-wrap-function is a specialized utility library for JavaScript/TypeScript code transformations, designed to wrap different types of functions inside protective function calls while preserving their original behavior, scope, and context. It's primarily used within the Babel ecosystem for Abstract Syntax Tree (AST) manipulations in plugins and transformers.

Package Information

  • Package Name: @babel/helper-wrap-function
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @babel/helper-wrap-function
  • License: MIT

Core Imports

import wrapFunction from "@babel/helper-wrap-function";

For CommonJS:

const wrapFunction = require("@babel/helper-wrap-function").default;

Basic Usage

import { NodePath } from "@babel/traverse";
import { callExpression, identifier } from "@babel/types";
import type * as t from "@babel/types";
import wrapFunction from "@babel/helper-wrap-function";

// Wrap an async function with asyncToGenerator helper
function transformAsyncFunction(path: NodePath<t.Function>) {
  const helperId = callExpression(identifier("_asyncToGenerator"), []);
  wrapFunction(path, helperId);
}

// Wrap a generator function with a custom helper
function wrapGeneratorWithHelper(path: NodePath<t.Function>) {
  const helperId = callExpression(identifier("skipFirstGeneratorNext"), []);
  wrapFunction(path, helperId, true, false);
}

Architecture

The helper is built around sophisticated function wrapping strategies:

  • Multi-Strategy Wrapping: Different wrapping approaches for declarations, named expressions, and anonymous expressions
  • Context Preservation: Maintains this binding, arguments object access, and lexical scope
  • Type-Aware Processing: Handles regular functions, arrow functions, class methods, object methods, generators, and async functions
  • Parameter Intelligence: Smart parameter forwarding for complex parameter patterns (destructuring, defaults, rest parameters)
  • Scope Management: Proper handling of super calls and environment unwrapping

Capabilities

Function Wrapping

Wraps functions inside protective function calls while preserving behavior, scope, and context.

/**
 * Wraps a function inside a protective function call while preserving behavior, scope, and context
 * @param path - Babel AST NodePath representing the function to wrap
 * @param callId - Expression used to wrap the function (typically a helper call)
 * @param noNewArrows - Controls arrow function conversion behavior (default: true)
 * @param ignoreFunctionLength - Controls function.length preservation (default: false)
 */
function wrapFunction(
  path: NodePath<t.Function>,
  callId: t.Expression,
  noNewArrows?: boolean,
  ignoreFunctionLength?: boolean
): void;

Parameters:

  • path: The Babel AST node path representing the function to wrap. Supports all function types:

    • Regular function declarations and expressions
    • Arrow function expressions
    • Class methods (instance and static)
    • Object methods
    • Generator functions
    • Async functions
    • Class private methods
  • callId: The expression used to wrap the function, typically a helper call like _asyncToGenerator(...) or skipFirstGeneratorNext(...)

  • noNewArrows (optional): When true (default), prevents creation of new arrow functions during transformation. When false, allows arrow function creation in the wrapping process.

  • ignoreFunctionLength (optional): When true, skips parameter forwarding optimizations that preserve function.length. When false (default), maintains function arity through parameter forwarding.

Wrapping Strategies:

The function automatically selects the appropriate wrapping strategy based on the function type:

1. Declaration Wrapper (for function declarations):

function NAME(PARAMS) { return REF.apply(this, arguments); }
function REF() {
  REF = FUNCTION;
  return REF.apply(this, arguments);
}

2. Named Expression Wrapper (for named function expressions):

(function () {
  var REF = FUNCTION;
  function NAME(PARAMS) {
    return REF.apply(this, arguments);
  }
  return NAME;
})()

3. Anonymous Expression Wrapper (for anonymous function expressions):

(function () {
  var REF = FUNCTION;
  return function NAME(PARAMS) {
    return REF.apply(this, arguments);
  };
})()

Usage Examples:

import { NodePath } from "@babel/traverse";
import { callExpression, identifier } from "@babel/types";
import wrapFunction from "@babel/helper-wrap-function";
import type * as t from "@babel/types";

// Example 1: Wrap async function for async-to-generator transformation
function wrapAsyncFunction(path: NodePath<t.Function>) {
  const asyncToGeneratorCall = callExpression(
    identifier("_asyncToGenerator"), 
    []
  );
  wrapFunction(path, asyncToGeneratorCall);
}

// Example 2: Wrap generator with helper, preserving arrow functions
function wrapGeneratorFunction(path: NodePath<t.Function>) {
  const helperCall = callExpression(
    identifier("skipFirstGeneratorNext"), 
    []
  );
  wrapFunction(path, helperCall, false, true);
}

// Example 3: Wrap method while preserving function length
function wrapMethodPreservingLength(path: NodePath<t.Method>) {
  const wrapperCall = callExpression(
    identifier("_wrapNativeSuper"), 
    []
  );
  wrapFunction(path, wrapperCall, true, false);
}

Key Features

Context Preservation:

  • Maintains proper this binding in all contexts
  • Preserves access to arguments object
  • Handles super calls correctly in class methods

Parameter Handling:

  • Supports complex parameter patterns (destructuring, default values, rest parameters)
  • Intelligent parameter forwarding for function.length preservation
  • Generates unique parameter identifiers to avoid conflicts

Scope Management:

  • Unwraps function environments to maintain lexical scope
  • Preserves closure variables and outer scope access
  • Handles nested function scenarios correctly

Type Safety:

  • Full TypeScript integration with Babel types
  • Generic type preservation throughout transformations
  • Compile-time checking for AST node types

Types

// Core types from @babel/types and @babel/traverse
import type { NodePath } from "@babel/traverse";
import type * as t from "@babel/types";

// Template builder type for internal wrapper generation
type ExpressionWrapperBuilder<ExtraBody extends t.Node[]> = (
  replacements?: Parameters<ReturnType<typeof template.expression>>[0],
) => t.CallExpression & {
  callee: t.FunctionExpression & {
    body: {
      body: [
        t.VariableDeclaration & {
          declarations: [
            { init: t.FunctionExpression | t.ArrowFunctionExpression },
          ];
        },
        ...ExtraBody,
      ];
    };
  };
};

Dependencies

This package requires the following Babel ecosystem dependencies:

  • @babel/template: Template-based AST generation and manipulation
  • @babel/traverse: AST traversal utilities and NodePath functionality
  • @babel/types: AST node type definitions, builders, and utilities

Common Use Cases

  1. Async-to-Generator Transformations: Wrapping async functions with _asyncToGenerator helper
  2. Generator Function Processing: Wrapping generators with specialized helpers like skipFirstGeneratorNext
  3. Function Hoisting: Converting function expressions to declarations with proper wrapping
  4. Method Transformation: Wrapping class and object methods while preserving context
  5. Plugin Development: Building Babel plugins that need to transform function behavior

Error Handling

The function performs in-place AST modifications and expects:

  • Valid Babel NodePath instances
  • Proper AST node types for the target functions
  • Available scope and environment context
  • Compatible Babel runtime environment

Common issues:

  • Attempting to wrap already-transformed functions may result in nested wrappers
  • Missing required Babel dependencies will cause runtime errors
  • Invalid AST nodes or corrupted paths may lead to transformation failures

Integration Notes

  • Designed for use within Babel plugin contexts and AST transformation pipelines
  • Thread-safe for concurrent transformations on different AST instances
  • Modifies AST in-place through provided NodePath - no return value
  • Requires proper Babel environment setup with traverse and types utilities
  • Compatible with Babel 7.x ecosystem and toolchain