@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-storeFeatures
- 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 implementationtrackChangedFields?: 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 identifiersnapshot- Complete entity stateoptions- Version creation optionschangeSummary?: string- Summary of changeschangedBy?: string- User identifierchangedFields?: 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 diffincludeUnchanged?: 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:
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)
Value Comparison:
- Default: JSON.stringify comparison for deep equality
- Customizable: Provide custom
compareFieldsfunction - Handles primitives, objects, arrays, null/undefined
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:runUse 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:
- @bernierllc/planning-session-core - Planning session versioning
- @bernierllc/work-item-core - Work item change tracking
- @bernierllc/content-versions-service - Content version management
- @bernierllc/refactoring-core - Audit trail support
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.
