<commit_before>/*
 * Reloaded / hot swap API code: `lftp` channels control
 *
 * SECURITY NOTE: do not let raw strings to be passed to `lftp`
 *                to prevent shell/exec injections
 */

function suprolftpdChannels(ret, api, local, req, res, next){
var lftps = local.lftps, chs = local.cfg.channels

    if(!local.url){// init, if internal call
        return mkdirp(local.cfg.data_path, setup_channels)
    }
//
//proto: repair go (without renaming)
//       go -wait-for- go_ok    change status
//       og -wait-for- og_ok    change status fire event on end
//stop:  stop -wait-for stop_ok change status fire event
/* GLOB not GLOB:

GLOB: send, receive from all

glob - for every obj put a file for send
 run send lftpd for every object not glob
 run receive lftpd for every object not glob

one code for all, one lftpd config for all, diff on OBJ

one any non glob obj -- run one in out transport for self

*/

    switch(local.url.pathname){
        case '/get': ret.data = chs
            break
        /*case '/setup': ret.data = 'setup'
            setup_channels()
            break*/
        default:
            ret.success = !(ret.err = '!such_subapi: ' + local.url.pathname)
            log(ret.err)
    }
    return setImmediate(ret_data)// async always

function ret_data(){
    return res.json(ret)
}

function mkdirp(path, callback){
var d

    try {
        d = local.require.fs.statSync(path)
    } catch(ex){
        return local.require.mkdirp.mkdirp(path,
        function mkdirp_data_dir(err){
            if(err) throw err

            return callback()
        })
    }
    if(!d.isDirectory()){
        throw new Error('Is not a directory: ' + path)
    }
    return callback()
}

function pad(n){
    return n < 10 ? '0' + n : n
}

function setup_channels(){
var chancfg, f

    local.sh = '/bin/sh ./etc/lftpd.sh'.split(' ')// './' -> "$PWD"
    // address script file using crossplatform relative path
    local.sh[1] = '../../..' + local.cfg.PWD + local.sh[1]

    if('GLOB' == local.cfg.OBJ){
        for(f in chs){
            if(!f) throw new Error('FATAL lftp: object id is not defined')
            if(!(chancfg = chs[f])) continue// skip undefined configs
            if(f != chancfg.id) chancfg.id = f// assign correct 'id'

            if(chancfg.autorun){
                make_cwd_spwan_lftp(chancfg)
            } else {
                chancfg.sts = 'stop'
            }
        }
    } else {// for a remote non GLOB object its only transport must run
        chancfg = chs[local.cfg.OBJ]
        if(chancfg.autorun){
            make_cwd_spwan_lftp(chancfg)
        } else throw new Error('FATAL lftp: object id is not autorun')
    }
}

function make_cwd_spwan_lftp(chancfg){
var cwd = local.cfg.data_path + chancfg.id// -> $PWD/data/suprolftpd/GLOB

    return local.require.mkdirp.mkdirp(cwd, spawn_lftp_there)

    function spawn_lftp_there(err){
    var lftp

        if(err) throw err

        lftp = lftps[chancfg.id] = local.require.cp.spawn(
            process.cwd() + local.sh[0], local.sh.slice(1),{
                cwd:cwd,
                env:{
                    PATH: local.cfg.PATH,
                    SUPRO_OBJ: chancfg.id
                },
                detached: false,
                stdio:['pipe','pipe','pipe']
            }
        )
        if(!lftp.pid || lftp.exitCode){
            throw new Error('!FATAL spawn `lftp` exit code: ' + cmd.exitCode)
        }

        lftp.on('close',
        function on_lftp_close(code){
            log('$ `lftp` stop code: ', String(code))
            lftps[chancfg.id] = void 0

            chancfg.sts = 'quit: ' + code
            api.wes.broadcast('wes4store',{
                store: 'lftpd',
                data:[ chancfg ]
            })
        })
        lftp.stdout.on('data',
        function(chunck){
            log('out: ' + chunck)
        })
        lftp.stderr.on('data',
        function(chunck){
            chancfg.sts = 'errr'
            log('err:' + chunck)
        })
        chancfg.sts = 'runs pid: ' + lftp.pid
        log('^ `lftp` ' + chancfg.sts)
    }
}
}
return suprolftpdChannels(ret, api, local, req, res, next) || true// async always
<commit_msg>api '/suprolftpd/lib/cnl/do': start, echo, quit<commit_after>/*
 * Reloaded / hot swap API code: `lftp` channels control
 *
 * SECURITY NOTE: do not let raw strings to be passed to `lftp`
 *                to prevent shell/exec injections
 */

function suprolftpdChannels(ret, api, local, req, res, next){
var lftps = local.lftps, chs = local.cfg.channels

    if(!local.url){// init, if internal call
        return mkdirp(local.cfg.data_path, setup_channels)
    }
//
//proto: repair go (without renaming)
//       go -wait-for- go_ok    change status
//       og -wait-for- og_ok    change status fire event on end
//stop:  stop -wait-for stop_ok change status fire event
/* GLOB not GLOB:

GLOB: send, receive from all

glob - for every obj put a file for send
 run send lftpd for every object not glob
 run receive lftpd for every object not glob

one code for all, one lftpd config for all, diff on OBJ

one any non glob obj -- run one in out transport for self

*/
    if(!req.json) return next(new Error('arguments: JSON required'))

    switch(local.url.pathname){
    case '/get': ret.data = chs ;break
    case '/cmd': return cmd_channel()
    case '/do' : return do_channel()
    default:
        ret.success = !(ret.err = '!such_subapi: ' + local.url.pathname)
        log(ret.err)
    }
    return setImmediate(ret_data)// async always

function ret_data(){
    return res.json(ret)
}

function cmd_channel(){
    return res.json(ret)
}

function do_channel(){
var chancfg, lftp, what, err

    what = req.json
    chancfg = chs[what.id]
    lftp = lftps[what.id]
    /*
     * SECURITY NOTE: do not let raw strings to be passed to `lftp`
     *                to prevent shell/exec injections
     */
    switch(what.cmd){
    case 'echo':
        if(lftp && chancfg && chancfg.id){// use strong shell quotes
            return lftp.stdin.write("echo '" + chancfg.id + "'\n", 'utf8', on_done)
        } else {
            err = '!lftp runs || no config || id in config'
            break
        }
    case 'quit':
        if(!lftp){
            err = '!channel `id`="' + what.id + '": was not found in `lftps`'
            break
        }
        return lftp.stdin.write('quit\n', 'utf8', on_done)//???if long process of up/down????
    case 'start':
        if(!lftp && chancfg && (!chancfg.sts || 'quit' == chancfg.sts.slice(0, 4))){
            return make_cwd_spwan_lftp(chancfg, on_done)
        } else {
            err = '!lftp runs || no config || status = "quit"'
            break
        }
    }
    return next(new Error(err || '!no such `do` action'))

    function on_done(){
        log('chs sts:', chancfg.sts)
        ret.data = chancfg

        return res.json(ret)
    }
}

function mkdirp(path, callback){
var d

    try {
        d = local.require.fs.statSync(path)
    } catch(ex){
        return local.require.mkdirp.mkdirp(path,
        function mkdirp_data_dir(err){
            if(err) throw err

            return callback()
        })
    }
    if(!d.isDirectory()){
        throw new Error('Is not a directory: ' + path)
    }
    return callback()
}

function pad(n){
    return n < 10 ? '0' + n : n
}

function setup_channels(){
var chancfg, f

    local.sh = '/bin/sh ./etc/lftpd.sh'.split(' ')// './' -> "$PWD"
    // address script file using crossplatform relative path
    local.sh[1] = '../../..' + local.cfg.PWD + local.sh[1]

    if('GLOB' == local.cfg.OBJ){
        for(f in chs){
            if(!f) throw new Error('FATAL lftp: object id is not defined')
            if(!(chancfg = chs[f])) continue// skip undefined configs
            if(f != chancfg.id) chancfg.id = f// assign correct 'id'

            if(chancfg.autorun){
                make_cwd_spwan_lftp(chancfg)
            } else {
                chancfg.sts = 'stop'
            }
        }
    } else {// for a remote non GLOB object its only transport must run
        chancfg = chs[local.cfg.OBJ]
        if(chancfg.autorun){
            make_cwd_spwan_lftp(chancfg)
        } else throw new Error('FATAL lftp: object id is not autorun')
    }
}

function make_cwd_spwan_lftp(chancfg, cb){
var cwd = local.cfg.data_path + chancfg.id// -> $PWD/data/suprolftpd/GLOB

    return local.require.mkdirp.mkdirp(cwd, spawn_lftp_there)

    function spawn_lftp_there(err){
    var lftp

        if(err){
            if(cb) return cb(err)
            throw err
        }

        lftp = lftps[chancfg.id] = local.require.cp.spawn(
            process.cwd() + local.sh[0], local.sh.slice(1),{
                cwd:cwd,
                env:{
                    PATH: local.cfg.PATH,
                    SUPRO_OBJ: chancfg.id
                },
                detached: false,
                stdio:['pipe','pipe','pipe']
            }
        )
        if(!lftp.pid || lftp.exitCode){
            err = new Error('!FATAL spawn `lftp` exit code: ' + lftp.exitCode)
            if(cb) return cb(err)
            throw err
        }

        lftp.on('close',
        function on_lftp_close(code){
            log('$ `lftp` stop code: ', String(code))
            lftps[chancfg.id] = void 0

            chancfg.sts = 'quit: ' + code
            api.wes.broadcast('wes4store',{
                store: 'lftpd',
                data:[ chancfg ]
            })
        })
        lftp.stdout.on('data',
        function(chunck){
            log('out: ' + chunck)
        })
        lftp.stderr.on('data',
        function(chunck){
            chancfg.sts = 'errr'
            log('err:' + chunck)
        })
        chancfg.sts = 'runs pid: ' + lftp.pid
        log('^ `lftp` ' + chancfg.sts)

        return cb && cb()
    }
}
}
return suprolftpdChannels(ret, api, local, req, res, next) || true// async always
<|endoftext|>


<commit_before>'use strict';

var merge = require('lodash').merge;
var cssnano = require('gulp-cssnano');
var cssnext = require('postcss-cssnext');
var gulpif = require('gulp-if');
var importer = require('postcss-import');
var postcss = require('gulp-postcss');

var defaults = {
  dest: './dist',
  optimize: false,
  src: './src/main.css'
};

module.exports = function (gulp, options) {
  var opts = merge({}, defaults, options);
  var dest = opts.dest;
  var optimize = opts.optimize;
  var src = opts.src;

  gulp.task('css', function () {
    return gulp.src(src)
      .pipe(postcss([
        importer(),
        cssnext()
      ]))
      .pipe(gulpif(optimize, cssnano()))
      .pipe(gulp.dest(dest));
  });
};
<commit_msg>ES2015-ify css.js<commit_after>'use strict';

