<commit_before>'use strict'

const
  fs = require('fs'), stream = require('stream'), path = require('path'), util = require('util')
,
  debug = util.debuglog('logerr')
,
  timezoneOffset = (new Date()).getTimezoneOffset() * 60000
;

let logl, root

function toWritable (handle) {
  if (handle instanceof stream.Writable) {
    return handle
  } else {
    return fs.createWriteStream(path.resolve(root, handle), { flags: 'a' })
      .on('error', err => {
        throw err
      })
  }
}

class Log extends console.Console {
  constructor (out, err, options = {}) {
    debug(`logerr instance being constructed with out:::${out} and err:::${err}`)
    // options specific to this log
    if (typeof err !== 'string' && !( err instanceof stream.Writable )) {
      options = err
      err = undefined
    }
    if (!options.namespace || typeof options.namespace !== 'string') {
      throw new Error(`log for ${out} missing a valid <String> namespace for util.debuglog`)
    }
    // handle optional second parameter (separate file for stderr)
    super(toWritable(out, options), err ? toWritable(err, options) : undefined)

    this.debuglog = require('util').debuglog(options.namespace)
  }
  common (level, prefix, method, ...args) {
    if (process.env.NODE_DEBUG && process.env.NODE_DEBUG.toLowerCase() === 'true') {
      console.log(...args)
    } else {
      this.debuglog(...args)
    }
    debug(`is the global logLevel (${logl}) <= the level of this log type? (${method}:::${level})`)
    if (logl <= level) return
    args.unshift(prefix, new Date(Date.now() - timezoneOffset).toISOString())
    super[method](...args)
  }
  log (...args) {
    this.common(2, 'L', 'log', ...args)
  }
  info (...args) {
    this.common(3, 'I', 'info', ...args)
  }
  error (...args) {
    this.common(0, 'E', 'error', ...args)
  }
  warn (...args) {
    this.common(1, 'W', 'warn', ...args)
  }
  trace (...args) {
    this.common(0, 't', 'trace', ...args)
  }
}

Log.prototype.log.newline = () => { console.log(this) }

module.exports = ({ logLevel = 0, logsPath = process.cwd() }) => {
  logl = logLevel
  root = logsPath
  debug(`logerr run with logLevel ${logl} and with logsPath ${root}`)
  // change module.exports for future requires
  module.exports = Log
  // return Log for the first require
  return Log
}
<commit_msg>totally had the logic of log levels completely fudged<commit_after>'use strict'

const
  fs = require('fs'), stream = require('stream'), path = require('path'), util = require('util')
,
  debug = util.debuglog('logerr')
,
  timezoneOffset = (new Date()).getTimezoneOffset() * 60000
;

let logl, root

function toWritable (handle) {
  if (handle instanceof stream.Writable) {
    return handle
  } else {
    return fs.createWriteStream(path.resolve(root, handle), { flags: 'a' })
      .on('error', err => {
        throw err
      })
  }
}

class Log extends console.Console {
  constructor (out, err, options = {}) {
    debug(`logerr instance being constructed with out:::${out} and err:::${err}`)
    // options specific to this log
    if (typeof err !== 'string' && !( err instanceof stream.Writable )) {
      options = err
      err = undefined
    }
    if (!options.namespace || typeof options.namespace !== 'string') {
      throw new Error(`log for ${out} missing a valid <String> namespace for util.debuglog`)
    }
    // handle optional second parameter (separate file for stderr)
    super(toWritable(out, options), err ? toWritable(err, options) : undefined)

    this.debuglog = require('util').debuglog(options.namespace)
  }
  common (level, prefix, method, ...args) {
    if (process.env.NODE_DEBUG && process.env.NODE_DEBUG.toLowerCase() === 'true') {
      console.log(...args)
    } else {
      this.debuglog(...args)
    }
    debug(`is the global logLevel (${logl}) >= the level of this log type? (${method}:::${level})`)
    if (logl >= level) return
    args.unshift(prefix, new Date(Date.now() - timezoneOffset).toISOString())
    super[method](...args)
  }
  log (...args) {
    this.common(2, 'L', 'log', ...args)
  }
  info (...args) {
    this.common(3, 'I', 'info', ...args)
  }
  error (...args) {
    this.common(0, 'E', 'error', ...args)
  }
  warn (...args) {
    this.common(1, 'W', 'warn', ...args)
  }
  trace (...args) {
    this.common(0, 't', 'trace', ...args)
  }
}

Log.prototype.log.newline = () => { console.log(this) }

module.exports = ({ logLevel = 0, logsPath = process.cwd() }) => {
  logl = logLevel
  root = logsPath
  debug(`logerr run with logLevel ${logl} and with logsPath ${root}`)
  // change module.exports for future requires
  module.exports = Log
  // return Log for the first require
  return Log
}
<|endoftext|>


<commit_before>const {
  FuseBox,
  WebIndexPlugin,
  QuantumPlugin,
  EnvPlugin,
  CopyPlugin,
  JSONPlugin,
  StyledComponentsPlugin,
} = require('fuse-box');

const { spawn } = require('child_process');

const production = process.env.NODE_ENV === 'dev' ? false : true;

const getConfig = target => {
  return {
    homeDir: 'src/',
    cache: !production,
    target,
    output: `build/$name.js`,
    useTypescriptCompiler: true,
    plugins: [
      EnvPlugin({ NODE_ENV: production ? 'production' : 'development' }),
      production &&
        QuantumPlugin({
          bakeApiIntoBundle: true,
          treeshake: true,
          uglify: {
            es6: true,
          },
        }),
    ],
    alias: {
      '~': '~/',
    },
    log: {
      showBundledFiles: false,
    },
  };
};

const getRendererConfig = (target, name) => {
  const cfg = Object.assign({}, getConfig(target, name), {
    sourceMaps: !production,
  });

  return cfg;
};

const getCopyPlugin = () => {
  return CopyPlugin({
    files: ['*.woff2', '*.png', '*.svg'],
    dest: 'assets',
    resolve: production ? './assets' : '/assets',
  });
};

const main = () => {
  const fuse = FuseBox.init(getConfig('server', 'main'));

  const app = fuse.bundle('main').instructions(`> [main/index.ts]`);

  if (!production) {
    app.watch();
  }

  fuse.run();
};

const renderer = () => {
  const cfg = getRendererConfig('electron');

  cfg.plugins.push(
    WebIndexPlugin({
      template: `static/pages/app.html`,
      path: production ? '.' : '/',
      target: `app.html`,
      bundles: ['app'],
    }),
  );

  cfg.plugins.push(
    WebIndexPlugin({
      template: `static/pages/app.html`,
      path: production ? '.' : '/',
      target: `permissions.html`,
      bundles: ['permissions'],
    }),
  );

  cfg.plugins.push(JSONPlugin());
  cfg.plugins.push(getCopyPlugin());
  cfg.plugins.push(StyledComponentsPlugin());

  const fuse = FuseBox.init(cfg);

  const app = fuse.bundle('app').instructions(`> [renderer/app/index.tsx]`);

  const permissions = fuse
    .bundle('permissions')
    .instructions(`> [renderer/permissions/index.tsx]`);

  if (!production) {
    fuse.dev({ httpServer: true });

    app.hmr().watch();
    permissions.watch();

    fuse.run().then(() => {
      spawn('npm', ['start'], {
        shell: true,
        stdio: 'inherit',
      });
    });
  } else {
    fuse.run();
  }
};

const preload = name => {
  const cfg = getRendererConfig('electron', name);
  const fuse = FuseBox.init(cfg);
  const app = fuse.bundle(name).instructions(`> [preloads/${name}.ts]`);

  if (!production) {
    app.watch();
  }

  fuse.run();
};

renderer();
preload('view-preload');
main();
<commit_msg>chore: prepare fuse config for auth dialog<commit_after>const {
  FuseBox,
  WebIndexPlugin,
  QuantumPlugin,
  EnvPlugin,
  CopyPlugin,
  JSONPlugin,
  StyledComponentsPlugin,
} = require('fuse-box');

const { spawn } = require('child_process');

const production = process.env.NODE_ENV === 'dev' ? false : true;

const getConfig = target => {
  return {
    homeDir: 'src/',
    cache: !production,
    target,
    output: `build/$name.js`,
    useTypescriptCompiler: true,
    plugins: [
      EnvPlugin({ NODE_ENV: production ? 'production' : 'development' }),
      production &&
        QuantumPlugin({
          bakeApiIntoBundle: true,
          treeshake: true,
          uglify: {
            es6: true,
          },
        }),
    ],
    alias: {
      '~': '~/',
    },
    log: {
      showBundledFiles: false,
    },
  };
};

const getRendererConfig = (target, name) => {
  const cfg = Object.assign({}, getConfig(target, name), {
    sourceMaps: !production,
  });

  return cfg;
};

const getCopyPlugin = () => {
  return CopyPlugin({
    files: ['*.woff2', '*.png', '*.svg'],
    dest: 'assets',
    resolve: production ? './assets' : '/assets',
  });
};

const main = () => {
  const fuse = FuseBox.init(getConfig('server', 'main'));

  const app = fuse.bundle('main').instructions(`> [main/index.ts]`);

  if (!production) {
    app.watch();
  }

  fuse.run();
};

const getWebIndexPlugin = name => {
  return WebIndexPlugin({
    template: `static/pages/app.html`,
    path: production ? '.' : '/',
    target: `${name}.html`,
    bundles: [name],
  });
};

