Commit 8906e91 for jssip.net
commit 8906e9186e7878778ae5e15684971ef15a19c224
Author: José Luis Millán <jmillan@aliax.net>
Date: Thu Dec 3 17:03:50 2026 +0100
TS RTCSession
diff --git a/package-lock.json b/package-lock.json
index 6579be7..f9e34f4 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -20,6 +20,7 @@
"@types/events": "^3.0.3",
"@types/jest": "^30.0.0",
"@types/node": "^25.0.10",
+ "@types/sdp-transform": "^3.0.0",
"cpx": "^1.5.0",
"esbuild": "^0.27.2",
"eslint": "^9.39.1",
@@ -2314,6 +2315,13 @@
"undici-types": "~7.16.0"
}
},
+ "node_modules/@types/sdp-transform": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/@types/sdp-transform/-/sdp-transform-3.0.0.tgz",
+ "integrity": "sha512-TLwbrRILH3mwnrXgjZLb2LXursBR/dnumGgFWKm8Jw3nTJCAN0g80pvS4KVpXHz4DpYtne762lcXin9GmShGbg==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@types/stack-utils": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.3.tgz",
diff --git a/package.json b/package.json
index 3d849c9..6d0b12f 100644
--- a/package.json
+++ b/package.json
@@ -56,6 +56,7 @@
"@types/events": "^3.0.3",
"@types/jest": "^30.0.0",
"@types/node": "^25.0.10",
+ "@types/sdp-transform": "^3.0.0",
"cpx": "^1.5.0",
"esbuild": "^0.27.2",
"eslint": "^9.39.1",
diff --git a/src/RTCSession.d.ts b/src/RTCSession.d.ts
deleted file mode 100644
index a5142ba..0000000
--- a/src/RTCSession.d.ts
+++ /dev/null
@@ -1,352 +0,0 @@
-import { EventEmitter } from 'events';
-
-import {
- IncomingRequest,
- IncomingResponse,
- OutgoingRequest,
-} from './SIPMessage';
-import NameAddrHeader = require('./NameAddrHeader');
-import URI = require('./URI');
-import { CallOptions, UA } from './UA';
-import { causes, DTMF_TRANSPORT } from './Constants';
-
-interface RTCPeerConnectionDeprecated extends RTCPeerConnection {
- /**
- * @deprecated
- * @see https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/getRemoteStreams
- */
- getRemoteStreams(): MediaStream[];
-}
-
-export declare enum SessionDirection {
- INCOMING = 'incoming',
- OUTGOING = 'outgoing',
-}
-
-export declare enum Originator {
- LOCAL = 'local',
- REMOTE = 'remote',
- SYSTEM = 'system',
-}
-
-// options
-export interface ExtraHeaders {
- extraHeaders?: string[];
-}
-
-export interface AnswerOptions extends ExtraHeaders {
- mediaConstraints?: MediaStreamConstraints;
- mediaStream?: MediaStream;
- pcConfig?: RTCConfiguration;
- rtcConstraints?: object;
- rtcAnswerConstraints?: RTCOfferOptions;
- rtcOfferConstraints?: RTCOfferOptions;
- sessionTimersExpires?: number;
-}
-
-export interface RejectOptions extends ExtraHeaders {
- status_code?: number;
- reason_phrase?: string;
-}
-
-export interface TerminateOptions extends RejectOptions {
- body?: string;
- cause?: causes | string;
-}
-
-export interface ReferOptions extends ExtraHeaders {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- eventHandlers?: any;
- replaces?: RTCSession;
-}
-
-export interface OnHoldResult {
- local: boolean;
- remote: boolean;
-}
-
-export interface DTMFOptions extends ExtraHeaders {
- duration?: number;
- interToneGap?: number;
- transportType?: DTMF_TRANSPORT;
-}
-
-export interface HoldOptions extends ExtraHeaders {
- useUpdate?: boolean;
-}
-
-export interface RenegotiateOptions extends HoldOptions {
- rtcOfferConstraints?: RTCOfferOptions;
-}
-
-// events
-export interface DTMF extends EventEmitter {
- tone: string;
- duration: number;
-}
-
-export interface Info extends EventEmitter {
- contentType: string;
- body: string;
-}
-
-export interface PeerConnectionEvent {
- peerconnection: RTCPeerConnectionDeprecated;
-}
-
-export interface ConnectingEvent {
- request: IncomingRequest | OutgoingRequest;
-}
-
-export interface SendingEvent {
- request: OutgoingRequest;
-}
-
-export interface IncomingEvent {
- originator: Originator.LOCAL;
-}
-
-export interface EndEvent {
- originator: Originator;
- message: IncomingRequest | IncomingResponse;
- cause: string;
-}
-
-export interface IncomingDTMFEvent {
- originator: Originator.REMOTE;
- dtmf: DTMF;
- request: IncomingRequest;
-}
-
-export interface OutgoingDTMFEvent {
- originator: Originator.LOCAL;
- dtmf: DTMF;
- request: OutgoingRequest;
-}
-
-export interface IncomingInfoEvent {
- originator: Originator.REMOTE;
- info: Info;
- request: IncomingRequest;
-}
-
-export interface OutgoingInfoEvent {
- originator: Originator.LOCAL;
- info: Info;
- request: OutgoingRequest;
-}
-
-export interface HoldEvent {
- originator: Originator;
-}
-
-export interface ReInviteEvent {
- request: IncomingRequest;
- callback?: VoidFunction;
- reject: (options?: RejectOptions) => void;
-}
-
-export interface ReferEvent {
- request: IncomingRequest;
- // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
- accept: Function;
- reject: VoidFunction;
-}
-
-export interface SDPEvent {
- originator: Originator;
- type: string;
- sdp: string;
-}
-
-export interface IceCandidateEvent {
- candidate: RTCIceCandidate;
- ready: VoidFunction;
-}
-
-export interface OutgoingEvent {
- originator: Originator.REMOTE;
- response: IncomingResponse;
-}
-
-export interface OutgoingAckEvent {
- originator: Originator.LOCAL;
-}
-
-export interface IncomingAckEvent {
- originator: Originator.REMOTE;
- ack: IncomingRequest;
-}
-
-export interface MediaStreamTypes {
- audio?: boolean;
- video?: boolean;
-}
-
-// listener
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-export type GenericErrorListener = (error: any) => void;
-export type PeerConnectionListener = (event: PeerConnectionEvent) => void;
-export type ConnectingListener = (event: ConnectingEvent) => void;
-export type SendingListener = (event: SendingEvent) => void;
-export type IncomingListener = (event: IncomingEvent) => void;
-export type OutgoingListener = (event: OutgoingEvent) => void;
-export type IncomingConfirmedListener = (event: IncomingAckEvent) => void;
-export type OutgoingConfirmedListener = (event: OutgoingAckEvent) => void;
-export type CallListener = IncomingListener | OutgoingListener;
-export type ConfirmedListener =
- | IncomingConfirmedListener
- | OutgoingConfirmedListener;
-export type EndListener = (event: EndEvent) => void;
-export type IncomingDTMFListener = (event: IncomingDTMFEvent) => void;
-export type OutgoingDTMFListener = (event: OutgoingDTMFEvent) => void;
-export type DTMFListener = IncomingDTMFListener | OutgoingDTMFListener;
-export type IncomingInfoListener = (event: IncomingInfoEvent) => void;
-export type OutgoingInfoListener = (event: OutgoingInfoEvent) => void;
-export type InfoListener = IncomingInfoListener | OutgoingInfoListener;
-export type HoldListener = (event: HoldEvent) => void;
-export type MuteListener = (event: MediaStreamTypes) => void;
-export type ReInviteListener = (event: ReInviteEvent) => void;
-export type UpdateListener = ReInviteListener;
-export type ReferListener = (event: ReferEvent) => void;
-export type SDPListener = (event: SDPEvent) => void;
-export type IceCandidateListener = (event: IceCandidateEvent) => void;
-
-export interface RTCSessionEventMap {
- peerconnection: PeerConnectionListener;
- connecting: ConnectingListener;
- sending: SendingListener;
- progress: CallListener;
- accepted: CallListener;
- confirmed: ConfirmedListener;
- ended: EndListener;
- failed: EndListener;
- newDTMF: DTMFListener;
- newInfo: InfoListener;
- hold: HoldListener;
- unhold: HoldListener;
- muted: MuteListener;
- unmuted: MuteListener;
- reinvite: ReInviteListener;
- update: UpdateListener;
- refer: ReferListener;
- replaces: ReferListener;
- sdp: SDPListener;
- icecandidate: IceCandidateListener;
- getusermediafailed: GenericErrorListener;
- 'peerconnection:createofferfailed': GenericErrorListener;
- 'peerconnection:createanswerfailed': GenericErrorListener;
- 'peerconnection:setlocaldescriptionfailed': GenericErrorListener;
- 'peerconnection:setremotedescriptionfailed': GenericErrorListener;
-}
-
-declare enum SessionStatus {
- STATUS_NULL = 0,
- STATUS_INVITE_SENT = 1,
- STATUS_1XX_RECEIVED = 2,
- STATUS_INVITE_RECEIVED = 3,
- STATUS_WAITING_FOR_ANSWER = 4,
- STATUS_ANSWERED = 5,
- STATUS_WAITING_FOR_ACK = 6,
- STATUS_CANCELED = 7,
- STATUS_TERMINATED = 8,
- STATUS_CONFIRMED = 9,
-}
-
-export class RTCSession extends EventEmitter {
- constructor(ua: UA);
-
- /**
- * The UA the session belongs to, which `Dialog` reads out of its owner.
- *
- * @internal
- */
- readonly ua: UA;
-
- /**
- * Places the call. Called by `UA.call()`.
- *
- * @internal
- */
- connect(target: string | URI, options?: CallOptions): void;
-
- /**
- * Takes over an incoming INVITE. Called by `UA.receiveRequest()`.
- *
- * @internal
- */
- init_incoming(request: IncomingRequest): void;
-
- /**
- * Takes over an in-dialog request. Called by `Dialog` and by `UA`.
- *
- * @internal
- */
- receiveRequest(request: IncomingRequest): void;
-
- static get C(): typeof SessionStatus;
-
- get C(): typeof SessionStatus;
-
- get causes(): typeof causes;
-
- get id(): string;
-
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- set data(data: any);
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- get data(): any;
-
- get connection(): RTCPeerConnectionDeprecated;
-
- get contact(): string;
-
- get direction(): SessionDirection;
-
- get local_identity(): NameAddrHeader;
-
- get remote_identity(): NameAddrHeader;
-
- get start_time(): Date;
-
- get end_time(): Date;
-
- get status(): SessionStatus;
-
- isInProgress(): boolean;
-
- isEstablished(): boolean;
-
- isEnded(): boolean;
-
- isReadyToReOffer(): boolean;
-
- answer(options?: AnswerOptions): void;
-
- terminate(options?: TerminateOptions): void;
-
- sendDTMF(tones: string | number, options?: DTMFOptions): void;
-
- sendInfo(contentType: string, body?: string, options?: ExtraHeaders): void;
-
- hold(options?: HoldOptions, done?: VoidFunction): boolean;
-
- unhold(options?: HoldOptions, done?: VoidFunction): boolean;
-
- renegotiate(options?: RenegotiateOptions, done?: VoidFunction): boolean;
-
- isOnHold(): OnHoldResult;
-
- mute(options?: MediaStreamTypes): void;
-
- unmute(options?: MediaStreamTypes): void;
-
- isMuted(): MediaStreamTypes;
-
- refer(target: string | URI, options?: ReferOptions): void;
-
- on<T extends keyof RTCSessionEventMap>(
- type: T,
- listener: RTCSessionEventMap[T]
- ): this;
-}
diff --git a/src/RTCSession.js b/src/RTCSession.ts
similarity index 52%
rename from src/RTCSession.js
rename to src/RTCSession.ts
index eaed0c9..6a80521 100644
--- a/src/RTCSession.js
+++ b/src/RTCSession.ts
@@ -1,105 +1,539 @@
-/* globals RTCPeerConnection: false, RTCSessionDescription: false */
-/* eslint-disable no-invalid-this */
-
-const EventEmitter = require('events').EventEmitter;
-const sdp_transform = require('sdp-transform');
-const { Logger } = require('./Logger');
-const JsSIP_C = require('./Constants');
-const Exceptions = require('./Exceptions');
-const Transactions = require('./Transactions');
-const Utils = require('./Utils');
-const Timers = require('./Timers');
-const SIPMessage = require('./SIPMessage');
-const { Dialog, Status: DialogStatus } = require('./Dialog');
-const { RequestSender } = require('./RequestSender');
-const { DTMF: RTCSession_DTMF, C: DTMF_C } = require('./RTCSession/DTMF');
-const { Info: RTCSession_Info } = require('./RTCSession/Info');
-const {
- ReferNotifier: RTCSession_ReferNotifier,
-} = require('./RTCSession/ReferNotifier');
-const {
- ReferSubscriber: RTCSession_ReferSubscriber,
-} = require('./RTCSession/ReferSubscriber');
-const URI = require('./URI');
+import { EventEmitter } from 'events';
+import * as sdp_transform from 'sdp-transform';
+
+import * as JsSIP_C from './Constants';
+import type { Direction, Originator } from './Constants';
+import { Dialog, Status as DialogStatus } from './Dialog';
+import type {
+ DialogOwner,
+ DialogSendRequestOptions,
+ DialogType,
+} from './Dialog';
+import * as Exceptions from './Exceptions';
+import { Logger } from './Logger';
+import { RequestSender } from './RequestSender';
+import {
+ DTMF as RTCSession_DTMF,
+ C as DTMF_C,
+ type SendDTMFOptions,
+} from './RTCSession/DTMF';
+import { Info as RTCSession_Info } from './RTCSession/Info';
+import { ReferNotifier as RTCSession_ReferNotifier } from './RTCSession/ReferNotifier';
+import {
+ ReferSubscriber as RTCSession_ReferSubscriber,
+ type SendReferOptions,
+} from './RTCSession/ReferSubscriber';
+import * as SIPMessage from './SIPMessage';
+import type {
+ IncomingRequest,
+ IncomingResponse,
+ OutgoingRequest,
+} from './SIPMessage';
+import * as Timers from './Timers';
+import * as Transactions from './Transactions';
+import type { CallOptions, RTCSessionEvent, UA } from './UA';
+import * as Utils from './Utils';
+import NameAddrHeader = require('./NameAddrHeader');
+import URI = require('./URI');
const logger = new Logger('RTCSession');
-const C = {
+/**
+ * How far along a session is.
+ */
+export enum Status {
+ NULL = 0,
+ INVITE_SENT = 1,
+ PROVISIONAL_RESPONSE_RECEIVED = 2,
+ INVITE_RECEIVED = 3,
+ WAITING_FOR_ANSWER = 4,
+ ANSWERED = 5,
+ WAITING_FOR_ACK = 6,
+ CANCELED = 7,
+ TERMINATED = 8,
+ CONFIRMED = 9,
+}
+
+/**
+ * The constants a session exposes, both as a static and as an instance
+ * member.
+ *
+ * @remarks
+ * - {@link Status} holds the same values under shorter names, and is what
+ * the session itself is typed with.
+ */
+export const C = {
// RTCSession states.
- STATUS_NULL: 0,
- STATUS_INVITE_SENT: 1,
- STATUS_1XX_RECEIVED: 2,
- STATUS_INVITE_RECEIVED: 3,
- STATUS_WAITING_FOR_ANSWER: 4,
- STATUS_ANSWERED: 5,
- STATUS_WAITING_FOR_ACK: 6,
- STATUS_CANCELED: 7,
- STATUS_TERMINATED: 8,
- STATUS_CONFIRMED: 9,
+ STATUS_NULL: Status.NULL,
+ STATUS_INVITE_SENT: Status.INVITE_SENT,
+ STATUS_1XX_RECEIVED: Status.PROVISIONAL_RESPONSE_RECEIVED,
+ STATUS_INVITE_RECEIVED: Status.INVITE_RECEIVED,
+ STATUS_WAITING_FOR_ANSWER: Status.WAITING_FOR_ANSWER,
+ STATUS_ANSWERED: Status.ANSWERED,
+ STATUS_WAITING_FOR_ACK: Status.WAITING_FOR_ACK,
+ STATUS_CANCELED: Status.CANCELED,
+ STATUS_TERMINATED: Status.TERMINATED,
+ STATUS_CONFIRMED: Status.CONFIRMED,
+};
+
+/**
+ * Whether the call was placed or received.
+ *
+ * @remarks
+ * - An alias of {@link Constants.Direction}, kept under the name the library
+ * has always used for a session.
+ */
+export type SessionDirection = Direction;
+
+/**
+ * The media kinds a session can mute and put on hold.
+ */
+const holdMediaTypes: string[] = ['audio', 'video'];
+
+/**
+ * A peer connection, plus the stream accessor some browsers still carry.
+ */
+export interface RTCPeerConnectionDeprecated extends RTCPeerConnection {
+ /**
+ * @deprecated
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/getRemoteStreams
+ */
+ getRemoteStreams(): MediaStream[];
+}
+
+/**
+ * Whole `Name: value` header field lines added to the request.
+ */
+export type ExtraHeaders = {
+ extraHeaders?: string[];
+};
+
+/**
+ * Options accepted by `answer()`, and the base of the ones `UA.call()` takes.
+ */
+export type AnswerOptions = ExtraHeaders & {
+ /**
+ * Anything the application wants to keep along with the session, which
+ * becomes its `data`.
+ */
+ data?: unknown;
+ mediaConstraints?: MediaStreamConstraints;
+ mediaStream?: MediaStream;
+ pcConfig?: RTCConfiguration;
+ rtcConstraints?: object;
+ rtcAnswerConstraints?: RTCOfferOptions;
+ rtcOfferConstraints?: RTCOfferOptions;
+ sessionTimersExpires?: number;
+};
+
+/**
+ * Options accepted when turning an incoming call down.
+ */
+export type RejectOptions = ExtraHeaders & {
+ status_code?: number;
+ reason_phrase?: string;
+};
+
+/**
+ * Options accepted by `terminate()`.
+ */
+export type TerminateOptions = RejectOptions & {
+ body?: string;
+ cause?: JsSIP_C.causes | string;
+};
+
+/**
+ * Options accepted by `refer()`.
+ */
+export type ReferOptions = ExtraHeaders & {
+ eventHandlers?: SendReferOptions['eventHandlers'];
+ /**
+ * Session the transfer is to replace, which makes it an attended one.
+ */
+ replaces?: RTCSession;
+};
+
+/**
+ * Which ends of the call are on hold.
+ */
+export type OnHoldResult = {
+ local: boolean;
+ remote: boolean;
+};
+
+/**
+ * Options accepted by `sendDTMF()`.
+ */
+export type DTMFOptions = ExtraHeaders & {
+ duration?: number;
+ interToneGap?: number;
+ transportType?: JsSIP_C.DTMF_TRANSPORT;
+ /**
+ * Set by `sendDTMF()` on each tone it hands over, so that a tone that
+ * fails stops the ones still queued.
+ *
+ * @internal
+ */
+ eventHandlers?: SendDTMFOptions['eventHandlers'];
+};
+
+/**
+ * Options accepted by `hold()` and `unhold()`.
+ */
+export type HoldOptions = ExtraHeaders & {
+ /**
+ * Whether to re-offer with an UPDATE rather than a re-INVITE.
+ */
+ useUpdate?: boolean;
+};
+
+/**
+ * Options accepted by `renegotiate()`.
+ */
+export type RenegotiateOptions = HoldOptions & {
+ rtcOfferConstraints?: RTCOfferOptions;
+};
+
+/**
+ * The media kinds an operation applies to.
+ */
+export type MediaStreamTypes = {
+ audio?: boolean;
+ video?: boolean;
+};
+
+/**
+ * Reported once the peer connection exists, before it is used.
+ */
+export type PeerConnectionEvent = {
+ peerconnection: RTCPeerConnectionDeprecated;
+};
+
+/**
+ * Reported while the call is being set up.
+ */
+export type ConnectingEvent = {
+ request: IncomingRequest | OutgoingRequest;
+};
+
+/**
+ * Reported just before the initial INVITE goes out.
+ */
+export type SendingEvent = {
+ request: OutgoingRequest;
+};
+
+/**
+ * Reported for a provisional response, so a call that is ringing.
+ */
+export type ProgressEvent = {
+ originator: Originator;
+ /**
+ * `null` on an incoming call, which rings without a response of its own.
+ */
+ response: IncomingResponse | null;
+};
+
+/**
+ * Reported when the call is answered.
+ */
+export type AcceptedEvent = {
+ originator: Originator;
+ response: IncomingResponse | null;
+};
+
+/**
+ * Reported once the answer is acknowledged.
+ */
+export type ConfirmedEvent = {
+ originator: Originator;
+ ack: IncomingRequest | null;
+};
+
+/**
+ * Reported when the call is over, whether it was ever established.
+ */
+export type EndEvent = {
+ originator: Originator;
+ /**
+ * The message that ended the call, `null` when nothing on the wire did.
+ */
+ message: IncomingRequest | IncomingResponse | null;
+ cause: JsSIP_C.causes | string;
+};
+
+/**
+ * Reported for a tone sent or received within the call.
+ */
+export type DTMFEvent = {
+ originator: Originator;
+ dtmf: RTCSession_DTMF;
+ request: IncomingRequest | OutgoingRequest | null;
+};
+
+/**
+ * Reported for an INFO sent or received within the call.
+ */
+export type InfoEvent = {
+ originator: Originator;
+ info: RTCSession_Info;
+ request: IncomingRequest | OutgoingRequest | undefined;
+};
+
+/**
+ * Reported when either end puts the call on hold, or takes it off.
+ */
+export type HoldEvent = {
+ originator: Originator;
+};
+
+/**
+ * Reported for a re-INVITE or an UPDATE the peer sent. Answering it can be
+ * held back by keeping `callback`, or refused through `reject`.
+ */
+export type ReInviteEvent = {
+ request: IncomingRequest;
+ callback?: VoidFunction;
+ reject: (options?: RejectOptions) => void;
+};
+
+/**
+ * Reported when the peer asks for the call to be transferred.
+ */
+export type ReferEvent = {
+ request: IncomingRequest;
+ /**
+ * Takes the transfer on, which places a call to the target.
+ */
+ accept: (initCallback?: InitCallback, options?: AnswerOptions) => void;
+ /**
+ * Turns the transfer down.
+ */
+ reject: VoidFunction;
+};
+
+/**
+ * Reported when a call arrives asking to take this one over.
+ */
+export type ReplacesEvent = {
+ request: IncomingRequest;
+ /**
+ * Takes the replacing call on, which ends this one once the new call is
+ * confirmed.
+ */
+ accept: (initCallback?: InitCallback) => void;
+ /**
+ * Turns the replacing call down.
+ */
+ reject: VoidFunction;
};
/**
- * Local variables.
+ * Reported for each session description the call produces or takes in, so
+ * that it can be looked at and mangled before it is used.
*/
-const holdMediaTypes = ['audio', 'video'];
+export type SDPEvent = {
+ originator: Originator;
+ type: string;
+ sdp: string;
+};
-class RTCSession extends EventEmitter {
+/**
+ * Reported for each ICE candidate gathered. Calling `ready` stops the
+ * gathering and sends the description built so far.
+ */
+export type IceCandidateEvent = {
+ candidate: RTCIceCandidate;
+ ready: VoidFunction;
+};
+
+/**
+ * Called with the session as soon as it exists, before anything is sent.
+ */
+export type InitCallback = (session: RTCSession) => void;
+
+// What the two re-offer helpers take. The methods built on them are the
+// public surface; this is only how they talk to each other.
+type ReofferOptions = {
+ extraHeaders?: string[] | null;
+ eventHandlers?: {
+ succeeded?: (response?: IncomingResponse) => void;
+ failed?: (response?: IncomingResponse) => void;
+ } | null;
+ rtcOfferConstraints?: RTCOfferOptions | null;
/**
- * Expose C object.
+ * Whether the UPDATE carries an offer of its own. Only `#sendUpdate()`
+ * looks at it.
*/
- static get C() {
+ sdpOffer?: boolean;
+};
+
+/**
+ * The events a {@link RTCSession} emits.
+ */
+export type RTCSessionEventMap = {
+ peerconnection: [event: PeerConnectionEvent];
+ connecting: [event: ConnectingEvent];
+ sending: [event: SendingEvent];
+ progress: [event: ProgressEvent];
+ accepted: [event: AcceptedEvent];
+ confirmed: [event: ConfirmedEvent];
+ ended: [event: EndEvent];
+ failed: [event: EndEvent];
+ newDTMF: [event: DTMFEvent];
+ newInfo: [event: InfoEvent];
+ hold: [event: HoldEvent];
+ unhold: [event: HoldEvent];
+ muted: [event: MediaStreamTypes];
+ unmuted: [event: MediaStreamTypes];
+ reinvite: [event: ReInviteEvent];
+ update: [event: ReInviteEvent];
+ refer: [event: ReferEvent];
+ replaces: [event: ReplacesEvent];
+ sdp: [event: SDPEvent];
+ icecandidate: [event: IceCandidateEvent];
+ getusermediafailed: [error: unknown];
+ 'peerconnection:createofferfailed': [error: unknown];
+ 'peerconnection:createanswerfailed': [error: unknown];
+ 'peerconnection:setlocaldescriptionfailed': [error: unknown];
+ 'peerconnection:setremotedescriptionfailed': [error: unknown];
+ /**
+ * Emitted just before `failed`, so that the transfer machinery can
+ * report the outcome before the application is told.
+ *
+ * @internal
+ */
+ _failed: [event: EndEvent];
+};
+
+/**
+ * The listeners the application registers through the `eventHandlers` option
+ * of `UA.call()`.
+ */
+export type RTCSessionEventHandlers = {
+ [K in keyof RTCSessionEventMap]: (...args: RTCSessionEventMap[K]) => void;
+};
+
+export class RTCSession
+ extends EventEmitter<RTCSessionEventMap>
+ implements DialogOwner
+{
+ /**
+ * The constants above, reachable without the instance.
+ */
+ static get C(): typeof C {
return C;
}
- constructor(ua) {
+ /**
+ * The UA the session belongs to.
+ *
+ * @internal
+ */
+ readonly ua: UA;
+
+ #id: string | null;
+ #status: Status;
+ #dialog: Dialog | null;
+ #earlyDialogs: Record<string, Dialog>;
+ #contact: string | null;
+ #from_tag: string | null;
+ #to_tag: string | null;
+ #connection: RTCPeerConnectionDeprecated | null;
+ #connectionPromiseQueue: Promise<unknown>;
+ #request: IncomingRequest | OutgoingRequest | null;
+ #is_canceled: boolean;
+ #cancel_reason: string;
+ #is_confirmed: boolean;
+ #late_sdp: boolean;
+ #rtcOfferConstraints: RTCOfferOptions | null;
+ #rtcAnswerConstraints: RTCOfferOptions | null;
+ #localMediaStream: MediaStream | null;
+ #localMediaStreamLocallyGenerated: boolean;
+ #rtcReady: boolean;
+ #iceReady: boolean;
+
+ #timers: {
+ ackTimer: ReturnType<typeof setTimeout> | null;
+ expiresTimer: ReturnType<typeof setTimeout> | null;
+ invite2xxTimer: ReturnType<typeof setTimeout> | null;
+ userNoAnswerTimer: ReturnType<typeof setTimeout> | null;
+ };
+
+ #direction: SessionDirection | null;
+ #local_identity: NameAddrHeader | null;
+ #remote_identity: NameAddrHeader | null;
+ #start_time: Date | null;
+ #end_time: Date | null;
+ #tones: string | null;
+
+ #audioMuted: boolean;
+ #videoMuted: boolean;
+ #localHold: boolean;
+ #remoteHold: boolean;
+
+ #sessionTimers: {
+ enabled: boolean;
+ refreshMethod: string;
+ defaultExpires: number;
+ currentExpires: number | null;
+ running: boolean;
+ refresher: boolean;
+ timer: ReturnType<typeof setTimeout> | null;
+ };
+
+ #referSubscribers: Record<number, RTCSession_ReferSubscriber>;
+ #data: unknown;
+
+ constructor(ua: UA) {
logger.debug('new');
super();
- this._id = null;
+ this.#id = null;
this.ua = ua;
- this._status = C.STATUS_NULL;
- this._dialog = null;
- this._earlyDialogs = {};
- this._contact = null;
- this._from_tag = null;
- this._to_tag = null;
+ this.#status = Status.NULL;
+ this.#dialog = null;
+ this.#earlyDialogs = {};
+ this.#contact = null;
+ this.#from_tag = null;
+ this.#to_tag = null;
// The RTCPeerConnection instance (public attribute).
- this._connection = null;
+ this.#connection = null;
// Prevent races on serial PeerConnction operations.
- this._connectionPromiseQueue = Promise.resolve();
+ this.#connectionPromiseQueue = Promise.resolve();
// Incoming/Outgoing request being currently processed.
- this._request = null;
+ this.#request = null;
// Cancel state for initial outgoing request.
- this._is_canceled = false;
- this._cancel_reason = '';
+ this.#is_canceled = false;
+ this.#cancel_reason = '';
// RTCSession confirmation flag.
- this._is_confirmed = false;
+ this.#is_confirmed = false;
// Is late SDP being negotiated.
- this._late_sdp = false;
+ this.#late_sdp = false;
// Default rtcOfferConstraints and rtcAnswerConstrainsts (passed in connect() or answer()).
- this._rtcOfferConstraints = null;
- this._rtcAnswerConstraints = null;
+ this.#rtcOfferConstraints = null;
+ this.#rtcAnswerConstraints = null;
// Local MediaStream.
- this._localMediaStream = null;
- this._localMediaStreamLocallyGenerated = false;
+ this.#localMediaStream = null;
+ this.#localMediaStreamLocallyGenerated = false;
// Flag to indicate PeerConnection ready for new actions.
- this._rtcReady = true;
+ this.#rtcReady = true;
// Flag to indicate ICE candidate gathering is finished even if iceGatheringState is not yet 'complete'.
- this._iceReady = false;
+ this.#iceReady = false;
// SIP Timers.
- this._timers = {
+ this.#timers = {
ackTimer: null,
expiresTimer: null,
invite2xxTimer: null,
@@ -107,21 +541,21 @@ class RTCSession extends EventEmitter {
};
// Session info.
- this._direction = null;
- this._local_identity = null;
- this._remote_identity = null;
- this._start_time = null;
- this._end_time = null;
- this._tones = null;
+ this.#direction = null;
+ this.#local_identity = null;
+ this.#remote_identity = null;
+ this.#start_time = null;
+ this.#end_time = null;
+ this.#tones = null;
// Mute/Hold state.
- this._audioMuted = false;
- this._videoMuted = false;
- this._localHold = false;
- this._remoteHold = false;
+ this.#audioMuted = false;
+ this.#videoMuted = false;
+ this.#localHold = false;
+ this.#remoteHold = false;
// Session Timers (RFC 4028).
- this._sessionTimers = {
+ this.#sessionTimers = {
enabled: this.ua.configuration.session_timers,
refreshMethod: this.ua.configuration.session_timers_refresh_method,
defaultExpires: JsSIP_C.SESSION_EXPIRES,
@@ -132,77 +566,79 @@ class RTCSession extends EventEmitter {
};
// Map of ReferSubscriber instances indexed by the REFER's CSeq number.
- this._referSubscribers = {};
+ this.#referSubscribers = {};
// Custom session empty object for high level use.
- this._data = {};
+ this.#data = {};
}
/**
* User API
*/
- // Expose RTCSession constants as a property of the RTCSession instance.
- get C() {
+ /**
+ * The constants above.
+ */
+ get C(): typeof C {
return C;
}
// Expose session failed/ended causes as a property of the RTCSession instance.
- get causes() {
+ get causes(): typeof JsSIP_C.causes {
return JsSIP_C.causes;
}
- get id() {
- return this._id;
+ get id(): string | null {
+ return this.#id;
}
- get connection() {
- return this._connection;
+ get connection(): RTCPeerConnectionDeprecated | null {
+ return this.#connection;
}
- get contact() {
- return this._contact;
+ get contact(): string | null {
+ return this.#contact;
}
- get direction() {
- return this._direction;
+ get direction(): SessionDirection | null {
+ return this.#direction;
}
- get local_identity() {
- return this._local_identity;
+ get local_identity(): NameAddrHeader | null {
+ return this.#local_identity;
}
- get remote_identity() {
- return this._remote_identity;
+ get remote_identity(): NameAddrHeader | null {
+ return this.#remote_identity;
}
- get start_time() {
- return this._start_time;
+ get start_time(): Date | null {
+ return this.#start_time;
}
- get end_time() {
- return this._end_time;
+ get end_time(): Date | null {
+ return this.#end_time;
}
- get data() {
- return this._data;
+ get data(): unknown {
+ return this.#data;
}
- set data(_data) {
- this._data = _data;
+ set data(data: unknown) {
+ this.#data = data;
}
- get status() {
- return this._status;
+ get status(): Status {
+ return this.#status;
}
- isInProgress() {
- switch (this._status) {
- case C.STATUS_NULL:
- case C.STATUS_INVITE_SENT:
- case C.STATUS_1XX_RECEIVED:
- case C.STATUS_INVITE_RECEIVED:
- case C.STATUS_WAITING_FOR_ANSWER: {
+ isInProgress(): boolean {
+ switch (this.#status) {
+ case Status.NULL:
+ case Status.INVITE_SENT:
+ case Status.PROVISIONAL_RESPONSE_RECEIVED:
+ case Status.INVITE_RECEIVED:
+ case Status.WAITING_FOR_ANSWER: {
return true;
}
default: {
@@ -211,11 +647,11 @@ class RTCSession extends EventEmitter {
}
}
- isEstablished() {
- switch (this._status) {
- case C.STATUS_ANSWERED:
- case C.STATUS_WAITING_FOR_ACK:
- case C.STATUS_CONFIRMED: {
+ isEstablished(): boolean {
+ switch (this.#status) {
+ case Status.ANSWERED:
+ case Status.WAITING_FOR_ACK:
+ case Status.CONFIRMED: {
return true;
}
default: {
@@ -224,10 +660,10 @@ class RTCSession extends EventEmitter {
}
}
- isEnded() {
- switch (this._status) {
- case C.STATUS_CANCELED:
- case C.STATUS_TERMINATED: {
+ isEnded(): boolean {
+ switch (this.#status) {
+ case Status.CANCELED:
+ case Status.TERMINATED: {
return true;
}
default: {
@@ -236,21 +672,25 @@ class RTCSession extends EventEmitter {
}
}
- isMuted() {
+ isMuted(): MediaStreamTypes {
return {
- audio: this._audioMuted,
- video: this._videoMuted,
+ audio: this.#audioMuted,
+ video: this.#videoMuted,
};
}
- isOnHold() {
+ isOnHold(): OnHoldResult {
return {
- local: this._localHold,
- remote: this._remoteHold,
+ local: this.#localHold,
+ remote: this.#remoteHold,
};
}
- connect(target, options = {}, initCallback) {
+ connect(
+ target: string | URI,
+ options: CallOptions = {},
+ initCallback?: InitCallback
+ ): void {
logger.debug('connect()');
const originalTarget = target;
@@ -265,10 +705,10 @@ class RTCSession extends EventEmitter {
const rtcConstraints = options.rtcConstraints || null;
const rtcOfferConstraints = options.rtcOfferConstraints || null;
- this._rtcOfferConstraints = rtcOfferConstraints;
- this._rtcAnswerConstraints = options.rtcAnswerConstraints || null;
+ this.#rtcOfferConstraints = rtcOfferConstraints;
+ this.#rtcAnswerConstraints = options.rtcAnswerConstraints || null;
- this._data = options.data || this._data;
+ this.#data = options.data || this.#data;
// Check target.
if (target === undefined) {
@@ -276,49 +716,53 @@ class RTCSession extends EventEmitter {
}
// Check Session Status.
- if (this._status !== C.STATUS_NULL) {
- throw new Exceptions.InvalidStateError(this._status);
+ if (this.#status !== Status.NULL) {
+ throw new Exceptions.InvalidStateError(this.#status);
}
// Check WebRTC support.
- // eslint-disable-next-line no-undef
+
if (!window.RTCPeerConnection) {
throw new Exceptions.NotSupportedError('WebRTC not supported');
}
// Check target validity.
- target = this.ua.normalizeTarget(target);
- if (!target) {
+ const target_uri = this.ua.normalizeTarget(target);
+
+ if (!target_uri) {
throw new TypeError(`Invalid target: ${originalTarget}`);
}
// Session Timers.
- if (this._sessionTimers.enabled) {
+ if (this.#sessionTimers.enabled) {
if (Utils.isDecimal(options.sessionTimersExpires)) {
- if (options.sessionTimersExpires >= JsSIP_C.MIN_SESSION_EXPIRES) {
- this._sessionTimers.defaultExpires = options.sessionTimersExpires;
+ if (options.sessionTimersExpires! >= JsSIP_C.MIN_SESSION_EXPIRES) {
+ this.#sessionTimers.defaultExpires = options.sessionTimersExpires!;
} else {
- this._sessionTimers.defaultExpires = JsSIP_C.SESSION_EXPIRES;
+ this.#sessionTimers.defaultExpires = JsSIP_C.SESSION_EXPIRES;
}
}
}
- // Set event handlers.
- for (const event in eventHandlers) {
- if (Object.prototype.hasOwnProperty.call(eventHandlers, event)) {
- this.on(event, eventHandlers[event]);
- }
+ // Set event handlers. The map pairs each name with the listener of
+ // that event, which the loop cannot express on its own.
+ const emitter = this as unknown as EventEmitter;
+
+ for (const [event, handler] of Object.entries(eventHandlers)) {
+ emitter.on(event, handler as unknown as (...args: unknown[]) => void);
}
// Session parameter initialization.
- this._from_tag = Utils.newTag();
+ this.#from_tag = Utils.newTag();
// Set anonymous property.
const anonymous = options.anonymous || false;
- const requestParams = { from_tag: this._from_tag };
+ const requestParams: SIPMessage.OutgoingRequestParams = {
+ from_tag: this.#from_tag,
+ };
- this._contact = this.ua.contact.toString({
+ this.#contact = this.ua.contact.toString({
anonymous,
outbound: true,
});
@@ -347,51 +791,51 @@ class RTCSession extends EventEmitter {
requestParams.from_display_name = options.fromDisplayName;
}
- extraHeaders.push(`Contact: ${this._contact}`);
+ extraHeaders.push(`Contact: ${this.#contact}`);
extraHeaders.push('Content-Type: application/sdp');
- if (this._sessionTimers.enabled) {
+ if (this.#sessionTimers.enabled) {
extraHeaders.push(
- `Session-Expires: ${this._sessionTimers.defaultExpires}${this.ua.configuration.session_timers_force_refresher ? ';refresher=uac' : ''}`
+ `Session-Expires: ${this.#sessionTimers.defaultExpires}${this.ua.configuration.session_timers_force_refresher ? ';refresher=uac' : ''}`
);
}
- this._request = new SIPMessage.InitialOutgoingInviteRequest(
- target,
+ this.#request = new SIPMessage.InitialOutgoingInviteRequest(
+ target_uri,
this.ua,
requestParams,
extraHeaders
);
- this._id = this._request.call_id + this._from_tag;
+ this.#id = `${this.#request.call_id}${this.#from_tag}`;
// Create a new RTCPeerConnection instance.
- this._createRTCConnection(pcConfig, rtcConstraints);
+ this.#createRTCConnection(pcConfig, rtcConstraints);
// Set internal properties.
- this._direction = 'outgoing';
- this._local_identity = this._request.from;
- this._remote_identity = this._request.to;
+ this.#direction = 'outgoing';
+ this.#local_identity = this.#request.from;
+ this.#remote_identity = this.#request.to;
// User explicitly provided a newRTCSession callback for this session.
if (initCallback) {
initCallback(this);
}
- this._newRTCSession('local', this._request);
+ this.#newRTCSession('local', this.#request);
- this._sendInitialRequest(
+ this.#sendInitialRequest(
mediaConstraints,
rtcOfferConstraints,
mediaStream
);
}
- init_incoming(request, initCallback) {
+ init_incoming(request: IncomingRequest, initCallback?: InitCallback): void {
logger.debug('init_incoming()');
let expires;
const contentType = request.hasHeader('Content-Type')
- ? request.getHeader('Content-Type').toLowerCase()
+ ? request.getHeader('Content-Type')!.toLowerCase()
: undefined;
// Check body and content type.
@@ -402,15 +846,15 @@ class RTCSession extends EventEmitter {
}
// Session parameter initialization.
- this._status = C.STATUS_INVITE_RECEIVED;
- this._from_tag = request.from_tag;
- this._id = request.call_id + this._from_tag;
- this._request = request;
- this._contact = this.ua.contact.toString();
+ this.#status = Status.INVITE_RECEIVED;
+ this.#from_tag = request.from_tag ?? null;
+ this.#id = `${request.call_id}${this.#from_tag}`;
+ this.#request = request;
+ this.#contact = this.ua.contact.toString();
// Get the Expires header value if exists.
if (request.hasHeader('expires')) {
- expires = request.getHeader('expires') * 1000;
+ expires = Number(request.getHeader('expires')) * 1000;
}
// Set the to_tag before
@@ -423,41 +867,41 @@ class RTCSession extends EventEmitter {
*
* NOTE: `_createDialog()` reports it through the 'failed' event.
*/
- if (!this._createDialog(request, 'UAS', true)) {
+ if (!this.#createDialog(request, 'UAS', true)) {
request.reply(400, 'Error creating dialog');
return;
}
if (request.body) {
- this._late_sdp = false;
+ this.#late_sdp = false;
} else {
- this._late_sdp = true;
+ this.#late_sdp = true;
}
- this._status = C.STATUS_WAITING_FOR_ANSWER;
+ this.#status = Status.WAITING_FOR_ANSWER;
// Set userNoAnswerTimer.
- this._timers.userNoAnswerTimer = setTimeout(() => {
+ this.#timers.userNoAnswerTimer = setTimeout(() => {
request.reply(408);
- this._failed('local', null, JsSIP_C.causes.NO_ANSWER);
+ this.#failed('local', null, JsSIP_C.causes.NO_ANSWER);
}, this.ua.configuration.no_answer_timeout);
// Set expiresTimer
// RFC3261 13.3.1
if (expires) {
- this._timers.expiresTimer = setTimeout(() => {
- if (this._status === C.STATUS_WAITING_FOR_ANSWER) {
+ this.#timers.expiresTimer = setTimeout(() => {
+ if (this.#status === Status.WAITING_FOR_ANSWER) {
request.reply(487);
- this._failed('system', null, JsSIP_C.causes.EXPIRES);
+ this.#failed('system', null, JsSIP_C.causes.EXPIRES);
}
}, expires);
}
// Set internal properties.
- this._direction = 'incoming';
- this._local_identity = request.to;
- this._remote_identity = request.from;
+ this.#direction = 'incoming';
+ this.#local_identity = request.to;
+ this.#remote_identity = request.from;
// A init callback was specifically defined.
if (initCallback) {
@@ -465,28 +909,28 @@ class RTCSession extends EventEmitter {
}
// Fire 'newRTCSession' event.
- this._newRTCSession('remote', request);
+ this.#newRTCSession('remote', request);
// The user may have rejected the call in the 'newRTCSession' event.
- if (this._status === C.STATUS_TERMINATED) {
+ if ((this.#status as Status) === Status.TERMINATED) {
return;
}
// Reply 180.
- request.reply(180, null, [`Contact: ${this._contact}`]);
+ request.reply(180, null, [`Contact: ${this.#contact}`]);
// Fire 'progress' event.
// TODO: Document that 'response' field in 'progress' event is null for incoming calls.
- this._progress('local', null);
+ this.#progress('local', null);
}
/**
* Answer the call.
*/
- answer(options = {}) {
+ answer(options: AnswerOptions = {}): void {
logger.debug('answer()');
- const request = this._request;
+ const request = this.#incoming;
const extraHeaders = Utils.cloneArray(options.extraHeaders);
const mediaConstraints = Utils.cloneObject(options.mediaConstraints);
const mediaStream = options.mediaStream || null;
@@ -501,35 +945,35 @@ class RTCSession extends EventEmitter {
let peerOffersFullAudio = false;
let peerOffersFullVideo = false;
- this._rtcAnswerConstraints = rtcAnswerConstraints;
- this._rtcOfferConstraints = options.rtcOfferConstraints || null;
+ this.#rtcAnswerConstraints = rtcAnswerConstraints;
+ this.#rtcOfferConstraints = options.rtcOfferConstraints || null;
- this._data = options.data || this._data;
+ this.#data = options.data || this.#data;
// Check Session Direction and Status.
- if (this._direction !== 'incoming') {
+ if (this.#direction !== 'incoming') {
throw new Exceptions.NotSupportedError(
'"answer" not supported for outgoing RTCSession'
);
}
// Check Session status.
- if (this._status !== C.STATUS_WAITING_FOR_ANSWER) {
- throw new Exceptions.InvalidStateError(this._status);
+ if (this.#status !== Status.WAITING_FOR_ANSWER) {
+ throw new Exceptions.InvalidStateError(this.#status);
}
// Session Timers.
- if (this._sessionTimers.enabled) {
+ if (this.#sessionTimers.enabled) {
if (Utils.isDecimal(options.sessionTimersExpires)) {
- if (options.sessionTimersExpires >= JsSIP_C.MIN_SESSION_EXPIRES) {
- this._sessionTimers.defaultExpires = options.sessionTimersExpires;
+ if (options.sessionTimersExpires! >= JsSIP_C.MIN_SESSION_EXPIRES) {
+ this.#sessionTimers.defaultExpires = options.sessionTimersExpires!;
} else {
- this._sessionTimers.defaultExpires = JsSIP_C.SESSION_EXPIRES;
+ this.#sessionTimers.defaultExpires = JsSIP_C.SESSION_EXPIRES;
}
}
}
- this._status = C.STATUS_ANSWERED;
+ this.#status = Status.ANSWERED;
/**
* A dialog creation error can only be caused by the received request,
@@ -537,15 +981,15 @@ class RTCSession extends EventEmitter {
*
* NOTE: `_createDialog()` reports it through the 'failed' event.
*/
- if (!this._createDialog(request, 'UAS')) {
+ if (!this.#createDialog(request, 'UAS')) {
request.reply(400, 'Error creating dialog');
return;
}
- clearTimeout(this._timers.userNoAnswerTimer);
+ clearTimeout(this.#timers.userNoAnswerTimer ?? undefined);
- extraHeaders.unshift(`Contact: ${this._contact}`);
+ extraHeaders.unshift(`Contact: ${this.#contact}`);
// Determine incoming media from incoming SDP offer (if any).
const sdp = request.parseSDP();
@@ -617,7 +1061,7 @@ class RTCSession extends EventEmitter {
// Create a new RTCPeerConnection instance.
// TODO: This may throw an error, should react.
- this._createRTCConnection(pcConfig, rtcConstraints);
+ this.#createRTCConnection(pcConfig, rtcConstraints);
Promise.resolve()
// Handle local MediaStream.
@@ -629,17 +1073,17 @@ class RTCSession extends EventEmitter {
// Audio and/or video requested, prompt getUserMedia.
else if (mediaConstraints.audio || mediaConstraints.video) {
- this._localMediaStreamLocallyGenerated = true;
+ this.#localMediaStreamLocallyGenerated = true;
return navigator.mediaDevices
.getUserMedia(mediaConstraints)
.catch(error => {
- if (this._status === C.STATUS_TERMINATED) {
+ if (this.#status === Status.TERMINATED) {
throw new Error('terminated');
}
request.reply(480);
- this._failed(
+ this.#failed(
'local',
null,
JsSIP_C.causes.USER_DENIED_MEDIA_ACCESS
@@ -652,39 +1096,46 @@ class RTCSession extends EventEmitter {
throw new Error('getUserMedia() failed');
});
}
+
+ // No media was asked for and none was given.
+ return undefined;
})
// Attach MediaStream to RTCPeerconnection.
.then(stream => {
- if (this._status === C.STATUS_TERMINATED) {
+ if (this.#status === Status.TERMINATED) {
throw new Error('terminated');
}
- this._localMediaStream = stream;
+ this.#localMediaStream = stream ?? null;
if (stream) {
stream.getTracks().forEach(track => {
- this._connection.addTrack(track, stream);
+ this.#connection!.addTrack(track, stream);
});
}
})
// Set remote description.
.then(() => {
- if (this._late_sdp) {
+ if (this.#late_sdp) {
return;
}
- const e = { originator: 'remote', type: 'offer', sdp: request.body };
+ const e: SDPEvent = {
+ originator: 'remote',
+ type: 'offer',
+ sdp: request.body,
+ };
logger.debug('emit "sdp"');
this.emit('sdp', e);
const offer = new RTCSessionDescription({ type: 'offer', sdp: e.sdp });
- this._connectionPromiseQueue = this._connectionPromiseQueue
- .then(() => this._connection.setRemoteDescription(offer))
+ this.#connectionPromiseQueue = this.#connectionPromiseQueue
+ .then(() => this.#connection!.setRemoteDescription(offer))
.catch(error => {
request.reply(488);
- this._failed('system', null, JsSIP_C.causes.WEBRTC_ERROR);
+ this.#failed('system', null, JsSIP_C.causes.WEBRTC_ERROR);
logger.warn(
'emit "peerconnection:setremotedescriptionfailed" [error:%o]',
@@ -696,19 +1147,19 @@ class RTCSession extends EventEmitter {
throw new Error('peerconnection.setRemoteDescription() failed');
});
- return this._connectionPromiseQueue;
+ return this.#connectionPromiseQueue;
})
// Create local description.
.then(() => {
- if (this._status === C.STATUS_TERMINATED) {
+ if (this.#status === Status.TERMINATED) {
throw new Error('terminated');
}
// TODO: Is this event already useful?
- this._connecting(request);
+ this.#connecting(request);
- if (!this._late_sdp) {
- return this._createLocalDescription(
+ if (!this.#late_sdp) {
+ return this.#createLocalDescription(
'answer',
rtcAnswerConstraints
).catch(() => {
@@ -717,9 +1168,9 @@ class RTCSession extends EventEmitter {
throw new Error('_createLocalDescription() failed');
});
} else {
- return this._createLocalDescription(
+ return this.#createLocalDescription(
'offer',
- this._rtcOfferConstraints
+ this.#rtcOfferConstraints
).catch(() => {
request.reply(500);
@@ -729,11 +1180,11 @@ class RTCSession extends EventEmitter {
})
// Send reply.
.then(desc => {
- if (this._status === C.STATUS_TERMINATED) {
+ if (this.#status === Status.TERMINATED) {
throw new Error('terminated');
}
- this._handleSessionTimersInIncomingRequest(request, extraHeaders);
+ this.#handleSessionTimersInIncomingRequest(request, extraHeaders);
request.reply(
200,
@@ -741,32 +1192,32 @@ class RTCSession extends EventEmitter {
extraHeaders,
desc,
() => {
- this._status = C.STATUS_WAITING_FOR_ACK;
+ this.#status = Status.WAITING_FOR_ACK;
- this._setInvite2xxTimer(request, desc);
- this._setACKTimer();
- this._accepted('local');
+ this.#setInvite2xxTimer(request, desc);
+ this.#setACKTimer();
+ this.#accepted('local');
},
() => {
- this._failed('system', null, JsSIP_C.causes.CONNECTION_ERROR);
+ this.#failed('system', null, JsSIP_C.causes.CONNECTION_ERROR);
}
);
})
.catch(error => {
- if (this._status === C.STATUS_TERMINATED) {
+ if (this.#status === Status.TERMINATED) {
return;
}
logger.warn(`answer() failed: ${error.message}`);
- this._failed('system', error.message, JsSIP_C.causes.INTERNAL_ERROR);
+ this.#failed('system', error.message, JsSIP_C.causes.INTERNAL_ERROR);
});
}
/**
* Terminate the call.
*/
- terminate(options = {}) {
+ terminate(options: TerminateOptions = {}): void {
logger.debug('terminate()');
const cause = options.cause || JsSIP_C.causes.BYE;
@@ -778,15 +1229,15 @@ class RTCSession extends EventEmitter {
let reason_phrase = options.reason_phrase;
// Check Session Status.
- if (this._status === C.STATUS_TERMINATED) {
- throw new Exceptions.InvalidStateError(this._status);
+ if (this.#status === Status.TERMINATED) {
+ throw new Exceptions.InvalidStateError(this.#status);
}
- switch (this._status) {
+ switch (this.#status) {
// - UAC -
- case C.STATUS_NULL:
- case C.STATUS_INVITE_SENT:
- case C.STATUS_1XX_RECEIVED: {
+ case Status.NULL:
+ case Status.INVITE_SENT:
+ case Status.PROVISIONAL_RESPONSE_RECEIVED: {
logger.debug('canceling session');
if (status_code && (status_code < 200 || status_code >= 700)) {
@@ -799,24 +1250,24 @@ class RTCSession extends EventEmitter {
// Check Session Status.
if (
- this._status === C.STATUS_NULL ||
- this._status === C.STATUS_INVITE_SENT
+ this.#status === Status.NULL ||
+ this.#status === Status.INVITE_SENT
) {
- this._is_canceled = true;
- this._cancel_reason = cancel_reason;
- } else if (this._status === C.STATUS_1XX_RECEIVED) {
- this._request.cancel(cancel_reason);
+ this.#is_canceled = true;
+ this.#cancel_reason = cancel_reason ?? '';
+ } else if (this.#status === Status.PROVISIONAL_RESPONSE_RECEIVED) {
+ this.#outgoing.cancel(cancel_reason);
}
- this._status = C.STATUS_CANCELED;
+ this.#status = Status.CANCELED;
- this._failed('local', null, JsSIP_C.causes.CANCELED);
+ this.#failed('local', null, JsSIP_C.causes.CANCELED);
break;
}
// - UAS -
- case C.STATUS_WAITING_FOR_ANSWER:
- case C.STATUS_ANSWERED: {
+ case Status.WAITING_FOR_ANSWER:
+ case Status.ANSWERED: {
logger.debug('rejecting session');
status_code = status_code || 480;
@@ -825,17 +1276,17 @@ class RTCSession extends EventEmitter {
throw new TypeError(`Invalid status_code: ${status_code}`);
}
- this._request.reply(status_code, reason_phrase, extraHeaders, body);
- this._failed('local', null, JsSIP_C.causes.REJECTED);
+ this.#incoming.reply(status_code, reason_phrase, extraHeaders, body);
+ this.#failed('local', null, JsSIP_C.causes.REJECTED);
break;
}
- case C.STATUS_WAITING_FOR_ACK:
- case C.STATUS_CONFIRMED: {
+ case Status.WAITING_FOR_ACK:
+ case Status.CONFIRMED: {
logger.debug('terminating session');
reason_phrase =
- options.reason_phrase || JsSIP_C.REASON_PHRASE[status_code] || '';
+ options.reason_phrase || JsSIP_C.REASON_PHRASE[status_code!] || '';
if (status_code && (status_code < 200 || status_code >= 700)) {
throw new TypeError(`Invalid status_code: ${status_code}`);
@@ -851,13 +1302,13 @@ class RTCSession extends EventEmitter {
// until it has received an ACK for its 2xx response or until the server
// transaction times out."
if (
- this._status === C.STATUS_WAITING_FOR_ACK &&
- this._direction === 'incoming' &&
- this._request.server_transaction.state !==
+ this.#status === Status.WAITING_FOR_ACK &&
+ this.#direction === 'incoming' &&
+ this.#incoming.server_transaction!.state !==
Transactions.Status.TERMINATED
) {
// Save the dialog for later restoration.
- const dialog = this._dialog;
+ const dialog = this.#dialog!;
// Send the BYE as soon as the ACK is received...
this.receiveRequest = ({ method }) => {
@@ -871,9 +1322,9 @@ class RTCSession extends EventEmitter {
};
// .., or when the INVITE transaction times out
- this._request.server_transaction.on('stateChanged', () => {
+ this.#incoming.server_transaction!.on('stateChanged', () => {
if (
- this._request.server_transaction.state ===
+ this.#incoming.server_transaction!.state ===
Transactions.Status.TERMINATED
) {
this.sendRequest(JsSIP_C.BYE, {
@@ -884,10 +1335,10 @@ class RTCSession extends EventEmitter {
}
});
- this._ended('local', null, cause);
+ this.#ended('local', null, cause);
// Restore the dialog into 'this' in order to be able to send the in-dialog BYE :-).
- this._dialog = dialog;
+ this.#dialog = dialog;
// Restore the dialog into 'ua' so the ACK can reach 'this' session.
this.ua.newDialog(dialog);
@@ -897,13 +1348,13 @@ class RTCSession extends EventEmitter {
body,
});
- this._ended('local', null, cause);
+ this.#ended('local', null, cause);
}
}
}
}
- sendDTMF(tones, options = {}) {
+ sendDTMF(tones: string | number, options: DTMFOptions = {}): void {
logger.debug('sendDTMF() | tones: %s', tones);
let duration = options.duration || null;
@@ -916,11 +1367,11 @@ class RTCSession extends EventEmitter {
// Check Session Status.
if (
- this._status !== C.STATUS_CONFIRMED &&
- this._status !== C.STATUS_WAITING_FOR_ACK &&
- this._status !== C.STATUS_1XX_RECEIVED
+ this.#status !== Status.CONFIRMED &&
+ this.#status !== Status.WAITING_FOR_ACK &&
+ this.#status !== Status.PROVISIONAL_RESPONSE_RECEIVED
) {
- throw new Exceptions.InvalidStateError(this._status);
+ throw new Exceptions.InvalidStateError(this.#status);
}
// Check Transport type.
@@ -982,7 +1433,7 @@ class RTCSession extends EventEmitter {
// RFC2833. Let RTCDTMFSender enqueue the DTMFs.
if (transportType === JsSIP_C.DTMF_TRANSPORT.RFC2833) {
// Send DTMF in current audio RTP stream.
- const sender = this._getDTMFRTPSender();
+ const sender = this.#getDTMFRTPSender();
if (sender) {
// Add remaining buffered tones.
@@ -994,33 +1445,33 @@ class RTCSession extends EventEmitter {
return;
}
- if (this._tones) {
+ if (this.#tones) {
// Tones are already queued, just add to the queue.
- this._tones += tones;
+ this.#tones += tones;
return;
}
- this._tones = tones;
+ this.#tones = tones;
// Send the first tone.
_sendDTMF.call(this);
- function _sendDTMF() {
+ function _sendDTMF(this: RTCSession): void {
let timeout;
- if (this._status === C.STATUS_TERMINATED || !this._tones) {
+ if (this.#status === Status.TERMINATED || !this.#tones) {
// Stop sending DTMF.
- this._tones = null;
+ this.#tones = null;
return;
}
// Retrieve the next tone.
- const tone = this._tones[0];
+ const tone = this.#tones[0];
- // Remove the tone from this._tones.
- this._tones = this._tones.substring(1);
+ // Remove the tone from this.#tones.
+ this.#tones = this.#tones.substring(1);
if (tone === ',') {
timeout = 2000;
@@ -1030,11 +1481,11 @@ class RTCSession extends EventEmitter {
options.eventHandlers = {
onFailed: () => {
- this._tones = null;
+ this.#tones = null;
},
};
- dtmf.send(tone, options);
- timeout = duration + interToneGap;
+ dtmf.send(tone!, options);
+ timeout = duration! + interToneGap!;
}
// Set timeout for the next tone.
@@ -1042,16 +1493,20 @@ class RTCSession extends EventEmitter {
}
}
- sendInfo(contentType, body, options = {}) {
+ sendInfo(
+ contentType: string,
+ body?: string,
+ options: ExtraHeaders = {}
+ ): void {
logger.debug('sendInfo()');
// Check Session Status.
if (
- this._status !== C.STATUS_CONFIRMED &&
- this._status !== C.STATUS_WAITING_FOR_ACK &&
- this._status !== C.STATUS_1XX_RECEIVED
+ this.#status !== Status.CONFIRMED &&
+ this.#status !== Status.WAITING_FOR_ACK &&
+ this.#status !== Status.PROVISIONAL_RESPONSE_RECEIVED
) {
- throw new Exceptions.InvalidStateError(this._status);
+ throw new Exceptions.InvalidStateError(this.#status);
}
const info = new RTCSession_Info(this);
@@ -1062,26 +1517,26 @@ class RTCSession extends EventEmitter {
/**
* Mute
*/
- mute(options = { audio: true, video: false }) {
+ mute(options: MediaStreamTypes = { audio: true, video: false }): void {
logger.debug('mute()');
let audioMuted = false,
videoMuted = false;
- if (this._audioMuted === false && options.audio) {
+ if (this.#audioMuted === false && options.audio) {
audioMuted = true;
- this._audioMuted = true;
- this._toggleMuteAudio(true);
+ this.#audioMuted = true;
+ this.#toggleMuteAudio(true);
}
- if (this._videoMuted === false && options.video) {
+ if (this.#videoMuted === false && options.video) {
videoMuted = true;
- this._videoMuted = true;
- this._toggleMuteVideo(true);
+ this.#videoMuted = true;
+ this.#toggleMuteVideo(true);
}
if (audioMuted === true || videoMuted === true) {
- this._onmute({
+ this.#onmute({
audio: audioMuted,
video: videoMuted,
});
@@ -1091,32 +1546,32 @@ class RTCSession extends EventEmitter {
/**
* Unmute
*/
- unmute(options = { audio: true, video: true }) {
+ unmute(options: MediaStreamTypes = { audio: true, video: true }): void {
logger.debug('unmute()');
let audioUnMuted = false,
videoUnMuted = false;
- if (this._audioMuted === true && options.audio) {
+ if (this.#audioMuted === true && options.audio) {
audioUnMuted = true;
- this._audioMuted = false;
+ this.#audioMuted = false;
- if (this._localHold === false) {
- this._toggleMuteAudio(false);
+ if (this.#localHold === false) {
+ this.#toggleMuteAudio(false);
}
}
- if (this._videoMuted === true && options.video) {
+ if (this.#videoMuted === true && options.video) {
videoUnMuted = true;
- this._videoMuted = false;
+ this.#videoMuted = false;
- if (this._localHold === false) {
- this._toggleMuteVideo(false);
+ if (this.#localHold === false) {
+ this.#toggleMuteVideo(false);
}
}
if (audioUnMuted === true || videoUnMuted === true) {
- this._onunmute({
+ this.#onunmute({
audio: audioUnMuted,
video: videoUnMuted,
});
@@ -1126,17 +1581,17 @@ class RTCSession extends EventEmitter {
/**
* Hold
*/
- hold(options = {}, done) {
+ hold(options: HoldOptions = {}, done?: VoidFunction): boolean {
logger.debug('hold()');
if (
- this._status !== C.STATUS_WAITING_FOR_ACK &&
- this._status !== C.STATUS_CONFIRMED
+ this.#status !== Status.WAITING_FOR_ACK &&
+ this.#status !== Status.CONFIRMED
) {
return false;
}
- if (this._localHold === true) {
+ if (this.#localHold === true) {
return false;
}
@@ -1144,8 +1599,8 @@ class RTCSession extends EventEmitter {
return false;
}
- this._localHold = true;
- this._onhold('local');
+ this.#localHold = true;
+ this.#onhold('local');
const eventHandlers = {
succeeded: () => {
@@ -1163,13 +1618,13 @@ class RTCSession extends EventEmitter {
};
if (options.useUpdate) {
- this._sendUpdate({
+ this.#sendUpdate({
sdpOffer: true,
eventHandlers,
extraHeaders: options.extraHeaders,
});
} else {
- this._sendReinvite({
+ this.#sendReinvite({
eventHandlers,
extraHeaders: options.extraHeaders,
});
@@ -1178,17 +1633,17 @@ class RTCSession extends EventEmitter {
return true;
}
- unhold(options = {}, done) {
+ unhold(options: HoldOptions = {}, done?: VoidFunction): boolean {
logger.debug('unhold()');
if (
- this._status !== C.STATUS_WAITING_FOR_ACK &&
- this._status !== C.STATUS_CONFIRMED
+ this.#status !== Status.WAITING_FOR_ACK &&
+ this.#status !== Status.CONFIRMED
) {
return false;
}
- if (this._localHold === false) {
+ if (this.#localHold === false) {
return false;
}
@@ -1196,8 +1651,8 @@ class RTCSession extends EventEmitter {
return false;
}
- this._localHold = false;
- this._onunhold('local');
+ this.#localHold = false;
+ this.#onunhold('local');
const eventHandlers = {
succeeded: () => {
@@ -1215,13 +1670,13 @@ class RTCSession extends EventEmitter {
};
if (options.useUpdate) {
- this._sendUpdate({
+ this.#sendUpdate({
sdpOffer: true,
eventHandlers,
extraHeaders: options.extraHeaders,
});
} else {
- this._sendReinvite({
+ this.#sendReinvite({
eventHandlers,
extraHeaders: options.extraHeaders,
});
@@ -1230,14 +1685,14 @@ class RTCSession extends EventEmitter {
return true;
}
- renegotiate(options = {}, done) {
+ renegotiate(options: RenegotiateOptions = {}, done?: VoidFunction): boolean {
logger.debug('renegotiate()');
const rtcOfferConstraints = options.rtcOfferConstraints || null;
if (
- this._status !== C.STATUS_WAITING_FOR_ACK &&
- this._status !== C.STATUS_CONFIRMED
+ this.#status !== Status.WAITING_FOR_ACK &&
+ this.#status !== Status.CONFIRMED
) {
return false;
}
@@ -1261,17 +1716,17 @@ class RTCSession extends EventEmitter {
},
};
- this._setLocalMediaStatus();
+ this.#setLocalMediaStatus();
if (options.useUpdate) {
- this._sendUpdate({
+ this.#sendUpdate({
sdpOffer: true,
eventHandlers,
rtcOfferConstraints,
extraHeaders: options.extraHeaders,
});
} else {
- this._sendReinvite({
+ this.#sendReinvite({
eventHandlers,
rtcOfferConstraints,
extraHeaders: options.extraHeaders,
@@ -1284,50 +1739,54 @@ class RTCSession extends EventEmitter {
/**
* Refer
*/
- refer(target, options) {
+ refer(
+ target: string | URI,
+ options?: ReferOptions
+ ): RTCSession_ReferSubscriber | false {
logger.debug('refer()');
const originalTarget = target;
if (
- this._status !== C.STATUS_WAITING_FOR_ACK &&
- this._status !== C.STATUS_CONFIRMED
+ this.#status !== Status.WAITING_FOR_ACK &&
+ this.#status !== Status.CONFIRMED
) {
return false;
}
// Check target validity.
- target = this.ua.normalizeTarget(target);
- if (!target) {
+ const target_uri = this.ua.normalizeTarget(target);
+
+ if (!target_uri) {
throw new TypeError(`Invalid target: ${originalTarget}`);
}
const referSubscriber = new RTCSession_ReferSubscriber(this);
- referSubscriber.sendRefer(target, options);
+ referSubscriber.sendRefer(target_uri, options);
// Store in the map.
let id = referSubscriber.id;
- this._referSubscribers[id] = referSubscriber;
+ this.#referSubscribers[id!] = referSubscriber;
// Listen for ending events so we can remove it from the map.
referSubscriber.on('requestFailed', () => {
- delete this._referSubscribers[id];
+ delete this.#referSubscribers[id!];
});
referSubscriber.on('accepted', () => {
- delete this._referSubscribers[id];
+ delete this.#referSubscribers[id!];
});
referSubscriber.on('failed', () => {
- delete this._referSubscribers[id];
+ delete this.#referSubscribers[id!];
});
referSubscriber.on('authenticated', () => {
// Refer request authentication casues CSEQ and hence ID update.
- delete this._referSubscribers[id];
+ delete this.#referSubscribers[id!];
id = referSubscriber.id;
- this._referSubscribers[id] = referSubscriber;
+ this.#referSubscribers[id!] = referSubscriber;
});
return referSubscriber;
@@ -1336,16 +1795,19 @@ class RTCSession extends EventEmitter {
/**
* Send a generic in-dialog Request
*/
- sendRequest(method, options) {
+ sendRequest(
+ method: string,
+ options?: DialogSendRequestOptions
+ ): OutgoingRequest | undefined {
logger.debug('sendRequest()');
- if (this._dialog) {
- return this._dialog.sendRequest(method, options);
+ if (this.#dialog) {
+ return this.#dialog.sendRequest(method, options);
} else {
- const dialogsArray = Object.values(this._earlyDialogs);
+ const dialogsArray = Object.values(this.#earlyDialogs);
if (dialogsArray.length > 0) {
- return dialogsArray[0].sendRequest(method, options);
+ return dialogsArray[0]!.sendRequest(method, options);
}
logger.warn('sendRequest() | no valid early dialog found');
@@ -1357,7 +1819,7 @@ class RTCSession extends EventEmitter {
/**
* In dialog Request Reception
*/
- receiveRequest(request) {
+ receiveRequest(request: IncomingRequest): void {
logger.debug('receiveRequest()');
if (request.method === JsSIP_C.CANCEL) {
@@ -1370,28 +1832,28 @@ class RTCSession extends EventEmitter {
// Terminate the whole session in case the user didn't accept (or yet send the answer)
// nor reject the request opening the session.
if (
- this._status === C.STATUS_WAITING_FOR_ANSWER ||
- this._status === C.STATUS_ANSWERED
+ this.#status === Status.WAITING_FOR_ANSWER ||
+ this.#status === Status.ANSWERED
) {
- this._status = C.STATUS_CANCELED;
- this._request.reply(487);
- this._failed('remote', request, JsSIP_C.causes.CANCELED);
+ this.#status = Status.CANCELED;
+ this.#incoming.reply(487);
+ this.#failed('remote', request, JsSIP_C.causes.CANCELED);
}
} else {
// Requests arriving here are in-dialog requests.
switch (request.method) {
case JsSIP_C.ACK: {
- if (this._status !== C.STATUS_WAITING_FOR_ACK) {
+ if (this.#status !== Status.WAITING_FOR_ACK) {
return;
}
// Update signaling status.
- this._status = C.STATUS_CONFIRMED;
+ this.#status = Status.CONFIRMED;
- clearTimeout(this._timers.ackTimer);
- clearTimeout(this._timers.invite2xxTimer);
+ clearTimeout(this.#timers.ackTimer ?? undefined);
+ clearTimeout(this.#timers.invite2xxTimer ?? undefined);
- if (this._late_sdp) {
+ if (this.#late_sdp) {
if (!request.body) {
this.terminate({
cause: JsSIP_C.causes.MISSING_SDP,
@@ -1400,7 +1862,7 @@ class RTCSession extends EventEmitter {
break;
}
- const e = {
+ const e: SDPEvent = {
originator: 'remote',
type: 'answer',
sdp: request.body,
@@ -1414,11 +1876,11 @@ class RTCSession extends EventEmitter {
sdp: e.sdp,
});
- this._connectionPromiseQueue = this._connectionPromiseQueue
- .then(() => this._connection.setRemoteDescription(answer))
+ this.#connectionPromiseQueue = this.#connectionPromiseQueue
+ .then(() => this.#connection!.setRemoteDescription(answer))
.then(() => {
- if (!this._is_confirmed) {
- this._confirmed('remote', request);
+ if (!this.#is_confirmed) {
+ this.#confirmed('remote', request);
}
})
.catch(error => {
@@ -1433,37 +1895,37 @@ class RTCSession extends EventEmitter {
);
this.emit('peerconnection:setremotedescriptionfailed', error);
});
- } else if (!this._is_confirmed) {
- this._confirmed('remote', request);
+ } else if (!this.#is_confirmed) {
+ this.#confirmed('remote', request);
}
break;
}
case JsSIP_C.BYE: {
if (
- this._status === C.STATUS_CONFIRMED ||
- this._status === C.STATUS_WAITING_FOR_ACK
+ this.#status === Status.CONFIRMED ||
+ this.#status === Status.WAITING_FOR_ACK
) {
request.reply(200);
- this._ended('remote', request, JsSIP_C.causes.BYE);
+ this.#ended('remote', request, JsSIP_C.causes.BYE);
} else if (
- this._status === C.STATUS_INVITE_RECEIVED ||
- this._status === C.STATUS_WAITING_FOR_ANSWER
+ this.#status === Status.INVITE_RECEIVED ||
+ this.#status === Status.WAITING_FOR_ANSWER
) {
request.reply(200);
- this._request.reply(487, 'BYE Received');
- this._ended('remote', request, JsSIP_C.causes.BYE);
+ this.#incoming.reply(487, 'BYE Received');
+ this.#ended('remote', request, JsSIP_C.causes.BYE);
} else {
request.reply(403, 'Wrong Status');
}
break;
}
case JsSIP_C.INVITE: {
- if (this._status === C.STATUS_CONFIRMED) {
+ if (this.#status === Status.CONFIRMED) {
if (request.hasHeader('replaces')) {
- this._receiveReplaces(request);
+ this.#receiveReplaces(request);
} else {
- this._receiveReinvite(request);
+ this.#receiveReinvite(request);
}
} else {
request.reply(403, 'Wrong Status');
@@ -1472,17 +1934,17 @@ class RTCSession extends EventEmitter {
}
case JsSIP_C.INFO: {
if (
- this._status === C.STATUS_1XX_RECEIVED ||
- this._status === C.STATUS_WAITING_FOR_ANSWER ||
- this._status === C.STATUS_ANSWERED ||
- this._status === C.STATUS_WAITING_FOR_ACK ||
- this._status === C.STATUS_CONFIRMED
+ this.#status === Status.PROVISIONAL_RESPONSE_RECEIVED ||
+ this.#status === Status.WAITING_FOR_ANSWER ||
+ this.#status === Status.ANSWERED ||
+ this.#status === Status.WAITING_FOR_ACK ||
+ this.#status === Status.CONFIRMED
) {
const contentType = request.hasHeader('Content-Type')
- ? request.getHeader('Content-Type').toLowerCase()
+ ? request.getHeader('Content-Type')!.toLowerCase()
: undefined;
- if (contentType && contentType.match(/^application\/dtmf-relay/i)) {
+ if (contentType?.match(/^application\/dtmf-relay/i)) {
new RTCSession_DTMF(this).init_incoming(request);
} else if (contentType !== undefined) {
new RTCSession_Info(this).init_incoming(request);
@@ -1495,24 +1957,24 @@ class RTCSession extends EventEmitter {
break;
}
case JsSIP_C.UPDATE: {
- if (this._status === C.STATUS_CONFIRMED) {
- this._receiveUpdate(request);
+ if (this.#status === Status.CONFIRMED) {
+ this.#receiveUpdate(request);
} else {
request.reply(403, 'Wrong Status');
}
break;
}
case JsSIP_C.REFER: {
- if (this._status === C.STATUS_CONFIRMED) {
- this._receiveRefer(request);
+ if (this.#status === Status.CONFIRMED) {
+ this.#receiveRefer(request);
} else {
request.reply(403, 'Wrong Status');
}
break;
}
case JsSIP_C.NOTIFY: {
- if (this._status === C.STATUS_CONFIRMED) {
- this._receiveNotify(request);
+ if (this.#status === Status.CONFIRMED) {
+ this.#receiveNotify(request);
} else {
request.reply(403, 'Wrong Status');
}
@@ -1529,10 +1991,10 @@ class RTCSession extends EventEmitter {
* Session Callbacks
*/
- onTransportError() {
+ onTransportError(): void {
logger.warn('onTransportError()');
- if (this._status !== C.STATUS_TERMINATED) {
+ if (this.#status !== Status.TERMINATED) {
this.terminate({
status_code: 500,
reason_phrase: JsSIP_C.causes.CONNECTION_ERROR,
@@ -1541,10 +2003,10 @@ class RTCSession extends EventEmitter {
}
}
- onRequestTimeout() {
+ onRequestTimeout(): void {
logger.warn('onRequestTimeout()');
- if (this._status !== C.STATUS_TERMINATED) {
+ if (this.#status !== Status.TERMINATED) {
this.terminate({
status_code: 408,
reason_phrase: JsSIP_C.causes.REQUEST_TIMEOUT,
@@ -1553,10 +2015,10 @@ class RTCSession extends EventEmitter {
}
}
- onDialogError() {
+ onDialogError(): void {
logger.warn('onDialogError()');
- if (this._status !== C.STATUS_TERMINATED) {
+ if (this.#status !== Status.TERMINATED) {
this.terminate({
status_code: 500,
reason_phrase: JsSIP_C.causes.DIALOG_ERROR,
@@ -1566,14 +2028,14 @@ class RTCSession extends EventEmitter {
}
// Called from DTMF handler.
- newDTMF(data) {
+ newDTMF(data: DTMFEvent): void {
logger.debug('newDTMF()');
this.emit('newDTMF', data);
}
// Called from Info handler.
- newInfo(data) {
+ newInfo(data: InfoEvent): void {
logger.debug('newInfo()');
this.emit('newInfo', data);
@@ -1582,15 +2044,15 @@ class RTCSession extends EventEmitter {
/**
* Check if RTCSession is ready for an outgoing re-INVITE or UPDATE with SDP.
*/
- isReadyToReOffer() {
- if (!this._rtcReady) {
+ isReadyToReOffer(): boolean {
+ if (!this.#rtcReady) {
logger.debug('isReadyToReOffer() | internal WebRTC status not ready');
return false;
}
// No established yet.
- if (!this._dialog) {
+ if (!this.#dialog) {
logger.debug('isReadyToReOffer() | session not established yet');
return false;
@@ -1598,8 +2060,8 @@ class RTCSession extends EventEmitter {
// Another INVITE transaction is in progress.
if (
- this._dialog.uac_pending_reply === true ||
- this._dialog.uas_pending_reply === true
+ this.#dialog.uac_pending_reply === true ||
+ this.#dialog.uas_pending_reply === true
) {
logger.debug(
'isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress'
@@ -1611,26 +2073,78 @@ class RTCSession extends EventEmitter {
return true;
}
- _close() {
+ /**
+ * The dialog the call runs in, `null` until it is established.
+ *
+ * @internal
+ */
+ get dialog(): Dialog | null {
+ return this.#dialog;
+ }
+
+ /**
+ * The INVITE that set the call up, whichever way it went.
+ *
+ * @internal
+ */
+ get request(): IncomingRequest | OutgoingRequest | null {
+ return this.#request;
+ }
+
+ /**
+ * Tag of the From header field of that INVITE.
+ *
+ * @internal
+ */
+ get from_tag(): string | null {
+ return this.#from_tag;
+ }
+
+ /**
+ * Tag of its To header field.
+ *
+ * @internal
+ */
+ get to_tag(): string | null {
+ return this.#to_tag;
+ }
+
+ /**
+ * The initial request seen as the incoming INVITE it is. Only the paths
+ * that run on a call this UA received reach it.
+ */
+ get #incoming(): IncomingRequest {
+ return this.#request as IncomingRequest;
+ }
+
+ /**
+ * The initial request seen as the INVITE this UA sent. Only the paths
+ * that run on an outgoing call reach it.
+ */
+ get #outgoing(): SIPMessage.InitialOutgoingInviteRequest {
+ return this.#request as SIPMessage.InitialOutgoingInviteRequest;
+ }
+
+ #close(): void {
logger.debug('close()');
// Close local MediaStream if it was not given by the user.
- if (this._localMediaStream && this._localMediaStreamLocallyGenerated) {
+ if (this.#localMediaStream && this.#localMediaStreamLocallyGenerated) {
logger.debug('close() | closing local MediaStream');
- Utils.closeMediaStream(this._localMediaStream);
+ Utils.closeMediaStream(this.#localMediaStream);
}
- if (this._status === C.STATUS_TERMINATED) {
+ if (this.#status === Status.TERMINATED) {
return;
}
- this._status = C.STATUS_TERMINATED;
+ this.#status = Status.TERMINATED;
// Terminate RTC.
- if (this._connection) {
+ if (this.#connection) {
try {
- this._connection.close();
+ this.#connection.close();
} catch (error) {
logger.warn('close() | error closing the RTCPeerConnection: %o', error);
}
@@ -1639,35 +2153,33 @@ class RTCSession extends EventEmitter {
// Terminate signaling.
// Clear SIP timers.
- for (const timer in this._timers) {
- if (Object.prototype.hasOwnProperty.call(this._timers, timer)) {
- clearTimeout(this._timers[timer]);
- }
+ for (const timer of Object.values(this.#timers)) {
+ clearTimeout(timer ?? undefined);
}
// Clear Session Timers.
- clearTimeout(this._sessionTimers.timer);
+ clearTimeout(this.#sessionTimers.timer ?? undefined);
// Terminate confirmed dialog.
- if (this._dialog) {
- this._dialog.terminate();
- delete this._dialog;
+ if (this.#dialog) {
+ this.#dialog.terminate();
+ this.#dialog = null;
}
// Terminate early dialogs.
- for (const dialog in this._earlyDialogs) {
- if (Object.prototype.hasOwnProperty.call(this._earlyDialogs, dialog)) {
- this._earlyDialogs[dialog].terminate();
- delete this._earlyDialogs[dialog];
+ for (const dialog in this.#earlyDialogs) {
+ if (Object.prototype.hasOwnProperty.call(this.#earlyDialogs, dialog)) {
+ this.#earlyDialogs[dialog]!.terminate();
+ delete this.#earlyDialogs[dialog];
}
}
// Terminate REFER subscribers.
- for (const subscriber in this._referSubscribers) {
+ for (const subscriber in this.#referSubscribers) {
if (
- Object.prototype.hasOwnProperty.call(this._referSubscribers, subscriber)
+ Object.prototype.hasOwnProperty.call(this.#referSubscribers, subscriber)
) {
- delete this._referSubscribers[subscriber];
+ delete this.#referSubscribers[subscriber];
}
}
@@ -1683,15 +2195,15 @@ class RTCSession extends EventEmitter {
* Response retransmissions cannot be accomplished by transaction layer
* since it is destroyed when receiving the first 2xx answer
*/
- _setInvite2xxTimer(request, body) {
+ #setInvite2xxTimer(request: IncomingRequest, body?: string): void {
let timeout = Timers.T1;
- function invite2xxRetransmission() {
- if (this._status !== C.STATUS_WAITING_FOR_ACK) {
+ function invite2xxRetransmission(this: RTCSession): void {
+ if (this.#status !== Status.WAITING_FOR_ACK) {
return;
}
- request.reply(200, null, [`Contact: ${this._contact}`], body);
+ request.reply(200, null, [`Contact: ${this.#contact}`], body);
if (timeout < Timers.T2) {
timeout = timeout * 2;
@@ -1700,13 +2212,13 @@ class RTCSession extends EventEmitter {
}
}
- this._timers.invite2xxTimer = setTimeout(
+ this.#timers.invite2xxTimer = setTimeout(
invite2xxRetransmission.bind(this),
timeout
);
}
- this._timers.invite2xxTimer = setTimeout(
+ this.#timers.invite2xxTimer = setTimeout(
invite2xxRetransmission.bind(this),
timeout
);
@@ -1717,23 +2229,31 @@ class RTCSession extends EventEmitter {
* If a UAS generates a 2xx response and never receives an ACK,
* it SHOULD generate a BYE to terminate the dialog.
*/
- _setACKTimer() {
- this._timers.ackTimer = setTimeout(() => {
- if (this._status === C.STATUS_WAITING_FOR_ACK) {
+ #setACKTimer(): void {
+ this.#timers.ackTimer = setTimeout(() => {
+ if (this.#status === Status.WAITING_FOR_ACK) {
logger.debug('no ACK received, terminating the session');
- clearTimeout(this._timers.invite2xxTimer);
+ clearTimeout(this.#timers.invite2xxTimer ?? undefined);
this.sendRequest(JsSIP_C.BYE);
- this._ended('remote', null, JsSIP_C.causes.NO_ACK);
+ this.#ended('remote', null, JsSIP_C.causes.NO_ACK);
}
}, Timers.TIMER_H);
}
- _createRTCConnection(pcConfig, rtcConstraints) {
- this._connection = new RTCPeerConnection(pcConfig, rtcConstraints);
+ #createRTCConnection(
+ pcConfig: RTCConfiguration,
+ rtcConstraints: object | null
+ ): void {
+ // The second argument is the legacy constraints form, which the
+ // current typings no longer carry.
+ this.#connection = new (RTCPeerConnection as unknown as new (
+ config?: RTCConfiguration,
+ constraints?: object | null
+ ) => RTCPeerConnectionDeprecated)(pcConfig, rtcConstraints);
- this._connection.addEventListener('iceconnectionstatechange', () => {
- const state = this._connection.iceConnectionState;
+ this.#connection.addEventListener('iceconnectionstatechange', () => {
+ const state = this.#connection!.iceConnectionState;
// TODO: Do more with different states.
if (state === 'failed') {
@@ -1748,53 +2268,60 @@ class RTCSession extends EventEmitter {
logger.debug('emit "peerconnection"');
this.emit('peerconnection', {
- peerconnection: this._connection,
+ peerconnection: this.#connection,
});
}
- _createLocalDescription(type, constraints) {
+ #createLocalDescription(
+ type: 'offer' | 'answer',
+ constraints: RTCOfferOptions | null
+ ): Promise<string> {
logger.debug('createLocalDescription()');
if (type !== 'offer' && type !== 'answer') {
throw new Error(`createLocalDescription() | invalid type "${type}"`);
}
- const connection = this._connection;
+ const connection = this.#connection!;
- this._rtcReady = false;
+ this.#rtcReady = false;
return (
Promise.resolve()
// Create Offer or Answer.
.then(() => {
if (type === 'offer') {
- return connection.createOffer(constraints).catch(error => {
- logger.warn(
- 'emit "peerconnection:createofferfailed" [error:%o]',
- error
- );
+ return connection
+ .createOffer(constraints ?? undefined)
+ .catch(error => {
+ logger.warn(
+ 'emit "peerconnection:createofferfailed" [error:%o]',
+ error
+ );
- this.emit('peerconnection:createofferfailed', error);
+ this.emit('peerconnection:createofferfailed', error);
- return Promise.reject(error);
- });
+ return Promise.reject(error as Error);
+ });
} else {
- return connection.createAnswer(constraints).catch(error => {
- logger.warn(
- 'emit "peerconnection:createanswerfailed" [error:%o]',
- error
- );
+ return connection
+ .createAnswer(constraints ?? undefined)
+ .catch(error => {
+ logger.warn(
+ 'emit "peerconnection:createanswerfailed" [error:%o]',
+ error
+ );
- this.emit('peerconnection:createanswerfailed', error);
+ this.emit('peerconnection:createanswerfailed', error);
- return Promise.reject(error);
- });
+ return Promise.reject(error as Error);
+ });
}
})
// Set local description.
.then(desc => {
return connection.setLocalDescription(desc).catch(error => {
- this._rtcReady = true;
+ this.#rtcReady = true;
logger.warn(
'emit "peerconnection:setlocaldescriptionfailed" [error:%o]',
@@ -1803,7 +2330,7 @@ class RTCSession extends EventEmitter {
this.emit('peerconnection:setlocaldescriptionfailed', error);
- return Promise.reject(error);
+ return Promise.reject(error as Error);
});
})
.then(() => {
@@ -1813,18 +2340,18 @@ class RTCSession extends EventEmitter {
* - 'connection.iceGatheringState' is 'complete' and no 'iceRestart' constraint is set.
* - 'connection.iceGatheringState' is 'gathering' and 'iceReady' is true.
*/
- const iceRestart = constraints && constraints.iceRestart;
+ const iceRestart = constraints?.iceRestart;
if (
(connection.iceGatheringState === 'complete' && !iceRestart) ||
- (connection.iceGatheringState === 'gathering' && this._iceReady)
+ (connection.iceGatheringState === 'gathering' && this.#iceReady)
) {
- this._rtcReady = true;
+ this.#rtcReady = true;
- const e = {
+ const e: SDPEvent = {
originator: 'local',
type: type,
- sdp: connection.localDescription.sdp,
+ sdp: connection.localDescription!.sdp,
};
logger.debug('emit "sdp"');
@@ -1837,12 +2364,12 @@ class RTCSession extends EventEmitter {
// Add 'pc.onicencandidate' event handler to resolve on last candidate.
return new Promise(resolve => {
let finished = false;
- let iceCandidateListener;
- let iceGatheringStateListener;
+ let iceCandidateListener: (event: Event) => void;
+ let iceGatheringStateListener: () => void;
- this._iceReady = false;
+ this.#iceReady = false;
- const ready = () => {
+ const ready = (): void => {
if (finished) {
return;
}
@@ -1857,15 +2384,15 @@ class RTCSession extends EventEmitter {
);
finished = true;
- this._rtcReady = true;
+ this.#rtcReady = true;
// connection.iceGatheringState will still indicate 'gathering' and thus be blocking.
- this._iceReady = true;
+ this.#iceReady = true;
- const e = {
+ const e: SDPEvent = {
originator: 'local',
type: type,
- sdp: connection.localDescription.sdp,
+ sdp: connection.localDescription!.sdp,
};
logger.debug('emit "sdp"');
@@ -1878,7 +2405,8 @@ class RTCSession extends EventEmitter {
connection.addEventListener(
'icecandidate',
(iceCandidateListener = event => {
- const candidate = event.candidate;
+ const candidate = (event as RTCPeerConnectionIceEvent)
+ .candidate;
if (candidate) {
this.emit('icecandidate', {
@@ -1907,12 +2435,16 @@ class RTCSession extends EventEmitter {
/**
* Dialog Management
*/
- _createDialog(message, type, early) {
+ #createDialog(
+ message: SIPMessage.IncomingMessage,
+ type: DialogType,
+ early?: boolean
+ ): boolean {
const local_tag = type === 'UAS' ? message.to_tag : message.from_tag;
const remote_tag = type === 'UAS' ? message.from_tag : message.to_tag;
- const id = message.call_id + local_tag + remote_tag;
+ const id = `${message.call_id}${local_tag}${remote_tag}`;
- let early_dialog = this._earlyDialogs[id];
+ let early_dialog = this.#earlyDialogs[id];
// Early Dialog.
if (early) {
@@ -1922,13 +2454,17 @@ class RTCSession extends EventEmitter {
try {
early_dialog = Dialog.Create(this, message, type, DialogStatus.EARLY);
} catch {
- this._failed('remote', message, JsSIP_C.causes.INTERNAL_ERROR);
+ this.#failed(
+ 'remote',
+ message as IncomingRequest | IncomingResponse,
+ JsSIP_C.causes.INTERNAL_ERROR
+ );
return false;
}
// Dialog has been successfully created.
- this._earlyDialogs[id] = early_dialog;
+ this.#earlyDialogs[id] = early_dialog;
return true;
}
@@ -1936,14 +2472,14 @@ class RTCSession extends EventEmitter {
// Confirmed Dialog.
else {
- this._from_tag = message.from_tag;
- this._to_tag = message.to_tag;
+ this.#from_tag = message.from_tag ?? null;
+ this.#to_tag = message.to_tag ?? null;
// In case the dialog is in _early_ state, update it.
if (early_dialog) {
early_dialog.update(message, type);
- this._dialog = early_dialog;
- delete this._earlyDialogs[id];
+ this.#dialog = early_dialog;
+ delete this.#earlyDialogs[id];
return true;
}
@@ -1954,12 +2490,16 @@ class RTCSession extends EventEmitter {
try {
dialog = Dialog.Create(this, message, type);
} catch {
- this._failed('remote', message, JsSIP_C.causes.INTERNAL_ERROR);
+ this.#failed(
+ 'remote',
+ message as IncomingRequest | IncomingResponse,
+ JsSIP_C.causes.INTERNAL_ERROR
+ );
return false;
}
- this._dialog = dialog;
+ this.#dialog = dialog;
return true;
}
@@ -1969,13 +2509,13 @@ class RTCSession extends EventEmitter {
* In dialog INVITE Reception
*/
- _receiveReinvite(request) {
+ #receiveReinvite(request: IncomingRequest): void {
logger.debug('receiveReinvite()');
const contentType = request.hasHeader('Content-Type')
- ? request.getHeader('Content-Type').toLowerCase()
+ ? request.getHeader('Content-Type')!.toLowerCase()
: undefined;
- const data = {
+ const data: ReInviteEvent = {
request,
callback: undefined,
reject: reject.bind(this),
@@ -1983,14 +2523,17 @@ class RTCSession extends EventEmitter {
let rejected = false;
- function reject(options = {}) {
+ function reject(
+ this: RTCSession,
+ options: RejectOptions = {}
+ ): false | void {
rejected = true;
const status_code = options.status_code || 403;
const reason_phrase = options.reason_phrase || '';
const extraHeaders = Utils.cloneArray(options.extraHeaders);
- if (this._status !== C.STATUS_CONFIRMED) {
+ if (this.#status !== Status.CONFIRMED) {
return false;
}
@@ -2008,18 +2551,18 @@ class RTCSession extends EventEmitter {
return;
}
- this._late_sdp = false;
+ this.#late_sdp = false;
// Request without SDP.
if (!request.body) {
- this._late_sdp = true;
- if (this._remoteHold) {
- this._remoteHold = false;
- this._onunhold('remote');
+ this.#late_sdp = true;
+ if (this.#remoteHold) {
+ this.#remoteHold = false;
+ this.#onunhold('remote');
}
- this._connectionPromiseQueue = this._connectionPromiseQueue
+ this.#connectionPromiseQueue = this.#connectionPromiseQueue
.then(() =>
- this._createLocalDescription('offer', this._rtcOfferConstraints)
+ this.#createLocalDescription('offer', this.#rtcOfferConstraints)
)
.then(sdp => {
sendAnswer.call(this, sdp);
@@ -2039,32 +2582,32 @@ class RTCSession extends EventEmitter {
return;
}
- this._processInDialogSdpOffer(request)
+ this.#processInDialogSdpOffer(request)
// Send answer.
.then(desc => {
- if (this._status === C.STATUS_TERMINATED) {
+ if (this.#status === Status.TERMINATED) {
return;
}
- sendAnswer.call(this, desc);
+ sendAnswer.call(this, desc as string);
})
.catch(error => {
logger.warn(error);
});
- function sendAnswer(desc) {
- const extraHeaders = [`Contact: ${this._contact}`];
+ function sendAnswer(this: RTCSession, desc: string): void {
+ const extraHeaders = [`Contact: ${this.#contact}`];
- this._handleSessionTimersInIncomingRequest(request, extraHeaders);
+ this.#handleSessionTimersInIncomingRequest(request, extraHeaders);
- if (this._late_sdp) {
- desc = this._mangleOffer(desc);
+ if (this.#late_sdp) {
+ desc = this.#mangleOffer(desc);
}
request.reply(200, null, extraHeaders, desc, () => {
- this._status = C.STATUS_WAITING_FOR_ACK;
- this._setInvite2xxTimer(request, desc);
- this._setACKTimer();
+ this.#status = Status.WAITING_FOR_ACK;
+ this.#setInvite2xxTimer(request, desc);
+ this.#setACKTimer();
});
// If callback is given execute it.
@@ -2077,13 +2620,13 @@ class RTCSession extends EventEmitter {
/**
* In dialog UPDATE Reception
*/
- _receiveUpdate(request) {
+ #receiveUpdate(request: IncomingRequest): void {
logger.debug('receiveUpdate()');
const contentType = request.hasHeader('Content-Type')
- ? request.getHeader('Content-Type').toLowerCase()
+ ? request.getHeader('Content-Type')!.toLowerCase()
: undefined;
- const data = {
+ const data: ReInviteEvent = {
request,
callback: undefined,
reject: reject.bind(this),
@@ -2091,14 +2634,17 @@ class RTCSession extends EventEmitter {
let rejected = false;
- function reject(options = {}) {
+ function reject(
+ this: RTCSession,
+ options: RejectOptions = {}
+ ): false | void {
rejected = true;
const status_code = options.status_code || 403;
const reason_phrase = options.reason_phrase || '';
const extraHeaders = Utils.cloneArray(options.extraHeaders);
- if (this._status !== C.STATUS_CONFIRMED) {
+ if (this.#status !== Status.CONFIRMED) {
return false;
}
@@ -2117,7 +2663,7 @@ class RTCSession extends EventEmitter {
}
if (!request.body) {
- sendAnswer.call(this, null);
+ sendAnswer.call(this, null as unknown as string);
return;
}
@@ -2130,23 +2676,23 @@ class RTCSession extends EventEmitter {
return;
}
- this._processInDialogSdpOffer(request)
+ this.#processInDialogSdpOffer(request)
// Send answer.
.then(desc => {
- if (this._status === C.STATUS_TERMINATED) {
+ if (this.#status === Status.TERMINATED) {
return;
}
- sendAnswer.call(this, desc);
+ sendAnswer.call(this, desc as string);
})
.catch(error => {
logger.warn(error);
});
- function sendAnswer(desc) {
- const extraHeaders = [`Contact: ${this._contact}`];
+ function sendAnswer(this: RTCSession, desc: string): void {
+ const extraHeaders = [`Contact: ${this.#contact}`];
- this._handleSessionTimersInIncomingRequest(request, extraHeaders);
+ this.#handleSessionTimersInIncomingRequest(request, extraHeaders);
request.reply(200, null, extraHeaders, desc);
@@ -2157,7 +2703,7 @@ class RTCSession extends EventEmitter {
}
}
- _processInDialogSdpOffer(request) {
+ #processInDialogSdpOffer(request: IncomingRequest): Promise<unknown> {
logger.debug('_processInDialogSdpOffer()');
const sdp = request.parseSDP();
@@ -2165,7 +2711,7 @@ class RTCSession extends EventEmitter {
let hold = false;
for (const m of sdp.media) {
- if (holdMediaTypes.indexOf(m.type) === -1) {
+ if (!holdMediaTypes.includes(m.type)) {
continue;
}
@@ -2181,21 +2727,25 @@ class RTCSession extends EventEmitter {
}
}
- const e = { originator: 'remote', type: 'offer', sdp: request.body };
+ const e: SDPEvent = {
+ originator: 'remote',
+ type: 'offer',
+ sdp: request.body,
+ };
logger.debug('emit "sdp"');
this.emit('sdp', e);
const offer = new RTCSessionDescription({ type: 'offer', sdp: e.sdp });
- this._connectionPromiseQueue = this._connectionPromiseQueue
+ this.#connectionPromiseQueue = this.#connectionPromiseQueue
// Set remote description.
.then(() => {
- if (this._status === C.STATUS_TERMINATED) {
+ if (this.#status === Status.TERMINATED) {
throw new Error('terminated');
}
- return this._connection.setRemoteDescription(offer).catch(error => {
+ return this.#connection!.setRemoteDescription(offer).catch(error => {
request.reply(488);
logger.warn(
'emit "peerconnection:setremotedescriptionfailed" [error:%o]',
@@ -2208,27 +2758,27 @@ class RTCSession extends EventEmitter {
});
})
.then(() => {
- if (this._status === C.STATUS_TERMINATED) {
+ if (this.#status === Status.TERMINATED) {
throw new Error('terminated');
}
- if (this._remoteHold === true && hold === false) {
- this._remoteHold = false;
- this._onunhold('remote');
- } else if (this._remoteHold === false && hold === true) {
- this._remoteHold = true;
- this._onhold('remote');
+ if (this.#remoteHold === true && hold === false) {
+ this.#remoteHold = false;
+ this.#onunhold('remote');
+ } else if (this.#remoteHold === false && hold === true) {
+ this.#remoteHold = true;
+ this.#onhold('remote');
}
})
// Create local description.
.then(() => {
- if (this._status === C.STATUS_TERMINATED) {
+ if (this.#status === Status.TERMINATED) {
throw new Error('terminated');
}
- return this._createLocalDescription(
+ return this.#createLocalDescription(
'answer',
- this._rtcAnswerConstraints
+ this.#rtcAnswerConstraints
).catch(error => {
request.reply(500);
logger.warn(
@@ -2243,13 +2793,13 @@ class RTCSession extends EventEmitter {
logger.warn('_processInDialogSdpOffer() failed [error: %o]', error);
});
- return this._connectionPromiseQueue;
+ return this.#connectionPromiseQueue;
}
/**
* In dialog Refer Reception
*/
- _receiveRefer(request) {
+ #receiveRefer(request: IncomingRequest): void {
logger.debug('receiveRefer()');
if (!request.refer_to) {
@@ -2269,7 +2819,7 @@ class RTCSession extends EventEmitter {
// Reply before the transaction timer expires.
request.reply(202);
- const notifier = new RTCSession_ReferNotifier(this, request.cseq);
+ const notifier = new RTCSession_ReferNotifier(this, request.cseq!);
logger.debug('emit "refer"');
@@ -2284,12 +2834,17 @@ class RTCSession extends EventEmitter {
},
});
- function accept(initCallback, options = {}) {
- initCallback = typeof initCallback === 'function' ? initCallback : null;
+ function accept(
+ this: RTCSession,
+ initCallback?: InitCallback,
+ options: AnswerOptions = {}
+ ): false | void {
+ initCallback =
+ typeof initCallback === 'function' ? initCallback : undefined;
if (
- this._status !== C.STATUS_WAITING_FOR_ACK &&
- this._status !== C.STATUS_CONFIRMED
+ this.#status !== Status.WAITING_FOR_ACK &&
+ this.#status !== Status.CONFIRMED
) {
return false;
}
@@ -2297,38 +2852,41 @@ class RTCSession extends EventEmitter {
const session = new RTCSession(this.ua);
session.on('progress', ({ response }) => {
- notifier.notify(response.status_code, response.reason_phrase);
+ notifier.notify(response!.status_code, response!.reason_phrase);
});
session.on('accepted', ({ response }) => {
- notifier.notify(response.status_code, response.reason_phrase);
+ notifier.notify(response!.status_code, response!.reason_phrase);
});
session.on('_failed', ({ message, cause }) => {
if (message) {
- notifier.notify(message.status_code, message.reason_phrase);
+ notifier.notify(
+ (message as IncomingResponse).status_code,
+ (message as IncomingResponse).reason_phrase
+ );
} else {
notifier.notify(487, cause);
}
});
// Consider the Replaces header present in the Refer-To URI.
- if (request.refer_to.uri.hasHeader('replaces')) {
+ if (request.refer_to!.uri.hasHeader('replaces')) {
const replaces = decodeURIComponent(
- request.refer_to.uri.getHeader('replaces')
+ String(request.refer_to!.uri.getHeader('replaces'))
);
options.extraHeaders = Utils.cloneArray(options.extraHeaders);
options.extraHeaders.push(`Replaces: ${replaces}`);
}
- const target_uri = request.refer_to.uri.clone();
+ const target_uri = request.refer_to!.uri.clone();
target_uri.clearHeaders();
session.connect(target_uri, options, initCallback);
}
- function reject() {
+ function reject(this: RTCSession): void {
notifier.notify(603);
}
}
@@ -2336,24 +2894,26 @@ class RTCSession extends EventEmitter {
/**
* In dialog Notify Reception
*/
- _receiveNotify(request) {
+ #receiveNotify(request: IncomingRequest): void {
logger.debug('receiveNotify()');
if (!request.event) {
request.reply(400);
}
- switch (request.event.event) {
+ switch (request.event!.event) {
case 'refer': {
let id;
let referSubscriber;
- if (request.event.params && request.event.params.id) {
- id = request.event.params.id;
- referSubscriber = this._referSubscribers[id];
- } else if (Object.keys(this._referSubscribers).length === 1) {
+ if (request.event!.params?.['id']) {
+ id = Number(request.event!.params['id']);
+ referSubscriber = this.#referSubscribers[id];
+ } else if (Object.keys(this.#referSubscribers).length === 1) {
referSubscriber =
- this._referSubscribers[Object.keys(this._referSubscribers)[0]];
+ this.#referSubscribers[
+ Number(Object.keys(this.#referSubscribers)[0])
+ ];
} else {
request.reply(400, 'Missing event id parameter');
@@ -2381,13 +2941,16 @@ class RTCSession extends EventEmitter {
/**
* INVITE with Replaces Reception
*/
- _receiveReplaces(request) {
+ #receiveReplaces(request: IncomingRequest): void {
logger.debug('receiveReplaces()');
- function accept(initCallback) {
+ function accept(
+ this: RTCSession,
+ initCallback?: InitCallback
+ ): false | void {
if (
- this._status !== C.STATUS_WAITING_FOR_ACK &&
- this._status !== C.STATUS_CONFIRMED
+ this.#status !== Status.WAITING_FOR_ACK &&
+ this.#status !== Status.CONFIRMED
) {
return false;
}
@@ -2402,7 +2965,7 @@ class RTCSession extends EventEmitter {
session.init_incoming(request, initCallback);
}
- function reject() {
+ function reject(this: RTCSession): void {
logger.debug('Replaced INVITE rejected by the user');
request.reply(486);
}
@@ -2422,8 +2985,12 @@ class RTCSession extends EventEmitter {
/**
* Initial Request Sender
*/
- _sendInitialRequest(mediaConstraints, rtcOfferConstraints, mediaStream) {
- const request_sender = new RequestSender(this.ua, this._request, {
+ #sendInitialRequest(
+ mediaConstraints: MediaStreamConstraints,
+ rtcOfferConstraints: RTCOfferOptions | null,
+ mediaStream: MediaStream | null
+ ): void {
+ const request_sender = new RequestSender(this.ua, this.#outgoing, {
onRequestTimeout: () => {
this.onRequestTimeout();
},
@@ -2432,10 +2999,10 @@ class RTCSession extends EventEmitter {
},
// Update the request on authentication.
onAuthenticated: request => {
- this._request = request;
+ this.#request = request;
},
onReceiveResponse: response => {
- this._receiveInviteResponse(response);
+ this.#receiveInviteResponse(response);
},
});
@@ -2450,16 +3017,16 @@ class RTCSession extends EventEmitter {
}
// Request for user media access.
else if (mediaConstraints.audio || mediaConstraints.video) {
- this._localMediaStreamLocallyGenerated = true;
+ this.#localMediaStreamLocallyGenerated = true;
return navigator.mediaDevices
.getUserMedia(mediaConstraints)
.catch(error => {
- if (this._status === C.STATUS_TERMINATED) {
+ if (this.#status === Status.TERMINATED) {
throw new Error('terminated');
}
- this._failed(
+ this.#failed(
'local',
null,
JsSIP_C.causes.USER_DENIED_MEDIA_ACCESS
@@ -2472,50 +3039,53 @@ class RTCSession extends EventEmitter {
throw error;
});
}
+
+ // No media was asked for and none was given.
+ return undefined;
})
.then(stream => {
- if (this._status === C.STATUS_TERMINATED) {
+ if (this.#status === Status.TERMINATED) {
throw new Error('terminated');
}
- this._localMediaStream = stream;
+ this.#localMediaStream = stream ?? null;
if (stream) {
stream.getTracks().forEach(track => {
- this._connection.addTrack(track, stream);
+ this.#connection!.addTrack(track, stream);
});
}
// TODO: should this be triggered here?
- this._connecting(this._request);
+ this.#connecting(this.#request!);
- return this._createLocalDescription('offer', rtcOfferConstraints).catch(
+ return this.#createLocalDescription('offer', rtcOfferConstraints).catch(
error => {
- this._failed('local', null, JsSIP_C.causes.WEBRTC_ERROR);
+ this.#failed('local', null, JsSIP_C.causes.WEBRTC_ERROR);
throw error;
}
);
})
.then(desc => {
- if (this._is_canceled || this._status === C.STATUS_TERMINATED) {
+ if (this.#is_canceled || this.#status === Status.TERMINATED) {
throw new Error('terminated');
}
- this._request.body = desc;
- this._status = C.STATUS_INVITE_SENT;
+ this.#request!.body = desc;
+ this.#status = Status.INVITE_SENT;
- logger.debug('emit "sending" [request:%o]', this._request);
+ logger.debug('emit "sending" [request:%o]', this.#request);
// Emit 'sending' so the app can mangle the body before the request is sent.
this.emit('sending', {
- request: this._request,
+ request: this.#outgoing,
});
request_sender.send();
})
.catch(error => {
- if (this._status === C.STATUS_TERMINATED) {
+ if (this.#status === Status.TERMINATED) {
return;
}
@@ -2526,12 +3096,12 @@ class RTCSession extends EventEmitter {
/**
* Get DTMF RTCRtpSender.
*/
- _getDTMFRTPSender() {
- const sender = this._connection.getSenders().find(rtpSender => {
- return rtpSender.track && rtpSender.track.kind === 'audio';
+ #getDTMFRTPSender(): RTCDTMFSender | undefined {
+ const sender = this.#connection!.getSenders().find(rtpSender => {
+ return rtpSender.track?.kind === 'audio';
});
- if (!(sender && sender.dtmf)) {
+ if (!sender?.dtmf) {
logger.warn('sendDTMF() | no local audio track to send DTMF with');
return;
@@ -2543,21 +3113,21 @@ class RTCSession extends EventEmitter {
/**
* Reception of Response for Initial INVITE
*/
- _receiveInviteResponse(response) {
+ #receiveInviteResponse(response: IncomingResponse): void {
logger.debug('receiveInviteResponse()');
// Handle 2XX retransmissions and responses from forked requests.
if (
- this._dialog &&
+ this.#dialog &&
response.status_code >= 200 &&
response.status_code <= 299
) {
// If it is a retransmission from the endpoint that established
// the dialog, send an ACK
if (
- this._dialog.id.call_id === response.call_id &&
- this._dialog.id.local_tag === response.from_tag &&
- this._dialog.id.remote_tag === response.to_tag
+ this.#dialog.id.call_id === response.call_id &&
+ this.#dialog.id.local_tag === response.from_tag &&
+ this.#dialog.id.remote_tag === response.to_tag
) {
this.sendRequest(JsSIP_C.ACK);
@@ -2580,29 +3150,29 @@ class RTCSession extends EventEmitter {
}
// Proceed to cancellation if the user requested.
- if (this._is_canceled) {
+ if (this.#is_canceled) {
if (response.status_code >= 100 && response.status_code < 200) {
- this._request.cancel(this._cancel_reason);
+ this.#outgoing.cancel(this.#cancel_reason);
} else if (response.status_code >= 200 && response.status_code < 299) {
- this._acceptAndTerminate(response);
+ this.#acceptAndTerminate(response);
}
return;
}
if (
- this._status !== C.STATUS_INVITE_SENT &&
- this._status !== C.STATUS_1XX_RECEIVED
+ this.#status !== Status.INVITE_SENT &&
+ this.#status !== Status.PROVISIONAL_RESPONSE_RECEIVED
) {
return;
}
switch (true) {
- case /^100$/.test(response.status_code): {
- this._status = C.STATUS_1XX_RECEIVED;
+ case /^100$/.test(String(response.status_code)): {
+ this.#status = Status.PROVISIONAL_RESPONSE_RECEIVED;
break;
}
- case /^1[0-9]{2}$/.test(response.status_code): {
+ case /^1[0-9]{2}$/.test(String(response.status_code)): {
// Do nothing with 1xx responses without To tag.
if (!response.to_tag) {
logger.debug('1xx response received without to tag');
@@ -2612,19 +3182,23 @@ class RTCSession extends EventEmitter {
// Create Early Dialog if 1XX comes with contact.
if (response.hasHeader('contact')) {
// An error on dialog creation will fire 'failed' event.
- if (!this._createDialog(response, 'UAC', true)) {
+ if (!this.#createDialog(response, 'UAC', true)) {
break;
}
}
- this._status = C.STATUS_1XX_RECEIVED;
+ this.#status = Status.PROVISIONAL_RESPONSE_RECEIVED;
if (!response.body) {
- this._progress('remote', response);
+ this.#progress('remote', response);
break;
}
- const e = { originator: 'remote', type: 'answer', sdp: response.body };
+ const e: SDPEvent = {
+ originator: 'remote',
+ type: 'answer',
+ sdp: response.body,
+ };
logger.debug('emit "sdp"');
this.emit('sdp', e);
@@ -2634,9 +3208,9 @@ class RTCSession extends EventEmitter {
sdp: e.sdp,
});
- this._connectionPromiseQueue = this._connectionPromiseQueue
- .then(() => this._connection.setRemoteDescription(answer))
- .then(() => this._progress('remote', response))
+ this.#connectionPromiseQueue = this.#connectionPromiseQueue
+ .then(() => this.#connection!.setRemoteDescription(answer))
+ .then(() => this.#progress('remote', response))
.catch(error => {
logger.warn(
'emit "peerconnection:setremotedescriptionfailed" [error:%o]',
@@ -2648,12 +3222,12 @@ class RTCSession extends EventEmitter {
break;
}
- case /^2[0-9]{2}$/.test(response.status_code): {
- this._status = C.STATUS_CONFIRMED;
+ case /^2[0-9]{2}$/.test(String(response.status_code)): {
+ this.#status = Status.CONFIRMED;
if (!response.body) {
- this._acceptAndTerminate(response, 400, JsSIP_C.causes.MISSING_SDP);
- this._failed(
+ this.#acceptAndTerminate(response, 400, JsSIP_C.causes.MISSING_SDP);
+ this.#failed(
'remote',
response,
JsSIP_C.causes.BAD_MEDIA_DESCRIPTION
@@ -2662,11 +3236,15 @@ class RTCSession extends EventEmitter {
}
// An error on dialog creation will fire 'failed' event.
- if (!this._createDialog(response, 'UAC')) {
+ if (!this.#createDialog(response, 'UAC')) {
break;
}
- const e = { originator: 'remote', type: 'answer', sdp: response.body };
+ const e: SDPEvent = {
+ originator: 'remote',
+ type: 'answer',
+ sdp: response.body,
+ };
logger.debug('emit "sdp"');
this.emit('sdp', e);
@@ -2676,34 +3254,36 @@ class RTCSession extends EventEmitter {
sdp: e.sdp,
});
- this._connectionPromiseQueue = this._connectionPromiseQueue
+ this.#connectionPromiseQueue = this.#connectionPromiseQueue
.then(() => {
// Be ready for 200 with SDP after a 180/183 with SDP.
// We created a SDP 'answer' for it, so check the current signaling state.
- if (this._connection.signalingState === 'stable') {
- return this._connection
- .createOffer(this._rtcOfferConstraints)
- .then(offer => this._connection.setLocalDescription(offer))
+ if (this.#connection!.signalingState === 'stable') {
+ return this.#connection!.createOffer(
+ this.#rtcOfferConstraints ?? undefined
+ )
+ .then(offer => this.#connection!.setLocalDescription(offer))
.catch(error => {
- this._acceptAndTerminate(response, 500, error.toString());
- this._failed('local', response, JsSIP_C.causes.WEBRTC_ERROR);
+ this.#acceptAndTerminate(response, 500, error.toString());
+ this.#failed('local', response, JsSIP_C.causes.WEBRTC_ERROR);
});
}
+
+ return undefined;
})
.then(() => {
- this._connection
- .setRemoteDescription(answer)
+ this.#connection!.setRemoteDescription(answer)
.then(() => {
// Handle Session Timers.
- this._handleSessionTimersInIncomingResponse(response);
+ this.#handleSessionTimersInIncomingResponse(response);
- this._accepted('remote', response);
+ this.#accepted('remote', response);
this.sendRequest(JsSIP_C.ACK);
- this._confirmed('local', null);
+ this.#confirmed('local', null);
})
.catch(error => {
- this._acceptAndTerminate(response, 488, 'Not Acceptable Here');
- this._failed(
+ this.#acceptAndTerminate(response, 488, 'Not Acceptable Here');
+ this.#failed(
'remote',
response,
JsSIP_C.causes.BAD_MEDIA_DESCRIPTION
@@ -2723,7 +3303,7 @@ class RTCSession extends EventEmitter {
default: {
const cause = Utils.sipErrorCause(response.status_code);
- this._failed('remote', response, cause);
+ this.#failed('remote', response, cause);
}
}
}
@@ -2731,32 +3311,32 @@ class RTCSession extends EventEmitter {
/**
* Send Re-INVITE
*/
- _sendReinvite(options = {}) {
+ #sendReinvite(options: ReofferOptions = {}): void {
logger.debug('sendReinvite()');
const extraHeaders = Utils.cloneArray(options.extraHeaders);
const eventHandlers = Utils.cloneObject(options.eventHandlers);
const rtcOfferConstraints =
- options.rtcOfferConstraints || this._rtcOfferConstraints || null;
+ options.rtcOfferConstraints || this.#rtcOfferConstraints || null;
let succeeded = false;
- extraHeaders.push(`Contact: ${this._contact}`);
+ extraHeaders.push(`Contact: ${this.#contact}`);
extraHeaders.push('Content-Type: application/sdp');
// Session Timers.
- if (this._sessionTimers.running) {
+ if (this.#sessionTimers.running) {
extraHeaders.push(
- `Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher ? 'uac' : 'uas'}`
+ `Session-Expires: ${this.#sessionTimers.currentExpires};refresher=${this.#sessionTimers.refresher ? 'uac' : 'uas'}`
);
}
- this._connectionPromiseQueue = this._connectionPromiseQueue
- .then(() => this._createLocalDescription('offer', rtcOfferConstraints))
+ this.#connectionPromiseQueue = this.#connectionPromiseQueue
+ .then(() => this.#createLocalDescription('offer', rtcOfferConstraints))
.then(sdp => {
- sdp = this._mangleOffer(sdp);
+ sdp = this.#mangleOffer(sdp);
- const e = { originator: 'local', type: 'offer', sdp };
+ const e: SDPEvent = { originator: 'local', type: 'offer', sdp };
logger.debug('emit "sdp"');
this.emit('sdp', e);
@@ -2785,11 +3365,11 @@ class RTCSession extends EventEmitter {
});
})
.catch(() => {
- onFailed();
+ onFailed.call(this);
});
- function onSucceeded(response) {
- if (this._status === C.STATUS_TERMINATED) {
+ function onSucceeded(this: RTCSession, response: IncomingResponse): void {
+ if (this.#status === Status.TERMINATED) {
return;
}
@@ -2801,7 +3381,7 @@ class RTCSession extends EventEmitter {
}
// Handle Session Timers.
- this._handleSessionTimersInIncomingResponse(response);
+ this.#handleSessionTimersInIncomingResponse(response);
// Must have SDP answer.
if (!response.body) {
@@ -2810,22 +3390,26 @@ class RTCSession extends EventEmitter {
return;
} else if (
!response.hasHeader('Content-Type') ||
- response.getHeader('Content-Type').toLowerCase() !== 'application/sdp'
+ response.getHeader('Content-Type')!.toLowerCase() !== 'application/sdp'
) {
onFailed.call(this);
return;
}
- const e = { originator: 'remote', type: 'answer', sdp: response.body };
+ const e: SDPEvent = {
+ originator: 'remote',
+ type: 'answer',
+ sdp: response.body,
+ };
logger.debug('emit "sdp"');
this.emit('sdp', e);
const answer = new RTCSessionDescription({ type: 'answer', sdp: e.sdp });
- this._connectionPromiseQueue = this._connectionPromiseQueue
- .then(() => this._connection.setRemoteDescription(answer))
+ this.#connectionPromiseQueue = this.#connectionPromiseQueue
+ .then(() => this.#connection!.setRemoteDescription(answer))
.then(() => {
if (eventHandlers.succeeded) {
eventHandlers.succeeded(response);
@@ -2843,7 +3427,7 @@ class RTCSession extends EventEmitter {
});
}
- function onFailed(response) {
+ function onFailed(this: RTCSession, response?: IncomingResponse): void {
if (eventHandlers.failed) {
eventHandlers.failed(response);
}
@@ -2853,35 +3437,35 @@ class RTCSession extends EventEmitter {
/**
* Send UPDATE
*/
- _sendUpdate(options = {}) {
+ #sendUpdate(options: ReofferOptions = {}): void {
logger.debug('sendUpdate()');
const extraHeaders = Utils.cloneArray(options.extraHeaders);
const eventHandlers = Utils.cloneObject(options.eventHandlers);
const rtcOfferConstraints =
- options.rtcOfferConstraints || this._rtcOfferConstraints || null;
+ options.rtcOfferConstraints || this.#rtcOfferConstraints || null;
const sdpOffer = options.sdpOffer || false;
let succeeded = false;
- extraHeaders.push(`Contact: ${this._contact}`);
+ extraHeaders.push(`Contact: ${this.#contact}`);
// Session Timers.
- if (this._sessionTimers.running) {
+ if (this.#sessionTimers.running) {
extraHeaders.push(
- `Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher ? 'uac' : 'uas'}`
+ `Session-Expires: ${this.#sessionTimers.currentExpires};refresher=${this.#sessionTimers.refresher ? 'uac' : 'uas'}`
);
}
if (sdpOffer) {
extraHeaders.push('Content-Type: application/sdp');
- this._connectionPromiseQueue = this._connectionPromiseQueue
- .then(() => this._createLocalDescription('offer', rtcOfferConstraints))
+ this.#connectionPromiseQueue = this.#connectionPromiseQueue
+ .then(() => this.#createLocalDescription('offer', rtcOfferConstraints))
.then(sdp => {
- sdp = this._mangleOffer(sdp);
+ sdp = this.#mangleOffer(sdp);
- const e = { originator: 'local', type: 'offer', sdp };
+ const e: SDPEvent = { originator: 'local', type: 'offer', sdp };
logger.debug('emit "sdp"');
this.emit('sdp', e);
@@ -2938,8 +3522,8 @@ class RTCSession extends EventEmitter {
});
}
- function onSucceeded(response) {
- if (this._status === C.STATUS_TERMINATED) {
+ function onSucceeded(this: RTCSession, response: IncomingResponse): void {
+ if (this.#status === Status.TERMINATED) {
return;
}
@@ -2949,7 +3533,7 @@ class RTCSession extends EventEmitter {
}
// Handle Session Timers.
- this._handleSessionTimersInIncomingResponse(response);
+ this.#handleSessionTimersInIncomingResponse(response);
// Must have SDP answer.
if (sdpOffer) {
@@ -2959,14 +3543,19 @@ class RTCSession extends EventEmitter {
return;
} else if (
!response.hasHeader('Content-Type') ||
- response.getHeader('Content-Type').toLowerCase() !== 'application/sdp'
+ response.getHeader('Content-Type')!.toLowerCase() !==
+ 'application/sdp'
) {
onFailed.call(this);
return;
}
- const e = { originator: 'remote', type: 'answer', sdp: response.body };
+ const e: SDPEvent = {
+ originator: 'remote',
+ type: 'answer',
+ sdp: response.body,
+ };
logger.debug('emit "sdp"');
this.emit('sdp', e);
@@ -2976,8 +3565,8 @@ class RTCSession extends EventEmitter {
sdp: e.sdp,
});
- this._connectionPromiseQueue = this._connectionPromiseQueue
- .then(() => this._connection.setRemoteDescription(answer))
+ this.#connectionPromiseQueue = this.#connectionPromiseQueue
+ .then(() => this.#connection!.setRemoteDescription(answer))
.then(() => {
if (eventHandlers.succeeded) {
eventHandlers.succeeded(response);
@@ -3000,14 +3589,18 @@ class RTCSession extends EventEmitter {
}
}
- function onFailed(response) {
+ function onFailed(this: RTCSession, response?: IncomingResponse): void {
if (eventHandlers.failed) {
eventHandlers.failed(response);
}
}
}
- _acceptAndTerminate(response, status_code, reason_phrase) {
+ #acceptAndTerminate(
+ response: IncomingResponse,
+ status_code?: number,
+ reason_phrase?: string
+ ): void {
logger.debug('acceptAndTerminate()');
const extraHeaders = [];
@@ -3020,7 +3613,7 @@ class RTCSession extends EventEmitter {
}
// An error on dialog creation will fire 'failed' event.
- if (this._dialog || this._createDialog(response, 'UAC')) {
+ if (this.#dialog || this.#createDialog(response, 'UAC')) {
this.sendRequest(JsSIP_C.ACK);
this.sendRequest(JsSIP_C.BYE, {
extraHeaders,
@@ -3028,24 +3621,24 @@ class RTCSession extends EventEmitter {
}
// Update session status.
- this._status = C.STATUS_TERMINATED;
+ this.#status = Status.TERMINATED;
}
/**
* Correctly set the SDP direction attributes if the call is on local hold
*/
- _mangleOffer(sdp) {
- if (!this._localHold && !this._remoteHold) {
+ #mangleOffer(sdp: string): string {
+ if (!this.#localHold && !this.#remoteHold) {
return sdp;
}
- sdp = sdp_transform.parse(sdp);
+ const parsed = sdp_transform.parse(sdp);
// Local hold.
- if (this._localHold && !this._remoteHold) {
+ if (this.#localHold && !this.#remoteHold) {
logger.debug('mangleOffer() | me on hold, mangling offer');
- for (const m of sdp.media) {
- if (holdMediaTypes.indexOf(m.type) === -1) {
+ for (const m of parsed.media) {
+ if (!holdMediaTypes.includes(m.type)) {
continue;
}
if (!m.direction) {
@@ -3058,20 +3651,20 @@ class RTCSession extends EventEmitter {
}
}
// Local and remote hold.
- else if (this._localHold && this._remoteHold) {
+ else if (this.#localHold && this.#remoteHold) {
logger.debug('mangleOffer() | both on hold, mangling offer');
- for (const m of sdp.media) {
- if (holdMediaTypes.indexOf(m.type) === -1) {
+ for (const m of parsed.media) {
+ if (!holdMediaTypes.includes(m.type)) {
continue;
}
m.direction = 'inactive';
}
}
// Remote hold.
- else if (this._remoteHold) {
+ else if (this.#remoteHold) {
logger.debug('mangleOffer() | remote on hold, mangling offer');
- for (const m of sdp.media) {
- if (holdMediaTypes.indexOf(m.type) === -1) {
+ for (const m of parsed.media) {
+ if (!holdMediaTypes.includes(m.type)) {
continue;
}
if (!m.direction) {
@@ -3084,28 +3677,28 @@ class RTCSession extends EventEmitter {
}
}
- return sdp_transform.write(sdp);
+ return sdp_transform.write(parsed);
}
- _setLocalMediaStatus() {
+ #setLocalMediaStatus(): void {
let enableAudio = true,
enableVideo = true;
- if (this._localHold || this._remoteHold) {
+ if (this.#localHold || this.#remoteHold) {
enableAudio = false;
enableVideo = false;
}
- if (this._audioMuted) {
+ if (this.#audioMuted) {
enableAudio = false;
}
- if (this._videoMuted) {
+ if (this.#videoMuted) {
enableVideo = false;
}
- this._toggleMuteAudio(!enableAudio);
- this._toggleMuteVideo(!enableVideo);
+ this.#toggleMuteAudio(!enableAudio);
+ this.#toggleMuteVideo(!enableVideo);
}
/**
@@ -3113,8 +3706,11 @@ class RTCSession extends EventEmitter {
* @param {IncomingRequest} request
* @param {Array} responseExtraHeaders Extra headers for the 200 response.
*/
- _handleSessionTimersInIncomingRequest(request, responseExtraHeaders) {
- if (!this._sessionTimers.enabled) {
+ #handleSessionTimersInIncomingRequest(
+ request: IncomingRequest,
+ responseExtraHeaders: string[]
+ ): void {
+ if (!this.#sessionTimers.enabled) {
return;
}
@@ -3124,27 +3720,27 @@ class RTCSession extends EventEmitter {
request.session_expires &&
request.session_expires >= JsSIP_C.MIN_SESSION_EXPIRES
) {
- this._sessionTimers.currentExpires = request.session_expires;
+ this.#sessionTimers.currentExpires = request.session_expires;
session_expires_refresher = request.session_expires_refresher || 'uas';
} else {
- this._sessionTimers.currentExpires = this._sessionTimers.defaultExpires;
+ this.#sessionTimers.currentExpires = this.#sessionTimers.defaultExpires;
session_expires_refresher = 'uas';
}
responseExtraHeaders.push(
- `Session-Expires: ${this._sessionTimers.currentExpires};refresher=${session_expires_refresher}`
+ `Session-Expires: ${this.#sessionTimers.currentExpires};refresher=${session_expires_refresher}`
);
- this._sessionTimers.refresher = session_expires_refresher === 'uas';
- this._runSessionTimer();
+ this.#sessionTimers.refresher = session_expires_refresher === 'uas';
+ this.#runSessionTimer();
}
/**
* Handle SessionTimers for an incoming response to INVITE or UPDATE.
* @param {IncomingResponse} response
*/
- _handleSessionTimersInIncomingResponse(response) {
- if (!this._sessionTimers.enabled) {
+ #handleSessionTimersInIncomingResponse(response: IncomingResponse): void {
+ if (!this.#sessionTimers.enabled) {
return;
}
@@ -3154,28 +3750,28 @@ class RTCSession extends EventEmitter {
response.session_expires &&
response.session_expires >= JsSIP_C.MIN_SESSION_EXPIRES
) {
- this._sessionTimers.currentExpires = response.session_expires;
+ this.#sessionTimers.currentExpires = response.session_expires;
session_expires_refresher = response.session_expires_refresher || 'uac';
} else {
- this._sessionTimers.currentExpires = this._sessionTimers.defaultExpires;
+ this.#sessionTimers.currentExpires = this.#sessionTimers.defaultExpires;
session_expires_refresher = 'uac';
}
- this._sessionTimers.refresher = session_expires_refresher === 'uac';
- this._runSessionTimer();
+ this.#sessionTimers.refresher = session_expires_refresher === 'uac';
+ this.#runSessionTimer();
}
- _runSessionTimer() {
- const expires = this._sessionTimers.currentExpires;
+ #runSessionTimer(): void {
+ const expires = this.#sessionTimers.currentExpires;
- this._sessionTimers.running = true;
+ this.#sessionTimers.running = true;
- clearTimeout(this._sessionTimers.timer);
+ clearTimeout(this.#sessionTimers.timer ?? undefined);
// I'm the refresher.
- if (this._sessionTimers.refresher) {
- this._sessionTimers.timer = setTimeout(() => {
- if (this._status === C.STATUS_TERMINATED) {
+ if (this.#sessionTimers.refresher) {
+ this.#sessionTimers.timer = setTimeout(() => {
+ if (this.#status === Status.TERMINATED) {
return;
}
@@ -3185,18 +3781,18 @@ class RTCSession extends EventEmitter {
logger.debug('runSessionTimer() | sending session refresh request');
- if (this._sessionTimers.refreshMethod === JsSIP_C.UPDATE) {
- this._sendUpdate();
+ if (this.#sessionTimers.refreshMethod === JsSIP_C.UPDATE) {
+ this.#sendUpdate();
} else {
- this._sendReinvite();
+ this.#sendReinvite();
}
- }, expires * 500); // Half the given interval (as the RFC states).
+ }, expires! * 500); // Half the given interval (as the RFC states).
}
// I'm not the refresher.
else {
- this._sessionTimers.timer = setTimeout(() => {
- if (this._status === C.STATUS_TERMINATED) {
+ this.#sessionTimers.timer = setTimeout(() => {
+ if (this.#status === Status.TERMINATED) {
return;
}
@@ -3209,41 +3805,44 @@ class RTCSession extends EventEmitter {
status_code: 408,
reason_phrase: 'Session Timer Expired',
});
- }, expires * 1100);
+ }, expires! * 1100);
}
}
- _toggleMuteAudio(mute) {
- const senders = this._connection.getSenders().filter(sender => {
- return sender.track && sender.track.kind === 'audio';
+ #toggleMuteAudio(mute: boolean): void {
+ const senders = this.#connection!.getSenders().filter(sender => {
+ return sender.track?.kind === 'audio';
});
for (const sender of senders) {
- sender.track.enabled = !mute;
+ sender.track!.enabled = !mute;
}
}
- _toggleMuteVideo(mute) {
- const senders = this._connection.getSenders().filter(sender => {
- return sender.track && sender.track.kind === 'video';
+ #toggleMuteVideo(mute: boolean): void {
+ const senders = this.#connection!.getSenders().filter(sender => {
+ return sender.track?.kind === 'video';
});
for (const sender of senders) {
- sender.track.enabled = !mute;
+ sender.track!.enabled = !mute;
}
}
- _newRTCSession(originator, request) {
+ #newRTCSession(
+ originator: Originator,
+ request: IncomingRequest | OutgoingRequest
+ ): void {
logger.debug('newRTCSession()');
this.ua.newRTCSession(this, {
originator,
session: this,
request,
- });
+ } as RTCSessionEvent);
}
- _connecting(request) {
+ #connecting(request: IncomingRequest | OutgoingRequest): void {
logger.debug('session connecting');
logger.debug('emit "connecting"');
@@ -3253,7 +3852,7 @@ class RTCSession extends EventEmitter {
});
}
- _progress(originator, response) {
+ #progress(originator: Originator, response: IncomingResponse | null): void {
logger.debug('session progress');
logger.debug('emit "progress"');
@@ -3264,10 +3863,10 @@ class RTCSession extends EventEmitter {
});
}
- _accepted(originator, message) {
+ #accepted(originator: Originator, message?: IncomingResponse | null): void {
logger.debug('session accepted');
- this._start_time = new Date();
+ this.#start_time = new Date();
logger.debug('emit "accepted"');
@@ -3277,10 +3876,10 @@ class RTCSession extends EventEmitter {
});
}
- _confirmed(originator, ack) {
+ #confirmed(originator: Originator, ack: IncomingRequest | null): void {
logger.debug('session confirmed');
- this._is_confirmed = true;
+ this.#is_confirmed = true;
logger.debug('emit "confirmed"');
@@ -3290,12 +3889,16 @@ class RTCSession extends EventEmitter {
});
}
- _ended(originator, message, cause) {
+ #ended(
+ originator: Originator,
+ message: IncomingRequest | IncomingResponse | null,
+ cause: JsSIP_C.causes | string
+ ): void {
logger.debug('session ended');
- this._end_time = new Date();
+ this.#end_time = new Date();
- this._close();
+ this.#close();
logger.debug('emit "ended"');
@@ -3306,7 +3909,11 @@ class RTCSession extends EventEmitter {
});
}
- _failed(originator, message, cause) {
+ #failed(
+ originator: Originator,
+ message: IncomingRequest | IncomingResponse | null,
+ cause: JsSIP_C.causes | string
+ ): void {
logger.debug('session failed');
// Emit private '_failed' event first.
@@ -3318,7 +3925,7 @@ class RTCSession extends EventEmitter {
cause,
});
- this._close();
+ this.#close();
logger.debug('emit "failed"');
@@ -3329,10 +3936,10 @@ class RTCSession extends EventEmitter {
});
}
- _onhold(originator) {
+ #onhold(originator: Originator): void {
logger.debug('session onhold');
- this._setLocalMediaStatus();
+ this.#setLocalMediaStatus();
logger.debug('emit "hold"');
@@ -3341,10 +3948,10 @@ class RTCSession extends EventEmitter {
});
}
- _onunhold(originator) {
+ #onunhold(originator: Originator): void {
logger.debug('session onunhold');
- this._setLocalMediaStatus();
+ this.#setLocalMediaStatus();
logger.debug('emit "unhold"');
@@ -3353,10 +3960,10 @@ class RTCSession extends EventEmitter {
});
}
- _onmute({ audio, video }) {
+ #onmute({ audio, video }: MediaStreamTypes): void {
logger.debug('session onmute');
- this._setLocalMediaStatus();
+ this.#setLocalMediaStatus();
logger.debug('emit "muted"');
@@ -3366,10 +3973,10 @@ class RTCSession extends EventEmitter {
});
}
- _onunmute({ audio, video }) {
+ #onunmute({ audio, video }: MediaStreamTypes): void {
logger.debug('session onunmute');
- this._setLocalMediaStatus();
+ this.#setLocalMediaStatus();
logger.debug('emit "unmuted"');
@@ -3379,5 +3986,3 @@ class RTCSession extends EventEmitter {
});
}
}
-
-module.exports = { RTCSession };
diff --git a/src/RTCSession/ReferSubscriber.ts b/src/RTCSession/ReferSubscriber.ts
index 6d03a0f..4f37943 100644
--- a/src/RTCSession/ReferSubscriber.ts
+++ b/src/RTCSession/ReferSubscriber.ts
@@ -79,10 +79,10 @@ export type ReferSubscriberEventHandlers = {
* `RTCSession` is ported to TypeScript.
*/
export interface ReplacedSession {
- readonly _dialog: { id: DialogId } | null;
- readonly _request: { call_id: string };
- readonly _from_tag: string | null;
- readonly _to_tag: string | null;
+ readonly dialog: { id: DialogId } | null;
+ readonly request: { call_id?: string } | null;
+ readonly from_tag: string | null;
+ readonly to_tag: string | null;
}
/**
@@ -113,7 +113,7 @@ export type SendReferOptions = {
* `RTCSession` is ported to TypeScript.
*/
export interface ReferSubscriberSession {
- readonly contact: string;
+ readonly contact: string | null;
readonly ua: {
readonly configuration: { uri: URI };
};
@@ -200,7 +200,7 @@ export class ReferSubscriber extends EventEmitter {
let replaces = null;
if (options.replaces) {
- const dialog = options.replaces._dialog;
+ const dialog = options.replaces.dialog;
// RFC 3891 section 3: to-tag is the remote tag and from-tag the local
// tag of the dialog to replace, whoever sent the initial INVITE.
@@ -209,9 +209,9 @@ export class ReferSubscriber extends EventEmitter {
replaces += `;to-tag=${dialog.id.remote_tag}`;
replaces += `;from-tag=${dialog.id.local_tag}`;
} else {
- replaces = options.replaces._request.call_id;
- replaces += `;to-tag=${options.replaces._to_tag}`;
- replaces += `;from-tag=${options.replaces._from_tag}`;
+ replaces = `${options.replaces.request?.call_id}`;
+ replaces += `;to-tag=${options.replaces.to_tag}`;
+ replaces += `;from-tag=${options.replaces.from_tag}`;
}
replaces = encodeURIComponent(replaces);
diff --git a/src/UA.ts b/src/UA.ts
index 28f7a1d..413e1af 100644
--- a/src/UA.ts
+++ b/src/UA.ts
@@ -950,7 +950,7 @@ export class UA extends EventEmitter<UAEventMap> {
* @internal
*/
newRTCSession(session: RTCSession, data: RTCSessionEvent): void {
- this.#sessions[session.id] = session;
+ this.#sessions[session.id!] = session;
this.emit('newRTCSession', data);
}
@@ -958,7 +958,7 @@ export class UA extends EventEmitter<UAEventMap> {
* @internal
*/
destroyRTCSession(session: RTCSession): void {
- delete this.#sessions[session.id];
+ delete this.#sessions[session.id!];
this.#mayClose();
}
diff --git a/src/test/RTCSession/test-DTMF.ts b/src/test/RTCSession/test-DTMF.ts
index f930c3a..38e6ef5 100644
--- a/src/test/RTCSession/test-DTMF.ts
+++ b/src/test/RTCSession/test-DTMF.ts
@@ -1,4 +1,3 @@
-import type { EventEmitter } from 'events';
import { once } from 'events';
import { setTimeout as delay } from 'timers/promises';
@@ -422,18 +421,11 @@ async function hangUp(ua: UA, session: RTCSession): Promise<void> {
/**
* Collects the tones a session reports, incoming and outgoing alike.
- *
- * @remarks
- * - The hand-written declarations of `RTCSession` give 'newDTMF' a union of
- * listener types that no single signature satisfies, so this goes through
- * the plain `EventEmitter` until `RTCSession` is ported to TypeScript.
*/
function collectDTMF(session: RTCSession): NewDTMFEvent[] {
const reported: NewDTMFEvent[] = [];
- (session as EventEmitter).on('newDTMF', (event: NewDTMFEvent) =>
- reported.push(event)
- );
+ session.on('newDTMF', event => reported.push(event));
return reported;
}
diff --git a/src/test/RTCSession/test-ReferSubscriber.ts b/src/test/RTCSession/test-ReferSubscriber.ts
index e42d834..c45ad3d 100644
--- a/src/test/RTCSession/test-ReferSubscriber.ts
+++ b/src/test/RTCSession/test-ReferSubscriber.ts
@@ -36,11 +36,11 @@ function createReplacedSession(
const outgoing = direction === 'outgoing';
return {
- _request: { call_id: CALL_ID },
+ request: { call_id: CALL_ID },
// Tags of the From and To header fields of the initial INVITE.
- _from_tag: outgoing ? LOCAL_TAG : REMOTE_TAG,
- _to_tag: outgoing ? REMOTE_TAG : LOCAL_TAG,
- _dialog: {
+ from_tag: outgoing ? LOCAL_TAG : REMOTE_TAG,
+ to_tag: outgoing ? REMOTE_TAG : LOCAL_TAG,
+ dialog: {
id: { call_id: CALL_ID, local_tag: LOCAL_TAG, remote_tag: REMOTE_TAG },
},
};
@@ -133,7 +133,7 @@ describe('ReferSubscriber.sendRefer()', () => {
test('Replaces of a session without dialog', () => {
const replaces = {
...createReplacedSession('outgoing'),
- _dialog: null,
+ dialog: null,
};
expect(field(sendRefer({ replaces }), 'Refer-To')).toBe(
diff --git a/src/test/include/webrtc.ts b/src/test/include/webrtc.ts
index 98a1ab2..9654ad2 100644
--- a/src/test/include/webrtc.ts
+++ b/src/test/include/webrtc.ts
@@ -51,6 +51,25 @@ export function sdp(sessionId: number): string {
].join('\r\n');
}
+/**
+ * The operations a test can make fail, so that the paths handling a browser
+ * that refuses to cooperate can be driven.
+ */
+export type Failable =
+ | 'getUserMedia'
+ | 'createOffer'
+ | 'createAnswer'
+ | 'setLocalDescription'
+ | 'setRemoteDescription';
+
+let failing: Set<Failable> = new Set();
+
+function refuse<T>(operation: Failable, value: T): Promise<T> {
+ return failing.has(operation)
+ ? Promise.reject(new Error(`${operation} failed`))
+ : Promise.resolve(value);
+}
+
type Listener = (event: unknown) => void;
export class MockRTCPeerConnection {
@@ -82,7 +101,7 @@ export class MockRTCPeerConnection {
this.signalingState =
description.type === 'offer' ? 'have-local-offer' : 'stable';
- return Promise.resolve();
+ return refuse('setLocalDescription', undefined);
}
setRemoteDescription(description: Description): Promise<void> {
@@ -90,7 +109,7 @@ export class MockRTCPeerConnection {
this.signalingState =
description.type === 'offer' ? 'have-remote-offer' : 'stable';
- return Promise.resolve();
+ return refuse('setRemoteDescription', undefined);
}
addTrack(track: FakeMediaStreamTrack): { track: FakeMediaStreamTrack } {
@@ -130,7 +149,10 @@ export class MockRTCPeerConnection {
this.created.push(description);
- return Promise.resolve(description);
+ return refuse(
+ type === 'offer' ? 'createOffer' : 'createAnswer',
+ description
+ );
}
}
@@ -139,8 +161,13 @@ let connectionCount = 0;
/**
* Defines the globals RTCSession reaches for. Returns the media stream that
* getUserMedia() hands out, so that a test can check what was attached.
+ *
+ * @param fail - Operations that reject rather than succeed. Each one is the
+ * browser refusing at a different point of setting a call up.
*/
-export function installWebRTC(): MockMediaStream {
+export function installWebRTC(fail: Failable[] = []): MockMediaStream {
+ failing = new Set(fail);
+
const stream = new MockMediaStream([
new FakeMediaStreamTrack({ kind: 'audio' }),
]);
@@ -164,7 +191,8 @@ export function installWebRTC(): MockMediaStream {
globals['navigator'] = {
userAgent: '',
mediaDevices: {
- getUserMedia: (): Promise<MockMediaStream> => Promise.resolve(stream),
+ getUserMedia: (): Promise<MockMediaStream> =>
+ refuse('getUserMedia', stream),
},
};
diff --git a/src/test/test-RTCSession.ts b/src/test/test-RTCSession.ts
index c0e88d9..feaf5b9 100644
--- a/src/test/test-RTCSession.ts
+++ b/src/test/test-RTCSession.ts
@@ -1,11 +1,25 @@
import { once } from 'events';
+import { setTimeout as delay } from 'timers/promises';
import './include/common';
import TestSocket from './include/TestSocket';
+import type { Failable } from './include/webrtc';
import { installWebRTC, sdp } from './include/webrtc';
import { startUA, stopUA } from './include/ua';
-import { body, buildResponse, header, method, tag } from './include/sipMessage';
+import {
+ body,
+ buildRequest,
+ buildResponse,
+ cseq,
+ header,
+ headers,
+ method,
+ ruri,
+ status,
+ tag,
+} from './include/sipMessage';
+import type { RTCSession } from '../RTCSession';
import { C, UA } from '../JsSIP';
const LOCAL_URI = 'sip:alice@example.com';
@@ -14,6 +28,12 @@ const PEER_URI = 'sip:bob@example.com';
const PEER_CONTACT = 'sip:bob@192.0.2.1:5060';
const PEER_TAG = 'peertag';
+// The third party of an attended transfer, which calls in asking to take the
+// established dialog over.
+const REPLACING_URI = 'sip:carol@example.com';
+const REPLACING_TAG = 'replacingtag';
+const REPLACING_CALL_ID = 'the-replacing-call';
+
/**
* The session events worth logging. 'failed' is among them so that a call
* that goes wrong shows up in the log instead of as a timeout.
@@ -36,6 +56,9 @@ const RINGS_AND_ANSWERS = [100, 180, 200];
* with the given statuses, takes re-INVITEs and accepts the BYE.
*/
class PeerSocket extends TestSocket {
+ // CSeq of the last request the peer sent within the dialog.
+ private cseq = 0;
+
constructor(private readonly toInvite: number[] = RINGS_AND_ANSWERS) {
super();
}
@@ -46,10 +69,24 @@ class PeerSocket extends TestSocket {
// A re-INVITE travels within the dialog: no ringing, just an answer.
const statuses = tag(header(request, 'To')) ? [200] : this.toInvite;
- this.receive(...statuses.map(status => this.answer(request, status)));
+ this.receive(...statuses.map(code => this.answer(request, code)));
+ break;
+ }
+
+ case 'REFER': {
+ // RFC 3515: take the transfer on, then report how it goes through
+ // NOTIFY requests sent within the dialog.
+ this.receive(this.answer(request, 202));
+ this.notifyRefer(request, '100 Trying', 'active;expires=60');
+ this.notifyRefer(request, '200 OK', 'terminated;reason=noresource');
break;
}
+ // The NOTIFY requests here are the ones the UA sends when it is the
+ // one being asked to transfer.
+ case 'NOTIFY':
+ case 'INFO':
+ case 'UPDATE':
case 'BYE': {
this.receive(this.answer(request, 200));
break;
@@ -57,6 +94,149 @@ class PeerSocket extends TestSocket {
}
}
+ /**
+ * Sends an INFO within the dialog.
+ */
+ info(contentType: string, payload: string): void {
+ this.receive(this.inDialog('INFO', [], { contentType, body: payload }));
+ }
+
+ /**
+ * Re-offers the call with an UPDATE, as the peer would to put it on hold.
+ */
+ update(extraHeaders: string[] = []): void {
+ this.receive(
+ this.inDialog('UPDATE', extraHeaders, {
+ contentType: 'application/sdp',
+ body: sdp(2).replace('a=sendrecv', 'a=sendonly'),
+ })
+ );
+ }
+
+ /**
+ * Calls in with an INVITE that asks to take the established dialog over,
+ * which is how the third party of an attended transfer arrives.
+ */
+ replaces(): void {
+ const invite = this.requests('INVITE')[0]!;
+
+ this.receive(
+ buildRequest('INVITE', LOCAL_CONTACT, {
+ from: `<${REPLACING_URI}>;tag=${REPLACING_TAG}`,
+ to: `<${LOCAL_URI}>`,
+ callId: REPLACING_CALL_ID,
+ cseq: 1,
+ extraHeaders: [
+ `Contact: <${PEER_CONTACT}>`,
+ // RFC 3891: the tags name the dialog as the party being
+ // replaced sees it.
+ `Replaces: ${header(invite, 'Call-ID')};from-tag=${tag(
+ header(invite, 'From')
+ )};to-tag=${PEER_TAG}`,
+ ],
+ contentType: 'application/sdp',
+ body: sdp(2),
+ })
+ );
+ }
+
+ /**
+ * Re-offers the call with a re-INVITE, the other way a peer puts it on
+ * hold.
+ */
+ reinvite(): void {
+ this.receive(
+ this.inDialog('INVITE', [`Contact: <${PEER_CONTACT}>`], {
+ contentType: 'application/sdp',
+ body: sdp(2).replace('a=sendrecv', 'a=sendonly'),
+ })
+ );
+ }
+
+ protected override onResponse(response: string): void {
+ // Every INVITE the peer sends, whether a re-INVITE or one replacing the
+ // call, needs its answer acknowledged from this side. The answers to
+ // the INVITEs the UA sends never reach here, since they are received
+ // rather than sent.
+ if (method(response) === 'INVITE' && status(response) === 200) {
+ this.receive(
+ buildRequest('ACK', LOCAL_CONTACT, {
+ from: header(response, 'From'),
+ to: header(response, 'To'),
+ callId: header(response, 'Call-ID'),
+ cseq: cseq(response).number,
+ })
+ );
+ }
+ }
+
+ /**
+ * Status codes the UA answered the replacing INVITE with, in order.
+ */
+ replacesStatuses(): number[] {
+ return this.responses()
+ .filter(response => header(response, 'Call-ID') === REPLACING_CALL_ID)
+ .map(response => status(response));
+ }
+
+ /**
+ * Asks the UA to transfer the call to the given target.
+ */
+ refer(target: string): void {
+ this.receive(this.inDialog('REFER', [`Refer-To: <${target}>`]));
+ }
+
+ /**
+ * Bodies of the NOTIFY requests the UA has sent, in order.
+ */
+ notified(): string[] {
+ return this.requests('NOTIFY').map(notify => body(notify));
+ }
+
+ /**
+ * A NOTIFY reporting how the transfer the given REFER asked for is going.
+ */
+ private notifyRefer(refer: string, statusLine: string, state: string): void {
+ this.receive(
+ buildRequest('NOTIFY', LOCAL_CONTACT, {
+ // The dialog as the peer sees it, which the REFER states the other
+ // way round.
+ from: header(refer, 'To'),
+ to: header(refer, 'From'),
+ callId: header(refer, 'Call-ID'),
+ cseq: ++this.cseq,
+ extraHeaders: [
+ // The subscription is the one the REFER created, named by its
+ // sequence number.
+ `Event: refer;id=${cseq(refer).number}`,
+ `Subscription-State: ${state}`,
+ ],
+ contentType: 'message/sipfrag;version=2.0',
+ body: `SIP/2.0 ${statusLine}`,
+ })
+ );
+ }
+
+ /**
+ * A request within the dialog the initial INVITE established.
+ */
+ private inDialog(
+ name: string,
+ extraHeaders: string[] = [],
+ content: { contentType?: string; body?: string } = {}
+ ): string {
+ const invite = this.requests('INVITE')[0]!;
+
+ return buildRequest(name, LOCAL_CONTACT, {
+ from: `${header(invite, 'To')};tag=${PEER_TAG}`,
+ to: header(invite, 'From'),
+ callId: header(invite, 'Call-ID'),
+ cseq: ++this.cseq,
+ extraHeaders,
+ ...content,
+ });
+ }
+
// Media directions of the SDP offers the UA has sent, in order.
directions(): (string | undefined)[] {
return this.requests('INVITE').map(
@@ -65,13 +245,16 @@ class PeerSocket extends TestSocket {
);
}
- private answer(request: string, status: number): string {
- // Only a 2xx to an INVITE carries the SDP answer.
- const answersTheOffer = status >= 200 && status < 300 && isInvite(request);
+ private answer(request: string, code: number): string {
+ // A 2xx answers the offer, whether the INVITE or an UPDATE carried it.
+ const answersTheOffer =
+ code >= 200 &&
+ code < 300 &&
+ (isInvite(request) || body(request).startsWith('v='));
- return buildResponse(request, status, {
+ return buildResponse(request, code, {
// A 100 Trying creates nothing, so it gets no tag of ours.
- toTag: status > 100 ? PEER_TAG : undefined,
+ toTag: code > 100 ? PEER_TAG : undefined,
extraHeaders: isInvite(request) ? [`Contact: <${PEER_CONTACT}>`] : [],
contentType: answersTheOffer ? 'application/sdp' : undefined,
body: answersTheOffer ? sdp(1) : undefined,
@@ -83,6 +266,149 @@ function isInvite(request: string): boolean {
return method(request) === 'INVITE';
}
+/**
+ * Places a call through the given socket and resolves once it is confirmed.
+ */
+async function placeCall(socket: PeerSocket): Promise<[UA, RTCSession]> {
+ const ua = new UA({
+ sockets: socket,
+ uri: LOCAL_URI,
+ contact_uri: LOCAL_CONTACT,
+ register: false,
+ });
+
+ await startUA(ua);
+
+ const session = ua.call(PEER_URI, {
+ mediaConstraints: { audio: true, video: false },
+ });
+
+ await once(session, 'confirmed');
+
+ return [ua, session];
+}
+
+/**
+ * Hangs the call up and stops the UA.
+ */
+async function hangUp(ua: UA, session: RTCSession): Promise<void> {
+ // 'ended' is emitted from within terminate(), so listen before calling it.
+ const ended = once(session, 'ended');
+
+ session.terminate();
+
+ await ended;
+ await stopUA(ua);
+}
+
+const INCOMING_CALL_ID = 'the-incoming-call';
+
+/**
+ * A socket that places a call into the UA: it sends the INVITE, acknowledges
+ * the answer, and can hang up afterwards.
+ */
+class CallerSocket extends TestSocket {
+ private cseq = 0;
+ private toTag: string | undefined;
+
+ /**
+ * Calls the UA, with an SDP offer unless told otherwise.
+ */
+ invite({ offer = true }: { offer?: boolean } = {}): void {
+ this.receive(
+ buildRequest('INVITE', LOCAL_CONTACT, {
+ from: `<${PEER_URI}>;tag=${PEER_TAG}`,
+ to: `<${LOCAL_URI}>`,
+ callId: INCOMING_CALL_ID,
+ cseq: ++this.cseq,
+ extraHeaders: [`Contact: <${PEER_CONTACT}>`],
+ contentType: offer ? 'application/sdp' : undefined,
+ body: offer ? sdp(1) : undefined,
+ })
+ );
+ }
+
+ /**
+ * Hangs the established call up.
+ */
+ bye(): void {
+ this.receive(
+ buildRequest('BYE', LOCAL_CONTACT, {
+ from: `<${PEER_URI}>;tag=${PEER_TAG}`,
+ to: `<${LOCAL_URI}>;tag=${this.toTag}`,
+ callId: INCOMING_CALL_ID,
+ cseq: ++this.cseq,
+ })
+ );
+ }
+
+ /**
+ * Status codes the UA has answered the INVITE with, in order.
+ */
+ inviteStatuses(): number[] {
+ return this.responses('INVITE').map(response => status(response));
+ }
+
+ protected override onResponse(response: string): void {
+ // Acknowledging the answer is what confirms the dialog.
+ if (method(response) === 'INVITE' && status(response) === 200) {
+ this.toTag = tag(header(response, 'To'));
+
+ this.receive(
+ buildRequest('ACK', LOCAL_CONTACT, {
+ from: `<${PEER_URI}>;tag=${PEER_TAG}`,
+ to: header(response, 'To'),
+ callId: INCOMING_CALL_ID,
+ // An ACK carries the sequence number of the INVITE it answers.
+ cseq: cseq(response).number,
+ })
+ );
+ }
+ }
+}
+
+/**
+ * Starts a UA that takes the call the socket is about to place, and resolves
+ * with the session once it is reported. The listeners are registered from
+ * within `newRTCSession`, since the session reaches 'progress' before the
+ * event handler returns.
+ */
+async function receiveCall(socket: CallerSocket): Promise<{
+ ua: UA;
+ session: RTCSession;
+ events: EVENT[];
+}> {
+ const ua = new UA({
+ sockets: socket,
+ uri: LOCAL_URI,
+ contact_uri: LOCAL_CONTACT,
+ register: false,
+ });
+
+ const events: EVENT[] = [];
+ let session!: RTCSession;
+
+ const reported: Promise<void> = new Promise(resolve => {
+ ua.on('newRTCSession', event => {
+ session = event.session;
+
+ for (const name of Object.values(EVENT)) {
+ session.on(name, () => events.push(name));
+ }
+
+ resolve();
+ });
+ });
+
+ await startUA(ua);
+
+ socket.invite();
+
+ await reported;
+
+ return { ua, session, events };
+}
+
/**
* Runs hold(), unhold() or renegotiate() and waits for the re-INVITE they send
* to be answered, which is when they call their 'done' callback. They return
@@ -157,7 +483,7 @@ describe('RTCSession', () => {
expect(sent).toEqual({ offer: 'application/sdp', acked: 1 });
// The peer's answer reached the peer connection.
- expect(session.connection.remoteDescription).toEqual({
+ expect(session.connection!.remoteDescription).toEqual({
type: 'answer',
sdp: sdp(1),
});
@@ -249,4 +575,509 @@ describe('RTCSession', () => {
expect(socket.requests('ACK')).toHaveLength(1);
expect(socket.requests('BYE')).toHaveLength(0);
});
+
+ test('an incoming call, answered and then hung up by the peer', async () => {
+ const socket = new CallerSocket();
+ const { ua, session, events } = await receiveCall(socket);
+
+ const answered = {
+ direction: session.direction,
+ remote: session.remote_identity!.uri.toString(),
+ };
+
+ session.answer({ mediaConstraints: { audio: true, video: false } });
+
+ await once(session, 'confirmed');
+
+ const ended = once(session, 'ended');
+
+ socket.bye();
+
+ const [end] = await ended;
+
+ await stopUA(ua);
+
+ expect(answered).toEqual({ direction: 'incoming', remote: PEER_URI });
+
+ // The UA rings before the application answers, and the peer's offer
+ // reached the peer connection.
+ expect(socket.inviteStatuses()).toEqual([100, 180, 200]);
+ expect(session.connection!.remoteDescription).toEqual({
+ type: 'offer',
+ sdp: sdp(1),
+ });
+
+ // The ringing is reported before the application answers, so
+ // 'progress' comes ahead of the 'connecting' that `answer()` emits.
+ // An outgoing call reports the two the other way round.
+ expect(events).toEqual([
+ EVENT.PROGRESS,
+ EVENT.CONNECTING,
+ EVENT.ACCEPTED,
+ EVENT.CONFIRMED,
+ EVENT.ENDED,
+ ]);
+
+ expect(end).toMatchObject({ originator: 'remote', cause: C.causes.BYE });
+ });
+
+ test('an incoming call the application rejects', async () => {
+ const socket = new CallerSocket();
+ const { ua, session, events } = await receiveCall(socket);
+
+ const failed = once(session, 'failed');
+
+ session.terminate({ status_code: 486 });
+
+ const [failure] = await failed;
+
+ await stopUA(ua);
+
+ expect(socket.inviteStatuses()).toEqual([100, 180, 486]);
+ expect(events).toEqual([EVENT.PROGRESS, EVENT.FAILED]);
+ expect(failure).toMatchObject({
+ originator: 'local',
+ cause: C.causes.REJECTED,
+ });
+ });
+});
+
+describe('call transfer', () => {
+ beforeEach(() => {
+ installWebRTC();
+ });
+
+ const TRANSFER_TARGET = 'sip:carol@example.com';
+
+ test('refer() asks the peer to transfer, and follows the NOTIFYs', async () => {
+ const socket = new PeerSocket();
+ const [ua, session] = await placeCall(socket);
+
+ const reported: string[] = [];
+ const subscriber = session.refer(TRANSFER_TARGET);
+
+ if (!subscriber) {
+ throw new Error('the session refused to transfer');
+ }
+
+ for (const name of ['requestSucceeded', 'trying', 'accepted', 'failed']) {
+ subscriber.on(name, () => reported.push(name));
+ }
+
+ await delay(100);
+
+ const refer = socket.requests('REFER')[0]!;
+
+ await hangUp(ua, session);
+
+ expect(header(refer, 'Refer-To')).toBe(`<${TRANSFER_TARGET}>`);
+
+ // Built out of the configured address of record, which is the part that
+ // reaches back into the UA through the session.
+ expect(header(refer, 'Referred-By')).toBe(`<${LOCAL_URI}>`);
+
+ expect(reported).toEqual(['requestSucceeded', 'trying', 'accepted']);
+ });
+
+ test('a transfer the peer asks for, and the application declines', async () => {
+ const socket = new PeerSocket();
+ const [ua, session] = await placeCall(socket);
+
+ const asked = once(session, 'refer');
+
+ socket.refer(TRANSFER_TARGET);
+
+ const [transfer] = await asked;
+
+ const referTo = transfer.request.refer_to.uri.toString();
+
+ transfer.reject();
+
+ await delay(100);
+ await hangUp(ua, session);
+
+ expect(referTo).toBe(TRANSFER_TARGET);
+
+ // The REFER is taken on before the application sees it, and the
+ // subscription it created is reported and then closed.
+ expect(socket.responses('REFER').map(status)).toEqual([202]);
+ expect(socket.notified()).toEqual([
+ 'SIP/2.0 100 Trying',
+ 'SIP/2.0 603 Decline',
+ ]);
+ });
+
+ test('an INVITE that replaces the call is reported and can be declined', async () => {
+ const socket = new PeerSocket();
+ const [ua, session] = await placeCall(socket);
+
+ // The replacing call arrives as an initial INVITE, which the UA refuses
+ // with a 405 unless the application is listening for incoming calls.
+ // The session it replaces is reached through the Replaces header field,
+ // so this listener never fires.
+ ua.on('newRTCSession', () => {});
+
+ const asked = once(session, 'replaces');
+
+ socket.replaces();
+
+ const [replacing] = await asked;
+
+ const from = replacing.request.from.uri.toString();
+
+ replacing.reject();
+
+ await delay(50);
+ await hangUp(ua, session);
+
+ expect(from).toBe(REPLACING_URI);
+
+ // The replacing INVITE is answered on its own transaction, and the call
+ // it tried to take over carries on.
+ expect(socket.replacesStatuses()).toEqual([100, 486]);
+ expect(socket.requests('BYE')).toHaveLength(1);
+ });
+
+ test('accepting a transfer calls the target and reports its progress', async () => {
+ const socket = new PeerSocket();
+ const [ua, session] = await placeCall(socket);
+
+ const asked = once(session, 'refer');
+
+ socket.refer(TRANSFER_TARGET);
+
+ const [transfer] = await asked;
+
+ // Taking the transfer on places a second call, whose progress the
+ // notifier reports back to the peer that asked for it.
+ transfer.accept(undefined, {
+ mediaConstraints: { audio: true, video: false },
+ });
+
+ await delay(150);
+ await hangUp(ua, session);
+
+ const placed = socket.requests('INVITE')[1]!;
+
+ expect(ruri(placed)).toBe(TRANSFER_TARGET);
+ expect(socket.notified()).toEqual([
+ 'SIP/2.0 100 Trying',
+ 'SIP/2.0 180 Ringing',
+ 'SIP/2.0 200 OK',
+ ]);
+ });
+
+ test('accepting a replacing INVITE ends the call it took over', async () => {
+ const socket = new PeerSocket();
+ const [ua, session] = await placeCall(socket);
+
+ // The replacing call is reported like any other incoming one, so it is
+ // answered from here.
+ ua.on('newRTCSession', ({ session: replacing }) => {
+ replacing.answer({ mediaConstraints: { audio: true, video: false } });
+ });
+
+ const asked = once(session, 'replaces');
+
+ socket.replaces();
+
+ const [replacing] = await asked;
+
+ // The call being replaced ends once the new one is confirmed.
+ const ended = once(session, 'ended');
+
+ replacing.accept();
+
+ const [end] = await ended;
+
+ // Counted before the UA is stopped, which hangs the new call up too.
+ const byes = socket.requests('BYE').length;
+
+ await stopUA(ua);
+
+ expect(socket.replacesStatuses()).toEqual([100, 180, 200]);
+ expect(end).toMatchObject({ originator: 'local', cause: C.causes.BYE });
+
+ // The call that was taken over is hung up, the new one carries on.
+ expect(byes).toBe(1);
+ });
+});
+
+describe('session timers', () => {
+ beforeEach(() => {
+ installWebRTC();
+ });
+
+ test('the initial INVITE offers to run them', async () => {
+ const socket = new PeerSocket();
+ const [ua, session] = await placeCall(socket);
+
+ await hangUp(ua, session);
+
+ const invite = socket.requests('INVITE')[0]!;
+
+ expect(header(invite, 'Session-Expires')).toBe('90');
+ expect(header(invite, 'Supported')).toContain('timer');
+ });
+
+ test('a UA configured without them does not offer them', async () => {
+ const socket = new PeerSocket();
+ const ua = new UA({
+ sockets: socket,
+ uri: LOCAL_URI,
+ contact_uri: LOCAL_CONTACT,
+ register: false,
+ session_timers: false,
+ });
+
+ await startUA(ua);
+
+ const session = ua.call(PEER_URI, {
+ mediaConstraints: { audio: true, video: false },
+ });
+
+ await once(session, 'confirmed');
+ await hangUp(ua, session);
+
+ const invite = socket.requests('INVITE')[0]!;
+
+ expect(headers(invite, 'Session-Expires')).toEqual([]);
+ expect(header(invite, 'Supported')).not.toContain('timer');
+ });
+});
+
+describe('a browser that refuses to set the call up', () => {
+ /**
+ * Places a call with the given operations failing, and resolves with what
+ * the session reported and what reached the wire.
+ */
+ async function callWith(
+ fail: Failable[],
+ event: string
+ ): Promise<{ reported: boolean; failure: unknown; invites: number }> {
+ installWebRTC(fail);
+
+ const socket = new PeerSocket();
+ const ua = new UA({
+ sockets: socket,
+ uri: LOCAL_URI,
+ contact_uri: LOCAL_CONTACT,
+ register: false,
+ });
+
+ await startUA(ua);
+
+ const session = ua.call(PEER_URI, {
+ mediaConstraints: { audio: true, video: false },
+ });
+
+ let reported = false;
+
+ session.on(event, () => (reported = true));
+
+ const [failure] = await once(session, 'failed');
+
+ await stopUA(ua);
+
+ return { reported, failure, invites: socket.requests('INVITE').length };
+ }
+
+ test('media the user does not grant fails the call before it is sent', async () => {
+ const outcome = await callWith(['getUserMedia'], 'getusermediafailed');
+
+ expect(outcome.reported).toBe(true);
+ expect(outcome.failure).toMatchObject({
+ originator: 'local',
+ cause: C.causes.USER_DENIED_MEDIA_ACCESS,
+ });
+ expect(outcome.invites).toBe(0);
+ });
+
+ test('an offer the peer connection cannot build fails the call too', async () => {
+ const outcome = await callWith(
+ ['createOffer'],
+ 'peerconnection:createofferfailed'
+ );
+
+ expect(outcome.reported).toBe(true);
+ expect(outcome.failure).toMatchObject({
+ originator: 'local',
+ cause: C.causes.WEBRTC_ERROR,
+ });
+ expect(outcome.invites).toBe(0);
+ });
+});
+
+describe('in-dialog requests', () => {
+ beforeEach(() => {
+ installWebRTC();
+ });
+
+ const CONTENT_TYPE = 'application/x-test';
+
+ /**
+ * Collects what the session reports through 'newInfo', as
+ * `originator:contentType` pairs.
+ */
+ function collectInfo(session: RTCSession): string[] {
+ const reported: string[] = [];
+
+ session.on('newInfo', ({ originator, info }) =>
+ reported.push(`${originator}:${info.contentType}`)
+ );
+
+ return reported;
+ }
+
+ test('sendInfo() carries the content type and the body', async () => {
+ const socket = new PeerSocket();
+ const [ua, session] = await placeCall(socket);
+
+ const reported = collectInfo(session);
+
+ session.sendInfo(CONTENT_TYPE, 'hello there');
+
+ await delay(50);
+ await hangUp(ua, session);
+
+ const info = socket.requests('INFO')[0]!;
+
+ expect(header(info, 'Content-Type')).toBe(CONTENT_TYPE);
+ expect(body(info)).toBe('hello there');
+ expect(reported).toEqual([`local:${CONTENT_TYPE}`]);
+ });
+
+ test('an INFO that arrives is reported and answered', async () => {
+ const socket = new PeerSocket();
+ const [ua, session] = await placeCall(socket);
+
+ const reported = collectInfo(session);
+
+ socket.info(CONTENT_TYPE, 'ping');
+
+ await delay(50);
+ await hangUp(ua, session);
+
+ expect(reported).toEqual([`remote:${CONTENT_TYPE}`]);
+ expect(socket.responses('INFO').map(response => status(response))).toEqual([
+ 200,
+ ]);
+ });
+
+ test('hold() re-offers with an UPDATE when asked to', async () => {
+ const socket = new PeerSocket();
+ const [ua, session] = await placeCall(socket);
+
+ await reoffer(done => session.hold({ useUpdate: true }, done));
+
+ const onHold = session.isOnHold();
+
+ await hangUp(ua, session);
+
+ const update = socket.requests('UPDATE')[0]!;
+
+ expect(onHold).toEqual({ local: true, remote: false });
+ expect(header(update, 'Content-Type')).toBe('application/sdp');
+ expect(body(update)).toContain('a=sendonly');
+
+ // The offer travelled in the UPDATE, so no second INVITE was needed.
+ expect(socket.requests('INVITE')).toHaveLength(1);
+ });
+
+ test('an UPDATE that arrives re-answers the call', async () => {
+ const socket = new PeerSocket();
+ const [ua, session] = await placeCall(socket);
+
+ const updated = once(session, 'update');
+
+ socket.update();
+
+ await updated;
+ await delay(50);
+
+ const answered = socket
+ .responses('UPDATE')
+ .map(response => status(response));
+
+ await hangUp(ua, session);
+
+ expect(answered).toEqual([200]);
+ expect(session.isOnHold()).toEqual({ local: false, remote: true });
+ });
+
+ test('a refresh the peer asks for names the refresher in the answer', async () => {
+ const socket = new PeerSocket();
+ const [ua, session] = await placeCall(socket);
+
+ const updated = once(session, 'update');
+
+ socket.update(['Session-Expires: 120;refresher=uac']);
+
+ await updated;
+ await delay(50);
+
+ const answer = socket.responses('UPDATE')[0]!;
+
+ await hangUp(ua, session);
+
+ // RFC 4028: the answer settles the interval and says who refreshes it.
+ expect(header(answer, 'Session-Expires')).toBe('120;refresher=uac');
+ });
+
+ test('a re-INVITE that arrives re-answers the call', async () => {
+ const socket = new PeerSocket();
+ const [ua, session] = await placeCall(socket);
+
+ const reinvited = once(session, 'reinvite');
+
+ socket.reinvite();
+
+ await reinvited;
+ await delay(50);
+
+ const answered = socket.responses('INVITE').map(r => status(r));
+ const onHold = session.isOnHold();
+
+ await hangUp(ua, session);
+
+ expect(answered).toEqual([100, 200]);
+ expect(onHold).toEqual({ local: false, remote: true });
+ });
+
+ test('mute() and unmute() report what is muted', async () => {
+ const socket = new PeerSocket();
+ const [ua, session] = await placeCall(socket);
+
+ const events: string[] = [];
+
+ session.on('muted', () => events.push('muted'));
+ session.on('unmuted', () => events.push('unmuted'));
+
+ session.mute({ audio: true, video: false });
+
+ const whileMuted = session.isMuted();
+
+ session.unmute({ audio: true, video: false });
+
+ const afterwards = session.isMuted();
+
+ await hangUp(ua, session);
+
+ // Muting is local to the media, so nothing goes out on the wire.
+ expect(events).toEqual(['muted', 'unmuted']);
+ expect(whileMuted).toEqual({ audio: true, video: false });
+ expect(afterwards).toEqual({ audio: false, video: false });
+ });
+
+ test('renegotiate() re-offers the call unchanged', async () => {
+ const socket = new PeerSocket();
+ const [ua, session] = await placeCall(socket);
+
+ await reoffer(done => session.renegotiate({}, done));
+
+ await hangUp(ua, session);
+
+ // The initial offer and the one that renegotiated, both sendrecv.
+ expect(socket.directions()).toEqual(['sendrecv', 'sendrecv']);
+ });
});