<commit_before>var ignoreWordsArr = require('./ignoreWords')
  ;

/**
 * Counts word frequncy from string passed in and returns the result
 * @param  {String} string The text we want to get word frequency from
 * @return {Array}        Sorted (desc) array containing objects like { word: "problems", frequency: 99 }
 */
function getWordFrequency(string) {

  var words = string.split(' ')
    wordFrequency = countWords(words)
    ;

  return sortWordFrequency(wordFrequency);
}

exports.getWordFrequency = getWordFrequency;

function countWords(words) {
  var nrWords = words.length
    , wordFrequency = {}
    , word
    , i
    ;

  for (i = 0; i < nrWords; i++) {
    word = words[i].replace(/,|\./, '');

    if ( ignoreWord(word) ) continue;

    if ( wordFrequency[word] ) {
      wordFrequency[word]++;
    } else {
      wordFrequency[word] = 1;
    }
  }

  return wordFrequency;
}

function sortWordFrequency(wordFrequency) {
  var wordFrequencyArr = []
    , word
    ;

  for (word in wordFrequency) {
    if ( !wordFrequency.hasOwnProperty(word) ) continue;

    wordFrequencyArr.push({
      word: word,
      frequency: wordFrequency[word]
    });
  }

  wordFrequencyArr.sort(function(firstWord, secondWord) {
    return secondWord.frequency - firstWord.frequency;
  });

  return wordFrequencyArr;
}

function ignoreWord(word) {
  var ignoreWords = {}

  ignoreWordsArr.forEach( function(ignore) {
    ignoreWords[ignore] = true;
  });

  return !!ignoreWords[ word.toLowerCase() ];

}<commit_msg>Added a missing comma<commit_after>var ignoreWordsArr = require('./ignoreWords')
  ;

/**
 * Counts word frequncy from string passed in and returns the result
 * @param  {String} string The text we want to get word frequency from
 * @return {Array}        Sorted (desc) array containing objects like { word: "problems", frequency: 99 }
 */
function getWordFrequency(string) {

  var words = string.split(' ')
    , wordFrequency = countWords(words)
    ;

  return sortWordFrequency(wordFrequency);
}

exports.getWordFrequency = getWordFrequency;

function countWords(words) {
  var nrWords = words.length
    , wordFrequency = {}
    , word
    , i
    ;

  for (i = 0; i < nrWords; i++) {
    word = words[i].replace(/,|\./, '');

    if ( ignoreWord(word) ) continue;

    if ( wordFrequency[word] ) {
      wordFrequency[word]++;
    } else {
      wordFrequency[word] = 1;
    }
  }

  return wordFrequency;
}

function sortWordFrequency(wordFrequency) {
  var wordFrequencyArr = []
    , word
    ;

  for (word in wordFrequency) {
    if ( !wordFrequency.hasOwnProperty(word) ) continue;

    wordFrequencyArr.push({
      word: word,
      frequency: wordFrequency[word]
    });
  }

  wordFrequencyArr.sort(function(firstWord, secondWord) {
    return secondWord.frequency - firstWord.frequency;
  });

  return wordFrequencyArr;
}

function ignoreWord(word) {
  var ignoreWords = {}

  ignoreWordsArr.forEach( function(ignore) {
    ignoreWords[ignore] = true;
  });

  return !!ignoreWords[ word.toLowerCase() ];

}<|endoftext|>


<commit_before>import Promise from 'bluebird';
import { Apis } from 'gxbjs-ws';
import { ChainStore } from 'gxbjs';
import Immutable from 'immutable';
import superagent from 'superagent';
import config from '../../config';

/**
 * fetch account information by account name or id
 * @param account_name
 */
const fetch_account = account_name => {
  return Apis.instance()
    .db_api()
    .exec('get_account_by_name', [account_name]);
};

/**
 * fetch full account information by name
 * @param account_name
 * @returns {bluebird}
 */
const fetch_full_account = account => {
  return Apis.instance()
    .db_api()
    .exec('get_full_accounts', [[account], false]);
};

/**
 * fetch account history by account name or id
 * @param id_or_name
 * @returns {bluebird}
 */
const fetch_account_history = (id_or_name, asset_id, operation_type, pageNo, pageSize) => {
  console.log(JSON.parse(config.build.env.ES_PLUGIN));
  return new Promise(function(resolve, reject) {
    if (id_or_name.indexOf('.') === -1) {
      fetch_account(id_or_name)
        .then(account => {
            let param = [
                {
                  term: {
                    'account_history.account': account.id
                  }
                }
              ]
              if(asset_id) {
                param.push({
                    term: {
                        'operation_history.op_object.amount_.asset_id': asset_id
                    }
                })
              }
              if(operation_type) {
                param.push({
                    term: {
                        'operation_type': operation_type
                    }
                })
              }
          superagent
            .post(JSON.parse(config.build.env.ES_PLUGIN))
            .set('Content-Type', 'application/json')
            .send({
              query: {
                bool: {
                  must: param
                }
              },
              from: (pageNo - 1) * pageSize,
              size: pageSize,
              sort: [{ 'block_data.block_time': 'desc' }]
            })
            .end((err, res) => {
              if (err) {
                reject(err);
              } else {
                try {
                  const respList = res.body.hits.hits;
                  const list = [];
                  for (let i = 0; i < respList.length; i++) {
                    list.push(respList[i]._source);
                  }
                  resolve({
                    list,
                    totalCount: res.body.hits.total,
                    pageNo,
                    pageSize
                  });
                } catch (ex) {
                  reject(ex);
                }
              }
            });
        })
        .catch(ex => {
          reject(ex);
        });
    } else {
      superagent
        .post(JSON.parse(config.build.env.ES_PLUGIN))
        .set('Content-Type', 'application/json')
        .send({
          query: {
            bool: {
              must: [
                {
                  term: {
                    'account_history.account': id_or_name
                  }
                }
              ]
            }
          },
          from: (pageNo - 1) * pageSize,
          size: pageSize,
          sort: [{ 'block_data.block_time': 'desc' }]
        })
        .end((err, res) => {
          if (err) {
            reject(err);
          } else {
            try {
              const respList = res.body.hits.hits;
              const list = [];
              for (let i = 0; i < respList.length; i++) {
                list.push(respList[i]._source);
              }
              resolve({
                list,
                totalCount: res.body.hits.total,
                pageNo,
                pageSize
              });
            } catch (ex) {
              reject(ex);
            }
          }
        });
    }
  });
};

/**
 * fetch account balance of GXC by account name or id
 * @param id_or_name
 * @returns {bluebird}
 */
const fetch_account_balance = id_or_name => {
  return new Promise((resolve, reject) => {
    if (id_or_name.indexOf('.') === -1) {
      fetch_account(id_or_name)
        .then(account => {
          return Apis.instance()
            .db_api()
            .exec('get_account_balances', [account.id, []]);
        })
        .then(balances => {
          resolve(balances);
        })
        .catch(ex => {
          reject(ex);
        });
    } else {
      Apis.instance()
        .db_api()
        .exec('get_account_balances', [id_or_name, []])
        .then(balances => {
          resolve(balances);
        })
        .catch(ex => {
          reject(ex);
        });
    }
  });
};

/**
 * fetch vest balance of GXC by account name or id
 * @param id_or_name
 * @returns {bluebird}
 */
const get_vesting_balances = (id_or_name) => {
  return new Promise((resolve, reject) => {
    if (id_or_name.indexOf('.') === -1) {
      fetch_account(id_or_name)
        .then((account) => {
          return Apis.instance().db_api().exec('get_vesting_balances', [account.id, []]);
        })
        .then((balances) => {
          resolve(balances);
        })
        .catch((ex) => {
          reject(ex);
        });
    } else {
      Apis.instance()
        .db_api()
        .exec('get_vesting_balances', [id_or_name, []])
        .then((balances) => {
          resolve(balances);
        })
        .catch((ex) => {
          reject(ex);
        });
    }
  });
};

/**
 * 获取区块信息
 * @param block_height 区块高度
 */
const fetch_block = function(block_height) {
  return new Promise(function(resolve, reject) {
    return Apis.instance()
      .db_api()
      .exec('get_block', [parseInt(block_height)])
      .then(function(block) {
        if (!block) {
          resolve(null);
        } else {
          resolve(block);
        }
      })
      .catch(function(ex) {
        reject(ex);
      });
  });
};

/**
 * 资产信息
 * @param asset_name
 */
const fetch_asset = function(asset_name) {
  return new Promise(function(resolve, reject) {
    return Apis.instance()
      .db_api()
      .exec('lookup_asset_symbols', [[asset_name]])
      .then(function(assets) {
        let asset = assets && assets.length > 0 ? assets[0] : {};
        if (asset.id) {
          Apis.instance()
            .db_api()
            .exec('get_objects', [[asset.dynamic_asset_data_id, asset.issuer]])
            .then(objs => {
              asset.detail = objs[0];
              asset.issuer = objs[1];
              resolve(asset);
            });
        } else {
          resolve(asset);
        }
      })
      .catch(function(ex) {
        reject(ex);
      });
  });
};

/**
 * 链上资产列表
 */
const fetch_assets = function() {
  return new Promise(function(resolve, reject) {
    return Apis.instance()
      .db_api()
      .exec('list_assets', ['A', 100])
      .then(function(assets) {
        let ids = [];
        assets.forEach(asset => {
          ids.push(asset.dynamic_asset_data_id);
          ids.push(asset.issuer);
        });
        Apis.instance()
          .db_api()
          .exec('get_objects', [ids])
          .then(objs => {
            assets.forEach((asset, i) => {
              asset.detail = objs[2 * i];
              asset.issuer = objs[2 * i + 1];
            });
            resolve(assets);
          });
      })
      .catch(function(ex) {
        reject(ex);
      });
  });
};

/**
 * GXC供应量查询接口
 */
const gxc_supply = function() {
  return new Promise(function(resolve, reject) {
    return Apis.instance()
      .db_api()
      .exec('get_objects', [['2.3.1']])
      .then(function(resps) {
        resolve(resps[0]);
      })
      .catch(ex => {
        reject(ex);
      });
  });
};

/**
 * 获取产品信息
 * @param prod_id
 */
