@signalwire/js 4.0.0-dev-20260803213546 → 4.0.0-dev-20260826210511

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.cjs CHANGED
@@ -3825,6 +3825,33 @@ function isLayoutChangedPayload(value) {
3825
3825
  return isObject(value) && hasProperty(value, "room_id") && hasProperty(value, "room_session_id") && hasProperty(value, "layout");
3826
3826
  }
3827
3827
 
3828
+ //#endregion
3829
+ //#region src/utils/unwrapVertoReply.ts
3830
+ /**
3831
+ * Unwrap a method's own reply from a `webrtc.verto` envelope.
3832
+ *
3833
+ * A control verb sent in-dialog comes back nested two levels deep:
3834
+ *
3835
+ * ```
3836
+ * { result: { node_id, code, result: { jsonrpc, id, result: <method payload> } } }
3837
+ * ```
3838
+ *
3839
+ * whereas the routed transport resolves the method payload directly under
3840
+ * `.result`. Readers want the latter shape, and the difference is silent when it
3841
+ * is wrong — `response.result.layouts` simply evaluates to `undefined` against the
3842
+ * envelope, so the data arrives, nothing throws, and the caller sees an empty
3843
+ * value. That exact failure produced an empty layout dropdown with a successful
3844
+ * request behind it.
3845
+ *
3846
+ * Accepting both shapes here keeps every reader indifferent to which transport
3847
+ * produced the response. Anything that is not a nested envelope (a plain ack, or
3848
+ * an already-unwrapped reply) passes through untouched.
3849
+ */
3850
+ function unwrapVertoReply(response) {
3851
+ const inner = require_operators.getValueFrom(response, "result.result");
3852
+ return inner && typeof inner === "object" && "result" in inner ? inner : response;
3853
+ }
3854
+
3828
3855
  //#endregion
3829
3856
  //#region src/managers/CallEventsManager.ts
3830
3857
  const logger$22 = require_operators.getLogger();
