<commit_before>// Load modules

var Hoek = require('hoek');
var Boom = require('boom');

// Declare internals

var internals = {};

exports = module.exports = internals.Router = function () {

    this._edge = null;              // { segment, record }
    this._literals = null;          // { literal: { segment, <node> } }
    this._param = null;             // <node>
    this._mixed = null;             // [{ segment, <node> }]
    this._wildcard = null;          // { segment, record }
};

internals.Router.prototype.add = function (segments, record) {

    /*
        { literal: 'x' }        -> x
        { empty: false }        -> {p}
        { wildcard: true }      -> {p*}
        { mixed: /regex/ }      -> a{p}b
    */

    var current = segments[0];
    var remaining = segments.slice(1);
    var isEdge = !remaining.length;
    var active = null;

    var literals = [];
    for (var i = 0, il = segments.length, isLiteral = true; i < il && isLiteral; ++i) {
        isLiteral = !!segments[i].literal;
        literals.push(segments[i].literal);
    }

    if (isLiteral) {
        current = { literal: '/' + literals.join('/') };
        isEdge = true;
    }

    if (current.literal !== undefined) {            // Can be empty string

        // Literal

        this._literals = this._literals || {};
        var literal = (record.settings.isCaseSensitive ? current.literal : current.literal.toLowerCase());
        this._literals[literal] = this._literals[literal] || new internals.Router();
        var node = this._literals[literal];
        if (isEdge) {
            Hoek.assert(!node._edge, 'New route', record.path, 'conflicts with existing', node._edge && node._edge.record.path);
            node._edge = { segment: current, record: record };
        }
        else {
            node.add(remaining, record);
            active = node;
        }
    }
    else if (current.wildcard) {

        // Wildcard

        Hoek.assert(!this._wildcard, 'New route', record.path, 'conflicts with existing', this._wildcard && this._wildcard.record.path);
        Hoek.assert(!this._param || !this._param._wildcard, 'New route', record.path, 'conflicts with existing', this._param && this._param._wildcard && this._param._wildcard.record.path)
        this._wildcard = { segment: current, record: record };
    }
    else if (current.mixed) {

        // Mixed

        this._mixed = this._mixed || [];

        var mixed = this._mixedLookup(current);
        if (!mixed) {
            mixed = { segment: current, node: new internals.Router() };
            this._mixed.push(mixed);
            this._mixed.sort(internals.mixed);
        }

        if (isEdge) {
            Hoek.assert(!mixed.node._edge, 'New route', record.path, 'conflicts with existing', mixed.node._edge && mixed.node._edge.record.path);
            mixed.node._edge = { segment: current, record: record };
        }
        else {
            mixed.node.add(remaining, record);
            active = mixed.node;
        }
    }
    else {

        // Parameter

        this._param = this._param || new internals.Router();

        if (isEdge) {
            Hoek.assert(!this._param._edge, 'New route', record.path, 'conflicts with existing', this._param._edge && this._param._edge.record.path);
            this._param._edge = { segment: current, record: record };
        }
        else {
            Hoek.assert(!this._wildcard || !remaining[0].wildcard, 'New route', record.path, 'conflicts with existing', this._wildcard && this._wildcard.record.path)
            this._param.add(remaining, record);
            node = this._param;
        }
    }
};

internals.Router.prototype._mixedLookup = function (segment) {

    for (var i = 0, il = this._mixed.length; i < il; ++i) {
        if (internals.mixed({ segment: segment }, this._mixed[i]) === 0) {
            return this._mixed[i];
        }
    }

    return null;
};

internals.mixed = function (a, b) {

    var aFirst = -1;
    var bFirst = 1;

    var as = a.segment;
    var bs = b.segment;

    if (as.length !== bs.length) {
        return (as.length > bs.length ? aFirst : bFirst);
    }

    if (as.first !== bs.first) {
        return (as.first ? bFirst : aFirst);
    }

    for (var j = 0, jl = as.segments.length ; j < jl; ++j) {
        var am = as.segments[j];
        var bm = bs.segments[j];

        if (am === bm) {
            continue;
        }

        if (am.length === bm.length) {
            return (am > bm ? bFirst : aFirst);
        }

        return (am.length < bm.length ? bFirst : aFirst);
    }

    return 0;
};

internals.Router.prototype.lookup = function (path, segments, options) {

    // Full literal

    var match = this._literals && this._literals[options.isCaseSensitive ? path : path.toLowerCase()];
    if (match &&
        match._edge) {

        return { record: match._edge.record, array: [] };
    }

    // Current segment

    var current = segments[0];
    var isEdge = segments.length === 1;

    // Literal

    if (this._literals) {
        current = (options.isCaseSensitive ? current : current.toLowerCase());
        match = this._literals[current];
        if (match) {
            var record = internals.deeper(match, isEdge, current, path, segments, [], options);
            if (record) {
                return record;
            }
        }
    }

    // Mixed

    if (this._mixed) {
        for (var i = 0, il = this._mixed.length; i < il; ++i) {
            match = this._mixed[i];
            var params = current.match(match.segment.mixed);
            if (params) {
                var array = [];
                for (var p = 1, pl = params.length; p < pl; ++p) {
                    var value = internals.param(params[p], true);
                    if (value &&
                        value.isBoom) {

                        return value;
                    }

                    array.push(value);
                }

                var record = internals.deeper(match.node, isEdge, current, path, segments, array, options);
                if (record) {
                    return record;
                }
            }
        }
    }

    // Param

    if (this._param) {
        var value = internals.param(current, this._param._edge && this._param._edge.segment.empty);
        if (value === false ||
            (value && value.isBoom)) {

            return value;
        }

        var record = internals.deeper(this._param, isEdge, current, path, segments, [value], options);
        if (record) {
            return record;
        }
    }

    // Wildcard

    if (this._wildcard) {
        var value = internals.param(path.slice(1), true);
        if (value &&
            value.isBoom) {

            return value;
        }

        return { record: this._wildcard.record, array: [value] };
    }

    return null;
};

internals.deeper = function (match, isEdge, current, path, segments, array, options) {

    if (!isEdge) {
        var result = match.lookup(path.slice(current.length + 1), segments.slice(1), options);
        if (result) {
            if (result.isBoom) {
                return result;
            }

            return { record: result.record, array: array.concat(result.array) };
        }
    }
    else if (match._edge) {
        return { record: match._edge.record, array: array };
    }
    else if (match._wildcard) {
        return { record: match._wildcard.record, array: array }
    }

    return null;
};

internals.param = function (value, empty) {

    if (!empty && !value) {
        return false;
    }

    if (empty && !value) {
        return undefined;
    }

    try {
        return decodeURIComponent(value);
    }
    catch (err) {
        return Boom.badRequest('Invalid request path');
    }
};
<commit_msg>Cleanup<commit_after>// Load modules

var Hoek = require('hoek');
var Boom = require('boom');

// Declare internals

var internals = {};

exports = module.exports = internals.Router = function () {

    this._edge = null;              // { segment, record }
    this._literals = null;          // { literal: { segment, <node> } }
    this._param = null;             // <node>
    this._mixed = null;             // [{ segment, <node> }]
    this._wildcard = null;          // { segment, record }
};

internals.Router.prototype.add = function (segments, record) {

    /*
        { literal: 'x' }        -> x
        { empty: false }        -> {p}
        { wildcard: true }      -> {p*}
        { mixed: /regex/ }      -> a{p}b
    */

    var current = segments[0];
    var remaining = segments.slice(1);
    var isEdge = !remaining.length;
    var active = null;

    var literals = [];
    for (var i = 0, il = segments.length, isLiteral = true; i < il && isLiteral; ++i) {
        isLiteral = !!segments[i].literal;
        literals.push(segments[i].literal);
    }

    if (isLiteral) {
        current = { literal: '/' + literals.join('/') };
        isEdge = true;
    }

    if (current.literal !== undefined) {            // Can be empty string

        // Literal

        this._literals = this._literals || {};
        var literal = (record.settings.isCaseSensitive ? current.literal : current.literal.toLowerCase());
        this._literals[literal] = this._literals[literal] || new internals.Router();
        var node = this._literals[literal];
        if (isEdge) {
            Hoek.assert(!node._edge, 'New route', record.path, 'conflicts with existing', node._edge && node._edge.record.path);
            node._edge = { segment: current, record: record };
        }
        else {
            node.add(remaining, record);
            active = node;
        }
    }
    else if (current.wildcard) {

        // Wildcard

        Hoek.assert(!this._wildcard, 'New route', record.path, 'conflicts with existing', this._wildcard && this._wildcard.record.path);
        Hoek.assert(!this._param || !this._param._wildcard, 'New route', record.path, 'conflicts with existing', this._param && this._param._wildcard && this._param._wildcard.record.path)
        this._wildcard = { segment: current, record: record };
    }
    else if (current.mixed) {

        // Mixed

        this._mixed = this._mixed || [];

        var mixed = this._mixedLookup(current);
        if (!mixed) {
            mixed = { segment: current, node: new internals.Router() };
            this._mixed.push(mixed);
            this._mixed.sort(internals.mixed);
        }

        if (isEdge) {
            Hoek.assert(!mixed.node._edge, 'New route', record.path, 'conflicts with existing', mixed.node._edge && mixed.node._edge.record.path);
            mixed.node._edge = { segment: current, record: record };
        }
        else {
            mixed.node.add(remaining, record);
            active = mixed.node;
        }
    }
    else {

        // Parameter

        this._param = this._param || new internals.Router();

        if (isEdge) {
            Hoek.assert(!this._param._edge, 'New route', record.path, 'conflicts with existing', this._param._edge && this._param._edge.record.path);
            this._param._edge = { segment: current, record: record };
        }
        else {
            Hoek.assert(!this._wildcard || !remaining[0].wildcard, 'New route', record.path, 'conflicts with existing', this._wildcard && this._wildcard.record.path)
            this._param.add(remaining, record);
            node = this._param;
        }
    }
};

internals.Router.prototype._mixedLookup = function (segment) {

    for (var i = 0, il = this._mixed.length; i < il; ++i) {
        if (internals.mixed({ segment: segment }, this._mixed[i]) === 0) {
            return this._mixed[i];
        }
    }

    return null;
};