import {merge} from 'lodash';
import cssnano from 'gulp-cssnano';
import cssnext from 'postcss-cssnext';
import gulpif from 'gulp-if';
import importer from 'postcss-import';
import postcss from 'gulp-postcss';

const defaults = {
  dest: './dist',
  optimize: false,
  src: './src/main.css'
};

module.exports = (gulp, options) => {
  const opts = merge({}, defaults, options);
  const dest = opts.dest;
  const optimize = opts.optimize;
  const src = opts.src;

  gulp.task('css', () => {
    return gulp.src(src)
      .pipe(postcss([
        importer(),
        cssnext()
      ]))
      .pipe(gulpif(optimize, cssnano()))
      .pipe(gulp.dest(dest));
  });
};
<|endoftext|>


<commit_before>'use strict';
var Parser = require('./parser.js');
var Streamer = require('./streamer.js');

function reducer(item, memo, sep, prependSep) {
  var foo = ''
  , c = new RegExp(sep, 'g')
  , q = new RegExp('"', 'g')
  , n = new RegExp('\n', 'g');

  if (!item) {
    item = '';
  }
  if (typeof item != 'string') {
    var s = item.toString();
    if (s == '[object Object]') {
      item = JSON.stringify(item);
      if (item == '{}') {
        item = '';
      }
    }
    else {
      item = s;
    }
  }
  if (memo || prependSep) {
    foo = memo + sep;
  }
  if (item.search(c) >= 0 || item.search(q) >= 0 || item.search(n) >= 0) {
    foo += '"' + item.replace(q, '""') + '"';
  }
  else {
    foo += '' + item;
  }
  return foo;
}

exports.eol = "\r\n";
exports.separator = ",";

exports.detect = function (input)
{
  var separators = [{c: 0, v: ','}, {c: 0, v: ';'}, {c: 0, v: '|'}, {c: 0, v: '\t'}, {c: 0, v: ':'}, {c: 0, v: null}];
  separators.forEach(function (item, indice) {
      item.c += input.split(item.v).length;
    }
  );
  var max = 0;
  var separator = separators.reduce(function (prev, cur) {
      if (cur.c >= max) {
        max = cur.c;
        return cur.v;
      }
      else {
        return prev;
      }
    }, null
  );
  return separator;
}

exports.stringify = function (input, sep) {
  var ret = '';
  sep = sep || exports.separator;
  if (Array.isArray(input) && !Array.isArray(input[0])) {
    for (var loop = 0; loop < input.length; loop++) {
      ret = reducer(input[loop], ret, sep, loop > 0);
    }
    ret += exports.eol;
  }
  else if (Array.isArray(input) && Array.isArray(input[0])) {
    input.forEach(function (item, index) {
        ret += exports.stringify(item, sep);
      }
    );
  }
  else if (typeof input == 'object') {
    for (var key in input) {
      if (input.hasOwnProperty(key)) {
        ret = reducer(input[key], ret, sep);
      }
    }
    ret += exports.eol;
  }
  else {
    ret = reducer(input, ret, sep) + exports.eol;
  }
  return ret;
}

exports.parse = function (input, sep) {

  var output = [];
  exports.forEach(input, sep, function (row, index) {
      output.push(row);
    }
  )
  return output;
}

exports.forEach = function (input, sep, callback) {
  if (arguments.length < 3) {
    callback = sep;
    sep = ',';
  }
  var i = 0, s = 0, r;
  while (r = exports.read(input.slice(s), sep, function (fields) {
        callback(fields, i++);
      }
    )
  ) {
    s += r;
  }
}

exports.read = function (input, sep, callback) {
  if (arguments.length < 3) {
    callback = sep;
    sep = ',';
  }
  var csv = new Parser(input, sep);
  var fields = csv.Row();
  callback(fields);
  return csv.pointer;
}

exports.readAll = function (input, sep, callback) {
  if (arguments.length < 3) {
    callback = sep;
    sep = ',';
  }
  var csv = new Parser(input, sep);
  var rows = csv.File();
  var ret = 0;
  if (csv.pointer < input.length) {
    ret = csv.pointer;
  }
  else {
    rows.pop();
    ret = csv.linePointer;
  }
  callback(rows);
  return ret;
}

exports.fetch = function (input, sep) {
  var output;
  exports.read(input, sep, function (fields) {
      output = fields;
    }
  );
  return output;

}

exports.createStream = function (options) {
  return new Streamer(options);
}

<commit_msg>add readchunk<commit_after>'use strict';
var Parser = require('./parser.js');
var Streamer = require('./streamer.js');

function reducer(item, memo, sep, prependSep) {
  var foo = ''
  , c = new RegExp(sep, 'g')
  , q = new RegExp('"', 'g')
  , n = new RegExp('\n', 'g');

  if (!item) {
    item = '';
  }
  if (typeof item != 'string') {
    var s = item.toString();
    if (s == '[object Object]') {
      item = JSON.stringify(item);
      if (item == '{}') {
        item = '';
      }
    }
    else {
      item = s;
    }
  }
  if (memo || prependSep) {
    foo = memo + sep;
  }
  if (item.search(c) >= 0 || item.search(q) >= 0 || item.search(n) >= 0) {
    foo += '"' + item.replace(q, '""') + '"';
  }
  else {
    foo += '' + item;
  }
  return foo;
}

exports.eol = "\r\n";
exports.separator = ",";

exports.detect = function (input)
{
  var separators = [{c: 0, v: ','}, {c: 0, v: ';'}, {c: 0, v: '|'}, {c: 0, v: '\t'}, {c: 0, v: ':'}, {c: 0, v: null}];
  separators.forEach(function (item, indice) {
      item.c += input.split(item.v).length;
    }
  );
  var max = 0;
  var separator = separators.reduce(function (prev, cur) {
      if (cur.c >= max) {
        max = cur.c;
        return cur.v;
      }
      else {
        return prev;
      }
    }, null
  );
  return separator;
}

exports.stringify = function (input, sep) {
  var ret = '';
  sep = sep || exports.separator;
  if (Array.isArray(input) && !Array.isArray(input[0])) {
    for (var loop = 0; loop < input.length; loop++) {
      ret = reducer(input[loop], ret, sep, loop > 0);
    }
    ret += exports.eol;
  }
  else if (Array.isArray(input) && Array.isArray(input[0])) {
    input.forEach(function (item, index) {
        ret += exports.stringify(item, sep);
      }
    );
  }
  else if (typeof input == 'object') {
    for (var key in input) {
      if (input.hasOwnProperty(key)) {
        ret = reducer(input[key], ret, sep);
      }
    }
    ret += exports.eol;
  }
  else {
    ret = reducer(input, ret, sep) + exports.eol;
  }
  return ret;
}

exports.parse = function (input, sep) {

  var output = [];
  exports.forEach(input, sep, function (row, index) {
      output.push(row);
    }
  )
  return output;
}

exports.forEach = function (input, sep, callback) {
  if (arguments.length < 3) {
    callback = sep;
    sep = ',';
  }
  var i = 0, s = 0, r;
  while (r = exports.read(input.slice(s), sep, function (fields) {
        callback(fields, i++);
      }
    )
  ) {
    s += r;
  }
}

exports.read = function (input, sep, callback) {
  if (arguments.length < 3) {
    callback = sep;
    sep = ',';
  }
  var csv = new Parser(input, sep);
  var fields = csv.Row();
  callback(fields);
  return csv.pointer;
}

exports.readAll = function (input, sep, callback) {
  if (arguments.length < 3) {
    callback = sep;
    sep = ',';
  }
  var csv = new Parser(input, sep);
  var rows = csv.File();
  callback(rows);
  return csv.pointer;
}

exports.readChunk = function (input, sep, callback) {
  if (arguments.length < 3) {
    callback = sep;
    sep = ',';
  }
  var csv = new Parser(input, sep);
  var rows = csv.File();
  var ret = 0;
  if (csv.pointer < input.length) {
    ret = csv.pointer;
  }
  else {
    rows.pop();
    ret = csv.linePointer;
  }
  callback(rows);
  return ret;
}

exports.fetch = function (input, sep) {
  var output;
  exports.read(input, sep, function (fields) {
      output = fields;
    }
  );
  return output;

}

exports.createStream = function (options) {
  return new Streamer(options);
}

<|endoftext|>


<commit_before>'use strict'

const config = require('./config')

const knex = require('knex')
const bookshelf = require('bookshelf')

let DAO = module.exports

DAO = (function () {

	function DAO(options) {

		if (!(this instanceof DAO)) {
			return new DAO(args)
		}

		const adapter = options.adapter || 'postgres'

		this.connection = config[adapter]
		this.knex = knex(this.connection)
		this.bookshelf = bookshelf(this.knex)

		// Register global plugins
		this.bookshelf.plugin(require('bookshelf-scopes'))
		this.bookshelf.plugin(require('bookshelf-deep-changed'))
		this.bookshelf.plugin(require('bookshelf-relationships'))
		this.bookshelf.plugin(require('bookshelf-history'))
		this.bookshelf.plugin(require('bookshelf-postgis'))

		return this.bookshelf
	}

	// DAO.prototype.init = function (args) {
	// 	return this.bookshelf
	// }

	return DAO
}())<commit_msg>update dao lib<commit_after>'use strict'

const config = require('./config')

const knex = require('knex')
const bookshelf = require('bookshelf')

module.exports = (function () {

	function DAO(options) {

		if (!(this instanceof DAO)) {
			return new DAO(options)
		}

		options = options || {}

		const adapter = options.adapter || 'postgres'

		this.connection = config[adapter]
		this.knex = knex(this.connection)
		this.bookshelf = bookshelf(this.knex)

		// Register global plugins
		this.bookshelf.plugin(require('bookshelf-scopes'))
		this.bookshelf.plugin(require('bookshelf-deep-changed'))
		this.bookshelf.plugin(require('bookshelf-relationships'))
		this.bookshelf.plugin(require('bookshelf-history'))
			// this.bookshelf.plugin(require('../plugins/bookshelf-postgis'))
	}

	DAO.prototype.init = function (args) {
		return this.bookshelf
	}

	return DAO
}())<|endoftext|>


<commit_before>'use strict';

