Constructor to create a PageScript object for each request.
Client js code added will be rendered at last in the html.
@param req {Object} Request object
@constructor
557627
function PageScript(req) {
    var codeList = [], bottomScriptList = [], cacheKey;

    /**
     * Add plugin load code. Called for each configured plugin on page.
     * @param pluginOptions {Object} Plugin options object described in plugin properties
     */
    this.addPluginLoad = function (pluginOptions) {
        var pluginLoadJSCode = "Rocket.Plugin.onLoad(" + JSON.stringify(pluginOptions) + ")";
        codeList.push({modules: PLUGIN_MODULE, code: pluginLoadJSCode});
    };

    /**
     * Method adds the code & required modules
     * @param modules {String} Comma separated list of modules, will be passed to require.js
     * @param code {String} Client script Code
     */
    this.add = function (modules, code) {
        codeList.push({modules: modules, code: code});
    };

    /**
     * Method used to include the code block passed to "BottomScript" mixin
     * @param block {Function} jade mixin function
     * @param opts {Object} locals or opts passed to "BottomScript" mixin
     */
    this.addPageBottomCode = function (block, opts) {
        opts.jade = jadeRuntime;
        var func = new Function(_.keys(opts), "var jade_debug = [{filename: ''}]," +
            " buf = [], jade_indent = [], jade_interp;" +
            "(" + block + ")(); return buf.join('')");

        bottomScriptList.push(func.apply(null, _.values(opts)).replace(/<[\/]{0,1}(script|SCRIPT)[^><]*>/g, "").trim());
    };

    /**
     * Renders the scripts added or included in this object into html
     * @param cb {Function} callback function - arguments - err, html
     */
    this.render = function (cb) {
        //if cache is configured, get cache key
        if (ScriptsCache) {
            var page = req.attrs.page;
            cacheKey ||
            (cacheKey = utils.replaceAll(req.url.replace(/\/$/, ""), "/", "_")+ "__" + page.pageId + "__" + req.session.user.userId);
        }

        /**
         * Function renders html.
         * @param callback {Function} callback function - arguments - err, html
         */
        function renderHTML(callback) {
            async.map(codeList, function (locals, n) {
                locals.req = req;
                ViewHelper.render({
                    cache: true,
                    path: SCRIPT_JADE
                }, locals, n)
            }, function (err, buf) {
                if (!err) {
                    buf = buf || [];
                    buf.splice(0, 0, SCRIPT_START_TAG);
                    buf.push(bottomScriptList.join(""));
                    buf.push(SCRIPT_END_TAG);
                }
                callback(err, buf.join(""));
            });
        }

        if (ScriptsCache) {
            ScriptsCache.wrap(cacheKey, function (callback) {
                renderHTML(callback)
            }, cb);
        }
        else {
            renderHTML(cb);
        }

    }
}
431547
function PageRenderer(req, res) {
    var page = req.attrs.page;
    Object.defineProperties(this, {
        req: {
            value: req
        },
        res: {
            value: res
        },
        page: {
            value: _.clone(page)
        },
        themeDBAction: {
            value: DBActions.getInstance(req, THEME_SCHEMA)
        },
        layoutDBAction: {
            value: DBActions.getInstance(req, LAYOUT_SCHEMA)
        },
        pageInstanceDBAction: {
            value: DBActions.getAuthInstance(req, PAGE_SCHEMA, PAGE_PERMISSION_SCHEMA)
        },
        pluginInstanceDBAction: {
            value: DBActions.getInstance(req, PLUGIN_INSTANCE_SCHEMA)
        },
        pagePermissionValidator: {
            value: new PermissionValidator(req, PAGE_PERMISSION_SCHEMA, PAGE_SCHEMA)
        },
        pluginPermissionValidator: {
            value: new PermissionValidator(req, PLUGIN_PERMISSION_SCHEMA, PLUGIN_INSTANCE_SCHEMA)
        },
        isExclusive: {
            value: req.query && req.query.mode === "exclusive"
        }
    });
}
395913
function createPageHandler(page) {
        if (DEBUG && !page.phantom) inspectArgs("createPageHandler: ", page);

        phPage = page;
        var matches;

        if (option.viewportsize) {
            matches = option.viewportsize.match(/^(\d+)x(\d+)$/);
            if (matches !== null) {
                page.property("viewportSize", {width: matches[1], height: matches[2]});
            }
        }

        if (option.cliprect) {
            matches = option.cliprect.match(/^(\d+)x(\d+)x(\d+)x(\d+)$/);
            if (matches !== null) {
                page.setting("clipRect", {top: matches[1], left: matches[2],
                    width: matches[3], height: matches[4]});
            }
        }

        if (option["user-agent"]) {
            page.setting("userAgent", option["user-agent"]);
        }

        if (option.zoomfactor) {
            page.setting("zoomFactor", parseFloat(option.zoomfactor));
        }

        if (option.timeout) {
            timer = setTimeout(function () {
                var err = `capturejs: cannot access ${option.uri}: request timed out`;
                console.error(err);
                phInstance.exit();
                process.nextTick(function () { callback(err) });
            }, +option.timeout);
        }

        return page.open(option.uri);
    }
