nucleus-mold
v1.0.3
Published
```typescript import { Nucleus } from './json-mold'; @Nucleus({ as: 'System.Wallet' }) export class Wallet { public balance: number = 0;
Readme
nucleus-mold
A lightweight and efficient utility for serialization and polymorphic deserialization of complex objects in TypeScript 5.0+
💻 Usage Example
1. Define Your Models
import { Nucleus } from './json-mold';
@Nucleus({ as: 'System.Wallet' })
export class Wallet {
public balance: number = 0;
// Private constructor is supported!
private constructor(balance: number) {
this.balance = balance;
}
public static create(balance: number) {
return new Wallet(balance);
}
public deposit(amount: number) {
this.balance += amount;
}
}
@Nucleus({ as: 'System.User' })
export class User {
constructor(
public id: string,
public name: string,
public wallet: Wallet // Nested @Nucleus object
) {}
public greet() {
return `Hello, I'm ${this.name}. Balance: ${this.wallet.balance}$`;
}
}2. Serialize and Deserialize
import { JsonMold, isSerializable } from './json-mold';
import { User, Wallet } from './models';
const wallet = Wallet.create(250);
const user = new User("usr_100", "Alex", wallet);
console.log(isSerializable(user)); // true
// --- CONCEAL (Serialize) ---
const jsonStr = JsonMold.conceal(user);
console.log(jsonStr);
/*
Output:
{
"__type": "System.User",
"id": "usr_100",
"name": "Alex",
"wallet": {
"__type": "System.Wallet",
"balance": 250
}
}
*/
// --- REVEAL (Deserialize) ---
const restoredUser = JsonMold.reveal<User>(jsonStr);
// It recovers the exact prototype chains without invoking constructors
console.log(restoredUser instanceof User); // true
console.log(restoredUser.wallet instanceof Wallet); // true
// Methods and 'this' context are fully functional
restoredUser.wallet.deposit(50);
console.log(restoredUser.greet()); // "Hello, I'm Alex. Balance: 300$"🛠️ API Reference
@Nucleus(options?: { as?: string })
A class decorator that registers the target class in the registry and injects the toJSON method.
options.as(optional): A unique string identifier to prevent name collisions across different modules.
JsonMold.conceal(obj: any, space?: number): string
Converts a domain object into a JSON string. Automatically attaches the __type meta key to any nested @Nucleus instances.
JsonMold.reveal<T = any>(json: string): T
Parses a JSON string and recursively rebuilds instances of registered classes by their __type token using Object.create.
isSerializable(obj: any): boolean
A helper function that returns true if the passed object comes from a class decorated with @Nucleus.
