<commit_before>'use strict';

var React = require('react');

function visualiseRender (component) {
    component.prototype.UPDATE_RENDER_LOG_POSITION_TIMEOUT_MS = 500;
    component.prototype.MAX_LOG_LENGTH = 20;
    component.prototype.STATE_CHANGES = {
        MOUNT: 'mount',
        UPDATE: 'update'
    };
    component.prototype.styling = {
        renderLog: {
            color: 'rgb(85, 85, 85)',
            fontFamily: '\'Helvetica Neue\', Arial, Helvetica, sans-serif',
            fontSize: '14px',
            lineHeight: '18px',
            background: 'linear-gradient(#fff, #ccc)',
            boxShadow: '0 2px 12px rgba(0,0,0,0.5)',
            textShadow: '0 1px 0 #fff',
            borderRadius: '7px',
            position: 'absolute',
            maxWidth: '70%',
            padding: '5px 10px',
            zIndex: '10000'
        },
        renderLogDetailNotes: {
            color: 'red',
            textAlign: 'center'
        },
        elementHighlightMonitor: {
            outline: '1px solid rgba(47, 150, 180, 1)'
        },
        elementHighlightMount: {
            outline: '3px solid rgba(197, 16, 12, 1)'
        },
        elementHighlightUpdate: {
            outline: '3px solid rgba(197, 203, 1, 1)'
        }
    };

    component.prototype.componentDidMount = function(){
        // Reset the logs
        this._resetRenderLog();

        // Record initial mount
        this.addToRenderLog(this.state, 'Initial Render');

        // Build the monitor node
        this._buildRenderLogNode();

        // Highlight the initial mount
        this._highlightChange(this.STATE_CHANGES.MOUNT);

        // Set the watch to update log position
        this._updateRenderLogPositionTimeout = setInterval(
            this._updateRenderLogPosition.bind(this), this.UPDATE_RENDER_LOG_POSITION_TIMEOUT_MS
        );
    };

    component.prototype.componentDidUpdate = function(prevProps, prevState){
        // Get the changes in state and props
        this._getReasonForReRender(prevProps, prevState);

        // Update the render log
        this._updateRenderLogNode();

        // Highlight the update
        this._highlightChange(this.STATE_CHANGES.UPDATE);
    };

    component.prototype.componentWillUnmount = function (){
        // Remove the monitor node
        this._removeRenderLogNode();

        // Clear the update position timeout
        clearInterval(this._updateRenderLogPositionTimeout);
    };

    /*
    * Reset the logs
    * @return void
    */
    component.prototype._resetRenderLog = function(){
        this.state.renderLog = [];
        this.state.renderCount = 1;
    };

    component.prototype._applyCSSStyling = function (node, styles) {
        Object.keys(styles).forEach(function(className) {
          node.style[className] = styles[className];
        });
    };

    /*
    * Build the renderLog node, add it to the body and assign it's position
    * based on the monitored component
    * @return void
    */
    component.prototype._buildRenderLogNode = function(){
        var renderLogContainer = document.createElement('div'),
            renderLogRenderCountNode = document.createElement("div"),
            renderLogDetailContainer = document.createElement("div"),
            renderLogNotesNode = document.createElement("div"),
            renderLogDetailNode = document.createElement("div");

        renderLogContainer.className = 'renderLog';

        // Apply styling
        this._applyCSSStyling(renderLogContainer, this.styling.renderLog)

        // Attach the click handler for toggling the detail log
        renderLogContainer.addEventListener('click', function(){

            // Show the detail Log
            if (renderLogRenderCountNode.style.display === 'none') {
                renderLogRenderCountNode.style.display = 'block';
                renderLogDetailContainer.style.display = 'none';
                renderLogContainer.style.zIndex = '10000';
            // Hide it
            } else {
                renderLogRenderCountNode.style.display = 'none';
                renderLogDetailContainer.style.display = 'block';
                renderLogContainer.style.zIndex = '10001';
            }
        });

        renderLogRenderCountNode.className = 'renderLogCounter';
        renderLogRenderCountNode.innerText = 1;

        renderLogDetailContainer.style.display = 'none';
        renderLogDetailNode.innerText = '';

        if (this.shouldComponentUpdate) {
            renderLogNotesNode.innerText = 'NOTE: This component uses a custom shouldComponentUpdate(), so the results above are purely informational';
        }

        this._applyCSSStyling(renderLogNotesNode, this.styling.renderLogDetailNotes);

        renderLogDetailContainer.appendChild(renderLogDetailNode);
        renderLogDetailContainer.appendChild(renderLogNotesNode);

        renderLogContainer.appendChild(renderLogRenderCountNode);
        renderLogContainer.appendChild(renderLogDetailContainer);

        this.renderLogContainer = renderLogContainer;
        this.renderLogDetail = renderLogDetailNode;
        this.renderLogNotes = renderLogNotesNode;
        this.renderLogRenderCount = renderLogRenderCountNode;

        // Append to the body
        document.getElementsByTagName('body')[0].appendChild(renderLogContainer);

        // Set initial position
        this._updateRenderLogPosition();

        //
        this._updateRenderLogNode();
    };

    /*
    * Update the render log position based on its parent position
    * @return void
    */
    component.prototype._updateRenderLogPosition = function(){
        var parentNode = React.findDOMNode(this),
          parentNodeRect = parentNode && parentNode.getBoundingClientRect();

        if (this.renderLogContainer && parentNodeRect) {
            this.renderLogContainer.style.top = (window.pageYOffset + parentNodeRect.top) + 'px';
            this.renderLogContainer.style.left = (parentNodeRect.left) + 'px';
        }
    };

    /*
    * Update the render log count and details
    * @return void
    */
    component.prototype._updateRenderLogNode = function() {
        var logFragment = document.createDocumentFragment();

        if (this.renderLogRenderCount) {
            this.renderLogRenderCount.innerText = (this.state.renderCount - 1 );
        }

        if (this.renderLogDetail) {
            this.renderLogDetail.innerHTML = '';
            for (var i = 0; i < this.state.renderLog.length; i++){
                var item = document.createElement('div');
                item.innerText = this.state.renderLog[i];
                logFragment.appendChild(item);
            }

            this.renderLogDetail.appendChild(logFragment);
        }
        //this.state.renderCount++;
    };

    /*
    * Remove the render log node from the body
    * @return void
    */
    component.prototype._removeRenderLogNode = function() {
        if (this.renderLogContainer) {
            document.getElementsByTagName('body')[0].removeChild(this.renderLogContainer);
        }
    };

    /*
    * Add a detail message to the render log and update the count
    * @param object nextState - The most current state of the component
    * @param String message
    * @return void
    */
    component.prototype.addToRenderLog = function(state, message) {
        state.renderLog.unshift(state.renderCount + ') ' + message);
        state.renderCount++;

        // Trim the log
        state.renderLog.splice(this.MAX_LOG_LENGTH, 1);
    };

    /*
     * Get the changes made to props or state.  In the event this component has its own
     * shouldComponentUpdate, don't do
     * anything
     * @param object prevProps
     * @param object prevState
     * @return boolean
     */
    component.prototype._getReasonForReRender = function(prevProps, prevState) {
        var nextState = this.state,
            nextProps = this.props,
            key;

        for (key in nextState){
            if (nextState.hasOwnProperty(key) && nextState[key] !== prevState[key]){
                if (typeof nextState[key] === 'object') {
                    return this.addToRenderLog(this.state, 'this.state['+key+'] changed');
                } else {
                    return this.addToRenderLog(this.state,
                        'this.state['+key+'] changed: \'' + prevState[key] + '\' => \'' + nextState[key] + '\'');
                }

            }
        }

        for (key in nextProps) {
            if (nextProps.hasOwnProperty(key) && nextProps[key] !== prevProps[key]) {
                if (typeof nextProps[key] === 'object') {
                    return this.addToRenderLog(this.state, 'this.props['+key+'] changed');
                } else {
                    return this.addToRenderLog(this.state,
                        'this.props['+key+'] changed: \'' + prevProps[key] + '\' => \'' + nextProps[key] + '\'');
                }
            }
        }

        return this.addToRenderLog(this.state, 'unknown reason for update, possibly from forceUpdate()');
    };

    /*
     * Highlight any change by adding an animation style to the component DOM node
     * @param String change - The type of change being made to the node
     * @return void
     */
    component.prototype._highlightChange = function(change) {
        var parentNode = React.findDOMNode(this),
            ANIMATION_DURATION = 500;

        if (parentNode) {
            parentNode.style.boxSizing = 'border-box';

            window.requestAnimationFrame(function () {
                // Immediately show the border
                parentNode.style.transition = 'outline 0s';
                if (change === this.STATE_CHANGES.MOUNT) {
                    parentNode.style.outline = this.styling.elementHighlightMount.outline;
                } else {
                    parentNode.style.outline = this.styling.elementHighlightUpdate.outline;
                }

                // Animate the border back to monitored color
                window.requestAnimationFrame(function () {
                    parentNode.style.outline = this.styling.elementHighlightMonitor.outline;
                    parentNode.style.transition = 'outline '+ANIMATION_DURATION+'ms linear';
                }.bind(this));
            }.bind(this));
        }
    };

    component.renderLogContainer = null;
    component.renderLogDetail = null;
    component.renderLogRenderCount = null;
    component._updateRenderLogPositionTimeout = null;
}

