<commit_before>import Ember from 'ember';
import ValidationError from 'ilios/mixins/validation-error';
import EmberValidations from 'ember-validations';

const { Component, computed, inject } = Ember;
const { service } = inject;
const { alias } = computed;

export default Component.extend(ValidationError, EmberValidations, {
  i18n: service(),
  singleMode: true,

  isSaving: false,

  tagName: 'div',

  numSubGroups: null,

  validationBuffer: alias('numSubGroups'),

  validations: {
    'validationBuffer': {
      presence: true,
      numericality: { onlyInteger: true, greaterThan: 0, lessThanOrEqualTo : 50 }
    },
  },

  actions: {
    save() {
      this.validate()
        .then(() => {
          this.set('isSaving', true);
          const num = this.get('numSubGroups');
          this.sendAction('generateNewLearnerGroups', num);
        })
        .catch(() => {});
    },

    cancel() {
      this.sendAction('cancel');
    },

    changeValue(value) {
      this.set('numSubGroups', value);
    }
  }
});
<commit_msg>lowered max to 12 for groups generation.<commit_after>import Ember from 'ember';
import ValidationError from 'ilios/mixins/validation-error';
import EmberValidations from 'ember-validations';

const { Component, computed, inject } = Ember;
const { service } = inject;
const { alias } = computed;

export default Component.extend(ValidationError, EmberValidations, {
  i18n: service(),
  singleMode: true,

  isSaving: false,

  tagName: 'div',

  numSubGroups: null,

  validationBuffer: alias('numSubGroups'),

  validations: {
    'validationBuffer': {
      presence: true,
      numericality: { onlyInteger: true, greaterThan: 0, lessThanOrEqualTo : 12 }
    },
  },

  actions: {
    save() {
      this.validate()
        .then(() => {
          this.set('isSaving', true);
          const num = this.get('numSubGroups');
          this.sendAction('generateNewLearnerGroups', num);
        })
        .catch(() => {});
    },

    cancel() {
      this.sendAction('cancel');
    },

    changeValue(value) {
      this.set('numSubGroups', value);
    }
  }
});
<|endoftext|>


<commit_before>'use strict';

angular.module('featureToggleFrontend')
    .factory('CurrentUser', function ($window, ENV) {
        function CurrentUser() {
            if (ENV.RequiresAuth === true) {
                var data = $window.user._json;
                angular.extend(this, data);
            }
        }

        // todo: what does this do?
        CurrentUser.create = function (data) {
            return new CurrentUser(data);
        };

        CurrentUser.prototype = {

          getPicture: function () {
            if (!ENV.RequiresAuth) {
                return '/img/user-blue.jpeg';
            }

            if (ENV.AuthProviders.AzureAuth) {
                return 'data:image/png;base64,' + this.picture;
            }

            if (this.picture) {
                return this.picture;
            }

            return '/img/user-blue.jpeg';
          },

          getUser: function () {
                return this;
            },

            getFullName: function () {
                if (!ENV.RequiresAuth) {
                  return 'Anonymous';
                }

                return this.name.givenName + ' ' + this.name.familyName;
            },

            requiresAuthentication: function () {
                return ENV.RequiresAuth;
            }

        };

        return new CurrentUser();
    });
<commit_msg>only use the azure avatar if it is assigned<commit_after>'use strict';

angular.module('featureToggleFrontend')
    .factory('CurrentUser', function ($window, ENV) {
        function CurrentUser() {
            if (ENV.RequiresAuth === true) {
                var data = $window.user._json;
                angular.extend(this, data);
            }
        }

        // todo: what does this do?
        CurrentUser.create = function (data) {
            return new CurrentUser(data);
        };

        CurrentUser.prototype = {

          getPicture: function () {
            if (!ENV.RequiresAuth) {
                return '/img/user-blue.jpeg';
            }

            if (ENV.AuthProviders.AzureAuth && this.picture) {
                return 'data:image/png;base64,' + this.picture;
            }

            if (this.picture) {
                return this.picture;
            }

            return '/img/user-blue.jpeg';
          },

          getUser: function () {
                return this;
            },

            getFullName: function () {
                if (!ENV.RequiresAuth) {
                  return 'Anonymous';
                }

                return this.name.givenName + ' ' + this.name.familyName;
            },

            requiresAuthentication: function () {
                return ENV.RequiresAuth;
            }

        };

        return new CurrentUser();
    });
<|endoftext|>


<commit_before>#!/usr/bin/env node

// babel-preset-env doesn't find this import if you
// use require() with backtick strings so use the es6 syntax
import "@babel/polyfill"
const semver = require(`semver`)
const util = require(`util`)

const createCli = require(`./create-cli`)
const report = require(`./reporter`)

const pkg = require(`../package.json`)
const updateNotifier = require(`update-notifier`)
// Check if update is available
updateNotifier({ pkg }).notify()

const MIN_NODE_VERSION = `>=8.0.0`

if (!semver.satisfies(process.version, MIN_NODE_VERSION)) {
  report.panic(
    report.stripIndent(`
      Gatsby requires Node.js v8 or higher (you have ${process.version}).
      Upgrade Node to the latest stable release: https://gatsby.dev/upgrading-node-js
    `)
  )
}

process.on(`unhandledRejection`, reason => {
  // This will exit the process in newer Node anyway so lets be consistent
  // across versions and crash

  // reason can be anything, it can be a message, an object, ANYTHING!
  // we convert it to an error object so we don't crash on structured error validation
  if (!(reason instanceof Error)) {
    reason = new Error(util.format(reason))
  }

  report.panic(`UNHANDLED REJECTION`, reason)
})

process.on(`uncaughtException`, error => {
  report.panic(`UNHANDLED EXCEPTION`, error)
})

