diff --git a/clusterctl.js b/clusterctl.js index 7f1161f7..b1ae99bd 100644 --- a/clusterctl.js +++ b/clusterctl.js @@ -69,7 +69,7 @@ class Command { } async run(args, control) { - await this._handler.call(this, args, control); + await this._handler(args, control); } } diff --git a/lib/config/classes.js b/lib/config/classes.js index 7aaf1890..ca369270 100644 --- a/lib/config/classes.js +++ b/lib/config/classes.js @@ -395,7 +395,7 @@ class ConfigGroup { value = Number.parseFloat(value); } - } else if (def.type === "object" ) { + } else if (def.type === "object") { try { value = JSON.parse(value); } catch (err) { @@ -409,10 +409,8 @@ class ConfigGroup { throw new InvalidValue(`Field ${name} cannot be null`); } - } else { - if (basicType(value) !== def.type) { - throw new InvalidValue(`Expected type of ${name} to be ${def.type}, not ${basicType(value)}`); - } + } else if (basicType(value) !== def.type) { + throw new InvalidValue(`Expected type of ${name} to be ${def.type}, not ${basicType(value)}`); } let prev = this._fields.get(name); @@ -493,10 +491,9 @@ class ConfigGroup { if (value !== null && basicType(value) !== def.type) { continue; } - } else { - if (basicType(value) !== def.type) { - continue; - } + + } else if (basicType(value) !== def.type) { + continue; } if (def.enum && !def.enum.includes(value)) { @@ -655,10 +652,11 @@ class ConfigGroup { throw new Error(`Config field ${item.name} has already been defined`); } - let computed = Object.assign({ + let computed = { optional: false, fullName: `${this.groupName}.${item.name}`, - }, item); + ...item, + }; if (!computed.optional && computed.initial_value === undefined) { throw new Error(`Non-optional field ${item.name} needs an initial_value`); diff --git a/lib/database.js b/lib/database.js index 76394c3a..74b59853 100644 --- a/lib/database.js +++ b/lib/database.js @@ -144,7 +144,6 @@ async function saveMapAsJsonArray(filePath, map) { } - function checkName(name) { if (typeof name !== "string") { throw new Error("name must be a string"); diff --git a/lib/factorio/export.js b/lib/factorio/export.js index 8f6e72c6..c1ac3da5 100644 --- a/lib/factorio/export.js +++ b/lib/factorio/export.js @@ -196,6 +196,7 @@ async function exportItems(server, modVersions, items) { iconLayer.scale(realScale); } + // eslint-disable-next-line no-loop-func iconLayer.scan(0, 0, iconLayer.bitmap.width, iconLayer.bitmap.height, function(x, y, sidx) { x += xs; y += ys; diff --git a/lib/factorio/server.js b/lib/factorio/server.js index 0ca12a86..9b2a033b 100644 --- a/lib/factorio/server.js +++ b/lib/factorio/server.js @@ -167,9 +167,9 @@ function randomDynamicPort() { async function generatePassword(length) { function validChar(byte) { const ranges = ["az", "AZ", "09"]; - return ranges.some(range => + return ranges.some(range => ( range.codePointAt(0) <= byte && byte <= range.codePointAt(1) - ); + )); } let randomBytesAsync = util.promisify(crypto.randomBytes); @@ -559,9 +559,9 @@ class FactorioServer extends events.EventEmitter { let channel = line .slice(6, channelEnd) .toString("utf-8") - .replace(/\\x([0-9a-f]{2})/g, (match, p1) => + .replace(/\\x([0-9a-f]{2})/g, (match, p1) => ( String.fromCharCode(parseInt(p1, 16)) - ) + )) ; let type = line.slice(channelEnd + 1, channelEnd + 2).toString("utf-8"); @@ -619,10 +619,8 @@ class FactorioServer extends events.EventEmitter { if (!expected.includes(output[name])) { continue heuristicLoop; } - } else { - if (expected !== output[name]) { - continue heuristicLoop; - } + } else if (expected !== output[name]) { + continue heuristicLoop; } } @@ -651,7 +649,7 @@ class FactorioServer extends events.EventEmitter { }; this._rconClient = new rconClient.Rcon(config); - this._rconClient.on("error", err => { /* Ignore */ }); + this._rconClient.on("error", () => { /* Ignore */ }); this._rconClient.on("authenticated", () => { this._rconReady = true; this.emit("rcon-ready"); }); this._rconClient.on("end", () => { this._rconClient = null; diff --git a/lib/fileOps/index.js b/lib/fileOps/index.js index 58f925fe..0e9bcbe8 100644 --- a/lib/fileOps/index.js +++ b/lib/fileOps/index.js @@ -1,3 +1,3 @@ "use strict"; const fileOps = require("./fileOps"); -module.exports = fileOps; \ No newline at end of file +module.exports = fileOps; diff --git a/lib/link/connectors.js b/lib/link/connectors.js index 75682dd6..a7997f0a 100644 --- a/lib/link/connectors.js +++ b/lib/link/connectors.js @@ -310,18 +310,6 @@ class WebSocketClientConnector extends WebSocketBaseConnector { console.error("SOCKET | Error:", err); }); - /* - this._socket.on("unexpected-response", (req, res) => { - let data = ""; - res.on('data', (chunk) => { data += chunk; }); - res.on('end', () => { - console.error(`SOCKET | Unexpeced Response ${res.statusCode}`); - console.error(data); - this._socket.emit("error", new Error(`Unexpected Response ${res.statusCode}`)); - }); - }); - */ - this._socket.on("open", () => { console.log("SOCKET | Open"); }); diff --git a/lib/link/messages.js b/lib/link/messages.js index 85c0e9d3..fd0d0876 100644 --- a/lib/link/messages.js +++ b/lib/link/messages.js @@ -11,8 +11,8 @@ const errors = require("lib/errors"); class Message { /** * Name of the plugin this message belongs to, or null. - * @returns {?string} - **/ + * @returns {?string} - plugin name or null if not from a plugin. + */ get plugin() { if (this._plugin === undefined) { let index = this.type.indexOf(":"); @@ -78,9 +78,10 @@ class Request extends Message { } if (forwardTo === "instance") { - requestProperties = Object.assign( - { "instance_id": { type: "integer" }}, requestProperties - ); + requestProperties = { + "instance_id": { type: "integer" }, + ...requestProperties, + }; } else if (forwardTo !== "master" && forwardTo !== null) { throw new Error(`Invalid forwardTo value ${forwardTo}`); @@ -635,9 +636,10 @@ class Event extends Message { this.broadcastTo = broadcastTo; if (forwardTo === "instance") { - eventProperties = Object.assign( - { "instance_id": { type: "integer" }}, eventProperties - ); + eventProperties = { + "instance_id": { type: "integer" }, + ...eventProperties, + }; } else if (forwardTo !== "master" && forwardTo !== null) { throw new Error(`Invalid forwardTo value ${forwardTo}`); diff --git a/lib/manager/modManager.js b/lib/manager/modManager.js index 8dc0fabb..19fb28ac 100644 --- a/lib/manager/modManager.js +++ b/lib/manager/modManager.js @@ -1,3 +1,5 @@ +// This file will be rewritten from scratch +/* eslint-disable */ /** Provides tools to manage mods in a clusterio install @module diff --git a/lib/npmPostinstall.js b/lib/npmPostinstall.js index 4c88a1b2..cc23a327 100644 --- a/lib/npmPostinstall.js +++ b/lib/npmPostinstall.js @@ -26,7 +26,7 @@ function download(url, file, callback){ // this might be an invalid path! fs.stat(pathArray.join("/"), (err, stat) => { if(err){ - makeDirectory(pathArray.join("/")).then(()=>{ + makeDirectory(pathArray.join("/")).then(() => { doDownload(url, file, callback); }); } else { @@ -82,7 +82,7 @@ let downloadList = [ // initiate folder creations and downloads function processMkdirRecursive(callback){ let item = directories.shift(); - makeDirectory(item).then(()=>{ + makeDirectory(item).then(() => { if(directories.length == 0){ if(callback) callback(); } else { @@ -92,7 +92,7 @@ function processMkdirRecursive(callback){ } function processDownloadRecursive(callback){ let item = downloadList.shift(); - download(item.url, item.file, item.callback).then(()=>{ + download(item.url, item.file, item.callback).then(() => { if(downloadList.length == 0){ if(callback) callback(); } else { diff --git a/lib/objectOps.js b/lib/objectOps.js index 5968d543..1fe093cc 100644 --- a/lib/objectOps.js +++ b/lib/objectOps.js @@ -1,35 +1,36 @@ /** -Helper functions related to objects -@module -*/ + * Helper functions related to objects + * @module + */ "use strict"; /** -Deep clones an object, is actually just JSON.parse(JSON.stringify()) but looks cleaner. -@param {object} obj to clone -@returns {object} The cloned object. - -@example -a = {"thingy":"with a value"}; -b = a; -a == b; // true -c = objectOps.deepclone(a); -a == c; // false -*/ + * Deep clones an object, is actually just JSON.parse(JSON.stringify()) but looks cleaner. + * @param {object} obj to clone + * @returns {object} The cloned object. + * + * @example + * a = {"thingy":"with a value"}; + * b = a; + * a == b; // true + * c = objectOps.deepclone(a); + * a == c; // false + */ module.exports.deepclone = function(obj){ return JSON.parse(JSON.stringify(obj)); }; -/** -Checks if a string is valid JSON using try/catch. If passed an object it will always return true. -@param {string} string to verify -@returns {boolean} true if valid JSON. -@example -objectOps.isJSON("99 bottles of beer"); // false -objectOps.isJSON("99"); // true -objectOps.isJSON({"thingy":"that is an object"}); // true -objectOps.isJSON(JSON.stringify({"thingy":"that is an object"})); // true -*/ +/** + * Checks if a string is valid JSON using try/catch. If passed an object it will always return true. + * @param {string} string to verify + * @returns {boolean} true if valid JSON. + * + * @example + * objectOps.isJSON("99 bottles of beer"); // false + * objectOps.isJSON("99"); // true + * objectOps.isJSON({"thingy":"that is an object"}); // true + * objectOps.isJSON(JSON.stringify({"thingy":"that is an object"})); // true + */ module.exports.isJSON = function(string){ let stringIsJson = false; let x; diff --git a/lib/prometheus.js b/lib/prometheus.js index 236a0d82..b461d60d 100644 --- a/lib/prometheus.js +++ b/lib/prometheus.js @@ -167,9 +167,9 @@ class ValueCollector extends Collector { function removeMatchingLabels(mapping, labels) { for (let key of mapping.keys()) { let candidate = keyToLabels(key); - let hasLabels = Object.entries(labels).every(([name, value]) => { - return candidate.get(name) === value; - }); + let hasLabels = Object.entries(labels).every(([name, value]) => ( + candidate.get(name) === value + )); if (hasLabels) { mapping.delete(key); } diff --git a/lib/schema.js b/lib/schema.js index 867f2497..66f038bd 100644 --- a/lib/schema.js +++ b/lib/schema.js @@ -74,7 +74,7 @@ const serverHandshake = ajv.compile({ $schema: "http://json-schema.org/draft-07/schema#", title: "Server Handshake", description: "Message sent from the server to a client during the handshake", - allOf: [ messageSchema ], + allOf: [messageSchema], anyOf: [ { properties: { @@ -137,7 +137,7 @@ const clientHandshake = ajv.compile({ $schema: "http://json-schema.org/draft-07/schema#", title: "Client Message", description: "Message sent from a client to the server", - allOf: [ messageSchema ], + allOf: [messageSchema], anyOf: [ { properties: { diff --git a/master.js b/master.js index 1b8bc7c1..234bd8bc 100644 --- a/master.js +++ b/master.js @@ -535,7 +535,7 @@ class BaseConnection extends link.Link { } } -let controlConnections = new Array(); +let controlConnections = []; class ControlConnection extends BaseConnection { constructor(registerData, connector, user) { super("control", connector); @@ -560,7 +560,7 @@ class ControlConnection extends BaseConnection { this.ws_dumper = null; this.connector.on("connect", () => { - this.connector._socket.clusterio_ignore_dump = !!this.ws_dumper; + this.connector._socket.clusterio_ignore_dump = Boolean(this.ws_dumper); }); this.connector.on("close", () => { if (this.ws_dumper) { @@ -880,6 +880,7 @@ class SlaveConnection extends BaseConnection { }); for (let event of ["connect", "drop", "close"]) { + // eslint-disable-next-line no-loop-func this.connector.on(event, () => { for (let masterPlugin of masterPlugins.values()) { masterPlugin.onSlaveConnectionEvent(this, event); @@ -991,7 +992,7 @@ const wss = new WebSocket.Server({ * 231-1. */ function isInteger(value) { - return value | 0 === value; + return (value | 0) === value; } diff --git a/plugins/research_sync/master.js b/plugins/research_sync/master.js index 060b19e6..a6f0cbd4 100644 --- a/plugins/research_sync/master.js +++ b/plugins/research_sync/master.js @@ -112,7 +112,7 @@ class MasterPlugin extends plugin.BaseMasterPlugin { } for (let instanceTech of message.data.technologies) { - let [name, level, progress, researched] = instanceTech; + let [name, level, progress, researched] = instanceTech; let tech = this.technologies.get(name); if (!tech) { this.technologies.set(name, { level, progress, researched }); @@ -152,7 +152,7 @@ class MasterPlugin extends plugin.BaseMasterPlugin { let technologies = []; for (let [name, tech] of this.technologies) { - technologies.push([ name, tech.level, tech.progress, tech.researched ]); + technologies.push([name, tech.level, tech.progress, tech.researched]); } return { technologies }; diff --git a/plugins/subspace_storage/dole.js b/plugins/subspace_storage/dole.js index 60db186b..fe06bb3a 100644 --- a/plugins/subspace_storage/dole.js +++ b/plugins/subspace_storage/dole.js @@ -16,7 +16,7 @@ const prometheusDoleFactorGauge = new prometheus.Gauge( ); class neuralDole { - + getRequestStats(itemname,samples) { var sum=0; @@ -28,7 +28,7 @@ class neuralDole { if (sum==0) return 0.1; return sum/samples; } - + constructor({ items, }){ @@ -41,6 +41,7 @@ class neuralDole { this.stats=[]; this.debt= {}; } + doMagic() { for (let [name, count] of this.items._items) { let magicData = doleNN.Tick( @@ -50,7 +51,7 @@ class neuralDole { this.getRequestStats(name,5) ); this.stats[name]=this.stats[name] || []; - this.stats[name].unshift({ req:0,given:0 });//stats[name][0] is the one we currently collect + this.stats[name].unshift({ req: 0, given: 0 });//stats[name][0] is the one we currently collect if (this.stats[name].length>10) this.stats[name].pop();//remove if too many samples in stats this.dole[name] = magicData[0]; @@ -59,6 +60,7 @@ class neuralDole { } this.itemsLastTick = new Map(this.items._items); } + divider(object) { let magicData = doleNN.Dose( object.count, // numReq @@ -100,7 +102,7 @@ function doleDivider({ let itemCount = items.getItemCount(object.name); const doleDivisionRetardation = 10; //lower rates will equal more dramatic swings const maxDoleDivision = 250; //a higher cap will divide the store more ways, but will take longer to recover as supplies increase - + const originalCount = Number(object.count) || 0; object.count /= ((_doleDivisionFactor[object.name]||0)+doleDivisionRetardation)/doleDivisionRetardation; object.count = Math.round(object.count); @@ -128,4 +130,4 @@ function doleDivider({ module.exports = { doleDivider, neuralDole, -}; \ No newline at end of file +}; diff --git a/plugins/subspace_storage/dole_nn_base.js b/plugins/subspace_storage/dole_nn_base.js index 314b1931..dc978ebc 100644 --- a/plugins/subspace_storage/dole_nn_base.js +++ b/plugins/subspace_storage/dole_nn_base.js @@ -47,7 +47,7 @@ function Dose(numreq,instore,store_last_tick,dole,carry,prev_req,numreq_total_ad instore=Number(instore); var instore_adj=instore; if (instore_adj==0) instore_adj=0.1; - + var b=Math.trunc(prev_req/instore_adj*numreq); var inp1=[numreq,instore_adj,store_last_tick/numreq,dole,carry];//0..4 var inp2=[prev_req/numreq,numreq/numreq_total_adj,store_last_tick/numreq_total_adj,prev_req/instore_adj,b,numreq_total_adj,store_last_tick,debt];//5..12 @@ -55,7 +55,7 @@ function Dose(numreq,instore,store_last_tick,dole,carry,prev_req,numreq_total_ad var internal=new Array(20).fill(0); var outputs=[0,0,0,0]; //NN: Please don't touch :), code is generated - + outputs[0]=inputs[7]*0.8058582544; outputs[0]=sigmoid2(outputs[0]); outputs[1]=sigmoid0(outputs[1]); @@ -65,20 +65,20 @@ function Dose(numreq,instore,store_last_tick,dole,carry,prev_req,numreq_total_ad debt=debt || 0; if (outputs[0]>0.99) outputs[0]=1.0; - + var res1=Number(outputs[0])*numreq+outputs[3]+debt; var res_capped=Math.round(res1); - + if (res_capped>numreq) res_capped=numreq; if (res_capped>instore) res_capped=instore; if (res_capped<0) res_capped=0; - + res1=res1 || 0; res_capped=res_capped || 0;//Safeguard against wrong values debt=res1-res_capped; debt_cap=Math.round(numreq*1.5)+5; if (debt>debt_cap) debt=debt_cap; - + carry=sigmoid0(outputs[2]*carry+outputs[0]) || 0; return [res_capped,dole+outputs[1],carry,debt]; } @@ -102,9 +102,9 @@ function Tick(instore,dole,store_last_tick,numreq_total_adj) var internal=new Array(10).fill(0); var outputs=[0,0]; //NN: Please don't touch :), code is generated - + outputs[0]=inputs[3]*0.9364774823; - outputs[0]=outputs[0]*1.0*0.4590721726; + outputs[0]=outputs[0]*0.4590721726; outputs[0]=sigmoid2(outputs[0]); outputs[1]=outputs[0]*1.828422785; outputs[1]=sigmoid3(outputs[1]); @@ -113,8 +113,8 @@ function Tick(instore,dole,store_last_tick,numreq_total_adj) if (numreq_total_adj<0.11) avg=1;//When no item's are requested, result is 0.1 ; In that case there is no deficit, so return 1 = 100% demand fulfilled if (avg>1) avg=1; if (avg<0) avg=0; - + return [sigmoid0(outputs[0]),avg]; } -module.exports = { Dose,Tick }; \ No newline at end of file +module.exports = { Dose,Tick }; diff --git a/plugins/subspace_storage/static/storage.js b/plugins/subspace_storage/static/storage.js index f20f1bac..a2f9157d 100644 --- a/plugins/subspace_storage/static/storage.js +++ b/plugins/subspace_storage/static/storage.js @@ -13,24 +13,24 @@ function drawcontents(data) { data = data.filter(function(item) { return search.test(item.name); }); - + sortByKey(data, "count"); - + const table = document.querySelector("#contents tbody"); //tables have tbody inserted automatically const rows = table.children; - + //update existing rows or create new ones data.forEach(function(item, i) { // format count to have .s in it for large number readability (1,000,000) item.count = item.count.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); - + let row = rows[i]; if(!row) { row = document.createElement("tr"); row.innerHTML = "