const renderer = () => {
  const cfg = getRendererConfig('electron');

  cfg.plugins.push(getWebIndexPlugin('app'));
  cfg.plugins.push(getWebIndexPlugin('permissions'));
  cfg.plugins.push(getWebIndexPlugin('auth'));

  cfg.plugins.push(JSONPlugin());
  cfg.plugins.push(getCopyPlugin());
  cfg.plugins.push(StyledComponentsPlugin());

  const fuse = FuseBox.init(cfg);

  const app = fuse.bundle('app').instructions(`> [renderer/app/index.tsx]`);

  const permissions = fuse
    .bundle('permissions')
    .instructions(`> [renderer/permissions/index.tsx]`);

  const auth = fuse.bundle('auth').instructions(`> [renderer/auth/index.tsx]`);

  if (!production) {
    fuse.dev({ httpServer: true });

    app.hmr().watch();
    permissions.watch();
    auth.watch();

    fuse.run().then(() => {
      spawn('npm', ['start'], {
        shell: true,
        stdio: 'inherit',
      });
    });
  } else {
    fuse.run();
  }
};

const preload = name => {
  const cfg = getRendererConfig('electron', name);
  const fuse = FuseBox.init(cfg);
  const app = fuse.bundle(name).instructions(`> [preloads/${name}.ts]`);

  if (!production) {
    app.watch();
  }

  fuse.run();
};

renderer();
preload('view-preload');
main();
<|endoftext|>


<commit_before>/*
@license https://github.com/t2ym/gulp-i18n-leverage/blob/master/LICENSE.md
Copyright (c) 2016, Tetsuya Mori <t2y3141592@gmail.com>. All rights reserved.
*/
'use strict';

var path = require('path');
var fs = require('fs');
var JSONstringify = require('json-stringify-safe');
var rfc6902 = require('rfc6902');
var deepcopy = require('deepcopy');
var gutil = require('gulp-util');
var through = require('through2');

/**
 * Gulp plugin to merge text changes in the default locale into a localized bundle.
 *
 * @namespace gulp-i18n-leverage
 */
module.exports = function(options) {
  return through.obj(function (file, enc, callback) {
    var jsonSpace = (options && options.jsonSpace !== undefined) ? options.jsonSpace : 2;
    var srcPath = (options && options.srcPath !== undefined) ? options.srcPath : 'app';
    var distPath = (options && options.distPath !== undefined) ? options.distPath : 'dist';
    var bundles = options && options.bundles ? options.bundles : {};

    if (file.isNull()) {
      return callback(null, file);
    }

    function deepMap(target, source, map) {
      var value;
      for (var prop in source) {
        value = source[prop];
        switch (typeof value) {
        case 'string':
        case 'number':
        case 'boolean':
          target[prop] = map(value, prop);
          break;
        case 'object':
          if (Array.isArray(value)) {
            // TODO: cannot handle deep objects properly
            target[prop] = target[prop] || [];
            deepMap(target[prop], value, map);
          }
          else {
            target[prop] = target[prop] || {};
            deepMap(target[prop], value, map);
          }
          break;
        case 'function':
        case 'symbol':
        case 'undefined':
          target[prop] = value;
          break;
        default:
          target[prop] = value;
          break;
        }
      }
    }

    function getNextFallbackLanguage(lang) {
      var nextFallbackLanguage = null;
      if (lang && lang.length > 0) {
        var parts = lang.split(/[-_]/);
        if (parts.length >= 2) {
          parts.pop();
          nextFallbackLanguage = parts.join('-');
        }
      }
      return nextFallbackLanguage;
    }

    function parsePath() {
      var r = {};
      r.path = file.path;
      r.base = file.base;
      r.srcBase = file.base.substr(0, file.base.length - 1);
      r.distBase = r.srcBase.substr(0, r.srcBase.length - srcPath.length) + distPath;
      r.urlPath = file.path.substr(r.srcBase.length);
      var splitPath = r.urlPath.split(path.sep + 'locales' + path.sep);
      r.componentBase = splitPath[0];
      r.resourcePath = r.componentBase + path.sep + 'locales';
      r.fileName = splitPath[1];
      r.extName = path.extname(r.fileName);
      var baseNameWithLang = r.fileName.substr(0, r.fileName.length - r.extName.length);
      var splitBaseName = baseNameWithLang.split('.');
      r.lang = splitBaseName.pop();
      r.baseName = r.fileName.substr(0, r.fileName.length - r.extName.length - r.lang.length - 1);
      r.defaultPath = r.componentBase + path.sep + r.baseName + r.extName;
      r.ancestorSrcPaths = [];
      var lang = getNextFallbackLanguage(r.lang);
      while (lang) {
        r.ancestorSrcPaths.push(r.srcBase + r.resourcePath + path.sep + r.baseName + '.' + lang + r.extName);
        lang = getNextFallbackLanguage(lang);
      }
      r.srcDefaultPath = r.srcBase + r.defaultPath;
      r.distDefaultPath = r.distBase + r.defaultPath;
      return r;
    }

    function findPatch(patch, op, path) {
      for (var i in patch) {
        var item = patch[i];
        if (item.op === op && item.path === path) {
          return item;
        }
      }
      return null;
    }

    function findValue(obj, path) {
      var splitPath = path.split('/');
      var value = obj;
      for (var i = 1; i < splitPath.length; i++) {
        value = value[splitPath[i]];
      }
      return value;
    }

    function fragmentObject(obj, path) {
      var fragments = [];
      var op;
      var i;
      switch (typeof obj) {
      case 'object':
        if (Array.isArray(obj)) {
          for (i = 0; i < obj.length; i++) {
            fragments = fragments.concat(fragmentObject(obj[i], path + '/' + i));
          }
        }
        else {
          for (i in obj) {
            fragments = fragments.concat(fragmentObject(obj[i], path + '/' + i));
          }
        }
        break;
      case 'string':
      case 'number':
      case 'boolean':
      case 'function':
      case 'symbol':
      case 'undefined':
      default:
        op = {};
        op[path] = obj;
        fragments = [ op ];
        break;
      }
      return fragments;
    }

    function fragmentOperation(rawOp) {
      var operations = [];
      switch (rawOp.op) {
      case 'add':
      case 'remove':
      case 'replace':
        if (typeof rawOp.value === 'object') {
          fragmentObject(rawOp.value, rawOp.path).forEach(function (op) {
            for (var p in op) {
              operations.push({ op: rawOp.op, path: p, value: op[p] });
            }
          });
        }
        else {
          operations.push(rawOp);
        }
        break;
      case 'move':
      case 'copy':
        if (typeof rawOp.value === 'object') {
          fragmentObject(rawOp.value, '').forEach(function (op) {
            for (var p in op) {
              operations.push({ op: rawOp.op, from: rawOp.from + p, path: rawOp.path + p });
            }
          });
        }
        else {
          operations.push(rawOp);
        }
        break;
      case 'test':
      default:
        operations.push(rawOp);
        break;
      }
      return operations;
    }

    function fragmentPatch(patch) {
      var fragmented = [];
      for (var i = 0; i < patch.length; i++) {
        fragmented = fragmented.concat(fragmentOperation(patch[i]));
      }
      return fragmented;
    }

    function minimizePatch(patch, prev, current) {
      var minimized = [];
      var valueOpMap = {};
      var serialized;
      var i;
      var item, item2;
      var removed;

      // construct valueOpMap
      for (i in patch) {
        item = patch[i];
        if (item.op === 'remove') {
          item.value = findValue(prev, item.path);
        }
        serialized = JSONstringify(item.value);
        valueOpMap[serialized] = valueOpMap[serialized] || [];
        valueOpMap[serialized].push(i);
      }

      // convert remove/add pairs to move operations
      for (i in valueOpMap) {
        if (valueOpMap[i].length === 2) {
          item = patch[valueOpMap[i][0]];
          if (item.op === 'add') {
            item2 = item;
            item = patch[valueOpMap[i][1]];
          }
          else {
            item2 = patch[valueOpMap[i][1]];
          }
          if (item.op === 'remove' && item2.op === 'add') {
            // convert them to move operation
            item.op = 'move';
            item.from = item.path;
            item.path = item2.path;
            delete item.value;
            item2.op = 'noop';
          }
        }
      }

      // construct minimized patch
      for (i in patch) {
        item = patch[i];
        switch (item.op) {
        case 'add':
        case 'remove':
        case 'replace':
        case 'move':
        case 'copy':
          minimized.push(item);
          break;
        case 'test':
        default:
          break;
        }
      }
      return minimized;
    }

    function updateMetaTodo(current, prev)
    {
      var meta = prev.meta || {};
      var prevClone = deepcopy(prev);
      var currentClone = deepcopy(current);
      var patch;
      var i, j;
      delete prevClone.meta;
      delete currentClone.meta;
      current.meta.todo = [];
      patch = rfc6902.createPatch(prevClone, currentClone);
      patch = minimizePatch(patch, prevClone, currentClone);
      //console.log('fragmenting ======================================================================');
      //console.log(JSONstringify(patch, null, 2));
      patch = fragmentPatch(patch);
      //console.log(JSONstringify(patch, null, 2));
      meta.todo = meta.todo || [];
      for (i = 0; i < patch.length; i++) {
        switch (patch[i].op) {
        case 'add':
        case 'replace':
          for (j = 0; j < meta.todo.length; j++) {
            if (meta.todo[j].path === patch[i].path) {
              meta.todo[j].op = 'noop';
              break;
            }
          }
          meta.todo.push(patch[i]);
          break;
        case 'remove':
          for (j = 0; j < meta.todo.length; j++) {
            if (meta.todo[j].path === patch[i].path) {
              meta.todo[j].op = 'noop';
            }
            else if (meta.todo[j].path.indexOf(patch[i].path + '/') === 0) {
              meta.todo[j].op = 'noop';
            }
          }
          break;
        case 'move':
          for (j = 0; j < meta.todo.length; j++) {
            if (meta.todo[j].path === patch[i].from) {
              meta.todo[j].path = patch[i].path;
            }
            else if (meta.todo[j].path.indexOf(patch[i].from + '/') === 0) {
              meta.todo[j].path = patch[i].path + meta.todo[j].path.substr(patch[i].from.length);
            }
          }
          break;
        case 'copy': // TODO: should not happen for now
        case 'test':
        default:
          break;
        }
      }
      for (i = meta.todo.length - 1; i >= 0; i--) {
        if (meta.todo[i].op === 'noop') {
          meta.todo.splice(i, 1);
        }
      }
      current.meta = meta;
      return current;
    }

    function update(paths, contents) {
      var prevDefault;
      var currentDefault;
      var prevLocalized;
      var prevLocalizedOriginal;
      var currentLocalized;
      var prevAncestors = [];
      var patchStatus;
      var i;
      try {
        prevDefault = JSON.parse(fs.readFileSync(paths.srcDefaultPath, 'utf8'));
      }
      catch (e) {
        prevDefault = {}; // presumably file not found
      }
      try {
        currentDefault = JSON.parse(fs.readFileSync(paths.distDefaultPath, 'utf8'));
      }
      catch (e) {
        currentDefault = {}; // presumably file not found
      }
      for (i = 0; i < paths.ancestorSrcPaths.length; i++) {
        try {
          prevAncestors[i] = JSON.parse(fs.readFileSync(paths.ancestorSrcPaths[i], 'utf8'));
        }
        catch (e) {
          prevAncestors[i] = null; // presumably file not found
        }
      }

      try {
        prevLocalized = JSON.parse(contents);
      }
      catch (e) {
        prevLocalized = {};
      }
      prevLocalizedOriginal = deepcopy(prevLocalized);

      var patch = rfc6902.createPatch(prevDefault, currentDefault);
      patch = minimizePatch(patch, prevDefault, currentDefault);

      for (i = 0; i < prevAncestors.length; i++) {
        if (prevAncestors[i]) {
          rfc6902.applyPatch(prevAncestors[i], patch);
        }
      }

      patchStatus = rfc6902.applyPatch(prevLocalized, patch);
      for (i = 0; i < patchStatus.length; i++) {
        if (patchStatus[i]) {
          console.log('warning: ' + patchStatus[i].name +
                                  ' for ' + JSONstringify(patch[i]));
        }
      }

      currentLocalized = deepcopy(currentDefault);

      for (i = 0; i < prevAncestors.length; i++) {
        if (prevAncestors[i]) {
          deepMap(currentLocalized, prevAncestors[i], function (value) { return value; });
        }
      }

      deepMap(currentLocalized, prevLocalized, function (value) { return value; });

      updateMetaTodo(currentLocalized, prevLocalizedOriginal);

      //console.log(JSONstringify(patch, null, 2));
      bundles[paths.lang] = bundles[paths.lang] || {};
      bundles[paths.lang][paths.baseName] = deepcopy(currentLocalized);
      bundles[''] = bundles[''] || {};
      bundles[''][paths.baseName] = deepcopy(currentDefault);
      return JSONstringify(currentLocalized, null, jsonSpace);
    }

    function doLeverage() {
      if (file.isNull()) {
        callback(null, file);
        return;
      }

      if (file.isStream()) {
        callback(new gutil.PluginError('leverage', 'Streaming not supported'));
        return;
      }

      if (file.isBuffer()) {
        var contents = String(file.contents);
        var paths = parsePath();
        //console.log(paths);
        var result = update(paths, contents);
        if (result) {
          file.contents = new Buffer(result);
          return callback(null, file);
        }
      }

      callback(null, file);
    }

    doLeverage();
  });
};
<commit_msg>Fix #2. Internally append path.sep to file.base if it is missing<commit_after>/*
@license https://github.com/t2ym/gulp-i18n-leverage/blob/master/LICENSE.md
Copyright (c) 2016, Tetsuya Mori <t2y3141592@gmail.com>. All rights reserved.
*/
'use strict';

