@run-js/change-tracker
A powerful, lightweight and fast TypeScript decorator-based library for automatic object change tracking. Monitor property mutations, capture diffs, and maintain change journals for audit logs, debugging, and analytics.
📋 Table of Contents
- ✨ Features
- 📦 Installation
- 🚀 Quick Start
- 📚 API Documentation
- 🔥 Advanced Usage
- 🧬 Inheritance Support
- 💎 TypeScript Support
- 🔍 Supported Equality Comparisons
- ⚙️ Options
- ⚡ Performance & Garbage Collection
- 📊 Benchmark Results
- 🎯 Use Cases
- 🔧 Requirements
- 📄 License Information
- 🌐 About Rudolf Run Ltd
- 🏷️ Keywords
✨ Features
- 🎯 Decorator-based: Simple
@changeTrackingdecorator for seamless integration - 📊 Change Tracking: Automatically track property modifications (set/unset/delete)
- 📝 Change Journal: Complete audit trail with timestamps and old/new values
- 🔄 Rollback Changes: Accept or discard changes with built-in rollback functionality
- 💾 Diff Generation: Get clean diffs of changed properties
- 🔒 TypeScript Native: Full TypeScript support with strong typing
- 🏃♂️ Zero Dependencies: Lightweight with no external dependencies
- 📦 Dual Package Support — Works in both ESM and CommonJS environments (Node.js, Jest, Vite, modern bundlers)
- 🧬 Inheritance Support: Full class hierarchy support — track properties across base and derived classes
- ⚡ High Performance: 100K tracked writes across 1,000 classes in ~250 ms — see benchmarks
- 📦 Tiny Footprint: ~8 KB minified bundle with source maps
- 🧪 Well Tested: Comprehensive test suite with 100% coverage
📦 Installation
npm install @run-js/change-tracker
🔧 Package Compatibility
This package supports both CommonJS and ESM environments through dual package exports:
- 🚀 ESM (Modern): Works with Vite, modern bundlers, and
importstatements - 🏗️ CommonJS (Legacy): Compatible with Node.js, Jest, and
require()statements - 📦 Automatic Detection: The correct format is selected automatically based on your environment
Usage Examples:
// ESM (import) - for modern bundlers, Vite, etc.
import { changeTracking, IChangeTrackingObject } from '@run-js/change-tracker';
// CommonJS (require) - for Node.js, Jest, etc.
const { changeTracking, IChangeTrackingObject } = require('@run-js/change-tracker');
Both approaches provide identical functionality and TypeScript support.
🚀 Quick Start
import { changeTracking, IChangeTrackingObject } from '@run-js/change-tracker';
// Apply the decorator to track specific properties
@changeTracking<User>('name', 'email', 'age')
class User {
name: string;
email: string;
age: number;
id: string; // Not tracked
}
// Create an instance and cast to include tracking methods
const user = new User();
// Make some changes
user.name = 'John Doe';
user.email = 'john@example.com';
user.age = 30;
// Get the changes
console.log((user as IChangeTrackingObject).getChangeDiff());
// Output: { name: 'John Doe', email: 'john@example.com', age: 30 }
// Get the complete change journal
console.log((user as IChangeTrackingObject).getChangeJournal());
// Output: [
// { propertyName: 'name', timestamp: Date, oldValue: undefined, newValue: 'John Doe' },
// { propertyName: 'email', timestamp: Date, oldValue: undefined, newValue: 'john@example.com' },
// { propertyName: 'age', timestamp: Date, oldValue: undefined, newValue: 30 }
// ]
📚 API Documentation
@changeTracking Decorator
The main decorator that enables change tracking for specified properties.
@changeTracking<T>(...propertyNames: (keyof T & string)[]): ClassDecorator
Parameters:
propertyNames: List of property names to track (must be string keys of the class)
Example:
@changeTracking<MyClass>('prop1', 'prop2')
class MyClass {
prop1: string;
prop2: number;
prop3: boolean; // Not tracked
}
IChangeTrackingObject Interface
Objects decorated with @changeTracking implement this interface, providing change tracking methods.
hasChanges()
Returns true if any tracked property differs from the accepted baseline, false otherwise.
user.name = 'John';
console.log(user.hasChanges()); // true
user.acceptChanges();
console.log(user.hasChanges()); // false
getChangeDiff()
Returns an object containing only the properties that have changed from their initial state.
const diff = user.getChangeDiff();
console.log(diff); // { name: 'New Name', age: 25 }
getChangeJournal()
Returns the complete journal of all changes made to tracked properties.
const journal = user.getChangeJournal();
journal.forEach(entry => {
console.log(`${entry.propertyName}: ${entry.oldValue} → ${entry.newValue} at ${entry.timestamp}`);
});
acceptChanges()
Accepts all current changes as the new baseline. Clears the change diff and journal.
user.name = 'John';
console.log(user.getChangeDiff()); // { name: 'John' }
user.acceptChanges();
console.log(user.getChangeDiff()); // {}
console.log(user.getChangeJournal()); // []
discardChanges()
Reverts all changes back to the last accepted state. Clears the change diff and journal.
user.name = 'John';
user.age = 30;
console.log(user.getChangeDiff()); // { name: 'John', age: 30 }
user.discardChanges();
console.log(user.name); // undefined (reverted)
console.log(user.age); // undefined (reverted)
console.log(user.getChangeDiff()); // {}
IChangeTrackingJournalEntry Interface
Represents a single change entry in the journal.
interface IChangeTrackingJournalEntry {
propertyName: string; // Name of the changed property
timestamp: Date; // When the change occurred
oldValue: unknown; // Previous value
newValue: unknown; // New value
}
🔥 Advanced Usage
Multiple Property Changes
@changeTracking<Product>('name', 'price', 'category')
class Product {
name: string;
price: number;
category: string;
description: string; // Not tracked
}
const product = new Product() as Product & IChangeTrackingObject;
// Multiple changes
product.name = 'Laptop';
product.price = 999.99;
product.category = 'Electronics';
product.description = 'A great laptop'; // Not tracked
console.log(product.getChangeDiff());
// { name: 'Laptop', price: 999.99, category: 'Electronics' }
Working with Change States
const user = new User() as User & IChangeTrackingObject;
// Initial setup
user.name = 'Alice';
user.email = 'alice@example.com';
user.acceptChanges(); // Set as baseline
// Make new changes
user.name = 'Alice Smith';
user.age = 28;
console.log(user.getChangeDiff());
// { name: 'Alice Smith', age: 28 }
// Discard recent changes
user.discardChanges();
console.log(user.name); // 'Alice' (reverted to accepted state)
console.log(user.email); // 'alice@example.com' (unchanged)
console.log(user.age); // undefined (reverted)
Property Deletion Tracking
const user = new User() as User & IChangeTrackingObject;
user.name = 'Bob';
user.acceptChanges();
// Delete a property
delete user.name;
console.log(user.getChangeJournal());
// [{ propertyName: 'name', timestamp: Date, oldValue: 'Bob', newValue: undefined }]
Instance Independence
Each instance maintains its own change tracking state:
const user1 = new User() as User & IChangeTrackingObject;
const user2 = new User() as User & IChangeTrackingObject;
user1.name = 'Alice';
user2.name = 'Bob';
console.log(user1.getChangeDiff()); // { name: 'Alice' }
console.log(user2.getChangeDiff()); // { name: 'Bob' }
🧬 Inheritance Support
Change tracking works seamlessly across class hierarchies. Each class in the chain only needs to declare its own tracked properties.
Basic Inheritance
import { changeTracking, IChangeTrackingObject } from '@run-js/change-tracker';
@changeTracking<Animal>('name', 'age')
class Animal {
name: string;
age: number;
}
@changeTracking<Dog>('breed', 'isGoodBoy')
class Dog extends Animal {
breed: string;
isGoodBoy: boolean;
}
const dog = new Dog() as Dog & IChangeTrackingObject;
dog.name = 'Rex';
dog.age = 5;
dog.breed = 'Labrador';
dog.isGoodBoy = true;
console.log(dog.hasChanges()); // true
console.log(dog.getChangeDiff());
// { name: 'Rex', age: 5, breed: 'Labrador', isGoodBoy: true }
dog.acceptChanges();
console.log(dog.hasChanges()); // false
Multi-Level Inheritance
Deep inheritance chains of any depth are supported:
@changeTracking<ServiceDog>('certification')
class ServiceDog extends Dog {
certification: string;
}
const serviceDog = new ServiceDog() as ServiceDog & IChangeTrackingObject;
serviceDog.name = 'Buddy';
serviceDog.breed = 'Golden Retriever';
serviceDog.certification = 'SAR-2026';
console.log(serviceDog.getChangeDiff());
// { name: 'Buddy', breed: 'Golden Retriever', certification: 'SAR-2026' }
Duplicate Properties Are Ignored
If a derived class lists a property that is already tracked by a base class, the duplicate is safely ignored:
// 'name' is already tracked by Animal — listing it again here has no effect
@changeTracking<Cat>('name', 'indoor')
class Cat extends Animal {
indoor: boolean;
}
💎 TypeScript Support
This library is written in TypeScript and provides full type safety:
- Decorator parameters are type-checked against class properties
- Change diff objects maintain proper typing
- Interface implementations are enforced at compile time
// ✅ Type-safe property names
@changeTracking<User>('name', 'email') // OK
// ❌ Compile-time error for invalid property names
@changeTracking<User>('invalidProp') // Error: Argument of type '"invalidProp"' is not assignable...
🔍 Supported Equality Comparisons
When detecting whether a property value has actually changed, the library uses a built-in deep equality check that goes beyond simple === comparison. The following types are supported:
| Type | Comparison Strategy |
|---|---|
Primitives (string, number, boolean, symbol, bigint) |
Strict equality (===) |
null / undefined |
Configurable — can treat null and undefined as equal |
Date |
Compared by timestamp (getTime()) |
RegExp |
Compared by string representation (toString()) |
URL |
Compared by string representation (toString()) |
NaN |
NaN is considered equal to NaN |
Array |
Recursive deep element-by-element comparison |
ArrayBuffer |
Byte-by-byte comparison |
Uint8Array |
Byte-by-byte comparison |
This means that setting a property to a new Date instance with the same timestamp, or a new array with identical contents, will not be recorded as a change.
@changeTracking<Example>('date', 'tags', 'pattern')
class Example {
date: Date;
tags: string[];
pattern: RegExp;
}
const obj = new Example() as Example & IChangeTrackingObject;
obj.date = new Date('2026-01-01');
obj.acceptChanges();
// Same timestamp — no change recorded
obj.date = new Date('2026-01-01');
console.log(obj.getChangeDiff()); // {}
obj.tags = ['a', 'b'];
obj.acceptChanges();
// Same array contents — no change recorded
obj.tags = ['a', 'b'];
console.log(obj.getChangeDiff()); // {}
⚙️ Options
The change tracking manager exposes an options property on ChangeTrackingManager.instance that allows you to configure its behavior.
import { ChangeTrackingManager } from '@run-js/change-tracker';
// Access options via the singleton instance
ChangeTrackingManager.instance.options.treatNullAndUndefinedAsEqual = true;
IChangeTrackingManagerOptions
| Option | Type | Default | Description |
|---|---|---|---|
timestampProvider |
() => Date |
() => new Date() |
Provides the timestamp for change journal entries. Override this to supply a custom clock, e.g. for testing or server-synchronized timestamps. |
treatNullAndUndefinedAsEqual |
boolean |
false |
When true, a change from null to undefined (or vice versa) will not be considered a change. |
preferedNullOrUndefined |
PreferedNullOrUndefinedType |
KeepAsIs |
Controls which value is stored when treatNullAndUndefinedAsEqual is true and a null/undefined value is written. |
Custom timestamp provider example:
import { ChangeTrackingManager } from '@run-js/change-tracker';
// Use a fixed timestamp (useful for testing)
const fixedDate = new Date('2026-01-01');
ChangeTrackingManager.instance.options.timestampProvider = () => fixedDate;
PreferedNullOrUndefinedType Enum
| Value | Behavior |
|---|---|
KeepAsIs |
The written value is kept unchanged. When a property is deleted, the stored value becomes undefined — unless the last known value was null, in which case null is preserved. |
Null |
Any undefined value (including property deletion) is normalized to null. |
Undefined |
Any null value is normalized to undefined. |
Note:
preferedNullOrUndefinedonly takes effect whentreatNullAndUndefinedAsEqualistrue.
Example:
import { changeTracking, ChangeTrackingManager, IChangeTrackingObject } from '@run-js/change-tracker';
// Enable treating null and undefined as equal
ChangeTrackingManager.instance.options.treatNullAndUndefinedAsEqual = true;
@changeTracking<Config>('value')
class Config {
value: string | null | undefined;
}
const config = new Config() as Config & IChangeTrackingObject;
config.value = null;
config.acceptChanges();
// With the option enabled, this is not recorded as a change
config.value = undefined;
console.log(config.getChangeDiff()); // {}
console.log(config.hasChanges()); // false
Normalization example with PreferedNullOrUndefinedType.Null:
import { ChangeTrackingManager, PreferedNullOrUndefinedType } from '@run-js/change-tracker';
ChangeTrackingManager.instance.options.treatNullAndUndefinedAsEqual = true;
ChangeTrackingManager.instance.options.preferedNullOrUndefined = PreferedNullOrUndefinedType.Null;
config.value = undefined;
console.log(config.value); // null — value was normalized
⚡ Performance & Garbage Collection
The library is designed with runtime efficiency and memory safety in mind:
- WeakMap-backed storage — Per-instance change stores are held in a
WeakMap. When an object is no longer referenced by your code, its tracking data becomes eligible for garbage collection automatically. There is no need to manually "dispose" tracked objects. - Prototype-level descriptors — Property getters/setters and tracking methods (
getChangeDiff,hasChanges, etc.) are defined once on the prototype, not on every instance. This keeps per-instance overhead to a minimum. - Lazy initialization — An instance's change store is only created the first time a tracked property is read or written. Simply constructing an object does not allocate tracking data.
- Efficient equality checks — Deep comparisons for
Date,RegExp,URL,Array,ArrayBuffer, andUint8Arrayuse direct indexed access instead of iterators, and short-circuit on the first mismatch. - Zero external dependencies — No additional packages are loaded at runtime.
Tip: If you are tracking very large objects with many properties, keep the tracked property list focused on the fields you actually need to monitor. Un-tracked properties incur zero overhead.
📊 Benchmark Results
Measured with 1,000 registered classes (5 tracked properties each), scaling from 1K to 100K operations on the built package output.
| Operation | 1K (ms) | 100K (ms) | Ratio (ideal 100×) |
|---|---|---|---|
| × 5 property writes | 14 | 265 | 19× |
| × 5 property reads | 3 | 169 | 55× |
hasChanges() |
11 | 710 | 62× |
getChangeDiff() |
8 | 712 | 88× |
getChangeJournal() |
1 | 24 | 20× |
acceptChanges() |
1 | 20 | 19× |
| × 5 writes (post-accept) | 5 | 273 | 60× |
discardChanges() |
2 | 32 | 22× |
Journal stress test (single object, 100K writes): 24 ms to build the journal, < 1 ms to retrieve all 100K entries.
Actual timings will vary by hardware.
🎯 Use Cases
- Audit Logging: Track who changed what and when
- Form State Management: Monitor form field changes and validation
- Undo/Redo Functionality: Implement undo systems with change journals
- Debugging: Track object mutations during development
- Analytics: Monitor user interactions with data
- ORM Integration: Track entity changes before database persistence
🔧 Requirements
- TypeScript 4.0+ (from 2020 or newer)
- Node.js 14+ (from 2020 or newer)
- Decorator support enabled in TypeScript configuration
Make sure your tsconfig.json includes:
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}
📄 License Information
Free for Personal Use - This library is free to use for personal and non-commercial projects.
Commercial License Required - Companies and commercial entities must obtain a commercial license for business use, including internal systems and commercial products.
See LICENSE.md for complete licensing terms. Contact us to obtain a commercial license.
🌐 About Rudolf Run Ltd
We stand for uncompromising commitment to quality.
Our philosophy is that software should meet the highest standards, without cutting corners or sacrificing functionality.
And because we believe in fairness, everyone should have access to the best software, regardless of budget.
- 📍 Larnaca, Cyprus
- 🌐 http://rudolf.run
- 📧 support@run-js.com
🏷️ Keywords
typescript • ts • change-tracking • change-tracker • object-tracking • object-changes • property-tracking • property-changes • rollback • undo • redo • accept • discard • revert • diff • audit-log • decorator • metadata • entity • orm • journal • history • state-management • versioning • mutation-tracking
Made by Rudolf Run Ltd with 🤯🤬😎 fighting JavaScript so you don't have to 😃.
Code and documentation copyright 2026 by Rudolf Run Ltd