<commit_before>/*
 @author Zakai Hamilton
 @component StorageDB
 */

screens.storage.db = function StorageDB(me) {
    me.init = function () {
        me.mongodb = require("mongodb");
        me.split = require("split-string");
        me.databases = {};
    };
    me.database = async function (name) {
        var db = null;
        var unlock = await me.core.mutex.lock(me.id);
        try {
            var database = me.databases[name];
            if (database) {
                unlock();
                return database;
            }
            var keys = await me.core.private.keys("mongodb");
            var info = keys[name];
            if (!info) {
                unlock();
                var err = name + " mongodb key not defined in private";
                me.log_error(err);
                throw err;
            }
            var url = info.url;
            var client = await me.mongodb.MongoClient.connect(url, { useNewUrlParser: true });
            db = client.db(info.db);
            me.log("connected to db: " + db.databaseName);
            me.databases[name] = db;
        }
        finally {
            unlock();
        }
        return db;
    };
    me.collection = async function (location) {
        var db = await me.database(location.db);
        if (!db) {
            throw "Cannot find database for location: " + location.toString();
        }
        if (location.options) {
            let names = await db.listCollections().toArray();
            if (!names) {
                throw "Cannot find collection names for location: " + location.toString();
            }
            if (!names.map(item => item.name).includes(location.collection)) {
                await db.createCollection(location.collection, location.options);
            }
        }
        var collection = db.collection(location.collection);
        if (!collection) {
            throw "Cannot find collection for location: " + location.toString();
        }
        if (location.indexes) {
            for (let index of location.indexes) {
                collection.createIndex(index);
            }
            location.indexes = null;
        }
        return collection;
    };
    me.objectId = function (id) {
        id = id.toString();
        var object = me.mongodb.ObjectID(id);
        return object;
    };
    me.findByIds = async function (location, ids) {
        var collection = await me.collection(location);
        ids = ids.map(id => id.toString());
        var results = await collection.find({ "_id": { "$in": ids } }).toArray();
        return results;
    };
    me.findById = async function (location, id) {
        var query = { _id: id };
        var [array, hash] = me.getCache(location, query, "find");
        if (array) {
            return array;
        }
        var collection = await me.collection(location);
        var result = await collection.findOne(query);
        me.setCache(location, hash, result);
        return result;
    };
    me.find = async function (location, query) {
        var [array, hash] = me.getCache(location, query, "find");
        if (array) {
            return array;
        }
        var collection = await me.collection(location);
        var result = await collection.findOne(query);
        me.setCache(location, hash, result);
        return result;
    };
    me.store = async function (location, data) {
        var collection = await me.collection(location);
        var isArray = true;
        if (!Array.isArray(data)) {
            isArray = true;
            data = [data];
        }
        data.map(async data => {
            if (data) {
                if (!data._id) {
                    data._id = me.mongodb.ObjectID().toString();
                }
                if (data._id) {
                    await collection.replaceOne({ _id: data._id }, data, { upsert: true });
                }
            }
        });
        if (!isArray) {
            data = data[0];
        }
        me.notifyCache(location);
        return data;
    };
    me.push = async function (location, data) {
        var collection = await me.collection(location);
        var isArray = true;
        if (!Array.isArray(data)) {
            isArray = true;
            data = [data];
        }
        data.map(async data => {
            if (data) {
                if (!data._id) {
                    data._id = me.mongodb.ObjectID().toString();
                }
                if (data._id) {
                    await collection.insertOne(data);
                }
            }
        });
        if (!isArray) {
            data = data[0];
        }
        me.notifyCache(location);
        return data;
    };
    me.remove = async function (location, query, removeOne = true) {
        var collection = await me.collection(location);
        var result = null;
        if (removeOne) {
            result = await collection.deleteOne(query);
        }
        else {
            result = await collection.deleteMany(query);
        }
        me.notifyCache(location);
        return result.nRemoved;
    };
    me.list = async function (location, query = {}, projection, params) {
        var [array, hash] = me.getCache(location, query, projection, params);
        if (array) {
            return array;
        }
        var collection = await me.collection(location);
        if (!projection) {
            projection = {};
        }
        var cursor = await collection.find(query, projection);
        if (params) {
            for (var param in params) {
                cursor = cursor[param](params[param]);
            }
        }
        array = await cursor.toArray();
        me.setCache(location, hash, array);
        return array;
    };
    me.use = async function (location, query, data) {
        data = Object.assign({}, data);
        delete data._id;
        var collection = await me.collection(location);
        var result = await collection.replaceOne(query, data, { upsert: true });
        me.notifyCache(location);
        return result;
    };
    me.createIndex = async function (location, index) {
        var collection = await me.collection(location);
        collection.createIndex(index);
    };
    me.getCache = function (location) {
        var args = Array.prototype.slice.call(arguments, 1);
        var result = null;
        var hash = me.core.string.hash(JSON.stringify(args));
        if (location.cache) {
            me.log("using cache for: " + JSON.stringify(args));
            result = location.cache[hash];
        }
        return [result, hash];
    };
    me.setCache = function (location, hash, value) {
        if (location.cache) {
            location.cache[hash] = value;
        }
    };
    me.notifyCache = function (location) {
        if (location.cache && location.componentId) {
            me.emptyCache(location);
            me.db.events.msg.send(location.componentId + ".emptyCache");
        }
    };
    me.emptyCache = function (location) {
        if (location.cache) {
            location.cache = {};
        }
    };
    me.extension = function (component) {
        var getLocation = function (name) {
            var location = {};
            var tokens = name.split(".");
            location.collection = tokens.pop();
            location.db = tokens.pop();
            location.options = component.options;
            location.indexes = component.indexes;
            location.cache = component.cache;
            location.componentId = component.id;
            return location;
        };
        var mapping = [
            "remove",
            "store",
            "findById",
            "find",
            "use",
            "findByIds",
            "list",
            "createIndex",
            "push",
            "emptyCache"
        ];
        var location = getLocation(component.id);
        for (var name of mapping) {
            component[name] = me[name].bind(null, location);
        }
    };
    return "server";
};<commit_msg>bug fix<commit_after>/*
 @author Zakai Hamilton
 @component StorageDB
 */

screens.storage.db = function StorageDB(me) {
    me.init = function () {
        me.mongodb = require("mongodb");
        me.split = require("split-string");
        me.databases = {};
    };
    me.database = async function (name) {
        var db = null;
        var unlock = await me.core.mutex.lock(me.id);
        try {
            var database = me.databases[name];
            if (database) {
                unlock();
                return database;
            }
            var keys = await me.core.private.keys("mongodb");
            var info = keys[name];
            if (!info) {
                unlock();
                var err = name + " mongodb key not defined in private";
                me.log_error(err);
                throw err;
            }
            var url = info.url;
            var client = await me.mongodb.MongoClient.connect(url, { useNewUrlParser: true });
            db = client.db(info.db);
            me.log("connected to db: " + db.databaseName);
            me.databases[name] = db;
        }
        finally {
            unlock();
        }
        return db;
    };
    me.collection = async function (location) {
        var db = await me.database(location.db);
        if (!db) {
            throw "Cannot find database for location: " + location.toString();
        }
        if (location.options) {
            let names = await db.listCollections().toArray();
            if (!names) {
                throw "Cannot find collection names for location: " + location.toString();
            }
            if (!names.map(item => item.name).includes(location.collection)) {
                await db.createCollection(location.collection, location.options);
            }
        }
        var collection = db.collection(location.collection);
        if (!collection) {
            throw "Cannot find collection for location: " + location.toString();
        }
        if (location.indexes) {
            for (let index of location.indexes) {
                collection.createIndex(index);
            }
            location.indexes = null;
        }
        return collection;
    };
    me.objectId = function (id) {
        id = id.toString();
        var object = me.mongodb.ObjectID(id);
        return object;
    };
    me.findByIds = async function (location, ids) {
        var collection = await me.collection(location);
        ids = ids.map(id => id.toString());
        var results = await collection.find({ "_id": { "$in": ids } }).toArray();
        return results;
    };
    me.findById = async function (location, id) {
        var query = { _id: id };
        var [array, hash] = me.getCache(location, query, "find");
        if (array) {
            return array;
        }
        var collection = await me.collection(location);
        var result = await collection.findOne(query);
        me.setCache(location, hash, result);
        return result;
    };
    me.find = async function (location, query) {
        var [array, hash] = me.getCache(location, query, "find");
        if (array) {
            return array;
        }
        var collection = await me.collection(location);
        var result = await collection.findOne(query);
        me.setCache(location, hash, result);
        return result;
    };
    me.store = async function (location, data) {
        var collection = await me.collection(location);
        var isArray = true;
        if (!Array.isArray(data)) {
            isArray = true;
            data = [data];
        }
        data.map(async data => {
            if (data) {
                if (!data._id) {
                    data._id = me.mongodb.ObjectID().toString();
                }
                if (data._id) {
                    await collection.replaceOne({ _id: data._id }, data, { upsert: true });
                }
            }
        });
        if (!isArray) {
            data = data[0];
        }
        me.notifyCache(location);
        return data;
    };
    me.push = async function (location, data) {
        var collection = await me.collection(location);
        var isArray = true;
        if (!Array.isArray(data)) {
            isArray = true;
            data = [data];
        }
        data.map(async data => {
            if (data) {
                if (!data._id) {
                    data._id = me.mongodb.ObjectID().toString();
                }
                if (data._id) {
                    await collection.insertOne(data);
                }
            }
        });
        if (!isArray) {
            data = data[0];
        }
        me.notifyCache(location);
        return data;
    };
    me.remove = async function (location, query, removeOne = true) {
        var collection = await me.collection(location);
        var result = null;
        if (removeOne) {
            result = await collection.deleteOne(query);
        }
        else {
            result = await collection.deleteMany(query);
        }
        me.notifyCache(location);
        return result.nRemoved;
    };
    me.list = async function (location, query = {}, projection, params) {
        var [array, hash] = me.getCache(location, query, projection, params);
        if (array) {
            return array;
        }
        var collection = await me.collection(location);
        if (!projection) {
            projection = {};
        }
        var cursor = await collection.find(query, projection);
        if (params) {
            for (var param in params) {
                cursor = cursor[param](params[param]);
            }
        }
        array = await cursor.toArray();
        me.setCache(location, hash, array);
        return array;
    };
    me.use = async function (location, query, data) {
        data = Object.assign({}, data);
        delete data._id;
        var collection = await me.collection(location);
        var result = await collection.replaceOne(query, data, { upsert: true });
        me.notifyCache(location);
        return result;
    };
    me.createIndex = async function (location, index) {
        var collection = await me.collection(location);
        collection.createIndex(index);
    };
    me.getCache = function (location) {
        var args = Array.prototype.slice.call(arguments, 1);
        var result = null;
        var hash = me.core.string.hash(JSON.stringify(args));
        if (location.cache) {
            me.log("using db cache for: " + JSON.stringify(args));
            result = location.cache[hash];
        }
        return [result, hash];
    };
    me.setCache = function (location, hash, value) {
        if (location.cache) {
            location.cache[hash] = value;
        }
    };
    me.notifyCache = function (location) {
        if (location.cache && location.componentId) {
            me.emptyCache(location);
            me.db.events.msg.send(location.componentId + ".emptyCache");
        }
    };
    me.emptyCache = function (location) {
        if (location.cache) {
            location.cache = {};
        }
    };
    me.extension = function (component) {
        var getLocation = function (name) {
            var location = {};
            var tokens = name.split(".");
            location.collection = tokens.pop();
            location.db = tokens.pop();
            location.options = component.options;
            location.indexes = component.indexes;
            location.cache = component.cache;
            location.componentId = component.id;
            return location;
        };
        var mapping = [
            "remove",
            "store",
            "findById",
            "find",
            "use",
            "findByIds",
            "list",
            "createIndex",
            "push",
            "emptyCache"
        ];
        var location = getLocation(component.id);
        for (var name of mapping) {
            component[name] = me[name].bind(null, location);
        }
    };
    return "server";
};<|endoftext|>


