<commit_before>/**
 * Created with JetBrains PhpStorm.
 * User: lispad
 * Date: 13.04.13
 * Time: 17:47
 * To change this template use File | Settings | File Templates.
 */

$(document).ready(function(){
    new LApp().init();
});

LApp=function(){
    this.init=function(){
        this.history.init();
        this.log = new LChat($('.page.chat > textarea'));
        $('.navbar-inner > ul.nav > li > ._connect').click(function(){
            if (typeof this.CS=='undefined'  || !this.CS.isConnected())
                this.connect();
            else
                this.disconnect();
        }.bind(this));
    };

    this.connect=function (){
        var buf='';
        /* Connection is set on creating, we have to recreate websocket to reconnect */
        this.CS=new LWebSocket("localhost", 8080);
        this.CS.on('connect',function(){
            this.log.add("==Connected to WebSocket==\n");
            $('.navbar-inner > div > ._status').removeClass('badge-important').removeClass('badge-info').addClass('badge-success').text('connected');
        }.bind(this));

        this.CS.on('disconnect',function(){
            this.log.add("==Socket closed (not connected):==\n");
            $('.navbar-inner > div > ._status').removeClass('badge-success').removeClass('badge-info').addClass('badge-important').text('disconnected');
        }.bind(this));

        this.CS.on('receive', function(data){
            this.log.push(data);
//        buf+=data;
//        var received=buf.split("\n");
//        buf=received.pop()
//        received.forEach(function(value){
//            log.add(value);
//        })
        }.bind(this));

        this.log.onChar(function(key){
            this.CS.send(key);
        }.bind(this));

        $('.navbar-inner > div > ._status').removeClass('badge-important').removeClass('badge-success').addClass('badge-info').text('connecting');
        this.CS.connect();
    };

    this.disconnect=function(){
        this.CS.disconnect();
    };

    this.history = {
        init: function () {
            window.addEventListener('popstate', function (event) {
                var url = location.hash.replace("#", '') || location.pathname.replace("/", '');
                if (url)
                    this._goToPage(url);
            }.bind(this), false);
        },
        _goToPage: function (url) {
            $('.navbar-inner > ul.nav > li').removeClass('active');
            $('.navbar-inner > ul.nav').children('.' + url).addClass('active');
            $('.page').hide();
            $('.page.' + url).show();
        }
    };
};

LWebSocket=function (addr, port){
    this._addr=addr;
    this._port = port;
    this._ws = null;
    this._listeners={
        connect:[],
        disconnect:[],
        receive:[]
    };

    this.isConnected=function() {
        return this._ws.readyState==this._ws.OPEN;
    };

    this.setPort = function (port){
        this._port=port;
    };

    this.send = function (buffer){
        if (this.isConnected())
            this._ws.send(buffer);
    };

    this.on = function (type, callback){
        if (typeof this._listeners[type]!='undefined')
            this._listeners[type].push(callback);
    };

    this.connect = function(){
        this._ws = new WebSocket('ws://'+this._addr+':'+this._port);

        this._ws.onopen = function() {
            this._listeners.connect.forEach(function(callback){callback();});
        }.bind(this);

        this._ws.onmessage = function (evt) {
            this._listeners.receive.forEach(function(callback){callback(evt.data);});
        }.bind(this);

        this._ws.onclose = function(ev) {
            this._listeners.disconnect.forEach(function(callback){callback();});
        }.bind(this);
    };

    this.disconnect=function(){
        this._ws.close();
    };
};

LChat=function(area){
    this._area=null;
    this._callback=null;
    this._echo=false;

    this.setArea=function(area){
        if (area instanceof $)
            this._area=area.get(0);
        else
            this._area=area||null;

        $(this._area).on('keypress',function(event){
            var key=String.fromCharCode(parseInt(event.charCode));
            if (this._callback!=null)
                this._callback(key);
            return this._echo;
        }.bind(this));
    };
    this.add=function(text){
        if (this._area.value.length>1024)
            this._area.value=this._area.value.substr(0, 1024);
        this._area.value=text+this._area.value;
    };

    this.push=function(text){
        this._area.value+=text;
    };

    this.clear=function(){
        this._area.value='';
    };

    this.onChar=function (callback){
        this._callback=callback;
    };

    this.echo=function (enabled){
        this._echo=enabled;
    };

    this.setArea(area);
};
<commit_msg>check existance<commit_after>/**
 * Created with JetBrains PhpStorm.
 * User: lispad
 * Date: 13.04.13
 * Time: 17:47
 * To change this template use File | Settings | File Templates.
 */

$(document).ready(function(){
    new LApp().init();
});

LApp=function(){
    this.init=function(){
        this.history.init();
        this.log = new LChat($('.page.chat > textarea'));

        this._connectButtonPressed=function(){
            if (typeof this.CS=='undefined'  || !this.CS.isConnected())
                this.connect();
            else
                this.disconnect();
        };
        $('.navbar-inner > ul.nav > li > ._connect').click(this._connectButtonPressed());
    };

    this.connect=function (){
        var buf='';
        /* Connection is set on creating, we have to recreate websocket to reconnect */
        this.CS=new LWebSocket("localhost", 8080);
        this.CS.on('connect',function(){
            this.log.add("==Connected to WebSocket==\n");
            $('.navbar-inner > div > ._status').removeClass('badge-important').removeClass('badge-info').addClass('badge-success').text('connected');
        }.bind(this));

        this.CS.on('disconnect',function(){
            this.log.add("==Socket closed (not connected):==\n");
            $('.navbar-inner > div > ._status').removeClass('badge-success').removeClass('badge-info').addClass('badge-important').text('disconnected');
        }.bind(this));

        this.CS.on('receive', function(data){
            this.log.push(data);
//        buf+=data;
//        var received=buf.split("\n");
//        buf=received.pop()
//        received.forEach(function(value){
//            log.add(value);
//        })
        }.bind(this));

        this.log.onChar(function(key){
            this.CS.send(key);
        }.bind(this));

        $('.navbar-inner > div > ._status').removeClass('badge-important').removeClass('badge-success').addClass('badge-info').text('connecting');
        this.CS.connect();
    };

    this.disconnect=function(){
        this.CS.disconnect();
    };

    this.history = {
        init: function () {
            window.addEventListener('popstate', function (event) {
                var url = location.hash.replace("#", '') || location.pathname.replace("/", '');
                if (url)
                    this._goToPage(url);
            }.bind(this), false);
        },
        _goToPage: function (url) {
            var newTab=$('.navbar-inner > ul.nav').children('.' + url);
            if (newTab.length==0)
                return console.error('Error in tab selection. Refresh page');
            $('.navbar-inner > ul.nav > li').removeClass('active');
            $('.navbar-inner > ul.nav').children('.' + url).addClass('active');
            $('.page').hide();
            $('.page.' + url).show();
        }
    };
};

LWebSocket=function (addr, port){
    this._addr=addr;
    this._port = port;
    this._ws = null;
    this._listeners={
        connect:[],
        disconnect:[],
        receive:[]
    };

    this.isConnected=function() {
        return this._ws.readyState==this._ws.OPEN;
    };

    this.setPort = function (port){
        this._port=port;
    };

    this.send = function (buffer){
        if (this.isConnected())
            this._ws.send(buffer);
    };

    this.on = function (type, callback){
        if (typeof this._listeners[type]!='undefined')
            this._listeners[type].push(callback);
    };

    this.connect = function(){
        this._ws = new WebSocket('ws://'+this._addr+':'+this._port);

        this._ws.onopen = function() {
            this._listeners.connect.forEach(function(callback){callback();});
        }.bind(this);

        this._ws.onmessage = function (evt) {
            this._listeners.receive.forEach(function(callback){callback(evt.data);});
        }.bind(this);

        this._ws.onclose = function(ev) {
            this._listeners.disconnect.forEach(function(callback){callback();});
        }.bind(this);
    };

    this.disconnect=function(){
        this._ws.close();
    };
};

LChat=function(area){
    this._area=null;
    this._callback=null;
    this._echo=false;

    this.setArea=function(area){
        if (area instanceof $)
            this._area=area.get(0);
        else
            this._area=area||null;

        $(this._area).on('keypress',function(event){
            var key=String.fromCharCode(parseInt(event.charCode));
            if (typeof this._callback=="function")
                this._callback(key);
            return this._echo;
        }.bind(this));
    };

    this.add=function(text){
        if (this._area.value.length>1024)
            this._area.value=this._area.value.substr(0, 1024);
        this._area.value=text+this._area.value;
    };

    this.push=function(text){
        this._area.value+=text;
    };

    this.clear=function(){
        this._area.value='';
    };

    this.onChar=function (callback){
        this._callback=callback;
    };

    this.echo=function (enabled){
        this._echo=enabled;
    };

    this.setArea(area);
};
<|endoftext|>


<commit_before>/* eslint-env mocha */

const assert = require("assert");
const sinon = require("sinon");

// tested module
const Compiler = require("../../lib/Compiler");

describe("Compiler#createFileHandler", function() {
	before(() => {
		sinon.stub(console, "log");
	});
	after(() => {
		sinon.restore();
	});

	it("should propagate errors via callback function (TypeError)", async function() {
		const compiler = new Compiler({
			options: {
				rootPaths: ["foo"]
			},
			fileUtils: {},
		});

		const file = "someFile";
		const currentFileInfo = {
			currentDirectory: undefined // This will cause a TypeError when calling path.join
		};
		const handleDataAndCallCallback = sinon.stub();
		const callback = sinon.stub();

		await compiler.fnFileHandler(file, currentFileInfo, handleDataAndCallCallback, callback);

		assert.equal(handleDataAndCallCallback.callCount, 0);
		assert.equal(callback.callCount, 1);
		assert.equal(callback.getCall(0).args.length, 1);
		assert.equal(callback.getCall(0).args[0].name, "TypeError");
		assert.equal(callback.getCall(0).args[0].message,
			`The "path" argument must be of type string. Received undefined`
		);
	});
	it("should propagate errors via callback function (File not found)", async function() {
		const compiler = new Compiler({
			options: {
				rootPaths: ["foo"]
			},
			fileUtils: {
				readFile: sinon.stub().resolves(null)
			},
		});

		const file = "someFile";
		const currentFileInfo = {
			currentDirectory: "someFolder"
		};
		const handleDataAndCallCallback = sinon.stub();
		const callback = sinon.stub();

		await compiler.fnFileHandler(file, currentFileInfo, handleDataAndCallCallback, callback);

		assert.equal(handleDataAndCallCallback.callCount, 0);
		assert.equal(callback.callCount, 1);
		assert.equal(callback.getCall(0).args.length, 1);
		assert.equal(callback.getCall(0).args[0].type, "File");
		assert.equal(callback.getCall(0).args[0].message,
			`Could not find file at path 'someFolder/someFile'`
		);
	});
	it("should propagate errors via callback function (error within handleDataAndCallCallback)", async function() {
		const compiler = new Compiler({
			options: {
				rootPaths: ["foo"]
			},
			fileUtils: {
				readFile: sinon.stub().resolves({
					path: "", content: ""
				})
			},
		});

		const file = "someFile";
		const currentFileInfo = {
			currentDirectory: "someFolder"
		};
		const handleDataAndCallCallback = sinon.stub().throws(new Error("Error from handleDataAndCallCallback"));
		const callback = sinon.stub();

		await compiler.fnFileHandler(file, currentFileInfo, handleDataAndCallCallback, callback);

		assert.equal(handleDataAndCallCallback.callCount, 1);
		assert.equal(callback.callCount, 1);
		assert.equal(callback.getCall(0).args.length, 1);
		assert.equal(callback.getCall(0).args[0].message,
			`Error from handleDataAndCallCallback`
		);
	});
});
<commit_msg>[INTERNAL] Remove check for TypeError name<commit_after>/* eslint-env mocha */

