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

node-stm

v1.0.1

Published

A TypeScript implementation of Software Transactional Memory (STM) using SQLite

Downloads

3

Readme

🚀 node-stm

TypeScript SQLite Node.js License

A powerful TypeScript implementation of Software Transactional Memory (STM) using SQLite as the backing store. This library provides atomic transactions with optimistic concurrency control for managing shared state in Node.js applications.

📚 Table of Contents

✨ Features

  • 🔄 Atomic Transactions: Guaranteed atomicity for all operations
  • 🛡️ Optimistic Concurrency Control: Automatic conflict detection and resolution
  • 💾 SQLite Backing Store: Persistent and reliable storage
  • 🗺️ JSON Path Operations: Access nested data with path-based operations
  • 📝 Type Safety: Full TypeScript support with type inference
  • 🔌 Multiple Database Modes: Support for both in-memory and file-based storage
  • 🔄 Automatic Retries: Built-in retry mechanism for handling conflicts
  • 🚀 High Performance: Optimized for concurrent operations

📦 Installation

npm install node-stm

🚀 Quick Start

import { SqliteSTM } from 'node-stm';

// Create a new STM instance
const stm = new SqliteSTM();

// Create a new TVar (transactional variable)
stm.newTVar('counter', 0);

// Execute an atomic transaction
const result = stm.atomically((tx) => {
  const value = tx.readTVar<number>('counter');
  tx.writeTVar('counter', value + 1);
  return value + 1;
});

console.log(result); // Output: 1

🧠 Core Concepts

TVars (Transactional Variables)

TVars are the fundamental building blocks of the STM system. They are:

  • 🔒 Thread-safe and transactionally consistent
  • 📦 Can store any JSON-serializable value
  • 🔄 Automatically versioned for conflict detection

Transactions

Transactions provide atomic operations with these guarantees:

  • ⚡ All-or-nothing execution
  • 🔄 Automatic rollback on failure
  • 🛡️ Conflict detection and resolution
  • 🔁 Automatic retries on conflicts

Path Operations

Access nested data using JSON paths:

// Read nested data
const city = tx.readTVarPath<string>('user', 'address.city');

// Update nested data
tx.updateTVarPath('user', 'preferences.theme', 'dark');

📖 API Reference

SqliteSTM Class

Constructor

constructor(db?: number, dir?: string)
  • db: Optional database ID (auto-generated if not provided)
  • dir: Optional directory for database storage

Methods

newTVar
newTVar<T>(id: string, initialValue: T): void

Creates a new transactional variable.

atomically
atomically<T>(fn: (tx: Transaction) => T): T

Executes an atomic transaction.

newConnection
newConnection(): SqliteSTM

Creates a new connection to the same database.

Transaction Class

Methods

readTVar
readTVar<T>(id: string): T

Reads a transactional variable.

writeTVar
writeTVar<T>(id: string, value: T): void

Writes to a transactional variable.

readTVarPath
readTVarPath<T>(id: string, path: string): T

Reads a specific path within a JSON object.

updateTVarPath
updateTVarPath<T>(id: string, path: string, value: T): void

Updates a specific path within a JSON object.

📝 Examples

Money Transfer Example

// Create a TVar with user balances
stm.newTVar('users', {
  alice: { balance: 100, transactions: [] },
  bob: { balance: 50, transactions: [] },
});

// Execute a money transfer
stm.atomically((tx) => {
  const aliceBalance = tx.readTVarPath<number>('users', 'alice.balance');
  const bobBalance = tx.readTVarPath<number>('users', 'bob.balance');

  // Transfer $30 from Alice to Bob
  tx.updateTVarPath('users', 'alice.balance', aliceBalance - 30);
  tx.updateTVarPath('users', 'bob.balance', bobBalance + 30);

  // Record the transaction
  const txId = Date.now().toString();
  tx.updateTVarPath('users', 'alice.transactions', [
    ...tx.readTVarPath<string[]>('users', 'alice.transactions'),
    `Sent $30 to Bob (${txId})`,
  ]);
});

Concurrent Counter Example

// Initialize counter
stm.newTVar('counter', 0);

// Create multiple concurrent transactions
const promises = Array.from(
  { length: 10 },
  () =>
    new Promise<void>((resolve) => {
      setTimeout(() => {
        stm.atomically((tx) => {
          const counter = tx.readTVar<number>('counter');
          tx.writeTVar('counter', counter + 1);
        });
        resolve();
      }, Math.random() * 10);
    })
);

await Promise.all(promises);

🔧 Advanced Usage

Custom Database Directory

const stm = new SqliteSTM(undefined, '/path/to/db/directory');

Handling Concurrent Modifications

try {
  stm.atomically((tx) => {
    // Your transaction code
  });
} catch (error) {
  if (error.message === 'Concurrent modification detected') {
    // Handle conflict
  }
}

Nested Transactions

stm.atomically((tx) => {
  // Outer transaction
  stm.newConnection().atomically((innerTx) => {
    // Inner transaction
  });
});

🤝 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.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

📄 License

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

🙏 Acknowledgments

  • Inspired by Haskell's STM implementation
  • Built with better-sqlite3
  • Thanks to all contributors who have helped shape this project