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

saga-flow

v1.0.0

Published

A JavaScript library for implementing the Saga pattern in distributed transactions

Readme

saga-flow

A JavaScript library for implementing the Saga pattern in distributed transactions

Installation

npm install saga-flow

Basic Usage

import {
  createSaga,
  defineStep,
  defineParallelSteps,
  withRetry,
  withTimeout,
  logger
} from 'saga-flow';

// Create a basic Saga
const saga = createSaga()
  .step(defineStep({
    name: 'CreateOrder',
    action: async () => {
      // Order creation logic
      return { orderId: 1 };
    },
    compensate: async () => {
      // Order cancellation logic
      return { orderCancelled: true };
    }
  }))
  .step(defineStep({
    name: 'ChargeCard',
    action: async (ctx) => {
      // Payment logic
      return { paymentId: 1 };
    },
    compensate: async () => {
      // Payment refund logic
      return { refunded: true };
    }
  }));

// Execute
await saga.run();

Advanced Features

1. Parallel Execution

const saga = createSaga()
  .step(createOrderStep)
  .parallel(defineParallelSteps([
    {
      name: 'ChargeCard',
      action: async (ctx) => {
        // Payment logic
      }
    },
    {
      name: 'SendEmail',
      action: async () => {
        // Email sending logic
      }
    }
  ]));

2. Retry and Timeout

const saga = createSaga()
  .step(defineStep({
    name: 'RetryStep',
    action: async () => {
      return await withRetry(
        () => withTimeout(
          async () => {
            // Perform operation
          },
          5000, // 5 second timeout
          'Operation timed out'
        ),
        {
          maxAttempts: 3,
          initialDelay: 1000,
          maxDelay: 10000,
          backoffFactor: 2,
          onRetry: (error, attempt) => {
            logger.warn(`Retry ${attempt}/3: ${error.message}`);
          }
        }
      );
    }
  }));

3. Event Handling

const saga = createSaga()
  .step(createOrderStep)
  .on('onStart', (ctx) => logger.info('Saga started:', ctx))
  .on('onSuccess', (ctx) => logger.info('Saga succeeded:', ctx))
  .on('onError', (error) => logger.error('Saga failed:', error))
  .on('onCompensate', (ctx) => logger.info('Compensation executed:', ctx));

4. Scheduling

// Run every 5 minutes
const taskId = scheduleSaga(saga, '*/5 * * * *');

// Cancel later
cancelScheduledSaga(taskId);

5. State Management

// Save state
const sagaId = 'order-123';
exportSagaState(sagaId, saga);

// Get state
const state = getSagaState(sagaId);

// Restore state
const restoredSaga = resumeSaga(sagaId, createSaga());

// Clear state
clearSagaState(sagaId);

6. Snapshot Management

// Register snapshot exporter
registerSnapshotExporter(async (snapshot) => {
  // Save snapshot to file or database
  await saveToDatabase(snapshot);
});

// Export snapshot
await exportSnapshot(sagaId, saga);

7. Parallel Processing Utility

const results = await executeParallel([
  async () => { /* Task 1 */ },
  async () => { /* Task 2 */ },
  async () => { /* Task 3 */ }
], {
  concurrency: 2,
  onProgress: ({ completed, total, success }) => {
    logger.info(`Progress: ${completed}/${total}`);
  },
  stopOnError: false
});

8. Logging

import { logger } from 'saga-flow';

// Set log level
logger.setLogLevel('DEBUG');

// Log messages
logger.debug('Debug message', { data: 123 });
logger.info('Info message', { data: 456 });
logger.warn('Warning message', { data: 789 });
logger.error('Error message', { error: new Error('Test') });

API Reference

Core API

  • createSaga(): Create a new Saga instance
  • defineStep(options): Define a Step
  • defineParallelSteps(steps): Define Steps for parallel execution

State Management API

  • exportSagaState(sagaId, state): Save Saga state
  • getSagaState(sagaId): Get saved state
  • resumeSaga(sagaId, saga): Restore from saved state
  • clearSagaState(sagaId): Clear saved state

Scheduling API

  • scheduleSaga(saga, cronExpression): Schedule Saga execution
  • cancelScheduledSaga(taskId): Cancel scheduled Saga

Utility API

  • withRetry(operation, options): Retry logic
  • withTimeout(operation, timeoutMs, errorMessage): Timeout handling
  • executeParallel(operations, options): Parallel execution
  • logger: Logging utility

Event List

  • onStart: Saga started
  • onSuccess: Saga succeeded
  • onError: Saga failed
  • onCompensate: Compensation executed
  • onStepSuccess: Step succeeded
  • onStepError: Step failed
  • onCompensateError: Compensation failed

License

MIT