Reference

TypeScript reference

Every type exported by @samline/formatter, including FormatOptions, FormatterResult, FormatType, the regex types and the Intl option types, with examples.

This page lists every type and value exported from @samline/formatter, what it represents, and where it shows up. Each entry links to the function or pattern that consumes or produces it.

Imports

import {
  format,
  isFormatType,
  FORMAT_TYPES,
  regex,
  isLuhn,
  isValidCard,
  isValidClabe,
  isValidCurp,
  isValidDniEs,
  isValidIban,
  isValidNss,
  isValidRfc,
  isValidRoutingNumber,
  isPhoneRegistered,
  getRawValue,
  getDateValueFromRaw,
  getTimeValueFromRaw,
  looksLikeRawDateValue,
  looksLikeRawTimeValue,
  stripPrefixAndSuffix,
  type FormatOptions,
  type FormatType,
  type FormatterResult,
  type DatePatternType,
  type NumeralThousandsGroupStyle,
  type TimePatternType,
  type PostalCountry,
  type Regex,
  type RegexEntry,
  type RegexKey,
} from '@samline/formatter'

import { formatPhone, registerPhone } from '@samline/formatter/phone'

import {
  formatCurrency,
  formatDate,
  formatNumber,
  formatPercent,
  formatRelativeTime,
  type IntlCurrencyOptions,
  type IntlDateOptions,
  type IntlNumberOptions,
  type IntlPercentOptions,
  type IntlRelativeTimeOptions,
} from '@samline/formatter/intl'

import {
  parseDate,
  type DateOptions,
  type DurationInput,
  type ParseDateOptions,
} from '@samline/formatter/date'

Format types

FormatType

Union of the seven supported format types. TypeScript narrows format()’s second argument against this union; an unsupported string raises TypeError at runtime.

import type { FormatType } from '@samline/formatter'

const type: FormatType = 'phone' // ✓
// const wrong: FormatType = 'foo'        // ✗ TS error

FormatOptions

Per-type configuration bag passed to format()’s third argument. Internally it is the intersection of the built-in engine’s per-type option interfaces plus a few package-specific extras (country, dateRawPattern, dateRawPatternDelimiter, timeRawPattern, timeRawPatternDelimiter, prefixMode, rawPrefix, suffix, suffixMode, rawSuffix, rawDecimalPadding, tailPrefix, interpretInputAs).

See the Configuration reference for the full per-formatType field reference.

import type { FormatOptions } from '@samline/formatter'

const opts: FormatOptions = {
  blocks: [4, 4, 4, 4],
  delimiter: ' ',
}

FormatterResult

The shape returned by format(). All fields are readonly so the result is safe to pipe through downstream layers without copy-on-write concerns.

import type { FormatterResult } from '@samline/formatter'

const result: FormatterResult = format('5512345678', 'phone')
result.formatted // '55 1234 5678'
result.raw // '5512345678'
result.type // 'phone'
FieldTypeMeaning
formattedstringDisplay string (with delimiters, prefix, etc.). Bind to the visible <input>.
rawstringCanonical backend-ready string. Mirror to a hidden <input>.
typeFormatTypeEcho of the requested format type. Useful for debugging or when the result is passed downstream.

DatePatternType / TimePatternType

Defined by the built-in engine (they were re-exported from cleave-zen before 3.0.0, with the same shape). Used in FormatOptions.datePattern / timePattern / dateRawPattern / timeRawPattern to define the segment order.

import type { DatePatternType, TimePatternType } from '@samline/formatter'

const datePattern: DatePatternType = ['d', 'm', 'Y'] // default
const timePattern: TimePatternType = ['h', 'm', 's'] // default

For 'date' each token is 'd', 'm', or 'Y' (day, month, year). For 'time' each token is 'h', 'm', or 's' (hours, minutes, seconds). The order is the display order the formatter inserts into the visible field.


Runtime helpers

FORMAT_TYPES

A readonly tuple of every supported type. Useful for iterating, building pickers, or type-driven UIs.

import { FORMAT_TYPES } from '@samline/formatter'

FORMAT_TYPES
// => ['general', 'phone', 'numeral', 'date', 'time', 'creditCard', 'creditCardType', 'text', 'slug']

isFormatType(value)

A type-guard that narrows an unknown string to FormatType. Pair it with format() when the format type comes from an untrusted source (URL, config, user input).

import { isFormatType, format } from '@samline/formatter'

