<commit_before>var falafel = require('falafel')
var duplexify = require('duplexify')
var through = require('through2')
var concat = require('concat-stream')
var from = require('from2')
var gdeps = require('glslify-deps')
var glslBundle = require('glslify-bundle')
var path = require('path')
var seval = require('static-eval')
var resolve = require('resolve')
var gresolve = require('glsl-resolve')
var extend = require('xtend')

var glslfile0 = path.join(__dirname,'index.js')
var glslfile1 = path.join(__dirname,'index')
var parseOptions = {
  ecmaVersion: 10,
  sourceType: 'module',
  allowReturnOutsideFunction: true,
  allowImportExportEverywhere: true,
  allowHashBang: true
}

module.exports = function (file, opts) {
  if (path.extname(file) == '.json') return through()
  if (!opts) opts = {}
  var dir = path.dirname(file)
  var glvar = null, mdir = dir
  var evars = {
    __dirname: dir,
    __filename: file,
    require: { resolve: resolve }
  }

  var sharedPosts = []
  var sharedTransforms = updateSharedTransforms()

  function evaluate (expr) {
    return seval(expr, evars)
  }

  function updateSharedTransforms () {
    ;[]
      .concat(opts.post || [])
      .concat(opts.p || [])
      .forEach(function (post) {
        post = Array.isArray(post) ? post : [post]
        var name = post[0]
        var opts = post[1] || {}
        sharedPosts.push({ name: name, opts: opts, base: process.cwd() })
      })

    return []
      .concat(opts.transform || [])
      .concat(opts.t || [])
      .filter(function (tr) {
        var name = tr[0]
        var opts = tr[1] || {}
        if (!opts.post) return true
        sharedPosts.push({ name: name, opts: opts, base: process.cwd() })
      })
  }

  var d = duplexify()
  var out = from(function () {})
  d.setReadable(out)
  d.setWritable(concat({ encoding: 'string' }, function (src) {
    var pending = 1
    if (src.indexOf('glslify') === -1) {
      out.push(src)
      out.push(null)
      return
    }

    try { var fout = falafel(src, parseOptions, onnode) }
    catch (err) { return d.emit('error', err) }
    done()

    function onnode (node) {
      // case: path = require('path')
      if (isRequirePath(node)) {
        evars.path = path
      } else if (isRequireGlslify(node, dir)) {
        var p = node.parent.parent, pp = p.parent
        if (isReqCallExpression(p, pp)) {
          // case: require('glslify')(...)
          pending++
          callexpr(p, done)
        } else if (p.type === 'VariableDeclarator') {
          // case: var glvar = require('glslify')
          glvar = p.id.name
        } else if (isReqCallFile(p, pp)) {
          // case: require('glslify').file(...)
          pending++
          callfile(pp, pp.callee.object.source(), done)
        } else if (isReqCallCompile(p, pp)) {
          // case: require('glslify').compile(...)
          pending++
          rcallcompile(pp, done)
        } else if (p.type === 'TaggedTemplateExpression') {
          // case: require('glslify')`...`
          pending++
          tagexpr(p, done)
        }
      } else if (isCallExpression(node, glvar)) {
        // case: glvar(...)
        pending++
        callexpr(node.parent, done)
      } else if (isTagExpression(node, glvar)) {
        // case: glvar`...`
        pending++
        tagexpr(node, done)
      } else if (isCallFile(node, glvar)) {
        // case: glvar.file(...)
        pending++
        callfile(node.parent.parent, glvar, done)
      } else if (isCallCompile(node, glvar)) {
        // case: glvar.compile(...)
        pending++
        callcompile(node.parent.parent, done)
      }
    }

    function tagexpr (node, cb) {
      var q = node.quasi
      var shadersrc = q.quasis.map(function (s) {
        return s.value.raw + '__GLX_PLACEHOLDER__'
      }).join('')
      var d = createDeps({ cwd: mdir })
      d.inline(shadersrc, mdir, function (err, deps) {
        if (err) return d.emit('error', err)
        applyPostTransforms(null, deps, {}, function (err, bsrc) {
          if (err) return d.emit('error', err)
          node.update(node.tag.source() + '('
            + JSON.stringify(bsrc.split('__GLX_PLACEHOLDER__'))
            + [''].concat(q.expressions.map(function (e) {
              return e.source()
            })).join(',')
            + ')')
          cb()
        })
      })
    }
    function callexpr (p, cb) {
      var marg = evaluate(p.arguments[0])
      var mopts = p.arguments[1] ? evaluate(p.arguments[1]) || {} : {}
      var d = createDeps({ cwd: mdir })
      var resolved = null
      if (/(void\s+main\s?\(.*\)|\n)/.test(marg)) { // source string
        d.inline(marg, mdir, ondeps)
      } else gresolve(marg, { basedir: mdir }, function (err, res) {
        if (err) d.emit('error', err)
        else d.add(resolved = res, ondeps)
      })
      function ondeps (err, deps) {
        if (err) return d.emit('error', err)
        applyPostTransforms(resolved, deps, mopts, function (err, bsrc) {
          if (err) return d.emit('error', err)
          p.update(p.callee.source()+'(['+JSON.stringify(bsrc)+'])')
          cb()
        })
      }
    }
    function callcompile (p, cb) {
      var mfile = p.arguments[0].value
      var mopts = p.arguments[1] ? evaluate(p.arguments[1]) || {} : {}
      var d = createDeps({ cwd: mdir })
      d.inline(mfile, mdir, ondeps)
      function ondeps (err, deps) {
        if (err) return d.emit('error', err)
        applyPostTransforms(null, deps, mopts, function (err, bsrc) {
          if (err) return d.emit('error', err)
          p.update(glvar + '([' + JSON.stringify(bsrc) + '])')
          cb()
        })
      }
    }
    function callfile (p, glvar, cb) {
      var mfile = evaluate(p.arguments[0])
      gresolve(mfile, { basedir: mdir }, function (err, res) {
        if (err) return d.emit('error', err)
        var mopts = p.arguments[1] ? evaluate(p.arguments[1]) || {} : {}
        var d = createDeps({ cwd: path.dirname(res) })
        d.add(res, ondeps)
        function ondeps (err, deps) {
          if (err) return d.emit('error', err)
          applyPostTransforms(res, deps, mopts, function (err, bsrc) {
            if (err) return d.emit('error', err)
            p.update(glvar + '([' + JSON.stringify(bsrc) + '])')
            cb()
          })
        }
      })
    }
    function rcallcompile (p, cb) {
      var marg = evaluate(p.arguments[0])
      var mopts = p.arguments[1] ? evaluate(p.arguments[1]) || {} : {}
      var d = createDeps({ cwd: mdir })
      d.inline(marg, mdir, ondeps)
      function ondeps (err, deps) {
        if (err) return d.emit('error', err)
        applyPostTransforms(null, deps, mopts, function (err, bsrc) {
          if (err) return d.emit('error', err)
          p.update(p.callee.object.source()+'(['+JSON.stringify(bsrc)+'])')
          cb()
        })
      }
    }
    function done () {
      if (--pending === 0) {
        out.push(fout.toString())
        out.push(null)
      }
    }
  }))
  return d

  function createDeps (opts) {
    var depper = gdeps(opts)
    depper.on('error', function (err) { d.emit('error', err) })
    depper.on('file', function (file) { d.emit('file', file) })
    var transforms = sharedTransforms
    transforms = Array.isArray(transforms) ? transforms : [transforms]
    transforms.forEach(function(transform) {
      transform = Array.isArray(transform) ? transform : [transform]
      var name = transform[0]
      var opts = transform[1] || {}
      if (!opts.post) {
        depper.transform(name, extend({}, opts))
      }
    })
    return depper
  }

  function applyPostTransforms (rootFile, deps, mopts, done) {
    var source = glslBundle(deps)
    var localPosts = [].concat(mopts.transform || []).concat(mopts.t || [])
      .map(function (transform) {
        transform = Array.isArray(transform) ? transform : [transform]
        var name = transform[0]
        var opts = transform[1] || {}
        return opts.post && { name: name, opts: opts, base: path.dirname(rootFile) }
      })
      .filter(Boolean)
      .concat(sharedPosts)
      .map(function (tr) {
        if (typeof tr.name === "function") {
          tr.tr = tr.name
        } else {
          var target = resolve.sync(tr.name, { basedir: tr.base || mdir })
          tr.tr = require(target)
        }
        return tr
      })

    gdeps.prototype.applyTransforms(rootFile, source, localPosts, done);
  }
}

function isRequirePath (node) {
  return node.type === 'Identifier' && node.name === 'require'
    && node.parent.type === 'CallExpression'
    && node.parent.arguments[0]
    && node.parent.arguments[0].type === 'Literal'
    && node.parent.arguments[0].value === 'path'
    && node.parent.parent.type === 'VariableDeclarator'
}

function isRequireGlslify (node, dir) {
  return node.type === 'Identifier' && node.name === 'require'
    && node.parent.type === 'CallExpression'
    && node.parent.arguments[0]
    && node.parent.arguments[0].type === 'Literal'
    && (/^glslify(?:\/index(?:\.js)?)?/.test(node.parent.arguments[0].value)
    || path.resolve(dir,node.parent.arguments[0].value) === __dirname
    || path.resolve(dir,node.parent.arguments[0].value) === glslfile0
    || path.resolve(dir,node.parent.arguments[0].value) === glslfile1)
}

function isReqCallExpression (node, parent) {
  return node.type === 'CallExpression'
    && parent.type === 'CallExpression'
}

function isReqCallFile (node, parent) {
  return node.type === 'MemberExpression'
    && node.property.name === 'file'
    && parent.type === 'CallExpression'
}

function isReqCallCompile (node, parent) {
  return node.type === 'MemberExpression'
    && node.property.name === 'compile'
    && parent.type === 'CallExpression'
}

function isCallExpression (node, glvar) {
  return node.type === 'Identifier'
    && node.name === glvar
    && node.parent.type === 'CallExpression'
}

function isTagExpression (node, glvar) {
  return node.type === 'TaggedTemplateExpression'
    && node.tag.name === glvar
}

function isCallFile (node, glvar) {
  return node.type === 'Identifier' && node.name === glvar
    && node.parent.type === 'MemberExpression'
    && node.parent.property.name === 'file'
    && node.parent.parent.type === 'CallExpression'
    && node.parent.parent.arguments[0]
}

function isCallCompile (node, glvar) {
  return node.type === 'Identifier' && node.name === glvar
    && node.parent.type === 'MemberExpression'
    && node.parent.property.name === 'compile'
    && node.parent.parent.type === 'CallExpression'
    && node.parent.parent.arguments[0]
}
<commit_msg>dedupe callcompile/rcallcompile for cleanliness<commit_after>var falafel = require('falafel')
var duplexify = require('duplexify')
var through = require('through2')
var concat = require('concat-stream')
var from = require('from2')
var gdeps = require('glslify-deps')
var glslBundle = require('glslify-bundle')
var path = require('path')
var seval = require('static-eval')
var resolve = require('resolve')
var gresolve = require('glsl-resolve')
var extend = require('xtend')

