asma-core-helpers 0.35.0 → 0.37.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,257 @@
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
+ /**
25
+ * The country to *edit* with. Always set, because a field needs a selection even for a value
26
+ * that carries no country of its own — in that case this is `fallbackIso2`.
27
+ */
28
+ iso2: PhoneCountry
29
+ /**
30
+ * The country the value actually *resolves to*, or `undefined` when nothing in the value
31
+ * says. Mirrors `parsePhoneNr(...).country`, and the two must agree: REQ-007.
32
+ *
33
+ * Read this, not `iso2`, before showing a user what country their stored number belongs to.
34
+ * `iso2` answers "which selection do I put in the picker"; `country` answers "do I actually
35
+ * know". Conflating them is what would let a therapist see a Norwegian flag on a foreign
36
+ * number and "correct" it into somebody else's valid Norwegian one.
37
+ */
38
+ country: PhoneCountry | undefined
39
+ /** National significant number, digits only — no dial code, no separators. */
40
+ national: string
41
+ }
42
+
43
+ const digitsOnly = (value: string): string => value.replace(/\D/g, '')
44
+
45
+ export type PhoneNrParse =
46
+ | { ok: true; e164: string; country: PhoneCountry | undefined; callingCode: string }
47
+ | { ok: false; reason: 'EMPTY' | 'INVALID'; input: string }
48
+
49
+ /**
50
+ * Canonicalise a value of unknown shape into E.164 — the one function every writer and
51
+ * the backfill share, so runtime and migration agree byte for byte.
52
+ *
53
+ * `defaultRegion` is required rather than defaulted on purpose. Guessing a region at
54
+ * *read* time, repeatedly and implicitly, is what left the fleet with several
55
+ * `+47`-assuming normalizers that disagree; the region is an explicit input applied
56
+ * once, where a value enters the system, and only when the input carries no `+`.
57
+ *
58
+ * Returns a result rather than throwing or coercing: a value that is not a real number
59
+ * under that region — junk like `'12345678'`, or a Swedish national number stored bare
60
+ * in a Norwegian tenant — is unrecoverable by any algorithm and must be reported to a
61
+ * human, never rewritten into something plausible.
62
+ */
63
+ export function parsePhoneNr(input: string | null | undefined, defaultRegion: PhoneCountry): PhoneNrParse {
64
+ const text = (input ?? '').trim()
65
+ if (text.length === 0) return { ok: false, reason: 'EMPTY', input: text }
66
+
67
+ try {
68
+ const parsed = parsePhoneNumberWithError(text, defaultRegion)
69
+ if (!parsed.isValid()) return { ok: false, reason: 'INVALID', input: text }
70
+
71
+ return { ok: true, e164: parsed.number, country: parsed.country, callingCode: parsed.countryCallingCode }
72
+ } catch {
73
+ return { ok: false, reason: 'INVALID', input: text }
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Split a stored value into the country and the national number the field edits.
79
+ *
80
+ * `country` is what the **value** says, and `undefined` when it says nothing recognisable. A
81
+ * leading `+` is evidence: `'+4748'` resolves to `NO` while still being typed, because the dial
82
+ * code names the country even though the number is incomplete. A value with no `+` carries no
83
+ * such evidence, so the fallback is reported as the country only when the numbering plan confirms
84
+ * it — otherwise `country` is `undefined` and `iso2` is merely the selection to edit with.
85
+ *
86
+ * Three shapes reach this function:
87
+ * - E.164 (`'+4748012345'`) — the format this ticket introduces;
88
+ * - a bare national number (`'48012345'`) — every record written before it, which
89
+ * is why `fallbackIso2` exists rather than the value being rejected;
90
+ * - a partially typed `+47…`, which `parsePhoneNumberFromString` cannot parse yet
91
+ * and which therefore falls through to the longest-dial-code match.
92
+ */
93
+ export function parsePhoneValue(
94
+ value: string | null | undefined,
95
+ fallbackIso2: PhoneCountry = DEFAULT_PHONE_COUNTRY,
96
+ ): ParsedPhone {
97
+ const trimmed = (value ?? '').trim()
98
+ if (trimmed.length === 0) return { iso2: fallbackIso2, country: undefined, national: '' }
99
+
100
+ if (!trimmed.startsWith('+')) {
101
+ // No `+`, so the value itself names no country. The fallback is only *confirmed* when the
102
+ // digits are a real number under it; otherwise the country stays unknown and the caller
103
+ // must not present the fallback as fact. `libphonenumber-js` cannot recover a foreign
104
+ // calling code from a plus-less string — `'37376002949'` under `NO` yields `+4737376002949`
105
+ // with `isValid() === false`, not Moldova — so guessing here is always a guess.
106
+ const national = digitsOnly(trimmed)
107
+ const confirmed = isValidPhone(national, fallbackIso2)
108
+
109
+ return { iso2: fallbackIso2, country: confirmed ? fallbackIso2 : undefined, national }
110
+ }
111
+
112
+ const parsed = parsePhoneNumberFromString(trimmed)
113
+ if (parsed?.country !== undefined) {
114
+ return { iso2: parsed.country, country: parsed.country, national: parsed.nationalNumber }
115
+ }
116
+
117
+ const digits = digitsOnly(trimmed)
118
+
119
+ // Keep the country the caller already holds when the digits still agree with it,
120
+ // so typing `+47…` one character at a time never reassigns the user's selection
121
+ // to another country sharing the prefix.
122
+ const fallbackDialCode = getPhoneDialCode(fallbackIso2)
123
+ if (digits.startsWith(fallbackDialCode)) {
124
+ return { iso2: fallbackIso2, country: fallbackIso2, national: digits.slice(fallbackDialCode.length) }
125
+ }
126
+
127
+ const iso2 = findCountryByDialCode(digits)
128
+ if (iso2 === undefined) return { iso2: fallbackIso2, country: undefined, national: digits }
129
+
130
+ return { iso2, country: iso2, national: digits.slice(getPhoneDialCode(iso2).length) }
131
+ }
132
+
133
+ /**
134
+ * Compose the stored value from the country and whatever the user typed.
135
+ *
136
+ * Two branches, and the split is the point. Once the input is a real number for the
137
+ * country, the stored value is the library's own E.164 rendering, which drops what a
138
+ * plain `+dialCode + digits` concatenation would double: a trunk prefix (`0701234567`
139
+ * for SE), a redundant country code (`4748012345` for NO) or an IDD prefix
140
+ * (`004748012345`). Concatenating those produced `+460701234567` and `+474748012345`.
141
+ *
142
+ * Until then it falls back to concatenation, because an in-progress number must still
143
+ * round-trip through the store for the field to show it back — so this deliberately
144
+ * does not reject anything. Use `isValidPhone` for the save gate. Returns `''` for an
145
+ * empty national part so an untouched field stores nothing rather than a bare `'+47'`.
146
+ */
147
+ export function toE164(nationalInput: string, iso2: PhoneCountry): string {
148
+ const digits = digitsOnly(nationalInput)
149
+ if (digits.length === 0) return ''
150
+
151
+ const parsed = parsePhoneNumberFromString(digits, iso2)
152
+ if (parsed?.isValid() === true) return parsed.number
153
+
154
+ return `+${getPhoneDialCode(iso2)}${digits}`
155
+ }
156
+
157
+ /**
158
+ * Progressive per-country grouping for the input mask, e.g. `'48012345'` → `'48 01 23 45'`
159
+ * for NO, `'70 123 45 67'` for SE and `'213 373 4253'` for US.
160
+ *
161
+ * Groups by the country's **international** format rather than its national one, and
162
+ * the difference is not cosmetic: countries with a trunk prefix (SE, GB, DE, FR) define
163
+ * their national formats *with* the leading `0`, so feeding the bare national number to
164
+ * `AsYouType(iso2)` returns it unformatted. The field edits the national part while the
165
+ * selector carries the country code, which is exactly the international shape.
166
+ *
167
+ * Grouping therefore follows each country's official format — for Norwegian numbers
168
+ * `xx xx xx xx`, not the `### ## ###` the legacy `NORWEGIAN_PHONE_NUMBER` constant
169
+ * hardcoded for every Norwegian number regardless of its prefix.
170
+ */
171
+ export function formatNationalAsYouType(nationalInput: string, iso2: PhoneCountry): string {
172
+ const digits = digitsOnly(nationalInput)
173
+ if (digits.length === 0) return ''
174
+
175
+ const dialCode = `+${getPhoneDialCode(iso2)}`
176
+ const formatted = new AsYouType().input(`${dialCode}${digits}`)
177
+
178
+ return formatted.startsWith(dialCode) ? formatted.slice(dialCode.length).trimStart() : formatted
179
+ }
180
+
181
+ /**
182
+ * Whether the national number is a real, dialable number for the country —
183
+ * a per-country pattern check, not a digit count. `'00000000'` and `'12345678'`
184
+ * are both rejected for NO, `'48012345'` is accepted.
185
+ */
186
+ export function isValidPhone(nationalInput: string, iso2: PhoneCountry): boolean {
187
+ const digits = digitsOnly(nationalInput)
188
+ if (digits.length < PHONE_MIN_DIGITS || digits.length > PHONE_MAX_DIGITS) return false
189
+
190
+ return isValidPhoneNumber(digits, iso2)
191
+ }
192
+
193
+ /** Whether a stored value is a valid number, resolving its country from the value itself. */
194
+ export function isValidPhoneValue(
195
+ value: string | null | undefined,
196
+ fallbackIso2: PhoneCountry = DEFAULT_PHONE_COUNTRY,
197
+ ): boolean {
198
+ const { iso2, national } = parsePhoneValue(value, fallbackIso2)
199
+ return isValidPhone(national, iso2)
200
+ }
201
+
202
+ /**
203
+ * Human-readable international form for read-only views, e.g. `'+47 48 01 23 45'`.
204
+ * Falls back to the stored value, byte for byte, for anything that is not a real number.
205
+ *
206
+ * The fallback covers the 13 production rows whose country cannot be derived — a plus-less
207
+ * `'0701234567'` is a Swedish mobile written nationally, and under the `NO` fallback it is not a
208
+ * number at all. Formatting it anyway produced `'+47 0701234567'`: a country the value never named,
209
+ * attached to digits that are not Norwegian. That is invariant 7 ("junk is refused, not
210
+ * transformed — none of them acquires a `+47` prefix") broken in the render rather than in the
211
+ * column, and it reads to a therapist as a number the system understood.
212
+ *
213
+ * Validity, not parseability, is the test. `parsePhoneNumberFromString` returns an object for
214
+ * `'+470701234567'` too, so the old `?? trimmed` fallback could never fire.
215
+ */
216
+ export function formatPhoneForDisplay(
217
+ value: string | null | undefined,
218
+ fallbackIso2: PhoneCountry = DEFAULT_PHONE_COUNTRY,
219
+ ): string {
220
+ const trimmed = (value ?? '').trim()
221
+ if (trimmed.length === 0) return ''
222
+
223
+ const { iso2, national } = parsePhoneValue(trimmed, fallbackIso2)
224
+ const parsed = parsePhoneNumberFromString(toE164(national, iso2))
225
+
226
+ return parsed?.isValid() === true ? parsed.formatInternational() : trimmed
227
+ }
228
+
229
+ /**
230
+ * `tel:` URI for a click-to-call link — the single place the scheme is added (ASMA-7485).
231
+ * Returns `''` only when the value holds no number at all, so callers can skip the link.
232
+ *
233
+ * A number we can confirm is dialled in its canonical E.164 form. Anything else is still
234
+ * dialable — a therapist has to be able to ring the 13 production rows whose country is not
235
+ * derivable — but it is linked **exactly as stored**, so the dialer opens pre-filled with the
236
+ * digits a human would have read off the field and typed.
237
+ *
238
+ * What it must never link is a number we composed. `'0701234567'` under `NO` used to yield
239
+ * `tel:+470701234567`: a Swedish mobile with a Norwegian code welded on, which is a different
240
+ * subscriber, reads as authoritative, and on a phone dials without asking. `tel:0701234567` is
241
+ * the honest version of the same link — it may not connect from a Norwegian handset either, but
242
+ * it hands the therapist the real digits to complete rather than a confident wrong number.
243
+ */
244
+ export function phoneTelHref(
245
+ value: string | null | undefined,
246
+ fallbackIso2: PhoneCountry = DEFAULT_PHONE_COUNTRY,
247
+ ): string {
248
+ const { iso2, national } = parsePhoneValue(value, fallbackIso2)
249
+ if (isValidPhone(national, iso2)) return `tel:${toE164(national, iso2)}`
250
+
251
+ const trimmed = (value ?? '').trim()
252
+ const digits = digitsOnly(trimmed)
253
+ if (digits.length < PHONE_MIN_DIGITS) return ''
254
+
255
+ // The leading `+` is kept when the stored value carried one, and never added when it did not.
256
+ return `tel:${trimmed.startsWith('+') ? '+' : ''}${digits}`
257
+ }