Skip to content

shreesharma07/numsy

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

70 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Numsy - A light-weight number processor

NPM Version NPM Downloads License: MIT TypeScript Node Version CI/CD Pipeline Security codecov Known Vulnerabilities Maintained PRs Welcome code style: prettier Package Manager

GitHub stars GitHub forks

Numsy is a light-weight TypeScript library for Indian phone number validation, sanitization, and CSV/Excel file processing. Built with class-based architecture, comprehensive error handling, and extensive logging capabilities.*

✨ Features

  • πŸ”’ Phone Number Validation - Validate Indian mobile numbers (10-digit starting with 6-9)
  • 🧹 Smart Sanitization - Clean and normalize phone numbers from various formats
  • πŸ“Š File Processing - Parse CSV and Excel files with automatic phone column detection
  • πŸ” Multiple Number Extraction - Extract multiple phone numbers from text
  • πŸ“ Comprehensive Logging - Built-in logging with configurable log levels
  • πŸ›‘οΈ Error Handling - Try-catch blocks everywhere with custom error classes
  • 🎯 TypeScript Support - Full type definitions included
  • ⚑ Fast Compilation - Built with SWC for lightning-fast builds
  • πŸ§ͺ Well Tested - Comprehensive test coverage
  • πŸ“¦ Modular Architecture - Use individual components or the unified API
  • 🎨 Class-Based Design - Modern, maintainable, and extensible
  • πŸ“š Helper Functions - Extensive utility functions for common tasks

πŸ“¦ Installation

npm install numsy
pnpm add numsy
yarn add numsy

πŸš€ Quick Start

Basic Usage

import Numsy from 'numsy';

const numsy = new Numsy();

// Validate a phone number
const result = numsy.validate('9876543210');
console.log(result);
// { original: '9876543210', sanitized: '9876543210', isValid: true }

// Check if valid
console.log(numsy.isValid('9876543210')); // true

// Sanitize number
console.log(numsy.sanitize('+91-987-654-3210')); // '9876543210'

// Format with country code
console.log(numsy.format('9876543210', true)); // '+919876543210'

Using Parser

import { Parser } from 'numsy';
// or
import parser from 'numsy/parser';

const parser = new Parser();

// Parse CSV file
const result = await parser.parseFile('./contacts.csv');
console.log(result.data);
console.log(result.totalRows);

Process Files

import Numsy from 'numsy';

const numsy = new Numsy();

// Process file with validation
const result = await numsy.processFile('./contacts.csv', './output');
console.log(`Processed ${result.totalRecords} records`);
console.log(`Valid: ${result.validRecords}, Invalid: ${result.invalidRecords}`);

πŸ–₯️ CLI Usage

Numsy includes a built-in server with a web interface for processing phone numbers without writing code.

Starting the Server

After installing the package:

# Using npx (recommended - no installation needed)
npx @numsy/numsy-serve

# Or install globally first
npm install -g @numsy/numsy
numsy-serve

# With custom options
npx @numsy/numsy-serve --port 3000
npx @numsy/numsy-serve --page
npx @numsy/numsy-serve -p 8080 --page

# Display help
npx @numsy/numsy-serve --help

For local development (in this repository):

# Using pnpm scripts
pnpm run serve

# Or using npm scripts
npm run serve

# Or directly with ts-node
npx ts-node src/cli/server.ts

# With options (requires -- separator)
pnpm run serve -- --port 3000
pnpm run serve -- --page

CLI Options

Option Alias Description Default
--port <number> -p Specify port number (1024-65535) 3000
--page -s, --serve Serve the HTML utility page false
--help -h Display help message -

Environment Variables

You can also configure the server using environment variables:

# Set port via environment variable
PORT=3000 npx @numsy/numsy-serve

# Set environment mode
NODE_ENV=production npx @numsy/numsy-serve