var glslfile0 = path.join(__dirname,'index.js')
var glslfile1 = path.join(__dirname,'index')
var parseOptions = {
  ecmaVersion: 10,
  sourceType: 'module',
  allowReturnOutsideFunction: true,
  allowImportExportEverywhere: true,
  allowHashBang: true
}

module.exports = function (file, opts) {
  if (path.extname(file) == '.json') return through()
  if (!opts) opts = {}
  var dir = path.dirname(file)
  var glvar = null, mdir = dir
  var evars = {
    __dirname: dir,
    __filename: file,
    require: { resolve: resolve }
  }

  var sharedPosts = []
  var sharedTransforms = updateSharedTransforms()

  function evaluate (expr) {
    return seval(expr, evars)
  }

  function updateSharedTransforms () {
    ;[]
      .concat(opts.post || [])
      .concat(opts.p || [])
      .forEach(function (post) {
        post = Array.isArray(post) ? post : [post]
        var name = post[0]
        var opts = post[1] || {}
        sharedPosts.push({ name: name, opts: opts, base: process.cwd() })
      })

    return []
      .concat(opts.transform || [])
      .concat(opts.t || [])
      .filter(function (tr) {
        var name = tr[0]
        var opts = tr[1] || {}
        if (!opts.post) return true
        sharedPosts.push({ name: name, opts: opts, base: process.cwd() })
      })
  }

  var d = duplexify()
  var out = from(function () {})
  d.setReadable(out)
  d.setWritable(concat({ encoding: 'string' }, function (src) {
    var pending = 1
    if (src.indexOf('glslify') === -1) {
      out.push(src)
      out.push(null)
      return
    }

    try { var fout = falafel(src, parseOptions, onnode) }
    catch (err) { return d.emit('error', err) }
    done()

    function onnode (node) {
      // case: path = require('path')
      if (isRequirePath(node)) {
        evars.path = path
      } else if (isRequireGlslify(node, dir)) {
        var p = node.parent.parent, pp = p.parent
        if (isReqCallExpression(p, pp)) {
          // case: require('glslify')(...)
          pending++
          callexpr(p, done)
        } else if (p.type === 'VariableDeclarator') {
          // case: var glvar = require('glslify')
          glvar = p.id.name
        } else if (isReqCallFile(p, pp)) {
          // case: require('glslify').file(...)
          pending++
          callfile(pp, pp.callee.object.source(), done)
        } else if (isReqCallCompile(p, pp)) {
          // case: require('glslify').compile(...)
          pending++
          callcompile(pp, pp.callee.object.source(), done)
        } else if (p.type === 'TaggedTemplateExpression') {
          // case: require('glslify')`...`
          pending++
          tagexpr(p, done)
        }
      } else if (isCallExpression(node, glvar)) {
        // case: glvar(...)
        pending++
        callexpr(node.parent, done)
      } else if (isTagExpression(node, glvar)) {
        // case: glvar`...`
        pending++
        tagexpr(node, done)
      } else if (isCallFile(node, glvar)) {
        // case: glvar.file(...)
        pending++
        callfile(node.parent.parent, glvar, done)
      } else if (isCallCompile(node, glvar)) {
        // case: glvar.compile(...)
        pending++
        callcompile(node.parent.parent, glvar, done)
      }
    }

    function tagexpr (node, cb) {
      var q = node.quasi
      var shadersrc = q.quasis.map(function (s) {
        return s.value.raw + '__GLX_PLACEHOLDER__'
      }).join('')
      var d = createDeps({ cwd: mdir })
      d.inline(shadersrc, mdir, function (err, deps) {
        if (err) return d.emit('error', err)
        applyPostTransforms(null, deps, {}, function (err, bsrc) {
          if (err) return d.emit('error', err)
          node.update(node.tag.source() + '('
            + JSON.stringify(bsrc.split('__GLX_PLACEHOLDER__'))
            + [''].concat(q.expressions.map(function (e) {
              return e.source()
            })).join(',')
            + ')')
          cb()
        })
      })
    }
    function callexpr (p, cb) {
      var marg = evaluate(p.arguments[0])
      var mopts = p.arguments[1] ? evaluate(p.arguments[1]) || {} : {}
      var d = createDeps({ cwd: mdir })
      var resolved = null
      if (/(void\s+main\s?\(.*\)|\n)/.test(marg)) { // source string
        d.inline(marg, mdir, ondeps)
      } else gresolve(marg, { basedir: mdir }, function (err, res) {
        if (err) d.emit('error', err)
        else d.add(resolved = res, ondeps)
      })
      function ondeps (err, deps) {
        if (err) return d.emit('error', err)
        applyPostTransforms(resolved, deps, mopts, function (err, bsrc) {
          if (err) return d.emit('error', err)
          p.update(p.callee.source()+'(['+JSON.stringify(bsrc)+'])')
          cb()
        })
      }
    }
    function callcompile (p, glvar, cb) {
      var mfile = evaluate(p.arguments[0])
      var mopts = p.arguments[1] ? evaluate(p.arguments[1]) || {} : {}
      var d = createDeps({ cwd: mdir })
      d.inline(mfile, mdir, ondeps)
      function ondeps (err, deps) {
        if (err) return d.emit('error', err)
        applyPostTransforms(null, deps, mopts, function (err, bsrc) {
          if (err) return d.emit('error', err)
          p.update(glvar + '([' + JSON.stringify(bsrc) + '])')
          cb()
        })
      }
    }
    function callfile (p, glvar, cb) {
      var mfile = evaluate(p.arguments[0])
      gresolve(mfile, { basedir: mdir }, function (err, res) {
        if (err) return d.emit('error', err)
        var mopts = p.arguments[1] ? evaluate(p.arguments[1]) || {} : {}
        var d = createDeps({ cwd: path.dirname(res) })
        d.add(res, ondeps)
        function ondeps (err, deps) {
          if (err) return d.emit('error', err)
          applyPostTransforms(res, deps, mopts, function (err, bsrc) {
            if (err) return d.emit('error', err)
            p.update(glvar + '([' + JSON.stringify(bsrc) + '])')
            cb()
          })
        }
      })
    }
    function done () {
      if (--pending === 0) {
        out.push(fout.toString())
        out.push(null)
      }
    }
  }))
  return d

  function createDeps (opts) {
    var depper = gdeps(opts)
    depper.on('error', function (err) { d.emit('error', err) })
    depper.on('file', function (file) { d.emit('file', file) })
    var transforms = sharedTransforms
    transforms = Array.isArray(transforms) ? transforms : [transforms]
    transforms.forEach(function(transform) {
      transform = Array.isArray(transform) ? transform : [transform]
      var name = transform[0]
      var opts = transform[1] || {}
      if (!opts.post) {
        depper.transform(name, extend({}, opts))
      }
    })
    return depper
  }

  function applyPostTransforms (rootFile, deps, mopts, done) {
    var source = glslBundle(deps)
    var localPosts = [].concat(mopts.transform || []).concat(mopts.t || [])
      .map(function (transform) {
        transform = Array.isArray(transform) ? transform : [transform]
        var name = transform[0]
        var opts = transform[1] || {}
        return opts.post && { name: name, opts: opts, base: path.dirname(rootFile) }
      })
      .filter(Boolean)
      .concat(sharedPosts)
      .map(function (tr) {
        if (typeof tr.name === "function") {
          tr.tr = tr.name
        } else {
          var target = resolve.sync(tr.name, { basedir: tr.base || mdir })
          tr.tr = require(target)
        }
        return tr
      })

    gdeps.prototype.applyTransforms(rootFile, source, localPosts, done);
  }
}

function isRequirePath (node) {
  return node.type === 'Identifier' && node.name === 'require'
    && node.parent.type === 'CallExpression'
    && node.parent.arguments[0]
    && node.parent.arguments[0].type === 'Literal'
    && node.parent.arguments[0].value === 'path'
    && node.parent.parent.type === 'VariableDeclarator'
}

function isRequireGlslify (node, dir) {
  return node.type === 'Identifier' && node.name === 'require'
    && node.parent.type === 'CallExpression'
    && node.parent.arguments[0]
    && node.parent.arguments[0].type === 'Literal'
    && (/^glslify(?:\/index(?:\.js)?)?/.test(node.parent.arguments[0].value)
    || path.resolve(dir,node.parent.arguments[0].value) === __dirname
    || path.resolve(dir,node.parent.arguments[0].value) === glslfile0
    || path.resolve(dir,node.parent.arguments[0].value) === glslfile1)
}

function isReqCallExpression (node, parent) {
  return node.type === 'CallExpression'
    && parent.type === 'CallExpression'
}

function isReqCallFile (node, parent) {
  return node.type === 'MemberExpression'
    && node.property.name === 'file'
    && parent.type === 'CallExpression'
}

function isReqCallCompile (node, parent) {
  return node.type === 'MemberExpression'
    && node.property.name === 'compile'
    && parent.type === 'CallExpression'
}

function isCallExpression (node, glvar) {
  return node.type === 'Identifier'
    && node.name === glvar
    && node.parent.type === 'CallExpression'
}

function isTagExpression (node, glvar) {
  return node.type === 'TaggedTemplateExpression'
    && node.tag.name === glvar
}

function isCallFile (node, glvar) {
  return node.type === 'Identifier' && node.name === glvar
    && node.parent.type === 'MemberExpression'
    && node.parent.property.name === 'file'
    && node.parent.parent.type === 'CallExpression'
    && node.parent.parent.arguments[0]
}

function isCallCompile (node, glvar) {
  return node.type === 'Identifier' && node.name === glvar
    && node.parent.type === 'MemberExpression'
    && node.parent.property.name === 'compile'
    && node.parent.parent.type === 'CallExpression'
    && node.parent.parent.arguments[0]
}
<|endoftext|>


<commit_before>import React, {Component} from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { CookiesProvider } from 'react-cookie';
import { Router, Route } from 'react-router'

import createBrowserHistory from 'history/createBrowserHistory'
import injectTapEventPlugin from 'react-tap-event-plugin';

import App from './containers/App'
import store from './store'

import ReactGA from 'react-ga'

ReactGA.initialize('UA-71297148-1');

function logPageView() {
  ReactGA.set({ page: window.location.pathname + window.location.search });
  ReactGA.pageview(window.location.pathname + window.location.search);
}

console.log(store.getState())

let history = createBrowserHistory();

history.listen((location, action) => {
  console.log(`The current URL is ${location.pathname}${location.search}${location.hash}`)
  console.log(`The last navigation action was ${action}`)
})

// Needed for onTouchTap
// http://stackoverflow.com/a/34015469/988941
injectTapEventPlugin();

// listen to storage event
window.addEventListener('storage', function(event){
    // do what you want on logout-event
    if (event.key === 'login-event') {
      window.location.reload()
      // window.location = "logout.php";
    }
}, false);

class UviApp extends Component {
  render() {
    logPageView();
    return (<Provider store={store}>
      <CookiesProvider>
        <Router history={history} onUpdate={logPageView}>

             <Route path="/" component={App}/>

        </Router>
      </CookiesProvider>
    </Provider>);
  }
}

render(<UviApp />, document.getElementById('root'));

<commit_msg>Added grid css.<commit_after>import React, {Component} from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { CookiesProvider } from 'react-cookie';
import { Router, Route } from 'react-router'
import 'react-grid-layout/css/styles.css'

