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/version-store

v1.0.5

Published

Generic version history and diff tracking for any entity type

Readme

@bernierllc/version-store

Generic version history and diff tracking for any entity type. Provides version control capabilities without entity-specific logic.

Installation

npm install @bernierllc/version-store

Features

  • Generic version tracking for any entity type
  • Automatic version numbering (1, 2, 3, ...)
  • Change field tracking (automatic or manual)
  • Snapshot storage (type-safe generic storage)
  • JSON diff generation between versions
  • Non-destructive rollback support
  • Version metadata management (who, when, why)
  • Type-safe generic implementation
  • Storage interface for custom implementations

Usage

Basic Version Tracking

import { VersionStore, VersionStorage, Version } from '@bernierllc/version-store';

// Define your entity type
interface PlanningSession {
  id: string;
  title: string;
  content: string;
  status: string;
}

// Implement storage (example with in-memory storage)
class InMemoryVersionStorage implements VersionStorage<PlanningSession> {
  private versions: Map<string, Version<PlanningSession>[]> = new Map();

  async saveVersion(version: Version<PlanningSession>): Promise<void> {
    const versions = this.versions.get(version.entityId) || [];
    versions.push(version);
    this.versions.set(version.entityId, versions);
  }

  async getVersion(entityId: string, versionNumber: number): Promise<Version<PlanningSession> | null> {
    const versions = this.versions.get(entityId) || [];
    return versions.find(v => v.versionNumber === versionNumber) || null;
  }

  async getVersions(entityId: string): Promise<Version<PlanningSession>[]> {
    return this.versions.get(entityId) || [];
  }

  async getLatestVersion(entityId: string): Promise<Version<PlanningSession> | null> {
    const versions = this.versions.get(entityId) || [];
    return versions[versions.length - 1] || null;
  }

  async getVersionCount(entityId: string): Promise<number> {
    return (this.versions.get(entityId) || []).length;
  }
}

// Create version store
const storage = new InMemoryVersionStorage();
const versionStore = new VersionStore<PlanningSession>({
  entityType: 'planning_session',
  storage,
  trackChangedFields: true,
});

// Create first version
const session: PlanningSession = {
  id: 'session-1',
  title: 'Q1 Planning',
  content: 'Initial planning session content...',
  status: 'active',
};

await versionStore.createVersion('session-1', session, {
  changeSummary: 'Initial version',
  changedBy: '[email protected]',
});

// Update and create second version
const updatedSession = {
  ...session,
  title: 'Q1 2025 Planning',
  status: 'in_progress',
};

await versionStore.createVersion('session-1', updatedSession, {
  changeSummary: 'Updated title and status',
  changedBy: '[email protected]',
});

Get Version History

// Get all versions
const history = await versionStore.getVersionHistory('session-1');
console.log(`Total versions: ${history.length}`);

history.forEach(version => {
  console.log(`v${version.versionNumber}: ${version.changeSummary}`);
  console.log(`  Changed fields: ${version.changedFields?.join(', ')}`);
  console.log(`  By: ${version.changedBy}`);
  console.log(`  At: ${version.createdAt}`);
});

// Get specific version
const v1 = await versionStore.getVersion('session-1', 1);
console.log('Version 1 snapshot:', v1?.snapshot);

// Get latest version
const latest = await versionStore.getLatestVersion('session-1');
console.log('Latest version:', latest?.versionNumber);

Generate Diffs

// Compare two versions
const diff = await versionStore.diff('session-1', 1, 2);

if (diff) {
  console.log('Added fields:', diff.added);
  console.log('Removed fields:', diff.removed);
  console.log('Changed fields:');
  Object.entries(diff.changed).forEach(([field, change]) => {
    console.log(`  ${field}: "${change.from}" → "${change.to}"`);
  });

  // Example output:
  // Changed fields:
  //   title: "Q1 Planning" → "Q1 2025 Planning"
  //   status: "active" → "in_progress"
}

// Get just changed field names
const changedFields = await versionStore.getChangedFields('session-1', 1, 2);
console.log('Changed:', changedFields); // ['title', 'status']

Rollback to Previous Version

