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 🙏

© 2026 – Pkg Stats / Ryan Hefner

explainerr

v0.1.0

Published

Rule-based, fully local explanations for confusing JavaScript errors. No AI, no network, no dependencies.

Readme

ExplainErr

Clear, human-readable explanations for confusing JavaScript errors. Rule-based, fully local, zero dependencies.

TypeError: Cannot read properties of undefined (reading 'map')

becomes a structured answer to: what happened, why it usually happens, how to fix it, how to prevent it and where it came from.

Status: 0.1.0, Phase 1. This release is the core engine plus 10 foundational JavaScript rules. See Rule coverage and Current limitations before relying on it.

Why it exists

Error messages are written for the engine, not for the person reading them. ExplainErr maps known messages to explanations written for people, and it does so with plain pattern rules:

  • No AI and no network. Nothing leaves your machine: no API calls, no telemetry, no source code transmission.
  • Deterministic. The same error always produces the same result.
  • Safe to call in error handlers. explain() never throws, never mutates the error, never touches console and never executes anything from a rule or a suggested fix.
  • Honest. When no rule matches, it says so and hands back the original message and stack trace unchanged.

Installation

npm install explainerr

Requires Node.js 20 or newer. Ships ESM, CommonJS and TypeScript declarations.

Basic usage

import { explain } from "explainerr";

try {
  const users = undefined;
  users.map((user) => user.name);
} catch (error) {
  const result = explain(error);

  if (result.matched) {
    console.log(result.title);
    console.log(result.explanation);
  }
}

CommonJS works the same way:

const { explain } = require("explainerr");

explain() only returns data. It does not log, rethrow or swallow anything; what happens to the original error stays up to you.

Example output

{
  matched: true,
  id: 'JS-TYPE-001',
  category: 'javascript',
  language: 'javascript',
  framework: null,
  errorType: 'TypeError',
  message: "Cannot read properties of undefined (reading 'map')",
  code: null,
  title: "Cannot read 'map' of undefined",
  explanation: "Your code tried to read the property or call the method 'map' on a value that is undefined. Only real values have properties, so JavaScript stops as soon as the access happens.",
  causes: [
    'The variable was declared but never assigned a value.',
    'Data from an API or another async source has not arrived yet.',
    'An object property or function return value is undefined when your code expected an object or array.',
    'A function parameter was not passed by the caller.'
  ],
  fixes: [
    {
      title: 'Use optional chaining so the access is skipped when the value is missing',
      code: 'const result = value?.map;'
    },
    // ...
  ],
  prevention: 'Initialize variables with sensible defaults and validate data that comes from outside your code before using it.',
  location: {
    fileName: 'file:///app/examples/basic.mjs',
    lineNumber: 6,
    columnNumber: 9,
    functionName: null
  },
  stack: "TypeError: Cannot read properties of undefined (reading 'map')\n    at ...",
  confidence: 'high'
}

When no rule matches

explain(new Error("The flux capacitor is misaligned"));
// {
//   matched: false,
//   id: null,
//   category: null,
//   language: 'javascript',
//   framework: null,
//   errorType: 'Error',
//   message: 'The flux capacitor is misaligned',   // preserved
//   code: null,
//   title: 'Unrecognized Error',
//   explanation: 'ExplainErr has no rule that matches this error yet, so it cannot explain it. ...',
//   causes: [],
//   fixes: [],
//   prevention: null,
//   location: { ... },                              // still parsed from the stack
//   stack: 'Error: The flux capacitor is misaligned\n    at ...',   // preserved
//   confidence: null
// }

Unavailable information is always null (or an empty array), never a guess. The result is plain data, so it is safe to pass to JSON.stringify.

Supported inputs

explain() accepts anything that can be thrown:

| Input | Handling | | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | | Native errors (Error, TypeError, ReferenceError, SyntaxError, RangeError, AggregateError, ...) | Name, message, stack, code and cause are read. | | Error subclasses | Same as native errors; a custom name is kept. | | Error-like objects ({ name, message, stack }) | Treated like errors. Wrongly typed fields are ignored or coerced. | | Raw message strings ("x is not defined") | Matched by message. Confidence is lowered because the error type is unknown. | | Printed errors and pasted stack traces ("TypeError: ...\n at ...") | Name, message, Node.js [CODE] and frames are parsed out of the text. | | null, undefined, numbers, plain objects, functions, ... | Returned as matched: false with a description. Never throws. | | Hostile objects (throwing getters, revoked proxies, circular cause) | Handled without throwing. |

Rule coverage

Be aware of how small the current rule set is. Version 0.1.0 ships these 10 rules:

| ID | Error | | --------------- | --------------------------------------------------------------------------------- | | JS-TYPE-001 | Cannot read properties of undefined/null (reading 'x') | | JS-TYPE-002 | Cannot set properties of undefined/null (setting 'x') | | JS-TYPE-003 | x is not a function | | JS-TYPE-004 | x is not iterable | | JS-TYPE-005 | Assignment to constant variable | | JS-REF-001 | x is not defined | | JS-REF-002 | Cannot access 'x' before initialization | | JS-RANGE-001 | Maximum call stack size exceeded | | JS-RANGE-002 | Invalid array length | | JS-SYNTAX-001 | JSON parse failures (Unexpected token ... JSON, Unexpected end of JSON input) |

There are no Node.js, React or TypeScript rules yet. The classifier can already recognize a Node.js error code (ENOENT, ERR_*) or a TypeScript diagnostic code (TS2322) and reports it in code, but such errors currently come back as matched: false.