import createBrowserHistory from 'history/createBrowserHistory'
import injectTapEventPlugin from 'react-tap-event-plugin';

import App from './containers/App'
import store from './store'

import ReactGA from 'react-ga'

ReactGA.initialize('UA-71297148-1');

function logPageView() {
  ReactGA.set({ page: window.location.pathname + window.location.search });
  ReactGA.pageview(window.location.pathname + window.location.search);
}

console.log(store.getState())

let history = createBrowserHistory();

history.listen((location, action) => {
  console.log(`The current URL is ${location.pathname}${location.search}${location.hash}`)
  console.log(`The last navigation action was ${action}`)
})

// Needed for onTouchTap
// http://stackoverflow.com/a/34015469/988941
injectTapEventPlugin();

// listen to storage event
window.addEventListener('storage', function(event){
    // do what you want on logout-event
    if (event.key === 'login-event') {
      window.location.reload()
      // window.location = "logout.php";
    }
}, false);

class UviApp extends Component {
  render() {
    logPageView();
    return (<Provider store={store}>
      <CookiesProvider>
        <Router history={history} onUpdate={logPageView}>

             <Route path="/" component={App}/>

        </Router>
      </CookiesProvider>
    </Provider>);
  }
}

render(<UviApp />, document.getElementById('root'));

<|endoftext|>


<commit_before>import React from 'react';
import {Router, Link} from 'react-router';
import { connect } from 'react-redux';
import { MenuItem, LeftNav, Mixins, Styles, Avatar } from 'material-ui';
import ListDivider from 'material-ui/lib/lists/list-divider';
import List from 'material-ui/lib/lists/list';
import ListItem from 'material-ui/lib/lists/list-item';
import Payment from 'material-ui/lib/svg-icons/action/payment';
import Subject from 'material-ui/lib/svg-icons/action/subject';
import Settings from 'material-ui/lib/svg-icons/action/settings';
import PowerSettingsNew from 'material-ui/lib/svg-icons/action/power-settings-new';
import {SelectableContainerEnhance} from 'material-ui/lib/hoc/selectable-enhance';

const SelectableList = SelectableContainerEnhance(List);
let { Colors, Spacing, Typography } = Styles;
let { StylePropable } = Mixins;

let menuItems = [
    { route: '/posts', text: 'Posts' },
    { route: '/settings', text: 'Settings' },
    { route: '/logout', text: 'Logout' }
  ];

let AppLeftNav = React.createClass({

  contextTypes: {
    muiTheme: React.PropTypes.object,
    router: React.PropTypes.func,
  },

  getStyles() {
    return {
      cursor: 'pointer',
      //.mui-font-style-headline
      fontSize: '24px',
      color: Typography.textFullWhite,
      lineHeight: Spacing.desktopKeylineIncrement + 'px',
      fontWeight: Typography.fontWeightLight,
      //backgroundColor: Colors.cyan500,
      paddingTop: '10px',
      marginBottom: '8px',
      backgroundColor: 'rgba(0, 0, 0, 0.4)',
    };
  },

  getInitialState() {
    return {
      leftNavOpen: false,
    };
  },

  render() {
    const author = {
      id: this.props.userInfos.id,
      name: this.props.userInfos.name,
      location:this.props.userInfos.location,
      website:this.props.userInfos.blog,
      image:this.props.userInfos.avatar_url
    };

    let header = (

        <Avatar src={author.image} size={80} style={{display:'block',margin: '0 auto', border: 'solid 1px rgba(255,255, 255, 0.7)'}} />

{author.name}

    );

    let menus = (
      <SelectableList
          valueLink={{
            value: this.props.location.pathname,
            requestChange: this.handleRequestChangeList,
          }}
        >
          <ListItem
            value="/posts"
            primaryText="Posts"
            leftIcon={<Subject />}
          />
          <ListItem
            value="/settings"
            primaryText="Settings"
            leftIcon={<Settings />}
          />
          <ListItem
            value="/logout"
            primaryText="Logout"
            leftIcon={<PowerSettingsNew />}
          />
        </SelectableList>
    );

    return (
      <LeftNav
        ref="leftNav"
        docked={false}
        open={this.state.leftNavOpen}
        onRequestChange={this.handleChangeRequestLeftNav}
        >
        {header}
        {menus}
        <ListDivider />
        <SelectableList
            valueLink={{
              value: "",
              requestChange: this.handleRequestChangeLink,
            }}
          >
          <ListItem
            value="https://www.paypal.me/anthonny/5"
            primaryText="Donation PayPal"
            leftIcon={<Payment />}
          />
          <ListItem
            value="https://gratipay.com/hubpress/"
            primaryText="Donation Gratipay"
            leftIcon={<Payment />}
          />
        </SelectableList>

version {this.props.config.version}

      </LeftNav>
    );
  },

  toggle() {
    this.setState({
      leftNavOpen: !this.state.leftNavOpen,
    });
  },

  handleRequestChangeLink(event, value) {
    window.location = value;
  },

  handleRequestChangeList(e, value) {
    this.props.history.pushState(null, value);
    this.setState({
      leftNavOpen: false,
    });
  },

  handleChangeRequestLeftNav(open) {
    this.setState({
      leftNavOpen: open,
    });
  },

  _onHeaderClick() {
    this.props.history.pushState(null, '/');
    this.setState({
      leftNavOpen: false,
    });
  },

});

export default AppLeftNav;
<commit_msg>feat(admin): add upgrade link fix #12<commit_after>import React from 'react';
import {Router, Link} from 'react-router';
import { connect } from 'react-redux';
import { MenuItem, LeftNav, Mixins, Styles, Avatar } from 'material-ui';
import ListDivider from 'material-ui/lib/lists/list-divider';
import List from 'material-ui/lib/lists/list';
import ListItem from 'material-ui/lib/lists/list-item';
import Payment from 'material-ui/lib/svg-icons/action/payment';
import Update from 'material-ui/lib/svg-icons/action/update';
import Subject from 'material-ui/lib/svg-icons/action/subject';
import Settings from 'material-ui/lib/svg-icons/action/settings';
import PowerSettingsNew from 'material-ui/lib/svg-icons/action/power-settings-new';
import {SelectableContainerEnhance} from 'material-ui/lib/hoc/selectable-enhance';

const SelectableList = SelectableContainerEnhance(List);
let { Colors, Spacing, Typography } = Styles;
let { StylePropable } = Mixins;

let menuItems = [
    { route: '/posts', text: 'Posts' },
    { route: '/settings', text: 'Settings' },
    { route: '/logout', text: 'Logout' }
  ];

let AppLeftNav = React.createClass({

  contextTypes: {
    muiTheme: React.PropTypes.object,
    router: React.PropTypes.func,
  },

  getStyles() {
    return {
      cursor: 'pointer',
      //.mui-font-style-headline
      fontSize: '24px',
      color: Typography.textFullWhite,
      lineHeight: Spacing.desktopKeylineIncrement + 'px',
      fontWeight: Typography.fontWeightLight,
      //backgroundColor: Colors.cyan500,
      paddingTop: '10px',
      marginBottom: '8px',
      backgroundColor: 'rgba(0, 0, 0, 0.4)',
    };
  },

  getInitialState() {
    return {
      leftNavOpen: false,
    };
  },

  render() {
    const author = {
      id: this.props.userInfos.id,
      name: this.props.userInfos.name,
      location:this.props.userInfos.location,
      website:this.props.userInfos.blog,
      image:this.props.userInfos.avatar_url
    };

    let header = (

        <Avatar src={author.image} size={80} style={{display:'block',margin: '0 auto', border: 'solid 1px rgba(255,255, 255, 0.7)'}} />

{author.name}

    );

    let menus = (
      <SelectableList
          valueLink={{
            value: this.props.location.pathname,
            requestChange: this.handleRequestChangeList,
          }}
        >
          <ListItem
            value="/posts"
            primaryText="Posts"
            leftIcon={<Subject />}
          />
          <ListItem
            value="/settings"
            primaryText="Settings"
            leftIcon={<Settings />}
          />
          <ListItem
            value="/logout"
            primaryText="Logout"
            leftIcon={<PowerSettingsNew />}
          />
        </SelectableList>
    );

    return (
      <LeftNav
        ref="leftNav"
        docked={false}
        open={this.state.leftNavOpen}
        onRequestChange={this.handleChangeRequestLeftNav}
        >
        {header}
        {menus}
        <ListDivider />
        <SelectableList
            valueLink={{
              value: "",
              requestChange: this.handleRequestChangeLink,
            }}
          >
          <ListItem
            value="https://www.paypal.me/anthonny/5"
            primaryText="Donation PayPal"
            leftIcon={<Payment />}
          />
          <ListItem
            value="https://gratipay.com/hubpress/"
            primaryText="Donation Gratipay"
            leftIcon={<Payment />}
          />
        </SelectableList>
        <ListDivider />
        <SelectableList
          valueLink={{
            value: "",
            requestChange: this.handleRequestChangeLink,
          }}
          >
          <ListItem
            value={`https://github.com/${this.props.config.meta.username}/${this.props.config.meta.repositoryName}/compare/${this.props.config.meta.branch}...HubPress:${this.props.config.meta.branch}`}
            primaryText="Check for upgrade"
            leftIcon={<Update />}
            />
        </SelectableList>

version {this.props.config.version}

      </LeftNav>
    );
  },

  toggle() {
    this.setState({
      leftNavOpen: !this.state.leftNavOpen,
    });
  },

  handleRequestChangeLink(event, value) {
    window.location = value;
  },

  handleRequestChangeList(e, value) {
    this.props.history.pushState(null, value);
    this.setState({
      leftNavOpen: false,
    });
  },

  handleChangeRequestLeftNav(open) {
    this.setState({
      leftNavOpen: open,
    });
  },

  _onHeaderClick() {
    this.props.history.pushState(null, '/');
    this.setState({
      leftNavOpen: false,
    });
  },

});

export default AppLeftNav;
<|endoftext|>


<commit_before>'use strict';

const vscode = require('vscode');
const request = require('request');
const copyPaste = require('copy-paste');
const open = require('open');
const Promise = require('bluebird');