internals.mixed = function (a, b) {

    var aFirst = -1;
    var bFirst = 1;

    var as = a.segment;
    var bs = b.segment;

    if (as.length !== bs.length) {
        return (as.length > bs.length ? aFirst : bFirst);
    }

    if (as.first !== bs.first) {
        return (as.first ? bFirst : aFirst);
    }

    for (var j = 0, jl = as.segments.length ; j < jl; ++j) {
        var am = as.segments[j];
        var bm = bs.segments[j];

        if (am === bm) {
            continue;
        }

        if (am.length === bm.length) {
            return (am > bm ? bFirst : aFirst);
        }

        return (am.length < bm.length ? bFirst : aFirst);
    }

    return 0;
};

internals.Router.prototype.lookup = function (path, segments, options) {

    // Full literal

    var match = this._literals && this._literals[options.isCaseSensitive ? path : path.toLowerCase()];
    if (match &&
        match._edge) {

        return { record: match._edge.record, array: [] };
    }

    // Current segment

    var current = segments[0];

    // Literal

    if (this._literals) {
        match = this._literals[options.isCaseSensitive ? current : current.toLowerCase()];
        if (match) {
            var record = internals.deeper(match, current, path, segments, [], options);
            if (record) {
                return record;
            }
        }
    }

    // Mixed

    if (this._mixed) {
        for (var i = 0, il = this._mixed.length; i < il; ++i) {
            match = this._mixed[i];
            var params = current.match(match.segment.mixed);
            if (params) {
                var array = [];
                for (var p = 1, pl = params.length; p < pl; ++p) {
                    var value = internals.param(params[p], true);
                    if (value &&
                        value.isBoom) {

                        return value;
                    }

                    array.push(value);
                }

                var record = internals.deeper(match.node, current, path, segments, array, options);
                if (record) {
                    return record;
                }
            }
        }
    }

    // Param

    if (this._param) {
        var value = internals.param(current, this._param._edge && this._param._edge.segment.empty);
        if (value === false ||
            (value && value.isBoom)) {

            return value;
        }

        var record = internals.deeper(this._param, current, path, segments, [value], options);
        if (record) {
            return record;
        }
    }

    // Wildcard

    if (this._wildcard) {
        var value = internals.param(path.slice(1), true);
        if (value &&
            value.isBoom) {

            return value;
        }

        return { record: this._wildcard.record, array: [value] };
    }

    return null;
};

internals.deeper = function (match, current, path, segments, array, options) {

    if (segments.length === 1) {
        if (match._edge) {
            return { record: match._edge.record, array: array };
        }

        if (match._wildcard) {
            return { record: match._wildcard.record, array: array }
        }
    }
    else {
        var result = match.lookup(path.slice(current.length + 1), segments.slice(1), options);
        if (result) {
            if (result.isBoom) {
                return result;
            }

            return { record: result.record, array: array.concat(result.array) };
        }
    }

    return null;
};

internals.param = function (value, empty) {

    if (!empty && !value) {
        return false;
    }

    if (empty && !value) {
        return undefined;
    }

    try {
        return decodeURIComponent(value);
    }
    catch (err) {
        return Boom.badRequest('Invalid request path');
    }
};
<|endoftext|>


<commit_before>var subscriptions = new SubsManager();

Router.configure({
	layoutTemplate: 'layout',
	loadingTemplate: 'loading',
	notFoundTemplate: 'notFound'
});

Router.route('/gameStats/:_id', {
	name: 'gameStats',
	waitOn: function() {
		return subscriptions.subscribe('oneGame', this.params._id);
	},
	data: function() {
		return Games.findOne(this.params._id);
	}
});

Router.route('/gameDefinition', {
	name: 'gameDefinition',
	waitOn: function() {
		return [subscriptions.subscribe('clubName'), subscriptions.subscribe('championshipLevel'), subscriptions.subscribe('championshipGroup')];
	}
});

Router.route('/participantsDefinition/:_id', {
	name: 'participantsDefinition',
	waitOn: function() {
		return subscriptions.subscribe('oneGame', this.params._id);
	},
	data: function() {
		return Games.findOne(this.params._id);
	}
});

Router.route('/myGames', {
	name: 'myGames',
	waitOn: function() {
		return subscriptions.subscribe('myGames', Meteor.userId());
	}
});

Router.route('/liveGames', {
	name: 'liveGames',
	waitOn: function() {
		return subscriptions.subscribe('liveGames');
	}
});

Router.route('/about', {
	name: 'about'
});

Router.route('/proVersionTest', {
	name: 'proVersionTest'
});

Router.route('/myAccount', {
	name: 'myAccount',
	data: function() {
		return Meteor.users.findOne({
			_id: Meteor.userId()
		});
	}
});

Router.route('/admin', {
	name: 'admin',
	waitOn: function() {
		return [subscriptions.subscribe('games'), subscriptions.subscribe('clubs'), subscriptions.subscribe("federationConfig")];
	}
});

Router.route('/createNewClub', {
	name: 'createNewClub',
	waitOn: function() {
		return subscriptions.subscribe("federationConfig");
	}
});

Router.route('/myClub', {
	name: 'myClub',
	waitOn: function() {
		return subscriptions.subscribe('myClub', Meteor.userId());
	},
	data: function() {
		return Clubs.findOne({
			createdBy: Meteor.userId()
		});
	}
});

Router.route('/myClub/newTeamDefinition', {
	name: 'newTeamDefinition',
	waitOn: function() {
		return [subscriptions.subscribe("federationConfig"), subscriptions.subscribe('myClub', Meteor.userId())];
	},
	data: function() {
		return Clubs.findOne({
			createdBy: Meteor.userId()
		});
	}
});

Router.route('/myClub/teamEdition', {
	name: 'teamEdition',
	waitOn: function() {
		return [subscriptions.subscribe('federationConfig'), subscriptions.subscribe('myClub', Meteor.userId())];
	},
	data: function() {
		return Clubs.findOne({
			createdBy: Meteor.userId()
		});
	}
});

Router.route('/', {
	name: 'home',
	waitOn: function() {
		return [subscriptions.subscribe('last3LiveGames'), subscriptions.subscribe('last3EndedGames')];
	},
	fastRender: true
});
<commit_msg>Remove participantsDefinition route<commit_after>var subscriptions = new SubsManager();

Router.configure({
	layoutTemplate: 'layout',
	loadingTemplate: 'loading',
	notFoundTemplate: 'notFound'
});

Router.route('/gameStats/:_id', {
	name: 'gameStats',
	waitOn: function() {
		return subscriptions.subscribe('oneGame', this.params._id);
	},
	data: function() {
		return Games.findOne(this.params._id);
	}
});

Router.route('/gameDefinition', {
	name: 'gameDefinition',
	waitOn: function() {
		return [subscriptions.subscribe('clubName'), subscriptions.subscribe('championshipLevel'), subscriptions.subscribe('championshipGroup')];
	}
});

Router.route('/myGames', {
	name: 'myGames',
	waitOn: function() {
		return subscriptions.subscribe('myGames', Meteor.userId());
	}
});

Router.route('/liveGames', {
	name: 'liveGames',
	waitOn: function() {
		return subscriptions.subscribe('liveGames');
	}
});

Router.route('/about', {
	name: 'about'
});

Router.route('/proVersionTest', {
	name: 'proVersionTest'
});

Router.route('/myAccount', {
	name: 'myAccount',
	data: function() {
		return Meteor.users.findOne({
			_id: Meteor.userId()
		});
	}
});

Router.route('/admin', {
	name: 'admin',
	waitOn: function() {
		return [subscriptions.subscribe('games'), subscriptions.subscribe('clubs'), subscriptions.subscribe("federationConfig")];
	}
});

Router.route('/createNewClub', {
	name: 'createNewClub',
	waitOn: function() {
		return subscriptions.subscribe("federationConfig");
	}
});

Router.route('/myClub', {
	name: 'myClub',
	waitOn: function() {
		return subscriptions.subscribe('myClub', Meteor.userId());
	},
	data: function() {
		return Clubs.findOne({
			createdBy: Meteor.userId()
		});
	}
});

Router.route('/myClub/newTeamDefinition', {
	name: 'newTeamDefinition',
	waitOn: function() {
		return [subscriptions.subscribe("federationConfig"), subscriptions.subscribe('myClub', Meteor.userId())];
	},
	data: function() {
		return Clubs.findOne({
			createdBy: Meteor.userId()
		});
	}
});

Router.route('/myClub/teamEdition', {
	name: 'teamEdition',
	waitOn: function() {
		return [subscriptions.subscribe('federationConfig'), subscriptions.subscribe('myClub', Meteor.userId())];
	},
	data: function() {
		return Clubs.findOne({
			createdBy: Meteor.userId()
		});
	}
});

Router.route('/', {
	name: 'home',
	waitOn: function() {
		return [subscriptions.subscribe('last3LiveGames'), subscriptions.subscribe('last3EndedGames')];
	},
	fastRender: true
});
<|endoftext|>


<commit_before>var util = require('util');
var events = require('events');
var Context = require('./context');
var Registry = require('./registry');

module.exports = Router;

/**
 * The application router.
 *
 * This takes a route (in any supported format) and resolves
 * it to a particular chain of commands.
 */
function Router(registry) {
  this.registry = registry;
  this.resolver = null;
}

// Router generates events.
util.inherits(Router, events.EventEmitter);

/*
 * Set a new registry.
 *
 * Use with caution.
 */
Router.prototype.setRegistry = function(registry) {
  this.registry = registry;
}

/**
 * Take the given request name and resolve it to a
 * real request name.
 */
Router.prototype.resolveRequest = function(requestName) {

  if (this.resolver != null) {
    //console.log('RESOLVING ' + this.resolver.resolve(requestName));
    return this.resolver.resolve(requestName);
  }

  // Return just the request name for now.
  return requestName;
}

Router.prototype.setRequestResolver = function(resolver) {
  this.resolver = resolver;
}

/**
 * Given a request, perform the associated commands.
 *
 * Emits:
 * - error: Given an Error object. Emitted when request cannot be found, or when any part of the request fails.
 * - commandsStart:  Given request spec and context. Emitted immediately before the chain is run.
 * - commandsLaunched: Trigger immediately after a chain is kicked off. This may fire before the first command is complete.
 * - commandListComplete: Emitted when the entire chain has been executed.
 * - commandContinue: Emitted when the command is "done enough" for processing to continue. The next
 *    command will start upon seeing this.
 * - commandComplete: Emitted when a command is totally complete. This may happen after other commands have begun
 *    executing.
 * - beforeCommand: A command emits this before it executes.
 * - beforeCommandInit: A command emits this before it runs its init() routine.
 * - commandListInterrupted
 * - reroute
 *
 * @param string request
 * @param pronto.Context cxt (optional)
 */
