@connextar/house 0.26.0 → 0.27.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.
Files changed (87) hide show
  1. package/README.md +74 -0
  2. package/dist/voice/handoff.d.ts +20 -0
  3. package/dist/voice/handoff.d.ts.map +1 -0
  4. package/dist/voice/handoff.js +18 -0
  5. package/dist/voice/handoff.js.map +1 -0
  6. package/dist/voice/index.d.ts +16 -0
  7. package/dist/voice/index.d.ts.map +1 -0
  8. package/dist/voice/index.js +16 -0
  9. package/dist/voice/index.js.map +1 -0
  10. package/dist/voice/opening-hours.d.ts +23 -0
  11. package/dist/voice/opening-hours.d.ts.map +1 -0
  12. package/dist/voice/opening-hours.js +117 -0
  13. package/dist/voice/opening-hours.js.map +1 -0
  14. package/dist/voice/out-of-hours.d.ts +29 -0
  15. package/dist/voice/out-of-hours.d.ts.map +1 -0
  16. package/dist/voice/out-of-hours.js +20 -0
  17. package/dist/voice/out-of-hours.js.map +1 -0
  18. package/dist/voice/phone.d.ts +33 -0
  19. package/dist/voice/phone.d.ts.map +1 -0
  20. package/dist/voice/phone.js +62 -0
  21. package/dist/voice/phone.js.map +1 -0
  22. package/dist/voice/relay/agent-client.d.ts +24 -0
  23. package/dist/voice/relay/agent-client.d.ts.map +1 -0
  24. package/dist/voice/relay/agent-client.js +45 -0
  25. package/dist/voice/relay/agent-client.js.map +1 -0
  26. package/dist/voice/relay/model.d.ts +124 -0
  27. package/dist/voice/relay/model.d.ts.map +1 -0
  28. package/dist/voice/relay/model.js +304 -0
  29. package/dist/voice/relay/model.js.map +1 -0
  30. package/dist/voice/relay/protocol.d.ts +44 -0
  31. package/dist/voice/relay/protocol.d.ts.map +1 -0
  32. package/dist/voice/relay/protocol.js +16 -0
  33. package/dist/voice/relay/protocol.js.map +1 -0
  34. package/dist/voice/relay/sentence-gate.d.ts +24 -0
  35. package/dist/voice/relay/sentence-gate.d.ts.map +1 -0
  36. package/dist/voice/relay/sentence-gate.js +65 -0
  37. package/dist/voice/relay/sentence-gate.js.map +1 -0
  38. package/dist/voice/relay/server.d.ts +71 -0
  39. package/dist/voice/relay/server.d.ts.map +1 -0
  40. package/dist/voice/relay/server.js +192 -0
  41. package/dist/voice/relay/server.js.map +1 -0
  42. package/dist/voice/relay/transfer-line.d.ts +33 -0
  43. package/dist/voice/relay/transfer-line.d.ts.map +1 -0
  44. package/dist/voice/relay/transfer-line.js +116 -0
  45. package/dist/voice/relay/transfer-line.js.map +1 -0
  46. package/dist/voice/relay-index.d.ts +13 -0
  47. package/dist/voice/relay-index.d.ts.map +1 -0
  48. package/dist/voice/relay-index.js +13 -0
  49. package/dist/voice/relay-index.js.map +1 -0
  50. package/dist/voice/session-token.d.ts +58 -0
  51. package/dist/voice/session-token.d.ts.map +1 -0
  52. package/dist/voice/session-token.js +152 -0
  53. package/dist/voice/session-token.js.map +1 -0
  54. package/dist/voice/transfer.d.ts +123 -0
  55. package/dist/voice/transfer.d.ts.map +1 -0
  56. package/dist/voice/transfer.js +95 -0
  57. package/dist/voice/transfer.js.map +1 -0
  58. package/dist/voice/twilio-request.d.ts +30 -0
  59. package/dist/voice/twilio-request.d.ts.map +1 -0
  60. package/dist/voice/twilio-request.js +46 -0
  61. package/dist/voice/twilio-request.js.map +1 -0
  62. package/dist/voice/twilio-signature.d.ts +8 -0
  63. package/dist/voice/twilio-signature.d.ts.map +1 -0
  64. package/dist/voice/twilio-signature.js +22 -0
  65. package/dist/voice/twilio-signature.js.map +1 -0
  66. package/dist/voice/twiml.d.ts +93 -0
  67. package/dist/voice/twiml.d.ts.map +1 -0
  68. package/dist/voice/twiml.js +107 -0
  69. package/dist/voice/twiml.js.map +1 -0
  70. package/package.json +15 -1
  71. package/src/voice/handoff.ts +34 -0
  72. package/src/voice/index.ts +78 -0
  73. package/src/voice/opening-hours.ts +125 -0
  74. package/src/voice/out-of-hours.ts +48 -0
  75. package/src/voice/phone.ts +68 -0
  76. package/src/voice/relay/agent-client.ts +64 -0
  77. package/src/voice/relay/model.ts +412 -0
  78. package/src/voice/relay/protocol.ts +52 -0
  79. package/src/voice/relay/sentence-gate.ts +64 -0
  80. package/src/voice/relay/server.ts +242 -0
  81. package/src/voice/relay/transfer-line.ts +114 -0
  82. package/src/voice/relay-index.ts +46 -0
  83. package/src/voice/session-token.ts +205 -0
  84. package/src/voice/transfer.ts +171 -0
  85. package/src/voice/twilio-request.ts +60 -0
  86. package/src/voice/twilio-signature.ts +27 -0
  87. package/src/voice/twiml.ts +184 -0
