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

veils-js

v1.0.4

Published

Veil Objects to replace DTOs, reduce boilerplate code, and leverage JavaScript's dynamic nature

Readme

Veils.js

Veil Objects to Replace DTOs, Reduce Boilerplate Code and Leverage JavaScript's Dynamic Nature

EO principles respected here We recommend WebStorm

npm version CI Coverage Zero Dependencies TypeScript Node.js License

Overview • Installation • Usage • Use Cases • Limitations • Contributing

[!TIP] Read this blog post first: Veil Objects to Replace DTOs.

Overview

In object-oriented programming, objects should represent live entities, not just passive data holders (DTOs). The Veils.js library allows you to create smart wrappers around your objects that cache reads until the first write, seamlessly combining the efficiency of a DTO with the elegance of OOP.

Installation

npm install veils-js

Usage

Supported Declarations

You can decorate object properties, getters, and any method declaration format:

const object = {
  property: 'property',
  get getter() {},
  es6Method() {},
  anonymousFunction: function () {},
  nfe: function namedFunctionExpression() {},
  async asyncMethod() {},
};

[!CAUTION] Because Veils.js relies on JavaScript Proxy objects, there are specific limitations regarding frozen properties, built-in objects (such as Map or Date), and class instances with #private elements. Be sure to read the Limitations section for more details.

Basic Veil

import { veil } from 'veils-js';
import type { VeilCache } from 'veils-js';

const john: User = {
  name: 'John',
  hash(): string {
    // Imagine some heavy CPU work here
    return 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855';
  },
};
const cache: VeilCache<User> = { hash: 'cached-hash-value' };
const covering: User = veil(john, cache);

Calling the hash() method instantly returns the 'cached-hash-value' string without executing the method body. This cached value is served until an uncached property (like name) is accessed or a mutation occurs, at which point the veil is "pierced."

You can also use the unpiercable decorator (do not confuse with TypeScript decorators), which will never be pierced: a very good instrument for data memoization but ignoring arguments passed.

Alter Output

The alterOut decorator lets you modify the output of object methods on the fly:

import { alterOut } from 'veils-js';
import type { ShiftsOut } from 'veils-js';

const john: User = { name: 'John' };
const shifts: ShiftsOut<User> = {
  name: (original: string): string => original.toUpperCase(),
};
const covering: User = alterOut(john, shifts);

Alter Input

The alterIn decorator modifies incoming method arguments before they reach the target object. The result of your transformer function replaces the original arguments:

import { alterIn } from 'veils-js';
import type { ShiftsIn } from 'veils-js';

const dude: User = {
  greet: (phrase: string, name: string): void => {
    console.log(`${phrase}, ${name}!`);
  },
};
const shifts: ShiftsIn<User> = {
  greet: (phrase: string, name: string) => [phrase.trim(), name.toUpperCase()],
};
const covering: User = alterIn(dude, shifts);

Use Case: SQL-Speaking Objects

Imagine a Project object that fetches its properties directly from a PostgreSQL database:

const project = (database: Database, identifier: number): Project => ({
  name: async (): Promise<string> => {
    const { rows } = await database.query('SELECT name FROM projects WHERE id = $1', [identifier]);
    return rows[0].name;
  },
});

This design is elegant for single-object manipulations. However, if you execute SELECT * FROM projects and map the results to Project instances, calling .name() on each will generate redundant database requests for data you already fetched (the N+1 query problem).

Instead of degrading your class into a dumb DTO, use an unpiercable veil:

import { unpiercable } from 'veils-js';

const projects = () => ({
  fetch: async (database: Database): Promise<Project[]> => {
    const { rows } = await database.query('SELECT * FROM projects');
    return rows.map((row) =>
      unpiercable(
        project(database, row.id),
        // Pre-calculate methods with the data we already hold in memory
        { name: Promise.resolve(row.name) },
      ),
    );
  },
});

Now you have real, smart objects. When project.name() is called, it instantly returns the cached promise without hitting the database.

Creating Custom Veil Decorators

In fact, veil and unpiercable are just high-level factory functions. They both use the cloak function under the hood. This function serves as the foundation for creating custom veil decorators.

