@signalwire/js 4.0.0-dev-20260714201720 → 4.0.0-dev-20260721161304

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
@@ -1,4 +1,4 @@
1
- const require_operators = require('./operators-B8ipd4Xl.cjs');
1
+ const require_operators = require('./operators-Bn4Ij3VB.cjs');
2
2
  let jwt_decode = require("jwt-decode");
3
3
  let rxjs = require("rxjs");
4
4
  let uuid = require("uuid");
@@ -3116,9 +3116,9 @@ const initialState = {};
3116
3116
  * the local participant with additional device control.
3117
3117
  */
3118
3118
  var Participant = class extends Destroyable {
3119
- constructor(id, executeMethod, deviceController) {
3119
+ constructor(id, callExecuteMethod, deviceController) {
3120
3120
  super();
3121
- this.executeMethod = executeMethod;
3121
+ this.callExecuteMethod = callExecuteMethod;
3122
3122
  this.deviceController = deviceController;
3123
3123
  this._state$ = this.createBehaviorSubject(initialState);
3124
3124
  this.id = id;
@@ -3340,22 +3340,55 @@ var Participant = class extends Destroyable {
3340
3340
  get value() {
3341
3341
  return this._state$.value;
3342
3342
  }
3343
+ /**
3344
+ * Target triple for member RPCs, built from the participant's own state.
3345
+ * The backend locates the member's session by the target `call_id`/`node_id`,
3346
+ * so this must always be the participant's own call context — never the
3347
+ * local call's id (issue #19400).
3348
+ *
3349
+ * Reading it doubles as a readiness probe: it throws until the first full
3350
+ * member event (`member.joined`/`member.updated` or the `call.joined`
3351
+ * roster) arrives, and never regresses afterwards.
3352
+ *
3353
+ * @throws {ParticipantNotReadyError} If the member state has not been
3354
+ * received yet (e.g. a participant first seen via `member.talking`) — an
3355
+ * empty call context can never address the member, so fail fast instead of
3356
+ * sending a doomed RPC.
3357
+ */
3358
+ get target() {
3359
+ const { call_id, node_id } = this._state$.value;
3360
+ if (!call_id || !node_id) throw new require_operators.ParticipantNotReadyError(this.id);
3361
+ return {
3362
+ member_id: this.id,
3363
+ call_id,
3364
+ node_id
3365
+ };
3366
+ }
3367
+ /**
3368
+ * Executes a member RPC against this participant, injecting its own
3369
+ * {@link target} as the target.
3370
+ *
3371
+ * @throws {ParticipantNotReadyError} Via {@link target}, when the
3372
+ * member state has not been received yet.
3373
+ */
3374
+ async executeMethod(method, args) {
3375
+ return this.callExecuteMethod(this.target, method, args);
3376
+ }
3343
3377
  /** Toggles the deafened state (mutes/unmutes incoming audio). */
3344
3378
  async toggleDeaf() {
3345
- const method = toggleDeafMethod(this.deaf);
3346
- await this.executeMethod(this.id, method, {});
3379
+ await this.executeMethod(toggleDeafMethod(this.deaf), {});
3347
3380
  }
3348
3381
  /** Toggles the hand-raised state. */
3349
3382
  async toggleHandraise() {
3350
- await this.executeMethod(this.id, toggleHandraiseMethod(this.handraised), {});
3383
+ await this.executeMethod(toggleHandraiseMethod(this.handraised), {});
3351
3384
  }
3352
3385
  /** Mutes the participant's audio. */
3353
3386
  async mute() {
3354
- await this.executeMethod(this.id, "call.mute", { channels: ["audio"] });
3387
+ await this.executeMethod("call.mute", { channels: ["audio"] });
3355
3388
  }
3356
3389
  /** Unmutes the participant's audio. */
3357
3390
  async unmute() {
3358
- await this.executeMethod(this.id, "call.unmute", { channels: ["audio"] });
3391
+ await this.executeMethod("call.unmute", { channels: ["audio"] });
3359
3392
  }
3360
3393
  /** Toggles the participant's audio mute state. */
3361
3394
  async toggleMute() {
@@ -3363,11 +3396,11 @@ var Participant = class extends Destroyable {
3363
3396
  }
3364
3397
  /** Mutes the participant's video. */
3365
3398
  async muteVideo() {
3366
- await this.executeMethod(this.id, "call.mute", { channels: ["video"] });
3399
+ await this.executeMethod("call.mute", { channels: ["video"] });
3367
3400
  }
3368
3401
  /** Unmutes the participant's video. */
3369
3402
  async unmuteVideo() {
3370
- await this.executeMethod(this.id, "call.unmute", { channels: ["video"] });
3403
+ await this.executeMethod("call.unmute", { channels: ["video"] });
3371
3404
  }
3372
3405
  /** Toggles the participant's video mute state. */
3373
3406
  async toggleMuteVideo() {
@@ -3375,7 +3408,7 @@ var Participant = class extends Destroyable {
3375
3408
  }
3376
3409
  /** Toggles echo cancellation on the audio input. */
3377
3410
  async toggleEchoCancellation() {
3378
- await this.executeMethod(this.id, "call.audioflags.set", {
3411
+ await this.executeMethod("call.audioflags.set", {
3379
3412
  echo_cancellation: !this.echoCancellation,
3380
3413
  auto_gain: this.autoGain,
3381
3414
  noise_suppression: this.noiseSuppression
@@ -3383,7 +3416,7 @@ var Participant = class extends Destroyable {
3383
3416
  }
3384
3417
  /** Toggles automatic gain control on the audio input. */
3385
3418
  async toggleAudioInputAutoGain() {
3386
- await this.executeMethod(this.id, "call.audioflags.set", {
3419
+ await this.executeMethod("call.audioflags.set", {
3387
3420
  echo_cancellation: this.echoCancellation,
3388
3421
  auto_gain: !this.autoGain,
3389
3422
  noise_suppression: this.noiseSuppression
@@ -3391,7 +3424,7 @@ var Participant = class extends Destroyable {
3391
3424
  }
3392
3425
  /** Toggles noise suppression on the audio input. */
3393
3426
  async toggleNoiseSuppression() {
3394
- await this.executeMethod(this.id, "call.audioflags.set", {
3427
+ await this.executeMethod("call.audioflags.set", {
3395
3428
  echo_cancellation: this.echoCancellation,
3396
3429
  auto_gain: this.autoGain,
3397
3430
  noise_suppression: !this.noiseSuppression
@@ -3399,7 +3432,7 @@ var Participant = class extends Destroyable {
3399
3432
  }
3400
3433
  /** Toggles low-bitrate mode for this participant's media. */
3401
3434
  async toggleLowbitrate() {
3402
- await this.executeMethod(this.id, "call.lowbitrate.set", { lowbitrate: !this.lowbitrate });
3435
+ await this.executeMethod("call.lowbitrate.set", { lowbitrate: !this.lowbitrate });
3403
3436
  }
3404
3437
  /**
3405
3438
  * Adjusts the **conference-only** microphone energy gate / sensitivity level
@@ -3415,7 +3448,7 @@ var Participant = class extends Destroyable {
3415
3448
  * (integer, larger values are more sensitive).
3416
3449
  */
3417
3450
  async setAudioInputSensitivity(value) {
3418
- await this.executeMethod(this.id, "call.microphone.sensitivity.set", { sensitivity: value });
3451
+ await this.executeMethod("call.microphone.sensitivity.set", { sensitivity: value });
3419
3452
  }
3420
3453
  /**
3421
3454
  * Sets the **server-side** microphone volume on this participant's bridged
@@ -3428,7 +3461,7 @@ var Participant = class extends Destroyable {
3428
3461
  * @param value - Volume level (0-100).
3429
3462
  */
3430
3463
  async setAudioInputVolume(value) {
3431
- await this.executeMethod(this.id, "call.microphone.volume.set", { volume: value });
3464
+ await this.executeMethod("call.microphone.volume.set", { volume: value });
3432
3465
  }
3433
3466
  /**
3434
3467
  * Sets the **server-side** speaker volume on this participant's bridged call
@@ -3442,45 +3475,31 @@ var Participant = class extends Destroyable {
3442
3475
  * @param value - Volume level (0-100).
3443
3476
  */
3444
3477
  async setAudioOutputVolume(value) {
3445
- await this.executeMethod(this.id, "call.speaker.volume.set", { volume: value });
3478
+ await this.executeMethod("call.speaker.volume.set", { volume: value });
3446
3479
  }
3447
3480
  /**
3448
3481
  * Sets the participant's position in the video layout.
3449
3482
  *
3450
- * Requires the `member.position` capability. The gateway keys positions by the
3451
- * **target member's own** `call_id`/`node_id` (see issue #19400 and the legacy
3452
- * `setPositions` implementation), so this sends the participant's own call
3453
- * context — matching {@link Participant.remove}. A resolved promise does not
3454
- * guarantee a visible change: the backend silently returns `200` (no-op) for
3455
- * non-conference targets.
3483
+ * Requires the `member.position` capability. The gateway requires a
3484
+ * `targets` array of `{ target, position }` entries (issue #19400). A
3485
+ * resolved promise does not guarantee a visible change: the backend silently
3486
+ * returns `200` (no-op) for non-conference targets.
3456
3487
  *
3457
3488
  * @param value - The {@link VideoPosition} to assign (e.g. `'auto'`, `'reserved-0'`).
3458
3489
  */
3459
3490
  async setPosition(value) {
3460
- const state = this._state$.value;
3461
- const target = {
3462
- member_id: this.id,
3463
- call_id: state.call_id ?? "",
3464
- node_id: state.node_id ?? ""
3465
- };
3466
- await this.executeMethod(target, "call.member.position.set", { targets: [{
3467
- target,
3491
+ await this.executeMethod("call.member.position.set", { targets: [{
3492
+ target: this.target,
3468
3493
  position: value
3469
3494
  }] });
3470
3495
  }
3471
3496
  /** Removes this participant from the call. */
3472
3497
  async remove() {
3473
- const state = this._state$.value;
3474
- const target = {
3475
- member_id: this.id,
3476
- call_id: state.call_id ?? "",
3477
- node_id: state.node_id ?? ""
3478
- };
3479
- await this.executeMethod(target, "call.member.remove", {});
3498
+ await this.executeMethod("call.member.remove", { targets: [this.target] });
3480
3499
  }
3481
3500
  /** Ends the call for this participant. */
3482
3501
  async end() {
3483
- await this.executeMethod(this.id, "call.end", {});
3502
+ await this.executeMethod("call.end", {});
3484
3503
  }
3485
3504
  /**
3486
3505
  * Replaces custom metadata for this participant.
@@ -3500,7 +3519,7 @@ var Participant = class extends Destroyable {
3500
3519
  }
3501
3520
  /** Destroys the participant, releasing all subscriptions and references. */
3502
3521
  destroy() {
3503
- this.executeMethod = void 0;
3522
+ this.callExecuteMethod = void 0;
3504
3523
  super.destroy();
3505
3524
  }
3506
3525
  };
@@ -3512,8 +3531,8 @@ var Participant = class extends Destroyable {
3512
3531
  */
3513
3532
  var SelfParticipant = class extends Participant {
3514
3533
  /** @internal */
3515
- constructor(id, executeMethod, vertoManager, deviceController) {
3516
- super(id, executeMethod, deviceController);
3534
+ constructor(id, callExecuteMethod, vertoManager, deviceController) {
3535
+ super(id, callExecuteMethod, deviceController);
3517
3536
  this.vertoManager = vertoManager;
3518
3537
  this._studioAudio$ = this.createBehaviorSubject(false);
3519
3538
  this.capabilities = new SelfCapabilities();
@@ -3537,7 +3556,7 @@ var SelfParticipant = class extends Participant {
3537
3556
  async enableStudioAudio() {
3538
3557
  if (this._studioAudio$.value) return;
3539
3558
  this._studioAudio$.next(true);
3540
- await this.executeMethod(this.id, "call.audioflags.set", {
3559
+ await this.executeMethod("call.audioflags.set", {
3541
3560
  echo_cancellation: false,
3542
3561
  auto_gain: false,
3543
3562
  noise_suppression: false
@@ -3550,7 +3569,7 @@ var SelfParticipant = class extends Participant {
3550
3569
  async disableStudioAudio() {
3551
3570
  if (!this._studioAudio$.value) return;
3552
3571
  this._studioAudio$.next(false);
3553
- await this.executeMethod(this.id, "call.audioflags.set", {
3572
+ await this.executeMethod("call.audioflags.set", {
3554
3573
  echo_cancellation: true,
3555
3574
  auto_gain: true,
3556
3575
  noise_suppression: true
@@ -7634,12 +7653,6 @@ function mosToQualityLevel(mos) {
7634
7653
  //#region src/core/entities/Call.ts
7635
7654
  const logger$12 = require_operators.getLogger();
7636
7655
  /**
7637
- * Verto method for setting member layout positions. Its gateway DTO requires a
7638
- * `targets` array whose entries are `{ target, position }` (NOT bare targets),
7639
- * so {@link WebRTCCall.buildMethodParams} special-cases it. See issue #19400.
7640
- */
7641
- const POSITION_SET_METHOD = "call.member.position.set";
7642
- /**
7643
7656
  * Ratio between the critical and warning RTT spike multipliers.
7644
7657
  * Warning threshold = baseline * warningMultiplier (default 3x)
7645
7658
  * Critical threshold = baseline * warningMultiplier * RTT_CRITICAL_TO_WARNING_RATIO
@@ -7790,7 +7803,7 @@ var WebRTCCall = class extends Destroyable {
7790
7803
  /** Toggles the call lock state, preventing or allowing new participants from joining. */
7791
7804
  async toggleLock() {
7792
7805
  const method = this.locked ? "call.unlock" : "call.lock";
7793
- await this.executeMethod(this.selfId ?? "", method, {});
7806
+ await this.executeMethod(this.callSelf, method, {});
7794
7807
  }
7795
7808
  /**
7796
7809
  * Toggles the hold state of the call (pauses/resumes local media transmission).
@@ -7839,14 +7852,24 @@ var WebRTCCall = class extends Destroyable {
7839
7852
  *
7840
7853
  * Constructs call context (node_id, call_id, member_id) and sends the RPC request.
7841
7854
  *
7842
- * @param target - Target member ID string, or a {@link MemberTarget} object.
7855
+ * @param target - Target {@link MemberTarget} triple, or the local member's
7856
+ * ID string for self-operations (any other string is rejected — a bare
7857
+ * member id cannot carry the remote member's own call context).
7843
7858
  * @param method - Verto method name (e.g. `'call.mute'`, `'call.member.remove'`).
7844
7859
  * @param args - Parameters for the RPC method.
7845
7860
  * @returns The RPC response.
7861
+ * @throws {CallNotReadyError} If the call has no self member context yet.
7862
+ * @throws {InvalidParams} If a string target is not the local member's ID.
7846
7863
  * @throws {JSONRPCError} If the RPC call returns an error.
7847
7864
  */
7848
7865
  async executeMethod(target, method, args) {
7849
- const params = this.buildMethodParams(target, args, method);
7866
+ const self = this.callSelf;
7867
+ 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}`);
7868
+ const params = {
7869
+ ...args,
7870
+ self,
7871
+ target: typeof target === "string" ? self : target
7872
+ };
7850
7873
  const request = buildRPCRequest({
7851
7874
  method,
7852
7875
  params
@@ -7860,29 +7883,23 @@ var WebRTCCall = class extends Destroyable {
7860
7883
  throw error;
7861
7884
  }
7862
7885
  }
7863
- buildMethodParams(target, args, method) {
7864
- const self = {
7865
- node_id: this.nodeId ?? "",
7866
- call_id: this.id,
7867
- member_id: this.vertoManager.selfId ?? ""
7868
- };
7869
- if (method === POSITION_SET_METHOD) return {
7870
- ...args,
7871
- self
7872
- };
7873
- if (typeof target === "object") return {
7874
- ...args,
7875
- self,
7876
- targets: [target]
7877
- };
7886
+ /**
7887
+ * The local leg's member triple — sent as `self` in every member RPC
7888
+ * envelope, and as the `target` of call-scoped self-operations (e.g. lock,
7889
+ * layout).
7890
+ *
7891
+ * @throws {CallNotReadyError} Before `call.joined` delivers the self member
7892
+ * context (`selfId`/`nodeId`) — an RPC without it cannot be routed, so fail
7893
+ * fast instead of sending a doomed request.
7894
+ */
7895
+ get callSelf() {
7896
+ const node_id = this.nodeId;
7897
+ const member_id = this.vertoManager.selfId;
7898
+ if (!node_id || !member_id) throw new require_operators.CallNotReadyError(this.id);
7878
7899
  return {
7879
- ...args,
7880
- self,
7881
- target: {
7882
- node_id: this.nodeId ?? "",
7883
- call_id: this.id,
7884
- member_id: target
7885
- }
7900
+ node_id,
7901
+ call_id: this.id,
7902
+ member_id
7886
7903
  };
7887
7904
  }
7888
7905
  /** Observable of the current call status (e.g. `'ringing'`, `'connected'`). */
@@ -8445,12 +8462,17 @@ var WebRTCCall = class extends Destroyable {
8445
8462
  *
8446
8463
  * **These operations are NOT atomic.** The layout is applied first, then each
8447
8464
  * member position sequentially, so members may briefly flash into their
8448
- * default slots before being moved to the requested positions.
8465
+ * default slots before being moved to the requested positions. Targeted
8466
+ * members are validated upfront, though: when any of them has no
8467
+ * {@link Participant.target | member call context} yet, the whole call
8468
+ * rejects before any request is sent and the layout is left unchanged.
8449
8469
  *
8450
8470
  * @param layout - Layout name (must be one of {@link layouts}).
8451
8471
  * @param positions - Optional map of member IDs to {@link VideoPosition} values.
8452
8472
  * When omitted or empty, only the layout is changed.
8453
8473
  * @throws {InvalidParams} If the layout is not in the available {@link layouts}.
8474
+ * @throws {ParticipantNotReadyError} If a targeted member's call context has
8475
+ * not been received yet — thrown before any request is sent.
8454
8476
  *
8455
8477
  * @example
8456
8478
  * ```ts
@@ -8461,18 +8483,19 @@ var WebRTCCall = class extends Destroyable {
8461
8483
  */
8462
8484
  async setLayout(layout, positions) {
8463
8485
  if (!this.layouts.includes(layout)) throw new require_operators.InvalidParams(`Layout ${layout} is not available in the current call layouts: ${this.layouts.join(", ")}`);
8464
- const selfId = await (0, rxjs.firstValueFrom)(this.selfId$.pipe((0, rxjs.filter)((id) => id !== null)));
8465
- await this.executeMethod(selfId, "call.layout.set", { layout });
8466
- const positionEntries = Object.entries(positions ?? {});
8467
- if (positionEntries.length === 0) return;
8468
- for (const [memberId, position] of positionEntries) {
8486
+ const targets = [];
8487
+ for (const [memberId, position] of Object.entries(positions ?? {})) {
8469
8488
  const participant = this.participants.find((p) => p.id === memberId);
8470
8489
  if (!participant) {
8471
8490
  logger$12.warn(`[Call] setLayout: member ${memberId} not found in participants; skipping position ${position}`);
8472
8491
  continue;
8473
8492
  }
8474
- await participant.setPosition(position);
8493
+ participant.target;
8494
+ targets.push([participant, position]);
8475
8495
  }
8496
+ const selfId = await (0, rxjs.firstValueFrom)(this.selfId$.pipe((0, rxjs.filter)((id) => id !== null)));
8497
+ await this.executeMethod(selfId, "call.layout.set", { layout });
8498
+ for (const [participant, position] of targets) await participant.setPosition(position);
8476
8499
  }
8477
8500
  /**
8478
8501
  * Transfers the call to another destination.
@@ -9387,9 +9410,9 @@ var ClientSessionManager = class extends Destroyable {
9387
9410
  }
9388
9411
  async handleAuthenticationError(error) {
9389
9412
  logger$9.error("Authentication error:", error);
9390
- const isRecoverableAuthError = error instanceof require_operators.JSONRPCError && (error.code === require_operators.RPC_ERROR_REQUESTER_VALIDATION_FAILED || error.code === require_operators.RPC_ERROR_INVALID_PARAMS || error.code === require_operators.RPC_ERROR_AUTHENTICATION_FAILED);
9413
+ const isRecoverableAuthError$1 = error instanceof require_operators.JSONRPCError && (error.code === require_operators.RPC_ERROR_REQUESTER_VALIDATION_FAILED || error.code === require_operators.RPC_ERROR_INVALID_PARAMS || error.code === require_operators.RPC_ERROR_AUTHENTICATION_FAILED);
9391
9414
  const hasStoredState = await (0, rxjs.firstValueFrom)(this.authorizationState$.pipe((0, rxjs.take)(1))) !== void 0;
9392
- if (isRecoverableAuthError && hasStoredState) {
9415
+ if (isRecoverableAuthError$1 && hasStoredState) {
9393
9416
  logger$9.debug("[Session] Recoverable auth error — cleaning up stored state and reconnecting fresh");
9394
9417
  try {
9395
9418
  await this.cleanupStoredConnectionParams();
@@ -9485,9 +9508,13 @@ var ClientSessionManager = class extends Destroyable {
9485
9508
  const isReconnect = hasReconnectState && storedToken;
9486
9509
  let dpopToken;
9487
9510
  if (isReconnect) logger$9.debug("[Session] Reconnecting with stored jwt_token + authorization_state");
9488
- else if (this.onBeforeReconnect && this.clientBound) {
9489
- logger$9.debug("[Session] Refreshing credentials before fresh connect");
9490
- await this.onBeforeReconnect();
9511
+ else {
9512
+ const credential = this.getCredential();
9513
+ const credentialExpired = credential.expiry_at !== void 0 && credential.expiry_at <= Date.now() + require_operators.CREDENTIAL_EXPIRY_SKEW_MS;
9514
+ if (this.onBeforeReconnect && (this.clientBound || credentialExpired)) {
9515
+ logger$9.debug("[Session] Refreshing credentials before fresh connect");
9516
+ await this.onBeforeReconnect();
9517
+ }
9491
9518
  }
9492
9519
  if ((!isReconnect || this.clientBound) && this.dpopManager?.initialized) try {
9493
9520
  dpopToken = await this.dpopManager.createRpcProof({ method: "signalwire.connect" });
@@ -9841,7 +9868,7 @@ var DeviceTokenManager = class extends Destroyable {
9841
9868
  await session.reauthenticate(tokenData.token, rpcProof, { clientBound: true });
9842
9869
  updateCredential({ token: tokenData.token });
9843
9870
  logger$7.info("[DeviceToken] Client Bound SAT activated successfully");
9844
- this._currentToken$.next(tokenData);
9871
+ this.emitCurrentToken(tokenData);
9845
9872
  return { activated: true };
9846
9873
  } catch (error) {
9847
9874
  logger$7.error("[DeviceToken] Failed to activate Client Bound SAT:", error);
@@ -9853,6 +9880,21 @@ var DeviceTokenManager = class extends Destroyable {
9853
9880
  }
9854
9881
  }
9855
9882
  /**
9883
+ * Emit a freshly received token to the reactive pipeline, stamping an
9884
+ * absolute `expires_at` when the response carried only `expires_in`.
9885
+ * Resolving the expiry at RECEIVE time (not at read time) is what lets
9886
+ * {@link refreshNowIfDue} detect due-ness on resume: a bare `expires_in`
9887
+ * re-resolved later would always compute a full TTL from "now" and never
9888
+ * cross the refresh buffer.
9889
+ */
9890
+ emitCurrentToken(token) {
9891
+ const stamped = token.expires_at ? token : {
9892
+ ...token,
9893
+ expires_at: resolveExpiresAt(token)
9894
+ };
9895
+ this._currentToken$.next(stamped);
9896
+ }
9897
+ /**
9856
9898
  * Returns true when the cached token has enough headroom before expiry to
9857
9899
  * be safely reused on reactivation. The headroom matches the refresh
9858
9900
  * buffer, so a token within the refresh window is treated as stale (the
@@ -9945,7 +9987,7 @@ var DeviceTokenManager = class extends Destroyable {
9945
9987
  const currentToken = this.getCredential().token;
9946
9988
  if (!currentToken) throw new require_operators.TokenRefreshError("No current token available for refresh");
9947
9989
  const newTokenData = await this.retryRefresh(session, currentToken, updateCredential);
9948
- this._currentToken$.next(newTokenData);
9990
+ this.emitCurrentToken(newTokenData);
9949
9991
  } catch (error) {
9950
9992
  logger$7.error("[DeviceToken] Automatic Client Bound SAT refresh failed:", error);
9951
9993
  this.errorHandler(error instanceof require_operators.TokenRefreshError ? error : new require_operators.TokenRefreshError("Automatic token refresh failed", error));
@@ -9972,6 +10014,22 @@ var DeviceTokenManager = class extends Destroyable {
9972
10014
  throw lastError instanceof Error ? lastError : new require_operators.TokenRefreshError("All refresh retries exhausted", lastError);
9973
10015
  }
9974
10016
  /**
10017
+ * Force an immediate refresh when the cached Client Bound SAT is already
10018
+ * past its refresh window. Called on resume from suspension where
10019
+ * background-tab throttling can delay the reactive timer past the buffer.
10020
+ * A no-op when no token is cached or it still has headroom; the normal
10021
+ * {@link executeRefresh} guards (paused / in-progress / unauthenticated)
10022
+ * still apply.
10023
+ */
10024
+ refreshNowIfDue() {
10025
+ const token = this._currentToken$.value;
10026
+ if (!token) return;
10027
+ if (resolveExpiresAt(token) * 1e3 - Date.now() <= require_operators.DEVICE_TOKEN_REFRESH_BUFFER_MS) {
10028
+ logger$7.debug("[DeviceToken] Resume: cached SAT past refresh window; refreshing now");
10029
+ this.executeRefresh();
10030
+ }
10031
+ }
10032
+ /**
9975
10033
  * Stops the reactive refresh pipeline from firing. Use when the underlying
9976
10034
  * session is being torn down (e.g., during {@link SignalWire.disconnect})
9977
10035
  * so a scheduled refresh cannot fire against a destroyed session.
@@ -10022,6 +10080,7 @@ var CredentialRefreshCoordinator = class extends Destroyable {
10022
10080
  this.deps = deps;
10023
10081
  this._activating = false;
10024
10082
  this._activationGeneration = 0;
10083
+ this._developerRefreshInProgress = false;
10025
10084
  if (dpopManager?.initialized) this._deviceTokenManager = (deps.deviceTokenManagerFactory ?? defaultDeviceTokenManagerFactory)(dpopManager, deps.http, (error) => deps.notifier.onError(error), () => deps.store.read());
10026
10085
  }
10027
10086
  /** True when the Client Bound SAT path is available (DPoP initialized). */
@@ -10040,28 +10099,120 @@ var CredentialRefreshCoordinator = class extends Destroyable {
10040
10099
  * invokes `deps.onRefreshExhausted` so the orchestrator can disconnect.
10041
10100
  */
10042
10101
  scheduleDeveloperRefresh(provider, expiresAt, attempt = 0) {
10102
+ this._activeProvider = provider;
10043
10103
  if (this._developerTimerId !== void 0) clearTimeout(this._developerTimerId);
10044
10104
  const refreshInterval = attempt === 0 ? Math.max(expiresAt - Date.now() - require_operators.CREDENTIAL_REFRESH_BUFFER_MS, 1e3) : Math.min(require_operators.CREDENTIAL_REFRESH_RETRY_BASE_MS * Math.pow(2, attempt) * (.5 + Math.random() * .5), require_operators.CREDENTIAL_REFRESH_MAX_DELAY_MS);
10045
- this._developerTimerId = setTimeout(async () => {
10105
+ this._developerTimerId = setTimeout(() => {
10106
+ this._developerTimerId = void 0;
10107
+ this.executeDeveloperRefresh(provider, expiresAt, attempt);
10108
+ }, refreshInterval);
10109
+ }
10110
+ /**
10111
+ * Runs the developer-provided refresh once: mints a new credential, stores
10112
+ * and persists it, reauthenticates the live session (via the notifier), and
10113
+ * reschedules against the new expiry. On failure retries with backoff up to
10114
+ * {@link CREDENTIAL_REFRESH_MAX_RETRIES}, then signals exhaustion.
10115
+ *
10116
+ * Shared by the scheduled timer tick and {@link forceRefreshIfDue}. The
10117
+ * `_developerRefreshInProgress` guard prevents the two from overlapping.
10118
+ */
10119
+ async executeDeveloperRefresh(provider, expiresAt, attempt) {
10120
+ if (this._developerRefreshInProgress) {
10121
+ logger$6.debug("[Coordinator] Developer refresh already in progress; skipping");
10122
+ return;
10123
+ }
10124
+ this._developerRefreshInProgress = true;
10125
+ try {
10126
+ const newCredentials = await this.refreshCredential(provider);
10127
+ this.deps.store.write(newCredentials);
10128
+ this.deps.store.persist(newCredentials);
10046
10129
  try {
10047
- if (!provider.refresh) throw new require_operators.InvalidCredentialsError("Credential provider does not support refresh");
10048
- const newCredentials = await provider.refresh();
10049
- this.deps.store.write(newCredentials);
10050
- this.deps.store.persist(newCredentials);
10051
- logger$6.info("[Coordinator] Credentials refreshed successfully.");
10052
- if (newCredentials.expiry_at) this.scheduleDeveloperRefresh(provider, newCredentials.expiry_at, 0);
10053
- } catch (error) {
10054
- const nextAttempt = attempt + 1;
10055
- logger$6.error(`[Coordinator] Credential refresh failed (attempt ${nextAttempt}/${require_operators.CREDENTIAL_REFRESH_MAX_RETRIES}):`, error);
10056
- this.deps.notifier.onError(error instanceof Error ? error : new Error(String(error), { cause: error }));
10057
- if (nextAttempt < require_operators.CREDENTIAL_REFRESH_MAX_RETRIES) this.scheduleDeveloperRefresh(provider, expiresAt, nextAttempt);
10058
- else {
10059
- logger$6.error("[Coordinator] Credential refresh exhausted all retries. Disconnecting.");
10060
- this.deps.notifier.onError(new require_operators.TokenRefreshError("Credential refresh failed after max retries"));
10061
- this.deps.notifier.onRefreshExhausted();
10062
- }
10130
+ await this.deps.notifier.onCredentialRefreshed(newCredentials);
10131
+ } catch (reauthError) {
10132
+ logger$6.warn("[Coordinator] onCredentialRefreshed rejected (non-fatal):", reauthError);
10063
10133
  }
10064
- }, refreshInterval);
10134
+ logger$6.info("[Coordinator] Credentials refreshed successfully.");
10135
+ if (newCredentials.expiry_at) this.scheduleDeveloperRefresh(provider, newCredentials.expiry_at, 0);
10136
+ } catch (error) {
10137
+ const nextAttempt = attempt + 1;
10138
+ logger$6.error(`[Coordinator] Credential refresh failed (attempt ${nextAttempt}/${require_operators.CREDENTIAL_REFRESH_MAX_RETRIES}):`, error);
10139
+ this.deps.notifier.onError(error instanceof Error ? error : new Error(String(error), { cause: error }));
10140
+ if (nextAttempt < require_operators.CREDENTIAL_REFRESH_MAX_RETRIES) this.scheduleDeveloperRefresh(provider, expiresAt, nextAttempt);
10141
+ else {
10142
+ logger$6.error("[Coordinator] Credential refresh exhausted all retries. Disconnecting.");
10143
+ this.deps.notifier.onError(new require_operators.TokenRefreshError("Credential refresh failed after max retries"));
10144
+ this.deps.notifier.onRefreshExhausted();
10145
+ }
10146
+ } finally {
10147
+ this._developerRefreshInProgress = false;
10148
+ }
10149
+ }
10150
+ /**
10151
+ * Force an immediate refresh when the current credential is already past its
10152
+ * scheduled refresh window. Called on resume from suspension, where
10153
+ * background-tab timer throttling can delay the armed refresh well past
10154
+ * expiry, leaving the live session stale.
10155
+ *
10156
+ * Routes to whichever mechanism is armed: the developer timer if armed,
10157
+ * otherwise the Client Bound SAT pipeline. A no-op when nothing is due.
10158
+ */
10159
+ forceRefreshIfDue() {
10160
+ if (this._developerTimerId !== void 0 && this._activeProvider) {
10161
+ const expiry = this.deps.store.read().expiry_at;
10162
+ if (expiry !== void 0 && Date.now() >= expiry - require_operators.CREDENTIAL_REFRESH_BUFFER_MS) {
10163
+ logger$6.debug("[Coordinator] Resume: credential past refresh window; forcing refresh");
10164
+ clearTimeout(this._developerTimerId);
10165
+ this._developerTimerId = void 0;
10166
+ this.executeDeveloperRefresh(this._activeProvider, expiry, 0);
10167
+ }
10168
+ return;
10169
+ }
10170
+ this._deviceTokenManager?.refreshNowIfDue();
10171
+ }
10172
+ /**
10173
+ * Sync the credential's expiry from the server-provided authorization (the
10174
+ * `signalwire.connect` result). SATs are opaque JWE, so
10175
+ * `fabric_subscriber.expires_at` is the authoritative expiry of the token
10176
+ * the session actually connected with — the provider-reported `expiry_at`
10177
+ * is only a hint (and may be wrong or absent). Corrects the stored
10178
+ * credential and re-arms the developer refresh timer against the real
10179
+ * deadline when the provider supports `refresh()`.
10180
+ */
10181
+ syncExpiryFromAuthorization(authorization, provider) {
10182
+ const expiresAtSec = authorization?.fabric_subscriber?.expires_at;
10183
+ if (!expiresAtSec) return;
10184
+ const expiryAt = expiresAtSec * 1e3;
10185
+ const credential = this.deps.store.read();
10186
+ if (credential.expiry_at === expiryAt) return;
10187
+ logger$6.debug(`[Coordinator] Correcting credential expiry from server authorization: ${new Date(expiryAt).toISOString()}`);
10188
+ const updated = {
10189
+ ...credential,
10190
+ expiry_at: expiryAt
10191
+ };
10192
+ this.deps.store.write(updated);
10193
+ this.deps.store.persist(updated);
10194
+ if (provider?.refresh) this.scheduleDeveloperRefresh(provider, expiryAt);
10195
+ }
10196
+ /**
10197
+ * Invoke `provider.refresh()` deduped against any concurrent developer
10198
+ * refresh. Concurrent callers — the scheduled tick, a resume-forced refresh,
10199
+ * and the orchestrator's -32003 recovery / reconnect re-mint — share one
10200
+ * in-flight promise, so a provider backed by one-time-use rotating refresh
10201
+ * tokens is never invoked twice in parallel.
10202
+ *
10203
+ * The caller owns applying the returned credential (store write, session
10204
+ * reauth, rescheduling); this method only serializes the network call.
10205
+ */
10206
+ async refreshCredential(provider) {
10207
+ if (this._refreshInFlight) return this._refreshInFlight;
10208
+ if (!provider.refresh) throw new require_operators.InvalidCredentialsError("Credential provider does not support refresh");
10209
+ const run = provider.refresh();
10210
+ this._refreshInFlight = run;
10211
+ const clear = () => {
10212
+ if (this._refreshInFlight === run) this._refreshInFlight = void 0;
10213
+ };
10214
+ run.then(clear, clear);
10215
+ return run;
10065
10216
  }
10066
10217
  /**
10067
10218
  * Cancels any scheduled developer-provided refresh. Idempotent.
@@ -10838,6 +10989,33 @@ var TransportManager = class extends Destroyable {
10838
10989
  }
10839
10990
  };
10840
10991
 
10992
+ //#endregion
10993
+ //#region src/utils/authRecovery.ts
10994
+ /**
10995
+ * Walk an error's `error`/`cause` chain looking for a {@link JSONRPCError}.
10996
+ * Errors thrown by call creation are wrapped (e.g. `CallCreateError`), so the
10997
+ * underlying signaling error is nested. Bounded by a visited set to guard
10998
+ * against cyclic causes.
10999
+ */
11000
+ function findJSONRPCError(error) {
11001
+ const seen = /* @__PURE__ */ new Set();
11002
+ let current = error;
11003
+ while (current instanceof Error && !seen.has(current)) {
11004
+ seen.add(current);
11005
+ if (current instanceof require_operators.JSONRPCError) return current;
11006
+ current = current.error ?? current.cause;
11007
+ }
11008
+ }
11009
+ /**
11010
+ * Whether an error is a session-recoverable authentication failure
11011
+ * (`-32002` authentication failed or `-32003` requester validation failed)
11012
+ * that a credential re-mint + retry can heal.
11013
+ */
11014
+ function isRecoverableAuthError(error) {
11015
+ const rpcError = findJSONRPCError(error);
11016
+ return rpcError !== void 0 && (rpcError.code === require_operators.RPC_ERROR_REQUESTER_VALIDATION_FAILED || rpcError.code === require_operators.RPC_ERROR_AUTHENTICATION_FAILED);
11017
+ }
11018
+
10841
11019
  //#endregion
10842
11020
  //#region src/clients/SignalWire.ts
10843
11021
  const logger$1 = require_operators.getLogger();
@@ -10952,7 +11130,8 @@ var SignalWire = class extends Destroyable {
10952
11130
  notifier: {
10953
11131
  onError: (error) => this._errors$.next(error),
10954
11132
  onWarning: (warning) => this._warnings$.next(warning),
10955
- onRefreshExhausted: () => void this.disconnect()
11133
+ onRefreshExhausted: () => void this.disconnect(),
11134
+ onCredentialRefreshed: async (credential) => this.reauthenticateLiveSession(credential)
10956
11135
  },
10957
11136
  store: {
10958
11137
  read: () => this._deps.credential,
@@ -11009,14 +11188,123 @@ var SignalWire = class extends Destroyable {
11009
11188
  }
11010
11189
  this._deps.credential = _credentials;
11011
11190
  this.persistCredential(_credentials);
11012
- if (this.isConnected && this._clientSession.authenticated && _credentials.token) try {
11013
- await this._clientSession.reauthenticate(_credentials.token);
11191
+ await this.reauthenticateLiveSession(_credentials);
11192
+ }
11193
+ /**
11194
+ * Reauthenticate the currently-open session with a freshly obtained
11195
+ * credential so the new token takes effect on the live socket immediately —
11196
+ * not just on the next reconnect. No-op when the session is not
11197
+ * connected/authenticated or the credential carries no token (e.g. an
11198
+ * authorization-state-only refresh). Non-fatal: reauth failures surface on
11199
+ * `errors$` without aborting the refresh that triggered this.
11200
+ */
11201
+ async reauthenticateLiveSession(credential) {
11202
+ if (!this.isConnected || !this._clientSession.authenticated || !credential.token) return;
11203
+ try {
11204
+ await this._clientSession.reauthenticate(credential.token);
11014
11205
  logger$1.info("[SignalWire] Session refreshed with new credentials.");
11015
11206
  } catch (error) {
11016
11207
  logger$1.error("[SignalWire] Failed to refresh session with new credentials:", error);
11017
11208
  this._errors$.next(error instanceof Error ? error : new Error(String(error), { cause: error }));
11018
11209
  }
11019
11210
  }
11211
+ /**
11212
+ * One-shot recovery for a live session that failed with a recoverable auth
11213
+ * error (`-32002`/`-32003`) because its token went stale — e.g. a refresh
11214
+ * timer that was throttled while the tab was backgrounded.
11215
+ *
11216
+ * Two steps, first that succeeds wins:
11217
+ * 1. Reauthenticate with the in-memory token (a fresh DPoP proof is
11218
+ * generated automatically). Heals a session whose token was already
11219
+ * refreshed by the coordinator but never applied to the open socket,
11220
+ * and a client-bound session whose server-side auth merely drifted.
11221
+ * 2. Re-mint via the developer provider's `refresh()` and reauthenticate.
11222
+ * Skipped for client-bound sessions (the DeviceTokenManager owns their
11223
+ * refresh; re-minting a base SAT here would drop the DPoP binding).
11224
+ *
11225
+ * @param allowRemint - Whether step 2 (provider re-mint) may run. Callers
11226
+ * pass `false` for non-auth failures so a transient network error never
11227
+ * escalates to a token re-mint; step 1 (in-memory reauth) always runs.
11228
+ * @returns `true` if the session was reauthenticated, `false` otherwise.
11229
+ */
11230
+ async recoverStaleCredential(allowRemint = true) {
11231
+ const currentToken = this._deps.credential.token;
11232
+ if (currentToken) try {
11233
+ await this._clientSession.reauthenticate(currentToken);
11234
+ return true;
11235
+ } catch (error) {
11236
+ logger$1.debug("[SignalWire] In-memory reauth failed during recovery:", error);
11237
+ }
11238
+ if (!allowRemint || this._clientSession.clientBound || !this._credentialProvider?.refresh) return false;
11239
+ try {
11240
+ const newCredentials = await this.remintCredential(this._credentialProvider);
11241
+ if (!newCredentials.token) return false;
11242
+ this._deps.credential = newCredentials;
11243
+ this.persistCredential(newCredentials);
11244
+ await this._clientSession.reauthenticate(newCredentials.token);
11245
+ if (newCredentials.expiry_at) this._refreshCoordinator?.scheduleDeveloperRefresh(this._credentialProvider, newCredentials.expiry_at);
11246
+ return true;
11247
+ } catch (error) {
11248
+ logger$1.error("[SignalWire] Credential recovery failed:", error);
11249
+ return false;
11250
+ }
11251
+ }
11252
+ /**
11253
+ * Re-mint a credential via `provider.refresh()`, routed through the
11254
+ * coordinator's shared in-flight guard so concurrent re-mint paths (a
11255
+ * scheduled/resume refresh, -32003 recovery, and reconnect) never fire a
11256
+ * second `provider.refresh()` in parallel — which rotating one-time-use
11257
+ * refresh tokens reject. Falls back to a direct call only if the coordinator
11258
+ * has not been constructed yet.
11259
+ */
11260
+ async remintCredential(provider) {
11261
+ if (this._refreshCoordinator) return this._refreshCoordinator.refreshCredential(provider);
11262
+ if (!provider.refresh) throw new require_operators.InvalidCredentialsError("Credential provider does not support refresh");
11263
+ return provider.refresh();
11264
+ }
11265
+ /**
11266
+ * Re-mint credentials before a fresh (re)connect (`onBeforeReconnect` hook).
11267
+ * The session invokes this only when it is client-bound OR the in-memory
11268
+ * token is expired. The re-mint mechanism depends on the binding:
11269
+ * - Client-bound: `authenticate()` with the DPoP fingerprint to obtain a
11270
+ * fresh base SAT the upcoming reconnect can re-bind (the
11271
+ * DeviceTokenManager re-activates afterwards).
11272
+ * - Unbound: the developer's non-interactive `refresh()` handler.
11273
+ * `authenticate()` is deliberately NOT used here — it may be interactive
11274
+ * (a login prompt) and must not fire on a background reconnect.
11275
+ *
11276
+ * Rejects on failure so the session aborts the reconnect rather than
11277
+ * replaying a stale token.
11278
+ */
11279
+ async refreshCredentialForReconnect() {
11280
+ if (!this._credentialProvider) return;
11281
+ try {
11282
+ let newCredentials;
11283
+ if (this._clientSession.clientBound) {
11284
+ const fingerprint = this._dpopManager?.initialized ? this._dpopManager.fingerprint : void 0;
11285
+ logger$1.debug("[SignalWire] Re-minting client-bound base SAT before reconnect");
11286
+ newCredentials = await this._credentialProvider.authenticate(fingerprint ? { fingerprint } : void 0);
11287
+ } else if (this._credentialProvider.refresh) {
11288
+ logger$1.debug("[SignalWire] Refreshing unbound credential before reconnect");
11289
+ newCredentials = await this.remintCredential(this._credentialProvider);
11290
+ } else {
11291
+ logger$1.warn("[SignalWire] [SW-NO-REFRESH-HANDLER] Token expired on reconnect but no refresh handler; reconnecting with the existing token.");
11292
+ return;
11293
+ }
11294
+ if (!newCredentials.token) {
11295
+ logger$1.warn("[SignalWire] Re-minted credential has no token; keeping the existing credential for reconnect.");
11296
+ return;
11297
+ }
11298
+ this._deps.credential = newCredentials;
11299
+ this.persistCredential(newCredentials);
11300
+ if (newCredentials.expiry_at && this._credentialProvider.refresh) this._refreshCoordinator?.scheduleDeveloperRefresh(this._credentialProvider, newCredentials.expiry_at);
11301
+ logger$1.debug("[SignalWire] Credential refreshed successfully for reconnect");
11302
+ } catch (error) {
11303
+ logger$1.error("[SignalWire] Failed to refresh credentials for reconnect:", error);
11304
+ this._errors$.next(error instanceof Error ? error : new Error(String(error), { cause: error }));
11305
+ throw error;
11306
+ }
11307
+ }
11020
11308
  /** Persist credential to localStorage when persistSession is enabled. */
11021
11309
  persistCredential(credential) {
11022
11310
  if (!credential.token) return;
@@ -11103,24 +11391,13 @@ var SignalWire = class extends Destroyable {
11103
11391
  this._attachManager = new AttachManager(this._deps.storage, this._deps.deviceController, PreferencesContainer.instance.reconnectCallsTimeout, this._deps.attachedCallsKey);
11104
11392
  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$);
11105
11393
  this._publicSession = new ClientSessionWrapper(this._clientSession);
11106
- this._clientSession.onBeforeReconnect = async () => {
11107
- if (!this._credentialProvider) return;
11108
- try {
11109
- const fingerprint = this._dpopManager?.initialized ? this._dpopManager.fingerprint : void 0;
11110
- logger$1.debug("[SignalWire] Credential expired, refreshing before reconnect");
11111
- const newCredentials = await this._credentialProvider.authenticate(fingerprint ? { fingerprint } : void 0);
11112
- this._deps.credential = newCredentials;
11113
- if (newCredentials.expiry_at && this._credentialProvider.refresh) this._refreshCoordinator?.scheduleDeveloperRefresh(this._credentialProvider, newCredentials.expiry_at);
11114
- logger$1.debug("[SignalWire] Credential refreshed successfully for reconnect");
11115
- } catch (error) {
11116
- logger$1.error("[SignalWire] Failed to refresh credentials for reconnect:", error);
11117
- this._errors$.next(error instanceof Error ? error : new Error(String(error), { cause: error }));
11118
- throw error;
11119
- }
11120
- };
11394
+ this._clientSession.onBeforeReconnect = async () => this.refreshCredentialForReconnect();
11121
11395
  this.subscribeTo(this._clientSession.errors$, (error) => {
11122
11396
  this._errors$.next(error);
11123
11397
  });
11398
+ this.subscribeTo(this._clientSession.authorization$, (authorization) => {
11399
+ this._refreshCoordinator?.syncExpiryFromAuthorization(authorization, this._credentialProvider);
11400
+ });
11124
11401
  await this._clientSession.connect();
11125
11402
  await this._refreshCoordinator?.activate(this._deps.user, this._clientSession);
11126
11403
  this.subscribeTo(this._clientSession.authenticated$.pipe((0, rxjs.skip)(1), (0, rxjs.filter)(Boolean)), async () => {
@@ -11283,6 +11560,13 @@ var SignalWire = class extends Destroyable {
11283
11560
  }
11284
11561
  try {
11285
11562
  this._visibilityController = new VisibilityController();
11563
+ this.subscribeTo(this._visibilityController.visibilityChange$.pipe((0, rxjs.filter)((event) => event.to === "visible")), () => {
11564
+ try {
11565
+ this._refreshCoordinator?.forceRefreshIfDue();
11566
+ } catch (error) {
11567
+ logger$1.warn("[SignalWire] Resume credential revalidation failed (non-fatal):", error);
11568
+ }
11569
+ });
11286
11570
  this.subscribeTo(this._visibilityController.visibilityChange$.pipe((0, rxjs.filter)((event) => event.to === "visible" && PreferencesContainer.instance.refreshDevicesOnVisible)), () => {
11287
11571
  logger$1.debug("[SignalWire] Page visible, re-enumerating devices");
11288
11572
  try {
@@ -11294,7 +11578,7 @@ var SignalWire = class extends Destroyable {
11294
11578
  logger$1.warn("[SignalWire] Failed to initialize VisibilityController:", error);
11295
11579
  }
11296
11580
  try {
11297
- this._diagnosticsCollector = new DiagnosticsCollector({ sdkVersion: "4.0.0-rc.1" });
11581
+ this._diagnosticsCollector = new DiagnosticsCollector({ sdkVersion: "4.0.0-rc.2" });
11298
11582
  } catch (error) {
11299
11583
  logger$1.warn("[SignalWire] Failed to initialize DiagnosticsCollector:", error);
11300
11584
  }
@@ -11365,21 +11649,23 @@ var SignalWire = class extends Destroyable {
11365
11649
  this._errors$.next(error instanceof Error ? error : new Error(String(error), { cause: error }));
11366
11650
  throw error;
11367
11651
  }
11368
- logger$1.debug("[SignalWire] Failed to register user, trying reauthentication...");
11369
- try {
11370
- await this._clientSession.reauthenticate(this._deps.credential.token);
11371
- logger$1.debug("[SignalWire] Reauthentication successful, retrying register()");
11652
+ logger$1.debug("[SignalWire] Failed to register user, attempting credential recovery...");
11653
+ let failureCause = error;
11654
+ if (await this.recoverStaleCredential(isRecoverableAuthError(error))) try {
11655
+ logger$1.debug("[SignalWire] Recovery succeeded, retrying register()");
11372
11656
  await this._transport.execute(RPCExecute({
11373
11657
  method: "subscriber.online",
11374
11658
  params: {}
11375
11659
  }));
11376
11660
  this._isRegistered$.next(true);
11377
- } catch (reauthError) {
11378
- logger$1.error("[SignalWire] Reauthentication failed during register():", reauthError);
11379
- const registerError = new require_operators.InvalidCredentialsError("Failed to register user, and reauthentication attempt also failed. Please check your credentials.", { cause: reauthError instanceof Error ? reauthError : new Error(String(reauthError), { cause: reauthError }) });
11380
- this._errors$.next(registerError);
11381
- throw registerError;
11661
+ return;
11662
+ } catch (retryError) {
11663
+ logger$1.error("[SignalWire] Register retry after recovery failed:", retryError);
11664
+ failureCause = retryError;
11382
11665
  }
11666
+ const registerError = new require_operators.InvalidCredentialsError("Failed to register user, and credential recovery also failed. Please check your credentials.", { cause: failureCause instanceof Error ? failureCause : new Error(String(failureCause), { cause: failureCause }) });
11667
+ this._errors$.next(registerError);
11668
+ throw registerError;
11383
11669
  }
11384
11670
  }
11385
11671
  /**
@@ -11432,7 +11718,15 @@ var SignalWire = class extends Destroyable {
11432
11718
  };
11433
11719
  await this.waitAuthentication();
11434
11720
  logger$1.debug("[SignalWire] Dialing with options:", computed_options);
11435
- return this._clientSession.createOutboundCall(destination, computed_options);
11721
+ try {
11722
+ return await this._clientSession.createOutboundCall(destination, computed_options);
11723
+ } catch (error) {
11724
+ if (!isRecoverableAuthError(error)) throw error;
11725
+ logger$1.debug("[SignalWire] Dial hit a recoverable auth error; recovering credential and retrying once");
11726
+ if (!await this.recoverStaleCredential()) throw error;
11727
+ await this.waitAuthentication();
11728
+ return this._clientSession.createOutboundCall(destination, computed_options);
11729
+ }
11436
11730
  }
11437
11731
  /**
11438
11732
  * Runs a multi-phase connectivity test against the given destination.
@@ -11828,7 +12122,7 @@ var StaticCredentialProvider = class {
11828
12122
  /**
11829
12123
  * Library version from package.json, injected at build time.
11830
12124
  */
11831
- const version = "4.0.0-rc.1";
12125
+ const version = "4.0.0-rc.2";
11832
12126
  /**
11833
12127
  * Flag indicating the library has been loaded and is ready to use.
11834
12128
  * For UMD builds: `window.SignalWire.ready`
@@ -11850,7 +12144,7 @@ const ready = true;
11850
12144
  */
11851
12145
  const emitReadyEvent = () => {
11852
12146
  if (typeof window !== "undefined") {
11853
- const event = new CustomEvent("signalwire:js:ready", { detail: { version: "4.0.0-rc.1" } });
12147
+ const event = new CustomEvent("signalwire:js:ready", { detail: { version: "4.0.0-rc.2" } });
11854
12148
  window.dispatchEvent(event);
11855
12149
  }
11856
12150
  };
@@ -11859,6 +12153,7 @@ emitReadyEvent();
11859
12153
  //#endregion
11860
12154
  exports.Address = Address;
11861
12155
  exports.CallCreateError = require_operators.CallCreateError;
12156
+ exports.CallNotReadyError = require_operators.CallNotReadyError;
11862
12157
  exports.ClientPreferences = ClientPreferences;
11863
12158
  exports.CollectionFetchError = require_operators.CollectionFetchError;
11864
12159
  exports.DPoPInitError = require_operators.DPoPInitError;
@@ -11870,6 +12165,7 @@ exports.MediaTrackError = require_operators.MediaTrackError;
11870
12165
  exports.MessageParseError = require_operators.MessageParseError;
11871
12166
  exports.OverconstrainedFallbackError = require_operators.OverconstrainedFallbackError;
11872
12167
  exports.Participant = Participant;
12168
+ exports.ParticipantNotReadyError = require_operators.ParticipantNotReadyError;
11873
12169
  exports.PreflightError = require_operators.PreflightError;
11874
12170
  exports.RecoveryError = require_operators.RecoveryError;
11875
12171
  exports.SelfCapabilities = SelfCapabilities;