<commit_before>const chai = require('chai');
const expect = chai.expect;

let {applyTemplates, tooManyNestedTemplatesError} = require('../applyTemplates');

const pageWithoutTemplatesMock = '<!DOCTYPE html>
Hello World
';
const pageWithOneTemplateMock = '<!DOCTYPE html>
Hello World
[[template-1]]';

const pageWithTemplateAppliedMock = '<!DOCTYPE html>
Hello World

This is a template
';
const pageWithNestedTemplateAppliedMock = '<!DOCTYPE html>
Hello World

This is a templateThis is a nested template
';

const templatesMock = {
  'template-1': '
This is a template
',
};

const nestedTemplateMock = {
  'template-1': '
This is a template[[template-2]]
',
  'template-2': 'This is a nested template',
};

const infiniteNestedTemplateMock = {
  'template-1': 'This is a template[[template-2]]',
  'template-2': 'This is a nested template[[template-1]]',
};

const tooManyNestedTemplatesErrorMessage = 'Too many nested templates!!';

describe('applyTemplates function', () => {
  it('Returns the same page if page has no templates in it and no templates are provided to the function.', () => {
    expect(applyTemplates(pageWithoutTemplatesMock)).to.equal(pageWithoutTemplatesMock);
  });
  it('Returns the same page if page has templates in it and no templates are provided to the function.', () => {
    expect(applyTemplates(pageWithOneTemplateMock)).to.equal(pageWithOneTemplateMock);
  });
  it('Returns the same page if page has no templates in it and templates are provided to the function.', () => {
    expect(applyTemplates(pageWithoutTemplatesMock, templatesMock)).to.equal(pageWithoutTemplatesMock);
  });
  it('Returns a new page with the template applied to it.', () => {
    expect(applyTemplates(pageWithOneTemplateMock, templatesMock)).to.equal(pageWithTemplateAppliedMock);
  });
  it('Returns a new page with the nested template applied to it.', () => {
    expect(applyTemplates(pageWithOneTemplateMock, nestedTemplateMock)).to.equal(pageWithNestedTemplateAppliedMock);
  });
  it('Throws an error when trying to apply infinite nested templates to a page.', () => {
    expect(() => applyTemplates(pageWithOneTemplateMock, infiniteNestedTemplateMock))
      .to.throw(tooManyNestedTemplatesError)
      .and.be.an.instanceOf(Error)
      .with.property('message', tooManyNestedTemplatesErrorMessage);
  });
  // it('Checks the function is called max 100 times when trying to apply infinite nested templates to a page.', () => {

  // });
});
<commit_msg>Added one more test for applyTemplates<commit_after>const chai = require('chai');
const expect = chai.expect;

let {applyTemplates, tooManyNestedTemplatesError} = require('../applyTemplates');

const pageWithoutTemplatesMock = '<!DOCTYPE html>
Hello World
';
const pageWithOneTemplateMock = '<!DOCTYPE html>
Hello World
[[template-1]]';
const pageWithOneTemplateWithSpacesMock = '<!DOCTYPE html>
Hello World
[[ template-1        ]]';

const pageWithTemplateAppliedMock = '<!DOCTYPE html>
Hello World

This is a template
';
const pageWithNestedTemplateAppliedMock = '<!DOCTYPE html>
Hello World

This is a templateThis is a nested template
';

const templatesMock = {
  'template-1': '
This is a template
',
};

const nestedTemplateMock = {
  'template-1': '
This is a template[[template-2]]
',
  'template-2': 'This is a nested template',
};

const infiniteNestedTemplateMock = {
  'template-1': 'This is a template[[template-2]]',
  'template-2': 'This is a nested template[[template-1]]',
};

const tooManyNestedTemplatesErrorMessage = 'Too many nested templates!!';

describe('applyTemplates function', () => {
  it('Returns the same page if page has no templates in it and no templates are provided to the function.', () => {
    expect(applyTemplates(pageWithoutTemplatesMock)).to.equal(pageWithoutTemplatesMock);
  });
  it('Returns the same page if page has templates in it and no templates are provided to the function.', () => {
    expect(applyTemplates(pageWithOneTemplateMock)).to.equal(pageWithOneTemplateMock);
  });
  it('Returns the same page if page has no templates in it and templates are provided to the function.', () => {
    expect(applyTemplates(pageWithoutTemplatesMock, templatesMock)).to.equal(pageWithoutTemplatesMock);
  });
  it('Returns a new page with the template applied to it.', () => {
    expect(applyTemplates(pageWithOneTemplateMock, templatesMock)).to.equal(pageWithTemplateAppliedMock);
  });
  it('Returns a new page with the template applied to it even if the template is specified with spaces between the brackets.', () => {
    expect(applyTemplates(pageWithOneTemplateWithSpacesMock, templatesMock)).to.equal(pageWithTemplateAppliedMock);
  });
  it('Returns a new page with the nested template applied to it.', () => {
    expect(applyTemplates(pageWithOneTemplateMock, nestedTemplateMock)).to.equal(pageWithNestedTemplateAppliedMock);
  });
  it('Throws an error when trying to apply infinite nested templates to a page.', () => {
    expect(() => applyTemplates(pageWithOneTemplateMock, infiniteNestedTemplateMock))
      .to.throw(tooManyNestedTemplatesError)
      .and.be.an.instanceOf(Error)
      .with.property('message', tooManyNestedTemplatesErrorMessage);
  });
  // it('Checks the function is called max 100 times when trying to apply infinite nested templates to a page.', () => {

  // });
});
<|endoftext|>


<commit_before>var LoggerFactory = require('slf').LoggerFactory;
var uuid = require('node-uuid').v4;
var Logger = require('slf').Logger;
var LOG = Logger.getLogger('lx:viewdb-persistence-store-remote');
var _ = require('lodash');

var Cursor = require('viewdb').Cursor;
var util = require('util');
var EventEmitter = require('events').EventEmitter;

var RemoteCursor = function (collection, query, options, getDocuments) {
  Cursor.call(this, collection, query, options, getDocuments);
	this.handles = [];
}

util.inherits(RemoteCursor, Cursor);

RemoteCursor.prototype._buildParams = function (defaults, method) {
  var q = this._query.query || this._query;
  var skip, limit, sort;
  if (this._query.query) {
    skip = this._query.skip;
    limit = this._query.limit;
    sort = this._query.sort;
  }
  var params = _.defaults({
    id: uuid(),
    observe: q,
    collection: this._collection._name,
    skip: skip,
    limit: limit,
    sort: sort
  }, defaults);

  if (method) {
    params.method = method;
  }
  return params;
}

RemoteCursor.prototype.count = function (applySkipLimit, callback) {
  var cb = _.isFunction(applySkipLimit) ? applySkipLimit : callback;
  var skipLimit = !_.isFunction(applySkipLimit) ? applySkipLimit : false;

  var params = this._buildParams({ applySkipLimit: skipLimit }, 'count');
  this._collection._client.request(params, function (err, result) {
    cb(err, result);
  });
};

RemoteCursor.prototype.sort = function (params) {
  this._query.sort = params;
  this._refresh();
  return this;
}

RemoteCursor.prototype.observe = function (options) {
  var self = this;
  var remoteHandle = null;
  var events = {
    i: options.init ? true : false
    , a: options.added ? true : false
    , r: options.removed ? true : false
    , c: options.changed ? true : false
    , m: options.moved ? true : false
  };

  var params = this._buildParams({
    events: events
  });

  var self = this;
  var handle = this._collection._client.subscribe(params, function (err, result) {
    if (remoteHandle || result.handle) {
      remoteHandle = result.handle;

      if (self.handles.indexOf(params.id) > -1) {
        self._collection._client.request({ "observe.stop": { h: params.id } });
        handle.stop();
        _.remove(self.handles, params.id);
      } else {
        _.forEach(result.changes, function (c) {
          //			console.log(c);

          if(c.i) { // init
            options.init(c.i.r);
          } else if (c.a) { //added
            //			console.log("RCVD A");
            options.added(c.a.e, c.a.i);
          } else if (c.r) { //removed
            //			console.log("RCVD R");
            options.removed(c.r.e, c.r.i);
          } else if (c.c) { //changed
            //			console.log("RCVD C");
            options.changed(c.c.o, c.c.n, c.c.i);
          } else if (c.m) { //moved
            //			console.log("RCVD M");
            options.moved(c.m.e, c.m.o, c.m.n);
          }
        });
      }
    }
  });

  return {
    stop: function () {
      if (!remoteHandle) {
        LOG.warn("WARN unsubscribing before receiving subscription handle from server");
        self.handles.push(params.id);
      } else {
        self._collection._client.request({ "observe.stop": { h: params.id } });
        handle.stop();
      }
    }
  }
};

module.exports = RemoteCursor;<commit_msg>bugfix for bugfix that did not fix bug<commit_after>var LoggerFactory = require('slf').LoggerFactory;
var uuid = require('node-uuid').v4;
var Logger = require('slf').Logger;
var LOG = Logger.getLogger('lx:viewdb-persistence-store-remote');
var _ = require('lodash');

var Cursor = require('viewdb').Cursor;
var util = require('util');
var EventEmitter = require('events').EventEmitter;

var RemoteCursor = function (collection, query, options, getDocuments) {
  Cursor.call(this, collection, query, options, getDocuments);
	this.handles = [];
}

util.inherits(RemoteCursor, Cursor);

RemoteCursor.prototype._buildParams = function (defaults, method) {
  var q = this._query.query || this._query;
  var skip, limit, sort;
  if (this._query.query) {
    skip = this._query.skip;
    limit = this._query.limit;
    sort = this._query.sort;
  }
  var params = _.defaults({
    id: uuid(),
    observe: q,
    collection: this._collection._name,
    skip: skip,
    limit: limit,
    sort: sort
  }, defaults);

  if (method) {
    params.method = method;
  }
  return params;
}