var path = require('path');
var fs = require('fs');
var JSONstringify = require('json-stringify-safe');
var rfc6902 = require('rfc6902');
var deepcopy = require('deepcopy');
var gutil = require('gulp-util');
var through = require('through2');

/**
 * Gulp plugin to merge text changes in the default locale into a localized bundle.
 *
 * @namespace gulp-i18n-leverage
 */
module.exports = function(options) {
  return through.obj(function (file, enc, callback) {
    var jsonSpace = (options && options.jsonSpace !== undefined) ? options.jsonSpace : 2;
    var srcPath = (options && options.srcPath !== undefined) ? options.srcPath : 'app';
    var distPath = (options && options.distPath !== undefined) ? options.distPath : 'dist';
    var bundles = options && options.bundles ? options.bundles : {};

    if (file.isNull()) {
      return callback(null, file);
    }

    function deepMap(target, source, map) {
      var value;
      for (var prop in source) {
        value = source[prop];
        switch (typeof value) {
        case 'string':
        case 'number':
        case 'boolean':
          target[prop] = map(value, prop);
          break;
        case 'object':
          if (Array.isArray(value)) {
            // TODO: cannot handle deep objects properly
            target[prop] = target[prop] || [];
            deepMap(target[prop], value, map);
          }
          else {
            target[prop] = target[prop] || {};
            deepMap(target[prop], value, map);
          }
          break;
        case 'function':
        case 'symbol':
        case 'undefined':
          target[prop] = value;
          break;
        default:
          target[prop] = value;
          break;
        }
      }
    }

    function getNextFallbackLanguage(lang) {
      var nextFallbackLanguage = null;
      if (lang && lang.length > 0) {
        var parts = lang.split(/[-_]/);
        if (parts.length >= 2) {
          parts.pop();
          nextFallbackLanguage = parts.join('-');
        }
      }
      return nextFallbackLanguage;
    }

    function parsePath() {
      var r = {};
      r.path = file.path;
      r.base = file.base[file.base.length - 1] === path.sep ? file.base : file.base + path.sep;
      r.srcBase = file.base.substr(0, r.base.length - 1);
      r.distBase = r.srcBase.substr(0, r.srcBase.length - srcPath.length) + distPath;
      r.urlPath = file.path.substr(r.srcBase.length);
      var splitPath = r.urlPath.split(path.sep + 'locales' + path.sep);
      r.componentBase = splitPath[0];
      r.resourcePath = r.componentBase + path.sep + 'locales';
      r.fileName = splitPath[1];
      r.extName = path.extname(r.fileName);
      var baseNameWithLang = r.fileName.substr(0, r.fileName.length - r.extName.length);
      var splitBaseName = baseNameWithLang.split('.');
      r.lang = splitBaseName.pop();
      r.baseName = r.fileName.substr(0, r.fileName.length - r.extName.length - r.lang.length - 1);
      r.defaultPath = r.componentBase + path.sep + r.baseName + r.extName;
      r.ancestorSrcPaths = [];
      var lang = getNextFallbackLanguage(r.lang);
      while (lang) {
        r.ancestorSrcPaths.push(r.srcBase + r.resourcePath + path.sep + r.baseName + '.' + lang + r.extName);
        lang = getNextFallbackLanguage(lang);
      }
      r.srcDefaultPath = r.srcBase + r.defaultPath;
      r.distDefaultPath = r.distBase + r.defaultPath;
      return r;
    }

    function findPatch(patch, op, path) {
      for (var i in patch) {
        var item = patch[i];
        if (item.op === op && item.path === path) {
          return item;
        }
      }
      return null;
    }

    function findValue(obj, path) {
      var splitPath = path.split('/');
      var value = obj;
      for (var i = 1; i < splitPath.length; i++) {
        value = value[splitPath[i]];
      }
      return value;
    }

    function fragmentObject(obj, path) {
      var fragments = [];
      var op;
      var i;
      switch (typeof obj) {
      case 'object':
        if (Array.isArray(obj)) {
          for (i = 0; i < obj.length; i++) {
            fragments = fragments.concat(fragmentObject(obj[i], path + '/' + i));
          }
        }
        else {
          for (i in obj) {
            fragments = fragments.concat(fragmentObject(obj[i], path + '/' + i));
          }
        }
        break;
      case 'string':
      case 'number':
      case 'boolean':
      case 'function':
      case 'symbol':
      case 'undefined':
      default:
        op = {};
        op[path] = obj;
        fragments = [ op ];
        break;
      }
      return fragments;
    }

    function fragmentOperation(rawOp) {
      var operations = [];
      switch (rawOp.op) {
      case 'add':
      case 'remove':
      case 'replace':
        if (typeof rawOp.value === 'object') {
          fragmentObject(rawOp.value, rawOp.path).forEach(function (op) {
            for (var p in op) {
              operations.push({ op: rawOp.op, path: p, value: op[p] });
            }
          });
        }
        else {
          operations.push(rawOp);
        }
        break;
      case 'move':
      case 'copy':
        if (typeof rawOp.value === 'object') {
          fragmentObject(rawOp.value, '').forEach(function (op) {
            for (var p in op) {
              operations.push({ op: rawOp.op, from: rawOp.from + p, path: rawOp.path + p });
            }
          });
        }
        else {
          operations.push(rawOp);
        }
        break;
      case 'test':
      default:
        operations.push(rawOp);
        break;
      }
      return operations;
    }

    function fragmentPatch(patch) {
      var fragmented = [];
      for (var i = 0; i < patch.length; i++) {
        fragmented = fragmented.concat(fragmentOperation(patch[i]));
      }
      return fragmented;
    }

    function minimizePatch(patch, prev, current) {
      var minimized = [];
      var valueOpMap = {};
      var serialized;
      var i;
      var item, item2;
      var removed;

      // construct valueOpMap
      for (i in patch) {
        item = patch[i];
        if (item.op === 'remove') {
          item.value = findValue(prev, item.path);
        }
        serialized = JSONstringify(item.value);
        valueOpMap[serialized] = valueOpMap[serialized] || [];
        valueOpMap[serialized].push(i);
      }

      // convert remove/add pairs to move operations
      for (i in valueOpMap) {
        if (valueOpMap[i].length === 2) {
          item = patch[valueOpMap[i][0]];
          if (item.op === 'add') {
            item2 = item;
            item = patch[valueOpMap[i][1]];
          }
          else {
            item2 = patch[valueOpMap[i][1]];
          }
          if (item.op === 'remove' && item2.op === 'add') {
            // convert them to move operation
            item.op = 'move';
            item.from = item.path;
            item.path = item2.path;
            delete item.value;
            item2.op = 'noop';
          }
        }
      }

      // construct minimized patch
      for (i in patch) {
        item = patch[i];
        switch (item.op) {
        case 'add':
        case 'remove':
        case 'replace':
        case 'move':
        case 'copy':
          minimized.push(item);
          break;
        case 'test':
        default:
          break;
        }
      }
      return minimized;
    }

    function updateMetaTodo(current, prev)
    {
      var meta = prev.meta || {};
      var prevClone = deepcopy(prev);
      var currentClone = deepcopy(current);
      var patch;
      var i, j;
      delete prevClone.meta;
      delete currentClone.meta;
      current.meta.todo = [];
      patch = rfc6902.createPatch(prevClone, currentClone);
      patch = minimizePatch(patch, prevClone, currentClone);
      //console.log('fragmenting ======================================================================');
      //console.log(JSONstringify(patch, null, 2));
      patch = fragmentPatch(patch);
      //console.log(JSONstringify(patch, null, 2));
      meta.todo = meta.todo || [];
      for (i = 0; i < patch.length; i++) {
        switch (patch[i].op) {
        case 'add':
        case 'replace':
          for (j = 0; j < meta.todo.length; j++) {
            if (meta.todo[j].path === patch[i].path) {
              meta.todo[j].op = 'noop';
              break;
            }
          }
          meta.todo.push(patch[i]);
          break;
        case 'remove':
          for (j = 0; j < meta.todo.length; j++) {
            if (meta.todo[j].path === patch[i].path) {
              meta.todo[j].op = 'noop';
            }
            else if (meta.todo[j].path.indexOf(patch[i].path + '/') === 0) {
              meta.todo[j].op = 'noop';
            }
          }
          break;
        case 'move':
          for (j = 0; j < meta.todo.length; j++) {
            if (meta.todo[j].path === patch[i].from) {
              meta.todo[j].path = patch[i].path;
            }
            else if (meta.todo[j].path.indexOf(patch[i].from + '/') === 0) {
              meta.todo[j].path = patch[i].path + meta.todo[j].path.substr(patch[i].from.length);
            }
          }
          break;
        case 'copy': // TODO: should not happen for now
        case 'test':
        default:
          break;
        }
      }
      for (i = meta.todo.length - 1; i >= 0; i--) {
        if (meta.todo[i].op === 'noop') {
          meta.todo.splice(i, 1);
        }
      }
      current.meta = meta;
      return current;
    }

    function update(paths, contents) {
      var prevDefault;
      var currentDefault;
      var prevLocalized;
      var prevLocalizedOriginal;
      var currentLocalized;
      var prevAncestors = [];
      var patchStatus;
      var i;
      try {
        prevDefault = JSON.parse(fs.readFileSync(paths.srcDefaultPath, 'utf8'));
      }
      catch (e) {
        prevDefault = {}; // presumably file not found
      }
      try {
        currentDefault = JSON.parse(fs.readFileSync(paths.distDefaultPath, 'utf8'));
      }
      catch (e) {
        currentDefault = {}; // presumably file not found
      }
      for (i = 0; i < paths.ancestorSrcPaths.length; i++) {
        try {
          prevAncestors[i] = JSON.parse(fs.readFileSync(paths.ancestorSrcPaths[i], 'utf8'));
        }
        catch (e) {
          prevAncestors[i] = null; // presumably file not found
        }
      }

      try {
        prevLocalized = JSON.parse(contents);
      }
      catch (e) {
        prevLocalized = {};
      }
      prevLocalizedOriginal = deepcopy(prevLocalized);

      var patch = rfc6902.createPatch(prevDefault, currentDefault);
      patch = minimizePatch(patch, prevDefault, currentDefault);

      for (i = 0; i < prevAncestors.length; i++) {
        if (prevAncestors[i]) {
          rfc6902.applyPatch(prevAncestors[i], patch);
        }
      }

      patchStatus = rfc6902.applyPatch(prevLocalized, patch);
      for (i = 0; i < patchStatus.length; i++) {
        if (patchStatus[i]) {
          console.log('warning: ' + patchStatus[i].name +
                                  ' for ' + JSONstringify(patch[i]));
        }
      }

      currentLocalized = deepcopy(currentDefault);

      for (i = 0; i < prevAncestors.length; i++) {
        if (prevAncestors[i]) {
          deepMap(currentLocalized, prevAncestors[i], function (value) { return value; });
        }
      }

      deepMap(currentLocalized, prevLocalized, function (value) { return value; });

      updateMetaTodo(currentLocalized, prevLocalizedOriginal);

      //console.log(JSONstringify(patch, null, 2));
      bundles[paths.lang] = bundles[paths.lang] || {};
      bundles[paths.lang][paths.baseName] = deepcopy(currentLocalized);
      bundles[''] = bundles[''] || {};
      bundles[''][paths.baseName] = deepcopy(currentDefault);
      return JSONstringify(currentLocalized, null, jsonSpace);
    }

    function doLeverage() {
      if (file.isNull()) {
        callback(null, file);
        return;
      }

      if (file.isStream()) {
        callback(new gutil.PluginError('leverage', 'Streaming not supported'));
        return;
      }

      if (file.isBuffer()) {
        var contents = String(file.contents);
        var paths = parsePath();
        //console.log(paths);
        var result = update(paths, contents);
        if (result) {
          file.contents = new Buffer(result);
          return callback(null, file);
        }
      }

      callback(null, file);
    }

    doLeverage();
  });
};
<|endoftext|>