const assert = require("assert");
const sinon = require("sinon");

// tested module
const Compiler = require("../../lib/Compiler");

describe("Compiler#createFileHandler", function() {
	before(() => {
		sinon.stub(console, "log");
	});
	after(() => {
		sinon.restore();
	});

	it("should propagate errors via callback function (TypeError)", async function() {
		const compiler = new Compiler({
			options: {
				rootPaths: ["foo"]
			},
			fileUtils: {},
		});

		const file = "someFile";
		const currentFileInfo = {
			currentDirectory: undefined // This will cause a TypeError when calling path.join
		};
		const handleDataAndCallCallback = sinon.stub();
		const callback = sinon.stub();

		await compiler.fnFileHandler(file, currentFileInfo, handleDataAndCallCallback, callback);

		assert.equal(handleDataAndCallCallback.callCount, 0);
		assert.equal(callback.callCount, 1);
		assert.equal(callback.getCall(0).args.length, 1);
		assert.equal(callback.getCall(0).args[0].message,
			`The "path" argument must be of type string. Received undefined`
		);
	});
	it("should propagate errors via callback function (File not found)", async function() {
		const compiler = new Compiler({
			options: {
				rootPaths: ["foo"]
			},
			fileUtils: {
				readFile: sinon.stub().resolves(null)
			},
		});

		const file = "someFile";
		const currentFileInfo = {
			currentDirectory: "someFolder"
		};
		const handleDataAndCallCallback = sinon.stub();
		const callback = sinon.stub();

		await compiler.fnFileHandler(file, currentFileInfo, handleDataAndCallCallback, callback);

		assert.equal(handleDataAndCallCallback.callCount, 0);
		assert.equal(callback.callCount, 1);
		assert.equal(callback.getCall(0).args.length, 1);
		assert.equal(callback.getCall(0).args[0].type, "File");
		assert.equal(callback.getCall(0).args[0].message,
			`Could not find file at path 'someFolder/someFile'`
		);
	});
	it("should propagate errors via callback function (error within handleDataAndCallCallback)", async function() {
		const compiler = new Compiler({
			options: {
				rootPaths: ["foo"]
			},
			fileUtils: {
				readFile: sinon.stub().resolves({
					path: "", content: ""
				})
			},
		});

		const file = "someFile";
		const currentFileInfo = {
			currentDirectory: "someFolder"
		};
		const handleDataAndCallCallback = sinon.stub().throws(new Error("Error from handleDataAndCallCallback"));
		const callback = sinon.stub();

		await compiler.fnFileHandler(file, currentFileInfo, handleDataAndCallCallback, callback);

		assert.equal(handleDataAndCallCallback.callCount, 1);
		assert.equal(callback.callCount, 1);
		assert.equal(callback.getCall(0).args.length, 1);
		assert.equal(callback.getCall(0).args[0].message,
			`Error from handleDataAndCallCallback`
		);
	});
});
<|endoftext|>


<commit_before>'use strict';

module.exports = {
  options: {
    verbose: true,
    enableSourceMaps: false
    // enableTargetBabelrc: true
  },
  modifyWebpackConfig({
    env: {
      target, // the target 'node' or 'web'
      dev, // is this a development build? true or false
    },
    webpackConfig, // the created webpack config
    webpackObject, // the imported webpack node module
    options: {
      razzleOptions, // the modified options passed to Razzle in the `options` key in `razzle.config.js` (options: { key: 'value'})
      webpackOptions, // the modified options that was used to configure webpack/ webpack loaders and plugins
    },
    paths, // the modified paths that will be used by Razzle.
  }) {
  //
  // webpackConfig.resolve.alias = Object.assign(webpackConfig.resolve.alias, {
  //   'rax': 'rax/es',
  //   'rax-view': 'rax-view/es',
  //   'rax-image': 'rax-image/es',
  //   'rax-text': 'rax-text/es',
  //   'rax-button': 'rax-button/es'
  // });
  return webpackConfig;
  },
  modifyWebpackOptions({
    env: {
      target, // the target 'node' or 'web'
      dev, // is this a development build? true or false
    },
    webpackObject, // the imported webpack node module
    options: {
      razzleOptions, // the modified options passed to Razzle in the `options` key in `razzle.config.js` (options: { key: 'value'})
      webpackOptions, // the modified options that was used to configure webpack/ webpack loaders and plugins
    },
    paths, // the modified paths that will be used by Razzle.
  }) {
    // webpackOptions.babelRule.include = webpackOptions.babelRule.include.concat([
    //   /rax/
    // ])
    webpackOptions.notNodeExternalResMatch = (request, context) => {
      return request.contains('rax')
    };
    return webpackOptions;
  },
};
<commit_msg>examples(with-rax): use indexOf instead of contains<commit_after>'use strict';

module.exports = {
  options: {
    verbose: true,
    enableSourceMaps: false
    // enableTargetBabelrc: true
  },
  modifyWebpackConfig({
    env: {
      target, // the target 'node' or 'web'
      dev, // is this a development build? true or false
    },
    webpackConfig, // the created webpack config
    webpackObject, // the imported webpack node module
    options: {
      razzleOptions, // the modified options passed to Razzle in the `options` key in `razzle.config.js` (options: { key: 'value'})
      webpackOptions, // the modified options that was used to configure webpack/ webpack loaders and plugins
    },
    paths, // the modified paths that will be used by Razzle.
  }) {
  //
  // webpackConfig.resolve.alias = Object.assign(webpackConfig.resolve.alias, {
  //   'rax': 'rax/es',
  //   'rax-view': 'rax-view/es',
  //   'rax-image': 'rax-image/es',
  //   'rax-text': 'rax-text/es',
  //   'rax-button': 'rax-button/es'
  // });
  return webpackConfig;
  },
  modifyWebpackOptions({
    env: {
      target, // the target 'node' or 'web'
      dev, // is this a development build? true or false
    },
    webpackObject, // the imported webpack node module
    options: {
      razzleOptions, // the modified options passed to Razzle in the `options` key in `razzle.config.js` (options: { key: 'value'})
      webpackOptions, // the modified options that was used to configure webpack/ webpack loaders and plugins
    },
    paths, // the modified paths that will be used by Razzle.
  }) {
    // webpackOptions.babelRule.include = webpackOptions.babelRule.include.concat([
    //   /rax/
    // ])
    webpackOptions.notNodeExternalResMatch = (request, context) => {
      return request.indexOf('rax') !== -1
    };
    return webpackOptions;
  },
};
<|endoftext|>


<commit_before>var liffUpConfig = {
    template:{
        open : '{{',
        close: '}}',
        clean: '[^]+'
    }
};
// DOMContentLoaded is fired once the document has been loaded and parsed,
// but without waiting for other external resources to load (css/images/etc)
// That makes the app more responsive and perceived as faster.
// https://developer.mozilla.org/Web/Reference/Events/DOMContentLoaded
window.addEventListener('DOMContentLoaded', function() {

    // We'll ask the browser to use strict code to help us catch errors earlier.
    // https://developer.mozilla.org/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode
    'use strict';

    // setup variables
    // element variables
    var rowTemplate = document.querySelector("#row-template");
    var accountsTable = document.querySelector("#account_list");
    var accountList = accountsTable.querySelector('tbody');
    // result variables

    // attach function calls on elements' event

    // We want to wait until the localisations library has loaded all the strings.
    // So we'll tell it to let us know once it's ready.
    navigator.mozL10n.once( localisations_load_callback );
});

// ---
// define functions here
function localisations_load_callback () {
    // navigator.mozL10n.language.code = 'ph';
    console.log('localisations loaded');
}

function render_row ( accountObj ) {
    var templateString,
        renderedString;

    // get needs
    templateString = rowTemplate.innerHTML;

    // set defaults
    accountObj = set_row_defaults( accountObj );

    renderedString = replace_values( templateString, accountObj );
    return renderedString;
}

function set_row_defaults ( accountObj ) {
    // for (var i = accountObj.length - 1; i >= 0; i--) {
        // accountObj['account'] = /[0-9\.\-]/.match( accountObj['account'] )
        // accountObj['amount'] = /[0-9\.\-]/.match( accountObj['amount'] )
        // accountObj['description'] = /[0-9\.\-]/.match( accountObj['description'] )
        // accountObj['balance'] = /[0-9\.\-]/.match( accountObj['balance'] )
    // };
    return accountObj;
}

function replace_values ( templateString, listObj ) {
    /***
        this function renders the template string dynamically.
        uses the passed data object's keys as target for replacement
    */

    // get keys to iterate on replacements
    var listObjKeys = Object.keys( listObj );
    var renderedString = templateString;

    // iterate
    for (var i = listObjKeys.length - 1; i >= 0; i--) {
        // create regex obj
        var dataIndexRegex = RegExp( "{{" + listObjKeys[i] + "}}" );
        // get value to replace
        var dataValue = listObj[ listObjKeys[i] ];

        // execute replace
        renderedString = renderedString.replace( dataIndexRegex, dataValue );
    };
    return renderedString;
}

function append_row ( accountObj ) {
    // append row by manipulating innerHTML
    // if it is better to use appendChild, replace this implementation
    // replace implementation if the rows has events

}
<commit_msg>align variable declaration<commit_after>var liffUpConfig = {
    template:{
        open : '{{',
        close: '}}',
        clean: '[^]+'
    }
};
// DOMContentLoaded is fired once the document has been loaded and parsed,
// but without waiting for other external resources to load (css/images/etc)
// That makes the app more responsive and perceived as faster.
// https://developer.mozilla.org/Web/Reference/Events/DOMContentLoaded
window.addEventListener('DOMContentLoaded', function() {

    // We'll ask the browser to use strict code to help us catch errors earlier.
    // https://developer.mozilla.org/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode
    'use strict';

    // setup variables
    // element variables
    var rowTemplate   = document.querySelector("#row-template");
    var accountsTable = document.querySelector("#account_list");
    var accountList   = accountsTable.querySelector('tbody');
    var accountForm   = document.querySelector('#account_form');
    // result variables

    // attach function calls on elements' event

    // We want to wait until the localisations library has loaded all the strings.
    // So we'll tell it to let us know once it's ready.
    navigator.mozL10n.once( localisations_load_callback );
});

// ---
// define functions here
function localisations_load_callback () {
    // navigator.mozL10n.language.code = 'ph';
    console.log('localisations loaded');
}

function render_row ( accountObj ) {
    var templateString,
        renderedString;

    // get needs
    templateString = rowTemplate.innerHTML;

    // set defaults
    accountObj = set_row_defaults( accountObj );

    renderedString = replace_values( templateString, accountObj );
    return renderedString;
}

function set_row_defaults ( accountObj ) {
    // for (var i = accountObj.length - 1; i >= 0; i--) {
        // accountObj['account'] = /[0-9\.\-]/.match( accountObj['account'] )
        // accountObj['amount'] = /[0-9\.\-]/.match( accountObj['amount'] )
        // accountObj['description'] = /[0-9\.\-]/.match( accountObj['description'] )
        // accountObj['balance'] = /[0-9\.\-]/.match( accountObj['balance'] )
    // };
    return accountObj;
}