RemoteCursor.prototype.count = function (applySkipLimit, callback) {
  var cb = _.isFunction(applySkipLimit) ? applySkipLimit : callback;
  var skipLimit = !_.isFunction(applySkipLimit) ? applySkipLimit : false;

  var params = this._buildParams({ applySkipLimit: skipLimit }, 'count');
  this._collection._client.request(params, function (err, result) {
    cb(err, result);
  });
};

RemoteCursor.prototype.sort = function (params) {
  this._query.sort = params;
  this._refresh();
  return this;
}

RemoteCursor.prototype.observe = function (options) {
  var self = this;
  var remoteHandle = null;
  var events = {
    i: options.init ? true : false
    , a: options.added ? true : false
    , r: options.removed ? true : false
    , c: options.changed ? true : false
    , m: options.moved ? true : false
  };

  var params = this._buildParams({
    events: events
  });

  var self = this;
  var handle = this._collection._client.subscribe(params, function (err, result) {
    if (remoteHandle || result.handle) {
      remoteHandle = result.handle || remoteHandle;

      if (self.handles.indexOf(params.id) > -1) {
        self._collection._client.request({ "observe.stop": { h: params.id } });
        handle.stop();
        _.remove(self.handles, params.id);
      } else {
        _.forEach(result.changes, function (c) {
          //			console.log(c);

          if(c.i) { // init
            options.init(c.i.r);
          } else if (c.a) { //added
            //			console.log("RCVD A");
            options.added(c.a.e, c.a.i);
          } else if (c.r) { //removed
            //			console.log("RCVD R");
            options.removed(c.r.e, c.r.i);
          } else if (c.c) { //changed
            //			console.log("RCVD C");
            options.changed(c.c.o, c.c.n, c.c.i);
          } else if (c.m) { //moved
            //			console.log("RCVD M");
            options.moved(c.m.e, c.m.o, c.m.n);
          }
        });
      }
    }
  });

  return {
    stop: function () {
      if (!remoteHandle) {
        LOG.warn("WARN unsubscribing before receiving subscription handle from server");
        self.handles.push(params.id);
      } else {
        self._collection._client.request({ "observe.stop": { h: params.id } });
        handle.stop();
      }
    }
  }
};

module.exports = RemoteCursor;<|endoftext|>


<commit_before>/*global $, delay */
/*jshint unused:false */

/**
 * Called when castform is first called on a form field.
 *
 * @param {jQuery} $submit
 * @param {jQuery} $field
 * @param {Object} options
 */
function load($field, options) {
  var $icon;
  // Create an element to display a checkmark or an X on validation.
  if (options.icon !== false) {
    $icon = options.$icon = $('<span>')
      .css('position', 'absolute')
      .insertAfter($field);
  }

  // Create a tooltip to show error messages.
  if (options.tooltip !== false) {
    var tooltip = ($icon || $field).tooltip({
      title: 'hellooooo'
    , placement: 'right'
    , trigger: 'manual'
    , animation: false
    }).data('tooltip');

    options.tooltip = delay(function(msg) {
      if (msg) {
        tooltip.options.title = msg;
        tooltip.show();
      } else {
        tooltip.hide();
      }
    });
  }
}

/**
 * Called before a field's validation functions are called.
 *
 * @param {jQuery} $field
 * @param {Object} options
 * @param {Boolean} pageLoad
 * @param {Boolean} asyncInvolved
 */
function check($field, options, pageLoad, asyncInvolved) {
  // Hide tooltip if a validation function contains async.
  if (asyncInvolved) {
    options.tooltip();
  }

}

/**
 * By default this will be called when a field passes all
 * validation tests successfully
 *
 * @param {jQuery} $field
 * @param {Object} options
 * @param {Boolean} pageLoad
 * @param {Boolean} success
 * @param {Object} validate
 */
function pass($field, options, pageLoad, success, validate) {
  if (pageLoad && !$field.val()) {
    return;
  }

  var $icon = options.$icon;
  var tooltip = options.tooltip;

  if (success) {
    // Display checkmark next to text field.
    if (!options.noIcon) {
      $icon.html('✓');
      $icon.css({ color: 'green', 'font-weight': 'bold' });
    }

    // Hide tooltip
    if (!options.noTooltip) {
      tooltip();
    }

  } else {
    // Display X next to text field.
    if (!options.noTooltip) {
      $icon.text('X');
      $icon.css({ color: 'red', 'font-weight': 'bold' });
    }

    // Display tooltip
    if (!options.noTooltip) {
      tooltip(validate.delay, validate.msg);
    }

  }
}

/**
 * Called when the submit button is pressed.
 *
 * @param {jQuery} $submit
 * @param {Object} options
 */
function submit($submit, options) {
  options.$icon.text('...');
}
<commit_msg>fix not showing icon and tooltip<commit_after>/*global $, delay */
/*jshint unused:false */

/**
 * Called when castform is first called on a form field.
 *
 * @param {jQuery} $submit
 * @param {jQuery} $field
 * @param {Object} options
 */
function load($field, options) {
  var $icon;
  // Create an element to display a checkmark or an X on validation.
  if (options.icon !== false) {
    $icon = options.$icon = $('<span>')
      .css('position', 'absolute')
      .insertAfter($field);
  }

  // Create a tooltip to show error messages.
  if (options.tooltip !== false) {
    var tooltip = ($icon || $field).tooltip({
      title: 'hellooooo'
    , placement: 'right'
    , trigger: 'manual'
    , animation: false
    }).data('tooltip');

    options.tooltip = delay(function(msg) {
      if (msg) {
        tooltip.options.title = msg;
        tooltip.show();
      } else {
        tooltip.hide();
      }
    });
  }
}

/**
 * Called before a field's validation functions are called.
 *
 * @param {jQuery} $field
 * @param {Object} options
 * @param {Boolean} pageLoad
 * @param {Boolean} asyncInvolved
 */
function check($field, options, pageLoad, asyncInvolved) {
  // Hide tooltip if a validation function contains async.
  if (asyncInvolved) {
    options.tooltip();
  }

}

/**
 * By default this will be called when a field passes all
 * validation tests successfully
 *
 * @param {jQuery} $field
 * @param {Object} options
 * @param {Boolean} pageLoad
 * @param {Boolean} success
 * @param {Object} validate
 */
function pass($field, options, pageLoad, success, validate) {
  if (pageLoad && !$field.val()) {
    return;
  }

  var $icon = options.$icon;
  var tooltip = options.tooltip;

  if (success) {
    // Display checkmark next to text field.
    if ($icon) {
      $icon.html('✓');
      $icon.css({ color: 'green', 'font-weight': 'bold' });
    }

    // Hide tooltip
    if (tooltip) {
      tooltip();
    }

  } else {
    // Display X next to text field.
    if ($icon) {
      $icon.text('X');
      $icon.css({ color: 'red', 'font-weight': 'bold' });
    }

    // Display tooltip
    if (tooltip) {
      tooltip(validate.delay, validate.msg);
    }

  }
}

/**
 * Called when the submit button is pressed.
 *
 * @param {jQuery} $submit
 * @param {Object} options
 */
function submit($submit, options) {
  options.$icon.text('...');
}
<|endoftext|>