<commit_before>/**
 * Creates a {@link LineString} {@link Feature} based on a
 * coordinate array. Properties can be added optionally.
 *
 * @module turf/linestring
 * @category helper
 * @param {Array<Array<Number>>} coordinates an array of Positions
 * @param {Object=} properties an Object of key-value pairs to add as properties
 * @returns {LineString} a LineString feature
 * @throws {Error} if no coordinates are passed
 * @example
 * var linestring1 = turf.linestring([
 *	[-21.964416, 64.148203],
 *	[-21.956176, 64.141316],
 *	[-21.93901, 64.135924],
 *	[-21.927337, 64.136673]
 * ]);
 * var linestring2 = turf.linestring([
 *	[-21.929054, 64.127985],
 *	[-21.912918, 64.134726],
 *	[-21.916007, 64.141016],
 * 	[-21.930084, 64.14446]
 * ], {name: 'line 1', distance: 145});
 *
 * //=linestring1
 *
 * //=linestring2
 */
module.exports = function(coordinates, properties){
  if (!coordinates) {
      throw new Error('No coordinates passed');
  }
  return {
    "type": "Feature",
    "geometry": {
      "type": "LineString",
      "coordinates": coordinates
    },
    "properties": properties || {}
  };
};
<commit_msg>Switch doc to closure compiler templating<commit_after>/**
 * Creates a {@link LineString} based on a
 * coordinate array. Properties can be added optionally.
 *
 * @module turf/linestring
 * @category helper
 * @param {Array<Array<Number>>} coordinates an array of Positions
 * @param {Object=} properties an Object of key-value pairs to add as properties
 * @returns {Feature<LineString>} a LineString feature
 * @throws {Error} if no coordinates are passed
 * @example
 * var linestring1 = turf.linestring([
 *	[-21.964416, 64.148203],
 *	[-21.956176, 64.141316],
 *	[-21.93901, 64.135924],
 *	[-21.927337, 64.136673]
 * ]);
 * var linestring2 = turf.linestring([
 *	[-21.929054, 64.127985],
 *	[-21.912918, 64.134726],
 *	[-21.916007, 64.141016],
 * 	[-21.930084, 64.14446]
 * ], {name: 'line 1', distance: 145});
 *
 * //=linestring1
 *
 * //=linestring2
 */
module.exports = function(coordinates, properties){
  if (!coordinates) {
      throw new Error('No coordinates passed');
  }
  return {
    "type": "Feature",
    "geometry": {
      "type": "LineString",
      "coordinates": coordinates
    },
    "properties": properties || {}
  };
};
<|endoftext|>


<commit_before>var postcss = require('postcss');
var minimatch = require('minimatch');
var Promise = require('promise');
var path = require('path');

module.exports = main;

