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

@shockmouse/recommendations

v1.0.1

Published

A robust, type-safe recommendation engine for managing product recommendations with sophisticated fallback handling, telemetry, and rate limiting.

Readme

Recommendation Engine SDK

A robust, type-safe recommendation engine for managing product recommendations with sophisticated fallback handling, telemetry, and rate limiting.

Features

  • 🎯 Priority-based recommendation sets
  • 🔄 Intelligent fallback chains
  • ⚡️ Built-in caching with TTL support
  • 🛡️ Rate limiting protection
  • 📊 Telemetry and error tracking
  • 🎨 Context-aware display conditions
  • ✅ Full TypeScript support
  • ⏱️ Timeout protection
  • 🔍 Batch evaluation

Installation

npm install @occollective/recommendations

Quick Start

import { createEngine } from '@shockmouse/recommendations';

// Create a configured engine instance
const engine = createEngine({
  maxTimeout: 2000, // 2 seconds
  maxFallbackDepth: 3,
  cache: {
    ttl: 5 * 60 * 1000, // 5 minutes
    maxSize: 1000,
  },
  rateLimiting: {
    windowMs: 60000, // 1 minute
    maxRequests: 100,
  },
});

// Define a recommendation set
engine.define(
  'holiday-sale',
  [
    { id: 'bundle-1', name: 'Holiday Bundle', price: 99.99 },
    { id: 'gift-1', name: 'Gift Set', price: 49.99 },
  ],
  async (context) => {
    // Custom display logic
    return isHolidaySeason() && hasStock();
  },
  {
    priority: 2,
    location: 'home-page',
    fallbackProducts: [
      { id: 'regular-1', name: 'Standard Option', price: 29.99 },
    ],
  }
);

// Get recommendations for a location
const recommendations = await engine.getForLocation('home-page', {
  userId: 'user-123',
  region: 'US',
});

Advanced Usage

Fallback Chains

Create sophisticated fallback chains for reliable recommendation delivery:

// Primary recommendation set
engine.define(
  'premium-members',
  premiumProducts,
  async (context) => isPremiumMember(context),
  {
    priority: 3,
    location: 'product-page',
    fallback: 'personalized', // Falls back to personalized recommendations
  }
);

// Secondary recommendation set
engine.define(
  'personalized',
  personalizedProducts,
  async (context) => hasPersonalizationData(context),
  {
    priority: 2,
    location: 'product-page',
    fallback: 'default', // Falls back to default recommendations
  }
);

// Default recommendation set
engine.define('default', defaultProducts, async () => true, {
  priority: 1,
  location: 'product-page',
  fallbackProducts: safeDefaultProducts, // Final fallback
});

Telemetry Integration

The engine provides comprehensive telemetry tracking:

const engine = createEngine({
  telemetry: {
    trackEvent: (name, properties) => {
      analytics.track(name, properties);
    },
    trackError: (error, context) => {
      errorReporting.captureException(error, { extra: context });
    },
    trackTiming: (name, durationMs, properties) => {
      metrics.recordTiming(name, durationMs, properties);
    },
  },
});

Rate Limiting

Protect your recommendation engine from overuse:

const engine = createEngine({
  rateLimiting: {
    windowMs: 60000, // 1 minute window
    maxRequests: 100, // Max requests per window
  },
});

Batch Processing

The engine automatically processes recommendations in batches to prevent blocking:

// These will be evaluated in batches of 3
engine.define('set1', products1, condition1, { location: 'home' });
engine.define('set2', products2, condition2, { location: 'home' });
engine.define('set3', products3, condition3, { location: 'home' });
engine.define('set4', products4, condition4, { location: 'home' });
engine.define('set5', products5, condition5, { location: 'home' });

Type Safety

The engine provides comprehensive TypeScript types:

import type {
  Product,
  RecommendationSet,
  RecommendationOptions,
  EngineOptions,
} from '@occollective/recommendations';

interface CustomProduct extends Product {
  category: string;
  inStock: boolean;
}

const options: RecommendationOptions = {
  priority: 2,
  location: 'category-page',
  fallbackProducts: defaultProducts,
};

Error Handling

The engine includes built-in error handling and timeout protection:

try {
  const recommendations = await engine.get('holiday-sale', context);
} catch (error) {
  if (error instanceof RecommendationError) {
    switch (error.code) {
      case ErrorCodes.RATE_LIMIT_EXCEEDED:
        // Handle rate limiting
        break;
      case ErrorCodes.EVALUATION_TIMEOUT:
        // Handle timeout
        break;
      case ErrorCodes.FALLBACK_DEPTH_EXCEEDED:
        // Handle excessive fallback chain
        break;
    }
  }
}

Performance Optimization

Caching Strategy

The engine implements intelligent caching:

const engine = createEngine({
  cache: {
    ttl: 5 * 60 * 1000, // Cache for 5 minutes
    maxSize: 1000, // Prevent memory leaks
  },
});

Efficient Context Usage

Optimize your display conditions:

engine.define(
  'efficient-set',
  products,
  async (context) => {
    // ✅ Good: Cache expensive operations
    const userSegment = await getUserSegmentCached(context.userId);
    return userSegment === 'target';
  },
  options
);

Best Practices

  1. Fallback Chains: Keep fallback depth reasonable (recommended max: 3-5 levels)
  2. Timeouts: Set appropriate timeouts based on your display condition complexity
  3. Caching: Use TTL values that balance freshness with performance
  4. Rate Limiting: Configure limits based on your infrastructure capacity
  5. Error Handling: Always handle potential errors, especially in production
  6. Telemetry: Implement comprehensive tracking for monitoring and debugging

License

MIT License - see the LICENSE file for details.