(function () {

  module.exports = [
    {
      name: 'Canvas size',
      methods: [
        {
          name: 'setSize',
          description: ''
        },
        {
          name: 'getSize',
          description: ''
        },
        {
          name: 'setWidth',
          description: ''
        },
        {
          name: 'getWidth',
          description: ''
        },
        {
          name: 'setHeight',
          description: ''
        },
        {
          name: 'getHeight',
          description: ''
        }
      ]
    },
    {
      name: 'Context',
      methods: [
        {
          name: 'getContext',
          description: ''
        },
        {
          name: 'getContextType',
          description: ''
        },
        {
          name: 'getContextAttributes',
          description: ''
        }
      ]
    },
    {
      name: 'Solid Shapes',
      methods: [
        {
          name: 'plotBurst',
          description: ''
        },
        {
          name: 'strokeBurst',
          description: ''
        },
        {
          name: 'fillBurst',
          description: ''
        },
        {
          name: 'plotCircle',
          description: ''
        },
        {
          name: 'strokeCircle',
          description: ''
        },
        {
          name: 'fillCircle',
          description: ''
        },
        {
          name: 'plotClosedPath',
          description: ''
        },
        {
          name: 'strokeClosedPath',
          description: ''
        },
        {
          name: 'fillClosedPath',
          description: ''
        },
        {
          name: 'plotPixel',
          description: ''
        },
        {
          name: 'strokePixel',
          description: ''
        },
        {
          name: 'fillPixel',
          description: ''
        },
        {
          name: 'plotPoly',
          description: ''
        },
        {
          name: 'strokePoly',
          description: ''
        },
        {
          name: 'fillPoly',
          description: ''
        },
        {
          name: 'plotRect',
          description: ''
        },
        {
          name: 'strokeRect',
          description: ''
        },
        {
          name: 'fillRect',
          description: ''
        },
        {
          name: 'plotRoundedRect',
          description: ''
        },
        {
          name: 'strokeRoundedRect',
          description: ''
        },
        {
          name: 'fillRoundedRect',
          description: ''
        },
        {
          name: 'plotStar',
          description: ''
        },
        {
          name: 'strokeStar',
          description: ''
        },
        {
          name: 'fillStar',
          description: ''
        }
      ]
    },
    {
      name: 'Open Shapes',
      methods: [
        {
          name: 'plotLine',
          description: ''
        },
        {
          name: 'strokeLine',
          description: ''
        },
        {
          name: 'plotLength',
          description: ''
        },
        {
          name: 'strokeLength',
          description: ''
        },
        {
          name: 'plotPath',
          description: ''
        },
        {
          name: 'strokePath',
          description: ''
        },
        {
          name: 'fillPath',
          description: ''
        }
      ]
    },
    {
      name: 'Paths',
      methods: [
        {
          name: 'plotArc',
          description: ''
        },
        {
          name: 'strokeArc',
          description: ''
        },
        {
          name: 'fillArc',
          description: ''
        },
        {
          name: 'plotEllipse',
          description: ''
        },
        {
          name: 'strokeEllipse',
          description: ''
        },
        {
          name: 'fillEllipse',
          description: ''
        }
      ]
    },
    {
      name: 'Text',
      methods: [
        {
          name: 'strokeText',
          description: ''
        },
        {
          name: 'fillText',
          description: ''
        }
      ]
    },
    {
      name: 'Fonts',
      methods: [
        {
          name: 'setFont',
          description: ''
        },
        {
          name: 'getFont',
          description: ''
        },
        {
          name: 'setFontFamily',
          description: ''
        },
        {
          name: 'getFontFamily',
          description: ''
        },
        {
          name: 'setFontSize',
          description: ''
        },
        {
          name: 'getFontSize',
          description: ''
        },
        {
          name: 'setFontStyle',
          description: ''
        },
        {
          name: 'getFontStyle',
          description: ''
        },
        {
          name: 'setFontVariant',
          description: ''
        },
        {
          name: 'getFontVariant',
          description: ''
        },
        {
          name: 'setFontWeight',
          description: ''
        },
        {
          name: 'getFontWeight',
          description: ''
        }
      ]
    },
    {
      name: 'Text Alignment',
      methods: [
        {
          name: 'setTextAlign',
          description: ''
        },
        {
          name: 'getTextAlign',
          description: ''
        },
        {
          name: 'setTextBaseline',
          description: ''
        },
        {
          name: 'getTextBaseline',
          description: ''
        }
      ]
    },
    {
      name: 'Measure Text',
      methods: [
        {
          name: 'getTextSize',
          description: ''
        }
      ]
    },
    {
      name: 'Stroke Styles',
      methods: [
        {
          name: 'stroke',
          description: ''
        },
        {
          name: 'setStroke',
          description: ''
        },
        {
          name: 'getStroke',
          description: ''
        },
        {
          name: 'setStrokeCap',
          description: ''
        },
        {
          name: 'getStrokeCap',
          description: ''
        },
        {
          name: 'setStrokeDash',
          description: ''
        },
        {
          name: 'getStrokeDash',
          description: ''
        },
        {
          name: 'setStrokeDashOffset',
          description: ''
        },
        {
          name: 'getStrokeDashOffset',
          description: ''
        },
        {
          name: 'setStrokeJoin',
          description: ''
        },
        {
          name: 'getStrokeJoin',
          description: ''
        },
        {
          name: 'setStrokeWidth',
          description: ''
        },
        {
          name: 'getStrokeWidth',
          description: ''
        },
        {
          name: 'setMiterLimit',
          description: ''
        },
        {
          name: 'getMiterLimit',
          description: ''
        }
      ]
    },
    {
      name: 'Fill styles',
      methods: [
        {
          name: 'fill',
          description: ''
        },
        {
          name: 'fillCanvas',
          description: ''
        },
        {
          name: 'clearRect',
          description: ''
        },
        {
          name: 'clearCanvas',
          description: ''
        },
        {
          name: 'setFill',
          description: ''
        },
        {
          name: 'getFill',
          description: ''
        },
        {
          name: 'createLinearGradient',
          description: ''
        },
        {
          name: 'createRadialGradient',
          description: ''
        },
        {
          name: 'createPattern',
          description: ''
        },
        {
          name: 'drawImage',
          description: ''
        }
      ]
    },
    {
      name: 'Image Data',
      methods: [
        {
          name: 'getDataURL',
          description: ''
        },
        {
          name: 'createImageData',
          description: ''
        },
        {
          name: 'getImageData',
          description: ''
        },
        {
          name: 'putImageData',
          description: ''
        },
        {
          name: 'getPixelData',
          description: ''
        },
        {
          name: 'getPixelColor',
          description: ''
        }
      ]
    },
    {
      name: 'Color Helpers',
      methods: [
        {
          name: 'createHSL',
          description: ''
        },
        {
          name: 'createHSLA',
          description: ''
        },
        {
          name: 'createRGB',
          description: ''
        },
        {
          name: 'createRGBA',
          description: ''
        },
        {
          name: 'getHSLFromHSLA',
          description: ''
        },
        {
          name: 'getRGBFromRGBA',
          description: ''
        }
      ]
    },
    {
      name: 'Converting Sizes',
      methods: [
        {
          name: 'getFractionFromPercent',
          description: ''
        },
        {
          name: 'getPercentFromFraction',
          description: ''
        },
        {
          name: 'getFractionOfWidth',
          description: ''
        },
        {
          name: 'getFractionOfHeight',
          description: ''
        },
        {
          name: 'getPercentOfWidth',
          description: ''
        },
        {
          name: 'getPercentOfHeight',
          description: ''
        },
        {
          name: 'getDistance',
          description: ''
        }
      ]
    },
    {
      name: 'Converting Angles',
      methods: [
        {
          name: 'getRadiansFromDegrees',
          description: ''
        },
        {
          name: 'getDegreesFromRadians',
          description: ''
        },
        {
          name: 'getAngle',
          description: ''
        }
      ]
    },
    {
      name: 'Path Plotting',
      methods: [
        {
          name: 'beginPath',
          description: ''
        },
        {
          name: 'closePath',
          description: ''
        },
        {
          name: 'moveTo',
          description: ''
        },
        {
          name: 'lineTo',
          description: ''
        },
        {
          name: 'arcTo',
          description: ''
        },
        {
          name: 'bezierCurveTo',
          description: ''
        },
        {
          name: 'quadraticCurveTo',
          description: ''
        }
      ]
    },
    {
      name: 'Canvas State',
      methods: [
        {
          name: 'save',
          description: ''
        },
        {
          name: 'restore',
          description: ''
        },
        {
          name: 'rotate',
          description: ''
        },
        {
          name: 'scale',
          description: ''
        },
        {
          name: 'translate',
          description: ''
        },
        {
          name: 'transform',
          description: ''
        },
        {
          name: 'setTransform',
          description: ''
        },
        {
          name: 'resetTransform',
          description: ''
        },
        {
          name: 'clip',
          description: ''
        },
        {
          name: 'setOpacity',
          description: ''
        },
        {
          name: 'getOpacity',
          description: ''
        },
        {
          name: 'setCompositeOperation',
          description: ''
        },
        {
          name: 'getCompositeOperation',
          description: ''
        },
        {
          name: 'setImageSmoothing',
          description: ''
        },
        {
          name: 'getImageSmoothing',
          description: ''
        },
        {
          name: 'setShadowBlur',
          description: ''
        },
        {
          name: 'getShadowBlur',
          description: ''
        },
        {
          name: 'setShadowColor',
          description: ''
        },
        {
          name: 'getShadowColor',
          description: ''
        },
        {
          name: 'setShadowOffsetX',
          description: ''
        },
        {
          name: 'getShadowOffsetX',
          description: ''
        },
        {
          name: 'setShadowOffsetY',
          description: ''
        },
        {
          name: 'getShadowOffsetY',
          description: ''
        }
      ]
    },
    {
      name: 'Misc',
      methods: [
        {
          name: 'drawFocusIfNeeded',
          description: ''
        },
        {
          name: 'isPointInPath',
          description: ''
        },
        {
          name: 'isPointInStroke',
          description: ''
        }
      ]
    }
  ];

})();
<commit_msg>Canvas size arguments<commit_after>'use strict';