<commit_before>import path from 'path'

import {
  cmsData,
  cmsOperations,
  coreUtils,
  config,
  abeExtend,
  Manager
} from '../../'

export function publish(filePath, tplPath, json) {
  var p = new Promise((resolve, reject) => {
    abeExtend.hooks.instance.trigger('beforePublish', json, filePath, tplPath)
    var p1 = new Promise((resolve) => {
      cmsOperations.save.save(
        path.join(config.root, config.draft.url, filePath.replace(config.root)),
        tplPath,
        json,
        '',
        'draft',
        null,
        'publish')
        .then(() => {
          resolve()
        }).catch(function(e) {
          console.error(e)
        })
    })

    p1.then((resSave) => {
      cmsOperations.save.save(
        path.join(config.root, config.draft.url, filePath.replace(config.root)),
        tplPath,
        json,
        '',
        'publish',
        resSave,
        'publish')
        .then((resSave) => {
          var result
          if(typeof resSave.error !== 'undefined' && resSave.error !== null  ){
            result = {
              success: 0,
              error: resSave.error
            }
          } else if(typeof resSave.reject !== 'undefined' && resSave.reject !== null){
            result = resSave
          } else if(typeof resSave.json !== 'undefined' && resSave.json !== null){
            result = {
              success: 1,
              json: resSave.json
            }
          }
          abeExtend.hooks.instance.trigger('afterPublish', result)
          Manager.instance.updateList()
          resolve(result)
        }).catch(function(e) {
          console.error('post.js', e)
          var result = {
            success: 0,
            error: 'publish error'
          }
          abeExtend.hooks.instance.trigger('afterPublish', result)
          resolve(result)
        })
    }).catch(function(e) {
      console.error('post.js', e)
      var result = {
        success: 0,
        error: 'publish error'
      }
      abeExtend.hooks.instance.trigger('afterPublish', result)
      resolve(result)
    })
  })

  return p
}

export function unpublish(filePath) {
  abeExtend.hooks.instance.trigger('beforeUnpublish', filePath)
  filePath = coreUtils.slug.clean(filePath)
  var tplUrl = cmsData.file.fromUrl(path.join(config.publish.url, filePath))
  if(coreUtils.file.exist(tplUrl.json.path)) {
    var json = JSON.parse(JSON.stringify(cmsData.file.get(tplUrl.json.path)))
    if(json.abe_meta.publish != null) {
      delete json.abe_meta.publish
    }

    cmsOperations.save.save(
      path.join(config.root, config.draft.url, json.abe_meta.link.replace(config.root)),
      json.abe_meta.template,
      json,
      '',
      'reject',
      null,
      'reject'
    )
    .then(() => {
      cmsOperations.remove.removeFile(tplUrl.publish.path, tplUrl.publish.json)
      abeExtend.hooks.instance.trigger('afterUnpublish', tplUrl.publish.path, tplUrl.publish.json)
      Manager.instance.updateList()
    })
  }
}

export function reject(filePath, tplPath, json) {
  abeExtend.hooks.instance.trigger('beforeReject', filePath)

  var p = new Promise((resolve) => {
    cmsOperations.save.save(
      path.join(config.root, config.draft.url, filePath.replace(config.root)),
      tplPath,
      json,
      '',
      'draft',
      null,
      'reject')
      .then(() => {
        resolve()
      }).catch(function(e) {
        console.error(e)
      })
  })

  p.then((resSave) => {
    cmsOperations.save.save(
      path.join(config.root, config.draft.url, filePath.replace(config.root)),
      tplPath,
      json,
      '',
      'reject',
      resSave,
      'reject')
      .then((resSave) => {
        var result
        if(typeof resSave.error !== 'undefined' && resSave.error !== null  ){
          result = {
            success: 0,
            error: resSave.error
          }
        } else if(typeof resSave.reject !== 'undefined' && resSave.reject !== null){
          result = resSave
        } else if(typeof resSave.json !== 'undefined' && resSave.json !== null){
          result = {
            success: 1,
            json: resSave.json
          }
        }
        abeExtend.hooks.instance.trigger('afterReject', result)
        Manager.instance.updateList()
        resolve(result)
      })
  }).catch(function(e) {
    console.error(e)
    var result = {
      success: 0,
      error: 'reject error'
    }
    abeExtend.hooks.instance.trigger('afterReject', result)
    resolve(result)
  })
}<commit_msg>fix: reject page not working<commit_after>import path from 'path'

import {
  cmsData,
  cmsOperations,
  coreUtils,
  config,
  abeExtend,
  Manager
} from '../../'

export function publish(filePath, tplPath, json) {
  var p = new Promise((resolve, reject) => {
    abeExtend.hooks.instance.trigger('beforePublish', json, filePath, tplPath)
    var p1 = new Promise((resolve) => {
      cmsOperations.save.save(
        path.join(config.root, config.draft.url, filePath.replace(config.root)),
        tplPath,
        json,
        '',
        'draft',
        null,
        'publish')
        .then(() => {
          resolve()
        }).catch(function(e) {
          console.error(e)
        })
    })

    p1.then((resSave) => {
      cmsOperations.save.save(
        path.join(config.root, config.draft.url, filePath.replace(config.root)),
        tplPath,
        json,
        '',
        'publish',
        resSave,
        'publish')
        .then((resSave) => {
          var result
          if(typeof resSave.error !== 'undefined' && resSave.error !== null  ){
            result = {
              success: 0,
              error: resSave.error
            }
          } else if(typeof resSave.reject !== 'undefined' && resSave.reject !== null){
            result = resSave
          } else if(typeof resSave.json !== 'undefined' && resSave.json !== null){
            result = {
              success: 1,
              json: resSave.json
            }
          }
          abeExtend.hooks.instance.trigger('afterPublish', result)
          Manager.instance.updateList()
          resolve(result)
        }).catch(function(e) {
          console.error('post.js', e)
          var result = {
            success: 0,
            error: 'publish error'
          }
          abeExtend.hooks.instance.trigger('afterPublish', result)
          resolve(result)
        })
    }).catch(function(e) {
      console.error('post.js', e)
      var result = {
        success: 0,
        error: 'publish error'
      }
      abeExtend.hooks.instance.trigger('afterPublish', result)
      resolve(result)
    })
  })

  return p
}

export function unpublish(filePath) {
  abeExtend.hooks.instance.trigger('beforeUnpublish', filePath)
  filePath = coreUtils.slug.clean(filePath)
  var tplUrl = cmsData.file.fromUrl(path.join(config.publish.url, filePath))
  if(coreUtils.file.exist(tplUrl.json.path)) {
    var json = JSON.parse(JSON.stringify(cmsData.file.get(tplUrl.json.path)))
    if(json.abe_meta.publish != null) {
      delete json.abe_meta.publish
    }

    cmsOperations.save.save(
      path.join(config.root, config.draft.url, json.abe_meta.link.replace(config.root)),
      json.abe_meta.template,
      json,
      '',
      'reject',
      null,
      'reject'
    )
    .then(() => {
      cmsOperations.remove.removeFile(tplUrl.publish.path, tplUrl.publish.json)
      abeExtend.hooks.instance.trigger('afterUnpublish', tplUrl.publish.path, tplUrl.publish.json)
      Manager.instance.updateList()
    })
  }
}

export function reject(filePath, tplPath, json) {
  var p = new Promise((resolve, reject) => {
    var p1 = new Promise((resolve) => {
      cmsOperations.save.save(
        path.join(config.root, config.draft.url, filePath.replace(config.root)),
        tplPath,
        json,
        '',
        'draft',
        null,
        'reject')
        .then((resSave) => {
          resolve()
        }).catch(function(e) {
          console.error(e)
        })
    })

    p1.then((resSave) => {
      cmsOperations.save.save(
        path.join(config.root, config.draft.url, filePath.replace(config.root)),
        tplPath,
        json,
        '',
        'reject',
        resSave,
        'reject')
        .then((resSave) => {
          var result
          if(typeof resSave.error !== 'undefined' && resSave.error !== null  ){
            result = {
              success: 0,
              error: resSave.error
            }
          } else if(typeof resSave.reject !== 'undefined' && resSave.reject !== null){
            result = resSave
          } else if(typeof resSave.json !== 'undefined' && resSave.json !== null){
            result = {
              success: 1,
              json: resSave.json
            }
          }
          abeExtend.hooks.instance.trigger('afterReject', result)
          Manager.instance.updateList()
          resolve(result)
        })
    }).catch(function(e) {
      console.error(e)
      var result = {
        success: 0,
        error: 'reject error'
      }
      abeExtend.hooks.instance.trigger('afterReject', result)
      resolve(result)
    })
  })

  return p
}<|endoftext|>


<commit_before>import Camera from '../../@damienmortini/core/3d/Camera.js';
import GLBoxObject from '../../@damienmortini/core/gl/object/GLBoxObject.js';
import TrackballController from '../../@damienmortini/core/3d/controller/TrackballController.js';
import GLProgram from '../../@damienmortini/core/gl/GLProgram.js';
import BasicShader from '../../@damienmortini/core/shader/BasicShader.js';

export default class View {
  constructor({
    canvas,
  }) {
    this.canvas = canvas;

    const webGLOptions = {
      depth: true,
      alpha: false,
      antialias: true,
    };

    if (!/\bforcewebgl1\b/.test(window.location.search)) {
      this.gl = this.canvas.getContext('webgl2', webGLOptions);
    }
    if (!this.gl) {
      this.gl = this.canvas.getContext('webgl', webGLOptions) || this.canvas.getContext('experimental-webgl', webGLOptions);
    }

    this.camera = new Camera();

    this.cameraController = new TrackballController({
      domElement: this.canvas,
      matrix: this.camera.transform,
      distance: 5,
    });

    this.gl.clearColor(0, 0, 0, 1);
    this.gl.enable(this.gl.CULL_FACE);
    this.gl.enable(this.gl.DEPTH_TEST);

    this.object = new GLBoxObject({
      gl: this.gl,
      normals: true,
      program: new GLProgram({
        gl: this.gl,
        shader: new BasicShader({
          normals: true,
          fragmentChunks: [
            ['end', `
              fragColor = vec4(vNormal * .5 + .5, 1.);
            `],
          ],
        }),
      }),
    });
  }

  resize(width, height) {
    this.gl.viewport(0, 0, this.gl.drawingBufferWidth, this.gl.drawingBufferHeight);
    this.camera.aspectRatio = width / height;
    this.update();
  }

  update() {
    this.gl.clear(this.gl.COLOR_BUFFER_BIT | this.gl.DEPTH_BUFFER_BIT);

    this.cameraController.update();

    this.object.draw({
      uniforms: {
        projectionView: this.camera.projectionView,
      },
    });
  }
}
<commit_msg>starter-gl: fix bind<commit_after>import Camera from '../../@damienmortini/core/3d/Camera.js';
import GLBoxObject from '../../@damienmortini/core/gl/object/GLBoxObject.js';
import TrackballController from '../../@damienmortini/core/3d/controller/TrackballController.js';
import GLProgram from '../../@damienmortini/core/gl/GLProgram.js';
import BasicShader from '../../@damienmortini/core/shader/BasicShader.js';

export default class View {
  constructor({
    canvas,
  }) {
    this.canvas = canvas;

    const webGLOptions = {
      depth: true,
      alpha: false,
      antialias: true,
    };

    if (!/\bforcewebgl1\b/.test(window.location.search)) {
      this.gl = this.canvas.getContext('webgl2', webGLOptions);
    }
    if (!this.gl) {
      this.gl = this.canvas.getContext('webgl', webGLOptions) || this.canvas.getContext('experimental-webgl', webGLOptions);
    }

    this.camera = new Camera();

    this.cameraController = new TrackballController({
      domElement: this.canvas,
      matrix: this.camera.transform,
      distance: 5,
    });

    this.gl.clearColor(0, 0, 0, 1);
    this.gl.enable(this.gl.CULL_FACE);
    this.gl.enable(this.gl.DEPTH_TEST);

    this.object = new GLBoxObject({
      gl: this.gl,
      normals: true,
      program: new GLProgram({
        gl: this.gl,
        shader: new BasicShader({
          normals: true,
          fragmentChunks: [
            ['end', `
              fragColor = vec4(vNormal * .5 + .5, 1.);
            `],
          ],
        }),
      }),
    });
  }

  resize(width, height) {
    this.gl.viewport(0, 0, this.gl.drawingBufferWidth, this.gl.drawingBufferHeight);
    this.camera.aspectRatio = width / height;
    this.update();
  }

  update() {
    this.gl.clear(this.gl.COLOR_BUFFER_BIT | this.gl.DEPTH_BUFFER_BIT);

    this.cameraController.update();

    this.object.draw({
      bind: true,
      uniforms: {
        projectionView: this.camera.projectionView,
      },
    });
  }
}
<|endoftext|>


<commit_before>/**
 * Proudly created by ohad on 20/03/2017.
 */
const _ = require('./prototype');

/**
 * Responsible for executing an AJAX request.
 * If the returned data is in JSON format, the function automatically decodes it.
 *
 * @param {string} url - The URL destination.
 * @param {function} callback - once a request had been successfully completed the callback is
 * called with the request.
 * @param {string} type - The request type (GET, POST). Defaults to 'POST'.
 * @param {string|Object|FormData} data - Additional HTTP parameters. Defaults to an empty string.
 * @param {boolean} async - whether to perform an async call.
 */
exports.ajax = function (url, data, callback, type = 'POST', async = true) {
  type = type.toUpperCase();
  _set(data, 'submit', 1);
  _set(data, 'ajax', 1);
  if (_csrf_token) _set(data, 'token', _csrf_token);

  let xhr = new XMLHttpRequest();
  if (type === 'POST' && !(data instanceof FormData) && !_.isString(data)) {
    data = exports.jsonToFormData(data);
  }
  xhr.withCredentials = true;
  if (type === 'GET') {
    xhr.open('GET', url + '?' + data, async);
    xhr.send();
  } else {
    xhr.open('POST', url, async);
    xhr.send(data);
  }
  xhr.onreadystatechange = function () {
    if (xhr.readyState == XMLHttpRequest.DONE && xhr.status === 200) {
      _csrf_token = _get(xhr.response, 'csrf_token');
      if (_.isFunction(callback)) callback(xhr);
    }
  }
};

/**
 * @param {string} key - of parameter within query.
 * @param {string} query - URL or query string. i.e. example.com?key1=val1&key2=val2
 * @returns {string} value of `key` parameter in query, or null if none was found.
 */
exports.getParameterFromQuery = function (key, query) {
  if (!query) query = window.location.href;
  key           = key.replace(/[\[\]]/g, '\\$&');
  const regex   = new RegExp('[?&]' + key + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(query);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, ' '));
};

/**
 * @param {string} query - URI or query string.
 * @param {string} key - of a parameter within query
 * @param {string} value - of key.
 * @returns {string} the new query with updated value of `key`. Old values are replaced.
 */
exports.updateQueryStringParameter = function (query, key, value) {
  const re        = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
  const separator = query.indexOf('?') !== -1 ? "&" : "?";
  if (query.match(re)) {
    return query.replace(re, '$1' + key + "=" + value + '$2');
  }
  else {
    return query + separator + key + "=" + value;
  }
};

/**
 * @param {Object} json
 * @returns {FormData} form data of the flattened json that can be used in Ajax POST requests.
 */
exports.jsonToFormData = function (json) {
  const flattened = _.flatten(json);
  let formData    = new FormData();
  for (let p in flattened) {
    formData.append(p, flattened[p]);
  }
  return formData;
};

/**
 * Authentication token for our backend.
 * @type {string}
 * @private
 */
let _csrf_token = '';

/**
 * @param {string|Object|FormData} data
 * @param {string} key
 * @returns {*} all values associated with key of data.
 * @private
 */
function _get(data, key) {
  if (_.isString(data)) return exports.getParameterFromQuery(key, data);
  if (_.isNil(data) || !_.isObject(data)) return;
  if (data instanceof FormData) {
    //noinspection JSUnresolvedFunction
    return data.getAll(key);
  }
  return data[key];
}

/**
 * Sets `value` to be associated with `key` for data.
 * @param {string|Object|FormData} data
 * @param {string} key
 * @param {*} value
 * @private
 */
function _set(data, key, value) {
  if (_.isNil(data)) return;
  if (_.isString(data)) {
    exports.updateQueryStringParameter(query, key, value);
  } else if (data instanceof FormData) {
    //noinspection JSUnresolvedFunction
    data.set(key, value);
  } else {
    data[key] = value;
  }
}<commit_msg>ajax tokens<commit_after>/**
 * Proudly created by ohad on 20/03/2017.
 */
const _ = require('./prototype');

/**
 * Responsible for executing an AJAX request.
 * If the returned data is in JSON format, the function automatically decodes it.
 *
 * @param {string} url - The URL destination.
 * @param {function} callback - once a request had been successfully completed the callback is
 * called with the request.
 * @param {string} type - The request type (GET, POST). Defaults to 'POST'.
 * @param {string|Object|FormData} data - Additional HTTP parameters. Defaults to an empty string.
 * @param {boolean} async - whether to perform an async call.
 */
exports.ajax = function (url, data, callback, type = 'POST', async = true) {
  type = type.toUpperCase();
  _set(data, 'submit', 1);
  _set(data, 'ajax', 1);
  if (_csrf_token) _set(data, 'token', _csrf_token);

  let xhr = new XMLHttpRequest();
  if (type === 'POST' && !(data instanceof FormData) && !_.isString(data)) {
    data = exports.jsonToFormData(data);
  }
  xhr.withCredentials = true;
  if (type === 'GET') {
    xhr.open('GET', url + '?' + data, async);
    xhr.send();
  } else {
    xhr.open('POST', url, async);
    xhr.send(data);
  }
  xhr.onreadystatechange = function () {
    if (xhr.readyState == XMLHttpRequest.DONE && xhr.status === 200) {
      // if (_get(data, 'json')) {
      const parsedResponse = JSON.parse(xhr.response);
      _csrf_token          = _get(parsedResponse, 'csrf_token');
      // }
      if (_.isFunction(callback)) callback(xhr);
    }
  }
};

/**
 * @param {string} key - of parameter within query.
 * @param {string} query - URL or query string. i.e. example.com?key1=val1&key2=val2
 * @returns {string} value of `key` parameter in query, or null if none was found.
 */
exports.getParameterFromQuery = function (key, query) {
  if (!query) query = window.location.href;
  key           = key.replace(/[\[\]]/g, '\\$&');
  const regex   = new RegExp('[?&]' + key + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(query);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, ' '));
};

/**
 * @param {string} query - URI or query string.
 * @param {string} key - of a parameter within query
 * @param {string} value - of key.
 * @returns {string} the new query with updated value of `key`. Old values are replaced.
 */
exports.updateQueryStringParameter = function (query, key, value) {
  const re        = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
  const separator = query.indexOf('?') !== -1 ? "&" : "?";
  if (query.match(re)) {
    return query.replace(re, '$1' + key + "=" + value + '$2');
  }
  else {
    return query + separator + key + "=" + value;
  }
};

/**
 * @param {Object} json
 * @returns {FormData} form data of the flattened json that can be used in Ajax POST requests.
 */
exports.jsonToFormData = function (json) {
  const flattened = _.flatten(json);
  let formData    = new FormData();
  for (let p in flattened) {
    formData.append(p, flattened[p]);
  }
  return formData;
};

/**
 * Authentication token for our backend.
 * @type {string}
 * @private
 */
let _csrf_token = '';

/**
 * @param {string|Object|FormData} data
 * @param {string} key
 * @returns {*} all values associated with key of data.
 * @private
 */
function _get(data, key) {
  if (_.isString(data)) return exports.getParameterFromQuery(key, data);
  if (_.isNil(data) || !_.isObject(data)) return;
  if (data instanceof FormData) {
    //noinspection JSUnresolvedFunction
    return data.getAll(key);
  }
  return data[key];
}

/**
 * Sets `value` to be associated with `key` for data.
 * @param {string|Object|FormData} data
 * @param {string} key
 * @param {*} value
 * @private
 */
function _set(data, key, value) {
  if (_.isNil(data)) return;
  if (_.isString(data)) {
    exports.updateQueryStringParameter(query, key, value);
  } else if (data instanceof FormData) {
    //noinspection JSUnresolvedFunction
    data.set(key, value);
  } else {
    data[key] = value;
  }
}<|endoftext|>


<commit_before>/******************************************************************************
 * language.js                                                                 *
 * Copyright 2013                                                              *
 * For details about the copyright holders, see the COPYRIGHT file.            *
 * This software is freely distributed under the ISC License.                  *
 * For details about the license, see the LICENSE file.                        *
 *                                                                             *
 * This module provides an API for interacting with the language model.        *
 ******************************************************************************/

define([
    "jquery"
], function($) {
    var language = {};

    language.langs = {
	    "include_path":"lib/codemirror-3.02/mode/",
	    "data":{
		    "none":{"description":"Plain Text",
                    "mode":"text/plain",
				    "requires":[]},
		    "asp":{"description":"ASP.NET",
                   "mode":"application/x-aspx",
			       "requires":["htmlmixed","clike","htmlembedded"]},
		    "clike":{"description":"C-Like Language",
                     "file":"clike/clike"},
		    "c":{"description":"C",
                 "mode":"text/x-csrc",
			     "options":{"useCPP":true},
			     "requires":["clike"]},
		    "cpp":{"description":"C++",
                   "mode":"text/x-c++src",
			       "options":{"useCPP":true},
			       "requires":["clike"]},
		    "csharp":{"description":"C#",
                      "mode":"text/x-csharp",
				      "requires":["clike"]},
		    "clojure":{"description":"Clojure",
                       "file":"clojure/clojure",
				       "mode":"text/x-clojure"},
		    "coffeescript":{"description":"CoffeeScript",
                            "file":"coffeescript/coffeescript",
						    "mode":"text/x-coffeescript"},
		    "css":{"description":"CSS",
                   "file":"css/css",
			       "mode":"text/css"},
		    "diff":{"description":"diff",
                    "file":"diff/diff",
				    "mode":"text/x-diff"},
		    "ecl":{"description":"ECL",
                   "file":"ecl/ecl",
			       "mode":"text/x-ecl"},
		    "ejs":{"description":"Embedded Javascript",
                   "mode":"application/x-ejs",
			       "requires":["htmlmixed","htmlembedded"]},
		    "erlang":{"description":"Erlang",
                      "file":"erlang/erlang",
				      "mode":"text/x-erlang"},
		    "gfm":{"description":"Github Flavored Markdown",
                   "file":"gfm/gfm",
			       "mode":"gfm",
			       "requires":["markdown",
						       "asp",
						       "c",
						       "cpp",
						       "csharp",
						       "clojure",
						       "coffeescript",
						       "diff",
						       "ecl",
						       "erlang",
						       "go",
						       "groovy",
						       "haskell",
						       "haxe",
						       "html",
						       "java",
						       "javascript",
						       "jinja2",
						       "json",
						       "jsp",
						       "stex",
						       "less",
						       "lua",
						       "markdown",
						       "mysql",
						       "ntriples",
						       "ocaml",
						       "pascal",
						       "perl",
						       "php",
						       "pig",
						       "plsql",
						       "properties",
						       "python",
						       "r",
						       "rpm-spec",
						       "rpm-changes",
						       "rst",
						       "ruby",
						       "rust",
						       "scala",
						       "scheme",
						       "shell",
						       "smalltalk",
						       "smarty",
						       "sparql",
						       "stex",
						       "tiddlywiki",
						       "tikiwiki",
						       "vbscript",
						       "velocity",
						       "verilog",
						       "xml",
						       "xquery",
						       "yaml"]},
		    "go":{"description":"Go",
                  "file":"go/go",
			      "mode":"text/x-go"},
		    "groovy":{"description":"Groovy",
                      "file":"groovy/groovy",
				      "mode":"text/x-groovy"},
		    "haskell":{"description":"Haskell",
                       "file":"haskell/haskell",
				       "mode":"text/x-haskell"},
		    "haxe":{"description":"Haxe",
                    "file":"haxe/haxe",
				    "mode":"text/x-haxe"},
		    "html":{"description":"HTML",
                    "mode":"text/html",
				    "requires":["xml"],
				    "options":{"htmlMode":true}},
		    "htmlmixed":{"description":"HTML/Javascript/CSS",
                         "file":"htmlmixed/htmlmixed",
					     "mode":"text/html",
					     "requires":["xml","javascript","css"]},
		    "htmlembedded":{"description":"Embedded HTML",
                            "file":"htmlembedded/htmlembedded"},
		    "java":{"description":"Java",
                    "mode":"text/x-java",
				    "requires":["clike"]},
		    "javascript":{"description":"Javascript",
                          "file":"javascript/javascript",
					      "mode":"text/javascript"},
		    "jinja2":{"description":"Jinja2",
                      "file":"jinja2/jinja2",
				      "mode":"jinja2"},
		    "json":{"description":"JSON",
                    "mode":"application/json",
				    "requires":["javascript"],
				    "options":{"json":true}},
		    "jsp":{"description":"JSP",
                   "mode":"application/x-jsp",
			       "requires":["htmlmixed","clike","htmlembedded"]},
		    "latex":{"description":"LaTeX",
                     "requires":["stex"]},
		    "less":{"description":"LESS",
                    "file":"less/less",
				    "mode":"text/x-less"},
		    "lua":{"description":"Lua",
                   "file":"lua/lua",
			       "mode":"text/x-lua"},
		    "markdown":{"description":"Markdown",
                        "file":"markdown/markdown",
					    "mode":"text/x-markdown",
					    "requires":["xml"]},
		    "mysql":{"description":"MySQL",
                     "file":"mysql/mysql",
				     "mode":"text/x-mysql"},
		    "ntriples":{"description":"N-Triples",
                        "file":"ntriples/ntriples",
					    "mode":"text/n-triples"},
		    "ocaml":{"description":"OCaml",
                     "file":"ocaml/ocaml",
				     "mode":"text/x-ocaml"},
		    "pascal":{"description":"Pascal",
                      "file":"pascal/pascal",
				      "mode":"text/x-pascal"},
		    "perl":{"description":"Perl",
                    "file":"perl/perl",
				    "mode":"text/x-perl"},
		    "php":{"description":"PHP",
                   "file":"php/php",
			       "mode":"application/x-httpd-php",
			       "requires":["xml","javascript","css","clike"]},
		    "pig":{"description":"Pig Latin",
                   "file":"pig/pig",
			       "mode":"text/x-pig"},
		    "plsql":{"description":"PL/SQL",
                     "file":"plsql/plsql",
				     "mode":"text/x-plsql"},
		    "properties":{"description":"Properties file (ini)",
                          "file":"properties/properties",
					      "mode":"text/x-properties"},
		    "python":{"description":"Python",
                      "file":"python/python",
				      "mode":"text/x-python"},
		    "python2":{"description":"Python 2",
                       "mode":"text/x-python",
				       "requires":["python"],
				       "options":{"version":2}},
		    "python3":{"description":"Python 3",
                       "mode":"text/x-python",
				       "requires":["python"],
				       "options":{"version":3}},
		    "r":{"description":"R",
                 "file":"r/r",
			     "mode":"text/x-rsrc"},
		    "rpm-spec":{"description":"RPM (spec)",
                        "file":"rpm/spec/spec",
					    "mode":"text/x-rpm-spec"},
		    "rpm-changes":{"description":"RPM (changes)",
                           "file":"rpm/changes/changes",
					       "mode":"text/x-rpm-changes"},
		    "rst":{"description":"reStructuredText",
                   "file":"rst/rst",
			       "mode":"text/x-rst"},
		    "ruby":{"description":"Ruby",
                    "file":"ruby/ruby",
				    "mode":"text/x-ruby"},
		    "rust":{"description":"Rust",
                    "file":"rust/rust",
				    "mode":"text/x-rustsrc"},
		    "scala":{"description":"Scala",
                     "mode":"text/x-scala",
				     "requires":["clike"]},
		    "scheme":{"description":"Scheme",
                      "file":"scheme/scheme",
				      "mode":"text/x-scheme"},
		    "shell":{"description":"Shell",
                     "file":"shell/shell",
				     "mode":"text/x-sh"},
		    "smalltalk":{"description":"Smalltalk",
                         "file":"smalltalk/smalltalk",
					     "mode":"text/x-stsrc"},
		    "smarty":{"description":"Smarty",
                      "file":"smarty/smarty",
				      "mode":"text/x-smarty"},
		    "sparql":{"description":"SPARQL",
                      "file":"sparql/sparql",
				      "mode":"application/x-sparql-query"},
		    "stex":{"description":"sTex",
                    "file":"stex/stex",
				    "mode":"text/x-stex"},
		    "tiddlywiki":{"description":"Tiddlywiki",
                          "file":"tiddlywiki/tiddlywiki",
					      "mode":"text/x-tiddlywiki"},
		    "tikiwiki":{"description":"Tiki wiki",
                        "file":"tiki/tiki",
					    "mode":"tiki"},
		    "vbscript":{"description":"VBScript",
                        "file":"vbscript/vbscript",
					    "mode":"text/vbscript"},
		    "velocity":{"description":"Velocity",
                        "file":"velocity/velocity",
					    "mode":"text/velocity"},
		    "verilog":{"description":"Verilog",
                       "file":"verilog/verilog",
				       "mode":"text/x-verilog"},
		    "xml":{"description":"XML",
                   "file":"xml/xml",
			       "mode":"application/xml"},
		    "xquery":{"description":"XQuery",
                      "file":"xquery/xquery",
				      "mode":"application/xquery"},
		    "yaml":{"description":"YAML",
                    "file":"yaml/yaml",
				    "mode":"text/x-yaml"}
	    }
    }

    return language;
});<commit_msg>Cleaned up unneeded language code<commit_after>/******************************************************************************
 * language.js                                                                 *
 * Copyright 2013                                                              *
 * For details about the copyright holders, see the COPYRIGHT file.            *
 * This software is freely distributed under the ISC License.                  *
 * For details about the license, see the LICENSE file.                        *
 *                                                                             *
 * This module provides an API for interacting with the language model.        *
 ******************************************************************************/

define([
    "jquery"
], function($) {
    var language = {};

    language.langs = {
	    "include_path":"lib/codemirror-3.02/mode/",
	    "data":{
		    "none":{"description":"Plain Text",
                    "mode":"text/plain",
				    "requires":[]},
		    "asp":{"description":"ASP.NET",
                   "mode":"application/x-aspx",
			       "requires":["htmlmixed","clike","htmlembedded"]},
		    "clike":{"file":"clike/clike"},
		    "c":{"description":"C",
                 "mode":"text/x-csrc",
			     "options":{"useCPP":true},
			     "requires":["clike"]},
		    "cpp":{"description":"C++",
                   "mode":"text/x-c++src",
			       "options":{"useCPP":true},
			       "requires":["clike"]},
		    "csharp":{"description":"C#",
                      "mode":"text/x-csharp",
				      "requires":["clike"]},
		    "clojure":{"description":"Clojure",
                       "file":"clojure/clojure",
				       "mode":"text/x-clojure"},
		    "coffeescript":{"description":"CoffeeScript",
                            "file":"coffeescript/coffeescript",
						    "mode":"text/x-coffeescript"},
		    "css":{"description":"CSS",
                   "file":"css/css",
			       "mode":"text/css"},
		    "diff":{"description":"diff",
                    "file":"diff/diff",
				    "mode":"text/x-diff"},
		    "ecl":{"description":"ECL",
                   "file":"ecl/ecl",
			       "mode":"text/x-ecl"},
		    "ejs":{"description":"Embedded Javascript",
                   "mode":"application/x-ejs",
			       "requires":["htmlmixed","htmlembedded"]},
		    "erlang":{"description":"Erlang",
                      "file":"erlang/erlang",
				      "mode":"text/x-erlang"},
		    "gfm":{"description":"Github Flavored Markdown",
                   "file":"gfm/gfm",
			       "mode":"gfm",
			       "requires":["markdown",
						       "asp",
						       "c",
						       "cpp",
						       "csharp",
						       "clojure",
						       "coffeescript",
						       "diff",
						       "ecl",
						       "erlang",
						       "go",
						       "groovy",
						       "haskell",
						       "haxe",
						       "html",
						       "java",
						       "javascript",
						       "jinja2",
						       "json",
						       "jsp",
						       "stex",
						       "less",
						       "lua",
						       "markdown",
						       "mysql",
						       "ntriples",
						       "ocaml",
						       "pascal",
						       "perl",
						       "php",
						       "pig",
						       "plsql",
						       "properties",
						       "python",
						       "r",
						       "rpm-spec",
						       "rpm-changes",
						       "rst",
						       "ruby",
						       "rust",
						       "scala",
						       "scheme",
						       "shell",
						       "smalltalk",
						       "smarty",
						       "sparql",
						       "stex",
						       "tiddlywiki",
						       "tikiwiki",
						       "vbscript",
						       "velocity",
						       "verilog",
						       "xml",
						       "xquery",
						       "yaml"]},
		    "go":{"description":"Go",
                  "file":"go/go",
			      "mode":"text/x-go"},
		    "groovy":{"description":"Groovy",
                      "file":"groovy/groovy",
				      "mode":"text/x-groovy"},
		    "haskell":{"description":"Haskell",
                       "file":"haskell/haskell",
				       "mode":"text/x-haskell"},
		    "haxe":{"description":"Haxe",
                    "file":"haxe/haxe",
				    "mode":"text/x-haxe"},
		    "html":{"description":"HTML",
                    "mode":"text/html",
				    "requires":["xml"],
				    "options":{"htmlMode":true}},
		    "htmlmixed":{"description":"HTML/Javascript/CSS",
                         "file":"htmlmixed/htmlmixed",
					     "mode":"text/html",
					     "requires":["xml","javascript","css"]},
		    "htmlembedded":{"description":"Embedded HTML",
                            "file":"htmlembedded/htmlembedded"},
		    "java":{"description":"Java",
                    "mode":"text/x-java",
				    "requires":["clike"]},
		    "javascript":{"description":"Javascript",
                          "file":"javascript/javascript",
					      "mode":"text/javascript"},
		    "jinja2":{"description":"Jinja2",
                      "file":"jinja2/jinja2",
				      "mode":"jinja2"},
		    "json":{"description":"JSON",
                    "mode":"application/json",
				    "requires":["javascript"],
				    "options":{"json":true}},
		    "jsp":{"description":"JSP",
                   "mode":"application/x-jsp",
			       "requires":["htmlmixed","clike","htmlembedded"]},
		    "latex":{"requires":["stex"]},
		    "less":{"description":"LESS",
                    "file":"less/less",
				    "mode":"text/x-less"},
		    "lua":{"description":"Lua",
                   "file":"lua/lua",
			       "mode":"text/x-lua"},
		    "markdown":{"description":"Markdown",
                        "file":"markdown/markdown",
					    "mode":"text/x-markdown",
					    "requires":["xml"]},
		    "mysql":{"description":"MySQL",
                     "file":"mysql/mysql",
				     "mode":"text/x-mysql"},
		    "ntriples":{"description":"N-Triples",
                        "file":"ntriples/ntriples",
					    "mode":"text/n-triples"},
		    "ocaml":{"description":"OCaml",
                     "file":"ocaml/ocaml",
				     "mode":"text/x-ocaml"},
		    "pascal":{"description":"Pascal",
                      "file":"pascal/pascal",
				      "mode":"text/x-pascal"},
		    "perl":{"description":"Perl",
                    "file":"perl/perl",
				    "mode":"text/x-perl"},
		    "php":{"description":"PHP",
                   "file":"php/php",
			       "mode":"application/x-httpd-php",
			       "requires":["xml","javascript","css","clike"]},
		    "pig":{"description":"Pig Latin",
                   "file":"pig/pig",
			       "mode":"text/x-pig"},
		    "plsql":{"description":"PL/SQL",
                     "file":"plsql/plsql",
				     "mode":"text/x-plsql"},
		    "properties":{"description":"Properties file (ini)",
                          "file":"properties/properties",
					      "mode":"text/x-properties"},
		    "python":{"description":"Python",
                      "file":"python/python",
				      "mode":"text/x-python"},
		    "python2":{"description":"Python 2",
                       "mode":"text/x-python",
				       "requires":["python"],
				       "options":{"version":2}},
		    "python3":{"description":"Python 3",
                       "mode":"text/x-python",
				       "requires":["python"],
				       "options":{"version":3}},
		    "r":{"description":"R",
                 "file":"r/r",
			     "mode":"text/x-rsrc"},
		    "rpm-spec":{"description":"RPM (spec)",
                        "file":"rpm/spec/spec",
					    "mode":"text/x-rpm-spec"},
		    "rpm-changes":{"description":"RPM (changes)",
                           "file":"rpm/changes/changes",
					       "mode":"text/x-rpm-changes"},
		    "rst":{"description":"reStructuredText",
                   "file":"rst/rst",
			       "mode":"text/x-rst"},
		    "ruby":{"description":"Ruby",
                    "file":"ruby/ruby",
				    "mode":"text/x-ruby"},
		    "rust":{"description":"Rust",
                    "file":"rust/rust",
				    "mode":"text/x-rustsrc"},
		    "scala":{"description":"Scala",
                     "mode":"text/x-scala",
				     "requires":["clike"]},
		    "scheme":{"description":"Scheme",
                      "file":"scheme/scheme",
				      "mode":"text/x-scheme"},
		    "shell":{"description":"Shell",
                     "file":"shell/shell",
				     "mode":"text/x-sh"},
		    "smalltalk":{"description":"Smalltalk",
                         "file":"smalltalk/smalltalk",
					     "mode":"text/x-stsrc"},
		    "smarty":{"description":"Smarty",
                      "file":"smarty/smarty",
				      "mode":"text/x-smarty"},
		    "sparql":{"description":"SPARQL",
                      "file":"sparql/sparql",
				      "mode":"application/x-sparql-query"},
		    "stex":{"description":"sTex",
                    "file":"stex/stex",
				    "mode":"text/x-stex"},
		    "tiddlywiki":{"description":"Tiddlywiki",
                          "file":"tiddlywiki/tiddlywiki",
					      "mode":"text/x-tiddlywiki"},
		    "tikiwiki":{"description":"Tiki wiki",
                        "file":"tiki/tiki",
					    "mode":"tiki"},
		    "vbscript":{"description":"VBScript",
                        "file":"vbscript/vbscript",
					    "mode":"text/vbscript"},
		    "velocity":{"description":"Velocity",
                        "file":"velocity/velocity",
					    "mode":"text/velocity"},
		    "verilog":{"description":"Verilog",
                       "file":"verilog/verilog",
				       "mode":"text/x-verilog"},
		    "xml":{"description":"XML",
                   "file":"xml/xml",
			       "mode":"application/xml"},
		    "xquery":{"description":"XQuery",
                      "file":"xquery/xquery",
				      "mode":"application/xquery"},
		    "yaml":{"description":"YAML",
                    "file":"yaml/yaml",
				    "mode":"text/x-yaml"}
	    }
    }

    return language;
});<|endoftext|>


<commit_before>import { EventAggregator } from 'aurelia-event-aggregator';
import { bindable, customAttribute } from 'aurelia-templating';
import { inject } from 'aurelia-dependency-injection';
import { getBooleanFromAttributeValue } from '../common/attributes';
import { AttributeManager } from '../common/attributeManager';

@customAttribute('md-collapsible')
@bindable({ name: 'accordion', defaultValue: false })
@bindable({ name: 'popout', defaultValue: false })
@bindable({ name: 'onOpen' })
@bindable({ name: 'onClose' })
@inject(Element, EventAggregator)
export class MdCollapsible {
  constructor(element, eventAggregator) {
    this.element = element;
    this.eventAggregator = eventAggregator;
    this.attributeManager = new AttributeManager(this.element);
  }

  attached() {
    this.attributeManager.addClasses('collapsible');
    if (getBooleanFromAttributeValue(this.popout)) {
      this.attributeManager.addClasses('popout');
    }
    this.refresh();
  }

  detached() {
    this.attributeManager.removeClasses(['collapsible', 'popout']);
    this.attributeManager.removeAttributes(['data-collapsible']);
  }

  refresh() {
    let accordion = getBooleanFromAttributeValue(this.accordion);
    let dataCollapsibleAttributeValue = accordion ? 'accordion' : 'expandable';

    this.attributeManager.addAttributes({ 'data-collapsible': dataCollapsibleAttributeValue });

    $(this.element).collapsible({
      accordion,
      onOpen: this.buildCollapsibleOpenCloseCallbackHandler(this.onOpen),
      onClose: this.buildCollapsibleOpenCloseCallbackHandler(this.onClose)
    });
  }

  accordionChanged() {
    this.refresh();
  }

  buildCollapsibleOpenCloseCallbackHandler(handler) {
    return typeof(handler) === 'function' ?
     (targetElementJquery) => {
       let targetElement = targetElementJquery[0];

       handler(targetElement);
     } : null;
  }
}
<commit_msg>refactor(md-collapsible): remove Eventggregator, close #430<commit_after>import { bindable, customAttribute } from 'aurelia-templating';
import { inject } from 'aurelia-dependency-injection';
import { getBooleanFromAttributeValue } from '../common/attributes';
import { AttributeManager } from '../common/attributeManager';

@customAttribute('md-collapsible')
@bindable({ name: 'accordion', defaultValue: false })
@bindable({ name: 'popout', defaultValue: false })
@bindable({ name: 'onOpen' })
@bindable({ name: 'onClose' })
@inject(Element)
export class MdCollapsible {
  constructor(element) {
    this.element = element;
    this.attributeManager = new AttributeManager(this.element);
  }

  attached() {
    this.attributeManager.addClasses('collapsible');
    if (getBooleanFromAttributeValue(this.popout)) {
      this.attributeManager.addClasses('popout');
    }
    this.refresh();
  }

  detached() {
    this.attributeManager.removeClasses(['collapsible', 'popout']);
    this.attributeManager.removeAttributes(['data-collapsible']);
  }

  refresh() {
    let accordion = getBooleanFromAttributeValue(this.accordion);
    let dataCollapsibleAttributeValue = accordion ? 'accordion' : 'expandable';

    this.attributeManager.addAttributes({ 'data-collapsible': dataCollapsibleAttributeValue });

    $(this.element).collapsible({
      accordion,
      onOpen: this.buildCollapsibleOpenCloseCallbackHandler(this.onOpen),
      onClose: this.buildCollapsibleOpenCloseCallbackHandler(this.onClose)
    });
  }

  accordionChanged() {
    this.refresh();
  }

  buildCollapsibleOpenCloseCallbackHandler(handler) {
    return typeof(handler) === 'function' ?
     (targetElementJquery) => {
       let targetElement = targetElementJquery[0];

       handler(targetElement);
     } : null;
  }
}
<|endoftext|>


<commit_before>import path from "path";

import _ from "lodash";
import Promise from "bluebird";

import { pluggable } from "pluggable";
import resolveModule from "./resolve";
import loadModule from "./load";
import hashModule from "./hash";
import parseModule from "./parse";
import transformModule from "./transform";
import updateRequires from "./update-requires";

/**
 * Given one or more module seeds, traverse their dependency graph, collecting any and
 * all dependency modules, and then parse, transform, and hash those modules.  Return
 * a promise that resolves to the full set of modules, once they have been correctly
 * gathered and compiled.
 *
 * @param  {Array}    moduleSeeds  Module seeds, i.e. modules that have not yet been
 *                                 populated with properties such as ast, `dependencies`,
 *                                 etc.  Module objects _should_ have path, rawSource,
 *                                 and namespace values.
 *
 * @return {Promise}               Resolves to array of all compiled modules.
 */
const compileModules = pluggable(function compileModules (moduleSeeds) {
  const modulesByAbsPath = this.cache.modulesByAbsPath;

  /**
   * Given a require string (or compatible value), attempt to resolve that
   * reference, generate a new seed module for that reference, and resolve to
   * that module, recursively compiled.
   *
   * @param  {String}  requireStr    Relative or absolute path.
   * @param  {String}  contextPath   Path from which relative paths should be resolved.
   * @param  {String}  contextNs     Default/originating namespace to use when resolving
   *                                 the require string.
   * @param  {String}  contextNsRoot Default/originating namespace root path to use
   *                                 when resolving the require string.
   *
   * @return {Promise}               Resolves to compiled module.
   */
  const getDependency = (requireStr, contextPath, contextNs, contextNsRoot) => {
    return this.resolveModule(requireStr, contextPath, contextNs, contextNsRoot)
      .then(compileModule.bind(this)) // eslint-disable-line no-use-before-define
      .then(childModule => [requireStr, childModule]);
  };

  /**
   * Given an array of dependencies that are guaranteed to have already been compiled
   * at the point of this function's invocation, generate a flattened list of
   * all modules dependencies.
   *
   * @param  {Array}  dependencies  Array of compiled modules.
   *
   * @return {Array}                Array of compiled modules (and their dependencies).
   */
  const getDeepDependencies = dependencies => _.chain(dependencies)
    .map(([, dep]) => dep.deepDependencies.concat(dep))
    .flatten()
    .value();

  /**
   * Given a module whose dependency references (like require strings) have been
   * determined, recursively compile all dependencies and return the module with
   * new dependency properties.
   *
   * @param  {Object}  module  Module for whom dependencies should be compiled.
   *
   * @return {Object}          Module with new dependency properties.
   */
  const generateDependencies = module => {
    const contextPath = path.dirname(module.path);
    const directDependencies = Promise.all(module.synchronousRequires.map(requireStr =>
      getDependency(requireStr, contextPath, module.ns, module.nsRoot)));

    return Promise.all([directDependencies, directDependencies.then(getDeepDependencies)])
      .then(([depTuples, deepDependencies]) => Object.assign({}, module, {
        // De-dupe any (deep-)dependencies by their hash.
        deepDependencies: _.chain(deepDependencies).indexBy("hash").values().value(),
        dependencies: _.chain(depTuples)
          .map(([, dependency]) => dependency)
          .indexBy("hash")
          .values()
          .value(),
        // Generate a mapping between the original require strings and the modules
        // they resolved to.
        dependenciesByInternalRef: _.object(depTuples)
      }));
  };

  /**
   * Takes in a seed module and returns a promise that resolves to a the same module
   * once it and its dependencies have been compiled.
   *
   * @param  {Object}  module  Seed module.
   *
   * @return {Promise}         Resolves to compiled module.
   */
  const compileModule = module => {
    if (module.path in modulesByAbsPath) {
      return modulesByAbsPath[module.path];
    }

    return modulesByAbsPath[module.path] = this.loadModule(module)
      .then(this.parseModule)
      .then(this.transformModule)
      .then(generateDependencies)
      .then(this.hashModule)
      .then(this.updateRequires);
  };

  return Promise.all(moduleSeeds.map(compileModule))
    .then(compiledSeedModules => _.chain(compiledSeedModules)
      .map(seedModule => seedModule.deepDependencies.concat(seedModule))
      .flatten()
      .uniq()
      .value()
    );
}, { resolveModule, loadModule, hashModule, parseModule, transformModule, updateRequires });

export default compileModules;
<commit_msg>Split `compileModules` into `compileModules`, `compileModule`, and `generateDependencies`.<commit_after>import path from "path";

import _ from "lodash";
import Promise from "bluebird";
import { pluggable } from "pluggable";

import resolveModule from "./resolve";
import loadModule from "./load";
import hashModule from "./hash";
import parseModule from "./parse";
import transformModule from "./transform";
import updateRequires from "./update-requires";

/**
 * Because the `compileModule` and `generateDependencies` functions interact
 * recursively, defining a stand-in pluggable for `compileModule` allows for
 * plugins to utilize `compileModule` from within an overridden `generateDependencies`.
 *
 * For true behavior, please see documentation for `compileModule`.
 *
 * @return {Promise}         Resolves to compiled module.
 */
const _compileModule = pluggable(function _compileModule () {
  return compileModule.apply(this, arguments); // eslint-disable-line no-use-before-define
});

/**
 * Given a module whose dependency references (like require strings) have been
 * determined, recursively compile all dependencies and return the module with
 * new dependency properties.
 *
 * @param  {Object}  module  Module for whom dependencies should be compiled.
 *
 * @return {Object}          Module with new dependency properties.
 */
const generateDependencies = pluggable(function generateDependencies (module) {

  // Given a require string or similar absolute/relative path reference, resolve
  // that reference and compile the dependency (recursively).
  const getDependency = (requireStr, contextPath, contextNs, contextNsRoot) => {
    return this.resolveModule(requireStr, contextPath, contextNs, contextNsRoot)
      .then(dependency => this._compileModule(dependency))
      .then(childModule => [requireStr, childModule]);
  };

  // Given an array of compiled module dependencies, generate a recursively flattened
  // list of all module dependencies.
  const getDeepDependencies = dependencies => _.chain(dependencies)
    .map(([, dep]) => dep.deepDependencies.concat(dep))
    .flatten()
    .value();

  const contextPath = path.dirname(module.path);
  const directDependencies = Promise.all(module.synchronousRequires.map(
    requireStr => getDependency(requireStr, contextPath, module.ns, module.nsRoot)
  ));

  return Promise.all([directDependencies, directDependencies.then(getDeepDependencies)])
    .then(([depTuples, deepDependencies]) => Object.assign({}, module, {
      // De-dupe any (deep-)dependencies by their hash.
      deepDependencies: _.chain(deepDependencies).indexBy("hash").values().value(),
      dependencies: _.chain(depTuples)
        .map(([, dependency]) => dependency)
        .indexBy("hash")
        .values()
        .value(),
      // Generate a mapping between the original require strings and the modules
      // they resolved to.
      dependenciesByInternalRef: _.object(depTuples)
    }));
}, { resolveModule, _compileModule });

/**
 * Given an unprocess module that has been loaded from disk, return a promise
 * that resolves to the same module in a processed/compiled state, and whose
 * dependencies have also been processed/compiled.
 *
 * @param  {Object}  module  Seed module.
 *
 * @return {Promise}         Resolves to compiled module.
 */
const compileModule = pluggable(function compileModule (module) {
  const modulesByAbsPath = this.cache.modulesByAbsPath;

  if (module.path in modulesByAbsPath) {
    return modulesByAbsPath[module.path];
  }

  return modulesByAbsPath[module.path] = this.loadModule(module)
    .then(this.parseModule)
    .then(this.transformModule)
    .then(this.generateDependencies)
    .then(this.hashModule)
    .then(this.updateRequires);
}, {
  loadModule,
  parseModule,
  transformModule,
  generateDependencies,
  hashModule,
  updateRequires
});

/**
 * Given one or more module seeds, traverse their dependency graph, collecting any and
 * all dependency modules, and then parse, transform, and hash those modules.  Return
 * a promise that resolves to the full set of modules, once they have been correctly
 * gathered and compiled.
 *
 * @param  {Array}    moduleSeeds  Module seeds, i.e. modules that have not yet been
 *                                 populated with properties such as ast, `dependencies`,
 *                                 etc.  Module objects _should_ have path, rawSource,
 *                                 and namespace values.
 *
 * @return {Promise}               Resolves to array of all compiled modules.
 */
const compileModules = pluggable(function compileModules (moduleSeeds) {
  return Promise.all(moduleSeeds.map(this.compileModule.bind(this)))
    .then(compiledSeedModules => _.chain(compiledSeedModules)
      .map(seedModule => seedModule.deepDependencies.concat(seedModule))
      .flatten()
      .uniq()
      .value()
    );
}, { compileModule });

export default compileModules;
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { findDOMNode } from 'react-dom';
import XboxSource from './XboxSource';
import PS4Source from './PS4Source';

const MARGIN = 30;

class DeviceSource extends Component {

  static propTypes = {
    layout: PropTypes.object.isRequired,
  }

  constructor(props) {
    super(props);
    this.state = {
      scale: 1.0,
      offsetX: 0,
      offsetY: 0,
    };
  }

  render() {
    return (

        {this.renderSource()}

    );
  }

  renderSource() {
    const { scale, offsetX, offsetY } = this.state;
    const scaleStyle = {
      transform: `scale(${this.state.scale})`,
      left: `${offsetX}px`,
      top: `${offsetY}px`,
    };
    const { view, device } = this.props.layout;
    const dragCtrlProps = { scale, view, index: -1 };
    switch (device) {
      case 'xbox':
        return <XboxSource scaleStyle={scaleStyle} dragCtrlProps={dragCtrlProps} view={view} />;
      case 'ps4':
        return <PS4Source scaleStyle={scaleStyle} dragCtrlProps={dragCtrlProps} view={view} />;
      default:
        return null;
    }
  }

  componentDidMount() {
    this.writeScale();
    window.addEventListener('resize', this.writeScale.bind(this));
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.writeScale.bind(this));
  }

  writeScale() {
    const thisEl = findDOMNode(this);
    const elRect = thisEl.getBoundingClientRect();
    const bgEl = thisEl.querySelector('.artboard-source .background');
    const margin = MARGIN * 2;
    const elW = elRect.width - margin;
    const elH = elRect.height - margin;
    const scaleW = elW / bgEl.clientWidth;
    const scaleH = elH / bgEl.clientHeight;
    const scale = Math.min(scaleW, scaleH);
    const offsetX = (elRect.width - (scale * bgEl.clientWidth)) / 2;
    const offsetY = (elRect.height - (scale * bgEl.clientHeight)) / 2;
    this.setState({ scale, offsetX, offsetY });
  }
}

export default DeviceSource;
<commit_msg>fix ui speed by decoupling render from ui update<commit_after>import React, { Component, PropTypes } from 'react';
import { findDOMNode } from 'react-dom';
import XboxSource from './XboxSource';
import PS4Source from './PS4Source';

const MARGIN = 30;

class DeviceSource extends Component {

  static propTypes = {
    layout: PropTypes.object.isRequired,
  }

  constructor(props) {
    super(props);
    this.state = {
      scale: 1.0,
      offsetX: 0,
      offsetY: 0,
      device: null,
    };
  }

  render() {
    return (

        {this.renderSource()}

    );
  }

  renderSource() {
    const { scale, offsetX, offsetY, device } = this.state;
    const scaleStyle = {
      transform: `scale(${this.state.scale})`,
      left: `${offsetX}px`,
      top: `${offsetY}px`,
    };
    const { view } = this.props.layout;
    const dragCtrlProps = { scale, view, index: -1 };
    switch (device) {
      case 'xbox':
        return <XboxSource scaleStyle={scaleStyle} dragCtrlProps={dragCtrlProps} view={view} />;
      case 'ps4':
        return <PS4Source scaleStyle={scaleStyle} dragCtrlProps={dragCtrlProps} view={view} />;
      default:
        return null;
    }
  }

  componentWillMount() {
    this.setState({ device: this.props.layout.device });
  }

  componentDidMount() {
    this.writeScale();
    window.addEventListener('resize', this.writeScale.bind(this));
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.writeScale.bind(this));
  }

  componentWillReceiveProps(nextProps) {
    console.log('componentWillReceiveProps')
    const d1 = this.props.layout.device;
    const d2 = nextProps.layout.device;
    if (d1 !== d2) {
      setTimeout(() => {
        this.setState({ device: d2 });
        this.writeScale();
      }, 1);
    }
  }

  writeScale() {
    const thisEl = findDOMNode(this);
    const elRect = thisEl.getBoundingClientRect();
    const bgEl = thisEl.querySelector('.artboard-source .background');
    const margin = MARGIN * 2;
    const elW = elRect.width - margin;
    const elH = elRect.height - margin;
    const scaleW = elW / bgEl.clientWidth;
    const scaleH = elH / bgEl.clientHeight;
    const scale = Math.min(scaleW, scaleH);
    const offsetX = (elRect.width - (scale * bgEl.clientWidth)) / 2;
    const offsetY = (elRect.height - (scale * bgEl.clientHeight)) / 2;
    this.setState({ scale, offsetX, offsetY });
  }
}

export default DeviceSource;
<|endoftext|>


<commit_before>import React from 'react';

/**
 * Download file link.
 *
 * @param props {object}
 * @param props.children {string|null} - Optional link text
 * @param props.data {object} - Data to be saved
 * @param props.filename {string}
 */
const DownloadFile = ({ children = 'Download file', data, filename = 'cliff-effects.json', ...otherProps }) => {
  const json = JSON.stringify(data);
  const blob = new Blob([json], { type: 'application/json' });
  const url = URL.createObjectURL(blob);

  return (
    <a {...otherProps} href={url} download={filename}>
      {children}
    </a>
  );
};

export default DownloadFile;
<commit_msg>Define DownloadFile as class to support refs<commit_after>import React from 'react';

/**
 * Download file link.
 *
 * @param props {object}
 * @param props.children {string|null} - Optional link text
 * @param props.data {object} - Data to be saved
 * @param props.filename {string}
 */
class DownloadFile extends React.Component {
  render() {
    const {
      children = 'Download file',
      data,
      filename = 'cliff-effects.json',
      ...otherProps
    } = this.props;

    const json = JSON.stringify(data);
    const blob = new Blob([json], { type: 'application/json' });
    const url = URL.createObjectURL(blob);

    return (
      <a {...otherProps} href={url} download={filename}>
        {children}
      </a>
    );
  }
}

export default DownloadFile;
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import { Link } from 'react-router-dom';
import ScheduleSlotTime from './ScheduleSlotTime';

function ScheduleSlot(props) {
  const slot = props.slot;
  const show = props.slot.show;

  const scheduleSlotClasses = cx(
    'ScheduleSlot',
    `ScheduleSlot--tone-${show.tone === 'dark' ? 'dark' : 'light'}`,
    {
      'ScheduleSlot--overnight': slot.is_overnight,
      'ScheduleSlot--on-air': props.onAir,
    }
  );

  return (

      <Link
        className="ScheduleSlot__inner"
        style={{ backgroundColor: show.brandColor }}
        to={`/shows/${show.slug}`}
      >
        <ScheduleSlotTime slot={slot} onAir={props.onAir} index={props.index} />

          {show.name}

      </Link>

  );
}

ScheduleSlot.propTypes = {
  calculateWidth: PropTypes.func.isRequired,
  onAir: PropTypes.bool.isRequired,
  slot: PropTypes.object.isRequired,
  index: PropTypes.number.isRequired,
};

export default ScheduleSlot;
<commit_msg>Add hash for schedule slot color<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import { Link } from 'react-router-dom';
import ScheduleSlotTime from './ScheduleSlotTime';

function ScheduleSlot(props) {
  const slot = props.slot;
  const show = props.slot.show;

  const scheduleSlotClasses = cx(
    'ScheduleSlot',
    `ScheduleSlot--tone-${show.tone === 'dark' ? 'dark' : 'light'}`,
    {
      'ScheduleSlot--overnight': slot.is_overnight,
      'ScheduleSlot--on-air': props.onAir,
    }
  );

  return (

      <Link
        className="ScheduleSlot__inner"
        style={{ backgroundColor: `#${show.brandColor}` }}
        to={`/shows/${show.slug}`}
      >
        <ScheduleSlotTime slot={slot} onAir={props.onAir} index={props.index} />

          {show.name}

      </Link>

  );
}

ScheduleSlot.propTypes = {
  calculateWidth: PropTypes.func.isRequired,
  onAir: PropTypes.bool.isRequired,
  slot: PropTypes.object.isRequired,
  index: PropTypes.number.isRequired,
};

export default ScheduleSlot;
<|endoftext|>


<commit_before>export const CURRENT_YEAR = (new Date()).getFullYear() - 1;

export const TOPICS = {
  javascript: 'JavaScript',
  css: 'CSS',
  ux: 'Design / UX',
  ruby: 'Ruby',
  ios: 'iOS / Swift',
  android: 'Android',
  data: 'Data / AI',
  php: 'PHP',
  elixir: 'Elixir',
  rust: 'Rust',
  golang: 'Go',
  devops: 'Dev Ops',
  'tech-comm': 'Technical communication',
  general: 'General',
};
<commit_msg>Renamed go to golang<commit_after>export const CURRENT_YEAR = (new Date()).getFullYear() - 1;

export const TOPICS = {
  javascript: 'JavaScript',
  css: 'CSS',
  ux: 'Design / UX',
  ruby: 'Ruby',
  ios: 'iOS / Swift',
  android: 'Android',
  data: 'Data / AI',
  php: 'PHP',
  elixir: 'Elixir',
  rust: 'Rust',
  golang: 'Golang',
  devops: 'Dev Ops',
  'tech-comm': 'Technical communication',
  general: 'General',
};
<|endoftext|>


<commit_before>import mainModule from './main';

angular.element(document).ready(function() {
  angular.bootstrap(document, [mainModule.name], { strictDi: true });
});
<commit_msg>JBDS-3834 Install fail - what next?<commit_after>import mainModule from './main';

angular.element(document).ready(function() {
  angular.bootstrap(document, [mainModule.name], { strictDi: true });
});

// Importing this adds a right-click menu with 'Inspect Element' option
const { remote } = require('electron');
const { Menu, MenuItem } = remote;

let rightClickPosition = null;

const menu = new Menu();
const toggleDevToolsItem = new MenuItem({
  label: 'Toggle Development Tools',
  accelerator: process.platform === 'darwin' ? 'Alt+Command+I' : 'Ctrl+Shift+I',
  click: () => {
    remote.getCurrentWindow().toggleDevTools();
  }
});
const inspectElementItem = new MenuItem({
  label: 'Inspect Element',
  click: () => {
    remote.getCurrentWindow().inspectElement(rightClickPosition.x, rightClickPosition.y);
  }
});
menu.append(toggleDevToolsItem);
menu.append(inspectElementItem);

window.addEventListener('contextmenu', (e) => {
  e.preventDefault();
  rightClickPosition = {x: e.x, y: e.y};
  menu.popup(remote.getCurrentWindow());
}, false);
<|endoftext|>


<commit_before>'use strict';

let co     = require('co');
let tls    = require('tls');
let url    = require('url');
let tty    = require('tty');
let stream = require('stream');
let cli    = require('heroku-cli-util');

function buildCommand(args) {
  if (args.length === 1) {
    // do not add quotes around arguments if there is only one argument
    // `heroku run "rake test"` should work like `heroku run rake test`
    return args[0];
  }
  let cmd = '';
  for (let arg of args) {
    if (arg.indexOf(' ') !== -1) {
      arg = `"${arg}"`;
    }
    cmd = cmd + " " + arg;
  }
  return cmd.trim();
}

function env (flag) {
  let c = {TERM: process.env.TERM};
  if (flag) {
    for (let v of flag.split(';')) {
      let m = v.match(/^\s*([\w\.\-]+)\s*=\s*(.*)?\s*$/);
      if (m) c[m[1]] = m[2];
      else cli.warn(`env flag ${v} appears invalid. Avoid using ';' in values.`);
    }
  }
  if (tty.isatty(1)) {
    c.COLUMNS = process.stdout.columns;
    c.LINES   = process.stdout.rows;
  }
  return c;
}

function startDyno(heroku, app, size, command, envFlag) {
  return heroku.apps(app).dynos().create({
    command:  command,
    attach:   true,
    size:     size,
    env:      env(envFlag),
  });
}

function readStdin(c) {
  let stdin = process.stdin;
  stdin.setEncoding('utf8');
  if (tty.isatty(0)) {
    stdin.setRawMode(true);
    stdin.pipe(c);
  } else {
    stdin.pipe(new stream.Transform({
      objectMode: true,
      transform: function (chunk, _, next) {
        c.write(chunk, next);
      },
      flush: function (done) {
        // TODO: this sends the EOF signal to rendezvous
        // too early if the stdin input is large
        // ideally rendezvous could wait to receive input
        // while it is processing
        c.write("\x04", done);
      }
    }));
  }
}

function readData(c) {
  let firstLine = true;
  return function (data) {
    // discard first line
    if (firstLine) {
      firstLine = false;
      readStdin(c);
      return;
    }
    data = data.replace('\r\n', '\n');
    let exitCode = data.match(/heroku-command-exit-status (\d+)/m);
    if (exitCode) {
      process.stdout.write(data.replace(/^heroku-command-exit-status \d+$\n?/m, ''));
      process.exit(exitCode[1]);
    }
    process.stdout.write(data);
  };
}

function attachToRendezvous(uri, opts) {
  let c = tls.connect(uri.port, uri.hostname, {rejectUnauthorized: opts.rejectUnauthorized});
  c.setTimeout(1000*60*20);
  c.setEncoding('utf8');
  c.on('connect', function () {
    c.write(uri.path.substr(1) + '\r\n');
  });
  c.on('data', readData(c));
  c.on('timeout', function () {
    cli.error('connection timed out');
    process.exit(opts.exitCode);
  });
  c.on('end', function () {
    process.exit(opts.exitCode);
  });
  c.on('error', cli.errorHandler());
  process.once('SIGINT', function () {
    c.end();
  });
}