let activate = (context) => {

  const baseUrl = 'https://api.cdnjs.com/libraries';
  const searchUrl = baseUrl + '?fields=version,description,homepage';
  const embedUrl = 'cdnjs.cloudflare.com/ajax/libs';
  const statusBarMessageTimeout = 5000; // milliseconds

  // Quote configuration values
  const quotes = {
    'single': "'",
    'double': '"'
  };
  const quoteDefault = "'";

  // Protocol configuration values
  const protocols = ['https://', 'http://', '//'];
  const protocolDefault = 'https://';

  // Set consistent status bar message using timeout with either promise or time in milliseconds
  let statusMessage = (text, promise) => {
    if (promise) {
      vscode.window.setStatusBarMessage("cdnjs: " + text, promise);
    } else {
      vscode.window.setStatusBarMessage("cdnjs: " + text, statusBarMessageTimeout);
    }
  }

  // Display search box and return input
  let showSearchInput = () => {

    return new Promise((resolve, reject) => {
      vscode.window.showInputBox({
        placeHolder: 'Search for a script or library. For example: jquery'
      }).then((value) => {

        // No search string was specified
        if (typeof(value) === 'undefined') {
          reject('No search string was specified');
          return false;
        }

        resolve(value);

      }, (err) => {
        reject(err);
      });
    });
  }

  // Perform search on cdnjs.com and return JSON results
  let search = (term) => {

    let promise = new Promise((resolve, reject) => {

      // Search cdnjs api
      request(searchUrl + '&search=' + term.trim(), (err, res, body) => {

        // Reject errors
        if (err) {
          reject(err);
          return false;
        }

        // Reject non-200 status code responses
        if (res.statusCode !== 200) {
          reject(body);
          return false;
        }

        body = JSON.parse(body);

        // Display error message if no results were found
        if (!body.results || body.results.length === 0) {
          vscode.window.showErrorMessage("No libraries were found by the search term: " + term);
          return false;
        }

        resolve(body.results);

      });
    });

    // Update Status Bar Message
    statusMessage("Searching for " + term, promise);
    return promise;
  }

  // Show picker of all libraries
  let showLibraryPicker = (results) => {

    // Build array of libraries
    let items = [];
    for (let result of results) {

      // Create QuickPickItem for library
      let item = {
        label: result.name,
        description: result.description,
        currentVersion: result.version,
        name: result.name
      };
      items.push(item);
    }

    // Update status bar message
    statusMessage('Found ' + items.length + ' libraries');

    return new Promise((resolve, reject) => {

      // Show QuickPick of search results
      vscode.window.showQuickPick(items, {
        placeHolder: 'Choose a library (found' + items.length + ' libraries)',
        matchOnDescription: true
      }).then((libraryName) => {

        // No library was chosen
        if (typeof(libraryName) === 'undefined') {
          reject('No library was chosen');
          return false;
        }

        resolve(libraryName);

      }, (err) => {
        reject(err);
      });

    });

  }

  // Get library data from cdnjs
  let getLibrary = (libraryName) => {

    let promise = new Promise((resolve, reject) => {

      // Request library versions
      request(baseUrl + '/' + libraryName, (err, res, body) => {

        // Reject errors
        if (err) {
          reject(err);
          return false;
        }

        // Reject non-200 status code responses
        if (res.statusCode !== 200) {
          reject(body);
          return false;
        }

        body = JSON.parse(body);

        // Display error message if no results were found
        if (body.length === 0) {
          vscode.window.showErrorMessage("The library " + libraryName + " was not found");
          return false;
        }

        resolve(body);
      });

    });

    // Update Status Bar Message
    statusMessage("Fetching data for " + libraryName, promise);
    return promise;
  }

  // Show library version picker
  let showLibraryVersionPicker = (library) => {

    return new Promise((resolve, reject) => {
      // Build array of library versions
      let items = [];
      for (let asset of library.assets) {

        // QuickPickItem for the library version
        let item = {
          label: asset.version,
          files: asset.files,
          version: asset.version,
          libraryName: library.name
        };

        // Add description if this is the current/latest/stable version
        if (asset.version === library.version) {
          item.description = 'current version';
        }
        items.push(item);
      }

      statusMessage('Found ' + items.length + ' versions');

      // Show QuickPick of library versions
      vscode.window.showQuickPick(items, {
        placeHolder: library.name
      }).then((asset) => {

        // No version was chosen
        if (typeof(asset) === 'undefined') {
          reject('No library version was chosen');
          return false;
        }

        resolve(asset);
      }, (err) => {
        reject(err);
      });
    });
  }

  // Show library version file picker
  let showFilePicker = (asset) => {

    return new Promise((resolve, reject) => {

      // Build array of files
      let items = [];
      for (let file of asset.files) {
        items.push(file);
      }

      statusMessage('Found ' + items.length + ' files');

      // Show QuickPick of asset files
      vscode.window.showQuickPick(items, {
        placeHolder: asset.libraryName + "/" + asset.version + "/"
      }).then((file) => {

        // No file was chosen
        if (typeof(file) === 'undefined') {
          reject('No library file was chosen');
          return false;
        }

        resolve(file);
      }, (err) => {
        reject(err);
      });

    });

  }

  // Show file action picker
  let showActionPicker = (chosen) => {

    return new Promise((resolve, reject) => {

      // Reject if any chosen file properties are missing
      if (!chosen.library || !chosen.version || !chosen.file) {
        reject('Missing file asset parameters');
        return false;
      }

      // Configuration
      const config = vscode.workspace.getConfiguration('cdnjs');

      // Determine the quote style from configuration
      const quote = quotes[config.get('quoteStyle', 'single')] || quoteDefault;

      // Determine url protocol
      const protocolConfig = config.get('protocol', protocolDefault);
      const protocol = protocols.indexOf(protocolConfig) >= 0 ? protocolConfig : protocolDefault;

      // Build the url for the file
      let url = protocol + embedUrl + '/' + chosen.library + '/' + chosen.version + '/' + chosen.file;

      // Arrays of actions
      let actions = [];
      let insertActions = [];
      let clipboardActions = [];

      // Determine file extension
      let fileExtension = chosen.file.split('.').pop();
      let tag = "";
      switch (fileExtension) {

        case 'js':
          // JavaScript
          tag = '<script src=' + quote + url + quote + '></script>';

          // Insert <script> tag into document action
          if (vscode.window.activeTextEditor) {
            insertActions.push({
              label: 'Insert <script> tag into document',
              callback: () => {
                insertText(tag);
              }
            });
          }

          // Copy <script> tag to clipboard action
          clipboardActions.push({
            label: 'Copy <script> tag to clipboard',
            callback: () => {
              copy(tag, '<script> tag copied to the clipboard');
            }
          });

          break;

        case 'css':
          // CSS
          tag = '<link rel=' + quote + 'stylesheet' + quote + ' href=' + quote + url + quote + '/>';

          // Insert <link> tag into document action
          if (vscode.window.activeTextEditor) {
            insertActions.push({
              label: 'Insert <link> tag into document',
              callback: () => {
                insertText(tag);
              }
            });
          }

          // Copy <link> tag to clipboard action
          clipboardActions.push({
            label: 'Copy <link> tag to clipboard',
            callback: () => {
              copy(tag, '<link> tag copied to the clipboard');
            }
          });

          break;

        default:
          break;
      }

      // Insert URL into document action
      if (vscode.window.activeTextEditor) {
        actions.push({
          label: 'Insert URL into document',
          callback: () => {
            insertText(url);
          }
        });
      }

      // Add other insert actions
      actions = actions.concat(insertActions);

      // Copy URL to clipboard action
      actions.push({
        label: 'Copy URL to clipboard',
        callback: () => {
          copy(url, 'URL copied to the clipboard');
        }
      });

      // Add other clipboard actions
      actions = actions.concat(clipboardActions);

      // Open URL in browser action
      actions.push({
        label: 'Open URL in default browser',
        callback: () => {
          open(url);
        }
      });

      return new Promise((resolve, reject) => {
        vscode.window.showQuickPick(actions, {
          placeHolder: url
        }).then((action) => {

          // No action was chosen
          if (typeof(action) === 'undefined') {
            reject('No action was chosen');
            return false;
          }

          // Execute action callback
          action.callback();

          resolve();
        }, (err) => {
          reject(err);
        });

      });

    });
  }

  // Insert text into active document at cursor positions
  let insertText = (text) => {

    let textEditor = vscode.window.activeTextEditor;

    // Ignore if no active TextEditor
    if (typeof(textEditor) === 'undefined') {
      return false;
    }

    // Get the active text document's uri
    let uri = textEditor.document.uri;

    // Create a new TextEdit for each selection
    let edits = [];
    for (let selection of textEditor.selections) {
      edits.push(vscode.TextEdit.insert(selection.active, text));
    }

    // New WorkspaceEdit
    let edit = new vscode.WorkspaceEdit();
    edit.set(uri, edits);

    // Applying the WorkspaceEdit
    vscode.workspace.applyEdit(edit)
      .then(() => {

        // Clear the selection
        textEditor.selection = new vscode.Selection(textEditor.selection.end, textEditor.selection.end);

      }, (err) => {
        reject(err);
      });

    return true;
  }

  // Copy text to clipboard and set statusBarMessage
  let copy = (text, message) => {
    copyPaste.copy(text, () => {
      if (message) {
        statusMessage(message);
      }
    });
  }

  let searchDisposable = vscode.commands.registerCommand('cdnjs.search', function() {

    // The chosen file
    let chosen = {};

    showSearchInput().then((value) => {

      return search(value);

    }).then((results) => {

      return showLibraryPicker(results);

    }).then((library) => {

      chosen.library = library.name;

      return getLibrary(library.name);

    }).then((library) => {

      return showLibraryVersionPicker(library);

    }).then((asset) => {

      chosen.version = asset.version;

      return showFilePicker(asset);

    }).then((file) => {

      chosen.file = file;

      return showActionPicker(chosen);

    }).catch((err) => {

      console.error(err);

    })

  });

  let recentLibrariesDisposable = vscode.commands.registerCommand('cdnjs.recentLibraries', function() {
    console.log('recentLibraries');
  });
}
exports.activate = activate;

let deactivate = () => {}
exports.deactivate = deactivate;<commit_msg>Removed defaults from getConfiguration<commit_after>'use strict';

const vscode = require('vscode');
const request = require('request');
const copyPaste = require('copy-paste');
const open = require('open');
const Promise = require('bluebird');