const fetch_product = function(prod_id) {
  return new Promise(function(resolve, reject) {
    let prod = ChainStore.objects_by_id.get(prod_id);
    if (prod) {
      prod = prod.toJS();
      prod.schema_contexts = prod.schema_contexts.map(function(schema) {
        if (typeof schema.schema_context === 'string') {
          schema.schema_context = JSON.parse(schema.schema_context);
        }
        return schema;
      });
      resolve(prod);
    } else {
      return Apis.instance()
        .db_api()
        .exec('get_objects', [[prod_id]])
        .then(function(resp) {
          if (!resp || resp.length === 0) {
            reject(new Error('product not found'));
          } else {
            let prod = Object.assign({ schema_contexts: [] }, resp[0]);
            prod.schema_contexts = prod.schema_contexts.map(function(schema) {
              if (typeof schema.schema_context === 'string') {
                schema.schema_context = JSON.parse(schema.schema_context);
              }
              return schema;
            });
            ChainStore.objects_by_id.set(prod_id, Immutable.fromJS(prod));
            resolve(prod);
          }
        })
        .catch(function(ex) {
          reject(ex);
        });
    }
  });
};

const fetch_candidates = function() {
  let filtered_nodes = [
    'aaron',
    'caitlin',
    'kairos',
    'sakura',
    'taffy',
    'init0',
    'init1',
    'init2',
    'init3',
    'init4',
    'init5',
    'init6',
    'init7',
    'init8',
    'init9',
    'init10',
    'miner1',
    'miner2',
    'miner3',
    'miner4',
    'miner5',
    'miner6',
    'miner7',
    'miner8',
    'miner9',
    'miner10',
    'miner11',
    'hrrs',
    'dennis1',
    'david12',
    'marks-lee',
    'robin-green',
    'coinget-bp'
  ];
  return Apis.instance()
    .db_api()
    .exec('get_trust_nodes', [])
    .then(nodes => {
      return Promise.all([
        Apis.instance()
          .db_api()
          .exec('get_full_accounts', [nodes, false]),
        superagent.get(
          'https://static.gxb.io/dapp/blockcity/nodevote/trustNode.json'
        )
      ]).then(results => {
        let accounts = results[0];
        let trustNodeOffChainInfo = JSON.parse(results[1].text).list;
        let candidates = accounts.map(a => {
          let info = trustNodeOffChainInfo.find(
            t => t.accountName === a[1].account.name
          );
          return {
            id: a[1].account.id,
            account: a[1].account.name,
            margin:
              a[1].pledge_balances.length > 0
                ? a[1].pledge_balances[0].amount.amount
                : 0,
            votes: 0,
            extra: info || null
          };
        });
        candidates = candidates.filter(c => {
          return filtered_nodes.indexOf(c.account) === -1 && c.margin > 0;
        });
        let promises = candidates.map(c => {
          return Apis.instance()
            .db_api()
            .exec('get_witness_by_account', [c.id]);
        });
        return Promise.all(promises).then(witnesses => {
          candidates = candidates
            .map((c, i) => {
              c.votes = witnesses[i].total_votes;
              c.total_vote_weights = witnesses[i].total_vote_weights;
              c.commission_rate = witnesses[i].commission_rate;
              c.witness_info = witnesses[i];
              return c;
            })
            .sort((a, b) => {
              if (a.commission_rate === b.commission_rate) {
                return a.total_vote_weights - b.total_vote_weights;
              } else {
                return b.commission_rate - a.commission_rate;
              }
            });
          return candidates.filter((c) => {
            return c.witness_info.is_valid;
          });
        });
      });
    })
    .catch(ex => {
      console.error(ex);
    });
};

export default {
  gxc_supply,
  fetch_block,
  fetch_asset,
  fetch_assets,
  fetch_account,
  fetch_full_account,
  fetch_account_history,
  fetch_account_balance,
  get_vesting_balances,
  fetch_product,
  fetch_candidates
};
<commit_msg>chore: format code<commit_after>import Promise from 'bluebird';
import { Apis } from 'gxbjs-ws';
import { ChainStore } from 'gxbjs';
import Immutable from 'immutable';
import superagent from 'superagent';
import config from '../../config';

/**
 * fetch account information by account name or id
 * @param account_name
 */
const fetch_account = account_name => {
  return Apis.instance()
    .db_api()
    .exec('get_account_by_name', [account_name]);
};

/**
 * fetch full account information by name
 * @param account_name
 * @returns {bluebird}
 */
const fetch_full_account = account => {
  return Apis.instance()
    .db_api()
    .exec('get_full_accounts', [[account], false]);
};

/**
 * fetch account history by account name or id
 * @param id_or_name
 * @returns {bluebird}
 */
const fetch_account_history = (id_or_name, asset_id, operation_type, pageNo, pageSize) => {
  console.log(JSON.parse(config.build.env.ES_PLUGIN));
  return new Promise(function(resolve, reject) {
    if (id_or_name.indexOf('.') === -1) {
      fetch_account(id_or_name)
        .then(account => {
          let param = [
            {
              term: {
                'account_history.account': account.id
              }
            }
          ]
          if (asset_id) {
            param.push({
              term: {
                'operation_history.op_object.amount_.asset_id': asset_id
              }
            })
          }
          if (operation_type) {
            param.push({
              term: {
                'operation_type': operation_type
              }
            })
          }
          superagent
            .post(JSON.parse(config.build.env.ES_PLUGIN))
            .set('Content-Type', 'application/json')
            .send({
              query: {
                bool: {
                  must: param
                }
              },
              from: (pageNo - 1) * pageSize,
              size: pageSize,
              sort: [{ 'block_data.block_time': 'desc' }]
            })
            .end((err, res) => {
              if (err) {
                reject(err);
              } else {
                try {
                  const respList = res.body.hits.hits;
                  const list = [];
                  for (let i = 0; i < respList.length; i++) {
                    list.push(respList[i]._source);
                  }
                  resolve({
                    list,
                    totalCount: res.body.hits.total,
                    pageNo,
                    pageSize
                  });
                } catch (ex) {
                  reject(ex);
                }
              }
            });
        })
        .catch(ex => {
          reject(ex);
        });
    } else {
      superagent
        .post(JSON.parse(config.build.env.ES_PLUGIN))
        .set('Content-Type', 'application/json')
        .send({
          query: {
            bool: {
              must: [
                {
                  term: {
                    'account_history.account': id_or_name
                  }
                }
              ]
            }
          },
          from: (pageNo - 1) * pageSize,
          size: pageSize,
          sort: [{ 'block_data.block_time': 'desc' }]
        })
        .end((err, res) => {
          if (err) {
            reject(err);
          } else {
            try {
              const respList = res.body.hits.hits;
              const list = [];
              for (let i = 0; i < respList.length; i++) {
                list.push(respList[i]._source);
              }
              resolve({
                list,
                totalCount: res.body.hits.total,
                pageNo,
                pageSize
              });
            } catch (ex) {
              reject(ex);
            }
          }
        });
    }
  });
};

/**
 * fetch account balance of GXC by account name or id
 * @param id_or_name
 * @returns {bluebird}
 */
const fetch_account_balance = id_or_name => {
  return new Promise((resolve, reject) => {
    if (id_or_name.indexOf('.') === -1) {
      fetch_account(id_or_name)
        .then(account => {
          return Apis.instance()
            .db_api()
            .exec('get_account_balances', [account.id, []]);
        })
        .then(balances => {
          resolve(balances);
        })
        .catch(ex => {
          reject(ex);
        });
    } else {
      Apis.instance()
        .db_api()
        .exec('get_account_balances', [id_or_name, []])
        .then(balances => {
          resolve(balances);
        })
        .catch(ex => {
          reject(ex);
        });
    }
  });
};

/**
 * fetch vest balance of GXC by account name or id
 * @param id_or_name
 * @returns {bluebird}
 */
const get_vesting_balances = (id_or_name) => {
  return new Promise((resolve, reject) => {
    if (id_or_name.indexOf('.') === -1) {
      fetch_account(id_or_name)
        .then((account) => {
          return Apis.instance().db_api().exec('get_vesting_balances', [account.id, []]);
        })
        .then((balances) => {
          resolve(balances);
        })
        .catch((ex) => {
          reject(ex);
        });
    } else {
      Apis.instance()
        .db_api()
        .exec('get_vesting_balances', [id_or_name, []])
        .then((balances) => {
          resolve(balances);
        })
        .catch((ex) => {
          reject(ex);
        });
    }
  });
};

/**
 * 获取区块信息
 * @param block_height 区块高度
 */
const fetch_block = function(block_height) {
  return new Promise(function(resolve, reject) {
    return Apis.instance()
      .db_api()
      .exec('get_block', [parseInt(block_height)])
      .then(function(block) {
        if (!block) {
          resolve(null);
        } else {
          resolve(block);
        }
      })
      .catch(function(ex) {
        reject(ex);
      });
  });
};

/**
 * 资产信息
 * @param asset_name
 */
const fetch_asset = function(asset_name) {
  return new Promise(function(resolve, reject) {
    return Apis.instance()
      .db_api()
      .exec('lookup_asset_symbols', [[asset_name]])
      .then(function(assets) {
        let asset = assets && assets.length > 0 ? assets[0] : {};
        if (asset.id) {
          Apis.instance()
            .db_api()
            .exec('get_objects', [[asset.dynamic_asset_data_id, asset.issuer]])
            .then(objs => {
              asset.detail = objs[0];
              asset.issuer = objs[1];
              resolve(asset);
            });
        } else {
          resolve(asset);
        }
      })
      .catch(function(ex) {
        reject(ex);
      });
  });
};

/**
 * 链上资产列表
 */
const fetch_assets = function() {
  return new Promise(function(resolve, reject) {
    return Apis.instance()
      .db_api()
      .exec('list_assets', ['A', 100])
      .then(function(assets) {
        let ids = [];
        assets.forEach(asset => {
          ids.push(asset.dynamic_asset_data_id);
          ids.push(asset.issuer);
        });
        Apis.instance()
          .db_api()
          .exec('get_objects', [ids])
          .then(objs => {
            assets.forEach((asset, i) => {
              asset.detail = objs[2 * i];
              asset.issuer = objs[2 * i + 1];
            });
            resolve(assets);
          });
      })
      .catch(function(ex) {
        reject(ex);
      });
  });
};

/**
 * GXC供应量查询接口
 */
const gxc_supply = function() {
  return new Promise(function(resolve, reject) {
    return Apis.instance()
      .db_api()
      .exec('get_objects', [['2.3.1']])
      .then(function(resps) {
        resolve(resps[0]);
      })
      .catch(ex => {
        reject(ex);
      });
  });
};

/**
 * 获取产品信息
 * @param prod_id
 */
