@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.
@@ -1,14 +1,45 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __sinchCreateRequire } from 'node:module';
3
3
  const require = __sinchCreateRequire(import.meta.url);
4
- import {
5
- __commonJS,
6
- __esm,
7
- __export,
8
- __require,
9
- __toCommonJS,
10
- __toESM
11
- } from "./chunk-X44DQ6CI.js";
4
+ var __create = Object.create;
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
11
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
12
+ }) : x)(function(x) {
13
+ if (typeof require !== "undefined") return require.apply(this, arguments);
14
+ throw Error('Dynamic require of "' + x + '" is not supported');
15
+ });
16
+ var __esm = (fn, res) => function __init() {
17
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
18
+ };
19
+ var __commonJS = (cb, mod) => function __require2() {
20
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
21
+ };
22
+ var __export = (target, all3) => {
23
+ for (var name in all3)
24
+ __defProp(target, name, { get: all3[name], enumerable: true });
25
+ };
26
+ var __copyProps = (to, from, except, desc) => {
27
+ if (from && typeof from === "object" || typeof from === "function") {
28
+ for (let key of __getOwnPropNames(from))
29
+ if (!__hasOwnProp.call(to, key) && key !== except)
30
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
31
+ }
32
+ return to;
33
+ };
34
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
35
+ // If the importer is in node compatibility mode or this is not an ESM
36
+ // file that has been converted to a CommonJS file using a Babel-
37
+ // compatible transform (i.e. "__esModule" has not been set), then set
38
+ // "default" to the CommonJS "module.exports" for node compatibility.
39
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
40
+ mod
41
+ ));
42
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
12
43
 
13
44
  // ../../node_modules/ms/index.js
