<commit_before>var init_template = function(obj_or_id) {
  var obj = (typeof obj_or_id == 'object') ? obj_or_id : $(obj_or_id);
  var template = obj.html();
  Mustache.parse(template);
  return template;
};

$(function() {

  // Vars
  var finder = $('#finder');

  // Init templates
  var templates = {};
  $('[type=x-tmpl-mustache]').each(function() {
    var $this = $(this);
    templates[$this.attr('id').replace(/-/g,'_')] = init_template($this);
  });

  // Template helpers
  var template_helpers = {
    custom_partial_or_default: function() {
      return function(text,render) {
        return render('{{>'+(this.custom_template||text)+'}}');
      }
    },
    adapted_field: function() {
      return function(text,render) {
        var tmpl;
        if (this.custom_template) {
          tmpl = this.custom_template;
        } else {
          tmpl = 'template_'+this.type+'_field';
          if (!(tmpl in templates)) tmpl = 'template_string_field';
        }
        return render('{{>'+tmpl+'}}');
      }
    },
    build_input_attributes: function() {
      var out = "";
      $.each(this.input_attributes, function(k,v) {
        if (v!==false) {
          out = out+' '+k;
          if (v!==true) out = out+'=\''+Mustache.escape(v)+'\'';
        }
      });
      return out;
    }
  };

  // Template render
  var mustache_render = function(data) {
    var data_and_helpers = $.extend(data,template_helpers);
    return Mustache.render(templates[data.template],data_and_helpers,templates);
  };

  // Sortable
  var make_sortable = function(selector,context) {
    var obj = (typeof selector == 'string') ? $(selector,context) : selector;
    return obj.sortable({
      forcePlaceholderSize: true,
      handle: '.handle'
    });
  };

  // Errors
  var mark_errors = function(context,report) {
    $.each(report,function(k,v) {
      var field = context.find('> [data-field-name='+k+']:first');
      if (field.is('fieldset')) {
        $.each(v, function(index,subreport) {
          var subcontext = field.find('> .nested-documents > li:nth('+index+')');
          mark_errors(subcontext, subreport);
        });
      } else {
        field.addClass('invalid');
        var errors = ", "+v.join(', ')+"";
        field.find('> label').append(errors);
      }
    });
  };

  // Ajax form
  $('body').on('submit','form.admin-post, form.admin-put', function(e) {
    e.preventDefault();
    var self = $(this);
    var submit_button = $('input[type=submit]',self);
    submit_button.hide();
    $.ajax({
      url: self.attr('action'),
      type: (self.is('.admin-put') ? 'put' : 'post'),
      data: new FormData(this),
      processData: false,
      contentType: false,
      success: function(res) {
        if (res.success==true) {
          finder.find('> li:nth-last-child(3) .selected').trigger('click.columnav',[function(cb_object) {
            var target = $('[data-id='+res.data.id+']', cb_object.column);
            if (target.size()>0) {
              cb_object.column.animate({scrollTop: target.position().top});
            }
          }]);
        }
      },
      error: function(xhr) {
        res = xhr.responseJSON;
        if (res.success==false) {
          $('.invalid',self).removeClass('invalid');
          $('.errors',self).remove();
          mark_errors(self,res.data);
          self.closest('.column').animate({scrollTop: self.find('.invalid:first').position().top});
          submit_button.show();
        }
      }
    });
  });

  // Create nested document
  $('body').on('click','.new-nested-document-btn', function(e) {
    e.preventDefault();
    var self = $(this);
    $.get(this.href, function(data) {
      var content = $(mustache_render(data));
      make_sortable(self.closest('fieldset').find('> ol').append(content).sortable('destroy'));
    });
  });

  // Ajax delete document
  $('body').on('click', 'button.admin-delete', function(e) {
    e.preventDefault();
    var self = $(this);
    if (confirm('Are you sure you want to delete this item? This operation is not reversible.')) {
      $.ajax({
        url: self.val(),
        type: 'DELETE',
        success: function() {
          var li = self.parents('li.admin-list-item');
          li.fadeOut(function() {
            li.remove();
          });
        }
      });
    }
  });

  // Ajax delete nested document
  $('body').on('click', 'button.admin-delete-nested', function(e) {
    e.preventDefault();
    var self = $(this);
    if (confirm('Are you sure you want to delete this item? This operation is not reversible.')) {
      var li = self.closest('li');
      li.fadeOut(function() {
        li.remove();
      });
    }
  });

  // Init column
  var init_column = function(c) {

    // Sort list item
    make_sortable('.documents',c).bind('sortupdate', function(e, ui) {
      var list = $(ui.item).closest('.documents');
      var ids = list.children().map(function() {
        return $(this).data().id;
      }).get();
      $.ajax({
        url: list.data().sortUrl,
        type: 'put',
        data: {
          action: 'sort',
          field: list.data().sortField,
          ids: ids
        }
      });
      /*
      ui.item contains the current dragged element.
      ui.item.index() contains the new index of the dragged element
      ui.oldindex contains the old index of the dragged element
      ui.startparent contains the element that the dragged item comes from
      ui.endparent contains the element that the dragged item was added to
      */
    });

    // Sort nested documents
    make_sortable('.nested-documents',c);

  }; // End - Init column

  // Init finder
  finder.columnav({
    on_push: function(data) {
      init_column(data.column);
    },
    process_data: function(data) {
      if (typeof data == 'object') {
        return mustache_render(data);
      } else {
        return data;
      }
    }
  });
  finder.trigger('getandpush.columnav',[window.admin_path+window.index_path]);

}); // End - DomReady

<commit_msg>Scroll_to function in the admin<commit_after>var init_template = function(obj_or_id) {
  var obj = (typeof obj_or_id == 'object') ? obj_or_id : $(obj_or_id);
  var template = obj.html();
  Mustache.parse(template);
  return template;
};

$(function() {

  // Vars
  var finder = $('#finder');

  // Init templates
  var templates = {};
  $('[type=x-tmpl-mustache]').each(function() {
    var $this = $(this);
    templates[$this.attr('id').replace(/-/g,'_')] = init_template($this);
  });

  // Template helpers
  var template_helpers = {
    custom_partial_or_default: function() {
      return function(text,render) {
        return render('{{>'+(this.custom_template||text)+'}}');
      }
    },
    adapted_field: function() {
      return function(text,render) {
        var tmpl;
        if (this.custom_template) {
          tmpl = this.custom_template;
        } else {
          tmpl = 'template_'+this.type+'_field';
          if (!(tmpl in templates)) tmpl = 'template_string_field';
        }
        return render('{{>'+tmpl+'}}');
      }
    },
    build_input_attributes: function() {
      var out = "";
      $.each(this.input_attributes, function(k,v) {
        if (v!==false) {
          out = out+' '+k;
          if (v!==true) out = out+'=\''+Mustache.escape(v)+'\'';
        }
      });
      return out;
    }
  };

  // Template render
  var mustache_render = function(data) {
    var data_and_helpers = $.extend(data,template_helpers);
    return Mustache.render(templates[data.template],data_and_helpers,templates);
  };

  // Sortable
  var make_sortable = function(selector,context) {
    var obj = (typeof selector == 'string') ? $(selector,context) : selector;
    return obj.sortable({
      forcePlaceholderSize: true,
      handle: '.handle'
    });
  };

  var scroll_to = function(el, column) {
    if (!column) {
      column = el.closest('.column');
    }
    column.animate({scrollTop: el.position().top});
  };

  // Errors
  var mark_errors = function(context,report) {
    $.each(report,function(k,v) {
      var field = context.find('> [data-field-name='+k+']:first');
      if (field.is('fieldset')) {
        $.each(v, function(index,subreport) {
          var subcontext = field.find('> .nested-documents > li:nth('+index+')');
          mark_errors(subcontext, subreport);
        });
      } else {
        field.addClass('invalid');
        var errors = ", "+v.join(', ')+"";
        field.find('> label').append(errors);
      }
    });
  };

  // Ajax form
  $('body').on('submit','form.admin-post, form.admin-put', function(e) {
    e.preventDefault();
    var self = $(this);
    var submit_button = $('input[type=submit]',self);
    submit_button.hide();
    $.ajax({
      url: self.attr('action'),
      type: (self.is('.admin-put') ? 'put' : 'post'),
      data: new FormData(this),
      processData: false,
      contentType: false,
      success: function(res) {
        if (res.success==true) {
          finder.find('> li:nth-last-child(3) .selected').trigger('click.columnav',[function(cb_object) {
            var target = $('[data-id='+res.data.id+']', cb_object.column);
            if (target.size()>0) {
              scroll_to(target, cb_object.column);
            }
          }]);
        }
      },
      error: function(xhr) {
        res = xhr.responseJSON;
        if (res.success==false) {
          $('.invalid',self).removeClass('invalid');
          $('.errors',self).remove();
          mark_errors(self,res.data);
          scroll_to(self.find('.invalid:first'));
          submit_button.show();
        }
      }
    });
  });

  // Create nested document
  $('body').on('click','.new-nested-document-btn', function(e) {
    e.preventDefault();
    var self = $(this);
    $.get(this.href, function(data) {
      var content = $(mustache_render(data));
      make_sortable(self.closest('fieldset').find('> ol').append(content).sortable('destroy'));
      scroll_to(content);
    });
  });

  // Ajax delete document
  $('body').on('click', 'button.admin-delete', function(e) {
    e.preventDefault();
    var self = $(this);
    if (confirm('Are you sure you want to delete this item? This operation is not reversible.')) {
      $.ajax({
        url: self.val(),
        type: 'DELETE',
        success: function() {
          var li = self.parents('li.admin-list-item');
          li.fadeOut(function() {
            li.remove();
          });
        }
      });
    }
  });

  // Ajax delete nested document
  $('body').on('click', 'button.admin-delete-nested', function(e) {
    e.preventDefault();
    var self = $(this);
    if (confirm('Are you sure you want to delete this item? This operation is not reversible.')) {
      var li = self.closest('li');
      li.fadeOut(function() {
        li.remove();
      });
    }
  });

  // Init column
  var init_column = function(c) {

    // Sort list item
    make_sortable('.documents',c).bind('sortupdate', function(e, ui) {
      var list = $(ui.item).closest('.documents');
      var ids = list.children().map(function() {
        return $(this).data().id;
      }).get();
      $.ajax({
        url: list.data().sortUrl,
        type: 'put',
        data: {
          action: 'sort',
          field: list.data().sortField,
          ids: ids
        }
      });
      /*
      ui.item contains the current dragged element.
      ui.item.index() contains the new index of the dragged element
      ui.oldindex contains the old index of the dragged element
      ui.startparent contains the element that the dragged item comes from
      ui.endparent contains the element that the dragged item was added to
      */
    });

    // Sort nested documents
    make_sortable('.nested-documents',c);

  }; // End - Init column

  // Init finder
  finder.columnav({
    on_push: function(data) {
      init_column(data.column);
    },
    process_data: function(data) {
      if (typeof data == 'object') {
        return mustache_render(data);
      } else {
        return data;
      }
    }
  });
  finder.trigger('getandpush.columnav',[window.admin_path+window.index_path]);

}); // End - DomReady