const fetch_product = function(prod_id) {
  return new Promise(function(resolve, reject) {
    let prod = ChainStore.objects_by_id.get(prod_id);
    if (prod) {
      prod = prod.toJS();
      prod.schema_contexts = prod.schema_contexts.map(function(schema) {
        if (typeof schema.schema_context === 'string') {
          schema.schema_context = JSON.parse(schema.schema_context);
        }
        return schema;
      });
      resolve(prod);
    } else {
      return Apis.instance()
        .db_api()
        .exec('get_objects', [[prod_id]])
        .then(function(resp) {
          if (!resp || resp.length === 0) {
            reject(new Error('product not found'));
          } else {
            let prod = Object.assign({ schema_contexts: [] }, resp[0]);
            prod.schema_contexts = prod.schema_contexts.map(function(schema) {
              if (typeof schema.schema_context === 'string') {
                schema.schema_context = JSON.parse(schema.schema_context);
              }
              return schema;
            });
            ChainStore.objects_by_id.set(prod_id, Immutable.fromJS(prod));
            resolve(prod);
          }
        })
        .catch(function(ex) {
          reject(ex);
        });
    }
  });
};

const fetch_candidates = function() {
  let filtered_nodes = [
    'aaron',
    'caitlin',
    'kairos',
    'sakura',
    'taffy',
    'init0',
    'init1',
    'init2',
    'init3',
    'init4',
    'init5',
    'init6',
    'init7',
    'init8',
    'init9',
    'init10',
    'miner1',
    'miner2',
    'miner3',
    'miner4',
    'miner5',
    'miner6',
    'miner7',
    'miner8',
    'miner9',
    'miner10',
    'miner11',
    'hrrs',
    'dennis1',
    'david12',
    'marks-lee',
    'robin-green',
    'coinget-bp'
  ];
  return Apis.instance()
    .db_api()
    .exec('get_trust_nodes', [])
    .then(nodes => {
      return Promise.all([
        Apis.instance()
          .db_api()
          .exec('get_full_accounts', [nodes, false]),
        superagent.get(
          'https://static.gxb.io/dapp/blockcity/nodevote/trustNode.json'
        )
      ]).then(results => {
        let accounts = results[0];
        let trustNodeOffChainInfo = JSON.parse(results[1].text).list;
        let candidates = accounts.map(a => {
          let info = trustNodeOffChainInfo.find(
            t => t.accountName === a[1].account.name
          );
          return {
            id: a[1].account.id,
            account: a[1].account.name,
            margin:
              a[1].pledge_balances.length > 0
                ? a[1].pledge_balances[0].amount.amount
                : 0,
            votes: 0,
            extra: info || null
          };
        });
        candidates = candidates.filter(c => {
          return filtered_nodes.indexOf(c.account) === -1 && c.margin > 0;
        });
        let promises = candidates.map(c => {
          return Apis.instance()
            .db_api()
            .exec('get_witness_by_account', [c.id]);
        });
        return Promise.all(promises).then(witnesses => {
          candidates = candidates
            .map((c, i) => {
              c.votes = witnesses[i].total_votes;
              c.total_vote_weights = witnesses[i].total_vote_weights;
              c.commission_rate = witnesses[i].commission_rate;
              c.witness_info = witnesses[i];
              return c;
            })
            .sort((a, b) => {
              if (a.commission_rate === b.commission_rate) {
                return a.total_vote_weights - b.total_vote_weights;
              } else {
                return b.commission_rate - a.commission_rate;
              }
            });
          return candidates.filter((c) => {
            return c.witness_info.is_valid;
          });
        });
      });
    })
    .catch(ex => {
      console.error(ex);
    });
};

export default {
  gxc_supply,
  fetch_block,
  fetch_asset,
  fetch_assets,
  fetch_account,
  fetch_full_account,
  fetch_account_history,
  fetch_account_balance,
  get_vesting_balances,
  fetch_product,
  fetch_candidates
};
<|endoftext|>


<commit_before>/*jshint white: false, node: true, vars: true, indent: 4 */
(function (module, __dirname) {
    "use strict";

    var compressor = require('node-minify');

    var HTTP_SUCCESS = 200,
        uglifyjs = require("uglify-js"),
        util = require("./util"),
        Batch = require("batch"),
        url = require("url"),
        fs = require("fs"),
        jsp = uglifyjs.parser,
        pro = uglifyjs.uglify,
        locate = util.locate,
        locateSync = util.locateSync;

    function matchForJS(req) {
        var parsed = url.parse(req.url, true, true);

        console.log("Current parsed.pathname=" + parsed.pathname);

        return parsed.pathname === "/js/compressed.js";
    }

    function matchForCSS(req) {
        var parsed = url.parse(req.url, true, true);

        return parsed.pathname === "/css/compressed.css";
    }

    function load(module, script, cb) {
        return locate(module["public"], script, function (err, quaified) {
            if (err) {
                return cb(err);
            }

            return fs.readFile(quaified, "utf-8", cb);
        });
    }

    function loadSync(module, script) {
        var qualified = locateSync(module["public"], script);
        return fs.readFileSync(qualified, "utf-8");
    }

    function uglify(scripts,  cb) {
        var ast = jsp.parse(scripts);

        ast = pro.ast_mangle(ast);
        ast = pro.ast_squeeze(ast);

        return cb(undefined, pro.gen_code(ast));
    }

    module.exports = function (module, logger) {

        if(process.env.NODE_ENV !== "production") {
            logger("Running in development mode");
            return function(req, res, next) {
                next();
            };
        }

        logger("Running in production mode");

        var trailingScripts = module.trailingScripts;

        module.trailingScripts = [ "js/compressed.js" ];

        module.scriptCache = "";

        //We should lock (make synchronous calls) until we finish so that we don't run into a race condition where we aren't cached, but the user can request
        //Synchronous calls are good in startup situtations where you want pre-initialize steps!
        trailingScripts.forEach(function(script) {

                try {
                    var cachedScript = loadSync(module, script);
                    logger("adding script to compression: " + script);
                    module.scriptCache+= ("\n" + cachedScript);
                } catch(e) {
                    logger("While loading " + script + ": " + e.message);
                }
        });

        logger("starting compression...");
        var ast = jsp.parse(module.scriptCache);
        ast = pro.ast_mangle(ast);
        ast = pro.ast_squeeze(ast);
        module.scriptCache = pro.gen_code(ast);
        logger("compression complete");

        return function (req, res, next) {

                if(matchForJS(req)) {
                    res.writeHead(HTTP_SUCCESS, {
                        'Content-Type': 'application/json; charset=UTF-8',
                        'Content-Length': module.scriptCache.length + 3
                    });
                    res.end(module.scriptCache);
                } else if(matchForCSS(req)) {

                } else {
                    return next();
                }
        };
    };
})(module, __dirname);
<commit_msg>fixing not required module<commit_after>/*jshint white: false, node: true, vars: true, indent: 4 */
(function (module, __dirname) {
    "use strict";

    var HTTP_SUCCESS = 200,
        uglifyjs = require("uglify-js"),
        util = require("./util"),
        url = require("url"),
        fs = require("fs"),
        jsp = uglifyjs.parser,
        pro = uglifyjs.uglify,
        locate = util.locate,
        locateSync = util.locateSync;

    function matchForJS(req) {
        var parsed = url.parse(req.url, true, true);

        console.log("Current parsed.pathname=" + parsed.pathname);

        return parsed.pathname === "/js/compressed.js";
    }

    function matchForCSS(req) {
        var parsed = url.parse(req.url, true, true);

        return parsed.pathname === "/css/compressed.css";
    }

    function load(module, script, cb) {
        return locate(module["public"], script, function (err, quaified) {
            if (err) {
                return cb(err);
            }

            return fs.readFile(quaified, "utf-8", cb);
        });
    }

    function loadSync(module, script) {
        var qualified = locateSync(module["public"], script);
        return fs.readFileSync(qualified, "utf-8");
    }

    function uglify(scripts,  cb) {
        var ast = jsp.parse(scripts);

        ast = pro.ast_mangle(ast);
        ast = pro.ast_squeeze(ast);

        return cb(undefined, pro.gen_code(ast));
    }

    module.exports = function (module, logger) {

        if(process.env.NODE_ENV !== "production") {
            logger("Running in development mode");
            return function(req, res, next) {
                next();
            };
        }

        logger("Running in production mode");

        var trailingScripts = module.trailingScripts;

        module.trailingScripts = [ "js/compressed.js" ];

        module.scriptCache = "";

        //We should lock (make synchronous calls) until we finish so that we don't run into a race condition where we aren't cached, but the user can request
        //Synchronous calls are good in startup situtations where you want pre-initialize steps!
        trailingScripts.forEach(function(script) {

                try {
                    var cachedScript = loadSync(module, script);
                    logger("adding script to compression: " + script);
                    module.scriptCache+= ("\n" + cachedScript);
                } catch(e) {
                    logger("While loading " + script + ": " + e.message);
                }
        });

        logger("starting compression...");
        var ast = jsp.parse(module.scriptCache);
        ast = pro.ast_mangle(ast);
        ast = pro.ast_squeeze(ast);
        module.scriptCache = pro.gen_code(ast);
        logger("compression complete");

        return function (req, res, next) {

                if(matchForJS(req)) {
                    res.writeHead(HTTP_SUCCESS, {
                        'Content-Type': 'application/json; charset=UTF-8',
                        'Content-Length': module.scriptCache.length + 3
                    });
                    res.end(module.scriptCache);
                } else if(matchForCSS(req)) {

                } else {
                    return next();
                }
        };
    };
})(module, __dirname);
<|endoftext|>


<commit_before>//----------------------------------------------------------------------------------------------------------------------
// Implements a model based API for TrivialDB.
//
// @module models.js
//----------------------------------------------------------------------------------------------------------------------

var util = require('util');

var _ = require('lodash');
var oftype = require('oftype');
var Promise = require('bluebird');

var errors = require('./errors');

//----------------------------------------------------------------------------------------------------------------------

function Model(modelDef)
{
    this.$$updates = {};
    this.$$values = modelDef || {};

    // Dirty can be read by external things, but we prefix it with '$' to prevent property collision.
    this.$dirty = true;

} // end Model

function buildSchema(model)
{
    var proto = model.prototype;
    var pk = proto.$$db.options.pk ? proto.$$db.options.pk : 'id';

    // Setup the id property
    Object.defineProperty(proto, 'id', {
        get: function(){ return this.$$values[pk]; },
        set: function(val)
        {
            // We only allow setting in the event that id is undefined.
            if(!this.$$values.id)
            {
                this.$dirty = true;
                this.$$values[pk] = val;
            } // end if
        }
    });

    // Setup the schema properties
    _.forIn(proto.$$schema, function(typeDef, key)
    {
        var type = typeDef.type || typeDef;

        Object.defineProperty(proto, key, {
            get: function()
            {
                // Check to see if we have a value in $$updates, if not, then we check $$values. Finally, if val is
                // still undefined, we grab the default value.
                var val = _.has(this.$$updates, key) ? this.$$updates[key] : this.$$values[key];
                val = val === undefined ? typeDef.default : val;

                switch(type)
                {
                    case Date:
                        return _.clone(_.isDate(val) ? val : new Date(val));
                    default:
                        return _.clone(val);
                } // end switch
            },
            set: function(newVal)
            {
                this.$dirty = true;
                switch(type)
                {
                    case Date:
                        this.$$updates[key] =  _.isDate(newVal) ? newVal : new Date(newVal);
                        break;
                    default:
                        this.$$updates[key] = newVal;
                        break;
                } // end switch
            }
        });
    });
} // end buildSchema

