Library Replacement Skill
This skill provides guidelines for finding redundant custom implementations and replacing them with well-known libraries.
Purpose
Identify custom implementations that:
- Duplicate functionality available in well-known libraries
- Are harder to maintain than library equivalents
- May have bugs that libraries have already solved
- Lack the testing/documentation of established libraries
When to Apply
Apply this skill when:
- Auditing codebase for technical debt
- Refactoring for maintainability
- Reducing custom code footprint
- Standardizing on ecosystem best practices
Common Replacement Patterns
Pattern Categories
| Category |
Custom Implementation Signs |
Recommended Libraries |
| Result/Error Handling |
Custom Result type, ok/err pattern |
neverthrow, ts-results, effect |
| Validation |
Custom validate functions, manual checks |
zod, valibot, arktype |
| Date/Time |
Custom date parsing/formatting |
date-fns, dayjs, luxon |
| Path Operations |
Custom path manipulation |
pathe, upath (cross-platform) |
| CLI Parsing |
Custom argument parsing |
commander, yargs, citty |
| Configuration |
Custom config loading |
c12, cosmiconfig, rc9 |
| Logging |
Custom logger implementations |
pino, consola, winston |
| HTTP Client |
Custom fetch wrappers |
ofetch, ky, got |
| Retry Logic |
Custom retry loops |
p-retry, async-retry |
| Debounce/Throttle |
Custom implementations |
lodash-es (specific imports), perfect-debounce |
| Deep Clone/Merge |
Custom recursive functions |
klona, defu, deepmerge-ts |
| Type Guards |
Repetitive type checks |
typeguard, ts-is |
| UUID/ID Generation |
Custom ID generators |
nanoid, ulid, uuid |
| Hashing |
Custom hash implementations |
ohash, hash-sum |
| File Watching |
Custom fs.watch wrappers |
chokidar, watchlist |
| Glob Patterns |
Custom glob matching |
tinyglobby, fast-glob, picomatch |
| JSON Parsing |
Custom streaming JSON |
@streamparser/json, stream-json |
| JSONL/NDJSON |
Custom line-by-line parsing |
ndjson, jsonlines |
| String Utils |
Custom case conversion, trim |
scule, change-case |
| Async Utilities |
Custom promise helpers |
p-* packages (p-limit, p-map, p-queue) |
| Schema Generation |
Custom type-to-schema |
typebox, zod-to-json-schema |
| Diff/Patch |
Custom diff algorithms |
diff, fast-diff, json-diff |
| Template Strings |
Custom template parsing |
handlebars, mustache, eta |
| Caching |
Custom cache implementations |
lru-cache, quick-lru, keyv |
| Rate Limiting |
Custom rate limiters |
p-throttle, limiter, bottleneck |
Bun-Specific Considerations
Bun provides built-in alternatives for some patterns:
| Pattern |
Bun Built-in |
External Library |
| Glob |
Bun.glob() |
Not needed |
| File I/O |
Bun.file(), Bun.write() |
Not needed |
| Hashing |
Bun.hash(), Bun.CryptoHasher |
Not needed |
| SQLite |
bun:sqlite |
Not needed |
| Test Runner |
bun:test |
Not needed |
| Shell Commands |
Bun.spawn(), Bun.$ |
Not needed |
Audit Checklist
When auditing code, look for:
1. Utility Functions (High Priority)
// RED FLAG: Custom implementations of common utilities
function deepClone(obj) { ... }
function debounce(fn, delay) { ... }
function retry(fn, maxAttempts) { ... }
function generateId() { return Math.random()... }
2. Error Handling Patterns (High Priority)
// RED FLAG: Custom Result type
type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };
// BETTER: Use neverthrow
import { Result, ok, err } from 'neverthrow';
3. Validation Logic (Medium Priority)
// RED FLAG: Manual validation
function validateEmail(email: string): boolean {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}
// BETTER: Use zod
const emailSchema = z.string().email();
4. Date/Time Operations (Medium Priority)
// RED FLAG: Custom date formatting
function formatDate(date: Date): string {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
...
}
// BETTER: Use date-fns
import { format } from 'date-fns';
format(date, 'yyyy-MM-dd');
5. Async Patterns (Medium Priority)
// RED FLAG: Custom promise utilities
async function promisePool(tasks, concurrency) { ... }
async function withTimeout(promise, ms) { ... }
// BETTER: Use p-* packages
import pLimit from 'p-limit';
import pTimeout from 'p-timeout';
Replacement Strategy
Phase 1: Audit
- Scan for custom utility functions
- Identify patterns matching library functionality
- Assess replacement difficulty
- Prioritize by impact and risk
Phase 2: Plan
For each replacement:
- Identify all usages of custom implementation
- Select appropriate library
- Plan migration approach (big bang vs incremental)
- Identify test coverage requirements
Phase 3: Replace (Concurrent Execution)
Parallelizable replacements (no shared dependencies):
- Different utility functions in separate files
- Independent module replacements
Sequential replacements (shared dependencies):
- Core types used across modules
- Shared validation schemas
Phase 4: Verify
- Run type checking
- Run all tests
- Review changes
- Verify no regressions
Difficulty Assessment
Easy Replacements
- Drop-in function replacement
- Same or compatible API
- No type changes needed
- Example:
generateId() -> nanoid()
Medium Replacements
- API differences require minor refactoring
- Some type adjustments needed
- Limited scope of changes
- Example: Custom validation -> Zod schemas
Hard Replacements
- Significant API differences
- Type system changes
- Wide usage across codebase
- Example: Custom Result type -> neverthrow
Testing Considerations
Before Replacement
- Ensure existing tests pass
- Identify test coverage gaps
- Document expected behavior
During Replacement
- Keep tests passing incrementally
- Add tests for edge cases
- Verify library handles all cases
After Replacement
- Full test suite must pass
- Add integration tests if needed
- Performance comparison if relevant
References
Converted and distributed by TomeVault — claim your Tome and manage your conversions.
1---2name: lib-replacement3description: Use when auditing codebase for custom implementations that can be replaced with well-known libraries. Provides replacement patterns, audit checklist, and migration strategies.4---56# Library Replacement Skill78This skill provides guidelines for finding redundant custom implementations and replacing them with well-known libraries.910## Purpose1112Identify custom implementations that:13- Duplicate functionality available in well-known libraries14- Are harder to maintain than library equivalents15- May have bugs that libraries have already solved16- Lack the testing/documentation of established libraries1718## When to Apply1920Apply this skill when:21- Auditing codebase for technical debt22- Refactoring for maintainability23- Reducing custom code footprint24- Standardizing on ecosystem best practices2526## Common Replacement Patterns2728### Pattern Categories2930| Category | Custom Implementation Signs | Recommended Libraries |31|----------|----------------------------|----------------------|32| Result/Error Handling | Custom Result type, ok/err pattern | `neverthrow`, `ts-results`, `effect` |33| Validation | Custom validate functions, manual checks | `zod`, `valibot`, `arktype` |34| Date/Time | Custom date parsing/formatting | `date-fns`, `dayjs`, `luxon` |35| Path Operations | Custom path manipulation | `pathe`, `upath` (cross-platform) |36| CLI Parsing | Custom argument parsing | `commander`, `yargs`, `citty` |37| Configuration | Custom config loading | `c12`, `cosmiconfig`, `rc9` |38| Logging | Custom logger implementations | `pino`, `consola`, `winston` |39| HTTP Client | Custom fetch wrappers | `ofetch`, `ky`, `got` |40| Retry Logic | Custom retry loops | `p-retry`, `async-retry` |41| Debounce/Throttle | Custom implementations | `lodash-es` (specific imports), `perfect-debounce` |42| Deep Clone/Merge | Custom recursive functions | `klona`, `defu`, `deepmerge-ts` |43| Type Guards | Repetitive type checks | `typeguard`, `ts-is` |44| UUID/ID Generation | Custom ID generators | `nanoid`, `ulid`, `uuid` |45| Hashing | Custom hash implementations | `ohash`, `hash-sum` |46| File Watching | Custom fs.watch wrappers | `chokidar`, `watchlist` |47| Glob Patterns | Custom glob matching | `tinyglobby`, `fast-glob`, `picomatch` |48| JSON Parsing | Custom streaming JSON | `@streamparser/json`, `stream-json` |49| JSONL/NDJSON | Custom line-by-line parsing | `ndjson`, `jsonlines` |50| String Utils | Custom case conversion, trim | `scule`, `change-case` |51| Async Utilities | Custom promise helpers | `p-*` packages (p-limit, p-map, p-queue) |52| Schema Generation | Custom type-to-schema | `typebox`, `zod-to-json-schema` |53| Diff/Patch | Custom diff algorithms | `diff`, `fast-diff`, `json-diff` |54| Template Strings | Custom template parsing | `handlebars`, `mustache`, `eta` |55| Caching | Custom cache implementations | `lru-cache`, `quick-lru`, `keyv` |56| Rate Limiting | Custom rate limiters | `p-throttle`, `limiter`, `bottleneck` |5758### Bun-Specific Considerations5960Bun provides built-in alternatives for some patterns:6162| Pattern | Bun Built-in | External Library |63|---------|--------------|------------------|64| Glob | `Bun.glob()` | Not needed |65| File I/O | `Bun.file()`, `Bun.write()` | Not needed |66| Hashing | `Bun.hash()`, `Bun.CryptoHasher` | Not needed |67| SQLite | `bun:sqlite` | Not needed |68| Test Runner | `bun:test` | Not needed |69| Shell Commands | `Bun.spawn()`, `Bun.$` | Not needed |7071## Audit Checklist7273When auditing code, look for:7475### 1. Utility Functions (High Priority)7677```typescript78// RED FLAG: Custom implementations of common utilities79function deepClone(obj) { ... }80function debounce(fn, delay) { ... }81function retry(fn, maxAttempts) { ... }82function generateId() { return Math.random()... }83```8485### 2. Error Handling Patterns (High Priority)8687```typescript88// RED FLAG: Custom Result type89type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };9091// BETTER: Use neverthrow92import { Result, ok, err } from 'neverthrow';93```9495### 3. Validation Logic (Medium Priority)9697```typescript98// RED FLAG: Manual validation99function validateEmail(email: string): boolean {100 return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);101}102103// BETTER: Use zod104const emailSchema = z.string().email();105```106107### 4. Date/Time Operations (Medium Priority)108109```typescript110// RED FLAG: Custom date formatting111function formatDate(date: Date): string {112 const year = date.getFullYear();113 const month = String(date.getMonth() + 1).padStart(2, '0');114 ...115}116117// BETTER: Use date-fns118import { format } from 'date-fns';119format(date, 'yyyy-MM-dd');120```121122### 5. Async Patterns (Medium Priority)123124```typescript125// RED FLAG: Custom promise utilities126async function promisePool(tasks, concurrency) { ... }127async function withTimeout(promise, ms) { ... }128129// BETTER: Use p-* packages130import pLimit from 'p-limit';131import pTimeout from 'p-timeout';132```133134## Replacement Strategy135136### Phase 1: Audit1371381. Scan for custom utility functions1392. Identify patterns matching library functionality1403. Assess replacement difficulty1414. Prioritize by impact and risk142143### Phase 2: Plan144145For each replacement:1461. Identify all usages of custom implementation1472. Select appropriate library1483. Plan migration approach (big bang vs incremental)1494. Identify test coverage requirements150151### Phase 3: Replace (Concurrent Execution)152153Parallelizable replacements (no shared dependencies):154- Different utility functions in separate files155- Independent module replacements156157Sequential replacements (shared dependencies):158- Core types used across modules159- Shared validation schemas160161### Phase 4: Verify1621631. Run type checking1642. Run all tests1653. Review changes1664. Verify no regressions167168## Difficulty Assessment169170### Easy Replacements171172- Drop-in function replacement173- Same or compatible API174- No type changes needed175- Example: `generateId()` -> `nanoid()`176177### Medium Replacements178179- API differences require minor refactoring180- Some type adjustments needed181- Limited scope of changes182- Example: Custom validation -> Zod schemas183184### Hard Replacements185186- Significant API differences187- Type system changes188- Wide usage across codebase189- Example: Custom Result type -> neverthrow190191## Testing Considerations192193### Before Replacement194195- Ensure existing tests pass196- Identify test coverage gaps197- Document expected behavior198199### During Replacement200201- Keep tests passing incrementally202- Add tests for edge cases203- Verify library handles all cases204205### After Replacement206207- Full test suite must pass208- Add integration tests if needed209- Performance comparison if relevant210211## References212213- [neverthrow - Type-Safe Errors](https://github.com/supermacro/neverthrow)214- [zod - TypeScript-first schema validation](https://zod.dev/)215- [date-fns - Modern date utility library](https://date-fns.org/)216- [Sindre Sorhus's p-* packages](https://github.com/sindresorhus?tab=repositories&q=p-)217- [unjs packages](https://unjs.io/) - High-quality JS utilities218219---220> Converted and distributed by [TomeVault](https://tomevault.io/claim/tacogips) — claim your Tome and manage your conversions.221<!-- tomevault:4.0:skill_md:2026-04-15 -->