<|endoftext|>


<commit_before>/*
MIT License

Copyright (c) 2017 Charles Strube

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

var easingEquations = require('./easing.js');

window.requestAnimFrame = (function() {
    return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        function(callback) {
            window.setTimeout(callback, 1000 / 60);
        };
})();

/**
 * animate, can animate any integer
 */
var Animate = function () {
    this.duration = 400;
    this.fps      = 60;
    this.interval = 1000/this.fps;
    this.ease     = 'easeInOutCubic';
};

Animate.prototype = {

    /**
     * ease mod
     * @param  {string} ease    easename
     * @return {object} this
     */
    setEase: function (ease) {
        this.ease = ease;
        return this;
    },

    /**
     * set fps
     * @param  {integer} fps
     * @return {object} this
     */
    setFps: function (fps) {
        this.fps = fps;
        return this;
    },

    /**
     * calc based on speed
     * initial = 0, target = 400, speed = 400 will result to one second
     * @param  {integer} initial initial value
     * @param  {integer} target  destination value
     * @param  {integer} speed   units per second
     * @return {object} this
     */
    setSpeed: function (initial, target, speed) {
        this.duration = Math.max(0.1, Math.min(Math.abs(initial - target) / speed, 0.8));
        return this;
    },

    /**
     * set custom duration
     * @return {object} this
     */
    setDuration: function (duration) {
        this.duration = duration;
        return this;
    },

    /**
     * get correct value for current interpolation
     * @param  {integer} initial initial
     * @param  {integer} target  target
     * @param  {integer} duration       animation duration left
     * @return {integer}         current
     */
    interpolation: function (initial, target, duration) {
        duration = duration || this.currentIntWithEase;
        return initial + ((target - initial) * duration);
    },

    /**
     * get current progresse
     * @param  {integer} delta delta
     * @return {integer}       current progress
     */
    getProgress: function () {
        return this.getDelta() / this.duration;
    },

    /**
     * get time since the beginning
     * @return {integer} time
     */
    getDelta: function () {
        return Date.now() - this.start;
    },

    /**
     * get epsilon (time since the last time)
     * @param  {integer} now current date
     * @return {interger}    time left
     */
    getEpsilon: function (now) {
        this.epsilon = now - this.then;
        return this.epsilon;
    },

    /**
     * check if is new frame
     * @return {boolean}
     */
    isNewFrame: function (now) {
        return this.getEpsilon(now) > this.interval;
    },

    /**
     * update then if the frame is complete
     * @param  {integer} now current date
     * @return {integer}     new date
     */
    updateFraming: function (now) {
        this.then = now - (this.epsilon % this.interval);
        return this.then;
    },

    /**
     * request animation frame with two callback
     * @param  {function} callback1 while animating
     * @param  {function} callback2 when is done
     * @return {void}
     */
    request: function (callback1, callback2) {

        // get callbacks
        this.callback1 = callback1;
        this.callback2 = callback2;

        // get initial start
        this.start     = Date.now();

        // get time for interval
        this.then      = Date.now();
        this.loop();
        return this;
    },

    /**
     * loop function
     * @return {void}
     */
    loop: function  () {

        // current
        var now = Date.now();

        // if last time > interval
        if (this.isNewFrame(now)) {

            // refresh time
            this.updateFraming(now);

            // ================= drawing =================
            // get progress with ease
            var progress            = this.getProgress();
            this.currentIntWithEase = easingEquations[this.ease](progress);

            // if progress is between 0 and 1
            if (progress < 1) {
                if (this.callback1) this.callback1(this.currentIntWithEase);
            }

            // animation is done
            else {
                if (this.callback2) this.callback2();
                this.start = 0;
                return this;
            }
        }
        requestAnimFrame(this.loop.bind(this));
    }

};

module.exports = Animate;
<commit_msg>Update callback<commit_after>/*
MIT License

Copyright (c) 2017 Charles Strube

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

var easingEquations = require('./easing.js');

window.requestAnimFrame = (function () {
    return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        function (callback) {
            window.setTimeout(callback, 1000 / 60);
        };
})();

/**
 * animate, can animate any integer
 */
var Animate = function () {
    this.duration = 400;
    this.fps = 60;
    this.interval = 1000 / this.fps;
    this.ease = 'easeInOutCubic';
};

Animate.prototype = {

    /**
     * ease mod
     * @param  {string} ease    easename
     * @return {object} this
     */
    setEase: function (ease) {
        this.ease = ease;
        return this;
    },

    /**
     * set fps
     * @param  {integer} fps
     * @return {object} this
     */
    setFps: function (fps) {
        this.fps = fps;
        return this;
    },

    /**
     * calc based on speed
     * initial = 0, target = 400, speed = 400 will result to one second
     * @param  {integer} initial initial value
     * @param  {integer} target  destination value
     * @param  {integer} speed   units per second
     * @return {object} this
     */
    setSpeed: function (initial, target, speed) {
        this.duration = Math.max(0.1, Math.min(Math.abs(initial - target) / speed, 0.8));
        return this;
    },

    /**
     * set custom duration
     * @return {object} this
     */
    setDuration: function (duration) {
        this.duration = duration;
        return this;
    },

    /**
     * get correct value for current interpolation
     * @param  {integer} initial initial
     * @param  {integer} target  target
     * @param  {integer} duration       animation duration left
     * @return {integer}         current
     */
    interpolation: function (initial, target, duration) {
        duration = duration || this.currentIntWithEase;
        return initial + ((target - initial) * duration);
    },

    /**
     * get current progresse
     * @param  {integer} delta delta
     * @return {integer}       current progress
     */
    getProgress: function () {
        return this.getDelta() / this.duration;
    },

    /**
     * get time since the beginning
     * @return {integer} time
     */
    getDelta: function () {
        return Date.now() - this.start;
    },

    /**
     * get epsilon (time since the last time)
     * @param  {integer} now current date
     * @return {interger}    time left
     */
    getEpsilon: function (now) {
        this.epsilon = now - this.then;
        return this.epsilon;
    },

    /**
     * check if is new frame
     * @return {boolean}
     */
    isNewFrame: function (now) {
        return this.getEpsilon(now) > this.interval;
    },

    /**
     * update then if the frame is complete
     * @param  {integer} now current date
     * @return {integer}     new date
     */
    updateFraming: function (now) {
        this.then = now - (this.epsilon % this.interval);
        return this.then;
    },

    /**
     * request animation frame with two callback
     * @param  {function} callback1 while animating
     * @param  {function} callback2 when is done
     * @return {void}
     */
    request: function (callback1, callback2) {

        // get callbacks
        this.callback1 = callback1;
        this.callback2 = callback2;

        // get initial start
        this.start = Date.now();

        // get time for interval
        this.then = Date.now();
        this.loop();
        return this;
    },

    /**
     * loop function
     * @return {void}
     */
    loop: function () {

        // current
        var now = Date.now();

        // if last time > interval
        if (this.isNewFrame(now)) {

            // refresh time
            this.updateFraming(now);

            // ================= drawing =================
            // get progress with ease
            var progress = this.getProgress();

            // if progress is between 0 and 1
            if (progress < 1) {
                // current easing
                this.currentIntWithEase = easingEquations[this.ease](progress);

                // call current callback
                if (this.callback1 && typeof this.callback1 === 'function')
                    this.callback1(this.currentIntWithEase);
            } else { // animation is done
                // call current callback and finish it

                this.currentIntWithEase = easingEquations[this.ease](1);
                if (this.callback1 && typeof this.callback2 === 'function')
                    this.callback1(this.currentIntWithEase);

                // optionnal callback
                if (this.callback2 && typeof this.callback2 === 'function')
                    this.callback2();

                this.start = 0;
                return this;
            }
        }
        requestAnimFrame(this.loop.bind(this));
    }

};

module.exports = Animate;
<|endoftext|>


<commit_before>'use strict';

const xml = require('xml');
const NAMESPACE = 'services';

const typesMapping = {
  STRING : { javaType: 'java.lang.String' },
  BOOLEAN: { javaType: 'boolean', nativeType: 'bool' },
  NUMBER : { javaType: 'float', nativeType: 'float' },
  ARRAY  : { javaType: generic('javaType', 'java.util.List'), nativeType: generic('nativeType', 'List') },
  OBJECT : { javaType: 'java.lang.Object' },
  DATE   : { javaType: 'java.util.Date', nativeType: 'DateTime' }
};

function packaged(name) {
  return `${NAMESPACE}.${name}`;
}

function generic(nature, type) {
  return function(elementType) {
    return elementType ? `${type}<${elementType[nature]}>` : type;
  };
}

function unwrapPromise(type) {
  return type && type.name === 'Promise' ? unwrapPromise(type.elementType) : type;
}

function getTypeMapping(type, definitions) {
  type = unwrapPromise(type) || { name: 'void' };

  function resolve(nature, withinNamespace) {
    let result = mapped && mapped[nature];

    if (typeof result === 'function') {
      result = result(mappedSubType);
    }

    result = result || type.name;

    if (definitions[result] && withinNamespace) {
      result = packaged(result);
    }

    return result;
  }

  const mapped = typesMapping[type.name.toUpperCase()];
  const mappedSubType = type.elementType && getTypeMapping(type.elementType, definitions);

  return {
    type       : resolve('type'),
    javaType   : resolve('javaType', true),
    nativeType : resolve('nativeType', true),
    fullType   : resolve('fullType', true),
    elementType: mappedSubType && mappedSubType.type
  };
}

const HTTP_METHODS = ['GET', 'PUT', 'POST', 'DELETE'];
const isValidHttpMethod = value => HTTP_METHODS.indexOf(value) !== -1;

/**
 * Enriches service method node by adding 'method', 'route' and 'description' attributes.
 * @param {Object} methodNode
 * @param {Object} method
 * @returns {Object} methodNode
 */
function enrichMethodNode(methodNode, method) {
  method.description && (methodNode.description = method.description);

  if (method.tags.route) {
    let httpPath = method.tags.route;
    let httpMethod = 'GET';
    const sepPos = httpPath.indexOf(' ');

    if (sepPos !== -1) {
      httpMethod = httpPath.substr(0, sepPos).toUpperCase();
      httpPath = httpPath.substr(sepPos + 1);

      if (!isValidHttpMethod(httpMethod)) {
        throw new Error(`Unsupported HTTP method [${httpMethod}] for ${method.name} method`);
      }
    }

    methodNode.method = httpMethod;
    methodNode.path = httpPath;
  }

  return methodNode;
}

