@signalwire/sdk 3.7.2 → 3.10.3

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.
Files changed (67) hide show
  1. package/CHANGELOG.md +201 -0
  2. package/README.md +1 -0
  3. package/dist/AgentBase.d.ts +107 -2
  4. package/dist/AgentBase.js +259 -13
  5. package/dist/AgentBase.js.map +1 -1
  6. package/dist/AiEvents.d.ts +70 -0
  7. package/dist/AiEvents.js +94 -0
  8. package/dist/AiEvents.js.map +1 -0
  9. package/dist/ContextBuilder.d.ts +215 -14
  10. package/dist/ContextBuilder.js +441 -14
  11. package/dist/ContextBuilder.js.map +1 -1
  12. package/dist/FunctionResult.d.ts +146 -1
  13. package/dist/FunctionResult.js +188 -2
  14. package/dist/FunctionResult.js.map +1 -1
  15. package/dist/PostPrompt.d.ts +19 -0
  16. package/dist/PostPrompt.js +43 -0
  17. package/dist/PostPrompt.js.map +1 -1
  18. package/dist/SWMLService.d.ts +97 -1
  19. package/dist/SWMLService.js +129 -2
  20. package/dist/SWMLService.js.map +1 -1
  21. package/dist/SemanticGate.d.ts +61 -1
  22. package/dist/SemanticGate.js +108 -15
  23. package/dist/SemanticGate.js.map +1 -1
  24. package/dist/SwaigFunction.d.ts +85 -9
  25. package/dist/SwaigFunction.js +214 -58
  26. package/dist/SwaigFunction.js.map +1 -1
  27. package/dist/ToolMiddleware.d.ts +82 -0
  28. package/dist/ToolMiddleware.js +131 -0
  29. package/dist/ToolMiddleware.js.map +1 -0
  30. package/dist/TypeInference.d.ts +1 -1
  31. package/dist/TypeInference.js.map +1 -1
  32. package/dist/cli/tsdocs/api-index.json +1 -1
  33. package/dist/cli/tsdocs/topics.js +24 -4
  34. package/dist/cli/tsdocs/topics.js.map +1 -1
  35. package/dist/index.d.ts +22 -8
  36. package/dist/index.js +15 -5
  37. package/dist/index.js.map +1 -1
  38. package/dist/llms.txt +1 -0
  39. package/dist/patterns/Proposal.d.ts +148 -0
  40. package/dist/patterns/Proposal.js +214 -0
  41. package/dist/patterns/Proposal.js.map +1 -0
  42. package/dist/patterns/RequestList.d.ts +138 -0
  43. package/dist/patterns/RequestList.js +171 -0
  44. package/dist/patterns/RequestList.js.map +1 -0
  45. package/dist/skills/SkillBase.d.ts +24 -1
  46. package/dist/skills/SkillBase.js +12 -1
  47. package/dist/skills/SkillBase.js.map +1 -1
  48. package/dist/speech/numbers.d.ts +66 -0
  49. package/dist/speech/numbers.js +281 -0
  50. package/dist/speech/numbers.js.map +1 -0
  51. package/dist/speech/spelling.d.ts +71 -0
  52. package/dist/speech/spelling.js +294 -0
  53. package/dist/speech/spelling.js.map +1 -0
  54. package/dist/testing/CallSimulator.d.ts +391 -0
  55. package/dist/testing/CallSimulator.js +966 -0
  56. package/dist/testing/CallSimulator.js.map +1 -0
  57. package/docs/agent-guide.md +2 -2
  58. package/docs/api-reference.md +279 -22
  59. package/docs/architecture.md +8 -4
  60. package/docs/cli-guide.md +2 -0
  61. package/docs/contexts-guide.md +75 -4
  62. package/docs/conversation_patterns.md +257 -0
  63. package/docs/mcp_integration.md +1 -1
  64. package/docs/pgi_agent_guide.md +5 -0
  65. package/docs/programmatically_governed_inference.md +2 -2
  66. package/docs/swaig-reference.md +98 -6
  67. package/package.json +1 -1