<commit_before>// observer module
(function (global, body, state) {

    var engine = global.E;

    // module instance cache
    engine.modules = {};

    // the module class
    var Module = {
        emit: emit,
        on: on,
        off: off,
        link: engine.link
    };

    // make engine observable
    engine.emit = emit;
    engine.on = on;
    engine.off = off;
    engine._events = {};

    /**
     * Create a new module instance.
     *
     * @public
     * @param {object} The object, which is extended with the observable methods.
     */
    engine.module = function (name) {

        // check modules cache
        if (engine.modules[name]) {
            return;
        }

        // save new empty module in cache, to prevent overlapping requests
        var module = engine.modules[name] = engine.clone(Module);

        // module instances link cache
        module._links = {};

        // create a link
        var link = this.link('load', function (err, config) {

            // handle error
            if (err) {

                // remove module from cache
                delete engine.modules[name];

                // emit error event
                return engine.emit('moduleLoadError', err);
            }

            // load css
            config.css && engine.css(config.css);

            // load scripts
            config.scripts && engine.scripts(config.module, config.scripts, loadHandler);

            // load sub modules
            if (config.load) {
                for (var i = 0; i < config.load.length; ++i) {
                    engine.module(config.load[i]);
                }
            }

            // create event object
            module._events = {};

            // save module name
            module._name = config.name || name;

            // save module name on module instance
            module._module = config.module;
        });

        // send module instance name
        link.send(null, name);
    };

    /**
     * Handles the initialization order for sub modules.
     *
     * @public
     * @param {object|string} The even name or object, which is emitted.
     * @param {mixed} The following arguments are passed to the event handlers.
     */
    function loadHandler (module) {

    }

    /**
     * Emit an event.
     *
     * @public
     * @param {object|string} The even name or object, which is emitted.
     * @param {mixed} The following arguments are passed to the event handlers.
     */
    function emit (event) {

        var instance = this;
        var _event = event;

        // handle emit
        if (typeof event === 'object') {

            // set event as event name
            _event = event.state || event.event;

            // get new scope and return if scope doesn't exists
            if(event.to && !(instance = engine.modules[event.to])) {
                return;
            }

            // set instance to null, to emit on all instances
            instance = event.all ? null : instance;
        }

        // slice first argument
        var args = arguments.length > 1 ? engine._toArray(arguments).slice(1) : [];

        // fire events on a single instance
        if (instance) {
            return fireEvents(instance, _event, args);
        }

        // fire events on all instances
        for (instance in engine.modules) {
            fireEvents(engine.modules[instance], _event, args, event.state);
        }
    }

    /**
     * Fire all matching events on a module instance.
     *
     * @public
     * @param {object} The module instance, on which the events are emitted.
     * @param {string} The event name.
     * @param {array} The arguments for the event handlers.
     */
    function fireEvents (instance, event, args, state) {

        // state specifc checks
        if (state) {

            // ignore events, if the instance state doesn't change
            if (instance._state === state) {
                return;
            }

            // set current state on instance
            instance._state = event;
        }

        // index for events that must be removed
        var rm = [];

        // instance events
        var events = instance._events;

        // instance event loop
        for (var _event in events) {

            // compare event or test regex
            if (_event === event || events[_event].re.test(event)) {

                // call handlers
                for (var i = 0; i < events[_event].length; ++i) {
                    if (events[_event][i]) {

                        // call registered Methods
                        events[_event][i].apply(self, args);

                        // remove from event buffer, if once is true
                        if (events[_event][i]._1) {
                            events[_event][i] = null;
                            rm.push([_event, i]);
                        }
                    }
                }

                // routes on the same instance are unique, this prevents
                // regexp overlapping on complicated routes
                if (args[0] && args[0]._rt && !events[_event].nr) {
                    break;
                }
            }
        }

        // remove unused events
        remove(events, rm);
    }

    /**
     * Listen on an event.
     *
     * @public
     * @param {string} The even name regular expression pattern.
     * @param {function} The event handler.
     * @param {boolean} Event handler is removed after calling.
     * @param {boolean} If an event is emitted from the route method, the event
     *                  loop stops, when an event is found. This argument tells the
     *                  event loop to continue.
     */
    function on (event, handler, once, noRoute) {

        var events = this._events;

        // get handler from a path
        if (typeof handler !== 'function') {
            handler = engine.path(handler);
        }

        if (typeof handler === fn) {

            if (!events[event]) {
                events[event] = [];

                // create regexp pattern
                events[event].re = new RegExp(event);
                events[event].nr = noRoute;
            }

            handler._1 = once;
            events[event].push(handler);
        }
    }

    /**
     * Remove an event or a single event hanlder from the event loop.
     *
     * @public
     * @param {string} The even name regular expression pattern.
     * @param {function} The event handler.
     */
    function off (event, handler) {

        var events = this._events;

        if (events[event]) {

            if (handler) {
                var rm = [];

                for (var i = 0; i < events[event].length; ++i) {
                    if (events[event][i] === handler) {
                        events[event][i] = null;
                        rm.push([event, i]);
                    }
                }

                remove(events, rm);

            } else {
                delete events[event];
            }
        }
    }

    /**
     * Removes the collected events from an observable.
     *
     * @private
     * @param {object} The events of an observable.
     * @param {array} The infos for removing events.
     */
    function remove (events, rmObject) {

        if (rmObject.length) {
            for (i = 0; i < rmObject.length; ++i) {

                // remove handler
                events[rmObject[i][0]].splice(rmObject[i][0], 1);

                // remove event
                if (events[rmObject[i][0]].length === 0) {
                    delete events[rmObject[i][0]];
                }
            }
        }
    }

// pass environment
})(this, document, location);

/*
    // setup default as server events
    coreInstance.on('I>', send('I>'));
    coreInstance.on('V>', send('V>'));
    coreInstance.on('M>', send('M>'));

    // setup and open a websocket
    coreInstance.socket = setupWebSocket;
    coreInstance.socket();

    // load start instance when websocket is connected
    coreInstance._ws.onopen = function () {
        Z._load();
    };

    // init constructors from top to bottom
    function initConstructors (err, constructors) {

        var length = constructors.length;
        var count = 0;
        var emitReady = [];
        var initConstructorsHandler = function (init) {

            if (!init) {

                // handle ready state
                for (var i = 0; i < emitReady.length; ++i) {

                    // mark element as ready
                    emitReady[i]._ready = true;
                    emitReady[i].emit('ready');
                }

                // emit empty route
                Z.route();

                return;
            }

            // set up ovserve configs from views and modules
            if (!init[0]) {
                flow.call(init[1], init[2], true);
                return initConstructorsHandler(constructors[++count]);
            }

            // call constructor
            init[0].call(init[1], init[2] || {}, function instanceConstructorCallback (err) {

                // get instances to emit ready event after all resources are loaded
                emitReady.push(init[1]);

                // continue initialization
                initConstructorsHandler(constructors[++count]);
            });
        };

        initConstructorsHandler(constructors[count]);
    }

    // load resources in parallel
    // TODO handle loading errors
    function loader (factory, clone, config, callback, sub, viewIndex) {
        var self = this;
        var elements = 1;
        var count = 0;
        var inits = [];
        var loaderHandler = function (err, constructor, _inits) {

            // catch constructor
            if (constructor) {
                inits.unshift([constructor, clone, config.config]);
            }

            inits = inits.concat(_inits || []);

            // init or callback when all elements are ready
            if (elements === ++count) {

                // add observe events config to initialization
                if (config.flow) {
                    inits.push([null, self, config.flow]);
                }

                // pass constructors to parent
                if (sub) {
                    callback(err, null, inits);

                // init constructors
                } else if (inits.length) {
                    initConstructors(err, inits);

                // finish without constructors
                } else {
                    callback(err, clone);
                }
            }
        };

        // factory clone
        factory && factory.call(self, clone, config, viewIndex - 1);

        // skip resources
        if (!config.load && !config.scripts) {
            return loaderHandler();
        }

        // load elements
        if (config.load) {

            // update the view index
            self._vi = self._vi || 0;

            // add the number of sub elements to count
            elements += config.load.length;

            // load sub elements
            for (var i = 0, type; i < config.load.length; ++i) {
                type = config.load[i][0];

                // increment view render order index
                if (type == 'V') {
                    ++self._vi;
                }

                // call loader
                self._load(type, config.load[i][1], loaderHandler, config.module ? true : false, self._vi);
            }
        }

        // load scripts
        if (config.scripts) {
            loadJS(config.module, config.main || 0, config.scripts, loaderHandler);
        }
    }

    // set up event flow
    function flow (config, onlyObs, onlyDom, domScope, data) {
        var self = this;
        var i, e, s;
        var elms;
        var flow;
        var scope = [domScope];

        // set children as scope if there is more then one data item
        if (domScope && data.length > 1 && domScope.children) {
            scope = domScope.children;
        }

        for (i = 0; i < config.length; ++i) {
            flow = config[i];

            // handle dom event
            if (flow.selector && !onlyObs) {

                // overwrite scope with the document
                if (flow.scope == 'global') {
                    scope = [doc];
                }

                // overwrite scope with parent
                if (flow.scope == 'parent') {
                    scope = [domScope];
                }

                for (s = 0; s < scope.length; ++s) {
                    elms = flow.selector === '.' ? [scope[s]] : scope[s].querySelectorAll(flow.selector);
                    if (elms) {
                        for (e = 0; e < elms.length; ++e) {

                            elms[e].addEventListener(
                                flow['in'],
                                createHandler.call(
                                    self,
                                    flow.out,
                                    scope[s],
                                    data[s],
                                    elms,
                                    flow.dontPrevent
                                )
                            );
                        }
                    }
                }

            // handle osberver event
            } else if (!onlyDom) {

                self.on(
                    flow['in'],
                    createHandler.call(self, flow.out),
                    flow['1'],
                    flow.noRoute
                );
            }
        }
    }

    // createHandler
    function createHandler (outConfig, domScope, dataItem, elms, dontPrevent) {
        var self = this;
        var i;

        return function handler (event, _data) {
            var config;
            var key;
            var to;
            var _path;
            var _domElm;
            var i;
            var loadElms = [];
            var path;
            var data;

            // create an event object
            event = event || {};
            event.ori = event.ori || self._name;

            // extend dom event object
            if (domScope) {

                // add dom scope to event
                event._scope = event._scope || domScope;

                // dont prevent default browser actions
                if (!dontPrevent) {
                    event.preventDefault();
                }

                // add found elements to event
                event._elms = elms;

                // add index of found elements
                event._item = event._item || dataItem;
            }

            // add pathname to data object
            event._path = win_location.pathname.substr(1).split('/');

            // parse and append url search to data
            if (win_location.search && !event._search) {
                event._search = searchToJSON();
            }

            // append url hash to data
            if (win_location.hash && !event._hash) {
                event._hash = win_location.hash.substr(1);
            }

            for (i = 0; i < outConfig.length; ++i) {

                config = outConfig[i];
                to = null;

                // check if target instance exists and set new scope
                if (config.to && !(to = cache.I[config.to])) {
                    continue;
                }

                // update scope
                var eSelf = to || self;

                // copy the static data or create a new data object
                data = config.data ? JSON.parse(JSON.stringify(config.data)) : {};

                // merge argument data to data object
                if (_data) {
                    for (key in _data) {
                        data[key] = _data[key];
                    }
                }

                // add dynamic data to the data object
                if (config.set) {

                    // add data to the data object
                    for (key in config.set) {

                        // parse path
                        path = parsePath.call(self, config.set[key], event);

                        // get an attribute value from a dom element or the element itself
                        if (path[0] === '$') {
                            _domElm = path.substr(1).split(':');

                            // TODO global scope should also be an option
                            _domElm[0] = doc.querySelector(_domElm[0]);

                            // get an attribute
                            if (_domElm[1]) {
                                _domElm[1] = _domElm[0][_domElm[1]];
                            }

                            // add dom attribute value or the element itself
                            data[key] = _domElm[1] === undefined ? _domElm[0] : _domElm[1];

                        // get search value with a path: 1. events, 2. data, 3. instance, 4. window
                        } else {
                            data[key] = self._path(path, event, true) || self._path(path, data, true) || self._path(path);
                        }
                    }

                    // create deep object out of flat keys
                    data = self._deep(data);
                }

                // collect elements to load
                if (config.load) {
                    loadElms.push(config.load);
                }

                // adapt to method
                if (config.route) {
                    eSelf.route(parsePath.call(self, config.route, data), data);
                }

                // emit an event
                if (config.emit) {
                    eSelf.emit.call(eSelf, config.emit, event, data);
                }

                // call a method
                if (config.call) {

                    // find call method when the event handler is called
                    if (typeof config.call === 'string' && typeof (config.call = eSelf._path(config.call)) !== fn) {
                        return console.error(self._name + ':', 'Cannot call', eSelf._name + ':' + config.call);
                    }

                    // call method
                    config.call.call(eSelf, event, data);
                }
            }

            // load elements in parallel
            loadElms[0] && loader.call(self, null, self, {load: loadElms}, function () {});
        };
    }
*/<commit_msg>moved event emitter to core engine module<commit_after>
    var engine = E;

    // link cache for the engine global
    engine._links = {};

    // create the websocket
    var websocket = engine.socket = new WebSocket('ws://' + window.location.host + '/');

    /**
     * Load the entrypoint module instance on socket open.
     *
     * @private
     */
    websocket.onopen = function () {
        engine.module();
    };

    /**
     * Message handler.
     *
     * @private
     * @param {string} The message string.
     */
    websocket.onmessage = function (message) {
        engine.link.message(message.data, websocket);
    };

    // module instance cache
    engine.modules = {};

    /**
     * Create a new module instance.
     *
     * @public
     * @param {object} The object, which is extended with the observable methods.
     */
    engine.module = function (name) {

        // check modules cache
        if (engine.modules[name]) {
            return;
        }

        // save new empty module in cache, to prevent overlapping requests
        var module = engine.modules[name] = engine.clone(Module);

        // module instances link cache
        module._links = {};

        // create a link
        var link = this.link('load', function (err, config) {

            // handle error
            if (err) {

                // remove module from cache
                delete engine.modules[name];

                // emit error event
                return engine.emit('moduleLoadError', err);
            }

            // load css
            config.css && engine.css(config.css);

            // load scripts
            config.scripts && engine.scripts(config.module, config.scripts, loadHandler);

            // load sub modules
            if (config.load) {
                for (var i = 0; i < config.load.length; ++i) {
                    engine.module(config.load[i]);
                }
            }

            // create event object
            module._events = {};

            // save module name
            module._name = config.name || name;

            // save module name on module instance
            module._module = config.module;
        });

        // send module instance name
        link.send(null, name);
    };

    /**
     * Handles the initialization order for sub modules.
     *
     * @public
     * @param {object|string} The even name or object, which is emitted.
     * @param {mixed} The following arguments are passed to the event handlers.
     */
    function loadHandler (module) {

    }

    /**
     * Load css files.
     *
     * @public
     * @param {array} The array containing css file urls.
     */
    engine.css = function (urls) {

        for (var i in urls) {
            if (!engine.csss[urls[i]]) {
                engine.csss[urls[i]] = 1;

                var link = body.createElement('link');
                link.setAttribute('rel', 'stylesheet');
                link.setAttribute('href', urls[i]);
                body.head.appendChild(link);
            }
        }
    };

    /**
     * Replace data fields in a string.
     *
     * @private
     * @param {string} The string.
     * @param {object} The data context.
     */
    function parsePath (path, event) {
        var self = this;
        var match = path.match(find_tmpl);

        // replace route with data
        if (match) {
            for (var i = 0, value; i < match.length; ++i) {

                // get value from object
                value = self._path(match[i].replace(find_braces, ''), event);

                // replace value in route
                if (typeof value !== 'undefined') {
                    path = path.replace(match[i], value);
                }
            }
        }

        return path;
    }

    /**
     * Parse a state search string to JSON.
     * Credentials: http://snipplr.com/view/70905/search-string-to-json/
     *
     * @private
     */
    function searchToJSON(){
        var rep = {'?':'{"','=':'":"','&':'","'};
        var s = state.search.replace(/[\?\=\&]/g, function(r) {
            return rep[r];
        });
        return JSON.parse(s.length? s+'"}' : "{}");
    }