/**
 * @param {Array.<String>} services
 * @param {Object.<String, Object>} definitions
 * @returns {*}
 */
function buildServicesXml(services, definitions) {
  const nsNode = [{ _attr: { name: NAMESPACE, fullname: NAMESPACE } }];
  const runtimeNode = [{ _attr: { generationMode: 'FULL' } }];

  const types = new Set();

  function registerType(type) {
    if (type && definitions[type] && !types.has(type)) {
      nsNode.push(dataTypeNode(definitions[type]));
      types.add(type);
    }
  }

  function typedNode(name, type) {
    const mapping = getTypeMapping(type, definitions);

    const result = {
      name      : name,
      type      : mapping.type,
      nativetype: mapping.nativeType,
      fulltype  : mapping.fullType,
      javatype  : mapping.javaType
    };

    mapping.elementType && (result.elementType = mapping.elementType);

    registerType(result.type);
    registerType(result.elementType);

    return result;
  }

  function dataTypeNode(definition) {
    const attributes = {
      name         : definition.name,
      description  : definition.description || definition.name,
      fullname     : packaged(definition.name),
      typeNamespace: NAMESPACE
    };

    const datatype = [];
    datatype.push({ _attr: attributes });

    Object.keys(definition.properties).forEach(propName => {
      const node = typedNode(propName, definition.properties[propName].type);

      datatype.push({ field: { _attr: node } });
    });

    return { datatype: datatype };
  }

  services.forEach(function(serviceName) {
    const serviceDef = definitions[serviceName];
    const serviceNode = [{
      _attr: {
        name       : serviceName,
        description: serviceDef.description || serviceName,
        fullname   : packaged(serviceName),
        namespace  : NAMESPACE
      }
    }];

    nsNode.push({ service: serviceNode });

    if (serviceDef) {
      Object.keys(serviceDef.methods).forEach(name => {
        const method = serviceDef.methods[name];

        if (method.access !== 'private') {
          const methodNode = [{
            _attr: enrichMethodNode(typedNode(name, method.returnType), method)
          }];

          method.params.forEach(param => {
            const argNode = typedNode(param.name, param.type);
            argNode.required = !param.optional;

            methodNode.push({
              arg: {
                _attr: argNode
              }
            });
          });

          serviceNode.push({ method: methodNode });
        }
      });
    }
  });

  return xml({ namespaces: [{ namespace: nsNode }, { runtime: runtimeNode }] }, {
    declaration: { encoding: 'ISO-8859-1' },
    indent     : '  '
  });
}

exports.buildXML = buildServicesXml;<commit_msg>fix (service descriptor) Cannot read property 'description' of undefined<commit_after>'use strict';

const xml = require('xml');
const NAMESPACE = 'services';

const typesMapping = {
  STRING : { javaType: 'java.lang.String' },
  BOOLEAN: { javaType: 'boolean', nativeType: 'bool' },
  NUMBER : { javaType: 'float', nativeType: 'float' },
  ARRAY  : { javaType: generic('javaType', 'java.util.List'), nativeType: generic('nativeType', 'List') },
  OBJECT : { javaType: 'java.lang.Object' },
  DATE   : { javaType: 'java.util.Date', nativeType: 'DateTime' }
};

function packaged(name) {
  return `${NAMESPACE}.${name}`;
}

function generic(nature, type) {
  return function(elementType) {
    return elementType ? `${type}<${elementType[nature]}>` : type;
  };
}

function unwrapPromise(type) {
  return type && type.name === 'Promise' ? unwrapPromise(type.elementType) : type;
}

function getTypeMapping(type, definitions) {
  type = unwrapPromise(type) || { name: 'void' };

  function resolve(nature, withinNamespace) {
    let result = mapped && mapped[nature];

    if (typeof result === 'function') {
      result = result(mappedSubType);
    }

    result = result || type.name;

    if (definitions[result] && withinNamespace) {
      result = packaged(result);
    }

    return result;
  }

  const mapped = typesMapping[type.name.toUpperCase()];
  const mappedSubType = type.elementType && getTypeMapping(type.elementType, definitions);

  return {
    type       : resolve('type'),
    javaType   : resolve('javaType', true),
    nativeType : resolve('nativeType', true),
    fullType   : resolve('fullType', true),
    elementType: mappedSubType && mappedSubType.type
  };
}

const HTTP_METHODS = ['GET', 'PUT', 'POST', 'DELETE'];
const isValidHttpMethod = value => HTTP_METHODS.indexOf(value) !== -1;

/**
 * Enriches service method node by adding 'method', 'route' and 'description' attributes.
 * @param {Object} methodNode
 * @param {Object} method
 * @returns {Object} methodNode
 */
function enrichMethodNode(methodNode, method) {
  method.description && (methodNode.description = method.description);

  if (method.tags.route) {
    let httpPath = method.tags.route;
    let httpMethod = 'GET';
    const sepPos = httpPath.indexOf(' ');

    if (sepPos !== -1) {
      httpMethod = httpPath.substr(0, sepPos).toUpperCase();
      httpPath = httpPath.substr(sepPos + 1);

      if (!isValidHttpMethod(httpMethod)) {
        throw new Error(`Unsupported HTTP method [${httpMethod}] for ${method.name} method`);
      }
    }

    methodNode.method = httpMethod;
    methodNode.path = httpPath;
  }

  return methodNode;
}

/**
 * @param {Array.<String>} services
 * @param {Object.<String, Object>} definitions
 * @returns {*}
 */
function buildServicesXml(services, definitions) {
  const nsNode = [{ _attr: { name: NAMESPACE, fullname: NAMESPACE } }];
  const runtimeNode = [{ _attr: { generationMode: 'FULL' } }];

  const types = new Set();

  function registerType(type) {
    if (type && definitions[type] && !types.has(type)) {
      nsNode.push(dataTypeNode(definitions[type]));
      types.add(type);
    }
  }

  function typedNode(name, type) {
    const mapping = getTypeMapping(type, definitions);

    const result = {
      name      : name,
      type      : mapping.type,
      nativetype: mapping.nativeType,
      fulltype  : mapping.fullType,
      javatype  : mapping.javaType
    };

    mapping.elementType && (result.elementType = mapping.elementType);

    registerType(result.type);
    registerType(result.elementType);

    return result;
  }

  function dataTypeNode(definition) {
    const attributes = {
      name         : definition.name,
      description  : definition.description || definition.name,
      fullname     : packaged(definition.name),
      typeNamespace: NAMESPACE
    };

    const datatype = [];
    datatype.push({ _attr: attributes });

    Object.keys(definition.properties).forEach(propName => {
      const node = typedNode(propName, definition.properties[propName].type);

      datatype.push({ field: { _attr: node } });
    });

    return { datatype: datatype };
  }

  services.forEach(function(serviceName) {
    const serviceDef = definitions[serviceName];
    const serviceNode = [{
      _attr: {
        name       : serviceName,
        description: (serviceDef && serviceDef.description) || serviceName,
        fullname   : packaged(serviceName),
        namespace  : NAMESPACE
      }
    }];

    nsNode.push({ service: serviceNode });

    if (serviceDef) {
      Object.keys(serviceDef.methods).forEach(name => {
        const method = serviceDef.methods[name];

        if (method.access !== 'private') {
          const methodNode = [{
            _attr: enrichMethodNode(typedNode(name, method.returnType), method)
          }];

          method.params.forEach(param => {
            const argNode = typedNode(param.name, param.type);
            argNode.required = !param.optional;

            methodNode.push({
              arg: {
                _attr: argNode
              }
            });
          });

          serviceNode.push({ method: methodNode });
        }
      });
    }
  });

  return xml({ namespaces: [{ namespace: nsNode }, { runtime: runtimeNode }] }, {
    declaration: { encoding: 'ISO-8859-1' },
    indent     : '  '
  });
}

exports.buildXML = buildServicesXml;<|endoftext|>


