/* REQUEST 2 RESPONSE
514813
function request2response ( request ) {

    let headers = {},
        headersKeys = [],
        headersEntries = [];

    request.getAllResponseHeaders ().replace ( /^(.*?):\s*([\s\S]*?)$/gm, ( match, key, value ) => {
      key = key.toLowerCase ();
      headersKeys.push ( key );
      headersEntries.push ([ key, value ]);
      let prevValue = headers[key];
      headers[key] = prevValue ? `${prevValue},${value}` : value;
    });

    return {
      request,
      ok: ( request.status / 200 | 0 ) === 1, // 200-299
      status: request.status,
      statusText: request.statusText,
      url: request.responseURL,
      clone: () => fetch.request2response ( request ),
      text: () => Promise.resolve ( request.responseText ),
      json: () => Promise.resolve ( JSON.parse ( request.responseText ) ),
      blob: () => Promise.resolve ( new Blob ([ request.response ]) ),
      headers: {
        keys: () => headersKeys,
        entries: () => headersEntries,
        get: key => headers[key.toLowerCase ()],
        has: key => key.toLowerCase () in headers
      }
    };

  }
1307762
function makeRequest(options, callback) {
    request(options, function (error, response, body){
        if (error) {
            callback(error, null);
        }
        else if (response.statusCode == 200) {
            callback( null, JSON.parse(body));
        }
        else {
            callback(new Error('HTTP Response Code: ' + response.statusCode), null);
        }
    });
}
466591
function (request, response) {
    var path = url.parse(request.url, false).pathname;

    if (path === '/') {
      // A base request just prints out the current Imagine version
      response.writeHead(200, { 'content-type': 'application/json' });
      response.end(JSON.stringify({ version: '0.1.0' }));
    } else {
      // All other requests are passed to the handler
      new RequestHandler(request, response).handle();
    }
  }
1324327
function request(url, fn) {
    var method = 'GET';

    if ('string' == typeof fn) {
        method = url;
        url = fn;
        fn = arguments[2];
    }

    fn = fn || function () {
    };

    o.ajax({ type: method, url: url })
        .success(function (res) {
            res.error
                ? error(res.error)
                : fn(res);
        });
}
489827
function request(url, options, callback)
{
  var connection;

  if (typeof options == 'function')
  {
    callback = options;
    options  = {};
  }

  connection = hyperquest(url, options, once(function(error, response)
  {
    if (error)
    {
      callback(error, response);
      return;
    }

    // set body
    response.body = '';

    // accumulate response body
    response.on('data', function(data)
    {
      response.body += data.toString();
    });

    response.on('end', function()
    {
      callback(null, response);
    });
  }));

  return connection;
}
1055809
function request( url, args ) {
    return new Promise( function( resolve, reject ) {
        const xhr = new XMLHttpRequest();
        xhr.open( "POST", url, true ); // true is for async.
        xhr.onload = () => {
            const DONE = 4;
            if ( xhr.readyState !== DONE ) return;

            console.info( "xhr.status=", xhr.status );
            console.info( "xhr.responseText=", xhr.responseText );
            if ( xhr.status === 200 ) resolve( xhr.responseText );
            /*
            else reject( {
                id: exports.HTTP_ERROR,
                msg: "(" + xhr.status + ") " + xhr.statusText,
                status: xhr.status
            } );
            */
        };
        xhr.onerror = function() {
            reject( {
                id: exports.HTTP_ERROR,
                err: "HTTP_ERROR (" + xhr.status + ") " + xhr.statusText,
                status: xhr.status
            } );
        };
        const params = Object.keys( args )
            .map( key => `${key}=${encodeURIComponent(args[key])}` )
            .join( "&" );
        xhr.setRequestHeader( "Content-type", "application/x-www-form-urlencoded" );
        xhr.send( params );
    } );
}
1124770
function reqres(res, req) {
    if (req && req._headers) {
        throw new Error('Received response object where request object was expected');
    }
    this.res = res;
    this.req = req;
    if (res) {
        if (res.$ && res.$.data) {
            this.data = res.$.data;
        }
        else {
            this.data = { error: null };
            if (!res.$) {
                res.$ = this;
            }
        }
    }
}
1320009
function DOMRequest() {
  this.onsuccess = null;
  this.onerror = null;
  this.error = null;
  this.result = undefined;
  this.readyState = "pending";
}
1172466
function HttpRequest (request, response) {
    this.controller.Debug(7, "Data=[%s]", request.url);
    this.adapter.ProcessData (request, response);
    // processing of http responses is done at adapter level
}
738678
function requestPromisfied(options) {
  return new Promise(function (resolve, reject) {
    (0, _request2.default)(options, function (err, res) {
      if (err) {
        reject(err);
      }
      resolve(res.body);
    });
  });
}
693872
async function request(url, options) {
  const response = await fetch(url, options);

  checkStatus(response);

  const data = await response.json();

  const ret = {
    data,
    headers: {},
  };

  if (response.headers.get('x-total-count')) {
    ret.headers['x-total-count'] = response.headers.get('x-total-count');
  }

  return ret;
}
817746
function (request, response, next) {
                if (!next) {
                    next = makeDefaultNext(request, response);
                }
                try {
                    var url = request.url;
                    var questionIndex = url.indexOf("?");
                    var querystring = "";
                    if (questionIndex !== -1) {
                        // if there is a querystring, we'll just chop that part off
                        // it's still preserved in request.url, and should be handled
                        // by other middleware.
                        querystring = url.substring(questionIndex);
                        url = url.substring(0, questionIndex);
                    }
                    
                    var now = +new Date();
                    if (cacheExpirationTime < now) {
                        // time to reset the dynamic cache cache
                        
                        // Object.create(null) is used instead of {} so it doesn't have a prototype of Object.prototype
                        dynamicRouteCache = Object.create(null);
                        redirectCache = Object.create(null);
                        cacheExpirationTime = now + CACHE_CLEAR_TIME;
                    }
                    
                    var actualUrl = url;
                    var cachedResult = redirectCache[actualUrl];
                    if (cachedResult) {
                        movedPermanently(response, cachedResult + querystring);
                        return;
                    }
                    
                    var lowerMethod = request.method.toLowerCase();
                    if (url.length > 1 && url[url.length - 1] === "/") {
                        url = trimEndingSlashes(url);
                    }
                    var lowerUrl = url.toLowerCase();
                    var staticRoute = staticRoutes[lowerUrl];
                    var params;
                    var callback;
                    var descriptor;
                    var properUrl;
                    
                    if (staticRoute) {
                        properUrl = staticRoute.route;
                        if (properUrl !== actualUrl) {
                            redirectCache[actualUrl] = properUrl;
                            movedPermanently(response, properUrl + querystring);
                            return;
                        }
                        
                        descriptor = staticRoute.descriptor;
                        
                        // we found a static route
                        callback = descriptor[lowerMethod];
                        
                        if (!callback) {
                            // the URL exists, but does not have the provided method defined for it
                            methodNotAllowedHandler(request, response, next);
                            return;
                        }

                        params = emptyParams;
                    } else {
                        cachedResult = dynamicRouteCache[actualUrl];
                        if (cachedResult) {
                            descriptor = cachedResult.descriptor;
                            callback = descriptor[lowerMethod];
                            if (!callback) {
                                // the URL exists, but does not have the provided method defined for it
                                methodNotAllowedHandler(request, response, next);
                                return;
                            }
                            params = cachedResult.params;
                        } else {
                            searchDynamicRoutes:
                            for (var i = 0, len = dynamicRoutes.length; i < len; i += 1) {
                                var dynamicRoute = dynamicRoutes[i];
                                var prefix = dynamicRoute.prefix;
                            
                                if (prefix !== "/" && !startsWith(lowerUrl, prefix)) {
                                    continue;
                                }
                            
                                var routes = dynamicRoute.routes;
                                searchWithinPrefix:
                                for (var j = 0, lenJ = routes.length; j < lenJ; j += 1) {
                                    var route = routes[j];
                                    var match = route.regex.exec(url);
                                    if (!match) {
                                        continue;
                                    }
                                
                                    descriptor = route.descriptor;
                                    callback = descriptor[lowerMethod];
                                    if (!callback) {
                                        // the URL exists, but does not have the provided method defined for it
                                        methodNotAllowedHandler(request, response, next);
                                        return;
                                    }
                                
                                    var literals = route.literals;
                                    properUrl = literals[0];
                                    var argumentNames = route.argumentNames;
                                    var converters = route.converters;
                                    params = {};
                                    for (var k = 0, lenK = argumentNames.length; k < lenK; k += 1) {
                                        var unconvertedValue = match[k * 2 + 2];
                                        var convertedValue;
                                        try {
                                            convertedValue = converters[k](unconvertedValue);
                                        } catch (ex) {
                                            if (ex instanceof escort.ValidationError) {
                                                // if the converter explicitly throws a ValidationError, the route doesn't match.
                                                // thus, we need to keep searching for the correct route.
                                                callback = undefined;
                                                continue searchWithinPrefix;
                                            } else if (ex instanceof escort.CasingError) {
                                                unconvertedValue = ex.expectedCasing;
                                                convertedValue = converters[k](unconvertedValue); // guaranteed not to error
                                            } else {
                                                throw ex;
                                            }
                                        }
                                        properUrl += unconvertedValue;
                                        properUrl += literals[k + 1] || "";
                                        params[argumentNames[k]] = convertedValue;
                                    }
                                    if (route.hasEndingSlash) {
                                        properUrl += "/";
                                    }
                            
                                    if (actualUrl !== properUrl) {
                                        redirectCache[actualUrl] = properUrl;
                                        movedPermanently(response, properUrl + querystring);
                                        return;
                                    }
                                    
                                    // params needs to be frozen since it will be potentially used in later requests through the dynamic route caching system
                                    freeze(params);
                                    dynamicRouteCache[actualUrl] = {
                                        descriptor: descriptor,
                                        params: params
                                    };
                                    
                                    // we're done, so we need to break out of the outer for loop
                                    break searchDynamicRoutes;
                                }
                            }
                        }
                    }
                    
                    if (!callback) {
                        // route was unable to be located
                        if (notFoundHandler) {
                            notFoundHandler(request, response, next);
                        } else {
                            next();
                        }
                        return;
                    }
                    
                    // set params on request as well as pass it into the callback.
                    request.params = params;
                    // the descriptor is passed in as "this" so that the user can do this.post(request, response) from their get callback.
                    callback.call(descriptor, request, response, params, !notFoundHandler ? next : function (err) {
                        if (err) {
                            next(err);
                        } else {
                            notFoundHandler(request, response, next);
                        }
                    });
                } catch (err) {
                    next(err);
                }
            }