function replace_values ( templateString, listObj ) {
    /***
        this function renders the template string dynamically.
        uses the passed data object's keys as target for replacement
    */

    // get keys to iterate on replacements
    var listObjKeys = Object.keys( listObj );
    var renderedString = templateString;

    // iterate
    for (var i = listObjKeys.length - 1; i >= 0; i--) {
        // create regex obj
        var dataIndexRegex = RegExp( "{{" + listObjKeys[i] + "}}" );
        // get value to replace
        var dataValue = listObj[ listObjKeys[i] ];

        // execute replace
        renderedString = renderedString.replace( dataIndexRegex, dataValue );
    };
    return renderedString;
}

function append_row ( accountObj ) {
    // append row by manipulating innerHTML
    // if it is better to use appendChild, replace this implementation
    // replace implementation if the rows has events

}
<|endoftext|>


<commit_before>var validate = require('./validator').merchandisher;

it("#01. SPKDoc should valid", function(){
    var SPKDoc = require('../src/merchandiser/spk-doc');
    validate.SPKDoc=(new SPKDoc());
}) <commit_msg>change merchandisher become merchandiser<commit_after>var validate = require('./validator').merchandiser;

it("#01. SPKDoc should valid", function(){
    var SPKDoc = require('../src/merchandiser/spk-doc');
    validate.SPKDoc=(new SPKDoc());
}) <|endoftext|>


<commit_before>const IDBRequest = require('./living/generated/IDBRequest')
const DOMException = require('domexception/lib/DOMException')
const IDBCursorWithValue = require('./living/generated/IDBCursorWithValue')
const IDBKeyRange = require('./living/generated/IDBKeyRange')

const webidl = require('./living/generated/utils')
const convert = require('./convert')

class IDBIndexImpl {
    // TODO Make loop a property of transaction.
    constructor (globalObject, [], { index, objectStore }) {
        this._globalObject = globalObject
        this._index = index
        // Different instances of index need different instances of keyPath, but
        // keyPath must be the same each time the accessor is called.
        this.keyPath = JSON.parse(JSON.stringify(this._index.keyPath))
        this.objectStore = objectStore
    }

    get name () {
        return this._index.name
    }

    set name (to) {
        if (this.objectStore._schema.isDeleted(this._index)) {
            throw DOMException.create(this._globalObject, [ 'TODO: message', 'InvalidStateError' ], {})
        }
        if (this.objectStore._transaction.mode != 'versionchange') {
            throw DOMException.create(this._globalObject, [ 'TODO: message', 'InvalidStateError' ], {})
        }
        if (this.objectStore._transaction._state != 'active') {
            throw DOMException.create(this._globalObject, [ 'TODO: message', 'TransactionInactiveError' ], {})
        }
        if (this._index.name != to) {
            if (to in this.objectStore._store.index) {
                throw DOMException.create(this._globalObject, [ 'TODO: message', 'ConstraintError' ], {})
            }
            this.objectStore._schema.renameIndex(this.objectStore._store.id, this._index.name, to)
            this.objectStore._transaction._queue.push({
                method: 'rename',
                type: 'index',
                store: JSON.parse(JSON.stringify(this.objectStore._store)),
                index: JSON.parse(JSON.stringify(this._index))
            })
        }
    }

    get multiEntry () {
        return this._index.multiEntry
    }

    get unique () {
        return this._index.unique
    }

    get (query) {
        const request = IDBRequest.createImpl(this._globalObject, [], {})
        if (this.objectStore._schema.isDeleted(this._index)) {
            throw DOMException.create(this._globalObject, [ 'TODO: message', 'InvalidStateError' ], {})
        }
        if (this.objectStore._transaction._state != 'active') {
            throw DOMException.create(this._globalObject, [ 'TODO: message', 'TransactionInactiveError' ], {})
        }
        if (!(query instanceof this._globalObject.IDBKeyRange)) {
            query = webidl.implForWrapper(this._globalObject.IDBKeyRange.only(query))
        }
        this.objectStore._transaction._queue.push({
            method: 'get',
            type: 'index',
            key: false,
            store: this.objectStore._store,
            index: this._index,
            query: query,
            request: request
        })
        return request
    }

    getKey (query) {
        const request = IDBRequest.createImpl(this._globalObject, [], {})
        if (this.objectStore._schema.isDeleted(this._index)) {
            throw DOMException.create(this._globalObject, [ 'TODO: message', 'InvalidStateError' ], {})
        }
        if (this.objectStore._transaction._state != 'active') {
            throw DOMException.create(this._globalObject, [ 'TODO: message', 'TransactionInactiveError' ], {})
        }
        if (!(query instanceof this._globalObject.IDBKeyRange)) {
            query = webidl.implForWrapper(this._globalObject.IDBKeyRange.only(query))
        }
        this.objectStore._transaction._queue.push({
            method: 'get',
            type: 'index',
            key: true,
            store: this.objectStore._store,
            index: this._index,
            query,
            request
        })
        return request
    }

    getAll (query, count = null) {
        if (this.objectStore._schema.isDeleted(this._index)) {
            throw DOMException.create(this._globalObject, [ 'TODO: message', 'InvalidStateError' ], {})
        }
        if (this.objectStore._transaction._state != 'active') {
            throw DOMException.create(this._globalObject, [ 'TODO: message', 'TransactionInactiveError' ], {})
        }
        if (query == null) {
            query = IDBKeyRange.createImpl(this._globalObject, [ null, null ], {})
        } else if (! (query instanceof this._globalObject.IDBKeyRange)) {
            query = this._globalObject.IDBKeyRange.only(convert.key(this._globalObject, query))
        }
        const request = IDBRequest.createImpl(this._globalObject, {}, { parent: this._transaction, source: this })
        this.objectStore._transaction._queue.push({
            method: 'getAll',
            type: 'index',
            request: request,
            store: JSON.parse(JSON.stringify(this.objectStore._store)),
            index: this._index,
            query: query,
            count: count,
            key: false
        })
        return request
    }

    getAllKeys (query, count = null) {
        if (this.objectStore._schema.isDeleted(this._index)) {
            throw DOMException.create(this._globalObject, [ 'TODO: message', 'InvalidStateError' ], {})
        }
        if (this.objectStore._transaction._state != 'active') {
            throw DOMException.create(this._globalObject, [ 'TODO: message', 'TransactionInactiveError' ], {})
        }
        if (query == null) {
            query = IDBKeyRange.createImpl(this._globalObject, [ null, null ], {})
        } else if (! (query instanceof this._globalObject.IDBKeyRange)) {
            query = this._globalObject.IDBKeyRange.only(convert.key(this._globalObject, query))
        }
        const request = IDBRequest.createImpl(this._globalObject, {}, { parent: this._transaction, source: this })
        this.objectStore._transaction._queue.push({
            method: 'getAll',
            type: 'index',
            request: request,
            store: JSON.parse(JSON.stringify(this.objectStore._store)),
            index: this._index,
            query: query,
            count: count,
            key: true
        })
        return request
    }

    count (query) {
        if (this.objectStore._schema.isDeleted(this._index)) {
            throw DOMException.create(this._globalObject, [ 'TODO: message', 'InvalidStateError' ], {})
        }
        if (this.objectStore._transaction._state != 'active') {
            throw DOMException.create(this._globalObject, [ 'TODO: message', 'TransactionInactiveError' ], {})
        }
        if (query == null) {
            query = IDBKeyRange.createImpl(this._globalObject, [ null, null ], {})
        } else if (! (query instanceof this._globalObject.IDBKeyRange)) {
            query = this._globalObject.IDBKeyRange.only(convert.key(this._globalObject, query))
        }
        const request = IDBRequest.createImpl(this._globalObject, [], { parent: this._transaction, source: this })
        this.objectStore._transaction._queue.push({
            method: 'count',
            type: 'index',
            request: request,
            store: JSON.parse(JSON.stringify(this.objectStore._store)),
            index: this._index,
            query: query
        })
        return request
    }

    openCursor (query, direction = 'next') {
        if (this.objectStore._schema.isDeleted(this._index)) {
            throw DOMException.create(this._globalObject, [ 'TODO: message', 'InvalidStateError' ], {})
        }
        if (this.objectStore._transaction._state != 'active') {
            throw DOMException.create(this._globalObject, [ 'TODO: message', 'TransactionInactiveError' ], {})
        }
        if (query != null && ! (query instanceof this.objectStore._globalObject.IDBKeyRange))  {
            query = this._globalObject.IDBKeyRange.only(query)
        }
        const request = IDBRequest.createImpl(this._globalObject, [], { parent: this._transaction })
        const cursor = IDBCursorWithValue.createImpl(this._globalObject, [], {
            type: 'index',
            hello: 'world',
            transaction: this.objectStore._transaction,
            request: request,
            store: this.objectStore._store,
            index: this._index,
            query: query,
            source: this
        })
        request._result = webidl.wrapperForImpl(cursor)
        this.objectStore._transaction._queue.push({
            method: 'openCursor',
            type: 'index',
            store: JSON.parse(JSON.stringify(this.objectStore._store)),
            index: this._index,
            request: request,
            cursor: cursor,
            direction: direction,
            source: this
        })
        return request
    }

    openKeyCursor (query, direction = 'next') {
        if (this.objectStore._schema.isDeleted(this._index)) {
            throw DOMException.create(this._globalObject, [ 'TODO: message', 'InvalidStateError' ], {})
        }
        if (this.objectStore._transaction._state != 'active') {
            throw DOMException.create(this._globalObject, [ 'TODO: message', 'TransactionInactiveError' ], {})
        }
        if (query != null && ! (query instanceof this.objectStore._globalObject.IDBKeyRange))  {
            query = this._globalObject.IDBKeyRange.only(query)
        }
        const request = IDBRequest.createImpl(this._globalObject, [], { parent: this._transaction })
        const cursor = IDBCursor.createImpl(this._globalObject, [], {
            type: 'index',
            hello: 'world',
            transaction: this.objectStore._transaction,
            request: request,
            store: this.objectStore._store,
            index: this._index,
            query: query,
            source: this
        })
        request._result = webidl.wrapperForImpl(cursor)
        this.objectStore._transaction._queue.push({
            method: 'openCursor',
            type: 'index',
            store: JSON.parse(JSON.stringify(this.objectStore._store)),
            index: this._index,
            request: request,
            cursor: cursor,
            direction: direction,
            source: this
        })
        return request
    }
}

module.exports = { implementation: IDBIndexImpl }
<commit_msg>DRY.<commit_after>const IDBRequest = require('./living/generated/IDBRequest')
const IDBKeyRange = require('./living/generated/IDBKeyRange')
const DOMException = require('domexception/lib/DOMException')
const IDBCursor = require('./living/generated/IDBCursor')
const IDBCursorWithValue = require('./living/generated/IDBCursorWithValue')

const webidl = require('./living/generated/utils')
const convert = require('./convert')

class IDBIndexImpl {
    // TODO Make loop a property of transaction.
    constructor (globalObject, [], { index, objectStore }) {
        this._globalObject = globalObject
        this._index = index
        // Different instances of index need different instances of keyPath, but
        // keyPath must be the same each time the accessor is called.
        this.keyPath = JSON.parse(JSON.stringify(this._index.keyPath))
        this.objectStore = objectStore
    }

    get name () {
        return this._index.name
    }