<commit_before>/*
  Copyright 2012 - $Date $ by PeopleWare n.v.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

define(
  ["dojo/_base/declare", "dojo/_base/lang", "ppwcode-util-oddsAndEnds/js", "dojo/has"],
  function(declare, lang, js, has) {

    //noinspection LocalVariableNamingConventionJS
    var _PreconditionViolationError = declare([Error], {
      instance: null,
      method: null,
      condition: null,
      arguments: null,
      caller: null,
      constructor: function(instance, method, caller, callArguments, condition) {
        this.instance = instance;
        this.method = (method && method.nom) || method;
        this.caller = (caller && caller.nom) || caller;
        this.arguments = callArguments;
        this.condition = condition;
        console.info(this.stack);
      },
      toString: function() {
        return "Precondition violation: " + this.condition +
               " (on " + this.instance.toString() + " in method " + this.method + ", called from " + this.caller + ")";
      }
    });

    //noinspection LocalVariableNamingConventionJS
    var _ContractMixin = declare(
      null,
      {
        _c_invar: [],

        _c_pre: function(condition) {
          if (has("ppwcode-contracts-precondition") && !condition.apply(this)) {
            throw new _PreconditionViolationError(
              this,
              this._c_pre.caller,
              this._c_pre.caller.caller,
              this._c_pre.caller.arguments,
              condition
            );
          }
        },

        _c_prop: function(subject, propName) {
          // summary:
          //   the property subject[propName] exists
          // description:
          //   if there is only 1 argument, subject is taken to be this
          var pName;
          var s;
          if (arguments.length < 2) {
            pName = subject;
            s = this;
          }
          else {
            pName = propName;
            s = subject;
          }
          return js.getAllKeys(s).some(function(k) {return k === pName;});
        },

        _c_prop_mandatory: function(subject, propName) {
          // summary:
          //   the property subject[propName] is mandatory (exists and not-null)
          // description:
          //   if there is only 1 argument, subject is taken to be this
          var pName;
          var s;
          if (arguments.length < 2) {
            pName = subject;
            s = this;
          }
          else {
            pName = propName;
            s = subject;
          }
          return this._c_prop(s, pName) && s[pName] !== null;
        },

        _c_prop_mandatory_string: function(subject, propName) {
          // summary:
          //   the property subject[propName] is a non-empty string
          // description:
          //   if there is only 1 argument, subject is taken to be this
          var pName;
          var s;
          if (arguments.length < 2) {
            pName = subject;
            s = this;
          }
          else {
            pName = propName;
            s = subject;
          }
          var exists = this._c_prop_mandatory(s, pName);
          if (exists) {
            var value = s[pName];
            return typeof value === "string" && value !== "";
          }
          else {
            return false;
          }
        },

        _c_prop_number: function(subject, propName) {
          // summary:
          //   the property subject[propName] is defined, and if it is not-null, it is a number
          // description:
          //   if there is only 1 argument, subject is taken to be this
          var pName;
          var s;
          if (arguments.length < 2) {
            pName = subject;
            s = this;
          }
          else {
            pName = propName;
            s = subject;
          }
          var exists = this._c_prop(s, pName);
          if (exists) {
            var value = s[pName];
            return value === null || value === undefined || typeof value === "number";
          }
          else {
            return false;
          }
        },

        _c_prop_int: function(subject, propName) {
          // summary:
          //   the property subject[propName] is defined, and if it is not-null, it is an integer
          // description:
          //   if there is only 1 argument, subject is taken to be this
          var pName;
          var s;
          if (arguments.length < 2) {
            pName = subject;
            s = this;
          }
          else {
            pName = propName;
            s = subject;
          }
          return this._c_prop_number(s, pName) && js.isInt(s[pName]);
        },

        _c_prop_bool: function(subject, propName) {
          // summary:
          //   the property subject[propName] is defined, and if it is not-null, it is a bool
          // description:
          //   if there is only 1 argument, subject is taken to be this
          var pName;
          var s;
          if (arguments.length < 2) {
            pName = subject;
            s = this;
          }
          else {
            pName = propName;
            s = subject;
          }
          var exists = this._c_prop(s, pName);
          if (exists) {
            var value = s[pName];
            return value === null || value === undefined || typeof value === "boolean";
          }
          else {
            return false;
          }
        },

        _c_prop_string: function(subject, propName) {
          // summary:
          //   the property subject[propName] is defined, and if it is not-null, it is a string
          // description:
          //   if there is only 1 argument, subject is taken to be this
          var pName;
          var s;
          if (arguments.length < 2) {
            pName = subject;
            s = this;
          }
          else {
            pName = propName;
            s = subject;
          }
          var exists = this._c_prop(s, pName);
          if (exists) {
            var value = s[pName];
            return value === null || value === undefined || lang.isString(value);
          }
          else {
            return false;
          }
        },

        _c_prop_date: function(subject, propName) {
          // summary:
          //   the property subject[propName] is defined, and if it is not-null, it is a Date
          // description:
          //   if there is only 1 argument, subject is taken to be this
          var pName;
          var s;
          if (arguments.length < 2) {
            pName = subject;
            s = this;
          }
          else {
            pName = propName;
            s = subject;
          }
          var exists = this._c_prop(s, pName);
          if (exists) {
            var value = s[pName];
            return value === null || value === undefined || js.typeOf(value) === "date";
          }
          else {
            return false;
          }
        },

        _c_prop_array: function(subject, propName) {
          // summary:
          //   the property subject[propName] is defined, and if it is not-null, it is an Array
          // description:
          //   if there is only 1 argument, subject is taken to be this
          var pName;
          var s;
          if (arguments.length < 2) {
            pName = subject;
            s = this;
          }
          else {
            pName = propName;
            s = subject;
          }
          var exists = this._c_prop(s, pName);
          if (exists) {
            var value = s[pName];
            return value === null || value === undefined || lang.isArray(value);
          }
          else {
            return false;
          }
        },

        _c_prop_function: function(subject, propName) {
          // summary:
          //   the property subject[propName] is defined, and if it is not-null, it is a Function
          // description:
          //   if there is only 1 argument, subject is taken to be this
          var pName;
          var s;
          if (arguments.length < 2) {
            pName = subject;
            s = this;
          }
          else {
            pName = propName;
            s = subject;
          }
          var exists = this._c_prop(s, pName);
          if (exists) {
            var value = s[pName];
            return value === null || value === undefined || lang.isFunction(value);
          }
          else {
            return false;
          }
        },

        _c_prop_instance: function(subject, propName, Constructor) {
          // summary:
          //   the property subject[propName] is defined, and if it is not-null, it is an
          //   instance of the Dojo declared type Constructor (isInstanceOf) or an
          //   EnumerationValue (isValueOf).
          // description:
          //   if there is only 1 argument, subject is taken to be this

          var pName;
          var s;
          var Constr;
          if (arguments.length < 3) {
            pName = subject;
            s = this;
            Constr = propName;
          }
          else {
            pName = propName;
            s = subject;
            Constr = Constructor;
          }

          var exists = this._c_prop(s, pName);
          if (exists) {
            var value = s[pName];
            if (!value) {
              return true;
            }
            else if (js.typeOf(Constr) === "function") {
              return value.isInstanceOf ? value.isInstanceOf(Constr) :
                     value instanceof Constr;
            }
            else if (js.typeOf(Constr) === "object") {
              // value must be an EnumerationValue, but we cannot test that here, because that would
              // create a dependency loop
              return value.isValueOf && value.isValueOf(Constr);
            }
            else {
              throw "ERROR: Constructor must be a Constructor function, or EnumerationValue definition";
            }
          }
          else {
            return false;
          }
        },

        _c_ABSTRACT: function() {
          // summary:
          //   use this to annotate a function as abstract
          // description:
          //   This method throws an exception "ABSTRACT".
          //
          //   An abstract method should be mentioned, to have a hook for documentation.
          //   Yet, an meaningful implementation is not possible.
          //   To detect errors early, and to avoid code inspection warnings, you
          //   can call this body in the abstract method. Because the method should
          //   be overwritten for every concrete subclass, this code should never be called.
          //
          //   Often, abstract methods also have parameters. These will not be used in the
          //   body of the abstract method declaration (the hook for the documentation),
          //   which will trigger code inspection warnings. To avoid these, you should
          //   add those parameters as arguments to this call.
          throw "ABSTRACT";
        },

        _c_NOP: function() {
          // summary:
          //   use this to annotate a function as having no body whatsoever
          // description:
          //   This method does NOP.
          //
          //   Methods like this must sometimes be mentioned, as a NOP implementation
          //   of an abstract method in some subclass, or in other circumstances.
          //   Using this method instead of a comment helps in avoiding unnecessary
          //   code inspection warnings.
          //
          //   Often, such NOP methods also have parameters. These will not be used in the
          //   empty body, which will trigger code inspection warnings. To avoid these, you
          //   should add those parameters as arguments to this call.
        }

      }
    );

    return _ContractMixin;
  });
<commit_msg>Optional typecheck for arrays.<commit_after>/*
  Copyright 2012 - $Date $ by PeopleWare n.v.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

define(
  ["dojo/_base/declare", "dojo/_base/lang", "ppwcode-util-oddsAndEnds/js", "dojo/has"],
  function(declare, lang, js, has) {

    //noinspection LocalVariableNamingConventionJS
    var _PreconditionViolationError = declare([Error], {
      instance: null,
      method: null,
      condition: null,
      arguments: null,
      caller: null,
      constructor: function(instance, method, caller, callArguments, condition) {
        this.instance = instance;
        this.method = (method && method.nom) || method;
        this.caller = (caller && caller.nom) || caller;
        this.arguments = callArguments;
        this.condition = condition;
        console.info(this.stack);
      },
      toString: function() {
        return "Precondition violation: " + this.condition +
               " (on " + this.instance.toString() + " in method " + this.method + ", called from " + this.caller + ")";
      }
    });

    function isInstanceOf(value, Constr) {
      if (!value) {
        return true;
      }
      else if (js.typeOf(Constr) === "function") {
        return value.isInstanceOf ? value.isInstanceOf(Constr) :
               value instanceof Constr;
      }
      else if (js.typeOf(Constr) === "object") {
        // value must be an EnumerationValue, but we cannot test that here, because that would
        // create a dependency loop
        return value.isValueOf && value.isValueOf(Constr);
      }
      else {
        throw "ERROR: Constructor must be a Constructor function, or EnumerationValue definition";
      }
    }

    //noinspection LocalVariableNamingConventionJS
    var _ContractMixin = declare(
      null,
      {
        _c_invar: [],

        _c_pre: function(condition) {
          if (has("ppwcode-contracts-precondition") && !condition.apply(this)) {
            throw new _PreconditionViolationError(
              this,
              this._c_pre.caller,
              this._c_pre.caller.caller,
              this._c_pre.caller.arguments,
              condition
            );
          }
        },

        _c_prop: function(subject, propName) {
          // summary:
          //   the property subject[propName] exists
          // description:
          //   if there is only 1 argument, subject is taken to be this
          var pName;
          var s;
          if (arguments.length < 2) {
            pName = subject;
            s = this;
          }
          else {
            pName = propName;
            s = subject;
          }
          return js.getAllKeys(s).some(function(k) {return k === pName;});
        },

        _c_prop_mandatory: function(subject, propName) {
          // summary:
          //   the property subject[propName] is mandatory (exists and not-null)
          // description:
          //   if there is only 1 argument, subject is taken to be this
          var pName;
          var s;
          if (arguments.length < 2) {
            pName = subject;
            s = this;
          }
          else {
            pName = propName;
            s = subject;
          }
          return this._c_prop(s, pName) && s[pName] !== null;
        },

        _c_prop_mandatory_string: function(subject, propName) {
          // summary:
          //   the property subject[propName] is a non-empty string
          // description:
          //   if there is only 1 argument, subject is taken to be this
          var pName;
          var s;
          if (arguments.length < 2) {
            pName = subject;
            s = this;
          }
          else {
            pName = propName;
            s = subject;
          }
          var exists = this._c_prop_mandatory(s, pName);
          if (exists) {
            var value = s[pName];
            return typeof value === "string" && value !== "";
          }
          else {
            return false;
          }
        },

        _c_prop_number: function(subject, propName) {
          // summary:
          //   the property subject[propName] is defined, and if it is not-null, it is a number
          // description:
          //   if there is only 1 argument, subject is taken to be this
          var pName;
          var s;
          if (arguments.length < 2) {
            pName = subject;
            s = this;
          }
          else {
            pName = propName;
            s = subject;
          }
          var exists = this._c_prop(s, pName);
          if (exists) {
            var value = s[pName];
            return value === null || value === undefined || typeof value === "number";
          }
          else {
            return false;
          }
        },

        _c_prop_int: function(subject, propName) {
          // summary:
          //   the property subject[propName] is defined, and if it is not-null, it is an integer
          // description:
          //   if there is only 1 argument, subject is taken to be this
          var pName;
          var s;
          if (arguments.length < 2) {
            pName = subject;
            s = this;
          }
          else {
            pName = propName;
            s = subject;
          }
          return this._c_prop_number(s, pName) && js.isInt(s[pName]);
        },

        _c_prop_bool: function(subject, propName) {
          // summary:
          //   the property subject[propName] is defined, and if it is not-null, it is a bool
          // description:
          //   if there is only 1 argument, subject is taken to be this
          var pName;
          var s;
          if (arguments.length < 2) {
            pName = subject;
            s = this;
          }
          else {
            pName = propName;
            s = subject;
          }
          var exists = this._c_prop(s, pName);
          if (exists) {
            var value = s[pName];
            return value === null || value === undefined || typeof value === "boolean";
          }
          else {
            return false;
          }
        },

        _c_prop_string: function(subject, propName) {
          // summary:
          //   the property subject[propName] is defined, and if it is not-null, it is a string
          // description:
          //   if there is only 1 argument, subject is taken to be this
          var pName;
          var s;
          if (arguments.length < 2) {
            pName = subject;
            s = this;
          }
          else {
            pName = propName;
            s = subject;
          }
          var exists = this._c_prop(s, pName);
          if (exists) {
            var value = s[pName];
            return value === null || value === undefined || lang.isString(value);
          }
          else {
            return false;
          }
        },

        _c_prop_date: function(subject, propName) {
          // summary:
          //   the property subject[propName] is defined, and if it is not-null, it is a Date
          // description:
          //   if there is only 1 argument, subject is taken to be this
          var pName;
          var s;
          if (arguments.length < 2) {
            pName = subject;
            s = this;
          }
          else {
            pName = propName;
            s = subject;
          }
          var exists = this._c_prop(s, pName);
          if (exists) {
            var value = s[pName];
            return value === null || value === undefined || js.typeOf(value) === "date";
          }
          else {
            return false;
          }
        },

        _c_prop_array: function(subject, propName, Constructor) {
          // summary:
          //   the property subject[propName] is defined, and if it is not-null, it is an Array.
          //   All elements are of type `Constructor`, if given.
          // description:
          //   if there is only 1 argument, subject is taken to be this
          var pName;
          var s;
          if (arguments.length < 2) {
            pName = subject;
            s = this;
          }
          else {
            pName = propName;
            s = subject;
          }
          var exists = this._c_prop(s, pName);
          if (exists) {
            var value = s[pName];
            return value === null
                   || value === undefined
                   || (lang.isArray(value)
                       && (!Constructor || value.every(function(e) {return isInstanceOf(e, Constructor)})));
          }
          else {
            return false;
          }
        },

        _c_prop_function: function(subject, propName) {
          // summary:
          //   the property subject[propName] is defined, and if it is not-null, it is a Function
          // description:
          //   if there is only 1 argument, subject is taken to be this
          var pName;
          var s;
          if (arguments.length < 2) {
            pName = subject;
            s = this;
          }
          else {
            pName = propName;
            s = subject;
          }
          var exists = this._c_prop(s, pName);
          if (exists) {
            var value = s[pName];
            return value === null || value === undefined || lang.isFunction(value);
          }
          else {
            return false;
          }
        },

        _c_prop_instance: function(subject, propName, Constructor) {
          // summary:
          //   the property subject[propName] is defined, and if it is not-null, it is an
          //   instance of the Dojo declared type Constructor (isInstanceOf) or an
          //   EnumerationValue (isValueOf).
          // description:
          //   if there is only 1 argument, subject is taken to be this

          var pName;
          var s;
          var Constr;
          if (arguments.length < 3) {
            pName = subject;
            s = this;
            Constr = propName;
          }
          else {
            pName = propName;
            s = subject;
            Constr = Constructor;
          }

          var exists = this._c_prop(s, pName);
          if (exists) {
            var value = s[pName];
            if (!value) {
              return true;
            }
            else {
              return isInstanceOf(value, Constr);
            }
          }
          else {
            return false;
          }
        },

        _c_ABSTRACT: function() {
          // summary:
          //   use this to annotate a function as abstract
          // description:
          //   This method throws an exception "ABSTRACT".
          //
          //   An abstract method should be mentioned, to have a hook for documentation.
          //   Yet, an meaningful implementation is not possible.
          //   To detect errors early, and to avoid code inspection warnings, you
          //   can call this body in the abstract method. Because the method should
          //   be overwritten for every concrete subclass, this code should never be called.
          //
          //   Often, abstract methods also have parameters. These will not be used in the
          //   body of the abstract method declaration (the hook for the documentation),
          //   which will trigger code inspection warnings. To avoid these, you should
          //   add those parameters as arguments to this call.
          throw "ABSTRACT";
        },

        _c_NOP: function() {
          // summary:
          //   use this to annotate a function as having no body whatsoever
          // description:
          //   This method does NOP.
          //
          //   Methods like this must sometimes be mentioned, as a NOP implementation
          //   of an abstract method in some subclass, or in other circumstances.
          //   Using this method instead of a comment helps in avoiding unnecessary
          //   code inspection warnings.
          //
          //   Often, such NOP methods also have parameters. These will not be used in the
          //   empty body, which will trigger code inspection warnings. To avoid these, you
          //   should add those parameters as arguments to this call.
        }

      }
    );

    return _ContractMixin;
  });
<|endoftext|>


<commit_before>/* Simple JSON database */
var util = require('util'),
    events = require('events'),
    fs = require('fs'),
    path = require('path'),
    foreach = require('snippets').foreach,
    config = {};

