@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.cjs CHANGED
@@ -19,13 +19,31 @@ var http__default = /*#__PURE__*/_interopDefault(http);
19
19
  var COMPONENT_SCHEMAS = [
20
20
  "auth",
21
21
  "actionHook",
22
- "synthesizer",
23
- "recognizer",
24
- "target",
25
- "vad",
22
+ "actionHookDelayAction",
23
+ "amd",
26
24
  "bidirectionalAudio",
27
25
  "fillerNoise",
28
- "actionHookDelayAction"
26
+ "recognizer",
27
+ "recognizer-assemblyAiOptions",
28
+ "recognizer-awsOptions",
29
+ "recognizer-azureOptions",
30
+ "recognizer-cobaltOptions",
31
+ "recognizer-customOptions",
32
+ "recognizer-deepgramOptions",
33
+ "recognizer-elevenlabsOptions",
34
+ "recognizer-gladiaOptions",
35
+ "recognizer-googleOptions",
36
+ "recognizer-houndifyOptions",
37
+ "recognizer-ibmOptions",
38
+ "recognizer-nuanceOptions",
39
+ "recognizer-nvidiaOptions",
40
+ "recognizer-openaiOptions",
41
+ "recognizer-sonioxOptions",
42
+ "recognizer-speechmaticsOptions",
43
+ "recognizer-verbioOptions",
44
+ "synthesizer",
45
+ "target",
46
+ "vad"
29
47
  ];
30
48
  var VERB_SCHEMAS = [
31
49
  "answer",
@@ -63,9 +81,9 @@ function findSchemaDir() {
63
81
  const currentDir = typeof __dirname !== "undefined" ? __dirname : path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))));
64
82
  const candidates = [
65
83
  path.resolve(currentDir, "../../schema"),
66
- // from src/
67
- path.resolve(currentDir, "../../../schema")
68
- // from dist/
84
+ // from typescript/src/
85
+ path.resolve(currentDir, "../schema")
86
+ // from dist/ (tsup bundles to package-root/dist/)
69
87
  ];