    set name (to) {
        if (this.objectStore._schema.isDeleted(this._index)) {
            throw DOMException.create(this._globalObject, [ 'TODO: message', 'InvalidStateError' ], {})
        }
        if (this.objectStore._transaction.mode != 'versionchange') {
            throw DOMException.create(this._globalObject, [ 'TODO: message', 'InvalidStateError' ], {})
        }
        if (this.objectStore._transaction._state != 'active') {
            throw DOMException.create(this._globalObject, [ 'TODO: message', 'TransactionInactiveError' ], {})
        }
        if (this._index.name != to) {
            if (to in this.objectStore._store.index) {
                throw DOMException.create(this._globalObject, [ 'TODO: message', 'ConstraintError' ], {})
            }
            this.objectStore._schema.renameIndex(this.objectStore._store.id, this._index.name, to)
            this.objectStore._transaction._queue.push({
                method: 'rename',
                type: 'index',
                store: JSON.parse(JSON.stringify(this.objectStore._store)),
                index: JSON.parse(JSON.stringify(this._index))
            })
        }
    }

    get multiEntry () {
        return this._index.multiEntry
    }

    get unique () {
        return this._index.unique
    }

    get (query) {
        const request = IDBRequest.createImpl(this._globalObject, [], {})
        if (this.objectStore._schema.isDeleted(this._index)) {
            throw DOMException.create(this._globalObject, [ 'TODO: message', 'InvalidStateError' ], {})
        }
        if (this.objectStore._transaction._state != 'active') {
            throw DOMException.create(this._globalObject, [ 'TODO: message', 'TransactionInactiveError' ], {})
        }
        if (!(query instanceof this._globalObject.IDBKeyRange)) {
            query = webidl.implForWrapper(this._globalObject.IDBKeyRange.only(query))
        }
        this.objectStore._transaction._queue.push({
            method: 'get',
            type: 'index',
            key: false,
            store: this.objectStore._store,
            index: this._index,
            query: query,
            request: request
        })
        return request
    }

    getKey (query) {
        const request = IDBRequest.createImpl(this._globalObject, [], {})
        if (this.objectStore._schema.isDeleted(this._index)) {
            throw DOMException.create(this._globalObject, [ 'TODO: message', 'InvalidStateError' ], {})
        }
        if (this.objectStore._transaction._state != 'active') {
            throw DOMException.create(this._globalObject, [ 'TODO: message', 'TransactionInactiveError' ], {})
        }
        if (!(query instanceof this._globalObject.IDBKeyRange)) {
            query = webidl.implForWrapper(this._globalObject.IDBKeyRange.only(query))
        }
        this.objectStore._transaction._queue.push({
            method: 'get',
            type: 'index',
            key: true,
            store: this.objectStore._store,
            index: this._index,
            query,
            request
        })
        return request
    }

    getAll (query, count = null) {
        if (this.objectStore._schema.isDeleted(this._index)) {
            throw DOMException.create(this._globalObject, [ 'TODO: message', 'InvalidStateError' ], {})
        }
        if (this.objectStore._transaction._state != 'active') {
            throw DOMException.create(this._globalObject, [ 'TODO: message', 'TransactionInactiveError' ], {})
        }
        if (query == null) {
            query = IDBKeyRange.createImpl(this._globalObject, [ null, null ], {})
        } else if (! (query instanceof this._globalObject.IDBKeyRange)) {
            query = this._globalObject.IDBKeyRange.only(convert.key(this._globalObject, query))
        }
        const request = IDBRequest.createImpl(this._globalObject, {}, { parent: this._transaction, source: this })
        this.objectStore._transaction._queue.push({
            method: 'getAll',
            type: 'index',
            request: request,
            store: JSON.parse(JSON.stringify(this.objectStore._store)),
            index: this._index,
            query: query,
            count: count,
            key: false
        })
        return request
    }

    getAllKeys (query, count = null) {
        if (this.objectStore._schema.isDeleted(this._index)) {
            throw DOMException.create(this._globalObject, [ 'TODO: message', 'InvalidStateError' ], {})
        }
        if (this.objectStore._transaction._state != 'active') {
            throw DOMException.create(this._globalObject, [ 'TODO: message', 'TransactionInactiveError' ], {})
        }
        if (query == null) {
            query = IDBKeyRange.createImpl(this._globalObject, [ null, null ], {})
        } else if (! (query instanceof this._globalObject.IDBKeyRange)) {
            query = this._globalObject.IDBKeyRange.only(convert.key(this._globalObject, query))
        }
        const request = IDBRequest.createImpl(this._globalObject, {}, { parent: this._transaction, source: this })
        this.objectStore._transaction._queue.push({
            method: 'getAll',
            type: 'index',
            request: request,
            store: JSON.parse(JSON.stringify(this.objectStore._store)),
            index: this._index,
            query: query,
            count: count,
            key: true
        })
        return request
    }

    count (query) {
        if (this.objectStore._schema.isDeleted(this._index)) {
            throw DOMException.create(this._globalObject, [ 'TODO: message', 'InvalidStateError' ], {})
        }
        if (this.objectStore._transaction._state != 'active') {
            throw DOMException.create(this._globalObject, [ 'TODO: message', 'TransactionInactiveError' ], {})
        }
        if (query == null) {
            query = IDBKeyRange.createImpl(this._globalObject, [ null, null ], {})
        } else if (! (query instanceof this._globalObject.IDBKeyRange)) {
            query = this._globalObject.IDBKeyRange.only(convert.key(this._globalObject, query))
        }
        const request = IDBRequest.createImpl(this._globalObject, [], { parent: this._transaction, source: this })
        this.objectStore._transaction._queue.push({
            method: 'count',
            type: 'index',
            request: request,
            store: JSON.parse(JSON.stringify(this.objectStore._store)),
            index: this._index,
            query: query
        })
        return request
    }

    _openCursor (Cursor, query, direction = 'next') {
        if (this.objectStore._schema.isDeleted(this._index)) {
            throw DOMException.create(this._globalObject, [ 'TODO: message', 'InvalidStateError' ], {})
        }
        if (this.objectStore._transaction._state != 'active') {
            throw DOMException.create(this._globalObject, [ 'TODO: message', 'TransactionInactiveError' ], {})
        }
        if (query != null && ! (query instanceof this.objectStore._globalObject.IDBKeyRange))  {
            query = this._globalObject.IDBKeyRange.only(query)
        }
        const request = IDBRequest.createImpl(this._globalObject, [], { parent: this._transaction })
        const cursor = Cursor.createImpl(this._globalObject, [], {
            type: 'index',
            hello: 'world',
            transaction: this.objectStore._transaction,
            request: request,
            store: this.objectStore._store,
            index: this._index,
            query: query,
            source: this
        })
        request._result = webidl.wrapperForImpl(cursor)
        this.objectStore._transaction._queue.push({
            method: 'openCursor',
            type: 'index',
            store: JSON.parse(JSON.stringify(this.objectStore._store)),
            index: this._index,
            request: request,
            cursor: cursor,
            direction: direction,
            source: this
        })
        return request
    }

    openCursor (query, direction = 'next') {
        return this._openCursor(IDBCursorWithValue, query, direction)
    }

    openKeyCursor (query, direction = 'next') {
        return this._openCursor(IDBCursor, query, direction)
    }
}

module.exports = { implementation: IDBIndexImpl }
<|endoftext|>


<commit_before>//地図表示の設定
var map = L.map('map',{
    center: [34.393073, 132.452091],
    zoom: 16,
});

//子供食堂(CC:Childlen's Cafeteria)
var CC1 = L.marker([34.392499, 132.475163]).bindPopup('青い鳥'),
    CC2 = L.marker([34.361024, 132.463756]).bindPopup('くるり食堂');

var map = L.layerGroup([CC1, CC2]);

//タイルレイヤの表示
L.tileLayer(
    'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
    {
        attribution: 'Map data © OpenStreetMap',
    }
).addTo(map);<commit_msg>mapの2重定義？<commit_after>//地図表示の設定
var map = L.map('map',{
    center: [34.393073, 132.452091],
    zoom: 16,
});

//子供食堂(CC:Childlen's Cafeteria)
var CC1 = L.marker([34.392499, 132.475163]).bindPopup('青い鳥'),
    CC2 = L.marker([34.361024, 132.463756]).bindPopup('くるり食堂');

map = L.layerGroup([CC1, CC2]);

//タイルレイヤの表示
L.tileLayer(
    'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
    {
        attribution: 'Map data © OpenStreetMap',
    }
).addTo(map);<|endoftext|>


<commit_before>TOAST_TIME = 1400
CARD_SWITCH_TIME = 500
NULL_URL = "none"

function apiKeyObtained(){
	Materialize.toast("We've got an APIKey!", TOAST_TIME);
	startApp();
}

function copyURLToClipboard(url) {
	if (url != NULL_URL) {
		var copyFrom = $('<textarea/>');
		copyFrom.text(url);
		$('body').append(copyFrom);
		copyFrom.select();
		document.execCommand('copy');
		copyFrom.remove();
		Materialize.toast('Copied!', TOAST_TIME);
	} else {
		Materialize.toast('Nothing to copy!', TOAST_TIME);
	}
}

function setCardName(newName){
	$("#short-url-container").animate({
		left: parseInt(-$("#content-wrapper").outerWidth())
	}, CARD_SWITCH_TIME, "easeInOutQuad", function(){
		try {
			var obj = JSON.parse(newName);
		} catch (e) {
			localStorage.shortenedURL = localStorage.shortenedURLreq;
			localStorage.shortURL = newName;

			$('#short-url').text(localStorage.shortURL);
			$('#shortened-url').text(localStorage.shortenedURL);

			return;
		}

		$('#short-url').text("Error!");
		$('#shortened-url').text(obj.fields[0].code);

		localStorage.shortenedURL = NULL_URL;
		localStorage.shortURL = NULL_URL;
	});

	$("#short-url-container").animate({
		left: parseInt($("#content-wrapper").outerWidth())
	}, 0, "easeInOutQuad", function(){

		$("#short-url-container").animate({
			left: 0
		}, CARD_SWITCH_TIME, "easeInOutQuad", function(){});

	});
}

function startApp(){

	// localStorage.removeItem("APIKey");

	if (localStorage.validAPIKey == 1 && localStorage.getItem("APIKey") != null && localStorage.APIKey!='Unauthorized'){
		console.log(localStorage.APIKey);

		$("#non-api-content-wrapper").hide();
		$("#content-wrapper").show();

		/*Init text fields*/
		if (localStorage.shortURL && localStorage.shortURL != NULL_URL){
			$('#short-url').text(localStorage.shortURL);
			$('#shortened-url').text(localStorage.shortenedURL);
		} else {
			$('#short-url').text("http://x.co/shortlnk");
			$('#shortened-url').text("http://www.full.link.example");
		}

		/*BTNs init*/

		$('select').material_select();
		$('#shorten-button').click(function(){
			shortenCurrentURL(setCardName);
		});

		$('#custom-shorten-button').click(function(){
			customShortenCurrentURL(setCardName, decodeURI($('#custom-url-form').serialize()));
		});

		$('#short-url').click(function(){
			copyURLToClipboard(localStorage.shortURL);
		});

		$('#clipboard-copy-btn').click(function(){
			copyURLToClipboard(localStorage.shortURL);
		});

		/*External APIs*/

		$('#fb-share-btn').click(function(){
			fbShare(localStorage.shortURL);
		});

		$('#tw-share-btn').click(function(){
			twShare(localStorage.shortURL);
		});

		$('#in-share-btn').click(function(){
			inShare(localStorage.shortURL);
		});

	} else chrome.tabs.query({active:true, currentWindow:true}, function(tabs){
		$('#manual-api-key-btn').click(function(){
			console.log = $('#manual-api-key-form').serialize();
			apiKeyObtained();
		});

		$("#non-api-content-wrapper").show();
		requestAPIKey(apiKeyObtained);
	});

}