Model.prototype.save = function(skipValidation)
{
    var self = this;

    // First, we validate
    var validatePromise;
    if(skipValidation)
    {
        validatePromise = Promise.resolve();
    }
    else
    {
        validatePromise = this.validate();
    } // end if

    // Now, we handle saving
    return validatePromise.then(function()
    {
        if(self.$dirty)
        {
            var pk = self.$$db.options.pk ? self.$$db.options.pk : 'id';

            return self.$$db.store(self.id, _.assign(self.$$values, self.$$updates))
                .then(function(id)
                {
                    self.$$updates = {};
                    self.$$values[pk] = id;
                    self.$dirty = false;
                    return self;
                });
        }
        else
        {
            return Promise.resolve(self);
        } // end if
    });
}; // end save

Model.prototype.sync = function(force)
{
    var self = this;
    return this.$$db.get(this.id)
        .then(function(obj)
        {
            // Only update if we're not dirty, or are forcing a sync.
            if(obj && !self.$dirty || force)
            {
                self.$$values = obj;
                self.$$updates = {};
            } // end if
        });
}; // end sync

Model.prototype.remove = function()
{
    var self = this;
    return this.$$db.remove(this.id)
        .then(function()
        {
            self.$$values = {};
        });
}; // end remove

Model.prototype.toJSON = function()
{
    var self = this;
    return _.transform(this.$$schema, function(results, value, key)
    {
        results[key] = self[key];
    }, { id: self.id });
}; // end toJSON

Model.prototype.validate = function()
{
    var self = this;
    return Promise.try(function()
    {
        self._validate(self.$$schema, self.$$values);
    });
}; // end validate

var messages = {
    requiredValue: _.template("Key ${key} requires a value!"),
    invalidChoice: _.template("Key ${key}: Value ${failedVal} is not a valid choice. Possible values: ${choices}"),
};

// Inner validation function
Model.prototype._validate = function(schema, values)
{
    var self = this;
    _.forIn(schema, function(type, key)
    {
        var typeDef = {};

        // Check to see if we have a value in $$updates, if not, then we check $$values. Finally,
        var val = _.has(self.$$updates, key) ? self.$$updates[key] : values[key];

        if(_.isPlainObject(type) && type.type)
        {
            // `type` is an options object with the key `type`.
            typeDef = type;
            type = type.type;
        }
        else if(_.isPlainObject(type))
        {
            // `type` is an object defining a nested schema.
            return self._validate(type, val);
        }
        else if(_.isArray(type) && type.length !== 0)
        {
            //TODO: Support typed arrays
            throw new Error("Typed arrays are not supported.");
        } // end if

        // If val is still undefined, we grab the default value.
        val = val === undefined ? typeDef.default : val;

        // Validate the value
        if(val === null || val === undefined)
        {
            if(typeDef.required)
            {
                throw new errors.ValidationError(key, type, messages.requiredValue({key: key}));
            } // end if
        }
        else
        {
            // TODO: May want to consider switching to value: https://www.npmjs.org/package/value

            // Make sure we are of the specified type
            if(type === Date)
            {
                if(isNaN(new Date(val).getTime()))
                {
                    throw new errors.ValidationError(key, type);
                } // end if
            }
            else if(!oftype(val, type, { primitiveObject: true }))
            {
                throw new errors.ValidationError(key, type);
            } // end if

            // If we have a 'choices' property, make sure we are one of the allowed values
            if(_.isArray(typeDef.choices))
            {
                // Ensure the value is an array, to simplify the logic
                val = _.isArray(val) ? val : [val];

                // Iterate over every value in the val array, and check it against our choices.
                var failedVal;
                _.each(val, function(value)
                {
                    if(!_.contains(typeDef.choices, value))
                    {
                        failedVal = value;
                    } // end if
                });

                if(failedVal)
                {
                    // This will only return the last invalid choice, as opposed to all of them. This could be
                    // refactored later, if that is decided to be worth it.
                    throw new errors.ValidationError(key, type,
                        messages.invalidChoice({key: key, failedVal: failedVal, choices: typeDef.choices})
                    );
                } // end if
            } // end if
        } // end if
    });
}; // end _validate

//----------------------------------------------------------------------------------------------------------------------

function defineModel(dbName, schemaDef, dbOptions)
{
    var trivialdb = require('../trivialdb');
    var db = trivialdb.db(dbName, dbOptions);

    // Build a custom Model Instance
    function JDBModel(modelDef)
    {
        Model.call(this, modelDef);
    } // end JDBModel

    // Inherit from Model
    util.inherits(JDBModel, Model);

    JDBModel.prototype.$$db = db;
    JDBModel.prototype.$$schema = schemaDef;

    /**
     * The schema definition of the model.
     */
    JDBModel.schema = schemaDef;

    // Build the schema for this model.
    buildSchema(JDBModel);

    /**
     * Gets a single model instance, by id. If a document with that id is not found, it resolves to a
     * `DocumentNotFound`.
     *
     * @param {string} id - The id of the document to retrieve
     * @returns {Promise}
     * @static
     */
    JDBModel.get = function(id)
    {
        return db.get(id)
            .then(function(obj)
            {
                if(obj)
                {
                    var pk = dbOptions.pk ? dbOptions.pk : 'id';
                    var model = new JDBModel(obj);
                    model.$$values[pk] = id;
                    model.$dirty = false;

                    return model;
                }
                else
                {
                    return Promise.reject(new errors.DocumentNotFound(id));
                } // end if
            });
    }; // end get

    JDBModel.all = function()
    {
        return this.filter();
    }; // end all

    JDBModel.filter = function(filter)
    {
        return db.filter(filter)
            .then(function(filtered)
            {
                return _.reduce(filtered, function(models, value, id)
                {
                    var model = new JDBModel(value);
                    model.$$values.id = id;
                    model.$dirty = false;
                    models.push(model);

                    return models;
                }, []);
            });
    }; // end filter

    JDBModel.remove = function(filter)
    {
        return db.remove(filter);
    }; // end remove

    JDBModel.removeAll = function()
    {
        db.values = {};
        return db.sync();
    }; // end removeAll

    // Return the new model function
    return JDBModel;
} // end defineModel

//----------------------------------------------------------------------------------------------------------------------

module.exports = {
    Model: Model,
    defineModel: defineModel
};

//----------------------------------------------------------------------------------------------------------------------
<commit_msg>Pass `updates` into _validate(), so it also follows the hierarchy like `values` does.<commit_after>//----------------------------------------------------------------------------------------------------------------------
// Implements a model based API for TrivialDB.
//
// @module models.js
//----------------------------------------------------------------------------------------------------------------------

var util = require('util');

var _ = require('lodash');
var oftype = require('oftype');
var Promise = require('bluebird');

var errors = require('./errors');

//----------------------------------------------------------------------------------------------------------------------

function Model(modelDef)
{
    this.$$updates = {};
    this.$$values = modelDef || {};

    // Dirty can be read by external things, but we prefix it with '$' to prevent property collision.
    this.$dirty = true;

} // end Model

function buildSchema(model)
{
    var proto = model.prototype;
    var pk = proto.$$db.options.pk ? proto.$$db.options.pk : 'id';

    // Setup the id property
    Object.defineProperty(proto, 'id', {
        get: function(){ return this.$$values[pk]; },
        set: function(val)
        {
            // We only allow setting in the event that id is undefined.
            if(!this.$$values.id)
            {
                this.$dirty = true;
                this.$$values[pk] = val;
            } // end if
        }
    });

    // Setup the schema properties
    _.forIn(proto.$$schema, function(typeDef, key)
    {
        var type = typeDef.type || typeDef;

        Object.defineProperty(proto, key, {
            get: function()
            {
                // Check to see if we have a value in $$updates, if not, then we check $$values. Finally, if val is
                // still undefined, we grab the default value.
                var val = _.has(this.$$updates, key) ? this.$$updates[key] : this.$$values[key];
                val = val === undefined ? typeDef.default : val;

                switch(type)
                {
                    case Date:
                        return _.clone(_.isDate(val) ? val : new Date(val));
                    default:
                        return _.clone(val);
                } // end switch
            },
            set: function(newVal)
            {
                this.$dirty = true;
                switch(type)
                {
                    case Date:
                        this.$$updates[key] =  _.isDate(newVal) ? newVal : new Date(newVal);
                        break;
                    default:
                        this.$$updates[key] = newVal;
                        break;
                } // end switch
            }
        });
    });
} // end buildSchema

Model.prototype.save = function(skipValidation)
{
    var self = this;

    // First, we validate
    var validatePromise;
    if(skipValidation)
    {
        validatePromise = Promise.resolve();
    }
    else
    {
        validatePromise = this.validate();
    } // end if

    // Now, we handle saving
    return validatePromise.then(function()
    {
        if(self.$dirty)
        {
            var pk = self.$$db.options.pk ? self.$$db.options.pk : 'id';

            return self.$$db.store(self.id, _.assign(self.$$values, self.$$updates))
                .then(function(id)
                {
                    self.$$updates = {};
                    self.$$values[pk] = id;
                    self.$dirty = false;
                    return self;
                });
        }
        else
        {
            return Promise.resolve(self);
        } // end if
    });
}; // end save

Model.prototype.sync = function(force)
{
    var self = this;
    return this.$$db.get(this.id)
        .then(function(obj)
        {
            // Only update if we're not dirty, or are forcing a sync.
            if(obj && !self.$dirty || force)
            {
                self.$$values = obj;
                self.$$updates = {};
            } // end if
        });
}; // end sync

Model.prototype.remove = function()
{
    var self = this;
    return this.$$db.remove(this.id)
        .then(function()
        {
            self.$$values = {};
        });
}; // end remove

Model.prototype.toJSON = function()
{
    var self = this;
    return _.transform(this.$$schema, function(results, value, key)
    {
        results[key] = self[key];
    }, { id: self.id });
}; // end toJSON

