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

open-feature-flags

v0.0.6-beta

Published

Feature flags library with custom providers and strategies

Readme

open-feature-flags

open-feature-flags es una librería modular desarrollada en TypeScript para gestionar feature flags. Su estructura sigue los principios de Clean Architecture, lo que garantiza la separación de responsabilidades y una fácil escalabilidad y mantenimiento. La librería permite habilitar o deshabilitar características de manera dinámica en una aplicación, mediante diferentes estrategias que pueden ser implementadas por el usuario final.

Características principales

  • Modularidad: Cada componente de la librería es fácilmente extensible.
  • Estrategias Personalizadas: Implementa tus propias estrategias para habilitar o deshabilitar feature flags.
  • Providers Flexibles: Puedes definir cómo y desde dónde cargar los feature flags (por ejemplo, desde variables de entorno, bases de datos, etc.).
  • Aplicación de Clean Architecture: La lógica de negocio está desacoplada de las implementaciones, permitiendo un mantenimiento más sencillo y la posibilidad de agregar nuevas funcionalidades sin romper el código existente.

Estructura de Carpetas

La estructura sigue Clean Architecture, organizando el proyecto en capas claras:

src/
├── application/
│   ├── services/
│   │   └── feature-flag-manager.service.ts
├── domain/
│   ├── entities/
│   │   └── feature-flag.entity.ts
│   ├── repositories/
│   │   ├── provider.repository.ts
│   │   └── strategy.repository.ts
│   └── providers/
│       └── provider.interface.ts
│   └── strategies/
│       ├── feature-flag.strategy.ts
├── infrastructure/
│   ├── persistence/
│   │   ├── provider.repository-impl.ts
│   │   └── strategy.repository-impl.ts
│   └── providers/
│       └── custom-provider-impl.ts
└── strategies/
    └── percentage.strategy-impl.ts

Descripción de Carpetas

  • application/: Contiene los casos de uso y servicios como FeatureFlagManagerService.
  • domain/: Define las entidades y contratos (interfaces) que forman parte de la lógica de negocio. Aquí es donde se encuentran las interfaces de los repositorios y estrategias.
  • infrastructure/: Implementaciones concretas de los repositorios y proveedores que interactúan con la infraestructura externa (como bases de datos, APIs, etc.).
  • strategies/: Aquí se implementan estrategias personalizadas, como PercentageStrategyImpl.

Instalación

Instala la librería usando npm o pnpm:

npm install open-feature-flags

o con pnpm:

pnpm add open-feature-flags

Uso

1. Configuración del FeatureFlagManager

Para usar la librería, primero necesitas registrar tus estrategias y providers en el FeatureFlagManagerService:

import { FeatureFlagManagerService } from './application/services/feature-flag-manager.service';
import { ProviderRepositoryImpl } from './infrastructure/persistence/provider.repository-impl';
import { StrategyRepositoryImpl } from './infrastructure/persistence/strategy.repository-impl';
import { CustomProviderImpl } from './infrastructure/providers/custom-provider-impl';
import { PercentageStrategyImpl } from './infrastructure/strategies/percentage.strategy-impl';

// Inicializamos los repositorios
const providerRepository = new ProviderRepositoryImpl();
const strategyRepository = new StrategyRepositoryImpl();

// Registramos los providers
providerRepository.registerProvider('custom', new CustomProviderImpl());

// Registramos las estrategias
strategyRepository.registerStrategy('percentage', new PercentageStrategyImpl());

// Inicializamos el FeatureFlagManagerService
const featureFlagManagerService = new FeatureFlagManagerService(providerRepository, strategyRepository);

2. Verificar si un feature está habilitado

Una vez configurado, puedes usar el FeatureFlagManagerService para verificar si una característica está habilitada:

const context = { userId: 12345 };
const isEnabled = await featureFlagManagerService.isFeatureEnabled('custom', 'new-ui', context, [50]);
console.log(`¿La nueva UI está habilitada para el usuario 12345? ${isEnabled}`);

3. Crear tu propia estrategia

Puedes crear tus propias estrategias implementando la interfaz FeatureFlagStrategy:

import { FeatureFlagStrategy } from '../domain/strategies/feature-flag.strategy';

export class CustomStrategyImpl implements FeatureFlagStrategy {
  isEnabled(context: unknown): boolean {
    // Lógica personalizada
    return true; // habilita siempre
  }
}

Luego registra esta estrategia en el StrategyRepository:

strategyRepository.registerStrategy('custom', new CustomStrategyImpl());

Pruebas

Para ejecutar las pruebas, simplemente utiliza Jest u otro framework de pruebas. Por ejemplo:

npm run test

Las pruebas se organizan de la misma manera que el código fuente, y están ubicadas en la carpeta tests/:

tests/
├── domain/
│   ├── providers/
│   │   └── provider.interface.test.ts
│   └── strategies/
│       └── percentage.strategy.test.ts
├── infrastructure/
│   ├── providers/
│   │   └── custom-provider-impl.test.ts
│   └── persistence/
│       ├── provider.repository-impl.test.ts
│       └── strategy.repository-impl.test.ts
└── application/
    └── services/
        └── feature-flag-manager.service.test.ts

Contribuciones

Contribuciones, issues y solicitudes de nuevas características son bienvenidas. Si deseas contribuir:

  1. Haz un fork del repositorio.
  2. Crea una nueva rama para tu feature (git checkout -b feature/nueva-feature).
  3. Haz commit de tus cambios (git commit -m 'Agrega nueva feature').
  4. Haz push a tu rama (git push origin feature/nueva-feature).
  5. Crea un pull request.

Licencia

Este proyecto está licenciado bajo la MIT License.