Router.prototype.handleRequest = function(request, cxt, tainted) {
  request = this.resolveRequest(request);

  var spec = this.registry.getRequestSpec(request);
  if (spec == undefined || spec == null) {
    var err = new Error('Request not found');
    this.emit('error', err, cxt);
    return;
  }

  if (!!tainted && request.length > 0 && request[0] == '@') {
    throw new Error('A tainted route cannot call an internal @-method.');
  }

  // BEGIN NEW
  //this.doCommand(request, spec);
  var context = cxt instanceof Context ? cxt : new Context();
  this.emit('commandsStart', spec, context);

  // doCommand is recursive.
  this.doCommand(request, spec, context, 0);

  this.emit('commandsLaunched', context);
}

/**
 * Execute the current command and then request that the next be executed.
 *
 * This executes the current command (`spec[index]`), and then
 * requests (if necessary) that the next command be executed.
 *
 * Stopping conditions:
 * The command processing stops under the following conditions:
 *  - There are no more commands to execute
 *  - An unhandle `Error` is thrown or emitted.
 *  - A `stop` event is received from the command, or manually triggered.
 *  - A `reroute` event is received from the command. In this case, the
 *    present list is aborted, and the new route is run.
 *
 *
 */
Router.prototype.doCommand = function(requestName, spec, context, index) {

  // Stopping conditions.
  if (index >= spec.length) {
    this.emit('commandListComplete', context);
    return;
  }
  else if (this.stop) {
    this.emit('commandListInterrupted', requestName, spec, context);

    // EXPERIMENTAL: When we stop, we really want to "finish" the
    // request, so we slice the spec and send it in again to complete
    // the "normal" process.
    var fakeSpec = spec.slice(0, index);
    this.stop = false;
    this.doCommand(requestName, fakeSpec, context, ++index);
    return;
  }
  //console.log('Running ' + spec[index].name);

  // No stopping conditions were met, so we build and execute the command.

  item = spec[index];
  var cmd = this.constructCommand(item);

  // emit beforeCommandInit
  cmd.init(item.name);

  var params = this.buildParams(item, context);
  var router = this;

  // Emit 'commandContinue'
  cmd.on('continue', function () {
    router.emit('commandContinue', item, context);
    // Recurse.
    router.doCommand(requestName, spec, context, ++index);
  });

  // Emit 'commandComplete'
  cmd.on('complete', function () { router.emit('commandComplete', spec, context)});
  // Catch a request to stop processing.
  cmd.on('stop', function () {
    router.emit('commandListInterrupted', requestName, spec, context);
    router.stop = true;
  });
  // Catch a request to reroute
  cmd.on('reroute', function (routeName, newCxt) {
    router.emit('reroute', routeName, newCxt);
    router.handleRequest(routeName, newCxt);
  });

  cmd.on('error', function (err) {
    // Bubble the event.
    router.emit('error', err, context);
    router.stop = true;
  })

  // Execute.
  this.emit('beforeCommand', cmd, context, params, spec);
  cmd.executionWrapper(context, params);
}

/**
 * Given a spec, create a new instance of a command.
 *
 * This should be done as late as possible to reduce
 * the amount of memory overhead on un-executed
 * commands.
 */
Router.prototype.constructCommand = function(spec) {
  var cmd = spec.command;
  if (cmd == undefined) {
    throw new Error("No command defined for " + spec.name);
  }
  else if(typeof cmd == 'string') {
    cmd = require(cmd);
  }
  return new cmd();
}

/**
 * Check whether the given request name exists.
 */
Router.prototype.hasRequest = function(requestName) {
  return this.registry.getRequestSpec(requestName) != undefined;
}

// FIXME:
Router.prototype.buildParams = function(spec, cxt) {
  // TODO: Insert from() resolution.
  params = {};
  for (var key in spec.params) {
    if (spec.params[key].from == undefined) {
      params[key] = spec.params[key].value;
    }
    else {
      var from = this.resolveFromSpec(spec.params[key].from, cxt);
      params[key] = from || spec.params[key].value;
    }

  }
  return params;
}

Router.prototype.resolveFromSpec = function(fromStr, cxt) {
  var retval;
  fromStr.split(' ').forEach(function(v, i) {
    // We want to split the pair string into an origin (cxt, get, header, etc.)
    // and the value.
    var firstColon = v.indexOf(':');
    var origin = v.substring(0, firstColon).toLowerCase();//source[0].toLowerCase();
    var key = v.substring(firstColon + 1);
    switch (origin) {
      case 'context':
      case 'cxt':
      case 'c':
        retval = cxt.get(key);
        return;
      case 'arg':
        // Support index or slice.
        break;

      // Proxy all others through cxt.getDatasource
      default:
        var ds = cxt.getDatasource(origin);
        if (ds != undefined) {
          retval = ds[key];
          return;
        }
    }
  });
  return retval;
}<commit_msg>Pass Context to request resolver.<commit_after>var util = require('util');
var events = require('events');
var Context = require('./context');
var Registry = require('./registry');

module.exports = Router;

/**
 * The application router.
 *
 * This takes a route (in any supported format) and resolves
 * it to a particular chain of commands.
 */
function Router(registry) {
  this.registry = registry;
  this.resolver = null;
}

// Router generates events.
util.inherits(Router, events.EventEmitter);

/*
 * Set a new registry.
 *
 * Use with caution.
 */
Router.prototype.setRegistry = function(registry) {
  this.registry = registry;
}

/**
 * Take the given request name and resolve it to a
 * real request name.
 */
Router.prototype.resolveRequest = function(requestName, context) {

  if (this.resolver != null) {
    //console.log('RESOLVING ' + this.resolver.resolve(requestName));
    return this.resolver.resolve(requestName, context);
  }

  // Return just the request name for now.
  return requestName;
}

Router.prototype.setRequestResolver = function(resolver) {
  this.resolver = resolver;
}

/**
 * Given a request, perform the associated commands.
 *
 * Emits:
 * - error: Given an Error object. Emitted when request cannot be found, or when any part of the request fails.
 * - commandsStart:  Given request spec and context. Emitted immediately before the chain is run.
 * - commandsLaunched: Trigger immediately after a chain is kicked off. This may fire before the first command is complete.
 * - commandListComplete: Emitted when the entire chain has been executed.
 * - commandContinue: Emitted when the command is "done enough" for processing to continue. The next
 *    command will start upon seeing this.
 * - commandComplete: Emitted when a command is totally complete. This may happen after other commands have begun
 *    executing.
 * - beforeCommand: A command emits this before it executes.
 * - beforeCommandInit: A command emits this before it runs its init() routine.
 * - commandListInterrupted
 * - reroute
 *
 * @param string request
 * @param pronto.Context cxt (optional)
 */
Router.prototype.handleRequest = function(request, cxt, tainted) {
  request = this.resolveRequest(request, cxt);

  var spec = this.registry.getRequestSpec(request);
  if (spec == undefined || spec == null) {
    var err = new Error('Request not found');
    this.emit('error', err, cxt);
    return;
  }

  if (!!tainted && request.length > 0 && request[0] == '@') {
    throw new Error('A tainted route cannot call an internal @-method.');
  }

  // BEGIN NEW
  //this.doCommand(request, spec);
  var context = cxt instanceof Context ? cxt : new Context();
  this.emit('commandsStart', spec, context);

  // doCommand is recursive.
  this.doCommand(request, spec, context, 0);

  this.emit('commandsLaunched', context);
}

/**
 * Execute the current command and then request that the next be executed.
 *
 * This executes the current command (`spec[index]`), and then
 * requests (if necessary) that the next command be executed.
 *
 * Stopping conditions:
 * The command processing stops under the following conditions:
 *  - There are no more commands to execute
 *  - An unhandle `Error` is thrown or emitted.
 *  - A `stop` event is received from the command, or manually triggered.
 *  - A `reroute` event is received from the command. In this case, the
 *    present list is aborted, and the new route is run.
 *
 *
 */
Router.prototype.doCommand = function(requestName, spec, context, index) {

  // Stopping conditions.
  if (index >= spec.length) {
    this.emit('commandListComplete', context);
    return;
  }
  else if (this.stop) {
    this.emit('commandListInterrupted', requestName, spec, context);

    // EXPERIMENTAL: When we stop, we really want to "finish" the
    // request, so we slice the spec and send it in again to complete
    // the "normal" process.
    var fakeSpec = spec.slice(0, index);
    this.stop = false;
    this.doCommand(requestName, fakeSpec, context, ++index);
    return;
  }
  //console.log('Running ' + spec[index].name);

  // No stopping conditions were met, so we build and execute the command.

  item = spec[index];
  var cmd = this.constructCommand(item);

  // emit beforeCommandInit
  cmd.init(item.name);

  var params = this.buildParams(item, context);
  var router = this;

  // Emit 'commandContinue'
  cmd.on('continue', function () {
    router.emit('commandContinue', item, context);
    // Recurse.
    router.doCommand(requestName, spec, context, ++index);
  });

  // Emit 'commandComplete'
  cmd.on('complete', function () { router.emit('commandComplete', spec, context)});
  // Catch a request to stop processing.
  cmd.on('stop', function () {
    router.emit('commandListInterrupted', requestName, spec, context);
    router.stop = true;
  });
  // Catch a request to reroute
  cmd.on('reroute', function (routeName, newCxt) {
    router.emit('reroute', routeName, newCxt);
    router.handleRequest(routeName, newCxt);
  });

  cmd.on('error', function (err) {
    // Bubble the event.
    router.emit('error', err, context);
    router.stop = true;
  })

  // Execute.
  this.emit('beforeCommand', cmd, context, params, spec);
  cmd.executionWrapper(context, params);
}

/**
 * Given a spec, create a new instance of a command.
 *
 * This should be done as late as possible to reduce
 * the amount of memory overhead on un-executed
 * commands.
 */
Router.prototype.constructCommand = function(spec) {
  var cmd = spec.command;
  if (cmd == undefined) {
    throw new Error("No command defined for " + spec.name);
  }
  else if(typeof cmd == 'string') {
    cmd = require(cmd);
  }
  return new cmd();
}

/**
 * Check whether the given request name exists.
 */