function safeFormat(value: string, formatType: string) {
  if (!isFormatType(formatType)) {
    throw new Error(`Unsupported format type: ${formatType}`)
  }
  return format(value, formatType)
}

isFormatType does not throw — it returns a boolean. The error in safeFormat is a UX choice, not a requirement.


Regex dictionary types

RegexEntry

A { pattern, errorMessage } pair. Every static entry of regex conforms to this shape; the callable parametric entries (digits, phone, creditCard, url, password, custom) return values that also conform to it.

interface RegexEntry {
  pattern: RegExp
  errorMessage: string
}

RegexKey

type RegexKey = /* union of static-entry keys */

RegexKey is the union of entries that always expose a static .pattern and .errorMessage.

import { regex, type RegexKey } from '@samline/formatter'

function validate(key: RegexKey, value: string): string | null {
  return regex[key].pattern.test(value) ? null : regex[key].errorMessage
}

validate('email', 'foo@bar.com') // null  (valid)
validate('email', 'not-an-email') // 'Please enter a valid email address.'

RegexKey covers the static entries (phone, email, rfc, curp, cp, clabe, nss, ine, ineCic, ineOcr, passportMx, ssn, itin, passportUs, ein, routingNumber, iban, bic, vatEu, dniEs, postalCode, numeral, onlyNumbers, creditCard, expirationDate, cardCvc, onlyLetters, onlyAlphanumeric, personName, url, domain, ipv4, ipv6, uuid, hexColor, hashtag, mention, base64, base64url, semver, macAddress, time24, time12, date, isoDateTime, latitude, longitude, slug, username). It excludes the parametric-only helpers digits, time, password, and custom. PostalCountry is the union of ISO codes regex.postalCode({ country }) accepts.

The check-digit validators share one signature:

type CheckDigitValidator = (value: unknown) => boolean
// isLuhn, isValidCard, isValidClabe, isValidNss, isValidCurp,
// isValidRfc, isValidIban, isValidRoutingNumber, isValidDniEs

Regex

The full type of the regex export. Useful when you write a wrapper around the dictionary.

import type { Regex } from '@samline/formatter'

function getErrorMessage(key: keyof Regex, value: string): string {
  const entry = regex[key]
  if (typeof entry === 'function') return 'Validation pending.'
  return entry.pattern.test(value) ? '' : entry.errorMessage
}

Parametric regex signatures

function regex.digits(params?: number | { length?: number; min?: number; max?: number }): RegexEntry
function regex.phone(params?: { length?: number }): RegexEntry
function regex.creditCard(params?: { min?: number; max?: number }): RegexEntry
function regex.url(params?: { protocol?: 'http' | 'https' | 'ftp' | 'all' }): RegexEntry
function regex.password(params?: {
  min?: number
  max?: number
  uppercase?: boolean
  lowercase?: boolean
  numbers?: boolean
  special?: boolean
}): RegexEntry

function regex.uuid(params?: { version?: number }): RegexEntry // 1–8
function regex.postalCode(params?: { country?: PostalCountry }): RegexEntry // default 'US'

// Same option names as format(value, 'date' | 'time' | 'numeral', options)
function regex.date(params?: { datePattern?: DatePatternType; delimiter?: string }): RegexEntry
function regex.time(params?: {
  timePattern?: TimePatternType
  timeFormat?: '12' | '24'
  delimiter?: string
}): RegexEntry
function regex.numeral(params?: {
  delimiter?: string
  numeralDecimalMark?: string
  numeralThousandsGroupStyle?: NumeralThousandsGroupStyle
  numeralDecimalScale?: number
  numeralPositiveOnly?: boolean
  prefix?: string
  tailPrefix?: boolean
  signBeforePrefix?: boolean
}): RegexEntry

function regex.custom(pattern: RegExp, errorMessage?: string): RegexEntry
function regex.custom(params: { pattern: RegExp; errorMessage: string }): RegexEntry

See the regex reference for examples of every overload.

Static regex record type

When you need to know the exact shape of a particular entry, pick it directly off the dictionary:

import { regex } from '@samline/formatter'

const emailEntry = regex.email
//    ^? { pattern: RegExp; errorMessage: string }

const phoneCallable = regex.phone
//    ^? ((params?: { length?: number }) => RegexEntry) & RegexEntry

const urlCallable = regex.url
//    ^? ((params?: { protocol?: 'http' | 'https' | 'ftp' | 'all' }) => RegexEntry) & RegexEntry

The callable entries (phone, creditCard, url, uuid, date, numeral, postalCode) carry the static .pattern and .errorMessage so callers can use either form without an if-branch. digits, time, password and custom only have an errorMessage until called.


