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

@esportsplus/reactivity

v0.33.0

Published

Downloads

1,082

Readme

@esportsplus/reactivity

Project doc bundle: docs/index.md — rejected dead-ends, skip reasons, completed-work index.

A fine-grained reactivity system with compile-time transformations. Write reactive code with natural JavaScript syntax while the compiler generates optimized signal-based code.

Installation

pnpm add @esportsplus/reactivity

Core Concepts

The library provides a reactive() function that acts as a compile-time macro. At build time, transformer plugins convert reactive() calls into optimized signal/computed primitives.

Reactive Primitives

import { reactive, effect } from '@esportsplus/reactivity';

// Signals - reactive values
let count = reactive(0);
let name = reactive('John');

// Read values naturally
console.log(count);  // 0
console.log(name);   // 'John'

// Write with simple assignment
count = 10;
name = 'Jane';

// Compound assignments work
count += 5;
count++;

// Computed values - derived from other reactive values
let doubled = reactive(() => count * 2);
console.log(doubled);  // 30

Reactive Objects

import { reactive } from '@esportsplus/reactivity';

let user = reactive({
    age: 25,
    name: 'John',
    // Computed properties are arrow functions
    canVote: () => user.age >= 18
});

console.log(user.name);     // 'John'
console.log(user.canVote);  // true

user.age = 17;
console.log(user.canVote);  // false

// Cleanup resources
user.dispose();

Note: dispose is a reserved key and cannot be used as a property name in reactive objects.

Reactive Arrays

import { reactive } from '@esportsplus/reactivity';

let state = reactive({
    items: [1, 2, 3],
    total: () => state.items.reduce((a, b) => a + b, 0)
});

console.log(state.total);  // 6

state.items.push(4, 5);
console.log(state.total);  // 15

// Listen to array events
state.items.on('push', ({ items }) => {
    console.log('Added:', items);
});

// Cleanup resources
state.items.dispose();

Async Computeds

Computed properties that return Promises are automatically unwrapped:

import { reactive } from '@esportsplus/reactivity';

let state = reactive({
    userId: 1,
    user: async () => {
        let response = await fetch(`/api/users/${state.userId}`);
        return response.json();
    }
});

// Initially undefined while loading
console.log(state.user);  // undefined

// After promise resolves, value is available
// Changing userId triggers a new fetch
state.userId = 2;

Effects

import { effect, reactive } from '@esportsplus/reactivity';

let count = reactive(0);

let cleanup = effect(() => {
    console.log('Count is:', count);
});

count = 1;  // logs: Count is: 1
count = 2;  // logs: Count is: 2

cleanup();  // stops the effect

Transformer Plugins

The library requires a build-time transformer to convert reactive() calls into optimized code. Two plugins are available:

Vite Plugin

// vite.config.ts
import { defineConfig } from 'vite';
import reactivity from '@esportsplus/reactivity/compiler/vite';

export default defineConfig({
    plugins: [
        reactivity()
    ]
});

TypeScript Custom Transformer

For direct TypeScript compilation using ttsc or ts-patch:

// tsconfig.json
{
    "compilerOptions": {
        "plugins": [
            { "transform": "@esportsplus/reactivity/compiler/tsc" }
        ]
    }
}

How It Works

The transformer converts your code at compile time:

Input:

let count = reactive(0);
let doubled = reactive(() => count * 2);

count = 5;
console.log(doubled);

Output:

import { computed, read, signal, write } from '@esportsplus/reactivity';

let count = signal(0);
let doubled = computed(() => read(count) * 2);

write(count, 5);
console.log(read(doubled));

Reactive objects are transformed into classes:

Input:

let user = reactive({
    name: 'John',
    greeting: () => `Hello, ${user.name}`
});

Output:

class ReactiveObject_1 {
    #name = signal('John');
    #greeting = null;