Server Features

  • βœ… Auto Port Detection - Automatically finds an available port if default is in use
  • 🌐 CORS Enabled - Works with any frontend application
  • πŸ”Œ REST API - Access validation endpoints programmatically
  • πŸ’š Health Check - Built-in health check endpoint
  • 🎯 Global API Prefix - All endpoints under /api
  • πŸ›‘οΈ Graceful Shutdown - Handles SIGTERM and SIGINT signals

API Endpoints

Once the server is running, you can access:

  • Health Check: http://localhost:3000/api/health
  • API Base: http://localhost:3000/api
  • Utility Page (with --page flag): http://localhost:3000

Example Server Output

╔═══════════════════════════════════════════════════════════════╗
β•‘ βœ… Server Started Successfully β•‘
β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•

πŸš€ Server running on: http://localhost:3000
πŸ“‘ API endpoint: http://localhost:3000/api
πŸ’š Health check: http://localhost:3000/api/health
🌐 Utility page: http://localhost:3000

πŸ“ Environment: development
⚑ Process ID: 12345

Press Ctrl+C to stop the server

πŸ’‘ API Examples

Phone Validation

import Numsy from 'numsy';

const numsy = new Numsy();

// Single validation
const result = numsy.validate('9876543210');

// Batch validation
const numbers = ['9876543210', '8123456789', '1234567890'];
const results = numsy.validateBatch(numbers);

// Extract multiple numbers from text
const text = 'Contact me at 9876543210 or 8123456789';
const extracted = numsy.extractMultiple(text);
console.log(extracted.validNumbers); // ['9876543210', '8123456789']

File Operations

import Numsy from 'numsy';

const numsy = new Numsy();

// Parse file
const parsed = await numsy.parseFile('./data.csv');

// Process with validation
const result = await numsy.processFile('./data.csv', './output');

// Write to CSV
await numsy.writeCsv(data, './output/clean-data.csv');

Using Individual Components

import { Parser, PhoneValidator, FileProcessor } from 'numsy';

// Use Parser separately
const parser = new Parser({
  normalizeColumns: true,
  detectPhoneColumn: true,
});

// Use PhoneValidator separately
const validator = new PhoneValidator({
  enableLogging: false,
});

// Use FileProcessor separately
const processor = new FileProcessor({
  outputDir: './output',
});

🎯 Configuration Options

import Numsy from 'numsy';

const numsy = new Numsy({
  enableLogging: true, // Enable console logging
  logLevel: 'debug', // Log level: 'log' | 'error' | 'warn' | 'debug' | 'verbose'
  throwOnError: false, // Throw errors vs return error objects
});

// Update options at runtime
numsy.setOptions({ enableLogging: false });

πŸ“š API Reference

Numsy Class

Main class providing unified API:

Methods

  • validate(phone: string): PhoneValidationResult - Validate single phone number
  • validateBatch(phones: string[]): PhoneValidationResult[] - Validate multiple numbers
  • sanitize(phone: string): string - Clean phone number
  • isValid(phone: string): boolean - Quick validation check
  • format(phone: string, withCountryCode?: boolean): string - Format phone number
  • extractMultiple(text: string): MultipleNumbersResult - Extract numbers from text
  • parseFile(filePath: string): Promise<FileParseResult> - Parse CSV/Excel file
  • processFile(filePath: string, outputDir?: string): Promise<ProcessingResult> - Process file with validation
  • writeCsv(data: ParsedDataRow[], outputPath: string): Promise<void> - Write to CSV
  • detectPhoneColumn(data: ParsedDataRow[]): string | null - Detect phone column

Parser Class

File parsing operations:

  • parseFile(filePath: string): Promise<FileParseResult> - Parse file
  • writeCsv(data, outputPath): Promise<void> - Write CSV
  • writeProcessedFiles(validData, invalidData, validPath, invalidPath): Promise<void> - Write multiple files

PhoneValidator Class

Phone validation operations:

  • validate(phone: string): PhoneValidationResult - Validate number
  • validateBatch(phones: string[]): PhoneValidationResult[] - Batch validation
  • sanitize(phone: string): string - Sanitize number
  • isValid(phone: string): boolean - Check validity
  • extractMultiple(text: string): MultipleNumbersResult - Extract numbers
  • format(phone: string, withCountryCode?: boolean): string - Format number