config.keep_backup = true;

/* Data */
function Data() {
	var self = this;
	events.EventEmitter.call(self);
	self._ready = false;
}
util.inherits(Data, events.EventEmitter);

/* Emit ready signal */
Data.prototype.ready = function() {
	var self = this;
	self._ready = true;
	self.emit('ready');
}

/* Wait until ready */
Data.prototype.whenReady = function(fn) {
	var self = this;
	if(self._ready) {
		fn();
		return;
	}
	self.on('ready', function() {
		fn();
	});
}

/* Load */
Data.prototype.load = function(target) {
	var self = this;
	fs.readFile(target, function (err, json_data) {
		if(err) {
			self.emit('error', err);
			return;
		}
		var data = JSON.parse(json_data);
		if(!data) {
			self.emit('error', 'Failed to read data');
		}
		foreach(data).each(function(v, k) {
			if(k[0] === '_') return;
			self[k] = v;
		});
		self.ready();
	});
	return self;
}

/* Save */
Data.prototype.save = function(target, fn) {
	var self = this,
	    data = {},
	    json_data,
	    now = new Date(),
	    target_bak,
	    target_tmp;

	if(!target) {
		fn('Target invalid: ' + target);
		return;
	}

	foreach(self).each(function(v, k) {
		if(k[0] === '_') return;
		data[k] = v;
	});
	json_data = JSON.stringify(data);
	if(!json_data) {
		fn('Failed to parse data!');
		return self;
	}

	target_bak = target + '.bak.' + now.getTime();
	target_tmp = target + '.tmp.' + now.getTime();

	//console.log('DEBUG: Writing to ' + target + ' data ' + json_data);

	// Save to temporary file
	fs.writeFile(target_tmp, json_data, 'utf8', function (err) {
		if(err) {
			fn(err);
			return;
		}
		path.exists(target, function(exists) {
			if(exists) {
				// Backup original file
				fs.rename(target, target_bak, function(err) {
					if(err) {
						fn(err);
						return;
					}

					// Change temporary file as primary
					fs.rename(target_tmp, target, function(err) {
						if(err) {
							fn(err);
							return;
						}

						if(!config.keep_backup) {
							fn();
							return;
						}

						fs.unlink(target_bak, function(err) {
							if(err) {
								fn(err);
							} else {
								fn();
							}
						});
					});
				});
				return;
			}

			// Change temporary file as primary
			fs.rename(target_tmp, target, function(err) {
				if(err) {
					fn(err);
					return;
				}
				fn();
			});

		});
	});
	return self;
}

/* Initialize */
Data.prototype.init = function(target) {
	var self = this;
	self._target = target;
	path.exists(target, function(exists) {
		if(exists) {
			self.load(target);
		} else {
			self.ready();
		}
	});
	return self;
}

/* Commit */
Data.prototype.commit = function(fn) {
	var self = this,
	    target = self._target;
	self.save(target, function(err) {
		fn(err);
	});
	return self;
}

/* Module */
var mod = module.exports = {};

mod.config = config;

mod.Data = Data;

mod.open = function(target) {
	var data = new Data();
	return data.init(target);
}

/* EOF */
<commit_msg>Added .config()<commit_after>/* Simple JSON database */
var util = require('util'),
    events = require('events'),
    fs = require('fs'),
    path = require('path'),
d    foreach = require('snippets').foreach,
    config = {};

config.keep_backup = true;

/* Data */
function Data() {
	var self = this;
	events.EventEmitter.call(self);
	self._ready = false;
}
util.inherits(Data, events.EventEmitter);

/* Emit ready signal */
Data.prototype.ready = function() {
	var self = this;
	self._ready = true;
	self.emit('ready');
}

/* Wait until ready */
Data.prototype.whenReady = function(fn) {
	var self = this;
	if(self._ready) {
		fn();
		return;
	}
	self.on('ready', function() {
		fn();
	});
}

/* Load */
Data.prototype.load = function(target) {
	var self = this;
	fs.readFile(target, function (err, json_data) {
		if(err) {
			self.emit('error', err);
			return;
		}
		var data = JSON.parse(json_data);
		if(!data) {
			self.emit('error', 'Failed to read data');
		}
		foreach(data).each(function(v, k) {
			if(k[0] === '_') return;
			self[k] = v;
		});
		self.ready();
	});
	return self;
}

/* Save */
Data.prototype.save = function(target, fn) {
	var self = this,
	    data = {},
	    json_data,
	    now = new Date(),
	    target_bak,
	    target_tmp;

	if(!target) {
		fn('Target invalid: ' + target);
		return;
	}

	foreach(self).each(function(v, k) {
		if(k[0] === '_') return;
		data[k] = v;
	});
	json_data = JSON.stringify(data);
	if(!json_data) {
		fn('Failed to parse data!');
		return self;
	}

	target_bak = target + '.bak.' + now.getTime();
	target_tmp = target + '.tmp.' + now.getTime();

	//console.log('DEBUG: Writing to ' + target + ' data ' + json_data);

	// Save to temporary file
	fs.writeFile(target_tmp, json_data, 'utf8', function (err) {
		if(err) {
			fn(err);
			return;
		}
		path.exists(target, function(exists) {
			if(exists) {
				// Backup original file
				fs.rename(target, target_bak, function(err) {
					if(err) {
						fn(err);
						return;
					}

					// Change temporary file as primary
					fs.rename(target_tmp, target, function(err) {
						if(err) {
							fn(err);
							return;
						}

						if(!config.keep_backup) {
							fn();
							return;
						}

						fs.unlink(target_bak, function(err) {
							if(err) {
								fn(err);
							} else {
								fn();
							}
						});
					});
				});
				return;
			}

			// Change temporary file as primary
			fs.rename(target_tmp, target, function(err) {
				if(err) {
					fn(err);
					return;
				}
				fn();
			});

		});
	});
	return self;
}

/* Initialize */
Data.prototype.init = function(target) {
	var self = this;
	self._target = target;
	path.exists(target, function(exists) {
		if(exists) {
			self.load(target);
		} else {
			self.ready();
		}
	});
	return self;
}

/* Commit */
Data.prototype.commit = function(fn) {
	var self = this,
	    target = self._target;
	self.save(target, function(err) {
		fn(err);
	});
	return self;
}

/* Module */
var mod = module.exports = {};

