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

pw-item-desc-parser

v1.2.0

Published

A TypeScript parser for Perfect World item descriptions with color formatting and LRU caching

Readme

pw-item-desc-parser

A TypeScript parser for Perfect World item descriptions with color formatting, LRU caching, and React compatibility.

Features

  • 🚀 High Performance: LRU cache with configurable size limits
  • 🎨 Color Formatting: Converts ^xxxxxx color codes to HTML with inline styles
  • 📝 Line Break Support: Converts \r to <br /> tags
  • 🔍 Search Functionality: Search through item descriptions
  • TypeScript Support: Full type definitions included
  • ⚛️ React Compatible: Works seamlessly with React applications
  • 📦 Bundled Data: Includes default item description file
  • 🔧 Flexible: Support for custom files and configurations

Installation

npm install pw-item-desc-parser

Quick Start

Basic Usage

import { ItemDescParser } from 'pw-item-desc-parser';

// Create parser instance
const parser = new ItemDescParser();

// Parse item by ID
const item = parser.parseById(10037);
console.log(item.formatted); // HTML formatted text

// Parse raw text
const rawText = '^ffcb4aUma invenção maravilhosa\\r^00ffffClique para usar';
const parsed = parser.parseDescription(rawText);
console.log(parsed.formatted);

TypeScript Usage

import { ItemDescParser, ParsedDescription } from 'pw-item-desc-parser';

const parser = new ItemDescParser({
  cacheSize: 2000,
  encoding: 'utf16le'
});

const description: ParsedDescription | null = parser.parseById(10037);

React Usage

import React, { useState, useEffect } from 'react';
import { ItemDescParser } from 'pw-item-desc-parser';

function ItemComponent({ itemId }) {
  const [parser] = useState(() => new ItemDescParser());
  const [description, setDescription] = useState(null);

  useEffect(() => {
    const desc = parser.parseById(itemId);
    setDescription(desc);
  }, [itemId, parser]);

  if (!description) return <div>Loading...</div>;

  return (
    <div dangerouslySetInnerHTML={{ __html: description.formatted }} />
  );
}

API Reference

ItemDescParser

Main parser class for handling item descriptions.

Constructor Options

interface ParserOptions {
  filePath?: string;     // Path to item description file (default: bundled file)
  cacheSize?: number;    // Maximum cache size (default: 1000)
  encoding?: string;     // File encoding (default: 'utf16le')
}

Methods

parseDescription(text: string): ParsedDescription

Parse raw description text with color codes and line breaks.

const result = parser.parseDescription('^ffcb4aText with color\\r^00ffffMore text');
// Returns: { text: '...', formatted: '<em style="color: #ffcb4a">Text with color</em><br /><em style="color: #00ffff">More text</em>' }
parseById(id: string | number): ParsedDescription | null

Parse item description by ID. Returns null if item not found.

const item = parser.parseById(10037);
if (item) {
  console.log(item.formatted);
}
loadFile(filePath?: string): ItemDescriptionMap

Load and parse the entire file. Returns map of all descriptions.

const allItems = parser.loadFile();
console.log(`Loaded ${Object.keys(allItems).length} items`);
searchDescriptions(searchText: string, caseSensitive?: boolean): Array<{id: string, description: ParsedDescription}>

Search through item descriptions.

const results = parser.searchDescriptions('invenção');
results.forEach(result => {
  console.log(`ID ${result.id}: ${result.description.text}`);
});
getAllDescriptions(): ItemDescriptionMap

Get all loaded descriptions.

clearCache(): void

Clear the LRU cache.

getCacheStats(): {size: number, maxSize: number}

Get cache statistics.

getAvailableIds(): string[]

Get array of available item IDs.

setFilePath(filePath: string): void

Set new file path (requires reload).

isLoaded(): boolean

Check if file is loaded.

Data Format

The parser expects item description files in the following format:

10037	"^ffcb4aUma invenção maravilhosa para a raça humana, \rexibindo completamente sua natureza de amante da diversão e da paz. \r^00ffffClique com o botão direito do mouse para usá-la."
10042	"^00ffffSelecione uma carruagem de cerco, use a tecla da seta para a direita para controlá-la."

Color Codes

  • Format: ^xxxxxx where xxxxxx is a 6-digit hexadecimal color code
  • Example: ^ffcb4a becomes <em style="color: #ffcb4a">text</em>

Line Breaks

  • Format: \r
  • Converts to: <br />

Performance

Benchmarks

  • File Loading: ~50ms for 25,000 items
  • Individual Parsing: ~0.1ms per item
  • Cache Hit: ~0.01ms
  • Memory Usage: ~2-5MB for full cache

Optimization Tips

  1. Use Cache: Enable caching for repeated access
  2. Batch Operations: Load file once, parse multiple items
  3. Search Efficiently: Use search instead of iterating through all items
  4. Memory Management: Clear cache when memory is limited
import { ItemDescParser } from 'pw-item-desc-parser';

// Optimized usage
const parser = new ItemDescParser({ cacheSize: 5000 });
parser.loadFile(); // Load once

// Fast repeated access
for (const id of itemIds) {
  const item = parser.parseById(id); // Uses cache
}

Examples

Custom File Usage

import { ItemDescParser } from 'pw-item-desc-parser';

const parser = new ItemDescParser({
  filePath: './my_custom_items.txt',
  cacheSize: 2000,
  encoding: 'utf16le'
});

const items = parser.loadFile();

Error Handling

import { ItemDescParser } from 'pw-item-desc-parser';

try {
  const parser = new ItemDescParser({ filePath: './nonexistent.txt' });
  const items = parser.loadFile();
} catch (error) {
  console.error('Failed to load file:', error.message);
}

Advanced Search

import { ItemDescParser } from 'pw-item-desc-parser';

const parser = new ItemDescParser();
parser.loadFile();

// Case-sensitive search
const results = parser.searchDescriptions('INVENÇÃO', true);

// Filter by specific criteria
const filteredResults = results.filter(result => 
  result.description.text.includes('magic')
);

React Integration

Custom Hook

import { useState, useEffect, useMemo } from 'react';
import { ItemDescParser } from 'pw-item-desc-parser';

function useItemParser(filePath) {
  const parser = useMemo(() => new ItemDescParser({ filePath }), [filePath]);
  const [isLoaded, setIsLoaded] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    try {
      parser.loadFile();
      setIsLoaded(true);
      setError(null);
    } catch (err) {
      setError(err.message);
      setIsLoaded(false);
    }
  }, [parser]);

  return { parser, isLoaded, error };
}

// Usage in component
function MyComponent() {
  const { parser, isLoaded, error } = useItemParser();
  
  if (error) return <div>Error: {error}</div>;
  if (!isLoaded) return <div>Loading...</div>;
  
  const item = parser.parseById(10037);
  return <div dangerouslySetInnerHTML={{ __html: item?.formatted }} />;
}

TypeScript Types

interface ParsedDescription {
  text: string;        // Original raw text
  formatted: string;   // HTML formatted text
}

interface ItemDescriptionMap {
  [id: string]: ParsedDescription;
}

interface ParserOptions {
  filePath?: string;
  cacheSize?: number;
  encoding?: string;
}

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

License

MIT License - see LICENSE file for details.

Changelog

1.0.0

  • Initial release
  • TypeScript support
  • LRU caching
  • React compatibility
  • Search functionality
  • Bundled default data file