ivr-tester
Version:
An automated testing framework for IVR call flows
90 lines (89 loc) • 3.36 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.TwilioCallServer = void 0;
const ws_1 = require("ws");
const TwilioCall_1 = require("../call/TwilioCall");
const url_1 = require("url");
const Emitter_1 = require("../Emitter");
class TwilioCallServer extends Emitter_1.TypedEmitter {
constructor(dtmfBufferGenerator, testAssigner, testExecutor) {
super();
this.dtmfBufferGenerator = dtmfBufferGenerator;
this.testAssigner = testAssigner;
this.testExecutor = testExecutor;
}
static formatServerUrl(server) {
const address = server.address();
switch (address.family) {
case "IPv4":
return new url_1.URL(`http://${address.address}:${address.port}`);
case "IPv6": // https://tools.ietf.org/html/rfc2732#section-2
return new url_1.URL(`http://[${address.address}]:${address.port}`);
default:
throw new Error(`Unrecognised '${address.family}' address family`);
}
}
static convertToWebSocketUrl(serverUrl) {
const streamUrl = new url_1.URL(serverUrl.toString());
streamUrl.pathname = "/";
streamUrl.protocol = streamUrl.protocol === "https:" ? "wss" : "ws";
return streamUrl;
}
listen(port) {
if (this.wss) {
throw new Error("Server already started");
}
this.wss = new ws_1.Server({ port });
return new Promise((resolve, reject) => {
const onError = (err) => reject(err);
this.wss.on("error", onError);
this.wss.on("listening", () => {
this.wss.off("error", onError);
const localUrl = TwilioCallServer.convertToWebSocketUrl(TwilioCallServer.formatServerUrl(this.wss));
this.emit("listening", { localUrl });
this.wss.on("connection", (ws) => this.callConnected(ws));
this.wss.on("close", () => this.closed());
this.wss.on("error", (error) => this.serverError(error));
resolve(localUrl);
});
});
}
async stop() {
await new Promise((resolve, reject) => {
if (!this.wss) {
resolve();
return;
}
this.wss.close((err) => {
if (err) {
reject(err);
}
else {
resolve();
}
});
this.wss = undefined;
});
}
callConnected(callWebSocket) {
const call = new TwilioCall_1.TwilioCall(callWebSocket, this.dtmfBufferGenerator);
this.emit("callConnected", { call });
const result = this.testAssigner.assign();
if (result.isAssigned === true) {
const testSession = this.testExecutor.startTest(result.scenario, call);
this.emit("testStarted", { testSession });
}
else {
call.close(TwilioCallServer.TestCouldNotBeAssignedReason);
}
}
closed() {
this.emit("stopped", undefined);
this.wss = undefined;
}
serverError(error) {
this.emit("error", { error });
}
}
exports.TwilioCallServer = TwilioCallServer;
TwilioCallServer.TestCouldNotBeAssignedReason = "TestCouldNotBeAssigned";