It intercepts property and method access, querying the provided policy's verdict method to determine whether to serve pre-calculated values from the cache or delegate to the original object. This mechanism implements the strategy pattern. Any property mutations notify the policy via its onMutate method before modifying the target object.

For instance, you can create an immutableVeil that serves values from the cache but strictly forbids any object mutations while the veil is active.

import { cloak } from 'veils-js';
import type { Policy, VeilCache } from 'veils-js';

export const immutablePolicy = (): Policy => ({
  verdict: (_property: string | symbol, isInCache: boolean): boolean => isInCache,
  onMutate: (property: string | symbol): never => {
    // Instead of piercing the veil, we block the mutation entirely
    throw new TypeError(`Mutation of '${String(property)}' is forbidden!`);
  },
});

export const immutableVeil = <T extends object>(object: T, cache: NoInfer<VeilCache<T>>): T =>
  cloak(object, cache, immutablePolicy());

Limitations

Frozen Properties

[!CAUTION] The library relies on JavaScript Proxy objects, which must comply with ECMAScript invariants. A Proxy cannot alter the return value of a property if it is a non-configurable, non-writable own data property (for instance, properties on frozen objects).

To prevent breaking the [[Get]] invariant and causing a TypeError, all decorators will silently ignore cache entries and transformer functions for frozen properties. Accessing them will always yield the original, unaltered value.

import type { ShiftsOut } from 'veils-js';
import { alterOut } from 'veils-js';

const frozen = Object.freeze({ name: 'John' });
const shifts: ShiftsOut<typeof frozen> = {
  name: (original: string): string => original.toUpperCase(),
};

const covering = alterOut(frozen, shifts);

// The transformer is silently ignored to comply with Proxy invariants
covering.name; // 'John'

Built-in Objects and Internal Slots

[!CAUTION] The Veils.js library uses Proxy to wrap your objects. In ECMAScript, Proxy objects do not forward internal slots (like [[MapData]], [[DateValue]], or [[PromiseState]]). As a result, you cannot use these decorators directly on most built-in objects (such as Map, Set, Date, or Promise).

When a method of a built-in object is executed via a Veil proxy, the receiver (this context) is the Proxy itself, which lacks the required internal slot, throwing a TypeError:

import { veil } from 'veils-js';

const map = new Map();
const covering = veil(map, { size: 10 });

// TypeError: Method Map.prototype.set called on incompatible receiver
covering.set('a', 1);

Private Elements

[!CAUTION] All decorators are "deep", which means that internal method or property accesses are intercepted if there is a corresponding cache entry or transformer function. Due to Proxy limitations, you cannot use these decorators on class instances if their methods access native #private fields or methods.

import { alterOut } from 'veils-js';
import type { ShiftsOut } from 'veils-js';

class User {
  #name: string;

  constructor(name: string) {
    this.#name = name;
  }

  greeting(): string {
    return `Hello, ${this.#name}!`;
  }
}

const john = new User('John');
const shifts: ShiftsOut<User> = {
  greeting: (original: string): string => original.toUpperCase(),
};
const covering: User = alterOut(john, shifts);

// Calling ANY method from the proxy that accesses a `#private` field will throw
covering.greeting(); // TypeError: Cannot read private member #name

If possible, use alternatives such as TypeScript compile-time member visibility or closure-based encapsulation (see, for example, our veilPolicy implementation). The following works as expected:

import { alterOut } from 'veils-js';
import type { ShiftsOut } from 'veils-js';

class User {
  // Uses TS `private` modifier instead of native `#`
  constructor(private readonly name: string) {}

  greeting(): string {
    return `Hello, ${this.name}!`;
  }
}

const john = new User('John');
const shifts: ShiftsOut<User> = {
  greeting: (original: string): string => original.toUpperCase(),
};
const covering: User = alterOut(john, shifts);
covering.greeting(); // 'HELLO, JOHN!'

Even better (using plain old JavaScript objects and closures):

import { alterOut } from 'veils-js';
import type { ShiftsOut } from 'veils-js';

const user = (name: string): User => ({
  greeting: (): string => `Hello, ${name}!`,
});

const john: User = user('John');
const shifts: ShiftsOut<User> = {
  greeting: (original: string): string => original.toUpperCase(),
};
const covering: User = alterOut(john, shifts);
covering.greeting(); // 'HELLO, JOHN!'