text-number-parser 0.1.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 Michael Three
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 ADDED
@@ -0,0 +1,155 @@
1
+ # text-number-parser
2
+
3
+ [![CI](https://github.com/michaelthreekiv/text-number-parser/actions/workflows/ci.yml/badge.svg)](https://github.com/michaelthreekiv/text-number-parser/actions/workflows/ci.yml)
4
+ [![npm version](https://img.shields.io/npm/v/text-number-parser)](https://www.npmjs.com/package/text-number-parser)
5
+
6
+ Parse localized Unicode number words into JavaScript `number` or `bigint` values.
7
+
8
+ ## Features
9
+
10
+ - TypeScript source with generated declaration files.
11
+ - Narrow public API with throwing and non-throwing parse functions.
12
+ - Unicode-aware tokenization and normalization.
13
+ - Parser modes for connector words and hyphenated input.
14
+ - Extensible lexicons for custom scale words and localization.
15
+ - Typed error objects for empty input, invalid tokens, and invalid number syntax.
16
+ - Vitest coverage for the public API.
17
+ - Tinybench suite for quick performance checks.
18
+
19
+ ## Installation
20
+
21
+ ```bash
22
+ npm install text-number-parser
23
+ ```
24
+
25
+ ## Usage
26
+
27
+ ```ts
28
+ import {
29
+ InvalidTokenError,
30
+ createParser,
31
+ parseTextNumber,
32
+ tryParseTextNumber,
33
+ } from "text-number-parser";
34
+
35
+ parseTextNumber("one hundred and twenty-one");
36
+ // 121
37
+
38
+ parseTextNumber("nine quadrillion nine trillion");
39
+ // 9009000000000000n
40
+
41
+ parseTextNumber("one hundred and one", { allowAnd: false });
42
+ // throws InvalidSyntaxError
43
+
44
+ const result = tryParseTextNumber("twenty hundred million cat");
45
+
46
+ if (!result.ok) {
47
+ console.error(result.error.code, result.error.message);
48
+ }
49
+
50
+ try {
51
+ parseTextNumber("two cats");
52
+ } catch (error) {
53
+ if (error instanceof InvalidTokenError) {
54
+ console.error(error.token, error.index);
55
+ }
56
+ }
57
+
58
+ const indianParser = createParser({
59
+ extendLexicon: [
60
+ { word: "dozen", type: "multiplier", value: 12 },
61
+ { word: "lakh", type: "multiplier", value: 100_000 },
62
+ { word: "crore", type: "multiplier", value: 10_000_000 },
63
+ ],
64
+ });
65
+
66
+ indianParser.parse("three crore five lakh");
67
+ // 30500000
68
+
69
+ const spanishParser = createParser({
70
+ lexicon: [{ word: "veintidós", type: "number", value: 22, cls: "teen" }],
71
+ locale: "es",
72
+ normalization: "NFC",
73
+ });
74
+
75
+ spanishParser.parse("VEINTIDO\u0301S");
76
+ // 22
77
+ ```
78
+
79
+ ## Public API
80
+
81
+ ### parseTextNumber(input, modes?)
82
+
83
+ Parses an English number phrase and returns either a `number` or a `bigint` when the value exceeds `Number.MAX_SAFE_INTEGER`.
84
+
85
+ Supported modes:
86
+
87
+ ```ts
88
+ type ParserModes = {
89
+ allowAnd?: boolean;
90
+ allowHyphen?: boolean;
91
+ };
92
+ ```
93
+
94
+ ### tryParseTextNumber(input, modes?)
95
+
96
+ Returns a discriminated union:
97
+
98
+ ```ts
99
+ type ParseResult =
100
+ | { ok: true; value: number | bigint }
101
+ | { ok: false; error: TextNumberError };
102
+ ```
103
+
104
+ ### createParser(options)
105
+
106
+ Builds an isolated parser instance with its own lexicon, default modes, locale-aware lowercasing, and Unicode normalization strategy.
107
+
108
+ ```ts
109
+ type CreateParserOptions = {
110
+ lexicon?: Iterable<LexiconEntry>;
111
+ extendLexicon?: Iterable<LexiconEntry>;
112
+ locale?: string | string[];
113
+ normalization?: "NFC" | "NFD" | "NFKC" | "NFKD" | false;
114
+ modes?: ParserModes;
115
+ };
116
+ ```
117
+
118
+ ### englishLexicon
119
+
120
+ Readonly default English lexicon used by the top-level parser.
121
+
122
+ ### Error classes
123
+
124
+ - `TextNumberError`
125
+ - `EmptyInputError`
126
+ - `InvalidTokenError`
127
+ - `InvalidSyntaxError`
128
+
129
+ Each error carries the original input. Token and syntax errors also expose the offending token and character index.
130
+
131
+ ## Supported language rules
132
+
133
+ - Units: `zero` through `nine`
134
+ - Teens: `ten` through `nineteen`
135
+ - Tens: `twenty` through `ninety`
136
+ - Multipliers: `hundred`, `thousand`, `million`, `billion`, `trillion`, `quadrillion`
137
+ - Optional filler: `and`
138
+ - Optional sign prefix: `minus`, `negative`
139
+ - Hyphenated inputs are accepted by default and can be disabled with `allowHyphen: false`
140
+ - Connector words can be disabled with `allowAnd: false`
141
+
142
+ ## Extensibility
143
+
144
+ - Use `extendLexicon` to add new words such as `dozen`, `lakh`, and `crore`.
145
+ - Use `lexicon` to replace the default dictionary entirely for localization.
146
+ - Unicode words are normalized before lookup, so composed and decomposed forms can resolve to the same entry.
147
+
148
+ ## Development
149
+
150
+ ```bash
151
+ npm install
152
+ npm run build
153
+ npm test
154
+ npm run bench
155
+ ```
package/dist/index.cjs ADDED
@@ -0,0 +1,344 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ EmptyInputError: () => EmptyInputError,
24
+ InvalidSyntaxError: () => InvalidSyntaxError,
25
+ InvalidTokenError: () => InvalidTokenError,
26
+ TextNumberError: () => TextNumberError,
27
+ createParser: () => createParser,
28
+ englishLexicon: () => englishLexicon,
29
+ isTextNumberError: () => isTextNumberError,
30
+ parseTextNumber: () => parseTextNumber,
31
+ tryParseTextNumber: () => tryParseTextNumber
32
+ });
33
+ module.exports = __toCommonJS(index_exports);
34
+
35
+ // src/errors.ts
36
+ var TextNumberError = class extends Error {
37
+ code;
38
+ input;
39
+ constructor(code, message, input) {
40
+ super(message);
41
+ this.name = "TextNumberError";
42
+ this.code = code;
43
+ this.input = input;
44
+ }
45
+ };
46
+ var EmptyInputError = class extends TextNumberError {
47
+ constructor(input) {
48
+ super("EMPTY_INPUT", "Input does not contain any number words.", input);
49
+ this.name = "EmptyInputError";
50
+ }
51
+ };
52
+ var InvalidTokenError = class extends TextNumberError {
53
+ token;
54
+ index;
55
+ constructor(input, token, index) {
56
+ super(
57
+ "INVALID_TOKEN",
58
+ `Unknown number word "${token}" at index ${index}.`,
59
+ input
60
+ );
61
+ this.name = "InvalidTokenError";
62
+ this.token = token;
63
+ this.index = index;
64
+ }
65
+ };
66
+ var InvalidSyntaxError = class extends TextNumberError {
67
+ token;
68
+ index;
69
+ reason;
70
+ constructor(input, token, index, reason) {
71
+ super(
72
+ "INVALID_SYNTAX",
73
+ `${reason} Problematic token "${token}" at index ${index}.`,
74
+ input
75
+ );
76
+ this.name = "InvalidSyntaxError";
77
+ this.token = token;
78
+ this.index = index;
79
+ this.reason = reason;
80
+ }
81
+ };
82
+ function isTextNumberError(error) {
83
+ return error instanceof TextNumberError;
84
+ }
85
+
86
+ // src/parser.ts
87
+ var MAX_SAFE_BIGINT = BigInt(Number.MAX_SAFE_INTEGER);
88
+ var DEFAULT_MODES = {
89
+ allowAnd: true,
90
+ allowHyphen: true
91
+ };
92
+ var WORD_PATTERN = /[\p{L}\p{M}]+/gu;
93
+ var HYPHENATED_WORD_PATTERN = /[\p{L}\p{M}](?:[\p{Pd}\u2212])[\p{L}\p{M}]/u;
94
+ var englishLexicon = [
95
+ { word: "zero", type: "number", value: 0, cls: "unit" },
96
+ { word: "one", type: "number", value: 1, cls: "unit" },
97
+ { word: "two", type: "number", value: 2, cls: "unit" },
98
+ { word: "three", type: "number", value: 3, cls: "unit" },
99
+ { word: "four", type: "number", value: 4, cls: "unit" },
100
+ { word: "five", type: "number", value: 5, cls: "unit" },
101
+ { word: "six", type: "number", value: 6, cls: "unit" },
102
+ { word: "seven", type: "number", value: 7, cls: "unit" },
103
+ { word: "eight", type: "number", value: 8, cls: "unit" },
104
+ { word: "nine", type: "number", value: 9, cls: "unit" },
105
+ { word: "ten", type: "number", value: 10, cls: "teen" },
106
+ { word: "eleven", type: "number", value: 11, cls: "teen" },
107
+ { word: "twelve", type: "number", value: 12, cls: "teen" },
108
+ { word: "thirteen", type: "number", value: 13, cls: "teen" },
109
+ { word: "fourteen", type: "number", value: 14, cls: "teen" },
110
+ { word: "fifteen", type: "number", value: 15, cls: "teen" },
111
+ { word: "sixteen", type: "number", value: 16, cls: "teen" },
112
+ { word: "seventeen", type: "number", value: 17, cls: "teen" },
113
+ { word: "eighteen", type: "number", value: 18, cls: "teen" },
114
+ { word: "nineteen", type: "number", value: 19, cls: "teen" },
115
+ { word: "twenty", type: "number", value: 20, cls: "tens" },
116
+ { word: "thirty", type: "number", value: 30, cls: "tens" },
117
+ { word: "forty", type: "number", value: 40, cls: "tens" },
118
+ { word: "fifty", type: "number", value: 50, cls: "tens" },
119
+ { word: "sixty", type: "number", value: 60, cls: "tens" },
120
+ { word: "seventy", type: "number", value: 70, cls: "tens" },
121
+ { word: "eighty", type: "number", value: 80, cls: "tens" },
122
+ { word: "ninety", type: "number", value: 90, cls: "tens" },
123
+ { word: "hundred", type: "hundred", value: 100 },
124
+ { word: "thousand", type: "multiplier", value: 1e3 },
125
+ { word: "million", type: "multiplier", value: 1e6 },
126
+ { word: "billion", type: "multiplier", value: 1e9 },
127
+ { word: "trillion", type: "multiplier", value: 1e12 },
128
+ { word: "quadrillion", type: "multiplier", value: 1e15 },
129
+ { word: "minus", type: "sign", value: -1 },
130
+ { word: "negative", type: "sign", value: -1 },
131
+ { word: "and", type: "none", requiresMode: "allowAnd" }
132
+ ];
133
+ function normalizeWord(word, locale, normalization) {
134
+ const normalized = normalization ? word.normalize(normalization) : word;
135
+ return locale === void 0 ? normalized.toLowerCase() : normalized.toLocaleLowerCase(locale);
136
+ }
137
+ function resolveModes(baseModes, overrideModes) {
138
+ return {
139
+ allowAnd: overrideModes?.allowAnd ?? baseModes.allowAnd,
140
+ allowHyphen: overrideModes?.allowHyphen ?? baseModes.allowHyphen
141
+ };
142
+ }
143
+ function toResolvedEntry(entry, normalizer) {
144
+ return {
145
+ word: entry.word,
146
+ normalizedWord: normalizer(entry.word),
147
+ type: entry.type,
148
+ value: BigInt(entry.value ?? 0),
149
+ cls: entry.cls ?? "none",
150
+ requiresMode: entry.requiresMode
151
+ };
152
+ }
153
+ function createLexiconMap(entries, normalizer) {
154
+ const lexicon = /* @__PURE__ */ new Map();
155
+ for (const entry of entries) {
156
+ const resolvedEntry = toResolvedEntry(entry, normalizer);
157
+ lexicon.set(resolvedEntry.normalizedWord, resolvedEntry);
158
+ }
159
+ return lexicon;
160
+ }
161
+ function invalidSyntax(input, token, reason) {
162
+ throw new InvalidSyntaxError(input, token.word, token.index, reason);
163
+ }
164
+ function toOutput(value) {
165
+ if (value <= MAX_SAFE_BIGINT && value >= -MAX_SAFE_BIGINT) {
166
+ return Number(value);
167
+ }
168
+ return value;
169
+ }
170
+ function tokenize(input, modes, normalizer) {
171
+ if (!modes.allowHyphen) {
172
+ const hyphenatedWord = input.match(HYPHENATED_WORD_PATTERN);
173
+ if (hyphenatedWord) {
174
+ throw new InvalidSyntaxError(
175
+ input,
176
+ hyphenatedWord[0],
177
+ hyphenatedWord.index ?? 0,
178
+ "Hyphenated words are disabled in the current parser mode."
179
+ );
180
+ }
181
+ }
182
+ const tokens = [];
183
+ for (const match of input.matchAll(WORD_PATTERN)) {
184
+ tokens.push({
185
+ word: normalizer(match[0]),
186
+ index: match.index ?? 0
187
+ });
188
+ }
189
+ return tokens;
190
+ }
191
+ function parseWithLexicon(input, lexicon, modes, normalizer) {
192
+ const tokens = tokenize(input, modes, normalizer);
193
+ if (tokens.length === 0) {
194
+ throw new EmptyInputError(input);
195
+ }
196
+ let total = 0n;
197
+ let group = 0n;
198
+ let sign = 1n;
199
+ let signUsed = false;
200
+ let hasValue = false;
201
+ let usedHundred = false;
202
+ let lastClass = "none";
203
+ let lastMultiplier = null;
204
+ for (const token of tokens) {
205
+ const definition = lexicon.get(token.word);
206
+ if (!definition) {
207
+ throw new InvalidTokenError(input, token.word, token.index);
208
+ }
209
+ if (definition.requiresMode && !modes[definition.requiresMode]) {
210
+ invalidSyntax(
211
+ input,
212
+ token,
213
+ `Token "${token.word}" is disabled in the current parser mode.`
214
+ );
215
+ }
216
+ switch (definition.type) {
217
+ case "sign": {
218
+ if (signUsed || hasValue) {
219
+ invalidSyntax(input, token, "Sign words are only allowed before the number.");
220
+ }
221
+ signUsed = true;
222
+ sign = definition.value;
223
+ break;
224
+ }
225
+ case "none": {
226
+ break;
227
+ }
228
+ case "number": {
229
+ if (lastClass === "unit" && definition.cls === "unit") {
230
+ invalidSyntax(input, token, "Two unit words cannot appear next to each other.");
231
+ }
232
+ if ((lastClass === "teen" || definition.cls === "teen") && lastClass !== "none") {
233
+ invalidSyntax(input, token, "Teen words must stand on their own within a group.");
234
+ }
235
+ if (lastClass === "tens" && definition.cls !== "unit") {
236
+ invalidSyntax(input, token, "A tens word can only be followed by a unit word.");
237
+ }
238
+ if (definition.cls === "tens" && lastClass !== "none") {
239
+ invalidSyntax(input, token, "A tens word must start a new group fragment.");
240
+ }
241
+ group += definition.value;
242
+ hasValue = true;
243
+ lastClass = definition.cls;
244
+ break;
245
+ }
246
+ case "hundred": {
247
+ if (group === 0n || usedHundred) {
248
+ invalidSyntax(
249
+ input,
250
+ token,
251
+ "Hundred requires a leading number and may only be used once per group."
252
+ );
253
+ }
254
+ group *= definition.value;
255
+ hasValue = true;
256
+ usedHundred = true;
257
+ lastClass = "none";
258
+ break;
259
+ }
260
+ case "multiplier": {
261
+ if (group === 0n) {
262
+ invalidSyntax(input, token, "Large multipliers require a leading group value.");
263
+ }
264
+ if (lastMultiplier !== null && definition.value >= lastMultiplier) {
265
+ invalidSyntax(input, token, "Large multipliers must appear in descending order.");
266
+ }
267
+ total += group * definition.value;
268
+ group = 0n;
269
+ hasValue = true;
270
+ usedHundred = false;
271
+ lastClass = "none";
272
+ lastMultiplier = definition.value;
273
+ break;
274
+ }
275
+ }
276
+ }
277
+ if (!hasValue) {
278
+ const lastToken = tokens.at(-1);
279
+ invalidSyntax(input, lastToken, "Input did not contain a numeric value.");
280
+ }
281
+ return toOutput((total + group) * sign);
282
+ }
283
+ function createParser(options = {}) {
284
+ const normalization = options.normalization ?? "NFKC";
285
+ const locale = options.locale;
286
+ const normalizer = (word) => normalizeWord(word, locale, normalization);
287
+ const lexicon = createLexiconMap(options.lexicon ?? englishLexicon, normalizer);
288
+ for (const entry of options.extendLexicon ?? []) {
289
+ const resolvedEntry = toResolvedEntry(entry, normalizer);
290
+ lexicon.set(resolvedEntry.normalizedWord, resolvedEntry);
291
+ }
292
+ const defaultModes = resolveModes(DEFAULT_MODES, options.modes);
293
+ const parse = (input, modes) => {
294
+ if (typeof input !== "string") {
295
+ throw new TypeError("parseTextNumber expects a string input.");
296
+ }
297
+ return parseWithLexicon(input, lexicon, resolveModes(defaultModes, modes), normalizer);
298
+ };
299
+ const tryParse = (input, modes) => {
300
+ try {
301
+ return {
302
+ ok: true,
303
+ value: parse(input, modes)
304
+ };
305
+ } catch (error) {
306
+ if (isTextNumberError(error)) {
307
+ return {
308
+ ok: false,
309
+ error
310
+ };
311
+ }
312
+ throw error;
313
+ }
314
+ };
315
+ return {
316
+ parse,
317
+ tryParse,
318
+ lexicon,
319
+ locale,
320
+ normalization,
321
+ modes: defaultModes
322
+ };
323
+ }
324
+
325
+ // src/index.ts
326
+ var defaultParser = createParser();
327
+ function parseTextNumber(input, modes) {
328
+ return defaultParser.parse(input, modes);
329
+ }
330
+ function tryParseTextNumber(input, modes) {
331
+ return defaultParser.tryParse(input, modes);
332
+ }
333
+ // Annotate the CommonJS export names for ESM import in node:
334
+ 0 && (module.exports = {
335
+ EmptyInputError,
336
+ InvalidSyntaxError,
337
+ InvalidTokenError,
338
+ TextNumberError,
339
+ createParser,
340
+ englishLexicon,
341
+ isTextNumberError,
342
+ parseTextNumber,
343
+ tryParseTextNumber
344
+ });
@@ -0,0 +1,257 @@
1
+ type TextNumberErrorCode = "EMPTY_INPUT" | "INVALID_TOKEN" | "INVALID_SYNTAX";
2
+ declare class TextNumberError extends Error {
3
+ readonly code: TextNumberErrorCode;
4
+ readonly input: string;
5
+ constructor(code: TextNumberErrorCode, message: string, input: string);
6
+ }
7
+ declare class EmptyInputError extends TextNumberError {
8
+ constructor(input: string);
9
+ }
10
+ declare class InvalidTokenError extends TextNumberError {
11
+ readonly token: string;
12
+ readonly index: number;
13
+ constructor(input: string, token: string, index: number);
14
+ }
15
+ declare class InvalidSyntaxError extends TextNumberError {
16
+ readonly token: string;
17
+ readonly index: number;
18
+ readonly reason: string;
19
+ constructor(input: string, token: string, index: number, reason: string);
20
+ }
21
+ declare function isTextNumberError(error: unknown): error is TextNumberError;
22
+
23
+ type ParsedNumber = bigint | number;
24
+ type LexiconTokenType = "none" | "sign" | "number" | "hundred" | "multiplier";
25
+ type LexiconTokenClass = "none" | "unit" | "teen" | "tens";
26
+ type TextNormalizationForm = "NFC" | "NFD" | "NFKC" | "NFKD";
27
+ type ParserModeName = "allowAnd" | "allowHyphen";
28
+ interface ParserModes {
29
+ allowAnd?: boolean;
30
+ allowHyphen?: boolean;
31
+ }
32
+ interface LexiconEntry {
33
+ word: string;
34
+ type: LexiconTokenType;
35
+ value?: number | bigint;
36
+ cls?: LexiconTokenClass;
37
+ requiresMode?: Extract<ParserModeName, "allowAnd">;
38
+ }
39
+ interface CreateParserOptions {
40
+ lexicon?: Iterable<LexiconEntry>;
41
+ extendLexicon?: Iterable<LexiconEntry>;
42
+ locale?: Intl.LocalesArgument;
43
+ normalization?: TextNormalizationForm | false;
44
+ modes?: ParserModes;
45
+ }
46
+ type ParseSuccess = {
47
+ ok: true;
48
+ value: ParsedNumber;
49
+ };
50
+ type ParseFailure = {
51
+ ok: false;
52
+ error: TextNumberError;
53
+ };
54
+ type ParseResult = ParseSuccess | ParseFailure;
55
+ interface TextNumberParser {
56
+ parse(input: string, modes?: ParserModes): ParsedNumber;
57
+ tryParse(input: string, modes?: ParserModes): ParseResult;
58
+ readonly lexicon: ReadonlyMap<string, Readonly<ResolvedLexiconEntry>>;
59
+ readonly locale?: Intl.LocalesArgument;
60
+ readonly normalization: TextNormalizationForm | false;
61
+ readonly modes: Readonly<ResolvedParserModes>;
62
+ }
63
+ interface ResolvedLexiconEntry {
64
+ word: string;
65
+ normalizedWord: string;
66
+ type: LexiconTokenType;
67
+ value: bigint;
68
+ cls: LexiconTokenClass;
69
+ requiresMode?: Extract<ParserModeName, "allowAnd">;
70
+ }
71
+ interface ResolvedParserModes {
72
+ allowAnd: boolean;
73
+ allowHyphen: boolean;
74
+ }
75
+ declare const englishLexicon: readonly [{
76
+ readonly word: "zero";
77
+ readonly type: "number";
78
+ readonly value: 0;
79
+ readonly cls: "unit";
80
+ }, {
81
+ readonly word: "one";
82
+ readonly type: "number";
83
+ readonly value: 1;
84
+ readonly cls: "unit";
85
+ }, {
86
+ readonly word: "two";
87
+ readonly type: "number";
88
+ readonly value: 2;
89
+ readonly cls: "unit";
90
+ }, {
91
+ readonly word: "three";
92
+ readonly type: "number";
93
+ readonly value: 3;
94
+ readonly cls: "unit";
95
+ }, {
96
+ readonly word: "four";
97
+ readonly type: "number";
98
+ readonly value: 4;
99
+ readonly cls: "unit";
100
+ }, {
101
+ readonly word: "five";
102
+ readonly type: "number";
103
+ readonly value: 5;
104
+ readonly cls: "unit";
105
+ }, {
106
+ readonly word: "six";
107
+ readonly type: "number";
108
+ readonly value: 6;
109
+ readonly cls: "unit";
110
+ }, {
111
+ readonly word: "seven";
112
+ readonly type: "number";
113
+ readonly value: 7;
114
+ readonly cls: "unit";
115
+ }, {
116
+ readonly word: "eight";
117
+ readonly type: "number";
118
+ readonly value: 8;
119
+ readonly cls: "unit";
120
+ }, {
121
+ readonly word: "nine";
122
+ readonly type: "number";
123
+ readonly value: 9;
124
+ readonly cls: "unit";
125
+ }, {
126
+ readonly word: "ten";
127
+ readonly type: "number";
128
+ readonly value: 10;
129
+ readonly cls: "teen";
130
+ }, {
131
+ readonly word: "eleven";
132
+ readonly type: "number";
133
+ readonly value: 11;
134
+ readonly cls: "teen";
135
+ }, {
136
+ readonly word: "twelve";
137
+ readonly type: "number";
138
+ readonly value: 12;
139
+ readonly cls: "teen";
140
+ }, {
141
+ readonly word: "thirteen";
142
+ readonly type: "number";
143
+ readonly value: 13;
144
+ readonly cls: "teen";
145
+ }, {
146
+ readonly word: "fourteen";
147
+ readonly type: "number";
148
+ readonly value: 14;
149
+ readonly cls: "teen";
150
+ }, {
151
+ readonly word: "fifteen";
152
+ readonly type: "number";
153
+ readonly value: 15;
154
+ readonly cls: "teen";
155
+ }, {
156
+ readonly word: "sixteen";
157
+ readonly type: "number";
158
+ readonly value: 16;
159
+ readonly cls: "teen";
160
+ }, {
161
+ readonly word: "seventeen";
162
+ readonly type: "number";
163
+ readonly value: 17;
164
+ readonly cls: "teen";
165
+ }, {
166
+ readonly word: "eighteen";
167
+ readonly type: "number";
168
+ readonly value: 18;
169
+ readonly cls: "teen";
170
+ }, {
171
+ readonly word: "nineteen";
172
+ readonly type: "number";
173
+ readonly value: 19;
174
+ readonly cls: "teen";
175
+ }, {
176
+ readonly word: "twenty";
177
+ readonly type: "number";
178
+ readonly value: 20;
179
+ readonly cls: "tens";
180
+ }, {
181
+ readonly word: "thirty";
182
+ readonly type: "number";
183
+ readonly value: 30;
184
+ readonly cls: "tens";
185
+ }, {
186
+ readonly word: "forty";
187
+ readonly type: "number";
188
+ readonly value: 40;
189
+ readonly cls: "tens";
190
+ }, {
191
+ readonly word: "fifty";
192
+ readonly type: "number";
193
+ readonly value: 50;
194
+ readonly cls: "tens";
195
+ }, {
196
+ readonly word: "sixty";
197
+ readonly type: "number";
198
+ readonly value: 60;
199
+ readonly cls: "tens";
200
+ }, {
201
+ readonly word: "seventy";
202
+ readonly type: "number";
203
+ readonly value: 70;
204
+ readonly cls: "tens";
205
+ }, {
206
+ readonly word: "eighty";
207
+ readonly type: "number";
208
+ readonly value: 80;
209
+ readonly cls: "tens";
210
+ }, {
211
+ readonly word: "ninety";
212
+ readonly type: "number";
213
+ readonly value: 90;
214
+ readonly cls: "tens";
215
+ }, {
216
+ readonly word: "hundred";
217
+ readonly type: "hundred";
218
+ readonly value: 100;
219
+ }, {
220
+ readonly word: "thousand";
221
+ readonly type: "multiplier";
222
+ readonly value: 1000;
223
+ }, {
224
+ readonly word: "million";
225
+ readonly type: "multiplier";
226
+ readonly value: 1000000;
227
+ }, {
228
+ readonly word: "billion";
229
+ readonly type: "multiplier";
230
+ readonly value: 1000000000;
231
+ }, {
232
+ readonly word: "trillion";
233
+ readonly type: "multiplier";
234
+ readonly value: 1000000000000;
235
+ }, {
236
+ readonly word: "quadrillion";
237
+ readonly type: "multiplier";
238
+ readonly value: 1000000000000000;
239
+ }, {
240
+ readonly word: "minus";
241
+ readonly type: "sign";
242
+ readonly value: -1;
243
+ }, {
244
+ readonly word: "negative";
245
+ readonly type: "sign";
246
+ readonly value: -1;
247
+ }, {
248
+ readonly word: "and";
249
+ readonly type: "none";
250
+ readonly requiresMode: "allowAnd";
251
+ }];
252
+ declare function createParser(options?: CreateParserOptions): TextNumberParser;
253
+
254
+ declare function parseTextNumber(input: string, modes?: ParserModes): ParsedNumber;
255
+ declare function tryParseTextNumber(input: string, modes?: ParserModes): ParseResult;
256
+
257
+ export { type CreateParserOptions, EmptyInputError, InvalidSyntaxError, InvalidTokenError, type LexiconEntry, type LexiconTokenClass, type LexiconTokenType, type ParseFailure, type ParseResult, type ParseSuccess, type ParsedNumber, type ParserModeName, type ParserModes, type TextNormalizationForm, TextNumberError, type TextNumberParser, createParser, englishLexicon, isTextNumberError, parseTextNumber, tryParseTextNumber };
@@ -0,0 +1,257 @@
1
+ type TextNumberErrorCode = "EMPTY_INPUT" | "INVALID_TOKEN" | "INVALID_SYNTAX";
2
+ declare class TextNumberError extends Error {
3
+ readonly code: TextNumberErrorCode;
4
+ readonly input: string;
5
+ constructor(code: TextNumberErrorCode, message: string, input: string);
6
+ }
7
+ declare class EmptyInputError extends TextNumberError {
8
+ constructor(input: string);
9
+ }
10
+ declare class InvalidTokenError extends TextNumberError {
11
+ readonly token: string;
12
+ readonly index: number;
13
+ constructor(input: string, token: string, index: number);
14
+ }
15
+ declare class InvalidSyntaxError extends TextNumberError {
16
+ readonly token: string;
17
+ readonly index: number;
18
+ readonly reason: string;
19
+ constructor(input: string, token: string, index: number, reason: string);
20
+ }
21
+ declare function isTextNumberError(error: unknown): error is TextNumberError;
22
+
23
+ type ParsedNumber = bigint | number;
24
+ type LexiconTokenType = "none" | "sign" | "number" | "hundred" | "multiplier";
25
+ type LexiconTokenClass = "none" | "unit" | "teen" | "tens";
26
+ type TextNormalizationForm = "NFC" | "NFD" | "NFKC" | "NFKD";
27
+ type ParserModeName = "allowAnd" | "allowHyphen";
28
+ interface ParserModes {
29
+ allowAnd?: boolean;
30
+ allowHyphen?: boolean;
31
+ }
32
+ interface LexiconEntry {
33
+ word: string;
34
+ type: LexiconTokenType;
35
+ value?: number | bigint;
36
+ cls?: LexiconTokenClass;
37
+ requiresMode?: Extract<ParserModeName, "allowAnd">;
38
+ }
39
+ interface CreateParserOptions {
40
+ lexicon?: Iterable<LexiconEntry>;
41
+ extendLexicon?: Iterable<LexiconEntry>;
42
+ locale?: Intl.LocalesArgument;
43
+ normalization?: TextNormalizationForm | false;
44
+ modes?: ParserModes;
45
+ }
46
+ type ParseSuccess = {
47
+ ok: true;
48
+ value: ParsedNumber;
49
+ };
50
+ type ParseFailure = {
51
+ ok: false;
52
+ error: TextNumberError;
53
+ };
54
+ type ParseResult = ParseSuccess | ParseFailure;
55
+ interface TextNumberParser {
56
+ parse(input: string, modes?: ParserModes): ParsedNumber;
57
+ tryParse(input: string, modes?: ParserModes): ParseResult;
58
+ readonly lexicon: ReadonlyMap<string, Readonly<ResolvedLexiconEntry>>;
59
+ readonly locale?: Intl.LocalesArgument;
60
+ readonly normalization: TextNormalizationForm | false;
61
+ readonly modes: Readonly<ResolvedParserModes>;
62
+ }
63
+ interface ResolvedLexiconEntry {
64
+ word: string;
65
+ normalizedWord: string;
66
+ type: LexiconTokenType;
67
+ value: bigint;
68
+ cls: LexiconTokenClass;
69
+ requiresMode?: Extract<ParserModeName, "allowAnd">;
70
+ }
71
+ interface ResolvedParserModes {
72
+ allowAnd: boolean;
73
+ allowHyphen: boolean;
74
+ }
75
+ declare const englishLexicon: readonly [{
76
+ readonly word: "zero";
77
+ readonly type: "number";
78
+ readonly value: 0;
79
+ readonly cls: "unit";
80
+ }, {
81
+ readonly word: "one";
82
+ readonly type: "number";
83
+ readonly value: 1;
84
+ readonly cls: "unit";
85
+ }, {
86
+ readonly word: "two";
87
+ readonly type: "number";
88
+ readonly value: 2;
89
+ readonly cls: "unit";
90
+ }, {
91
+ readonly word: "three";
92
+ readonly type: "number";
93
+ readonly value: 3;
94
+ readonly cls: "unit";
95
+ }, {
96
+ readonly word: "four";
97
+ readonly type: "number";
98
+ readonly value: 4;
99
+ readonly cls: "unit";
100
+ }, {
101
+ readonly word: "five";
102
+ readonly type: "number";
103
+ readonly value: 5;
104
+ readonly cls: "unit";
105
+ }, {
106
+ readonly word: "six";
107
+ readonly type: "number";
108
+ readonly value: 6;
109
+ readonly cls: "unit";
110
+ }, {
111
+ readonly word: "seven";
112
+ readonly type: "number";
113
+ readonly value: 7;
114
+ readonly cls: "unit";
115
+ }, {
116
+ readonly word: "eight";
117
+ readonly type: "number";
118
+ readonly value: 8;
119
+ readonly cls: "unit";
120
+ }, {
121
+ readonly word: "nine";
122
+ readonly type: "number";
123
+ readonly value: 9;
124
+ readonly cls: "unit";
125
+ }, {
126
+ readonly word: "ten";
127
+ readonly type: "number";
128
+ readonly value: 10;
129
+ readonly cls: "teen";
130
+ }, {
131
+ readonly word: "eleven";
132
+ readonly type: "number";
133
+ readonly value: 11;
134
+ readonly cls: "teen";
135
+ }, {
136
+ readonly word: "twelve";
137
+ readonly type: "number";
138
+ readonly value: 12;
139
+ readonly cls: "teen";
140
+ }, {
141
+ readonly word: "thirteen";
142
+ readonly type: "number";
143
+ readonly value: 13;
144
+ readonly cls: "teen";
145
+ }, {
146
+ readonly word: "fourteen";
147
+ readonly type: "number";
148
+ readonly value: 14;
149
+ readonly cls: "teen";
150
+ }, {
151
+ readonly word: "fifteen";
152
+ readonly type: "number";
153
+ readonly value: 15;
154
+ readonly cls: "teen";
155
+ }, {
156
+ readonly word: "sixteen";
157
+ readonly type: "number";
158
+ readonly value: 16;
159
+ readonly cls: "teen";
160
+ }, {
161
+ readonly word: "seventeen";
162
+ readonly type: "number";
163
+ readonly value: 17;
164
+ readonly cls: "teen";
165
+ }, {
166
+ readonly word: "eighteen";
167
+ readonly type: "number";
168
+ readonly value: 18;
169
+ readonly cls: "teen";
170
+ }, {
171
+ readonly word: "nineteen";
172
+ readonly type: "number";
173
+ readonly value: 19;
174
+ readonly cls: "teen";
175
+ }, {
176
+ readonly word: "twenty";
177
+ readonly type: "number";
178
+ readonly value: 20;
179
+ readonly cls: "tens";
180
+ }, {
181
+ readonly word: "thirty";
182
+ readonly type: "number";
183
+ readonly value: 30;
184
+ readonly cls: "tens";
185
+ }, {
186
+ readonly word: "forty";
187
+ readonly type: "number";
188
+ readonly value: 40;
189
+ readonly cls: "tens";
190
+ }, {
191
+ readonly word: "fifty";
192
+ readonly type: "number";
193
+ readonly value: 50;
194
+ readonly cls: "tens";
195
+ }, {
196
+ readonly word: "sixty";
197
+ readonly type: "number";
198
+ readonly value: 60;
199
+ readonly cls: "tens";
200
+ }, {
201
+ readonly word: "seventy";
202
+ readonly type: "number";
203
+ readonly value: 70;
204
+ readonly cls: "tens";
205
+ }, {
206
+ readonly word: "eighty";
207
+ readonly type: "number";
208
+ readonly value: 80;
209
+ readonly cls: "tens";
210
+ }, {
211
+ readonly word: "ninety";
212
+ readonly type: "number";
213
+ readonly value: 90;
214
+ readonly cls: "tens";
215
+ }, {
216
+ readonly word: "hundred";
217
+ readonly type: "hundred";
218
+ readonly value: 100;
219
+ }, {
220
+ readonly word: "thousand";
221
+ readonly type: "multiplier";
222
+ readonly value: 1000;
223
+ }, {
224
+ readonly word: "million";
225
+ readonly type: "multiplier";
226
+ readonly value: 1000000;
227
+ }, {
228
+ readonly word: "billion";
229
+ readonly type: "multiplier";
230
+ readonly value: 1000000000;
231
+ }, {
232
+ readonly word: "trillion";
233
+ readonly type: "multiplier";
234
+ readonly value: 1000000000000;
235
+ }, {
236
+ readonly word: "quadrillion";
237
+ readonly type: "multiplier";
238
+ readonly value: 1000000000000000;
239
+ }, {
240
+ readonly word: "minus";
241
+ readonly type: "sign";
242
+ readonly value: -1;
243
+ }, {
244
+ readonly word: "negative";
245
+ readonly type: "sign";
246
+ readonly value: -1;
247
+ }, {
248
+ readonly word: "and";
249
+ readonly type: "none";
250
+ readonly requiresMode: "allowAnd";
251
+ }];
252
+ declare function createParser(options?: CreateParserOptions): TextNumberParser;
253
+
254
+ declare function parseTextNumber(input: string, modes?: ParserModes): ParsedNumber;
255
+ declare function tryParseTextNumber(input: string, modes?: ParserModes): ParseResult;
256
+
257
+ export { type CreateParserOptions, EmptyInputError, InvalidSyntaxError, InvalidTokenError, type LexiconEntry, type LexiconTokenClass, type LexiconTokenType, type ParseFailure, type ParseResult, type ParseSuccess, type ParsedNumber, type ParserModeName, type ParserModes, type TextNormalizationForm, TextNumberError, type TextNumberParser, createParser, englishLexicon, isTextNumberError, parseTextNumber, tryParseTextNumber };
package/dist/index.js ADDED
@@ -0,0 +1,309 @@
1
+ // src/errors.ts
2
+ var TextNumberError = class extends Error {
3
+ code;
4
+ input;
5
+ constructor(code, message, input) {
6
+ super(message);
7
+ this.name = "TextNumberError";
8
+ this.code = code;
9
+ this.input = input;
10
+ }
11
+ };
12
+ var EmptyInputError = class extends TextNumberError {
13
+ constructor(input) {
14
+ super("EMPTY_INPUT", "Input does not contain any number words.", input);
15
+ this.name = "EmptyInputError";
16
+ }
17
+ };
18
+ var InvalidTokenError = class extends TextNumberError {
19
+ token;
20
+ index;
21
+ constructor(input, token, index) {
22
+ super(
23
+ "INVALID_TOKEN",
24
+ `Unknown number word "${token}" at index ${index}.`,
25
+ input
26
+ );
27
+ this.name = "InvalidTokenError";
28
+ this.token = token;
29
+ this.index = index;
30
+ }
31
+ };
32
+ var InvalidSyntaxError = class extends TextNumberError {
33
+ token;
34
+ index;
35
+ reason;
36
+ constructor(input, token, index, reason) {
37
+ super(
38
+ "INVALID_SYNTAX",
39
+ `${reason} Problematic token "${token}" at index ${index}.`,
40
+ input
41
+ );
42
+ this.name = "InvalidSyntaxError";
43
+ this.token = token;
44
+ this.index = index;
45
+ this.reason = reason;
46
+ }
47
+ };
48
+ function isTextNumberError(error) {
49
+ return error instanceof TextNumberError;
50
+ }
51
+
52
+ // src/parser.ts
53
+ var MAX_SAFE_BIGINT = BigInt(Number.MAX_SAFE_INTEGER);
54
+ var DEFAULT_MODES = {
55
+ allowAnd: true,
56
+ allowHyphen: true
57
+ };
58
+ var WORD_PATTERN = /[\p{L}\p{M}]+/gu;
59
+ var HYPHENATED_WORD_PATTERN = /[\p{L}\p{M}](?:[\p{Pd}\u2212])[\p{L}\p{M}]/u;
60
+ var englishLexicon = [
61
+ { word: "zero", type: "number", value: 0, cls: "unit" },
62
+ { word: "one", type: "number", value: 1, cls: "unit" },
63
+ { word: "two", type: "number", value: 2, cls: "unit" },
64
+ { word: "three", type: "number", value: 3, cls: "unit" },
65
+ { word: "four", type: "number", value: 4, cls: "unit" },
66
+ { word: "five", type: "number", value: 5, cls: "unit" },
67
+ { word: "six", type: "number", value: 6, cls: "unit" },
68
+ { word: "seven", type: "number", value: 7, cls: "unit" },
69
+ { word: "eight", type: "number", value: 8, cls: "unit" },
70
+ { word: "nine", type: "number", value: 9, cls: "unit" },
71
+ { word: "ten", type: "number", value: 10, cls: "teen" },
72
+ { word: "eleven", type: "number", value: 11, cls: "teen" },
73
+ { word: "twelve", type: "number", value: 12, cls: "teen" },
74
+ { word: "thirteen", type: "number", value: 13, cls: "teen" },
75
+ { word: "fourteen", type: "number", value: 14, cls: "teen" },
76
+ { word: "fifteen", type: "number", value: 15, cls: "teen" },
77
+ { word: "sixteen", type: "number", value: 16, cls: "teen" },
78
+ { word: "seventeen", type: "number", value: 17, cls: "teen" },
79
+ { word: "eighteen", type: "number", value: 18, cls: "teen" },
80
+ { word: "nineteen", type: "number", value: 19, cls: "teen" },
81
+ { word: "twenty", type: "number", value: 20, cls: "tens" },
82
+ { word: "thirty", type: "number", value: 30, cls: "tens" },
83
+ { word: "forty", type: "number", value: 40, cls: "tens" },
84
+ { word: "fifty", type: "number", value: 50, cls: "tens" },
85
+ { word: "sixty", type: "number", value: 60, cls: "tens" },
86
+ { word: "seventy", type: "number", value: 70, cls: "tens" },
87
+ { word: "eighty", type: "number", value: 80, cls: "tens" },
88
+ { word: "ninety", type: "number", value: 90, cls: "tens" },
89
+ { word: "hundred", type: "hundred", value: 100 },
90
+ { word: "thousand", type: "multiplier", value: 1e3 },
91
+ { word: "million", type: "multiplier", value: 1e6 },
92
+ { word: "billion", type: "multiplier", value: 1e9 },
93
+ { word: "trillion", type: "multiplier", value: 1e12 },
94
+ { word: "quadrillion", type: "multiplier", value: 1e15 },
95
+ { word: "minus", type: "sign", value: -1 },
96
+ { word: "negative", type: "sign", value: -1 },
97
+ { word: "and", type: "none", requiresMode: "allowAnd" }
98
+ ];
99
+ function normalizeWord(word, locale, normalization) {
100
+ const normalized = normalization ? word.normalize(normalization) : word;
101
+ return locale === void 0 ? normalized.toLowerCase() : normalized.toLocaleLowerCase(locale);
102
+ }
103
+ function resolveModes(baseModes, overrideModes) {
104
+ return {
105
+ allowAnd: overrideModes?.allowAnd ?? baseModes.allowAnd,
106
+ allowHyphen: overrideModes?.allowHyphen ?? baseModes.allowHyphen
107
+ };
108
+ }
109
+ function toResolvedEntry(entry, normalizer) {
110
+ return {
111
+ word: entry.word,
112
+ normalizedWord: normalizer(entry.word),
113
+ type: entry.type,
114
+ value: BigInt(entry.value ?? 0),
115
+ cls: entry.cls ?? "none",
116
+ requiresMode: entry.requiresMode
117
+ };
118
+ }
119
+ function createLexiconMap(entries, normalizer) {
120
+ const lexicon = /* @__PURE__ */ new Map();
121
+ for (const entry of entries) {
122
+ const resolvedEntry = toResolvedEntry(entry, normalizer);
123
+ lexicon.set(resolvedEntry.normalizedWord, resolvedEntry);
124
+ }
125
+ return lexicon;
126
+ }
127
+ function invalidSyntax(input, token, reason) {
128
+ throw new InvalidSyntaxError(input, token.word, token.index, reason);
129
+ }
130
+ function toOutput(value) {
131
+ if (value <= MAX_SAFE_BIGINT && value >= -MAX_SAFE_BIGINT) {
132
+ return Number(value);
133
+ }
134
+ return value;
135
+ }
136
+ function tokenize(input, modes, normalizer) {
137
+ if (!modes.allowHyphen) {
138
+ const hyphenatedWord = input.match(HYPHENATED_WORD_PATTERN);
139
+ if (hyphenatedWord) {
140
+ throw new InvalidSyntaxError(
141
+ input,
142
+ hyphenatedWord[0],
143
+ hyphenatedWord.index ?? 0,
144
+ "Hyphenated words are disabled in the current parser mode."
145
+ );
146
+ }
147
+ }
148
+ const tokens = [];
149
+ for (const match of input.matchAll(WORD_PATTERN)) {
150
+ tokens.push({
151
+ word: normalizer(match[0]),
152
+ index: match.index ?? 0
153
+ });
154
+ }
155
+ return tokens;
156
+ }
157
+ function parseWithLexicon(input, lexicon, modes, normalizer) {
158
+ const tokens = tokenize(input, modes, normalizer);
159
+ if (tokens.length === 0) {
160
+ throw new EmptyInputError(input);
161
+ }
162
+ let total = 0n;
163
+ let group = 0n;
164
+ let sign = 1n;
165
+ let signUsed = false;
166
+ let hasValue = false;
167
+ let usedHundred = false;
168
+ let lastClass = "none";
169
+ let lastMultiplier = null;
170
+ for (const token of tokens) {
171
+ const definition = lexicon.get(token.word);
172
+ if (!definition) {
173
+ throw new InvalidTokenError(input, token.word, token.index);
174
+ }
175
+ if (definition.requiresMode && !modes[definition.requiresMode]) {
176
+ invalidSyntax(
177
+ input,
178
+ token,
179
+ `Token "${token.word}" is disabled in the current parser mode.`
180
+ );
181
+ }
182
+ switch (definition.type) {
183
+ case "sign": {
184
+ if (signUsed || hasValue) {
185
+ invalidSyntax(input, token, "Sign words are only allowed before the number.");
186
+ }
187
+ signUsed = true;
188
+ sign = definition.value;
189
+ break;
190
+ }
191
+ case "none": {
192
+ break;
193
+ }
194
+ case "number": {
195
+ if (lastClass === "unit" && definition.cls === "unit") {
196
+ invalidSyntax(input, token, "Two unit words cannot appear next to each other.");
197
+ }
198
+ if ((lastClass === "teen" || definition.cls === "teen") && lastClass !== "none") {
199
+ invalidSyntax(input, token, "Teen words must stand on their own within a group.");
200
+ }
201
+ if (lastClass === "tens" && definition.cls !== "unit") {
202
+ invalidSyntax(input, token, "A tens word can only be followed by a unit word.");
203
+ }
204
+ if (definition.cls === "tens" && lastClass !== "none") {
205
+ invalidSyntax(input, token, "A tens word must start a new group fragment.");
206
+ }
207
+ group += definition.value;
208
+ hasValue = true;
209
+ lastClass = definition.cls;
210
+ break;
211
+ }
212
+ case "hundred": {
213
+ if (group === 0n || usedHundred) {
214
+ invalidSyntax(
215
+ input,
216
+ token,
217
+ "Hundred requires a leading number and may only be used once per group."
218
+ );
219
+ }
220
+ group *= definition.value;
221
+ hasValue = true;
222
+ usedHundred = true;
223
+ lastClass = "none";
224
+ break;
225
+ }
226
+ case "multiplier": {
227
+ if (group === 0n) {
228
+ invalidSyntax(input, token, "Large multipliers require a leading group value.");
229
+ }
230
+ if (lastMultiplier !== null && definition.value >= lastMultiplier) {
231
+ invalidSyntax(input, token, "Large multipliers must appear in descending order.");
232
+ }
233
+ total += group * definition.value;
234
+ group = 0n;
235
+ hasValue = true;
236
+ usedHundred = false;
237
+ lastClass = "none";
238
+ lastMultiplier = definition.value;
239
+ break;
240
+ }
241
+ }
242
+ }
243
+ if (!hasValue) {
244
+ const lastToken = tokens.at(-1);
245
+ invalidSyntax(input, lastToken, "Input did not contain a numeric value.");
246
+ }
247
+ return toOutput((total + group) * sign);
248
+ }
249
+ function createParser(options = {}) {
250
+ const normalization = options.normalization ?? "NFKC";
251
+ const locale = options.locale;
252
+ const normalizer = (word) => normalizeWord(word, locale, normalization);
253
+ const lexicon = createLexiconMap(options.lexicon ?? englishLexicon, normalizer);
254
+ for (const entry of options.extendLexicon ?? []) {
255
+ const resolvedEntry = toResolvedEntry(entry, normalizer);
256
+ lexicon.set(resolvedEntry.normalizedWord, resolvedEntry);
257
+ }
258
+ const defaultModes = resolveModes(DEFAULT_MODES, options.modes);
259
+ const parse = (input, modes) => {
260
+ if (typeof input !== "string") {
261
+ throw new TypeError("parseTextNumber expects a string input.");
262
+ }
263
+ return parseWithLexicon(input, lexicon, resolveModes(defaultModes, modes), normalizer);
264
+ };
265
+ const tryParse = (input, modes) => {
266
+ try {
267
+ return {
268
+ ok: true,
269
+ value: parse(input, modes)
270
+ };
271
+ } catch (error) {
272
+ if (isTextNumberError(error)) {
273
+ return {
274
+ ok: false,
275
+ error
276
+ };
277
+ }
278
+ throw error;
279
+ }
280
+ };
281
+ return {
282
+ parse,
283
+ tryParse,
284
+ lexicon,
285
+ locale,
286
+ normalization,
287
+ modes: defaultModes
288
+ };
289
+ }
290
+
291
+ // src/index.ts
292
+ var defaultParser = createParser();
293
+ function parseTextNumber(input, modes) {
294
+ return defaultParser.parse(input, modes);
295
+ }
296
+ function tryParseTextNumber(input, modes) {
297
+ return defaultParser.tryParse(input, modes);
298
+ }
299
+ export {
300
+ EmptyInputError,
301
+ InvalidSyntaxError,
302
+ InvalidTokenError,
303
+ TextNumberError,
304
+ createParser,
305
+ englishLexicon,
306
+ isTextNumberError,
307
+ parseTextNumber,
308
+ tryParseTextNumber
309
+ };
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "text-number-parser",
3
+ "version": "0.1.0",
4
+ "description": "Parse localized Unicode number words into JavaScript number and bigint values.",
5
+ "author": "Michael Three <michael.three@kiv.dev>",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/michaelthreekiv/text-number-parser.git"
9
+ },
10
+ "homepage": "https://github.com/michaelthreekiv/text-number-parser#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/michaelthreekiv/text-number-parser/issues"
13
+ },
14
+ "type": "module",
15
+ "main": "./dist/index.cjs",
16
+ "module": "./dist/index.js",
17
+ "types": "./dist/index.d.ts",
18
+ "publishConfig": {
19
+ "access": "public"
20
+ },
21
+ "exports": {
22
+ ".": {
23
+ "types": "./dist/index.d.ts",
24
+ "import": "./dist/index.js",
25
+ "require": "./dist/index.cjs"
26
+ }
27
+ },
28
+ "files": [
29
+ "dist",
30
+ "README.md"
31
+ ],
32
+ "engines": {
33
+ "node": ">=18"
34
+ },
35
+ "scripts": {
36
+ "build": "tsup src/index.ts --format esm,cjs --dts --clean",
37
+ "test": "vitest run",
38
+ "bench": "tsx benchmark/parse.bench.ts",
39
+ "check": "npm run build && npm run test",
40
+ "prepublishOnly": "npm run check"
41
+ },
42
+ "keywords": [
43
+ "parser",
44
+ "number",
45
+ "words-to-number",
46
+ "text-number",
47
+ "unicode",
48
+ "localization",
49
+ "i18n",
50
+ "bigint",
51
+ "nlp"
52
+ ],
53
+ "license": "MIT",
54
+ "devDependencies": {
55
+ "tinybench": "^2.9.0",
56
+ "tsup": "^8.3.5",
57
+ "tsx": "^4.20.3",
58
+ "typescript": "^5.8.3",
59
+ "vitest": "^3.2.4"
60
+ }
61
+ }