Current limitations

  • Small rule set. Most real-world errors are not covered yet (see above).
  • V8 wording only. Rules match the messages produced by V8 (Node.js, Chrome, Edge). Firefox and Safari word the same errors differently and are mostly not matched.
  • V8 stack traces only. Firefox/Safari fn@file:line:col frames are not parsed; location is null for them.
  • No source maps. Locations are reported exactly as they appear in the stack trace.
  • English only.
  • The outer error only. cause and the inner errors of an AggregateError are normalized (see normalizeError) but not explained.
  • Error type must match by name. A TypeError rule does not apply to a subclass that sets a different name.
  • Framework detection is minimal. framework is "react" only when the stack passes through react/react-dom or the message is a minified React error; otherwise it is null.
  • Only the first 4,096 characters of a message are tested against rules.

How the rule engine works

Every call runs the same pipeline:

input → normalize → parse stack → classify → match rules → build explanation
  1. Normalizer (src/core/normalizer.ts) turns any input into one shape: name, message, stack, code, cause, errors. It only reads the input.
  2. Stack parser (src/parsers/stack-parser.ts) extracts file, line, column and function name from V8 frames.
  3. Classifier (src/core/classifier.ts) derives language, framework, Node.js code and TypeScript code. Each is null unless there is concrete evidence.
  4. Matcher (src/core/matcher.ts) evaluates every rule and ranks the matches.
  5. Analyzer (src/core/analyzer.ts) fills the winning rule's text and assembles the result.

Rules are data

A rule is a plain object. Rules are matched, never executed:

import type { Rule } from "explainerr";

const rule: Rule = {
  id: "JS-REF-002",
  category: "javascript",
  errorTypes: ["ReferenceError"], // optional
  patterns: [/Cannot access '(?<name>[^']+)' before initialization/],
  codes: [], // optional, e.g. ["ENOENT"]
  priority: 0, // optional
  title: "'{{name}}' was used before it was initialized",
  explanation: "...",
  causes: ["..."],
  fixes: [{ title: "Move the declaration above its first use", code: "..." }],
  prevention: "...",
  confidence: "high",
};
  • Patterns: a string is a case-sensitive substring test, a RegExp is tested as given. A rule matches if any pattern matches.
  • Codes: a rule also matches when one of its codes equals the error's code.
  • Error types: if errorTypes is set, an error with a different known name never matches. If the input has no name at all (a bare message string), the rule may still match, with confidence lowered one step.
  • Placeholders: {{name}} in any text field is replaced with the named capture group name from the pattern that matched. {{name|fallback}} supplies text for when the group is absent. This is string substitution only.

Overlapping rules

When several rules match, the winner is chosen in a fixed order:

  1. higher priority;
  2. stronger evidence: code match, then pattern match, then verified error type;
  3. rule ID in ascending order.

Registration order never affects the outcome.

Custom rules

import { createExplainer } from "explainerr";

const explainer = createExplainer({
  rules: [myRule], // added to the built-in rules
  // includeBuiltinRules: false,  // use only your own rules
});

explainer.explain(error);

Rules are validated once, when the explainer is created. A malformed rule, a duplicate ID, a RegExp with the stateful g/y flag or a placeholder without a matching capture group throws a TypeError at that point, so configuration mistakes surface at startup. explain() itself never throws.

API

| Export | Description | | ------------------------------------ | ---------------------------------------------------------------------- | | explain(error) | Explains any value using the built-in rules. Returns an Explanation. | | createExplainer(options?) | Returns { explain } with custom rules. | | normalizeError(input) | The normalizer on its own. Returns a NormalizedError. | | parseStackTrace(stack) | The stack parser on its own. Returns StackFrame[]. | | classifyError(normalized, frames?) | The classifier on its own. Returns a Classification. | | builtinRules | The rules that ship with the package. |

Types: Explanation, MatchedExplanation, UnmatchedExplanation, Rule, Fix, RuleMatch, SourceLocation, StackFrame, NormalizedError, Classification, Explainer, ExplainerOptions, Confidence, Language, Framework, RuleCategory, InputKind.

Explanation is a discriminated union, so checking result.matched narrows id, prevention and confidence to non-null values.

Development setup

Working on the package itself needs Node.js 22 or newer, because the test and lint tooling requires it. The published package runs on Node.js 20 and newer.

git clone <your fork>
cd explainerr
npm install

| Command | Purpose | | ---------------------- | -------------------------------------------------- | | npm run build | Build ESM, CommonJS and declarations into dist/. | | npm test | Run the test suite once. | | npm run test:watch | Run tests in watch mode. | | npm run typecheck | Type-check sources and tests. | | npm run lint | Run ESLint. | | npm run format | Format with Prettier. | | npm run format:check | Check formatting without writing. | | npm run check | Typecheck, lint, format check and tests in one go. |

After building, the examples run against the built package:

node examples/basic.mjs
node examples/basic.cjs
node examples/custom-rules.mjs

Project layout

src/
  core/        normalizer, classifier, matcher, analyzer, explainer, rule validation, templates
  parsers/     V8 stack trace parser
  rules/       built-in rules by category (javascript/, node/, react/, typescript/)
  types/       all public and internal interfaces
  utils/       guarded property access
  index.ts     public API
tests/
  core/        unit tests per pipeline stage
  parsers/     stack parser tests
  integration/ explain() end to end

Adding a rule

  1. Add the rule object to the matching file under src/rules/<category>/.
  2. Give it a unique ID.
  3. Add test cases to tests/integration/explain.test.ts, ideally with an error actually produced by the engine.

License

MIT