@jambonz/sdk 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/dist/client/index.cjs +60 -13
  2. package/dist/client/index.cjs.map +1 -1
  3. package/dist/client/index.d.cts +36 -7
  4. package/dist/client/index.d.ts +36 -7
  5. package/dist/client/index.js +59 -13
  6. package/dist/client/index.js.map +1 -1
  7. package/dist/common-BSJZX7WO.d.cts +34 -0
  8. package/dist/common-BSJZX7WO.d.ts +34 -0
  9. package/dist/index.cjs +364 -32
  10. package/dist/index.cjs.map +1 -1
  11. package/dist/index.d.cts +8 -7
  12. package/dist/index.d.ts +8 -7
  13. package/dist/index.js +360 -32
  14. package/dist/index.js.map +1 -1
  15. package/dist/rest-BF9HKZrA.d.ts +136 -0
  16. package/dist/rest-v8weIueZ.d.cts +136 -0
  17. package/dist/session-DHc6G_9y.d.cts +112 -0
  18. package/dist/session-DHc6G_9y.d.ts +112 -0
  19. package/dist/types/index.d.cts +4 -3
  20. package/dist/types/index.d.ts +4 -3
  21. package/dist/{verb-builder-But-DJle.d.cts → verb-builder-Dg_IPC4I.d.ts} +35 -2
  22. package/dist/{verb-builder-CO_qoYxC.d.ts → verb-builder-DkHAJrk4.d.cts} +35 -2
  23. package/dist/{verbs-B_afNNUM.d.cts → verbs-fjJjfGEt.d.cts} +40 -14
  24. package/dist/{verbs-B_afNNUM.d.ts → verbs-fjJjfGEt.d.ts} +40 -14
  25. package/dist/webhook/index.cjs +68 -8
  26. package/dist/webhook/index.cjs.map +1 -1
  27. package/dist/webhook/index.d.cts +45 -3
  28. package/dist/webhook/index.d.ts +45 -3
  29. package/dist/webhook/index.js +68 -9
  30. package/dist/webhook/index.js.map +1 -1
  31. package/dist/websocket/index.cjs +291 -19
  32. package/dist/websocket/index.cjs.map +1 -1
  33. package/dist/websocket/index.d.cts +198 -4
  34. package/dist/websocket/index.d.ts +198 -4
  35. package/dist/websocket/index.js +290 -20
  36. package/dist/websocket/index.js.map +1 -1
  37. package/package.json +19 -6
  38. package/schema/callbacks/base.schema.json +29 -0
  39. package/schema/callbacks/call-status.schema.json +22 -0
  40. package/schema/callbacks/conference-status.schema.json +24 -0
  41. package/schema/callbacks/conference-wait.schema.json +11 -0
  42. package/schema/callbacks/conference.schema.json +11 -0
  43. package/schema/callbacks/dequeue.schema.json +19 -0
  44. package/schema/callbacks/dial-dtmf.schema.json +18 -0
  45. package/schema/callbacks/dial-hold.schema.json +22 -0
  46. package/schema/callbacks/dial-refer.schema.json +28 -0
  47. package/schema/callbacks/dial.schema.json +31 -0
  48. package/schema/callbacks/enqueue-wait.schema.json +17 -0
  49. package/schema/callbacks/enqueue.schema.json +27 -0
  50. package/schema/callbacks/gather-partial.schema.json +54 -0
  51. package/schema/callbacks/gather.schema.json +60 -0
  52. package/schema/callbacks/listen.schema.json +21 -0
  53. package/schema/callbacks/llm.schema.json +30 -0
  54. package/schema/callbacks/message.schema.json +35 -0
  55. package/schema/callbacks/play.schema.json +36 -0
  56. package/schema/callbacks/session-new.schema.json +143 -0
  57. package/schema/callbacks/session-reconnect.schema.json +9 -0
  58. package/schema/callbacks/session-redirect.schema.json +38 -0
  59. package/schema/callbacks/sip-refer-event.schema.json +20 -0
  60. package/schema/callbacks/sip-refer.schema.json +22 -0
  61. package/schema/callbacks/sip-request.schema.json +27 -0
  62. package/schema/callbacks/transcribe-translation.schema.json +24 -0
  63. package/schema/callbacks/transcribe.schema.json +46 -0
  64. package/schema/callbacks/verb-status.schema.json +57 -0
  65. package/schema/components/actionHook.schema.json +36 -0
  66. package/schema/components/actionHookDelayAction.schema.json +37 -0
  67. package/schema/components/amd.schema.json +68 -0
  68. package/schema/components/auth.schema.json +18 -0
  69. package/schema/components/bidirectionalAudio.schema.json +22 -0
  70. package/schema/components/fillerNoise.schema.json +25 -0
  71. package/schema/components/recognizer-assemblyAiOptions.schema.json +35 -0
  72. package/schema/components/recognizer-awsOptions.schema.json +52 -0
  73. package/schema/components/recognizer-azureOptions.schema.json +32 -0
  74. package/schema/components/recognizer-cobaltOptions.schema.json +34 -0
  75. package/schema/components/recognizer-customOptions.schema.json +27 -0
  76. package/schema/components/recognizer-deepgramOptions.schema.json +147 -0
  77. package/schema/components/recognizer-elevenlabsOptions.schema.json +39 -0
  78. package/schema/components/recognizer-gladiaOptions.schema.json +8 -0
  79. package/schema/components/recognizer-googleOptions.schema.json +35 -0
  80. package/schema/components/recognizer-houndifyOptions.schema.json +53 -0
  81. package/schema/components/recognizer-ibmOptions.schema.json +54 -0
  82. package/schema/components/recognizer-nuanceOptions.schema.json +150 -0
  83. package/schema/components/recognizer-nvidiaOptions.schema.json +39 -0
  84. package/schema/components/recognizer-openaiOptions.schema.json +59 -0
  85. package/schema/components/recognizer-sonioxOptions.schema.json +46 -0
  86. package/schema/components/recognizer-speechmaticsOptions.schema.json +91 -0
  87. package/schema/components/recognizer-verbioOptions.schema.json +46 -0
  88. package/schema/components/recognizer.schema.json +212 -0
  89. package/schema/components/synthesizer.schema.json +82 -0
  90. package/schema/components/target.schema.json +105 -0
  91. package/schema/components/vad.schema.json +48 -0
  92. package/schema/jambonz-app.schema.json +106 -0
  93. package/schema/verbs/alert.schema.json +20 -0
  94. package/schema/verbs/answer.schema.json +12 -0
  95. package/schema/verbs/conference.schema.json +43 -0
  96. package/schema/verbs/config.schema.json +170 -0
  97. package/schema/verbs/dequeue.schema.json +36 -0
  98. package/schema/verbs/dial.schema.json +153 -0
  99. package/schema/verbs/dtmf.schema.json +27 -0
  100. package/schema/verbs/dub.schema.json +52 -0
  101. package/schema/verbs/enqueue.schema.json +38 -0
  102. package/schema/verbs/gather.schema.json +145 -0
  103. package/schema/verbs/hangup.schema.json +29 -0
  104. package/schema/verbs/leave.schema.json +12 -0
  105. package/schema/verbs/listen.schema.json +109 -0
  106. package/schema/verbs/llm.schema.json +131 -0
  107. package/schema/verbs/message.schema.json +30 -0
  108. package/schema/verbs/pause.schema.json +26 -0
  109. package/schema/verbs/pipeline.schema.json +61 -0
  110. package/schema/verbs/play.schema.json +69 -0
  111. package/schema/verbs/redirect.schema.json +23 -0
  112. package/schema/verbs/say.schema.json +84 -0
  113. package/schema/verbs/sip-decline.schema.json +31 -0
  114. package/schema/verbs/sip-refer.schema.json +41 -0
  115. package/schema/verbs/sip-request.schema.json +33 -0
  116. package/schema/verbs/stream.schema.json +30 -0
  117. package/schema/verbs/tag.schema.json +21 -0
  118. package/schema/verbs/transcribe.schema.json +48 -0
  119. package/dist/common-Bsqv1Brz.d.cts +0 -69
  120. package/dist/common-Bsqv1Brz.d.ts +0 -69
  121. package/dist/rest-BV_FsqnH.d.cts +0 -97
  122. package/dist/rest-CthGXHnw.d.ts +0 -97