/*
    // setup default as server events
    coreInstance.on('I>', send('I>'));
    coreInstance.on('V>', send('V>'));
    coreInstance.on('M>', send('M>'));

    // setup and open a websocket
    coreInstance.socket = setupWebSocket;
    coreInstance.socket();

    // load start instance when websocket is connected
    coreInstance._ws.onopen = function () {
        Z._load();
    };

    // init constructors from top to bottom
    function initConstructors (err, constructors) {

        var length = constructors.length;
        var count = 0;
        var emitReady = [];
        var initConstructorsHandler = function (init) {

            if (!init) {

                // handle ready state
                for (var i = 0; i < emitReady.length; ++i) {

                    // mark element as ready
                    emitReady[i]._ready = true;
                    emitReady[i].emit('ready');
                }

                // emit empty route
                Z.route();

                return;
            }

            // set up ovserve configs from views and modules
            if (!init[0]) {
                flow.call(init[1], init[2], true);
                return initConstructorsHandler(constructors[++count]);
            }

            // call constructor
            init[0].call(init[1], init[2] || {}, function instanceConstructorCallback (err) {

                // get instances to emit ready event after all resources are loaded
                emitReady.push(init[1]);

                // continue initialization
                initConstructorsHandler(constructors[++count]);
            });
        };

        initConstructorsHandler(constructors[count]);
    }

    // load resources in parallel
    // TODO handle loading errors
    function loader (factory, clone, config, callback, sub, viewIndex) {
        var self = this;
        var elements = 1;
        var count = 0;
        var inits = [];
        var loaderHandler = function (err, constructor, _inits) {

            // catch constructor
            if (constructor) {
                inits.unshift([constructor, clone, config.config]);
            }

            inits = inits.concat(_inits || []);

            // init or callback when all elements are ready
            if (elements === ++count) {

                // add observe events config to initialization
                if (config.flow) {
                    inits.push([null, self, config.flow]);
                }

                // pass constructors to parent
                if (sub) {
                    callback(err, null, inits);

                // init constructors
                } else if (inits.length) {
                    initConstructors(err, inits);

                // finish without constructors
                } else {
                    callback(err, clone);
                }
            }
        };

        // factory clone
        factory && factory.call(self, clone, config, viewIndex - 1);

        // skip resources
        if (!config.load && !config.scripts) {
            return loaderHandler();
        }

        // load elements
        if (config.load) {

            // update the view index
            self._vi = self._vi || 0;

            // add the number of sub elements to count
            elements += config.load.length;

            // load sub elements
            for (var i = 0, type; i < config.load.length; ++i) {
                type = config.load[i][0];

                // increment view render order index
                if (type == 'V') {
                    ++self._vi;
                }

                // call loader
                self._load(type, config.load[i][1], loaderHandler, config.module ? true : false, self._vi);
            }
        }

        // load scripts
        if (config.scripts) {
            loadJS(config.module, config.main || 0, config.scripts, loaderHandler);
        }
    }

    // set up event flow
    function flow (config, onlyObs, onlyDom, domScope, data) {
        var self = this;
        var i, e, s;
        var elms;
        var flow;
        var scope = [domScope];

        // set children as scope if there is more then one data item
        if (domScope && data.length > 1 && domScope.children) {
            scope = domScope.children;
        }

        for (i = 0; i < config.length; ++i) {
            flow = config[i];

            // handle dom event
            if (flow.selector && !onlyObs) {

                // overwrite scope with the document
                if (flow.scope == 'global') {
                    scope = [doc];
                }

                // overwrite scope with parent
                if (flow.scope == 'parent') {
                    scope = [domScope];
                }

                for (s = 0; s < scope.length; ++s) {
                    elms = flow.selector === '.' ? [scope[s]] : scope[s].querySelectorAll(flow.selector);
                    if (elms) {
                        for (e = 0; e < elms.length; ++e) {

                            elms[e].addEventListener(
                                flow['in'],
                                createHandler.call(
                                    self,
                                    flow.out,
                                    scope[s],
                                    data[s],
                                    elms,
                                    flow.dontPrevent
                                )
                            );
                        }
                    }
                }

            // handle osberver event
            } else if (!onlyDom) {

                self.on(
                    flow['in'],
                    createHandler.call(self, flow.out),
                    flow['1'],
                    flow.noRoute
                );
            }
        }
    }

    // createHandler
    function createHandler (outConfig, domScope, dataItem, elms, dontPrevent) {
        var self = this;
        var i;

        return function handler (event, _data) {
            var config;
            var key;
            var to;
            var _path;
            var _domElm;
            var i;
            var loadElms = [];
            var path;
            var data;

            // create an event object
            event = event || {};
            event.ori = event.ori || self._name;

            // extend dom event object
            if (domScope) {

                // add dom scope to event
                event._scope = event._scope || domScope;

                // dont prevent default browser actions
                if (!dontPrevent) {
                    event.preventDefault();
                }

                // add found elements to event
                event._elms = elms;

                // add index of found elements
                event._item = event._item || dataItem;
            }

            // add pathname to data object
            event._path = win_location.pathname.substr(1).split('/');

            // parse and append url search to data
            if (win_location.search && !event._search) {
                event._search = searchToJSON();
            }

            // append url hash to data
            if (win_location.hash && !event._hash) {
                event._hash = win_location.hash.substr(1);
            }

            for (i = 0; i < outConfig.length; ++i) {

                config = outConfig[i];
                to = null;

                // check if target instance exists and set new scope
                if (config.to && !(to = cache.I[config.to])) {
                    continue;
                }

                // update scope
                var eSelf = to || self;

                // copy the static data or create a new data object
                data = config.data ? JSON.parse(JSON.stringify(config.data)) : {};

                // merge argument data to data object
                if (_data) {
                    for (key in _data) {
                        data[key] = _data[key];
                    }
                }

                // add dynamic data to the data object
                if (config.set) {

                    // add data to the data object
                    for (key in config.set) {

                        // parse path
                        path = parsePath.call(self, config.set[key], event);

                        // get an attribute value from a dom element or the element itself
                        if (path[0] === '$') {
                            _domElm = path.substr(1).split(':');

                            // TODO global scope should also be an option
                            _domElm[0] = doc.querySelector(_domElm[0]);

                            // get an attribute
                            if (_domElm[1]) {
                                _domElm[1] = _domElm[0][_domElm[1]];
                            }

                            // add dom attribute value or the element itself
                            data[key] = _domElm[1] === undefined ? _domElm[0] : _domElm[1];

                        // get search value with a path: 1. events, 2. data, 3. instance, 4. window
                        } else {
                            data[key] = self._path(path, event, true) || self._path(path, data, true) || self._path(path);
                        }
                    }

                    // create deep object out of flat keys
                    data = self._deep(data);
                }

                // collect elements to load
                if (config.load) {
                    loadElms.push(config.load);
                }

                // adapt to method
                if (config.route) {
                    eSelf.route(parsePath.call(self, config.route, data), data);
                }

                // emit an event
                if (config.emit) {
                    eSelf.emit.call(eSelf, config.emit, event, data);
                }

                // call a method
                if (config.call) {

                    // find call method when the event handler is called
                    if (typeof config.call === 'string' && typeof (config.call = eSelf._path(config.call)) !== fn) {
                        return console.error(self._name + ':', 'Cannot call', eSelf._name + ':' + config.call);
                    }

                    // call method
                    config.call.call(eSelf, event, data);
                }
            }

            // load elements in parallel
            loadElms[0] && loader.call(self, null, self, {load: loadElms}, function () {});
        };
    }
*/<|endoftext|>


