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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@anatix/runtime

v1.0.8

Published

Runtime infrastructure for Anatix-generated microservices

Downloads

1,126

Readme

@anatix/runtime

Runtime infrastructure pour applications générées par Anatix

npm version License: MIT

📦 Installation

npm install @anatix/runtime

🎯 Vue d'ensemble

@anatix/runtime fournit l'infrastructure nécessaire aux applications générées par Anatix, incluant :

  • 🛡️ Guards : Authentification JWT et autorisation RBAC
  • 📨 Envelope : Pattern Inbox/Outbox pour événements fiables
  • 🚀 Event-Bus : Bus d'événements avec RabbitMQ
  • 📝 Logger : Logging structuré
  • 🔄 Proxy : Appels HTTP avec retry automatique
  • 🔐 Security : Hashing de mots de passe
  • 🗄️ Naming : Stratégie de nommage TypeORM
  • ⚙️ Configs : Types pour repositories et services
  • 🛠️ Utils : Utilitaires divers (dates, filtres)

📚 Modules

Guards

Authentification et autorisation pour NestJS.

import { JwtAuthGuard, PermissionsGuard, Permissions } from '@anatix/runtime/guards';

@Controller('users')
@UseGuards(JwtAuthGuard, PermissionsGuard)
export class UsersController {
  @Get()
  @Permissions('users:User:list')
  async list() {
    // Accessible uniquement avec la permission
  }
}

Envelope

Pattern Inbox/Outbox pour événements fiables et idempotents.

import { withInboxOutbox, OutboxRepo, ensureMeta } from '@anatix/runtime/envelope';

await withInboxOutbox(
  dataSource,
  'user.created',
  meta,
  payload,
  async (manager) => {
    // Logique métier dans transaction
    const user = await manager.save(User, payload);
    return user;
  },
  async (manager) => {
    // Publier d'autres événements après commit
    await OutboxRepo.enqueue(manager, {
      topic: 'user.welcomed',
      payload: { userId: user.id },
      meta: ensureMeta(),
    });
  }
);

Event-Bus

Bus d'événements avec RabbitMQ.

import { EventBusService } from '@anatix/runtime/event-bus';

@Injectable()
export class UserService {
  constructor(private eventBus: EventBusService) {}

  async createUser(dto: CreateUserDto) {
    const user = await this.repo.save(dto);
    
    // Publier un événement
    await this.eventBus.publish('user.created', {
      userId: user.id,
      email: user.email,
    });
    
    return user;
  }
}

// Souscrire à un événement
await eventBus.on('user.created', async (envelope, ctx) => {
  console.log('New user:', envelope.data);
});

Logger

Logging structuré avec helper pratique.

import { LogHelper, LogPort } from '@anatix/runtime/logger';

@Injectable()
export class UserService {
  private readonly logger: LogHelper;

  constructor(logPort: LogPort) {
    this.logger = new LogHelper(logPort, 'users');
  }

  async createUser(dto: CreateUserDto) {
    this.logger.info('Creating user', { email: dto.email });
    
    try {
      const user = await this.repo.save(dto);
      this.logger.info('User created', { userId: user.id });
      return user;
    } catch (error) {
      await this.logger.critical('user creation', { dto }, error);
    }
  }
}

Proxy

Appels HTTP avec retry et timeout.

import { proxyGet, proxyPost } from '@anatix/runtime/proxy';

@Injectable()
export class PaymentService {
  constructor(private http: HttpService) {}

  async createPayment(dto: CreatePaymentDto) {
    return proxyPost(
      this.http,
      `${PAYMENT_SERVICE_URL}/payments`,
      dto,
      { timeout: 10000, retryAttempts: 3 }
    );
  }
}

Security

Hashing de mots de passe.

import { HashingAdapter, BcryptAdapter, HASHING_ADAPTER } from '@anatix/runtime/security';

// Configuration du module
{
  provide: HASHING_ADAPTER,
  useClass: BcryptAdapter,
}

// Utilisation
@Injectable()
export class AuthService {
  constructor(
    @Inject(HASHING_ADAPTER) private hasher: HashingAdapter
  ) {}