package/dist/index.js CHANGED
@@ -11,13 +11,31 @@ import { EventEmitter } from 'events';
11
11
  var COMPONENT_SCHEMAS = [
12
12
  "auth",
13
13
  "actionHook",
14
- "synthesizer",
15
- "recognizer",
16
- "target",
17
- "vad",
14
+ "actionHookDelayAction",
15
+ "amd",
18
16
  "bidirectionalAudio",
19
17
  "fillerNoise",
20
- "actionHookDelayAction"
18
+ "recognizer",
19
+ "recognizer-assemblyAiOptions",
20
+ "recognizer-awsOptions",
21
+ "recognizer-azureOptions",
22
+ "recognizer-cobaltOptions",
23
+ "recognizer-customOptions",
24
+ "recognizer-deepgramOptions",
25
+ "recognizer-elevenlabsOptions",
26
+ "recognizer-gladiaOptions",
27
+ "recognizer-googleOptions",
28
+ "recognizer-houndifyOptions",
29
+ "recognizer-ibmOptions",
30
+ "recognizer-nuanceOptions",
31
+ "recognizer-nvidiaOptions",
32
+ "recognizer-openaiOptions",
33
+ "recognizer-sonioxOptions",
34
+ "recognizer-speechmaticsOptions",
35
+ "recognizer-verbioOptions",
36
+ "synthesizer",
37
+ "target",
38
+ "vad"
21
39
  ];