document.addEventListener('DOMContentLoaded', function(){
	$("#content-wrapper").hide();
	$("#non-api-content-wrapper").hide();
	startApp();
});<commit_msg>startApp single trigger<commit_after>TOAST_TIME = 1400
CARD_SWITCH_TIME = 500
NULL_URL = "none"

function apiKeyObtained(){
	if (localStorage.appStarted == 0){
		localStorage.appStarted = 1;
		Materialize.toast("We've got an APIKey!", TOAST_TIME);
		startApp();
	}
}

function copyURLToClipboard(url) {
	if (url != NULL_URL) {
		var copyFrom = $('<textarea/>');
		copyFrom.text(url);
		$('body').append(copyFrom);
		copyFrom.select();
		document.execCommand('copy');
		copyFrom.remove();
		Materialize.toast('Copied!', TOAST_TIME);
	} else {
		Materialize.toast('Nothing to copy!', TOAST_TIME);
	}
}

function setCardName(newName){
	$("#short-url-container").animate({
		left: parseInt(-$("#content-wrapper").outerWidth())
	}, CARD_SWITCH_TIME, "easeInOutQuad", function(){
		try {
			var obj = JSON.parse(newName);
		} catch (e) {
			localStorage.shortenedURL = localStorage.shortenedURLreq;
			localStorage.shortURL = newName;

			$('#short-url').text(localStorage.shortURL);
			$('#shortened-url').text(localStorage.shortenedURL);

			return;
		}

		$('#short-url').text("Error!");
		$('#shortened-url').text(obj.fields[0].code);

		localStorage.shortenedURL = NULL_URL;
		localStorage.shortURL = NULL_URL;
	});

	$("#short-url-container").animate({
		left: parseInt($("#content-wrapper").outerWidth())
	}, 0, "easeInOutQuad", function(){

		$("#short-url-container").animate({
			left: 0
		}, CARD_SWITCH_TIME, "easeInOutQuad", function(){});

	});
}

function startApp(){

	// localStorage.removeItem("APIKey");

	if (localStorage.validAPIKey == 1 && localStorage.getItem("APIKey") != null && localStorage.APIKey!='Unauthorized'){
		console.log(localStorage.APIKey);

		$("#non-api-content-wrapper").hide();
		$("#content-wrapper").show();

		/*Init text fields*/
		if (localStorage.shortURL && localStorage.shortURL != NULL_URL){
			$('#short-url').text(localStorage.shortURL);
			$('#shortened-url').text(localStorage.shortenedURL);
		} else {
			$('#short-url').text("http://x.co/shortlnk");
			$('#shortened-url').text("http://www.full.link.example");
		}

		/*BTNs init*/

		$('select').material_select();
		$('#shorten-button').click(function(){
			shortenCurrentURL(setCardName);
		});

		$('#custom-shorten-button').click(function(){
			customShortenCurrentURL(setCardName, decodeURI($('#custom-url-form').serialize()));
		});

		$('#short-url').click(function(){
			copyURLToClipboard(localStorage.shortURL);
		});

		$('#clipboard-copy-btn').click(function(){
			copyURLToClipboard(localStorage.shortURL);
		});

		/*External APIs*/

		$('#fb-share-btn').click(function(){
			fbShare(localStorage.shortURL);
		});

		$('#tw-share-btn').click(function(){
			twShare(localStorage.shortURL);
		});

		$('#in-share-btn').click(function(){
			inShare(localStorage.shortURL);
		});

	} else chrome.tabs.query({active:true, currentWindow:true}, function(tabs){
		$('#manual-api-key-btn').click(function(){
			console.log = $('#manual-api-key-form').serialize();
			apiKeyObtained();
		});

		$("#non-api-content-wrapper").show();
		requestAPIKey(apiKeyObtained);
	});

}

document.addEventListener('DOMContentLoaded', function(){
	$("#content-wrapper").hide();
	$("#non-api-content-wrapper").hide();
	localStorage.appStarted = 0;
	startApp();
});<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

const {classes: Cc, interfaces: Ci, utils: Cu} = Components;

Cu.import('resource://gre/modules/XPCOMUtils.jsm');
XPCOMUtils.defineLazyModuleGetter(this, 'console',
  'resource://gre/modules/Console.jsm');
XPCOMUtils.defineLazyModuleGetter(this, 'CustomizableUI',
  'resource:///modules/CustomizableUI.jsm');
XPCOMUtils.defineLazyModuleGetter(this, 'ObjectUtils',
  'resource://gre/modules/ObjectUtils.jsm');
XPCOMUtils.defineLazyModuleGetter(this, 'PrivateBrowsingUtils',
  'resource://gre/modules/PrivateBrowsingUtils.jsm');
XPCOMUtils.defineLazyModuleGetter(this, 'Services',
  'resource://gre/modules/Services.jsm');
XPCOMUtils.defineLazyModuleGetter(this, 'WindowWatcher',
  'chrome://universalsearch-lib/content/window-watcher.js');

const EXPORTED_SYMBOLS = ['UniversalSearch'];

function Search() {
  /*
  The main UniversalSearch module manages the add-on lifecycle, loading and
  unloading code when the add-on is installed, enabled, disabled, or
  uninstalled. It's invoked by the bootstrap.js file.
  */

  // Due to limitations in passing objects between window contexts, we have to
  // bind the callbacks passed to WindowWatcher.start().
  this.loadIntoWindow = this.loadIntoWindow.bind(this);
  this.unloadFromWindow = this.unloadFromWindow.bind(this);
  this.onError = this.onError.bind(this);
}

Search.prototype = {
  load: function() {
    WindowWatcher.start(this.loadIntoWindow, this.unloadFromWindow, this.onError);
  },

  unload: function() {
    WindowWatcher.stop();
  },

  loadIntoWindow: function(win) {
    // Sets the app global per window.
    win.universalSearch = win.universalSearch || {}

    win.universalSearch.prefs = this._initializePrefs();
    win.universalSearch.urlbarPrefs = this._initializeUrlbarPrefs();
    this._hideSearchBar(win);
    this._loadStyleSheets(win);
    this._loadScripts(win);
    this._startApp(win);

  },

  unloadFromWindow: function(win) {

    // NOTE: order matters here: _restoreSearchBar needs `win.universalSearch`
    // to be defined, while _stopApp deletes `win.universalSearch`.
    this._restoreSearchBar(win);
    this._stopApp(win);
    this._unloadScripts(win);
    this._unloadStyleSheets(win);

    // Delete any remaining references.
    delete win.universalSearch;
  },

  _initializePrefs: function() {
    return Services.prefs.getBranch('extensions.universalsearch.');
  },

  _initializeUrlbarPrefs: function() {
    return Services.prefs.getBranch('browser.urlbar.');
  },

  _hideSearchBar: function(win) {
    // If the search bar is visible, note the location and hide it.
    const searchBarLocation = CustomizableUI.getPlacementOfWidget('search-container');
    if (searchBarLocation) {
      win.universalSearch.searchBarLocation = searchBarLocation;
      CustomizableUI.removeWidgetFromArea('search-container');
    }
  },

  _restoreSearchBar: function(win) {
    // If the search bar was originally visible, restore it.
    if (win.universalSearch.searchBarLocation) {
      const loc = win.universalSearch.searchBarLocation;
      CustomizableUI.addWidgetToArea('search-container', loc.area, loc.position);
    }
  },

  _loadStyleSheets: function(win) {
    const doc = win.document;
    const docEl = doc.documentElement;

    // Insert the main stylesheet with platform-independent styles.
    const stylesheet = doc.createElementNS('http://www.w3.org/1999/xhtml', 'h:link');
    stylesheet.href = 'chrome://universalsearch-skin/content/style.css';
    stylesheet.rel = 'stylesheet';
    stylesheet.type = 'text/css';
    stylesheet.id = 'universal-search-stylesheet';
    stylesheet.style.display = 'none';

    // Insert platform-specific styles, using `Services.appinfo.OS` to
    // distinguish between Mac OS ('Darwin'), Linux, and Windows ('WINNT').
    const stylesheetPlatform = doc.createElementNS('http://www.w3.org/1999/xhtml', 'h:link');
    stylesheetPlatform.rel = 'stylesheet';
    stylesheetPlatform.type = 'text/css';
    stylesheetPlatform.id = 'universal-search-stylesheet-platform';
    stylesheetPlatform.style.display = 'none';

    if (Services.appinfo.OS === 'Darwin') {
      stylesheetPlatform.href = 'chrome://universalsearch-skin/content/style-osx.css';
    } else if (Services.appinfo.OS === 'WINNT') {
      stylesheetPlatform.href = 'chrome://universalsearch-skin/content/style-windows.css';
    } else {
      stylesheetPlatform.href = 'chrome://universalsearch-skin/content/style-linux.css';
    }

    docEl.appendChild(stylesheet);
    docEl.appendChild(stylesheetPlatform);
  },

  _unloadStyleSheets: function(win) {
    const doc = win.document;
    const docEl = win.document.documentElement;

    const stylesheet = doc.getElementById('universal-search-stylesheet');
    const stylesheetPlatform = doc.getElementById('universal-search-stylesheet-platform');

    docEl.removeChild(stylesheet);
    docEl.removeChild(stylesheetPlatform);
  },

  _loadScripts: function(win) {
    // Note that we load the scripts into the app namespace, to ease cleanup.
    // Each module's EXPORTED_SYMBOLS will be properties on win.universalSearch.
    Cu.import('resource://gre/modules/Console.jsm', win.universalSearch);
    Cu.import('resource://gre/modules/Services.jsm', win.universalSearch);

    Cu.import('chrome://universalsearch-lib/content/events.js', win.universalSearch);
    Cu.import('chrome://universalsearch-lib/content/metrics.js', win.universalSearch);
    Cu.import('chrome://universalsearch-lib/content/recommendation-server.js', win.universalSearch);
    Cu.import('chrome://universalsearch-lib/content/movie-transform.js', win.universalSearch);
    Cu.import('chrome://universalsearch-lib/content/tld-transform.js', win.universalSearch);
    Cu.import('chrome://universalsearch-lib/content/wikipedia-transform.js', win.universalSearch);

    Cu.import('chrome://universalsearch-ui/content/highlight-manager.js', win.universalSearch);
    Cu.import('chrome://universalsearch-ui/content/popup.js', win.universalSearch);
    Cu.import('chrome://universalsearch-ui/content/recommendation.js', win.universalSearch);
    Cu.import('chrome://universalsearch-ui/content/recommendation-row.js', win.universalSearch);
    Cu.import('chrome://universalsearch-ui/content/urlbar.js', win.universalSearch);
  },

  _unloadScripts: function(win) {
    // Unload scripts from the namespace. Not clear on whether this is necessary
    // if we just delete win.universalSearch.
    Cu.unload('chrome://universalsearch-ui/content/highlight-manager.js', win.universalSearch);
    Cu.unload('chrome://universalsearch-ui/content/popup.js', win.universalSearch);
    Cu.unload('chrome://universalsearch-ui/content/recommendation.js', win.universalSearch);
    Cu.unload('chrome://universalsearch-ui/content/recommendation-row.js', win.universalSearch);
    Cu.unload('chrome://universalsearch-ui/content/urlbar.js', win.universalSearch);

    Cu.unload('chrome://universalsearch-lib/content/wikipedia-transform.js', win.universalSearch);
    Cu.unload('chrome://universalsearch-lib/content/tld-transform.js', win.universalSearch);
    Cu.unload('chrome://universalsearch-lib/content/movie-transform.js', win.universalSearch);
    Cu.unload('chrome://universalsearch-lib/content/recommendation-server.js', win.universalSearch);
    Cu.unload('chrome://universalsearch-lib/content/metrics.js', win.universalSearch);
    Cu.unload('chrome://universalsearch-lib/content/events.js', win.universalSearch);

    // NOTE: we can't unload Console.jsm until the last console call.
    // It's unloaded by the caller (the unloadFromWindow method).
  },

  _startApp: function(win) {
    // Initialize modules and assemble the object graph.

    const app = win.universalSearch;

    app.events = new app.Events();
    app.events.init();

    app.recommendationServer = new app.RecommendationServer({
      events: app.events,
      xhr: Cc['@mozilla.org/xmlextras/xmlhttprequest;1'],
      timeout: 1000,
      // app.console is provided by loading Console.jsm
      console: app.console,
      prefs: app.prefs,
      urlbarPrefs: app.urlbarPrefs
    });
    app.recommendationServer.init();

    // NOTE: order matters here, the urlbar and highlightManager both need
    // to be handed the initialized recommendation
    app.recommendation = new app.Recommendation({
      eTLD: Services.eTLD,
      events: app.events,
      io: Services.io,
      objectUtils: ObjectUtils,
      win: win,
      RecommendationRow: app.RecommendationRow,
      tldTransform: app.tldTransform,
      wikipediaTransform: app.wikipediaTransform,
      movieTransform: app.movieTransform
    });
    app.recommendation.init();

    app.urlbar = new app.Urlbar({
      win: win,
      events: app.events,
      privateBrowsingUtils: PrivateBrowsingUtils,
      recommendation: app.recommendation
    });
    app.urlbar.init();

    app.popup = new app.Popup({
      win: win,
      events: app.events
    });
    app.popup.init();

    app.highlightManager = new app.HighlightManager({
      win: win,
      events: app.events,
      recommendation: app.recommendation,
      popup: app.popup
    });
    app.highlightManager.init();

    app.metrics = new app.Metrics({
      events: app.events,
      popup: app.popup,
      recommendation: app.recommendation,
      win: win,
      observerService: Cc["@mozilla.org/observer-service;1"]
                       .getService(Ci.nsIObserverService)
    });
    app.metrics.init();
  },

  _stopApp: function(win) {
    const app = win.universalSearch;

    app.popup.destroy();
    app.recommendation.destroy();
    app.highlightManager.destroy();
    app.urlbar.destroy();
    app.recommendationServer.destroy();
    app.events.destroy();

    delete win.universalSearch;
  },

  onError: function(msg) {
    console.error(msg);
  }
};