<commit_before>/*
	AutoUpdateController.js
	Copyright (c) 2014-2020 dangered wolf, et al
	Released under the MIT licence
*/

import { I18n } from "./I18n.js";
import { formatBytes } from "./Utils.js";

export class AutoUpdateController {
	h3;
	h2;
	tryAgain;
	restartNow;
	spinner;
	icon;

	isCheckingForUpdates;

	static initialize() {

		if (typeof require === "undefined") {
			return;
		}

		const { ipcRenderer } = require("electron");

		ipcRenderer.on("error",(e, args, f, g) => {
			AutoUpdateController.h2 = I18n("There was a problem checking for updates.");
			AutoUpdateController.spinner = false;

			if (args?.code) {
				AutoUpdateController.h3 = `${args.domain || ""} ${args.code || ""} ${args.errno || ""} ${args.syscall || ""} ${args.path || ""}`;
			} else if (f) {
				AutoUpdateController.h3 = f.match(/^(Cannot check for updates: )(.)+\n/g)
			} else {
				AutoUpdateController.h3 = I18n("An unknown error occurred. Please try again shortly.");
			}

			AutoUpdateController.icon = "error_outline";
			AutoUpdateController.tryAgain = I18n("Try Again");
			AutoUpdateController.restartNow = false;

			AutoUpdateController.isCheckingForUpdates = false;
			$(document).trigger("mtdUpdateUIChanged");

		});

		ipcRenderer.on("checking-for-update", (e,args) => {
			AutoUpdateController.icon = undefined;
			AutoUpdateController.spinner = true;
			AutoUpdateController.h2 = I18n("Checking for updates...");
			AutoUpdateController.h3 = undefined;
			AutoUpdateController.updateh3 = undefined;
			AutoUpdateController.tryAgain = undefined;
			AutoUpdateController.restartNow = false;
			$("[id='update'] .mtd-welcome-next-button").html(I18n("Skip") + "");

			AutoUpdateController.isCheckingForUpdates = true;
			$(document).trigger("mtdUpdateUIChanged");
		});

		ipcRenderer.on("update-available", (e,args) => {
			AutoUpdateController.icon = undefined;
			AutoUpdateController.spinner = true;
			AutoUpdateController.h2 = I18n("Updating...");
			AutoUpdateController.h3 = undefined;
			AutoUpdateController.tryAgain = undefined;
			AutoUpdateController.restartNow = false;

			AutoUpdateController.isCheckingForUpdates = true;
			$(document).trigger("mtdUpdateUIChanged");
		});

		ipcRenderer.on("download-progress", (e,args) => {
			AutoUpdateController.icon = undefined;
			AutoUpdateController.spinner = true;
			AutoUpdateController.h2 = I18n("Downloading update...");
			AutoUpdateController.h3 = Math.floor(args.percent) + I18n("% complete (") +
									  formatBytes(args.transferred) + I18n("/") + formatBytes(args.total) + I18n("; ") +
									  formatBytes(args.bytesPerSecond) + ("/s)");

			AutoUpdateController.tryAgain = undefined;
			AutoUpdateController.restartNow = false;

			AutoUpdateController.isCheckingForUpdates = true;
			$(document).trigger("mtdUpdateUIChanged");
		});

		ipcRenderer.on("update-downloaded", (e,args) => {
			AutoUpdateController.spinner = false;
			AutoUpdateController.icon = "update";
			AutoUpdateController.h2 = I18n("Update downloaded");
			AutoUpdateController.h3 = I18n("Restart ModernDeck to complete the update");

			AutoUpdateController.tryAgain = undefined;
			AutoUpdateController.restartNow = true;

			AutoUpdateController.isCheckingForUpdates = false;
			$(document).trigger("mtdUpdateUIChanged");
		});

		ipcRenderer.on("update-not-available", (e,args) => {
			AutoUpdateController.spinner = false;
			AutoUpdateController.h2 = I18n("You're up to date");
			AutoUpdateController.icon = "check_circle";
			AutoUpdateController.h3 = SystemVersion + I18n(" is the latest version.");

			AutoUpdateController.tryAgain = I18n("Check Again");
			AutoUpdateController.restartNow = false;
			$("[id='update'] .mtd-welcome-next-button").html(I18n("Next") + "");

			AutoUpdateController.isCheckingForUpdates = false;
			$(document).trigger("mtdUpdateUIChanged");
		});
	}

}
<commit_msg>Added new update options for enterprise<commit_after>/*
	AutoUpdateController.js
	Copyright (c) 2014-2020 dangered wolf, et al
	Released under the MIT licence
*/

import { I18n } from "./I18n.js";
import { formatBytes } from "./Utils.js";

export class AutoUpdateController {
	h3;
	h2;
	tryAgain;
	restartNow;
	installButton;
	spinner;
	icon;

	isCheckingForUpdates;

	static initialize() {

		if (typeof require === "undefined") {
			return;
		}

		const { ipcRenderer } = require("electron");

		AutoUpdateController.h2 = I18n("Check for updates");
		AutoUpdateController.spinner = false;
		AutoUpdateController.h3 = I18n("ModernDeck updates help keep you secure and add new features.");
		AutoUpdateController.icon = "info_outline";
		AutoUpdateController.tryAgain = I18n("Check now");
		AutoUpdateController.restartNow = false;
		AutoUpdateController.installButton = undefined;
		AutoUpdateController.isCheckingForUpdates = false;

		ipcRenderer.on("error",(e, args, f, g) => {
			AutoUpdateController.h2 = I18n("There was a problem checking for updates.");
			AutoUpdateController.spinner = false;

			if (args?.code) {
				AutoUpdateController.h3 = `${args.domain || ""} ${args.code || ""} ${args.errno || ""} ${args.syscall || ""} ${args.path || ""}`;
			} else if (f) {
				AutoUpdateController.h3 = f.match(/^(Cannot check for updates: )(.)+\n/g)
			} else {
				AutoUpdateController.h3 = I18n("An unknown error occurred. Please try again shortly.");
			}

			AutoUpdateController.icon = "error_outline";
			AutoUpdateController.tryAgain = I18n("Try Again");
			AutoUpdateController.restartNow = false;
			AutoUpdateController.installButton = undefined;
			AutoUpdateController.isCheckingForUpdates = false;
			$(document).trigger("mtdUpdateUIChanged");

		});

		ipcRenderer.on("checking-for-update", (e,args) => {
			AutoUpdateController.icon = undefined;
			AutoUpdateController.spinner = true;
			AutoUpdateController.h2 = I18n("Checking for updates...");
			AutoUpdateController.h3 = undefined;
			AutoUpdateController.updateh3 = undefined;
			AutoUpdateController.tryAgain = undefined;
			AutoUpdateController.installButton = undefined;
			AutoUpdateController.restartNow = false;
			$("[id='update'] .mtd-welcome-next-button").html(I18n("Skip") + "");

			AutoUpdateController.isCheckingForUpdates = true;
			$(document).trigger("mtdUpdateUIChanged");
		});

		ipcRenderer.on("update-available", (e,args) => {
			if (typeof window.enterpriseConfig !== "undefined" && (window.enterpriseConfig.autoUpdatePolicy === "checkOnly" || window.enterpriseConfig.autoUpdatePolicy === "manual")) {
				AutoUpdateController.h2 = I18n("An update for ModernDeck is available");
				AutoUpdateController.h3 = I18n("ModernDeck updates help keep you secure and add new features.");
				AutoUpdateController.spinner = false;
				AutoUpdateController.icon = "error_outline";
				AutoUpdateController.installButton = I18n("Download");
			} else {
				AutoUpdateController.h2 = I18n("Updating...");
				AutoUpdateController.h3 = undefined;
				AutoUpdateController.spinner = true;
				AutoUpdateController.icon = undefined;
				AutoUpdateController.installButton = undefined;
			}
			AutoUpdateController.tryAgain = undefined;
			AutoUpdateController.restartNow = false;

			AutoUpdateController.isCheckingForUpdates = true;
			$(document).trigger("mtdUpdateUIChanged");
		});

		ipcRenderer.on("download-progress", (e,args) => {
			AutoUpdateController.icon = undefined;
			AutoUpdateController.spinner = true;
			AutoUpdateController.h2 = I18n("Downloading update...");
			AutoUpdateController.h3 = Math.floor(args.percent) + I18n("% complete (") +
									  formatBytes(args.transferred) + I18n("/") + formatBytes(args.total) + I18n("; ") +
									  formatBytes(args.bytesPerSecond) + ("/s)");

			AutoUpdateController.tryAgain = undefined;
			AutoUpdateController.installButton = undefined;
			AutoUpdateController.restartNow = false;

			AutoUpdateController.isCheckingForUpdates = true;
			$(document).trigger("mtdUpdateUIChanged");
		});

		ipcRenderer.on("update-downloaded", (e,args) => {
			AutoUpdateController.spinner = false;
			AutoUpdateController.icon = "update";
			AutoUpdateController.h2 = I18n("Update downloaded");
			AutoUpdateController.h3 = I18n("Restart ModernDeck to complete the update");

			AutoUpdateController.tryAgain = undefined;
			AutoUpdateController.installButton = undefined;
			AutoUpdateController.restartNow = true;

			AutoUpdateController.isCheckingForUpdates = false;
			$(document).trigger("mtdUpdateUIChanged");
		});

		ipcRenderer.on("update-not-available", (e,args) => {
			AutoUpdateController.spinner = false;
			AutoUpdateController.h2 = I18n("You're up to date");
			AutoUpdateController.icon = "check_circle";
			AutoUpdateController.h3 = SystemVersion + I18n(" is the latest version.");

			AutoUpdateController.tryAgain = I18n("Check Again");
			AutoUpdateController.installButton = undefined;
			AutoUpdateController.restartNow = false;
			$("[id='update'] .mtd-welcome-next-button").html(I18n("Next") + "");

			AutoUpdateController.isCheckingForUpdates = false;
			$(document).trigger("mtdUpdateUIChanged");
		});
	}

}
<|endoftext|>