let activate = (context) => {

  const baseUrl = 'https://api.cdnjs.com/libraries';
  const searchUrl = baseUrl + '?fields=version,description,homepage';
  const embedUrl = 'cdnjs.cloudflare.com/ajax/libs';
  const statusBarMessageTimeout = 5000; // milliseconds

  // Quote configuration values
  const quotes = {
    'single': "'",
    'double': '"'
  };
  const quoteDefault = "'";

  // Protocol configuration values
  const protocols = ['https://', 'http://', '//'];
  const protocolDefault = 'https://';

  // Set consistent status bar message using timeout with either promise or time in milliseconds
  let statusMessage = (text, promise) => {
    if (promise) {
      vscode.window.setStatusBarMessage("cdnjs: " + text, promise);
    } else {
      vscode.window.setStatusBarMessage("cdnjs: " + text, statusBarMessageTimeout);
    }
  }

  // Display search box and return input
  let showSearchInput = () => {

    return new Promise((resolve, reject) => {
      vscode.window.showInputBox({
        placeHolder: 'Search for a script or library. For example: jquery'
      }).then((value) => {

        // No search string was specified
        if (typeof(value) === 'undefined') {
          reject('No search string was specified');
          return false;
        }

        resolve(value);

      }, (err) => {
        reject(err);
      });
    });
  }

  // Perform search on cdnjs.com and return JSON results
  let search = (term) => {

    let promise = new Promise((resolve, reject) => {

      // Search cdnjs api
      request(searchUrl + '&search=' + term.trim(), (err, res, body) => {

        // Reject errors
        if (err) {
          reject(err);
          return false;
        }

        // Reject non-200 status code responses
        if (res.statusCode !== 200) {
          reject(body);
          return false;
        }

        body = JSON.parse(body);

        // Display error message if no results were found
        if (!body.results || body.results.length === 0) {
          vscode.window.showErrorMessage("No libraries were found by the search term: " + term);
          return false;
        }

        resolve(body.results);

      });
    });

    // Update Status Bar Message
    statusMessage("Searching for " + term, promise);
    return promise;
  }

  // Show picker of all libraries
  let showLibraryPicker = (results) => {

    // Build array of libraries
    let items = [];
    for (let result of results) {

      // Create QuickPickItem for library
      let item = {
        label: result.name,
        description: result.description,
        currentVersion: result.version,
        name: result.name
      };
      items.push(item);
    }

    // Update status bar message
    statusMessage('Found ' + items.length + ' libraries');

    return new Promise((resolve, reject) => {

      // Show QuickPick of search results
      vscode.window.showQuickPick(items, {
        placeHolder: 'Choose a library (found' + items.length + ' libraries)',
        matchOnDescription: true
      }).then((libraryName) => {

        // No library was chosen
        if (typeof(libraryName) === 'undefined') {
          reject('No library was chosen');
          return false;
        }

        resolve(libraryName);

      }, (err) => {
        reject(err);
      });

    });

  }

  // Get library data from cdnjs
  let getLibrary = (libraryName) => {

    let promise = new Promise((resolve, reject) => {

      // Request library versions
      request(baseUrl + '/' + libraryName, (err, res, body) => {

        // Reject errors
        if (err) {
          reject(err);
          return false;
        }

        // Reject non-200 status code responses
        if (res.statusCode !== 200) {
          reject(body);
          return false;
        }

        body = JSON.parse(body);

        // Display error message if no results were found
        if (body.length === 0) {
          vscode.window.showErrorMessage("The library " + libraryName + " was not found");
          return false;
        }

        resolve(body);
      });

    });

    // Update Status Bar Message
    statusMessage("Fetching data for " + libraryName, promise);
    return promise;
  }

  // Show library version picker
  let showLibraryVersionPicker = (library) => {

    return new Promise((resolve, reject) => {
      // Build array of library versions
      let items = [];
      for (let asset of library.assets) {

        // QuickPickItem for the library version
        let item = {
          label: asset.version,
          files: asset.files,
          version: asset.version,
          libraryName: library.name
        };

        // Add description if this is the current/latest/stable version
        if (asset.version === library.version) {
          item.description = 'current version';
        }
        items.push(item);
      }

      statusMessage('Found ' + items.length + ' versions');

      // Show QuickPick of library versions
      vscode.window.showQuickPick(items, {
        placeHolder: library.name
      }).then((asset) => {

        // No version was chosen
        if (typeof(asset) === 'undefined') {
          reject('No library version was chosen');
          return false;
        }

        resolve(asset);
      }, (err) => {
        reject(err);
      });
    });
  }

  // Show library version file picker
  let showFilePicker = (asset) => {

    return new Promise((resolve, reject) => {

      // Build array of files
      let items = [];
      for (let file of asset.files) {
        items.push(file);
      }

      statusMessage('Found ' + items.length + ' files');

      // Show QuickPick of asset files
      vscode.window.showQuickPick(items, {
        placeHolder: asset.libraryName + "/" + asset.version + "/"
      }).then((file) => {

        // No file was chosen
        if (typeof(file) === 'undefined') {
          reject('No library file was chosen');
          return false;
        }

        resolve(file);
      }, (err) => {
        reject(err);
      });

    });

  }

  // Show file action picker
  let showActionPicker = (chosen) => {

    return new Promise((resolve, reject) => {

      // Reject if any chosen file properties are missing
      if (!chosen.library || !chosen.version || !chosen.file) {
        reject('Missing file asset parameters');
        return false;
      }

      // Configuration
      const config = vscode.workspace.getConfiguration('cdnjs');

      // Determine the quote style from configuration
      const quote = quotes[config.get('quoteStyle')] || quoteDefault;

      // Determine url protocol
      const protocolConfig = config.get('protocol');
      const protocol = protocols.indexOf(protocolConfig) >= 0 ? protocolConfig : protocolDefault;

      // Build the url for the file
      let url = protocol + embedUrl + '/' + chosen.library + '/' + chosen.version + '/' + chosen.file;

      // Arrays of actions
      let actions = [];
      let insertActions = [];
      let clipboardActions = [];

      // Determine file extension
      let fileExtension = chosen.file.split('.').pop();
      let tag = "";
      switch (fileExtension) {

        case 'js':
          // JavaScript
          tag = '<script src=' + quote + url + quote + '></script>';

          // Insert <script> tag into document action
          if (vscode.window.activeTextEditor) {
            insertActions.push({
              label: 'Insert <script> tag into document',
              callback: () => {
                insertText(tag);
              }
            });
          }

          // Copy <script> tag to clipboard action
          clipboardActions.push({
            label: 'Copy <script> tag to clipboard',
            callback: () => {
              copy(tag, '<script> tag copied to the clipboard');
            }
          });

          break;

        case 'css':
          // CSS
          tag = '<link rel=' + quote + 'stylesheet' + quote + ' href=' + quote + url + quote + '/>';

          // Insert <link> tag into document action
          if (vscode.window.activeTextEditor) {
            insertActions.push({
              label: 'Insert <link> tag into document',
              callback: () => {
                insertText(tag);
              }
            });
          }

          // Copy <link> tag to clipboard action
          clipboardActions.push({
            label: 'Copy <link> tag to clipboard',
            callback: () => {
              copy(tag, '<link> tag copied to the clipboard');
            }
          });

          break;

        default:
          break;
      }

      // Insert URL into document action
      if (vscode.window.activeTextEditor) {
        actions.push({
          label: 'Insert URL into document',
          callback: () => {
            insertText(url);
          }
        });
      }

      // Add other insert actions
      actions = actions.concat(insertActions);

      // Copy URL to clipboard action
      actions.push({
        label: 'Copy URL to clipboard',
        callback: () => {
          copy(url, 'URL copied to the clipboard');
        }
      });

      // Add other clipboard actions
      actions = actions.concat(clipboardActions);

      // Open URL in browser action
      actions.push({
        label: 'Open URL in default browser',
        callback: () => {
          open(url);
        }
      });

      return new Promise((resolve, reject) => {
        vscode.window.showQuickPick(actions, {
          placeHolder: url
        }).then((action) => {

          // No action was chosen
          if (typeof(action) === 'undefined') {
            reject('No action was chosen');
            return false;
          }

          // Execute action callback
          action.callback();

          resolve();
        }, (err) => {
          reject(err);
        });

      });

    });
  }

  // Insert text into active document at cursor positions
  let insertText = (text) => {

    let textEditor = vscode.window.activeTextEditor;

    // Ignore if no active TextEditor
    if (typeof(textEditor) === 'undefined') {
      return false;
    }

    // Get the active text document's uri
    let uri = textEditor.document.uri;

    // Create a new TextEdit for each selection
    let edits = [];
    for (let selection of textEditor.selections) {
      edits.push(vscode.TextEdit.insert(selection.active, text));
    }

    // New WorkspaceEdit
    let edit = new vscode.WorkspaceEdit();
    edit.set(uri, edits);

    // Applying the WorkspaceEdit
    vscode.workspace.applyEdit(edit)
      .then(() => {

        // Clear the selection
        textEditor.selection = new vscode.Selection(textEditor.selection.end, textEditor.selection.end);

      }, (err) => {
        reject(err);
      });

    return true;
  }

  // Copy text to clipboard and set statusBarMessage
  let copy = (text, message) => {
    copyPaste.copy(text, () => {
      if (message) {
        statusMessage(message);
      }
    });
  }

  let searchDisposable = vscode.commands.registerCommand('cdnjs.search', function() {

    // The chosen file
    let chosen = {};

    showSearchInput().then((value) => {

      return search(value);

    }).then((results) => {

      return showLibraryPicker(results);

    }).then((library) => {

      chosen.library = library.name;

      return getLibrary(library.name);

    }).then((library) => {

      return showLibraryVersionPicker(library);

    }).then((asset) => {

      chosen.version = asset.version;

      return showFilePicker(asset);

    }).then((file) => {

      chosen.file = file;

      return showActionPicker(chosen);

    }).catch((err) => {

      console.error(err);

    })

  });

  let recentLibrariesDisposable = vscode.commands.registerCommand('cdnjs.recentLibraries', function() {
    console.log('recentLibraries');
  });
}
exports.activate = activate;

let deactivate = () => {}
exports.deactivate = deactivate;<|endoftext|>


<commit_before>var falafel = require('falafel')
var duplexify = require('duplexify')
var through = require('through2')
var concat = require('concat-stream')
var from = require('from2')
var gdeps = require('glslify-deps')
var gbundle = require('glslify-bundle')
var path = require('path')
var seval = require('static-eval')
var resolve = require('resolve')
var gresolve = require('glsl-resolve')
var extend = require('xtend')

var glslfile0 = path.join(__dirname,'index.js')
var glslfile1 = path.join(__dirname,'index')
var parseOptions = {
  ecmaVersion: 10,
  sourceType: 'module',
  allowReturnOutsideFunction: true,
  allowImportExportEverywhere: true,
  allowHashBang: true
}