1052193
function createRequestWrapper(req) {
        var status,
            statusText,
            responseText;
        try {
            status = req.status;
            statusText = req.statusText;
            responseText = req.responseText;
        } catch (e) {
            status = 0;
            statusText = '';
            responseText = null;
        }
        return {
            status: status,
            statusText: statusText,
            responseText: responseText,
            rawRequest: req
        };
    }
1123042
function makeRequest () {
    request = self.request.apply(null, args);
    requestMiddleware.use(request);
    request.on("response", function (response) {
      var contentEncoding, gzipper;

      //Only cache successful responses
      if (response.statusCode >= 200 && response.statusCode < 300) {
        response.on('error', function (error) {
          self.handleError(error);
        });
        fs.writeFile(self.cacheDirectory + key + ".json", JSON.stringify(response.headers), function (error) {
          if (error) self.handleError(error);
        });

        responseWriter = fs.createWriteStream(self.cacheDirectory + key);

        responseWriter.on('error', function (error) {
          self.handleError(error);
        });

        contentEncoding = response.headers['content-encoding'] || '';
        contentEncoding = contentEncoding.trim().toLowerCase();

        if (contentEncoding === 'gzip') {
          response.on('error', function (error) {
            responseWriter.end();
          });
          response.pipe(responseWriter);
        } else {
          gzipper = zlib.createGzip();
          response.on('error', function (error) {
            gzipper.end();
          });
          gzipper.on('error', function (error) {
            self.handleError(error);
            responseWriter.end();
          });
          responseWriter.on('error', function (error) {
            response.unpipe(gzipper);
            gzipper.end();
          });
          response.pipe(gzipper).pipe(responseWriter);
        }
      }
    });
    self.emit("request", args[0]);
  }
530818
function( req, res ) {

	    /*
	     * Proxying every request as it is, except the specified by the user
	     * in the command line where we add our magic
	     */
	    proxy.proxyRequest(req, res, {

		host: inUrl.host,
		port: inUrl.port || 80,
		path: inUrl.path,
		handler: function( chunk ) {
		    /*
		     * Checking for <head> is a poor way of making sure the response body is a html document
		     * TODO: I'll add headers tests: Content-Type etc.
		     */
		    var html = chunk.toString();

		    /*
		     * TODO: This check shouldn't be done here but in node-http-proxy
		     */
		    if ( ! rhtml.test( html ) ) {

			return chunk;

		    }

		    return new Buffer(
			html.replace(
			    RegExp( '(<script[^>]*' + testFrameworkTarget + '[^>]*>[^<]*</script>)', 'im' ),
			    '$1' + emitterInjection
			)
		    );

		}

	    });

	}
153585
function jsonp(req) {
    var sUrl = req.url,
        inData = req.data,
        callback = req.callback;
    if (!sUrl || typeof sUrl != 'string') throw new Error('invalid URL');
    if (inData && (typeof inData === 'undefined' ? 'undefined' : _typeof(inData)) != 'object') throw new Error('invalid input argument (data)');
    if (typeof callback != 'function') throw new Error('input argument (callback) should be a function');

    var id = newJsonPid_();
    if (sUrl.indexOf('?') > 0) sUrl += '&';else sUrl += '?';
    sUrl += 'callback=TRIGGER__%5B' + id + '%5D'; // encodeURIComponent('[' + id + ']')

    if (inData) {
      Object.keys(inData).forEach(function (sKey) {
        var item = inData[sKey];
        sUrl += '&' + sKey + '=' + encodeURIComponent(item + '');
      });
    }

    var head = document.head || document.getElementsByTagName('head')[0] || document.documentElement;
    var script = document.createElement('script');
    script.async = 'async';
    if (req.scriptCharset) script.charset = req.scriptCharset;
    script.src = sUrl;
    script.onload = script.onreadystatechange = function () {
      if (!script.readyState || /loaded|complete/.test(script.readyState)) {
        script.onload = script.onreadystatechange = null; // handle memory leak in IE
        if (head && script.parentNode) // remove the script node
          head.removeChild(script);

        script = undefined; // dereference the script
        setTimeout(function () {
          var fn = window.TRIGGER__[id];
          if (fn) {
            delete window.TRIGGER__[id];
            if (req.notifyError) callback(null); // null means failed, fn not removed in TRIGGER__[id]() yet
          }
        }, 0);
      }
    };
    head.insertBefore(script, head.firstChild);

    window.TRIGGER__[id] = function (json) {
      var fn = window.TRIGGER__[id];
      if (fn) {
        delete window.TRIGGER__[id]; // unregist callback: TRIGGER__[xxx]
        callback(json);
      }
    };
  }