22
40
  var VERB_SCHEMAS = [
23
41
  "answer",
@@ -55,9 +73,9 @@ function findSchemaDir() {
55
73
  const currentDir = typeof __dirname !== "undefined" ? __dirname : dirname(fileURLToPath(import.meta.url));
56
74
  const candidates = [
57
75
  resolve(currentDir, "../../schema"),
58
- // from src/
59
- resolve(currentDir, "../../../schema")
60
- // from dist/
76
+ // from typescript/src/
77
+ resolve(currentDir, "../schema")
78
+ // from dist/ (tsup bundles to package-root/dist/)
61
79
  ];
62
80
  for (const candidate of candidates) {
63
81
  try {
@@ -127,6 +145,9 @@ function getValidator(schemaDir) {
127
145
  var VerbBuilder = class {
128
146
  verbs = [];
129
147
  validator;
148
+ /**
149
+ * @param opts - Options for validation and schema directory.
150
+ */
130
151
  constructor(opts) {
131
152
  if (opts?.validate === false) {
132
153
  this.validator = null;
@@ -135,85 +156,111 @@ var VerbBuilder = class {
135
156
  }
136
157
  }
137
158
  // --- Audio & Speech ---
159
+ /** Speak text using TTS. Supports SSML, multiple voices, and streaming. */
138
160
  say(opts) {
139
161
  return this.addVerb({ verb: "say", ...opts });
140
162
  }
163
+ /** Play an audio file from a URL. */
141
164
  play(opts) {
142
165
  return this.addVerb({ verb: "play", ...opts });
143
166
  }
167
+ /** Collect speech (STT) and/or DTMF input from the caller. */
144
168
  gather(opts) {
145
169
  return this.addVerb({ verb: "gather", ...opts });
146
170
  }
147
171
  // --- AI & Real-time ---
172
+ /** Connect the caller to an LLM for real-time voice conversation. */
148
173
  llm(opts) {
149
174
  return this.addVerb({ verb: "llm", ...opts });
150
175
  }
176
+ /** Voice AI pipeline with integrated turn detection. */
151
177
  pipeline(opts) {
152
178
  return this.addVerb({ verb: "pipeline", ...opts });
153
179
  }
180
+ /** Stream real-time call audio to a WebSocket endpoint. Supports bidirectional audio. */
154
181
  listen(opts) {
155
182
  return this.addVerb({ verb: "listen", ...opts });
156
183
  }
184
+ /** Stream real-time call audio to a WebSocket endpoint. Synonym for {@link listen}. */
157
185
  stream(opts) {
158
186
  return this.addVerb({ verb: "stream", ...opts });
159
187
  }
188
+ /** Real-time call transcription sent to a webhook. */
160
189
  transcribe(opts) {
161
190
  return this.addVerb({ verb: "transcribe", ...opts });
162
191
  }
163
192
  // --- Call Control ---
193
+ /** Place an outbound call and bridge it to the current caller. */
164
194
  dial(opts) {
165
195
  return this.addVerb({ verb: "dial", ...opts });
166
196
  }
197
+ /** Join or create a multi-party conference room. */
167
198
  conference(opts) {
168
199
  return this.addVerb({ verb: "conference", ...opts });
169
200
  }
201
+ /** Place the caller into a named queue. */
170
202
  enqueue(opts) {
171
203
  return this.addVerb({ verb: "enqueue", ...opts });
172
204
  }
205
+ /** Remove a caller from a queue and bridge them. */
173
206
  dequeue(opts) {
174
207
  return this.addVerb({ verb: "dequeue", ...opts });
175
208
  }
209
+ /** End the call. */
176
210
  hangup(opts) {
177
211
  return this.addVerb({ verb: "hangup", ...opts });
178
212
  }
213
+ /** Transfer control to a different webhook URL. */
179
214
  redirect(opts) {
180
215
  return this.addVerb({ verb: "redirect", ...opts });
181
216
  }
217
+ /** Wait for a specified duration before continuing. */
182
218
  pause(opts) {
183
219
  return this.addVerb({ verb: "pause", ...opts });
184
220
  }
221
+ /** Leave a conference or queue. */
185
222
  leave(opts) {
186
223
  return this.addVerb({ verb: "leave", ...opts });
187
224
  }
188
225
  // --- SIP ---
226
+ /** Reject an incoming call with a SIP error response. */
189
227
  sipDecline(opts) {
190
228
  return this.addVerb({ verb: "sip:decline", ...opts });
191
229
  }
230
+ /** Send a SIP INFO or other request within the dialog. */
192
231
  sipRequest(opts) {
193
232
  return this.addVerb({ verb: "sip:request", ...opts });
194
233
  }
234
+ /** Transfer the call via SIP REFER. */
195
235
  sipRefer(opts) {
196
236
  return this.addVerb({ verb: "sip:refer", ...opts });
197
237
  }
198
238
  // --- Utility ---
239
+ /** Set session-level defaults (TTS vendor/voice, STT vendor, VAD, etc.). */
199
240
  config(opts) {
200
241
  return this.addVerb({ verb: "config", ...opts });
201
242
  }
243
+ /** Explicitly answer the call (sends a 200 OK). */
202
244
  answer(opts) {
203
245
  return this.addVerb({ verb: "answer", ...opts });
204
246
  }
247
+ /** Send a SIP 180 Ringing with optional Alert-Info header. */
205
248
  alert(opts) {
206
249
  return this.addVerb({ verb: "alert", ...opts });
207
250
  }
251
+ /** Attach metadata to the call for tracking or routing. */
208
252
  tag(opts) {
209
253
  return this.addVerb({ verb: "tag", ...opts });
210
254
  }
255
+ /** Send DTMF tones into the call. */
211
256
  dtmf(opts) {
212
257
  return this.addVerb({ verb: "dtmf", ...opts });
213
258
  }
259
+ /** Mix an auxiliary audio track into the call. */
214
260
  dub(opts) {
215
261
  return this.addVerb({ verb: "dub", ...opts });
216
262
  }
263
+ /** Send an SMS or MMS message. */
217
264
  message(opts) {
218
265
  return this.addVerb({ verb: "message", ...opts });
219
266
  }
@@ -260,6 +307,7 @@ var VerbBuilder = class {
260
307
  }
261
308
  };
262
309
  var WebhookResponse = class extends VerbBuilder {
310
+ /** @param opts - Options for validation and schema directory. */
263
311
  constructor(opts) {
264
312
  super(opts);
265
313
  }
@@ -315,9 +363,35 @@ var WebhookResponse = class extends VerbBuilder {
315
363
  };
316
364
  }
317
365
  };
366
+
367
+ // src/webhook/env-vars.ts
368
+ function envVarsMiddleware(schema) {
369
+ return (req, res, next) => {
370
+ if (req.method === "OPTIONS") {
371
+ res.json(schema);
372
+ return;
373
+ }
374
+ next();
375
+ };
376
+ }
318
377
  var Session = class extends EventEmitter {
378
+ /** Unique call identifier. */
319
379
  callSid;
380
+ /** Caller phone number or SIP URI. */
381
+ from;
382
+ /** Called phone number or SIP URI. */
383
+ to;
384
+ /** Call direction. */
385
+ direction;
386
+ /** Account identifier. */
387
+ accountSid;
388
+ /** Application identifier. */
389
+ applicationSid;
390
+ /** SIP Call-ID. */
391
+ callId;
392
+ /** Distributed trace header (B3 format), if present. */
320
393
  b3;
394
+ /** Full call session data from jambonz (includes env_vars, SIP headers, etc.). */
321
395
  data;
322
396
  /** Application-specific storage that persists for the session. */
323
397
  locals = {};
@@ -329,14 +403,21 @@ var Session = class extends EventEmitter {
329
403
  commandQueue = [];
330
404
  ttsCounter = 0;
331
405
  ttsPaused = false;
406
+ /** @internal */
332
407
  constructor(opts) {
333
408
  super();
334
409
  this.ws = opts.ws;
335
410
  this.logger = opts.logger;
336
411
  this.msgid = opts.msg.msgid;
337
- this.callSid = opts.msg.data?.call_sid ?? opts.msg.call_sid ?? "";
338
- this.b3 = opts.msg.b3;
339
412
  this.data = opts.msg.data ?? {};
413
+ this.callSid = this.data.call_sid ?? opts.msg.call_sid ?? "";
414
+ this.from = this.data.from ?? "";
415
+ this.to = this.data.to ?? "";
416
+ this.direction = this.data.direction ?? "inbound";
417
+ this.accountSid = this.data.account_sid ?? "";
418
+ this.applicationSid = this.data.application_sid ?? "";
419
+ this.callId = this.data.call_id ?? "";
420
+ this.b3 = opts.msg.b3;
340
421
  this.builder = new VerbBuilder({
341
422
  validate: opts.validate,
342
423
  schemaDir: opts.schemaDir
@@ -354,106 +435,132 @@ var Session = class extends EventEmitter {
354
435
  // ---------------------------------------------------------------------------
355
436
  // Verb builder delegation — same API as VerbBuilder
356
437
  // ---------------------------------------------------------------------------
438
+ /** Speak text using TTS. Supports SSML, multiple voices, and streaming. */
357
439
  say(opts) {
358
440
  this.builder.say(opts);
359
441
  return this;
360
442
  }
443
+ /** Play an audio file from a URL. */
361
444
  play(opts) {
362
445
  this.builder.play(opts);
363
446
  return this;
364
447
  }
448
+ /** Collect speech (STT) and/or DTMF input from the caller. */
365
449
  gather(opts) {
366
450
  this.builder.gather(opts);
367
451
  return this;
368
452
  }
453
+ /** Connect the caller to an LLM for real-time voice conversation. */
369
454
  llm(opts) {
370
455
  this.builder.llm(opts);
371
456
  return this;
372
457
  }
458
+ /** Voice AI pipeline with integrated turn detection. */
373
459
  pipeline(opts) {
374
460
  this.builder.pipeline(opts);
375
461
  return this;
376
462
  }
463
+ /** Stream real-time call audio to a WebSocket endpoint. Supports bidirectional audio. */
377
464
  listen(opts) {
378
465
  this.builder.listen(opts);
379
466
  return this;
380
467
  }
468
+ /** Stream real-time call audio to a WebSocket endpoint. Synonym for {@link listen}. */
381
469
  stream(opts) {
382
470
  this.builder.stream(opts);
383
471
  return this;
384
472
  }
473
+ /** Real-time call transcription sent to a webhook. */
385
474
  transcribe(opts) {
386
475
  this.builder.transcribe(opts);
387
476
  return this;
388
477
  }
478
+ /** Place an outbound call and bridge it to the current caller. */
389
479
  dial(opts) {
390
480
  this.builder.dial(opts);
391
481
  return this;
392
482
  }
483
+ /** Join or create a multi-party conference room. */
393
484
  conference(opts) {
394
485
  this.builder.conference(opts);
395
486
  return this;
396
487
  }
488
+ /** Place the caller into a named queue. */
397
489
  enqueue(opts) {
398
490
  this.builder.enqueue(opts);
399
491
  return this;
400
492
  }
493
+ /** Remove a caller from a queue and bridge them. */
401
494
  dequeue(opts) {
402
495
  this.builder.dequeue(opts);
403
496
  return this;
404
497
  }
498
+ /** End the call. */
405
499
  hangup(opts) {
406
500
  this.builder.hangup(opts);
407
501
  return this;
408
502
  }
503
+ /** Transfer control to a different webhook URL. */
409
504
  redirect(opts) {
410
505
  this.builder.redirect(opts);
411
506
  return this;
412
507
  }
508
+ /** Wait for a specified duration before continuing. */
413
509
  pause(opts) {
414
510
  this.builder.pause(opts);
415
511
  return this;
416
512
  }
513
+ /** Leave a conference or queue. */
417
514
  leave(opts) {
418
515
  this.builder.leave(opts);
419
516
  return this;
420
517
  }
518
+ /** Reject an incoming call with a SIP error response. */
421
519
  sipDecline(opts) {
422
520
  this.builder.sipDecline(opts);
423
521
  return this;
424
522
  }
523
+ /** Send a SIP INFO or other request within the dialog. */
425
524
  sipRequest(opts) {
426
525
  this.builder.sipRequest(opts);
427
526
  return this;
428
527
  }
528
+ /** Transfer the call via SIP REFER. */
429
529
  sipRefer(opts) {
430
530
  this.builder.sipRefer(opts);
431
531
  return this;
432
532
  }
533
+ /** Set session-level defaults (TTS vendor/voice, STT vendor, VAD, etc.). */
433
534
  config(opts) {
434
535
  this.builder.config(opts);
435
536
  return this;
436
537
  }
538
+ /** Explicitly answer the call (sends a 200 OK). */
437
539
  answer(opts) {
438
540
  this.builder.answer(opts);
439
541
  return this;
440
542
  }
543
+ /** Send a SIP 180 Ringing with optional Alert-Info header. */
441
544
  alert(opts) {
442
545
  this.builder.alert(opts);
443
546
  return this;
444
547
  }
548
+ /** Attach metadata to the call for tracking or routing. */
445
549
  tag(opts) {
446
550
  this.builder.tag(opts);
447
551
  return this;
448
552
  }
553
+ /** Send DTMF tones into the call. */
449
554
  dtmf(opts) {
450
555
  this.builder.dtmf(opts);
451
556
  return this;
452
557
  }
558
+ /** Mix an auxiliary audio track into the call. */
453
559
  dub(opts) {
454
560
  this.builder.dub(opts);
455
561
  return this;
456
562
  }
563
+ /** Send an SMS or MMS message. */
457
564
  message(opts) {
458
565
  this.builder.message(opts);
459
566
  return this;
@@ -507,18 +614,30 @@ var Session = class extends EventEmitter {
507
614
  this.wsSend(response);
508
615
  }
509
616
  // ---------------------------------------------------------------------------
617
+ // Verb status events
618
+ // ---------------------------------------------------------------------------
619
+ /**
620
+ * Enable real-time verb status events for this session.
621
+ * Once enabled, the session emits 'verb:status' events for verb lifecycle
622
+ * changes (starting, finished, start-playback, stop-playback, etc.).
623
+ *
624
+ * This is a convenience for `.config({ notifyEvents: true })` — it can be
625
+ * chained into the initial verb sequence or called at any time.
626
+ */
627
+ notifyEvents(enabled = true) {
628
+ this.builder.config({ notifyEvents: enabled });
629
+ return this;
630
+ }
631
+ // ---------------------------------------------------------------------------
510
632
  // Inject commands (immediate execution, bypass verb queue)
511
633
  // ---------------------------------------------------------------------------
512
634
  /** Send an inject command for immediate execution. */
513
635
  injectCommand(command, data, callSid) {
514
636
  this.wsSend({
515
637
  type: "command",
516
- command: "inject",
517
- data: {
518
- command,
519
- ...typeof data === "object" && data !== null ? data : {},
520
- ...callSid ? { call_sid: callSid } : {}
521
- }
638
+ command,
639
+ ...callSid ? { callSid } : {},
640
+ data: typeof data === "object" && data !== null ? data : {}
522
641
  });
523
642
  }
524
643
  /** Redirect call execution to a new webhook. */
@@ -527,7 +646,8 @@ var Session = class extends EventEmitter {
527
646
  }
528
647
  /** Inject a whisper verb (say/play) to one party on the call. */
529
648
  injectWhisper(verb, callSid) {
530
- this.injectCommand("whisper", Array.isArray(verb) ? verb : [verb], callSid);
649
+ const whisper = Array.isArray(verb) ? verb : [verb];
650
+ this.injectCommand("whisper", { whisper }, callSid);
531
651
  }
532
652
  /** Mute or unmute the call. */
533
653
  injectMute(status, callSid) {
@@ -703,6 +823,9 @@ var Session = class extends EventEmitter {
703
823
  } else if (data?.event_type === "user_interruption") {
704
824
  this.handleUserInterruption();
705
825
  }
826
+ if (data?.event_type) {
827
+ this.emit(`tts:${data.event_type}`, data);
828
+ }
706
829
  this.emit("tts:streaming-event", data);
707
830
  break;
708
831
  case "tts:tokens-result":
@@ -778,6 +901,132 @@ var WsClient = class extends EventEmitter {
778
901
  }
779
902
  }
780
903
  };
904
+ var AudioStream = class extends EventEmitter {
905
+ metadata;
906
+ callSid;
907
+ sampleRate;
908
+ ws;
909
+ logger;
910
+ constructor(ws, metadata, logger) {
911
+ super();
912
+ this.ws = ws;
913
+ this.logger = logger;
914
+ this.metadata = metadata;
915
+ this.callSid = metadata.callSid;
916
+ this.sampleRate = metadata.sampleRate;
917
+ ws.on("message", (data, isBinary) => {
918
+ if (isBinary) {
919
+ this.emit("audio", Buffer.from(data));
920
+ } else {
921
+ this.onTextMessage(data);
922
+ }
923
+ });
924
+ ws.on("close", (code, reason) => {
925
+ this.emit("close", code, reason.toString());
926
+ });
927
+ ws.on("error", (err) => {
928
+ this.emit("error", err);
929
+ });
930
+ }
931
+ /** Send raw L16 PCM audio back to the caller (streaming mode). */
932
+ sendAudio(pcm) {
933
+ if (this.ws.readyState === 1) {
934
+ this.ws.send(pcm);
935
+ }
936
+ }
937
+ /** Send a playAudio command with base64-encoded audio (non-streaming mode). */
938
+ playAudio(audioContent, opts) {
939
+ this.sendJson({
940
+ type: "playAudio",
941
+ data: {
942
+ audioContent,
943
+ audioContentType: opts?.audioContentType ?? "raw",
944
+ sampleRate: opts?.sampleRate ?? this.sampleRate,
945
+ ...opts?.id !== void 0 ? { id: opts.id } : {},
946
+ ...opts?.queuePlay !== void 0 ? { queuePlay: opts.queuePlay } : {}
947
+ }
948
+ });
949
+ }
950
+ /** Stop any currently playing audio and flush the buffer. */
951
+ killAudio() {
952
+ this.sendJson({ type: "killAudio" });
953
+ }
954
+ /** Tell jambonz to close the connection and end the listen verb. */
955
+ disconnect() {
956
+ this.sendJson({ type: "disconnect" });
957
+ }
958
+ /** Insert a synchronization marker. */
959
+ sendMark(name) {
960
+ this.sendJson({ type: "mark", data: { name } });
961
+ }
962
+ /** Clear all pending markers. */
963
+ clearMarks() {
964
+ this.sendJson({ type: "clearMarks" });
965
+ }
966
+ /** Close the WebSocket connection. */
967
+ close() {
968
+ this.ws.close();
969
+ }
970
+ onTextMessage(raw) {
971
+ try {
972
+ const str = typeof raw === "string" ? raw : Buffer.from(raw).toString("utf-8");
973
+ const msg = JSON.parse(str);
974
+ if (msg.event === "dtmf") {
975
+ this.emit("dtmf", { digit: msg.dtmf, duration: msg.duration });
976
+ return;
977
+ }
978
+ switch (msg.type) {
979
+ case "playDone":
980
+ this.emit("playDone", msg.data ?? {});
981
+ break;
982
+ case "mark":
983
+ this.emit("mark", msg.data ?? {});
984
+ break;
985
+ default:
986
+ this.logger.debug({ msg }, "AudioStream: unhandled text message");
987
+ }
988
+ } catch (err) {
989
+ this.logger.info({ err }, "AudioStream: error parsing text message");
990
+ }
991
+ }
992
+ sendJson(msg) {
993
+ if (this.ws.readyState === 1) {
994
+ this.ws.send(JSON.stringify(msg));
995
+ }
996
+ }
997
+ };
998
+
999
+ // src/websocket/audio-client.ts
1000
+ var AudioClient = class extends EventEmitter {
1001
+ logger;
1002
+ path;
1003
+ constructor(logger, path) {
1004
+ super();
1005
+ this.logger = logger;
1006
+ this.path = path;
1007
+ }
1008
+ /** Handle a new audio WebSocket connection. */
1009
+ handle(ws, req) {
1010
+ const onFirstMessage = (data, isBinary) => {
1011
+ ws.removeListener("message", onFirstMessage);
1012
+ if (isBinary) {
1013
+ this.logger.info("AudioClient: expected JSON metadata as first message, got binary");
1014
+ ws.close();
1015
+ return;
1016
+ }
1017
+ try {
1018
+ const raw = typeof data === "string" ? data : Buffer.from(data).toString("utf-8");
1019
+ const metadata = JSON.parse(raw);
1020
+ const stream = new AudioStream(ws, metadata, this.logger);
1021
+ this.emit("connection", stream, req);
1022
+ } catch (err) {
1023
+ this.logger.info({ err }, "AudioClient: error parsing initial metadata");
1024
+ ws.close();
1025
+ }
1026
+ };
1027
+ ws.on("message", onFirstMessage);
1028
+ }
1029
+ };
781
1030
 
782
1031
  // src/websocket/router.ts
783
1032
  var WsRouter = class {
@@ -815,6 +1064,7 @@ var WsRouter = class {
815
1064
 
816
1065
  // src/websocket/endpoint.ts
817
1066
  var WS_PROTOCOL = "ws.jambonz.org";
1067
+ var AUDIO_PROTOCOL = "audio.drachtio.org";
818
1068
  var defaultLogger = {
819
1069
  info: () => {
820
1070
  },
@@ -824,7 +1074,7 @@ var defaultLogger = {
824
1074
  }
825
1075
  };
826
1076
  function createEndpoint(opts) {
827
- const { server, port, logger = defaultLogger, middlewares = [] } = opts;
1077
+ const { server, port, logger = defaultLogger, middlewares = [], envVars } = opts;
828
1078
  const router = new WsRouter();
829
1079
  const wss = new WebSocketServer({
830
1080
  noServer: true,
@@ -833,6 +1083,23 @@ function createEndpoint(opts) {
833
1083
  return false;
834
1084
  }
835
1085
  });
1086
+ const audioWss = new WebSocketServer({
1087
+ noServer: true,
1088
+ handleProtocols: (protocols) => {
1089
+ if (protocols.has(AUDIO_PROTOCOL)) return AUDIO_PROTOCOL;
1090
+ return false;
1091
+ }
1092
+ });
1093
+ const audioRoutes = /* @__PURE__ */ new Map();
1094
+ server.on("request", (req, res) => {
1095
+ if (req.method === "OPTIONS" && envVars) {
1096
+ res.writeHead(200, { "Content-Type": "application/json" });
1097
+ res.end(JSON.stringify(envVars));
1098
+ return;
1099
+ }
1100
+ res.writeHead(426, { "Content-Type": "text/plain" });
1101
+ res.end("Upgrade Required");
1102
+ });
836
1103
  server.on("upgrade", (req, socket, head) => {
837
1104
  const fakeRes = new http.ServerResponse(req);
838
1105
  runMiddlewares(middlewares, req, fakeRes, (err) => {
@@ -841,6 +1108,14 @@ function createEndpoint(opts) {
841
1108
  socket.destroy();
842
1109
  return;
843
1110
  }
1111
+ const pathname = req.url?.split("?")[0] ?? "/";
1112
+ const audioClient = audioRoutes.get(pathname);
1113
+ if (audioClient) {
1114
+ audioWss.handleUpgrade(req, socket, head, (ws) => {
1115
+ audioClient.handle(ws, req);
1116
+ });
1117
+ return;
1118
+ }
844
1119
  const client = router.route(req);
845
1120
  if (!client) {
846
1121
  logger.debug({ url: req.url }, "Endpoint: no route for WebSocket upgrade");
@@ -855,11 +1130,18 @@ function createEndpoint(opts) {
855
1130
  if (port && !server.listening) {
856
1131
  server.listen(port);
857
1132
  }
858
- return function makeService({ path }) {
1133
+ const makeService = function makeService2({ path }) {
859
1134
  const client = new WsClient(logger, path);
860
1135
  router.use(path, client);
861
1136
  return client;
862
1137
  };
1138
+ makeService.audio = function audio({ path }) {
1139
+ const normalized = path.startsWith("/") ? path : `/${path}`;
1140
+ const client = new AudioClient(logger, normalized);
1141
+ audioRoutes.set(normalized, client);
1142
+ return client;
1143
+ };
1144
+ return makeService;
863
1145
  }
864
1146
  function runMiddlewares(middlewares, req, res, done) {
865
1147
  let i = 0;
@@ -890,12 +1172,20 @@ var HttpClient = class {
890
1172
  "Content-Type": "application/json"
891
1173
  };
892
1174
  }
1175
+ async throwError(method, path, res) {
1176
+ let detail = "";
1177
+ try {
1178
+ detail = `: ${await res.text()}`;
1179
+ } catch {
1180
+ }
1181
+ throw new Error(`${method} ${path} failed: ${res.status} ${res.statusText}${detail}`);
1182
+ }
893
1183
  async get(path) {
894
1184
  const res = await fetch(`${this.baseUrl}${path}`, {
895
1185
  method: "GET",
896
1186
  headers: this.headers
897
1187
  });
898
- if (!res.ok) throw new Error(`GET ${path} failed: ${res.status} ${res.statusText}`);
1188
+ if (!res.ok) await this.throwError("GET", path, res);
899
1189
  return res.json();
900
1190
  }
901
1191
  async post(path, body) {
@@ -904,7 +1194,7 @@ var HttpClient = class {
904
1194
  headers: this.headers,
905
1195
  body: JSON.stringify(body)
906
1196
  });
907
- if (!res.ok) throw new Error(`POST ${path} failed: ${res.status} ${res.statusText}`);
1197
+ if (!res.ok) await this.throwError("POST", path, res);
908
1198
  return res.json();
909
1199
  }
910
1200
  async put(path, body) {
@@ -913,14 +1203,14 @@ var HttpClient = class {
913
1203
  headers: this.headers,
914
1204
  body: JSON.stringify(body)
915
1205
  });
916
- if (!res.ok) throw new Error(`PUT ${path} failed: ${res.status} ${res.statusText}`);
1206
+ if (!res.ok) await this.throwError("PUT", path, res);
917
1207
  }
918
1208
  async del(path) {
919
1209
  const res = await fetch(`${this.baseUrl}${path}`, {
920
1210
  method: "DELETE",
921
1211
  headers: this.headers
922
1212
  });
923
- if (!res.ok) throw new Error(`DELETE ${path} failed: ${res.status} ${res.statusText}`);
1213
+ if (!res.ok) await this.throwError("DELETE", path, res);
924
1214
  }
925
1215
  };
926
1216
  var CallsResource = class {
@@ -936,12 +1226,30 @@ var CallsResource = class {
936
1226
  );
937
1227
  return result.sid;
938
1228
  }
1229
+ /** List active calls, optionally filtered. */
1230
+ async list(filter) {
1231
+ const params = new URLSearchParams();
1232
+ if (filter?.direction) params.set("direction", filter.direction);
1233
+ if (filter?.from) params.set("from", filter.from);
1234
+ if (filter?.to) params.set("to", filter.to);
1235
+ if (filter?.callStatus) params.set("callStatus", filter.callStatus);
1236
+ const qs = params.toString();
1237
+ return this.http.get(
1238
+ `/Accounts/${this.accountSid}/Calls${qs ? `?${qs}` : ""}`
1239
+ );
1240
+ }
939
1241
  /** Get info about an active call. */
940
1242
  async get(callSid) {
941
1243
  return this.http.get(
942
1244
  `/Accounts/${this.accountSid}/Calls/${callSid}`
943
1245
  );
944
1246
  }
1247
+ /** Get count of active inbound and outbound calls. */
1248
+ async count() {
1249
+ return this.http.get(
1250
+ `/Accounts/${this.accountSid}/CallCount`
1251
+ );
1252
+ }
945
1253
  /** Update an active call (redirect, mute, hangup, etc). */
946
1254
  async update(callSid, opts) {
947
1255
  return this.http.put(
@@ -968,29 +1276,49 @@ var CallsResource = class {
968
1276
  return this.update(callSid, { mute_status: status });
969
1277
  }
970
1278
  };
971
- var MessagesResource = class {
1279
+ var ConferencesResource = class {
972
1280
  constructor(http2, accountSid) {
973
1281
  this.http = http2;
974
1282
  this.accountSid = accountSid;
975
1283
  }
976
- /** Send an SMS/MMS message. */
977
- async create(opts) {
978
- return this.http.post(
979
- `/Accounts/${this.accountSid}/Messages`,
980
- opts
1284
+ /** List active conferences. */
1285
+ async list() {
1286
+ return this.http.get(
1287
+ `/Accounts/${this.accountSid}/Conferences`
1288
+ );
1289
+ }
1290
+ };
1291
+ var QueuesResource = class {
1292
+ constructor(http2, accountSid) {
1293
+ this.http = http2;
1294
+ this.accountSid = accountSid;
1295
+ }
1296
+ /** List active queues. */
1297
+ async list(search) {
1298
+ const qs = search ? `?search=${encodeURIComponent(search)}` : "";
1299
+ return this.http.get(
1300
+ `/Accounts/${this.accountSid}/Queues${qs}`
981
1301
  );
982
1302
  }
983
1303
  };
984
1304
  var JambonzClient = class {
1305
+ /** Active call management (create, list, update, redirect, mute, whisper, hangup). */
985
1306
  calls;
986
- messages;
1307
+ /** Active conference listing. */
1308
+ conferences;
1309
+ /** Active queue listing. */
1310
+ queues;
1311
+ /**
1312
+ * @param opts - API connection options (baseUrl, accountSid, apiKey).
1313
+ */
987
1314
  constructor(opts) {
988
1315
  const http2 = new HttpClient(opts);
989
1316
  this.calls = new CallsResource(http2, opts.accountSid);
990
- this.messages = new MessagesResource(http2, opts.accountSid);
1317
+ this.conferences = new ConferencesResource(http2, opts.accountSid);
1318
+ this.queues = new QueuesResource(http2, opts.accountSid);
991
1319
  }
992
1320
  };
993
1321
 
994
- export { CallsResource, JambonzClient, JambonzValidator, MessagesResource, Session, VerbBuilder, WebhookResponse, WsClient, WsRouter, createEndpoint, getValidator };
1322
+ export { AudioClient, AudioStream, CallsResource, ConferencesResource, JambonzClient, JambonzValidator, QueuesResource, Session, VerbBuilder, WebhookResponse, WsClient, WsRouter, createEndpoint, envVarsMiddleware, getValidator };
995
1323
  //# sourceMappingURL=index.js.map
996
1324
  //# sourceMappingURL=index.js.map