mod._config = config;

/* Configure DMAPI from outside */
mod.config = function(data) {
    var my = this;
    foreach(data).each(function(v, k) {
        my._config[k] = v;
    });
	return my;
}

mod.Data = Data;

mod.open = function(target) {
	var data = new Data();
	return data.init(target);
}

/* EOF */
<|endoftext|>


<commit_before>var stream = require('stream')
, eventEmitter = require('events').EventEmitter
, inherits = require('inherits')

function Bricoleur (opts) { // provide a scope option to set server/browser
  if (!(this instanceof Bricoleur)) return new Bricoleur(opts)
  stream.Stream.call(this)
  if (!opts) opts = {}
  this.readable = true
  this.writable = true

  // CONSTANTS
  var SELF = this
  , MAP = null
  , BROWSER = false
  , _ = {} // module scope

  if (process.browser) BROWSER = true

  this.compile = function compileClient (next) {
  }

  this.write  = function (chunk,enc,next) {
    console.log(chunk.toString())
  }

  this._read = function (size) {} // !?!

  this.end = function () {
  }

  this.addConnection = function (key) { // user socket connection
    self[key] = {}
    var s = self[key]
    s.id = key
    self.conns.push(key)

    // add write stream
    s.in = new stream.Writable()
    s.in._write = function (chunk, encoding, cb) {
      self.recv(chunk)
      cb()
    }

    // add read stream
    s.out = new stream()
    s.out.readable = true
    s.send = function (data) {
      s.out.emit('data',JSON.stringify(data))
    }
  }

  this.removeConnection = function (key) {
    self[key].out.emit('close')
    delete self[key]
  }
}

inherits(Bricoleur, stream.Stream)
module.exports = Bricoleur
<commit_msg>hacked in module loading<commit_after>var stream = require('stream')
, eventEmitter = require('events').EventEmitter
, inherits = require('inherits')

function Bricoleur (opts) { // provide a scope option to set server/browser
  if (!(this instanceof Bricoleur)) return new Bricoleur(opts)
  stream.Stream.call(this)
  if (!opts) opts = {}
  this.readable = true
  this.writable = true

  // CONSTANTS
  var SELF = this
  , MAP = null
  , BROWSER = false
  , _ = {} // module scope

  if (process.browser) BROWSER = true

  this.write  = function (chunk, enc, next) {
    console.log(chunk.toString())
  }

  this._read = function (size) {} // !?!

  this.end = function () {}

  this.loadModule = function (mod) {
    console.log('loading mod '+mod.id)
    if (BROWSER===true&&mod.html){
      var m = require(mod.id.toUpperCase())
      _[mod.id] = new m(mod.html)
    }
  }

  this.unloadModule = function (mod) {

  }

  this.connect = function (mod,mod) {

  }

  this.disconnect = function (mod,mod) {

  }

  this.addConnection = function (key) { // user socket connection
    self[key] = {}
    var s = self[key]
    s.id = key
    self.conns.push(key)

    // add write stream
    s.in = new stream.Writable()
    s.in._write = function (chunk, encoding, cb) {
      self.recv(chunk)
      cb()
    }
    // add read stream
    s.out = new stream()
    s.out.readable = true
    s.send = function (data) {
      s.out.emit('data',JSON.stringify(data))
    }
  }

  this.removeConnection = function (key) {
    self[key].out.emit('close')
    delete self[key]
  }
}

inherits(Bricoleur, stream.Stream)
module.exports = Bricoleur
<|endoftext|>


<commit_before>var exec  = require('child_process').exec;
var path  = require('path');
var chalk = require('chalk');
var fs    = require('fs-extra');

var defaultEmberCliFiles = [
  'app/styles/app.css',
  'app/routes/index.js',
  'app/router.js',
  'app/app.js',
  'config/environment.js'
];

module.exports = function(config){
  var emberPath   = path.join(config.get('projectPath'), 'ember');

  return function(callback) {
    console.log();
    process.stdout.write("Removing default ember-cli files...");

    try {
      defaultEmberCliFiles.forEach(function(filePath){
        fs.removeSync(path.join(emberPath, filePath));
      });

      process.stdout.write(chalk.green("done\n"));
      callback(null);
    }
    catch(e) {
      callback(e);
    }
  }
}

<commit_msg>remove app.'s from being deleted from ember cli generated files for the time being<commit_after>var exec  = require('child_process').exec;
var path  = require('path');
var chalk = require('chalk');
var fs    = require('fs-extra');

var defaultEmberCliFiles = [
  'app/styles/app.css',
  'app/routes/index.js',
  'app/router.js',
  //'app/app.js',
  'config/environment.js'
];

module.exports = function(config){
  var emberPath   = path.join(config.get('projectPath'), 'ember');

  return function(callback) {
    console.log();
    process.stdout.write("Removing default ember-cli files...");

    try {
      defaultEmberCliFiles.forEach(function(filePath){
        fs.removeSync(path.join(emberPath, filePath));
      });

      process.stdout.write(chalk.green("done\n"));
      callback(null);
    }
    catch(e) {
      callback(e);
    }
  }
}

<|endoftext|>


<commit_before>// BRICO

var through = require('through')
var proc = process.title // node or browser

module.exports = function bricoleur (data) {

  // DATA
  var dataFilter = through(function write(d) {
    if (d.key) {
      var cat = d.key.split(':')
      console.log(cat)
    }

    // should be somekind of filter/register/lookup
    // just use level encoding info to get encoding

    // use keystructure & encoding!

    if (d.type && d.type === 'put') {
      var val
      typeof d.value === 'string' && d.value[0] === '{'
        ? val = JSON.parse(d.value)
        : val = d.value
    }
  }, function end () {
    this.emit('end')
  })

  // BOOT
  var liveStream = data.liveStream()
  liveStream.pipe(dataFilter)

  // WILDS / RUNNING MODULES
  var _ = {}

  function rm (mod) {
    _[mod].end()
    delete _[mod]
  }

  function put (mod) {
    if (map[mod] && map[mod].nimoy.process === proc)
      _[mod] = require('./_wilds/'+mod)()
  }

  function conn (mods) {
    var mods = con.split('-')
    _[mods[0]].pipe(_[mods[1]])
  }

  // METHODS / API
  return through(function interface (input) {
    // GET DATA IN!

  }, function end () {
    this.end()
  })
}

// MODE? / AUTH?
<commit_msg>index incoming map data<commit_after>// BRICO

var through = require('through')
var proc = process.title // node or browser

module.exports = function bricoleur (data) {

  // DATA
  var dataFilter = through(function write(d) {
    if (d.key) {
      var cat = d.key.split(':')[0]
      if (cat === 'wilds') index(d.value)
    }

    // should be somekind of filter/register/lookup
    // just use level encoding info to get encoding

    // use keystructure & encoding!

    if (d.type && d.type === 'put') {
      var val
      typeof d.value === 'string' && d.value[0] === '{'
        ? val = JSON.parse(d.value)
        : val = d.value
    }
  }, function end () {
    this.emit('end')
  })

  function index (pkg) { // build an index!

  }

  // BOOT
  var liveStream = data.liveStream()
  liveStream.pipe(dataFilter)

  // WILDS / RUNNING MODULES
  var _ = {}

  function rm (mod) {
    _[mod].end()
    delete _[mod]
  }

  function put (mod) {
    if (map[mod] && map[mod].nimoy.process === proc)
      _[mod] = require('./_wilds/'+mod)()
  }

  function conn (mods) {
    var mods = con.split('-')
    _[mods[0]].pipe(_[mods[1]])
  }

  // METHODS / API
  return through(function interface (input) {
    // GET DATA IN!

  }, function end () {
    this.end()
  })
}

// MODE? / AUTH?
<|endoftext|>


<commit_before>var telepath = require('tele')
, stream = require('stream')
, async = require ('async')

module.exports = function (usr) { // BRICOLEUR
  var self = this
  , map = null
  , _ = {} // module scope
  telepath(this)

  // detect if running in node or browser
  if (global.process && global.process.title === 'node') self.scope = 'server'
  if (!global.process) self.scope = 'client'

  if (self.scope === 'client') { // client side > fix it ...
    console.log('running client side')
  }

  if (usr) self.usr = usr

  this.recv = function (buffer) {
    var data = JSON.parse(buffer.toString())
    console.log(data)

    if (data.meta === 'module_map') { // add map
      console.log(data)
      map = data
      self.map = data
      self.build()
    } else if (self.scope==='client' && data.key){
      console.log(data.key)
    }
  }

  this.build = function () { // load modules && handle connections
    if (!map) throw new Error('no map')
    // add client side map build
    async.forEach(map[self.scope], lookupModule, connModules)

    function lookupModule (mod, cb) {
      var modules = self.usr.modules[self.scope]
      for (var i=0;i<modules.length;i++) {
        if (modules[i]===mod.id) {
          console.log('loading mod '+mod.id)
          self.loadModule(mod)
          break
        }
      }
      cb()
    }

    function connModules () {
      if (usr.conns) {
        console.log('modules loaded :: connecting modules...')
        async.forEach(usr.conns[self.scope], self.connModule, function () {
          console.log('connected modules for : '+usr.host)
        })
      }
      if (!usr.conns) console.log('no conns for : '+usr.host)
    }
  }

  this.connModule = function (conn, cb) { // ['modA>modB','modB>modC'] make module connections
    var modA = null
    , modB = null

    for (key in conn) { // could be clearer
      // create a start / end place to connect to on client soc conn
      modA = _[conn[key].split('>')[0]]
      modB = _[conn[key].split('>')[1]]
      console.log('connecting '+conn[key])
      if (!modA.out || !modB.in) throw new Error(modA+','+modB+' :no .out or .in connections')
      if (modA.out && modB.in) modA.out.pipe(modB.in)
      cb()
    }
  }

  this.disconnModule = function (disconn) {
  }

  this.loadModule = function (mod) { // load module!
    _[mod.id.toUpperCase()] = require(mod.filePath)
    _[mod.id] = new _[mod.id.toUpperCase()]()
    if (mod.html) _[mod.id].template = mod.html
  }

  this.unloadModule = function (mod) {
  }

  // ------------------------------------------------------------
  this.addConnection = function (key) { // user socket connection
    self[key] = {}
    var s = self[key]
    s.id = key

    // add write stream
    s.in = new stream.Writable()
    s.in._write = function (chunk, encoding, cb) {
      self.recv(chunk) // add id to obj -- for filtering
      cb()
    }

    // add read stream
    s.out = new stream()
    s.out.readable = true
    s.send = function (data) {
      s.out.emit('data',JSON.stringify(data))
    }
  }

  this.removeConnection = function (key) {
    self[key].out.emit('close')
    delete self[key]
  }// ---------------------------------------------------
}