@@ -4016,9 +4043,10 @@ var CallEventsManager = class extends Destroyable {
4016
4043
  updateLayouts() {
4017
4044
  if (!this.selfId) return;
4018
4045
  this.webRtcCallSession.executeMethod(this.selfId, "call.layout.list", {}).then((response) => {
4046
+ const { result } = unwrapVertoReply(response);
4019
4047
  this._sessionState$.next({
4020
4048
  ...this._sessionState$.value,
4021
- layouts: response.result.layouts
4049
+ layouts: result.layouts
4022
4050
  });
4023
4051
  }).catch((error) => {
4024
4052
  logger$22.error("[CallEventsManager] Error fetching layouts:", error);
@@ -6018,6 +6046,48 @@ const logger$16 = require_operators.getLogger();
6018
6046
  function resolveInviteNodeId(args) {
6019
6047
  return args.isInvite && !args.reattach && !args.explicitNodeId ? "" : args.currentNodeId ?? "";
6020
6048
  }
6049
+ /**
6050
+ * Surface the real outcome of a `webrtc.verto` reply.
6051
+ *
6052
+ * A webrtc.verto response nests several envelopes, each keyed by a verto-style
6053
+ * string `code` ("200" ok, "400"/etc. fail) rather than a JSON-RPC `error`. An outer
6054
+ * layer reports only whether the frame was delivered; an inner layer carries the op's
6055
+ * own outcome:
6056
+ *
6057
+ * response.result = { code:"200", result:{…} } ← delivery acknowledgement
6058
+ * .result = { jsonrpc, id, result:{…} } ← the reply payload
6059
+ * .result = { code:"400", message:"Bad request" } ← the actual op outcome
6060
+ *
6061
+ * A failure can appear at any layer (delivery refused, or the op itself rejected
6062
+ * deeper down), so walk every nested `.result` object and return the FIRST non-2xx
6063
+ * `code` with its message. Returns null when every `code` seen is 2xx or absent —
6064
+ * i.e. the op succeeded. This is the only way to detect that e.g. a mute/kick was
6065
+ * rejected, since the outer delivery `code` is "200" (delivered) even then.
6066
+ *
6067
+ * Pure function — exported for unit testing.
6068
+ */
6069
+ function findNestedVertoFailure(response) {
6070
+ let node = response;
6071
+ while (node !== null && typeof node === "object") {
6072
+ const obj = node;
6073
+ const err = obj.error;
6074
+ if (err !== null && typeof err === "object") {
6075
+ const e = err;
6076
+ const errCode = typeof e.code === "string" || typeof e.code === "number" ? String(e.code) : void 0;
6077
+ if (errCode !== void 0 && !/^2\d\d$/.test(errCode)) return {
6078
+ code: errCode,
6079
+ message: typeof e.message === "string" ? e.message : void 0
6080
+ };
6081
+ }
6082
+ const code = typeof obj.code === "string" || typeof obj.code === "number" ? String(obj.code) : void 0;
6083
+ if (code !== void 0 && !/^2\d\d$/.test(code)) return {
6084
+ code,
6085
+ message: typeof obj.message === "string" ? obj.message : void 0
6086
+ };
6087
+ node = obj.result !== null && typeof obj.result === "object" ? obj.result : null;
6088
+ }
6089
+ return null;
6090
+ }
6021
6091
  var VertoManager = class extends Destroyable {
6022
6092
  constructor(callSession) {
6023
6093
  super();
@@ -6342,6 +6412,33 @@ var WebRTCVertoManager = class extends VertoManager {
6342
6412
  get vertoPing$() {
6343
6413
  return this.cachedObservable("vertoPing$", () => this.webRtcCallSession.webrtcMessages$.pipe(require_operators.filterAs(isVertoPingInnerParams, "params"), (0, rxjs.takeUntil)(this.destroyed$)));
6344
6414
  }
6415
+ /**
6416
+ * Send a member-control op in-dialog via verto.info.
6417
+ *
6418
+ * The control payload rides in `params.command` — a sibling of `dialogParams`,
6419
+ * at the same level as `dtmf` in {@link sendDigits} — and the inner verto.info
6420
+ * is matched to this call's channel by `dialogParams.callID`, the in-dialog
6421
+ * convention for member-scoped frames. Because it is delivered on the dialog
6422
+ * itself, control lands on the call's own channel with no {node_id,call_id,member_id}
6423
+ * "self" tuple to get wrong. The outer webrtc.verto envelope (added by executeVerto)
6424
+ * still carries the own-leg callID + node_id for session routing.
6425
+ *
6426
+ * Keep `command` OUT of `dialogParams`: it is read at the params level, and
6427
+ * filterVertoParams rewrites/filters dialogParams keys but passes params-level
6428
+ * keys through verbatim.
6429
+ */
6430
+ async sendCallControl(method, params) {
6431
+ const response = await this.executeVerto(VertoInfo({
6432
+ dialogParams: { callID: this.webRtcCallSession.id },
6433
+ command: {
6434
+ method,
6435
+ params
6436
+ }
6437
+ }));
6438
+ const failure = findNestedVertoFailure(response);
6439
+ if (failure) throw new require_operators.JSONRPCError(Number.parseInt(failure.code, 10) || 0, failure.message ?? `Call control "${method}" failed (code ${failure.code})`, void 0);
6440
+ return response;
6441
+ }
6345
6442
  async executeVerto(message, optionals = {}) {
6346
6443
  const webrtcVertoMessage = WebrtcVerto({
6347
6444
  callID: optionals.callID ?? this.webRtcCallSession.id,
@@ -6350,15 +6447,16 @@ var WebRTCVertoManager = class extends VertoManager {
6350
6447
  subscribe: optionals.subscribe
6351
6448
  });
6352
6449
  const response = await this.webRtcCallSession.execute(webrtcVertoMessage);
6450
+ const nonFatal = message.method === "verto.info" ? { fatal: false } : void 0;
6353
6451
  if (response.error) {
6354
6452
  const error = new require_operators.JSONRPCError(response.error.code, response.error.message, response.error.data);
6355
- this.onError?.(error);
6453
+ this.onError?.(error, nonFatal);
6356
6454
  return response;
6357
6455
  }
6358
6456
  const innerResult = require_operators.getValueFrom(response, "result.result");
6359
6457
  if (innerResult?.error) {
6360
6458
  const error = new require_operators.JSONRPCError(innerResult.error.code, innerResult.error.message, innerResult.error.data);
6361
- this.onError?.(error);
6459
+ this.onError?.(error, nonFatal);
6362
6460
  return response;
6363
6461
  }
6364
6462
  return response;
@@ -7747,8 +7845,11 @@ var WebRTCCall = class extends Destroyable {
7747
7845
  emitError(callError) {
7748
7846
  if (this._status$.value === "destroyed" || this._status$.value === "failed") return;
7749
7847
  this._errors$.next(callError);
7750
- if (callError.fatal) {
7848
+ if (callError.fatal && this._status$.value !== "disconnecting") {
7751
7849
  this._status$.next("failed");
7850
+ this.vertoManager.bye().catch((error) => {
7851
+ logger$12.debug("[Call] fatal-teardown bye failed (signaling likely already dead):", error);
7852
+ });
7752
7853
  this.destroy();
7753
7854
  }
7754
7855
  }
@@ -7865,6 +7966,7 @@ var WebRTCCall = class extends Destroyable {
7865
7966
  async executeMethod(target, method, args) {
7866
7967
  const self = this.callSelf;
7867
7968
  if (typeof target === "string" && target !== self.member_id) throw new require_operators.InvalidParams(`Target member ID ${target} does not match call's self member ID ${self.member_id}`);
7969
+ if (this.clientSession.callControl === "in-dialog") return this.executeMethodInDialog(target, method, args);
7868
7970
  const params = {
7869
7971
  ...args,
7870
7972
  self,
@@ -7884,6 +7986,81 @@ var WebRTCCall = class extends Destroyable {
7884
7986
  }
7885
7987
  }
7886
7988
  /**
7989
+ * `executeMethod` for a call opened with `callControl: 'in-dialog'`.
7990
+ *
7991
+ * Translates the routed transport's calling convention into the in-dialog one. No
7992
+ * `self` tuple is sent, but a `target` is — the same {call_id, member_id} the routed
7993
+ * transport puts in `target` (minus node_id), for self-ops and cross-member ops alike.
7994
+ *
7995
+ * Target shapes are per-verb and irregular, so they are centralised here rather
7996
+ * than left to callers: most verbs take a singular `target`, `call.member.remove`
7997
+ * takes a plural `targets` array, and `call.member.position.set` takes a flat
7998
+ * `targets` of `{call_id, position}` — the one verb keyed on call_id rather than
7999
+ * member_id, so the member triple `Participant.setPosition` built is unwrapped.
8000
+ */
8001
+ async executeMethodInDialog(target, method, args) {
8002
+ const control = { ...args };
8003
+ if (method === "call.member.position.set") control.targets = (args.targets ?? []).map((entry) => ({
8004
+ call_id: entry.target?.call_id ?? entry.call_id,
8005
+ position: entry.position
8006
+ }));
8007
+ else {
8008
+ const member = typeof target === "object" ? {
8009
+ call_id: target.call_id,
8010
+ member_id: target.member_id
8011
+ } : {
8012
+ call_id: this.id,
8013
+ member_id: target
8014
+ };
8015
+ if (method === "call.member.remove") control.targets = [member];
8016
+ else control.target = member;
8017
+ }
8018
+ return this.sendCommand(method, control);
8019
+ }
8020
+ /**
8021
+ * Sends a `call.*` control verb **in-dialog** via `verto.info`, as an alternative
8022
+ * to the routed {@link executeMethod} transport.
8023
+ *
8024
+ * Why both exist: `executeMethod` addresses the member with an explicit
8025
+ * `{node_id, call_id, member_id}` tuple, which does not resolve for every conference,
8026
+ * so the op can fail. An in-dialog frame carries the verb on the member's own
8027
+ * signaling channel instead, so control works without the client needing to know how
8028
+ * the conference is hosted.
8029
+ *
8030
+ * The trade-off is reach: the in-dialog transport is only accepted for calls that
8031
+ * join a conference over SWML (e.g. an SWML `join_conference`); use the routed
8032
+ * default otherwise.
8033
+ *
8034
+ * `params` are sent verbatim — nothing is built for you, which includes the target.
8035
+ * **A self-directed op still needs one**, or it is refused; name yourself explicitly:
8036
+ *
8037
+ * ```ts
8038
+ * const { call_id, member_id } = call.self.target;
8039
+ * await call.sendCommand('call.mute', { channels: ['audio'], target: { call_id, member_id } });
8040
+ * ```
8041
+ *
8042
+ * Never include `node_id` — only the two ids. The shapes are per-verb: most take a
8043
+ * singular `target`, `call.member.remove` takes a plural `targets` array, and
8044
+ * `call.member.position.set` takes a flat `targets: [{call_id, position}]` (the one
8045
+ * verb keyed on `call_id` rather than `member_id`). Verbs that act on the call as a
8046
+ * whole, or that the SDK does not wrap at all, take no target.
8047
+ *
8048
+ * For the typed alternative that handles all of this, create the client with
8049
+ * `callControl: 'in-dialog'` and use the ordinary `Call`/`Participant` methods.
8050
+ *
8051
+ * @internal Not part of the supported surface while the in-dialog transport is still
8052
+ * rolling out. `WebRTCCall` is exported from the package entry, so without this tag
8053
+ * TypeDoc publishes the method — and the example above — as public API.
8054
+ *
8055
+ * @param method - A `call.*` method name (e.g. `'call.mute'`).
8056
+ * @param params - Method parameters, sent verbatim.
8057
+ * @returns The method's own reply, unwrapped from the `verto.info` envelope.
8058
+ * @throws {JSONRPCError} If the control op fails.
8059
+ */
8060
+ async sendCommand(method, params = {}) {
8061
+ return unwrapVertoReply(await this.vertoManager.sendCallControl(method, params));
8062
+ }
8063
+ /**
7887
8064
  * The local leg's member triple — sent as `self` in every member RPC
7888
8065
  * envelope, and as the `target` of call-scoped self-operations (e.g. lock,
7889
8066
  * layout).
@@ -9210,6 +9387,7 @@ var ClientSessionManager = class extends Destroyable {
9210
9387
  minor: 0,
9211
9388
  revision: 0
9212
9389
  };
9390
+ this.callControl = "routed";
9213
9391
  this._authorization$ = this.createBehaviorSubject(void 0);
9214
9392
  this._errors$ = this.createReplaySubject(1);
9215
9393
  this._authState$ = this.createBehaviorSubject({ kind: "unauthenticated" });
@@ -9683,6 +9861,9 @@ var ClientSessionWrapper = class {
9683
9861
  get iceServers() {
9684
9862
  return this.clientSessionManager.iceServers;
9685
9863
  }
9864
+ get callControl() {
9865
+ return this.clientSessionManager.callControl;
9866
+ }
9686
9867
  async execute(request, options) {
9687
9868
  return this.clientSessionManager.execute(request, options);
9688
9869
  }
@@ -9921,7 +10102,7 @@ var DeviceTokenManager = class extends Destroyable {
9921
10102
  method: "POST",
9922
10103
  uri: require_operators.DEVICE_TOKEN_ENDPOINT
9923
10104
  });
9924
- const response = await this.http.request({
10105
+ const response = await this.http().request({
9925
10106
  url: require_operators.DEVICE_TOKEN_ENDPOINT,
9926
10107
  ...POST_PARAMS,
9927
10108
  body: JSON.stringify({
@@ -9948,7 +10129,7 @@ var DeviceTokenManager = class extends Destroyable {
9948
10129
  uri: require_operators.DEVICE_REFRESH_ENDPOINT,
9949
10130
  accessToken: currentToken
9950
10131
  });
9951
- const response = await this.http.request({
10132
+ const response = await this.http().request({
9952
10133
  url: require_operators.DEVICE_REFRESH_ENDPOINT,
9953
10134
  ...POST_PARAMS,
9954
10135
  body: JSON.stringify({
@@ -11109,6 +11290,16 @@ var SignalWire = class extends Destroyable {
11109
11290
  });
11110
11291
  }
11111
11292
  /**
11293
+ * Build the refresh path's own HTTP controller, against whatever host is current.
11294
+ *
11295
+ * Called on first use rather than up front, so `apiHost` already reflects the
11296
+ * token's `ch` claim. Same credential source as the container's controller — only
11297
+ * the instance, and therefore its observable streams, is separate.
11298
+ */
11299
+ createRefreshHttpController() {
11300
+ return new HTTPRequestController(this._deps.apiHost, () => this._deps.credential);
11301
+ }
11302
+ /**
11112
11303
  * Initializes DPoP if not already set up. Returns the fingerprint on success.
11113
11304
  */
11114
11305
  async initDPoP() {
@@ -11135,7 +11326,14 @@ var SignalWire = class extends Destroyable {
11135
11326
  async resolveCredentials() {
11136
11327
  const fingerprint = await this.initDPoP();
11137
11328
  this._refreshCoordinator = new CredentialRefreshCoordinator(this._dpopManager, {
11138
- http: this._deps.http,
11329
+ http: () => {
11330
+ if (!this._refreshHttp || this._refreshHttpHost !== this._deps.apiHost) {
11331
+ this._refreshHttp?.destroy();
11332
+ this._refreshHttp = this.createRefreshHttpController();
11333
+ this._refreshHttpHost = this._deps.apiHost;
11334
+ }
11335
+ return this._refreshHttp;
11336
+ },
11139
11337
  notifier: {
11140
11338
  onError: (error) => this._errors$.next(error),
11141
11339
  onWarning: (warning) => this._warnings$.next(warning),
@@ -11401,6 +11599,7 @@ var SignalWire = class extends Destroyable {
11401
11599
  this._attachManager = new AttachManager(this._deps.storage, this._deps.deviceController, PreferencesContainer.instance.reconnectCallsTimeout, this._deps.attachedCallsKey);
11402
11600
  this._clientSession = new ClientSessionManager(() => this._deps.credential, this._transport, this._deps.storage, this._deps.authorizationStateKey, this._deps.deviceController, this._attachManager, this._deps.webRTCApiProvider, this._dpopManager, this._networkMonitor?.networkChange$);
11403
11601
  this._publicSession = new ClientSessionWrapper(this._clientSession);
11602
+ this._clientSession.callControl = this._options.callControl ?? "routed";
11404
11603
  this._clientSession.onBeforeReconnect = async () => this.refreshCredentialForReconnect();
11405
11604
  this.subscribeTo(this._clientSession.errors$, (error) => {
11406
11605
  this._errors$.next(error);
@@ -12017,6 +12216,8 @@ var SignalWire = class extends Destroyable {
12017
12216
  destroy() {
12018
12217
  this._refreshCoordinator?.destroy();
12019
12218
  this._refreshCoordinator = void 0;
12219
+ this._refreshHttp?.destroy();
12220
+ this._refreshHttp = void 0;
12020
12221
  this._dpopManager?.destroy();
12021
12222
  const session = this._clientSession;
12022
12223
  session?.teardownSessionState();