(function () {

  var types = {
    number: 'number',
    boolean: 'boolean',
    string: 'string',
    object: 'object',
    array: 'array'
  };

  module.exports = [
    {
      name: 'Canvas size',
      methods: [
        {
          name: 'setSize',
          arguments: [
            {
              name: 'width',
              type: types.number
            },
            {
              name: 'height',
              type: types.number
            }
          ],
          description: ''
        },
        {
          name: 'getSize',
          description: ''
        },
        {
          name: 'setWidth',
          description: '',
          arguments: [
            {
              name: 'width',
              type: types.number
            }
          ]
        },
        {
          name: 'getWidth',
          description: ''
        },
        {
          name: 'setHeight',
          description: '',
          arguments: [
            {
              name: 'height',
              type: types.number
            }
          ]
        },
        {
          name: 'getHeight',
          description: ''
        }
      ]
    },
    {
      name: 'Context',
      methods: [
        {
          name: 'getContext',
          description: ''
        },
        {
          name: 'getContextType',
          description: ''
        },
        {
          name: 'getContextAttributes',
          description: ''
        }
      ]
    },
    {
      name: 'Solid Shapes',
      methods: [
        {
          name: 'plotBurst',
          description: ''
        },
        {
          name: 'strokeBurst',
          description: ''
        },
        {
          name: 'fillBurst',
          description: ''
        },
        {
          name: 'plotCircle',
          description: ''
        },
        {
          name: 'strokeCircle',
          description: ''
        },
        {
          name: 'fillCircle',
          description: ''
        },
        {
          name: 'plotClosedPath',
          description: ''
        },
        {
          name: 'strokeClosedPath',
          description: ''
        },
        {
          name: 'fillClosedPath',
          description: ''
        },
        {
          name: 'plotPixel',
          description: ''
        },
        {
          name: 'strokePixel',
          description: ''
        },
        {
          name: 'fillPixel',
          description: ''
        },
        {
          name: 'plotPoly',
          description: ''
        },
        {
          name: 'strokePoly',
          description: ''
        },
        {
          name: 'fillPoly',
          description: ''
        },
        {
          name: 'plotRect',
          description: ''
        },
        {
          name: 'strokeRect',
          description: ''
        },
        {
          name: 'fillRect',
          description: ''
        },
        {
          name: 'plotRoundedRect',
          description: ''
        },
        {
          name: 'strokeRoundedRect',
          description: ''
        },
        {
          name: 'fillRoundedRect',
          description: ''
        },
        {
          name: 'plotStar',
          description: ''
        },
        {
          name: 'strokeStar',
          description: ''
        },
        {
          name: 'fillStar',
          description: ''
        }
      ]
    },
    {
      name: 'Open Shapes',
      methods: [
        {
          name: 'plotLine',
          description: ''
        },
        {
          name: 'strokeLine',
          description: ''
        },
        {
          name: 'plotLength',
          description: ''
        },
        {
          name: 'strokeLength',
          description: ''
        },
        {
          name: 'plotPath',
          description: ''
        },
        {
          name: 'strokePath',
          description: ''
        },
        {
          name: 'fillPath',
          description: ''
        }
      ]
    },
    {
      name: 'Paths',
      methods: [
        {
          name: 'plotArc',
          description: ''
        },
        {
          name: 'strokeArc',
          description: ''
        },
        {
          name: 'fillArc',
          description: ''
        },
        {
          name: 'plotEllipse',
          description: ''
        },
        {
          name: 'strokeEllipse',
          description: ''
        },
        {
          name: 'fillEllipse',
          description: ''
        }
      ]
    },
    {
      name: 'Text',
      methods: [
        {
          name: 'strokeText',
          description: ''
        },
        {
          name: 'fillText',
          description: ''
        }
      ]
    },
    {
      name: 'Fonts',
      methods: [
        {
          name: 'setFont',
          description: ''
        },
        {
          name: 'getFont',
          description: ''
        },
        {
          name: 'setFontFamily',
          description: ''
        },
        {
          name: 'getFontFamily',
          description: ''
        },
        {
          name: 'setFontSize',
          description: ''
        },
        {
          name: 'getFontSize',
          description: ''
        },
        {
          name: 'setFontStyle',
          description: ''
        },
        {
          name: 'getFontStyle',
          description: ''
        },
        {
          name: 'setFontVariant',
          description: ''
        },
        {
          name: 'getFontVariant',
          description: ''
        },
        {
          name: 'setFontWeight',
          description: ''
        },
        {
          name: 'getFontWeight',
          description: ''
        }
      ]
    },
    {
      name: 'Text Alignment',
      methods: [
        {
          name: 'setTextAlign',
          description: ''
        },
        {
          name: 'getTextAlign',
          description: ''
        },
        {
          name: 'setTextBaseline',
          description: ''
        },
        {
          name: 'getTextBaseline',
          description: ''
        }
      ]
    },
    {
      name: 'Measure Text',
      methods: [
        {
          name: 'getTextSize',
          description: ''
        }
      ]
    },
    {
      name: 'Stroke Styles',
      methods: [
        {
          name: 'stroke',
          description: ''
        },
        {
          name: 'setStroke',
          description: ''
        },
        {
          name: 'getStroke',
          description: ''
        },
        {
          name: 'setStrokeCap',
          description: ''
        },
        {
          name: 'getStrokeCap',
          description: ''
        },
        {
          name: 'setStrokeDash',
          description: ''
        },
        {
          name: 'getStrokeDash',
          description: ''
        },
        {
          name: 'setStrokeDashOffset',
          description: ''
        },
        {
          name: 'getStrokeDashOffset',
          description: ''
        },
        {
          name: 'setStrokeJoin',
          description: ''
        },
        {
          name: 'getStrokeJoin',
          description: ''
        },
        {
          name: 'setStrokeWidth',
          description: ''
        },
        {
          name: 'getStrokeWidth',
          description: ''
        },
        {
          name: 'setMiterLimit',
          description: ''
        },
        {
          name: 'getMiterLimit',
          description: ''
        }
      ]
    },
    {
      name: 'Fill styles',
      methods: [
        {
          name: 'fill',
          description: ''
        },
        {
          name: 'fillCanvas',
          description: ''
        },
        {
          name: 'clearRect',
          description: ''
        },
        {
          name: 'clearCanvas',
          description: ''
        },
        {
          name: 'setFill',
          description: ''
        },
        {
          name: 'getFill',
          description: ''
        },
        {
          name: 'createLinearGradient',
          description: ''
        },
        {
          name: 'createRadialGradient',
          description: ''
        },
        {
          name: 'createPattern',
          description: ''
        },
        {
          name: 'drawImage',
          description: ''
        }
      ]
    },
    {
      name: 'Image Data',
      methods: [
        {
          name: 'getDataURL',
          description: ''
        },
        {
          name: 'createImageData',
          description: ''
        },
        {
          name: 'getImageData',
          description: ''
        },
        {
          name: 'putImageData',
          description: ''
        },
        {
          name: 'getPixelData',
          description: ''
        },
        {
          name: 'getPixelColor',
          description: ''
        }
      ]
    },
    {
      name: 'Color Helpers',
      methods: [
        {
          name: 'createHSL',
          description: ''
        },
        {
          name: 'createHSLA',
          description: ''
        },
        {
          name: 'createRGB',
          description: ''
        },
        {
          name: 'createRGBA',
          description: ''
        },
        {
          name: 'getHSLFromHSLA',
          description: ''
        },
        {
          name: 'getRGBFromRGBA',
          description: ''
        }
      ]
    },
    {
      name: 'Converting Sizes',
      methods: [
        {
          name: 'getFractionFromPercent',
          description: ''
        },
        {
          name: 'getPercentFromFraction',
          description: ''
        },
        {
          name: 'getFractionOfWidth',
          description: ''
        },
        {
          name: 'getFractionOfHeight',
          description: ''
        },
        {
          name: 'getPercentOfWidth',
          description: ''
        },
        {
          name: 'getPercentOfHeight',
          description: ''
        },
        {
          name: 'getDistance',
          description: ''
        }
      ]
    },
    {
      name: 'Converting Angles',
      methods: [
        {
          name: 'getRadiansFromDegrees',
          description: ''
        },
        {
          name: 'getDegreesFromRadians',
          description: ''
        },
        {
          name: 'getAngle',
          description: ''
        }
      ]
    },
    {
      name: 'Path Plotting',
      methods: [
        {
          name: 'beginPath',
          description: ''
        },
        {
          name: 'closePath',
          description: ''
        },
        {
          name: 'moveTo',
          description: ''
        },
        {
          name: 'lineTo',
          description: ''
        },
        {
          name: 'arcTo',
          description: ''
        },
        {
          name: 'bezierCurveTo',
          description: ''
        },
        {
          name: 'quadraticCurveTo',
          description: ''
        }
      ]
    },
    {
      name: 'Canvas State',
      methods: [
        {
          name: 'save',
          description: ''
        },
        {
          name: 'restore',
          description: ''
        },
        {
          name: 'rotate',
          description: ''
        },
        {
          name: 'scale',
          description: ''
        },
        {
          name: 'translate',
          description: ''
        },
        {
          name: 'transform',
          description: ''
        },
        {
          name: 'setTransform',
          description: ''
        },
        {
          name: 'resetTransform',
          description: ''
        },
        {
          name: 'clip',
          description: ''
        },
        {
          name: 'setOpacity',
          description: ''
        },
        {
          name: 'getOpacity',
          description: ''
        },
        {
          name: 'setCompositeOperation',
          description: ''
        },
        {
          name: 'getCompositeOperation',
          description: ''
        },
        {
          name: 'setImageSmoothing',
          description: ''
        },
        {
          name: 'getImageSmoothing',
          description: ''
        },
        {
          name: 'setShadowBlur',
          description: ''
        },
        {
          name: 'getShadowBlur',
          description: ''
        },
        {
          name: 'setShadowColor',
          description: ''
        },
        {
          name: 'getShadowColor',
          description: ''
        },
        {
          name: 'setShadowOffsetX',
          description: ''
        },
        {
          name: 'getShadowOffsetX',
          description: ''
        },
        {
          name: 'setShadowOffsetY',
          description: ''
        },
        {
          name: 'getShadowOffsetY',
          description: ''
        }
      ]
    },
    {
      name: 'Misc',
      methods: [
        {
          name: 'drawFocusIfNeeded',
          description: ''
        },
        {
          name: 'isPointInPath',
          description: ''
        },
        {
          name: 'isPointInStroke',
          description: ''
        }
      ]
    }
  ];

})();
<|endoftext|>


<commit_before>const fs = require('fs');
const util = require('util');

const xml2js = require('xml2js');

const wfg = {};