// client communication stream
// user > brico.in[usr] [module.in] [module.out] brico.out[usr] > user
// save | persist connections(flows) : easy to make manipulate module flows
// mux -- demux ?!? howto handle multiples???

// context is f'd how to map/route conns
<commit_msg>loadModule responds to client/server modules<commit_after>var telepath = require('tele')
, stream = require('stream')
, async = require ('async')

module.exports = function (usr) { // BRICOLEUR
  var self = this
  , map = null
  , _ = {} // module scope
  telepath(this)

  // detect if running in node or browser
  if (global.process && global.process.title === 'node') self.scope = 'server'
  if (!global.process) self.scope = 'client'
  if (usr) self.usr = usr

  this.recv = function (buffer) {
    var data = JSON.parse(buffer.toString())
    console.log(data)

    if (data.meta === 'module_map') { // add map
      map = data
      self.map = data
      self.build()
    } else if (self.scope === 'client' && data.key){
      console.log(data.key)
    }
  }

  this.build = function () { // load modules && handle connections
    if (!map) throw new Error('no map')
    async.forEach(map[self.scope], lookupModule, connModules)

    function lookupModule (mod, cb) {
      var modules = usr.modules[self.scope]
      for (var i=0;i<modules.length;i++) {
        if (modules[i]===mod.id) {
          console.log('loading mod '+mod.id)
          self.loadModule(mod)
          break
        }
      }
      cb()
    }

    function connModules () {
      if (usr.conns) {
        console.log('modules loaded :: connecting modules...')
        async.forEach(usr.conns[self.scope], self.connModule, function () {
          console.log('connected modules for : '+usr.host)
        })
      }
      if (!usr.conns) console.log('no conns for : '+usr.host)
    }
  }

  this.connModule = function (conn, cb) { // ['modA>modB','modB>modC'] make module connections
    var modA = null
    , modB = null

    for (key in conn) { // could be clearer
      // create a start / end place to connect to on client soc conn
      modA = _[conn[key].split('>')[0]]
      modB = _[conn[key].split('>')[1]]
      console.log('connecting '+conn[key])
      if (!modA.out || !modB.in) throw new Error(modA+','+modB+' :no .out or .in connections')
      if (modA.out && modB.in) modA.out.pipe(modB.in)
      cb()
    }
  }

  this.disconnModule = function (disconn) {
  }

  this.loadModule = function (mod) { // load module!
    if (self.scope==='server') _[mod.id.toUpperCase()] = require(mod.filePath)
    if (self.scope==='client') _[mod.id.toUpperCase()] = require(mod.id)

    _[mod.id] = new _[mod.id.toUpperCase()]()
    if (mod.html) _[mod.id].template = mod.html
  }

  this.unloadModule = function (mod) {
  }

  // ------------------------------------------------------------
  this.addConnection = function (key) { // user socket connection
    self[key] = {}
    var s = self[key]
    s.id = key

    // add write stream
    s.in = new stream.Writable()
    s.in._write = function (chunk, encoding, cb) {
      self.recv(chunk) // add id to obj -- for filtering
      cb()
    }

    // add read stream
    s.out = new stream()
    s.out.readable = true
    s.send = function (data) {
      s.out.emit('data',JSON.stringify(data))
    }
  }

  this.removeConnection = function (key) {
    self[key].out.emit('close')
    delete self[key]
  }// ---------------------------------------------------
}

<|endoftext|>


<commit_before>// BROWSER ENVIRONMENT
if(!Function.prototype.bind) require('bindshim') //kindle jalopy doesn't have bind
var ws = require('websocket-stream');
var wss = ws('ws://192.168.1.76/');

wss.on('data', function (d) {
  var c =document.getElementById('container')
  c.innerHTML = d
})
<commit_msg>fix host add events for wss<commit_after>// BROWSER ENVIRONMENT
if(!Function.prototype.bind) require('bindshim') //kindle jalopy doesn't have bind
var host = window.document.location.host.replace(/:.*/, '')
var ws = require('websocket-stream')
var wss = ws('ws://'+host)

wss.onopen = function () {
  console.log('connected')
}
wss.on('data', function (d) {
  console.log(d)
})
wss.on('close', function () {
  console.log('server close')
})
<|endoftext|>


<commit_before>import nodeResolve from 'rollup-plugin-node-resolve';
import uglify from 'rollup-plugin-uglify';
import progress from 'rollup-plugin-progress';
import sourcemaps from 'rollup-plugin-sourcemaps';
import visualizer from 'rollup-plugin-visualizer';

var MINIFY = process.env.MINIFY;
var ROUTER = process.env.ROUTER;
var EVENTS = process.env.EVENTS;
var RESOLVE = process.env.RESOLVE;

var pkg = require('./package.json');
var banner =
`/**
 * ${pkg.description}
 * @version v${pkg.version}
 * @link ${pkg.homepage}
 * @license MIT License, http://www.opensource.org/licenses/MIT
 */`;

var uglifyOpts = { output: {} };
// retain multiline comment with @license
uglifyOpts.output.comments = (node, comment) =>
comment.type === 'comment2' && /@license/i.test(comment.value);

var plugins = [
  nodeResolve({jsnext: true}),
  progress(),
  sourcemaps(),
];

if (MINIFY) plugins.push(uglify(uglifyOpts));
if (ROUTER && MINIFY) plugins.push(visualizer({ sourcemap: true }));

var extension = MINIFY ? ".min.js" : ".js";

const BASE_CONFIG = {
  sourceMap: true,
  format: 'umd',
  exports: 'named',
  plugins: plugins,
  banner: banner,
};

const ROUTER_CONFIG = Object.assign({
  moduleName: 'angular-ui-router',
  entry: 'lib-esm/index.js',
  dest: 'release/angular-ui-router' + extension,
  globals: { angular: 'angular' },
  external: 'angular',
}, BASE_CONFIG);

const EVENTS_CONFIG = Object.assign({}, BASE_CONFIG, {
  moduleName: 'angular-ui-router-state-events',
  entry: 'lib-esm/legacy/stateEvents.js',
  dest: 'release/stateEvents' + extension,
  globals: { angular: 'angular', 'ui-router-core': 'ui-router-core' },
  external: ['angular', 'ui-router-core'],
});

const RESOLVE_CONFIG = Object.assign({}, BASE_CONFIG, {
  moduleName: 'angular-ui-router-resolve-service',
  entry: 'lib-esm/legacy/resolveService.js',
  dest: 'release/resolveService' + extension,
  globals: { angular: 'angular', 'ui-router-core': 'ui-router-core' },
  external: ['angular', 'ui-router-core'],
});

const CONFIG =
    RESOLVE ? RESOLVE_CONFIG :
    EVENTS ? EVENTS_CONFIG :
    ROUTER ? ROUTER_CONFIG : ROUTER_CONFIG;

export default CONFIG;
<commit_msg>chore(build): Remove incorrect rollup config<commit_after><|endoftext|>


<commit_before>(function(Hogan) {

  var ctor = function() {};

  // Create a Bogus namespace that inherits from Hogan.
  ctor.prototype = Hogan;
  var Bogus = new ctor();
  if (typeof module !== 'undefined') {
    module.exports = Bogus;
  }
  else {
    this.Bogus = Bogus
  }

  // Override the compiler's generate method to create Bogus templates.
  Bogus.generate = function (code, text, options) {
    if (options.asString) {
      return 'function(c,p,i){' + code + ';}';
    }

    return new Bogus.Template(new Function('c', 'p', 'i', code),
                              text, Bogus, options);
  };

  // Template class that inherits from Hogan.Template.
  Bogus.Template = function() {
      Hogan.Template.apply(this, arguments);
  };
  ctor.prototype = Hogan.Template.prototype;
  var proto = Bogus.Template.prototype = new ctor();

  // Value helper.
  var getValue = function(obj, key) {
    if (obj && typeof obj === 'object') {
      if (obj.attributes) {
        obj = obj.attributes;
      }
      if (key in obj) {
        return { val: obj[key], found: true };
      }
    }
    return { val: false, found: false };
  };

  // render a section
  proto.rs = function(context, partials, section) {
    var buf = '',
        tail = context[context.length - 1];

    if (typeof tail === 'object' && tail.forEach) {
      tail.forEach(function(model) {
        context.push(model);
        buf += section(context, partials);
        context.pop();
      });
    }
    else {
      buf = section(context, partials);
    }

    return buf;
  };

  // maybe start a section
  proto.s = function(val, ctx, partials, inverted, start, end, tags) {
    var pass;

    if (typeof val === 'object' && val.length === 0) {
      return false;
    }

    if (typeof val === 'function') {
      val = this.ls(val, ctx, partials, inverted, start, end, tags);
    }

    pass = (val === '') || !!val;

    if (!inverted && pass && ctx) {
      ctx.push((typeof val === 'object') ? val : ctx[ctx.length - 1]);
    }

    return pass;
  };

  // find values with dotted names
  proto.d = function(key, ctx, partials, returnFound) {
    var names = null,
        val = null,
        result = null,
        cx = null;

    if (key === '.') {
      return ctx[ctx.length - 1];
    }

    names = key.split('.');
    val = this.f(names[0], ctx, partials, returnFound);
    for (var i = 1; i < names.length; i++) {
      result = getValue(val, names[i]);
      if (result.found) {
        cx = val;
        val = result.val;
      }
      else {
        val = '';
        break;
      }
    }

    if (returnFound && !val) {
      return false;
    }

    if (!returnFound && typeof val === 'function') {
      ctx.push(cx);
      val = this.lv(val, ctx, partials);
      ctx.pop();
    }

    return val;
  };

  // find values with normal names
  proto.f = function(key, ctx, partials, returnFound) {
    var val = false,
        result = null,
        found = false;

    for (var i = ctx.length - 1; i >= 0; i--) {
      result = getValue(ctx[i], key);
      if (result.found) {
        found = true;
        val = result.val;
        break;
      }
    }

    if (!found) {
      return (returnFound) ? false : "";
    }

    if (!returnFound && typeof val === 'function') {
      val = this.lv(val, ctx, partials);
    }

    return val;
  };

// Require Hogan.js if we need to.
})(typeof require === 'function' ? require('hogan.js') : Hogan);
<commit_msg>Minor.<commit_after>(function(Hogan) {

  var ctor = function() {};

  // Create a Bogus namespace that inherits from Hogan.
  ctor.prototype = Hogan;
  var Bogus = new ctor();
  if (typeof module !== 'undefined') {
    module.exports = Bogus;
  }
  else {
    this.Bogus = Bogus;
  }

  // Override the compiler's generate method to create Bogus templates.
  Bogus.generate = function (code, text, options) {
    if (options.asString) {
      return 'function(c,p,i){' + code + ';}';
    }

    return new Bogus.Template(new Function('c', 'p', 'i', code),
                              text, Bogus, options);
  };

  // Template class that inherits from Hogan.Template.
  Bogus.Template = function() {
      Hogan.Template.apply(this, arguments);
  };
  ctor.prototype = Hogan.Template.prototype;
  var proto = Bogus.Template.prototype = new ctor();

  // Value helper.
  var getValue = function(obj, key) {
    if (obj && typeof obj === 'object') {
      if (obj.attributes) {
        obj = obj.attributes;
      }
      if (key in obj) {
        return { val: obj[key], found: true };
      }
    }
    return { val: false, found: false };
  };

  // render a section
  proto.rs = function(context, partials, section) {
    var buf = '',
        tail = context[context.length - 1];

    if (typeof tail === 'object' && tail.forEach) {
      tail.forEach(function(model) {
        context.push(model);
        buf += section(context, partials);
        context.pop();
      });
    }
    else {
      buf = section(context, partials);
    }

    return buf;
  };

  // maybe start a section
  proto.s = function(val, ctx, partials, inverted, start, end, tags) {
    var pass;

    if (typeof val === 'object' && val.length === 0) {
      return false;
    }

    if (typeof val === 'function') {
      val = this.ls(val, ctx, partials, inverted, start, end, tags);
    }

    pass = (val === '') || !!val;

    if (!inverted && pass && ctx) {
      ctx.push((typeof val === 'object') ? val : ctx[ctx.length - 1]);
    }

    return pass;
  };

  // find values with dotted names
  proto.d = function(key, ctx, partials, returnFound) {
    var names = null,
        val = null,
        result = null,
        cx = null;

    if (key === '.') {
      return ctx[ctx.length - 1];
    }

    names = key.split('.');
    val = this.f(names[0], ctx, partials, returnFound);
    for (var i = 1; i < names.length; i++) {
      result = getValue(val, names[i]);
      if (result.found) {
        cx = val;
        val = result.val;
      }
      else {
        val = '';
        break;
      }
    }

    if (returnFound && !val) {
      return false;
    }

    if (!returnFound && typeof val === 'function') {
      ctx.push(cx);
      val = this.lv(val, ctx, partials);
      ctx.pop();
    }

    return val;
  };

  // find values with normal names
  proto.f = function(key, ctx, partials, returnFound) {
    var val = false,
        result = null,
        found = false;

    for (var i = ctx.length - 1; i >= 0; i--) {
      result = getValue(ctx[i], key);
      if (result.found) {
        found = true;
        val = result.val;
        break;
      }
    }

    if (!found) {
      return (returnFound) ? false : "";
    }

    if (!returnFound && typeof val === 'function') {
      val = this.lv(val, ctx, partials);
    }

    return val;
  };

// Require Hogan.js if we need to.
})(typeof require === 'function' ? require('hogan.js') : Hogan);
<|endoftext|>