// Expose a singleton, since we only need one of these for the add-on.
const UniversalSearch = new Search();
<commit_msg>Only unload scripts once<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

const {classes: Cc, interfaces: Ci, utils: Cu} = Components;

Cu.import('resource://gre/modules/XPCOMUtils.jsm');
XPCOMUtils.defineLazyModuleGetter(this, 'console',
  'resource://gre/modules/Console.jsm');
XPCOMUtils.defineLazyModuleGetter(this, 'CustomizableUI',
  'resource:///modules/CustomizableUI.jsm');
XPCOMUtils.defineLazyModuleGetter(this, 'ObjectUtils',
  'resource://gre/modules/ObjectUtils.jsm');
XPCOMUtils.defineLazyModuleGetter(this, 'PrivateBrowsingUtils',
  'resource://gre/modules/PrivateBrowsingUtils.jsm');
XPCOMUtils.defineLazyModuleGetter(this, 'Services',
  'resource://gre/modules/Services.jsm');
XPCOMUtils.defineLazyModuleGetter(this, 'WindowWatcher',
  'chrome://universalsearch-lib/content/window-watcher.js');

const EXPORTED_SYMBOLS = ['UniversalSearch'];

function Search() {
  /*
  The main UniversalSearch module manages the add-on lifecycle, loading and
  unloading code when the add-on is installed, enabled, disabled, or
  uninstalled. It's invoked by the bootstrap.js file.
  */

  // Due to limitations in passing objects between window contexts, we have to
  // bind the callbacks passed to WindowWatcher.start().
  this.loadIntoWindow = this.loadIntoWindow.bind(this);
  this.unloadFromWindow = this.unloadFromWindow.bind(this);
  this.onError = this.onError.bind(this);
}

Search.prototype = {
  load: function() {
    WindowWatcher.start(this.loadIntoWindow, this.unloadFromWindow, this.onError);
  },

  unload: function() {
    // Scripts only need to be unloaded once, globally.
    this._unloadScripts();

    // The running code and styles must be removed from each window.
    WindowWatcher.stop();
  },

  loadIntoWindow: function(win) {
    // Sets the app global per window.
    win.universalSearch = win.universalSearch || {}

    win.universalSearch.prefs = this._initializePrefs();
    win.universalSearch.urlbarPrefs = this._initializeUrlbarPrefs();
    this._hideSearchBar(win);
    this._loadStyleSheets(win);
    this._loadScripts(win);
    this._startApp(win);

  },

  unloadFromWindow: function(win) {

    // NOTE: order matters here: _restoreSearchBar needs `win.universalSearch`
    // to be defined, while _stopApp deletes `win.universalSearch`.
    this._restoreSearchBar(win);
    this._stopApp(win);
    this._unloadStyleSheets(win);

    // Delete any remaining references.
    delete win.universalSearch;
  },

  _initializePrefs: function() {
    return Services.prefs.getBranch('extensions.universalsearch.');
  },

  _initializeUrlbarPrefs: function() {
    return Services.prefs.getBranch('browser.urlbar.');
  },

  _hideSearchBar: function(win) {
    // If the search bar is visible, note the location and hide it.
    const searchBarLocation = CustomizableUI.getPlacementOfWidget('search-container');
    if (searchBarLocation) {
      win.universalSearch.searchBarLocation = searchBarLocation;
      CustomizableUI.removeWidgetFromArea('search-container');
    }
  },

  _restoreSearchBar: function(win) {
    // If the search bar was originally visible, restore it.
    if (win.universalSearch.searchBarLocation) {
      const loc = win.universalSearch.searchBarLocation;
      CustomizableUI.addWidgetToArea('search-container', loc.area, loc.position);
    }
  },

  _loadStyleSheets: function(win) {
    const doc = win.document;
    const docEl = doc.documentElement;

    // Insert the main stylesheet with platform-independent styles.
    const stylesheet = doc.createElementNS('http://www.w3.org/1999/xhtml', 'h:link');
    stylesheet.href = 'chrome://universalsearch-skin/content/style.css';
    stylesheet.rel = 'stylesheet';
    stylesheet.type = 'text/css';
    stylesheet.id = 'universal-search-stylesheet';
    stylesheet.style.display = 'none';

    // Insert platform-specific styles, using `Services.appinfo.OS` to
    // distinguish between Mac OS ('Darwin'), Linux, and Windows ('WINNT').
    const stylesheetPlatform = doc.createElementNS('http://www.w3.org/1999/xhtml', 'h:link');
    stylesheetPlatform.rel = 'stylesheet';
    stylesheetPlatform.type = 'text/css';
    stylesheetPlatform.id = 'universal-search-stylesheet-platform';
    stylesheetPlatform.style.display = 'none';

    if (Services.appinfo.OS === 'Darwin') {
      stylesheetPlatform.href = 'chrome://universalsearch-skin/content/style-osx.css';
    } else if (Services.appinfo.OS === 'WINNT') {
      stylesheetPlatform.href = 'chrome://universalsearch-skin/content/style-windows.css';
    } else {
      stylesheetPlatform.href = 'chrome://universalsearch-skin/content/style-linux.css';
    }

    docEl.appendChild(stylesheet);
    docEl.appendChild(stylesheetPlatform);
  },

  _unloadStyleSheets: function(win) {
    const doc = win.document;
    const docEl = win.document.documentElement;

    const stylesheet = doc.getElementById('universal-search-stylesheet');
    const stylesheetPlatform = doc.getElementById('universal-search-stylesheet-platform');

    docEl.removeChild(stylesheet);
    docEl.removeChild(stylesheetPlatform);
  },

  _loadScripts: function(win) {
    // Note that we load the scripts into the app namespace, to ease cleanup.
    // Each module's EXPORTED_SYMBOLS will be properties on win.universalSearch.
    Cu.import('resource://gre/modules/Console.jsm', win.universalSearch);
    Cu.import('resource://gre/modules/Services.jsm', win.universalSearch);

    Cu.import('chrome://universalsearch-lib/content/events.js', win.universalSearch);
    Cu.import('chrome://universalsearch-lib/content/metrics.js', win.universalSearch);
    Cu.import('chrome://universalsearch-lib/content/recommendation-server.js', win.universalSearch);
    Cu.import('chrome://universalsearch-lib/content/movie-transform.js', win.universalSearch);
    Cu.import('chrome://universalsearch-lib/content/tld-transform.js', win.universalSearch);
    Cu.import('chrome://universalsearch-lib/content/wikipedia-transform.js', win.universalSearch);

    Cu.import('chrome://universalsearch-ui/content/highlight-manager.js', win.universalSearch);
    Cu.import('chrome://universalsearch-ui/content/popup.js', win.universalSearch);
    Cu.import('chrome://universalsearch-ui/content/recommendation.js', win.universalSearch);
    Cu.import('chrome://universalsearch-ui/content/recommendation-row.js', win.universalSearch);
    Cu.import('chrome://universalsearch-ui/content/urlbar.js', win.universalSearch);
  },

  _unloadScripts: function(win) {
    // Unload scripts from the namespace. Not clear on whether this is necessary
    // if we just delete win.universalSearch.

    // NOTE: ONLY unload scripts that are packaged inside this addon (#268).
    // NEVER unload scripts used globally by Firefox.
    Cu.unload('chrome://universalsearch-ui/content/highlight-manager.js', win.universalSearch);
    Cu.unload('chrome://universalsearch-ui/content/popup.js', win.universalSearch);
    Cu.unload('chrome://universalsearch-ui/content/recommendation.js', win.universalSearch);
    Cu.unload('chrome://universalsearch-ui/content/recommendation-row.js', win.universalSearch);
    Cu.unload('chrome://universalsearch-ui/content/urlbar.js', win.universalSearch);

    Cu.unload('chrome://universalsearch-lib/content/wikipedia-transform.js', win.universalSearch);
    Cu.unload('chrome://universalsearch-lib/content/tld-transform.js', win.universalSearch);
    Cu.unload('chrome://universalsearch-lib/content/movie-transform.js', win.universalSearch);
    Cu.unload('chrome://universalsearch-lib/content/recommendation-server.js', win.universalSearch);
    Cu.unload('chrome://universalsearch-lib/content/metrics.js', win.universalSearch);
    Cu.unload('chrome://universalsearch-lib/content/events.js', win.universalSearch);
  },

  _startApp: function(win) {
    // Initialize modules and assemble the object graph.

    const app = win.universalSearch;

    app.events = new app.Events();
    app.events.init();

    app.recommendationServer = new app.RecommendationServer({
      events: app.events,
      xhr: Cc['@mozilla.org/xmlextras/xmlhttprequest;1'],
      timeout: 1000,
      // app.console is provided by loading Console.jsm
      console: app.console,
      prefs: app.prefs,
      urlbarPrefs: app.urlbarPrefs
    });
    app.recommendationServer.init();

    // NOTE: order matters here, the urlbar and highlightManager both need
    // to be handed the initialized recommendation
    app.recommendation = new app.Recommendation({
      eTLD: Services.eTLD,
      events: app.events,
      io: Services.io,
      objectUtils: ObjectUtils,
      win: win,
      RecommendationRow: app.RecommendationRow,
      tldTransform: app.tldTransform,
      wikipediaTransform: app.wikipediaTransform,
      movieTransform: app.movieTransform
    });
    app.recommendation.init();

    app.urlbar = new app.Urlbar({
      win: win,
      events: app.events,
      privateBrowsingUtils: PrivateBrowsingUtils,
      recommendation: app.recommendation
    });
    app.urlbar.init();

    app.popup = new app.Popup({
      win: win,
      events: app.events
    });
    app.popup.init();

    app.highlightManager = new app.HighlightManager({
      win: win,
      events: app.events,
      recommendation: app.recommendation,
      popup: app.popup
    });
    app.highlightManager.init();

    app.metrics = new app.Metrics({
      events: app.events,
      popup: app.popup,
      recommendation: app.recommendation,
      win: win,
      observerService: Cc["@mozilla.org/observer-service;1"]
                       .getService(Ci.nsIObserverService)
    });
    app.metrics.init();
  },

  _stopApp: function(win) {
    const app = win.universalSearch;

    app.popup.destroy();
    app.recommendation.destroy();
    app.highlightManager.destroy();
    app.urlbar.destroy();
    app.recommendationServer.destroy();
    app.events.destroy();

    delete win.universalSearch;
  },

  onError: function(msg) {
    console.error(msg);
  }
};

