@siphon-project/control 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -17,8 +17,9 @@ var ControlError = class _ControlError extends Error {
17
17
  Object.setPrototypeOf(this, _ControlError.prototype);
18
18
  }
19
19
  /**
20
- * True when this is a server-side `unsupported_verb` rejection — the state a
21
- * media verb (`playFile`/`dtmf`/…) lands in until the server implements it.
20
+ * True when this is a server-side `unsupported_verb` rejection — what a verb
21
+ * answers when the configured media backend cannot carry it out (streaming
22
+ * and recording on anything but siphon-rtp).
22
23
  */
23
24
  isUnsupportedVerb() {
24
25
  return this.kind === "command" && this.code === "unsupported_verb";
@@ -80,10 +81,10 @@ function encodeCommand(id, module, verb, target, args) {
80
81
  frame.args = args ?? null;
81
82
  return JSON.stringify(frame);
82
83
  }
83
- function parseInboundFrame(text) {
84
+ function parseInboundFrame(text2) {
84
85
  let value;
85
86
  try {
86
- value = JSON.parse(text);
87
+ value = JSON.parse(text2);
87
88
  } catch {
88
89
  return null;
89
90
  }
@@ -130,11 +131,19 @@ var SipVerb = {
130
131
  * the channel. Channel-addressed, unlike `originate`, which creates one.
131
132
  */
132
133
  Dial: "dial",
134
+ /**
135
+ * Give up on the dial ringing for this channel's caller and leave the caller
136
+ * alone: the phones are CANCELled and the dial ends in `DialFailed` with code
137
+ * 487. Refused (`invalid_state`) when nothing is ringing, and once a phone
138
+ * has answered and is being bridged.
139
+ */
140
+ CancelDial: "cancel_dial",
133
141
  SetHeader: "set_header",
134
142
  GetHeader: "get_header",
135
143
  RemoveHeader: "remove_header",
136
144
  AcceptRefer: "accept_refer",
137
145
  RejectRefer: "reject_refer",
146
+ CompleteRefer: "complete_refer",
138
147
  Bridge: "bridge",
139
148
  Unbridge: "unbridge",
140
149
  ReplacePeer: "replace_peer",
@@ -248,7 +257,7 @@ var Session = class {
248
257
  return Promise.reject(ControlError.closed());
249
258
  }
250
259
  const id = `c-${this.nextId.value++}`;
251
- const text = encodeCommand(id, module, verb, target, args);
260
+ const text2 = encodeCommand(id, module, verb, target, args);
252
261
  return new Promise((resolve, reject) => {
253
262
  const timer = setTimeout(() => {
254
263
  this.pending.delete(id);
@@ -256,7 +265,7 @@ var Session = class {
256
265
  }, this.replyTimeoutMs);
257
266
  this.pending.set(id, { resolve, reject, timer });
258
267
  try {
259
- this.socket.send(text);
268
+ this.socket.send(text2);
260
269
  } catch (error) {
261
270
  this.pending.delete(id);
262
271
  clearTimeout(timer);
@@ -264,8 +273,8 @@ var Session = class {
264
273
  }
265
274
  });
266
275
  }
267
- onMessage(text) {
268
- const frame = parseInboundFrame(text);
276
+ onMessage(text2) {
277
+ const frame = parseInboundFrame(text2);
269
278
  if (frame === null) {
270
279
  return;
271
280
  }
@@ -636,10 +645,29 @@ function responseArgs(options) {
636
645
  }
637
646
  return args;
638
647
  }
648
+ function insertTransferIdentity(args, identity) {
649
+ if (identity?.from !== void 0) args.from = identity.from;
650
+ if (identity?.fromDisplay !== void 0) args.from_display = identity.fromDisplay;
651
+ if (identity?.pAssertedIdentity !== void 0) {
652
+ args.p_asserted_identity = identity.pAssertedIdentity;
653
+ }
654
+ if (identity?.privacy !== void 0) args.privacy = identity.privacy;
655
+ if (identity?.numberPolicy !== void 0) args.number_policy = identity.numberPolicy;
656
+ if (identity?.format !== void 0) args.format = identity.format;
657
+ if (identity?.headers !== void 0) args.headers = identity.headers;
658
+ }
659
+ function routeSetToWire(route) {
660
+ if (route === void 0 || route === null) return void 0;
661
+ if (!Array.isArray(route) || route.some((entry) => typeof entry !== "string")) {
662
+ throw new TypeError(`a target's "route" is an array of Route entry strings`);
663
+ }
664
+ return route.length === 0 ? void 0 : [...route];
665
+ }
639
666
  function routeTargetToWire(target) {
640
667
  if (typeof target === "string") {
641
668
  return target;
642
669
  }
670
+ const route = routeSetToWire(target.route);
643
671
  const object = { uri: target.uri };
644
672
  if (target.nextHop !== void 0) {
645
673
  object.next_hop = target.nextHop;
@@ -653,6 +681,9 @@ function routeTargetToWire(target) {
653
681
  if (target.rerouteAfterProgress === true) {
654
682
  object.reroute_after_progress = true;
655
683
  }
684
+ if (route !== void 0) {
685
+ object.route = route;
686
+ }
656
687
  return object;
657
688
  }
658
689
  function stringValue(result) {
@@ -664,6 +695,10 @@ function stringValue(result) {
664
695
  }
665
696
  return null;
666
697
  }
698
+ function text(result, name) {
699
+ const value = result?.[name];
700
+ return typeof value === "string" ? value : void 0;
701
+ }
667
702
  function originateArgs(channel, to, media, options) {
668
703
  return originateCommonArgs({ channel, to }, media, options);
669
704
  }
@@ -712,6 +747,11 @@ function dialTargetToWire(target) {
712
747
  const aor = target.aor;
713
748
  const nextHop = target.nextHop;
714
749
  const headers = target.headers;
750
+ const to = target.to;
751
+ const route = routeSetToWire(target.route);
752
+ if (to !== void 0 && typeof to !== "string") {
753
+ throw new TypeError(`a dial target's "to" is a SIP URI string`);
754
+ }
715
755
  if (typeof uri === "string" && typeof aor === "string") {
716
756
  throw new TypeError(
717
757
  'a dial target names "uri" or "aor", never both \u2014 siphon reads the aor and ignores the uri beside it, so this would place a different call'
@@ -723,17 +763,27 @@ function dialTargetToWire(target) {
723
763
  `an aor target takes no "nextHop": each of its branches routes over its own contact's captured flow`
724
764
  );
725
765
  }
766
+ if (route !== void 0) {
767
+ throw new TypeError(
768
+ `an aor target takes no "route": each of its branches follows its own contact's Path`
769
+ );
770
+ }
726
771
  const object2 = { aor };
727
772
  if (headers !== void 0) object2.headers = headers;
773
+ if (to !== void 0) object2.to = to;
728
774
  return object2;
729
775
  }
730
776
  if (typeof uri !== "string") {
731
777
  throw new TypeError('a dial target requires a string "uri" or "aor"');
732
778
  }
733
- if (nextHop === void 0 && headers === void 0) return uri;
779
+ if (nextHop === void 0 && headers === void 0 && to === void 0 && route === void 0) {
780
+ return uri;
781
+ }
734
782
  const object = { uri };
735
783
  if (nextHop !== void 0) object.next_hop = nextHop;
736
784
  if (headers !== void 0) object.headers = headers;
785
+ if (to !== void 0) object.to = to;
786
+ if (route !== void 0) object.route = route;
737
787
  return object;
738
788
  }
739
789
  function dialArgs(targets, options) {
@@ -792,6 +842,10 @@ function playArgs(source, options) {
792
842
  args.file = source.file;
793
843
  } else if ("dbId" in source) {
794
844
  args.db_id = source.dbId;
845
+ } else if ("tone" in source) {
846
+ args.tone = source.tone;
847
+ } else if ("url" in source) {
848
+ args.url = source.url;
795
849
  } else {
796
850
  args.blob = Buffer.from(source.blob).toString("base64");
797
851
  }
@@ -804,6 +858,9 @@ function playArgs(source, options) {
804
858
  if (options?.durationMs !== void 0) {
805
859
  args.duration_ms = options.durationMs;
806
860
  }
861
+ if (options?.gainDecibels !== void 0) {
862
+ args.gain_decibels = options.gainDecibels;
863
+ }
807
864
  if (options?.toTag !== void 0) {
808
865
  args.to_tag = options.toTag;
809
866
  }
@@ -973,6 +1030,32 @@ var Call = class {
973
1030
  }
974
1031
  await this.sip(SipVerb.Drop, args);
975
1032
  }
1033
+ /**
1034
+ * Give up on the dial ringing for this call and leave the caller alone.
1035
+ *
1036
+ * Every phone still ringing is CANCELled (RFC 3261 §9.1), each reported by
1037
+ * `DialBranchFailed` with cause `cancelled`, and the dial ends in
1038
+ * `DialFailed` with code 487. The caller is exactly as the dial found it —
1039
+ * answered and anchored for an `onAnswer: "bridge"` dial, unanswered and
1040
+ * parked otherwise — still this app's, and free to be dialled for again.
1041
+ * {@link Call.hangup} ends the caller as well.
1042
+ *
1043
+ * `reason` is reported as the `cause` of a bridging dial's `DialFailed`
1044
+ * (default `cancelled`), so the handler that hears it can tell its own cancel
1045
+ * from a dial that failed by itself.
1046
+ *
1047
+ * Rejects with `invalid_state` when nothing is ringing (`details.reason` is
1048
+ * `no_dial_in_progress`), and once a phone has answered and is being bridged
1049
+ * (`dial_answered`), whose outcome arrives as `DialAnswered` or
1050
+ * `BridgeFailed`.
1051
+ */
1052
+ async cancelDial(reason) {
1053
+ const args = {};
1054
+ if (reason !== void 0) {
1055
+ args.reason = reason;
1056
+ }
1057
+ await this.sip(SipVerb.CancelDial, args);
1058
+ }
976
1059
  /**
977
1060
  * Send an in-dialog REFER on the A-leg (blind transfer).
978
1061
  *
@@ -1009,7 +1092,7 @@ var Call = class {
1009
1092
  *
1010
1093
  * `targets` is a non-empty list of carriers tried cheapest-first: each entry
1011
1094
  * is a bare URI string or a {@link RouteTargetObject}
1012
- * (`{uri, nextHop?, headers?, timeout?, rerouteAfterProgress?}`). A target
1095
+ * (`{uri, nextHop?, headers?, timeout?, rerouteAfterProgress?, route?}`). A target
1013
1096
  * that has shown progress keeps the call past its `timeout` unless it sets
1014
1097
  * `rerouteAfterProgress`. `strategy` defaults to
1015
1098
  * `"sequential"` (v1 supports only sequential/single — anything else rejects
@@ -1086,7 +1169,7 @@ var Call = class {
1086
1169
  */
1087
1170
  async dial(targets, options) {
1088
1171
  const result = await this.sip(SipVerb.Dial, dialArgs(targets, options));
1089
- const text = (name) => {
1172
+ const text2 = (name) => {
1090
1173
  const value = result?.[name];
1091
1174
  return typeof value === "string" ? value : void 0;
1092
1175
  };
@@ -1097,12 +1180,12 @@ var Call = class {
1097
1180
  return {
1098
1181
  // The server echoes the channel back; fall back to the one addressed
1099
1182
  // rather than returning an empty id.
1100
- channel: text("channel") ?? this.channelId,
1183
+ channel: text2("channel") ?? this.channelId,
1101
1184
  targets: count("targets"),
1102
- strategy: text("strategy"),
1185
+ strategy: text2("strategy"),
1103
1186
  timeout: count("timeout"),
1104
- onAnswer: text("on_answer"),
1105
- groupId: text("group_id"),
1187
+ onAnswer: text2("on_answer"),
1188
+ groupId: text2("group_id"),
1106
1189
  totalTimeout: count("total_timeout"),
1107
1190
  ringback: (() => {
1108
1191
  const value = result?.ringback;
@@ -1118,6 +1201,9 @@ var Call = class {
1118
1201
  * `b2bua.default_refer_mode`. No pending REFER (already decided, timed out, or
1119
1202
  * the call is gone) rejects with `code === "not_found"`.
1120
1203
  *
1204
+ * `mode: "controller"` leaves the transfer to this application — see
1205
+ * {@link AcceptReferOptions.mode} and {@link Call.completeRefer}.
1206
+ *
1121
1207
  * `profile` names the media profile for the pairing the transfer creates —
1122
1208
  * see {@link AcceptReferOptions.profile}, which is required at an SRTP edge.
1123
1209
  */
@@ -1135,8 +1221,32 @@ var Call = class {
1135
1221
  if (options?.profile !== void 0) {
1136
1222
  args.profile = options.profile;
1137
1223
  }
1224
+ if (options?.timeout !== void 0) {
1225
+ args.timeout = options.timeout;
1226
+ }
1227
+ insertTransferIdentity(args, options);
1138
1228
  await this.sip(SipVerb.AcceptRefer, args);
1139
1229
  }
1230
+ /**
1231
+ * Report how a transfer accepted with `acceptRefer({ mode: "controller" })`
1232
+ * went: the server sends the referrer the sipfrag NOTIFY that ends its
1233
+ * subscription. `code` is the status in it (200-699), a 2xx for a transfer
1234
+ * that succeeded, and `reason` its reason phrase, used as given. Nothing
1235
+ * else happens to the call.
1236
+ *
1237
+ * **Report before releasing the referrer's leg.** The NOTIFY travels on its
1238
+ * dialog, so once that leg is hung up or replaced this rejects with
1239
+ * `code === "not_found"`. With no such transfer open on the call — already
1240
+ * reported, past its deadline, or its referrer hung up — it rejects with
1241
+ * `code === "invalid_state"` (`details.reason === "no_transfer_pending"`).
1242
+ */
1243
+ async completeRefer(code, reason) {
1244
+ const args = { code };
1245
+ if (reason !== void 0) {
1246
+ args.reason = reason;
1247
+ }
1248
+ await this.sip(SipVerb.CompleteRefer, args);
1249
+ }
1140
1250
  /**
1141
1251
  * Reject a *pending inbound* REFER with a final non-2xx (default
1142
1252
  * `603 Decline`). No pending REFER rejects with `code === "not_found"`.
@@ -1243,6 +1353,7 @@ var Call = class {
1243
1353
  if (options.replaceALeg !== void 0) args.replace_a_leg = options.replaceALeg;
1244
1354
  if (options.profile !== void 0) args.profile = options.profile;
1245
1355
  if (options.timeout !== void 0) args.timeout = options.timeout;
1356
+ insertTransferIdentity(args, options);
1246
1357
  return this.sip(SipVerb.ReplacePeer, args);
1247
1358
  }
1248
1359
  /** Set a header on the stored A-leg INVITE. */
@@ -1293,11 +1404,17 @@ var Call = class {
1293
1404
  async dtmf(digits, options) {
1294
1405
  await this.sip(SipVerb.Dtmf, dtmfArgs(digits, options));
1295
1406
  }
1296
- /** Hold the A-leg media via silence. */
1407
+ /**
1408
+ * Silence the call's media in both directions on the media engine.
1409
+ *
1410
+ * A media gate, not a SIP hold: nothing is sent on either dialog, so no
1411
+ * phone shows a held call. Rejects with `invalid_state` on a call the engine
1412
+ * only relays; to hold one party of a bridge, use {@link Call.unbridge}.
1413
+ */
1297
1414
  async hold() {
1298
1415
  await this.sip(SipVerb.Hold, {});
1299
1416
  }
1300
- /** Resume the A-leg media after a {@link Call.hold}. */
1417
+ /** Restore the call's media after a {@link Call.hold}. */
1301
1418
  async unhold() {
1302
1419
  await this.sip(SipVerb.Unhold, {});
1303
1420
  }
@@ -1373,13 +1490,13 @@ var Call = class {
1373
1490
  SipVerb.RecordStart,
1374
1491
  recordStartArgs(options)
1375
1492
  );
1376
- const text = (name) => {
1493
+ const text2 = (name) => {
1377
1494
  const value = result?.[name];
1378
1495
  return typeof value === "string" ? value : void 0;
1379
1496
  };
1380
1497
  return {
1381
- channel: text("channel") ?? this.channelId,
1382
- recordingId: text("recording_id")
1498
+ channel: text2("channel") ?? this.channelId,
1499
+ recordingId: text2("recording_id")
1383
1500
  };
1384
1501
  }
1385
1502
  /**
@@ -1498,6 +1615,25 @@ var SipFacade = class {
1498
1615
  );
1499
1616
  this.dispatch(call);
1500
1617
  }
1618
+ /**
1619
+ * Open the event queue of a call this client is placing, before its
1620
+ * `originate` goes out: siphon sends no `StasisStart` for it, and its first
1621
+ * event can overtake the reply. `null` when the channel is already live here,
1622
+ * which must not be taken over.
1623
+ */
1624
+ openChannel(channel) {
1625
+ if (this.channels.has(channel)) {
1626
+ return null;
1627
+ }
1628
+ const queue = new AsyncQueue();
1629
+ this.channels.set(channel, queue);
1630
+ return queue;
1631
+ }
1632
+ /** Close a channel {@link SipFacade.openChannel} opened for a refused originate. */
1633
+ closeChannel(channel) {
1634
+ this.channels.get(channel)?.close();
1635
+ this.channels.delete(channel);
1636
+ }
1501
1637
  route(channel, event) {
1502
1638
  this.channels.get(channel)?.push(event);
1503
1639
  }
@@ -1570,8 +1706,14 @@ var SipClient = class _SipClient {
1570
1706
  *
1571
1707
  * The one verb that *creates* a channel rather than addressing one, which is
1572
1708
  * why it lives here and not on {@link Call}. It resolves as soon as the
1573
- * INVITE is on the wire — the call is `calling`, and the answer, failure or
1574
- * timeout arrives later as an event on the channel.
1709
+ * INVITE is on the wire — the call is `calling` — to the {@link Call} it
1710
+ * placed: the answer, failure or timeout arrives on {@link Call.nextEvent},
1711
+ * exactly as a handed-over call's does, and `hangup` CANCELs or BYEs it.
1712
+ *
1713
+ * siphon sends no `StasisStart` for a channel its controller created, so the
1714
+ * channel is opened here before the command goes out (a fast 180 can
1715
+ * overtake the reply). An id still live on this client rejects with
1716
+ * `code === "conflict"` before anything is sent.
1575
1717
  *
1576
1718
  * ```ts
1577
1719
  * const call = await client.originate(
@@ -1583,23 +1725,8 @@ var SipClient = class _SipClient {
1583
1725
  * ```
1584
1726
  */
1585
1727
  async originate(channel, to, media, options) {
1586
- const result = await this.client.command(
1587
- MODULE_SIP,
1588
- "originate",
1589
- null,
1590
- originateArgs(channel, to, media, options)
1591
- );
1592
- const text = (name) => {
1593
- const value = result?.[name];
1594
- return typeof value === "string" ? value : void 0;
1595
- };
1596
- return {
1597
- // The server echoes the id back; fall back to the one we asked for
1598
- // rather than returning an empty channel a caller cannot address.
1599
- channel: text("channel") ?? channel,
1600
- callId: text("call_id"),
1601
- sipCallId: text("sip_call_id")
1602
- };
1728
+ const { result, queue } = await this.place(channel, originateArgs(channel, to, media, options));
1729
+ return this.placedCall(channel, text(result, "call_id"), text(result, "sip_call_id"), result, queue);
1603
1730
  }
1604
1731
  /**
1605
1732
  * Ring every phone registered at `aor` under a caller-supplied channel id —
@@ -1634,29 +1761,51 @@ var SipClient = class _SipClient {
1634
1761
  * ```
1635
1762
  */
1636
1763
  async originateAor(channel, aor, media, options, ring) {
1637
- const result = await this.client.command(
1638
- MODULE_SIP,
1639
- "originate",
1640
- null,
1764
+ const { result, queue } = await this.place(
1765
+ channel,
1641
1766
  originateAorArgs(channel, aor, media, options, ring)
1642
1767
  );
1643
- const text = (name) => {
1644
- const value = result?.[name];
1645
- return typeof value === "string" ? value : void 0;
1646
- };
1647
- const count = (name) => {
1648
- const value = result?.[name];
1649
- return typeof value === "number" ? value : void 0;
1650
- };
1768
+ const groupId = text(result, "group_id");
1769
+ const totalTimeout = result?.total_timeout;
1651
1770
  return {
1652
- channel: text("channel") ?? channel,
1653
- groupId: text("group_id"),
1654
- aor: text("aor"),
1655
- strategy: text("strategy"),
1656
- totalTimeout: count("total_timeout"),
1771
+ // The server echoes the id back; fall back to the one we asked for
1772
+ // rather than returning an empty channel a caller cannot address.
1773
+ channel: text(result, "channel") ?? channel,
1774
+ // Until a phone answers, the group stands in for the call, as its events say.
1775
+ call: this.placedCall(channel, groupId, groupId, result, queue),
1776
+ groupId,
1777
+ aor: text(result, "aor"),
1778
+ strategy: text(result, "strategy"),
1779
+ totalTimeout: typeof totalTimeout === "number" ? totalTimeout : void 0,
1657
1780
  branches: branchList(result?.branches) ?? []
1658
1781
  };
1659
1782
  }
1783
+ /** Open `channel`, send the originate, and close it again if the server refuses. */
1784
+ async place(channel, args) {
1785
+ const queue = this.facade.openChannel(channel);
1786
+ if (queue === null) {
1787
+ throw ControlError.command("conflict", `channel ${channel} is already live on this client`);
1788
+ }
1789
+ try {
1790
+ const result = await this.client.command(MODULE_SIP, "originate", null, args);
1791
+ return { result, queue };
1792
+ } catch (error) {
1793
+ this.facade.closeChannel(channel);
1794
+ throw error;
1795
+ }
1796
+ }
1797
+ placedCall(channel, callId, sipCallId, reply, queue) {
1798
+ return new Call(
1799
+ this.client.commander(),
1800
+ channel,
1801
+ callId ?? null,
1802
+ sipCallId ?? null,
1803
+ null,
1804
+ reply,
1805
+ false,
1806
+ queue
1807
+ );
1808
+ }
1660
1809
  /** Send a raw command on any module (the generic escape hatch). */
1661
1810
  command(module, verb, target, args) {
1662
1811
  return this.client.command(module, verb, target, args);