Compare commits

...

8 Commits

Author SHA1 Message Date
4dfd70f6a7 Added type helpers to isReserved
All checks were successful
Build / Publish Docs (push) Successful in 35s
Build / Build NPM Project (push) Successful in 39s
Build / Tag Version (push) Successful in 9s
2026-08-08 10:51:56 -04:00
af5054192e Added new reserved IP check
All checks were successful
Build / Publish Docs (push) Successful in 38s
Build / Build NPM Project (push) Successful in 41s
Build / Tag Version (push) Successful in 10s
2026-08-08 10:39:39 -04:00
b7df327cd5 Improved markdown parser
All checks were successful
Build / Publish Docs (push) Successful in 1m35s
Build / Build NPM Project (push) Successful in 1m45s
Build / Tag Version (push) Successful in 10s
2026-07-31 01:42:39 -04:00
aa652bd7e0 Added helpers
All checks were successful
Build / Publish Docs (push) Successful in 1m47s
Build / Build NPM Project (push) Successful in 35s
Build / Tag Version (push) Successful in 8s
2026-07-29 17:51:24 -04:00
e815126807 Added helpers
Some checks failed
Build / Tag Version (push) Has been cancelled
Build / Build NPM Project (push) Has been cancelled
Build / Publish Docs (push) Has been cancelled
2026-07-29 17:51:08 -04:00
6319f810b5 Added safty guardrails to matchAll 2026-07-29 17:42:13 -04:00
91f4abf1f1 Added size getter for cache
All checks were successful
Build / Publish Docs (push) Successful in 38s
Build / Build NPM Project (push) Successful in 44s
Build / Tag Version (push) Successful in 15s
2026-07-24 22:04:45 -04:00
f9971d7ce1 Added size getter for cache
All checks were successful
Build / Build NPM Project (push) Successful in 1m7s
Build / Publish Docs (push) Successful in 1m7s
Build / Tag Version (push) Successful in 13s
2026-07-24 21:56:08 -04:00
7 changed files with 161 additions and 89 deletions

View File

