@20baht/formats 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nattapong Promthong
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,116 @@
1
- # Temporary Holding Version
1
+ # @20baht/formats
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Named value formats, and a few display formats (a relative time, a duration, money:
4
+ [below](#display-formats)). Each value format is three plain functions: a **check**, a **normaliser** (the one spelling to
5
+ store) and a **formatter** (the spelling people read). No dependencies, no DOM; the same code runs in the
6
+ browser and on the server.
7
+
8
+ ```bash
9
+ bun add @20baht/formats
10
+ ```
11
+
12
+ | Export | Valid when | `normalize` | `format` |
13
+ | --- | --- | --- | --- |
14
+ | `thaiId` | 13 digits, first digit 1–8, check digit fits | `1101700230708` | `1-1017-00230-70-8` |
15
+ | `thaiTaxId` | 13 digits (a juristic person's begin with 0, or a person's own ID), check digit fits | `0101000000001` | `0-1010-00000-00-1` |
16
+ | `thaiPhone` | Thai mobile (06/08/09 + 8 digits) or landline (9 digits), national or `+66` | `+66812345678` | `081-234-5678` |
17
+ | `e164` | `+` and 8–15 digits, the first not 0 (shape only) | `+14155552671` | `+14155552671` |
18
+ | `cardNumber` | 12–19 digits passing the Luhn check | `4111111111111111` | `4111 1111 1111 1111` |
19
+ | `iban` | ISO 13616 shape and the mod-97 check | `GB82WEST12345698765432` | `GB82 WEST 1234 5698 7654 32` |
20
+
21
+ Also `luhn(digits)`, the bare check.
22
+
23
+ ```ts
24
+ import { thaiId, thaiPhone } from '@20baht/formats';
25
+
26
+ thaiId.check('1-1017-00230-70-8'); // true: spaces and dashes are read through
27
+ thaiId.normalize('1-1017-00230-70-8'); // '1101700230708', or null when not valid
28
+ thaiPhone.normalize('081-234-5678'); // '+66812345678'
29
+ thaiPhone.format('+66812345678'); // '081-234-5678'; a value that is not valid comes back as it was
30
+ ```
31
+
32
+ Nothing throws: a value that is not text (or a whole number, for the all-digit formats) is not valid.
33
+
34
+ ## In a bahtui form
35
+
36
+ `formatRegistry()` wraps every format as registry entries, so a schema refers to one by name and the
37
+ browser and the server give the same answer from one import:
38
+
39
+ ```jsonc
40
+ { "type": "text", "key": "citizen_id", "label": "ID card",
41
+ "formatter": "thaiId",
42
+ "validators": [{ "type": "custom", "fn": "thaiId" }] }
43
+ ```
44
+
45
+ ```ts
46
+ import { formatRegistry } from '@20baht/formats';
47
+
48
+ // browser
49
+ form.registry = { ...formatRegistry({ locale: 'th' }) };
50
+
51
+ // server
52
+ const result = validateSubmission(schema, body, formatRegistry({ locale: 'th' }));
53
+ ```
54
+
55
+ Merge it with a registry of your own by spreading both levels:
56
+
57
+ ```ts
58
+ const formats = formatRegistry();
59
+ form.registry = {
60
+ ...mine,
61
+ validators: { ...formats.validators, ...mine.validators },
62
+ formatters: { ...formats.formatters, ...mine.formatters },
63
+ };
64
+ ```
65
+
66
+ - A **validator** answers `null` for a valid value and for an empty one (`required` owns emptiness), else
67
+ a message: English or Thai (`locale`), or your own per format (`messages: { iban: '…' }`). A schema's own
68
+ `message` on the validator still wins.
69
+ - A **formatter** runs while the user types: it rewrites a complete, valid value to its display spelling and
70
+ leaves anything else untouched. The value the form submits is therefore the display spelling
71
+ (`1-1017-00230-70-8`); the validator reads it through, and the server stores `thaiId.normalize(value)`.
72
+
73
+ The names are `FORMAT_NAMES`: `thaiId`, `thaiTaxId`, `thaiPhone`, `e164`, `cardNumber`, `iban`.
74
+
75
+ ## Display formats
76
+
77
+ Three plain functions for text people read, not values to store: no check, no normaliser. They use Intl,
78
+ so the words are CLDR's for the locale: `en` by default (as `formatRegistry`), `th`, or any BCP 47 tag.
79
+ Nothing throws: a value they cannot read, or a locale or currency Intl does not know, gives `''`.
80
+
81
+ ```ts
82
+ import { duration, money, relativeTime } from '@20baht/formats';
83
+
84
+ relativeTime(createdAt); // '5 minutes ago', against the clock
85
+ relativeTime(createdAt, { now, locale: 'th' }); // '5 นาทีที่ผ่านมา'
86
+ duration(65 * 60_000); // '1h 5m'
87
+ duration(65 * 60_000, { locale: 'th' }); // '1ชม. 5นาที'
88
+ money(1234.5, 'THB', { locale: 'th' }); // '฿1,234.50'
89
+ money('12345678901234567.89', 'USD'); // '$12,345,678,901,234,567.89'
90
+ ```
91
+
92
+ - **`relativeTime(date, { now, locale })`**: `date` is a `Date`, epoch milliseconds or a date string; `now`
93
+ defaults to `Date.now()`. The unit is the largest the gap has one whole of (second, minute, hour, day, week,
94
+ month as 30 days, year as 365), and the count is cut toward zero: 3 h 59 min is `3 hours ago`, 29 days
95
+ `4 weeks ago`. Always a number (`1 day ago`, not `yesterday`), except under a second either way: `now` /
96
+ `ขณะนี้`.
97
+ - **`duration(ms, { locale })`**: the largest unit with a whole one and the unit after it, the second left out
98
+ when it is zero, both cut, never rounded up: `1h 5m`, `1d 1h` (for 1 d 1 h 1 min 1 s), `2h` (for 2 h 30 s),
99
+ `1h 59m` (for 1 h 59 min 59 s). Units are CLDR's narrow ones, the spelling `Intl.DurationFormat`'s narrow
100
+ style gives. Days are the largest unit (`400d 3h`); under a second it shows milliseconds (`450ms`), and 0 is
101
+ `0s`. A negative duration gets a minus: `-1h 5m`.
102
+ - **`money(amount, currency, { locale })`**: `Intl.NumberFormat`'s currency style with the currency's own
103
+ decimals (`¥1,235`). `amount` is a number, a bigint or a decimal string (`-?digits(.digits)?`, as a Postgres
104
+ `numeric` arrives), and a string keeps every digit. The symbol is the locale's: `฿1,234.50` in `th`,
105
+ `THB 1,234.50` in `en` (with a no-break space).
106
+
107
+ ## What is not here, and why
108
+
109
+ - **Email.** bahtui's built-in `email` validator is loose on purpose: a strict one refuses real addresses.
110
+ - **Phone numbers of every country.** That is libphonenumber. `e164` checks the shape; `thaiPhone` knows Thailand.
111
+ - **A plain shape** (a postcode, an employee code). A schema already states those as `pattern`.
112
+ - **Thai bank account numbers.** There is no check digit common to the banks; the length is a `pattern`.
113
+ - **IBAN length per country.** That table changes when a country joins; this package ships no data that
114
+ changes on someone else's schedule.
115
+
116
+ A new format is a release of this package and of nothing else: it versions on its own.
@@ -0,0 +1,30 @@
1
+ export interface DisplayOptions {
2
+ /** A BCP 47 tag: `en`, `th`, `th-TH`… Default `en`, as `formatRegistry`. */
3
+ locale?: string;
4
+ }
5
+ export interface RelativeTimeOptions extends DisplayOptions {
6
+ /** The moment `date` is told against. Default the clock (`Date.now()`). */
7
+ now?: Date | number;
8
+ }
9
+ /**
10
+ * How long ago (or how far ahead) `date` is from `now`, in the largest unit it has one whole of,
11
+ * cut toward zero: `5 minutes ago`, `5 นาทีที่ผ่านมา`, `in 2 days`. Less than a second either
12
+ * way is `now` (`ขณะนี้`). Always a number (`1 day ago`, never `yesterday`: 25 hours back may be two
13
+ * calendar days back). '' when `date` or `now` cannot be read.
14
+ */
15
+ export declare function relativeTime(date: Date | number | string, options?: RelativeTimeOptions): string;
16
+ /**
17
+ * A length of time, compact: the largest unit with a whole one and the unit after it when that is
18
+ * not zero, each cut, never rounded up: `1h 5m`, `1d 1h`, `45s`; in Thai `1ชม. 5นาที`. CLDR's
19
+ * narrow units, as `Intl.DurationFormat`'s narrow style spells them. Days are the largest unit
20
+ * (`400d 3h`); under a second it is milliseconds (`450ms`), and 0 is `0s`. A negative duration
21
+ * gets a minus (`-1h 5m`). '' when `ms` is not a finite number.
22
+ */
23
+ export declare function duration(ms: number, options?: DisplayOptions): string;
24
+ /**
25
+ * An amount in a currency (ISO 4217 code), in the locale's way and the currency's own number of
26
+ * decimals: `$1,234.50`, `฿1,234.50` (`th`), `THB 1,234.50` (`en`), `¥1,235`. A decimal string
27
+ * (Postgres `numeric` as a driver hands it over) or a bigint keeps every digit. '' when the amount
28
+ * is not a finite number or a decimal, or the currency or locale is not known.
29
+ */
30
+ export declare function money(amount: number | bigint | string, currency: string, options?: DisplayOptions): string;
@@ -0,0 +1,78 @@
1
+ function attempt(fn) {
2
+ try {
3
+ return fn();
4
+ }
5
+ catch {
6
+ return '';
7
+ }
8
+ }
9
+ function timeOf(value) {
10
+ if (value instanceof Date)
11
+ return value.getTime();
12
+ if (typeof value === 'number')
13
+ return value;
14
+ return typeof value === 'string' ? Date.parse(value) : Number.NaN;
15
+ }
16
+ const SECOND = 1000;
17
+ const MINUTE = 60 * SECOND;
18
+ const HOUR = 60 * MINUTE;
19
+ const DAY = 24 * HOUR;
20
+ const RELATIVE_UNITS = [
21
+ ['year', 365 * DAY],
22
+ ['month', 30 * DAY],
23
+ ['week', 7 * DAY],
24
+ ['day', DAY],
25
+ ['hour', HOUR],
26
+ ['minute', MINUTE],
27
+ ['second', SECOND],
28
+ ];
29
+ export function relativeTime(date, options = {}) {
30
+ const diff = timeOf(date) - timeOf(options.now ?? Date.now());
31
+ if (!Number.isFinite(diff))
32
+ return '';
33
+ const locale = options.locale ?? 'en';
34
+ return attempt(() => {
35
+ for (const [unit, size] of RELATIVE_UNITS) {
36
+ if (Math.abs(diff) >= size) {
37
+ return new Intl.RelativeTimeFormat(locale, { numeric: 'always' }).format(Math.trunc(diff / size), unit);
38
+ }
39
+ }
40
+ return new Intl.RelativeTimeFormat(locale, { numeric: 'auto' }).format(0, 'second');
41
+ });
42
+ }
43
+ const DURATION_UNITS = [
44
+ ['day', DAY],
45
+ ['hour', HOUR],
46
+ ['minute', MINUTE],
47
+ ['second', SECOND],
48
+ ];
49
+ export function duration(ms, options = {}) {
50
+ if (typeof ms !== 'number' || !Number.isFinite(ms))
51
+ return '';
52
+ const locale = options.locale ?? 'en';
53
+ const unit = (count, name) => new Intl.NumberFormat(locale, { style: 'unit', unit: name, unitDisplay: 'narrow' }).format(count);
54
+ const sign = ms < 0 ? -1 : 1;
55
+ let rest = Math.abs(ms);
56
+ return attempt(() => {
57
+ const first = DURATION_UNITS.findIndex(([, size]) => rest >= size);
58
+ if (first === -1)
59
+ return unit(sign * Math.trunc(rest), rest >= 1 ? 'millisecond' : 'second');
60
+ const parts = [];
61
+ for (const [name, size] of DURATION_UNITS.slice(first, first + 2)) {
62
+ const count = Math.trunc(rest / size);
63
+ rest -= count * size;
64
+ if (count > 0)
65
+ parts.push(unit(parts.length === 0 ? sign * count : count, name));
66
+ }
67
+ return parts.join(' ');
68
+ });
69
+ }
70
+ const DECIMAL = /^-?\d+(\.\d+)?$/;
71
+ export function money(amount, currency, options = {}) {
72
+ const readable = typeof amount === 'bigint' ||
73
+ (typeof amount === 'number' && Number.isFinite(amount)) ||
74
+ (typeof amount === 'string' && DECIMAL.test(amount));
75
+ if (!readable)
76
+ return '';
77
+ return attempt(() => new Intl.NumberFormat(options.locale ?? 'en', { style: 'currency', currency }).format(amount));
78
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * One kind of value, three questions. None of them throws: a value that is not text (or a whole
3
+ * number, for the all-digit formats) is simply not valid.
4
+ */
5
+ export interface Format {
6
+ /** Is this a valid value of the format, however it is spaced or dashed? */
7
+ check(value: unknown): boolean;
8
+ /** The one spelling to store and compare: no separators. `null` when the value is not valid. */
9
+ normalize(value: unknown): string | null;
10
+ /** The spelling people read. A value that is not valid comes back as the text it was. */
11
+ format(value: unknown): string;
12
+ }
13
+ /**
14
+ * A format from its two halves: `parse` (text to the canonical spelling, or null) and `show`
15
+ * (canonical to display).
16
+ */
17
+ export declare function defineFormat(parse: (text: string) => string | null, show: (canonical: string) => string): Format;
18
+ /** Spaces and dashes out; null when anything but digits is left. */
19
+ export declare function digitsOf(text: string): string | null;
20
+ /** `abcdefgh` in groups of 4: `abcd efgh`. */
21
+ export declare function inFours(text: string): string;
package/dist/format.js ADDED
@@ -0,0 +1,26 @@
1
+ function textOf(value) {
2
+ if (typeof value === 'string')
3
+ return value;
4
+ return typeof value === 'number' && Number.isSafeInteger(value) ? String(value) : null;
5
+ }
6
+ export function defineFormat(parse, show) {
7
+ const normalize = (value) => {
8
+ const text = textOf(value);
9
+ return text === null ? null : parse(text);
10
+ };
11
+ return {
12
+ check: (value) => normalize(value) !== null,
13
+ normalize,
14
+ format: (value) => {
15
+ const canonical = normalize(value);
16
+ return canonical === null ? (textOf(value) ?? '') : show(canonical);
17
+ },
18
+ };
19
+ }
20
+ export function digitsOf(text) {
21
+ const digits = text.replace(/[\s-]/g, '');
22
+ return /^\d+$/.test(digits) ? digits : null;
23
+ }
24
+ export function inFours(text) {
25
+ return text.replace(/(.{4})(?=.)/g, '$1 ');
26
+ }
@@ -0,0 +1,5 @@
1
+ export type { Format } from './format.js';
2
+ export { thaiId, thaiPhone, thaiTaxId } from './thai.js';
3
+ export { cardNumber, e164, iban, luhn } from './international.js';
4
+ export { FORMAT_NAMES, formatRegistry, type FormatLocale, type FormatName, type FormatRegistry, type FormatRegistryOptions, } from './registry.js';
5
+ export { duration, money, relativeTime, type DisplayOptions, type RelativeTimeOptions, } from './display.js';
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { thaiId, thaiPhone, thaiTaxId } from './thai.js';
2
+ export { cardNumber, e164, iban, luhn } from './international.js';
3
+ export { FORMAT_NAMES, formatRegistry, } from './registry.js';
4
+ export { duration, money, relativeTime, } from './display.js';
@@ -0,0 +1,19 @@
1
+ import { type Format } from './format.js';
2
+ /**
3
+ * A phone number in E.164: `+`, then 8 to 15 digits, the first not 0. This is the shape only:
4
+ * whether a country has such a number is libphonenumber's question, not this package's.
5
+ */
6
+ export declare const e164: Format;
7
+ /**
8
+ * The Luhn check (ISO/IEC 7812) on a string of digits: from the right, every second digit is
9
+ * doubled (and 9 taken off when that passes 9); the total must end in 0.
10
+ */
11
+ export declare function luhn(digits: string): boolean;
12
+ /** A payment card number: 12 to 19 digits that pass the Luhn check. */
13
+ export declare const cardNumber: Format;
14
+ /**
15
+ * An IBAN (ISO 13616): two letters, two check digits, then 11 to 30 letters or digits; with the
16
+ * first four characters moved to the end, the number is 1 modulo 97. The length each country
17
+ * uses is not checked: that table changes when a country joins, and belongs to the host.
18
+ */
19
+ export declare const iban: Format;
@@ -0,0 +1,37 @@
1
+ import { defineFormat, digitsOf, inFours } from './format.js';
2
+ export const e164 = defineFormat((text) => {
3
+ const compact = text.replace(/[\s().-]/g, '');
4
+ return /^\+[1-9]\d{7,14}$/.test(compact) ? compact : null;
5
+ }, (canonical) => canonical);
6
+ export function luhn(digits) {
7
+ if (!/^\d+$/.test(digits))
8
+ return false;
9
+ let sum = 0;
10
+ for (let i = 0; i < digits.length; i++) {
11
+ const digit = Number(digits[digits.length - 1 - i]);
12
+ const doubled = digit * 2;
13
+ if (i % 2 === 0)
14
+ sum += digit;
15
+ else
16
+ sum += doubled > 9 ? doubled - 9 : doubled;
17
+ }
18
+ return sum % 10 === 0;
19
+ }
20
+ export const cardNumber = defineFormat((text) => {
21
+ const digits = digitsOf(text);
22
+ return digits && digits.length >= 12 && digits.length <= 19 && luhn(digits) ? digits : null;
23
+ }, inFours);
24
+ function mod97(text) {
25
+ let remainder = 0;
26
+ for (const char of text) {
27
+ const value = char >= 'A' ? String(char.charCodeAt(0) - 55) : char;
28
+ remainder = Number(`${remainder}${value}`) % 97;
29
+ }
30
+ return remainder;
31
+ }
32
+ export const iban = defineFormat((text) => {
33
+ const compact = text.replace(/\s/g, '').toUpperCase();
34
+ if (!/^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$/.test(compact))
35
+ return null;
36
+ return mod97(compact.slice(4) + compact.slice(0, 4)) === 1 ? compact : null;
37
+ }, inFours);
@@ -0,0 +1,40 @@
1
+ import type { Format } from './format.js';
2
+ declare const FORMATS: {
3
+ thaiId: Format;
4
+ thaiTaxId: Format;
5
+ thaiPhone: Format;
6
+ e164: Format;
7
+ cardNumber: Format;
8
+ iban: Format;
9
+ };
10
+ export type FormatName = keyof typeof FORMATS;
11
+ /** The names a schema refers to: `{ "type": "custom", "fn": "thaiId" }`, `"formatter": "thaiId"`. */
12
+ export declare const FORMAT_NAMES: FormatName[];
13
+ export type FormatLocale = 'en' | 'th';
14
+ export interface FormatRegistryOptions {
15
+ /** Language of the built-in messages. Default `en`. */
16
+ locale?: FormatLocale;
17
+ /** A message of your own per format; the rest keep the built-in one. */
18
+ messages?: Partial<Record<FormatName, string>>;
19
+ }
20
+ /**
21
+ * The part of a bahtui `Registry` these formats fill. Structural on purpose: this package does
22
+ * not import the engine, and the two shapes fit (a validator may ignore the `data` and `field`
23
+ * it is also handed).
24
+ */
25
+ export interface FormatRegistry {
26
+ validators: Record<FormatName, (value: unknown) => string | null>;
27
+ formatters: Record<FormatName, (value: unknown) => unknown>;
28
+ }
29
+ /**
30
+ * Every format as registry entries, for the browser and the server alike:
31
+ *
32
+ * element.registry = { ...formatRegistry({ locale: 'th' }) };
33
+ * validateSubmission(schema, body, formatRegistry());
34
+ *
35
+ * A validator answers null for a valid or an empty value (`required` owns emptiness), else the
36
+ * message. A formatter rewrites a complete, valid value to its display spelling and returns
37
+ * anything else untouched: it runs while the user types.
38
+ */
39
+ export declare function formatRegistry(options?: FormatRegistryOptions): FormatRegistry;
40
+ export {};
@@ -0,0 +1,34 @@
1
+ import { cardNumber, e164, iban } from './international.js';
2
+ import { thaiId, thaiPhone, thaiTaxId } from './thai.js';
3
+ const FORMATS = { thaiId, thaiTaxId, thaiPhone, e164, cardNumber, iban };
4
+ export const FORMAT_NAMES = Object.keys(FORMATS);
5
+ const MESSAGES = {
6
+ en: {
7
+ thaiId: 'Enter a valid Thai national ID number',
8
+ thaiTaxId: 'Enter a valid Thai tax ID number',
9
+ thaiPhone: 'Enter a valid Thai phone number',
10
+ e164: 'Enter a phone number in international format, like +66812345678',
11
+ cardNumber: 'Enter a valid card number',
12
+ iban: 'Enter a valid IBAN',
13
+ },
14
+ th: {
15
+ thaiId: 'เลขประจำตัวประชาชนไม่ถูกต้อง',
16
+ thaiTaxId: 'เลขประจำตัวผู้เสียภาษีไม่ถูกต้อง',
17
+ thaiPhone: 'หมายเลขโทรศัพท์ไม่ถูกต้อง',
18
+ e164: 'กรอกหมายเลขโทรศัพท์รูปแบบสากล เช่น +66812345678',
19
+ cardNumber: 'หมายเลขบัตรไม่ถูกต้อง',
20
+ iban: 'IBAN ไม่ถูกต้อง',
21
+ },
22
+ };
23
+ const isEmpty = (value) => value === null || value === undefined || value === '';
24
+ export function formatRegistry(options = {}) {
25
+ const messages = { ...MESSAGES[options.locale ?? 'en'], ...options.messages };
26
+ const validators = {};
27
+ const formatters = {};
28
+ for (const name of FORMAT_NAMES) {
29
+ const format = FORMATS[name];
30
+ validators[name] = (value) => (isEmpty(value) || format.check(value) ? null : messages[name]);
31
+ formatters[name] = (value) => (format.check(value) ? format.format(value) : value);
32
+ }
33
+ return { validators, formatters };
34
+ }
package/dist/thai.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ import { type Format } from './format.js';
2
+ /**
3
+ * A Thai national ID number: 13 digits, a first digit of 1 to 8 (the kinds of person the
4
+ * register knows) and a check digit that fits.
5
+ */
6
+ export declare const thaiId: Format;
7
+ /**
8
+ * A Thai taxpayer identification number: the 13 digits of a juristic person (they begin with 0)
9
+ * or a person's own national ID. Same check digit.
10
+ */
11
+ export declare const thaiTaxId: Format;
12
+ /**
13
+ * A Thai phone number, mobile or landline, written nationally (`081-234-5678`) or with the
14
+ * country code (`+66 81 234 5678`). Normalises to E.164 (`+66812345678`).
15
+ */
16
+ export declare const thaiPhone: Format;
package/dist/thai.js ADDED
@@ -0,0 +1,37 @@
1
+ import { defineFormat, digitsOf } from './format.js';
2
+ function checkDigitFits(digits) {
3
+ let sum = 0;
4
+ for (let i = 0; i < 12; i++)
5
+ sum += Number(digits[i]) * (13 - i);
6
+ return (11 - (sum % 11)) % 10 === Number(digits[12]);
7
+ }
8
+ function thirteen(text) {
9
+ const digits = digitsOf(text);
10
+ return digits?.length === 13 && checkDigitFits(digits) ? digits : null;
11
+ }
12
+ const dashed = (d) => `${d.slice(0, 1)}-${d.slice(1, 5)}-${d.slice(5, 10)}-${d.slice(10, 12)}-${d.slice(12)}`;
13
+ export const thaiId = defineFormat((text) => {
14
+ const digits = thirteen(text);
15
+ return digits && /^[1-8]/.test(digits) ? digits : null;
16
+ }, dashed);
17
+ export const thaiTaxId = defineFormat(thirteen, dashed);
18
+ function thaiNational(text) {
19
+ const compact = text.replace(/[\s().-]/g, '');
20
+ const match = /^(?:\+?66|0)0?(\d+)$/.exec(compact);
21
+ const national = match?.[1];
22
+ if (national === undefined)
23
+ return null;
24
+ return /^(?:[689]\d{8}|[23457]\d{7})$/.test(national) ? national : null;
25
+ }
26
+ function nationalDisplay(e164Number) {
27
+ const n = e164Number.slice(3);
28
+ if (n.length === 9)
29
+ return `0${n.slice(0, 2)}-${n.slice(2, 5)}-${n.slice(5)}`;
30
+ return n.startsWith('2')
31
+ ? `02-${n.slice(1, 4)}-${n.slice(4)}`
32
+ : `0${n.slice(0, 2)}-${n.slice(2, 5)}-${n.slice(5)}`;
33
+ }
34
+ export const thaiPhone = defineFormat((text) => {
35
+ const national = thaiNational(text);
36
+ return national === null ? null : `+66${national}`;
37
+ }, nationalDisplay);
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@20baht/formats",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "type": "module",
5
+ "engines": {
6
+ "node": ">=20.19.0"
7
+ },
8
+ "description": "Named value formats with a check, a normaliser and a display formatter each: Thai national ID and tax ID, Thai phone numbers, E.164, card numbers (Luhn) and IBAN; display formats for a relative time, a duration and money. No dependencies; plugs into a bahtui registry.",
9
+ "license": "MIT",
10
+ "author": "Nattapong Promthong",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/bank20baht/20baht.git",
14
+ "directory": "packages/core/formats"
15
+ },
16
+ "homepage": "https://github.com/bank20baht/20baht/tree/main/packages/core/formats#readme",
17
+ "bugs": {
18
+ "url": "https://github.com/bank20baht/20baht/issues"
19
+ },
20
+ "keywords": [
21
+ "validation",
22
+ "thai-id",
23
+ "tax-id",
24
+ "phone",
25
+ "luhn",
26
+ "iban",
27
+ "forms"
28
+ ],
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "files": [
33
+ "dist"
34
+ ],
35
+ "exports": {
36
+ ".": {
37
+ "types": "./dist/index.d.ts",
38
+ "import": "./dist/index.js",
39
+ "default": "./dist/index.js"
40
+ },
41
+ "./package.json": "./package.json"
42
+ },
43
+ "scripts": {
44
+ "build": "rm -rf dist && tsc -p tsconfig.json --removeComments && tsc -p tsconfig.json --emitDeclarationOnly",
45
+ "test": "vitest run",
46
+ "test:watch": "vitest",
47
+ "test:coverage": "vitest run --coverage"
48
+ },
49
+ "devDependencies": {
50
+ "typescript": "^5.9.3",
51
+ "vitest": "^3.2.4"
52
+ },
53
+ "main": "./dist/index.js",
54
+ "types": "./dist/index.d.ts",
55
+ "sideEffects": false
56
+ }