wfg.ProtocolParser = class {

    _parseItfRequest(out, itfRequest, opcode) {
        const reqName = itfRequest.$.name;

        //function docs
        const description = itfRequest.description;
        description.forEach((val) => {
            out.write("\t/**\n");
            if (val.hasOwnProperty("_")) {
                val._.split("\n").forEach((line) => {
                    out.write("\t *" + line + "\n");
                });
            }

            if (itfRequest.hasOwnProperty("arg")) {
                const reqArgs = itfRequest.arg;
                out.write("\t *\n");
                reqArgs.forEach((arg) => {
                    const argDescription = arg.$.summary;
                    const argName = arg.$.name;
                    out.write(util.format("\t * @param %s %s \n", argName, argDescription));
                });
                out.write("\t *\n");
            }

            out.write("\t */\n");
        });

        //function
        out.write(util.format("\t%s(", reqName));
        if (itfRequest.hasOwnProperty("arg")) {
            const reqArgs = itfRequest.arg;
            for (let i = 0; i < reqArgs.length; i++) {
                const arg = reqArgs[i];
                const argName = arg.$.name;
                if (i !== 0) {
                    out.write(", ");
                }
                out.write(argName);
            }
        }
        out.write("){\n");
        out.write(util.format("\t\tthis._connection._marshall(this._id, %d, [", opcode));

        //function args

        out.write(util.format("]);\n"));
        out.write("\t}\n");
    }

    _parseInterface(out, protocolItf) {
        const itfName = protocolItf.$.name;
        const itfVersion = protocolItf.$.version;

        console.log(util.format("Processing interface %s v%d", itfName, itfVersion));

        //if version is 1, we extends from WObject, else we extend from the previous version.
        for (let i = 1; i <= itfVersion; i++) {

            //class docs
            const description = protocolItf.description;
            description.forEach((val) => {
                out.write("/**\n");
                if (val.hasOwnProperty("_")) {
                    val._.split("\n").forEach((line) => {
                        out.write(" *" + line + "\n");
                    });
                }
                out.write(" */\n");
            });

            //class
            const className = util.format("%sV%d", itfName, i);
            if (i === 1) {
                out.write(util.format("wfc.%s = class %s extends wfc.WObject {\n", className, className));
            } else {
                out.write(util.format("wfc.%s = class %s extends wfc.%sV%d {\n", className, className, itfName, i - 1));
            }

            //interface can have no requests, so we need to check for it's absence.
            if (protocolItf.hasOwnProperty("request")) {
                const itfRequests = protocolItf.request;
                for (let i = 0; i < itfRequests.length; i++) {
                    this._parseItfRequest(out, itfRequests[i], i + 1);
                }
            }

            out.write("};\n");
        }
    }

    _parseProtocol(jsonProtocol) {
        const protocolName = jsonProtocol.protocol.$.name;
        const out = fs.createWriteStream(util.format("westfield-client-%s.js", protocolName));
        out.on('open', (fd) => {
            out.write("/*\n");
            jsonProtocol.protocol.copyright.forEach((val) => {
                val.split("\n").forEach((line) => {
                    out.write(" *" + line + "\n");
                });
            });
            out.write(" */\n");

            jsonProtocol.protocol.interface.forEach((itf) => {
                this._parseInterface(out, itf);
            });
        });
    }

    parse() {
        fs.readFile(this.protocolFile, (err, data) => {
            if (err) throw err;
            new xml2js.Parser().parseString(data, (err, result) => {
                if (err) throw err;

                //uncomment to see the protocol as json output
                //console.log(util.inspect(result, false, null));

                this._parseProtocol(result);
                console.log('Done');
            });
        });
    }

    constructor(protocolFile) {
        this.protocolFile = protocolFile;
    }
}

new wfg.ProtocolParser('/usr/share/wayland/wayland.xml').parse();

<commit_msg>generate arguments for marshalling<commit_after>const fs = require('fs');
const util = require('util');

const xml2js = require('xml2js');

const wfg = {};

wfg.ProtocolParser = class {

    //TODO remove
    ["uint"](argName, optional) {
        return {
            jsType: optional ? "?Number" : "Number",
            marshall: optional ? util.format("wfc._intOptional(%s)", argName) : util.format("wfc._int(%s)", argName)
        };
    }

    //TODO remove
    ["fixed"](argName, optional) {
        return {
            jsType: optional ? "?Number" : "Number",
            marshall: optional ? util.format("wfc._floatOptional(%s)", argName) : util.format("wfc._float(%s)", argName)
        };
    }

    //TODO remove
    ["fd"](argName, optional) {
        return {
            jsType: optional ? "?Number" : "Number",
            marshall: optional ? util.format("wfc._intOptional(%s)", argName) : util.format("wfc._int(%s)", argName)
        };
    }

    ["int"](argName, optional) {
        return {
            jsType: optional ? "?Number" : "Number",
            marshall: optional ? util.format("wfc._intOptional(%s)", argName) : util.format("wfc._int(%s)", argName)
        };
    }

    ["float"](argName, optional) {
        return {
            jsType: optional ? "?Number" : "Number",
            marshall: optional ? util.format("wfc._floatOptional(%s)", argName) : util.format("wfc._float(%s)", argName)
        };
    }

    ["double"](argName, optional) {
        return {
            jsType: optional ? "?Number" : "Number",
            marshall: optional ? util.format("wfc._doubleOptional(%s)", argName) : util.format("wfc._double(%s)", argName)
        };
    }

    ["object"](argName, optional) {
        return {
            jsType: optional ? "?*" : "*",
            marshall: optional ? util.format("wfc._doubleOptional(%s)", argName) : util.format("wfc._double(%s)", argName)
        };
    }

    ["new_id"](argName, optional) {
        return {
            jsType: optional ? "?*" : "*",
            marshall: optional ? util.format("wfc._doubleOptional(%s)", argName) : util.format("wfc._double(%s)", argName)
        };
    }

    ["string"](argName, optional) {
        return {
            jsType: optional ? "?string" : "string",
            marshall: optional ? util.format("wfc._doubleOptional(%s)", argName) : util.format("wfc._double(%s)", argName)
        };
    }

    ["array"](argName, optional) {
        return {
            jsType: optional ? "?ArrayBuffer" : "ArrayBuffer",
            marshall: optional ? util.format("wfc._doubleOptional(%s)", argName) : util.format("wfc._double(%s)", argName)
        };
    }

    _parseItfRequest(out, itfRequest, opcode, itfVersion) {
        const reqName = itfRequest.$.name;

        //function docs
        const description = itfRequest.description;
        description.forEach((val) => {
            out.write("\n\t/**\n");
            if (val.hasOwnProperty("_")) {
                val._.split("\n").forEach((line) => {
                    out.write("\t *" + line + "\n");
                });
            }

            if (itfRequest.hasOwnProperty("arg")) {
                const reqArgs = itfRequest.arg;
                out.write("\t *\n");
                reqArgs.forEach((arg) => {
                    const argDescription = arg.$.summary;
                    const argName = arg.$.name;
                    const argType = arg.$.type;

                    //TODO process if arg is optional
                    out.write(util.format("\t * @param {%s} %s %s \n", this[argType](argName, false).jsType, argName, argDescription));
                });
                out.write("\t *\n");
            }

            out.write("\t */\n");
        });

        //function
        out.write(util.format("\t%s(", reqName));
        if (itfRequest.hasOwnProperty("arg")) {
            const reqArgs = itfRequest.arg;
            for (let i = 0; i < reqArgs.length; i++) {
                const arg = reqArgs[i];
                const argName = arg.$.name;
                if (i !== 0) {
                    out.write(", ");
                }
                out.write(argName);
            }
        }
        out.write(") {\n");
        out.write(util.format("\t\tthis._connection._marshall(this._id, %d, [", opcode));

        //function args
        if (itfRequest.hasOwnProperty("arg")) {
            const reqArgs = itfRequest.arg;
            for (let i = 0; i < reqArgs.length; i++) {
                const arg = reqArgs[i];

                const argName = arg.$.name;
                const argType = arg.$.type;

                if (i !== 0) {
                    out.write(", ");
                }

                //TODO process if arg is optional
                out.write(this[argType](argName, false).marshall);
            }
        }

        out.write(util.format("]);\n"));
        out.write("\t}\n");
    }

    _parseInterface(out, protocolItf) {
        const itfName = protocolItf.$.name;
        const itfVersion = protocolItf.$.version;

        console.log(util.format("Processing interface %s v%d", itfName, itfVersion));

        //if version is 1, we extends from WObject, else we extend from the previous version.
        for (let i = 1; i <= itfVersion; i++) {

            //class docs
            const description = protocolItf.description;
            description.forEach((val) => {
                out.write("\n/**\n");
                if (val.hasOwnProperty("_")) {
                    val._.split("\n").forEach((line) => {
                        out.write(" *" + line + "\n");
                    });
                }
                out.write(" */\n");
            });

            //class
            if (i === 1) {
                out.write(util.format("wfc.%s = class %s extends wfc.WObject {\n", itfName, itfName));
            } else {
                const className = util.format("%sV%d", itfName, i);
                if (i === 2) {
                    out.write(util.format("wfc.%s = class %s extends wfc.%s {\n", className, className, itfName));
                } else {
                    out.write(util.format("wfc.%s = class %s extends wfc.%sV%d {\n", className, className, itfName, i - 1));
                }
            }

            //interface can have no requests, so we need to check for it's absence.
            if (protocolItf.hasOwnProperty("request")) {
                const itfRequests = protocolItf.request;
                for (let j = 0; j < itfRequests.length; j++) {
                    this._parseItfRequest(out, itfRequests[j], j + 1, i);
                }
            }

            out.write("};\n");
        }
    }

    _parseProtocol(jsonProtocol) {
        const protocolName = jsonProtocol.protocol.$.name;
        const out = fs.createWriteStream(util.format("westfield-client-%s.js", protocolName));
        out.on('open', (fd) => {
            out.write("/*\n");
            jsonProtocol.protocol.copyright.forEach((val) => {
                val.split("\n").forEach((line) => {
                    out.write(" *" + line + "\n");
                });
            });
            out.write(" */\n");

            jsonProtocol.protocol.interface.forEach((itf) => {
                this._parseInterface(out, itf);
            });
        });
    }

    parse() {
        fs.readFile(this.protocolFile, (err, data) => {
            if (err) throw err;
            new xml2js.Parser().parseString(data, (err, result) => {
                if (err) throw err;

                //uncomment to see the protocol as json output
                //console.log(util.inspect(result, false, null));

                this._parseProtocol(result);
                console.log('Done');
            });
        });
    }

    constructor(protocolFile) {
        this.protocolFile = protocolFile;
    }
}

new wfg.ProtocolParser('/usr/share/wayland/wayland.xml').parse();

<|endoftext|>


<commit_before>const fs = require('fs');
const util = require('util');

const xml2js = require('xml2js');

const wfg = {};

wfg.ProtocolParser = class {

    _parseInterface(out, protocolItf) {
        const itfName = protocolItf.$.name;
        const itfVersion = protocolItf.$.version;
        const itfDesc = protocolItf.description[0]._;
        const itfSummary = protocolItf.description[0].$.summary;

        console.log(util.format("Processing interface %s v%d", itfName, itfVersion));

        //if version is 1, we extends from WObject, else we extend from the previous version.
        out.write(util.format("wfc.%sV%d = class %s extends wfc.WObject {\n", itfName, itfVersion, itfName));
        out.write("};\n");
    }

    _parseProtocol(jsonProtocol) {
        const protocolName = jsonProtocol.protocol.$.name;
        const out = fs.createWriteStream(util.format("westfield-client-%s.js", protocolName));
        out.on('open', (fd) => {
            jsonProtocol.protocol.copyright.forEach((val) => {
                val.split("\n").forEach((line) => {
                    out.write("//" + line + "\n");
                });
            });

            jsonProtocol.protocol.interface.forEach((itf) => {
                this._parseInterface(out, itf);
            });
        });
    }

    parse() {
        fs.readFile(this.protocolFile, (err, data) => {
            if (err) throw err;
            new xml2js.Parser().parseString(data, (err, result) => {
                if (err) throw err;

                //uncomment to see the protocol as json output
                //console.log(util.inspect(result, false, null));

                this._parseProtocol(result);
                console.log('Done');
            });
        });
    }

    constructor(protocolFile) {
        this.protocolFile = protocolFile;
    }
}