Model.prototype.validate = function()
{
    var self = this;
    return Promise.try(function()
    {
        self._validate(self.$$schema, self.$$updates, self.$$values);
    });
}; // end validate

var messages = {
    requiredValue: _.template("Key ${key} requires a value!"),
    invalidChoice: _.template("Key ${key}: Value ${failedVal} is not a valid choice. Possible values: ${choices}"),
};

// Inner validation function
Model.prototype._validate = function(schema, updates, values)
{
    var self = this;
    _.forIn(schema, function(type, key)
    {
        var typeDef = {};

        // Check to see if we have a value in $$updates, if not, then we check $$values. Finally,
        var val = _.has(updates, key) ? updates[key] : values[key];

        if(_.isPlainObject(type) && type.type)
        {
            // `type` is an options object with the key `type`.
            typeDef = type;
            type = type.type;
        }
        else if(_.isPlainObject(type))
        {
            // `type` is an object defining a nested schema.
            return self._validate(type, updates[key], values[key]);
        }
        else if(_.isArray(type) && type.length !== 0)
        {
            //TODO: Support typed arrays
            throw new Error("Typed arrays are not supported.");
        } // end if

        // If val is still undefined, we grab the default value.
        val = val === undefined ? typeDef.default : val;

        // Validate the value
        if(val === null || val === undefined)
        {
            if(typeDef.required)
            {
                throw new errors.ValidationError(key, type, messages.requiredValue({key: key}));
            } // end if
        }
        else
        {
            // TODO: May want to consider switching to value: https://www.npmjs.org/package/value

            // Make sure we are of the specified type
            if(type === Date)
            {
                if(isNaN(new Date(val).getTime()))
                {
                    throw new errors.ValidationError(key, type);
                } // end if
            }
            else if(!oftype(val, type, { primitiveObject: true }))
            {
                throw new errors.ValidationError(key, type);
            } // end if

            // If we have a 'choices' property, make sure we are one of the allowed values
            if(_.isArray(typeDef.choices))
            {
                // Ensure the value is an array, to simplify the logic
                val = _.isArray(val) ? val : [val];

                // Iterate over every value in the val array, and check it against our choices.
                var failedVal;
                _.each(val, function(value)
                {
                    if(!_.contains(typeDef.choices, value))
                    {
                        failedVal = value;
                    } // end if
                });

                if(failedVal)
                {
                    // This will only return the last invalid choice, as opposed to all of them. This could be
                    // refactored later, if that is decided to be worth it.
                    throw new errors.ValidationError(key, type,
                        messages.invalidChoice({key: key, failedVal: failedVal, choices: typeDef.choices})
                    );
                } // end if
            } // end if
        } // end if
    });
}; // end _validate

//----------------------------------------------------------------------------------------------------------------------

function defineModel(dbName, schemaDef, dbOptions)
{
    var trivialdb = require('../trivialdb');
    var db = trivialdb.db(dbName, dbOptions);

    // Build a custom Model Instance
    function JDBModel(modelDef)
    {
        Model.call(this, modelDef);
    } // end JDBModel

    // Inherit from Model
    util.inherits(JDBModel, Model);

    JDBModel.prototype.$$db = db;
    JDBModel.prototype.$$schema = schemaDef;

    /**
     * The schema definition of the model.
     */
    JDBModel.schema = schemaDef;

    // Build the schema for this model.
    buildSchema(JDBModel);

    /**
     * Gets a single model instance, by id. If a document with that id is not found, it resolves to a
     * `DocumentNotFound`.
     *
     * @param {string} id - The id of the document to retrieve
     * @returns {Promise}
     * @static
     */
    JDBModel.get = function(id)
    {
        return db.get(id)
            .then(function(obj)
            {
                if(obj)
                {
                    var pk = dbOptions.pk ? dbOptions.pk : 'id';
                    var model = new JDBModel(obj);
                    model.$$values[pk] = id;
                    model.$dirty = false;

                    return model;
                }
                else
                {
                    return Promise.reject(new errors.DocumentNotFound(id));
                } // end if
            });
    }; // end get

    JDBModel.all = function()
    {
        return this.filter();
    }; // end all

    JDBModel.filter = function(filter)
    {
        return db.filter(filter)
            .then(function(filtered)
            {
                return _.reduce(filtered, function(models, value, id)
                {
                    var model = new JDBModel(value);
                    model.$$values.id = id;
                    model.$dirty = false;
                    models.push(model);

                    return models;
                }, []);
            });
    }; // end filter

    JDBModel.remove = function(filter)
    {
        return db.remove(filter);
    }; // end remove

    JDBModel.removeAll = function()
    {
        db.values = {};
        return db.sync();
    }; // end removeAll

    // Return the new model function
    return JDBModel;
} // end defineModel

//----------------------------------------------------------------------------------------------------------------------

module.exports = {
    Model: Model,
    defineModel: defineModel
};

//----------------------------------------------------------------------------------------------------------------------
<|endoftext|>


<commit_before>// @import Injerit.js
// @import ElementStore
// @import ElementStore.Utils
// @import callbacks
// @import hash
// @import dom_event_delegator
// @import events

(function(g) {

var _guid = 0;

var Module = Object.extend({

	includes: [
		Callbacks.Utils,
		Events.Notifications,
		ElementStore.Utils
	],

	self: {
		manager: null,

		getManager: function getManager() {
			return Module.manager;
		},

		unregister: function unregister(module) {
			if (Module.manager) {
				Module.manager.unregisterModule(module);
			}
		}
	},

	prototype: {

		actions: {},

		delegator: null,

		element: null,

		elementStore: {},

		guid: null,

		options: {
			actionPrefix: null
		},

		init: function init(elementOrId, options) {
			this.guid = _guid++;
			this.element = typeof elementOrId === "string" ? document.getElementById(elementOrId) : elementOrId;

			if (!this.element) {
				throw new Error("Could not find element: " + elementOrId);
			}

			if (!this.hasOwnProperty("options")) {
				this.options = new Hash();
			}

			this._initOptions(this.options);

			if (options) {
				this.options.merge(options);
			}

			if (!this.delegator) {
				this.delegator = new dom.events.Delegator();
			}

			this.delegator.delegate = this;
			this.delegator.node = this.element;

			if (this.options.actionPrefix) {
				this.delegator.setActionPrefix(this.options.actionPrefix);
			}

			this.delegator.init();

			this._initActions();
			this._initCallbacks();
			this._initNotifications();
			this.callbacks.execute("beforeElementStoreInit");
			this.initElementStore(this.element);
			this.callbacks.execute("beforeReady");
			this._ready();
			this.callbacks.execute("afterReady");

			return this;
		},

		destructor: function destructor(keepElement) {
			this.callbacks.execute("beforeDestroy");

			this.constructor.unregister(this);
			this.destroyElementStore();
			this.destroyCallbacks();

			if (this.delegator) {
				this.delegator.destructor();
			}

			if (!keepElement && this.element) {
				this.element.parentNode.removeChild(this.element);
			}

			if (this.options) {
				this.options.destructor();
			}

			this.actions = this.element = this.delegator = this.options = null;
		},

		focus: function focus() {
			var els = this.element.getElementsByTagName("*");
			var i = 0, length = els.length, el;

			for (i; i < length; i++) {
				el = els[i];

				if (el.tagName === "A" || el.tagName === "BUTTON" || el.tagName === "TEXTAREA" || el.tagName === "SELECT" || (el.tagName === "INPUT" && el.type !== "hidden")) {
					if (el.focus) {
						el.focus();
					}

					if (el.select) {
						el.select();
					}

					break;
				}
			}
		},

		_ready: function _ready() {

		},

		_initActions: function _initActions() {
			var actions = new Hash(), proto = this.__proto__;

			while (proto) {
				if (proto.hasOwnProperty("actions")) {
					actions.safeMerge(proto.actions);
				}

				proto = proto.__proto__;
			}

			this.delegator.setEventActionMapping(actions);
		},

		_initCallbacks: function _initCallbacks() {
			var types = new Hash(), proto = this.__proto__;

			while (proto) {
				if (proto.hasOwnProperty("callbacks")) {
					types.safeMerge(proto.callbacks);
				}

				proto = proto.__proto__;
			}

			this.initCallbacks(types);
		},

		_initOptions: function _initOptions() {
			var proto = this.__proto__;

			while (proto) {
				if (proto.hasOwnProperty("options")) {
					this.options.safeMerge(proto.options);
				}

				proto = proto.__proto__;
			}
		},

		setOptions: function setOptions(overrides) {
			if (!this.hasOwnProperty("options")) {
				this.options = overrides;
			}
			else {
				this.options.merge(overrides);
			}
		}

	}

});

// Make globally available
g.Module = Module;

})(window);<commit_msg>Refactory Module#focus to accept bool arg: true to focus anything, false to focus fields only<commit_after>// @import Injerit.js
// @import ElementStore
// @import ElementStore.Utils
// @import callbacks
// @import hash
// @import dom_event_delegator
// @import events