createCli(process.argv)
<commit_msg>fix(gatsby-cli): Add isGlobal to update notifier. (#18015)<commit_after>#!/usr/bin/env node

// babel-preset-env doesn't find this import if you
// use require() with backtick strings so use the es6 syntax
import "@babel/polyfill"
const semver = require(`semver`)
const util = require(`util`)

const createCli = require(`./create-cli`)
const report = require(`./reporter`)

const pkg = require(`../package.json`)
const updateNotifier = require(`update-notifier`)
// Check if update is available
updateNotifier({ pkg }).notify({ isGlobal: true })

const MIN_NODE_VERSION = `>=8.0.0`

if (!semver.satisfies(process.version, MIN_NODE_VERSION)) {
  report.panic(
    report.stripIndent(`
      Gatsby requires Node.js v8 or higher (you have ${process.version}).
      Upgrade Node to the latest stable release: https://gatsby.dev/upgrading-node-js
    `)
  )
}

process.on(`unhandledRejection`, reason => {
  // This will exit the process in newer Node anyway so lets be consistent
  // across versions and crash

  // reason can be anything, it can be a message, an object, ANYTHING!
  // we convert it to an error object so we don't crash on structured error validation
  if (!(reason instanceof Error)) {
    reason = new Error(util.format(reason))
  }

  report.panic(`UNHANDLED REJECTION`, reason)
})

process.on(`uncaughtException`, error => {
  report.panic(`UNHANDLED EXCEPTION`, error)
})

createCli(process.argv)
<|endoftext|>


<commit_before>var React = require('react');
var TestUtils = require('react/lib/ReactTestUtils');
var expect = require('expect');
var FuzzySearch = require("../src/index")
var _testData = require("./data")

function createComponent(onChange){
	return (
		<FuzzySearch
          idField="id" // The name of the id (or other field) per object in the items array to use as a key property for results)
          items={_testData} // An array (or Immutable.js List)
          nameField="n" // The name of the property to display as results
          maxUnfilteredItems={100} // The number of item to display when not searching
          minScore={.7} // The minimum score to place in the list. minScore is multiplied by the number of search terms.
          onChange={onChange} // Item selected callback
          placeholder="Search..."
          searchField="n" // The name of the property to search
        />
	);
}

describe("Search arbritary data and find best matches", function(){
	it('renders', function () {
		var fuzzySearch = TestUtils.renderIntoDocument(createComponent());
		expect(fuzzySearch).toExist();
	});

	it("returns results", function(done){
		var fuzzySearch = TestUtils.renderIntoDocument(createComponent());
		var inp = TestUtils.findRenderedDOMComponentWithClass(fuzzySearch, "fuzzy-inp")

		TestUtils.Simulate.focus(inp)
        TestUtils.Simulate.change(inp, { target: { value: "tiffany morton"}})

		setTimeout(function(){
			var results = TestUtils.scryRenderedDOMComponentsWithClass(fuzzySearch, "fuzzy-search-result")
			expect(results.length).toBeGreaterThan(0)
			done();
		}, 300)
	})

	it("ranks an exact match number one", function(done){
		var fuzzySearch = TestUtils.renderIntoDocument(createComponent());
		var inp = TestUtils.findRenderedDOMComponentWithClass(fuzzySearch, "fuzzy-inp")

		TestUtils.Simulate.focus(inp)
        TestUtils.Simulate.change(inp, { target: { value: "tiffany morton"}})

        setTimeout(function(){
			var results = TestUtils.scryRenderedDOMComponentsWithClass(fuzzySearch, "fuzzy-search-result")
			expect(results[0].getDOMNode().textContent).toBe("Tiffany Morton")
			done();
		}, 300)
	})

	it("ranks closest match number one", function(done){
		var fuzzySearch = TestUtils.renderIntoDocument(createComponent());
		var inp = TestUtils.findRenderedDOMComponentWithClass(fuzzySearch, "fuzzy-inp")

		TestUtils.Simulate.focus(inp)
        TestUtils.Simulate.change(inp, { target: { value: "tiphanie morten"}})

        setTimeout(function(){
			var results = TestUtils.scryRenderedDOMComponentsWithClass(fuzzySearch, "fuzzy-search-result")
			expect(results[0].getDOMNode().textContent).toBe("Tiffany Morton")
			done();
		}, 300)
	})

	it("excludes results that are poor matches", function(done){
		var fuzzySearch = TestUtils.renderIntoDocument(createComponent());
		var inp = TestUtils.findRenderedDOMComponentWithClass(fuzzySearch, "fuzzy-inp")

		TestUtils.Simulate.focus(inp)
        TestUtils.Simulate.change(inp, { target: { value: "doreen levine"}})

        setTimeout(function(){
			var results = TestUtils.scryRenderedDOMComponentsWithClass(fuzzySearch, "fuzzy-search-result")
			expect(results.some(n => n.getDOMNode().textContent == "Dong Schwartz")).toBe(false)
			done();
		}, 300)
	})

	afterEach(function(done){
        var React = require("react/addons");
        React.unmountComponentAtNode(document.body);
        document.body.innerHTML == "";
        setTimeout(done);
    })
})<commit_msg>Tests for resultsComponents<commit_after>var React = require('react');
var TestUtils = require('react/lib/ReactTestUtils');
var expect = require('expect');
var FuzzySearch = require("../src/index")
var _testData = require("./data")

function createComponent(onChange, resultsComponent, resultsComponentProps){
	return (
		<FuzzySearch
          idField="id" // The name of the id (or other field) per object in the items array to use as a key property for results)
          items={_testData} // An array (or Immutable.js List)
          nameField="n" // The name of the property to display as results
          maxUnfilteredItems={100} // The number of item to display when not searching
          minScore={.7} // The minimum score to place in the list. minScore is multiplied by the number of search terms.
          onChange={onChange} // Item selected callback
          placeholder="Search..."
          resultsComponent={resultsComponent}
          resultsComponentProps={resultsComponentProps}
          searchField="n" // The name of the property to search
        />
	);
}

describe("Search arbritary data and find best matches", function(){
	it('renders', function () {
		var fuzzySearch = TestUtils.renderIntoDocument(createComponent());
		expect(fuzzySearch).toExist();
	});

	it("returns results", function(done){
		var fuzzySearch = TestUtils.renderIntoDocument(createComponent());
		var inp = TestUtils.findRenderedDOMComponentWithClass(fuzzySearch, "fuzzy-inp")

		TestUtils.Simulate.focus(inp)
        TestUtils.Simulate.change(inp, { target: { value: "tiffany morton"}})

		setTimeout(function(){
			var results = TestUtils.scryRenderedDOMComponentsWithClass(fuzzySearch, "fuzzy-search-result")
			expect(results.length).toBeGreaterThan(0)
			done();
		}, 300)
	})

	it("ranks an exact match number one", function(done){
		var fuzzySearch = TestUtils.renderIntoDocument(createComponent());
		var inp = TestUtils.findRenderedDOMComponentWithClass(fuzzySearch, "fuzzy-inp")

		TestUtils.Simulate.focus(inp)
        TestUtils.Simulate.change(inp, { target: { value: "tiffany morton"}})

        setTimeout(function(){
			var results = TestUtils.scryRenderedDOMComponentsWithClass(fuzzySearch, "fuzzy-search-result")
			expect(results[0].getDOMNode().textContent).toBe("Tiffany Morton")
			done();
		}, 300)
	})

	it("ranks closest match number one", function(done){
		var fuzzySearch = TestUtils.renderIntoDocument(createComponent());
		var inp = TestUtils.findRenderedDOMComponentWithClass(fuzzySearch, "fuzzy-inp")

		TestUtils.Simulate.focus(inp)
        TestUtils.Simulate.change(inp, { target: { value: "tiphanie morten"}})

        setTimeout(function(){
			var results = TestUtils.scryRenderedDOMComponentsWithClass(fuzzySearch, "fuzzy-search-result")
			expect(results[0].getDOMNode().textContent).toBe("Tiffany Morton")
			done();
		}, 300)
	})

	it("excludes results that are poor matches", function(done){
		var fuzzySearch = TestUtils.renderIntoDocument(createComponent());
		var inp = TestUtils.findRenderedDOMComponentWithClass(fuzzySearch, "fuzzy-inp")

		TestUtils.Simulate.focus(inp)
        TestUtils.Simulate.change(inp, { target: { value: "doreen levine"}})

        setTimeout(function(){
			var results = TestUtils.scryRenderedDOMComponentsWithClass(fuzzySearch, "fuzzy-search-result")
			expect(results.some(n => n.getDOMNode().textContent == "Dong Schwartz")).toBe(false)
			done();
		}, 300)
	})

	it("Uses a custom component passed as resultsComponent", function(done){
		var customComponent = React.createClass({
			render: function() { return <div className="custom-component" />}
		})
		var fuzzySearch = TestUtils.renderIntoDocument(createComponent(null, customComponent));
		var inp = TestUtils.findRenderedDOMComponentWithClass(fuzzySearch, "fuzzy-inp")

		TestUtils.Simulate.focus(inp)
        TestUtils.Simulate.change(inp, { target: { value: "doreen levine"}})

        setTimeout(function(){
			var renderedCustomComponent = TestUtils.scryRenderedDOMComponentsWithClass(fuzzySearch, "custom-component")
			expect(renderedCustomComponent.length).toBe(25)
			done();
		}, 300)

	})

	afterEach(function(done){
        var React = require("react/addons");
        React.unmountComponentAtNode(document.body);
        document.body.innerHTML == "";
        setTimeout(done);
    })
})<|endoftext|>


<commit_before>
var DEFAULT_MIN = 1;
var DEFAULT_MAX = 3;

App.QuantityWidgetComponent = Ember.Component.extend({

  tagName: 'div',
  classNameBindings: [ ':quantity-widget', 'isMin', 'isMax', 'isDirty' ],
  attributeBindings: [ 'name:data-icon' ],
  quantityDidChange: 'quantityDidChange',
  showRemoveControl: false,

  trackedActions: {
    increment: true,
    decrement: true
  },

  actions: {
    plusIcon: function () {
      this.send('increment');
    },

    minusIcon: function () {
      this.send('decrement');
    },

    removeIcon: function () {
      this.set('quantity', 0);
    },

    increment: function () {
      this.handleMax();
      if (this.get('isMax')) return;
      this.set('quantity', this.incrementProperty('quantity'));
    },

    decrement: function () {
      if (this.get('isMin')) return;
      this.set('quantity', this.decrementProperty('quantity') );
      this.handleMax();
    }
  },

  initial: Ember.computed.oneWay('quantity'),
  quantity: DEFAULT_MIN,
  max: DEFAULT_MAX,
  min: DEFAULT_MIN,

  isDirty: function () {
    return this.get('initial') !== this.get('quantity');
  }.property('quantity'),

  isMin: function () {
    return this.get('quantity') === this.get('min');
  }.property('quantity'),

  isMax: function () {
    return this.get('quantity') >= this.get('max');
  }.property('quantity'),

  handleMax: function () {
    Ember.run.cancel(this.timer);

    if ( this.get('isMax') ) {
      this.set('showMax', true);
      this.timer = Ember.run.later(this, function (){
        this.set('showMax', false);
      }, 1500);
    } else {
      this.set('showMax', false);
    }
  },

  onQuantityChange: function () {
    this.sendAction('quantityDidChange', this.get('trackedModel'), this.get('quantity'));
  }.observes('quantity'),

  shouldShowRemoveControl: function () {
    return ( this.get('showRemoveControl') && this.get('isMin') );
  }.property('isMin', 'quantity')

});
<commit_msg>Support for arbitray quantityString in quantity widget<commit_after>
var DEFAULT_MIN = 1;
var DEFAULT_MAX = 3;

App.QuantityWidgetComponent = Ember.Component.extend({

  tagName: 'div',
  classNameBindings: [ ':quantity-widget', 'isMin', 'isMax', 'isDirty' ],
  attributeBindings: [ 'name:data-icon' ],
  quantityDidChange: 'quantityDidChange',
  showRemoveControl: false,
  quantityString: 'Qty. %@',

  trackedActions: {
    increment: true,
    decrement: true
  },

  actions: {
    plusIcon: function () {
      this.send('increment');
    },

    minusIcon: function () {
      this.send('decrement');
    },

    removeIcon: function () {
      this.set('quantity', 0);
    },

    increment: function () {
      this.handleMax();
      if (this.get('isMax')) return;
      this.set('quantity', this.incrementProperty('quantity'));
    },

    decrement: function () {
      if (this.get('isMin')) return;
      this.set('quantity', this.decrementProperty('quantity') );
      this.handleMax();
    }
  },

  initial: Ember.computed.oneWay('quantity'),
  quantity: DEFAULT_MIN,
  max: DEFAULT_MAX,
  min: DEFAULT_MIN,

  isDirty: function () {
    return this.get('initial') !== this.get('quantity');
  }.property('quantity'),

  isMin: function () {
    return this.get('quantity') === this.get('min');
  }.property('quantity'),

  isMax: function () {
    return this.get('quantity') >= this.get('max');
  }.property('quantity'),

  quantityText: function () {
    return this.get('quantityString').fmt(this.get('quantity'));
  }.property('quantity', 'quantityString'),

  handleMax: function () {
    Ember.run.cancel(this.timer);

    if ( this.get('isMax') ) {
      this.set('showMax', true);
      this.timer = Ember.run.later(this, function (){
        this.set('showMax', false);
      }, 1500);
    } else {
      this.set('showMax', false);
    }
  },

  onQuantityChange: function () {
    this.sendAction('quantityDidChange', this.get('trackedModel'), this.get('quantity'));
  }.observes('quantity'),

  shouldShowRemoveControl: function () {
    return ( this.get('showRemoveControl') && this.get('isMin') );
  }.property('isMin', 'quantity')

});
<|endoftext|>


<commit_before>var Pontoon = function() {

  /* private */
  var PREFIX = 5,
      _clients = [];

  /* public  */
  return {

	  /*
	   * Send data to server
	   * Pontoon server push expects a POST with the following properties:
	   *
	   * id - list of msgid strings, the length of id should match the length of value ['Hello World']
	   * value - list of msgstrs, should be empty if no changes, otherwise set to the edited value ['Hallo Welt']
	   * project - url of the page being localized
	   * locale - locale msgstrs are localized too
	  */
	  send: function() {
	    var project = ('project' in this.client._meta) ? this.client._meta['project'] : this.client._doc.location.href,
	        lang = $(this.client._ptn).find('input').val(),
	        data = {
	          'id': [],
	          'value': [],
	          'project': project,
	          'locale': lang
	        },
	        entities = [],
	        url = ('url' in this.client._meta) ? this.client._meta['url'] : 'http://pontoon.server.ubuntu:8001/push/';

	    $(this.client._entities).each(function() {
	      var entity = this,
	          trans = entity.translation ? entity.translation : entity.string;
	      entities.push({
	        'id': entity.string,
	        'value': trans
	      });
	    });

	    $(entities).each(function() {
	      data['id'].push(this.id);
	      if (this.id === this.value) {
	        data['value'].push("");
	      } else {
	        data['value'].push(this.value);
	      }
	    });

	    $.ajaxSettings.traditional = true;
	    $.post(url, data, null, "text");
	  },

	  /**
	   * Build source - translation pairs
	   */
	  rebuildUIList: function() {
	    var self = this,
	        list = $(this.client._ptn).find('#entitylist').empty()
	        // tables still need 'cellspacing="0"' in the markup
	        // http://meyerweb.com/eric/thoughts/2007/05/01/reset-reloaded/
	        .append('

Source	Translation

');

	    // Render
		$(this.client._entities).each(function() {
	      var tr = $('

' + this.txtString + '

TranslationTranslation memoryOther usersOther locales
<textarea>' + (this.translation || '') + '</textarea>
', self.client._ptn);

	      tr.get(0).entity = this;
	      this.node.get(0).entity = this;
	      this.ui = tr;

	      list.find('tbody').append(tr);
		});

	    // Event handlers
	    $("#pontoon tr").hover(function() {
	      this.entity.hover();
	    }, function() {
	      this.entity.unhover();
	    }).click(function() {
	      $(self.client._doc).find('.editableToolbar > .edit').click();
	    });

	    this.updateProgress();
	  },

	  /**
	   * Update progress indicator and value
	   */
	  updateProgress: function() {
	  	var all = $("#pontoon tbody tr").length,
	  	    translated = $("#pontoon tbody tr.translated").length;
	    $('#progress span').width(Math.round(translated*100 / all) + '%');
	    $('#progress-value').html(translated + '/' + all);
	  },

	  /**
	   * Attach event handlers
	   */
	  attachHandlers: function() {
	  	var self = this;

	    // Update entities and progress when saved
	    $(".editableToolbar > .save", this.client._doc).click(function() {
	      var element = $(this).parent().get(0).target;
	      self.updateEntities(element);
	      self.updateProgress();
	    });

	    // Update progress when cancelled
	    $(".editableToolbar > .cancel", this.client._doc).click(function() {
	      self.updateProgress();
	    });

	    // Open/close Pontoon UI
	    $('#switch, #logo').unbind("click.pontoon").bind("click.pontoon", function() {
	      $('#entitylist').toggle();
	      $('#source').height($(document).height() - $('#pontoon').height());
	      $('#pontoon').toggleClass('opened');
	    });

	    // Locale selector
	    $('#locale').unbind("click.pontoon").bind("click.pontoon", function() {
	      $('#locale-list').css("left", $("#locale").position().left).toggle();
	      $(this).toggleClass('opened');
	    });
	    $('#locale-list li').unbind("click.pontoon").bind("click.pontoon", function() {
	      $('#flag').attr("class", $(this).find('span').attr("class"));
	      $('#locale .language').html($(this).find('.language').html());
	      $('#locale').click();
	    });

	    // Send changes to server
	    $("#send").click(function () {
	      self.send();
	    });
	  },

	  /**
	   * Update entity and main UI
	   *
	   * element HTML Element which contains html10n nodes
	   */
	  updateEntities: function(element) {
	    var entity = element.entity,
	        clone = $(element).clone();

	    entity.translation = $(clone).html();
	    entity.txtTranslation = $(clone).text();
	    entity.ui.find('textarea').text(entity.translation).parents('tr').addClass('translated');
	  },

	  /**
	   * Create entity object
	   */
	  createEntity: function(e) {
	  	var entity = {

	      string: e.string || null, /* Original string used in PO file (may include HTML markup) */
	      txtString: e.txtString || null, /* Original string used in UI (text only), derived from string */
	      translation: e.translation || null, /* Translated string used in PO file (may include HTML markup) */
	      txtTranslation: e.txtTranslation || null, /* Translated string used in UI (text only), derived from translation */
	      node: e.node || null, /* HTML Element holding string */
	      ui: e.ui || null, /* HTML Element representing string in the main UI */
	      id: e.id || null,
	      _client: this,

	      hover: function() {
	        this.node.get(0).showToolbar();
	        this.ui.toggleClass('hovered');
	      },
	      unhover: function() {
	        this.node.get(0).hideToolbar();
	        this.ui.toggleClass('hovered');
	      }
	  	}
		this.client._entities.push(entity);
	  },

	  /**
	   * Extract entities from the document, not prepared for working with Pontoon
	   * Create entity object from every non-empty text node
	   */
	  guessEntities: function() {
	    var self = this;

	    $(this.client._doc).find(':not("script, style")').contents().each(function() {
	      if (this.nodeType === Node.TEXT_NODE && $.trim(this.nodeValue).length > 0) {
	        entity = {};
	        entity.string = entity.txtString = entity.translation = entity.txtTranslation = entity.id = this.nodeValue;
	        entity.node = $(this).parent();
	        self.createEntity(entity);

	        $(this).parent().attr("data-l10n", entity.string);
	      }
	    });
	  },

	  /**
	   * Extract all gettext msgid and msgstr from the document
	   * Strings are prepended with l10n comment nodes
	   * Example: Hallo Welt
	   *
	   * Create entity object from comment and the text node that follows
	   * Move comment node contents to the parent's element data-l10n attribute
	   * Remove comment nodes
	   */
	  parseEntities: function() {
	    var self = this;

	    $(this.client._doc).find('*').contents().each(function() {
	      if (this.nodeType === Node.COMMENT_NODE && this.nodeValue.indexOf('l10n ') === 0) {
	        entity = {};
	        entity.string = entity.txtString = entity.id = this.nodeValue.substring(PREFIX);
	        entity.translation = entity.txtTranslation = $(this.nextSibling).text();
	        entity.node = $(this).parent();
	        self.createEntity(entity);

	        $(this).parent().attr("data-l10n", entity.string);
	        $(this).remove();
	      }
	    });
	  },

	  /**
	   * Determine if the current page is prepared for working with Pontoon
	   */
	  isEnchanted: function() {
		if (this.client._enchanted === null) {
	      this.client._enchanted = ($(this.client._doc).find('head > meta[name=Pontoon]').length > 0);
	    }
	    return this.client._enchanted;
	  },

	  /**
	   * Extract entities from the document
	   */
	  extractEntities: function() {
		if (this.isEnchanted()) {
	      return this.parseEntities();
	    }
	    return this.guessEntities();
	  },

	  /**
	   * Disable document editing
	   */
	  disableEditing: function() {
	    $(this.client._doc).find('link[href="../../client/lib/css/editable.css"]').each(function() {
	      $(this).remove();
	    });
	    $(this.client._entities).each(function() {
	      this.node.disableEditableText();
	    });
		$(this.client._doc).find('.editableToolbar').remove();
	  },

	  /**
	   * Enable document editing
	   */
	  enableEditing: function() {
	  	var ss = $('<link rel="stylesheet" href="../../client/lib/css/editable.css">', this.client._doc);
	    $('head', this.client._doc).append(ss);
	    this.extractEntities();
	    $(this.client._entities).each(function() {
	      this.node.editableText();
	    });
	  },

	  /**
	   * Initialize Pontoon Client
	   */
	  init: function(doc, ptn) {
	    if (!doc) {
	      throw "Document handler required";
	    }

	    // Build client object
	    this.client = {
		    _doc: doc,
		    _ptn: ptn,
		    _entities: [],
		    _meta: {},
		    _enchanted: null
	    };

		var meta = $(doc).find('head > meta[name=Pontoon]');
		if (meta.attr('content')) {
		  this.client._meta['project'] = meta.attr('content');
		}
		if (meta.attr('ip')) {
		  this.client._meta['url'] = meta.attr('ip');
		}

	    _clients.push(this.client);

        // Enable editable text
	    this.enableEditing();

	    // Show and render main UI
	    this.attachHandlers();
	    this.rebuildUIList();
	    $('#pontoon').slideDown();
	  }

  };
}();
<commit_msg>Tabs to spaces<commit_after>var Pontoon = function() {

  /* private */
  var PREFIX = 5,
      _clients = [];

  /* public  */
  return {

    /*
     * Send data to server
     * Pontoon server push expects a POST with the following properties:
     *
     * id - list of msgid strings, the length of id should match the length of value ['Hello World']
     * value - list of msgstrs, should be empty if no changes, otherwise set to the edited value ['Hallo Welt']
     * project - url of the page being localized
     * locale - locale msgstrs are localized too
    */
    send: function() {
      var project = ('project' in this.client._meta) ? this.client._meta['project'] : this.client._doc.location.href,
          lang = $(this.client._ptn).find('input').val(),
          data = {
            'id': [],
            'value': [],
            'project': project,
            'locale': lang
          },
          entities = [],
          url = ('url' in this.client._meta) ? this.client._meta['url'] : 'http://pontoon.server.ubuntu:8001/push/';

      $(this.client._entities).each(function() {
        var entity = this,
            trans = entity.translation ? entity.translation : entity.string;
        entities.push({
          'id': entity.string,
          'value': trans
        });
      });

      $(entities).each(function() {
        data['id'].push(this.id);
        if (this.id === this.value) {
          data['value'].push("");
        } else {
          data['value'].push(this.value);
        }
      });

      $.ajaxSettings.traditional = true;
      $.post(url, data, null, "text");
    },

    /**
     * Build source - translation pairs
     */
    rebuildUIList: function() {
      var self = this,
          list = $(this.client._ptn).find('#entitylist').empty()
          // tables still need 'cellspacing="0"' in the markup
          // http://meyerweb.com/eric/thoughts/2007/05/01/reset-reloaded/
          .append('

Source	Translation

');

      // Render
      $(this.client._entities).each(function() {
        var tr = $('

' + this.txtString + '

TranslationTranslation memoryOther usersOther locales
<textarea>' + (this.translation || '') + '</textarea>
', self.client._ptn);

        tr.get(0).entity = this;
        this.node.get(0).entity = this;
        this.ui = tr;

        list.find('tbody').append(tr);
      });

      // Event handlers
      $("#pontoon tr").hover(function() {
        this.entity.hover();
      }, function() {
        this.entity.unhover();
      }).click(function() {
        $(self.client._doc).find('.editableToolbar > .edit').click();
      });

      this.updateProgress();
    },

    /**
     * Update progress indicator and value
     */
    updateProgress: function() {
      var all = $("#pontoon tbody tr").length,
          translated = $("#pontoon tbody tr.translated").length;
      $('#progress span').width(Math.round(translated*100 / all) + '%');
      $('#progress-value').html(translated + '/' + all);
    },

    /**
     * Attach event handlers
     */
    attachHandlers: function() {
      var self = this;

      // Update entities and progress when saved
      $(".editableToolbar > .save", this.client._doc).click(function() {
        var element = $(this).parent().get(0).target;
        self.updateEntities(element);
        self.updateProgress();
      });

      // Update progress when cancelled
      $(".editableToolbar > .cancel", this.client._doc).click(function() {
        self.updateProgress();
      });

      // Open/close Pontoon UI
      $('#switch, #logo').unbind("click.pontoon").bind("click.pontoon", function() {
        $('#entitylist').toggle();
        $('#source').height($(document).height() - $('#pontoon').height());
        $('#pontoon').toggleClass('opened');
      });

      // Locale selector
      $('#locale').unbind("click.pontoon").bind("click.pontoon", function() {
        $('#locale-list').css("left", $("#locale").position().left).toggle();
        $(this).toggleClass('opened');
      });
      $('#locale-list li').unbind("click.pontoon").bind("click.pontoon", function() {
        $('#flag').attr("class", $(this).find('span').attr("class"));
        $('#locale .language').html($(this).find('.language').html());
        $('#locale').click();
      });

      // Send changes to server
      $("#send").click(function () {
        self.send();
      });
    },

    /**
     * Update entity and main UI
     *
     * element HTML Element which contains html10n nodes
     */
    updateEntities: function(element) {
      var entity = element.entity,
          clone = $(element).clone();

      entity.translation = $(clone).html();
      entity.txtTranslation = $(clone).text();
      entity.ui.find('textarea').text(entity.translation).parents('tr').addClass('translated');
    },

    /**
     * Create entity object
     */
    createEntity: function(e) {
      var entity = {
        string: e.string || null, /* Original string used in PO file (may include HTML markup) */
        txtString: e.txtString || null, /* Original string used in UI (text only), derived from string */
        translation: e.translation || null, /* Translated string used in PO file (may include HTML markup) */
        txtTranslation: e.txtTranslation || null, /* Translated string used in UI (text only), derived from translation */
        node: e.node || null, /* HTML Element holding string */
        ui: e.ui || null, /* HTML Element representing string in the main UI */
        id: e.id || null,
        _client: this,

        hover: function() {
          this.node.get(0).showToolbar();
          this.ui.toggleClass('hovered');
        },
        unhover: function() {
          this.node.get(0).hideToolbar();
          this.ui.toggleClass('hovered');
        }
      }

      this.client._entities.push(entity);
    },

    /**
     * Extract entities from the document, not prepared for working with Pontoon
     * Create entity object from every non-empty text node
     */
    guessEntities: function() {
      var self = this;

      $(this.client._doc).find(':not("script, style")').contents().each(function() {
        if (this.nodeType === Node.TEXT_NODE && $.trim(this.nodeValue).length > 0) {
          entity = {};
          entity.string = entity.txtString = entity.translation = entity.txtTranslation = entity.id = this.nodeValue;
          entity.node = $(this).parent();
          self.createEntity(entity);

          $(this).parent().attr("data-l10n", entity.string);
        }
      });
    },

    /**
     * Extract all gettext msgid and msgstr from the document
     * Strings are prepended with l10n comment nodes
     * Example: Hallo Welt
     *
     * Create entity object from comment and the text node that follows
     * Move comment node contents to the parent's element data-l10n attribute
     * Remove comment nodes
     */
    parseEntities: function() {
      var self = this;

      $(this.client._doc).find('*').contents().each(function() {
        if (this.nodeType === Node.COMMENT_NODE && this.nodeValue.indexOf('l10n ') === 0) {
          entity = {};
          entity.string = entity.txtString = entity.id = this.nodeValue.substring(PREFIX);
          entity.translation = entity.txtTranslation = $(this.nextSibling).text();
          entity.node = $(this).parent();
          self.createEntity(entity);

          $(this).parent().attr("data-l10n", entity.string);
          $(this).remove();
        }
      });
    },

    /**
     * Determine if the current page is prepared for working with Pontoon
     */
    isEnchanted: function() {
      if (this.client._enchanted === null) {
        this.client._enchanted = ($(this.client._doc).find('head > meta[name=Pontoon]').length > 0);
      }

      return this.client._enchanted;
    },

    /**
     * Extract entities from the document
     */
    extractEntities: function() {
      if (this.isEnchanted()) {
        return this.parseEntities();
      }

      return this.guessEntities();
    },

    /**
     * Disable document editing
     */
    disableEditing: function() {
      $(this.client._doc).find('link[href="../../client/lib/css/editable.css"]').each(function() {
        $(this).remove();
      });

      $(this.client._entities).each(function() {
        this.node.disableEditableText();
      });

      $(this.client._doc).find('.editableToolbar').remove();
    },

    /**
     * Enable document editing
     */
    enableEditing: function() {
      var ss = $('<link rel="stylesheet" href="../../client/lib/css/editable.css">', this.client._doc);
      $('head', this.client._doc).append(ss);

      this.extractEntities();

      $(this.client._entities).each(function() {
        this.node.editableText();
      });
    },

    /**
     * Initialize Pontoon Client
     */
    init: function(doc, ptn) {
      if (!doc) {
        throw "Document handler required";
      }

      // Build client object
      this.client = {
        _doc: doc,
        _ptn: ptn,
        _entities: [],
        _meta: {},
        _enchanted: null
      };

      // Read meta values
      var meta = $(doc).find('head > meta[name=Pontoon]');
      if (meta.attr('content')) {
        this.client._meta['project'] = meta.attr('content');
      }
      if (meta.attr('ip')) {
        this.client._meta['url'] = meta.attr('ip');
      }

      _clients.push(this.client);

      // Enable editable text
      this.enableEditing();

      // Show and render main UI
      this.attachHandlers();
      this.rebuildUIList();
      $('#pontoon').slideDown();
    }

  };
}();
<|endoftext|>


<commit_before>(function () {
  'use strict';
  angular
    .module('users')
    .controller('SearchCorpCodeDlgController', SearchCorpCodeDlgController);
  SearchCorpCodeDlgController.$inject = ['ArticleSendersMethodsService', '$scope', '$uibModalInstance'];
/*
 상장코드 검색용 대화창 콘트롤러
 */
  function SearchCorpCodeDlgController(ArticleSendersMethodsService, $scope, $uibModalInstance) {
    $scope.corpCode = '000000';
    $scope.result = { error: null };
    $scope.search = function ($event) {
      var keyCode = $event.which || $event.keyCode;
      if (keyCode === 13) {
        // on enter key
        ArticleSendersMethodsService.dartCorpInfo($scope.corpCode,
          function (error, data) {
            if (error) {
              $scope.success = true;
              $scope.result = {
                crp_nm: '(주) 비트피알',
                crp_nm_i: '비트피알',
                adr: '서울시 마포구 독막로 331 22F(도화동, 마스터즈타워)',
                hm_url: 'http://www.bitpr.kr',
                crp_no: '211-2345-23',
                phn_no: '02-2134-5678',
                est_dt: '20160601',
                corpCode: $scope.corpCode
              };
              // $scope.result.error = '인증에 실패하였습니다. 상장코드를 왁인해 주세요.';
            } else {
              $scope.success = true;
              delete $scope.result.error;
              $scope.result = data;
              $scope.result.corpCode = $scope.corpCode;
            }
          }
        );
      }
    };

    $scope.cancel = function() {
      $uibModalInstance.dismiss($scope.result.error);
    };
    // 선택된 파일공유 : 이메일 입력후 전송하기
    $scope.ok = function () {
      $uibModalInstance.close($scope.result);
    };
  }

  angular
    .module('users')
    .controller('AuthenticationController', AuthenticationController);

  AuthenticationController.$inject = ['$uibModal', '$scope', '$state', '$http', '$location', '$window', 'Authentication', 'PasswordValidator'];

  function AuthenticationController($uibModal, $scope, $state, $http, $location, $window, Authentication, PasswordValidator) {
    var vm = this;

    vm.authentication = Authentication;
    vm.getPopoverMsg = PasswordValidator.getPopoverMsg;
    vm.signup = signup;
    vm.signin = signin;
    vm.callOauthProvider = callOauthProvider;
    vm.email = $state.params.email;
    vm.credentials = {};
    vm.authCorpError;

    if ($location.search().result === 'success-signup') {
      vm.success = '회원등록이 완료되었습니다.';
    }

    // Get an eventual error defined in the URL query string:
    vm.error = $location.search().err;

    // If user is signed in then redirect back home
    if (vm.authentication.user) {
      $location.path('/');
    }

    vm.authCorpCode = function () {
      var modalInstance = $uibModal.open({
        animation: true,
        templateUrl: 'modules/users/client/views/authentication/search-corpcode-dialog.tmpl.html',
        controller: 'SearchCorpCodeDlgController'
      });

      modalInstance.result.then(function (res) {
        if (res && res.error) {
          vm.authCorpError = res.error;
        } else {
          console.log(res);
          vm.credentials.corpCode = res.corpCode;
          vm.credentials.corpName = res.crp_nm_i;
          vm.credentials.corpInfo = res;
          vm.credentials.telephone = res.phn_no;
        }
      }, function (error) {
        // on cancel
        vm.authCorpError = error;
      });
    };

    function signup(isValid) {
      vm.error = null;

      if (!isValid) {
        $scope.$broadcast('show-errors-check-validity', 'vm.userForm');

        return false;
      }

      $http.post('/api/auth/signup', vm.credentials).success(function (response) {
        // And redirect to the previous or home page
        $state.go('authentication.emailauthinfo');
      }).error(function (response) {
        vm.error = response.message;
      });
    }

    function signin(isValid) {
      vm.error = null;

      if (!isValid) {
        $scope.$broadcast('show-errors-check-validity', 'vm.userForm');

        return false;
      }

      $http.post('/api/auth/signin', vm.credentials).success(function (response) {
        // If successful we assign the response to the global user model
        vm.authentication.user = response;
        // And redirect to the previous or home page
        if ($state.previous.state.name === 'home') {
          $state.go('dashboard');
        } else {
          $state.go($state.previous.state.name || 'dashboard', $state.previous.params);
        }
      }).error(function (response) {
        vm.error = response.message;
      });
    }

    // OAuth provider request
    function callOauthProvider(url) {
      console.log($state.previous.href);
      if ($state.previous && $state.previous.href === '/')
        $state.previous.href = '/dashboard';

      if ($state.previous && $state.previous.href) {
        url += '?redirect_to=' + encodeURIComponent($state.previous.href);
      }

      console.log(url);
      // Effectively call OAuth authentication route:
      $window.location.href = url;
    }
  }
}());
<commit_msg>회원가입시 상장코드 인증하기<commit_after>(function () {
  'use strict';
  angular
    .module('users')
    .controller('SearchCorpCodeDlgController', SearchCorpCodeDlgController);
  SearchCorpCodeDlgController.$inject = ['ArticleSendersMethodsService', '$scope', '$uibModalInstance'];
/*
 상장코드 검색용 대화창 콘트롤러
 */
  function SearchCorpCodeDlgController(ArticleSendersMethodsService, $scope, $uibModalInstance) {
    $scope.corpCode = '';
    $scope.result = { error: null };
    $scope.search = function ($event) {
      var keyCode = $event.which || $event.keyCode;
      if (keyCode === 13) {
        // on enter key
        ArticleSendersMethodsService.dartCorpInfo($scope.corpCode,
          function (error, data) {
            if (error) {
              // local test 용 (dart에 실서버에서만 api허용)
              // $scope.success = true;
              // $scope.result = {
              //   crp_nm: '(주) 비트피알',
              //   crp_nm_i: '비트피알',
              //   adr: '서울시 마포구 독막로 331 22F(도화동, 마스터즈타워)',
              //   hm_url: 'http://www.bitpr.kr',
              //   crp_no: '211-2345-23',
              //   phn_no: '02-2134-5678',
              //   est_dt: '20160601',
              //   corpCode: $scope.corpCode
              // };
              $scope.result.error = '인증에 실패하였습니다. 상장코드를 왁인해 주세요.';
            } else {
              $scope.success = true;
              delete $scope.result.error;
              $scope.result = data;
              $scope.result.corpCode = $scope.corpCode;
            }
          }
        );
      }
    };

    $scope.cancel = function() {
      $uibModalInstance.dismiss($scope.result.error);
    };
    // 선택된 파일공유 : 이메일 입력후 전송하기
    $scope.ok = function () {
      $uibModalInstance.close($scope.result);
    };
  }

  angular
    .module('users')
    .controller('AuthenticationController', AuthenticationController);

  AuthenticationController.$inject = ['$uibModal', '$scope', '$state', '$http', '$location', '$window', 'Authentication', 'PasswordValidator'];

  function AuthenticationController($uibModal, $scope, $state, $http, $location, $window, Authentication, PasswordValidator) {
    var vm = this;

    vm.authentication = Authentication;
    vm.getPopoverMsg = PasswordValidator.getPopoverMsg;
    vm.signup = signup;
    vm.signin = signin;
    vm.callOauthProvider = callOauthProvider;
    vm.email = $state.params.email;
    vm.credentials = {};

    if ($location.search().result === 'success-signup') {
      vm.success = '회원등록이 완료되었습니다.';
    }

    // Get an eventual error defined in the URL query string:
    vm.error = $location.search().err;

    // If user is signed in then redirect back home
    if (vm.authentication.user) {
      $location.path('/');
    }

    vm.authCorpCode = function () {
      var modalInstance = $uibModal.open({
        animation: true,
        templateUrl: 'modules/users/client/views/authentication/search-corpcode-dialog.tmpl.html',
        controller: 'SearchCorpCodeDlgController'
      });

      modalInstance.result.then(function (res) {
        if (res && res.error) {
          vm.authCorpError = res.error;
        } else {
          console.log(res);
          vm.credentials.corpCode = res.corpCode;
          vm.credentials.corpName = res.crp_nm_i;
          vm.credentials.corpInfo = res;
          vm.credentials.telephone = res.phn_no;
        }
      }, function (error) {
        // on cancel
        vm.authCorpError = error;
      });
    };

    function signup(isValid) {
      vm.error = null;

      if (!isValid) {
        $scope.$broadcast('show-errors-check-validity', 'vm.userForm');

        return false;
      }

      $http.post('/api/auth/signup', vm.credentials).success(function (response) {
        // And redirect to the previous or home page
        $state.go('authentication.emailauthinfo');
      }).error(function (response) {
        vm.error = response.message;
      });
    }

    function signin(isValid) {
      vm.error = null;

      if (!isValid) {
        $scope.$broadcast('show-errors-check-validity', 'vm.userForm');

        return false;
      }

      $http.post('/api/auth/signin', vm.credentials).success(function (response) {
        // If successful we assign the response to the global user model
        vm.authentication.user = response;
        // And redirect to the previous or home page
        if ($state.previous.state.name === 'home') {
          $state.go('dashboard');
        } else {
          $state.go($state.previous.state.name || 'dashboard', $state.previous.params);
        }
      }).error(function (response) {
        vm.error = response.message;
      });
    }

    // OAuth provider request
    function callOauthProvider(url) {
      console.log($state.previous.href);
      if ($state.previous && $state.previous.href === '/')
        $state.previous.href = '/dashboard';

      if ($state.previous && $state.previous.href) {
        url += '?redirect_to=' + encodeURIComponent($state.previous.href);
      }

      console.log(url);
      // Effectively call OAuth authentication route:
      $window.location.href = url;
    }
  }
}());
<|endoftext|>


<commit_before>// Create the cache manager (a shared object)
var cacheManager = Titanium.App.Properties.getObject("cachedXHRDocuments", {});

XHR = function(){};

// Public functions
// ================

// GET
// @url (string) URL to fetch
// @onSuccess (function) success callback
// @onError (function) error callback
// @extraParams (object)
XHR.prototype.get = function(url, onSuccess, onError, extraParams) {
	// Debug
	// Titanium.API.info(url);

	// Create some default params
	var onSuccess = onSuccess || function(){};
	var onError = onError || function(){};
	var extraParams = extraParams || {};
	extraParams.async = (extraParams.hasOwnProperty('async')) ? extraParams.async : true;
	extraParams.ttl = extraParams.ttl || false;
	extraParams.shouldAuthenticate = extraParams.shouldAuthenticate || false; // if you set this to true, pass "username" and "password" as well
	extraParams.contentType = extraParams.contentType || "application/json";

	var cache = readCache(url);
	// If there is nothing cached, send the request
	if (!extraParams.ttl || cache == 0) {

		// Create the HTTP connection
		var xhr = Titanium.Network.createHTTPClient({
			enableKeepAlive: false
		});
		// Create the result object
		var result = {};

		// Open the HTTP connection
		xhr.open("GET", url, extraParams.async);
		xhr.setRequestHeader('Content-Type', extraParams.contentType);

		// If we need to authenticate
		if (extraParams.shouldAuthenticate) {
			var authstr = 'Basic ' + Titanium.Utils.base64encode(extraParams.username + ':' + extraParams.password);
			xhr.setRequestHeader('Authorization', authstr);
		}

		// When the connection was successful
		xhr.onload = function() {
			// Check the status of this
			result.status = xhr.status == 200 ? "ok" : xhr.status;
			result.data = xhr.responseText;

			onSuccess(result);

			// Cache this response
			writeCache(result.data, url, extraParams.ttl);
		};

		// When there was an error
		xhr.onerror = function(e) {
			// Check the status of this
			result.status = "error";
			result.data = e;
			result.code = xhr.status;
			onError(result);
		};

		xhr.send();
	} else {
		var result = {};

		result.status = "cache";
		result.data = cache;

		onSuccess(result);
	}
};

// POST requests
// @url (string) URL to fetch
// @data (object)
// @onSuccess (function) success callback
// @onError (function) error callback
// @extraParams (object)
XHR.prototype.post = function(url, data, onSuccess, onError, extraParams) {

	// Debug
	Titanium.API.info(url + " " + JSON.stringify(data));

	// Create some default params
	var onSuccess = onSuccess || function(){};
	var onError = onError || function(){};
	var extraParams = extraParams || {};
	extraParams.async = (extraParams.hasOwnProperty('async')) ? extraParams.async : true;
	extraParams.shouldAuthenticate = extraParams.shouldAuthenticate || false; // if you set this to true, pass "username" and "password" as well
	extraParams.contentType = extraParams.contentType || "application/json";

	// Create the HTTP connection
	var xhr = Titanium.Network.createHTTPClient({
		enableKeepAlive: false
	});
	// Create the result object
	var result = {};

	// Open the HTTP connection
	xhr.open("POST", url, extraParams.async);
	xhr.setRequestHeader('Content-Type', extraParams.contentType);

	// If we need to authenticate
	if (extraParams.shouldAuthenticate) {
		var authstr = 'Basic ' + Titanium.Utils.base64encode(extraParams.username + ':' + extraParams.password);
		xhr.setRequestHeader('Authorization', authstr);
	}

	// When the connection was successful
	xhr.onload = function() {
		// Check the status of this
		result.status = xhr.status == 200 ? "ok" : xhr.status;
		result.data = xhr.responseText;

		onSuccess(result);
	};

	// When there was an error
	xhr.onerror = function(e) {
		// Check the status of this
		result.status = "error";
		result.data = e.error;
		result.code = xhr.status;
		onError(result);
	};

	xhr.send(data);
};

// PUT requests
// @url (string) URL to fetch
// @data (object)
// @onSuccess (function) success callback
// @onError (function) error callback
// @extraParams (object)
XHR.prototype.put = function(url, data, onSuccess, onError, extraParams) {
	// Create some default params
	var onSuccess = onSuccess || function(){};
	var onError = onError || function(){};
	var extraParams = extraParams || {};
	extraParams.async = (extraParams.hasOwnProperty('async')) ? extraParams.async : true;
	extraParams.shouldAuthenticate = extraParams.shouldAuthenticate || false; // if you set this to true, pass "username" and "password" as well
	extraParams.contentType = extraParams.contentType || "application/json";

	// Create the HTTP connection
	var xhr = Titanium.Network.createHTTPClient({
		enableKeepAlive: false
	});
	// Create the result object
	var result = {};

	// Open the HTTP connection
	xhr.open("PUT", url, extraParams.async);
	xhr.setRequestHeader('Content-Type', extraParams.contentType);

	// If we need to authenticate
	if (extraParams.shouldAuthenticate) {
		var authstr = 'Basic ' + Titanium.Utils.base64encode(extraParams.username + ':' + extraParams.password);
		xhr.setRequestHeader('Authorization', authstr);
	}

	// When the connection was successful
	xhr.onload = function() {
		// Check the status of this
		result.status = xhr.status == 200 ? "ok" : xhr.status;
		result.data = xhr.responseText;

		onSuccess(result);
	};

	// When there was an error
	xhr.onerror = function(e) {
		// Check the status of this
		result.status = "error";
		result.data = e.error;
		result.code = xhr.status;
		onError(result);
	};

	xhr.send(data);
};

// DELETE requests
// @url (string) URL to fetch
// @onSuccess (function) success callback
// @onError (function) error callback
// @extraParams (object)
XHR.prototype.destroy = function(url, onSuccess, onError, extraParams) {
	// Create some default params
	var onSuccess = onSuccess || function(){};
	var onError = onError || function(){};
	var extraParams = extraParams || {};
	extraParams.async = (extraParams.hasOwnProperty('async')) ? extraParams.async : true;
	extraParams.shouldAuthenticate = extraParams.shouldAuthenticate || false; // if you set this to true, pass "username" and "password" as well
	extraParams.contentType = extraParams.contentType || "application/json";

	// Create the HTTP connection
	var xhr = Titanium.Network.createHTTPClient({
		enableKeepAlive: false
	});
	// Create the result object
	var result = {};

	// Open the HTTP connection
	xhr.open("DELETE", url, extraParams.async);
	xhr.setRequestHeader('Content-Type', extraParams.contentType);

	// If we need to authenticate
	if (extraParams.shouldAuthenticate) {
		var authstr = 'Basic ' + Titanium.Utils.base64encode(extraParams.username + ':' + extraParams.password);
		xhr.setRequestHeader('Authorization', authstr);
	}

	// When the connection was successful
	xhr.onload = function() {
		// Check the status of this
		result.status = xhr.status == 200 ? "ok" : xhr.status;
		result.data = xhr.responseText;

		onSuccess(result);
	};

	// When there was an error
	xhr.onerror = function(e) {
		// Check the status of this
		result.status = "error";
		result.data = e.error;
		result.code = xhr.status;
		onError(result);
	};

	xhr.send();
};

// Helper functions
// =================

// Removes all the expired documents from the manager and the file system
XHR.prototype.clean = function() {

	var nowInMilliseconds = new Date().getTime();
	var expiredDocuments = 0;

	for (var key in cacheManager) {
		var cache = cacheManager[key];

		if(cache.timestamp <= nowInMilliseconds){
			// Delete references and file
			var file = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, key);
			// Delete the record and file
			delete cacheManager[key];
			file.deleteFile();

			// Update the cache manager
			updateCacheManager();

			// Update the deleted documents count
			expiredDocuments = expiredDocuments + 1;

			//Titanium.API.info("REMOVED CACHE FILE " + cachedDocuments[i].file);
		}

	}

	// Return the number of files deleted
	return expiredDocuments;
};

// Removes all documents from the manager and the file system
XHR.prototype.purge = function() {

	var purgedDocuments = 0;

	for (var key in cacheManager) {
		var cache = cacheManager[key];
		// Delete references and file
		var file = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, key);
		// Delete the record and file
		delete cacheManager[key];
		file.deleteFile();

		// Update the cache manager
		updateCacheManager();

		// Update the deleted documents count
		purgedDocuments = purgedDocuments + 1;

		//Titanium.API.info("REMOVED CACHE FILE " + cachedDocuments[i].file);

	}

	// Return the number of files deleted
	return purgedDocuments;
};

// Private functions
// =================

readCache = function(url) {
	// Hash the URL
	var hashedURL = Titanium.Utils.md5HexDigest(url);

	// Check if the file exists in the manager (append the .dat extension?)
	var cache = cacheManager[hashedURL];
	// Default the return value to false
	var result = false;

	//Titanium.API.info("CHECKING CACHE");

	// If the file was found
	if (cache) {
		// Fetch a reference to the cache file
		var file = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, hashedURL);

		// Check that the TTL is further than the current date
		if (cache.timestamp >= new Date().getTime()) {
			//Titanium.API.info("CACHE FOUND");

			// Return the content of the file
			result = file.read();

		} else {
			//Titanium.API.info("OLD CACHE");

			// Delete the record and file
			delete cacheManager[hashedURL];
			file.deleteFile();

			// Update the cache manager
			updateCacheManager();
		}
	} else {
		//Titanium.API.info("NO CACHE FOUND");
	}

	return result;
};

updateCacheManager = function(){
	Titanium.App.Properties.setObject("cachedXHRDocuments", cacheManager);
};

writeCache = function(data, url, ttl) {

	//Titanium.API.info("WRITING CACHE");

	// hash the url
	var hashedURL = Titanium.Utils.md5HexDigest(url);

	// Write the file to the disk
	var file = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, hashedURL);

	// If the file was saved without any problems
	if (file.write(data)) {
		// Insert the cached object in the cache manager
		cacheManager[hashedURL] = { "timestamp": (new Date().getTime()) + (ttl*60*1000) };
		updateCacheManager();

		//Titanium.API.info("WROTE CACHE");
	}

};

// Return everything
module.exports = XHR;<commit_msg>Added support for XML and Binary content. See the docs for more info<commit_after>// Create the cache manager (a shared object)
var cacheManager = Titanium.App.Properties.getObject("cachedXHRDocuments", {});

XHR = function(){};

// Public functions
// ================

// GET
// @url (string) URL to fetch
// @onSuccess (function) success callback
// @onError (function) error callback
// @extraParams (object)
XHR.prototype.get = function(url, onSuccess, onError, extraParams) {
	// Debug
	// Titanium.API.info(url);

	// Create some default params
	var onSuccess = onSuccess || function(){};
	var onError = onError || function(){};
	var extraParams = extraParams || {};
	extraParams.async = (extraParams.hasOwnProperty('async')) ? extraParams.async : true;
	extraParams.ttl = extraParams.ttl || false;
	extraParams.shouldAuthenticate = extraParams.shouldAuthenticate || false; // if you set this to true, pass "username" and "password" as well
	extraParams.contentType = extraParams.contentType || "application/json";

	var cache = readCache(url);
	// If there is nothing cached, send the request
	if (!extraParams.ttl || cache == 0) {

		// Create the HTTP connection
		var xhr = Titanium.Network.createHTTPClient({
			enableKeepAlive: false
		});
		// Create the result object
		var result = {};

		// Open the HTTP connection
		xhr.open("GET", url, extraParams.async);
		xhr.setRequestHeader('Content-Type', extraParams.contentType);

		// If we need to authenticate
		if (extraParams.shouldAuthenticate) {
			var authstr = 'Basic ' + Titanium.Utils.base64encode(extraParams.username + ':' + extraParams.password);
			xhr.setRequestHeader('Authorization', authstr);
		}

		// When the connection was successful
		xhr.onload = function() {
			// Check the status of this
			result.status = xhr.status == 200 ? "ok" : xhr.status;

			// Check the type of content we should serve back to the user
			if (extraParams.contentType.indexOf("application/json") != -1) {
				result.data = xhr.responseText;
			} else if (extraParams.contentType.indexOf("text/xml") != -1) {
				result.data = xhr.responseXML;
			} else {
				result.data = xhr.responseData;
			}

			onSuccess(result);

			// Cache this response
			writeCache(result.data, url, extraParams.ttl);
		};

		// When there was an error
		xhr.onerror = function(e) {
			// Check the status of this
			result.status = "error";
			result.data = e;
			result.code = xhr.status;
			onError(result);
		};

		xhr.send();
	} else {
		var result = {};

		result.status = "cache";
		result.data = cache;

		onSuccess(result);
	}
};

// POST requests
// @url (string) URL to fetch
// @data (object)
// @onSuccess (function) success callback
// @onError (function) error callback
// @extraParams (object)
XHR.prototype.post = function(url, data, onSuccess, onError, extraParams) {

	// Debug
	Titanium.API.info(url + " " + JSON.stringify(data));

	// Create some default params
	var onSuccess = onSuccess || function(){};
	var onError = onError || function(){};
	var extraParams = extraParams || {};
	extraParams.async = (extraParams.hasOwnProperty('async')) ? extraParams.async : true;
	extraParams.shouldAuthenticate = extraParams.shouldAuthenticate || false; // if you set this to true, pass "username" and "password" as well
	extraParams.contentType = extraParams.contentType || "application/json";

	// Create the HTTP connection
	var xhr = Titanium.Network.createHTTPClient({
		enableKeepAlive: false
	});
	// Create the result object
	var result = {};

	// Open the HTTP connection
	xhr.open("POST", url, extraParams.async);
	xhr.setRequestHeader('Content-Type', extraParams.contentType);

	// If we need to authenticate
	if (extraParams.shouldAuthenticate) {
		var authstr = 'Basic ' + Titanium.Utils.base64encode(extraParams.username + ':' + extraParams.password);
		xhr.setRequestHeader('Authorization', authstr);
	}

	// When the connection was successful
	xhr.onload = function() {
		// Check the status of this
		result.status = xhr.status == 200 ? "ok" : xhr.status;
		result.data = xhr.responseText;

		onSuccess(result);
	};

	// When there was an error
	xhr.onerror = function(e) {
		// Check the status of this
		result.status = "error";
		result.data = e.error;
		result.code = xhr.status;
		onError(result);
	};

	xhr.send(data);
};

// PUT requests
// @url (string) URL to fetch
// @data (object)
// @onSuccess (function) success callback
// @onError (function) error callback
// @extraParams (object)
XHR.prototype.put = function(url, data, onSuccess, onError, extraParams) {
	// Create some default params
	var onSuccess = onSuccess || function(){};
	var onError = onError || function(){};
	var extraParams = extraParams || {};
	extraParams.async = (extraParams.hasOwnProperty('async')) ? extraParams.async : true;
	extraParams.shouldAuthenticate = extraParams.shouldAuthenticate || false; // if you set this to true, pass "username" and "password" as well
	extraParams.contentType = extraParams.contentType || "application/json";

	// Create the HTTP connection
	var xhr = Titanium.Network.createHTTPClient({
		enableKeepAlive: false
	});
	// Create the result object
	var result = {};

	// Open the HTTP connection
	xhr.open("PUT", url, extraParams.async);
	xhr.setRequestHeader('Content-Type', extraParams.contentType);

	// If we need to authenticate
	if (extraParams.shouldAuthenticate) {
		var authstr = 'Basic ' + Titanium.Utils.base64encode(extraParams.username + ':' + extraParams.password);
		xhr.setRequestHeader('Authorization', authstr);
	}

	// When the connection was successful
	xhr.onload = function() {
		// Check the status of this
		result.status = xhr.status == 200 ? "ok" : xhr.status;
		result.data = xhr.responseText;

		onSuccess(result);
	};

	// When there was an error
	xhr.onerror = function(e) {
		// Check the status of this
		result.status = "error";
		result.data = e.error;
		result.code = xhr.status;
		onError(result);
	};

	xhr.send(data);
};

// DELETE requests
// @url (string) URL to fetch
// @onSuccess (function) success callback
// @onError (function) error callback
// @extraParams (object)
XHR.prototype.destroy = function(url, onSuccess, onError, extraParams) {
	// Create some default params
	var onSuccess = onSuccess || function(){};
	var onError = onError || function(){};
	var extraParams = extraParams || {};
	extraParams.async = (extraParams.hasOwnProperty('async')) ? extraParams.async : true;
	extraParams.shouldAuthenticate = extraParams.shouldAuthenticate || false; // if you set this to true, pass "username" and "password" as well
	extraParams.contentType = extraParams.contentType || "application/json";

	// Create the HTTP connection
	var xhr = Titanium.Network.createHTTPClient({
		enableKeepAlive: false
	});
	// Create the result object
	var result = {};

	// Open the HTTP connection
	xhr.open("DELETE", url, extraParams.async);
	xhr.setRequestHeader('Content-Type', extraParams.contentType);

	// If we need to authenticate
	if (extraParams.shouldAuthenticate) {
		var authstr = 'Basic ' + Titanium.Utils.base64encode(extraParams.username + ':' + extraParams.password);
		xhr.setRequestHeader('Authorization', authstr);
	}

	// When the connection was successful
	xhr.onload = function() {
		// Check the status of this
		result.status = xhr.status == 200 ? "ok" : xhr.status;
		result.data = xhr.responseText;

		onSuccess(result);
	};

	// When there was an error
	xhr.onerror = function(e) {
		// Check the status of this
		result.status = "error";
		result.data = e.error;
		result.code = xhr.status;
		onError(result);
	};

	xhr.send();
};

// Helper functions
// =================

// Removes all the expired documents from the manager and the file system
XHR.prototype.clean = function() {

	var nowInMilliseconds = new Date().getTime();
	var expiredDocuments = 0;

	for (var key in cacheManager) {
		var cache = cacheManager[key];

		if(cache.timestamp <= nowInMilliseconds){
			// Delete references and file
			var file = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, key);
			// Delete the record and file
			delete cacheManager[key];
			file.deleteFile();

			// Update the cache manager
			updateCacheManager();

			// Update the deleted documents count
			expiredDocuments = expiredDocuments + 1;

			//Titanium.API.info("REMOVED CACHE FILE " + cachedDocuments[i].file);
		}

	}

	// Return the number of files deleted
	return expiredDocuments;
};