module.exports = function (file, opts) {
  if (path.extname(file) == '.json') return through()
  if (!opts) opts = {}
  var posts = []
  var dir = path.dirname(file)
  var glvar = null, mdir = dir
  var evars = {
    __dirname: dir,
    __filename: file,
    require: { resolve: resolve }
  }

  ;[]
    .concat(opts.post || [])
    .concat(opts.p || [])
    .forEach(function (post) {
      post = Array.isArray(post) ? post : [post]
      var name = post[0]
      var opts = post[1] || {}
      posts.push({ name: name, opts: opts })
    })

  function evaluate (expr) {
    return seval(expr, evars)
  }

  var d = duplexify()
  var out = from(function () {})
  d.setReadable(out)
  d.setWritable(concat({ encoding: 'string' }, function (src) {
    var pending = 1
    if (src.indexOf('glslify') === -1) {
      out.push(src)
      out.push(null)
      return
    }

    try { var fout = falafel(src, parseOptions, onnode) }
    catch (err) { return d.emit('error', err) }
    done()
    function onnode (node) {
      if (node.type === 'Identifier' && node.name === 'require'
      && node.parent.type === 'CallExpression'
      && node.parent.arguments[0]
      && node.parent.arguments[0].type === 'Literal'
      && node.parent.arguments[0].value === 'path'
      && node.parent.parent.type === 'VariableDeclarator') {
        evars.path = path
      } else if (node.type === 'Identifier' && node.name === 'require'
      && node.parent.type === 'CallExpression'
      && node.parent.arguments[0]
      && node.parent.arguments[0].type === 'Literal'
      && (/^glslify(?:\/index(?:\.js)?)?/.test(node.parent.arguments[0].value)
      || path.resolve(dir,node.parent.arguments[0].value) === __dirname
      || path.resolve(dir,node.parent.arguments[0].value) === glslfile0
      || path.resolve(dir,node.parent.arguments[0].value) === glslfile1)) {
        var p = node.parent.parent, pp = p.parent
        if (p.type === 'CallExpression' && pp.type === 'CallExpression') {
          // case: require('glslify')(...)
          pending++
          callexpr(p, done)
        } else if (p.type === 'VariableDeclarator') {
          // case: var glvar = require('glslify')
          glvar = p.id.name
        } else if (p.type === 'MemberExpression' && p.property.name === 'file'
        && pp.type === 'CallExpression') {
          // case: require('glslify').file(...)
          pending++
          rcallfile(pp, done)
        } else if (p.type === 'MemberExpression' && p.property.name === 'compile'
        && pp.type === 'CallExpression') {
          // case: require('glslify').compile(...)
          pending++
          rcallcompile(pp, done)
        } else if (p.type === 'TaggedTemplateExpression') {
          // case: require('glslify')`...`
          pending++
          tagexpr(p, done)
        }
      } else if (node.type === 'Identifier' && node.name === glvar
      && node.parent.type === 'CallExpression') {
        // case: glvar(...)
        pending++
        callexpr(node.parent, done)
      } else if (node.type === 'TaggedTemplateExpression'
      && node.tag.name === glvar) {
        // case: glvar`...`
        pending++
        tagexpr(node, done)
      } else if (node.type === 'Identifier' && node.name === glvar
      && node.parent.type === 'MemberExpression'
      && node.parent.property.name === 'file'
      && node.parent.parent.type === 'CallExpression'
      && node.parent.parent.arguments[0]) {
        pending++
        callfile(node.parent.parent, done)
      } else if (node.type === 'Identifier' && node.name === glvar
      && node.parent.type === 'MemberExpression'
      && node.parent.property.name === 'compile'
      && node.parent.parent.type === 'CallExpression'
      && node.parent.parent.arguments[0]) {
        pending++
        callcompile(node.parent.parent, done)
      }
    }
    function tagexpr (node, cb) {
      var q = node.quasi
      var shadersrc = q.quasis.map(function (s) {
        return s.value.raw + '__GLX_PLACEHOLDER__'
      }).join('')
      var d = createDeps({ cwd: mdir })
      d.inline(shadersrc, mdir, function (err, deps) {
        if (err) return d.emit('error', err)
        try { var bsrc = bundle(deps) }
        catch (err) { return d.emit('error', err) }
        node.update(node.tag.source() + '('
          + JSON.stringify(bsrc.split('__GLX_PLACEHOLDER__'))
          + [''].concat(q.expressions.map(function (e) {
            return e.source()
          })).join(',')
          + ')')
        cb()
      })
    }
    function callexpr (p, cb) {
      var marg = evaluate(p.arguments[0])
      var mopts = p.arguments[1] ? evaluate(p.arguments[1]) || {} : {}
      var d = createDeps(extend({ cwd: mdir }, mopts))
      if (/(void\s+main\s?\(.*\)|\n)/.test(marg)) { // source string
        d.inline(marg, mdir, ondeps)
      } else gresolve(marg, { basedir: mdir }, function (err, res) {
        if (err) d.emit('error', err)
        else d.add(res, ondeps)
      })
      function ondeps (err, deps) {
        if (err) return d.emit('error', err)
        try { var bsrc = bundle(deps) }
        catch (err) { return d.emit('error', err) }
        p.update(p.callee.source()+'(['+JSON.stringify(bsrc)+'])')
        cb()
      }
    }
    function callcompile (p, cb) {
      var mfile = p.arguments[0].value
      var mopts = p.arguments[1] ? evaluate(p.arguments[1]) || {} : {}
      var d = createDeps({ cwd: mdir })
      d.inline(mfile, mdir, ondeps)
      function ondeps (err, deps) {
        if (err) return d.emit('error', err)
        try { var bsrc = bundle(deps) }
        catch (err) { return d.emit('error', err) }
        p.update(glvar + '([' + JSON.stringify(bsrc) + '])')
        cb()
      }
    }
    function callfile (p, cb) {
      var mfile = p.arguments[0].value
      gresolve(mfile, { basedir: mdir }, function (err, res) {
        if (err) return d.emit('error', err)
        var mopts = p.arguments[1] ? evaluate(p.arguments[1]) || {} : {}
        var d = createDeps(extend({ cwd: path.dirname(res) }, mopts))
        d.add(res, ondeps)
      })
      function ondeps (err, deps) {
        if (err) return d.emit('error', err)
        try { var bsrc = bundle(deps) }
        catch (err) { return d.emit('error', err) }
        p.update(glvar + '([' + JSON.stringify(bsrc) + '])')
        cb()
      }
    }
    function rcallfile (p, cb) {
      var mfile = evaluate(p.arguments[0])
      gresolve(mfile, { basedir: mdir }, function (err, res) {
        if (err) return d.emit('error', err)
        var mopts = p.arguments[1] ? evaluate(p.arguments[1]) || {} : {}
        var d = createDeps(extend({ cwd: path.dirname(res) }, mopts))
        d.add(res, ondeps)
      })
      function ondeps (err, deps) {
        if (err) return d.emit('error', err)
        try { var bsrc = bundle(deps) }
        catch (err) { return d.emit('error', err) }
        p.update(p.callee.object.source()+'(['+JSON.stringify(bsrc)+'])')
        cb()
      }
    }
    function rcallcompile (p, cb) {
      var marg = evaluate(p.arguments[0])
      var mopts = p.arguments[1] ? evaluate(p.arguments[1]) || {} : {}
      var d = createDeps({ cwd: mdir })
      d.inline(marg, mdir, ondeps)
      function ondeps (err, deps) {
        if (err) return d.emit('error', err)
        try { var bsrc = bundle(deps) }
        catch (err) { return d.emit('error', err) }
        p.update(p.callee.object.source()+'(['+JSON.stringify(bsrc)+'])')
        cb()
      }
    }
    function done () {
      if (--pending === 0) {
        out.push(fout.toString())
        out.push(null)
      }
    }
  }))
  return d

  function createDeps (opts) {
    var depper = gdeps(opts)
    var basedir = opts.cwd
    depper.on('error', function (err) { d.emit('error', err) })
    depper.on('file', function (file) { d.emit('file', file) })
    var transforms = opts.transform || []
    transforms = Array.isArray(transforms) ? transforms : [transforms]
    transforms.forEach(function(transform) {
      transform = Array.isArray(transform) ? transform : [transform]
      var name = transform[0]
      var opts = transform[1] || {}
      if (opts.post) {
        posts.push({ name: name, opts: opts, base: basedir })
      } else {
        depper.transform(name, opts)
      }
    })
    return depper
  }
  function bundle (deps) {
    var source = gbundle(deps)
    posts.forEach(function (tr) {
      var transform
      if (typeof tr.name === "function") {
        transform = tr.name
      } else {
        var target = resolve.sync(tr.name, { basedir: tr.base || mdir })
        transform = require(target)
      }

      var src = transform(null, source, { post: true })
      if (src) source = src
    })
    return source
  }
}
<commit_msg>Fix for CLI post transforms<commit_after>var falafel = require('falafel')
var duplexify = require('duplexify')
var through = require('through2')
var concat = require('concat-stream')
var from = require('from2')
var gdeps = require('glslify-deps')
var gbundle = require('glslify-bundle')
var path = require('path')
var seval = require('static-eval')
var resolve = require('resolve')
var gresolve = require('glsl-resolve')
var extend = require('xtend')

var glslfile0 = path.join(__dirname,'index.js')
var glslfile1 = path.join(__dirname,'index')
var parseOptions = {
  ecmaVersion: 10,
  sourceType: 'module',
  allowReturnOutsideFunction: true,
  allowImportExportEverywhere: true,
  allowHashBang: true
}