@@ -0,0 +1,171 @@
1
+ import { type LineStatus, transferTarget } from "./out-of-hours.js";
2
+ import { type CallForwardingMode, divertsToAiLine, isAllowedTransferNumber, presentedNumber } from "./phone.js";
3
+
4
+ /**
5
+ * Where a transfer to a person goes, and whether a call coming in is one of our
6
+ * own transfers come back. Lifted from PharmaLineAI (0.27.7), where a pharmacy
7
+ * was the line; here the line is anything with a transfer number, so a
8
+ * switchboard's forwarding line fits as well as a pharmacy.
9
+ *
10
+ * House holds no database, rate limiter or audit log, so `dialTarget` and
11
+ * `isTransferComingBack` take the app's own through a store. The rules are the
12
+ * same in every app:
13
+ *
14
+ * - only UK landline, mobile and freephone ranges are dialled (`isAllowedTransferNumber`);
15
+ * - a number that diverts every call back to the AI line is never dialled (`divertsToAiLine`);
16
+ * - each caller, and each line, has an hourly ceiling on transfers;
17
+ * - a number that is rung is remembered, so the same call diverted back is recognised.
18
+ */
19
+
20
+ /** A line a transfer can go from. `phone` is the line's own public number, for the loop check. */
21
+ export interface TransferLine {
22
+ id: string;
23
+ phone: string | null;
24
+ transferNumber: string | null;
25
+ callForwarding: CallForwardingMode | null;
26
+ }
27
+
28
+ /** Why a transfer won't be dialled, when it won't, read before any call to the carrier. */
29
+ export type TransferRefusal = "none" | "refused" | "loops";
30
+
31
+ /** An hourly (or any) ceiling, in the shape of a house rate-limit rule. */
32
+ export interface TransferRule {
33
+ limit: number;
34
+ windowMs: number;
35
+ }
36
+
37
+ export interface TransferRules {
38
+ /** The AI's transfers, per line. */
39
+ relay: TransferRule;
40
+ /** Every call put through with the AI off, per line: higher, since every call is a transfer. */
41
+ direct: TransferRule;
42
+ /** One caller, so they can't use up the line's ceiling for everyone else. */
43
+ caller: TransferRule;
44
+ }
45
+
46
+ /** What a refused dial reports, for the app's audit log in its own words. */
47
+ export type DialRefusal =
48
+ | { action: "voice.transfer_refused" }
49
+ | { action: "voice.transfer_loops" }
50
+ | { action: "voice.transfer_capped"; scope: "caller" | "line"; limit: number };
51
+
52
+ export interface TransferStore {
53
+ /** Consume one from a rate-limit bucket. */
54
+ consume(key: string, rule: TransferRule): Promise<{ allowed: boolean }>;
55
+ /** Record why a transfer wasn't dialled. */
56
+ refused(refusal: DialRefusal): Promise<void>;
57
+ /** Remember the number just rung, for `isTransferComingBack`. May throw; a failure is ignored. */
58
+ remember(target: string, at: Date): Promise<void>;
59
+ /** Runs first, such as a guard that refuses calls while an admin is viewing as someone. */
60
+ beforeDial?(): Promise<void>;
61
+ }
62
+
63
+ /**
64
+ * Where a transfer would go now by the line's settings alone, or why it can't:
65
+ * closed with no out-of-hours number or no transfer number (`none`), a number
66
+ * outside the UK ranges (`refused`), or the line's own number when every call to
67
+ * it is diverted to the AI line (`loops`). The hourly cap is the only rule it
68
+ * leaves out, so an agent can read this and never promise a person the
69
+ * webhooks won't ring.
70
+ */
71
+ export function plannedTransfer(
72
+ line: Pick<TransferLine, "phone" | "transferNumber" | "callForwarding">,
73
+ status: LineStatus,
74
+ ): { target: string; refusal: null } | { target: null; refusal: TransferRefusal } {
75
+ const target = transferTarget(status, line.transferNumber);
76
+ if (!target) return { target: null, refusal: "none" };
77
+ if (!isAllowedTransferNumber(target)) return { target: null, refusal: "refused" };
78
+ if (divertsToAiLine(line, target)) return { target: null, refusal: "loops" };
79
+ return { target, refusal: null };
80
+ }
81
+
82
+ /**
83
+ * The number to ring for a transfer now, or null when the caller should hear why
84
+ * nobody can be put through. Each refusal goes to `store.refused`. The rate-limit
85
+ * keys are `transfers:<id>:from:<caller>`, `transfers-direct:<id>` and
86
+ * `transfers:<id>`, as PharmaLine has always used.
87
+ */
88
+ export async function dialTarget(
89
+ line: TransferLine,
90
+ status: LineStatus,
91
+ /** `direct`: the AI is off and every call is put through. `caller`: the number Twilio signed. */
92
+ how: { path: "relay" | "direct"; caller?: string | null },
93
+ deps: { store: TransferStore; rules: TransferRules; now?: Date },
94
+ ): Promise<string | null> {
95
+ const { store, rules } = deps;
96
+ await store.beforeDial?.();
97
+ const { target, refusal } = plannedTransfer(line, status);
98
+ if (refusal === "none") return null;
99
+
100
+ const refuse = async (r: DialRefusal) => {
101
+ await store.refused(r);
102
+ return null;
103
+ };
104
+ if (refusal === "refused") return refuse({ action: "voice.transfer_refused" });
105
+ if (refusal === "loops") return refuse({ action: "voice.transfer_loops" });
106
+
107
+ // The caller's own ceiling first, so a caller turned away doesn't use up everyone else's.
108
+ const caller = presentedNumber(how.caller);
109
+ if (caller && !(await store.consume(`transfers:${line.id}:from:${caller}`, rules.caller)).allowed) {
110
+ return refuse({ action: "voice.transfer_capped", scope: "caller", limit: rules.caller.limit });
111
+ }
112
+ const [key, rule] =
113
+ how.path === "direct" ? [`transfers-direct:${line.id}`, rules.direct] : [`transfers:${line.id}`, rules.relay];
114
+ if (!(await store.consume(key, rule)).allowed) {
115
+ return refuse({ action: "voice.transfer_capped", scope: "line", limit: rule.limit });
116
+ }
117
+
118
+ if (!target) return null;
119
+ try {
120
+ await store.remember(target, deps.now ?? new Date());
121
+ } catch {
122
+ // Only the rewritten-caller-ID loop check leans on this; the AI-line check still holds.
123
+ }
124
+ return target;
125
+ }
126
+
127
+ /**
128
+ * How soon after a transfer is dialled a call from the number rung is taken to be
129
+ * that transfer, diverted back with the caller ID rewritten. A 25 s ring plus a
130
+ * few seconds for the diversion; an app that rings longer passes its own window.
131
+ */
132
+ export const LOOP_WINDOW_MS = 45_000;
133
+
134
+ export interface ComingBackStore {
135
+ /** Whether `from` is one of the app's own AI lines or presented numbers. */
136
+ isOwnNumber(from: string): Promise<boolean>;
137
+ /**
138
+ * Whether `from` is the number this line rang since `since`, clearing the mark
139
+ * as it matches so it counts once.
140
+ */
141
+ takeRecentDial(from: string, since: Date): Promise<boolean>;
142
+ }
143
+
144
+ /**
145
+ * Whether a call to an AI line is one of our own transfers, diverted back to it.
146
+ * Every transfer presents one of our own numbers as caller ID, so a call from any
147
+ * of them is one. Some providers show the diverting line instead, so a call from
148
+ * the number just rung counts too, once. Not when the line's phone system lets
149
+ * the AI line through (`EVERY_CALL_EXCEPT_AI_LINE`): then nothing diverts back.
150
+ *
151
+ * Twilio's `ForwardedFrom` can't decide this: every genuine call diverted from
152
+ * the line's own number carries it as well. A store error reads as "not a loop",
153
+ * so the caller is answered.
154
+ */
155
+ export async function isTransferComingBack(
156
+ line: { voiceNumber: string | null; callForwarding: CallForwardingMode | null },
157
+ from: string | null,
158
+ store: ComingBackStore,
159
+ now: Date = new Date(),
160
+ windowMs = LOOP_WINDOW_MS,
161
+ ): Promise<boolean> {
162
+ if (!from) return false;
163
+ if (from === line.voiceNumber) return true;
164
+ try {
165
+ if (await store.isOwnNumber(from)) return true;
166
+ if (line.callForwarding === "EVERY_CALL_EXCEPT_AI_LINE") return false;
167
+ return await store.takeRecentDial(from, new Date(now.getTime() - windowMs));
168
+ } catch {
169
+ return false;
170
+ }
171
+ }
@@ -0,0 +1,60 @@
1
+ import { isValidTwilioSignature } from "./twilio-signature.js";
2
+
3
+ /** A Twilio webhook's form fields. */
4
+ export type TwilioParams = Record<string, string>;
5
+
6
+ /** A TwiML response. */
7
+ export function twiml(xml: string, status = 200): Response {
8
+ return new Response(xml, { status, headers: { "content-type": "text/xml; charset=utf-8" } });
9
+ }
10
+
11
+ export interface TwilioWebhookConfig {
12
+ /** The account's auth token (the IE1 token for an IE1 number). Empty: webhooks answer 503. */
13
+ authToken: string | undefined;
14
+ /** The public base URL Twilio is given, such as `https://support.example.com`. */
15
+ webhookBaseUrl: string;
16
+ }
17
+
18
+ export type TwilioReadResult = { ok: true; params: TwilioParams } | { ok: false; response: Response };
19
+
20
+ /**
21
+ * Read and authenticate Twilio webhooks. Twilio signs the exact URL it requested;
22
+ * behind a proxy the URL the app sees can differ in scheme or host, so the
23
+ * configured public base URL is also tried.
24
+ *
25
+ * The config is read on each request (a function), so an app can take it from
26
+ * its environment at call time and a test can change it.
27
+ */
28
+ export function createTwilioWebhooks(config: () => TwilioWebhookConfig) {
29
+ async function readTwilioRequest(request: Request): Promise<TwilioReadResult> {
30
+ const { authToken, webhookBaseUrl } = config();
31
+ if (!authToken) {
32
+ return { ok: false, response: new Response("Voice webhooks are not configured.", { status: 503 }) };
33
+ }
34
+
35
+ const params: TwilioParams = {};
36
+ try {
37
+ const form = new URLSearchParams(await request.text());
38
+ for (const [key, value] of form) params[key] = value;
39
+ } catch {
40
+ return { ok: false, response: new Response("Bad request", { status: 400 }) };
41
+ }
42
+
43
+ const url = new URL(request.url);
44
+ const publicUrl = new URL(`${url.pathname}${url.search}`, webhookBaseUrl).toString();
45
+ const signature = request.headers.get("x-twilio-signature");
46
+ if (!isValidTwilioSignature(authToken, signature, [request.url, publicUrl], params)) {
47
+ return { ok: false, response: new Response("Forbidden", { status: 403 }) };
48
+ }
49
+ return { ok: true, params };
50
+ }
51
+
52
+ /** Absolute URL for a callback Twilio should request (and will sign). */
53
+ function webhookUrl(path: string, query: Record<string, string> = {}): string {
54
+ const url = new URL(path, config().webhookBaseUrl);
55
+ for (const [k, v] of Object.entries(query)) url.searchParams.set(k, v);
56
+ return url.toString();
57
+ }
58
+
59
+ return { readTwilioRequest, webhookUrl };
60
+ }
@@ -0,0 +1,27 @@
1
+ import { createHmac, timingSafeEqual } from "node:crypto";
2
+
3
+ /**
4
+ * Twilio request signing (X-Twilio-Signature): base64(HMAC-SHA1(authToken, url + each POST param
5
+ * name and value, sorted by name)). See https://www.twilio.com/docs/usage/security.
6
+ */
7
+ export function computeTwilioSignature(authToken: string, url: string, params: Record<string, string>): string {
8
+ const data = Object.keys(params)
9
+ .sort()
10
+ .reduce((acc, key) => acc + key + params[key], url);
11
+ return createHmac("sha1", authToken).update(data, "utf8").digest("base64");
12
+ }
13
+
14
+ /** Constant-time check of a presented signature against any of the candidate URLs. */
15
+ export function isValidTwilioSignature(
16
+ authToken: string,
17
+ signature: string | null,
18
+ urls: string[],
19
+ params: Record<string, string>,
20
+ ): boolean {
21
+ if (!authToken || !signature) return false;
22
+ const presented = Buffer.from(signature);
23
+ return urls.some((url) => {
24
+ const expected = Buffer.from(computeTwilioSignature(authToken, url, params));
25
+ return expected.length === presented.length && timingSafeEqual(expected, presented);
26
+ });
27
+ }
@@ -0,0 +1,184 @@
1
+ /**
2
+ * Minimal TwiML builders. Every interpolated value is XML-escaped, so a caller's
3
+ * name or a business's greeting can never close a tag or add a verb.
4
+ *
5
+ * Lifted from PharmaLineAI (0.27.7). New here: `gather`, `play`, `<Number url>`
6
+ * call screening and a `timeout` on `dial` (PharmaLine's was fixed at 25 s,
7
+ * which is still the default).
8
+ */
9
+
10
+ export function escapeXml(value: string): string {
11
+ return value
12
+ .replace(/&/g, "&amp;")
13
+ .replace(/</g, "&lt;")
14
+ .replace(/>/g, "&gt;")
15
+ .replace(/"/g, "&quot;")
16
+ .replace(/'/g, "&apos;");
17
+ }
18
+
19
+ type AttrValue = string | number | boolean | null | undefined;
20
+
21
+ function attrs(values: Record<string, AttrValue>): string {
22
+ return Object.entries(values)
23
+ .filter(([, v]) => v !== undefined && v !== null && v !== "")
24
+ .map(([k, v]) => ` ${k}="${escapeXml(String(v))}"`)
25
+ .join("");
26
+ }
27
+
28
+ /** A whole TwiML document around verbs already built. */
29
+ export function response(body: string): string {
30
+ return `<?xml version="1.0" encoding="UTF-8"?><Response>${body}</Response>`;
31
+ }
32
+
33
+ /** The voice a fixed `<Say>` line is spoken in. */
34
+ export interface SayVoice {
35
+ language: string;
36
+ voice: string;
37
+ }
38
+
39
+ /** The default `<Say>` voice: Polly's British English neural voice, as PharmaLine has always used. */
40
+ export const DEFAULT_SAY_VOICE: SayVoice = { language: "en-GB", voice: "Polly.Amy-Neural" };
41
+
42
+ /** A `<Say>` verb (not a document). */
43
+ export function say(text: string, voice: SayVoice = DEFAULT_SAY_VOICE): string {
44
+ return `<Say${attrs({ language: voice.language, voice: voice.voice })}>${escapeXml(text)}</Say>`;
45
+ }
46
+
47
+ /** A `<Play>` verb (not a document): pre-rendered audio at an absolute URL. */
48
+ export function play(url: string): string {
49
+ return `<Play>${escapeXml(url)}</Play>`;
50
+ }
51
+
52
+ /** Speak a message and hang up. */
53
+ export function sayAndHangup(text: string, voice?: SayVoice): string {
54
+ return response(`${say(text, voice)}<Hangup/>`);
55
+ }
56
+
57
+ /** Play or say verbs already built, then hang up. */
58
+ export function thenHangup(verbs: string): string {
59
+ return response(`${verbs}<Hangup/>`);
60
+ }
61
+
62
+ export function hangup(): string {
63
+ return response("<Hangup/>");
64
+ }
65
+
66
+ /**
67
+ * Turn the call away unanswered. As the first and only verb, Twilio never
68
+ * answers, so the call isn't billed: `rejected` plays a not-in-service message,
69
+ * `busy` a busy tone. For a transfer that diverted back to the line it came
70
+ * from, `busy` is what the transferring `<Dial>` sees.
71
+ */
72
+ export function reject(reason: "busy" | "rejected" = "busy"): string {
73
+ return response(`<Reject${attrs({ reason })}/>`);
74
+ }
75
+
76
+ export interface GatherOptions {
77
+ /** Where Twilio posts `Digits` / `SpeechResult`. Also posted when nothing was said. */
78
+ actionUrl: string;
79
+ input?: "dtmf" | "speech" | "dtmf speech";
80
+ numDigits?: number;
81
+ /** Seconds of silence before the gather gives up (Twilio's default is 5). */
82
+ timeout?: number;
83
+ language?: string;
84
+ /** Words the recogniser should favour, such as business names. */
85
+ hints?: string[];
86
+ speechTimeout?: "auto" | number;
87
+ /** Partial speech results, posted as they arrive (used to spot speech over the prompt). */
88
+ partialResultCallback?: string;
89
+ /** Verbs spoken or played inside the gather, such as `say(…)` or `play(…)`. */
90
+ prompt: string;
91
+ }
92
+
93
+ /** Ask the caller for a key press or a few words. A document. */
94
+ export function gather(o: GatherOptions): string {
95
+ const open = `<Gather${attrs({
96
+ input: o.input ?? "dtmf",
97
+ action: o.actionUrl,
98
+ method: "POST",
99
+ numDigits: o.numDigits,
100
+ timeout: o.timeout,
101
+ language: o.language,
102
+ hints: o.hints?.length ? o.hints.join(", ") : undefined,
103
+ speechTimeout: o.speechTimeout,
104
+ partialResultCallback: o.partialResultCallback,
105
+ actionOnEmptyResult: true,
106
+ })}>`;
107
+ return response(`${open}${o.prompt}</Gather>`);
108
+ }
109
+
110
+ export interface RelayTwimlOptions {
111
+ relayUrl: string;
112
+ actionUrl: string;
113
+ welcomeGreeting: string;
114
+ language: string;
115
+ ttsProvider: string;
116
+ voice?: string;
117
+ transcriptionProvider: string;
118
+ /** Passed to the relay's `setup` message as customParameters. Never personal data. */
119
+ parameters: Record<string, string>;
120
+ /** Record the call; Twilio posts the finished recording here. */
121
+ recordingCallbackUrl?: string;
122
+ /** Verbs before the relay connects, such as a `play(…)` of a fixed line. */
123
+ preamble?: string;
124
+ }
125
+
126
+ /** Hand the call to the AI via ConversationRelay; `action` runs when the AI session ends. */
127
+ export function connectConversationRelay(o: RelayTwimlOptions): string {
128
+ const params = Object.entries(o.parameters)
129
+ .map(([name, value]) => `<Parameter${attrs({ name, value })}/>`)
130
+ .join("");
131
+ const relay = `<ConversationRelay${attrs({
132
+ url: o.relayUrl,
133
+ welcomeGreeting: o.welcomeGreeting,
134
+ language: o.language,
135
+ ttsProvider: o.ttsProvider,
136
+ voice: o.voice,
137
+ transcriptionProvider: o.transcriptionProvider,
138
+ interruptible: "any",
139
+ dtmfDetection: true,
140
+ })}>${params}</ConversationRelay>`;
141
+ const record = o.recordingCallbackUrl
142
+ ? `<Start><Recording${attrs({ recordingStatusCallback: o.recordingCallbackUrl, recordingStatusCallbackEvent: "completed" })}/></Start>`
143
+ : "";
144
+ return response(`${o.preamble ?? ""}${record}<Connect${attrs({ action: o.actionUrl })}>${relay}</Connect>`);
145
+ }
146
+
147
+ export interface DialOptions {
148
+ number: string;
149
+ callerId?: string | null;
150
+ actionUrl: string;
151
+ /** Spoken before dialling, in `sayVoice` (default `DEFAULT_SAY_VOICE`). */
152
+ preamble?: string;
153
+ /** Verbs before dialling, used instead of `preamble` (for example a `play(…)`). */
154
+ preambleVerbs?: string;
155
+ sayVoice?: SayVoice;
156
+ /** Seconds to ring before giving up. Default 25; a UK ring is about 3 s. */
157
+ timeout?: number;
158
+ /**
159
+ * Call screening: TwiML Twilio fetches and plays to whoever answers, before
160
+ * the caller is connected. An empty `<Response/>` bridges the call; a
161
+ * `<Hangup/>` refuses it, and the `<Dial action>` then runs.
162
+ */
163
+ screenUrl?: string;
164
+ /** Status callbacks for the dialled leg. */
165
+ statusCallback?: string;
166
+ statusCallbackEvent?: string;
167
+ }
168
+
169
+ /** Put the caller through to a person; `action` decides what happens if nobody accepts. */
170
+ export function dial(o: DialOptions): string {
171
+ const lead = o.preambleVerbs ?? (o.preamble ? say(o.preamble, o.sayVoice) : "");
172
+ const number = `<Number${attrs({
173
+ url: o.screenUrl,
174
+ method: o.screenUrl ? "POST" : undefined,
175
+ statusCallback: o.statusCallback,
176
+ statusCallbackMethod: o.statusCallback ? "POST" : undefined,
177
+ statusCallbackEvent: o.statusCallback
178
+ ? (o.statusCallbackEvent ?? "initiated ringing answered completed")
179
+ : undefined,
180
+ })}>${escapeXml(o.number)}</Number>`;
181
+ return response(
182
+ `${lead}<Dial${attrs({ callerId: o.callerId, timeout: o.timeout ?? 25, action: o.actionUrl })}>${number}</Dial>`,
183
+ );
184
+ }