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.
@@ -0,0 +1,242 @@
1
+ import assert from 'node:assert/strict'
2
+ import { describe, it } from 'node:test'
3
+
4
+ import {
5
+ formatNationalAsYouType,
6
+ formatPhoneForDisplay,
7
+ isValidPhone,
8
+ isValidPhoneValue,
9
+ parsePhoneNr,
10
+ parsePhoneValue,
11
+ phoneTelHref,
12
+ toE164,
13
+ } from './phoneNumber.js'
14
+ import type { PhoneCountry } from './phoneCountries.js'
15
+
16
+ describe('parsePhoneNr', () => {
17
+ // The canonicalisation contract every writer and the backfill share. Each row is a
18
+ // shape found in, or reachable into, `customer_user.phone_nr` today.
19
+ const contract: readonly [string, PhoneCountry, string | 'INVALID'][] = [
20
+ ['45456565', 'NO', '+4745456565'],
21
+ ['4745456565', 'NO', '+4745456565'],
22
+ ['004745456565', 'NO', '+4745456565'],
23
+ ['+47 454 56 565', 'NO', '+4745456565'],
24
+ ['47123456', 'NO', '+4747123456'],
25
+ ['+37379094538', 'NO', '+37379094538'],
26
+ ['0701234567', 'NO', 'INVALID'],
27
+ ['0701234567', 'SE', '+46701234567'],
28
+ ['12345', 'NO', 'INVALID'],
29
+ ]
30
+
31
+ for (const [input, region, expected] of contract) {
32
+ it(`canonicalises ${input} under ${region} to ${expected}`, () => {
33
+ const result = parsePhoneNr(input, region)
34
+
35
+ if (expected === 'INVALID') {
36
+ assert.deepEqual(result, { ok: false, reason: 'INVALID', input: input.trim() })
37
+ return
38
+ }
39
+
40
+ assert.equal(result.ok, true)
41
+ assert.equal(result.ok && result.e164, expected)
42
+ })
43
+ }
44
+
45
+ it('reports the country and calling code the value resolved to', () => {
46
+ const result = parsePhoneNr('45456565', 'NO')
47
+
48
+ assert.deepEqual(result, { ok: true, e164: '+4745456565', country: 'NO', callingCode: '47' })
49
+ })
50
+
51
+ it('separates an empty value from an invalid one so a report can tell them apart', () => {
52
+ for (const value of ['', ' ', null, undefined]) {
53
+ assert.deepEqual(parsePhoneNr(value, 'NO'), { ok: false, reason: 'EMPTY', input: '' })
54
+ }
55
+ })
56
+
57
+ it('reports rather than rewrites a number that is not real for the region', () => {
58
+ // `12345678` and `00000000` passed the pre-ticket digit-count rules and are in the
59
+ // data; no algorithm can recover an intended number from them.
60
+ for (const junk of ['12345678', '00000000', '11111111']) {
61
+ assert.deepEqual(parsePhoneNr(junk, 'NO'), { ok: false, reason: 'INVALID', input: junk })
62
+ }
63
+ })
64
+ })
65
+
66
+ describe('parsePhoneValue', () => {
67
+ it('splits a stored E.164 value into country and national number', () => {
68
+ assert.deepEqual(parsePhoneValue('+4748012345'), { iso2: 'NO', national: '48012345' })
69
+ assert.deepEqual(parsePhoneValue('+12015550123', 'NO'), { iso2: 'US', national: '2015550123' })
70
+ })
71
+
72
+ it('reads a pre-ASMA-7485 bare national number as the fallback country', () => {
73
+ // Every record written before this ticket is 8 bare digits with no country.
74
+ assert.deepEqual(parsePhoneValue('48012345', 'NO'), { iso2: 'NO', national: '48012345' })
75
+ assert.deepEqual(parsePhoneValue('48012345', 'SE'), { iso2: 'SE', national: '48012345' })
76
+ })
77
+
78
+ it('keeps the caller country while a matching number is still being typed', () => {
79
+ assert.deepEqual(parsePhoneValue('+47', 'NO'), { iso2: 'NO', national: '' })
80
+ assert.deepEqual(parsePhoneValue('+4748', 'NO'), { iso2: 'NO', national: '48' })
81
+ })
82
+
83
+ it('switches country when the typed prefix belongs to another one', () => {
84
+ assert.deepEqual(parsePhoneValue('+46701', 'NO'), { iso2: 'SE', national: '701' })
85
+ })
86
+
87
+ it('treats empty, whitespace and nullish values as an empty number', () => {
88
+ for (const value of ['', ' ', null, undefined]) {
89
+ assert.deepEqual(parsePhoneValue(value, 'NO'), { iso2: 'NO', national: '' })
90
+ }
91
+ })
92
+
93
+ it('falls back to the given country for an unknown calling code', () => {
94
+ assert.deepEqual(parsePhoneValue('+9991234', 'NO'), { iso2: 'NO', national: '9991234' })
95
+ })
96
+ })
97
+
98
+ describe('toE164', () => {
99
+ it('composes the stored value from the country and the typed digits', () => {
100
+ assert.equal(toE164('48012345', 'NO'), '+4748012345')
101
+ assert.equal(toE164('2015550123', 'US'), '+12015550123')
102
+ })
103
+
104
+ it('drops mask separators so the stored value is digits and a plus only', () => {
105
+ assert.equal(toE164('48 01 23 45', 'NO'), '+4748012345')
106
+ assert.equal(toE164('(201) 555-0123', 'US'), '+12015550123')
107
+ })
108
+
109
+ it('stores nothing rather than a bare dial code for an empty number', () => {
110
+ assert.equal(toE164('', 'NO'), '')
111
+ assert.equal(toE164(' ', 'NO'), '')
112
+ })
113
+
114
+ it('does not validate — an in-progress number must still round-trip', () => {
115
+ assert.equal(toE164('4', 'NO'), '+474')
116
+ })
117
+
118
+ it('does not double a country code the input already carries', () => {
119
+ // Concatenation stored `+474748012345` and `+47004748012345`, both unusable.
120
+ assert.equal(toE164('4748012345', 'NO'), '+4748012345')
121
+ assert.equal(toE164('004748012345', 'NO'), '+4748012345')
122
+ assert.equal(toE164('4781234567', 'NO'), '+4781234567')
123
+ })
124
+
125
+ it('drops the trunk prefix countries write their national numbers with', () => {
126
+ // SE/GB/DE national form carries a leading 0 that is not part of the E.164 number,
127
+ // so concatenation stored `+460701234567` for a number people write as 070-123 45 67.
128
+ assert.equal(toE164('0701234567', 'SE'), '+46701234567')
129
+ assert.equal(toE164('07911123456', 'GB'), '+447911123456')
130
+ assert.equal(toE164('015112345678', 'DE'), '+4915112345678')
131
+ })
132
+
133
+ it('keeps a genuine national number that merely starts with the dial code', () => {
134
+ assert.equal(toE164('47123456', 'NO'), '+4747123456')
135
+ })
136
+
137
+ it('round-trips through parsePhoneValue', () => {
138
+ const parsed = parsePhoneValue(toE164('48012345', 'NO'))
139
+ assert.deepEqual(parsed, { iso2: 'NO', national: '48012345' })
140
+ })
141
+ })
142
+
143
+ describe('formatNationalAsYouType', () => {
144
+ it('groups by the country format, progressively', () => {
145
+ assert.equal(formatNationalAsYouType('4', 'NO'), '4')
146
+ assert.equal(formatNationalAsYouType('480', 'NO'), '48 0')
147
+ assert.equal(formatNationalAsYouType('48012345', 'NO'), '48 01 23 45')
148
+ })
149
+
150
+ it('uses each country own grouping, not a Norwegian one', () => {
151
+ assert.equal(formatNationalAsYouType('2133734253', 'US'), '213 373 4253')
152
+ assert.equal(formatNationalAsYouType('512345678', 'PL'), '512 345 678')
153
+ })
154
+
155
+ it('groups countries that carry a trunk prefix, which the national format cannot', () => {
156
+ // AsYouType('SE') returns '701234567' unformatted: Swedish national formats are
157
+ // defined with the leading 0, which a national significant number does not carry.
158
+ assert.equal(formatNationalAsYouType('701234567', 'SE'), '70 123 45 67')
159
+ assert.equal(formatNationalAsYouType('7400123456', 'GB'), '7400 123456')
160
+ assert.equal(formatNationalAsYouType('612345678', 'FR'), '6 12 34 56 78')
161
+ })
162
+
163
+ it('returns an empty string when there is nothing to format', () => {
164
+ assert.equal(formatNationalAsYouType('', 'NO'), '')
165
+ assert.equal(formatNationalAsYouType('abc', 'NO'), '')
166
+ })
167
+ })
168
+
169
+ describe('isValidPhone', () => {
170
+ it('accepts a real number for the country', () => {
171
+ assert.equal(isValidPhone('48012345', 'NO'), true)
172
+ assert.equal(isValidPhone('2015550123', 'US'), true)
173
+ })
174
+
175
+ it('rejects by country pattern, not merely by digit count', () => {
176
+ // Both are eight digits — the length the field used to accept unconditionally.
177
+ assert.equal(isValidPhone('12345678', 'NO'), false)
178
+ assert.equal(isValidPhone('00000000', 'NO'), false)
179
+ })
180
+
181
+ it('rejects numbers outside the E.164 length bounds', () => {
182
+ assert.equal(isValidPhone('123', 'NO'), false)
183
+ assert.equal(isValidPhone('1234567890123456', 'NO'), false)
184
+ })
185
+
186
+ it('accepts a number that is valid elsewhere but not for the selected country', () => {
187
+ assert.equal(isValidPhone('2015550123', 'NO'), false)
188
+ })
189
+
190
+ it('ignores mask separators', () => {
191
+ assert.equal(isValidPhone('48 01 23 45', 'NO'), true)
192
+ })
193
+ })
194
+
195
+ describe('isValidPhoneValue', () => {
196
+ it('resolves the country from the stored value', () => {
197
+ assert.equal(isValidPhoneValue('+12015550123'), true)
198
+ assert.equal(isValidPhoneValue('+4712345678'), false)
199
+ })
200
+
201
+ it('validates a legacy bare number against the fallback country', () => {
202
+ assert.equal(isValidPhoneValue('48012345', 'NO'), true)
203
+ assert.equal(isValidPhoneValue('12345678', 'NO'), false)
204
+ })
205
+
206
+ it('treats an empty value as invalid — emptiness is the required rule job', () => {
207
+ assert.equal(isValidPhoneValue(''), false)
208
+ assert.equal(isValidPhoneValue(null), false)
209
+ })
210
+ })
211
+
212
+ describe('formatPhoneForDisplay', () => {
213
+ it('renders the international form for read-only views', () => {
214
+ assert.equal(formatPhoneForDisplay('+4748012345'), '+47 48 01 23 45')
215
+ assert.equal(formatPhoneForDisplay('+12015550123'), '+1 201 555 0123')
216
+ })
217
+
218
+ it('upgrades a legacy bare number to the international form', () => {
219
+ assert.equal(formatPhoneForDisplay('48012345', 'NO'), '+47 48 01 23 45')
220
+ })
221
+
222
+ it('returns an empty string for an empty value', () => {
223
+ assert.equal(formatPhoneForDisplay(''), '')
224
+ assert.equal(formatPhoneForDisplay(null), '')
225
+ })
226
+ })
227
+
228
+ describe('phoneTelHref', () => {
229
+ it('is the only place the tel: scheme is added (ASMA-7485)', () => {
230
+ assert.equal(phoneTelHref('+4748012345'), 'tel:+4748012345')
231
+ assert.equal(phoneTelHref('48012345', 'NO'), 'tel:+4748012345')
232
+ })
233
+
234
+ it('carries no spaces or dashes', () => {
235
+ assert.equal(phoneTelHref('48 01 23 45', 'NO'), 'tel:+4748012345')
236
+ })
237
+
238
+ it('returns an empty string when there is nothing to dial', () => {
239
+ assert.equal(phoneTelHref(''), '')
240
+ assert.equal(phoneTelHref(null), '')
241
+ })
242
+ })
@@ -0,0 +1,203 @@
1
+ /**
2
+ * Phone-number formatting, parsing and validation for ASMA forms (ASMA-7485).
3
+ *
4
+ * The stored form is bare E.164 (`+4748012345`) — digits and a leading `+`, no
5
+ * spaces, no `tel:`. The `tel:` scheme belongs to the render of a click-to-call
6
+ * link and is produced by `phoneTelHref`, never written to a field.
7
+ */
8
+
9
+ import {
10
+ AsYouType,
11
+ isValidPhoneNumber,
12
+ parsePhoneNumberFromString,
13
+ parsePhoneNumberWithError,
14
+ } from 'libphonenumber-js'
15
+
16
+ import { DEFAULT_PHONE_COUNTRY, findCountryByDialCode, getPhoneDialCode } from './phoneCountries.js'
17
+ import type { PhoneCountry } from './phoneCountries.js'
18
+
19
+ /** Shortest and longest national significant number in the E.164 plan. */
20
+ export const PHONE_MIN_DIGITS = 4
21
+ export const PHONE_MAX_DIGITS = 15
22
+
23
+ export interface ParsedPhone {
24
+ iso2: PhoneCountry
25
+ /** National significant number, digits only — no dial code, no separators. */
26
+ national: string
27
+ }
28
+
29
+ const digitsOnly = (value: string): string => value.replace(/\D/g, '')
30
+
31
+ export type PhoneNrParse =
32
+ | { ok: true; e164: string; country: PhoneCountry | undefined; callingCode: string }
33
+ | { ok: false; reason: 'EMPTY' | 'INVALID'; input: string }
34
+
35
+ /**
36
+ * Canonicalise a value of unknown shape into E.164 — the one function every writer and
37
+ * the backfill share, so runtime and migration agree byte for byte.
38
+ *
39
+ * `defaultRegion` is required rather than defaulted on purpose. Guessing a region at
40
+ * *read* time, repeatedly and implicitly, is what left the fleet with several
41
+ * `+47`-assuming normalizers that disagree; the region is an explicit input applied
42
+ * once, where a value enters the system, and only when the input carries no `+`.
43
+ *
44
+ * Returns a result rather than throwing or coercing: a value that is not a real number
45
+ * under that region — junk like `'12345678'`, or a Swedish national number stored bare
46
+ * in a Norwegian tenant — is unrecoverable by any algorithm and must be reported to a
47
+ * human, never rewritten into something plausible.
48
+ */
49
+ export function parsePhoneNr(input: string | null | undefined, defaultRegion: PhoneCountry): PhoneNrParse {
50
+ const text = (input ?? '').trim()
51
+ if (text.length === 0) return { ok: false, reason: 'EMPTY', input: text }
52
+
53
+ try {
54
+ const parsed = parsePhoneNumberWithError(text, defaultRegion)
55
+ if (!parsed.isValid()) return { ok: false, reason: 'INVALID', input: text }
56
+
57
+ return { ok: true, e164: parsed.number, country: parsed.country, callingCode: parsed.countryCallingCode }
58
+ } catch {
59
+ return { ok: false, reason: 'INVALID', input: text }
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Split a stored value into the country and the national number the field edits.
65
+ *
66
+ * Three shapes reach this function:
67
+ * - E.164 (`'+4748012345'`) — the format this ticket introduces;
68
+ * - a bare national number (`'48012345'`) — every record written before it, which
69
+ * is why `fallbackIso2` exists rather than the value being rejected;
70
+ * - a partially typed `+47…`, which `parsePhoneNumberFromString` cannot parse yet
71
+ * and which therefore falls through to the longest-dial-code match.
72
+ */
73
+ export function parsePhoneValue(
74
+ value: string | null | undefined,
75
+ fallbackIso2: PhoneCountry = DEFAULT_PHONE_COUNTRY,
76
+ ): ParsedPhone {
77
+ const trimmed = (value ?? '').trim()
78
+ if (trimmed.length === 0) return { iso2: fallbackIso2, national: '' }
79
+
80
+ if (!trimmed.startsWith('+')) {
81
+ return { iso2: fallbackIso2, national: digitsOnly(trimmed) }
82
+ }
83
+
84
+ const parsed = parsePhoneNumberFromString(trimmed)
85
+ if (parsed?.country !== undefined) {
86
+ return { iso2: parsed.country, national: parsed.nationalNumber }
87
+ }
88
+
89
+ const digits = digitsOnly(trimmed)
90
+
91
+ // Keep the country the caller already holds when the digits still agree with it,
92
+ // so typing `+47…` one character at a time never reassigns the user's selection
93
+ // to another country sharing the prefix.
94
+ const fallbackDialCode = getPhoneDialCode(fallbackIso2)
95
+ if (digits.startsWith(fallbackDialCode)) {
96
+ return { iso2: fallbackIso2, national: digits.slice(fallbackDialCode.length) }
97
+ }
98
+
99
+ const iso2 = findCountryByDialCode(digits)
100
+ if (iso2 === undefined) return { iso2: fallbackIso2, national: digits }
101
+
102
+ return { iso2, national: digits.slice(getPhoneDialCode(iso2).length) }
103
+ }
104
+
105
+ /**
106
+ * Compose the stored value from the country and whatever the user typed.
107
+ *
108
+ * Two branches, and the split is the point. Once the input is a real number for the
109
+ * country, the stored value is the library's own E.164 rendering, which drops what a
110
+ * plain `+dialCode + digits` concatenation would double: a trunk prefix (`0701234567`
111
+ * for SE), a redundant country code (`4748012345` for NO) or an IDD prefix
112
+ * (`004748012345`). Concatenating those produced `+460701234567` and `+474748012345`.
113
+ *
114
+ * Until then it falls back to concatenation, because an in-progress number must still
115
+ * round-trip through the store for the field to show it back — so this deliberately
116
+ * does not reject anything. Use `isValidPhone` for the save gate. Returns `''` for an
117
+ * empty national part so an untouched field stores nothing rather than a bare `'+47'`.
118
+ */
119
+ export function toE164(nationalInput: string, iso2: PhoneCountry): string {
120
+ const digits = digitsOnly(nationalInput)
121
+ if (digits.length === 0) return ''
122
+
123
+ const parsed = parsePhoneNumberFromString(digits, iso2)
124
+ if (parsed?.isValid() === true) return parsed.number
125
+
126
+ return `+${getPhoneDialCode(iso2)}${digits}`
127
+ }
128
+
129
+ /**
130
+ * Progressive per-country grouping for the input mask, e.g. `'48012345'` → `'48 01 23 45'`
131
+ * for NO, `'70 123 45 67'` for SE and `'213 373 4253'` for US.
132
+ *
133
+ * Groups by the country's **international** format rather than its national one, and
134
+ * the difference is not cosmetic: countries with a trunk prefix (SE, GB, DE, FR) define
135
+ * their national formats *with* the leading `0`, so feeding the bare national number to
136
+ * `AsYouType(iso2)` returns it unformatted. The field edits the national part while the
137
+ * selector carries the country code, which is exactly the international shape.
138
+ *
139
+ * Grouping therefore follows each country's official format — for Norwegian numbers
140
+ * `xx xx xx xx`, not the `### ## ###` the legacy `NORWEGIAN_PHONE_NUMBER` constant
141
+ * hardcoded for every Norwegian number regardless of its prefix.
142
+ */
143
+ export function formatNationalAsYouType(nationalInput: string, iso2: PhoneCountry): string {
144
+ const digits = digitsOnly(nationalInput)
145
+ if (digits.length === 0) return ''
146
+
147
+ const dialCode = `+${getPhoneDialCode(iso2)}`
148
+ const formatted = new AsYouType().input(`${dialCode}${digits}`)
149
+
150
+ return formatted.startsWith(dialCode) ? formatted.slice(dialCode.length).trimStart() : formatted
151
+ }
152
+
153
+ /**
154
+ * Whether the national number is a real, dialable number for the country —
155
+ * a per-country pattern check, not a digit count. `'00000000'` and `'12345678'`
156
+ * are both rejected for NO, `'48012345'` is accepted.
157
+ */
158
+ export function isValidPhone(nationalInput: string, iso2: PhoneCountry): boolean {
159
+ const digits = digitsOnly(nationalInput)
160
+ if (digits.length < PHONE_MIN_DIGITS || digits.length > PHONE_MAX_DIGITS) return false
161
+
162
+ return isValidPhoneNumber(digits, iso2)
163
+ }
164
+
165
+ /** Whether a stored value is a valid number, resolving its country from the value itself. */
166
+ export function isValidPhoneValue(
167
+ value: string | null | undefined,
168
+ fallbackIso2: PhoneCountry = DEFAULT_PHONE_COUNTRY,
169
+ ): boolean {
170
+ const { iso2, national } = parsePhoneValue(value, fallbackIso2)
171
+ return isValidPhone(national, iso2)
172
+ }
173
+
174
+ /**
175
+ * Human-readable international form for read-only views, e.g. `'+47 48 01 23 45'`.
176
+ * Falls back to the raw value so an unparseable legacy record still renders.
177
+ */
178
+ export function formatPhoneForDisplay(
179
+ value: string | null | undefined,
180
+ fallbackIso2: PhoneCountry = DEFAULT_PHONE_COUNTRY,
181
+ ): string {
182
+ const trimmed = (value ?? '').trim()
183
+ if (trimmed.length === 0) return ''
184
+
185
+ const { iso2, national } = parsePhoneValue(trimmed, fallbackIso2)
186
+ const parsed = parsePhoneNumberFromString(toE164(national, iso2))
187
+
188
+ return parsed?.formatInternational() ?? trimmed
189
+ }
190
+
191
+ /**
192
+ * `tel:` URI for a click-to-call link — the single place the scheme is added (ASMA-7485).
193
+ * Returns `''` when there is nothing to dial, so callers can skip rendering the link.
194
+ */
195
+ export function phoneTelHref(
196
+ value: string | null | undefined,
197
+ fallbackIso2: PhoneCountry = DEFAULT_PHONE_COUNTRY,
198
+ ): string {
199
+ const { iso2, national } = parsePhoneValue(value, fallbackIso2)
200
+ const e164 = toE164(national, iso2)
201
+
202
+ return e164.length === 0 ? '' : `tel:${e164}`
203
+ }