CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-tsickle

Transpile TypeScript code to JavaScript with Closure annotations.

Pending
Overview
Eval results
Files

transformer-utilities.mddocs/

Transformer Utilities

Core utilities for AST manipulation and transformation support, including helper functions for working with TypeScript nodes, creating Closure-compatible constructs, and managing comments during transformation.

Capabilities

AST Node Utilities

Functions for checking node properties and extracting information from TypeScript AST nodes.

/**
 * Checks if declaration has specified modifier flag
 */
function hasModifierFlag(declaration: ts.Declaration, flag: ts.ModifierFlags): boolean;

/**
 * Checks if node is an ambient declaration
 */
function isAmbient(node: ts.Node): boolean;

/**
 * Checks if filename is a TypeScript declaration file
 */
function isDtsFileName(fileName: string): boolean;

/**
 * Gets identifier text from identifier node
 */
function getIdentifierText(identifier: ts.Identifier): string;

/**
 * Gets full text from entity name
 */
function getEntityNameText(name: ts.EntityName): string;

/**
 * Checks if symbol represents a value (not just a type)
 */
function symbolIsValue(tc: ts.TypeChecker, sym: ts.Symbol): boolean;

/**
 * Unescapes TypeScript internal string representation
 */
function unescapeName(name: ts.__String): string;

Usage Examples:

import { hasModifierFlag, isAmbient, getIdentifierText } from "tsickle";

// Check if class is exported
if (hasModifierFlag(classDecl, ts.ModifierFlags.Export)) {
  console.log("Class is exported");
}

// Check if declaration is ambient
if (isAmbient(node)) {
  // Handle ambient declaration
  console.log("Ambient declaration found");
}

// Extract identifier text
const name = getIdentifierText(identifier);
console.log(`Identifier: ${name}`);

Comment Management

Functions for creating and managing comments during transformation.

/**
 * Creates not emitted statement with comments
 */
function createNotEmittedStatementWithComments(
  sourceFile: ts.SourceFile,
  original: ts.Node
): ts.Statement;

/**
 * Synthesizes comment ranges from parsed comments
 */
function synthesizeCommentRanges(
  sourceFile: ts.SourceFile,
  parsedComments: ts.CommentRange[]
): ts.SynthesizedComment[];

/**
 * Gets all leading comments for a node
 */
function getAllLeadingComments(
  node: ts.Node
): ReadonlyArray<Readonly<ts.CommentRange & {text: string}>>;

/**
 * Creates single line comment
 */
function createSingleLineComment(text: string): ts.SynthesizedComment;

/**
 * Creates multi line comment
 */
function createMultiLineComment(text: string): ts.SynthesizedComment;

Usage Examples:

import { createSingleLineComment, getAllLeadingComments } from "tsickle";

// Create a single line comment
const comment = createSingleLineComment("Generated by tsickle");

// Get all comments from a node
const comments = getAllLeadingComments(functionDecl);
console.log(`Found ${comments.length} comments`);

String and Literal Utilities

Functions for creating string literals and handling string representations.

/**
 * Creates single-quoted string literal
 */
function createSingleQuoteStringLiteral(text: string): ts.StringLiteral;

Usage Example:

import { createSingleQuoteStringLiteral } from "tsickle";

// Create a single-quoted string literal
const literal = createSingleQuoteStringLiteral("my-module");
// Results in: 'my-module'

Google Closure Utilities

Functions for creating and managing Google Closure-specific constructs.

/**
 * Creates goog function call expression
 */
function createGoogCall(
  fn: string,
  args?: ts.Expression[]
): ts.CallExpression;

/**
 * Gets Google Closure function name from call
 */
function getGoogFunctionName(call: ts.CallExpression): string | undefined;

Usage Examples:

import { createGoogCall, getGoogFunctionName } from "tsickle";

// Create goog.require call
const requireCall = createGoogCall('require', [
  ts.factory.createStringLiteral('my.module')
]);