function main(options) {

  var options = options || {};
  var pluginsConfig = options.plugins;
  var plugins = [];

  // Require each plugin, pass it it’s options
  // and add it to the plugins array.
  Object.keys(pluginsConfig).forEach(function(pluginName) {
    var value = pluginsConfig[pluginName];
    if (value === false) return;
    var pluginOptions = value === true ? {} : value;
    var plugin = require(pluginName);
    plugins.push(plugin(pluginOptions));
  });

  var map = normalizeMapOptions(options.map);

  var processor = postcss(plugins);

  return function (files, metalsmith, done) {
    var styles = Object.keys(files).filter(minimatch.filter("*.css", { matchBase: true }));

    if(styles.length == 0) {
      done();
      return;
    }

    var promises = [];

    styles.forEach(function (file) {
      var contents = files[file].contents.toString();
      var absolutePath = path.resolve(metalsmith.source(), file);

      var promise = processor
        .process(contents, {
          from: absolutePath,
          to: absolutePath,
          map: map
        })
        .then(function (result) {
          files[file].contents = new Buffer(result.css);

           if (result.map) {
             files[file + '.map'] = {
               contents: new Buffer(JSON.stringify(result.map)),
               mode: files[file].mode,
               stats: files[file].stats
             };
           }
        });

        promises.push(promise);
    });

    Promise.all(promises)
      .then(function(results) {
        done();
      })
      .catch(function(error) {
        done(new Error("Error during postcss processing: " + JSON.stringify(error)));
      });

  }
}

function normalizeMapOptions(map) {
  if (!map) return undefined;

  return {
    inline: map === true ? true : map.inline,
    prev: false, // Not implemented yet
    sourcesContent: undefined,  // Not implemented yet
    annotation: undefined // Not implemented yet
  };
}
<commit_msg>add array syntax support<commit_after>var postcss = require('postcss');
var minimatch = require('minimatch');
var Promise = require('promise');
var path = require('path');

module.exports = main;

function main(options) {

  var options = options || {};
  var pluginsConfig = options.plugins;
  var plugins = [];

  // Require each plugin, pass it it’s options
  // and add it to the plugins array.
  if (Array.isArray(pluginsConfig)) {
    pluginsConfig.forEach(function (plugin) {
      var pkg;
      var config = {};
      if (typeof plugin === 'string') {
        pkg = plugin;
      } else {
        pkg = plugin[0];
        config = plugin[1];
      }
      if (config === false) {
        return;
      }
      plugins.push(require(pkg)(config));
    });
  } else {
    Object.keys(pluginsConfig).forEach(function (pluginName) {
      var value = pluginsConfig[pluginName];
      if (value === false) return;
      var pluginOptions = value === true ? {} : value;
      plugins.push(require(pluginName)(pluginOptions));
    });
  }

  var map = normalizeMapOptions(options.map);

  var processor = postcss(plugins);

  return function (files, metalsmith, done) {
    var styles = Object.keys(files).filter(minimatch.filter("*.css", { matchBase: true }));

    if(styles.length == 0) {
      done();
      return;
    }

    var promises = [];

    styles.forEach(function (file) {
      var contents = files[file].contents.toString();
      var absolutePath = path.resolve(metalsmith.source(), file);

      var promise = processor
        .process(contents, {
          from: absolutePath,
          to: absolutePath,
          map: map
        })
        .then(function (result) {
          files[file].contents = new Buffer(result.css);

           if (result.map) {
             files[file + '.map'] = {
               contents: new Buffer(JSON.stringify(result.map)),
               mode: files[file].mode,
               stats: files[file].stats
             };
           }
        });

        promises.push(promise);
    });

    Promise.all(promises)
      .then(function(results) {
        done();
      })
      .catch(function(error) {
        done(new Error("Error during postcss processing: " + JSON.stringify(error)));
      });

  }
}

function normalizeMapOptions(map) {
  if (!map) return undefined;

  return {
    inline: map === true ? true : map.inline,
    prev: false, // Not implemented yet
    sourcesContent: undefined,  // Not implemented yet
    annotation: undefined // Not implemented yet
  };
}
<|endoftext|>


<commit_before>'use strict';

var join      = require('path').join
var EventEmitter = require('events')
//var Obv       = require('obv')

var pull      = require('pull-stream')
var timestamp = require('monotonic-timestamp')
var explain   = require('explain-error')
//var createFeed = require('ssb-feed')
var ref       = require('ssb-ref')
var ssbKeys   = require('ssb-keys')
var Notify    = require('pull-notify')

var isFeedId = ref.isFeedId
var isMsgId  = ref.isMsgId
var isBlobId = ref.isBlobId

var u         = require('./util')
var stdopts   = u.options
var Format    = u.Format
//53 bit integer
var MAX_INT  = 0x1fffffffffffff

function isString (s) {
  return 'string' === typeof s
}

var isArray = Array.isArray

function isObject (o) {
  return o && 'object' === typeof o && !Array.isArray(o)
}

function getVMajor () {
  var version = require('./package.json').version
  return (version.split('.')[0])|0
}

function errorCB (err) {
  if(err) throw err
}

module.exports = function (_db, opts, keys, path) {
  path = path || _db.location

  keys = keys || ssbKeys.generate()

  var db = require('./db')(join(opts.path || path, 'flume'), keys, opts)

  //legacy database
  if(_db) require('./legacy')(_db, db)
  else db.ready.set(true)

  db.sublevel = function (a, b) {
    return _db.sublevel(a, b)
  }

  //UGLY HACK, but...
  //fairly sure that something up the stack expects ssb to be an event emitter.
  db.__proto__ = new EventEmitter()

  db.opts = opts

  var _get = db.get

  db.get = function (key, cb) {
    var isPrivate = false, unbox
    if('object' === typeof key) {
      isPrivate = key.private === true
      unbox = key.unbox
      key = key.id
    }
    if(ref.isMsg(key))
      return db.keys.get(key, function (err, data) {
        if(isPrivate && unbox) data = db.unbox(data, unbox)
        if(err) cb(err)
        else cb(null, data && u.reboxValue(data.value, isPrivate))
      })
    else if(Number.isInteger(key))
      _get(key, cb) //seq
    else
      throw new Error('secure-scuttlebutt.get: key *must* be a ssb message id or a flume offset')
  }

  db.add = function (msg, cb) {
    db.queue(msg, function (err, data) {
      if(err) cb(err)
      else db.flush(function () { cb(null, data) })
    })
  }

  db.createFeed = function (keys) {
    if(!keys) keys = ssbKeys.generate()
    function add (content, cb) {
      //LEGACY: hacks to support add as a continuable
      if(!cb)
        return function (cb) { add (content, cb) }

      db.append({content: content, keys: keys}, cb)
    }
    return {
      add: add, publish: add,
      id: keys.id, keys: keys
    }
  }

  db.createRawLogStream = function (opts) {
    return db.stream(opts)
  }

  //pull in the features that are needed to pass the tests
  //and that sbot, etc uses but are slow.
  require('./extras')(db, opts, keys)

  //writeStream - used in (legacy) replication.
  db.createWriteStream = function (cb) {
    cb = cb || errorCB
    return pull(
      pull.asyncMap(function (data, cb) {
        db.queue(data, function (err, msg) {
          if(err) {
            db.emit('invalid', err, msg)
          }
          setImmediate(cb)
        })
      }),
      pull.drain(null, function (err) {
        if(err) return cb(err)
        db.flush(cb)
      })
    )
  }

  //should be private
  db.createHistoryStream = db.clock.createHistoryStream

  //called with [id, seq] or "<id>:<seq>"
  db.getAtSequence = function (seqid, cb) {
    //will NOT expose private plaintext
    db.clock.get(isString(seqid) ? seqid.split(':') : seqid, function (err, value) {
      if(err) cb(err)
      else cb(null, u.rebox(value))
    })
  }

  db.getVectorClock = function (_, cb) {
    if(!cb) cb = _
    db.last.get(function (err, h) {
      if(err) return cb(err)
      var clock = {}
      for(var k in h)
        clock[k] = h[k].sequence
      cb(null, clock)
    })

  }

  if(_db) {
    var close = db.close
    db.close = function (cb) {
      var n = 2
      _db.close(next); close(next)

      function next (err) {
        if(err && n>0) {
          n = -1
          return cb(err)
        }
        if(--n) return
        cb()
      }

    }

  }
  return db
}

<commit_msg>allow %{msg_id}?unbox={key}<commit_after>'use strict';

var join      = require('path').join
var EventEmitter = require('events')
//var Obv       = require('obv')

var pull      = require('pull-stream')
var timestamp = require('monotonic-timestamp')
var explain   = require('explain-error')
//var createFeed = require('ssb-feed')
var ref       = require('ssb-ref')
var ssbKeys   = require('ssb-keys')
var Notify    = require('pull-notify')

var isFeedId = ref.isFeedId
var isMsgId  = ref.isMsgId
var isBlobId = ref.isBlobId

var u         = require('./util')
var stdopts   = u.options
var Format    = u.Format
//53 bit integer
var MAX_INT  = 0x1fffffffffffff

function isString (s) {
  return 'string' === typeof s
}

var isArray = Array.isArray

function isObject (o) {
  return o && 'object' === typeof o && !Array.isArray(o)
}

function getVMajor () {
  var version = require('./package.json').version
  return (version.split('.')[0])|0
}

function errorCB (err) {
  if(err) throw err
}