Router.prototype.hasRequest = function(requestName) {
  return this.registry.getRequestSpec(requestName) != undefined;
}

// FIXME:
Router.prototype.buildParams = function(spec, cxt) {
  // TODO: Insert from() resolution.
  params = {};
  for (var key in spec.params) {
    if (spec.params[key].from == undefined) {
      params[key] = spec.params[key].value;
    }
    else {
      var from = this.resolveFromSpec(spec.params[key].from, cxt);
      params[key] = from || spec.params[key].value;
    }

  }
  return params;
}

Router.prototype.resolveFromSpec = function(fromStr, cxt) {
  var retval;
  fromStr.split(' ').forEach(function(v, i) {
    // We want to split the pair string into an origin (cxt, get, header, etc.)
    // and the value.
    var firstColon = v.indexOf(':');
    var origin = v.substring(0, firstColon).toLowerCase();//source[0].toLowerCase();
    var key = v.substring(firstColon + 1);
    switch (origin) {
      case 'context':
      case 'cxt':
      case 'c':
        retval = cxt.get(key);
        return;
      case 'arg':
        // Support index or slice.
        break;

      // Proxy all others through cxt.getDatasource
      default:
        var ds = cxt.getDatasource(origin);
        if (ds != undefined) {
          retval = ds[key];
          return;
        }
    }
  });
  return retval;
}
<|endoftext|>


<commit_before>Router.configure({
    layoutTemplate: 'layout',
    loadingTemplate: 'loading',
    notFoundTemplate: 'notFound'
});
Router.route('/', {
    name: 'bookmarksList'
});
Router.route('/submit', {
    name: 'bookmarkSubmit'
});
Router.route('/bookmark/:_id', {
    name: 'bookmarkPage',
    data: function() {
        return Bookmarks.findOne(this.params._id);
    }
});
var requireLogin = function() {
    if (!Meteor.user()) {
        this.render('accessDenied');
    } else {
        this.next();
    }
}
Router.onBeforeAction(requireLogin, {
    only: 'bookmarkSubmit'
});<commit_msg>Adding data not found<commit_after>Router.configure({
    layoutTemplate: 'layout',
    loadingTemplate: 'loading',
    notFoundTemplate: 'notFound'
});
Router.route('/', {
    name: 'bookmarksList'
});
Router.route('/submit', {
    name: 'bookmarkSubmit'
});
Router.route('/bookmark/:_id', {
    name: 'bookmarkPage',
    data: function() {
        return Bookmarks.findOne(this.params._id);
    }
});
var requireLogin = function() {
    if (!Meteor.user()) {
        if (Meteor.loggingIn()) {
            this.render(this.loadingTemplate);
        } else {
            this.render('accessDenied');
        }
    } else {
        this.next();
    }
}
Router.onBeforeAction('dataNotFound', {
    only: 'bookmarkPage'
});
Router.onBeforeAction(requireLogin, {
    only: 'bookmarkSubmit'
});<|endoftext|>


<commit_before>'use strict';
/* jshint node: true, latedef: nofunc */

var _       = require('lodash'),
    service = require('./service.js');

module.exports = {

  get: {

    clean: function(req, res) {

      var appId = req.app.get('applicationId'),
          instanceId = req.app.get('instanceId'),
          instanceIndex = req.app.get('instanceIndex');

      service.clean(appId, function(err, results) {
        if (err) console.log('error querying service');
        // redis clean, now register ourselves
        service.register(appId, instanceId, instanceIndex, function(err, result) {
          if (err) console.log('error registering service');
          res.redirect('/');
        });
      });

    },

    info: function(req, res) {

      var data = {};

      data.applicationName = req.app.get('applicationName');
      data.applicationId = req.app.get('applicationId');
      data.instanceAddress = req.app.get('instanceAddress');
      data.instanceId = req.app.get('instanceId');
      data.instanceIndex = req.app.get('instanceIndex');
      data.redis = req.app.get('redisEnabled');
      data.theme = req.app.get('theme');

      service.query(req.app.get('applicationId'), function(err, results) {
        if (err) console.log('error querying service');
        // if an empty array is returned, we are not using redis
        // therefore push this instanceId into results
        if (_.isEmpty(results)) {
          results.push(data.instanceId);
        }
        data.instances = results;
        res.status(200).json(data);
      });

    },

    kill: function(req, res) {
      // implement a crude control to stop random people on the internet killing
      // the long-running demo app. For convenience, don't require the env var
      // to be set - only disable killing if it's explicitly false.
      if (process.env.KILLABLE === 'false') {
        console.log('received kill request, but we are UNKILLABLE');
        return res.redirect('/');
      }

      // if running mutiple instances, an incoming kill request could get
      // load balanced to anywhere, so need some logic to only kill ourselves
      var killId = req.query.id;

      if (killId == req.app.get('instanceId')) {
        // clean up before dying... yes it's cheating, but it's a DEMO
        console.log('received kill request for this instance (id: ' + killId + ')');
        service.unregister(req.app.get('applicationId'),
                           req.app.get('instanceId'),
                           req.app.get('instanceIndex'),
                           function(err, result) {
          if (err) console.log('error unregistering service');
          // redirect then die
          setTimeout(function(){ process.exit(1); }, 500);
          res.redirect('/');
        });
      } else {
        console.log('received kill request for instance ' + killId);
        if (killId) {
          // bounce request, gorouter will eventually hit the desired instance
          // TODO make a request to same URI with the 'X-CF-APP-INSTANCE' header
          // set, so we don't bounce around gorouter
          res.redirect('/killme?id=' + killId);
        } else {
          // we don't understand what killIndex is
          res.redirect('/');
        }
      }
    }

  }

};
<commit_msg>reverse kill switch<commit_after>'use strict';
/* jshint node: true, latedef: nofunc */

var _       = require('lodash'),
    service = require('./service.js');

module.exports = {

  get: {

    clean: function(req, res) {

      var appId = req.app.get('applicationId'),
          instanceId = req.app.get('instanceId'),
          instanceIndex = req.app.get('instanceIndex');

      service.clean(appId, function(err, results) {
        if (err) console.log('error querying service');
        // redis clean, now register ourselves
        service.register(appId, instanceId, instanceIndex, function(err, result) {
          if (err) console.log('error registering service');
          res.redirect('/');
        });
      });

    },

    info: function(req, res) {

      var data = {};

      data.applicationName = req.app.get('applicationName');
      data.applicationId = req.app.get('applicationId');
      data.instanceAddress = req.app.get('instanceAddress');
      data.instanceId = req.app.get('instanceId');
      data.instanceIndex = req.app.get('instanceIndex');
      data.redis = req.app.get('redisEnabled');
      data.theme = req.app.get('theme');

      service.query(req.app.get('applicationId'), function(err, results) {
        if (err) console.log('error querying service');
        // if an empty array is returned, we are not using redis
        // therefore push this instanceId into results
        if (_.isEmpty(results)) {
          results.push(data.instanceId);
        }
        data.instances = results;
        res.status(200).json(data);
      });

    },

    kill: function(req, res) {
      // implement a crude control to stop random people on the internet killing
      // the long-running demo app.
      if (!_.isNil(process.env.UNKILLABLE)) {
        console.log('received kill request, but we are UNKILLABLE');
        return res.redirect('/');
      }

      // if running mutiple instances, an incoming kill request could get
      // load balanced to anywhere, so need some logic to only kill ourselves
      var killId = req.query.id;

      if (killId == req.app.get('instanceId')) {
        // clean up before dying... yes it's cheating, but it's a DEMO
        console.log('received kill request for this instance (id: ' + killId + ')');
        service.unregister(req.app.get('applicationId'),
                           req.app.get('instanceId'),
                           req.app.get('instanceIndex'),
                           function(err, result) {
          if (err) console.log('error unregistering service');
          // redirect then die
          setTimeout(function(){ process.exit(1); }, 500);
          res.redirect('/');
        });
      } else {
        console.log('received kill request for instance ' + killId);
        if (killId) {
          // bounce request, gorouter will eventually hit the desired instance
          // TODO make a request to same URI with the 'X-CF-APP-INSTANCE' header
          // set, so we don't bounce around gorouter
          res.redirect('/killme?id=' + killId);
        } else {
          // we don't understand what killIndex is
          res.redirect('/');
        }
      }
    }

  }

};
<|endoftext|>


<commit_before>FlowRouter.route('/DM', {
  name: 'DMView',
  action() {
      BlazeLayout.render('MainLayout');
  }
});

FlowRouter.route('/', {
  name: 'home',
  action() {
    BlazeLayout.render('HomeLayout');
  }
});

FlowRouter.route('/test', {
  name: "test",
  action() {
    BlazeLayout.render('MainLayout', {main: 'Items'})
  }
});

FlowRouter.route('/DM/addItem', {
  name: 'addItem',
  action() {
      BlazeLayout.render('MainLayout', {main: 'addItem'});
  }
});
<commit_msg>updates routing<commit_after>FlowRouter.route('/', {
  name: 'home',
  action() {
    BlazeLayout.render('HomeLayout');
  }
});

FlowRouter.route('/DM', {
  name: 'DMView',
  action() {
    BlazeLayout.render('MainLayout', {main: 'Items', addItem: 'addItem'});
  }
});

FlowRouter.route('/DM/addItem', {
  name: 'addItem',
  action() {
      BlazeLayout.render('MainLayout', {main: 'addItem'});
  }
});
<|endoftext|>


<commit_before>var _ = require('lodash');
var path = require('path');
var resolve = require('resolve');
var glob = require('glob');

module.exports = GruntBrowserifyRunner;

function GruntBrowserifyRunner(options) {
  this.browserify = options.browserify;
  this.watchify = options.watchify;
  this.logger = options.logger;
  this.writer = options.writer;
}

