Commit 9615520 for jssip.net

commit 9615520bdacdb138e270d8c378202b66e33edc65
Author: José Luis Millán <jmillan@aliax.net>
Date:   Thu Dec 3 13:43:46 2026 +0100

    TS RTCSession/ReferSubscriber

diff --git a/src/RTCSession.js b/src/RTCSession.js
index 2a721c9..e855a23 100644
--- a/src/RTCSession.js
+++ b/src/RTCSession.js
@@ -17,7 +17,9 @@ const { Info: RTCSession_Info } = require('./RTCSession/Info');
 const {
 	ReferNotifier: RTCSession_ReferNotifier,
 } = require('./RTCSession/ReferNotifier');
-const RTCSession_ReferSubscriber = require('./RTCSession/ReferSubscriber');
+const {
+	ReferSubscriber: RTCSession_ReferSubscriber,
+} = require('./RTCSession/ReferSubscriber');
 const URI = require('./URI');

 const logger = new Logger('RTCSession');
diff --git a/src/RTCSession/ReferSubscriber.js b/src/RTCSession/ReferSubscriber.js
deleted file mode 100644
index 54a2e68..0000000
--- a/src/RTCSession/ReferSubscriber.js
+++ /dev/null
@@ -1,176 +0,0 @@
-const EventEmitter = require('events').EventEmitter;
-const { Logger } = require('../Logger');
-const JsSIP_C = require('../Constants');
-const Grammar = require('../Grammar');
-const Utils = require('../Utils');
-
-const logger = new Logger('RTCSession:ReferSubscriber');
-
-module.exports = class ReferSubscriber extends EventEmitter {
-	constructor(session) {
-		super();
-
-		this._id = null;
-		this._session = session;
-	}
-
-	get id() {
-		return this._id;
-	}
-
-	sendRefer(target, options = {}) {
-		logger.debug('sendRefer()');
-
-		const extraHeaders = Utils.cloneArray(options.extraHeaders);
-		const eventHandlers = Utils.cloneObject(options.eventHandlers);
-
-		// Set event handlers.
-		for (const event in eventHandlers) {
-			if (Object.prototype.hasOwnProperty.call(eventHandlers, event)) {
-				this.on(event, eventHandlers[event]);
-			}
-		}
-
-		// Replaces URI header field.
-		let replaces = null;
-
-		if (options.replaces) {
-			const dialog = options.replaces._dialog;
-
-			// RFC 3891 section 3: to-tag is the remote tag and from-tag the local
-			// tag of the dialog to replace, whoever sent the initial INVITE.
-			if (dialog) {
-				replaces = dialog.id.call_id;
-				replaces += `;to-tag=${dialog.id.remote_tag}`;
-				replaces += `;from-tag=${dialog.id.local_tag}`;
-			} else {
-				replaces = options.replaces._request.call_id;
-				replaces += `;to-tag=${options.replaces._to_tag}`;
-				replaces += `;from-tag=${options.replaces._from_tag}`;
-			}
-
-			replaces = encodeURIComponent(replaces);
-		}
-
-		// Refer-To header field.
-		const referTo = `Refer-To: <${target}${replaces ? `?Replaces=${replaces}` : ''}>`;
-
-		extraHeaders.push(referTo);
-
-		// Referred-By header field (if not already present).
-		if (
-			!extraHeaders.some(header =>
-				header.toLowerCase().startsWith('referred-by:')
-			)
-		) {
-			const referredBy = `Referred-By: <${this._session._ua._configuration.uri.scheme}:${this._session._ua._configuration.uri.user}@${this._session._ua._configuration.uri.host}>`;
-
-			extraHeaders.push(referredBy);
-		}
-
-		extraHeaders.push(`Contact: ${this._session.contact}`);
-
-		const request = this._session.sendRequest(JsSIP_C.REFER, {
-			extraHeaders,
-			eventHandlers: {
-				onSuccessResponse: response => {
-					this._requestSucceeded(response);
-				},
-				onErrorResponse: response => {
-					this._requestFailed(response, JsSIP_C.causes.REJECTED);
-				},
-				onTransportError: () => {
-					this._requestFailed(null, JsSIP_C.causes.CONNECTION_ERROR);
-				},
-				onRequestTimeout: () => {
-					this._requestFailed(null, JsSIP_C.causes.REQUEST_TIMEOUT);
-				},
-				onDialogError: () => {
-					this._requestFailed(null, JsSIP_C.causes.DIALOG_ERROR);
-				},
-				onAuthenticated: _request => {
-					this._id = _request.cseq;
-					this.emit('authenticated');
-				},
-			},
-		});
-
-		this._id = request.cseq;
-	}
-
-	receiveNotify(request) {
-		logger.debug('receiveNotify()');
-
-		if (!request.body) {
-			return;
-		}
-
-		const status_line = Grammar.parse(
-			request.body.trim().split('\r\n', 1)[0],
-			'Status_Line'
-		);
-
-		if (status_line === -1) {
-			logger.debug(
-				`receiveNotify() | error parsing NOTIFY body: "${request.body}"`
-			);
-
-			return;
-		}
-
-		switch (true) {
-			case /^100$/.test(status_line.status_code): {
-				this.emit('trying', {
-					request,
-					status_line,
-				});
-				break;
-			}
-
-			case /^1[0-9]{2}$/.test(status_line.status_code): {
-				this.emit('progress', {
-					request,
-					status_line,
-				});
-				break;
-			}
-
-			case /^2[0-9]{2}$/.test(status_line.status_code): {
-				this.emit('accepted', {
-					request,
-					status_line,
-				});
-				break;
-			}
-
-			default: {
-				this.emit('failed', {
-					request,
-					status_line,
-				});
-				break;
-			}
-		}
-	}
-
-	_requestSucceeded(response) {
-		logger.debug('REFER succeeded');
-
-		logger.debug('emit "requestSucceeded"');
-
-		this.emit('requestSucceeded', {
-			response,
-		});
-	}
-
-	_requestFailed(response, cause) {
-		logger.debug('REFER failed');
-
-		logger.debug('emit "requestFailed"');
-
-		this.emit('requestFailed', {
-			response: response || null,
-			cause,
-		});
-	}
-};
diff --git a/src/RTCSession/ReferSubscriber.ts b/src/RTCSession/ReferSubscriber.ts
new file mode 100644
index 0000000..91365f6
--- /dev/null
+++ b/src/RTCSession/ReferSubscriber.ts
@@ -0,0 +1,361 @@
+import { EventEmitter } from 'events';
+
+import * as JsSIP_C from '../Constants';
+import type { DialogId, DialogSendRequestOptions } from '../Dialog';
+import * as Grammar from '../Grammar';
+import { Logger } from '../Logger';
+import type {
+	IncomingRequest,
+	IncomingResponse,
+	OutgoingRequest,
+} from '../SIPMessage';
+import * as Utils from '../Utils';
+import URI = require('../URI');
+
+const logger = new Logger('RTCSession:ReferSubscriber');
+
+/**
+ * Reported when the REFER got a final positive response.
+ */
+export type ReferRequestSucceededEvent = {
+	response: IncomingResponse;
+};
+
+/**
+ * Reported when the REFER was not accepted.
+ */
+export type ReferRequestFailedEvent = {
+	/**
+	 * The response that failed the REFER, or `null` when the request never
+	 * got one.
+	 */
+	response: IncomingResponse | null;
+	cause: JsSIP_C.causes;
+};
+
+/**
+ * Reported for each NOTIFY the peer sends about how the transfer is going.
+ */
+export type ReferNotifyEvent = {
+	request: IncomingRequest;
+	/**
+	 * Status line of the `message/sipfrag` body of the NOTIFY, so the status
+	 * the transferred call has reached.
+	 */
+	status_line: Grammar.StatusLine;
+};
+
+/**
+ * The events a {@link ReferSubscriber} emits.
+ */
+export type ReferSubscriberEventMap = {
+	requestSucceeded: [event: ReferRequestSucceededEvent];
+	requestFailed: [event: ReferRequestFailedEvent];
+	/**
+	 * The REFER was challenged and sent again, so {@link ReferSubscriber.id}
+	 * has changed.
+	 */
+	authenticated: [];
+	trying: [event: ReferNotifyEvent];
+	progress: [event: ReferNotifyEvent];
+	accepted: [event: ReferNotifyEvent];
+	failed: [event: ReferNotifyEvent];
+};
+
+/**
+ * The listeners the application registers through the `eventHandlers` option
+ * of `send()`.
+ */
+export type ReferSubscriberEventHandlers = {
+	[K in keyof ReferSubscriberEventMap]: (
+		...args: ReferSubscriberEventMap[K]
+	) => void;
+};
+
+/**
+ * The `RTCSession` surface the session to be replaced is read through.
+ *
+ * TODO: Replace with `import type { RTCSession } from '../RTCSession'` once
+ * `RTCSession` is ported to TypeScript.
+ */
+export interface ReplacedSession {
+	readonly _dialog: { id: DialogId } | null;
+	readonly _request: { call_id: string };
+	readonly _from_tag: string | null;
+	readonly _to_tag: string | null;
+}
+
+/**
+ * Options accepted by `sendRefer()`.
+ */
+export type SendReferOptions = {
+	/**
+	 * Whole `Name: value` header field lines to add to the REFER.
+	 */
+	extraHeaders?: string[] | null;
+	/**
+	 * Listeners registered before the REFER is sent, so that no event is
+	 * missed.
+	 */
+	eventHandlers?: Partial<ReferSubscriberEventHandlers> | null;
+	/**
+	 * Session the transfer is to replace, which adds a `Replaces` parameter to
+	 * the Refer-To URI per
+	 * [RFC 3891](https://datatracker.ietf.org/doc/html/rfc3891).
+	 */
+	replaces?: ReplacedSession | null;
+};
+
+/**
+ * The `RTCSession` surface a refer subscriber depends on.
+ *
+ * TODO: Replace with `import type { RTCSession } from '../RTCSession'` once
+ * `RTCSession` is ported to TypeScript.
+ */
+export interface ReferSubscriberSession {
+	readonly contact: string;
+	// The session exposes no accessor for the UA it belongs to.
+	readonly _ua: {
+		readonly configuration: { uri: URI };
+	};
+
+	sendRequest(
+		method: string,
+		options?: DialogSendRequestOptions
+	): OutgoingRequest | undefined;
+}
+
+/**
+ * Asks the peer to transfer the call, by sending a REFER and following the
+ * NOTIFY requests that report how it goes, per
+ * [RFC 3515](https://datatracker.ietf.org/doc/html/rfc3515).
+ */
+export class ReferSubscriber extends EventEmitter {
+	#session: ReferSubscriberSession;
+	#id: number | null;
+
+	constructor(session: ReferSubscriberSession) {
+		super();
+
+		this.#id = null;
+		this.#session = session;
+	}
+
+	/**
+	 * Sequence number of the REFER, which is the `id` parameter of the Event
+	 * header field of the NOTIFY requests that answer it.
+	 *
+	 * @remarks
+	 * - `null` until the REFER is sent, and renewed when the REFER is
+	 *   challenged, which the `authenticated` event reports.
+	 */
+	get id(): number | null {
+		return this.#id;
+	}
+
+	/**
+	 * Ask the peer to transfer the call to the given target.
+	 *
+	 * @remarks
+	 * - Called by the `RTCSession`. Applications ask for a transfer through
+	 *   its `refer()` instead.
+	 */
+	sendRefer(target: URI | string, options: SendReferOptions = {}): void {
+		logger.debug('sendRefer()');
+
+		const extraHeaders = Utils.cloneArray(options.extraHeaders);
+		const eventHandlers = Utils.cloneObject(options.eventHandlers);
+
+		// Set event handlers. They are registered one by one, rather than by
+		// iterating the object, so that each listener keeps the signature of the
+		// event it is registered for.
+		if (eventHandlers.requestSucceeded) {
+			this.on('requestSucceeded', eventHandlers.requestSucceeded);
+		}
+
+		if (eventHandlers.requestFailed) {
+			this.on('requestFailed', eventHandlers.requestFailed);
+		}
+
+		if (eventHandlers.authenticated) {
+			this.on('authenticated', eventHandlers.authenticated);
+		}
+
+		if (eventHandlers.trying) {
+			this.on('trying', eventHandlers.trying);
+		}
+
+		if (eventHandlers.progress) {
+			this.on('progress', eventHandlers.progress);
+		}
+
+		if (eventHandlers.accepted) {
+			this.on('accepted', eventHandlers.accepted);
+		}
+
+		if (eventHandlers.failed) {
+			this.on('failed', eventHandlers.failed);
+		}
+
+		// Replaces URI header field.
+		let replaces = null;
+
+		if (options.replaces) {
+			const dialog = options.replaces._dialog;
+
+			// RFC 3891 section 3: to-tag is the remote tag and from-tag the local
+			// tag of the dialog to replace, whoever sent the initial INVITE.
+			if (dialog) {
+				replaces = dialog.id.call_id;
+				replaces += `;to-tag=${dialog.id.remote_tag}`;
+				replaces += `;from-tag=${dialog.id.local_tag}`;
+			} else {
+				replaces = options.replaces._request.call_id;
+				replaces += `;to-tag=${options.replaces._to_tag}`;
+				replaces += `;from-tag=${options.replaces._from_tag}`;
+			}
+
+			replaces = encodeURIComponent(replaces);
+		}
+
+		// Refer-To header field.
+		const referTo = `Refer-To: <${target}${replaces ? `?Replaces=${replaces}` : ''}>`;
+
+		extraHeaders.push(referTo);
+
+		// Referred-By header field (if not already present).
+		if (
+			!extraHeaders.some(header =>
+				header.toLowerCase().startsWith('referred-by:')
+			)
+		) {
+			const uri = this.#session._ua.configuration.uri;
+
+			const referredBy = `Referred-By: <${uri.scheme}:${uri.user}@${uri.host}>`;
+
+			extraHeaders.push(referredBy);
+		}
+
+		extraHeaders.push(`Contact: ${this.#session.contact}`);
+
+		const request = this.#session.sendRequest(JsSIP_C.REFER, {
+			extraHeaders,
+			eventHandlers: {
+				onSuccessResponse: response => {
+					this.#requestSucceeded(response);
+				},
+				onErrorResponse: response => {
+					this.#requestFailed(response, JsSIP_C.causes.REJECTED);
+				},
+				onTransportError: () => {
+					this.#requestFailed(null, JsSIP_C.causes.CONNECTION_ERROR);
+				},
+				onRequestTimeout: () => {
+					this.#requestFailed(null, JsSIP_C.causes.REQUEST_TIMEOUT);
+				},
+				onDialogError: () => {
+					this.#requestFailed(null, JsSIP_C.causes.DIALOG_ERROR);
+				},
+				onAuthenticated: _request => {
+					this.#id = _request.cseq;
+					this.emit('authenticated');
+				},
+			},
+		});
+
+		// The session only builds a refer subscriber once it holds a dialog, so
+		// the REFER was certainly sent.
+		this.#id = request!.cseq;
+	}
+
+	/**
+	 * Take over a NOTIFY reporting how the transfer is going.
+	 *
+	 * @remarks
+	 * - Called by the `RTCSession`. The application must not call it.
+	 * - A NOTIFY with no body, or one whose body does not start with a status
+	 *   line, is discarded, so no event is reported for it.
+	 */
+	receiveNotify(request: IncomingRequest): void {
+		logger.debug('receiveNotify()');
+
+		if (!request.body) {
+			return;
+		}
+
+		const status_line: Grammar.StatusLine | -1 = Grammar.parse(
+			request.body.trim().split('\r\n', 1)[0]!,
+			'Status_Line'
+		);
+
+		if (status_line === -1) {
+			logger.debug(
+				`receiveNotify() | error parsing NOTIFY body: "${request.body}"`
+			);
+
+			return;
+		}
+
+		// The grammar only accepts a three digit status code, so matching the
+		// written form tells the ranges apart.
+		const status_code = String(status_line.status_code);
+
+		switch (true) {
+			case /^100$/.test(status_code): {
+				this.emit('trying', {
+					request,
+					status_line,
+				});
+				break;
+			}
+
+			case /^1[0-9]{2}$/.test(status_code): {
+				this.emit('progress', {
+					request,
+					status_line,
+				});
+				break;
+			}
+
+			case /^2[0-9]{2}$/.test(status_code): {
+				this.emit('accepted', {
+					request,
+					status_line,
+				});
+				break;
+			}
+
+			default: {
+				this.emit('failed', {
+					request,
+					status_line,
+				});
+				break;
+			}
+		}
+	}
+
+	#requestSucceeded(response: IncomingResponse): void {
+		logger.debug('REFER succeeded');
+
+		logger.debug('emit "requestSucceeded"');
+
+		this.emit('requestSucceeded', {
+			response,
+		});
+	}
+
+	#requestFailed(
+		response: IncomingResponse | null,
+		cause: JsSIP_C.causes
+	): void {
+		logger.debug('REFER failed');
+
+		logger.debug('emit "requestFailed"');
+
+		this.emit('requestFailed', {
+			response: response || null,
+			cause,
+		});
+	}
+}
diff --git a/src/test/RTCSession/test-ReferSubscriber.ts b/src/test/RTCSession/test-ReferSubscriber.ts
new file mode 100644
index 0000000..992bdc6
--- /dev/null
+++ b/src/test/RTCSession/test-ReferSubscriber.ts
@@ -0,0 +1,257 @@
+import '../include/common';
+
+import { causes } from '../../Constants';
+import type { DialogRequestSenderEventHandlers } from '../../Dialog/RequestSender';
+import type {
+	ReferNotifyEvent,
+	ReferSubscriberSession,
+	ReplacedSession,
+} from '../../RTCSession/ReferSubscriber';
+import { ReferSubscriber } from '../../RTCSession/ReferSubscriber';
+import type {
+	IncomingRequest,
+	IncomingResponse,
+	OutgoingRequest,
+} from '../../SIPMessage';
+import URI = require('../../URI');
+
+const TARGET = 'sip:bob@example.com';
+const CALL_ID = 'a84b4c76e66710';
+const LOCAL_TAG = 'localtag';
+const REMOTE_TAG = 'remotetag';
+
+const CONTACT = '<sip:alice@example.com;transport=ws>';
+
+// A response is only ever handed on to the application, so nothing has to be
+// in it.
+const RESPONSE = {} as IncomingResponse;
+
+const LOCAL_AOR = new URI('sip', 'alice', 'example.com');
+
+// Session to replace, with the fields set by RTCSession once its dialog is
+// confirmed.
+function createReplacedSession(
+	direction: 'outgoing' | 'incoming'
+): ReplacedSession {
+	const outgoing = direction === 'outgoing';
+
+	return {
+		_request: { call_id: CALL_ID },
+		// Tags of the From and To header fields of the initial INVITE.
+		_from_tag: outgoing ? LOCAL_TAG : REMOTE_TAG,
+		_to_tag: outgoing ? REMOTE_TAG : LOCAL_TAG,
+		_dialog: {
+			id: { call_id: CALL_ID, local_tag: LOCAL_TAG, remote_tag: REMOTE_TAG },
+		},
+	};
+}
+
+// Sends a REFER and returns the header fields it added to the request.
+function sendRefer(options: {
+	replaces?: ReplacedSession;
+	extraHeaders?: string[];
+}): string[] {
+	let extraHeaders: string[] = [];
+
+	const session: ReferSubscriberSession = {
+		contact: CONTACT,
+		_ua: { configuration: { uri: LOCAL_AOR } },
+		sendRequest(_method, sent = {}) {
+			extraHeaders = sent.extraHeaders ?? [];
+
+			return { cseq: 1 } as OutgoingRequest;
+		},
+	};
+
+	new ReferSubscriber(session).sendRefer(TARGET, options);
+
+	return extraHeaders;
+}
+
+/**
+ * Sends a REFER with every listener registered through `eventHandlers`, lets
+ * the caller play what becomes of the request, and returns what the
+ * subscriber reported.
+ */
+function referOutcome(
+	respond: (handlers: Partial<DialogRequestSenderEventHandlers>) => void
+): [string, unknown][] {
+	let handlers: Partial<DialogRequestSenderEventHandlers> = {};
+
+	const session: ReferSubscriberSession = {
+		contact: CONTACT,
+		_ua: { configuration: { uri: LOCAL_AOR } },
+		sendRequest(_method, sent = {}) {
+			handlers = sent.eventHandlers ?? {};
+
+			return { cseq: 1 } as OutgoingRequest;
+		},
+	};
+
+	const subscriber = new ReferSubscriber(session);
+	const reported: [string, unknown][] = [];
+
+	subscriber.sendRefer(TARGET, {
+		eventHandlers: {
+			requestSucceeded: event => reported.push(['requestSucceeded', event]),
+			requestFailed: event => reported.push(['requestFailed', event]),
+			// The subscriber is indexed by its id, so what matters about this
+			// event is the id the session can read when it fires.
+			authenticated: () => reported.push(['authenticated', subscriber.id]),
+		},
+	});
+
+	respond(handlers);
+
+	return reported;
+}
+
+// The one header field with the given name, if any.
+function field(headers: string[], name: string): string | undefined {
+	return headers.find(header =>
+		header.toLowerCase().startsWith(`${name.toLowerCase()}:`)
+	);
+}
+
+describe('ReferSubscriber.sendRefer()', () => {
+	test('Replaces of an outgoing session', () => {
+		const headers = sendRefer({ replaces: createReplacedSession('outgoing') });
+
+		expect(field(headers, 'Refer-To')).toBe(
+			'Refer-To: <sip:bob@example.com?Replaces=a84b4c76e66710%3Bto-tag%3Dremotetag%3Bfrom-tag%3Dlocaltag>'
+		);
+	});
+
+	test('Replaces of an incoming session', () => {
+		const headers = sendRefer({ replaces: createReplacedSession('incoming') });
+
+		expect(field(headers, 'Refer-To')).toBe(
+			'Refer-To: <sip:bob@example.com?Replaces=a84b4c76e66710%3Bto-tag%3Dremotetag%3Bfrom-tag%3Dlocaltag>'
+		);
+	});
+
+	test('Replaces of a session without dialog', () => {
+		const replaces = {
+			...createReplacedSession('outgoing'),
+			_dialog: null,
+		};
+
+		expect(field(sendRefer({ replaces }), 'Refer-To')).toBe(
+			'Refer-To: <sip:bob@example.com?Replaces=a84b4c76e66710%3Bto-tag%3Dremotetag%3Bfrom-tag%3Dlocaltag>'
+		);
+	});
+
+	test('a transfer that replaces nothing', () => {
+		const headers = sendRefer({});
+
+		expect(field(headers, 'Refer-To')).toBe('Refer-To: <sip:bob@example.com>');
+	});
+
+	test('the local address goes out as Referred-By, next to the Contact', () => {
+		const headers = sendRefer({});
+
+		expect(field(headers, 'Referred-By')).toBe(
+			'Referred-By: <sip:alice@example.com>'
+		);
+		expect(field(headers, 'Contact')).toBe(`Contact: ${CONTACT}`);
+	});
+
+	test('a Referred-By the caller gave is left alone', () => {
+		const given = 'Referred-By: <sip:carol@example.com>';
+
+		const headers = sendRefer({ extraHeaders: [given] });
+
+		expect(headers.filter(header => header.startsWith('Referred-By:'))).toEqual(
+			[given]
+		);
+	});
+});
+
+describe('the outcome of the REFER', () => {
+	test('a final positive response reports "requestSucceeded"', () => {
+		expect(
+			referOutcome(handlers => handlers.onSuccessResponse!(RESPONSE))
+		).toEqual([['requestSucceeded', { response: RESPONSE }]]);
+	});
+
+	test('each way the REFER can fail has its own cause', () => {
+		const reported = referOutcome(handlers => {
+			handlers.onErrorResponse!(RESPONSE);
+			handlers.onTransportError!();
+			handlers.onRequestTimeout!();
+			handlers.onDialogError!(RESPONSE);
+		});
+
+		expect(reported).toEqual([
+			['requestFailed', { response: RESPONSE, cause: causes.REJECTED }],
+			['requestFailed', { response: null, cause: causes.CONNECTION_ERROR }],
+			['requestFailed', { response: null, cause: causes.REQUEST_TIMEOUT }],
+			// Only a response the peer sent is reported, so a dialog error
+			// carries none even though one went into it.
+			['requestFailed', { response: null, cause: causes.DIALOG_ERROR }],
+		]);
+	});
+
+	test('a challenged REFER renews the id the session indexes it by', () => {
+		const reported = referOutcome(handlers =>
+			handlers.onAuthenticated!({ cseq: 2 } as OutgoingRequest)
+		);
+
+		expect(reported).toEqual([['authenticated', 2]]);
+	});
+});
+
+// A NOTIFY as the peer sends it, of which only the body is read.
+function notify(body: string): IncomingRequest {
+	return { body } as IncomingRequest;
+}
+
+/**
+ * Feeds the given NOTIFY bodies to a subscriber and returns the events it
+ * reported, as `[name, status code]` pairs.
+ */
+function receiveNotify(...bodies: string[]): [string, number][] {
+	const subscriber = new ReferSubscriber({} as ReferSubscriberSession);
+
+	const reported: [string, number][] = [];
+
+	for (const name of ['trying', 'progress', 'accepted', 'failed']) {
+		subscriber.on(name, ({ status_line }: ReferNotifyEvent) =>
+			reported.push([name, status_line.status_code])
+		);
+	}
+
+	for (const body of bodies) {
+		subscriber.receiveNotify(notify(body));
+	}
+
+	return reported;
+}
+
+describe('ReferSubscriber.receiveNotify()', () => {
+	test('each status range is reported as its own event', () => {
+		expect(
+			receiveNotify(
+				'SIP/2.0 100 Trying',
+				'SIP/2.0 180 Ringing',
+				'SIP/2.0 200 OK',
+				'SIP/2.0 486 Busy Here'
+			)
+		).toEqual([
+			['trying', 100],
+			['progress', 180],
+			['accepted', 200],
+			['failed', 486],
+		]);
+	});
+
+	test('only the status line of the body is read', () => {
+		expect(
+			receiveNotify('SIP/2.0 200 OK\r\nContact: <sip:bob@example.com>\r\n')
+		).toEqual([['accepted', 200]]);
+	});
+
+	test('a NOTIFY that reports no status is discarded', () => {
+		expect(receiveNotify('', 'what you will')).toEqual([]);
+	});
+});
diff --git a/src/test/test-ReferSubscriber.ts b/src/test/test-ReferSubscriber.ts
deleted file mode 100644
index 1747ef0..0000000
--- a/src/test/test-ReferSubscriber.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import './include/common';
-
-import ReferSubscriber = require('../RTCSession/ReferSubscriber');
-
-const TARGET = 'sip:bob@example.com';
-const CALL_ID = 'a84b4c76e66710';
-const LOCAL_TAG = 'localtag';
-const REMOTE_TAG = 'remotetag';
-
-// Session to replace, with the fields set by RTCSession once its dialog is
-// confirmed.
-function createReplacedSession(direction: 'outgoing' | 'incoming'): object {
-	const outgoing = direction === 'outgoing';
-
-	return {
-		_request: { call_id: CALL_ID },
-		// Tags of the From and To header fields of the initial INVITE.
-		_from_tag: outgoing ? LOCAL_TAG : REMOTE_TAG,
-		_to_tag: outgoing ? REMOTE_TAG : LOCAL_TAG,
-		_dialog: {
-			id: { call_id: CALL_ID, local_tag: LOCAL_TAG, remote_tag: REMOTE_TAG },
-		},
-	};
-}
-
-// Sends a REFER that replaces the given session and returns its Refer-To
-// header field.
-function sendRefer(replaces: object): string | undefined {
-	let extraHeaders: string[] = [];
-
-	const session = {
-		contact: '<sip:alice@example.com;transport=ws>',
-		_ua: {
-			_configuration: {
-				uri: { scheme: 'sip', user: 'alice', host: 'example.com' },
-			},
-		},
-		sendRequest(_method: string, options: { extraHeaders: string[] }) {
-			extraHeaders = options.extraHeaders;
-
-			return { cseq: 1 };
-		},
-	};
-
-	new ReferSubscriber(session).sendRefer(TARGET, { replaces });
-
-	return extraHeaders.find(header => header.startsWith('Refer-To:'));
-}
-
-describe('ReferSubscriber', () => {
-	test('Replaces of an outgoing session', () => {
-		expect(sendRefer(createReplacedSession('outgoing'))).toBe(
-			'Refer-To: <sip:bob@example.com?Replaces=a84b4c76e66710%3Bto-tag%3Dremotetag%3Bfrom-tag%3Dlocaltag>'
-		);
-	});
-
-	test('Replaces of an incoming session', () => {
-		expect(sendRefer(createReplacedSession('incoming'))).toBe(
-			'Refer-To: <sip:bob@example.com?Replaces=a84b4c76e66710%3Bto-tag%3Dremotetag%3Bfrom-tag%3Dlocaltag>'
-		);
-	});
-
-	test('Replaces of a session without dialog', () => {
-		const replaces = { ...createReplacedSession('outgoing'), _dialog: null };
-
-		expect(sendRefer(replaces)).toBe(
-			'Refer-To: <sip:bob@example.com?Replaces=a84b4c76e66710%3Bto-tag%3Dremotetag%3Bfrom-tag%3Dlocaltag>'
-		);
-	});
-});