module.exports = function (_db, opts, keys, path) {
  path = path || _db.location

  keys = keys || ssbKeys.generate()

  var db = require('./db')(join(opts.path || path, 'flume'), keys, opts)

  //legacy database
  if(_db) require('./legacy')(_db, db)
  else db.ready.set(true)

  db.sublevel = function (a, b) {
    return _db.sublevel(a, b)
  }

  //UGLY HACK, but...
  //fairly sure that something up the stack expects ssb to be an event emitter.
  db.__proto__ = new EventEmitter()

  db.opts = opts

  var _get = db.get

  db.get = function (key, cb) {
    var isPrivate = false, unbox
    if('object' === typeof key) {
      isPrivate = key.private === true
      unbox = key.unbox
      key = key.id
    }
    console.log(key, ref.isMsg(key), ref.isMsgLink(key))
    if(ref.isMsg(key))
      return db.keys.get(key, function (err, data) {
        if(isPrivate && unbox) data = db.unbox(data, unbox)
        if(err) cb(err)
        else cb(null, data && u.reboxValue(data.value, isPrivate))
      })
    else if(ref.isMsgLink(key)) {
      var link = ref.parseLink(key)
      return db.get({id: link.link, private: !!link.query.unbox, unbox: link.query.unbox}, cb)
    }
    else if(Number.isInteger(key))
      _get(key, cb) //seq
    else
      throw new Error('secure-scuttlebutt.get: key *must* be a ssb message id or a flume offset')
  }

  db.add = function (msg, cb) {
    db.queue(msg, function (err, data) {
      if(err) cb(err)
      else db.flush(function () { cb(null, data) })
    })
  }

  db.createFeed = function (keys) {
    if(!keys) keys = ssbKeys.generate()
    function add (content, cb) {
      //LEGACY: hacks to support add as a continuable
      if(!cb)
        return function (cb) { add (content, cb) }

      db.append({content: content, keys: keys}, cb)
    }
    return {
      add: add, publish: add,
      id: keys.id, keys: keys
    }
  }

  db.createRawLogStream = function (opts) {
    return db.stream(opts)
  }

  //pull in the features that are needed to pass the tests
  //and that sbot, etc uses but are slow.
  require('./extras')(db, opts, keys)

  //writeStream - used in (legacy) replication.
  db.createWriteStream = function (cb) {
    cb = cb || errorCB
    return pull(
      pull.asyncMap(function (data, cb) {
        db.queue(data, function (err, msg) {
          if(err) {
            db.emit('invalid', err, msg)
          }
          setImmediate(cb)
        })
      }),
      pull.drain(null, function (err) {
        if(err) return cb(err)
        db.flush(cb)
      })
    )
  }

  //should be private
  db.createHistoryStream = db.clock.createHistoryStream

  //called with [id, seq] or "<id>:<seq>"
  db.getAtSequence = function (seqid, cb) {
    //will NOT expose private plaintext
    db.clock.get(isString(seqid) ? seqid.split(':') : seqid, function (err, value) {
      if(err) cb(err)
      else cb(null, u.rebox(value))
    })
  }

  db.getVectorClock = function (_, cb) {
    if(!cb) cb = _
    db.last.get(function (err, h) {
      if(err) return cb(err)
      var clock = {}
      for(var k in h)
        clock[k] = h[k].sequence
      cb(null, clock)
    })

  }

  if(_db) {
    var close = db.close
    db.close = function (cb) {
      var n = 2
      _db.close(next); close(next)

      function next (err) {
        if(err && n>0) {
          n = -1
          return cb(err)
        }
        if(--n) return
        cb()
      }

    }

  }
  return db
}

<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var spawn = require('child_process').spawn;
var hyperquest = require('hyperquest');
var rimraf = require('rimraf');
var zlib = require('zlib');
var unzip = require('unzip');
var csvToVrt = require('csv-to-vrt');
var uploadStream = require('./lib/uploadStream');
var checkHash = require('./lib/checkHash');

var zipReg = /.zip$/i;
var csvReg = /(?:txt|csv)$/i;
var restrictedReg = /\.\.|\//g;

var program;

if(require.main === module){
  program = require('commander');
  program
    .version('0.0.1')
    .option('-b, --bucket <bucket>', 'An S3 bucket where the data should be loaded.')
    .option('-p, --profile <profile>', 'The aws profile in ~/.aws/credentials. Will also respect environmental variables.', 'default')
    .option('-d, --directory <directory>', 'A directory where the data should be loaded, either relative to the current folder or the passed S3 bucket.', '.')
    .option('-f --file <file>', 'The json data file that contains the collected data endpoints. Defaults to data.json.', 'data.json')
    .option('-m --match <match>', 'A string or regular expression that the names from the <file> must contain or match', null)
    .parse(process.argv)
  run(program);
}

function run(program, callback){
  var data = JSON.parse(fs.readFileSync(program.file));
  var stringMatch = typeof program.match === 'string';
  var regMatch = typeof program.match === 'object';

  if(program.bucket) uploadStream.init(program.bucket, program.profile)

  data.forEach(function(record){

    //Don't allow to traverse to other folders via data.json
    if(restrictedReg.test(record.name)){
      throw new Error('Invalid record name. Must not contain ".." or "/".');
    }

    if(stringMatch && record.name.indexOf(program.match) === -1) return;
    else if(regMatch && !program.match.test(record.name)) return;

    var request = hyperquest(record.url);

    request.on('error', function(err){
      console.log('Error requesting %s.\n', record.url, err);
      if(callback) return callback(err);
      throw err;
    })

    checkHash(request, record.hash, function(hashIsEqual, remoteHash){
      if(hashIsEqual) return;
      request.unpipe();
      request.emit('error', new Error('The hash from ' + record.name + ' did not match the downloaded file\'s hash.\nRecord hash: ' + record.hash +'\nRemote hash: ' + remoteHash +'\n'));
    });

    if(zipReg.test(record.url)){
      request.pipe(unzip.Extract({path: name}))
        .on('close', function(){
          var unzipped = path.join(name, record.file)

          function removeZipped(err, details){
            rimraf(name, function(e){
              if(e) throw e;
              if(err) throw err;
            });
          }

          if(csvReg.test(record.file)){
            csvToVrt(unzipped, record.sourceSrs, function(vrt){
              handleStream(spawnOgr(vrt), record, removeZipped);
            });
          }else{
            handleStream(spawnOgr(unzipped), record, removeZipped);
          }
        });
    }else{
      handleStream(spawnOgr(null, request), record, report)
    }
  });

  function report(err, details){
    console.log(err, details);
  }

  function spawnOgr(file, stream){
    var child;
    if(stream){
      child = spawn('ogr2ogr', ['-f', 'CSV', '-t_srs', 'WGS84', -'lco', 'GEOMETRY=AS_XY', '/vsistdout/', '/vsistdin/'])
      stream.pipe(child.stdin);
    }else{
      child = spawn('ogr2ogr', ['-f', 'CSV', '-t_srs', 'WGS84', '-lco', 'GEOMETRY=AS_XY', '/vsistdout/', file])
    }
    return child.stdout;
  }

  function handleStream(stream, record, cb){
    if(!cb) cb = function(err){if(err) throw err;};

    var endfile = path.join(program.directory, record.name + '.csv.gz');
    var zipStream = zlib.createGzip();

    stream.on('error', function(err){
      this.unpipe();
      cb(err);
    })

    stream.pipe(zipStream);

    if(program.bucket){
      return uploadStream.stream(zipStream, endfile, cb);
    }

    zipStream.pipe(fs.createWriteStream(endfile))
      .on('finish', cb)
      .on('error', function(err){
        this.unpipe();
        cb(err);
      })
  }

}
<commit_msg>Callback changes<commit_after>#!/usr/bin/env node

'use strict';
var fs = require('fs');
var path = require('path');
var spawn = require('child_process').spawn;
var hyperquest = require('hyperquest');
var rimraf = require('rimraf');
var zlib = require('zlib');
var unzip = require('unzip');
var csvToVrt = require('csv-to-vrt');
var uploadStream = require('./lib/uploadStream');
var checkHash = require('./lib/checkHash');

var zipReg = /.zip$/i;
var csvReg = /(?:txt|csv)$/i;
var restrictedReg = /\.\.|\//g;

var program;

if(require.main === module){
  program = require('commander');
  program
    .version('0.0.1')
    .option('-b, --bucket <bucket>', 'An S3 bucket where the data should be loaded.')
    .option('-p, --profile <profile>', 'The aws profile in ~/.aws/credentials. Will also respect environmental variables.', 'default')
    .option('-d, --directory <directory>', 'A directory where the data should be loaded, either relative to the current folder or the passed S3 bucket.', '.')
    .option('-f --file <file>', 'The json data file that contains the collected data endpoints. Defaults to data.json.', 'data.json')
    .option('-m --match <match>', 'A string or regular expression that the names from the <file> must contain or match', null)
    .parse(process.argv)
  run(program);
}