<commit_before>/*=============================
dromos javascript library core.

This class is loaded by the dromos Bootstrap and should not
be included directly in a page

=============================*/
define(["jquery", "dromos.utilities"], function($jQ, utilities)
{
	// Variables for handling plugins
	var __DROMOS_PLUGIN__ = "dromos-module";
	var __DROMOS_INIT__ = "dromos-init";
	var __DROMOS_CONFIG__ = "dromos-config";

	// Make sure dromos exists, it should exist as normally this would be loaded by the bootstrap
	dromos = dromos || {};

	// As dromos already exists and has functions defined, we create this
	// piece by piece rather than as a single object

	/**
	* Creates and returns a namespace from tcNamespace
	* if tcDelimiter is defined it will be used to separate the namespaces,
	* otherwise the default delimiter is '.'
	*/
	dromos.namespace = function(tcNamespace, tcDelimiter)
	{
		var laParts = tcNamespace.split(tcDelimiter || '.');
		dromos.base[laParts[0]] = dromos.base[laParts[0]] || {};
        var loCurrent = dromos.base[laParts[0]];
        for (var i=1, lnLength=laParts.length; i<lnLength; i++)
        {
            loCurrent = loCurrent[laParts[i]] || {};
        }
        return loCurrent;
	};

	dromos.addDOMNotifier = function(tnIndex, toElement)
	{
		var loFNBefore = toElement.insertBefore;
		toElement.insertBefore = function()
		{
			var loReturn = loFNBefore.apply(this, arguments);
			if (loReturn != null && $jQ(loReturn).parents(document).length >0)
			{
				dromos.addDOMNotifier(0, loReturn);
				$jQ(this).trigger('domchildadded');
			}
			return loReturn;
		}

		var loFNAppend = toElement.appendChild;
		toElement.appendChild = function()
		{
			var loReturn = loFNAppend.apply(this, arguments);
			if (loReturn != null && $jQ(loReturn).parents(document).length >0)
			{
				dromos.addDOMNotifier(0, loReturn);
				$jQ(this).trigger('domchildadded');
			}
			return loReturn;
		}
	}

	// Update all elements to notify of dom changes
	$jQ('*').each(dromos.addDOMNotifier);
	$jQ('*').on('domchildadded', function()
			{
				$jQ(this).find("[" + __DROMOS_PLUGIN__ + "]").each(function(tnIndex, toElement)
				{
					var loElement = $jQ(toElement);
					var lcModule = loElement.attr(__DROMOS_PLUGIN__);
					if (lcModule)
					{
						var lcInit = loElement.attr(__DROMOS_INIT__);
						var lcConfig = loElement.attr(__DROMOS_CONFIG__);
						loElement.removeAttr(__DROMOS_PLUGIN__).removeAttr(__DROMOS_INIT__).removeAttr(__DROMOS_CONFIG__);
						require(lcModule, function(toModule)
							{
								dromos.utilities.initialiseModule(toModule, toElement, tnIndex, lcInit, dromos.base[lcConfig]);
							});
					}
				});
		});

	// return the dromos object for future require calls
	return dromos;
});
<commit_msg>Fix for script load finishing before body starts<commit_after>/*=============================
dromos javascript library core.

This class is loaded by the dromos Bootstrap and should not
be included directly in a page

=============================*/
define(["jquery", "dromos.utilities"], function($jQ, utilities)
{
	// Variables for handling plugins
	var __DROMOS_PLUGIN__ = "dromos-module";
	var __DROMOS_INIT__ = "dromos-init";
	var __DROMOS_CONFIG__ = "dromos-config";

	// Make sure dromos exists, it should exist as normally this would be loaded by the bootstrap
	dromos = dromos || {};

	// As dromos already exists and has functions defined, we create this
	// piece by piece rather than as a single object

	/**
	* Creates and returns a namespace from tcNamespace
	* if tcDelimiter is defined it will be used to separate the namespaces,
	* otherwise the default delimiter is '.'
	*/
	dromos.namespace = function(tcNamespace, tcDelimiter)
	{
		var laParts = tcNamespace.split(tcDelimiter || '.');
		dromos.base[laParts[0]] = dromos.base[laParts[0]] || {};
        var loCurrent = dromos.base[laParts[0]];
        for (var i=1, lnLength=laParts.length; i<lnLength; i++)
        {
            loCurrent = loCurrent[laParts[i]] || {};
        }
        return loCurrent;
	};

	dromos.addDOMNotifier = function(tnIndex, toElement)
	{
		var loFNBefore = toElement.insertBefore;
		toElement.insertBefore = function()
		{
			var loReturn = loFNBefore.apply(this, arguments);
			if (loReturn != null && $jQ(loReturn).parents(document).length >0)
			{
				dromos.addDOMNotifier(0, loReturn);
				$jQ(this).trigger('domchildadded');
			}
			return loReturn;
		}

		var loFNAppend = toElement.appendChild;
		toElement.appendChild = function()
		{
			var loReturn = loFNAppend.apply(this, arguments);
			if (loReturn != null && $jQ(loReturn).parents(document).length >0)
			{
				dromos.addDOMNotifier(0, loReturn);
				$jQ(this).trigger('domchildadded');
			}
			return loReturn;
		}
	}

	// Update all elements to notify of dom changes
	$jQ('*').each(dromos.addDOMNotifier);
	$jQ('*').on('domchildadded', function()
			{
				$jQ(function()
					{
						$jQ(this).find("[" + __DROMOS_PLUGIN__ + "]").each(function(tnIndex, toElement)
						{
							var loElement = $jQ(toElement);
							var lcModule = loElement.attr(__DROMOS_PLUGIN__);
							if (lcModule)
							{
								var lcInit = loElement.attr(__DROMOS_INIT__);
								var lcConfig = loElement.attr(__DROMOS_CONFIG__);
								loElement.removeAttr(__DROMOS_PLUGIN__).removeAttr(__DROMOS_INIT__).removeAttr(__DROMOS_CONFIG__);
								require(lcModule, function(toModule)
									{
										dromos.utilities.initialiseModule(toModule, toElement, tnIndex, lcInit, dromos.base[lcConfig]);
									});
							}
						});
					}
				);
		});

	// return the dromos object for future require calls
	return dromos;
});
<|endoftext|>


<commit_before>/* module make possible connectoin thrue socket.io on a client */
var CloudCmd, Util, DOM, io;
(function(CloudCmd, Util, DOM){
    'use strict';

    var Messages        = [],
        socket,
        Terminal,

        ERROR_MSG       = 'could not connect to socket.io\n'+
                          'npm i socket.io';

    DOM.jsload('/socket.io/lib/socket.io.js', {
        onerror : Util.retExec(Util.log, ERROR_MSG),
        onload  : connect
    });

    function connect() {
        socket = io.connect(CloudCmd.HOST);

        CloudCmd.Socket = socket;

        socket.on('connect', function () {
            outToTerminal({stdout: 'socket connected'});
        });

        socket.on('message', function (msg) {
            var lMsg = Util.parseJSON(msg);

            outToTerminal(lMsg);

        });

        socket.on('disconnect', function () {
            outToTerminal({stderr: 'socket disconected'});
        });
    }

    function outToTerminal(pMsg){
        var i, n, lResult, lStdout, lStderr,
            lConsole = CloudCmd.Console;
        DOM.Images.hideLoad();

        if( Util.isObject(lConsole) ){
            if(Messages.length){
                /* show oll msg from buffer */
                for(i = 0, n = Messages.length; i < n; i++){
                    lStdout = Messages[i].stdout;
                    lStderr = Messages[i].stderr;

                    if(lStdout)
                        lConsole.log(lStdout);

                    if(lStderr){
                        /* if it's object - convert is to string' */
                        if( Util.isObject(lStderr) )
                            lStderr =  Util.stringifyJSON(lStderr);

                        lConsole.error(lStderr);
                    }
                }
                Messages = [];
            }

            lStdout = pMsg.stdout;
            lStderr = pMsg.stderr;

            if(lStdout)
                lResult = lConsole.log(lStdout);

            if(lStderr && lStderr.code !== 1)
                lResult = lConsole.error(lStderr.toString());
        }
        else
            /* if term not accesable save msg to buffer */
            Messages.push(pMsg);

        Util.log(pMsg);

        return lResult;
    }

})(CloudCmd, Util, DOM);<commit_msg>fix(socket) reconnect<commit_after>/* module make possible connectoin thrue socket.io on a client */
var CloudCmd, Util, DOM, io;
(function(CloudCmd, Util, DOM){
    'use strict';

    var Messages        = [],
        socket,
        Terminal,

        ERROR_MSG       = 'could not connect to socket.io\n'+
                          'npm i socket.io';

    DOM.jsload('/socket.io/lib/socket.io.js', {
        onerror : Util.retExec(Util.log, ERROR_MSG),
        onload  : connect
    });

    function connect() {
        socket = io.connect(CloudCmd.HOST, {
            reconnect: true
        });

        CloudCmd.Socket = socket;

        socket.on('connect', function () {
            outToTerminal({stdout: 'socket connected'});
        });

        socket.on('message', function (msg) {
            var lMsg = Util.parseJSON(msg);

            outToTerminal(lMsg);

        });

        socket.on('disconnect', function () {
            outToTerminal({stderr: 'socket disconected'});
        });
    }

    function outToTerminal(pMsg){
        var i, n, lResult, lStdout, lStderr,
            lConsole = CloudCmd.Console;
        DOM.Images.hideLoad();

        if( Util.isObject(lConsole) ){
            if(Messages.length){
                /* show oll msg from buffer */
                for(i = 0, n = Messages.length; i < n; i++){
                    lStdout = Messages[i].stdout;
                    lStderr = Messages[i].stderr;

                    if(lStdout)
                        lConsole.log(lStdout);

                    if(lStderr){
                        /* if it's object - convert is to string' */
                        if( Util.isObject(lStderr) )
                            lStderr =  Util.stringifyJSON(lStderr);

                        lConsole.error(lStderr);
                    }
                }
                Messages = [];
            }

            lStdout = pMsg.stdout;
            lStderr = pMsg.stderr;

            if(lStdout)
                lResult = lConsole.log(lStdout);

            if(lStderr && lStderr.code !== 1)
                lResult = lConsole.error(lStderr.toString());
        }
        else
            /* if term not accesable save msg to buffer */
            Messages.push(pMsg);

        Util.log(pMsg);

        return lResult;
    }

})(CloudCmd, Util, DOM);<|endoftext|>


