How to use negotiateProtocol method in ava

Best JavaScript code snippet using ava

index.js

Source:index.js Github

copy

Full Screen

1const url = require('url')2const querystring = require('querystring')34const http = require('http')5const https = require('https')67const websocketClient = require('ws')89const util = require('util')10const events = require('events')1112/**13 * A signalR client for node.js which support ASP.net but not ASP.net Core.14 * For ASP.net Core signalR support use the offical client from Microsoft.15 */16class signalrClient {17 /**18 * @param {String} url19 * @param {string[]} hubs20 */21 constructor(url, hubs) {22 this.url = url23 this.qs = {}24 this.headers = {}25 this.agent = false26 this.reconnectDelayTime = 500027 this.requestTimeout = 500028 this.callTimeout = 500029 this.connection = {30 state: connectionState.disconnected,31 hub: new hub(this),32 lastMessageAt: new Date().getTime()33 }34 this._bound = false35 this._websocket = undefined36 this._hubNames = hubs37 this._invocationId = 038 this._callTimeout = 039 this._keepAliveTimeout = 500040 this._keepAlive = true41 this._beatInterval = 500042 this._beatTimer = null43 this._reconnectCount = 044 this._reconnectTimer = null45 }4647 _receiveMessage(message) {48 this._markLastMessage()49 if (message.type === 'message' && message.data != '{}') {50 let data = JSON.parse(message.data)51 if (data.M) {52 data.M.forEach((message) => {53 let hubName = message.H.toLowerCase()54 let handler = this.connection.hub.handlers[hubName]55 if (handler) {56 let methodName = message.M.toLowerCase()57 let method = handler[methodName]58 if (method) {59 method.apply(this, message.A)60 }61 }62 })63 } else if (data.I) {64 this.connection.hub._handleCallback(+data.I, data.E, data.R)65 }66 }67 }6869 _sendMessage(hub, method, args) {70 let payload = JSON.stringify({71 H: hub,72 M: method,73 A: args,74 I: this._invocationId75 })76 ++this._invocationId77 if (this._websocket && this._websocket.readyState === this._websocket.OPEN) {78 this._websocket.send(payload, (err) => {79 if (err) console.log(err)80 })81 }82 }8384 _negotiate() {85 return new Promise((resolve, reject) => {86 let query = querystring.stringify({87 ...this.qs,88 connectionData: JSON.stringify(this._hubNames),89 clientProtocol: 1.590 })91 let negotiateRequestOptions = url.parse(`${this.url}/negotiate?${query}`, true)92 negotiateRequestOptions.headers = this.headers93 negotiateRequestOptions.timeout = this.requestTimeout || 500094 if (this.agent) negotiateRequestOptions.agent = this.agent95 let req = this.request.get(negotiateRequestOptions, (res) => {96 let data = ''97 res.on('data', (chunk) => {98 data += chunk99 })100 res.on('end', () => {101 try {102 if (res.statusCode == 200) {103 let negotiateProtocol = JSON.parse(data)104 if (!negotiateProtocol.TryWebSockets) {105 reject({ code: errorCode.unsupportedWebsocket, message: null })106 }107 resolve(negotiateProtocol)108 } else if (res.statusCode == 401 || res.statusCode == 302) {109 reject({ code: errorCode.unauthorized, message: null })110 } else {111 reject({ code: errorCode.negotiateError, message: res.statusCode })112 }113 } catch (e) {114 reject({ code: errorCode.negotiateError, message: e })115 }116 })117 res.on('error', (e) => {118 reject({ code: errorCode.negotiateError, message: e })119 })120 })121 req.on('error', (e) => {122 if (req.aborted) return123 req = null124 reject({ code: errorCode.negotiateError, message: e })125 })126 req.on('timeout', () => {127 req.abort()128 reject({ code: errorCode.negotiateError, message: 'ETIMEDOUT' })129 })130 })131 }132133 _connect() {134 let url = this.url.replace(/^http/, "ws")135 let query = querystring.stringify({136 ...this.qs,137 clientProtocol: 1.5,138 transport: "webSockets",139 connectionToken: this.connection.token,140 connectionData: JSON.stringify(this._hubNames),141 tid: 10142 })143 let ws = new websocketClient(`${url}/connect?${query}`, {144 handshakeTimeout: this.requestTimeout,145 headers: this.headers146 })147 ws.onopen = (event) => {148 this._invocationId = 0149 this._callTimeout = 0150 this._start().then(() => {151 this._reconnectCount = 0152 this.emit('connected')153 this.connection.state = connectionState.connected154 this._markLastMessage()155 if (this._keepAlive) this._beat()156 }).catch((error) => {157 this.connection.state = connectionState.disconnected158 this._error(error.code, error.message)159 })160 }161 ws.onerror = (event) => {162 this._error(errorCode.socketError, event.error)163 }164 ws.onmessage = (message) => {165 this._receiveMessage(message)166 }167 ws.onclose = (event) => {168 this._callTimeout = 1000169 this.connection.state = connectionState.disconnected170 this.emit('disconnected', 'failed')171 this._reconnect()172 }173 ws.on('unexpected-response', (request, response) => {174 this.connection.state = connectionState.disconnected175 if (response && response.statusCode === 401) {176 this._error(errorCode.unauthorized)177 this._clearBeatTimer()178 this._close()179 this.emit('disconnected', 'unauthorized')180 } else {181 this._error(errorCode.connectError)182 }183 })184 this._websocket = ws185 }186187 _reconnect(restart = false) {188 if (this._reconnectTimer || this.connection.state === connectionState.reconnecting) return189 this._clearBeatTimer()190 this._close()191 this._reconnectTimer = setTimeout(() => {192 ++this._reconnectCount193 this.connection.state = connectionState.reconnecting194 this.emit('reconnecting', this._reconnectCount)195 restart ? this.start() : this._connect()196 this._reconnectTimer = null197 }, this.reconnectDelayTime || 5000)198 }199200 _clearReconnectTimer() {201 if (this._reconnectTimer) {202 clearTimeout(this._reconnectTimer)203 this._reconnectTimer = null204 }205 }206207 _beat() {208 let timeElapsed = new Date().getTime() - this.connection.lastMessageAt209 if (timeElapsed > this._keepAliveTimeout) {210 this.connection.state = connectionState.disconnected211 this._error(errorCode.connectLost)212 } else {213 this._beatTimer = setTimeout(() => {214 this._beat()215 }, this._beatInterval)216 }217 }218219 _clearBeatTimer() {220 if (this._beatTimer) {221 clearTimeout(this._beatTimer)222 this._beatTimer = null223 }224 }225226 _markLastMessage() {227 this.connection.lastMessageAt = new Date().getTime()228 }229230 _start() {231 return new Promise((resolve, reject) => {232 let query = querystring.stringify({233 ...this.qs,234 clientProtocol: 1.5,235 transport: "webSockets",236 connectionToken: this.connection.token,237 connectionData: JSON.stringify(this._hubNames)238 })239 let startRequestOptions = url.parse(`${this.url}/start?${query}`, true)240 startRequestOptions.headers = this.headers241 startRequestOptions.timeout = this.requestTimeout || 5000242 if (this.agent) startRequestOptions.agent = this.agent243 let req = this.request.get(startRequestOptions, res => {244 let data = ''245 res.on('data', (chunk) => { data += chunk })246 res.on('end', () => {247 if (res.statusCode == 200) {248 resolve(data)249 } else if (res.statusCode == 401 || res.statusCode == 302) {250 reject({ code: errorCode.unauthorized, message: null })251 } else {252 reject({ code: errorCode.startError, message: res.statusCode })253 }254 })255 res.on('error', (e) => {256 reject({ code: errorCode.startError, message: e })257 })258 })259 req.on('error', (e) => {260 if (req.aborted) return261 req = null262 reject({ code: errorCode.startError, message: e })263 })264 req.on('timeout', () => {265 req.abort()266 reject({ code: errorCode.startError, message: 'ETIMEDOUT' })267 })268 })269 }270271 _abort() {272 return new Promise((resolve, reject) => {273 let query = querystring.stringify({274 ...this.qs,275 clientProtocol: 1.5,276 transport: "webSockets",277 connectionToken: this.connection.token,278 connectionData: JSON.stringify(this._hubNames)279 })280 let abortRequestOptions = url.parse(`${this.url}/abort?${query}`, true)281 abortRequestOptions.method = 'POST'282 abortRequestOptions.headers = this.headers283 abortRequestOptions.timeout = this.requestTimeout || 5000284 if (this.agent) abortRequestOptions.agent = this.agent285 let req = this.request.request(abortRequestOptions, res => {286 res.on('data', (chunk) => { })287 res.on('end', () => { resolve() })288 res.on('error', (e) => { reject({ code: errorCode.abortError, message: e }) })289 })290 req.on('error', (e) => { reject({ code: errorCode.abortError, message: e }) })291 req.write('')292 req.end()293 })294 }295296 _error(code, ex = null) {297 this.emit('error', code, ex)298 if (code === errorCode.negotiateError || code === errorCode.connectError) {299 this._reconnect(true)300 }301 if (code === errorCode.startError || code === errorCode.connectLost) {302 this._reconnect()303 }304 }305306 _close() {307 if (this._websocket) {308 this._websocket.onclose = () => { }309 this._websocket.onmessage = () => { }310 this._websocket.onerror = () => { }311 this._websocket.close()312 this._websocket = undefined313 }314 }315316 start() {317 if (!this._bound) {318 if (!this.url) {319 this._error(errorCode.invalidURL)320 return321 }322 if (this.url.startsWith('http:') || this.url.startsWith('https:')) {323 let _url = url.parse(this.url)324 this.request = _url.protocol === 'https:' ? https : http325 } else {326 this._error(errorCode.invalidProtocol)327 return328 }329 if (this._hubNames && this._hubNames.length > 0) {330 let hubNames = []331 this._hubNames.forEach(name => {332 hubNames.push({ name: name.toLowerCase() })333 })334 this._hubNames = hubNames335 } else {336 this._error(errorCode.noHub)337 return338 }339 this._bound = true340 }341 this._negotiate().then((negotiateProtocol) => {342 this.connection = {343 ...this.connection,344 id: negotiateProtocol.ConnectionId,345 token: negotiateProtocol.ConnectionToken346 }347 if (negotiateProtocol.KeepAliveTimeout) {348 this._keepAlive = true349 this._keepAliveTimeout = negotiateProtocol.KeepAliveTimeout * 1000350 this._beatInterval = this._keepAliveTimeout / 4351 } else {352 this._keepAlive = false353 }354 this._connect()355 }).catch((error) => {356 this.connection.state = connectionState.disconnected357 this._error(error.code, error.message)358 })359 }360361 end() {362 if (this._websocket) {363 this.emit('disconnected', 'end')364 this._abort().catch((e) => {365 console.log(e.code)366 // this._error(e.code, e.message)367 })368 }369 this._clearReconnectTimer()370 this._clearBeatTimer()371 this._close()372 }373}374375class hub {376 /**377 * @param {signalrClient} client378 */379 constructor(client) {380 this.client = client381 this.handlers = {}382 this.callbacks = {}383 }384385 _handleCallback(invocationId, error, result) {386 let cb = this.callbacks[invocationId]387 if (cb) cb(error, result)388 }389390 /**391 * Binding events receive messages392 */393 on(hubName, methodName, cb) {394 let handler = this.handlers[hubName.toLowerCase()]395 if (!handler) {396 handler = this.handlers[hubName.toLowerCase()] = {}397 }398 handler[methodName.toLowerCase()] = cb399 }400401 _processInvocationArgs(args) {402 let messages = []403 if (args.length > 2) {404 for (let i = 2; i < args.length; i++) {405 let arg = args[i]406 messages[i - 2] = (typeof arg === "function" || typeof arg === "undefined") ? null : arg407 }408 }409 return messages410 }411412 /**413 * Call the hub method and get return values asynchronously414 */415 call(hubName, methodName) {416 return new Promise((resolve, reject) => {417 let messages = this._processInvocationArgs(arguments)418 let invocationId = this.client._invocationId419 let timeoutTimer = setTimeout(() => {420 delete this.callbacks[invocationId]421 reject('Timeout')422 }, this.client._callTimeout || this.client.callTimeout || 5000)423 this.callbacks[invocationId] = (err, result) => {424 clearTimeout(timeoutTimer)425 delete this.callbacks[invocationId]426 return err ? reject(err) : resolve(result)427 }428 this.client._sendMessage(hubName, methodName, messages)429 })430 }431432 /**433 * Invoke the hub method without return values434 */435 invoke(hubName, methodName) {436 let messages = this._processInvocationArgs(arguments)437 this.client._sendMessage(hubName, methodName, messages)438 }439}440441const errorCode = {442 invalidURL: 'Invalid URL',443 invalidProtocol: 'Invalid protocol',444 noHub: 'No hub',445 unsupportedWebsocket: 'Websockets is not supported',446 unauthorized: 'Unauthorized',447 connectLost: 'Connect lost',448 negotiateError: 'Negotiate error',449 startError: 'Start error',450 connectError: 'Connect error',451 socketError: 'Socket error',452 abortError: 'Abort error'453}454455const connectionState = {456 connected: 1,457 reconnecting: 2,458 disconnected: 4459}460461util.inherits(signalrClient, events.EventEmitter)462463exports.client = signalrClient464exports.error = errorCode ...

Full Screen

Full Screen

_worker.js

Source:_worker.js Github

copy

Full Screen

1exports.default = ({negotiateProtocol}) => {2 negotiateProtocol(['experimental']).ready();...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var availableProtocols = require('./availableProtocols');2var protocol = availableProtocols.negotiateProtocol('HTTP/1.1', 'HTTP/1.1');3console.log(protocol);4var availableProtocols = require('./availableProtocols');5var protocol = availableProtocols.negotiateProtocol('HTTP/1.1', 'HTTP/1.0');6console.log(protocol);7var availableProtocols = require('./availableProtocols');8var protocol = availableProtocols.negotiateProtocol('HTTP/1.0', 'HTTP/1.1');9console.log(protocol);10var availableProtocols = require('./availableProtocols');11var protocol = availableProtocols.negotiateProtocol('HTTP/1.0', 'HTTP/1.0');12console.log(protocol);13var availableProtocols = require('./availableProtocols');14var protocol = availableProtocols.negotiateProtocol('HTTP/1.0', 'HTTP/2.0');15console.log(protocol);16var availableProtocols = require('./availableProtocols');17var protocol = availableProtocols.negotiateProtocol('HTTP/2.0', 'HTTP/1.0');18console.log(protocol);19var availableProtocols = require('./availableProtocols');20var protocol = availableProtocols.negotiateProtocol('HTTP/2.0', 'HTTP/1.1');21console.log(protocol);22var availableProtocols = require('./availableProtocols');

Full Screen

Using AI Code Generation

copy

Full Screen

1const availableProtocols = require('availableProtocols');2const request = require('request');3request(url, (error, response, body) => {4 if (error) {5 console.log(error);6 } else {7 const protocol = availableProtocols.negotiateProtocol(response);8 console.log(protocol);9 }10});

Full Screen

Using AI Code Generation

copy

Full Screen

1var availableProtocols = require('./availableProtocols');2var request = require('request');3request.get(url, function(err, res, body) {4 var protocol = availableProtocols.negotiateProtocol(res.headers['accept']);5 console.log(protocol);6});7var availableProtocols = require('./availableProtocols');8var request = require('request');9request.get(url, function(err, res, body) {10 var protocols = availableProtocols.availableProtocols(res.headers['accept']);11 console.log(protocols);12});

Full Screen

Using AI Code Generation

copy

Full Screen

1var availableProtocols = require('available-protocols');2console.log(protocol);3var availableProtocols = require('available-protocols');4console.log(protocol);5var availableProtocols = require('available-protocols');6console.log(protocol);7var availableProtocols = require('available-protocols');8console.log(protocol);9var availableProtocols = require('available-protocols');10console.log(protocol);11var availableProtocols = require('available-protocols');12console.log(protocol);13var availableProtocols = require('available-protocols');14console.log(protocol);15var availableProtocols = require('available-protocols');16console.log(protocol);

Full Screen

Using AI Code Generation

copy

Full Screen

1const protocol = availableProtocols.negotiateProtocol(2);3console.log(protocol);4const protocol = availableProtocols.negotiateProtocol(5);6console.log(protocol);7const protocol = availableProtocols.negotiateProtocol(8);9console.log(protocol);10const protocol = availableProtocols.negotiateProtocol(11);12console.log(protocol);13const protocol = availableProtocols.negotiateProtocol(14);15console.log(protocol);16const protocol = availableProtocols.negotiateProtocol(17);18console.log(protocol);

Full Screen

Using AI Code Generation

copy

Full Screen

1function getProtocol() {2 var availableProtocols = document.getElementById("protocols").value;3 var protocol = availableProtocols.split(',');4 return protocol;5}6function getNegotiatedProtocol() {7 var protocol = document.getElementById("negotiatedProtocol").value;8 return protocol;9}10function negotiateProtocol() {11 var protocol = getProtocol();12 var negotiatedProtocol = getNegotiatedProtocol();13 var result = navigator.negotiateProtocol(negotiatedProtocol, protocol);14 document.getElementById("result").innerHTML = result;15}16 <p><button type="button" onclick="negotiateProtocol()">Negotiate Protocol</button></p>

Full Screen

Using AI Code Generation

copy

Full Screen

1var protocol = availableProtocols.negotiateProtocol(requestedProtocols);2var protocol = availableProtocols.negotiateProtocol(requestedProtocols);3var protocol = availableProtocols.negotiateProtocol(requestedProtocols);4availableProtocols.addProtocol(protocol);5availableProtocols.addProtocol('myProtocol');6availableProtocols.removeProtocol(protocol);7availableProtocols.removeProtocol('myProtocol');8var protocols = availableProtocols.getAvailableProtocols();

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run ava automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful