Skip to content

Releases: Zheruel/nano-string-utils

v0.23.0 - Add Three New Validation Functions

21 Oct 21:47
a41dd9d

Choose a tag to compare

Added

New Validation Functions

  • isNumeric() - Validates if a string represents a numeric value (integer or decimal)

    • Handles positive and negative integers (42, -17)
    • Supports decimal numbers (3.14, -0.5)
    • Automatic whitespace trimming
    • Rejects empty strings, Infinity, and scientific notation
    • Bundle size: 122 bytes gzipped
  • isAlphanumeric() - Validates if a string contains only alphanumeric characters (a-z, A-Z, 0-9)

    • Strict ASCII validation (no Unicode, special characters, or whitespace)
    • Perfect for username validation, identifiers, and tokens
    • Bundle size: 88 bytes gzipped
  • isUUID() - Validates if a string is a valid UUID in standard 8-4-4-4-12 format

    • Supports all UUID versions (v1-v5)
    • Accepts NIL UUID (00000000-0000-0000-0000-000000000000)
    • Case-insensitive validation
    • Bundle size: 89 bytes gzipped

Branded Type Integration

Full type-safe handling for all three validation functions:

  • New branded types: NumericString, AlphanumericString, UUID
  • Type guards: isValidNumeric(), isValidAlphanumeric(), isValidUUID()
  • Builder functions: toNumericString(), toAlphanumericString(), toUUID()
  • Assertion functions: assertNumericString(), assertAlphanumericString(), assertUUID()
  • Unsafe casts: unsafeNumericString(), unsafeAlphanumericString(), unsafeUUID()
  • Zero runtime overhead - type safety enforced at compile time

CLI Support

All three functions available via `nano-string` command:

  • `nano-string isNumeric "42"`
  • `nano-string isAlphanumeric "user123"`
  • `nano-string isUUID "550e8400-e29b-41d4-a716-446655440000"`

Documentation

  • Updated function count from 48 to 51 utilities
  • Added comprehensive JSDoc documentation with real-world usage examples
  • Updated README with function descriptions, examples, and bundle sizes
  • Regenerated bundle size and performance benchmark data

📦 Installation: `npm install nano-string-utils`

📚 Documentation: https://zheruel.github.io/nano-string-utils/

v0.22.0 - Enhanced Unicode Support

16 Oct 17:58
5f63fc1

Choose a tag to compare

Enhanced Unicode Support for reverse() and truncate()

Improved

  • Production-grade grapheme cluster handling for both reverse() and truncate() functions
    • ZWJ (Zero-Width Joiner) emoji sequences preserved: family emojis (👨‍👩‍👧‍👦), flags (🏴‍☠️, 🇺🇸), professions (👨‍⚕️, 👩‍🚀)
    • Emoji with skin tone modifiers correctly handled (👍🏽, 👋🏾)
    • Diacritics and combining marks preserved (café, Malmö, naïve, decomposed Unicode)
    • ASCII fast-path optimization maintains performance for simple strings (no performance regression)

Performance

  • Minimal bundle size impact for significant correctness improvement
    • reverse(): 67B → 307B (+240B for full Unicode support)
    • truncate(): 226B → 477B (+251B for full Unicode support)
    • Total bundle: 8.99 KB → 8.92 KB (slight decrease due to optimizations)
    • ASCII strings maintain original performance through fast-path checks

Test Coverage

  • 26 new comprehensive test cases
    • 11 tests for reverse() covering ZWJ sequences, skin tones, diacritics, and mixed content
    • 15 tests for truncate() covering grapheme boundaries, emoji preservation, and edge cases
    • 100% code coverage maintained across all functions

Documentation

  • Updated JSDoc examples to demonstrate Unicode handling capabilities
  • Enhanced documentation site with Unicode examples
  • Regenerated benchmark data reflecting new bundle sizes

v0.21.0 - isHexColor validation function

15 Oct 16:23
8a6cd3e

Choose a tag to compare

