<commit_before>"use strict";

var expect = require("chai").expect;
var fs = require("fs");
var Index = require('../index.js');
var index = new Index();
var stage_dir = index.stage_dir;
var Octokit = require("@octokit/rest");
var octokit = Octokit();
var sinon = require('sinon')
var reset_index = function(index_string_ref) {
	delete require.cache[require.resolve(index_string_ref)];
	return require(index_string_ref);
};

var sandbox = sinon.createSandbox();

var reset_mocks = function() {
	sandbox.restore();
	process.env.NODE_PRE_GYP_GITHUB_TOKEN = "secret";
	fs = reset_index('fs');
	fs.readFileSync = function(){return '{"name":"test","version":"0.0.1","repository": {"url":"git+https://github.com/test/test.git"},"binary":{"host":"https://github.com/test/test/releases/download/","remote_path":"{version}"}}';};
	index.stage_dir = stage_dir;
	Index.prototype.octokit = function() {return octokit;};
	sandbox.stub(octokit, 'authenticate');
	sandbox.stub(octokit.repos, 'getReleases').callsFake(function(options, cb){
		cb(null, {data: [{"tag_name":"0.0.0","assets":[{"name":"filename"}]}]});
	});
	sandbox.stub(octokit.repos, 'createRelease').callsFake(function(options, cb){
		cb(null,{data: {"tag_name":"0.0.1","draft":true,"assets":[{}]}});
	});
	sandbox.stub(octokit.repos, 'uploadAsset').callsFake(function(cfg,cb){cb();});
};

if(!process.env.COVERALLS_SERVICE_NAME) console.log('To post to coveralls.io, be sure to set COVERALLS_SERVICE_NAME environment variable');
if(!process.env.COVERALLS_REPO_TOKEN) console.log('To post to coveralls.io, be sure to set COVERALLS_REPO_TOKEN environment variable');

describe("Publishes packages to GitHub Releases", function() {

	describe("Publishes without an error under all options", function() {

		it("should publish without error in all scenarios", function() {
			var log = console.log;
			reset_mocks();
			fs.readdir = function(filename, cb) {
				cb(null,["filename"]);
			};
	    	fs.statSync = function() {return 0;}
			console.log = function() {};

			// testing scenario when a release already exists
			expect(function(){ index.publish(); }).to.not.throw();
			expect(function(){ index.publish({'draft': false, 'verbose': false}); }).to.not.throw();
			expect(function(){ index.publish({'draft': false, 'verbose': true}); }).to.not.throw();
			expect(function(){ index.publish({'draft': true, 'verbose': false}); }).to.not.throw();
			expect(function(){ index.publish({'draft': true, 'verbose': true}); }).to.not.throw();

			// testing scenario when a release does not already exist
			octokit.repos.getReleases = function(options, cb){
				cb(null,{data: []});
			};
			octokit.repos.createRelease = function(options, cb){
				cb(null, { data: { draft: false} });
			};
			expect(function(){ index.publish(); }).to.not.throw();
			expect(function(){ index.publish({'draft': false, 'verbose': false}); }).to.not.throw();
			expect(function(){ index.publish({'draft': false, 'verbose': true}); }).to.not.throw();
			octokit.repos.createRelease = function(options, cb){
				cb(null, { data: { draft: true} });
			};
			expect(function(){ index.publish({'draft': true, 'verbose': false}); }).to.not.throw();
			expect(function(){ index.publish({'draft': true, 'verbose': true}); }).to.not.throw();
			fs.readFileSync = function(){return '{"version":"0.0.1","repository": {"url":"git+https://github.com/test/test.git"},"binary":{"host":"https://github.com/test/test/releases/download/","remote_path":"{version}"}}';};
			expect(function(){ index.publish(); }).to.not.throw();
			console.log = log;
		});

	});

	describe("Throws an error when node-pre-gyp-github is not configured properly", function() {

		it("should throw an error when missing repository.url in package.json", function() {
			var options = {'draft': true, 'verbose': false};
			reset_mocks();
			fs.readFileSync = function(){return '{}';};
			expect(function(){ index.publish(options); }).to.throw("Missing repository.url in package.json");
		});

		it("should throw an error when a correctly formatted GitHub repository.url is not found in package.json", function() {
			var options = {'draft': true, 'verbose': false};
			reset_mocks();
			fs.readFileSync = function(){return '{"repository": {"url":"bad_format_url"}}';};
			expect(function(){ index.publish(options); }).to.throw("A correctly formatted GitHub repository.url was not found within package.json");
		});

		it("should throw an error when missing binary.host in package.json", function() {
			var options = {'draft': true, 'verbose': false};
			reset_mocks();
			fs.readFileSync = function(){return '{"repository": {"url":"git+https://github.com/test/test.git"}}';};
			expect(function(){ index.publish(options); }).to.throw("Missing binary.host in package.json");
		});

		it("should throw an error when binary.host does not begin with the correct url", function() {
			var options = {'draft': true, 'verbose': false};
			reset_mocks();
			fs.readFileSync = function(){return '{"repository": {"url":"git+https://github.com/test/test.git"},"binary":{"host":"bad_format_binary"}}';};
			expect(function(){ index.publish(options); }).to.throw(/^binary.host in package.json should begin with:/i);
		});

		it("should throw an error when the NODE_PRE_GYP_GITHUB_TOKEN environment variable is not found", function() {
			var options = {'draft': true, 'verbose': false};
			reset_mocks();
			process.env.NODE_PRE_GYP_GITHUB_TOKEN = "";
			expect(function(){ index.publish(options); }).to.throw("NODE_PRE_GYP_GITHUB_TOKEN environment variable not found");
		});

		it("should throw an error when octokit.repos.getReleases returns an error", function() {
			var options = {'draft': true, 'verbose': false};
			reset_mocks();

			octokit.repos.getReleases.restore();
      		sandbox.stub(octokit.repos, 'getReleases').callsFake(function(options, cb){
				cb(new Error('getReleases error'));
			});
			expect(function(){ index.publish(options); }).to.throw('getReleases error');
		});

		it("should throw an error when octokit.repos.createRelease returns an error", function() {
			var options = {'draft': true, 'verbose': false};
			reset_mocks();
			octokit.repos.getReleases = function(options, cb){
				cb(null,{data: []});
			};
			octokit.repos.createRelease = function(options, cb){
				cb(new Error('createRelease error'));
			};
			expect(function(){ index.publish(options); }).to.throw('createRelease error');
		});

		it("should throw an error when the stage directory structure is missing", function() {
			var options = {'draft': true, 'verbose': false};
			reset_mocks();
			fs.readdir = function(filename, cb) {
				cb(new Error('readdir Error'));
			};
			expect(function(){ index.publish(options); }).to.throw('readdir Error');
		});

		it("should throw an error when there are no files found within the stage directory", function() {
			var options = {'draft': true, 'verbose': false};
			reset_mocks();
			fs.readdir = function(filename, cb) {
				cb(null,[]);
			};
			expect(function(){ index.publish(options); }).to.throw(/^No files found within the stage directory:/i);
		});

		it("should throw an error when a staged file already exists in the current release", function() {
			var options = {'draft': true, 'verbose': false};
			reset_mocks();
			fs.readdir = function(filename, cb) {
				cb(null,["filename"]);
			};
			octokit.repos.getReleases = function(options, cb){
				cb(null, {data: [{"tag_name":"0.0.1","assets":[{"name":"filename"}]}]});
			};
			expect(function(){ index.publish(options); }).to.throw(/^Staged file .* found but it already exists in release .*. If you would like to replace it, you must first manually delete it within GitHub./i);
		});

		it("should throw an error when github.releases.uploadAsset returns an error", function() {
			var options = {'draft': true, 'verbose': false};
			reset_mocks();
			fs.readdir = function(filename, cb) {
				cb(null,["filename"]);
			};
			octokit.repos.uploadAsset = function(cfg,cb){
				cb(new Error('uploadAsset error'));
			};
			expect(function(){ index.publish(options); }).to.throw("uploadAsset error");
		});

	});

	describe("Verify backwords compatible with any breaking changes made within the same MINOR version.", function() {

		it("should publish even when package.json's binary.remote_path property is not provided and instead the version is hard coded within binary.host", function() {
			var options = {'draft': false, 'verbose': false};
			reset_mocks();
			fs.readFileSync = function(){return '{"name":"test","version":"0.0.1","repository": {"url":"git+https://github.com/test/test.git"},"binary":{"host":"https://github.com/test/test/releases/download/0.0.1"}}';};
			fs.readdir = function(filename, cb) {
				cb(null,["filename"]);
			};
      		fs.statSync = function() {return 0;}
			octokit.reposcreateRelease = function(options, cb){
				cb(null,{data: {"tag_name":"0.0.1","draft":false,"assets":[{}]}});
			};
			expect(function(){ index.publish(options); }).to.not.throw();
		});

	});
});
<commit_msg>Removed trailing spaces<commit_after>"use strict";

var expect = require("chai").expect;
var fs = require("fs");
var Index = require('../index.js');
var index = new Index();
var stage_dir = index.stage_dir;
var Octokit = require("@octokit/rest");
var octokit = Octokit();
var sinon = require('sinon')
var reset_index = function(index_string_ref) {
	delete require.cache[require.resolve(index_string_ref)];
	return require(index_string_ref);
};

var sandbox = sinon.createSandbox();