GruntBrowserifyRunner.prototype = _.create(GruntBrowserifyRunner.prototype, {
  run: function (files, destination, options, next) {
    var self = this;

    //determine watchify or browserify
    var engine = options.watch? this.watchify: this.browserify;

    //set constructor options and instantiate
    var bOpts = options.browserifyOptions || {};
    bOpts.entries = files;
    var b = engine(bOpts);

    b.on('error', function (err) {
      self.logger.fail.warn(err);
    });

    //define default bundle options
    var ignoredAliases = [];
    options.bundleOptions = (options.bundleOptions || {});
    options.bundleOptions.filter = function (requireId) {
      return (ignoredAliases.indexOf(requireId) < 0);
    };

    if (options.alias) {
      _.forEach(options.alias, function (aliasPair) {
        if (!aliasPair.match(':')) {
          self.logger.fail.warn('Aliases must be split with a colon');
        }
        else {
          //first, try the module path as it is since
          //it may be a node module name
          var modulePath;
          aliasPair = aliasPair.split(':');
          try {
            modulePath = resolve.sync(aliasPair[0]);
          }
          catch (e) {
            //if resolution fails, the path is probably not
            //a node module so resolve the full module path
            modulePath = resolve.sync(path.resolve(aliasPair[0]));
          }

          b.require(resolve.sync(modulePath), {expose: aliasPair[1]});
        }
      });

    }

    if (options.require) {
      _.forEach(options.require, function (file) {
        b.require(file);
      });
    }

    if (options.exclude) {
      _.forEach(options.exclude, function (file) {
        if (testForGlob(file)) {
          runOptionForGlob(b, 'exclude', file);
        }
        else {
          b.exclude(file);
        }
      });
    }

    if (options.ignore) {
      _.forEach(options.ignore, function (file) {
        runOptionForGlob(b, 'ignore', file);
      });
    }

    if (options.external) {
      _.forEach(options.external, function (id) {
        //allow externalizing of alias lists
        if (id.match(':')) {
          id = id.split(':')[1];
        }

        if (testForGlob(id)) {
          runOptionForGlob(b, 'external', id);
        }
        else {
          try {
            require.resolve(id);
          }
          catch (e) {
            //it's an arbitary alias that can't be resolved,
            //add it to the ignore list
            ignoredAliases.push(id);
          }
          b.external(id);
        }
      });
    }

    if (options.transform) {
      _.forEach(options.transform, function (transformer) {
        if (typeof transformer !== 'object') {
          b.transform(transformer);
        }
        else {
          b.transform(transformer[1], transformer[0]);
        }
      });
    }

    if (options.plugin) {
      _.forEach(options.plugin, function (plugin) {
        if (typeof plugin !== 'object') {
          b.plugin(plugin);
        }
        else {
          b.plugin(plugin[0], plugin[1]);
        }
      });
    }

    var destPath = this.createDestDir(destination);
    var keepAlive = this.keepAliveFn.bind(this, options);
    var done = options.keepAlive? keepAlive : next;
    var bundleComplete = this.onBundleComplete(destination, done);

    if (options.watch) {
      var bundleUpdate = this.onBundleComplete(destination, keepAlive, {allowErrors: true});
      b.on('update', function (ids) {
        ids.forEach(function (id) {
          self.logger.log.ok(id + ' changed, updating browserify bundle.');
        });
        doBundle(b, options, bundleUpdate);
      });
    }

    doBundle(b, options, bundleComplete);
  },

  createDestDir: function (destination) {
    var destPath = path.dirname(path.resolve(destination));
    if (!this.writer.exists(destPath)) {
      this.writer.mkdir(destPath);
    }
    return destPath;
  },

  keepAliveFn: function (options) {
    this.logger.log.ok('Watchifying...');
  },

  onBundleComplete: function (destination, next, options) {
    var self = this;
    return function (err, src) {
      if (err) {
        self.logger.log.error(err);
        if (!options || !options.allowErrors) {
          self.logger.fail.warn('Error running grunt-browserify.');
        }
      }

      self.writer.write(destination, src);
      next();
    };
  }
});

function doBundle(browserifyInstance, opts, bundleComplete) {
  if (opts.preBundleCB) {
    opts.preBundleCB(browserifyInstance);
  }

  browserifyInstance.bundle((opts.bundleOptions || {}), function (err, src) {
    if (opts.postBundleCB) {
      opts.postBundleCB(err, src, bundleComplete);
    }
    else {
      bundleComplete(err, src);
    }
  });
}

function testForGlob(id) {
  return (/\*/.test(id));
}

function runOptionForGlob(browserifyInstance, method, pattern) {
  var files = glob.sync(pattern);
  if (!files || files.length < 1) {
    //it's not a glob, it's a file path
    files = [pattern];
  }
  files.forEach(function (f) {
    browserifyInstance[method].call(browserifyInstance, path.resolve(f));
  });
}
<commit_msg>Correctly output bundled src<commit_after>var _ = require('lodash');
var path = require('path');
var resolve = require('resolve');
var glob = require('glob');

module.exports = GruntBrowserifyRunner;

function GruntBrowserifyRunner(options) {
  this.browserify = options.browserify;
  this.watchify = options.watchify;
  this.logger = options.logger;
  this.writer = options.writer;
}

GruntBrowserifyRunner.prototype = _.create(GruntBrowserifyRunner.prototype, {
  run: function (files, destination, options, next) {
    var self = this;

    //determine watchify or browserify
    var engine = options.watch? this.watchify: this.browserify;

    //set constructor options and instantiate
    var bOpts = options.browserifyOptions || {};
    bOpts.entries = files;
    var b = engine(bOpts);

    b.on('error', function (err) {
      self.logger.fail.warn(err);
    });

    //define default bundle options
    var ignoredAliases = [];
    options.bundleOptions = (options.bundleOptions || {});
    options.bundleOptions.filter = function (requireId) {
      return (ignoredAliases.indexOf(requireId) < 0);
    };

    if (options.alias) {
      _.forEach(options.alias, function (aliasPair) {
        if (!aliasPair.match(':')) {
          self.logger.fail.warn('Aliases must be split with a colon');
        }
        else {
          //first, try the module path as it is since
          //it may be a node module name
          var modulePath;
          aliasPair = aliasPair.split(':');
          try {
            modulePath = resolve.sync(aliasPair[0]);
          }
          catch (e) {
            //if resolution fails, the path is probably not
            //a node module so resolve the full module path
            modulePath = resolve.sync(path.resolve(aliasPair[0]));
          }

          b.require(resolve.sync(modulePath), {expose: aliasPair[1]});
        }
      });

    }

    if (options.require) {
      _.forEach(options.require, function (file) {
        b.require(file);
      });
    }

    if (options.exclude) {
      _.forEach(options.exclude, function (file) {
        if (testForGlob(file)) {
          runOptionForGlob(b, 'exclude', file);
        }
        else {
          b.exclude(file);
        }
      });
    }

    if (options.ignore) {
      _.forEach(options.ignore, function (file) {
        runOptionForGlob(b, 'ignore', file);
      });
    }

    if (options.external) {
      _.forEach(options.external, function (id) {
        //allow externalizing of alias lists
        if (id.match(':')) {
          id = id.split(':')[1];
        }

        if (testForGlob(id)) {
          runOptionForGlob(b, 'external', id);
        }
        else {
          try {
            require.resolve(id);
          }
          catch (e) {
            //it's an arbitary alias that can't be resolved,
            //add it to the ignore list
            ignoredAliases.push(id);
          }
          b.external(id);
        }
      });
    }

    if (options.transform) {
      _.forEach(options.transform, function (transformer) {
        if (typeof transformer !== 'object') {
          b.transform(transformer);
        }
        else {
          b.transform(transformer[1], transformer[0]);
        }
      });
    }

    if (options.plugin) {
      _.forEach(options.plugin, function (plugin) {
        if (typeof plugin !== 'object') {
          b.plugin(plugin);
        }
        else {
          b.plugin(plugin[0], plugin[1]);
        }
      });
    }

    var destPath = this.createDestDir(destination);
    var keepAlive = this.keepAliveFn.bind(this, options);
    var done = options.keepAlive? keepAlive : next;
    var bundleComplete = this.onBundleComplete(destination, done);

    if (options.watch) {
      var bundleUpdate = this.onBundleComplete(destination, keepAlive, {allowErrors: true});
      b.on('update', function (ids) {
        ids.forEach(function (id) {
          self.logger.log.ok(id + ' changed, updating browserify bundle.');
        });
        doBundle(b, options, bundleUpdate);
      });
    }

    doBundle(b, options, bundleComplete);
  },

  createDestDir: function (destination) {
    var destPath = path.dirname(path.resolve(destination));
    if (!this.writer.exists(destPath)) {
      this.writer.mkdir(destPath);
    }
    return destPath;
  },

  keepAliveFn: function (options) {
    this.logger.log.ok('Watchifying...');
  },

  onBundleComplete: function (destination, next, options) {
    var self = this;
    options = (options || {});
    return function (err, src) {
      if (err) {
        self.logger.log.error(err);
        if (!options.allowErrors) {
          self.logger.fail.warn('Error running grunt-browserify.');
        }
      }

      if (src) {
        if (!options.debug && !src.match(/;$/)) {
          src += ';';
        }

        self.writer.write(destination, src);
      }

      next();
    };
  }
});

function doBundle(browserifyInstance, opts, bundleComplete) {
  if (opts.preBundleCB) {
    opts.preBundleCB(browserifyInstance);
  }

  browserifyInstance.bundle((opts.bundleOptions || {}), function (err, src) {
    if (opts.postBundleCB) {
      opts.postBundleCB(err, src, bundleComplete);
    }
    else {
      bundleComplete(err, src);
    }
  });
}

function testForGlob(id) {
  return (/\*/.test(id));
}

function runOptionForGlob(browserifyInstance, method, pattern) {
  var files = glob.sync(pattern);
  if (!files || files.length < 1) {
    //it's not a glob, it's a file path
    files = [pattern];
  }
  files.forEach(function (f) {
    browserifyInstance[method].call(browserifyInstance, path.resolve(f));
  });
}
<|endoftext|>


<commit_before>'use strict';
var Agenda = require('agenda');
var config = require('config');
var _ = require('lodash');
var ApplicationEvent = require('broker/lib/event_types/application_event');
var EventBroker = require('broker/lib/event_broker');
var BBPromise = require('bluebird');
var logger = require('hoist-logger');

function Runner() {
  _.bindAll(this);
}

