open-index/open-npm huggingface dataset:
npm package: @origins-digital/logger
Description: Origins Digital NestJS Logger with Winston
Author: Origins Digital
Latest version: 2.1.4

# @origins-digital/logger

A comprehensive logging package for NestJS applications using Winston.

## Installation

```bash
npm install @origins-digital/logger
```

## Features

- Winston-based logging with JSON formatting
- Request logging middleware
- Configurable log levels
- Environment-specific formatting (local vs production)
- Automatic stack trace inclusion
- Request/response metadata logging
- Sensitive data filtering

## Usage

### Basic Setup

```typescript
import { Module } from '@nestjs/common';
import { LoggerModule } from 'nestjs-winston';
import { LoggerConfig } from '@origins-digital/logger';

@Module({
  imports: [LoggerModule.forRoot(LoggerConfig.instance().loggerOptions())],
})
export class AppModule {}
```

### Using the Logger

```typescript
import { Controller, Get } from '@nestjs/common';
import { Logger } from '@nestjs/common';
import { LoggerMiddleware } from '@origins-digital/logger';

@Controller('example')
export class ExampleController {
  private readonly logger = new Logger(ExampleController.name);

  @Get()
  getExample() {
    this.logger.log('This is an info message');
    this.logger.debug('This is a debug message');
    this.logger.warn('This is a warning message');
    this.logger.error(
      'This is an error message',
      new Error('Something went wrong'),
    );

    return { message: 'Example response' };
  }
}
```

### Request Logging Middleware

```typescript
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { LoggerMiddleware } from '@origins-digital/logger';

@Module({})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(LoggerMiddleware).forRoutes('*');
  }
}
```

## Log Levels

The package supports the following log levels:

- `silly` (5)
- `debug` (4)
- `verbose` (3)
- `info` (2) - Default
- `warn` (1)
- `error` (0)

You can configure the log level using the `LOG_LEVEL` environment variable, either by name or number.

## Log Format

### Production Format

```json
{
  "timestamp": "2024-03-21 10:30:45:123",
  "level": "info",
  "message": "Example message",
  "context": "ExampleController",
  "meta": {
    "key": "value"
  }
}
```

### Local Development Format

```
2024-03-21 10:30:45:123 [ExampleController] info: Example message {"key":"value"}
```

## Request Logging

The middleware automatically logs:

- Request method and URL
- Request headers (excluding sensitive data)
- Request body (excluding sensitive data)
- Response status and timing
- Client information (IP, user agent, etc.)
- Error stack traces (if any)

## Configuration

The logger can be configured through environment variables:

- `LOG_LEVEL`: Set the logging level (default: 'info')
- `APP_ENV`: Set the environment ('local' for colored output, 'production' for JSON)

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.
npm package: @origins-digital/nestjs-concurrency
Description: Concurrency package
Author: Origins Digital
Latest version: 1.1.4

# @origins-digital/nestjs-concurrency

A NestJS module that provides decorators for managing concurrent operations in your NestJS applications.

## Installation

```bash
npm install @origins-digital/nestjs-concurrency
```

## Features

- NestJS decorators for concurrency control
- Automatic lock management
- TTL (Time To Live) configuration for locks
- Context-aware locking
- NestJS integration

## Usage

### Basic Setup

First, import the `ConcurrencyModule` in your NestJS application:

```typescript
import { Module } from '@nestjs/common';
import { ConcurrencyModule } from '@origins-digital/nestjs-concurrency';

@Module({
  imports: [ConcurrencyModule],
})
export class AppModule {}
```

### Using ConcurrencyHandler Decorator

The `@ConcurrencyHandler` decorator ensures that only one instance of a method runs at a time:

```typescript
import { Injectable } from '@nestjs/common';
import { ConcurrencyHandler } from '@origins-digital/nestjs-concurrency';

@Injectable()
export class UserService {
  @ConcurrencyHandler({
    key: ([id]) => `user:${id}`,
    timeoutMs: 30000, // Lock for 30 seconds
    excludeContext: false, // Include context in the lock key
  })
  async updateUser(id: string, data: any) {
    // This will only execute if no other instance is running
    return this.userRepository.update(id, data);
  }
}
```