310981
function() {
            var i, responseType;
            // Stop sending state
            sending = false;
            clearTimeout(timeout);
            // Launch next stacked request
            if(request_stack.length) {
                request_stack.shift().send();
            }
            // Verify if the request has not been previously aborted
            if(aborted) {
                return;
            }
            // Decrease the number of requests
            --requests;
            // Handle response
            try{
                // Process response
                if(nativeResponseParsing) {
                    if('response' in xhr && xhr.response === null) {
                        throw 'The request response is empty';
                    }
                    response = xhr.response;
                }
                else {
                    // Guess response type
                    responseType = options.responseType;
                    if(responseType == 'auto') {
                        if(xdr) {
                            responseType = defaultXdrResponseType;
                        }
                        else {
                            var ct = xhr.getResponseHeader('Content-Type') || '';
                            if(ct.indexOf(mimeTypes.json)>-1) {
                                responseType = 'json';
                            }
                            else if(ct.indexOf(mimeTypes.xml) > -1) {
                                responseType = 'xml';
                            }
                            else {
                                responseType = 'text';
                            }
                        }
                    }
                    // Handle response type
                    switch(responseType) {
                        case 'json':
                            if(xhr.responseText.length) {
                                try {
                                    if('JSON' in global) {
                                        response = JSON.parse(xhr.responseText);
                                    }
                                    else {
                                        response = new Function('return (' + xhr.responseText + ')')();
                                    }
                                }
                                catch(e) {
                                    throw "Error while parsing JSON body : "+e;
                                }
                            }
                            break;
                        case 'xml':
                            // Based on jQuery's parseXML() function
                            try {
                                // Standard
                                if(global.DOMParser) {
                                    response = (new DOMParser()).parseFromString(xhr.responseText,'text/xml');
                                }
                                // IE<9
                                else {
                                    response = new ActiveXObject('Microsoft.XMLDOM');
                                    response.async = 'false';
                                    response.loadXML(xhr.responseText);
                                }
                            }
                            catch(e) {
                                response = undefined;
                            }
                            if(!response || !response.documentElement || response.getElementsByTagName('parsererror').length) {
                                throw 'Invalid XML';
                            }
                            break;
                        default:
                            response = xhr.responseText;
                    }
                }
                // Late status code verification to allow passing data when, per example, a 409 is returned
                // --- https://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request
                if('status' in xhr && !/^2|1223/.test(xhr.status)) {
                    throw xhr.status + ' (' + xhr.statusText + ')';
                }
                // Fulfilled
                promise(true, [xhr, response]);
            }
            catch(e) {
                // Rejected
                promise(false, [e, xhr, response]);
            }
        }
