<commit_before>/**
 * Copyright 2014 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

var assert = require('assert');
var fs = require('fs');
var gcloud = require('../');
var glob = require('glob');
var mitm = require('mitm');
var vm = require('vm');

var util = require('../lib/common/util.js');

function runCodeInSandbox(code, sandbox) {
  vm.createContext(sandbox);
  try {
    vm.runInNewContext(code, sandbox, {
      filename: 'assert-code.vm',
      timeout: 1000
    });
  } catch(err) {
    // rethrow the error with code for context and resolving issues faster.
    throw new Error('\n' + code + '\n\n' + err.message);
  }
}

describe('documentation', function() {
  var MITM;
  var FILES;

  before(function(done) {
    // Turn off the network so that API calls aren't actually made.
    MITM = mitm();
    glob('docs/json/master/**/*.json', function(err, files) {
      assert.ifError(err);
      FILES = files;
      done();
    });
  });

  after(function() {
    // Re-enable the network.
    MITM.disable();
  });

  it('should run docs examples without errors', function() {
    this.timeout(5000);

    FILES.forEach(function(filename) {
      var fileContents = fs.readFileSync(filename, {
        encoding: 'utf8'
      });
      var fileDocBlocks;

      try {
        fileDocBlocks = JSON.parse(fileContents);
      } catch(e) {
        throw new Error([
          'Failed to parse one of the doc files (' + e.message + ')',
          'Filename: ' + filename,
          'File contents: "' + fileContents + '"'
        ].join('\n'));
      }

      var mockConsole = Object.keys(console).reduce(function(console, method) {
        console[method] = util.noop;
        return console;
      }, {});

      // Set a global to indicate to any interested function inside of gcloud
      // that this is a sandbox environment.
      global.GCLOUD_SANDBOX_ENV = true;

      var sandbox = {
        gcloud: gcloud,
        require: require,
        process: process,
        console: mockConsole,
        Buffer: Buffer,
        Date: Date,
        Array: Array,
        global: global
      };

      fileDocBlocks.methods.forEach(function(method) {
        var examples = method.metadata.examples.map(function(example) {
          return example.code;
        });

        var code = examples
          .join('\n')
          .replace(/require\(\'gcloud\'\)/g, 'require(\'..\/\')')
          .replace(/require\(\'gcloud/g, 'require(\'..');

        assert.doesNotThrow(runCodeInSandbox.bind(null, code, sandbox));
      });

      delete global.GCLOUD_SANDBOX_ENV;
    });
  });
});
<commit_msg>tests: disable grpc requests from going off<commit_after>/**
 * Copyright 2014 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

var assert = require('assert');
var fs = require('fs');
var gcloud = require('../');
var glob = require('glob');
var mitm = require('mitm');
var vm = require('vm');

var util = require('../lib/common/util.js');

function runCodeInSandbox(code, sandbox) {
  vm.createContext(sandbox);
  try {
    vm.runInNewContext(code, sandbox, {
      filename: 'assert-code.vm',
      timeout: 1000
    });
  } catch(err) {
    // rethrow the error with code for context and resolving issues faster.
    throw new Error('\n' + code + '\n\n' + err.message);
  }
}

describe('documentation', function() {
  var MITM;
  var FILES;

  before(function(done) {
    // Set a global to indicate to any interested function inside of gcloud that
    // this is a sandbox environment.
    global.GCLOUD_SANDBOX_ENV = true;

    // Turn off the network so that API calls aren't actually made.
    MITM = mitm();

    glob('docs/json/master/**/*.json', function(err, files) {
      assert.ifError(err);
      FILES = files;
      done();
    });
  });

  after(function() {
    delete global.GCLOUD_SANDBOX_ENV;

    // Re-enable the network.
    MITM.disable();
  });

  it('should run docs examples without errors', function() {
    this.timeout(5000);

    FILES.forEach(function(filename) {
      var fileContents = fs.readFileSync(filename, {
        encoding: 'utf8'
      });
      var fileDocBlocks;

      try {
        fileDocBlocks = JSON.parse(fileContents);
      } catch(e) {
        throw new Error([
          'Failed to parse one of the doc files (' + e.message + ')',
          'Filename: ' + filename,
          'File contents: "' + fileContents + '"'
        ].join('\n'));
      }

      var mockConsole = Object.keys(console).reduce(function(console, method) {
        console[method] = util.noop;
        return console;
      }, {});

      var sandbox = {
        gcloud: gcloud,
        require: require,
        process: process,
        console: mockConsole,
        Buffer: Buffer,
        Date: Date,
        Array: Array,
        global: global
      };

      fileDocBlocks.methods.forEach(function(method) {
        var examples = method.metadata.examples.map(function(example) {
          return example.code;
        });

        var code = examples
          .join('\n')
          .replace(/require\(\'gcloud\'\)/g, 'require(\'..\/\')')
          .replace(/require\(\'gcloud/g, 'require(\'..');

        assert.doesNotThrow(runCodeInSandbox.bind(null, code, sandbox));
      });
    });
  });
});
<|endoftext|>


<commit_before>var assert = require("assert");
var fs = require("fs");
var path = require("path");
var api = require("../")(process.env.WEBSITE, process.env.USERNAME, process.env.PASSWORD);

describe("dump", function() {
    this.timeout(5000);

    it("can retrieve dump", function(done) {
        var dest = path.join(__dirname, "test.zip");
        if (fs.existsSync(dest)) {
            fs.unlinkSync(dest);
        }
        api.dump.download(dest, function() {
            assert(fs.existsSync(dest), "Downloaded dump file exists");
            done();
        });
    });
});
<commit_msg>Improve test for dump api<commit_after>var assert = require("assert");
var fs = require("fs");
var path = require("path");
var api = require("../")(process.env.WEBSITE, process.env.USERNAME, process.env.PASSWORD);

describe("dump", function() {
    this.timeout(30 * 1000);

    it("can retrieve dump", function(done) {
        var dest = path.join(__dirname, "test.zip");
        if (fs.existsSync(dest)) {
            fs.unlinkSync(dest);
        }
        api.dump.download(dest, function(err) {
            if (err) done(err);
            assert(fs.existsSync(dest), "Downloaded dump file exists");
            done();
        });
    });
});
<|endoftext|>


<commit_before>
var yauzl = require("../");

var paths = process.argv.slice(2);
paths.forEach(function(path) {
  yauzl.open(path, function(err, zipfile) {
    if (err) throw err;
    zipfile.on("error", function(err) {
      throw err;
    });
    zipfile.on("entry", function(entry) {
      console.log(entry);
      console.log(entry.getLastModDate());
      if (/\/$/.exec(entry)) return;
      zipfile.openReadStream(entry, function(err, readStream) {
        if (err) throw err;
        readStream.pipe(process.stdout);
      });
    });
  });
});

<commit_msg>test/dump.js supports --no-contents<commit_after>
var yauzl = require("../");

var paths = [];
var dumpContents = true;
process.argv.slice(2).forEach(function(arg) {
  if (arg === "--no-contents") {
    dumpContents = false;
  } else {
    paths.push(arg);
  }
});

paths.forEach(function(path) {
  yauzl.open(path, function(err, zipfile) {
    if (err) throw err;
    zipfile.on("error", function(err) {
      throw err;
    });
    zipfile.on("entry", function(entry) {
      console.log(entry);
      console.log(entry.getLastModDate());
      if (!dumpContents || /\/$/.exec(entry)) return;
      zipfile.openReadStream(entry, function(err, readStream) {
        if (err) throw err;
        readStream.pipe(process.stdout);
      });
    });
  });
});

<|endoftext|>


<commit_before>import '../src'
import bufferEqual from 'buffer-equal'
import convert from 'convert-source-map'
import gulp from 'gulp'
import timeout from 'timeout-then'
import rump from 'rump'
import {colors} from 'gulp-util'
import {readFile, writeFile} from 'mz/fs'
import {resolve, sep} from 'path'
import {spy} from 'sinon'

const protocol = process.platform === 'win32' ? 'file:///' : 'file://',
      {stripColor} = colors

describe('tasks', function() {
  this.timeout(0)

  beforeEach(() => {
    rump.configure({environment: 'development', paths: {
      source: {root: 'test/fixtures', styles: ''},
      destination: {root: 'tmp', styles: '', images: 'images'},
    }})
  })

  it('are added and defined', () => {
    const callback = spy()
    rump.on('gulp:main', callback)
    rump.on('gulp:styles', callback)
    rump.addGulpTasks({prefix: 'spec'})
    callback.should.be.calledTwice()
    gulp.tasks['spec:info:styles'].should.be.ok()
    gulp.tasks['spec:build:styles'].should.be.ok()
    gulp.tasks['spec:watch:styles'].should.be.ok()
  })

  it('displays correct information in info task', () => {
    const logs = [],
          {log} = console
    console.log = (...args) => logs.push(stripColor(args.join(' ')))
    gulp.start('spec:info')
    console.log = log
    logs.slice(-9).should.eql([
      '',
      '--- Styles v0.7.0',
      `Processed CSS files from test${sep}fixtures are copied with source maps to tmp`,
      'Affected files:',
      'index.css',
      'less.less',
      'sass.scss',
      'stylus.styl',
      '',
    ])
  })

  describe('for building', () => {
    let originals

    before(async() => {
      originals = await Promise.all([
        readFile('test/fixtures/index.css'),
        readFile('test/fixtures/lib/variables.css'),
        readFile('test/fixtures/less.less'),
        readFile('test/fixtures/lib/variables.less'),
        readFile('test/fixtures/sass.scss'),
        readFile('test/fixtures/lib/variables.scss'),
        readFile('test/fixtures/stylus.styl'),
        readFile('test/fixtures/lib/variables.styl'),
      ])
      await new Promise(resolve => {
        gulp.task('postbuild', ['spec:watch'], resolve)
        gulp.start('postbuild')
      })
    })

    beforeEach(() => timeout(1000))

    afterEach(async() => {
      await timeout(1000)
      await Promise.all([
        writeFile('test/fixtures/index.css', originals[0]),
        writeFile('test/fixtures/lib/variables.css', originals[1]),
        writeFile('test/fixtures/less.less', originals[2]),
        writeFile('test/fixtures/lib/variables.less', originals[3]),
        writeFile('test/fixtures/sass.scss', originals[4]),
        writeFile('test/fixtures/lib/variables.scss', originals[5]),
        writeFile('test/fixtures/stylus.styl', originals[6]),
        writeFile('test/fixtures/lib/variables.styl', originals[7]),
      ])
    })

    it('handles image paths for Sass', async() => {
      const content = await readFile('tmp/sass.css')
      content
        .toString()
        .should
        .containEql('background-image: url("images/sample.png")')
    })

    it('handles updates', async() => {
      const firstContents = await Promise.all([
        readFile('tmp/index.css'),
        readFile('tmp/less.css'),
        readFile('tmp/sass.css'),
        readFile('tmp/stylus.css'),
      ])
      let secondContents
      await timeout(1000)
      await Promise.all([
        writeFile('test/fixtures/lib/variables.css', ':root{--color:black}'),
        writeFile('test/fixtures/lib/variables.less', '@color: black;'),
        writeFile('test/fixtures/lib/variables.scss', '$color: black;'),
        writeFile('test/fixtures/lib/variables.styl', 'color = black'),
      ])
      await timeout(1000)
      secondContents = await Promise.all([
        readFile('tmp/index.css'),
        readFile('tmp/less.css'),
        readFile('tmp/sass.css'),
        readFile('tmp/stylus.css'),
      ])
      firstContents.forEach((firstContent, index) => {
        bufferEqual(firstContent, secondContents[index]).should.be.false()
      })
    })

    it('handles autoprefix', async() => {
      const contents = await Promise.all([
        readFile('tmp/index.css'),
        readFile('tmp/less.css'),
        readFile('tmp/sass.css'),
        readFile('tmp/stylus.css'),
      ])
      contents.map(content => {
        content.toString().should.containEql('display: flex')
        content.toString().should.containEql('display: -webkit-flex')
      })
    })

    it('handles source maps in development', async() => {
      const css = readFile('tmp/index.css'),
            less = readFile('tmp/less.css'),
            sass = readFile('tmp/sass.css'),
            stylus = readFile('tmp/stylus.css'),
            contents = await Promise.all([css, less, sass, stylus]),
            pathSet = contents
              .map(x => convert.fromSource(x.toString()))
              .map(x => x.getProperty('sources').sort()),
            paths = [].concat(...pathSet)
              .filter(x => x)
              .map(x => x.replace(protocol, '').split('/').join(sep))
      paths.should.eql([
        resolve('node_modules/normalize.css/normalize.css'),
        resolve('test/fixtures/index.css'),
        resolve('node_modules/bootstrap/less/buttons.less'),
        resolve('node_modules/bootstrap/less/mixins/buttons.less'),
        resolve('node_modules/bootstrap/less/mixins/opacity.less'),
        resolve('node_modules/bootstrap/less/mixins/tab-focus.less'),
        resolve('node_modules/bootstrap/less/mixins/vendor-prefixes.less'),
        resolve('node_modules/normalize.css/normalize.css'),
        resolve('test/fixtures/less.less'),
        resolve('node_modules/normalize-compass/normalize.scss'),
        resolve('test/fixtures/sass.scss'),
        resolve('node_modules/normalize.css/normalize.css'),
        resolve('test/fixtures/stylus.styl'),
      ])
    })

    it('handles minification in production', async() => {
      const firstContents = await Promise.all([
        readFile('tmp/index.css'),
        readFile('tmp/less.css'),
        readFile('tmp/sass.css'),
        readFile('tmp/stylus.css'),
      ])
      let secondContents
      rump.reconfigure({environment: 'production'})
      await timeout(1000)
      await Promise.all([
        writeFile('test/fixtures/lib/variables.css', ':root{--color:orange}'),
        writeFile('test/fixtures/lib/variables.less', '@color: orange;'),
        writeFile('test/fixtures/lib/variables.scss', '$color: orange;'),
        writeFile('test/fixtures/lib/variables.styl', 'color = orange'),
      ])
      await timeout(1000)
      secondContents = await Promise.all([
        readFile('tmp/index.css'),
        readFile('tmp/less.css'),
        readFile('tmp/sass.css'),
        readFile('tmp/stylus.css'),
      ])
      firstContents.forEach((firstContent, index) => {
        firstContent.length.should.be.above(secondContents[index].length)
      })
    })
  })
})
<commit_msg>Code cleanup<commit_after>import '../src'
import bufferEqual from 'buffer-equal'
import convert from 'convert-source-map'
import gulp from 'gulp'
import timeout from 'timeout-then'
import rump from 'rump'
import {colors} from 'gulp-util'
import {readFile, writeFile} from 'mz/fs'
import {resolve, sep} from 'path'
import {spy} from 'sinon'

const protocol = process.platform === 'win32' ? 'file:///' : 'file://',
      {stripColor} = colors

describe('tasks', function() {
  this.timeout(0)

  beforeEach(() => {
    rump.configure({environment: 'development', paths: {
      source: {root: 'test/fixtures', styles: ''},
      destination: {root: 'tmp', styles: '', images: 'images'},
    }})
  })

  it('are added and defined', () => {
    const callback = spy()
    rump.on('gulp:main', callback)
    rump.on('gulp:styles', callback)
    rump.addGulpTasks({prefix: 'spec'})
    callback.should.be.calledTwice()
    gulp.tasks['spec:info:styles'].should.be.ok()
    gulp.tasks['spec:build:styles'].should.be.ok()
    gulp.tasks['spec:watch:styles'].should.be.ok()
  })

  it('displays correct information in info task', () => {
    const logs = [],
          {log} = console
    console.log = (...args) => logs.push(stripColor(args.join(' ')))
    gulp.start('spec:info')
    console.log = log
    logs.slice(-9).should.eql([
      '',
      '--- Styles v0.7.0',
      `Processed CSS files from test${sep}fixtures are copied with source maps to tmp`,
      'Affected files:',
      'index.css',
      'less.less',
      'sass.scss',
      'stylus.styl',
      '',
    ])
  })

  describe('for building', () => {
    let originals

    before(async() => {
      originals = await Promise.all([
        readFile('test/fixtures/index.css'),
        readFile('test/fixtures/lib/variables.css'),
        readFile('test/fixtures/less.less'),
        readFile('test/fixtures/lib/variables.less'),
        readFile('test/fixtures/sass.scss'),
        readFile('test/fixtures/lib/variables.scss'),
        readFile('test/fixtures/stylus.styl'),
        readFile('test/fixtures/lib/variables.styl'),
      ])
      await new Promise(resolve => {
        gulp.task('postbuild', ['spec:watch'], resolve)
        gulp.start('postbuild')
      })
    })

    beforeEach(() => timeout(1000))

    afterEach(() => Promise.all([
      writeFile('test/fixtures/index.css', originals[0]),
      writeFile('test/fixtures/lib/variables.css', originals[1]),
      writeFile('test/fixtures/less.less', originals[2]),
      writeFile('test/fixtures/lib/variables.less', originals[3]),
      writeFile('test/fixtures/sass.scss', originals[4]),
      writeFile('test/fixtures/lib/variables.scss', originals[5]),
      writeFile('test/fixtures/stylus.styl', originals[6]),
      writeFile('test/fixtures/lib/variables.styl', originals[7]),
    ]))

    it('handles image paths for Sass', async() => {
      const content = await readFile('tmp/sass.css')
      content
        .toString()
        .should
        .containEql('background-image: url("images/sample.png")')
    })

    it('handles updates', async() => {
      const firstContents = await Promise.all([
        readFile('tmp/index.css'),
        readFile('tmp/less.css'),
        readFile('tmp/sass.css'),
        readFile('tmp/stylus.css'),
      ])
      let secondContents
      await timeout(1000)
      await Promise.all([
        writeFile('test/fixtures/lib/variables.css', ':root{--color:black}'),
        writeFile('test/fixtures/lib/variables.less', '@color: black;'),
        writeFile('test/fixtures/lib/variables.scss', '$color: black;'),
        writeFile('test/fixtures/lib/variables.styl', 'color = black'),
      ])
      await timeout(1000)
      secondContents = await Promise.all([
        readFile('tmp/index.css'),
        readFile('tmp/less.css'),
        readFile('tmp/sass.css'),
        readFile('tmp/stylus.css'),
      ])
      firstContents.forEach((firstContent, index) => {
        bufferEqual(firstContent, secondContents[index]).should.be.false()
      })
    })

    it('handles autoprefix', async() => {
      const contents = await Promise.all([
        readFile('tmp/index.css'),
        readFile('tmp/less.css'),
        readFile('tmp/sass.css'),
        readFile('tmp/stylus.css'),
      ])
      contents.map(content => {
        content.toString().should.containEql('display: flex')
        content.toString().should.containEql('display: -webkit-flex')
      })
    })

    it('handles source maps in development', async() => {
      const css = readFile('tmp/index.css'),
            less = readFile('tmp/less.css'),
            sass = readFile('tmp/sass.css'),
            stylus = readFile('tmp/stylus.css'),
            contents = await Promise.all([css, less, sass, stylus]),
            pathSet = contents
              .map(x => convert.fromSource(x.toString()))
              .map(x => x.getProperty('sources').sort()),
            paths = [].concat(...pathSet)
              .filter(x => x)
              .map(x => x.replace(protocol, '').split('/').join(sep))
      paths.should.eql([
        resolve('node_modules/normalize.css/normalize.css'),
        resolve('test/fixtures/index.css'),
        resolve('node_modules/bootstrap/less/buttons.less'),
        resolve('node_modules/bootstrap/less/mixins/buttons.less'),
        resolve('node_modules/bootstrap/less/mixins/opacity.less'),
        resolve('node_modules/bootstrap/less/mixins/tab-focus.less'),
        resolve('node_modules/bootstrap/less/mixins/vendor-prefixes.less'),
        resolve('node_modules/normalize.css/normalize.css'),
        resolve('test/fixtures/less.less'),
        resolve('node_modules/normalize-compass/normalize.scss'),
        resolve('test/fixtures/sass.scss'),
        resolve('node_modules/normalize.css/normalize.css'),
        resolve('test/fixtures/stylus.styl'),
      ])
    })

    it('handles minification in production', async() => {
      const firstContents = await Promise.all([
        readFile('tmp/index.css'),
        readFile('tmp/less.css'),
        readFile('tmp/sass.css'),
        readFile('tmp/stylus.css'),
      ])
      let secondContents
      rump.reconfigure({environment: 'production'})
      await timeout(1000)
      await Promise.all([
        writeFile('test/fixtures/lib/variables.css', ':root{--color:orange}'),
        writeFile('test/fixtures/lib/variables.less', '@color: orange;'),
        writeFile('test/fixtures/lib/variables.scss', '$color: orange;'),
        writeFile('test/fixtures/lib/variables.styl', 'color = orange'),
      ])
      await timeout(1000)
      secondContents = await Promise.all([
        readFile('tmp/index.css'),
        readFile('tmp/less.css'),
        readFile('tmp/sass.css'),
        readFile('tmp/stylus.css'),
      ])
      firstContents.forEach((firstContent, index) => {
        firstContent.length.should.be.above(secondContents[index].length)
      })
    })
  })
})
<|endoftext|>


<commit_before>
// import module
var hdf5 = require('../build/Release/hdf5');

// instantiate h5file
var h5file = new hdf5.H5File('/home/ryan/data/MillionSongSubset/data/A/A/A/TRAAAAW128F429D538.h5');

console.log(h5file.filename());
console.log(h5file.filesize());

// close the file
h5file.close();<commit_msg>output file object<commit_after>
// import module
var hdf5 = require('../build/Release/hdf5');

// instantiate h5file
var h5file = new hdf5.H5File('/home/ryan/data/MillionSongSubset/data/A/A/A/TRAAAAW128F429D538.h5');

console.log(h5file);
console.log(h5file.filename());
console.log(h5file.filesize());

// close the file
h5file.close();<|endoftext|>


<commit_before>module( "load", { teardown: moduleTeardown } );

asyncTest( "jar.load - js", function() {
    var path = "//" + window.location.host + window.location.pathname + "data/data.js";

    jar( "jar.load - js" ).done(function() {
        this.clear().done(function() {

            // through xhr-request
            jar.load( path, "js", "jar.load - js" ).done(function( data, base ) {
                ok( data.length, "Data is returned" );
                ok( js, "Variable is assigned" );
                ok( base instanceof jar, "Second argument is instace of jar" );

                // cleanup
                window.js = undefined;

                // wait a bit, so data can be writed
                window.setTimeout(function() {
                    ok( jar.has( "jar.load - js", path ), "Meta-data should be intializated" );

                    // through jar-store
                    jar.load( path, "js", "jar.load - js" ).done(function( data, base ) {
                        ok( data.length, "Data is returned" );
                        ok( js, "Variable is assigned" );
                        ok( base instanceof jar, "Second argument is instace of jar" );

                        // cleanup
                        window.js = undefined;

                        start();
                    });
                }, 100 );
            });
        });
    });
});

asyncTest( "jar.load - xml", function() {
    var path = "//" + window.location.host + window.location.pathname + "data/data.xml";

    jar( "jar.load - xml" ).done(function() {
        this.clear().done(function() {

            // through xhr-request
            jar.load( path, "xml", "jar.load - xml" ).done(function( data, base ) {
                strictEqual( jar.type( data ), "xml", "Data is returned" );
                ok( base instanceof jar, "Second argument is instace of jar" );

                // wait a bit, so data can be writed
                window.setTimeout(function() {
                    ok( jar.has( "jar.load - xml", path ), "Meta-data should be intializated" );

                    // through jar-store
                    jar.load( path, "xml", "jar.load - xml" ).done(function( data, base ) {
                        strictEqual( jar.type( data ), "xml", "Data is returned" );
                        ok( base instanceof jar, "Second argument is instace of jar" );

                        start();
                    });
                }, 100 );
            });
        });
    });
});

asyncTest( "jar.load - css", function() {
    var path = "//" + window.location.host + window.location.pathname + "data/data.css";

    jar( "jar.load - css" ).done(function() {
        this.clear().done(function() {

            // through xhr-request
            jar.load( path, "css", "jar.load - css" ).done(function( data, base ) {
                var element = jQuery( '

' ).appendTo( "#qunit-fixture" );
                strictEqual( element.css( "font-size" ), "99px", "css style should be applied" );

                ok( base instanceof jar, "Second argument is instace of jar" );

                // wait a bit, so data can be writed
                window.setTimeout(function() {
                    ok( jar.has( "jar.load - css", path ), "Meta-data should be intializated" );

                    // through jar-store
                    jar.load( path, "css", "jar.load - css" ).done(function( data, base ) {
                        ok( base instanceof jar, "Second argument is instace of jar" );

                        start();
                    });
                }, 100 );
            });
        });
    });
});<commit_msg>Fix typo<commit_after>module( "load", { teardown: moduleTeardown } );

asyncTest( "jar.load - js", function() {
    var path = "//" + window.location.host + window.location.pathname + "data/data.js";

    jar( "jar.load - js" ).done(function() {
        this.clear().done(function() {

            // through xhr-request
            jar.load( path, "js", "jar.load - js" ).done(function( data, base ) {
                ok( data.length, "Data is returned" );
                ok( js, "Variable is assigned" );
                ok( base instanceof jar, "Second argument is instance of jar" );

                // cleanup
                window.js = undefined;

                // wait a bit, so data can be writed
                window.setTimeout(function() {
                    ok( jar.has( "jar.load - js", path ), "Meta-data should be intializated" );

                    // through jar-store
                    jar.load( path, "js", "jar.load - js" ).done(function( data, base ) {
                        ok( data.length, "Data is returned" );
                        ok( js, "Variable is assigned" );
                        ok( base instanceof jar, "Second argument is instance of jar" );

                        // cleanup
                        window.js = undefined;

                        start();
                    });
                }, 100 );
            });
        });
    });
});

asyncTest( "jar.load - xml", function() {
    var path = "//" + window.location.host + window.location.pathname + "data/data.xml";

    jar( "jar.load - xml" ).done(function() {
        this.clear().done(function() {

            // through xhr-request
            jar.load( path, "xml", "jar.load - xml" ).done(function( data, base ) {
                strictEqual( jar.type( data ), "xml", "Data is returned" );
                ok( base instanceof jar, "Second argument is instance of jar" );

                // wait a bit, so data can be writed
                window.setTimeout(function() {
                    ok( jar.has( "jar.load - xml", path ), "Meta-data should be intializated" );

                    // through jar-store
                    jar.load( path, "xml", "jar.load - xml" ).done(function( data, base ) {
                        strictEqual( jar.type( data ), "xml", "Data is returned" );
                        ok( base instanceof jar, "Second argument is instance of jar" );

                        start();
                    });
                }, 100 );
            });
        });
    });
});

asyncTest( "jar.load - css", function() {
    var path = "//" + window.location.host + window.location.pathname + "data/data.css";

    jar( "jar.load - css" ).done(function() {
        this.clear().done(function() {

            // through xhr-request
            jar.load( path, "css", "jar.load - css" ).done(function( data, base ) {
                var element = jQuery( '

' ).appendTo( "#qunit-fixture" );
                strictEqual( element.css( "font-size" ), "99px", "css style should be applied" );

                ok( base instanceof jar, "Second argument is instance of jar" );

                // wait a bit, so data can be writed
                window.setTimeout(function() {
                    ok( jar.has( "jar.load - css", path ), "Meta-data should be intializated" );

                    // through jar-store
                    jar.load( path, "css", "jar.load - css" ).done(function( data, base ) {
                        ok( base instanceof jar, "Second argument is instance of jar" );

                        start();
                    });
                }, 100 );
            });
        });
    });
});<|endoftext|>


<commit_before>import browserslist from '../';

import test from 'ava';
import path from 'path';

const css   = path.join(__dirname, 'fixtures', 'dir', 'test.css');
const ies   = path.join(__dirname, 'fixtures', 'explorers');
const link  = path.join(__dirname, 'fixtures', 'symlink');

test.afterEach(() => {
    delete process.env.BROWSERSLIST;
    delete process.env.BROWSERSLIST_CONFIG;
});

test('accepts array', t => {
    t.deepEqual(browserslist(['ie 11', 'ie 10']), ['ie 11', 'ie 10']);
});

test('accepts string', t => {
    t.deepEqual(browserslist('ie 11, ie 10'), ['ie 11', 'ie 10']);
});

test('returns unique array', t => {
    t.deepEqual(browserslist('ie 10, ie 10'), ['ie 10']);
});

test('returns empty result', t => {
    t.deepEqual(browserslist([]), []);
    t.deepEqual(browserslist(''), []);
});

test.serial('uses environment variable on empty request', t => {
    process.env.BROWSERSLIST = 'ie 10';
    t.deepEqual(browserslist(null, { path: css }), ['ie 10']);
});

test('reads config on no variable', t => {
    t.deepEqual(browserslist(null, { path: css }), ['ie 11', 'ie 10']);
});

test('reads config by direct path', t => {
    t.deepEqual(browserslist(null, { config: ies }), ['ie 9', 'ie 8']);
});

test.serial('reads config by direct path in environment variable', t => {
    process.env.BROWSERSLIST_CONFIG = ies;
    t.deepEqual(browserslist(null, { path: css }), ['ie 9', 'ie 8']);
});

test('throw a error on wrong path to config', t => {
    t.throws(() => {
        browserslist(null, { config: ies + '2' });
    }, /Can't read/);
});

test('reads config by symlink', t => {
    t.deepEqual(browserslist(null, { config: link }), ['ie 9', 'ie 8']);
});

test('has default selection', t => {
    t.truthy(browserslist.defaults.length > 0);
});

test('uses default selection on empty request and no config', t => {
    t.deepEqual(browserslist(), browserslist(browserslist.defaults));
});

test('raises on unknow query', t => {
    t.throws(() => {
        browserslist('good');
    }, 'Unknown browser query `good`');
});

test('sorts browsers', t => {
    t.deepEqual(browserslist(['ff 10', 'ie 11', 'ie 6', 'ie 10', 'ff 9']),
                ['firefox 10', 'firefox 9', 'ie 11', 'ie 10', 'ie 6']);
});

test('has actual example in README.md', t => {
    t.deepEqual(browserslist('last 1 version, > 10%'),
        ['and_chr 50', 'chrome 51', 'chrome 50', 'edge 13', 'firefox 47',
         'ie 11', 'ie_mob 11', 'ios_saf 9.3', 'opera 38', 'safari 9.1']);
});

test('throws custom error', t => {
    let error;
    try {
        browserslist('wrong');
    } catch (e) {
        error = e;
    }
    t.deepEqual(error.name, 'BrowserslistError');
    t.deepEqual(typeof error.stack, 'string');
});

test('excludes queries', t => {
    t.deepEqual(browserslist(['ie >= 9', 'not ie 11', 'not ie 10', 'ie 10']),
                ['ie 10', 'ie 9']);
});

test('clean 0 version', t => {
    t.false(browserslist(['> 0%', '> 0% in FI']).includes('and_chr 0'));
});
<commit_msg>Fix node.js <6 support<commit_after>import browserslist from '../';

import test from 'ava';
import path from 'path';

const css   = path.join(__dirname, 'fixtures', 'dir', 'test.css');
const ies   = path.join(__dirname, 'fixtures', 'explorers');
const link  = path.join(__dirname, 'fixtures', 'symlink');

test.afterEach(() => {
    delete process.env.BROWSERSLIST;
    delete process.env.BROWSERSLIST_CONFIG;
});

test('accepts array', t => {
    t.deepEqual(browserslist(['ie 11', 'ie 10']), ['ie 11', 'ie 10']);
});

test('accepts string', t => {
    t.deepEqual(browserslist('ie 11, ie 10'), ['ie 11', 'ie 10']);
});

test('returns unique array', t => {
    t.deepEqual(browserslist('ie 10, ie 10'), ['ie 10']);
});

test('returns empty result', t => {
    t.deepEqual(browserslist([]), []);
    t.deepEqual(browserslist(''), []);
});

test.serial('uses environment variable on empty request', t => {
    process.env.BROWSERSLIST = 'ie 10';
    t.deepEqual(browserslist(null, { path: css }), ['ie 10']);
});

test('reads config on no variable', t => {
    t.deepEqual(browserslist(null, { path: css }), ['ie 11', 'ie 10']);
});

test('reads config by direct path', t => {
    t.deepEqual(browserslist(null, { config: ies }), ['ie 9', 'ie 8']);
});

test.serial('reads config by direct path in environment variable', t => {
    process.env.BROWSERSLIST_CONFIG = ies;
    t.deepEqual(browserslist(null, { path: css }), ['ie 9', 'ie 8']);
});

test('throw a error on wrong path to config', t => {
    t.throws(() => {
        browserslist(null, { config: ies + '2' });
    }, /Can't read/);
});

test('reads config by symlink', t => {
    t.deepEqual(browserslist(null, { config: link }), ['ie 9', 'ie 8']);
});

test('has default selection', t => {
    t.truthy(browserslist.defaults.length > 0);
});

test('uses default selection on empty request and no config', t => {
    t.deepEqual(browserslist(), browserslist(browserslist.defaults));
});

test('raises on unknow query', t => {
    t.throws(() => {
        browserslist('good');
    }, 'Unknown browser query `good`');
});

test('sorts browsers', t => {
    t.deepEqual(browserslist(['ff 10', 'ie 11', 'ie 6', 'ie 10', 'ff 9']),
                ['firefox 10', 'firefox 9', 'ie 11', 'ie 10', 'ie 6']);
});

test('has actual example in README.md', t => {
    t.deepEqual(browserslist('last 1 version, > 10%'),
        ['and_chr 50', 'chrome 51', 'chrome 50', 'edge 13', 'firefox 47',
         'ie 11', 'ie_mob 11', 'ios_saf 9.3', 'opera 38', 'safari 9.1']);
});

test('throws custom error', t => {
    let error;
    try {
        browserslist('wrong');
    } catch (e) {
        error = e;
    }
    t.deepEqual(error.name, 'BrowserslistError');
    t.deepEqual(typeof error.stack, 'string');
});

test('excludes queries', t => {
    t.deepEqual(browserslist(['ie >= 9', 'not ie 11', 'not ie 10', 'ie 10']),
                ['ie 10', 'ie 9']);
});

test('clean 0 version', t => {
    t.deepEqual(browserslist(['> 0%', '> 0% in FI']).indexOf('and_chr 0'), -1);
});
<|endoftext|>


<commit_before>/*eslint-disable */

'use strict';

var should = require('should'),
    fs = require('fs'),
    path = require('path'),
    getRemoteContent = require('../index');

function compare(remotePath, fixturePath, done) {
    getRemoteContent(remotePath, function (err, css) {
        css.should.be.equal(String(fs.readFileSync(fixturePath)));

        done();
    });
}

describe('remote-content', function() {
    this.timeout(5000);

    it('Should get remote content from link tags in an HTML document', function(done) {
        compare('https://raw.githubusercontent.com/jonkemp/remote-content/master/test/fixtures/file.css', path.join('test', 'fixtures', 'file.css'), done);
    });
});
<commit_msg>Increase timeout.<commit_after>/*eslint-disable */

'use strict';

var should = require('should'),
    fs = require('fs'),
    path = require('path'),
    getRemoteContent = require('../index');

function compare(remotePath, fixturePath, done) {
    getRemoteContent(remotePath, function (err, css) {
        css.should.be.equal(String(fs.readFileSync(fixturePath)));

        done();
    });
}

describe('remote-content', function() {
    this.timeout(15000);

    it('Should get remote content from link tags in an HTML document', function(done) {
        compare('https://raw.githubusercontent.com/jonkemp/remote-content/master/test/fixtures/file.css', path.join('test', 'fixtures', 'file.css'), done);
    });
});
<|endoftext|>


<commit_before>// test/main.js
var satelize = require('satelize');
var assert = require("assert");

describe('service calls', function() {
    describe('with ip arguments', function() {
        it('return Netherlands nice country', function(done) {
        	satelize.satelize({JSONP: false, ip:'46.19.37.108'}, function(err, geoData) {
    			if (err) console.log(err);

    			var d = JSON.parse(geoData);

                console.log(d);

    			assert.equal(d.country, 'Netherlands');
    			assert.notEqual(d.country, 'France');

    			done();
  			});
        });
    });
});<commit_msg>folders as modules compliant mocha test require<commit_after>// test/main.js
var satelize = require('../lib/satelize');
var assert = require("assert");

describe('service calls', function() {
    describe('with ip arguments', function() {
        it('return Netherlands nice country', function(done) {
        	satelize.satelize({JSONP: false, ip:'46.19.37.108'}, function(err, geoData) {
    			if (err) console.log(err);

    			var d = JSON.parse(geoData);

                console.log(d);

    			assert.equal(d.country, 'Netherlands');
    			assert.notEqual(d.country, 'France');

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


<commit_before>var fs = require('fs');
var path = require('path');
var assert = require('assert');

var page = require('../lib/page');

var CONTENT = fs.readFileSync(path.join(__dirname, './fixtures/PAGE.md'), 'utf8');
var LEXED = page(CONTENT);

describe('Page parsing', function() {
    it('should detection sections', function() {
        assert.equal(LEXED.length, 3);
    });

    it('should detection section types', function() {
        assert.equal(LEXED[0].type, 'normal');
        assert.equal(LEXED[1].type, 'exercise');
        assert.equal(LEXED[2].type, 'normal');
    });
});
<commit_msg>Add tests for page content rendering<commit_after>var fs = require('fs');
var path = require('path');
var assert = require('assert');

var page = require('../lib/page');

var CONTENT = fs.readFileSync(path.join(__dirname, './fixtures/PAGE.md'), 'utf8');
var LEXED = page(CONTENT);

describe('Page parsing', function() {
    it('should detection sections', function() {
        assert.equal(LEXED.length, 3);
    });

    it('should detection section types', function() {
        assert.equal(LEXED[0].type, 'normal');
        assert.equal(LEXED[1].type, 'exercise');
        assert.equal(LEXED[2].type, 'normal');
    });

    it('should gen content for normal sections', function() {
        assert(LEXED[0].content);
        assert(!LEXED[1].content);
        assert(LEXED[2].content);
    });
});
<|endoftext|>


<commit_before>var mock = require('./mock');
var Output = require('../lib/output/base');

describe('Page', function() {
    var book, output;

    before(function() {
        return mock.setupDefaultBook({
            'heading.md': '# Hello\n\n## World',
            'links.md': '[link](hello.md) [readme](README.md)',

            'codes/simple.md': '```hello world```',
            'codes/lang.md': '```js\nhello world\n```',
            'codes/lang.adoc': '```js\nhello world\n```',

            'folder/paths.md': '',

            'variables/file/mtime.md': '{{ file.mtime }}',
            'variables/file/path.md': '{{ file.path }}',
            'variables/page/title.md': '{{ page.title }}',
            'variables/page/previous.md': '{{ page.previous.title }} {{ page.previous.path }}',
            'variables/page/next.md': '{{ page.next.title }} {{ page.next.path }}'
        }, [
            {
                title: 'Test page.next',
                path: 'variables/page/next.md'
            },
            {
                title: 'Test Variables',
                path: 'variables/page/title.md'
            },
            {
                title: 'Test page.previous',
                path: 'variables/page/previous.md'
            }
        ])
        .then(function(_book) {
            book = _book;
            output = new Output(book);

            return book.parse();
        });
    });

    describe('.resolveLocal', function() {
        it('should correctly resolve path to file', function() {
            var page = book.addPage('heading.md');

            page.resolveLocal('test.png').should.equal('test.png');
            page.resolveLocal('/test.png').should.equal('test.png');
            page.resolveLocal('test/hello.png').should.equal('test/hello.png');
            page.resolveLocal('/test/hello.png').should.equal('test/hello.png');
        });

        it('should correctly resolve path to file (2)', function() {
            var page = book.addPage('folder/paths.md');

            page.resolveLocal('test.png').should.equal('folder/test.png');
            page.resolveLocal('/test.png').should.equal('test.png');
            page.resolveLocal('test/hello.png').should.equal('folder/test/hello.png');
            page.resolveLocal('/test/hello.png').should.equal('test/hello.png');
        });
    });

    describe('.relative', function() {
        it('should correctly resolve absolute path in the book', function() {
            var page = book.addPage('heading.md');
            var page2 = book.addPage('folder/paths.md');

            page.relative('/test.png').should.equal('test.png');
            page.relative('test.png').should.equal('test.png');
            page2.relative('/test.png').should.equal('../test.png');
            page2.relative('test.png').should.equal('test.png');
        });
    });

    describe('Headings', function() {
        it('should add a default ID to headings', function() {
            var page = book.addPage('heading.md');

            return page.toHTML(output)
            .then(function() {
                page.content.should.be.html({
                    'h1#hello': {
                        count: 1
                    },
                    'h2#world': {
                        count: 1
                    }
                });
            });
        });
    });

    describe('Code Blocks', function() {
        var page;

        before(function() {
            output.template.addBlock('code', function(blk) {
                return (blk.kwargs.language || '') + blk.body + 'test';
            });
        });

        it('should apply "code" block', function() {
            page = book.addPage('codes/simple.md');
            return page.toHTML(output)
                .should.be.fulfilledWith('
hello worldtest
\n');
        });

        it('should add language as kwargs', function() {
            page = book.addPage('codes/lang.md');
            return page.toHTML(output)
                .should.be.fulfilledWith('
jshello world\ntest
\n');
        });

        it('should add language as kwargs (asciidoc)', function() {
            page = book.addPage('codes/lang.adoc');
            return page.toHTML(output)
                .should.be.fulfilledWith('
\n
\n
jshello worldtest
\n
\n
');
        });
    });

    describe('Links', function() {
        var page;

        before(function() {
            page = book.addPage('links.md');
            return page.toHTML(output);
        });

        it('should replace links to page to .html', function() {
            page.content.should.be.html({
                'a[href="index.html"]': {
                    count: 1
                }
            });
        });

        it('should not replace links to file not in SUMMARY', function() {
            page.content.should.be.html({
                'a[href="hello.md"]': {
                    count: 1
                }
            });
        });
    });

    describe('Templating Context', function() {
        it('should set file.mtime', function() {
            var page = book.addPage('variables/file/mtime.md');
            return page.toHTML(output)
            .then(function(content) {
                content.should.endWith('(CET)
\n');
            });
        });

        it('should set file.path', function() {
            var page = book.addPage('variables/file/path.md');
            return page.toHTML(output)
            .should.be.fulfilledWith('
variables/file/path.md
\n');
        });

        it('should set page.title when page is in summary', function() {
            var page = book.getPage('variables/page/title.md');
            return page.toHTML(output)
            .should.be.fulfilledWith('
Test Variables
\n');
        });

        it('should set page.previous when possible', function() {
            var page = book.getPage('variables/page/previous.md');
            return page.toHTML(output)
            .should.be.fulfilledWith('
Test Variables variables/page/title.md
\n');
        });

        it('should set page.next when possible', function() {
            var page = book.getPage('variables/page/next.md');
            return page.toHTML(output)
            .should.be.fulfilledWith('
Test Variables variables/page/title.md
\n');
        });
    });
});
<commit_msg>Fix and improve tests for links in page<commit_after>var mock = require('./mock');
var Output = require('../lib/output/base');

describe('Page', function() {
    var book, output;

    before(function() {
        return mock.setupDefaultBook({
            'heading.md': '# Hello\n\n## World',
            'links.md': '[link](hello.md) [link 2](variables/page/next.md) [readme](README.md)',

            'codes/simple.md': '```hello world```',
            'codes/lang.md': '```js\nhello world\n```',
            'codes/lang.adoc': '```js\nhello world\n```',

            'folder/paths.md': '',

            'variables/file/mtime.md': '{{ file.mtime }}',
            'variables/file/path.md': '{{ file.path }}',
            'variables/page/title.md': '{{ page.title }}',
            'variables/page/previous.md': '{{ page.previous.title }} {{ page.previous.path }}',
            'variables/page/next.md': '{{ page.next.title }} {{ page.next.path }}'
        }, [
            {
                title: 'Test page.next',
                path: 'variables/page/next.md'
            },
            {
                title: 'Test Variables',
                path: 'variables/page/title.md'
            },
            {
                title: 'Test page.previous',
                path: 'variables/page/previous.md'
            }
        ])
        .then(function(_book) {
            book = _book;
            output = new Output(book);

            return book.parse();
        });
    });

    describe('.resolveLocal', function() {
        it('should correctly resolve path to file', function() {
            var page = book.addPage('heading.md');

            page.resolveLocal('test.png').should.equal('test.png');
            page.resolveLocal('/test.png').should.equal('test.png');
            page.resolveLocal('test/hello.png').should.equal('test/hello.png');
            page.resolveLocal('/test/hello.png').should.equal('test/hello.png');
        });

        it('should correctly resolve path to file (2)', function() {
            var page = book.addPage('folder/paths.md');

            page.resolveLocal('test.png').should.equal('folder/test.png');
            page.resolveLocal('/test.png').should.equal('test.png');
            page.resolveLocal('test/hello.png').should.equal('folder/test/hello.png');
            page.resolveLocal('/test/hello.png').should.equal('test/hello.png');
        });
    });

    describe('.relative', function() {
        it('should correctly resolve absolute path in the book', function() {
            var page = book.addPage('heading.md');
            var page2 = book.addPage('folder/paths.md');

            page.relative('/test.png').should.equal('test.png');
            page.relative('test.png').should.equal('test.png');
            page2.relative('/test.png').should.equal('../test.png');
            page2.relative('test.png').should.equal('test.png');
        });
    });

    describe('Headings', function() {
        it('should add a default ID to headings', function() {
            var page = book.addPage('heading.md');

            return page.toHTML(output)
            .then(function() {
                page.content.should.be.html({
                    'h1#hello': {
                        count: 1
                    },
                    'h2#world': {
                        count: 1
                    }
                });
            });
        });
    });

    describe('Code Blocks', function() {
        var page;

        before(function() {
            output.template.addBlock('code', function(blk) {
                return (blk.kwargs.language || '') + blk.body + 'test';
            });
        });

        it('should apply "code" block', function() {
            page = book.addPage('codes/simple.md');
            return page.toHTML(output)
                .should.be.fulfilledWith('
hello worldtest
\n');
        });

        it('should add language as kwargs', function() {
            page = book.addPage('codes/lang.md');
            return page.toHTML(output)
                .should.be.fulfilledWith('
jshello world\ntest
\n');
        });

        it('should add language as kwargs (asciidoc)', function() {
            page = book.addPage('codes/lang.adoc');
            return page.toHTML(output)
                .should.be.fulfilledWith('
\n
\n
jshello worldtest
\n
\n
');
        });
    });

    describe('Links', function() {
        var page;

        before(function() {
            page = book.addPage('links.md');
            return page.toHTML(output);
        });

        it('should replace links to page to .html', function() {
            page.content.should.be.html({
                'a[href="./"]': {
                    count: 1
                }
            });
        });

        it('should use directory urls when file is a README', function() {
            page.content.should.be.html({
                'a[href="./"]': {
                    count: 1
                }
            });
        });

        it('should not replace links to file not in SUMMARY', function() {
            page.content.should.be.html({
                'a[href="hello.md"]': {
                    count: 1
                }
            });
        });
    });

    describe('Templating Context', function() {
        it('should set file.mtime', function() {
            var page = book.addPage('variables/file/mtime.md');
            return page.toHTML(output)
            .then(function(content) {
                content.should.endWith('(CET)
\n');
            });
        });

        it('should set file.path', function() {
            var page = book.addPage('variables/file/path.md');
            return page.toHTML(output)
            .should.be.fulfilledWith('
variables/file/path.md
\n');
        });

        it('should set page.title when page is in summary', function() {
            var page = book.getPage('variables/page/title.md');
            return page.toHTML(output)
            .should.be.fulfilledWith('
Test Variables
\n');
        });

        it('should set page.previous when possible', function() {
            var page = book.getPage('variables/page/previous.md');
            return page.toHTML(output)
            .should.be.fulfilledWith('
Test Variables variables/page/title.md
\n');
        });

        it('should set page.next when possible', function() {
            var page = book.getPage('variables/page/next.md');
            return page.toHTML(output)
            .should.be.fulfilledWith('
Test Variables variables/page/title.md
\n');
        });
    });
});
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var assert = require('assert');

var kramed = require('kramed');

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

var CONTENT = fs.readFileSync(path.join(__dirname, './fixtures/PAGE.md'), 'utf8');
var RENDERED = render(CONTENT);

function render(content) {
    var lexed = kramed.lexer(CONTENT);

    // Options to parser
    var options = Object.create(kramed.defaults);
    options.renderer = renderer();

    return kramed.parser(lexed, options);
}

describe('Markdown renderer', function() {
    it('should strip all html tags', function() {
        assert.equal(RENDERED.indexOf('</'), -1);
        console.log(RENDERED);
    });
    it('should produce the same html output as the original', function() {
        assert.equal(
            kramed(RENDERED),
            kramed(CONTENT)
        );
    });
});
<commit_msg>Remove console.log from test<commit_after>var fs = require('fs');
var path = require('path');
var assert = require('assert');

var kramed = require('kramed');

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

var CONTENT = fs.readFileSync(path.join(__dirname, './fixtures/PAGE.md'), 'utf8');
var RENDERED = render(CONTENT);

function render(content) {
    var lexed = kramed.lexer(CONTENT);

    // Options to parser
    var options = Object.create(kramed.defaults);
    options.renderer = renderer();

    return kramed.parser(lexed, options);
}

describe('Markdown renderer', function() {
    it('should strip all html tags', function() {
        assert.equal(RENDERED.indexOf('</'), -1);
    });
    it('should produce the same html output as the original', function() {
        assert.equal(
            kramed(RENDERED),
            kramed(CONTENT)
        );
    });
});
<|endoftext|>


<commit_before>(function() {
    'use strict';

    var fs      = require('fs'),
        path    = require('path'),
        os      = require('os'),
        zlib    = require('zlib'),

        pipe    = require('..'),
        test    = require('tape');

    test('file1 | file2: no error', function(t) {
        var tmp     = os.tmpdir(),
            name    = path.basename(__filename),
            nameTmp = path.join(tmp, name + Math.random());

         tryPipe(__filename, nameTmp, function() {
            var file1 = fs.readFileSync(__filename, 'utf8'),
                file2 = fs.readFileSync(nameTmp, 'utf8');

            fs.unlinkSync(nameTmp);

            t.equal(file1, file2, 'files equal');
            t.end();
         });
    });

    test('file1 | file2: write open EACESS', function(t) {
        var name    = path.basename(__filename),
            nameTmp = '/' + name + Math.random();

        tryPipe(__filename, nameTmp, function(error) {
            t.ok(error, error && error.message);

            t.end();
        });
    });

    test('file1 | file2: read open ENOENT', function(t) {
        var tmp     = os.tmpdir(),
            random  = Math.random(),
            name    = path.basename(__filename),
            nameTmp = path.join(tmp, name + random);

        tryPipe(__filename + random, nameTmp, function(error) {
            t.ok(error, error && error.message);

            t.end();
        });
    });

    test('file1 | gzip | file2: no errors', function(t) {
        var tmp         = os.tmpdir(),
            random      = Math.random(),
            name        = path.basename(__filename),
            nameTmp     = path.join(tmp, name + random),

            read        = fs.createReadStream(__filename),
            write       = fs.createWriteStream(nameTmp),
            zip         = zlib.createGzip();

        pipe([read, zip, write], function(error) {
            var file1   = fs.readFileSync(__filename, 'utf8'),
                file2   = fs.readFileSync(nameTmp),
                zip     = zlib.gzipSync(file1);

            fs.unlinkSync(nameTmp);

            t.notOk(error, 'no errors');
            t.deepEqual(zip, file2, 'file gziped');
            t.end();
        });
    });

      test('file1 | gzip', function(t) {
        var read        = fs.createReadStream(__filename),
            zip         = zlib.createGzip();

        pipe([read, zip], function(error) {
            t.notOk(error, 'no errors');
            t.end();
        });
    });

    function tryPipe(from, to, fn) {
        var read    = fs.createReadStream(from),
            write   = fs.createWriteStream(to);

        pipe([read, write], function(error) {
            fn(error);
        });
    }

})();
<commit_msg>chore(pipe) rm " "<commit_after>(function() {
    'use strict';

    var fs      = require('fs'),
        path    = require('path'),
        os      = require('os'),
        zlib    = require('zlib'),

        pipe    = require('..'),
        test    = require('tape');

    test('file1 | file2: no error', function(t) {
        var tmp     = os.tmpdir(),
            name    = path.basename(__filename),
            nameTmp = path.join(tmp, name + Math.random());

         tryPipe(__filename, nameTmp, function() {
            var file1 = fs.readFileSync(__filename, 'utf8'),
                file2 = fs.readFileSync(nameTmp, 'utf8');

            fs.unlinkSync(nameTmp);

            t.equal(file1, file2, 'files equal');
            t.end();
         });
    });

    test('file1 | file2: write open EACESS', function(t) {
        var name    = path.basename(__filename),
            nameTmp = '/' + name + Math.random();

        tryPipe(__filename, nameTmp, function(error) {
            t.ok(error, error && error.message);

            t.end();
        });
    });

    test('file1 | file2: read open ENOENT', function(t) {
        var tmp     = os.tmpdir(),
            random  = Math.random(),
            name    = path.basename(__filename),
            nameTmp = path.join(tmp, name + random);

        tryPipe(__filename + random, nameTmp, function(error) {
            t.ok(error, error && error.message);

            t.end();
        });
    });

    test('file1 | gzip | file2: no errors', function(t) {
        var tmp         = os.tmpdir(),
            random      = Math.random(),
            name        = path.basename(__filename),
            nameTmp     = path.join(tmp, name + random),

            read        = fs.createReadStream(__filename),
            write       = fs.createWriteStream(nameTmp),
            zip         = zlib.createGzip();

        pipe([read, zip, write], function(error) {
            var file1   = fs.readFileSync(__filename, 'utf8'),
                file2   = fs.readFileSync(nameTmp),
                zip     = zlib.gzipSync(file1);

            fs.unlinkSync(nameTmp);

            t.notOk(error, 'no errors');
            t.deepEqual(zip, file2, 'file gziped');
            t.end();
        });
    });

    test('file1 | gzip', function(t) {
        var read        = fs.createReadStream(__filename),
            zip         = zlib.createGzip();

        pipe([read, zip], function(error) {
            t.notOk(error, 'no errors');
            t.end();
        });
    });

    function tryPipe(from, to, fn) {
        var read    = fs.createReadStream(from),
            write   = fs.createWriteStream(to);

        pipe([read, write], function(error) {
            fn(error);
        });
    }

})();
<|endoftext|>


<commit_before>const Commando = require('discord.js-commando');
const sqlite = require('sqlite');
const log = require(__dirname + '/logger.js');
const config =  require('./config');
const appConfig = config.appConfig;
const path = require('path');

//var serverConfig = config.serverConfig;
//var getServerConfig = config.getServerConfig;
var db;

const responses = require('./resources/responses.js');

const client = new Commando.Client({
	owner: appConfig.ownerid,
	commandPrefix: '!',
	unknownCommandResponse: false
});

client.registry
	.registerGroups([
		['interests', 'Interests'],
		['runescape', 'RuneScape'],
		['internet', 'Internet'],
		['games', 'Games'],
		['misc', 'Misc']
	])
	.registerDefaults()
	.registerCommandsIn(path.join(__dirname, 'commands'));

client.setProvider(sqlite.open(path.join(__dirname, 'settings.sqlite3')).then(sdb => new Commando.SQLiteProvider(sdb))).catch(log.error);

client.on('ready', () => {
	log.info('Client is ready');
	updatePlaying();
	setInterval(updatePlaying, 600000);
});

sqlite.open(path.join(__dirname,'deixbot.sqlite')).then( (rdb) => {
	log.info('Successfully opened database');
	db = rdb;
	client.login(appConfig.apikey).then(() => {
		log.info('Logged in with token');
	});
}).catch(log.error);

function updatePlaying() {
	db.get('SELECT playingString from playing ORDER BY RANDOM() LIMIT 1').then((game) => {
		client.user.setGame(game.playingString);
	}).catch(log.error);
}

client.on('message', (msg) => {
	if(msg.author.id !== client.user.id) {
		responses.forEach( (e) => {
			if(e.check(msg)) return e.action(msg);
		});
	}
});

process.on('SIGINT', () => {
	client.destroy();
	db.close().then(process.exit(0));
});
<commit_msg>Added response reloading<commit_after>const Commando = require('discord.js-commando');
const sqlite = require('sqlite');
const log = require(__dirname + '/logger.js');
const config =  require('./config');
const appConfig = config.appConfig;
const path = require('path');

//var serverConfig = config.serverConfig;
//var getServerConfig = config.getServerConfig;
var db;

var responses = require('./resources/responses.js');

var reloadResponses = {
	check: (msg) => {
		return msg.author.id === appConfig.ownerid && /(!reboot responses|!reboot chat|reboot speech)/.test(msg.cleanContent);
	},
	action: (msg) => {
		msg.channel.sendMessage('Rebooting speech module...').then( () => {
			delete require.cache[require.resolve('./resources/responses.js')];
			responses = [];
			responses = require('./resources/responses.js');
			responses.push(reloadResponses);
			return msg.channel.sendMessage('Speech module back online! Sal-u-tations!');
		});
	}
};

responses.push(reloadResponses);

const client = new Commando.Client({
	owner: appConfig.ownerid,
	commandPrefix: '!',
	unknownCommandResponse: false
});

client.registry
	.registerGroups([
		['interests', 'Interests'],
		['runescape', 'RuneScape'],
		['internet', 'Internet'],
		['games', 'Games'],
		['misc', 'Misc']
	])
	.registerDefaults()
	.registerCommandsIn(path.join(__dirname, 'commands'));

client.setProvider(sqlite.open(path.join(__dirname, 'settings.sqlite3')).then(sdb => new Commando.SQLiteProvider(sdb))).catch(log.error);

client.on('ready', () => {
	log.info('Client is ready');
	updatePlaying();
	setInterval(updatePlaying, 600000);
});

sqlite.open(path.join(__dirname,'deixbot.sqlite')).then( (rdb) => {
	log.info('Successfully opened database');
	db = rdb;
	client.login(appConfig.apikey).then(() => {
		log.info('Logged in with token');
	});
}).catch(log.error);

function updatePlaying() {
	db.get('SELECT playingString from playing ORDER BY RANDOM() LIMIT 1').then((game) => {
		client.user.setGame(game.playingString);
	}).catch(log.error);
}

client.on('message', (msg) => {
	if(msg.author.id !== client.user.id) {
		responses.forEach( (e) => {
			if(e.check(msg)) return e.action(msg);
		});
	}
});

process.on('SIGINT', () => {
	client.destroy();
	db.close().then(process.exit(0));
});
<|endoftext|>


<commit_before>var jake = require("jake")
  , gzip = require('gzip')
  , sys = require("sys")
  , path = require("path")
  , fs = require("fs")
  , util = require('util')
  , files = ['snake', 'base', 'web.db', 'vql']
  , i = 0
  , code = []
  , outputFile = "build/snake.js"
  , outputMinFile = "build/snake.min.js"
  , outputDevFile = "build/snake.dev.js"
  , gzippedFile = "build/snake.js.gz"
  , sys = require('sys')
  , exec = require('child_process').exec
  , jshintComments = "/*jshint white: true, devel: true, evil: true, laxbreak: true, onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true, indent: 2, maxerr: 1 */\n/* global openDatabase*/\n";

task("default", [], function () {

  var compressorDone = function (preMin, postMin) {

    console.log("Successfully compressed " + preMin);

    fs.stat(preMin, function (err, stats) {
      preMin = stats;
      fs.stat(postMin, function (err, stats) {
        postMin = stats;
        var ratio = Math.round((postMin.size / preMin.size) * 100);

        console.log("Original size: " + preMin.size);
        console.log("Compressed size: " + postMin.size);
        console.log("Compression ratio: " + ratio + "%");
      });
    });
  }

  , compressFile = function () {
    // Uglify JS
    fs.readFile(outputFile, "utf8", function (err, text) {
      if (err) {
        throw err;
      }

      console.log("Started Lint testing " + outputFile);

      exec("jshint " + outputFile + " --config jshint.json", function (error, stdout, stderr) {
        if (stdout) {
          console.log("--jshint--");
          console.log(stdout);
        }
        if (error !== null) {
          console.log('exec error: ' + error);
        }
      });

      console.log("Compressing " + outputFile + " using UglifyJS");

      exec("uglifyjs " + outputFile + " >> " + outputMinFile, function (error, stdout, stderr) {
        if (stdout) {
          console.log("--UglifyJS--");
          console.log(stdout);
        }

        if (error !== null) {
          console.log('exec error: ' + error);
        }
      });

      console.log("Compressing " + outputFile + " using node-gzip");

      // NOTE: requires gzip (npm install gzip)
      gzip(text, function (err, data) {
        // Save gzip output to a file
        fs.writeFile(gzippedFile, data, 'utf8', function (err) {
          console.log("gzipped file: " + gzippedFile);
          fs.stat(gzippedFile, function (err, stats) {
            console.log("gzipped size: " + stats.size);
          });
        });
      });
    });
  }

  , writeFile = function () {
    // delete the file first
    fs.unlink(outputFile);

    // write all files into a snake build
    fs.writeFile(outputFile, code.join("\n"), 'utf8', function (err) {
      console.log("Wrote to " + outputFile);

      if (err) {
        throw err;
      }

      // run compressor
      compressFile();
    });

    // write files into a dev version with jshint comments
    fs.writeFile(outputDevFile, jshintComments + code.join("\n") + "\n(function () { Snake.debug = true; })();", 'utf8', function (err) {
      console.log("Wrote to " + outputDevFile);
    });
  }

  , readFile = function () {
    if (code.length === files.length) {
      writeFile();
    } else {
      var inputFile = "src/" + files[i] + ".js";
      console.log("Merging " + inputFile);

      fs.readFile(inputFile, 'utf8', function (err, data) {
        if (err) {
          throw err;
        }

        // join all the files
        code.push(data);

        // read the next file...
        readFile();
      });

      i = i + 1;
    }
  };

  readFile();

}, true);
<commit_msg>removed jshint comments from dev file<commit_after>var jake = require("jake")
  , gzip = require('gzip')
  , sys = require("sys")
  , path = require("path")
  , fs = require("fs")
  , util = require('util')
  , files = ['snake', 'base', 'web.db', 'vql']
  , i = 0
  , code = []
  , outputFile = "build/snake.js"
  , outputMinFile = "build/snake.min.js"
  , outputDevFile = "build/snake.dev.js"
  , gzippedFile = "build/snake.js.gz"
  , sys = require('sys')
  , exec = require('child_process').exec;

task("default", [], function () {

  var compressorDone = function (preMin, postMin) {

    console.log("Successfully compressed " + preMin);

    fs.stat(preMin, function (err, stats) {
      preMin = stats;
      fs.stat(postMin, function (err, stats) {
        postMin = stats;
        var ratio = Math.round((postMin.size / preMin.size) * 100);

        console.log("Original size: " + preMin.size);
        console.log("Compressed size: " + postMin.size);
        console.log("Compression ratio: " + ratio + "%");
      });
    });
  }

  , compressFile = function () {
    // Uglify JS
    fs.readFile(outputFile, "utf8", function (err, text) {
      if (err) {
        throw err;
      }

      console.log("Started Lint testing " + outputFile);

      exec("jshint " + outputFile + " --config jshint.json", function (error, stdout, stderr) {
        if (stdout) {
          console.log("--jshint--");
          console.log(stdout);
        }
        if (error !== null) {
          console.log('exec error: ' + error);
        }
      });

      console.log("Compressing " + outputFile + " using UglifyJS");

      exec("uglifyjs " + outputFile + " >> " + outputMinFile, function (error, stdout, stderr) {
        if (stdout) {
          console.log("--UglifyJS--");
          console.log(stdout);
        }

        if (error !== null) {
          console.log('exec error: ' + error);
        }
      });

      console.log("Compressing " + outputFile + " using node-gzip");

      // NOTE: requires gzip (npm install gzip)
      gzip(text, function (err, data) {
        // Save gzip output to a file
        fs.writeFile(gzippedFile, data, 'utf8', function (err) {
          console.log("gzipped file: " + gzippedFile);
          fs.stat(gzippedFile, function (err, stats) {
            console.log("gzipped size: " + stats.size);
          });
        });
      });
    });
  }

  , writeFile = function () {
    // delete the file first
    fs.unlink(outputFile);

    // write all files into a snake build
    fs.writeFile(outputFile, code.join("\n"), 'utf8', function (err) {
      console.log("Wrote to " + outputFile);

      if (err) {
        throw err;
      }

      // run compressor
      compressFile();
    });

// TODO add license
    // write files into a dev version with jshint comments
    fs.writeFile(outputDevFile, code.join("\n") + "\n(function () { Snake.debug = true; }());", 'utf8', function (err) {
      console.log("Wrote to " + outputDevFile);
    });
  }

  , readFile = function () {
    if (code.length === files.length) {
      writeFile();
    } else {
      var inputFile = "src/" + files[i] + ".js";
      console.log("Merging " + inputFile);

      fs.readFile(inputFile, 'utf8', function (err, data) {
        if (err) {
          throw err;
        }

        // join all the files
        code.push(data);

        // read the next file...
        readFile();
      });

      i = i + 1;
    }
  };

  readFile();

}, true);
<|endoftext|>


<commit_before>void function(){

var whatKey = function(k){
  // if ('char' in k) {
  //   return function whatKey(e){
  //     return (e.char || '').toLowerCase();
  //   };
  // }
  if ('keyIdentifier' in k) {
    return function whatKey(e){
      return e.keyIdentifier.toLowerCase();
    };
  } else if ('charCode' in k) {
    return function whatKey(e){
      return (e.charCode || '').toLowerCase();
    };
  }
}(document.createEvent('KeyboardEvent'));

function Keyboard(view){
  var self = this;
  this.keys = {};
  this.view = view;
  this.ctrl = false;
  this.shift = false;
  this.alt = false;
  this.meta = false;

  var events = {
    keydown: function(e){
      self.update(e);
      self.emit('down', e);
    },
    keyup: function(e){
      self.update(e);
      self.emit('up', e);
    },
    keypress: function(e){
      self.update(e);
      self.emit('press', e);
    }
  };

  for (var k in events) {
    view.addEventListener(k, events[k], true);
  }
}

Keyboard.prototype = {
  constructor: Keyboard,
  update: function update(evt){
    this.lastKey = whatKey(evt);
    this.lasyEvent = evt;
    this.ctrl = evt.ctrlKey;
    this.shift = evt.shiftKey;
    this.alt = evt.altKey;
    this.meta = evt.metaKey;
  },
  emit: function emit(type, evt){
    var listeners = this.keys[this.lastKey];
    if (listeners) {
      for (var i=0; i < listeners.length; i++) {
        listeners[i](type, evt);
      }
    }
  },
  on: function on(bind, listener){
    var self = this,
        current = 0,
        events = [],
        keys = bind.split('->');

    if (keys.length > 1) {

      keys.forEach(function(key, index){
        var listeners = self.keys[key] || (self.keys[key] = []);
        listeners.push(function(type, evt){
          if (type === 'down') {
            if (events.length === index) {
              events.push(evt);
              if (index === keys.length - 1) {
                listener.apply(self, events);
                events.length = 0;
              }
            }
          } else {
            events.length = 0;
          }
        });
      });

    } else if ((keys = bind.split('+')).length > 1) {

      keys.forEach(function(key, index){
        var listeners = self.keys[key] || (self.keys[key] = []);
        listeners.push(function(type, evt){
          if (evt.type === 'down') {
            current++;
            events[index] = evt;
            if (events.length === keys.length) {
              listener.apply(self, events);
              events.length = 0;
            }
          } else if (type === 'up') {
            current--;
            events[index] = null;
          }
        });
      });

    } else {
      var listeners = self.keys[bind] || (self.keys[bind] = []);
      listeners.push(function(type, evt){
        listener.call(self, evt);
      });
    }
  }
};

window.keyboard = new Keyboard(window);

}();
<commit_msg>fix it<commit_after>void function(){

function whatKey(evt){
  return String.fromCharCode(evt.charCode);
}

function Keyboard(view){
  var self = this;
  this.keys = {};
  this.view = view;
  this.ctrl = false;
  this.shift = false;
  this.alt = false;
  this.meta = false;

  var events = {
    keydown: function(e){
      self.update(e);
      self.emit('down', e);
    },
    keyup: function(e){
      self.update(e);
      self.emit('up', e);
    },
    keypress: function(e){
      self.update(e);
      self.emit('press', e);
    }
  };

  for (var k in events) {
    view.addEventListener(k, events[k], true);
  }
}

Keyboard.prototype = {
  constructor: Keyboard,
  update: function update(evt){
    this.lastKey = whatKey(evt);
    this.lastEvent = evt;
    this.ctrl = evt.ctrlKey;
    this.shift = evt.shiftKey;
    this.alt = evt.altKey;
    this.meta = evt.metaKey;
  },
  emit: function emit(type, evt){
    var listeners = this.keys[this.lastKey];
    if (listeners) {
      for (var i=0; i < listeners.length; i++) {
        listeners[i](type, evt);
      }
    }
  },
  on: function on(bind, listener){
    var self = this,
        current = 0,
        events = [],
        keys = bind.split('->');

    if (keys.length > 1) {

      keys.forEach(function(key, index){
        var listeners = self.keys[key] || (self.keys[key] = []);
        listeners.push(function(type, evt){
          if (type === 'down' && events.length === index) {
            events.push(evt);
            if (index === keys.length - 1) {
              listener.apply(self, events);
              events.length = 0;
            }
          } else {
            events.length = 0;
          }
        });
      });

    } else if ((keys = bind.split('+')).length > 1) {

      keys.forEach(function(key, index){
        var listeners = self.keys[key] || (self.keys[key] = []);
        listeners.push(function(type, evt){
          if (evt.type === 'down') {
            current++;
            events[index] = evt;
            if (events.length === keys.length) {
              listener.apply(self, events);
              events.length = 0;
            }
          } else if (type === 'up') {
            current--;
            events[index] = null;
          }
        });
      });

    } else {
      var listeners = self.keys[bind] || (self.keys[bind] = []);
      listeners.push(function(type, evt){
        listener.call(self, evt);
      });
    }
  }
};

window.keyboard = new Keyboard(window);

}();
<|endoftext|>


<commit_before>#! /usr/bin/env node
const args = require('../args') // TODO
const path = require('path')

const gest = require('../src/index')
const REPL = require('../src/REPL')
const { readFile, checkPath, flagsToOptions, colorResponse } = require('../src/util')

args
  .option('header', 'HTTP request header')
  .option('baseUrl', 'Base URL for sending HTTP requests')

const flags = args.parse(process.argv)

try {
  if (!flags.help && !flags.version) {
    let config
    try {
      config = require(path.join(process.cwd(), 'package.json')).gest
    } catch (e) {}

    const options = Object.assign({ schema: 'schema.js' }, config, flagsToOptions(flags))

    const schema = require(path.join(process.cwd(), options.schema))

    if (args.sub && args.sub.length) {
      checkPath(path.join(process.cwd(), args.sub[0]))
      .then(readFile)
      .catch(() => args.sub[0])
      .then(gest(schema, options))
      .then(colorResponse)
      .then(console.log)
      .catch(console.log)
    } else {
      // REPL
      REPL(schema, options)
    }
  }
} catch (e) {
  switch (e.code) {
    case 'MODULE_NOT_FOUND':
      console.log('\nSchema not found. Trying running `gest` with your `schema.js` in the current working directory.\n')
      break
    default: console.log(e)
  }
}
<commit_msg>Add inspect flag<commit_after>#! /usr/bin/env node
const args = require('../args') // TODO
const path = require('path')
const { printSchema } = require('graphql')

const gest = require('../src/index')
const REPL = require('../src/REPL')
const { readFile, checkPath, flagsToOptions, colorResponse } = require('../src/util')

args
  .option('header', 'HTTP request header')
  .option('baseUrl', 'Base URL for sending HTTP requests')
  .option(['I', 'inspect'], 'Print your GraphQL schema options')

const flags = args.parse(process.argv)

try {
  if (!flags.help && !flags.version) {
    let config
    try {
      config = require(path.join(process.cwd(), 'package.json')).gest
    } catch (e) {}

    const options = Object.assign({ schema: 'schema.js' }, config, flagsToOptions(flags))

    const schema = require(path.join(process.cwd(), options.schema))

    if (flags.inspect) {
      console.log(printSchema(schema))
      process.exit()
    }

    if (args.sub && args.sub.length) {
      checkPath(path.join(process.cwd(), args.sub[0]))
      .then(readFile)
      .catch(() => args.sub[0])
      .then(gest(schema, options))
      .then(colorResponse)
      .then(console.log)
      .catch(console.log)
    } else {
      // REPL
      REPL(schema, options)
    }
  }
} catch (e) {
  switch (e.code) {
    case 'MODULE_NOT_FOUND':
      console.log('\nSchema not found. Trying running `gest` with your `schema.js` in the current working directory.\n')
      break
    default: console.log(e)
  }
}
<|endoftext|>


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

/**
 * return a fixed length random string from array
 * @param array
 * @param len
 * @returns {string}
 */
function random(array, len) {
  const size = array.length;
  const randomIndexes = crypto.randomBytes(len).toJSON().data;
  return randomIndexes.map((char) => array[char % size]).join('');
}

/**
 * returns a random integer in [min, max].
 * @param min
 * @param max
 * @returns {Number}
 */
function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.ceil(max);
  return Math.floor(crypto.randomBytes(1)[0] / 0xff * (max - min + 1)) + min;
}

module.exports = function init({isMinimal}) {
  const key = random('abcdefghjkmnpqrstuvwxyz23456789!@#$%^&*()_+<>?:|{}-=[];,./ABCDEFGHJKLMNPQRSTUVWXYZ', 16);
  const port = getRandomInt(1024, 65535);
  const timeout = getRandomInt(200, 1000);

  const clientJson = {
    'host': '127.0.0.1',
    'port': 1080,
    'servers': [
      {
        'enabled': true,
        'transport': 'tcp',
        'host': '127.0.0.1',
        'port': port,
        'key': key,
        'presets': [
          {'name': 'ss-base'},
          {'name': 'ss-aead-cipher', 'params': {'method': 'aes-256-gcm'}}
        ],
        'tls_cert': 'cert.pem'
      }
    ],
    'dns': [],
    'dns_expire': 3600,
    'timeout': timeout,
    'workers': 0,
    'log_path': 'bs-client.log',
    'log_level': 'info',
    'log_max_days': 30
  };

  if (isMinimal) {
    delete clientJson.servers[0].transport;
    delete clientJson.servers[0].tls_cert;
    delete clientJson.dns;
    delete clientJson.dns_expire;
    delete clientJson.timeout;
    delete clientJson.workers;
    delete clientJson.log_path;
    delete clientJson.log_level;
    delete clientJson.log_max_days;
  }

  const serverJson = {
    'host': '0.0.0.0',
    'port': port,
    'key': key,
    'transport': 'tcp',
    'presets': [
      {'name': 'ss-base'},
      {'name': 'ss-aead-cipher', 'params': {'method': 'aes-256-gcm'}}
    ],
    'tls_key': 'key.pem',
    'tls_cert': 'cert.pem',
    'dns': [],
    'dns_expire': 3600,
    'timeout': timeout,
    'redirect': '',
    'workers': 0,
    'log_path': 'bs-server.log',
    'log_level': 'info',
    'log_max_days': 30
  };

  if (isMinimal) {
    delete serverJson.transport;
    delete serverJson.tls_key;
    delete serverJson.tls_cert;
    delete serverJson.dns;
    delete serverJson.dns_expire;
    delete serverJson.timeout;
    delete serverJson.redirect;
    delete serverJson.workers;
    delete serverJson.log_path;
    delete serverJson.log_level;
    delete serverJson.log_max_days;
  }

  fs.writeFileSync('blinksocks.client.json', JSON.stringify(clientJson, null, '  '));
  fs.writeFileSync('blinksocks.server.json', JSON.stringify(serverJson, null, '  '));

  console.log('> Generate Done. For help please see:');
  console.log('> https://github.com/blinksocks/blinksocks/tree/master/docs/config/README.md');
};
<commit_msg>bin: generate new format configs<commit_after>const fs = require('fs');
const crypto = require('crypto');

/**
 * return a fixed length random string from array
 * @param array
 * @param len
 * @returns {string}
 */
function random(array, len) {
  const size = array.length;
  const randomIndexes = crypto.randomBytes(len).toJSON().data;
  return randomIndexes.map((char) => array[char % size]).join('');
}

/**
 * returns a random integer in [min, max].
 * @param min
 * @param max
 * @returns {Number}
 */
function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.ceil(max);
  return Math.floor(crypto.randomBytes(1)[0] / 0xff * (max - min + 1)) + min;
}

module.exports = function init({isMinimal}) {
  const key = random('abcdefghjkmnpqrstuvwxyz23456789!@#$%^&*()_+<>?:|{}-=[];,./ABCDEFGHJKLMNPQRSTUVWXYZ', 16);
  const port = getRandomInt(1024, 65535);
  const timeout = getRandomInt(200, 1000);

  const clientJson = {
    'service': 'socks5://127.0.0.1:1080',
    'servers': [
      {
        'enabled': true,
        'service': `tcp://127.0.0.1:${port}`,
        'key': key,
        'presets': [
          {'name': 'ss-base'},
          {'name': 'ss-aead-cipher', 'params': {'method': 'aes-256-gcm'}}
        ],
        'tls_cert': 'cert.pem'
      }
    ],
    'dns': [],
    'dns_expire': 3600,
    'timeout': timeout,
    'workers': 0,
    'log_path': 'bs-client.log',
    'log_level': 'info',
    'log_max_days': 30
  };

  if (isMinimal) {
    delete clientJson.servers[0].tls_cert;
    delete clientJson.dns;
    delete clientJson.dns_expire;
    delete clientJson.timeout;
    delete clientJson.workers;
    delete clientJson.log_path;
    delete clientJson.log_level;
    delete clientJson.log_max_days;
  }

  const serverJson = {
    'service': `tcp://0.0.0.0:${port}`,
    'key': key,
    'presets': [
      {'name': 'ss-base'},
      {'name': 'ss-aead-cipher', 'params': {'method': 'aes-256-gcm'}}
    ],
    'tls_key': 'key.pem',
    'tls_cert': 'cert.pem',
    'dns': [],
    'dns_expire': 3600,
    'timeout': timeout,
    'redirect': '',
    'workers': 0,
    'log_path': 'bs-server.log',
    'log_level': 'info',
    'log_max_days': 30
  };

  if (isMinimal) {
    delete serverJson.tls_key;
    delete serverJson.tls_cert;
    delete serverJson.dns;
    delete serverJson.dns_expire;
    delete serverJson.timeout;
    delete serverJson.redirect;
    delete serverJson.workers;
    delete serverJson.log_path;
    delete serverJson.log_level;
    delete serverJson.log_max_days;
  }

  fs.writeFileSync('blinksocks.client.json', JSON.stringify(clientJson, null, '  '));
  fs.writeFileSync('blinksocks.server.json', JSON.stringify(serverJson, null, '  '));

  console.log('> Generate Done. For help please see:');
  console.log('> https://github.com/blinksocks/blinksocks/tree/master/docs/config/README.md');
};
<|endoftext|>


<commit_before>// To support using nodejs modules that do module.exports = ...
var module = {};

var Util = {
Text: (function Text(){
	var http_matcher = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
	var www_matcher = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
	var mail_to_matcher = /(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim;
   var image_suffix_matcher = /\.(gif|jpg|jpeg|png|tiff|tif|svg|mini|thumbnail|standard|medium|large|huge)/gim;
	var my_name = (window.Me && Me.name && Me.name.toLowerCase()) || '';
	var filter = (function(){
		var f = window.UiOptions && UiOptions.wordFilter;
		return f && new RegExp(f.join('|'), 'gi');
	})();

	return {
		newlineMatcher: /\n|\r\n/gim,

		linkify: function(text){
         var tmp = this.imageDisplay(text);
         if (text != tmp) {
            return tmp;
         }
			text = text.replace(http_matcher, '$1');
			text = text.replace(www_matcher, '$1$2');
			text = text.replace(mail_to_matcher, '$1');
			return text
		},

		linkifyTest: function(text){
			return this.httpMatch(text) ||
			       this.wwwMatch(text) ||
			       this.mailtoMatch(text);
		},

      // We need these four match methods because regex.test() is buggy when
      // you reuse a regex object. Other regex functions are fine though...
      httpMatch: function(text) {
         return (/(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim).test(text);
      },

      wwwMatch: function(text) {
         return (/(^|[^\/])(www\.[\S]+(\b|$))/gim).test(text);
      },

      mailtoMatch: function(text) {
         return (/(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim).test(text);
      },

      imageSuffixMatch: function(text) {
         return (/\.(gif|jpg|jpeg|png|tiff|tif|svg|mini|thumbnail|standard|medium|large|huge)/gim).test(text);
      },

		mentionMatcher: function(text){
			var matches = text.match(/@([^\s]+)/g);
			return matches && matches.some(function(match){
				match = match.substr(1);
				return match.length >= 2 && my_name.indexOf(match.toLowerCase()) >= 0;
			});
		},

      imageDisplay: function(text){
         if (this.httpMatch(text) || this.wwwMatch(text)) {
            if (this.wwwMatch(text))
               text = 'http://' + text;

            if (this.imageSuffixMatch(text)) {
               text = text.replace(http_matcher, ' ');
            }
         }
         return text;
      },

		wordFilter: function(text){
			if(!filter) return text;
			return text.replace(filter, function(m) {
				return Array(m.length+1).join("*");
			});
		}
	};
})(),

nextTick: function(f){
	return setTimeout(f,0);
},

ts:function(){
	return new Date().getTime();
},

time:function time(t){
	var H = t.getHours(),
			h = H % 12,
			m = t.getMinutes();

	return (h==0 ? 12 : h) + ":" + (m < 10 ? '0' + m : m) + (H > 11 ? 'pm' : 'am');
},

date:function date(t){
	var d = t.getDate(),
	    m = t.getMonth() + 1;

	return m + "/" + (d < 10 ? '0' + d : d);
},

url:function(){
	return window.location.href.split('?')[0];
},

inherits:function(to, from){
	$.extend(to.prototype, from.prototype, {_super: from});
}
};

if(window.EventEmitter){
	EventEmitter.prototype.muteEvents = function(fn){
		this.emit = function(){}
		fn();
		delete this.emit;
	}
}
<commit_msg>Revamp of image / yt embed parsing<commit_after>// To support using nodejs modules that do module.exports = ...
var module = {};

var Util = {
Text: (function Text(){
	var my_name = (window.Me && Me.name && Me.name.toLowerCase()) || '';
	var filter = (function(){
		var f = window.UiOptions && UiOptions.wordFilter;
		return f && new RegExp(f.join('|'), 'gi');
	})();

	return {
		newlineMatcher: /\n|\r\n/gim,

      linkify: function(text) {
         var lines = text.split("\n");
         text = "";
         for (i = 0; i < lines.length; ++i) {
            var words = lines[i].split(" ");
            lines[i] = "";
            for (j = 0; j < words.length; ++j) {
               var tmp = words[j];
               words[j] = this.parseYoutube(words[j]);

               if (words[j] == tmp) {
                  words[j] = this.parseImg(words[j]);

                  if (words[j] == tmp) {
                     words[j] = this.parseLink(words[j]);
                  }
               }

               lines[i] += words[j] + (j != words.length - 1 ? " " : "");
            }
            text += lines[i] + (i != lines.length - 1 ? "\n" : "");
         }

         return text;
      },

      parseImg: function(text) {
         var url = "";
         if (this.matchHttp(text)) {
            url = text;
         } else if (this.matchWWW(text)) {
            url = "http://" + text;
         }

         if (url != "" && this.matchImgSuffix(url)) {
            return '';
         }

         return text;
      },

      parseYoutube: function(text) {
         var id = this.getYoutubeId(text);
         var rr = id == "oHg5SJYRHA0" ? 1 : 0;
         var url = 'https://www.youtube.com/v/' + id + '?version=3&autoplay=' + rr;
         if ((this.matchHttp(text) || this.matchWWW(text)) && this.matchYoutube(text)) {
               return '<object width="640" height="390"><param name="movie" value="' + url + '"></param><param name="allowScriptAccess" value="always"></param><embed src="' + url + '" type="application/x-shockwave-flash" allowscriptaccess="always" width="640" height="390"></embed></object>'
         }

         return text;
      },

      parseLink: function(text) {
         if (this.matchHttp(text)) {
            return '' + text + '';
         } else if (this.matchWWW(text)) {
            var url = "http://" + text;
            return '' + text + '';
         } else {
            return text;
         }
      },

		linkifyTest: function(text){
			return this.matchHttp(text) ||
			       this.matchWWW(text) ||
			       this.matchMailto(text);
		},

      // We need these four match methods because regex.test() is buggy when
      // you reuse a regex object. Other regex functions are fine though...
      matchHttp: function(text) {
         return (/(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim).test(text);
      },

      matchWWW: function(text) {
         return (/(^|[^\/])(www\.[\S]+(\b|$))/gim).test(text);
      },

      matchMailto: function(text) {
         return (/(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim).test(text);
      },

      matchYoutube: function(text) {
         return (/youtube\.com|youtu\.be/).test(text);
      },

      getYoutubeId: function(text) {
         var id = (/[a-zA-Z0-9\-\_]{11}/).exec((/(v=|\/v\/|\/embed\/)[a-zA-Z0-9\-\_]{11}/).exec(text));
         return id;
      },

      matchImgSuffix: function(text) {
         return (/\.(gif|jpg|jpeg|png|tiff|tif|svg|mini|thumbnail|standard|medium|large|huge)/gim).test(text);
      },

		mentionMatcher: function(text){
			var matches = text.match(/@([^\s]+)/g);
			return matches && matches.some(function(match){
				match = match.substr(1);
				return match.length >= 2 && my_name.indexOf(match.toLowerCase()) >= 0;
			});
		},

      imageDisplay: function(text){
         if (this.matchHttp(text) || this.matchWWW(text)) {
            if (this.matchWWW(text))
               text = 'http://' + text;

            if (this.imageSuffixMatch(text)) {
               text = text.replace(http_matcher, ' ');
            }
         }
         return text;
      },

		wordFilter: function(text){
			if(!filter) return text;
			return text.replace(filter, function(m) {
				return Array(m.length+1).join("*");
			});
		},
	};
})(),

nextTick: function(f){
	return setTimeout(f,0);
},

ts:function(){
	return new Date().getTime();
},

time:function time(t){
	var H = t.getHours(),
			h = H % 12,
			m = t.getMinutes();

	return (h==0 ? 12 : h) + ":" + (m < 10 ? '0' + m : m) + (H > 11 ? 'pm' : 'am');
},

date:function date(t){
	var d = t.getDate(),
	    m = t.getMonth() + 1;

	return m + "/" + (d < 10 ? '0' + d : d);
},

url:function(){
	return window.location.href.split('?')[0];
},

inherits:function(to, from){
	$.extend(to.prototype, from.prototype, {_super: from});
}
};

if(window.EventEmitter){
	EventEmitter.prototype.muteEvents = function(fn){
		this.emit = function(){}
		fn();
		delete this.emit;
	}
}
<|endoftext|>