// Rollback to version 1
const rollbackResult = await versionStore.rollback('session-1', 1, {
  changeSummary: 'Rolled back to initial version',
  changedBy: '[email protected]',
  metadata: {
    rollbackReason: 'Reverted incorrect changes',
  },
});

if (rollbackResult.success) {
  console.log('Rolled back to version 1');
  console.log('New version created:', rollbackResult.version?.versionNumber);

  // Verify rollback
  const latest = await versionStore.getLatestVersion('session-1');
  console.log('Current state:', latest?.snapshot);
  // Current state matches version 1 snapshot
}

Custom Field Comparison

// Custom comparison for date fields
const versionStore = new VersionStore<PlanningSession>({
  entityType: 'planning_session',
  storage,
  compareFields: (oldVal, newVal) => {
    // Treat dates within 1 second as equal
    if (oldVal instanceof Date && newVal instanceof Date) {
      return Math.abs(oldVal.getTime() - newVal.getTime()) < 1000;
    }
    return oldVal === newVal;
  },
});

Ignore Fields in Diff

// Ignore timestamp fields in diff
const diff = await versionStore.diff('session-1', 1, 2, {
  ignoreFields: ['updatedAt', 'createdAt', 'version'],
  maxDepth: 5,
});

// Only compares meaningful fields
console.log('Changed fields:', diff?.changedFields);
// ['title', 'status'] (timestamps ignored)

API Reference

VersionStore

Main class for version tracking.

Constructor

constructor(config: VersionStoreConfig)

Config Options:

  • entityType: string - Entity type identifier (e.g., 'planning_session')
  • storage: VersionStorage<T> - Storage implementation
  • trackChangedFields?: boolean - Auto-track changed fields (default: true)
  • compareFields?: (oldValue: any, newValue: any) => boolean - Custom field comparison

Methods

createVersion()
async createVersion(
  entityId: string,
  snapshot: T,
  options?: CreateVersionOptions
): Promise<VersionResult<T>>

Create a new version of an entity.

Parameters:

  • entityId - Entity identifier
  • snapshot - Complete entity state
  • options - Version creation options
    • changeSummary?: string - Summary of changes
    • changedBy?: string - User identifier
    • changedFields?: string[] - Changed field names (auto-detected if not provided)
    • metadata?: Record<string, any> - Additional metadata

Returns: VersionResult<T> with success status and created version

getVersion()
async getVersion(entityId: string, versionNumber: number): Promise<Version<T> | null>

Get a specific version by version number.

getLatestVersion()
async getLatestVersion(entityId: string): Promise<Version<T> | null>

Get the latest version for an entity.

getVersionHistory()
async getVersionHistory(entityId: string): Promise<Version<T>[]>

Get all versions for an entity, ordered by version number ascending.

diff()
async diff(
  entityId: string,
  fromVersion: number,
  toVersion: number,
  options?: DiffOptions
): Promise<VersionDiff | null>

Generate a diff between two versions.

Options:

  • maxDepth?: number - Maximum depth for nested object comparison (default: 10)
  • ignoreFields?: string[] - Fields to ignore in diff
  • includeUnchanged?: boolean - Include unchanged fields (default: false)
getChangedFields()
async getChangedFields(
  entityId: string,
  fromVersion: number,
  toVersion: number
): Promise<string[]>

Get list of changed field names between two versions.

rollback()
async rollback(
  entityId: string,
  targetVersion: number,
  options?: CreateVersionOptions
): Promise<VersionResult<T>>

Rollback to a previous version (creates new version with old snapshot).

getVersionCount()
async getVersionCount(entityId: string): Promise<number>

Get the total number of versions for an entity.

getNextVersionNumber()
async getNextVersionNumber(entityId: string): Promise<number>

Get the next version number for an entity (1-indexed).

hasVersions()
async hasVersions(entityId: string): Promise<boolean>

Check if an entity has any versions.

VersionStorage Interface

Storage interface that must be implemented by callers.