(function(g) {

var _guid = 0;

var Module = Object.extend({

	includes: [
		Callbacks.Utils,
		Events.Notifications,
		ElementStore.Utils
	],

	self: {
		manager: null,

		getManager: function getManager() {
			return Module.manager;
		},

		unregister: function unregister(module) {
			if (Module.manager) {
				Module.manager.unregisterModule(module);
			}
		}
	},

	prototype: {

		actions: {},

		delegator: null,

		element: null,

		elementStore: {},

		guid: null,

		options: {
			actionPrefix: null
		},

		init: function init(elementOrId, options) {
			this.guid = _guid++;
			this.element = typeof elementOrId === "string" ? document.getElementById(elementOrId) : elementOrId;

			if (!this.element) {
				throw new Error("Could not find element: " + elementOrId);
			}

			if (!this.hasOwnProperty("options")) {
				this.options = new Hash();
			}

			this._initOptions(this.options);

			if (options) {
				this.options.merge(options);
			}

			if (!this.delegator) {
				this.delegator = new dom.events.Delegator();
			}

			this.delegator.delegate = this;
			this.delegator.node = this.element;

			if (this.options.actionPrefix) {
				this.delegator.setActionPrefix(this.options.actionPrefix);
			}

			this.delegator.init();

			this._initActions();
			this._initCallbacks();
			this._initNotifications();
			this.callbacks.execute("beforeElementStoreInit");
			this.initElementStore(this.element);
			this.callbacks.execute("beforeReady");
			this._ready();
			this.callbacks.execute("afterReady");

			return this;
		},

		destructor: function destructor(keepElement) {
			this.callbacks.execute("beforeDestroy");

			this.constructor.unregister(this);
			this.destroyElementStore();
			this.destroyCallbacks();

			if (this.delegator) {
				this.delegator.destructor();
			}

			if (!keepElement && this.element) {
				this.element.parentNode.removeChild(this.element);
			}

			if (this.options) {
				this.options.destructor();
			}

			this.actions = this.element = this.delegator = this.options = null;
		},

		focus: function focus(anything) {
			var els = this.element.getElementsByTagName("*");
			var i = 0, length = els.length, el;

			if (anything) {
				for (i; i < length; i++) {
					el = els[i];

					if (el.tagName === "A" || el.tagName === "BUTTON" || el.tagName === "TEXTAREA" || el.tagName === "SELECT" || (el.tagName === "INPUT" && el.type !== "hidden")) {
						if (el.focus) {
							el.focus();
						}

						if (el.select) {
							el.select();
						}

						break;
					}
				}
			}
			else {
				for (i; i < length; i++) {
					el = els[i];

					if (el.tagName === "TEXTAREA" || el.tagName === "SELECT" || (el.tagName === "INPUT" && el.type !== "hidden")) {
						if (el.focus) {
							el.focus();
						}

						if (el.select) {
							el.select();
						}

						break;
					}
				}
			}
		},

		_ready: function _ready() {

		},

		_initActions: function _initActions() {
			var actions = new Hash(), proto = this.__proto__;

			while (proto) {
				if (proto.hasOwnProperty("actions")) {
					actions.safeMerge(proto.actions);
				}

				proto = proto.__proto__;
			}

			this.delegator.setEventActionMapping(actions);
		},

		_initCallbacks: function _initCallbacks() {
			var types = new Hash(), proto = this.__proto__;

			while (proto) {
				if (proto.hasOwnProperty("callbacks")) {
					types.safeMerge(proto.callbacks);
				}

				proto = proto.__proto__;
			}

			this.initCallbacks(types);
		},

		_initOptions: function _initOptions() {
			var proto = this.__proto__;

			while (proto) {
				if (proto.hasOwnProperty("options")) {
					this.options.safeMerge(proto.options);
				}

				proto = proto.__proto__;
			}
		},

		setOptions: function setOptions(overrides) {
			if (!this.hasOwnProperty("options")) {
				this.options = overrides;
			}
			else {
				this.options.merge(overrides);
			}
		}

	}

});

// Make globally available
g.Module = Module;

})(window);<|endoftext|>


<commit_before>const { resolve, relative } = require('path')
const { defaultsDeep, omit, startCase } = require('lodash')
const f7BuildConfig = require('./f7-config')

const resolvePath = (...args) => resolve(__dirname, ...args)

module.exports = function nuxt7 (_options) {
  const options = defaultsDeep({}, _options, this.options.framework7, defaults)

  // CamelCase component names
  options.build._components = normalizeComponents(options.build.components)

  // Router Mode
  if (options.mode === 'history') {
    options.view.pushStateSeparator = "__window.location.origin ? '' : '#'__"
    options.view.pushStateRoot = '__window.location.origin__'
  }

  // Force mode to SPA
  this.options.mode = 'spa'
  this.options.render.ssr = false
  this.options.build.ssr = false

  // Disable postcss for less transformations
  this.options.build.postcss = false

  // Extend webpack config
  this.extendBuild(config => extendConfig(config, options))

  // Global theme color
  if (options.themeColor) {
    options.build.ios.themeColor = options.themeColor
    options.build.md.themeColor = options.themeColor

    if (!this.options.manifest) {
      this.options.manifest = {}
    }
    this.options.manifest.theme_color = options.themeColor
  }

  // Move F7 dependencies to common chunk
  this.addVendor(`framework7-vue`)
  this.addVendor('dom7')
  this.addVendor('template7')

  // Webpack 4 cacheGroup
  if (this.options.build.optimization) {
    const { cacheGroups } = this.options.build.optimization.splitChunks

    cacheGroups.framework7 = {
      test: /node_modules[\\/](framework7|framework7-vue|dom7|template7|ssr-window|path-to-regexp)[\\/]/,
      chunks: 'all',
      priority: 10,
      name: 'framework7'
    }
  }

  // Remove custom keys for framework7 plugin
  options.plugin = omit(options, extraKeys)

  // Add templates
  addTemplates.call(this, options)

  // Icons
  if (options.f7Icons) {
    options.f7IconsSrc = relative(
      this.options.buildDir,
      resolvePath('fonts/framework7-icons.css')
    )
  }

  if (options.mdIcons) {
    options.mdIconsSrc = relative(
      this.options.buildDir,
      resolvePath('fonts/material-icons.css')
    )
  }

  // Enable nativeUI for a better Native experience
  if (!this.options.meta) {
    this.options.meta = {}
  }
  if (this.options.meta.nativeUI === undefined) {
    this.options.meta.nativeUI = true
  }

  // Require PWA module
  if (options.pwa !== false) {
    return this.requireModule('@nuxtjs/pwa')
  }

  return Promise.resolve()
}

function extendConfig (config, options) {
  // Increase performance check limits to 2M (non-gzipped)
  const MAX_SIZE = 2 * 1024 * 1024
  Object.assign(config.performance, {
    maxEntrypointSize: MAX_SIZE,
    maxAssetSize: MAX_SIZE
  })
}

function addTemplates (options) {
  // Framework7 plugin
  this.addPlugin({
    src: resolvePath('templates/framework7/f7.plugin.js'),
    fileName: 'framework7/f7.plugin.js',
    options
  })

  // Copy all templates
  for (const template of templates) {
    this.addTemplate({
      src: resolvePath('templates/' + template),
      fileName: template,
      options
    })
  }
}

function tryResolve (path) {
  try {
    return require.resolve(path)
  } catch (err) {
    return null
  }
}

function normalizeComponents (components) {
  return components.map((name) => ({
    name,
    camelName: startCase(name).replace(/ /g, ''),
    js: tryResolve(`framework7/dist/components/${name}/${name}.js`),
    less: tryResolve(`framework7/dist/components/${name}/${name}.less`)
  }))
}

const templates = [
  // Framework 7
  'framework7/f7.router.js',
  'framework7/f7.styles.less',
  'framework7/f7.components.js',
  // Nuxt
  'App.js',
  'components/nuxt.js',
  'layouts/default.vue',
  'router.js'
]

const extraKeys = [
  'build',
  'mode',
  'themeColor',
  'css',
  'f7Icons',
  'mdIcons',
  'f7IconsSrc',
  'mdIconsSrc',
  'pwa',
  'routes',
  'plugin'
]

const defaults = {
  build: Object.assign({}, f7BuildConfig),

  mode: 'hash',
  css: true,
  f7Icons: true,
  mdIcons: true,

  routes: {},

  view: {
    main: true,
    pushState: true,
    pushStateRoot: null
  }
}
<commit_msg>fix: transpile framework7 es builds<commit_after>const { resolve, relative } = require('path')
const { defaultsDeep, omit, startCase } = require('lodash')
const f7BuildConfig = require('./f7-config')

const resolvePath = (...args) => resolve(__dirname, ...args)

module.exports = function nuxt7 (_options) {
  const options = defaultsDeep({}, _options, this.options.framework7, defaults)

  // CamelCase component names
  options.build._components = normalizeComponents(options.build.components)

  // Router Mode
  if (options.mode === 'history') {
    options.view.pushStateSeparator = "__window.location.origin ? '' : '#'__"
    options.view.pushStateRoot = '__window.location.origin__'
  }

  // Force mode to SPA
  this.options.mode = 'spa'
  this.options.render.ssr = false
  this.options.build.ssr = false

  // Disable postcss for less transformations
  this.options.build.postcss = false

  // Extend webpack config
  this.extendBuild(config => extendConfig(config, options))

  // Global theme color
  if (options.themeColor) {
    options.build.ios.themeColor = options.themeColor
    options.build.md.themeColor = options.themeColor

    if (!this.options.manifest) {
      this.options.manifest = {}
    }
    this.options.manifest.theme_color = options.themeColor
  }

  // Move F7 dependencies to common chunk
  this.addVendor(`framework7-vue`)
  this.addVendor('dom7')
  this.addVendor('template7')

  // Webpack 4 cacheGroup
  if (this.options.build.optimization) {
    const { cacheGroups } = this.options.build.optimization.splitChunks

    cacheGroups.framework7 = {
      test: /node_modules[\\/](framework7|framework7-vue|dom7|template7|ssr-window|path-to-regexp)[\\/]/,
      chunks: 'all',
      priority: 10,
      name: 'framework7'
    }
  }

  // Remove custom keys for framework7 plugin
  options.plugin = omit(options, extraKeys)

  // Add templates
  addTemplates.call(this, options)

  // Icons
  if (options.f7Icons) {
    options.f7IconsSrc = relative(
      this.options.buildDir,
      resolvePath('fonts/framework7-icons.css')
    )
  }

  if (options.mdIcons) {
    options.mdIconsSrc = relative(
      this.options.buildDir,
      resolvePath('fonts/material-icons.css')
    )
  }

  // Enable nativeUI for a better Native experience
  if (!this.options.meta) {
    this.options.meta = {}
  }
  if (this.options.meta.nativeUI === undefined) {
    this.options.meta.nativeUI = true
  }

  // Require PWA module
  if (options.pwa !== false) {
    return this.requireModule('@nuxtjs/pwa')
  }

  return Promise.resolve()
}

function extendConfig (config, options) {
  // Increase performance check limits to 2M (non-gzipped)
  const MAX_SIZE = 2 * 1024 * 1024
  Object.assign(config.performance, {
    maxEntrypointSize: MAX_SIZE,
    maxAssetSize: MAX_SIZE
  })

  // Transpile framework7 (es builds are not being transpiled)
  const babel = config.module.rules.find(r => r.test + '' === '/\\.jsx?$/')
  babel.exclude = /node_modules(?![\\/](framework7|framework7-vue)[\\/])/
}

function addTemplates (options) {
  // Framework7 plugin
  this.addPlugin({
    src: resolvePath('templates/framework7/f7.plugin.js'),
    fileName: 'framework7/f7.plugin.js',
    options
  })

  // Copy all templates
  for (const template of templates) {
    this.addTemplate({
      src: resolvePath('templates/' + template),
      fileName: template,
      options
    })
  }
}

function tryResolve (path) {
  try {
    return require.resolve(path)
  } catch (err) {
    return null
  }
}

function normalizeComponents (components) {
  return components.map((name) => ({
    name,
    camelName: startCase(name).replace(/ /g, ''),
    js: tryResolve(`framework7/dist/components/${name}/${name}.js`),
    less: tryResolve(`framework7/dist/components/${name}/${name}.less`)
  }))
}

