@mdgascar/phone 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  Parse, validate and format Madagascar (+261) mobile phone numbers. Zero dependencies,
4
4
  ESM + CommonJS + types.
5
5
 
6
- Implements spec 0.6.0.
6
+ Implements spec 0.8.0.
7
7
 
8
8
  ```sh
9
9
  npm install @mdgascar/phone
@@ -12,21 +12,21 @@ npm install @mdgascar/phone
12
12
  ```ts
13
13
  import {
14
14
  OPERATOR_NAMES,
15
- formatPhoneNumber,
16
- isValidPhoneNumber,
17
- parsePhoneNumber,
18
- safeParsePhoneNumber,
19
- tryParsePhoneNumber,
15
+ formatPhone,
16
+ isValidPhone,
17
+ parsePhone,
18
+ safeParsePhone,
19
+ tryParsePhone,
20
20
  } from '@mdgascar/phone';
21
21
 
22
- parsePhoneNumber('034 12 345 67');
22
+ parsePhone('034 12 345 67');
23
23
  // { e164: '+261341234567', nationalNumber: '341234567', operator: 'yas' }
24
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)
25
+ formatPhone('+261341234567', 'national'); // '034 12 345 67'
26
+ isValidPhone('031 12 345 67'); // false
27
+ tryParsePhone('031 12 345 67'); // undefined (never throws)
28
28
 
29
- const result = safeParsePhoneNumber(userInput);
29
+ const result = safeParsePhone(userInput);
30
30
  if (!result.success) console.log(result.error.code); // 'INVALID_FORMAT' | 'UNKNOWN_OPERATOR' | …
31
31
 
32
32
  OPERATOR_NAMES.yas; // 'Yas Madagascar'