<commit_before>// Import Modules
const INDEX = require('../../index.js')

// Import Packages
const _ = require('lodash')
const merge = require('merge')

// Define helper variables
const ws = INDEX.connection
const mongo = INDEX.mongo
const dispatcher = INDEX.dispatcher

/**
 * Function to watch for updates on all collections
 */
const watchUpdates = () => {
  Object.keys(mongo.models).forEach(model => {
    const Model = mongo.models[model]
    ws.subscribe(`connapp.server.${model.toLowerCase()}.update`, args => {

      const sentData = (((args.argsDict || {}).data || [])[0] || {})
      console.log(sentData)
      const mobileQuery = sentData.argsDict.query
      const mobileSetdata = sentData.argsDict.setData
      const upsert = true

      Model
        .findOneAndUpdate(mobileQuery, mobileSetdata, { upsert, new: true }).exec()
        .then(updatedDoc => {
          dispatcher.updateDocumentToApp(model, updatedDoc._id, updatedDoc)
        })
        .catch(err => console.log(err))
    })
  })
}

/**
 * Function to watch for inserts on all collections
 */
const watchInserts = () => {
  Object.keys(mongo.models).forEach(model => {
    const Model = mongo.models[model]
    ws.subscribe(`connapp.server.${model.toLowerCase()}.insert`, args => {
      console.log(`connapp.server.${model.toLowerCase()}.insert Triggered`)
      const sentData = (((args.argsDict || {}).data || [])[0] || {})
      console.log(sentData)
      const mobileData = sentData.argsDict.data

      let doc = new Model(mobileData)

      // Make sure this is treated as new by the post-save hook
      doc.isNew = true

      doc.save()
        .then(res => {
          dispatcher.insertToApp(model, res)
        })
        .catch(err => console.log(err))
    })
  })
}

/**
 * Function to watch for inserts on all collections
 */
const watchSync = () => {
  Object.keys(mongo.models).forEach(model => {
    const Model = mongo.models[model]
    const uri = `connapp.server.${model.toLowerCase()}.fetch`
    // console.log(uri)
    ws.subscribe(uri, args => {
      // console.log(args)
      const sentData = (((args.argsDict || {}).data || [])[0] || {})
      const ids = sentData.argsList
      const mobileQuery = sentData.argsDict.query
      const mobileSession = sentData.argsDict.session
      const fecthAll = sentData.argsDict.fetchAll === true

      console.log(`${uri} Triggered`)
      // console.log(uri+' was triggered')

      Model
        .find(mobileQuery).exec()
        .then(data => {
          // console.log(data)
          // If nothing is found, does nothing
          if (!data.length) {
            dispatcher.insertToApp(model, {}, 0, mobileSession)
          }

          // console.log(ids)
          // Loops through the found data and dispatch route accordingly

          if (!fecthAll) {
            data.forEach(item => {
              const _id = item._id.toString()
              if ( ids.indexOf(_id) == -1 ) {
                dispatcher.insertToApp(model, item, data.length, mobileSession)
              } else {
                // console.log(item)
                dispatcher.updateDocumentToApp(model, _id, item, mobileSession)
              }
            })
          } else {
            const insertData = data.filter(item => {
              return ids.indexOf(item._id) == -1
            })
            const updateData = data.filter(item => {
              return ids.indexOf(item._id) != -1
            })

            if (insertData.length) {
              _.chunk(insertData, 500).forEach(item => {
                dispatcher.insertToApp(model, item, data.length, mobileSession)
              })
            }

            if (updateData.length) {
              updateData.forEach(item => {
                dispatcher.updateDocumentToApp(model, _id, item, mobileSession)
              })
            }
          }

	      })
        .catch(err => console.log(err))
    })
  })
}

const watchersObj = {
  watchUpdates: watchUpdates,
  watchInserts: watchInserts,
  watchSync: watchSync
}

const runAllWatchers = () => _.mapValues(
  watchersObj,
  watcher => {
    var status = true

    try {
      watcher()
    } catch(e) {
      status = e
    }

    return status
  }
)

// Exports
module.exports = {
  list: watchersObj,
  watchersStatus: runAllWatchers()
}
<commit_msg>Much smaller<commit_after>// Import Modules
const INDEX = require('../../index.js')

// Import Packages
const _ = require('lodash')
const merge = require('merge')

// Define helper variables
const ws = INDEX.connection
const mongo = INDEX.mongo
const dispatcher = INDEX.dispatcher

/**
 * Function to watch for updates on all collections
 */
const watchUpdates = () => {
  Object.keys(mongo.models).forEach(model => {
    const Model = mongo.models[model]
    ws.subscribe(`connapp.server.${model.toLowerCase()}.update`, args => {

      const sentData = (((args.argsDict || {}).data || [])[0] || {})
      console.log(sentData)
      const mobileQuery = sentData.argsDict.query
      const mobileSetdata = sentData.argsDict.setData
      const upsert = true

      Model
        .findOneAndUpdate(mobileQuery, mobileSetdata, { upsert, new: true }).exec()
        .then(updatedDoc => {
          dispatcher.updateDocumentToApp(model, updatedDoc._id, updatedDoc)
        })
        .catch(err => console.log(err))
    })
  })
}

/**
 * Function to watch for inserts on all collections
 */
const watchInserts = () => {
  Object.keys(mongo.models).forEach(model => {
    const Model = mongo.models[model]
    ws.subscribe(`connapp.server.${model.toLowerCase()}.insert`, args => {
      console.log(`connapp.server.${model.toLowerCase()}.insert Triggered`)
      const sentData = (((args.argsDict || {}).data || [])[0] || {})
      console.log(sentData)
      const mobileData = sentData.argsDict.data

      let doc = new Model(mobileData)

      // Make sure this is treated as new by the post-save hook
      doc.isNew = true

      doc.save()
        .then(res => {
          dispatcher.insertToApp(model, res)
        })
        .catch(err => console.log(err))
    })
  })
}

/**
 * Function to watch for inserts on all collections
 */
const watchSync = () => {
  Object.keys(mongo.models).forEach(model => {
    const Model = mongo.models[model]
    const uri = `connapp.server.${model.toLowerCase()}.fetch`
    // console.log(uri)
    ws.subscribe(uri, args => {
      // console.log(args)
      const sentData = (((args.argsDict || {}).data || [])[0] || {})
      const ids = sentData.argsList
      const mobileQuery = sentData.argsDict.query
      const mobileSession = sentData.argsDict.session
      const fecthAll = sentData.argsDict.fetchAll === true

      console.log(`${uri} Triggered`)
      // console.log(uri+' was triggered')

      Model
        .find(mobileQuery).exec()
        .then(data => {
          // console.log(data)
          // If nothing is found, does nothing
          if (!data.length) {
            dispatcher.insertToApp(model, {}, 0, mobileSession)
          }

          // console.log(ids)
          // Loops through the found data and dispatch route accordingly

          if (!fecthAll) {
            data.forEach(item => {
              const _id = item._id.toString()
              if ( ids.indexOf(_id) == -1 ) {
                dispatcher.insertToApp(model, item, data.length, mobileSession)
              } else {
                // console.log(item)
                dispatcher.updateDocumentToApp(model, _id, item, mobileSession)
              }
            })
          } else {
            const insertData = data.filter(item => {
              return ids.indexOf(item._id) == -1
            })
            const updateData = data.filter(item => {
              return ids.indexOf(item._id) != -1
            })

            if (insertData.length) {
              _.chunk(insertData, 20).forEach(item => {
                dispatcher.insertToApp(model, item, data.length, mobileSession)
              })
            }

            if (updateData.length) {
              updateData.forEach(item => {
                dispatcher.updateDocumentToApp(model, _id, item, mobileSession)
              })
            }
          }

	      })
        .catch(err => console.log(err))
    })
  })
}

const watchersObj = {
  watchUpdates: watchUpdates,
  watchInserts: watchInserts,
  watchSync: watchSync
}

const runAllWatchers = () => _.mapValues(
  watchersObj,
  watcher => {
    var status = true

    try {
      watcher()
    } catch(e) {
      status = e
    }

    return status
  }
)

// Exports
module.exports = {
  list: watchersObj,
  watchersStatus: runAllWatchers()
}
<|endoftext|>