70
88
  for (const candidate of candidates) {
71
89
  try {
@@ -135,6 +153,9 @@ function getValidator(schemaDir) {
135
153
  var VerbBuilder = class {
136
154
  verbs = [];
137
155
  validator;
156
+ /**
157
+ * @param opts - Options for validation and schema directory.
158
+ */
138
159
  constructor(opts) {
139
160
  if (opts?.validate === false) {
140
161
  this.validator = null;
@@ -143,85 +164,111 @@ var VerbBuilder = class {
143
164
  }
144
165
  }
145
166
  // --- Audio & Speech ---
167
+ /** Speak text using TTS. Supports SSML, multiple voices, and streaming. */
146
168
  say(opts) {
147
169
  return this.addVerb({ verb: "say", ...opts });
148
170
  }
171
+ /** Play an audio file from a URL. */
149
172
  play(opts) {
150
173
  return this.addVerb({ verb: "play", ...opts });
151
174
  }
175
+ /** Collect speech (STT) and/or DTMF input from the caller. */
152
176
  gather(opts) {
153
177
  return this.addVerb({ verb: "gather", ...opts });
154
178
  }
155
179
  // --- AI & Real-time ---
180
+ /** Connect the caller to an LLM for real-time voice conversation. */
156
181
  llm(opts) {
157
182
  return this.addVerb({ verb: "llm", ...opts });
158
183
  }
184
+ /** Voice AI pipeline with integrated turn detection. */
159
185
  pipeline(opts) {
160
186
  return this.addVerb({ verb: "pipeline", ...opts });
161
187
  }
188
+ /** Stream real-time call audio to a WebSocket endpoint. Supports bidirectional audio. */
162
189
  listen(opts) {
163
190
  return this.addVerb({ verb: "listen", ...opts });
164
191
  }
192
+ /** Stream real-time call audio to a WebSocket endpoint. Synonym for {@link listen}. */
165
193
  stream(opts) {
166
194
  return this.addVerb({ verb: "stream", ...opts });
167
195
  }
196
+ /** Real-time call transcription sent to a webhook. */
168
197
  transcribe(opts) {
169
198
  return this.addVerb({ verb: "transcribe", ...opts });
170
199
  }
171
200
  // --- Call Control ---
201
+ /** Place an outbound call and bridge it to the current caller. */
172
202
  dial(opts) {
173
203
  return this.addVerb({ verb: "dial", ...opts });
174
204
  }
205
+ /** Join or create a multi-party conference room. */
175
206
  conference(opts) {
176
207
  return this.addVerb({ verb: "conference", ...opts });
177
208
  }
209
+ /** Place the caller into a named queue. */
178
210
  enqueue(opts) {
179
211
  return this.addVerb({ verb: "enqueue", ...opts });
180
212
  }
213
+ /** Remove a caller from a queue and bridge them. */
181
214
  dequeue(opts) {
182
215
  return this.addVerb({ verb: "dequeue", ...opts });
183
216
  }
217
+ /** End the call. */
184
218
  hangup(opts) {
185
219
  return this.addVerb({ verb: "hangup", ...opts });
186
220
  }
221
+ /** Transfer control to a different webhook URL. */
187
222
  redirect(opts) {
188
223
  return this.addVerb({ verb: "redirect", ...opts });
189
224
  }
225
+ /** Wait for a specified duration before continuing. */
190
226
  pause(opts) {
191
227
  return this.addVerb({ verb: "pause", ...opts });
192
228
  }
229
+ /** Leave a conference or queue. */
193
230
  leave(opts) {
194
231
  return this.addVerb({ verb: "leave", ...opts });
195
232
  }
196
233
  // --- SIP ---
234
+ /** Reject an incoming call with a SIP error response. */
197
235
  sipDecline(opts) {
198
236
  return this.addVerb({ verb: "sip:decline", ...opts });
199
237
  }
238
+ /** Send a SIP INFO or other request within the dialog. */
200
239
  sipRequest(opts) {
201
240
  return this.addVerb({ verb: "sip:request", ...opts });
202
241
  }
242
+ /** Transfer the call via SIP REFER. */
203
243
  sipRefer(opts) {
204
244
  return this.addVerb({ verb: "sip:refer", ...opts });
205
245
  }
206
246
  // --- Utility ---
247
+ /** Set session-level defaults (TTS vendor/voice, STT vendor, VAD, etc.). */
207
248
  config(opts) {
208
249
  return this.addVerb({ verb: "config", ...opts });
209
250
  }
251
+ /** Explicitly answer the call (sends a 200 OK). */
210
252
  answer(opts) {
211
253
  return this.addVerb({ verb: "answer", ...opts });
212
254
  }
255
+ /** Send a SIP 180 Ringing with optional Alert-Info header. */
213
256
  alert(opts) {
214
257
  return this.addVerb({ verb: "alert", ...opts });
215
258
  }
259
+ /** Attach metadata to the call for tracking or routing. */
216
260
  tag(opts) {
217
261
  return this.addVerb({ verb: "tag", ...opts });
218
262
  }
263
+ /** Send DTMF tones into the call. */
219
264
  dtmf(opts) {
220
265
  return this.addVerb({ verb: "dtmf", ...opts });
221
266
  }
267
+ /** Mix an auxiliary audio track into the call. */
222
268
  dub(opts) {
223
269
  return this.addVerb({ verb: "dub", ...opts });
224
270
  }
271
+ /** Send an SMS or MMS message. */
225
272
  message(opts) {
226
273
  return this.addVerb({ verb: "message", ...opts });
227
274
  }
@@ -268,6 +315,7 @@ var VerbBuilder = class {
268
315
  }
269
316
  };
270
317
  var WebhookResponse = class extends VerbBuilder {
318
+ /** @param opts - Options for validation and schema directory. */
271
319
  constructor(opts) {
272
320
  super(opts);
273
321
  }
@@ -323,9 +371,35 @@ var WebhookResponse = class extends VerbBuilder {
323
371
  };
324
372
  }
325
373
  };
374
+
375
+ // src/webhook/env-vars.ts
376
+ function envVarsMiddleware(schema) {
377
+ return (req, res, next) => {
378
+ if (req.method === "OPTIONS") {
379
+ res.json(schema);
380
+ return;
381
+ }
382
+ next();
383
+ };
384
+ }
326
385
  var Session = class extends events.EventEmitter {
386
+ /** Unique call identifier. */
327
387
  callSid;
388
+ /** Caller phone number or SIP URI. */
389
+ from;
390
+ /** Called phone number or SIP URI. */
391
+ to;
392
+ /** Call direction. */
393
+ direction;
394
+ /** Account identifier. */
395
+ accountSid;
396
+ /** Application identifier. */
397
+ applicationSid;
398
+ /** SIP Call-ID. */
399
+ callId;
400
+ /** Distributed trace header (B3 format), if present. */
328
401
  b3;
402
+ /** Full call session data from jambonz (includes env_vars, SIP headers, etc.). */
329
403
  data;
330
404
  /** Application-specific storage that persists for the session. */
331
405
  locals = {};
@@ -337,14 +411,21 @@ var Session = class extends events.EventEmitter {
337
411
  commandQueue = [];
338
412
  ttsCounter = 0;
339
413
  ttsPaused = false;
414
+ /** @internal */
340
415
  constructor(opts) {
341
416
  super();
342
417
  this.ws = opts.ws;
343
418
  this.logger = opts.logger;
344
419
  this.msgid = opts.msg.msgid;
345
- this.callSid = opts.msg.data?.call_sid ?? opts.msg.call_sid ?? "";
346
- this.b3 = opts.msg.b3;
347
420
  this.data = opts.msg.data ?? {};
421
+ this.callSid = this.data.call_sid ?? opts.msg.call_sid ?? "";
422
+ this.from = this.data.from ?? "";
423
+ this.to = this.data.to ?? "";
424
+ this.direction = this.data.direction ?? "inbound";
425
+ this.accountSid = this.data.account_sid ?? "";
426
+ this.applicationSid = this.data.application_sid ?? "";
427
+ this.callId = this.data.call_id ?? "";
428
+ this.b3 = opts.msg.b3;
348
429
  this.builder = new VerbBuilder({
349
430
  validate: opts.validate,
350
431
  schemaDir: opts.schemaDir
@@ -362,106 +443,132 @@ var Session = class extends events.EventEmitter {
362
443
  // ---------------------------------------------------------------------------
363
444
  // Verb builder delegation — same API as VerbBuilder
364
445
  // ---------------------------------------------------------------------------
446
+ /** Speak text using TTS. Supports SSML, multiple voices, and streaming. */
365
447
  say(opts) {
366
448
  this.builder.say(opts);
367
449
  return this;
368
450
  }
451
+ /** Play an audio file from a URL. */
369
452
  play(opts) {
370
453
  this.builder.play(opts);
371
454
  return this;
372
455
  }
456
+ /** Collect speech (STT) and/or DTMF input from the caller. */
373
457
  gather(opts) {
374
458
  this.builder.gather(opts);
375
459
  return this;
376
460
  }
461
+ /** Connect the caller to an LLM for real-time voice conversation. */
377
462
  llm(opts) {
378
463
  this.builder.llm(opts);
379
464
  return this;
380
465
  }
466
+ /** Voice AI pipeline with integrated turn detection. */
381
467
  pipeline(opts) {
382
468
  this.builder.pipeline(opts);
383
469
  return this;
384
470
  }
471
+ /** Stream real-time call audio to a WebSocket endpoint. Supports bidirectional audio. */
385
472
  listen(opts) {
386
473
  this.builder.listen(opts);
387
474
  return this;
388
475
  }
476
+ /** Stream real-time call audio to a WebSocket endpoint. Synonym for {@link listen}. */
389
477
  stream(opts) {
390
478
  this.builder.stream(opts);
391
479
  return this;
392
480
  }
481
+ /** Real-time call transcription sent to a webhook. */
393
482
  transcribe(opts) {
394
483
  this.builder.transcribe(opts);
395
484
  return this;
396
485
  }
486
+ /** Place an outbound call and bridge it to the current caller. */
397
487
  dial(opts) {
398
488
  this.builder.dial(opts);
399
489
  return this;
400
490
  }
491
+ /** Join or create a multi-party conference room. */
401
492
  conference(opts) {
402
493
  this.builder.conference(opts);
403
494
  return this;
404
495
  }
496
+ /** Place the caller into a named queue. */
405
497
  enqueue(opts) {
406
498
  this.builder.enqueue(opts);
407
499
  return this;
408
500
  }
501
+ /** Remove a caller from a queue and bridge them. */
409
502
  dequeue(opts) {
410
503
  this.builder.dequeue(opts);
411
504
  return this;
412
505
  }
506
+ /** End the call. */
413
507
  hangup(opts) {
414
508
  this.builder.hangup(opts);
415
509
  return this;
416
510
  }
511
+ /** Transfer control to a different webhook URL. */
417
512
  redirect(opts) {
418
513
  this.builder.redirect(opts);
419
514
  return this;
420
515
  }
516
+ /** Wait for a specified duration before continuing. */
421
517
  pause(opts) {
422
518
  this.builder.pause(opts);
423
519
  return this;
424
520
  }
521
+ /** Leave a conference or queue. */
425
522
  leave(opts) {
426
523
  this.builder.leave(opts);
427
524
  return this;
428
525
  }
526
+ /** Reject an incoming call with a SIP error response. */
429
527
  sipDecline(opts) {
430
528
  this.builder.sipDecline(opts);
431
529
  return this;
432
530
  }
531
+ /** Send a SIP INFO or other request within the dialog. */
433
532
  sipRequest(opts) {
434
533
  this.builder.sipRequest(opts);
435
534
  return this;
436
535
  }
536
+ /** Transfer the call via SIP REFER. */
437
537
  sipRefer(opts) {
438
538
  this.builder.sipRefer(opts);
439
539
  return this;
440
540
  }
541
+ /** Set session-level defaults (TTS vendor/voice, STT vendor, VAD, etc.). */
441
542
  config(opts) {
442
543
  this.builder.config(opts);
443
544
  return this;
444
545
  }
546
+ /** Explicitly answer the call (sends a 200 OK). */
445
547
  answer(opts) {
446
548
  this.builder.answer(opts);
447
549
  return this;
448
550
  }
551
+ /** Send a SIP 180 Ringing with optional Alert-Info header. */
449
552
  alert(opts) {
450
553
  this.builder.alert(opts);
451
554
  return this;
452
555
  }
556
+ /** Attach metadata to the call for tracking or routing. */
453
557
  tag(opts) {
454
558
  this.builder.tag(opts);
455
559
  return this;
456
560
  }
561
+ /** Send DTMF tones into the call. */
457
562
  dtmf(opts) {
458
563
  this.builder.dtmf(opts);
459
564
  return this;
460
565
  }
566
+ /** Mix an auxiliary audio track into the call. */
461
567
  dub(opts) {
462
568
  this.builder.dub(opts);
463
569
  return this;
464
570
  }
571
+ /** Send an SMS or MMS message. */
465
572
  message(opts) {
466
573
  this.builder.message(opts);
467
574
  return this;
@@ -515,18 +622,30 @@ var Session = class extends events.EventEmitter {
515
622
  this.wsSend(response);
516
623
  }
517
624
  // ---------------------------------------------------------------------------
625
+ // Verb status events
626
+ // ---------------------------------------------------------------------------
627
+ /**
628
+ * Enable real-time verb status events for this session.
629
+ * Once enabled, the session emits 'verb:status' events for verb lifecycle
630
+ * changes (starting, finished, start-playback, stop-playback, etc.).
631
+ *
632
+ * This is a convenience for `.config({ notifyEvents: true })` — it can be
633
+ * chained into the initial verb sequence or called at any time.
634
+ */
635
+ notifyEvents(enabled = true) {
636
+ this.builder.config({ notifyEvents: enabled });
637
+ return this;
638
+ }
639
+ // ---------------------------------------------------------------------------
518
640
  // Inject commands (immediate execution, bypass verb queue)
519
641
  // ---------------------------------------------------------------------------
520
642
  /** Send an inject command for immediate execution. */
521
643
  injectCommand(command, data, callSid) {
522
644
  this.wsSend({
523
645
  type: "command",
524
- command: "inject",
525
- data: {
526
- command,
527
- ...typeof data === "object" && data !== null ? data : {},
528
- ...callSid ? { call_sid: callSid } : {}
529
- }
646
+ command,
647
+ ...callSid ? { callSid } : {},
648
+ data: typeof data === "object" && data !== null ? data : {}
530
649
  });
531
650
  }
532
651
  /** Redirect call execution to a new webhook. */
@@ -535,7 +654,8 @@ var Session = class extends events.EventEmitter {
535
654
  }
536
655
  /** Inject a whisper verb (say/play) to one party on the call. */
537
656
  injectWhisper(verb, callSid) {
538
- this.injectCommand("whisper", Array.isArray(verb) ? verb : [verb], callSid);
657
+ const whisper = Array.isArray(verb) ? verb : [verb];
658
+ this.injectCommand("whisper", { whisper }, callSid);
539
659
  }
540
660
  /** Mute or unmute the call. */
541
661
  injectMute(status, callSid) {
@@ -711,6 +831,9 @@ var Session = class extends events.EventEmitter {
711
831
  } else if (data?.event_type === "user_interruption") {
712
832
  this.handleUserInterruption();
713
833
  }
834
+ if (data?.event_type) {
835
+ this.emit(`tts:${data.event_type}`, data);
836
+ }
714
837
  this.emit("tts:streaming-event", data);
715
838
  break;
716
839
  case "tts:tokens-result":
@@ -786,6 +909,132 @@ var WsClient = class extends events.EventEmitter {
786
909
  }
787
910
  }
788
911
  };
912
+ var AudioStream = class extends events.EventEmitter {
913
+ metadata;
914
+ callSid;
915
+ sampleRate;
916
+ ws;
917
+ logger;
918
+ constructor(ws, metadata, logger) {
919
+ super();
920
+ this.ws = ws;
921
+ this.logger = logger;
922
+ this.metadata = metadata;
923
+ this.callSid = metadata.callSid;
924
+ this.sampleRate = metadata.sampleRate;
925
+ ws.on("message", (data, isBinary) => {
926
+ if (isBinary) {
927
+ this.emit("audio", Buffer.from(data));
928
+ } else {
929
+ this.onTextMessage(data);
930
+ }
931
+ });
932
+ ws.on("close", (code, reason) => {
933
+ this.emit("close", code, reason.toString());
934
+ });
935
+ ws.on("error", (err) => {
936
+ this.emit("error", err);
937
+ });
938
+ }
939
+ /** Send raw L16 PCM audio back to the caller (streaming mode). */
940
+ sendAudio(pcm) {
941
+ if (this.ws.readyState === 1) {
942
+ this.ws.send(pcm);
943
+ }
944
+ }
945
+ /** Send a playAudio command with base64-encoded audio (non-streaming mode). */
946
+ playAudio(audioContent, opts) {
947
+ this.sendJson({
948
+ type: "playAudio",
949
+ data: {
950
+ audioContent,
951
+ audioContentType: opts?.audioContentType ?? "raw",
952
+ sampleRate: opts?.sampleRate ?? this.sampleRate,
953
+ ...opts?.id !== void 0 ? { id: opts.id } : {},
954
+ ...opts?.queuePlay !== void 0 ? { queuePlay: opts.queuePlay } : {}
955
+ }
956
+ });
957
+ }
958
+ /** Stop any currently playing audio and flush the buffer. */
959
+ killAudio() {
960
+ this.sendJson({ type: "killAudio" });
961
+ }
962
+ /** Tell jambonz to close the connection and end the listen verb. */
963
+ disconnect() {
964
+ this.sendJson({ type: "disconnect" });
965
+ }
966
+ /** Insert a synchronization marker. */
967
+ sendMark(name) {
968
+ this.sendJson({ type: "mark", data: { name } });
969
+ }
970
+ /** Clear all pending markers. */
971
+ clearMarks() {
972
+ this.sendJson({ type: "clearMarks" });
973
+ }
974
+ /** Close the WebSocket connection. */
975
+ close() {
976
+ this.ws.close();
977
+ }
978
+ onTextMessage(raw) {
979
+ try {
980
+ const str = typeof raw === "string" ? raw : Buffer.from(raw).toString("utf-8");
981
+ const msg = JSON.parse(str);
982
+ if (msg.event === "dtmf") {
983
+ this.emit("dtmf", { digit: msg.dtmf, duration: msg.duration });
984
+ return;
985
+ }
986
+ switch (msg.type) {
987
+ case "playDone":
988
+ this.emit("playDone", msg.data ?? {});
989
+ break;
990
+ case "mark":
991
+ this.emit("mark", msg.data ?? {});
992
+ break;
993
+ default:
994
+ this.logger.debug({ msg }, "AudioStream: unhandled text message");
995
+ }
996
+ } catch (err) {
997
+ this.logger.info({ err }, "AudioStream: error parsing text message");
998
+ }
999
+ }
1000
+ sendJson(msg) {
1001
+ if (this.ws.readyState === 1) {
1002
+ this.ws.send(JSON.stringify(msg));
1003
+ }
1004
+ }
1005
+ };
1006
+
1007
+ // src/websocket/audio-client.ts
1008
+ var AudioClient = class extends events.EventEmitter {
1009
+ logger;
1010
+ path;
1011
+ constructor(logger, path) {
1012
+ super();
1013
+ this.logger = logger;
1014
+ this.path = path;
1015
+ }
1016
+ /** Handle a new audio WebSocket connection. */
1017
+ handle(ws, req) {
1018
+ const onFirstMessage = (data, isBinary) => {
1019
+ ws.removeListener("message", onFirstMessage);
1020
+ if (isBinary) {
1021
+ this.logger.info("AudioClient: expected JSON metadata as first message, got binary");
1022
+ ws.close();
1023
+ return;
1024
+ }
1025
+ try {
1026
+ const raw = typeof data === "string" ? data : Buffer.from(data).toString("utf-8");
1027
+ const metadata = JSON.parse(raw);
1028
+ const stream = new AudioStream(ws, metadata, this.logger);
1029
+ this.emit("connection", stream, req);
1030
+ } catch (err) {
1031
+ this.logger.info({ err }, "AudioClient: error parsing initial metadata");
1032
+ ws.close();
1033
+ }
1034
+ };
1035
+ ws.on("message", onFirstMessage);
1036
+ }
1037
+ };
789
1038
 
790
1039
  // src/websocket/router.ts
791
1040
  var WsRouter = class {
@@ -823,6 +1072,7 @@ var WsRouter = class {
823
1072
 
824
1073
  // src/websocket/endpoint.ts
825
1074
  var WS_PROTOCOL = "ws.jambonz.org";
1075
+ var AUDIO_PROTOCOL = "audio.drachtio.org";
826
1076
  var defaultLogger = {
827
1077
  info: () => {
828
1078
  },
@@ -832,7 +1082,7 @@ var defaultLogger = {
832
1082
  }
833
1083
  };
834
1084
  function createEndpoint(opts) {
835
- const { server, port, logger = defaultLogger, middlewares = [] } = opts;
1085
+ const { server, port, logger = defaultLogger, middlewares = [], envVars } = opts;
836
1086
  const router = new WsRouter();
837
1087
  const wss = new ws.WebSocketServer({
838
1088
  noServer: true,
@@ -841,6 +1091,23 @@ function createEndpoint(opts) {
841
1091
  return false;
842
1092
  }
843
1093
  });
1094
+ const audioWss = new ws.WebSocketServer({
1095
+ noServer: true,
1096
+ handleProtocols: (protocols) => {
1097
+ if (protocols.has(AUDIO_PROTOCOL)) return AUDIO_PROTOCOL;
1098
+ return false;
1099
+ }
1100
+ });
1101
+ const audioRoutes = /* @__PURE__ */ new Map();
1102
+ server.on("request", (req, res) => {
1103
+ if (req.method === "OPTIONS" && envVars) {
1104
+ res.writeHead(200, { "Content-Type": "application/json" });
1105
+ res.end(JSON.stringify(envVars));
1106
+ return;
1107
+ }
1108
+ res.writeHead(426, { "Content-Type": "text/plain" });
1109
+ res.end("Upgrade Required");
1110
+ });
844
1111
  server.on("upgrade", (req, socket, head) => {
845
1112
  const fakeRes = new http__default.default.ServerResponse(req);
846
1113
  runMiddlewares(middlewares, req, fakeRes, (err) => {
@@ -849,6 +1116,14 @@ function createEndpoint(opts) {
849
1116
  socket.destroy();
850
1117
  return;
851
1118
  }
1119
+ const pathname = req.url?.split("?")[0] ?? "/";
1120
+ const audioClient = audioRoutes.get(pathname);
1121
+ if (audioClient) {
1122
+ audioWss.handleUpgrade(req, socket, head, (ws) => {
1123
+ audioClient.handle(ws, req);
1124
+ });
1125
+ return;
1126
+ }
852
1127
  const client = router.route(req);
853
1128
  if (!client) {
854
1129
  logger.debug({ url: req.url }, "Endpoint: no route for WebSocket upgrade");
@@ -863,11 +1138,18 @@ function createEndpoint(opts) {
863
1138
  if (port && !server.listening) {
864
1139
  server.listen(port);
865
1140
  }
866
- return function makeService({ path }) {
1141
+ const makeService = function makeService2({ path }) {
867
1142
  const client = new WsClient(logger, path);
868
1143
  router.use(path, client);
869
1144
  return client;
870
1145
  };
1146
+ makeService.audio = function audio({ path }) {
1147
+ const normalized = path.startsWith("/") ? path : `/${path}`;
1148
+ const client = new AudioClient(logger, normalized);
1149
+ audioRoutes.set(normalized, client);
1150
+ return client;
1151
+ };
1152
+ return makeService;
871
1153
  }
872
1154
  function runMiddlewares(middlewares, req, res, done) {
873
1155
  let i = 0;
@@ -898,12 +1180,20 @@ var HttpClient = class {
898
1180
  "Content-Type": "application/json"
899
1181
  };
900
1182
  }
1183
+ async throwError(method, path, res) {
1184
+ let detail = "";
1185
+ try {
1186
+ detail = `: ${await res.text()}`;
1187
+ } catch {
1188
+ }
1189
+ throw new Error(`${method} ${path} failed: ${res.status} ${res.statusText}${detail}`);
1190
+ }
901
1191
  async get(path) {
902
1192
  const res = await fetch(`${this.baseUrl}${path}`, {
903
1193
  method: "GET",
904
1194
  headers: this.headers
905
1195
  });
906
- if (!res.ok) throw new Error(`GET ${path} failed: ${res.status} ${res.statusText}`);
1196
+ if (!res.ok) await this.throwError("GET", path, res);
907
1197
  return res.json();
908
1198
  }
909
1199
  async post(path, body) {
@@ -912,7 +1202,7 @@ var HttpClient = class {
912
1202
  headers: this.headers,
913
1203
  body: JSON.stringify(body)
914
1204
  });
915
- if (!res.ok) throw new Error(`POST ${path} failed: ${res.status} ${res.statusText}`);
1205
+ if (!res.ok) await this.throwError("POST", path, res);
916
1206
  return res.json();
917
1207
  }
918
1208
  async put(path, body) {
@@ -921,14 +1211,14 @@ var HttpClient = class {
921
1211
  headers: this.headers,
922
1212
  body: JSON.stringify(body)
923
1213
  });
924
- if (!res.ok) throw new Error(`PUT ${path} failed: ${res.status} ${res.statusText}`);
1214
+ if (!res.ok) await this.throwError("PUT", path, res);
925
1215
  }
926
1216
  async del(path) {
927
1217
  const res = await fetch(`${this.baseUrl}${path}`, {
928
1218
  method: "DELETE",
929
1219
  headers: this.headers
930
1220
  });
931
- if (!res.ok) throw new Error(`DELETE ${path} failed: ${res.status} ${res.statusText}`);
1221
+ if (!res.ok) await this.throwError("DELETE", path, res);
932
1222
  }
933
1223
  };
934
1224
  var CallsResource = class {
@@ -944,12 +1234,30 @@ var CallsResource = class {
944
1234
  );
945
1235
  return result.sid;
946
1236
  }
1237
+ /** List active calls, optionally filtered. */
1238
+ async list(filter) {
1239
+ const params = new URLSearchParams();
1240
+ if (filter?.direction) params.set("direction", filter.direction);
1241
+ if (filter?.from) params.set("from", filter.from);
1242
+ if (filter?.to) params.set("to", filter.to);
1243
+ if (filter?.callStatus) params.set("callStatus", filter.callStatus);
1244
+ const qs = params.toString();
1245
+ return this.http.get(
1246
+ `/Accounts/${this.accountSid}/Calls${qs ? `?${qs}` : ""}`
1247
+ );
1248
+ }
947
1249
  /** Get info about an active call. */
948
1250
  async get(callSid) {
949
1251
  return this.http.get(
950
1252
  `/Accounts/${this.accountSid}/Calls/${callSid}`
951
1253
  );
952
1254
  }
1255
+ /** Get count of active inbound and outbound calls. */
1256
+ async count() {
1257
+ return this.http.get(
1258
+ `/Accounts/${this.accountSid}/CallCount`
1259
+ );
1260
+ }
953
1261
  /** Update an active call (redirect, mute, hangup, etc). */
954
1262
  async update(callSid, opts) {
955
1263
  return this.http.put(
@@ -976,39 +1284,63 @@ var CallsResource = class {
976
1284
  return this.update(callSid, { mute_status: status });
977
1285
  }
978
1286
  };
979
- var MessagesResource = class {
1287
+ var ConferencesResource = class {
980
1288
  constructor(http2, accountSid) {
981
1289
  this.http = http2;
982
1290
  this.accountSid = accountSid;
983
1291
  }
984
- /** Send an SMS/MMS message. */
985
- async create(opts) {
986
- return this.http.post(
987
- `/Accounts/${this.accountSid}/Messages`,
988
- opts
1292
+ /** List active conferences. */
1293
+ async list() {
1294
+ return this.http.get(
1295
+ `/Accounts/${this.accountSid}/Conferences`
1296
+ );
1297
+ }
1298
+ };
1299
+ var QueuesResource = class {
1300
+ constructor(http2, accountSid) {
1301
+ this.http = http2;
1302
+ this.accountSid = accountSid;
1303
+ }
1304
+ /** List active queues. */
1305
+ async list(search) {
1306
+ const qs = search ? `?search=${encodeURIComponent(search)}` : "";
1307
+ return this.http.get(
1308
+ `/Accounts/${this.accountSid}/Queues${qs}`
989
1309
  );
990
1310
  }
991
1311
  };
992
1312
  var JambonzClient = class {
1313
+ /** Active call management (create, list, update, redirect, mute, whisper, hangup). */
993
1314
  calls;
994
- messages;
1315
+ /** Active conference listing. */
1316
+ conferences;
1317
+ /** Active queue listing. */
1318
+ queues;
1319
+ /**
1320
+ * @param opts - API connection options (baseUrl, accountSid, apiKey).
1321
+ */
995
1322
  constructor(opts) {
996
1323
  const http2 = new HttpClient(opts);
997
1324
  this.calls = new CallsResource(http2, opts.accountSid);
998
- this.messages = new MessagesResource(http2, opts.accountSid);
1325
+ this.conferences = new ConferencesResource(http2, opts.accountSid);
1326
+ this.queues = new QueuesResource(http2, opts.accountSid);
999
1327
  }
1000
1328
  };
1001
1329
 
1330
+ exports.AudioClient = AudioClient;
1331
+ exports.AudioStream = AudioStream;
1002
1332
  exports.CallsResource = CallsResource;
1333
+ exports.ConferencesResource = ConferencesResource;
1003
1334
  exports.JambonzClient = JambonzClient;
1004
1335
  exports.JambonzValidator = JambonzValidator;
1005
- exports.MessagesResource = MessagesResource;
1336
+ exports.QueuesResource = QueuesResource;
1006
1337
  exports.Session = Session;
1007
1338
  exports.VerbBuilder = VerbBuilder;
1008
1339
  exports.WebhookResponse = WebhookResponse;
1009
1340
  exports.WsClient = WsClient;
1010
1341
  exports.WsRouter = WsRouter;
1011
1342
  exports.createEndpoint = createEndpoint;
1343
+ exports.envVarsMiddleware = envVarsMiddleware;
1012
1344
  exports.getValidator = getValidator;
1013
1345
  //# sourceMappingURL=index.cjs.map
1014
1346
  //# sourceMappingURL=index.cjs.map