  async register(dto: RegisterDto) {
    const hashedPassword = await this.hasher.hash(dto.password);
    return this.userRepo.create({ ...dto, password: hashedPassword });
  }
}

Naming

Stratégie de nommage TypeORM (snake_case).

import { AnatixNamingStrategy } from '@anatix/runtime/naming';

const dataSource = new DataSource({
  type: 'postgres',
  namingStrategy: new AnatixNamingStrategy(),
  entities: [...],
});

Configs

Types pour repositories et services.

import { ServiceListOptions, ServiceQueryOptions } from '@anatix/runtime/configs';

@Controller('users')
export class UsersController {
  @Get()
  async list(@Query() options: ServiceListOptions) {
    return this.userService.list(options);
  }

  @Get('search')
  async search(@Query() options: ServiceQueryOptions) {
    return this.userService.search(options);
  }
}

Utils

Utilitaires pour dates et filtres.

import { 
  toISOStringSafe, 
  toDateOnlyString,
  parseFilterFields,
  type FilterFieldDefs 
} from '@anatix/runtime/utils';

// Conversion de dates
const iso = toISOStringSafe(new Date()); // '2024-01-15T00:00:00.000Z'
const dateOnly = toDateOnlyString(new Date()); // '2024-01-15'

// Parsing de filtres
const defs: FilterFieldDefs = {
  date: ['createdAt'],
  number: ['age'],
  boolean: ['isActive'],
  enum: ['status'],
  enumValues: { status: ['PENDING', 'ACTIVE'] },
};

const filters = parseFilterFields(queryParams, defs);

Decorators

Filtre d'exception global.

import { GlobalExceptionFilter } from '@anatix/runtime/decorators';

// Dans main.ts
const app = await NestFactory.create(AppModule);
app.useGlobalFilters(new GlobalExceptionFilter());

🔧 Configuration

Variables d'environnement

RabbitMQ (Event-Bus)

RABBITMQ_URL=amqp://localhost
EVENT_BUS_EXCHANGE=anatix-event-bus
EVENT_BUS_QUEUE=default-queue

JWT (Guards)

AUTH_JWT_ALGORITHM=HS256
AUTH_JWT_SECRET=your-secret
AUTH_JWT_PUBLIC_KEY=your-public-key
AUTH_JWT_ISSUER=your-issuer
AUTH_JWT_AUDIENCE=your-audience

Proxy

PROXY_TIMEOUT_MS=5000
PROXY_RETRY_ATTEMPTS=2

Hashing

BCRYPT_ROUNDS=12

Logging

NODE_ENV=development
LOG_ERRORS=true

📖 Documentation

Documentation complète disponible dans le code source (JSDoc/TSDoc).

🤝 Contribution

Ce package est maintenu par l'équipe Anatix. Les contributions externes ne sont pas acceptées pour le moment.

📄 License

MIT © Anatix Team

🔗 Liens


---

## 🎉 C'est Terminé !

### ✅ Récapitulatif Complet de @anatix/runtime

On a créé **10 modules** production-ready :

1. ✅ **Guards** - Authentification JWT + RBAC générique
2. ✅ **Envelope** - Inbox/Outbox pattern avec idempotence
3. ✅ **Event-Bus** - RabbitMQ avec publish/subscribe/RPC
4. ✅ **Logger** - Logging structuré avec helper
5. ✅ **Proxy** - HTTP avec retry et timeout
6. ✅ **Security** - Hashing abstrait + implémentation Bcrypt
7. ✅ **Decorators** - Exception filter global
8. ✅ **Utils** - Date helpers + filter parsing
9. ✅ **Naming** - TypeORM naming strategy (snake_case)
10. ✅ **Configs** - Types pour repo/service

### 📦 Structure Finale

@anatix/runtime/ ├── src/ │ ├── guards/ │ ├── envelope/ │ ├── event-bus/ │ ├── logger/ │ ├── proxy/ │ ├── security/ │ ├── naming/ │ ├── configs/ │ ├── utils/ │ ├── decorators/ │ └── index.ts ├── package.json ├── tsconfig.json ├── tsconfig.build.json └── README.md