@hyperpackai/helpers
v0.3.0
Published
Hyperion Helpers — zero-dependency, tree-shakable utility library for TypeScript. String, number, date, array, object, validation, browser, storage, security, async, functional, and AI helpers.
Maintainers
Readme
@hyperpackai/helpers
Zero-dependency, tree-shakable utility library for TypeScript. Every helper is implemented with native APIs only — no lodash, no date-fns, no external packages.
Features
- Zero runtime dependencies — native APIs only, no third-party packages
- TypeScript-first — every function fully typed with JSDoc
- SSR-safe — all browser-only helpers guard with
typeof window - Tree-shakable — subpath exports for each module category
- ESM-only — NodeNext module resolution,
.jsextensions in imports - Banking-grade security — AES-GCM 256 encryption, PBKDF2 key derivation, Web Crypto API
Installation
npm install @hyperpackai/helpersUsage
Import from the root (convenience)
import { capitalize, clamp, uuid, retry } from "@hyperpackai/helpers";Import from subpaths (optimal tree-shaking)
import { capitalize, slugify } from "@hyperpackai/helpers/string";
import { clamp, formatCurrency } from "@hyperpackai/helpers/number";
import { formatDate, addDays } from "@hyperpackai/helpers/date";
import { unique, groupBy, sortBy } from "@hyperpackai/helpers/array";
import { deepClone, deepMerge, isEqual } from "@hyperpackai/helpers/object";
import { isEmail, isURL, isEmpty } from "@hyperpackai/helpers/validation";
import { buildUrl, getQueryParam } from "@hyperpackai/helpers/url";
import { hexToRgb, isDarkColor } from "@hyperpackai/helpers/color";
import { sanitize, uuid, hash, encrypt, decrypt } from "@hyperpackai/helpers/security";
import { retry, debounce, throttle, timeout } from "@hyperpackai/helpers/async";
import { compose, pipe, memoize, once } from "@hyperpackai/helpers/functional";
import { featureFlag, versionCompare, appHealth } from "@hyperpackai/helpers/enterprise";
import { extractJson, cleanLLMResponse, countTokensEstimate } from "@hyperpackai/helpers/ai";
import { logger, measurePerformance, benchmark } from "@hyperpackai/helpers/dev";Modules
string — 15 functions
capitalize("hello world") // "Hello world"
uncapitalize("Hello") // "hello"
camelCase("hello-world") // "helloWorld"
pascalCase("hello-world") // "HelloWorld"
kebabCase("helloWorld") // "hello-world"
snakeCase("helloWorld") // "hello_world"
titleCase("hello world") // "Hello World"
truncate("Hello World", 8) // "Hello W…"
slugify("Hello World!") // "hello-world"
reverse("hello") // "olleh"
mask("4111111111111111", 4, 12) // "4111••••••••1111"
contains("Hello", "ello") // true (case-insensitive by default)
startsWith("Hello", "he", false) // true
endsWith("Hello", "LO", false) // true
removeWhitespace("h e l l o") // "hello"All functions accept string | null | undefined and return safe defaults.
number — 13 functions
clamp(15, 0, 10) // 10
round(3.14159, 2) // 3.14
floor(3.99, 1) // 3.9
ceil(3.11, 1) // 3.2
percentage(50, 200) // 25
random(1, 100) // random float in [1, 100)
randomInt(1, 10) // random integer in [1, 10]
formatNumber(1234567, "en-US") // "1,234,567"
formatCurrency(1234.56, "USD") // "$1,234.56"
between(5, 1, 10) // true
isEven(4) // true
isOdd(3) // truedate — 18 functions
today() // Date at midnight today
now() // current Date
formatDate(d, "YYYY-MM-DD") // "2024-01-15"
formatDate(d, "HH:mm:ss") // "12:30:45"
formatTime(d) // "12:30:45" via Intl
formatDateTime(d) // "Jan 15, 2024, 12:30:45 PM"
addDays(d, 7) // new Date + 7 days
subtractDays(d, 7) // new Date - 7 days
addMonths(d, 3) // new Date + 3 months
addYears(d, 1) // new Date + 1 year
diffDays(a, b) // whole days between a and b
diffMonths(a, b) // whole months between a and b
diffYears(a, b) // whole years between a and b
isToday(d) // true if date is today
isWeekend(d) // true if Saturday or Sunday
isLeapYear(2024) // trueToken format string supports: YYYY YY MM M DD D HH H mm m ss s
array — 15 functions
unique([1, 2, 2, 3]) // [1, 2, 3]
uniqueBy(users, u => u.id) // deduplicate by key
groupBy(items, i => i.type) // { a: [...], b: [...] }
sortBy(items, i => i.name) // sorted copy ascending
sortBy(items, i => i.age, "desc") // sorted copy descending
chunk([1,2,3,4,5], 2) // [[1,2],[3,4],[5]]
flatten([[1,2],[3,[4]]]) // [1,2,3,[4]]
shuffle([1,2,3,4,5]) // random order
sum([1,2,3,4]) // 10
average([1,2,3,4]) // 2.5
first([1,2,3], 2) // [1,2]
last([1,2,3], 2) // [2,3]
remove([1,2,3,4], x => x % 2 === 0) // [1,3]
insert([1,2,3], 1, 99) // [1,99,2,3]
move([1,2,3,4], 0, 2) // [2,3,1,4]object — 8 functions
deepClone(obj) // structuredClone with JSON fallback
deepMerge(target, ...sources) // recursive deep merge
pick(obj, ["a", "c"]) // { a: 1, c: 3 }
omit(obj, ["b"]) // { a: 1, c: 3 }
get(obj, "a.b.c") // nested value by dot path
set(obj, "a.b.c", 42) // new object with value set
freeze(obj) // deep Object.freeze
isEqual(a, b) // deep structural equalityvalidation — 12 functions
isEmail("[email protected]") // true
isPhone("+1 800 555 0100") // true
isURL("https://example.com") // true
isUUID("f47ac10b-58cc-4372-...") // true (v4)
isNumber(42) // true (excludes NaN, Infinity)
isString("hello") // true
isBoolean(true) // true
isArray([1,2,3]) // true
isObject({}) // true (excludes arrays, null)
isDate(new Date()) // true (excludes invalid Date)
isEmpty("") // true (also: null, [], {}, " ")
isNil(null) // true (also: undefined)browser — 10 functions
All functions are SSR-safe (no-op / return false when window is unavailable).
await copyToClipboard("text") // copies to clipboard, returns success bool
downloadBlob(blob, "file.pdf") // triggers download via anchor click
openWindow("https://example.com") // opens in new tab with noopener
printPage() // triggers window.print()
scrollToTop() // smooth scroll to top
scrollToBottom() // smooth scroll to bottom
isMobile() // true on mobile user agents
isTablet() // true on tablet user agents
isDesktop() // true when not mobile/tablet
isDarkMode() // true when prefers-color-scheme: darkstorage — 9 functions
SSR-safe wrappers around localStorage and sessionStorage. Automatically serializes/deserializes JSON.
setLocal("key", { user: "Alice" })
getLocal<User>("key") // typed retrieval
removeLocal("key")
clearLocal()
setSession("token", "abc123")
getSession<string>("token")
removeSession("token")
clearSession()
getCookie("session_id") // parses document.cookiefile — 7 functions
getFileExtension("report.pdf") // "pdf"
getFileName("path/to/report.pdf") // "report"
formatFileSize(1048576) // "1 MB"
await fileToBase64(file) // "data:image/png;base64,..."
base64ToFile("data:...", "img.png") // File instance
isImageFile(file) // true for image/* MIME types
isAllowedFileType(file, [".pdf", ".docx"]) // extension checkurl — 7 functions
buildUrl("https://api.example.com", {
path: "/v1/users",
params: { page: 2, size: 10 },
hash: "results"
})
// → "https://api.example.com/v1/users?page=2&size=10#results"
parseUrl("https://example.com:8080/path?foo=bar#hash")
// → { href, protocol, host, hostname, port, pathname, search, hash, params }
getQueryParam("https://example.com?page=2", "page") // "2"
setQueryParam("https://example.com?a=1", "b", 2) // adds b=2
removeQueryParam("https://example.com?a=1&b=2", "a") // removes a
encode("hello world") // "hello%20world"
decode("hello%20world") // "hello world"color — 6 functions
hexToRgb("#3a86ff") // { r: 58, g: 134, b: 255 }
rgbToHex({ r: 58, g: 134, b: 255 }) // "#3a86ff"
lighten("#3a86ff", 20) // lighter shade
darken("#3a86ff", 20) // darker shade
generateGradient("#ff0000", "#0000ff") // "linear-gradient(135deg, #ff0000, #0000ff)"
isDarkColor("#222222") // true (WCAG 2.1 relative luminance)security — 11 functions
uuid() // UUID v4 via crypto.randomUUID
generateToken(32) // 64-char cryptographically random hex
sanitize("<script>xss</script>") // HTML entity escaping (XSS prevention)
await hash("password", "SHA-256") // hex string (Web Crypto + Node fallback)
await encrypt("secret", "key") // AES-GCM 256 base64 ciphertext
await decrypt(ciphertext, "key") // original plaintext
maskCardNumber("4111111111111111") // "4111 **** **** 1111"
maskAccountNumber("12345678") // "12******78" style
maskIBAN("GB29NWBK60161331926819") // "GB29**************6819"
maskMobile("+14155552671") // keeps first 3 and last 2 digits
maskEmail("[email protected]") // "u***@example.com"Encryption uses AES-GCM 256 with PBKDF2 key derivation (100,000 iterations, SHA-256).
async — 8 exports
await sleep(1000) // wait 1 second
await delay(500) // alias for sleep
await retry(fetchUser, { // exponential backoff
attempts: 3,
delayMs: 1000,
backoff: 2
})
await poll(() => isReady(), { // poll until condition or timeout
intervalMs: 500,
timeoutMs: 30_000
})
const fn = debounce(search, 300) // debounced, with .cancel() and .flush()
const fn = throttle(update, 200) // throttled
await timeout(fetchData(), 5000) // rejects with TimeoutError if slow
const q = queue() // sequential task queue
await q.add(() => task1())
await q.add(() => task2())functional — 7 functions
const process = compose(trim, uppercase, addPrefix) // right-to-left
const process = pipe(addPrefix, uppercase, trim) // left-to-right
const expensiveFn = memoize(compute) // cached by first argument
const initOnce = once(initialize) // runs only the first time
identity(42) // 42
noop() // undefined
const getDB = singleton(() => new DB()) // same instance every callenterprise — 10 functions
generateCorrelationId() // "corr-lf3k2a-a1b2c3d4"
generateTraceId() // 32-char hex (W3C trace format)
generateRequestId() // "req-lf3k2a-a1b2c3"
generateTransactionId() // "txn-lf3k2a-a1b2c3d4"
environment() // "production" | "staging" | "development" | "test"
isProduction() // true when NODE_ENV=production
isDevelopment() // true when NODE_ENV=development
setFeatureFlag("new-ui", true)
featureFlag("new-ui") // true (also reads FEATURE_NEW_UI env var)
versionCompare("1.10.0", "1.9.0") // 1
versionCompare("2.0.0", "2.0.0") // 0
versionCompare("1.0.0", "2.0.0") // -1
registerHealthCheck("db", () => db.ping())
appHealth() // { status: "healthy"|"degraded"|"unhealthy", checks: {...}, uptime }ai — 6 functions
Pure text utilities for working with LLM responses. No providers, no network calls.
extractCodeBlocks(response)
// [{ language: "ts", code: "const x = 1;", raw: "```ts\n..." }]
extractMarkdown(response) // removes code fences, keeps prose
stripMarkdown(response) // plain text (removes all markdown)
countTokensEstimate(text) // ⌈length / 4⌉ token estimate
cleanLLMResponse(text) // strips "Sure!", trailing pleasantries
extractJson<MyType>(text) // first valid JSON in any formatdev — 5 functions
const log = logger("auth")
log.info("User logged in", { userId: 123 })
log.warn("Rate limit approaching")
log.error("Token expired")
log.setLevel("warn") // suppresses debug and info
debug("renderer", "frame rendered") // no-op in production
const { durationMs, result } = await measurePerformance("sort", () => arr.sort())
const stats = await benchmark("sort", () => arr.sort(), 1000)
// { name, iterations, totalMs, averageMs, opsPerSecond }
prettyPrint({ user: { id: 1 } }, "current user")Requirements
- Node.js ≥ 20
- TypeScript ≥ 5 (for consuming the package types)
- No browser polyfills required for SSR
License
MIT