module.exports = visualiseRender;
<commit_msg>Fixed stateless component bug (unresolved in source project - https://github.com/redsunsoft/react-render-visualizer/pull/3)<commit_after>'use strict';

var React = require('react');

function visualiseRender (component) {
    component.prototype.UPDATE_RENDER_LOG_POSITION_TIMEOUT_MS = 500;
    component.prototype.MAX_LOG_LENGTH = 20;
    component.prototype.STATE_CHANGES = {
        MOUNT: 'mount',
        UPDATE: 'update'
    };
    component.prototype.styling = {
        renderLog: {
            color: 'rgb(85, 85, 85)',
            fontFamily: '\'Helvetica Neue\', Arial, Helvetica, sans-serif',
            fontSize: '14px',
            lineHeight: '18px',
            background: 'linear-gradient(#fff, #ccc)',
            boxShadow: '0 2px 12px rgba(0,0,0,0.5)',
            textShadow: '0 1px 0 #fff',
            borderRadius: '7px',
            position: 'absolute',
            maxWidth: '70%',
            padding: '5px 10px',
            zIndex: '10000'
        },
        renderLogDetailNotes: {
            color: 'red',
            textAlign: 'center'
        },
        elementHighlightMonitor: {
            outline: '1px solid rgba(47, 150, 180, 1)'
        },
        elementHighlightMount: {
            outline: '3px solid rgba(197, 16, 12, 1)'
        },
        elementHighlightUpdate: {
            outline: '3px solid rgba(197, 203, 1, 1)'
        }
    };

    component.prototype.componentDidMount = function(){
        // Create empty state object if not defined
        if (!this.state) {
            this.state = {};
        }

        // Reset the logs
        this._resetRenderLog();

        // Record initial mount
        this.addToRenderLog(this.state, 'Initial Render');

        // Build the monitor node
        this._buildRenderLogNode();

        // Highlight the initial mount
        this._highlightChange(this.STATE_CHANGES.MOUNT);

        // Set the watch to update log position
        this._updateRenderLogPositionTimeout = setInterval(
            this._updateRenderLogPosition.bind(this), this.UPDATE_RENDER_LOG_POSITION_TIMEOUT_MS
        );
    };

    component.prototype.componentDidUpdate = function(prevProps, prevState){
        // Get the changes in state and props
        this._getReasonForReRender(prevProps, prevState);

        // Update the render log
        this._updateRenderLogNode();

        // Highlight the update
        this._highlightChange(this.STATE_CHANGES.UPDATE);
    };

    component.prototype.componentWillUnmount = function (){
        // Remove the monitor node
        this._removeRenderLogNode();

        // Clear the update position timeout
        clearInterval(this._updateRenderLogPositionTimeout);
    };

    /*
    * Reset the logs
    * @return void
    */
    component.prototype._resetRenderLog = function(){
        this.state.renderLog = [];
        this.state.renderCount = 1;
    };

    component.prototype._applyCSSStyling = function (node, styles) {
        Object.keys(styles).forEach(function(className) {
          node.style[className] = styles[className];
        });
    };

    /*
    * Build the renderLog node, add it to the body and assign it's position
    * based on the monitored component
    * @return void
    */
    component.prototype._buildRenderLogNode = function(){
        var renderLogContainer = document.createElement('div'),
            renderLogRenderCountNode = document.createElement("div"),
            renderLogDetailContainer = document.createElement("div"),
            renderLogNotesNode = document.createElement("div"),
            renderLogDetailNode = document.createElement("div");

        renderLogContainer.className = 'renderLog';

        // Apply styling
        this._applyCSSStyling(renderLogContainer, this.styling.renderLog)

        // Attach the click handler for toggling the detail log
        renderLogContainer.addEventListener('click', function(){

            // Show the detail Log
            if (renderLogRenderCountNode.style.display === 'none') {
                renderLogRenderCountNode.style.display = 'block';
                renderLogDetailContainer.style.display = 'none';
                renderLogContainer.style.zIndex = '10000';
            // Hide it
            } else {
                renderLogRenderCountNode.style.display = 'none';
                renderLogDetailContainer.style.display = 'block';
                renderLogContainer.style.zIndex = '10001';
            }
        });

        renderLogRenderCountNode.className = 'renderLogCounter';
        renderLogRenderCountNode.innerText = 1;

        renderLogDetailContainer.style.display = 'none';
        renderLogDetailNode.innerText = '';

        if (this.shouldComponentUpdate) {
            renderLogNotesNode.innerText = 'NOTE: This component uses a custom shouldComponentUpdate(), so the results above are purely informational';
        }

        this._applyCSSStyling(renderLogNotesNode, this.styling.renderLogDetailNotes);

        renderLogDetailContainer.appendChild(renderLogDetailNode);
        renderLogDetailContainer.appendChild(renderLogNotesNode);

        renderLogContainer.appendChild(renderLogRenderCountNode);
        renderLogContainer.appendChild(renderLogDetailContainer);

        this.renderLogContainer = renderLogContainer;
        this.renderLogDetail = renderLogDetailNode;
        this.renderLogNotes = renderLogNotesNode;
        this.renderLogRenderCount = renderLogRenderCountNode;

        // Append to the body
        document.getElementsByTagName('body')[0].appendChild(renderLogContainer);

        // Set initial position
        this._updateRenderLogPosition();

        //
        this._updateRenderLogNode();
    };

    /*
    * Update the render log position based on its parent position
    * @return void
    */
    component.prototype._updateRenderLogPosition = function(){
        var parentNode = React.findDOMNode(this),
          parentNodeRect = parentNode && parentNode.getBoundingClientRect();

        if (this.renderLogContainer && parentNodeRect) {
            this.renderLogContainer.style.top = (window.pageYOffset + parentNodeRect.top) + 'px';
            this.renderLogContainer.style.left = (parentNodeRect.left) + 'px';
        }
    };

    /*
    * Update the render log count and details
    * @return void
    */
    component.prototype._updateRenderLogNode = function() {
        var logFragment = document.createDocumentFragment();

        if (this.renderLogRenderCount) {
            this.renderLogRenderCount.innerText = (this.state.renderCount - 1 );
        }

        if (this.renderLogDetail) {
            this.renderLogDetail.innerHTML = '';
            for (var i = 0; i < this.state.renderLog.length; i++){
                var item = document.createElement('div');
                item.innerText = this.state.renderLog[i];
                logFragment.appendChild(item);
            }

            this.renderLogDetail.appendChild(logFragment);
        }
        //this.state.renderCount++;
    };

    /*
    * Remove the render log node from the body
    * @return void
    */
    component.prototype._removeRenderLogNode = function() {
        if (this.renderLogContainer) {
            document.getElementsByTagName('body')[0].removeChild(this.renderLogContainer);
        }
    };

    /*
    * Add a detail message to the render log and update the count
    * @param object nextState - The most current state of the component
    * @param String message
    * @return void
    */
    component.prototype.addToRenderLog = function(state, message) {
        state.renderLog.unshift(state.renderCount + ') ' + message);
        state.renderCount++;

        // Trim the log
        state.renderLog.splice(this.MAX_LOG_LENGTH, 1);
    };

    /*
     * Get the changes made to props or state.  In the event this component has its own
     * shouldComponentUpdate, don't do
     * anything
     * @param object prevProps
     * @param object prevState
     * @return boolean
     */
    component.prototype._getReasonForReRender = function(prevProps, prevState) {
        var nextState = this.state,
            nextProps = this.props,
            key;

        for (key in nextState){
            if (nextState.hasOwnProperty(key) && nextState[key] !== prevState[key]){
                if (typeof nextState[key] === 'object') {
                    return this.addToRenderLog(this.state, 'this.state['+key+'] changed');
                } else {
                    return this.addToRenderLog(this.state,
                        'this.state['+key+'] changed: \'' + prevState[key] + '\' => \'' + nextState[key] + '\'');
                }

            }
        }

        for (key in nextProps) {
            if (nextProps.hasOwnProperty(key) && nextProps[key] !== prevProps[key]) {
                if (typeof nextProps[key] === 'object') {
                    return this.addToRenderLog(this.state, 'this.props['+key+'] changed');
                } else {
                    return this.addToRenderLog(this.state,
                        'this.props['+key+'] changed: \'' + prevProps[key] + '\' => \'' + nextProps[key] + '\'');
                }
            }
        }

        return this.addToRenderLog(this.state, 'unknown reason for update, possibly from forceUpdate()');
    };

    /*
     * Highlight any change by adding an animation style to the component DOM node
     * @param String change - The type of change being made to the node
     * @return void
     */
    component.prototype._highlightChange = function(change) {
        var parentNode = React.findDOMNode(this),
            ANIMATION_DURATION = 500;

        if (parentNode) {
            parentNode.style.boxSizing = 'border-box';

            window.requestAnimationFrame(function () {
                // Immediately show the border
                parentNode.style.transition = 'outline 0s';
                if (change === this.STATE_CHANGES.MOUNT) {
                    parentNode.style.outline = this.styling.elementHighlightMount.outline;
                } else {
                    parentNode.style.outline = this.styling.elementHighlightUpdate.outline;
                }

                // Animate the border back to monitored color
                window.requestAnimationFrame(function () {
                    parentNode.style.outline = this.styling.elementHighlightMonitor.outline;
                    parentNode.style.transition = 'outline '+ANIMATION_DURATION+'ms linear';
                }.bind(this));
            }.bind(this));
        }
    };

    component.renderLogContainer = null;
    component.renderLogDetail = null;
    component.renderLogRenderCount = null;
    component._updateRenderLogPositionTimeout = null;
}

module.exports = visualiseRender;
<|endoftext|>


<commit_before>var http = require("http");

http.createServer(function (request, response) {
   // Send the HTTP header
   // HTTP Status: 200 : OK
   // Content Type: text/plain
   response.writeHead(200, {'Content-Type': 'text/plain'});

   // Send the response body as "Hello World"
   response.end('Hello World\n');
}).listen(8081);

// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');<commit_msg>Use express instead of http<commit_after>// var http = require("http");
// app.set('view engine', 'html');
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/views'));
app.use(express.static(__dirname + '/scripts'));

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

app.get('/', function (req, res) {
  res.send('Hello World!')
})

app.post('/', function (req, res) {
  res.send('Got a POST request')
})

app.put('/user', function (req, res) {
  res.send('Got a PUT request at /user')
})

app.delete('/user', function (req, res) {
  res.send('Got a DELETE request at /user')
})<|endoftext|>


<commit_before>module.exports = simpleGet

var http = require('http')
var https = require('https')
var once = require('once')
var url = require('url')
var zlib = require('zlib')

function simpleGet (opts, cb) {
  if (typeof opts === 'string') opts = { url: opts }
  cb = once(cb)

  // Follow redirects
  if (opts.maxRedirects === 0) return cb(new Error('too many redirects'))
  if (!opts.maxRedirects) opts.maxRedirects = 10

  if (opts.url) parseOptsUrl(opts)
  if (!opts.headers) opts.headers = {}

  var body = opts.body
  opts.body = undefined
  if (body && !opts.method) opts.method = 'POST'

  // Request gzip/deflate
  var customAcceptEncoding = Object.keys(opts.headers).some(function (h) {
    return h.toLowerCase() === 'accept-encoding'
  })
  if (!customAcceptEncoding) opts.headers['accept-encoding'] = 'gzip, deflate'

  // Support http: and https: urls
  var protocol = opts.protocol === 'https:' ? https : http
  var req = protocol.request(opts, function (res) {
    // Follow 3xx redirects
    if (res.statusCode >= 300 && res.statusCode < 400 && 'location' in res.headers) {
      opts.url = res.headers.location
      parseOptsUrl(opts)
      res.resume() // Discard response
      opts.maxRedirects -= 1
      return simpleGet(opts, cb)
    }

    // Support gzip/deflate
    if (['gzip', 'deflate'].indexOf(res.headers['content-encoding']) !== -1) {
      // Pipe the response through an unzip stream (gunzip, inflate) and wrap it so it
      // looks like an `http.IncomingMessage`.
      var stream = zlib.createUnzip()
      res.pipe(stream)
      res.on('close', function () { stream.emit('close') })
      stream.httpVersion = res.httpVersion
      stream.headers = res.headers
      stream.trailers = res.trailers
      stream.setTimeout = res.setTimeout.bind(res)
      stream.method = res.method
      stream.url = res.url
      stream.statusCode = res.statusCode
      stream.socket = res.socket
      cb(null, stream)
    } else {
      cb(null, res)
    }
  })
  req.on('error', cb)
  req.end(body)
  return req
}

module.exports.concat = function (opts, cb) {
  simpleGet(opts, function (err, res) {
    if (err) return cb(err)
    var chunks = []
    res.on('data', function (chunk) {
      chunks.push(chunk)
    })
    res.on('end', function () {
      cb(null, Buffer.concat(chunks), res)
    })
  })
}

;['get', 'post', 'put', 'patch', 'head', 'delete'].forEach(function (method) {
  module.exports[method] = function (opts, cb) {
    if (typeof opts === 'string') opts = { url: opts }
    opts.method = method.toUpperCase()
    return simpleGet(opts, cb)
  }
})

function parseOptsUrl (opts) {
  var loc = url.parse(opts.url)
  if (loc.hostname) opts.hostname = loc.hostname
  if (loc.port) opts.port = loc.port
  if (loc.protocol) opts.protocol = loc.protocol
  opts.path = loc.path
  delete opts.url
}
<commit_msg>always return req<commit_after>module.exports = simpleGet

var http = require('http')
var https = require('https')
var once = require('once')
var url = require('url')
var zlib = require('zlib')

function simpleGet (opts, cb) {
  if (typeof opts === 'string') opts = { url: opts }
  cb = once(cb)

  // Follow redirects
  if (opts.maxRedirects === 0) {
    cb(new Error('too many redirects'))
    return
  }
  if (!opts.maxRedirects) opts.maxRedirects = 10

  if (opts.url) parseOptsUrl(opts)
  if (!opts.headers) opts.headers = {}

  var body = opts.body
  opts.body = undefined
  if (body && !opts.method) opts.method = 'POST'

  // Request gzip/deflate
  var customAcceptEncoding = Object.keys(opts.headers).some(function (h) {
    return h.toLowerCase() === 'accept-encoding'
  })
  if (!customAcceptEncoding) opts.headers['accept-encoding'] = 'gzip, deflate'

  // Support http: and https: urls
  var protocol = opts.protocol === 'https:' ? https : http
  var req = protocol.request(opts, function (res) {
    // Follow 3xx redirects
    if (res.statusCode >= 300 && res.statusCode < 400 && 'location' in res.headers) {
      opts.url = res.headers.location
      parseOptsUrl(opts)
      res.resume() // Discard response
      opts.maxRedirects -= 1
      return simpleGet(opts, cb)
    }

    // Support gzip/deflate
    if (['gzip', 'deflate'].indexOf(res.headers['content-encoding']) !== -1) {
      // Pipe the response through an unzip stream (gunzip, inflate) and wrap it so it
      // looks like an `http.IncomingMessage`.
      var stream = zlib.createUnzip()
      res.pipe(stream)
      res.on('close', function () { stream.emit('close') })
      stream.httpVersion = res.httpVersion
      stream.headers = res.headers
      stream.trailers = res.trailers
      stream.setTimeout = res.setTimeout.bind(res)
      stream.method = res.method
      stream.url = res.url
      stream.statusCode = res.statusCode
      stream.socket = res.socket
      cb(null, stream)
    } else {
      cb(null, res)
    }
  })
  req.on('error', cb)
  req.end(body)
  return req
}

module.exports.concat = function (opts, cb) {
  return simpleGet(opts, function (err, res) {
    if (err) return cb(err)
    var chunks = []
    res.on('data', function (chunk) {
      chunks.push(chunk)
    })
    res.on('end', function () {
      cb(null, Buffer.concat(chunks), res)
    })
  })
}

;['get', 'post', 'put', 'patch', 'head', 'delete'].forEach(function (method) {
  module.exports[method] = function (opts, cb) {
    if (typeof opts === 'string') opts = { url: opts }
    opts.method = method.toUpperCase()
    return simpleGet(opts, cb)
  }
})

function parseOptsUrl (opts) {
  var loc = url.parse(opts.url)
  if (loc.hostname) opts.hostname = loc.hostname
  if (loc.port) opts.port = loc.port
  if (loc.protocol) opts.protocol = loc.protocol
  opts.path = loc.path
  delete opts.url
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

/**
 * Falsy Values: false, 0, "", null, undefined, NaN
 *
 * - Command Line Usage:
 * node index.js --debug --dir=/path/to/api.json/and/handler/subdirectories
 */
(function () {
    /**
     * Module Dependencies.
     * @type {exports}
     */
    var http = require('http'),
        path = require('path'),
        argo = require('argo'),
        router = require('argo-url-router'),
        hypermedia = require('hypermedia'),
        slop = require('slop');

    /**
     * Walks a file system directory, and invokes the callback function at every encountered file.
     *
     * @param dir {string} representing a file system directory.
     * @example "/"
     *
     * @param callback {Function} with a single 'file' path argument.
     * @example
     * function (file) {
     *     var path = require('path'),
     *         name = path.basename(file);
     * }
     *
     * @return {undefined}
     */
    function walkSync(dir, callback) {
        if (typeof dir === 'string' && typeof callback === 'function') {
            try {
                var fs = require('fs'),
                    path = require('path'),
                    stat = fs.lstatSync(dir);
                if (stat.isFile()) {
                    callback(dir);
                } else if (stat.isDirectory()) {
                    try {
                        fs.readdirSync(dir).forEach(function (sub) {
                            walkSync(path.join(dir, sub), callback);
                        });
                    } catch (error) {
                        console.error('The path, ' + dir + ', cannot be walked.');
                    }
                }
            } catch (error) {
                console.error('The path, ' + dir + ', does not exist.');
            }
        }
    }

    /**
     * Walks a file system directory, and looks for Node Javascript files that export a handler function.
     *
     * @param dir {string} representing a file system directory.
     * @example "/"
     *
     * @param id {string} representing the name of the file without the ".js" extension.
     * @example "name"
     *
     * @return {Function} if a handler function was exported; {null}, otherwise.
     */
    function handlerById(dir, id) {
        var handler = null;
        if (typeof id === 'string' && typeof dir === 'string') {
            walkSync(dir, function (file) {
                var path = require('path'),
                    name = path.basename(file, '.js');
                if (name === id) {
                    if (debug) {
                        console.log('The ' + id + '.js directory is ' + file + '.');
                    }
                    try {
                        handler = require(file);
                    } catch (error) {
                        handler = null;
                    }
                }
            });
        }
        return typeof handler === 'function' ? handler : null;
    }

    /**
     * Command Line Options.
     * Dir will resolve a given path, or be the current working directory.
     */
    var opt = slop().parse(process.argv),
        dir = path.resolve(typeof opt.get('dir') === 'string' ? opt.get('dir') : ''),
        debug = opt.has('debug');

    if (debug) {
        console.log('The cwd directory is ' + process.cwd() + '.');
        console.log('The api directory is ' + dir + '.');
    }

    /**
     * HTTP Application Router.
     */
    var app = argo(),
        hapi = {};

    /**
     * Walk the given directory in an attempt to find and parse a file called api.json.
     */
    walkSync(dir, function (file) {
        var name = path.basename(file, '.json');
        if (name === 'api') {
            if (debug) {
                console.log('The api.json directory is ' + file + '.');
            }
            try {
                hapi = require(file);
            } catch (error) {
                hapi = {};
            }
        }
    });

    /**
     * Set up middleware including:
     * - URI route handling
     * - CORS request handling
     * - CORS response handling
     * - Hypermedia response handling
     * - Unhandled Exception handling
     *
     * Order:
     * 1. Request Middleware - Order Added.
     * 2. Request Route
     * 3. Response Route
     * 4. Response Middleware - Order Reversed.
     */
    app
        .use(router)
        .use(function (handle) {
            handle('request', function (env, next) {
                /**
                 * Cross-Origin Request
                 * @see http://www.w3.org/TR/cors
                 * @see http://www.html5rocks.com/static/images/cors_server_flowchart.png
                 */
                hapi.incomingMessageCors(env.request, env.cors = env.cors || {});
                return next(env);
            });
        })
        .use(function (handle) {
            handle('response', function (env, next) {
                /**
                 * Cross-Origin Response
                 * @see http://www.w3.org/TR/cors
                 * @see http://www.html5rocks.com/static/images/cors_server_flowchart.png
                 */
                hapi.serverResponseCors(env.response, env.cors = env.cors || {});
                return next(env);
            });
        })
        .use(function (handle) {
            handle('response', function (env, next) {
                /**
                 * Hypermedia Response
                 */
                hapi.serverResponseNavData(env.response, env.hypermedia);
                return next(env);
            });
        })
        .use(function (handle) {
            handle('error', function (env, error, next) {
                /**
                 * Unhandled Exceptions
                 */
                console.error('The server had an unhandled exception. Exiting the process.');
                console.error(new Date().toUTCString() + ' uncaughtException:', error.message);
                console.error(error.stack);
                env.response.statusCode = 500;
                next(env);
                process.exit(1);
            });
        });

    /**
     * Create a hypermedia.Api from the parsed api.json file.
     * Map middleware and apis defined in the file to the HTTP Application Router.
     */
    hapi = hypermedia.Api.create(hapi);
    hapi
        .eachReqMiddleware(function (m) {
            var handler = handlerById(dir, m.id);
            app.use(function (handle) {
                handle(m.middleware, handler || function (env, next) {
                    if (debug) {
                        console.log('The middleware, ' + m.id + ', needs a handler.');
                    }
                    return next(env);
                });
            });
            if (debug) {
                console.log('The middleware, ' + m.id + ', ' + (handler ? 'has' : 'needs') + ' a handler.');
            }
        })
        .eachApi(function (a) {
            var handler = handlerById(dir, a.id);
            app.route(a.uri, { 'methods': [ a.method ] }, function (handle) {
                handle('request', function (env, next) {
                    env.api = a;
                    if (debug) {
                        console.log('The api, ' + a.id + ', will be used.');
                    }
                    return next(env);
                });
                handle('request', handler || function (env, next) {
                    env.response.statusCode = 200;
                    if (debug) {
                        console.log('The api, ' + a.id + ', needs a handler.');
                    }
                    return next(env);
                });
            });
            if (debug) {
                console.log('The api, ' + a.id + ', ' + (handler ? 'has' : 'needs') + ' a handler.');
            }
        })
        .eachResMiddleware(function (m) {
            var handler = handlerById(dir, m.id);
            app.use(function (handle) {
                handle(m.middleware, handler || function (env, next) {
                    if (debug) {
                        console.log('The middleware, ' + m.id + ', needs a handler.');
                    }
                    return next(env);
                });
            });
            if (debug) {
                console.log('The middleware, ' + m.id + ', ' + (handler ? 'has' : 'needs') + ' a handler.');
            }
        });

    console.log('The server port is ' + hapi.port + '.');
    console.log('The server hostname is ' + hapi.hostname + '.');

    /**
     * Create an HTTP Server with the Application Router.
     */
    http
        .createServer(app.build().run)
        .on('error', function (error) {
            console.error('The server may need root user privileges to start.');
            console.error(new Date().toUTCString() + ' caughtException:', error.message);
            console.error(error.stack);
        })
        .on('listening', function () {
            console.log('The server started.');
        })
        .listen(hapi.port, hapi.hostname);
})();
<commit_msg>Command Line Interface Changes.<commit_after>#!/usr/bin/env node

/**
 * Falsy Values: false, 0, "", null, undefined, NaN
 * Command Line Usage (Local):  node [path/to/]index.js
 * Command Line Usage (Global): coast
 */

/**
 * Walk a file system directory, and callback at every file.
 *
 * @param dir {String} representing a file system directory.
 * @example "/"
 * @param callback {Function} with a single 'file' path argument.
 * @example function (file) { var name = require('path').basename(file); }
 * @return {Undefined}
 */
function walkDirByFileSync(dir, callback) {
    if (typeof dir === 'string' && typeof callback === 'function') {
        try {
            var fs = require('fs'),
                path = require('path'),
                stat = fs.lstatSync(dir);
            if (stat.isFile()) {
                callback(dir);
            } else if (stat.isDirectory()) {
                try {
                    fs.readdirSync(dir).forEach(function (sub) {
                        walkDirByFileSync(path.join(dir, sub), callback);
                    });
                } catch (error) {
                    console.error(new Date().toUTCString() + ' caughtException:', error.message);
                    console.error(error.stack);
                }
            }
        } catch (error) {
            console.error(new Date().toUTCString() + ' caughtException:', error.message);
            console.error(error.stack);
        }
    }
}

/**
 * Walk a file system directory, and require file by name.
 *
 * @param dir {String} representing a file system directory.
 * @example "/"
 * @param name {String} representing the name of the file.
 * @example "name.js"
 * @return {Object}
 * @example module.exports
 * @example null
 */
function requireFileByName(dir, name) {
    var handler = null;
    if (typeof dir === 'string' && typeof name === 'string') {
        walkDirByFileSync(dir, function (file) {
            var path = require('path');
            if (path.basename(file) === name) {
                try {
                    handler = require(file);
                } catch (error) {
                    handler = null;
                }
            }
        });
    }
    return handler;
}

/**
 * Look for api.json in cwd.
 */
var lostFile = true;

walkDirByFileSync(process.cwd(), function (file) {
    var path = require('path');
    if (path.basename(file) === 'api.json') {
        /**
         * Found api.json in cwd.
         * Require Hypermedia as a module to use exported middleware in a server.
         * Read and minify Hypermedia as a text file to use exported client in a browser.
         */
        var fs = require('fs'),
            hypermedia = require('hypermedia'),
            uglify = require('uglify-js'),
            clientPath = require.resolve('hypermedia'),
            readClient = fs.readFileSync(clientPath, 'utf-8'),
            miniClient = uglify.minify(clientPath).code,
            api = hypermedia.Api.createFromFile(file);

        lostFile = false;

        if (api.protocol === 'http') {
            var express = require('express'),
                app = express(),
                lostMiddleware = [];

            /**
             * Default API route handler that acknowledges requests with a 200 OK.
             *
             * @param req {IncomingMessage} object created by http.Server.
             * @see http://nodejs.org/api/http.html#http_http_incomingmessage
             * @param res {ServerResponse} object created by http.Server.
             * @see http://nodejs.org/api/http.html#http_class_http_serverresponse
             * @param next {Function} middleware in the pipeline.
             * @return {Undefined}
             */
            function defaultApi(req, res, next) {
                res.statusCode = 200;
                return next();
            }

            /**
             * Default middleware handler that does nothing.
             *
             * @param req {IncomingMessage} object created by http.Server.
             * @see http://nodejs.org/api/http.html#http_http_incomingmessage
             * @param res {ServerResponse} object created by http.Server.
             * @see http://nodejs.org/api/http.html#http_class_http_serverresponse
             * @param next {Function} middleware in the pipeline.
             * @return {Undefined}
             */
            function defaultMid(req, res, next) {
                return next();
            }

            /**
             * Create API with middleware/route stack:
             * 1. Incoming Message CORS Middleware (Creates req.cors based on http.IncomingMessage.)
             * 2. a. Client User Agent API (Returns API client from GET /ua.)
             *    b. Custom api.json Middleware/APIs
             * 3. Outgoing Message Body Middleware (Modifies res.body to String.)
             * 4. Outgoing Message Hypermedia Middleware (Modifies res.body based on res.hype.)
             * 5. Outgoing Message CORS Middleware (Modifies http.ServerResponse based on req.cors.)
             * 6. Outgoing Message Final Middleware (Sends final res.body to client.)
             */
            app
                .disable('x-powered-by')
                .use(function (req, res, next) {
                    api.incomingMessageCors(req, res);
                    return next();
                })
                .get('/ua', function (req, res, next) {
                    res.statusCode = 200;
                    res.setHeader('content-type', 'application/javascript');
                    res.body = api.debug ? readClient : miniClient;
                    return next();
                });

            /**
             * Look for [routine.id].js in cwd.
             * Use custom middleware and APIs when found; default, otherwise.
             */
            api.each(function (routine, type) {
                var handler = requireFileByName(process.cwd(), routine.id + '.js'),
                    lostFile = typeof handler !== 'function';
                if (lostFile) {
                    lostMiddleware.push(routine.id);
                }
                if (type === 'mid') {
                    app.use(lostFile ? defaultMid : handler);
                }
                if (type === 'api') {
                    app[routine.method.toLowerCase()](routine.uri, lostFile ? defaultApi : handler);
                }
            });

            if (lostMiddleware.length > 0) {
                console.log('A handler file was not found for ' + lostMiddleware.join(', ') + '.');
            }

            app
                .use(function (req, res, next) {
                    api.outgoingMessageBody(req, res);
                    return next();
                })
                .use(function (req, res, next) {
                    api.outgoingMessageHypermedia(req, res);
                    return next();
                })
                .use(function (req, res, next) {
                    api.outgoingMessageCors(req, res);
                    return next();
                })
                .use(function (req, res) {
                    api.outgoingMessageFinal(req, res);
                })
                .listen(api.port, api.hostname, function () {
                    console.log('A server is accepting connections on ' + api.hostname + ':' + api.port + '.');
                });
        } else {
            console.log('A transfer protocol other than HTTP is not currently supported in api.json.');
        }
    }
});

if (lostFile) {
    console.log('A file called api.json was not found within the current working directory.');
}
<|endoftext|>


<commit_before>const fs = require('fs');
const Promise = require('bluebird');

module.exports = function(knex, path, tableName, mapTo, options) {
  return new Promise(function(resolve, reject) {
    if (
      typeof path === 'undefined' ||
      typeof tableName === 'undefined' ||
      (typeof mapTo === 'undefined' && !mapTo.useFirstLineForColumns)
    ) {
      reject(Error('path, tableName and mapTo needs to be defined'));
    }
    options = Object.assign({
      columnSeparator: '\t',
      rowSeparator: '\n',
      encoding: 'utf8',
      ignoreFirstLine: Boolean(useFirstLineForColumns),
      useFirstLineForColumns: false,
      handleInsert: function(inserts, tableName) {
        return knex(tableName).insert(inserts);
      },
    }, options);

    const stream = fs.createReadStream(path).setEncoding(options.encoding);

    const splitEnd = '';

    const inserts = [];

    stream.on('data', function(chunk) {
      const tempRows = chunk.split(options.rowSeparator);
      if (splitEnd.length > 0) {
        tempRows[0] = splitEnd + tempRows[0];
        splitEnd = '';
      }
      if (!tempRows[tempRows.length-1].endsWith(options.rowSeparator)) {
        splitEnd = tempRows.pop();
      }
      if (options.ignoreFirstLine || options.useFirstLineForColumns) {
        if (options.useFirstLineForColumns) {
          mapTo = tempRows.shift().split(options.columnSeparator);
        } else {
          tempRows.shift();
        }
        options.ignoreFirstLine = false;
        options.useFirstLineForColumns = false;
      }

      tempRows.map(function(row) {
        const cols = row.split(options.columnSeparator);
        const knexRow = {};
        mapTo.map(function(key, index) {
          if (key === null) {
            return;
          }
          try {
            knexRow[key] = cols[index] ? JSON.parse(cols[index]) : null;
          } catch (e) {
            knexRow[key] = cols[index];
          }
        });
        inserts.push(knexRow);
      });
    });

    stream.on('end', function() {
      options.handleInsert(inserts, tableName)
          .then(resolve('all rows inserted'));
    });
  });
};
<commit_msg>move mapTo behind options<commit_after>const fs = require('fs');
const Promise = require('bluebird');

module.exports = function(knex, path, tableName, options) {
  return new Promise(function(resolve, reject) {
    options = Object.assign({
      columnSeparator: '\t',
      rowSeparator: '\n',
      encoding: 'utf8',
      ignoreFirstLine: false,
      useFirstLineForColumns: true,
      handleInsert: function(inserts, tableName) {
        return knex(tableName).insert(inserts);
      },
    }, options);

    if (
      typeof path === 'undefined' ||
      typeof tableName === 'undefined' ||
      (typeof options.mapTo === 'undefined' && !options.useFirstLineForColumns)
    ) {
      reject(Error('path, tableName and mapTo needs to be defined'));
    }

    const stream = fs.createReadStream(path).setEncoding(options.encoding);

    const splitEnd = '';

    const inserts = [];

    stream.on('data', function(chunk) {
      const tempRows = chunk.split(options.rowSeparator);
      if (splitEnd.length > 0) {
        tempRows[0] = splitEnd + tempRows[0];
        splitEnd = '';
      }
      if (!tempRows[tempRows.length-1].endsWith(options.rowSeparator)) {
        splitEnd = tempRows.pop();
      }
      if (options.ignoreFirstLine || options.useFirstLineForColumns) {
        if (options.useFirstLineForColumns) {
          mapTo = tempRows.shift().split(options.columnSeparator);
        } else {
          tempRows.shift();
        }
        options.ignoreFirstLine = false;
        options.useFirstLineForColumns = false;
      }

      tempRows.map(function(row) {
        const cols = row.split(options.columnSeparator);
        const knexRow = {};
        mapTo.map(function(key, index) {
          if (key === null) {
            return;
          }
          try {
            knexRow[key] = cols[index] ? JSON.parse(cols[index]) : null;
          } catch (e) {
            knexRow[key] = cols[index];
          }
        });
        inserts.push(knexRow);
      });
    });

    stream.on('end', function() {
      options.handleInsert(inserts, tableName)
          .then(resolve('all rows inserted'));
    });
  });
};
<|endoftext|>


<commit_before>'use strict';

function fuzzysearch (needle, haystack) {
  var tlen = haystack.length;
  var qlen = needle.length;
  if (qlen > tlen) {
    return false;
  }
  if (qlen === tlen) {
    return needle === haystack;
  }
  outer: for (var i = 0, j = 0; i < qlen; i++) {
    var nch = needle.charCodeAt(i);
    while (j < tlen) {
      if (haystack.charCodeAt(j++) === nch) {
        continue outer;
      }
    }
    return false;
  }
  return true;
}

module.exports = fuzzysearch;
<commit_msg>relevant len variable names<commit_after>'use strict';

function fuzzysearch (needle, haystack) {
  var hlen = haystack.length;
  var nlen = needle.length;
  if (nlen > hlen) {
    return false;
  }
  if (nlen === hlen) {
    return needle === haystack;
  }
  outer: for (var i = 0, j = 0; i < nlen; i++) {
    var nch = needle.charCodeAt(i);
    while (j < hlen) {
      if (haystack.charCodeAt(j++) === nch) {
        continue outer;
      }
    }
    return false;
  }
  return true;
}

module.exports = fuzzysearch;
<|endoftext|>


<commit_before>"use strict";

var request = require('request'),
	path = require("path"),
	fs = require('fs'),
	mime = require('mime'),
	GitHubApi = require("github"),
	cwd = process.cwd();

function NodePreGypGithub() {}

NodePreGypGithub.prototype.github;
NodePreGypGithub.prototype.owner;
NodePreGypGithub.prototype.repo;
NodePreGypGithub.prototype.package_json = {};
NodePreGypGithub.prototype.release = {};
NodePreGypGithub.prototype.stage_dir = path.join(cwd,"build","stage");

NodePreGypGithub.prototype.init = function() {
	var ownerRepo, hostPrefix,
		error = function(){
		process.exit(1);
	};

	this.package_json = JSON.parse(fs.readFileSync(path.join(cwd,'package.json')));

	if(!this.package_json.repository || !this.package_json.repository.url){
		console.error('Error: Missing repository.url in package.json');
		error();
	}
	else {
		ownerRepo = this.package_json.repository.url.match(/github\.com\/(.*)(?=\.git)/i);
		if (ownerRepo) {
			ownerRepo = ownerRepo[1].split('/');
			this.owner = ownerRepo[0];
			this.repo = ownerRepo[1];
		}
		else {
			console.error('Error: Not a GitHub repository.url in package.json');
			error();
		}
	}

	hostPrefix = 'https://github.com/' + this.owner + '/' + this.repo + '/releases/download/';
	if(!this.package_json.binary || 'object' !== typeof this.package_json.binary ||
			'string' !== typeof this.package_json.binary.host){
		console.error('Error: Missing binary.host in package.json, configure node-pre-gyp first');
		error();
	}
	else if (this.package_json.binary.host.substr(0, hostPrefix.length) !== hostPrefix){
		console.error('Error: binary.host in package.json should begin with: "' + hostPrefix + '"');
		error();
	}

	this.github = new GitHubApi({ // set defaults
		// required
		version: "3.0.0",
		// optional
		debug: false,
		protocol: "https",
		host: "api.github.com",
		pathPrefix: "", // for some GHEs; none for GitHub
		timeout: 5000,
		headers: {
			"user-agent": (this.package_json.name) ? this.package_json.name : "node-pre-gyp-github" // GitHub is happy with a unique user agent
		}
	});
};

NodePreGypGithub.prototype.authenticate_settings = function(){
	return {
		type: "oauth",
		token: process.env.NODE_PRE_GYP_GITHUB_TOKEN
	};
};

NodePreGypGithub.prototype.createRelease = function(args, callback) {
	var options = {
		'owner': this.owner,
		'repo': this.repo,
		'tag_name': this.package_json.version,
		'target_commitish': 'master',
		'name': 'v' + this.package_json.version,
		'body': this.package_json.name + ' ' + this.package_json.version,
		'draft': true,
		'prerelease': false
	};

	Object.keys(args).forEach(function(key) {
		if(args.hasOwnProperty(key)) {
			options[key] = args[key];
		}
	});

	this.github.authenticate(this.authenticate_settings());
	this.github.releases.createRelease(options, callback);
};

NodePreGypGithub.prototype.uploadAsset = function(cfg){
	this.github.authenticate(this.authenticate_settings());
	this.github.releases.uploadAsset({
		owner: this.owner,
		id: this.release.id,
		repo: this.repo,
		name: cfg.fileName,
		filePath: cfg.filePath
	}, function(err){
		if(err) {console.error(err); return;}
		console.log('Staged file ' + cfg.fileName + ' saved to ' + this.owner + '/' +  this.repo + ' release ' + this.release.tag_name + ' successfully.');
	}.bind(this));
};

NodePreGypGithub.prototype.uploadAssets = function(){
	var asset;
	console.log("Stage directory path: " + path.join(this.stage_dir));
	fs.readdir(path.join(this.stage_dir), function(err, files){
		if(typeof files === 'undefined') {console.log('no files found'); return;}
		files.forEach(function(file){
			asset = this.release.assets.filter(function(element, index, array){
				return element.name === file;
			});
			if(asset.length) {
				console.log("Staged file " + file + " found but it already exists in release " + this.release.tag_name + ". If you would like to replace it, you must first manually delete it within GitHub.");
			}
			else {
				console.log("Staged file " + file + " found. Proceeding to upload it.");
				this.uploadAsset({
					fileName: file,
					filePath: path.join(this.stage_dir, file)
				});
			}
		}.bind(this));
	}.bind(this));
};

NodePreGypGithub.prototype.publish = function(options) {
	this.init();
	this.github.authenticate(this.authenticate_settings());
	this.github.releases.listReleases({
		'owner': this.owner,
		'repo': this.repo
	}, function(err, data){
		var release;

		if(err) {console.error(err); return;}

		// when remote_path is set expect files to be in stage_dir / remote_path after substitution
		if (this.package_json.binary.remote_path) {
			options.tag_name = this.package_json.binary.remote_path.replace(/{version}/g, this.package_json.version);
			this.stage_dir = path.join(this.stage_dir, options.tag_name);
		} else {
			options.tag_name = this.package_json.version;
		}

		release	= (function(){ // create a new array containing only those who have a matching version.
			data = data.filter(function(element, index, array){
				return element.tag_name === options.tag_name;
			}.bind(this));
			return data;
		}.bind(this))();

		this.release = release[0];

		if(!release.length) {
			this.createRelease(options, function(err, release) {
				if(err) {console.error(err); return;}

				this.release = release;
				console.log('Release ' + this.package_json.version + " not found, so a draft release was created. YOU MUST MANUALLY PUBLISH THIS DRAFT WITHIN GITHUB FOR IT TO BE ACCESSIBLE.");
				this.uploadAssets();
			}.bind(this));
		}
		else {
			this.uploadAssets();
		}
	}.bind(this));
};

module.exports = NodePreGypGithub;<commit_msg>post createRelease message should not be confusing<commit_after>"use strict";

var request = require('request'),
	path = require("path"),
	fs = require('fs'),
	mime = require('mime'),
	GitHubApi = require("github"),
	cwd = process.cwd();

function NodePreGypGithub() {}

NodePreGypGithub.prototype.github;
NodePreGypGithub.prototype.owner;
NodePreGypGithub.prototype.repo;
NodePreGypGithub.prototype.package_json = {};
NodePreGypGithub.prototype.release = {};
NodePreGypGithub.prototype.stage_dir = path.join(cwd,"build","stage");

NodePreGypGithub.prototype.init = function() {
	var ownerRepo, hostPrefix,
		error = function(){
		process.exit(1);
	};

	this.package_json = JSON.parse(fs.readFileSync(path.join(cwd,'package.json')));

	if(!this.package_json.repository || !this.package_json.repository.url){
		console.error('Error: Missing repository.url in package.json');
		error();
	}
	else {
		ownerRepo = this.package_json.repository.url.match(/github\.com\/(.*)(?=\.git)/i);
		if (ownerRepo) {
			ownerRepo = ownerRepo[1].split('/');
			this.owner = ownerRepo[0];
			this.repo = ownerRepo[1];
		}
		else {
			console.error('Error: Not a GitHub repository.url in package.json');
			error();
		}
	}

	hostPrefix = 'https://github.com/' + this.owner + '/' + this.repo + '/releases/download/';
	if(!this.package_json.binary || 'object' !== typeof this.package_json.binary ||
			'string' !== typeof this.package_json.binary.host){
		console.error('Error: Missing binary.host in package.json, configure node-pre-gyp first');
		error();
	}
	else if (this.package_json.binary.host.substr(0, hostPrefix.length) !== hostPrefix){
		console.error('Error: binary.host in package.json should begin with: "' + hostPrefix + '"');
		error();
	}

	this.github = new GitHubApi({ // set defaults
		// required
		version: "3.0.0",
		// optional
		debug: false,
		protocol: "https",
		host: "api.github.com",
		pathPrefix: "", // for some GHEs; none for GitHub
		timeout: 5000,
		headers: {
			"user-agent": (this.package_json.name) ? this.package_json.name : "node-pre-gyp-github" // GitHub is happy with a unique user agent
		}
	});
};

NodePreGypGithub.prototype.authenticate_settings = function(){
	return {
		type: "oauth",
		token: process.env.NODE_PRE_GYP_GITHUB_TOKEN
	};
};

NodePreGypGithub.prototype.createRelease = function(args, callback) {
	var options = {
		'owner': this.owner,
		'repo': this.repo,
		'tag_name': this.package_json.version,
		'target_commitish': 'master',
		'name': 'v' + this.package_json.version,
		'body': this.package_json.name + ' ' + this.package_json.version,
		'draft': true,
		'prerelease': false
	};

	Object.keys(args).forEach(function(key) {
		if(args.hasOwnProperty(key)) {
			options[key] = args[key];
		}
	});

	this.github.authenticate(this.authenticate_settings());
	this.github.releases.createRelease(options, callback);
};

NodePreGypGithub.prototype.uploadAsset = function(cfg){
	this.github.authenticate(this.authenticate_settings());
	this.github.releases.uploadAsset({
		owner: this.owner,
		id: this.release.id,
		repo: this.repo,
		name: cfg.fileName,
		filePath: cfg.filePath
	}, function(err){
		if(err) {console.error(err); return;}
		console.log('Staged file ' + cfg.fileName + ' saved to ' + this.owner + '/' +  this.repo + ' release ' + this.release.tag_name + ' successfully.');
	}.bind(this));
};

NodePreGypGithub.prototype.uploadAssets = function(){
	var asset;
	console.log("Stage directory path: " + path.join(this.stage_dir));
	fs.readdir(path.join(this.stage_dir), function(err, files){
		if(typeof files === 'undefined') {console.log('no files found'); return;}
		files.forEach(function(file){
			asset = this.release.assets.filter(function(element, index, array){
				return element.name === file;
			});
			if(asset.length) {
				console.log("Staged file " + file + " found but it already exists in release " + this.release.tag_name + ". If you would like to replace it, you must first manually delete it within GitHub.");
			}
			else {
				console.log("Staged file " + file + " found. Proceeding to upload it.");
				this.uploadAsset({
					fileName: file,
					filePath: path.join(this.stage_dir, file)
				});
			}
		}.bind(this));
	}.bind(this));
};

NodePreGypGithub.prototype.publish = function(options) {
	this.init();
	this.github.authenticate(this.authenticate_settings());
	this.github.releases.listReleases({
		'owner': this.owner,
		'repo': this.repo
	}, function(err, data){
		var release;

		if(err) {console.error(err); return;}

		// when remote_path is set expect files to be in stage_dir / remote_path after substitution
		if (this.package_json.binary.remote_path) {
			options.tag_name = this.package_json.binary.remote_path.replace(/{version}/g, this.package_json.version);
			this.stage_dir = path.join(this.stage_dir, options.tag_name);
		} else {
			options.tag_name = this.package_json.version;
		}

		release	= (function(){ // create a new array containing only those who have a matching version.
			data = data.filter(function(element, index, array){
				return element.tag_name === options.tag_name;
			}.bind(this));
			return data;
		}.bind(this))();

		this.release = release[0];

		if(!release.length) {
			this.createRelease(options, function(err, release) {
				if(err) {console.error(err); return;}

				this.release = release;
				if (release.draft) {
					console.log('Release ' + release.tag_name + " not found, so a draft release was created. YOU MUST MANUALLY PUBLISH THIS DRAFT WITHIN GITHUB FOR IT TO BE ACCESSIBLE.");
				} else {
					console.log('Release ' + release.tag_name + " not found, so a new release was created and published.");
				}
				this.uploadAssets();
			}.bind(this));
		}
		else {
			this.uploadAssets();
		}
	}.bind(this));
};

module.exports = NodePreGypGithub;<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import Head from 'next/head';
import GoogleAnalytics from './GoogleAnalytics';
import { globalStyles } from '../common/styles';
import { StyleSheet, css } from 'glamor/aphrodite';

export default class Document extends React.Component {
  static propTypes = {
    title: PropTypes.string,
    description: PropTypes.string,
  };

  static defaultProps = {
    title: 'Native Directory',
    description: 'Native Directory is a curated list of React Native libraries to help you build your projects.',
  };

  render() {
    return (
      <main className={css(styles.render)}>
        <Head>
          <title>{this.props.title}</title>
          <meta name="theme-color" content="#00C9FF" />
          <meta name="twitter:title" content={this.props.title} />
          <meta property="og:title" content={this.props.title} />

          <meta name="description" content={this.props.description} />
          <meta property="og:description" content={this.props.description} />
          <meta name="twitter:description" content={this.props.description} />
        </Head>,
        {this.props.children}
      </main>
    );
  }
}

const styles = StyleSheet.create({
  render: {
    visibility: 'visible',
  },
});
<commit_msg>Remove extra comma<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import Head from 'next/head';
import GoogleAnalytics from './GoogleAnalytics';
import { globalStyles } from '../common/styles';
import { StyleSheet, css } from 'glamor/aphrodite';

export default class Document extends React.Component {
  static propTypes = {
    title: PropTypes.string,
    description: PropTypes.string,
  };

  static defaultProps = {
    title: 'Native Directory',
    description: 'Native Directory is a curated list of React Native libraries to help you build your projects.',
  };

  render() {
    return (
      <main className={css(styles.render)}>
        <Head>
          <title>{this.props.title}</title>
          <meta name="theme-color" content="#00C9FF" />
          <meta name="twitter:title" content={this.props.title} />
          <meta property="og:title" content={this.props.title} />

          <meta name="description" content={this.props.description} />
          <meta property="og:description" content={this.props.description} />
          <meta name="twitter:description" content={this.props.description} />
        </Head>
        {this.props.children}
      </main>
    );
  }
}

const styles = StyleSheet.create({
  render: {
    visibility: 'visible',
  },
});
<|endoftext|>


<commit_before>/**
 * relative <https://github.com/jonschlinkert/relative>
 * Copyright (c) 2014 Jon Schlinkert, contributors.
 * Licensed under the MIT license.
 */

'use strict';

var fs = require('fs');
var path = require('path');
var normalize = require('normalize-path');

// True if the filepath is a directory.
function isDir() {
  var filepath = path.join.apply(path, arguments);
  if (!fs.existsSync(filepath)) {
    return false;
  }
  return fs.statSync(filepath).isDirectory();
}

/**
 * ## relative
 *
 * Return the relative path from `a` to `b`.
 *
 * **Example**:
 *
 * ```js
 * var relative = require('relative');
 * relative('test/fixtures/foo.txt', 'docs/new/file.txt');
 * //=> '../../docs/new/file.txt'
 * ```
 *
 * @param   {String} `from`
 * @param   {String} `to`
 * @return  {String}
 */

var relative = module.exports = function(a, b) {
  if(arguments.length === 1) {b = a; a = process.cwd();}
  a = !isDir(a) ? path.dirname(a) : a;
  var rel = path.relative(path.resolve(a), path.resolve(b));
  return normalize(rel);
};

/**
 * ## .toBase
 *
 * Get the path relative to the given base path.
 *
 * **Example**:
 *
 * ```js
 * relative.toBase('test/fixtures', 'test/fixtures/docs/new/file.txt');
 * //=> 'docs/new/file.txt'
 * ```
 *
 * @param   {String}  `basepath`  The base directory
 * @param   {String}  `filepath`  The full filepath
 * @return  {String}            The relative path
 */

relative.toBase = function (basepath, filepath) {
  filepath = path.resolve(filepath);
  basepath = path.resolve(basepath);

  if (filepath.indexOf(basepath) === 0) {
    filepath = filepath.replace(basepath, '');
  }
  filepath = normalize(filepath);

  // Remove leading slash.
  return filepath.replace(/^\//, '');
};
<commit_msg>make logic a little less cryptic. remove normalization. that should be done by the implementor<commit_after>/**
 * relative <https://github.com/jonschlinkert/relative>
 * Copyright (c) 2014 Jon Schlinkert, contributors.
 * Licensed under the MIT license.
 */

'use strict';

var fs = require('fs');
var path = require('path');
var isDir = require('is-directory');

/**
 * Return the relative path from `a` to `b`.
 *
 * **Example**:
 *
 * ```js
 * var relative = require('relative');
 * relative('test/fixtures/foo.txt', 'docs/new/file.txt');
 * //=> '../../docs/new/file.txt'
 * ```
 *
 * @param   {String} `from`
 * @param   {String} `to`
 * @return  {String}
 */

var relative = module.exports = function relative(from, to) {
  if (arguments.length === 1) {
    to = from;
    from = process.cwd();
  }

  if (!isDir(from)) {
    from = path.dirname(from);
  }

  from = path.resolve(from);
  to = path.resolve(to);

  return path.relative(from, to);
};

/**
 * Get the path relative to the given base path.
 *
 * **Example**:
 *
 * ```js
 * relative.toBase('test/fixtures', 'test/fixtures/docs/new/file.txt');
 * //=> 'docs/new/file.txt'
 * ```
 *
 * @param {String} `basepath` The base directory
 * @param {String} `filepath` The full filepath
 * @return {String} The relative path
 */

relative.toBase = function (basepath, filepath) {
  filepath = path.resolve(filepath);
  basepath = path.resolve(basepath);

  if (filepath.indexOf(basepath) === 0) {
    filepath = filepath.replace(basepath, '');
  }

  // Remove leading slash if one was created
  return filepath.replace(/^[\\\/]*/, '');
};
<|endoftext|>


<commit_before>/**
 * concept
 * https://www.w3.org/TR/wai-aria-1.1/#roletype
 *
 * id
 * https://www.w3.org/TR/wai-aria-1.1/#valuetype_idref
 * https://www.w3.org/TR/html5/dom.html#the-id-attribute
 *
 * hidden
 * https://www.w3.org/TR/wai-aria-1.1/#aria-hidden
 * https://www.w3.org/TR/wai-aria-1.1/#dfn-hidden
 * https://www.w3.org/TR/html5/editing.html#the-hidden-attribute
 *
 * disabled
 * https://www.w3.org/TR/wai-aria-1.1/#aria-disabled
 * https://www.w3.org/TR/html5/forms.html#attr-fe-disabled
 *
 * events
 * https://www.w3.org/TR/dom/#events
 */

const map = Array.prototype.map;

export default class Instance {
    /**
     * The base instance from which all other instances in this taxonomy inherit
     * @param {Element} element root element node
     */
    constructor(element) {
        element.instance = this;
        this.element = element;
    }

    /**
     * Get unique identifier
     * @returns {String}
     */
    get id() {
        return this.element.id || '';
    }

    /**
     * Get hidden state
     * @returns {String}
     */
    get hidden() {
        return String(this.element.hidden);
    }

    /**
     * Set hidden state
     * @param {String} hidden state
     */
    set hidden(hidden) {
        this.element.hidden = hidden === 'true';
    }

    /**
     * Get disabled state
     * @returns {String}
     */
    get disabled() {
        return this.element.getAttribute('aria-disabled') || 'false';
    }

    /**
     * Set disabled state
     * @param {String} disabled state
     */
    set disabled(disabled) {
        this.element.setAttribute('aria-disabled', disabled);
    }

    /**
     * Add event listener
     * @param {String} type event type
     * @param {Function} listener event listener
     * @param {Object} context event listener context
     * @returns {Instance} this
     */
    on(type, listener, context) {
        this.element.addEventListener(type, listener.bind(context || this));
        return this;
    }

    /**
     * Dispatch event
     * @param {String} type event type;
     * @returns {Instance} this
     */
    emit(type) {
        this.element.dispatchEvent(new Event(type, { bubbles : true, cancelable : true }));
        return this;
    }

    /**
     * Find the first descendant instance
     * @param {Instance} Class target instance class
     * @param {Function} filter function
     * @returns {Instance|null}
     */
    find(Class, filter) {
        return filter?
            this.findAll(Class, filter)[0] || null :
            Class.getInstance(this.element.querySelector(`[data-instance=${Class.name}]`));
    }

    /**
     * Find all descendant instances
     * @param {Instance} Class target instance class
     * @param {Function} filter function
     * @returns {Array} array of found instances
     */
    findAll(Class, filter) {
        const result = map.call(
            this.element.querySelectorAll(`[data-instance=${Class.name}]`),
            element => Class.getInstance(element));
        return filter? result.filter(filter) : result;
    }

    /**
     * Find the nearest ancestor instance
     * @param {Instance} Class target instance class
     * @param {Function} filter function
     * @returns {Instance} found instance
     */
    closest(Class, filter) {
        let instance = this;
        do instance = Class.getInstance(instance.element.parentElement.closest(`[data-instance=${Class.name}]`));
        while(instance && filter && !filter(instance));
        return instance;
    }

    /**
     * Create if needed and return the instance of specified element
     * @param {Element} element root element node of target instance
     * @returns {Instance|null}
     */
    static getInstance(element) {
        return element && element.dataset && element.dataset.instance === this.name?
            element.instance || new this(element) :
            null;
    }

    /**
     * Create if needed and return the nearest ancestor instance of specified element
     * @param {Element} element node inside target instance
     * @returns {Instance|null}
     */
    static closestInstance(element) {
        return this.getInstance(element.closest(`[data-instance=${this.name}]`));
    }

    /**
     * Delegate event listener to the document node
     * @param {String} type event type
     * @param {Function} listener event listener
     * @param {Object} context event listener context
     */
    static on(type, listener, context) {
        document.addEventListener(type, event => {
            const instance = (context || this).closestInstance(event.target);
            if(instance) listener.call(instance, event);
        }, true);
    }
}
<commit_msg>Instance: improve jsdoc, Element.prototype.instance property<commit_after>/**
 * base concept
 * https://www.w3.org/TR/wai-aria-1.1/#roletype
 * https://www.w3.org/TR/dom/#element
 *
 * id
 * https://www.w3.org/TR/wai-aria-1.1/#valuetype_idref
 * https://www.w3.org/TR/html5/dom.html#the-id-attribute
 *
 * hidden
 * https://www.w3.org/TR/wai-aria-1.1/#aria-hidden
 * https://www.w3.org/TR/wai-aria-1.1/#dfn-hidden
 * https://www.w3.org/TR/html5/editing.html#the-hidden-attribute
 *
 * disabled
 * https://www.w3.org/TR/wai-aria-1.1/#aria-disabled
 * https://www.w3.org/TR/html5/forms.html#attr-fe-disabled
 *
 * events
 * https://www.w3.org/TR/dom/#events
 */

Object.defineProperty(Element.prototype, 'instance', {
    enumerable : true,
    writable : true,
    value : null
});

const map = Array.prototype.map;

export default class Instance {
    /**
     * The base instance from which all other instances in this taxonomy inherit
     * @param {Element} element root element node
     */
    constructor(element) {
        element.instance = this;
        this.element = element;
    }

    /**
     * Get unique identifier
     * @returns {String}
     */
    get id() {
        return this.element.id || '';
    }

    /**
     * Get hidden state
     * @returns {String}
     */
    get hidden() {
        return String(this.element.hidden);
    }

    /**
     * Set hidden state
     * @param {String} hidden state
     */
    set hidden(hidden) {
        this.element.hidden = hidden === 'true';
    }

    /**
     * Get disabled state
     * @returns {String}
     */
    get disabled() {
        return this.element.getAttribute('aria-disabled') || 'false';
    }

    /**
     * Set disabled state
     * @param {String} disabled state
     */
    set disabled(disabled) {
        this.element.setAttribute('aria-disabled', disabled);
    }

    /**
     * Add event listener
     * @param {String} type event type
     * @param {Function} listener event listener
     * @param {Object} [context] event listener context
     * @returns {Instance} this
     */
    on(type, listener, context) {
        this.element.addEventListener(type, listener.bind(context || this));
        return this;
    }

    /**
     * Dispatch an event
     * @param {String} type event type;
     * @returns {Instance} this
     */
    emit(type) {
        this.element.dispatchEvent(new Event(type, { bubbles : true, cancelable : true }));
        return this;
    }

    /**
     * Find the first descendant instance of the specified class
     * @param {Instance} Class target instance class
     * @param {Function} [filter] function
     * @returns {Instance|null}
     */
    find(Class, filter) {
        return filter?
            this.findAll(Class, filter)[0] || null :
            Class.getInstance(this.element.querySelector(`[data-instance=${Class.name}]`));
    }

    /**
     * Find all descendant instances of the specified class
     * @param {Instance} Class target instance class
     * @param {Function} [filter] function
     * @returns {Array} array of found instances
     */
    findAll(Class, filter) {
        const result = map.call(
            this.element.querySelectorAll(`[data-instance=${Class.name}]`),
            element => Class.getInstance(element));
        return filter? result.filter(filter) : result;
    }

    /**
     * Find the nearest ancestor instance of the specified class
     * @param {Instance} Class target instance class
     * @param {Function} [filter] function
     * @returns {Instance} found instance
     */
    closest(Class, filter) {
        let instance = this;
        do instance = Class.getInstance(instance.element.parentElement.closest(`[data-instance=${Class.name}]`));
        while(instance && filter && !filter(instance));
        return instance;
    }

    /**
     * Create if needed and return the instance of the specified element
     * @param {Element} element root element node of target instance
     * @returns {Instance|null}
     */
    static getInstance(element) {
        return element && element.dataset && element.dataset.instance === this.name?
            element.instance || new this(element) :
            null;
    }

    /**
     * Create if needed and return the nearest ancestor instance of the specified element
     * @param {Element} element node inside target instance
     * @returns {Instance|null}
     */
    static closestInstance(element) {
        return this.getInstance(element.closest(`[data-instance=${this.name}]`));
    }

    /**
     * Delegate an event listener to the document node
     * @param {String} type event type
     * @param {Function} listener event listener
     * @param {Object} [context] event listener context
     */
    static on(type, listener, context) {
        document.addEventListener(type, event => {
            const instance = (context || this).closestInstance(event.target);
            if(instance) listener.call(instance, event);
        }, true);
    }
}
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var logger = require('koa-logger');
var route = require('koa-route');
var koa = require('koa');
var serve = require('koa-static');
var app = module.exports = koa();
var routes = require('./routes.js');
// var bibTex = require('bibTex');

// middleware
app.use(logger());

// route middleware
app.use(route.get('/', routes.list));
app.use(route.get('/paper/new', routes.add));
app.use(route.get('/paper/:id', routes.show));
app.use(route.post('/paper', routes.create));
app.use(route.post('/search', routes.search));
app.use(route.post('/paper/:id', routes.update));
// app.use(route.get('/paper/:id/edit', routes.edit));
app.use(route.get('/paper/:id/delete', routes.remove));
app.use(route.get('/paper/:id/download', routes.download));
// setInterval(bibTex.reset, 600000);

//file dir
app.use(serve(__dirname + '/lib'));
app.use(serve(__dirname + '/paper'));

// listen
app.listen(3000);
console.log('listening on port 3000');

<commit_msg>move to 8080<commit_after>
/**
 * Module dependencies.
 */

var logger = require('koa-logger');
var route = require('koa-route');
var koa = require('koa');
var serve = require('koa-static');
var app = module.exports = koa();
var routes = require('./routes.js');
// var bibTex = require('bibTex');

// middleware
app.use(logger());

// route middleware
app.use(route.get('/', routes.list));
app.use(route.get('/paper/new', routes.add));
app.use(route.get('/paper/:id', routes.show));
app.use(route.post('/paper', routes.create));
app.use(route.post('/search', routes.search));
app.use(route.post('/paper/:id', routes.update));
// app.use(route.get('/paper/:id/edit', routes.edit));
app.use(route.get('/paper/:id/delete', routes.remove));
app.use(route.get('/paper/:id/download', routes.download));
// setInterval(bibTex.reset, 600000);

//file dir
app.use(serve(__dirname + '/lib'));
app.use(serve(__dirname + '/paper'));

// listen
app.listen(8080);
console.log('listening on port 8080');

<|endoftext|>


<commit_before>window.poma = (function() {
  'use strict';

  var poma = function() {}

  var _metafunc = function(node) {
    return (node instanceof Node) ? '_execute' : '_executes'
  }

  poma._execute = function(node, fn) {
    var args = [].slice.call(arguments, 2)
    node[fn].apply(node, args)
    return node
  }

  poma._executes = function(nodes, fn) {
    var args = [].slice.call(arguments, 2)
    for (var i = 0, len = nodes.length; i < len; i += 1) {
      nodes[i][fn].apply(nodes[i], args)
    }
    return nodes
  }

// ## PUBLIC ##

  poma.on = function(node, type, fn) {
    var f = _metafunc(node)
    return poma[f](node, 'addEventListener', type, fn, false)
  }

  poma.off = function(node, type, fn) {
    var f = _metafunc(node)
    return poma[f](node, 'removeEventListener', type, fn, false)
  }

  poma.once = function(node, type, fn) {
    var handler = function(e) {
      poma.off(node, type, handler)
      fn(e)
    }
    poma.on(node, type, handler)
    return node
  }

  poma.event = function(type, data) {
    var e = document.createEvent('HTMLEvents')
    e.initEvent(type, true, true)
    e.eventName = type
    e.data = data || {}
    return e
  }

  poma.trigger = function(node, type, data) {
    var e = (typeof type === 'string') ? poma.event(type, data) : type
    var f = _metafunc(node)
    return poma[f](node, 'dispatchEvent', e)
  }

  poma.matches = (function() {
    var b = document.body
    return b.matches || b.webkitMatchesSelector || b.mozMatchesSelector || b.msMatchesSelector
  })();

  poma.parentSelector = function(node, selector) {
    node = node.parentNode
    while (node && node !== document) {
      if (poma.matches.bind(node)(selector)) {
        return node
      } else {
        node = node.parentNode
      }
    }
    return false
  }

  poma.parentSelectorAll = function(node, selector) {
    var nodes = []
    node = node.parentNode
    while (node !== document) {
      if (poma.matches.bind(node)(selector)) {
        nodes.push(node)
      }
      node = node.parentNode
    }
    return (nodes.length) ? nodes : false
  }

  poma.remove = function(node) {
    return node.parentNode.removeChild(node)
  }

  poma.insertAfter = function(node, target) {
    var parent = target.parentNode
    if (parent.lastchild === target) {
      return parent.appendChild(node)
    } else {
      return parent.insertBefore(node, target.nextSibling)
    }
  }

  poma.plugin = function(object, fn) {
    if (typeof poma[fn] === 'function')
      return console.error('The "' + fn + '" function already exists on poma');
    poma[fn] = object[fn]
    return poma[fn]
  }

  return poma

})();

<commit_msg>Remove else condition and just return the result<commit_after>window.poma = (function() {
  'use strict';

  var poma = function() {}

  var _metafunc = function(node) {
    return (node instanceof Node) ? '_execute' : '_executes'
  }

  poma._execute = function(node, fn) {
    var args = [].slice.call(arguments, 2)
    node[fn].apply(node, args)
    return node
  }

  poma._executes = function(nodes, fn) {
    var args = [].slice.call(arguments, 2)
    for (var i = 0, len = nodes.length; i < len; i += 1) {
      nodes[i][fn].apply(nodes[i], args)
    }
    return nodes
  }

// ## PUBLIC ##

  poma.on = function(node, type, fn) {
    var f = _metafunc(node)
    return poma[f](node, 'addEventListener', type, fn, false)
  }

  poma.off = function(node, type, fn) {
    var f = _metafunc(node)
    return poma[f](node, 'removeEventListener', type, fn, false)
  }

  poma.once = function(node, type, fn) {
    var handler = function(e) {
      poma.off(node, type, handler)
      fn(e)
    }
    poma.on(node, type, handler)
    return node
  }

  poma.event = function(type, data) {
    var e = document.createEvent('HTMLEvents')
    e.initEvent(type, true, true)
    e.eventName = type
    e.data = data || {}
    return e
  }

  poma.trigger = function(node, type, data) {
    var e = (typeof type === 'string') ? poma.event(type, data) : type
    var f = _metafunc(node)
    return poma[f](node, 'dispatchEvent', e)
  }

  poma.matches = (function() {
    var b = document.body
    return b.matches || b.webkitMatchesSelector || b.mozMatchesSelector || b.msMatchesSelector
  })();

  poma.parentSelector = function(node, selector) {
    node = node.parentNode
    while (node && node !== document) {
      if (poma.matches.bind(node)(selector)) {
        return node
      } else {
        node = node.parentNode
      }
    }
    return false
  }

  poma.parentSelectorAll = function(node, selector) {
    var nodes = []
    node = node.parentNode
    while (node !== document) {
      if (poma.matches.bind(node)(selector)) {
        nodes.push(node)
      }
      node = node.parentNode
    }
    return (nodes.length) ? nodes : false
  }

  poma.remove = function(node) {
    return node.parentNode.removeChild(node)
  }

  poma.insertAfter = function(node, target) {
    var parent = target.parentNode
    if (parent.lastchild === target) {
      return parent.appendChild(node)
    }
    return parent.insertBefore(node, target.nextSibling)
  }

  poma.plugin = function(object, fn) {
    if (typeof poma[fn] === 'function')
      return console.error('The "' + fn + '" function already exists on poma');
    poma[fn] = object[fn]
    return poma[fn]
  }

  return poma

})();

<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import Unit from './Unit';
import { UnitStates } from '../constants/ActionTypes';

const UnitList = ({ onUnitClick, units }) => (

    {units.map((unitsColumn, index) =>
      <div className='row' key={ `row_${index}` } >
        {unitsColumn.map((unit, columnIndex) =>
            <Unit
              {...unit}
              key={ `unit_${index}_${columnIndex}` }
              onClick={() => onUnitClick(unit.id, UnitStates.YOUNG)}
            />
        )}

    )}

)

UnitList.propTypes = {
  onUnitClick: PropTypes.func.isRequired,
  units: PropTypes.arrayOf(
    PropTypes.arrayOf(
      PropTypes.shape({
        id: PropTypes.number.isRequired,
        state: PropTypes.string.isRequired
      }).isRequired
    ).isRequired
  ).isRequired
}

export default UnitList;
<commit_msg>Add attr actions to UnitList.propTypes. Repalce UnitClick with actions.upateUnitState.<commit_after>import React, { Component, PropTypes } from 'react';
import Unit from './Unit';
import { UnitStates } from '../constants/ActionTypes';

const UnitList = ({ units, actions }) => (

    {units.map((unitsColumn, index) =>
      <div className='row' key={ `row_${index}` } >
        {unitsColumn.map((unit, columnIndex) =>
            <Unit
              {...unit}
              key={ `unit_${index}_${columnIndex}` }
              actions={actions}
              onClick={() => actions.updateUnitState(unit.id, UnitStates.YOUNG)}
            />
        )}

    )}

)

UnitList.propTypes = {
  actions: PropTypes.object.isRequired,
  units: PropTypes.arrayOf(
    PropTypes.arrayOf(
      PropTypes.shape({
        id: PropTypes.number.isRequired,
        state: PropTypes.string.isRequired
      }).isRequired
    ).isRequired
  ).isRequired
}

export default UnitList;
<|endoftext|>