var reset_mocks = function() {
	sandbox.restore();
	process.env.NODE_PRE_GYP_GITHUB_TOKEN = "secret";
	fs = reset_index('fs');
	fs.readFileSync = function(){return '{"name":"test","version":"0.0.1","repository": {"url":"git+https://github.com/test/test.git"},"binary":{"host":"https://github.com/test/test/releases/download/","remote_path":"{version}"}}';};
	index.stage_dir = stage_dir;
	Index.prototype.octokit = function() {return octokit;};
	sandbox.stub(octokit, 'authenticate');
	sandbox.stub(octokit.repos, 'getReleases').callsFake(function(options, cb){
		cb(null, {data: [{"tag_name":"0.0.0","assets":[{"name":"filename"}]}]});
	});
	sandbox.stub(octokit.repos, 'createRelease').callsFake(function(options, cb){
		cb(null,{data: {"tag_name":"0.0.1","draft":true,"assets":[{}]}});
	});
	sandbox.stub(octokit.repos, 'uploadAsset').callsFake(function(cfg,cb){cb();});
};

if(!process.env.COVERALLS_SERVICE_NAME) console.log('To post to coveralls.io, be sure to set COVERALLS_SERVICE_NAME environment variable');
if(!process.env.COVERALLS_REPO_TOKEN) console.log('To post to coveralls.io, be sure to set COVERALLS_REPO_TOKEN environment variable');

describe("Publishes packages to GitHub Releases", function() {
	describe("Publishes without an error under all options", function() {
		it("should publish without error in all scenarios", function() {
			var log = console.log;
			reset_mocks();
			fs.readdir = function(filename, cb) {
				cb(null,["filename"]);
			};
	    	fs.statSync = function() {return 0;}
			console.log = function() {};

			// testing scenario when a release already exists
			expect(function(){ index.publish(); }).to.not.throw();
			expect(function(){ index.publish({'draft': false, 'verbose': false}); }).to.not.throw();
			expect(function(){ index.publish({'draft': false, 'verbose': true}); }).to.not.throw();
			expect(function(){ index.publish({'draft': true, 'verbose': false}); }).to.not.throw();
			expect(function(){ index.publish({'draft': true, 'verbose': true}); }).to.not.throw();

			// testing scenario when a release does not already exist
			octokit.repos.getReleases = function(options, cb){
				cb(null,{data: []});
			};
			octokit.repos.createRelease = function(options, cb){
				cb(null, { data: { draft: false} });
			};
			expect(function(){ index.publish(); }).to.not.throw();
			expect(function(){ index.publish({'draft': false, 'verbose': false}); }).to.not.throw();
			expect(function(){ index.publish({'draft': false, 'verbose': true}); }).to.not.throw();
			octokit.repos.createRelease = function(options, cb){
				cb(null, { data: { draft: true} });
			};
			expect(function(){ index.publish({'draft': true, 'verbose': false}); }).to.not.throw();
			expect(function(){ index.publish({'draft': true, 'verbose': true}); }).to.not.throw();
			fs.readFileSync = function(){return '{"version":"0.0.1","repository": {"url":"git+https://github.com/test/test.git"},"binary":{"host":"https://github.com/test/test/releases/download/","remote_path":"{version}"}}';};
			expect(function(){ index.publish(); }).to.not.throw();
			console.log = log;
		});
	});

	describe("Throws an error when node-pre-gyp-github is not configured properly", function() {
		it("should throw an error when missing repository.url in package.json", function() {
			var options = {'draft': true, 'verbose': false};
			reset_mocks();
			fs.readFileSync = function(){return '{}';};
			expect(function(){ index.publish(options); }).to.throw("Missing repository.url in package.json");
		});

		it("should throw an error when a correctly formatted GitHub repository.url is not found in package.json", function() {
			var options = {'draft': true, 'verbose': false};
			reset_mocks();
			fs.readFileSync = function(){return '{"repository": {"url":"bad_format_url"}}';};
			expect(function(){ index.publish(options); }).to.throw("A correctly formatted GitHub repository.url was not found within package.json");
		});

		it("should throw an error when missing binary.host in package.json", function() {
			var options = {'draft': true, 'verbose': false};
			reset_mocks();
			fs.readFileSync = function(){return '{"repository": {"url":"git+https://github.com/test/test.git"}}';};
			expect(function(){ index.publish(options); }).to.throw("Missing binary.host in package.json");
		});

		it("should throw an error when binary.host does not begin with the correct url", function() {
			var options = {'draft': true, 'verbose': false};
			reset_mocks();
			fs.readFileSync = function(){return '{"repository": {"url":"git+https://github.com/test/test.git"},"binary":{"host":"bad_format_binary"}}';};
			expect(function(){ index.publish(options); }).to.throw(/^binary.host in package.json should begin with:/i);
		});

		it("should throw an error when the NODE_PRE_GYP_GITHUB_TOKEN environment variable is not found", function() {
			var options = {'draft': true, 'verbose': false};
			reset_mocks();
			process.env.NODE_PRE_GYP_GITHUB_TOKEN = "";
			expect(function(){ index.publish(options); }).to.throw("NODE_PRE_GYP_GITHUB_TOKEN environment variable not found");
		});

		it("should throw an error when octokit.repos.getReleases returns an error", function() {
			var options = {'draft': true, 'verbose': false};
			reset_mocks();

			octokit.repos.getReleases.restore();
      		sandbox.stub(octokit.repos, 'getReleases').callsFake(function(options, cb){
				cb(new Error('getReleases error'));
			});
			expect(function(){ index.publish(options); }).to.throw('getReleases error');
		});

		it("should throw an error when octokit.repos.createRelease returns an error", function() {
			var options = {'draft': true, 'verbose': false};
			reset_mocks();
			octokit.repos.getReleases = function(options, cb){
				cb(null,{data: []});
			};
			octokit.repos.createRelease = function(options, cb){
				cb(new Error('createRelease error'));
			};
			expect(function(){ index.publish(options); }).to.throw('createRelease error');
		});

		it("should throw an error when the stage directory structure is missing", function() {
			var options = {'draft': true, 'verbose': false};
			reset_mocks();
			fs.readdir = function(filename, cb) {
				cb(new Error('readdir Error'));
			};
			expect(function(){ index.publish(options); }).to.throw('readdir Error');
		});

		it("should throw an error when there are no files found within the stage directory", function() {
			var options = {'draft': true, 'verbose': false};
			reset_mocks();
			fs.readdir = function(filename, cb) {
				cb(null,[]);
			};
			expect(function(){ index.publish(options); }).to.throw(/^No files found within the stage directory:/i);
		});

		it("should throw an error when a staged file already exists in the current release", function() {
			var options = {'draft': true, 'verbose': false};
			reset_mocks();
			fs.readdir = function(filename, cb) {
				cb(null,["filename"]);
			};
			octokit.repos.getReleases = function(options, cb){
				cb(null, {data: [{"tag_name":"0.0.1","assets":[{"name":"filename"}]}]});
			};
			expect(function(){ index.publish(options); }).to.throw(/^Staged file .* found but it already exists in release .*. If you would like to replace it, you must first manually delete it within GitHub./i);
		});

		it("should throw an error when github.releases.uploadAsset returns an error", function() {
			var options = {'draft': true, 'verbose': false};
			reset_mocks();
			fs.readdir = function(filename, cb) {
				cb(null,["filename"]);
			};
			octokit.repos.uploadAsset = function(cfg,cb){
				cb(new Error('uploadAsset error'));
			};
			expect(function(){ index.publish(options); }).to.throw("uploadAsset error");
		});
	});

	describe("Verify backwords compatible with any breaking changes made within the same MINOR version.", function() {
		it("should publish even when package.json's binary.remote_path property is not provided and instead the version is hard coded within binary.host", function() {
			var options = {'draft': false, 'verbose': false};
			reset_mocks();
			fs.readFileSync = function(){return '{"name":"test","version":"0.0.1","repository": {"url":"git+https://github.com/test/test.git"},"binary":{"host":"https://github.com/test/test/releases/download/0.0.1"}}';};
			fs.readdir = function(filename, cb) {
				cb(null,["filename"]);
			};
      		fs.statSync = function() {return 0;}
			octokit.reposcreateRelease = function(options, cb){
				cb(null,{data: {"tag_name":"0.0.1","draft":false,"assets":[{}]}});
			};
			expect(function(){ index.publish(options); }).to.not.throw();
		});
	});
});
<|endoftext|>


<commit_before>'use strict';

var browserify_express = require('browserify-express');

function bundle() {
  return browserify_express({
    entry: __dirname + '/bundle.source.js',
    watch: [__dirname + '../lib/', __dirname + '/bundle.source.js'],
    mount: '/public/js/bundle.js',
    verbose: true,
    //minify: true,
    bundle_opts: { debug: true }, // enable inline sourcemap on js files
    write_file: __dirname + '/bundle.out.js'
  });
}

module.exports = bundle;<commit_msg>fix browserify-express watch path, thanks @sulkaharo<commit_after>'use strict';

var browserify_express = require('browserify-express');

function bundle() {
  return browserify_express({
    entry: __dirname + '/bundle.source.js',
    watch: __dirname + '/../lib/',
    mount: '/public/js/bundle.js',
    verbose: true,
    //minify: true,
    bundle_opts: { debug: true }, // enable inline sourcemap on js files
    write_file: __dirname + '/bundle.out.js'
  });
}

module.exports = bundle;<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview DevTools' implementation of the InspectorController API.
 */
goog.require('devtools.InspectorController');

goog.provide('devtools.InspectorControllerImpl');

