Skip to content
github-actions[bot] edited this page Nov 20, 2026 · 25 revisions

UMT Main Package

UMT Main Package is written in TypeScript and is a collection of useful functions for various tasks.

Install

npm install umt

# or

yarn add umt

# or

pnpm add umt

# or

bun add umt

v5 is ESM-only. Use import; require("umt") is not supported. Runtime matrix and migration notes: COMPATIBILITY.md.

import { isBetween, addBusinessDays, fromUnix } from "umt";
// or a subpath:
import { weekOfYear } from "umt/Date";

Date helpers

Local-time calendar helpers. Week boundaries are Sunday-start (JavaScript Date#getDay() 0). There are no UTC variants.

Function Behavior
isBetween(date, start, end, unit?, inclusivity?) Default inclusivity is "()" (exclusive both ends, matching dayjs). Ranges are not swapped: if start is after end, the result is false. Omit unit for millisecond timestamps; with a unit, all three dates are truncated via startOf first.
isSame(left, right, unit?) Same truncation rules as isBetween. Omit unit for exact getTime() equality.
addBusinessDays(date, amount, holidays?) / subBusinessDays Walks calendar days until amount weekdays (minus optional holidays compared with isSameDay) have been counted. The start date is not counted: Friday + 1 is Monday, Saturday + 1 is Monday. 0 returns a clone and does not snap to a business day. Does not mutate the input.
getQuarter(date) Local month → 1–4 (Jan–Mar = 1), matching startOf(..., "quarter").
weekOfYear(date) Sunday-start week index. Week 1 contains January 1 of that local year. Uses day-count rounding so DST does not shift the week number. Not ISO-8601 (Monday-start) week numbering.
fromUnix(value, unit?) / toUnix(date, unit?) Default unit is "s".toUnix(..., "s") is Math.floor(date.getTime() / 1000).
format(date, formatString?) Token formatter on local Date fields. Default pattern is "YYYY-MM-DDTHH:mm:ssZ".[text] is copied as-is. Z / ZZ use date's timezone offset. Throws TypeError("Invalid Date in format") if date is not a Date.
parseDate(string, formatString) Inverse of format with the same tokens and [text] escapes. YY is 2000–2099. Missing fields default to 1970-01-01 00:00:00. Z / ZZ are that offset; otherwise local. Returns an Invalid Date on mismatch, out-of-range fields, or a d that disagrees with the calendar date. Python / Rust return None.
isAfter / isBefore Strict comparison. Omit unit for exact timestamps; with a unit, both dates are truncated with startOf first. Same calendar day at "day" is not after or before.
daysInMonth(date) Local-time days in that month (28–31). Leap-year February is 29. Invalid Date → NaN.
businessDaysBetween(start, end, holidays?) Start excluded, end included. Inverse of addBusinessDays when end is a business day. Negative when end is before start. Same calendar day → 0 (not -0).

DateInclusivity is "()" | "[]" | "[)" | "(]". UnixTimeUnit is "s" | "ms". DateBoundaryUnit is second | minute | hour | day | week | month | quarter | year.

import {
  addBusinessDays,
  businessDaysBetween,
  daysInMonth,
  format,
  fromUnix,
  getQuarter,
  isAfter,
  isBetween,
  isSame,
  parseDate,
  toUnix,
  weekOfYear,
} from "umt/Date";

const start = new Date(2025, 3, 10);
const mid = new Date(2025, 3, 15);
const end = new Date(2025, 3, 20);

isBetween(mid, start, end); // true
isBetween(start, start, end); // false (exclusive default)
isBetween(start, start, end, undefined, "[]"); // true

addBusinessDays(new Date(2025, 3, 18), 1); // 2025-04-21 (Monday)
getQuarter(new Date(2025, 3, 15)); // 2
weekOfYear(new Date(2025, 0, 1)); // 1
weekOfYear(new Date(2025, 0, 5)); // 2 (Sunday)

fromUnix(0).getTime(); // 0
toUnix(new Date(1_700_000_000_999)); // 1700000000

format(new Date(2023, 5, 10, 15, 30, 45), "YYYY-MM-DD"); // "2023-06-10"
format(new Date(2023, 5, 10, 15, 30, 45), "[Year:] YYYY"); // "Year: 2023"

parseDate("2025-04-04", "YYYY-MM-DD").getTime(); // local 2025-04-04
Number.isNaN(parseDate("2025-13-01", "YYYY-MM-DD").getTime()); // true
isAfter(new Date(2025, 3, 16), new Date(2025, 3, 15)); // true
isAfter(new Date(2025, 3, 15, 23), new Date(2025, 3, 15, 1), "day"); // false
isSame(new Date(2025, 3, 15, 1), new Date(2025, 3, 15, 23), "day"); // true
daysInMonth(new Date(2024, 1, 1)); // 29
businessDaysBetween(new Date(2025, 3, 18), new Date(2025, 3, 21)); // 1 (Fri → Mon)

Python and Rust ports of these helpers live in package/umt_python and package/umt_rust. Rust treats DateTime<Utc> calendar fields as wall-clock values except fromUnix / toUnix, which use real epoch timestamps. isSame is in TypeScript, Python, and Rust. Date format is not ported to Python. Rust umt_format takes an explicit timezone_offset_minutes (no default pattern; use umt_format_iso for the ISO-like default). Go has FormatDate (no Z / ZZ) but not IsBetween, AddBusinessDays, unix conversion, IsSame, or ParseDate. Wasm skips Date helpers that take DateTime<Utc> (umt_format, umt_parse_date, umt_is_same, umt_is_after, umt_business_days_between, …).

IP helpers

IPv4 dotted-decimal only (no IPv6). Numeric results are unsigned 32-bit values. getNetworkAddress returns a number, not a dotted string — pass it through longToIp.

Input validation is the caller's responsibility. These functions do not throw on malformed strings (see COMPATIBILITY.md). Python and Rust ports do validate.

Function Behavior
ipToLong(ip) / longToIp(long) Pack or unpack four octets. Leading zeros in an octet are accepted ("192.168.01.1" equals "192.168.1.1").
cidrToLong(cidr) / cidrToSubnetMask(cidr) Prefix length 0–32 to a mask number / dotted mask. CIDR 0 is 0 ("0.0.0.0").
subnetMaskToCidr(mask) Counts set bits. Does not require a contiguous mask: "255.0.255.0" returns 16.
isInRange(ip, network, cidr) (ip & mask) === (network & mask). CIDR 0 matches every IPv4 address.
isPrivateIp(ip) RFC 1918 only: 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16. Loopback (127.0.0.1) and link-local (169.254.0.0/16) are not private. TypeScript, Python, Rust, and Go compute the three (network, mask) pairs once at module load.
getIpClass(ip) Classful first-octet lookup (A–E).0.0.0.0 and malformed input return "".
getNetworkAddress(ip, mask) ipToLong(ip) & cidrToLong(subnetMaskToCidr(mask)) as an unsigned 32-bit number.
ipToBinaryString(ip) 32-character 0/1 string, eight bits per octet.
isValidIp(ip) Four decimal octets 0–255, no leading zeros, no whitespace. "192.168.01.1" is false even though TypeScript ipToLong accepts that string. Python / Rust is_valid_ip matches ip_to_long (both reject leading zeros).
parseCidr(cidr) "network/prefix" → { networkAddress, prefixLength } with host bits cleared ("192.168.1.130/25" → "192.168.1.128"). TypeScript does not validate. Python / Rust error on a bad address or prefix.
import {
  cidrToSubnetMask,
  getNetworkAddress,
  ipToLong,
  isInRange,
  isPrivateIp,
  isValidIp,
  longToIp,
  parseCidr,
} from "umt/IP";

ipToLong("192.168.1.1"); // 3232235777
longToIp(3232235777); // "192.168.1.1"
cidrToSubnetMask(24); // "255.255.255.0"
isInRange("192.168.1.2", "192.168.1.0", 24); // true
isPrivateIp("10.0.0.1"); // true
isPrivateIp("127.0.0.1"); // false
isValidIp("192.168.1.1"); // true
isValidIp("192.168.01.1"); // false
parseCidr("192.168.1.130/25"); // { networkAddress: "192.168.1.128", prefixLength: 25 }
longToIp(getNetworkAddress("192.168.1.1", "255.255.255.0")); // "192.168.1.0"

Python and Rust ports live in package/umt_python and package/umt_rust. Those ports raise / return Err on malformed input and reject non-contiguous subnet masks. They are not exposed through umt-plugin-wasm: Rust IP functions are not named umt_*, so wasm codegen ignores them.

Crypto helpers

RFC 4648 Base32 in umt/Crypto (alphabet A-Z + 2-7, = padding). Python, Rust, and Go ports exist. This is encoding, not encryption.

Function Behavior
encodeBase32(input) string or Uint8Array → padded Base32. Empty input → "". "Hello" → "JBSWY3DP". "f" → "MY======". Python accepts str | bytes; Go takes []byte only.
decodeBase32(input) Base32 → Uint8Array. Skips = anywhere ("JB=SWY3DP" equals "JBSWY3DP"). TypeScript does not throw: invalid / lowercase characters map to value 0 (same as A), so "1A" is [0]. Python / Rust / Go error on 1, 0, @, lowercase, and non-ASCII.
decodeBase32ToString(input) UTF-8 decode of decodeBase32. "JBSWY3DP" → "Hello". "4OAZHY4CSPRYDK7DQGQ6HANP" → "こんにちは".
encodeHex(input) string or Uint8Array → lowercase hex, two digits per byte. Empty → "". "Hello" → "48656c6c6f". Python accepts str | bytes; Rust is generic AsRef<[u8]>. Go has no hex helpers.
decodeHex(input) Hex → Uint8Array. Accepts upper and lower case. TypeScript does not validate: odd length drops the last character ("abc" → [171]); non-hex pairs become 0 ("zz" → [0]). Python / Rust error (ValueError / Err("Invalid hex string")). Wasm skips encode (generic) and decode (Result).
import {
  decodeBase32,
  decodeBase32ToString,
  decodeHex,
  encodeBase32,
  encodeHex,
} from "umt/Crypto";

encodeBase32("Hello"); // "JBSWY3DP"
encodeBase32("f"); // "MY======"
decodeBase32ToString("JBSWY3DP"); // "Hello"
decodeBase32ToString("MY======"); // "f"
Array.from(decodeBase32("1A")); // [0] (invalid `1` treated as 0)
encodeHex("Hello"); // "48656c6c6f"
encodeHex(new Uint8Array([0, 255])); // "00ff"
Array.from(decodeHex("48656c6c6f")); // [72, 101, 108, 108, 111]
Array.from(decodeHex("00FF")); // [0, 255]

Wasm skips Base32 (generic encode, Result decode) and hex (umt_encode_hex is generic; umt_decode_hex returns Result<Vec<u8>, HexError>).

Validate and Standard Schema

Validator factories in umt/Validate (string(), number(), object(), arrayOf(), union(), …) implement Standard Schema V1. Each factory return value has a ~standard property:

Field Value
version 1
vendor "umt" (STANDARD_SCHEMA_VENDOR)
validate(value) Synchronous. On success { value } is the original input (validators do not transform). On failure { issues: [{ message }] } with a single issue.

attachStandard() is how factories advertise the spec. It does not set ~standard.types. Consume validators through ~standard.validate, @hono/standard-validator's sValidator, or any other Standard Schema V1 host (Zod / Valibot schemas are interchangeable with UMT on that interface).

import { number, object, string } from "umt/Validate";

const user = object({ name: string(), age: number() });
user["~standard"].vendor; // "umt"

const ok = user["~standard"].validate({ name: "Ada", age: 1 });
// { value: { name: "Ada", age: 1 } }

const ng = user["~standard"].validate({ name: "Ada" });
// { issues: [{ message: ... }] }

UMT validators never return a Promise from ~standard.validate.

parseEmail

parseEmail({ email, options: { level } }) returns { valid, parts? } with parts: { local, domain } when the regex matches. level is required: "basic" | "rfc822" | "rfc2822" | "rfc5321" | "rfc5322". Inputs longer than 320 UTF-16 code units are rejected before the regex (ReDoS). Python and Rust apply the same 320-unit cap. Go has no global cap; rfc2822 / rfc5322 reject length > 998, rfc5321 rejects length > 256.

Level Behavior
basic Common local/domain characters. Single-label domains are accepted (user@localhost).
rfc822 Comments, quoted locals, optional whitespace around @. Single-label domains allowed. Local part max 64.
rfc2822 Requires a TLD ([A-Za-z]{2,}). Rejects ... Max 998.
rfc5321 SMTP path: max 256, local max 64, rejects ... Allows user@[192.168.1.1] / user@[IPv6:…]. Single-label domains fail.
rfc5322 Comments and quoted strings. Max 998. Rejects ...
import { parseEmail } from "umt/Validate";

parseEmail({ email: "user@example.com", options: { level: "basic" } });
// { valid: true, parts: { local: "user", domain: "example.com" } }

parseEmail({ email: "user@localhost", options: { level: "basic" } }).valid; // true
parseEmail({ email: "user@localhost", options: { level: "rfc5321" } }).valid; // false
parseEmail({ email: "userexample.com", options: { level: "basic" } }).valid; // false

Python parse_email(email, ParseEmailOptions(level=...)) keeps the five patterns and the 320-unit cap. Rust umt_parse_email uses the matching regex for every level (Rfc822 / Rfc5322 included); None options default to Basic. Go ParseEmail(email) returns (EmailParts, error) at basic only; ParseEmailWithLevel(email, level) returns {Valid, Parts} (unknown / empty level is invalid). Wasm skips umt_parse_email (custom options type).

Decorator

Class-field validation in umt/Decorator. Rules live on the prototype chain (validateInstance includes inherited fields). @Validatable wraps the constructor and throws after super(...), so it sees initialized class fields.

Decorator Behavior
@IsString / @IsArray / @IsBoolean Type checks. @IsNumber rejects numeric strings ("1").
@Min(n) / @Max(n) Inclusive numeric bounds. Non-numbers fail.
@LengthBetween(min, max) Inclusive length on strings and arrays.
@Optional Skip other rules when the value is undefined.
@Nullable Skip other rules when the value is null.
@Schema(schema) Any Standard Schema V1 validator (UMT, Zod, Valibot). Async validate results are treated as failure.
@Validatable Throws Error joining all messages with "; " if any field fails.

validateInstance(instance) returns a Result: success carries the instance; error carries { path, message }[].

import {
  IsNumber,
  IsString,
  Optional,
  Schema,
  Validatable,
  validateInstance,
} from "umt/Decorator";
import { number } from "umt/Validate";

class Profile {
  @IsString name = "alice";
  @Optional
  @IsNumber
  age?: number;
}

validateInstance(new Profile()).type; // "success"

@Validatable
class Product {
  @Schema(number()) price = 100;
}
new Product(); // succeeds; throws `Error` if `price` is not a number

String helpers

Unicode-aware string utilities in umt/String. Python, Rust, and Go ports exist (strip_ansi / umt_strip_ansi / StripAnsi, and the same mapping for tags and words).

Function Behavior
stripAnsi(string) Removes CSI sequences (colors, cursor movement, including C1 U+009B) and OSC sequences (BEL or ST terminated). Incomplete CSI with no final byte is left unchanged. Unlike sanitizeString, other non-printables stay.
stripTags(string) Deletes HTML/XML tags (<[^<>]*>), repeating until stable so "<sc<script>ript>" becomes "". Self-closing tags are removed without inserting a separator ("line1<br/>line2" → "line1line2").
words(string, pattern?) Default: insert spaces on camelCase / acronym boundaries, then split on non-letter/number separators. CJK and other letters are kept. If pattern is passed, returns string.match(pattern) or [].
normalizeWhitespace(string) Collapses Unicode \s+ to a single space and trims. Unlike deleteSpaces, words stay separated. All-whitespace input → "".
deleteSpaces(string) Removes every Unicode \s character (spaces, tabs, newlines, em space U+2003, ideographic space U+3000, …). "Hello World" → "HelloWorld". All-whitespace input → "".
sanitizeString(string) Keeps printable ASCII (U+0020–U+007E) plus TAB / LF / CR. Drops NULL, other C0, DEL, C1, ANSI ESC, and all non-ASCII (CJK, emoji, "é"). Unlike stripAnsi, it does not parse CSI: "\u001B[31mred\u001B[0m" → "[31mred[0m".
unescapeHtml(string) Named entities (&amp; &lt; &gt; &quot; &#39; &#x27; &#x2F; &#x60; &#x3D;) plus decimal / hex numeric references (&#65;, &#x41;).&#X41; (uppercase X) is left unchanged. Dangerous code points are not decoded (NULL, C0 except TAB/LF/CR, DEL, C1, surrogates, >0x10FFFF). Python / Rust / Go do not apply those extra filters.
camelCase(string) Replaces non-alphanumeric runs, then lowercases only the first character. Does not split acronyms: "HELLO" → "hELLO", "XMLHttpRequest" → "xMLHttpRequest".
kebabCase(string) Inserts dashes on aB / ABc boundaries, replaces spaces / underscores / other non-alphanumerics, lowercases. Splits acronyms: "XMLHttpRequest" → "xml-http-request".
slugify(string) NFD, strip combining marks U+0300–U+036F, lowercase, then collapse non-ASCII-alnum runs and underscores to -. CJK is dropped: "Japanese: こんにちは" → "japanese". TypeScript, Python, Rust, and wasm match. Go matches the ASCII drop but decomposes only a fixed Latin-1 table, not full Unicode NFD.
escapeHtml(string) Escapes & < > " ' plus backtick (&#x60;) and forward slash (&#x2F;) so older-browser attribute delimiters and </script> injection are harder. Python / Rust / Go escape only & < > " '; ` and / stay.
toFullWidth(string) ASCII digits and letters only ([0-9A-Za-z]), each code point + 0xFEE0. Punctuation and space stay: "a-b!" → "a-b!". Ports match. Inverse of toHalfWidth for those characters.
toHalfWidth(string) Full-width digits and letters only (0-9A-Za-z), each code point - 0xFEE0. CJK, punctuation, and ideographic space stay. Python also converts U+FF01–U+FF5E (full-width ! through ~) and U+3000 → " ". Rust / Go match TypeScript.
toBase64(string) UTF-8 → standard Base64 (A-Za-z0-9+/, = padding). Empty → "". "Hello World" → "SGVsbG8gV29ybGQ=". Not URL-safe (- _). Python / Rust / Go / wasm match the alphabet. Encoding, not encryption — distinct from umt/Crypto Base32.
fromBase64(string) Standard Base64 → UTF-8 string. Empty → "". Uses atob then TextDecoder. Missing padding is accepted ("SGVsbG8gV29ybGQ" → "Hello World"). Invalid characters throw InvalidCharacterError. Invalid UTF-8 becomes U+FFFD ("gA==" → "�"). Python / Rust / Go require padding and error on invalid Base64. Rust also errors on invalid UTF-8; Go returns the raw bytes; Python raises ValueError. Wasm follows Rust.
encodeBase64Url(string) UTF-8 → RFC 4648 section 5 (- _), no = padding. Empty → "". "Hello World" → "SGVsbG8gV29ybGQ". "???>" → "Pz8_Pg". Python / Rust / wasm match. Go has no URL-safe helpers.
decodeBase64Url(string) URL-safe Base64 → UTF-8. Padding optional. TypeScript rewrites -/_ then calls fromBase64 (invalid UTF-8 → U+FFFD). Python / Rust require the URL-safe alphabet and error on invalid Base64; Rust also errors on invalid UTF-8. Wasm generates both from Rust.
import {
  decodeBase64Url,
  deleteSpaces,
  encodeBase64Url,
  escapeHtml,
  fromBase64,
  sanitizeString,
  slugify,
  stripAnsi,
  stripTags,
  toBase64,
  toFullWidth,
  toHalfWidth,
  words,
} from "umt/String";

stripAnsi("\u001B[31mred\u001B[0m"); // "red"
sanitizeString("\u001B[31mred\u001B[0m"); // "[31mred[0m"
sanitizeString("héllo"); // "hllo"
sanitizeString("日本語"); // ""
deleteSpaces("  tab\t space "); // "tabspace"
stripTags("<p>Hello <b>World</b></p>"); // "Hello World"
stripTags("<sc<script>ript>"); // ""
words("XMLHttpRequest"); // ["XML", "Http", "Request"]
words("foo-bar_baz"); // ["foo", "bar", "baz"]
words("a1 b2 c3", /[a-z]\d/g); // ["a1", "b2", "c3"]
normalizeWhitespace("  hello   world \t\n foo "); // "hello world foo"
unescapeHtml("Tom &amp; Jerry"); // "Tom & Jerry"
unescapeHtml("&#0;"); // "&#0;" (NULL left unchanged)
camelCase("hello-world"); // "helloWorld"
camelCase("HELLO"); // "hELLO"
kebabCase("XMLHttpRequest"); // "xml-http-request"
slugify("Hello World!"); // "hello-world"
slugify("café"); // "cafe"
slugify("Japanese: こんにちは"); // "japanese"
escapeHtml("<script></script>"); // "&lt;script&gt;&lt;&#x2F;script&gt;"
escapeHtml("Use `template`"); // "Use &#x60;template&#x60;"
toFullWidth("Abc123"); // "Abc123"
toFullWidth("a-b!"); // "a-b!"
toHalfWidth("ABC123"); // "ABC123"
toHalfWidth("! "); // "! " (full-width bang and ideographic space stay)
toBase64("Hello World"); // "SGVsbG8gV29ybGQ="
toBase64(""); // ""
fromBase64("SGVsbG8gV29ybGQ="); // "Hello World"
fromBase64("SGVsbG8gV29ybGQ"); // "Hello World" (padding optional in TypeScript)
fromBase64("YQ=="); // "a"
encodeBase64Url("Hello World"); // "SGVsbG8gV29ybGQ"
encodeBase64Url("???>"); // "Pz8_Pg"
decodeBase64Url("SGVsbG8gV29ybGQ"); // "Hello World"
decodeBase64Url("Zg=="); // "f"

Go splits the custom-pattern case into Words vs WordsWithPattern.

Color and URL helpers

hexaToRgba (umt/Color) and isAbsoluteUrl / joinPath (umt/URL). Python, Rust, and Go ports exist.

Function Behavior
hexaToRgba(hex) # plus 3, 6, or 8 hex digits → { r, g, b, a }.r/g/b are 0–255; a is 0–1 rounded to 2 decimals (#FF000080 → 0.5). TypeScript does not validate; malformed input can yield NaN. Python / Rust / Go require the # + hex pattern and error otherwise.
getLuminance({ r, g, b, a? }) WCAG 2.1 relative luminance 0–1. Alpha is ignored. TypeScript does not range-check. Python raises ValueError("Invalid rgba value") outside r/g/b 0–255 or a 0–1. Wasm skips both luminance helpers (RgbaInput).
getContrastRatio(a, b) WCAG 2.1 contrast 1–21. Argument order does not matter. Black / white is 21. Identical colors are 1.
isAbsoluteUrl(url) RFC 3986 scheme check: letter, then letters / digits / + / . / -, then :.mailto: and tel: are absolute. Protocol-relative ("//example.com"), relative paths, and schemes starting with a digit are not.
joinPath(...segments) String join, not path.join and not a URL parser. Keeps the first segment's leading / and the last segment's trailing /. Strips leading / from later segments and trailing / from earlier ones, then drops empty pieces. No . / .. resolution. No segments → "". A single "///" stays "///".
stringifyQuery(params) Inverse of parseQueryString. application/x-www-form-urlencoded, no leading ?. Empty → "". "hello world" → "hello+world". Wasm skips it (HashMap).
import { getContrastRatio, getLuminance, hexaToRgba } from "umt/Color";
import { isAbsoluteUrl, joinPath, stringifyQuery } from "umt/URL";

hexaToRgba("#FF0000"); // { r: 255, g: 0, b: 0, a: 1 }
hexaToRgba("#F00"); // { r: 255, g: 0, b: 0, a: 1 }
hexaToRgba("#FF000080"); // { r: 255, g: 0, b: 0, a: 0.5 }
getLuminance({ r: 255, g: 0, b: 0 }); // 0.2126
getContrastRatio({ r: 0, g: 0, b: 0 }, { r: 255, g: 255, b: 255 }); // 21

isAbsoluteUrl("https://example.com"); // true
isAbsoluteUrl("mailto:user@host"); // true
isAbsoluteUrl("/path/to/page"); // false
isAbsoluteUrl("//example.com"); // false

joinPath("https://example.com/", "/api/", "/users"); // "https://example.com/api/users"
joinPath("/a/", "/b/", "/c"); // "/a/b/c"
joinPath("a", "", "b"); // "a/b"
joinPath(); // ""
stringifyQuery({ q: "hello world", tag: "a&b" }); // "q=hello+world&tag=a%26b"

Wasm codegen skips umt_hexa_to_rgba (custom Result) and generates isAbsoluteUrl / joinPath / normalizeWhitespace / unescapeHtml / escapeHtml / camelCase / slugify / sanitizeString / deleteSpaces / toFullWidth / toHalfWidth / escapeRegexp / encodeBase64Url / decodeBase64Url. Wasm slugify follows Rust and drops CJK ("japanese"), matching TypeScript. Wasm escapeHtml / toHalfWidth follow Rust (no backtick or / escaping; half-width conversion is alnum-only). Wasm's JS name is escapeRegexp (lowercase p); TypeScript is escapeRegExp.

Tool helpers

escapeRegExp (umt/Tool) prefixes regex metacharacters with \. Python escape_regexp, Rust umt_escape_regexp, Go EscapeRegExp, and wasm escapeRegexp (lowercase p) match the same set: $ ( ) * + . ? [ \ ] ^ { | }. Hyphen and / are not escaped ("foo-bar" and "a/b" stay unchanged). Empty input → "".

import { escapeRegExp } from "umt/Tool";

escapeRegExp("a.b"); // "a\\.b"
escapeRegExp(".*+?^${}()|[]\\"); // "\\.\\*\\+\\?\\^\\$\\{\\}\\(\\)\\|\\[\\]\\\\"
escapeRegExp("foo-bar"); // "foo-bar"
escapeRegExp("path/to/file.txt"); // "path/to/file\\.txt"

calculator builds its currency-symbol regex with this helper at call time (the symbol is caller input).

pipe / createPipeline (umt/Tool) and the data-first operators (umt/Pipe) are documented under Pipe helpers.

Pipe helpers

pipe (umt/Tool) has two call shapes in TypeScript 5.3.0+. Data-first operators live in umt/Pipe and are not ported. createPipeline is a separate callable Pipeline API.

Call Result
pipe(value) Fluent Pipe<T>. Chain .map / .when / .tap / .filterStrict / .filterWithDefault / .filterResult, then .end().
pipe(value, fn, ...fns) Applies functions left-to-right and returns the value (not a Pipe). Typed overloads cover up to 20 functions; extra functions still run at runtime.

Python pipe / Rust umt_pipe are fluent-only (pipe(value) → Pipe). Go Pipe(value, fns...) is data-first with any and returns the value even with no functions (Pipe(1) is 1, not a builder). Wasm skips umt_pipe (generics).

Operator Behavior
defaultTo(fallback) ?? — only null / undefined are replaced. 0, "", and false stay.
filter(predicate) Native Array#filter. Does not mutate. Predicate gets (value, index).
find(predicate) First match, or undefined. Predicate gets (value, index).
flatMap(fn) Native Array#flatMap (one level). Non-array returns stay as elements.
fold(reducer, initial) Reduce with a required initial value. Empty array → initial. Reducer gets (accumulator, value, index).
join(separator?) Native Array#join. Omit the separator → ",".
replace(pattern, replacement) Native String#replace. A string pattern replaces the first match only; use a /g regex for all.
slice(start?, end?) Native Array#slice. Negative indexes count from the end. No indexes → a shallow copy.
split(separator, limit?) Native String#split. split(",") on "" is [""], not [].
toLowerCase() / toUpperCase() / trim() Zero-arg factories. Call them (trim()), do not pass the function itself.
transform(fn) Arrays: map each element (the function receives the element only, so Number.parseInt is safe). Non-arrays: apply to the value.

filter / find / flatMap / slice / transform do not mutate the input array. filterStrict throws Error("Value did not match filter predicate"). Python filter_strict raises ValueError; Rust filter_strict panics with the same message.

import {
  defaultTo,
  filter,
  fold,
  join,
  replace,
  split,
  toUpperCase,
  transform,
  trim,
} from "umt/Pipe";
import { pipe } from "umt/Tool";

pipe(1)
  .map((x) => x + 1)
  .end(); // 2

pipe(1, (x) => x + 1, (x) => x * 3, (x) => `${x}`); // "6"

pipe([1, 2, 3, 4], filter((x) => x % 2 === 0)); // [2, 4]
pipe(undefined, defaultTo("")); // ""
pipe(0, defaultTo(1)); // 0
pipe("a-b-c", replace("-", "+")); // "a+b-c" (first match)
pipe("a-b-c", replace(/-/g, "+")); // "a+b+c"
pipe(["10", "10", "10"], transform(Number.parseInt)); // [10, 10, 10]

pipe(
  " a , b , c ",
  split(","),
  transform(trim()),
  transform(toUpperCase()),
  join("-"),
); // "A-B-C"

pipe("1,2,3", split(","), transform(Number), fold((sum, x) => sum + x, 0)); // 6

Array, Async, and Error helpers

Python and Rust port countBy / partition / sliding / mapSeries. Python also has safe_execute_async. Rust umt_map_series is synchronous (Result; the first Err stops). Go still has none of these. Wasm skips the generic array helpers and umt_map_series.

Function Behavior
countBy(array, iteratee) Counts elements by iteratee key (string | number). Empty input → {}. Iteratee receives (value, index, array).
partition(array, predicate) [pass, fail] in original order. Does not mutate the input. Predicate receives (value, index, array).
sliding(array, size, step?) Fixed-size windows. Default step is 1. Incomplete trailing windows are omitted. size larger than length → []. Does not mutate the input.
mapSeries(items, fn) Awaits each mapper before starting the next (never overlapping). Returns results in input order. Rejects if any task rejects; it does not swallow errors.
safeExecuteAsync(callback) try/await/catch into Result: { type: "success", value } or { type: "error", error }. Accepts a sync return or a Promise. Sync throws and rejected promises both become type: "error". Never throws.
import { countBy, partition, sliding } from "umt/Array";
import { mapSeries } from "umt/Async";
import { safeExecuteAsync } from "umt/Error";

countBy(["one", "two", "three"], (s) => s.length); // { 3: 2, 5: 1 }
partition([1, 2, 3, 4], (n) => n % 2 === 0); // [[2, 4], [1, 3]]
sliding([1, 2, 3, 4, 5], 3); // [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
sliding([1, 2, 3, 4, 5], 3, 2); // [[1, 2, 3], [3, 4, 5]]

await mapSeries([1, 2, 3], async (n) => n * 2); // [2, 4, 6]
await safeExecuteAsync(async () => 42); // { type: "success", value: 42 }

Math helpers

Expression utilities in umt/Math. Python, Rust, and Go ports exist (calculator / umt_calculator / Calculator, and the same mapping for mathConverter).

Function Behavior
calculator(expression, exchange?) Strips whitespace. If the string contains =, solves a single-variable equation ("x=5" → "5", "2x=6" → "3"). Otherwise evaluates + - * / ^ and parentheses. Incomplete input is returned as-is ("1+" → "1+").^ reduces the last pair first ("2^2^2" → "16"). Optional exchange replaces symbol + digits ("$10*2" with { $: 100 } → "2000"). Finite results are rounded to 10 decimal places before toString().
calculatorInitialization(exchange) Returns (expression) => calculator(expression, exchange).
mathConverter(equation) Rewrites n*n or n^2 as a sum of simpler products ("1250*1250" → "1500*1000+400*100+200*100+50*50"). Unequal * operands and + are left unchanged.
toBaseN(value, radix?) Number#toString(radix). Default radix is 2 (toBaseN(10) → "1010"), not JavaScript's default 10. Hex digits are lowercase (toBaseN(255, 16) → "ff"). Radix outside 2–36 throws RangeError. Python to_base_n also defaults to 2 and takes int (True → "1"). Rust umt_to_base_n has no default radix; invalid radix returns the string "Invalid radix" (not Err). Go ToBaseN panics via strconv.FormatInt if the base is outside 2–36.
degToRad(degrees) / radToDeg(radians) Goes through multiplication / division, not native * /. Does not wrap to 0–360 (radToDeg((5 * Math.PI) / 2) is 450). radToDeg(Math.PI) is 180; degToRad(180) is Math.PI. NaN / Infinity propagate. Python matches. Rust / Go / wasm use native float multiply (x * 180 / PI).
import {
  calculator,
  calculatorInitialization,
  degToRad,
  mathConverter,
  radToDeg,
  toBaseN,
} from "umt/Math";

calculator("1+2"); // "3"
calculator("(2+3)*4"); // "20"
calculator("2^2^2"); // "16"
calculator("1+"); // "1+"
calculator("$10*2", { $: 100 }); // "2000"
calculatorInitialization({ $: 100 })("$1"); // "100"
mathConverter("1250*1250"); // "1500*1000+400*100+200*100+50*50"
toBaseN(10); // "1010"
toBaseN(15, 16); // "f"
toBaseN(255, 16); // "ff"
radToDeg(Math.PI); // 180
degToRad(180); // 3.141592653589793

Wasm generates mathConverter, toBaseN / toBinary / toHex (Rust: i64, "Invalid radix" on a bad base), and degToRad / radToDeg (native float multiply). It skips calculator (HashMap exchange rates).

UA helpers

Coarse User-Agent labels in umt/UA. Python, Rust, and Go ports exist. This is not a full UA parser: there are no versions, engines, or vendor strings — only the enums below. Matching is case-insensitive. parseUserAgent lowercases the input, then calls the three extractors.

Function Behavior
extractBrowserFromUserAgent(ua) Order: Edge (edg / edge) → IE (msie / trident) → Firefox (firefox / fxios) → Opera (opr/, returned as "other") → Chrome (chrome / crios) → Safari → "other". Safari is last because Chrome / Firefox on iOS also contain Safari.
extractDeviceFromUserAgent(ua) Order: bot (bot / googlebot / crawler / spider / robot / crawling) → mobile (iphone / ipod / webos / blackberry / iemobile / opera mini) → Android with mobile → "mobile", Android without mobile → "tablet" → iPad → desktop (windows / macintosh / linux) → "other".
extractOsFromUserAgent(ua) Order: iOS (iphone / ipad / ipod) → Android → macOS (mac os x) → Windows (windows / win32) → Linux → "other". iPhone UAs that contain like Mac OS X are still "ios". Android UAs that contain Linux are still "android".
parseUserAgent(userAgent) { os, browser, device }. Googlebot is { os: "other", browser: "other", device: "bot" }.
import {
  extractBrowserFromUserAgent,
  extractDeviceFromUserAgent,
  extractOsFromUserAgent,
  parseUserAgent,
} from "umt/UA";

parseUserAgent(
  "Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Mobile/15E148 Safari/604.1",
); // { os: "ios", browser: "safari", device: "mobile" }

extractBrowserFromUserAgent(
  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36 OPR/75.0.3969.149",
); // "other" (Opera)
extractDeviceFromUserAgent(
  "Mozilla/5.0 (Linux; Android 10) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.105 Safari/537.36",
); // "tablet" (no Mobile token)
extractOsFromUserAgent(
  "Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15",
); // "ios"

Python and Go return the same lowercase strings. Rust uses Browser / Device / Os enums (as_str() is the TypeScript label). Go wraps each field in a struct (Browser.Name, OS.Name, Device.Type). Wasm skips all four functions (custom enums / UserAgentInfo).

Function List

Advance

Array

Async

Color

Consts

Crypto

DataStructure

Date

Decorator

Error

Function

IP

Iterator

Map

Math

Number

Object

Pipe

Predicate

Random

Simple

String

Time

Tool

UA

Unit

URL

Validate

API

Classes

Interfaces

Type Aliases

Variables

Functions

Clone this wiki locally