function run(program, callback){
  var stringMatch = typeof program.match === 'string';
  var regMatch = typeof program.match === 'object';

  var data = JSON.parse(fs.readFileSync(program.file));
  var recordCount = data.length;
  var processed = 0;

  function recordCallback(err){
    if(err){
     if(callback) return callback(err);
     throw err;
    }

    if(++processed === recordCount){
      callback(null, recordCount);
    }
  }

  if(program.bucket) uploadStream.init(program.bucket, program.profile)

  data.forEach(function(record){

    //Don't allow to traverse to other folders via data.json
    if(restrictedReg.test(record.name)){
      throw new Error('Invalid record name. Must not contain ".." or "/".');
    }

    //If the record is filtered, remove it from the count
    if(stringMatch && record.name.indexOf(program.match) === -1 ||
       regMatch && !program.match.test(record.name)
    ){
       return --recordCount;
    }

    var request = hyperquest(record.url);

    request.on('error', recordCallback);

    checkHash(request, record.hash, function(hashIsEqual, remoteHash){
      if(hashIsEqual) return;
      request.unpipe();
      request.emit('error', new Error('The hash from ' + record.name + ' did not match the downloaded file\'s hash.\nRecord hash: ' + record.hash +'\nRemote hash: ' + remoteHash +'\n'));
    });

    if(zipReg.test(record.url)){
      request.pipe(unzip.Extract({path: record.name}))
        .on('close', function(){
          var unzipped = path.join(record.name, record.file)

          function removeZipped(err, details){
            rimraf(record.name, function(e){
              recordCallback(e || err);
            });
          }

          if(csvReg.test(record.file)){
            csvToVrt(unzipped, record.sourceSrs, function(vrt){
              handleStream(spawnOgr(vrt), record, removeZipped);
            });
          }else{
            handleStream(spawnOgr(unzipped), record, removeZipped);
          }
        });
    }else{
      handleStream(spawnOgr(null, request), record, report)
    }
  });

  function report(err, details){
    console.log(err, details);
  }

  function spawnOgr(file, stream){
    var child;
    if(stream){
      child = spawn('ogr2ogr', ['-f', 'CSV', '-t_srs', 'WGS84', -'lco', 'GEOMETRY=AS_XY', '/vsistdout/', '/vsistdin/'])
      stream.pipe(child.stdin);
    }else{
      child = spawn('ogr2ogr', ['-f', 'CSV', '-t_srs', 'WGS84', '-lco', 'GEOMETRY=AS_XY', '/vsistdout/', file])
    }
    return child.stdout;
  }

  function handleStream(stream, record, cb){
    if(!cb) cb = function(err){if(err) throw err;};

    var endfile = path.join(program.directory, record.name + '.csv.gz');
    var zipStream = zlib.createGzip();

    stream.on('error', function(err){
      this.unpipe();
      cb(err);
    })

    stream.pipe(zipStream);

    if(program.bucket){
      return uploadStream.stream(zipStream, endfile, cb);
    }

    zipStream.pipe(fs.createWriteStream(endfile))
      .on('finish', cb)
      .on('error', function(err){
        this.unpipe();
        cb(err);
      })
  }

}
<|endoftext|>


<commit_before>/***************************************************************************
 * @description
 *
 * emergency;    // 8xxxxxxx
 * alert;        // 7xxxxxxx
 * critical;     // 6xxxxxxx
 * error;        // 5xxxxxxx
 * warning;      // 4xxxxxxx
 * notice;       // 3xxxxxxx
 * info;         // 2xxxxxxx
 * debug;        // 1xxxxxxx
 *
 * @TODO logger deberia permitir indistintamente su invocacion de tres formas:
 * logger(3, {})            => la mas completa
 * logger("some message")   => para mensajes sobre la marcha
 * logger({})               => igualmente sobre la marcha, pero con info estructurada
 * logger(Error)            => logueo de errores
 ***************************************************************************/
var Logentries      = require('le_node')
,   chalk           = require('chalk')
,   _               = require('lodash')
,   handlebars      = require('handlebars')
,   siftRequest     = require("./lib/sift-request")
;

const LOCAL_OUTPUT_ONLY = !process.env.LOGENTRIES_TOKEN && process.env.RACK_ENV !== "staging" && process.env.RACK_ENV !== "production";
try {
    const CONFIG = {};
    CONFIG.token= process.env.LOGENTRIES_TOKEN;
    CONFIG.console= true;
    CONFIG.levels= ["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"];
    CONFIG.minLevel= process.env.LOGENTRIES_LOG_LEVEL || 0;
    CONFIG.bufferSize= 200;
    CONFIG.secure= false;
    CONFIG.flatten= false;
    CONFIG.flattenArrays= false;
    //replacer:
    CONFIG.timestamp= true;
    CONFIG.withLevel= true;
    CONFIG.withStack= true;
    const LOGENTRIES_CLIENT = new Logentries(CONFIG);
    console.log("Yeah! Logentries instantation succeded!");
    LOGENTRIES_CLIENT.on("error", (e) => LOGENTRIES_CLIENT.critical("[XXXXXXXX] [Unsuccessfully connect to Logentries", e));
} catch (e) {
    console.log("Ouch! Logentries instantation failed!");
}
module.exports = (LOCAL_OUTPUT_ONLY)? FAKE_CLIENT : GENUINE_CLIENT;

/*******************************************************************************
 * @description
 *
 * @param {Object} lib:
 * @param {Number} libraryId:
 */
function FAKE_CLIENT(lib, libraryId){
    return {
        "debug": fakeLogger("debug", lib, libraryId),
        "info": fakeLogger("info", lib, libraryId),
        "notice": fakeLogger("notice", lib, libraryId),
        "warning": fakeLogger("warning", lib, libraryId),
        "error": fakeLogger("error", lib, libraryId),
        "critical": fakeLogger("critical", lib, libraryId),
        "alert": fakeLogger("alert", lib, libraryId),
        "emergency": fakeLogger("emergency", lib, libraryId),
    };
}

/*******************************************************************************
 * @description
 *
 * @param {Object} lib:
 * @param {Number} libraryId:
 */
function GENUINE_CLIENT(lib, libraryId){
    return {
        "debug": genuineLogger("debug", lib, libraryId),
        "info": genuineLogger("info", lib, libraryId),
        "notice": genuineLogger("notice", lib, libraryId),
        "warning": genuineLogger("warning", lib, libraryId),
        "error": genuineLogger("error", lib, libraryId),
        "critical": genuineLogger("critical", lib, libraryId),
        "alert": genuineLogger("alert", lib, libraryId),
        "emergency": genuineLogger("emergency", lib, libraryId),
    };
}

/*******************************************************************************
 * @description
 *
 * @param {Object} lib:
 * @param {String} level:
 * @param {Number} libraryId:
 *
 * @return {Function}:
 */
function fakeLogger(level, lib, libraryId){
    libraryId = libraryId || 999;
    return f;

    function f(eventCode, info){
        //sanitize and defaults
        //@TODO info deberia poder ser solo Object o String
        //@TODO eventCode deberia ser Number
        info = info || {};
        if (_.isString(info)) { info = {str: info} }        //estandarizacion de String a Object

        //compongo el codigo de evento
        var LEVEL_CODE;
        switch (level) {
            case 'debug': LEVEL_CODE = 1*10000000; break;
            case 'info': LEVEL_CODE = 2*10000000; break;
            case 'notice': LEVEL_CODE = 3*10000000; break;
            case 'warning': LEVEL_CODE = 4*10000000; break;
            case 'error': LEVEL_CODE = 5*10000000; break;
            case 'critical': LEVEL_CODE = 6*10000000; break;
            case 'alert': LEVEL_CODE = 7*10000000; break;
            case 'emergency': LEVEL_CODE = 8*10000000; break;
            default: break;
        }
        var LIBRARY_CODE = libraryId*10000;
        var FULL_CODE = LEVEL_CODE + LIBRARY_CODE + eventCode;

        //genero el cuerpo del mensaje del slug
        var MESSAGE;
        try {
            MESSAGE = handlebars.compile(lib[level][eventCode])(info);
        } catch (e) {
            MESSAGE = "=========EVENT CODE MALFORMED: " + level + "/" + eventCode + "==========";
        }

        //compongo el slug
        var SLUG = "[" + FULL_CODE + "] [" + MESSAGE + "]";

        //logueo un String (slug)
        console.log(SLUG);
        if (info && info.error) {
            console.log("====================STACK BEGINS===================");
            console.log(info.error.stack);
            console.log("====================STACK ENDS===================");
        }
    }
}

/*******************************************************************************
 * @description
 * Puesto que en entornos de desarrollo (development) solo se loguea un
 * mensaje que resume el evento (al contrario que en pre-produccion y en
 * produccion, donde se almacena como JSON toda la informacion del mismo),
 * en los casos en que el evento contenga un Object de tipo Error, ademas
 * del slug se loguea explicitamente el stack del Error, pues de otro modo se
 * pierde la informacion contenida en el mismo, vital para la depuracion
 * del mismo.
 *
 * @param {Object} lib:
 * @param {String} level:
 * @param {Number} libraryId:
 *
 * @return {Function}:
 */