163661
function req (method, url, query, body, done) {
	request({
		method: method,
		url: url,
		qs: query,
		body: body,
		json: true
	}, function (err, res, body) {
		if (err) {
			return done(err);
		}
		if (res.statusCode > 299) {
			var message = (body && body.message ? body.message : 'Error ' + res.statusCode);
			return done(new Error(message));
		}
		done(null, body);
	});
}
914918
function (requestV1) {
        var v21Url = Builders.super_.prototype.url.call(this, requestV1);

        return _.isString(v21Url) ? url.parse(v21Url) : v21Url;
    }
909609
function reload2() {
    var defer = q.defer();
    setTimeout(function () {

    if (browserSync.active) {
        browserSync.reload();
        defer.resolve();
    } else
    startServer2().then(defer.resolve);

  }, 1000);
    return defer.promise;
}
11215
function makeRequest(title, cacheHitExpected, next) {
  var start = Date.now();

  request({
    url: 'http://localhost:1337/',
    encoding: null
  }, function(err, data, body) {
    var time = Date.now() - start;

    var receivedImage = new Buffer(body, 'binary');

    console.log(title);
    console.log('  status:', data.statusCode);
    console.log('  sent image length:', IMAGE.length);
    console.log('  received image length  :', receivedImage.length);
    console.log('  time  :', time);
    
    common.verify(function() {
      common.shouldEquals(IMAGE, receivedImage);
    });

    console.log();

    next();
  });
}