package/dist/index.cjs CHANGED
@@ -24,7 +24,7 @@ var OPERATOR_BY_PREFIX = /* @__PURE__ */ new Map([
24
24
  var OPERATOR_PREFIX_LENGTH = 2;
25
25
 
26
26
  // src/generated/errors.ts
27
- var SPEC_VERSION = "0.6.0";
27
+ var SPEC_VERSION = "0.8.0";
28
28
  var MdgError = class extends Error {
29
29
  /** Always `'MdgError'`. */
30
30
  name = "MdgError";
@@ -91,7 +91,7 @@ function readNationalNumber(input) {
91
91
  }
92
92
 
93
93
  // src/phone-number.ts
94
- function safeParsePhoneNumber(input) {
94
+ function safeParsePhone(input) {
95
95
  if (typeof input !== "string") return failure("INVALID_TYPE", "Expected the number as a string.");
96
96
  const national = readNationalNumber(input);
97
97
  if (!national.success) return national;
@@ -106,17 +106,17 @@ function safeParsePhoneNumber(input) {
106
106
  };
107
107
  return { success: true, data: phone };
108
108
  }
109
- function parsePhoneNumber(input) {
110
- const result = safeParsePhoneNumber(input);
109
+ function parsePhone(input) {
110
+ const result = safeParsePhone(input);
111
111
  if (!result.success) throw result.error;
112
112
  return result.data;
113
113
  }
114
- function tryParsePhoneNumber(input) {
115
- const result = safeParsePhoneNumber(input);
114
+ function tryParsePhone(input) {
115
+ const result = safeParsePhone(input);
116
116
  return result.success ? result.data : void 0;
117
117
  }
118
- function isValidPhoneNumber(input) {
119
- return safeParsePhoneNumber(input).success;
118
+ function isValidPhone(input) {
119
+ return safeParsePhone(input).success;
120
120
  }
121
121
 
122
122
  // src/format.ts
@@ -136,23 +136,23 @@ var FORMATTERS = {
136
136
  function isPhoneNumberFormat(value) {
137
137
  return PHONE_NUMBER_FORMATS.some((format) => format === value);
138
138
  }
139
- function formatPhoneNumber(input, format) {
139
+ function formatPhone(input, format) {
140
140
  if (!isPhoneNumberFormat(format)) {
141
141
  throw new MdgError(
142
142
  "INVALID_TYPE",
143
143
  `Format must be one of: ${PHONE_NUMBER_FORMATS.join(", ")}.`
144
144
  );
145
145
  }
146
- return FORMATTERS[format](parsePhoneNumber(input).nationalNumber);
146
+ return FORMATTERS[format](parsePhone(input).nationalNumber);
147
147
  }
148
148
 
149
149
  exports.MdgError = MdgError;
150
150
  exports.OPERATOR_NAMES = OPERATOR_NAMES;
151
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;
152
+ exports.formatPhone = formatPhone;
153
+ exports.isValidPhone = isValidPhone;
154
+ exports.parsePhone = parsePhone;
155
+ exports.safeParsePhone = safeParsePhone;
156
+ exports.tryParsePhone = tryParsePhone;
157
157
  //# sourceMappingURL=index.cjs.map
158
158
  //# sourceMappingURL=index.cjs.map
@@ -1 +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,sBAAA,GAAyB,CAAA;;;AC9C/B,IAAM,YAAA,GAAe;AAwCrB,IAAM,QAAA,GAAN,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AAI,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"]}
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,sBAAA,GAAyB,CAAA;;;AC9C/B,IAAM,YAAA,GAAe;AAwCrB,IAAM,QAAA,GAAN,cAAuB,KAAA,CAAM;AAAA;AAAA,EAEhB,IAAA,GAAO,UAAA;AAAA;AAAA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AAA,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,WAAA,CAAY,OAAe,MAAA,EAAmC;AAC5E,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,UAAA,CAAW,KAAK,EAAE,cAAc,CAAA;AAC5D","file":"index.cjs","sourcesContent":["// GENERATED — edit spec/ instead. Run `just codegen` to refresh.\n\n// From spec/modules/phone/data.yaml, spec 0.8.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[parsePhone('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.8.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 = safeParsePhone(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 * spell(-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 parsePhone}.\n *\n * @example\n * ```ts\n * const phone: PhoneNumber = parsePhone('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 = safeParsePhone('+261 34 12 345 67');\n * if (result.success) result.data.operator; // 'yas'\n * ```\n */\nexport function safeParsePhone(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 * parsePhone('034 12 345 67');\n * // { e164: '+261341234567', nationalNumber: '341234567', operator: 'yas' }\n * ```\n */\nexport function parsePhone(input: string): PhoneNumber {\n const result = safeParsePhone(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 safeParsePhone} 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 parsePhone} would throw.\n *\n * @example\n * ```ts\n * tryParsePhone('034 12 345 67')?.operator; // 'yas'\n * tryParsePhone('031 12 345 67'); // undefined\n * ```\n */\nexport function tryParsePhone(input: unknown): PhoneNumber | undefined {\n const result = safeParsePhone(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 parsePhone} would succeed.\n *\n * @example\n * ```ts\n * isValidPhone('034 12 345 67'); // true\n * isValidPhone('031 12 345 67'); // false\n * ```\n */\nexport function isValidPhone(input: unknown): boolean {\n return safeParsePhone(input).success;\n}\n","import { COUNTRY_CODE, GROUPING, TRUNK_PREFIX } from './generated/data.ts';\nimport { MdgError } from './generated/errors.ts';\nimport { parsePhone } from './phone-number.ts';\n\n/**\n * How {@link formatPhone} 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 parsePhone}.\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 parsePhone}.\n *\n * @example\n * ```ts\n * formatPhone('+261341234567', 'national'); // '034 12 345 67'\n * formatPhone('034 12 345 67', 'international'); // '+261 34 12 345 67'\n * ```\n */\nexport function formatPhone(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](parsePhone(input).nationalNumber);\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * How {@link formatPhoneNumber} writes a number.
2
+ * How {@link formatPhone} writes a number.
3
3
  *
4
4
  * - `e164`: `+261341234567`
5
5
  * - `international`: `+261 34 12 345 67`
@@ -14,19 +14,19 @@ type PhoneNumberFormat = 'e164' | 'international' | 'national';
14
14
  /**
15
15
  * Writes a Malagasy mobile number in a standard form.
16
16
  *
17
- * @param input - The number in any spelling accepted by {@link parsePhoneNumber}.
17
+ * @param input - The number in any spelling accepted by {@link parsePhone}.
18
18
  * @param format - `'e164'`, `'international'` or `'national'`.
19
19
  * @returns The formatted number.
20
20
  * @throws {@link MdgError} `INVALID_TYPE` for an unknown format, plus every error of
21
- * {@link parsePhoneNumber}.
21
+ * {@link parsePhone}.
22
22
  *
23
23
  * @example
24
24
  * ```ts
25
- * formatPhoneNumber('+261341234567', 'national'); // '034 12 345 67'
26
- * formatPhoneNumber('034 12 345 67', 'international'); // '+261 34 12 345 67'
25
+ * formatPhone('+261341234567', 'national'); // '034 12 345 67'
26
+ * formatPhone('034 12 345 67', 'international'); // '+261 34 12 345 67'
27
27
  * ```
28
28
  */
29
- declare function formatPhoneNumber(input: string, format: PhoneNumberFormat): string;
29
+ declare function formatPhone(input: string, format: PhoneNumberFormat): string;
30
30
 
31
31
  /** Identifier of a Malagasy mobile operator. */
32
32
  type OperatorId = 'orange' | 'airtel' | 'yas' | 'blueline';
@@ -35,7 +35,7 @@ type OperatorId = 'orange' | 'airtel' | 'yas' | 'blueline';
35
35
  *
36
36
  * @example
37
37
  * ```ts
38
- * OPERATOR_NAMES[parsePhoneNumber('034 12 345 67').operator]; // 'Yas Madagascar'
38
+ * OPERATOR_NAMES[parsePhone('034 12 345 67').operator]; // 'Yas Madagascar'
39
39
  * ```
40
40
  */
41
41
  declare const OPERATOR_NAMES: {
@@ -46,7 +46,7 @@ declare const OPERATOR_NAMES: {
46
46
  };
47
47
 
48
48
  /** Version of the shared spec this code was generated from. */
49
- declare const SPEC_VERSION = "0.6.0";
49
+ declare const SPEC_VERSION = "0.8.0";
50
50
  /**
51
51
  * Error code shared by every mdg-utils language port.
52
52
  *
@@ -61,7 +61,7 @@ type ErrorCode = 'INVALID_TYPE' | 'OUT_OF_RANGE' | 'INVALID_FORMAT' | 'UNKNOWN_O
61
61
  *
62
62
  * @example
63
63
  * ```ts
64
- * const result = safeParsePhoneNumber(input);
64
+ * const result = safeParsePhone(input);
65
65
  * if (result.success) console.log(result.data);
66
66
  * else console.log(result.error.code);
67
67
  * ```
@@ -79,7 +79,7 @@ type SafeParseResult<T> = {
79
79
  * @example
80
80
  * ```ts
81
81
  * try {
82
- * numberToWords(-1);
82
+ * spell(-1);
83
83
  * } catch (error) {
84
84
  * if (error instanceof MdgError && error.code === 'OUT_OF_RANGE') {
85
85
  * // handle it
@@ -113,11 +113,11 @@ declare class MdgError extends Error {
113
113
 
114
114
  declare const phoneNumberBrand: unique symbol;
115
115
  /**
116
- * A Malagasy mobile number that passed validation. Create it with {@link parsePhoneNumber}.
116
+ * A Malagasy mobile number that passed validation. Create it with {@link parsePhone}.
117
117
  *
118
118
  * @example
119
119
  * ```ts
120
- * const phone: PhoneNumber = parsePhoneNumber('034 12 345 67');
120
+ * const phone: PhoneNumber = parsePhone('034 12 345 67');
121
121
  * phone.e164; // '+261341234567'
122
122
  * ```
123
123
  */
@@ -139,11 +139,11 @@ interface PhoneNumber {
139
139
  *
140
140
  * @example
141
141
  * ```ts
142
- * const result = safeParsePhoneNumber('+261 34 12 345 67');
142
+ * const result = safeParsePhone('+261 34 12 345 67');
143
143
  * if (result.success) result.data.operator; // 'yas'
144
144
  * ```
145
145
  */
146
- declare function safeParsePhoneNumber(input: unknown): SafeParseResult<PhoneNumber>;
146
+ declare function safeParsePhone(input: unknown): SafeParseResult<PhoneNumber>;
147
147
  /**
148
148
  * Reads a Malagasy mobile number written in any common way.
149
149
  *
@@ -157,39 +157,39 @@ declare function safeParsePhoneNumber(input: unknown): SafeParseResult<PhoneNumb
157
157
  *
158
158
  * @example
159
159
  * ```ts
160
- * parsePhoneNumber('034 12 345 67');
160
+ * parsePhone('034 12 345 67');
161
161
  * // { e164: '+261341234567', nationalNumber: '341234567', operator: 'yas' }
162
162
  * ```
163
163
  */
164
- declare function parsePhoneNumber(input: string): PhoneNumber;
164
+ declare function parsePhone(input: string): PhoneNumber;
165
165
  /**
166
166
  * Reads a Malagasy mobile number, or gives `undefined` instead of throwing.
167
167
  *
168
- * Use {@link safeParsePhoneNumber} when you need to know why the input was rejected.
168
+ * Use {@link safeParsePhone} when you need to know why the input was rejected.
169
169
  *
170
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.
171
+ * @returns The {@link PhoneNumber}, or `undefined` when {@link parsePhone} would throw.
172
172
  *
173
173
  * @example
174
174
  * ```ts
175
- * tryParsePhoneNumber('034 12 345 67')?.operator; // 'yas'
176
- * tryParsePhoneNumber('031 12 345 67'); // undefined
175
+ * tryParsePhone('034 12 345 67')?.operator; // 'yas'
176
+ * tryParsePhone('031 12 345 67'); // undefined
177
177
  * ```
178
178
  */
179
- declare function tryParsePhoneNumber(input: unknown): PhoneNumber | undefined;
179
+ declare function tryParsePhone(input: unknown): PhoneNumber | undefined;
180
180
  /**
181
181
  * Tells whether the input is a valid Malagasy mobile number. Never throws.
182
182
  *
183
183
  * @param input - Any value.
184
- * @returns `true` when {@link parsePhoneNumber} would succeed.
184
+ * @returns `true` when {@link parsePhone} would succeed.
185
185
  *
186
186
  * @example
187
187
  * ```ts
188
- * isValidPhoneNumber('034 12 345 67'); // true
189
- * isValidPhoneNumber('031 12 345 67'); // false
188
+ * isValidPhone('034 12 345 67'); // true
189
+ * isValidPhone('031 12 345 67'); // false
190
190
  * ```
191
191
  */
192
- declare function isValidPhoneNumber(input: unknown): boolean;
192
+ declare function isValidPhone(input: unknown): boolean;
193
193
 
194
- export { MdgError, OPERATOR_NAMES, SPEC_VERSION, formatPhoneNumber, isValidPhoneNumber, parsePhoneNumber, safeParsePhoneNumber, tryParsePhoneNumber };
194
+ export { MdgError, OPERATOR_NAMES, SPEC_VERSION, formatPhone, isValidPhone, parsePhone, safeParsePhone, tryParsePhone };
195
195
  export type { ErrorCode, OperatorId, PhoneNumber, PhoneNumberFormat, SafeParseResult };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * How {@link formatPhoneNumber} writes a number.
2
+ * How {@link formatPhone} writes a number.
3
3
  *
4
4
  * - `e164`: `+261341234567`
5
5
  * - `international`: `+261 34 12 345 67`
@@ -14,19 +14,19 @@ type PhoneNumberFormat = 'e164' | 'international' | 'national';
14
14
  /**
15
15
  * Writes a Malagasy mobile number in a standard form.
16
16
  *
17
- * @param input - The number in any spelling accepted by {@link parsePhoneNumber}.
17
+ * @param input - The number in any spelling accepted by {@link parsePhone}.
18
18
  * @param format - `'e164'`, `'international'` or `'national'`.
19
19
  * @returns The formatted number.
20
20
  * @throws {@link MdgError} `INVALID_TYPE` for an unknown format, plus every error of
21
- * {@link parsePhoneNumber}.
21
+ * {@link parsePhone}.
22
22
  *
23
23
  * @example
24
24
  * ```ts
25
- * formatPhoneNumber('+261341234567', 'national'); // '034 12 345 67'
26
- * formatPhoneNumber('034 12 345 67', 'international'); // '+261 34 12 345 67'
25
+ * formatPhone('+261341234567', 'national'); // '034 12 345 67'
26
+ * formatPhone('034 12 345 67', 'international'); // '+261 34 12 345 67'
27
27
  * ```
28
28
  */
29
- declare function formatPhoneNumber(input: string, format: PhoneNumberFormat): string;
29
+ declare function formatPhone(input: string, format: PhoneNumberFormat): string;
30
30
 
31
31
  /** Identifier of a Malagasy mobile operator. */
32
32
  type OperatorId = 'orange' | 'airtel' | 'yas' | 'blueline';
@@ -35,7 +35,7 @@ type OperatorId = 'orange' | 'airtel' | 'yas' | 'blueline';
35
35
  *
36
36
  * @example
37
37
  * ```ts
38
- * OPERATOR_NAMES[parsePhoneNumber('034 12 345 67').operator]; // 'Yas Madagascar'
38
+ * OPERATOR_NAMES[parsePhone('034 12 345 67').operator]; // 'Yas Madagascar'
39
39
  * ```
40
40
  */
41
41
  declare const OPERATOR_NAMES: {
@@ -46,7 +46,7 @@ declare const OPERATOR_NAMES: {
46
46
  };
47
47
 
48
48
  /** Version of the shared spec this code was generated from. */
49
- declare const SPEC_VERSION = "0.6.0";
49
+ declare const SPEC_VERSION = "0.8.0";
50
50
  /**
51
51
  * Error code shared by every mdg-utils language port.
52
52
  *
@@ -61,7 +61,7 @@ type ErrorCode = 'INVALID_TYPE' | 'OUT_OF_RANGE' | 'INVALID_FORMAT' | 'UNKNOWN_O
61
61
  *
62
62
  * @example
63
63
  * ```ts
64
- * const result = safeParsePhoneNumber(input);
64
+ * const result = safeParsePhone(input);
65
65
  * if (result.success) console.log(result.data);
66
66
  * else console.log(result.error.code);
67
67
  * ```
@@ -79,7 +79,7 @@ type SafeParseResult<T> = {
79
79
  * @example
80
80
  * ```ts
81
81
  * try {
82
- * numberToWords(-1);
82
+ * spell(-1);
83
83
  * } catch (error) {
84
84
  * if (error instanceof MdgError && error.code === 'OUT_OF_RANGE') {
85
85
  * // handle it
@@ -113,11 +113,11 @@ declare class MdgError extends Error {
113
113
 
114
114
  declare const phoneNumberBrand: unique symbol;
115
115
  /**
116
- * A Malagasy mobile number that passed validation. Create it with {@link parsePhoneNumber}.
116
+ * A Malagasy mobile number that passed validation. Create it with {@link parsePhone}.
117
117
  *
118
118
  * @example
119
119
  * ```ts
120
- * const phone: PhoneNumber = parsePhoneNumber('034 12 345 67');
120
+ * const phone: PhoneNumber = parsePhone('034 12 345 67');
121
121
  * phone.e164; // '+261341234567'
122
122
  * ```
123
123
  */
@@ -139,11 +139,11 @@ interface PhoneNumber {
139
139
  *
140
140
  * @example
141
141
  * ```ts
142
- * const result = safeParsePhoneNumber('+261 34 12 345 67');
142
+ * const result = safeParsePhone('+261 34 12 345 67');
143
143
  * if (result.success) result.data.operator; // 'yas'
144
144
  * ```
145
145
  */
146
- declare function safeParsePhoneNumber(input: unknown): SafeParseResult<PhoneNumber>;
146
+ declare function safeParsePhone(input: unknown): SafeParseResult<PhoneNumber>;
147
147
  /**
148
148
  * Reads a Malagasy mobile number written in any common way.
149
149
  *
@@ -157,39 +157,39 @@ declare function safeParsePhoneNumber(input: unknown): SafeParseResult<PhoneNumb
157
157
  *
158
158
  * @example
159
159
  * ```ts
160
- * parsePhoneNumber('034 12 345 67');
160
+ * parsePhone('034 12 345 67');
161
161
  * // { e164: '+261341234567', nationalNumber: '341234567', operator: 'yas' }
162
162
  * ```
163
163
  */
164
- declare function parsePhoneNumber(input: string): PhoneNumber;
164
+ declare function parsePhone(input: string): PhoneNumber;
165
165
  /**
166
166
  * Reads a Malagasy mobile number, or gives `undefined` instead of throwing.
167
167
  *
168
- * Use {@link safeParsePhoneNumber} when you need to know why the input was rejected.
168
+ * Use {@link safeParsePhone} when you need to know why the input was rejected.
169
169
  *
170
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.
171
+ * @returns The {@link PhoneNumber}, or `undefined` when {@link parsePhone} would throw.
172
172
  *
173
173
  * @example
174
174
  * ```ts
175
- * tryParsePhoneNumber('034 12 345 67')?.operator; // 'yas'
176
- * tryParsePhoneNumber('031 12 345 67'); // undefined
175
+ * tryParsePhone('034 12 345 67')?.operator; // 'yas'
176
+ * tryParsePhone('031 12 345 67'); // undefined
177
177
  * ```
178
178
  */
179
- declare function tryParsePhoneNumber(input: unknown): PhoneNumber | undefined;
179
+ declare function tryParsePhone(input: unknown): PhoneNumber | undefined;
180
180
  /**
181
181
  * Tells whether the input is a valid Malagasy mobile number. Never throws.
182
182
  *
183
183
  * @param input - Any value.
184
- * @returns `true` when {@link parsePhoneNumber} would succeed.
184
+ * @returns `true` when {@link parsePhone} would succeed.
185
185
  *
186
186
  * @example
187
187
  * ```ts
188
- * isValidPhoneNumber('034 12 345 67'); // true
189
- * isValidPhoneNumber('031 12 345 67'); // false
188
+ * isValidPhone('034 12 345 67'); // true
189
+ * isValidPhone('031 12 345 67'); // false
190
190
  * ```
191
191
  */
192
- declare function isValidPhoneNumber(input: unknown): boolean;
192
+ declare function isValidPhone(input: unknown): boolean;
193
193
 
194
- export { MdgError, OPERATOR_NAMES, SPEC_VERSION, formatPhoneNumber, isValidPhoneNumber, parsePhoneNumber, safeParsePhoneNumber, tryParsePhoneNumber };
194
+ export { MdgError, OPERATOR_NAMES, SPEC_VERSION, formatPhone, isValidPhone, parsePhone, safeParsePhone, tryParsePhone };
195
195
  export type { ErrorCode, OperatorId, PhoneNumber, PhoneNumberFormat, SafeParseResult };
package/dist/index.js CHANGED
@@ -22,7 +22,7 @@ var OPERATOR_BY_PREFIX = /* @__PURE__ */ new Map([
22
22
  var OPERATOR_PREFIX_LENGTH = 2;
23
23
 
24
24
  // src/generated/errors.ts
25
- var SPEC_VERSION = "0.6.0";
25
+ var SPEC_VERSION = "0.8.0";
26
26
  var MdgError = class extends Error {
27
27
  /** Always `'MdgError'`. */
28
28
  name = "MdgError";
@@ -89,7 +89,7 @@ function readNationalNumber(input) {
89
89
  }
90
90
 
91
91
  // src/phone-number.ts
92
- function safeParsePhoneNumber(input) {
92
+ function safeParsePhone(input) {
93
93
  if (typeof input !== "string") return failure("INVALID_TYPE", "Expected the number as a string.");
94
94
  const national = readNationalNumber(input);
95
95
  if (!national.success) return national;
@@ -104,17 +104,17 @@ function safeParsePhoneNumber(input) {
104
104
  };
105
105
  return { success: true, data: phone };
106
106
  }
107
- function parsePhoneNumber(input) {
108
- const result = safeParsePhoneNumber(input);
107
+ function parsePhone(input) {
108
+ const result = safeParsePhone(input);
109
109
  if (!result.success) throw result.error;
110
110
  return result.data;
111
111
  }
112
- function tryParsePhoneNumber(input) {
113
- const result = safeParsePhoneNumber(input);
112
+ function tryParsePhone(input) {
113
+ const result = safeParsePhone(input);
114
114
  return result.success ? result.data : void 0;
115
115
  }
116
- function isValidPhoneNumber(input) {
117
- return safeParsePhoneNumber(input).success;
116
+ function isValidPhone(input) {
117
+ return safeParsePhone(input).success;
118
118
  }
119
119
 
120
120
  // src/format.ts
@@ -134,16 +134,16 @@ var FORMATTERS = {
134
134
  function isPhoneNumberFormat(value) {
135
135
  return PHONE_NUMBER_FORMATS.some((format) => format === value);
136
136
  }
137
- function formatPhoneNumber(input, format) {
137
+ function formatPhone(input, format) {
138
138
  if (!isPhoneNumberFormat(format)) {
139
139
  throw new MdgError(
140
140
  "INVALID_TYPE",
141
141
  `Format must be one of: ${PHONE_NUMBER_FORMATS.join(", ")}.`
142
142
  );
143
143
  }
144
- return FORMATTERS[format](parsePhoneNumber(input).nationalNumber);
144
+ return FORMATTERS[format](parsePhone(input).nationalNumber);
145
145
  }
146
146
 
147
- export { MdgError, OPERATOR_NAMES, SPEC_VERSION, formatPhoneNumber, isValidPhoneNumber, parsePhoneNumber, safeParsePhoneNumber, tryParsePhoneNumber };
147
+ export { MdgError, OPERATOR_NAMES, SPEC_VERSION, formatPhone, isValidPhone, parsePhone, safeParsePhone, tryParsePhone };
148
148
  //# sourceMappingURL=index.js.map
149
149
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +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,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AAA,EAAO,KAAA,GAAQ,IAAI,CAAC,CAAA;AAC1C,CAAA,EAAG,EAAE,CAAA;AAEL,SAAS,YAAY,cAAA,EAAgC;AACnD,EAAA,OAAO,YAAA,CAAa,GAAA,CAAI,CAAC,CAAC,OAAO,GAAG,CAAA,KAAM,cAAA,CAAe,KAAA,CAAM,KAAA,EAAO,GAAG,CAAC,CAAA,CAAE,KAAK,GAAG,CAAA;AACtF;AAEA,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.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"]}
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,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,cAAA,EAAgC;AACnD,EAAA,OAAO,YAAA,CAAa,GAAA,CAAI,CAAC,CAAC,OAAO,GAAG,CAAA,KAAM,cAAA,CAAe,KAAA,CAAM,KAAA,EAAO,GAAG,CAAC,CAAA,CAAE,KAAK,GAAG,CAAA;AACtF;AAEA,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,WAAA,CAAY,OAAe,MAAA,EAAmC;AAC5E,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,UAAA,CAAW,KAAK,EAAE,cAAc,CAAA;AAC5D","file":"index.js","sourcesContent":["// GENERATED — edit spec/ instead. Run `just codegen` to refresh.\n\n// From spec/modules/phone/data.yaml, spec 0.8.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[parsePhone('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.8.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 = safeParsePhone(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 * spell(-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 parsePhone}.\n *\n * @example\n * ```ts\n * const phone: PhoneNumber = parsePhone('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 = safeParsePhone('+261 34 12 345 67');\n * if (result.success) result.data.operator; // 'yas'\n * ```\n */\nexport function safeParsePhone(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 * parsePhone('034 12 345 67');\n * // { e164: '+261341234567', nationalNumber: '341234567', operator: 'yas' }\n * ```\n */\nexport function parsePhone(input: string): PhoneNumber {\n const result = safeParsePhone(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 safeParsePhone} 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 parsePhone} would throw.\n *\n * @example\n * ```ts\n * tryParsePhone('034 12 345 67')?.operator; // 'yas'\n * tryParsePhone('031 12 345 67'); // undefined\n * ```\n */\nexport function tryParsePhone(input: unknown): PhoneNumber | undefined {\n const result = safeParsePhone(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 parsePhone} would succeed.\n *\n * @example\n * ```ts\n * isValidPhone('034 12 345 67'); // true\n * isValidPhone('031 12 345 67'); // false\n * ```\n */\nexport function isValidPhone(input: unknown): boolean {\n return safeParsePhone(input).success;\n}\n","import { COUNTRY_CODE, GROUPING, TRUNK_PREFIX } from './generated/data.ts';\nimport { MdgError } from './generated/errors.ts';\nimport { parsePhone } from './phone-number.ts';\n\n/**\n * How {@link formatPhone} 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 parsePhone}.\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 parsePhone}.\n *\n * @example\n * ```ts\n * formatPhone('+261341234567', 'national'); // '034 12 345 67'\n * formatPhone('034 12 345 67', 'international'); // '+261 34 12 345 67'\n * ```\n */\nexport function formatPhone(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](parsePhone(input).nationalNumber);\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mdgascar/phone",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "description": "Parse, validate and format Madagascar (+261) mobile phone numbers.",
5
5
  "license": "MIT",
6
6
  "author": "Mdgascar contributors",