// Expose a singleton, since we only need one of these for the add-on.
const UniversalSearch = new Search();
<|endoftext|>


<commit_before>'use strict'

const t = require('tap')
const test = t.test
const FindMyWay = require('../')

test('the router is an object with methods', t => {
  t.plan(3)

  const findMyWay = FindMyWay()

  t.is(typeof findMyWay.on, 'function')
  t.is(typeof findMyWay.lookup, 'function')
  t.is(typeof findMyWay.find, 'function')
})

test('register a route', t => {
  t.plan(1)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/test', () => {
    t.ok('inside the handler')
  })

  findMyWay.lookup({ method: 'GET', url: '/test' }, null)
})

test('default route', t => {
  t.plan(1)

  const findMyWay = FindMyWay({
    defaultRoute: () => {
      t.ok('inside the default route')
    }
  })

  findMyWay.lookup({ method: 'GET', url: '/test' }, null)
})

test('async handler', t => {
  t.plan(1)

  const findMyWay = FindMyWay({
    async: true
  })

  findMyWay.on('GET', '/test', (req, res, params) => {
    t.ok('inside async handler')
  })

  findMyWay.lookup({ method: 'GET', url: '/test' }, null)
})

test('parametric route', t => {
  t.plan(1)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/test/:id', (req, res, params) => {
    t.is(params.id, 'hello')
  })

  findMyWay.lookup({ method: 'GET', url: '/test/hello' }, null)
})

test('multiple parametric route', t => {
  t.plan(2)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/test/:id', (req, res, params) => {
    t.is(params.id, 'hello')
  })

  findMyWay.on('GET', '/other-test/:id', (req, res, params) => {
    t.is(params.id, 'world')
  })

  findMyWay.lookup({ method: 'GET', url: '/test/hello' }, null)
  findMyWay.lookup({ method: 'GET', url: '/other-test/world' }, null)
})

test('multiple parametric route with the same prefix', t => {
  t.plan(2)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/test/:id', (req, res, params) => {
    t.is(params.id, 'hello')
  })

  findMyWay.on('GET', '/test/:id/world', (req, res, params) => {
    t.is(params.id, 'world')
  })

  findMyWay.lookup({ method: 'GET', url: '/test/hello' }, null)
  findMyWay.lookup({ method: 'GET', url: '/test/world/world' }, null)
})

test('nested parametric route', t => {
  t.plan(2)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/test/:hello/test/:world', (req, res, params) => {
    t.is(params.hello, 'hello')
    t.is(params.world, 'world')
  })

  findMyWay.lookup({ method: 'GET', url: '/test/hello/test/world' }, null)
})

test('nested parametric route with same prefix', t => {
  t.plan(3)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/test', (req, res, params) => {
    t.ok('inside route')
  })

  findMyWay.on('GET', '/test/:hello/test/:world', (req, res, params) => {
    t.is(params.hello, 'hello')
    t.is(params.world, 'world')
  })

  findMyWay.lookup({ method: 'GET', url: '/test' }, null)
  findMyWay.lookup({ method: 'GET', url: '/test/hello/test/world' }, null)
})

test('long route', t => {
  t.plan(1)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/abc/def/ghi/lmn/opq/rst/uvz', (req, res, params) => {
    t.ok('inside long path')
  })

  findMyWay.lookup({ method: 'GET', url: '/abc/def/ghi/lmn/opq/rst/uvz' }, null)
})

test('long parametric route', t => {
  t.plan(3)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/abc/:def/ghi/:lmn/opq/:rst/uvz', (req, res, params) => {
    t.is(params.def, 'def')
    t.is(params.lmn, 'lmn')
    t.is(params.rst, 'rst')
  })

  findMyWay.lookup({ method: 'GET', url: '/abc/def/ghi/lmn/opq/rst/uvz' }, null)
})

test('long parametric route with common prefix', t => {
  t.plan(9)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/', (req, res, params) => {
    throw new Error('I shoul not be here')
  })

  findMyWay.on('GET', '/abc', (req, res, params) => {
    throw new Error('I shoul not be here')
  })

  findMyWay.on('GET', '/abc/:def', (req, res, params) => {
    t.is(params.def, 'def')
  })

  findMyWay.on('GET', '/abc/:def/ghi/:lmn', (req, res, params) => {
    t.is(params.def, 'def')
    t.is(params.lmn, 'lmn')
  })

  findMyWay.on('GET', '/abc/:def/ghi/:lmn/opq/:rst', (req, res, params) => {
    t.is(params.def, 'def')
    t.is(params.lmn, 'lmn')
    t.is(params.rst, 'rst')
  })

  findMyWay.on('GET', '/abc/:def/ghi/:lmn/opq/:rst/uvz', (req, res, params) => {
    t.is(params.def, 'def')
    t.is(params.lmn, 'lmn')
    t.is(params.rst, 'rst')
  })

  findMyWay.lookup({ method: 'GET', url: '/abc/def' }, null)
  findMyWay.lookup({ method: 'GET', url: '/abc/def/ghi/lmn' }, null)
  findMyWay.lookup({ method: 'GET', url: '/abc/def/ghi/lmn/opq/rst' }, null)
  findMyWay.lookup({ method: 'GET', url: '/abc/def/ghi/lmn/opq/rst/uvz' }, null)
})