<commit_before>/*global $:false, _:false, Morris:false, __report:false, __history:false, __options: false */
/*jshint browser:true*/

$(function(){
  "use strict";

  // bootstrap popover
  $('[rel=popover]').popover();

  // @todo put client side templates into a JST
  var fileGraphTemplate = _.template(
    '<div class="threshold-<%= threshold %>">' +
      '<%= label %>' +
      '<span class="horizontal-bar" style="width:<%= width %>px">' +
      '<%= value %>' +
      '
'
  );

  var horizontalBar = function(orig, width, label, thresholds){
    var threshold = 0;
    for (var i = thresholds.length - 1; i > -1; i--) {
      if (orig > thresholds[i]) {
        threshold = i + 1;
        break;
      }
    }
    return fileGraphTemplate({
      width : width,
      label : label,
      threshold : threshold,
      value : orig
    });
  };

  function drawFileCharts() {
    // @todo make a jQuery plugin to accomodate the horizontalBar function
    $('.js-file-chart').each(function(){
      var el = $(this), width = el.width();

      var value = el.data('complexity');
      el.append(horizontalBar(value, Math.min(value * 2, width),'complexity', [5,10]));

      value = el.data('sloc');
      el.append(horizontalBar(value, Math.min(value, width), 'sloc', [400,600]));

      value = el.data('bugs');
      el.append(horizontalBar(value, value * 5, 'est errors', [1,5]));

      value = el.data('lint');
      el.append(horizontalBar(value, value * 5, 'lint errors', [1,10]));
    });
  }

  function drawOverviewCharts(reports) {

    var maintainability = {
      element: 'chart_maintainability',
      data: [],
      xkey: 'label',
      ykeys: ['value'],
      ymax : 100,
      ymin : 0,
      labels: ['Maintainability'],
      barColors : ['#ff9b40']
    };
    var sloc = {
      element: 'chart_sloc',
      data: [],
      xkey: 'label',
      ykeys: ['value'],
      ymax : 400,
      labels: ['Lines'],
      barColors : ['#1f6b75']
    };
    var bugs = {
      element: 'chart_bugs',
      data: [],
      xkey: 'label',
      ykeys: ['value'],
      labels: ['Errors'],
      ymax: 20,
      barColors : ['#ff9b40']
    };
    var lint = {
      element: 'chart_lint',
      data: [],
      xkey: 'label',
      ykeys: ['value'],
      labels: ['Errors'],
      ymax: 20,
      barColors : ['#1f6b75']
    };

    reports.forEach(function(report){

      // @todo shouldn't need this, 'auto [num]' doesn't seem to work : https://github.com/oesmith/morris.js/issues/201
      sloc.ymax = Math.max(sloc.ymax, report.complexity.aggregate.complexity.sloc.physical);
      bugs.ymax = Math.max(bugs.ymax, report.complexity.aggregate.complexity.halstead.bugs.toFixed(2));

      sloc.data.push({
        value : report.complexity.aggregate.complexity.sloc.physical,
        label : report.info.fileShort
      });
      bugs.data.push({
        value : report.complexity.aggregate.complexity.halstead.bugs.toFixed(2),
        label : report.info.fileShort
      });
      maintainability.data.push({
        value : report.complexity.maintainability ? report.complexity.maintainability.toFixed(2) : 0,
        label : report.info.fileShort
      });
      lint.data.push({
        value : report.jshint && report.jshint.messages,
        label : report.info.fileShort
      });
    });

    function onGraphClick(i){
      document.location = __report.reports[i].info.link;
    }

    var charts = [
      Morris.Bar(bugs),
      Morris.Bar(sloc),
      Morris.Bar(maintainability)
    ];

    if (__options.flags.jshint) charts.push(Morris.Bar(lint));

    charts.forEach(function(chart){
      chart.on('click', onGraphClick);
    });
    return charts;
  }

  function drawHistoricalChart(history) {
    var data = _.map(history,function(record){
      var date = new Date(record.date);
      return {
        date : date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate(),
        average_maintainability : parseFloat(record.average.maintainability),
        average_sloc : record.average.sloc
      };
    }).slice(-20);
    Morris.Line({
      element: 'chart_historical_sloc',
      data: data,
      xkey: 'date',
      ykeys: ['average_sloc'],
      labels: ['Average Lines'],
      parseTime : false
    });
    Morris.Line({
      element: 'chart_historical_maint',
      data: data,
      xkey: 'date',
      ykeys: ['average_maintainability'],
      labels: ['Maintainability'],
      ymax: 100,
      parseTime : false
    });
  }

  function drawCharts() {
    $('.js-chart').empty();
    drawHistoricalChart(__history);
    drawOverviewCharts(__report.reports);
    drawFileCharts(__report.reports);
  }

  drawCharts();

  $(window).on('resize', _.debounce(drawCharts,200));
});

<commit_msg>fixed file graphs<commit_after>/*global $:false, _:false, Morris:false, __report:false, __history:false, __options: false */
/*jshint browser:true*/

$(function(){
  "use strict";

  // bootstrap popover
  $('[rel=popover]').popover();

  // @todo put client side templates into a JST
  var fileGraphTemplate = _.template(
    '<div class="threshold-<%= threshold %>">' +
      '<%= label %>' +
      '<span class="horizontal-bar" style="width:<%= width %>px">' +
      '<%= value %>' +
      '
'
  );

  var horizontalBar = function(orig, width, label, thresholds){
    var threshold = 0;
    for (var i = thresholds.length - 1; i > -1; i--) {
      if (orig > thresholds[i]) {
        threshold = i + 1;
        break;
      }
    }
    return fileGraphTemplate({
      width : width,
      label : label,
      threshold : threshold,
      value : orig
    });
  };

  function drawFileCharts() {
    // @todo make a jQuery plugin to accomodate the horizontalBar function
    $('.js-file-chart').each(function(){
      var el = $(this),
          width = el.width() - 130; // @todo establish max width of graph in plugin

      el.empty();

      var value = el.data('complexity');
      el.append(horizontalBar(value, Math.min(value * 2, width),'complexity', [5,10]));

      value = el.data('sloc');
      el.append(horizontalBar(value, Math.min(value, width), 'sloc', [400,600]));

      value = el.data('bugs');
      el.append(horizontalBar(value, value * 5, 'est errors', [1,5]));

      value = el.data('lint');
      el.append(horizontalBar(value, value * 5, 'lint errors', [1,10]));
    });
  }

  function drawOverviewCharts(reports) {

    var maintainability = {
      element: 'chart_maintainability',
      data: [],
      xkey: 'label',
      ykeys: ['value'],
      ymax : 100,
      ymin : 0,
      labels: ['Maintainability'],
      barColors : ['#ff9b40']
    };
    var sloc = {
      element: 'chart_sloc',
      data: [],
      xkey: 'label',
      ykeys: ['value'],
      ymax : 400,
      labels: ['Lines'],
      barColors : ['#1f6b75']
    };
    var bugs = {
      element: 'chart_bugs',
      data: [],
      xkey: 'label',
      ykeys: ['value'],
      labels: ['Errors'],
      ymax: 20,
      barColors : ['#ff9b40']
    };
    var lint = {
      element: 'chart_lint',
      data: [],
      xkey: 'label',
      ykeys: ['value'],
      labels: ['Errors'],
      ymax: 20,
      barColors : ['#1f6b75']
    };

    reports.forEach(function(report){

      // @todo shouldn't need this, 'auto [num]' doesn't seem to work : https://github.com/oesmith/morris.js/issues/201
      sloc.ymax = Math.max(sloc.ymax, report.complexity.aggregate.complexity.sloc.physical);
      bugs.ymax = Math.max(bugs.ymax, report.complexity.aggregate.complexity.halstead.bugs.toFixed(2));

      sloc.data.push({
        value : report.complexity.aggregate.complexity.sloc.physical,
        label : report.info.fileShort
      });
      bugs.data.push({
        value : report.complexity.aggregate.complexity.halstead.bugs.toFixed(2),
        label : report.info.fileShort
      });
      maintainability.data.push({
        value : report.complexity.maintainability ? report.complexity.maintainability.toFixed(2) : 0,
        label : report.info.fileShort
      });
      lint.data.push({
        value : report.jshint && report.jshint.messages,
        label : report.info.fileShort
      });
    });

    function onGraphClick(i){
      document.location = __report.reports[i].info.link;
    }

    var charts = [
      Morris.Bar(bugs),
      Morris.Bar(sloc),
      Morris.Bar(maintainability)
    ];

    if (__options.flags.jshint) charts.push(Morris.Bar(lint));

    charts.forEach(function(chart){
      chart.on('click', onGraphClick);
    });
    return charts;
  }

  function drawHistoricalChart(history) {
    var data = _.map(history,function(record){
      var date = new Date(record.date);
      return {
        date : date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate(),
        average_maintainability : parseFloat(record.average.maintainability),
        average_sloc : record.average.sloc
      };
    }).slice(-20);
    Morris.Line({
      element: 'chart_historical_sloc',
      data: data,
      xkey: 'date',
      ykeys: ['average_sloc'],
      labels: ['Average Lines'],
      parseTime : false
    });
    Morris.Line({
      element: 'chart_historical_maint',
      data: data,
      xkey: 'date',
      ykeys: ['average_maintainability'],
      labels: ['Maintainability'],
      ymax: 100,
      parseTime : false
    });
  }

  function drawCharts() {
    $('.js-chart').empty();
    drawHistoricalChart(__history);
    drawOverviewCharts(__report.reports);
    drawFileCharts(__report.reports);
  }

  drawCharts();

  $(window).on('resize', _.debounce(drawCharts,200));
});

