@mdgascar/phone 0.0.0-stage → 0.7.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mdgascar contributors
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,37 @@
1
- # Temporary Holding Version
1
+ # @mdgascar/phone
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
+ Parse, validate and format Madagascar (+261) mobile phone numbers. Zero dependencies,
4
+ ESM + CommonJS + types.
5
+
6
+ Implements spec 0.6.0.
7
+
8
+ ```sh
9
+ npm install @mdgascar/phone
10
+ ```
11
+
12
+ ```ts
13
+ import {
14
+ OPERATOR_NAMES,
15
+ formatPhoneNumber,
16
+ isValidPhoneNumber,
17
+ parsePhoneNumber,
18
+ safeParsePhoneNumber,
19
+ tryParsePhoneNumber,
20
+ } from '@mdgascar/phone';
21
+
22
+ parsePhoneNumber('034 12 345 67');
23
+ // { e164: '+261341234567', nationalNumber: '341234567', operator: 'yas' }
24
+
25
+ formatPhoneNumber('+261341234567', 'national'); // '034 12 345 67'
26
+ isValidPhoneNumber('031 12 345 67'); // false
27
+ tryParsePhoneNumber('031 12 345 67'); // undefined (never throws)
28
+
29
+ const result = safeParsePhoneNumber(userInput);
30
+ if (!result.success) console.log(result.error.code); // 'INVALID_FORMAT' | 'UNKNOWN_OPERATOR' | …
31
+
32
+ OPERATOR_NAMES.yas; // 'Yas Madagascar'
33
+ ```
34
+
35
+ Rules, operator prefixes and sources: [spec/phone](https://github.com/mdgascar/mdg-utils-spec/blob/dev/modules/phone/README.md).
36
+
37
+ Docs, API reference and a live playground: [mdgascar.github.io/mdg-utils-docs/docs/phone/](https://mdgascar.github.io/mdg-utils-docs/docs/phone/).
package/dist/index.cjs ADDED
@@ -0,0 +1,158 @@
1
+ 'use strict';
2
+
3
+ // src/generated/data.ts
4
+ var COUNTRY_CODE = "261";
5
+ var INTERNATIONAL_PREFIX = "00";
6
+ var TRUNK_PREFIX = "0";
7
+ var NATIONAL_NUMBER_LENGTH = 9;
8
+ var GROUPING = [2, 2, 3, 2];
9
+ var OPERATOR_NAMES = {
10
+ orange: "Orange Madagascar",
11
+ airtel: "Airtel Madagascar",
12
+ yas: "Yas Madagascar",
13
+ blueline: "Blueline"
14
+ };
15
+ var OPERATOR_BY_PREFIX = /* @__PURE__ */ new Map([
16
+ ["32", "orange"],
17
+ ["33", "airtel"],
18
+ ["34", "yas"],
19
+ ["35", "airtel"],
20
+ ["37", "orange"],
21
+ ["38", "yas"],
22
+ ["39", "blueline"]
23
+ ]);
24
+ var OPERATOR_PREFIX_LENGTH = 2;
25
+
26
+ // src/generated/errors.ts
27
+ var SPEC_VERSION = "0.6.0";
28
+ var MdgError = class extends Error {
29
+ /** Always `'MdgError'`. */
30
+ name = "MdgError";
31
+ /** Why the call failed; the same code in every language. */
32
+ code;
33
+ /**
34
+ * Creates an error with a shared spec code.
35
+ *
36
+ * @param code - Shared spec error code.
37
+ * @param message - Human-readable explanation, in English.
38
+ */
39
+ constructor(code, message) {
40
+ super(message);
41
+ this.code = code;
42
+ }
43
+ /**
44
+ * Makes `instanceof MdgError` true for errors from any mdg-utils package or build.
45
+ *
46
+ * @remarks Each package, and its ESM and CommonJS builds, has its own copy of this class,
47
+ * so the check looks at the error's shape instead of its prototype chain.
48
+ *
49
+ * @param value - Any value, usually a caught error.
50
+ * @returns `true` when `value` is an mdg-utils error.
51
+ */
52
+ static [Symbol.hasInstance](value) {
53
+ return value instanceof Error && value.name === "MdgError" && "code" in value;
54
+ }
55
+ };
56
+
57
+ // src/result.ts
58
+ function failure(code, message) {
59
+ return { success: false, error: new MdgError(code, message) };
60
+ }
61
+
62
+ // src/read-national-number.ts
63
+ var MAX_INPUT_LENGTH = 32;
64
+ var SEPARATORS = /[\s().-]/g;
65
+ var NATIONAL_NUMBER_DIGITS = /^[1-9]\d*$/;
66
+ var NATIONAL_PREFIXES = [
67
+ `+${COUNTRY_CODE}`,
68
+ `${INTERNATIONAL_PREFIX}${COUNTRY_CODE}`,
69
+ COUNTRY_CODE,
70
+ TRUNK_PREFIX,
71
+ ""
72
+ ];
73
+ function stripNationalPrefix(compact) {
74
+ const prefix = NATIONAL_PREFIXES.find(
75
+ (candidate) => compact.startsWith(candidate) && compact.length === candidate.length + NATIONAL_NUMBER_LENGTH
76
+ );
77
+ return prefix === void 0 ? void 0 : compact.slice(prefix.length);
78
+ }
79
+ function readNationalNumber(input) {
80
+ if (input.length > MAX_INPUT_LENGTH) {
81
+ return failure(
82
+ "INVALID_FORMAT",
83
+ `Phone numbers are at most ${String(MAX_INPUT_LENGTH)} characters.`
84
+ );
85
+ }
86
+ const nationalNumber = stripNationalPrefix(input.replace(SEPARATORS, ""));
87
+ if (nationalNumber === void 0 || !NATIONAL_NUMBER_DIGITS.test(nationalNumber)) {
88
+ return failure("INVALID_FORMAT", "Expected a Malagasy number such as 034 12 345 67.");
89
+ }
90
+ return { success: true, data: nationalNumber };
91
+ }
92
+
93
+ // src/phone-number.ts
94
+ function safeParsePhoneNumber(input) {
95
+ if (typeof input !== "string") return failure("INVALID_TYPE", "Expected the number as a string.");
96
+ const national = readNationalNumber(input);
97
+ if (!national.success) return national;
98
+ const operator = OPERATOR_BY_PREFIX.get(national.data.slice(0, OPERATOR_PREFIX_LENGTH));
99
+ if (operator === void 0) {
100
+ return failure("UNKNOWN_OPERATOR", "The prefix is not assigned to a Malagasy mobile operator.");
101
+ }
102
+ const phone = {
103
+ e164: `+${COUNTRY_CODE}${national.data}`,
104
+ nationalNumber: national.data,
105
+ operator
106
+ };
107
+ return { success: true, data: phone };
108
+ }
109
+ function parsePhoneNumber(input) {
110
+ const result = safeParsePhoneNumber(input);
111
+ if (!result.success) throw result.error;
112
+ return result.data;
113
+ }
114
+ function tryParsePhoneNumber(input) {
115
+ const result = safeParsePhoneNumber(input);
116
+ return result.success ? result.data : void 0;
117
+ }
118
+ function isValidPhoneNumber(input) {
119
+ return safeParsePhoneNumber(input).success;
120
+ }
121
+
122
+ // src/format.ts
123
+ var PHONE_NUMBER_FORMATS = ["e164", "international", "national"];
124
+ var GROUP_BOUNDS = GROUPING.reduce((bounds, size) => {
125
+ const start = bounds.at(-1)?.[1] ?? 0;
126
+ return [...bounds, [start, start + size]];
127
+ }, []);
128
+ function groupDigits(nationalNumber) {
129
+ return GROUP_BOUNDS.map(([start, end]) => nationalNumber.slice(start, end)).join(" ");
130
+ }
131
+ var FORMATTERS = {
132
+ e164: (nationalNumber) => `+${COUNTRY_CODE}${nationalNumber}`,
133
+ international: (nationalNumber) => `+${COUNTRY_CODE} ${groupDigits(nationalNumber)}`,
134
+ national: (nationalNumber) => `${TRUNK_PREFIX}${groupDigits(nationalNumber)}`
135
+ };
136
+ function isPhoneNumberFormat(value) {
137
+ return PHONE_NUMBER_FORMATS.some((format) => format === value);
138
+ }
139
+ function formatPhoneNumber(input, format) {
140
+ if (!isPhoneNumberFormat(format)) {
141
+ throw new MdgError(
142
+ "INVALID_TYPE",
143
+ `Format must be one of: ${PHONE_NUMBER_FORMATS.join(", ")}.`
144
+ );
145
+ }
146
+ return FORMATTERS[format](parsePhoneNumber(input).nationalNumber);
147
+ }
148
+
149
+ exports.MdgError = MdgError;
150
+ exports.OPERATOR_NAMES = OPERATOR_NAMES;
151
+ exports.SPEC_VERSION = SPEC_VERSION;
152
+ exports.formatPhoneNumber = formatPhoneNumber;
153
+ exports.isValidPhoneNumber = isValidPhoneNumber;
154
+ exports.parsePhoneNumber = parsePhoneNumber;
155
+ exports.safeParsePhoneNumber = safeParsePhoneNumber;
156
+ exports.tryParsePhoneNumber = tryParsePhoneNumber;
157
+ //# sourceMappingURL=index.cjs.map
158
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/generated/data.ts","../src/generated/errors.ts","../src/result.ts","../src/read-national-number.ts","../src/phone-number.ts","../src/format.ts"],"names":[],"mappings":";;;AAKO,IAAM,YAAA,GAAe,KAAA;AAGrB,IAAM,oBAAA,GAAuB,IAAA;AAG7B,IAAM,YAAA,GAAe,GAAA;AAGrB,IAAM,sBAAA,GAAyB,CAAA;AAG/B,IAAM,QAAA,GAAW,CAAC,CAAA,EAAG,CAAA,EAAG,GAAG,CAAC,CAAA;AAa5B,IAAM,cAAA,GAAiB;AAAA,EAC5B,MAAA,EAAQ,mBAAA;AAAA,EACR,MAAA,EAAQ,mBAAA;AAAA,EACR,GAAA,EAAK,gBAAA;AAAA,EACL,QAAA,EAAU;AACZ;AAGO,IAAM,kBAAA,uBAA0D,GAAA,CAAwB;AAAA,EAC7F,CAAC,MAAM,QAAQ,CAAA;AAAA,EACf,CAAC,MAAM,QAAQ,CAAA;AAAA,EACf,CAAC,MAAM,KAAK,CAAA;AAAA,EACZ,CAAC,MAAM,QAAQ,CAAA;AAAA,EACf,CAA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AEA,IAAM,UAAA,GAAsF;AAAA,EAC1F,MAAM,CAAC,cAAA,KAAmB,CAAA,CAAA,EAAI,YAAY,GAAG,cAAc,CAAA,CAAA;AAAA,EAC3D,aAAA,EAAe,CAAC,cAAA,KAAmB,CAAA,CAAA,EAAI,YAAY,CAAA,CAAA,EAAI,WAAA,CAAY,cAAc,CAAC,CAAA,CAAA;AAAA,EAClF,QAAA,EAAU,CAAC,cAAA,KAAmB,CAAA,EAAG,YAAY,CAAA,EAAG,WAAA,CAAY,cAAc,CAAC,CAAA;AAC7E,CAAA;AAEA,SAAS,oBAAoB,KAAA,EAA4C;AACvE,EAAA,OAAO,oBAAA,CAAqB,IAAA,CAAK,CAAC,MAAA,KAAW,WAAW,KAAK,CAAA;AAC/D;AAiBO,SAAS,iBAAA,CAAkB,OAAe,MAAA,EAAmC;AAClF,EAAA,IAAI,CAAC,mBAAA,CAAoB,MAAM,CAAA,EAAG;AAChC,IAAA,MAAM,IAAI,QAAA;AAAA,MACR,cAAA;AAAA,MACA,CAAA,uBAAA,EAA0B,oBAAA,CAAqB,IAAA,CAAK,IAAI,CAAC,CAAA,CAAA;AAAA,KAC3D;AAAA,EACF;AACA,EAAA,OAAO,WAAW,MAAM,CAAA,CAAE,gBAAA,CAAiB,KAAK,EAAE,cAAc,CAAA;AAClE","file":"index.cjs","sourcesContent":["// GENERATED — edit spec/ instead. Run `just codegen` to refresh.\n\n// From spec/modules/phone/data.yaml, spec 0.6.0.\n\n/** @internal */\nexport const COUNTRY_CODE = '261' as const;\n\n/** @internal */\nexport const INTERNATIONAL_PREFIX = '00' as const;\n\n/** @internal */\nexport const TRUNK_PREFIX = '0' as const;\n\n/** @internal */\nexport const NATIONAL_NUMBER_LENGTH = 9 as const;\n\n/** @internal Digit group sizes of the national number. */\nexport const GROUPING = [2, 2, 3, 2] as const;\n\n/** Identifier of a Malagasy mobile operator. */\nexport type OperatorId = 'orange' | 'airtel' | 'yas' | 'blueline';\n\n/**\n * Display name of each mobile operator, by {@link OperatorId}.\n *\n * @example\n * ```ts\n * OPERATOR_NAMES[parsePhoneNumber('034 12 345 67').operator]; // 'Yas Madagascar'\n * ```\n */\nexport const OPERATOR_NAMES = {\n orange: 'Orange Madagascar',\n airtel: 'Airtel Madagascar',\n yas: 'Yas Madagascar',\n blueline: 'Blueline',\n} as const;\n\n/** @internal Two-digit operator code → operator. */\nexport const OPERATOR_BY_PREFIX: ReadonlyMap<string, OperatorId> = new Map<string, OperatorId>([\n ['32', 'orange'],\n ['33', 'airtel'],\n ['34', 'yas'],\n ['35', 'airtel'],\n ['37', 'orange'],\n ['38', 'yas'],\n ['39', 'blueline'],\n]);\n\n/** @internal */\nexport const OPERATOR_PREFIX_LENGTH = 2 as const;\n","// GENERATED — edit spec/ instead. Run `just codegen` to refresh.\n\n/** Version of the shared spec this code was generated from. */\nexport const SPEC_VERSION = '0.6.0';\n\n/**\n * Error code shared by every mdg-utils language port.\n *\n * - `INVALID_TYPE`: The input is not of the accepted type (for example a string or a non-integer where an integer is expected).\n * - `OUT_OF_RANGE`: The input has the right type but lies outside the supported range.\n * - `INVALID_FORMAT`: The input text cannot be read as a value of this module (wrong characters or wrong length).\n * - `UNKNOWN_OPERATOR`: The phone number is well formed but its operator code is not assigned to a mobile operator.\n */\nexport type ErrorCode = 'INVALID_TYPE' | 'OUT_OF_RANGE' | 'INVALID_FORMAT' | 'UNKNOWN_OPERATOR';\n\n/**\n * Outcome of a `safeParse…` function: the value, or the error that would have been thrown.\n *\n * @example\n * ```ts\n * const result = safeParsePhoneNumber(input);\n * if (result.success) console.log(result.data);\n * else console.log(result.error.code);\n * ```\n */\nexport type SafeParseResult<T> =\n | { readonly success: true; readonly data: T }\n | { readonly success: false; readonly error: MdgError };\n\n/**\n * Error thrown by mdg-utils functions. Check `code`, which is the same in every language.\n *\n * @example\n * ```ts\n * try {\n * numberToWords(-1);\n * } catch (error) {\n * if (error instanceof MdgError && error.code === 'OUT_OF_RANGE') {\n * // handle it\n * }\n * }\n * ```\n */\nexport class MdgError extends Error {\n /** Always `'MdgError'`. */\n override readonly name = 'MdgError';\n /** Why the call failed; the same code in every language. */\n readonly code: ErrorCode;\n\n /**\n * Creates an error with a shared spec code.\n *\n * @param code - Shared spec error code.\n * @param message - Human-readable explanation, in English.\n */\n constructor(code: ErrorCode, message: string) {\n super(message);\n this.code = code;\n }\n\n /**\n * Makes `instanceof MdgError` true for errors from any mdg-utils package or build.\n *\n * @remarks Each package, and its ESM and CommonJS builds, has its own copy of this class,\n * so the check looks at the error's shape instead of its prototype chain.\n *\n * @param value - Any value, usually a caught error.\n * @returns `true` when `value` is an mdg-utils error.\n */\n static override [Symbol.hasInstance](value: unknown): boolean {\n return value instanceof Error && value.name === 'MdgError' && 'code' in value;\n }\n}\n","import { MdgError, type ErrorCode, type SafeParseResult } from './generated/errors.ts';\n\n/**\n * A rejected parse carrying its spec error code.\n *\n * @param code - The spec error code.\n * @param message - What was wrong with the input.\n * @returns `{ success: false, error }`.\n *\n * @example\n * ```ts\n * failure('INVALID_FORMAT', 'Expected a number.'); // { success: false, error: MdgError }\n * ```\n */\nexport function failure(code: ErrorCode, message: string): SafeParseResult<never> {\n return { success: false, error: new MdgError(code, message) };\n}\n","// Reads a number typed in any common way into its 9-digit national significant number.\nimport {\n COUNTRY_CODE,\n INTERNATIONAL_PREFIX,\n NATIONAL_NUMBER_LENGTH,\n TRUNK_PREFIX,\n} from './generated/data.ts';\nimport type { SafeParseResult } from './generated/errors.ts';\nimport { failure } from './result.ts';\n\n// Bounded so a parser that reads user input never scans unbounded text.\nconst MAX_INPUT_LENGTH = 32;\nconst SEPARATORS = /[\\s().-]/g;\n// A national significant number never starts with the trunk prefix 0 (ITU-T E.164).\nconst NATIONAL_NUMBER_DIGITS = /^[1-9]\\d*$/;\nconst NATIONAL_PREFIXES = [\n `+${COUNTRY_CODE}`,\n `${INTERNATIONAL_PREFIX}${COUNTRY_CODE}`,\n COUNTRY_CODE,\n TRUNK_PREFIX,\n '',\n] as const;\n\nfunction stripNationalPrefix(compact: string): string | undefined {\n const prefix = NATIONAL_PREFIXES.find(\n (candidate) =>\n compact.startsWith(candidate) && compact.length === candidate.length + NATIONAL_NUMBER_LENGTH,\n );\n return prefix === undefined ? undefined : compact.slice(prefix.length);\n}\n\n/**\n * Strips separators and the `+261`, `00261`, `261` or `0` prefix, keeping the 9 digits.\n *\n * @param input - The number as typed by a user.\n * @returns The national significant number, or `INVALID_FORMAT`.\n *\n * @example\n * ```ts\n * readNationalNumber('+261 34 12 345 67'); // { success: true, data: '341234567' }\n * ```\n */\nexport function readNationalNumber(input: string): SafeParseResult<string> {\n if (input.length > MAX_INPUT_LENGTH) {\n return failure(\n 'INVALID_FORMAT',\n `Phone numbers are at most ${String(MAX_INPUT_LENGTH)} characters.`,\n );\n }\n const nationalNumber = stripNationalPrefix(input.replace(SEPARATORS, ''));\n if (nationalNumber === undefined || !NATIONAL_NUMBER_DIGITS.test(nationalNumber)) {\n return failure('INVALID_FORMAT', 'Expected a Malagasy number such as 034 12 345 67.');\n }\n return { success: true, data: nationalNumber };\n}\n","import {\n COUNTRY_CODE,\n OPERATOR_BY_PREFIX,\n OPERATOR_PREFIX_LENGTH,\n type OperatorId,\n} from './generated/data.ts';\nimport type { SafeParseResult } from './generated/errors.ts';\nimport { readNationalNumber } from './read-national-number.ts';\nimport { failure } from './result.ts';\n\ndeclare const phoneNumberBrand: unique symbol;\n\n/**\n * A Malagasy mobile number that passed validation. Create it with {@link parsePhoneNumber}.\n *\n * @example\n * ```ts\n * const phone: PhoneNumber = parsePhoneNumber('034 12 345 67');\n * phone.e164; // '+261341234567'\n * ```\n */\nexport interface PhoneNumber {\n /** The number in E.164 form, for storage and APIs: `+261341234567`. */\n readonly e164: string;\n /** The 9 digits after the country code: `341234567`. */\n readonly nationalNumber: string;\n /** The operator that holds the number's prefix. */\n readonly operator: OperatorId;\n /** Marks values that went through validation; it does not exist at runtime. */\n readonly [phoneNumberBrand]: true;\n}\n\n/**\n * Reads a Malagasy mobile number without throwing.\n *\n * @param input - The number as typed by a user, in any accepted spelling.\n * @returns `{ success: true, data }` with the {@link PhoneNumber}, or `{ success: false, error }`.\n *\n * @example\n * ```ts\n * const result = safeParsePhoneNumber('+261 34 12 345 67');\n * if (result.success) result.data.operator; // 'yas'\n * ```\n */\nexport function safeParsePhoneNumber(input: unknown): SafeParseResult<PhoneNumber> {\n if (typeof input !== 'string') return failure('INVALID_TYPE', 'Expected the number as a string.');\n const national = readNationalNumber(input);\n if (!national.success) return national;\n const operator = OPERATOR_BY_PREFIX.get(national.data.slice(0, OPERATOR_PREFIX_LENGTH));\n if (operator === undefined) {\n return failure('UNKNOWN_OPERATOR', 'The prefix is not assigned to a Malagasy mobile operator.');\n }\n const phone = {\n e164: `+${COUNTRY_CODE}${national.data}`,\n nationalNumber: national.data,\n operator,\n };\n return { success: true, data: phone as PhoneNumber };\n}\n\n/**\n * Reads a Malagasy mobile number written in any common way.\n *\n * Accepts `034 12 345 67`, `+261 34 12 345 67`, `00261…`, `261…` and `34 12 345 67`;\n * spaces, dashes, dots and parentheses are ignored.\n *\n * @param input - The number as typed by a user.\n * @returns The validated {@link PhoneNumber}.\n * @throws {@link MdgError} `INVALID_TYPE` for non-strings, `INVALID_FORMAT` for text that is\n * not a Malagasy number, `UNKNOWN_OPERATOR` for an unassigned mobile prefix.\n *\n * @example\n * ```ts\n * parsePhoneNumber('034 12 345 67');\n * // { e164: '+261341234567', nationalNumber: '341234567', operator: 'yas' }\n * ```\n */\nexport function parsePhoneNumber(input: string): PhoneNumber {\n const result = safeParsePhoneNumber(input);\n if (!result.success) throw result.error;\n return result.data;\n}\n\n/**\n * Reads a Malagasy mobile number, or gives `undefined` instead of throwing.\n *\n * Use {@link safeParsePhoneNumber} when you need to know why the input was rejected.\n *\n * @param input - The number as typed by a user, in any accepted spelling.\n * @returns The {@link PhoneNumber}, or `undefined` when {@link parsePhoneNumber} would throw.\n *\n * @example\n * ```ts\n * tryParsePhoneNumber('034 12 345 67')?.operator; // 'yas'\n * tryParsePhoneNumber('031 12 345 67'); // undefined\n * ```\n */\nexport function tryParsePhoneNumber(input: unknown): PhoneNumber | undefined {\n const result = safeParsePhoneNumber(input);\n return result.success ? result.data : undefined;\n}\n\n/**\n * Tells whether the input is a valid Malagasy mobile number. Never throws.\n *\n * @param input - Any value.\n * @returns `true` when {@link parsePhoneNumber} would succeed.\n *\n * @example\n * ```ts\n * isValidPhoneNumber('034 12 345 67'); // true\n * isValidPhoneNumber('031 12 345 67'); // false\n * ```\n */\nexport function isValidPhoneNumber(input: unknown): boolean {\n return safeParsePhoneNumber(input).success;\n}\n","import { COUNTRY_CODE, GROUPING, TRUNK_PREFIX } from './generated/data.ts';\nimport { MdgError } from './generated/errors.ts';\nimport { parsePhoneNumber } from './phone-number.ts';\n\n/**\n * How {@link formatPhoneNumber} writes a number.\n *\n * - `e164`: `+261341234567`\n * - `international`: `+261 34 12 345 67`\n * - `national`: `034 12 345 67`\n *\n * @example\n * ```ts\n * const format: PhoneNumberFormat = 'national';\n * ```\n */\nexport type PhoneNumberFormat = 'e164' | 'international' | 'national';\n\nconst PHONE_NUMBER_FORMATS: readonly PhoneNumberFormat[] = ['e164', 'international', 'national'];\n\nconst GROUP_BOUNDS = GROUPING.reduce<readonly (readonly [number, number])[]>((bounds, size) => {\n const start = bounds.at(-1)?.[1] ?? 0;\n return [...bounds, [start, start + size]];\n}, []);\n\nfunction groupDigits(nationalNumber: string): string {\n return GROUP_BOUNDS.map(([start, end]) => nationalNumber.slice(start, end)).join(' ');\n}\n\nconst FORMATTERS: Readonly<Record<PhoneNumberFormat, (nationalNumber: string) => string>> = {\n e164: (nationalNumber) => `+${COUNTRY_CODE}${nationalNumber}`,\n international: (nationalNumber) => `+${COUNTRY_CODE} ${groupDigits(nationalNumber)}`,\n national: (nationalNumber) => `${TRUNK_PREFIX}${groupDigits(nationalNumber)}`,\n};\n\nfunction isPhoneNumberFormat(value: unknown): value is PhoneNumberFormat {\n return PHONE_NUMBER_FORMATS.some((format) => format === value);\n}\n\n/**\n * Writes a Malagasy mobile number in a standard form.\n *\n * @param input - The number in any spelling accepted by {@link parsePhoneNumber}.\n * @param format - `'e164'`, `'international'` or `'national'`.\n * @returns The formatted number.\n * @throws {@link MdgError} `INVALID_TYPE` for an unknown format, plus every error of\n * {@link parsePhoneNumber}.\n *\n * @example\n * ```ts\n * formatPhoneNumber('+261341234567', 'national'); // '034 12 345 67'\n * formatPhoneNumber('034 12 345 67', 'international'); // '+261 34 12 345 67'\n * ```\n */\nexport function formatPhoneNumber(input: string, format: PhoneNumberFormat): string {\n if (!isPhoneNumberFormat(format)) {\n throw new MdgError(\n 'INVALID_TYPE',\n `Format must be one of: ${PHONE_NUMBER_FORMATS.join(', ')}.`,\n );\n }\n return FORMATTERS[format](parsePhoneNumber(input).nationalNumber);\n}\n"]}
@@ -0,0 +1,195 @@
1
+ /**
2
+ * How {@link formatPhoneNumber} writes a number.
3
+ *
4
+ * - `e164`: `+261341234567`
5
+ * - `international`: `+261 34 12 345 67`
6
+ * - `national`: `034 12 345 67`
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * const format: PhoneNumberFormat = 'national';
11
+ * ```
12
+ */
13
+ type PhoneNumberFormat = 'e164' | 'international' | 'national';
14
+ /**
15
+ * Writes a Malagasy mobile number in a standard form.
16
+ *
17
+ * @param input - The number in any spelling accepted by {@link parsePhoneNumber}.
18
+ * @param format - `'e164'`, `'international'` or `'national'`.
19
+ * @returns The formatted number.
20
+ * @throws {@link MdgError} `INVALID_TYPE` for an unknown format, plus every error of
21
+ * {@link parsePhoneNumber}.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * formatPhoneNumber('+261341234567', 'national'); // '034 12 345 67'
26
+ * formatPhoneNumber('034 12 345 67', 'international'); // '+261 34 12 345 67'
27
+ * ```
28
+ */
29
+ declare function formatPhoneNumber(input: string, format: PhoneNumberFormat): string;
30
+
31
+ /** Identifier of a Malagasy mobile operator. */
32
+ type OperatorId = 'orange' | 'airtel' | 'yas' | 'blueline';
33
+ /**
34
+ * Display name of each mobile operator, by {@link OperatorId}.
35
+ *
36
+ * @example
37
+ * ```ts
38
+ * OPERATOR_NAMES[parsePhoneNumber('034 12 345 67').operator]; // 'Yas Madagascar'
39
+ * ```
40
+ */
41
+ declare const OPERATOR_NAMES: {
42
+ readonly orange: "Orange Madagascar";
43
+ readonly airtel: "Airtel Madagascar";
44
+ readonly yas: "Yas Madagascar";
45
+ readonly blueline: "Blueline";
46
+ };
47
+
48
+ /** Version of the shared spec this code was generated from. */
49
+ declare const SPEC_VERSION = "0.6.0";
50
+ /**
51
+ * Error code shared by every mdg-utils language port.
52
+ *
53
+ * - `INVALID_TYPE`: The input is not of the accepted type (for example a string or a non-integer where an integer is expected).
54
+ * - `OUT_OF_RANGE`: The input has the right type but lies outside the supported range.
55
+ * - `INVALID_FORMAT`: The input text cannot be read as a value of this module (wrong characters or wrong length).
56
+ * - `UNKNOWN_OPERATOR`: The phone number is well formed but its operator code is not assigned to a mobile operator.
57
+ */
58
+ type ErrorCode = 'INVALID_TYPE' | 'OUT_OF_RANGE' | 'INVALID_FORMAT' | 'UNKNOWN_OPERATOR';
59
+ /**
60
+ * Outcome of a `safeParse…` function: the value, or the error that would have been thrown.
61
+ *
62
+ * @example
63
+ * ```ts
64
+ * const result = safeParsePhoneNumber(input);
65
+ * if (result.success) console.log(result.data);
66
+ * else console.log(result.error.code);
67
+ * ```
68
+ */
69
+ type SafeParseResult<T> = {
70
+ readonly success: true;
71
+ readonly data: T;
72
+ } | {
73
+ readonly success: false;
74
+ readonly error: MdgError;
75
+ };
76
+ /**
77
+ * Error thrown by mdg-utils functions. Check `code`, which is the same in every language.
78
+ *
79
+ * @example
80
+ * ```ts
81
+ * try {
82
+ * numberToWords(-1);
83
+ * } catch (error) {
84
+ * if (error instanceof MdgError && error.code === 'OUT_OF_RANGE') {
85
+ * // handle it
86
+ * }
87
+ * }
88
+ * ```
89
+ */
90
+ declare class MdgError extends Error {
91
+ /** Always `'MdgError'`. */
92
+ readonly name = "MdgError";
93
+ /** Why the call failed; the same code in every language. */
94
+ readonly code: ErrorCode;
95
+ /**
96
+ * Creates an error with a shared spec code.
97
+ *
98
+ * @param code - Shared spec error code.
99
+ * @param message - Human-readable explanation, in English.
100
+ */
101
+ constructor(code: ErrorCode, message: string);
102
+ /**
103
+ * Makes `instanceof MdgError` true for errors from any mdg-utils package or build.
104
+ *
105
+ * @remarks Each package, and its ESM and CommonJS builds, has its own copy of this class,
106
+ * so the check looks at the error's shape instead of its prototype chain.
107
+ *
108
+ * @param value - Any value, usually a caught error.
109
+ * @returns `true` when `value` is an mdg-utils error.
110
+ */
111
+ static [Symbol.hasInstance](value: unknown): boolean;
112
+ }
113
+
114
+ declare const phoneNumberBrand: unique symbol;
115
+ /**
116
+ * A Malagasy mobile number that passed validation. Create it with {@link parsePhoneNumber}.
117
+ *
118
+ * @example
119
+ * ```ts
120
+ * const phone: PhoneNumber = parsePhoneNumber('034 12 345 67');
121
+ * phone.e164; // '+261341234567'
122
+ * ```
123
+ */
124
+ interface PhoneNumber {
125
+ /** The number in E.164 form, for storage and APIs: `+261341234567`. */
126
+ readonly e164: string;
127
+ /** The 9 digits after the country code: `341234567`. */
128
+ readonly nationalNumber: string;
129
+ /** The operator that holds the number's prefix. */
130
+ readonly operator: OperatorId;
131
+ /** Marks values that went through validation; it does not exist at runtime. */
132
+ readonly [phoneNumberBrand]: true;
133
+ }
134
+ /**
135
+ * Reads a Malagasy mobile number without throwing.
136
+ *
137
+ * @param input - The number as typed by a user, in any accepted spelling.
138
+ * @returns `{ success: true, data }` with the {@link PhoneNumber}, or `{ success: false, error }`.
139
+ *
140
+ * @example
141
+ * ```ts
142
+ * const result = safeParsePhoneNumber('+261 34 12 345 67');
143
+ * if (result.success) result.data.operator; // 'yas'
144
+ * ```
145
+ */
146
+ declare function safeParsePhoneNumber(input: unknown): SafeParseResult<PhoneNumber>;
147
+ /**
148
+ * Reads a Malagasy mobile number written in any common way.
149
+ *
150
+ * Accepts `034 12 345 67`, `+261 34 12 345 67`, `00261…`, `261…` and `34 12 345 67`;
151
+ * spaces, dashes, dots and parentheses are ignored.
152
+ *
153
+ * @param input - The number as typed by a user.
154
+ * @returns The validated {@link PhoneNumber}.
155
+ * @throws {@link MdgError} `INVALID_TYPE` for non-strings, `INVALID_FORMAT` for text that is
156
+ * not a Malagasy number, `UNKNOWN_OPERATOR` for an unassigned mobile prefix.
157
+ *
158
+ * @example
159
+ * ```ts
160
+ * parsePhoneNumber('034 12 345 67');
161
+ * // { e164: '+261341234567', nationalNumber: '341234567', operator: 'yas' }
162
+ * ```
163
+ */
164
+ declare function parsePhoneNumber(input: string): PhoneNumber;
165
+ /**
166
+ * Reads a Malagasy mobile number, or gives `undefined` instead of throwing.
167
+ *
168
+ * Use {@link safeParsePhoneNumber} when you need to know why the input was rejected.
169
+ *
170
+ * @param input - The number as typed by a user, in any accepted spelling.
171
+ * @returns The {@link PhoneNumber}, or `undefined` when {@link parsePhoneNumber} would throw.
172
+ *
173
+ * @example
174
+ * ```ts
175
+ * tryParsePhoneNumber('034 12 345 67')?.operator; // 'yas'
176
+ * tryParsePhoneNumber('031 12 345 67'); // undefined
177
+ * ```
178
+ */
179
+ declare function tryParsePhoneNumber(input: unknown): PhoneNumber | undefined;
180
+ /**
181
+ * Tells whether the input is a valid Malagasy mobile number. Never throws.
182
+ *
183
+ * @param input - Any value.
184
+ * @returns `true` when {@link parsePhoneNumber} would succeed.
185
+ *
186
+ * @example
187
+ * ```ts
188
+ * isValidPhoneNumber('034 12 345 67'); // true
189
+ * isValidPhoneNumber('031 12 345 67'); // false
190
+ * ```
191
+ */
192
+ declare function isValidPhoneNumber(input: unknown): boolean;
193
+
194
+ export { MdgError, OPERATOR_NAMES, SPEC_VERSION, formatPhoneNumber, isValidPhoneNumber, parsePhoneNumber, safeParsePhoneNumber, tryParsePhoneNumber };
195
+ export type { ErrorCode, OperatorId, PhoneNumber, PhoneNumberFormat, SafeParseResult };
@@ -0,0 +1,195 @@
1
+ /**
2
+ * How {@link formatPhoneNumber} writes a number.
3
+ *
4
+ * - `e164`: `+261341234567`
5
+ * - `international`: `+261 34 12 345 67`
6
+ * - `national`: `034 12 345 67`
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * const format: PhoneNumberFormat = 'national';
11
+ * ```
12
+ */
13
+ type PhoneNumberFormat = 'e164' | 'international' | 'national';
14
+ /**
15
+ * Writes a Malagasy mobile number in a standard form.
16
+ *
17
+ * @param input - The number in any spelling accepted by {@link parsePhoneNumber}.
18
+ * @param format - `'e164'`, `'international'` or `'national'`.
19
+ * @returns The formatted number.
20
+ * @throws {@link MdgError} `INVALID_TYPE` for an unknown format, plus every error of
21
+ * {@link parsePhoneNumber}.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * formatPhoneNumber('+261341234567', 'national'); // '034 12 345 67'
26
+ * formatPhoneNumber('034 12 345 67', 'international'); // '+261 34 12 345 67'
27
+ * ```
28
+ */
29
+ declare function formatPhoneNumber(input: string, format: PhoneNumberFormat): string;
30
+
31
+ /** Identifier of a Malagasy mobile operator. */
32
+ type OperatorId = 'orange' | 'airtel' | 'yas' | 'blueline';
33
+ /**
34
+ * Display name of each mobile operator, by {@link OperatorId}.
35
+ *
36
+ * @example
37
+ * ```ts
38
+ * OPERATOR_NAMES[parsePhoneNumber('034 12 345 67').operator]; // 'Yas Madagascar'
39
+ * ```
40
+ */
41
+ declare const OPERATOR_NAMES: {
42
+ readonly orange: "Orange Madagascar";
43
+ readonly airtel: "Airtel Madagascar";
44
+ readonly yas: "Yas Madagascar";
45
+ readonly blueline: "Blueline";
46
+ };
47
+
48
+ /** Version of the shared spec this code was generated from. */
49
+ declare const SPEC_VERSION = "0.6.0";
50
+ /**
51
+ * Error code shared by every mdg-utils language port.
52
+ *
53
+ * - `INVALID_TYPE`: The input is not of the accepted type (for example a string or a non-integer where an integer is expected).
54
+ * - `OUT_OF_RANGE`: The input has the right type but lies outside the supported range.
55
+ * - `INVALID_FORMAT`: The input text cannot be read as a value of this module (wrong characters or wrong length).
56
+ * - `UNKNOWN_OPERATOR`: The phone number is well formed but its operator code is not assigned to a mobile operator.
57
+ */
58
+ type ErrorCode = 'INVALID_TYPE' | 'OUT_OF_RANGE' | 'INVALID_FORMAT' | 'UNKNOWN_OPERATOR';
59
+ /**
60
+ * Outcome of a `safeParse…` function: the value, or the error that would have been thrown.
61
+ *
62
+ * @example
63
+ * ```ts
64
+ * const result = safeParsePhoneNumber(input);
65
+ * if (result.success) console.log(result.data);
66
+ * else console.log(result.error.code);
67
+ * ```
68
+ */
69
+ type SafeParseResult<T> = {
70
+ readonly success: true;
71
+ readonly data: T;
72
+ } | {
73
+ readonly success: false;
74
+ readonly error: MdgError;
75
+ };
76
+ /**
77
+ * Error thrown by mdg-utils functions. Check `code`, which is the same in every language.
78
+ *
79
+ * @example
80
+ * ```ts
81
+ * try {
82
+ * numberToWords(-1);
83
+ * } catch (error) {
84
+ * if (error instanceof MdgError && error.code === 'OUT_OF_RANGE') {
85
+ * // handle it
86
+ * }
87
+ * }
88
+ * ```
89
+ */
90
+ declare class MdgError extends Error {
91
+ /** Always `'MdgError'`. */
92
+ readonly name = "MdgError";
93
+ /** Why the call failed; the same code in every language. */
94
+ readonly code: ErrorCode;
95
+ /**
96
+ * Creates an error with a shared spec code.
97
+ *
98
+ * @param code - Shared spec error code.
99
+ * @param message - Human-readable explanation, in English.
100
+ */
101
+ constructor(code: ErrorCode, message: string);
102
+ /**
103
+ * Makes `instanceof MdgError` true for errors from any mdg-utils package or build.
104
+ *
105
+ * @remarks Each package, and its ESM and CommonJS builds, has its own copy of this class,
106
+ * so the check looks at the error's shape instead of its prototype chain.
107
+ *
108
+ * @param value - Any value, usually a caught error.
109
+ * @returns `true` when `value` is an mdg-utils error.
110
+ */
111
+ static [Symbol.hasInstance](value: unknown): boolean;
112
+ }
113
+
114
+ declare const phoneNumberBrand: unique symbol;
115
+ /**
116
+ * A Malagasy mobile number that passed validation. Create it with {@link parsePhoneNumber}.
117
+ *
118
+ * @example
119
+ * ```ts
120
+ * const phone: PhoneNumber = parsePhoneNumber('034 12 345 67');
121
+ * phone.e164; // '+261341234567'
122
+ * ```
123
+ */
124
+ interface PhoneNumber {
125
+ /** The number in E.164 form, for storage and APIs: `+261341234567`. */
126
+ readonly e164: string;
127
+ /** The 9 digits after the country code: `341234567`. */
128
+ readonly nationalNumber: string;
129
+ /** The operator that holds the number's prefix. */
130
+ readonly operator: OperatorId;
131
+ /** Marks values that went through validation; it does not exist at runtime. */
132
+ readonly [phoneNumberBrand]: true;
133
+ }
134
+ /**
135
+ * Reads a Malagasy mobile number without throwing.
136
+ *
137
+ * @param input - The number as typed by a user, in any accepted spelling.
138
+ * @returns `{ success: true, data }` with the {@link PhoneNumber}, or `{ success: false, error }`.
139
+ *
140
+ * @example
141
+ * ```ts
142
+ * const result = safeParsePhoneNumber('+261 34 12 345 67');
143
+ * if (result.success) result.data.operator; // 'yas'
144
+ * ```
145
+ */
146
+ declare function safeParsePhoneNumber(input: unknown): SafeParseResult<PhoneNumber>;
147
+ /**
148
+ * Reads a Malagasy mobile number written in any common way.
149
+ *
150
+ * Accepts `034 12 345 67`, `+261 34 12 345 67`, `00261…`, `261…` and `34 12 345 67`;
151
+ * spaces, dashes, dots and parentheses are ignored.
152
+ *
153
+ * @param input - The number as typed by a user.
154
+ * @returns The validated {@link PhoneNumber}.
155
+ * @throws {@link MdgError} `INVALID_TYPE` for non-strings, `INVALID_FORMAT` for text that is
156
+ * not a Malagasy number, `UNKNOWN_OPERATOR` for an unassigned mobile prefix.
157
+ *
158
+ * @example
159
+ * ```ts
160
+ * parsePhoneNumber('034 12 345 67');
161
+ * // { e164: '+261341234567', nationalNumber: '341234567', operator: 'yas' }
162
+ * ```
163
+ */
164
+ declare function parsePhoneNumber(input: string): PhoneNumber;
165
+ /**
166
+ * Reads a Malagasy mobile number, or gives `undefined` instead of throwing.
167
+ *
168
+ * Use {@link safeParsePhoneNumber} when you need to know why the input was rejected.
169
+ *
170
+ * @param input - The number as typed by a user, in any accepted spelling.
171
+ * @returns The {@link PhoneNumber}, or `undefined` when {@link parsePhoneNumber} would throw.
172
+ *
173
+ * @example
174
+ * ```ts
175
+ * tryParsePhoneNumber('034 12 345 67')?.operator; // 'yas'
176
+ * tryParsePhoneNumber('031 12 345 67'); // undefined
177
+ * ```
178
+ */
179
+ declare function tryParsePhoneNumber(input: unknown): PhoneNumber | undefined;
180
+ /**
181
+ * Tells whether the input is a valid Malagasy mobile number. Never throws.
182
+ *
183
+ * @param input - Any value.
184
+ * @returns `true` when {@link parsePhoneNumber} would succeed.
185
+ *
186
+ * @example
187
+ * ```ts
188
+ * isValidPhoneNumber('034 12 345 67'); // true
189
+ * isValidPhoneNumber('031 12 345 67'); // false
190
+ * ```
191
+ */
192
+ declare function isValidPhoneNumber(input: unknown): boolean;
193
+
194
+ export { MdgError, OPERATOR_NAMES, SPEC_VERSION, formatPhoneNumber, isValidPhoneNumber, parsePhoneNumber, safeParsePhoneNumber, tryParsePhoneNumber };
195
+ export type { ErrorCode, OperatorId, PhoneNumber, PhoneNumberFormat, SafeParseResult };
package/dist/index.js ADDED
@@ -0,0 +1,149 @@
1
+ // src/generated/data.ts
2
+ var COUNTRY_CODE = "261";
3
+ var INTERNATIONAL_PREFIX = "00";
4
+ var TRUNK_PREFIX = "0";
5
+ var NATIONAL_NUMBER_LENGTH = 9;
6
+ var GROUPING = [2, 2, 3, 2];
7
+ var OPERATOR_NAMES = {
8
+ orange: "Orange Madagascar",
9
+ airtel: "Airtel Madagascar",
10
+ yas: "Yas Madagascar",
11
+ blueline: "Blueline"
12
+ };
13
+ var OPERATOR_BY_PREFIX = /* @__PURE__ */ new Map([
14
+ ["32", "orange"],
15
+ ["33", "airtel"],
16
+ ["34", "yas"],
17
+ ["35", "airtel"],
18
+ ["37", "orange"],
19
+ ["38", "yas"],
20
+ ["39", "blueline"]
21
+ ]);
22
+ var OPERATOR_PREFIX_LENGTH = 2;
23
+
24
+ // src/generated/errors.ts
25
+ var SPEC_VERSION = "0.6.0";
26
+ var MdgError = class extends Error {
27
+ /** Always `'MdgError'`. */
28
+ name = "MdgError";
29
+ /** Why the call failed; the same code in every language. */
30
+ code;
31
+ /**
32
+ * Creates an error with a shared spec code.
33
+ *
34
+ * @param code - Shared spec error code.
35
+ * @param message - Human-readable explanation, in English.
36
+ */
37
+ constructor(code, message) {
38
+ super(message);
39
+ this.code = code;
40
+ }
41
+ /**
42
+ * Makes `instanceof MdgError` true for errors from any mdg-utils package or build.
43
+ *
44
+ * @remarks Each package, and its ESM and CommonJS builds, has its own copy of this class,
45
+ * so the check looks at the error's shape instead of its prototype chain.
46
+ *
47
+ * @param value - Any value, usually a caught error.
48
+ * @returns `true` when `value` is an mdg-utils error.
49
+ */
50
+ static [Symbol.hasInstance](value) {
51
+ return value instanceof Error && value.name === "MdgError" && "code" in value;
52
+ }
53
+ };
54
+
55
+ // src/result.ts
56
+ function failure(code, message) {
57
+ return { success: false, error: new MdgError(code, message) };
58
+ }
59
+
60
+ // src/read-national-number.ts
61
+ var MAX_INPUT_LENGTH = 32;
62
+ var SEPARATORS = /[\s().-]/g;
63
+ var NATIONAL_NUMBER_DIGITS = /^[1-9]\d*$/;
64
+ var NATIONAL_PREFIXES = [
65
+ `+${COUNTRY_CODE}`,
66
+ `${INTERNATIONAL_PREFIX}${COUNTRY_CODE}`,
67
+ COUNTRY_CODE,
68
+ TRUNK_PREFIX,
69
+ ""
70
+ ];
71
+ function stripNationalPrefix(compact) {
72
+ const prefix = NATIONAL_PREFIXES.find(
73
+ (candidate) => compact.startsWith(candidate) && compact.length === candidate.length + NATIONAL_NUMBER_LENGTH
74
+ );
75
+ return prefix === void 0 ? void 0 : compact.slice(prefix.length);
76
+ }
77
+ function readNationalNumber(input) {
78
+ if (input.length > MAX_INPUT_LENGTH) {
79
+ return failure(
80
+ "INVALID_FORMAT",
81
+ `Phone numbers are at most ${String(MAX_INPUT_LENGTH)} characters.`
82
+ );
83
+ }
84
+ const nationalNumber = stripNationalPrefix(input.replace(SEPARATORS, ""));
85
+ if (nationalNumber === void 0 || !NATIONAL_NUMBER_DIGITS.test(nationalNumber)) {
86
+ return failure("INVALID_FORMAT", "Expected a Malagasy number such as 034 12 345 67.");
87
+ }
88
+ return { success: true, data: nationalNumber };
89
+ }
90
+
91
+ // src/phone-number.ts
92
+ function safeParsePhoneNumber(input) {
93
+ if (typeof input !== "string") return failure("INVALID_TYPE", "Expected the number as a string.");
94
+ const national = readNationalNumber(input);
95
+ if (!national.success) return national;
96
+ const operator = OPERATOR_BY_PREFIX.get(national.data.slice(0, OPERATOR_PREFIX_LENGTH));
97
+ if (operator === void 0) {
98
+ return failure("UNKNOWN_OPERATOR", "The prefix is not assigned to a Malagasy mobile operator.");
99
+ }
100
+ const phone = {
101
+ e164: `+${COUNTRY_CODE}${national.data}`,
102
+ nationalNumber: national.data,
103
+ operator
104
+ };
105
+ return { success: true, data: phone };
106
+ }
107
+ function parsePhoneNumber(input) {
108
+ const result = safeParsePhoneNumber(input);
109
+ if (!result.success) throw result.error;
110
+ return result.data;
111
+ }
112
+ function tryParsePhoneNumber(input) {
113
+ const result = safeParsePhoneNumber(input);
114
+ return result.success ? result.data : void 0;
115
+ }
116
+ function isValidPhoneNumber(input) {
117
+ return safeParsePhoneNumber(input).success;
118
+ }
119
+
120
+ // src/format.ts
121
+ var PHONE_NUMBER_FORMATS = ["e164", "international", "national"];
122
+ var GROUP_BOUNDS = GROUPING.reduce((bounds, size) => {
123
+ const start = bounds.at(-1)?.[1] ?? 0;
124
+ return [...bounds, [start, start + size]];
125
+ }, []);
126
+ function groupDigits(nationalNumber) {
127
+ return GROUP_BOUNDS.map(([start, end]) => nationalNumber.slice(start, end)).join(" ");
128
+ }
129
+ var FORMATTERS = {
130
+ e164: (nationalNumber) => `+${COUNTRY_CODE}${nationalNumber}`,
131
+ international: (nationalNumber) => `+${COUNTRY_CODE} ${groupDigits(nationalNumber)}`,
132
+ national: (nationalNumber) => `${TRUNK_PREFIX}${groupDigits(nationalNumber)}`
133
+ };
134
+ function isPhoneNumberFormat(value) {
135
+ return PHONE_NUMBER_FORMATS.some((format) => format === value);
136
+ }
137
+ function formatPhoneNumber(input, format) {
138
+ if (!isPhoneNumberFormat(format)) {
139
+ throw new MdgError(
140
+ "INVALID_TYPE",
141
+ `Format must be one of: ${PHONE_NUMBER_FORMATS.join(", ")}.`
142
+ );
143
+ }
144
+ return FORMATTERS[format](parsePhoneNumber(input).nationalNumber);
145
+ }
146
+
147
+ export { MdgError, OPERATOR_NAMES, SPEC_VERSION, formatPhoneNumber, isValidPhoneNumber, parsePhoneNumber, safeParsePhoneNumber, tryParsePhoneNumber };
148
+ //# sourceMappingURL=index.js.map
149
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/generated/data.ts","../src/generated/errors.ts","../src/result.ts","../src/read-national-number.ts","../src/phone-number.ts","../src/format.ts"],"names":[],"mappings":";AAKO,IAAM,YAAA,GAAe,KAAA;AAGrB,IAAM,oBAAA,GAAuB,IAAA;AAG7B,IAAM,YAAA,GAAe,GAAA;AAGrB,IAAM,sBAAA,GAAyB,CAAA;AAG/B,IAAM,QAAA,GAAW,CAAC,CAAA,EAAG,CAAA,EAAG,GAAG,CAAC,CAAA;AAa5B,IAAM,cAAA,GAAiB;AAAA,EAC5B,MAAA,EAAQ,mBAAA;AAAA,EACR,MAAA,EAAQ,mBAAA;AAAA,EACR,GAAA,EAAK,gBAAA;AAAA,EACL,QAAA,EAAU;AACZ;AAGO,IAAM,kBAAA,uBAA0D,GAAA,CAAwB;AAAA,EAC7F,CAAC,MAAM,QAAQ,CAAA;AAAA,EACf,CAAC,MAAM,QAAQ,CAAA;AAAA,EACf,CAAC,MAAM,KAAK,CAAA;AAAA,EACZ,CAAC,MAAM,QAAQ,CAAA;AAAA,EACf,CAAC,MAAM,QAAQ,CAAA;AAAA,EACf,CAAC,MAAM,KAAK,CAAA;AAAA,EACZ,CAAC,MAAM,UAAU;AACnB,CAAC,CAAA;AAGM,IAAM,sBA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3D,aAAA,EAAe,CAAC,cAAA,KAAmB,CAAA,CAAA,EAAI,YAAY,CAAA,CAAA,EAAI,WAAA,CAAY,cAAc,CAAC,CAAA,CAAA;AAAA,EAClF,QAAA,EAAU,CAAC,cAAA,KAAmB,CAAA,EAAG,YAAY,CAAA,EAAG,WAAA,CAAY,cAAc,CAAC,CAAA;AAC7E,CAAA;AAEA,SAAS,oBAAoB,KAAA,EAA4C;AACvE,EAAA,OAAO,oBAAA,CAAqB,IAAA,CAAK,CAAC,MAAA,KAAW,WAAW,KAAK,CAAA;AAC/D;AAiBO,SAAS,iBAAA,CAAkB,OAAe,MAAA,EAAmC;AAClF,EAAA,IAAI,CAAC,mBAAA,CAAoB,MAAM,CAAA,EAAG;AAChC,IAAA,MAAM,IAAI,QAAA;AAAA,MACR,cAAA;AAAA,MACA,CAAA,uBAAA,EAA0B,oBAAA,CAAqB,IAAA,CAAK,IAAI,CAAC,CAAA,CAAA;AAAA,KAC3D;AAAA,EACF;AACA,EAAA,OAAO,WAAW,MAAM,CAAA,CAAE,gBAAA,CAAiB,KAAK,EAAE,cAAc,CAAA;AAClE","file":"index.js","sourcesContent":["// GENERATED — edit spec/ instead. Run `just codegen` to refresh.\n\n// From spec/modules/phone/data.yaml, spec 0.6.0.\n\n/** @internal */\nexport const COUNTRY_CODE = '261' as const;\n\n/** @internal */\nexport const INTERNATIONAL_PREFIX = '00' as const;\n\n/** @internal */\nexport const TRUNK_PREFIX = '0' as const;\n\n/** @internal */\nexport const NATIONAL_NUMBER_LENGTH = 9 as const;\n\n/** @internal Digit group sizes of the national number. */\nexport const GROUPING = [2, 2, 3, 2] as const;\n\n/** Identifier of a Malagasy mobile operator. */\nexport type OperatorId = 'orange' | 'airtel' | 'yas' | 'blueline';\n\n/**\n * Display name of each mobile operator, by {@link OperatorId}.\n *\n * @example\n * ```ts\n * OPERATOR_NAMES[parsePhoneNumber('034 12 345 67').operator]; // 'Yas Madagascar'\n * ```\n */\nexport const OPERATOR_NAMES = {\n orange: 'Orange Madagascar',\n airtel: 'Airtel Madagascar',\n yas: 'Yas Madagascar',\n blueline: 'Blueline',\n} as const;\n\n/** @internal Two-digit operator code → operator. */\nexport const OPERATOR_BY_PREFIX: ReadonlyMap<string, OperatorId> = new Map<string, OperatorId>([\n ['32', 'orange'],\n ['33', 'airtel'],\n ['34', 'yas'],\n ['35', 'airtel'],\n ['37', 'orange'],\n ['38', 'yas'],\n ['39', 'blueline'],\n]);\n\n/** @internal */\nexport const OPERATOR_PREFIX_LENGTH = 2 as const;\n","// GENERATED — edit spec/ instead. Run `just codegen` to refresh.\n\n/** Version of the shared spec this code was generated from. */\nexport const SPEC_VERSION = '0.6.0';\n\n/**\n * Error code shared by every mdg-utils language port.\n *\n * - `INVALID_TYPE`: The input is not of the accepted type (for example a string or a non-integer where an integer is expected).\n * - `OUT_OF_RANGE`: The input has the right type but lies outside the supported range.\n * - `INVALID_FORMAT`: The input text cannot be read as a value of this module (wrong characters or wrong length).\n * - `UNKNOWN_OPERATOR`: The phone number is well formed but its operator code is not assigned to a mobile operator.\n */\nexport type ErrorCode = 'INVALID_TYPE' | 'OUT_OF_RANGE' | 'INVALID_FORMAT' | 'UNKNOWN_OPERATOR';\n\n/**\n * Outcome of a `safeParse…` function: the value, or the error that would have been thrown.\n *\n * @example\n * ```ts\n * const result = safeParsePhoneNumber(input);\n * if (result.success) console.log(result.data);\n * else console.log(result.error.code);\n * ```\n */\nexport type SafeParseResult<T> =\n | { readonly success: true; readonly data: T }\n | { readonly success: false; readonly error: MdgError };\n\n/**\n * Error thrown by mdg-utils functions. Check `code`, which is the same in every language.\n *\n * @example\n * ```ts\n * try {\n * numberToWords(-1);\n * } catch (error) {\n * if (error instanceof MdgError && error.code === 'OUT_OF_RANGE') {\n * // handle it\n * }\n * }\n * ```\n */\nexport class MdgError extends Error {\n /** Always `'MdgError'`. */\n override readonly name = 'MdgError';\n /** Why the call failed; the same code in every language. */\n readonly code: ErrorCode;\n\n /**\n * Creates an error with a shared spec code.\n *\n * @param code - Shared spec error code.\n * @param message - Human-readable explanation, in English.\n */\n constructor(code: ErrorCode, message: string) {\n super(message);\n this.code = code;\n }\n\n /**\n * Makes `instanceof MdgError` true for errors from any mdg-utils package or build.\n *\n * @remarks Each package, and its ESM and CommonJS builds, has its own copy of this class,\n * so the check looks at the error's shape instead of its prototype chain.\n *\n * @param value - Any value, usually a caught error.\n * @returns `true` when `value` is an mdg-utils error.\n */\n static override [Symbol.hasInstance](value: unknown): boolean {\n return value instanceof Error && value.name === 'MdgError' && 'code' in value;\n }\n}\n","import { MdgError, type ErrorCode, type SafeParseResult } from './generated/errors.ts';\n\n/**\n * A rejected parse carrying its spec error code.\n *\n * @param code - The spec error code.\n * @param message - What was wrong with the input.\n * @returns `{ success: false, error }`.\n *\n * @example\n * ```ts\n * failure('INVALID_FORMAT', 'Expected a number.'); // { success: false, error: MdgError }\n * ```\n */\nexport function failure(code: ErrorCode, message: string): SafeParseResult<never> {\n return { success: false, error: new MdgError(code, message) };\n}\n","// Reads a number typed in any common way into its 9-digit national significant number.\nimport {\n COUNTRY_CODE,\n INTERNATIONAL_PREFIX,\n NATIONAL_NUMBER_LENGTH,\n TRUNK_PREFIX,\n} from './generated/data.ts';\nimport type { SafeParseResult } from './generated/errors.ts';\nimport { failure } from './result.ts';\n\n// Bounded so a parser that reads user input never scans unbounded text.\nconst MAX_INPUT_LENGTH = 32;\nconst SEPARATORS = /[\\s().-]/g;\n// A national significant number never starts with the trunk prefix 0 (ITU-T E.164).\nconst NATIONAL_NUMBER_DIGITS = /^[1-9]\\d*$/;\nconst NATIONAL_PREFIXES = [\n `+${COUNTRY_CODE}`,\n `${INTERNATIONAL_PREFIX}${COUNTRY_CODE}`,\n COUNTRY_CODE,\n TRUNK_PREFIX,\n '',\n] as const;\n\nfunction stripNationalPrefix(compact: string): string | undefined {\n const prefix = NATIONAL_PREFIXES.find(\n (candidate) =>\n compact.startsWith(candidate) && compact.length === candidate.length + NATIONAL_NUMBER_LENGTH,\n );\n return prefix === undefined ? undefined : compact.slice(prefix.length);\n}\n\n/**\n * Strips separators and the `+261`, `00261`, `261` or `0` prefix, keeping the 9 digits.\n *\n * @param input - The number as typed by a user.\n * @returns The national significant number, or `INVALID_FORMAT`.\n *\n * @example\n * ```ts\n * readNationalNumber('+261 34 12 345 67'); // { success: true, data: '341234567' }\n * ```\n */\nexport function readNationalNumber(input: string): SafeParseResult<string> {\n if (input.length > MAX_INPUT_LENGTH) {\n return failure(\n 'INVALID_FORMAT',\n `Phone numbers are at most ${String(MAX_INPUT_LENGTH)} characters.`,\n );\n }\n const nationalNumber = stripNationalPrefix(input.replace(SEPARATORS, ''));\n if (nationalNumber === undefined || !NATIONAL_NUMBER_DIGITS.test(nationalNumber)) {\n return failure('INVALID_FORMAT', 'Expected a Malagasy number such as 034 12 345 67.');\n }\n return { success: true, data: nationalNumber };\n}\n","import {\n COUNTRY_CODE,\n OPERATOR_BY_PREFIX,\n OPERATOR_PREFIX_LENGTH,\n type OperatorId,\n} from './generated/data.ts';\nimport type { SafeParseResult } from './generated/errors.ts';\nimport { readNationalNumber } from './read-national-number.ts';\nimport { failure } from './result.ts';\n\ndeclare const phoneNumberBrand: unique symbol;\n\n/**\n * A Malagasy mobile number that passed validation. Create it with {@link parsePhoneNumber}.\n *\n * @example\n * ```ts\n * const phone: PhoneNumber = parsePhoneNumber('034 12 345 67');\n * phone.e164; // '+261341234567'\n * ```\n */\nexport interface PhoneNumber {\n /** The number in E.164 form, for storage and APIs: `+261341234567`. */\n readonly e164: string;\n /** The 9 digits after the country code: `341234567`. */\n readonly nationalNumber: string;\n /** The operator that holds the number's prefix. */\n readonly operator: OperatorId;\n /** Marks values that went through validation; it does not exist at runtime. */\n readonly [phoneNumberBrand]: true;\n}\n\n/**\n * Reads a Malagasy mobile number without throwing.\n *\n * @param input - The number as typed by a user, in any accepted spelling.\n * @returns `{ success: true, data }` with the {@link PhoneNumber}, or `{ success: false, error }`.\n *\n * @example\n * ```ts\n * const result = safeParsePhoneNumber('+261 34 12 345 67');\n * if (result.success) result.data.operator; // 'yas'\n * ```\n */\nexport function safeParsePhoneNumber(input: unknown): SafeParseResult<PhoneNumber> {\n if (typeof input !== 'string') return failure('INVALID_TYPE', 'Expected the number as a string.');\n const national = readNationalNumber(input);\n if (!national.success) return national;\n const operator = OPERATOR_BY_PREFIX.get(national.data.slice(0, OPERATOR_PREFIX_LENGTH));\n if (operator === undefined) {\n return failure('UNKNOWN_OPERATOR', 'The prefix is not assigned to a Malagasy mobile operator.');\n }\n const phone = {\n e164: `+${COUNTRY_CODE}${national.data}`,\n nationalNumber: national.data,\n operator,\n };\n return { success: true, data: phone as PhoneNumber };\n}\n\n/**\n * Reads a Malagasy mobile number written in any common way.\n *\n * Accepts `034 12 345 67`, `+261 34 12 345 67`, `00261…`, `261…` and `34 12 345 67`;\n * spaces, dashes, dots and parentheses are ignored.\n *\n * @param input - The number as typed by a user.\n * @returns The validated {@link PhoneNumber}.\n * @throws {@link MdgError} `INVALID_TYPE` for non-strings, `INVALID_FORMAT` for text that is\n * not a Malagasy number, `UNKNOWN_OPERATOR` for an unassigned mobile prefix.\n *\n * @example\n * ```ts\n * parsePhoneNumber('034 12 345 67');\n * // { e164: '+261341234567', nationalNumber: '341234567', operator: 'yas' }\n * ```\n */\nexport function parsePhoneNumber(input: string): PhoneNumber {\n const result = safeParsePhoneNumber(input);\n if (!result.success) throw result.error;\n return result.data;\n}\n\n/**\n * Reads a Malagasy mobile number, or gives `undefined` instead of throwing.\n *\n * Use {@link safeParsePhoneNumber} when you need to know why the input was rejected.\n *\n * @param input - The number as typed by a user, in any accepted spelling.\n * @returns The {@link PhoneNumber}, or `undefined` when {@link parsePhoneNumber} would throw.\n *\n * @example\n * ```ts\n * tryParsePhoneNumber('034 12 345 67')?.operator; // 'yas'\n * tryParsePhoneNumber('031 12 345 67'); // undefined\n * ```\n */\nexport function tryParsePhoneNumber(input: unknown): PhoneNumber | undefined {\n const result = safeParsePhoneNumber(input);\n return result.success ? result.data : undefined;\n}\n\n/**\n * Tells whether the input is a valid Malagasy mobile number. Never throws.\n *\n * @param input - Any value.\n * @returns `true` when {@link parsePhoneNumber} would succeed.\n *\n * @example\n * ```ts\n * isValidPhoneNumber('034 12 345 67'); // true\n * isValidPhoneNumber('031 12 345 67'); // false\n * ```\n */\nexport function isValidPhoneNumber(input: unknown): boolean {\n return safeParsePhoneNumber(input).success;\n}\n","import { COUNTRY_CODE, GROUPING, TRUNK_PREFIX } from './generated/data.ts';\nimport { MdgError } from './generated/errors.ts';\nimport { parsePhoneNumber } from './phone-number.ts';\n\n/**\n * How {@link formatPhoneNumber} writes a number.\n *\n * - `e164`: `+261341234567`\n * - `international`: `+261 34 12 345 67`\n * - `national`: `034 12 345 67`\n *\n * @example\n * ```ts\n * const format: PhoneNumberFormat = 'national';\n * ```\n */\nexport type PhoneNumberFormat = 'e164' | 'international' | 'national';\n\nconst PHONE_NUMBER_FORMATS: readonly PhoneNumberFormat[] = ['e164', 'international', 'national'];\n\nconst GROUP_BOUNDS = GROUPING.reduce<readonly (readonly [number, number])[]>((bounds, size) => {\n const start = bounds.at(-1)?.[1] ?? 0;\n return [...bounds, [start, start + size]];\n}, []);\n\nfunction groupDigits(nationalNumber: string): string {\n return GROUP_BOUNDS.map(([start, end]) => nationalNumber.slice(start, end)).join(' ');\n}\n\nconst FORMATTERS: Readonly<Record<PhoneNumberFormat, (nationalNumber: string) => string>> = {\n e164: (nationalNumber) => `+${COUNTRY_CODE}${nationalNumber}`,\n international: (nationalNumber) => `+${COUNTRY_CODE} ${groupDigits(nationalNumber)}`,\n national: (nationalNumber) => `${TRUNK_PREFIX}${groupDigits(nationalNumber)}`,\n};\n\nfunction isPhoneNumberFormat(value: unknown): value is PhoneNumberFormat {\n return PHONE_NUMBER_FORMATS.some((format) => format === value);\n}\n\n/**\n * Writes a Malagasy mobile number in a standard form.\n *\n * @param input - The number in any spelling accepted by {@link parsePhoneNumber}.\n * @param format - `'e164'`, `'international'` or `'national'`.\n * @returns The formatted number.\n * @throws {@link MdgError} `INVALID_TYPE` for an unknown format, plus every error of\n * {@link parsePhoneNumber}.\n *\n * @example\n * ```ts\n * formatPhoneNumber('+261341234567', 'national'); // '034 12 345 67'\n * formatPhoneNumber('034 12 345 67', 'international'); // '+261 34 12 345 67'\n * ```\n */\nexport function formatPhoneNumber(input: string, format: PhoneNumberFormat): string {\n if (!isPhoneNumberFormat(format)) {\n throw new MdgError(\n 'INVALID_TYPE',\n `Format must be one of: ${PHONE_NUMBER_FORMATS.join(', ')}.`,\n );\n }\n return FORMATTERS[format](parsePhoneNumber(input).nationalNumber);\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
2
  "name": "@mdgascar/phone",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.7.0",
4
+ "description": "Parse, validate and format Madagascar (+261) mobile phone numbers.",
5
+ "license": "MIT",
6
+ "author": "Mdgascar contributors",
7
+ "homepage": "https://github.com/mdgascar/mdg-utils-js/tree/main/packages/phone#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/mdgascar/mdg-utils-js.git",
11
+ "directory": "packages/phone"
12
+ },
13
+ "bugs": "https://github.com/mdgascar/mdg-utils-js/issues",
14
+ "keywords": [
15
+ "madagascar",
16
+ "malagasy",
17
+ "phone",
18
+ "phone-number",
19
+ "validation",
20
+ "e164"
21
+ ],
22
+ "type": "module",
23
+ "sideEffects": false,
24
+ "exports": {
25
+ ".": {
26
+ "import": {
27
+ "types": "./dist/index.d.ts",
28
+ "default": "./dist/index.js"
29
+ },
30
+ "require": {
31
+ "types": "./dist/index.d.cts",
32
+ "default": "./dist/index.cjs"
33
+ }
34
+ },
35
+ "./package.json": "./package.json"
36
+ },
37
+ "main": "./dist/index.cjs",
38
+ "module": "./dist/index.js",
39
+ "types": "./dist/index.d.ts",
40
+ "files": [
41
+ "dist"
42
+ ],
43
+ "engines": {
44
+ "node": ">=22.18.0"
45
+ },
46
+ "publishConfig": {
47
+ "access": "public",
48
+ "provenance": true
49
+ },
50
+ "scripts": {
51
+ "build": "tsup",
52
+ "api": "api-extractor run --local"
53
+ }
6
54
  }