function genuineLogger(level, lib, libraryId){
    libraryId = libraryId || 999;
    return f;

    function f(eventCode, info){
        //sanitize and defaults
        //@TODO info deberia poder ser solo Object o String
        //@TODO eventCode deberia ser Number
        info = info || {};
        if (_.isString(info)) { info = {str: info} }        //estandarizacion de String a Object

        //compongo el codigo de evento
        var LEVEL_CODE;
        switch (level) {
            case 'debug': LEVEL_CODE = 1*10000000; break;
            case 'info': LEVEL_CODE = 2*10000000; break;
            case 'notice': LEVEL_CODE = 3*10000000; break;
            case 'warning': LEVEL_CODE = 4*10000000; break;
            case 'error': LEVEL_CODE = 5*10000000; break;
            case 'critical': LEVEL_CODE = 6*10000000; break;
            case 'alert': LEVEL_CODE = 7*10000000; break;
            case 'emergency': LEVEL_CODE = 8*10000000; break;
            default: break;
        }
        var LIBRARY_CODE = libraryId*10000;
        var FULL_CODE = LEVEL_CODE + LIBRARY_CODE + eventCode;

        //Selecciono, esc, informacion pertinente de la request
        if (info && info.request) { info.request = siftRequest(info.request) }
        //genero el cuerpo del mensaje del slug
        var MESSAGE;
        try {
            MESSAGE = handlebars.compile(lib[level][eventCode])(info);
        } catch (e) {
            MESSAGE = "=========EVENT CODE MALFORMED: " + level + "/" + eventCode + "==========";
        }

        //compongo el slug
        var SLUG = "[" + FULL_CODE + "] [" + MESSAGE + "]";

        //segun el entorno, logueo un String (slug) o un Object (info)
        if (process.env.RACK_ENV === "development"){
            LOGENTRIES_CLIENT[level](SLUG);
            //@vid description
            if (info && info.error) {
                console.log("====================STACK BEGINS===================");
                console.log(info.error.stack);
                console.log("====================STACK ENDS===================");
            }
        } else {
            info.severity = level;
            info.library = libraryId;
            info.code = eventCode;
            info.fullCode = FULL_CODE;
            info.eventSlug = SLUG;
            //if (info && info.error) info.response = ERROR_CODES[info.error];
            LOGENTRIES_CLIENT[level](info);
        }
    }
}<commit_msg>Restringida evaluacion de OUTPUT_ONLY al RACK_ENV de ejecucion.<commit_after>/***************************************************************************
 * @description
 *
 * emergency;    // 8xxxxxxx
 * alert;        // 7xxxxxxx
 * critical;     // 6xxxxxxx
 * error;        // 5xxxxxxx
 * warning;      // 4xxxxxxx
 * notice;       // 3xxxxxxx
 * info;         // 2xxxxxxx
 * debug;        // 1xxxxxxx
 *
 * @TODO logger deberia permitir indistintamente su invocacion de tres formas:
 * logger(3, {})            => la mas completa
 * logger("some message")   => para mensajes sobre la marcha
 * logger({})               => igualmente sobre la marcha, pero con info estructurada
 * logger(Error)            => logueo de errores
 ***************************************************************************/
var Logentries      = require('le_node')
,   chalk           = require('chalk')
,   _               = require('lodash')
,   handlebars      = require('handlebars')
,   siftRequest     = require("./lib/sift-request")
;

const LOCAL_OUTPUT_ONLY = !process.env.LOGENTRIES_TOKEN;
try {
    const CONFIG = {};
    CONFIG.token= process.env.LOGENTRIES_TOKEN;
    CONFIG.console= true;
    CONFIG.levels= ["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"];
    CONFIG.minLevel= process.env.LOGENTRIES_LOG_LEVEL || 0;
    CONFIG.bufferSize= 200;
    CONFIG.secure= false;
    CONFIG.flatten= false;
    CONFIG.flattenArrays= false;
    //replacer:
    CONFIG.timestamp= true;
    CONFIG.withLevel= true;
    CONFIG.withStack= true;
    const LOGENTRIES_CLIENT = new Logentries(CONFIG);
    console.log("Yeah! Logentries instantation succeded!");
    LOGENTRIES_CLIENT.on("error", (e) => LOGENTRIES_CLIENT.critical("[XXXXXXXX] [Unsuccessfully connect to Logentries", e));
} catch (e) {
    console.log("Ouch! Logentries instantation failed!");
}
module.exports = (LOCAL_OUTPUT_ONLY)? FAKE_CLIENT : GENUINE_CLIENT;

/*******************************************************************************
 * @description
 *
 * @param {Object} lib:
 * @param {Number} libraryId:
 */
function FAKE_CLIENT(lib, libraryId){
    return {
        "debug": fakeLogger("debug", lib, libraryId),
        "info": fakeLogger("info", lib, libraryId),
        "notice": fakeLogger("notice", lib, libraryId),
        "warning": fakeLogger("warning", lib, libraryId),
        "error": fakeLogger("error", lib, libraryId),
        "critical": fakeLogger("critical", lib, libraryId),
        "alert": fakeLogger("alert", lib, libraryId),
        "emergency": fakeLogger("emergency", lib, libraryId),
    };
}

/*******************************************************************************
 * @description
 *
 * @param {Object} lib:
 * @param {Number} libraryId:
 */
function GENUINE_CLIENT(lib, libraryId){
    return {
        "debug": genuineLogger("debug", lib, libraryId),
        "info": genuineLogger("info", lib, libraryId),
        "notice": genuineLogger("notice", lib, libraryId),
        "warning": genuineLogger("warning", lib, libraryId),
        "error": genuineLogger("error", lib, libraryId),
        "critical": genuineLogger("critical", lib, libraryId),
        "alert": genuineLogger("alert", lib, libraryId),
        "emergency": genuineLogger("emergency", lib, libraryId),
    };
}

/*******************************************************************************
 * @description
 *
 * @param {Object} lib:
 * @param {String} level:
 * @param {Number} libraryId:
 *
 * @return {Function}:
 */
function fakeLogger(level, lib, libraryId){
    libraryId = libraryId || 999;
    return f;

    function f(eventCode, info){
        //sanitize and defaults
        //@TODO info deberia poder ser solo Object o String
        //@TODO eventCode deberia ser Number
        info = info || {};
        if (_.isString(info)) { info = {str: info} }        //estandarizacion de String a Object

        //compongo el codigo de evento
        var LEVEL_CODE;
        switch (level) {
            case 'debug': LEVEL_CODE = 1*10000000; break;
            case 'info': LEVEL_CODE = 2*10000000; break;
            case 'notice': LEVEL_CODE = 3*10000000; break;
            case 'warning': LEVEL_CODE = 4*10000000; break;
            case 'error': LEVEL_CODE = 5*10000000; break;
            case 'critical': LEVEL_CODE = 6*10000000; break;
            case 'alert': LEVEL_CODE = 7*10000000; break;
            case 'emergency': LEVEL_CODE = 8*10000000; break;
            default: break;
        }
        var LIBRARY_CODE = libraryId*10000;
        var FULL_CODE = LEVEL_CODE + LIBRARY_CODE + eventCode;

        //genero el cuerpo del mensaje del slug
        var MESSAGE;
        try {
            MESSAGE = handlebars.compile(lib[level][eventCode])(info);
        } catch (e) {
            MESSAGE = "=========EVENT CODE MALFORMED: " + level + "/" + eventCode + "==========";
        }

        //compongo el slug
        var SLUG = "[" + FULL_CODE + "] [" + MESSAGE + "]";

        //logueo un String (slug)
        console.log(SLUG);
        if (info && info.error) {
            console.log("====================STACK BEGINS===================");
            console.log(info.error.stack);
            console.log("====================STACK ENDS===================");
        }
    }
}

/*******************************************************************************
 * @description
 * Puesto que en entornos de desarrollo (development) solo se loguea un
 * mensaje que resume el evento (al contrario que en pre-produccion y en
 * produccion, donde se almacena como JSON toda la informacion del mismo),
 * en los casos en que el evento contenga un Object de tipo Error, ademas
 * del slug se loguea explicitamente el stack del Error, pues de otro modo se
 * pierde la informacion contenida en el mismo, vital para la depuracion
 * del mismo.
 *
 * @param {Object} lib:
 * @param {String} level:
 * @param {Number} libraryId:
 *
 * @return {Function}:
 */
function genuineLogger(level, lib, libraryId){
    libraryId = libraryId || 999;
    return f;

    function f(eventCode, info){
        //sanitize and defaults
        //@TODO info deberia poder ser solo Object o String
        //@TODO eventCode deberia ser Number
        info = info || {};
        if (_.isString(info)) { info = {str: info} }        //estandarizacion de String a Object

        //compongo el codigo de evento
        var LEVEL_CODE;
        switch (level) {
            case 'debug': LEVEL_CODE = 1*10000000; break;
            case 'info': LEVEL_CODE = 2*10000000; break;
            case 'notice': LEVEL_CODE = 3*10000000; break;
            case 'warning': LEVEL_CODE = 4*10000000; break;
            case 'error': LEVEL_CODE = 5*10000000; break;
            case 'critical': LEVEL_CODE = 6*10000000; break;
            case 'alert': LEVEL_CODE = 7*10000000; break;
            case 'emergency': LEVEL_CODE = 8*10000000; break;
            default: break;
        }
        var LIBRARY_CODE = libraryId*10000;
        var FULL_CODE = LEVEL_CODE + LIBRARY_CODE + eventCode;

        //Selecciono, esc, informacion pertinente de la request
        if (info && info.request) { info.request = siftRequest(info.request) }
        //genero el cuerpo del mensaje del slug
        var MESSAGE;
        try {
            MESSAGE = handlebars.compile(lib[level][eventCode])(info);
        } catch (e) {
            MESSAGE = "=========EVENT CODE MALFORMED: " + level + "/" + eventCode + "==========";
        }

        //compongo el slug
        var SLUG = "[" + FULL_CODE + "] [" + MESSAGE + "]";

        //segun el entorno, logueo un String (slug) o un Object (info)
        if (process.env.RACK_ENV === "development"){
            LOGENTRIES_CLIENT[level](SLUG);
            //@vid description
            if (info && info.error) {
                console.log("====================STACK BEGINS===================");
                console.log(info.error.stack);
                console.log("====================STACK ENDS===================");
            }
        } else {
            info.severity = level;
            info.library = libraryId;
            info.code = eventCode;
            info.fullCode = FULL_CODE;
            info.eventSlug = SLUG;
            //if (info && info.error) info.response = ERROR_CODES[info.error];
            LOGENTRIES_CLIENT[level](info);
        }
    }
}<|endoftext|>