- Docs
- Changelog
Changelog
Release history for @samline/formatter: fixes, behavior changes and explicitly marked breaking changes.
All notable changes to @samline/formatter are documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
[3.3.1] - 2026-11-17
Changed
- Internal: source uses arrow functions throughout (TypeScript overloads excepted). No API or behavior change.
[3.3.0] - 2026-11-15
Slugs in other scripts, and pnpm.
Added
slugoptionscharMapandpreserve.charMaptransliterates other scripts before slugging:'cyrillic','greek','german', your own map such as{ å: 'aa' }, or several merged in order (format('Привет мир', 'slug', { charMap: 'cyrillic' }).rawisprivet-mir). Without it, letters outside Latin are still dropped.preservekeeps characters such as.and_. An unknown preset name or a non-stringpreservethrows aTypeError.- Types
SlugCharMap,CharMapandCharMapName.
Fixed
- Casing (
caseoption:title,sentence,capitalize) andslugifycome from@samline/string1.5.0, so decomposed accents (efollowed by U+0301) stay inside their word instead of starting a new one.
Changed
- Installs with pnpm and runs every script with Bun, with the @samline family CI, Prettier settings and gzip budgets for each public entry.
- CDN examples use pinned jsDelivr URLs.
- The bundled
@samline/stringgrows the core by about 0.8 KB gzip; the documented budgets are nowformatalone under 18 KB minified, every root export under 34 KB (13 KB gzip) and the core IIFE under 38 KB. - Test toolchain upgraded to Vitest 5 and jsdom 30 (the previous Vitest had published advisories).
Tests
- Coverage thresholds: 90 % branches and 95 % statements, functions and lines, with new tests for the date module.
- Playwright tests of the three standalone scripts in Chromium, Firefox and WebKit.
3.2.1 - 2026-11-15
Fixes for the date tools in Japanese, Chinese and Korean, and two new date-tools examples.
Fixed
- Month names in Japanese and Chinese.
formatDatePattern(date, 'D MMMM YYYY', { locale: 'ja' })printed'23 3 2026':Intlwrites the month as a number with月as a separate part, and only the number was kept.MMMMandMMMnow keep the counter ('23 3月 2026') inja,zhandzh-TW, as Day.js did. - Korean month and weekday names in
parseDate.parseDate('12 11월 2026', { format: 'D MMMM YYYY', locale: 'ko' })returnedundefined: names are compared after Unicode normalization, which splits each Hangul syllable into three letters, and the shortest prefix tried was longer than the name itself.
Documentation
- Examples: two new live fields with the date tools (twenty in all). Check a date strictly has no mask and shows
isValidDateandparseDaterejecting2026-02-30, with the reason written by the example itself; Move a date by months showsformatDatePattern(endOfDate(addDate(date, n, 'month'), 'month'), 'YYYY-MM-DD'). Both copy HTML / CDN files that loadformatter.date.global.jsand Package / ESM files that import@samline/formatter/date. parseDatereturnsundefinedfor an invalid date where@samline/datereturned{ isValid: false, error }; the migration table inreference/intl.md,reference/date.md, the README and the skill say so.
3.2.0 - 2026-11-13
Date tools in a new @samline/formatter/date subpath, on the native Date
and Intl APIs with no dependencies. They replace the retired
@samline/date (a Day.js wrapper) and cover the rest of what Day.js and
its plugins offer. Nothing changes for existing imports: input masks for
dates and times stay in the core. The regex catalog was audited: 21
patterns accepted invalid values or rejected valid ones; new patterns
cover common Mexican, US, European and web fields, and check-digit
validators catch the typos a pattern cannot.
Added
@samline/formatter/date. Every function is a separate export and returns a newDate; months are 1–12; any IANA time zone throughtimeZone; names in every locale throughIntl.- Reading:
parseDatewith tokens ('DD/MM/YYYY','D [de] MMMM [de] YYYY','h:mm A', offsets, Unix time), strict by default and with a loose mode, localized month, weekday and AM/PM names, andisValidDate. Impossible dates and skipped daylight-saving times are rejected. - Showing:
formatDatePatternwith the Day.js token set plus ordinals, weeks, offsets, time-zone names and the localizedL/LL/LLL/LLLLformats;formatCalendar('Tomorrow at 9:00 AM');formatRelativeTimefrom./intl, re-exported. - Changing:
addDateandsubtractDate(units or a duration object; month ends clamp and wall times survive daylight saving),startOfDate,endOfDate,setDateUnitandclampDate. - Comparing and measuring:
diffDate(calendar months and days),isBeforeDate,isAfterDate,isSameDate,isSameOrBeforeDate,isSameOrAfterDate,isBetweenDate,minDate,maxDate,isToday,isTomorrow,isYesterday,isWeekend,isLeapYear,daysInMonth,dayOfYear,quarter,weekOfYear,weekYear,isoWeek,isoWeekYear,isoWeeksInYearandgetWeekInfo(locale week rules fromIntl.Locale, with CLDR data where the browser has none). - Time zones:
createDateandgetDatePartsfor wall clocks in any zone,getTimeZoneOffset,getTimeZone,fromUnixandtoUnix. Skipped and repeated times resolve likeDateandTemporal. - Durations:
createDuration(milliseconds, ISO 8601 or an object),durationAs,durationToISO,formatDuration(words in any locale, orH:mm:ss),formatDurationPatternandhumanizeDuration.
- Reading:
formatter.date.global.js. A browser add-on loaded after either global script that addswindow.Formatter.date, reusingFormatter.intl.formatRelativeTime. Exported as@samline/formatter/browser/date.- New
regexentries.personName(O'Connor,Pérez-Gómez,Ma. Fernanda),domain,clabe,nss,time12,isoDateTime,latitude,longitudeandbase64url. - Identity documents. Mexico:
ine(clave de elector),ineCic,ineOcrandpassportMx. US:itinandpassportUs. The US has no national ID card; state driver’s licenses differ per state, so the docs show how to add yours withregex.custom(). - US and European patterns.
ssn,ein,routingNumber,iban,bic,vatEu(all 27 EU countries plus Northern Ireland) anddniEs(Spanish DNI and NIE).postalCode({ country })covers 24 countries (US, MX, CA, GB, IE, DE, FR, ES, IT, PT, NL, BE, AT, CH, PL, SE, BR, AR, CO, CL, PE, JP, IN, AU); the staticpostalCodestays US ZIP. Other countries useregex.custom(). - Check-digit validators.
isLuhn,isValidCard,isValidClabe,isValidNss,isValidCurp,isValidRfc,isValidIban(length per country and mod 97),isValidRoutingNumberandisValidDniEs, exported from the root and aswindow.Formatter.checks. They ignore spaces and hyphens and return a boolean, ready for avalidaterule in@samline/forms. - Patterns that follow the masks.
regex.date(options),regex.time(options)andregex.numeral(options)take the same options asformat()(pattern order, delimiter, 12/24-hour clock, decimal mark, grouping style, decimal scale, sign and prefix) and accept exactly what that mask writes.regex.uuid({ version })pins one UUID version. - Tests for the date tools across six local time zones, daylight-saving days in New York, half-hour offsets, leap years, ISO and locale weeks, and the CLDR fallback; built-package tests for the ESM, CommonJS and add-on entries and their size budget (every date function together under 30 KB minified and 10 KB gzip).
Fixed
regexwas bundled into every application, even one that imported onlyformat(about 5 KB before this release, 12 KB with the new catalog). It is now built in a side-effect-free call, so bundlers drop it when unused:formatalone is about 15 KB minified, down from 21 KB in 3.1.0. The check-digit validators do not pull inregexeither (isValidIbanalone is about 1.3 KB).regex.phoneandregex.creditCardaccepted any non-digit between digits, soabc5512345678passed. Only spaces, hyphens, dots, parentheses and+(phones) or single spaces and hyphens (cards) are allowed now.regex.creditCardrejected valid 12–14 and 17–19 digit cards (Diners, Maestro, long Visa, UnionPay). It now accepts every ISO/IEC 7812 length, 12–19;creditCard({ min, max })still narrows it.regex.emailaccepteda..b@c.com,.a@c.com,a@b..com,<a>@b.comanda,b@c.com. It now checks a dot-atom local part, real domain labels and the 64/254 length limits, and accepts internationalized domains.regex.rfcaccepted month 13 and RFCs without homoclave;regex.curpaccepted any date, sex letter and state. Both now check the date, and CURP checks sex (H, M, X), the state code (NE for abroad), the inner consonants and the check digit position.regex.cprejects00xxx.regex.onlyLettersandonlyAlphanumericrejectedGüemes,Françoisand other accented letters, and accepted blank or multi-line values. They accept letters in every script now and need at least one letter (or digit).regex.urlacceptedhttps://.; it now needs a domain,localhostor an IP host.url({ protocol: 'all' })left outftp, unlike the static entry.regex.ipv4accepted leading zeros (01.02.03.004).regex.ipv6accepted only the full eight-group form and rejected::1and2001:db8::1; it now accepts compressed and IPv4-embedded forms, verified againstnode:net.regex.dateaccepted2026-02-31and2026-02-29; it now checks real calendar days, leap years included.regex.time24accepts optional seconds, as the'time'mask writes them.regex.uuidaccepted only v4 (UUID v7 failed); it accepts versions 1–8 now.regex.hexColoraccepts#RGBAand#RRGGBBAA.regex.hashtagrejected#méxicoand accepted#123;regex.mentionrejected@2pacand@juan.perez.regex.macAddressaccepted mixed separators and now accepts the Cisco form001b.4411.3ab7.regex.semverrejected+buildmetadata and accepted1.2.3-01.regex.base64accepted the empty string.regex.passwordignored non-ASCII capitals such asÑ, andspecial: truedid not count~,`,\or symbols like€. Any character other than a letter, number or space counts as special now.
Documentation
reference/regex.mdwas rewritten: tables for Mexican, US, European and postal rules, the check-digit validators with a@samline/formsexample, and a Compatibility section that lists which patterns became stricter or wider (it used to say nothing that worked before would stop working).reference/intl.md: the migration table from@samline/datepointed users back to that package for date math; it now maps every function to@samline/formatter/date, since@samline/datewas removed from npm.- Recipes: the
@samline/formsrecipe importedregexfrom@samline/forms, which does not export it; it now imports from@samline/formatterand verifies a CURP check digit. New recipes cover check digits, rules built from the mask options and countries without a built-in rule. - API, TypeScript and entrypoint references list the validators, the new builders and
PostalCountry; quoted bundle sizes were re-measured (several were already out of date). - Examples: three new live fields (eighteen in all). Date tools in any language reads the masked date with
parseDateand shows it withformatDatePatternin five locales (the CDN file loadsformatter.date.global.js); Postal code by country buildsregex.postalCode({ country })from a select; IBAN with check digits pairsregex.ibanwithisValidIban. CURP now runsisValidCurpafterregex.curp(its sample values had wrong check digits), the amount and euro fields validate withregex.numeral(options), and the validator gainedregex.phonewith a letters-between-digits sample. A new recipe reads a masked date with the date tools to check an age.
Tests
node:netdecides the expected IPv4 and IPv6 results, andformat()output is fed back intoregex.date,regex.timeandregex.numeral, so the patterns cannot drift from the masks.- Every single-digit typo must fail the Luhn, CLABE, IBAN and routing checks; the CURP test documents the two cases RENAPO’s algorithm cannot see.
test:packagenow bundlesformatalone (under 17 KB) andisValidIbanalone (under 3 KB), so a change that breaks tree-shaking fails the build.
3.1.0 - 2026-11-13
Two new format types and a case option, built on
@samline/string, which is bundled
into the build, so formatter still has libphonenumber-js as its only
runtime dependency (and only through the opt-in phone subpath).
Added
'text'format type. Free text with a casing mode and no mask:case: 'upper' | 'lower' | 'title' | 'sentence' | 'capitalize',smallWordsfor title case (['de', 'la']) andlocalefor locale-aware casing (Turkish İ / ı).rawequalsformatted.'slug'format type. A URL slug while the user types: accents removed, ß, æ, œ, ø, ł transliterated, separators collapsed.formattedkeeps a trailing separator so the space key works;rawis the final, trimmed slug. Options:delimiter(default'-'),replacements(for example{ '&': 'y' }),maxLengthandlocale.caseon'general'. The same casing modes as'text', applied after the mask. It takes precedence overuppercase/lowercase, which keep working unchanged.FORMAT_TYPESlists nine types.
Changed
uppercaseandlowercaseacceptlocalefor locale-aware casing. Withoutlocalethe output is unchanged.- The browser scripts inline only the package
versioninstead of the wholepackage.json, about 1.2 KB gzip less each.window.Formatter.versionis unchanged.
3.0.0 - 2026-11-12
Phones become opt-in so the core no longer bundles libphonenumber-js, the
cleave-zen engine moves into the package, numerals can pad decimals and a new
@samline/formatter/intl subpath formats stored values for display.
Resolves #1,
#2,
#3 and
#4.
Breaking
- Phone support is opt-in.
format(value, 'phone')throws aTypeErroruntilregisterPhone()from the new@samline/formatter/phonesubpath has run once; the error names the fix. Registration applies to every entrypoint (.,/vanilla, ESM and CommonJS share one registry).formatPhonemoved from the root to@samline/formatter/phone. - Browser scripts renamed.
dist/browser/global.global.jsis replaced bydist/browser/formatter.global.js(no phones) anddist/browser/formatter.phone.global.js(phones registered on load). The./browserexport points at the core build;./browser/phoneis new. cleave-zenremoved fromdependencies.numeralThousandsGroupStyleis now the exported string unionNumeralThousandsGroupStyle('thousand' | 'lakh' | 'wan' | 'none') instead of cleave-zen’sNumeralThousandGroupStylesenum.DatePatternTypeandTimePatternTypekeep their shape.
Migration
import { format } from '@samline/formatter'
+ import { registerPhone } from '@samline/formatter/phone'
+ registerPhone()
- import { formatPhone } from '@samline/formatter'
+ import { formatPhone } from '@samline/formatter/phone'
- <script src="https://unpkg.com/@samline/formatter@2.1.0/dist/browser/global.global.js"></script>
+ <script src="https://unpkg.com/@samline/formatter@3.0.0/dist/browser/formatter.phone.global.js"></script>
Pages that format no phones can load formatter.global.js instead.
Added
@samline/formatter/intl:formatNumber,formatCurrency,formatPercent,formatDateandformatRelativeTimeon the nativeIntlAPIs, with no dependencies.null,undefinedand''return''; values that cannot be read return a configurablefallbackinstead ofNaNorInvalid Date;Intl.*Formatinstances are cached by locale and options.formatDatereads formatter’s raw dates ('2026-11-12','20261112', or anypattern) as local calendar dates. The browser builds expose the same functions aswindow.Formatter.intl. Replaces@samline/datefor display; the Intl reference page has migration notes.numeralDecimalPaddingpads the decimal part of a numeral’sformattedvalue up tonumeralDecimalScale(1,234,567.5→1,234,567.50). It defaults tofalse; apply it on blur or for display.rawstays unpadded and dot-decimal, and is stable when the padded value is formatted again.rawDecimalPaddingpads a numeral’srawtonumeralDecimalScale('1234.5'→'1234.50','1234'→'1234.00') for backends that expect a fixed scale. It is independent ofnumeralDecimalPadding, defaults tofalse, andrawstays stable when formatted again.registerPhone()andisPhoneRegistered()(the latter also exported from the root).- The
NumeralThousandsGroupStyletype. - A size budget in
test:package: the root entry stays under 25 KB minified (10 KB gzip) and the core IIFE under 30 KB. Measured for this release: root about 19 KB (7 KB gzip, from about 164 KB), core IIFE about 25 KB withintl, phone IIFE about 165 KB. - Engine unit tests (
test/core/engine.test.ts) whose expected values were recorded from cleave-zen 0.0.17; before the switch a 100,000-case randomized comparison matched the port exactly. - Built-output tests for both IIFEs, the shared phone registry in ESM and CommonJS, the
intlsubpath and the absence of a cleave-zen import.
Changed
- The numeral, date, time, credit-card and general engine is now
src/core/engine/, a strict TypeScript port of the cleave-zen 0.0.17 modules formatter used (MIT notice kept in LICENSE.md). Unused code (the cursor tracker) was not ported, delimiter stripping no longer builds aRegExpper character, and steps that stripped delimiters from digit-only strings were removed. - Casing for
generalmasks and for matching typed affixes goes through oneapplyCase()step, so new modes can be added in a single place.
Fixed
These come from auditing the ported engine and change a few outputs:
- A
','numeralDecimalMarknow groups with'.'when nodelimiteris given. Before, both used',', so1234,5displayed1,234,5with raw1.2345. - Numeral
rawno longer uses anMplaceholder: a prefix containingMleft in the value (-MXN 5withsignBeforePrefix) produced raw-.5instead of-5. Only a minus before the first digit counts as the sign, sogetRawValue('12-3', 'numeral')returns123. - An empty
numeralDecimalMarkfalls back to'.'instead of producing raw values such as.5. - Mastercard detection is limited to 51–55 and 2221–2720;
2220and2721–2799aregeneral. Partial prefixes (222,27,272) still resolve while typing. - A 12-hour
timeturns a typed hour00into12. formatGeneralno longer appendsdelimiterto the caller’sdelimitersarray on every call.- With both
uppercaseandlowercase, affix matching now uses the same casing as the displayed mask (lowercase wins), instead of uppercase.
Documentation
- Corrected examples that never matched the code: the US phone example returns
(202)-555-1234, thetailPrefixexamples needblocks, the card option isstrictMode(notcreditCardStrictMode),stripLeadingZeroesdefaults totrue, and the detected brands are listed as implemented (Elo, Hiper and Hipercard are not detected). - New Intl display reference, phone opt-in sections, decimal padding guide, two-build CDN tables and an updated entrypoint size matrix.
2.1.0 - 2026-11-05
Fixed
- Fixed the browser IIFE (
@samline/formatter/browser, the CDN file): a classic<script>previously leftwindow.Formatteras{ default }, sowindow.Formatter.formatwasundefinedin real browsers. The global now exposesformat,regexandversiondirectly. - Made the default
rawof a prefixed or suffixedgeneralvalue stable when the displayed value is formatted again: the formatter’s owndelimiter/delimitersare removed from the typed body, soformat('ORD-1234-5678', …).rawmatchesformat('12345678', …).raw. Characters thatnumericOnlyhides are still preserved, as documented. - Made canonical
rawvalues (rawPrefix/rawSuffix) strip every configureddelimitersentry, not onlydelimiter. - Restored a locked
prefix/suffix(default'lock'mode) when a single character of the decoration is deleted, instead of duplicating it (100 US→100 USD, not100 US USD). format(value, 'general')without a non-emptyblocksarray now throws a descriptiveTypeErrorinstead of an internalcleave-zenerror.- Phone country codes are now case-insensitive (
'mx'behaves like'MX'). - With
uppercaseorlowercase, aprefix/suffixtyped or pasted in another case is now recognized instead of duplicated (prefixMode: 'passthrough':save20→SAVE20, notSAVESAVE20). In lock mode, a pasted prefix in another case is now excluded fromraw, as documented forrawPrefix: false; the typed body keeps its original case. - Anchored
regex.numeralto the whole value; it previously matched any string containing a digit. It accepts plain or comma-grouped digits with an optional sign and decimals. regex.password()rules are now requirements rather than an allow-list: characters outside the enabled rule groups (such as!withspecial: false) no longer fail validation, and disabling every rule produces a working length-only policy.- Parametric regex builders (
digits,phone,creditCard,password) throw a descriptiveRangeErrorfor negative, fractional or inverted (min > max) ranges instead of an invalid-regexSyntaxError.
Changed
- The browser IIFE is now minified (about 165 KB instead of 272 KB before compression) and ships a source map.
- Replaced the Starlight documentation app with a combined Home, Examples and Docs website built from the shared package website theme. Website commands use the
site:prefix; the npm package remains runtime-only (distandCHANGELOG.md). - Switched repository tooling to Bun workspaces, matching the other
@samlinepackages. - Renamed
LICENSEtoLICENSE.mdand restructured the README to match the other@samlinepackages.
Added
- Added a built-output smoke suite (
npm run test:package) that runs the IIFE as a classic script, compares ESM/CommonJS exports and checks the npm archive contents. It runs in CI andprepublishOnly. - Added the downloadable Formatter integration skill (
skills/formatter/SKILL.md), published at/skills/formatter/SKILL.md. - Added regression tests for every fix above.
2.0.3 - 2026-09-23
Added
- Added internal and Starlight guides for styling and UX, covering visible/raw field structure, native input attributes, accessibility states, caret behavior, and common integration pitfalls.
- Added a documentation synchronization checklist and durable project lessons based on the formatter/forms documentation audit.
Changed
- Reorganized the Starlight guide navigation so framework integration, styling, and recipes form one task-oriented learning path before the reference section.
- Added styling and UX links throughout the README, getting-started pages, recipes, and reference overview.
- Clarified changelog coverage for the prefix/suffix and password-validator regression tests shipped in
2.0.2. - Corrected the reference overview to explain that new pages must be added to the explicit sidebar configuration.
2.0.2 - 2026-09-23
Added
- Exported
DatePatternTypeandTimePatternTypefrom the package entrypoints. - Expanded the internal and Starlight documentation with dedicated API, recipes, entrypoint, framework, and TypeScript references.
- Added regression coverage for dedicated and combined prefix/suffix stripping.
- Strengthened password-validator tests so every enabled uppercase, lowercase, numeric, and special-character requirement is enforced independently.
Fixed
- Made
stripPrefixAndSuffix()remove the dedicatedsuffixoption as documented, including combined prefix/suffix values. - Made parametric password validators enforce each enabled uppercase, lowercase, numeric, and special-character requirement.
- Corrected documentation contracts for
RegexKey, the browser global, affix helpers, and framework examples. - Prevented the country-selector recipe from accumulating input listeners and removed direct DOM mutation from the React recipe.
2.0.1 - 2026-09-23
Fixed
- Corrected automatic date and time interpretation when the configured display delimiter is an empty string.
- Kept the browser global version synchronized with
package.json.
Changed
- Added continuous integration coverage and refreshed the internal and Starlight documentation.
- Removed obsolete implementation history and redundant source comments while preserving public contracts and non-obvious invariants.
[2.0.0] - 2026-07-19
Changed — BREAKING
-
format()now defaults tointerpretInputAs: 'auto'for'date'and'time'inputs. v1.2.0 introduced'display'as the default, which fixed the live-keystroke scramble (typing15091989into ad/m/Ydisplay +Ymdraw field) but exposed the inverse problem: a server-pre-filled raw (Bladeold()carrying"19901212") was now mis-segmented and the visible ended up showing"19/09/1212". v2.0.0 flips the default to a context-aware heuristic: a value with no delimiter and a digit length equal to the raw pattern length is treated as raw; anything else (a value with delimiters, or a partial value) is treated as display. This covers the realistic “general purpose” case without an opt-in: a server-pre-filled raw Ymd is correctly converted to display, and a user keystroke (which always lands with a delimiter after the first digit of each segment) is processed as display socleave-zeninserts the missing separators as it always did.'display'and'raw'are preserved as opt-ins for callers that know the convention unambiguously.// Default (v2.0.0+) — auto-detect raw vs display by the input shape format('19901212', 'date', { datePattern: ['d', 'm', 'Y'], delimiter: '/', dateRawPattern: ['Y', 'm', 'd'], dateRawPatternDelimiter: '' }) // => { formatted: '12/12/1990', raw: '19901212', type: 'date' } // Opt-in to the v1.2.0 strict display interpretation format('15091989', 'date', { datePattern: ['d', 'm', 'Y'], delimiter: '/', dateRawPattern: ['Y', 'm', 'd'], dateRawPatternDelimiter: '', interpretInputAs: 'display' }) // => { formatted: '15/09/1989', raw: '19890915', type: 'date' } // Opt-in to the pre-1.2.0 round-trip rearrangement format('19890915', 'date', { datePattern: ['d', 'm', 'Y'], delimiter: '/', dateRawPattern: ['Y', 'm', 'd'], dateRawPatternDelimiter: '', interpretInputAs: 'raw' }) // => { formatted: '15/09/1989', raw: '19890915', type: 'date' }The only realistic regression is a paste of exactly the raw-pattern digit count with no delimiter (e.g. pasting
"12121990"into ad/m/Y+Ymdfield, which the auto heuristic now routes through the raw branch). Callers that need to disambiguate that case can pass'display'or'raw'explicitly. The keystroke case is unaffected: by the time the input event listener fires, the formatter has already inserted the delimiters, so the value reachingformat()has a delimiter and the auto heuristic routes it through the display branch.
Added
interpretInputAs?: 'auto'as a third value alongside'display'and'raw'. The auto heuristic inspects the value: if it has no delimiter (matching the configureddatePattern/timePatterndelimiter or the default//:) and its digit-only length matches the raw pattern length, it is treated as raw. Otherwise it is treated as display. The heuristic is the new v2.0.0 default; explicit'auto'is accepted for readability and forward-compatibility.looksLikeRawDateValue(value, options?)andlooksLikeRawTimeValue(value, options?)exported helpers that expose the auto heuristic for callers that want to apply the same detection independently offormat()(e.g. a custom form pipeline that needs to know whether to treat an inbound string as raw or display before doing other work).
Migration notes
- From
1.xto2.0.0: this is a breaking change. Pin to1.x(e.g.^1.2.0) if you cannot update immediately. Theformat()API signature is unchanged; the breaking part is the default of one option. The only realistic call site that the new default breaks is one that passes a raw-formatted string with no delimiter toformat()and previously relied on the v1.2.0 display interpretation (which would mis-segment the raw digits) — those sites now correctly produce the canonical display and raw, so the “regression” is in practice a fix. @samline/forms@2.4.0drops the internalinterpretInputAs: 'raw'override that v2.3.5 added to work around the v1.2.0 default; the v2.0.0 formatter default already does the right thing for the initial value pass and the mirror-source events that the override was guarding.
1.2.0 - 2026-07-16
Changed
-
format()now defaults tointerpretInputAs: 'display'for'date'and'time'inputs. Up to 1.1.2,format()always pre-processed the input as raw-formatted: it segmented the digits bydateRawPattern/timeRawPatternand re-emitted them indatePattern/timePatternorder. That works for round-trip callers (asetValuefrom a backend that holds the canonical form), but it scrambles the visible digits whenever a real user types into a field whose display order differs from the raw order — typing15091989into ad/m/Ydisplay with aYmdraw produced visible19/09/0805and hidden08050919(the underlying EasyTrip bug report). The default now matches the realistic case —format()is called from aninputevent listener with the visible value, which is in display order — and the legacy round-trip interpretation is preserved as a strict opt-in:interpretInputAs: 'raw'. The fix is applied symmetrically to thedateandtimebranches ofgetValueForFormatting.// Default (v1.2.0+) — live keystrokes in display order format('15091989', 'date', { datePattern: ['d', 'm', 'Y'], delimiter: '/', dateRawPattern: ['Y', 'm', 'd'], dateRawPatternDelimiter: '' }) // => { formatted: '15/09/1989', raw: '19890915', type: 'date' } // Opt-in to the legacy round-trip semantics format('19890915', 'date', { datePattern: ['d', 'm', 'Y'], delimiter: '/', dateRawPattern: ['Y', 'm', 'd'], dateRawPatternDelimiter: '', interpretInputAs: 'raw' }) // => { formatted: '15/09/1989', raw: '19890915', type: 'date' } -
getTimeRawValuenow derives its delimiter fromoptions.delimiterwhentimeRawPatternDelimiteris not set, matching the 1.1.1 fix that was applied togetDateRawValuebut never ported to the time branch. A single{ timePattern, timeRawPattern, delimiter }configuration now round-trips consistently without the consumer having to repeat the delimiter in the raw options. ExplicittimeRawPatternDelimiterstill wins over the display delimiter.// Before 1.2.0: raw delimiter ignored the display `delimiter: '-'`, // always used the default `:`. The display and the raw did not agree. format('143000', 'time', { timePattern: ['h', 'm', 's'], timeRawPattern: ['h', 'm'], delimiter: '-' }) // => { formatted: '14-30-00', raw: '14-30', type: 'time' }
Added
interpretInputAs?: 'display' | 'raw'option onFormatOptions, applied to the'date'and'time'branches offormat(). Default'display'(the realistic live-keystroke case). Set to'raw'to opt into the legacy pre-1.2.0 round-trip semantics where the input is segmented bydateRawPattern/timeRawPatternand re-emitted indatePattern/timePatternorder. See the### Changedentry above for examples.
1.1.2 - 2026-07-14
Fixed
-
numericOnly/uppercase/lowercasenot applied to therawmirror whenprefix/suffixare configured andrawPrefix/rawSuffixare set. Up to 1.1.1, theformattedvalue went throughcleave-zen.formatGeneral(which honoursnumericOnlyand the case transforms), but the body part of therawmirror was built from the user’s typed input verbatim. A user fat-fingering letters into anumericOnly: truefield would see a clean display but ship a contaminated canonical identifier (e.g.EASY1a2b3c4d5e6f7g8h9i) to the backend. The fix derives the body part of the raw frombodyFormatted(with the display delimiter stripped) only when the caller has opted into a canonical raw viarawPrefix: true/rawSuffix: true; callers who keep the historical default (rawPrefix: false/rawSuffix: false) see no change. The defensivenumericOnlystrip is still applied so the canonical raw is digits-only when the caller asked for digits-only.// Repro from the upstream bug report — now fixed. format('1a2b3c4d5e6f7g8h9i', 'general', { blocks: [4, 5], delimiter: ' ', prefix: 'EASY', prefixMode: 'lock', rawPrefix: true, numericOnly: true }) // => { formatted: 'EASY1234 56789', raw: 'EASY123456789', type: 'general' }
[1.1.1] - 2026-07-14
Added
general+prefixis now fully formatter-managed. The formatter used to delegateprefixhandling tocleave-zen’sstripPrefix, which discards any input that doesn’t already start with the configured prefix and freezes the field at the literal prefix. We now manage the prefix on the formatter’s side:lockmode (default) auto-prepends the configured prefix and lets the user type only the suffix;passthroughmode reflects whatever the user has typed of the prefix instead. Both modes let input flow through to the suffix on every keystroke instead of snapping the field to the prefix.rawPrefix: booleanoption forgeneralformats. Whentrue, therawmirror includes the configured prefix (so aprefix: 'EASY'field withrawPrefix: truemirrorsEASY123456789, ready to ship to a backend that expects the canonical identifier). Defaults tofalseso the historical “digits only” raw mirror is preserved unless the caller opts in.suffix,suffixModeandrawSuffixforgeneralformats. Symmetric withprefix/prefixMode/rawPrefix: the formatter now manages a dedicated tail decoration independent of the head.suffixstrings can be wholly different fromprefix(e.g.prefix: 'PRE-',suffix: '-END'for aPRE-12345-ENDfield).suffixMode: 'lock'auto-appends the configured suffix (default);suffixMode: 'passthrough'lets the user type it character-by-character.rawSuffix: trueadds the suffix to therawmirror, independent ofrawPrefix. Backwards compatible: the historicalprefix + tailPrefix: trueshape continues to work;suffixtakes precedence when both are provided.
Fixed
format('date')round-trip self-consistency. When callers customisedatePattern(or itsdelimiter) without also settingdateRawPatternanddateRawPatternDelimiter, the formatted display and the raw mirror no longer diverge silently. Both now derive from the display pattern / delimiter when the raw options are absent, so a single configuration such as{ datePattern: ['d', 'm', 'Y'], delimiter: '/' }round-trips15/09/1989↔15/09/1989end-to-end. Callers who need the historical asymmetricY-m-draw output can still opt in by passingdateRawPatternanddateRawPatternDelimiterexplicitly.
[1.1.0] - 2026-06-29
Added
- Expanded regex catalog with parametric and callable entries:
regex.digits(n)/regex.digits({ length })/regex.digits({ min, max })— variable-digit count.regex.phone({ length })— custom phone length (default 10 digits).regex.creditCard({ min, max })— custom card-number range (default 15–16).regex.url({ protocol })— restrict URL schemes (http,https,ftp).regex.password({ min, max, uppercase, lowercase, numbers, special })— composable password rules.
- New
regex.custom()helper for user-defined patterns. Accepts either positional (pattern, errorMessage?) or object ({ pattern, errorMessage }) form. - New built-in patterns:
slug,username,date,time24,ipv4,ipv6,macAddress,hexColor,hashtag,mention,uuid,base64,semver,postalCode. - Improved error messages across the catalog (e.g. card numbers now specify the expected digit range, expiration dates accept both
MM/YYandMM/YYYY, etc.).
Changed
regex.phone,regex.creditCard, andregex.urlare now also callable functions. The static.patternis still attached, so both forms coexist and nothing that worked before stops working.RegexKeyis exported askeyof typeof regexto drive type-safe UIs and iteration.
Documentation
- New “Backward compatibility”, “Usage modes”, and “Pattern reference” sections in
docs/regex.md. - Reference table reorganized into thematic groups (Phone & Identity, Numbers & Cards, Text, Dates & Times, Web & Network, Social, Security, Encoding & Versions, Utilities).
[1.0.1] - 2026-06-29
Changed
- Documentation refresh: added TypeScript support notes and aligned the docs site with the README.
- Homepage URL updated in
package.json.
[1.0.0] - 2026-06-29
Added
- Initial public release of
@samline/formatter. format(value, formatType, options?)core function returning{ formatted, raw, type }.- Supported format types:
general,phone,numeral,date,time,creditCard,creditCardType. - Three entrypoints:
@samline/formatter,@samline/formatter/vanilla,@samline/formatter/browser(IIFE). - Pre-built validation regex catalog with paired error messages.
- Advanced helpers:
formatPhone,getRawValue,getDateValueFromRaw,getTimeValueFromRaw,stripPrefixAndSuffix.