Runner.prototype = {
  processEvents: function (job, done) {
    logger.info({
      job: job
    }, 'processing schedule job');
    var data = job.attrs.data;
    BBPromise.try(function () {
        return BBPromise.all(_.map(data.events, function (eventName) {
          return this.createEvent(data, eventName).catch(
            /* istanbul ignore next */
            function (err) {
              logger.info(err);
              logger.error(err);
              throw err;
            });
        }, this)).catch(
          /* istanbul ignore next */
          function (err) {
            logger.info(err);
            logger.error(err);
            throw err;
          });
      },[],this).catch(
        /* istanbul ignore next */
        function (err) {
          logger.info(err);
          logger.error(err);
          throw err;
        })
      .nodeify(done);
  },
  createEvent: function (data, eventName) {
    var applicationEvent = new ApplicationEvent({
      applicationId: data.application,
      environment: data.environment,
      eventName: eventName
    });
    logger.info({
      eventId: applicationEvent.messageId,
      applicationId: applicationEvent.applicationId,
      correlationId: applicationEvent.correlationId,
      eventName: eventName
    }, 'raising scheduled event');
    return EventBroker.publish(applicationEvent);
  },
  start: function () {

    this.agenda = new Agenda({
      db: {
        address: config.get('Hoist.mongo.db')
      }
    });
    this.agenda.define('create:event', this.processEvents);
    this.agenda.start();
    logger.info('waiting on schedule');
  },
  stop: function (cb) {
    this.agenda.stop(cb || /* istanbul ignore next */ function () {});
  }
};

module.exports = new Runner();
<commit_msg>add raygun alert<commit_after>'use strict';
var Agenda = require('agenda');
var config = require('config');
var _ = require('lodash');
var ApplicationEvent = require('broker/lib/event_types/application_event');
var EventBroker = require('broker/lib/event_broker');
var BBPromise = require('bluebird');
var logger = require('hoist-logger');

function Runner() {
  _.bindAll(this);
}

Runner.prototype = {
  processEvents: function (job, done) {
    logger.info({
      job: job
    }, 'processing schedule job');
    var data = job.attrs.data;
    BBPromise.try(function () {
        return BBPromise.all(_.map(data.events, function (eventName) {
          return this.createEvent(data, eventName);
        }, this));
      }, [], this).catch(
        /* istanbul ignore next */
        function (err) {
          logger.info(err);
          logger.error(err);
          var application;
          if (data) {
            application = data.application;
          }
          logger.alert(err, application);
          throw err;
        })
      .nodeify(done);
  },
  createEvent: function (data, eventName) {
    var applicationEvent = new ApplicationEvent({
      applicationId: data.application,
      environment: data.environment,
      eventName: eventName
    });
    logger.info({
      eventId: applicationEvent.messageId,
      applicationId: applicationEvent.applicationId,
      correlationId: applicationEvent.correlationId,
      eventName: eventName
    }, 'raising scheduled event');
    return EventBroker.publish(applicationEvent);
  },
  start: function () {
    this.agenda = new Agenda({
      db: {
        address: config.get('Hoist.mongo.db')
      }
    });
    this.agenda.define('create:event', this.processEvents);
    this.agenda.start();
    logger.info('waiting on schedule');
  },
  stop: function (cb) {
    this.agenda.stop(cb || /* istanbul ignore next */ function () {});
  }
};

module.exports = new Runner();
<|endoftext|>


<commit_before>/**
 * Created by luiseduardobrito on 3/4/15.
 */
angular.module('restPlayground', [
  'com.devnup.rest'
])

  .run(function ($rest) {

    // Configure your rest template
    $rest.config({

      // Base domain for requests
      // Used as prefix in all http calls
      base: '',

      // Example: $rest.get('http://example.com').cache().success(console.log)
      cache: {

        // Storage type
        type: 'local',

        // 5 seconds min cache
        min: 5000,

        // 1 min max cache
        // will automatically update itself when enabled
        // using .cache() method after the request call
        // when timeout is reached
        max: 10000
      }
    });
  })

  .controller('PlaygroundCtrl', [
    '$scope', '$rest',
    function ($scope, $rest) {

      $scope.available = {
        methods: ['get', 'post', 'put', 'delete']
      };

      $scope.input = {
        method: 'get',
        url: 'http://dev.ws.devnup.com/api/status',
        cache: {
          enabled: false,
          hash: function () {
            return JSON.stringify(angular.copy($scope.input));
          }
        },
        params: [{}]
      };

      $scope.result = '';

      $scope.refresh = function (input) {

        var params = {};

        input.params.map(function (p) {
          if (p.key && p.value) {
            params[p.key] = p.value;
          }
        });

        $rest[$scope.input.method || 'get'](input.url, params, {
            cache: input.cache
          })
          .error(function (err) {
            console.error(err);
          })
          .success(function (data) {
            try {
              $scope.result = JSON.stringify(data);
            } catch (e) {
              $scope.result = data || e && e.message ? e.message : (e || 'Error');
            }
          })
      };

      $scope.refresh($scope.input);

    }]);<commit_msg>identing result using stringify<commit_after>/**
 * Created by luiseduardobrito on 3/4/15.
 */
angular.module('restPlayground', [
  'com.devnup.rest'
])

  .run(function ($rest) {

    // Configure your rest template
    $rest.config({

      // Base domain for requests
      // Used as prefix in all http calls
      base: '',

      // Example: $rest.get('http://example.com').cache().success(console.log)
      cache: {

        // Storage type
        type: 'local',

        // 5 seconds min cache
        min: 5000,

        // 1 min max cache
        // will automatically update itself when enabled
        // using .cache() method after the request call
        // when timeout is reached
        max: 10000
      }
    });
  })

  .controller('PlaygroundCtrl', [
    '$scope', '$rest',
    function ($scope, $rest) {

      $scope.available = {
        methods: ['get', 'post', 'put', 'delete']
      };

      $scope.input = {
        method: 'get',
        url: 'http://dev.ws.devnup.com/api/status',
        cache: {
          enabled: false,
          hash: function () {
            return JSON.stringify(angular.copy($scope.input));
          }
        },
        params: [{}]
      };

      $scope.result = '';

      $scope.refresh = function (input) {

        var params = {};

        input.params.map(function (p) {
          if (p.key && p.value) {
            params[p.key] = p.value;
          }
        });

        $rest[$scope.input.method || 'get'](input.url, params, {
            cache: input.cache
          })
          .error(function (err) {
            console.error(err);
          })
          .success(function (data) {
            try {
              $scope.result = JSON.stringify(data, null, 4);
            } catch (e) {
              $scope.result = data || (e && e.message ? e.message : (e || 'Error'));
            }
          })
      };

      $scope.refresh($scope.input);

    }]);<|endoftext|>


<commit_before>/*
 * ICESOFT COMMERCIAL SOURCE CODE LICENSE V 1.1
 *
 * The contents of this file are subject to the ICEsoft Commercial Source
 * Code License Agreement V1.1 (the "License"); you may not use this file
 * except in compliance with the License. You may obtain a copy of the
 * License at
 * http://www.icesoft.com/license/commercial-source-v1.1.html
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations under
 * the License.
 *
 * Copyright 2009-2014 ICEsoft Technologies Canada, Corp. All Rights Reserved.
 */

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

var TRANSACTION_HEADER_KEY = 'com.icesoft.services.transaction.id';
module.exports.TRANSACTION_HEADER_KEY = TRANSACTION_HEADER_KEY;

var PROCESS_HEADER_KEY = 'com.icesoft.services.process.id';
module.exports.PROCESS_HEADER_KEY = PROCESS_HEADER_KEY;

//For the purposes of the service scope, a "request" and a "transaction" are the same.  Each
//request to our services is assigned a transactionId that travels through all relevant services
//and is the id which is used to store any request/transaction scoped data.
// var ICESOFT_REQUEST_HEADER = "com.icesoft.services.request.id";

/**
 * Get a specific scope API as defined by the provided scopeIdentifier. The result is
 * a Promise that resolves to a standard API for that particular scope.
 *
 * This is not generally meant for public consumption. Instead, clients should use the
 * concrete methods for the particular scope (getRequestScope, getBackpackScope, etc. ).
 * However, it is possible to use this for managing custom scopes if we want to provide
 * that feature.
 *
 * @param accountName
 * @param realmName
 * @param scopeIdentifier The id of the scope object to create
 * @returns {Promise}
 */
function getScope(accountName, realmName, scopeIdentifier) {

    return new Promise(function (resolve, reject) {

        var scopeId = scopeIdentifier;

        if (!scopeId) {
            reject('missing scope identifier');
        }

        db.getCollection(accountName, realmName, 'scopes', function (err, scopesCollection) {

            if (err) {
                reject(err);
            }

            //This object contains the general API for any scope.  The collection is always
            //the same, the only difference between them is which scopeId is used as the
            //database _id and that's provided when you initially get the scope.
            var scopeAPI = {

                setAttribute: function (key, value) {

                    return new Promise(function (resolve, reject) {

                        var updateAttribute = {};
                        updateAttribute[key] = value;

                        scopesCollection
                            .updateOne(
                                {_scopeId: scopeId},
                                {$set: updateAttribute},
                                {upsert: true})
                            .then(
                                function (result) {
                                    if (result.result && result.result.ok === 1) {
                                        resolve(updateAttribute);
                                    } else {
                                        reject(result.result);
                                    }
                                }
                            )
                            .catch(
                                function (err) {
                                    reject(err);
                                }
                            );
                    });

                },

                getAttribute: function (key) {

                    return new Promise(function (resolve, reject) {

                        scopesCollection
                            .find({_scopeId: scopeId})
                            .toArray()
                            .then(
                                function (result) {
                                    if (result[0] && result[0][key]) {
                                        resolve(result[0][key]);
                                    } else {
                                        resolve();
                                    }
                                }
                            )
                            .catch(
                                function (err) {
                                    reject(err);
                                }
                            );
                    });
                },

                removeAttribute: function (key) {

                    return new Promise(function (resolve, reject) {

                        var removeAttribute = {};
                        removeAttribute[key] = "";

                        scopesCollection
                            .updateOne(
                                {_scopeId: scopeId},
                                {$unset: removeAttribute})
                            .then(
                                function (result) {

                                    if (result.result && result.result.ok === 1) {
                                        resolve(key);
                                    } else {
                                        reject(result.result);
                                    }
                                }
                            )
                            .catch(
                                function (err) {
                                    reject(err);
                                }
                            );
                    });
                },

                getAttributeKeys: function () {

                    return new Promise(function (resolve, reject) {
                        scopesCollection
                            .find({_scopeId: scopeId})
                            .project({_id: 0, _scopeId: 0})
                            .toArray()
                            .then(
                                function (result) {
                                    resolve(Object.keys(result[0]));
                                }
                            )
                            .catch(
                                function (err) {
                                    reject(err);
                                }
                            );
                    });

                },

                getId: function () {
                    return scopeId;
                },

                invalidate: function () {
                    return new Promise(function (resolve, reject) {
                        scopesCollection
                            .remove({_scopeId: scopeId})
                            .then(
                                function (result) {
                                    if (result.result && result.result.ok === 1) {
                                        resolve(scopeId);
                                    } else {
                                        reject(result.result);
                                    }
                                }
                            )
                            .catch(
                                function (err) {
                                    reject(err);
                                }
                            );
                    });
                },

                //The following have not been implemented yet.  They reflect what we know
                //of standard JavaEE session APIs but may or may not be applicable for our
                //purposes.
                getCreationTime: function () {
                    //TODO
                    return new Promise(function (resolve, reject) {
                        resolve();
                    });
                },

                getLastAccessedTime: function () {
                    //TODO
                    return new Promise(function (resolve, reject) {
                        resolve();
                    });
                },

                getMaxInactiveInterval: function () {
                    //TODO
                    return new Promise(function (resolve, reject) {
                        resolve();
                    });
                },

                setMaxInactiveInterval: function (interval) {
                    //TODO
                    return new Promise(function (resolve, reject) {
                        resolve();
                    });
                }

            };

            resolve(scopeAPI);
        });

    });

}
module.exports.getScope = getScope;