### Decorator Options

The decorator accepts the following options for fine-tuning concurrency behavior:

```typescript
interface ConcurrencyOptions {
  key?: string | ConcurrencyKeyBuilder; // Lock key pattern or function that generates the key
  timeoutMs?: number | ConcurrencyTtlBuilder; // Time to live in milliseconds for locks
}
```

### Response Format

The decorator returns a promise that resolves to the original method's return value. If the lock cannot be acquired, it will throw a standard JavaScript Error.

## Error Handling

The package uses standard JavaScript Error for error handling in the following scenarios:

- When the timeout is reached
- When invalid options are provided

## Best Practices

1. Always set appropriate timeout values for locks to prevent deadlocks
2. Use meaningful key patterns that include unique identifiers
3. Monitor lock statistics for performance optimization
4. Use the decorator at the service level rather than the controller level
5. Use functions for key generation when you need to access method arguments

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## License

This project is licensed under the MIT License - see the LICENSE file for details.
npm package: @origins-digital/nestjs-firebase-guard
Description: NestJS Firebase Fan Guard package
Author: Origins Digital
Latest version: 3.1.4

# @origins-digital/firebase-fan-guard

A NestJS guard package for Firebase authentication of fan users.

> **Zod compatibility**: Environment/config schemas used by this package are compatible with **Zod v4.x**.

## Installation

```bash
npm install @origins-digital/firebase-fan-guard
```

## Features

- Firebase token verification for fan authentication
- Optional authentication support
- Automatic public key caching
- Fan payload extraction decorator
- Swagger integration

## Usage

### Basic Setup

```typescript
import { Module } from '@nestjs/common';
import { FirebaseFanGuardModule } from '@origins-digital/firebase-fan-guard';

@Module({
  imports: [
    FirebaseFanGuardModule.forRoot({
      publicKeyEndpoint: process.env.FIREBASE_PUBLIC_KEY_ENDPOINT,
    }),
  ],
})
export class AppModule {}
```

### Controller Usage

```typescript
import { Controller, Get } from '@nestjs/common';
import {
  AuthFirebaseFanGuard,
  FanPayloadParam,
} from '@origins-digital/firebase-fan-guard';
import { DecodedIdToken } from '@origins-digital/firebase-fan-guard';

@Controller('fan')
@AuthFirebaseFanGuard()
export class FanController {
  @Get('profile')
  getProfile(@FanPayloadParam() fanPayload: DecodedIdToken) {
    return {
      email: fanPayload.email,
      name: fanPayload.name,
      // ... other fan data
    };
  }
}
```

### Optional Authentication

```typescript
import { Controller, Get } from '@nestjs/common';
import {
  OptionalAuthFirebaseFanGuard,
  FanPayloadParam,
} from '@origins-digital/firebase-fan-guard';
import { DecodedIdToken } from '@origins-digital/firebase-fan-guard';

@Controller('fan')
@OptionalAuthFirebaseFanGuard()
export class FanController {
  @Get('profile')
  getProfile(@FanPayloadParam() fanPayload?: DecodedIdToken) {
    if (fanPayload) {
      return {
        email: fanPayload.email,
        name: fanPayload.name,
        // ... authenticated fan data
      };
    }
    return {
      // ... public fan data
    };
  }
}
```

### Swagger Integration

```typescript
import { Controller, Get } from '@nestjs/common';
import {
  ApiAuthFirebaseFanGuard,
  FanPayloadParam,
} from '@origins-digital/firebase-fan-guard';
import { DecodedIdToken } from '@origins-digital/firebase-fan-guard';

@Controller('fan')
@ApiAuthFirebaseFanGuard()
export class FanController {
  @Get('profile')
  getProfile(@FanPayloadParam() fanPayload: DecodedIdToken) {
    return {
      email: fanPayload.email,
      name: fanPayload.name,
    };
  }
}
```

