asma-core-helpers 0.34.0 → 0.36.0
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/README.md +25 -0
- package/lib/helpers/generateEnvConfigsBindings.d.ts.map +1 -1
- package/lib/helpers/generateEnvConfigsBindings.js +29 -5
- package/lib/helpers/generateEnvConfigsBindings.js.map +1 -1
- package/lib/phone/index.d.ts +15 -0
- package/lib/phone/index.d.ts.map +1 -0
- package/lib/phone/index.js +15 -0
- package/lib/phone/index.js.map +1 -0
- package/lib/phone/phoneCountries.d.ts +44 -0
- package/lib/phone/phoneCountries.d.ts.map +1 -0
- package/lib/phone/phoneCountries.js +84 -0
- package/lib/phone/phoneCountries.js.map +1 -0
- package/lib/phone/phoneExample.d.ts +17 -0
- package/lib/phone/phoneExample.d.ts.map +1 -0
- package/lib/phone/phoneExample.js +21 -0
- package/lib/phone/phoneExample.js.map +1 -0
- package/lib/phone/phoneNumber.d.ts +101 -0
- package/lib/phone/phoneNumber.d.ts.map +1 -0
- package/lib/phone/phoneNumber.js +158 -0
- package/lib/phone/phoneNumber.js.map +1 -0
- package/package.json +6 -1
- package/src/helpers/generateEnvConfigsBindings.test.ts +67 -0
- package/src/helpers/generateEnvConfigsBindings.ts +37 -6
- package/src/phone/index.ts +38 -0
- package/src/phone/phoneCountries.test.ts +96 -0
- package/src/phone/phoneCountries.ts +118 -0
- package/src/phone/phoneExample.test.ts +17 -0
- package/src/phone/phoneExample.ts +24 -0
- package/src/phone/phoneNumber.test.ts +242 -0
- package/src/phone/phoneNumber.ts +203 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "asma-core-helpers",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.36.0",
|
|
4
4
|
"description": "Core helper utilities for ASMA applications",
|
|
5
5
|
"files": [
|
|
6
6
|
"lib/**/*",
|
|
@@ -30,6 +30,10 @@
|
|
|
30
30
|
"./validation": {
|
|
31
31
|
"types": "./lib/validation/index.d.ts",
|
|
32
32
|
"default": "./lib/validation/index.js"
|
|
33
|
+
},
|
|
34
|
+
"./phone": {
|
|
35
|
+
"types": "./lib/phone/index.d.ts",
|
|
36
|
+
"default": "./lib/phone/index.js"
|
|
33
37
|
}
|
|
34
38
|
},
|
|
35
39
|
"scripts": {
|
|
@@ -62,6 +66,7 @@
|
|
|
62
66
|
"asma-event-bus": "^0.7.27",
|
|
63
67
|
"buffer": "^6.0.3",
|
|
64
68
|
"idb-keyval": "^6.2.1",
|
|
69
|
+
"libphonenumber-js": "^1.13.12",
|
|
65
70
|
"mobx": "^6.12.3",
|
|
66
71
|
"mobx-state-tree": "^7.0.2",
|
|
67
72
|
"wonka": "^6.3.4"
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import assert from 'node:assert/strict'
|
|
2
|
+
import { after, before, describe, it } from 'node:test'
|
|
3
|
+
|
|
4
|
+
// realWindow / initEnvConfigsVars read window + localStorage at module-import time,
|
|
5
|
+
// so the globals must exist before the module under test is (dynamically) imported.
|
|
6
|
+
const globalWithWindow = globalThis as typeof globalThis & {
|
|
7
|
+
window?: Record<string, unknown>
|
|
8
|
+
localStorage?: Storage
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
let bindings: typeof import('./generateEnvConfigsBindings.ts')
|
|
12
|
+
|
|
13
|
+
before(async () => {
|
|
14
|
+
globalWithWindow.window = {
|
|
15
|
+
location: {
|
|
16
|
+
origin: 'http://test.adopus.no',
|
|
17
|
+
hostname: 'test.adopus.no',
|
|
18
|
+
host: 'test.adopus.no',
|
|
19
|
+
},
|
|
20
|
+
}
|
|
21
|
+
globalWithWindow.localStorage = {
|
|
22
|
+
getItem: () => null,
|
|
23
|
+
setItem: () => undefined,
|
|
24
|
+
removeItem: () => undefined,
|
|
25
|
+
clear: () => undefined,
|
|
26
|
+
key: () => null,
|
|
27
|
+
length: 0,
|
|
28
|
+
} as unknown as Storage
|
|
29
|
+
|
|
30
|
+
bindings = await import('./generateEnvConfigsBindings.ts')
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
after(() => {
|
|
34
|
+
delete globalWithWindow.window
|
|
35
|
+
delete globalWithWindow.localStorage
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
describe('generateEnvConfigsBindings (shared module instance)', () => {
|
|
39
|
+
it('throws when nothing has been registered yet', () => {
|
|
40
|
+
assert.throws(() => bindings.EnvConfigsFnInternal())
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
it("keeps every app's service resolvable after several apps register (no last-write-wins)", () => {
|
|
44
|
+
// Host app first: requires SRV_PROXY (like asma-app-shell).
|
|
45
|
+
bindings.generateEnvConfigsBindings(
|
|
46
|
+
{ envs: {} },
|
|
47
|
+
['SRV_AUTH', 'SRV_PROXY', 'DEVELOPMENT'],
|
|
48
|
+
{ CACHE_VERSION: '1.0.0' },
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
// Child app second, mounted later: does NOT require SRV_PROXY (like asma-app-calendar).
|
|
52
|
+
bindings.generateEnvConfigsBindings(
|
|
53
|
+
{ envs: {} },
|
|
54
|
+
['SRV_AUTH', 'SRV_CALENDAR', 'DEVELOPMENT'],
|
|
55
|
+
{ CACHE_VERSION: '1.0.1' },
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
const config = bindings.EnvConfigsFnInternal()
|
|
59
|
+
|
|
60
|
+
// SRV_PROXY must stay resolvable even though the last registration omitted it.
|
|
61
|
+
assert.equal(config.SRV_PROXY, '/api/artifact')
|
|
62
|
+
// Services only the child requires must be resolvable too.
|
|
63
|
+
assert.equal(config.SRV_CALENDAR, '/api/calendar')
|
|
64
|
+
// On overlapping keys the first registration wins (host app semantics).
|
|
65
|
+
assert.equal(config.CACHE_VERSION, '1.0.0')
|
|
66
|
+
})
|
|
67
|
+
})
|
|
@@ -34,22 +34,47 @@ export type IEnvironmentUrlsGenQLOnly = SRVKeys<IEnvironmentUrls>
|
|
|
34
34
|
|
|
35
35
|
//type IKeyEnvironmentUrlsWs = `${IKeyEnvironmentUrls}_WS`
|
|
36
36
|
|
|
37
|
-
const EnvConfigsFnInstanceId = uuid4()
|
|
38
|
-
|
|
39
37
|
/**
|
|
40
38
|
*
|
|
41
39
|
* For internal use only (inside asma-helpers)
|
|
42
40
|
*/
|
|
43
41
|
|
|
44
42
|
export function EnvConfigsFnInternal() {
|
|
45
|
-
const
|
|
43
|
+
const reg = realWindow.__GENERATE_ENV_CONFIGS_BINDINGS__?.EnvConfigsFnReg
|
|
46
44
|
|
|
47
|
-
if (!
|
|
45
|
+
if (!reg || Object.keys(reg).length === 0) {
|
|
48
46
|
throw new Error(
|
|
49
47
|
'EnvConfigsFn is not defined! please make sure that generateEnvConfigsBindings is called before EnvConfigsFn',
|
|
50
48
|
)
|
|
51
49
|
}
|
|
52
|
-
|
|
50
|
+
|
|
51
|
+
// Several apps can share this module instance (kernel-external builds register every
|
|
52
|
+
// app's EnvConfigsFn under its own key). Merge them so every service any registered
|
|
53
|
+
// app needs stays resolvable regardless of mount order: union of all keys, first
|
|
54
|
+
// registration wins on conflict (the host app mounts first and keeps its own values).
|
|
55
|
+
const merged: Record<string, unknown> = {}
|
|
56
|
+
|
|
57
|
+
for (const key of Object.keys(reg)) {
|
|
58
|
+
const fn = reg[key]
|
|
59
|
+
|
|
60
|
+
if (!fn) {
|
|
61
|
+
continue
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const config = fn()
|
|
65
|
+
|
|
66
|
+
if (!config || typeof config !== 'object') {
|
|
67
|
+
continue
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
for (const [configKey, value] of Object.entries(config)) {
|
|
71
|
+
if (!(configKey in merged)) {
|
|
72
|
+
merged[configKey] = value
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return merged as unknown as {
|
|
53
78
|
CACHE_VERSION: string
|
|
54
79
|
SRV_AUTH?: string
|
|
55
80
|
CDN_ASMA_BASE_URL?: string
|
|
@@ -126,7 +151,13 @@ export function generateEnvConfigsBindings<
|
|
|
126
151
|
fetchConfigsReg: {},
|
|
127
152
|
}
|
|
128
153
|
|
|
129
|
-
|
|
154
|
+
// Key by a per-call id (NOT a module-level id): on a shared module instance every
|
|
155
|
+
// app's generateEnvConfigsBindings() call must register its own EnvConfigsFn instead
|
|
156
|
+
// of overwriting the previous app's (last-write-wins), which made services that only
|
|
157
|
+
// one app requires (e.g. SRV_PROXY) disappear for everyone else.
|
|
158
|
+
const envConfigsFnInstanceId = uuid4()
|
|
159
|
+
|
|
160
|
+
realWindow.__GENERATE_ENV_CONFIGS_BINDINGS__.EnvConfigsFnReg[envConfigsFnInstanceId] = EnvConfigsFn
|
|
130
161
|
|
|
131
162
|
return { EnvConfigsFn }
|
|
132
163
|
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Country-aware phone primitives for ASMA forms (ASMA-7485).
|
|
3
|
+
*
|
|
4
|
+
* Published as `asma-core-helpers/phone` and deliberately **not** re-exported from
|
|
5
|
+
* the root barrel: the root entry is what the ESM kernel bundles and serves to all
|
|
6
|
+
* 17 fleet apps, and `libphonenumber-js` has no business in that shared unit. As a
|
|
7
|
+
* subpath it is absent from `KERNEL_EXTERNAL_SPECIFIERS`, so it bundles into the two
|
|
8
|
+
* apps that actually render a phone field instead.
|
|
9
|
+
*
|
|
10
|
+
* @see asma-modules/_docs/adr/adr-g-0017-frontend-form-state-and-validation-ownership.md:49 — DEC-001, why the rules live here and not in asma-ui-core
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export {
|
|
14
|
+
DEFAULT_PHONE_COUNTRY,
|
|
15
|
+
findCountryByDialCode,
|
|
16
|
+
getPhoneDialCode,
|
|
17
|
+
listPhoneCountries,
|
|
18
|
+
matchesPhoneCountry,
|
|
19
|
+
type PhoneCountry,
|
|
20
|
+
type PhoneCountryOption,
|
|
21
|
+
} from './phoneCountries.js'
|
|
22
|
+
|
|
23
|
+
export {
|
|
24
|
+
formatNationalAsYouType,
|
|
25
|
+
formatPhoneForDisplay,
|
|
26
|
+
isValidPhone,
|
|
27
|
+
isValidPhoneValue,
|
|
28
|
+
parsePhoneNr,
|
|
29
|
+
parsePhoneValue,
|
|
30
|
+
phoneTelHref,
|
|
31
|
+
PHONE_MAX_DIGITS,
|
|
32
|
+
PHONE_MIN_DIGITS,
|
|
33
|
+
toE164,
|
|
34
|
+
type ParsedPhone,
|
|
35
|
+
type PhoneNrParse,
|
|
36
|
+
} from './phoneNumber.js'
|
|
37
|
+
|
|
38
|
+
export { phoneExample } from './phoneExample.js'
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import assert from 'node:assert/strict'
|
|
2
|
+
import { describe, it } from 'node:test'
|
|
3
|
+
|
|
4
|
+
import {
|
|
5
|
+
DEFAULT_PHONE_COUNTRY,
|
|
6
|
+
findCountryByDialCode,
|
|
7
|
+
getPhoneDialCode,
|
|
8
|
+
listPhoneCountries,
|
|
9
|
+
matchesPhoneCountry,
|
|
10
|
+
} from './phoneCountries.js'
|
|
11
|
+
import type { PhoneCountryOption } from './phoneCountries.js'
|
|
12
|
+
|
|
13
|
+
const norway = (locale: string): PhoneCountryOption | undefined =>
|
|
14
|
+
listPhoneCountries(locale).find((option) => option.iso2 === 'NO')
|
|
15
|
+
|
|
16
|
+
describe('DEFAULT_PHONE_COUNTRY', () => {
|
|
17
|
+
it('pre-selects Norway (ASMA-7485)', () => {
|
|
18
|
+
assert.equal(DEFAULT_PHONE_COUNTRY, 'NO')
|
|
19
|
+
})
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
describe('listPhoneCountries', () => {
|
|
23
|
+
it('covers every supported country with its calling code', () => {
|
|
24
|
+
const options = listPhoneCountries('en')
|
|
25
|
+
assert.equal(options.length, 245)
|
|
26
|
+
assert.deepEqual(norway('en'), { iso2: 'NO', dialCode: '47', name: 'Norway' })
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
it('localizes names per locale instead of shipping a translation table', () => {
|
|
30
|
+
assert.equal(norway('nb')?.name, 'Norge')
|
|
31
|
+
assert.equal(norway('en')?.name, 'Norway')
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
it('sorts by localized name, so the order differs between locales', () => {
|
|
35
|
+
const nb = listPhoneCountries('nb').map((option) => option.name)
|
|
36
|
+
const en = listPhoneCountries('en').map((option) => option.name)
|
|
37
|
+
|
|
38
|
+
assert.deepEqual(nb, [...nb].sort(new Intl.Collator('nb').compare))
|
|
39
|
+
assert.deepEqual(en, [...en].sort(new Intl.Collator('en').compare))
|
|
40
|
+
// Østerrike sorts last in nb, Austria near the front in en.
|
|
41
|
+
assert.notEqual(nb.indexOf('Østerrike'), en.indexOf('Austria'))
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
it('memoizes per locale — the Intl lookup runs once per country', () => {
|
|
45
|
+
assert.equal(listPhoneCountries('en'), listPhoneCountries('en'))
|
|
46
|
+
assert.notEqual(listPhoneCountries('en'), listPhoneCountries('nb'))
|
|
47
|
+
})
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
describe('getPhoneDialCode', () => {
|
|
51
|
+
it('returns the calling code without a plus', () => {
|
|
52
|
+
assert.equal(getPhoneDialCode('NO'), '47')
|
|
53
|
+
assert.equal(getPhoneDialCode('US'), '1')
|
|
54
|
+
})
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
describe('matchesPhoneCountry', () => {
|
|
58
|
+
const option: PhoneCountryOption = { iso2: 'NO', dialCode: '47', name: 'Norway' }
|
|
59
|
+
|
|
60
|
+
it('matches by country name, case-insensitively', () => {
|
|
61
|
+
assert.equal(matchesPhoneCountry(option, 'nor'), true)
|
|
62
|
+
assert.equal(matchesPhoneCountry(option, 'NORWAY'), true)
|
|
63
|
+
assert.equal(matchesPhoneCountry(option, 'sweden'), false)
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
it('matches by calling code, with or without the plus', () => {
|
|
67
|
+
assert.equal(matchesPhoneCountry(option, '47'), true)
|
|
68
|
+
assert.equal(matchesPhoneCountry(option, '+47'), true)
|
|
69
|
+
assert.equal(matchesPhoneCountry(option, '4'), true)
|
|
70
|
+
assert.equal(matchesPhoneCountry(option, '61'), false)
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
it('keeps every row for an empty or whitespace query', () => {
|
|
74
|
+
assert.equal(matchesPhoneCountry(option, ''), true)
|
|
75
|
+
assert.equal(matchesPhoneCountry(option, ' '), true)
|
|
76
|
+
})
|
|
77
|
+
})
|
|
78
|
+
|
|
79
|
+
describe('findCountryByDialCode', () => {
|
|
80
|
+
it('resolves the main country of a shared calling code', () => {
|
|
81
|
+
// 25 countries share +1; a first-match scan would answer Antigua.
|
|
82
|
+
assert.equal(findCountryByDialCode('12015550123'), 'US')
|
|
83
|
+
assert.equal(findCountryByDialCode('79161234567'), 'RU')
|
|
84
|
+
assert.equal(findCountryByDialCode('447400123456'), 'GB')
|
|
85
|
+
})
|
|
86
|
+
|
|
87
|
+
it('prefers the longest matching calling code', () => {
|
|
88
|
+
assert.equal(findCountryByDialCode('4748012345'), 'NO')
|
|
89
|
+
assert.equal(findCountryByDialCode('46701234567'), 'SE')
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
it('returns undefined when no calling code matches', () => {
|
|
93
|
+
assert.equal(findCountryByDialCode('9991234'), undefined)
|
|
94
|
+
assert.equal(findCountryByDialCode(''), undefined)
|
|
95
|
+
})
|
|
96
|
+
})
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Country dial-code catalogue for the ASMA phone field (ASMA-7485).
|
|
3
|
+
*
|
|
4
|
+
* Country names come from the platform's own `Intl.DisplayNames` rather than a
|
|
5
|
+
* checked-in translation table, so every locale the browser knows is covered
|
|
6
|
+
* without shipping (or maintaining) 245 names per language.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { getCountries, getCountryCallingCode, isSupportedCountry, Metadata } from 'libphonenumber-js'
|
|
10
|
+
import type { CountryCode } from 'libphonenumber-js'
|
|
11
|
+
|
|
12
|
+
/** ISO 3166-1 alpha-2 code, narrowed to what the phone metadata actually supports. */
|
|
13
|
+
export type PhoneCountry = CountryCode
|
|
14
|
+
|
|
15
|
+
/** Pre-selected country for every ASMA phone field — see ASMA-7485. */
|
|
16
|
+
export const DEFAULT_PHONE_COUNTRY: PhoneCountry = 'NO'
|
|
17
|
+
|
|
18
|
+
export interface PhoneCountryOption {
|
|
19
|
+
iso2: PhoneCountry
|
|
20
|
+
/** Calling code without the leading `+`, e.g. `'47'`. */
|
|
21
|
+
dialCode: string
|
|
22
|
+
/** Country name in the requested locale, e.g. `'Norge'` / `'Norway'`. */
|
|
23
|
+
name: string
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const optionsByLocale = new Map<string, readonly PhoneCountryOption[]>()
|
|
27
|
+
|
|
28
|
+
function countryName(iso2: PhoneCountry, displayNames: Intl.DisplayNames): string {
|
|
29
|
+
// `of` returns undefined for codes the ICU data does not know; the code itself
|
|
30
|
+
// is a better fallback than an empty row.
|
|
31
|
+
return displayNames.of(iso2) ?? iso2
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Every supported country, sorted by localized name.
|
|
36
|
+
*
|
|
37
|
+
* Ordering of the *rendered* list (pinning the selected country first) belongs to
|
|
38
|
+
* the UI; this returns the stable alphabetical catalogue. Memoized per locale
|
|
39
|
+
* because the underlying `Intl.DisplayNames` lookup runs once per country.
|
|
40
|
+
*/
|
|
41
|
+
export function listPhoneCountries(locale: string): readonly PhoneCountryOption[] {
|
|
42
|
+
const cached = optionsByLocale.get(locale)
|
|
43
|
+
if (cached !== undefined) return cached
|
|
44
|
+
|
|
45
|
+
const displayNames = new Intl.DisplayNames([locale], { type: 'region' })
|
|
46
|
+
const collator = new Intl.Collator(locale)
|
|
47
|
+
|
|
48
|
+
const options = getCountries()
|
|
49
|
+
.map((iso2) => ({
|
|
50
|
+
iso2,
|
|
51
|
+
dialCode: getCountryCallingCode(iso2),
|
|
52
|
+
name: countryName(iso2, displayNames),
|
|
53
|
+
}))
|
|
54
|
+
.sort((left, right) => collator.compare(left.name, right.name))
|
|
55
|
+
|
|
56
|
+
optionsByLocale.set(locale, options)
|
|
57
|
+
return options
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function getPhoneDialCode(iso2: PhoneCountry): string {
|
|
61
|
+
return getCountryCallingCode(iso2)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Search predicate for the country picker: matches on localized name **or** on the
|
|
66
|
+
* calling code, so both `"Norway"` and `"47"` narrow the list to +47 (ASMA-7485).
|
|
67
|
+
*
|
|
68
|
+
* A leading `+` in the query is ignored so pasting `+47` works.
|
|
69
|
+
*/
|
|
70
|
+
export function matchesPhoneCountry(option: PhoneCountryOption, query: string): boolean {
|
|
71
|
+
const trimmed = query.trim()
|
|
72
|
+
if (trimmed.length === 0) return true
|
|
73
|
+
|
|
74
|
+
if (option.name.toLocaleLowerCase().includes(trimmed.toLocaleLowerCase())) return true
|
|
75
|
+
|
|
76
|
+
const digits = trimmed.replace(/^\+/, '').replace(/\D/g, '')
|
|
77
|
+
return digits.length > 0 && option.dialCode.startsWith(digits)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Calling codes are at most three digits in the E.164 plan. */
|
|
81
|
+
const MAX_CALLING_CODE_LENGTH = 3
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* `Metadata` exposes the calling-code → countries index at runtime, but the shipped
|
|
85
|
+
* typings declare only `selectNumberingPlan`/`numberingPlan`. Narrowed here against
|
|
86
|
+
* the inspected runtime shape and guarded at the call site, so a future release that
|
|
87
|
+
* drops the method degrades to "country not found" instead of throwing.
|
|
88
|
+
*/
|
|
89
|
+
interface CallingCodeIndex {
|
|
90
|
+
getCountryCodesForCallingCode?: (callingCode: string) => readonly string[] | undefined
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* The primary country for a calling code — `'1'` → `US`, not whichever NANP
|
|
95
|
+
* territory happens to sort first. The metadata index lists the main country first.
|
|
96
|
+
*/
|
|
97
|
+
function mainCountryForCallingCode(callingCode: string): PhoneCountry | undefined {
|
|
98
|
+
const index = new Metadata() as unknown as CallingCodeIndex
|
|
99
|
+
const candidate = index.getCountryCodesForCallingCode?.(callingCode)?.[0]
|
|
100
|
+
|
|
101
|
+
return candidate !== undefined && isSupportedCountry(candidate) ? candidate : undefined
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* The country owning the longest calling-code prefix of `digits`.
|
|
106
|
+
*
|
|
107
|
+
* Longest-prefix rather than first-match because calling codes are not prefix-free
|
|
108
|
+
* (`+1` vs `+7`, `+47` vs `+473`), and main-country-wins because 25 countries share
|
|
109
|
+
* `+1` — a plain scan resolves every North-American number to Antigua.
|
|
110
|
+
*/
|
|
111
|
+
export function findCountryByDialCode(digits: string): PhoneCountry | undefined {
|
|
112
|
+
for (let length = Math.min(MAX_CALLING_CODE_LENGTH, digits.length); length >= 1; length -= 1) {
|
|
113
|
+
const country = mainCountryForCallingCode(digits.slice(0, length))
|
|
114
|
+
if (country !== undefined) return country
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
return undefined
|
|
118
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import assert from 'node:assert/strict'
|
|
2
|
+
import { describe, it } from 'node:test'
|
|
3
|
+
|
|
4
|
+
import { phoneExample } from './phoneExample.js'
|
|
5
|
+
|
|
6
|
+
describe('phoneExample', () => {
|
|
7
|
+
it('supplies the actionable half of a validation message (REQ-003)', () => {
|
|
8
|
+
assert.equal(phoneExample('NO'), '+47 40 61 23 45')
|
|
9
|
+
assert.equal(phoneExample('US'), '+1 201 555 0123')
|
|
10
|
+
})
|
|
11
|
+
|
|
12
|
+
it('always yields something to show, even without example metadata', () => {
|
|
13
|
+
for (const iso2 of ['NO', 'US', 'GB', 'SE', 'AX', 'SJ'] as const) {
|
|
14
|
+
assert.match(phoneExample(iso2), /^\+\d/)
|
|
15
|
+
}
|
|
16
|
+
})
|
|
17
|
+
})
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Example numbers for the actionable half of a validation message (ADR-0017 REQ-003:
|
|
3
|
+
* "what's wrong — how to fix"), e.g. `errorWithHint(msgs.invalid_phone, phoneExample('NO'))`
|
|
4
|
+
* → `'Invalid phone — Ex: +47 40 61 23 45'`.
|
|
5
|
+
*
|
|
6
|
+
* Kept in its own module so consumers that only format or validate do not pull the
|
|
7
|
+
* example metadata (~1.4 kB gz) into their bundle.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { getExampleNumber } from 'libphonenumber-js'
|
|
11
|
+
import examples from 'libphonenumber-js/examples.mobile.json'
|
|
12
|
+
|
|
13
|
+
import { getPhoneDialCode } from './phoneCountries.js'
|
|
14
|
+
import type { PhoneCountry } from './phoneCountries.js'
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* A representative mobile number for the country, in international form.
|
|
18
|
+
*
|
|
19
|
+
* Falls back to the bare dial code for the handful of territories that have no
|
|
20
|
+
* example in the metadata, so the hint is never an empty string.
|
|
21
|
+
*/
|
|
22
|
+
export function phoneExample(iso2: PhoneCountry): string {
|
|
23
|
+
return getExampleNumber(iso2, examples)?.formatInternational() ?? `+${getPhoneDialCode(iso2)}`
|
|
24
|
+
}
|