1263699
def create_request(self, method='', url='', query_params=None, body=None, headers=None):
        

        if query_params:
            query = urlencode(query_params)
            if query:
                url = url + ('&' if url.find('?') > 0 else '?') + query

        content_type = None
        accept = None

        if headers is None:
            headers = {}

        it = iterator(headers)

        for key, value in it:
            if key.lower().find('content-type') >= 0:
                content_type = value
            if key.lower().find('accept') >= 0:
                accept = value

        if content_type is None:
            content_type = 'application/json'
            headers['Content-Type'] = content_type

        if accept is None:
            accept = 'application/json'
            headers['Accept'] = accept

        if content_type.lower().find('application/json') >= 0:
            body = json.dumps(body) if body else None
        elif content_type.lower().find('application/x-www-form-urlencoded') >= 0:
            body = urlencode(body) if body else None

        return requests.Request(method, url, headers=headers, data=body)
1368206
function _makeRequest (request_query, cb) {
  https.get(request_query, function(res) {
      var data = [];
      res
      .on('data', function(chunk) { data.push(chunk); })
      .on('end', function() {
          var dataBuff = data.join('').trim();
          var result;
          try {
            result = JSON.parse(dataBuff);
          } catch (exp) {
            result = {'status_code': 500, 'status_text': 'JSON Parse Failed'};
          }
          cb(null, result);
      });
  })
  .on('error', function(e) {
      cb(e);
  });
}
70838
function createJSScript(id, src, cb) {
  var headElement = document.getElementsByTagName("head")[0];

  var scripter = document.createElement('script');
  scripter.setAttribute("type", 'text/javascript');
  scripter.setAttribute("id", id);
  if (src.indexOf('http') === 0 || src.indexOf('/') === 0) {
    scripter.onload = scripter.onreadystatechange = function () {
      if (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') {
        ImmitSax.data[id] = 'finish'
        setTimeout(function(){
          ImmitSax.roll(id)
          ImmitSax.off(id)
        }, 200);
      }
    }
    // if (src.lastIndexOf('.js')==-1) src += '.js'
    scripter.setAttribute("src", src);
    headElement.appendChild(scripter);
  }
  else {
    scripter.appendChild(document.createTextNode(src))
    headElement.appendChild(scripter);
    ImmitSax.data[id] = 'finish'
    ImmitSax.roll(id)
    ImmitSax.off(id)
  }
}
297128
function handleRequest(req, res) {
	var reqPath = _normalizeURL(req.url).substr(opts.root.length + 2)
	if (reqPath.match(/\.js$/)) {
		_handleModuleRequest(reqPath, res)
	} else {
		_handleMainModuleRequest(reqPath, req, res)
	}

	function _normalizeURL(url) {
		return url.replace(/\?.*/g, '').replace(/\/js$/, '.js')
	}
}
620109
function request (suppliedOptions,data,next) 
{
    var options = makeOptions(suppliedOptions);
    switch (options.method ? options.method.toUpperCase() : "BADMETHOD") {
        case "PUT":
        case "POST":
                    var dataString = JSON.stringify(data);
                    options.headers['Content-Length'] = dataString.length;
                    var req = https.request(options,requestDone);
                    req.end(dataString);
                    break;
        case "GET":
        case "DELETE":
                    var req = https.request(options,requestDone);
                    req.end();
                    break;
                    
        case "BADMETHOD":
        default:
                    var e = new Error('trakter: invalid method or not specified');
                    e.name = 'TrakterBadMethod';
                    e.code = 97;
                    next (e);
                    break;
    }

    function requestDone(res) {
        res.setEncoding('utf8');
        var responseString = '';
        res.on('error', function(err) {
            next (err,null);
        });
        res.on('data', function(data) {
            responseString += data;
        });
        res.on('end', function() {
            var err = checkError(options.method,res);
            if ( err !== null) {
                next (err);
            } else {
                next (null,JSON.parse(responseString));
            }
        });
    }
}
307845
function createPagination(req) {
  return function createPagination(pages, page, liClass, anchorClass) {
    var params = qs.parse(url.parse(req.url).query);
    var str = '';

    params.page = 1;
    var clas = (page == 1 && 'active') || '';

    for (var p = 1; p <= pages; p++) {
      params.page = p;
      clas = (page == p && 'active') || '';

      var href = '?' + qs.stringify(params);

      str += `<li class="${liClass} ${clas}"><a class="${anchorClass}" href="${href}">${p}</a></li>`;
    }

    return str;
  };
}
773029
function request( next ) {
	/* jshint validthis: true */
	var self = this,
		body = '',
		req;

	this.req.opts.agent = agent;

	// TODO: record request headers
	// TODO: record request header length
	// TODO: record request body length

	req = http.request( this.req.opts, onResponse );
	req.on( 'error', onError );

	this.start = Date.now();
	this.timer = process.hrtime();

	if ( this.req.body ) {
		req.write( this.req.body );
	}
	req.end();

	cache[ this.rid ] = req;

	/**
	* FUNCTION: onConnect( response, socket, head )
	*	Callback invoked upon connecting to a server.
	*
	* @private
	* @param {Object} response - HTTP response object
	* @param {Socket} socket - TCP socket
	* @param {Object} head - HTTP response head
	*/
	function onConnect( response, socket, head ) {
		// Do something...
	}

	/**
	* FUNCTION: onResponse( response )
	*	Callback invoked upon receiving an HTTP response.
	*
	* @private
	* @param {Object} response - HTTP response object
	*/
	function onResponse( res ) {
		self.res.status = res.statusCode;
		self.res.headers = res.headers;

		// TODO: record headers length

		res.on( 'data', onData );
		res.on( 'end', onEnd );
	}

	/**
	* FUNCTION: onError( error )
	*	Callback invoked if an error is encountered while making a request.
	*
	* @private
	* @param {Error} error - error object
	*/
	function onError( error ) {
		self.req.error = error;
		if ( process.connected ) {
			// TODO: log (or not; serialize in output message?)
			console.error( process.pid, 'request', error );
		}
	}

	/**
	* FUNCTION: onData( chunk )
	*	Callback invoked after receiving a chunk of response data.
	*
	* @private
	* @param {Buffer} chunk - response data
	*/
	function onData( chunk ) {
		self.res.bytes += chunk.length;
		body += chunk.toString();
	}

	/**
	* FUNCTION: onEnd()
	*	Callback invoked after a response ends.
	*
	* @private
	*/
	function onEnd() {
		self.elapsed = process.hrtime( self.timer );
		self.end = Date.now();
		self.res.body = body;
		delete cache[ self.rid ];
		delete self.req.opts[ 'agent' ];
		next();
	}
}
87942
function(request, options){
                if(typeof options == "undefined") options = {}; // define options if not yet defined
                options.relative_path_root = relative_path_root; // overwrite user defined rel path root - TODO - make this a private property
                return require_function(request, options);
            }
