@sinch/functions-runtime 0.5.16 → 0.5.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +74 -13
- package/dist/bin/sinch-runtime.js +39 -31
- package/dist/bin/sinch-runtime.js.map +1 -1
- package/dist/chunk-GW2PELD4.js +4 -0
- package/dist/{chunk-IRSTA74R.js → chunk-VEB6FXNI.js} +1577 -49
- package/dist/chunk-VEB6FXNI.js.map +1 -0
- package/dist/index.d.ts +1891 -70
- package/dist/index.js +40 -10
- package/dist/voice/v2.d.ts +59 -572
- package/dist/voice/v2.js +26 -1230
- package/dist/voice/v2.js.map +1 -1
- package/package.json +2 -2
- package/dist/chunk-IRSTA74R.js.map +0 -1
- package/dist/chunk-X44DQ6CI.js +0 -52
- /package/dist/{chunk-X44DQ6CI.js.map → chunk-GW2PELD4.js.map} +0 -0
package/dist/voice/v2.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../voice-v2-preview/src/core/redaction.ts","../../../voice-v2-preview/src/wire/http.ts","../../../voice-v2-preview/src/core/endpoints.ts","../../../voice-v2-preview/src/core/commands.ts","../../../voice-v2-preview/src/core/plan.ts","../../../voice-v2-preview/src/core/transfer.ts","../../../voice-v2-preview/src/core/client.ts"],"sourcesContent":["/**\n * Voice API v2 credential redaction.\n *\n * `startRecording.recordingOptions.credentials` is a **required** colon-delimited string\n * carrying a long-lived storage secret — `accessKeyId:secretAccessKey:eu-central-1` for AWS.\n * The v2 schema offers no presigned-URL alternative and no STS session-token slot (the third\n * component is the region, not a token), so the secret rides inside the SVAML command body\n * itself: in `POST /calls` requests, in webhook responses, in `PATCH` bodies, and in anything\n * that stringifies one of those.\n *\n * That makes every log line and every exception message a potential disclosure. This module\n * is the mitigation, and it mirrors `redactCallHeaders` in `@sinch/agents`: replace the value\n * with a placeholder on the way out, never suppress the field, so a redacted body still reads\n * as the body it came from.\n */\n\n/** What a redacted secret is replaced with. */\nexport const REDACTED = '[redacted]';\n\n/**\n * Deep-copy a command list, plan or request body with every recording credential replaced.\n *\n * Use this — never the original — whenever a v2 body is logged, printed or serialised into an\n * error. The copy is structurally identical apart from the credential strings, so it stays\n * useful for debugging the shape of a request.\n *\n * Any string-valued `credentials` key is redacted, wherever it sits. That is deliberately\n * broader than `recordingOptions.credentials`: bodies also reach here through `raw()`, which\n * accepts hand-built objects this module does not model, and over-redacting a log line costs\n * nothing while under-redacting one costs a storage key.\n *\n * @param body - Anything JSON-shaped: a command array, a plan, a request body\n * @returns A copy with credentials replaced by {@link REDACTED}\n *\n * @example\n * ```typescript\n * console.log(JSON.stringify(redactCredentials(plan.commands)));\n * // ... \"credentials\":\"[redacted]\" ...\n * ```\n */\nexport function redactCredentials<T>(body: T): T {\n return redactValue(body) as T;\n}\n\nfunction redactValue(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(redactValue);\n }\n if (value === null || typeof value !== 'object') {\n return value;\n }\n const out: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(value as Record<string, unknown>)) {\n out[key] = key === 'credentials' && typeof item === 'string' ? REDACTED : redactValue(item);\n }\n return out;\n}\n\n/**\n * Remove any credential carried by `body` from `text`.\n *\n * The error path needs this rather than {@link redactCredentials}: an API error response is\n * opaque text, and a 400 that quotes the offending body would otherwise put the storage key\n * into an exception message — which is exactly where secrets end up in a stack trace, a log\n * aggregator and a bug report at once.\n *\n * Both the whole credential string and each of its colon-separated components are removed, so\n * an error that echoes only the secret half is caught too. Components shorter than eight\n * characters are left alone: they are region codes and format names, and stripping short\n * strings would corrupt unrelated parts of the message.\n *\n * @param text - Untrusted text about to be put into an error message\n * @param body - The request body that was sent alongside it\n * @returns The text with every credential fragment replaced by {@link REDACTED}\n */\nexport function scrubCredentials(text: string, body: unknown): string {\n let out = text;\n for (const secret of collectCredentials(body)) {\n for (const fragment of [secret, ...secret.split(':')]) {\n if (fragment.length >= 8) {\n out = out.split(fragment).join(REDACTED);\n }\n }\n }\n return out;\n}\n\nfunction collectCredentials(value: unknown, found: Set<string> = new Set()): Set<string> {\n if (Array.isArray(value)) {\n for (const item of value) {\n collectCredentials(item, found);\n }\n return found;\n }\n if (value === null || typeof value !== 'object') {\n return found;\n }\n for (const [key, item] of Object.entries(value as Record<string, unknown>)) {\n if (key === 'credentials' && typeof item === 'string' && item.length > 0) {\n found.add(item);\n } else {\n collectCredentials(item, found);\n }\n }\n return found;\n}\n","/**\n * The lower layer: HTTP, auth, and the URL layout of the Voice API v2.\n *\n * This file and `./types.ts` are the half of `voice/v2/` that dies when `@sinch/voice@2`\n * ships. Everything an OpenAPI generator can produce lives here — the Basic-auth header, the\n * `/v2/projects/{projectId}/…` paths, the fetch call, the status handling. Nothing here knows\n * what a command is, only that it is JSON.\n *\n * It implements {@link CallTransport}, which `core/` owns. Dependencies run *up* only for pure\n * helpers ({@link scrubCredentials}); `core/` never imports from this directory except through\n * `core/models.ts`.\n */\n\nimport type { CallTransport } from '../core/transport.js';\nimport type { CallResponse, Command, PatchTarget } from './types.js';\nimport { scrubCredentials } from '../core/redaction.js';\n\n/** Global Voice API host. Geo-redirects to the nearest region. */\nexport const DEFAULT_HOST = 'https://voice.api.sinch.com';\n\nconst FETCH_TIMEOUT_MS = 10_000;\n\n/** Credentials and endpoint configuration for {@link HttpTransport}. */\nexport interface HttpTransportOptions {\n /** Sinch project id */\n projectId: string;\n /** Access Key ID (Basic auth username) */\n keyId: string;\n /** Access Key Secret (Basic auth password) */\n keySecret: string;\n /** API host. Defaults to {@link DEFAULT_HOST}. */\n host?: string;\n /** Injected fetch, for tests. Defaults to `globalThis.fetch`. */\n fetch?: typeof globalThis.fetch;\n}\n\n/**\n * {@link CallTransport} over `fetch`.\n *\n * Authenticates with HTTP Basic using the project Access Key pair\n * (`PROJECT_ID_API_KEY` / `PROJECT_ID_API_SECRET`) — not the v1 application key.\n *\n * Holds no module-level state: every instance carries its own credentials and fetch, so two\n * compiled copies of this module in one process cannot interfere with each other.\n */\nexport class HttpTransport implements CallTransport {\n private readonly projectId: string;\n private readonly keyId: string;\n private readonly keySecret: string;\n private readonly host: string;\n private readonly fetchImpl: typeof globalThis.fetch;\n\n constructor(options: HttpTransportOptions) {\n this.projectId = options.projectId;\n this.keyId = options.keyId;\n this.keySecret = options.keySecret;\n this.host = (options.host ?? DEFAULT_HOST).replace(/\\/$/, '');\n this.fetchImpl = options.fetch ?? globalThis.fetch;\n }\n\n async createCall(body: object): Promise<CallResponse> {\n const response = await this.request('POST', 'calls', body);\n return response as CallResponse;\n }\n\n async patchCall(target: PatchTarget, commands: Command[]): Promise<void> {\n const path =\n 'callId' in target\n ? `calls/${encodeURIComponent(target.callId)}`\n : `sessions/${encodeURIComponent(target.sessionId)}/calls/${encodeURIComponent(target.callName)}`;\n await this.request('PATCH', path, { commands });\n }\n\n private get authHeaders(): Record<string, string> {\n const token = Buffer.from(`${this.keyId}:${this.keySecret}`).toString('base64');\n return { Authorization: `Basic ${token}`, 'Content-Type': 'application/json' };\n }\n\n private async request(method: string, path: string, body: unknown): Promise<unknown> {\n if (!this.projectId || !this.keyId || !this.keySecret) {\n throw new Error(\n 'Voice API v2 needs PROJECT_ID, PROJECT_ID_API_KEY and PROJECT_ID_API_SECRET (the project Access Key pair, not the v1 application key).'\n );\n }\n\n const url = `${this.host}/v2/projects/${encodeURIComponent(this.projectId)}/${path}`;\n const response = await this.fetchImpl(url, {\n method,\n headers: this.authHeaders,\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),\n });\n\n if (!response.ok) {\n // The API's error text is echoed into the exception, and a 400 that quotes the offending\n // body would otherwise carry a `startRecording` storage key into a stack trace, a log\n // aggregator and a bug report at once. Scrub anything the body itself was carrying.\n const error = scrubCredentials(await response.text(), body);\n throw new Error(`Voice API v2 error: ${response.status} - ${error}`);\n }\n\n // PATCH returns 202 with no body\n return response.status === 204 || response.status === 202 ? undefined : response.json();\n }\n}\n","/**\n * Voice API v2 endpoints — the `to`/`from` half of every command.\n *\n * A leaf module: it knows the wire types and nothing else. `commands.ts` builds command\n * lists on top of it and `client.ts` builds requests on top of that, so neither the command\n * builder nor a menu nested inside one needs a client to name a destination.\n */\n\nimport type {\n CallHeader,\n From,\n PhoneEndpoint,\n SampleRate,\n SipEndpoint,\n StreamEndpoint,\n StreamOptions,\n To,\n VoiceRelayEndpoint,\n} from './models.js';\n\n// ============================================\n// Defaults\n// ============================================\n\n/** Sample rate used when none is given. Matches the agent SDK's `pcm_16000`, so no resampling. */\nexport const DEFAULT_SAMPLE_RATE: SampleRate = 16000;\n\n/** TTS voice used when none is given. `voiceName` is required by the API. */\nexport const DEFAULT_VOICE = 'Emma';\n\n/**\n * Transcription language used when none is given. `sttLanguage` is required on a VOICE_RELAY\n * endpoint (spec line 2948) and is a BCP-47 tag; `en-US` is the schema's own example.\n */\nexport const DEFAULT_STT_LANGUAGE = 'en-US';\n\n/** Stream protocol version. The schema's default and the only value it documents. */\nconst STREAM_PROTOCOL_VERSION = 1;\n\n/**\n * The three `streamOptions` fields, always populated.\n *\n * Never send a partial object: the schema's per-field default is 8 kHz (spec line 2904), and\n * every consumer of a stream this library builds assumes 16 kHz end to end.\n */\nexport function defaultStreamOptions(sampleRate: SampleRate = DEFAULT_SAMPLE_RATE): StreamOptions {\n return { version: STREAM_PROTOCOL_VERSION, codec: 'PCM', sampleRate };\n}\n\n// ============================================\n// Shorthands\n// ============================================\n\n/** A call destination: an E.164 number, a `sip:`/`wss:` URI, or a full endpoint object. */\nexport type Destination = string | To;\n\n/** A call origin: an E.164 number, a `sip:` URI, or a full endpoint object. */\nexport type Origin = string | From;\n\n/** Custom call headers, as a plain map or as the wire array */\nexport type Headers = Record<string, string> | CallHeader[];\n\n// ============================================\n// Destination Helpers\n// ============================================\n\n/**\n * Build a PHONE destination.\n *\n * @param number - E.164 phone number. Spaces and dashes are stripped.\n *\n * @example\n * ```typescript\n * dialPhone('+15551234567'); // { type: 'PHONE', phone: { number: '+15551234567' } }\n * ```\n */\nexport function dialPhone(number: string): PhoneEndpoint {\n return { type: 'PHONE', phone: { number: number.replace(/[\\s-]/g, '') } };\n}\n\n/**\n * Build a SIP destination.\n *\n * @param address - SIP URI (`sip:` or `sips:`)\n * @param options - Transport protocol and custom SIP headers\n *\n * @example\n * ```typescript\n * dialSip('sip:agent@pbx.example.com', { transport: 'TLS' });\n * ```\n */\nexport function dialSip(\n address: string,\n options: { transport?: 'UDP' | 'TCP' | 'TLS'; headers?: Headers } = {}\n): SipEndpoint {\n const callHeaders = toCallHeaders(options.headers);\n return {\n type: 'SIP',\n sip: {\n endpoint: address,\n ...(options.transport && { transport: options.transport }),\n ...(callHeaders && { callHeaders }),\n },\n };\n}\n\n/**\n * Build a STREAM destination — a WebSocket leg carrying real-time audio.\n *\n * `streamOptions` is always sent in full, never partially and never omitted: the schema's\n * per-field default is 8 kHz (spec line 2904), which is not what any consumer of a stream\n * this library builds expects.\n *\n * @param endpoint - WebSocket URL (`ws://` or `wss://`) reachable from the public internet\n * @param options - Sample rate, and headers delivered on the WebSocket upgrade and in the `connect` message\n *\n * @example\n * ```typescript\n * dialStream('wss://example.com/audio', { headers: { 'x-contact-id': 'abc123' } });\n * ```\n */\nexport function dialStream(\n endpoint: string,\n options: { sampleRate?: SampleRate; headers?: Headers } = {}\n): StreamEndpoint {\n const callHeaders = toCallHeaders(options.headers);\n return {\n type: 'STREAM',\n stream: {\n endpoint,\n streamOptions: defaultStreamOptions(options.sampleRate),\n ...(callHeaders && { callHeaders }),\n },\n };\n}\n\n/**\n * Build a VOICE_RELAY destination — platform-side STT and TTS, text over the socket.\n *\n * The opposite trade to {@link dialStream}: Sinch owns the audio pipeline and the\n * application never sees a sample. That also means the application never owns the TTS\n * stream, which is why `@sinch/agents` uses STREAM rather than this.\n *\n * @param endpoint - WebSocket URL that accepts the relay connection. Required by the schema.\n * @param options - Platform voice, transcription language, barge-in and headers\n */\nexport function dialRelay(\n endpoint: string,\n options: {\n ttsVoice?: string;\n sttLanguage?: string;\n enableInterruptions?: boolean;\n headers?: Headers;\n } = {}\n): VoiceRelayEndpoint {\n const callHeaders = toCallHeaders(options.headers);\n return {\n type: 'VOICE_RELAY',\n voiceRelay: {\n endpoint,\n ...(options.enableInterruptions !== undefined && {\n enableInterruptions: options.enableInterruptions,\n }),\n ttsVoice: options.ttsVoice ?? DEFAULT_VOICE,\n sttLanguage: options.sttLanguage ?? DEFAULT_STT_LANGUAGE,\n ...(callHeaders && { callHeaders }),\n },\n };\n}\n\n// ============================================\n// Endpoint Coercion\n// ============================================\n\n/**\n * Coerce a shorthand destination into a v2 endpoint object.\n *\n * @param destination - E.164 number, `sip:`/`ws:` URI, or an endpoint object\n * @throws If a string is neither a phone number nor a recognised URI\n *\n * @example\n * ```typescript\n * toEndpoint('+15551234567'); // { type: 'PHONE', phone: { number: '+15551234567' } }\n * toEndpoint('sip:a@b.com'); // { type: 'SIP', sip: { endpoint: 'sip:a@b.com' } }\n * ```\n */\nexport function toEndpoint(destination: Destination): To {\n if (typeof destination !== 'string') {\n return destination;\n }\n if (/^sips?:/i.test(destination)) {\n return { type: 'SIP', sip: { endpoint: destination } };\n }\n if (/^wss?:\\/\\//i.test(destination)) {\n // streamOptions in full, never omitted: the schema's per-field default is 8 kHz (spec\n // line 2919), and every consumer of a stream this library builds — the agent pipeline\n // above all — assumes pcm_16000 end to end.\n return {\n type: 'STREAM',\n stream: { endpoint: destination, streamOptions: defaultStreamOptions() },\n };\n }\n if (/^\\+?\\d[\\d\\s-]*$/.test(destination)) {\n return { type: 'PHONE', phone: { number: destination.replace(/[\\s-]/g, '') } };\n }\n throw new Error(\n `Cannot interpret '${destination}' as a call destination. Use an E.164 number, a sip: URI, a ws:// URL, or an endpoint object.`\n );\n}\n\n/**\n * Coerce a shorthand origin into a v2 `from` endpoint object.\n *\n * @param origin - E.164 number, `sip:` URI, or an endpoint object\n * @throws If the endpoint cannot originate a call, or if a SIP origin carries keys the\n * `sipFrom` schema (spec line 2800) does not allow\n */\nexport function toOrigin(origin: Origin): From {\n const endpoint = toEndpoint(origin);\n if (endpoint.type === 'STREAM' || endpoint.type === 'VOICE_RELAY') {\n throw new Error(\n 'A call cannot originate from a STREAM or VOICE_RELAY endpoint. Use a phone number or SIP URI.'\n );\n }\n if (endpoint.type === 'SIP') {\n // `from` is `sipFrom`, not `sip`: it takes `endpoint` and `displayName` only, and is\n // additionalProperties:false. Dropping the extra keys silently would send a `from` that\n // does not mean what the caller wrote, so refuse instead.\n const sip = endpoint.sip as { transport?: string; callHeaders?: unknown[] };\n if (sip.transport !== undefined || sip.callHeaders !== undefined) {\n throw new Error(\n 'A SIP origin takes only an endpoint and a displayName — transport and callHeaders belong on the destination, and the API rejects them on `from`.'\n );\n }\n }\n return endpoint;\n}\n\n/**\n * Convert a header map into the wire array form.\n *\n * @param headers - Plain map or wire array\n * @returns The wire array, or `undefined` when there is nothing to send\n */\nexport function toCallHeaders(headers?: Headers): CallHeader[] | undefined {\n if (!headers) {\n return undefined;\n }\n const list = Array.isArray(headers)\n ? headers\n : Object.entries(headers).map(([key, value]) => ({ key, value }));\n return list.length > 0 ? list : undefined;\n}\n","/**\n * Voice API v2 command builder — the one primitive.\n *\n * `svamlCommands` is an ordered list, and the same ordered list appears in six places:\n *\n * | Where | |\n * |---|---|\n * | `POST /calls` | `{ commands: [...] }` |\n * | Webhook response | the same array |\n * | `PATCH /sessions/{id}/calls/{name}` | the same array |\n * | `dial.events.*` | nested |\n * | `menu.menus.*.matches.<key>` | nested |\n * | `menu.menus.*.onFail` | nested |\n *\n * So there is one builder, and everything else is an envelope around it. {@link commands} is\n * a free factory rather than a client method for exactly that reason: four of those six\n * positions are *inside* another command, where no client is in scope and none is needed —\n * a command list depends on no credentials, no host and no project. It is also what keeps\n * this module liftable into a standalone package for the CLI later, as the spec plans.\n *\n * @example\n * ```typescript\n * const flow = commands().say('One moment').bridgeCall('support').hangup();\n *\n * await voice.call(to, { onAnswer: flow }); // POST /calls\n * return toWebhookResponse({ commands: flow.build() });\n * await voice.patch({ callId }, flow); // mid-call\n * ```\n */\n\nimport { DEFAULT_VOICE, toEndpoint, toOrigin, type Destination, type Origin } from './endpoints.js';\nimport type {\n AmdEvents,\n CallEvents,\n Command,\n DialCommand,\n MenuCommand,\n MenuItem,\n MenuPrompt,\n Message,\n MessagesCommand,\n RecordingDestination,\n RecordingEvents,\n RecordingFormat,\n RecordingOptions,\n RecordingType,\n StopMessagesFlags,\n To,\n} from './models.js';\n\n// ============================================\n// Flows\n// ============================================\n\n/**\n * Anything that can stand in for a command list.\n *\n * Three spellings of one idea, because the six positions read differently: a builder value\n * reads best when a flow is named and reused (`{ onAnswer: greeting }`), a callback reads\n * best when it is defined in place (`.match('1', c => c.dial(sales))`), and a bare array is\n * what hand-written command literals already are. Every nesting point in this module and in\n * {@link ../client.js} takes this same type — that is the consistency that matters, rather\n * than forcing one spelling on positions where it reads badly.\n */\nexport type Flow =\n | CommandBuilder\n | Command[]\n | ((builder: CommandBuilder) => CommandBuilder | void);\n\n/**\n * Reduce any {@link Flow} spelling to a command list.\n *\n * @param flow - Builder, callback or literal array\n * @throws If the flow produced no commands — an empty `events` list or an empty `matches`\n * entry is always a mistake, and the API would reject it as one anyway.\n */\nexport function resolveFlow(flow: Flow): Command[] {\n let list: Command[];\n if (typeof flow === 'function') {\n const builder = commands();\n list = (flow(builder) ?? builder).build();\n } else if (Array.isArray(flow)) {\n list = flow;\n } else {\n list = flow.build();\n }\n if (list.length === 0) {\n throw new Error(\n 'Voice v2 flow is empty. Every nested command list needs at least one command — add say(), play(), dial(), hangup() or answer().'\n );\n }\n return list;\n}\n\n// ============================================\n// Dial options and the complete events block\n// ============================================\n\n/** Options for a single TTS message */\nexport interface SayOptions {\n /** Voice name. Defaults to {@link DEFAULT_VOICE}. */\n voiceName?: string;\n /** Set to `SSML` when `text` is an SSML document */\n format?: 'TEXT' | 'SSML';\n}\n\n/**\n * The six per-outcome command lists on a `dial`.\n *\n * Supplying **any** of them switches the platform out of service-webhook mode for **all**\n * of them — see {@link completeEvents}.\n */\nexport interface DialEvents {\n /**\n * Runs when the leg is answered.\n *\n * Required whenever any other event is named: an `events` block detaches the service\n * webhook from every outcome, so a block without this one answers the leg into silence.\n */\n onAnswer?: Flow;\n /** Runs when the callee is busy. Defaults to hangup. */\n onBusy?: Flow;\n /** Runs when the callee rejects. Defaults to hangup. */\n onReject?: Flow;\n /** Runs when the dial timeout elapses without an answer. Defaults to hangup. */\n onTimeout?: Flow;\n /** Runs when the leg is hung up. Never defaulted unless `endOnHangup` names another leg. */\n onHangup?: Flow;\n /** Runs when the leg could not be set up. Defaults to hangup. */\n onFailure?: Flow;\n}\n\n/** Everything a single `dial` command can carry */\nexport interface DialOptions extends DialEvents {\n /** Caller identity presented to the callee */\n from?: Origin;\n /** Seconds to wait for an answer. Maximum 60. */\n timeout?: number;\n /** Maximum call duration in seconds. Maximum 14400. */\n maxDuration?: number;\n /** Identifier for this leg (1-32 chars, no whitespace), unique among live legs */\n callName?: string;\n /**\n * Leg to end when *this* leg hangs up after connecting.\n *\n * This is the only thing that makes `onHangup` default at all. On a single-leg call there\n * is nothing to end — the call is already over — so leaving this unset is what \"onHangup\n * is not defaulted\" means in code.\n */\n endOnHangup?: string;\n /**\n * Leg to end when this leg *never connects* — busy, rejected, timed out or failed.\n *\n * Unset means end this leg, which is right for the first leg of a call: whatever it would\n * have been bridged to has not been dialled yet.\n */\n endOnFailure?: string;\n}\n\n/** The four outcomes that mean \"this leg never connected\" */\nconst FAILURE_KEYS = ['onBusy', 'onReject', 'onTimeout', 'onFailure'] as const;\n\n/** Every key the platform reads off a `dial`'s `events` */\nconst EVENT_KEYS = ['onAnswer', 'onHangup', ...FAILURE_KEYS] as const;\n\n/** The four AMD result outcomes. Unrelated to {@link EVENT_KEYS} despite the shared spelling. */\nconst AMD_EVENT_KEYS = ['onHuman', 'onMachine', 'onBeep', 'onUnknown'] as const;\n\n/**\n * The gate both `dial` and `amd` share: did the caller name any outcome at all?\n *\n * This is the whole of the all-or-nothing rule. Verified in `calling-ng`\n * (`Svaml/Visitors/AddCallBehaviorWebhookVisitor.cs` and `Svaml/SvamlCommandFactory.cs`): every\n * command that carries lifecycle events is built with `OverrideUserCallbacks` set from\n * `command.Events is not null`, and the visitor attaches the service webhook to each outcome\n * only when that flag is false. So the switch is the **presence of the `events` object**, never\n * which keys are inside it — one named outcome detaches the webhook from all of them.\n *\n * @param keys - The outcome names this command carries\n * @param events - What the caller named\n */\nfunction namesAnyEvent<K extends string>(\n keys: readonly K[],\n events: Partial<Record<K, Flow>>\n): boolean {\n return keys.some((key) => events[key] !== undefined);\n}\n\n/**\n * Build a **complete** `events` block, or nothing at all.\n *\n * Verified in `calling-ng` (`AddCallBehaviorWebhookVisitor`): the service webhook is\n * auto-attached to all six event lists exactly when the command's `events` object is\n * absent, and to none of them when it is present. Supplying `onAnswer` alone therefore\n * silently opts out of webhook handling for busy, rejected, timed-out, hung-up and failed —\n * nothing errors, those events simply stop being handled.\n *\n * So this returns `undefined` when the caller named no event at all — declining to\n * short-circuit, and leaving the service webhook in charge — and otherwise fills in the\n * four never-connected outcomes with a hangup. That costs nothing: the platform has already\n * disabled the webhook the moment any event was supplied, so the alternative is not\n * webhook-handled failure, it is *nothing* handling it.\n *\n * `onAnswer` has no default, because a leg that answers has no unambiguous next step — so it\n * is *required* instead. A block without it is the same trap one key smaller: the leg answers,\n * the webhook has already been detached, and nothing at all runs.\n *\n * @param events - The event lists the caller named\n * @param topology - What the calling helper knows about the other leg\n * @returns A complete block, or `undefined` for service-webhook mode\n * @throws If a block would be emitted without `onAnswer`, or if the leg-topology options are\n * set on a dial that names no event — both are silently broken on the wire.\n */\nexport function completeEvents(\n events: DialEvents,\n topology: { endOnHangup?: string; endOnFailure?: string } = {}\n): CallEvents | undefined {\n if (!namesAnyEvent(EVENT_KEYS, events)) {\n // `endOnHangup`/`endOnFailure` are only ever expressed *through* an events block, so with\n // no event named there is nowhere to put them and they would leave silently.\n if (topology.endOnHangup !== undefined || topology.endOnFailure !== undefined) {\n throw new Error(\n 'Voice v2 dial: endOnHangup and endOnFailure are emitted inside the `events` block, and this dial names no event — they would have been dropped silently. Name onAnswer (plus any outcome you want handled inline), or drop them and let the service webhook end the legs.'\n );\n }\n return undefined;\n }\n\n const onNeverConnected: Command[] = [\n { command: 'hangup', ...(topology.endOnFailure && { callName: topology.endOnFailure }) },\n ];\n\n const block: CallEvents = {};\n if (events.onAnswer !== undefined) {\n block.onAnswer = resolveFlow(events.onAnswer);\n }\n for (const key of FAILURE_KEYS) {\n const supplied = events[key];\n block[key] = supplied !== undefined ? resolveFlow(supplied) : onNeverConnected;\n }\n if (events.onHangup !== undefined) {\n block.onHangup = resolveFlow(events.onHangup);\n } else if (topology.endOnHangup) {\n block.onHangup = [{ command: 'hangup', callName: topology.endOnHangup }];\n }\n\n // Checked last so an empty nested flow still reports itself first — that is the more\n // specific mistake, and resolveFlow above has already caught it.\n if (block.onAnswer === undefined) {\n throw new Error(\n 'Voice v2 dial: naming any event detaches the service webhook from all six outcomes, so an `events` block without onAnswer leaves an answered leg with no commands — silence until maxCallDurationSeconds. Add onAnswer, or name no events at all and let the service webhook answer the leg.'\n );\n }\n return block;\n}\n\n/**\n * Build a **complete** `amd` events block, or nothing at all.\n *\n * The same all-or-nothing rule as {@link completeEvents}, confirmed for `amd` in `calling-ng`\n * (`Svaml/Visitors/AddCallBehaviorWebhookVisitor.cs`, `Visit(Amd)`): with\n * `OverrideUserCallbacks` set it iterates the four outcome lists and attaches nothing; without\n * it, it `Attach`es the service webhook to `onHuman`, `onMachine`, `onBeep` and `onUnknown`.\n * `Svaml/SvamlCommandFactory.cs` builds the command as `new Amd(command.Events is not null)`, so\n * the flag is exactly \"the caller sent an `events` object\". Naming `onHuman` alone therefore\n * stops machine, beep and unknown from reaching the webhook, with no error.\n *\n * **Unnamed outcomes default to an empty command list, and that default does nothing at\n * runtime.** Two halves to that, both deliberate:\n *\n * - There is no honest command to default *to*. All four outcomes mean the call is up and\n * something answered — none of them is a failure, so `dial`'s hangup default would end a live,\n * answered call, which is the opposite of what a caller who named only `onHuman` wants. An\n * empty list is the only default that cannot be wrong.\n * - Emitting `onMachine: []` and omitting `onMachine` behave identically, because the platform\n * keys off the presence of `events`, not off its keys. So this buys no behaviour back — what\n * it buys is that the opt-out is **visible**: the body in a log or a bug report shows four\n * outcomes with three of them plainly empty, instead of one key and three invisible holes.\n * The cost is a few bytes on the wire.\n *\n * The actual mitigation is therefore the documentation, not the default: name all four, or name\n * none and leave `call.amd.*` to the service webhook.\n *\n * @param events - The outcomes the caller named\n * @returns A complete block, or `undefined` for service-webhook mode\n */\nfunction completeAmdEvents(events: AmdEventOptions): AmdEvents | undefined {\n if (!namesAnyEvent(AMD_EVENT_KEYS, events)) {\n return undefined;\n }\n\n const block: AmdEvents = {};\n for (const key of AMD_EVENT_KEYS) {\n const flow = events[key];\n block[key] = flow !== undefined ? resolveFlow(flow) : [];\n }\n return block;\n}\n\n/**\n * Build one `dial` command.\n *\n * @param to - Already-coerced destination endpoint\n * @param options - Dial settings, named events and leg topology\n */\nexport function buildDial(to: To, options: DialOptions = {}): DialCommand {\n // A STREAM or VOICE_RELAY leg has no caller identity to present, and neither appears in the\n // `from` union at all (spec line 2693), so `from` is left off entirely.\n const carriesCli = to.type !== 'STREAM' && to.type !== 'VOICE_RELAY';\n const from = carriesCli && options.from ? toOrigin(options.from) : undefined;\n const events = completeEvents(options, options);\n return {\n command: 'dial',\n ...(options.callName && { callName: options.callName }),\n ...(from && { from }),\n to,\n ...(options.timeout !== undefined && { dialTimeoutDurationSeconds: options.timeout }),\n ...(options.maxDuration !== undefined && { maxCallDurationSeconds: options.maxDuration }),\n ...(events && { events }),\n };\n}\n\n// ============================================\n// AMD, webhook and recording options\n// ============================================\n\n/**\n * The four answering-machine-detection outcomes.\n *\n * @remarks\n * These are the AMD *result* events, not a `dial`'s six lifecycle events: they mean the call is\n * up and something answered, so none of them is a failure and none gets a hangup default.\n *\n * **They do share `dial`'s all-or-nothing rule.** Confirmed in `calling-ng`,\n * `Svaml/Visitors/AddCallBehaviorWebhookVisitor.cs` (`Visit(Amd)`) with\n * `Svaml/SvamlCommandFactory.cs` (`new Amd(command.Events is not null)`): sending an `events`\n * object detaches the service webhook from **all four** outcomes, so naming `onHuman` alone\n * silently stops machine, beep and unknown from being handled by anything. Nothing errors.\n *\n * The builder answers that by always emitting a complete four-outcome block once any one is\n * named — see {@link completeAmdEvents} for why the unnamed ones default to an empty list and\n * what that does and does not buy. Name all four, or name none and let the service webhook take\n * `call.amd.*`.\n */\nexport interface AmdEventOptions {\n /** Runs when a human is detected */\n onHuman?: Flow;\n /** Runs when a machine is detected */\n onMachine?: Flow;\n /** Runs when the answering machine's beep is detected */\n onBeep?: Flow;\n /** Runs when detection produced no verdict */\n onUnknown?: Flow;\n}\n\n/** Options for a `webhook` command */\nexport interface WebhookOptions {\n /**\n * URL retried immediately when the primary URL fails. After repeated consecutive failures\n * the platform sends only here until the primary recovers.\n */\n fallbackUrl?: string;\n}\n\n/**\n * Credentials for the storage service a recording is delivered to.\n *\n * @remarks\n * **This is a long-lived secret travelling inside a call flow.** The v2 schema takes the\n * credential as one required colon-delimited string on the `startRecording` command, so it is\n * present in the `POST /calls` body, in any webhook response or `PATCH` that starts a\n * recording, and in every copy of those a log or an error message makes. There is no\n * presigned-URL form and no STS session-token slot — the third component is the region, not a\n * token — so the value cannot be made short-lived and must be treated as being exactly as\n * sensitive as the IAM key it contains.\n *\n * Take it structured, as here, rather than concatenating secrets at the call site, and log\n * v2 bodies only through `redactCredentials`. The client scrubs it out of API error text on\n * its own, which is the one path that would otherwise carry it into a stack trace.\n *\n * @example\n * ```typescript\n * { accessKeyId: 'AKIA...', secretAccessKey: process.env.RECORDING_SECRET!, region: 'eu-central-1' }\n * // → 'AKIA...:<secret>:eu-central-1'\n * ```\n */\nexport interface RecordingCredentials {\n /** Access key id */\n accessKeyId: string;\n /** Secret access key. The sensitive half. */\n secretAccessKey: string;\n /** Storage region, e.g. `eu-central-1` */\n region: string;\n}\n\n/** Everything a `startRecording` command can carry */\nexport interface StartRecordingOptions {\n /** Destination URL, e.g. `s3://voice-recordings-prod/calls` */\n destinationUrl: string;\n /**\n * Credentials for the destination. Prefer the structured form; the raw colon-delimited\n * string is there for credential formats this library does not model.\n */\n credentials: RecordingCredentials | string;\n /**\n * Storage service. Defaults to `AWS`, and is always emitted — the schema lists\n * `destination` as required, whatever its documented default.\n */\n destination?: RecordingDestination;\n /**\n * Identifier for this recording (1-32 chars, no whitespace). Without it the recording can\n * only be stopped by the call disconnecting, never by {@link CommandBuilder.stopRecording}.\n */\n recordingName?: string;\n /** Audio format. The platform defaults to `MP3`; omitted from the body when unset. */\n format?: RecordingFormat;\n /** Streams captured. The platform defaults to `COMBINED`; omitted from the body when unset. */\n recordingType?: RecordingType;\n /**\n * Transcribe the recording to text. Setting this, or {@link transcriptionLocale}, emits\n * `transcriptionOptions`; a locale on its own implies `isEnabled: true`.\n */\n transcribe?: boolean;\n /** BCP-47 language tag for transcription. The platform defaults to `en-US`. */\n transcriptionLocale?: string;\n /**\n * Runs when the recording stops. Note this fires on *stop*, not on delivery — the file may\n * still be in flight to the destination.\n *\n * Unlike a `dial` or an `amd`, naming neither this nor {@link onFailure} does **not** hand the\n * outcome to the service webhook — see {@link RecordingEvents}. Nothing is emitted\n * and nothing is notified.\n */\n onFinish?: Flow;\n /**\n * Runs when the recording could not be started. The only way to hear about a failed recording:\n * there is no service-webhook fallback for this command.\n */\n onFailure?: Flow;\n}\n\n/**\n * Assemble the wire credential string.\n *\n * @throws If a component contains `:`, which would silently shift the other components along\n * and hand the platform a malformed key.\n */\nfunction toCredentials(credentials: RecordingCredentials | string): string {\n if (typeof credentials === 'string') {\n return credentials;\n }\n const parts = [credentials.accessKeyId, credentials.secretAccessKey, credentials.region];\n if (parts.some((part) => part.includes(':'))) {\n throw new Error(\n 'Voice v2 startRecording credentials are joined with colons, so no component may contain one. Pass the pre-joined string instead if your storage service needs a different format.'\n );\n }\n return parts.join(':');\n}\n\n/** Build the wire `recordingOptions` object. */\nfunction toRecordingOptions(options: StartRecordingOptions): RecordingOptions {\n const transcribing =\n options.transcribe !== undefined || options.transcriptionLocale !== undefined;\n return {\n ...(options.format && { format: options.format }),\n ...(options.recordingType && { recordingType: options.recordingType }),\n destination: options.destination ?? 'AWS',\n destinationUrl: options.destinationUrl,\n credentials: toCredentials(options.credentials),\n ...(transcribing && {\n transcriptionOptions: {\n isEnabled: options.transcribe ?? true,\n ...(options.transcriptionLocale && { locale: options.transcriptionLocale }),\n },\n }),\n };\n}\n\n// ============================================\n// Prompts\n// ============================================\n\n/** Anything that can stand in for a menu prompt: a builder, a callback, or plain text. */\nexport type PromptFlow = string | PromptBuilder | ((prompt: PromptBuilder) => PromptBuilder | void);\n\n/** Collects the messages a menu plays, and whether a keypress may cut them short. */\nexport class PromptBuilder {\n private readonly messages: Message[] = [];\n private barge: boolean | undefined;\n\n /**\n * Speak text.\n *\n * @param text - Text to synthesise, or an SSML document when `format` is `SSML`\n * @param options - Voice and format overrides\n */\n say(text: string, options: SayOptions = {}): this {\n this.messages.push(sayMessage(text, options));\n return this;\n }\n\n /**\n * Play an audio file.\n *\n * @param url - Publicly reachable URL of the audio file\n */\n play(url: string): this {\n this.messages.push({ type: 'PLAY', play: { url } });\n return this;\n }\n\n /**\n * Let input interrupt the prompt instead of waiting for it to finish. Emits\n * `allowBargeIn`, which the platform defaults to `true`.\n *\n * @param enabled - Pass `false` to state the opposite explicitly\n */\n bargeIn(enabled = true): this {\n this.barge = enabled;\n return this;\n }\n\n /** Emit the prompt. @throws If nothing was queued to play */\n build(): MenuPrompt {\n if (this.messages.length === 0) {\n throw new Error('Voice v2 menu prompt is empty. Call say() or play() on it.');\n }\n return {\n messages: [...this.messages],\n ...(this.barge !== undefined && { allowBargeIn: this.barge }),\n };\n }\n}\n\nfunction resolvePrompt(prompt: PromptFlow): MenuPrompt {\n if (typeof prompt === 'string') {\n return new PromptBuilder().say(prompt).build();\n }\n if (typeof prompt === 'function') {\n const builder = new PromptBuilder();\n return (prompt(builder) ?? builder).build();\n }\n return prompt.build();\n}\n\n// ============================================\n// Menus\n// ============================================\n\n/**\n * One named menu: a prompt, the input rules, and what each input does.\n *\n * A menu that defines neither `match()` nor `onFail()` falls through to the service webhook\n * with the collected input, arriving as `call.menu`.\n */\nexport class MenuItemBuilder {\n private readonly item: MenuItem = {};\n private readonly matchOrder: string[] = [];\n private readonly matches: Record<string, Command[]> = {};\n\n /**\n * Prompt played when the menu is entered.\n *\n * @param prompt - Plain text, a {@link PromptBuilder}, or a callback receiving one\n */\n prompt(prompt: PromptFlow): this {\n this.item.prompt = resolvePrompt(prompt);\n return this;\n }\n\n /**\n * Prompt played on each retry. Falls back to `prompt` when unset.\n *\n * @param prompt - Plain text, a {@link PromptBuilder}, or a callback receiving one\n */\n repeatPrompt(prompt: PromptFlow): this {\n this.item.repeatPrompt = resolvePrompt(prompt);\n return this;\n }\n\n /**\n * How long to wait for input before repeating.\n *\n * @param seconds - Seconds of silence that count as no input\n */\n inputTimeout(seconds: number): this {\n this.item.inputTimeoutDurationSeconds = seconds;\n return this;\n }\n\n /**\n * How many times the prompt repeats before `onFail` runs.\n *\n * @param times - Repeat count\n */\n repeatCount(times: number): this {\n this.item.repeatCount = times;\n return this;\n }\n\n /**\n * Fewest input characters collected before the menu evaluates them. Emits\n * `minimumInputLength`. 1-100, default 1.\n *\n * @param count - Minimum input length\n */\n minLength(count: number): this {\n this.item.minimumInputLength = count;\n return this;\n }\n\n /**\n * Input character count that triggers evaluation. Emits `maximumInputLength`. 1-100,\n * default 1.\n *\n * @param count - Maximum input length\n */\n maxLength(count: number): this {\n this.item.maximumInputLength = count;\n return this;\n }\n\n /**\n * Character sequence that ends input and triggers evaluation immediately, e.g. `#`.\n *\n * The pair to {@link maxLength}: with a range of accepted lengths, this is how a shorter\n * entry is submitted without waiting out `inputTimeout`. The sequence itself is part of\n * the input the `matches` keys see.\n *\n * @param sequence - Digits, `*` and `#` only, up to 10 characters\n */\n terminatedBy(sequence: string): this {\n this.item.terminatingSequence = sequence;\n return this;\n }\n\n /**\n * What one input does.\n *\n * Keys may be literal digits or regular expressions, and the platform evaluates them in\n * definition order with first match winning — so the order these are written in is part of\n * the behaviour, not decoration. {@link build} refuses to emit a menu whose keys JSON\n * cannot carry in that order; see the error it throws.\n *\n * @param pattern - Digits, or a regular expression source\n * @param flow - Commands to run on a match\n */\n match(pattern: string, flow: Flow): this {\n if (!(pattern in this.matches)) {\n this.matchOrder.push(pattern);\n }\n this.matches[pattern] = resolveFlow(flow);\n return this;\n }\n\n /**\n * Commands to run once the caller is out of attempts.\n *\n * @param flow - Commands to run\n */\n onFail(flow: Flow): this {\n this.item.onFail = resolveFlow(flow);\n return this;\n }\n\n /**\n * Emit the menu.\n *\n * @throws If the `matches` keys cannot be serialised in the order they were written\n */\n build(): MenuItem {\n const item: MenuItem = { ...this.item };\n if (this.matchOrder.length > 0) {\n // JSON objects cannot hold an arbitrary key order: JavaScript — and therefore\n // JSON.stringify — always emits integer-like keys first, in ascending numeric order,\n // before the rest in insertion order. `matches` is evaluated first-match-wins, so a\n // silently reordered map is a behaviour change, not a formatting one. Refuse instead.\n const emitted = Object.keys(this.matches);\n const reordered = emitted.some((key, index) => key !== this.matchOrder[index]);\n if (reordered) {\n throw new Error(\n `Voice v2 menu matches are evaluated in definition order, but JSON cannot carry these keys in the order they were written (${this.matchOrder.join(', ')} would be sent as ${emitted.join(', ')}). Numeric keys always sort first, ascending. Write them in ascending numeric order, or use a regular-expression key such as '^1$'.`\n );\n }\n item.matches = { ...this.matches };\n }\n return item;\n }\n}\n\n// ============================================\n// Command Builder\n// ============================================\n\n/**\n * Ordered `svamlCommands` list.\n *\n * Commands come out in the order they were written. Consecutive `say` and `play` calls\n * collect into one `messages` command — `messages` is non-blocking in v2, so two separate\n * commands would play over each other instead of in sequence.\n *\n * A `hangup()` written directly after messages rides those messages' `onFinish`. That is how\n * \"say this, then hang up\" is expressed against a non-blocking command: a standalone `hangup`\n * queued next would fire while the audio was still playing. Written anywhere else it is a\n * plain `hangup` command in exactly that position, so `hangup().say('x')` emits hangup then\n * say — literally what it reads, and, as written, never reached on a live call.\n */\nexport class CommandBuilder {\n private readonly list: Command[] = [];\n private readonly pending: Message[] = [];\n\n /**\n * Speak text on the call.\n *\n * @param text - Text to synthesise, or an SSML document when `format` is `SSML`\n * @param options - Voice and format overrides\n */\n say(text: string, options: SayOptions = {}): this {\n this.pending.push(sayMessage(text, options));\n return this;\n }\n\n /**\n * Play an audio file on the call.\n *\n * @param url - Publicly reachable URL of the audio file\n */\n play(url: string): this {\n this.pending.push({ type: 'PLAY', play: { url } });\n return this;\n }\n\n /**\n * End the call at this point in the sequence.\n *\n * Messages queued before it still play in full — and end the call whether they finish or\n * fail, since a failed playback would otherwise leave the call with nothing to do.\n * Anything queued after it is emitted after it, and on a live call is never reached.\n *\n * @param callName - Leg to end. Ends the current leg when omitted.\n */\n hangup(callName?: string): this {\n const command = (): Command => ({ command: 'hangup', ...(callName && { callName }) });\n if (this.pending.length > 0) {\n this.list.push({\n command: 'messages',\n messages: this.pending.splice(0),\n // Both outcomes, for the same reason a `dial`'s events block is completed: `messages`\n // models `onFinish` *and* `onFailure`, and a playback that fails — an audio URL the\n // platform cannot fetch — would otherwise reach neither this list nor the service\n // webhook, leaving the call sitting with no next command.\n events: { onFinish: [command()], onFailure: [command()] },\n });\n } else {\n this.list.push(command());\n }\n return this;\n }\n\n /** Explicitly answer an inbound leg. */\n answer(): this {\n return this.push({ command: 'answer' });\n }\n\n /**\n * Add the current leg to a named bridge, creating the bridge on first reference.\n *\n * @param bridgeName - Bridge name (1-32 chars, no whitespace)\n */\n bridgeCall(bridgeName: string): this {\n return this.push({ command: 'bridgeCall', bridgeName });\n }\n\n /**\n * Dial another leg. Non-blocking — two dials in one list ring two legs in parallel.\n *\n * @param to - Who to call\n * @param options - Dial settings, named events and leg topology\n */\n dial(to: Destination, options: DialOptions = {}): this {\n return this.push(buildDial(toEndpoint(to), options));\n }\n\n /**\n * Collect DTMF input against a named menu. Blocking.\n *\n * Consecutive `menu()` calls extend one `menu` command, so a multi-level IVR is written as\n * a run of them and `gotoMenu` jumps between the names. The first one names `startMenu`.\n * Anything written between two menus (a `say`, a `dial`) breaks the run, and the next\n * `menu()` starts a second command — the list stays in the order it was written.\n *\n * @param name - Menu name, referenced by {@link gotoMenu} and reported on `call.menu`\n * @param define - Callback receiving the {@link MenuItemBuilder} for this menu\n *\n * @example\n * ```typescript\n * commands().menu('main', (m) =>\n * m\n * .prompt((p) => p.say('Press 1 for sales or 2 for support').bargeIn())\n * .match('1', (c) => c.dial(sales))\n * .match('2', (c) => c.dial(support))\n * .onFail((c) => c.say('Sorry, goodbye').hangup())\n * );\n * ```\n */\n menu(name: string, define: (menu: MenuItemBuilder) => MenuItemBuilder | void): this {\n this.flush();\n const builder = new MenuItemBuilder();\n const item = (define(builder) ?? builder).build();\n const last = this.list[this.list.length - 1];\n if (last && last.command === 'menu') {\n last.menus[name] = item;\n return this;\n }\n const command: MenuCommand = { command: 'menu', startMenu: name, menus: { [name]: item } };\n this.list.push(command);\n return this;\n }\n\n /**\n * Jump to another menu in the enclosing `menu` command. Legal only inside menu execution.\n *\n * @param menuName - Menu to enter\n */\n gotoMenu(menuName: string): this {\n return this.push({ command: 'gotoMenu', menuName });\n }\n\n /**\n * Wait before running the next command. Blocking.\n *\n * The call stays connected and audio is unaffected — this delays the *script*, not the\n * media. So it is the way to let a non-blocking command get somewhere before the next one\n * runs: a beat after `amd` reports a beep, before the message that leaves the voicemail.\n *\n * @param durationMilliseconds - How long to wait, in milliseconds. Minimum 1.\n * @throws If the duration is below the schema's minimum of 1\n */\n pause(durationMilliseconds: number): this {\n if (!Number.isInteger(durationMilliseconds) || durationMilliseconds < 1) {\n throw new Error(\n `Voice v2 pause takes a whole number of milliseconds, at least 1 (got ${durationMilliseconds}).`\n );\n }\n return this.push({ command: 'pause', durationMilliseconds });\n }\n\n /**\n * Stop a named `messages` sequence. Non-blocking.\n *\n * Targets a sequence by the `messagesName` it was started under, so it is only reachable\n * from a later command list — a `PATCH` on a live call, or a `dial` event — never from the\n * same list that queued the messages.\n *\n * @param messagesName - Sequence to stop (1-32 chars, no whitespace)\n * @param flags - `ONLY_PLAYING` cancels the current message and lets the queue continue.\n * Omitted, the platform applies `ALL_FROM_NOW_ON` and the whole queue goes.\n */\n stopMessages(messagesName: string, flags?: StopMessagesFlags): this {\n return this.push({ command: 'stopMessages', messagesName, ...(flags && { flags }) });\n }\n\n /**\n * Run answering machine detection on the call. Non-blocking.\n *\n * Detection runs in parallel with the rest of the list; the verdict arrives on one of the\n * four events, or — with no events named — as a `call.amd.*` webhook.\n *\n * These four are the AMD *result* outcomes, so none of them gets a hangup default the way a\n * `dial`'s never-connected outcomes do. They do follow `dial`'s all-or-nothing rule: naming\n * any one of them detaches the service webhook from all four, so this emits a **complete**\n * block once any is named, with the rest as empty lists. Confirmed in `calling-ng` — see\n * {@link AmdEventOptions}.\n *\n * @param events - Commands to run per detection outcome. Omit entirely for webhook mode.\n *\n * @example\n * ```typescript\n * commands()\n * .amd({\n * onHuman: (c) => c.say('Hi, do you have a moment?'),\n * onMachine: (c) => c.say('Sorry we missed you.').hangup(),\n * onBeep: (c) => c.pause(500).say('Sorry we missed you.').hangup(),\n * onUnknown: (c) => c.say('Hi, do you have a moment?'),\n * })\n * .say('Connecting you now.');\n *\n * // Naming none of them leaves all four to the service webhook as `call.amd.*`.\n * commands().amd();\n * ```\n */\n amd(events: AmdEventOptions = {}): this {\n const block = completeAmdEvents(events);\n return this.push({ command: 'amd', ...(block && { events: block }) });\n }\n\n /**\n * Ask the application what to do next. **Blocking** — the call waits for the response.\n *\n * The event is delivered as `call.webhook.<webhookName>`, so `webhookName: 'escalate'`\n * arrives as `'call.webhook.escalate'`. `Client.onCall` routes those by name to a handler\n * registered under `webhooks`, and to `manage` when no name matches.\n *\n * @param webhookName - Name for this event (1-64 chars, no whitespace)\n * @param url - URL to call. The platform allows it 5 seconds to answer.\n * @param options - Fallback URL\n *\n * @example\n * ```typescript\n * commands().say('One moment.').webhook('escalate', 'https://acme.com/voice');\n *\n * export const handler = voice.onCall({\n * webhooks: { escalate: () => commands().dial('+15550001111') },\n * });\n * ```\n */\n webhook(webhookName: string, url: string, options: WebhookOptions = {}): this {\n return this.push({\n command: 'webhook',\n webhookName,\n url,\n ...(options.fallbackUrl && { fallbackUrl: options.fallbackUrl }),\n });\n }\n\n /**\n * Start recording the call. Non-blocking.\n *\n * **The credential is a long-lived storage secret carried inside the command body** — the\n * schema requires it and offers no short-lived alternative. See {@link RecordingCredentials}\n * before logging anything a `startRecording` is part of.\n *\n * @param options - Destination, credentials, encoding, transcription and outcome events\n * @throws If a structured credential component contains a colon\n *\n * @example\n * ```typescript\n * commands().startRecording({\n * recordingName: 'support',\n * destinationUrl: 's3://voice-recordings-prod/calls',\n * credentials: {\n * accessKeyId: process.env.RECORDING_KEY_ID!,\n * secretAccessKey: process.env.RECORDING_SECRET!,\n * region: 'eu-central-1',\n * },\n * transcribe: true,\n * });\n * ```\n */\n startRecording(options: StartRecordingOptions): this {\n const events: RecordingEvents = {};\n if (options.onFinish !== undefined) {\n events.onFinish = resolveFlow(options.onFinish);\n }\n if (options.onFailure !== undefined) {\n events.onFailure = resolveFlow(options.onFailure);\n }\n return this.push({\n command: 'startRecording',\n ...(options.recordingName && { recordingName: options.recordingName }),\n recordingOptions: toRecordingOptions(options),\n ...(Object.keys(events).length > 0 && { events }),\n });\n }\n\n /**\n * Stop a named recording. Non-blocking.\n *\n * A recording started without a `recordingName` cannot be targeted at all — it ends when\n * the call disconnects and not before.\n *\n * @param recordingName - Recording to stop (1-32 chars, no whitespace)\n */\n stopRecording(recordingName: string): this {\n return this.push({ command: 'stopRecording', recordingName });\n }\n\n /**\n * Append a hand-built command — the escape hatch for anything not modelled here.\n *\n * @param commands - Commands to append, in order\n */\n add(...commands: Command[]): this {\n return this.push(...commands);\n }\n\n /**\n * Emit the command list.\n *\n * Repeatable and non-consuming: the builder is a description of a flow, not a one-shot\n * handle, so the same one can be sent twice or nested in two places.\n */\n build(): Command[] {\n const out = [...this.list];\n if (this.pending.length > 0) {\n out.push({ command: 'messages', messages: [...this.pending] });\n }\n return out;\n }\n\n private push(...commands: Command[]): this {\n this.flush();\n this.list.push(...commands);\n return this;\n }\n\n private flush(): void {\n if (this.pending.length > 0) {\n const messages: MessagesCommand = { command: 'messages', messages: this.pending.splice(0) };\n this.list.push(messages);\n }\n }\n}\n\n/**\n * Start a command list.\n *\n * @example\n * ```typescript\n * const flow = commands().say('One moment, connecting you').bridgeCall('support');\n * ```\n */\nexport function commands(): CommandBuilder {\n return new CommandBuilder();\n}\n\n// ============================================\n// Helpers\n// ============================================\n\nfunction sayMessage(text: string, options: SayOptions): Message {\n return {\n type: 'SAY',\n say: {\n text,\n voiceName: options.voiceName ?? DEFAULT_VOICE,\n ...(options.format && { format: options.format }),\n },\n };\n}\n","/**\n * Voice API v2 call plan\n *\n * One internal representation of a call flow with two emit targets:\n * a call-create body for `POST /v2/projects/{projectId}/calls`, and a\n * webhook-response body returned from a webhook handler.\n *\n * The two are not the same object. `callRequest` is `additionalProperties: false`\n * and accepts only `commands`, while a webhook response may also carry `callName`\n * and call-level `events`. Keeping the plan separate from both is what makes that\n * difference explicit instead of accidental.\n *\n * @example\n * ```typescript\n * const plan: Plan = {\n * commands: [{ command: 'hangup' }],\n * callName: 'incoming',\n * };\n *\n * toCallRequest(plan); // { commands: [...] } — callName dropped\n * toWebhookResponse(plan); // { commands: [...], callName } — callName kept\n * ```\n */\n\nimport type { CallRequest, Command, WebhookResponse } from './models.js';\n\n// ============================================\n// Plan\n// ============================================\n\n/**\n * Emit-target-agnostic description of a call flow.\n *\n * Build one of these with the client's planning methods, then hand it to\n * {@link toCallRequest} or {@link toWebhookResponse}.\n */\nexport interface Plan {\n /** Ordered command list. Must contain at least one command. */\n commands: Command[];\n /**\n * Name for the inbound leg. Webhook responses only — the API ignores it\n * everywhere except a response to `call.incoming`, and `POST /calls` rejects it.\n */\n callName?: string;\n /**\n * Commands to run when the call hangs up. Webhook responses only; on a\n * call-create body the equivalent lives on the `dial` command's `events`.\n */\n onHangup?: Command[];\n}\n\n// ============================================\n// Emitters\n// ============================================\n\n/**\n * Emit a plan as a `POST /v2/projects/{projectId}/calls` body.\n *\n * Drops `callName` and `onHangup`: the `callRequest` schema forbids them and the\n * API rejects unknown keys with a 400.\n *\n * @param plan - Call flow to serialise\n * @throws If the plan has no commands\n *\n * @example\n * ```typescript\n * const body = toCallRequest({ commands: [{ command: 'hangup' }] });\n * // { commands: [{ command: 'hangup' }] }\n * ```\n */\nexport function toCallRequest(plan: Plan): CallRequest {\n assertCommands(plan);\n return { commands: plan.commands };\n}\n\n/**\n * Emit a plan as a webhook-response body.\n *\n * The response is an object wrapping a `commands` array, not a bare array.\n *\n * @param plan - Call flow to serialise\n * @throws If the plan has no commands\n *\n * @example\n * ```typescript\n * const body = toWebhookResponse({\n * commands: [{ command: 'answer' }],\n * callName: 'incoming',\n * onHangup: [{ command: 'hangup' }],\n * });\n * // { commands: [...], callName: 'incoming', events: { onHangup: [...] } }\n * ```\n */\nexport function toWebhookResponse(plan: Plan): WebhookResponse {\n assertCommands(plan);\n const response: WebhookResponse = { commands: plan.commands };\n if (plan.callName) {\n response.callName = plan.callName;\n }\n if (plan.onHangup && plan.onHangup.length > 0) {\n response.events = { onHangup: plan.onHangup };\n }\n return response;\n}\n\nfunction assertCommands(plan: Plan): void {\n if (!plan.commands || plan.commands.length === 0) {\n throw new Error(\n 'Voice v2 plan requires at least one command. Build one with commands() — say(), play(), dial(), answer() or hangup() — or use call()/callWithStream()/bridge() on the client.'\n );\n }\n}\n","/**\n * Dialling a party into a live call's bridge — the one thing v2 can do that v1 cannot.\n *\n * v1 can hang a leg up and it can play into one, but it cannot add a new leg to a call that\n * is already up. v2 can: a `PATCH` runs commands in the context of a live leg, and a `dial`\n * whose `onAnswer` joins the bridge the call is already using puts a third party on it\n * without disturbing anyone already there.\n *\n * This lives in `core/` rather than in a caller because none of it falls out of an OpenAPI\n * generator. The dial is four lines; the leg-aware failure handling around it is the part\n * that took reading the platform's own source to get right, and it is wrong by default.\n */\n\nimport { commands } from './commands.js';\nimport { type Destination, type Origin } from './endpoints.js';\nimport type { Command } from './models.js';\n\n/**\n * The bridge every call this package builds joins unless told otherwise.\n *\n * Lives here rather than in `client.ts` because both the transfer builder and the client\n * need it, and the client is the one that imports — the other direction would be a cycle.\n */\nexport const DEFAULT_BRIDGE_NAME = 'bridge';\n\n/** Name given to the leg a transfer dials, when the caller does not name it. */\nexport const DEFAULT_TRANSFER_LEG = 'transfer';\n\n/**\n * Seconds to wait for the transferred-to party before giving up.\n *\n * Not the platform's default — it is the one this operation wants. Somebody has just been\n * told they are being put through and is listening to nothing while this rings, so the wait\n * is bounded well inside the 60-second maximum.\n */\nconst DEFAULT_TRANSFER_TIMEOUT = 30;\n\n/** Options for {@link buildTransferCommands} and {@link Client.transfer}. */\nexport interface TransferOptions {\n /**\n * Bridge the live legs are already joined in. Defaults to {@link DEFAULT_BRIDGE_NAME}.\n *\n * Bridges are **session-scoped**, so this default is safe rather than merely convenient:\n * `bridgeCall` joins the current call to a bridge \"in the same session\", and the session\n * is pinned by the patch target. Two unrelated calls both defaulting to `bridge` are in\n * two different sessions and therefore two different bridges — there is no way for the\n * default to connect strangers.\n *\n * Pass it explicitly for a call whose bridge was named — `bridgeName` on `bridge()`,\n * `callWithStream()` or `callWithRelay()` — or for a call this package did not place.\n * Getting it wrong is quiet: the new leg lands in a freshly created, empty bridge and\n * hears silence, since the platform creates a bridge on demand rather than failing.\n */\n bridgeName?: string;\n /** Caller identity presented to the party being dialled */\n from?: Origin;\n /** Seconds to wait for an answer. Defaults to 30; the platform maximum is 60. */\n timeout?: number;\n /**\n * Name for the new leg. Defaults to {@link DEFAULT_TRANSFER_LEG}.\n *\n * Must be unique among the session's live legs. Name it when something downstream reads\n * leg names off the webhook payload and has to tell this leg apart from the rest.\n */\n callName?: string;\n /**\n * Leg to end when the dialled party never answers — busy, rejected, timed out, failed —\n * or hangs up after the handover.\n *\n * The one thing this operation cannot infer, and the one that matters most. See\n * {@link buildTransferCommands} for what happens when it is left unset.\n */\n endLeg?: string;\n}\n\n/**\n * Commands that dial a party into a live call's existing bridge.\n *\n * The new leg joins the bridge the call is already using, so everything already on it stays\n * attached. There is deliberately no leading `bridgeCall`: that would *move* the addressed\n * leg into a new bridge and drop whoever it is currently talking to. The bridge already\n * exists — the new leg just joins it.\n *\n * Every outcome that is not an answer ends {@link TransferOptions.endLeg}, and so does the\n * dialled party hanging up afterwards. That is the whole reason this is a helper rather than\n * four inline lines. Somebody has just been told they are being put through; without it a\n * busy or unanswered number leaves them on a live, billed call with nobody on the other side\n * of the bridge and no command left to run — silence until they hang up themselves. Which\n * leg to end is caller-specific — for an agent it is the media leg, whose own `onHangup`\n * cascades and ends the call — so it is an option rather than a guess.\n *\n * Leaving it unset does not hand the outcome back to the service webhook: naming `onAnswer`\n * has already detached the webhook from all six outcomes, so the four failures fall to a bare\n * hangup of the leg that never connected and `onHangup` is not emitted at all. That is the\n * stranding case above. Set it unless you have arranged for something else to end the call.\n *\n * `onHangup` is the one an earlier version of this omitted, which left a complete-looking\n * events block that was not one: naming any outcome detaches the service webhook from *all*\n * of them, so the unnamed ones reached nothing at all.\n *\n * @param to - Party to dial: an E.164 number, a `sip:` URI, or an endpoint object\n * @param options - Bridge, caller id, dial timeout, leg names\n *\n * @example\n * ```typescript\n * const commands = buildTransferCommands('+15550001111', { endLeg: 'origin' });\n * await client.patch({ sessionId, callName: 'origin' }, commands);\n * ```\n */\nexport function buildTransferCommands(to: Destination, options: TransferOptions = {}): Command[] {\n const bridgeName = options.bridgeName ?? DEFAULT_BRIDGE_NAME;\n return commands()\n .dial(to, {\n callName: options.callName ?? DEFAULT_TRANSFER_LEG,\n ...(options.from !== undefined && { from: options.from }),\n timeout: options.timeout ?? DEFAULT_TRANSFER_TIMEOUT,\n onAnswer: (c) => c.bridgeCall(bridgeName),\n // Two legs, so both defaults are leg-aware rather than a bare hangup of this one.\n ...(options.endLeg !== undefined && {\n endOnHangup: options.endLeg,\n endOnFailure: options.endLeg,\n }),\n })\n .build();\n}\n","/**\n * Voice API v2 Client for Sinch Functions\n *\n * Voice v1 cannot put a WebSocket media stream on an outbound call: `connectStream`\n * is a SVAML action scoped to the incoming-call callback, and an outbound call\n * answers through ACE. Voice API v2 makes STREAM a first-class endpoint type on\n * any leg in either direction, so the way to stream audio on a call that has a\n * human on it is to dial the human, then dial a second leg to a WebSocket and\n * bridge the two. `callWithStream` builds exactly that.\n *\n * Everything this client sends is an envelope around one ordered `svamlCommands` list, built\n * by {@link commands}. The client's job is the envelope; the credentials and the HTTP belong to\n * the {@link CallTransport} it holds, which is the line the SDK will eventually be swapped in on.\n *\n * @example\n * ```typescript\n * import * as v2 from '@sinch/functions-runtime/voice/v2';\n *\n * const voice = v2.createClient(context);\n *\n * // Call a human and stream both directions to our own WebSocket handler\n * await voice.callWithStream('+15559876543', '/media');\n *\n * // Inline flow, no webhook round-trip\n * await voice.call('+15559876543', {\n * from: '+15551234567',\n * onAnswer: (c) => c.say('Your appointment is confirmed.').hangup(),\n * });\n *\n * // Named events omitted entirely — the service webhook decides what happens\n * await voice.call('+15559876543', { from: '+15551234567' });\n * ```\n */\n\nimport type { ClientContext } from './context.js';\nimport type { CallTransport } from './transport.js';\nimport { HttpTransport } from '../wire/http.js';\nimport {\n buildDial,\n commands,\n resolveFlow,\n type DialEvents,\n type Flow,\n CommandBuilder,\n} from './commands.js';\nimport {\n defaultStreamOptions,\n dialRelay,\n toCallHeaders,\n toEndpoint,\n type Destination,\n type Headers,\n type Origin,\n} from './endpoints.js';\nimport type { Plan } from './plan.js';\nimport { toCallRequest, toWebhookResponse } from './plan.js';\nimport { buildTransferCommands, DEFAULT_BRIDGE_NAME, type TransferOptions } from './transfer.js';\nimport type {\n CallResponse,\n Command,\n PatchTarget,\n SampleRate,\n To,\n WebhookRequest,\n WebhookResponse,\n} from './models.js';\n\n// ============================================\n// Defaults\n// ============================================\n\nconst ORIGIN_LEG = 'origin';\nconst STREAM_LEG = 'stream';\nconst RELAY_LEG = 'relay';\n\n// ============================================\n// Options\n// ============================================\n\n/** Construction options for {@link Client} */\nexport interface Options {\n /** Sinch project id. Defaults to `PROJECT_ID`, then `context.config.projectId`. */\n projectId?: string;\n /** Access Key ID (Basic auth username). Defaults to `PROJECT_ID_API_KEY`. */\n keyId?: string;\n /** Access Key Secret (Basic auth password). Defaults to `PROJECT_ID_API_SECRET`. */\n keySecret?: string;\n /** API host. Defaults to `https://voice.api.sinch.com`; set a regional host to skip the redirect. */\n host?: string;\n /** Public base URL of this function, used to resolve relative stream paths. Defaults to `context.host`. */\n publicUrl?: string;\n /** Injected fetch, for tests. Defaults to `globalThis.fetch`. */\n fetch?: typeof globalThis.fetch;\n}\n\n/** Options shared by the call-creating helpers */\nexport interface CallOptions {\n /** Caller identity presented to the callee */\n from?: Origin;\n /** Seconds to wait for an answer. Maximum 60. */\n timeout?: number;\n /** Maximum call duration in seconds. Maximum 14400. */\n maxDuration?: number;\n}\n\n/**\n * Options for {@link Client.call}.\n *\n * Naming **any** event switches the platform out of service-webhook mode for every event —\n * see `completeEvents`. Naming none leaves the service webhook in charge, which is the mode\n * `callBehavior: WEBHOOK` on the service configures and the only mode inbound calls have.\n * Inline events are an optimisation on top of it, not an alternative to it.\n */\nexport interface PlaceCallOptions extends CallOptions, DialEvents {\n /** Name for the dialled leg. Defaults to `origin`. */\n callName?: string;\n}\n\n/** Options for {@link Client.callWithStream} */\nexport interface StreamCallOptions extends CallOptions {\n /** Headers delivered on the WebSocket upgrade and in the `connect` message */\n headers?: Headers;\n /** Audio sampling rate. Defaults to {@link DEFAULT_SAMPLE_RATE}. */\n sampleRate?: SampleRate;\n /** Bridge name joining the two legs. Defaults to `bridge`. */\n bridgeName?: string;\n}\n\n/** Options for {@link Client.callWithRelay} */\nexport interface RelayCallOptions extends CallOptions {\n /** Platform TTS voice, e.g. `Emma`. Required on the wire; defaults to `DEFAULT_VOICE`. */\n ttsVoice?: string;\n /**\n * BCP-47 language tag for speech-to-text, e.g. `en-US`. Required on the wire; defaults to\n * {@link DEFAULT_STT_LANGUAGE}.\n */\n sttLanguage?: string;\n /** Let the caller talk over the platform's TTS. The platform defaults this to `true`. */\n enableInterruptions?: boolean;\n /** Headers delivered on the WebSocket upgrade and in the `connect` message */\n headers?: Headers;\n /** Bridge name joining the two legs. Defaults to `bridge`. */\n bridgeName?: string;\n}\n\n/** Options for {@link Client.bridge} */\nexport interface BridgeOptions extends CallOptions {\n /** Bridge name joining the two legs. Defaults to `bridge`. */\n bridgeName?: string;\n}\n\n// ============================================\n// Webhook Dispatch\n// ============================================\n\n/** What a webhook handler may return. Returning nothing responds with `204 No Content`. */\nexport type HandlerResult = Plan | Command[] | CommandBuilder | void | undefined;\n\n/** A single webhook handler */\nexport type WebhookHandler = (event: WebhookRequest) => HandlerResult | Promise<HandlerResult>;\n\n/**\n * Handlers keyed by call lifecycle stage.\n *\n * These are the v1 callback names carried over. The v2 event they map to is\n * listed in {@link EVENT_MAP}.\n */\nexport interface CallHandlers {\n /** `call.incoming` — an inbound call arrived (the v1 ICE callback) */\n incoming?: WebhookHandler;\n /** `call.answered` — an outbound call was answered (the v1 ACE callback) */\n answered?: WebhookHandler;\n /** `call.menu` and `call.webhook.*` — a mid-call decision point (the v1 PIE callback) */\n manage?: WebhookHandler;\n /** `call.hangup` and `call.failed` — the call ended (the v1 DICE callback) */\n completed?: WebhookHandler;\n /**\n * Handlers for `webhook` commands, keyed by the `webhookName` they were raised under.\n *\n * A `webhook` command names its own event: `webhook('escalate', url)` is delivered as\n * `call.webhook.escalate`. Registering the handler under the same name is what closes that\n * loop — without it every `webhook` command in a function funnels into the single `manage`\n * handler, which then has to re-parse the event string to tell them apart.\n *\n * Checked before `manage`, which still claims any `call.webhook.*` name not listed here.\n */\n webhooks?: Record<string, WebhookHandler>;\n /** Any event none of the above claims */\n fallback?: WebhookHandler;\n}\n\n/**\n * A lifecycle handler slot — every key of {@link CallHandlers} except `webhooks`, which is a\n * map of handlers rather than one.\n */\nexport type HandlerKey = Exclude<keyof CallHandlers, 'webhooks'>;\n\n/**\n * v2 event name to handler key.\n *\n * @remarks\n * The spec (v2.0.58) names these `call.*`. There is no `call.completed` — the end-of-call\n * event is `call.hangup` — and no `call.initiated`: the event enum (lines 2264-2280) starts\n * at `call.incoming`, so a call being created raises nothing.\n */\nexport const EVENT_MAP: Readonly<Record<string, HandlerKey>> = {\n 'call.incoming': 'incoming',\n 'call.answered': 'answered',\n 'call.menu': 'manage',\n 'call.hangup': 'completed',\n 'call.failed': 'completed',\n};\n\n/**\n * Resolve a v2 event name to a handler key.\n *\n * Tolerates a leading `webhook.` (used in some early drafts) and routes every\n * dynamic `call.webhook.<name>` event from the `webhook` command to `manage`.\n *\n * @param event - Event name from the webhook payload\n * @returns The matching handler key, or `undefined` if the event is unmapped\n */\nexport function resolveHandlerKey(event: string): HandlerKey | undefined {\n const name = stripLegacyPrefix(event);\n if (name.startsWith(WEBHOOK_EVENT_PREFIX)) {\n return 'manage';\n }\n return EVENT_MAP[name];\n}\n\n/** Prefix the platform puts in front of a `webhook` command's `webhookName`. */\nconst WEBHOOK_EVENT_PREFIX = 'call.webhook.';\n\nfunction stripLegacyPrefix(event: string): string {\n return event.startsWith('webhook.') ? event.slice('webhook.'.length) : event;\n}\n\n/**\n * Recover the `webhookName` a `webhook` command was written with.\n *\n * The inverse of the naming rule in {@link CommandBuilder.webhook}: `webhook('my.custom.event',\n * url)` raises `call.webhook.my.custom.event`, and this turns that back into\n * `my.custom.event`. Names may contain dots, so everything after the prefix is the name.\n *\n * @param event - Event name from the webhook payload\n * @returns The webhook name, or `undefined` for any other event\n */\nexport function resolveWebhookName(event: string): string | undefined {\n const name = stripLegacyPrefix(event);\n return name.startsWith(WEBHOOK_EVENT_PREFIX)\n ? name.slice(WEBHOOK_EVENT_PREFIX.length) || undefined\n : undefined;\n}\n\n// ============================================\n// Client\n// ============================================\n\n/**\n * Client for the Sinch Voice API v2.\n *\n * The upper half of this package: it builds command lists, applies the leg-aware defaults and\n * dispatches webhooks. It sends nothing itself — the {@link CallTransport} does that, and by\n * default that is `HttpTransport`, which authenticates with HTTP Basic using the project\n * Access Key pair (`PROJECT_ID_API_KEY` / `PROJECT_ID_API_SECRET`) — not the v1\n * application key.\n */\nexport class Client {\n private readonly publicUrl: string | undefined;\n\n /**\n * The lower layer, reached only through the interface this half of the module owns.\n *\n * This field and the `new HttpTransport` below are the whole coupling between the\n * command builder and the network. When `@sinch/voice@2` ships, an adapter over the\n * SDK replaces that one expression and nothing else in this file moves.\n */\n private readonly transport: CallTransport;\n\n /**\n * @param context - Function context, used for env and for the public host\n * @param options - Explicit overrides for anything the context cannot supply\n */\n constructor(context?: ClientContext, options: Options = {}) {\n const env = context?.env ?? process.env;\n this.publicUrl = toWebSocketBase(options.publicUrl ?? context?.host);\n this.transport = new HttpTransport({\n projectId: options.projectId ?? env.PROJECT_ID ?? context?.config?.projectId ?? '',\n keyId: options.keyId ?? env.PROJECT_ID_API_KEY ?? '',\n keySecret: options.keySecret ?? env.PROJECT_ID_API_SECRET ?? '',\n ...(options.host !== undefined && { host: options.host }),\n ...(options.fetch !== undefined && { fetch: options.fetch }),\n });\n }\n\n /**\n * Place an outbound call.\n *\n * Name the events you want handled inline and they are sent as a **complete** block, with\n * busy, rejected, timed-out and failed defaulting to hangup. Name none and no `events` key\n * is sent at all, which is what hands the call to the service webhook.\n *\n * There is no half-way house, and that is the platform's rule rather than this client's:\n * `events` present means the service webhook is attached to *none* of the six lists, so a\n * lone `onAnswer` would silently stop busy and hangup from being handled by anything.\n *\n * @param to - Who to call\n * @param options - Dial settings and named events\n * @throws If the API rejects the request\n *\n * @example\n * ```typescript\n * // Inline: say a line and hang up, failures end the call\n * await voice.call('+15559876543', {\n * from: '+15551234567',\n * onAnswer: (c) => c.say('Your appointment is confirmed.').hangup(),\n * });\n *\n * // A flow built once and reused\n * const greeting = commands().say('One moment').bridgeCall('support');\n * await voice.call('+15559876543', { onAnswer: greeting });\n *\n * // Service-webhook mode: no events named, so `call.answered` fires\n * await voice.call('+15559876543', { from: '+15551234567' });\n * ```\n */\n call(to: Destination, options: PlaceCallOptions = {}): Promise<CallResponse> {\n return this.raw(toCallRequest(this.planCall(to, options)));\n }\n\n /**\n * Build the {@link call} flow without sending it.\n *\n * @param to - Who to call\n * @param options - Dial settings and named events\n */\n planCall(to: Destination, options: PlaceCallOptions = {}): Plan {\n // Single leg: nothing else exists to end, so the failure defaults are a bare hangup and\n // `onHangup` is not defaulted at all — the call is already over by the time it fires.\n return {\n commands: [\n buildDial(toEndpoint(to), { ...options, callName: options.callName ?? ORIGIN_LEG }),\n ],\n };\n }\n\n /**\n * Call a destination and put a WebSocket audio stream on the same call.\n *\n * Dials the destination as leg `origin`; on answer that leg joins a bridge and a\n * second leg is dialled to the STREAM endpoint, which joins the same bridge.\n * Either leg hanging up ends the other.\n *\n * `streamOptions` is always sent in full — the platform defaults to 44100 Hz\n * when the object is omitted and to 8000 Hz when it is partially supplied.\n *\n * Both endpoints are positional, mirroring {@link bridge}: this dials two things and\n * bridges them, and neither of them has a sensible default. In particular there is no\n * honest default path for the audio leg — the runtime neither serves nor owns one — so\n * the socket URL is as required as the number.\n *\n * @param to - Who to call\n * @param stream - WebSocket endpoint for the audio leg. Either a full `ws://`/`wss://`\n * URL or an absolute path, resolved against this function's public URL.\n * @param options - Headers, sample rate, bridge name and dial settings\n * @throws If the stream path cannot be resolved, or if the API rejects the request\n *\n * @example\n * ```typescript\n * // Relative path, resolved against the function's public host\n * await voice.callWithStream('+15559876543', '/media', {\n * from: '+15551234567',\n * headers: { 'x-contact-id': 'abc123' },\n * });\n *\n * // Full URL, 8 kHz to match a PSTN-only path\n * await voice.callWithStream('+15559876543', 'wss://example.com/audio', {\n * from: '+15551234567',\n * sampleRate: 8000,\n * });\n * ```\n */\n callWithStream(\n to: Destination,\n stream: string,\n options?: StreamCallOptions\n ): Promise<CallResponse> {\n return this.raw(toCallRequest(this.planStreamCall(to, stream, options)));\n }\n\n /**\n * Build the {@link callWithStream} flow without sending it.\n *\n * @param to - Who to call\n * @param stream - WebSocket endpoint for the audio leg, as a URL or an absolute path\n * @param options - Headers, sample rate, bridge name and dial settings\n * @throws If the stream path cannot be resolved\n */\n planStreamCall(to: Destination, stream: string, options: StreamCallOptions = {}): Plan {\n const headers = toCallHeaders(options.headers);\n const streamEndpoint: To = {\n type: 'STREAM',\n stream: {\n endpoint: this.resolveStreamEndpoint(stream),\n streamOptions: defaultStreamOptions(options.sampleRate),\n ...(headers && { callHeaders: headers }),\n },\n };\n\n return this.planBridged(toEndpoint(to), streamEndpoint, STREAM_LEG, options);\n }\n\n /**\n * Call a destination and put the Voice Relay service on the same call.\n *\n * Same topology as {@link callWithStream} — dial the human, bridge a second leg — but the\n * second leg is a VOICE_RELAY endpoint rather than a raw audio socket: Sinch runs STT and\n * TTS, and the application exchanges text. The trade is that the application never owns\n * the TTS stream, which rules the relay out for anything that needs its own voice or\n * needs to inject filler speech while an LLM thinks.\n *\n * The relay socket is positional and required: the `voiceRelay` schema (spec line 2946)\n * requires `endpoint`, so there is no relay leg without one.\n *\n * @param to - Who to call\n * @param relay - WebSocket endpoint the relay connects to. Either a full `ws://`/`wss://`\n * URL or an absolute path, resolved against this function's public URL.\n * @param options - Voice, transcription language, barge-in, bridge name and dial settings\n * @throws If the API rejects the request\n */\n callWithRelay(to: Destination, relay: string, options?: RelayCallOptions): Promise<CallResponse> {\n return this.raw(toCallRequest(this.planRelayCall(to, relay, options)));\n }\n\n /**\n * Build the {@link callWithRelay} flow without sending it.\n *\n * @param to - Who to call\n * @param relay - WebSocket endpoint the relay connects to, as a URL or an absolute path\n * @param options - Voice, transcription language, barge-in, bridge name and dial settings\n */\n planRelayCall(to: Destination, relay: string, options: RelayCallOptions = {}): Plan {\n const relayEndpoint = dialRelay(this.resolveStreamEndpoint(relay), {\n ...(options.ttsVoice && { ttsVoice: options.ttsVoice }),\n ...(options.sttLanguage && { sttLanguage: options.sttLanguage }),\n ...(options.enableInterruptions !== undefined && {\n enableInterruptions: options.enableInterruptions,\n }),\n ...(options.headers && { headers: options.headers }),\n });\n\n return this.planBridged(toEndpoint(to), relayEndpoint, RELAY_LEG, options);\n }\n\n /**\n * Call two destinations and bridge them together.\n *\n * @param a - First party, dialled as leg `origin`\n * @param b - Second party, dialled once `a` answers\n * @param options - Dial settings and bridge name\n *\n * @example\n * ```typescript\n * await voice.bridge('+15551110000', '+15552220000', { from: '+15551234567' });\n * ```\n */\n bridge(a: Destination, b: Destination, options: BridgeOptions = {}): Promise<CallResponse> {\n return this.raw(toCallRequest(this.planBridge(a, b, options)));\n }\n\n /**\n * Build the {@link bridge} flow without sending it.\n *\n * @param a - First party, dialled as leg `origin`\n * @param b - Second party, dialled once `a` answers\n * @param options - Dial settings and bridge name\n */\n planBridge(a: Destination, b: Destination, options: BridgeOptions = {}): Plan {\n return this.planBridged(toEndpoint(a), toEndpoint(b), 'destination', options);\n }\n\n /**\n * End one or more legs of a live call.\n *\n * @param target - The live call, addressed by `callId` or by `sessionId` + `callName`\n * @param callNames - Legs to end. Ends the addressed leg when omitted.\n *\n * @example\n * ```typescript\n * await voice.hangup({ sessionId }, 'origin', 'stream');\n * ```\n */\n hangup(target: PatchTarget, ...callNames: string[]): Promise<void> {\n return this.patch(target, this.planHangup(...callNames));\n }\n\n /**\n * Build the {@link hangup} command list without sending it.\n *\n * @param callNames - Legs to end. Ends the addressed leg when omitted.\n */\n planHangup(...callNames: string[]): Command[] {\n const flow = commands();\n if (callNames.length > 0) {\n for (const callName of callNames) {\n flow.hangup(callName);\n }\n } else {\n flow.hangup();\n }\n return flow.build();\n }\n\n /**\n * Run commands against a live call — the escalation path.\n *\n * @param target - The live call, addressed by `callId` or by `sessionId` + `callName`\n * @param flow - Commands to execute in the context of the addressed leg, in any\n * {@link Flow} spelling\n * @throws If the API rejects the request\n *\n * @example\n * ```typescript\n * // Pull a human agent into an in-progress streamed call\n * await voice.patch({ sessionId, callName: 'origin' }, (c) =>\n * c.bridgeCall('escalation').dial('+15550001111', {\n * callName: 'agent',\n * onAnswer: (a) => a.bridgeCall('escalation'),\n * endOnFailure: 'origin',\n * })\n * );\n * ```\n */\n async patch(target: PatchTarget, flow: Flow): Promise<void> {\n await this.transport.patchCall(target, resolveFlow(flow));\n }\n\n /**\n * Dial a party into a live call's bridge — the transfer v1 has no equivalent of.\n *\n * The named sugar over {@link patch}: it sends exactly\n * `patch(target, buildTransferCommands(to, options))`, and the value is entirely in what\n * that builder puts around the dial. See {@link buildTransferCommands} for why every\n * non-answer outcome has to end another leg.\n *\n * ### Why both a target and a bridge name\n *\n * They address different things and neither is redundant. {@link PatchTarget} pins the\n * **session** — by `callId`, or by `sessionId` plus the leg the commands run in the context\n * of. `bridgeName` then resolves **within** that session, because `bridgeCall` joins the\n * current call to a bridge \"in the same session\". That scoping is also what makes the\n * default safe: two unrelated calls both using `bridge` are in two different sessions, so\n * they cannot meet.\n *\n * The one genuinely ambiguous case is inside a single session: reuse a name for what you\n * meant as two bridges and you get one bridge, because joining a name that already exists\n * is documented to join it rather than create a second.\n *\n * @param target - The live call, addressed by `callId` or by `sessionId` + `callName`\n * @param to - Party to dial: an E.164 number, a `sip:` URI, or an endpoint object\n * @param options - Bridge, caller id, dial timeout, leg names\n * @throws If the API rejects the request\n *\n * @example\n * ```typescript\n * // A call placed by this client with default options: the bridge is already known\n * await voice.transfer({ sessionId, callName: 'origin' }, '+15550001111', {\n * endLeg: 'origin',\n * });\n *\n * // A call whose bridge was named, or one this package did not place\n * await voice.transfer({ callId }, 'sip:agent@pbx.example.com', {\n * bridgeName: 'agent',\n * endLeg: 'stream',\n * });\n * ```\n */\n transfer(target: PatchTarget, to: Destination, options: TransferOptions = {}): Promise<void> {\n return this.patch(target, buildTransferCommands(to, options));\n }\n\n /**\n * Post a call-create body verbatim — the escape hatch for anything this client\n * does not model.\n *\n * The body type is deliberately permissive rather than the `callRequest` shape: the wire\n * command types are internal to this module, so anything hand-built here is unchecked by\n * design. Use {@link toCallRequest} on a plan when you want the shape validated.\n *\n * @param body - A `callRequest` body, or any object the API accepts\n * @throws If the API rejects the request\n */\n raw(body: Record<string, unknown> | object): Promise<CallResponse> {\n return this.transport.createCall(body);\n }\n\n /**\n * Build a webhook dispatcher over the v2 call lifecycle.\n *\n * Handlers may return a plan, a command builder, a bare command array, or nothing.\n * Nothing means \"no commands\" and yields `undefined`, which a handler should\n * turn into a `204`.\n *\n * @param handlers - Handlers keyed by lifecycle stage\n * @returns A function that maps a webhook payload to a response body\n *\n * @example\n * ```typescript\n * export const handleVoiceWebhook = voice.onCall({\n * incoming: () => commands().answer().say('Thanks for calling').hangup(),\n * completed: (event) => {\n * console.log('call ended', event.call.callId);\n * },\n * });\n * ```\n */\n onCall(handlers: CallHandlers): (event: WebhookRequest) => Promise<WebhookResponse | undefined> {\n return async (event: WebhookRequest): Promise<WebhookResponse | undefined> => {\n const webhookName = resolveWebhookName(event.event);\n const key = resolveHandlerKey(event.event);\n const handler =\n (webhookName && handlers.webhooks?.[webhookName]) ||\n (key && handlers[key]) ||\n handlers.fallback;\n if (!handler) {\n return undefined;\n }\n\n const result = await handler(event);\n if (!result) {\n return undefined;\n }\n\n const plan: Plan =\n Array.isArray(result) || result instanceof CommandBuilder\n ? { commands: resolveFlow(result) }\n : result;\n return toWebhookResponse(plan);\n };\n }\n\n // ============================================\n // Internals\n // ============================================\n\n /**\n * The bridged shape: dial one leg, and on answer join a bridge and dial the second into it.\n *\n * The leg-aware defaults live here because this is where the topology is known. The second\n * leg names the first in both `endOnHangup` and `endOnFailure` — every way it can fail ends\n * the first one too, or `callWithStream` strands the human on a bridge with nothing on the\n * other side, and a stream-first plan leaves an answered WebSocket leg (with its billed\n * STT/TTS/LLM sockets) running to the platform's 14400-second ceiling talking to nobody.\n *\n * The first leg names the second in `endOnHangup` only. Its failure events fire *before*\n * the second leg has been dialled, so naming it there would target a leg that does not\n * exist; a bare hangup is the leg-aware answer for the first leg of a call.\n */\n private planBridged(\n first: To,\n second: To,\n secondLeg: string,\n options: CallOptions & { bridgeName?: string }\n ): Plan {\n const bridgeName = options.bridgeName ?? DEFAULT_BRIDGE_NAME;\n\n const secondDial = buildDial(second, {\n ...options,\n callName: secondLeg,\n onAnswer: (c) => c.bridgeCall(bridgeName),\n endOnHangup: ORIGIN_LEG,\n endOnFailure: ORIGIN_LEG,\n });\n\n const originDial = buildDial(first, {\n ...options,\n callName: ORIGIN_LEG,\n onAnswer: (c) => c.bridgeCall(bridgeName).add(secondDial),\n endOnHangup: secondLeg,\n });\n\n return { commands: [originDial] };\n }\n\n private resolveStreamEndpoint(stream: string): string {\n if (/^wss?:\\/\\//i.test(stream)) {\n return stream;\n }\n if (!stream.startsWith('/')) {\n throw new Error(\n `Stream endpoint '${stream}' must be a ws:// or wss:// URL, or an absolute path such as '/stream'.`\n );\n }\n if (!this.publicUrl) {\n throw new Error(\n `Cannot resolve stream path '${stream}' — this function's public URL is unknown. Pass a full wss:// URL, or set the publicUrl option (context.host is only present in production).`\n );\n }\n return `${this.publicUrl}${stream}`;\n }\n}\n\n// ============================================\n// Factory\n// ============================================\n\n/**\n * Create a Voice API v2 client.\n *\n * @param context - Function context, used for env and for the public host\n * @param options - Explicit overrides for anything the context cannot supply\n *\n * @example\n * ```typescript\n * const voice = createClient(context);\n * const voiceEu = createClient(context, { host: 'https://eu1.voice.api.sinch.com' });\n * ```\n */\nexport function createClient(context?: ClientContext, options?: Options): Client {\n return new Client(context, options);\n}\n\n// ============================================\n// Helpers\n// ============================================\n\nfunction toWebSocketBase(base?: string): string | undefined {\n if (!base) {\n return undefined;\n }\n const trimmed = base.replace(/\\/$/, '');\n if (/^wss?:\\/\\//i.test(trimmed)) {\n return trimmed;\n }\n if (/^https:\\/\\//i.test(trimmed)) {\n return `wss://${trimmed.slice('https://'.length)}`;\n }\n if (/^http:\\/\\//i.test(trimmed)) {\n return `ws://${trimmed.slice('http://'.length)}`;\n }\n return `wss://${trimmed}`;\n}\n"],"mappings":";;;;;;AAiB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S,OAAO;AACzB;","names":["commands","commands"]}
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sinch/functions-runtime",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.17",
|
|
4
4
|
"description": "Node.js SDK and local development runtime for Sinch Functions: voice, messaging and HTTP serverless functions",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
"README.md"
|
|
26
26
|
],
|
|
27
27
|
"scripts": {
|
|
28
|
-
"build": "tsup && dts-bundle-generator -o dist/index.d.ts src/index.ts --no-check && dts-bundle-generator -o dist/voice/v2.d.ts src/voice/v2.ts --no-check --export-referenced-types=false",
|
|
28
|
+
"build": "tsup && dts-bundle-generator -o dist/index.d.ts src/index.ts --no-check && dts-bundle-generator -o dist/voice/v2.d.ts src/voice/v2.ts --no-check --export-referenced-types=false && node ../../scripts/fix-v2-dts.mjs dist/voice/v2.d.ts",
|
|
29
29
|
"build:tsc": "tsc",
|
|
30
30
|
"dev": "tsup --watch",
|
|
31
31
|
"test": "vitest run",
|