function* run (context, heroku) {
  let command = buildCommand(context.args);
  if (!command) {
    cli.error('Usage: heroku run COMMAND\n\nExample: heroku run bash');
    process.exit(1);
  }
  let sh = context.flags['exit-code'] ? `${command}; echo heroku-command-exit-status $?` : command;
  let p = startDyno(heroku, context.app, context.flags.size, sh, context.flags.env);
  let dyno = yield cli.action(`Running ${cli.color.cyan.bold(command)} on ${context.app}`, {success: false}, p);
  console.error(`up, ${dyno.name}`);
  attachToRendezvous(url.parse(dyno.attach_url), {
    exitCode: context.flags['exit-code'] ? -1 : 0, // exit with -1 if the stream ends and heroku-command-exit-status is empty
    rejectUnauthorized: heroku.options.rejectUnauthorized,
  });
}

module.exports = {
  topic: 'run',
  description: 'run a one-off process inside a heroku dyno',
  help: `
Examples:

  $ heroku run bash
  Running bash on app... up, run.1
  ~ $

  $ heroku run -s hobby -- myscript.sh -a arg1 -s arg2
  Running myscript.sh -a arg1 -s arg2 on app... up, run.1
`,
  variableArgs: true,
  needsAuth: true,
  needsApp: true,
  flags: [
    {name: 'size', char: 's', description: 'dyno size', hasValue: true},
    {name: 'exit-code', description: 'passthrough the exit code of the remote command'},
    {name: 'env', description: "environment variables to set (use ';' to split multiple vars)", hasValue: true},
  ],
  run: cli.command(co.wrap(run))
};
<commit_msg>disconnect from dyno after 5 sigints<commit_after>'use strict';

let co     = require('co');
let tls    = require('tls');
let url    = require('url');
let tty    = require('tty');
let stream = require('stream');
let cli    = require('heroku-cli-util');

function buildCommand(args) {
  if (args.length === 1) {
    // do not add quotes around arguments if there is only one argument
    // `heroku run "rake test"` should work like `heroku run rake test`
    return args[0];
  }
  let cmd = '';
  for (let arg of args) {
    if (arg.indexOf(' ') !== -1) {
      arg = `"${arg}"`;
    }
    cmd = cmd + " " + arg;
  }
  return cmd.trim();
}

function env (flag) {
  let c = {TERM: process.env.TERM};
  if (flag) {
    for (let v of flag.split(';')) {
      let m = v.match(/^\s*([\w\.\-]+)\s*=\s*(.*)?\s*$/);
      if (m) c[m[1]] = m[2];
      else cli.warn(`env flag ${v} appears invalid. Avoid using ';' in values.`);
    }
  }
  if (tty.isatty(1)) {
    c.COLUMNS = process.stdout.columns;
    c.LINES   = process.stdout.rows;
  }
  return c;
}

function startDyno(heroku, app, size, command, envFlag) {
  return heroku.apps(app).dynos().create({
    command:  command,
    attach:   true,
    size:     size,
    env:      env(envFlag),
  });
}

function readStdin(c) {
  let stdin = process.stdin;
  stdin.setEncoding('utf8');
  if (tty.isatty(0)) {
    stdin.setRawMode(true);
    stdin.pipe(c);
    let sigints = 0;
    stdin.on('data', function (c) {
      if (c === '\u0003') sigints++;
      if (sigints >= 5) {
        cli.error('forcing dyno disconnect');
        process.exit(1);
      }
    });
  } else {
    stdin.pipe(new stream.Transform({
      objectMode: true,
      transform: function (chunk, _, next) {
        c.write(chunk, next);
      },
      flush: function (done) {
        // TODO: this sends the EOF signal to rendezvous
        // too early if the stdin input is large
        // ideally rendezvous could wait to receive input
        // while it is processing
        c.write("\x04", done);
      }
    }));
  }
}

function readData(c) {
  let firstLine = true;
  return function (data) {
    // discard first line
    if (firstLine) {
      firstLine = false;
      readStdin(c);
      return;
    }
    data = data.replace('\r\n', '\n');
    let exitCode = data.match(/heroku-command-exit-status (\d+)/m);
    if (exitCode) {
      process.stdout.write(data.replace(/^heroku-command-exit-status \d+$\n?/m, ''));
      process.exit(exitCode[1]);
    }
    process.stdout.write(data);
  };
}

function attachToRendezvous(uri, opts) {
  let c = tls.connect(uri.port, uri.hostname, {rejectUnauthorized: opts.rejectUnauthorized});
  c.setTimeout(1000*60*20);
  c.setEncoding('utf8');
  c.on('connect', function () {
    c.write(uri.path.substr(1) + '\r\n');
  });
  c.on('data', readData(c));
  c.on('timeout', function () {
    cli.error('connection timed out');
    process.exit(opts.exitCode);
  });
  c.on('end', function () {
    process.exit(opts.exitCode);
  });
  c.on('error', cli.errorHandler());
  process.once('SIGINT', function () {
    c.end();
  });
}

function* run (context, heroku) {
  let command = buildCommand(context.args);
  if (!command) {
    cli.error('Usage: heroku run COMMAND\n\nExample: heroku run bash');
    process.exit(1);
  }
  let sh = context.flags['exit-code'] ? `${command}; echo heroku-command-exit-status $?` : command;
  let p = startDyno(heroku, context.app, context.flags.size, sh, context.flags.env);
  let dyno = yield cli.action(`Running ${cli.color.cyan.bold(command)} on ${context.app}`, {success: false}, p);
  console.error(`up, ${dyno.name}`);
  attachToRendezvous(url.parse(dyno.attach_url), {
    exitCode: context.flags['exit-code'] ? -1 : 0, // exit with -1 if the stream ends and heroku-command-exit-status is empty
    rejectUnauthorized: heroku.options.rejectUnauthorized,
  });
}

module.exports = {
  topic: 'run',
  description: 'run a one-off process inside a heroku dyno',
  help: `
Examples:

  $ heroku run bash
  Running bash on app... up, run.1
  ~ $

  $ heroku run -s hobby -- myscript.sh -a arg1 -s arg2
  Running myscript.sh -a arg1 -s arg2 on app... up, run.1
`,
  variableArgs: true,
  needsAuth: true,
  needsApp: true,
  flags: [
    {name: 'size', char: 's', description: 'dyno size', hasValue: true},
    {name: 'exit-code', description: 'passthrough the exit code of the remote command'},
    {name: 'env', description: "environment variables to set (use ';' to split multiple vars)", hasValue: true},
  ],
  run: cli.command(co.wrap(run))
};
<|endoftext|>


<commit_before>const fs = require('fs')
const path = require('path')
const globby = require('globby')
const SVGO = require('svgo')

const buildit = require('@buildit/buildit')
const write = require('@buildit/write')

buildit(async () => {
  // uikit component
  await compileIcons({
    src: 'node_modules/uikit/src/images/components/*.svg',
    dest: 'icons/components'
  })

  await compileIcons({
    src: 'node_modules/uikit/src/images/icons/*.svg',
    dest: 'icons'
  })

  // custom icons
  await compileIcons({
    src: 'custom-icons/*.svg',
    dest: 'custom-icons/result'
  })
})

const svgo = new SVGO({
  plugins: [
    { removeTitle: true },
    { removeStyleElement: true },
    { removeComments: true },
    { removeDesc: true },
    { removeUselessDefs: true },
    { cleanupIDs: { remove: true } },
    { convertShapeToPath: true }
  ]
})

// the template file which to generate icon files
const iconTmpl =
`module.exports = {
  name: '#{name}',
  data: '#{data}',
  viewBox: '#{viewBox}',
  width: #{width},
  height: #{height}
}
`

async function compileIcons ({ src, dest }) {
  const srcIcons = await readIcons(src)
  const icons = []

  // for each icon
  for (let name in srcIcons) {
    let icon = srcIcons[name]

    // optimize
    icon = await optimizeIcon(icon)

    const data = icon.data.replace(/<svg[^>]+>/gi, '').replace(/<\/svg>/gi, '')
    const width = parseFloat(icon.info.width) || 20
    const height = parseFloat(icon.info.height) || 20

    const content = compileTmpl(iconTmpl, {
      name,
      data,
      width,
      height,
      viewBox: `0 0 ${width} ${height}`
    })

    // save file
    await write(`${dest}/${name}.js`, content)

    icons.push({ content, name })
  }

  return icons
}

async function readIcons (src) {
  const files = await globby(src, {
    nosort: true
  })

  return files.reduce((icons, file) => {
    const name = path.basename(file, '.svg')
    const data = fs.readFileSync(file).toString().trim().replace(/\n/g, '').replace(/>\s+</g, '><')
    icons[name] = data
    return icons
  }, {})
}

function optimizeIcon (icon) {
  return new Promise((resolve, reject) => {
    svgo.optimize(icon, result => {
      resolve(result)
    })
  })
}

function compileTmpl (content, data) {
  return content.replace(/#{(\w+)}/gi, function (match, name) {
    return data[name] ? data[name] : ''
  })
}
<commit_msg>fix icons build<commit_after>const fs = require('fs')
const path = require('path')
const globby = require('globby')
const SVGO = require('svgo')

const lumpit = require('@lump/it')
const write = require('@lump/write')

lumpit(async () => {
  // uikit component
  await compileIcons({
    src: 'node_modules/uikit/src/images/components/*.svg',
    dest: 'icons/components'
  })

  await compileIcons({
    src: 'node_modules/uikit/src/images/icons/*.svg',
    dest: 'icons'
  })

  // custom icons
  await compileIcons({
    src: 'custom-icons/*.svg',
    dest: 'custom-icons/result'
  })
})

const svgo = new SVGO({
  plugins: [
    { removeTitle: true },
    { removeStyleElement: true },
    { removeComments: true },
    { removeDesc: true },
    { removeUselessDefs: true },
    { cleanupIDs: { remove: true } },
    { convertShapeToPath: true }
  ]
})

// the template file which to generate icon files
const iconTmpl =
`module.exports = {
  name: '#{name}',
  data: '#{data}',
  viewBox: '#{viewBox}',
  width: #{width},
  height: #{height}
}
`

async function compileIcons ({ src, dest }) {
  const srcIcons = await readIcons(src)
  const icons = []

  // for each icon
  for (let name in srcIcons) {
    let icon = srcIcons[name]

    // optimize
    icon = await optimizeIcon(icon)

    const data = icon.data.replace(/<svg[^>]+>/gi, '').replace(/<\/svg>/gi, '')
    const width = parseFloat(icon.info.width) || 20
    const height = parseFloat(icon.info.height) || 20

    const content = compileTmpl(iconTmpl, {
      name,
      data,
      width,
      height,
      viewBox: `0 0 ${width} ${height}`
    })

    // save file
    await write(`${dest}/${name}.js`, content)

    icons.push({ content, name })
  }

  return icons
}

async function readIcons (src) {
  const files = await globby(src, {
    nosort: true
  })

  return files.reduce((icons, file) => {
    const name = path.basename(file, '.svg')
    const data = fs.readFileSync(file).toString().trim().replace(/\n/g, '').replace(/>\s+</g, '><')
    icons[name] = data
    return icons
  }, {})
}

function optimizeIcon (icon) {
  return new Promise((resolve, reject) => {
    svgo.optimize(icon, result => {
      resolve(result)
    })
  })
}

function compileTmpl (content, data) {
  return content.replace(/#{(\w+)}/gi, function (match, name) {
    return data[name] ? data[name] : ''
  })
}
<|endoftext|>