### Start Relay Server for Tests Source: https://github.com/twilio/twilio-voice.js/blob/master/README.md Start the relay server required for running integration tests. ```bash npm run test:relay-server ``` -------------------------------- ### Install Twilio Voice SDK with NPM Source: https://github.com/twilio/twilio-voice.js/blob/master/README.md Use this command to add the Voice SDK as a dependency to your project. ```bash npm install @twilio/voice-sdk --save ``` -------------------------------- ### Handle Browser Autoplay Policy with User Interaction Source: https://github.com/twilio/twilio-voice.js/blob/master/COMMON_ISSUES.md To comply with browser autoplay policies, ensure user interaction before initializing the Twilio Device. This example shows how to set up the device after a button click. ```javascript document.getElementById('ready_button').addEventListener('click', () => { device = new Twilio.Device(token); }); ``` -------------------------------- ### Preflight Test Warnings Source: https://github.com/twilio/twilio-voice.js/blob/master/PREFLIGHT.md The 'warnings' property in the preflight test report contains an array of any warnings detected during the test. These can indicate potential issues that do not prevent call setup. ```javascript "warnings": [...] ``` -------------------------------- ### TwiML Bin for Playback Source: https://github.com/twilio/twilio-voice.js/blob/master/PREFLIGHT.md Use this TwiML Bin configuration to create a TwiML App that plays back recorded audio. Ensure your access token is associated with a TwiML app that supports recording and playback. ```xml You said: {{RecordingUrl}} Now waiting for a few seconds to gather audio performance metrics. Hanging up now. ``` -------------------------------- ### Run Unit Tests Source: https://github.com/twilio/twilio-voice.js/blob/master/README.md Execute the unit tests for the Twilio Voice.js SDK using the npm command. ```bash npm run test:unit ``` -------------------------------- ### Display Node, Chrome, and Electron Versions Source: https://github.com/twilio/twilio-voice.js/blob/master/tests/electron/index.html This snippet shows how to write the versions of Node.js, Chrome, and Electron to the document. Useful for debugging or verifying the runtime environment. ```html document.write(process.versions.node), Chrome document.write(process.versions.chrome), and Electron document.write(process.versions.electron). ``` -------------------------------- ### TwiML App for Recording Source: https://github.com/twilio/twilio-voice.js/blob/master/PREFLIGHT.md Use this TwiML Bin to record a message during a preflight test. Configure the action URL to point to your TwiML Bin's playback URL. ```xml Record a message in 3, 2, 1 Did not detect a message to record ``` -------------------------------- ### Handle Preflight Test Sample Event Source: https://github.com/twilio/twilio-voice.js/blob/master/PREFLIGHT.md Process 'sample' events, published every second, to access WebRTC sample data for the call. The sample object format is consistent with Call.on('sample'). ```javascript preflightTest.on('sample', handler(sample)) ``` -------------------------------- ### TwiML App for Echo Source: https://github.com/twilio/twilio-voice.js/blob/master/PREFLIGHT.md This TwiML Bin is used when `PreflightTest.Options.fakeMicInput` is set to true. It captures and plays back audio, requiring a token with a TwiML app that supports this functionality. ```xml ``` -------------------------------- ### Run Integration Tests with Cypress Source: https://github.com/twilio/twilio-voice.js/blob/master/README.md Execute integration tests using Cypress for Chrome or Firefox browsers. ```bash npm run test:integration:chrome npm run test:integration:firefox ``` -------------------------------- ### Generate STUN/TURN Credentials and Run Preflight Test Source: https://github.com/twilio/twilio-voice.js/blob/master/PREFLIGHT.md Generates STUN/TURN credentials using Twilio's Network Traversal Service and configures the preflight test to use specific edge locations and the generated ICE servers. It also logs whether TURN is required for media connection. ```typescript import Client from 'twilio'; import { Device } from '@twilio/voice-sdk'; // Generate the STUN and TURN server credentials with a ttl of 120 seconds const client = Client(twilioAccountSid, authToken); const token = await client.tokens.create({ ttl: 120 }); let iceServers = token.iceServers; // By default, global will be used as the default edge location. // You can replace global with a specific edge name for each of the iceServer configuration. iceServers = iceServers.map(config => { let { url, urls, ...rest } = config; url = url.replace('global', 'ashburn'); urls = urls.replace('global', 'ashburn'); return { url, urls, ...rest }; }); // Use the TURN credentials using the iceServers parameter const preflightTest = Device.runPreflight(token, { iceServers }); // Read from the report object to determine whether TURN is required to connect to media preflightTest.on('completed', (report) => { console.log(report.isTurnRequired); }); ``` -------------------------------- ### Extract Twilio Voice.js SDK from Tarball Source: https://github.com/twilio/twilio-voice.js/blob/master/README.md Use this command to extract the Twilio Voice.js SDK from a downloaded tar.gz file. ```bash tar -xvzf twilio-voice.js-2.0.0.tar.gz cd twilio-voice.js-2.0.0 ``` -------------------------------- ### Running a Preflight Test Source: https://github.com/twilio/twilio-voice.js/blob/master/PREFLIGHT.md Initiates a preflight test call using a Twilio Access Token and optional configuration settings. The test returns an object that emits 'completed' or 'failed' events. ```APIDOC ## Device.runPreflight(token, options) ### Description Initiates a preflight test call to determine Voice calling readiness. This method is a static member of the `Device` class. ### Method Static method of the `Device` class. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### Token `token` (string) - Required - A Twilio Access Token used to initiate the test call. This token is passed to the `Device` constructor and used to connect to a TwiML app capable of recording and playing back audio. #### Options `options` (object) - Optional - Configuration settings for the preflight test. ##### `codecPreferences` - `codecPreferences` (array of strings) - Optional - An ordered list of preferred codecs. Defaults to `['pcmu', 'opus']`. ##### `debug` - `debug` (boolean) - Optional - Set to `true` to enable debug logging in the browser console. Defaults to `false`. ##### `edge` - `edge` (string) - Optional - Specifies which Twilio edge to use for the test call. Defaults to `roaming`. See [edges](https://www.twilio.com/docs/voice/sdks/javascript/edges) documentation for available options. ##### `fakeMicInput` - `fakeMicInput` (boolean) - Optional - If `true`, the test call ignores microphone input and uses a default audio file. If `false`, it captures audio from the microphone. Defaults to `false`. ##### `iceServers` - `iceServers` (array of objects) - Optional - An array of custom ICE servers for media connection. If provided, the test detects if a TURN server is required. See [Using Twilio NTS for Generating STUN/TURN Credentials](#using-twilio-nts-for-generating-stunturn-credentials). ##### `signalingTimeoutMs` - `signalingTimeoutMs` (number) - Optional - The time in milliseconds to wait for establishing a signaling connection. Defaults to `10000`. ### Request Example ```javascript import { Device } from '@twilio/voice-sdk'; const token = "YOUR_TWILIO_ACCESS_TOKEN"; const options = { codecPreferences: ['opus', 'pcmu'], debug: true, edge: 'frankfurt', fakeMicInput: false, signalingTimeoutMs: 5000 }; const preflightTest = Device.runPreflight(token, options); preflightTest.on(Device.Events.Preflight.Completed, (report) => { console.log('Preflight test completed:', report); }); preflightTest.on(Device.Events.Preflight.Failed, (error) => { console.error('Preflight test failed:', error); }); ``` ### Response #### Success Response (200) Returns a `PreflightTest` object which is an EventEmitter. #### Response Example ```javascript // The 'report' object passed to the 'completed' event handler might contain: { isTurnRequired: true, // ... other report details } ``` ### Events The `PreflightTest` object emits the following events: - **`completed`**: Emitted when the preflight test successfully completes. It receives a `report` object containing details about the test results. - **`failed`**: Emitted when the preflight test fails. It receives an `error` object detailing the failure. ``` -------------------------------- ### Import Device with CommonJS Source: https://github.com/twilio/twilio-voice.js/blob/master/README.md Import the Device module from the Twilio Voice SDK using CommonJS syntax. ```javascript const Device = require('@twilio/voice-sdk').Device; ``` -------------------------------- ### Run Preflight Test - Twilio Voice.js Source: https://github.com/twilio/twilio-voice.js/blob/master/PREFLIGHT.md Initiates a preflight test call using the provided token and options. Subscribes to 'completed' and 'failed' events to log the test report or error. ```typescript import { Device, PreflightTest } from '@twilio/voice-sdk'; const preflightTest = Device.runPreflight(token, options); preflightTest.on(PreflightTest.Events.Completed, (report) => { console.log(report); }); preflightTest.on(PreflightTest.Events.Failed, (error) => { console.log(error); }); ``` -------------------------------- ### Import Device with ES Module or TypeScript Source: https://github.com/twilio/twilio-voice.js/blob/master/README.md Import the Device module from the Twilio Voice SDK using ES Module or TypeScript syntax. ```javascript import { Device } from '@twilio/voice-sdk'; ``` -------------------------------- ### Include Twilio Voice.js SDK in HTML Source: https://github.com/twilio/twilio-voice.js/blob/master/README.md Include the minified version of the Twilio Voice.js SDK in your HTML file using a script tag. ```html ``` -------------------------------- ### TwiML for STIR/SHAKEN Integration Tests Source: https://github.com/twilio/twilio-voice.js/blob/master/README.md This TwiML is used for setting up the 'STIR/SHAKEN' TwiML App for Twilio Voice.js integration testing. Ensure your Twilio number is used for the Dial verb. ```xml xxxxxxxxxxxxxxxx ``` -------------------------------- ### CSP connect-src for Multiple Edge Locations Source: https://github.com/twilio/twilio-voice.js/blob/master/README.md Include Signaling URIs for multiple edge locations in your connect-src directive when using an array for Device.ConnectOptions.edge. ```http connect-src https://eventgw.twilio.com https://media.twiliocdn.com https://sdk.twilio.com wss://voice-js.ashburn.twilio.com wss://voice-js.sydney.twilio.com wss://voice-js.roaming.twilio.com ``` -------------------------------- ### TwiML for Integration Tests Source: https://github.com/twilio/twilio-voice.js/blob/master/README.md This TwiML is used for setting up the 'Integration Tests' TwiML App for Twilio Voice.js integration testing. It includes parameters for client identity and custom parameters. ```xml {{To}} ``` -------------------------------- ### Handle Preflight Test Failed Event Source: https://github.com/twilio/twilio-voice.js/blob/master/PREFLIGHT.md Handle the 'failed' event to address issues during connection establishment or fatal errors in the test call. This event is also triggered if .stop() is called during the test. ```javascript preflightTest.on('failed', handler(error)) ``` -------------------------------- ### PreflightTest Events Source: https://github.com/twilio/twilio-voice.js/blob/master/PREFLIGHT.md Event handlers for monitoring the status and progress of a preflight test. ```APIDOC ## .on('connected', handler) ### Description Raised when `PreflightTest.status` has transitioned to `PreflightTest.Status.Connected`. This signifies that the connection to Twilio has been successfully established. ### Method .on('connected', handler) ``` ```APIDOC ## .on('failed', handler(error)) ### Description Raised when `PreflightTest.status` has transitioned to `PreflightTest.Status.Failed`. This occurs if establishing a connection to Twilio fails, a test call encounters a fatal error, or if `PreflightTest.stop` is invoked during the test. The emitted error follows the format of [Device.on('error')](https://www.twilio.com/docs/voice/sdks/javascript/twiliodevice#error-event). ### Method .on('failed', handler(error)) ``` ```APIDOC ## .on('sample', handler(sample)) ### Description Published every second, this event is raised when the [Call](https://www.twilio.com/docs/voice/sdks/javascript/twiliocall) receives a WebRTC sample object. The `sample` object is sourced from [Call.on('sample')](https://www.twilio.com/docs/voice/sdks/javascript/twiliocall#sample-event) and adheres to the same format. ### Method .on('sample', handler(sample)) ``` ```APIDOC ## .on('warning', handler(warning)) ### Description Raised when the preflight test encounters a warning. The warning object may contain a `name`, `description`, and optional `rtcWarning` data. ### Method .on('warning', handler(warning)) ``` -------------------------------- ### Default Content Security Policy Directives Source: https://github.com/twilio/twilio-voice.js/blob/master/README.md Recommended CSP directives for twilio-voice.js compatibility. These should be included in your Content Security Policy. ```http script-src https://media.twiliocdn.com https://sdk.twilio.com media-src mediastream: https://media.twiliocdn.com https://sdk.twilio.com connect-src https://eventgw.twilio.com wss://voice-js.roaming.twilio.com https://media.twiliocdn.com https://sdk.twilio.com ``` -------------------------------- ### Preflight Test Completed Report Structure Source: https://github.com/twilio/twilio-voice.js/blob/master/PREFLIGHT.md The 'completed' event provides a detailed report object. Inspect properties like 'callQuality', 'iceCandidateStats', and 'networkTiming' to understand the call's performance. ```json { "callSid": "CAa6a7a187a9cba2714d6fdccf472cc7b1", "callQuality": "excellent", "iceCandidateStats": [...], "selectedIceCandidatePairStats": { "localCandidate": {...}, "remoteCandidate": {...} }, "isTurnRequired": false, "networkTiming": { "dtls": { "start": 1584573229981, "end": 1584573230166, "duration": 185 }, "ice": { "start": 1584573229898, "end": 1584573229982, "duration": 84 }, "peerConnection": { "start": 1584573229902, "end": 1584573230167, "duration": 265 }, "signaling": { "start": 1595885835227, "end": 1595885835573, "duration": 346 } }, "stats": { "jitter": { "average": 35, "max": 35, "min": 35 }, "mos": { "average": 2, "max": 2, "min": 2 }, "rtt": { "average": 80.33, "max": 88, "min": 77 } }, "testTiming": { "start": 1584573229085, "end": 1584573242279, "duration": 13194 }, "totals": { "bytesReceived": 62720, "bytesSent": 93760, "packetsLost": 0, "packetsLostFraction": 0, "packetsReceived": 392, "packetsSent": 586 }, "samples": [...] } ``` -------------------------------- ### Configure Selected Edge for Preflight Test Source: https://github.com/twilio/twilio-voice.js/blob/master/PREFLIGHT.md Set the 'selectedEdge' property to specify the network edge for the preflight test. This helps in testing connectivity to a specific Twilio edge. ```javascript "selectedEdge": "roaming" ``` -------------------------------- ### Handle Preflight Test Connected Event Source: https://github.com/twilio/twilio-voice.js/blob/master/PREFLIGHT.md Listen for the 'connected' event to know when the connection to Twilio has been successfully established. ```javascript preflightTest.on('connected', handler()) ``` -------------------------------- ### PreflightTest.stop() Source: https://github.com/twilio/twilio-voice.js/blob/master/PREFLIGHT.md Stops the ongoing preflight test and triggers a 'failed' event. ```APIDOC ## .stop() ### Description Calling this method on the `PreflightTest` object will stop the existing test. This action will raise a `failed` event with an error code `31008`, indicating that the call has been cancelled. ### Method .stop() ``` -------------------------------- ### Handle Preflight Test Completion Source: https://github.com/twilio/twilio-voice.js/blob/master/PREFLIGHT.md Attach a handler to the 'completed' event to process the results of the preflight test. The handler receives a report object containing details about the test. ```javascript preflightTest.on('completed', handler(report)) ``` -------------------------------- ### CSP connect-src for Specific Edge Location Source: https://github.com/twilio/twilio-voice.js/blob/master/README.md Add the Signaling URI for a specific edge location to your connect-src directive if you are using the Device.ConnectOptions.edge parameter. ```http connect-src https://eventgw.twilio.com https://media.twiliocdn.com https://sdk.twilio.com wss://voice-js.ashburn.twilio.com ``` -------------------------------- ### PreflightTest Properties Source: https://github.com/twilio/twilio-voice.js/blob/master/PREFLIGHT.md Accessible properties of the PreflightTest object providing details about the test status and results. ```APIDOC ## PreflightTest Properties ### `callSid` - **Type**: string - **Description**: The `callSid` generated for the test call. This is set when the client has finished connecting to Twilio. ### `endTime` - **Type**: number - **Description**: A timestamp in milliseconds of when the test ended. This is set when the test has completed and raised the `completed` event. ### `latestSample` - **Type**: object - **Description**: The latest WebRTC sample collected. This is set whenever the connection emits a `sample`. Please see [Call.on('sample')](https://www.twilio.com/docs/voice/sdks/javascript/twiliocall#sample-event) API for more details. ### `report` - **Type**: object - **Description**: The report for this test. This is set when the test has completed and raised the `completed` event. ### `startTime` - **Type**: number - **Description**: A timestamp in milliseconds of when the test started. This is set right after calling `Device.runPreflight(token, options)`. ### `status` - **Type**: string - **Description**: The status of the test. Possible values include: - `Completed`: The connection to Twilio has been disconnected and the test call has completed. - `Connected`: The connection to Twilio has been established. - `Connecting`: Connecting to Twilio has started. - `Failed`: The test has stopped and failed. ``` -------------------------------- ### Preflight Test Warning Data Structure Source: https://github.com/twilio/twilio-voice.js/blob/master/PREFLIGHT.md Examine the structure of warning data received from the 'warning' event, which may include connection errors or RTCWarning details. ```typescript { /** * Name of the warning. * See https://www.twilio.com/docs/voice/voice-insights/api/call/details-sdk-call-quality-events */ name: 'insights-connection-error', /** * Description of the Warning. */ description: 'Received an error when attempting to connect to Insights gateway', /** * Optional RTCWarning data coming from Call.on('warning') * See https://www.twilio.com/docs/voice/sdks/javascript/twiliocall#warning-event */ rtcWarning: {...} } ``` -------------------------------- ### Access Twilio Device Globally Source: https://github.com/twilio/twilio-voice.js/blob/master/README.md Access the Twilio Device object from the browser global scope after including the SDK. ```javascript const Device = Twilio.Device; ``` -------------------------------- ### Preflight Test Edge Information Source: https://github.com/twilio/twilio-voice.js/blob/master/PREFLIGHT.md The 'edge' property in the preflight test report indicates the network edge to which the test call was connected. This is useful for diagnosing connectivity issues. ```javascript "edge": "ashburn" ``` -------------------------------- ### Stop Preflight Test Source: https://github.com/twilio/twilio-voice.js/blob/master/PREFLIGHT.md Invoke the .stop() method on a PreflightTest object to terminate the ongoing test. This action will trigger a 'failed' event with error code 31008. ```javascript preflightTest.stop() ``` -------------------------------- ### CSP connect-src with Home Region Grant Source: https://github.com/twilio/twilio-voice.js/blob/master/README.md Add the insights endpoint for your home region grant to the connect-src directive when using Twilio access tokens with a home region. ```http connect-src https://eventgw.sg1.twilio.com wss://voice-js.roaming.twilio.com https://media.twiliocdn.com https://sdk.twilio.com ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.