const templates = [
  // Framework 7
  'framework7/f7.router.js',
  'framework7/f7.styles.less',
  'framework7/f7.components.js',
  // Nuxt
  'App.js',
  'components/nuxt.js',
  'layouts/default.vue',
  'router.js'
]

const extraKeys = [
  'build',
  'mode',
  'themeColor',
  'css',
  'f7Icons',
  'mdIcons',
  'f7IconsSrc',
  'mdIconsSrc',
  'pwa',
  'routes',
  'plugin'
]

const defaults = {
  build: Object.assign({}, f7BuildConfig),

  mode: 'hash',
  css: true,
  f7Icons: true,
  mdIcons: true,

  routes: {},

  view: {
    main: true,
    pushState: true,
    pushStateRoot: null
  }
}
<|endoftext|>


<commit_before>//////////////////////////////////////////
// Needle -- Node Simple HTTP Client
// Written by Tomás Pollak <tomas@forkhq.com>
// (c) 2011 - Fork Ltd.
// MIT Licensed
//////////////////////////////////////////

var util = require('util'),
		fs = require('fs'),
		path = require('path'),
		http = require('http'),
		https = require('https'),
		url = require('url'),
		stringify = require('qs').stringify,
		version = require('./../package').version;

var parsers = {
	'application/json': function(data, callback){
		callback(data && JSON.parse(data));
	}
};

try {
	var xml2js = require('xml2js');

	parsers['application/xml'] = function(data, callback){

		var xml_parser = new xml2js.Parser();

		xml_parser.on('end', callback);
		xml_parser.on('error', function(result) {
			// throw("Error parsing XML!")
			callback(null);
		});

		xml_parser.parseString(data);

	};

} catch(e) { }

// utility function for flattening params in multipart POST's

function flatten(object, into, prefix){

	into = into || {};

	for(key in object){
		var prefix_key = prefix ? prefix + "[" + key + "]" : key;
		var prop = object[key];

		if(prop && typeof prop === "object" && !(prop.file && prop.content_type))
			flatten(prop, into, prefix_key)
		else
			into[prefix_key] = prop;

	}

	return into;

}

var Needle = {

	default_boundary: 'NODENEEDLEHTTPCLIENT',

	request: function(uri, method, data, options, callback){

		// normalize arguments
		var callback = (typeof options == 'function') ? options : callback;
		var options = options || {};
		if(uri.indexOf('http') == -1) uri = 'http://' + uri;

		var remote = url.parse(uri);
		var is_https = remote.protocol === "https:";
		var port = remote.port || (is_https ? 443 : 80);
		var protocol = is_https ? https : http;

		var parse_response = options.parse == false ? false : true;
		var timeout = options.timeout || 10000; // 10 seconds timeout
		var timer = null;

		var headers = {
			"Host" : remote.hostname,
			"User-Agent": "Needle/" + version + " (NodeJS " + process.version + ")",
			"Connection": "close",
			"Accept": "*/*"
		}

		if(data) {
			if(options.multipart){
				var boundary = options.boundary || this.default_boundary;
				var post_data = this.build_multipart_body(data, boundary);
				headers['Content-Type'] = 'multipart/form-data; boundary=' + boundary;
			} else {
				var post_data = (typeof(data) === "string") ? data : stringify(data);
				headers['Content-Type'] = 'application/x-www-form-urlencoded'
			}
			if(process.env.DEBUG) console.log(post_data);
		}

		if(post_data)
			headers['Content-Length'] = Buffer.byteLength(post_data);

		for(h in options.headers)
			if(headers.hasOwnProperty(h)) headers[h] = options.headers[h];

		if(options.username && options.password){
			var b = new Buffer([options.username, options.password].join(':'));
			headers['Authorization'] = "Basic " + b.toString('base64');
		}

		var request_opts = {
			host: remote.hostname,
			port: port,
			path: remote.path || remote.pathname,
			method: method,
			headers: headers
		}

		if(process.env.DEBUG) console.log(request_opts);

		var request = protocol.request(request_opts, function(response){

			var body = '';
			response.setEncoding('utf8');

			if(timer) clearTimeout(timer);

			response.on('data', function(chunk){
				body += chunk;
			});

			response.on('end', function() {
				if(parse_response && parsers[response.headers['content-type']]) {
					parsers[response.headers['content-type']](body, function(result){
						if(callback) callback(null, response, result);
					});
				} else {
					if(callback) callback(null, response, body);
				}
			});

		});

		if(timeout) {
			timer = setTimeout(function() {
				request.abort();
			}, timeout)
		}

		request.on('error', function(err) {
			if(process.env.DEBUG) console.log('Error on request: ' + err);
			if(timer) clearTimeout(timer);
			if(callback) callback(err || true);
		});

		if(post_data) request.write(post_data, options.encoding || 'utf8');
		request.end();

		return request;

	},

	build_multipart_body: function(data, boundary){

		var body = '';
		var object = flatten(data);

		for(var key in object){

			var value = object[key];
			var part = value.file && value.content_type ? value : {value: value};
			body += this.generate_part(key, part, boundary);

		}

		return body + '\r\n' + '--' + boundary + '--';

	},

	generate_part: function(name, part, boundary){

		var return_part = '--' + boundary + "\r\n";
		return_part += "Content-Disposition: form-data; name=\"" + name + "\"";

		if(part.file && part.content_type){

			var filename = path.basename(part.file);
			return_part += "; filename=\"" + filename + "\"\r\n";
			return_part += "Content-Type: " + part.content_type + "\r\n\r\n";

			var data = fs.readFileSync(filename);
			return_part += (part.content_type.indexOf('text') == -1)
				? data.toString('base64')
				: data.toString('utf8');

		} else {

			return_part += "\r\n\r\n";
			return_part += part.value;

		}

		return return_part + '\r\n';

	}

}

exports.get = function(uri, options, callback){
	return Needle.request(uri, "GET", null, options, callback);
}

exports.post = function(uri, data, options, callback){
	return Needle.request(uri, "POST", data, options, callback);
}

exports.put = function(uri, data, options, callback){
	return Needle.request(uri, "PUT", data, options, callback);
}

exports.delete = function(uri, data, options, callback){
	return Needle.request(uri, "DELETE", null, options, callback);
}
<commit_msg>Parse Content-Type header correctly for parsing (e.g. when charset=utf-8 is received)<commit_after>//////////////////////////////////////////
// Needle -- Node Simple HTTP Client
// Written by Tomás Pollak <tomas@forkhq.com>
// (c) 2011 - Fork Ltd.
// MIT Licensed
//////////////////////////////////////////

var util = require('util'),
		fs = require('fs'),
		path = require('path'),
		http = require('http'),
		https = require('https'),
		url = require('url'),
		stringify = require('qs').stringify,
		version = require('./../package').version;

var parsers = {
	'application/json': function(data, callback){
		callback(data && JSON.parse(data));
	}
};

try {
	var xml2js = require('xml2js');

	parsers['application/xml'] = function(data, callback){

		var xml_parser = new xml2js.Parser();

		xml_parser.on('end', callback);
		xml_parser.on('error', function(result) {
			// throw("Error parsing XML!")
			callback(null);
		});

		xml_parser.parseString(data);

	};

} catch(e) { }

// utility function for flattening params in multipart POST's

function flatten(object, into, prefix){

	into = into || {};

	for(key in object){
		var prefix_key = prefix ? prefix + "[" + key + "]" : key;
		var prop = object[key];

		if(prop && typeof prop === "object" && !(prop.file && prop.content_type))
			flatten(prop, into, prefix_key)
		else
			into[prefix_key] = prop;

	}

	return into;

}

var Needle = {

	default_boundary: 'NODENEEDLEHTTPCLIENT',

	request: function(uri, method, data, options, callback){

		// normalize arguments
		var callback = (typeof options == 'function') ? options : callback;
		var options = options || {};
		if(uri.indexOf('http') == -1) uri = 'http://' + uri;

		var remote = url.parse(uri);
		var is_https = remote.protocol === "https:";
		var port = remote.port || (is_https ? 443 : 80);
		var protocol = is_https ? https : http;

		var parse_response = options.parse == false ? false : true;
		var timeout = options.timeout || 10000; // 10 seconds timeout
		var timer = null;

		var headers = {
			"Host" : remote.hostname,
			"User-Agent": "Needle/" + version + " (NodeJS " + process.version + ")",
			"Connection": "close",
			"Accept": "*/*"
		}

		if(data) {
			if(options.multipart){
				var boundary = options.boundary || this.default_boundary;
				var post_data = this.build_multipart_body(data, boundary);
				headers['Content-Type'] = 'multipart/form-data; boundary=' + boundary;
			} else {
				var post_data = (typeof(data) === "string") ? data : stringify(data);
				headers['Content-Type'] = 'application/x-www-form-urlencoded'
			}
			if(process.env.DEBUG) console.log(post_data);
		}

		if(post_data)
			headers['Content-Length'] = Buffer.byteLength(post_data);

		for(h in options.headers)
			if(headers.hasOwnProperty(h)) headers[h] = options.headers[h];

		if(options.username && options.password){
			var b = new Buffer([options.username, options.password].join(':'));
			headers['Authorization'] = "Basic " + b.toString('base64');
		}

		var request_opts = {
			host: remote.hostname,
			port: port,
			path: remote.path || remote.pathname,
			method: method,
			headers: headers
		}

		if(process.env.DEBUG) console.log(request_opts);

		var request = protocol.request(request_opts, function(response){

			var body = '';
			response.setEncoding('utf8');

			if(timer) clearTimeout(timer);

			response.on('data', function(chunk){
				body += chunk;
			});

			response.on('end', function() {
				var content_type = response.headers['content-type'].split(';')[0];
				if(parse_response && parsers[content_type]) {
					parsers[content_type](body, function(result){
						if(callback) callback(null, response, result);
					});
				} else {
					if(callback) callback(null, response, body);
				}
			});

		});

		if(timeout) {
			timer = setTimeout(function() {
				request.abort();
			}, timeout)
		}

		request.on('error', function(err) {
			if(process.env.DEBUG) console.log('Error on request: ' + err);
			if(timer) clearTimeout(timer);
			if(callback) callback(err || true);
		});

		if(post_data) request.write(post_data, options.encoding || 'utf8');
		request.end();

		return request;

	},

	build_multipart_body: function(data, boundary){

		var body = '';
		var object = flatten(data);

		for(var key in object){

			var value = object[key];
			var part = value.file && value.content_type ? value : {value: value};
			body += this.generate_part(key, part, boundary);

		}

		return body + '\r\n' + '--' + boundary + '--';

	},

	generate_part: function(name, part, boundary){

		var return_part = '--' + boundary + "\r\n";
		return_part += "Content-Disposition: form-data; name=\"" + name + "\"";

		if(part.file && part.content_type){

			var filename = path.basename(part.file);
			return_part += "; filename=\"" + filename + "\"\r\n";
			return_part += "Content-Type: " + part.content_type + "\r\n\r\n";

			var data = fs.readFileSync(filename);
			return_part += (part.content_type.indexOf('text') == -1)
				? data.toString('base64')
				: data.toString('utf8');

		} else {

			return_part += "\r\n\r\n";
			return_part += part.value;

		}

		return return_part + '\r\n';

	}

}