// Extract function name from goog call
const fnName = getGoogFunctionName(callExpression);
if (fnName === 'require') {
  console.log('Found goog.require call');
}

Diagnostic Utilities

Functions for reporting diagnostics and warnings during transformation.

/**
 * Reports debug warning
 */
function reportDebugWarning(
  host: AnnotatorHost,
  node: ts.Node,
  message: string
): void;

/**
 * Reports diagnostic
 */
function reportDiagnostic(
  diagnostics: ts.Diagnostic[],
  node: ts.Node,
  message: string,
  category?: ts.DiagnosticCategory
): void;

Usage Examples:

import { reportDebugWarning, reportDiagnostic } from "tsickle";

// Report a debug warning
reportDebugWarning(host, node, "Unsupported TypeScript feature detected");

// Report an error diagnostic
reportDiagnostic(
  diagnostics,
  node,
  "Invalid module syntax",
  ts.DiagnosticCategory.Error
);

Integration with Transformers

These utilities are designed to work seamlessly with TypeScript's transformer API:

// Example transformer using utilities
function myTransformer(context: ts.TransformationContext): ts.Transformer<ts.SourceFile> {
  return (sourceFile: ts.SourceFile) => {
    function visit(node: ts.Node): ts.Node {
      // Use utilities for node inspection
      if (ts.isClassDeclaration(node) && hasModifierFlag(node, ts.ModifierFlags.Export)) {
        // Add comment to exported classes
        const comment = createSingleLineComment("Exported class processed by tsickle");
        // ... transform logic
      }
      return ts.visitEachChild(node, visit, context);
    }
    return ts.visitNode(sourceFile, visit);
  };
}

Error Handling

The transformer utilities include robust error handling:

  • Node validation: Functions validate input nodes before processing
  • Diagnostic reporting: Built-in diagnostic reporting for transformation issues
  • Graceful degradation: Utilities handle edge cases and malformed AST nodes
  • Debug support: Debug utilities help identify transformation issues

Performance Considerations

These utilities are optimized for performance in large codebases:

  • Lazy evaluation: Node properties are computed only when needed
  • Caching: Frequently accessed properties are cached appropriately
  • Memory efficiency: Minimal memory allocation for temporary objects
  • TypeScript AST integration: Direct integration with TypeScript's internal APIs

Common Patterns

Checking Declaration Types

import { hasModifierFlag, isAmbient } from "tsickle";

function processDeclaration(decl: ts.Declaration) {
  if (isAmbient(decl)) {
    // Handle ambient declarations differently
    return processAmbientDeclaration(decl);
  }
  
  if (hasModifierFlag(decl, ts.ModifierFlags.Export)) {
    // Process exported declarations
    return processExportedDeclaration(decl);
  }
  
  // Handle regular declarations
  return processRegularDeclaration(decl);
}

Working with Identifiers

import { getIdentifierText, getEntityNameText } from "tsickle";

function processIdentifiers(node: ts.Node) {
  if (ts.isIdentifier(node)) {
    const name = getIdentifierText(node);
    console.log(`Processing identifier: ${name}`);
  } else if (ts.isQualifiedName(node)) {
    const fullName = getEntityNameText(node);
    console.log(`Processing qualified name: ${fullName}`);
  }
}

Comment Preservation

import { getAllLeadingComments, createMultiLineComment } from "tsickle";

function preserveComments(originalNode: ts.Node, transformedNode: ts.Node): ts.Node {
  const comments = getAllLeadingComments(originalNode);
  if (comments.length > 0) {
    // Preserve original comments on transformed node
    const preservedComment = createMultiLineComment(
      "Original comments preserved during transformation"
    );
    // Attach to transformed node...
  }
  return transformedNode;
}

Install with Tessl CLI

npx tessl i tessl/npm-tsickle

docs

core-transformation.md

decorator-support.md

externs-generation.md

index.md

jsdoc-processing.md

module-system.md

path-utilities.md

transformer-utilities.md

type-translation.md

tile.json