<|endoftext|>


<commit_before>var less = require('less'),
    Path = require('path');

module.exports = function (filename, body, config, callback) {

    function prepareLessError(err) {
        // Add missing meta-data
        err.character = typeof err.column === 'number' ? err.column : 0;

        // TODO: With recursive imports, LESS doesn't give the root file it parsed.
        //err.sourceFileName = filename;

        // If the less error include a few lines of context, append them to err.message.
        // Disabled because it violates the test that wants err.message to end with a newline.
        if (false && err.extract) {
            err.message += ':\n' + err.extract.join('\n');
        } else {
            // Ensure message ends with a dot.
            if (!/\.$/.test(err.message)) { err.message += '.'; }
        }
        return err;
    }

    var parseOptions = {
            paths: [Path.dirname(filename)]//,
//            filename: filename
        },
        parser = new less.Parser(parseOptions),
        results = [];

    parser.parse(body, function (err, tree) {
        if (err) {
            return callback(undefined, [prepareLessError(err)]);
        }

        try {
            // Compiling to CSS will throw in case of undefined @variables etc.:
            tree.toCSS();
        } catch (e) {
            return callback(undefined, [prepareLessError(e)]);
        }

        return callback(undefined, []);
    });
};
<commit_msg>Less linter: If the less compiler says the filename causing an error is 'input', substitute the name of the file we're linting.<commit_after>var less = require('less'),
    Path = require('path');

module.exports = function (filename, body, config, callback) {

    function prepareLessError(err) {
        // Add missing meta-data
        err.character = typeof err.column === 'number' ? err.column : 0;

        // TODO: With recursive imports, LESS doesn't give the root file it parsed.
        //err.sourceFileName = filename;

        // If the less error include a few lines of context, append them to err.message.
        // Disabled because it violates the test that wants err.message to end with a newline.
        if (false && err.extract) {
            err.message += ':\n' + err.extract.join('\n');
        } else {
            // Ensure message ends with a dot.
            if (!/\.$/.test(err.message)) { err.message += '.'; }
        }
        if (err.filename === 'input') {
            err.filename = filename;
        }
        return err;
    }

    var parseOptions = {
            paths: [Path.dirname(filename)]//,
//            filename: filename
        },
        parser = new less.Parser(parseOptions),
        results = [];

    parser.parse(body, function (err, tree) {
        if (err) {
            return callback(undefined, [prepareLessError(err)]);
        }

        try {
            // Compiling to CSS will throw in case of undefined @variables etc.:
            tree.toCSS();
        } catch (e) {
            return callback(undefined, [prepareLessError(e)]);
        }

        return callback(undefined, []);
    });
};
<|endoftext|>


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

// AUTOGENERATED. DO NOT EDIT.

goog.provide('goog.html.htmlTestVectors');
goog.setTestOnly();

goog.html.htmlTestVectors.HTML_TEST_VECTORS = [
    {input: "",
     acceptable: [
         "",
     ],
     name: "body_onload.html.test"},
    {input: "",
     acceptable: [
         "",
         "",
     ],
     name: "iframe_src.html.test"},
    {input: "",
     acceptable: [
         "",
         "",
         "",
         "",
         "",
     ],
     name: "img.html.test"},
    {input: "\">",
     acceptable: [
         "">",
         "">",
         "\">",
         "\">",
     ],
     name: "img_malformed.html.test"},
    {input: "",
     acceptable: [
         "",
         "",
         "",
         "",
         "",
     ],
     name: "img_onerror.html.test"},
    {input: "",
     acceptable: [
         "",
         "",
         "",
         "",
         "",
     ],
     name: "img_quot.html.test"},
    {input: "",
     acceptable: [
         "",
     ],
     name: "img_style.html.test"},
    {input: "",
     acceptable: [
         "",
         "",
         "",
         "",
         "",
     ],
     name: "img_tab.html.test"},
    {input: "<input type=\"image\" src=\"javascript:alert('xss');\">",
     acceptable: [
         "",
         "<input type=\"image\">",
         "<input type=\"image\" />",
     ],
     name: "input.html.test"},
    {input: "javascript:/*--></title></style></textarea></script></xmp><svg/onload='+/\"/+/onmouseover=1/+/[*/[]/+alert(xss)//'>",
     acceptable: [
         "javascript:/*-->",
     ],
     name: "polygot.html.test"},
    {input: "<LINK REL=\"stylesheet\" HREF=\"http://google.com/xss.css\">",
     acceptable: [
         "<link rel=\"stylesheet\"/>",
         "<link rel=stylesheet>",
         "",
     ],
     name: "remote_stylesheet.html.test"},
    {input: "",
     acceptable: [
         "",
     ],
     name: "remote_stylesheet2.html.test"},
    {input: "",
     acceptable: [
         "",
     ],
     name: "script_alert.html.test"},
    {input: "<",
     acceptable: [
         "<",
     ],
     name: "script_extra.html.test"},
    {input: "<<s/script>",
     acceptable: [
         "<",
         "<script>alert()</script>",
         "<script>alert()</script>",
     ],
     name: "script_inception.html.test"},
    {input: "",
     acceptable: [
         "",
     ],
     name: "script_src.html.test"},
    {input: "</title>",
     acceptable: [
         "",
     ],
     name: "script_title.html.test"},
    {input: "",
     acceptable: [
         "",
         "",
         "",
         "",
         "",
     ],
     name: "unicode.html.test"},
];
<commit_msg>Fix incorrect code in Closure mocking framework documentation<commit_after>// Copyright 2019 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// AUTOGENERATED. DO NOT EDIT.

goog.provide('goog.html.htmlTestVectors');
goog.setTestOnly();

goog.html.htmlTestVectors.HTML_TEST_VECTORS = [
    {input: "",
     acceptable: [
         "",
     ],
     name: "body_onload"},
    {input: "",
     acceptable: [
         "",
         "",
     ],
     name: "iframe_src"},
    {input: "",
     acceptable: [
         "",
         "",
         "",
         "",
         "",
     ],
     name: "img"},
    {input: "\">",
     acceptable: [
         "">",
         "">",
         "\">",
         "\">",
     ],
     name: "img_malformed"},
    {input: "",
     acceptable: [
         "",
         "",
         "",
         "",
         "",
     ],
     name: "img_onerror"},
    {input: "",
     acceptable: [
         "",
         "",
         "",
         "",
         "",
     ],
     name: "img_quot"},
    {input: "",
     acceptable: [
         "",
     ],
     name: "img_style"},
    {input: "",
     acceptable: [
         "",
         "",
         "",
         "",
         "",
     ],
     name: "img_tab"},
    {input: "<input type=\"image\" src=\"javascript:alert('xss');\">",
     acceptable: [
         "",
         "<input type=\"image\">",
         "<input type=\"image\" />",
     ],
     name: "input"},
    {input: "javascript:/*--></title></style></textarea></script></xmp><svg/onload='+/\"/+/onmouseover=1/+/[*/[]/+alert(xss)//'>",
     acceptable: [
         "javascript:/*-->",
     ],
     name: "polygot"},
    {input: "<LINK REL=\"stylesheet\" HREF=\"http://google.com/xss.css\">",
     acceptable: [
         "<link rel=\"stylesheet\"/>",
         "<link rel=stylesheet>",
         "",
     ],
     name: "remote_stylesheet"},
    {input: "",
     acceptable: [
         "",
     ],
     name: "remote_stylesheet2"},
    {input: "",
     acceptable: [
         "",
     ],
     name: "script_alert"},
    {input: "<",
     acceptable: [
         "<",
     ],
     name: "script_extra"},
    {input: "<<s/script>",
     acceptable: [
         "<",
         "<script>alert()</script>",
         "<script>alert()</script>",
     ],
     name: "script_inception"},
    {input: "",
     acceptable: [
         "",
     ],
     name: "script_src"},
    {input: "</title>",
     acceptable: [
         "",
     ],
     name: "script_title"},
    {input: "",
     acceptable: [
         "",
         "",
         "",
         "",
         "",
     ],
     name: "unicode"},
];
<|endoftext|>