/**
 * Extracts the request from the barrel and uses that request to get
 * the value of the provided header.
 *
 * @param barrel
 * @param headerName
 * @returns {*}
 */
function getHeader(barrel, headerName) {
    //TODO: make sure this is correct and robust
    return barrel.req.headers[headerName];
}

/**
 * Get the transaction id header from the request object stored in the barrel.
 *
 * @param barrel
 * @returns {*}
 */
function getTransactionId(barrel) {
    return getHeader(barrel, TRANSACTION_HEADER_KEY);
}

/**
 * Get the process id header from the request object stored in the barrel.
 *
 * @param barrel
 * @returns {*}
 */
function getProcessId(barrel) {
    return getHeader(barrel, PROCESS_HEADER_KEY);
}

/**
 * General utility method that gets any scope from this account/realm
 * based on the scopeId passed in.
 *
 * @param barrel
 * @param scopeId
 * @returns {Promise}
 */
function getScopeFromBarrel(barrel, scopeId) {
    return getScope(barrel.accountId, barrel.realmId, scopeId);
}

/**
 * Get a listing of all the scopes in the given account and realm.
 *
 * @param accountName The account name
 * @param realmName The realm
 * @returns {Promise}
 */
function getAllScopes(accountName, realmName) {

    return new Promise(function (resolve, reject) {

        db.getCollection(accountName, realmName, 'scopes', function (err, scopesCollection) {

            if (err) {
                reject(err);
            }
            scopesCollection.find().toArray(function (err, scopes) {
                if (err) {
                    console.log('err! ', err);
                    reject(err);
                }
                resolve(scopes);
            });
        });
    });
}
module.exports.getScopesDirectory = getAllScopes;

/**
 * Returns a Promise for acquiring an API that can be used for request/transaction scoped
 * data. This is tracked by the current transaction code, which is generated by authProxy
 * when a request to one of the services is initially received. Downstream services can
 * place and consume variables in this scope, which is maintained by passing the transaction
 * code along in the request header (if using an HTTP request) or via the event payload (if
 * listening for an Event).
 *
 * @param barrel
 * @returns {Promise<T>|Promise}
 */
function getRequestScope(barrel) {
    return getScopeFromBarrel(barrel, getTransactionId(barrel));
}

/**
 * Set a request/transaction-scoped key/value pair.
 *
 * @param barrel
 * @param key
 * @param value
 * @returns {Promise|Promise<T>}
 */
function setRequestAttribute(barrel, key, value) {

    return new Promise(function (resolve, reject) {

        getRequestScope(barrel)
            .then(
                function (scope) {

                    scope.setAttribute(key, value)
                        .then(
                            function (setResult) {
                                resolve(setResult);
                            }
                        )
                        .catch(
                            function (err) {
                                reject(err);
                            }
                        );
                })
            .catch(
                function (err) {
                    reject(err);
                }
            );
    });
}
module.exports.setRequestAttribute = setRequestAttribute;

/**
 * Get the value of a request/transaction-scoped attribute.
 *
 * @param barrel
 * @param key
 * @returns {Promise|Promise<T>}
 */
function getRequestAttribute(barrel, key) {

    return new Promise(function (resolve, reject) {

        getRequestScope(barrel)
            .then(
                function (scope) {

                    scope.getAttribute(key)
                        .then(
                            function (getResult) {
                                resolve(getResult);
                            }
                        )
                        .catch(
                            function (err) {
                                reject(err);
                            }
                        );
                })
            .catch(
                function (err) {
                    reject(err);
                }
            );
    });
}
module.exports.getRequestAttribute = getRequestAttribute;

/**
 * Remove a request/transaction-scoped key/value pair.
 *
 * @param barrel
 * @param key
 * @returns {Promise|Promise<T>}
 */
function removeRequestAttribute(barrel, key) {

    return new Promise(function (resolve, reject) {

        getRequestScope(barrel)
            .then(
                function (scope) {

                    scope.removeAttribute(key)
                        .then(
                            function (removeResult) {
                                resolve(removeResult);
                            }
                        )
                        .catch(
                            function (err) {
                                reject(err);
                            }
                        );
                })
            .catch(
                function (err) {
                    reject(err);
                }
            );
    });
}
module.exports.removeRequestAttribute = removeRequestAttribute;

/**
 * Get all the current request/transaction-scoped keys.
 *
 * @param barrel
 * @returns {Promise|Promise<T>}
 */
function getRequestAttributeKeys(barrel) {

    return new Promise(function (resolve, reject) {

        getRequestScope(barrel)
            .then(
                function (scope) {

                    scope.getAttributeKeys()
                        .then(
                            function (keysResult) {
                                resolve(keysResult);
                            }
                        )
                        .catch(
                            function (err) {
                                reject(err);
                            }
                        );
                })
            .catch(
                function (err) {
                    reject(err);
                }
            );
    });
}
module.exports.getRequestAttributeKeys = getRequestAttributeKeys;

/**
 * Invalidate the current request/transaction scoped storage.  This should
 * generally be used for cleaning up the entire scope when it's no longer
 * valid.
 *
 * @param barrel
 * @returns {Promise|Promise<T>}
 */
function invalidateRequest(barrel) {

    return new Promise(function (resolve, reject) {

        getRequestScope(barrel)
            .then(
                function (scope) {

                    scope.invalidate()
                        .then(
                            function (invalidateResult) {
                                resolve(invalidateResult);
                            }
                        )
                        .catch(
                            function (err) {
                                reject(err);
                            }
                        );
                })
            .catch(
                function (err) {
                    reject(err);
                }
            );
    });
}

/**
 * Returns a Promise for acquiring an API that can be used for process-scoped
 * data. This is tracked by a process code, which is generated by the Process service
 * when a process is started. Downstream services can place and consume variables in
 * this scope, which is maintained by passing the process code along in the request header
 * (if using an HTTP request) or via the event payload (if listening for an Event).
 *
 * @param barrel
 * @returns {Promise<T>|Promise}
 */
function getProcessScope(barrel) {
    return getScopeFromBarrel(barrel, getProcessId(barrel));
}

//For most other scopes (realm, backpack/action, etc.) the code should mostly be a an exercise
//in copy and paste but this seems highly inefficient so we'll look at improving this part.<commit_msg>refactor to rename 'request' to 'transaction' as well as significantly reduce code duplication for other scopes<commit_after>/*
 * ICESOFT COMMERCIAL SOURCE CODE LICENSE V 1.1
 *
 * The contents of this file are subject to the ICEsoft Commercial Source
 * Code License Agreement V1.1 (the "License"); you may not use this file
 * except in compliance with the License. You may obtain a copy of the
 * License at
 * http://www.icesoft.com/license/commercial-source-v1.1.html
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations under
 * the License.
 *
 * Copyright 2009-2014 ICEsoft Technologies Canada, Corp. All Rights Reserved.
 */

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

var TRANSACTION_HEADER_KEY = 'com.icesoft.services.transaction.id';
module.exports.TRANSACTION_HEADER_KEY = TRANSACTION_HEADER_KEY;

var PROCESS_HEADER_KEY = 'com.icesoft.services.process.id';
module.exports.PROCESS_HEADER_KEY = PROCESS_HEADER_KEY;

//For the purposes of the service scope, a "request" and a "transaction" are the same.  Each
//request to our services is assigned a transactionId that travels through all relevant services
//and is the id which is used to store any request/transaction scoped data.
// var ICESOFT_REQUEST_HEADER = "com.icesoft.services.request.id";

/**
 * Get a specific scope API as defined by the provided scopeIdentifier. The result is
 * a Promise that resolves to a standard API for that particular scope.
 *
 * This is not generally meant for public consumption. Instead, clients should use the
 * concrete methods for the particular scope (getRequestScope, getBackpackScope, etc. ).
 * However, it is possible to use this for managing custom scopes if we want to provide
 * that feature.
 *
 * @param accountName
 * @param realmName
 * @param scopeIdentifier The id of the scope object to create
 * @returns {Promise}
 */