@@ -1,6 +1,6 @@
{
"name": "@ztimson/utils",
"version": "0.30.0",
"version": "0.30.6",
"description": "Utility library",
"author": "Zak Timson",
"license": "MIT",

View File

@@ -31,6 +31,8 @@ export class Cache<K extends string | number | symbol, T> {
/** Await initial loading */
loading = new Promise<void>(r => this._loading = r);
get size() { return this.store.keys().toArray().length }
/**
* Create new cache
* @param {keyof T} key Default property to use as primary key

65
src/html.ts Normal file
View File

@@ -0,0 +1,65 @@
/**
* Decode HTML escaped characters
* @param html HTML to clean up
* @returns {any}
*/
export function decodeHtml(html: string) {
return html
.replace(/&nbsp;/g, '\u00A0')
.replace(/&quot;/g, '"')
.replace(/&apos;/g, "'")
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&cent;/g, '¢')
.replace(/&pound;/g, '£')
.replace(/&yen;/g, '¥')
.replace(/&euro;/g, '€')
.replace(/&copy;/g, '©')
.replace(/&reg;/g, '®')
.replace(/&trade;/g, '™')
.replace(/&times;/g, '×')
.replace(/&divide;/g, '÷')
.replace(/&#(\d+);/g, (match, dec) => String.fromCharCode(dec))
.replace(/&#x([0-9a-fA-F]+);/g, (match, hex) => String.fromCharCode(parseInt(hex, 16)))
.replace(/&amp;/g, '&'); // Always last!
}
/**
* Parse markdown headers
*
* **NOTE: frontmatter parsing only works 2 layers deep**
*
* @param {string} content
* @returns {{meta: any, content: string} | {meta: {}, content: string}}
*/
export function parseMarkdown(content: string) {
const match = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
if (!match) return {meta: {}, content};
const meta: any = {};
let currentParent: string | null = null;
for (const rawLine of match[1].split('\n')) {
if (!rawLine.trim()) continue;
const indented = /^\s+/.test(rawLine);
const line = rawLine.trim();
const colonIdx = line.indexOf(':');
if (colonIdx === -1) continue;
const key = line.slice(0, colonIdx).trim();
const value = line.slice(colonIdx + 1).trim();
let parsed: any = value;
try { parsed = JSON.parse(value); } catch {}
if (!indented) {
currentParent = value === '' ? key : null;
if (value === '') meta[key] = {};
else meta[key] = parsed;
} else if (currentParent) {
meta[currentParent][key] = parsed;
}
}
return {meta, content: match[2].trim()};
}

View File

@@ -7,10 +7,12 @@ export * from './cache';
export * from './color';
export * from './csv';
export * from './database';
export * from './files';
export * from './emitter';
export * from './errors';
export * from './files';
export * from './html';
export * from './http';
export * from './ip';
export * from './json';
export * from './jwt';
export * from './logger';

77
src/ip.ts Normal file
View File

@@ -0,0 +1,77 @@
/**
* Check if IP address falls within any of the given CIDR ranges
* @param {string} ip IPV4 to check (192.168.0.12)
* @param {...string} cidrs IP ranges to check against (example: 192.168.0.0/24)
* @returns {boolean} Whether IP address is within any range
*/
export function matchesCidr(ip: string, ...cidrs: string[]): boolean {
if (!ip) return false;
if (!cidrs.length) return true;
const ipToInt = (str: string) => str.split('.')
.reduce((int, octet) => (int << 8) + parseInt(octet), 0) >>> 0;
return cidrs.some(cidr => {
if (!cidr) return true;
if (!cidr.includes('/')) return ip === cidr; // Single IP
const [range, bits] = cidr.split('/');
const mask = ~(2 ** (32 - parseInt(bits)) - 1);
return (ipToInt(ip) & mask) === (ipToInt(range) & mask);
});
}
/**
* Convert IPv6 to v4 because who uses that, NAT4Life
* @param {string} ip IPv6 address, e.g. 2001:0db8:85a3:0000:0000:8a2e:0370:7334
* @returns {string | null} IPv4 address, e.g. 172.16.58.3
*/
export function ipV6ToV4(ip: string) {
if(!ip) return null;
const ipv4 = ip.split(':').splice(-1)[0];
if(ipv4 == '1') return '127.0.0.1';
return ipv4;
}
/**
* @deprecated Use isReserved
*
* Check if IP is reserved, e.g. localhost, private IPs, etc.
* @param {string} ip
* @returns {boolean}
*/
export function reservedIp(ip: string): boolean {
if(ip == 'localhost' || ip == '127.0.0.1') return true;
return /\b(10\.(?:[0-9]{1,3}\.){2}[0-9]{1,3})\b|\b(172\.(?:1[6-9]|2[0-9]|3[0-1])\.(?:[0-9]{1,3}\.)[0-9]{1,3})\b|\b(192\.168\.(?:[0-9]{1,3}\.)[0-9]{1,3})\b/.test(ip);
}
/**
* Check if IP is within a reserved range
* @param {string} ip
* @returns {null | 'Invalid' | 'Host' | 'Loopback' | 'Private (Class A)' | 'Private (Class B)' | 'Link-Local' | 'IETF Protocol Assignments' | 'Documentation (TEST-NET-1)' | 'Benchmarking' | 'Documentation (TEST-NET-2)' | 'Documentation (TEST-NET-3)' | 'Multicast' | 'Reserved (Class E)'} null if public, class name if reserved
*/
export function isReserved(ip: string): null | 'Invalid' | 'Host' | 'Loopback' | 'Private (Class A)' | 'Private (Class B)' | 'Link-Local' | 'IETF Protocol Assignments' | 'Documentation (TEST-NET-1)' | 'Benchmarking' | 'Documentation (TEST-NET-2)' | 'Documentation (TEST-NET-3)' | 'Multicast' | 'Reserved (Class E)' {
const ipToNumber = (ip: string) => {
return ip.split('.').reduce((acc: number, octet: string) => (acc << 8) + parseInt(octet, 10), 0) >>> 0;
};
const ipNum = ipToNumber(ip);
if (ipNum === null) return 'Invalid';
const reserved = [
{ name: "Host", start: ipToNumber("0.0.0.0"), end: ipToNumber("0.255.255.255") },
{ name: "Loopback", start: ipToNumber("127.0.0.0"), end: ipToNumber("127.255.255.255") },
{ name: "Private (Class A)", start: ipToNumber("10.0.0.0"), end: ipToNumber("10.255.255.255") },
{ name: "CGNAT", start: ipToNumber("100.64.0.0"), end: ipToNumber("100.127.255.255") },
{ name: "Private (Class B)", start: ipToNumber("172.16.0.0"), end: ipToNumber("172.31.255.255") },
{ name: "Private (Class C)", start: ipToNumber("192.168.0.0"), end: ipToNumber("192.168.255.255") },
{ name: "Link-Local", start: ipToNumber("169.254.0.0"), end: ipToNumber("169.254.255.255") },
{ name: "IETF Protocol Assignments", start: ipToNumber("192.0.0.0"), end: ipToNumber("192.0.0.255") },
{ name: "Documentation (TEST-NET-1)", start: ipToNumber("192.0.2.0"), end: ipToNumber("192.0.2.255") },
{ name: "Benchmarking", start: ipToNumber("198.18.0.0"), end: ipToNumber("198.19.255.255") },
{ name: "Documentation (TEST-NET-2)", start: ipToNumber("198.51.100.0"), end: ipToNumber("198.51.100.255") },
{ name: "Documentation (TEST-NET-3)", start: ipToNumber("203.0.113.0"), end: ipToNumber("203.0.113.255") },
{ name: "Multicast", start: ipToNumber("224.0.0.0"), end: ipToNumber("239.255.255.255") },
{ name: "Reserved (Class E)", start: ipToNumber("240.0.0.0"), end: ipToNumber("255.255.255.255") }
];
const match = reserved.find(r => ipNum >= r.start && ipNum <= r.end);
return match ? <any>match.name : null;
}

View File

@@ -76,46 +76,6 @@ export function gravatar(email: string, def='mp') {
return `https://www.gravatar.com/avatar/${md5(email)}?d=${def}`;
}
/**
* Check if IP address falls within CIDR range
* @param {string} ip IPV4 to check (192.168.0.12)
* @param {string} cidr IP range to check against (example: 192.168.0.0/24)
* @returns {boolean} Whether IP address is within range
*/
export function matchesCidr(ip: string, cidr: string): boolean {
if(!cidr) return true;
if(!ip) return false;
if(!cidr?.includes('/')) return ip === cidr; // Single IP
const [range, bits] = cidr.split('/');
const mask = ~(2 ** (32 - parseInt(bits)) - 1);
const ipToInt = (str: string) => str.split('.')
.reduce((int, octet) => (int << 8) + parseInt(octet), 0) >>> 0;
return (ipToInt(ip) & mask) === (ipToInt(range) & mask);
}
/**
* Convert IPv6 to v4 because who uses that, NAT4Life
* @param {string} ip IPv6 address, e.g. 2001:0db8:85a3:0000:0000:8a2e:0370:7334
* @returns {string | null} IPv4 address, e.g. 172.16.58.3
*/
export function ipV6ToV4(ip: string) {
if(!ip) return null;
const ipv4 = ip.split(':').splice(-1)[0];
if(ipv4 == '1') return '127.0.0.1';
return ipv4;
}
/**
* Check if IP is reserved, e.g. localhost, private IPs, etc.
* @param {string} ip
* @returns {boolean}
*/
export function reservedIp(ip: string): boolean {
if(ip == 'localhost' || ip == '127.0.0.1') return true;
return /\b(10\.(?:[0-9]{1,3}\.){2}[0-9]{1,3})\b|\b(172\.(?:1[6-9]|2[0-9]|3[0-1])\.(?:[0-9]{1,3}\.)[0-9]{1,3})\b|\b(192\.168\.(?:[0-9]{1,3}\.)[0-9]{1,3})\b/.test(ip);
}
/**
* Represents a function that listens for events and handles them accordingly.
*

View File

@@ -27,32 +27,6 @@ export function camelCase(str?: string): string {
return pascal.charAt(0).toLowerCase() + pascal.slice(1);
}
/**
* Decode HTML escaped characters
* @param html HTML to clean up
* @returns {any}
*/
export function decodeHtml(html: string) {
return html
.replace(/&nbsp;/g, '\u00A0')
.replace(/&quot;/g, '"')
.replace(/&apos;/g, "'")
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&cent;/g, '¢')
.replace(/&pound;/g, '£')
.replace(/&yen;/g, '¥')
.replace(/&euro;/g, '€')
.replace(/&copy;/g, '©')
.replace(/&reg;/g, '®')
.replace(/&trade;/g, '™')
.replace(/&times;/g, '×')
.replace(/&divide;/g, '÷')
.replace(/&#(\d+);/g, (match, dec) => String.fromCharCode(dec))
.replace(/&#x([0-9a-fA-F]+);/g, (match, hex) => String.fromCharCode(parseInt(hex, 16)))
.replace(/&amp;/g, '&'); // Always last!
}
/**
* Convert number of bytes into a human-readable size
*
@@ -125,7 +99,6 @@ export function kebabCase(str?: string): string {
return wordSegments(str).map(w => w.toLowerCase()).join("-");
}
/**
* Add padding to string
*
@@ -256,18 +229,14 @@ export function strSplice(str: string, start: number, deleteCount: number, inser
return before + insert + after;
}
function titleCase(str: string) {
// Normalize separators: replace underscores and hyphens with spaces
let normalizedStr = str.replace(/(_|-)/g, ' ');
// Handle CamelCase/PascalCase boundaries: insert a space before capital letters
normalizedStr = normalizedStr.replace(/([a-z])([A-Z])/g, '$1 $2');
// Lowercase the whole string, split by any whitespace, and capitalize each word
let words = normalizedStr.toLowerCase().split(/\s+/).filter(Boolean);
const titledWords = words.map(word => {
if (word.length === 0) return '';
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
});
return titledWords.join(' ');
/**
* Converts text to Title Case
*/
export function titleCase(str?: string): string {
if(!str) return '';
return wordSegments(str)
.map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())
.join(' ');
}
/**
@@ -280,19 +249,16 @@ function titleCase(str: string) {
* @return {RegExpExecArray[]} Found matches.
*/
export function matchAll(value: string, regex: RegExp | string): RegExpExecArray[] {
if(typeof regex === 'string') {
regex = new RegExp(regex, 'g');
}
// https://stackoverflow.com/a/60290199
if(!regex.global) {
throw new TypeError('Regular expression must be global.');
}
if(typeof regex === 'string') regex = new RegExp(regex, 'g');
if(!regex.global) throw new TypeError('Regular expression must be global.');
let ret: RegExpExecArray[] = [];
let match: RegExpExecArray | null;
while((match = regex.exec(value)) !== null) {
ret.push(match);
if(match[0].length === 0) {
regex.lastIndex++;
}
}
return ret;