module.exports = function (file, opts) {
  if (path.extname(file) == '.json') return through()
  if (!opts) opts = {}
  var posts = []
  var dir = path.dirname(file)
  var glvar = null, mdir = dir
  var evars = {
    __dirname: dir,
    __filename: file,
    require: { resolve: resolve }
  }

  function evaluate (expr) {
    return seval(expr, evars)
  }

  var d = duplexify()
  var out = from(function () {})
  d.setReadable(out)
  d.setWritable(concat({ encoding: 'string' }, function (src) {
    var pending = 1
    if (src.indexOf('glslify') === -1) {
      out.push(src)
      out.push(null)
      return
    }

    ;[]
      .concat(opts.post || [])
      .concat(opts.p || [])
      .forEach(function (post) {
        post = Array.isArray(post) ? post : [post]
        var name = post[0]
        var opts = post[1] || {}
        posts.push({ name: name, opts: opts, base: process.cwd() })
      })

    try { var fout = falafel(src, parseOptions, onnode) }
    catch (err) { return d.emit('error', err) }
    done()
    function onnode (node) {
      if (node.type === 'Identifier' && node.name === 'require'
      && node.parent.type === 'CallExpression'
      && node.parent.arguments[0]
      && node.parent.arguments[0].type === 'Literal'
      && node.parent.arguments[0].value === 'path'
      && node.parent.parent.type === 'VariableDeclarator') {
        evars.path = path
      } else if (node.type === 'Identifier' && node.name === 'require'
      && node.parent.type === 'CallExpression'
      && node.parent.arguments[0]
      && node.parent.arguments[0].type === 'Literal'
      && (/^glslify(?:\/index(?:\.js)?)?/.test(node.parent.arguments[0].value)
      || path.resolve(dir,node.parent.arguments[0].value) === __dirname
      || path.resolve(dir,node.parent.arguments[0].value) === glslfile0
      || path.resolve(dir,node.parent.arguments[0].value) === glslfile1)) {
        var p = node.parent.parent, pp = p.parent
        if (p.type === 'CallExpression' && pp.type === 'CallExpression') {
          // case: require('glslify')(...)
          pending++
          callexpr(p, done)
        } else if (p.type === 'VariableDeclarator') {
          // case: var glvar = require('glslify')
          glvar = p.id.name
        } else if (p.type === 'MemberExpression' && p.property.name === 'file'
        && pp.type === 'CallExpression') {
          // case: require('glslify').file(...)
          pending++
          rcallfile(pp, done)
        } else if (p.type === 'MemberExpression' && p.property.name === 'compile'
        && pp.type === 'CallExpression') {
          // case: require('glslify').compile(...)
          pending++
          rcallcompile(pp, done)
        } else if (p.type === 'TaggedTemplateExpression') {
          // case: require('glslify')`...`
          pending++
          tagexpr(p, done)
        }
      } else if (node.type === 'Identifier' && node.name === glvar
      && node.parent.type === 'CallExpression') {
        // case: glvar(...)
        pending++
        callexpr(node.parent, done)
      } else if (node.type === 'TaggedTemplateExpression'
      && node.tag.name === glvar) {
        // case: glvar`...`
        pending++
        tagexpr(node, done)
      } else if (node.type === 'Identifier' && node.name === glvar
      && node.parent.type === 'MemberExpression'
      && node.parent.property.name === 'file'
      && node.parent.parent.type === 'CallExpression'
      && node.parent.parent.arguments[0]) {
        pending++
        callfile(node.parent.parent, done)
      } else if (node.type === 'Identifier' && node.name === glvar
      && node.parent.type === 'MemberExpression'
      && node.parent.property.name === 'compile'
      && node.parent.parent.type === 'CallExpression'
      && node.parent.parent.arguments[0]) {
        pending++
        callcompile(node.parent.parent, done)
      }
    }
    function tagexpr (node, cb) {
      var q = node.quasi
      var shadersrc = q.quasis.map(function (s) {
        return s.value.raw + '__GLX_PLACEHOLDER__'
      }).join('')
      var d = createDeps({ cwd: mdir })
      d.inline(shadersrc, mdir, function (err, deps) {
        if (err) return d.emit('error', err)
        try { var bsrc = bundle(deps) }
        catch (err) { return d.emit('error', err) }
        node.update(node.tag.source() + '('
          + JSON.stringify(bsrc.split('__GLX_PLACEHOLDER__'))
          + [''].concat(q.expressions.map(function (e) {
            return e.source()
          })).join(',')
          + ')')
        cb()
      })
    }
    function callexpr (p, cb) {
      var marg = evaluate(p.arguments[0])
      var mopts = p.arguments[1] ? evaluate(p.arguments[1]) || {} : {}
      var d = createDeps(extend({ cwd: mdir }, mopts))
      if (/(void\s+main\s?\(.*\)|\n)/.test(marg)) { // source string
        d.inline(marg, mdir, ondeps)
      } else gresolve(marg, { basedir: mdir }, function (err, res) {
        if (err) d.emit('error', err)
        else d.add(res, ondeps)
      })
      function ondeps (err, deps) {
        if (err) return d.emit('error', err)
        try { var bsrc = bundle(deps) }
        catch (err) { return d.emit('error', err) }
        p.update(p.callee.source()+'(['+JSON.stringify(bsrc)+'])')
        cb()
      }
    }
    function callcompile (p, cb) {
      var mfile = p.arguments[0].value
      var mopts = p.arguments[1] ? evaluate(p.arguments[1]) || {} : {}
      var d = createDeps({ cwd: mdir })
      d.inline(mfile, mdir, ondeps)
      function ondeps (err, deps) {
        if (err) return d.emit('error', err)
        try { var bsrc = bundle(deps) }
        catch (err) { return d.emit('error', err) }
        p.update(glvar + '([' + JSON.stringify(bsrc) + '])')
        cb()
      }
    }
    function callfile (p, cb) {
      var mfile = p.arguments[0].value
      gresolve(mfile, { basedir: mdir }, function (err, res) {
        if (err) return d.emit('error', err)
        var mopts = p.arguments[1] ? evaluate(p.arguments[1]) || {} : {}
        var d = createDeps(extend({ cwd: path.dirname(res) }, mopts))
        d.add(res, ondeps)
      })
      function ondeps (err, deps) {
        if (err) return d.emit('error', err)
        try { var bsrc = bundle(deps) }
        catch (err) { return d.emit('error', err) }
        p.update(glvar + '([' + JSON.stringify(bsrc) + '])')
        cb()
      }
    }
    function rcallfile (p, cb) {
      var mfile = evaluate(p.arguments[0])
      gresolve(mfile, { basedir: mdir }, function (err, res) {
        if (err) return d.emit('error', err)
        var mopts = p.arguments[1] ? evaluate(p.arguments[1]) || {} : {}
        var d = createDeps(extend({ cwd: path.dirname(res) }, mopts))
        d.add(res, ondeps)
      })
      function ondeps (err, deps) {
        if (err) return d.emit('error', err)
        try { var bsrc = bundle(deps) }
        catch (err) { return d.emit('error', err) }
        p.update(p.callee.object.source()+'(['+JSON.stringify(bsrc)+'])')
        cb()
      }
    }
    function rcallcompile (p, cb) {
      var marg = evaluate(p.arguments[0])
      var mopts = p.arguments[1] ? evaluate(p.arguments[1]) || {} : {}
      var d = createDeps({ cwd: mdir })
      d.inline(marg, mdir, ondeps)
      function ondeps (err, deps) {
        if (err) return d.emit('error', err)
        try { var bsrc = bundle(deps) }
        catch (err) { return d.emit('error', err) }
        p.update(p.callee.object.source()+'(['+JSON.stringify(bsrc)+'])')
        cb()
      }
    }
    function done () {
      if (--pending === 0) {
        out.push(fout.toString())
        out.push(null)
      }
    }
  }))
  return d

  function createDeps (opts) {
    var depper = gdeps(opts)
    var basedir = opts.cwd
    depper.on('error', function (err) { d.emit('error', err) })
    depper.on('file', function (file) { d.emit('file', file) })
    var transforms = opts.transform || []
    transforms = Array.isArray(transforms) ? transforms : [transforms]
    transforms.forEach(function(transform) {
      transform = Array.isArray(transform) ? transform : [transform]
      var name = transform[0]
      var opts = transform[1] || {}
      if (opts.post) {
        posts.push({ name: name, opts: opts, base: basedir })
      } else {
        depper.transform(name, opts)
      }
    })
    return depper
  }
  function bundle (deps) {
    var source = gbundle(deps)
    posts.forEach(function (tr) {
      var transform
      if (typeof tr.name === "function") {
        transform = tr.name
      } else {
        var target = resolve.sync(tr.name, { basedir: tr.base || mdir })
        transform = require(target)
      }

      var src = transform(null, source, { post: true })
      if (src) source = src
    })
    return source
  }
}
<|endoftext|>


<commit_before>import "./styles.scss";

var vid = document.getElementById("videoBackground");
vid.playbackRate = 0.5;

const links = [
  { text: "Pure Fire Ent.", link: "https://www.purefire.world" },
  { text: "Pure Fire Merch", link: "https://www.spotify.com/witeout777" },
  { text: "1stRdKo Clothing", link: "https://www.1strdko.com" },
  { text: "Kounter Clothing", link: "https://www.kounterclothing.com" },
  { text: "Red Caves Real Estate", link: "https://www.kounterclothing.com" }
];

let linksDiv = document.createElement("div");

for (let i = 0; i < links.length; i++) {
  let listItemLink = document.createElement("a");
  listItemLink.href = links[i].link;

  let listItem = document.createElement("div");

  listItemLink.appendChild(listItem);

  listItem.innerHTML = links[i].text;
  listItem.className = "linkBox";

  linksDiv.appendChild(listItemLink);
}

document.getElementById("listContainer").appendChild(linksDiv);
<commit_msg>Updated list of projects<commit_after>import "./styles.scss";

var vid = document.getElementById("videoBackground");
vid.playbackRate = 0.5;

const links = [
  { text: "Amazon Clone", link: "https://www.purefire.world" },
  { text: "Oil & Gas Dashboard", link: "https://www.spotify.com/witeout777" }
];

let linksDiv = document.createElement("div");

for (let i = 0; i < links.length; i++) {
  let listItemLink = document.createElement("a");
  listItemLink.href = links[i].link;

  let listItem = document.createElement("div");

  listItemLink.appendChild(listItem);

  listItem.innerHTML = links[i].text;
  listItem.className = "linkBox";

  linksDiv.appendChild(listItemLink);
}

document.getElementById("listContainer").appendChild(linksDiv);
<|endoftext|>


<commit_before>/*

	JOTPOT Server.
	Copyright (c) Jacob O'Toole 2016-2017

*/

//Version 1.0.1

//Node modules
let fs = require("fs") ;
let vm = require("vm") ;
let events = require("events") ;

let handles = new Object() ;
let handleOver = new Object() ;

module.exports.handles = handles ;

function handle(evt,func,allowOverwrite=true) {

	//New handles allowed?
	if (typeof handleOver[evt] === "undefined") {

		handleOver[evt] = allowOverwrite ;

	}

	else if (handleOver[evt] === false) {

		return false ;

	}

	//If there are no handles yet for the event.
	if (typeof handles[evt] === "undefined") {

		//Set this as the only handle
		handles[evt] = [func] ;

	}

	else {

		//Or add this as a handle
		handles[evt].push(func) ;

	}

	//YAY Handle set!!!
	return true ;

}

module.exports.doEvt = function (evt,...args) {

	return new Promise((resolve,reject)=>{

	//If the event has no handles.
	if (typeof handles[evt] === "undefined") {

		//Carry on
		resolve(false) ;

	}

	//Will resolve false if nothing returns true.
	let rv = false ;
	let totalPromises = 0 ;

	//Function to handle resolving promises
	let handleResolved = (d) => {

		totalPromises-- ;
		//If it is handled
		if (d) {

			//Then we need to resolve true, but not yet.
			rv = true ;

		}

		//If there aren't any pending promesses left, then resolve.
		if (totalPromises === 0) {

			//resolve what we need to resolve.
			resolve(rv) ;

		}

	}

	//Go through all the handles for the event.
	for (let doing in handles[evt]) {

		//Call the handle
		let val = handles[evt][doing](...args) ;

		//If it is falsey, then we cant check because it will error when we try to get .then.
		if (!val) {

			continue ;

		}

		//Is it a promise?
		if (typeof val.then === "function") {

			//One more pending promise.
			totalPromises++ ;

			//Set up the handleResolved function when it resolves.
			val.then(handleResolved) ;

		}

		//If it returns true
		else if (val) {

			//Then we should resolve true... But later
			rv = true ;

		}

	}

	//If there aren't any pending promesses, then resolve.
	if (totalPromises === 0) {

		//resolve what we need to resolve.
		resolve(rv) ;

	}

	}) ;

}

//Set up an event emmitor for recieving variable stuff.
let varEvt = new events() ;
process.on("message",m=>{

	//Got a var
	if (m[0] === "gv") {

		varEvt.emit("got " + m[1],m[2]) ;

	}

	//Set a var
	else if (m[0] === "sv") {

		varEvt.emit("set " + m[1]) ;

	}

	//Var no exist
	else if (m[0] === "fv") {

		varEvt.emit("got " + m[1],void(0)) ;

	}

}) ;

//Function to load an extention. File is path to extention, and serverObj is the object that will be the base of the server variable.
module.exports.loadExt = (file,serverObj,lock=null) => {

	//If the extention doesn't exist...
	if (!fs.existsSync(file)) {

		//We don't load with the error "Not found"
		return {"loaded":false,"error":"Not found"} ;

	}

	//Ah, but if it isn't a file:
	if (!fs.statSync(file).isFile()) {

		//We don't load with the error "Not file"
		return {"loaded":false,"error":"Not file"} ;

	}

	//If there is no lock
	if (lock === null) {

		//Create a new one with no limits.
		lock = new module.exports.lock() ;

	}

	//Save the origional server object.
	const origServerObj = serverObj ;

	//Just, dissapointing...
	serverObj.isMaster = false ;

	//Add the handle function to the serverObj
	serverObj.handle = handle ;

	//Functiom to set a global variable. 1 arg is var name to get.
	serverObj.getGlobal = varTG => {

		return new Promise(resolve=>{

			//When we get the variable.
			varEvt.once("got " + varTG,d=>{

				//Resolve with the contents
				resolve(d) ;

			});

			//Send a request to the master process to get the variable.
			process.send(["gv",varTG,lock.vars]) ;

		}) ;

	} ;

	//Function to set a variable. 1st arg is var name, second is value to set it to.
	serverObj.setGlobal = (varTS,val) => {

		return new Promise(resolve=>{

			//When it is set, resolve
			varEvt.once("set " + varTS,_=>resolve()) ;
			//Tell the master to set it.
			process.send(["sv",varTS,val,lock.vars]) ;

		}) ;

	} ;

	//Function for extention to load another extention.
	serverObj.loadExt = (ePath,eLock=null) => {

		//Return their server object.
		return module.exports.loadExt(ePath,origServerObj,eLock) ;

	}

	//Wrap the source
	let source = `(function(require,server,console,setTimeout,setInterval){${fs.readFileSync(file).toString()}});` ;

	//To catch so ther server doesn't go down if the extention fails to load.
	try {

		//Run it with the required arguments
		vm.runInNewContext(source,{},{

			filename: file + "fun"

		})(require,serverObj,console,setTimeout,setInterval) ;

		//So, it loaded...
		return {"loaded":true,"serverObj":serverObj} ;

	}
	catch(err) {

		//Somthing went wrong:
		return {"loaded":false,"error":err} ;

	}

}

