Commit e3c4b98 for jssip.net

commit e3c4b98352b6d4c31f51eebbb676fbc6f0d46f0f
Author: José Luis Millán <jmillan@aliax.net>
Date:   Thu Dec 3 15:31:02 2026 +0100

    TS UA

diff --git a/src/Dialog.ts b/src/Dialog.ts
index 8996db9..2d421f3 100644
--- a/src/Dialog.ts
+++ b/src/Dialog.ts
@@ -79,7 +79,7 @@ export interface DialogUA extends RequestSenderUA {
  * modules are ported to TypeScript.
  */
 export interface DialogOwner {
-	readonly _ua: DialogUA;
+	readonly ua: DialogUA;

 	receiveRequest(request: IncomingRequest): void;
 }
@@ -184,7 +184,7 @@ export class Dialog {
 		id: DialogId
 	) {
 		this.#owner = owner;
-		this.#ua = owner._ua;
+		this.#ua = owner.ua;
 		this.#id = id;

 		if (message instanceof SIPMessage.IncomingResponse) {
@@ -294,7 +294,7 @@ export class Dialog {
 		const onAuthenticated = eventHandlers.onAuthenticated || (() => {});

 		// Increase the local CSeq on authentication.
-		eventHandlers.onAuthenticated = _request => {
+		eventHandlers.onAuthenticated = authenticated_request => {
 			// NOTE: `#createRequest()` above made sure there is a local sequence
 			// number.
 			this.#local_seqnum = (this.#local_seqnum ?? 0) + 1;
@@ -304,7 +304,7 @@ export class Dialog {
 				this.#outgoing_ack_seqnum = this.#local_seqnum;
 			}

-			onAuthenticated(_request);
+			onAuthenticated(authenticated_request);
 		};

 		const request_sender = new DialogRequestSender(
diff --git a/src/JsSIP.js b/src/JsSIP.js
index ccd80dd..035cb00 100644
--- a/src/JsSIP.js
+++ b/src/JsSIP.js
@@ -2,13 +2,13 @@ const pkg = require('../package.json');
 const C = require('./Constants');
 const Exceptions = require('./Exceptions');
 const Utils = require('./Utils');
-const UA = require('./UA');
+const { UA } = require('./UA');
 const URI = require('./URI');
 const NameAddrHeader = require('./NameAddrHeader');
 const Grammar = require('./Grammar');
 const { WebSocketInterface } = require('./WebSocketInterface');
 const debug = require('debug')('JsSIP');
-const RTCSession = require('./RTCSession');
+const { RTCSession } = require('./RTCSession');

 debug('version %s', pkg.version);

diff --git a/src/Notifier.ts b/src/Notifier.ts
index 27de3a7..bb3af7e 100644
--- a/src/Notifier.ts
+++ b/src/Notifier.ts
@@ -211,7 +211,7 @@ export class Notifier
 	 *
 	 * @internal
 	 */
-	readonly _ua: NotifierUA;
+	readonly ua: NotifierUA;

 	#initial_subscribe: IncomingRequest;
 	#dialog: Dialog | null = null;
@@ -253,7 +253,7 @@ export class Notifier

 		const eventName = subscribe.getHeader('event');

-		this._ua = ua;
+		this.ua = ua;
 		this.#initial_subscribe = subscribe;
 		this.#defaultExpires = defaultExpires || C.DEFAULT_EXPIRES_SEC;

@@ -270,7 +270,7 @@ export class Notifier
 		if (contact) {
 			this.#contact = contact;
 		} else {
-			this.#contact = `Contact: ${this._ua.contact.toString()}`;
+			this.#contact = `Contact: ${this.ua.contact.toString()}`;

 			this.#headers.push(this.#contact);
 		}
@@ -314,8 +314,8 @@ export class Notifier
 	/**
 	 * Replaces whatever was kept along with the notifier.
 	 */
-	set data(_data: unknown) {
-		this.#data = _data;
+	set data(data: unknown) {
+		this.#data = data;
 	}

 	/**
diff --git a/src/RTCSession.d.ts b/src/RTCSession.d.ts
index 232669e..a5142ba 100644
--- a/src/RTCSession.d.ts
+++ b/src/RTCSession.d.ts
@@ -7,7 +7,7 @@ import {
 } from './SIPMessage';
 import NameAddrHeader = require('./NameAddrHeader');
 import URI = require('./URI');
-import { UA } from './UA';
+import { CallOptions, UA } from './UA';
 import { causes, DTMF_TRANSPORT } from './Constants';

 interface RTCPeerConnectionDeprecated extends RTCPeerConnection {
@@ -256,6 +256,34 @@ declare enum SessionStatus {
 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;
@@ -265,7 +293,7 @@ export class RTCSession extends EventEmitter {
 	get id(): string;

 	// eslint-disable-next-line @typescript-eslint/no-explicit-any
-	set data(_data: any);
+	set data(data: any);
 	// eslint-disable-next-line @typescript-eslint/no-explicit-any
 	get data(): any;

diff --git a/src/RTCSession.js b/src/RTCSession.js
index e855a23..eaed0c9 100644
--- a/src/RTCSession.js
+++ b/src/RTCSession.js
@@ -43,7 +43,7 @@ const C = {
  */
 const holdMediaTypes = ['audio', 'video'];

-module.exports = class RTCSession extends EventEmitter {
+class RTCSession extends EventEmitter {
 	/**
 	 * Expose C object.
 	 */
@@ -57,7 +57,7 @@ module.exports = class RTCSession extends EventEmitter {
 		super();

 		this._id = null;
-		this._ua = ua;
+		this.ua = ua;
 		this._status = C.STATUS_NULL;
 		this._dialog = null;
 		this._earlyDialogs = {};
@@ -122,8 +122,8 @@ module.exports = class RTCSession extends EventEmitter {

 		// Session Timers (RFC 4028).
 		this._sessionTimers = {
-			enabled: this._ua.configuration.session_timers,
-			refreshMethod: this._ua.configuration.session_timers_refresh_method,
+			enabled: this.ua.configuration.session_timers,
+			refreshMethod: this.ua.configuration.session_timers_refresh_method,
 			defaultExpires: JsSIP_C.SESSION_EXPIRES,
 			currentExpires: null,
 			running: false,
@@ -287,7 +287,7 @@ module.exports = class RTCSession extends EventEmitter {
 		}

 		// Check target validity.
-		target = this._ua.normalizeTarget(target);
+		target = this.ua.normalizeTarget(target);
 		if (!target) {
 			throw new TypeError(`Invalid target: ${originalTarget}`);
 		}
@@ -318,7 +318,7 @@ module.exports = class RTCSession extends EventEmitter {

 		const requestParams = { from_tag: this._from_tag };

-		this._contact = this._ua.contact.toString({
+		this._contact = this.ua.contact.toString({
 			anonymous,
 			outbound: true,
 		});
@@ -328,18 +328,18 @@ module.exports = class RTCSession extends EventEmitter {
 			requestParams.from_uri = new URI('sip', 'anonymous', 'anonymous.invalid');

 			extraHeaders.push(
-				`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`
+				`P-Preferred-Identity: ${this.ua.configuration.uri.toString()}`
 			);
 			extraHeaders.push('Privacy: id');
 		} else if (options.fromUserName) {
 			requestParams.from_uri = new URI(
 				'sip',
 				options.fromUserName,
-				this._ua.configuration.uri.host
+				this.ua.configuration.uri.host
 			);

 			extraHeaders.push(
-				`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`
+				`P-Preferred-Identity: ${this.ua.configuration.uri.toString()}`
 			);
 		}

@@ -351,13 +351,13 @@ module.exports = class RTCSession extends EventEmitter {
 		extraHeaders.push('Content-Type: application/sdp');
 		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._ua,
+			this.ua,
 			requestParams,
 			extraHeaders
 		);
@@ -406,7 +406,7 @@ module.exports = class RTCSession extends EventEmitter {
 		this._from_tag = request.from_tag;
 		this._id = request.call_id + this._from_tag;
 		this._request = request;
-		this._contact = this._ua.contact.toString();
+		this._contact = this.ua.contact.toString();

 		// Get the Expires header value if exists.
 		if (request.hasHeader('expires')) {
@@ -441,7 +441,7 @@ module.exports = class RTCSession extends EventEmitter {
 		this._timers.userNoAnswerTimer = setTimeout(() => {
 			request.reply(408);
 			this._failed('local', null, JsSIP_C.causes.NO_ANSWER);
-		}, this._ua.configuration.no_answer_timeout);
+		}, this.ua.configuration.no_answer_timeout);

 		// Set expiresTimer
 		// RFC3261 13.3.1
@@ -890,7 +890,7 @@ module.exports = class RTCSession extends EventEmitter {
 					this._dialog = dialog;

 					// Restore the dialog into 'ua' so the ACK can reach 'this' session.
-					this._ua.newDialog(dialog);
+					this.ua.newDialog(dialog);
 				} else {
 					this.sendRequest(JsSIP_C.BYE, {
 						extraHeaders,
@@ -1297,7 +1297,7 @@ module.exports = class RTCSession extends EventEmitter {
 		}

 		// Check target validity.
-		target = this._ua.normalizeTarget(target);
+		target = this.ua.normalizeTarget(target);
 		if (!target) {
 			throw new TypeError(`Invalid target: ${originalTarget}`);
 		}
@@ -1671,7 +1671,7 @@ module.exports = class RTCSession extends EventEmitter {
 			}
 		}

-		this._ua.destroyRTCSession(this);
+		this.ua.destroyRTCSession(this);
 	}

 	/**
@@ -2294,7 +2294,7 @@ module.exports = class RTCSession extends EventEmitter {
 				return false;
 			}

-			const session = new RTCSession(this._ua);
+			const session = new RTCSession(this.ua);

 			session.on('progress', ({ response }) => {
 				notifier.notify(response.status_code, response.reason_phrase);
@@ -2392,7 +2392,7 @@ module.exports = class RTCSession extends EventEmitter {
 				return false;
 			}

-			const session = new RTCSession(this._ua);
+			const session = new RTCSession(this.ua);

 			// Terminate the current session when the new one is confirmed.
 			session.on('confirmed', () => {
@@ -2423,7 +2423,7 @@ module.exports = class RTCSession extends EventEmitter {
 	 * Initial Request Sender
 	 */
 	_sendInitialRequest(mediaConstraints, rtcOfferConstraints, mediaStream) {
-		const request_sender = new RequestSender(this._ua, this._request, {
+		const request_sender = new RequestSender(this.ua, this._request, {
 			onRequestTimeout: () => {
 				this.onRequestTimeout();
 			},
@@ -3236,7 +3236,7 @@ module.exports = class RTCSession extends EventEmitter {
 	_newRTCSession(originator, request) {
 		logger.debug('newRTCSession()');

-		this._ua.newRTCSession(this, {
+		this.ua.newRTCSession(this, {
 			originator,
 			session: this,
 			request,
@@ -3378,4 +3378,6 @@ module.exports = class RTCSession extends EventEmitter {
 			video,
 		});
 	}
-};
+}
+
+module.exports = { RTCSession };
diff --git a/src/RTCSession/ReferSubscriber.ts b/src/RTCSession/ReferSubscriber.ts
index 91365f6..6d03a0f 100644
--- a/src/RTCSession/ReferSubscriber.ts
+++ b/src/RTCSession/ReferSubscriber.ts
@@ -114,8 +114,7 @@ export type SendReferOptions = {
  */
 export interface ReferSubscriberSession {
 	readonly contact: string;
-	// The session exposes no accessor for the UA it belongs to.
-	readonly _ua: {
+	readonly ua: {
 		readonly configuration: { uri: URI };
 	};

@@ -229,7 +228,7 @@ export class ReferSubscriber extends EventEmitter {
 				header.toLowerCase().startsWith('referred-by:')
 			)
 		) {
-			const uri = this.#session._ua.configuration.uri;
+			const uri = this.#session.ua.configuration.uri;

 			const referredBy = `Referred-By: <${uri.scheme}:${uri.user}@${uri.host}>`;

@@ -256,8 +255,8 @@ export class ReferSubscriber extends EventEmitter {
 				onDialogError: () => {
 					this.#requestFailed(null, JsSIP_C.causes.DIALOG_ERROR);
 				},
-				onAuthenticated: _request => {
-					this.#id = _request.cseq;
+				onAuthenticated: authenticated_request => {
+					this.#id = authenticated_request.cseq;
 					this.emit('authenticated');
 				},
 			},
diff --git a/src/Subscriber.ts b/src/Subscriber.ts
index 14b73a5..07a98dd 100644
--- a/src/Subscriber.ts
+++ b/src/Subscriber.ts
@@ -203,7 +203,7 @@ export class Subscriber
 	 *
 	 * @internal
 	 */
-	readonly _ua: SubscriberUA;
+	readonly ua: SubscriberUA;

 	#target: URI;
 	#expires: number;
@@ -287,9 +287,9 @@ export class Subscriber
 			throw new TypeError('Missing Event header field');
 		}

-		this._ua = ua;
+		this.ua = ua;

-		const normalized = this._ua.normalizeTarget(target);
+		const normalized = this.ua.normalizeTarget(target);

 		if (!normalized) {
 			throw new TypeError(`Invalid target: ${target.toString()}`);
@@ -310,7 +310,7 @@ export class Subscriber
 		this.#params = Utils.cloneObject(params);

 		if (!this.#params.from_uri) {
-			this.#params.from_uri = this._ua.configuration.uri;
+			this.#params.from_uri = this.ua.configuration.uri;
 		}

 		this.#params.from_tag = Utils.newTag();
@@ -339,7 +339,7 @@ export class Subscriber
 		]);

 		if (!this.#headers.find(header => header.startsWith('Contact'))) {
-			const contact = `Contact: ${this._ua.contact.toString()}`;
+			const contact = `Contact: ${this.ua.contact.toString()}`;

 			this.#headers.push(contact);
 		}
@@ -381,8 +381,8 @@ export class Subscriber
 	/**
 	 * Replaces whatever was kept along with the subscriber.
 	 */
-	set data(_data: unknown) {
-		this.#data = _data;
+	set data(data: unknown) {
+		this.#data = data;
 	}

 	/**
@@ -415,7 +415,7 @@ export class Subscriber
 	 */
 	matchEarlyNotify(
 		call_id: string | undefined,
-		to_tag: string | undefined
+		to_tag: string | null | undefined
 	): boolean {
 		return (
 			this.#dialog === null &&
@@ -668,7 +668,7 @@ export class Subscriber
 			this.#dialog = null;
 		}

-		this._ua.destroySubscriber(this);
+		this.ua.destroySubscriber(this);

 		logger.debug(`emit "terminated" code=${terminationCode}`);

@@ -687,12 +687,12 @@ export class Subscriber

 		this.#state = State.WAITING_NOTIFY;

-		this._ua.newSubscriber(this);
+		this.ua.newSubscriber(this);

 		const request = new SIPMessage.OutgoingRequest(
 			JsSIP_C.SUBSCRIBE,
 			this.#target,
-			this._ua,
+			this.ua,
 			this.#params,
 			headers,
 			// A request carries no body either way, but the field is typed as
@@ -702,7 +702,7 @@ export class Subscriber

 		this.#initial_cseq = request.cseq;

-		const request_sender = new RequestSender(this._ua, request, {
+		const request_sender = new RequestSender(this.ua, request, {
 			onRequestTimeout: () => {
 				this.onRequestTimeout();
 			},
@@ -821,7 +821,7 @@ export class Subscriber
 			// (RFC 6665 4.1.2.3).
 			if (this.#terminated) {
 				// A stopped UA drops every incoming request, the final NOTIFY too.
-				if (this._ua.status === this._ua.C.STATUS_USER_CLOSED) {
+				if (this.ua.status === this.ua.C.STATUS_USER_CLOSED) {
 					this.#terminateDialog(
 						TerminationCode.UA_STOPPED,
 						undefined,
diff --git a/src/Transactions.ts b/src/Transactions.ts
index 9ae8846..5d187ba 100644
--- a/src/Transactions.ts
+++ b/src/Transactions.ts
@@ -773,14 +773,14 @@ export class InviteServerTransaction extends EventEmitter {
  *  _false_ new request
  */
 export function checkTransaction(
-	{ _transactions }: { _transactions: TransactionRegistry },
+	{ transactions }: { transactions: TransactionRegistry },
 	request: SIPMessage.IncomingRequest
 ): boolean | undefined {
 	// NOTE: `tr` is declared per case so that each one gets the matching
 	// transaction type.
 	switch (request.method) {
 		case JsSIP_C.INVITE: {
-			const tr = _transactions.ist[request.via_branch!];
+			const tr = transactions.ist[request.via_branch!];

 			if (tr) {
 				switch (tr.state) {
@@ -801,7 +801,7 @@ export function checkTransaction(
 			break;
 		}
 		case JsSIP_C.ACK: {
-			const tr = _transactions.ist[request.via_branch!];
+			const tr = transactions.ist[request.via_branch!];

 			// RFC 6026 7.1.
 			if (tr) {
@@ -823,7 +823,7 @@ export function checkTransaction(
 			break;
 		}
 		case JsSIP_C.CANCEL: {
-			const tr = _transactions.ist[request.via_branch!];
+			const tr = transactions.ist[request.via_branch!];

 			if (tr) {
 				request.reply_sl(200);
@@ -840,7 +840,7 @@ export function checkTransaction(
 		}
 		default: {
 			// Non-INVITE Server Transaction RFC 3261 17.2.2.
-			const tr = _transactions.nist[request.via_branch!];
+			const tr = transactions.nist[request.via_branch!];

 			if (tr) {
 				switch (tr.state) {
diff --git a/src/UA.d.ts b/src/UA.d.ts
deleted file mode 100644
index 649209b..0000000
--- a/src/UA.d.ts
+++ /dev/null
@@ -1,296 +0,0 @@
-import { EventEmitter } from 'events';
-
-import { Socket, WeightedSocket } from './Socket';
-import {
-	AnswerOptions,
-	Originator,
-	RTCSession,
-	RTCSessionEventMap,
-	TerminateOptions,
-} from './RTCSession';
-import {
-	IncomingRequest,
-	IncomingResponse,
-	OutgoingRequest,
-} from './SIPMessage';
-import { Message, SendMessageOptions } from './Message';
-import { Options, SendOptionsOptions } from './Options';
-import { Registrator } from './Registrator';
-import { Notifier, NotifierOptions } from './Notifier';
-import { Subscriber, SubscriberOptions } from './Subscriber';
-import URI = require('./URI');
-import { causes } from './Constants';
-import { Configuration } from './Configuration';
-import { Transport } from './Transport';
-
-export interface UnRegisterOptions {
-	all?: boolean;
-}
-
-export interface CallOptions extends AnswerOptions {
-	eventHandlers?: Partial<RTCSessionEventMap>;
-	anonymous?: boolean;
-	fromUserName?: string;
-	fromDisplayName?: string;
-}
-
-export interface UAConfiguration {
-	// mandatory parameters
-	sockets: Socket | Socket[] | WeightedSocket[];
-	uri: string;
-	// optional parameters
-	authorization_jwt?: string;
-	authorization_user?: string;
-	connection_recovery_max_interval?: number;
-	connection_recovery_min_interval?: number;
-	contact_uri?: string;
-	display_name?: string;
-	instance_id?: string;
-	no_answer_timeout?: number;
-	session_timers?: boolean;
-	session_timers_refresh_method?: string;
-	session_timers_force_refresher?: boolean;
-	password?: string;
-	realm?: string;
-	ha1?: string;
-	register?: boolean;
-	register_expires?: number;
-	register_from_tag_trail?: string | (() => string);
-	registrar_server?: string;
-	use_preloaded_route?: boolean;
-	user_agent?: string;
-	extra_headers?: string[];
-}
-
-export interface IncomingRTCSessionEvent {
-	originator: Originator.REMOTE;
-	session: RTCSession;
-	request: IncomingRequest;
-}
-
-export interface OutgoingRTCSessionEvent {
-	originator: Originator.LOCAL;
-	session: RTCSession;
-	request: OutgoingRequest;
-}
-
-export type RTCSessionEvent = IncomingRTCSessionEvent | OutgoingRTCSessionEvent;
-
-export interface ConnectingEvent {
-	socket: Socket;
-	attempts: number;
-}
-
-export interface ConnectedEvent {
-	socket: Socket;
-}
-
-export interface DisconnectEvent {
-	socket: Socket;
-	error: boolean;
-	code?: number;
-	reason?: string;
-}
-
-export interface RegisteredEvent {
-	response: IncomingResponse;
-	/**
-	 * Binding lifetime in seconds granted by the registrar, as given. JsSIP
-	 * refreshes the binding before it elapses, but a registrar that stops
-	 * answering leaves the binding to expire at this deadline.
-	 */
-	expires: number;
-}
-
-export interface UnRegisteredEvent {
-	response: IncomingResponse;
-	cause?: causes;
-}
-
-export interface IncomingMessageEvent {
-	originator: Originator.REMOTE;
-	message: Message;
-	request: IncomingRequest;
-}
-
-export interface OutgoingMessageEvent {
-	originator: Originator.LOCAL;
-	message: Message;
-	request: OutgoingRequest;
-}
-
-export interface IncomingOptionsEvent {
-	originator: Originator.REMOTE;
-	message: Options;
-	request: IncomingRequest;
-}
-
-export interface OutgoingOptionsEvent {
-	originator: Originator.LOCAL;
-	message: Options;
-	request: OutgoingRequest;
-}
-
-export type ConnectingListener = (event: ConnectingEvent) => void;
-export type ConnectedListener = (event: ConnectedEvent) => void;
-export type DisconnectedListener = (event: DisconnectEvent) => void;
-export type RegisteredListener = (event: RegisteredEvent) => void;
-export type RegistrationRefreshedListener = RegisteredListener;
-export type UnRegisteredListener = (event: UnRegisteredEvent) => void;
-export type RegistrationFailedListener = UnRegisteredListener;
-export type RegistrationExpiringListener = () => void;
-export type IncomingRTCSessionListener = (
-	event: IncomingRTCSessionEvent
-) => void;
-export type OutgoingRTCSessionListener = (
-	event: OutgoingRTCSessionEvent
-) => void;
-export type RTCSessionListener =
-	| IncomingRTCSessionListener
-	| OutgoingRTCSessionListener;
-export type IncomingMessageListener = (event: IncomingMessageEvent) => void;
-export type OutgoingMessageListener = (event: OutgoingMessageEvent) => void;
-export type MessageListener = IncomingMessageListener | OutgoingMessageListener;
-export type IncomingOptionsListener = (event: IncomingOptionsEvent) => void;
-export type OutgoingOptionsListener = (event: OutgoingOptionsEvent) => void;
-export type OptionsListener = IncomingOptionsListener | OutgoingOptionsListener;
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-export type SipEventListener = <T = any>(event: {
-	event: T;
-	request: IncomingRequest;
-}) => void;
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-export type SipSubscribeListener = <T = any>(event: {
-	event: T;
-	request: IncomingRequest;
-}) => void;
-
-export interface UAEventMap {
-	connecting: ConnectingListener;
-	connected: ConnectedListener;
-	disconnected: DisconnectedListener;
-	registered: RegisteredListener;
-	registrationRefreshed: RegistrationRefreshedListener;
-	unregistered: UnRegisteredListener;
-	registrationFailed: RegistrationFailedListener;
-	registrationExpiring: RegistrationExpiringListener;
-	newRTCSession: RTCSessionListener;
-	newMessage: MessageListener;
-	sipEvent: SipEventListener;
-	newSubscribe: SipSubscribeListener;
-	newOptions: OptionsListener;
-}
-
-export interface UAContactOptions {
-	anonymous?: boolean;
-	outbound?: boolean;
-}
-
-export interface UAContact {
-	pub_gruu?: string;
-	temp_gruu?: string;
-	uri: URI;
-
-	toString(options?: UAContactOptions): string;
-}
-
-export interface RequestParams {
-	from_uri: URI;
-	from_display_name?: string;
-	from_tag: string;
-	to_uri: URI;
-	to_display_name?: string;
-	to_tag?: string;
-	call_id: string;
-	cseq: number;
-}
-
-export interface SubscriberParams {
-	from_uri: URI;
-	from_display_name?: string;
-	to_uri: URI;
-	to_display_name?: string;
-}
-
-export { NotifierOptions, SubscriberOptions };
-
-declare enum UAStatus {
-	// UA status codes.
-	STATUS_INIT = 0,
-	STATUS_READY = 1,
-	STATUS_USER_CLOSED = 2,
-	STATUS_NOT_READY = 3,
-	// UA error codes.
-	// eslint-disable-next-line @typescript-eslint/no-duplicate-enum-values
-	CONFIGURATION_ERROR = 1,
-	// eslint-disable-next-line @typescript-eslint/no-duplicate-enum-values
-	NETWORK_ERROR = 2,
-}
-
-export class UA extends EventEmitter {
-	static get C(): typeof UAStatus;
-
-	constructor(configuration: UAConfiguration);
-
-	get C(): typeof UAStatus;
-
-	get status(): UAStatus;
-
-	get contact(): UAContact;
-
-	get configuration(): Configuration;
-
-	get transport(): Transport;
-
-	start(): void;
-
-	stop(): void;
-
-	register(): void;
-
-	unregister(options?: UnRegisterOptions): void;
-
-	registrator(): Registrator;
-
-	call(target: string, options?: CallOptions): RTCSession;
-
-	sendMessage(
-		target: string | URI,
-		body: string,
-		options?: SendMessageOptions
-	): Message;
-
-	sendOptions(
-		target: string | URI,
-		body?: string,
-		options?: SendOptionsOptions
-	): Options;
-
-	subscribe(
-		target: string,
-		eventName: string,
-		accept: string,
-		options?: SubscriberOptions
-	): Subscriber;
-
-	notify(
-		subscribe: IncomingRequest,
-		contentType: string,
-		options?: NotifierOptions
-	): Notifier;
-
-	terminateSessions(options?: TerminateOptions): void;
-
-	isRegistered(): boolean;
-
-	isConnected(): boolean;
-
-	get<T extends keyof UAConfiguration>(parameter: T): UAConfiguration[T];
-
-	set<T extends keyof UAConfiguration>(
-		parameter: T,
-		value: UAConfiguration[T]
-	): boolean;
-
-	on<T extends keyof UAEventMap>(type: T, listener: UAEventMap[T]): this;
-}
diff --git a/src/UA.js b/src/UA.js
deleted file mode 100644
index 4aed61c..0000000
--- a/src/UA.js
+++ /dev/null
@@ -1,1202 +0,0 @@
-/* eslint-disable no-invalid-this */
-
-const EventEmitter = require('events').EventEmitter;
-const { Logger } = require('./Logger');
-const JsSIP_C = require('./Constants');
-const { Registrator } = require('./Registrator');
-const RTCSession = require('./RTCSession');
-const { Subscriber } = require('./Subscriber');
-const { Notifier } = require('./Notifier');
-const { Message } = require('./Message');
-const { Options } = require('./Options');
-const Transactions = require('./Transactions');
-const { Transport } = require('./Transport');
-const Utils = require('./Utils');
-const Exceptions = require('./Exceptions');
-const URI = require('./URI');
-const Parser = require('./Parser');
-const SIPMessage = require('./SIPMessage');
-const { sanityCheck } = require('./sanityCheck');
-const config = require('./Configuration');
-
-const logger = new Logger('UA');
-
-/**
- * How long stop() waits for the transactions pending at that moment, so that
- * the requests it sends (un-REGISTER, BYE, un-SUBSCRIBE) get a chance to be
- * answered before the transport goes away.
- */
-const CLOSE_TIMEOUT = 2000;
-
-const C = {
-	// UA status codes.
-	STATUS_INIT: 0,
-	STATUS_READY: 1,
-	STATUS_USER_CLOSED: 2,
-	STATUS_NOT_READY: 3,
-
-	// UA error codes.
-	CONFIGURATION_ERROR: 1,
-	NETWORK_ERROR: 2,
-};
-
-/**
- * The User-Agent class.
- * @class JsSIP.UA
- * @param {Object} configuration Configuration parameters.
- * @throws {JsSIP.Exceptions.ConfigurationError} If a configuration parameter is invalid.
- * @throws {TypeError} If no configuration is given.
- */
-module.exports = class UA extends EventEmitter {
-	// Expose C object.
-	static get C() {
-		return C;
-	}
-
-	constructor(configuration) {
-		// Check configuration argument.
-		if (!configuration) {
-			throw new TypeError('Not enough arguments');
-		}
-
-		// Hide sensitive information.
-		const sensitiveKeys = ['password', 'ha1', 'authorization_jwt'];
-
-		logger.debug(
-			'new() [configuration:%o]',
-			Object.entries(configuration).filter(
-				([key]) => !sensitiveKeys.includes(key)
-			)
-		);
-
-		super();
-
-		this._cache = {
-			credentials: {},
-		};
-
-		this._configuration = Object.assign({}, config.DEFAULT_CONFIGURATION);
-		this._dynConfiguration = {};
-		this._dialogs = {};
-
-		// User actions outside any session/dialog (MESSAGE/OPTIONS).
-		this._applicants = {};
-
-		this._sessions = {};
-
-		// Subscriber instances with a subscription sent or established.
-		this._subscribers = new Set();
-
-		this._transport = null;
-		this._contact = null;
-		this._status = C.STATUS_INIT;
-		this._error = null;
-		this._transactions = {
-			nist: {},
-			nict: {},
-			ist: {},
-			ict: {},
-		};
-
-		// Custom UA empty object for high level use.
-		this._data = {};
-
-		this._closeTimer = null;
-
-		// Load configuration.
-		try {
-			this._loadConfig(configuration);
-		} catch (error) {
-			this._status = C.STATUS_NOT_READY;
-			this._error = C.CONFIGURATION_ERROR;
-			throw error;
-		}
-
-		// Initialize registrator.
-		this._registrator = new Registrator(this);
-	}
-
-	get C() {
-		return C;
-	}
-
-	get status() {
-		return this._status;
-	}
-
-	get contact() {
-		return this._contact;
-	}
-
-	get configuration() {
-		return this._configuration;
-	}
-
-	get transport() {
-		return this._transport;
-	}
-
-	// =================
-	//  High Level API
-	// =================
-
-	/**
-	 * Connect to the server if status = STATUS_INIT.
-	 * Resume UA after being closed.
-	 */
-	start() {
-		logger.debug('start()');
-
-		if (this._status === C.STATUS_INIT) {
-			this._transport.connect();
-		} else if (this._status === C.STATUS_USER_CLOSED) {
-			logger.debug('restarting UA');
-
-			// Disconnect.
-			if (this._closeTimer !== null) {
-				clearTimeout(this._closeTimer);
-				this._closeTimer = null;
-				this._transport.disconnect();
-			}
-
-			// Reconnect.
-			this._status = C.STATUS_INIT;
-			this._transport.connect();
-		} else if (this._status === C.STATUS_READY) {
-			logger.debug('UA is in READY status, not restarted');
-		} else {
-			logger.debug(
-				'ERROR: connection is down, Auto-Recovery system is trying to reconnect'
-			);
-		}
-
-		// Set dynamic configuration.
-		this._dynConfiguration.register = this._configuration.register;
-	}
-
-	/**
-	 * Register.
-	 */
-	register() {
-		logger.debug('register()');
-
-		this._dynConfiguration.register = true;
-		this._registrator.register();
-	}
-
-	/**
-	 * Unregister.
-	 */
-	unregister(options) {
-		logger.debug('unregister()');
-
-		this._dynConfiguration.register = false;
-		this._registrator.unregister(options);
-	}
-
-	/**
-	 * Get the Registrator instance.
-	 */
-	registrator() {
-		return this._registrator;
-	}
-
-	/**
-	 * Registration state.
-	 */
-	isRegistered() {
-		return this._registrator.registered;
-	}
-
-	/**
-	 * Connection state.
-	 */
-	isConnected() {
-		return this._transport.isConnected();
-	}
-
-	/**
-	 * Make an outgoing call.
-	 *
-	 * -param {String} target
-	 * -param {Object} [options]
-	 *
-	 * -throws {TypeError}
-	 *
-	 */
-	call(target, options) {
-		logger.debug('call()');
-
-		const session = new RTCSession(this);
-
-		session.connect(target, options);
-
-		return session;
-	}
-
-	/**
-	 * Send a message.
-	 *
-	 * -param {String} target
-	 * -param {String} body
-	 * -param {Object} [options]
-	 *
-	 * -throws {TypeError}
-	 *
-	 */
-	sendMessage(target, body, options) {
-		logger.debug('sendMessage()');
-
-		const message = new Message(this);
-
-		message.send(target, body, options);
-
-		return message;
-	}
-
-	/**
-	 * Create subscriber instance
-	 */
-	subscribe(target, eventName, accept, options) {
-		logger.debug('subscribe()');
-
-		return new Subscriber(this, target, eventName, accept, options);
-	}
-
-	/**
-	 * Create notifier instance
-	 */
-	notify(subscribe, contentType, options) {
-		logger.debug('notify()');
-
-		return new Notifier(this, subscribe, contentType, options);
-	}
-
-	/**
-	 * Send a SIP OPTIONS.
-	 *
-	 * -param {String} target
-	 * -param {String} [body]
-	 * -param {Object} [options]
-	 *
-	 * -throws {TypeError}
-	 *
-	 */
-	sendOptions(target, body, options) {
-		logger.debug('sendOptions()');
-
-		const message = new Options(this);
-
-		message.send(target, body, options);
-
-		return message;
-	}
-
-	/**
-	 * Terminate ongoing sessions.
-	 */
-	terminateSessions(options) {
-		logger.debug('terminateSessions()');
-
-		for (const idx in this._sessions) {
-			if (!this._sessions[idx].isEnded()) {
-				this._sessions[idx].terminate(options);
-			}
-		}
-	}
-
-	/**
-	 * Gracefully close.
-	 *
-	 */
-	stop() {
-		logger.debug('stop()');
-
-		// Remove dynamic settings.
-		this._dynConfiguration = {};
-
-		if (this._status === C.STATUS_USER_CLOSED) {
-			logger.debug('UA already closed');
-
-			return;
-		}
-
-		// Close registrator.
-		this._registrator.close();
-
-		// Run  _terminate_ on every Session.
-		for (const session in this._sessions) {
-			if (Object.prototype.hasOwnProperty.call(this._sessions, session)) {
-				logger.debug(`closing session ${session}`);
-				try {
-					this._sessions[session].terminate();
-				} catch (error) {}
-			}
-		}
-
-		// Unsubscribe every subscription. The un-SUBSCRIBE must leave before
-		// the UA is closed, so that the server does not keep sending NOTIFY
-		// requests to a gone UA until the subscription expires.
-		for (const subscriber of this._subscribers) {
-			logger.debug('closing subscriber');
-			try {
-				subscriber.terminate();
-			} catch (error) {}
-		}
-
-		// Run  _close_ on every applicant.
-		for (const applicant in this._applicants) {
-			if (Object.prototype.hasOwnProperty.call(this._applicants, applicant)) {
-				try {
-					this._applicants[applicant].close();
-				} catch (error) {}
-			}
-		}
-
-		this._status = C.STATUS_USER_CLOSED;
-
-		// Give some time for the requests sent above to be answered. _mayClose()
-		// closes as soon as they are.
-		this._closeTimer = setTimeout(() => this._close(), CLOSE_TIMEOUT);
-
-		this._mayClose();
-	}
-
-	/**
-	 * Normalice a string into a valid SIP request URI
-	 * -param {String} target
-	 * -returns {JsSIP.URI|undefined}
-	 */
-	normalizeTarget(target) {
-		return Utils.normalizeTarget(target, this._configuration.hostport_params);
-	}
-
-	/**
-	 * Allow retrieving configuration and autogenerated fields in runtime.
-	 */
-	get(parameter) {
-		switch (parameter) {
-			case 'authorization_user': {
-				return this._configuration.authorization_user;
-			}
-
-			case 'realm': {
-				return this._configuration.realm;
-			}
-
-			case 'ha1': {
-				return this._configuration.ha1;
-			}
-
-			case 'authorization_jwt': {
-				return this._configuration.authorization_jwt;
-			}
-
-			default: {
-				logger.warn('get() | cannot get "%s" parameter in runtime', parameter);
-
-				return undefined;
-			}
-		}
-	}
-
-	/**
-	 * Allow configuration changes in runtime.
-	 * Returns true if the parameter could be set.
-	 */
-	set(parameter, value) {
-		switch (parameter) {
-			case 'authorization_user': {
-				this._configuration.authorization_user = String(value);
-				break;
-			}
-
-			case 'password': {
-				this._configuration.password = String(value);
-				break;
-			}
-
-			case 'realm': {
-				this._configuration.realm = String(value);
-				break;
-			}
-
-			case 'ha1': {
-				this._configuration.ha1 = String(value);
-				// Delete the plain SIP password.
-				this._configuration.password = null;
-				break;
-			}
-
-			case 'authorization_jwt': {
-				this._configuration.authorization_jwt = String(value);
-				break;
-			}
-
-			case 'display_name': {
-				this._configuration.display_name = value;
-				break;
-			}
-
-			case 'extra_headers': {
-				this._configuration.extra_headers = value;
-				break;
-			}
-
-			default: {
-				logger.warn('set() | cannot set "%s" parameter in runtime', parameter);
-
-				return false;
-			}
-		}
-
-		return true;
-	}
-
-	// ==========================
-	// Event Handlers.
-	// ==========================
-
-	/**
-	 * new Transaction
-	 */
-	newTransaction(transaction) {
-		this._transactions[transaction.type][transaction.id] = transaction;
-		this.emit('newTransaction', {
-			transaction,
-		});
-	}
-
-	/**
-	 * Transaction destroyed.
-	 */
-	destroyTransaction(transaction) {
-		delete this._transactions[transaction.type][transaction.id];
-		this.emit('transactionDestroyed', {
-			transaction,
-		});
-
-		this._mayClose();
-	}
-
-	/**
-	 * new Dialog
-	 */
-	newDialog(dialog) {
-		this._dialogs[dialog.id] = dialog;
-	}
-
-	/**
-	 * Dialog destroyed.
-	 */
-	destroyDialog(dialog) {
-		delete this._dialogs[dialog.id];
-	}
-
-	/**
-	 *  new Message
-	 */
-	newMessage(message, data) {
-		this._applicants[message] = message;
-		this.emit('newMessage', data);
-	}
-
-	/**
-	 *  new Options
-	 */
-	newOptions(message, data) {
-		this._applicants[message] = message;
-		this.emit('newOptions', data);
-	}
-
-	/**
-	 *  Message destroyed.
-	 */
-	destroyMessage(message) {
-		delete this._applicants[message];
-	}
-
-	/**
-	 *  Options destroyed.
-	 */
-	destroyOptions(options) {
-		delete this._applicants[options];
-	}
-
-	/**
-	 * Subscriber sent its initial SUBSCRIBE.
-	 */
-	newSubscriber(subscriber) {
-		this._subscribers.add(subscriber);
-	}
-
-	/**
-	 * Subscriber terminated.
-	 */
-	destroySubscriber(subscriber) {
-		this._subscribers.delete(subscriber);
-	}
-
-	/**
-	 * new RTCSession
-	 */
-	newRTCSession(session, data) {
-		this._sessions[session.id] = session;
-		this.emit('newRTCSession', data);
-	}
-
-	/**
-	 * RTCSession destroyed.
-	 */
-	destroyRTCSession(session) {
-		delete this._sessions[session.id];
-
-		this._mayClose();
-	}
-
-	/**
-	 * Registered
-	 */
-	registered(data) {
-		this.emit('registered', data);
-	}
-
-	/**
-	 * Registration Refreshed
-	 */
-	registrationRefreshed(data) {
-		this.emit('registrationRefreshed', data);
-	}
-
-	/**
-	 * Unregistered
-	 */
-	unregistered(data) {
-		this.emit('unregistered', data);
-	}
-
-	/**
-	 * Registration Failed
-	 */
-	registrationFailed(data) {
-		this.emit('registrationFailed', data);
-	}
-
-	// =========================
-	// ReceiveRequest.
-	// =========================
-
-	/**
-	 * Request reception
-	 */
-	receiveRequest(request) {
-		const method = request.method;
-
-		// Check that request URI points to us.
-		if (!this._doesRuriPointToUs(request.ruri)) {
-			logger.debug('Request-URI does not point to us');
-			if (request.method !== JsSIP_C.ACK) {
-				request.reply_sl(404);
-			}
-
-			return;
-		}
-
-		// Check request URI scheme.
-		if (request.ruri.scheme === JsSIP_C.SIPS) {
-			request.reply_sl(416);
-
-			return;
-		}
-
-		// Check transaction.
-		if (Transactions.checkTransaction(this, request)) {
-			return;
-		}
-
-		// Create the server transaction.
-		if (method === JsSIP_C.INVITE) {
-			/* eslint-disable no-new */
-			new Transactions.InviteServerTransaction(this, this._transport, request);
-			/* eslint-enable no-new */
-		} else if (method !== JsSIP_C.ACK && method !== JsSIP_C.CANCEL) {
-			/* eslint-disable no-new */
-			new Transactions.NonInviteServerTransaction(
-				this,
-				this._transport,
-				request
-			);
-			/* eslint-enable no-new */
-		}
-
-		// RFC3261 12.2.2
-		// Requests that do not change in any way the state of a dialog may be
-		// received within a dialog (for example, an OPTIONS request).
-		// They are processed as if they had been received outside the dialog.
-		if (method === JsSIP_C.OPTIONS) {
-			if (this.listeners('newOptions').length === 0) {
-				request.reply(200);
-
-				return;
-			}
-
-			const message = new Options(this);
-
-			message.init_incoming(request);
-		} else if (method === JsSIP_C.MESSAGE) {
-			if (this.listeners('newMessage').length === 0) {
-				request.reply(405);
-
-				return;
-			}
-			const message = new Message(this);
-
-			message.init_incoming(request);
-		} else if (method === JsSIP_C.SUBSCRIBE) {
-			if (this.listeners('newSubscribe').length === 0) {
-				request.reply(405);
-
-				return;
-			}
-		} else if (method === JsSIP_C.INVITE) {
-			// Initial INVITE.
-			if (!request.to_tag && this.listeners('newRTCSession').length === 0) {
-				request.reply(405);
-
-				return;
-			}
-		}
-
-		let dialog;
-		let session;
-
-		// Initial Request.
-		if (!request.to_tag) {
-			switch (method) {
-				case JsSIP_C.INVITE: {
-					// eslint-disable-next-line no-undef
-					if (window.RTCPeerConnection) {
-						// TODO
-						if (request.hasHeader('replaces')) {
-							const replaces = request.replaces;
-
-							dialog = this._findDialog(
-								replaces.call_id,
-								replaces.from_tag,
-								replaces.to_tag
-							);
-							if (dialog) {
-								session = dialog.owner;
-								if (!session.isEnded()) {
-									session.receiveRequest(request);
-								} else {
-									request.reply(603);
-								}
-							} else {
-								request.reply(481);
-							}
-						} else {
-							session = new RTCSession(this);
-							session.init_incoming(request);
-						}
-					} else {
-						logger.warn('INVITE received but WebRTC is not supported');
-						request.reply(488);
-					}
-					break;
-				}
-				case JsSIP_C.BYE: {
-					// Out of dialog BYE received.
-					request.reply(481);
-					break;
-				}
-				case JsSIP_C.CANCEL: {
-					session = this._findSession(request);
-					if (session) {
-						session.receiveRequest(request);
-					} else {
-						logger.debug('received CANCEL request for a non existent session');
-					}
-					break;
-				}
-				case JsSIP_C.ACK: {
-					// Absorb it.
-					// ACK request without a corresponding Invite Transaction
-					// and without To tag.
-					break;
-				}
-				case JsSIP_C.NOTIFY: {
-					// Receive new sip event.
-					this.emit('sipEvent', {
-						event: request.event,
-						request,
-					});
-					request.reply(200);
-					break;
-				}
-				case JsSIP_C.SUBSCRIBE: {
-					Notifier.init_incoming(request, () => {
-						this.emit('newSubscribe', {
-							event: request.event,
-							request,
-						});
-					});
-					break;
-				}
-				default: {
-					request.reply(405);
-					break;
-				}
-			}
-		}
-		// In-dialog request.
-		else {
-			dialog = this._findDialog(
-				request.call_id,
-				request.from_tag,
-				request.to_tag
-			);
-
-			if (dialog) {
-				dialog.receiveRequest(request);
-			} else if (method === JsSIP_C.NOTIFY) {
-				session = this._findSession(request);
-
-				if (session) {
-					session.receiveRequest(request);
-				} else {
-					const subscriber = this._findEarlyNotifySubscriber(request);
-
-					if (subscriber) {
-						subscriber.receiveEarlyNotify(request);
-					} else {
-						logger.debug(
-							'received NOTIFY request for a non existent subscription'
-						);
-						request.reply(481, 'Subscription does not exist');
-					}
-				}
-			} else if (method !== JsSIP_C.ACK) {
-				// RFC3261 12.2.2
-				// Request with to tag, but no matching dialog found.
-				// Exception: ACK for an Invite request for which a dialog has not
-				// been created.
-				request.reply(481);
-			}
-		}
-	}
-
-	// =================
-	// Utils.
-	// =================
-
-	/**
-	 * Whether the UA has anything left to wait for.
-	 *
-	 * Sessions are looked at besides the transactions because a session sits
-	 * here with none of its own once its dialog is confirmed. Subscribers and
-	 * applicants are not: each is destroyed while handling the response to its
-	 * last request, a tick before the transaction that carried it.
-	 */
-	_isIdle() {
-		return (
-			Object.keys(this._sessions).length === 0 &&
-			Object.keys(this._transactions.nict).length === 0 &&
-			Object.keys(this._transactions.nist).length === 0 &&
-			Object.keys(this._transactions.ict).length === 0 &&
-			Object.keys(this._transactions.ist).length === 0
-		);
-	}
-
-	/**
-	 * Ends the shutdown begun by stop().
-	 */
-	_close() {
-		this._closeTimer = null;
-		this._transport.disconnect();
-	}
-
-	/**
-	 * Closes a stopping UA as soon as what was pending when it was stopped is
-	 * done with, instead of waiting for the whole CLOSE_TIMEOUT.
-	 */
-	_mayClose() {
-		// A close timer is only pending while the UA is stopping.
-		if (this._closeTimer === null || !this._isIdle()) {
-			return;
-		}
-
-		clearTimeout(this._closeTimer);
-		this._close();
-	}
-
-	/**
-	 * Whether the Request-URI of an incoming request addresses this UA.
-	 */
-	_doesRuriPointToUs(ruri) {
-		if (
-			ruri.user === this._configuration.uri.user ||
-			ruri.user === this._contact.uri.user
-		) {
-			return true;
-		}
-
-		// The registrar is free to choose how the GRUUs it grants look (RFC
-		// 5627, Appendix A), and this UA advertises them in the Contact header
-		// of its outgoing requests, so requests targeted at them point to us.
-		for (const gruu of [this._contact.pub_gruu, this._contact.temp_gruu]) {
-			const uri = gruu ? URI.parse(gruu) : undefined;
-
-			// Compare AORs plus the 'gr' parameter, which is what identifies the
-			// instance (RFC 5627, Section 3.1). Any other parameter a proxy may
-			// have added on the way takes no part in the match.
-			if (
-				uri &&
-				uri.toAor() === ruri.toAor() &&
-				uri.getParam('gr') === ruri.getParam('gr')
-			) {
-				return true;
-			}
-		}
-
-		return false;
-	}
-
-	/**
-	 * Get the session to which the request belongs to, if any.
-	 */
-	_findSession({ call_id, from_tag, to_tag }) {
-		const sessionIDa = call_id + from_tag;
-		const sessionA = this._sessions[sessionIDa];
-		const sessionIDb = call_id + to_tag;
-		const sessionB = this._sessions[sessionIDb];
-
-		if (sessionA) {
-			return sessionA;
-		} else if (sessionB) {
-			return sessionB;
-		} else {
-			return null;
-		}
-	}
-
-	/**
-	 * Get the subscriber whose dialog is created by the given NOTIFY, if any.
-	 *
-	 * RFC 6665 4.1.2.4: the first NOTIFY of a subscription may arrive before
-	 * the 2xx response to the initial SUBSCRIBE, so there is no dialog yet.
-	 * Only a subscriber still waiting for that first NOTIFY matches; any later
-	 * NOTIFY is routed by `_findDialog()`.
-	 */
-	_findEarlyNotifySubscriber({ call_id, to_tag }) {
-		for (const subscriber of this._subscribers) {
-			if (subscriber.matchEarlyNotify(call_id, to_tag)) {
-				return subscriber;
-			}
-		}
-
-		return null;
-	}
-
-	/**
-	 * Get the dialog to which the request belongs to, if any.
-	 */
-	_findDialog(call_id, from_tag, to_tag) {
-		let id = call_id + from_tag + to_tag;
-		let dialog = this._dialogs[id];
-
-		if (dialog) {
-			return dialog;
-		} else {
-			id = call_id + to_tag + from_tag;
-			dialog = this._dialogs[id];
-			if (dialog) {
-				return dialog;
-			} else {
-				return null;
-			}
-		}
-	}
-
-	_loadConfig(configuration) {
-		// Check and load the given configuration.
-		// This can throw.
-		config.load(this._configuration, configuration);
-
-		// Post Configuration Process.
-
-		// Allow passing 0 number as display_name.
-		if (this._configuration.display_name === 0) {
-			this._configuration.display_name = '0';
-		}
-
-		// Instance-id for GRUU.
-		if (!this._configuration.instance_id) {
-			this._configuration.instance_id = Utils.newUUID();
-		}
-
-		// Jssip_id instance parameter. Static random tag of length 5.
-		this._configuration.jssip_id = Utils.createRandomToken(5);
-
-		// String containing this._configuration.uri without scheme and user.
-		const hostport_params = this._configuration.uri.clone();
-
-		hostport_params.user = null;
-		this._configuration.hostport_params = hostport_params
-			.toString()
-			.replace(/^sip:/i, '');
-
-		// Transport.
-		try {
-			this._transport = new Transport(this._configuration.sockets, {
-				// Recovery options.
-				max_interval: this._configuration.connection_recovery_max_interval,
-				min_interval: this._configuration.connection_recovery_min_interval,
-			});
-
-			// Transport event callbacks.
-			this._transport.onconnecting = onTransportConnecting.bind(this);
-			this._transport.onconnect = onTransportConnect.bind(this);
-			this._transport.ondisconnect = onTransportDisconnect.bind(this);
-			this._transport.ondata = onTransportData.bind(this);
-		} catch (error) {
-			logger.warn(error);
-			throw new Exceptions.ConfigurationError(
-				'sockets',
-				this._configuration.sockets
-			);
-		}
-
-		// Remove sockets instance from configuration object.
-		delete this._configuration.sockets;
-
-		// Check whether authorization_user is explicitly defined.
-		// Take 'this._configuration.uri.user' value if not.
-		if (!this._configuration.authorization_user) {
-			this._configuration.authorization_user = this._configuration.uri.user;
-		}
-
-		// If no 'registrar_server' is set use the 'uri' value without user portion and
-		// without URI params/headers.
-		if (!this._configuration.registrar_server) {
-			const registrar_server = this._configuration.uri.clone();
-
-			registrar_server.user = null;
-			registrar_server.clearParams();
-			registrar_server.clearHeaders();
-			this._configuration.registrar_server = registrar_server;
-		}
-
-		// User no_answer_timeout.
-		this._configuration.no_answer_timeout *= 1000;
-
-		// Via Host.
-		if (this._configuration.contact_uri) {
-			this._configuration.via_host = this._configuration.contact_uri.host;
-		}
-
-		// Contact URI.
-		else {
-			this._configuration.contact_uri = new URI(
-				'sip',
-				Utils.createRandomToken(8),
-				this._configuration.via_host,
-				null,
-				{ transport: 'ws' }
-			);
-		}
-
-		this._contact = {
-			pub_gruu: null,
-			temp_gruu: null,
-			uri: this._configuration.contact_uri,
-			toString(options = {}) {
-				const anonymous = options.anonymous || null;
-				const outbound = options.outbound || null;
-				let contact = '<';
-
-				if (anonymous) {
-					contact +=
-						this.temp_gruu || 'sip:anonymous@anonymous.invalid;transport=ws';
-				} else {
-					contact += this.pub_gruu || this.uri.toString();
-				}
-
-				if (outbound && (anonymous ? !this.temp_gruu : !this.pub_gruu)) {
-					contact += ';ob';
-				}
-
-				contact += '>';
-
-				return contact;
-			},
-		};
-
-		// Seal the configuration.
-		const writable_parameters = [
-			'authorization_user',
-			'password',
-			'realm',
-			'ha1',
-			'authorization_jwt',
-			'display_name',
-			'register',
-			'extra_headers',
-		];
-
-		for (const parameter in this._configuration) {
-			if (
-				Object.prototype.hasOwnProperty.call(this._configuration, parameter)
-			) {
-				if (writable_parameters.indexOf(parameter) !== -1) {
-					Object.defineProperty(this._configuration, parameter, {
-						writable: true,
-						configurable: false,
-					});
-				} else {
-					Object.defineProperty(this._configuration, parameter, {
-						writable: false,
-						configurable: false,
-					});
-				}
-			}
-		}
-
-		logger.debug('configuration parameters after validation:');
-		for (const parameter in this._configuration) {
-			// Only show the user user configurable parameters.
-			if (
-				Object.prototype.hasOwnProperty.call(
-					config.DEFAULT_CONFIGURATION,
-					parameter
-				)
-			) {
-				switch (parameter) {
-					case 'uri':
-					case 'registrar_server': {
-						logger.debug(`- ${parameter}: ${this._configuration[parameter]}`);
-						break;
-					}
-					case 'password':
-					case 'ha1':
-					case 'authorization_jwt': {
-						logger.debug(`- ${parameter}: NOT SHOWN`);
-						break;
-					}
-					default: {
-						logger.debug(
-							`- ${parameter}: ${JSON.stringify(this._configuration[parameter])}`
-						);
-					}
-				}
-			}
-		}
-
-		return;
-	}
-};
-
-/**
- * Transport event handlers
- */
-
-// Transport connecting event.
-function onTransportConnecting(data) {
-	this.emit('connecting', data);
-}
-
-// Transport connected event.
-function onTransportConnect(data) {
-	if (this._status === C.STATUS_USER_CLOSED) {
-		return;
-	}
-
-	this._status = C.STATUS_READY;
-	this._error = null;
-
-	this.emit('connected', data);
-
-	if (this._dynConfiguration.register) {
-		this._registrator.register();
-	}
-}
-
-// Transport disconnected event.
-function onTransportDisconnect(data) {
-	// Run _onTransportError_ callback on every client transaction using _transport_.
-	const client_transactions = ['nict', 'ict', 'nist', 'ist'];
-
-	for (const type of client_transactions) {
-		for (const id in this._transactions[type]) {
-			if (Object.prototype.hasOwnProperty.call(this._transactions[type], id)) {
-				this._transactions[type][id].onTransportError();
-			}
-		}
-	}
-
-	this.emit('disconnected', data);
-
-	// Call registrator _onTransportClosed_.
-	this._registrator.onTransportClosed();
-
-	if (this._status !== C.STATUS_USER_CLOSED) {
-		this._status = C.STATUS_NOT_READY;
-		this._error = C.NETWORK_ERROR;
-	}
-}
-
-// Transport data event.
-function onTransportData(data) {
-	const transport = data.transport;
-	let message = data.message;
-
-	message = Parser.parseMessage(message, this);
-
-	if (!message) {
-		return;
-	}
-
-	if (
-		this._status === C.STATUS_USER_CLOSED &&
-		message instanceof SIPMessage.IncomingRequest
-	) {
-		return;
-	}
-
-	// Do some sanity check.
-	if (!sanityCheck(message, this, transport)) {
-		return;
-	}
-
-	if (message instanceof SIPMessage.IncomingRequest) {
-		message.transport = transport;
-		this.receiveRequest(message);
-	} else if (message instanceof SIPMessage.IncomingResponse) {
-		// Unike stated in 18.1.2, if a response does not match
-		// any transaction, it is discarded here and no passed to the core
-		// in order to be discarded there.
-
-		let transaction;
-
-		switch (message.method) {
-			case JsSIP_C.INVITE: {
-				transaction = this._transactions.ict[message.via_branch];
-				if (transaction) {
-					transaction.receiveResponse(message);
-				}
-				break;
-			}
-			case JsSIP_C.ACK: {
-				// Just in case ;-).
-				break;
-			}
-			default: {
-				transaction = this._transactions.nict[message.via_branch];
-				if (transaction) {
-					transaction.receiveResponse(message);
-				}
-				break;
-			}
-		}
-	}
-}
diff --git a/src/UA.ts b/src/UA.ts
new file mode 100644
index 0000000..28f7a1d
--- /dev/null
+++ b/src/UA.ts
@@ -0,0 +1,1629 @@
+import { EventEmitter } from 'events';
+
+import * as config from './Configuration';
+import type { Configuration } from './Configuration';
+import * as JsSIP_C from './Constants';
+import type { Originator } from './Constants';
+import type { Dialog } from './Dialog';
+import { ConfigurationError } from './Exceptions';
+import { Logger } from './Logger';
+import { Message } from './Message';
+import type { SendMessageOptions } from './Message';
+import { Notifier } from './Notifier';
+import type { NotifierOptions } from './Notifier';
+import { Options } from './Options';
+import type { SendOptionsOptions } from './Options';
+import * as Parser from './Parser';
+import { Registrator } from './Registrator';
+import type {
+	RegisteredEvent,
+	UnregisteredEvent,
+	UnregisterOptions,
+} from './Registrator';
+import { RTCSession } from './RTCSession';
+import type {
+	AnswerOptions,
+	RTCSessionEventMap,
+	TerminateOptions,
+} from './RTCSession';
+import { sanityCheck } from './sanityCheck';
+import * as SIPMessage from './SIPMessage';
+import type { IncomingRequest, OutgoingRequest } from './SIPMessage';
+import type { Socket, WeightedSocket } from './Socket';
+import { Subscriber } from './Subscriber';
+import type { SubscriberOptions } from './Subscriber';
+import * as Transactions from './Transactions';
+import { Transport } from './Transport';
+import type {
+	TransportConnectedEvent,
+	TransportConnectingEvent,
+	TransportDataEvent,
+	TransportDisconnectedEvent,
+} from './Transport';
+import * as Utils from './Utils';
+import URI = require('./URI');
+
+const logger = new Logger('UA');
+
+/**
+ * How long stop() waits for the transactions pending at that moment, so that
+ * the requests it sends (un-REGISTER, BYE, un-SUBSCRIBE) get a chance to be
+ * answered before the transport goes away.
+ */
+const CLOSE_TIMEOUT = 2000;
+
+/**
+ * What the UA is doing, which {@link UA.status} reports.
+ */
+export enum Status {
+	INIT = 0,
+	READY = 1,
+	USER_CLOSED = 2,
+	NOT_READY = 3,
+}
+
+/**
+ * Why a UA that is not ready got there.
+ */
+export enum ErrorCode {
+	CONFIGURATION_ERROR = 1,
+	NETWORK_ERROR = 2,
+}
+
+/**
+ * The constants the UA exposes, both as a static and as an instance member.
+ *
+ * @remarks
+ * - {@link Status} and {@link ErrorCode} hold the same values under shorter
+ *   names, and are what the UA itself is typed with.
+ */
+export const C = {
+	// UA status codes.
+	STATUS_INIT: Status.INIT,
+	STATUS_READY: Status.READY,
+	STATUS_USER_CLOSED: Status.USER_CLOSED,
+	STATUS_NOT_READY: Status.NOT_READY,
+
+	// UA error codes.
+	CONFIGURATION_ERROR: ErrorCode.CONFIGURATION_ERROR,
+	NETWORK_ERROR: ErrorCode.NETWORK_ERROR,
+};
+
+/**
+ * What an application configures a UA with.
+ *
+ * @remarks
+ * - Every parameter is described on {@link Configuration}, which is the
+ *   validated form of this one. `uri`, `contact_uri` and `registrar_server`
+ *   are written as strings here and parsed into a `URI`.
+ */
+export type UAConfiguration = {
+	// Mandatory parameters.
+	sockets: Socket | Socket[] | WeightedSocket[];
+	uri: string;
+	// Optional parameters.
+	authorization_jwt?: string;
+	authorization_user?: string;
+	connection_recovery_max_interval?: number;
+	connection_recovery_min_interval?: number;
+	contact_uri?: string;
+	display_name?: string;
+	instance_id?: string;
+	no_answer_timeout?: number;
+	session_timers?: boolean;
+	session_timers_refresh_method?: string;
+	session_timers_force_refresher?: boolean;
+	password?: string;
+	realm?: string;
+	ha1?: string;
+	register?: boolean;
+	register_expires?: number;
+	register_from_tag_trail?: string | (() => string);
+	registrar_server?: string;
+	use_preloaded_route?: boolean;
+	user_agent?: string;
+	extra_headers?: string[];
+};
+
+/**
+ * The configuration of a running UA, which {@link UA.configuration} hands
+ * out.
+ *
+ * @remarks
+ * - The parameters a UA computes for itself are set, and `sockets` is gone:
+ *   it is consumed by the {@link Transport} and removed.
+ */
+export type LoadedConfiguration = Omit<
+	Configuration,
+	'sockets' | 'display_name'
+> & {
+	/**
+	 * A `0` given as a number is turned into the string `'0'`, so a loaded
+	 * display name is always text.
+	 */
+	display_name: string | null;
+	uri: URI;
+	contact_uri: URI;
+	registrar_server: URI;
+	instance_id: string;
+	/**
+	 * Random token identifying this UA instance, used to tell its own Via
+	 * header fields apart from anyone else's.
+	 */
+	jssip_id: string;
+	/**
+	 * {@link Configuration.uri} without its scheme and user part, so the
+	 * host, port and URI parameters.
+	 */
+	hostport_params: string;
+};
+
+// The configuration while `#loadConfig()` is filling it in: the validated
+// parameters, plus the computed ones it is about to add.
+//
+// TODO: `#loadConfig()` mutates the object it starts from rather than
+// deriving a value of its own, which is what forces the two types and the
+// cast between them. See the TODO at the top of `Configuration.ts`.
+type WorkingConfiguration = Configuration & {
+	jssip_id?: string;
+	hostport_params?: string;
+};
+
+/**
+ * Options accepted by `contact.toString()`.
+ */
+export type UAContactOptions = {
+	/**
+	 * Whether to hide the identity, which uses the temporary GRUU, or
+	 * `sip:anonymous@anonymous.invalid` when there is none.
+	 */
+	anonymous?: boolean;
+	/**
+	 * Whether to add the `ob` parameter of
+	 * [RFC 5626](https://datatracker.ietf.org/doc/html/rfc5626), which asks
+	 * the edge proxy to keep the flow open. It is left out when a GRUU is
+	 * used, as that already identifies the instance.
+	 */
+	outbound?: boolean;
+};
+
+/**
+ * The address the UA puts in the Contact header field of its requests.
+ */
+export type UAContact = {
+	/**
+	 * Public GRUU the registrar granted, if any.
+	 */
+	pub_gruu: string | null;
+	/**
+	 * Temporary GRUU the registrar granted, if any.
+	 */
+	temp_gruu: string | null;
+	/**
+	 * The address itself.
+	 */
+	uri: URI;
+	/**
+	 * The whole header field value, angle brackets included.
+	 */
+	toString(options?: UAContactOptions): string;
+};
+
+/**
+ * Options accepted by `call()`.
+ */
+export type CallOptions = AnswerOptions & {
+	/**
+	 * Listeners registered before the INVITE is sent, so that no event is
+	 * missed.
+	 */
+	eventHandlers?: Partial<RTCSessionEventMap>;
+	/**
+	 * Whether to hide the identity, which sends the call from
+	 * `sip:anonymous@anonymous.invalid` with a Privacy header field.
+	 */
+	anonymous?: boolean;
+	/**
+	 * User part of the From header field.
+	 */
+	fromUserName?: string;
+	/**
+	 * Display name of the From header field.
+	 */
+	fromDisplayName?: string;
+};
+
+/**
+ * Reported when a call comes in.
+ */
+export type IncomingRTCSessionEvent = {
+	originator: 'remote';
+	session: RTCSession;
+	request: IncomingRequest;
+};
+
+/**
+ * Reported when a call goes out.
+ */
+export type OutgoingRTCSessionEvent = {
+	originator: 'local';
+	session: RTCSession;
+	request: OutgoingRequest;
+};
+
+export type RTCSessionEvent = IncomingRTCSessionEvent | OutgoingRTCSessionEvent;
+
+/**
+ * Reported while the UA is trying to connect a socket.
+ */
+export type ConnectingEvent = TransportConnectingEvent;
+
+/**
+ * Reported once the transport is connected.
+ */
+export type ConnectedEvent = TransportConnectedEvent;
+
+/**
+ * Reported when the transport is gone, whoever closed it.
+ */
+export type DisconnectEvent = TransportDisconnectedEvent;
+
+export type { RegisteredEvent };
+
+/**
+ * Reported when a binding is gone, or could not be made.
+ */
+export type UnRegisteredEvent = UnregisteredEvent;
+
+/**
+ * Reported when a MESSAGE comes in.
+ */
+export type IncomingMessageEvent = {
+	originator: 'remote';
+	message: Message;
+	request: IncomingRequest;
+};
+
+/**
+ * Reported when a MESSAGE goes out.
+ */
+export type OutgoingMessageEvent = {
+	originator: 'local';
+	message: Message;
+	request: OutgoingRequest;
+};
+
+/**
+ * Reported when an OPTIONS comes in.
+ */
+export type IncomingOptionsEvent = {
+	originator: 'remote';
+	message: Options;
+	request: IncomingRequest;
+};
+
+/**
+ * Reported when an OPTIONS goes out.
+ */
+export type OutgoingOptionsEvent = {
+	originator: 'local';
+	message: Options;
+	request: OutgoingRequest;
+};
+
+/**
+ * Reported for a request carrying an event package, so an out of dialog
+ * NOTIFY or an incoming SUBSCRIBE.
+ */
+export type SipEventEvent = {
+	/**
+	 * Parsed Event header field of the request.
+	 */
+	event: unknown;
+	request: IncomingRequest;
+};
+
+/**
+ * The events a {@link UA} emits.
+ */
+export type UAEventMap = {
+	connecting: [event: ConnectingEvent];
+	connected: [event: ConnectedEvent];
+	disconnected: [event: DisconnectEvent];
+	registered: [event: RegisteredEvent];
+	registrationRefreshed: [event: RegisteredEvent];
+	unregistered: [event: UnRegisteredEvent];
+	registrationFailed: [event: UnRegisteredEvent];
+	registrationExpiring: [];
+	newRTCSession: [event: RTCSessionEvent];
+	newMessage: [event: IncomingMessageEvent | OutgoingMessageEvent];
+	newOptions: [event: IncomingOptionsEvent | OutgoingOptionsEvent];
+	sipEvent: [event: SipEventEvent];
+	newSubscribe: [event: SipEventEvent];
+	newTransaction: [event: { transaction: Transactions.Transaction }];
+	transactionDestroyed: [event: { transaction: Transactions.Transaction }];
+};
+
+/**
+ * The user agent: the entry point of the library, which holds the transport,
+ * the registration and everything running on top of them.
+ *
+ * @throws
+ * - `TypeError` if no configuration is given.
+ * - {@link ConfigurationError} if a configuration parameter is missing or
+ *   invalid.
+ *
+ * @example
+ * ```ts
+ * const ua = new JsSIP.UA({
+ *   uri: 'sip:alice@example.com',
+ *   sockets: new JsSIP.WebSocketInterface('wss://sip.example.com'),
+ *   password: 'secret',
+ * });
+ *
+ * ua.on('registered', () => console.log('registered'));
+ * ua.start();
+ * ```
+ */
+export class UA extends EventEmitter<UAEventMap> {
+	/**
+	 * The constants above, reachable without the instance.
+	 */
+	static get C(): typeof C {
+		return C;
+	}
+
+	/**
+	 * The transaction tables, indexed by transaction id.
+	 *
+	 * @internal
+	 */
+	readonly transactions: Transactions.TransactionRegistry = {
+		nist: {},
+		nict: {},
+		ist: {},
+		ict: {},
+	};
+
+	/**
+	 * User actions outside any session or dialog, so the MESSAGE and OPTIONS
+	 * requests that have not finished yet.
+	 *
+	 * @internal
+	 */
+	readonly applicants: Set<Message | Options> = new Set();
+
+	#configuration: WorkingConfiguration;
+	#dynConfiguration: { register?: boolean } = {};
+	#dialogs: Record<string, Dialog> = {};
+
+	#sessions: Record<string, RTCSession> = {};
+
+	// Subscriber instances with a subscription sent or established.
+	#subscribers: Set<Subscriber> = new Set();
+
+	#transport!: Transport;
+	#contact!: UAContact;
+	#status: Status = Status.INIT;
+	#registrator: Registrator;
+	#closeTimer: ReturnType<typeof setTimeout> | null = null;
+	#data: unknown = {};
+
+	constructor(configuration: UAConfiguration) {
+		// Check configuration argument.
+		if (!configuration) {
+			throw new TypeError('Not enough arguments');
+		}
+
+		// Hide sensitive information.
+		const sensitiveKeys = ['password', 'ha1', 'authorization_jwt'];
+
+		logger.debug(
+			'new() [configuration:%o]',
+			Object.entries(configuration).filter(
+				([key]) => !sensitiveKeys.includes(key)
+			)
+		);
+
+		super();
+
+		this.#configuration = Object.assign({}, config.DEFAULT_CONFIGURATION);
+
+		// Load configuration.
+		try {
+			this.#loadConfig(configuration);
+		} catch (error) {
+			this.#status = Status.NOT_READY;
+			throw error;
+		}
+
+		// Initialize registrator.
+		this.#registrator = new Registrator(this);
+	}
+
+	/**
+	 * The constants above.
+	 */
+	get C(): typeof C {
+		return C;
+	}
+
+	/**
+	 * What the UA is doing.
+	 */
+	get status(): Status {
+		return this.#status;
+	}
+
+	/**
+	 * The address the UA puts in the Contact header field of its requests.
+	 */
+	get contact(): UAContact {
+		return this.#contact;
+	}
+
+	/**
+	 * The configuration, as the UA validated and completed it.
+	 */
+	get configuration(): LoadedConfiguration {
+		return this.#configuration as LoadedConfiguration;
+	}
+
+	/**
+	 * The transport the UA sends and receives through.
+	 */
+	get transport(): Transport {
+		return this.#transport;
+	}
+
+	/**
+	 * Anything the application wants to keep along with the UA.
+	 */
+	get data(): unknown {
+		return this.#data;
+	}
+
+	/**
+	 * Replaces whatever was kept along with the UA.
+	 */
+	set data(data: unknown) {
+		this.#data = data;
+	}
+
+	// =================
+	//  High Level API
+	// =================
+
+	/**
+	 * Connect to the server, or resume a UA that was stopped.
+	 */
+	start(): void {
+		logger.debug('start()');
+
+		if (this.#status === Status.INIT) {
+			this.#transport.connect();
+		} else if (this.#status === Status.USER_CLOSED) {
+			logger.debug('restarting UA');
+
+			// Disconnect.
+			if (this.#closeTimer !== null) {
+				clearTimeout(this.#closeTimer);
+				this.#closeTimer = null;
+				this.#transport.disconnect();
+			}
+
+			// Reconnect.
+			this.#status = Status.INIT;
+			this.#transport.connect();
+		} else if (this.#status === Status.READY) {
+			logger.debug('UA is in READY status, not restarted');
+		} else {
+			logger.debug(
+				'ERROR: connection is down, Auto-Recovery system is trying to reconnect'
+			);
+		}
+
+		// Set dynamic configuration.
+		this.#dynConfiguration.register = this.#configuration.register;
+	}
+
+	/**
+	 * Register the UA, and keep the binding alive from then on.
+	 */
+	register(): void {
+		logger.debug('register()');
+
+		this.#dynConfiguration.register = true;
+		this.#registrator.register();
+	}
+
+	/**
+	 * Remove the binding the UA registered.
+	 */
+	unregister(options?: UnregisterOptions): void {
+		logger.debug('unregister()');
+
+		this.#dynConfiguration.register = false;
+		this.#registrator.unregister(options);
+	}
+
+	/**
+	 * The registrator, which holds the state of the registration.
+	 */
+	registrator(): Registrator {
+		return this.#registrator;
+	}
+
+	/**
+	 * Whether the UA currently holds a binding at the registrar.
+	 */
+	isRegistered(): boolean {
+		return this.#registrator.registered;
+	}
+
+	/**
+	 * Whether the transport is connected.
+	 */
+	isConnected(): boolean {
+		return this.#transport.isConnected();
+	}
+
+	/**
+	 * Make an outgoing call.
+	 *
+	 * @throws
+	 * - `TypeError` if the target is not a valid one.
+	 */
+	call(target: string | URI, options?: CallOptions): RTCSession {
+		logger.debug('call()');
+
+		const session = new RTCSession(this);
+
+		session.connect(target, options);
+
+		return session;
+	}
+
+	/**
+	 * Send a SIP MESSAGE.
+	 *
+	 * @throws
+	 * - `TypeError` if the target is not a valid one.
+	 */
+	sendMessage(
+		target: string | URI,
+		body: string,
+		options?: SendMessageOptions
+	): Message {
+		logger.debug('sendMessage()');
+
+		const message = new Message(this);
+
+		message.send(target, body, options);
+
+		return message;
+	}
+
+	/**
+	 * Subscribe to an event the peer reports. Nothing is sent until
+	 * `subscribe()` is called on the result.
+	 *
+	 * @throws
+	 * - `TypeError` if an argument is missing or the target is not a valid
+	 *   one.
+	 */
+	subscribe(
+		target: string | URI,
+		eventName: string,
+		accept: string,
+		options?: SubscriberOptions
+	): Subscriber {
+		logger.debug('subscribe()');
+
+		return new Subscriber(this, target, eventName, accept, options);
+	}
+
+	/**
+	 * Accept a subscription the peer asked for. Nothing is sent until
+	 * `start()` is called on the result.
+	 *
+	 * @throws
+	 * - `TypeError` if the content type is missing or the SUBSCRIBE is not
+	 *   one a notifier can be built on.
+	 */
+	notify(
+		subscribe: IncomingRequest,
+		contentType: string,
+		options?: NotifierOptions
+	): Notifier {
+		logger.debug('notify()');
+
+		return new Notifier(this, subscribe, contentType, options);
+	}
+
+	/**
+	 * Send a SIP OPTIONS.
+	 *
+	 * @throws
+	 * - `TypeError` if the target is not a valid one.
+	 */
+	sendOptions(
+		target: string | URI,
+		body?: string,
+		options?: SendOptionsOptions
+	): Options {
+		logger.debug('sendOptions()');
+
+		const message = new Options(this);
+
+		message.send(target, body, options);
+
+		return message;
+	}
+
+	/**
+	 * Terminate every session that has not ended yet.
+	 */
+	terminateSessions(options?: TerminateOptions): void {
+		logger.debug('terminateSessions()');
+
+		for (const session of Object.values(this.#sessions)) {
+			if (!session.isEnded()) {
+				session.terminate(options);
+			}
+		}
+	}
+
+	/**
+	 * Close everything down gracefully: un-register, hang up, un-subscribe,
+	 * and disconnect once those are answered.
+	 */
+	stop(): void {
+		logger.debug('stop()');
+
+		// Remove dynamic settings.
+		this.#dynConfiguration = {};
+
+		if (this.#status === Status.USER_CLOSED) {
+			logger.debug('UA already closed');
+
+			return;
+		}
+
+		// Close registrator.
+		this.#registrator.close();
+
+		// Terminate every session.
+		for (const [id, session] of Object.entries(this.#sessions)) {
+			logger.debug(`closing session ${id}`);
+			try {
+				session.terminate();
+			} catch (error) {}
+		}
+
+		// Unsubscribe every subscription. The un-SUBSCRIBE must leave before
+		// the UA is closed, so that the server does not keep sending NOTIFY
+		// requests to a gone UA until the subscription expires.
+		for (const subscriber of this.#subscribers) {
+			logger.debug('closing subscriber');
+			try {
+				subscriber.terminate();
+			} catch (error) {}
+		}
+
+		// Close every applicant.
+		//
+		// NOTE: Neither `Message` nor `Options` exposes a `close()`, so every
+		// one of these throws into the empty catch and nothing is closed. Kept
+		// as it is until it is decided what stopping should do to a pending
+		// MESSAGE or OPTIONS; see TODO.md.
+		for (const applicant of this.applicants) {
+			try {
+				(applicant as unknown as { close: () => void }).close();
+			} catch (error) {}
+		}
+
+		this.#status = Status.USER_CLOSED;
+
+		// Give some time for the requests sent above to be answered.
+		// #mayClose() closes as soon as they are.
+		this.#closeTimer = setTimeout(() => this.#close(), CLOSE_TIMEOUT);
+
+		this.#mayClose();
+	}
+
+	/**
+	 * Turn a string into the SIP URI a request can be sent to, filling in the
+	 * host of the UA when the string carries none.
+	 */
+	normalizeTarget(target: string | URI): URI | undefined {
+		return Utils.normalizeTarget(target, this.configuration.hostport_params);
+	}
+
+	/**
+	 * Read back a configuration parameter.
+	 *
+	 * @remarks
+	 * - Only the credentials can be read: `authorization_user`, `realm`,
+	 *   `ha1` and `authorization_jwt`. Anything else logs a warning and
+	 *   gives `undefined`.
+	 */
+	get(parameter: string): string | null | undefined {
+		switch (parameter) {
+			case 'authorization_user': {
+				return this.configuration.authorization_user;
+			}
+
+			case 'realm': {
+				return this.configuration.realm;
+			}
+
+			case 'ha1': {
+				return this.configuration.ha1;
+			}
+
+			case 'authorization_jwt': {
+				return this.configuration.authorization_jwt;
+			}
+
+			default: {
+				logger.warn('get() | cannot get "%s" parameter in runtime', parameter);
+
+				return undefined;
+			}
+		}
+	}
+
+	/**
+	 * Change a configuration parameter while the UA is running.
+	 *
+	 * @returns Whether the parameter is one that can be set.
+	 *
+	 * @remarks
+	 * - Only `authorization_user`, `password`, `realm`, `ha1`,
+	 *   `authorization_jwt`, `display_name` and `extra_headers` can be set.
+	 *   Anything else logs a warning and gives `false`.
+	 * - Setting `ha1` deletes the plain password.
+	 */
+	set(parameter: string, value: unknown): boolean {
+		switch (parameter) {
+			case 'authorization_user': {
+				this.#configuration.authorization_user = String(value);
+				break;
+			}
+
+			case 'password': {
+				this.#configuration.password = String(value);
+				break;
+			}
+
+			case 'realm': {
+				this.#configuration.realm = String(value);
+				break;
+			}
+
+			case 'ha1': {
+				this.#configuration.ha1 = String(value);
+				// Delete the plain SIP password.
+				this.#configuration.password = null;
+				break;
+			}
+
+			case 'authorization_jwt': {
+				this.#configuration.authorization_jwt = String(value);
+				break;
+			}
+
+			case 'display_name': {
+				this.#configuration.display_name = value as string;
+				break;
+			}
+
+			case 'extra_headers': {
+				this.#configuration.extra_headers = value as string[];
+				break;
+			}
+
+			default: {
+				logger.warn('set() | cannot set "%s" parameter in runtime', parameter);
+
+				return false;
+			}
+		}
+
+		return true;
+	}
+
+	// ==========================
+	// Event Handlers.
+	// ==========================
+
+	/**
+	 * @internal
+	 */
+	newTransaction(transaction: Transactions.Transaction): void {
+		// Each transaction goes in the table its own `type` names, a pairing
+		// the union cannot express.
+		const table = this.transactions[transaction.type] as Record<
+			string,
+			Transactions.Transaction
+		>;
+
+		table[transaction.id] = transaction;
+
+		this.emit('newTransaction', {
+			transaction,
+		});
+	}
+
+	/**
+	 * @internal
+	 */
+	destroyTransaction(transaction: Transactions.Transaction): void {
+		const table = this.transactions[transaction.type] as Record<
+			string,
+			Transactions.Transaction
+		>;
+
+		delete table[transaction.id];
+
+		this.emit('transactionDestroyed', {
+			transaction,
+		});
+
+		this.#mayClose();
+	}
+
+	/**
+	 * @internal
+	 */
+	newDialog(dialog: Dialog): void {
+		this.#dialogs[dialog.id.toString()] = dialog;
+	}
+
+	/**
+	 * @internal
+	 */
+	destroyDialog(dialog: Dialog): void {
+		delete this.#dialogs[dialog.id.toString()];
+	}
+
+	/**
+	 * @internal
+	 */
+	newMessage(
+		message: Message,
+		data: {
+			originator: Originator;
+			message: Message;
+			request: OutgoingRequest | IncomingRequest;
+		}
+	): void {
+		this.applicants.add(message);
+		this.emit('newMessage', data as IncomingMessageEvent);
+	}
+
+	/**
+	 * @internal
+	 */
+	newOptions(
+		message: Options,
+		data: {
+			originator: Originator;
+			message: Options;
+			request: OutgoingRequest | IncomingRequest;
+		}
+	): void {
+		this.applicants.add(message);
+		this.emit('newOptions', data as IncomingOptionsEvent);
+	}
+
+	/**
+	 * @internal
+	 */
+	destroyMessage(message: Message): void {
+		this.applicants.delete(message);
+	}
+
+	/**
+	 * @internal
+	 */
+	destroyOptions(options: Options): void {
+		this.applicants.delete(options);
+	}
+
+	/**
+	 * @internal
+	 */
+	newSubscriber(subscriber: Subscriber): void {
+		this.#subscribers.add(subscriber);
+	}
+
+	/**
+	 * @internal
+	 */
+	destroySubscriber(subscriber: Subscriber): void {
+		this.#subscribers.delete(subscriber);
+	}
+
+	/**
+	 * @internal
+	 */
+	newRTCSession(session: RTCSession, data: RTCSessionEvent): void {
+		this.#sessions[session.id] = session;
+		this.emit('newRTCSession', data);
+	}
+
+	/**
+	 * @internal
+	 */
+	destroyRTCSession(session: RTCSession): void {
+		delete this.#sessions[session.id];
+
+		this.#mayClose();
+	}
+
+	/**
+	 * @internal
+	 */
+	registered(data: RegisteredEvent): void {
+		this.emit('registered', data);
+	}
+
+	/**
+	 * @internal
+	 */
+	registrationRefreshed(data: RegisteredEvent): void {
+		this.emit('registrationRefreshed', data);
+	}
+
+	/**
+	 * @internal
+	 */
+	unregistered(data: UnregisteredEvent): void {
+		this.emit('unregistered', data);
+	}
+
+	/**
+	 * @internal
+	 */
+	registrationFailed(data: UnregisteredEvent): void {
+		this.emit('registrationFailed', data);
+	}
+
+	// =========================
+	// ReceiveRequest.
+	// =========================
+
+	/**
+	 * Take over a request the transport received.
+	 *
+	 * @internal
+	 */
+	receiveRequest(request: IncomingRequest): void {
+		const method = request.method;
+
+		// Check that request URI points to us.
+		if (!this.#doesRuriPointToUs(request.ruri)) {
+			logger.debug('Request-URI does not point to us');
+			if (request.method !== JsSIP_C.ACK) {
+				request.reply_sl(404);
+			}
+
+			return;
+		}
+
+		// Check request URI scheme.
+		if (request.ruri.scheme === JsSIP_C.SIPS) {
+			request.reply_sl(416);
+
+			return;
+		}
+
+		// Check transaction.
+		if (Transactions.checkTransaction(this, request)) {
+			return;
+		}
+
+		// Create the server transaction.
+		// The constructor puts the new transaction on the request and in the
+		// transaction table of the UA, so there is nothing left to do with the
+		// value it returns.
+		/* eslint-disable no-new */
+		if (method === JsSIP_C.INVITE) {
+			new Transactions.InviteServerTransaction(this, this.#transport, request);
+		} else if (method !== JsSIP_C.ACK && method !== JsSIP_C.CANCEL) {
+			new Transactions.NonInviteServerTransaction(
+				this,
+				this.#transport,
+				request
+			);
+		}
+		/* eslint-enable no-new */
+
+		// RFC3261 12.2.2
+		// Requests that do not change in any way the state of a dialog may be
+		// received within a dialog (for example, an OPTIONS request).
+		// They are processed as if they had been received outside the dialog.
+		if (method === JsSIP_C.OPTIONS) {
+			if (this.listeners('newOptions').length === 0) {
+				request.reply(200);
+
+				return;
+			}
+
+			const message = new Options(this);
+
+			message.init_incoming(request);
+		} else if (method === JsSIP_C.MESSAGE) {
+			if (this.listeners('newMessage').length === 0) {
+				request.reply(405);
+
+				return;
+			}
+			const message = new Message(this);
+
+			message.init_incoming(request);
+		} else if (method === JsSIP_C.SUBSCRIBE) {
+			if (this.listeners('newSubscribe').length === 0) {
+				request.reply(405);
+
+				return;
+			}
+		} else if (method === JsSIP_C.INVITE) {
+			// Initial INVITE.
+			if (!request.to_tag && this.listeners('newRTCSession').length === 0) {
+				request.reply(405);
+
+				return;
+			}
+		}
+
+		let dialog;
+		let session;
+
+		// Initial Request.
+		if (!request.to_tag) {
+			switch (method) {
+				case JsSIP_C.INVITE: {
+					if (window.RTCPeerConnection) {
+						// TODO
+						if (request.hasHeader('replaces')) {
+							const replaces = request.replaces!;
+
+							dialog = this.#findDialog(
+								replaces.call_id,
+								replaces.from_tag,
+								replaces.to_tag
+							);
+							if (dialog) {
+								session = dialog.owner as RTCSession;
+								if (!session.isEnded()) {
+									session.receiveRequest(request);
+								} else {
+									request.reply(603);
+								}
+							} else {
+								request.reply(481);
+							}
+						} else {
+							session = new RTCSession(this);
+							session.init_incoming(request);
+						}
+					} else {
+						logger.warn('INVITE received but WebRTC is not supported');
+						request.reply(488);
+					}
+					break;
+				}
+				case JsSIP_C.BYE: {
+					// Out of dialog BYE received.
+					request.reply(481);
+					break;
+				}
+				case JsSIP_C.CANCEL: {
+					session = this.#findSession(request);
+					if (session) {
+						session.receiveRequest(request);
+					} else {
+						logger.debug('received CANCEL request for a non existent session');
+					}
+					break;
+				}
+				case JsSIP_C.ACK: {
+					// Absorb it.
+					// ACK request without a corresponding Invite Transaction
+					// and without To tag.
+					break;
+				}
+				case JsSIP_C.NOTIFY: {
+					// Receive new sip event.
+					this.emit('sipEvent', {
+						event: request.event,
+						request,
+					});
+					request.reply(200);
+					break;
+				}
+				case JsSIP_C.SUBSCRIBE: {
+					Notifier.init_incoming(request, () => {
+						this.emit('newSubscribe', {
+							event: request.event,
+							request,
+						});
+					});
+					break;
+				}
+				default: {
+					request.reply(405);
+					break;
+				}
+			}
+		}
+		// In-dialog request.
+		else {
+			dialog = this.#findDialog(
+				request.call_id,
+				request.from_tag,
+				request.to_tag
+			);
+
+			if (dialog) {
+				dialog.receiveRequest(request);
+			} else if (method === JsSIP_C.NOTIFY) {
+				session = this.#findSession(request);
+
+				if (session) {
+					session.receiveRequest(request);
+				} else {
+					const subscriber = this.#findEarlyNotifySubscriber(request);
+
+					if (subscriber) {
+						subscriber.receiveEarlyNotify(request);
+					} else {
+						logger.debug(
+							'received NOTIFY request for a non existent subscription'
+						);
+						request.reply(481, 'Subscription does not exist');
+					}
+				}
+			} else if (method !== JsSIP_C.ACK) {
+				// RFC3261 12.2.2
+				// Request with to tag, but no matching dialog found.
+				// Exception: ACK for an Invite request for which a dialog has not
+				// been created.
+				request.reply(481);
+			}
+		}
+	}
+
+	// =================
+	// Utils.
+	// =================
+
+	/**
+	 * Whether the UA has anything left to wait for.
+	 *
+	 * Sessions are looked at besides the transactions because a session sits
+	 * here with none of its own once its dialog is confirmed. Subscribers and
+	 * applicants are not: each is destroyed while handling the response to its
+	 * last request, a tick before the transaction that carried it.
+	 */
+	#isIdle(): boolean {
+		return (
+			Object.keys(this.#sessions).length === 0 &&
+			Object.keys(this.transactions.nict).length === 0 &&
+			Object.keys(this.transactions.nist).length === 0 &&
+			Object.keys(this.transactions.ict).length === 0 &&
+			Object.keys(this.transactions.ist).length === 0
+		);
+	}
+
+	/**
+	 * Ends the shutdown begun by stop().
+	 */
+	#close(): void {
+		this.#closeTimer = null;
+		this.#transport.disconnect();
+	}
+
+	/**
+	 * Closes a stopping UA as soon as what was pending when it was stopped is
+	 * done with, instead of waiting for the whole CLOSE_TIMEOUT.
+	 */
+	#mayClose(): void {
+		// A close timer is only pending while the UA is stopping.
+		if (this.#closeTimer === null || !this.#isIdle()) {
+			return;
+		}
+
+		clearTimeout(this.#closeTimer);
+		this.#close();
+	}
+
+	/**
+	 * Whether the Request-URI of an incoming request addresses this UA.
+	 */
+	#doesRuriPointToUs(ruri: URI): boolean {
+		if (
+			ruri.user === this.configuration.uri.user ||
+			ruri.user === this.#contact.uri.user
+		) {
+			return true;
+		}
+
+		// The registrar is free to choose how the GRUUs it grants look (RFC
+		// 5627, Appendix A), and this UA advertises them in the Contact header
+		// of its outgoing requests, so requests targeted at them point to us.
+		for (const gruu of [this.#contact.pub_gruu, this.#contact.temp_gruu]) {
+			const uri = gruu ? URI.parse(gruu) : undefined;
+
+			if (!uri) {
+				continue;
+			}
+
+			// Compare AORs plus the 'gr' parameter, which is what identifies the
+			// instance (RFC 5627, Section 3.1). Any other parameter a proxy may
+			// have added on the way takes no part in the match.
+			if (
+				uri.toAor() === ruri.toAor() &&
+				uri.getParam('gr') === ruri.getParam('gr')
+			) {
+				return true;
+			}
+		}
+
+		return false;
+	}
+
+	/**
+	 * Get the session to which the request belongs to, if any.
+	 */
+	#findSession({
+		call_id,
+		from_tag,
+		to_tag,
+	}: {
+		call_id?: string;
+		from_tag?: string | null;
+		to_tag?: string | null;
+	}): RTCSession | null {
+		// A missing tag takes part in the key as the text of its own absence,
+		// which is how the ids were built in the first place.
+		const sessionIDa = `${call_id}${from_tag}`;
+		const sessionA = this.#sessions[sessionIDa];
+		const sessionIDb = `${call_id}${to_tag}`;
+		const sessionB = this.#sessions[sessionIDb];
+
+		if (sessionA) {
+			return sessionA;
+		} else if (sessionB) {
+			return sessionB;
+		} else {
+			return null;
+		}
+	}
+
+	/**
+	 * Get the subscriber whose dialog is created by the given NOTIFY, if any.
+	 *
+	 * RFC 6665 4.1.2.4: the first NOTIFY of a subscription may arrive before
+	 * the 2xx response to the initial SUBSCRIBE, so there is no dialog yet.
+	 * Only a subscriber still waiting for that first NOTIFY matches; any later
+	 * NOTIFY is routed by `#findDialog()`.
+	 */
+	#findEarlyNotifySubscriber({
+		call_id,
+		to_tag,
+	}: {
+		call_id?: string;
+		to_tag?: string | null;
+	}): Subscriber | null {
+		for (const subscriber of this.#subscribers) {
+			if (subscriber.matchEarlyNotify(call_id, to_tag)) {
+				return subscriber;
+			}
+		}
+
+		return null;
+	}
+
+	/**
+	 * Get the dialog to which the request belongs to, if any.
+	 */
+	// The tags are nullable because an incoming message distinguishes a
+	// valueless `;tag` parameter from an absent one, while a Replaces header
+	// field only ever has the latter.
+	#findDialog(
+		call_id: string | undefined,
+		from_tag: string | null | undefined,
+		to_tag: string | null | undefined
+	): Dialog | null {
+		let id = `${call_id}${from_tag}${to_tag}`;
+		let dialog = this.#dialogs[id];
+
+		if (dialog) {
+			return dialog;
+		} else {
+			id = `${call_id}${to_tag}${from_tag}`;
+			dialog = this.#dialogs[id];
+			if (dialog) {
+				return dialog;
+			} else {
+				return null;
+			}
+		}
+	}
+
+	#loadConfig(configuration: UAConfiguration): void {
+		// Check and load the given configuration.
+		// This can throw.
+		config.load(
+			this.#configuration,
+			configuration as unknown as Record<string, unknown>
+		);
+
+		// Post Configuration Process.
+
+		// Allow passing 0 number as display_name.
+		if (this.#configuration.display_name === 0) {
+			this.#configuration.display_name = '0';
+		}
+
+		// Instance-id for GRUU.
+		if (!this.#configuration.instance_id) {
+			this.#configuration.instance_id = Utils.newUUID();
+		}
+
+		// Jssip_id instance parameter. Static random tag of length 5.
+		this.#configuration.jssip_id = Utils.createRandomToken(5);
+
+		// String containing this.#configuration.uri without scheme and user.
+		const hostport_params = this.#configuration.uri!.clone();
+
+		hostport_params.user = undefined;
+		this.#configuration.hostport_params = hostport_params
+			.toString()
+			.replace(/^sip:/i, '');
+
+		// Transport.
+		try {
+			this.#transport = new Transport(this.#configuration.sockets!, {
+				// Recovery options.
+				max_interval: this.#configuration.connection_recovery_max_interval,
+				min_interval: this.#configuration.connection_recovery_min_interval,
+			});
+
+			// Transport event callbacks.
+			this.#transport.onconnecting = event =>
+				this.#onTransportConnecting(event);
+			this.#transport.onconnect = event => this.#onTransportConnect(event);
+			this.#transport.ondisconnect = event =>
+				this.#onTransportDisconnect(event);
+			this.#transport.ondata = event => this.#onTransportData(event);
+		} catch (error) {
+			logger.warn(error);
+			throw new ConfigurationError('sockets', this.#configuration.sockets);
+		}
+
+		// Remove sockets instance from configuration object.
+		delete (this.#configuration as Partial<Configuration>).sockets;
+
+		// Check whether authorization_user is explicitly defined.
+		// Take 'this.#configuration.uri.user' value if not.
+		if (!this.#configuration.authorization_user) {
+			this.#configuration.authorization_user =
+				this.#configuration.uri!.user ?? null;
+		}
+
+		// If no 'registrar_server' is set use the 'uri' value without user
+		// portion and without URI params/headers.
+		if (!this.#configuration.registrar_server) {
+			const registrar_server = this.#configuration.uri!.clone();
+
+			registrar_server.user = undefined;
+			registrar_server.clearParams();
+			registrar_server.clearHeaders();
+			this.#configuration.registrar_server = registrar_server;
+		}
+
+		// User no_answer_timeout.
+		this.#configuration.no_answer_timeout *= 1000;
+
+		// Via Host.
+		if (this.#configuration.contact_uri) {
+			this.#configuration.via_host = this.#configuration.contact_uri.host;
+		}
+
+		// Contact URI.
+		else {
+			this.#configuration.contact_uri = new URI(
+				'sip',
+				Utils.createRandomToken(8),
+				this.#configuration.via_host,
+				undefined,
+				{ transport: 'ws' }
+			);
+		}
+
+		this.#contact = {
+			pub_gruu: null,
+			temp_gruu: null,
+			uri: this.#configuration.contact_uri,
+			toString(options: UAContactOptions = {}) {
+				const anonymous = options.anonymous || null;
+				const outbound = options.outbound || null;
+				let contact = '<';
+
+				if (anonymous) {
+					contact +=
+						this.temp_gruu || 'sip:anonymous@anonymous.invalid;transport=ws';
+				} else {
+					contact += this.pub_gruu || this.uri.toString();
+				}
+
+				if (outbound && (anonymous ? !this.temp_gruu : !this.pub_gruu)) {
+					contact += ';ob';
+				}
+
+				contact += '>';
+
+				return contact;
+			},
+		};
+
+		// Seal the configuration.
+		const writable_parameters = [
+			'authorization_user',
+			'password',
+			'realm',
+			'ha1',
+			'authorization_jwt',
+			'display_name',
+			'register',
+			'extra_headers',
+		];
+
+		for (const parameter of Object.keys(this.#configuration)) {
+			if (writable_parameters.includes(parameter)) {
+				Object.defineProperty(this.#configuration, parameter, {
+					writable: true,
+					configurable: false,
+				});
+			} else {
+				Object.defineProperty(this.#configuration, parameter, {
+					writable: false,
+					configurable: false,
+				});
+			}
+		}
+
+		logger.debug('configuration parameters after validation:');
+
+		const shown = this.#configuration as unknown as Record<string, unknown>;
+
+		for (const parameter of Object.keys(this.#configuration)) {
+			// Only show the user user configurable parameters.
+			if (
+				Object.prototype.hasOwnProperty.call(
+					config.DEFAULT_CONFIGURATION,
+					parameter
+				)
+			) {
+				switch (parameter) {
+					case 'uri':
+					case 'registrar_server': {
+						logger.debug(`- ${parameter}: ${shown[parameter]}`);
+						break;
+					}
+					case 'password':
+					case 'ha1':
+					case 'authorization_jwt': {
+						logger.debug(`- ${parameter}: NOT SHOWN`);
+						break;
+					}
+					default: {
+						logger.debug(`- ${parameter}: ${JSON.stringify(shown[parameter])}`);
+					}
+				}
+			}
+		}
+	}
+
+	// ==========================
+	// Transport event handlers.
+	// ==========================
+
+	#onTransportConnecting(data: TransportConnectingEvent): void {
+		this.emit('connecting', data);
+	}
+
+	#onTransportConnect(data: TransportConnectedEvent): void {
+		if (this.#status === Status.USER_CLOSED) {
+			return;
+		}
+
+		this.#status = Status.READY;
+
+		this.emit('connected', data);
+
+		if (this.#dynConfiguration.register) {
+			this.#registrator.register();
+		}
+	}
+
+	#onTransportDisconnect(data: TransportDisconnectedEvent): void {
+		// Run onTransportError() on every transaction using the transport.
+		for (const type of ['nict', 'ict', 'nist', 'ist'] as const) {
+			const table: Record<string, Transactions.Transaction> =
+				this.transactions[type];
+
+			for (const transaction of Object.values(table)) {
+				transaction.onTransportError();
+			}
+		}
+
+		this.emit('disconnected', data);
+
+		// Call registrator onTransportClosed().
+		this.#registrator.onTransportClosed();
+
+		if (this.#status !== Status.USER_CLOSED) {
+			this.#status = Status.NOT_READY;
+		}
+	}
+
+	#onTransportData(data: TransportDataEvent): void {
+		const transport = data.transport;
+
+		const message = Parser.parseMessage(data.message, this);
+
+		if (!message) {
+			return;
+		}
+
+		if (
+			this.#status === Status.USER_CLOSED &&
+			message instanceof SIPMessage.IncomingRequest
+		) {
+			return;
+		}
+
+		// Do some sanity check.
+		if (!sanityCheck(message, this, transport)) {
+			return;
+		}
+
+		if (message instanceof SIPMessage.IncomingRequest) {
+			message.transport = transport;
+			this.receiveRequest(message);
+		} else if (message instanceof SIPMessage.IncomingResponse) {
+			// Unike stated in 18.1.2, if a response does not match
+			// any transaction, it is discarded here and no passed to the core
+			// in order to be discarded there.
+
+			switch (message.method) {
+				case JsSIP_C.INVITE: {
+					const transaction = this.transactions.ict[message.via_branch!];
+
+					if (transaction) {
+						transaction.receiveResponse(message);
+					}
+					break;
+				}
+				case JsSIP_C.ACK: {
+					// Just in case ;-).
+					break;
+				}
+				default: {
+					const transaction = this.transactions.nict[message.via_branch!];
+
+					if (transaction) {
+						transaction.receiveResponse(message);
+					}
+					break;
+				}
+			}
+		}
+	}
+}
diff --git a/src/sanityCheck.ts b/src/sanityCheck.ts
index bbdf0c3..2c1a933 100644
--- a/src/sanityCheck.ts
+++ b/src/sanityCheck.ts
@@ -15,7 +15,7 @@ const logger = new Logger('sanityCheck');
  * TypeScript.
  */
 export interface SanityCheckUA extends UALike {
-	readonly _transactions: TransactionRegistry;
+	readonly transactions: TransactionRegistry;
 }

 /**
@@ -159,12 +159,12 @@ function rfc3261_8_2_2_2(
 		// TODO: A Via with no `branch` parameter keys on the literal string
 		// 'undefined', so two such requests look like retransmissions of each
 		// other. Kept as is to preserve behaviour.
-		if (ua._transactions.ist[String(message.via_branch)]) {
+		if (ua.transactions.ist[String(message.via_branch)]) {
 			return false;
 		}
 		// Otherwise check whether it is a merged request.
 		else {
-			for (const tr of Object.values(ua._transactions.ist)) {
+			for (const tr of Object.values(ua.transactions.ist)) {
 				if (
 					tr.request.from_tag === fromTag &&
 					tr.request.call_id === call_id &&
@@ -183,13 +183,13 @@ function rfc3261_8_2_2_2(
 	// If the branch matches the key of any NIST then assume it is a retransmission
 	// and ignore the request.
 	// TODO: we should reply the last response.
-	else if (ua._transactions.nist[String(message.via_branch)]) {
+	else if (ua.transactions.nist[String(message.via_branch)]) {
 		return false;
 	}

 	// Otherwise check whether it is a merged request.
 	else {
-		for (const tr of Object.values(ua._transactions.nist)) {
+		for (const tr of Object.values(ua.transactions.nist)) {
 			if (
 				tr.request.from_tag === fromTag &&
 				tr.request.call_id === call_id &&
diff --git a/src/test/RTCSession/test-ReferSubscriber.ts b/src/test/RTCSession/test-ReferSubscriber.ts
index 992bdc6..e42d834 100644
--- a/src/test/RTCSession/test-ReferSubscriber.ts
+++ b/src/test/RTCSession/test-ReferSubscriber.ts
@@ -55,7 +55,7 @@ function sendRefer(options: {

 	const session: ReferSubscriberSession = {
 		contact: CONTACT,
-		_ua: { configuration: { uri: LOCAL_AOR } },
+		ua: { configuration: { uri: LOCAL_AOR } },
 		sendRequest(_method, sent = {}) {
 			extraHeaders = sent.extraHeaders ?? [];

@@ -80,7 +80,7 @@ function referOutcome(

 	const session: ReferSubscriberSession = {
 		contact: CONTACT,
-		_ua: { configuration: { uri: LOCAL_AOR } },
+		ua: { configuration: { uri: LOCAL_AOR } },
 		sendRequest(_method, sent = {}) {
 			handlers = sent.eventHandlers ?? {};

diff --git a/src/test/test-Dialog.ts b/src/test/test-Dialog.ts
index 5e8feee..c8d9fdf 100644
--- a/src/test/test-Dialog.ts
+++ b/src/test/test-Dialog.ts
@@ -7,7 +7,7 @@ import TestSocket from './include/TestSocket';
 import { startUA, stopUA } from './include/ua';

 import { Dialog, DialogError, DialogErrorReason } from '../Dialog';
-import type { DialogOwner } from '../Dialog';
+import type { DialogOwner, DialogUA } from '../Dialog';
 import { UA, WebSocketInterface } from '../JsSIP';
 import type { Notifier } from '../Notifier';
 import * as Parser from '../Parser';
@@ -22,12 +22,15 @@ describe('Dialog.Create()', () => {
 	// that `Create()` registers them with.
 	const dialogs: Dialog[] = [];

+	// `satisfies` rather than a cast over the whole object, so that the
+	// members `DialogOwner` names stay checked. Only the breadth of `DialogUA`
+	// is stubbed out.
 	const owner = {
-		_ua: {
+		ua: {
 			newDialog: (dialog: Dialog) => dialogs.push(dialog),
-		},
+		} as unknown as DialogUA,
 		receiveRequest: () => {},
-	} as unknown as DialogOwner;
+	} satisfies DialogOwner;

 	let ua: UA;

diff --git a/src/test/test-Message.ts b/src/test/test-Message.ts
index 7f36914..b620cd5 100644
--- a/src/test/test-Message.ts
+++ b/src/test/test-Message.ts
@@ -13,7 +13,6 @@ import { startUA, stopUA } from './include/ua';
 import { causes } from '../Constants';
 import { NotSupportedError } from '../Exceptions';
 import type { Message, MessageFailedEvent } from '../Message';
-import type { IncomingMessageEvent } from '../UA';
 import { UA } from '../JsSIP';

 const AOR = 'sip:alice@example.com';
@@ -143,7 +142,7 @@ async function receiveMessage(
 	 * anything it throws would escape into a timer instead of reaching the
 	 * test. Catch it here and report it back.
 	 */
-	ua.on('newMessage', ({ message, request }: IncomingMessageEvent) => {
+	ua.on('newMessage', ({ message, request }) => {
 		seen = request.body;

 		try {
diff --git a/src/test/test-Options.ts b/src/test/test-Options.ts
index 765372e..181821f 100644
--- a/src/test/test-Options.ts
+++ b/src/test/test-Options.ts
@@ -6,7 +6,6 @@ import TestSocket from './include/TestSocket';
 import { startUA, stopUA } from './include/ua';

 import { UA } from '../JsSIP';
-import type { IncomingOptionsEvent } from '../UA';

 const AOR = 'sip:alice@example.com';
 const REMOTE = 'sip:bob@example.com';
@@ -33,9 +32,7 @@ class OptionsSocket extends TestSocket {
  * NOTE: Reaches into the UA because there is no public way to observe them.
  */
 function applicants(ua: UA): unknown[] {
-	return Object.values(
-		(ua as unknown as { _applicants: Record<string, unknown> })._applicants
-	);
+	return [...ua.applicants];
 }

 describe('UA.destroyOptions()', () => {
@@ -92,7 +89,7 @@ describe('UA.destroyOptions()', () => {

 		// Without a 'newOptions' listener the UA answers the request itself and
 		// never builds an Options, so there would be nothing to destroy.
-		ua.on('newOptions', ({ message }: IncomingOptionsEvent) => {
+		ua.on('newOptions', ({ message }) => {
 			// The OPTIONS is being handled, so the UA is holding its applicant.
 			held = applicants(ua);