From 3d1efa57a0d439f252d07a3e9da2c1b651eb22f5 Mon Sep 17 00:00:00 2001 From: spalger Date: Thu, 19 May 2016 07:28:52 -0700 Subject: [PATCH 01/15] splip in lodash-migrate for debugging --- grunt/config/esvm.js | 2 +- scripts/Version.js | 2 +- scripts/ci.js | 2 +- scripts/release/bower.js | 2 +- src/lib/transport/find_common_protocol.js | 2 +- src/lib/utils.js | 2 +- test/fixtures/keepalive.js | 2 +- test/mocks/browser_http.js | 2 +- test/mocks/browser_server.js | 2 +- test/unit/browser_builds/angular.js | 2 +- test/unit/buffer_flush_tests.js | 2 +- test/unit/specs/client_action.js | 2 +- test/unit/specs/connection_abstract.js | 2 +- test/unit/specs/connection_pool.js | 2 +- test/unit/specs/errors.js | 2 +- test/unit/specs/host.js | 2 +- test/unit/specs/http_connector.js | 2 +- test/unit/specs/log.js | 2 +- test/unit/specs/random_selector.js | 2 +- test/unit/specs/round_robin_selector.js | 2 +- test/unit/specs/transport.js | 2 +- test/unit/specs/transport_with_server.js | 2 +- test/utils/expect_sub_object.js | 2 +- test/utils/jenkins-reporter.js | 2 +- test/utils/make_j_unit_xml.js | 2 +- test/utils/server.js | 2 +- 26 files changed, 26 insertions(+), 26 deletions(-) diff --git a/grunt/config/esvm.js b/grunt/config/esvm.js index 31c3047f0..711ec0484 100644 --- a/grunt/config/esvm.js +++ b/grunt/config/esvm.js @@ -1,4 +1,4 @@ -var _ = require('lodash'); +var _ = require('lodash-migrate'); var utils = require('../utils'); var fromRoot = require('path').join.bind(null, __dirname, '..', '..'); diff --git a/scripts/Version.js b/scripts/Version.js index 93efcd599..917009d83 100644 --- a/scripts/Version.js +++ b/scripts/Version.js @@ -1,4 +1,4 @@ -var _ = require('lodash'); +var _ = require('lodash-migrate'); var package = require('../package.json'); var branches = package.config.supported_es_branches; var semver = require('semver'); diff --git a/scripts/ci.js b/scripts/ci.js index 9403784c2..cf1fa7760 100644 --- a/scripts/ci.js +++ b/scripts/ci.js @@ -18,7 +18,7 @@ *******/ var Promise = require('bluebird'); -var _ = require('lodash'); +var _ = require('lodash-migrate'); var through2 = require('through2'); var map = require('through2-map'); var split = require('split'); diff --git a/scripts/release/bower.js b/scripts/release/bower.js index 3889bbbf7..3ada9c4e3 100644 --- a/scripts/release/bower.js +++ b/scripts/release/bower.js @@ -1,7 +1,7 @@ var fs = require('fs'); var spawn = require('../_spawn'); var async = require('async'); -var _ = require('lodash'); +var _ = require('lodash-migrate'); var root = require('path').join(__dirname, '../..'); var bowerDir = root + '/src/bower_es_js'; diff --git a/src/lib/transport/find_common_protocol.js b/src/lib/transport/find_common_protocol.js index 6b60907fb..4df4213fd 100644 --- a/src/lib/transport/find_common_protocol.js +++ b/src/lib/transport/find_common_protocol.js @@ -1,4 +1,4 @@ -var isEmpty = require('lodash').isEmpty; +var isEmpty = require('lodash-migrate').isEmpty; module.exports = function (hosts) { if (isEmpty(hosts)) return false; diff --git a/src/lib/utils.js b/src/lib/utils.js index 4996cee8b..69c5f9f3e 100644 --- a/src/lib/utils.js +++ b/src/lib/utils.js @@ -1,5 +1,5 @@ var path = require('path'); -var _ = require('lodash'); +var _ = require('lodash-migrate'); var nodeUtils = require('util'); /** diff --git a/test/fixtures/keepalive.js b/test/fixtures/keepalive.js index c61ce7250..18bad5575 100644 --- a/test/fixtures/keepalive.js +++ b/test/fixtures/keepalive.js @@ -1,6 +1,6 @@ var clock = require('sinon').useFakeTimers(); var Client = require('../../src/elasticsearch').Client; -var _ = require('lodash'); +var _ = require('lodash-migrate'); var times = require('async').times; process.once('message', function (port) { diff --git a/test/mocks/browser_http.js b/test/mocks/browser_http.js index edbbbf448..135d6ecc7 100644 --- a/test/mocks/browser_http.js +++ b/test/mocks/browser_http.js @@ -27,7 +27,7 @@ module.exports = MockHttpRequest; -var _ = require('lodash'); +var _ = require('lodash-migrate'); function MockHttpRequest() { // These are internal flags and data structures diff --git a/test/mocks/browser_server.js b/test/mocks/browser_server.js index 7c4d0db59..36babae1a 100644 --- a/test/mocks/browser_server.js +++ b/test/mocks/browser_server.js @@ -3,7 +3,7 @@ var complete = []; var MockHttpRequest = require('./browser_http'); var XhrServer = MockHttpRequest.MockHttpServer; var parseUrl = MockHttpRequest.prototype.parseUri; -var _ = require('lodash'); +var _ = require('lodash-migrate'); var server = new XhrServer(function (request) { var reqDetails = { diff --git a/test/unit/browser_builds/angular.js b/test/unit/browser_builds/angular.js index 559b09edb..ed6b2d974 100644 --- a/test/unit/browser_builds/angular.js +++ b/test/unit/browser_builds/angular.js @@ -1,4 +1,4 @@ -var _ = require('lodash'); +var _ = require('lodash-migrate'); var expect = require('expect.js'); var Promise = require('bluebird'); var sinon = require('sinon'); diff --git a/test/unit/buffer_flush_tests.js b/test/unit/buffer_flush_tests.js index 7023c73ff..d00f75b4d 100644 --- a/test/unit/buffer_flush_tests.js +++ b/test/unit/buffer_flush_tests.js @@ -3,7 +3,7 @@ module.exports = function (makeLogger) { var stub = require('../utils/auto_release_stub').make(); var fs = require('fs'); var once = require('events').EventEmitter.prototype.once; - var _ = require('lodash'); + var _ = require('lodash-migrate'); describe('buffer flush', function () { if (require('stream').Writable) { diff --git a/test/unit/specs/client_action.js b/test/unit/specs/client_action.js index 578432a6f..0b2bc76f2 100644 --- a/test/unit/specs/client_action.js +++ b/test/unit/specs/client_action.js @@ -1,7 +1,7 @@ var ca = require('../../../src/lib/client_action').factory; var proxy = require('../../../src/lib/client_action').proxyFactory; var expect = require('expect.js'); -var _ = require('lodash'); +var _ = require('lodash-migrate'); var Promise = require('bluebird'); /** diff --git a/test/unit/specs/connection_abstract.js b/test/unit/specs/connection_abstract.js index a1e8ec88b..4f4a91cb6 100644 --- a/test/unit/specs/connection_abstract.js +++ b/test/unit/specs/connection_abstract.js @@ -2,7 +2,7 @@ var ConnectionAbstract = require('../../../src/lib/connection'); var Host = require('../../../src/lib/host'); var sinon = require('sinon'); var expect = require('expect.js'); -var _ = require('lodash'); +var _ = require('lodash-migrate'); var errors = require('../../../src/lib/errors'); var stub = require('../../utils/auto_release_stub').make(); diff --git a/test/unit/specs/connection_pool.js b/test/unit/specs/connection_pool.js index 76df25378..b4f9d92ff 100644 --- a/test/unit/specs/connection_pool.js +++ b/test/unit/specs/connection_pool.js @@ -2,7 +2,7 @@ var ConnectionPool = require('../../../src/lib/connection_pool'); var Host = require('../../../src/lib/host'); var errors = require('../../../src/lib/errors'); var ConnectionAbstract = require('../../../src/lib/connection'); -var _ = require('lodash'); +var _ = require('lodash-migrate'); var EventEmitter = require('events').EventEmitter; var expect = require('expect.js'); var sinon = require('sinon'); diff --git a/test/unit/specs/errors.js b/test/unit/specs/errors.js index fb885c0e3..0347b7b4e 100644 --- a/test/unit/specs/errors.js +++ b/test/unit/specs/errors.js @@ -1,6 +1,6 @@ var errors = require('../../../src/lib/errors'); var expect = require('expect.js'); -var _ = require('lodash'); +var _ = require('lodash-migrate'); _.each(errors, function (CustomError, name) { if (name.charAt(0) !== '_') { diff --git a/test/unit/specs/host.js b/test/unit/specs/host.js index d02444b1a..f0e4033c7 100644 --- a/test/unit/specs/host.js +++ b/test/unit/specs/host.js @@ -1,5 +1,5 @@ var Host = require('../../../src/lib/host'); -var _ = require('lodash'); +var _ = require('lodash-migrate'); var expect = require('expect.js'); var url = require('url'); var expectSubObject = require('../../utils/expect_sub_object'); diff --git a/test/unit/specs/http_connector.js b/test/unit/specs/http_connector.js index c9ee86f2b..47245e0f8 100644 --- a/test/unit/specs/http_connector.js +++ b/test/unit/specs/http_connector.js @@ -1,6 +1,6 @@ describe('Http Connector', function () { - var _ = require('lodash'); + var _ = require('lodash-migrate'); var expect = require('expect.js'); var nock = require('nock'); var sinon = require('sinon'); diff --git a/test/unit/specs/log.js b/test/unit/specs/log.js index 8976c01bd..9cc6e38a1 100644 --- a/test/unit/specs/log.js +++ b/test/unit/specs/log.js @@ -1,5 +1,5 @@ var Log = require('../../../src/lib/log'); -var _ = require('lodash'); +var _ = require('lodash-migrate'); var expect = require('expect.js'); describe('Log class', function () { diff --git a/test/unit/specs/random_selector.js b/test/unit/specs/random_selector.js index 91b0149b0..ad6ac70c8 100644 --- a/test/unit/specs/random_selector.js +++ b/test/unit/specs/random_selector.js @@ -1,6 +1,6 @@ describe('Random Selector', function () { var randomSelector = require('../../../src/lib/selectors/random'); - var _ = require('lodash'); + var _ = require('lodash-migrate'); var expect = require('expect.js'); it('chooses a selection by random', function () { diff --git a/test/unit/specs/round_robin_selector.js b/test/unit/specs/round_robin_selector.js index 2298a0180..d320b5dc8 100644 --- a/test/unit/specs/round_robin_selector.js +++ b/test/unit/specs/round_robin_selector.js @@ -1,6 +1,6 @@ describe('Round Robin Selector', function () { var selector = require('../../../src/lib/selectors/round_robin'); - var _ = require('lodash'); + var _ = require('lodash-migrate'); var expect = require('expect.js'); it('chooses options in order', function () { diff --git a/test/unit/specs/transport.js b/test/unit/specs/transport.js index 39c15fca6..c8aa567f2 100644 --- a/test/unit/specs/transport.js +++ b/test/unit/specs/transport.js @@ -5,7 +5,7 @@ var Promise = require('bluebird'); var sinon = require('sinon'); var expect = require('expect.js'); -var _ = require('lodash'); +var _ = require('lodash-migrate'); var nodeList = require('../../fixtures/short_node_list.json'); var stub = require('../../utils/auto_release_stub').make(); diff --git a/test/unit/specs/transport_with_server.js b/test/unit/specs/transport_with_server.js index 865885da8..9b267ba31 100644 --- a/test/unit/specs/transport_with_server.js +++ b/test/unit/specs/transport_with_server.js @@ -7,7 +7,7 @@ var expect = require('expect.js'); var sinon = require('sinon'); var nock = require('../../mocks/server.js'); var through2 = require('through2'); -var _ = require('lodash'); +var _ = require('lodash-migrate'); var nodeList = require('../../fixtures/short_node_list.json'); var stub = require('../../utils/auto_release_stub').make(); diff --git a/test/utils/expect_sub_object.js b/test/utils/expect_sub_object.js index 57b6b4276..d4c61a0f1 100644 --- a/test/utils/expect_sub_object.js +++ b/test/utils/expect_sub_object.js @@ -1,4 +1,4 @@ -var _ = require('lodash'); +var _ = require('lodash-migrate'); var expect = require('expect.js'); module.exports = function expectSubObject(obj, subObj) { _.forOwn(subObj, function (val, prop) { diff --git a/test/utils/jenkins-reporter.js b/test/utils/jenkins-reporter.js index 818e30bb6..5d2208013 100644 --- a/test/utils/jenkins-reporter.js +++ b/test/utils/jenkins-reporter.js @@ -7,7 +7,7 @@ module.exports = JenkinsReporter; var Base = require('mocha/lib/reporters/base'); -var _ = require('lodash'); +var _ = require('lodash-migrate'); var chalk = require('chalk'); var makeJUnitXml = require('./make_j_unit_xml'); var fs = require('fs'); diff --git a/test/utils/make_j_unit_xml.js b/test/utils/make_j_unit_xml.js index 01cf06c04..b87831667 100644 --- a/test/utils/make_j_unit_xml.js +++ b/test/utils/make_j_unit_xml.js @@ -28,7 +28,7 @@ var testXml = require('xmlbuilder'); var suites = testXml.create('testsuites'); var suiteCount = 0; var moment = require('moment'); -var _ = require('lodash'); +var _ = require('lodash-migrate'); var chalk = require('chalk'); function makeJUnitXml(runnerName, testDetails) { diff --git a/test/utils/server.js b/test/utils/server.js index 0ebe2894b..88b7e07d8 100644 --- a/test/utils/server.js +++ b/test/utils/server.js @@ -1,7 +1,7 @@ var express = require('express'); var http = require('http'); var fs = require('fs'); -var _ = require('lodash'); +var _ = require('lodash-migrate'); var async = require('async'); var root = require('path').join(__dirname, '../..'); var browserify = require('browserify'); From 21e96b7080aff849f587fb60965f679c0034c265 Mon Sep 17 00:00:00 2001 From: spalger Date: Thu, 19 May 2016 07:29:11 -0700 Subject: [PATCH 02/15] _.rest -> _.tail --- scripts/Version.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/Version.js b/scripts/Version.js index 917009d83..abaf6bed9 100644 --- a/scripts/Version.js +++ b/scripts/Version.js @@ -48,7 +48,7 @@ Version.prototype.mergeOpts = function (opts) { return self.satisfies(rule.version); }) .map(_.ary(_.partialRight(_.omit, 'version'), 1)) - .concat(_.rest(arguments)) + .concat(_.tail(arguments)) .reverse() .reduce(_.merge, {}); }; From d1e5940f731a684336c4e1ff1d9ff089fd8f639f Mon Sep 17 00:00:00 2001 From: spalger Date: Thu, 19 May 2016 07:30:26 -0700 Subject: [PATCH 03/15] force lodash v4 on some iterators so they do not run multiple times --- scripts/generate/js_api.js | 9 +++++---- scripts/generate/templates/api_methods.tmpl | 6 +++--- scripts/generate/templates/index.js | 2 ++ 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/scripts/generate/js_api.js b/scripts/generate/js_api.js index f53750b71..6b8255f24 100644 --- a/scripts/generate/js_api.js +++ b/scripts/generate/js_api.js @@ -4,6 +4,7 @@ module.exports = function (branch, done) { * @type {[type]} */ var _ = require('../../src/lib/utils'); + var _v4 = require('lodash-migrate/lodash'); var utils = require('../../grunt/utils'); var fs = require('fs'); var async = require('async'); @@ -174,8 +175,8 @@ module.exports = function (branch, done) { var actions = []; // itterate all of the specs within the file, should only be one - _.each(spec, function (def, name) { - //camelcase the name + _v4.each(spec, function (def, name) { + // camelcase the name name = _.map(name.split('.'), _.camelCase).join('.'); if (name === 'cat.aliases') { @@ -218,7 +219,7 @@ module.exports = function (branch, done) { var urls = _.difference(def.url.paths, overrides.aliases[name]); var urlSignatures = []; - urls = _.map(urls, function (url) { + urls = _v4.map(urls, function (url) { var optionalVars = {}; var requiredVars = {}; var param; @@ -239,7 +240,7 @@ module.exports = function (branch, done) { urlSignatures.push(_.union(_.keys(optionalVars), _.keys(requiredVars)).sort().join(':')); - return _.omit({ + return _v4.omitBy({ fmt: url.replace(urlParamRE, function (full, match) { return '<%=' + _.camelCase(match) + '%>'; }), diff --git a/scripts/generate/templates/api_methods.tmpl b/scripts/generate/templates/api_methods.tmpl index 01574797d..e4bbbc345 100644 --- a/scripts/generate/templates/api_methods.tmpl +++ b/scripts/generate/templates/api_methods.tmpl @@ -8,7 +8,7 @@ NOTE: At this time, you must opt into the <%= branch %> API by setting the `apiV <% } actions = _.sortBy(actions, 'namespace'); -_.each(actions, function (action) { +_v4.each(actions, function (action) { action.index = 'api-' + action.name.toLowerCase().replace(/[^\w]+/g, '-') + branchSuffix; %> @@ -31,12 +31,12 @@ The default method is `<%= action.spec.method || 'GET' %>` and the usual < +_v4.each(action.allParams, function (param, paramName) { %> `<%= paramWithDefault(paramName, param.default) %>`:: `<%= paramType(param.type) %>` -- <%= joinParagraphs(param.description || '', 4) %><% if (param.type === 'enum') {%> Options:::<% -_.each(param.options, function (opt) {%> +_v4.each(param.options, function (opt) {%> * `"<%= opt %>"`<% });%> <% diff --git a/scripts/generate/templates/index.js b/scripts/generate/templates/index.js index 0c3ef4cad..21e8c872a 100644 --- a/scripts/generate/templates/index.js +++ b/scripts/generate/templates/index.js @@ -1,5 +1,6 @@ var _ = require('../../../src/lib/utils'); +var _v4 = require('lodash-migrate/lodash'); var utils = require('../../../grunt/utils'); var fs = require('fs'); var path = require('path'); @@ -42,6 +43,7 @@ var templateGlobals = { stringify: stringify, _: _, + _v4: _v4, indent: function (block, spaces) { var indent = _.repeat(' ', spaces); From bd93bc914ca7695d74ec88ecdf5798f60a55d0c1 Mon Sep 17 00:00:00 2001 From: spalger Date: Thu, 19 May 2016 07:31:15 -0700 Subject: [PATCH 04/15] _.unique -> _.uniq && _.pluck -> _.map --- scripts/generate/js_api.js | 12 +++++++++--- test/fixtures/keepalive.js | 4 ++-- test/integration/yaml_suite/client_manager.js | 6 +++--- 3 files changed, 14 insertions(+), 8 deletions(-) diff --git a/scripts/generate/js_api.js b/scripts/generate/js_api.js index 6b8255f24..b7fe299ff 100644 --- a/scripts/generate/js_api.js +++ b/scripts/generate/js_api.js @@ -88,7 +88,7 @@ module.exports = function (branch, done) { apiSpec = { actions: groups.normal || [], proxies: groups.proxies || [], - namespaces: _.unique(namespaces.sort(), true), + namespaces: _.uniq(namespaces.sort(), true), clientActionModifier: overrides.clientActionModifier }; @@ -252,8 +252,14 @@ module.exports = function (branch, done) { }); }); - if (urlSignatures.length !== _.unique(urlSignatures).length) { - throw new Error('Multiple URLS with the same signature detected for ' + spec.name + '\n' + _.pluck(urls, 'fmt').join('\n') + '\n'); + if (urlSignatures.length !== _.uniq(urlSignatures).length) { + throw new Error( + 'Multiple URLS with the same signature detected for ' + + spec.name + + '\n' + + _.map(urls, 'fmt').join('\n') + + '\n' + ); } if (urls.length > 1) { diff --git a/test/fixtures/keepalive.js b/test/fixtures/keepalive.js index 18bad5575..a929f8788 100644 --- a/test/fixtures/keepalive.js +++ b/test/fixtures/keepalive.js @@ -32,10 +32,10 @@ process.once('message', function (port) { var out = { socketCount: err || sockets.length, remaining: _.where(sockets, { destroyed: true }).length - sockets.length, - timeouts: _.size(clock.timers) && _.pluck(clock.timers, 'func').map(String) + timeouts: _.size(clock.timers) && _.map(clock.timers, 'func').map(String) }; clock.restore(); process.connected ? process.send(out) : console.log(out); }); -}); \ No newline at end of file +}); diff --git a/test/integration/yaml_suite/client_manager.js b/test/integration/yaml_suite/client_manager.js index c4bad9cdb..75437f360 100644 --- a/test/integration/yaml_suite/client_manager.js +++ b/test/integration/yaml_suite/client_manager.js @@ -112,7 +112,7 @@ module.exports = { snapshot: '_all' }) .then(function (resp) { - return _.pluck(resp.snapshots, 'snapshot'); + return _.map(resp.snapshots, 'snapshot'); }, function () { return []; }) @@ -121,13 +121,13 @@ module.exports = { repository: repo, snapshot: snapshot }); - }, {concurrency: 1}) + }, { concurrency: 1 }) .then(function () { return client.snapshot.deleteRepository({ repository: repo }); }); - }, {concurrency: 1}) + }, { concurrency: 1 }) ]); }; From 939cca84c6ac5ae8be16cba25ca0e701b775c3b3 Mon Sep 17 00:00:00 2001 From: spalger Date: Thu, 19 May 2016 07:31:36 -0700 Subject: [PATCH 05/15] add new override for master api --- scripts/generate/overrides.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/generate/overrides.js b/scripts/generate/overrides.js index 31c277c80..9dabbd4c3 100644 --- a/scripts/generate/overrides.js +++ b/scripts/generate/overrides.js @@ -204,7 +204,8 @@ function (spec) { version: '>=2.0.0', aliases: { 'reindex.rethrottle': [ - '/_update_by_query/{task_id}/_rethrottle' + '/_update_by_query/{task_id}/_rethrottle', + '/_delete_by_query/{task_id}/_rethrottle' ] } } From 68a8f712c8b3d10bf8a12da90bdafd55dad1a6d9 Mon Sep 17 00:00:00 2001 From: spalger Date: Thu, 19 May 2016 07:52:01 -0700 Subject: [PATCH 06/15] fix eslint errors --- .eslintignore | 3 + package.json | 3 +- scripts/Version.js | 4 +- scripts/_spawn.js | 2 +- scripts/ci.js | 48 ++++++++------ scripts/generate/index.js | 4 +- scripts/generate/js_api.js | 2 +- scripts/generate/overrides.js | 2 + scripts/generate/templates/index.js | 22 +++---- scripts/generate/yaml_tests.js | 2 +- scripts/release/bower.js | 2 +- src/elasticsearch.jquery.js | 2 +- test/fixtures/keepalive_server.js | 2 +- test/integration/yaml_suite/client_manager.js | 3 +- test/integration/yaml_suite/run.js | 2 +- test/integration/yaml_suite/yaml_doc.js | 66 +++++++++---------- test/integration/yaml_suite/yaml_file.js | 2 +- test/mocks/browser_http.js | 2 +- test/mocks/browser_server.js | 20 +++--- test/mocks/incomming_message.js | 2 +- test/mocks/writable_stream.js | 2 +- test/unit/browser_builds/angular.js | 2 +- test/unit/browser_builds/generic.js | 2 +- test/unit/browser_builds/jquery.js | 2 +- test/unit/buffer_flush_tests.js | 2 +- test/unit/coverage.js | 4 +- test/unit/generic_logger_tests.js | 2 +- test/unit/index.js | 2 +- test/unit/specs/abstract_logger.js | 2 +- test/unit/specs/client.js | 2 +- test/unit/specs/client_action.js | 4 +- test/unit/specs/connection_abstract.js | 5 +- test/unit/specs/connection_pool.js | 10 +-- test/unit/specs/host.js | 8 +-- test/unit/specs/http_connector.js | 6 +- test/unit/specs/json_serializer.js | 2 +- test/unit/specs/log.js | 4 +- test/unit/specs/nodes_to_host_callback.js | 3 +- test/unit/specs/transport.js | 26 ++++---- test/unit/specs/utils.js | 11 ++-- test/unit/specs/yaml_test_reader.js | 2 +- test/utils/auto_release_stub.js | 2 +- test/utils/expect_sub_object.js | 2 +- test/utils/jenkins-reporter.js | 4 +- test/utils/make_j_unit_xml.js | 6 +- test/utils/server.js | 7 +- test/utils/slk.js | 2 +- 47 files changed, 165 insertions(+), 156 deletions(-) create mode 100644 .eslintignore diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 000000000..1fa83a552 --- /dev/null +++ b/.eslintignore @@ -0,0 +1,3 @@ +src/_* +src/bower_es_js +src/lib/apis diff --git a/package.json b/package.json index e9a7f2c56..d671ab364 100644 --- a/package.json +++ b/package.json @@ -107,7 +107,8 @@ "scripts": { "test": "grunt test", "generate": "node scripts/generate", - "grunt": "grunt" + "grunt": "grunt", + "eslint": "eslint src scripts test" }, "engines": { "node": ">=0.8" diff --git a/scripts/Version.js b/scripts/Version.js index abaf6bed9..d7f08b029 100644 --- a/scripts/Version.js +++ b/scripts/Version.js @@ -1,6 +1,6 @@ var _ = require('lodash-migrate'); -var package = require('../package.json'); -var branches = package.config.supported_es_branches; +var pkg = require('../package.json'); +var branches = pkg.config.supported_es_branches; var semver = require('semver'); var maxMinorVersion = function (majorV) { diff --git a/scripts/_spawn.js b/scripts/_spawn.js index d5ed4e1e7..3efdd7d99 100644 --- a/scripts/_spawn.js +++ b/scripts/_spawn.js @@ -60,4 +60,4 @@ function _spawn(cmd, args, opts, cb) { _spawn.exec = function (cmd, opts, cb) { return _spawn('/bin/sh', ['-c', cmd], opts, cb); -}; \ No newline at end of file +}; diff --git a/scripts/ci.js b/scripts/ci.js index cf1fa7760..b1e35c405 100644 --- a/scripts/ci.js +++ b/scripts/ci.js @@ -23,7 +23,7 @@ var through2 = require('through2'); var map = require('through2-map'); var split = require('split'); var join = require('path').join; -var child_process = require('child_process'); +var cp = require('child_process'); var chalk = require('chalk'); var format = require('util').format; @@ -59,10 +59,10 @@ task('SAUCE_LABS', false, function () { return new Promise(function (resolve, reject) { // build the clients and start the server, once the server is ready call trySaucelabs() var serverTasks = ['browser_clients:build', 'run:browser_test_server:keepalive']; - spawn(GRUNT, serverTasks, function (cp) { + spawn(GRUNT, serverTasks, function (proc) { var toLines = split(); - cp.stdout + proc.stdout .pipe(toLines) .pipe(through2(function (line, enc, cb) { cb(); @@ -71,11 +71,11 @@ task('SAUCE_LABS', false, function () { trySaucelabs() - .finally(function () { cp && cp.kill(); }) + .finally(function () { if (proc) proc.kill(); }) .then(resolve, reject); - cp.on('exit', function () { cp = null; }); - cp.stdout.unpipe(toLines); + proc.on('exit', function () { proc = null; }); + proc.stdout.unpipe(toLines); toLines.end(); })); }) @@ -132,25 +132,30 @@ task('CHECK_COVERAGE', false, function () { execTask('SETUP', function () { return Promise.try(function readVersion() { if (!ENV.ES_V) { - if (ENV.ES_RELEASE) + if (ENV.ES_RELEASE) { return ['v' + ENV.ES_RELEASE, ENV.ES_RELEASE]; + } - if (ENV.ES_REF) + if (ENV.ES_REF) { return [ENV.ES_REF, null]; + } } var match; - if (match = ENV.ES_V.match(/^(.*)_nightly$/)) + if (match = ENV.ES_V.match(/^(.*)_nightly$/)) { return [match[1], null]; + } - if (/^(?:1\.\d+|0\.90)\..*$/.test(ENV.ES_V)) + if (/^(?:1\.\d+|0\.90)\..*$/.test(ENV.ES_V)) { return ['v' + ENV.ES_V, ENV.ES_V]; + } throw new Error('unable to parse ES_V ' + ENV.ES_V); }) .then(function readOtherConf(ver) { - if (!ver) + if (!ver) { throw new Error('Unable to run the ci script without at least an ES_REF or ES_RELEASE environment var.'); + } log('ES_PORT:', ENV.ES_PORT = parseInt(ENV.ES_PORT || 9400, 10)); log('ES_HOST:', ENV.ES_HOST = ENV.ES_HOST || 'localhost'); @@ -162,8 +167,9 @@ execTask('SETUP', function () { else delete ENV.ES_RELEASE; }) .then(function readTasks() { - if (!ENV.RUN) + if (!ENV.RUN) { return _.where(TASKS, { default: true }); + } return ENV.RUN .split(',') @@ -196,7 +202,7 @@ execTask('SETUP', function () { }); }); -/****** +/** **** * utils ******/ function log() { @@ -275,25 +281,25 @@ function execTask(name, task) { function spawn(file, args, block) { return new Promise(function (resolve, reject) { - var cp = child_process.spawn(file, args, { + var proc = cp.spawn(file, args, { cwd: ROOT, env: ENV, stdio: [0, 'pipe', 'pipe'] }); - cp.stdout.pipe(taskOut, { end: false }); - cp.stderr.pipe(taskOut, { end: false }); + proc.stdout.pipe(taskOut, { end: false }); + proc.stderr.pipe(taskOut, { end: false }); var stdout = ''; - cp.stdout + proc.stdout .pipe(through2(function (chunk, enc, cb) { stdout += chunk; cb(); })); - block && block(cp); + if (block) block(proc); - cp.on('exit', function (code) { + proc.on('exit', function (code) { if (code > 0) { reject(new Error('non-zero exit code: ' + code)); } else { @@ -301,13 +307,13 @@ function spawn(file, args, block) { } }); - cp.on('error', function (origErr) { + proc.on('error', function (origErr) { reject(new Error('Unable to execute "' + file + ' ' + args.join(' ') + '": ' + origErr.message)); }); }); } -function node(/*args... */) { +function node(/* args... */) { return spawn( process.execPath, _.toArray(arguments) diff --git a/scripts/generate/index.js b/scripts/generate/index.js index 937039fa2..742b947b8 100644 --- a/scripts/generate/index.js +++ b/scripts/generate/index.js @@ -1,4 +1,4 @@ -/*jshint curly: false */ +/* jshint curly: false */ var async = require('async'); var fs = require('fs'); var spawn = require('../_spawn'); @@ -206,7 +206,7 @@ function createArchive(branch) { spawnStep('mkdir', [dir], paths.root), spawnStep('git', ['archive', '--format', 'tar', '--output', tarball, branch, specPathInRepo], paths.esSrc), spawnStep('tar', ['-x', '-f', tarball, '-C', dir, '--strip-components', subDirCount]), - spawnStep('rm', [tarball]) + spawnStep('rm', [tarball]) ], done); }; } diff --git a/scripts/generate/js_api.js b/scripts/generate/js_api.js index b7fe299ff..f374b003f 100644 --- a/scripts/generate/js_api.js +++ b/scripts/generate/js_api.js @@ -171,7 +171,7 @@ module.exports = function (branch, done) { ); } - function __puke__transformSpec(spec) { + function __puke__transformSpec(spec) { // eslint-disable-line var actions = []; // itterate all of the specs within the file, should only be one diff --git a/scripts/generate/overrides.js b/scripts/generate/overrides.js index 9dabbd4c3..f3ee815eb 100644 --- a/scripts/generate/overrides.js +++ b/scripts/generate/overrides.js @@ -187,6 +187,7 @@ module.exports = [ version: '>=1.6.0', // strange indentation makes pretty api files +/* eslint-disable */ clientActionModifier: function (spec) { return require('../utils').merge(spec, { @@ -198,6 +199,7 @@ function (spec) { } }); } +/* eslint-enable */ }, { diff --git a/scripts/generate/templates/index.js b/scripts/generate/templates/index.js index 21e8c872a..0f74000af 100644 --- a/scripts/generate/templates/index.js +++ b/scripts/generate/templates/index.js @@ -15,7 +15,7 @@ var path = require('path'); */ function stringify(thing, pretty) { return (pretty ? JSON.stringify(thing, null, ' ') : JSON.stringify(thing)) - .replace(/\'/g, '\\\'') + .replace(/'/g, '\\\'') .replace(/\\?"/g, function (quote) { // replace external (unescaped) double quotes with single quotes return quote === '\\"' ? '"' : '\''; @@ -70,16 +70,16 @@ var templateGlobals = { paramType: function (type) { switch (type && type.toLowerCase ? type.toLowerCase() : 'any') { - case 'time': - return 'Date, Number'; - case 'any': - return 'Anything'; - case 'enum': - return 'String'; - case 'list': - return 'String, String[], Boolean'; - default: - return _.ucfirst(type); + case 'time': + return 'Date, Number'; + case 'any': + return 'Anything'; + case 'enum': + return 'String'; + case 'list': + return 'String, String[], Boolean'; + default: + return _.ucfirst(type); } }, diff --git a/scripts/generate/yaml_tests.js b/scripts/generate/yaml_tests.js index eed151ee1..a3cdcda17 100644 --- a/scripts/generate/yaml_tests.js +++ b/scripts/generate/yaml_tests.js @@ -55,4 +55,4 @@ module.exports = function (branch, done) { console.log(chalk.white.bold('wrote') + ' YAML index to', file); done(); } -}; \ No newline at end of file +}; diff --git a/scripts/release/bower.js b/scripts/release/bower.js index 3ada9c4e3..e05b6432a 100644 --- a/scripts/release/bower.js +++ b/scripts/release/bower.js @@ -42,4 +42,4 @@ async.series([ console.log('Error: ', err.message ? err.message : err); } } -}); \ No newline at end of file +}); diff --git a/src/elasticsearch.jquery.js b/src/elasticsearch.jquery.js index 6d6cce7f9..740a2ee1f 100644 --- a/src/elasticsearch.jquery.js +++ b/src/elasticsearch.jquery.js @@ -19,4 +19,4 @@ return new es.Client(config); }; -}(jQuery)); \ No newline at end of file +}(jQuery)); diff --git a/test/fixtures/keepalive_server.js b/test/fixtures/keepalive_server.js index 7f92981d1..e0d365878 100644 --- a/test/fixtures/keepalive_server.js +++ b/test/fixtures/keepalive_server.js @@ -13,4 +13,4 @@ var server = require('http').createServer(app); server.listen(function () { var port = server.address().port; process.connected ? process.send(port) : console.log(port); -}); \ No newline at end of file +}); diff --git a/test/integration/yaml_suite/client_manager.js b/test/integration/yaml_suite/client_manager.js index 75437f360..4cc481a7b 100644 --- a/test/integration/yaml_suite/client_manager.js +++ b/test/integration/yaml_suite/client_manager.js @@ -55,7 +55,8 @@ module.exports = { function doCreateClient(options, cb) { if (typeof options === 'function') { - cb = options, options = {}; + cb = options; + options = {}; } var logConfig = {}; diff --git a/test/integration/yaml_suite/run.js b/test/integration/yaml_suite/run.js index 1ee63484c..9ec43a994 100644 --- a/test/integration/yaml_suite/run.js +++ b/test/integration/yaml_suite/run.js @@ -37,4 +37,4 @@ module.exports = function (branch) { }); }); -}; \ No newline at end of file +}; diff --git a/test/integration/yaml_suite/yaml_doc.js b/test/integration/yaml_suite/yaml_doc.js index 18fcc7b99..bb2299d08 100644 --- a/test/integration/yaml_suite/yaml_doc.js +++ b/test/integration/yaml_suite/yaml_doc.js @@ -26,10 +26,10 @@ var ES_VERSION = null; var versionExp = '((?:\\d+\\.){0,2}\\d+)(?:[\\.\\-]\\w+)?|'; // match all whitespace within a "regexp" match arg -var reWhitespace_RE = /\s+/g; +var reWhitespaceRE = /\s+/g; // match all comments within a "regexp" match arg -var reComments_RE = /([\S\s]?)#[^\n]*\n/g; +var reCommentsRE = /([\S\s]?)#[^\n]*\n/g; /** * Regular Expression to extract a version number from a string @@ -356,34 +356,34 @@ YamlDoc.prototype = { // resolve the catch arg to a value used for matching once the request is complete switch (args.catch) { - case void 0: - catcher = null; - break; - case 'missing': - catcher = 404; - break; - case 'conflict': - catcher = 409; - break; - case 'forbidden': - catcher = 403; - break; - case 'request_timeout': - catcher = 408; - break; - case 'request': - catcher = /.*/; - break; - case 'param': - catcher = TypeError; - break; - default: - catcher = args.catch.match(/^\/(.*)\/$/); - if (catcher) { - catcher = new RegExp(catcher[1]); - } else { - return done(new TypeError('unsupported catch type ' + args.catch)); - } + case void 0: + catcher = null; + break; + case 'missing': + catcher = 404; + break; + case 'conflict': + catcher = 409; + break; + case 'forbidden': + catcher = 403; + break; + case 'request_timeout': + catcher = 408; + break; + case 'request': + catcher = /.*/; + break; + case 'param': + catcher = TypeError; + break; + default: + catcher = args.catch.match(/^\/(.*)\/$/); + if (catcher) { + catcher = new RegExp(catcher[1]); + } else { + return done(new TypeError('unsupported catch type ' + args.catch)); + } } delete args.catch; @@ -448,7 +448,7 @@ YamlDoc.prototype = { } var timeoutId; - var cb = _.bind(function (error, body) { + var cb = _.bind(function (error, body) { this._last_requests_response = body; clearTimeout(timeoutId); @@ -588,7 +588,7 @@ YamlDoc.prototype = { // convert the matcher into a compatible string for building a regexp maybeRE = match // replace comments, but allow the # to be escaped like \# - .replace(reComments_RE, function (match, prevChar) { + .replace(reCommentsRE, function (match, prevChar) { if (prevChar === '\\') { return match; } else { @@ -597,7 +597,7 @@ YamlDoc.prototype = { }) // remove all whitespace from the expression, all meaningful // whitespace is represented with \s - .replace(reWhitespace_RE, ''); + .replace(reWhitespaceRE, ''); var startsWithSlash = maybeRE[0] === '/'; var endsWithSlash = maybeRE[maybeRE.length - 1] === '/'; diff --git a/test/integration/yaml_suite/yaml_file.js b/test/integration/yaml_suite/yaml_file.js index 1035a37ec..b96529fc6 100644 --- a/test/integration/yaml_suite/yaml_file.js +++ b/test/integration/yaml_suite/yaml_file.js @@ -19,7 +19,7 @@ function YamlFile(filename, docs) { describe(filename, function () { file.docs = _.map(docs, function (doc) { - doc = new YamlDoc(doc, file); + doc = new YamlDoc(doc, file); if (doc.description === 'setup') { beforeEach(/* doc */function (done) { async.series(doc.getActionsRunners(), done); diff --git a/test/mocks/browser_http.js b/test/mocks/browser_http.js index 135d6ecc7..00d6cdb8b 100644 --- a/test/mocks/browser_http.js +++ b/test/mocks/browser_http.js @@ -1,4 +1,4 @@ - +/* eslint-disable */ ////////////// /// Extended version of: /// https://github.com/philikon/MockHttpRequest/ diff --git a/test/mocks/browser_server.js b/test/mocks/browser_server.js index 36babae1a..a10435cce 100644 --- a/test/mocks/browser_server.js +++ b/test/mocks/browser_server.js @@ -57,15 +57,15 @@ var mockNock = module.exports = function (url) { req.status = status; req.body = body; switch (typeof req.body) { - case 'string': - case 'number': - break; - default: - try { - req.body = req.body && JSON.stringify(req.body); - } catch (e) { - req.body = req.body; - } + case 'string': + case 'number': + break; + default: + try { + req.body = req.body && JSON.stringify(req.body); + } catch (e) { + req.body = req.body; + } } interceptors.push(req); return mockNock(url); @@ -80,4 +80,4 @@ mockNock.done = function () { if (interceptors.length) { throw new Error('Some interceptors were not called: ' + JSON.stringify(interceptors)); } -}; \ No newline at end of file +}; diff --git a/test/mocks/incomming_message.js b/test/mocks/incomming_message.js index 2cca8809d..ce29326cd 100644 --- a/test/mocks/incomming_message.js +++ b/test/mocks/incomming_message.js @@ -32,4 +32,4 @@ util.inherits(MockIncommingMessage, Readable); * } * incom.push(null); * }); - */ \ No newline at end of file + */ diff --git a/test/mocks/writable_stream.js b/test/mocks/writable_stream.js index e20239af0..1907b233c 100644 --- a/test/mocks/writable_stream.js +++ b/test/mocks/writable_stream.js @@ -75,4 +75,4 @@ if (Writable) { // There is no shutdown() for files. MockWritableStream.prototype.destroySoon = MockWritableStream.prototype.end; -} \ No newline at end of file +} diff --git a/test/unit/browser_builds/angular.js b/test/unit/browser_builds/angular.js index ed6b2d974..13eafe14f 100644 --- a/test/unit/browser_builds/angular.js +++ b/test/unit/browser_builds/angular.js @@ -82,4 +82,4 @@ describe('Angular esFactory', function () { return prom; }); }); -}); \ No newline at end of file +}); diff --git a/test/unit/browser_builds/generic.js b/test/unit/browser_builds/generic.js index 4deec0163..e523fe7c9 100644 --- a/test/unit/browser_builds/generic.js +++ b/test/unit/browser_builds/generic.js @@ -17,4 +17,4 @@ describe('elasticsearch namespace', function () { expect(client.transport).to.be.a(es.Transport); client.close(); }); -}); \ No newline at end of file +}); diff --git a/test/unit/browser_builds/jquery.js b/test/unit/browser_builds/jquery.js index 0a0e3724e..42156c37b 100644 --- a/test/unit/browser_builds/jquery.js +++ b/test/unit/browser_builds/jquery.js @@ -16,4 +16,4 @@ describe('jQuery.es namespace', function () { expect(client.transport).to.be.a($.es.Transport); client.close(); }); -}); \ No newline at end of file +}); diff --git a/test/unit/buffer_flush_tests.js b/test/unit/buffer_flush_tests.js index d00f75b4d..2d2adf004 100644 --- a/test/unit/buffer_flush_tests.js +++ b/test/unit/buffer_flush_tests.js @@ -57,4 +57,4 @@ module.exports = function (makeLogger) { }); } }); -}; \ No newline at end of file +}; diff --git a/test/unit/coverage.js b/test/unit/coverage.js index 63b4fbd9b..a59557d9d 100644 --- a/test/unit/coverage.js +++ b/test/unit/coverage.js @@ -1,5 +1,5 @@ -var blanket = require("blanket")({ +var blanket = require('blanket')({ pattern: require('path').join(__dirname, '../../src') }); -require('./index'); \ No newline at end of file +require('./index'); diff --git a/test/unit/generic_logger_tests.js b/test/unit/generic_logger_tests.js index f9f3ed834..42f788ceb 100644 --- a/test/unit/generic_logger_tests.js +++ b/test/unit/generic_logger_tests.js @@ -234,4 +234,4 @@ module.exports = function (makeLogger) { expect(logger.write.callCount).to.eql(1); }); }); -}; \ No newline at end of file +}; diff --git a/test/unit/index.js b/test/unit/index.js index 8f437dc25..ed696a9c4 100644 --- a/test/unit/index.js +++ b/test/unit/index.js @@ -3,4 +3,4 @@ require('bluebird').longStackTraces(); var specDir = __dirname + '/specs'; require('fs').readdirSync(specDir).forEach(function (file) { require(specDir + '/' + file); -}); \ No newline at end of file +}); diff --git a/test/unit/specs/abstract_logger.js b/test/unit/specs/abstract_logger.js index 45158a9ba..577c0fc9f 100644 --- a/test/unit/specs/abstract_logger.js +++ b/test/unit/specs/abstract_logger.js @@ -32,4 +32,4 @@ describe('Logger Abstract', function () { require('../generic_logger_tests')(makeLogger); -}); \ No newline at end of file +}); diff --git a/test/unit/specs/client.js b/test/unit/specs/client.js index 4d7c59275..0be3338f5 100644 --- a/test/unit/specs/client.js +++ b/test/unit/specs/client.js @@ -68,7 +68,7 @@ describe('Client instances creation', function () { } util.inherits(NullStream, stream.Writable); - NullStream.prototype._write = function(/* chunk, encoding, next */) { + NullStream.prototype._write = function (/* chunk, encoding, next */) { done(); }; diff --git a/test/unit/specs/client_action.js b/test/unit/specs/client_action.js index 0b2bc76f2..82f4be8a0 100644 --- a/test/unit/specs/client_action.js +++ b/test/unit/specs/client_action.js @@ -195,7 +195,7 @@ describe('Client Action runner', function () { it('rejects array', function (done) { action({ one: ['one'], - two: [ 1304 ] + two: [1304] }, function (err, params) { expect(err).to.be.a(TypeError); done(); @@ -629,7 +629,7 @@ describe('Client Action runner', function () { method: 'POST' }); - action({method: 'get'}, function (err, params) { + action({ method: 'get' }, function (err, params) { expect(params.method).to.be('GET'); done(); }); diff --git a/test/unit/specs/connection_abstract.js b/test/unit/specs/connection_abstract.js index 4f4a91cb6..e05bf1c0d 100644 --- a/test/unit/specs/connection_abstract.js +++ b/test/unit/specs/connection_abstract.js @@ -17,11 +17,11 @@ describe('Connection Abstract', function () { it('requires a valid host', function () { expect(function () { - new ConnectionAbstract(); + var conn = new ConnectionAbstract(); }).to.throwError(TypeError); expect(function () { - new ConnectionAbstract({}); + var conn = new ConnectionAbstract({}); }).to.throwError(TypeError); }); @@ -81,7 +81,6 @@ describe('Connection Abstract', function () { it('calls it\'s own request method', function () { var conn = new ConnectionAbstract(host); - var football = {}; stub(conn, 'request'); conn.ping(); expect(conn.request.callCount).to.eql(1); diff --git a/test/unit/specs/connection_pool.js b/test/unit/specs/connection_pool.js index b4f9d92ff..ccfd73261 100644 --- a/test/unit/specs/connection_pool.js +++ b/test/unit/specs/connection_pool.js @@ -1,6 +1,5 @@ var ConnectionPool = require('../../../src/lib/connection_pool'); var Host = require('../../../src/lib/host'); -var errors = require('../../../src/lib/errors'); var ConnectionAbstract = require('../../../src/lib/connection'); var _ = require('lodash-migrate'); var EventEmitter = require('events').EventEmitter; @@ -121,7 +120,7 @@ describe('Connection Pool', function () { }); it('detects if the selector is not async', function (done) { - pool.selector = function (list) { + pool.selector = function () { expect(arguments.length).to.be(1); }; @@ -149,11 +148,11 @@ describe('Connection Pool', function () { }); it('should catch errors in sync selectors', function (done) { - pool.selector = function (list) { + pool.selector = function () { return JSON.notAMethod(); }; - pool.select(function (err, selection) { + pool.select(function (err) { expect(err).be.an(Error); done(); }); @@ -297,7 +296,8 @@ describe('Connection Pool', function () { var result = pool.getConnections(); expect(result.length).to.be(1000); expect(_.reduce(result, function (sum, num) { - return sum += num; + sum += num + return sum; }, 0)).to.eql(499500); }); }); diff --git a/test/unit/specs/host.js b/test/unit/specs/host.js index f0e4033c7..9bef6bde8 100644 --- a/test/unit/specs/host.js +++ b/test/unit/specs/host.js @@ -32,7 +32,7 @@ describe('Host class', function () { }); it('accepts a string for query', function () { - var host = new Host({ query: 'beep=boop'}); + var host = new Host({ query: 'beep=boop' }); expect(host.query).to.eql({ beep: 'boop' @@ -157,14 +157,14 @@ describe('Host class', function () { var host = new Host(); host.path = 'prefix'; - expect(host.makeUrl({ path: '/this and that'})) + expect(host.makeUrl({ path: '/this and that' })) .to.be('http://localhost:9200/prefix/this and that'); }); it('does not try to prevent double forward-slashes', function () { var host = new Host({ path: 'prefix/' }); - expect(host.makeUrl({ path: '/this and that'})) + expect(host.makeUrl({ path: '/this and that' })) .to.be('http://localhost:9200/prefix//this and that'); }); @@ -175,7 +175,7 @@ describe('Host class', function () { host = new Host({ host: 'john', port: 80 }); expect(host.makeUrl()).to.be('http://john/'); - host = new Host({ host: 'italy', path: '/pie', auth: 'user:pass'}); + host = new Host({ host: 'italy', path: '/pie', auth: 'user:pass' }); expect(host.makeUrl()).to.be('http://italy:9200/pie'); }); diff --git a/test/unit/specs/http_connector.js b/test/unit/specs/http_connector.js index 47245e0f8..64825831a 100644 --- a/test/unit/specs/http_connector.js +++ b/test/unit/specs/http_connector.js @@ -324,7 +324,7 @@ describe('Http Connector', function () { zlib.gzip(body, function (err, compressedBody) { server .get('/users/1') - .reply(200, compressedBody, {'Content-Encoding': 'gzip'}); + .reply(200, compressedBody, { 'Content-Encoding': 'gzip' }); con.request({ method: 'GET', @@ -350,7 +350,7 @@ describe('Http Connector', function () { zlib.deflate(body, function (err, compressedBody) { server .get('/users/1') - .reply(200, compressedBody, {'Content-Encoding': 'deflate'}); + .reply(200, compressedBody, { 'Content-Encoding': 'deflate' }); con.request({ method: 'GET', @@ -371,7 +371,7 @@ describe('Http Connector', function () { var body = 'blah'; server .get('/users/1') - .reply(200, body, {'Content-Encoding': 'gzip'}); + .reply(200, body, { 'Content-Encoding': 'gzip' }); con.request({ method: 'GET', diff --git a/test/unit/specs/json_serializer.js b/test/unit/specs/json_serializer.js index 0ec2f9e5c..9a876ba0f 100644 --- a/test/unit/specs/json_serializer.js +++ b/test/unit/specs/json_serializer.js @@ -97,4 +97,4 @@ describe('JSON serializer', function () { }).to.throwError(); }); }); -}); \ No newline at end of file +}); diff --git a/test/unit/specs/log.js b/test/unit/specs/log.js index 9cc6e38a1..aa5dab6e0 100644 --- a/test/unit/specs/log.js +++ b/test/unit/specs/log.js @@ -141,7 +141,7 @@ describe('Log class', function () { log.emit = function (eventName) { call = { - event : eventName, + event: eventName, args: Array.prototype.slice.call(arguments, 1) }; }; @@ -221,7 +221,7 @@ describe('Log class', function () { }); it('accepts an array of output config objects', function () { - var log = new Log({ log: [{ level: 'error' }, { level: 'trace'}] }); + var log = new Log({ log: [{ level: 'error' }, { level: 'trace' }] }); expect(log.listenerCount('error')).to.eql(2); expect(log.listenerCount('warning')).to.eql(1); expect(log.listenerCount('info')).to.eql(1); diff --git a/test/unit/specs/nodes_to_host_callback.js b/test/unit/specs/nodes_to_host_callback.js index 2f52b4bd3..c8830f9c4 100644 --- a/test/unit/specs/nodes_to_host_callback.js +++ b/test/unit/specs/nodes_to_host_callback.js @@ -61,7 +61,6 @@ describe('Nodes to host callback', function () { }); - it('ignores hosts that don\'t have an http_host property', function () { var hosts = callback({ node_id: { @@ -74,7 +73,7 @@ describe('Nodes to host callback', function () { it('throws an error when the host property is not formatted properly', function () { expect(function () { - var hosts = callback({ + callback({ node_id: { http_address: 'not actually an http host' } diff --git a/test/unit/specs/transport.js b/test/unit/specs/transport.js index c8aa567f2..4b99845ea 100644 --- a/test/unit/specs/transport.js +++ b/test/unit/specs/transport.js @@ -1,7 +1,6 @@ var Transport = require('../../../src/lib/transport'); var Host = require('../../../src/lib/host'); var errors = require('../../../src/lib/errors'); -var Promise = require('bluebird'); var sinon = require('sinon'); var expect = require('expect.js'); @@ -354,10 +353,10 @@ describe('Transport Class', function () { }); it('logs an error if nodes to host throws one', function (done) { - trans.nodesToHostCallback = function (nodes) { + trans.nodesToHostCallback = function () { throw new Error('I failed'); }; - trans.log.error = function (err) { + trans.log.error = function () { done(); }; trans.sniff(); @@ -408,7 +407,7 @@ describe('Transport Class', function () { }); }); it('passed back the full server response', function (done) { - trans.sniff(function (err, resp, status) { + trans.sniff(function (err, resp) { expect(resp.ok).to.eql(true); expect(resp.cluster_name).to.eql('clustername'); done(); @@ -501,7 +500,7 @@ describe('Transport Class', function () { }); var conn = getConnection(trans); var body = [ - { _id: 'simple body'}, + { _id: 'simple body' }, { name: 'ഢധയമബ' } ]; @@ -526,7 +525,7 @@ describe('Transport Class', function () { var trans = new Transport({ hosts: 'localhost' }); - var conn = getConnection(trans); + getConnection(trans); var body = { _id: 'circular body' }; @@ -560,7 +559,7 @@ describe('Transport Class', function () { } }); - trans.request({}, function (err, body, status) { + trans.request({}, function (err) { expect(err.message).to.eql('I am broken'); }); }); @@ -574,7 +573,7 @@ describe('Transport Class', function () { } }); - trans.request({}, function (err, body, status) { + trans.request({}, function (err) { expect(err.message).to.eql('I am broken'); }); }); @@ -638,7 +637,6 @@ describe('Transport Class', function () { }); - describe('return value', function () { it('returns an object with an abort() method when a callback is sent', function () { var tran = new Transport(); @@ -681,7 +679,7 @@ describe('Transport Class', function () { expect(process.domain).to.be(null); var tran = new Transport(); shortCircuitRequest(tran); - tran.request({}, function(err, result, status) { + tran.request({}, function () { expect(process.domain).to.be(null); }); }); @@ -689,12 +687,12 @@ describe('Transport Class', function () { it('binds the callback to the correct domain', function () { expect(process.domain).to.be(null); var domain = require('domain').create(); - domain.run(function() { + domain.run(function () { var tran = new Transport(); shortCircuitRequest(tran); expect(process.domain).not.to.be(null); var startingDomain = process.domain - tran.request({}, function(err, result, status) { + tran.request({}, function () { expect(process.domain).not.to.be(null); expect(process.domain).to.be(startingDomain); process.domain.exit(); @@ -758,7 +756,6 @@ describe('Transport Class', function () { var clock = sinon.useFakeTimers('setTimeout', 'clearTimeout'); stub.autoRelease(clock); var tran = new Transport({}); - var err; var prom = tran.request({}); // disregard promise, prevent bluebird's warnings @@ -776,7 +773,6 @@ describe('Transport Class', function () { var tran = new Transport({ requestTimeout: 5000 }); - var err; var prom = tran.request({}); // disregard promise, prevent bluebird's warnings @@ -799,7 +795,7 @@ describe('Transport Class', function () { tran.request({ requestTimeout: falsy - }, function (_err) {}); + }, function () {}); expect(_.size(clock.timers)).to.eql(0); }); diff --git a/test/unit/specs/utils.js b/test/unit/specs/utils.js index fe1b73d9d..0c6f6fcfc 100644 --- a/test/unit/specs/utils.js +++ b/test/unit/specs/utils.js @@ -32,7 +32,7 @@ describe('Utils', function () { } }, function (thing, name) { - describe('#isArrayOf' + name, function (test) { + describe('#isArrayOf' + name, function () { it('likes arrays of ' + name, function () { expect(_['isArrayOf' + name + 's'](thing.is)).to.be(true); }); @@ -54,7 +54,6 @@ describe('Utils', function () { expect(_.isNumeric(0)).to.be(true); expect(_.isNumeric(32)).to.be(true); expect(_.isNumeric('040')).to.be(true); - expect(_.isNumeric(0144)).to.be(true); expect(_.isNumeric('0xFF')).to.be(true); expect(_.isNumeric(0xFFF)).to.be(true); }); @@ -196,7 +195,7 @@ describe('Utils', function () { }); it('sorta kinda works on objects', function () { - expect(_.toLowerString({a: 'thing'})).to.eql('[object object]'); + expect(_.toLowerString({ a: 'thing' })).to.eql('[object object]'); }); }); @@ -216,7 +215,7 @@ describe('Utils', function () { }); it('sorta kinda works on objects', function () { - expect(_.toUpperString({a: 'thing'})).to.eql('[OBJECT OBJECT]'); + expect(_.toUpperString({ a: 'thing' })).to.eql('[OBJECT OBJECT]'); }); }); @@ -268,7 +267,7 @@ describe('Utils', function () { foo: ['bax', 'boz'] } }; - _.deepMerge(obj, { bax: { foo: ['poo'] }}); + _.deepMerge(obj, { bax: { foo: ['poo'] } }); expect(obj.bax.foo).to.have.length(3); }); @@ -282,7 +281,7 @@ describe('Utils', function () { expect(out).to.not.be(inp); }); it('accepts a primitive value and calls the the transform function', function (done) { - var out = _.createArray('str', function (val) { + _.createArray('str', function (val) { expect(val).to.be('str'); done(); }); diff --git a/test/unit/specs/yaml_test_reader.js b/test/unit/specs/yaml_test_reader.js index 0c241949a..4e101c1df 100644 --- a/test/unit/specs/yaml_test_reader.js +++ b/test/unit/specs/yaml_test_reader.js @@ -19,4 +19,4 @@ describe('Yaml Test Reader', function () { expect(compare('0.90 - 1.2', '1.4')).to.be(false); }); }); -}); \ No newline at end of file +}); diff --git a/test/utils/auto_release_stub.js b/test/utils/auto_release_stub.js index ce66cbf02..7ae531de7 100644 --- a/test/utils/auto_release_stub.js +++ b/test/utils/auto_release_stub.js @@ -18,4 +18,4 @@ exports.make = function () { }; return stubber; -}; \ No newline at end of file +}; diff --git a/test/utils/expect_sub_object.js b/test/utils/expect_sub_object.js index d4c61a0f1..f5c8f0e32 100644 --- a/test/utils/expect_sub_object.js +++ b/test/utils/expect_sub_object.js @@ -9,4 +9,4 @@ module.exports = function expectSubObject(obj, subObj) { expect(obj).property(prop, val); } }); -}; \ No newline at end of file +}; diff --git a/test/utils/jenkins-reporter.js b/test/utils/jenkins-reporter.js index 5d2208013..4516020d6 100644 --- a/test/utils/jenkins-reporter.js +++ b/test/utils/jenkins-reporter.js @@ -22,7 +22,7 @@ var log = (function () { } locked(str); }; -})(); +}()); var integration = _.find(process.argv, function (arg) { return arg.indexOf('test/integration') > -1; }); var unit = _.find(process.argv, function (arg) { return arg.indexOf('test/unit') > -1; }); @@ -86,7 +86,7 @@ function JenkinsReporter(runner) { stack.shift(); }); - runner.on('fail', function (test, err) { + runner.on('fail', function (test) { if ('hook' === test.type) { runner.emit('test end', test); } diff --git a/test/utils/make_j_unit_xml.js b/test/utils/make_j_unit_xml.js index b87831667..f8a800e99 100644 --- a/test/utils/make_j_unit_xml.js +++ b/test/utils/make_j_unit_xml.js @@ -41,7 +41,7 @@ function makeJUnitXml(runnerName, testDetails) { timestamp: moment(suiteInfo.start).toJSON(), hostname: 'localhost', tests: (suiteInfo.results && suiteInfo.results.length) || 0, - failures: _.where(suiteInfo.results, {pass: false}).length, + failures: _.where(suiteInfo.results, { pass: false }).length, errors: 0, time: suiteInfo.time / 1000 }); @@ -89,7 +89,7 @@ function makeJUnitXml(runnerName, testDetails) { giveOutput(suite, suiteInfo); }); - return suites.toString({ pretty: true}); + return suites.toString({ pretty: true }); } function giveOutput(el, info) { @@ -103,4 +103,4 @@ function giveOutput(el, info) { if (err) { el.ele('system-err', {}).cdata(chalk.stripColor(err)); } -} \ No newline at end of file +} diff --git a/test/utils/server.js b/test/utils/server.js index 88b7e07d8..1b23024b8 100644 --- a/test/utils/server.js +++ b/test/utils/server.js @@ -1,3 +1,4 @@ +/* eslint-disable import/no-unresolved */ var express = require('express'); var http = require('http'); var fs = require('fs'); @@ -31,6 +32,8 @@ testFiles.build = fs.readdirSync(browserBuildsDir) if (file.substr(-3) === '.js') { return browserBuildsDir + '/' + file; } + + return null }) .filter(Boolean); @@ -73,7 +76,7 @@ function bundleTests(name) { // create a route that just rends a specific file (like a symlink or something) function sendFile(file) { - return function (req, res, next) { + return function (req, res) { res.sendfile(file); }; } @@ -111,4 +114,4 @@ app http.createServer(app).listen(8000, function () { console.log('listening on port 8000'); -}); \ No newline at end of file +}); diff --git a/test/utils/slk.js b/test/utils/slk.js index e2764ba8b..0b95154c4 100644 --- a/test/utils/slk.js +++ b/test/utils/slk.js @@ -3,4 +3,4 @@ module.exports = JSON.parse(new Buffer( 'eyJ1c2VyIjoiZWxhc3RpY3NlYXJjaC1qcyIsImtleSI6IjI0ZjQ5ZTA3LWQ4MmYtNDA2Ny04NTRlLWQ4MTVlYmQxNWU0NiJ9', 'base64' -).toString('utf8')); \ No newline at end of file +).toString('utf8')); From ae615a0f2d20904ed21b726326ce9ee04a466bfb Mon Sep 17 00:00:00 2001 From: spalger Date: Thu, 19 May 2016 08:42:31 -0700 Subject: [PATCH 07/15] [apis] regenerate --- src/lib/apis/master.js | 251 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 251 insertions(+) diff --git a/src/lib/apis/master.js b/src/lib/apis/master.js index 17202f02e..7a58870e4 100644 --- a/src/lib/apis/master.js +++ b/src/lib/apis/master.js @@ -1661,6 +1661,257 @@ api['delete'] = ca({ method: 'DELETE' }); +/** + * Perform a [deleteByQuery](https://www.elastic.co/guide/en/elasticsearch/plugins/master/plugins-reindex.html) request + * + * @param {Object} params - An object with parameters used to carry out this action + * @param {String} params.analyzer - The analyzer to use for the query string + * @param {Boolean} params.analyzeWildcard - Specify whether wildcard and prefix queries should be analyzed (default: false) + * @param {String} [params.defaultOperator=OR] - The default operator for query string query (AND or OR) + * @param {String} params.df - The field to use as default where no field prefix is given in the query string + * @param {Boolean} params.explain - Specify whether to return detailed information about score computation as part of a hit + * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return as part of a hit + * @param {String, String[], Boolean} params.fielddataFields - A comma-separated list of fields to return as the field data representation of a field for each hit + * @param {Number} params.from - Starting offset (default: 0) + * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) + * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) + * @param {String} [params.conflicts=abort] - What to do when the delete-by-query hits version conflicts? + * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. + * @param {Boolean} params.lenient - Specify whether format-based query failures (such as providing text to a numeric field) should be ignored + * @param {Boolean} params.lowercaseExpandedTerms - Specify whether query terms should be lowercased + * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) + * @param {String} params.q - Query in the Lucene query string syntax + * @param {String, String[], Boolean} params.routing - A comma-separated list of specific routing values + * @param {Duration} params.scroll - Specify how long a consistent view of the index should be maintained for scrolled search + * @param {String} params.searchType - Search operation type + * @param {Date, Number} params.searchTimeout - Explicit timeout for each search request. Defaults to no timeout. + * @param {Number} params.size - Number of hits to return (default: 10) + * @param {String, String[], Boolean} params.sort - A comma-separated list of : pairs + * @param {String, String[], Boolean} params._source - True or false to return the _source field or not, or a list of fields to return + * @param {String, String[], Boolean} params._sourceExclude - A list of fields to exclude from the returned _source field + * @param {String, String[], Boolean} params._sourceInclude - A list of fields to extract and return from the _source field + * @param {Number} params.terminateAfter - The maximum number of documents to collect for each shard, upon reaching which the query execution will terminate early. + * @param {String, String[], Boolean} params.stats - Specific 'tag' of the request for logging and statistical purposes + * @param {String} params.suggestField - Specify which field to use for suggestions + * @param {String} [params.suggestMode=missing] - Specify suggest mode + * @param {Number} params.suggestSize - How many suggestions to return in response + * @param {Text} params.suggestText - The source text for which the suggestions should be returned + * @param {Date, Number} [params.timeout=1m] - Time each individual bulk request should wait for shards that are unavailable. + * @param {Boolean} params.trackScores - Whether to calculate and return scores even if they are not used for sorting + * @param {Boolean} params.version - Specify whether to return document version as part of a hit + * @param {Boolean} params.requestCache - Specify if request cache should be used for this request or not, defaults to index level setting + * @param {Boolean} params.refresh - Should the effected indexes be refreshed? + * @param {String} params.consistency - Explicit write consistency setting for the operation + * @param {Integer} params.scrollSize - Size on the scroll request powering the update_by_query + * @param {Boolean} params.waitForCompletion - Should the request should block until the delete-by-query is complete. + * @param {Float} params.requestsPerSecond - The throttle for this request in sub-requests per second. 0 means set no throttle. + * @param {String, String[], Boolean} params.index - A comma-separated list of index names to search; use `_all` or empty string to perform the operation on all indices + * @param {String, String[], Boolean} params.type - A comma-separated list of document types to search; leave empty to perform the operation on all types + */ +api.deleteByQuery = ca({ + params: { + analyzer: { + type: 'string' + }, + analyzeWildcard: { + type: 'boolean', + name: 'analyze_wildcard' + }, + defaultOperator: { + type: 'enum', + 'default': 'OR', + options: [ + 'AND', + 'OR' + ], + name: 'default_operator' + }, + df: { + type: 'string' + }, + explain: { + type: 'boolean' + }, + fields: { + type: 'list' + }, + fielddataFields: { + type: 'list', + name: 'fielddata_fields' + }, + from: { + type: 'number' + }, + ignoreUnavailable: { + type: 'boolean', + name: 'ignore_unavailable' + }, + allowNoIndices: { + type: 'boolean', + name: 'allow_no_indices' + }, + conflicts: { + type: 'enum', + 'default': 'abort', + options: [ + 'abort', + 'proceed' + ] + }, + expandWildcards: { + type: 'enum', + 'default': 'open', + options: [ + 'open', + 'closed', + 'none', + 'all' + ], + name: 'expand_wildcards' + }, + lenient: { + type: 'boolean' + }, + lowercaseExpandedTerms: { + type: 'boolean', + name: 'lowercase_expanded_terms' + }, + preference: { + type: 'string' + }, + q: { + type: 'string' + }, + routing: { + type: 'list' + }, + scroll: { + type: 'duration' + }, + searchType: { + type: 'enum', + options: [ + 'query_then_fetch', + 'dfs_query_then_fetch' + ], + name: 'search_type' + }, + searchTimeout: { + type: 'time', + name: 'search_timeout' + }, + size: { + type: 'number' + }, + sort: { + type: 'list' + }, + _source: { + type: 'list' + }, + _sourceExclude: { + type: 'list', + name: '_source_exclude' + }, + _sourceInclude: { + type: 'list', + name: '_source_include' + }, + terminateAfter: { + type: 'number', + name: 'terminate_after' + }, + stats: { + type: 'list' + }, + suggestField: { + type: 'string', + name: 'suggest_field' + }, + suggestMode: { + type: 'enum', + 'default': 'missing', + options: [ + 'missing', + 'popular', + 'always' + ], + name: 'suggest_mode' + }, + suggestSize: { + type: 'number', + name: 'suggest_size' + }, + suggestText: { + type: 'text', + name: 'suggest_text' + }, + timeout: { + type: 'time', + 'default': '1m' + }, + trackScores: { + type: 'boolean', + name: 'track_scores' + }, + version: { + type: 'boolean' + }, + requestCache: { + type: 'boolean', + name: 'request_cache' + }, + refresh: { + type: 'boolean' + }, + consistency: { + type: 'enum', + options: [ + 'one', + 'quorum', + 'all' + ] + }, + scrollSize: { + type: 'integer', + name: 'scroll_size' + }, + waitForCompletion: { + type: 'boolean', + 'default': false, + name: 'wait_for_completion' + }, + requestsPerSecond: { + type: 'float', + 'default': 0, + name: 'requests_per_second' + } + }, + urls: [ + { + fmt: '/<%=index%>/<%=type%>/_delete_by_query', + req: { + index: { + type: 'list' + }, + type: { + type: 'list' + } + } + }, + { + fmt: '/<%=index%>/_delete_by_query', + req: { + index: { + type: 'list' + } + } + } + ], + needBody: true, + method: 'POST' +}); + /** * Perform a [deleteScript](http://www.elastic.co/guide/en/elasticsearch/reference/master/modules-scripting.html) request * From b2929de9d546da6075f2a23a23e36e1002ddf53e Mon Sep 17 00:00:00 2001 From: spalger Date: Thu, 19 May 2016 08:43:19 -0700 Subject: [PATCH 08/15] _.contains -> _.includes --- scripts/generate/index.js | 2 +- scripts/generate/templates/api_file.tmpl | 2 +- src/lib/transport.js | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/scripts/generate/index.js b/scripts/generate/index.js index 742b947b8..c2f2f9f03 100644 --- a/scripts/generate/index.js +++ b/scripts/generate/index.js @@ -95,7 +95,7 @@ function dirRegex(dir, regexp) { function dirOpts(dir, opts) { opts = _.isArray(opts) ? opts : [opts]; return dirFilter(dir, function (name) { - return _.contains(opts, name); + return _.includes(opts, name); }); } diff --git a/scripts/generate/templates/api_file.tmpl b/scripts/generate/templates/api_file.tmpl index a413da0f9..b0c730253 100644 --- a/scripts/generate/templates/api_file.tmpl +++ b/scripts/generate/templates/api_file.tmpl @@ -11,7 +11,7 @@ api._namespaces = <%= stringify(namespaces) %>;<% _.each(actions, function (action) { var namespace = action.location.split('.').shift(); - if (_.contains(namespaces, namespace)) { + if (_.includes(namespaces, namespace)) { _.pull(namespaces, namespace); %> diff --git a/src/lib/transport.js b/src/lib/transport.js index ba2ad07ee..452782372 100644 --- a/src/lib/transport.js +++ b/src/lib/transport.js @@ -274,7 +274,7 @@ Transport.prototype.request = function (params, cb) { if ( (!err || err instanceof errors.Serialization) && (status < 200 || status >= 300) - && (!params.ignore || !_.contains(params.ignore, status)) + && (!params.ignore || !_.includes(params.ignore, status)) ) { var errorMetadata = _.pick(params.req, ['path', 'query', 'body']); From fbac07a6ed94bedd8991e343e05464d73bf379d3 Mon Sep 17 00:00:00 2001 From: spalger Date: Thu, 19 May 2016 08:43:38 -0700 Subject: [PATCH 09/15] _.pairs => _.toPairs --- test/integration/yaml_suite/yaml_doc.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/integration/yaml_suite/yaml_doc.js b/test/integration/yaml_suite/yaml_doc.js index bb2299d08..7e6ef635c 100644 --- a/test/integration/yaml_suite/yaml_doc.js +++ b/test/integration/yaml_suite/yaml_doc.js @@ -9,7 +9,7 @@ */ module.exports = YamlDoc; -var _ = require('../../../src/lib/utils'); +var _ = require('lodash-migrate/lodash'); var expect = require('expect.js'); var clientManager = require('./client_manager'); var inspect = require('util').inspect; @@ -200,7 +200,7 @@ YamlDoc.prototype = { // creates [ [ {name:"", args:"" }, ... ], ... ] // from [ {name:args, name:args}, {name:args} ] var actionSets = _.map(config, function (set) { - return _.map(_.pairs(set), function (pair) { + return _.map(_.toPairs(set), function (pair) { return { name: pair[0], args: pair[1] }; }); }); From 38cf442accaaf02520705e5332ee7e630c6130cb Mon Sep 17 00:00:00 2001 From: spalger Date: Thu, 19 May 2016 08:44:15 -0700 Subject: [PATCH 10/15] protect methods that can not use lodash-migrate --- test/unit/buffer_flush_tests.js | 3 ++- test/unit/specs/file_logger.js | 3 ++- test/unit/specs/random_selector.js | 3 ++- test/unit/specs/round_robin_selector.js | 3 ++- test/unit/specs/stream_logger.js | 3 ++- test/unit/specs/transport.js | 3 ++- test/unit/specs/utils.js | 2 +- 7 files changed, 13 insertions(+), 7 deletions(-) diff --git a/test/unit/buffer_flush_tests.js b/test/unit/buffer_flush_tests.js index 2d2adf004..59ccef5f5 100644 --- a/test/unit/buffer_flush_tests.js +++ b/test/unit/buffer_flush_tests.js @@ -4,6 +4,7 @@ module.exports = function (makeLogger) { var fs = require('fs'); var once = require('events').EventEmitter.prototype.once; var _ = require('lodash-migrate'); + var _v4 = require('lodash-migrate/lodash'); describe('buffer flush', function () { if (require('stream').Writable) { @@ -21,7 +22,7 @@ module.exports = function (makeLogger) { var logger = makeLogger(); // write the line 10 times - _.times(10, function () { + _v4.times(10, function () { logger.onDebug(line); }); diff --git a/test/unit/specs/file_logger.js b/test/unit/specs/file_logger.js index 4766cae6b..23ccf1007 100644 --- a/test/unit/specs/file_logger.js +++ b/test/unit/specs/file_logger.js @@ -3,6 +3,7 @@ describe('File Logger', function () { var FileLogger = require('../../../src/lib/loggers/file'); var once = require('events').EventEmitter.prototype.once; var _ = require('../../../src/lib/utils'); + var _v4 = require('lodash-migrate/lodash'); var parentLog; var logger; var expect = require('expect.js'); @@ -49,7 +50,7 @@ describe('File Logger', function () { var logger = makeLogger(); // write the line 10 times - _.times(10, function () { + _v4.times(10, function () { logger.onDebug(line); }); diff --git a/test/unit/specs/random_selector.js b/test/unit/specs/random_selector.js index ad6ac70c8..2e38ff851 100644 --- a/test/unit/specs/random_selector.js +++ b/test/unit/specs/random_selector.js @@ -1,13 +1,14 @@ describe('Random Selector', function () { var randomSelector = require('../../../src/lib/selectors/random'); var _ = require('lodash-migrate'); + var _v4 = require('lodash-migrate/lodash'); var expect = require('expect.js'); it('chooses a selection by random', function () { var log = { a: 0, b: 0, c: 0 }; var choices = _.keys(log); - _.times(1000, function () { + _v4.times(1000, function () { var choice = randomSelector(choices); log[choice]++; }); diff --git a/test/unit/specs/round_robin_selector.js b/test/unit/specs/round_robin_selector.js index d320b5dc8..a7b0b80b1 100644 --- a/test/unit/specs/round_robin_selector.js +++ b/test/unit/specs/round_robin_selector.js @@ -1,6 +1,7 @@ describe('Round Robin Selector', function () { var selector = require('../../../src/lib/selectors/round_robin'); var _ = require('lodash-migrate'); + var _v4 = require('lodash-migrate/lodash'); var expect = require('expect.js'); it('chooses options in order', function () { @@ -8,7 +9,7 @@ describe('Round Robin Selector', function () { var expected = _.clone(options); var selections = []; - _.times(options.length, function () { + _v4.times(options.length, function () { selections.push(selector(options)); }); diff --git a/test/unit/specs/stream_logger.js b/test/unit/specs/stream_logger.js index f4c3d65ce..49cade3db 100644 --- a/test/unit/specs/stream_logger.js +++ b/test/unit/specs/stream_logger.js @@ -5,6 +5,7 @@ describe('Stream Logger', function () { var once = require('events').EventEmitter.prototype.once; var stream = new MockWritableStream(); var _ = require('../../../src/lib/utils'); + var _v4 = require('lodash-migrate/lodash'); var expect = require('expect.js'); var parentLog; @@ -47,7 +48,7 @@ describe('Stream Logger', function () { stream.write.restore(); // write the line 10 times - _.times(10, function () { + _v4.times(10, function () { logger.onDebug(line); }); diff --git a/test/unit/specs/transport.js b/test/unit/specs/transport.js index 4b99845ea..a851beee8 100644 --- a/test/unit/specs/transport.js +++ b/test/unit/specs/transport.js @@ -5,6 +5,7 @@ var errors = require('../../../src/lib/errors'); var sinon = require('sinon'); var expect = require('expect.js'); var _ = require('lodash-migrate'); +var _v4 = require('lodash-migrate/lodash'); var nodeList = require('../../fixtures/short_node_list.json'); var stub = require('../../utils/auto_release_stub').make(); @@ -632,7 +633,7 @@ describe('Transport Class', function () { }); }; } - it('retries when there are retries remaining', testRetries(_.random(25, 40))); + it('retries when there are retries remaining', testRetries(_v4.random(25, 40))); it('responds when there are no retries', testRetries(0)); }); diff --git a/test/unit/specs/utils.js b/test/unit/specs/utils.js index 0c6f6fcfc..feb89e7d0 100644 --- a/test/unit/specs/utils.js +++ b/test/unit/specs/utils.js @@ -349,7 +349,7 @@ describe('Utils', function () { }); describe('#applyArgs', function () { - _.times(10, function (i) { + _v4.times(10, function (i) { var method = i > 5 ? 'apply' : 'call'; var argCount = i + 1; var slice = 1; From c7f6c09d8c15502dffcf2add84d39446e1476a1e Mon Sep 17 00:00:00 2001 From: spalger Date: Thu, 19 May 2016 09:09:31 -0700 Subject: [PATCH 11/15] get the unit tests to pass --- grunt/config/mochacov.js | 2 +- grunt/utils.js | 26 +++++++++---------- scripts/ci.js | 2 +- scripts/generate/js_api.js | 1 - scripts/generate/templates/api_file.tmpl | 4 +-- scripts/generate/templates/client_action.tmpl | 4 +-- .../templates/client_action_proxy.tmpl | 4 +-- scripts/generate/templates/index.js | 1 - src/lib/client.js | 8 +++--- src/lib/client_action.js | 2 +- src/lib/connection_pool.js | 4 +-- src/lib/connectors/browser_index.js | 2 +- src/lib/connectors/http.js | 8 +++--- src/lib/errors.js | 2 +- src/lib/host.js | 6 ++--- src/lib/log.js | 4 +-- src/lib/logger.js | 8 +++--- src/lib/transport.js | 4 +-- src/lib/utils.js | 6 ++--- test/integration/yaml_suite/yaml_doc.js | 2 +- test/mocks/browser_http.js | 4 +-- test/unit/buffer_flush_tests.js | 1 - test/unit/specs/client_action.js | 2 +- test/unit/specs/connection_pool.js | 4 +-- test/unit/specs/errors.js | 2 +- test/unit/specs/file_logger.js | 1 - test/unit/specs/random_selector.js | 1 - test/unit/specs/round_robin_selector.js | 3 +-- test/unit/specs/stream_logger.js | 1 - test/unit/specs/transport.js | 17 ++++++------ test/utils/make_j_unit_xml.js | 6 ++--- 31 files changed, 67 insertions(+), 75 deletions(-) diff --git a/grunt/config/mochacov.js b/grunt/config/mochacov.js index eec8f7d6e..dd896a0a7 100644 --- a/grunt/config/mochacov.js +++ b/grunt/config/mochacov.js @@ -78,4 +78,4 @@ grunt.registerTask('mocha_jenkins_integration', function (branch) { grunt.task.run('mochacov:jenkins_integration'); }); -module.exports = config; \ No newline at end of file +module.exports = config; diff --git a/grunt/utils.js b/grunt/utils.js index 8a3405c67..a880791b6 100644 --- a/grunt/utils.js +++ b/grunt/utils.js @@ -31,19 +31,19 @@ utils.minorVersion = function (version) { utils.increaseVersion = function (version, type) { var i; switch (type) { - case 'major': - i = 0; - break; - case 'minor': - i = 1; - break; - case 'bug': - case 'patch': - case 'bugfix': - i = 2; - break; - default: - throw new TypeError('unexpected version bump type'); + case 'major': + i = 0; + break; + case 'minor': + i = 1; + break; + case 'bug': + case 'patch': + case 'bugfix': + i = 2; + break; + default: + throw new TypeError('unexpected version bump type'); } // breakout the current version diff --git a/scripts/ci.js b/scripts/ci.js index b1e35c405..1ea221f0e 100644 --- a/scripts/ci.js +++ b/scripts/ci.js @@ -30,7 +30,7 @@ var format = require('util').format; var NL_RE = /(\r?\n)/g; var ROOT = join(__dirname, '..'); var GRUNT = join(ROOT, 'node_modules', '.bin', 'grunt'); -var ENV = _.clone(process.env); +var ENV = _v4.clone(process.env); var JENKINS = !!ENV.JENKINS_HOME; var TASKS = []; diff --git a/scripts/generate/js_api.js b/scripts/generate/js_api.js index f374b003f..a9a2da981 100644 --- a/scripts/generate/js_api.js +++ b/scripts/generate/js_api.js @@ -4,7 +4,6 @@ module.exports = function (branch, done) { * @type {[type]} */ var _ = require('../../src/lib/utils'); - var _v4 = require('lodash-migrate/lodash'); var utils = require('../../grunt/utils'); var fs = require('fs'); var async = require('async'); diff --git a/scripts/generate/templates/api_file.tmpl b/scripts/generate/templates/api_file.tmpl index b0c730253..11797a2e5 100644 --- a/scripts/generate/templates/api_file.tmpl +++ b/scripts/generate/templates/api_file.tmpl @@ -9,7 +9,7 @@ var api = module.exports = {}; api._namespaces = <%= stringify(namespaces) %>;<% -_.each(actions, function (action) { +_v4.each(actions, function (action) { var namespace = action.location.split('.').shift(); if (_.includes(namespaces, namespace)) { _.pull(namespaces, namespace); @@ -22,7 +22,7 @@ api.<%= namespace %> = namespace();<% }); -_.each(proxies, function (action) {%> +_v4.each(proxies, function (action) {%> <%= partials.client_action_proxy(action) %><% }); diff --git a/scripts/generate/templates/client_action.tmpl b/scripts/generate/templates/client_action.tmpl index 4a80b7f0f..490e19652 100644 --- a/scripts/generate/templates/client_action.tmpl +++ b/scripts/generate/templates/client_action.tmpl @@ -2,11 +2,11 @@ * Perform a [<%= name %>](<%= docUrl %>) request * * @param {Object} params - An object with parameters used to carry out this action<% -_.each(allParams, function(param, paramName) { %> +_v4.each(allParams, function(param, paramName) { %> * @param {<%= paramType(param.type) %>} <%= paramWithDefault('params.' + paramName, param.default) %><% if (param.description) { %> - <%= param.description %><% } %><% }) %> */ -api<%= (location[0] === '[' ? '' : '.') + location %> = ca(<%= stringify(spec, true) %>); \ No newline at end of file +api<%= (location[0] === '[' ? '' : '.') + location %> = ca(<%= stringify(spec, true) %>); diff --git a/scripts/generate/templates/client_action_proxy.tmpl b/scripts/generate/templates/client_action_proxy.tmpl index f5dd98929..b122028b2 100644 --- a/scripts/generate/templates/client_action_proxy.tmpl +++ b/scripts/generate/templates/client_action_proxy.tmpl @@ -2,7 +2,7 @@ * Perform a [<%= name %>](<%= docUrl %>) request * * @param {Object} params - An object with parameters used to carry out this action<% -_.each(allParams, function(param, paramName) { %> +_v4.each(allParams, function(param, paramName) { %> * @param {<%= paramType(param.type) %>} <%= paramWithDefault('params.' + paramName, param.default) %><% if (param.description) { %> - <%= param.description %><% @@ -16,4 +16,4 @@ if (typeof transformBody === 'string') { %>, { } }<% } -%>); \ No newline at end of file +%>); diff --git a/scripts/generate/templates/index.js b/scripts/generate/templates/index.js index 0f74000af..fc555c3b9 100644 --- a/scripts/generate/templates/index.js +++ b/scripts/generate/templates/index.js @@ -1,6 +1,5 @@ var _ = require('../../../src/lib/utils'); -var _v4 = require('lodash-migrate/lodash'); var utils = require('../../../grunt/utils'); var fs = require('fs'); var path = require('path'); diff --git a/src/lib/client.js b/src/lib/client.js index c29e2e4cb..e9b2321ed 100755 --- a/src/lib/client.js +++ b/src/lib/client.js @@ -56,11 +56,11 @@ function Client(config) { this.transport = new Transport(config); - _.each(EsApiClient.prototype, function (Fn, prop) { + _v4.each(EsApiClient.prototype, _.bind(function (Fn, prop) { if (Fn.prototype instanceof clientAction.ApiNamespace) { this[prop] = new Fn(this.transport); } - }, this); + }, this)); delete this._namespaces; } @@ -74,9 +74,9 @@ function Client(config) { var Constructor = EsApiClient; if (config.plugins) { - Constructor.prototype = _.cloneDeep(Constructor.prototype); + Constructor.prototype = _v4.cloneDeep(Constructor.prototype); - _.each(config.plugins, function (setup) { + _v4.each(config.plugins, function (setup) { Constructor = setup(Constructor, config, { apis: require('./apis'), connectors: require('./connectors'), diff --git a/src/lib/client_action.js b/src/lib/client_action.js index e6596eb0e..6b34e2e6f 100644 --- a/src/lib/client_action.js +++ b/src/lib/client_action.js @@ -57,7 +57,7 @@ function makeFactoryWithModifier(modifier) { } try { - return exec(this.transport, spec, _.clone(params), cb); + return exec(this.transport, spec, _v4.clone(params), cb); } catch (e) { if (typeof cb === 'function') { _.nextTick(cb, e); diff --git a/src/lib/connection_pool.js b/src/lib/connection_pool.js index 87c6dfcb9..7a892cd48 100644 --- a/src/lib/connection_pool.js +++ b/src/lib/connection_pool.js @@ -257,7 +257,7 @@ ConnectionPool.prototype.getConnections = function (status, limit) { if (limit == null) { return list.slice(0); } else { - return _.shuffle(list).slice(0, limit); + return _v4.shuffle(list).slice(0, limit); } }; @@ -308,7 +308,7 @@ ConnectionPool.prototype.setHosts = function (hosts) { var i; var id; var host; - var toRemove = _.clone(this.index); + var toRemove = _v4.clone(this.index); for (i = 0; i < hosts.length; i++) { host = hosts[i]; diff --git a/src/lib/connectors/browser_index.js b/src/lib/connectors/browser_index.js index 8553ee8da..ad47d6253 100644 --- a/src/lib/connectors/browser_index.js +++ b/src/lib/connectors/browser_index.js @@ -6,7 +6,7 @@ var opts = { var _ = require('../utils'); // remove modules that have been ignored by browserify -_.each(opts, function (conn, name) { +_v4.each(opts, function (conn, name) { if (typeof conn !== 'function') { delete opts[name]; } diff --git a/src/lib/connectors/http.js b/src/lib/connectors/http.js index 041b1bf5c..7bb742683 100644 --- a/src/lib/connectors/http.js +++ b/src/lib/connectors/http.js @@ -53,7 +53,7 @@ HttpConnector.prototype.onStatusSet = _.handler(function (status) { var agent = this.agent; var toRemove = []; var collectSockets = function (sockets, host) { - _.each(sockets, function (s) { + _v4.each(sockets, function (s) { if (s) toRemove.push([host, s]); }); }; @@ -61,9 +61,9 @@ HttpConnector.prototype.onStatusSet = _.handler(function (status) { agent.minSockets = agent.maxSockets = 0; agent.requests = {}; - _.each(agent.sockets, collectSockets); - _.each(agent.freeSockets, collectSockets); - _.each(toRemove, function (args) { + _v4.each(agent.sockets, collectSockets); + _v4.each(agent.freeSockets, collectSockets); + _v4.each(toRemove, function (args) { var host = args[0], socket = args[1]; agent.removeSocket(socket, host); socket.destroy(); diff --git a/src/lib/errors.js b/src/lib/errors.js index 47139354f..1f2273d57 100644 --- a/src/lib/errors.js +++ b/src/lib/errors.js @@ -137,7 +137,7 @@ var statusCodes = [ [510, 'Not Extended'] ]; -_.each(statusCodes, function createStatusCodeError(tuple) { +_v4.each(statusCodes, function createStatusCodeError(tuple) { var status = tuple[0]; var names = tuple[1]; var allNames = [].concat(names, status); diff --git a/src/lib/host.js b/src/lib/host.js index cdb2f10e7..21cdee433 100644 --- a/src/lib/host.js +++ b/src/lib/host.js @@ -46,7 +46,7 @@ Host.defaultPorts = { }; function Host(config, globalConfig) { - config = _.clone(config || {}); + config = _v4.clone(config || {}); globalConfig = globalConfig || {}; // defaults @@ -85,7 +85,7 @@ function Host(config, globalConfig) { if (_.isObject(config)) { // move hostname/portname to host/port semi-intelligently. - _.each(simplify, function (to) { + _v4.each(simplify, function (to) { var from = to + 'name'; if (config[from] && config[to]) { if (config[to].indexOf(config[from]) === 0) { @@ -107,7 +107,7 @@ function Host(config, globalConfig) { } _.forOwn(config, function (val, prop) { - if (val != null) this[prop] = _.clone(val); + if (val != null) this[prop] = _v4.clone(val); }, this); // make sure the query string is parsed diff --git a/src/lib/log.js b/src/lib/log.js index a463bccf0..9baa30dce 100644 --- a/src/lib/log.js +++ b/src/lib/log.js @@ -176,7 +176,7 @@ Log.parseLevels = function (input) { * @method join * @static * @private - * @param {*} arrayish - An array like object that can be itterated by _.each + * @param {*} arrayish - An array like object that can be itterated by _v4.each * @return {String} - The final string. */ Log.join = function (arrayish) { @@ -289,7 +289,7 @@ Log.normalizeTraceArgs = function (method, requestUrl, body, responseBody, respo if (typeof requestUrl === 'string') { requestUrl = url.parse(requestUrl, true, true); } else { - requestUrl = _.clone(requestUrl); + requestUrl = _v4.clone(requestUrl); if (requestUrl.path) { requestUrl.query = url.parse(requestUrl.path, true, false).query; } diff --git a/src/lib/logger.js b/src/lib/logger.js index 35f8f07e1..e466fec11 100644 --- a/src/lib/logger.js +++ b/src/lib/logger.js @@ -64,7 +64,7 @@ LoggerAbstract.prototype.setupListeners = function (levels) { this.listeningLevels = []; - _.each(levels, function (level) { + _v4.each(levels, _.bind(function (level) { var fnName = 'on' + _.ucfirst(level); if (this.bound[fnName]) { this.listeningLevels.push(level); @@ -72,7 +72,7 @@ LoggerAbstract.prototype.setupListeners = function (levels) { } else { throw new Error('Unable to listen for level "' + level + '"'); } - }, this); + }, this)); }; /** @@ -83,9 +83,9 @@ LoggerAbstract.prototype.setupListeners = function (levels) { * @return {undefined} */ LoggerAbstract.prototype.cleanUpListeners = _.handler(function () { - _.each(this.listeningLevels, function (level) { + _v4.each(this.listeningLevels, _.bind(function (level) { this.log.removeListener(level, this.bound['on' + _.ucfirst(level)]); - }, this); + }, this)); }); /** diff --git a/src/lib/transport.js b/src/lib/transport.js index 452782372..88c559573 100644 --- a/src/lib/transport.js +++ b/src/lib/transport.js @@ -62,7 +62,7 @@ function Transport(config) { } if (randomizeHosts) { - hostsConfig = _.shuffle(hostsConfig); + hostsConfig = _v4.shuffle(hostsConfig); } self.setHosts(hostsConfig); @@ -439,7 +439,7 @@ Transport.prototype.setHosts = function (hostsConfigs) { Transport.prototype.close = function () { this.log.close(); this.closed = true; - _.each(this._timers, clearTimeout); + _v4.each(this._timers, clearTimeout); this._timers = null; this.connectionPool.close(); }; diff --git a/src/lib/utils.js b/src/lib/utils.js index 69c5f9f3e..1f4247066 100644 --- a/src/lib/utils.js +++ b/src/lib/utils.js @@ -32,7 +32,7 @@ utils.joinPath = path.join; * @return {Object} - returns the modified to value */ utils.deepMerge = function (to, from) { - _.each(from, function (fromVal, key) { + _v4.each(from, function (fromVal, key) { switch (typeof to[key]) { case 'undefined': to[key] = from[key]; @@ -56,7 +56,7 @@ utils.deepMerge = function (to, from) { * @param {Array} arr - An array to check * @return {Boolean} */ -_.each([ +_v4.each([ 'String', 'Object', 'PlainObject', @@ -404,7 +404,7 @@ _.getUnwrittenFromStream = function (stream) { var out = ''; if (!writeBuffer.length) return out; - _.each(writeBuffer, function (writeReq) { + _v4.each(writeBuffer, function (writeReq) { if (writeReq.chunk) { // 0.9.12+ uses WriteReq objects with a chunk prop out += '' + writeReq.chunk; diff --git a/test/integration/yaml_suite/yaml_doc.js b/test/integration/yaml_suite/yaml_doc.js index 7e6ef635c..77dd1c348 100644 --- a/test/integration/yaml_suite/yaml_doc.js +++ b/test/integration/yaml_suite/yaml_doc.js @@ -568,7 +568,7 @@ YamlDoc.prototype = { // recursively replace all $var within args _.forOwn(args, function recurse(val, key, lvl) { if (_.isObject(val)) { - return _.each(val, recurse); + return _v4.each(val, recurse); } if (_.isString(val)) { diff --git a/test/mocks/browser_http.js b/test/mocks/browser_http.js index 00d6cdb8b..912de0fe5 100644 --- a/test/mocks/browser_http.js +++ b/test/mocks/browser_http.js @@ -221,7 +221,7 @@ MockHttpRequest.prototype = { getAllResponseHeaders: function () { var r = ''; - _.each(this.responseHeaders, function (header) { + _v4.each(this.responseHeaders, function (header) { if ((header === 'set-cookie') || (header === 'set-cookie2')) { return; } @@ -353,7 +353,7 @@ MockHttpRequest.prototype = { this.responseText = null; this.error = true; - _.each(this.requestHeaders, function (header) { + _v4.each(this.requestHeaders, function (header) { delete this.requestHeaders[header]; }, this); diff --git a/test/unit/buffer_flush_tests.js b/test/unit/buffer_flush_tests.js index 59ccef5f5..5f70928e0 100644 --- a/test/unit/buffer_flush_tests.js +++ b/test/unit/buffer_flush_tests.js @@ -4,7 +4,6 @@ module.exports = function (makeLogger) { var fs = require('fs'); var once = require('events').EventEmitter.prototype.once; var _ = require('lodash-migrate'); - var _v4 = require('lodash-migrate/lodash'); describe('buffer flush', function () { if (require('stream').Writable) { diff --git a/test/unit/specs/client_action.js b/test/unit/specs/client_action.js index 82f4be8a0..ae49068aa 100644 --- a/test/unit/specs/client_action.js +++ b/test/unit/specs/client_action.js @@ -68,7 +68,7 @@ describe('Client Action runner', function () { afterEach(function () { _stash = {}; }); var make = function (params) { _stash.orig = params; - _stash.copy = _.clone(params); + _stash.copy = _v4.clone(params); return params; }; make.check = function () { diff --git a/test/unit/specs/connection_pool.js b/test/unit/specs/connection_pool.js index ccfd73261..91772d76e 100644 --- a/test/unit/specs/connection_pool.js +++ b/test/unit/specs/connection_pool.js @@ -175,10 +175,10 @@ describe('Connection Pool', function () { new ConnectionAbstract(new Host('http://localhost:9202')), new ConnectionAbstract(new Host('http://localhost:9203')) ]; - var pingQueue = _.shuffle(connections); + var pingQueue = _v4.shuffle(connections); var expectedSelection = pingQueue[pingQueue.length - 1]; - _.each(pingQueue, function (conn) { + _v4.each(pingQueue, function (conn) { pool.addConnection(conn); stub(conn, 'ping', function (params, cb) { if (typeof params === 'function') { diff --git a/test/unit/specs/errors.js b/test/unit/specs/errors.js index 0347b7b4e..12c707099 100644 --- a/test/unit/specs/errors.js +++ b/test/unit/specs/errors.js @@ -2,7 +2,7 @@ var errors = require('../../../src/lib/errors'); var expect = require('expect.js'); var _ = require('lodash-migrate'); -_.each(errors, function (CustomError, name) { +_v4.each(errors, function (CustomError, name) { if (name.charAt(0) !== '_') { describe(name, function () { it('extend the ErrorAbstract and Error classes', function () { diff --git a/test/unit/specs/file_logger.js b/test/unit/specs/file_logger.js index 23ccf1007..cb5a862d0 100644 --- a/test/unit/specs/file_logger.js +++ b/test/unit/specs/file_logger.js @@ -3,7 +3,6 @@ describe('File Logger', function () { var FileLogger = require('../../../src/lib/loggers/file'); var once = require('events').EventEmitter.prototype.once; var _ = require('../../../src/lib/utils'); - var _v4 = require('lodash-migrate/lodash'); var parentLog; var logger; var expect = require('expect.js'); diff --git a/test/unit/specs/random_selector.js b/test/unit/specs/random_selector.js index 2e38ff851..7b7df3149 100644 --- a/test/unit/specs/random_selector.js +++ b/test/unit/specs/random_selector.js @@ -1,7 +1,6 @@ describe('Random Selector', function () { var randomSelector = require('../../../src/lib/selectors/random'); var _ = require('lodash-migrate'); - var _v4 = require('lodash-migrate/lodash'); var expect = require('expect.js'); it('chooses a selection by random', function () { diff --git a/test/unit/specs/round_robin_selector.js b/test/unit/specs/round_robin_selector.js index a7b0b80b1..58d5ec8fe 100644 --- a/test/unit/specs/round_robin_selector.js +++ b/test/unit/specs/round_robin_selector.js @@ -1,12 +1,11 @@ describe('Round Robin Selector', function () { var selector = require('../../../src/lib/selectors/round_robin'); var _ = require('lodash-migrate'); - var _v4 = require('lodash-migrate/lodash'); var expect = require('expect.js'); it('chooses options in order', function () { var options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]; - var expected = _.clone(options); + var expected = _v4.clone(options); var selections = []; _v4.times(options.length, function () { diff --git a/test/unit/specs/stream_logger.js b/test/unit/specs/stream_logger.js index 49cade3db..44413ad63 100644 --- a/test/unit/specs/stream_logger.js +++ b/test/unit/specs/stream_logger.js @@ -5,7 +5,6 @@ describe('Stream Logger', function () { var once = require('events').EventEmitter.prototype.once; var stream = new MockWritableStream(); var _ = require('../../../src/lib/utils'); - var _v4 = require('lodash-migrate/lodash'); var expect = require('expect.js'); var parentLog; diff --git a/test/unit/specs/transport.js b/test/unit/specs/transport.js index a851beee8..5e2f81e56 100644 --- a/test/unit/specs/transport.js +++ b/test/unit/specs/transport.js @@ -5,7 +5,6 @@ var errors = require('../../../src/lib/errors'); var sinon = require('sinon'); var expect = require('expect.js'); var _ = require('lodash-migrate'); -var _v4 = require('lodash-migrate/lodash'); var nodeList = require('../../fixtures/short_node_list.json'); var stub = require('../../utils/auto_release_stub').make(); @@ -288,23 +287,23 @@ describe('Transport Class', function () { it('calls _.shuffle be default', function () { var _ = require('../../../src/lib/utils'); stub(Transport.connectionPools.main.prototype, 'setHosts'); - stub(_, 'shuffle'); + stub(_v4, 'shuffle'); var trans = new Transport({ hosts: 'localhost' }); - expect(_.shuffle.callCount).to.eql(1); + expect(_v4.shuffle.callCount).to.eql(1); }); it('skips the call to _.shuffle when false', function () { var _ = require('../../../src/lib/utils'); stub(Transport.connectionPools.main.prototype, 'setHosts'); - stub(_, 'shuffle'); + stub(_v4, 'shuffle'); var trans = new Transport({ hosts: 'localhost', randomizeHosts: false }); - expect(_.shuffle.callCount).to.eql(0); + expect(_v4.shuffle.callCount).to.eql(0); }); }); }); @@ -619,7 +618,7 @@ describe('Transport Class', function () { // trigger a select so that we can harvest the connection list trans.connectionPool.select(_.noop); - _.each(connections, function (conn) { + _v4.each(connections, function (conn) { stub(conn, 'request', failRequest); }); @@ -763,7 +762,7 @@ describe('Transport Class', function () { prom.then(_.noop, _.noop); expect(_.size(clock.timers)).to.eql(1); - _.each(clock.timers, function (timer, id) { + _v4.each(clock.timers, function (timer, id) { expect(timer.callAt).to.eql(30000); clearTimeout(id); }); @@ -780,14 +779,14 @@ describe('Transport Class', function () { prom.then(_.noop, _.noop); expect(_.size(clock.timers)).to.eql(1); - _.each(clock.timers, function (timer, id) { + _v4.each(clock.timers, function (timer, id) { expect(timer.callAt).to.eql(5000); clearTimeout(id); }); }); - _.each([false, 0, null], function (falsy) { + _v4.each([false, 0, null], function (falsy) { it('skips the timeout when it is ' + falsy, function () { var clock = sinon.useFakeTimers(); stub.autoRelease(clock); diff --git a/test/utils/make_j_unit_xml.js b/test/utils/make_j_unit_xml.js index f8a800e99..8d5dbbe3e 100644 --- a/test/utils/make_j_unit_xml.js +++ b/test/utils/make_j_unit_xml.js @@ -32,7 +32,7 @@ var _ = require('lodash-migrate'); var chalk = require('chalk'); function makeJUnitXml(runnerName, testDetails) { - _.each(testDetails.suites, function serializeSuite(suiteInfo) { + _v4.each(testDetails.suites, function serializeSuite(suiteInfo) { var suite = suites.ele('testsuite', { package: 'elasticsearch-js', @@ -46,7 +46,7 @@ function makeJUnitXml(runnerName, testDetails) { time: suiteInfo.time / 1000 }); - _.each(suiteInfo.results, function (testInfo) { + _v4.each(suiteInfo.results, function (testInfo) { var section; var integration = false; @@ -83,7 +83,7 @@ function makeJUnitXml(runnerName, testDetails) { }); if (suiteInfo.suites) { - _.each(suiteInfo.suites, serializeSuite); + _v4.each(suiteInfo.suites, serializeSuite); } giveOutput(suite, suiteInfo); From 4a77556866aeab36cb4124a5663a9522230742dd Mon Sep 17 00:00:00 2001 From: spalger Date: Thu, 19 May 2016 12:47:33 -0700 Subject: [PATCH 12/15] tracked down more necessary updated, lots of _.bind() --- docs/configuration.asciidoc | 2 +- docs/host.asciidoc | 2 +- scripts/ci.js | 2 +- scripts/generate/js_api.js | 2 +- scripts/generate/templates/api_file.tmpl | 4 +-- .../templates/configuration_docs.tmpl | 2 +- test/integration/yaml_suite/run.js | 2 +- test/integration/yaml_suite/yaml_doc.js | 36 +++++++++---------- test/integration/yaml_suite/yaml_file.js | 2 +- test/mocks/browser_server.js | 2 +- test/utils/jenkins-reporter.js | 4 +-- 11 files changed, 30 insertions(+), 30 deletions(-) diff --git a/docs/configuration.asciidoc b/docs/configuration.asciidoc index b5ad70a8a..138f3fbc2 100644 --- a/docs/configuration.asciidoc +++ b/docs/configuration.asciidoc @@ -315,7 +315,7 @@ var client = new elasticsearch.Client({ selector: function (hosts) { var myCountry = process.env.COUNTRY; // first try to find a node that is in the same country - var selection = _.find(nodes, function (node) { + var selection = _v4.find(nodes, function (node) { return node.host.country === myCountry; }); diff --git a/docs/host.asciidoc b/docs/host.asciidoc index 98bc353c8..6fb0784d0 100644 --- a/docs/host.asciidoc +++ b/docs/host.asciidoc @@ -88,7 +88,7 @@ var client = new elasticsearch.Client({ selector: function (hosts) { var myCountry = process.env.COUNTRY; // first try to find a node that is in the same country - var selection = _.find(nodes, function (node) { + var selection = _v4.find(nodes, function (node) { return node.host.country === myCountry; }); diff --git a/scripts/ci.js b/scripts/ci.js index 1ea221f0e..ac0c2625f 100644 --- a/scripts/ci.js +++ b/scripts/ci.js @@ -174,7 +174,7 @@ execTask('SETUP', function () { return ENV.RUN .split(',') .map(function (name) { - return _.find(TASKS, { name: name.trim() }); + return _v4.find(TASKS, { name: name.trim() }); }) .filter(Boolean); }); diff --git a/scripts/generate/js_api.js b/scripts/generate/js_api.js index a9a2da981..372b84917 100644 --- a/scripts/generate/js_api.js +++ b/scripts/generate/js_api.js @@ -91,7 +91,7 @@ module.exports = function (branch, done) { clientActionModifier: overrides.clientActionModifier }; - var create = _.assign({}, _.find(apiSpec.actions, { name: 'index' }), { + var create = _.assign({}, _v4.find(apiSpec.actions, { name: 'index' }), { name: 'create', location: 'create', proxy: 'index', diff --git a/scripts/generate/templates/api_file.tmpl b/scripts/generate/templates/api_file.tmpl index 11797a2e5..90612b1ca 100644 --- a/scripts/generate/templates/api_file.tmpl +++ b/scripts/generate/templates/api_file.tmpl @@ -18,12 +18,12 @@ _v4.each(actions, function (action) { api.<%= namespace %> = namespace();<% }%> -<%= partials.client_action(action) %><% +<%= _v4.trimEnd(partials.client_action(action)) %><% }); _v4.each(proxies, function (action) {%> -<%= partials.client_action_proxy(action) %><% +<%= _v4.trimEnd(partials.client_action_proxy(action)) %><% }); %> diff --git a/scripts/generate/templates/configuration_docs.tmpl b/scripts/generate/templates/configuration_docs.tmpl index f554c5cca..5a5691896 100644 --- a/scripts/generate/templates/configuration_docs.tmpl +++ b/scripts/generate/templates/configuration_docs.tmpl @@ -303,7 +303,7 @@ var client = new elasticsearch.Client({ selector: function (hosts) { var myCountry = process.env.COUNTRY; // first try to find a node that is in the same country - var selection = _.find(nodes, function (node) { + var selection = _v4.find(nodes, function (node) { return node.host.country === myCountry; }); diff --git a/test/integration/yaml_suite/run.js b/test/integration/yaml_suite/run.js index 9ec43a994..dddd72efe 100644 --- a/test/integration/yaml_suite/run.js +++ b/test/integration/yaml_suite/run.js @@ -32,7 +32,7 @@ module.exports = function (branch) { return clientManager.get().clearEs(); }); - var files = _.map(require('./yaml_tests_' + _.snakeCase(branch) + '.json'), function (docs, filename) { + var files = _v4.map(require('./yaml_tests_' + _.snakeCase(branch) + '.json'), function (docs, filename) { return new YamlFile(filename, docs); }); diff --git a/test/integration/yaml_suite/yaml_doc.js b/test/integration/yaml_suite/yaml_doc.js index 77dd1c348..f59e2b8c1 100644 --- a/test/integration/yaml_suite/yaml_doc.js +++ b/test/integration/yaml_suite/yaml_doc.js @@ -407,14 +407,14 @@ YamlDoc.prototype = { var clientAction = this.get(clientActionName, client); _.assign(inputParams, args[action]); - var params = _.transform(inputParams, function (params, val, name) { + var params = _.transform(inputParams, _.bind(function (params, val, name) { var camelName = _.camelCase(name); // search through the params and url peices to find this param name var paramName = name; var spec = clientAction && clientAction.spec; var knownParam = spec && spec.params && spec.params[camelName]; - var knownUrlParam = spec && !knownParam && !!_.find(spec.url ? [spec.url] : spec.urls, function (url) { + var knownUrlParam = spec && !knownParam && !!_v4.find(spec.url ? [spec.url] : spec.urls, function (url) { if ((url.opt && url.opt[camelName]) || (url.req && url.req[camelName])) { return true; } @@ -437,12 +437,12 @@ YamlDoc.prototype = { }.bind(this); transformObject(params, val, paramName); - }, {}, this); + }, this), {}); expect(clientAction || clientActionName).to.be.a('function'); - if (_.isNumeric(catcher)) { + if (!isNaN(parseFloat(catcher))) { params.ignore = _.union(params.ignore || [], [catcher]); catcher = null; } @@ -494,9 +494,9 @@ YamlDoc.prototype = { * @return {undefined} */ do_set: function (args) { - _.forOwn(args, function (name, path) { + _.forOwn(args, _.bind(function (name, path) { this._stash[name] = this.get(path); - }, this); + }, this)); }, /** @@ -578,7 +578,7 @@ YamlDoc.prototype = { } }); - _.forOwn(args, function (match, path) { + _.forOwn(args, _.bind(function (match, path) { var origMatch = match; var maybeRE = false; @@ -645,7 +645,7 @@ YamlDoc.prototype = { throw new Error(msg.join('\n')); } - }, this); + }, this)); }, /** @@ -655,9 +655,9 @@ YamlDoc.prototype = { * @return {undefined} */ do_lt: function (args) { - _.forOwn(args, function (num, path) { + _.forOwn(args, _.bind(function (num, path) { expect(this.get(path)).to.be.below(num, 'path: ' + path); - }, this); + }, this)); }, /** @@ -667,9 +667,9 @@ YamlDoc.prototype = { * @return {undefined} */ do_lte: function (args) { - _.forOwn(args, function (num, path) { + _.forOwn(args, _.bind(function (num, path) { expect(this.get(path) <= num).to.be.ok('path: ' + path); - }, this); + }, this)); }, /** @@ -679,9 +679,9 @@ YamlDoc.prototype = { * @return {undefined} */ do_gt: function (args) { - _.forOwn(args, function (num, path) { + _.forOwn(args, _.bind(function (num, path) { expect(this.get(path)).to.be.above(num, 'path: ' + path); - }, this); + }, this)); }, /** @@ -691,9 +691,9 @@ YamlDoc.prototype = { * @return {undefined} */ do_gte: function (args) { - _.forOwn(args, function (num, path) { + _.forOwn(args, _.bind(function (num, path) { expect(this.get(path) >= num).to.be.ok('path: ' + path); - }, this); + }, this)); }, /** @@ -704,8 +704,8 @@ YamlDoc.prototype = { * @return {undefined} */ do_length: function (args) { - _.forOwn(args, function (len, path) { + _.forOwn(args, _.bind(function (len, path) { expect(_.size(this.get(path))).to.eql(len, 'path: ' + path); - }, this); + }, this)); } }; diff --git a/test/integration/yaml_suite/yaml_file.js b/test/integration/yaml_suite/yaml_file.js index b96529fc6..d8458c9cc 100644 --- a/test/integration/yaml_suite/yaml_file.js +++ b/test/integration/yaml_suite/yaml_file.js @@ -18,7 +18,7 @@ function YamlFile(filename, docs) { file.skipping = false; describe(filename, function () { - file.docs = _.map(docs, function (doc) { + file.docs = _v4.map(docs, function (doc) { doc = new YamlDoc(doc, file); if (doc.description === 'setup') { beforeEach(/* doc */function (done) { diff --git a/test/mocks/browser_server.js b/test/mocks/browser_server.js index a10435cce..017ff5bc2 100644 --- a/test/mocks/browser_server.js +++ b/test/mocks/browser_server.js @@ -11,7 +11,7 @@ var server = new XhrServer(function (request) { host: request.urlParts.host, path: request.urlParts.relative }; - var response = _.find(interceptors, reqDetails); + var response = _v4.find(interceptors, reqDetails); if (response) { // remove of tick down the times diff --git a/test/utils/jenkins-reporter.js b/test/utils/jenkins-reporter.js index 4516020d6..3275e06cf 100644 --- a/test/utils/jenkins-reporter.js +++ b/test/utils/jenkins-reporter.js @@ -24,8 +24,8 @@ var log = (function () { }; }()); -var integration = _.find(process.argv, function (arg) { return arg.indexOf('test/integration') > -1; }); -var unit = _.find(process.argv, function (arg) { return arg.indexOf('test/unit') > -1; }); +var integration = _v4.find(process.argv, function (arg) { return arg.indexOf('test/integration') > -1; }); +var unit = _v4.find(process.argv, function (arg) { return arg.indexOf('test/unit') > -1; }); var output; if (unit) { From ec06c51c5d30ad2d23a1f95528b01b3b7f035948 Mon Sep 17 00:00:00 2001 From: spalger Date: Thu, 19 May 2016 14:23:33 -0700 Subject: [PATCH 13/15] final sweep, moved everything to _v4 --- Gruntfile.js | 2 - grunt/config/clean.js | 2 +- grunt/config/compress.js | 10 +- grunt/config/concat.js | 2 +- grunt/config/copy.js | 2 +- grunt/config/esvm.js | 6 +- grunt/config/mochacov.js | 6 +- grunt/config/open.js | 2 +- grunt/config/prompt.js | 2 +- grunt/config/s3.js | 2 +- grunt/config/saucelabs-mocha.js | 2 +- grunt/utils.js | 4 +- package.json | 2 +- scripts/Version.js | 8 +- scripts/ci.js | 18 +- scripts/generate/api_index.js | 4 +- scripts/generate/configuration_docs.js | 4 +- scripts/generate/doc_index.js | 4 +- scripts/generate/index.js | 20 +- scripts/generate/js_api.js | 68 +++--- scripts/generate/templates/api_file.tmpl | 2 +- scripts/generate/templates/api_index.tmpl | 2 +- scripts/generate/templates/api_methods.tmpl | 4 +- scripts/generate/templates/index.js | 9 +- scripts/generate/yaml_tests.js | 10 +- scripts/release/bower.js | 6 +- src/lib/client.js | 6 +- src/lib/client_action.js | 40 ++-- src/lib/connection.js | 8 +- src/lib/connection_pool.js | 28 +-- src/lib/connectors/angular.js | 4 +- src/lib/connectors/browser_index.js | 2 +- src/lib/connectors/http.js | 14 +- src/lib/connectors/jquery.js | 4 +- src/lib/connectors/xhr.js | 8 +- src/lib/errors.js | 32 +-- src/lib/host.js | 22 +- src/lib/log.js | 24 +-- src/lib/logger.js | 26 +-- src/lib/loggers/console.js | 16 +- src/lib/loggers/file.js | 8 +- src/lib/loggers/stdio.js | 18 +- src/lib/loggers/stream.js | 10 +- src/lib/loggers/tracer.js | 12 +- src/lib/nodes_to_host.js | 4 +- src/lib/serializers/angular.js | 4 +- src/lib/serializers/json.js | 4 +- src/lib/transport.js | 28 +-- .../transport/sniff_on_connection_fault.js | 4 +- src/lib/utils.js | 99 ++++----- test/fixtures/keepalive.js | 10 +- test/integration/yaml_suite/client_manager.js | 12 +- test/integration/yaml_suite/run.js | 4 +- test/integration/yaml_suite/yaml_doc.js | 70 +++--- test/integration/yaml_suite/yaml_file.js | 2 +- test/mocks/browser_http.js | 2 +- test/mocks/browser_server.js | 2 +- test/unit/browser_builds/angular.js | 7 +- test/unit/browser_builds/jquery.js | 1 + test/unit/buffer_flush_tests.js | 2 +- test/unit/specs/client_action.js | 8 +- test/unit/specs/connection_abstract.js | 8 +- test/unit/specs/connection_pool.js | 18 +- test/unit/specs/errors.js | 2 +- test/unit/specs/file_logger.js | 4 +- test/unit/specs/host.js | 2 +- test/unit/specs/http_connector.js | 8 +- test/unit/specs/log.js | 12 +- test/unit/specs/random_selector.js | 6 +- test/unit/specs/round_robin_selector.js | 2 +- test/unit/specs/stream_logger.js | 6 +- test/unit/specs/transport.js | 34 +-- test/unit/specs/transport_with_server.js | 8 +- test/unit/specs/utils.js | 202 +++++++++--------- test/utils/expect_sub_object.js | 4 +- test/utils/jenkins-reporter.js | 12 +- test/utils/make_j_unit_xml.js | 4 +- test/utils/server.js | 4 +- 78 files changed, 542 insertions(+), 542 deletions(-) diff --git a/Gruntfile.js b/Gruntfile.js index 96ad6350d..ef986ba9f 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -1,5 +1,3 @@ -'use strict'; - module.exports = function (grunt) { // load plugins require('load-grunt-config')(grunt, { diff --git a/grunt/config/clean.js b/grunt/config/clean.js index 4998e758b..5eee123b8 100644 --- a/grunt/config/clean.js +++ b/grunt/config/clean.js @@ -2,4 +2,4 @@ module.exports = { dist: { src: ['<%= distDir %>'] } -}; \ No newline at end of file +}; diff --git a/grunt/config/compress.js b/grunt/config/compress.js index 5c3d1db53..4298f1070 100644 --- a/grunt/config/compress.js +++ b/grunt/config/compress.js @@ -11,8 +11,8 @@ function archive(out) { } module.exports = { - master_zip: archive('elasticsearch-js-master.zip'), - master_tarball: archive('elasticsearch-js-master.tar.gz'), - release_zip: archive('elasticsearch-js-<%= package.version %>.zip'), - release_tarball: archive('elasticsearch-js-<%= package.version %>.tar.gz') -}; \ No newline at end of file + master_zip: archive('elasticsearch-js-master.zip'), + master_tarball: archive('elasticsearch-js-master.tar.gz'), + release_zip: archive('elasticsearch-js-<%= package.version %>.zip'), + release_tarball: archive('elasticsearch-js-<%= package.version %>.tar.gz') +}; diff --git a/grunt/config/concat.js b/grunt/config/concat.js index 7bfabc9fd..b9434bd38 100644 --- a/grunt/config/concat.js +++ b/grunt/config/concat.js @@ -15,4 +15,4 @@ module.exports = { footer: '\n}());' } } -}; \ No newline at end of file +}; diff --git a/grunt/config/copy.js b/grunt/config/copy.js index 1f6d57aba..8ae070ea7 100644 --- a/grunt/config/copy.js +++ b/grunt/config/copy.js @@ -11,4 +11,4 @@ module.exports = { dest: '<%= bowerSubmodule %>', expand: true } -}; \ No newline at end of file +}; diff --git a/grunt/config/esvm.js b/grunt/config/esvm.js index 711ec0484..5ee23ccad 100644 --- a/grunt/config/esvm.js +++ b/grunt/config/esvm.js @@ -1,11 +1,11 @@ -var _ = require('lodash-migrate'); +// var _ = require('lodash'); var utils = require('../utils'); var fromRoot = require('path').join.bind(null, __dirname, '..', '..'); var release = process.env.ES_RELEASE; var ref = process.env.ES_REF; -var port = parseFloat(_.get(process.env, 'ES_PORT', 9400)); -var host = _.get(process.env, 'ES_HOST', 'localhost'); +var port = parseFloat(_v4.get(process.env, 'ES_PORT', 9400)); +var host = _v4.get(process.env, 'ES_HOST', 'localhost'); var Version = require('../../scripts/Version'); var versionedOpts = [ diff --git a/grunt/config/mochacov.js b/grunt/config/mochacov.js index dd896a0a7..0afc61649 100644 --- a/grunt/config/mochacov.js +++ b/grunt/config/mochacov.js @@ -1,7 +1,7 @@ var root = require('find-root')(__dirname); var rel = require('path').resolve.bind(null, root); var rootReq = function (p) { return require(rel(p)); }; -var _ = rootReq('src/lib/utils'); +// var _ = rootReq('src/lib/utils'); var grunt = require('grunt'); var JENKINS_REPORTER = rel('test/utils/jenkins-reporter.js'); @@ -65,7 +65,7 @@ var config = { grunt.registerTask('mocha_integration', function (branch) { grunt.config.set( 'mochacov.integration.src', - 'test/integration/yaml_suite/index_' + _.snakeCase(branch) + '.js' + 'test/integration/yaml_suite/index_' + _v4.snakeCase(branch) + '.js' ); grunt.task.run('mochacov:integration'); }); @@ -73,7 +73,7 @@ grunt.registerTask('mocha_integration', function (branch) { grunt.registerTask('mocha_jenkins_integration', function (branch) { grunt.config.set( 'mochacov.jenkins_integration.src', - 'test/integration/yaml_suite/index_' + _.snakeCase(branch) + '.js' + 'test/integration/yaml_suite/index_' + _v4.snakeCase(branch) + '.js' ); grunt.task.run('mochacov:jenkins_integration'); }); diff --git a/grunt/config/open.js b/grunt/config/open.js index f67d0ab53..2043afa59 100644 --- a/grunt/config/open.js +++ b/grunt/config/open.js @@ -3,4 +3,4 @@ module.exports = { path: 'coverage.html', app: 'Google Chrome' } -}; \ No newline at end of file +}; diff --git a/grunt/config/prompt.js b/grunt/config/prompt.js index 772af5e18..ba7823c6b 100644 --- a/grunt/config/prompt.js +++ b/grunt/config/prompt.js @@ -9,4 +9,4 @@ module.exports = { }] } } -}; \ No newline at end of file +}; diff --git a/grunt/config/s3.js b/grunt/config/s3.js index 73cd1ac47..0bca06e86 100644 --- a/grunt/config/s3.js +++ b/grunt/config/s3.js @@ -22,4 +22,4 @@ module.exports = { } } } -}; \ No newline at end of file +}; diff --git a/grunt/config/saucelabs-mocha.js b/grunt/config/saucelabs-mocha.js index e7bd8cabf..54b681983 100644 --- a/grunt/config/saucelabs-mocha.js +++ b/grunt/config/saucelabs-mocha.js @@ -33,4 +33,4 @@ module.exports = { ] } } -}; \ No newline at end of file +}; diff --git a/grunt/utils.js b/grunt/utils.js index a880791b6..ff4011daa 100644 --- a/grunt/utils.js +++ b/grunt/utils.js @@ -1,4 +1,4 @@ -var _ = require('../src/lib/utils'); +// var _ = require('../src/lib/utils'); var root = require('find-root')(__dirname); var pkg = require(root + '/package.json'); @@ -8,7 +8,7 @@ var branches = [].concat(stable, unstable); var utils = { branchSuffix: function (branch) { - return branch === utils.branches._default ? '' : '_' + _.snakeCase(branch); + return branch === utils.branches._default ? '' : '_' + _v4.snakeCase(branch); }, branches: branches, stableBranches: stable, diff --git a/package.json b/package.json index d671ab364..d16bd021d 100644 --- a/package.json +++ b/package.json @@ -108,7 +108,7 @@ "test": "grunt test", "generate": "node scripts/generate", "grunt": "grunt", - "eslint": "eslint src scripts test" + "eslint": "eslint src scripts test grunt Gruntfile.js" }, "engines": { "node": ">=0.8" diff --git a/scripts/Version.js b/scripts/Version.js index d7f08b029..cd43f4a46 100644 --- a/scripts/Version.js +++ b/scripts/Version.js @@ -1,4 +1,4 @@ -var _ = require('lodash-migrate'); +// var _ = require('lodash'); var pkg = require('../package.json'); var branches = pkg.config.supported_es_branches; var semver = require('semver'); @@ -47,10 +47,10 @@ Version.prototype.mergeOpts = function (opts) { return opts.filter(function (rule) { return self.satisfies(rule.version); }) - .map(_.ary(_.partialRight(_.omit, 'version'), 1)) - .concat(_.tail(arguments)) + .map(_v4.ary(_v4.partialRight(_v4.omit, 'version'), 1)) + .concat(_v4.tail(arguments)) .reverse() - .reduce(_.merge, {}); + .reduce(_v4.merge, {}); }; module.exports = Version; diff --git a/scripts/ci.js b/scripts/ci.js index ac0c2625f..ccb7c9fbb 100644 --- a/scripts/ci.js +++ b/scripts/ci.js @@ -18,7 +18,7 @@ *******/ var Promise = require('bluebird'); -var _ = require('lodash-migrate'); +// var _ = require('lodash'); var through2 = require('through2'); var map = require('through2-map'); var split = require('split'); @@ -80,7 +80,7 @@ task('SAUCE_LABS', false, function () { })); }) // ignore server errors - .catch(_.noop); + .catch(_v4.noop); // attempt to run tests on saucelabs and retry if it fails var saucelabsAttempts = 0; @@ -116,7 +116,7 @@ task('SAUCE_LABS', false, function () { }); }) // swallow spawn() errors, custom error handler in place - .catch(_.noop); + .catch(_v4.noop); }); } }); @@ -168,7 +168,7 @@ execTask('SETUP', function () { }) .then(function readTasks() { if (!ENV.RUN) { - return _.where(TASKS, { default: true }); + return _v4.filter(TASKS, { default: true }); } return ENV.RUN @@ -218,7 +218,7 @@ function logImportant(text) { function push(m) { return function () { - var args = _.toArray(arguments); + var args = _v4.toArray(arguments); var cb = args.pop(); this.push(m.apply(this, args)); cb(); @@ -235,7 +235,7 @@ function indent() { } function task(name, def, fn) { - if (_.isFunction(def)) { + if (_v4.isFunction(def)) { fn = def; def = true; } @@ -248,7 +248,7 @@ function task(name, def, fn) { } function execTask(name, task) { - if (_.isObject(name)) { + if (_v4.isObject(name)) { task = name.fn; name = name.name; } @@ -316,13 +316,13 @@ function spawn(file, args, block) { function node(/* args... */) { return spawn( process.execPath, - _.toArray(arguments) + _v4.toArray(arguments) ); } function grunt(/* args... */) { return spawn( GRUNT, - _.toArray(arguments) + _v4.toArray(arguments) ); } diff --git a/scripts/generate/api_index.js b/scripts/generate/api_index.js index 4704d49cb..a1ae5e33d 100644 --- a/scripts/generate/api_index.js +++ b/scripts/generate/api_index.js @@ -1,9 +1,9 @@ module.exports = function (done) { - var _ = require('../../src/lib/utils'); + // var _ = require('../../src/lib/utils'); var utils = require('../../grunt/utils'); var chalk = require('chalk'); - var fromRoot = _.partial(require('path').join, require('find-root')(__dirname)); + var fromRoot = _v4.partial(require('path').join, require('find-root')(__dirname)); var write = require('fs').writeFileSync; var nodeApiIndex = fromRoot('src/lib/apis/index.js'); diff --git a/scripts/generate/configuration_docs.js b/scripts/generate/configuration_docs.js index 939e8bdae..bc118982b 100644 --- a/scripts/generate/configuration_docs.js +++ b/scripts/generate/configuration_docs.js @@ -1,8 +1,8 @@ module.exports = function (done) { - var _ = require('../../src/lib/utils'); + // var _ = require('../../src/lib/utils'); var chalk = require('chalk'); - var fromRoot = _.partial(require('path').join, require('find-root')(__dirname)); + var fromRoot = _v4.partial(require('path').join, require('find-root')(__dirname)); var write = require('fs').writeFile; var outputPath = fromRoot('docs/configuration.asciidoc'); diff --git a/scripts/generate/doc_index.js b/scripts/generate/doc_index.js index 07cea06f2..bf0394eb4 100644 --- a/scripts/generate/doc_index.js +++ b/scripts/generate/doc_index.js @@ -1,9 +1,9 @@ module.exports = function (done) { - var _ = require('../../src/lib/utils'); + // var _ = require('../../src/lib/utils'); var utils = require('../../grunt/utils'); var chalk = require('chalk'); - var fromRoot = _.partial(require('path').join, require('find-root')(__dirname)); + var fromRoot = _v4.partial(require('path').join, require('find-root')(__dirname)); var write = require('fs').writeFile; var outputPath = fromRoot('docs/index.asciidoc'); diff --git a/scripts/generate/index.js b/scripts/generate/index.js index c2f2f9f03..d80e6a404 100644 --- a/scripts/generate/index.js +++ b/scripts/generate/index.js @@ -30,7 +30,7 @@ var argv = require('optimist') var path = require('path'); var fromRoot = path.join.bind(path, require('find-root')(__dirname)); var utils = require(fromRoot('grunt/utils')); -var _ = require(fromRoot('src/lib/utils')); +// var _ = require(fromRoot('src/lib/utils')); var esUrl = 'https://github.com/elastic/elasticsearch.git'; var branches; @@ -56,10 +56,10 @@ var paths = { docsIndex: fromRoot('docs/index.asciidoc'), apiSrc: 'src/lib/apis', getArchiveDir: function (branch) { - return fromRoot('src/_elasticsearch_' + _.snakeCase(branch)); + return fromRoot('src/_elasticsearch_' + _v4.snakeCase(branch)); }, getArchiveTarball: function (branch) { - return fromRoot('src/_elasticsearch_' + _.snakeCase(branch) + '.tar'); + return fromRoot('src/_elasticsearch_' + _v4.snakeCase(branch) + '.tar'); }, getSpecPathInRepo: function (branch) { return /^v?(master|[2-9]\.)/.test(branch) ? 'rest-api-spec/src/main/resources/rest-api-spec' : 'rest-api-spec'; @@ -93,9 +93,9 @@ function dirRegex(dir, regexp) { } function dirOpts(dir, opts) { - opts = _.isArray(opts) ? opts : [opts]; + opts = _v4.isArray(opts) ? opts : [opts]; return dirFilter(dir, function (name) { - return _.includes(opts, name); + return _v4.includes(opts, name); }); } @@ -130,7 +130,7 @@ function fetchBranchesStep() { function findGeneratedApiFiles() { var anyApiMethodDocs = /^(configuration|index|api_methods).*\.asciidoc$/; var anyApiJsFiled = /^.+\.js$/; - var allBranches = _.isEqual(branches, utils.branches); + var allBranches = _v4.isEqual(branches, utils.branches); if (allBranches) { return [ @@ -140,7 +140,7 @@ function findGeneratedApiFiles() { } return branches.reduce(function (files, branch) { - var b = _.snakeCase(branch); + var b = _v4.snakeCase(branch); files.push(dirOpts(paths.docs, 'api_methods_' + b + '.asciidoc')); @@ -166,7 +166,7 @@ function clearGeneratedFiles() { generatedFiles.push(dirRegex(paths.src, esArchives)); - var rmSteps = _.chain(generatedFiles) + var rmSteps = _v4.chain(generatedFiles) .flattenDeep() .uniq() .map(function (path) { @@ -195,7 +195,7 @@ function createArchive(branch) { var dir = paths.getArchiveDir(branch); var tarball = paths.getArchiveTarball(branch); var specPathInRepo = paths.getSpecPathInRepo(branch); - var subDirCount = _.countBy(specPathInRepo, _.partial(_.eq, '/')).true || 0; + var subDirCount = _v4.countBy(specPathInRepo, _v4.partial(_v4.eq, '/')).true || 0; if (isDirectory(dir)) { console.log(branch + ' archive already exists'); @@ -227,7 +227,7 @@ var steps = [ ].filter(Boolean); branches.forEach(function (branch) { - steps.push(_.partial(async.series, [ + steps.push(_v4.partial(async.series, [ removePrevArchive(branch), createArchive(branch), generateStep(branch) diff --git a/scripts/generate/js_api.js b/scripts/generate/js_api.js index 372b84917..58b1093c6 100644 --- a/scripts/generate/js_api.js +++ b/scripts/generate/js_api.js @@ -3,7 +3,7 @@ module.exports = function (branch, done) { * Read the API actions form the rest-api-spec repo. * @type {[type]} */ - var _ = require('../../src/lib/utils'); + // var _ = require('../../src/lib/utils'); var utils = require('../../grunt/utils'); var fs = require('fs'); var async = require('async'); @@ -19,7 +19,7 @@ module.exports = function (branch, done) { var docVars; // slightly modified clone of apiSpec for the docs var branchSuffix = utils.branchSuffix(branch); - var esDir = fromRoot('src/_elasticsearch_' + _.snakeCase(branch)); + var esDir = fromRoot('src/_elasticsearch_' + _v4.snakeCase(branch)); var version = Version.fromBranch(branch); var overrides = version.mergeOpts(require('./overrides'), { @@ -71,27 +71,27 @@ module.exports = function (branch, done) { }); // collect the namespaces from the action locations - var namespaces = _.filter(_.map(actions, function (action) { + var namespaces = _v4.filter(_v4.map(actions, function (action) { if (~action.location.indexOf('.')) { var path = action.location.split('.').slice(0, -1); - _.pull(path, 'prototype'); + _v4.pull(path, 'prototype'); return path.join('.'); } })); // seperate the proxy actions - var groups = _.groupBy(actions, function (action) { + var groups = _v4.groupBy(actions, function (action) { return action.proxy ? 'proxies' : 'normal'; }); apiSpec = { actions: groups.normal || [], proxies: groups.proxies || [], - namespaces: _.uniq(namespaces.sort(), true), + namespaces: _v4.uniq(namespaces.sort()), clientActionModifier: overrides.clientActionModifier }; - var create = _.assign({}, _v4.find(apiSpec.actions, { name: 'index' }), { + var create = _v4.assign({}, _v4.find(apiSpec.actions, { name: 'index' }), { name: 'create', location: 'create', proxy: 'index', @@ -119,7 +119,7 @@ module.exports = function (branch, done) { } function writeApiFile(done) { - var outputPath = fromRoot('src/lib/apis/' + _.snakeCase(branch) + '.js'); + var outputPath = fromRoot('src/lib/apis/' + _v4.snakeCase(branch) + '.js'); fs.writeFileSync(outputPath, templates.apiFile(apiSpec)); console.log(chalk.white.bold('wrote'), apiSpec.actions.length, 'api actions to', outputPath); done(); @@ -145,8 +145,8 @@ module.exports = function (branch, done) { // merge the actions and proxies to make // itteration easir and keep them in order - docVars = _.omit(apiSpec, 'proxies'); - docVars.actions = _.sortBy( + docVars = _v4.omit(apiSpec, 'proxies'); + docVars.actions = _v4.sortBy( [].concat(apiSpec.actions).concat(apiSpec.proxies), 'name' ); @@ -176,7 +176,7 @@ module.exports = function (branch, done) { // itterate all of the specs within the file, should only be one _v4.each(spec, function (def, name) { // camelcase the name - name = _.map(name.split('.'), _.camelCase).join('.'); + name = _v4.map(name.split('.'), _v4.camelCase).join('.'); if (name === 'cat.aliases') { def.documentation = 'http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat.html'; @@ -185,23 +185,23 @@ module.exports = function (branch, done) { var steps = name.split('.'); function transformParamKeys(note, param, key) { - var cmlKey = _.camelCase(key); + var cmlKey = _v4.camelCase(key); if (cmlKey !== key) { param.name = key; } note[cmlKey] = param; } - def.url.params = _.transform(def.url.params, transformParamKeys, {}); - def.url.parts = _.transform(def.url.parts, transformParamKeys, {}); + def.url.params = _v4.transform(def.url.params, transformParamKeys, {}); + def.url.parts = _v4.transform(def.url.parts, transformParamKeys, {}); - var allParams = _.extend({}, def.url.params, def.url.parts); + var allParams = _v4.extend({}, def.url.params, def.url.parts); var spec = { name: name, - methods: _.map(def.methods, function (m) { return m.toUpperCase(); }), + methods: _v4.map(def.methods, function (m) { return m.toUpperCase(); }), params: def.url.params, body: def.body || null, - path2lib: _.repeat('../', steps.length + 1) + 'lib/' + path2lib: _v4.repeat('../', steps.length + 1) + 'lib/' }; if (def.body && def.body.required) { @@ -216,7 +216,7 @@ module.exports = function (branch, done) { spec.requestTimeout = 3000; } - var urls = _.difference(def.url.paths, overrides.aliases[name]); + var urls = _v4.difference(def.url.paths, overrides.aliases[name]); var urlSignatures = []; urls = _v4.map(urls, function (url) { var optionalVars = {}; @@ -231,47 +231,47 @@ module.exports = function (branch, done) { } while (match = urlParamRE.exec(url)) { - name = _.camelCase(match[1]); + name = _v4.camelCase(match[1]); param = def.url.parts[name] || {}; target = (param.required || !param.default) ? requiredVars : optionalVars; - target[name] = _.omit(param, 'required', 'description', 'name'); + target[name] = _v4.omit(param, 'required', 'description', 'name'); } - urlSignatures.push(_.union(_.keys(optionalVars), _.keys(requiredVars)).sort().join(':')); + urlSignatures.push(_v4.union(_v4.keys(optionalVars), _v4.keys(requiredVars)).sort().join(':')); return _v4.omitBy({ fmt: url.replace(urlParamRE, function (full, match) { - return '<%=' + _.camelCase(match) + '%>'; + return '<%=' + _v4.camelCase(match) + '%>'; }), - opt: _.size(optionalVars) ? optionalVars : null, - req: _.size(requiredVars) ? requiredVars : null, - sortOrder: _.size(requiredVars) * -1 + opt: _v4.size(optionalVars) ? optionalVars : null, + req: _v4.size(requiredVars) ? requiredVars : null, + sortOrder: _v4.size(requiredVars) * -1 }, function (v) { return !v; }); }); - if (urlSignatures.length !== _.uniq(urlSignatures).length) { + if (urlSignatures.length !== _v4.uniq(urlSignatures).length) { throw new Error( 'Multiple URLS with the same signature detected for ' + spec.name + '\n' + - _.map(urls, 'fmt').join('\n') + + _v4.map(urls, 'fmt').join('\n') + '\n' ); } if (urls.length > 1) { - spec.urls = _.map(_.sortBy(urls, 'sortOrder'), function (url) { - return _.omit(url, 'sortOrder'); + spec.urls = _v4.map(_v4.sortBy(urls, 'sortOrder'), function (url) { + return _v4.omit(url, 'sortOrder'); }); } else { - spec.url = _.omit(urls[0], 'sortOrder'); + spec.url = _v4.omit(urls[0], 'sortOrder'); } - spec.params = _.transform(spec.params, function (note, param, name) { + spec.params = _v4.transform(spec.params, function (note, param, name) { // param.name = name; - note[name] = _.pick(param, [ + note[name] = _v4.pick(param, [ 'type', 'default', 'options', 'required', 'name' ]); }, {}); @@ -280,7 +280,7 @@ module.exports = function (branch, done) { spec.paramAsBody = overrides.paramAsBody[name]; } - if (_.size(spec.params) === 0) { + if (_v4.size(spec.params) === 0) { delete spec.params; } @@ -290,7 +290,7 @@ module.exports = function (branch, done) { var action = { _methods: spec.methods, - spec: _.pick(spec, [ + spec: _v4.pick(spec, [ 'params', 'url', 'urls', diff --git a/scripts/generate/templates/api_file.tmpl b/scripts/generate/templates/api_file.tmpl index 90612b1ca..f178293c8 100644 --- a/scripts/generate/templates/api_file.tmpl +++ b/scripts/generate/templates/api_file.tmpl @@ -12,7 +12,7 @@ api._namespaces = <%= stringify(namespaces) %>;<% _v4.each(actions, function (action) { var namespace = action.location.split('.').shift(); if (_.includes(namespaces, namespace)) { - _.pull(namespaces, namespace); + _v4.pull(namespaces, namespace); %> api.<%= namespace %> = namespace();<% diff --git a/scripts/generate/templates/api_index.tmpl b/scripts/generate/templates/api_index.tmpl index 60e14139c..073e9f773 100644 --- a/scripts/generate/templates/api_index.tmpl +++ b/scripts/generate/templates/api_index.tmpl @@ -2,7 +2,7 @@ module.exports = { <% branches.forEach(function (branch, i, list) { - var req = "require('./" + _.snakeCase(branch) + "')"; + var req = "require('./" + _v4.snakeCase(branch) + "')"; if (branch === utils.branches._default) { print(" '_default': " + req + ',\n'); } diff --git a/scripts/generate/templates/api_methods.tmpl b/scripts/generate/templates/api_methods.tmpl index e4bbbc345..eb5d0fa9b 100644 --- a/scripts/generate/templates/api_methods.tmpl +++ b/scripts/generate/templates/api_methods.tmpl @@ -7,7 +7,7 @@ NOTE: This is currently the default API, but in upcoming versions that will chan NOTE: At this time, you must opt into the <%= branch %> API by setting the `apiVersion` config parameter. <% } -actions = _.sortBy(actions, 'namespace'); +actions = _v4.sortBy(actions, 'namespace'); _v4.each(actions, function (action) { action.index = 'api-' + action.name.toLowerCase().replace(/[^\w]+/g, '-') + branchSuffix; @@ -27,7 +27,7 @@ The default method is `<%= action.spec.method || 'GET' %>` and the usual < -<% if (_.size(action.allParams)) { %> +<% if (_v4.size(action.allParams)) { %> *Params* [horizontal]<% diff --git a/scripts/generate/templates/index.js b/scripts/generate/templates/index.js index fc555c3b9..6d281f1f0 100644 --- a/scripts/generate/templates/index.js +++ b/scripts/generate/templates/index.js @@ -1,5 +1,5 @@ -var _ = require('../../../src/lib/utils'); +// var _ = require('../../../src/lib/utils'); var utils = require('../../../grunt/utils'); var fs = require('fs'); var path = require('path'); @@ -41,11 +41,10 @@ var templateGlobals = { stringify: stringify, - _: _, _v4: _v4, indent: function (block, spaces) { - var indent = _.repeat(' ', spaces); + var indent = _v4.repeat(' ', spaces); return block.split('\n').map(function (line) { return indent + line; }).join('\n'); @@ -78,7 +77,7 @@ var templateGlobals = { case 'list': return 'String, String[], Boolean'; default: - return _.ucfirst(type); + return _v4.ucfirst(type); } }, @@ -98,7 +97,7 @@ var templateGlobals = { fs.readdirSync(path.resolve(__dirname)).forEach(function (filename) { var name = filename.replace(/\..+$/, ''); if (name !== 'index') { - templates[name] = _.template( + templates[name] = _v4.template( fs.readFileSync(path.resolve(__dirname, filename), 'utf8'), { imports: templateGlobals diff --git a/scripts/generate/yaml_tests.js b/scripts/generate/yaml_tests.js index a3cdcda17..39c72cfea 100644 --- a/scripts/generate/yaml_tests.js +++ b/scripts/generate/yaml_tests.js @@ -8,10 +8,10 @@ module.exports = function (branch, done) { var chalk = require('chalk'); var path = require('path'); var fromRoot = path.join.bind(path, require('find-root')(__dirname)); - var _ = require(fromRoot('src/lib/utils')); + // var _ = require(fromRoot('src/lib/utils')); var tests = {}; // populated in readYamlTests - var esDir = fromRoot('src/_elasticsearch_' + _.snakeCase(branch)); + var esDir = fromRoot('src/_elasticsearch_' + _v4.snakeCase(branch)); // generate the yaml tests async.series([ @@ -43,15 +43,15 @@ module.exports = function (branch, done) { } function writeYamlTests(done) { - var testFile = fromRoot('test/integration/yaml_suite/yaml_tests_' + _.snakeCase(branch) + '.json'); + var testFile = fromRoot('test/integration/yaml_suite/yaml_tests_' + _v4.snakeCase(branch) + '.json'); fs.writeFileSync(testFile, JSON.stringify(tests, null, ' '), 'utf8'); console.log(chalk.white.bold('wrote') + ' YAML tests as JSON to', testFile); done(); } function writeTestIndex(done) { - var file = fromRoot('test/integration/yaml_suite/index_' + _.snakeCase(branch) + '.js'); - fs.writeFileSync(file, 'require(\'./run\')(\'' + branch + '\');', 'utf8'); + var file = fromRoot('test/integration/yaml_suite/index_' + _v4.snakeCase(branch) + '.js'); + fs.writeFileSync(file, 'require(\'./run\')(\'' + branch + '\');\n', 'utf8'); console.log(chalk.white.bold('wrote') + ' YAML index to', file); done(); } diff --git a/scripts/release/bower.js b/scripts/release/bower.js index e05b6432a..f2d4256a1 100644 --- a/scripts/release/bower.js +++ b/scripts/release/bower.js @@ -1,7 +1,7 @@ var fs = require('fs'); var spawn = require('../_spawn'); var async = require('async'); -var _ = require('lodash-migrate'); +// var _ = require('lodash'); var root = require('path').join(__dirname, '../..'); var bowerDir = root + '/src/bower_es_js'; @@ -21,7 +21,7 @@ fs.writeFileSync(bowerDir + '/bower.json', JSON.stringify(bowerJson, null, ' ') fs.writeFileSync(bowerDir + '/package.json', JSON.stringify(bowerPackageJson, null, ' ')); function make(cmd, args) { - return _.bind(spawn, null, cmd, args, { + return _v4.bind(spawn, null, cmd, args, { verbose: true, cwd: bowerDir }); @@ -36,7 +36,7 @@ async.series([ make('npm', ['publish']) ], function (err) { if (err) { - if (_.isNumber(err)) { + if (_v4.isNumber(err)) { console.log('Non-zero exit code: %d', err); } else { console.log('Error: ', err.message ? err.message : err); diff --git a/src/lib/client.js b/src/lib/client.js index e9b2321ed..48b260bdb 100755 --- a/src/lib/client.js +++ b/src/lib/client.js @@ -28,7 +28,7 @@ module.exports = Client; var Transport = require('./transport'); var clientAction = require('./client_action'); -var _ = require('./utils'); +// var _ = require('./utils'); function Client(config) { config = config || {}; @@ -56,7 +56,7 @@ function Client(config) { this.transport = new Transport(config); - _v4.each(EsApiClient.prototype, _.bind(function (Fn, prop) { + _v4.each(EsApiClient.prototype, _v4.bind(function (Fn, prop) { if (Fn.prototype instanceof clientAction.ApiNamespace) { this[prop] = new Fn(this.transport); } @@ -66,7 +66,7 @@ function Client(config) { } - EsApiClient.prototype = _.funcEnum(config, 'apiVersion', Client.apis, '_default'); + EsApiClient.prototype = _v4.funcEnum(config, 'apiVersion', Client.apis, '_default'); if (!config.sniffEndpoint && EsApiClient.prototype === Client.apis['0.90']) { config.sniffEndpoint = '/_cluster/nodes'; } diff --git a/src/lib/client_action.js b/src/lib/client_action.js index 6b34e2e6f..86080a85f 100644 --- a/src/lib/client_action.js +++ b/src/lib/client_action.js @@ -1,5 +1,5 @@ -var _ = require('./utils'); +// var _ = require('./utils'); /** * Constructs a client action factory that uses specific defaults @@ -34,12 +34,12 @@ exports.namespaceFactory = function () { }; function makeFactoryWithModifier(modifier) { - modifier = modifier || _.identity; + modifier = modifier || _v4.identity; var factory = function (spec) { spec = modifier(spec); - if (!_.isPlainObject(spec.params)) { + if (!_v4.isPlainObject(spec.params)) { spec.params = {}; } @@ -60,7 +60,7 @@ function makeFactoryWithModifier(modifier) { return exec(this.transport, spec, _v4.clone(params), cb); } catch (e) { if (typeof cb === 'function') { - _.nextTick(cb, e); + _v4.nextTick(cb, e); } else { var def = this.transport.defer(); def.reject(e); @@ -97,11 +97,11 @@ function makeFactoryWithModifier(modifier) { var castType = { 'enum': function validSelection(param, val, name) { - if (_.isString(val) && val.indexOf(',') > -1) { + if (_v4.isString(val) && val.indexOf(',') > -1) { val = commaSepList(val); } - if (_.isArray(val)) { + if (_v4.isArray(val)) { return val.map(function (v) { return validSelection(param, v, name); }).join(','); @@ -119,7 +119,7 @@ var castType = { )); }, duration: function (param, val, name) { - if (_.isNumeric(val) || _.isInterval(val)) { + if (_v4.isNumeric(val) || _v4.isInterval(val)) { return val; } else { throw new TypeError( @@ -137,7 +137,7 @@ var castType = { val = commaSepList(val); /* falls through */ case 'object': - if (_.isArray(val)) { + if (_v4.isArray(val)) { return val.join(','); } /* falls through */ @@ -146,11 +146,11 @@ var castType = { } }, 'boolean': function (param, val) { - val = _.isString(val) ? val.toLowerCase() : val; + val = _v4.isString(val) ? val.toLowerCase() : val; return (val === 'no' || val === 'off') ? false : !!val; }, number: function (param, val, name) { - if (_.isNumeric(val)) { + if (_v4.isNumeric(val)) { return val * 1; } else { throw new TypeError('Invalid ' + name + ': expected a number.'); @@ -169,7 +169,7 @@ var castType = { if (typeof val === 'string') { return val; } - else if (_.isNumeric(val)) { + else if (_v4.isNumeric(val)) { return '' + val; } else if (val instanceof Date) { @@ -188,7 +188,7 @@ function resolveUrl(url, params) { // url has required params if (!url.reqParamKeys) { // create cached key list on demand - url.reqParamKeys = _.keys(url.req); + url.reqParamKeys = _v4.keys(url.req); } for (i = 0; i < url.reqParamKeys.length; i ++) { @@ -210,7 +210,7 @@ function resolveUrl(url, params) { if (url.opt) { // url has optional params if (!url.optParamKeys) { - url.optParamKeys = _.keys(url.opt); + url.optParamKeys = _v4.keys(url.opt); } for (i = 0; i < url.optParamKeys.length; i ++) { @@ -229,10 +229,10 @@ function resolveUrl(url, params) { if (!url.template) { // compile the template on demand - url.template = _.template(url.fmt); + url.template = _v4.template(url.fmt); } - return url.template(_.transform(vars, function (note, val, name) { + return url.template(_v4.transform(vars, function (note, val, name) { // encode each value note[name] = encodeURIComponent(val); // remove it from the params so that it isn't sent to the final request @@ -287,14 +287,14 @@ function exec(transport, spec, params, cb) { if (!request.path) { // there must have been some mimimun requirements that were not met var minUrl = spec.url || spec.urls[spec.urls.length - 1]; - throw new TypeError('Unable to build a path with those params. Supply at least ' + _.keys(minUrl.req).join(', ')); + throw new TypeError('Unable to build a path with those params. Supply at least ' + _v4.keys(minUrl.req).join(', ')); } // build the query string if (!spec.paramKeys) { // build a key list on demand - spec.paramKeys = _.keys(spec.params); - spec.requireParamKeys = _.transform(spec.params, function (req, param, key) { + spec.paramKeys = _v4.keys(spec.params); + spec.requireParamKeys = _v4.transform(spec.params, function (req, param, key) { if (param.required) { req.push(key); } @@ -311,10 +311,10 @@ function exec(transport, spec, params, cb) { request[key] = params[key]; break; case 'ignore': - request.ignore = _.isArray(params[key]) ? params[key] : [params[key]]; + request.ignore = _v4.isArray(params[key]) ? params[key] : [params[key]]; break; case 'method': - request.method = _.toUpperString(params[key]); + request.method = _v4.toUpperString(params[key]); break; default: var paramSpec = spec.params[key]; diff --git a/src/lib/connection.js b/src/lib/connection.js index 93c8c38a6..cf7e3d8ac 100644 --- a/src/lib/connection.js +++ b/src/lib/connection.js @@ -1,6 +1,6 @@ module.exports = ConnectionAbstract; -var _ = require('./utils'); +// var _ = require('./utils'); var EventEmitter = require('events').EventEmitter; var Log = require('./log'); var Host = require('./host'); @@ -26,9 +26,9 @@ function ConnectionAbstract(host, config) { throw new TypeError('Invalid host'); } - _.makeBoundMethods(this); + _v4.makeBoundMethods(this); } -_.inherits(ConnectionAbstract, EventEmitter); +_v4.inherits(ConnectionAbstract, EventEmitter); /** * Make a request using this connection. Must be overridden by Connection classes, which can add whatever keys to @@ -61,7 +61,7 @@ ConnectionAbstract.prototype.ping = function (params, cb) { requestTimeout = params.requestTimeout; } - abort = this.request(_.defaults(params || {}, { + abort = this.request(_v4.defaults(params || {}, { path: '/', method: 'HEAD' }), function (err) { diff --git a/src/lib/connection_pool.js b/src/lib/connection_pool.js index 7a892cd48..49c67b445 100644 --- a/src/lib/connection_pool.js +++ b/src/lib/connection_pool.js @@ -9,12 +9,12 @@ module.exports = ConnectionPool; -var _ = require('./utils'); +// var _ = require('./utils'); var Log = require('./log'); function ConnectionPool(config) { config = config || {}; - _.makeBoundMethods(this); + _v4.makeBoundMethods(this); if (!config.log) { this.log = new Log(); @@ -27,16 +27,16 @@ function ConnectionPool(config) { this._config = config; // get the selector config var - this.selector = _.funcEnum(config, 'selector', ConnectionPool.selectors, ConnectionPool.defaultSelector); + this.selector = _v4.funcEnum(config, 'selector', ConnectionPool.selectors, ConnectionPool.defaultSelector); // get the connection class - this.Connection = _.funcEnum(config, 'connectionClass', ConnectionPool.connectionClasses, + this.Connection = _v4.funcEnum(config, 'connectionClass', ConnectionPool.connectionClasses, ConnectionPool.defaultConnectionClass); // time that connections will wait before being revived this.deadTimeout = config.hasOwnProperty('deadTimeout') ? config.deadTimeout : 60000; this.maxDeadTimeout = config.hasOwnProperty('maxDeadTimeout') ? config.maxDeadTimeout : 18e5; - this.calcDeadTimeout = _.funcEnum(config, 'calcDeadTimeout', ConnectionPool.calcDeadTimeoutOptions, 'exponential'); + this.calcDeadTimeout = _v4.funcEnum(config, 'calcDeadTimeout', ConnectionPool.calcDeadTimeoutOptions, 'exponential'); // a map of connections to their "id" property, used when sniffing this.index = {}; @@ -86,7 +86,7 @@ ConnectionPool.prototype.select = function (cb) { this.selector(this._conns.alive, cb); } else { try { - _.nextTick(cb, void 0, this.selector(this._conns.alive)); + _v4.nextTick(cb, void 0, this.selector(this._conns.alive)); } catch (e) { cb(e); } @@ -94,7 +94,7 @@ ConnectionPool.prototype.select = function (cb) { } else if (this._timeouts.length) { this._selectDeadConnection(cb); } else { - _.nextTick(cb, void 0); + _v4.nextTick(cb, void 0); } }; @@ -106,7 +106,7 @@ ConnectionPool.prototype.select = function (cb) { * @param {String} oldStatus - the connection's old status * @param {ConnectionAbstract} connection - the connection object itself */ -ConnectionPool.prototype.onStatusSet = _.handler(function (status, oldStatus, connection) { +ConnectionPool.prototype.onStatusSet = _v4.handler(function (status, oldStatus, connection) { var index; var died = (status === 'dead'); @@ -121,14 +121,14 @@ ConnectionPool.prototype.onStatusSet = _.handler(function (status, oldStatus, co } if (from !== to) { - if (_.isArray(from)) { + if (_v4.isArray(from)) { index = from.indexOf(connection); if (index !== -1) { from.splice(index, 1); } } - if (_.isArray(to)) { + if (_v4.isArray(to)) { index = to.indexOf(connection); if (index === -1) { to.push(connection); @@ -200,11 +200,11 @@ ConnectionPool.prototype._onConnectionDied = function (connection, alreadyWasDea var ms = this.calcDeadTimeout(timeout.attempt, this.deadTimeout); timeout.id = setTimeout(timeout.revive, ms); - timeout.runAt = _.now() + ms; + timeout.runAt = _v4.now() + ms; }; ConnectionPool.prototype._selectDeadConnection = function (cb) { - var orderedTimeouts = _.sortBy(this._timeouts, 'runAt'); + var orderedTimeouts = _v4.sortBy(this._timeouts, 'runAt'); var log = this.log; process.nextTick(function next() { @@ -322,14 +322,14 @@ ConnectionPool.prototype.setHosts = function (hosts) { } } - var removeIds = _.keys(toRemove); + var removeIds = _v4.keys(toRemove); for (i = 0; i < removeIds.length; i++) { this.removeConnection(this.index[removeIds[i]]); } }; ConnectionPool.prototype.getAllHosts = function () { - return _.values(this.index).map(function (connection) { + return _v4.values(this.index).map(function (connection) { return connection.host; }); }; diff --git a/src/lib/connectors/angular.js b/src/lib/connectors/angular.js index 3336c7462..36f010101 100644 --- a/src/lib/connectors/angular.js +++ b/src/lib/connectors/angular.js @@ -6,7 +6,7 @@ */ module.exports = AngularConnector; -var _ = require('../utils'); +// var _ = require('../utils'); var ConnectionAbstract = require('../connection'); var ConnectionFault = require('../errors').ConnectionFault; @@ -20,7 +20,7 @@ function AngularConnector(host, config) { }]); } -_.inherits(AngularConnector, ConnectionAbstract); +_v4.inherits(AngularConnector, ConnectionAbstract); AngularConnector.prototype.request = function (params, cb) { var abort = this.$q.defer(); diff --git a/src/lib/connectors/browser_index.js b/src/lib/connectors/browser_index.js index ad47d6253..2a918cabe 100644 --- a/src/lib/connectors/browser_index.js +++ b/src/lib/connectors/browser_index.js @@ -3,7 +3,7 @@ var opts = { jquery: require('./jquery'), angular: require('./angular') }; -var _ = require('../utils'); +// var _ = require('../utils'); // remove modules that have been ignored by browserify _v4.each(opts, function (conn, name) { diff --git a/src/lib/connectors/http.js b/src/lib/connectors/http.js index 7bb742683..cc3fd4574 100644 --- a/src/lib/connectors/http.js +++ b/src/lib/connectors/http.js @@ -12,7 +12,7 @@ var handles = { http: require('http'), https: require('https') }; -var _ = require('../utils'); +// var _ = require('../utils'); var qs = require('querystring'); var KeepAliveAgent = require('./_keep_alive_agent'); var ConnectionAbstract = require('../connection'); @@ -31,12 +31,12 @@ function HttpConnector(host, config) { this.hand = handles[this.host.protocol]; if (!this.hand) { throw new TypeError('Invalid protocol "' + this.host.protocol + - '", expected one of ' + _.keys(handles).join(', ')); + '", expected one of ' + _v4.keys(handles).join(', ')); } this.useSsl = this.host.protocol === 'https'; - config = _.defaults(config || {}, { + config = _v4.defaults(config || {}, { keepAlive: true, minSockets: 10, // 10 makes sense but 11 actually keeps 10 sockets around @@ -46,9 +46,9 @@ function HttpConnector(host, config) { this.agent = config.createNodeAgent ? config.createNodeAgent(this, config) : this.createAgent(config); } -_.inherits(HttpConnector, ConnectionAbstract); +_v4.inherits(HttpConnector, ConnectionAbstract); -HttpConnector.prototype.onStatusSet = _.handler(function (status) { +HttpConnector.prototype.onStatusSet = _v4.handler(function (status) { if (status === 'closed') { var agent = this.agent; var toRemove = []; @@ -102,7 +102,7 @@ HttpConnector.prototype.makeAgentConfig = function (config) { }; if (this.useSsl) { - _.merge(agentConfig, this.host.ssl); + _v4.merge(agentConfig, this.host.ssl); } return agentConfig; @@ -147,7 +147,7 @@ HttpConnector.prototype.request = function (params, cb) { // general clean-up procedure to run after the request // completes, has an error, or is aborted. - var cleanUp = _.bind(function (err) { + var cleanUp = _v4.bind(function (err) { clearTimeout(timeoutId); request && request.removeAllListeners(); diff --git a/src/lib/connectors/jquery.js b/src/lib/connectors/jquery.js index f935e0497..1f4e504ef 100644 --- a/src/lib/connectors/jquery.js +++ b/src/lib/connectors/jquery.js @@ -7,14 +7,14 @@ */ module.exports = JqueryConnector; -var _ = require('../utils'); +// var _ = require('../utils'); var ConnectionAbstract = require('../connection'); var ConnectionFault = require('../errors').ConnectionFault; function JqueryConnector(host, config) { ConnectionAbstract.call(this, host, config); } -_.inherits(JqueryConnector, ConnectionAbstract); +_v4.inherits(JqueryConnector, ConnectionAbstract); JqueryConnector.prototype.request = function (params, cb) { var ajax = { diff --git a/src/lib/connectors/xhr.js b/src/lib/connectors/xhr.js index 2b21539a6..dd3d56e1c 100644 --- a/src/lib/connectors/xhr.js +++ b/src/lib/connectors/xhr.js @@ -7,7 +7,7 @@ module.exports = XhrConnector; /* jshint browser:true */ -var _ = require('../utils'); +// var _ = require('../utils'); var ConnectionAbstract = require('../connection'); var ConnectionFault = require('../errors').ConnectionFault; var asyncDefault = !(navigator && /PhantomJS/i.test(navigator.userAgent)); @@ -15,13 +15,13 @@ var asyncDefault = !(navigator && /PhantomJS/i.test(navigator.userAgent)); function XhrConnector(host, config) { ConnectionAbstract.call(this, host, config); } -_.inherits(XhrConnector, ConnectionAbstract); +_v4.inherits(XhrConnector, ConnectionAbstract); /** * Simply returns an XHR object cross browser * @type {Function} */ -var getXhr = _.noop; +var getXhr = _v4.noop; if (typeof XMLHttpRequest !== 'undefined') { // rewrite the getXhr method to always return the native implementation @@ -30,7 +30,7 @@ if (typeof XMLHttpRequest !== 'undefined') { }; } else { // find the first MS implementation available - getXhr = _(['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0']) + getXhr = _v4(['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0']) .map(function (appName) { /* jshint unused: false */ try { diff --git a/src/lib/errors.js b/src/lib/errors.js index 1f2273d57..a1d8ec521 100644 --- a/src/lib/errors.js +++ b/src/lib/errors.js @@ -1,4 +1,4 @@ -var _ = require('./utils'); +// var _ = require('./utils'); var qs = require('querystring'); var errors = module.exports; @@ -21,21 +21,21 @@ function ErrorAbstract(msg, constructor, metadata) { } if (metadata) { - _.assign(this, metadata); + _v4.assign(this, metadata); this.toString = function () { return msg + ' :: ' + JSON.stringify(metadata); }; this.toJSON = function () { - return _.assign({ + return _v4.assign({ msg: msg }, metadata); }; } } errors._Abstract = ErrorAbstract; -_.inherits(ErrorAbstract, Error); +_v4.inherits(ErrorAbstract, Error); /** * Connection Error @@ -44,7 +44,7 @@ _.inherits(ErrorAbstract, Error); errors.ConnectionFault = function ConnectionFault(msg) { ErrorAbstract.call(this, msg || 'Connection Failure', errors.ConnectionFault); }; -_.inherits(errors.ConnectionFault, ErrorAbstract); +_v4.inherits(errors.ConnectionFault, ErrorAbstract); /** * No Living Connections @@ -53,7 +53,7 @@ _.inherits(errors.ConnectionFault, ErrorAbstract); errors.NoConnections = function NoConnections(msg) { ErrorAbstract.call(this, msg || 'No Living connections', errors.NoConnections); }; -_.inherits(errors.NoConnections, ErrorAbstract); +_v4.inherits(errors.NoConnections, ErrorAbstract); /** * Generic Error @@ -62,7 +62,7 @@ _.inherits(errors.NoConnections, ErrorAbstract); errors.Generic = function Generic(msg, metadata) { ErrorAbstract.call(this, msg || 'Generic Error', errors.Generic, metadata); }; -_.inherits(errors.Generic, ErrorAbstract); +_v4.inherits(errors.Generic, ErrorAbstract); /** * Request Timeout Error @@ -71,7 +71,7 @@ _.inherits(errors.Generic, ErrorAbstract); errors.RequestTimeout = function RequestTimeout(msg) { ErrorAbstract.call(this, msg || 'Request Timeout', errors.RequestTimeout); }; -_.inherits(errors.RequestTimeout, ErrorAbstract); +_v4.inherits(errors.RequestTimeout, ErrorAbstract); /** @@ -81,7 +81,7 @@ _.inherits(errors.RequestTimeout, ErrorAbstract); errors.Serialization = function Serialization(msg) { ErrorAbstract.call(this, msg || 'Unable to parse/serialize body', errors.Serialization); }; -_.inherits(errors.Serialization, ErrorAbstract); +_v4.inherits(errors.Serialization, ErrorAbstract); /** @@ -90,7 +90,7 @@ _.inherits(errors.Serialization, ErrorAbstract); errors.RequestTypeError = function RequestTypeError(feature) { ErrorAbstract.call(this, 'Cross-domain AJAX requests ' + feature + ' are not supported', errors.RequestTypeError); }; -_.inherits(errors.RequestTypeError, ErrorAbstract); +_v4.inherits(errors.RequestTypeError, ErrorAbstract); var statusCodes = [ [300, 'Multiple Choices'], @@ -142,15 +142,15 @@ _v4.each(statusCodes, function createStatusCodeError(tuple) { var names = tuple[1]; var allNames = [].concat(names, status); var primaryName = allNames[0]; - var className = _.studlyCase(primaryName); - allNames = _.uniq(allNames.concat(className)); + var className = _v4.studlyCase(primaryName); + allNames = _v4.uniq(allNames.concat(className)); function StatusCodeError(msg, metadata) { this.status = status; this.displayName = className; var esErrObject = null; - if (_.isPlainObject(msg)) { + if (_v4.isPlainObject(msg)) { esErrObject = msg; msg = null; } @@ -168,8 +168,8 @@ _v4.each(statusCodes, function createStatusCodeError(tuple) { memo += '[' + cause.type + '] ' + cause.reason; - var extraData = _.omit(cause, ['type', 'reason']); - if (_.size(extraData)) { + var extraData = _v4.omit(cause, ['type', 'reason']); + if (_v4.size(extraData)) { memo += ', with { ' + qs.stringify(extraData, ' ', '=', { encodeURIComponent: function (v) { return String(v).split('\n').join('\\n'); @@ -188,7 +188,7 @@ _v4.each(statusCodes, function createStatusCodeError(tuple) { ErrorAbstract.call(this, msg || primaryName, StatusCodeError, metadata); return this; } - _.inherits(StatusCodeError, ErrorAbstract); + _v4.inherits(StatusCodeError, ErrorAbstract); allNames.forEach(function (name) { errors[name] = StatusCodeError; diff --git a/src/lib/host.js b/src/lib/host.js index 21cdee433..dfa37c332 100644 --- a/src/lib/host.js +++ b/src/lib/host.js @@ -6,7 +6,7 @@ module.exports = Host; var url = require('url'); var qs = require('querystring'); -var _ = require('./utils'); +// var _ = require('./utils'); var startsWithProtocolRE = /^([a-z]+:)?\/\//; var defaultProto = 'http:'; @@ -58,7 +58,7 @@ function Host(config, globalConfig) { this.headers = null; this.suggestCompression = !!globalConfig.suggestCompression; - this.ssl = _.defaults({}, config.ssl || {}, globalConfig.ssl || {}, sslDefaults); + this.ssl = _v4.defaults({}, config.ssl || {}, globalConfig.ssl || {}, sslDefaults); if (typeof config === 'string') { var firstColon = config.indexOf(':'); @@ -69,7 +69,7 @@ function Host(config, globalConfig) { if ((noSlash || portNoPath || portWithPath) && !startsWithProtocolRE.test(config)) { config = defaultProto + '//' + config; } - config = _.pick(url.parse(config, false, true), urlParseFields); + config = _v4.pick(url.parse(config, false, true), urlParseFields); // default logic for the port is to use 9200 for the default. When a string is specified though, // we will use the default from the protocol of the string. if (!config.port) { @@ -83,7 +83,7 @@ function Host(config, globalConfig) { } } - if (_.isObject(config)) { + if (_v4.isObject(config)) { // move hostname/portname to host/port semi-intelligently. _v4.each(simplify, function (to) { var from = to + 'name'; @@ -106,20 +106,20 @@ function Host(config, globalConfig) { delete config.auth; } - _.forOwn(config, function (val, prop) { + _v4.forOwn(config, _v4.bind(function (val, prop) { if (val != null) this[prop] = _v4.clone(val); - }, this); + }, this)); // make sure the query string is parsed if (this.query === null) { // majority case this.query = {}; - } else if (!_.isPlainObject(this.query)) { + } else if (!_v4.isPlainObject(this.query)) { this.query = qs.parse(this.query); } // make sure that the port is a number - if (_.isNumeric(this.port)) { + if (_v4.isNumeric(this.port)) { this.port = parseInt(this.port, 10); } else { this.port = 9200; @@ -177,10 +177,10 @@ function objectPropertyGetter(prop, preOverride) { } if (overrides) { - obj = _.assign({}, obj, overrides); + obj = _v4.assign({}, obj, overrides); } - return _.size(obj) ? obj : null; + return _v4.size(obj) ? obj : null; }; } @@ -189,7 +189,7 @@ Host.prototype.getHeaders = objectPropertyGetter('headers', function (overrides) return overrides; } - return _.defaults(overrides || {}, { + return _v4.defaults(overrides || {}, { 'Accept-Encoding': 'gzip,deflate' }); }); diff --git a/src/lib/log.js b/src/lib/log.js index 9baa30dce..2ebf9e55a 100644 --- a/src/lib/log.js +++ b/src/lib/log.js @@ -1,4 +1,4 @@ -var _ = require('./utils'); +// var _ = require('./utils'); var url = require('url'); var EventEmitter = require('events').EventEmitter; @@ -24,13 +24,13 @@ function Log(config) { var i; var outputs; - if (_.isArrayOfStrings(config.log)) { + if (_v4.isArrayOfStrings(config.log)) { outputs = [{ levels: config.log }]; } else { - outputs = _.createArray(config.log, function (val) { - if (_.isPlainObject(val)) { + outputs = _v4.createArray(config.log, function (val) { + if (_v4.isPlainObject(val)) { return val; } if (typeof val === 'string') { @@ -50,7 +50,7 @@ function Log(config) { this.addOutput(outputs[i]); } } -_.inherits(Log, EventEmitter); +_v4.inherits(Log, EventEmitter); Log.loggers = require('./loggers'); @@ -151,14 +151,14 @@ Log.levels = [ Log.parseLevels = function (input) { switch (typeof input) { case 'string': - var i = _.indexOf(Log.levels, input); + var i = _v4.indexOf(Log.levels, input); if (i >= 0) { return Log.levels.slice(0, i + 1); } /* fall through */ case 'object': - if (_.isArray(input)) { - var valid = _.intersection(input, Log.levels); + if (_v4.isArray(input)) { + var valid = _v4.intersection(input, Log.levels); if (valid.length === input.length) { return valid; } @@ -180,9 +180,9 @@ Log.parseLevels = function (input) { * @return {String} - The final string. */ Log.join = function (arrayish) { - return _.map(arrayish, function (item) { - if (_.isPlainObject(item)) { - return _.inspect(item) + '\n'; + return _v4.map(arrayish, function (item) { + if (_v4.isPlainObject(item)) { + return _v4.inspect(item) + '\n'; } else { return item.toString(); } @@ -209,7 +209,7 @@ Log.prototype.addOutput = function (config) { config.levels = Log.parseLevels(config.levels || config.level || 'warning'); delete config.level; - var Logger = _.funcEnum(config, 'type', Log.loggers, process.browser ? 'console' : 'stdio'); + var Logger = _v4.funcEnum(config, 'type', Log.loggers, process.browser ? 'console' : 'stdio'); return new Logger(this, config); }; diff --git a/src/lib/logger.js b/src/lib/logger.js index e466fec11..fc3283b48 100644 --- a/src/lib/logger.js +++ b/src/lib/logger.js @@ -1,4 +1,4 @@ -var _ = require('./utils'); +// var _ = require('./utils'); /** * Abstract class providing common functionality to loggers @@ -9,7 +9,7 @@ function LoggerAbstract(log, config) { this.log = log; this.listeningLevels = []; - _.makeBoundMethods(this); + _v4.makeBoundMethods(this); // when the log closes, remove our event listeners this.log.once('closing', this.bound.cleanUpListeners); @@ -37,7 +37,7 @@ LoggerAbstract.prototype.timestamp = function () { }; function indent(text, spaces) { - var space = _.repeat(' ', spaces || 2); + var space = _v4.repeat(' ', spaces || 2); return (text || '').split(/\r?\n/).map(function (line) { return space + line; }).join('\n'); @@ -64,8 +64,8 @@ LoggerAbstract.prototype.setupListeners = function (levels) { this.listeningLevels = []; - _v4.each(levels, _.bind(function (level) { - var fnName = 'on' + _.ucfirst(level); + _v4.each(levels, _v4.bind(function (level) { + var fnName = 'on' + _v4.ucfirst(level); if (this.bound[fnName]) { this.listeningLevels.push(level); this.log.on(level, this.bound[fnName]); @@ -82,9 +82,9 @@ LoggerAbstract.prototype.setupListeners = function (levels) { * @private * @return {undefined} */ -LoggerAbstract.prototype.cleanUpListeners = _.handler(function () { - _v4.each(this.listeningLevels, _.bind(function (level) { - this.log.removeListener(level, this.bound['on' + _.ucfirst(level)]); +LoggerAbstract.prototype.cleanUpListeners = _v4.handler(function () { + _v4.each(this.listeningLevels, _v4.bind(function (level) { + this.log.removeListener(level, this.bound['on' + _v4.ucfirst(level)]); }, this)); }); @@ -96,7 +96,7 @@ LoggerAbstract.prototype.cleanUpListeners = _.handler(function () { * @param {Error} e - The Error object to log * @return {undefined} */ -LoggerAbstract.prototype.onError = _.handler(function (e) { +LoggerAbstract.prototype.onError = _v4.handler(function (e) { this.write((e.name === 'Error' ? 'ERROR' : e.name), e.stack); }); @@ -108,7 +108,7 @@ LoggerAbstract.prototype.onError = _.handler(function (e) { * @param {String} msg - The message to be logged * @return {undefined} */ -LoggerAbstract.prototype.onWarning = _.handler(function (msg) { +LoggerAbstract.prototype.onWarning = _v4.handler(function (msg) { this.write('WARNING', msg); }); @@ -120,7 +120,7 @@ LoggerAbstract.prototype.onWarning = _.handler(function (msg) { * @param {String} msg - The message to be logged * @return {undefined} */ -LoggerAbstract.prototype.onInfo = _.handler(function (msg) { +LoggerAbstract.prototype.onInfo = _v4.handler(function (msg) { this.write('INFO', msg); }); @@ -132,7 +132,7 @@ LoggerAbstract.prototype.onInfo = _.handler(function (msg) { * @param {String} msg - The message to be logged * @return {undefined} */ -LoggerAbstract.prototype.onDebug = _.handler(function (msg) { +LoggerAbstract.prototype.onDebug = _v4.handler(function (msg) { this.write('DEBUG', msg); }); @@ -144,7 +144,7 @@ LoggerAbstract.prototype.onDebug = _.handler(function (msg) { * @param {String} msg - The message to be logged * @return {undefined} */ -LoggerAbstract.prototype.onTrace = _.handler(function (requestDetails) { +LoggerAbstract.prototype.onTrace = _v4.handler(function (requestDetails) { this.write('TRACE', this._formatTraceMessage(requestDetails)); }); diff --git a/src/lib/loggers/console.js b/src/lib/loggers/console.js index d5ec9771f..75a7eff03 100644 --- a/src/lib/loggers/console.js +++ b/src/lib/loggers/console.js @@ -13,15 +13,15 @@ module.exports = Console; var LoggerAbstract = require('../logger'); -var _ = require('../utils'); +// var _ = require('../utils'); function Console(log, config) { LoggerAbstract.call(this, log, config); // config/state - this.color = _.has(config, 'color') ? !!config.color : true; + this.color = _v4.has(config, 'color') ? !!config.color : true; } -_.inherits(Console, LoggerAbstract); +_v4.inherits(Console, LoggerAbstract); /** * Override the LoggerAbstract's setup listeners to do a little extra setup @@ -47,7 +47,7 @@ Console.prototype.write = function (label, message, to) { * @param {Error} e - The Error object to log * @return {undefined} */ -Console.prototype.onError = _.handler(function (e) { +Console.prototype.onError = _v4.handler(function (e) { var to = console.error ? 'error' : 'log'; this.write(e.name === 'Error' ? 'ERROR' : e.name, e.stack || e.message, to); }); @@ -60,7 +60,7 @@ Console.prototype.onError = _.handler(function (e) { * @param {String} msg - The message to be logged * @return {undefined} */ -Console.prototype.onWarning = _.handler(function (msg) { +Console.prototype.onWarning = _v4.handler(function (msg) { this.write('WARNING', msg, console.warn ? 'warn' : 'log'); }); @@ -72,7 +72,7 @@ Console.prototype.onWarning = _.handler(function (msg) { * @param {String} msg - The message to be logged * @return {undefined} */ -Console.prototype.onInfo = _.handler(function (msg) { +Console.prototype.onInfo = _v4.handler(function (msg) { this.write('INFO', msg, console.info ? 'info' : 'log'); }); @@ -84,7 +84,7 @@ Console.prototype.onInfo = _.handler(function (msg) { * @param {String} msg - The message to be logged * @return {undefined} */ -Console.prototype.onDebug = _.handler(function (msg) { +Console.prototype.onDebug = _v4.handler(function (msg) { this.write('DEBUG', msg, console.debug ? 'debug' : 'log'); }); /** @@ -94,6 +94,6 @@ Console.prototype.onDebug = _.handler(function (msg) { * @private * @return {undefined} */ -Console.prototype.onTrace = _.handler(function (msg) { +Console.prototype.onTrace = _v4.handler(function (msg) { this.write('TRACE', this._formatTraceMessage(msg), 'log'); }); diff --git a/src/lib/loggers/file.js b/src/lib/loggers/file.js index 4b4357f96..35bf273a4 100755 --- a/src/lib/loggers/file.js +++ b/src/lib/loggers/file.js @@ -12,7 +12,7 @@ module.exports = File; var StreamLogger = require('./stream'); -var _ = require('../utils'); +// var _ = require('../utils'); var fs = require('fs'); function File(log, config) { @@ -29,10 +29,10 @@ function File(log, config) { StreamLogger.call(this, log, config); } -_.inherits(File, StreamLogger); +_v4.inherits(File, StreamLogger); -File.prototype.onProcessExit = _.handler(function () { - var toWrite = _.getUnwrittenFromStream(this.stream); +File.prototype.onProcessExit = _v4.handler(function () { + var toWrite = _v4.getUnwrittenFromStream(this.stream); if (toWrite) { fs.appendFileSync(this.path, toWrite); } diff --git a/src/lib/loggers/stdio.js b/src/lib/loggers/stdio.js index 1ba868d33..0caa7454f 100755 --- a/src/lib/loggers/stdio.js +++ b/src/lib/loggers/stdio.js @@ -17,7 +17,7 @@ var chalk = require('chalk'); chalk.enabled = true; var LoggerAbstract = require('../logger'); -var _ = require('../utils'); +// var _ = require('../utils'); var defaultColors = { error: chalk.red.bold, @@ -31,12 +31,12 @@ function Stdio(log, config) { LoggerAbstract.call(this, log, config); // config/state - this.color = !!(_.has(config, 'color') ? config.color : chalk.supportsColor); + this.color = !!(_v4.has(config, 'color') ? config.color : chalk.supportsColor); - this.colors = _.defaults(config.colors || {}, defaultColors); + this.colors = _v4.defaults(config.colors || {}, defaultColors); } -_.inherits(Stdio, LoggerAbstract); +_v4.inherits(Stdio, LoggerAbstract); /** * Sends output to a stream, does some formatting first @@ -65,7 +65,7 @@ Stdio.prototype.write = function (label, message, to, colorize) { * @param {Error} e - The Error object to log * @return {undefined} */ -Stdio.prototype.onError = _.handler(function (e) { +Stdio.prototype.onError = _v4.handler(function (e) { this.write(e.name === 'Error' ? 'ERROR' : e.name, e.stack, process.stderr, this.colors.error); }); @@ -77,7 +77,7 @@ Stdio.prototype.onError = _.handler(function (e) { * @param {String} msg - The message to be logged * @return {undefined} */ -Stdio.prototype.onWarning = _.handler(function (msg) { +Stdio.prototype.onWarning = _v4.handler(function (msg) { this.write('WARNING', msg, process.stderr, this.colors.warning); }); @@ -89,7 +89,7 @@ Stdio.prototype.onWarning = _.handler(function (msg) { * @param {String} msg - The message to be logged * @return {undefined} */ -Stdio.prototype.onInfo = _.handler(function (msg) { +Stdio.prototype.onInfo = _v4.handler(function (msg) { this.write('INFO', msg, process.stdout, this.colors.info); }); @@ -101,7 +101,7 @@ Stdio.prototype.onInfo = _.handler(function (msg) { * @param {String} msg - The message to be logged * @return {undefined} */ -Stdio.prototype.onDebug = _.handler(function (msg) { +Stdio.prototype.onDebug = _v4.handler(function (msg) { this.write('DEBUG', msg, process.stdout, this.colors.debug); }); @@ -112,6 +112,6 @@ Stdio.prototype.onDebug = _.handler(function (msg) { * @private * @return {undefined} */ -Stdio.prototype.onTrace = _.handler(function (message) { +Stdio.prototype.onTrace = _v4.handler(function (message) { this.write('TRACE', this._formatTraceMessage(message), process.stdout, this.colors.trace); }); diff --git a/src/lib/loggers/stream.js b/src/lib/loggers/stream.js index 235440d15..55f2d10d9 100755 --- a/src/lib/loggers/stream.js +++ b/src/lib/loggers/stream.js @@ -13,7 +13,7 @@ module.exports = Stream; var LoggerAbstract = require('../logger'); -var _ = require('../utils'); +// var _ = require('../utils'); function Stream(log, config) { LoggerAbstract.call(this, log, config); @@ -26,17 +26,17 @@ function Stream(log, config) { process.once('exit', this.bound.onProcessExit); } -_.inherits(Stream, LoggerAbstract); +_v4.inherits(Stream, LoggerAbstract); -Stream.prototype.cleanUpListeners = _.handler(function () { +Stream.prototype.cleanUpListeners = _v4.handler(function () { process.removeListener('exit', this.bound.onProcessExit); LoggerAbstract.prototype.cleanUpListeners.call(this); }); // flush the write buffer to stderr synchronously -Stream.prototype.onProcessExit = _.handler(function () { +Stream.prototype.onProcessExit = _v4.handler(function () { // process is dying, lets manually flush the buffer synchronously to stderr. - var unwritten = _.getUnwrittenFromStream(this.stream); + var unwritten = _v4.getUnwrittenFromStream(this.stream); if (unwritten) { console.error('Log stream did not get to finish writing. Flushing to stderr'); console.error(unwritten); diff --git a/src/lib/loggers/tracer.js b/src/lib/loggers/tracer.js index c79b48c5e..a3b85fdd2 100755 --- a/src/lib/loggers/tracer.js +++ b/src/lib/loggers/tracer.js @@ -14,7 +14,7 @@ module.exports = Tracer; var StreamLogger = require('./stream'); var fs = require('fs'); -var _ = require('../utils'); +// var _ = require('../utils'); var url = require('url'); function Tracer(log, config) { @@ -29,18 +29,18 @@ function Tracer(log, config) { StreamLogger.call(this, log, config); } -_.inherits(Tracer, StreamLogger); +_v4.inherits(Tracer, StreamLogger); var usefulUrlFields = ['protocol', 'slashes', 'port', 'hostname', 'pathname', 'query']; Tracer.prototype._formatTraceMessage = function (req) { - var reqUrl = _.pick(url.parse(req.url, true, false), usefulUrlFields); + var reqUrl = _v4.pick(url.parse(req.url, true, false), usefulUrlFields); - var originalHost = url.format(_.pick(reqUrl, 'protocol', 'hostname', 'port')); + var originalHost = url.format(_v4.pick(reqUrl, 'protocol', 'hostname', 'port')); reqUrl.port = this.curlPort; reqUrl.hostname = this.curlHost; - reqUrl.query = _.defaults(reqUrl.query || {}, { pretty: true }); + reqUrl.query = _v4.defaults(reqUrl.query || {}, { pretty: true }); /* jshint quotmark: double */ var curlCall = @@ -56,7 +56,7 @@ Tracer.prototype._formatTraceMessage = function (req) { }; function comment(str) { - return _.map(str.split(/\r?\n/g), function (line) { + return _v4.map(str.split(/\r?\n/g), function (line) { return '# ' + line; }).join('\n'); } diff --git a/src/lib/nodes_to_host.js b/src/lib/nodes_to_host.js index 4e6a01de3..3c63d81d0 100644 --- a/src/lib/nodes_to_host.js +++ b/src/lib/nodes_to_host.js @@ -1,10 +1,10 @@ -var _ = require('./utils'); +// var _ = require('./utils'); var extractHostPartsRE1x = /\[\/*([^:]+):(\d+)\]/; function makeNodeParser(hostProp) { return function (nodes) { - return _.transform(nodes, function (hosts, node, id) { + return _v4.transform(nodes, function (hosts, node, id) { var address = node[hostProp] if (!address) return; diff --git a/src/lib/serializers/angular.js b/src/lib/serializers/angular.js index 1548badc1..290a1e7a4 100644 --- a/src/lib/serializers/angular.js +++ b/src/lib/serializers/angular.js @@ -1,9 +1,9 @@ /* global angular */ -var _ = require('../utils'); +// var _ = require('../utils'); var JsonSerializer = require('../serializers/json'); function AngularSerializer() {} -_.inherits(AngularSerializer, JsonSerializer); +_v4.inherits(AngularSerializer, JsonSerializer); // mimic the JsonSerializer's encode method, but use angular's toJson instead AngularSerializer.prototype.encode = function (val) { diff --git a/src/lib/serializers/json.js b/src/lib/serializers/json.js index 091806784..c8421123e 100755 --- a/src/lib/serializers/json.js +++ b/src/lib/serializers/json.js @@ -4,7 +4,7 @@ */ module.exports = Json; -var _ = require('../utils'); +// var _ = require('../utils'); function Json() {} @@ -46,7 +46,7 @@ Json.prototype.deserialize = function (str) { Json.prototype.bulkBody = function (val) { var body = '', i; - if (_.isArray(val)) { + if (_v4.isArray(val)) { for (i = 0; i < val.length; i++) { body += this.serialize(val[i]) + '\n'; } diff --git a/src/lib/transport.js b/src/lib/transport.js index 88c559573..4561bb603 100644 --- a/src/lib/transport.js +++ b/src/lib/transport.js @@ -4,7 +4,7 @@ */ module.exports = Transport; -var _ = require('./utils'); +// var _ = require('./utils'); var errors = require('./errors'); var Host = require('./host'); var Promise = require('promise/lib/es6-extensions'); @@ -19,15 +19,15 @@ function Transport(config) { config.log = self.log = new LogClass(config); // setup the connection pool - var ConnectionPool = _.funcEnum(config, 'connectionPool', Transport.connectionPools, 'main'); + var ConnectionPool = _v4.funcEnum(config, 'connectionPool', Transport.connectionPools, 'main'); self.connectionPool = new ConnectionPool(config); // setup the serializer - var Serializer = _.funcEnum(config, 'serializer', Transport.serializers, 'json'); + var Serializer = _v4.funcEnum(config, 'serializer', Transport.serializers, 'json'); self.serializer = new Serializer(config); // setup the nodesToHostCallback - self.nodesToHostCallback = _.funcEnum(config, 'nodesToHostCallback', Transport.nodesToHostCallbacks, 'main'); + self.nodesToHostCallback = _v4.funcEnum(config, 'nodesToHostCallback', Transport.nodesToHostCallbacks, 'main'); // setup max retries self.maxRetries = config.hasOwnProperty('maxRetries') ? config.maxRetries : 3; @@ -50,8 +50,8 @@ function Transport(config) { } if (config.hosts) { - var hostsConfig = _.createArray(config.hosts, function (val) { - if (_.isPlainObject(val) || _.isString(val) || val instanceof Host) { + var hostsConfig = _v4.createArray(config.hosts, function (val) { + if (_v4.isPlainObject(val) || _v4.isString(val) || val instanceof Host) { return val; } }); @@ -139,7 +139,7 @@ Transport.prototype.request = function (params, cb) { var defer; // the defer object, will be set when we are using promises. var body = params.body; - var headers = !params.headers ? {} : _.transform(params.headers, function (headers, val, name) { + var headers = !params.headers ? {} : _v4.transform(params.headers, function (headers, val, name) { headers[String(name).toLowerCase()] = val; }); @@ -161,7 +161,7 @@ Transport.prototype.request = function (params, cb) { } if (body && params.method === 'GET') { - _.nextTick(respond, new TypeError('Body can not be sent with method "GET"')); + _v4.nextTick(respond, new TypeError('Body can not be sent with method "GET"')); return ret; } @@ -274,10 +274,10 @@ Transport.prototype.request = function (params, cb) { if ( (!err || err instanceof errors.Serialization) && (status < 200 || status >= 300) - && (!params.ignore || !_.includes(params.ignore, status)) + && (!params.ignore || !_v4.includes(params.ignore, status)) ) { - var errorMetadata = _.pick(params.req, ['path', 'query', 'body']); + var errorMetadata = _v4.pick(params.req, ['path', 'query', 'body']); errorMetadata.statusCode = status; errorMetadata.response = body; @@ -361,7 +361,7 @@ Transport.prototype._timeout = function (cb, delay) { if (cb) { // set the timer id = setTimeout(function () { - _.pull(timers, id); + _v4.pull(timers, id); cb(); }, delay); @@ -392,7 +392,7 @@ Transport.prototype.sniff = function (cb) { var sniffedNodesProtocol = this.sniffedNodesProtocol; // make cb a function if it isn't - cb = typeof cb === 'function' ? cb : _.noop; + cb = typeof cb === 'function' ? cb : _v4.noop; this.request({ path: this.sniffEndpoint, @@ -409,7 +409,7 @@ Transport.prototype.sniff = function (cb) { return; } - _.forEach(hostsConfigs, function (hostConfig) { + _v4.forEach(hostsConfigs, function (hostConfig) { if (sniffedNodesProtocol) hostConfig.protocol = sniffedNodesProtocol; }); @@ -427,7 +427,7 @@ Transport.prototype.sniff = function (cb) { */ Transport.prototype.setHosts = function (hostsConfigs) { var globalConfig = this._config; - this.connectionPool.setHosts(_.map(hostsConfigs, function (conf) { + this.connectionPool.setHosts(_v4.map(hostsConfigs, function (conf) { return (conf instanceof Host) ? conf : new Host(conf, globalConfig); })); }; diff --git a/src/lib/transport/sniff_on_connection_fault.js b/src/lib/transport/sniff_on_connection_fault.js index e7bd8c089..cc45fa249 100644 --- a/src/lib/transport/sniff_on_connection_fault.js +++ b/src/lib/transport/sniff_on_connection_fault.js @@ -1,4 +1,4 @@ -var _ = require('../utils'); +// var _ = require('../utils'); /** @@ -25,7 +25,7 @@ module.exports = function setupSniffOnConnectionFault(transport) { // create a function that will count down to a // point n milliseconds into the future var countdownTo = function (ms) { - var start = _.now(); + var start = _v4.now(); return function () { return start - ms; }; diff --git a/src/lib/utils.js b/src/lib/utils.js index 1f4247066..25167bab1 100644 --- a/src/lib/utils.js +++ b/src/lib/utils.js @@ -1,25 +1,26 @@ var path = require('path'); -var _ = require('lodash-migrate'); +// var _ = require('lodash'); +// require('../../stub') var nodeUtils = require('util'); /** - * Custom utils library, basically a modified version of [lodash](http://lodash.com/docs) + - * [node.utils](http://nodejs.org/api/util.html#util_util) that doesn't use mixins to prevent + * Custom _v4 library, basically a modified version of [lodash](http://lodash.com/docs) + + * [node._v4](http://nodejs.org/api/util.html#util_util) that doesn't use mixins to prevent * confusion when requiring lodash itself. * - * @class utils + * @class _v4 * @static */ -var utils = _.extend({}, _, nodeUtils); -_ = utils; +_v4.assign(_v4, nodeUtils); +// _v4 = _v4; /** * Link to [path.join](http://nodejs.org/api/path.html#path_path_join_path1_path2) * - * @method utils.joinPath + * @method _v4.joinPath * @type {function} */ -utils.joinPath = path.join; +_v4.joinPath = path.join; /** * Recursively merge two objects, walking into each object and concating arrays. If both to and from have a value at a @@ -31,18 +32,18 @@ utils.joinPath = path.join; * @param {Object} from - Object to pull changed from * @return {Object} - returns the modified to value */ -utils.deepMerge = function (to, from) { +_v4.deepMerge = function (to, from) { _v4.each(from, function (fromVal, key) { switch (typeof to[key]) { case 'undefined': to[key] = from[key]; break; case 'object': - if (_.isArray(to[key]) && _.isArray(from[key])) { + if (_v4.isArray(to[key]) && _v4.isArray(from[key])) { to[key] = to[key].concat(from[key]); } - else if (_.isPlainObject(to[key]) && _.isPlainObject(from[key])) { - utils.deepMerge(to[key], from[key]); + else if (_v4.isPlainObject(to[key]) && _v4.isPlainObject(from[key])) { + _v4.deepMerge(to[key], from[key]); } } }); @@ -65,11 +66,11 @@ _v4.each([ 'Function', 'RegExp' ], function (type) { - var check = _['is' + type]; + var check = _v4['is' + type]; - utils['isArrayOf' + type + 's'] = function (arr) { + _v4['isArrayOf' + type + 's'] = function (arr) { // quick shallow check of arrays - return _.isArray(arr) && _.every(arr.slice(0, 10), check); + return _v4.isArray(arr) && _v4.every(arr.slice(0, 10), check); }; }); @@ -81,7 +82,7 @@ _v4.each([ * @param {string} word - The word to transform * @return {string} */ -utils.ucfirst = function (word) { +_v4.ucfirst = function (word) { return word[0].toUpperCase() + word.substring(1).toLowerCase(); }; @@ -142,7 +143,7 @@ function adjustWordCase(firstWordCap, otherWordsCap, sep) { * @param {String} string * @return {String} */ -utils.studlyCase = adjustWordCase(true, true, ''); +_v4.studlyCase = adjustWordCase(true, true, ''); /** * Transform a string into camelCase @@ -151,7 +152,7 @@ utils.studlyCase = adjustWordCase(true, true, ''); * @param {String} string * @return {String} */ -utils.camelCase = adjustWordCase(false, true, ''); +_v4.camelCase = adjustWordCase(false, true, ''); /** * Transform a string into snakeCase @@ -160,7 +161,7 @@ utils.camelCase = adjustWordCase(false, true, ''); * @param {String} string * @return {String} */ -utils.snakeCase = adjustWordCase(false, false, '_'); +_v4.snakeCase = adjustWordCase(false, false, '_'); /** * Lower-case a string, and return an empty string if any is not a string @@ -168,7 +169,7 @@ utils.snakeCase = adjustWordCase(false, false, '_'); * @param any {*} - Something or nothing * @returns {string} */ -utils.toLowerString = function (any) { +_v4.toLowerString = function (any) { if (any) { if (typeof any !== 'string') { any = any.toString(); @@ -185,7 +186,7 @@ utils.toLowerString = function (any) { * @param any {*} - Something or nothing * @returns {string} */ -utils.toUpperString = function (any) { +_v4.toUpperString = function (any) { if (any) { if (typeof any !== 'string') { any = any.toString(); @@ -203,7 +204,7 @@ utils.toUpperString = function (any) { * @param {*} val * @return {Boolean} */ -utils.isNumeric = function (val) { +_v4.isNumeric = function (val) { return typeof val !== 'object' && val - parseFloat(val) >= 0; }; @@ -217,7 +218,7 @@ var intervalRE = /^(\d+(?:\.\d+)?)(M|w|d|h|m|s|y|ms)$/; * @param {String} val * @return {Boolean} */ -utils.isInterval = function (val) { +_v4.isInterval = function (val) { return !!(val.match && val.match(intervalRE)); }; @@ -230,7 +231,7 @@ utils.isInterval = function (val) { * @param {Number} times - Times the string should be repeated * @return {String} */ -utils.repeat = function (what, times) { +_v4.repeat = function (what, times) { return (new Array(times + 1)).join(what); }; @@ -243,7 +244,7 @@ utils.repeat = function (what, times) { * @param [sliceIndex=0] {Integer} - The index that args should be sliced at, before feeding args to func * @returns {*} - the return value of func */ -utils.applyArgs = function (func, context, args, sliceIndex) { +_v4.applyArgs = function (func, context, args, sliceIndex) { sliceIndex = sliceIndex || 0; switch (args.length - sliceIndex) { case 0: @@ -269,9 +270,9 @@ utils.applyArgs = function (func, context, args, sliceIndex) { * when it is called. * @return {[type]} [description] */ -_.nextTick = function (cb) { +_v4.nextTick = function (cb) { // bind the function and schedule it - process.nextTick(_.bindKey(_, 'applyArgs', cb, null, arguments, 1)); + process.nextTick(_v4.bindKey(_v4, 'applyArgs', cb, null, arguments, 1)); }; /** @@ -279,7 +280,7 @@ _.nextTick = function (cb) { * flagging it to be bound to the object at object creation when "makeBoundMethods" is called * * ``` - * ClassName.prototype.methodName = _.handler(function () { + * ClassName.prototype.methodName = _v4.handler(function () { * // this will always be bound when called via classInstance.bound.methodName * this === classInstance * }); @@ -289,11 +290,11 @@ _.nextTick = function (cb) { * @param {Function} func - The method that is being defined * @return {Function} */ -_.handler = function (func) { +_v4.handler = function (func) { func._provideBound = true; return func; }; -_.scheduled = _.handler; +_v4.scheduled = _v4.handler; /** * Creates an "bound" property on an object, which all or a subset of methods from @@ -304,24 +305,24 @@ _.scheduled = _.handler; * onEvent: function () {} * }; * - * _.makeBoundMethods(obj); + * _v4.makeBoundMethods(obj); * * obj.bound.onEvent() // is bound to obj, and can safely be used as an event handler. * ``` * * @param {Object} obj - The object to bind the methods to */ -_.makeBoundMethods = function (obj) { +_v4.makeBoundMethods = function (obj) { obj.bound = {}; for (var prop in obj) { // dearest maintainer, we want to look through the prototype if (typeof obj[prop] === 'function' && obj[prop]._provideBound === true) { - obj.bound[prop] = _.bind(obj[prop], obj); + obj.bound[prop] = _v4.bind(obj[prop], obj); } } }; -_.noop = function () {}; +_v4.noop = function () {}; /** * Implements the standard "string or constructor" check that I was copy/pasting everywhere @@ -329,7 +330,7 @@ _.noop = function () {}; * @param {Object} opts - a map of the options * @return {Function|undefined} - If a valid option was specified, then the constructor is returned */ -_.funcEnum = function (config, name, opts, def) { +_v4.funcEnum = function (config, name, opts, def) { var val = config[name]; switch (typeof val) { case 'undefined': @@ -343,14 +344,14 @@ _.funcEnum = function (config, name, opts, def) { /* falls through */ default: var err = 'Invalid ' + name + ' "' + val + '", expected a function'; - switch (_.size(opts)) { + switch (_v4.size(opts)) { case 0: break; case 1: - err += ' or ' + _.keys(opts)[0]; + err += ' or ' + _v4.keys(opts)[0]; break; default: - err += ' or one of ' + _.keys(opts).join(', '); + err += ' or one of ' + _v4.keys(opts).join(', '); break; } throw new TypeError(err); @@ -367,13 +368,13 @@ _.funcEnum = function (config, name, opts, def) { * @param {Function} transform - A function called for each element of the resulting array * @return {Array|false} - an array on success, or false on failure. */ -_.createArray = function (input, transform) { - transform = typeof transform === 'function' ? transform : _.identity; +_v4.createArray = function (input, transform) { + transform = typeof transform === 'function' ? transform : _v4.identity; var output = []; var item; var i; - if (!_.isArray(input)) { + if (!_v4.isArray(input)) { input = [input]; } @@ -396,8 +397,8 @@ _.createArray = function (input, transform) { * @param {WritableStream} stream - an instance of stream.Writable * @return {string} - the remaining test to be written to the stream */ -_.getUnwrittenFromStream = function (stream) { - var writeBuffer = _.getStreamWriteBuffer(stream); +_v4.getUnwrittenFromStream = function (stream) { + var writeBuffer = _v4.getStreamWriteBuffer(stream); if (!writeBuffer) return; // flush the write buffer @@ -408,7 +409,7 @@ _.getUnwrittenFromStream = function (stream) { if (writeReq.chunk) { // 0.9.12+ uses WriteReq objects with a chunk prop out += '' + writeReq.chunk; - } else if (_.isArray(writeReq) && (typeof writeReq[0] === 'string' || Buffer.isBuffer(writeReq[0]))) { + } else if (_v4.isArray(writeReq) && (typeof writeReq[0] === 'string' || Buffer.isBuffer(writeReq[0]))) { // 0.9.4 - 0.9.9 buffers are arrays of arrays like [[chunk, cb], [chunk, undef], ...]. out += '' + writeReq[0]; } else { @@ -418,7 +419,7 @@ _.getUnwrittenFromStream = function (stream) { return out; }; -_.getStreamWriteBuffer = function (stream) { +_v4.getStreamWriteBuffer = function (stream) { if (!stream || !stream._writableState) return; var writeState = stream._writableState; @@ -430,16 +431,16 @@ _.getStreamWriteBuffer = function (stream) { } }; -_.clearWriteStreamBuffer = function (stream) { - var buffer = _.getStreamWriteBuffer(stream); +_v4.clearWriteStreamBuffer = function (stream) { + var buffer = _v4.getStreamWriteBuffer(stream); return buffer && buffer.splice(0); }; /** * return the current time in milliseconds since epoch */ -_.now = function () { +_v4.now = function () { return (typeof Date.now === 'function') ? Date.now() : (new Date()).getTime(); }; -module.exports = utils; +module.exports = _v4; diff --git a/test/fixtures/keepalive.js b/test/fixtures/keepalive.js index a929f8788..a6c0a3c5f 100644 --- a/test/fixtures/keepalive.js +++ b/test/fixtures/keepalive.js @@ -1,6 +1,6 @@ var clock = require('sinon').useFakeTimers(); var Client = require('../../src/elasticsearch').Client; -var _ = require('lodash-migrate'); +// var _ = require('lodash'); var times = require('async').times; process.once('message', function (port) { @@ -20,9 +20,9 @@ process.once('message', function (port) { clock.tick(10); }, function (err) { var conns = es.transport.connectionPool._conns; - var sockets = _([].concat(conns.dead, conns.alive)) + var sockets = _v4([].concat(conns.dead, conns.alive)) .transform(function (sockets, conn) { - sockets.push(_.values(conn.agent.sockets), _.values(conn.agent.freeSockets)); + sockets.push(_v4.values(conn.agent.sockets), _v4.values(conn.agent.freeSockets)); }, []) .flattenDeep() .value(); @@ -31,8 +31,8 @@ process.once('message', function (port) { var out = { socketCount: err || sockets.length, - remaining: _.where(sockets, { destroyed: true }).length - sockets.length, - timeouts: _.size(clock.timers) && _.map(clock.timers, 'func').map(String) + remaining: _v4.filter(sockets, { destroyed: true }).length - sockets.length, + timeouts: _v4.size(clock.timers) && _v4.map(clock.timers, 'func').map(String) }; clock.restore(); diff --git a/test/integration/yaml_suite/client_manager.js b/test/integration/yaml_suite/client_manager.js index 4cc481a7b..e67503643 100644 --- a/test/integration/yaml_suite/client_manager.js +++ b/test/integration/yaml_suite/client_manager.js @@ -9,10 +9,10 @@ if (BROWSER) { es = require('../../../src/elasticsearch'); } -var _ = require('../../../src/lib/utils'); +// var _ = require('../../../src/lib/utils'); var path = require('path'); var fs = require('fs'); -var fromRoot = _.bindKey(path, 'join', require('find-root')(__dirname)); +var fromRoot = _v4.bindKey(path, 'join', require('find-root')(__dirname)); var Bluebird = require('bluebird'); // current client @@ -60,7 +60,7 @@ module.exports = { } var logConfig = {}; - if (_.has(options, 'logConfig')) { + if (_v4.has(options, 'logConfig')) { logConfig = options.logConfig; } else { if (BROWSER) { @@ -106,14 +106,14 @@ module.exports = { client.snapshot.getRepository({ snapshot: '_all' }) - .then(_.keys) + .then(_v4.keys) .map(function (repo) { return client.snapshot.get({ repository: repo, snapshot: '_all' }) .then(function (resp) { - return _.map(resp.snapshots, 'snapshot'); + return _v4.map(resp.snapshots, 'snapshot'); }, function () { return []; }) @@ -132,7 +132,7 @@ module.exports = { ]); }; - _.nextTick(cb); + _v4.nextTick(cb); } }, get: function () { diff --git a/test/integration/yaml_suite/run.js b/test/integration/yaml_suite/run.js index dddd72efe..f5ec5cf23 100644 --- a/test/integration/yaml_suite/run.js +++ b/test/integration/yaml_suite/run.js @@ -4,7 +4,7 @@ module.exports = function (branch) { var YamlFile = require('./yaml_file'); var root = require('find-root')(__dirname); var rootReq = function (loc) { return require(path.join(root, loc)); }; - var _ = rootReq('src/lib/utils'); + // var _ = rootReq('src/lib/utils'); var utils = rootReq('grunt/utils'); var es = rootReq('src/elasticsearch'); var clientManager = require('./client_manager'); @@ -32,7 +32,7 @@ module.exports = function (branch) { return clientManager.get().clearEs(); }); - var files = _v4.map(require('./yaml_tests_' + _.snakeCase(branch) + '.json'), function (docs, filename) { + var files = _v4.map(require('./yaml_tests_' + _v4.snakeCase(branch) + '.json'), function (docs, filename) { return new YamlFile(filename, docs); }); diff --git a/test/integration/yaml_suite/yaml_doc.js b/test/integration/yaml_suite/yaml_doc.js index f59e2b8c1..089b4d082 100644 --- a/test/integration/yaml_suite/yaml_doc.js +++ b/test/integration/yaml_suite/yaml_doc.js @@ -9,7 +9,7 @@ */ module.exports = YamlDoc; -var _ = require('lodash-migrate/lodash'); +// var _ = require('lodash-migrate/lodash'); var expect = require('expect.js'); var clientManager = require('./client_manager'); var inspect = require('util').inspect; @@ -70,8 +70,8 @@ function versionToComparableString(version, def) { return def; } - var parts = _.map(version.split('.'), function (part) { - part = '' + _.parseInt(part); + var parts = _v4.map(version.split('.'), function (part) { + part = '' + _v4.parseInt(part); return (new Array(Math.max(4 - part.length, 0))).join('0') + part; }); @@ -109,26 +109,26 @@ function YamlDoc(doc, file) { var self = this; self.file = file; - self.description = _.keys(doc).shift(); + self.description = _v4.keys(doc).shift(); self._stash = {}; self._last_requests_response = null; // setup the actions, creating a bound and testable method for each - self._actions = _.map(self.flattenTestActions(doc[self.description]), function (action) { + self._actions = _v4.map(self.flattenTestActions(doc[self.description]), function (action) { // get the method that will do the action var method = self['do_' + action.name]; // check that it's a function expect(method || 'YamlDoc#' + action.name).to.be.a('function'); - if (_.isPlainObject(action.args)) { + if (_v4.isPlainObject(action.args)) { action.name += '(' + JSON.stringify(action.args) + ')'; } else if (action.args) { action.name += '(' + action.args + ')'; } // wrap in a check for skipping - action.bound = _.bind(method, self, action.args); + action.bound = _v4.bind(method, self, action.args); // create a function that can be passed to mocha or async action.testable = function (_cb) { @@ -199,15 +199,15 @@ YamlDoc.prototype = { flattenTestActions: function (config) { // creates [ [ {name:"", args:"" }, ... ], ... ] // from [ {name:args, name:args}, {name:args} ] - var actionSets = _.map(config, function (set) { - return _.map(_.toPairs(set), function (pair) { + var actionSets = _v4.map(config, function (set) { + return _v4.map(_v4.toPairs(set), function (pair) { return { name: pair[0], args: pair[1] }; }); }); // do a single level flatten, merge=ing the nested arrays from step one // into a master array, creating an array of action objects - return _.reduce(actionSets, function (note, set) { + return _v4.reduce(actionSets, function (note, set) { return note.concat(set); }, []); }, @@ -273,7 +273,7 @@ YamlDoc.prototype = { log('getting', path, 'from', from); - var steps = _.map(path ? path.replace(/\\\./g, '\uffff').split('.') : [], function (step) { + var steps = _v4.map(path ? path.replace(/\\\./g, '\uffff').split('.') : [], function (step) { return step.replace(/\uffff/g, '.'); }); var remainingSteps; @@ -301,7 +301,7 @@ YamlDoc.prototype = { */ do_skip: function (args, done) { if (args.version) { - return rangeMatchesCurrentVersion(args.version, _.bind(function (match) { + return rangeMatchesCurrentVersion(args.version, _v4.bind(function (match) { if (match) { if (this.description === 'setup') { this.file.skipping = true; @@ -320,7 +320,7 @@ YamlDoc.prototype = { if (args.features) { var features = Array.isArray(args.features) ? args.features : [args.features]; - var notImplemented = _.difference(features, implementedFeatures); + var notImplemented = _v4.difference(features, implementedFeatures); if (notImplemented.length) { if (this.description === 'setup') { @@ -396,19 +396,19 @@ YamlDoc.prototype = { delete args.headers; } - var otherKeys = _.keys(args); + var otherKeys = _v4.keys(args); var action = otherKeys.shift(); if (otherKeys.length) { return done(new TypeError('Unexpected top-level args to "do": ' + otherKeys.join(', '))); } var client = clientManager.get(); - var clientActionName = _.map(action.split('.'), _.camelCase).join('.'); + var clientActionName = _v4.map(action.split('.'), _v4.camelCase).join('.'); var clientAction = this.get(clientActionName, client); - _.assign(inputParams, args[action]); + _v4.assign(inputParams, args[action]); - var params = _.transform(inputParams, _.bind(function (params, val, name) { - var camelName = _.camelCase(name); + var params = _v4.transform(inputParams, _v4.bind(function (params, val, name) { + var camelName = _v4.camelCase(name); // search through the params and url peices to find this param name var paramName = name; @@ -427,10 +427,10 @@ YamlDoc.prototype = { // for ercursively traversing the params to replace '$stashed' vars var transformObject = function (vals, val, i) { - if (_.isString(val)) { + if (_v4.isString(val)) { val = (val[0] === '$') ? this.get(val) : val; - } else if (_.isPlainObject(val) || _.isArray(val)) { - val = _.transform(val, transformObject); + } else if (_v4.isPlainObject(val) || _v4.isArray(val)) { + val = _v4.transform(val, transformObject); } vals[i] = val; @@ -443,12 +443,12 @@ YamlDoc.prototype = { expect(clientAction || clientActionName).to.be.a('function'); if (!isNaN(parseFloat(catcher))) { - params.ignore = _.union(params.ignore || [], [catcher]); + params.ignore = _v4.union(params.ignore || [], [catcher]); catcher = null; } var timeoutId; - var cb = _.bind(function (error, body) { + var cb = _v4.bind(function (error, body) { this._last_requests_response = body; clearTimeout(timeoutId); @@ -494,7 +494,7 @@ YamlDoc.prototype = { * @return {undefined} */ do_set: function (args) { - _.forOwn(args, _.bind(function (name, path) { + _v4.forOwn(args, _v4.bind(function (name, path) { this._stash[name] = this.get(path); }, this)); }, @@ -566,25 +566,25 @@ YamlDoc.prototype = { var self = this; // recursively replace all $var within args - _.forOwn(args, function recurse(val, key, lvl) { - if (_.isObject(val)) { + _v4.forOwn(args, function recurse(val, key, lvl) { + if (_v4.isObject(val)) { return _v4.each(val, recurse); } - if (_.isString(val)) { + if (_v4.isString(val)) { lvl[key] = val.replace(/\$[a-zA-Z0-9_]+/g, function (name) { return self.get(name); }); } }); - _.forOwn(args, _.bind(function (match, path) { + _v4.forOwn(args, _v4.bind(function (match, path) { var origMatch = match; var maybeRE = false; var usedRE = false; - if (_.isString(match)) { + if (_v4.isString(match)) { // convert the matcher into a compatible string for building a regexp maybeRE = match // replace comments, but allow the # to be escaped like \# @@ -655,7 +655,7 @@ YamlDoc.prototype = { * @return {undefined} */ do_lt: function (args) { - _.forOwn(args, _.bind(function (num, path) { + _v4.forOwn(args, _v4.bind(function (num, path) { expect(this.get(path)).to.be.below(num, 'path: ' + path); }, this)); }, @@ -667,7 +667,7 @@ YamlDoc.prototype = { * @return {undefined} */ do_lte: function (args) { - _.forOwn(args, _.bind(function (num, path) { + _v4.forOwn(args, _v4.bind(function (num, path) { expect(this.get(path) <= num).to.be.ok('path: ' + path); }, this)); }, @@ -679,7 +679,7 @@ YamlDoc.prototype = { * @return {undefined} */ do_gt: function (args) { - _.forOwn(args, _.bind(function (num, path) { + _v4.forOwn(args, _v4.bind(function (num, path) { expect(this.get(path)).to.be.above(num, 'path: ' + path); }, this)); }, @@ -691,7 +691,7 @@ YamlDoc.prototype = { * @return {undefined} */ do_gte: function (args) { - _.forOwn(args, _.bind(function (num, path) { + _v4.forOwn(args, _v4.bind(function (num, path) { expect(this.get(path) >= num).to.be.ok('path: ' + path); }, this)); }, @@ -704,8 +704,8 @@ YamlDoc.prototype = { * @return {undefined} */ do_length: function (args) { - _.forOwn(args, _.bind(function (len, path) { - expect(_.size(this.get(path))).to.eql(len, 'path: ' + path); + _v4.forOwn(args, _v4.bind(function (len, path) { + expect(_v4.size(this.get(path))).to.eql(len, 'path: ' + path); }, this)); } }; diff --git a/test/integration/yaml_suite/yaml_file.js b/test/integration/yaml_suite/yaml_file.js index d8458c9cc..61f282541 100644 --- a/test/integration/yaml_suite/yaml_file.js +++ b/test/integration/yaml_suite/yaml_file.js @@ -8,7 +8,7 @@ module.exports = YamlFile; var YamlDoc = require('./yaml_doc'); var clientManager = require('./client_manager'); -var _ = require('../../../src/lib/utils'); +// var _ = require('../../../src/lib/utils'); var async = require('async'); function YamlFile(filename, docs) { diff --git a/test/mocks/browser_http.js b/test/mocks/browser_http.js index 912de0fe5..e04180972 100644 --- a/test/mocks/browser_http.js +++ b/test/mocks/browser_http.js @@ -27,7 +27,7 @@ module.exports = MockHttpRequest; -var _ = require('lodash-migrate'); +// var _ = require('lodash'); function MockHttpRequest() { // These are internal flags and data structures diff --git a/test/mocks/browser_server.js b/test/mocks/browser_server.js index 017ff5bc2..90a8de629 100644 --- a/test/mocks/browser_server.js +++ b/test/mocks/browser_server.js @@ -3,7 +3,7 @@ var complete = []; var MockHttpRequest = require('./browser_http'); var XhrServer = MockHttpRequest.MockHttpServer; var parseUrl = MockHttpRequest.prototype.parseUri; -var _ = require('lodash-migrate'); +// var _ = require('lodash'); var server = new XhrServer(function (request) { var reqDetails = { diff --git a/test/unit/browser_builds/angular.js b/test/unit/browser_builds/angular.js index 13eafe14f..68bd76c4d 100644 --- a/test/unit/browser_builds/angular.js +++ b/test/unit/browser_builds/angular.js @@ -1,4 +1,5 @@ -var _ = require('lodash-migrate'); +/* global angular */ +// var _ = require('lodash'); var expect = require('expect.js'); var Promise = require('bluebird'); var sinon = require('sinon'); @@ -16,13 +17,13 @@ describe('Angular esFactory', function () { function bootstrap(env) { beforeEach(function () { - var promiseProvider = _.noop; + var promiseProvider = _v4.noop; if (env.bluebirdPromises) { promiseProvider = function ($provide) { $provide.service('$q', function () { return { defer: function () { - return _.bindAll(Promise.defer(), ['resolve', 'reject']); + return _v4.bindAll(Promise.defer(), ['resolve', 'reject']); }, reject: Promise.reject, when: Promise.resolve, diff --git a/test/unit/browser_builds/jquery.js b/test/unit/browser_builds/jquery.js index 42156c37b..11e04ad63 100644 --- a/test/unit/browser_builds/jquery.js +++ b/test/unit/browser_builds/jquery.js @@ -1,3 +1,4 @@ +/* global $ */ var expect = require('expect.js'); var Transport = require('../../../src/lib/transport'); diff --git a/test/unit/buffer_flush_tests.js b/test/unit/buffer_flush_tests.js index 5f70928e0..ee56ba4ce 100644 --- a/test/unit/buffer_flush_tests.js +++ b/test/unit/buffer_flush_tests.js @@ -3,7 +3,7 @@ module.exports = function (makeLogger) { var stub = require('../utils/auto_release_stub').make(); var fs = require('fs'); var once = require('events').EventEmitter.prototype.once; - var _ = require('lodash-migrate'); + // var _ = require('lodash'); describe('buffer flush', function () { if (require('stream').Writable) { diff --git a/test/unit/specs/client_action.js b/test/unit/specs/client_action.js index ae49068aa..f16cbe324 100644 --- a/test/unit/specs/client_action.js +++ b/test/unit/specs/client_action.js @@ -1,7 +1,7 @@ var ca = require('../../../src/lib/client_action').factory; var proxy = require('../../../src/lib/client_action').proxyFactory; var expect = require('expect.js'); -var _ = require('lodash-migrate'); +// var _ = require('lodash'); var Promise = require('bluebird'); /** @@ -45,7 +45,7 @@ function makeClientAction(spec) { }; } - return _.bind(ca(spec), mockClient()); + return _v4.bind(ca(spec), mockClient()); } /** @@ -55,7 +55,7 @@ function makeClientAction(spec) { * @return {Function} - the clientActionProxy */ function makeClientActionProxy(fn, spec) { - return _.bind(proxy(fn, spec || {}), mockClient()); + return _v4.bind(proxy(fn, spec || {}), mockClient()); } @@ -118,7 +118,7 @@ describe('Client Action runner', function () { it('handles passing just the callback', function () { var action = makeClientActionProxy(function (params, cb) { - expect(_.isObject(params)).to.be.ok(); + expect(_v4.isObject(params)).to.be.ok(); expect(cb).to.be.a('function'); }); diff --git a/test/unit/specs/connection_abstract.js b/test/unit/specs/connection_abstract.js index e05bf1c0d..9463f7016 100644 --- a/test/unit/specs/connection_abstract.js +++ b/test/unit/specs/connection_abstract.js @@ -2,7 +2,7 @@ var ConnectionAbstract = require('../../../src/lib/connection'); var Host = require('../../../src/lib/host'); var sinon = require('sinon'); var expect = require('expect.js'); -var _ = require('lodash-migrate'); +// var _ = require('lodash'); var errors = require('../../../src/lib/errors'); var stub = require('../../utils/auto_release_stub').make(); @@ -73,10 +73,10 @@ describe('Connection Abstract', function () { stub(conn, 'request'); - expect(_.size(clock.timers)).to.eql(0); + expect(_v4.size(clock.timers)).to.eql(0); conn.ping(); - expect(_.size(clock.timers)).to.eql(1); - expect(clock.timers[_.keys(clock.timers).shift()].delay).to.eql(5000); + expect(_v4.size(clock.timers)).to.eql(1); + expect(clock.timers[_v4.keys(clock.timers).shift()].delay).to.eql(5000); }); it('calls it\'s own request method', function () { diff --git a/test/unit/specs/connection_pool.js b/test/unit/specs/connection_pool.js index 91772d76e..e5ac7307c 100644 --- a/test/unit/specs/connection_pool.js +++ b/test/unit/specs/connection_pool.js @@ -1,7 +1,7 @@ var ConnectionPool = require('../../../src/lib/connection_pool'); var Host = require('../../../src/lib/host'); var ConnectionAbstract = require('../../../src/lib/connection'); -var _ = require('lodash-migrate'); +// var _ = require('lodash'); var EventEmitter = require('events').EventEmitter; var expect = require('expect.js'); var sinon = require('sinon'); @@ -36,10 +36,10 @@ describe('Connection Pool', function () { }); it('#addConnection only adds the connection if it doesn\'t already exist', function () { - expect(_.keys(pool.index).length).to.eql(0); + expect(_v4.keys(pool.index).length).to.eql(0); pool.addConnection(connection); - expect(_.keys(pool.index)).to.eql([host.toString()]); + expect(_v4.keys(pool.index)).to.eql([host.toString()]); expect(pool._conns.alive).to.eql([connection]); expect(pool._conns.dead).to.eql([]); @@ -52,7 +52,7 @@ describe('Connection Pool', function () { expect(pool._conns.alive).to.eql([connection]); expect(pool._conns.dead).to.eql([]); - expect(_.keys(pool.index).length).to.eql(1); + expect(_v4.keys(pool.index).length).to.eql(1); }); it('closes the connection when it removes it', function () { @@ -247,13 +247,13 @@ describe('Connection Pool', function () { stub.autoRelease(clock); connection.setStatus('dead'); - expect(_.size(clock.timers)).to.eql(1); - var id = _(clock.timers).keys().first(); + expect(_v4.size(clock.timers)).to.eql(1); + var id = _v4(clock.timers).keys().first(); // it re-dies connection.setStatus('dead'); - expect(_.size(clock.timers)).to.eql(1); - expect(_(clock.timers).keys().first()).to.not.eql(id); + expect(_v4.size(clock.timers)).to.eql(1); + expect(_v4(clock.timers).keys().first()).to.not.eql(id); }); it('does nothing when a connection is re-alive', function () { @@ -295,7 +295,7 @@ describe('Connection Pool', function () { var result = pool.getConnections(); expect(result.length).to.be(1000); - expect(_.reduce(result, function (sum, num) { + expect(_v4.reduce(result, function (sum, num) { sum += num return sum; }, 0)).to.eql(499500); diff --git a/test/unit/specs/errors.js b/test/unit/specs/errors.js index 12c707099..9016e93fe 100644 --- a/test/unit/specs/errors.js +++ b/test/unit/specs/errors.js @@ -1,6 +1,6 @@ var errors = require('../../../src/lib/errors'); var expect = require('expect.js'); -var _ = require('lodash-migrate'); +// var _ = require('lodash'); _v4.each(errors, function (CustomError, name) { if (name.charAt(0) !== '_') { diff --git a/test/unit/specs/file_logger.js b/test/unit/specs/file_logger.js index cb5a862d0..d002d6d3d 100644 --- a/test/unit/specs/file_logger.js +++ b/test/unit/specs/file_logger.js @@ -2,7 +2,7 @@ describe('File Logger', function () { var Log = require('../../../src/lib/log'); var FileLogger = require('../../../src/lib/loggers/file'); var once = require('events').EventEmitter.prototype.once; - var _ = require('../../../src/lib/utils'); + // var _ = require('../../../src/lib/utils'); var parentLog; var logger; var expect = require('expect.js'); @@ -15,7 +15,7 @@ describe('File Logger', function () { afterEach(function () { parentLog.close(); - logger && _.clearWriteStreamBuffer(logger.stream); + logger && _v4.clearWriteStreamBuffer(logger.stream); }); function makeLogger(parent, levels) { diff --git a/test/unit/specs/host.js b/test/unit/specs/host.js index 9bef6bde8..9b0966020 100644 --- a/test/unit/specs/host.js +++ b/test/unit/specs/host.js @@ -1,5 +1,5 @@ var Host = require('../../../src/lib/host'); -var _ = require('lodash-migrate'); +// var _ = require('lodash'); var expect = require('expect.js'); var url = require('url'); var expectSubObject = require('../../utils/expect_sub_object'); diff --git a/test/unit/specs/http_connector.js b/test/unit/specs/http_connector.js index 64825831a..72450025b 100644 --- a/test/unit/specs/http_connector.js +++ b/test/unit/specs/http_connector.js @@ -1,6 +1,6 @@ describe('Http Connector', function () { - var _ = require('lodash-migrate'); + // var _ = require('lodash'); var expect = require('expect.js'); var nock = require('nock'); var sinon = require('sinon'); @@ -67,12 +67,12 @@ describe('Http Connector', function () { it('allows defining a custom agent', function () { var football = {}; - var con = new HttpConnection(new Host(), { createNodeAgent: _.constant(football) }); + var con = new HttpConnection(new Host(), { createNodeAgent: _v4.constant(football) }); expect(con.agent).to.be(football); }); it('allows setting agent to false', function () { - var con = new HttpConnection(new Host(), { createNodeAgent: _.constant(false) }); + var con = new HttpConnection(new Host(), { createNodeAgent: _v4.constant(false) }); expect(con.agent).to.be(false); }); }); @@ -482,7 +482,7 @@ describe('Http Connector', function () { this.timeout(5 * 60 * 1000); var cp = require('child_process'); var path = require('path'); - var fixture = _.partial(path.join, __dirname, '../../fixtures'); + var fixture = _v4.partial(path.join, __dirname, '../../fixtures'); var timeout; // start the timeout once we hear back from the client var server = cp.fork(fixture('keepalive_server.js')) diff --git a/test/unit/specs/log.js b/test/unit/specs/log.js index aa5dab6e0..e9be3591a 100644 --- a/test/unit/specs/log.js +++ b/test/unit/specs/log.js @@ -1,5 +1,5 @@ var Log = require('../../../src/lib/log'); -var _ = require('lodash-migrate'); +// var _ = require('lodash'); var expect = require('expect.js'); describe('Log class', function () { @@ -129,11 +129,11 @@ describe('Log class', function () { log: [ { type: function (log, config) { - log.on('error', _.noop); - log.on('warning', _.noop); - log.on('info', _.noop); - log.on('debug', _.noop); - log.on('trace', _.noop); + log.on('error', _v4.noop); + log.on('warning', _v4.noop); + log.on('info', _v4.noop); + log.on('debug', _v4.noop); + log.on('trace', _v4.noop); } } ] diff --git a/test/unit/specs/random_selector.js b/test/unit/specs/random_selector.js index 7b7df3149..18709b210 100644 --- a/test/unit/specs/random_selector.js +++ b/test/unit/specs/random_selector.js @@ -1,18 +1,18 @@ describe('Random Selector', function () { var randomSelector = require('../../../src/lib/selectors/random'); - var _ = require('lodash-migrate'); + // var _ = require('lodash'); var expect = require('expect.js'); it('chooses a selection by random', function () { var log = { a: 0, b: 0, c: 0 }; - var choices = _.keys(log); + var choices = _v4.keys(log); _v4.times(1000, function () { var choice = randomSelector(choices); log[choice]++; }); - expect(_.filter(log, function (count) { + expect(_v4.filter(log, function (count) { return count < 200 || count > 400; })).to.have.length(0); diff --git a/test/unit/specs/round_robin_selector.js b/test/unit/specs/round_robin_selector.js index 58d5ec8fe..18e9d957d 100644 --- a/test/unit/specs/round_robin_selector.js +++ b/test/unit/specs/round_robin_selector.js @@ -1,6 +1,6 @@ describe('Round Robin Selector', function () { var selector = require('../../../src/lib/selectors/round_robin'); - var _ = require('lodash-migrate'); + // var _ = require('lodash'); var expect = require('expect.js'); it('chooses options in order', function () { diff --git a/test/unit/specs/stream_logger.js b/test/unit/specs/stream_logger.js index 44413ad63..52b6c1cf7 100644 --- a/test/unit/specs/stream_logger.js +++ b/test/unit/specs/stream_logger.js @@ -4,7 +4,7 @@ describe('Stream Logger', function () { var MockWritableStream = require('../../mocks/writable_stream'); var once = require('events').EventEmitter.prototype.once; var stream = new MockWritableStream(); - var _ = require('../../../src/lib/utils'); + // var _ = require('../../../src/lib/utils'); var expect = require('expect.js'); var parentLog; @@ -19,7 +19,7 @@ describe('Stream Logger', function () { afterEach(function () { parentLog.close(); - _.clearWriteStreamBuffer(stream); + _v4.clearWriteStreamBuffer(stream); }); function makeLogger(parent, levels) { @@ -41,7 +41,7 @@ describe('Stream Logger', function () { // get the last handler for process's "exit" event var exitHandlers = process._events.exit; - var exitHandler = _.isArray(exitHandlers) ? _.last(exitHandlers) : exitHandlers; + var exitHandler = _v4.isArray(exitHandlers) ? _v4.last(exitHandlers) : exitHandlers; // allow the logger to acctually write to the stream stream.write.restore(); diff --git a/test/unit/specs/transport.js b/test/unit/specs/transport.js index 5e2f81e56..2603f3bab 100644 --- a/test/unit/specs/transport.js +++ b/test/unit/specs/transport.js @@ -4,7 +4,7 @@ var errors = require('../../../src/lib/errors'); var sinon = require('sinon'); var expect = require('expect.js'); -var _ = require('lodash-migrate'); +// var _ = require('lodash'); var nodeList = require('../../fixtures/short_node_list.json'); var stub = require('../../utils/auto_release_stub').make(); @@ -83,11 +83,11 @@ describe('Transport Class', function () { sniffInterval: 25000 }); - expect(_.size(clock.timers)).to.eql(1); - var id = _.keys(clock.timers).pop(); + expect(_v4.size(clock.timers)).to.eql(1); + var id = _v4.keys(clock.timers).pop(); clock.tick(25000); expect(trans.sniff.callCount).to.eql(1); - expect(_.size(clock.timers)).to.eql(1); + expect(_v4.size(clock.timers)).to.eql(1); expect(clock.timers).to.not.have.key(id); }); @@ -285,7 +285,7 @@ describe('Transport Class', function () { describe('randomizeHosts options', function () { it('calls _.shuffle be default', function () { - var _ = require('../../../src/lib/utils'); + // var _ = require('../../../src/lib/utils'); stub(Transport.connectionPools.main.prototype, 'setHosts'); stub(_v4, 'shuffle'); var trans = new Transport({ @@ -295,7 +295,7 @@ describe('Transport Class', function () { expect(_v4.shuffle.callCount).to.eql(1); }); it('skips the call to _.shuffle when false', function () { - var _ = require('../../../src/lib/utils'); + // var _ = require('../../../src/lib/utils'); stub(Transport.connectionPools.main.prototype, 'setHosts'); stub(_v4, 'shuffle'); var trans = new Transport({ @@ -606,7 +606,7 @@ describe('Transport Class', function () { } var trans = new Transport({ - hosts: _.map(new Array(retries + 1), function (val, i) { + hosts: _v4.map(new Array(retries + 1), function (val, i) { return 'localhost/' + i; }), maxRetries: retries, @@ -617,7 +617,7 @@ describe('Transport Class', function () { }); // trigger a select so that we can harvest the connection list - trans.connectionPool.select(_.noop); + trans.connectionPool.select(_v4.noop); _v4.each(connections, function (conn) { stub(conn, 'request', failRequest); }); @@ -641,7 +641,7 @@ describe('Transport Class', function () { it('returns an object with an abort() method when a callback is sent', function () { var tran = new Transport(); shortCircuitRequest(tran); - var ret = tran.request({}, _.noop); + var ret = tran.request({}, _v4.noop); expect(ret).to.be.a('object'); expect(ret.abort).to.be.a('function'); }); @@ -651,7 +651,7 @@ describe('Transport Class', function () { var ret = tran.request({}); expect(ret.then).to.be.a('function'); expect(ret.abort).to.be.a('function'); - ret.then(_.noop, _.noop); // prevent complaining from bluebird + ret.then(_v4.noop, _v4.noop); // prevent complaining from bluebird }); it('promise is always pulled from the defer created by this.defer()', function () { var fakePromise = {}; @@ -659,8 +659,8 @@ describe('Transport Class', function () { var tran = new Transport({ defer: function () { return { - resolve: _.noop, - reject: _.noop, + resolve: _v4.noop, + reject: _v4.noop, promise: fakePromise }; } @@ -759,9 +759,9 @@ describe('Transport Class', function () { var prom = tran.request({}); // disregard promise, prevent bluebird's warnings - prom.then(_.noop, _.noop); + prom.then(_v4.noop, _v4.noop); - expect(_.size(clock.timers)).to.eql(1); + expect(_v4.size(clock.timers)).to.eql(1); _v4.each(clock.timers, function (timer, id) { expect(timer.callAt).to.eql(30000); clearTimeout(id); @@ -776,9 +776,9 @@ describe('Transport Class', function () { var prom = tran.request({}); // disregard promise, prevent bluebird's warnings - prom.then(_.noop, _.noop); + prom.then(_v4.noop, _v4.noop); - expect(_.size(clock.timers)).to.eql(1); + expect(_v4.size(clock.timers)).to.eql(1); _v4.each(clock.timers, function (timer, id) { expect(timer.callAt).to.eql(5000); clearTimeout(id); @@ -797,7 +797,7 @@ describe('Transport Class', function () { requestTimeout: falsy }, function () {}); - expect(_.size(clock.timers)).to.eql(0); + expect(_v4.size(clock.timers)).to.eql(0); }); }); }); diff --git a/test/unit/specs/transport_with_server.js b/test/unit/specs/transport_with_server.js index 9b267ba31..4ba36c737 100644 --- a/test/unit/specs/transport_with_server.js +++ b/test/unit/specs/transport_with_server.js @@ -7,7 +7,7 @@ var expect = require('expect.js'); var sinon = require('sinon'); var nock = require('../../mocks/server.js'); var through2 = require('through2'); -var _ = require('lodash-migrate'); +// var _ = require('lodash'); var nodeList = require('../../fixtures/short_node_list.json'); var stub = require('../../utils/auto_release_stub').make(); @@ -277,7 +277,7 @@ describe('Transport + Mock server', function () { expect(err).to.be(undefined); expect(resp).to.eql({ i: 'am here' }); expect(status).to.eql(200); - expect(_.keys(clock.timers)).to.have.length(0); + expect(_v4.keys(clock.timers)).to.have.length(0); clock.restore(); }); }); @@ -342,9 +342,9 @@ describe('Transport + Mock server', function () { .catch(function (err) { expect(ConnectionPool.prototype._onConnectionDied.callCount).to.eql(1); expect(tran.sniff.callCount).to.eql(0); - expect(_.size(clock.timers)).to.eql(1); + expect(_v4.size(clock.timers)).to.eql(1); - var timeout = _.values(clock.timers).pop(); + var timeout = _v4.values(clock.timers).pop(); timeout.func(); expect(tran.sniff.callCount).to.eql(1); }); diff --git a/test/unit/specs/utils.js b/test/unit/specs/utils.js index feb89e7d0..1fd8f4a60 100644 --- a/test/unit/specs/utils.js +++ b/test/unit/specs/utils.js @@ -1,4 +1,4 @@ -var _ = require('../../../src/lib/utils'); +// var _ = require('../../../src/lib/utils'); var expect = require('expect.js'); var stub = require('../../utils/auto_release_stub').make(); @@ -6,7 +6,7 @@ var stub = require('../../utils/auto_release_stub').make(); describe('Utils', function () { describe('Additional Type Checkers', function () { - _.forEach({ + _v4.forEach({ Object: { is: [[], /regexp/] }, @@ -34,66 +34,66 @@ describe('Utils', function () { function (thing, name) { describe('#isArrayOf' + name, function () { it('likes arrays of ' + name, function () { - expect(_['isArrayOf' + name + 's'](thing.is)).to.be(true); + expect(_v4['isArrayOf' + name + 's'](thing.is)).to.be(true); }); it('dislikes when there is even one non ' + name, function () { // notice a string in the array thing.is.push(thing.not || ' not '); - expect(_['isArrayOf' + name + 's'](thing.is)).to.be(false); + expect(_v4['isArrayOf' + name + 's'](thing.is)).to.be(false); }); }); }); describe('#isNumeric', function () { it('likes integer literals', function () { - expect(_.isNumeric('-10')).to.be(true); - expect(_.isNumeric('0')).to.be(true); - expect(_.isNumeric('5')).to.be(true); - expect(_.isNumeric(-16)).to.be(true); - expect(_.isNumeric(0)).to.be(true); - expect(_.isNumeric(32)).to.be(true); - expect(_.isNumeric('040')).to.be(true); - expect(_.isNumeric('0xFF')).to.be(true); - expect(_.isNumeric(0xFFF)).to.be(true); + expect(_v4.isNumeric('-10')).to.be(true); + expect(_v4.isNumeric('0')).to.be(true); + expect(_v4.isNumeric('5')).to.be(true); + expect(_v4.isNumeric(-16)).to.be(true); + expect(_v4.isNumeric(0)).to.be(true); + expect(_v4.isNumeric(32)).to.be(true); + expect(_v4.isNumeric('040')).to.be(true); + expect(_v4.isNumeric('0xFF')).to.be(true); + expect(_v4.isNumeric(0xFFF)).to.be(true); }); it('likes float literals', function () { - expect(_.isNumeric('-1.6')).to.be(true); - expect(_.isNumeric('4.536')).to.be(true); - expect(_.isNumeric(-2.6)).to.be(true); - expect(_.isNumeric(3.1415)).to.be(true); - expect(_.isNumeric(8e5)).to.be(true); - expect(_.isNumeric('123e-2')).to.be(true); + expect(_v4.isNumeric('-1.6')).to.be(true); + expect(_v4.isNumeric('4.536')).to.be(true); + expect(_v4.isNumeric(-2.6)).to.be(true); + expect(_v4.isNumeric(3.1415)).to.be(true); + expect(_v4.isNumeric(8e5)).to.be(true); + expect(_v4.isNumeric('123e-2')).to.be(true); }); it('dislikes non-numeric stuff', function () { - expect(_.isNumeric('')).to.be(false); - expect(_.isNumeric(' ')).to.be(false); - expect(_.isNumeric('\t\t')).to.be(false); - expect(_.isNumeric('abcdefghijklm1234567890')).to.be(false); - expect(_.isNumeric('xabcdefx')).to.be(false); - expect(_.isNumeric(true)).to.be(false); - expect(_.isNumeric(false)).to.be(false); - expect(_.isNumeric('bcfed5.2')).to.be(false); - expect(_.isNumeric('7.2acdgs')).to.be(false); - expect(_.isNumeric(undefined)).to.be(false); - expect(_.isNumeric(null)).to.be(false); - expect(_.isNumeric(NaN)).to.be(false); - expect(_.isNumeric(Infinity)).to.be(false); - expect(_.isNumeric(Number.POSITIVE_INFINITY)).to.be(false); - expect(_.isNumeric(Number.NEGATIVE_INFINITY)).to.be(false); - expect(_.isNumeric(new Date(2009, 1, 1))).to.be(false); - expect(_.isNumeric([])).to.be(false); - expect(_.isNumeric([1, 2, 3, 4])).to.be(false); - expect(_.isNumeric({})).to.be(false); - expect(_.isNumeric(function () {})).to.be(false); + expect(_v4.isNumeric('')).to.be(false); + expect(_v4.isNumeric(' ')).to.be(false); + expect(_v4.isNumeric('\t\t')).to.be(false); + expect(_v4.isNumeric('abcdefghijklm1234567890')).to.be(false); + expect(_v4.isNumeric('xabcdefx')).to.be(false); + expect(_v4.isNumeric(true)).to.be(false); + expect(_v4.isNumeric(false)).to.be(false); + expect(_v4.isNumeric('bcfed5.2')).to.be(false); + expect(_v4.isNumeric('7.2acdgs')).to.be(false); + expect(_v4.isNumeric(undefined)).to.be(false); + expect(_v4.isNumeric(null)).to.be(false); + expect(_v4.isNumeric(NaN)).to.be(false); + expect(_v4.isNumeric(Infinity)).to.be(false); + expect(_v4.isNumeric(Number.POSITIVE_INFINITY)).to.be(false); + expect(_v4.isNumeric(Number.NEGATIVE_INFINITY)).to.be(false); + expect(_v4.isNumeric(new Date(2009, 1, 1))).to.be(false); + expect(_v4.isNumeric([])).to.be(false); + expect(_v4.isNumeric([1, 2, 3, 4])).to.be(false); + expect(_v4.isNumeric({})).to.be(false); + expect(_v4.isNumeric(function () {})).to.be(false); }); }); describe('#isInterval', function () { - _.forEach({ + _v4.forEach({ M: 'months', w: 'weeks', d: 'days', @@ -104,20 +104,20 @@ describe('Utils', function () { }, function (name, unit) { it('likes ' + name, function () { - expect(_.isInterval('1' + unit)).to.be(true); + expect(_v4.isInterval('1' + unit)).to.be(true); }); it('likes decimal ' + name, function () { - expect(_.isInterval('1.5' + unit)).to.be(true); + expect(_v4.isInterval('1.5' + unit)).to.be(true); }); }); it('dislikes more than one unit', function () { - expect(_.isInterval('1my')).to.be(false); + expect(_v4.isInterval('1my')).to.be(false); }); it('dislikes spaces', function () { - expect(_.isInterval('1 m')).to.be(false); + expect(_v4.isInterval('1 m')).to.be(false); }); }); }); @@ -127,108 +127,108 @@ describe('Utils', function () { describe('#camelCase', function () { it('find spaces, underscores, and other natural word breaks', function () { - expect(_.camelCase('Neil Patrick.Harris-is_a.dog')).to.eql('neilPatrickHarrisIsADog'); + expect(_v4.camelCase('Neil Patrick.Harris-is_a.dog')).to.eql('neilPatrickHarrisIsADog'); }); it('ignores abreviations', function () { - expect(_.camelCase('Json_parser')).to.eql('jsonParser'); + expect(_v4.camelCase('Json_parser')).to.eql('jsonParser'); }); it('handles leading _', function () { - expect(_.camelCase('_thing_one_')).to.eql('_thingOne'); + expect(_v4.camelCase('_thing_one_')).to.eql('_thingOne'); }); it('works on numbers', function () { - expect(_.camelCase('version 1.0')).to.eql('version10'); + expect(_v4.camelCase('version 1.0')).to.eql('version10'); }); }); describe('#studlyCase', function () { it('find spaces, underscores, and other natural word breaks', function () { - expect(_.studlyCase('Neil Patrick.Harris-is_a.dog')).to.eql('NeilPatrickHarrisIsADog'); + expect(_v4.studlyCase('Neil Patrick.Harris-is_a.dog')).to.eql('NeilPatrickHarrisIsADog'); }); it('ignores abreviations', function () { - expect(_.studlyCase('Json_parser')).to.eql('JsonParser'); + expect(_v4.studlyCase('Json_parser')).to.eql('JsonParser'); }); it('handles leading _', function () { - expect(_.studlyCase('_thing_one_')).to.eql('_ThingOne'); + expect(_v4.studlyCase('_thing_one_')).to.eql('_ThingOne'); }); it('works on numbers', function () { - expect(_.studlyCase('version 1.0')).to.eql('Version10'); + expect(_v4.studlyCase('version 1.0')).to.eql('Version10'); }); }); describe('#snakeCase', function () { it('find spaces, underscores, and other natural word breaks', function () { - expect(_.snakeCase('Neil Patrick.Harris-is_a.dog')).to.eql('neil_patrick_harris_is_a_dog'); + expect(_v4.snakeCase('Neil Patrick.Harris-is_a.dog')).to.eql('neil_patrick_harris_is_a_dog'); }); it('ignores abreviations', function () { - expect(_.snakeCase('Json_parser')).to.eql('json_parser'); + expect(_v4.snakeCase('Json_parser')).to.eql('json_parser'); }); it('handles leading _', function () { - expect(_.snakeCase('_thing_one_')).to.eql('_thing_one'); + expect(_v4.snakeCase('_thing_one_')).to.eql('_thing_one'); }); it('works on numbers', function () { - expect(_.snakeCase('version 1.0')).to.eql('version_1_0'); + expect(_v4.snakeCase('version 1.0')).to.eql('version_1_0'); }); }); describe('#toLowerString', function () { it('transforms normal strings', function () { - expect(_.toLowerString('PASTA')).to.eql('pasta'); + expect(_v4.toLowerString('PASTA')).to.eql('pasta'); }); it('ignores long form empty vals (null, false, undef)', function () { - expect(_.toLowerString(null)).to.eql(''); - expect(_.toLowerString(false)).to.eql(''); - expect(_.toLowerString(void 0)).to.eql(''); + expect(_v4.toLowerString(null)).to.eql(''); + expect(_v4.toLowerString(false)).to.eql(''); + expect(_v4.toLowerString(void 0)).to.eql(''); }); it('uses the objects own toString', function () { - expect(_.toLowerString(['A', 'B'])).to.eql('a,b'); + expect(_v4.toLowerString(['A', 'B'])).to.eql('a,b'); }); it('sorta kinda works on objects', function () { - expect(_.toLowerString({ a: 'thing' })).to.eql('[object object]'); + expect(_v4.toLowerString({ a: 'thing' })).to.eql('[object object]'); }); }); describe('#toUpperString', function () { it('transforms normal strings', function () { - expect(_.toUpperString('PASTA')).to.eql('PASTA'); + expect(_v4.toUpperString('PASTA')).to.eql('PASTA'); }); it('ignores long form empty vals (null, false, undef)', function () { - expect(_.toUpperString(null)).to.eql(''); - expect(_.toUpperString(false)).to.eql(''); - expect(_.toUpperString(void 0)).to.eql(''); + expect(_v4.toUpperString(null)).to.eql(''); + expect(_v4.toUpperString(false)).to.eql(''); + expect(_v4.toUpperString(void 0)).to.eql(''); }); it('uses the objects own toString', function () { - expect(_.toUpperString(['A', 'B'])).to.eql('A,B'); + expect(_v4.toUpperString(['A', 'B'])).to.eql('A,B'); }); it('sorta kinda works on objects', function () { - expect(_.toUpperString({ a: 'thing' })).to.eql('[OBJECT OBJECT]'); + expect(_v4.toUpperString({ a: 'thing' })).to.eql('[OBJECT OBJECT]'); }); }); describe('#repeat', function () { it('repeats strings', function () { - expect(_.repeat(' ', 5)).to.eql(' '); - expect(_.repeat('foobar', 2)).to.eql('foobarfoobar'); + expect(_v4.repeat(' ', 5)).to.eql(' '); + expect(_v4.repeat('foobar', 2)).to.eql('foobarfoobar'); }); }); describe('#ucfirst', function () { it('only capitalized the first letter, lowercases everything else', function () { - expect(_.ucfirst('ALGER')).to.eql('Alger'); + expect(_v4.ucfirst('ALGER')).to.eql('Alger'); }); }); @@ -241,14 +241,14 @@ describe('Utils', function () { var obj = { foo: 'bar' }; - expect(_.deepMerge(obj, { bar: 'baz' })).to.eql(obj); + expect(_v4.deepMerge(obj, { bar: 'baz' })).to.eql(obj); }); it('concats arrays', function () { var obj = { foo: ['bax', 'boz'] }; - _.deepMerge(obj, { foo: ['boop'] }); + _v4.deepMerge(obj, { foo: ['boop'] }); expect(obj.foo).to.have.length(3); }); @@ -256,7 +256,7 @@ describe('Utils', function () { var obj = { foo: ['stop', 'foo', 'stahp'] }; - _.deepMerge(obj, { foo: 'string' }); + _v4.deepMerge(obj, { foo: 'string' }); expect(obj.foo).to.have.length(3); }); @@ -267,7 +267,7 @@ describe('Utils', function () { foo: ['bax', 'boz'] } }; - _.deepMerge(obj, { bax: { foo: ['poo'] } }); + _v4.deepMerge(obj, { bax: { foo: ['poo'] } }); expect(obj.bax.foo).to.have.length(3); }); @@ -276,26 +276,26 @@ describe('Utils', function () { describe('#createArray', function () { it('accepts an array of things and simply returns a copy of it', function () { var inp = [{ a: 1 }, 'pizza']; - var out = _.createArray(inp); + var out = _v4.createArray(inp); expect(out).to.eql(inp); expect(out).to.not.be(inp); }); it('accepts a primitive value and calls the the transform function', function (done) { - _.createArray('str', function (val) { + _v4.createArray('str', function (val) { expect(val).to.be('str'); done(); }); }); it('wraps any non-array in an array', function () { - expect(_.createArray({})).to.eql([{}]); - expect(_.createArray('')).to.eql(['']); - expect(_.createArray(123)).to.eql([123]); - expect(_.createArray(/abc/)).to.eql([/abc/]); - expect(_.createArray(false)).to.eql([false]); + expect(_v4.createArray({})).to.eql([{}]); + expect(_v4.createArray('')).to.eql(['']); + expect(_v4.createArray(123)).to.eql([123]); + expect(_v4.createArray(/abc/)).to.eql([/abc/]); + expect(_v4.createArray(false)).to.eql([false]); }); it('returns false when the transform function returns undefined', function () { - expect(_.createArray(['str', 1], function (val) { - if (_.isString(val)) { + expect(_v4.createArray(['str', 1], function (val) { + if (_v4.isString(val)) { return { val: val }; @@ -306,27 +306,27 @@ describe('Utils', function () { describe('#funcEnum', function () { /* - * _.funcEnum(object, key, opts, default); + * _v4.funcEnum(object, key, opts, default); */ it('tests if the value at key in object is a function, returns it if so', function () { var config = { func: function () {} }; - expect(_.funcEnum(config, 'func', {}, 'toString')) + expect(_v4.funcEnum(config, 'func', {}, 'toString')) .to.be(config.func); }); it('tests if the value at key in object is undefined, returns the option at key default if so', function () { var config = { func: undefined }; - expect(_.funcEnum(config, 'func', {}, 'toString')) + expect(_v4.funcEnum(config, 'func', {}, 'toString')) .to.be(Object.prototype.toString); }); it('tests if the value at key in object is a string, returns the option at that key if so', function () { var config = { 'config key name': 'toString' }; - expect(_.funcEnum(config, 'config key name', { toString: 'pizza' }, 'toJSON')) + expect(_v4.funcEnum(config, 'config key name', { toString: 'pizza' }, 'toJSON')) .to.be('pizza'); }); it('throws an informative error if the selection if invalid', function () { @@ -335,15 +335,15 @@ describe('Utils', function () { }; expect(function () { - _.funcEnum(config, 'config', {}); + _v4.funcEnum(config, 'config', {}); }).to.throwError(/expected a function/i); expect(function () { - _.funcEnum(config, 'config', { main: 'default' }, 'main'); + _v4.funcEnum(config, 'config', { main: 'default' }, 'main'); }).to.throwError(/expected a function or main/i); expect(function () { - _.funcEnum(config, 'config', { main: 'default', other: 'default' }, 'main'); + _v4.funcEnum(config, 'config', { main: 'default', other: 'default' }, 'main'); }).to.throwError(/expected a function or one of main, other/i); }); }); @@ -358,8 +358,8 @@ describe('Utils', function () { var func = function () {}; stub(func, method); - var args = _.map(new Array(i), function (val, i) { return i; }); - _.applyArgs(func, null, args); + var args = _v4.map(new Array(i), function (val, i) { return i; }); + _v4.applyArgs(func, null, args); expect(func[method].callCount).to.eql(1); if (method === 'apply') { @@ -374,9 +374,9 @@ describe('Utils', function () { var func = function () {}; stub(func, method); - var args = _.map(new Array(argCount), function (val, i) { return i; }); + var args = _v4.map(new Array(argCount), function (val, i) { return i; }); var expected = args.slice(slice); - _.applyArgs(func, null, args, slice); + _v4.applyArgs(func, null, args, slice); expect(func[method].callCount).to.eql(1); if (method === 'apply') { @@ -390,24 +390,24 @@ describe('Utils', function () { describe('#getUnwrittenFromStream', function () { it('ignores things that do not have writableState', function () { - expect(_.getUnwrittenFromStream()).to.be(undefined); - expect(_.getUnwrittenFromStream(false)).to.be(undefined); - expect(_.getUnwrittenFromStream([])).to.be(undefined); - expect(_.getUnwrittenFromStream({})).to.be(undefined); + expect(_v4.getUnwrittenFromStream()).to.be(undefined); + expect(_v4.getUnwrittenFromStream(false)).to.be(undefined); + expect(_v4.getUnwrittenFromStream([])).to.be(undefined); + expect(_v4.getUnwrittenFromStream({})).to.be(undefined); }); if (require('stream').Writable) { var MockWritableStream = require('../../mocks/writable_stream'); it('ignores empty stream', function () { var stream = new MockWritableStream(); - expect(_.getUnwrittenFromStream(stream)).to.be(''); + expect(_v4.getUnwrittenFromStream(stream)).to.be(''); }); it('returns only what is in the buffer', function () { var stream = new MockWritableStream(); stream.write('hot'); stream.write('dog'); - expect(_.getUnwrittenFromStream(stream)).to.be('dog'); + expect(_v4.getUnwrittenFromStream(stream)).to.be('dog'); }); } }); diff --git a/test/utils/expect_sub_object.js b/test/utils/expect_sub_object.js index f5c8f0e32..7499206c1 100644 --- a/test/utils/expect_sub_object.js +++ b/test/utils/expect_sub_object.js @@ -1,7 +1,7 @@ -var _ = require('lodash-migrate'); +// var _ = require('lodash'); var expect = require('expect.js'); module.exports = function expectSubObject(obj, subObj) { - _.forOwn(subObj, function (val, prop) { + _v4.forOwn(subObj, function (val, prop) { if (typeof obj[prop] === 'object') { // non-strict equals expect(obj[prop]).to.eql(val, 'Expected property' + prop + ' of object to equal ' + val); diff --git a/test/utils/jenkins-reporter.js b/test/utils/jenkins-reporter.js index 3275e06cf..7399d00f9 100644 --- a/test/utils/jenkins-reporter.js +++ b/test/utils/jenkins-reporter.js @@ -7,7 +7,7 @@ module.exports = JenkinsReporter; var Base = require('mocha/lib/reporters/base'); -var _ = require('lodash-migrate'); +// var _ = require('lodash'); var chalk = require('chalk'); var makeJUnitXml = require('./make_j_unit_xml'); var fs = require('fs'); @@ -15,7 +15,7 @@ var path = require('path'); var inspect = require('util').inspect; var log = (function () { - var locked = _.bind(process.stdout.write, process.stdout); + var locked = _v4.bind(process.stdout.write, process.stdout); return function (str) { if (typeof str !== 'string') { str = inspect(str); @@ -126,7 +126,7 @@ function JenkinsReporter(runner) { errMsg += '\n(' + test.err.sourceURL + ':' + test.err.line + ')'; } - console.error(_.map(errMsg.split('\n'), function (line) { + console.error(_v4.map(errMsg.split('\n'), function (line) { return indt() + ' ' + line; }).join('\n')); } @@ -146,7 +146,7 @@ function JenkinsReporter(runner) { runner.on('hook end', function (hook) { if (hook.title.indexOf('"after each"') > -1 && stack[0] && stack[0].results.length) { - var result = _.last(stack[0].results); + var result = _v4.last(stack[0].results); result.stdout += stack[0].stdout; result.stderr += stack[0].stderr; stack[0].stdout = stack[0].stderr = ''; @@ -157,7 +157,7 @@ function JenkinsReporter(runner) { restoreStdio(); var xml = makeJUnitXml('node ' + process.version, { stats: stats, - suites: _.map(rootSuite.suites, function removeElements(suite) { + suites: _v4.map(rootSuite.suites, function removeElements(suite) { var s = { name: suite.name, start: suite.start, @@ -168,7 +168,7 @@ function JenkinsReporter(runner) { }; if (suite.suites) { - s.suites = _.map(suite.suites, removeElements); + s.suites = _v4.map(suite.suites, removeElements); } return s; }) diff --git a/test/utils/make_j_unit_xml.js b/test/utils/make_j_unit_xml.js index 8d5dbbe3e..2744d1b8d 100644 --- a/test/utils/make_j_unit_xml.js +++ b/test/utils/make_j_unit_xml.js @@ -28,7 +28,7 @@ var testXml = require('xmlbuilder'); var suites = testXml.create('testsuites'); var suiteCount = 0; var moment = require('moment'); -var _ = require('lodash-migrate'); +// var _ = require('lodash'); var chalk = require('chalk'); function makeJUnitXml(runnerName, testDetails) { @@ -41,7 +41,7 @@ function makeJUnitXml(runnerName, testDetails) { timestamp: moment(suiteInfo.start).toJSON(), hostname: 'localhost', tests: (suiteInfo.results && suiteInfo.results.length) || 0, - failures: _.where(suiteInfo.results, { pass: false }).length, + failures: _v4.filter(suiteInfo.results, { pass: false }).length, errors: 0, time: suiteInfo.time / 1000 }); diff --git a/test/utils/server.js b/test/utils/server.js index 1b23024b8..9484020cf 100644 --- a/test/utils/server.js +++ b/test/utils/server.js @@ -2,7 +2,7 @@ var express = require('express'); var http = require('http'); var fs = require('fs'); -var _ = require('lodash-migrate'); +// var _ = require('lodash'); var async = require('async'); var root = require('path').join(__dirname, '../..'); var browserify = require('browserify'); @@ -12,7 +12,7 @@ var browserBuildsDir = root + '/test/unit/browser_builds'; var testFiles = {}; -testFiles.unit = _(fs.readdirSync(unitSpecDir)) +testFiles.unit = _v4(fs.readdirSync(unitSpecDir)) .difference([ 'file_logger.js', 'http_connector.js', From 8ad271d81cc889c19c66f5070c13459d0217fb2f Mon Sep 17 00:00:00 2001 From: spalger Date: Thu, 19 May 2016 14:33:04 -0700 Subject: [PATCH 14/15] and finally, return to standard mo --- docs/configuration.asciidoc | 2 +- docs/host.asciidoc | 2 +- grunt/config/esvm.js | 6 +- grunt/config/mochacov.js | 6 +- grunt/utils.js | 4 +- package.json | 2 +- scripts/Version.js | 8 +- scripts/ci.js | 22 +- scripts/generate/api_index.js | 4 +- scripts/generate/configuration_docs.js | 4 +- scripts/generate/doc_index.js | 4 +- scripts/generate/index.js | 20 +- scripts/generate/js_api.js | 74 +++---- scripts/generate/templates/api_file.tmpl | 10 +- scripts/generate/templates/api_index.tmpl | 2 +- scripts/generate/templates/api_methods.tmpl | 10 +- scripts/generate/templates/client_action.tmpl | 2 +- .../templates/client_action_proxy.tmpl | 2 +- .../templates/configuration_docs.tmpl | 2 +- scripts/generate/templates/index.js | 10 +- scripts/generate/yaml_tests.js | 8 +- scripts/release/bower.js | 6 +- src/lib/client.js | 10 +- src/lib/client_action.js | 42 ++-- src/lib/connection.js | 8 +- src/lib/connection_pool.js | 32 +-- src/lib/connectors/angular.js | 4 +- src/lib/connectors/browser_index.js | 4 +- src/lib/connectors/http.js | 22 +- src/lib/connectors/jquery.js | 4 +- src/lib/connectors/xhr.js | 8 +- src/lib/errors.js | 34 +-- src/lib/host.js | 26 +-- src/lib/log.js | 28 +-- src/lib/logger.js | 26 +-- src/lib/loggers/console.js | 16 +- src/lib/loggers/file.js | 8 +- src/lib/loggers/stdio.js | 18 +- src/lib/loggers/stream.js | 10 +- src/lib/loggers/tracer.js | 12 +- src/lib/nodes_to_host.js | 4 +- src/lib/serializers/angular.js | 4 +- src/lib/serializers/json.js | 4 +- src/lib/transport.js | 32 +-- src/lib/transport/find_common_protocol.js | 2 +- .../transport/sniff_on_connection_fault.js | 4 +- src/lib/utils.js | 103 +++++---- test/fixtures/keepalive.js | 10 +- test/integration/yaml_suite/client_manager.js | 12 +- test/integration/yaml_suite/run.js | 4 +- test/integration/yaml_suite/yaml_doc.js | 74 +++---- test/integration/yaml_suite/yaml_file.js | 4 +- test/mocks/browser_http.js | 6 +- test/mocks/browser_server.js | 4 +- test/unit/browser_builds/angular.js | 6 +- test/unit/buffer_flush_tests.js | 4 +- test/unit/specs/client_action.js | 10 +- test/unit/specs/connection_abstract.js | 8 +- test/unit/specs/connection_pool.js | 22 +- test/unit/specs/errors.js | 4 +- test/unit/specs/file_logger.js | 6 +- test/unit/specs/host.js | 2 +- test/unit/specs/http_connector.js | 8 +- test/unit/specs/log.js | 12 +- test/unit/specs/random_selector.js | 8 +- test/unit/specs/round_robin_selector.js | 6 +- test/unit/specs/stream_logger.js | 8 +- test/unit/specs/transport.js | 52 ++--- test/unit/specs/transport_with_server.js | 8 +- test/unit/specs/utils.js | 204 +++++++++--------- test/utils/expect_sub_object.js | 4 +- test/utils/jenkins-reporter.js | 16 +- test/utils/make_j_unit_xml.js | 10 +- test/utils/server.js | 4 +- 74 files changed, 594 insertions(+), 597 deletions(-) diff --git a/docs/configuration.asciidoc b/docs/configuration.asciidoc index 138f3fbc2..b5ad70a8a 100644 --- a/docs/configuration.asciidoc +++ b/docs/configuration.asciidoc @@ -315,7 +315,7 @@ var client = new elasticsearch.Client({ selector: function (hosts) { var myCountry = process.env.COUNTRY; // first try to find a node that is in the same country - var selection = _v4.find(nodes, function (node) { + var selection = _.find(nodes, function (node) { return node.host.country === myCountry; }); diff --git a/docs/host.asciidoc b/docs/host.asciidoc index 6fb0784d0..98bc353c8 100644 --- a/docs/host.asciidoc +++ b/docs/host.asciidoc @@ -88,7 +88,7 @@ var client = new elasticsearch.Client({ selector: function (hosts) { var myCountry = process.env.COUNTRY; // first try to find a node that is in the same country - var selection = _v4.find(nodes, function (node) { + var selection = _.find(nodes, function (node) { return node.host.country === myCountry; }); diff --git a/grunt/config/esvm.js b/grunt/config/esvm.js index 5ee23ccad..31c3047f0 100644 --- a/grunt/config/esvm.js +++ b/grunt/config/esvm.js @@ -1,11 +1,11 @@ -// var _ = require('lodash'); +var _ = require('lodash'); var utils = require('../utils'); var fromRoot = require('path').join.bind(null, __dirname, '..', '..'); var release = process.env.ES_RELEASE; var ref = process.env.ES_REF; -var port = parseFloat(_v4.get(process.env, 'ES_PORT', 9400)); -var host = _v4.get(process.env, 'ES_HOST', 'localhost'); +var port = parseFloat(_.get(process.env, 'ES_PORT', 9400)); +var host = _.get(process.env, 'ES_HOST', 'localhost'); var Version = require('../../scripts/Version'); var versionedOpts = [ diff --git a/grunt/config/mochacov.js b/grunt/config/mochacov.js index 0afc61649..dd896a0a7 100644 --- a/grunt/config/mochacov.js +++ b/grunt/config/mochacov.js @@ -1,7 +1,7 @@ var root = require('find-root')(__dirname); var rel = require('path').resolve.bind(null, root); var rootReq = function (p) { return require(rel(p)); }; -// var _ = rootReq('src/lib/utils'); +var _ = rootReq('src/lib/utils'); var grunt = require('grunt'); var JENKINS_REPORTER = rel('test/utils/jenkins-reporter.js'); @@ -65,7 +65,7 @@ var config = { grunt.registerTask('mocha_integration', function (branch) { grunt.config.set( 'mochacov.integration.src', - 'test/integration/yaml_suite/index_' + _v4.snakeCase(branch) + '.js' + 'test/integration/yaml_suite/index_' + _.snakeCase(branch) + '.js' ); grunt.task.run('mochacov:integration'); }); @@ -73,7 +73,7 @@ grunt.registerTask('mocha_integration', function (branch) { grunt.registerTask('mocha_jenkins_integration', function (branch) { grunt.config.set( 'mochacov.jenkins_integration.src', - 'test/integration/yaml_suite/index_' + _v4.snakeCase(branch) + '.js' + 'test/integration/yaml_suite/index_' + _.snakeCase(branch) + '.js' ); grunt.task.run('mochacov:jenkins_integration'); }); diff --git a/grunt/utils.js b/grunt/utils.js index ff4011daa..a880791b6 100644 --- a/grunt/utils.js +++ b/grunt/utils.js @@ -1,4 +1,4 @@ -// var _ = require('../src/lib/utils'); +var _ = require('../src/lib/utils'); var root = require('find-root')(__dirname); var pkg = require(root + '/package.json'); @@ -8,7 +8,7 @@ var branches = [].concat(stable, unstable); var utils = { branchSuffix: function (branch) { - return branch === utils.branches._default ? '' : '_' + _v4.snakeCase(branch); + return branch === utils.branches._default ? '' : '_' + _.snakeCase(branch); }, branches: branches, stableBranches: stable, diff --git a/package.json b/package.json index d16bd021d..3220ce49a 100644 --- a/package.json +++ b/package.json @@ -96,7 +96,7 @@ "dependencies": { "chalk": "^1.0.0", "forever-agent": "^0.6.0", - "lodash": "^3.10.0", + "lodash": "^4.12.0", "lodash-compat": "^3.0.0", "promise": "^7.1.1" }, diff --git a/scripts/Version.js b/scripts/Version.js index cd43f4a46..bfcfcebeb 100644 --- a/scripts/Version.js +++ b/scripts/Version.js @@ -1,4 +1,4 @@ -// var _ = require('lodash'); +var _ = require('lodash'); var pkg = require('../package.json'); var branches = pkg.config.supported_es_branches; var semver = require('semver'); @@ -47,10 +47,10 @@ Version.prototype.mergeOpts = function (opts) { return opts.filter(function (rule) { return self.satisfies(rule.version); }) - .map(_v4.ary(_v4.partialRight(_v4.omit, 'version'), 1)) - .concat(_v4.tail(arguments)) + .map(_.ary(_.partialRight(_.omit, 'version'), 1)) + .concat(_.tail(arguments)) .reverse() - .reduce(_v4.merge, {}); + .reduce(_.merge, {}); }; module.exports = Version; diff --git a/scripts/ci.js b/scripts/ci.js index ccb7c9fbb..bc6bda3d3 100644 --- a/scripts/ci.js +++ b/scripts/ci.js @@ -18,7 +18,7 @@ *******/ var Promise = require('bluebird'); -// var _ = require('lodash'); +var _ = require('lodash'); var through2 = require('through2'); var map = require('through2-map'); var split = require('split'); @@ -30,7 +30,7 @@ var format = require('util').format; var NL_RE = /(\r?\n)/g; var ROOT = join(__dirname, '..'); var GRUNT = join(ROOT, 'node_modules', '.bin', 'grunt'); -var ENV = _v4.clone(process.env); +var ENV = _.clone(process.env); var JENKINS = !!ENV.JENKINS_HOME; var TASKS = []; @@ -80,7 +80,7 @@ task('SAUCE_LABS', false, function () { })); }) // ignore server errors - .catch(_v4.noop); + .catch(_.noop); // attempt to run tests on saucelabs and retry if it fails var saucelabsAttempts = 0; @@ -116,7 +116,7 @@ task('SAUCE_LABS', false, function () { }); }) // swallow spawn() errors, custom error handler in place - .catch(_v4.noop); + .catch(_.noop); }); } }); @@ -168,13 +168,13 @@ execTask('SETUP', function () { }) .then(function readTasks() { if (!ENV.RUN) { - return _v4.filter(TASKS, { default: true }); + return _.filter(TASKS, { default: true }); } return ENV.RUN .split(',') .map(function (name) { - return _v4.find(TASKS, { name: name.trim() }); + return _.find(TASKS, { name: name.trim() }); }) .filter(Boolean); }); @@ -218,7 +218,7 @@ function logImportant(text) { function push(m) { return function () { - var args = _v4.toArray(arguments); + var args = _.toArray(arguments); var cb = args.pop(); this.push(m.apply(this, args)); cb(); @@ -235,7 +235,7 @@ function indent() { } function task(name, def, fn) { - if (_v4.isFunction(def)) { + if (_.isFunction(def)) { fn = def; def = true; } @@ -248,7 +248,7 @@ function task(name, def, fn) { } function execTask(name, task) { - if (_v4.isObject(name)) { + if (_.isObject(name)) { task = name.fn; name = name.name; } @@ -316,13 +316,13 @@ function spawn(file, args, block) { function node(/* args... */) { return spawn( process.execPath, - _v4.toArray(arguments) + _.toArray(arguments) ); } function grunt(/* args... */) { return spawn( GRUNT, - _v4.toArray(arguments) + _.toArray(arguments) ); } diff --git a/scripts/generate/api_index.js b/scripts/generate/api_index.js index a1ae5e33d..4704d49cb 100644 --- a/scripts/generate/api_index.js +++ b/scripts/generate/api_index.js @@ -1,9 +1,9 @@ module.exports = function (done) { - // var _ = require('../../src/lib/utils'); + var _ = require('../../src/lib/utils'); var utils = require('../../grunt/utils'); var chalk = require('chalk'); - var fromRoot = _v4.partial(require('path').join, require('find-root')(__dirname)); + var fromRoot = _.partial(require('path').join, require('find-root')(__dirname)); var write = require('fs').writeFileSync; var nodeApiIndex = fromRoot('src/lib/apis/index.js'); diff --git a/scripts/generate/configuration_docs.js b/scripts/generate/configuration_docs.js index bc118982b..939e8bdae 100644 --- a/scripts/generate/configuration_docs.js +++ b/scripts/generate/configuration_docs.js @@ -1,8 +1,8 @@ module.exports = function (done) { - // var _ = require('../../src/lib/utils'); + var _ = require('../../src/lib/utils'); var chalk = require('chalk'); - var fromRoot = _v4.partial(require('path').join, require('find-root')(__dirname)); + var fromRoot = _.partial(require('path').join, require('find-root')(__dirname)); var write = require('fs').writeFile; var outputPath = fromRoot('docs/configuration.asciidoc'); diff --git a/scripts/generate/doc_index.js b/scripts/generate/doc_index.js index bf0394eb4..07cea06f2 100644 --- a/scripts/generate/doc_index.js +++ b/scripts/generate/doc_index.js @@ -1,9 +1,9 @@ module.exports = function (done) { - // var _ = require('../../src/lib/utils'); + var _ = require('../../src/lib/utils'); var utils = require('../../grunt/utils'); var chalk = require('chalk'); - var fromRoot = _v4.partial(require('path').join, require('find-root')(__dirname)); + var fromRoot = _.partial(require('path').join, require('find-root')(__dirname)); var write = require('fs').writeFile; var outputPath = fromRoot('docs/index.asciidoc'); diff --git a/scripts/generate/index.js b/scripts/generate/index.js index d80e6a404..c2f2f9f03 100644 --- a/scripts/generate/index.js +++ b/scripts/generate/index.js @@ -30,7 +30,7 @@ var argv = require('optimist') var path = require('path'); var fromRoot = path.join.bind(path, require('find-root')(__dirname)); var utils = require(fromRoot('grunt/utils')); -// var _ = require(fromRoot('src/lib/utils')); +var _ = require(fromRoot('src/lib/utils')); var esUrl = 'https://github.com/elastic/elasticsearch.git'; var branches; @@ -56,10 +56,10 @@ var paths = { docsIndex: fromRoot('docs/index.asciidoc'), apiSrc: 'src/lib/apis', getArchiveDir: function (branch) { - return fromRoot('src/_elasticsearch_' + _v4.snakeCase(branch)); + return fromRoot('src/_elasticsearch_' + _.snakeCase(branch)); }, getArchiveTarball: function (branch) { - return fromRoot('src/_elasticsearch_' + _v4.snakeCase(branch) + '.tar'); + return fromRoot('src/_elasticsearch_' + _.snakeCase(branch) + '.tar'); }, getSpecPathInRepo: function (branch) { return /^v?(master|[2-9]\.)/.test(branch) ? 'rest-api-spec/src/main/resources/rest-api-spec' : 'rest-api-spec'; @@ -93,9 +93,9 @@ function dirRegex(dir, regexp) { } function dirOpts(dir, opts) { - opts = _v4.isArray(opts) ? opts : [opts]; + opts = _.isArray(opts) ? opts : [opts]; return dirFilter(dir, function (name) { - return _v4.includes(opts, name); + return _.includes(opts, name); }); } @@ -130,7 +130,7 @@ function fetchBranchesStep() { function findGeneratedApiFiles() { var anyApiMethodDocs = /^(configuration|index|api_methods).*\.asciidoc$/; var anyApiJsFiled = /^.+\.js$/; - var allBranches = _v4.isEqual(branches, utils.branches); + var allBranches = _.isEqual(branches, utils.branches); if (allBranches) { return [ @@ -140,7 +140,7 @@ function findGeneratedApiFiles() { } return branches.reduce(function (files, branch) { - var b = _v4.snakeCase(branch); + var b = _.snakeCase(branch); files.push(dirOpts(paths.docs, 'api_methods_' + b + '.asciidoc')); @@ -166,7 +166,7 @@ function clearGeneratedFiles() { generatedFiles.push(dirRegex(paths.src, esArchives)); - var rmSteps = _v4.chain(generatedFiles) + var rmSteps = _.chain(generatedFiles) .flattenDeep() .uniq() .map(function (path) { @@ -195,7 +195,7 @@ function createArchive(branch) { var dir = paths.getArchiveDir(branch); var tarball = paths.getArchiveTarball(branch); var specPathInRepo = paths.getSpecPathInRepo(branch); - var subDirCount = _v4.countBy(specPathInRepo, _v4.partial(_v4.eq, '/')).true || 0; + var subDirCount = _.countBy(specPathInRepo, _.partial(_.eq, '/')).true || 0; if (isDirectory(dir)) { console.log(branch + ' archive already exists'); @@ -227,7 +227,7 @@ var steps = [ ].filter(Boolean); branches.forEach(function (branch) { - steps.push(_v4.partial(async.series, [ + steps.push(_.partial(async.series, [ removePrevArchive(branch), createArchive(branch), generateStep(branch) diff --git a/scripts/generate/js_api.js b/scripts/generate/js_api.js index 58b1093c6..2f9022144 100644 --- a/scripts/generate/js_api.js +++ b/scripts/generate/js_api.js @@ -3,7 +3,7 @@ module.exports = function (branch, done) { * Read the API actions form the rest-api-spec repo. * @type {[type]} */ - // var _ = require('../../src/lib/utils'); + var _ = require('../../src/lib/utils'); var utils = require('../../grunt/utils'); var fs = require('fs'); var async = require('async'); @@ -19,7 +19,7 @@ module.exports = function (branch, done) { var docVars; // slightly modified clone of apiSpec for the docs var branchSuffix = utils.branchSuffix(branch); - var esDir = fromRoot('src/_elasticsearch_' + _v4.snakeCase(branch)); + var esDir = fromRoot('src/_elasticsearch_' + _.snakeCase(branch)); var version = Version.fromBranch(branch); var overrides = version.mergeOpts(require('./overrides'), { @@ -71,27 +71,27 @@ module.exports = function (branch, done) { }); // collect the namespaces from the action locations - var namespaces = _v4.filter(_v4.map(actions, function (action) { + var namespaces = _.filter(_.map(actions, function (action) { if (~action.location.indexOf('.')) { var path = action.location.split('.').slice(0, -1); - _v4.pull(path, 'prototype'); + _.pull(path, 'prototype'); return path.join('.'); } })); // seperate the proxy actions - var groups = _v4.groupBy(actions, function (action) { + var groups = _.groupBy(actions, function (action) { return action.proxy ? 'proxies' : 'normal'; }); apiSpec = { actions: groups.normal || [], proxies: groups.proxies || [], - namespaces: _v4.uniq(namespaces.sort()), + namespaces: _.uniq(namespaces.sort()), clientActionModifier: overrides.clientActionModifier }; - var create = _v4.assign({}, _v4.find(apiSpec.actions, { name: 'index' }), { + var create = _.assign({}, _.find(apiSpec.actions, { name: 'index' }), { name: 'create', location: 'create', proxy: 'index', @@ -119,7 +119,7 @@ module.exports = function (branch, done) { } function writeApiFile(done) { - var outputPath = fromRoot('src/lib/apis/' + _v4.snakeCase(branch) + '.js'); + var outputPath = fromRoot('src/lib/apis/' + _.snakeCase(branch) + '.js'); fs.writeFileSync(outputPath, templates.apiFile(apiSpec)); console.log(chalk.white.bold('wrote'), apiSpec.actions.length, 'api actions to', outputPath); done(); @@ -145,8 +145,8 @@ module.exports = function (branch, done) { // merge the actions and proxies to make // itteration easir and keep them in order - docVars = _v4.omit(apiSpec, 'proxies'); - docVars.actions = _v4.sortBy( + docVars = _.omit(apiSpec, 'proxies'); + docVars.actions = _.sortBy( [].concat(apiSpec.actions).concat(apiSpec.proxies), 'name' ); @@ -174,9 +174,9 @@ module.exports = function (branch, done) { var actions = []; // itterate all of the specs within the file, should only be one - _v4.each(spec, function (def, name) { + _.each(spec, function (def, name) { // camelcase the name - name = _v4.map(name.split('.'), _v4.camelCase).join('.'); + name = _.map(name.split('.'), _.camelCase).join('.'); if (name === 'cat.aliases') { def.documentation = 'http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat.html'; @@ -185,23 +185,23 @@ module.exports = function (branch, done) { var steps = name.split('.'); function transformParamKeys(note, param, key) { - var cmlKey = _v4.camelCase(key); + var cmlKey = _.camelCase(key); if (cmlKey !== key) { param.name = key; } note[cmlKey] = param; } - def.url.params = _v4.transform(def.url.params, transformParamKeys, {}); - def.url.parts = _v4.transform(def.url.parts, transformParamKeys, {}); + def.url.params = _.transform(def.url.params, transformParamKeys, {}); + def.url.parts = _.transform(def.url.parts, transformParamKeys, {}); - var allParams = _v4.extend({}, def.url.params, def.url.parts); + var allParams = _.extend({}, def.url.params, def.url.parts); var spec = { name: name, - methods: _v4.map(def.methods, function (m) { return m.toUpperCase(); }), + methods: _.map(def.methods, function (m) { return m.toUpperCase(); }), params: def.url.params, body: def.body || null, - path2lib: _v4.repeat('../', steps.length + 1) + 'lib/' + path2lib: _.repeat('../', steps.length + 1) + 'lib/' }; if (def.body && def.body.required) { @@ -216,9 +216,9 @@ module.exports = function (branch, done) { spec.requestTimeout = 3000; } - var urls = _v4.difference(def.url.paths, overrides.aliases[name]); + var urls = _.difference(def.url.paths, overrides.aliases[name]); var urlSignatures = []; - urls = _v4.map(urls, function (url) { + urls = _.map(urls, function (url) { var optionalVars = {}; var requiredVars = {}; var param; @@ -231,47 +231,47 @@ module.exports = function (branch, done) { } while (match = urlParamRE.exec(url)) { - name = _v4.camelCase(match[1]); + name = _.camelCase(match[1]); param = def.url.parts[name] || {}; target = (param.required || !param.default) ? requiredVars : optionalVars; - target[name] = _v4.omit(param, 'required', 'description', 'name'); + target[name] = _.omit(param, 'required', 'description', 'name'); } - urlSignatures.push(_v4.union(_v4.keys(optionalVars), _v4.keys(requiredVars)).sort().join(':')); + urlSignatures.push(_.union(_.keys(optionalVars), _.keys(requiredVars)).sort().join(':')); - return _v4.omitBy({ + return _.omitBy({ fmt: url.replace(urlParamRE, function (full, match) { - return '<%=' + _v4.camelCase(match) + '%>'; + return '<%=' + _.camelCase(match) + '%>'; }), - opt: _v4.size(optionalVars) ? optionalVars : null, - req: _v4.size(requiredVars) ? requiredVars : null, - sortOrder: _v4.size(requiredVars) * -1 + opt: _.size(optionalVars) ? optionalVars : null, + req: _.size(requiredVars) ? requiredVars : null, + sortOrder: _.size(requiredVars) * -1 }, function (v) { return !v; }); }); - if (urlSignatures.length !== _v4.uniq(urlSignatures).length) { + if (urlSignatures.length !== _.uniq(urlSignatures).length) { throw new Error( 'Multiple URLS with the same signature detected for ' + spec.name + '\n' + - _v4.map(urls, 'fmt').join('\n') + + _.map(urls, 'fmt').join('\n') + '\n' ); } if (urls.length > 1) { - spec.urls = _v4.map(_v4.sortBy(urls, 'sortOrder'), function (url) { - return _v4.omit(url, 'sortOrder'); + spec.urls = _.map(_.sortBy(urls, 'sortOrder'), function (url) { + return _.omit(url, 'sortOrder'); }); } else { - spec.url = _v4.omit(urls[0], 'sortOrder'); + spec.url = _.omit(urls[0], 'sortOrder'); } - spec.params = _v4.transform(spec.params, function (note, param, name) { + spec.params = _.transform(spec.params, function (note, param, name) { // param.name = name; - note[name] = _v4.pick(param, [ + note[name] = _.pick(param, [ 'type', 'default', 'options', 'required', 'name' ]); }, {}); @@ -280,7 +280,7 @@ module.exports = function (branch, done) { spec.paramAsBody = overrides.paramAsBody[name]; } - if (_v4.size(spec.params) === 0) { + if (_.size(spec.params) === 0) { delete spec.params; } @@ -290,7 +290,7 @@ module.exports = function (branch, done) { var action = { _methods: spec.methods, - spec: _v4.pick(spec, [ + spec: _.pick(spec, [ 'params', 'url', 'urls', diff --git a/scripts/generate/templates/api_file.tmpl b/scripts/generate/templates/api_file.tmpl index f178293c8..bd87d7f05 100644 --- a/scripts/generate/templates/api_file.tmpl +++ b/scripts/generate/templates/api_file.tmpl @@ -9,21 +9,21 @@ var api = module.exports = {}; api._namespaces = <%= stringify(namespaces) %>;<% -_v4.each(actions, function (action) { +_.each(actions, function (action) { var namespace = action.location.split('.').shift(); if (_.includes(namespaces, namespace)) { - _v4.pull(namespaces, namespace); + _.pull(namespaces, namespace); %> api.<%= namespace %> = namespace();<% }%> -<%= _v4.trimEnd(partials.client_action(action)) %><% +<%= _.trimEnd(partials.client_action(action)) %><% }); -_v4.each(proxies, function (action) {%> +_.each(proxies, function (action) {%> -<%= _v4.trimEnd(partials.client_action_proxy(action)) %><% +<%= _.trimEnd(partials.client_action_proxy(action)) %><% }); %> diff --git a/scripts/generate/templates/api_index.tmpl b/scripts/generate/templates/api_index.tmpl index 073e9f773..60e14139c 100644 --- a/scripts/generate/templates/api_index.tmpl +++ b/scripts/generate/templates/api_index.tmpl @@ -2,7 +2,7 @@ module.exports = { <% branches.forEach(function (branch, i, list) { - var req = "require('./" + _v4.snakeCase(branch) + "')"; + var req = "require('./" + _.snakeCase(branch) + "')"; if (branch === utils.branches._default) { print(" '_default': " + req + ',\n'); } diff --git a/scripts/generate/templates/api_methods.tmpl b/scripts/generate/templates/api_methods.tmpl index eb5d0fa9b..01574797d 100644 --- a/scripts/generate/templates/api_methods.tmpl +++ b/scripts/generate/templates/api_methods.tmpl @@ -7,8 +7,8 @@ NOTE: This is currently the default API, but in upcoming versions that will chan NOTE: At this time, you must opt into the <%= branch %> API by setting the `apiVersion` config parameter. <% } -actions = _v4.sortBy(actions, 'namespace'); -_v4.each(actions, function (action) { +actions = _.sortBy(actions, 'namespace'); +_.each(actions, function (action) { action.index = 'api-' + action.name.toLowerCase().replace(/[^\w]+/g, '-') + branchSuffix; %> @@ -27,16 +27,16 @@ The default method is `<%= action.spec.method || 'GET' %>` and the usual < -<% if (_v4.size(action.allParams)) { %> +<% if (_.size(action.allParams)) { %> *Params* [horizontal]<% -_v4.each(action.allParams, function (param, paramName) { %> +_.each(action.allParams, function (param, paramName) { %> `<%= paramWithDefault(paramName, param.default) %>`:: `<%= paramType(param.type) %>` -- <%= joinParagraphs(param.description || '', 4) %><% if (param.type === 'enum') {%> Options:::<% -_v4.each(param.options, function (opt) {%> +_.each(param.options, function (opt) {%> * `"<%= opt %>"`<% });%> <% diff --git a/scripts/generate/templates/client_action.tmpl b/scripts/generate/templates/client_action.tmpl index 490e19652..81477174b 100644 --- a/scripts/generate/templates/client_action.tmpl +++ b/scripts/generate/templates/client_action.tmpl @@ -2,7 +2,7 @@ * Perform a [<%= name %>](<%= docUrl %>) request * * @param {Object} params - An object with parameters used to carry out this action<% -_v4.each(allParams, function(param, paramName) { %> +_.each(allParams, function(param, paramName) { %> * @param {<%= paramType(param.type) %>} <%= paramWithDefault('params.' + paramName, param.default) %><% if (param.description) { %> - <%= param.description %><% diff --git a/scripts/generate/templates/client_action_proxy.tmpl b/scripts/generate/templates/client_action_proxy.tmpl index b122028b2..d708f1401 100644 --- a/scripts/generate/templates/client_action_proxy.tmpl +++ b/scripts/generate/templates/client_action_proxy.tmpl @@ -2,7 +2,7 @@ * Perform a [<%= name %>](<%= docUrl %>) request * * @param {Object} params - An object with parameters used to carry out this action<% -_v4.each(allParams, function(param, paramName) { %> +_.each(allParams, function(param, paramName) { %> * @param {<%= paramType(param.type) %>} <%= paramWithDefault('params.' + paramName, param.default) %><% if (param.description) { %> - <%= param.description %><% diff --git a/scripts/generate/templates/configuration_docs.tmpl b/scripts/generate/templates/configuration_docs.tmpl index 5a5691896..f554c5cca 100644 --- a/scripts/generate/templates/configuration_docs.tmpl +++ b/scripts/generate/templates/configuration_docs.tmpl @@ -303,7 +303,7 @@ var client = new elasticsearch.Client({ selector: function (hosts) { var myCountry = process.env.COUNTRY; // first try to find a node that is in the same country - var selection = _v4.find(nodes, function (node) { + var selection = _.find(nodes, function (node) { return node.host.country === myCountry; }); diff --git a/scripts/generate/templates/index.js b/scripts/generate/templates/index.js index 6d281f1f0..3a2f2ad23 100644 --- a/scripts/generate/templates/index.js +++ b/scripts/generate/templates/index.js @@ -1,5 +1,5 @@ -// var _ = require('../../../src/lib/utils'); +var _ = require('../../../src/lib/utils'); var utils = require('../../../grunt/utils'); var fs = require('fs'); var path = require('path'); @@ -41,10 +41,10 @@ var templateGlobals = { stringify: stringify, - _v4: _v4, + _: _, indent: function (block, spaces) { - var indent = _v4.repeat(' ', spaces); + var indent = _.repeat(' ', spaces); return block.split('\n').map(function (line) { return indent + line; }).join('\n'); @@ -77,7 +77,7 @@ var templateGlobals = { case 'list': return 'String, String[], Boolean'; default: - return _v4.ucfirst(type); + return _.ucfirst(type); } }, @@ -97,7 +97,7 @@ var templateGlobals = { fs.readdirSync(path.resolve(__dirname)).forEach(function (filename) { var name = filename.replace(/\..+$/, ''); if (name !== 'index') { - templates[name] = _v4.template( + templates[name] = _.template( fs.readFileSync(path.resolve(__dirname, filename), 'utf8'), { imports: templateGlobals diff --git a/scripts/generate/yaml_tests.js b/scripts/generate/yaml_tests.js index 39c72cfea..093695b1a 100644 --- a/scripts/generate/yaml_tests.js +++ b/scripts/generate/yaml_tests.js @@ -8,10 +8,10 @@ module.exports = function (branch, done) { var chalk = require('chalk'); var path = require('path'); var fromRoot = path.join.bind(path, require('find-root')(__dirname)); - // var _ = require(fromRoot('src/lib/utils')); + var _ = require(fromRoot('src/lib/utils')); var tests = {}; // populated in readYamlTests - var esDir = fromRoot('src/_elasticsearch_' + _v4.snakeCase(branch)); + var esDir = fromRoot('src/_elasticsearch_' + _.snakeCase(branch)); // generate the yaml tests async.series([ @@ -43,14 +43,14 @@ module.exports = function (branch, done) { } function writeYamlTests(done) { - var testFile = fromRoot('test/integration/yaml_suite/yaml_tests_' + _v4.snakeCase(branch) + '.json'); + var testFile = fromRoot('test/integration/yaml_suite/yaml_tests_' + _.snakeCase(branch) + '.json'); fs.writeFileSync(testFile, JSON.stringify(tests, null, ' '), 'utf8'); console.log(chalk.white.bold('wrote') + ' YAML tests as JSON to', testFile); done(); } function writeTestIndex(done) { - var file = fromRoot('test/integration/yaml_suite/index_' + _v4.snakeCase(branch) + '.js'); + var file = fromRoot('test/integration/yaml_suite/index_' + _.snakeCase(branch) + '.js'); fs.writeFileSync(file, 'require(\'./run\')(\'' + branch + '\');\n', 'utf8'); console.log(chalk.white.bold('wrote') + ' YAML index to', file); done(); diff --git a/scripts/release/bower.js b/scripts/release/bower.js index f2d4256a1..3705c1dcb 100644 --- a/scripts/release/bower.js +++ b/scripts/release/bower.js @@ -1,7 +1,7 @@ var fs = require('fs'); var spawn = require('../_spawn'); var async = require('async'); -// var _ = require('lodash'); +var _ = require('lodash'); var root = require('path').join(__dirname, '../..'); var bowerDir = root + '/src/bower_es_js'; @@ -21,7 +21,7 @@ fs.writeFileSync(bowerDir + '/bower.json', JSON.stringify(bowerJson, null, ' ') fs.writeFileSync(bowerDir + '/package.json', JSON.stringify(bowerPackageJson, null, ' ')); function make(cmd, args) { - return _v4.bind(spawn, null, cmd, args, { + return _.bind(spawn, null, cmd, args, { verbose: true, cwd: bowerDir }); @@ -36,7 +36,7 @@ async.series([ make('npm', ['publish']) ], function (err) { if (err) { - if (_v4.isNumber(err)) { + if (_.isNumber(err)) { console.log('Non-zero exit code: %d', err); } else { console.log('Error: ', err.message ? err.message : err); diff --git a/src/lib/client.js b/src/lib/client.js index 48b260bdb..51058dade 100755 --- a/src/lib/client.js +++ b/src/lib/client.js @@ -28,7 +28,7 @@ module.exports = Client; var Transport = require('./transport'); var clientAction = require('./client_action'); -// var _ = require('./utils'); +var _ = require('./utils'); function Client(config) { config = config || {}; @@ -56,7 +56,7 @@ function Client(config) { this.transport = new Transport(config); - _v4.each(EsApiClient.prototype, _v4.bind(function (Fn, prop) { + _.each(EsApiClient.prototype, _.bind(function (Fn, prop) { if (Fn.prototype instanceof clientAction.ApiNamespace) { this[prop] = new Fn(this.transport); } @@ -66,7 +66,7 @@ function Client(config) { } - EsApiClient.prototype = _v4.funcEnum(config, 'apiVersion', Client.apis, '_default'); + EsApiClient.prototype = _.funcEnum(config, 'apiVersion', Client.apis, '_default'); if (!config.sniffEndpoint && EsApiClient.prototype === Client.apis['0.90']) { config.sniffEndpoint = '/_cluster/nodes'; } @@ -74,9 +74,9 @@ function Client(config) { var Constructor = EsApiClient; if (config.plugins) { - Constructor.prototype = _v4.cloneDeep(Constructor.prototype); + Constructor.prototype = _.cloneDeep(Constructor.prototype); - _v4.each(config.plugins, function (setup) { + _.each(config.plugins, function (setup) { Constructor = setup(Constructor, config, { apis: require('./apis'), connectors: require('./connectors'), diff --git a/src/lib/client_action.js b/src/lib/client_action.js index 86080a85f..e6596eb0e 100644 --- a/src/lib/client_action.js +++ b/src/lib/client_action.js @@ -1,5 +1,5 @@ -// var _ = require('./utils'); +var _ = require('./utils'); /** * Constructs a client action factory that uses specific defaults @@ -34,12 +34,12 @@ exports.namespaceFactory = function () { }; function makeFactoryWithModifier(modifier) { - modifier = modifier || _v4.identity; + modifier = modifier || _.identity; var factory = function (spec) { spec = modifier(spec); - if (!_v4.isPlainObject(spec.params)) { + if (!_.isPlainObject(spec.params)) { spec.params = {}; } @@ -57,10 +57,10 @@ function makeFactoryWithModifier(modifier) { } try { - return exec(this.transport, spec, _v4.clone(params), cb); + return exec(this.transport, spec, _.clone(params), cb); } catch (e) { if (typeof cb === 'function') { - _v4.nextTick(cb, e); + _.nextTick(cb, e); } else { var def = this.transport.defer(); def.reject(e); @@ -97,11 +97,11 @@ function makeFactoryWithModifier(modifier) { var castType = { 'enum': function validSelection(param, val, name) { - if (_v4.isString(val) && val.indexOf(',') > -1) { + if (_.isString(val) && val.indexOf(',') > -1) { val = commaSepList(val); } - if (_v4.isArray(val)) { + if (_.isArray(val)) { return val.map(function (v) { return validSelection(param, v, name); }).join(','); @@ -119,7 +119,7 @@ var castType = { )); }, duration: function (param, val, name) { - if (_v4.isNumeric(val) || _v4.isInterval(val)) { + if (_.isNumeric(val) || _.isInterval(val)) { return val; } else { throw new TypeError( @@ -137,7 +137,7 @@ var castType = { val = commaSepList(val); /* falls through */ case 'object': - if (_v4.isArray(val)) { + if (_.isArray(val)) { return val.join(','); } /* falls through */ @@ -146,11 +146,11 @@ var castType = { } }, 'boolean': function (param, val) { - val = _v4.isString(val) ? val.toLowerCase() : val; + val = _.isString(val) ? val.toLowerCase() : val; return (val === 'no' || val === 'off') ? false : !!val; }, number: function (param, val, name) { - if (_v4.isNumeric(val)) { + if (_.isNumeric(val)) { return val * 1; } else { throw new TypeError('Invalid ' + name + ': expected a number.'); @@ -169,7 +169,7 @@ var castType = { if (typeof val === 'string') { return val; } - else if (_v4.isNumeric(val)) { + else if (_.isNumeric(val)) { return '' + val; } else if (val instanceof Date) { @@ -188,7 +188,7 @@ function resolveUrl(url, params) { // url has required params if (!url.reqParamKeys) { // create cached key list on demand - url.reqParamKeys = _v4.keys(url.req); + url.reqParamKeys = _.keys(url.req); } for (i = 0; i < url.reqParamKeys.length; i ++) { @@ -210,7 +210,7 @@ function resolveUrl(url, params) { if (url.opt) { // url has optional params if (!url.optParamKeys) { - url.optParamKeys = _v4.keys(url.opt); + url.optParamKeys = _.keys(url.opt); } for (i = 0; i < url.optParamKeys.length; i ++) { @@ -229,10 +229,10 @@ function resolveUrl(url, params) { if (!url.template) { // compile the template on demand - url.template = _v4.template(url.fmt); + url.template = _.template(url.fmt); } - return url.template(_v4.transform(vars, function (note, val, name) { + return url.template(_.transform(vars, function (note, val, name) { // encode each value note[name] = encodeURIComponent(val); // remove it from the params so that it isn't sent to the final request @@ -287,14 +287,14 @@ function exec(transport, spec, params, cb) { if (!request.path) { // there must have been some mimimun requirements that were not met var minUrl = spec.url || spec.urls[spec.urls.length - 1]; - throw new TypeError('Unable to build a path with those params. Supply at least ' + _v4.keys(minUrl.req).join(', ')); + throw new TypeError('Unable to build a path with those params. Supply at least ' + _.keys(minUrl.req).join(', ')); } // build the query string if (!spec.paramKeys) { // build a key list on demand - spec.paramKeys = _v4.keys(spec.params); - spec.requireParamKeys = _v4.transform(spec.params, function (req, param, key) { + spec.paramKeys = _.keys(spec.params); + spec.requireParamKeys = _.transform(spec.params, function (req, param, key) { if (param.required) { req.push(key); } @@ -311,10 +311,10 @@ function exec(transport, spec, params, cb) { request[key] = params[key]; break; case 'ignore': - request.ignore = _v4.isArray(params[key]) ? params[key] : [params[key]]; + request.ignore = _.isArray(params[key]) ? params[key] : [params[key]]; break; case 'method': - request.method = _v4.toUpperString(params[key]); + request.method = _.toUpperString(params[key]); break; default: var paramSpec = spec.params[key]; diff --git a/src/lib/connection.js b/src/lib/connection.js index cf7e3d8ac..93c8c38a6 100644 --- a/src/lib/connection.js +++ b/src/lib/connection.js @@ -1,6 +1,6 @@ module.exports = ConnectionAbstract; -// var _ = require('./utils'); +var _ = require('./utils'); var EventEmitter = require('events').EventEmitter; var Log = require('./log'); var Host = require('./host'); @@ -26,9 +26,9 @@ function ConnectionAbstract(host, config) { throw new TypeError('Invalid host'); } - _v4.makeBoundMethods(this); + _.makeBoundMethods(this); } -_v4.inherits(ConnectionAbstract, EventEmitter); +_.inherits(ConnectionAbstract, EventEmitter); /** * Make a request using this connection. Must be overridden by Connection classes, which can add whatever keys to @@ -61,7 +61,7 @@ ConnectionAbstract.prototype.ping = function (params, cb) { requestTimeout = params.requestTimeout; } - abort = this.request(_v4.defaults(params || {}, { + abort = this.request(_.defaults(params || {}, { path: '/', method: 'HEAD' }), function (err) { diff --git a/src/lib/connection_pool.js b/src/lib/connection_pool.js index 49c67b445..87c6dfcb9 100644 --- a/src/lib/connection_pool.js +++ b/src/lib/connection_pool.js @@ -9,12 +9,12 @@ module.exports = ConnectionPool; -// var _ = require('./utils'); +var _ = require('./utils'); var Log = require('./log'); function ConnectionPool(config) { config = config || {}; - _v4.makeBoundMethods(this); + _.makeBoundMethods(this); if (!config.log) { this.log = new Log(); @@ -27,16 +27,16 @@ function ConnectionPool(config) { this._config = config; // get the selector config var - this.selector = _v4.funcEnum(config, 'selector', ConnectionPool.selectors, ConnectionPool.defaultSelector); + this.selector = _.funcEnum(config, 'selector', ConnectionPool.selectors, ConnectionPool.defaultSelector); // get the connection class - this.Connection = _v4.funcEnum(config, 'connectionClass', ConnectionPool.connectionClasses, + this.Connection = _.funcEnum(config, 'connectionClass', ConnectionPool.connectionClasses, ConnectionPool.defaultConnectionClass); // time that connections will wait before being revived this.deadTimeout = config.hasOwnProperty('deadTimeout') ? config.deadTimeout : 60000; this.maxDeadTimeout = config.hasOwnProperty('maxDeadTimeout') ? config.maxDeadTimeout : 18e5; - this.calcDeadTimeout = _v4.funcEnum(config, 'calcDeadTimeout', ConnectionPool.calcDeadTimeoutOptions, 'exponential'); + this.calcDeadTimeout = _.funcEnum(config, 'calcDeadTimeout', ConnectionPool.calcDeadTimeoutOptions, 'exponential'); // a map of connections to their "id" property, used when sniffing this.index = {}; @@ -86,7 +86,7 @@ ConnectionPool.prototype.select = function (cb) { this.selector(this._conns.alive, cb); } else { try { - _v4.nextTick(cb, void 0, this.selector(this._conns.alive)); + _.nextTick(cb, void 0, this.selector(this._conns.alive)); } catch (e) { cb(e); } @@ -94,7 +94,7 @@ ConnectionPool.prototype.select = function (cb) { } else if (this._timeouts.length) { this._selectDeadConnection(cb); } else { - _v4.nextTick(cb, void 0); + _.nextTick(cb, void 0); } }; @@ -106,7 +106,7 @@ ConnectionPool.prototype.select = function (cb) { * @param {String} oldStatus - the connection's old status * @param {ConnectionAbstract} connection - the connection object itself */ -ConnectionPool.prototype.onStatusSet = _v4.handler(function (status, oldStatus, connection) { +ConnectionPool.prototype.onStatusSet = _.handler(function (status, oldStatus, connection) { var index; var died = (status === 'dead'); @@ -121,14 +121,14 @@ ConnectionPool.prototype.onStatusSet = _v4.handler(function (status, oldStatus, } if (from !== to) { - if (_v4.isArray(from)) { + if (_.isArray(from)) { index = from.indexOf(connection); if (index !== -1) { from.splice(index, 1); } } - if (_v4.isArray(to)) { + if (_.isArray(to)) { index = to.indexOf(connection); if (index === -1) { to.push(connection); @@ -200,11 +200,11 @@ ConnectionPool.prototype._onConnectionDied = function (connection, alreadyWasDea var ms = this.calcDeadTimeout(timeout.attempt, this.deadTimeout); timeout.id = setTimeout(timeout.revive, ms); - timeout.runAt = _v4.now() + ms; + timeout.runAt = _.now() + ms; }; ConnectionPool.prototype._selectDeadConnection = function (cb) { - var orderedTimeouts = _v4.sortBy(this._timeouts, 'runAt'); + var orderedTimeouts = _.sortBy(this._timeouts, 'runAt'); var log = this.log; process.nextTick(function next() { @@ -257,7 +257,7 @@ ConnectionPool.prototype.getConnections = function (status, limit) { if (limit == null) { return list.slice(0); } else { - return _v4.shuffle(list).slice(0, limit); + return _.shuffle(list).slice(0, limit); } }; @@ -308,7 +308,7 @@ ConnectionPool.prototype.setHosts = function (hosts) { var i; var id; var host; - var toRemove = _v4.clone(this.index); + var toRemove = _.clone(this.index); for (i = 0; i < hosts.length; i++) { host = hosts[i]; @@ -322,14 +322,14 @@ ConnectionPool.prototype.setHosts = function (hosts) { } } - var removeIds = _v4.keys(toRemove); + var removeIds = _.keys(toRemove); for (i = 0; i < removeIds.length; i++) { this.removeConnection(this.index[removeIds[i]]); } }; ConnectionPool.prototype.getAllHosts = function () { - return _v4.values(this.index).map(function (connection) { + return _.values(this.index).map(function (connection) { return connection.host; }); }; diff --git a/src/lib/connectors/angular.js b/src/lib/connectors/angular.js index 36f010101..3336c7462 100644 --- a/src/lib/connectors/angular.js +++ b/src/lib/connectors/angular.js @@ -6,7 +6,7 @@ */ module.exports = AngularConnector; -// var _ = require('../utils'); +var _ = require('../utils'); var ConnectionAbstract = require('../connection'); var ConnectionFault = require('../errors').ConnectionFault; @@ -20,7 +20,7 @@ function AngularConnector(host, config) { }]); } -_v4.inherits(AngularConnector, ConnectionAbstract); +_.inherits(AngularConnector, ConnectionAbstract); AngularConnector.prototype.request = function (params, cb) { var abort = this.$q.defer(); diff --git a/src/lib/connectors/browser_index.js b/src/lib/connectors/browser_index.js index 2a918cabe..8553ee8da 100644 --- a/src/lib/connectors/browser_index.js +++ b/src/lib/connectors/browser_index.js @@ -3,10 +3,10 @@ var opts = { jquery: require('./jquery'), angular: require('./angular') }; -// var _ = require('../utils'); +var _ = require('../utils'); // remove modules that have been ignored by browserify -_v4.each(opts, function (conn, name) { +_.each(opts, function (conn, name) { if (typeof conn !== 'function') { delete opts[name]; } diff --git a/src/lib/connectors/http.js b/src/lib/connectors/http.js index cc3fd4574..041b1bf5c 100644 --- a/src/lib/connectors/http.js +++ b/src/lib/connectors/http.js @@ -12,7 +12,7 @@ var handles = { http: require('http'), https: require('https') }; -// var _ = require('../utils'); +var _ = require('../utils'); var qs = require('querystring'); var KeepAliveAgent = require('./_keep_alive_agent'); var ConnectionAbstract = require('../connection'); @@ -31,12 +31,12 @@ function HttpConnector(host, config) { this.hand = handles[this.host.protocol]; if (!this.hand) { throw new TypeError('Invalid protocol "' + this.host.protocol + - '", expected one of ' + _v4.keys(handles).join(', ')); + '", expected one of ' + _.keys(handles).join(', ')); } this.useSsl = this.host.protocol === 'https'; - config = _v4.defaults(config || {}, { + config = _.defaults(config || {}, { keepAlive: true, minSockets: 10, // 10 makes sense but 11 actually keeps 10 sockets around @@ -46,14 +46,14 @@ function HttpConnector(host, config) { this.agent = config.createNodeAgent ? config.createNodeAgent(this, config) : this.createAgent(config); } -_v4.inherits(HttpConnector, ConnectionAbstract); +_.inherits(HttpConnector, ConnectionAbstract); -HttpConnector.prototype.onStatusSet = _v4.handler(function (status) { +HttpConnector.prototype.onStatusSet = _.handler(function (status) { if (status === 'closed') { var agent = this.agent; var toRemove = []; var collectSockets = function (sockets, host) { - _v4.each(sockets, function (s) { + _.each(sockets, function (s) { if (s) toRemove.push([host, s]); }); }; @@ -61,9 +61,9 @@ HttpConnector.prototype.onStatusSet = _v4.handler(function (status) { agent.minSockets = agent.maxSockets = 0; agent.requests = {}; - _v4.each(agent.sockets, collectSockets); - _v4.each(agent.freeSockets, collectSockets); - _v4.each(toRemove, function (args) { + _.each(agent.sockets, collectSockets); + _.each(agent.freeSockets, collectSockets); + _.each(toRemove, function (args) { var host = args[0], socket = args[1]; agent.removeSocket(socket, host); socket.destroy(); @@ -102,7 +102,7 @@ HttpConnector.prototype.makeAgentConfig = function (config) { }; if (this.useSsl) { - _v4.merge(agentConfig, this.host.ssl); + _.merge(agentConfig, this.host.ssl); } return agentConfig; @@ -147,7 +147,7 @@ HttpConnector.prototype.request = function (params, cb) { // general clean-up procedure to run after the request // completes, has an error, or is aborted. - var cleanUp = _v4.bind(function (err) { + var cleanUp = _.bind(function (err) { clearTimeout(timeoutId); request && request.removeAllListeners(); diff --git a/src/lib/connectors/jquery.js b/src/lib/connectors/jquery.js index 1f4e504ef..f935e0497 100644 --- a/src/lib/connectors/jquery.js +++ b/src/lib/connectors/jquery.js @@ -7,14 +7,14 @@ */ module.exports = JqueryConnector; -// var _ = require('../utils'); +var _ = require('../utils'); var ConnectionAbstract = require('../connection'); var ConnectionFault = require('../errors').ConnectionFault; function JqueryConnector(host, config) { ConnectionAbstract.call(this, host, config); } -_v4.inherits(JqueryConnector, ConnectionAbstract); +_.inherits(JqueryConnector, ConnectionAbstract); JqueryConnector.prototype.request = function (params, cb) { var ajax = { diff --git a/src/lib/connectors/xhr.js b/src/lib/connectors/xhr.js index dd3d56e1c..2b21539a6 100644 --- a/src/lib/connectors/xhr.js +++ b/src/lib/connectors/xhr.js @@ -7,7 +7,7 @@ module.exports = XhrConnector; /* jshint browser:true */ -// var _ = require('../utils'); +var _ = require('../utils'); var ConnectionAbstract = require('../connection'); var ConnectionFault = require('../errors').ConnectionFault; var asyncDefault = !(navigator && /PhantomJS/i.test(navigator.userAgent)); @@ -15,13 +15,13 @@ var asyncDefault = !(navigator && /PhantomJS/i.test(navigator.userAgent)); function XhrConnector(host, config) { ConnectionAbstract.call(this, host, config); } -_v4.inherits(XhrConnector, ConnectionAbstract); +_.inherits(XhrConnector, ConnectionAbstract); /** * Simply returns an XHR object cross browser * @type {Function} */ -var getXhr = _v4.noop; +var getXhr = _.noop; if (typeof XMLHttpRequest !== 'undefined') { // rewrite the getXhr method to always return the native implementation @@ -30,7 +30,7 @@ if (typeof XMLHttpRequest !== 'undefined') { }; } else { // find the first MS implementation available - getXhr = _v4(['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0']) + getXhr = _(['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0']) .map(function (appName) { /* jshint unused: false */ try { diff --git a/src/lib/errors.js b/src/lib/errors.js index a1d8ec521..47139354f 100644 --- a/src/lib/errors.js +++ b/src/lib/errors.js @@ -1,4 +1,4 @@ -// var _ = require('./utils'); +var _ = require('./utils'); var qs = require('querystring'); var errors = module.exports; @@ -21,21 +21,21 @@ function ErrorAbstract(msg, constructor, metadata) { } if (metadata) { - _v4.assign(this, metadata); + _.assign(this, metadata); this.toString = function () { return msg + ' :: ' + JSON.stringify(metadata); }; this.toJSON = function () { - return _v4.assign({ + return _.assign({ msg: msg }, metadata); }; } } errors._Abstract = ErrorAbstract; -_v4.inherits(ErrorAbstract, Error); +_.inherits(ErrorAbstract, Error); /** * Connection Error @@ -44,7 +44,7 @@ _v4.inherits(ErrorAbstract, Error); errors.ConnectionFault = function ConnectionFault(msg) { ErrorAbstract.call(this, msg || 'Connection Failure', errors.ConnectionFault); }; -_v4.inherits(errors.ConnectionFault, ErrorAbstract); +_.inherits(errors.ConnectionFault, ErrorAbstract); /** * No Living Connections @@ -53,7 +53,7 @@ _v4.inherits(errors.ConnectionFault, ErrorAbstract); errors.NoConnections = function NoConnections(msg) { ErrorAbstract.call(this, msg || 'No Living connections', errors.NoConnections); }; -_v4.inherits(errors.NoConnections, ErrorAbstract); +_.inherits(errors.NoConnections, ErrorAbstract); /** * Generic Error @@ -62,7 +62,7 @@ _v4.inherits(errors.NoConnections, ErrorAbstract); errors.Generic = function Generic(msg, metadata) { ErrorAbstract.call(this, msg || 'Generic Error', errors.Generic, metadata); }; -_v4.inherits(errors.Generic, ErrorAbstract); +_.inherits(errors.Generic, ErrorAbstract); /** * Request Timeout Error @@ -71,7 +71,7 @@ _v4.inherits(errors.Generic, ErrorAbstract); errors.RequestTimeout = function RequestTimeout(msg) { ErrorAbstract.call(this, msg || 'Request Timeout', errors.RequestTimeout); }; -_v4.inherits(errors.RequestTimeout, ErrorAbstract); +_.inherits(errors.RequestTimeout, ErrorAbstract); /** @@ -81,7 +81,7 @@ _v4.inherits(errors.RequestTimeout, ErrorAbstract); errors.Serialization = function Serialization(msg) { ErrorAbstract.call(this, msg || 'Unable to parse/serialize body', errors.Serialization); }; -_v4.inherits(errors.Serialization, ErrorAbstract); +_.inherits(errors.Serialization, ErrorAbstract); /** @@ -90,7 +90,7 @@ _v4.inherits(errors.Serialization, ErrorAbstract); errors.RequestTypeError = function RequestTypeError(feature) { ErrorAbstract.call(this, 'Cross-domain AJAX requests ' + feature + ' are not supported', errors.RequestTypeError); }; -_v4.inherits(errors.RequestTypeError, ErrorAbstract); +_.inherits(errors.RequestTypeError, ErrorAbstract); var statusCodes = [ [300, 'Multiple Choices'], @@ -137,20 +137,20 @@ var statusCodes = [ [510, 'Not Extended'] ]; -_v4.each(statusCodes, function createStatusCodeError(tuple) { +_.each(statusCodes, function createStatusCodeError(tuple) { var status = tuple[0]; var names = tuple[1]; var allNames = [].concat(names, status); var primaryName = allNames[0]; - var className = _v4.studlyCase(primaryName); - allNames = _v4.uniq(allNames.concat(className)); + var className = _.studlyCase(primaryName); + allNames = _.uniq(allNames.concat(className)); function StatusCodeError(msg, metadata) { this.status = status; this.displayName = className; var esErrObject = null; - if (_v4.isPlainObject(msg)) { + if (_.isPlainObject(msg)) { esErrObject = msg; msg = null; } @@ -168,8 +168,8 @@ _v4.each(statusCodes, function createStatusCodeError(tuple) { memo += '[' + cause.type + '] ' + cause.reason; - var extraData = _v4.omit(cause, ['type', 'reason']); - if (_v4.size(extraData)) { + var extraData = _.omit(cause, ['type', 'reason']); + if (_.size(extraData)) { memo += ', with { ' + qs.stringify(extraData, ' ', '=', { encodeURIComponent: function (v) { return String(v).split('\n').join('\\n'); @@ -188,7 +188,7 @@ _v4.each(statusCodes, function createStatusCodeError(tuple) { ErrorAbstract.call(this, msg || primaryName, StatusCodeError, metadata); return this; } - _v4.inherits(StatusCodeError, ErrorAbstract); + _.inherits(StatusCodeError, ErrorAbstract); allNames.forEach(function (name) { errors[name] = StatusCodeError; diff --git a/src/lib/host.js b/src/lib/host.js index dfa37c332..08e6fa740 100644 --- a/src/lib/host.js +++ b/src/lib/host.js @@ -6,7 +6,7 @@ module.exports = Host; var url = require('url'); var qs = require('querystring'); -// var _ = require('./utils'); +var _ = require('./utils'); var startsWithProtocolRE = /^([a-z]+:)?\/\//; var defaultProto = 'http:'; @@ -46,7 +46,7 @@ Host.defaultPorts = { }; function Host(config, globalConfig) { - config = _v4.clone(config || {}); + config = _.clone(config || {}); globalConfig = globalConfig || {}; // defaults @@ -58,7 +58,7 @@ function Host(config, globalConfig) { this.headers = null; this.suggestCompression = !!globalConfig.suggestCompression; - this.ssl = _v4.defaults({}, config.ssl || {}, globalConfig.ssl || {}, sslDefaults); + this.ssl = _.defaults({}, config.ssl || {}, globalConfig.ssl || {}, sslDefaults); if (typeof config === 'string') { var firstColon = config.indexOf(':'); @@ -69,7 +69,7 @@ function Host(config, globalConfig) { if ((noSlash || portNoPath || portWithPath) && !startsWithProtocolRE.test(config)) { config = defaultProto + '//' + config; } - config = _v4.pick(url.parse(config, false, true), urlParseFields); + config = _.pick(url.parse(config, false, true), urlParseFields); // default logic for the port is to use 9200 for the default. When a string is specified though, // we will use the default from the protocol of the string. if (!config.port) { @@ -83,9 +83,9 @@ function Host(config, globalConfig) { } } - if (_v4.isObject(config)) { + if (_.isObject(config)) { // move hostname/portname to host/port semi-intelligently. - _v4.each(simplify, function (to) { + _.each(simplify, function (to) { var from = to + 'name'; if (config[from] && config[to]) { if (config[to].indexOf(config[from]) === 0) { @@ -106,20 +106,20 @@ function Host(config, globalConfig) { delete config.auth; } - _v4.forOwn(config, _v4.bind(function (val, prop) { - if (val != null) this[prop] = _v4.clone(val); + _.forOwn(config, _.bind(function (val, prop) { + if (val != null) this[prop] = _.clone(val); }, this)); // make sure the query string is parsed if (this.query === null) { // majority case this.query = {}; - } else if (!_v4.isPlainObject(this.query)) { + } else if (!_.isPlainObject(this.query)) { this.query = qs.parse(this.query); } // make sure that the port is a number - if (_v4.isNumeric(this.port)) { + if (_.isNumeric(this.port)) { this.port = parseInt(this.port, 10); } else { this.port = 9200; @@ -177,10 +177,10 @@ function objectPropertyGetter(prop, preOverride) { } if (overrides) { - obj = _v4.assign({}, obj, overrides); + obj = _.assign({}, obj, overrides); } - return _v4.size(obj) ? obj : null; + return _.size(obj) ? obj : null; }; } @@ -189,7 +189,7 @@ Host.prototype.getHeaders = objectPropertyGetter('headers', function (overrides) return overrides; } - return _v4.defaults(overrides || {}, { + return _.defaults(overrides || {}, { 'Accept-Encoding': 'gzip,deflate' }); }); diff --git a/src/lib/log.js b/src/lib/log.js index 2ebf9e55a..a463bccf0 100644 --- a/src/lib/log.js +++ b/src/lib/log.js @@ -1,4 +1,4 @@ -// var _ = require('./utils'); +var _ = require('./utils'); var url = require('url'); var EventEmitter = require('events').EventEmitter; @@ -24,13 +24,13 @@ function Log(config) { var i; var outputs; - if (_v4.isArrayOfStrings(config.log)) { + if (_.isArrayOfStrings(config.log)) { outputs = [{ levels: config.log }]; } else { - outputs = _v4.createArray(config.log, function (val) { - if (_v4.isPlainObject(val)) { + outputs = _.createArray(config.log, function (val) { + if (_.isPlainObject(val)) { return val; } if (typeof val === 'string') { @@ -50,7 +50,7 @@ function Log(config) { this.addOutput(outputs[i]); } } -_v4.inherits(Log, EventEmitter); +_.inherits(Log, EventEmitter); Log.loggers = require('./loggers'); @@ -151,14 +151,14 @@ Log.levels = [ Log.parseLevels = function (input) { switch (typeof input) { case 'string': - var i = _v4.indexOf(Log.levels, input); + var i = _.indexOf(Log.levels, input); if (i >= 0) { return Log.levels.slice(0, i + 1); } /* fall through */ case 'object': - if (_v4.isArray(input)) { - var valid = _v4.intersection(input, Log.levels); + if (_.isArray(input)) { + var valid = _.intersection(input, Log.levels); if (valid.length === input.length) { return valid; } @@ -176,13 +176,13 @@ Log.parseLevels = function (input) { * @method join * @static * @private - * @param {*} arrayish - An array like object that can be itterated by _v4.each + * @param {*} arrayish - An array like object that can be itterated by _.each * @return {String} - The final string. */ Log.join = function (arrayish) { - return _v4.map(arrayish, function (item) { - if (_v4.isPlainObject(item)) { - return _v4.inspect(item) + '\n'; + return _.map(arrayish, function (item) { + if (_.isPlainObject(item)) { + return _.inspect(item) + '\n'; } else { return item.toString(); } @@ -209,7 +209,7 @@ Log.prototype.addOutput = function (config) { config.levels = Log.parseLevels(config.levels || config.level || 'warning'); delete config.level; - var Logger = _v4.funcEnum(config, 'type', Log.loggers, process.browser ? 'console' : 'stdio'); + var Logger = _.funcEnum(config, 'type', Log.loggers, process.browser ? 'console' : 'stdio'); return new Logger(this, config); }; @@ -289,7 +289,7 @@ Log.normalizeTraceArgs = function (method, requestUrl, body, responseBody, respo if (typeof requestUrl === 'string') { requestUrl = url.parse(requestUrl, true, true); } else { - requestUrl = _v4.clone(requestUrl); + requestUrl = _.clone(requestUrl); if (requestUrl.path) { requestUrl.query = url.parse(requestUrl.path, true, false).query; } diff --git a/src/lib/logger.js b/src/lib/logger.js index fc3283b48..5732d7fed 100644 --- a/src/lib/logger.js +++ b/src/lib/logger.js @@ -1,4 +1,4 @@ -// var _ = require('./utils'); +var _ = require('./utils'); /** * Abstract class providing common functionality to loggers @@ -9,7 +9,7 @@ function LoggerAbstract(log, config) { this.log = log; this.listeningLevels = []; - _v4.makeBoundMethods(this); + _.makeBoundMethods(this); // when the log closes, remove our event listeners this.log.once('closing', this.bound.cleanUpListeners); @@ -37,7 +37,7 @@ LoggerAbstract.prototype.timestamp = function () { }; function indent(text, spaces) { - var space = _v4.repeat(' ', spaces || 2); + var space = _.repeat(' ', spaces || 2); return (text || '').split(/\r?\n/).map(function (line) { return space + line; }).join('\n'); @@ -64,8 +64,8 @@ LoggerAbstract.prototype.setupListeners = function (levels) { this.listeningLevels = []; - _v4.each(levels, _v4.bind(function (level) { - var fnName = 'on' + _v4.ucfirst(level); + _.each(levels, _.bind(function (level) { + var fnName = 'on' + _.ucfirst(level); if (this.bound[fnName]) { this.listeningLevels.push(level); this.log.on(level, this.bound[fnName]); @@ -82,9 +82,9 @@ LoggerAbstract.prototype.setupListeners = function (levels) { * @private * @return {undefined} */ -LoggerAbstract.prototype.cleanUpListeners = _v4.handler(function () { - _v4.each(this.listeningLevels, _v4.bind(function (level) { - this.log.removeListener(level, this.bound['on' + _v4.ucfirst(level)]); +LoggerAbstract.prototype.cleanUpListeners = _.handler(function () { + _.each(this.listeningLevels, _.bind(function (level) { + this.log.removeListener(level, this.bound['on' + _.ucfirst(level)]); }, this)); }); @@ -96,7 +96,7 @@ LoggerAbstract.prototype.cleanUpListeners = _v4.handler(function () { * @param {Error} e - The Error object to log * @return {undefined} */ -LoggerAbstract.prototype.onError = _v4.handler(function (e) { +LoggerAbstract.prototype.onError = _.handler(function (e) { this.write((e.name === 'Error' ? 'ERROR' : e.name), e.stack); }); @@ -108,7 +108,7 @@ LoggerAbstract.prototype.onError = _v4.handler(function (e) { * @param {String} msg - The message to be logged * @return {undefined} */ -LoggerAbstract.prototype.onWarning = _v4.handler(function (msg) { +LoggerAbstract.prototype.onWarning = _.handler(function (msg) { this.write('WARNING', msg); }); @@ -120,7 +120,7 @@ LoggerAbstract.prototype.onWarning = _v4.handler(function (msg) { * @param {String} msg - The message to be logged * @return {undefined} */ -LoggerAbstract.prototype.onInfo = _v4.handler(function (msg) { +LoggerAbstract.prototype.onInfo = _.handler(function (msg) { this.write('INFO', msg); }); @@ -132,7 +132,7 @@ LoggerAbstract.prototype.onInfo = _v4.handler(function (msg) { * @param {String} msg - The message to be logged * @return {undefined} */ -LoggerAbstract.prototype.onDebug = _v4.handler(function (msg) { +LoggerAbstract.prototype.onDebug = _.handler(function (msg) { this.write('DEBUG', msg); }); @@ -144,7 +144,7 @@ LoggerAbstract.prototype.onDebug = _v4.handler(function (msg) { * @param {String} msg - The message to be logged * @return {undefined} */ -LoggerAbstract.prototype.onTrace = _v4.handler(function (requestDetails) { +LoggerAbstract.prototype.onTrace = _.handler(function (requestDetails) { this.write('TRACE', this._formatTraceMessage(requestDetails)); }); diff --git a/src/lib/loggers/console.js b/src/lib/loggers/console.js index 75a7eff03..d5ec9771f 100644 --- a/src/lib/loggers/console.js +++ b/src/lib/loggers/console.js @@ -13,15 +13,15 @@ module.exports = Console; var LoggerAbstract = require('../logger'); -// var _ = require('../utils'); +var _ = require('../utils'); function Console(log, config) { LoggerAbstract.call(this, log, config); // config/state - this.color = _v4.has(config, 'color') ? !!config.color : true; + this.color = _.has(config, 'color') ? !!config.color : true; } -_v4.inherits(Console, LoggerAbstract); +_.inherits(Console, LoggerAbstract); /** * Override the LoggerAbstract's setup listeners to do a little extra setup @@ -47,7 +47,7 @@ Console.prototype.write = function (label, message, to) { * @param {Error} e - The Error object to log * @return {undefined} */ -Console.prototype.onError = _v4.handler(function (e) { +Console.prototype.onError = _.handler(function (e) { var to = console.error ? 'error' : 'log'; this.write(e.name === 'Error' ? 'ERROR' : e.name, e.stack || e.message, to); }); @@ -60,7 +60,7 @@ Console.prototype.onError = _v4.handler(function (e) { * @param {String} msg - The message to be logged * @return {undefined} */ -Console.prototype.onWarning = _v4.handler(function (msg) { +Console.prototype.onWarning = _.handler(function (msg) { this.write('WARNING', msg, console.warn ? 'warn' : 'log'); }); @@ -72,7 +72,7 @@ Console.prototype.onWarning = _v4.handler(function (msg) { * @param {String} msg - The message to be logged * @return {undefined} */ -Console.prototype.onInfo = _v4.handler(function (msg) { +Console.prototype.onInfo = _.handler(function (msg) { this.write('INFO', msg, console.info ? 'info' : 'log'); }); @@ -84,7 +84,7 @@ Console.prototype.onInfo = _v4.handler(function (msg) { * @param {String} msg - The message to be logged * @return {undefined} */ -Console.prototype.onDebug = _v4.handler(function (msg) { +Console.prototype.onDebug = _.handler(function (msg) { this.write('DEBUG', msg, console.debug ? 'debug' : 'log'); }); /** @@ -94,6 +94,6 @@ Console.prototype.onDebug = _v4.handler(function (msg) { * @private * @return {undefined} */ -Console.prototype.onTrace = _v4.handler(function (msg) { +Console.prototype.onTrace = _.handler(function (msg) { this.write('TRACE', this._formatTraceMessage(msg), 'log'); }); diff --git a/src/lib/loggers/file.js b/src/lib/loggers/file.js index 35bf273a4..4b4357f96 100755 --- a/src/lib/loggers/file.js +++ b/src/lib/loggers/file.js @@ -12,7 +12,7 @@ module.exports = File; var StreamLogger = require('./stream'); -// var _ = require('../utils'); +var _ = require('../utils'); var fs = require('fs'); function File(log, config) { @@ -29,10 +29,10 @@ function File(log, config) { StreamLogger.call(this, log, config); } -_v4.inherits(File, StreamLogger); +_.inherits(File, StreamLogger); -File.prototype.onProcessExit = _v4.handler(function () { - var toWrite = _v4.getUnwrittenFromStream(this.stream); +File.prototype.onProcessExit = _.handler(function () { + var toWrite = _.getUnwrittenFromStream(this.stream); if (toWrite) { fs.appendFileSync(this.path, toWrite); } diff --git a/src/lib/loggers/stdio.js b/src/lib/loggers/stdio.js index 0caa7454f..1ba868d33 100755 --- a/src/lib/loggers/stdio.js +++ b/src/lib/loggers/stdio.js @@ -17,7 +17,7 @@ var chalk = require('chalk'); chalk.enabled = true; var LoggerAbstract = require('../logger'); -// var _ = require('../utils'); +var _ = require('../utils'); var defaultColors = { error: chalk.red.bold, @@ -31,12 +31,12 @@ function Stdio(log, config) { LoggerAbstract.call(this, log, config); // config/state - this.color = !!(_v4.has(config, 'color') ? config.color : chalk.supportsColor); + this.color = !!(_.has(config, 'color') ? config.color : chalk.supportsColor); - this.colors = _v4.defaults(config.colors || {}, defaultColors); + this.colors = _.defaults(config.colors || {}, defaultColors); } -_v4.inherits(Stdio, LoggerAbstract); +_.inherits(Stdio, LoggerAbstract); /** * Sends output to a stream, does some formatting first @@ -65,7 +65,7 @@ Stdio.prototype.write = function (label, message, to, colorize) { * @param {Error} e - The Error object to log * @return {undefined} */ -Stdio.prototype.onError = _v4.handler(function (e) { +Stdio.prototype.onError = _.handler(function (e) { this.write(e.name === 'Error' ? 'ERROR' : e.name, e.stack, process.stderr, this.colors.error); }); @@ -77,7 +77,7 @@ Stdio.prototype.onError = _v4.handler(function (e) { * @param {String} msg - The message to be logged * @return {undefined} */ -Stdio.prototype.onWarning = _v4.handler(function (msg) { +Stdio.prototype.onWarning = _.handler(function (msg) { this.write('WARNING', msg, process.stderr, this.colors.warning); }); @@ -89,7 +89,7 @@ Stdio.prototype.onWarning = _v4.handler(function (msg) { * @param {String} msg - The message to be logged * @return {undefined} */ -Stdio.prototype.onInfo = _v4.handler(function (msg) { +Stdio.prototype.onInfo = _.handler(function (msg) { this.write('INFO', msg, process.stdout, this.colors.info); }); @@ -101,7 +101,7 @@ Stdio.prototype.onInfo = _v4.handler(function (msg) { * @param {String} msg - The message to be logged * @return {undefined} */ -Stdio.prototype.onDebug = _v4.handler(function (msg) { +Stdio.prototype.onDebug = _.handler(function (msg) { this.write('DEBUG', msg, process.stdout, this.colors.debug); }); @@ -112,6 +112,6 @@ Stdio.prototype.onDebug = _v4.handler(function (msg) { * @private * @return {undefined} */ -Stdio.prototype.onTrace = _v4.handler(function (message) { +Stdio.prototype.onTrace = _.handler(function (message) { this.write('TRACE', this._formatTraceMessage(message), process.stdout, this.colors.trace); }); diff --git a/src/lib/loggers/stream.js b/src/lib/loggers/stream.js index 55f2d10d9..235440d15 100755 --- a/src/lib/loggers/stream.js +++ b/src/lib/loggers/stream.js @@ -13,7 +13,7 @@ module.exports = Stream; var LoggerAbstract = require('../logger'); -// var _ = require('../utils'); +var _ = require('../utils'); function Stream(log, config) { LoggerAbstract.call(this, log, config); @@ -26,17 +26,17 @@ function Stream(log, config) { process.once('exit', this.bound.onProcessExit); } -_v4.inherits(Stream, LoggerAbstract); +_.inherits(Stream, LoggerAbstract); -Stream.prototype.cleanUpListeners = _v4.handler(function () { +Stream.prototype.cleanUpListeners = _.handler(function () { process.removeListener('exit', this.bound.onProcessExit); LoggerAbstract.prototype.cleanUpListeners.call(this); }); // flush the write buffer to stderr synchronously -Stream.prototype.onProcessExit = _v4.handler(function () { +Stream.prototype.onProcessExit = _.handler(function () { // process is dying, lets manually flush the buffer synchronously to stderr. - var unwritten = _v4.getUnwrittenFromStream(this.stream); + var unwritten = _.getUnwrittenFromStream(this.stream); if (unwritten) { console.error('Log stream did not get to finish writing. Flushing to stderr'); console.error(unwritten); diff --git a/src/lib/loggers/tracer.js b/src/lib/loggers/tracer.js index a3b85fdd2..c79b48c5e 100755 --- a/src/lib/loggers/tracer.js +++ b/src/lib/loggers/tracer.js @@ -14,7 +14,7 @@ module.exports = Tracer; var StreamLogger = require('./stream'); var fs = require('fs'); -// var _ = require('../utils'); +var _ = require('../utils'); var url = require('url'); function Tracer(log, config) { @@ -29,18 +29,18 @@ function Tracer(log, config) { StreamLogger.call(this, log, config); } -_v4.inherits(Tracer, StreamLogger); +_.inherits(Tracer, StreamLogger); var usefulUrlFields = ['protocol', 'slashes', 'port', 'hostname', 'pathname', 'query']; Tracer.prototype._formatTraceMessage = function (req) { - var reqUrl = _v4.pick(url.parse(req.url, true, false), usefulUrlFields); + var reqUrl = _.pick(url.parse(req.url, true, false), usefulUrlFields); - var originalHost = url.format(_v4.pick(reqUrl, 'protocol', 'hostname', 'port')); + var originalHost = url.format(_.pick(reqUrl, 'protocol', 'hostname', 'port')); reqUrl.port = this.curlPort; reqUrl.hostname = this.curlHost; - reqUrl.query = _v4.defaults(reqUrl.query || {}, { pretty: true }); + reqUrl.query = _.defaults(reqUrl.query || {}, { pretty: true }); /* jshint quotmark: double */ var curlCall = @@ -56,7 +56,7 @@ Tracer.prototype._formatTraceMessage = function (req) { }; function comment(str) { - return _v4.map(str.split(/\r?\n/g), function (line) { + return _.map(str.split(/\r?\n/g), function (line) { return '# ' + line; }).join('\n'); } diff --git a/src/lib/nodes_to_host.js b/src/lib/nodes_to_host.js index 3c63d81d0..4e6a01de3 100644 --- a/src/lib/nodes_to_host.js +++ b/src/lib/nodes_to_host.js @@ -1,10 +1,10 @@ -// var _ = require('./utils'); +var _ = require('./utils'); var extractHostPartsRE1x = /\[\/*([^:]+):(\d+)\]/; function makeNodeParser(hostProp) { return function (nodes) { - return _v4.transform(nodes, function (hosts, node, id) { + return _.transform(nodes, function (hosts, node, id) { var address = node[hostProp] if (!address) return; diff --git a/src/lib/serializers/angular.js b/src/lib/serializers/angular.js index 290a1e7a4..1548badc1 100644 --- a/src/lib/serializers/angular.js +++ b/src/lib/serializers/angular.js @@ -1,9 +1,9 @@ /* global angular */ -// var _ = require('../utils'); +var _ = require('../utils'); var JsonSerializer = require('../serializers/json'); function AngularSerializer() {} -_v4.inherits(AngularSerializer, JsonSerializer); +_.inherits(AngularSerializer, JsonSerializer); // mimic the JsonSerializer's encode method, but use angular's toJson instead AngularSerializer.prototype.encode = function (val) { diff --git a/src/lib/serializers/json.js b/src/lib/serializers/json.js index c8421123e..091806784 100755 --- a/src/lib/serializers/json.js +++ b/src/lib/serializers/json.js @@ -4,7 +4,7 @@ */ module.exports = Json; -// var _ = require('../utils'); +var _ = require('../utils'); function Json() {} @@ -46,7 +46,7 @@ Json.prototype.deserialize = function (str) { Json.prototype.bulkBody = function (val) { var body = '', i; - if (_v4.isArray(val)) { + if (_.isArray(val)) { for (i = 0; i < val.length; i++) { body += this.serialize(val[i]) + '\n'; } diff --git a/src/lib/transport.js b/src/lib/transport.js index 4561bb603..452782372 100644 --- a/src/lib/transport.js +++ b/src/lib/transport.js @@ -4,7 +4,7 @@ */ module.exports = Transport; -// var _ = require('./utils'); +var _ = require('./utils'); var errors = require('./errors'); var Host = require('./host'); var Promise = require('promise/lib/es6-extensions'); @@ -19,15 +19,15 @@ function Transport(config) { config.log = self.log = new LogClass(config); // setup the connection pool - var ConnectionPool = _v4.funcEnum(config, 'connectionPool', Transport.connectionPools, 'main'); + var ConnectionPool = _.funcEnum(config, 'connectionPool', Transport.connectionPools, 'main'); self.connectionPool = new ConnectionPool(config); // setup the serializer - var Serializer = _v4.funcEnum(config, 'serializer', Transport.serializers, 'json'); + var Serializer = _.funcEnum(config, 'serializer', Transport.serializers, 'json'); self.serializer = new Serializer(config); // setup the nodesToHostCallback - self.nodesToHostCallback = _v4.funcEnum(config, 'nodesToHostCallback', Transport.nodesToHostCallbacks, 'main'); + self.nodesToHostCallback = _.funcEnum(config, 'nodesToHostCallback', Transport.nodesToHostCallbacks, 'main'); // setup max retries self.maxRetries = config.hasOwnProperty('maxRetries') ? config.maxRetries : 3; @@ -50,8 +50,8 @@ function Transport(config) { } if (config.hosts) { - var hostsConfig = _v4.createArray(config.hosts, function (val) { - if (_v4.isPlainObject(val) || _v4.isString(val) || val instanceof Host) { + var hostsConfig = _.createArray(config.hosts, function (val) { + if (_.isPlainObject(val) || _.isString(val) || val instanceof Host) { return val; } }); @@ -62,7 +62,7 @@ function Transport(config) { } if (randomizeHosts) { - hostsConfig = _v4.shuffle(hostsConfig); + hostsConfig = _.shuffle(hostsConfig); } self.setHosts(hostsConfig); @@ -139,7 +139,7 @@ Transport.prototype.request = function (params, cb) { var defer; // the defer object, will be set when we are using promises. var body = params.body; - var headers = !params.headers ? {} : _v4.transform(params.headers, function (headers, val, name) { + var headers = !params.headers ? {} : _.transform(params.headers, function (headers, val, name) { headers[String(name).toLowerCase()] = val; }); @@ -161,7 +161,7 @@ Transport.prototype.request = function (params, cb) { } if (body && params.method === 'GET') { - _v4.nextTick(respond, new TypeError('Body can not be sent with method "GET"')); + _.nextTick(respond, new TypeError('Body can not be sent with method "GET"')); return ret; } @@ -274,10 +274,10 @@ Transport.prototype.request = function (params, cb) { if ( (!err || err instanceof errors.Serialization) && (status < 200 || status >= 300) - && (!params.ignore || !_v4.includes(params.ignore, status)) + && (!params.ignore || !_.includes(params.ignore, status)) ) { - var errorMetadata = _v4.pick(params.req, ['path', 'query', 'body']); + var errorMetadata = _.pick(params.req, ['path', 'query', 'body']); errorMetadata.statusCode = status; errorMetadata.response = body; @@ -361,7 +361,7 @@ Transport.prototype._timeout = function (cb, delay) { if (cb) { // set the timer id = setTimeout(function () { - _v4.pull(timers, id); + _.pull(timers, id); cb(); }, delay); @@ -392,7 +392,7 @@ Transport.prototype.sniff = function (cb) { var sniffedNodesProtocol = this.sniffedNodesProtocol; // make cb a function if it isn't - cb = typeof cb === 'function' ? cb : _v4.noop; + cb = typeof cb === 'function' ? cb : _.noop; this.request({ path: this.sniffEndpoint, @@ -409,7 +409,7 @@ Transport.prototype.sniff = function (cb) { return; } - _v4.forEach(hostsConfigs, function (hostConfig) { + _.forEach(hostsConfigs, function (hostConfig) { if (sniffedNodesProtocol) hostConfig.protocol = sniffedNodesProtocol; }); @@ -427,7 +427,7 @@ Transport.prototype.sniff = function (cb) { */ Transport.prototype.setHosts = function (hostsConfigs) { var globalConfig = this._config; - this.connectionPool.setHosts(_v4.map(hostsConfigs, function (conf) { + this.connectionPool.setHosts(_.map(hostsConfigs, function (conf) { return (conf instanceof Host) ? conf : new Host(conf, globalConfig); })); }; @@ -439,7 +439,7 @@ Transport.prototype.setHosts = function (hostsConfigs) { Transport.prototype.close = function () { this.log.close(); this.closed = true; - _v4.each(this._timers, clearTimeout); + _.each(this._timers, clearTimeout); this._timers = null; this.connectionPool.close(); }; diff --git a/src/lib/transport/find_common_protocol.js b/src/lib/transport/find_common_protocol.js index 4df4213fd..6b60907fb 100644 --- a/src/lib/transport/find_common_protocol.js +++ b/src/lib/transport/find_common_protocol.js @@ -1,4 +1,4 @@ -var isEmpty = require('lodash-migrate').isEmpty; +var isEmpty = require('lodash').isEmpty; module.exports = function (hosts) { if (isEmpty(hosts)) return false; diff --git a/src/lib/transport/sniff_on_connection_fault.js b/src/lib/transport/sniff_on_connection_fault.js index cc45fa249..e7bd8c089 100644 --- a/src/lib/transport/sniff_on_connection_fault.js +++ b/src/lib/transport/sniff_on_connection_fault.js @@ -1,4 +1,4 @@ -// var _ = require('../utils'); +var _ = require('../utils'); /** @@ -25,7 +25,7 @@ module.exports = function setupSniffOnConnectionFault(transport) { // create a function that will count down to a // point n milliseconds into the future var countdownTo = function (ms) { - var start = _v4.now(); + var start = _.now(); return function () { return start - ms; }; diff --git a/src/lib/utils.js b/src/lib/utils.js index 25167bab1..40cf01021 100644 --- a/src/lib/utils.js +++ b/src/lib/utils.js @@ -1,26 +1,23 @@ var path = require('path'); -// var _ = require('lodash'); -// require('../../stub') var nodeUtils = require('util'); /** - * Custom _v4 library, basically a modified version of [lodash](http://lodash.com/docs) + - * [node._v4](http://nodejs.org/api/util.html#util_util) that doesn't use mixins to prevent + * Custom _ library, basically a modified version of [lodash](http://lodash.com/docs) + + * [node._](http://nodejs.org/api/util.html#util_util) that doesn't use mixins to prevent * confusion when requiring lodash itself. * - * @class _v4 + * @class _ * @static */ -_v4.assign(_v4, nodeUtils); -// _v4 = _v4; +var _ = require('lodash').assign({}, require('lodash'), nodeUtils); /** * Link to [path.join](http://nodejs.org/api/path.html#path_path_join_path1_path2) * - * @method _v4.joinPath + * @method _.joinPath * @type {function} */ -_v4.joinPath = path.join; +_.joinPath = path.join; /** * Recursively merge two objects, walking into each object and concating arrays. If both to and from have a value at a @@ -32,18 +29,18 @@ _v4.joinPath = path.join; * @param {Object} from - Object to pull changed from * @return {Object} - returns the modified to value */ -_v4.deepMerge = function (to, from) { - _v4.each(from, function (fromVal, key) { +_.deepMerge = function (to, from) { + _.each(from, function (fromVal, key) { switch (typeof to[key]) { case 'undefined': to[key] = from[key]; break; case 'object': - if (_v4.isArray(to[key]) && _v4.isArray(from[key])) { + if (_.isArray(to[key]) && _.isArray(from[key])) { to[key] = to[key].concat(from[key]); } - else if (_v4.isPlainObject(to[key]) && _v4.isPlainObject(from[key])) { - _v4.deepMerge(to[key], from[key]); + else if (_.isPlainObject(to[key]) && _.isPlainObject(from[key])) { + _.deepMerge(to[key], from[key]); } } }); @@ -57,7 +54,7 @@ _v4.deepMerge = function (to, from) { * @param {Array} arr - An array to check * @return {Boolean} */ -_v4.each([ +_.each([ 'String', 'Object', 'PlainObject', @@ -66,11 +63,11 @@ _v4.each([ 'Function', 'RegExp' ], function (type) { - var check = _v4['is' + type]; + var check = _['is' + type]; - _v4['isArrayOf' + type + 's'] = function (arr) { + _['isArrayOf' + type + 's'] = function (arr) { // quick shallow check of arrays - return _v4.isArray(arr) && _v4.every(arr.slice(0, 10), check); + return _.isArray(arr) && _.every(arr.slice(0, 10), check); }; }); @@ -82,7 +79,7 @@ _v4.each([ * @param {string} word - The word to transform * @return {string} */ -_v4.ucfirst = function (word) { +_.ucfirst = function (word) { return word[0].toUpperCase() + word.substring(1).toLowerCase(); }; @@ -143,7 +140,7 @@ function adjustWordCase(firstWordCap, otherWordsCap, sep) { * @param {String} string * @return {String} */ -_v4.studlyCase = adjustWordCase(true, true, ''); +_.studlyCase = adjustWordCase(true, true, ''); /** * Transform a string into camelCase @@ -152,7 +149,7 @@ _v4.studlyCase = adjustWordCase(true, true, ''); * @param {String} string * @return {String} */ -_v4.camelCase = adjustWordCase(false, true, ''); +_.camelCase = adjustWordCase(false, true, ''); /** * Transform a string into snakeCase @@ -161,7 +158,7 @@ _v4.camelCase = adjustWordCase(false, true, ''); * @param {String} string * @return {String} */ -_v4.snakeCase = adjustWordCase(false, false, '_'); +_.snakeCase = adjustWordCase(false, false, '_'); /** * Lower-case a string, and return an empty string if any is not a string @@ -169,7 +166,7 @@ _v4.snakeCase = adjustWordCase(false, false, '_'); * @param any {*} - Something or nothing * @returns {string} */ -_v4.toLowerString = function (any) { +_.toLowerString = function (any) { if (any) { if (typeof any !== 'string') { any = any.toString(); @@ -186,7 +183,7 @@ _v4.toLowerString = function (any) { * @param any {*} - Something or nothing * @returns {string} */ -_v4.toUpperString = function (any) { +_.toUpperString = function (any) { if (any) { if (typeof any !== 'string') { any = any.toString(); @@ -204,7 +201,7 @@ _v4.toUpperString = function (any) { * @param {*} val * @return {Boolean} */ -_v4.isNumeric = function (val) { +_.isNumeric = function (val) { return typeof val !== 'object' && val - parseFloat(val) >= 0; }; @@ -218,7 +215,7 @@ var intervalRE = /^(\d+(?:\.\d+)?)(M|w|d|h|m|s|y|ms)$/; * @param {String} val * @return {Boolean} */ -_v4.isInterval = function (val) { +_.isInterval = function (val) { return !!(val.match && val.match(intervalRE)); }; @@ -231,7 +228,7 @@ _v4.isInterval = function (val) { * @param {Number} times - Times the string should be repeated * @return {String} */ -_v4.repeat = function (what, times) { +_.repeat = function (what, times) { return (new Array(times + 1)).join(what); }; @@ -244,7 +241,7 @@ _v4.repeat = function (what, times) { * @param [sliceIndex=0] {Integer} - The index that args should be sliced at, before feeding args to func * @returns {*} - the return value of func */ -_v4.applyArgs = function (func, context, args, sliceIndex) { +_.applyArgs = function (func, context, args, sliceIndex) { sliceIndex = sliceIndex || 0; switch (args.length - sliceIndex) { case 0: @@ -270,9 +267,9 @@ _v4.applyArgs = function (func, context, args, sliceIndex) { * when it is called. * @return {[type]} [description] */ -_v4.nextTick = function (cb) { +_.nextTick = function (cb) { // bind the function and schedule it - process.nextTick(_v4.bindKey(_v4, 'applyArgs', cb, null, arguments, 1)); + process.nextTick(_.bindKey(_, 'applyArgs', cb, null, arguments, 1)); }; /** @@ -280,7 +277,7 @@ _v4.nextTick = function (cb) { * flagging it to be bound to the object at object creation when "makeBoundMethods" is called * * ``` - * ClassName.prototype.methodName = _v4.handler(function () { + * ClassName.prototype.methodName = _.handler(function () { * // this will always be bound when called via classInstance.bound.methodName * this === classInstance * }); @@ -290,11 +287,11 @@ _v4.nextTick = function (cb) { * @param {Function} func - The method that is being defined * @return {Function} */ -_v4.handler = function (func) { +_.handler = function (func) { func._provideBound = true; return func; }; -_v4.scheduled = _v4.handler; +_.scheduled = _.handler; /** * Creates an "bound" property on an object, which all or a subset of methods from @@ -305,24 +302,24 @@ _v4.scheduled = _v4.handler; * onEvent: function () {} * }; * - * _v4.makeBoundMethods(obj); + * _.makeBoundMethods(obj); * * obj.bound.onEvent() // is bound to obj, and can safely be used as an event handler. * ``` * * @param {Object} obj - The object to bind the methods to */ -_v4.makeBoundMethods = function (obj) { +_.makeBoundMethods = function (obj) { obj.bound = {}; for (var prop in obj) { // dearest maintainer, we want to look through the prototype if (typeof obj[prop] === 'function' && obj[prop]._provideBound === true) { - obj.bound[prop] = _v4.bind(obj[prop], obj); + obj.bound[prop] = _.bind(obj[prop], obj); } } }; -_v4.noop = function () {}; +_.noop = function () {}; /** * Implements the standard "string or constructor" check that I was copy/pasting everywhere @@ -330,7 +327,7 @@ _v4.noop = function () {}; * @param {Object} opts - a map of the options * @return {Function|undefined} - If a valid option was specified, then the constructor is returned */ -_v4.funcEnum = function (config, name, opts, def) { +_.funcEnum = function (config, name, opts, def) { var val = config[name]; switch (typeof val) { case 'undefined': @@ -344,14 +341,14 @@ _v4.funcEnum = function (config, name, opts, def) { /* falls through */ default: var err = 'Invalid ' + name + ' "' + val + '", expected a function'; - switch (_v4.size(opts)) { + switch (_.size(opts)) { case 0: break; case 1: - err += ' or ' + _v4.keys(opts)[0]; + err += ' or ' + _.keys(opts)[0]; break; default: - err += ' or one of ' + _v4.keys(opts).join(', '); + err += ' or one of ' + _.keys(opts).join(', '); break; } throw new TypeError(err); @@ -368,13 +365,13 @@ _v4.funcEnum = function (config, name, opts, def) { * @param {Function} transform - A function called for each element of the resulting array * @return {Array|false} - an array on success, or false on failure. */ -_v4.createArray = function (input, transform) { - transform = typeof transform === 'function' ? transform : _v4.identity; +_.createArray = function (input, transform) { + transform = typeof transform === 'function' ? transform : _.identity; var output = []; var item; var i; - if (!_v4.isArray(input)) { + if (!_.isArray(input)) { input = [input]; } @@ -397,19 +394,19 @@ _v4.createArray = function (input, transform) { * @param {WritableStream} stream - an instance of stream.Writable * @return {string} - the remaining test to be written to the stream */ -_v4.getUnwrittenFromStream = function (stream) { - var writeBuffer = _v4.getStreamWriteBuffer(stream); +_.getUnwrittenFromStream = function (stream) { + var writeBuffer = _.getStreamWriteBuffer(stream); if (!writeBuffer) return; // flush the write buffer var out = ''; if (!writeBuffer.length) return out; - _v4.each(writeBuffer, function (writeReq) { + _.each(writeBuffer, function (writeReq) { if (writeReq.chunk) { // 0.9.12+ uses WriteReq objects with a chunk prop out += '' + writeReq.chunk; - } else if (_v4.isArray(writeReq) && (typeof writeReq[0] === 'string' || Buffer.isBuffer(writeReq[0]))) { + } else if (_.isArray(writeReq) && (typeof writeReq[0] === 'string' || Buffer.isBuffer(writeReq[0]))) { // 0.9.4 - 0.9.9 buffers are arrays of arrays like [[chunk, cb], [chunk, undef], ...]. out += '' + writeReq[0]; } else { @@ -419,7 +416,7 @@ _v4.getUnwrittenFromStream = function (stream) { return out; }; -_v4.getStreamWriteBuffer = function (stream) { +_.getStreamWriteBuffer = function (stream) { if (!stream || !stream._writableState) return; var writeState = stream._writableState; @@ -431,16 +428,16 @@ _v4.getStreamWriteBuffer = function (stream) { } }; -_v4.clearWriteStreamBuffer = function (stream) { - var buffer = _v4.getStreamWriteBuffer(stream); +_.clearWriteStreamBuffer = function (stream) { + var buffer = _.getStreamWriteBuffer(stream); return buffer && buffer.splice(0); }; /** * return the current time in milliseconds since epoch */ -_v4.now = function () { +_.now = function () { return (typeof Date.now === 'function') ? Date.now() : (new Date()).getTime(); }; -module.exports = _v4; +module.exports = _; diff --git a/test/fixtures/keepalive.js b/test/fixtures/keepalive.js index a6c0a3c5f..abbdee2d7 100644 --- a/test/fixtures/keepalive.js +++ b/test/fixtures/keepalive.js @@ -1,6 +1,6 @@ var clock = require('sinon').useFakeTimers(); var Client = require('../../src/elasticsearch').Client; -// var _ = require('lodash'); +var _ = require('lodash'); var times = require('async').times; process.once('message', function (port) { @@ -20,9 +20,9 @@ process.once('message', function (port) { clock.tick(10); }, function (err) { var conns = es.transport.connectionPool._conns; - var sockets = _v4([].concat(conns.dead, conns.alive)) + var sockets = _([].concat(conns.dead, conns.alive)) .transform(function (sockets, conn) { - sockets.push(_v4.values(conn.agent.sockets), _v4.values(conn.agent.freeSockets)); + sockets.push(_.values(conn.agent.sockets), _.values(conn.agent.freeSockets)); }, []) .flattenDeep() .value(); @@ -31,8 +31,8 @@ process.once('message', function (port) { var out = { socketCount: err || sockets.length, - remaining: _v4.filter(sockets, { destroyed: true }).length - sockets.length, - timeouts: _v4.size(clock.timers) && _v4.map(clock.timers, 'func').map(String) + remaining: _.filter(sockets, { destroyed: true }).length - sockets.length, + timeouts: _.size(clock.timers) && _.map(clock.timers, 'func').map(String) }; clock.restore(); diff --git a/test/integration/yaml_suite/client_manager.js b/test/integration/yaml_suite/client_manager.js index e67503643..4cc481a7b 100644 --- a/test/integration/yaml_suite/client_manager.js +++ b/test/integration/yaml_suite/client_manager.js @@ -9,10 +9,10 @@ if (BROWSER) { es = require('../../../src/elasticsearch'); } -// var _ = require('../../../src/lib/utils'); +var _ = require('../../../src/lib/utils'); var path = require('path'); var fs = require('fs'); -var fromRoot = _v4.bindKey(path, 'join', require('find-root')(__dirname)); +var fromRoot = _.bindKey(path, 'join', require('find-root')(__dirname)); var Bluebird = require('bluebird'); // current client @@ -60,7 +60,7 @@ module.exports = { } var logConfig = {}; - if (_v4.has(options, 'logConfig')) { + if (_.has(options, 'logConfig')) { logConfig = options.logConfig; } else { if (BROWSER) { @@ -106,14 +106,14 @@ module.exports = { client.snapshot.getRepository({ snapshot: '_all' }) - .then(_v4.keys) + .then(_.keys) .map(function (repo) { return client.snapshot.get({ repository: repo, snapshot: '_all' }) .then(function (resp) { - return _v4.map(resp.snapshots, 'snapshot'); + return _.map(resp.snapshots, 'snapshot'); }, function () { return []; }) @@ -132,7 +132,7 @@ module.exports = { ]); }; - _v4.nextTick(cb); + _.nextTick(cb); } }, get: function () { diff --git a/test/integration/yaml_suite/run.js b/test/integration/yaml_suite/run.js index f5ec5cf23..9ec43a994 100644 --- a/test/integration/yaml_suite/run.js +++ b/test/integration/yaml_suite/run.js @@ -4,7 +4,7 @@ module.exports = function (branch) { var YamlFile = require('./yaml_file'); var root = require('find-root')(__dirname); var rootReq = function (loc) { return require(path.join(root, loc)); }; - // var _ = rootReq('src/lib/utils'); + var _ = rootReq('src/lib/utils'); var utils = rootReq('grunt/utils'); var es = rootReq('src/elasticsearch'); var clientManager = require('./client_manager'); @@ -32,7 +32,7 @@ module.exports = function (branch) { return clientManager.get().clearEs(); }); - var files = _v4.map(require('./yaml_tests_' + _v4.snakeCase(branch) + '.json'), function (docs, filename) { + var files = _.map(require('./yaml_tests_' + _.snakeCase(branch) + '.json'), function (docs, filename) { return new YamlFile(filename, docs); }); diff --git a/test/integration/yaml_suite/yaml_doc.js b/test/integration/yaml_suite/yaml_doc.js index 089b4d082..cd7911536 100644 --- a/test/integration/yaml_suite/yaml_doc.js +++ b/test/integration/yaml_suite/yaml_doc.js @@ -9,7 +9,7 @@ */ module.exports = YamlDoc; -// var _ = require('lodash-migrate/lodash'); +var _ = require('lodash'); var expect = require('expect.js'); var clientManager = require('./client_manager'); var inspect = require('util').inspect; @@ -70,8 +70,8 @@ function versionToComparableString(version, def) { return def; } - var parts = _v4.map(version.split('.'), function (part) { - part = '' + _v4.parseInt(part); + var parts = _.map(version.split('.'), function (part) { + part = '' + _.parseInt(part); return (new Array(Math.max(4 - part.length, 0))).join('0') + part; }); @@ -109,26 +109,26 @@ function YamlDoc(doc, file) { var self = this; self.file = file; - self.description = _v4.keys(doc).shift(); + self.description = _.keys(doc).shift(); self._stash = {}; self._last_requests_response = null; // setup the actions, creating a bound and testable method for each - self._actions = _v4.map(self.flattenTestActions(doc[self.description]), function (action) { + self._actions = _.map(self.flattenTestActions(doc[self.description]), function (action) { // get the method that will do the action var method = self['do_' + action.name]; // check that it's a function expect(method || 'YamlDoc#' + action.name).to.be.a('function'); - if (_v4.isPlainObject(action.args)) { + if (_.isPlainObject(action.args)) { action.name += '(' + JSON.stringify(action.args) + ')'; } else if (action.args) { action.name += '(' + action.args + ')'; } // wrap in a check for skipping - action.bound = _v4.bind(method, self, action.args); + action.bound = _.bind(method, self, action.args); // create a function that can be passed to mocha or async action.testable = function (_cb) { @@ -199,15 +199,15 @@ YamlDoc.prototype = { flattenTestActions: function (config) { // creates [ [ {name:"", args:"" }, ... ], ... ] // from [ {name:args, name:args}, {name:args} ] - var actionSets = _v4.map(config, function (set) { - return _v4.map(_v4.toPairs(set), function (pair) { + var actionSets = _.map(config, function (set) { + return _.map(_.toPairs(set), function (pair) { return { name: pair[0], args: pair[1] }; }); }); // do a single level flatten, merge=ing the nested arrays from step one // into a master array, creating an array of action objects - return _v4.reduce(actionSets, function (note, set) { + return _.reduce(actionSets, function (note, set) { return note.concat(set); }, []); }, @@ -273,7 +273,7 @@ YamlDoc.prototype = { log('getting', path, 'from', from); - var steps = _v4.map(path ? path.replace(/\\\./g, '\uffff').split('.') : [], function (step) { + var steps = _.map(path ? path.replace(/\\\./g, '\uffff').split('.') : [], function (step) { return step.replace(/\uffff/g, '.'); }); var remainingSteps; @@ -301,7 +301,7 @@ YamlDoc.prototype = { */ do_skip: function (args, done) { if (args.version) { - return rangeMatchesCurrentVersion(args.version, _v4.bind(function (match) { + return rangeMatchesCurrentVersion(args.version, _.bind(function (match) { if (match) { if (this.description === 'setup') { this.file.skipping = true; @@ -320,7 +320,7 @@ YamlDoc.prototype = { if (args.features) { var features = Array.isArray(args.features) ? args.features : [args.features]; - var notImplemented = _v4.difference(features, implementedFeatures); + var notImplemented = _.difference(features, implementedFeatures); if (notImplemented.length) { if (this.description === 'setup') { @@ -396,25 +396,25 @@ YamlDoc.prototype = { delete args.headers; } - var otherKeys = _v4.keys(args); + var otherKeys = _.keys(args); var action = otherKeys.shift(); if (otherKeys.length) { return done(new TypeError('Unexpected top-level args to "do": ' + otherKeys.join(', '))); } var client = clientManager.get(); - var clientActionName = _v4.map(action.split('.'), _v4.camelCase).join('.'); + var clientActionName = _.map(action.split('.'), _.camelCase).join('.'); var clientAction = this.get(clientActionName, client); - _v4.assign(inputParams, args[action]); + _.assign(inputParams, args[action]); - var params = _v4.transform(inputParams, _v4.bind(function (params, val, name) { - var camelName = _v4.camelCase(name); + var params = _.transform(inputParams, _.bind(function (params, val, name) { + var camelName = _.camelCase(name); // search through the params and url peices to find this param name var paramName = name; var spec = clientAction && clientAction.spec; var knownParam = spec && spec.params && spec.params[camelName]; - var knownUrlParam = spec && !knownParam && !!_v4.find(spec.url ? [spec.url] : spec.urls, function (url) { + var knownUrlParam = spec && !knownParam && !!_.find(spec.url ? [spec.url] : spec.urls, function (url) { if ((url.opt && url.opt[camelName]) || (url.req && url.req[camelName])) { return true; } @@ -427,10 +427,10 @@ YamlDoc.prototype = { // for ercursively traversing the params to replace '$stashed' vars var transformObject = function (vals, val, i) { - if (_v4.isString(val)) { + if (_.isString(val)) { val = (val[0] === '$') ? this.get(val) : val; - } else if (_v4.isPlainObject(val) || _v4.isArray(val)) { - val = _v4.transform(val, transformObject); + } else if (_.isPlainObject(val) || _.isArray(val)) { + val = _.transform(val, transformObject); } vals[i] = val; @@ -443,12 +443,12 @@ YamlDoc.prototype = { expect(clientAction || clientActionName).to.be.a('function'); if (!isNaN(parseFloat(catcher))) { - params.ignore = _v4.union(params.ignore || [], [catcher]); + params.ignore = _.union(params.ignore || [], [catcher]); catcher = null; } var timeoutId; - var cb = _v4.bind(function (error, body) { + var cb = _.bind(function (error, body) { this._last_requests_response = body; clearTimeout(timeoutId); @@ -494,7 +494,7 @@ YamlDoc.prototype = { * @return {undefined} */ do_set: function (args) { - _v4.forOwn(args, _v4.bind(function (name, path) { + _.forOwn(args, _.bind(function (name, path) { this._stash[name] = this.get(path); }, this)); }, @@ -566,25 +566,25 @@ YamlDoc.prototype = { var self = this; // recursively replace all $var within args - _v4.forOwn(args, function recurse(val, key, lvl) { - if (_v4.isObject(val)) { - return _v4.each(val, recurse); + _.forOwn(args, function recurse(val, key, lvl) { + if (_.isObject(val)) { + return _.each(val, recurse); } - if (_v4.isString(val)) { + if (_.isString(val)) { lvl[key] = val.replace(/\$[a-zA-Z0-9_]+/g, function (name) { return self.get(name); }); } }); - _v4.forOwn(args, _v4.bind(function (match, path) { + _.forOwn(args, _.bind(function (match, path) { var origMatch = match; var maybeRE = false; var usedRE = false; - if (_v4.isString(match)) { + if (_.isString(match)) { // convert the matcher into a compatible string for building a regexp maybeRE = match // replace comments, but allow the # to be escaped like \# @@ -655,7 +655,7 @@ YamlDoc.prototype = { * @return {undefined} */ do_lt: function (args) { - _v4.forOwn(args, _v4.bind(function (num, path) { + _.forOwn(args, _.bind(function (num, path) { expect(this.get(path)).to.be.below(num, 'path: ' + path); }, this)); }, @@ -667,7 +667,7 @@ YamlDoc.prototype = { * @return {undefined} */ do_lte: function (args) { - _v4.forOwn(args, _v4.bind(function (num, path) { + _.forOwn(args, _.bind(function (num, path) { expect(this.get(path) <= num).to.be.ok('path: ' + path); }, this)); }, @@ -679,7 +679,7 @@ YamlDoc.prototype = { * @return {undefined} */ do_gt: function (args) { - _v4.forOwn(args, _v4.bind(function (num, path) { + _.forOwn(args, _.bind(function (num, path) { expect(this.get(path)).to.be.above(num, 'path: ' + path); }, this)); }, @@ -691,7 +691,7 @@ YamlDoc.prototype = { * @return {undefined} */ do_gte: function (args) { - _v4.forOwn(args, _v4.bind(function (num, path) { + _.forOwn(args, _.bind(function (num, path) { expect(this.get(path) >= num).to.be.ok('path: ' + path); }, this)); }, @@ -704,8 +704,8 @@ YamlDoc.prototype = { * @return {undefined} */ do_length: function (args) { - _v4.forOwn(args, _v4.bind(function (len, path) { - expect(_v4.size(this.get(path))).to.eql(len, 'path: ' + path); + _.forOwn(args, _.bind(function (len, path) { + expect(_.size(this.get(path))).to.eql(len, 'path: ' + path); }, this)); } }; diff --git a/test/integration/yaml_suite/yaml_file.js b/test/integration/yaml_suite/yaml_file.js index 61f282541..b96529fc6 100644 --- a/test/integration/yaml_suite/yaml_file.js +++ b/test/integration/yaml_suite/yaml_file.js @@ -8,7 +8,7 @@ module.exports = YamlFile; var YamlDoc = require('./yaml_doc'); var clientManager = require('./client_manager'); -// var _ = require('../../../src/lib/utils'); +var _ = require('../../../src/lib/utils'); var async = require('async'); function YamlFile(filename, docs) { @@ -18,7 +18,7 @@ function YamlFile(filename, docs) { file.skipping = false; describe(filename, function () { - file.docs = _v4.map(docs, function (doc) { + file.docs = _.map(docs, function (doc) { doc = new YamlDoc(doc, file); if (doc.description === 'setup') { beforeEach(/* doc */function (done) { diff --git a/test/mocks/browser_http.js b/test/mocks/browser_http.js index e04180972..9b42d48ff 100644 --- a/test/mocks/browser_http.js +++ b/test/mocks/browser_http.js @@ -27,7 +27,7 @@ module.exports = MockHttpRequest; -// var _ = require('lodash'); +var _ = require('lodash'); function MockHttpRequest() { // These are internal flags and data structures @@ -221,7 +221,7 @@ MockHttpRequest.prototype = { getAllResponseHeaders: function () { var r = ''; - _v4.each(this.responseHeaders, function (header) { + _.each(this.responseHeaders, function (header) { if ((header === 'set-cookie') || (header === 'set-cookie2')) { return; } @@ -353,7 +353,7 @@ MockHttpRequest.prototype = { this.responseText = null; this.error = true; - _v4.each(this.requestHeaders, function (header) { + _.each(this.requestHeaders, function (header) { delete this.requestHeaders[header]; }, this); diff --git a/test/mocks/browser_server.js b/test/mocks/browser_server.js index 90a8de629..3d0010519 100644 --- a/test/mocks/browser_server.js +++ b/test/mocks/browser_server.js @@ -3,7 +3,7 @@ var complete = []; var MockHttpRequest = require('./browser_http'); var XhrServer = MockHttpRequest.MockHttpServer; var parseUrl = MockHttpRequest.prototype.parseUri; -// var _ = require('lodash'); +var _ = require('lodash'); var server = new XhrServer(function (request) { var reqDetails = { @@ -11,7 +11,7 @@ var server = new XhrServer(function (request) { host: request.urlParts.host, path: request.urlParts.relative }; - var response = _v4.find(interceptors, reqDetails); + var response = _.find(interceptors, reqDetails); if (response) { // remove of tick down the times diff --git a/test/unit/browser_builds/angular.js b/test/unit/browser_builds/angular.js index 68bd76c4d..aa021498b 100644 --- a/test/unit/browser_builds/angular.js +++ b/test/unit/browser_builds/angular.js @@ -1,5 +1,5 @@ /* global angular */ -// var _ = require('lodash'); +var _ = require('lodash'); var expect = require('expect.js'); var Promise = require('bluebird'); var sinon = require('sinon'); @@ -17,13 +17,13 @@ describe('Angular esFactory', function () { function bootstrap(env) { beforeEach(function () { - var promiseProvider = _v4.noop; + var promiseProvider = _.noop; if (env.bluebirdPromises) { promiseProvider = function ($provide) { $provide.service('$q', function () { return { defer: function () { - return _v4.bindAll(Promise.defer(), ['resolve', 'reject']); + return _.bindAll(Promise.defer(), ['resolve', 'reject']); }, reject: Promise.reject, when: Promise.resolve, diff --git a/test/unit/buffer_flush_tests.js b/test/unit/buffer_flush_tests.js index ee56ba4ce..4d61a7ed8 100644 --- a/test/unit/buffer_flush_tests.js +++ b/test/unit/buffer_flush_tests.js @@ -3,7 +3,7 @@ module.exports = function (makeLogger) { var stub = require('../utils/auto_release_stub').make(); var fs = require('fs'); var once = require('events').EventEmitter.prototype.once; - // var _ = require('lodash'); + var _ = require('lodash'); describe('buffer flush', function () { if (require('stream').Writable) { @@ -21,7 +21,7 @@ module.exports = function (makeLogger) { var logger = makeLogger(); // write the line 10 times - _v4.times(10, function () { + _.times(10, function () { logger.onDebug(line); }); diff --git a/test/unit/specs/client_action.js b/test/unit/specs/client_action.js index f16cbe324..6dd71002d 100644 --- a/test/unit/specs/client_action.js +++ b/test/unit/specs/client_action.js @@ -1,7 +1,7 @@ var ca = require('../../../src/lib/client_action').factory; var proxy = require('../../../src/lib/client_action').proxyFactory; var expect = require('expect.js'); -// var _ = require('lodash'); +var _ = require('lodash'); var Promise = require('bluebird'); /** @@ -45,7 +45,7 @@ function makeClientAction(spec) { }; } - return _v4.bind(ca(spec), mockClient()); + return _.bind(ca(spec), mockClient()); } /** @@ -55,7 +55,7 @@ function makeClientAction(spec) { * @return {Function} - the clientActionProxy */ function makeClientActionProxy(fn, spec) { - return _v4.bind(proxy(fn, spec || {}), mockClient()); + return _.bind(proxy(fn, spec || {}), mockClient()); } @@ -68,7 +68,7 @@ describe('Client Action runner', function () { afterEach(function () { _stash = {}; }); var make = function (params) { _stash.orig = params; - _stash.copy = _v4.clone(params); + _stash.copy = _.clone(params); return params; }; make.check = function () { @@ -118,7 +118,7 @@ describe('Client Action runner', function () { it('handles passing just the callback', function () { var action = makeClientActionProxy(function (params, cb) { - expect(_v4.isObject(params)).to.be.ok(); + expect(_.isObject(params)).to.be.ok(); expect(cb).to.be.a('function'); }); diff --git a/test/unit/specs/connection_abstract.js b/test/unit/specs/connection_abstract.js index 9463f7016..f9b67ff33 100644 --- a/test/unit/specs/connection_abstract.js +++ b/test/unit/specs/connection_abstract.js @@ -2,7 +2,7 @@ var ConnectionAbstract = require('../../../src/lib/connection'); var Host = require('../../../src/lib/host'); var sinon = require('sinon'); var expect = require('expect.js'); -// var _ = require('lodash'); +var _ = require('lodash'); var errors = require('../../../src/lib/errors'); var stub = require('../../utils/auto_release_stub').make(); @@ -73,10 +73,10 @@ describe('Connection Abstract', function () { stub(conn, 'request'); - expect(_v4.size(clock.timers)).to.eql(0); + expect(_.size(clock.timers)).to.eql(0); conn.ping(); - expect(_v4.size(clock.timers)).to.eql(1); - expect(clock.timers[_v4.keys(clock.timers).shift()].delay).to.eql(5000); + expect(_.size(clock.timers)).to.eql(1); + expect(clock.timers[_.keys(clock.timers).shift()].delay).to.eql(5000); }); it('calls it\'s own request method', function () { diff --git a/test/unit/specs/connection_pool.js b/test/unit/specs/connection_pool.js index e5ac7307c..0b4c8b5c3 100644 --- a/test/unit/specs/connection_pool.js +++ b/test/unit/specs/connection_pool.js @@ -1,7 +1,7 @@ var ConnectionPool = require('../../../src/lib/connection_pool'); var Host = require('../../../src/lib/host'); var ConnectionAbstract = require('../../../src/lib/connection'); -// var _ = require('lodash'); +var _ = require('lodash'); var EventEmitter = require('events').EventEmitter; var expect = require('expect.js'); var sinon = require('sinon'); @@ -36,10 +36,10 @@ describe('Connection Pool', function () { }); it('#addConnection only adds the connection if it doesn\'t already exist', function () { - expect(_v4.keys(pool.index).length).to.eql(0); + expect(_.keys(pool.index).length).to.eql(0); pool.addConnection(connection); - expect(_v4.keys(pool.index)).to.eql([host.toString()]); + expect(_.keys(pool.index)).to.eql([host.toString()]); expect(pool._conns.alive).to.eql([connection]); expect(pool._conns.dead).to.eql([]); @@ -52,7 +52,7 @@ describe('Connection Pool', function () { expect(pool._conns.alive).to.eql([connection]); expect(pool._conns.dead).to.eql([]); - expect(_v4.keys(pool.index).length).to.eql(1); + expect(_.keys(pool.index).length).to.eql(1); }); it('closes the connection when it removes it', function () { @@ -175,10 +175,10 @@ describe('Connection Pool', function () { new ConnectionAbstract(new Host('http://localhost:9202')), new ConnectionAbstract(new Host('http://localhost:9203')) ]; - var pingQueue = _v4.shuffle(connections); + var pingQueue = _.shuffle(connections); var expectedSelection = pingQueue[pingQueue.length - 1]; - _v4.each(pingQueue, function (conn) { + _.each(pingQueue, function (conn) { pool.addConnection(conn); stub(conn, 'ping', function (params, cb) { if (typeof params === 'function') { @@ -247,13 +247,13 @@ describe('Connection Pool', function () { stub.autoRelease(clock); connection.setStatus('dead'); - expect(_v4.size(clock.timers)).to.eql(1); - var id = _v4(clock.timers).keys().first(); + expect(_.size(clock.timers)).to.eql(1); + var id = _(clock.timers).keys().first(); // it re-dies connection.setStatus('dead'); - expect(_v4.size(clock.timers)).to.eql(1); - expect(_v4(clock.timers).keys().first()).to.not.eql(id); + expect(_.size(clock.timers)).to.eql(1); + expect(_(clock.timers).keys().first()).to.not.eql(id); }); it('does nothing when a connection is re-alive', function () { @@ -295,7 +295,7 @@ describe('Connection Pool', function () { var result = pool.getConnections(); expect(result.length).to.be(1000); - expect(_v4.reduce(result, function (sum, num) { + expect(_.reduce(result, function (sum, num) { sum += num return sum; }, 0)).to.eql(499500); diff --git a/test/unit/specs/errors.js b/test/unit/specs/errors.js index 9016e93fe..fb885c0e3 100644 --- a/test/unit/specs/errors.js +++ b/test/unit/specs/errors.js @@ -1,8 +1,8 @@ var errors = require('../../../src/lib/errors'); var expect = require('expect.js'); -// var _ = require('lodash'); +var _ = require('lodash'); -_v4.each(errors, function (CustomError, name) { +_.each(errors, function (CustomError, name) { if (name.charAt(0) !== '_') { describe(name, function () { it('extend the ErrorAbstract and Error classes', function () { diff --git a/test/unit/specs/file_logger.js b/test/unit/specs/file_logger.js index d002d6d3d..4766cae6b 100644 --- a/test/unit/specs/file_logger.js +++ b/test/unit/specs/file_logger.js @@ -2,7 +2,7 @@ describe('File Logger', function () { var Log = require('../../../src/lib/log'); var FileLogger = require('../../../src/lib/loggers/file'); var once = require('events').EventEmitter.prototype.once; - // var _ = require('../../../src/lib/utils'); + var _ = require('../../../src/lib/utils'); var parentLog; var logger; var expect = require('expect.js'); @@ -15,7 +15,7 @@ describe('File Logger', function () { afterEach(function () { parentLog.close(); - logger && _v4.clearWriteStreamBuffer(logger.stream); + logger && _.clearWriteStreamBuffer(logger.stream); }); function makeLogger(parent, levels) { @@ -49,7 +49,7 @@ describe('File Logger', function () { var logger = makeLogger(); // write the line 10 times - _v4.times(10, function () { + _.times(10, function () { logger.onDebug(line); }); diff --git a/test/unit/specs/host.js b/test/unit/specs/host.js index 9b0966020..44f432455 100644 --- a/test/unit/specs/host.js +++ b/test/unit/specs/host.js @@ -1,5 +1,5 @@ var Host = require('../../../src/lib/host'); -// var _ = require('lodash'); +var _ = require('lodash'); var expect = require('expect.js'); var url = require('url'); var expectSubObject = require('../../utils/expect_sub_object'); diff --git a/test/unit/specs/http_connector.js b/test/unit/specs/http_connector.js index 72450025b..c88f3577e 100644 --- a/test/unit/specs/http_connector.js +++ b/test/unit/specs/http_connector.js @@ -1,6 +1,6 @@ describe('Http Connector', function () { - // var _ = require('lodash'); + var _ = require('lodash'); var expect = require('expect.js'); var nock = require('nock'); var sinon = require('sinon'); @@ -67,12 +67,12 @@ describe('Http Connector', function () { it('allows defining a custom agent', function () { var football = {}; - var con = new HttpConnection(new Host(), { createNodeAgent: _v4.constant(football) }); + var con = new HttpConnection(new Host(), { createNodeAgent: _.constant(football) }); expect(con.agent).to.be(football); }); it('allows setting agent to false', function () { - var con = new HttpConnection(new Host(), { createNodeAgent: _v4.constant(false) }); + var con = new HttpConnection(new Host(), { createNodeAgent: _.constant(false) }); expect(con.agent).to.be(false); }); }); @@ -482,7 +482,7 @@ describe('Http Connector', function () { this.timeout(5 * 60 * 1000); var cp = require('child_process'); var path = require('path'); - var fixture = _v4.partial(path.join, __dirname, '../../fixtures'); + var fixture = _.partial(path.join, __dirname, '../../fixtures'); var timeout; // start the timeout once we hear back from the client var server = cp.fork(fixture('keepalive_server.js')) diff --git a/test/unit/specs/log.js b/test/unit/specs/log.js index e9be3591a..44e7fa28d 100644 --- a/test/unit/specs/log.js +++ b/test/unit/specs/log.js @@ -1,5 +1,5 @@ var Log = require('../../../src/lib/log'); -// var _ = require('lodash'); +var _ = require('lodash'); var expect = require('expect.js'); describe('Log class', function () { @@ -129,11 +129,11 @@ describe('Log class', function () { log: [ { type: function (log, config) { - log.on('error', _v4.noop); - log.on('warning', _v4.noop); - log.on('info', _v4.noop); - log.on('debug', _v4.noop); - log.on('trace', _v4.noop); + log.on('error', _.noop); + log.on('warning', _.noop); + log.on('info', _.noop); + log.on('debug', _.noop); + log.on('trace', _.noop); } } ] diff --git a/test/unit/specs/random_selector.js b/test/unit/specs/random_selector.js index 18709b210..91b0149b0 100644 --- a/test/unit/specs/random_selector.js +++ b/test/unit/specs/random_selector.js @@ -1,18 +1,18 @@ describe('Random Selector', function () { var randomSelector = require('../../../src/lib/selectors/random'); - // var _ = require('lodash'); + var _ = require('lodash'); var expect = require('expect.js'); it('chooses a selection by random', function () { var log = { a: 0, b: 0, c: 0 }; - var choices = _v4.keys(log); + var choices = _.keys(log); - _v4.times(1000, function () { + _.times(1000, function () { var choice = randomSelector(choices); log[choice]++; }); - expect(_v4.filter(log, function (count) { + expect(_.filter(log, function (count) { return count < 200 || count > 400; })).to.have.length(0); diff --git a/test/unit/specs/round_robin_selector.js b/test/unit/specs/round_robin_selector.js index 18e9d957d..2298a0180 100644 --- a/test/unit/specs/round_robin_selector.js +++ b/test/unit/specs/round_robin_selector.js @@ -1,14 +1,14 @@ describe('Round Robin Selector', function () { var selector = require('../../../src/lib/selectors/round_robin'); - // var _ = require('lodash'); + var _ = require('lodash'); var expect = require('expect.js'); it('chooses options in order', function () { var options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]; - var expected = _v4.clone(options); + var expected = _.clone(options); var selections = []; - _v4.times(options.length, function () { + _.times(options.length, function () { selections.push(selector(options)); }); diff --git a/test/unit/specs/stream_logger.js b/test/unit/specs/stream_logger.js index 52b6c1cf7..f4c3d65ce 100644 --- a/test/unit/specs/stream_logger.js +++ b/test/unit/specs/stream_logger.js @@ -4,7 +4,7 @@ describe('Stream Logger', function () { var MockWritableStream = require('../../mocks/writable_stream'); var once = require('events').EventEmitter.prototype.once; var stream = new MockWritableStream(); - // var _ = require('../../../src/lib/utils'); + var _ = require('../../../src/lib/utils'); var expect = require('expect.js'); var parentLog; @@ -19,7 +19,7 @@ describe('Stream Logger', function () { afterEach(function () { parentLog.close(); - _v4.clearWriteStreamBuffer(stream); + _.clearWriteStreamBuffer(stream); }); function makeLogger(parent, levels) { @@ -41,13 +41,13 @@ describe('Stream Logger', function () { // get the last handler for process's "exit" event var exitHandlers = process._events.exit; - var exitHandler = _v4.isArray(exitHandlers) ? _v4.last(exitHandlers) : exitHandlers; + var exitHandler = _.isArray(exitHandlers) ? _.last(exitHandlers) : exitHandlers; // allow the logger to acctually write to the stream stream.write.restore(); // write the line 10 times - _v4.times(10, function () { + _.times(10, function () { logger.onDebug(line); }); diff --git a/test/unit/specs/transport.js b/test/unit/specs/transport.js index 2603f3bab..f7aaba374 100644 --- a/test/unit/specs/transport.js +++ b/test/unit/specs/transport.js @@ -4,7 +4,7 @@ var errors = require('../../../src/lib/errors'); var sinon = require('sinon'); var expect = require('expect.js'); -// var _ = require('lodash'); +var _ = require('lodash'); var nodeList = require('../../fixtures/short_node_list.json'); var stub = require('../../utils/auto_release_stub').make(); @@ -83,11 +83,11 @@ describe('Transport Class', function () { sniffInterval: 25000 }); - expect(_v4.size(clock.timers)).to.eql(1); - var id = _v4.keys(clock.timers).pop(); + expect(_.size(clock.timers)).to.eql(1); + var id = _.keys(clock.timers).pop(); clock.tick(25000); expect(trans.sniff.callCount).to.eql(1); - expect(_v4.size(clock.timers)).to.eql(1); + expect(_.size(clock.timers)).to.eql(1); expect(clock.timers).to.not.have.key(id); }); @@ -285,25 +285,25 @@ describe('Transport Class', function () { describe('randomizeHosts options', function () { it('calls _.shuffle be default', function () { - // var _ = require('../../../src/lib/utils'); + var _ = require('../../../src/lib/utils'); stub(Transport.connectionPools.main.prototype, 'setHosts'); - stub(_v4, 'shuffle'); + stub(_, 'shuffle'); var trans = new Transport({ hosts: 'localhost' }); - expect(_v4.shuffle.callCount).to.eql(1); + expect(_.shuffle.callCount).to.eql(1); }); it('skips the call to _.shuffle when false', function () { - // var _ = require('../../../src/lib/utils'); + var _ = require('../../../src/lib/utils'); stub(Transport.connectionPools.main.prototype, 'setHosts'); - stub(_v4, 'shuffle'); + stub(_, 'shuffle'); var trans = new Transport({ hosts: 'localhost', randomizeHosts: false }); - expect(_v4.shuffle.callCount).to.eql(0); + expect(_.shuffle.callCount).to.eql(0); }); }); }); @@ -606,7 +606,7 @@ describe('Transport Class', function () { } var trans = new Transport({ - hosts: _v4.map(new Array(retries + 1), function (val, i) { + hosts: _.map(new Array(retries + 1), function (val, i) { return 'localhost/' + i; }), maxRetries: retries, @@ -617,8 +617,8 @@ describe('Transport Class', function () { }); // trigger a select so that we can harvest the connection list - trans.connectionPool.select(_v4.noop); - _v4.each(connections, function (conn) { + trans.connectionPool.select(_.noop); + _.each(connections, function (conn) { stub(conn, 'request', failRequest); }); @@ -632,7 +632,7 @@ describe('Transport Class', function () { }); }; } - it('retries when there are retries remaining', testRetries(_v4.random(25, 40))); + it('retries when there are retries remaining', testRetries(_.random(25, 40))); it('responds when there are no retries', testRetries(0)); }); @@ -641,7 +641,7 @@ describe('Transport Class', function () { it('returns an object with an abort() method when a callback is sent', function () { var tran = new Transport(); shortCircuitRequest(tran); - var ret = tran.request({}, _v4.noop); + var ret = tran.request({}, _.noop); expect(ret).to.be.a('object'); expect(ret.abort).to.be.a('function'); }); @@ -651,7 +651,7 @@ describe('Transport Class', function () { var ret = tran.request({}); expect(ret.then).to.be.a('function'); expect(ret.abort).to.be.a('function'); - ret.then(_v4.noop, _v4.noop); // prevent complaining from bluebird + ret.then(_.noop, _.noop); // prevent complaining from bluebird }); it('promise is always pulled from the defer created by this.defer()', function () { var fakePromise = {}; @@ -659,8 +659,8 @@ describe('Transport Class', function () { var tran = new Transport({ defer: function () { return { - resolve: _v4.noop, - reject: _v4.noop, + resolve: _.noop, + reject: _.noop, promise: fakePromise }; } @@ -759,10 +759,10 @@ describe('Transport Class', function () { var prom = tran.request({}); // disregard promise, prevent bluebird's warnings - prom.then(_v4.noop, _v4.noop); + prom.then(_.noop, _.noop); - expect(_v4.size(clock.timers)).to.eql(1); - _v4.each(clock.timers, function (timer, id) { + expect(_.size(clock.timers)).to.eql(1); + _.each(clock.timers, function (timer, id) { expect(timer.callAt).to.eql(30000); clearTimeout(id); }); @@ -776,17 +776,17 @@ describe('Transport Class', function () { var prom = tran.request({}); // disregard promise, prevent bluebird's warnings - prom.then(_v4.noop, _v4.noop); + prom.then(_.noop, _.noop); - expect(_v4.size(clock.timers)).to.eql(1); - _v4.each(clock.timers, function (timer, id) { + expect(_.size(clock.timers)).to.eql(1); + _.each(clock.timers, function (timer, id) { expect(timer.callAt).to.eql(5000); clearTimeout(id); }); }); - _v4.each([false, 0, null], function (falsy) { + _.each([false, 0, null], function (falsy) { it('skips the timeout when it is ' + falsy, function () { var clock = sinon.useFakeTimers(); stub.autoRelease(clock); @@ -797,7 +797,7 @@ describe('Transport Class', function () { requestTimeout: falsy }, function () {}); - expect(_v4.size(clock.timers)).to.eql(0); + expect(_.size(clock.timers)).to.eql(0); }); }); }); diff --git a/test/unit/specs/transport_with_server.js b/test/unit/specs/transport_with_server.js index 4ba36c737..865885da8 100644 --- a/test/unit/specs/transport_with_server.js +++ b/test/unit/specs/transport_with_server.js @@ -7,7 +7,7 @@ var expect = require('expect.js'); var sinon = require('sinon'); var nock = require('../../mocks/server.js'); var through2 = require('through2'); -// var _ = require('lodash'); +var _ = require('lodash'); var nodeList = require('../../fixtures/short_node_list.json'); var stub = require('../../utils/auto_release_stub').make(); @@ -277,7 +277,7 @@ describe('Transport + Mock server', function () { expect(err).to.be(undefined); expect(resp).to.eql({ i: 'am here' }); expect(status).to.eql(200); - expect(_v4.keys(clock.timers)).to.have.length(0); + expect(_.keys(clock.timers)).to.have.length(0); clock.restore(); }); }); @@ -342,9 +342,9 @@ describe('Transport + Mock server', function () { .catch(function (err) { expect(ConnectionPool.prototype._onConnectionDied.callCount).to.eql(1); expect(tran.sniff.callCount).to.eql(0); - expect(_v4.size(clock.timers)).to.eql(1); + expect(_.size(clock.timers)).to.eql(1); - var timeout = _v4.values(clock.timers).pop(); + var timeout = _.values(clock.timers).pop(); timeout.func(); expect(tran.sniff.callCount).to.eql(1); }); diff --git a/test/unit/specs/utils.js b/test/unit/specs/utils.js index 1fd8f4a60..0c6f6fcfc 100644 --- a/test/unit/specs/utils.js +++ b/test/unit/specs/utils.js @@ -1,4 +1,4 @@ -// var _ = require('../../../src/lib/utils'); +var _ = require('../../../src/lib/utils'); var expect = require('expect.js'); var stub = require('../../utils/auto_release_stub').make(); @@ -6,7 +6,7 @@ var stub = require('../../utils/auto_release_stub').make(); describe('Utils', function () { describe('Additional Type Checkers', function () { - _v4.forEach({ + _.forEach({ Object: { is: [[], /regexp/] }, @@ -34,66 +34,66 @@ describe('Utils', function () { function (thing, name) { describe('#isArrayOf' + name, function () { it('likes arrays of ' + name, function () { - expect(_v4['isArrayOf' + name + 's'](thing.is)).to.be(true); + expect(_['isArrayOf' + name + 's'](thing.is)).to.be(true); }); it('dislikes when there is even one non ' + name, function () { // notice a string in the array thing.is.push(thing.not || ' not '); - expect(_v4['isArrayOf' + name + 's'](thing.is)).to.be(false); + expect(_['isArrayOf' + name + 's'](thing.is)).to.be(false); }); }); }); describe('#isNumeric', function () { it('likes integer literals', function () { - expect(_v4.isNumeric('-10')).to.be(true); - expect(_v4.isNumeric('0')).to.be(true); - expect(_v4.isNumeric('5')).to.be(true); - expect(_v4.isNumeric(-16)).to.be(true); - expect(_v4.isNumeric(0)).to.be(true); - expect(_v4.isNumeric(32)).to.be(true); - expect(_v4.isNumeric('040')).to.be(true); - expect(_v4.isNumeric('0xFF')).to.be(true); - expect(_v4.isNumeric(0xFFF)).to.be(true); + expect(_.isNumeric('-10')).to.be(true); + expect(_.isNumeric('0')).to.be(true); + expect(_.isNumeric('5')).to.be(true); + expect(_.isNumeric(-16)).to.be(true); + expect(_.isNumeric(0)).to.be(true); + expect(_.isNumeric(32)).to.be(true); + expect(_.isNumeric('040')).to.be(true); + expect(_.isNumeric('0xFF')).to.be(true); + expect(_.isNumeric(0xFFF)).to.be(true); }); it('likes float literals', function () { - expect(_v4.isNumeric('-1.6')).to.be(true); - expect(_v4.isNumeric('4.536')).to.be(true); - expect(_v4.isNumeric(-2.6)).to.be(true); - expect(_v4.isNumeric(3.1415)).to.be(true); - expect(_v4.isNumeric(8e5)).to.be(true); - expect(_v4.isNumeric('123e-2')).to.be(true); + expect(_.isNumeric('-1.6')).to.be(true); + expect(_.isNumeric('4.536')).to.be(true); + expect(_.isNumeric(-2.6)).to.be(true); + expect(_.isNumeric(3.1415)).to.be(true); + expect(_.isNumeric(8e5)).to.be(true); + expect(_.isNumeric('123e-2')).to.be(true); }); it('dislikes non-numeric stuff', function () { - expect(_v4.isNumeric('')).to.be(false); - expect(_v4.isNumeric(' ')).to.be(false); - expect(_v4.isNumeric('\t\t')).to.be(false); - expect(_v4.isNumeric('abcdefghijklm1234567890')).to.be(false); - expect(_v4.isNumeric('xabcdefx')).to.be(false); - expect(_v4.isNumeric(true)).to.be(false); - expect(_v4.isNumeric(false)).to.be(false); - expect(_v4.isNumeric('bcfed5.2')).to.be(false); - expect(_v4.isNumeric('7.2acdgs')).to.be(false); - expect(_v4.isNumeric(undefined)).to.be(false); - expect(_v4.isNumeric(null)).to.be(false); - expect(_v4.isNumeric(NaN)).to.be(false); - expect(_v4.isNumeric(Infinity)).to.be(false); - expect(_v4.isNumeric(Number.POSITIVE_INFINITY)).to.be(false); - expect(_v4.isNumeric(Number.NEGATIVE_INFINITY)).to.be(false); - expect(_v4.isNumeric(new Date(2009, 1, 1))).to.be(false); - expect(_v4.isNumeric([])).to.be(false); - expect(_v4.isNumeric([1, 2, 3, 4])).to.be(false); - expect(_v4.isNumeric({})).to.be(false); - expect(_v4.isNumeric(function () {})).to.be(false); + expect(_.isNumeric('')).to.be(false); + expect(_.isNumeric(' ')).to.be(false); + expect(_.isNumeric('\t\t')).to.be(false); + expect(_.isNumeric('abcdefghijklm1234567890')).to.be(false); + expect(_.isNumeric('xabcdefx')).to.be(false); + expect(_.isNumeric(true)).to.be(false); + expect(_.isNumeric(false)).to.be(false); + expect(_.isNumeric('bcfed5.2')).to.be(false); + expect(_.isNumeric('7.2acdgs')).to.be(false); + expect(_.isNumeric(undefined)).to.be(false); + expect(_.isNumeric(null)).to.be(false); + expect(_.isNumeric(NaN)).to.be(false); + expect(_.isNumeric(Infinity)).to.be(false); + expect(_.isNumeric(Number.POSITIVE_INFINITY)).to.be(false); + expect(_.isNumeric(Number.NEGATIVE_INFINITY)).to.be(false); + expect(_.isNumeric(new Date(2009, 1, 1))).to.be(false); + expect(_.isNumeric([])).to.be(false); + expect(_.isNumeric([1, 2, 3, 4])).to.be(false); + expect(_.isNumeric({})).to.be(false); + expect(_.isNumeric(function () {})).to.be(false); }); }); describe('#isInterval', function () { - _v4.forEach({ + _.forEach({ M: 'months', w: 'weeks', d: 'days', @@ -104,20 +104,20 @@ describe('Utils', function () { }, function (name, unit) { it('likes ' + name, function () { - expect(_v4.isInterval('1' + unit)).to.be(true); + expect(_.isInterval('1' + unit)).to.be(true); }); it('likes decimal ' + name, function () { - expect(_v4.isInterval('1.5' + unit)).to.be(true); + expect(_.isInterval('1.5' + unit)).to.be(true); }); }); it('dislikes more than one unit', function () { - expect(_v4.isInterval('1my')).to.be(false); + expect(_.isInterval('1my')).to.be(false); }); it('dislikes spaces', function () { - expect(_v4.isInterval('1 m')).to.be(false); + expect(_.isInterval('1 m')).to.be(false); }); }); }); @@ -127,108 +127,108 @@ describe('Utils', function () { describe('#camelCase', function () { it('find spaces, underscores, and other natural word breaks', function () { - expect(_v4.camelCase('Neil Patrick.Harris-is_a.dog')).to.eql('neilPatrickHarrisIsADog'); + expect(_.camelCase('Neil Patrick.Harris-is_a.dog')).to.eql('neilPatrickHarrisIsADog'); }); it('ignores abreviations', function () { - expect(_v4.camelCase('Json_parser')).to.eql('jsonParser'); + expect(_.camelCase('Json_parser')).to.eql('jsonParser'); }); it('handles leading _', function () { - expect(_v4.camelCase('_thing_one_')).to.eql('_thingOne'); + expect(_.camelCase('_thing_one_')).to.eql('_thingOne'); }); it('works on numbers', function () { - expect(_v4.camelCase('version 1.0')).to.eql('version10'); + expect(_.camelCase('version 1.0')).to.eql('version10'); }); }); describe('#studlyCase', function () { it('find spaces, underscores, and other natural word breaks', function () { - expect(_v4.studlyCase('Neil Patrick.Harris-is_a.dog')).to.eql('NeilPatrickHarrisIsADog'); + expect(_.studlyCase('Neil Patrick.Harris-is_a.dog')).to.eql('NeilPatrickHarrisIsADog'); }); it('ignores abreviations', function () { - expect(_v4.studlyCase('Json_parser')).to.eql('JsonParser'); + expect(_.studlyCase('Json_parser')).to.eql('JsonParser'); }); it('handles leading _', function () { - expect(_v4.studlyCase('_thing_one_')).to.eql('_ThingOne'); + expect(_.studlyCase('_thing_one_')).to.eql('_ThingOne'); }); it('works on numbers', function () { - expect(_v4.studlyCase('version 1.0')).to.eql('Version10'); + expect(_.studlyCase('version 1.0')).to.eql('Version10'); }); }); describe('#snakeCase', function () { it('find spaces, underscores, and other natural word breaks', function () { - expect(_v4.snakeCase('Neil Patrick.Harris-is_a.dog')).to.eql('neil_patrick_harris_is_a_dog'); + expect(_.snakeCase('Neil Patrick.Harris-is_a.dog')).to.eql('neil_patrick_harris_is_a_dog'); }); it('ignores abreviations', function () { - expect(_v4.snakeCase('Json_parser')).to.eql('json_parser'); + expect(_.snakeCase('Json_parser')).to.eql('json_parser'); }); it('handles leading _', function () { - expect(_v4.snakeCase('_thing_one_')).to.eql('_thing_one'); + expect(_.snakeCase('_thing_one_')).to.eql('_thing_one'); }); it('works on numbers', function () { - expect(_v4.snakeCase('version 1.0')).to.eql('version_1_0'); + expect(_.snakeCase('version 1.0')).to.eql('version_1_0'); }); }); describe('#toLowerString', function () { it('transforms normal strings', function () { - expect(_v4.toLowerString('PASTA')).to.eql('pasta'); + expect(_.toLowerString('PASTA')).to.eql('pasta'); }); it('ignores long form empty vals (null, false, undef)', function () { - expect(_v4.toLowerString(null)).to.eql(''); - expect(_v4.toLowerString(false)).to.eql(''); - expect(_v4.toLowerString(void 0)).to.eql(''); + expect(_.toLowerString(null)).to.eql(''); + expect(_.toLowerString(false)).to.eql(''); + expect(_.toLowerString(void 0)).to.eql(''); }); it('uses the objects own toString', function () { - expect(_v4.toLowerString(['A', 'B'])).to.eql('a,b'); + expect(_.toLowerString(['A', 'B'])).to.eql('a,b'); }); it('sorta kinda works on objects', function () { - expect(_v4.toLowerString({ a: 'thing' })).to.eql('[object object]'); + expect(_.toLowerString({ a: 'thing' })).to.eql('[object object]'); }); }); describe('#toUpperString', function () { it('transforms normal strings', function () { - expect(_v4.toUpperString('PASTA')).to.eql('PASTA'); + expect(_.toUpperString('PASTA')).to.eql('PASTA'); }); it('ignores long form empty vals (null, false, undef)', function () { - expect(_v4.toUpperString(null)).to.eql(''); - expect(_v4.toUpperString(false)).to.eql(''); - expect(_v4.toUpperString(void 0)).to.eql(''); + expect(_.toUpperString(null)).to.eql(''); + expect(_.toUpperString(false)).to.eql(''); + expect(_.toUpperString(void 0)).to.eql(''); }); it('uses the objects own toString', function () { - expect(_v4.toUpperString(['A', 'B'])).to.eql('A,B'); + expect(_.toUpperString(['A', 'B'])).to.eql('A,B'); }); it('sorta kinda works on objects', function () { - expect(_v4.toUpperString({ a: 'thing' })).to.eql('[OBJECT OBJECT]'); + expect(_.toUpperString({ a: 'thing' })).to.eql('[OBJECT OBJECT]'); }); }); describe('#repeat', function () { it('repeats strings', function () { - expect(_v4.repeat(' ', 5)).to.eql(' '); - expect(_v4.repeat('foobar', 2)).to.eql('foobarfoobar'); + expect(_.repeat(' ', 5)).to.eql(' '); + expect(_.repeat('foobar', 2)).to.eql('foobarfoobar'); }); }); describe('#ucfirst', function () { it('only capitalized the first letter, lowercases everything else', function () { - expect(_v4.ucfirst('ALGER')).to.eql('Alger'); + expect(_.ucfirst('ALGER')).to.eql('Alger'); }); }); @@ -241,14 +241,14 @@ describe('Utils', function () { var obj = { foo: 'bar' }; - expect(_v4.deepMerge(obj, { bar: 'baz' })).to.eql(obj); + expect(_.deepMerge(obj, { bar: 'baz' })).to.eql(obj); }); it('concats arrays', function () { var obj = { foo: ['bax', 'boz'] }; - _v4.deepMerge(obj, { foo: ['boop'] }); + _.deepMerge(obj, { foo: ['boop'] }); expect(obj.foo).to.have.length(3); }); @@ -256,7 +256,7 @@ describe('Utils', function () { var obj = { foo: ['stop', 'foo', 'stahp'] }; - _v4.deepMerge(obj, { foo: 'string' }); + _.deepMerge(obj, { foo: 'string' }); expect(obj.foo).to.have.length(3); }); @@ -267,7 +267,7 @@ describe('Utils', function () { foo: ['bax', 'boz'] } }; - _v4.deepMerge(obj, { bax: { foo: ['poo'] } }); + _.deepMerge(obj, { bax: { foo: ['poo'] } }); expect(obj.bax.foo).to.have.length(3); }); @@ -276,26 +276,26 @@ describe('Utils', function () { describe('#createArray', function () { it('accepts an array of things and simply returns a copy of it', function () { var inp = [{ a: 1 }, 'pizza']; - var out = _v4.createArray(inp); + var out = _.createArray(inp); expect(out).to.eql(inp); expect(out).to.not.be(inp); }); it('accepts a primitive value and calls the the transform function', function (done) { - _v4.createArray('str', function (val) { + _.createArray('str', function (val) { expect(val).to.be('str'); done(); }); }); it('wraps any non-array in an array', function () { - expect(_v4.createArray({})).to.eql([{}]); - expect(_v4.createArray('')).to.eql(['']); - expect(_v4.createArray(123)).to.eql([123]); - expect(_v4.createArray(/abc/)).to.eql([/abc/]); - expect(_v4.createArray(false)).to.eql([false]); + expect(_.createArray({})).to.eql([{}]); + expect(_.createArray('')).to.eql(['']); + expect(_.createArray(123)).to.eql([123]); + expect(_.createArray(/abc/)).to.eql([/abc/]); + expect(_.createArray(false)).to.eql([false]); }); it('returns false when the transform function returns undefined', function () { - expect(_v4.createArray(['str', 1], function (val) { - if (_v4.isString(val)) { + expect(_.createArray(['str', 1], function (val) { + if (_.isString(val)) { return { val: val }; @@ -306,27 +306,27 @@ describe('Utils', function () { describe('#funcEnum', function () { /* - * _v4.funcEnum(object, key, opts, default); + * _.funcEnum(object, key, opts, default); */ it('tests if the value at key in object is a function, returns it if so', function () { var config = { func: function () {} }; - expect(_v4.funcEnum(config, 'func', {}, 'toString')) + expect(_.funcEnum(config, 'func', {}, 'toString')) .to.be(config.func); }); it('tests if the value at key in object is undefined, returns the option at key default if so', function () { var config = { func: undefined }; - expect(_v4.funcEnum(config, 'func', {}, 'toString')) + expect(_.funcEnum(config, 'func', {}, 'toString')) .to.be(Object.prototype.toString); }); it('tests if the value at key in object is a string, returns the option at that key if so', function () { var config = { 'config key name': 'toString' }; - expect(_v4.funcEnum(config, 'config key name', { toString: 'pizza' }, 'toJSON')) + expect(_.funcEnum(config, 'config key name', { toString: 'pizza' }, 'toJSON')) .to.be('pizza'); }); it('throws an informative error if the selection if invalid', function () { @@ -335,21 +335,21 @@ describe('Utils', function () { }; expect(function () { - _v4.funcEnum(config, 'config', {}); + _.funcEnum(config, 'config', {}); }).to.throwError(/expected a function/i); expect(function () { - _v4.funcEnum(config, 'config', { main: 'default' }, 'main'); + _.funcEnum(config, 'config', { main: 'default' }, 'main'); }).to.throwError(/expected a function or main/i); expect(function () { - _v4.funcEnum(config, 'config', { main: 'default', other: 'default' }, 'main'); + _.funcEnum(config, 'config', { main: 'default', other: 'default' }, 'main'); }).to.throwError(/expected a function or one of main, other/i); }); }); describe('#applyArgs', function () { - _v4.times(10, function (i) { + _.times(10, function (i) { var method = i > 5 ? 'apply' : 'call'; var argCount = i + 1; var slice = 1; @@ -358,8 +358,8 @@ describe('Utils', function () { var func = function () {}; stub(func, method); - var args = _v4.map(new Array(i), function (val, i) { return i; }); - _v4.applyArgs(func, null, args); + var args = _.map(new Array(i), function (val, i) { return i; }); + _.applyArgs(func, null, args); expect(func[method].callCount).to.eql(1); if (method === 'apply') { @@ -374,9 +374,9 @@ describe('Utils', function () { var func = function () {}; stub(func, method); - var args = _v4.map(new Array(argCount), function (val, i) { return i; }); + var args = _.map(new Array(argCount), function (val, i) { return i; }); var expected = args.slice(slice); - _v4.applyArgs(func, null, args, slice); + _.applyArgs(func, null, args, slice); expect(func[method].callCount).to.eql(1); if (method === 'apply') { @@ -390,24 +390,24 @@ describe('Utils', function () { describe('#getUnwrittenFromStream', function () { it('ignores things that do not have writableState', function () { - expect(_v4.getUnwrittenFromStream()).to.be(undefined); - expect(_v4.getUnwrittenFromStream(false)).to.be(undefined); - expect(_v4.getUnwrittenFromStream([])).to.be(undefined); - expect(_v4.getUnwrittenFromStream({})).to.be(undefined); + expect(_.getUnwrittenFromStream()).to.be(undefined); + expect(_.getUnwrittenFromStream(false)).to.be(undefined); + expect(_.getUnwrittenFromStream([])).to.be(undefined); + expect(_.getUnwrittenFromStream({})).to.be(undefined); }); if (require('stream').Writable) { var MockWritableStream = require('../../mocks/writable_stream'); it('ignores empty stream', function () { var stream = new MockWritableStream(); - expect(_v4.getUnwrittenFromStream(stream)).to.be(''); + expect(_.getUnwrittenFromStream(stream)).to.be(''); }); it('returns only what is in the buffer', function () { var stream = new MockWritableStream(); stream.write('hot'); stream.write('dog'); - expect(_v4.getUnwrittenFromStream(stream)).to.be('dog'); + expect(_.getUnwrittenFromStream(stream)).to.be('dog'); }); } }); diff --git a/test/utils/expect_sub_object.js b/test/utils/expect_sub_object.js index 7499206c1..013be8a5b 100644 --- a/test/utils/expect_sub_object.js +++ b/test/utils/expect_sub_object.js @@ -1,7 +1,7 @@ -// var _ = require('lodash'); +var _ = require('lodash'); var expect = require('expect.js'); module.exports = function expectSubObject(obj, subObj) { - _v4.forOwn(subObj, function (val, prop) { + _.forOwn(subObj, function (val, prop) { if (typeof obj[prop] === 'object') { // non-strict equals expect(obj[prop]).to.eql(val, 'Expected property' + prop + ' of object to equal ' + val); diff --git a/test/utils/jenkins-reporter.js b/test/utils/jenkins-reporter.js index 7399d00f9..48c5de673 100644 --- a/test/utils/jenkins-reporter.js +++ b/test/utils/jenkins-reporter.js @@ -7,7 +7,7 @@ module.exports = JenkinsReporter; var Base = require('mocha/lib/reporters/base'); -// var _ = require('lodash'); +var _ = require('lodash'); var chalk = require('chalk'); var makeJUnitXml = require('./make_j_unit_xml'); var fs = require('fs'); @@ -15,7 +15,7 @@ var path = require('path'); var inspect = require('util').inspect; var log = (function () { - var locked = _v4.bind(process.stdout.write, process.stdout); + var locked = _.bind(process.stdout.write, process.stdout); return function (str) { if (typeof str !== 'string') { str = inspect(str); @@ -24,8 +24,8 @@ var log = (function () { }; }()); -var integration = _v4.find(process.argv, function (arg) { return arg.indexOf('test/integration') > -1; }); -var unit = _v4.find(process.argv, function (arg) { return arg.indexOf('test/unit') > -1; }); +var integration = _.find(process.argv, function (arg) { return arg.indexOf('test/integration') > -1; }); +var unit = _.find(process.argv, function (arg) { return arg.indexOf('test/unit') > -1; }); var output; if (unit) { @@ -126,7 +126,7 @@ function JenkinsReporter(runner) { errMsg += '\n(' + test.err.sourceURL + ':' + test.err.line + ')'; } - console.error(_v4.map(errMsg.split('\n'), function (line) { + console.error(_.map(errMsg.split('\n'), function (line) { return indt() + ' ' + line; }).join('\n')); } @@ -146,7 +146,7 @@ function JenkinsReporter(runner) { runner.on('hook end', function (hook) { if (hook.title.indexOf('"after each"') > -1 && stack[0] && stack[0].results.length) { - var result = _v4.last(stack[0].results); + var result = _.last(stack[0].results); result.stdout += stack[0].stdout; result.stderr += stack[0].stderr; stack[0].stdout = stack[0].stderr = ''; @@ -157,7 +157,7 @@ function JenkinsReporter(runner) { restoreStdio(); var xml = makeJUnitXml('node ' + process.version, { stats: stats, - suites: _v4.map(rootSuite.suites, function removeElements(suite) { + suites: _.map(rootSuite.suites, function removeElements(suite) { var s = { name: suite.name, start: suite.start, @@ -168,7 +168,7 @@ function JenkinsReporter(runner) { }; if (suite.suites) { - s.suites = _v4.map(suite.suites, removeElements); + s.suites = _.map(suite.suites, removeElements); } return s; }) diff --git a/test/utils/make_j_unit_xml.js b/test/utils/make_j_unit_xml.js index 2744d1b8d..6474afa12 100644 --- a/test/utils/make_j_unit_xml.js +++ b/test/utils/make_j_unit_xml.js @@ -28,11 +28,11 @@ var testXml = require('xmlbuilder'); var suites = testXml.create('testsuites'); var suiteCount = 0; var moment = require('moment'); -// var _ = require('lodash'); +var _ = require('lodash'); var chalk = require('chalk'); function makeJUnitXml(runnerName, testDetails) { - _v4.each(testDetails.suites, function serializeSuite(suiteInfo) { + _.each(testDetails.suites, function serializeSuite(suiteInfo) { var suite = suites.ele('testsuite', { package: 'elasticsearch-js', @@ -41,12 +41,12 @@ function makeJUnitXml(runnerName, testDetails) { timestamp: moment(suiteInfo.start).toJSON(), hostname: 'localhost', tests: (suiteInfo.results && suiteInfo.results.length) || 0, - failures: _v4.filter(suiteInfo.results, { pass: false }).length, + failures: _.filter(suiteInfo.results, { pass: false }).length, errors: 0, time: suiteInfo.time / 1000 }); - _v4.each(suiteInfo.results, function (testInfo) { + _.each(suiteInfo.results, function (testInfo) { var section; var integration = false; @@ -83,7 +83,7 @@ function makeJUnitXml(runnerName, testDetails) { }); if (suiteInfo.suites) { - _v4.each(suiteInfo.suites, serializeSuite); + _.each(suiteInfo.suites, serializeSuite); } giveOutput(suite, suiteInfo); diff --git a/test/utils/server.js b/test/utils/server.js index 9484020cf..bb1770e04 100644 --- a/test/utils/server.js +++ b/test/utils/server.js @@ -2,7 +2,7 @@ var express = require('express'); var http = require('http'); var fs = require('fs'); -// var _ = require('lodash'); +var _ = require('lodash'); var async = require('async'); var root = require('path').join(__dirname, '../..'); var browserify = require('browserify'); @@ -12,7 +12,7 @@ var browserBuildsDir = root + '/test/unit/browser_builds'; var testFiles = {}; -testFiles.unit = _v4(fs.readdirSync(unitSpecDir)) +testFiles.unit = _(fs.readdirSync(unitSpecDir)) .difference([ 'file_logger.js', 'http_connector.js', From aae2f427a178f91e8dff20938d5009416c762908 Mon Sep 17 00:00:00 2001 From: spalger Date: Thu, 19 May 2016 14:39:27 -0700 Subject: [PATCH 15/15] revert incorrect utils -> _ replacements --- src/lib/utils.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/lib/utils.js b/src/lib/utils.js index 40cf01021..c05d6d817 100644 --- a/src/lib/utils.js +++ b/src/lib/utils.js @@ -2,11 +2,11 @@ var path = require('path'); var nodeUtils = require('util'); /** - * Custom _ library, basically a modified version of [lodash](http://lodash.com/docs) + - * [node._](http://nodejs.org/api/util.html#util_util) that doesn't use mixins to prevent + * Custom utils library, basically a modified version of [lodash](http://lodash.com/docs) + + * [node.utils](http://nodejs.org/api/util.html#util_util) that doesn't use mixins to prevent * confusion when requiring lodash itself. * - * @class _ + * @class utils * @static */ var _ = require('lodash').assign({}, require('lodash'), nodeUtils);