## Error Handling

The guard will throw the following exceptions:

- `BadRequestException`: When client configuration is missing or email is not verified
- `UnauthorizedException`: When token is missing or invalid

## Configuration

The `FirebaseFanGuardModule` accepts the following configuration:

```typescript
interface FirebaseFanGuardConfig {
  publicKeyEndpoint: string;
}
```

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.
npm package: @origins-digital/nestjs-mongodb
Description: Common nestjs mongodb utilities for all nestjs projects
Author: Origins Digital
Latest version: 3.1.4

# @origins-digital/nestjs-mongodb

A NestJS module for MongoDB integration with automatic reconnection handling and connection management.

## Installation

```bash
npm install @origins-digital/nestjs-mongodb
```

## Features

- Seamless MongoDB integration with NestJS
- Automatic reconnection handling with exponential backoff
- Connection error logging and monitoring
- Global or module-scoped connection management
- Type-safe MongoDB operations

## Usage

### Basic Setup

```typescript
import { Module } from '@nestjs/common';
import { MongoDbModule } from '@origins-digital/nestjs-mongodb';
import { ConfigService } from '@nestjs/config';

@Module({
  imports: [
    MongoDbModule.forRoot({
      hostConnectionString: 'mongodb://localhost:27017',
      databaseName: 'your-database',
      global: true, // Optional: makes the connection available globally
    }),
  ],
})
export class AppModule {}
```

### Using Environment Variables

```typescript
import { Module } from '@nestjs/common';
import { MongoDbModule } from '@origins-digital/nestjs-mongodb';
import { ConfigService } from '@nestjs/config';

@Module({
  imports: [
    MongoDbModule.forRoot({
      hostConnectionString: process.env.MONGODB_URI,
      databaseName: process.env.MONGODB_DATABASE,
    }),
  ],
})
export class AppModule {}
```

### Using in Services

```typescript
import { Injectable, Inject } from '@nestjs/common';
import { Db } from 'mongodb';
import { MONGODB_PROVIDER } from '@origins-digital/nestjs-mongodb';

@Injectable()
export class UsersService {
  constructor(
    @Inject(MONGODB_PROVIDER)
    private readonly db: Db,
  ) {}

  async findAll() {
    return this.db.collection('users').find().toArray();
  }

  async create(user: any) {
    return this.db.collection('users').insertOne(user);
  }
}
```

### Connection Management

The module includes automatic reconnection handling with exponential backoff:

1. Initial connection attempt with 5-second timeout
2. If connection fails, retry with increasing intervals
3. Automatic reconnection on connection errors
4. Detailed error logging

## Error Handling

The module provides comprehensive error handling:

- Connection errors are logged with detailed information
- Automatic reconnection attempts with exponential backoff
- Connection state monitoring
- Error events handling

## Configuration Options

```typescript
interface MongoDBOptions {
  hostConnectionString: string; // MongoDB connection string
  databaseName: string; // Database name
  global?: boolean; // Optional: make connection global
}
```

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.
npm package: @origins-digital/nestjs-swagger
Description: Origins Digital NestJS Swagger package
Author: Origins Digital
Latest version: 2.1.4

# @origins-digital/nestjs-swagger

A NestJS package that provides enhanced Swagger/OpenAPI integration with Zod schema support.

## Installation

```bash
npm install @origins-digital/nestjs-swagger
```

## Features

- Seamless integration with NestJS Swagger
- Automatic Zod schema to OpenAPI conversion
- Support for DTOs created with `@origins-digital/zod-openapi-utils`
- Custom Swagger UI configuration
- Bearer token authentication support
- Automatic API documentation generation

## Usage

### Basic Setup

```typescript
import { Module } from '@nestjs/common';
import { initSwagger } from '@origins-digital/nestjs-swagger';

@Module({})
export class AppModule {
  constructor(private readonly app: INestApplication) {
    initSwagger(app, 'My API', '1.0.0');
  }
}
```

