mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-20 15:43:13 +09:00
Fix misc problems detected by ESLint
Reformat and clean up issues detected by ESLint.
This commit is contained in:
1 parent
8cb21c5fa8
commit
e9f5cae4f0
34 files changed
+132
-189
No files matched your search
+1
-1
@@ -69,7 +69,7 @@ class Command {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async run(args, control) {
|
async run(args, control) {
|
||||||
await this._handler.call(this, args, control);
|
await this._handler(args, control);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+9
-11
@@ -395,7 +395,7 @@ class ConfigGroup {
|
|||||||
value = Number.parseFloat(value);
|
value = Number.parseFloat(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
} else if (def.type === "object" ) {
|
} else if (def.type === "object") {
|
||||||
try {
|
try {
|
||||||
value = JSON.parse(value);
|
value = JSON.parse(value);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -409,10 +409,8 @@ class ConfigGroup {
|
|||||||
throw new InvalidValue(`Field ${name} cannot be null`);
|
throw new InvalidValue(`Field ${name} cannot be null`);
|
||||||
}
|
}
|
||||||
|
|
||||||
} else {
|
} else if (basicType(value) !== def.type) {
|
||||||
if (basicType(value) !== def.type) {
|
throw new InvalidValue(`Expected type of ${name} to be ${def.type}, not ${basicType(value)}`);
|
||||||
throw new InvalidValue(`Expected type of ${name} to be ${def.type}, not ${basicType(value)}`);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let prev = this._fields.get(name);
|
let prev = this._fields.get(name);
|
||||||
@@ -493,10 +491,9 @@ class ConfigGroup {
|
|||||||
if (value !== null && basicType(value) !== def.type) {
|
if (value !== null && basicType(value) !== def.type) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
if (basicType(value) !== def.type) {
|
} else if (basicType(value) !== def.type) {
|
||||||
continue;
|
continue;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (def.enum && !def.enum.includes(value)) {
|
if (def.enum && !def.enum.includes(value)) {
|
||||||
@@ -655,10 +652,11 @@ class ConfigGroup {
|
|||||||
throw new Error(`Config field ${item.name} has already been defined`);
|
throw new Error(`Config field ${item.name} has already been defined`);
|
||||||
}
|
}
|
||||||
|
|
||||||
let computed = Object.assign({
|
let computed = {
|
||||||
optional: false,
|
optional: false,
|
||||||
fullName: `${this.groupName}.${item.name}`,
|
fullName: `${this.groupName}.${item.name}`,
|
||||||
}, item);
|
...item,
|
||||||
|
};
|
||||||
|
|
||||||
if (!computed.optional && computed.initial_value === undefined) {
|
if (!computed.optional && computed.initial_value === undefined) {
|
||||||
throw new Error(`Non-optional field ${item.name} needs an initial_value`);
|
throw new Error(`Non-optional field ${item.name} needs an initial_value`);
|
||||||
|
|||||||
@@ -144,7 +144,6 @@ async function saveMapAsJsonArray(filePath, map) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
function checkName(name) {
|
function checkName(name) {
|
||||||
if (typeof name !== "string") {
|
if (typeof name !== "string") {
|
||||||
throw new Error("name must be a string");
|
throw new Error("name must be a string");
|
||||||
|
|||||||
@@ -196,6 +196,7 @@ async function exportItems(server, modVersions, items) {
|
|||||||
iconLayer.scale(realScale);
|
iconLayer.scale(realScale);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// eslint-disable-next-line no-loop-func
|
||||||
iconLayer.scan(0, 0, iconLayer.bitmap.width, iconLayer.bitmap.height, function(x, y, sidx) {
|
iconLayer.scan(0, 0, iconLayer.bitmap.width, iconLayer.bitmap.height, function(x, y, sidx) {
|
||||||
x += xs;
|
x += xs;
|
||||||
y += ys;
|
y += ys;
|
||||||
|
|||||||
@@ -167,9 +167,9 @@ function randomDynamicPort() {
|
|||||||
async function generatePassword(length) {
|
async function generatePassword(length) {
|
||||||
function validChar(byte) {
|
function validChar(byte) {
|
||||||
const ranges = ["az", "AZ", "09"];
|
const ranges = ["az", "AZ", "09"];
|
||||||
return ranges.some(range =>
|
return ranges.some(range => (
|
||||||
range.codePointAt(0) <= byte && byte <= range.codePointAt(1)
|
range.codePointAt(0) <= byte && byte <= range.codePointAt(1)
|
||||||
);
|
));
|
||||||
}
|
}
|
||||||
let randomBytesAsync = util.promisify(crypto.randomBytes);
|
let randomBytesAsync = util.promisify(crypto.randomBytes);
|
||||||
|
|
||||||
@@ -559,9 +559,9 @@ class FactorioServer extends events.EventEmitter {
|
|||||||
let channel = line
|
let channel = line
|
||||||
.slice(6, channelEnd)
|
.slice(6, channelEnd)
|
||||||
.toString("utf-8")
|
.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))
|
String.fromCharCode(parseInt(p1, 16))
|
||||||
)
|
))
|
||||||
;
|
;
|
||||||
|
|
||||||
let type = line.slice(channelEnd + 1, channelEnd + 2).toString("utf-8");
|
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])) {
|
if (!expected.includes(output[name])) {
|
||||||
continue heuristicLoop;
|
continue heuristicLoop;
|
||||||
}
|
}
|
||||||
} else {
|
} else if (expected !== output[name]) {
|
||||||
if (expected !== output[name]) {
|
continue heuristicLoop;
|
||||||
continue heuristicLoop;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -651,7 +649,7 @@ class FactorioServer extends events.EventEmitter {
|
|||||||
};
|
};
|
||||||
|
|
||||||
this._rconClient = new rconClient.Rcon(config);
|
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("authenticated", () => { this._rconReady = true; this.emit("rcon-ready"); });
|
||||||
this._rconClient.on("end", () => {
|
this._rconClient.on("end", () => {
|
||||||
this._rconClient = null;
|
this._rconClient = null;
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
const fileOps = require("./fileOps");
|
const fileOps = require("./fileOps");
|
||||||
module.exports = fileOps;
|
module.exports = fileOps;
|
||||||
@@ -310,18 +310,6 @@ class WebSocketClientConnector extends WebSocketBaseConnector {
|
|||||||
console.error("SOCKET | Error:", err);
|
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", () => {
|
this._socket.on("open", () => {
|
||||||
console.log("SOCKET | Open");
|
console.log("SOCKET | Open");
|
||||||
});
|
});
|
||||||
|
|||||||
+10
-8
@@ -11,8 +11,8 @@ const errors = require("lib/errors");
|
|||||||
class Message {
|
class Message {
|
||||||
/**
|
/**
|
||||||
* Name of the plugin this message belongs to, or null.
|
* 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() {
|
get plugin() {
|
||||||
if (this._plugin === undefined) {
|
if (this._plugin === undefined) {
|
||||||
let index = this.type.indexOf(":");
|
let index = this.type.indexOf(":");
|
||||||
@@ -78,9 +78,10 @@ class Request extends Message {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (forwardTo === "instance") {
|
if (forwardTo === "instance") {
|
||||||
requestProperties = Object.assign(
|
requestProperties = {
|
||||||
{ "instance_id": { type: "integer" }}, requestProperties
|
"instance_id": { type: "integer" },
|
||||||
);
|
...requestProperties,
|
||||||
|
};
|
||||||
|
|
||||||
} else if (forwardTo !== "master" && forwardTo !== null) {
|
} else if (forwardTo !== "master" && forwardTo !== null) {
|
||||||
throw new Error(`Invalid forwardTo value ${forwardTo}`);
|
throw new Error(`Invalid forwardTo value ${forwardTo}`);
|
||||||
@@ -635,9 +636,10 @@ class Event extends Message {
|
|||||||
this.broadcastTo = broadcastTo;
|
this.broadcastTo = broadcastTo;
|
||||||
|
|
||||||
if (forwardTo === "instance") {
|
if (forwardTo === "instance") {
|
||||||
eventProperties = Object.assign(
|
eventProperties = {
|
||||||
{ "instance_id": { type: "integer" }}, eventProperties
|
"instance_id": { type: "integer" },
|
||||||
);
|
...eventProperties,
|
||||||
|
};
|
||||||
|
|
||||||
} else if (forwardTo !== "master" && forwardTo !== null) {
|
} else if (forwardTo !== "master" && forwardTo !== null) {
|
||||||
throw new Error(`Invalid forwardTo value ${forwardTo}`);
|
throw new Error(`Invalid forwardTo value ${forwardTo}`);
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
// This file will be rewritten from scratch
|
||||||
|
/* eslint-disable */
|
||||||
/**
|
/**
|
||||||
Provides tools to manage mods in a clusterio install
|
Provides tools to manage mods in a clusterio install
|
||||||
@module
|
@module
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ function download(url, file, callback){
|
|||||||
// this might be an invalid path!
|
// this might be an invalid path!
|
||||||
fs.stat(pathArray.join("/"), (err, stat) => {
|
fs.stat(pathArray.join("/"), (err, stat) => {
|
||||||
if(err){
|
if(err){
|
||||||
makeDirectory(pathArray.join("/")).then(()=>{
|
makeDirectory(pathArray.join("/")).then(() => {
|
||||||
doDownload(url, file, callback);
|
doDownload(url, file, callback);
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
@@ -82,7 +82,7 @@ let downloadList = [
|
|||||||
// initiate folder creations and downloads
|
// initiate folder creations and downloads
|
||||||
function processMkdirRecursive(callback){
|
function processMkdirRecursive(callback){
|
||||||
let item = directories.shift();
|
let item = directories.shift();
|
||||||
makeDirectory(item).then(()=>{
|
makeDirectory(item).then(() => {
|
||||||
if(directories.length == 0){
|
if(directories.length == 0){
|
||||||
if(callback) callback();
|
if(callback) callback();
|
||||||
} else {
|
} else {
|
||||||
@@ -92,7 +92,7 @@ function processMkdirRecursive(callback){
|
|||||||
}
|
}
|
||||||
function processDownloadRecursive(callback){
|
function processDownloadRecursive(callback){
|
||||||
let item = downloadList.shift();
|
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(downloadList.length == 0){
|
||||||
if(callback) callback();
|
if(callback) callback();
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
+25
-24
@@ -1,35 +1,36 @@
|
|||||||
/**
|
/**
|
||||||
Helper functions related to objects
|
* Helper functions related to objects
|
||||||
@module
|
* @module
|
||||||
*/
|
*/
|
||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Deep clones an object, is actually just JSON.parse(JSON.stringify()) but looks cleaner.
|
* Deep clones an object, is actually just JSON.parse(JSON.stringify()) but looks cleaner.
|
||||||
@param {object} obj to clone
|
* @param {object} obj to clone
|
||||||
@returns {object} The cloned object.
|
* @returns {object} The cloned object.
|
||||||
|
*
|
||||||
@example
|
* @example
|
||||||
a = {"thingy":"with a value"};
|
* a = {"thingy":"with a value"};
|
||||||
b = a;
|
* b = a;
|
||||||
a == b; // true
|
* a == b; // true
|
||||||
c = objectOps.deepclone(a);
|
* c = objectOps.deepclone(a);
|
||||||
a == c; // false
|
* a == c; // false
|
||||||
*/
|
*/
|
||||||
module.exports.deepclone = function(obj){
|
module.exports.deepclone = function(obj){
|
||||||
return JSON.parse(JSON.stringify(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
|
* Checks if a string is valid JSON using try/catch. If passed an object it will always return true.
|
||||||
objectOps.isJSON("99"); // true
|
* @param {string} string to verify
|
||||||
objectOps.isJSON({"thingy":"that is an object"}); // true
|
* @returns {boolean} true if valid JSON.
|
||||||
objectOps.isJSON(JSON.stringify({"thingy":"that is an object"})); // true
|
*
|
||||||
*/
|
* @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){
|
module.exports.isJSON = function(string){
|
||||||
let stringIsJson = false;
|
let stringIsJson = false;
|
||||||
let x;
|
let x;
|
||||||
|
|||||||
+3
-3
@@ -167,9 +167,9 @@ class ValueCollector extends Collector {
|
|||||||
function removeMatchingLabels(mapping, labels) {
|
function removeMatchingLabels(mapping, labels) {
|
||||||
for (let key of mapping.keys()) {
|
for (let key of mapping.keys()) {
|
||||||
let candidate = keyToLabels(key);
|
let candidate = keyToLabels(key);
|
||||||
let hasLabels = Object.entries(labels).every(([name, value]) => {
|
let hasLabels = Object.entries(labels).every(([name, value]) => (
|
||||||
return candidate.get(name) === value;
|
candidate.get(name) === value
|
||||||
});
|
));
|
||||||
if (hasLabels) {
|
if (hasLabels) {
|
||||||
mapping.delete(key);
|
mapping.delete(key);
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-2
@@ -74,7 +74,7 @@ const serverHandshake = ajv.compile({
|
|||||||
$schema: "http://json-schema.org/draft-07/schema#",
|
$schema: "http://json-schema.org/draft-07/schema#",
|
||||||
title: "Server Handshake",
|
title: "Server Handshake",
|
||||||
description: "Message sent from the server to a client during the handshake",
|
description: "Message sent from the server to a client during the handshake",
|
||||||
allOf: [ messageSchema ],
|
allOf: [messageSchema],
|
||||||
anyOf: [
|
anyOf: [
|
||||||
{
|
{
|
||||||
properties: {
|
properties: {
|
||||||
@@ -137,7 +137,7 @@ const clientHandshake = ajv.compile({
|
|||||||
$schema: "http://json-schema.org/draft-07/schema#",
|
$schema: "http://json-schema.org/draft-07/schema#",
|
||||||
title: "Client Message",
|
title: "Client Message",
|
||||||
description: "Message sent from a client to the server",
|
description: "Message sent from a client to the server",
|
||||||
allOf: [ messageSchema ],
|
allOf: [messageSchema],
|
||||||
anyOf: [
|
anyOf: [
|
||||||
{
|
{
|
||||||
properties: {
|
properties: {
|
||||||
|
|||||||
@@ -535,7 +535,7 @@ class BaseConnection extends link.Link {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let controlConnections = new Array();
|
let controlConnections = [];
|
||||||
class ControlConnection extends BaseConnection {
|
class ControlConnection extends BaseConnection {
|
||||||
constructor(registerData, connector, user) {
|
constructor(registerData, connector, user) {
|
||||||
super("control", connector);
|
super("control", connector);
|
||||||
@@ -560,7 +560,7 @@ class ControlConnection extends BaseConnection {
|
|||||||
|
|
||||||
this.ws_dumper = null;
|
this.ws_dumper = null;
|
||||||
this.connector.on("connect", () => {
|
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", () => {
|
this.connector.on("close", () => {
|
||||||
if (this.ws_dumper) {
|
if (this.ws_dumper) {
|
||||||
@@ -880,6 +880,7 @@ class SlaveConnection extends BaseConnection {
|
|||||||
});
|
});
|
||||||
|
|
||||||
for (let event of ["connect", "drop", "close"]) {
|
for (let event of ["connect", "drop", "close"]) {
|
||||||
|
// eslint-disable-next-line no-loop-func
|
||||||
this.connector.on(event, () => {
|
this.connector.on(event, () => {
|
||||||
for (let masterPlugin of masterPlugins.values()) {
|
for (let masterPlugin of masterPlugins.values()) {
|
||||||
masterPlugin.onSlaveConnectionEvent(this, event);
|
masterPlugin.onSlaveConnectionEvent(this, event);
|
||||||
@@ -991,7 +992,7 @@ const wss = new WebSocket.Server({
|
|||||||
* 2<sup>31</sup>-1.
|
* 2<sup>31</sup>-1.
|
||||||
*/
|
*/
|
||||||
function isInteger(value) {
|
function isInteger(value) {
|
||||||
return value | 0 === value;
|
return (value | 0) === value;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -112,7 +112,7 @@ class MasterPlugin extends plugin.BaseMasterPlugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for (let instanceTech of message.data.technologies) {
|
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);
|
let tech = this.technologies.get(name);
|
||||||
if (!tech) {
|
if (!tech) {
|
||||||
this.technologies.set(name, { level, progress, researched });
|
this.technologies.set(name, { level, progress, researched });
|
||||||
@@ -152,7 +152,7 @@ class MasterPlugin extends plugin.BaseMasterPlugin {
|
|||||||
|
|
||||||
let technologies = [];
|
let technologies = [];
|
||||||
for (let [name, tech] of this.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 };
|
return { technologies };
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ const prometheusDoleFactorGauge = new prometheus.Gauge(
|
|||||||
);
|
);
|
||||||
|
|
||||||
class neuralDole {
|
class neuralDole {
|
||||||
|
|
||||||
getRequestStats(itemname,samples)
|
getRequestStats(itemname,samples)
|
||||||
{
|
{
|
||||||
var sum=0;
|
var sum=0;
|
||||||
@@ -28,7 +28,7 @@ class neuralDole {
|
|||||||
if (sum==0) return 0.1;
|
if (sum==0) return 0.1;
|
||||||
return sum/samples;
|
return sum/samples;
|
||||||
}
|
}
|
||||||
|
|
||||||
constructor({
|
constructor({
|
||||||
items,
|
items,
|
||||||
}){
|
}){
|
||||||
@@ -41,6 +41,7 @@ class neuralDole {
|
|||||||
this.stats=[];
|
this.stats=[];
|
||||||
this.debt= {};
|
this.debt= {};
|
||||||
}
|
}
|
||||||
|
|
||||||
doMagic() {
|
doMagic() {
|
||||||
for (let [name, count] of this.items._items) {
|
for (let [name, count] of this.items._items) {
|
||||||
let magicData = doleNN.Tick(
|
let magicData = doleNN.Tick(
|
||||||
@@ -50,7 +51,7 @@ class neuralDole {
|
|||||||
this.getRequestStats(name,5)
|
this.getRequestStats(name,5)
|
||||||
);
|
);
|
||||||
this.stats[name]=this.stats[name] || [];
|
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
|
if (this.stats[name].length>10) this.stats[name].pop();//remove if too many samples in stats
|
||||||
|
|
||||||
this.dole[name] = magicData[0];
|
this.dole[name] = magicData[0];
|
||||||
@@ -59,6 +60,7 @@ class neuralDole {
|
|||||||
}
|
}
|
||||||
this.itemsLastTick = new Map(this.items._items);
|
this.itemsLastTick = new Map(this.items._items);
|
||||||
}
|
}
|
||||||
|
|
||||||
divider(object) {
|
divider(object) {
|
||||||
let magicData = doleNN.Dose(
|
let magicData = doleNN.Dose(
|
||||||
object.count, // numReq
|
object.count, // numReq
|
||||||
@@ -100,7 +102,7 @@ function doleDivider({
|
|||||||
let itemCount = items.getItemCount(object.name);
|
let itemCount = items.getItemCount(object.name);
|
||||||
const doleDivisionRetardation = 10; //lower rates will equal more dramatic swings
|
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 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;
|
const originalCount = Number(object.count) || 0;
|
||||||
object.count /= ((_doleDivisionFactor[object.name]||0)+doleDivisionRetardation)/doleDivisionRetardation;
|
object.count /= ((_doleDivisionFactor[object.name]||0)+doleDivisionRetardation)/doleDivisionRetardation;
|
||||||
object.count = Math.round(object.count);
|
object.count = Math.round(object.count);
|
||||||
@@ -128,4 +130,4 @@ function doleDivider({
|
|||||||
module.exports = {
|
module.exports = {
|
||||||
doleDivider,
|
doleDivider,
|
||||||
neuralDole,
|
neuralDole,
|
||||||
};
|
};
|
||||||
@@ -47,7 +47,7 @@ function Dose(numreq,instore,store_last_tick,dole,carry,prev_req,numreq_total_ad
|
|||||||
instore=Number(instore);
|
instore=Number(instore);
|
||||||
var instore_adj=instore;
|
var instore_adj=instore;
|
||||||
if (instore_adj==0) instore_adj=0.1;
|
if (instore_adj==0) instore_adj=0.1;
|
||||||
|
|
||||||
var b=Math.trunc(prev_req/instore_adj*numreq);
|
var b=Math.trunc(prev_req/instore_adj*numreq);
|
||||||
var inp1=[numreq,instore_adj,store_last_tick/numreq,dole,carry];//0..4
|
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
|
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 internal=new Array(20).fill(0);
|
||||||
var outputs=[0,0,0,0];
|
var outputs=[0,0,0,0];
|
||||||
//NN: Please don't touch :), code is generated
|
//NN: Please don't touch :), code is generated
|
||||||
|
|
||||||
outputs[0]=inputs[7]*0.8058582544;
|
outputs[0]=inputs[7]*0.8058582544;
|
||||||
outputs[0]=sigmoid2(outputs[0]);
|
outputs[0]=sigmoid2(outputs[0]);
|
||||||
outputs[1]=sigmoid0(outputs[1]);
|
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;
|
debt=debt || 0;
|
||||||
if (outputs[0]>0.99) outputs[0]=1.0;
|
if (outputs[0]>0.99) outputs[0]=1.0;
|
||||||
|
|
||||||
var res1=Number(outputs[0])*numreq+outputs[3]+debt;
|
var res1=Number(outputs[0])*numreq+outputs[3]+debt;
|
||||||
var res_capped=Math.round(res1);
|
var res_capped=Math.round(res1);
|
||||||
|
|
||||||
if (res_capped>numreq) res_capped=numreq;
|
if (res_capped>numreq) res_capped=numreq;
|
||||||
if (res_capped>instore) res_capped=instore;
|
if (res_capped>instore) res_capped=instore;
|
||||||
if (res_capped<0) res_capped=0;
|
if (res_capped<0) res_capped=0;
|
||||||
|
|
||||||
res1=res1 || 0;
|
res1=res1 || 0;
|
||||||
res_capped=res_capped || 0;//Safeguard against wrong values
|
res_capped=res_capped || 0;//Safeguard against wrong values
|
||||||
debt=res1-res_capped;
|
debt=res1-res_capped;
|
||||||
debt_cap=Math.round(numreq*1.5)+5;
|
debt_cap=Math.round(numreq*1.5)+5;
|
||||||
if (debt>debt_cap) debt=debt_cap;
|
if (debt>debt_cap) debt=debt_cap;
|
||||||
|
|
||||||
carry=sigmoid0(outputs[2]*carry+outputs[0]) || 0;
|
carry=sigmoid0(outputs[2]*carry+outputs[0]) || 0;
|
||||||
return [res_capped,dole+outputs[1],carry,debt];
|
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 internal=new Array(10).fill(0);
|
||||||
var outputs=[0,0];
|
var outputs=[0,0];
|
||||||
//NN: Please don't touch :), code is generated
|
//NN: Please don't touch :), code is generated
|
||||||
|
|
||||||
outputs[0]=inputs[3]*0.9364774823;
|
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[0]=sigmoid2(outputs[0]);
|
||||||
outputs[1]=outputs[0]*1.828422785;
|
outputs[1]=outputs[0]*1.828422785;
|
||||||
outputs[1]=sigmoid3(outputs[1]);
|
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 (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>1) avg=1;
|
||||||
if (avg<0) avg=0;
|
if (avg<0) avg=0;
|
||||||
|
|
||||||
return [sigmoid0(outputs[0]),avg];
|
return [sigmoid0(outputs[0]),avg];
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { Dose,Tick };
|
module.exports = { Dose,Tick };
|
||||||
@@ -13,24 +13,24 @@ function drawcontents(data) {
|
|||||||
data = data.filter(function(item) {
|
data = data.filter(function(item) {
|
||||||
return search.test(item.name);
|
return search.test(item.name);
|
||||||
});
|
});
|
||||||
|
|
||||||
sortByKey(data, "count");
|
sortByKey(data, "count");
|
||||||
|
|
||||||
const table = document.querySelector("#contents tbody"); //tables have tbody inserted automatically
|
const table = document.querySelector("#contents tbody"); //tables have tbody inserted automatically
|
||||||
const rows = table.children;
|
const rows = table.children;
|
||||||
|
|
||||||
//update existing rows or create new ones
|
//update existing rows or create new ones
|
||||||
data.forEach(function(item, i) {
|
data.forEach(function(item, i) {
|
||||||
// format count to have .s in it for large number readability (1,000,000)
|
// 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, ",");
|
item.count = item.count.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
||||||
|
|
||||||
let row = rows[i];
|
let row = rows[i];
|
||||||
if(!row) {
|
if(!row) {
|
||||||
row = document.createElement("tr");
|
row = document.createElement("tr");
|
||||||
row.innerHTML = "<td><div></div></td><td class=name></td><td class=count></td>";
|
row.innerHTML = "<td><div></div></td><td class=name></td><td class=count></td>";
|
||||||
table.appendChild(row);
|
table.appendChild(row);
|
||||||
}
|
}
|
||||||
|
|
||||||
const itemIcon = row.querySelector("div");
|
const itemIcon = row.querySelector("div");
|
||||||
const iconClass = getItemIconClass(item.name);
|
const iconClass = getItemIconClass(item.name);
|
||||||
if (itemIcon.getAttribute("class") !== iconClass) {
|
if (itemIcon.getAttribute("class") !== iconClass) {
|
||||||
@@ -56,13 +56,13 @@ function drawcontents(data) {
|
|||||||
if(name.textContent !== localeName) {
|
if(name.textContent !== localeName) {
|
||||||
name.textContent = localeName;
|
name.textContent = localeName;
|
||||||
}
|
}
|
||||||
|
|
||||||
const count = row.querySelector(".count");
|
const count = row.querySelector(".count");
|
||||||
if(count.textContent !== ""+item.count) {
|
if(count.textContent !== String(item.count)) {
|
||||||
count.textContent = item.count;
|
count.textContent = item.count;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
//remove excess rows, for example, after filtering
|
//remove excess rows, for example, after filtering
|
||||||
while (data.length < rows.length) {
|
while (data.length < rows.length) {
|
||||||
table.removeChild(rows[data.length]);
|
table.removeChild(rows[data.length]);
|
||||||
|
|||||||
@@ -12,4 +12,4 @@ module.exports = function(app) {
|
|||||||
app.get("/nodeDetails", function(req, res) {
|
app.get("/nodeDetails", function(req, res) {
|
||||||
res.render("nodeDetails");
|
res.render("nodeDetails");
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -23,7 +23,6 @@ const version = require("./package").version;
|
|||||||
|
|
||||||
// internal libraries
|
// internal libraries
|
||||||
const fileOps = require("lib/fileOps");
|
const fileOps = require("lib/fileOps");
|
||||||
const hashFile = require("lib/hash").hashFile;
|
|
||||||
const factorio = require("lib/factorio");
|
const factorio = require("lib/factorio");
|
||||||
const link = require("lib/link");
|
const link = require("lib/link");
|
||||||
const plugin = require("lib/plugin");
|
const plugin = require("lib/plugin");
|
||||||
@@ -88,7 +87,7 @@ const serverSettingsActions = {
|
|||||||
"game_password": applyAsConfig("password"),
|
"game_password": applyAsConfig("password"),
|
||||||
"require_user_verification": applyAsConfig("require-user-verification"),
|
"require_user_verification": applyAsConfig("require-user-verification"),
|
||||||
"tags": applyAsConfig("tags"),
|
"tags": applyAsConfig("tags"),
|
||||||
"visibility": async function action(server, value) {
|
"visibility": async (server, value) => {
|
||||||
for (let scope of ["lan", "public", "steam"]) {
|
for (let scope of ["lan", "public", "steam"]) {
|
||||||
try {
|
try {
|
||||||
let enabled = Boolean(value[scope]);
|
let enabled = Boolean(value[scope]);
|
||||||
@@ -352,13 +351,14 @@ class Instance extends link.Link{
|
|||||||
throw new Error(`Expected name of module for plugin ${pluginName} to match the plugin name`);
|
throw new Error(`Expected name of module for plugin ${pluginName} to match the plugin name`);
|
||||||
}
|
}
|
||||||
|
|
||||||
module = Object.assign({
|
module = {
|
||||||
version: plugin.info.version,
|
version: plugin.info.version,
|
||||||
dependencies: { "clusterio": "*" },
|
dependencies: { "clusterio": "*" },
|
||||||
path: modulePath,
|
path: modulePath,
|
||||||
load: [],
|
load: [],
|
||||||
require: [],
|
require: [],
|
||||||
}, module);
|
...module,
|
||||||
|
};
|
||||||
modules.set(module.name, module);
|
modules.set(module.name, module);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -380,12 +380,13 @@ class Instance extends link.Link{
|
|||||||
throw new Error(`Expected name of module ${entry.name} to match the directory name`);
|
throw new Error(`Expected name of module ${entry.name} to match the directory name`);
|
||||||
}
|
}
|
||||||
|
|
||||||
module = Object.assign({
|
module = {
|
||||||
path: path.join("modules", entry.name),
|
path: path.join("modules", entry.name),
|
||||||
dependencies: { "clusterio": "*" },
|
dependencies: { "clusterio": "*" },
|
||||||
load: [],
|
load: [],
|
||||||
require: [],
|
require: [],
|
||||||
}, module);
|
...module,
|
||||||
|
};
|
||||||
modules.set(module.name, module);
|
modules.set(module.name, module);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -754,7 +755,7 @@ class Slave extends link.Link {
|
|||||||
console.error(err);
|
console.error(err);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
});
|
});
|
||||||
});;
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
this.connector.on("close", () => {
|
this.connector.on("close", () => {
|
||||||
@@ -874,10 +875,10 @@ class Slave extends link.Link {
|
|||||||
|
|
||||||
|
|
||||||
// save a copy of the instance config
|
// save a copy of the instance config
|
||||||
let warnedOutput = Object.assign(
|
let warnedOutput = {
|
||||||
{ _warning: "Changes to this file will be overwritten by the master server's copy." },
|
_warning: "Changes to this file will be overwritten by the master server's copy.",
|
||||||
instanceInfo.config.serialize()
|
...instanceInfo.config.serialize(),
|
||||||
);
|
};
|
||||||
await fs.outputFile(
|
await fs.outputFile(
|
||||||
path.join(instanceInfo.path, "instance.json"),
|
path.join(instanceInfo.path, "instance.json"),
|
||||||
JSON.stringify(warnedOutput, null, 4)
|
JSON.stringify(warnedOutput, null, 4)
|
||||||
@@ -1237,37 +1238,6 @@ async function startSlave() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
await slaveConnector.connect();
|
await slaveConnector.connect();
|
||||||
|
|
||||||
/*
|
|
||||||
} else if (command == "manage"){
|
|
||||||
await manage(config, instance);
|
|
||||||
// process.exit(0);
|
|
||||||
*/
|
|
||||||
}
|
|
||||||
|
|
||||||
// string, function
|
|
||||||
// returns [{modName:string,hash:string}, ... ]
|
|
||||||
function hashMods(instance, callback) {
|
|
||||||
if(!callback) {
|
|
||||||
throw new Error("ERROR in function hashMods NO CALLBACK");
|
|
||||||
}
|
|
||||||
|
|
||||||
function hashMod(name) {
|
|
||||||
if (path.extname(name) != ".zip") {
|
|
||||||
// Can't hash unzipped mods, return null that's filtered out later
|
|
||||||
return null;
|
|
||||||
} else {
|
|
||||||
return hashFile(instance.path("mods", name)).then(hash => (
|
|
||||||
{ modName: name, hash: hash }
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let promises = fs.readdirSync(instance.path("mods")).map(hashMod);
|
|
||||||
Promise.all(promises).then(hashes => {
|
|
||||||
// Remove null entries from hashMod
|
|
||||||
callback(hashes.filter(entry => entry !== null));
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
|
|||||||
@@ -156,7 +156,7 @@ describe("Integration of Clusterio", function() {
|
|||||||
],
|
],
|
||||||
];
|
];
|
||||||
|
|
||||||
for (let [prop, value, , ] of testConfigs) {
|
for (let [prop, value, ,] of testConfigs) {
|
||||||
value = `"'${JSON.stringify(value).replace(/"/g, process.platform === "win32" ? '""' : '\\"')}'"`;
|
value = `"'${JSON.stringify(value).replace(/"/g, process.platform === "win32" ? '""' : '\\"')}'"`;
|
||||||
let args = `--instance test --field factorio.settings --prop ${prop} --value ${value}`;
|
let args = `--instance test --field factorio.settings --prop ${prop} --value ${value}`;
|
||||||
await exec(`node clusterctl --config ${controlConfigPath} set-instance-config-prop ${args}`);
|
await exec(`node clusterctl --config ${controlConfigPath} set-instance-config-prop ${args}`);
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ class TestControl extends link.Link {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async debugWsMessageEventHandler() { }
|
async debugWsMessageEventHandler() { }
|
||||||
|
|
||||||
async instanceOutputEventHandler() { }
|
async instanceOutputEventHandler() { }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -35,6 +36,7 @@ class TestControlConnector extends link.WebSocketClientConnector {
|
|||||||
// Mark that this test takes a lot of time, or depeneds on a test
|
// Mark that this test takes a lot of time, or depeneds on a test
|
||||||
// that takes a lot of time.
|
// that takes a lot of time.
|
||||||
function slowTest(test) {
|
function slowTest(test) {
|
||||||
|
// eslint-disable-next-line no-process-env
|
||||||
if (process.env.FAST_TEST) {
|
if (process.env.FAST_TEST) {
|
||||||
test.skip();
|
test.skip();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ describe("Integration of lib/factorio/server", function() {
|
|||||||
|
|
||||||
before(async function() {
|
before(async function() {
|
||||||
// Delete result from previous run of these tests
|
// Delete result from previous run of these tests
|
||||||
if (fs.existsSync(writePath)) {
|
if (await fs.pathExists(writePath)) {
|
||||||
await fs.remove(writePath);
|
await fs.remove(writePath);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -287,7 +287,7 @@ describe("lib/config/classes", function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("should work if field is in enum", function() {
|
it("should work if field is in enum", function() {
|
||||||
testInstance.set("enum", "c"),
|
testInstance.set("enum", "c");
|
||||||
assert.equal(testInstance.get("enum"), "c");
|
assert.equal(testInstance.get("enum"), "c");
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -299,7 +299,7 @@ describe("lib/config/classes", function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("should work if field is optional", function() {
|
it("should work if field is optional", function() {
|
||||||
testInstance.set("test", "spam"),
|
testInstance.set("test", "spam");
|
||||||
assert.equal(testInstance.get("test"), "spam");
|
assert.equal(testInstance.get("test"), "spam");
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -311,7 +311,7 @@ describe("lib/config/classes", function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("should treat empty string as null", function() {
|
it("should treat empty string as null", function() {
|
||||||
testInstance.set("test", ""),
|
testInstance.set("test", "");
|
||||||
assert.equal(testInstance.get("test"), null);
|
assert.equal(testInstance.get("test"), null);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -451,7 +451,8 @@ describe("lib/config/classes", function() {
|
|||||||
});
|
});
|
||||||
it("should construct a finalized class", function() {
|
it("should construct a finalized class", function() {
|
||||||
TestConfig.finalize();
|
TestConfig.finalize();
|
||||||
new TestConfig();
|
let config = new TestConfig();
|
||||||
|
assert(config);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ describe("lib/database", function() {
|
|||||||
new Error("Expected all keys to be string but got number")
|
new Error("Expected all keys to be string but got number")
|
||||||
);
|
);
|
||||||
assert.throws(
|
assert.throws(
|
||||||
() => database.mapToObject(new Map([[Symbol(), 1]])),
|
() => database.mapToObject(new Map([[Symbol("test"), 1]])),
|
||||||
new Error("Expected all keys to be string but got symbol")
|
new Error("Expected all keys to be string but got symbol")
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -18,5 +18,5 @@ describe("lib/factorio/export", function() {
|
|||||||
let locale = await factorio._exportLocale(testServer, new Map(), ["base"], "en");
|
let locale = await factorio._exportLocale(testServer, new Map(), ["base"], "en");
|
||||||
assert.deepEqual(locale, new Map([["test.key-a", "1"], ["test.key-b", "2"]]));
|
assert.deepEqual(locale, new Map([["test.key-a", "1"], ["test.key-b", "2"]]));
|
||||||
});
|
});
|
||||||
});;
|
});
|
||||||
});
|
});
|
||||||
@@ -93,7 +93,7 @@ describe("lib/factorio/server", function() {
|
|||||||
|
|
||||||
it("should return a port number in the dynamic range", function() {
|
it("should return a port number in the dynamic range", function() {
|
||||||
function validate(port) {
|
function validate(port) {
|
||||||
return 49152 <= port && port <= 65535;
|
return (49152 <= port && port <= 65535);
|
||||||
}
|
}
|
||||||
for (let i=0; i < 20; i++) {
|
for (let i=0; i < 20; i++) {
|
||||||
assert(validate(factorio._randomDynamicPort()));
|
assert(validate(factorio._randomDynamicPort()));
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ const path = require("path");
|
|||||||
|
|
||||||
const generateSSLcert = require("lib/generateSSLcert");
|
const generateSSLcert = require("lib/generateSSLcert");
|
||||||
|
|
||||||
describe("generateSSLcert.js(options)", ()=>{
|
describe("generateSSLcert.js(options)", function() {
|
||||||
let testDir = path.join("temp", "test", "certTest");
|
let testDir = path.join("temp", "test", "certTest");
|
||||||
before(async function() {
|
before(async function() {
|
||||||
await fs.remove(testDir);
|
await fs.remove(testDir);
|
||||||
@@ -13,6 +13,7 @@ describe("generateSSLcert.js(options)", ()=>{
|
|||||||
|
|
||||||
it("Creates a folder with a .crt and .key file in it", async function() {
|
it("Creates a folder with a .crt and .key file in it", async function() {
|
||||||
this.timeout(1000);
|
this.timeout(1000);
|
||||||
|
// eslint-disable-next-line no-process-env
|
||||||
if (process.env.FAST_TEST) {
|
if (process.env.FAST_TEST) {
|
||||||
this.skip();
|
this.skip();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -81,7 +81,7 @@ describe("lib/link/connectors", function() {
|
|||||||
describe(".processHandshake()", function() {
|
describe(".processHandshake()", function() {
|
||||||
it("should close on invalid message", function() {
|
it("should close on invalid message", function() {
|
||||||
testConnector._socket.closeCalled = false;
|
testConnector._socket.closeCalled = false;
|
||||||
testConnector._processHandshake({ data: "invalid message" }),
|
testConnector._processHandshake({ data: "invalid message" });
|
||||||
assert(testConnector._socket.closeCalled, "Close was not called on the socket");
|
assert(testConnector._socket.closeCalled, "Close was not called on the socket");
|
||||||
});
|
});
|
||||||
it("should call register on hello", function() {
|
it("should call register on hello", function() {
|
||||||
|
|||||||
@@ -56,7 +56,7 @@ describe("lib/link/link", function() {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
it("should set the handler", function() {
|
it("should set the handler", function() {
|
||||||
let handler = (message) => {};
|
function handler(message) { }
|
||||||
testLink.setHandler("handler_test", handler, (message) => true);
|
testLink.setHandler("handler_test", handler, (message) => true);
|
||||||
assert.equal(testLink._handlers.get("handler_test"), handler);
|
assert.equal(testLink._handlers.get("handler_test"), handler);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ describe("lib/link/messages", function() {
|
|||||||
|
|
||||||
let handlerResult;
|
let handlerResult;
|
||||||
it("should attach handler to a target link", function() {
|
it("should attach handler to a target link", function() {
|
||||||
testRequest.attach(testTargetLink, async (message) => handlerResult );
|
testRequest.attach(testTargetLink, async (message) => handlerResult);
|
||||||
assert(testTargetLink._handlers.has("test_request"), "Handler was not set");
|
assert(testTargetLink._handlers.has("test_request"), "Handler was not set");
|
||||||
});
|
});
|
||||||
it("should send result of calling the handler", async function() {
|
it("should send result of calling the handler", async function() {
|
||||||
@@ -83,9 +83,7 @@ describe("lib/link/messages", function() {
|
|||||||
testSourceLink.connector.send = (type, data) => {
|
testSourceLink.connector.send = (type, data) => {
|
||||||
request = { type, data };
|
request = { type, data };
|
||||||
};
|
};
|
||||||
testSourceLink.waitFor = (type, condition) => {
|
testSourceLink.waitFor = (type, condition) => ({ data: { type, request }});
|
||||||
return { data: { type, request }};
|
|
||||||
};
|
|
||||||
assert.deepEqual(
|
assert.deepEqual(
|
||||||
await testRequest.send(testSourceLink, { test: "request" }),
|
await testRequest.send(testSourceLink, { test: "request" }),
|
||||||
{ type: "test_response", request: { type: "test_request", data: { test: "request" }}}
|
{ type: "test_response", request: { type: "test_request", data: { test: "request" }}}
|
||||||
@@ -94,9 +92,7 @@ describe("lib/link/messages", function() {
|
|||||||
delete testSourceLink.waitFor;
|
delete testSourceLink.waitFor;
|
||||||
});
|
});
|
||||||
it("should throw error response", async function() {
|
it("should throw error response", async function() {
|
||||||
testSourceLink.waitFor = (type, condition) => {
|
testSourceLink.waitFor = (type, condition) => ({ data: { error: "test error" }});
|
||||||
return { data: { error: "test error" }};
|
|
||||||
};
|
|
||||||
await assert.rejects(
|
await assert.rejects(
|
||||||
testRequest.send(testSourceLink, { test: "blah" }),
|
testRequest.send(testSourceLink, { test: "blah" }),
|
||||||
new errors.RequestError("test error")
|
new errors.RequestError("test error")
|
||||||
|
|||||||
+3
-22
@@ -3,31 +3,12 @@ var assert = require("assert");
|
|||||||
var objectOps = require("lib/objectOps");
|
var objectOps = require("lib/objectOps");
|
||||||
|
|
||||||
describe("objectOps.js", function(){
|
describe("objectOps.js", function(){
|
||||||
/*describe("objectOps.clone()", function(){
|
|
||||||
it("clones javascript objects", function(){
|
|
||||||
var object1 = {hello:"world", cat:{legs:4, name:"Kitty", colors:["brown", "yellow", "purple"]}};
|
|
||||||
var object2 = {};
|
|
||||||
object2 = objectOps.clone(object1);
|
|
||||||
|
|
||||||
assert.equal(object2.cat.name, object1.cat.name)
|
|
||||||
assert.equal(object1.hello, object2.hello)
|
|
||||||
});
|
|
||||||
it("does not deep clone objects", function(){
|
|
||||||
var obj1 = {hello:"world", cat:{legs:4, name:"Kitty", colors:["brown", "yellow", "purple"]}};
|
|
||||||
var obj2 = {};
|
|
||||||
obj2 = objectOps.clone(obj1);
|
|
||||||
|
|
||||||
obj1.cat.colors = "black";
|
|
||||||
assert.equal(obj1.cat.colors, "black");
|
|
||||||
assert.notEqual(obj2.cat.colors[1], "yellow");
|
|
||||||
});
|
|
||||||
});*/
|
|
||||||
describe("objectOps.deepclone()", function(){
|
describe("objectOps.deepclone()", function(){
|
||||||
it("deep clones javascript objects", function(){
|
it("deep clones javascript objects", function(){
|
||||||
var obj1 = { hello:"world", cat:{ legs:4, name:"Kitty", colors:["brown", "yellow", "purple"] }};
|
var obj1 = { hello: "world", cat: { legs: 4, name: "Kitty", colors: ["brown", "yellow", "purple"] }};
|
||||||
var obj2 = {};
|
var obj2 = {};
|
||||||
obj2 = objectOps.deepclone(obj1);
|
obj2 = objectOps.deepclone(obj1);
|
||||||
|
|
||||||
obj1.cat.colors = "black";
|
obj1.cat.colors = "black";
|
||||||
assert.equal(obj1.cat.colors, "black");
|
assert.equal(obj1.cat.colors, "black");
|
||||||
assert.equal(obj2.cat.colors[1], "yellow");
|
assert.equal(obj2.cat.colors[1], "yellow");
|
||||||
@@ -38,4 +19,4 @@ describe("objectOps.js", function(){
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
+1
-1
@@ -103,7 +103,7 @@ describe("lib/plugin", function() {
|
|||||||
plugin.attachPluginMessages(mockLink, {}, null);
|
plugin.attachPluginMessages(mockLink, {}, null);
|
||||||
});
|
});
|
||||||
it("should attach handler for the given message", function() {
|
it("should attach handler for the given message", function() {
|
||||||
let mockEventEventHandler = function() {};
|
function mockEventEventHandler() { };
|
||||||
plugin.attachPluginMessages(mockLink, { name: "test", messages: { mockEvent }}, { mockEventEventHandler });
|
plugin.attachPluginMessages(mockLink, { name: "test", messages: { mockEvent }}, { mockEventEventHandler });
|
||||||
assert(mockLink._handlers.get("test:test_event"), "handler was not registered");
|
assert(mockLink._handlers.get("test:test_event"), "handler was not registered");
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -523,7 +523,7 @@ describe("lib/prometheus", function() {
|
|||||||
|
|
||||||
let serializedResult = {
|
let serializedResult = {
|
||||||
metric: { type: "type", name: "name", help: "Help", labels: ["a", "b"] },
|
metric: { type: "type", name: "name", help: "Help", labels: ["a", "b"] },
|
||||||
samples: [ ['a="1",b="2"', 1], ['a="3",b="4"', 5] ],
|
samples: [['a="1",b="2"', 1], ['a="3",b="4"', 5]],
|
||||||
};
|
};
|
||||||
let deserializedResult = {
|
let deserializedResult = {
|
||||||
metric: new prometheus.Metric("type", "name", "Help", ["a", "b"]),
|
metric: new prometheus.Metric("type", "name", "Help", ["a", "b"]),
|
||||||
|
|||||||
Reference in new issue
Block a user