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

@swoft/party-manager

v0.3.6

Published

## 🎯 Overview

Readme

Party Manager Domain Package

🎯 Overview

Enterprise-grade TypeScript package for party (person, organization, team) management following Domain-Driven Design principles. This package provides authentication, user management, and organizational structure capabilities with production-ready error handling, logging, and monitoring.

✨ Features

  • Authentication & Authorization: Secure login, session management, password recovery
  • Person Management: User profiles, contact information, organizational associations
  • Organization Management: Company structures, hierarchies, departments
  • Team Management: Team creation, member management, leadership assignment
  • Production-Ready: Comprehensive error handling, structured logging, health checks
  • Event-Driven: Real event bus with pub/sub for domain events
  • Type-Safe: Full TypeScript with strict type checking

πŸ“¦ Installation

# From local Verdaccio registry
pnpm add @swoft/party-manager

# Or with npm
npm install @swoft/party-manager

πŸš€ Quick Start

import { ServiceFactory, DomainEventBuilder } from '@swoft/party-manager';

// Initialize the service factory
const factory = ServiceFactory.getInstance();
await factory.initialize();

// Get EventBus (the working component)
const eventBus = factory.getEventBus();

// Subscribe to domain events
eventBus.subscribe('UserAction', async (event) => {
  console.log('Event:', event.eventType, 'for', event.aggregateId);
});

// Publish events
await eventBus.publish(
  DomainEventBuilder.create('UserAction', 'user-123', {
    action: 'login',
    timestamp: new Date()
  })
);

// Health check
const health = await factory.getHealthStatus();
console.log('System healthy:', health.healthy);
console.log('Database:', health.database);

// Graceful shutdown
await factory.shutdown();

πŸ—οΈ Architecture

This package follows Domain-Driven Design (DDD) principles with clean architecture:

src/
β”œβ”€β”€ bounded-contexts/          # Domain boundaries
β”‚   β”œβ”€β”€ authentication/        # Login, sessions, passwords
β”‚   β”‚   β”œβ”€β”€ domain/           # Aggregates, value objects
β”‚   β”‚   └── application/      # Use case services
β”‚   └── parties/              # People, orgs, teams
β”‚       β”œβ”€β”€ domain/           # Rich domain models
β”‚       └── application/      # Business operations
β”œβ”€β”€ infrastructure/           # Technical implementations
β”‚   β”œβ”€β”€ factory/             # Simple service factory (no DI)
β”‚   β”œβ”€β”€ repositories/        # MongoDB implementations
β”‚   β”œβ”€β”€ events/             # Event bus implementation
β”‚   β”œβ”€β”€ logging/            # Structured logging
β”‚   β”œβ”€β”€ errors/             # Error types & handling
β”‚   └── health/             # Health monitoring
└── config/                  # Environment configuration

πŸ”§ Configuration

Environment Variables

# MongoDB Configuration
PARTY_MANAGER_MONGO_URL=mongodb://localhost:27017
PARTY_MANAGER_DB_NAME=party_manager
MONGO_MAX_POOL_SIZE=10
MONGO_MIN_POOL_SIZE=2

# Logging
LOG_LEVEL=info  # error | warn | info | debug
LOG_FORMAT=json  # json | text

# Health Checks
HEALTH_CHECK_ENABLED=true
HEALTH_CHECK_PATH=/health

# Metrics (optional)
METRICS_ENABLED=false
METRICS_PATH=/metrics

Programmatic Configuration

import { getConfig } from '@swoft/party-manager';

const config = getConfig();
// Returns typed configuration object

πŸ“š API Documentation

ServiceFactory

The main entry point for all services:

const factory = ServiceFactory.getInstance();

// Initialize (required once)
await factory.initialize();

// Get services
factory.getAuthenticationService()
factory.getRegistrationService()
factory.getPasswordService()
factory.getPersonRepository()
factory.getOrganisationRepository()
factory.getTeamRepository()
factory.getEventBus()