### Advanced Configuration

```typescript
import { Module } from '@nestjs/common';
import { initSwagger } from '@origins-digital/nestjs-swagger';
import { UsersModule } from './users/users.module';

@Module({})
export class AppModule {
  constructor(private readonly app: INestApplication) {
    initSwagger(
      app,
      'My API',
      '1.0.0',
      {
        // Additional schemas to include in the documentation
        CustomSchema: {
          type: 'object',
          properties: {
            id: { type: 'string' },
            name: { type: 'string' },
          },
        },
      },
      'api-docs',
      [UsersModule],
    );
  }
}
```

### Using with Zod DTOs

```typescript
import { z } from 'zod';
import { createZodDto } from '@origins-digital/zod-openapi-utils';

const UserSchema = z
  .object({
    id: z.string().uuid(),
    name: z.string(),
    email: z.string().email(),
  })
  .meta({ title: 'User' });

export class CreateUserDto extends createZodDto(UserSchema) {}

@Controller('users')
export class UsersController {
  @Post()
  create(@Body() createUserDto: CreateUserDto) {
    // The DTO will be automatically documented in Swagger
    return this.usersService.create(createUserDto);
  }
}
```

## Configuration Options

The `initSwagger` function accepts the following parameters:

- `app`: The NestJS application instance
- `packageName`: The name of your API
- `version`: The API version
- `schemas`: Optional additional OpenAPI schemas to include
- `uri`: Optional custom Swagger UI path (defaults to 'docs')
- `modules`: Optional array of modules to include in the documentation

## API Documentation

The Swagger UI will be available at:

- Default: `http://localhost:3000/docs`
- Custom: `http://localhost:3000/{uri}`

The OpenAPI specification will be available at:

- `http://localhost:3000/docs-json`

## Dependencies

- `@nestjs/swagger`: ^7.3.0
- `@origins-digital/zod-openapi-utils`: ^0.0.5

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.
npm package: @origins-digital/prisma-pagination
Description: Common prisma pagination utilities for all projects
Author: Origins Digital
Latest version: 3.1.4

# @origins-digital/prisma-pagination

A cursor-based pagination utility for Prisma ORM.

## Installation

```bash
npm install @origins-digital/prisma-pagination
```

## Features

- Cursor-based pagination for Prisma models
- Support for forward and backward pagination
- Type-safe pagination options
- Automatic cursor encoding/decoding
- Optional total count calculation
- Customizable sorting

## Usage

### Basic Setup

```typescript
import {
  paginateWithCursor,
  PaginationOptions,
  PaginationOrder,
} from '@origins-digital/prisma-pagination';

// Define your Prisma model type
type User = {
  id: string;
  name: string;
  email: string;
  createdAt: Date;
};

// Create pagination options
const options: PaginationOptions<keyof User> = {
  limit: 10,
  sort: {
    field: 'createdAt',
    order: 'desc',
  },
  loadTotalCount: true,
};

// Use pagination with your Prisma model
const result = await paginateWithCursor(prisma.user)(
  {}, // where clause
  options,
  { select: { id: true, name: true } }, // additional Prisma query options
);
```

### Forward Pagination

```typescript
const options: PaginationOptions<keyof User> = {
  limit: 10,
  after: 'eyJpZCI6IjEyMzQ1Njc4OTAifQ==', // Base64 encoded cursor
  sort: {
    field: 'createdAt',
    order: 'desc',
  },
};

const result = await paginateWithCursor(prisma.user)({}, options);
```

### Backward Pagination

```typescript
const options: PaginationOptions<keyof User> = {
  limit: 10,
  before: 'eyJpZCI6IjEyMzQ1Njc4OTAifQ==', // Base64 encoded cursor
  sort: {
    field: 'createdAt',
    order: 'desc',
  },
};

const result = await paginateWithCursor(prisma.user)({}, options);
```

### Nested Field Sorting