@@ -0,0 +1,281 @@
1
+ /**
2
+ * Numbers as an English text-to-speech voice should say them.
3
+ *
4
+ * The platform normalizes text before its pronunciation rules run, so a bare
5
+ * number is already words by then: `addPronunciation` can't make "10001" read
6
+ * digit by digit. Give the model, or a `say` action, the words instead.
7
+ */
8
+ const DIGITS = [
9
+ 'zero',
10
+ 'one',
11
+ 'two',
12
+ 'three',
13
+ 'four',
14
+ 'five',
15
+ 'six',
16
+ 'seven',
17
+ 'eight',
18
+ 'nine',
19
+ ];
20
+ const TEENS = [
21
+ 'ten',
22
+ 'eleven',
23
+ 'twelve',
24
+ 'thirteen',
25
+ 'fourteen',
26
+ 'fifteen',
27
+ 'sixteen',
28
+ 'seventeen',
29
+ 'eighteen',
30
+ 'nineteen',
31
+ ];
32
+ const TENS = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
33
+ const SCALES = ['', 'thousand', 'million', 'billion', 'trillion'];
34
+ // Currency: [major singular, major plural, minor singular, minor plural, minor
35
+ // units per major]; null minor for a currency without one
36
+ const CURRENCIES = {
37
+ USD: ['dollar', 'dollars', 'cent', 'cents', 100],
38
+ CAD: ['dollar', 'dollars', 'cent', 'cents', 100],
39
+ AUD: ['dollar', 'dollars', 'cent', 'cents', 100],
40
+ NZD: ['dollar', 'dollars', 'cent', 'cents', 100],
41
+ EUR: ['euro', 'euros', 'cent', 'cents', 100],
42
+ GBP: ['pound', 'pounds', 'penny', 'pence', 100],
43
+ MXN: ['peso', 'pesos', 'centavo', 'centavos', 100],
44
+ INR: ['rupee', 'rupees', 'paisa', 'paise', 100],
45
+ JPY: ['yen', 'yen', null, null, 1],
46
+ };
47
+ /**
48
+ * `text` with every Unicode decimal digit (`٢`, `4`, `𝟏`) as its ASCII digit, as
49
+ * the reference's `\d` and `int()` read them. Each script's digits are a run of
50
+ * ten code points, 0 to 9, so a digit's value is its place in its run.
51
+ */
52
+ function asciiDigits(text) {
53
+ return text.replace(/\p{Nd}/gu, (digit) => {
54
+ let cp = digit.codePointAt(0);
55
+ let place = 0;
56
+ while (/\p{Nd}/u.test(String.fromCodePoint(cp - 1))) {
57
+ cp -= 1;
58
+ place += 1;
59
+ }
60
+ return String(place % 10);
61
+ });
62
+ }
63
+ /**
64
+ * `n` in English words: `numberWords(1405)` is "one thousand four hundred five".
65
+ * @param n - A whole number, as a safe integer or a bigint.
66
+ * @returns The words.
67
+ * @throws Error for a number that isn't whole, or of a quadrillion or more.
68
+ */
69
+ export function numberWords(n) {
70
+ let value;
71
+ if (typeof n === 'bigint') {
72
+ value = n;
73
+ }
74
+ else if (typeof n === 'number' && Number.isSafeInteger(n)) {
75
+ value = BigInt(n);
76
+ }
77
+ else {
78
+ throw new Error(`numberWords takes a whole number, got ${String(n)}`);
79
+ }
80
+ if (value < 0n)
81
+ return `minus ${numberWords(-value)}`;
82
+ if (value === 0n)
83
+ return 'zero';
84
+ if (value >= 1000n ** BigInt(SCALES.length))
85
+ throw new Error(`${value} is too large to say`);
86
+ const parts = [];
87
+ for (let scale = SCALES.length - 1; scale >= 0; scale--) {
88
+ const chunk = Number((value / 1000n ** BigInt(scale)) % 1000n);
89
+ if (chunk) {
90
+ parts.push(belowThousand(chunk));
91
+ if (SCALES[scale])
92
+ parts.push(SCALES[scale]);
93
+ }
94
+ }
95
+ return parts.join(' ');
96
+ }
97
+ function belowThousand(n) {
98
+ const words = [];
99
+ if (n >= 100) {
100
+ words.push(DIGITS[Math.floor(n / 100)], 'hundred');
101
+ n %= 100;
102
+ }
103
+ if (n >= 20) {
104
+ words.push(TENS[Math.floor(n / 10)] + (n % 10 ? `-${DIGITS[n % 10]}` : ''));
105
+ }
106
+ else if (n >= 10) {
107
+ words.push(TEENS[n - 10]);
108
+ }
109
+ else if (n) {
110
+ words.push(DIGITS[n]);
111
+ }
112
+ return words.join(' ');
113
+ }
114
+ /**
115
+ * The digits in `text`, one word each, as a voice should read a ZIP code, an
116
+ * account number or a phone number.
117
+ *
118
+ * `sayDigits('415-555-0192')` is "four one five, five five five, zero one nine
119
+ * two": with `group` left out, the groups are the ones the text has, separated
120
+ * by anything that isn't a digit. `group` 3 splits the digits into threes;
121
+ * `[3, 3, 4]` into those sizes, the rest in a last group. A comma between
122
+ * groups makes the voice pause.
123
+ *
124
+ * @param text - The digits, with any separators.
125
+ * @param group - The group size, or the sizes in order.
126
+ * @param opts - `zero`, the word for 0.
127
+ * @returns The words, or "" when `text` has no digits.
128
+ * @throws Error for a group size that isn't a positive whole number.
129
+ */
130
+ export function sayDigits(text, group, opts = {}) {
131
+ const str = asciiDigits(String(text));
132
+ let groups;
133
+ if (group === undefined || group === null) {
134
+ groups = str.match(/\d+/g) ?? [];
135
+ }
136
+ else {
137
+ const digits = str.replace(/\D/g, '');
138
+ const sizes = typeof group === 'number' ? [group] : [...group];
139
+ if (sizes.length === 0 || sizes.some((s) => !Number.isInteger(s) || s < 1)) {
140
+ throw new Error(`group sizes must be positive, got ${JSON.stringify(group)}`);
141
+ }
142
+ groups = [];
143
+ let position = 0;
144
+ while (position < digits.length) {
145
+ const index = groups.length;
146
+ let size;
147
+ if (typeof group === 'number')
148
+ size = group;
149
+ else if (index < sizes.length)
150
+ size = sizes[index];
151
+ else
152
+ size = digits.length - position; // the rest, in a last group
153
+ groups.push(digits.slice(position, position + size));
154
+ position += size;
155
+ }
156
+ }
157
+ const names = [opts.zero ?? 'zero', ...DIGITS.slice(1)];
158
+ return groups
159
+ .filter((g) => g)
160
+ .map((g) => [...g].map((d) => names[Number(d)]).join(' '))
161
+ .join(', ');
162
+ }
163
+ /**
164
+ * The last `n` digits of `text`, one word each: for "a card ending in ..." or
165
+ * "the account ending in ...".
166
+ *
167
+ * `sayLastDigits('4111 1111 1111 1234')` is "one two three four".
168
+ *
169
+ * @param text - The number, with any separators.
170
+ * @param n - How many of its last digits. Default 4.
171
+ * @param opts - `zero`, the word for 0.
172
+ * @returns The words, or "" when `text` has no digits.
173
+ * @throws Error for an `n` that isn't a positive whole number.
174
+ */
175
+ export function sayLastDigits(text, n = 4, opts = {}) {
176
+ if (typeof n !== 'number' || !Number.isInteger(n) || n < 1) {
177
+ throw new Error(`n must be a positive whole number, got ${String(n)}`);
178
+ }
179
+ const digits = asciiDigits(String(text)).replace(/\D/g, '');
180
+ return sayDigits(digits.slice(-n), n, opts);
181
+ }
182
+ /**
183
+ * An amount of money in words: `sayMoney(14.5)` is "fourteen dollars and fifty
184
+ * cents".
185
+ *
186
+ * The amount is rounded to the currency's smallest unit, half up, from its
187
+ * decimal text, so `sayMoney(0.125)` is "thirteen cents" and `sayMoney('2.675')`
188
+ * "two dollars and sixty-eight cents". The currencies are USD, CAD, AUD, NZD,
189
+ * EUR, GBP, MXN, INR and JPY.
190
+ *
191
+ * @param amount - The amount, in the currency's major unit (dollars, not
192
+ * cents): a number, a bigint, or a decimal string such as "14.50".
193
+ * @param currency - The ISO 4217 code. Default "USD".
194
+ * @returns The words, such as "one dollar", "five cents" or "minus two pounds
195
+ * and one penny".
196
+ * @throws Error for an amount that isn't a finite number, or another currency.
197
+ */
198
+ export function sayMoney(amount, currency = 'USD') {
199
+ const names = CURRENCIES[currency.toUpperCase()];
200
+ if (names === undefined) {
201
+ throw new Error(`sayMoney doesn't know ${JSON.stringify(currency)}; it takes ${JSON.stringify(Object.keys(CURRENCIES).sort())}`);
202
+ }
203
+ const [majorOne, majorMany, minorOne, minorMany, perMajor] = names;
204
+ const parsed = parseDecimal(amount);
205
+ if (parsed === null)
206
+ throw new Error(`amount must be a number, got ${String(amount)}`);
207
+ // Past a quadrillion it can't be said; checked before the math, so an
208
+ // exponent such as 1e999999999 is refused rather than computed
209
+ if (parsed.digits && String(parsed.digits).length + parsed.exponent > 16) {
210
+ throw new Error(`${String(amount)} is too large to say`);
211
+ }
212
+ // The product in minor units, to 28 significant digits as the reference's
213
+ // Decimal context gives it, then rounded half up to a whole unit
214
+ const product = toPrecision(parsed.digits * BigInt(perMajor), parsed.exponent, 28);
215
+ const minorTotal = roundHalfUp(product.digits, product.exponent);
216
+ const major = minorTotal / BigInt(perMajor);
217
+ const minor = minorTotal % BigInt(perMajor);
218
+ const parts = [];
219
+ if (major || !minor || minorOne === null) {
220
+ parts.push(`${numberWords(major)} ${major === 1n ? majorOne : majorMany}`);
221
+ }
222
+ if (minor && minorOne !== null && minorMany !== null) {
223
+ parts.push(`${numberWords(minor)} ${minor === 1n ? minorOne : minorMany}`);
224
+ }
225
+ const words = parts.join(' and ');
226
+ return parsed.negative && minorTotal ? `minus ${words}` : words;
227
+ }
228
+ /** `|amount|` as `digits * 10 ** exponent`, with its sign; null when it isn't a finite number. */
229
+ function parseDecimal(amount) {
230
+ if (typeof amount === 'bigint') {
231
+ return { negative: amount < 0n, digits: amount < 0n ? -amount : amount, exponent: 0 };
232
+ }
233
+ if (typeof amount === 'number' && !Number.isFinite(amount))
234
+ return null;
235
+ if (typeof amount !== 'number' && typeof amount !== 'string')
236
+ return null;
237
+ // A number's shortest text, as Python's str() gives a float's; underscores
238
+ // between digits are allowed, as Python's Decimal allows them
239
+ const text = asciiDigits(String(amount))
240
+ .trim()
241
+ .replace(/(?<=\d)_(?=\d)/g, '');
242
+ const m = /^([+-]?)(\d*)(?:\.(\d*))?(?:e([+-]?\d+))?$/i.exec(text);
243
+ if (!m || (m[2] === '' && (m[3] ?? '') === ''))
244
+ return null;
245
+ const whole = m[2] ?? '';
246
+ const fraction = m[3] ?? '';
247
+ return {
248
+ negative: m[1] === '-',
249
+ digits: BigInt(whole + fraction || '0'),
250
+ exponent: Number(m[4] ?? 0) - fraction.length,
251
+ };
252
+ }
253
+ /**
254
+ * `digits * 10 ** exponent` to `precision` significant digits, half even: the
255
+ * rounding of a Decimal context (the reference's default is 28 digits).
256
+ */
257
+ function toPrecision(digits, exponent, precision) {
258
+ const extra = String(digits).length - precision;
259
+ if (extra <= 0)
260
+ return { digits, exponent };
261
+ const divisor = 10n ** BigInt(extra);
262
+ let kept = digits / divisor;
263
+ const twice = 2n * (digits % divisor);
264
+ if (twice > divisor || (twice === divisor && kept % 2n === 1n))
265
+ kept += 1n;
266
+ return { digits: kept, exponent: exponent + extra };
267
+ }
268
+ /** `digits * 10 ** exponent` rounded to a whole number, half up. */
269
+ function roundHalfUp(digits, exponent) {
270
+ if (digits === 0n)
271
+ return 0n;
272
+ if (exponent >= 0)
273
+ return digits * 10n ** BigInt(exponent);
274
+ // Below a tenth of a unit it rounds to 0, however small
275
+ if (-exponent > String(digits).length + 1)
276
+ return 0n;
277
+ const divisor = 10n ** BigInt(-exponent);
278
+ const quotient = digits / divisor;
279
+ return 2n * (digits % divisor) >= divisor ? quotient + 1n : quotient;
280
+ }
281
+ //# sourceMappingURL=numbers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"numbers.js","sourceRoot":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spelled out, from the recognizer's text.
3
+ *
4
+ * A caller spells a name, a code or an email address in many ways: letter by
5
+ * letter ("s m i t h"), with letter names ("ess em eye tee aitch"), with words
6
+ * ("S as in Sam"), with the NATO alphabet ("sierra mike"), or with "double l"
7
+ * for two. {@link readSpelled} turns all of them into units, one letter, digit
8
+ * or symbol each, and {@link spokenEmail} reads an address said aloud.
9
+ *
10
+ * The recognizer confuses some letters, and which ones depends on the
11
+ * recognizer and the voice. {@link spellingVariants} expands units with
12
+ * confusion groups you supply, measured on your own calls; none are built in.
13
+ * English only.
14
+ */
15
+ /** Options for {@link readSpelled}. */
16
+ export interface ReadSpelledOptions {
17
+ /** True to read "oh" as the digit 0, for a code of digits; by default it's the letter O. */
18
+ ohIsZero?: boolean;
19
+ }
20
+ /**
21
+ * The units a caller spelled: one uppercase letter, digit or symbol each.
22
+ *
23
+ * `readSpelled('S as in Sam, m i t h')` and `readSpelled('sierra mike india
24
+ * tango hotel')` are both `['S', 'M', 'I', 'T', 'H']`. "double l" is two L's,
25
+ * and "capital" before a letter is dropped. A word that names no letter, such
26
+ * as "smith", is taken as spelled: its letters.
27
+ *
28
+ * @param text - The recognizer's text.
29
+ * @param opts - `ohIsZero`.
30
+ * @returns The units, in order.
31
+ */
32
+ export declare function readSpelled(text: string, opts?: ReadSpelledOptions): string[];
33
+ /**
34
+ * An email address said aloud, as text: "john dot smith at example dot com" is
35
+ * "john.smith@example.com".
36
+ *
37
+ * Words are kept as words, and letters, digits and symbols spelled out are
38
+ * joined to them, so "j o h n underscore smith at example dot co dot uk" is
39
+ * "john_smith@example.co.uk". An address the recognizer already wrote as one
40
+ * is returned lowercased.
41
+ *
42
+ * @param text - The recognizer's text.
43
+ * @returns The address, lowercased. Check it before you use it: this reads the
44
+ * words, it doesn't validate them.
45
+ */
46
+ export declare function spokenEmail(text: string): string;
47
+ /** Options for {@link spellingVariants}. */
48
+ export interface SpellingVariantsOptions {
49
+ /**
50
+ * Only these positions vary, such as the words the recognizer was least sure
51
+ * of (`AgentBase.speechFinals()` gives each word's confidence). Default: all.
52
+ */
53
+ positions?: Iterable<number>;
54
+ /** The most spellings to return. Default 50. */
55
+ limit?: number;
56
+ }
57
+ /**
58
+ * The spellings `units` could be, given letters the recognizer confuses.
59
+ *
60
+ * `groups` maps a unit to the units it may be heard as, such as `{ S: 'F', F:
61
+ * 'S', M: 'N', N: 'M' }` (a string is its letters): measure them on your own
62
+ * recognizer and voices. The units as heard come first, then the variants with
63
+ * one change, then two, and so on, up to `limit`. Look each up in your own
64
+ * records; the first that matches is the likeliest.
65
+ *
66
+ * @param units - The units, from {@link readSpelled}.
67
+ * @param groups - For each unit, the units it may have been.
68
+ * @param opts - `positions` and `limit`.
69
+ * @returns The spellings, joined.
70
+ */
71
+ export declare function spellingVariants(units: readonly string[], groups: Readonly<Record<string, Iterable<string>>> | ReadonlyMap<string, Iterable<string>>, opts?: SpellingVariantsOptions): string[];
@@ -0,0 +1,294 @@
1
+ /**
2
+ * What a caller spelled out, from the recognizer's text.
3
+ *
4
+ * A caller spells a name, a code or an email address in many ways: letter by
5
+ * letter ("s m i t h"), with letter names ("ess em eye tee aitch"), with words
6
+ * ("S as in Sam"), with the NATO alphabet ("sierra mike"), or with "double l"
7
+ * for two. {@link readSpelled} turns all of them into units, one letter, digit
8
+ * or symbol each, and {@link spokenEmail} reads an address said aloud.
9
+ *
10
+ * The recognizer confuses some letters, and which ones depends on the
11
+ * recognizer and the voice. {@link spellingVariants} expands units with
12
+ * confusion groups you supply, measured on your own calls; none are built in.
13
+ * English only.
14
+ */
15
+ // prettier-ignore
16
+ const LETTER_NAMES = {
17
+ a: 'A', ay: 'A',
18
+ b: 'B', be: 'B', bee: 'B',
19
+ c: 'C', see: 'C', sea: 'C', cee: 'C',
20
+ d: 'D', dee: 'D',
21
+ e: 'E', ee: 'E',
22
+ f: 'F', ef: 'F', eff: 'F',
23
+ g: 'G', gee: 'G', jee: 'G',
24
+ h: 'H', aitch: 'H', haitch: 'H',
25
+ i: 'I', eye: 'I',
26
+ j: 'J', jay: 'J',
27
+ k: 'K', kay: 'K',
28
+ l: 'L', el: 'L', ell: 'L',
29
+ m: 'M', em: 'M',
30
+ n: 'N', en: 'N',
31
+ o: 'O',
32
+ p: 'P', pee: 'P',
33
+ q: 'Q', cue: 'Q', queue: 'Q',
34
+ r: 'R', ar: 'R', are: 'R',
35
+ s: 'S', es: 'S', ess: 'S',
36
+ t: 'T', tee: 'T', tea: 'T',
37
+ u: 'U', you: 'U',
38
+ v: 'V', vee: 'V',
39
+ w: 'W',
40
+ x: 'X', ex: 'X',
41
+ y: 'Y', why: 'Y', wye: 'Y',
42
+ z: 'Z', zee: 'Z', zed: 'Z',
43
+ };
44
+ // prettier-ignore
45
+ const NATO = {
46
+ alpha: 'A', alfa: 'A', bravo: 'B', charlie: 'C', delta: 'D',
47
+ echo: 'E', foxtrot: 'F', golf: 'G', hotel: 'H', india: 'I',
48
+ juliet: 'J', juliett: 'J', kilo: 'K', lima: 'L', mike: 'M',
49
+ november: 'N', oscar: 'O', papa: 'P', quebec: 'Q', romeo: 'R',
50
+ sierra: 'S', tango: 'T', uniform: 'U', victor: 'V',
51
+ whiskey: 'W', whisky: 'W', xray: 'X', 'x-ray': 'X', yankee: 'Y',
52
+ zulu: 'Z',
53
+ };
54
+ // prettier-ignore
55
+ const DIGIT_WORDS = {
56
+ zero: '0', one: '1', two: '2', three: '3', four: '4',
57
+ five: '5', six: '6', seven: '7', eight: '8', nine: '9',
58
+ };
59
+ // prettier-ignore
60
+ const SYMBOLS = {
61
+ dot: '.', period: '.', point: '.',
62
+ at: '@',
63
+ dash: '-', hyphen: '-',
64
+ underscore: '_',
65
+ plus: '+',
66
+ slash: '/',
67
+ };
68
+ // Words that say how the next letter is written, not which it is
69
+ const CASE_WORDS = new Set(['capital', 'uppercase', 'upper', 'lowercase', 'lower', 'small']);
70
+ const TOKEN = /[a-z0-9@._+/'-]+/g;
71
+ const UNIT_SYMBOLS = '@._+/-';
72
+ const lookup = (table, word) => Object.hasOwn(table, word) ? table[word] : undefined;
73
+ /** The letter, digit or symbol one spoken word names, or null. */
74
+ function unitOf(word, ohIsZero) {
75
+ if (word === 'oh')
76
+ return ohIsZero ? '0' : 'O';
77
+ for (const table of [LETTER_NAMES, NATO, DIGIT_WORDS, SYMBOLS]) {
78
+ const unit = lookup(table, word);
79
+ if (unit !== undefined)
80
+ return unit;
81
+ }
82
+ if (word.length === 1 && (/\d/.test(word) || UNIT_SYMBOLS.includes(word)))
83
+ return word;
84
+ return null;
85
+ }
86
+ const isLetter = (unit) => unit !== null && /^[A-Z]$/.test(unit);
87
+ /**
88
+ * The units a caller spelled: one uppercase letter, digit or symbol each.
89
+ *
90
+ * `readSpelled('S as in Sam, m i t h')` and `readSpelled('sierra mike india
91
+ * tango hotel')` are both `['S', 'M', 'I', 'T', 'H']`. "double l" is two L's,
92
+ * and "capital" before a letter is dropped. A word that names no letter, such
93
+ * as "smith", is taken as spelled: its letters.
94
+ *
95
+ * @param text - The recognizer's text.
96
+ * @param opts - `ohIsZero`.
97
+ * @returns The units, in order.
98
+ */
99
+ export function readSpelled(text, opts = {}) {
100
+ const ohIsZero = opts.ohIsZero ?? false;
101
+ const tokens = spellingTokens(text);
102
+ const units = [];
103
+ let i = 0;
104
+ while (i < tokens.length) {
105
+ const word = tokens[i];
106
+ // "S as in Sam": the letter, and the word after "as in" is skipped
107
+ if (tokens[i + 1] === 'as' && tokens[i + 2] === 'in') {
108
+ const letter = unitOf(word, false);
109
+ units.push(isLetter(letter) ? letter : word[0].toUpperCase());
110
+ i += 4;
111
+ continue;
112
+ }
113
+ if (CASE_WORDS.has(word)) {
114
+ i += 1;
115
+ continue;
116
+ }
117
+ if (word === 'double' && i + 1 < tokens.length) {
118
+ const following = tokens[i + 1];
119
+ if (following === 'you' || following === 'u') {
120
+ units.push('W');
121
+ }
122
+ else {
123
+ const unit = unitOf(following, ohIsZero);
124
+ if (unit)
125
+ units.push(unit, unit);
126
+ else
127
+ units.push(...letters(following), ...letters(following));
128
+ }
129
+ i += 2;
130
+ continue;
131
+ }
132
+ const unit = unitOf(word, ohIsZero);
133
+ if (unit)
134
+ units.push(unit);
135
+ else
136
+ units.push(...letters(word));
137
+ i += 1;
138
+ }
139
+ return units;
140
+ }
141
+ /**
142
+ * The words of spelled text. A hyphen inside a word, as a recognizer writes
143
+ * "S-M-I-T-H", separates units; a spoken "dash" is the symbol.
144
+ */
145
+ function spellingTokens(text) {
146
+ const tokens = [];
147
+ for (const token of text.toLowerCase().match(TOKEN) ?? []) {
148
+ if (token.includes('-') && token.length > 1 && lookup(NATO, token) === undefined) {
149
+ tokens.push(...token.split('-').filter((part) => part));
150
+ }
151
+ else {
152
+ tokens.push(token);
153
+ }
154
+ }
155
+ return tokens;
156
+ }
157
+ function letters(word) {
158
+ return [...word]
159
+ .filter((c) => /[a-z0-9]/i.test(c) || UNIT_SYMBOLS.includes(c))
160
+ .map((c) => (/[a-z]/i.test(c) ? c.toUpperCase() : c));
161
+ }
162
+ /**
163
+ * An email address said aloud, as text: "john dot smith at example dot com" is
164
+ * "john.smith@example.com".
165
+ *
166
+ * Words are kept as words, and letters, digits and symbols spelled out are
167
+ * joined to them, so "j o h n underscore smith at example dot co dot uk" is
168
+ * "john_smith@example.co.uk". An address the recognizer already wrote as one
169
+ * is returned lowercased.
170
+ *
171
+ * @param text - The recognizer's text.
172
+ * @returns The address, lowercased. Check it before you use it: this reads the
173
+ * words, it doesn't validate them.
174
+ */
175
+ export function spokenEmail(text) {
176
+ const compact = text.trim().toLowerCase().replace(/\s+/g, '');
177
+ if (/^[^@\s]+@[^@\s]+\.[a-z]{2,}$/.test(compact))
178
+ return compact;
179
+ const tokens = text.toLowerCase().match(TOKEN) ?? [];
180
+ const parts = [];
181
+ let i = 0;
182
+ while (i < tokens.length) {
183
+ const word = tokens[i];
184
+ if (word === 'at' && tokens[i + 1] === 'sign') {
185
+ parts.push('@');
186
+ i += 2;
187
+ continue;
188
+ }
189
+ if (tokens[i + 1] === 'as' && tokens[i + 2] === 'in') {
190
+ const letter = unitOf(word, false);
191
+ parts.push((isLetter(letter) ? letter : word[0]).toLowerCase());
192
+ i += 4;
193
+ continue;
194
+ }
195
+ if (word === 'double' && i + 1 < tokens.length) {
196
+ const doubled = (unitOf(tokens[i + 1], false) ?? tokens[i + 1]).toLowerCase();
197
+ parts.push(doubled + doubled);
198
+ i += 2;
199
+ continue;
200
+ }
201
+ const symbol = lookup(SYMBOLS, word);
202
+ const nato = lookup(NATO, word);
203
+ const digit = lookup(DIGIT_WORDS, word);
204
+ const letterName = lookup(LETTER_NAMES, word);
205
+ if (symbol !== undefined)
206
+ parts.push(symbol);
207
+ else if (nato !== undefined)
208
+ parts.push(nato.toLowerCase());
209
+ else if (digit !== undefined)
210
+ parts.push(digit);
211
+ else if (word.length === 1 || (letterName !== undefined && word.length <= 2)) {
212
+ parts.push((letterName ?? word).toLowerCase());
213
+ }
214
+ else
215
+ parts.push(word);
216
+ i += 1;
217
+ }
218
+ return parts.join('');
219
+ }
220
+ /**
221
+ * The spellings `units` could be, given letters the recognizer confuses.
222
+ *
223
+ * `groups` maps a unit to the units it may be heard as, such as `{ S: 'F', F:
224
+ * 'S', M: 'N', N: 'M' }` (a string is its letters): measure them on your own
225
+ * recognizer and voices. The units as heard come first, then the variants with
226
+ * one change, then two, and so on, up to `limit`. Look each up in your own
227
+ * records; the first that matches is the likeliest.
228
+ *
229
+ * @param units - The units, from {@link readSpelled}.
230
+ * @param groups - For each unit, the units it may have been.
231
+ * @param opts - `positions` and `limit`.
232
+ * @returns The spellings, joined.
233
+ */
234
+ export function spellingVariants(units, groups, opts = {}) {
235
+ const limit = opts.limit ?? 50;
236
+ const allowed = opts.positions === undefined ? null : new Set(opts.positions);
237
+ const groupOf = (unit) => (groups instanceof Map
238
+ ? groups.get(unit)
239
+ : Object.hasOwn(groups, unit)
240
+ ? groups[unit]
241
+ : undefined) ?? [];
242
+ const choices = units.map((unit, n) => allowed === null || allowed.has(n)
243
+ ? [unit, ...[...groupOf(unit)].filter((u) => u !== unit)]
244
+ : [unit]);
245
+ const varying = choices.flatMap((c, n) => (c.length > 1 ? [n] : []));
246
+ const spellings = [units.join('')];
247
+ if (spellings.length >= limit)
248
+ return spellings;
249
+ for (let changes = 1; changes <= varying.length; changes++) {
250
+ for (const where of combinations(varying, changes)) {
251
+ for (const picks of product(where.map((n) => choices[n].slice(1)))) {
252
+ const spelled = [...units];
253
+ where.forEach((n, k) => (spelled[n] = picks[k]));
254
+ spellings.push(spelled.join(''));
255
+ if (spellings.length >= limit)
256
+ return spellings;
257
+ }
258
+ }
259
+ }
260
+ return spellings;
261
+ }
262
+ /** The `size`-element combinations of `items`, in order, as Python's itertools gives them. */
263
+ function* combinations(items, size) {
264
+ const index = Array.from({ length: size }, (_, k) => k);
265
+ if (size > items.length)
266
+ return;
267
+ for (;;) {
268
+ yield index.map((k) => items[k]);
269
+ let k = size - 1;
270
+ while (k >= 0 && index[k] === k + items.length - size)
271
+ k--;
272
+ if (k < 0)
273
+ return;
274
+ index[k]++;
275
+ for (let j = k + 1; j < size; j++)
276
+ index[j] = index[j - 1] + 1;
277
+ }
278
+ }
279
+ /** The cartesian product of `lists`, the last varying fastest. */
280
+ function* product(lists) {
281
+ if (lists.some((l) => l.length === 0))
282
+ return;
283
+ const index = lists.map(() => 0);
284
+ for (;;) {
285
+ yield index.map((k, n) => lists[n][k]);
286
+ let n = lists.length - 1;
287
+ while (n >= 0 && index[n] === lists[n].length - 1)
288
+ index[n--] = 0;
289
+ if (n < 0)
290
+ return;
291
+ index[n]++;
292
+ }
293
+ }
294
+ //# sourceMappingURL=spelling.js.map