exports.get = function(uri, options, callback){
	return Needle.request(uri, "GET", null, options, callback);
}

exports.post = function(uri, data, options, callback){
	return Needle.request(uri, "POST", data, options, callback);
}

exports.put = function(uri, data, options, callback){
	return Needle.request(uri, "PUT", data, options, callback);
}

exports.delete = function(uri, data, options, callback){
	return Needle.request(uri, "DELETE", null, options, callback);
}
<|endoftext|>


<commit_before>module.exports = function Nerver(nira) {
    var NERVER = {};
    NERVER.fs = require('fs');
    NERVER.nira = nira;
    NERVER.NendOfFile = "\n@NOF@!!_!!*@@";
    NERVER.cmdDir = __dirname+"/cmds";
    NERVER.responseDir = __dirname+"/cmdresponse";
    NERVER.period = 200;
    NERVER.timeoutCount = (8 * 60 * 60000) / NERVER.period;

    NERVER.init = function(nit) {
        NERVER.nit = nit;
        NERVER.CMDS = [
            { name : "DESCRIBE", action : NERVER.nira.getDescription },
            { name : "COMMENTS", action : NERVER.nira.getComments },
            { name : "CREATE_COMMENT", action : NERVER.nira.createComment },
            { name : "STATUS", action : nit.statusPrint, isNerverAction: true },
        ];
    };

    NERVER.prompt = function(cb) {
        var prompt = require('prompt');

        var properties = [
        {
            name: 'username'
        },
        {
            name: 'password',
            hidden: true
        }
        ];

        prompt.start();

        prompt.get(properties, function (err, result) {
            if (err) { return onErr(err); }
            NERVER.nira.login(result.username, result.password, function(isLoggedIn){
                cb && cb(isLoggedIn);
            });
        });

        function onErr(err) {
            console.log(err);
            return 1;
        }
    };

    NERVER.start = function(arg) {
        if(arg === "x" || arg === "-x"){
            //Skip login
            NERVER.listen(false);
        } else {
            NERVER.prompt(function(isLoggedIn) {
                NERVER.listen(isLoggedIn);
            });
        }
    };

    NERVER.listen = function(isLoggedIn){
        NERVER.isLoggedIn = isLoggedIn;
        NERVER.printStart();
        NERVER.counter = 0;
        NERVER.mkdir(NERVER.cmdDir);
        NERVER.mkdir(NERVER.responseDir)
        var files = NERVER.fs.readdirSync(NERVER.cmdDir);

        for(var i=0; i<files.length; i++) {
            var f = files[i];
            NERVER.deleteFile(f);
        }
        NERVER.runInterval = setInterval(function() {
            files = NERVER.fs.readdirSync(NERVER.cmdDir);

            if(NERVER.counter > NERVER.timeoutCount){
                clearInterval(NERVER.runInterval);
                console.log("Nerver session ended.");
                process.exit();
                return;
            }
            NERVER.counter++;
            NERVER.mkdir(NERVER.cmdDir);
            NERVER.mkdir(NERVER.responseDir)
            var files = NERVER.fs.readdirSync(NERVER.cmdDir);
            for(var i=0; i<files.length; i++) {
                var f = files[i];
                NERVER.run(f);
                NERVER.deleteFile(f);
            }
            //process.stdout.write(".");
            //if(NERVER.counter%30===0){
             //   process.stdout.clearLine();
             //   process.stdout.cursorTo(0);
            //}
        }, NERVER.period);
    };

    NERVER.printStart = function(){
        if(!NERVER.isLoggedIn){
            console.log("Not Logged in");
        }else {
            console.log("Logged in.");
        }
        console.log("Nerver is listening...\n----------------------------------------------\n\n\n");
    };

    NERVER.deleteFile = function(file) {
        NERVER.fs.unlinkSync(NERVER.cmdDir + "/" + file);
    };

    NERVER.run = function(f) {
        var split = f.split(".");
        if(!f || split.length !== 4){
            return;
        }
        var cmdName = split[0];

        var issueID = split[1];
        var option = split[2];
        var guid = split[3];
        var responseFile = NERVER.responseDir + "/" + guid;
        try {
            for(var i=0; i<NERVER.CMDS.length; i++) {
                if(cmdName === NERVER.CMDS[i].name){
                    var command = NERVER.CMDS[i];
                    if(command.isNerverAction){

                        NERVER.fs.writeFile(responseFile, "{}"+NERVER.NendOfFile);
                        if(command.name === "STATUS") {
                            setTimeout(function() { console.log('\033[2J');command.action(); }, 500);
                            setTimeout(function() { console.log('\033[2J');command.action(); }, 1500);
                            setTimeout(function() { console.log('\033[2J');command.action(); }, 3500);
                        } else {
                            command.action();
                        }
                    } else {
                        command.action(issueID, option, function(data){
                            data = data || "";
                            NERVER.fs.writeFile(responseFile, JSON.stringify(data)+NERVER.NendOfFile);
                        });
                    }
                }
            }
        } catch (e) {
             NERVER.fs.writeFile(responseFile, e.toString() + NERVER.NendOfFile)
        }
    };

    NERVER.mkdir = function(dir){
        try { NERVER.fs.mkdirSync(dir); }catch(e){}
    };
    return NERVER;
}<commit_msg>show l1 for nerver status<commit_after>module.exports = function Nerver(nira) {
    var NERVER = {};
    NERVER.fs = require('fs');
    NERVER.nira = nira;
    NERVER.NendOfFile = "\n@NOF@!!_!!*@@";
    NERVER.cmdDir = __dirname+"/cmds";
    NERVER.responseDir = __dirname+"/cmdresponse";
    NERVER.period = 200;
    NERVER.timeoutCount = (8 * 60 * 60000) / NERVER.period;

    NERVER.init = function(nit) {
        NERVER.nit = nit;
        NERVER.CMDS = [
            { name : "DESCRIBE", action : NERVER.nira.getDescription },
            { name : "COMMENTS", action : NERVER.nira.getComments },
            { name : "CREATE_COMMENT", action : NERVER.nira.createComment },
            { name : "STATUS", action : function(){nit.statusPrint(); nit.logOneLiners();}, isNerverAction: true },
        ];
    };

    NERVER.prompt = function(cb) {
        var prompt = require('prompt');

        var properties = [
        {
            name: 'username'
        },
        {
            name: 'password',
            hidden: true
        }
        ];

        prompt.start();

        prompt.get(properties, function (err, result) {
            if (err) { return onErr(err); }
            NERVER.nira.login(result.username, result.password, function(isLoggedIn){
                cb && cb(isLoggedIn);
            });
        });

        function onErr(err) {
            console.log(err);
            return 1;
        }
    };

    NERVER.start = function(arg) {
        if(arg === "x" || arg === "-x"){
            //Skip login
            NERVER.listen(false);
        } else {
            NERVER.prompt(function(isLoggedIn) {
                NERVER.listen(isLoggedIn);
            });
        }
    };

    NERVER.listen = function(isLoggedIn){
        NERVER.isLoggedIn = isLoggedIn;
        NERVER.printStart();
        NERVER.counter = 0;
        NERVER.mkdir(NERVER.cmdDir);
        NERVER.mkdir(NERVER.responseDir)
        var files = NERVER.fs.readdirSync(NERVER.cmdDir);

        for(var i=0; i<files.length; i++) {
            var f = files[i];
            NERVER.deleteFile(f);
        }
        NERVER.runInterval = setInterval(function() {
            files = NERVER.fs.readdirSync(NERVER.cmdDir);

            if(NERVER.counter > NERVER.timeoutCount){
                clearInterval(NERVER.runInterval);
                console.log("Nerver session ended.");
                process.exit();
                return;
            }
            NERVER.counter++;
            NERVER.mkdir(NERVER.cmdDir);
            NERVER.mkdir(NERVER.responseDir)
            var files = NERVER.fs.readdirSync(NERVER.cmdDir);
            for(var i=0; i<files.length; i++) {
                var f = files[i];
                NERVER.run(f);
                NERVER.deleteFile(f);
            }
            //process.stdout.write(".");
            //if(NERVER.counter%30===0){
             //   process.stdout.clearLine();
             //   process.stdout.cursorTo(0);
            //}
        }, NERVER.period);
    };

    NERVER.printStart = function(){
        if(!NERVER.isLoggedIn){
            console.log("Not Logged in");
        }else {
            console.log("Logged in.");
        }
        console.log("Nerver is listening...\n----------------------------------------------\n\n\n");
    };

    NERVER.deleteFile = function(file) {
        NERVER.fs.unlinkSync(NERVER.cmdDir + "/" + file);
    };

    NERVER.run = function(f) {
        var split = f.split(".");
        if(!f || split.length !== 4){
            return;
        }
        var cmdName = split[0];

        var issueID = split[1];
        var option = split[2];
        var guid = split[3];
        var responseFile = NERVER.responseDir + "/" + guid;
        try {
            for(var i=0; i<NERVER.CMDS.length; i++) {
                if(cmdName === NERVER.CMDS[i].name){
                    var command = NERVER.CMDS[i];
                    if(command.isNerverAction){

                        NERVER.fs.writeFile(responseFile, "{}"+NERVER.NendOfFile);
                        if(command.name === "STATUS") {
                            setTimeout(function() { console.log('\033[2J');command.action(); }, 500);
                            setTimeout(function() { console.log('\033[2J');command.action(); }, 1500);
                            setTimeout(function() { console.log('\033[2J');command.action(); }, 3500);
                        } else {
                            command.action();
                        }
                    } else {
                        command.action(issueID, option, function(data){
                            data = data || "";
                            NERVER.fs.writeFile(responseFile, JSON.stringify(data)+NERVER.NendOfFile);
                        });
                    }
                }
            }
        } catch (e) {
             NERVER.fs.writeFile(responseFile, e.toString() + NERVER.NendOfFile)
        }
    };

    NERVER.mkdir = function(dir){
        try { NERVER.fs.mkdirSync(dir); }catch(e){}
    };
    return NERVER;
}<|endoftext|>