test('wildcard', t => {
  t.plan(1)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/test/*', (req, res, params) => {
    t.is(params['*'], 'hello')
  })

  findMyWay.lookup({ method: 'GET', url: '/test/hello' }, null)
})

test('find should return the route', t => {
  t.plan(1)
  const findMyWay = FindMyWay()
  const fn = () => {}

  findMyWay.on('GET', '/test', fn)

  t.deepEqual(findMyWay.find('GET', '/test'), { handler: fn, params: {}, store: null })
})

test('find should return the route with params', t => {
  t.plan(1)
  const findMyWay = FindMyWay()
  const fn = () => {}

  findMyWay.on('GET', '/test/:id', fn)

  t.deepEqual(findMyWay.find('GET', '/test/hello'), { handler: fn, params: { id: 'hello' }, store: null })
})

test('find should return a null handler if the route does not exist', t => {
  t.plan(1)
  const findMyWay = FindMyWay()

  // t.deepEqual(findMyWay.find('GET', '/test'), { handler: null, params: [], store: null })
  t.deepEqual(findMyWay.find('GET', '/test'), null)
})

test('should decode the uri - parametric', t => {
  t.plan(1)
  const findMyWay = FindMyWay()
  const fn = () => {}

  findMyWay.on('GET', '/test/:id', fn)

  t.deepEqual(findMyWay.find('GET', '/test/he%2Fllo'), { handler: fn, params: { id: 'he/llo' }, store: null })
})

test('should decode the uri - wildcard', t => {
  t.plan(1)
  const findMyWay = FindMyWay()
  const fn = () => {}

  findMyWay.on('GET', '/test/*', fn)

  t.deepEqual(findMyWay.find('GET', '/test/he%2Fllo'), { handler: fn, params: { '*': 'he/llo' }, store: null })
})
<commit_msg>Updatd test<commit_after>'use strict'

const t = require('tap')
const test = t.test
const FindMyWay = require('../')

test('the router is an object with methods', t => {
  t.plan(3)

  const findMyWay = FindMyWay()

  t.is(typeof findMyWay.on, 'function')
  t.is(typeof findMyWay.lookup, 'function')
  t.is(typeof findMyWay.find, 'function')
})

test('register a route', t => {
  t.plan(1)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/test', () => {
    t.ok('inside the handler')
  })

  findMyWay.lookup({ method: 'GET', url: '/test' }, null)
})

test('default route', t => {
  t.plan(1)

  const findMyWay = FindMyWay({
    defaultRoute: () => {
      t.ok('inside the default route')
    }
  })

  findMyWay.lookup({ method: 'GET', url: '/test' }, null)
})

test('parametric route', t => {
  t.plan(1)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/test/:id', (req, res, params) => {
    t.is(params.id, 'hello')
  })

  findMyWay.lookup({ method: 'GET', url: '/test/hello' }, null)
})

test('multiple parametric route', t => {
  t.plan(2)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/test/:id', (req, res, params) => {
    t.is(params.id, 'hello')
  })

  findMyWay.on('GET', '/other-test/:id', (req, res, params) => {
    t.is(params.id, 'world')
  })

  findMyWay.lookup({ method: 'GET', url: '/test/hello' }, null)
  findMyWay.lookup({ method: 'GET', url: '/other-test/world' }, null)
})

test('multiple parametric route with the same prefix', t => {
  t.plan(2)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/test/:id', (req, res, params) => {
    t.is(params.id, 'hello')
  })

  findMyWay.on('GET', '/test/:id/world', (req, res, params) => {
    t.is(params.id, 'world')
  })

  findMyWay.lookup({ method: 'GET', url: '/test/hello' }, null)
  findMyWay.lookup({ method: 'GET', url: '/test/world/world' }, null)
})

test('nested parametric route', t => {
  t.plan(2)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/test/:hello/test/:world', (req, res, params) => {
    t.is(params.hello, 'hello')
    t.is(params.world, 'world')
  })

  findMyWay.lookup({ method: 'GET', url: '/test/hello/test/world' }, null)
})

test('nested parametric route with same prefix', t => {
  t.plan(3)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/test', (req, res, params) => {
    t.ok('inside route')
  })

  findMyWay.on('GET', '/test/:hello/test/:world', (req, res, params) => {
    t.is(params.hello, 'hello')
    t.is(params.world, 'world')
  })

  findMyWay.lookup({ method: 'GET', url: '/test' }, null)
  findMyWay.lookup({ method: 'GET', url: '/test/hello/test/world' }, null)
})

test('long route', t => {
  t.plan(1)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/abc/def/ghi/lmn/opq/rst/uvz', (req, res, params) => {
    t.ok('inside long path')
  })

  findMyWay.lookup({ method: 'GET', url: '/abc/def/ghi/lmn/opq/rst/uvz' }, null)
})

test('long parametric route', t => {
  t.plan(3)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/abc/:def/ghi/:lmn/opq/:rst/uvz', (req, res, params) => {
    t.is(params.def, 'def')
    t.is(params.lmn, 'lmn')
    t.is(params.rst, 'rst')
  })

  findMyWay.lookup({ method: 'GET', url: '/abc/def/ghi/lmn/opq/rst/uvz' }, null)
})

test('long parametric route with common prefix', t => {
  t.plan(9)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/', (req, res, params) => {
    throw new Error('I shoul not be here')
  })

  findMyWay.on('GET', '/abc', (req, res, params) => {
    throw new Error('I shoul not be here')
  })

  findMyWay.on('GET', '/abc/:def', (req, res, params) => {
    t.is(params.def, 'def')
  })

  findMyWay.on('GET', '/abc/:def/ghi/:lmn', (req, res, params) => {
    t.is(params.def, 'def')
    t.is(params.lmn, 'lmn')
  })

  findMyWay.on('GET', '/abc/:def/ghi/:lmn/opq/:rst', (req, res, params) => {
    t.is(params.def, 'def')
    t.is(params.lmn, 'lmn')
    t.is(params.rst, 'rst')
  })

  findMyWay.on('GET', '/abc/:def/ghi/:lmn/opq/:rst/uvz', (req, res, params) => {
    t.is(params.def, 'def')
    t.is(params.lmn, 'lmn')
    t.is(params.rst, 'rst')
  })

  findMyWay.lookup({ method: 'GET', url: '/abc/def' }, null)
  findMyWay.lookup({ method: 'GET', url: '/abc/def/ghi/lmn' }, null)
  findMyWay.lookup({ method: 'GET', url: '/abc/def/ghi/lmn/opq/rst' }, null)
  findMyWay.lookup({ method: 'GET', url: '/abc/def/ghi/lmn/opq/rst/uvz' }, null)
})

test('wildcard', t => {
  t.plan(1)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/test/*', (req, res, params) => {
    t.is(params['*'], 'hello')
  })

  findMyWay.lookup(
    { method: 'GET', url: '/test/hello' },
    null
  )
})

test('find should return the route', t => {
  t.plan(1)
  const findMyWay = FindMyWay()
  const fn = () => {}

  findMyWay.on('GET', '/test', fn)

  t.deepEqual(
    findMyWay.find('GET', '/test'),
    { handler: fn, params: {}, store: null }
  )
})

test('find should return the route with params', t => {
  t.plan(1)
  const findMyWay = FindMyWay()
  const fn = () => {}

  findMyWay.on('GET', '/test/:id', fn)

  t.deepEqual(
    findMyWay.find('GET', '/test/hello'),
    { handler: fn, params: { id: 'hello' }, store: null }
  )
})

test('find should return a null handler if the route does not exist', t => {
  t.plan(1)
  const findMyWay = FindMyWay()

  t.deepEqual(
    findMyWay.find('GET', '/test'),
    null
  )
})

test('should decode the uri - parametric', t => {
  t.plan(1)
  const findMyWay = FindMyWay()
  const fn = () => {}

  findMyWay.on('GET', '/test/:id', fn)

  t.deepEqual(
    findMyWay.find('GET', '/test/he%2Fllo'),
    { handler: fn, params: { id: 'he/llo' }, store: null }
  )
})

test('should decode the uri - wildcard', t => {
  t.plan(1)
  const findMyWay = FindMyWay()
  const fn = () => {}

  findMyWay.on('GET', '/test/*', fn)

  t.deepEqual(
    findMyWay.find('GET', '/test/he%2Fllo'),
    { handler: fn, params: { '*': 'he/llo' }, store: null }
  )
})

test('safe decodeURIComponent', t => {
  t.plan(1)
  const findMyWay = FindMyWay()
  const fn = () => {}

  findMyWay.on('GET', '/test/:id', fn)

  t.deepEqual(
    findMyWay.find('GET', '/test/hel%"Flo'),
    null
  )
})

test('safe decodeURIComponent - nested route', t => {
  t.plan(1)
  const findMyWay = FindMyWay()
  const fn = () => {}

  findMyWay.on('GET', '/test/hello/world/:id/blah', fn)

  t.deepEqual(
    findMyWay.find('GET', '/test/hello/world/hel%"Flo/blah'),
    null
  )
})

test('safe decodeURIComponent - wildcard', t => {
  t.plan(1)
  const findMyWay = FindMyWay()
  const fn = () => {}

  findMyWay.on('GET', '/test/*', fn)

  t.deepEqual(
    findMyWay.find('GET', '/test/hel%"Flo'),
    null
  )
})
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict'

var fs = require('fs')
var RPCClient = require('bitcoin').Client
var bitcoinjs = require('bitcoinjs-lib')
var leveldown = require('leveldown')
var levelup = require('levelup')
var through2 = require('through2')
var ProgressBar = require('progress')

/* read config and create rpc client */
var config = JSON.parse(fs.readFileSync(process.argv[2]))
var rpc = new RPCClient(config)

/* download block */
function getBlock (height, cb) {
  rpc.getBlockHash(height, function (err, blockHash) {
    if (err) return cb(err)
    rpc.getBlock(blockHash, false, function (err, block) {
      if (err) return cb(err)
      cb(null, bitcoinjs.Block.fromBuffer(new Buffer(block, 'hex')))
    })
  })
}

/* update UTXOs for block */
function updateUTXOs (db, height, block, cb) {
  var batch = db.batch()
  block.transactions.forEach(function (tx, txIndex) {
    var inputs = txIndex > 0 ? tx.ins : tx.ins.slice(1)
    inputs.forEach(function (txInput) {
      batch.del(txInput.hash.reverse().toString('hex') + ':' + txInput.index)
    })
    var txId = tx.getId()
    tx.outs.forEach(function (txOutput, outputIndex) {
      batch.put(txId + ':' + outputIndex, {
        value: txOutput.value,
        script: txOutput.script.toString('hex'),
        height: height
      })
    })
  })
  batch.write(cb)
}

/* handle transactions from blocks [height, lastHeight] */
function handleBlocks (db, height, lastHeight, bar, cb) {
  getBlock(height, function (err, block) {
    if (err) return cb(err)
    updateUTXOs(db, height, block, function (err) {
      if (err) return cb(err)
      if (height === lastHeight) return cb(null)
      bar.tick()
      handleBlocks(db, height + 1, lastHeight, bar, cb)
    })
  })
}

/* create json db from leveldb */
function createJSON (db, cb) {
  var isFirst = true

  var writeStream = fs.createWriteStream(config.jsondb, { flags: 'w' })
  writeStream.write('[', function (err) {
    if (err) return cb(err)
    db.createReadStream()
      .pipe(through2({ objectMode: true },
        function (chunk, enc, cb) {
          var dataKey = chunk.key.split(':')
          var data = JSON.stringify({
            txId: dataKey[0],
            outputIndex: dataKey[1],
            value: chunk.value.value,
            script: chunk.value.script,
            height: chunk.value.height
          })

          if (isFirst) {
            isFirst = false
            this.push(data)
          } else {
            this.push(',' + data)
          }

          cb(null)
        },
        function (cb) {
          this.push(']')
          cb(null)
        }
      ))
      .pipe(writeStream)
      .on('error', function (err) {
        cb(err)
      })
      .on('close', function () {
        cb(null)
      })
  })
}

/* open db */
var db = levelup(config.leveldb, { db: leveldown, valueEncoding: 'json' })

/* create progress bar */
var bar = new ProgressBar(':percent (:current/:total), :elapseds elapsed, eta :etas', {
  total: config.lastHeight
})
bar.curr = config.firstHeight

/* run process */
handleBlocks(db, config.firstHeight, config.lastHeight, bar, function (err) {
  if (err) throw err
  console.log('Creating JSON database...')
  createJSON(db, function (err) {
    if (err) throw err
    db.close(function (err) {
      if (err) throw err
    })
  })
})
<commit_msg>Fix generator.js<commit_after>#!/usr/bin/env node
'use strict'

var fs = require('fs')
var RPCClient = require('bitcoin').Client
var bitcoinjs = require('bitcoinjs-lib')
var leveldown = require('leveldown')
var levelup = require('levelup')
var through2 = require('through2')
var ProgressBar = require('progress')

/* read config and create rpc client */
var config = JSON.parse(fs.readFileSync(process.argv[2]))
var rpc = new RPCClient(config)

/* download block */
function getBlock (height, cb) {
  rpc.getBlockHash(height, function (err, blockHash) {
    if (err) return cb(err)
    rpc.getBlock(blockHash, false, function (err, block) {
      if (err) return cb(err)
      cb(null, bitcoinjs.Block.fromBuffer(new Buffer(block, 'hex')))
    })
  })
}

/* update UTXOs for block */
function updateUTXOs (db, height, block, cb) {
  var batch = db.batch()
  block.transactions.forEach(function (tx, txIndex) {
    var txId = tx.getId()
    var inputs = txIndex > 0 ? tx.ins : tx.ins.slice(1)
    inputs.forEach(function (txInput) {
      batch.del(txInput.hash.reverse().toString('hex') + ':' + txInput.index)
    })
    tx.outs.forEach(function (txOutput, outputIndex) {
      batch.put(txId + ':' + outputIndex, {
        value: txOutput.value,
        script: txOutput.script.toString('hex'),
        height: height
      })
    })
  })
  batch.write(cb)
}

/* handle transactions from blocks [height, lastHeight] */
function handleBlocks (db, height, lastHeight, bar, cb) {
  getBlock(height, function (err, block) {
    if (err) return cb(err)
    updateUTXOs(db, height, block, function (err) {
      if (err) return cb(err)
      if (height === lastHeight) return cb(null)
      bar.tick()
      handleBlocks(db, height + 1, lastHeight, bar, cb)
    })
  })
}

/* create json db from leveldb */
function createJSON (db, cb) {
  var isFirst = true

  var writeStream = fs.createWriteStream(config.jsondb, { flags: 'w' })
  writeStream.write('[', function (err) {
    if (err) return cb(err)
    db.createReadStream()
      .pipe(through2({ objectMode: true },
        function (chunk, enc, cb) {
          var dataKey = chunk.key.split(':')
          var data = JSON.stringify({
            txId: dataKey[0],
            outputIndex: dataKey[1],
            value: chunk.value.value,
            script: chunk.value.script,
            height: chunk.value.height
          })

          if (isFirst) {
            isFirst = false
            this.push(data)
          } else {
            this.push(',' + data)
          }

          cb(null)
        },
        function (cb) {
          this.push(']')
          cb(null)
        }
      ))
      .pipe(writeStream)
      .on('error', function (err) {
        cb(err)
      })
      .on('close', function () {
        cb(null)
      })
  })
}

/* open db */
var db = levelup(config.leveldb, { db: leveldown, valueEncoding: 'json' })

/* create progress bar */
var bar = new ProgressBar(':percent (:current/:total), :elapseds elapsed, eta :etas', {
  total: config.lastHeight
})
bar.curr = config.firstHeight

/* run process */
handleBlocks(db, config.firstHeight, config.lastHeight, bar, function (err) {
  if (err) throw err
  console.log('Creating JSON database...')
  createJSON(db, function (err) {
    if (err) throw err
    db.close(function (err) {
      if (err) throw err
    })
  })
})
<|endoftext|>