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

@bernierllc/webhook-processor

v1.0.6

Published

Webhook event processing service with signature validation, retry logic, and event routing

Downloads

550

Readme

@bernierllc/webhook-processor

Webhook event processing service with signature validation, retry logic, and event routing.

Overview

The @bernierllc/webhook-processor package provides a comprehensive service for processing webhook events from various sources (GitHub, Stripe, etc.). It handles webhook reception, validation, parsing, commit analysis, event routing, retry logic, and persistence.

Features

  • Webhook Reception: Receive and validate webhooks from multiple sources
  • Signature Validation: HMAC-SHA256 signature validation for secure webhooks
  • GitHub Integration: Parse GitHub webhooks and analyze commits
  • Commit Analysis: Determine if commits are "interesting" for content generation
  • Event Routing: Route events to registered handlers based on source and event type
  • Retry Logic: Automatic retry for failed webhook processing
  • Event Persistence: Optional persistence to Supabase for audit trails
  • Event Broadcasting: Emit events via event emitter for distributed systems

Installation

npm install @bernierllc/webhook-processor

Usage

import { WebhookProcessor, createWebhookProcessor } from '@bernierllc/webhook-processor';
import type { WebhookRequest } from '@bernierllc/webhook-receiver';

// Create processor
const processor = createWebhookProcessor({
  enableSignatureValidation: true,
  secretKey: process.env.WEBHOOK_SECRET,
  enableRetries: true,
  maxRetries: 3,
  enablePersistence: true,
  supabaseUrl: process.env.SUPABASE_URL,
  supabaseAnonKey: process.env.SUPABASE_ANON_KEY,
  handlers: [
    {
      source: 'github',
      eventType: 'push',
      handler: async (event) => {
        console.log('GitHub push received:', event.payload.id);
        // Process the event
      },
      priority: 10
    }
  ]
});

// Process a webhook request
const request: WebhookRequest = {
  method: 'POST',
  headers: {
    'content-type': 'application/json',
    'x-github-signature': 'sha256=...'
  },
  body: Buffer.from(JSON.stringify(webhookPayload)),
  url: '/webhook/github'
};

const result = await processor.process(request);

if (result.success) {
  console.log('Webhook processed:', result.eventId);
  console.log('Handlers executed:', result.processedEvent?.metadata.handlerCount);
} else {
  console.error('Processing failed:', result.error);
  if (result.retryCount !== undefined) {
    console.log('Will retry at:', result.nextRetryAt);
  }
}

API

WebhookProcessor

Constructor

new WebhookProcessor(config?: WebhookProcessorConfig)

Config Options:

  • enableSignatureValidation (optional) - Enable signature validation (default: true)
  • secretKey (optional) - Secret key for signature validation
  • enableRetries (optional) - Enable retry logic (default: true)
  • maxRetries (optional) - Maximum retry attempts (default: 3)
  • retryDelay (optional) - Retry delay in milliseconds (default: 1000)
  • enablePersistence (optional) - Enable event persistence (default: false)
  • supabaseUrl (optional) - Supabase project URL (required if persistence enabled)
  • supabaseAnonKey (optional) - Supabase anonymous key (required if persistence enabled)
  • handlers (optional) - Array of event handlers to register

Methods

  • registerHandler(handler: WebhookEventHandler): void - Register an event handler
  • removeHandler(handler: WebhookEventHandler): void - Remove an event handler
  • process(request: WebhookRequest): Promise<ProcessResult> - Process a webhook request
  • validateSignature(payload: WebhookPayload): Promise<boolean> - Validate webhook signature
  • getStats(): { totalProcessed: number; successCount: number; failureCount: number } - Get processing statistics
  • shutdown(): Promise<void> - Shutdown the processor gracefully

Event Handlers

Event handlers are functions that process webhook events:

interface WebhookEventHandler {
  source: string;                    // Source to match (e.g., 'github', 'stripe')
  eventType?: string;                // Event type to match (e.g., 'push', 'payment.succeeded')
  handler: (event: ProcessedWebhookEvent) => Promise<void>;
  priority?: number;                  // Priority (higher = executed first)
}

GitHub Webhook Processing

The processor automatically handles GitHub webhooks:

  1. Parses the webhook payload using @bernierllc/github-parser
  2. Analyzes commits using @bernierllc/commit-analyzer to determine if they're "interesting"
  3. Routes to handlers registered for source: 'github' and eventType: 'push'
processor.registerHandler({
  source: 'github',
  eventType: 'push',
  handler: async (event) => {
    if (event.commitAnalysis?.interesting) {
      // Generate content from interesting commits
      await generateContentFromCommit(event.parsed?.commits?.[0]);
    }
  }
});

Retry Logic

When webhook processing fails, the processor can automatically retry:

const processor = createWebhookProcessor({
  enableRetries: true,
  maxRetries: 3,
  retryDelay: 1000
});

// Failed webhooks are automatically queued for retry
const result = await processor.process(request);
if (!result.success && result.retryCount !== undefined) {
  console.log(`Will retry (attempt ${result.retryCount}) at ${result.nextRetryAt}`);
}

Event Persistence

Events can be persisted to Supabase for audit trails:

const processor = createWebhookProcessor({
  enablePersistence: true,
  supabaseUrl: process.env.SUPABASE_URL,
  supabaseAnonKey: process.env.SUPABASE_ANON_KEY
});

The processor expects a webhook_events table:

CREATE TABLE webhook_events (
  event_id TEXT PRIMARY KEY,
  source TEXT NOT NULL,
  event_type TEXT NOT NULL,
  payload JSONB NOT NULL,
  processed_at TIMESTAMPTZ NOT NULL,
  processing_duration INTEGER,
  handler_count INTEGER,
  success_count INTEGER,
  failure_count INTEGER
);

Integration Status

  • Logger: ✅ Integrated - Uses @bernierllc/logger for all logging operations
  • Docs-Suite: ✅ Ready - Full TypeDoc API documentation available
  • NeverHub: ⚠️ Optional - Can emit webhook events to NeverHub event bus for distributed observability

Dependencies

  • @bernierllc/webhook-receiver - Webhook reception and validation
  • @bernierllc/github-parser - GitHub webhook parsing
  • @bernierllc/commit-analyzer - Commit interest analysis
  • @bernierllc/task-queue-core - Background task processing for retries
  • @bernierllc/event-emitter - Event broadcasting
  • @bernierllc/supabase-client - Event persistence (optional)
  • @bernierllc/logger - Logging

Testing

Run tests with:

npm test
npm run test:coverage

Target coverage: 85%+ (service package standard)

Current coverage: 97.82% statements, 88.67% branches, 92.85% functions, 97.8% lines

License

Copyright (c) 2025 Bernier LLC

This file is licensed to the client under a limited-use license. The client may use and modify this code only within the scope of the project it was delivered for. Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.