function getScope(accountName, realmName, scopeIdentifier) {

    return new Promise(function (resolve, reject) {

        var scopeId = scopeIdentifier;

        if (!scopeId) {
            reject('missing scope identifier');
        }

        db.getCollection(accountName, realmName, 'scopes', function (err, scopesCollection) {

            if (err) {
                reject(err);
            }

            //This object contains the general API for any scope.  The collection is always
            //the same, the only difference between them is which scopeId is used as the
            //database _id and that's provided when you initially get the scope.
            var scopeAPI = {

                setAttribute: function (key, value) {

                    return new Promise(function (resolve, reject) {

                        var updateAttribute = {};
                        updateAttribute[key] = value;

                        scopesCollection
                            .updateOne(
                                {_scopeId: scopeId},
                                {$set: updateAttribute},
                                {upsert: true})
                            .then(
                                function (result) {
                                    if (result.result && result.result.ok === 1) {
                                        resolve(updateAttribute);
                                    } else {
                                        reject(result.result);
                                    }
                                }
                            )
                            .catch(
                                function (err) {
                                    reject(err);
                                }
                            );
                    });

                },

                getAttribute: function (key) {

                    return new Promise(function (resolve, reject) {

                        scopesCollection
                            .find({_scopeId: scopeId})
                            .toArray()
                            .then(
                                function (result) {
                                    if (result[0] && result[0][key]) {
                                        resolve(result[0][key]);
                                    } else {
                                        resolve();
                                    }
                                }
                            )
                            .catch(
                                function (err) {
                                    reject(err);
                                }
                            );
                    });
                },

                removeAttribute: function (key) {

                    return new Promise(function (resolve, reject) {

                        var removeAttribute = {};
                        removeAttribute[key] = "";

                        scopesCollection
                            .updateOne(
                                {_scopeId: scopeId},
                                {$unset: removeAttribute})
                            .then(
                                function (result) {

                                    if (result.result && result.result.ok === 1) {
                                        resolve(key);
                                    } else {
                                        reject(result.result);
                                    }
                                }
                            )
                            .catch(
                                function (err) {
                                    reject(err);
                                }
                            );
                    });
                },

                getAttributeKeys: function () {

                    return new Promise(function (resolve, reject) {
                        scopesCollection
                            .find({_scopeId: scopeId})
                            .project({_id: 0, _scopeId: 0})
                            .toArray()
                            .then(
                                function (result) {
                                    resolve(Object.keys(result[0]));
                                }
                            )
                            .catch(
                                function (err) {
                                    reject(err);
                                }
                            );
                    });

                },

                getId: function () {
                    return scopeId;
                },

                invalidate: function () {
                    return new Promise(function (resolve, reject) {
                        scopesCollection
                            .remove({_scopeId: scopeId})
                            .then(
                                function (result) {
                                    if (result.result && result.result.ok === 1) {
                                        resolve(scopeId);
                                    } else {
                                        reject(result.result);
                                    }
                                }
                            )
                            .catch(
                                function (err) {
                                    reject(err);
                                }
                            );
                    });
                },

                //The following have not been implemented yet.  They reflect what we know
                //of standard JavaEE session APIs but may or may not be applicable for our
                //purposes.
                getCreationTime: function () {
                    //TODO
                    return new Promise(function (resolve, reject) {
                        resolve();
                    });
                },

                getLastAccessedTime: function () {
                    //TODO
                    return new Promise(function (resolve, reject) {
                        resolve();
                    });
                },

                getMaxInactiveInterval: function () {
                    //TODO
                    return new Promise(function (resolve, reject) {
                        resolve();
                    });
                },

                setMaxInactiveInterval: function (interval) {
                    //TODO
                    return new Promise(function (resolve, reject) {
                        resolve();
                    });
                }

            };

            resolve(scopeAPI);
        });

    });

}
module.exports.getScope = getScope;

// -------------------------
// BASE SCOPE FUNCTIONS
// -------------------------

//The following functions are the base calls used by all scope-related
//functions. They simply use the provided scopeId to operate since all
//scopes use their own id to store the specific data.

function getScopeFromBarrel(barrel, scopeId) {
    return getScope(barrel.accountId, barrel.realmId, scopeId);
}

function setAttribute(barrel, scopeId, key, value) {

    return new Promise(function (resolve, reject) {

        getScopeFromBarrel(barrel, scopeId)
            .then(
                function (scope) {

                    scope.setAttribute(key, value)
                        .then(
                            function (setResult) {
                                resolve(setResult);
                            }
                        )
                        .catch(
                            function (err) {
                                reject(err);
                            }
                        );
                })
            .catch(
                function (err) {
                    reject(err);
                }
            );
    });
}

function getAttribute(barrel, scopeId, key) {

    return new Promise(function (resolve, reject) {

        getScopeFromBarrel(barrel, scopeId)
            .then(
                function (scope) {

                    scope.getAttribute(key)
                        .then(
                            function (getResult) {
                                resolve(getResult);
                            }
                        )
                        .catch(
                            function (err) {
                                reject(err);
                            }
                        );
                })
            .catch(
                function (err) {
                    reject(err);
                }
            );
    });
}

function removeAttribute(barrel, scopeId, key) {

    return new Promise(function (resolve, reject) {

        getScopeFromBarrel(barrel, scopeId)
            .then(
                function (scope) {

                    scope.removeAttribute(key)
                        .then(
                            function (removeResult) {
                                resolve(removeResult);
                            }
                        )
                        .catch(
                            function (err) {
                                reject(err);
                            }
                        );
                })
            .catch(
                function (err) {
                    reject(err);
                }
            );
    });
}

function getAttributeKeys(barrel, scopeId) {

    return new Promise(function (resolve, reject) {

        getScopeFromBarrel(barrel, scopeId)
            .then(
                function (scope) {

                    scope.getAttributeKeys()
                        .then(
                            function (keysResult) {
                                resolve(keysResult);
                            }
                        )
                        .catch(
                            function (err) {
                                reject(err);
                            }
                        );
                })
            .catch(
                function (err) {
                    reject(err);
                }
            );
    });
}

function invalidate(barrel, scopeId) {

    return new Promise(function (resolve, reject) {

        getScopeFromBarrel(barrel, scopeId)
            .then(
                function (scope) {

                    scope.invalidate()
                        .then(
                            function (invalidateResult) {
                                resolve(invalidateResult);
                            }
                        )
                        .catch(
                            function (err) {
                                reject(err);
                            }
                        );
                })
            .catch(
                function (err) {
                    reject(err);
                }
            );
    });
}

/**
 * Extracts the raw request from the barrel and uses that to get
 * the value of the specified header.
 *
 * @param barrel
 * @param headerName
 * @returns {*}
 */
function getHeader(barrel, headerName) {
    //TODO: make sure this is correct and robust
    return barrel.req.headers[headerName];
}

/**
 * Get a listing of all the scopes in the given account and realm.
 *
 * @param accountName The account name
 * @param realmName The realm
 * @returns {Promise}
 */
function getAllScopes(accountName, realmName) {

    return new Promise(function (resolve, reject) {

        db.getCollection(accountName, realmName, 'scopes', function (err, scopesCollection) {

            if (err) {
                reject(err);
            }
            scopesCollection.find().toArray(function (err, scopes) {
                if (err) {
                    console.log('err! ', err);
                    reject(err);
                }
                resolve(scopes);
            });
        });
    });
}
module.exports.getScopesDirectory = getAllScopes;

// -------------------------
// TRANSACTION SCOPE
// -------------------------

/**
 * Get the transaction id header from the request object stored in the barrel.
 *
 * @param barrel
 * @returns {*}
 */
function getTransactionId(barrel) {
    return getHeader(barrel, TRANSACTION_HEADER_KEY);
}

/**
 * Set a transaction-scoped key/value pair.
 *
 * @param barrel
 * @param key
 * @param value
 * @returns {Promise|Promise<T>}
 */
function setTransactionAttribute(barrel, key, value) {
    return setAttribute(barrel, getTransactionId(barrel), key, value);
}
module.exports.setTransactionAttribute = setTransactionAttribute;

/**
 * Get the value of a transaction-scoped attribute.
 *
 * @param barrel
 * @param key
 * @returns {Promise|Promise<T>}
 */
function getTransactionAttribute(barrel, key) {
    return getAttribute(barrel, getTransactionId(barrel), key);
}
module.exports.getTransactionAttribute = getTransactionAttribute;

/**
 * Remove a transaction-scoped key/value pair.
 *
 * @param barrel
 * @param key
 * @returns {Promise|Promise<T>}
 */
function removeTransactionAttribute(barrel, key) {
    return removeAttribute(barrel, getTransactionId(barrel), key);
}
module.exports.removeTransactionAttribute = removeTransactionAttribute;

/**
 * Get all the current transaction-scoped keys.
 *
 * @param barrel
 * @returns {Promise|Promise<T>}
 */
function getTransactionAttributeKeys(barrel) {
    return getAttributeKeys(barrel, getTransactionId(barrel));
}
module.exports.getTransactionAttributeKeys = getTransactionAttributeKeys;

/**
 * Invalidate the current transaction scoped storage.  This should
 * generally be used for cleaning up the entire scope when it's no longer
 * valid.
 *
 * @param barrel
 * @returns {Promise|Promise<T>}
 */
function invalidateTransaction(barrel) {
    return invalidate(barrel, getTransactionId(barrel));
}
module.exports.invalidateTransaction = invalidateTransaction;

// -------------------------
// REALM SCOPE
// -------------------------

/**
 * Get the realm id header from the request object stored in the barrel.
 *
 * @param barrel
 * @returns {*}
 */
function getRealmId(barrel) {
    return "_realm_" + barrel.realmId;
}

/**
 * Set a realm-scoped key/value pair.
 *
 * @param barrel
 * @param key
 * @param value
 * @returns {Promise|Promise<T>}
 */
function setRealmAttribute(barrel, key, value) {
    return setAttribute(barrel, getRealmId(barrel), key, value);
}
module.exports.setRealmAttribute = setRealmAttribute;

/**
 * Get the value of a realm-scoped attribute.
 *
 * @param barrel
 * @param key
 * @returns {Promise|Promise<T>}
 */
function getRealmAttribute(barrel, key) {
    return getAttribute(barrel, getRealmId(barrel), key);
}
module.exports.getRealmAttribute = getRealmAttribute;

/**
 * Remove a realm-scoped key/value pair.
 *
 * @param barrel
 * @param key
 * @returns {Promise|Promise<T>}
 */
function removeRealmAttribute(barrel, key) {
    return removeAttribute(barrel, getRealmId(barrel), key);
}
module.exports.removeRealmAttribute = removeRealmAttribute;

/**
 * Get all the current realm-scoped keys.
 *
 * @param barrel
 * @returns {Promise|Promise<T>}
 */
function getRealmAttributeKeys(barrel) {
    return getAttributeKeys(barrel, getRealmId(barrel));
}
module.exports.getRealmAttributeKeys = getRealmAttributeKeys;

/**
 * Invalidate the current realm-scoped storage.  This should
 * generally be used for cleaning up the entire scope when it's no longer
 * valid.
 *
 * @param barrel
 * @returns {Promise|Promise<T>}
 */
function invalidateRealm(barrel) {
    return invalidate(barrel, getRealmId(barrel));
}
module.exports.invalidateRealm = invalidateRealm;

// -------------------------
// PROCESS SCOPE
// -------------------------

/**
 * Get the process id header from the request object stored in the barrel.
 *
 * @param barrel
 * @returns The current process id (if there is one).
 */
function getProcessId(barrel) {
    return getHeader(barrel, PROCESS_HEADER_KEY);
}

<|endoftext|>