Added

  • New Function: isHexColor() - Validates hexadecimal color codes with comprehensive format support

    • Supports 3-digit (#fff), 6-digit (#ffffff), 4-digit with alpha (#fff8), and 8-digit with alpha (#ffffff80) formats
    • Case-insensitive validation for all formats
    • Pre-compiled regex for optimal performance
    • Bundle size: 118 bytes raw, 103 bytes gzipped
    • 100% test coverage with 32 test cases
    • Use cases: design systems, theme validation, color picker validation, form validation
  • Branded Type Integration for HexColor - Full type-safe color handling

    • New HexColor branded type for compile-time safety
    • Type guard: isValidHexColor() for type narrowing
    • Builder function: toHexColor() returns HexColor | null with validation
    • Assertion function: assertHexColor() throws BrandedTypeError on invalid input
    • Unsafe cast: unsafeHexColor() for trusted input (no validation)
    • Integrates seamlessly with existing branded type system

Improved

  • Benchmark Infrastructure - Enhanced function extraction for more accurate metrics
    • Added exclusion list for 26 branded type system helpers
    • Separates core utilities (49 functions) from type system infrastructure
    • Prevents metric inflation in bundle size and performance benchmarks
    • More accurate representation of library capabilities
    • Better comparison with other libraries (lodash, es-toolkit)

Documentation

  • Updated total function count from 48 to 49 core utilities
  • Added isHexColor to documentation site with interactive playground examples
  • Updated bundle size references to accurately reflect package size (< 12KB)
  • Regenerated benchmark data with new function

Full Changelog: v0.20.0...v0.21.0

v0.20.0 - SafeHTML, TypeScript Strict Mode Fixes & Enhanced Documentation

09 Oct 17:57
a243e8f

Choose a tag to compare

Summary

This release introduces type-safe XSS prevention with the new SafeHTML branded type, fixes TypeScript strict mode violations, improves documentation with comprehensive examples, and streamlines benchmark reporting by replacing markdown files with JSON data for the interactive documentation site.

Changes

New Features

SafeHTML Branded Type - Compile-Time XSS Prevention

Added a new branded type SafeHTML that provides compile-time protection against XSS attacks:

  • toSafeHTML() - Builder function with opinionated secure defaults:
    • Strips all HTML by default for maximum security
    • Removes script tags and dangerous content
    • Removes non-printable characters
    • Optional configuration to allow specific safe tags
  • unsafeSafeHTML() - Bypass for trusted input (use with caution)
  • Zero runtime overhead - Type safety enforced at compile time
  • 11 comprehensive tests covering all sanitization scenarios
  • Integrates seamlessly with existing branded types (Email, URL, Slug)

Branded Type Pattern Documentation

Added comprehensive documentation for extending the library with custom branded types:

  • "Extending with Custom Branded Types" section in README
  • Examples showing how to create domain-specific types (PhoneNumber, PostalCode, CreditCard)
  • Demonstrates type-safe constructors and validation patterns
  • Shows composability with built-in branded types

Enhanced JSDoc Examples

Improved developer experience with real-world examples across 20+ functions:

  • All examples use proper ```ts code blocks for syntax highlighting
  • Practical use cases: form validation, search normalization, file naming, etc.
  • Functions enhanced: capitalize, codePoints, deburr, detectScript, escapeHtml, graphemes, hashString, pad, padEnd, padStart, pluralize, randomString, reverse, singularize, smartSplit, stripHtml, toASCII

Bug Fixes

TypeScript Strict Mode Compliance

Resolved all TypeScript violations related to noUncheckedIndexedAccess:

  • Added non-null assertions for guaranteed valid array access in levenshtein, pad, fuzzyMatch, smartSplit
  • Fixed randomString to handle empty charset edge case with early return
  • Zero runtime cost - all assertions validated by algorithm guarantees
  • All 1207 tests passing

Infrastructure Changes

Bundle Size Adjustments

Updated size limits to accommodate new SafeHTML feature while maintaining reasonable constraints:

  • ESM: 9.1 KB → 9.5 KB (+400 bytes headroom)
  • CJS: 9.5 KB → 10 KB (+500 bytes headroom)
  • Current actual size: 8.84 KB ESM / 9.36 KB CJS (well under limits)
  • SafeHTML adds ~500 bytes for compile-time XSS prevention

Benchmark Reporting Improvements

Streamlined benchmark output for better integration with documentation site:

  • Removed: benchmark-results.md and bundle-size-results.md markdown files
  • Kept: bundle-sizes.json and performance-benchmarks.json for programmatic access
  • Updated bundle-size.ts to generate JSON-only output
  • JSON files copied to docs-src/public/ for serving in interactive docs
  • Cleaner output with summary statistics in console

Documentation Updates

  • CHANGELOG.md: Complete v0.20.0 release notes with categorized changes
  • README.md:
    • Added branded type extension guide with examples
    • Updated benchmark instructions to reflect new workflow
    • Linked to interactive benchmark viewer on documentation site
    • Updated bundle size limits in documentation

Testing

  • All 1207 tests passing
  • Added 11 new tests for SafeHTML functionality
  • Bundle size validation passing
  • TypeScript strict mode compilation successful

Security Considerations

The SafeHTML branded type provides an additional layer of security for applications that need to handle user-generated content. By enforcing sanitization at the type level, it helps prevent XSS vulnerabilities by making it impossible to use unsanitized strings where safe HTML is expected.

Breaking Changes

None. This release is fully backward compatible.

v0.19.1: Enhanced NPM Discoverability

07 Oct 15:20

Choose a tag to compare

Changed

  • Package Metadata - Enhanced NPM discoverability
    • Expanded description to highlight key features: "49 tree-shakeable string utilities with zero dependencies. TypeScript-first, <1KB per function. Case conversion, validation, sanitization, fuzzy matching & more."
    • Increased keywords from 9 to 20 for better search visibility
    • Added targeted keywords: string-manipulation, text-processing, case-conversion, kebabCase, pascalCase, email-validation, url-validation, fuzzy-match, levenshtein, sanitize, tree-shakeable, micro
    • Improved package findability for common use cases and search queries

Full Changelog: https://github.com/Zheruel/nano-string-utils/blob/main/CHANGELOG.md

v0.19.0: Performance and Documentation Improvements

04 Oct 11:38
518a66a

Choose a tag to compare

Performance

  • Significant Bundle Size Reductions - Achieved 98% win rate against competitors (47/48 functions)

    • Overall 7% average size reduction through code optimization
    • camelCase: 72% reduction (827B → 232B gzipped)
    • capitalize: 86% reduction (697B → 99B gzipped)
    • truncate: 94% smaller than lodash (180B vs 2.9KB)
    • template: 95% smaller than lodash (302B vs 5.7KB)
    • padStart/padEnd: 93% smaller than lodash
    • Package total: < 8.5KB minified + gzipped
  • Runtime Performance Improvements - Competitive with industry-leading libraries

    • Wins 10 out of 14 benchmarked functions vs es-toolkit
    • Ultra-fast case conversions: 3.4M-4.3M ops/s
    • Efficient truncate: 23.4M ops/s
    • Fast template interpolation: 998K ops/s

Added

  • Performance Benchmarking Infrastructure

    • New benchmarks/performance-benchmarks.ts - comprehensive benchmark suite
    • Compares nano-string-utils against lodash and es-toolkit
    • Measures operations per second with statistical margins
    • Generates performance-benchmarks.json for documentation
    • Interactive performance visualization in documentation site
  • Interactive Documentation Enhancements

    • New performance benchmark viewer with live charts
    • Added docs-src/src/performance.ts with visual performance comparisons
    • Enhanced bundle size display with better formatting
    • Link to interactive performance benchmarks in README

Improved

  • Code Optimizations

    • Simplified case conversion implementations (camelCase, pascalCase, kebabCase, snakeCase)
    • More concise mapping logic and removed redundant checks
    • Optimized pad() function with more efficient string concatenation
    • Unicode-aware word splitting engine - now properly handles emojis, extended pictographic characters, and Unicode letters from all scripts
  • Tree-Shaking Improvements

    • Refactored branded types from namespace export to individual exports
    • Separately exports types, guards, assertions, and builders
    • Enables better dead code elimination - users only bundle what they import
  • Bundle Size Tracking

    • Updated methodology to report gzipped sizes (more realistic)
    • Enhanced bundle-size-results.md with accurate metrics
    • Improved visual distinction between winners in comparisons

Fixed

  • Null/Undefined Handling - Restored proper null/undefined checks that were removed during optimization
    • camelCase, kebabCase, snakeCase, pascalCase now correctly handle null/undefined inputs
    • pad() now correctly handles null/undefined inputs
    • All 1195 tests passing

Documentation

  • README Updates
    • Replaced minified sizes with gzipped sizes for accuracy
    • Updated performance comparisons with real benchmark data
    • Improved comparison tables with latest metrics
    • Added comprehensive benchmark results and methodology

v0.18.0 - Add redact() function

30 Sep 23:24
9625234

Choose a tag to compare

Added

  • New Function: redact() - Redact sensitive information from text for UI/logging purposes
    • Built-in pattern support for SSN, credit cards, emails, and phone numbers
    • Multiple redaction strategies: partial (show last N chars) and full (complete masking)
    • Selective type redaction - choose which data types to redact
    • Custom pattern support with regex and replacement functions
    • Configurable partial length (default: 4 characters)
    • Smart format preservation for phone numbers (parentheses, dots, dashes)
    • Consistent output formatting (e.g., SSNs always use dash format)
    • Security notice in documentation emphasizing proper use cases
    • 42 comprehensive test cases covering all redaction types and edge cases
    • Bundle size: ~1.3KB gzipped

Changed

  • Bundle Size - Increased size limit from 9 KB to 9.1 KB to accommodate new redaction function
  • Documentation - Updated function count from 47 to 48 functions
  • Interactive Playground - Added redact() to documentation site with live examples

Install

npm install nano-string-utils@0.18.0

View the full changelog: https://github.com/Zheruel/nano-string-utils/blob/main/CHANGELOG.md

v0.17.0 - Text Classification, Script Detection & Security Sanitization

27 Sep 11:14
73eb115

Choose a tag to compare

🎉 What's New

This release introduces three powerful new utility functions for text analysis and security:

🔍 classifyText(text: string): Classification

Intelligently classifies text content with confidence scoring:

  • Detects URLs, emails, phone numbers
  • Identifies JSON, code, markdown, HTML
  • Recognizes questions and numeric content
  • Returns type and confidence score (0-1)
  • Bundle size: ~2.3KB

🌍 detectScript(text: string): Script

Detects the dominant writing system in text:

  • Supports: Latin, CJK, Arabic, Cyrillic, Hebrew, Devanagari, Greek, Thai
  • Useful for internationalization and language detection
  • Bundle size: ~2.4KB

🔒 sanitize(str: string, options?: SanitizeOptions): string

Security-focused string sanitization for web applications:

  • Removes XSS vectors (script tags, event handlers, dangerous URIs)
  • Configurable HTML tag/attribute allowlisting
  • Control character removal
  • Whitespace normalization
  • Custom pattern removal
  • Bundle size: ~2.5KB

📊 Performance

All functions maintain excellent performance standards:

  • classifyText: ~400K-2M operations/second
  • detectScript: ~500K-10M operations/second
  • sanitize: ~365K-2.2M operations/second

📦 Bundle Size

Total library size remains under 9KB gzipped with all 47 functions.

🧪 Quality Assurance

  • ✅ 579 new tests added (1,153 total tests)
  • ✅ 100% code coverage for new functions
  • ✅ TypeScript strict mode compliant
  • ✅ Zero dependencies maintained

📚 Documentation

  • Updated README with comprehensive API documentation
  • Added all functions to interactive playground
  • Enhanced bundle size tracking and comparisons

Installation

```bash
npm install nano-string-utils@0.17.0

or

yarn add nano-string-utils@0.17.0

or

pnpm add nano-string-utils@0.17.0
```

Usage Examples

```javascript
import { classifyText, detectScript, sanitize } from 'nano-string-utils';

// Text classification
classifyText('https://example.com'); // { type: 'url', confidence: 1 }
classifyText('What is TypeScript?'); // { type: 'question', confidence: 1 }

// Script detection
detectScript('Hello World'); // 'latin'
detectScript('你好世界'); // 'cjk'
detectScript('مرحبا'); // 'arabic'

// Security sanitization
sanitize("<script>alert('xss')</script>Hello"); // "Hello"
sanitize("Bold text", { allowedTags: ["b"] }); // "Bold text"
```


Full Changelog: v0.16.0...v0.17.0

v0.16.0 - Text Processing Utilities

22 Sep 20:01
bd28f2d

Choose a tag to compare

What's New

🎉 New Functions (3)

extractEntities(text: string): ExtractedEntities

Extract various entities from text including:

  • 📧 Email addresses
  • 🔗 URLs
  • 🏷️ Social media mentions (@username)
  • #️⃣ Hashtags
  • 📱 Phone numbers
  • 📅 Dates (ISO, US, EU formats)
  • 💵 Prices

smartSplit(text: string): string[]

Intelligently split text into sentences with:

  • Abbreviation handling (Dr., Mr., Mrs., etc.)
  • Decimal number preservation ($10.50)
  • Ellipsis detection
  • Special case handling (U.S.A., M.I.T.)

humanizeList(items: unknown[], options?: HumanizeListOptions)

Convert arrays to human-readable lists:

  • Oxford comma support
  • Custom conjunctions (and/or)
  • Quote wrapping
  • Null/undefined filtering

📈 Changes

  • Bundle size limit increased from 6.5KB to 7.5KB
  • Total function count: 44
  • All functions maintain < 1.2KB individual size

📦 Install

```bash
npm install nano-string-utils@0.16.0
```

📚 Full Changelog

See CHANGELOG.md

v0.15.0 - CDN Optimization

21 Sep 12:35
0b83567

Choose a tag to compare

🚀 CDN Optimization Release

This release adds full support for using nano-string-utils directly from CDN services, making it easier than ever to use in browser environments without any build tools.

✨ What's New

CDN Support

  • IIFE Build Format - New browser-ready build that exposes nanoStringUtils global variable
  • CDN Configuration - Added unpkg, jsdelivr, and browser fields to package.json
  • Zero Build Tools Required - Use directly via <script> tags in HTML

📦 Usage

Via Script Tag

<script src="https://unpkg.com/nano-string-utils@0.15.0/dist/index.iife.js"></script>
<script>
  const slug = nanoStringUtils.slugify("Hello World!");
  console.log(slug); // 'hello-world'
</script>

Via ES Modules

<script type="module">
  import { slugify, camelCase } from 'https://unpkg.com/nano-string-utils@0.15.0/dist/index.js';
  
  console.log(slugify("Hello World")); // 'hello-world'
  console.log(camelCase("hello-world")); // 'helloWorld'
</script>

🏗️ Build Improvements

  • Triple output format: ESM, CommonJS, and IIFE
  • All builds are minified and tree-shaken
  • Source maps included for all formats
  • Bundle size remains under 6.5KB

📊 Stats

  • ESM: 6.01 KB (brotli compressed)
  • CJS: 6.41 KB (brotli compressed)
  • IIFE: ~19 KB (minified)
  • Functions: 41 utilities
  • Dependencies: Still zero! 🎉

🔗 CDN Links

📝 Full Changelog

See CHANGELOG.md for details.