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 🙏

© 2024 – Pkg Stats / Ryan Hefner

type-explorer

v0.1.4

Published

A runtime type analysis tool with support for multiple schema adapters

Downloads

334

Readme

type-explorer

A powerful runtime type analysis and schema generation utility for TypeScript/JavaScript that provides deep structural analysis of values and automatic schema generation for popular validation libraries.

Key Features

  • Deep Type Analysis

    • Comprehensive inspection of complex data structures
    • Circular reference detection
    • Support for all JavaScript built-in types
    • Custom type handler registration
    • Configurable analysis depth
  • Schema Generation

    • Multi-library support (Zod, Joi, Yup, OpenAPI)
    • Type-safe schema generation
    • Automatic type inference
    • Support for complex nested structures
  • Developer Experience

    • TypeScript-first design
    • Extensive configuration options
    • Predefined analysis presets
    • Detailed type information

Installation

# Using bun
bun add type-explorer

# Using npm
npm install type-explorer

# Using yarn
yarn add type-explorer

# Using pnpm
pnpm add type-explorer

Quick Start

import { TypeAnalyzer } from "type-explorer";

// Initialize analyzer
const analyzer = new TypeAnalyzer();

// Analyze data structure
const result = analyzer.analyze({
  user: {
    id: 1,
    name: "John Doe",
    roles: ["admin", "user"],
    lastLogin: new Date(),
  },
});

// Generate schema (e.g., using Zod)
import { ZodSchemaAdapter } from "type-explorer";
const zodAdapter = new ZodSchemaAdapter();
const schema = zodAdapter.generateSchemaFromData(data);

Core Concepts

Type Analysis

The TypeAnalyzer provides detailed information about your data structures:

const analysis = analyzer.analyze({
  name: "John",
  age: 30,
  hobbies: ["reading", "coding"],
  metadata: {
    lastLogin: new Date(),
    preferences: { theme: "dark" },
  },
});

Analysis Configuration

Customize the analysis depth and detail level:

const analyzer = new TypeAnalyzer({
  maxDepth: 10, // Maximum recursion depth
  includeMethods: true, // Include function analysis
  includeGettersSetters: true, // Include accessor properties
  includePrototype: true, // Include prototype chain
  includePrivateProps: false, // Exclude private properties
});

Preset Configurations

import { CONFIG_PRESETS } from "type-explorer";

// Quick surface-level analysis
const minimalAnalyzer = new TypeAnalyzer(CONFIG_PRESETS.MINIMAL);

// Balanced depth and detail (default)
const standardAnalyzer = new TypeAnalyzer(CONFIG_PRESETS.STANDARD);

// Deep inspection including private properties
const detailedAnalyzer = new TypeAnalyzer(CONFIG_PRESETS.DETAILED);

Schema Generation

Zod Schemas

import { ZodSchemaAdapter } from "type-explorer";
import { z } from "zod";

const zodAdapter = new ZodSchemaAdapter();
const schemaString = zodAdapter.generateSchemaFromData(data);
const schema = new Function("z", `return ${schemaString}`)(z);

console.log(schema.parse(data));

Supported types:

  • Primitives (string, number, boolean, null, undefined)
  • Complex types (object, array, Date, enum, union)
  • Modifiers (optional, nullable)

Joi Schemas

import { JoiSchemaAdapter } from "type-explorer";
import * as Joi from "joi";

const joiAdapter = new JoiSchemaAdapter();
const schemaString = joiAdapter.generateSchemaFromData(data);
const schema = new Function("Joi", `return ${schemaString}`)(Joi);

console.log(schema.validate(data));

Supported types:

  • Primitives (string, number, boolean, null, undefined)
  • Complex types (object, array, Date)
  • Validation features (valid(), alternatives().try(), allow(null))

Yup Schemas

import { YupSchemaAdapter } from "type-explorer";
import * as yup from "yup";

const yupAdapter = new YupSchemaAdapter();
const schemaString = yupAdapter.generateSchemaFromData(data);
const schema = new Function("yup", `return ${schemaString}`)(yup);

console.log(schema.validateSync(data));

Supported types:

  • Primitives (string, number, boolean, null, undefined)
  • Complex types (object, array, Date)
  • Validation features (oneOf(), nullable(), optional())

OpenAPI Schemas

import { OpenAPISchemaAdapter } from "type-explorer";

const openAPIAdapter = new OpenAPISchemaAdapter();
const schemaString = openAPIAdapter.generateSchemaFromData(data);
const schema = JSON.parse(schemaString);
console.log(schema);

Supported features:

  • OpenAPI 3.0 specification
  • All standard JSON Schema types
  • Nullable properties
  • References ($ref)
  • Property descriptions

Advanced Usage

Custom Type Handlers

Register custom type handlers for specialized classes:

analyzer.registerCustomType("MyClass", (value, context) => ({
  type: "MyClass",
  customProperty: value.someProperty,
  path: [...context.path],
}));

Error Handling

try {
  const schema = adapter.generateSchemaFromData(data);
  const validationResult = schema.safeParse(testData);

  if (!validationResult.success) {
    console.error("Validation errors:", validationResult.error);
  }
} catch (error) {
  console.error("Schema generation error:", error);
}

Type Analysis Results

The analyzer provides detailed type information:

interface AnalysisResult {
  type: string; // Type identifier
  path: (string | number)[]; // Property path
  properties?: Record<string, AnalysisResult>; // For objects
  elementTypes?: Array<{
    // For arrays
    type: AnalysisResult;
    frequency: number;
    count: number;
    indices: number[];
  }>;
  // ... additional type-specific properties
}

Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Links