14
45
  var require_ms = __commonJS({
@@ -31109,7 +31140,7 @@ var require_authorization_helper = __commonJS({
31109
31140
  var crypto_1 = __importDefault(__require("crypto"));
31110
31141
  var generateAuthorizationHeader = (httpVerb, body, contentType, canonicalizedHeaders, canonicalizedResource, applicationKey, applicationSecret) => {
31111
31142
  const hasBody = !!body;
31112
- const stringToSign = buildStringToSign(httpVerb, hasBody ? (0, exports.calculateMD5)(body) : "", contentType, canonicalizedHeaders, canonicalizedResource);
31143
+ const stringToSign = buildStringToSign2(httpVerb, hasBody ? (0, exports.calculateMD5)(body) : "", contentType, canonicalizedHeaders, canonicalizedResource);
31113
31144
  const signature = (0, exports.calculateSignature)(applicationSecret, stringToSign);
31114
31145
  return `Application ${applicationKey}:${signature}`;
31115
31146
  };
@@ -31187,7 +31218,7 @@ var require_authorization_helper = __commonJS({
31187
31218
  const contentType = getHeader(normalizedHeaders["content-type"]);
31188
31219
  const hasBody = !!body;
31189
31220
  const contentMD5 = hasBody ? (0, exports.calculateMD5)(body) : "";
31190
- const stringToSign = buildStringToSign(method.toUpperCase(), contentMD5, contentType, `x-timestamp:${normalizedHeaders["x-timestamp"]}`, path6);
31221
+ const stringToSign = buildStringToSign2(method.toUpperCase(), contentMD5, contentType, `x-timestamp:${normalizedHeaders["x-timestamp"]}`, path6);
31191
31222
  const signature = (0, exports.calculateSignature)(applicationSecret, stringToSign);
31192
31223
  if (authKeyAndSecret[1] !== signature) {
31193
31224
  console.error("Invalid signature");
@@ -31203,7 +31234,7 @@ var require_authorization_helper = __commonJS({
31203
31234
  return crypto_1.default.createHmac("sha256", Buffer.from(secret, "base64")).update(Buffer.from(stringToSign, "utf-8")).digest("base64");
31204
31235
  };
31205
31236
  exports.calculateSignature = calculateSignature;
31206
- var buildStringToSign = (httpVerb, contentMD5, contentType, canonicalizedHeaders, canonicalizedResource) => {
31237
+ var buildStringToSign2 = (httpVerb, contentMD5, contentType, canonicalizedHeaders, canonicalizedResource) => {
31207
31238
  return `${httpVerb}
31208
31239
  ${contentMD5}
31209
31240
  ${contentType}
@@ -57113,7 +57144,7 @@ var require_websocket = __commonJS({
57113
57144
  var http3 = __require("http");
57114
57145
  var net = __require("net");
57115
57146
  var tls = __require("tls");
57116
- var { randomBytes: randomBytes2, createHash } = __require("crypto");
57147
+ var { randomBytes: randomBytes2, createHash: createHash2 } = __require("crypto");
57117
57148
  var { Duplex, Readable: Readable3 } = __require("stream");
57118
57149
  var { URL: URL3 } = __require("url");
57119
57150
  var PerMessageDeflate = require_permessage_deflate();
@@ -57770,7 +57801,7 @@ var require_websocket = __commonJS({
57770
57801
  abortHandshake(websocket, socket, "Invalid Upgrade header");
57771
57802
  return;
57772
57803
  }
57773
- const digest = createHash("sha1").update(key + GUID).digest("base64");
57804
+ const digest = createHash2("sha1").update(key + GUID).digest("base64");
57774
57805
  if (res.headers["sec-websocket-accept"] !== digest) {
57775
57806
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
57776
57807
  return;
@@ -58137,7 +58168,7 @@ var require_websocket_server = __commonJS({
58137
58168
  var EventEmitter2 = __require("events");
58138
58169
  var http3 = __require("http");
58139
58170
  var { Duplex } = __require("stream");
58140
- var { createHash } = __require("crypto");
58171
+ var { createHash: createHash2 } = __require("crypto");
58141
58172
  var extension = require_extension();
58142
58173
  var PerMessageDeflate = require_permessage_deflate();
58143
58174
  var subprotocol = require_subprotocol();
@@ -58434,7 +58465,7 @@ var require_websocket_server = __commonJS({
58434
58465
  );
58435
58466
  }
58436
58467
  if (this._state > RUNNING) return abortHandshake(socket, 503);
58437
- const digest = createHash("sha1").update(key + GUID).digest("base64");
58468
+ const digest = createHash2("sha1").update(key + GUID).digest("base64");
58438
58469
  const headers = [
58439
58470
  "HTTP/1.1 101 Switching Protocols",
58440
58471
  "Upgrade: websocket",
@@ -59882,6 +59913,1294 @@ function createConfig(context) {
59882
59913
  }
59883
59914
  var createUniversalConfig = createConfig;
59884
59915
 
59916
+ // ../voice-v2-preview/dist/core/redaction.js
59917
+ var REDACTED = "[redacted]";
59918
+ function redactCredentials(body) {
59919
+ return redactValue(body);
59920
+ }
59921
+ function redactValue(value) {
59922
+ if (Array.isArray(value)) {
59923
+ return value.map(redactValue);
59924
+ }
59925
+ if (value === null || typeof value !== "object") {
59926
+ return value;
59927
+ }
59928
+ const out = {};
59929
+ for (const [key, item] of Object.entries(value)) {
59930
+ out[key] = key === "credentials" && typeof item === "string" ? REDACTED : redactValue(item);
59931
+ }
59932
+ return out;
59933
+ }
59934
+ function scrubCredentials(text, body) {
59935
+ let out = text;
59936
+ for (const secret of collectCredentials(body)) {
59937
+ for (const fragment of [secret, ...secret.split(":")]) {
59938
+ if (fragment.length >= 8) {
59939
+ out = out.split(fragment).join(REDACTED);
59940
+ }
59941
+ }
59942
+ }
59943
+ return out;
59944
+ }
59945
+ function collectCredentials(value, found = /* @__PURE__ */ new Set()) {
59946
+ if (Array.isArray(value)) {
59947
+ for (const item of value) {
59948
+ collectCredentials(item, found);
59949
+ }
59950
+ return found;
59951
+ }
59952
+ if (value === null || typeof value !== "object") {
59953
+ return found;
59954
+ }
59955
+ for (const [key, item] of Object.entries(value)) {
59956
+ if (key === "credentials" && typeof item === "string" && item.length > 0) {
59957
+ found.add(item);
59958
+ } else {
59959
+ collectCredentials(item, found);
59960
+ }
59961
+ }
59962
+ return found;
59963
+ }
59964
+
59965
+ // ../voice-v2-preview/dist/wire/http.js
59966
+ var DEFAULT_HOST = "https://voice.api.sinch.com";
59967
+ var FETCH_TIMEOUT_MS = 1e4;
59968
+ var HttpTransport = class {
59969
+ projectId;
59970
+ host;
59971
+ fetchImpl;
59972
+ // The Access Key pair is held in ECMAScript private fields, not TypeScript `private` ones.
59973
+ // `private` is a compile-time marker: the field is still an ordinary enumerable own property
59974
+ // at runtime, so `JSON.stringify` prints it. This transport hangs off `context.voice`, which
59975
+ // means one `JSON.stringify(context)` or one structured log line would emit
59976
+ // `PROJECT_ID_API_SECRET` in full. `#` fields are invisible to both.
59977
+ #keyId;
59978
+ #keySecret;
59979
+ constructor(options) {
59980
+ this.projectId = options.projectId;
59981
+ this.#keyId = options.keyId;
59982
+ this.#keySecret = options.keySecret;
59983
+ this.host = (options.host ?? DEFAULT_HOST).replace(/\/$/, "");
59984
+ this.fetchImpl = options.fetch ?? globalThis.fetch;
59985
+ }
59986
+ /**
59987
+ * Serialise without the credentials.
59988
+ *
59989
+ * The `#` fields already keep them out of `JSON.stringify`; this keeps the output a
59990
+ * deliberate shape rather than whatever fields happen to be left over.
59991
+ */
59992
+ toJSON() {
59993
+ return { transport: "HttpTransport", projectId: this.projectId, host: this.host };
59994
+ }
59995
+ async createCall(body) {
59996
+ const response = await this.request("POST", "calls", body);
59997
+ return response;
59998
+ }
59999
+ async patchCall(target, commands2) {
60000
+ const path6 = "callId" in target ? `calls/${encodeURIComponent(target.callId)}` : `sessions/${encodeURIComponent(target.sessionId)}/calls/${encodeURIComponent(target.callName)}`;
60001
+ await this.request("PATCH", path6, { commands: commands2 });
60002
+ }
60003
+ get authHeaders() {
60004
+ const token = Buffer.from(`${this.#keyId}:${this.#keySecret}`).toString("base64");
60005
+ return { Authorization: `Basic ${token}`, "Content-Type": "application/json" };
60006
+ }
60007
+ async request(method, path6, body) {
60008
+ if (!this.projectId || !this.#keyId || !this.#keySecret) {
60009
+ throw new Error("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).");
60010
+ }
60011
+ const url2 = `${this.host}/v2/projects/${encodeURIComponent(this.projectId)}/${path6}`;
60012
+ const response = await this.fetchImpl(url2, {
60013
+ method,
60014
+ headers: this.authHeaders,
60015
+ body: JSON.stringify(body),
60016
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
60017
+ });
60018
+ if (!response.ok) {
60019
+ const error = scrubCredentials(await response.text(), body);
60020
+ throw new Error(`Voice API v2 error: ${response.status} - ${error}`);
60021
+ }
60022
+ return response.status === 204 || response.status === 202 ? void 0 : response.json();
60023
+ }
60024
+ };
60025
+
60026
+ // ../voice-v2-preview/dist/core/endpoints.js
60027
+ var DEFAULT_SAMPLE_RATE = 16e3;
60028
+ var DEFAULT_VOICE = "Emma";
60029
+ var DEFAULT_STT_LANGUAGE = "en-US";
60030
+ var STREAM_PROTOCOL_VERSION = 1;
60031
+ function defaultStreamOptions(sampleRate = DEFAULT_SAMPLE_RATE) {
60032
+ return { version: STREAM_PROTOCOL_VERSION, codec: "PCM", sampleRate };
60033
+ }
60034
+ function dialPhone(number) {
60035
+ return { type: "PHONE", phone: { number: number.replace(/[\s-]/g, "") } };
60036
+ }
60037
+ function dialSip(address, options = {}) {
60038
+ const callHeaders = toCallHeaders(options.headers);
60039
+ return {
60040
+ type: "SIP",
60041
+ sip: {
60042
+ endpoint: address,
60043
+ ...options.transport && { transport: options.transport },
60044
+ ...callHeaders && { callHeaders }
60045
+ }
60046
+ };
60047
+ }
60048
+ function dialStream(endpoint, options = {}) {
60049
+ const callHeaders = toCallHeaders(options.headers);
60050
+ return {
60051
+ type: "STREAM",
60052
+ stream: {
60053
+ endpoint,
60054
+ streamOptions: defaultStreamOptions(options.sampleRate),
60055
+ ...callHeaders && { callHeaders }
60056
+ }
60057
+ };
60058
+ }
60059
+ function dialRelay(endpoint, options = {}) {
60060
+ const callHeaders = toCallHeaders(options.headers);
60061
+ return {
60062
+ type: "VOICE_RELAY",
60063
+ voiceRelay: {
60064
+ endpoint,
60065
+ ...options.enableInterruptions !== void 0 && {
60066
+ enableInterruptions: options.enableInterruptions
60067
+ },
60068
+ ttsVoice: options.ttsVoice ?? DEFAULT_VOICE,
60069
+ sttLanguage: options.sttLanguage ?? DEFAULT_STT_LANGUAGE,
60070
+ ...callHeaders && { callHeaders }
60071
+ }
60072
+ };
60073
+ }
60074
+ function toEndpoint(destination) {
60075
+ if (typeof destination !== "string") {
60076
+ return destination;
60077
+ }
60078
+ if (/^sips?:/i.test(destination)) {
60079
+ return { type: "SIP", sip: { endpoint: destination } };
60080
+ }
60081
+ if (/^wss?:\/\//i.test(destination)) {
60082
+ return {
60083
+ type: "STREAM",
60084
+ stream: { endpoint: destination, streamOptions: defaultStreamOptions() }
60085
+ };
60086
+ }
60087
+ if (/^\+?\d[\d\s-]*$/.test(destination)) {
60088
+ return { type: "PHONE", phone: { number: destination.replace(/[\s-]/g, "") } };
60089
+ }
60090
+ throw new Error(`Cannot interpret '${destination}' as a call destination. Use an E.164 number, a sip: URI, a ws:// URL, or an endpoint object.`);
60091
+ }
60092
+ function toOrigin(origin2) {
60093
+ const endpoint = toEndpoint(origin2);
60094
+ if (endpoint.type === "STREAM" || endpoint.type === "VOICE_RELAY") {
60095
+ throw new Error("A call cannot originate from a STREAM or VOICE_RELAY endpoint. Use a phone number or SIP URI.");
60096
+ }
60097
+ if (endpoint.type === "SIP") {
60098
+ const sip = endpoint.sip;
60099
+ if (sip.transport !== void 0 || sip.callHeaders !== void 0) {
60100
+ throw new Error("A SIP origin takes only an endpoint and a displayName \u2014 transport and callHeaders belong on the destination, and the API rejects them on `from`.");
60101
+ }
60102
+ }
60103
+ return endpoint;
60104
+ }
60105
+ function toCallHeaders(headers) {
60106
+ if (!headers) {
60107
+ return void 0;
60108
+ }
60109
+ const list = Array.isArray(headers) ? headers : Object.entries(headers).map(([key, value]) => ({ key, value }));
60110
+ return list.length > 0 ? list : void 0;
60111
+ }
60112
+
60113
+ // ../voice-v2-preview/dist/core/commands.js
60114
+ function resolveFlow(flow) {
60115
+ let list;
60116
+ if (typeof flow === "function") {
60117
+ const builder = commands();
60118
+ list = (flow(builder) ?? builder).build();
60119
+ } else if (Array.isArray(flow)) {
60120
+ list = flow;
60121
+ } else {
60122
+ list = flow.build();
60123
+ }
60124
+ if (list.length === 0) {
60125
+ throw new Error("Voice v2 flow is empty. Every nested command list needs at least one command \u2014 add say(), play(), dial(), hangup() or answer().");
60126
+ }
60127
+ return list;
60128
+ }
60129
+ var FAILURE_KEYS = ["onBusy", "onReject", "onTimeout", "onFailure"];
60130
+ var EVENT_KEYS = ["onAnswer", "onHangup", ...FAILURE_KEYS];
60131
+ var AMD_EVENT_KEYS = ["onHuman", "onMachine", "onBeep", "onUnknown"];
60132
+ function namesAnyEvent(keys, events) {
60133
+ return keys.some((key) => events[key] !== void 0);
60134
+ }
60135
+ function completeEvents(events, topology = {}) {
60136
+ if (!namesAnyEvent(EVENT_KEYS, events)) {
60137
+ if (topology.endOnHangup !== void 0 || topology.endOnFailure !== void 0) {
60138
+ throw new Error("Voice v2 dial: endOnHangup and endOnFailure are emitted inside the `events` block, and this dial names no event \u2014 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.");
60139
+ }
60140
+ return void 0;
60141
+ }
60142
+ const onNeverConnected = [
60143
+ { command: "hangup", ...topology.endOnFailure && { callName: topology.endOnFailure } }
60144
+ ];
60145
+ const block = {};
60146
+ if (events.onAnswer !== void 0) {
60147
+ block.onAnswer = resolveFlow(events.onAnswer);
60148
+ }
60149
+ for (const key of FAILURE_KEYS) {
60150
+ const supplied = events[key];
60151
+ block[key] = supplied !== void 0 ? resolveFlow(supplied) : onNeverConnected;
60152
+ }
60153
+ if (events.onHangup !== void 0) {
60154
+ block.onHangup = resolveFlow(events.onHangup);
60155
+ } else if (topology.endOnHangup) {
60156
+ block.onHangup = [{ command: "hangup", callName: topology.endOnHangup }];
60157
+ }
60158
+ if (block.onAnswer === void 0) {
60159
+ throw new Error("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 \u2014 silence until maxCallDurationSeconds. Add onAnswer, or name no events at all and let the service webhook answer the leg.");
60160
+ }
60161
+ return block;
60162
+ }
60163
+ function completeAmdEvents(events) {
60164
+ if (!namesAnyEvent(AMD_EVENT_KEYS, events)) {
60165
+ return void 0;
60166
+ }
60167
+ const block = {};
60168
+ for (const key of AMD_EVENT_KEYS) {
60169
+ const flow = events[key];
60170
+ block[key] = flow !== void 0 ? resolveFlow(flow) : [];
60171
+ }
60172
+ return block;
60173
+ }
60174
+ function buildDial(to, options = {}) {
60175
+ const carriesCli = to.type !== "STREAM" && to.type !== "VOICE_RELAY";
60176
+ const from = carriesCli && options.from ? toOrigin(options.from) : void 0;
60177
+ const events = completeEvents(options, options);
60178
+ return {
60179
+ command: "dial",
60180
+ ...options.callName && { callName: options.callName },
60181
+ ...from && { from },
60182
+ to,
60183
+ ...options.timeout !== void 0 && { dialTimeoutDurationSeconds: options.timeout },
60184
+ ...options.maxDuration !== void 0 && { maxCallDurationSeconds: options.maxDuration },
60185
+ ...events && { events }
60186
+ };
60187
+ }
60188
+ function toCredentials(credentials) {
60189
+ if (typeof credentials === "string") {
60190
+ return credentials;
60191
+ }
60192
+ const parts = [credentials.accessKeyId, credentials.secretAccessKey, credentials.region];
60193
+ if (parts.some((part) => part.includes(":"))) {
60194
+ throw new Error("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.");
60195
+ }
60196
+ return parts.join(":");
60197
+ }
60198
+ function toRecordingOptions(options) {
60199
+ const transcribing = options.transcribe !== void 0 || options.transcriptionLocale !== void 0;
60200
+ return {
60201
+ ...options.format && { format: options.format },
60202
+ ...options.recordingType && { recordingType: options.recordingType },
60203
+ destination: options.destination ?? "AWS",
60204
+ destinationUrl: options.destinationUrl,
60205
+ credentials: toCredentials(options.credentials),
60206
+ ...transcribing && {
60207
+ transcriptionOptions: {
60208
+ isEnabled: options.transcribe ?? true,
60209
+ ...options.transcriptionLocale && { locale: options.transcriptionLocale }
60210
+ }
60211
+ }
60212
+ };
60213
+ }
60214
+ var PromptBuilder = class {
60215
+ messages = [];
60216
+ barge;
60217
+ /**
60218
+ * Speak text.
60219
+ *
60220
+ * @param text - Text to synthesise, or an SSML document when `format` is `SSML`
60221
+ * @param options - Voice and format overrides
60222
+ */
60223
+ say(text, options = {}) {
60224
+ this.messages.push(sayMessage(text, options));
60225
+ return this;
60226
+ }
60227
+ /**
60228
+ * Play an audio file.
60229
+ *
60230
+ * @param url - Publicly reachable URL of the audio file
60231
+ */
60232
+ play(url2) {
60233
+ this.messages.push({ type: "PLAY", play: { url: url2 } });
60234
+ return this;
60235
+ }
60236
+ /**
60237
+ * Let input interrupt the prompt instead of waiting for it to finish. Emits
60238
+ * `allowBargeIn`, which the platform defaults to `true`.
60239
+ *
60240
+ * @param enabled - Pass `false` to state the opposite explicitly
60241
+ */
60242
+ bargeIn(enabled = true) {
60243
+ this.barge = enabled;
60244
+ return this;
60245
+ }
60246
+ /** Emit the prompt. @throws If nothing was queued to play */
60247
+ build() {
60248
+ if (this.messages.length === 0) {
60249
+ throw new Error("Voice v2 menu prompt is empty. Call say() or play() on it.");
60250
+ }
60251
+ return {
60252
+ messages: [...this.messages],
60253
+ ...this.barge !== void 0 && { allowBargeIn: this.barge }
60254
+ };
60255
+ }
60256
+ };
60257
+ function resolvePrompt(prompt) {
60258
+ if (typeof prompt === "string") {
60259
+ return new PromptBuilder().say(prompt).build();
60260
+ }
60261
+ if (typeof prompt === "function") {
60262
+ const builder = new PromptBuilder();
60263
+ return (prompt(builder) ?? builder).build();
60264
+ }
60265
+ return prompt.build();
60266
+ }
60267
+ var MenuItemBuilder = class {
60268
+ item = {};
60269
+ matchOrder = [];
60270
+ matches = {};
60271
+ /**
60272
+ * Prompt played when the menu is entered.
60273
+ *
60274
+ * @param prompt - Plain text, a {@link PromptBuilder}, or a callback receiving one
60275
+ */
60276
+ prompt(prompt) {
60277
+ this.item.prompt = resolvePrompt(prompt);
60278
+ return this;
60279
+ }
60280
+ /**
60281
+ * Prompt played on each retry. Falls back to `prompt` when unset.
60282
+ *
60283
+ * @param prompt - Plain text, a {@link PromptBuilder}, or a callback receiving one
60284
+ */
60285
+ repeatPrompt(prompt) {
60286
+ this.item.repeatPrompt = resolvePrompt(prompt);
60287
+ return this;
60288
+ }
60289
+ /**
60290
+ * How long to wait for input before repeating.
60291
+ *
60292
+ * @param seconds - Seconds of silence that count as no input
60293
+ */
60294
+ inputTimeout(seconds) {
60295
+ this.item.inputTimeoutDurationSeconds = seconds;
60296
+ return this;
60297
+ }
60298
+ /**
60299
+ * How many times the prompt repeats before `onFail` runs.
60300
+ *
60301
+ * @param times - Repeat count
60302
+ */
60303
+ repeatCount(times) {
60304
+ this.item.repeatCount = times;
60305
+ return this;
60306
+ }
60307
+ /**
60308
+ * Fewest input characters collected before the menu evaluates them. Emits
60309
+ * `minimumInputLength`. 1-100, default 1.
60310
+ *
60311
+ * @param count - Minimum input length
60312
+ */
60313
+ minLength(count) {
60314
+ this.item.minimumInputLength = count;
60315
+ return this;
60316
+ }
60317
+ /**
60318
+ * Input character count that triggers evaluation. Emits `maximumInputLength`. 1-100,
60319
+ * default 1.
60320
+ *
60321
+ * @param count - Maximum input length
60322
+ */
60323
+ maxLength(count) {
60324
+ this.item.maximumInputLength = count;
60325
+ return this;
60326
+ }
60327
+ /**
60328
+ * Character sequence that ends input and triggers evaluation immediately, e.g. `#`.
60329
+ *
60330
+ * The pair to {@link maxLength}: with a range of accepted lengths, this is how a shorter
60331
+ * entry is submitted without waiting out `inputTimeout`. The sequence itself is part of
60332
+ * the input the `matches` keys see.
60333
+ *
60334
+ * @param sequence - Digits, `*` and `#` only, up to 10 characters
60335
+ */
60336
+ terminatedBy(sequence) {
60337
+ this.item.terminatingSequence = sequence;
60338
+ return this;
60339
+ }
60340
+ /**
60341
+ * What one input does.
60342
+ *
60343
+ * Keys may be literal digits or regular expressions, and the platform evaluates them in
60344
+ * definition order with first match winning — so the order these are written in is part of
60345
+ * the behaviour, not decoration. {@link build} refuses to emit a menu whose keys JSON
60346
+ * cannot carry in that order; see the error it throws.
60347
+ *
60348
+ * @param pattern - Digits, or a regular expression source
60349
+ * @param flow - Commands to run on a match
60350
+ */
60351
+ match(pattern, flow) {
60352
+ if (!(pattern in this.matches)) {
60353
+ this.matchOrder.push(pattern);
60354
+ }
60355
+ this.matches[pattern] = resolveFlow(flow);
60356
+ return this;
60357
+ }
60358
+ /**
60359
+ * Commands to run once the caller is out of attempts.
60360
+ *
60361
+ * @param flow - Commands to run
60362
+ */
60363
+ onFail(flow) {
60364
+ this.item.onFail = resolveFlow(flow);
60365
+ return this;
60366
+ }
60367
+ /**
60368
+ * Emit the menu.
60369
+ *
60370
+ * @throws If the `matches` keys cannot be serialised in the order they were written
60371
+ */
60372
+ build() {
60373
+ const item = { ...this.item };
60374
+ if (this.matchOrder.length > 0) {
60375
+ const emitted = Object.keys(this.matches);
60376
+ const reordered = emitted.some((key, index) => key !== this.matchOrder[index]);
60377
+ if (reordered) {
60378
+ throw new Error(`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$'.`);
60379
+ }
60380
+ item.matches = { ...this.matches };
60381
+ }
60382
+ return item;
60383
+ }
60384
+ };
60385
+ var CommandBuilder = class {
60386
+ list = [];
60387
+ pending = [];
60388
+ /**
60389
+ * Speak text on the call.
60390
+ *
60391
+ * @param text - Text to synthesise, or an SSML document when `format` is `SSML`
60392
+ * @param options - Voice and format overrides
60393
+ */
60394
+ say(text, options = {}) {
60395
+ this.pending.push(sayMessage(text, options));
60396
+ return this;
60397
+ }
60398
+ /**
60399
+ * Play an audio file on the call.
60400
+ *
60401
+ * @param url - Publicly reachable URL of the audio file
60402
+ */
60403
+ play(url2) {
60404
+ this.pending.push({ type: "PLAY", play: { url: url2 } });
60405
+ return this;
60406
+ }
60407
+ /**
60408
+ * End the call at this point in the sequence.
60409
+ *
60410
+ * Messages queued before it still play in full — and end the call whether they finish or
60411
+ * fail, since a failed playback would otherwise leave the call with nothing to do.
60412
+ * Anything queued after it is emitted after it, and on a live call is never reached.
60413
+ *
60414
+ * @param callName - Leg to end. Ends the current leg when omitted.
60415
+ */
60416
+ hangup(callName) {
60417
+ const command = () => ({ command: "hangup", ...callName && { callName } });
60418
+ if (this.pending.length > 0) {
60419
+ this.list.push({
60420
+ command: "messages",
60421
+ messages: this.pending.splice(0),
60422
+ // Both outcomes, for the same reason a `dial`'s events block is completed: `messages`
60423
+ // models `onFinish` *and* `onFailure`, and a playback that fails — an audio URL the
60424
+ // platform cannot fetch — would otherwise reach neither this list nor the service
60425
+ // webhook, leaving the call sitting with no next command.
60426
+ events: { onFinish: [command()], onFailure: [command()] }
60427
+ });
60428
+ } else {
60429
+ this.list.push(command());
60430
+ }
60431
+ return this;
60432
+ }
60433
+ /** Explicitly answer an inbound leg. */
60434
+ answer() {
60435
+ return this.push({ command: "answer" });
60436
+ }
60437
+ /**
60438
+ * Add the current leg to a named bridge, creating the bridge on first reference.
60439
+ *
60440
+ * @param bridgeName - Bridge name (1-32 chars, no whitespace)
60441
+ */
60442
+ bridgeCall(bridgeName) {
60443
+ return this.push({ command: "bridgeCall", bridgeName });
60444
+ }
60445
+ /**
60446
+ * Dial another leg. Non-blocking — two dials in one list ring two legs in parallel.
60447
+ *
60448
+ * @param to - Who to call
60449
+ * @param options - Dial settings, named events and leg topology
60450
+ */
60451
+ dial(to, options = {}) {
60452
+ return this.push(buildDial(toEndpoint(to), options));
60453
+ }
60454
+ /**
60455
+ * Collect DTMF input against a named menu. Blocking.
60456
+ *
60457
+ * Consecutive `menu()` calls extend one `menu` command, so a multi-level IVR is written as
60458
+ * a run of them and `gotoMenu` jumps between the names. The first one names `startMenu`.
60459
+ * Anything written between two menus (a `say`, a `dial`) breaks the run, and the next
60460
+ * `menu()` starts a second command — the list stays in the order it was written.
60461
+ *
60462
+ * @param name - Menu name, referenced by {@link gotoMenu} and reported on `call.menu`
60463
+ * @param define - Callback receiving the {@link MenuItemBuilder} for this menu
60464
+ *
60465
+ * @example
60466
+ * ```typescript
60467
+ * commands().menu('main', (m) =>
60468
+ * m
60469
+ * .prompt((p) => p.say('Press 1 for sales or 2 for support').bargeIn())
60470
+ * .match('1', (c) => c.dial(sales))
60471
+ * .match('2', (c) => c.dial(support))
60472
+ * .onFail((c) => c.say('Sorry, goodbye').hangup())
60473
+ * );
60474
+ * ```
60475
+ */
60476
+ menu(name, define) {
60477
+ this.flush();
60478
+ const builder = new MenuItemBuilder();
60479
+ const item = (define(builder) ?? builder).build();
60480
+ const last = this.list[this.list.length - 1];
60481
+ if (last && last.command === "menu") {
60482
+ last.menus[name] = item;
60483
+ return this;
60484
+ }
60485
+ const command = { command: "menu", startMenu: name, menus: { [name]: item } };
60486
+ this.list.push(command);
60487
+ return this;
60488
+ }
60489
+ /**
60490
+ * Jump to another menu in the enclosing `menu` command. Legal only inside menu execution.
60491
+ *
60492
+ * @param menuName - Menu to enter
60493
+ */
60494
+ gotoMenu(menuName) {
60495
+ return this.push({ command: "gotoMenu", menuName });
60496
+ }
60497
+ /**
60498
+ * Wait before running the next command. Blocking.
60499
+ *
60500
+ * The call stays connected and audio is unaffected — this delays the *script*, not the
60501
+ * media. So it is the way to let a non-blocking command get somewhere before the next one
60502
+ * runs: a beat after `amd` reports a beep, before the message that leaves the voicemail.
60503
+ *
60504
+ * @param durationMilliseconds - How long to wait, in milliseconds. Minimum 1.
60505
+ * @throws If the duration is below the schema's minimum of 1
60506
+ */
60507
+ pause(durationMilliseconds) {
60508
+ if (!Number.isInteger(durationMilliseconds) || durationMilliseconds < 1) {
60509
+ throw new Error(`Voice v2 pause takes a whole number of milliseconds, at least 1 (got ${durationMilliseconds}).`);
60510
+ }
60511
+ return this.push({ command: "pause", durationMilliseconds });
60512
+ }
60513
+ /**
60514
+ * Stop a named `messages` sequence. Non-blocking.
60515
+ *
60516
+ * Targets a sequence by the `messagesName` it was started under, so it is only reachable
60517
+ * from a later command list — a `PATCH` on a live call, or a `dial` event — never from the
60518
+ * same list that queued the messages.
60519
+ *
60520
+ * @param messagesName - Sequence to stop (1-32 chars, no whitespace)
60521
+ * @param flags - `ONLY_PLAYING` cancels the current message and lets the queue continue.
60522
+ * Omitted, the platform applies `ALL_FROM_NOW_ON` and the whole queue goes.
60523
+ */
60524
+ stopMessages(messagesName, flags) {
60525
+ return this.push({ command: "stopMessages", messagesName, ...flags && { flags } });
60526
+ }
60527
+ /**
60528
+ * Run answering machine detection on the call. Non-blocking.
60529
+ *
60530
+ * Detection runs in parallel with the rest of the list; the verdict arrives on one of the
60531
+ * four events, or — with no events named — as a `call.amd.*` webhook.
60532
+ *
60533
+ * These four are the AMD *result* outcomes, so none of them gets a hangup default the way a
60534
+ * `dial`'s never-connected outcomes do. They do follow `dial`'s all-or-nothing rule: naming
60535
+ * any one of them detaches the service webhook from all four, so this emits a **complete**
60536
+ * block once any is named, with the rest as empty lists. Confirmed in `calling-ng` — see
60537
+ * {@link AmdEventOptions}.
60538
+ *
60539
+ * @param events - Commands to run per detection outcome. Omit entirely for webhook mode.
60540
+ *
60541
+ * @example
60542
+ * ```typescript
60543
+ * commands()
60544
+ * .amd({
60545
+ * onHuman: (c) => c.say('Hi, do you have a moment?'),
60546
+ * onMachine: (c) => c.say('Sorry we missed you.').hangup(),
60547
+ * onBeep: (c) => c.pause(500).say('Sorry we missed you.').hangup(),
60548
+ * onUnknown: (c) => c.say('Hi, do you have a moment?'),
60549
+ * })
60550
+ * .say('Connecting you now.');
60551
+ *
60552
+ * // Naming none of them leaves all four to the service webhook as `call.amd.*`.
60553
+ * commands().amd();
60554
+ * ```
60555
+ */
60556
+ amd(events = {}) {
60557
+ const block = completeAmdEvents(events);
60558
+ return this.push({ command: "amd", ...block && { events: block } });
60559
+ }
60560
+ /**
60561
+ * Ask the application what to do next. **Blocking** — the call waits for the response.
60562
+ *
60563
+ * The event is delivered as `call.webhook.<webhookName>`, so `webhookName: 'escalate'`
60564
+ * arrives as `'call.webhook.escalate'`. `Client.onCall` routes those by name to a handler
60565
+ * registered under `webhooks`, and to `manage` when no name matches.
60566
+ *
60567
+ * @param webhookName - Name for this event (1-64 chars, no whitespace)
60568
+ * @param url - URL to call. The platform allows it 5 seconds to answer.
60569
+ * @param options - Fallback URL
60570
+ *
60571
+ * @example
60572
+ * ```typescript
60573
+ * commands().say('One moment.').webhook('escalate', 'https://acme.com/voice');
60574
+ *
60575
+ * export const handler = voice.onCall({
60576
+ * webhooks: { escalate: () => commands().dial('+15550001111') },
60577
+ * });
60578
+ * ```
60579
+ */
60580
+ webhook(webhookName, url2, options = {}) {
60581
+ return this.push({
60582
+ command: "webhook",
60583
+ webhookName,
60584
+ url: url2,
60585
+ ...options.fallbackUrl && { fallbackUrl: options.fallbackUrl }
60586
+ });
60587
+ }
60588
+ /**
60589
+ * Start recording the call. Non-blocking.
60590
+ *
60591
+ * **The credential is a long-lived storage secret carried inside the command body** — the
60592
+ * schema requires it and offers no short-lived alternative. See {@link RecordingCredentials}
60593
+ * before logging anything a `startRecording` is part of.
60594
+ *
60595
+ * @param options - Destination, credentials, encoding, transcription and outcome events
60596
+ * @throws If a structured credential component contains a colon
60597
+ *
60598
+ * @example
60599
+ * ```typescript
60600
+ * commands().startRecording({
60601
+ * recordingName: 'support',
60602
+ * destinationUrl: 's3://voice-recordings-prod/calls',
60603
+ * credentials: {
60604
+ * accessKeyId: process.env.RECORDING_KEY_ID!,
60605
+ * secretAccessKey: process.env.RECORDING_SECRET!,
60606
+ * region: 'eu-central-1',
60607
+ * },
60608
+ * transcribe: true,
60609
+ * });
60610
+ * ```
60611
+ */
60612
+ startRecording(options) {
60613
+ const events = {};
60614
+ if (options.onFinish !== void 0) {
60615
+ events.onFinish = resolveFlow(options.onFinish);
60616
+ }
60617
+ if (options.onFailure !== void 0) {
60618
+ events.onFailure = resolveFlow(options.onFailure);
60619
+ }
60620
+ return this.push({
60621
+ command: "startRecording",
60622
+ ...options.recordingName && { recordingName: options.recordingName },
60623
+ recordingOptions: toRecordingOptions(options),
60624
+ ...Object.keys(events).length > 0 && { events }
60625
+ });
60626
+ }
60627
+ /**
60628
+ * Stop a named recording. Non-blocking.
60629
+ *
60630
+ * A recording started without a `recordingName` cannot be targeted at all — it ends when
60631
+ * the call disconnects and not before.
60632
+ *
60633
+ * @param recordingName - Recording to stop (1-32 chars, no whitespace)
60634
+ */
60635
+ stopRecording(recordingName) {
60636
+ return this.push({ command: "stopRecording", recordingName });
60637
+ }
60638
+ /**
60639
+ * Append a hand-built command — the escape hatch for anything not modelled here.
60640
+ *
60641
+ * @param commands - Commands to append, in order
60642
+ */
60643
+ add(...commands2) {
60644
+ return this.push(...commands2);
60645
+ }
60646
+ /**
60647
+ * Emit the command list.
60648
+ *
60649
+ * Repeatable and non-consuming: the builder is a description of a flow, not a one-shot
60650
+ * handle, so the same one can be sent twice or nested in two places.
60651
+ */
60652
+ build() {
60653
+ const out = [...this.list];
60654
+ if (this.pending.length > 0) {
60655
+ out.push({ command: "messages", messages: [...this.pending] });
60656
+ }
60657
+ return out;
60658
+ }
60659
+ push(...commands2) {
60660
+ this.flush();
60661
+ this.list.push(...commands2);
60662
+ return this;
60663
+ }
60664
+ flush() {
60665
+ if (this.pending.length > 0) {
60666
+ const messages = { command: "messages", messages: this.pending.splice(0) };
60667
+ this.list.push(messages);
60668
+ }
60669
+ }
60670
+ };
60671
+ function commands() {
60672
+ return new CommandBuilder();
60673
+ }
60674
+ function sayMessage(text, options) {
60675
+ return {
60676
+ type: "SAY",
60677
+ say: {
60678
+ text,
60679
+ voiceName: options.voiceName ?? DEFAULT_VOICE,
60680
+ ...options.format && { format: options.format }
60681
+ }
60682
+ };
60683
+ }
60684
+
60685
+ // ../voice-v2-preview/dist/core/plan.js
60686
+ function toCallRequest(plan) {
60687
+ assertCommands(plan);
60688
+ return { commands: plan.commands };
60689
+ }
60690
+ function toWebhookResponse(plan) {
60691
+ assertCommands(plan);
60692
+ const response = { commands: plan.commands };
60693
+ if (plan.callName) {
60694
+ response.callName = plan.callName;
60695
+ }
60696
+ if (plan.onHangup && plan.onHangup.length > 0) {
60697
+ response.events = { onHangup: plan.onHangup };
60698
+ }
60699
+ return response;
60700
+ }
60701
+ function assertCommands(plan) {
60702
+ if (!plan.commands || plan.commands.length === 0) {
60703
+ throw new Error("Voice v2 plan requires at least one command. Build one with commands() \u2014 say(), play(), dial(), answer() or hangup() \u2014 or use call()/callWithStream()/bridge() on the client.");
60704
+ }
60705
+ }
60706
+
60707
+ // ../voice-v2-preview/dist/core/transfer.js
60708
+ var DEFAULT_BRIDGE_NAME = "bridge";
60709
+ var DEFAULT_TRANSFER_LEG = "transfer";
60710
+ var DEFAULT_TRANSFER_TIMEOUT = 30;
60711
+ function buildTransferCommands(to, options = {}) {
60712
+ const bridgeName = options.bridgeName ?? DEFAULT_BRIDGE_NAME;
60713
+ return commands().dial(to, {
60714
+ callName: options.callName ?? DEFAULT_TRANSFER_LEG,
60715
+ ...options.from !== void 0 && { from: options.from },
60716
+ timeout: options.timeout ?? DEFAULT_TRANSFER_TIMEOUT,
60717
+ onAnswer: (c) => c.bridgeCall(bridgeName),
60718
+ // Two legs, so both defaults are leg-aware rather than a bare hangup of this one.
60719
+ ...options.endLeg !== void 0 && {
60720
+ endOnHangup: options.endLeg,
60721
+ endOnFailure: options.endLeg
60722
+ }
60723
+ }).build();
60724
+ }
60725
+
60726
+ // ../voice-v2-preview/dist/core/client.js
60727
+ var ORIGIN_LEG = "origin";
60728
+ var STREAM_LEG = "stream";
60729
+ var RELAY_LEG = "relay";
60730
+ var EVENT_MAP = {
60731
+ "call.incoming": "incoming",
60732
+ "call.answered": "answered",
60733
+ "call.menu": "manage",
60734
+ "call.hangup": "completed",
60735
+ "call.failed": "completed"
60736
+ };
60737
+ function resolveHandlerKey(event) {
60738
+ const name = stripLegacyPrefix(event);
60739
+ if (name.startsWith(WEBHOOK_EVENT_PREFIX)) {
60740
+ return "manage";
60741
+ }
60742
+ return EVENT_MAP[name];
60743
+ }
60744
+ var WEBHOOK_EVENT_PREFIX = "call.webhook.";
60745
+ function stripLegacyPrefix(event) {
60746
+ return event.startsWith("webhook.") ? event.slice("webhook.".length) : event;
60747
+ }
60748
+ function resolveWebhookName(event) {
60749
+ const name = stripLegacyPrefix(event);
60750
+ return name.startsWith(WEBHOOK_EVENT_PREFIX) ? name.slice(WEBHOOK_EVENT_PREFIX.length) || void 0 : void 0;
60751
+ }
60752
+ var Client = class {
60753
+ publicUrl;
60754
+ /**
60755
+ * The lower layer, reached only through the interface this half of the module owns.
60756
+ *
60757
+ * This field and the `new HttpTransport` below are the whole coupling between the
60758
+ * command builder and the network. When `@sinch/voice@2` ships, an adapter over the
60759
+ * SDK replaces that one expression and nothing else in this file moves.
60760
+ */
60761
+ transport;
60762
+ /**
60763
+ * @param context - Function context, used for env and for the public host
60764
+ * @param options - Explicit overrides for anything the context cannot supply
60765
+ */
60766
+ constructor(context, options = {}) {
60767
+ const env = context?.env ?? process.env;
60768
+ this.publicUrl = toWebSocketBase(options.publicUrl ?? context?.host);
60769
+ this.transport = new HttpTransport({
60770
+ projectId: options.projectId ?? env.PROJECT_ID ?? context?.config?.projectId ?? "",
60771
+ keyId: options.keyId ?? env.PROJECT_ID_API_KEY ?? "",
60772
+ keySecret: options.keySecret ?? env.PROJECT_ID_API_SECRET ?? "",
60773
+ ...options.host !== void 0 && { host: options.host },
60774
+ ...options.fetch !== void 0 && { fetch: options.fetch }
60775
+ });
60776
+ }
60777
+ /**
60778
+ * Serialise without reaching the credentials.
60779
+ *
60780
+ * This client is `context.voice`, an enumerable member of the function context, so a
60781
+ * `JSON.stringify(context)` in user code or a structured log line walks straight into the
60782
+ * transport. The transport keeps the Access Key in `#` fields and redacts itself as well;
60783
+ * this stops anything later added to the client — the v1 SDK namespace `attachVoiceClient`
60784
+ * assigns onto `.v1`, for one — from being serialised by accident.
60785
+ */
60786
+ toJSON() {
60787
+ return {
60788
+ client: "Client",
60789
+ transport: this.transport,
60790
+ ...this.publicUrl !== void 0 && { publicUrl: this.publicUrl }
60791
+ };
60792
+ }
60793
+ /**
60794
+ * Place an outbound call.
60795
+ *
60796
+ * Name the events you want handled inline and they are sent as a **complete** block, with
60797
+ * busy, rejected, timed-out and failed defaulting to hangup. Name none and no `events` key
60798
+ * is sent at all, which is what hands the call to the service webhook.
60799
+ *
60800
+ * There is no half-way house, and that is the platform's rule rather than this client's:
60801
+ * `events` present means the service webhook is attached to *none* of the six lists, so a
60802
+ * lone `onAnswer` would silently stop busy and hangup from being handled by anything.
60803
+ *
60804
+ * @param to - Who to call
60805
+ * @param options - Dial settings and named events
60806
+ * @throws If the API rejects the request
60807
+ *
60808
+ * @example
60809
+ * ```typescript
60810
+ * // Inline: say a line and hang up, failures end the call
60811
+ * await voice.call('+15559876543', {
60812
+ * from: '+15551234567',
60813
+ * onAnswer: (c) => c.say('Your appointment is confirmed.').hangup(),
60814
+ * });
60815
+ *
60816
+ * // A flow built once and reused
60817
+ * const greeting = commands().say('One moment').bridgeCall('support');
60818
+ * await voice.call('+15559876543', { onAnswer: greeting });
60819
+ *
60820
+ * // Service-webhook mode: no events named, so `call.answered` fires
60821
+ * await voice.call('+15559876543', { from: '+15551234567' });
60822
+ * ```
60823
+ */
60824
+ call(to, options = {}) {
60825
+ return this.raw(toCallRequest(this.planCall(to, options)));
60826
+ }
60827
+ /**
60828
+ * Build the {@link call} flow without sending it.
60829
+ *
60830
+ * @param to - Who to call
60831
+ * @param options - Dial settings and named events
60832
+ */
60833
+ planCall(to, options = {}) {
60834
+ return {
60835
+ commands: [
60836
+ buildDial(toEndpoint(to), { ...options, callName: options.callName ?? ORIGIN_LEG })
60837
+ ]
60838
+ };
60839
+ }
60840
+ /**
60841
+ * Call a destination and put a WebSocket audio stream on the same call.
60842
+ *
60843
+ * Dials the destination as leg `origin`; on answer that leg joins a bridge and a
60844
+ * second leg is dialled to the STREAM endpoint, which joins the same bridge.
60845
+ * Either leg hanging up ends the other.
60846
+ *
60847
+ * `streamOptions` is always sent in full — the platform defaults to 44100 Hz
60848
+ * when the object is omitted and to 8000 Hz when it is partially supplied.
60849
+ *
60850
+ * Both endpoints are positional, mirroring {@link bridge}: this dials two things and
60851
+ * bridges them, and neither of them has a sensible default. In particular there is no
60852
+ * honest default path for the audio leg — the runtime neither serves nor owns one — so
60853
+ * the socket URL is as required as the number.
60854
+ *
60855
+ * @param to - Who to call
60856
+ * @param stream - WebSocket endpoint for the audio leg. Either a full `ws://`/`wss://`
60857
+ * URL or an absolute path, resolved against this function's public URL.
60858
+ * @param options - Headers, sample rate, bridge name and dial settings
60859
+ * @throws If the stream path cannot be resolved, or if the API rejects the request
60860
+ *
60861
+ * @example
60862
+ * ```typescript
60863
+ * // Relative path, resolved against the function's public host
60864
+ * await voice.callWithStream('+15559876543', '/media', {
60865
+ * from: '+15551234567',
60866
+ * headers: { 'x-contact-id': 'abc123' },
60867
+ * });
60868
+ *
60869
+ * // Full URL, 8 kHz to match a PSTN-only path
60870
+ * await voice.callWithStream('+15559876543', 'wss://example.com/audio', {
60871
+ * from: '+15551234567',
60872
+ * sampleRate: 8000,
60873
+ * });
60874
+ * ```
60875
+ */
60876
+ callWithStream(to, stream4, options) {
60877
+ return this.raw(toCallRequest(this.planStreamCall(to, stream4, options)));
60878
+ }
60879
+ /**
60880
+ * Build the {@link callWithStream} flow without sending it.
60881
+ *
60882
+ * @param to - Who to call
60883
+ * @param stream - WebSocket endpoint for the audio leg, as a URL or an absolute path
60884
+ * @param options - Headers, sample rate, bridge name and dial settings
60885
+ * @throws If the stream path cannot be resolved
60886
+ */
60887
+ planStreamCall(to, stream4, options = {}) {
60888
+ const headers = toCallHeaders(options.headers);
60889
+ const streamEndpoint = {
60890
+ type: "STREAM",
60891
+ stream: {
60892
+ endpoint: this.resolveStreamEndpoint(stream4),
60893
+ streamOptions: defaultStreamOptions(options.sampleRate),
60894
+ ...headers && { callHeaders: headers }
60895
+ }
60896
+ };
60897
+ return this.planBridged(toEndpoint(to), streamEndpoint, STREAM_LEG, options);
60898
+ }
60899
+ /**
60900
+ * Call a destination and put the Voice Relay service on the same call.
60901
+ *
60902
+ * Same topology as {@link callWithStream} — dial the human, bridge a second leg — but the
60903
+ * second leg is a VOICE_RELAY endpoint rather than a raw audio socket: Sinch runs STT and
60904
+ * TTS, and the application exchanges text. The trade is that the application never owns
60905
+ * the TTS stream, which rules the relay out for anything that needs its own voice or
60906
+ * needs to inject filler speech while an LLM thinks.
60907
+ *
60908
+ * The relay socket is positional and required: the `voiceRelay` schema (spec line 2946)
60909
+ * requires `endpoint`, so there is no relay leg without one.
60910
+ *
60911
+ * @param to - Who to call
60912
+ * @param relay - WebSocket endpoint the relay connects to. Either a full `ws://`/`wss://`
60913
+ * URL or an absolute path, resolved against this function's public URL.
60914
+ * @param options - Voice, transcription language, barge-in, bridge name and dial settings
60915
+ * @throws If the API rejects the request
60916
+ */
60917
+ callWithRelay(to, relay, options) {
60918
+ return this.raw(toCallRequest(this.planRelayCall(to, relay, options)));
60919
+ }
60920
+ /**
60921
+ * Build the {@link callWithRelay} flow without sending it.
60922
+ *
60923
+ * @param to - Who to call
60924
+ * @param relay - WebSocket endpoint the relay connects to, as a URL or an absolute path
60925
+ * @param options - Voice, transcription language, barge-in, bridge name and dial settings
60926
+ */
60927
+ planRelayCall(to, relay, options = {}) {
60928
+ const relayEndpoint = dialRelay(this.resolveStreamEndpoint(relay), {
60929
+ ...options.ttsVoice && { ttsVoice: options.ttsVoice },
60930
+ ...options.sttLanguage && { sttLanguage: options.sttLanguage },
60931
+ ...options.enableInterruptions !== void 0 && {
60932
+ enableInterruptions: options.enableInterruptions
60933
+ },
60934
+ ...options.headers && { headers: options.headers }
60935
+ });
60936
+ return this.planBridged(toEndpoint(to), relayEndpoint, RELAY_LEG, options);
60937
+ }
60938
+ /**
60939
+ * Call two destinations and bridge them together.
60940
+ *
60941
+ * @param a - First party, dialled as leg `origin`
60942
+ * @param b - Second party, dialled once `a` answers
60943
+ * @param options - Dial settings and bridge name
60944
+ *
60945
+ * @example
60946
+ * ```typescript
60947
+ * await voice.bridge('+15551110000', '+15552220000', { from: '+15551234567' });
60948
+ * ```
60949
+ */
60950
+ bridge(a, b, options = {}) {
60951
+ return this.raw(toCallRequest(this.planBridge(a, b, options)));
60952
+ }
60953
+ /**
60954
+ * Build the {@link bridge} flow without sending it.
60955
+ *
60956
+ * @param a - First party, dialled as leg `origin`
60957
+ * @param b - Second party, dialled once `a` answers
60958
+ * @param options - Dial settings and bridge name
60959
+ */
60960
+ planBridge(a, b, options = {}) {
60961
+ return this.planBridged(toEndpoint(a), toEndpoint(b), "destination", options);
60962
+ }
60963
+ /**
60964
+ * End one or more legs of a live call.
60965
+ *
60966
+ * @param target - The live call, addressed by `callId` or by `sessionId` + `callName`
60967
+ * @param callNames - Legs to end. Ends the addressed leg when omitted.
60968
+ *
60969
+ * @example
60970
+ * ```typescript
60971
+ * await voice.hangup({ sessionId }, 'origin', 'stream');
60972
+ * ```
60973
+ */
60974
+ hangup(target, ...callNames) {
60975
+ return this.patch(target, this.planHangup(...callNames));
60976
+ }
60977
+ /**
60978
+ * Build the {@link hangup} command list without sending it.
60979
+ *
60980
+ * @param callNames - Legs to end. Ends the addressed leg when omitted.
60981
+ */
60982
+ planHangup(...callNames) {
60983
+ const flow = commands();
60984
+ if (callNames.length > 0) {
60985
+ for (const callName of callNames) {
60986
+ flow.hangup(callName);
60987
+ }
60988
+ } else {
60989
+ flow.hangup();
60990
+ }
60991
+ return flow.build();
60992
+ }
60993
+ /**
60994
+ * Run commands against a live call — the escalation path.
60995
+ *
60996
+ * @param target - The live call, addressed by `callId` or by `sessionId` + `callName`
60997
+ * @param flow - Commands to execute in the context of the addressed leg, in any
60998
+ * {@link Flow} spelling
60999
+ * @throws If the API rejects the request
61000
+ *
61001
+ * @example
61002
+ * ```typescript
61003
+ * // Pull a human agent into an in-progress streamed call
61004
+ * await voice.patch({ sessionId, callName: 'origin' }, (c) =>
61005
+ * c.bridgeCall('escalation').dial('+15550001111', {
61006
+ * callName: 'agent',
61007
+ * onAnswer: (a) => a.bridgeCall('escalation'),
61008
+ * endOnFailure: 'origin',
61009
+ * })
61010
+ * );
61011
+ * ```
61012
+ */
61013
+ async patch(target, flow) {
61014
+ await this.transport.patchCall(target, resolveFlow(flow));
61015
+ }
61016
+ /**
61017
+ * Dial a party into a live call's bridge — the transfer v1 has no equivalent of.
61018
+ *
61019
+ * The named sugar over {@link patch}: it sends exactly
61020
+ * `patch(target, buildTransferCommands(to, options))`, and the value is entirely in what
61021
+ * that builder puts around the dial. See {@link buildTransferCommands} for why every
61022
+ * non-answer outcome has to end another leg.
61023
+ *
61024
+ * ### Why both a target and a bridge name
61025
+ *
61026
+ * They address different things and neither is redundant. {@link PatchTarget} pins the
61027
+ * **session** — by `callId`, or by `sessionId` plus the leg the commands run in the context
61028
+ * of. `bridgeName` then resolves **within** that session, because `bridgeCall` joins the
61029
+ * current call to a bridge "in the same session". That scoping is also what makes the
61030
+ * default safe: two unrelated calls both using `bridge` are in two different sessions, so
61031
+ * they cannot meet.
61032
+ *
61033
+ * The one genuinely ambiguous case is inside a single session: reuse a name for what you
61034
+ * meant as two bridges and you get one bridge, because joining a name that already exists
61035
+ * is documented to join it rather than create a second.
61036
+ *
61037
+ * @param target - The live call, addressed by `callId` or by `sessionId` + `callName`
61038
+ * @param to - Party to dial: an E.164 number, a `sip:` URI, or an endpoint object
61039
+ * @param options - Bridge, caller id, dial timeout, leg names
61040
+ * @throws If the API rejects the request
61041
+ *
61042
+ * @example
61043
+ * ```typescript
61044
+ * // A call placed by this client with default options: the bridge is already known
61045
+ * await voice.transfer({ sessionId, callName: 'origin' }, '+15550001111', {
61046
+ * endLeg: 'origin',
61047
+ * });
61048
+ *
61049
+ * // A call whose bridge was named, or one this package did not place
61050
+ * await voice.transfer({ callId }, 'sip:agent@pbx.example.com', {
61051
+ * bridgeName: 'agent',
61052
+ * endLeg: 'stream',
61053
+ * });
61054
+ * ```
61055
+ */
61056
+ transfer(target, to, options = {}) {
61057
+ return this.patch(target, buildTransferCommands(to, options));
61058
+ }
61059
+ /**
61060
+ * Post a call-create body verbatim — the escape hatch for anything this client
61061
+ * does not model.
61062
+ *
61063
+ * The body type is deliberately permissive rather than the `callRequest` shape: the wire
61064
+ * command types are internal to this module, so anything hand-built here is unchecked by
61065
+ * design. Use {@link toCallRequest} on a plan when you want the shape validated.
61066
+ *
61067
+ * @param body - A `callRequest` body, or any object the API accepts
61068
+ * @throws If the API rejects the request
61069
+ */
61070
+ raw(body) {
61071
+ return this.transport.createCall(body);
61072
+ }
61073
+ /**
61074
+ * Build a webhook dispatcher over the v2 call lifecycle.
61075
+ *
61076
+ * Handlers may return a plan, a command builder, a bare command array, or nothing.
61077
+ * Nothing means "no commands" and yields `undefined`, which a handler should
61078
+ * turn into a `204`.
61079
+ *
61080
+ * @param handlers - Handlers keyed by lifecycle stage
61081
+ * @returns A function that maps a webhook payload to a response body
61082
+ *
61083
+ * @example
61084
+ * ```typescript
61085
+ * export const handleVoiceWebhook = voice.onCall({
61086
+ * incoming: () => commands().answer().say('Thanks for calling').hangup(),
61087
+ * completed: (event) => {
61088
+ * console.log('call ended', event.call.callId);
61089
+ * },
61090
+ * });
61091
+ * ```
61092
+ */
61093
+ onCall(handlers) {
61094
+ return async (event) => {
61095
+ const webhookName = resolveWebhookName(event.event);
61096
+ const key = resolveHandlerKey(event.event);
61097
+ const handler = webhookName && handlers.webhooks?.[webhookName] || key && handlers[key] || handlers.fallback;
61098
+ if (!handler) {
61099
+ return void 0;
61100
+ }
61101
+ const result2 = await handler(event);
61102
+ if (!result2) {
61103
+ return void 0;
61104
+ }
61105
+ const plan = Array.isArray(result2) || result2 instanceof CommandBuilder ? { commands: resolveFlow(result2) } : result2;
61106
+ return toWebhookResponse(plan);
61107
+ };
61108
+ }
61109
+ // ============================================
61110
+ // Internals
61111
+ // ============================================
61112
+ /**
61113
+ * The bridged shape: dial one leg, and on answer join a bridge and dial the second into it.
61114
+ *
61115
+ * The leg-aware defaults live here because this is where the topology is known. The second
61116
+ * leg names the first in both `endOnHangup` and `endOnFailure` — every way it can fail ends
61117
+ * the first one too, or `callWithStream` strands the human on a bridge with nothing on the
61118
+ * other side, and a stream-first plan leaves an answered WebSocket leg (with its billed
61119
+ * STT/TTS/LLM sockets) running to the platform's 14400-second ceiling talking to nobody.
61120
+ *
61121
+ * The first leg names the second in `endOnHangup` only. Its failure events fire *before*
61122
+ * the second leg has been dialled, so naming it there would target a leg that does not
61123
+ * exist; a bare hangup is the leg-aware answer for the first leg of a call.
61124
+ */
61125
+ planBridged(first, second, secondLeg, options) {
61126
+ const bridgeName = options.bridgeName ?? DEFAULT_BRIDGE_NAME;
61127
+ const secondDial = buildDial(second, {
61128
+ ...options,
61129
+ callName: secondLeg,
61130
+ onAnswer: (c) => c.bridgeCall(bridgeName),
61131
+ endOnHangup: ORIGIN_LEG,
61132
+ endOnFailure: ORIGIN_LEG
61133
+ });
61134
+ const originDial = buildDial(first, {
61135
+ ...options,
61136
+ callName: ORIGIN_LEG,
61137
+ onAnswer: (c) => c.bridgeCall(bridgeName).add(secondDial),
61138
+ endOnHangup: secondLeg
61139
+ });
61140
+ return { commands: [originDial] };
61141
+ }
61142
+ resolveStreamEndpoint(stream4) {
61143
+ if (/^wss?:\/\//i.test(stream4)) {
61144
+ return stream4;
61145
+ }
61146
+ if (!stream4.startsWith("/")) {
61147
+ throw new Error(`Stream endpoint '${stream4}' must be a ws:// or wss:// URL, or an absolute path such as '/stream'.`);
61148
+ }
61149
+ if (!this.publicUrl) {
61150
+ throw new Error(`Cannot resolve stream path '${stream4}' \u2014 this function's public URL is unknown. Pass a full wss:// URL, or set the publicUrl option (context.host is only present in production).`);
61151
+ }
61152
+ return `${this.publicUrl}${stream4}`;
61153
+ }
61154
+ };
61155
+ function createClient(context, options) {
61156
+ return new Client(context, options);
61157
+ }
61158
+ function toWebSocketBase(base) {
61159
+ if (!base) {
61160
+ return void 0;
61161
+ }
61162
+ const trimmed = base.replace(/\/$/, "");
61163
+ if (/^wss?:\/\//i.test(trimmed)) {
61164
+ return trimmed;
61165
+ }
61166
+ if (/^https:\/\//i.test(trimmed)) {
61167
+ return `wss://${trimmed.slice("https://".length)}`;
61168
+ }
61169
+ if (/^http:\/\//i.test(trimmed)) {
61170
+ return `ws://${trimmed.slice("http://".length)}`;
61171
+ }
61172
+ return `wss://${trimmed}`;
61173
+ }
61174
+
61175
+ // ../runtime-shared/dist/voice/client.js
61176
+ function attachVoiceClient(context, v1) {
61177
+ let client;
61178
+ Object.defineProperty(context, "voice", {
61179
+ configurable: true,
61180
+ enumerable: true,
61181
+ get() {
61182
+ if (!client) {
61183
+ client = Object.assign(createClient(context), { v1 });
61184
+ }
61185
+ return client;
61186
+ }
61187
+ });
61188
+ return context;
61189
+ }
61190
+ function onCall(handlers) {
61191
+ return async (context, event) => {
61192
+ const response = await context.voice.onCall(handlers)(event);
61193
+ if (!response) {
61194
+ return void 0;
61195
+ }
61196
+ return {
61197
+ commands: response.commands,
61198
+ ...response.callName && { callName: response.callName },
61199
+ ...response.events?.onHangup && { onHangup: response.events.onHangup }
61200
+ };
61201
+ };
61202
+ }
61203
+
59885
61204
  // ../runtime-shared/dist/host/middleware.js
59886
61205
  var import_express = __toESM(require_express2(), 1);
59887
61206
  var defaultOptions = {
@@ -60103,6 +61422,83 @@ function createSecurityOptions(config) {
60103
61422
  };
60104
61423
  }
60105
61424
 
61425
+ // ../runtime-shared/dist/security/voice-signature.js
61426
+ import { createHash, createHmac, timingSafeEqual as timingSafeEqual2 } from "crypto";
61427
+ var VOICE_TIMESTAMP_SKEW_MS = 5 * 60 * 1e3;
61428
+ var VOICE_MISSING_SECRET_WARNING = "Voice v2 webhook not verified: VOICE_SERVICE_SECRET is not set; Sinch does not expose the service secret yet";
61429
+ var AUTHORIZATION_PATTERN = /^service\s+([^:\s]+):(\S+)$/i;
61430
+ function fail(reason) {
61431
+ return { valid: false, reason };
61432
+ }
61433
+ function buildStringToSign(request, body) {
61434
+ const hasBody = body.length > 0;
61435
+ return [
61436
+ request.method.toUpperCase(),
61437
+ hasBody ? createHash("md5").update(body, "utf8").digest("base64") : "",
61438
+ hasBody ? request.contentType ?? "" : "",
61439
+ `x-timestamp:${request.timestamp ?? ""}`,
61440
+ request.path
61441
+ ].join("\n");
61442
+ }
61443
+ function validateVoiceSignature(request, options) {
61444
+ if (request.body === void 0) {
61445
+ return fail("raw request body is unavailable, so the signature cannot be recomputed");
61446
+ }
61447
+ const match = AUTHORIZATION_PATTERN.exec(request.authorization?.trim() ?? "");
61448
+ if (!match) {
61449
+ return fail('Authorization header is missing or is not "service <serviceId>:<signature>"');
61450
+ }
61451
+ const [, serviceId, signature] = match;
61452
+ if (options.serviceId && serviceId !== options.serviceId) {
61453
+ return fail("service id in the Authorization header does not match VOICE_SERVICE_ID");
61454
+ }
61455
+ const timestamp = request.timestamp?.trim();
61456
+ if (!timestamp) {
61457
+ return fail("x-timestamp header is missing");
61458
+ }
61459
+ const sentAt = Date.parse(timestamp);
61460
+ if (Number.isNaN(sentAt)) {
61461
+ return fail("x-timestamp header is not an ISO 8601 timestamp");
61462
+ }
61463
+ const skewMs = options.skewMs ?? VOICE_TIMESTAMP_SKEW_MS;
61464
+ if (Math.abs((options.now ?? Date.now()) - sentAt) > skewMs) {
61465
+ return fail("x-timestamp header is outside the accepted clock skew window");
61466
+ }
61467
+ const key = Buffer.from(options.serviceSecret, "base64");
61468
+ if (key.length === 0) {
61469
+ return fail("VOICE_SERVICE_SECRET is not a Base64 service secret");
61470
+ }
61471
+ const expected = createHmac("sha256", key).update(buildStringToSign(request, request.body), "utf8").digest();
61472
+ const received = Buffer.from(signature, "base64");
61473
+ if (received.length !== expected.length || !timingSafeEqual2(received, expected)) {
61474
+ return fail("signature does not match the request");
61475
+ }
61476
+ return { valid: true };
61477
+ }
61478
+ var warnedMissingSecret = false;
61479
+ function resetVoiceSignatureWarning() {
61480
+ warnedMissingSecret = false;
61481
+ }
61482
+ function verifyVoiceWebhook(request, options) {
61483
+ if (!shouldValidateWebhook(options.mode, options.isDevelopment)) {
61484
+ return { valid: true };
61485
+ }
61486
+ const env = options.env ?? process.env;
61487
+ const serviceSecret = env.VOICE_SERVICE_SECRET;
61488
+ if (!serviceSecret) {
61489
+ if (!warnedMissingSecret) {
61490
+ warnedMissingSecret = true;
61491
+ console.warn(`[SECURITY] ${VOICE_MISSING_SECRET_WARNING}`);
61492
+ }
61493
+ return { valid: true };
61494
+ }
61495
+ return validateVoiceSignature(request, {
61496
+ serviceSecret,
61497
+ serviceId: env.VOICE_SERVICE_ID,
61498
+ now: options.now
61499
+ });
61500
+ }
61501
+
60106
61502
  // ../runtime-shared/dist/sinch/index.js
60107
61503
  var import_sdk_core = __toESM(require_dist11(), 1);
60108
61504
  function createSinchClients() {
@@ -60263,21 +61659,42 @@ var FAVICON_SVG = `<svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/sv
60263
61659
  function getFaviconSvg() {
60264
61660
  return FAVICON_SVG;
60265
61661
  }
60266
- var VOICE_CALLBACKS = ["ice", "ace", "pie", "dice", "notify"];
61662
+ var VOICE_V1_CALLBACKS = ["ice", "ace", "pie", "dice", "notify"];
60267
61663
  var NOTIFICATION_EVENTS = ["dice", "notify"];
60268
- function isVoiceCallback(functionName) {
60269
- return VOICE_CALLBACKS.includes(functionName);
61664
+ var VOICE_WEBHOOK_HANDLER = "voiceWebhook";
61665
+ var VOICE_EVENT_PREFIX = "call.";
61666
+ function isVoiceV1Callback(functionName) {
61667
+ return VOICE_V1_CALLBACKS.includes(functionName);
60270
61668
  }
60271
61669
  function isNotificationEvent(functionName) {
60272
61670
  return NOTIFICATION_EVENTS.includes(functionName);
60273
61671
  }
61672
+ function isVoiceEvent(event) {
61673
+ return typeof event === "string" && event.startsWith(VOICE_EVENT_PREFIX);
61674
+ }
61675
+ function isVoiceWebhook(body) {
61676
+ return isVoiceEvent(body?.event);
61677
+ }
61678
+ function buildVoiceSignedRequest(req) {
61679
+ return {
61680
+ method: req.method,
61681
+ path: req.originalUrl.split("?")[0] || "/",
61682
+ contentType: req.headers["content-type"],
61683
+ timestamp: req.headers["x-timestamp"],
61684
+ authorization: req.headers.authorization,
61685
+ body: req.rawBody
61686
+ };
61687
+ }
60274
61688
  function extractFunctionName(path6, body) {
60275
- if (body?.event && isVoiceCallback(body.event)) {
61689
+ if (body?.event && isVoiceV1Callback(body.event)) {
60276
61690
  return body.event;
60277
61691
  }
61692
+ if (isVoiceEvent(body?.event)) {
61693
+ return VOICE_WEBHOOK_HANDLER;
61694
+ }
60278
61695
  const pathname = path6.split("?")[0];
60279
61696
  const segments = pathname.split("/").filter((s) => s && s !== "*");
60280
- if (segments.length === 1 && isVoiceCallback(segments[0])) {
61697
+ if (segments.length === 1 && isVoiceV1Callback(segments[0])) {
60281
61698
  return segments[0];
60282
61699
  }
60283
61700
  if (segments.length >= 2 && segments[0] === "webhook") {
@@ -60339,12 +61756,12 @@ function formatCustomResponse(result2) {
60339
61756
  body: response.body
60340
61757
  };
60341
61758
  }
60342
- function validateVoiceRequest(body) {
61759
+ function validateVoiceV1Request(body) {
60343
61760
  if (!body || typeof body !== "object") {
60344
61761
  return {
60345
61762
  valid: false,
60346
61763
  error: "Missing request body",
60347
- expectedEvents: [...VOICE_CALLBACKS]
61764
+ expectedEvents: [...VOICE_V1_CALLBACKS]
60348
61765
  };
60349
61766
  }
60350
61767
  const data = body;
@@ -60352,7 +61769,7 @@ function validateVoiceRequest(body) {
60352
61769
  return {
60353
61770
  valid: false,
60354
61771
  error: "Missing event type in request body",
60355
- expectedEvents: [...VOICE_CALLBACKS]
61772
+ expectedEvents: [...VOICE_V1_CALLBACKS]
60356
61773
  };
60357
61774
  }
60358
61775
  if (!data.callId) {
@@ -60403,7 +61820,7 @@ function buildBaseContext(req, config = {}) {
60403
61820
  }
60404
61821
  };
60405
61822
  }
60406
- async function handleVoiceCallback(functionName, userFunction, context, callbackData, logger) {
61823
+ async function handleVoiceV1Callback(functionName, userFunction, context, callbackData, logger) {
60407
61824
  const handler = userFunction[functionName];
60408
61825
  if (!handler || typeof handler !== "function") {
60409
61826
  if (functionName === "ice") {
@@ -60449,6 +61866,27 @@ async function handleVoiceCallback(functionName, userFunction, context, callback
60449
61866
  }
60450
61867
  return formatSvamlResponse(result2, functionName);
60451
61868
  }
61869
+ async function handleVoiceWebhook(userFunction, context, event, logger) {
61870
+ const handler = userFunction[VOICE_WEBHOOK_HANDLER];
61871
+ if (!handler || typeof handler !== "function") {
61872
+ throw new Error(`No export '${VOICE_WEBHOOK_HANDLER}' found for Voice v2 event '${event?.event}'. Export one built with onCall({ incoming: ... }), or drop VOICE_SERVICE_ID to stay on the v1 ice/ace/pie/dice callbacks.`);
61873
+ }
61874
+ const result2 = await handler(context, event);
61875
+ if (logger) {
61876
+ logger("Function result:", result2);
61877
+ }
61878
+ if (result2 === void 0 || result2 === null) {
61879
+ return { statusCode: 204 };
61880
+ }
61881
+ if (!isVoiceResult(result2)) {
61882
+ return formatCustomResponse(result2);
61883
+ }
61884
+ const body = await context.voice.onCall({ fallback: () => result2 })(event);
61885
+ return body === void 0 ? { statusCode: 204 } : { statusCode: 200, headers: { "Content-Type": "application/json" }, body };
61886
+ }
61887
+ function isVoiceResult(result2) {
61888
+ return Array.isArray(result2) || result2 instanceof CommandBuilder || typeof result2 === "object" && Array.isArray(result2.commands);
61889
+ }
60452
61890
  async function handleCustomEndpoint(functionName, userFunction, context, request, logger) {
60453
61891
  let handler = userFunction[functionName];
60454
61892
  if ((!handler || typeof handler !== "function") && functionName === "default") {
@@ -60530,7 +61968,7 @@ function setupRequestHandler(app, options = {}) {
60530
61968
  const functionUrl = pathToFileURL(functionPath).href;
60531
61969
  const module = await import(functionUrl);
60532
61970
  return module.default || module;
60533
- }, buildContext = buildBaseContext, logger = console.log, landingPageEnabled = true, authConfig, authKey, authSecret, onRequestStart = () => {
61971
+ }, buildContext = (req) => attachVoiceClient(buildBaseContext(req)), logger = console.log, landingPageEnabled = true, authConfig, authKey, authSecret, onRequestStart = () => {
60534
61972
  }, onRequestEnd = () => {
60535
61973
  } } = options;
60536
61974
  app.use("/{*splat}", async (req, res) => {
@@ -60573,7 +62011,7 @@ function setupRequestHandler(app, options = {}) {
60573
62011
  const isDev = process.env.NODE_ENV !== "production" && process.env.ASPNETCORE_ENVIRONMENT !== "Production";
60574
62012
  if (shouldValidateWebhook(protectionMode, isDev)) {
60575
62013
  const sinchClients = getSinchClients();
60576
- if (isVoiceCallback(functionName) && sinchClients.validateWebhookSignature) {
62014
+ if (isVoiceV1Callback(functionName) && sinchClients.validateWebhookSignature) {
60577
62015
  const rawBody = req.rawBody;
60578
62016
  if (rawBody === void 0) {
60579
62017
  logger("[SECURITY] Cannot validate voice webhook signature: raw body unavailable");
@@ -60601,12 +62039,20 @@ function setupRequestHandler(app, options = {}) {
60601
62039
  }
60602
62040
  }
60603
62041
  }
62042
+ if (functionName === VOICE_WEBHOOK_HANDLER && isVoiceWebhook(req.body)) {
62043
+ const verdict = verifyVoiceWebhook(buildVoiceSignedRequest(req), { mode: protectionMode, isDevelopment: isDev });
62044
+ if (!verdict.valid) {
62045
+ logger(`[SECURITY] Voice v2 webhook signature validation failed: ${verdict.reason}`);
62046
+ res.status(401).json({ error: "Invalid webhook signature" });
62047
+ return;
62048
+ }
62049
+ }
60604
62050
  onRequestStart({ functionName, req });
60605
62051
  const context = buildContext(req);
60606
62052
  const userFunction = await Promise.resolve(loadUserFunction());
60607
62053
  let response;
60608
- if (isVoiceCallback(functionName)) {
60609
- const validation = validateVoiceRequest(req.body);
62054
+ if (isVoiceV1Callback(functionName)) {
62055
+ const validation = validateVoiceV1Request(req.body);
60610
62056
  if (!validation.valid) {
60611
62057
  res.status(400).json({
60612
62058
  error: validation.error,
@@ -60614,7 +62060,9 @@ function setupRequestHandler(app, options = {}) {
60614
62060
  });
60615
62061
  return;
60616
62062
  }
60617
- response = await handleVoiceCallback(functionName, userFunction, context, req.body, logger);
62063
+ response = await handleVoiceV1Callback(functionName, userFunction, context, req.body, logger);
62064
+ } else if (functionName === VOICE_WEBHOOK_HANDLER && isVoiceWebhook(req.body)) {
62065
+ response = await handleVoiceWebhook(userFunction, context, req.body, logger);
60618
62066
  } else {
60619
62067
  const request = {
60620
62068
  method: req.method,
@@ -60734,7 +62182,7 @@ var ElevenLabsState = new ElevenLabsStateManager();
60734
62182
 
60735
62183
  // ../runtime-shared/dist/ai/elevenlabs/client.js
60736
62184
  var ELEVENLABS_API_BASE = "https://api.elevenlabs.io/v1";
60737
- var FETCH_TIMEOUT_MS = 1e4;
62185
+ var FETCH_TIMEOUT_MS2 = 1e4;
60738
62186
  var ElevenLabsClient = class {
60739
62187
  apiKey;
60740
62188
  constructor(apiKey) {
@@ -60765,7 +62213,7 @@ var ElevenLabsClient = class {
60765
62213
  method: "POST",
60766
62214
  headers: this.authHeaders,
60767
62215
  body: JSON.stringify(request),
60768
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
62216
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS2)
60769
62217
  });
60770
62218
  if (!response.ok) {
60771
62219
  const error = await response.text();
@@ -60779,7 +62227,7 @@ var ElevenLabsClient = class {
60779
62227
  async getConversationDetails(conversationId) {
60780
62228
  const response = await fetch(`${ELEVENLABS_API_BASE}/convai/conversations/${encodeURIComponent(conversationId)}`, {
60781
62229
  headers: { "xi-api-key": this.apiKey },
60782
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
62230
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS2)
60783
62231
  });
60784
62232
  if (!response.ok) {
60785
62233
  const error = await response.text();
@@ -60817,7 +62265,7 @@ var ElevenLabsClient = class {
60817
62265
  async getOrImportPhoneNumber(config) {
60818
62266
  const listResponse = await fetch(`${ELEVENLABS_API_BASE}/convai/phone-numbers`, {
60819
62267
  headers: this.authHeaders,
60820
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
62268
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS2)
60821
62269
  });
60822
62270
  if (!listResponse.ok) {
60823
62271
  throw new Error(`Failed to list phone numbers: ${listResponse.status}`);
@@ -60849,7 +62297,7 @@ var ElevenLabsClient = class {
60849
62297
  inbound_trunk_config: { media_encryption: "disabled" },
60850
62298
  outbound_trunk_config: sipConfig
60851
62299
  }),
60852
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
62300
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS2)
60853
62301
  });
60854
62302
  if (!createResponse2.ok) {
60855
62303
  const err = await createResponse2.text();
@@ -60872,7 +62320,7 @@ var ElevenLabsClient = class {
60872
62320
  agent_id: agentId,
60873
62321
  outbound_trunk_config: sipConfig
60874
62322
  }),
60875
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
62323
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS2)
60876
62324
  });
60877
62325
  if (!response.ok) {
60878
62326
  await response.text();
@@ -60904,7 +62352,7 @@ var ElevenLabsClient = class {
60904
62352
  }
60905
62353
  }
60906
62354
  }),
60907
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
62355
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS2)
60908
62356
  });
60909
62357
  if (!response.ok) {
60910
62358
  await response.text();
@@ -60999,7 +62447,7 @@ var ElevenLabsController = class {
60999
62447
  try {
61000
62448
  const request = req.body;
61001
62449
  const response = await this.handleConversationInit(request);
61002
- res.json(response);
62450
+ res.json({ type: "conversation_initiation_client_data", ...response });
61003
62451
  } catch (error) {
61004
62452
  console.error("[ElevenLabs] Error in conversation init:", error);
61005
62453
  res.status(500).json({ error: "Internal server error" });
@@ -61038,7 +62486,7 @@ var ElevenLabsController = class {
61038
62486
  };
61039
62487
 
61040
62488
  // ../runtime-shared/dist/ai/elevenlabs/autoconfigurator.js
61041
- var FETCH_TIMEOUT_MS2 = 1e4;
62489
+ var FETCH_TIMEOUT_MS3 = 1e4;
61042
62490
  function maskPhone(phone) {
61043
62491
  if (phone.length <= 6)
61044
62492
  return "***";
@@ -61121,7 +62569,7 @@ async function autoDiscoverPhoneNumber() {
61121
62569
  const auth = Buffer.from(`${appKey}:${appSecret}`).toString("base64");
61122
62570
  const configResponse = await fetch(`https://callingapi.sinch.com/v1/configuration/numbers/`, {
61123
62571
  headers: { Authorization: `Basic ${auth}` },
61124
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS2)
62572
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS3)
61125
62573
  });
61126
62574
  if (!configResponse.ok) {
61127
62575
  console.warn(`[ElevenLabs] Failed to query Voice API for phone numbers: ${configResponse.status}`);
@@ -64977,7 +66425,7 @@ utils_default.freezeMethods(AxiosHeaders);
64977
66425
  var AxiosHeaders_default = AxiosHeaders;
64978
66426
 
64979
66427
  // ../../node_modules/axios/lib/core/AxiosError.js
64980
- var REDACTED = "[REDACTED ****]";
66428
+ var REDACTED2 = "[REDACTED ****]";
64981
66429
  function hasOwnOrPrototypeToJSON(source) {
64982
66430
  if (utils_default.hasOwnProp(source, "toJSON")) {
64983
66431
  return true;
@@ -65018,7 +66466,7 @@ function redactConfig(config, redactKeys) {
65018
66466
  }
65019
66467
  result2 = /* @__PURE__ */ Object.create(null);
65020
66468
  for (const [key, value] of Object.entries(source)) {
65021
- const reducedValue = lowerKeys.has(key.toLowerCase()) ? REDACTED : visit(value);
66469
+ const reducedValue = lowerKeys.has(key.toLowerCase()) ? REDACTED2 : visit(value);
65022
66470
  if (!utils_default.isUndefined(reducedValue)) {
65023
66471
  result2[key] = reducedValue;
65024
66472
  }
@@ -68761,6 +70209,46 @@ async function configureElevenLabs() {
68761
70209
  console.log("\u26A0\uFE0F Could not configure ElevenLabs:", error instanceof Error ? error.message : error);
68762
70210
  }
68763
70211
  }
70212
+ var VOICE_V2_HOST = "https://voice.api.sinch.com";
70213
+ async function configureVoiceServiceWebhook(tunnelUrl, env = process.env, fetchImpl = globalThis.fetch) {
70214
+ const serviceId = env.VOICE_SERVICE_ID;
70215
+ if (!serviceId) return;
70216
+ const projectId = env.PROJECT_ID;
70217
+ const keyId = env.PROJECT_ID_API_KEY;
70218
+ const keySecret = env.PROJECT_ID_API_SECRET;
70219
+ if (!projectId || !keyId || !keySecret) {
70220
+ console.log(
70221
+ "\u26A0\uFE0F VOICE_SERVICE_ID is set but PROJECT_ID, PROJECT_ID_API_KEY or PROJECT_ID_API_SECRET is missing - skipping Voice service webhook update"
70222
+ );
70223
+ return;
70224
+ }
70225
+ const url2 = `${VOICE_V2_HOST}/v2/projects/${encodeURIComponent(projectId)}/services/${encodeURIComponent(serviceId)}`;
70226
+ try {
70227
+ const response = await fetchImpl(url2, {
70228
+ method: "PATCH",
70229
+ headers: {
70230
+ Authorization: `Basic ${Buffer.from(`${keyId}:${keySecret}`).toString("base64")}`,
70231
+ "Content-Type": "application/json"
70232
+ },
70233
+ body: JSON.stringify({
70234
+ callBehavior: { type: "WEBHOOK", webhook: { url: tunnelUrl } }
70235
+ })
70236
+ });
70237
+ if (!response.ok) {
70238
+ console.log(
70239
+ `\u26A0\uFE0F Could not update Voice service webhook (${serviceId}): ${response.status} ${response.statusText}`
70240
+ );
70241
+ return;
70242
+ }
70243
+ console.log(`\u2705 Updated Voice service webhook (${serviceId}) to ${tunnelUrl}`);
70244
+ console.log("\u{1F4A1} Call the number bound to this service in Build to test your voice function!");
70245
+ } catch (error) {
70246
+ console.log(
70247
+ `\u26A0\uFE0F Could not update Voice service webhook (${serviceId}):`,
70248
+ error instanceof Error ? error.message : error
70249
+ );
70250
+ }
70251
+ }
68764
70252
 
68765
70253
  // src/tunnel/ws-stream.ts
68766
70254
  var UPGRADE_TIMEOUT_MS = 1e4;
@@ -69194,9 +70682,9 @@ var TunnelClient = class {
69194
70682
  const hasNewFormat = "AUTO_CONFIGURE" in process.env;
69195
70683
  const autoEnabled = process.env.AUTO_CONFIGURE === "true";
69196
70684
  const sinchServices = (process.env.SINCH_SERVICES ?? "").split(",").map((s) => s.trim());
69197
- const autoConfigVoice = hasNewFormat ? autoEnabled && sinchServices.includes("voice") : process.env.AUTO_CONFIGURE_VOICE !== "false" && !!process.env.VOICE_APPLICATION_KEY;
70685
+ const autoConfigVoice = hasNewFormat ? autoEnabled && sinchServices.includes("voice") : process.env.AUTO_CONFIGURE_VOICE !== "false" && !!(process.env.VOICE_APPLICATION_KEY || process.env.VOICE_SERVICE_ID);
69198
70686
  const autoConfigConversation = hasNewFormat ? autoEnabled && sinchServices.includes("conversation") : process.env.AUTO_CONFIGURE_CONVERSATION !== "false" && !!process.env.CONVERSATION_APP_ID;
69199
- if (autoConfigVoice && process.env.VOICE_APPLICATION_KEY) {
70687
+ if (autoConfigVoice && (process.env.VOICE_APPLICATION_KEY || process.env.VOICE_SERVICE_ID)) {
69200
70688
  await this.configureVoiceWebhooks();
69201
70689
  }
69202
70690
  if (autoConfigConversation && process.env.CONVERSATION_APP_ID) {
@@ -69213,11 +70701,14 @@ var TunnelClient = class {
69213
70701
  await cleanupConversationWebhook(this.webhookConfig);
69214
70702
  }
69215
70703
  async configureVoiceWebhooks() {
70704
+ await configureVoiceServiceWebhook(this.buildTunnelUrl());
69216
70705
  try {
69217
70706
  const appKey = process.env.VOICE_APPLICATION_KEY;
69218
70707
  const appSecret = process.env.VOICE_APPLICATION_SECRET;
69219
70708
  if (!appKey || !appSecret) {
69220
- console.log("\u{1F4A1} Voice API not configured - skipping phone number display");
70709
+ if (!process.env.VOICE_SERVICE_ID) {
70710
+ console.log("\u{1F4A1} Voice API not configured - skipping phone number display");
70711
+ }
69221
70712
  return;
69222
70713
  }
69223
70714
  try {
@@ -69826,6 +71317,9 @@ var SecretsLoader = class {
69826
71317
  var secretsLoader = new SecretsLoader();
69827
71318
 
69828
71319
  export {
71320
+ __require,
71321
+ __commonJS,
71322
+ __toESM,
69829
71323
  AgentProvider,
69830
71324
  AgentSipHelper,
69831
71325
  createConnectAgentAction,
@@ -69842,6 +71336,31 @@ export {
69842
71336
  UniversalConfig,
69843
71337
  createConfig,
69844
71338
  createUniversalConfig,
71339
+ REDACTED,
71340
+ redactCredentials,
71341
+ DEFAULT_HOST,
71342
+ DEFAULT_SAMPLE_RATE,
71343
+ DEFAULT_VOICE,
71344
+ DEFAULT_STT_LANGUAGE,
71345
+ dialPhone,
71346
+ dialSip,
71347
+ dialStream,
71348
+ dialRelay,
71349
+ PromptBuilder,
71350
+ MenuItemBuilder,
71351
+ CommandBuilder,
71352
+ commands,
71353
+ toCallRequest,
71354
+ toWebhookResponse,
71355
+ DEFAULT_BRIDGE_NAME,
71356
+ DEFAULT_TRANSFER_LEG,
71357
+ buildTransferCommands,
71358
+ resolveHandlerKey,
71359
+ resolveWebhookName,
71360
+ Client,
71361
+ createClient,
71362
+ attachVoiceClient,
71363
+ onCall,
69845
71364
  toCamelCase,
69846
71365
  transformKeys,
69847
71366
  parseJson,
@@ -69852,21 +71371,30 @@ export {
69852
71371
  shouldValidateWebhook,
69853
71372
  getProtectionMode,
69854
71373
  createSecurityOptions,
71374
+ VOICE_TIMESTAMP_SKEW_MS,
71375
+ VOICE_MISSING_SECRET_WARNING,
71376
+ validateVoiceSignature,
71377
+ resetVoiceSignatureWarning,
71378
+ verifyVoiceWebhook,
69855
71379
  getSinchClients,
69856
71380
  resetSinchClients,
69857
71381
  getLandingPageHtml,
69858
71382
  getFaviconSvg,
69859
- VOICE_CALLBACKS,
71383
+ VOICE_V1_CALLBACKS,
69860
71384
  NOTIFICATION_EVENTS,
69861
- isVoiceCallback,
71385
+ VOICE_WEBHOOK_HANDLER,
71386
+ isVoiceV1Callback,
69862
71387
  isNotificationEvent,
71388
+ isVoiceWebhook,
71389
+ buildVoiceSignedRequest,
69863
71390
  extractFunctionName,
69864
71391
  generateRequestId,
69865
71392
  formatSvamlResponse,
69866
71393
  formatCustomResponse,
69867
- validateVoiceRequest,
71394
+ validateVoiceV1Request,
69868
71395
  buildBaseContext,
69869
- handleVoiceCallback,
71396
+ handleVoiceV1Callback,
71397
+ handleVoiceWebhook,
69870
71398
  handleCustomEndpoint,
69871
71399
  createApp,
69872
71400
  createSinchRuntime,
@@ -70211,4 +71739,4 @@ serve-static/index.js:
70211
71739
  * MIT Licensed
70212
71740
  *)
70213
71741
  */
70214
- //# sourceMappingURL=chunk-IRSTA74R.js.map
71742
+ //# sourceMappingURL=chunk-VEB6FXNI.js.map