Helper Functions

Pure utility functions:

import {
  sanitizePhoneNumber,
  validatePhoneNumber,
  extractPhoneNumbers,
  normalizeDataRows,
  detectPhoneColumn,
  isNonEmptyString,
  isValidNumber,
  LoggerHelper,
  AppError,
} from 'numsy';

πŸ—οΈ Architecture

Numsy follows a modern, class-based architecture:

src/
β”œβ”€β”€ common/
β”‚ β”œβ”€β”€ interfaces/ # TypeScript interfaces
β”‚ β”œβ”€β”€ functions/ # Pure utility functions
β”‚ └── helpers/ # Helper classes (Logger, Error, File, Validation)
β”œβ”€β”€ core/
β”‚ β”œβ”€β”€ Numsy.ts # Main class
β”‚ β”œβ”€β”€ Parser.ts # File parser
β”‚ β”œβ”€β”€ PhoneValidator.ts # Phone validator
β”‚ └── FileProcessor.ts # File processor
└── index.ts # Package entry point

πŸ”§ Development

Setup

# Install dependencies
pnpm install

# Build package
pnpm run build

# Run tests
pnpm test

# Development with auto-reload
pnpm run dev

# Start server (for web interface)
pnpm run start:dev

Scripts

  • pnpm run build - Build with SWC (fast compilation)
  • pnpm run build:nest - Build with Nest CLI
  • pnpm run dev - Development mode with nodemon
  • pnpm run test - Run tests
  • pnpm run test:watch - Watch mode
  • pnpm run test:cov - Coverage report
  • pnpm run lint - Lint code
  • pnpm run format - Format code

πŸ“– Documentation

πŸ§ͺ Testing

Numsy includes comprehensive test coverage:

# Run all tests
pnpm test

# Watch mode
pnpm test:watch

# Coverage report
pnpm test:cov

πŸ›‘οΈ Error Handling

Numsy provides comprehensive error handling:

import { Numsy, AppError } from 'numsy';

try {
  const numsy = new Numsy({ throwOnError: true });
  const result = await numsy.processFile('./data.csv');
} catch (error) {
  if (error instanceof AppError) {
    console.error(`Error [${error.code}]: ${error.message}`);
    console.error('Details:', error.details);
  }
}

πŸ“ TypeScript Support

Full TypeScript support with complete type definitions:

import {
  Numsy,
  NumsyOptions,
  PhoneValidationResult,
  MultipleNumbersResult,
  ProcessingResult,
  FileParseResult,
  ParsedDataRow,
} from 'numsy';

const options: NumsyOptions = {
  enableLogging: true,
  logLevel: 'debug',
  throwOnError: false,
};

const numsy = new Numsy(options);
const result: PhoneValidationResult = numsy.validate('9876543210');

🀝 Contributing

Contributions are welcome! Please read CONTRIBUTING.md for details.

πŸ“„ License

MIT License - see LICENSE file for details.

πŸ‘¨β€πŸ’» Author

Shri Kumar Sharma

πŸ”— Links

🌟 Support

If you find this package helpful, please give it a star on GitHub!

πŸ“Š Stats

  • Bundle Size: Optimized and tree-shakeable
  • TypeScript: 100% TypeScript codebase
  • Test Coverage: Comprehensive test suite
  • Dependencies: Minimal and well-maintained

πŸš€ Optimizations

  • ⚑ SWC Compilation - 20x faster than TypeScript compiler
  • 🎯 Tree-Shakeable - Import only what you need
  • πŸ“¦ Modular Design - Use individual components
  • πŸ”§ Zero Config - Works out of the box
  • πŸ›‘οΈ Type Safe - Full TypeScript support

Made with ❀️ by Shri Kumar Sharma

About

Numsy is a lightweight TypeScript toolkit for validating, sanitizing, and processing Indian phone numbers from CSV/Excel datasets with reliability and strong typing.

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Packages

 
 
 

Contributors