// Removes all documents from the manager and the file system
XHR.prototype.purge = function() {

	var purgedDocuments = 0;

	for (var key in cacheManager) {
		var cache = cacheManager[key];
		// Delete references and file
		var file = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, key);
		// Delete the record and file
		delete cacheManager[key];
		file.deleteFile();

		// Update the cache manager
		updateCacheManager();

		// Update the deleted documents count
		purgedDocuments = purgedDocuments + 1;

		//Titanium.API.info("REMOVED CACHE FILE " + cachedDocuments[i].file);

	}

	// Return the number of files deleted
	return purgedDocuments;
};

// Private functions
// =================

readCache = function(url) {
	// Hash the URL
	var hashedURL = Titanium.Utils.md5HexDigest(url);

	// Check if the file exists in the manager (append the .dat extension?)
	var cache = cacheManager[hashedURL];
	// Default the return value to false
	var result = false;

	//Titanium.API.info("CHECKING CACHE");

	// If the file was found
	if (cache) {
		// Fetch a reference to the cache file
		var file = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, hashedURL);

		// Check that the TTL is further than the current date
		if (cache.timestamp >= new Date().getTime()) {
			//Titanium.API.info("CACHE FOUND");

			// Return the content of the file
			result = file.read();

		} else {
			//Titanium.API.info("OLD CACHE");

			// Delete the record and file
			delete cacheManager[hashedURL];
			file.deleteFile();

			// Update the cache manager
			updateCacheManager();
		}
	} else {
		//Titanium.API.info("CACHE " + hashedURL + " NOT FOUND");
	}

	return result;
};