interface VersionStorage<T> {
  saveVersion(version: Version<T>): Promise<void>;
  getVersion(entityId: string, versionNumber: number): Promise<Version<T> | null>;
  getVersions(entityId: string): Promise<Version<T>[]>;
  getLatestVersion(entityId: string): Promise<Version<T> | null>;
  getVersionCount(entityId: string): Promise<number>;
}

Version

Represents a single version snapshot.

interface Version<T> {
  id: string;
  entityId: string;
  entityType: string;
  versionNumber: number;
  snapshot: T;
  changeSummary?: string;
  changedFields?: string[];
  changedBy?: string;
  createdAt: Date;
  metadata?: Record<string, any>;
}

VersionDiff

Represents differences between two versions.

interface VersionDiff {
  added: Record<string, any>;
  removed: Record<string, any>;
  changed: Record<string, { from: any; to: any }>;
  changedFields: string[];
  fromVersion: number;
  toVersion: number;
}

Diff Algorithm

The diff algorithm uses structural JSON object comparison:

  1. Field-Level Comparison:

    • Compare all keys in both objects
    • Detect added fields (in new but not old)
    • Detect removed fields (in old but not new)
    • Detect changed fields (value differs between versions)
  2. Value Comparison:

    • Default: JSON.stringify comparison for deep equality
    • Customizable: Provide custom compareFields function
    • Handles primitives, objects, arrays, null/undefined
  3. Algorithm Complexity:

    • Time: O(n) where n is total number of fields across both objects
    • Space: O(n) for diff result storage
    • Suitable for entities with 100s of fields

Rollback Strategy

Non-Destructive Rollback:

  • Never delete or modify existing versions
  • Create new version with old snapshot
  • Preserves complete audit trail

Example:

// Current state: version 5
await versionStore.rollback(entityId, 3);
// Result: version 6 created with snapshot from version 3
// Version history: 1, 2, 3, 4, 5, 6 (6 = copy of 3)

Storage Implementations

This package requires a storage implementation. Examples:

In-Memory Storage (for testing)

class InMemoryVersionStorage<T> implements VersionStorage<T> {
  private versions: Map<string, Version<T>[]> = new Map();
  // ... implement interface methods
}

PostgreSQL Storage (example)

class PostgresVersionStorage<T> implements VersionStorage<T> {
  constructor(private pool: Pool) {}

  async saveVersion(version: Version<T>): Promise<void> {
    await this.pool.query(
      'INSERT INTO versions (id, entity_id, entity_type, version_number, snapshot, ...) VALUES ($1, $2, ...)',
      [version.id, version.entityId, ...]
    );
  }
  // ... implement other interface methods
}

Supabase Storage (example)

class SupabaseVersionStorage<T> implements VersionStorage<T> {
  constructor(private supabase: SupabaseClient) {}

  async saveVersion(version: Version<T>): Promise<void> {
    await this.supabase.from('versions').insert({
      id: version.id,
      entity_id: version.entityId,
      ...
    });
  }
  // ... implement other interface methods
}

Integration Status

  • Logger: not-applicable (pure utility, no logging needed)
  • Docs-Suite: ready (full TypeDoc documentation)
  • NeverHub: not-applicable (no service discovery or events)

Testing

The package includes comprehensive test coverage (>90%):

# Run tests
npm test

# Run tests with coverage
npm run test:coverage

# Run tests once (CI mode)
npm run test:run

Use Cases

  • Planning Systems - Track planning session changes
  • Work Item Tracking - Change history for tasks
  • Content Management - Content version history
  • Configuration Management - Config change tracking
  • Document Management - Document versioning
  • Audit Trails - Complete change audit trail
  • Any CRUD Operations - Generic version tracking

MECE Boundary

Includes

  • Version CRUD operations
  • Automatic version numbering
  • Change field tracking
  • Snapshot storage
  • Diff generation
  • Rollback support
  • Version metadata management

Excludes

  • Database storage implementation (caller provides via storage interface)
  • Entity-specific logic (planning sessions, work items, content, etc.)
  • REST API routes
  • UI diff visualization components
  • Authentication/authorization
  • Version pruning/cleanup policies (application concern)
  • Conflict resolution (application concern)

See Also

Packages that use version-store:

License

Copyright (c) 2025 Bernier LLC. All rights reserved.

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.