//Function to load an extention in master mode. Similar to loadExt. vars arg is vars object for seting and getting globals.
module.exports.loadMasterExt = (file,serverObj,lock=null,vars) => {

	//If the extention doesn't exist...
	if (!fs.existsSync(file)) {

		//We don't load with the error "Not found"
		return {"loaded":false,"error":"Not found"} ;

	}

	//Ah, but if it isn't a file:
	if (!fs.statSync(file).isFile()) {

		//We don't load with the error "Not file"
		return {"loaded":false,"error":"Not file"} ;

	}

	//If there is no lock
	if (lock === null) {

		//Create a new one with no limits.
		lock = new module.exports.lock() ;

	}

	//Save the origional server object.
	const origServerObj = serverObj ;

	//This is the MASTER!!!
	serverObj.isMaster = true ;

	//Add the handle function to the serverObj
	serverObj.handle = handle ;

	//Functiom to set a global variable. 1 arg is var name to get.
	serverObj.getGlobal = varTG => {

		return new Promise(resolve=>{

			//Resolve instantly, because it is master, there are no async events to do :(
			if (lock.vars === null) {

				//No lock so get var fromm root variables.
				resolve(vars[varTG]) ;

			}

			else {

				//Get var under the lock object.
				resolve(vars[lock.vars][varTG]) ;

			}

		}) ;

	} ;

	//Function to set a variable. 1st arg is var name, second is value to set it to.
	serverObj.setGlobal = (varTS,val) => {

		//set the value and resolve instantly, because it is master, there are no async events to do :(

		if (lock.vars === null) {

			//No lock
			vars[varTS] = val ;

		}

		else {

			//With a lock.
			vars[lock.vars][varTS] = val ;

		}

		resolve() ;

	} ;

	//Functino for extention to load another extention.
	serverObj.loadExt = (ePath,eLock=null) => {

		//Return their server object.
		return module.exports.loadMasterExt(ePath,origServerObj,eLock,vars) ;

	}

	//Wrap the source
	let source = `(function(require,server,console,setTimeout,setInterval){${fs.readFileSync(file).toString()}});` ;

	//To catch so ther server doesn't go down if the extention fails to load.
	try {

		//Run it with the required arguments
		vm.runInNewContext(source,{},{

			filename: file + "fun"

		})(require,serverObj,console,setTimeout,setInterval) ;

		//So, it loaded...
		return {"loaded":true,"serverObj":serverObj} ;

	}
	catch(err) {

		//Somthing went wrong:
		return {"loaded":false,"error":err} ;

	}

}

module.exports.lock = class {

	constructor(vars=null,mode=0,hosts=[],) {

		this.vars = vars ;
		this.mode = mode ;
		if (mode > 0) {

			this.hosts = hosts ;

		}

	}

}<commit_msg>Removed comma causing error<commit_after>/*

	JOTPOT Server.
	Copyright (c) Jacob O'Toole 2016-2017

*/

//Version 1.0.1

//Node modules
let fs = require("fs") ;
let vm = require("vm") ;
let events = require("events") ;

let handles = new Object() ;
let handleOver = new Object() ;

module.exports.handles = handles ;

function handle(evt,func,allowOverwrite=true) {

	//New handles allowed?
	if (typeof handleOver[evt] === "undefined") {

		handleOver[evt] = allowOverwrite ;

	}

	else if (handleOver[evt] === false) {

		return false ;

	}

	//If there are no handles yet for the event.
	if (typeof handles[evt] === "undefined") {

		//Set this as the only handle
		handles[evt] = [func] ;

	}

	else {

		//Or add this as a handle
		handles[evt].push(func) ;

	}

	//YAY Handle set!!!
	return true ;

}

module.exports.doEvt = function (evt,...args) {

	return new Promise((resolve,reject)=>{

	//If the event has no handles.
	if (typeof handles[evt] === "undefined") {

		//Carry on
		resolve(false) ;

	}

	//Will resolve false if nothing returns true.
	let rv = false ;
	let totalPromises = 0 ;

	//Function to handle resolving promises
	let handleResolved = (d) => {

		totalPromises-- ;
		//If it is handled
		if (d) {

			//Then we need to resolve true, but not yet.
			rv = true ;

		}

		//If there aren't any pending promesses left, then resolve.
		if (totalPromises === 0) {

			//resolve what we need to resolve.
			resolve(rv) ;

		}

	}

	//Go through all the handles for the event.
	for (let doing in handles[evt]) {

		//Call the handle
		let val = handles[evt][doing](...args) ;

		//If it is falsey, then we cant check because it will error when we try to get .then.
		if (!val) {

			continue ;

		}

		//Is it a promise?
		if (typeof val.then === "function") {

			//One more pending promise.
			totalPromises++ ;

			//Set up the handleResolved function when it resolves.
			val.then(handleResolved) ;

		}

		//If it returns true
		else if (val) {

			//Then we should resolve true... But later
			rv = true ;

		}

	}

	//If there aren't any pending promesses, then resolve.
	if (totalPromises === 0) {

		//resolve what we need to resolve.
		resolve(rv) ;

	}

	}) ;

}

//Set up an event emmitor for recieving variable stuff.
let varEvt = new events() ;
process.on("message",m=>{

	//Got a var
	if (m[0] === "gv") {

		varEvt.emit("got " + m[1],m[2]) ;

	}

	//Set a var
	else if (m[0] === "sv") {

		varEvt.emit("set " + m[1]) ;

	}

	//Var no exist
	else if (m[0] === "fv") {

		varEvt.emit("got " + m[1],void(0)) ;

	}

}) ;

//Function to load an extention. File is path to extention, and serverObj is the object that will be the base of the server variable.
module.exports.loadExt = (file,serverObj,lock=null) => {

	//If the extention doesn't exist...
	if (!fs.existsSync(file)) {

		//We don't load with the error "Not found"
		return {"loaded":false,"error":"Not found"} ;

	}

	//Ah, but if it isn't a file:
	if (!fs.statSync(file).isFile()) {

		//We don't load with the error "Not file"
		return {"loaded":false,"error":"Not file"} ;

	}

	//If there is no lock
	if (lock === null) {

		//Create a new one with no limits.
		lock = new module.exports.lock() ;

	}

	//Save the origional server object.
	const origServerObj = serverObj ;

	//Just, dissapointing...
	serverObj.isMaster = false ;

	//Add the handle function to the serverObj
	serverObj.handle = handle ;

	//Functiom to set a global variable. 1 arg is var name to get.
	serverObj.getGlobal = varTG => {

		return new Promise(resolve=>{

			//When we get the variable.
			varEvt.once("got " + varTG,d=>{

				//Resolve with the contents
				resolve(d) ;

			});

			//Send a request to the master process to get the variable.
			process.send(["gv",varTG,lock.vars]) ;

		}) ;

	} ;

	//Function to set a variable. 1st arg is var name, second is value to set it to.
	serverObj.setGlobal = (varTS,val) => {

		return new Promise(resolve=>{

			//When it is set, resolve
			varEvt.once("set " + varTS,_=>resolve()) ;
			//Tell the master to set it.
			process.send(["sv",varTS,val,lock.vars]) ;

		}) ;

	} ;

	//Function for extention to load another extention.
	serverObj.loadExt = (ePath,eLock=null) => {

		//Return their server object.
		return module.exports.loadExt(ePath,origServerObj,eLock) ;

	}

	//Wrap the source
	let source = `(function(require,server,console,setTimeout,setInterval){${fs.readFileSync(file).toString()}});` ;

	//To catch so ther server doesn't go down if the extention fails to load.
	try {

		//Run it with the required arguments
		vm.runInNewContext(source,{},{

			filename: file + "fun"

		})(require,serverObj,console,setTimeout,setInterval) ;

		//So, it loaded...
		return {"loaded":true,"serverObj":serverObj} ;

	}
	catch(err) {

		//Somthing went wrong:
		return {"loaded":false,"error":err} ;

	}

}

//Function to load an extention in master mode. Similar to loadExt. vars arg is vars object for seting and getting globals.
module.exports.loadMasterExt = (file,serverObj,lock=null,vars) => {

	//If the extention doesn't exist...
	if (!fs.existsSync(file)) {

		//We don't load with the error "Not found"
		return {"loaded":false,"error":"Not found"} ;

	}

	//Ah, but if it isn't a file:
	if (!fs.statSync(file).isFile()) {

		//We don't load with the error "Not file"
		return {"loaded":false,"error":"Not file"} ;

	}

	//If there is no lock
	if (lock === null) {

		//Create a new one with no limits.
		lock = new module.exports.lock() ;

	}

	//Save the origional server object.
	const origServerObj = serverObj ;

	//This is the MASTER!!!
	serverObj.isMaster = true ;

	//Add the handle function to the serverObj
	serverObj.handle = handle ;

	//Functiom to set a global variable. 1 arg is var name to get.
	serverObj.getGlobal = varTG => {

		return new Promise(resolve=>{

			//Resolve instantly, because it is master, there are no async events to do :(
			if (lock.vars === null) {

				//No lock so get var fromm root variables.
				resolve(vars[varTG]) ;

			}

			else {

				//Get var under the lock object.
				resolve(vars[lock.vars][varTG]) ;

			}

		}) ;

	} ;

	//Function to set a variable. 1st arg is var name, second is value to set it to.
	serverObj.setGlobal = (varTS,val) => {

		//set the value and resolve instantly, because it is master, there are no async events to do :(

		if (lock.vars === null) {

			//No lock
			vars[varTS] = val ;

		}

		else {

			//With a lock.
			vars[lock.vars][varTS] = val ;

		}

		resolve() ;

	} ;

	//Functino for extention to load another extention.
	serverObj.loadExt = (ePath,eLock=null) => {

		//Return their server object.
		return module.exports.loadMasterExt(ePath,origServerObj,eLock,vars) ;

	}

	//Wrap the source
	let source = `(function(require,server,console,setTimeout,setInterval){${fs.readFileSync(file).toString()}});` ;

	//To catch so ther server doesn't go down if the extention fails to load.
	try {

		//Run it with the required arguments
		vm.runInNewContext(source,{},{

			filename: file + "fun"

		})(require,serverObj,console,setTimeout,setInterval) ;

		//So, it loaded...
		return {"loaded":true,"serverObj":serverObj} ;

	}
	catch(err) {

		//Somthing went wrong:
		return {"loaded":false,"error":err} ;

	}

}

module.exports.lock = class {

	constructor(vars=null,mode=0,hosts=[]) {

		this.vars = vars ;
		this.mode = mode ;
		if (mode > 0) {

			this.hosts = hosts ;

		}

	}

}<|endoftext|>