devtools.InspectorControllerImpl = function() {
  devtools.InspectorController.call(this);
  this.frame_element_id_ = 1;

  this.installInspectorControllerDelegate_('clearMessages');
  this.installInspectorControllerDelegate_('storeLastActivePanel');
  this.installInspectorControllerDelegate_('highlightDOMNode');
  this.installInspectorControllerDelegate_('hideDOMNodeHighlight');
  this.installInspectorControllerDelegate_('getChildNodes');
  this.installInspectorControllerDelegate_('setAttribute');
  this.installInspectorControllerDelegate_('removeAttribute');
  this.installInspectorControllerDelegate_('setTextNodeValue');
  this.installInspectorControllerDelegate_('enableResourceTracking');
  this.installInspectorControllerDelegate_('disableResourceTracking');
  this.installInspectorControllerDelegate_('enableTimeline');
  this.installInspectorControllerDelegate_('disableTimeline');

  //TODO: nuke with the next WebKit roll.
  this.installInjectedScriptDelegate_('getStyles');
  this.installInjectedScriptDelegate_('getComputedStyle');
  this.installInjectedScriptDelegate_('getInlineStyle');
  this.installInjectedScriptDelegate_('applyStyleText');
  this.installInjectedScriptDelegate_('setStyleText');
  this.installInjectedScriptDelegate_('toggleStyleEnabled');
  this.installInjectedScriptDelegate_('applyStyleRuleText');
  this.installInjectedScriptDelegate_('addStyleSelector');
  this.installInjectedScriptDelegate_('setStyleProperty');
  this.installInjectedScriptDelegate_('getPrototypes');
  this.installInjectedScriptDelegate_('setPropertyValue');
  this.installInjectedScriptDelegate_('evaluate');
  this.installInjectedScriptDelegate_('addInspectedNode');
  this.installInjectedScriptDelegate_('pushNodeToFrontend');
  this.installInjectedScriptDelegate_('performSearch');
  this.installInjectedScriptDelegate_('searchCanceled');
  this.installInjectedScriptDelegate_('openInInspectedWindow');
};
goog.inherits(devtools.InspectorControllerImpl,
    devtools.InspectorController);

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.platform = function() {
  return DevToolsHost.getPlatform();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.closeWindow = function() {
  DevToolsHost.closeWindow();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.attach = function() {
  DevToolsHost.dockWindow();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.detach = function() {
  DevToolsHost.undockWindow();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.hiddenPanels = function() {
  return 'databases';
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.search = function(sourceRow, query) {
  return DevToolsHost.search(sourceRow, query);
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.toggleNodeSearch = function() {
  devtools.InspectorController.prototype.toggleNodeSearch.call(this);
  DevToolsHost.toggleInspectElementMode(this.searchingForNode());
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.localizedStringsURL =
    function(opt_prefix) {
  // l10n is turned off in test mode because delayed loading of strings
  // causes test failures.
  if (false) {
    var locale = DevToolsHost.getApplicationLocale();
    locale = locale.replace('_', '-');
    return 'l10n/localizedStrings_' + locale + '.js';
  } else {
    return undefined;
  }
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.addSourceToFrame =
    function(mimeType, source, element) {
  return DevToolsHost.addSourceToFrame(mimeType, source, element);
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.addResourceSourceToFrame =
    function(identifier, element) {
  var resource = WebInspector.resources[identifier];
  if (!resource) {
    return;
  }
  DevToolsHost.addResourceSourceToFrame(identifier, resource.mimeType, element);
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.inspectedWindow = function() {
  return null;
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.debuggerEnabled = function() {
  return true;
};

devtools.InspectorControllerImpl.prototype.addBreakpoint = function(
    sourceID, line, condition) {
  devtools.tools.getDebuggerAgent().addBreakpoint(sourceID, line, condition);
};

devtools.InspectorControllerImpl.prototype.removeBreakpoint = function(
    sourceID, line) {
  devtools.tools.getDebuggerAgent().removeBreakpoint(sourceID, line);
};

devtools.InspectorControllerImpl.prototype.updateBreakpoint = function(
    sourceID, line, condition) {
  devtools.tools.getDebuggerAgent().updateBreakpoint(
      sourceID, line, condition);
};

devtools.InspectorControllerImpl.prototype.pauseInDebugger = function() {
  devtools.tools.getDebuggerAgent().pauseExecution();
};

devtools.InspectorControllerImpl.prototype.resumeDebugger = function() {
  devtools.tools.getDebuggerAgent().resumeExecution();
};

devtools.InspectorControllerImpl.prototype.stepIntoStatementInDebugger =
    function() {
  devtools.tools.getDebuggerAgent().stepIntoStatement();
};

devtools.InspectorControllerImpl.prototype.stepOutOfFunctionInDebugger =
    function() {
  devtools.tools.getDebuggerAgent().stepOutOfFunction();
};

devtools.InspectorControllerImpl.prototype.stepOverStatementInDebugger =
    function() {
  devtools.tools.getDebuggerAgent().stepOverStatement();
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.pauseOnExceptions = function() {
  return devtools.tools.getDebuggerAgent().pauseOnExceptions();
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.setPauseOnExceptions = function(
    value) {
  return devtools.tools.getDebuggerAgent().setPauseOnExceptions(value);
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.startProfiling = function() {
  devtools.tools.getDebuggerAgent().startProfiling(
      devtools.DebuggerAgent.ProfilerModules.PROFILER_MODULE_CPU);
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.stopProfiling = function() {
  devtools.tools.getDebuggerAgent().stopProfiling(
      devtools.DebuggerAgent.ProfilerModules.PROFILER_MODULE_CPU);
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.evaluateInCallFrame =
    function(callFrameId, code, callback) {
  devtools.tools.getDebuggerAgent().evaluateInCallFrame(callFrameId, code,
                                                        callback);
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.getProperties = function(
    objectProxy, ignoreHasOwnProperty, callback) {
  if (objectProxy.isScope) {
    devtools.tools.getDebuggerAgent().resolveScope(objectProxy.objectId,
        callback);
  } else if (objectProxy.isV8Ref) {
    devtools.tools.getDebuggerAgent().resolveChildren(objectProxy.objectId,
        callback, true);
  } else {
    this.callInjectedScript_('getProperties', objectProxy,
        ignoreHasOwnProperty, callback);
  }
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.dispatchOnInjectedScript = function(
    callId, methodName, argsString) {
  var callback = function(result, isException) {
    WebInspector.didDispatchOnInjectedScript(callId,
        isException ? result : JSON.parse(result),
        isException);
  };
  RemoteToolsAgent.ExecuteUtilityFunction(
      devtools.Callback.wrap(callback),
      'InjectedScript',
      JSON.stringify(['dispatch', methodName, argsString]));
};

/**
 * TODO: nuke with the next WebKit roll.
 * Installs delegating handler into the inspector controller.
 * @param {string} methodName Method to install delegating handler for.
 */
devtools.InspectorControllerImpl.prototype.installInjectedScriptDelegate_ =
    function(methodName) {
  this[methodName] = goog.bind(this.callInjectedScript_, this,
      methodName);
};

/**
 * TODO: nuke with the next WebKit roll.
 * Bound function with the installInjectedScriptDelegate_ actual
 * implementation.
 */
devtools.InspectorControllerImpl.prototype.callInjectedScript_ =
    function(methodName, var_arg) {
  var allArgs = Array.prototype.slice.call(arguments);
  var callback = allArgs[allArgs.length - 1];
  var args = Array.prototype.slice.call(allArgs, 0, allArgs.length - 1);
  RemoteToolsAgent.ExecuteUtilityFunction(
      devtools.InspectorControllerImpl.parseWrap_(callback),
      'InjectedScript', JSON.stringify(args));
};

/**
 * Installs delegating handler into the inspector controller.
 * @param {string} methodName Method to install delegating handler for.
 */
devtools.InspectorControllerImpl.prototype.installInspectorControllerDelegate_
    = function(methodName) {
  this[methodName] = goog.bind(this.callInspectorController_, this,
      methodName);
};

/**
 * Bound function with the installInjectedScriptDelegate_ actual
 * implementation.
 */
devtools.InspectorControllerImpl.prototype.callInspectorController_ =
    function(methodName, var_arg) {
  var args = Array.prototype.slice.call(arguments);
  RemoteToolsAgent.ExecuteUtilityFunction(
      devtools.Callback.wrap(function(){}),
      'InspectorController', JSON.stringify(args));
};

devtools.InspectorControllerImpl.parseWrap_ = function(callback) {
  return devtools.Callback.wrap(
      function(data) {
        callback.call(this, JSON.parse(data));
      });
};

InspectorController = new devtools.InspectorControllerImpl();
<commit_msg>DevTools: add setting/setSetting methods to InspectorController in front-end.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview DevTools' implementation of the InspectorController API.
 */
goog.require('devtools.InspectorController');

goog.provide('devtools.InspectorControllerImpl');

devtools.InspectorControllerImpl = function() {
  devtools.InspectorController.call(this);
  this.frame_element_id_ = 1;

  this.installInspectorControllerDelegate_('clearMessages');
  this.installInspectorControllerDelegate_('storeLastActivePanel');
  this.installInspectorControllerDelegate_('highlightDOMNode');
  this.installInspectorControllerDelegate_('hideDOMNodeHighlight');
  this.installInspectorControllerDelegate_('getChildNodes');
  this.installInspectorControllerDelegate_('setAttribute');
  this.installInspectorControllerDelegate_('removeAttribute');
  this.installInspectorControllerDelegate_('setTextNodeValue');
  this.installInspectorControllerDelegate_('enableResourceTracking');
  this.installInspectorControllerDelegate_('disableResourceTracking');
  this.installInspectorControllerDelegate_('enableTimeline');
  this.installInspectorControllerDelegate_('disableTimeline');
  this.installInspectorControllerDelegate_('setting');
  this.installInspectorControllerDelegate_('setSetting');
};
goog.inherits(devtools.InspectorControllerImpl,
    devtools.InspectorController);

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.platform = function() {
  return DevToolsHost.getPlatform();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.closeWindow = function() {
  DevToolsHost.closeWindow();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.attach = function() {
  DevToolsHost.dockWindow();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.detach = function() {
  DevToolsHost.undockWindow();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.hiddenPanels = function() {
  return 'databases';
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.search = function(sourceRow, query) {
  return DevToolsHost.search(sourceRow, query);
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.toggleNodeSearch = function() {
  devtools.InspectorController.prototype.toggleNodeSearch.call(this);
  DevToolsHost.toggleInspectElementMode(this.searchingForNode());
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.localizedStringsURL =
    function(opt_prefix) {
  // l10n is turned off in test mode because delayed loading of strings
  // causes test failures.
  if (false) {
    var locale = DevToolsHost.getApplicationLocale();
    locale = locale.replace('_', '-');
    return 'l10n/localizedStrings_' + locale + '.js';
  } else {
    return undefined;
  }
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.addSourceToFrame =
    function(mimeType, source, element) {
  return DevToolsHost.addSourceToFrame(mimeType, source, element);
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.addResourceSourceToFrame =
    function(identifier, element) {
  var resource = WebInspector.resources[identifier];
  if (!resource) {
    return;
  }
  DevToolsHost.addResourceSourceToFrame(identifier, resource.mimeType, element);
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.inspectedWindow = function() {
  return null;
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.debuggerEnabled = function() {
  return true;
};

devtools.InspectorControllerImpl.prototype.addBreakpoint = function(
    sourceID, line, condition) {
  devtools.tools.getDebuggerAgent().addBreakpoint(sourceID, line, condition);
};

devtools.InspectorControllerImpl.prototype.removeBreakpoint = function(
    sourceID, line) {
  devtools.tools.getDebuggerAgent().removeBreakpoint(sourceID, line);
};

devtools.InspectorControllerImpl.prototype.updateBreakpoint = function(
    sourceID, line, condition) {
  devtools.tools.getDebuggerAgent().updateBreakpoint(
      sourceID, line, condition);
};

devtools.InspectorControllerImpl.prototype.pauseInDebugger = function() {
  devtools.tools.getDebuggerAgent().pauseExecution();
};

devtools.InspectorControllerImpl.prototype.resumeDebugger = function() {
  devtools.tools.getDebuggerAgent().resumeExecution();
};

devtools.InspectorControllerImpl.prototype.stepIntoStatementInDebugger =
    function() {
  devtools.tools.getDebuggerAgent().stepIntoStatement();
};

devtools.InspectorControllerImpl.prototype.stepOutOfFunctionInDebugger =
    function() {
  devtools.tools.getDebuggerAgent().stepOutOfFunction();
};

devtools.InspectorControllerImpl.prototype.stepOverStatementInDebugger =
    function() {
  devtools.tools.getDebuggerAgent().stepOverStatement();
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.pauseOnExceptions = function() {
  return devtools.tools.getDebuggerAgent().pauseOnExceptions();
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.setPauseOnExceptions = function(
    value) {
  return devtools.tools.getDebuggerAgent().setPauseOnExceptions(value);
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.startProfiling = function() {
  devtools.tools.getDebuggerAgent().startProfiling(
      devtools.DebuggerAgent.ProfilerModules.PROFILER_MODULE_CPU);
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.stopProfiling = function() {
  devtools.tools.getDebuggerAgent().stopProfiling(
      devtools.DebuggerAgent.ProfilerModules.PROFILER_MODULE_CPU);
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.evaluateInCallFrame =
    function(callFrameId, code, callback) {
  devtools.tools.getDebuggerAgent().evaluateInCallFrame(callFrameId, code,
                                                        callback);
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.getProperties = function(
    objectProxy, ignoreHasOwnProperty, callback) {
  if (objectProxy.isScope) {
    devtools.tools.getDebuggerAgent().resolveScope(objectProxy.objectId,
        callback);
  } else if (objectProxy.isV8Ref) {
    devtools.tools.getDebuggerAgent().resolveChildren(objectProxy.objectId,
        callback, true);
  } else {
    this.callInjectedScript_('getProperties', objectProxy,
        ignoreHasOwnProperty, callback);
  }
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.dispatchOnInjectedScript = function(
    callId, methodName, argsString) {
  var callback = function(result, isException) {
    WebInspector.didDispatchOnInjectedScript(callId,
        isException ? result : JSON.parse(result),
        isException);
  };
  RemoteToolsAgent.ExecuteUtilityFunction(
      devtools.Callback.wrap(callback),
      'InjectedScript',
      JSON.stringify(['dispatch', methodName, argsString]));
};

/**
 * This method allows calling a methods on InjectedScript object in the
 * inspected page.
 */
devtools.InspectorControllerImpl.prototype.callInjectedScript_ =
    function(methodName, var_arg) {
  var allArgs = Array.prototype.slice.call(arguments);
  var callback = allArgs[allArgs.length - 1];
  var args = Array.prototype.slice.call(allArgs, 0, allArgs.length - 1);
  RemoteToolsAgent.ExecuteUtilityFunction(
      devtools.InspectorControllerImpl.parseWrap_(callback),
      'InjectedScript', JSON.stringify(args));
};

/**
 * Installs delegating handler into the inspector controller.
 * @param {string} methodName Method to install delegating handler for.
 */
devtools.InspectorControllerImpl.prototype.installInspectorControllerDelegate_
    = function(methodName) {
  this[methodName] = goog.bind(this.callInspectorController_, this,
      methodName);
};

/**
 * Bound function with the installInjectedScriptDelegate_ actual
 * implementation.
 */
devtools.InspectorControllerImpl.prototype.callInspectorController_ =
    function(methodName, var_arg) {
  var args = Array.prototype.slice.call(arguments);
  RemoteToolsAgent.ExecuteUtilityFunction(
      devtools.Callback.wrap(function(){}),
      'InspectorController', JSON.stringify(args));
};

devtools.InspectorControllerImpl.parseWrap_ = function(callback) {
  return devtools.Callback.wrap(
      function(data) {
        callback.call(this, JSON.parse(data));
      });
};

InspectorController = new devtools.InspectorControllerImpl();
<|endoftext|>


<commit_before>QUnit.module('OpenCrypto');

QUnit.test("Session Key Generation Test", function(assert) {
  var crypt = new OpenCrypto();
  crypt.getSessionKey().then(function(sessionKey) {
    assert.ok(1 == "1", 'Passed!');
  });
});
<commit_msg>Update OpenCrypto.test.js<commit_after>QUnit.module('OpenCrypto');

QUnit.test( "Password Key Derivation Test", function(assert) {
  assert.ok(1 == "1", "Passed!");
});

/*QUnit.test("Session Key Generation Test", function(assert) {
  crypt.getSessionKey().then(function(sessionKey) {
    assert.ok(1 == "1", 'Passed!');
  });
});*/
<|endoftext|>


<commit_before>'use strict';

const events = require('events');
const http = require('http');
const stream = require('stream');
const util = require('util');
const ws = require('ws');

const debug = util.debuglog('rdbg');

class Console extends stream.Readable {
  constructor(client) {
    super({
      objectMode: true
    });

    client.on('message', (method, params) => {
      if (method === 'Console.messageAdded') {
        this.push(params.message);
      } else if (method === 'Console.messagesCleared') {
        this.emit('clear');
      }
    });

    this._client = client;
  }

  _read() {
  }

  get client() {
    return this._client;
  }

  enable(callback) {
    this.client.request('Console.enable', error => {
      callback(error);
    });
  }

  disable(callback) {
    this.client.request('Console.enable', error => {
      callback(error);
    });
  }
}

module.exports.Console = Console;

class Debugger extends events.EventEmitter {
  constructor(client) {
    super();

    client.on('message', (method, params) => {
      if (method === 'Debugger.scriptParsed') {
        this.emit('scriptParse', params);
      } else if (method === 'Debugger.scriptFailedToParse') {
        this.emit('scriptError', params);
      } else if (method === 'Debugger.globalObjectCleared') {
        this.emit('clear');
      }
    });

    this._client = client;
  }

  get client() {
    return this._client;
  }

  enable(callback) {
    this.client.request('Debugger.enable', function(error) {
      callback(error);
    });
  }

  disable(callback) {
    this.client.request('Debugger.enable', function(error) {
      callback(error);
    });
  }

  pause(callback) {
    this.client.request('Debugger.pause', function(error) {
      callback(error);
    });
  }

  disable(callback) {
    this.client.request('Debugger.disable', function(error) {
      callback(error);
    });
  }

  canSetScriptSource(callback) {
    this.client.request('Debugger.canSetScriptSource', function(error, result) {
      if (error) {
        return callback(error);
      }

      callback(null, result.result);
    });
  }

  getScriptSource(scriptId, callback) {
    this.client.request('Debugger.getScriptSource', {
      scriptId: scriptId,
    }, function(error, result) {
      if (error) {
        return callback(error);
      }

      callback(null, result.scriptSource);
    });
  }

  setScriptSource(scriptId, source, callback) {
    this.client.request('Debugger.setScriptSource', {
      scriptId: scriptId,
      scriptSource: source
    }, callback);
  }
}

module.exports.Debugger = Debugger;

class Runtime extends events.EventEmitter {
  constructor(client) {
    super();

    client.on('message', (method, params) => {
    });

    this._client = client;
  }

  get client() {
    return this._client;
  }

  enable(callback) {
    this.client.request('Runtime.enable', error => {
      return callback(error);
    });
  }

  evaluate(cmd, options, callback) {
    if (typeof options === 'function') {
      callback = options;
      options = undefined;
    }

    this.client.request('Runtime.evaluate', Object.assign({}, {
      expression: cmd,
    }, options), (error, result) => {
      if (error) {
        return callback(error);
      }

      callback(null, result.result, result.wasThrown);
    });
  }
}

module.exports.Runtime = Runtime;

class Client extends events.EventEmitter {
  constructor() {
    super();

    this._counter = 0;
    this._callbacks = {};
    this._commands = {};
    this._socket = null;
  }

  get socket() {
    return this._socket;
  }

  get console() {
    if (!this._console) {
      this._console = new Console(this);
    }

    return this._console;
  }

  get debugger() {
    if (!this._debugger) {
      this._debugger = new Debugger(this);
    }

    return this._debugger;
  }

  get runtime() {
    if (!this._runtime) {
      this._runtime = new Runtime(this);
    }

    return this._runtime;
  }

  request(method, parameters, id, callback) {
    if (typeof parameters === 'function') {
      callback = parameters;
      parameters = undefined;
    }

    if (typeof id === 'function') {
      callback = id;
      id = undefined;
    }

    if (typeof parameters === 'undefined') {
      parameters = {};
    }

    if (typeof id === 'undefined') {
      id = this._counter++;
    }

    var request = {
      id: id,
      method: method,
      params: parameters,
    };

    this._callbacks[id] = callback;
    this._commands[id] = request;

    debug('request %s', util.inspect(request));
    this.emit('request', request);
    this._socket.send(JSON.stringify(request));
  }

  connect(uri, callback) {
    if (callback) {
      this.on('connect', callback);
    }

    let socket = ws.connect(uri);
    socket.once('open', () => {
      debug('connect');
      this.emit('connect');
    });

    socket.on('close', () => {
      debug('close');
      this.emit('close');
    });

    socket.on('error', (error) => {
      debug('error');
      this.emit('error', error);
    });

    socket.on('message', data => {
      try {
        var message = JSON.parse(data);

        if (message.id !== undefined) {
          var command = this._commands[message.id];
          var callback = this._callbacks[message.id];

          debug('response %s, %s', util.inspect(command), util.inspect(message));
          this.emit('response', command, message);

          if (callback) {
            if (message.error) {
              callback(message.error);
            } else {
              callback(null, message.result);
            }

            delete this._callbacks[message.id];
          }

          delete this._commands[message.id];

        } else {
          debug('message %s', util.inspect(message));
          this.emit('message', message.method, message.params);
        }
      } catch (error) {
        this.emit('error', error);
      }
    });

    this._socket = socket;
    this.emit('socket', socket);
  }

  close() {
    if (this.socket) {
      this.socket.close();
    }
  }
}

module.exports.Client = Client;

function connect(uri, callback) {
  var client = new Client();
  if (callback) {
    client.on('connect', callback);
  }

  client.connect(uri);

  return client;
}

module.exports.connect = connect;

function get(port, host, callback) {
  if (typeof host === 'function') {
    callback = host;
    host = undefined;
  }

  if (typeof host == 'undefined') {
    host = 'localhost';
  }

  var request = http.get({
    port: port,
    host: host,
    path: '/json'
  });

  request.on('response', (response) => {
    var data = '';

    response.on('data', (chunk) => {
      data += chunk;
    });

    response.on('end', () => {
      try {
        var targets = JSON.parse(data);
        return callback(null, targets);
      } catch (error) {
        return callback(error);
      }
    });
  });

  request.on('error', (error) => {
    return callback(error);
  });
};

module.exports.get = get;
<commit_msg>lib: deprecate `get` in favor for `list`<commit_after>'use strict';

const events = require('events');
const http = require('http');
const stream = require('stream');
const util = require('util');
const ws = require('ws');

const debug = util.debuglog('rdbg');

class Console extends stream.Readable {
  constructor(client) {
    super({
      objectMode: true
    });

    client.on('message', (method, params) => {
      if (method === 'Console.messageAdded') {
        this.push(params.message);
      } else if (method === 'Console.messagesCleared') {
        this.emit('clear');
      }
    });

    this._client = client;
  }

  _read() {
  }

  get client() {
    return this._client;
  }

  enable(callback) {
    this.client.request('Console.enable', error => {
      callback(error);
    });
  }

  disable(callback) {
    this.client.request('Console.enable', error => {
      callback(error);
    });
  }
}

module.exports.Console = Console;

class Debugger extends events.EventEmitter {
  constructor(client) {
    super();

    client.on('message', (method, params) => {
      if (method === 'Debugger.scriptParsed') {
        this.emit('scriptParse', params);
      } else if (method === 'Debugger.scriptFailedToParse') {
        this.emit('scriptError', params);
      } else if (method === 'Debugger.globalObjectCleared') {
        this.emit('clear');
      }
    });

    this._client = client;
  }

  get client() {
    return this._client;
  }

  enable(callback) {
    this.client.request('Debugger.enable', function(error) {
      callback(error);
    });
  }

  disable(callback) {
    this.client.request('Debugger.enable', function(error) {
      callback(error);
    });
  }

  pause(callback) {
    this.client.request('Debugger.pause', function(error) {
      callback(error);
    });
  }

  disable(callback) {
    this.client.request('Debugger.disable', function(error) {
      callback(error);
    });
  }

  canSetScriptSource(callback) {
    this.client.request('Debugger.canSetScriptSource', function(error, result) {
      if (error) {
        return callback(error);
      }

      callback(null, result.result);
    });
  }

  getScriptSource(scriptId, callback) {
    this.client.request('Debugger.getScriptSource', {
      scriptId: scriptId,
    }, function(error, result) {
      if (error) {
        return callback(error);
      }

      callback(null, result.scriptSource);
    });
  }

  setScriptSource(scriptId, source, callback) {
    this.client.request('Debugger.setScriptSource', {
      scriptId: scriptId,
      scriptSource: source
    }, callback);
  }
}

module.exports.Debugger = Debugger;

class Runtime extends events.EventEmitter {
  constructor(client) {
    super();

    client.on('message', (method, params) => {
    });

    this._client = client;
  }

  get client() {
    return this._client;
  }

  enable(callback) {
    this.client.request('Runtime.enable', error => {
      return callback(error);
    });
  }

  evaluate(cmd, options, callback) {
    if (typeof options === 'function') {
      callback = options;
      options = undefined;
    }

    this.client.request('Runtime.evaluate', Object.assign({}, {
      expression: cmd,
    }, options), (error, result) => {
      if (error) {
        return callback(error);
      }

      callback(null, result.result, result.wasThrown);
    });
  }
}

module.exports.Runtime = Runtime;

class Client extends events.EventEmitter {
  constructor() {
    super();

    this._counter = 0;
    this._callbacks = {};
    this._commands = {};
    this._socket = null;
  }

  get socket() {
    return this._socket;
  }

  get console() {
    if (!this._console) {
      this._console = new Console(this);
    }

    return this._console;
  }

  get debugger() {
    if (!this._debugger) {
      this._debugger = new Debugger(this);
    }

    return this._debugger;
  }

  get runtime() {
    if (!this._runtime) {
      this._runtime = new Runtime(this);
    }

    return this._runtime;
  }

  request(method, parameters, id, callback) {
    if (typeof parameters === 'function') {
      callback = parameters;
      parameters = undefined;
    }

    if (typeof id === 'function') {
      callback = id;
      id = undefined;
    }

    if (typeof parameters === 'undefined') {
      parameters = {};
    }

    if (typeof id === 'undefined') {
      id = this._counter++;
    }

    var request = {
      id: id,
      method: method,
      params: parameters,
    };

    this._callbacks[id] = callback;
    this._commands[id] = request;

    debug('request %s', util.inspect(request));
    this.emit('request', request);
    this._socket.send(JSON.stringify(request));
  }

  connect(uri, callback) {
    if (callback) {
      this.on('connect', callback);
    }

    let socket = ws.connect(uri);
    socket.once('open', () => {
      debug('connect');
      this.emit('connect');
    });

    socket.on('close', () => {
      debug('close');
      this.emit('close');
    });

    socket.on('error', (error) => {
      debug('error');
      this.emit('error', error);
    });

    socket.on('message', data => {
      try {
        var message = JSON.parse(data);

        if (message.id !== undefined) {
          var command = this._commands[message.id];
          var callback = this._callbacks[message.id];

          debug('response %s, %s', util.inspect(command), util.inspect(message));
          this.emit('response', command, message);

          if (callback) {
            if (message.error) {
              callback(message.error);
            } else {
              callback(null, message.result);
            }

            delete this._callbacks[message.id];
          }

          delete this._commands[message.id];

        } else {
          debug('message %s', util.inspect(message));
          this.emit('message', message.method, message.params);
        }
      } catch (error) {
        this.emit('error', error);
      }
    });

    this._socket = socket;
    this.emit('socket', socket);
  }

  close() {
    if (this.socket) {
      this.socket.close();
    }
  }
}

module.exports.Client = Client;

function connect(uri, callback) {
  var client = new Client();
  if (callback) {
    client.on('connect', callback);
  }

  client.connect(uri);

  return client;
}

module.exports.connect = connect;

function list(port, host, callback) {
  if (typeof host === 'function') {
    callback = host;
    host = undefined;
  }

  if (typeof host == 'undefined') {
    host = 'localhost';
  }

  var request = http.get({
    port: port,
    host: host,
    path: '/json/list'
  });

  request.on('response', (response) => {
    var data = '';

    response.on('data', (chunk) => {
      data += chunk;
    });

    response.on('end', () => {
      try {
        var targets = JSON.parse(data);
        return callback(null, targets);
      } catch (error) {
        return callback(error);
      }
    });
  });

  request.on('error', (error) => {
    return callback(error);
  });
}

module.exports.list = list;
module.exports.get = util.deprecate(list, 'rdbg.get: Use rdbg.list instead');
<|endoftext|>


<commit_before>(function a(){
    $.get('https://api.github.com/repos/KaMeHb-UA/LeNode/releases/latest', function(data, status){
        if (status != 'success') a(); else {
            $('a[rel="download"]').attr('href', data.assets[0].browser_download_url);
            $('#latest-version').html(data.tag_name);
            $('*[rel="release-description"]').html(data.body.replace(/#* /,''));
        }
    }, 'json');
})();<commit_msg>Little fix<commit_after>(function a(){
    $.get('https://api.github.com/repos/KaMeHb-UA/LeNode/releases/latest', function(data, status){
        if (status != 'success') a(); else {
            $('a[rel="download"]').attr('href', data.assets[0].browser_download_url);
            $('#latest-version').html(data.tag_name);
            $('*[rel="release-description"]').html(data.name);
        }
    }, 'json');
})();<|endoftext|>


<commit_before>/**
Editing interface for OpenAssessment settings (including assessments).

Args:
    element (DOM element): The DOM element representing this view.
    assessmentViews (object literal): Mapping of CSS IDs to view objects.
    data (Object literal): The data object passed from XBlock backend.

Returns:
    OpenAssessment.EditSettingsView

**/
OpenAssessment.EditSettingsView = function(element, assessmentViews, data) {
    var self = this;
    this.settingsElement = element;
    this.assessmentsElement = $(element).siblings('#openassessment_assessment_module_settings_editors').get(0);
    this.assessmentViews = assessmentViews;

    // Configure the date and time fields
    this.startDatetimeControl = new OpenAssessment.DatetimeControl(
        this.element,
        "#openassessment_submission_start_date",
        "#openassessment_submission_start_time"
    ).install();

    this.dueDatetimeControl = new OpenAssessment.DatetimeControl(
        this.element,
        "#openassessment_submission_due_date",
        "#openassessment_submission_due_time"
    ).install();

    new OpenAssessment.SelectControl(
        $("#openassessment_submission_file_upload_response", this.element),
        function(selectedValue) {
            var el = $("#openassessment_submission_file_upload_type_wrapper", self.element);
            if (!selectedValue) {
                el.addClass('is--hidden');
            } else {
                el.removeClass('is--hidden');
            }
        },
        new OpenAssessment.Notifier([
            new OpenAssessment.AssessmentToggleListener()
        ])
    ).install();

    new OpenAssessment.SelectControl(
        $("#openassessment_submission_upload_selector", this.element),
        {'custom': $("#openassessment_submission_white_listed_file_types_wrapper", this.element)},
        new OpenAssessment.Notifier([
            new OpenAssessment.AssessmentToggleListener()
        ])
    ).install();

    this.leaderboardIntField = new OpenAssessment.IntField(
        $("#openassessment_leaderboard_editor", this.element),
        {min: 0, max: 100}
    );

    this.fileTypeWhiteListInputField = new OpenAssessment.InputControl(
        $("#openassessment_submission_white_listed_file_types", this.element),
        function(value) {
            var badExts = [];
            var errors = [];
            if (!value) {
                errors.push(gettext('File types can not be empty.'));
                return errors;
            }
            var whiteList = $.map(value.replace(/\./g, '').toLowerCase().split(','), $.trim);
            $.each(whiteList, function(index, ext) {
                if (data.FILE_EXT_BLACK_LIST.indexOf(ext) !== -1) {
                    badExts.push(ext);
                }
            });
            if (badExts.length) {
                errors.push(gettext('The following file types are not allowed: ') + badExts.join(','));
            }

            return errors;
        }
    );

    this.initializeSortableAssessments();
};

OpenAssessment.EditSettingsView.prototype = {

    /**
    Installs click listeners which initialize drag and drop functionality for assessment modules.
    **/
    initializeSortableAssessments: function() {
        var view = this;
        // Initialize Drag and Drop of Assessment Modules
        $('#openassessment_assessment_module_settings_editors', view.element).sortable({
            // On Start, we want to collapse all draggable items so that dragging is visually simple (no scrolling)
            start: function(event, ui) {
                // Hide all of the contents (not the headers) of the divs, to collapse during dragging.
                $('.openassessment_assessment_module_editor', view.element).hide();

                // Because of the way that JQuery actively resizes elements during dragging (directly setting
                // the style property), the only way to over come it is to use an important tag ( :( ), or
                // to tell JQuery to set the height to be Automatic (i.e. resize to the minimum nescesary size.)
                // Because all of the information we don't want displayed is now hidden, an auto height will
                // perform the apparent "collapse" that we are looking for in the Placeholder and Helper.
                var targetHeight = 'auto';
                // Shrink the blank area behind the dragged item.
                ui.placeholder.height(targetHeight);
                // Shrink the dragged item itself.
                ui.helper.height(targetHeight);
                // Update the sortable to reflect these changes.
                $('#openassessment_assessment_module_settings_editors', view.element)
                    .sortable('refresh').sortable('refreshPositions');
            },
            // On stop, we redisplay the divs to their original state
            stop: function() {
                $('.openassessment_assessment_module_editor', view.element).show();
            },
            snap: true,
            axis: "y",
            handle: ".drag-handle",
            cursorAt: {top: 20}
        });
        $('#openassessment_assessment_module_settings_editors .drag-handle', view.element).disableSelection();
    },

    /**
    Get or set the display name of the problem.

    Args:
        name (string, optional): If provided, set the display name.

    Returns:
        string

    **/
    displayName: function(name) {
        var sel = $("#openassessment_title_editor", this.settingsElement);
        return OpenAssessment.Fields.stringField(sel, name);
    },

    /**
    Get or set the submission start date.

    Args:
        dateString (string, optional): If provided, set the date (YY-MM-DD).
        timeString (string, optional): If provided, set the time (HH:MM, 24-hour clock).

    Returns:
        string (ISO-format UTC datetime)

    **/
    submissionStart: function(dateString, timeString) {
        return this.startDatetimeControl.datetime(dateString, timeString);
    },

    /**
    Get or set the submission end date.

    Args:
        dateString (string, optional): If provided, set the date (YY-MM-DD).
        timeString (string, optional): If provided, set the time (HH:MM, 24-hour clock).

    Returns:
        string (ISO-format UTC datetime)

    **/
    submissionDue: function(dateString, timeString) {
        return this.dueDatetimeControl.datetime(dateString, timeString);
    },

    /**
     Get or set text response necessity.

    Args:
        value (string, optional): If provided, set text response necessity.

    Returns:
        string ('required', 'optional' or '')
     */
    textResponseNecessity: function(value) {
        var sel = $("#openassessment_submission_text_response", this.settingsElement);
        if (value !== undefined) {
            sel.val(value);
        }
        return sel.val();
    },

    /**
     Get or set file upload necessity.

    Args:
        value (string, optional): If provided, set file upload necessity.

    Returns:
        string ('required', 'optional' or '')
     */
    fileUploadResponseNecessity: function(value, triggerChange) {
        var sel = $("#openassessment_submission_file_upload_response", this.settingsElement);
        if (value !== undefined) {
            triggerChange = triggerChange || false;
            sel.val(value);
            if (triggerChange) {
                $(sel).trigger("change");
            }
        }
        return sel.val();
    },

    /**
    Get or set upload file type.

    Args:
        uploadType (string, optional): If provided, enable specified upload type submission.

    Returns:
        string (image, file or custom)

    **/
    fileUploadType: function(uploadType) {
        var fileUploadTypeWrapper = $("#openassessment_submission_file_upload_type_wrapper", this.settingsElement);
        var fileUploadAllowed = !$(fileUploadTypeWrapper).hasClass('is--hidden');
        if (fileUploadAllowed) {
            var sel = $("#openassessment_submission_upload_selector", this.settingsElement);
            if (uploadType !== undefined) {
                sel.val(uploadType);
            }
            return sel.val();
        }

        return '';
    },

    /**
    Get or set upload file extension white list.

    Args:
        exts (string, optional): If provided, set the file extension white list

    Returns:
        string: comma separated file extension white list string
    **/
    fileTypeWhiteList: function(exts) {
        if (exts !== undefined) {
            this.fileTypeWhiteListInputField.set(exts);
        }
        return this.fileTypeWhiteListInputField.get();
    },

    /**
    Enable / disable latex rendering.

    Args:
        isEnabled(boolean, optional): if provided enable/disable latex rendering
    Returns:
        boolean
    **/
    latexEnabled: function(isEnabled) {
        var sel = $('#openassessment_submission_latex_editor', this.settingsElement);
        if (isEnabled !== undefined) {
            if (isEnabled) {
                sel.val(1);
            } else {
                sel.val(0);
            }
        }
        return sel.val() === 1;
    },
    /**
    Get or set the number of scores to show in the leaderboard.
    If set to 0, the leaderboard will not be shown.

    Args:
        num (int, optional)

    Returns:
        int

    **/
    leaderboardNum: function(num) {
        if (num !== undefined) {
            this.leaderboardIntField.set(num);
        }
        return this.leaderboardIntField.get(num);
    },

    /**
    Construct a list of enabled assessments and their properties.

    Returns:
        list of object literals representing the assessments.

    Example usage:
    >>> editSettingsView.assessmentsDescription()
    [
        {
            name: "peer-assessment",
            start: "2014-04-01T00:00",
            due: null
            must_grade: 5,
            must_be_graded_by: 2,
        },
        {
            name: "self-assessment",
            start: null,
            due: null
        }
    ]
    **/
    assessmentsDescription: function() {
        var assessmentDescList = [];
        var view = this;

        // Find all assessment modules within our element in the DOM,
        // and append their definitions to the description
        $('.openassessment_assessment_module_settings_editor', this.assessmentsElement).each(
            function() {
                var asmntView = view.assessmentViews[$(this).attr('id')];
                if (asmntView.isEnabled()) {
                    var description = asmntView.description();
                    description.name = asmntView.name;
                    assessmentDescList.push(description);
                }
            }
        );
        return assessmentDescList;
    },

    /**
    Retrieve the names of all assessments in the editor,
    in the order that the user defined,
    including assessments that are not currently active.

    Returns:
        list of strings

    **/
    editorAssessmentsOrder: function() {
        var editorAssessments = [];
        var view = this;
        $('.openassessment_assessment_module_settings_editor', this.assessmentsElement).each(
            function() {
                var asmntView = view.assessmentViews[$(this).attr('id')];
                editorAssessments.push(asmntView.name);
            }
        );
        return editorAssessments;
    },

    /**
    Mark validation errors.

    Returns:
        Boolean indicating whether the view is valid.

    **/
    validate: function() {
        // Validate the start and due datetime controls
        var isValid = true;

        isValid = (this.startDatetimeControl.validate() && isValid);
        isValid = (this.dueDatetimeControl.validate() && isValid);
        isValid = (this.leaderboardIntField.validate() && isValid);
        if (this.fileUploadType() === 'custom') {
            isValid = (this.fileTypeWhiteListInputField.validate() && isValid);
        } else {
            // we want to keep the valid white list in case author changes upload type back to custom
            if (this.fileTypeWhiteListInputField.get() && !this.fileTypeWhiteListInputField.validate()) {
                // but will clear the field in case it is invalid
                this.fileTypeWhiteListInputField.set('');
            }
        }

        // Validate each of the *enabled* assessment views
        $.each(this.assessmentViews, function() {
            if (this.isEnabled()) {
                isValid = (this.validate() && isValid);
            }
        });

        return isValid;
    },

    /**
    Return a list of validation errors visible in the UI.
    Mainly useful for testing.

    Returns:
        list of string

    **/
    validationErrors: function() {
        var errors = [];

        if (this.startDatetimeControl.validationErrors().length > 0) {
            errors.push("Submission start is invalid");
        }
        if (this.dueDatetimeControl.validationErrors().length > 0) {
            errors.push("Submission due is invalid");
        }
        if (this.leaderboardIntField.validationErrors().length > 0) {
            errors.push("Leaderboard number is invalid");
        }
        if (this.fileTypeWhiteListInputField.validationErrors().length > 0) {
            errors = errors.concat(this.fileTypeWhiteListInputField.validationErrors());
        }

        $.each(this.assessmentViews, function() {
            errors = errors.concat(this.validationErrors());
        });

        return errors;
    },

    /**
    Clear all validation errors from the UI.
    **/
    clearValidationErrors: function() {
        this.startDatetimeControl.clearValidationErrors();
        this.dueDatetimeControl.clearValidationErrors();
        this.leaderboardIntField.clearValidationErrors();
        this.fileTypeWhiteListInputField.clearValidationErrors();
        $.each(this.assessmentViews, function() {
            this.clearValidationErrors();
        });
    },
};
<commit_msg>Fixed the "Allow LaTeX Responses" setting<commit_after>/**
Editing interface for OpenAssessment settings (including assessments).

Args:
    element (DOM element): The DOM element representing this view.
    assessmentViews (object literal): Mapping of CSS IDs to view objects.
    data (Object literal): The data object passed from XBlock backend.

Returns:
    OpenAssessment.EditSettingsView

**/
OpenAssessment.EditSettingsView = function(element, assessmentViews, data) {
    var self = this;
    this.settingsElement = element;
    this.assessmentsElement = $(element).siblings('#openassessment_assessment_module_settings_editors').get(0);
    this.assessmentViews = assessmentViews;

    // Configure the date and time fields
    this.startDatetimeControl = new OpenAssessment.DatetimeControl(
        this.element,
        "#openassessment_submission_start_date",
        "#openassessment_submission_start_time"
    ).install();

    this.dueDatetimeControl = new OpenAssessment.DatetimeControl(
        this.element,
        "#openassessment_submission_due_date",
        "#openassessment_submission_due_time"
    ).install();

    new OpenAssessment.SelectControl(
        $("#openassessment_submission_file_upload_response", this.element),
        function(selectedValue) {
            var el = $("#openassessment_submission_file_upload_type_wrapper", self.element);
            if (!selectedValue) {
                el.addClass('is--hidden');
            } else {
                el.removeClass('is--hidden');
            }
        },
        new OpenAssessment.Notifier([
            new OpenAssessment.AssessmentToggleListener()
        ])
    ).install();

    new OpenAssessment.SelectControl(
        $("#openassessment_submission_upload_selector", this.element),
        {'custom': $("#openassessment_submission_white_listed_file_types_wrapper", this.element)},
        new OpenAssessment.Notifier([
            new OpenAssessment.AssessmentToggleListener()
        ])
    ).install();

    this.leaderboardIntField = new OpenAssessment.IntField(
        $("#openassessment_leaderboard_editor", this.element),
        {min: 0, max: 100}
    );

    this.fileTypeWhiteListInputField = new OpenAssessment.InputControl(
        $("#openassessment_submission_white_listed_file_types", this.element),
        function(value) {
            var badExts = [];
            var errors = [];
            if (!value) {
                errors.push(gettext('File types can not be empty.'));
                return errors;
            }
            var whiteList = $.map(value.replace(/\./g, '').toLowerCase().split(','), $.trim);
            $.each(whiteList, function(index, ext) {
                if (data.FILE_EXT_BLACK_LIST.indexOf(ext) !== -1) {
                    badExts.push(ext);
                }
            });
            if (badExts.length) {
                errors.push(gettext('The following file types are not allowed: ') + badExts.join(','));
            }

            return errors;
        }
    );

    this.initializeSortableAssessments();
};

OpenAssessment.EditSettingsView.prototype = {

    /**
    Installs click listeners which initialize drag and drop functionality for assessment modules.
    **/
    initializeSortableAssessments: function() {
        var view = this;
        // Initialize Drag and Drop of Assessment Modules
        $('#openassessment_assessment_module_settings_editors', view.element).sortable({
            // On Start, we want to collapse all draggable items so that dragging is visually simple (no scrolling)
            start: function(event, ui) {
                // Hide all of the contents (not the headers) of the divs, to collapse during dragging.
                $('.openassessment_assessment_module_editor', view.element).hide();

                // Because of the way that JQuery actively resizes elements during dragging (directly setting
                // the style property), the only way to over come it is to use an important tag ( :( ), or
                // to tell JQuery to set the height to be Automatic (i.e. resize to the minimum nescesary size.)
                // Because all of the information we don't want displayed is now hidden, an auto height will
                // perform the apparent "collapse" that we are looking for in the Placeholder and Helper.
                var targetHeight = 'auto';
                // Shrink the blank area behind the dragged item.
                ui.placeholder.height(targetHeight);
                // Shrink the dragged item itself.
                ui.helper.height(targetHeight);
                // Update the sortable to reflect these changes.
                $('#openassessment_assessment_module_settings_editors', view.element)
                    .sortable('refresh').sortable('refreshPositions');
            },
            // On stop, we redisplay the divs to their original state
            stop: function() {
                $('.openassessment_assessment_module_editor', view.element).show();
            },
            snap: true,
            axis: "y",
            handle: ".drag-handle",
            cursorAt: {top: 20}
        });
        $('#openassessment_assessment_module_settings_editors .drag-handle', view.element).disableSelection();
    },

    /**
    Get or set the display name of the problem.

    Args:
        name (string, optional): If provided, set the display name.

    Returns:
        string

    **/
    displayName: function(name) {
        var sel = $("#openassessment_title_editor", this.settingsElement);
        return OpenAssessment.Fields.stringField(sel, name);
    },

    /**
    Get or set the submission start date.

    Args:
        dateString (string, optional): If provided, set the date (YY-MM-DD).
        timeString (string, optional): If provided, set the time (HH:MM, 24-hour clock).

    Returns:
        string (ISO-format UTC datetime)

    **/
    submissionStart: function(dateString, timeString) {
        return this.startDatetimeControl.datetime(dateString, timeString);
    },

    /**
    Get or set the submission end date.

    Args:
        dateString (string, optional): If provided, set the date (YY-MM-DD).
        timeString (string, optional): If provided, set the time (HH:MM, 24-hour clock).

    Returns:
        string (ISO-format UTC datetime)

    **/
    submissionDue: function(dateString, timeString) {
        return this.dueDatetimeControl.datetime(dateString, timeString);
    },

    /**
     Get or set text response necessity.

    Args:
        value (string, optional): If provided, set text response necessity.

    Returns:
        string ('required', 'optional' or '')
     */
    textResponseNecessity: function(value) {
        var sel = $("#openassessment_submission_text_response", this.settingsElement);
        if (value !== undefined) {
            sel.val(value);
        }
        return sel.val();
    },

    /**
     Get or set file upload necessity.

    Args:
        value (string, optional): If provided, set file upload necessity.

    Returns:
        string ('required', 'optional' or '')
     */
    fileUploadResponseNecessity: function(value, triggerChange) {
        var sel = $("#openassessment_submission_file_upload_response", this.settingsElement);
        if (value !== undefined) {
            triggerChange = triggerChange || false;
            sel.val(value);
            if (triggerChange) {
                $(sel).trigger("change");
            }
        }
        return sel.val();
    },

    /**
    Get or set upload file type.

    Args:
        uploadType (string, optional): If provided, enable specified upload type submission.

    Returns:
        string (image, file or custom)

    **/
    fileUploadType: function(uploadType) {
        var fileUploadTypeWrapper = $("#openassessment_submission_file_upload_type_wrapper", this.settingsElement);
        var fileUploadAllowed = !$(fileUploadTypeWrapper).hasClass('is--hidden');
        if (fileUploadAllowed) {
            var sel = $("#openassessment_submission_upload_selector", this.settingsElement);
            if (uploadType !== undefined) {
                sel.val(uploadType);
            }
            return sel.val();
        }

        return '';
    },

    /**
    Get or set upload file extension white list.

    Args:
        exts (string, optional): If provided, set the file extension white list

    Returns:
        string: comma separated file extension white list string
    **/
    fileTypeWhiteList: function(exts) {
        if (exts !== undefined) {
            this.fileTypeWhiteListInputField.set(exts);
        }
        return this.fileTypeWhiteListInputField.get();
    },

    /**
    Enable / disable latex rendering.

    Args:
        isEnabled(boolean, optional): if provided enable/disable latex rendering
    Returns:
        boolean
    **/
    latexEnabled: function(isEnabled) {
        var sel = $('#openassessment_submission_latex_editor', this.settingsElement);
        if (isEnabled !== undefined) {
            if (isEnabled) {
                sel.val(1);
            } else {
                sel.val(0);
            }
        }
        return sel.val() === "1";
    },
    /**
    Get or set the number of scores to show in the leaderboard.
    If set to 0, the leaderboard will not be shown.

    Args:
        num (int, optional)

    Returns:
        int

    **/
    leaderboardNum: function(num) {
        if (num !== undefined) {
            this.leaderboardIntField.set(num);
        }
        return this.leaderboardIntField.get(num);
    },

    /**
    Construct a list of enabled assessments and their properties.

    Returns:
        list of object literals representing the assessments.

    Example usage:
    >>> editSettingsView.assessmentsDescription()
    [
        {
            name: "peer-assessment",
            start: "2014-04-01T00:00",
            due: null
            must_grade: 5,
            must_be_graded_by: 2,
        },
        {
            name: "self-assessment",
            start: null,
            due: null
        }
    ]
    **/
    assessmentsDescription: function() {
        var assessmentDescList = [];
        var view = this;

        // Find all assessment modules within our element in the DOM,
        // and append their definitions to the description
        $('.openassessment_assessment_module_settings_editor', this.assessmentsElement).each(
            function() {
                var asmntView = view.assessmentViews[$(this).attr('id')];
                if (asmntView.isEnabled()) {
                    var description = asmntView.description();
                    description.name = asmntView.name;
                    assessmentDescList.push(description);
                }
            }
        );
        return assessmentDescList;
    },

    /**
    Retrieve the names of all assessments in the editor,
    in the order that the user defined,
    including assessments that are not currently active.

    Returns:
        list of strings

    **/
    editorAssessmentsOrder: function() {
        var editorAssessments = [];
        var view = this;
        $('.openassessment_assessment_module_settings_editor', this.assessmentsElement).each(
            function() {
                var asmntView = view.assessmentViews[$(this).attr('id')];
                editorAssessments.push(asmntView.name);
            }
        );
        return editorAssessments;
    },

    /**
    Mark validation errors.

    Returns:
        Boolean indicating whether the view is valid.

    **/
    validate: function() {
        // Validate the start and due datetime controls
        var isValid = true;

        isValid = (this.startDatetimeControl.validate() && isValid);
        isValid = (this.dueDatetimeControl.validate() && isValid);
        isValid = (this.leaderboardIntField.validate() && isValid);
        if (this.fileUploadType() === 'custom') {
            isValid = (this.fileTypeWhiteListInputField.validate() && isValid);
        } else {
            // we want to keep the valid white list in case author changes upload type back to custom
            if (this.fileTypeWhiteListInputField.get() && !this.fileTypeWhiteListInputField.validate()) {
                // but will clear the field in case it is invalid
                this.fileTypeWhiteListInputField.set('');
            }
        }

        // Validate each of the *enabled* assessment views
        $.each(this.assessmentViews, function() {
            if (this.isEnabled()) {
                isValid = (this.validate() && isValid);
            }
        });

        return isValid;
    },

    /**
    Return a list of validation errors visible in the UI.
    Mainly useful for testing.

    Returns:
        list of string

    **/
    validationErrors: function() {
        var errors = [];

        if (this.startDatetimeControl.validationErrors().length > 0) {
            errors.push("Submission start is invalid");
        }
        if (this.dueDatetimeControl.validationErrors().length > 0) {
            errors.push("Submission due is invalid");
        }
        if (this.leaderboardIntField.validationErrors().length > 0) {
            errors.push("Leaderboard number is invalid");
        }
        if (this.fileTypeWhiteListInputField.validationErrors().length > 0) {
            errors = errors.concat(this.fileTypeWhiteListInputField.validationErrors());
        }

        $.each(this.assessmentViews, function() {
            errors = errors.concat(this.validationErrors());
        });

        return errors;
    },

    /**
    Clear all validation errors from the UI.
    **/
    clearValidationErrors: function() {
        this.startDatetimeControl.clearValidationErrors();
        this.dueDatetimeControl.clearValidationErrors();
        this.leaderboardIntField.clearValidationErrors();
        this.fileTypeWhiteListInputField.clearValidationErrors();
        $.each(this.assessmentViews, function() {
            this.clearValidationErrors();
        });
    },
};
<|endoftext|>


<commit_before>/// <binding BeforeBuild='webpack:build, min:css' Clean='clean' />
"use strict";

var gulp = require("gulp"),
    debug = require("gulp-debug"),
    util = require("gulp-util"),
    rimraf = require("rimraf"),
    merge = require("merge-stream"),
    concat = require("gulp-concat"),
    rename = require("gulp-rename"),
    sass = require("gulp-sass"),
    cssmin = require("gulp-cssmin"),
    uglify = require("gulp-uglify"),
    webpack = require('webpack'),
    sourcemaps = require('gulp-sourcemaps');

var paths = {
    webroot: "./wwwroot/"
};

paths.js = paths.webroot + "js/**/*.js";
paths.jsx = paths.webroot + "js/**/*.jsx";
paths.minJs = paths.webroot + "js/**/*.min.js";

paths.sass = paths.webroot + "sass/**/*.scss";
paths.css = paths.webroot + "css";

paths.concatJsDest = paths.webroot + "js/site.js";
paths.concatJsMinDest = paths.webroot + "js/site.min.js";
paths.concatCssDest = paths.webroot + "css/site.min.css";

gulp.task("clean:js", function (cb) {
    rimraf(paths.concatJsDest, cb);
});

gulp.task("clean:css", function (cb) {
    rimraf(paths.concatCssDest, cb);
});

gulp.task("clean", ["clean:js", "clean:css"]);

gulp.task("webpack:build", function (callback) {
    webpack({
        entry: {
            search: paths.webroot + "js/views/search/main.jsx"
        },
        output: {
            path: paths.webroot + 'js/dist/',
            filename: '[name].js'
        },
        module: {
            loaders: [
                {
                    test: /\.jsx?$/,
                    loader: 'babel-loader',
                    query: {
                        presets: ['react', 'es2015']
                    }
                }
            ]
        }
    }, function(err, stats) {
        util.log('[webpack:build]', stats.toString({
            colors: true
        }));
        callback();
    });
});

gulp.task("min:css", function () {
    return gulp.src([paths.sass])
        .pipe(sourcemaps.init())            // start source maps
        .pipe(sass())                       // compile sass
        .pipe(rename({                      // with new directory, filename ext
            dirname: paths.css,
            extname: '.css'}))
        .pipe(sourcemaps.write())           // create sourcemaps
        .pipe(gulp.dest("."))               // write out compiled files
        .pipe(concat(paths.concatCssDest))  // concat + min
        .pipe(cssmin())
        .pipe(gulp.dest("."));
});

gulp.task("build", ["min:css", "webpack:build"]);

gulp.task("watch:js", function() {
    gulp.watch([paths.js, paths.jsx], ["webpack:build"]);
});<commit_msg>add watch for sass and js<commit_after>/// <binding BeforeBuild='webpack:build, min:css' Clean='clean' />
"use strict";

var gulp = require("gulp"),
    debug = require("gulp-debug"),
    util = require("gulp-util"),
    rimraf = require("rimraf"),
    merge = require("merge-stream"),
    concat = require("gulp-concat"),
    rename = require("gulp-rename"),
    sass = require("gulp-sass"),
    cssmin = require("gulp-cssmin"),
    uglify = require("gulp-uglify"),
    webpack = require('webpack'),
    sourcemaps = require('gulp-sourcemaps');

var paths = {
    webroot: "./wwwroot/"
};

paths.js = paths.webroot + "js/**/*.js";
paths.jsx = paths.webroot + "js/**/*.jsx";
paths.minJs = paths.webroot + "js/**/*.min.js";

paths.sass = paths.webroot + "sass/**/*.scss";
paths.css = paths.webroot + "css";

paths.concatJsDest = paths.webroot + "js/site.js";
paths.concatJsMinDest = paths.webroot + "js/site.min.js";
paths.concatCssDest = paths.webroot + "css/site.min.css";

gulp.task("clean:js", function (cb) {
    rimraf(paths.concatJsDest, cb);
});

gulp.task("clean:css", function (cb) {
    rimraf(paths.concatCssDest, cb);
});

gulp.task("clean", ["clean:js", "clean:css"]);

gulp.task("webpack:build", function (callback) {
    webpack({
        entry: {
            search: paths.webroot + "js/views/search/main.jsx"
        },
        output: {
            path: paths.webroot + 'js/dist/',
            filename: '[name].js'
        },
        module: {
            loaders: [
                {
                    test: /\.jsx?$/,
                    loader: 'babel-loader',
                    query: {
                        presets: ['react', 'es2015']
                    }
                }
            ]
        }
    }, function(err, stats) {
        util.log('[webpack:build]', stats.toString({
            colors: true
        }));
        callback();
    });
});

gulp.task("min:css", function () {
    return gulp.src([paths.sass])
        .pipe(sourcemaps.init())            // start source maps
        .pipe(sass())                       // compile sass
        .pipe(rename({                      // with new directory, filename ext
            dirname: paths.css,
            extname: '.css'}))
        .pipe(sourcemaps.write())           // create sourcemaps
        .pipe(gulp.dest("."))               // write out compiled files
        .pipe(concat(paths.concatCssDest))  // concat + min
        .pipe(cssmin())
        .pipe(gulp.dest("."));
});

gulp.task("build", ["min:css", "webpack:build"]);

gulp.task("watch:js", function() {
    gulp.watch([paths.js, paths.jsx], ["webpack:build"]);
});

gulp.task("watch", function() {
    gulp.watch([paths.js, paths.jsx], ["webpack:build"]);
    gulp.watch([paths.sass], ["min:css"]);
});<|endoftext|>