@desource/phone-mask
v2.0.0
Published
⚡ Ultra-lightweight international phone number formatter & validator with auto-sync to Google libphonenumber. Framework-agnostic core library.
Maintainers
Readme
@desource/phone-mask
Core TypeScript library for international phone number masking with Google's libphonenumber data
Framework-agnostic phone masking library that stays up-to-date with Google's libphonenumber database.
Before upgrading to 2.0.0, review Migration from 1.7.0 for breaking changes and required updates.
✨ Features
- 🌍 240+ countries with accurate masks and dialing codes
- 🔄 Auto-synced from Google's libphonenumber
- 🪶 Tiny — root entry is 6.1 KB minified, 2.9 KB gzipped, 2.3 KB brotli
- 🌳 Tree-shakeable — import only what you need
- 🔧 TypeScript — fully typed
- 🎯 Zero dependencies
📦 Installation
npm install @desource/phone-mask
# or
yarn add @desource/phone-mask
# or
pnpm add @desource/phone-maskImport Paths
The root entry contains country metadata and mask data. Display formatting, lower-level formatters, input handling, detection, and utility helpers live in the kit subpath.
import { MasksFullMapEn, type CountryKey } from '@desource/phone-mask';
import { formatPhone, createPhoneFormatter, formatDigitsWithMap } from '@desource/phone-mask/kit';Distribution formats
Package imports use unminified ESM or CommonJS; application bundlers handle tree-shaking and minification. Both entries include TypeScript declarations for each module format.
| Use case | Root entry | Kit entry |
| ------------------------------------- | ---------------------------- | --------------------- |
| ESM, including native browser modules | dist/esm/index.js | dist/esm/kit.js |
| CommonJS | dist/phone-mask.cjs | dist/kit.cjs |
| Browser globals, readable | dist/phone-mask.umd.js | dist/kit.umd.js |
| Browser globals, minified | dist/phone-mask.umd.min.js | dist/kit.umd.min.js |
For browser usage without a build step, load both globals to combine country data with formatting helpers:
<script src="https://cdn.jsdelivr.net/npm/@desource/phone-mask/dist/phone-mask.umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@desource/phone-mask/dist/kit.umd.min.js"></script>
<script>
const result = phoneMaskKit.formatDigitsWithMap(phoneMask.MasksBaseMap.US[0], '2025551234');
console.log(result.display); // "+1 202-555-1234"
</script>Pin both CDN URLs to the same package version in production. UNPKG supports the same file paths.
🚀 Quick Start
Display Formatting
import { formatPhone } from '@desource/phone-mask/kit';
formatPhone('+12345678888'); // '+1 234 567 8888'
formatPhone('2345678888', 'US', { code: false, flag: true }); // '🇺🇸 234 567 8888'See formatPhone for options and supported input formats.
Basic Formatting
import { MasksBaseMap, MasksMap } from '@desource/phone-mask';
import { formatDigitsWithMap } from '@desource/phone-mask/kit';
// Get US mask with country code prefix
const prefixUsMask = MasksBaseMap.US;
// ["+1 ###-###-####"]
// Format digits
const result = formatDigitsWithMap(prefixUsMask[0], '2025551234');
console.log(result.display); // "+1 202-555-1234"
console.log(result.map); // [-1, -1, -1, 0, 1, 2, -1, 3, 4, 5, -1, 6, 7, 8, 9]
// Get US mask without country code prefix
const usMask = MasksMap.US.mask;
// ["###-###-####"]
// Format digits without country code
const resultNoCode = formatDigitsWithMap(usMask[0], '2025551234');
console.log(resultNoCode.display); // "202-555-1234"
console.log(resultNoCode.map); // [0, 1, 2, -1, 3, 4, 5, -1, 6, 7, 8, 9]Working with Country Data
import { MasksFullMapEn, type MaskFull } from '@desource/phone-mask';
// Access country data
const us = MasksFullMapEn.US;
console.log(us.name); // "United States"
console.log(us.code); // "+1"
console.log(us.mask); // ["###-###-####"]
console.log(us.flag); // "🇺🇸"Multiple Mask Variants
Some countries have multiple mask formats:
import { MasksFullMapEn } from '@desource/phone-mask';
const gb = MasksFullMapEn.GB;
console.log(gb.mask);
// [
// "#### ######",
// "### ### ####",
// "## #### ####"
// ]Localized Country Names
import { MasksFullMap } from '@desource/phone-mask';
// Get localized names
const germanMap = MasksFullMap('de');
console.log(germanMap.US.name); // "Vereinigte Staaten"
const frenchMap = MasksFullMap('fr');
console.log(frenchMap.US.name); // "États-Unis"Utility Functions
import { countPlaceholders, removeCountryCodePrefix, pickMaskVariant, extractDigits } from '@desource/phone-mask/kit';
// Count placeholder digits
const count = countPlaceholders('+1 ###-###-####');
// 10
// Remove country code prefix
const stripped = removeCountryCodePrefix('+1 ###-###-####');
// "###-###-####"
// Pick best mask variant for digit count
const variants = ['+44 #### ######', '+44 ### ### ####'];
const best = pickMaskVariant(variants, 10);
// "+44 #### ######"
// Extract only digits from string
const digits = extractDigits('+1 (202) 555-1234');
// "12025551234"Validate Number Against Country Rules
Use createPhoneFormatter() to validate length against a specific country's mask variants.
The recipes below accept local numbers or international numbers with the selected country's calling code. They truncate excess digits to match the framework inputs. Use country.code to remove a known calling code from phone values; removeCountryCodePrefix() is intended for mask templates.
import { MasksFullMapEn, type CountryKey } from '@desource/phone-mask';
import { createPhoneFormatter, extractDigits } from '@desource/phone-mask/kit';
function validateForCountry(input: string, id: CountryKey) {
const country = MasksFullMapEn[id];
const value = input.trim();
if (!country || (value.startsWith('+') && !value.startsWith(country.code))) {
return {
digits: '',
display: '',
isComplete: false
};
}
const formatter = createPhoneFormatter(country);
const inputWithoutCode = value.startsWith(country.code) ? value.slice(country.code.length) : value;
const digits = extractDigits(inputWithoutCode, formatter.getMaxDigits());
return {
digits,
display: formatter.formatDisplay(digits),
isComplete: formatter.isComplete(digits)
};
}
validateForCountry('+1 (202) 555-1234', 'US');
// { digits: "2025551234", display: "202-555-1234", isComplete: true }
validateForCountry('+12025551234', 'US');
// { digits: "2025551234", display: "202-555-1234", isComplete: true }Raw Digits for Backend Processing
Use raw digits for storage and transport. Keep formatting on the client only.
import { MasksFullMapEn, type CountryKey } from '@desource/phone-mask';
import { createPhoneFormatter, extractDigits } from '@desource/phone-mask/kit';
function buildPhonePayload(input: string, id: CountryKey) {
const country = MasksFullMapEn[id];
const value = input.trim();
if (!country || (value.startsWith('+') && !value.startsWith(country.code))) return null;
const formatter = createPhoneFormatter(country);
const inputWithoutCode = value.startsWith(country.code) ? value.slice(country.code.length) : value;
const localDigits = extractDigits(inputWithoutCode, formatter.getMaxDigits());
return {
country: id,
phoneDigits: localDigits, // canonical backend field
phoneE164: `${country.code}${localDigits}` // optional: with dialing prefix
};
}Custom Regex + Metadata (Regional/Carrier Prefixes)
Combine Phone Mask metadata with region-specific regex rules:
import { MasksFullMapEn, type CountryKey } from '@desource/phone-mask';
import { createPhoneFormatter, extractDigits } from '@desource/phone-mask/kit';
const tenantCarrierRules: Partial<Record<CountryKey, RegExp>> = {
BR: /^(11|21|31)\d{8,9}$/,
IN: /^(98|99)\d{8}$/
};
function validateWithCarrierRule(input: string, id: CountryKey): boolean {
const country = MasksFullMapEn[id];
const value = input.trim();
if (!country || (value.startsWith('+') && !value.startsWith(country.code))) return false;
const formatter = createPhoneFormatter(country);
const inputWithoutCode = value.startsWith(country.code) ? value.slice(country.code.length) : value;
const digits = extractDigits(inputWithoutCode, formatter.getMaxDigits());
const carrierRule = tenantCarrierRules[id];
if (!formatter.isComplete(digits)) return false;
return carrierRule ? carrierRule.test(digits) : true;
}Multi-tenant: tenantId Default Country + Tenant-specific Validation Rules
import { MasksFullMapEn, type CountryKey } from '@desource/phone-mask';
import { createPhoneFormatter, extractDigits } from '@desource/phone-mask/kit';
type TenantPolicy = {
defaultCountry: CountryKey;
prefixRule?: RegExp;
};
const TENANT_POLICIES: Record<string, TenantPolicy> = {
acme: { defaultCountry: 'US', prefixRule: /^(202|303)\d{7}$/ },
globex: { defaultCountry: 'GB', prefixRule: /^7\d{9}$/ }
};
function createTenantPhoneService(tenantId: string) {
const policy = TENANT_POLICIES[tenantId] ?? { defaultCountry: 'US' as const };
const id = policy.defaultCountry;
const country = MasksFullMapEn[id];
const formatter = createPhoneFormatter(country);
return {
defaultCountry: id,
format(input: string) {
const value = input.trim();
if (value.startsWith('+') && !value.startsWith(country.code)) return input;
const inputWithoutCode = value.startsWith(country.code) ? value.slice(country.code.length) : value;
const digits = extractDigits(inputWithoutCode, formatter.getMaxDigits());
return formatter.formatDisplay(digits);
},
validate(input: string) {
const value = input.trim();
if (value.startsWith('+') && !value.startsWith(country.code)) return false;
const inputWithoutCode = value.startsWith(country.code) ? value.slice(country.code.length) : value;
const digits = extractDigits(inputWithoutCode, formatter.getMaxDigits());
const complete = formatter.isComplete(digits);
const prefixOk = policy.prefixRule ? policy.prefixRule.test(digits) : true;
return complete && prefixOk;
}
};
}📖 API Reference
Types
// Country ISO 3166-1 alpha-2 code
type CountryKey = 'US' | 'GB' | 'DE' | ... // 240+ countries
// Mask interfaces
interface MaskBase {
id: CountryKey;
mask: Array<string>;
}
interface Mask extends MaskBase {
code: string;
}
interface MaskWithFlag extends Mask {
flag: string;
}
interface MaskFull extends MaskWithFlag {
name: string;
}
type MaskBaseMap = Record<CountryKey, Array<string>>;
type MaskMap = Record<CountryKey, Omit<Mask, 'id'>>;
type MaskWithFlagMap = Record<CountryKey, Omit<MaskWithFlag, 'id'>>;
type MaskFullMap = Record<CountryKey, Omit<MaskFull, 'id'>>;Root Entry Exports
Import mask data and country types from @desource/phone-mask.
MasksBaseMap & MasksBase
Basic country masks including country code prefix (lightweight version):
const MasksBaseMap: MaskBaseMap;
const MasksBase: MaskBase[];Use these to get raw masks with country code prefix. Note: some helper functions may expect masks without country code.
MasksMap & Masks
Masks with country code as separate property:
const MasksMap: MaskMap;
const Masks: Mask[];MasksWithFlagMap & MasksWithFlag
Masks with country code and flag:
const MasksWithFlagMap: MaskWithFlagMap;
const MasksWithFlag: MaskWithFlag[];MasksFullMapEn & MasksFullEn
Full country data with country names in English:
const MasksFullMapEn: MaskFullMap;
const MasksFullEn: MaskFull[];MasksFullMap(locale: string) & MasksFull(locale: string)
Get full country data with localized country names:
function MasksFullMap(locale: string): MaskFullMap;
function MasksFull(locale: string): MaskFull[];Supported locales: en, de, fr, es, it, pt, ru, zh, ja, ko, and more.
getFlagEmoji(countryCode: CountryKey)
Get flag emoji for country code:
function getFlagEmoji(countryCode: CountryKey): string;Kit Subpath Exports
Import formatter, input handling, detection, and utility helpers from @desource/phone-mask/kit.
// Count # placeholders in mask
function countPlaceholders(mask: string): number;
// Remove country code prefix from mask
function removeCountryCodePrefix(mask: string): string;
// Pick best mask variant for digit length
function pickMaskVariant(masks: string[], digitLength: number): string;
// Extract digits from any string
function extractDigits(value: string, maxLength?: number): string;
// Detect a complete international number from current masks
function detectCountryFromPhone(value: string): CountryKey | undefined;
// Format digits according to template
function formatDigitsWithMap(value: string, digits: string): { display: string; map: number[] };detectCountryFromPhone requires a leading +. It first matches formatting exactly, then falls back to
calling code and digit count excluding that code. Shared matches use the calling code's generated default country;
for example, unformatted +1 numbers default to US. Unsupported syntax, unknown calling codes, and
unmatched lengths return undefined. Detection uses masks, not allocation prefixes or number validation.
import { detectCountryFromPhone } from '@desource/phone-mask/kit';
detectCountryFromPhone('+7 123 456 7788'); // 'KZ': unique mask
detectCountryFromPhone('+71234567788'); // 'RU': shared length, default country
detectCountryFromPhone('1234567788'); // undefined: no international prefixprocessPaste returns an optional country when detection succeeds. Apply that country before the
returned newDigits, which excludes the calling code. A detected international paste replaces the whole input and places the
caret at the end, without truncating to the previous country's mask. Other pastes retain normal
selection and insertion behavior.
formatPhone(value, country?, options?)
Format a phone number for display using the country's mask groups, separated by spaces. This pure function works in the browser and during SSR. React, Vue, and Svelte re-export this function for use in templates and JSX. Angular’s PhonePipe delegates to it. Each framework package also exposes it through its /core subpath.
import { formatPhone, type PhoneFormatOptions } from '@desource/phone-mask/kit';
formatPhone('+12345678888'); // '+1 234 567 8888'
formatPhone('2345678888', 'US'); // '+1 234 567 8888'
formatPhone('+1 (234) 567-8888', 'US', { code: false }); // '234 567 8888'
formatPhone('+12345678888', 'US', { flag: true }); // '🇺🇸 +1 234 567 8888'
formatPhone('234 567 8888', 'US', { code: false, flag: true }); // '🇺🇸 234 567 8888'interface PhoneFormatOptions {
readonly code?: boolean; // Include the calling code; defaults to true.
readonly flag?: boolean; // Prepend the flag emoji; defaults to false.
}
function formatPhone(
value: string | null | undefined,
country?: CountryKey | null,
options?: PhoneFormatOptions
): string;Only an explicit + calling code is removed; bare digits are treated as a number without a calling code. Pass an ISO country code for those values. With no country, detection requires a complete international number and uses mask shape, calling code, and length. Shared matches use a default country, such as US for +1; detection does not inspect area-code allocations. Pass undefined or null as the country to combine detection with options.
A supplied country takes priority when its calling code matches, so formatPhone('+12345678888', 'CA', { flag: true }) retains the Canadian flag. If codes conflict, successful detection takes priority: formatPhone('+442079460958', 'US') returns '+44 2079 460958'. Unsuccessful detection preserves the original value.
Significant leading zeros are preserved. Empty, whitespace-only, null, and undefined values return ''. Unsupported countries, invalid characters, extensions, and values exceeding the selected mask's length remain unchanged. The function does not infer trunk prefixes or validate whether a number is assigned. Render its result as text, as with any user-provided value.
🎯 Use Cases
Custom Input Formatting
import { MasksFullMapEn } from '@desource/phone-mask';
import { formatDigitsWithMap, extractDigits } from '@desource/phone-mask/kit';
function formatPhoneInput(value: string, countryCode: string = 'US') {
const country = MasksFullMapEn[countryCode];
const mask = country?.mask[0];
if (!mask) return value;
const digits = extractDigits(value);
return `${country.code} ${formatDigitsWithMap(mask, digits).display}`;
}
// Usage
const formatted = formatPhoneInput('2025551234', 'US');
// "+1 202-555-1234"Phone Number Validation
import { MasksFullMapEn } from '@desource/phone-mask';
import { countPlaceholders } from '@desource/phone-mask/kit';
function isValidPhoneLength(digits: string, country: string): boolean {
const masks = MasksFullMapEn[country]?.mask;
if (!masks) return false;
const validLengths = masks.map((m) => countPlaceholders(m));
return validLengths.includes(digits.length);
}
// Usage
isValidPhoneLength('2025551234', 'US'); // true (10 digits)
isValidPhoneLength('202555', 'US'); // false (too short)Building a Country Selector
import { MasksFullEn, type CountryKey, type MaskFull } from '@desource/phone-mask';
type CountryOption = Omit<MaskFull, 'mask'>;
function getCountryOptions(): CountryOption[] {
return MasksFullEn.map((data) => ({
id: data.id,
name: data.name,
code: data.code,
flag: data.flag
}));
}
// Usage
const countries = getCountryOptions();
// [
// { id: 'US', name: 'United States', code: '+1', flag: '🇺🇸' },
// { id: 'GB', name: 'United Kingdom', code: '+44', flag: '🇬🇧' },
// ...
// ]Getting Flag Emojis
import { getFlagEmoji } from '@desource/phone-mask';
// Get flag emoji for country code
const flag = getFlagEmoji('US'); // "🇺🇸"🔄 Data Updates
The library syncs with Google's libphonenumber via automated workflow. To update manually:
pnpm genThis fetches the latest data and regenerates data.json.
This updates generated metadata files used by the package (src/data.json, src/data.min.js, and src/data-types.ts).
📊 Bundle Size
Measured by bundling the packed package in a real consumer build with tree-shaking enabled:
| Consumer import | Size (minified) | Gzipped | Brotli |
| ----------------------------------------------------------------- | --------------: | ------: | ------: |
| import * as PhoneMask from '@desource/phone-mask' | 6.09 KB | 2.86 KB | 2.30 KB |
| import { MasksFullMapEn } from '@desource/phone-mask' | 5.75 KB | 2.67 KB | 2.13 KB |
| import * as Kit from '@desource/phone-mask/kit' | 13.28 KB | 5.83 KB | 4.90 KB |
| import { createPhoneFormatter } from '@desource/phone-mask/kit' | 1.03 KB | 0.59 KB | 0.53 KB |
| import { formatDigitsWithMap } from '@desource/phone-mask/kit' | 0.25 KB | 0.21 KB | 0.18 KB |
| import { extractDigits } from '@desource/phone-mask/kit' | 0.08 KB | 0.10 KB | 0.08 KB |
| import { getCountry } from '@desource/phone-mask/kit' | 5.84 KB | 2.72 KB | 2.18 KB |
The root entry contains country metadata and mask data. Use @desource/phone-mask/kit when you need display formatting, lower-level formatters, input handling, detection, or utility helpers. Data-dependent helpers such as getCountry include mask data; pure formatter and input helpers tree-shake to small standalone bundles.
🔗 Related Packages
- @desource/phone-mask-angular — Angular component + directive + pipe + service
- @desource/phone-mask-react — React component + hook
- @desource/phone-mask-svelte — Svelte component + composable + action + attachment
- @desource/phone-mask-vue — Vue 3 component + composable + directive
- @desource/phone-mask-nuxt — Nuxt module
📄 License
MIT © 2026 DeSource Labs
🤝 Contributing
See Contributing Guide for development, testing, and publication checks.
