Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d0af3a63bc | |||
| bf73d2670b | |||
| 361613f507 | |||
| 681c89d5af | |||
| 0142904414 | |||
| ddaf5c9957 | |||
| 18261dc5da | |||
| e32e5d6f71 | |||
| 41bc5e7eb5 | |||
| fda92e46d5 | |||
| 1be2c1118f | |||
| ead8fcffc0 |
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ztimson/utils",
|
||||
"version": "0.28.6",
|
||||
"version": "0.28.17",
|
||||
"description": "Utility library",
|
||||
"author": "Zak Timson",
|
||||
"license": "MIT",
|
||||
|
||||
67
src/color.ts
67
src/color.ts
@@ -1,12 +1,73 @@
|
||||
import {dec2Hex} from './math.ts';
|
||||
|
||||
/**
|
||||
* Determine if either black or white provides more contrast to the provided color
|
||||
* @param {string} background Color to compare against
|
||||
* @param {string} color Color to compare against
|
||||
* @return {"white" | "black"} Color with the most contrast
|
||||
*/
|
||||
export function contrast(background: string): 'white' | 'black' {
|
||||
const exploded = background?.match(background.length >= 6 ? /[0-9a-fA-F]{2}/g : /[0-9a-fA-F]/g);
|
||||
export function contrast(color: string): 'white' | 'black' {
|
||||
const exploded = color?.match(color.length >= 6 ? /[0-9a-fA-F]{2}/g : /[0-9a-fA-F]/g);
|
||||
if(!exploded || exploded?.length < 3) return 'black';
|
||||
const [r, g, b] = exploded.map(hex => parseInt(hex.length == 1 ? `${hex}${hex}` : hex, 16));
|
||||
const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
|
||||
return luminance > 0.5 ? 'black' : 'white';
|
||||
}
|
||||
|
||||
export function hex2Int(hex: string): {r: number, g: number, b: number} {
|
||||
let r = 0, g = 0, b = 0;
|
||||
if (hex.length === 4) {
|
||||
r = parseInt(hex[1] + hex[1], 16);
|
||||
g = parseInt(hex[2] + hex[2], 16);
|
||||
b = parseInt(hex[3] + hex[3], 16);
|
||||
} else {
|
||||
r = parseInt(hex.slice(1, 3), 16);
|
||||
g = parseInt(hex.slice(3, 5), 16);
|
||||
b = parseInt(hex.slice(5, 7), 16);
|
||||
}
|
||||
return {r, g, b};
|
||||
}
|
||||
|
||||
export function hue2rgb(p: number, q: number, t: number): number {
|
||||
if(t < 0) t += 1;
|
||||
if(t > 1) t -= 1;
|
||||
if(t < 1 / 6) return p + (q - p) * 6 * t;
|
||||
if(t < 1 / 2) return q;
|
||||
if(t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
|
||||
return p;
|
||||
}
|
||||
|
||||
export function int2Hex(r: number, g: number, b: number) {
|
||||
return '#' + dec2Hex(r) + dec2Hex(g) + dec2Hex(b);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adjusts the darkness of a hex color.
|
||||
* @param {string} hex - The hex color (e.g., '#ff0000').
|
||||
* @param {number} amount - A value between -1 (black) and 1 (white)
|
||||
*/
|
||||
export function shadeColor(hex: string, amount: number) {
|
||||
let {r, g, b} = hex2Int(hex);
|
||||
r /= 255; g /= 255; b /= 255;
|
||||
const max = Math.max(r, g, b), min = Math.min(r, g, b);
|
||||
let h, s, l = (max + min) / 2;
|
||||
|
||||
if (max === min) {
|
||||
h = s = 0;
|
||||
} else {
|
||||
const d = max - min;
|
||||
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
|
||||
switch (max) {
|
||||
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
|
||||
case g: h = (b - r) / d + 2; break;
|
||||
case b: h = (r - g) / d + 4; break;
|
||||
default: h = 0; break;
|
||||
}
|
||||
h /= 6;
|
||||
}
|
||||
|
||||
// Adjust Lightness
|
||||
l = Math.max(0, Math.min(1, l + amount));
|
||||
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
|
||||
const p = 2 * l - q;
|
||||
return int2Hex(hue2rgb(p, q, h + 1/3), hue2rgb(p, q, h), hue2rgb(p, q, h - 1/3));
|
||||
};
|
||||
|
||||
47
src/csv.ts
47
src/csv.ts
@@ -14,41 +14,55 @@ import {LETTER_LIST} from './string.ts';
|
||||
export function fromCsv<T = any>(csv: string, hasHeaders = true): T[] {
|
||||
function parseLine(line: string): (string | null)[] {
|
||||
const columns: string[] = [];
|
||||
let current = '', inQuotes = false;
|
||||
let current = '', inQuotes = false, quoteChar: string | null = null;
|
||||
for (let i = 0; i < line.length; i++) {
|
||||
const char = line[i];
|
||||
const nextChar = line[i + 1];
|
||||
if (char === '"') {
|
||||
if (inQuotes && nextChar === '"') {
|
||||
current += '"'; // Handle escaped quotes
|
||||
if ((char === '"' || char === "'") && !inQuotes) {
|
||||
inQuotes = true;
|
||||
quoteChar = char;
|
||||
} else if (char === quoteChar && inQuotes) {
|
||||
if (nextChar === quoteChar) {
|
||||
current += quoteChar; // Handle escaped quotes
|
||||
i++;
|
||||
} else inQuotes = !inQuotes;
|
||||
} else {
|
||||
inQuotes = false;
|
||||
quoteChar = null;
|
||||
}
|
||||
} else if (char === ',' && !inQuotes) {
|
||||
columns.push(current.trim()); // Trim column values
|
||||
columns.push(current.trim());
|
||||
current = '';
|
||||
} else current += char;
|
||||
}
|
||||
columns.push(current.trim()); // Trim last column value
|
||||
return columns.map(col => col.replace(/^"|"$/g, '').replace(/""/g, '"'));
|
||||
columns.push(current.trim());
|
||||
return columns.map(col => {
|
||||
// Remove surrounding quotes (both " and ')
|
||||
col = col.replace(/^["']|["']$/g, '');
|
||||
// Unescape doubled quotes
|
||||
return col.replace(/""/g, '"').replace(/''/g, "'");
|
||||
});
|
||||
}
|
||||
|
||||
// Normalize line endings and split rows
|
||||
const rows = [];
|
||||
let currentRow = '', inQuotes = false;
|
||||
for (const char of csv.replace(/\r\n/g, '\n')) { // Normalize \r\n to \n
|
||||
if (char === '"') inQuotes = !inQuotes;
|
||||
let currentRow = '', inQuotes = false, quoteChar: string | null = null;
|
||||
for (const char of csv.replace(/\r\n/g, '\n')) {
|
||||
if ((char === '"' || char === "'") && !inQuotes) {
|
||||
inQuotes = true;
|
||||
quoteChar = char;
|
||||
} else if (char === quoteChar && inQuotes) {
|
||||
inQuotes = false;
|
||||
quoteChar = null;
|
||||
}
|
||||
if (char === '\n' && !inQuotes) {
|
||||
rows.push(currentRow.trim()); // Trim row
|
||||
rows.push(currentRow.trim());
|
||||
currentRow = '';
|
||||
} else currentRow += char;
|
||||
}
|
||||
if (currentRow) rows.push(currentRow.trim()); // Trim last row
|
||||
if (currentRow) rows.push(currentRow.trim());
|
||||
|
||||
// Extract headers
|
||||
let headers: any = hasHeaders ? rows.splice(0, 1)[0] : null;
|
||||
if (headers) headers = headers.match(/(?:[^,"']+|"(?:[^"]|"")*"|'(?:[^']|'')*')+/g)?.map((h: any) => h.trim());
|
||||
|
||||
// Parse rows
|
||||
return <T[]>rows.map(r => {
|
||||
const props = parseLine(r);
|
||||
const h = headers || (Array(props.length).fill(null).map((_, i) => {
|
||||
@@ -65,7 +79,6 @@ export function fromCsv<T = any>(csv: string, hasHeaders = true): T[] {
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Convert an array of objects to a CSV string
|
||||
*
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
export * from 'var-persist';
|
||||
|
||||
export * from './arg-parser';
|
||||
export * from './array';
|
||||
export * from './aset';
|
||||
@@ -21,5 +23,6 @@ export * from './search';
|
||||
export * from './string';
|
||||
export * from './template';
|
||||
export * from './time';
|
||||
export * from './tts';
|
||||
export * from './types';
|
||||
export * from 'var-persist';
|
||||
export * from './xml';
|
||||
|
||||
@@ -30,6 +30,10 @@ export function dec2Frac(num: number, maxDen=1000): string {
|
||||
(numerator ? numerator + '/' + closest.d : '');
|
||||
}
|
||||
|
||||
export function dec2Hex(num: number): string {
|
||||
const hex = Math.round(num * 255).toString(16);
|
||||
return hex.length === 1 ? '0' + hex : hex;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert fraction to decimal number
|
||||
@@ -42,7 +46,7 @@ export function dec2Frac(num: number, maxDen=1000): string {
|
||||
* @param {string} frac Fraction to convert
|
||||
* @return {number} Faction as a decimal
|
||||
*/
|
||||
export function fracToDec(frac: string) {
|
||||
export function frac2Dec(frac: string) {
|
||||
let split = frac.split(' ');
|
||||
const whole = split.length == 2 ? Number(split[0]) : 0;
|
||||
split = (<string>split.pop()).split('/');
|
||||
|
||||
17
src/misc.ts
17
src/misc.ts
@@ -76,6 +76,23 @@ 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
|
||||
|
||||
@@ -27,6 +27,31 @@ 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(/ /g, '\u00A0')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, "'")
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/¢/g, '¢')
|
||||
.replace(/£/g, '£')
|
||||
.replace(/¥/g, '¥')
|
||||
.replace(/€/g, '€')
|
||||
.replace(/©/g, '©')
|
||||
.replace(/®/g, '®')
|
||||
.replace(/™/g, '™')
|
||||
.replace(/×/g, '×')
|
||||
.replace(/÷/g, '÷')
|
||||
.replace(/&#(\d+);/g, (match, dec) => String.fromCharCode(dec))
|
||||
.replace(/&#x([0-9a-fA-F]+);/g, (match, hex) => String.fromCharCode(parseInt(hex, 16)))
|
||||
.replace(/&/g, '&'); // Always last!
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert number of bytes into a human-readable size
|
||||
@@ -135,7 +160,15 @@ export function pascalCase(str?: string): string {
|
||||
.join('');
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Remove all emojis from a string
|
||||
* @param {string} str Input string with emojis
|
||||
* @returns {string} Sanitized string without emojis
|
||||
*/
|
||||
export function removeEmojis(str: string): string {
|
||||
const emojiRegex = /(?:[\u2700-\u27bf]|(?:\ud83c[\udde6-\uddff]){2}|[\ud83c[\udde6-\uddff]|[\ud83d[\ude00-\ude4f]|[\ud83d[\ude80-\udeff]|[\ud83c[\udd00-\uddff]|[\ud83d[\ude50-\ude7f]|[\u2600-\u26ff]|[\u2700-\u27bf]|[\ud83e[\udd00-\uddff]|[\ud83c[\udf00-\uffff]|[\ud83d[\ude00-\udeff]|[\ud83c[\udde6-\uddff])/g;
|
||||
return str.replace(emojiRegex, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a random hexadecimal value
|
||||
|
||||
@@ -8,7 +8,16 @@ export class TemplateError extends BadRequestError { }
|
||||
export function findTemplateVars(html: string): Record<string, any> {
|
||||
const variables = new Set<string>();
|
||||
const arrays = new Set<string>();
|
||||
const excluded = new Set<string>(['true', 'false', 'null', 'undefined']);
|
||||
const excluded = new Set([
|
||||
'let', 'const', 'var', 'function', 'if', 'while', 'do', 'this', 'typeof',
|
||||
'new', 'instanceof', 'in', 'for', 'else', 'case', 'break', 'continue',
|
||||
'switch', 'default', 'with', 'eval', 'arguments', 'void', 'delete', 'null',
|
||||
'undefined', 'true', 'false', 'async', 'await', 'try', 'catch', 'finally',
|
||||
'throw', 'return', 'yield', 'debugger', 'extends', 'import', 'export',
|
||||
'class', 'super', 'static', 'get', 'set', 'constructor', 'enum', 'implements',
|
||||
'interface', 'package', 'private', 'protected', 'public', 'abstract', 'final',
|
||||
'native', 'synchronized', 'throws', 'transient', 'volatile'
|
||||
]);
|
||||
|
||||
// Extract & exclude loop variables, mark arrays
|
||||
for (const loop of matchAll(html, /\{\{\s*?\*\s*?(.+?)\s+in\s+(.+?)\s*?}}/g)) {
|
||||
@@ -70,6 +79,7 @@ export function findTemplateVars(html: string): Record<string, any> {
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function renderTemplate(template: string, data: any, fetch?: (file: string) => Promise<string>) {
|
||||
if(!fetch) fetch = (file) => { throw new TemplateError(`Unable to fetch template: ${file}`); }
|
||||
|
||||
|
||||
148
src/tts.ts
Normal file
148
src/tts.ts
Normal file
@@ -0,0 +1,148 @@
|
||||
import {removeEmojis} from './string.ts';
|
||||
|
||||
export class TTS {
|
||||
private static readonly QUALITY_PATTERNS = ['Google', 'Microsoft', 'Samantha', 'Premium', 'Natural', 'Neural'];
|
||||
private static _errorHandlerInstalled = false;
|
||||
|
||||
private _currentUtterance: SpeechSynthesisUtterance | null = null;
|
||||
private _voicesLoaded: Promise<void>;
|
||||
private _stoppedUtterances = new WeakSet<SpeechSynthesisUtterance>();
|
||||
|
||||
private _rate: number = 1.0;
|
||||
get rate(): number { return this._rate; }
|
||||
set rate(value: number) {
|
||||
this._rate = value;
|
||||
if(this._currentUtterance) this._currentUtterance.rate = value;
|
||||
}
|
||||
|
||||
private _pitch: number = 1.0;
|
||||
get pitch(): number { return this._pitch; }
|
||||
set pitch(value: number) {
|
||||
this._pitch = value;
|
||||
if(this._currentUtterance) this._currentUtterance.pitch = value;
|
||||
}
|
||||
|
||||
private _volume: number = 1.0;
|
||||
get volume(): number { return this._volume; }
|
||||
set volume(value: number) {
|
||||
this._volume = value;
|
||||
if(this._currentUtterance) this._currentUtterance.volume = value;
|
||||
}
|
||||
|
||||
private _voice: SpeechSynthesisVoice | undefined;
|
||||
get voice(): SpeechSynthesisVoice | undefined { return this._voice; }
|
||||
set voice(value: SpeechSynthesisVoice | undefined) {
|
||||
this._voice = value;
|
||||
if(this._currentUtterance && value) this._currentUtterance.voice = value;
|
||||
}
|
||||
|
||||
constructor(config?: {rate?: number; pitch?: number; volume?: number; voice?: SpeechSynthesisVoice | null}) {
|
||||
TTS.installErrorHandler();
|
||||
this._voicesLoaded = this.initializeVoices();
|
||||
if(config) {
|
||||
if(config.rate !== undefined) this._rate = config.rate;
|
||||
if(config.pitch !== undefined) this._pitch = config.pitch;
|
||||
if(config.volume !== undefined) this._volume = config.volume;
|
||||
this._voice = config.voice === null ? undefined : (config.voice || undefined);
|
||||
}
|
||||
}
|
||||
|
||||
private static installErrorHandler(): void {
|
||||
if(this._errorHandlerInstalled) return;
|
||||
window.addEventListener('unhandledrejection', (event) => {
|
||||
if(event.reason?.error === 'interrupted' && event.reason instanceof SpeechSynthesisErrorEvent) event.preventDefault();
|
||||
});
|
||||
this._errorHandlerInstalled = true;
|
||||
}
|
||||
|
||||
private initializeVoices(): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
const voices = window.speechSynthesis.getVoices();
|
||||
if(voices.length > 0) {
|
||||
if(!this._voice) this._voice = TTS.bestVoice();
|
||||
resolve();
|
||||
} else {
|
||||
const handler = () => {
|
||||
window.speechSynthesis.removeEventListener('voiceschanged', handler);
|
||||
if(!this._voice) this._voice = TTS.bestVoice();
|
||||
resolve();
|
||||
};
|
||||
window.speechSynthesis.addEventListener('voiceschanged', handler);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static bestVoice(lang = 'en'): SpeechSynthesisVoice | undefined {
|
||||
const voices = window.speechSynthesis.getVoices();
|
||||
for (const pattern of this.QUALITY_PATTERNS) {
|
||||
const voice = voices.find(v => v.name.includes(pattern) && v.lang.startsWith(lang));
|
||||
if(voice) return voice;
|
||||
}
|
||||
return voices.find(v => v.lang.startsWith(lang));
|
||||
}
|
||||
|
||||
private static cleanText(text: string): string {
|
||||
return removeEmojis(text)
|
||||
.replace(/```[\s\S]*?```/g, ' code block ')
|
||||
.replace(/[#*_~`]/g, '');
|
||||
}
|
||||
|
||||
private createUtterance(text: string): SpeechSynthesisUtterance {
|
||||
const cleanedText = TTS.cleanText(text);
|
||||
const utterance = new SpeechSynthesisUtterance(cleanedText);
|
||||
const voice = this._voice || TTS.bestVoice();
|
||||
if(voice) utterance.voice = voice;
|
||||
utterance.rate = this._rate;
|
||||
utterance.pitch = this._pitch;
|
||||
utterance.volume = this._volume;
|
||||
return utterance;
|
||||
}
|
||||
|
||||
async speak(text: string): Promise<void> {
|
||||
if(!text.trim()) return Promise.resolve();
|
||||
await this._voicesLoaded;
|
||||
return new Promise((resolve, reject) => {
|
||||
this._currentUtterance = this.createUtterance(text);
|
||||
const utterance = this._currentUtterance;
|
||||
utterance.onend = () => {
|
||||
this._currentUtterance = null;
|
||||
resolve();
|
||||
};
|
||||
utterance.onerror = (error) => {
|
||||
this._currentUtterance = null;
|
||||
if(this._stoppedUtterances.has(utterance) && error.error === 'interrupted') resolve();
|
||||
else reject(error);
|
||||
};
|
||||
window.speechSynthesis.speak(utterance);
|
||||
});
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
if(this._currentUtterance) this._stoppedUtterances.add(this._currentUtterance);
|
||||
window.speechSynthesis.cancel();
|
||||
this._currentUtterance = null;
|
||||
}
|
||||
|
||||
speakStream(): {next: (text: string) => void, done: () => Promise<void>} {
|
||||
let buffer = '';
|
||||
let streamPromise: Promise<void> = Promise.resolve();
|
||||
const sentenceRegex = /[^.!?\n]+[.!?\n]+/g;
|
||||
return {
|
||||
next: (text: string): void => {
|
||||
buffer += text;
|
||||
const sentences = buffer.match(sentenceRegex);
|
||||
if(sentences) {
|
||||
sentences.forEach(sentence => streamPromise = this.speak(sentence.trim()));
|
||||
buffer = buffer.replace(sentenceRegex, '');
|
||||
}
|
||||
},
|
||||
done: async (): Promise<void> => {
|
||||
if(buffer.trim()) {
|
||||
streamPromise = this.speak(buffer.trim());
|
||||
buffer = '';
|
||||
}
|
||||
await streamPromise;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
155
src/xml.ts
Normal file
155
src/xml.ts
Normal file
@@ -0,0 +1,155 @@
|
||||
/**
|
||||
* Parses an XML string into a structured JavaScript object.
|
||||
* @param {string} xml - The XML string to parse
|
||||
* @returns {Object} An object with `tag`, `attributes`, and `children` properties
|
||||
*/
|
||||
export function fromXml(xml: string) {
|
||||
xml = xml.trim();
|
||||
let pos = 0;
|
||||
|
||||
function parseNode(): any {
|
||||
skipWhitespace();
|
||||
if(xml[pos] !== '<') return parseText();
|
||||
pos++; // skip <
|
||||
|
||||
if(xml[pos] === '?') {
|
||||
parseDeclaration();
|
||||
return parseNode();
|
||||
}
|
||||
|
||||
if(xml[pos] === '!') {
|
||||
parseComment();
|
||||
return parseNode();
|
||||
}
|
||||
|
||||
const tagName = parseTagName();
|
||||
const attributes = parseAttributes();
|
||||
skipWhitespace();
|
||||
|
||||
if(xml[pos] === '/' && xml[pos + 1] === '>') {
|
||||
pos += 2; // skip />
|
||||
return { tag: tagName, attributes, children: [] };
|
||||
}
|
||||
|
||||
pos++; // skip >
|
||||
const children = [];
|
||||
while(pos < xml.length) {
|
||||
skipWhitespace();
|
||||
if(xml[pos] === '<' && xml[pos + 1] === '/') {
|
||||
pos += 2; // skip </
|
||||
parseTagName(); // skip closing tag name
|
||||
skipWhitespace();
|
||||
pos++; // skip >
|
||||
break;
|
||||
}
|
||||
const child = parseNode();
|
||||
if(child) children.push(child);
|
||||
}
|
||||
return { tag: tagName, attributes, children };
|
||||
}
|
||||
|
||||
/** Parses and returns the tag name at the current position */
|
||||
function parseTagName() {
|
||||
let name = '';
|
||||
while (pos < xml.length && /[a-zA-Z0-9_:-]/.test(xml[pos])) name += xml[pos++];
|
||||
return name;
|
||||
}
|
||||
|
||||
/** Parses and returns an object containing all attributes at the current position */
|
||||
function parseAttributes() {
|
||||
const attrs: any = {};
|
||||
while (pos < xml.length) {
|
||||
skipWhitespace();
|
||||
if (xml[pos] === '>' || xml[pos] === '/') break;
|
||||
const name = parseTagName();
|
||||
skipWhitespace();
|
||||
if (xml[pos] === '=') {
|
||||
pos++;
|
||||
skipWhitespace();
|
||||
const quote = xml[pos++];
|
||||
let value = '';
|
||||
while (xml[pos] !== quote) value += xml[pos++];
|
||||
pos++; // skip closing quote
|
||||
attrs[name] = escapeXml(value, true);
|
||||
}
|
||||
}
|
||||
return attrs;
|
||||
}
|
||||
|
||||
/** Parses and returns text content, or null if empty */
|
||||
function parseText() {
|
||||
let text = '';
|
||||
while (pos < xml.length && xml[pos] !== '<') text += xml[pos++];
|
||||
text = text.trim();
|
||||
return text ? escapeXml(text, true) : null;
|
||||
}
|
||||
|
||||
/** Skips over XML declaration (<?xml ... ?>) */
|
||||
function parseDeclaration() {
|
||||
while (xml[pos] !== '>') pos++;
|
||||
pos++;
|
||||
}
|
||||
|
||||
/** Skips over XML comments (<!-- ... -->) */
|
||||
function parseComment() {
|
||||
while (!(xml[pos] === '-' && xml[pos + 1] === '-' && xml[pos + 2] === '>')) pos++;
|
||||
pos += 3;
|
||||
}
|
||||
|
||||
/** Advances position past any whitespace characters */
|
||||
function skipWhitespace() {
|
||||
while (pos < xml.length && /\s/.test(xml[pos])) pos++;
|
||||
}
|
||||
|
||||
return parseNode();
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a JavaScript object into an XML string.
|
||||
* @param {Object} obj - Object with `tag`, `attributes`, and `children` properties, or a string
|
||||
* @param {string} indent - Current indentation level (used internally for formatting)
|
||||
* @returns {string} The formatted XML string
|
||||
*/
|
||||
export function toXml(obj: any, indent = '') {
|
||||
if(typeof obj === 'string') return escapeXml(obj);
|
||||
const { tag, attributes = {}, children = [] } = obj;
|
||||
let xml = `${indent}<${tag}`;
|
||||
for (const [key, value] of Object.entries(attributes))
|
||||
xml += ` ${key}="${escapeXml(<any>value)}"`;
|
||||
if (children.length === 0) {
|
||||
xml += ' />';
|
||||
return xml;
|
||||
}
|
||||
xml += '>';
|
||||
const hasComplexChildren = children.some((c: any) => typeof c === 'object');
|
||||
for (const child of children) {
|
||||
if (hasComplexChildren) xml += '\n';
|
||||
xml += toXml(child, hasComplexChildren ? indent + ' ' : '');
|
||||
}
|
||||
if(hasComplexChildren) xml += `\n${indent}`;
|
||||
xml += `</${tag}>`;
|
||||
return xml;
|
||||
}
|
||||
|
||||
/**
|
||||
* Escapes or unescapes XML special characters.
|
||||
* @param {string} str - The string to process
|
||||
* @param {boolean} decode - If true, decodes XML entities; if false, encodes special characters
|
||||
* @returns {string} The processed string
|
||||
*/
|
||||
export function escapeXml(str: string, decode = false) {
|
||||
if(decode) {
|
||||
return str
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, "'")
|
||||
.replace(/&/g, '&');
|
||||
}
|
||||
return str
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { dec2Frac, fracToDec } from '../src';
|
||||
import { dec2Frac, frac2Dec } from '../src';
|
||||
|
||||
describe('Math Utilities', () => {
|
||||
describe('dec2Frac', () => {
|
||||
@@ -27,25 +27,25 @@ describe('Math Utilities', () => {
|
||||
|
||||
describe('fracToDec', () => {
|
||||
it('should convert mixed fraction to decimal', () => {
|
||||
expect(fracToDec('1 1/4')).toBeCloseTo(1.25);
|
||||
expect(fracToDec('2 1/2')).toBeCloseTo(2.5);
|
||||
expect(fracToDec('3 3/4')).toBeCloseTo(3.75);
|
||||
expect(frac2Dec('1 1/4')).toBeCloseTo(1.25);
|
||||
expect(frac2Dec('2 1/2')).toBeCloseTo(2.5);
|
||||
expect(frac2Dec('3 3/4')).toBeCloseTo(3.75);
|
||||
});
|
||||
|
||||
it('should convert fraction without whole part to decimal', () => {
|
||||
expect(fracToDec('3/4')).toBeCloseTo(0.75);
|
||||
expect(fracToDec('1/2')).toBeCloseTo(0.5);
|
||||
expect(fracToDec('1/10')).toBeCloseTo(0.1);
|
||||
expect(frac2Dec('3/4')).toBeCloseTo(0.75);
|
||||
expect(frac2Dec('1/2')).toBeCloseTo(0.5);
|
||||
expect(frac2Dec('1/10')).toBeCloseTo(0.1);
|
||||
});
|
||||
|
||||
it('should convert whole number fraction', () => {
|
||||
expect(fracToDec('4 0/1')).toBeCloseTo(4);
|
||||
expect(fracToDec('0/1')).toBeCloseTo(0);
|
||||
expect(frac2Dec('4 0/1')).toBeCloseTo(4);
|
||||
expect(frac2Dec('0/1')).toBeCloseTo(0);
|
||||
});
|
||||
|
||||
it('should handle zero correctly', () => {
|
||||
expect(fracToDec('0/1')).toBeCloseTo(0);
|
||||
expect(fracToDec('0 0/1')).toBeCloseTo(0);
|
||||
expect(frac2Dec('0/1')).toBeCloseTo(0);
|
||||
expect(frac2Dec('0 0/1')).toBeCloseTo(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
170
tests/xml.spec.ts
Normal file
170
tests/xml.spec.ts
Normal file
@@ -0,0 +1,170 @@
|
||||
import { toXml, fromXml } from '../src';
|
||||
|
||||
describe('XML Parser', () => {
|
||||
describe('fromXml', () => {
|
||||
it('should parse simple tag', () => {
|
||||
const xml = '<root></root>';
|
||||
const result = fromXml(xml);
|
||||
expect(result).toEqual({ tag: 'root', attributes: {}, children: [] });
|
||||
});
|
||||
|
||||
it('should parse self-closing tag', () => {
|
||||
const xml = '<item />';
|
||||
const result = fromXml(xml);
|
||||
expect(result).toEqual({ tag: 'item', attributes: {}, children: [] });
|
||||
});
|
||||
|
||||
it('should parse tag with attributes', () => {
|
||||
const xml = '<user id="1" name="someone" />';
|
||||
const result = fromXml(xml);
|
||||
expect(result).toEqual({
|
||||
tag: 'user',
|
||||
attributes: { id: '1', name: 'someone' },
|
||||
children: []
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse tag with text content', () => {
|
||||
const xml = '<email>someone@example.com</email>';
|
||||
const result = fromXml(xml);
|
||||
expect(result).toEqual({
|
||||
tag: 'email',
|
||||
attributes: {},
|
||||
children: ['someone@example.com']
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse nested tags', () => {
|
||||
const xml = '<root><child>text</child></root>';
|
||||
const result = fromXml(xml);
|
||||
expect(result).toEqual({
|
||||
tag: 'root',
|
||||
attributes: {},
|
||||
children: [
|
||||
{ tag: 'child', attributes: {}, children: ['text'] }
|
||||
]
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse multiple children', () => {
|
||||
const xml = '<root><a /><b /><c /></root>';
|
||||
const result = fromXml(xml);
|
||||
expect(result.children.length).toBe(3);
|
||||
expect(result.children[0]).toEqual({ tag: 'a', attributes: {}, children: [] });
|
||||
});
|
||||
|
||||
it('should skip XML declaration', () => {
|
||||
const xml = '<?xml version="1.0"?><root />';
|
||||
const result = fromXml(xml);
|
||||
expect(result.tag).toBe('root');
|
||||
});
|
||||
|
||||
it('should skip comments', () => {
|
||||
const xml = '<root><!-- comment --><child /></root>';
|
||||
const result = fromXml(xml);
|
||||
expect(result.children.length).toBe(1);
|
||||
expect(result.children[0].tag).toBe('child');
|
||||
});
|
||||
|
||||
it('should handle escaped characters', () => {
|
||||
const xml = '<text><hello> & "world"</text>';
|
||||
const result = fromXml(xml);
|
||||
expect(result.children[0]).toBe('<hello> & "world"');
|
||||
});
|
||||
|
||||
it('should parse complex nested structure', () => {
|
||||
const xml = `
|
||||
<root>
|
||||
<user id="1" name="someone">
|
||||
<email>someone@example.com</email>
|
||||
<active />
|
||||
</user>
|
||||
</root>
|
||||
`;
|
||||
const result = fromXml(xml);
|
||||
expect(result.tag).toBe('root');
|
||||
expect(result.children[0].tag).toBe('user');
|
||||
expect(result.children[0].attributes.name).toBe('someone');
|
||||
expect(result.children[0].children.length).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('toXml', () => {
|
||||
it('should encode simple tag', () => {
|
||||
const obj = { tag: 'root', attributes: {}, children: [] };
|
||||
expect(toXml(obj)).toBe('<root />');
|
||||
});
|
||||
|
||||
it('should encode tag with attributes', () => {
|
||||
const obj = { tag: 'user', attributes: { id: '1', name: 'someone' }, children: [] };
|
||||
const result = toXml(obj);
|
||||
expect(result).toContain('id="1"');
|
||||
expect(result).toContain('name="someone"');
|
||||
});
|
||||
|
||||
it('should encode tag with text content', () => {
|
||||
const obj = { tag: 'email', attributes: {}, children: ['someone@example.com'] };
|
||||
expect(toXml(obj)).toBe('<email>someone@example.com</email>');
|
||||
});
|
||||
|
||||
it('should encode nested tags with indentation', () => {
|
||||
const obj = {
|
||||
tag: 'root',
|
||||
attributes: {},
|
||||
children: [
|
||||
{ tag: 'child', attributes: {}, children: ['text'] }
|
||||
]
|
||||
};
|
||||
const result = toXml(obj);
|
||||
expect(result).toContain('<root>');
|
||||
expect(result).toContain(' <child>');
|
||||
expect(result).toContain('</root>');
|
||||
});
|
||||
|
||||
it('should escape special characters', () => {
|
||||
const obj = { tag: 'text', attributes: {}, children: ['<hello> & "world"'] };
|
||||
const result = toXml(obj);
|
||||
expect(result).toContain('<hello> & "world"');
|
||||
});
|
||||
|
||||
it('should escape attributes', () => {
|
||||
const obj = { tag: 'node', attributes: { attr: 'a & b' }, children: [] };
|
||||
const result = toXml(obj);
|
||||
expect(result).toContain('attr="a & b"');
|
||||
});
|
||||
|
||||
it('should handle multiple children', () => {
|
||||
const obj = {
|
||||
tag: 'root',
|
||||
attributes: {},
|
||||
children: [
|
||||
{ tag: 'a', attributes: {}, children: [] },
|
||||
{ tag: 'b', attributes: {}, children: [] }
|
||||
]
|
||||
};
|
||||
const result = toXml(obj);
|
||||
expect(result).toContain('<a />');
|
||||
expect(result).toContain('<b />');
|
||||
});
|
||||
|
||||
it('should encode string directly', () => {
|
||||
expect(toXml('hello')).toBe('hello');
|
||||
expect(toXml('a & b')).toBe('a & b');
|
||||
});
|
||||
});
|
||||
|
||||
describe('round-trip', () => {
|
||||
it('should encode and decode to same structure', () => {
|
||||
const obj = {
|
||||
tag: 'root',
|
||||
attributes: { id: '1' },
|
||||
children: [
|
||||
{ tag: 'child', attributes: {}, children: ['text'] }
|
||||
]
|
||||
};
|
||||
const xml = toXml(obj);
|
||||
const parsed = fromXml(xml);
|
||||
expect(parsed).toEqual(obj);
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user