// Health monitoring
await factory.getHealthStatus()

// Cleanup
await factory.shutdown()

Authentication Service

interface LoginCommand {
  email: string;
  password: string;
  rememberMe: boolean;
  ipAddress?: string;
  userAgent?: string;
}

const result = await authService.login(command);
await authService.logout(sessionId);
await authService.validateSession(sessionId);

Event Bus

Production-ready event system with pub/sub:

// Subscribe to events
const subscription = eventBus.subscribe('UserLoggedIn', async (event) => {
  // Handle event
});

// Unsubscribe
subscription.unsubscribe();

// Subscribe to all events
eventBus.subscribeToAll(async (event) => {
  console.log('Event:', event.eventType);
});

// Get statistics
const stats = eventBus.getStats();

Error Handling

Comprehensive error types with HTTP status codes:

import { 
  InvalidCredentialsError,
  AccountLockedError,
  PersonNotFoundError,
  DatabaseError,
  ErrorHandler 
} from '@swoft/party-manager';

try {
  await authService.login(command);
} catch (error) {
  if (error instanceof InvalidCredentialsError) {
    // Handle invalid credentials (401)
  } else if (error instanceof AccountLockedError) {
    // Handle locked account (403)
  }
  
  // Get HTTP status code
  const statusCode = ErrorHandler.getHttpStatusCode(error);
  
  // Format for API response
  const response = ErrorHandler.formatErrorResponse(error);
}

Logging

Structured logging with correlation IDs:

import { Logger, LogLevel } from '@swoft/party-manager';

const logger = Logger.getInstance();

// Log with context
logger.info('Operation completed', {
  userId: '123',
  correlationId: 'abc-def',
  duration: 150
});

// Create child logger with fixed context
const serviceLogger = logger.child({ service: 'AuthService' });
serviceLogger.error('Authentication failed', error);

πŸ§ͺ Testing

# Run tests
pnpm test

# With coverage
pnpm test:coverage

# Watch mode
pnpm test:watch

πŸ“Š Bundle Size Limits

The package enforces strict size limits to prevent bloat:

  • Main API Bundle: < 80 KB
  • ESM Bundle: < 65 KB
  • Contracts Bundle: < 35 KB
  • Contracts ESM: < 25 KB

Check current sizes:

pnpm analyze

πŸ› οΈ Development

Building

# Build the package
pnpm build

# Watch mode
pnpm build:watch

# Type checking
pnpm check

Architecture Decisions

This package was refactored using expert panel reviews to achieve enterprise-grade quality:

  1. No Dependency Injection Framework: Simple factory pattern instead of complex DI
  2. Minimal Exports: Only 2 export paths (main + contracts) for clean API
  3. Real Event Bus: Production pub/sub instead of mocks
  4. Comprehensive Error Handling: Typed errors with proper status codes
  5. Structured Logging: JSON/text formats with correlation IDs

See docs/EXPERT-PANEL-METHOD.md for the complete transformation story.

πŸ“ Contracts

For TypeScript API contracts (Zodios):

import { partyManagerApi } from '@swoft/party-manager/contracts';

🀝 Contributing

  1. Follow DDD principles - keep domain logic in aggregates
  2. Maintain clean architecture boundaries
  3. Add tests for new features
  4. Update documentation
  5. Respect size limits

πŸ“„ License

MIT

πŸ† Credits

Refactored to enterprise-grade quality through expert panel methodology featuring insights from:

  • Eric Evans (Domain-Driven Design)
  • Vaughn Vernon (Implementing DDD)
  • Martin Fowler (Enterprise Architecture)
  • Michel Weststrate (MobX, TypeScript)
  • Kamil Mysliwiec (NestJS)
  • Jared Palmer (Turborepo)
  • Ben Awad (Production TypeScript)

Built with ❀️ using Domain-Driven Design principles