    get name() { return read(this.#name); }
    set name(v) { write(this.#name, v); }
    get greeting() { return read(this.#greeting ??= computed(() => `Hello, ${this.name}`)); }

    dispose() {
        if (this.#greeting) dispose(this.#greeting);
    }
}

let user = new ReactiveObject_1();

API Reference

Core Functions

| Function | Description | |----------|-------------| | reactive(value) | Creates a signal from a primitive value (compile-time only) | | reactive(() => expr) | Creates a computed value (compile-time only) | | reactive({...}) | Creates a reactive object with signals and computeds | | reactive([...]) | Creates a reactive array | | effect(fn, onError?) | Runs a function that re-executes when dependencies change. Returns a dispose function. Optional onError receives thrown or rejected errors | | root(fn) | Creates an untracked scope. If fn accepts an argument, a dispose function is provided | | onCleanup(fn) | Registers a cleanup function for the current effect/computed |

Low-Level Functions

These operate directly on signal/computed nodes — the transformer emits them, and they can be called by hand:

| Function | Description | |----------|-------------| | signal(value, equals?) | Creates a raw signal. Optional equals comparator suppresses writes it deems equal (default ===) | | computed(fn, equals?) | Creates a raw computed. A fn returning a Promise or AsyncIterable becomes an async computed automatically (initial value undefined, unwrapped to Settled<T>). Optional equals comparator | | read(node) | Reads a signal or computed value, subscribing the current scope | | write(signal, value) | Sets a signal value | | peek(node) | Reads a signal/computed's current value without subscribing (returns an up-to-date value even for a dirty computed) | | untrack(fn) | Runs fn without tracking dependencies; returns fn's result | | batch(fn) | Groups writes so dependent effects defer until fn returns; pair with flush() for a synchronous transaction | | flush() | Synchronously settles all pending computed/effect updates | | dispose(computed) | Disposes a computed and its dependencies | | computed.invalidate(computed) | Forces re-derivation of a computed on next read (re-dispatches an async computed's promise for a refetch) | | signal.selector(signal, key) | Per-key selector: within a tracking scope, subscribes to whether signal's value equals key, so only key-matching observers re-run on write (O(1) fan-out) |

Type Guards

| Function | Description | |----------|-------------| | isSignal(value) | Checks if value is a Signal | | isComputed(value) | Checks if value is a Computed | | isPromise(value) | Checks if value is a Promise |

Classes

For advanced use cases, the underlying classes are exported:

| Class | Description | |-------|-------------| | ReactiveArray<T> | Array subclass with reactivity and event dispatching | | ReactiveObject<T> | Base class for reactive objects |

Constants

Symbol constants for type identification:

| Constant | Description | |----------|-------------| | SIGNAL | Symbol identifying Signal nodes | | COMPUTED | Symbol identifying Computed nodes | | REACTIVE_ARRAY | Symbol identifying ReactiveArray instances | | REACTIVE_OBJECT | Symbol identifying ReactiveObject instances |

Types

| Type | Description | |------|-------------| | Signal<T> | Signal node type | | Computed<T> | Computed node type | | Settled<T> | Resolved value type of a computed (unwraps Promise<T>/AsyncIterable<T> to T) | | SelectorSignal<T> | Signal variant backing signal.selector per-key subscriptions | | Link | Dependency graph link between nodes | | Reactive<T> | Utility type for inferring reactive object/array types | | TransformResult | Compiler transform output metadata |

ReactiveArray

Methods

| Method | Description | |--------|-------------| | clear() | Removes all items, disposes nested reactive objects, and dispatches clear event | | concat(...items) | Appends items in place (mutating, returns this). Unlike Array.prototype.concat | | dispatch(event, value?) | Manually dispatches an event to registered listeners | | dispose() | Disposes all nested reactive objects and empties the array | | on(event, listener) | Subscribes to an array event. Deduplicates by reference | | once(event, listener) | Subscribes to an event once |

All standard array methods (push, pop, shift, unshift, splice, sort, reverse) are overridden and trigger corresponding events. Empty calls to push, unshift, and concat are no-ops.

Events

| Event | Payload | Description | |-------|---------|-------------| | clear | undefined | Array was cleared | | concat | { items: T[] } | Items were concatenated | | pop | { item: T } | Item was popped | | push | { items: T[] } | Items were pushed | | reverse | undefined | Array was reversed | | set | { index, item } | Item was set at index | | shift | { item: T } | Item was shifted | | sort | { order: number[] } | Array was sorted (order maps new→old indices) | | splice | { start, deleteCount, items } | Array was spliced | | unshift | { items: T[] } | Items were unshifted |

Architecture

  • src/system.ts — the core signal/computed/effect engine: height-bucketed heap scheduler, generation-version dependency dedup (read-version dedup), and iterative (non-recursive) notify/update/dispose walks. Also supports async (Promise/AsyncIterable) computeds and per-key selector signals (signal.selector).
  • src/constants.ts — shared state bitmasks and symbol constants consumed by every other module.
  • src/types.ts — shared Signal/Computed/Link/Reactive types.
  • src/reactive/index.ts, src/reactive/array.ts, src/reactive/object.ts — the runtime reactive() dispatch and the ReactiveObject/ReactiveArray classes it builds on.
  • src/compiler/* — the build-time transform pipeline (constants.ts, primitives.ts, object.ts, array.ts, index.ts) plus the plugins/tsc.ts and plugins/vite.ts entrypoints that wire it into a build (see Transformer Plugins above).

Development

pnpm install
pnpm build   # tsc
pnpm test    # vitest run
pnpm bench   # vitest bench --run

agent:test (tsc --noEmit && vitest run) and agent:bench (vitest bench --run) are the CI-facing aliases of the same build/test/bench commands.

License

MIT