Advanced helper signatures

The lower-level helpers used internally by format(). They are exported because they are useful in isolation, but the public contract is format().

// From '@samline/formatter/phone'
function registerPhone(): void
function isPhoneRegistered(): boolean // also exported from the root
function formatPhone(
  value: string,
  country?: string, // ISO 3166-1 alpha-2; defaults to 'MX'
  delimiter?: string // group separator; defaults to ' '
): string

function getRawValue(formatted: string, formatType: FormatType, options?: FormatOptions): string

function getDateValueFromRaw(value: string, options?: FormatOptions): string

function getTimeValueFromRaw(value: string, options?: FormatOptions): string

function looksLikeRawDateValue(value: string, options?: FormatOptions): boolean

function looksLikeRawTimeValue(value: string, options?: FormatOptions): boolean

function stripPrefixAndSuffix(value: string, options?: FormatOptions): string

stripPrefixAndSuffix removes a leading prefix, a dedicated trailing suffix, and the legacy prefix-as-suffix form selected by tailPrefix: true.


Generic input handling

format accepts unknown as its value type. Cast or guard inputs as needed; most consumers come from e.target.value, which is always string.

import type { FormatterResult } from '@samline/formatter'

function handleInput(rawEvent: Event): FormatterResult | null {
  const target = rawEvent.target as HTMLInputElement
  if (!target.value) return null
  return format(target.value, 'phone', { country: 'MX' })
}

Default type aliases

// Format-side defaults
type DatePatternType = ('d' | 'm' | 'y' | 'Y')[]
type TimePatternType = ('h' | 'm' | 's')[]
type NumeralThousandsGroupStyle = 'thousand' | 'lakh' | 'wan' | 'none'

// Regex-side defaults
type PostalCountry = 'US' | 'MX' | 'CA' | 'GB' | 'IE' | 'DE' | 'FR' | 'ES' | 'IT' | 'PT' | 'NL' | 'BE'
  | 'AT' | 'CH' | 'PL' | 'SE' | 'BR' | 'AR' | 'CO' | 'CL' | 'PE' | 'JP' | 'IN' | 'AU'
type RegexKey = /* union of static-entry keys */
type Regex = typeof regex
interface RegexEntry { pattern: RegExp; errorMessage: string }

These are the literal aliases exported by the package. Since 3.0.0 numeralThousandsGroupStyle accepts the plain strings; the NumeralThousandGroupStyles enum from cleave-zen is no longer needed.

Intl option types

Exported from @samline/formatter/intl. Each extends IntlCommonOptions (locale?: string | readonly string[], fallback?: string).

TypeUsed byAdds
IntlNumberOptionsformatNumberdecimals, minDecimals, maxDecimals and Intl.NumberFormatOptions fields
IntlCurrencyOptionsformatCurrencythe number fields plus required currency, display, currencySign
IntlPercentOptionsformatPercentthe number fields
IntlDateOptionsformatDatepreset, pattern and Intl.DateTimeFormatOptions fields
IntlRelativeTimeOptionsformatRelativeTimenow, style, numeric, unit, pattern

Input types: IntlNumberInput (number | bigint | string | null | undefined) and IntlDateInput (Date | number | string | null | undefined). See the Intl display reference.

Date types

Exported from @samline/formatter/date.

TypeMeaning
DateInputDate | number | string
DateOptionstimeZone, locale, weekStart, minimalDays, taken by most functions
DateUnit'year' | 'quarter' | 'month' | 'week' | 'isoWeek' | 'day' | 'hour' | 'minute' | 'second' | 'millisecond'
DateSetUnitThe units setDateUnit changes, including 'weekday', 'isoWeekday' and 'dayOfYear'
DateParts / DatePartsInputWall-clock parts read by getDateParts / written by createDate; month is 1–12
Weekday / WeekInfo0 (Sunday) – 6; { firstDay, minimalDays, weekend }
ParseDateOptionsformat, strict and the date options
FormatDatePatternOptions / CalendarOptionsThe date options plus fallback; CalendarOptions adds now and sameElse
DiffOptions / BetweenOptions / RelativeDayOptions / ZoneOptionsfloat; unit and inclusivity; now; timeZone
Duration / DurationInput / DurationObject / DurationUnitA complete duration; milliseconds, ISO 8601 or an object; its fields; its units
FormatDurationOptions / HumanizeDurationOptionslocale, style, fallback; plus withSuffix

See the Date tools reference.