new wfg.ProtocolParser('/usr/share/wayland/wayland.xml').parse();

<commit_msg>generate request functions without args<commit_after>const fs = require('fs');
const util = require('util');

const xml2js = require('xml2js');

const wfg = {};

wfg.ProtocolParser = class {

    _parseItfRequest(out, itfRequest, opcode) {
        const reqName = itfRequest.$.name;

        //function docs
        const description = itfRequest.description;
        description.forEach((val) => {
            out.write("\t/**\n");
            if (val.hasOwnProperty("_")) {
                val._.split("\n").forEach((line) => {
                    out.write("\t *" + line + "\n");
                });
            }

            if (itfRequest.hasOwnProperty("arg")) {
                const reqArgs = itfRequest.arg;
                out.write("\t *\n");
                reqArgs.forEach((arg) => {
                    const argDescription = arg.$.summary;
                    const argName = arg.$.name;
                    out.write(util.format("\t * @param %s %s \n", argName, argDescription));
                });
                out.write("\t *\n");
            }

            out.write("\t */\n");
        });

        //function
        out.write(util.format("\t%s(", reqName));
        if (itfRequest.hasOwnProperty("arg")) {
            const reqArgs = itfRequest.arg;
            for (let i = 0; i < reqArgs.length; i++) {
                const arg = reqArgs[i];
                const argName = arg.$.name;
                if (i !== 0) {
                    out.write(", ");
                }
                out.write(argName);
            }
        }
        out.write("){\n");
        out.write(util.format("\t\tthis._connection._marshall(this._id, %d, [", opcode));

        //function args

        out.write(util.format("]);\n"));
        out.write("\t}\n");
    }

    _parseInterface(out, protocolItf) {
        const itfName = protocolItf.$.name;
        const itfVersion = protocolItf.$.version;

        console.log(util.format("Processing interface %s v%d", itfName, itfVersion));

        //if version is 1, we extends from WObject, else we extend from the previous version.
        for (let i = 1; i <= itfVersion; i++) {

            //class docs
            const description = protocolItf.description;
            description.forEach((val) => {
                out.write("/**\n");
                if (val.hasOwnProperty("_")) {
                    val._.split("\n").forEach((line) => {
                        out.write(" *" + line + "\n");
                    });
                }
                out.write(" */\n");
            });

            //class
            const className = util.format("%sV%d", itfName, i);
            if (i === 1) {
                out.write(util.format("wfc.%s = class %s extends wfc.WObject {\n", className, className));
            } else {
                out.write(util.format("wfc.%s = class %s extends wfc.%sV%d {\n", className, className, itfName, i - 1));
            }

            //interface can have no requests, so we need to check for it's absence.
            if (protocolItf.hasOwnProperty("request")) {
                const itfRequests = protocolItf.request;
                for (let i = 0; i < itfRequests.length; i++) {
                    this._parseItfRequest(out, itfRequests[i], i + 1);
                }
            }

            out.write("};\n");
        }
    }

    _parseProtocol(jsonProtocol) {
        const protocolName = jsonProtocol.protocol.$.name;
        const out = fs.createWriteStream(util.format("westfield-client-%s.js", protocolName));
        out.on('open', (fd) => {
            out.write("/*\n");
            jsonProtocol.protocol.copyright.forEach((val) => {
                val.split("\n").forEach((line) => {
                    out.write(" *" + line + "\n");
                });
            });
            out.write(" */\n");

            jsonProtocol.protocol.interface.forEach((itf) => {
                this._parseInterface(out, itf);
            });
        });
    }

    parse() {
        fs.readFile(this.protocolFile, (err, data) => {
            if (err) throw err;
            new xml2js.Parser().parseString(data, (err, result) => {
                if (err) throw err;

                //uncomment to see the protocol as json output
                //console.log(util.inspect(result, false, null));

                this._parseProtocol(result);
                console.log('Done');
            });
        });
    }

    constructor(protocolFile) {
        this.protocolFile = protocolFile;
    }
}

new wfg.ProtocolParser('/usr/share/wayland/wayland.xml').parse();

<|endoftext|>


<commit_before>const util = require('../util')
const jsesc = require('jsesc');

const INDENTATION = ' '.repeat(4)
const indent = (line, level = 1) => INDENTATION.repeat(level) + line
const quote = str => jsesc(str, { quotes: 'double' })

function toRust (curlCommand) {
  const lines = ['extern crate reqwest;']
  const request = util.parseCurlCommand(curlCommand)

  const hasHeaders = request.headers || request.cookies

  {
    // Generate imports.
    const imports = [
      { want: 'header', condition: hasHeaders },
      { want: 'multipart', condition: !!request.multipartUploads }
    ].filter(i => i.condition).map (i => i.want)

    if (imports.length > 1) {
      lines.push(`use reqwest::{${imports.join(', ')}};`)
    } else if (imports.length) {
      lines.push(`use reqwest::${imports[0]};`)
    }
  }

  lines.push('', 'fn main() -> Result<(), Box<dyn std::error::Error>> {')

  if (request.headers || request.cookies) {
    lines.push(indent('let mut headers = header::HeaderMap::new();'))

    for (let headerName in request.headers) {
      const headerValue = quote(request.headers[headerName])
      lines.push(indent(`headers.insert("${headerName}", "${headerValue}".parse().unwrap());`))
    }

    if (request.cookies) {
      let cookies = Object.keys(request.cookies)
        .map(key => `${key}=${request.cookies[key]}`)
        .join('; ')
      lines.push(indent(`headers.insert(header::COOKIE, "${quote(cookies)}".parse().unwrap());`))
    }

    lines.push('')
  }

  if (request.multipartUploads) {
    lines.push(indent('let form = multipart::Form::new()'))
    const parts = Object.keys(request.multipartUploads).map(partType => {
      const partValue = request.multipartUploads[partType]
      switch (partType) {
      case 'image', 'file':
        const path = partValue.split('@')[1]
        return indent(`.file("${partType}", "${quote(path)}")?`, 2)
      default:
        return indent(`.text("${partType}", "${quote(partValue)}")`, 2)
      }
    })
    parts[parts.length - 1] += ';'
    lines.push(...parts, '')
  }

  lines.push(indent('let res = reqwest::Client::new()'))
  lines.push(indent(`.${request.method}("${quote(request.url)}")`, 2))

  if (request.auth) {
    const [ user, password ] = request.auth.split(':', 2).map(quote)
    lines.push(indent(`.basic_auth("${user || ''}", Some("${password || ''}"))`, 2))
  }

  if (hasHeaders) {
    lines.push(indent('.headers(headers)', 2))
  }

  if (request.multipartUploads) {
    lines.push(indent('.multipart(form)', 2))
  }

  if (request.data) {
    if (typeof request.data === 'string' && request.data.indexOf("\n") !== -1) {
      // Use raw strings for multiline content
      lines.push(
        indent('.body(r#"', 2),
        request.data,
        '"#',
        indent(')', 2)
      )
    } else {
      lines.push(indent(`.body("${quote(request.data)}")`, 2))
    }
  }

  lines.push(
    indent('.send()?', 2),
    indent('.text()?;', 2),
    indent('println!("{}", res);'),
    '',
    indent('Ok(())'),
    '}'
  )

  return lines.join("\n") + "\n"
}

module.exports = toRust
<commit_msg>Ensure Rust generator is up to Standard's standards (pun intended)<commit_after>const util = require('../util')
const jsesc = require('jsesc')

const INDENTATION = ' '.repeat(4)
const indent = (line, level = 1) => INDENTATION.repeat(level) + line
const quote = str => jsesc(str, { quotes: 'double' })

function toRust (curlCommand) {
  const lines = ['extern crate reqwest;']
  const request = util.parseCurlCommand(curlCommand)

  const hasHeaders = request.headers || request.cookies

  {
    // Generate imports.
    const imports = [
      { want: 'header', condition: hasHeaders },
      { want: 'multipart', condition: !!request.multipartUploads }
    ].filter(i => i.condition).map(i => i.want)

    if (imports.length > 1) {
      lines.push(`use reqwest::{${imports.join(', ')}};`)
    } else if (imports.length) {
      lines.push(`use reqwest::${imports[0]};`)
    }
  }

  lines.push('', 'fn main() -> Result<(), Box<dyn std::error::Error>> {')

  if (request.headers || request.cookies) {
    lines.push(indent('let mut headers = header::HeaderMap::new();'))

    for (const headerName in request.headers) {
      const headerValue = quote(request.headers[headerName])
      lines.push(indent(`headers.insert("${headerName}", "${headerValue}".parse().unwrap());`))
    }

    if (request.cookies) {
      const cookies = Object.keys(request.cookies)
        .map(key => `${key}=${request.cookies[key]}`)
        .join('; ')
      lines.push(indent(`headers.insert(header::COOKIE, "${quote(cookies)}".parse().unwrap());`))
    }

    lines.push('')
  }

  if (request.multipartUploads) {
    lines.push(indent('let form = multipart::Form::new()'))
    const parts = Object.keys(request.multipartUploads).map(partType => {
      const partValue = request.multipartUploads[partType]
      switch (partType) {
        case 'image':
        case 'file': {
          const path = partValue.split('@')[1]
          return indent(`.file("${partType}", "${quote(path)}")?`, 2)
        }
        default:
          return indent(`.text("${partType}", "${quote(partValue)}")`, 2)
      }
    })
    parts[parts.length - 1] += ';'
    lines.push(...parts, '')
  }

  lines.push(indent('let res = reqwest::Client::new()'))
  lines.push(indent(`.${request.method}("${quote(request.url)}")`, 2))

  if (request.auth) {
    const [user, password] = request.auth.split(':', 2).map(quote)
    lines.push(indent(`.basic_auth("${user || ''}", Some("${password || ''}"))`, 2))
  }

  if (hasHeaders) {
    lines.push(indent('.headers(headers)', 2))
  }

  if (request.multipartUploads) {
    lines.push(indent('.multipart(form)', 2))
  }

  if (request.data) {
    if (typeof request.data === 'string' && request.data.indexOf('\n') !== -1) {
      // Use raw strings for multiline content
      lines.push(
        indent('.body(r#"', 2),
        request.data,
        '"#',
        indent(')', 2)
      )
    } else {
      lines.push(indent(`.body("${quote(request.data)}")`, 2))
    }
  }

  lines.push(
    indent('.send()?', 2),
    indent('.text()?;', 2),
    indent('println!("{}", res);'),
    '',
    indent('Ok(())'),
    '}'
  )

  return lines.join('\n') + '\n'
}

module.exports = toRust
<|endoftext|>


<commit_before>/**
 * Ionic Letter Avatar is directive for AngularJS apps
 * @version v3.0.0 - 2015-09-28 * @link https://github.com/uttesh/ionic-letteravatar
 * @author Uttesh Kumar T.H. <uttesh@gmail.com>
 * @license MIT License, http://www.opensource.org/licenses/MIT
 */

