npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

ts-analyser

v2.0.1

Published

A comprehensive TypeScript library for analyzing and transforming TypeScript code, including imports/exports analysis, function complexity metrics, side effect detection, and automated refactoring

Downloads

264

Readme

ts-analyser

A comprehensive, secure TypeScript library for analyzing and transforming TypeScript code. Features advanced function analysis, side effect detection, complexity metrics, and automated refactoring capabilities with built-in security protections.

Installation

npm install ts-analyser

Security

This library implements multiple security protections:

  • Input Validation: All file paths are validated and sanitized
  • Type Safety: Strict TypeScript typing prevents runtime type errors
  • Memory Protection: AST traversal depth limits prevent stack overflow attacks
  • Error Sanitization: Error messages don't leak sensitive file system information
  • Path Security: Directory traversal protection for file operations

For security-sensitive applications, consider additional sandboxing and input validation.

Usage

import { analyze } from 'ts-analyser';

const result = analyze('/path/to/file.ts');
console.log(JSON.stringify(result, null, 2));

API

Core Analysis

analyze(filename: string): AnalysisResult

Analyzes the given TypeScript file and returns an object containing imports and exports information.

ImportInfo

  • originalPath: string - The import path as written in the code
  • resolvedPath: string - The resolved absolute path of the imported module
  • entities: ImportEntity[] - List of imported entities

ImportEntity

  • name: string - The name of the imported entity
  • alias?: string - The alias if the import is renamed

ExportInfo

  • name: string - The name of the exported entity
  • type: string - The JavaScript type ('function', 'variable', 'class', 'interface', 'type', 'enum', 'const', 'let', 'var')
  • signature: string - The full TypeScript signature of the export

Advanced Analysis (for Power Users)

FunctionAnalyzer

Main analyzer class providing access to all function analysis capabilities.

const analyzer = new FunctionAnalyzer(sourceCode, 'file.ts');

// Find functions
const func = analyzer.getFunctionByName('myFunction');

// Analyze complexity
const complexity = analyzer.calculateComplexity(func);

// Detect side effects
const sideEffects = analyzer.detectSideEffects(func);

// Find split opportunities
const splits = analyzer.detectSplitOpportunities(func);

// Purify function (make it pure)
const purified = analyzer.purifyFunction(func);

SplitAnalyzer

Specialized analyzer for detecting function splitting opportunities.

const splitAnalyzer = new SplitAnalyzer(sourceFile);
const candidates = splitAnalyzer.detectSplitOpportunities(funcNode);

// Each candidate includes:
// - Benefit score (higher is better)
// - Input/output variables
// - Complexity metrics before/after
// - Whether it's recommended

SideEffectAnalyzer

Detects side effects and closure references in functions.

const sideEffectAnalyzer = new SideEffectAnalyzer(sourceFile);
const effects = sideEffectAnalyzer.detectSideEffects(funcNode);

// Detects:
// - Closure reads/writes
// - Parameter mutations
// - Global variable access
// - Console operations
// - DOM operations
// - Async operations

ComplexityAnalyzer

Calculates various complexity metrics for functions.

const complexityAnalyzer = new ComplexityAnalyzer(sourceFile);
const metrics = complexityAnalyzer.calculateComplexity(funcNode);

// Metrics include:
// - Cyclomatic complexity
// - Lines of code
// - Maximum nesting depth
// - Parameter count
// - Variable count
// - Cognitive complexity

FunctionPurifier

Transforms functions to eliminate side effects and make them pure.

const purifier = new FunctionPurifier(sourceFile);
const result = purifier.purifyFunction(funcNode);

// Result includes:
// - Transformed pure function code
// - Added parameters for closures
// - Return properties for modified variables
// - Remaining side effects that couldn't be eliminated

Example

Given a TypeScript file example.ts:

export function greet(name: string): string {
  return `Hello, ${name}!`;
}

export const PI = 3.14159;

export class Calculator {
  add(a: number, b: number): number {
    return a + b;
  }
}

import { log } from 'console';
import * as fs from 'fs';
import React from 'react';

Running analyze('example.ts') returns:

{
  "imports": [
    {
      "originalPath": "console",
      "resolvedPath": "/path/to/node_modules/console/index.d.ts",
      "entities": [
        {
          "name": "log"
        }
      ]
    },
    {
      "originalPath": "fs",
      "resolvedPath": "/path/to/node_modules/@types/node/fs.d.ts",
      "entities": [
        {
          "name": "*",
          "alias": "fs"
        }
      ]
    },
    {
      "originalPath": "react",
      "resolvedPath": "/path/to/node_modules/react/index.d.ts",
      "entities": [
        {
          "name": "React"
        }
      ]
    }
  ],
  "exports": [
    {
      "name": "greet",
      "type": "function",
      "signature": "export function greet(name: string): string {\n  return `Hello, ${name}!`;\n}"
    },
    {
      "name": "PI",
      "type": "const",
      "signature": "PI: 3.14159"
    },
    {
      "name": "Calculator",
      "type": "class",
      "signature": "export class Calculator {\n  add(a: number, b: number): number {\n    return a + b;\n  }\n}"
    }
  ]
}

Contributing

Contributions are welcome! Please ensure all tests pass before submitting a pull request.

License

MIT