```typescript
const options: PaginationOptions<keyof User> = {
  limit: 10,
  sort: {
    field: 'profile.name', // Sort by nested field
    order: 'asc',
  },
};

const result = await paginateWithCursor(prisma.user)({}, options);
```

## API Reference

### PaginationOptions

```typescript
type PaginationOptions<T> = {
  limit: number; // Number of items per page
  before?: string; // Cursor for backward pagination
  after?: string; // Cursor for forward pagination
  sort: PaginationOrder<T>; // Sorting configuration
  loadTotalCount?: boolean; // Whether to calculate total count
};
```

### PaginationOrder

```typescript
class PaginationOrder<T> {
  field: T; // Field to sort by
  order: 'desc' | 'asc'; // Sort direction
}
```

## Response Format

The pagination function returns an object with the following structure:

```typescript
{
  items: T[];            // Array of paginated items
  hasNextPage: boolean;  // Whether there are more items after
  hasPreviousPage: boolean; // Whether there are more items before
  startCursor: string;   // Cursor for the first item
  endCursor: string;     // Cursor for the last item
  totalCount?: number;   // Total number of items (if loadTotalCount is true)
}
```

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.
npm package: @origins-digital/zod-openapi-utils
Description: Origins Zod OpenAPI Utils
Author: Origins Digital
Latest version: 2.2.4

# @origins-digital/zod-openapi-utils

A utility package that bridges Zod schemas with OpenAPI/Swagger documentation in NestJS applications.

> **Zod compatibility**: Fully compatible with **Zod v4.x**.

## Installation

```bash
npm install @origins-digital/zod-openapi-utils
```

## Features

- Automatic conversion of Zod schemas to OpenAPI/Swagger schemas
- Support for all Zod types and validations including lazy schemas
- Type-safe API documentation
- Seamless integration with NestJS Swagger
- Custom format support (email, URL, UUID, CUID, etc.)
- Support for recursive and circular references

## Usage

### Basic Setup

```typescript
import { Module } from '@nestjs/common';
import { makeOpenAPIComponents } from '@origins-digital/zod-openapi-utils';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';

@Module({})
export class AppModule {
  constructor() {
    const config = new DocumentBuilder()
      .setTitle('Your API')
      .setDescription('API description')
      .setVersion('1.0')
      .build();

    const document = SwaggerModule.createDocument(app, config, {
      extraModels: makeOpenAPIComponents([
        // Your Zod schemas here
      ]),
    });

    SwaggerModule.setup('api', app, document);
  }
}
```

### Using Zod Schemas with OpenAPI

```typescript
import { z } from 'zod';
import { createZodDto } from '@origins-digital/zod-openapi-utils';

// Define your Zod schema with .meta() OpenAPI metadata
const UserSchema = z
  .object({
    id: z.string().uuid(),
    email: z.string().email(),
    name: z.string().min(2).max(100),
    age: z.number().int().min(0).max(120),
    createdAt: z.date(),
    password: z.string().min(8), // use helpers like z.password() if available
  })
  .meta({
    title: 'User',
    description: 'User entity schema',
  });

// Create DTO from Zod schema
export class CreateUserDto extends createZodDto(UserSchema) {}

// Use it in your controller
@Controller('users')
export class UsersController {
  @Post()
  create(@Body() createUserDto: CreateUserDto) {
    // The DTO will be validated against the Zod schema
    return this.usersService.create(createUserDto);
  }
}
```

### Supported Zod Types and Validations

- **Strings**: email, URL, UUID, CUID, regex patterns, min/max length
- **Numbers**: integers, min/max values, multipleOf
- **Dates**: date-time format
- **Booleans**
- **Objects**: nested schemas
- **Arrays**: min/max length
- **Unions and Enums**
- **Lazy Schemas**: recursive and circular references
- **Custom Formats**: password, time, etc.
- **Nested types**: This package is also able to detect nested types when using metadata via `.meta()` and create the reference in the OpenAPI spec.

## Error Handling

The package includes a custom exception handler for Zod validation errors that integrates with NestJS's exception handling system.

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.