(function () {

	'use strict';
	var nla = angular.module('ionic-letter-avatar', []);

	nla.constant('defaultSettings', {
		alphabetcolors : ["#5A8770", "#B2B7BB", "#6FA9AB", "#F5AF29", "#0088B9", "#F18636", "#D93A37", "#A6B12E", "#5C9BBC", "#F5888D", "#9A89B5", "#407887", "#9A89B5", "#5A8770", "#D33F33", "#A2B01F", "#F0B126", "#0087BF", "#F18636", "#0087BF", "#B2B7BB", "#72ACAE", "#9C8AB4", "#5A8770", "#EEB424", "#407887"],
		textColor : '#ffffff',
		defaultBorder : 'border:5px solid white',
		fontsize : 30, // unit in pixels
		height : 50, // unit in pixels
		width : 50, // unit in pixels
		fontWeight : 400, //
		charCount : 1,
		fontFamily : 'HelveticaNeue-Light,Helvetica Neue Light,Helvetica Neue,Helvetica, Arial,Lucida Grande, sans-serif',
		base : 'data:image/svg+xml;base64,',
		radius : 'border-radius:30px;'

	});

	nla.directive('ionicLetterAvatar', ['defaultSettings', function (defaultSettings) {
				return {
					restrict : 'AE',
					replace : true,
					link : function (scope, element, attrs) {

						var params = {
							charCount : attrs.charcount || defaultSettings.charCount,
							data : attrs.data,
							textColor : defaultSettings.textColor,
							height : attrs.height || defaultSettings.height,
							width : attrs.width || defaultSettings.width,
							fontsize : attrs.fontsize || defaultSettings.fontsize,
							fontWeight : attrs.fontweight || defaultSettings.fontWeight,
							fontFamily : attrs.fontfamily || defaultSettings.fontFamily,
							avatarBorderStyle : attrs.avatarcustomborder,
							avatardefaultBorder : attrs.avatarborder,
							defaultBorder : defaultSettings.defaultBorder,
							shape : attrs.shape
						};

						var c = params.data.substr(0, params.charCount).toUpperCase();
						var cobj = getCharacterObject(c, params.textColor, params.fontFamily, params.fontWeight, params.fontsize);
						var colorIndex = '';
						var color = '';

						if (c.charCodeAt(0) < 65) {
							color = getRandomColors();
						} else {
							colorIndex = Math.floor((c.charCodeAt(0) - 65) % defaultSettings.alphabetcolors.length);
							color = defaultSettings.alphabetcolors[colorIndex];
						}

						var svg = getImgTag(params.width, params.height, color);
						svg.append(cobj);
						var lvcomponent = angular.element('
').append(svg.clone()).html();
						var svgHtml = window.btoa(unescape(encodeURIComponent(lvcomponent)));
						var component;
						var base = defaultSettings.base;
						var _style = '';
						if (params.avatarBorderStyle) {
							_style = params.avatarBorderStyle;
						} else if (params.avatardefaultBorder) {
							_style = params.defaultBorder;
						}

						if (params.shape) {
							if (params.shape === 'round') {
								var round_style = defaultSettings.radius + _style;
								component = "";
							}
						} else {
							component = "";
						}
						element.replaceWith(component);
					}
				};
			}
		]);

	function getRandomColors() {
		var letters = '0123456789ABCDEF'.split('');
		var _color = '#';
		for (var i = 0; i < 6; i++) {
			_color += letters[Math.floor(Math.random() * 16)];
		}
		return _color;
	}

	function getImgTag(width, height, color) {

		var svgTag = angular.element('<svg></svg>')
			.attr({
				'xmlns' : 'http://www.w3.org/2000/svg',
				'pointer-events' : 'none',
				'width' : width,
				'height' : height
			})
			.css({
				'background-color' : color,
				'width' : width + 'px',
				'height' : height + 'px'
			});

		return svgTag;
	}

	function getCharacterObject(character, textColor, fontFamily, fontWeight, fontsize) {
		var textTag = angular.element('<text text-anchor="middle"></text>')
			.attr({
				'y' : '50%',
				'x' : '50%',
				'dy' : '0.35em',
				'pointer-events' : 'auto',
				'fill' : textColor,
				'font-family' : fontFamily
			})
			.html(character)
			.css({
				'font-weight' : fontWeight,
				'font-size' : fontsize + 'px',
			});

		return textTag;
	}

})();<commit_msg>Fixed the collection-repeat issue using a watcher and scope for data<commit_after>/**
 * Ionic Letter Avatar is directive for AngularJS apps
 * @version v3.0.0 - 2015-09-28 * @link https://github.com/uttesh/ionic-letteravatar
 * @author Uttesh Kumar T.H. <uttesh@gmail.com>
 * @license MIT License, http://www.opensource.org/licenses/MIT
 */

(function () {

	'use strict';
	var nla = angular.module('ionic-letter-avatar', []);

	nla.constant('defaultSettings', {
		alphabetcolors : ["#5A8770", "#B2B7BB", "#6FA9AB", "#F5AF29", "#0088B9", "#F18636", "#D93A37", "#A6B12E", "#5C9BBC", "#F5888D", "#9A89B5", "#407887", "#9A89B5", "#5A8770", "#D33F33", "#A2B01F", "#F0B126", "#0087BF", "#F18636", "#0087BF", "#B2B7BB", "#72ACAE", "#9C8AB4", "#5A8770", "#EEB424", "#407887"],
		textColor : '#ffffff',
		defaultBorder : 'border:5px solid white',
		fontsize : 30, // unit in pixels
		height : 50, // unit in pixels
		width : 50, // unit in pixels
		fontWeight : 400, //
		charCount : 1,
		fontFamily : 'HelveticaNeue-Light,Helvetica Neue Light,Helvetica Neue,Helvetica, Arial,Lucida Grande, sans-serif',
		base : 'data:image/svg+xml;base64,',
		radius : 'border-radius:30px;'

	});

	nla.directive('ionicLetterAvatar', ['defaultSettings', function (defaultSettings) {
				return {
					restrict : 'AE',
					replace : true,
					scope: {
						data: "@"
					},
					link : function (scope, element, attrs) {

						function createAvatar() {
							var params = {
								charCount : attrs.charcount || defaultSettings.charCount,
								data : params.data,
								textColor : defaultSettings.textColor,
								height : attrs.height || defaultSettings.height,
								width : attrs.width || defaultSettings.width,
								fontsize : attrs.fontsize || defaultSettings.fontsize,
								fontWeight : attrs.fontweight || defaultSettings.fontWeight,
								fontFamily : attrs.fontfamily || defaultSettings.fontFamily,
								avatarBorderStyle : attrs.avatarcustomborder,
								avatardefaultBorder : attrs.avatarborder,
								defaultBorder : defaultSettings.defaultBorder,
								shape : attrs.shape
							};

							var c = params.data.substr(0, params.charCount).toUpperCase();
							var cobj = getCharacterObject(c, params.textColor, params.fontFamily, params.fontWeight, params.fontsize);
							var colorIndex = '';
							var color = '';

							if (c.charCodeAt(0) < 65) {
								color = getRandomColors();
							} else {
								colorIndex = Math.floor((c.charCodeAt(0) - 65) % defaultSettings.alphabetcolors.length);
								color = defaultSettings.alphabetcolors[colorIndex];
							}

							var svg = getImgTag(params.width, params.height, color);
							svg.append(cobj);
							var lvcomponent = angular.element('
').append(svg.clone()).html();
							var svgHtml = window.btoa(unescape(encodeURIComponent(lvcomponent)));
							var component;
							var base = defaultSettings.base;
							var _style = '';
							if (params.avatarBorderStyle) {
								_style = params.avatarBorderStyle;
							} else if (params.avatardefaultBorder) {
								_style = params.defaultBorder;
							}

							if (params.shape) {
								if (params.shape === 'round') {
									var round_style = defaultSettings.radius + _style;
									component = "";
								}
							} else {
								component = "";
							}
							element.html(component);
						}

						scope.$watch('data', function(newVal) {
							if(newVal) {
								//delay it till the data is available
								createAvatar();
							}
						});

					}
				};
			}
		]);

	function getRandomColors() {
		var letters = '0123456789ABCDEF'.split('');
		var _color = '#';
		for (var i = 0; i < 6; i++) {
			_color += letters[Math.floor(Math.random() * 16)];
		}
		return _color;
	}

	function getImgTag(width, height, color) {

		var svgTag = angular.element('<svg></svg>')
			.attr({
				'xmlns' : 'http://www.w3.org/2000/svg',
				'pointer-events' : 'none',
				'width' : width,
				'height' : height
			})
			.css({
				'background-color' : color,
				'width' : width + 'px',
				'height' : height + 'px'
			});

		return svgTag;
	}

	function getCharacterObject(character, textColor, fontFamily, fontWeight, fontsize) {
		var textTag = angular.element('<text text-anchor="middle"></text>')
			.attr({
				'y' : '50%',
				'x' : '50%',
				'dy' : '0.35em',
				'pointer-events' : 'auto',
				'fill' : textColor,
				'font-family' : fontFamily
			})
			.html(character)
			.css({
				'font-weight' : fontWeight,
				'font-size' : fontsize + 'px',
			});

		return textTag;
	}

})();
<|endoftext|>


<commit_before>/*
 * isStyleSupported
 * Detect support for CSS styles and assignable values
 * @param {String} prop
 * @param {String} value (optional)
 * @return {Boolean}
 */

(function(win){
    'use strict';

    var el = win.document.createElement('div'),
    prefixes = ['Webkit', 'Moz', 'O', 'ms'],
    camelRe = /-([a-z]|[0-9])/ig,
    cache = {},
    key,
    length,
    support,
    camel,
    capitalized,
    prefixed;

    // Convert CSS notation (kebal-case) to DOM notation (camel-case)
    function toCamelCase(prop){
        return prop.replace(camelRe, function(all, letter){
            return (letter + '').toUpperCase();
        });
    }

    // Test the different native APIs for style support
    function nativeSupports(prop, value){
        // Check the standard method first
        if('CSS' in win && 'supports' in win.CSS){
            return win.CSS.supports(prop, value);
        }
        // Check for Opera's native method
        if('supportsCSS' in win){
            return win.supportsCSS(prop, value);
        }
        return false;
    }

    win.isStyleSupported = function(prop, value){
        // If no value is supplied, use "inherit"
        value = arguments.length === 2 ? value : 'inherit';
        // Check native methods first
        support = nativeSupports(prop, value);
        if(!support){
            camel = toCamelCase(prop);
            capitalized = camel.charAt(0).toUpperCase() + camel.slice(1);
            // Add the unprefixed property and value as CSS test to the
            // test element and determine support based on whether the
            // property exists in the style object
            el.style.cssText = prop+':'+value;
            support = camel in el.style && el.style[camel] !== '';
            length = prefixes.length;
            while(!support && length--){
                // We repeat the previous steps here, this time trying
                // each vendor prefix to determine support
                prefixed = '-'+prefixes[length].toLowerCase()+'-'+prop;
                support = checkNative(prefixed, value);
                if(!support){
                    camel = prefixes[length] + capitalized;
                    el.style.cssText = prefixed+':'+value;
                    support = camel in el.style && el.style[camel] !== '';
                }
            }
        }
        return support;
    };

})(this);<commit_msg>Refactored<commit_after>/*
 * isStyleSupported
 * Detect support for CSS properties and their assignable values
 * @param {String} prop
 * @param {String} value (optional)
 * @return {Boolean}
 */

(function(win){
    'use strict';

    var el = win.document.createElement('div'),
    prefixes = ['Webkit', 'Moz', 'O', 'ms'],
    camelRe = /-([a-z]|[0-9])/ig,
    length,
    support,
    camel,
    capitalized,
    prefixed;

    // Convert CSS notation (kebal-case) to DOM notation (camel-case)
    function toCamelCase(prop){
        return prop.replace(camelRe, function(all, letter){
            return (letter + '').toUpperCase();
        });
    }

    // Test the different native APIs for style support
    function nativeSupports(prop, value){
        // Check the standard method first
        if('CSS' in win && 'supports' in win.CSS){
            return win.CSS.supports(prop, value);
        }
        // Check for Opera's native method
        if('supportsCSS' in win){
            return win.supportsCSS(prop, value);
        }
        return false;
    }

    win.isStyleSupported = function(prop, value){
        // If no value is supplied, use "inherit"
        value = arguments.length === 2 ? value : 'inherit';
        // Check native methods first
        support = nativeSupports(prop, value);
        if(!support){
            camel = toCamelCase(prop);
            capitalized = camel.charAt(0).toUpperCase() + camel.slice(1);
            // Add the unprefixed property and value as CSS test to the
            // test element and determine support based on whether the
            // property exists in the style object
            el.style.cssText = prop + ':' + value;
            support = camel in el.style && el.style[camel] !== '';
            length = prefixes.length;
            while(!support && length--){
                // We repeat the previous steps here, this time trying
                // each vendor prefix to determine support
                prefixed = '-'+prefixes[length].toLowerCase()+'-'+prop;
                support = nativeSupports(prefixed, value);
                if(!support){
                    camel = prefixes[length] + capitalized;
                    el.style.cssText = prefixed + ':' + value;
                    support = camel in el.style && el.style[camel] !== '';
                }
            }
        }
        return support;
    };

})(this);<|endoftext|>


<commit_before>var util = require('util');
var request = require('request');
var qs = require('qs');
var fbSignedParser = require('fb-signed-parser');
var async = require('async');
var _ = require('underscore');

var facebookUrl = 'https://facebook.com/';
var graphApiUrl = 'https://graph.facebook.com/';
var graphUrl = 'https://graph.facebook.com/v2.0/';

module.exports = function (app, options) {

    var _name = 'Facebook Tab Page';

    if (!options.id) {
        throw new Error(_name + ': Please define a facebook application id.');
    }

    if (!options.secret) {
        throw new Error(_name + ': Please define a facebook application secret.');
    }

    if (!options.callback) {
        throw new Error(_name + ': Please define a facebook application auth callback url.');
    }

    if (!options.scope) {
        throw new Error(_name + ': Please define a facebook application auth scope.');
    }

    return function auth(req, res, next) {

        // Set p3p header http://bit.ly/QYmhxt
        res.set('P3P', 'CP="IDC DSP COR CURa ADMa OUR IND PHY ONL COM STA"');

        if( req.body.signed_request ){

            // get signedRequest data
            var signedRequest = fbSignedParser.parse(req.body.signed_request, options.secret);

            console.log( signedRequest );

            // Set page ID on session
            req.session.pageId = signedRequest.page.id;

            // Merge session and signed data
            if( req.session.facebook ){

                req.session.facebook.page = _.extend( req.session.facebook.page, signedRequest.page );
                req.session.facebook.user = _.extend( req.session.facebook.user, signedRequest.user );
            }

        }
        else{
            console.error( 'req.body.signed_request is empty %s', req.url );
            console.log( req.query.signed_request );
        }

        // Is is autenticated go to next
        if (req.session.accessToken && req.session.facebook) {

            next();

        } else {

            if (req.param('code')) {

                // Get access token http://bit.ly/1jXCmiY
                var url = util.format(graphUrl + 'oauth/access_token?code=%s&client_id=%d&redirect_uri=%s&client_secret=%s', req.param('code'), options.id, encodeURIComponent(options.callback), options.secret);

                request(url, function (error, response, body) {

                    if (!error && response.statusCode == 200) {

                        var dataParse = qs.parse(body);

                        // set accessToken session
                        req.session.accessToken = dataParse.access_token;

                        // Call user, application and page data
                        async.parallel({
                            user: function (callback) {

                                request(util.format(graphUrl + 'me?access_token=%s', req.session.accessToken), function (error, response, body) {

                                    if( error ){
                                        console.log( error );
                                    }

                                    callback(null,JSON.parse(body));

                                });

                            },
                            application: function (callback) {
                                request(util.format(graphUrl + 'fql?q=SELECT+app_id,app_name,namespace,display_name+FROM+application+WHERE+app_id=%d&access_token=%s', options.id, req.session.accessToken), function (error, response, body) {

                                    if( error ){
                                        console.log( error );
                                    }

                                    callback(null,JSON.parse(body));

                                });
                            },
                            page: function (callback) {
                                request(util.format(graphUrl + 'fql?q=SELECT+username,website+FROM+page+WHERE+page_id=%d&access_token=%s', req.session.pageId, req.session.accessToken), function (error, response, body) {

                                    if( error ){
                                        console.log( error );
                                    }

                                    console.log( body );

                                    callback(null,JSON.parse(body));

                                });
                            }
                        },
                        function (err, results) {

                            var facebook = {};

                            if( results.application.data[0] ){

                                facebook.application = results.application.data[0];

                            }

                            if( results.page.data[0] ){

                                facebook.page = results.page.data[0];

                            }

                            if( results.user ){

                                facebook.user = results.user;

                            }

                            req.session.facebook = facebook;

                            res.redirect(util.format('https://www.facebook.com/%s/app_%d', facebook.page.username, options.id));

                        });

                    }

                });

            }
            else {

                // Request auth dialog
                var url = util.format(facebookUrl + 'dialog/oauth?client_id=%d&redirect_uri=%s&auth_type=rerequest&scope=%s', options.id, encodeURIComponent(options.callback), options.scope.join(','));
                res.send('<script>window.top.location = ' + '"' + url + '"' + ';</script>');

            }

        }

    }

}<commit_msg>test data<commit_after>var util = require('util');
var request = require('request');
var qs = require('qs');
var fbSignedParser = require('fb-signed-parser');
var async = require('async');
var _ = require('underscore');

var facebookUrl = 'https://facebook.com/';
var graphApiUrl = 'https://graph.facebook.com/';
var graphUrl = 'https://graph.facebook.com/v2.0/';

module.exports = function (app, options) {

    var _name = 'Facebook Tab Page';

    if (!options.id) {
        throw new Error(_name + ': Please define a facebook application id.');
    }

    if (!options.secret) {
        throw new Error(_name + ': Please define a facebook application secret.');
    }

    if (!options.callback) {
        throw new Error(_name + ': Please define a facebook application auth callback url.');
    }

    if (!options.scope) {
        throw new Error(_name + ': Please define a facebook application auth scope.');
    }

    return function auth(req, res, next) {

        // Set p3p header http://bit.ly/QYmhxt
        res.set('P3P', 'CP="IDC DSP COR CURa ADMa OUR IND PHY ONL COM STA"');

        console.log( req.body.signed_request );

        if( req.body.signed_request ){

            // get signedRequest data
            var signedRequest = fbSignedParser.parse(req.body.signed_request, options.secret);

            console.log( signedRequest );

            // Set page ID on session
            req.session.pageId = signedRequest.page.id;

            // Merge session and signed data
            if( req.session.facebook ){

                req.session.facebook.page = _.extend( req.session.facebook.page, signedRequest.page );
                req.session.facebook.user = _.extend( req.session.facebook.user, signedRequest.user );
            }

        }
        else{
            console.error( 'req.body.signed_request is empty %s', req.url );
            console.log( req.query.signed_request );
        }

        // Is is autenticated go to next
        if (req.session.accessToken && req.session.facebook) {

            next();

        } else {

            if (req.param('code')) {

                // Get access token http://bit.ly/1jXCmiY
                var url = util.format(graphUrl + 'oauth/access_token?code=%s&client_id=%d&redirect_uri=%s&client_secret=%s', req.param('code'), options.id, encodeURIComponent(options.callback), options.secret);

                request(url, function (error, response, body) {

                    if (!error && response.statusCode == 200) {

                        var dataParse = qs.parse(body);

                        // set accessToken session
                        req.session.accessToken = dataParse.access_token;

                        // Call user, application and page data
                        async.parallel({
                            user: function (callback) {

                                request(util.format(graphUrl + 'me?access_token=%s', req.session.accessToken), function (error, response, body) {

                                    if( error ){
                                        console.log( error );
                                    }

                                    callback(null,JSON.parse(body));

                                });

                            },
                            application: function (callback) {
                                request(util.format(graphUrl + 'fql?q=SELECT+app_id,app_name,namespace,display_name+FROM+application+WHERE+app_id=%d&access_token=%s', options.id, req.session.accessToken), function (error, response, body) {

                                    if( error ){
                                        console.log( error );
                                    }

                                    callback(null,JSON.parse(body));

                                });
                            },
                            page: function (callback) {
                                request(util.format(graphUrl + 'fql?q=SELECT+username,website+FROM+page+WHERE+page_id=%d&access_token=%s', req.session.pageId, req.session.accessToken), function (error, response, body) {

                                    if( error ){
                                        console.log( error );
                                    }

                                    console.log( body );

                                    callback(null,JSON.parse(body));

                                });
                            }
                        },
                        function (err, results) {

                            var facebook = {};

                            if( results.application.data[0] ){

                                facebook.application = results.application.data[0];

                            }

                            if( results.page.data[0] ){

                                facebook.page = results.page.data[0];

                            }

                            if( results.user ){

                                facebook.user = results.user;

                            }

                            req.session.facebook = facebook;

                            res.redirect(util.format('https://www.facebook.com/%s/app_%d', facebook.page.username, options.id));

                        });

                    }

                });

            }
            else {

                // Request auth dialog
                var url = util.format(facebookUrl + 'dialog/oauth?client_id=%d&redirect_uri=%s&auth_type=rerequest&scope=%s', options.id, encodeURIComponent(options.callback), options.scope.join(','));
                res.send('<script>window.top.location = ' + '"' + url + '"' + ';</script>');

            }

        }

    }

}<|endoftext|>