updateCacheManager = function(){
	Titanium.App.Properties.setObject("cachedXHRDocuments", cacheManager);
};

writeCache = function(data, url, ttl) {

	//Titanium.API.info("WRITING CACHE");

	// hash the url
	var hashedURL = Titanium.Utils.md5HexDigest(url);

	// Write the file to the disk
	var file = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, hashedURL);

	// Write the file to the disk
	// TODO: There appears to be a bug in Titanium and makes the method
	// below always return false when dealing with binary files
	file.write(data);

	// Insert the cached object in the cache manager
	cacheManager[hashedURL] = { "timestamp": (new Date().getTime()) + (ttl*60*1000) };
	updateCacheManager();

	//Titanium.API.info("WROTE CACHE");
};

// Return everything
module.exports = XHR;<|endoftext|>


<commit_before>"use strict";
var fs = require("fs");
var os = require("os");
var path = require("path");
var isLib = require("./isLib");
var parseURL = require("../basic/parseURL");
var userAgent = "Efront/1.0";
var memery = require("./memery");
var mainLoaderPromise = new Promise(function (ok, oh) {
    fs.readFile(path.join(__dirname, "../basic/loader.js"), function (error, data) {
        if (error) oh(error);
        ok(data.toString());
    });
});
function fromComponent(base) {
    var packer = require("./finalpacker");
    var requestInternet = fromInternet("");
    var request = function (url, onsuccess, onerror) {
        var isdestroied = false;
        if (/^https?\:\/\//i.test(url)) {
            return requestInternet(url, onsuccess, onerror);
        }
        if (/^\/?comm\b/i.test(url)) {
            try {

                var temppath = require.resolve(url.replace(/^\/?comm\b/i, '.').replace(/[\\\$]/g, '/'), { paths: [].concat(memery.coms_path.split(','), ".") })
                if (isLib(temppath)) {
                    var mode = function () {
                        return require(temppath);
                    };
                    mode.file = temppath;
                    onsuccess(mode);
                    return;
                }
            } catch (e) {

            }
        }
        var abort = function () {
            isdestroied = true;
        };
        requestHandles.push(abort);
        var url1 = base.replace(/[^\\\/]*$/, url);
        url1 = url1.replace(/^\/?/, "/");
        packer(url1, function (result) {
            var index = requestHandles.indexOf(abort);
            if (index >= 0) {
                requestHandles.splice(index, 1);
            }
            if (isdestroied) return;
            if (result instanceof Error) {
                onerror(result);
            }
            if (!result) {
                if (!/^comm\//i.test(url)) {
                    console.fail(url);
                    onerror(url);
                } else {
                    url1 = url.replace(/^comm\//i, '');
                    if (global[url1]) {
                        result = function () { return this }.bind(global[url1]);
                    } else {
                        try {
                            url1 = url1.replace(/\$/g, '/');
                            if (/\//.test(url1)) {
                                var parth = path.relative(url1, '.');
                                if (/^\./.test(parth)) {
                                    url1 = "./" + path.relative('.', url1).replace('\\', '/');
                                }

                                var resolved = require.resolve(url1, { paths: [].concat(memery.coms_path.split(','), '.') });
                            } else {
                                var resolved = require.resolve(url1);
                            }
                            if (resolved) {

                                result = function () {
                                    return require(resolved);
                                };
                                result.file = resolved;
                                result.args = [];
                            }
                        } catch (e) {
                            console.fail(e);
                            onerror(url1);
                        }
                    }
                }
            } else {
                result = result.toString();
            }
            onsuccess(result || '');
            require("./watch").close();
        });
    };
    require("./watch").close();
    return request;
}
function fromInternet(mainfilepath) {
    var http = require('http');
    var https = require('https');
    var reg = /^(https?)\:\/\//i;
    function request(url, onsuccess, onerror) {
        if (!reg.test(url)) {
            url = mainfilepath.replace(/\/[^\/]*$/, url.replace(/^\/?/, "/"));
        }
        var _url = parseURL(url);
        var req = /^https?/i.test(_url.protocol) ? https : http;
        var onend = function () {
            var index = requestHandles.indexOf(abort);
            if (index >= 0) {
                requestHandles.splice(index, 1);
            }
        };
        var request = req.request(Object.assign({ method: "get" }, _url), function (res) {
            var result = [];
            var size = 0;
            res.on("data", function (buffer) {
                size += buffer.length;
                result.push(buffer);
            });
            res.once("end", function (event) {
                onend();
                onsuccess(Buffer.concat(result).toString());
            });
            res.once("abort", onend);
            res.once('timeout', function (event) {
                onend();
                onerror(event);
            });
            res.once("error", function (event) {
                onend();
                onerror(event);
            });
        });
        request.end();
        var abort = request.abort.bind(request);
        requestHandles.push(abort);
    }
    return request;
}
var timeoutHandles = {};
var intervalHandles = {};
var requestHandles = [];
function efront() {
    function Storage() { }
    Storage.prototype = {
        getItem() { },
        setItem() { }
    };

    var Window = function () {
    };
    Window.prototype = global;
    var window = new Window;
    Object.assign(window, {
        performance: {},
        require,
        setTimeout(f, timerout) {
            var args = [].slice.call(arguments, 2);
            var handle = setTimeout(function () {
                delete timeoutHandles[handle];
                return f.apply(this, args);
            }, timerout);
            timeoutHandles[handle] = true;
            return handle;
        },
        setInterval(f, timerout) {
            var args = [].slice.call(arguments, 2);
            var handle = setInterval(function () {
                delete intervalHandles[handle];
                return f.apply(this, args);
            }, timerout);
            intervalHandles[handle] = true;
            return handle;
        },
        navigator: {
            userAgent,
            platform: os.platform()
        },
        clearTimeout(handle) {
            delete timeoutHandles[handle];
            return clearTimeout(handle);
        },
        clearInterval(handle) {
            delete intervalHandles[handle];
            return clearInterval(handle);
        },
        document: {
            body: {
                style: {},
                setAttribute() {
                },
                getAttribute() {
                }
            },
            write() {
                console.log.apply(console, arguments);
            }
        },
        localStorage: new Storage,
        sessionStorage: new Storage

    });
    window.top = window.window = window;
    return window;
}
module.exports = function (mainpath, args) {
    mainpath = mainpath.replace(/\.[cm]?[jt]sx?$/i, '');
    var unload = function () {
        Object.keys(intervalHandles).map(clearInterval);
        Object.keys(timeoutHandles).map(clearTimeout);
        requestHandles.slice(0).map(r => r());
    };
    var _mainpath = "./" + mainpath.replace(/\\/g, '/').replace(/^\.\//, '');
    var fullpath = require.resolve(_mainpath, { paths: [].concat(memery.coms_path.split(","), '.') });
    var pathname = path.relative(mainpath.replace(/[^\\\/]+$/, ''), '.');
    pathname = path.join(fullpath, pathname);
    pathname = pathname.replace(/\\/g, '/').replace(/[^\/]+$/, '');
    var location = Object.freeze({
        pathname,
        reload() {
            unload();
            var window = efront();
            var getLoader;
            if (/^https?\:\/\//i.test(mainpath)) {
                getLoader = fromInternet.bind(window, mainpath);
            } else {
                getLoader = fromComponent.bind(window, '/');
            }
            window.request = getLoader();
            window.location = location;
            window.startPath = mainpath.replace(/^\.[\/\\]/, '');
            window.process = Object.create(process);
            Object.assign(window.process, {
                argv: args
            });
            mainLoaderPromise.then(function (loader) {
                new Function(loader).call(window);
            }).catch(function (e) {
                console.log(e);
                console.error("启动失败");
            });
        }
    });
    location.reload();
};<commit_msg>解决带反斜杠的路径无法使用run命令启动的问题<commit_after>"use strict";
var fs = require("fs");
var os = require("os");
var path = require("path");
var isLib = require("./isLib");
var parseURL = require("../basic/parseURL");
var userAgent = "Efront/1.0";
var memery = require("./memery");
var mainLoaderPromise = new Promise(function (ok, oh) {
    fs.readFile(path.join(__dirname, "../basic/loader.js"), function (error, data) {
        if (error) oh(error);
        ok(data.toString());
    });
});
function fromComponent(base) {
    var packer = require("./finalpacker");
    var requestInternet = fromInternet("");
    var request = function (url, onsuccess, onerror) {
        var isdestroied = false;
        if (/^https?\:\/\//i.test(url)) {
            return requestInternet(url, onsuccess, onerror);
        }
        if (/^\/?comm\b/i.test(url)) {
            try {

                var temppath = require.resolve(url.replace(/^\/?comm\b/i, '.').replace(/[\\\$]/g, '/'), { paths: [].concat(memery.coms_path.split(','), ".") })
                if (isLib(temppath)) {
                    var mode = function () {
                        return require(temppath);
                    };
                    mode.file = temppath;
                    onsuccess(mode);
                    return;
                }
            } catch (e) {

            }
        }
        var abort = function () {
            isdestroied = true;
        };
        requestHandles.push(abort);
        var url1 = base.replace(/[^\\\/]*$/, url);
        url1 = url1.replace(/^\/?/, "/");
        packer(url1, function (result) {
            var index = requestHandles.indexOf(abort);
            if (index >= 0) {
                requestHandles.splice(index, 1);
            }
            if (isdestroied) return;
            if (result instanceof Error) {
                onerror(result);
            }
            if (!result) {
                if (!/^comm\//i.test(url)) {
                    console.fail(url);
                    onerror(url);
                } else {
                    url1 = url.replace(/^comm\//i, '');
                    if (global[url1]) {
                        result = function () { return this }.bind(global[url1]);
                    } else {
                        try {
                            url1 = url1.replace(/\$/g, '/');
                            if (/\//.test(url1)) {
                                var parth = path.relative(url1, '.');
                                if (/^\./.test(parth)) {
                                    url1 = "./" + path.relative('.', url1).replace('\\', '/');
                                }

                                var resolved = require.resolve(url1, { paths: [].concat(memery.coms_path.split(','), '.') });
                            } else {
                                var resolved = require.resolve(url1);
                            }
                            if (resolved) {

                                result = function () {
                                    return require(resolved);
                                };
                                result.file = resolved;
                                result.args = [];
                            }
                        } catch (e) {
                            console.fail(e);
                            onerror(url1);
                        }
                    }
                }
            } else {
                result = result.toString();
            }
            onsuccess(result || '');
            require("./watch").close();
        });
    };
    require("./watch").close();
    return request;
}
function fromInternet(mainfilepath) {
    var http = require('http');
    var https = require('https');
    var reg = /^(https?)\:\/\//i;
    function request(url, onsuccess, onerror) {
        if (!reg.test(url)) {
            url = mainfilepath.replace(/\/[^\/]*$/, url.replace(/^\/?/, "/"));
        }
        var _url = parseURL(url);
        var req = /^https?/i.test(_url.protocol) ? https : http;
        var onend = function () {
            var index = requestHandles.indexOf(abort);
            if (index >= 0) {
                requestHandles.splice(index, 1);
            }
        };
        var request = req.request(Object.assign({ method: "get" }, _url), function (res) {
            var result = [];
            var size = 0;
            res.on("data", function (buffer) {
                size += buffer.length;
                result.push(buffer);
            });
            res.once("end", function (event) {
                onend();
                onsuccess(Buffer.concat(result).toString());
            });
            res.once("abort", onend);
            res.once('timeout', function (event) {
                onend();
                onerror(event);
            });
            res.once("error", function (event) {
                onend();
                onerror(event);
            });
        });
        request.end();
        var abort = request.abort.bind(request);
        requestHandles.push(abort);
    }
    return request;
}
var timeoutHandles = {};
var intervalHandles = {};
var requestHandles = [];
function efront() {
    function Storage() { }
    Storage.prototype = {
        getItem() { },
        setItem() { }
    };

    var Window = function () {
    };
    Window.prototype = global;
    var window = new Window;
    Object.assign(window, {
        performance: {},
        require,
        setTimeout(f, timerout) {
            var args = [].slice.call(arguments, 2);
            var handle = setTimeout(function () {
                delete timeoutHandles[handle];
                return f.apply(this, args);
            }, timerout);
            timeoutHandles[handle] = true;
            return handle;
        },
        setInterval(f, timerout) {
            var args = [].slice.call(arguments, 2);
            var handle = setInterval(function () {
                delete intervalHandles[handle];
                return f.apply(this, args);
            }, timerout);
            intervalHandles[handle] = true;
            return handle;
        },
        navigator: {
            userAgent,
            platform: os.platform()
        },
        clearTimeout(handle) {
            delete timeoutHandles[handle];
            return clearTimeout(handle);
        },
        clearInterval(handle) {
            delete intervalHandles[handle];
            return clearInterval(handle);
        },
        document: {
            body: {
                style: {},
                setAttribute() {
                },
                getAttribute() {
                }
            },
            write() {
                console.log.apply(console, arguments);
            }
        },
        localStorage: new Storage,
        sessionStorage: new Storage

    });
    window.top = window.window = window;
    return window;
}
module.exports = function (mainpath, args) {
    mainpath = mainpath.replace(/\.[cm]?[jt]sx?$/i, '');
    var unload = function () {
        Object.keys(intervalHandles).map(clearInterval);
        Object.keys(timeoutHandles).map(clearTimeout);
        requestHandles.slice(0).map(r => r());
    };
    var _mainpath = "./" + mainpath.replace(/\\/g, '/').replace(/^\.\//, '');
    var fullpath = require.resolve(_mainpath, { paths: [].concat(memery.coms_path.split(","), '.') });
    var pathname = path.relative(mainpath.replace(/[^\\\/]+$/, ''), '.');
    pathname = path.join(fullpath, pathname);
    pathname = pathname.replace(/\\/g, '/').replace(/[^\/]+$/, '');
    var location = Object.freeze({
        pathname,
        reload() {
            unload();
            var window = efront();
            var getLoader;
            if (/^https?\:\/\//i.test(mainpath)) {
                getLoader = fromInternet.bind(window, mainpath);
            } else {
                getLoader = fromComponent.bind(window, '/');
            }
            window.request = getLoader();
            window.location = location;
            window.startPath = _mainpath.replace(/^\.[\/\\]/, '');
            window.process = Object.create(process);
            Object.assign(window.process, {
                argv: args
            });
            mainLoaderPromise.then(function (loader) {
                new Function(loader).call(window);
            }).catch(function (e) {
                console.log(e);
                console.error("启动失败");
            });
        }
    });
    location.reload();
};<|endoftext|>