888733
function onRequest(request, response) {
  var filename = path.join(__dirname, request.url);

  // Serving server.js from cache. Useful for microbenchmarks.
  if (request.url === cachedUrl) {
    if (response.push) {
      // Also push down the client js, since it's possible if the requester wants
      // one, they want both.
      var push = response.push('/client.js');
      push.writeHead(200);
      fs.createReadStream(path.join(__dirname, '/client.js')).pipe(push);
    }
    response.end(cachedFile);
  }

  // Reading file from disk if it exists and is safe.
  else if ((filename.indexOf(__dirname) === 0) && fs.existsSync(filename) && fs.statSync(filename).isFile()) {
    response.writeHead(200);
    var fileStream = fs.createReadStream(filename);
    fileStream.pipe(response);
    fileStream.on('finish',response.end);
  }

  // Example for testing large (boundary-sized) frames.
  else if (request.url === "/largeframe") {
    response.writeHead(200);
    var body = 'a';
    for (var i = 0; i < 14; i++) {
      body += body;
    }
    body = body + 'a';
    response.end(body);
  }

  // Otherwise responding with 404.
  else {
    response.writeHead(404);
    response.end();
  }
}
1148356
function (obj) {
                if (!resourceChecked) {
                    Util.saveLoadedRes();
                    resourceChecked = true;
                }
                currReqID = obj.reqID;
                // console.log('arrive', obj.id);
                this.trigger('pageletarrive', obj);
                var pagelet = new PageLet(obj, function () {
                    // console.log('dom ready', obj.id);
                    var item;
                    count--;
                    // enforce js executed after dom inserted.
                    if (count === 0) {
                        while ((item = pagelets.shift())) {
                            BigPipe.trigger('pageletinsert', pagelet, item.pageletData);
                            // console.log('pagelet exec js', item.pageletData.id);
                            item.loadJs((function (item) {
                                // console.log('pagelet exec done', item.pageletData.id);
                                BigPipe.trigger('pageletdone', pagelet, item.pageletData);
                            })(item));
                        }
                    }
                });
                pagelet.pageletData = obj;
                pagelets.push(pagelet);
                count++;
                pagelet.loadCss();
            }