Fix JSDoc issues

Fix missing documentation for parameters and return types, incorect
config and errors in type definitions.
This commit is contained in:
Hornwitser committed 2020-06-17 20:53:18 +02:00
1 parent 3dba92a03d
commit 703fda43ad
20 files changed
+193 -52

No files matched your search

+8 -6
View File
@@ -22,6 +22,8 @@ const config = require("lib/config");
* Formats a parsed Factorio output from lib/factorio into a readable * Formats a parsed Factorio output from lib/factorio into a readable
* colorized output using terminal escape codes that can be printed. * colorized output using terminal escape codes that can be printed.
* *
* @param {Object} output - Factorio server output.
* @returns {string} terminal colorized message.
* @private * @private
*/ */
function formatOutputColored(output) { function formatOutputColored(output) {
@@ -77,8 +79,8 @@ class Command {
* Resolves a string with either an instance name or an id into an integer * Resolves a string with either an instance name or an id into an integer
* with the instance ID. * with the instance ID.
* *
* @param client - link to master server to query instance on. * @param {module:lib/link.Link} client - link to master server to query instance on.
* @param instanceName - string with name or id of instance. * @param {string} instanceName - string with name or id of instance.
* @returns {number} instance ID. * @returns {number} instance ID.
* @private * @private
*/ */
@@ -109,8 +111,8 @@ async function resolveInstance(client, instanceName) {
* Resolves a string with either an slave name or an id into an integer with * Resolves a string with either an slave name or an id into an integer with
* the slave ID. * the slave ID.
* *
* @param client - link to master server to query slave on. * @param {module:lib/link.Link} client - link to master server to query slave on.
* @param slaveName - string with name or id of slave. * @param {string} slaveName - string with name or id of slave.
* @returns {number} slave ID. * @returns {number} slave ID.
* @private * @private
*/ */
@@ -141,8 +143,8 @@ async function resolveSlave(client, slaveName) {
* Resolves a string with either a role name or an id into an object * Resolves a string with either a role name or an id into an object
* representing the role. * representing the role.
* *
* @param client - link to master server to query role on. * @param {module:lib/link.Link} client - link to master server to query role on.
* @param roleName - string with name or id of role. * @param {string} roleName - string with name or id of role.
* @returns {Object} Role info. * @returns {Object} Role info.
* @private * @private
*/ */
-1
View File
@@ -16,7 +16,6 @@
"clusterctl.js", "clusterctl.js",
"lib/", "lib/",
"plugins/", "plugins/",
"routes/",
"routes.js" "routes.js"
], ],
"excludePattern": "node_modules" "excludePattern": "node_modules"
+51 -11
View File
@@ -120,6 +120,8 @@ class Config extends events.EventEmitter {
/** /**
* Serialize the config to a plain JavaScript object * Serialize the config to a plain JavaScript object
*
* @returns {Object} JSON serializable representation of the config.
*/ */
serialize() { serialize() {
let groups = [...this._unknownGroups.values()]; let groups = [...this._unknownGroups.values()];
@@ -135,6 +137,9 @@ class Config extends events.EventEmitter {
* *
* Updates all groups in the config with groups in the serialized * Updates all groups in the config with groups in the serialized
* config passed. * config passed.
*
* @param {Object} serializedConfig - Output from .serialize().
* @param {boolean} notify - Invoke fieldChanged events if true.
*/ */
update(serializedConfig, notify) { update(serializedConfig, notify) {
this._validate(serializedConfig); this._validate(serializedConfig);
@@ -150,6 +155,9 @@ class Config extends events.EventEmitter {
/** /**
* Get the value for a config field * Get the value for a config field
*
* @param {string} name - Name of field to get.
* @returns {*} the value for the field.
*/ */
get(name) { get(name) {
let [group, field] = splitOn(".", name); let [group, field] = splitOn(".", name);
@@ -158,22 +166,32 @@ class Config extends events.EventEmitter {
/** /**
* Set the value for a config field * Set the value for a config field
*
* @param {string} name - Name of field to set.
* @param {*} value - the value to set on field
*/ */
set(name, value) { set(name, value) {
let [group, field] = splitOn(".", name); let [group, field] = splitOn(".", name);
return this.group(group).set(field, value); this.group(group).set(field, value);
} }
/** /**
* Set property of an object value for a config field * Set property of an object value for a config field
*
* @param {string} name - Name of field to set property on.
* @param {string} prop - Name of property to set on field.
* @param {*} value - the value to set the property to.
*/ */
setProp(name, prop, value) { setProp(name, prop, value) {
let [group, field] = splitOn(".", name); let [group, field] = splitOn(".", name);
return this.group(group).setProp(field, prop, value); this.group(group).setProp(field, prop, value);
} }
/** /**
* Get the config group instance with the given name * Get the config group instance with the given name
*
* @param {string} name - Name of group to get.
* @returns {module:lib/config.ConfigGroup} config group.
*/ */
group(name) { group(name) {
if (!this._initialized) { if (!this._initialized) {
@@ -223,6 +241,8 @@ class Config extends events.EventEmitter {
* *
* Adds the ConfigGroup to this config as a group that will get * Adds the ConfigGroup to this config as a group that will get
* initialized, loaded and serialized with this config class. * initialized, loaded and serialized with this config class.
*
* @param {module:lib/config.ConfigGroup} group - class to register.
*/ */
static registerGroup(group) { static registerGroup(group) {
this._initSubclass(); this._initSubclass();
@@ -261,7 +281,7 @@ class ConfigGroup {
* After the creation of the new config group you have to call * After the creation of the new config group you have to call
* either .init() or .load() on it in order to fully initialize it. * either .init() or .load() on it in order to fully initialize it.
*/ */
constructor(serializedGroup) { constructor() {
if (!this.constructor._finalized) { if (!this.constructor._finalized) {
throw new Error(`Cannot instantiate incomplete ConfigGroup class ${this.constructor.name}`); throw new Error(`Cannot instantiate incomplete ConfigGroup class ${this.constructor.name}`);
} }
@@ -276,6 +296,8 @@ class ConfigGroup {
* *
* Computes and assigns the initial values for all fields of the * Computes and assigns the initial values for all fields of the
* config group. * config group.
*
* @param {module:lib/config.Config} config - Config group belongs to.
*/ */
async init(config) { async init(config) {
this._config = config; this._config = config;
@@ -303,6 +325,10 @@ class ConfigGroup {
* Loads all the values from the passed serialized version of the * Loads all the values from the passed serialized version of the
* group and then initializes any possible missing fields from it to * group and then initializes any possible missing fields from it to
* their default values. * their default values.
*
* @param {module:lib/config.Config} config - Config group belongs to.
* @param {Object} serializedGroup -
* Result from a previous call to .serialize().
*/ */
async load(config, serializedGroup) { async load(config, serializedGroup) {
this.update(serializedGroup, false); this.update(serializedGroup, false);
@@ -320,6 +346,9 @@ class ConfigGroup {
/** /**
* Get value for field * Get value for field
*
* @param {string} name - Name of field to get.
* @returns {*} Value stored for the field.
*/ */
get(name) { get(name) {
if (!this.constructor._definitions.has(name)) { if (!this.constructor._definitions.has(name)) {
@@ -335,6 +364,8 @@ class ConfigGroup {
* The field must be defined for the config group and the value is * The field must be defined for the config group and the value is
* type checked against the field definition. * type checked against the field definition.
* *
* @param {string} name - Name of field to set.
* @param {*} value - Value to set for field.
* @throws {module:lib/config.InvalidField} if field is not defined. * @throws {module:lib/config.InvalidField} if field is not defined.
* @throws {module:lib/config.InvalidValue} if value is not allowed for the field. * @throws {module:lib/config.InvalidValue} if value is not allowed for the field.
*/ */
@@ -397,6 +428,9 @@ class ConfigGroup {
* Update value of stored object field by setting the specified property * Update value of stored object field by setting the specified property
* on it. The field must be defined as an object for the config group. * on it. The field must be defined as an object for the config group.
* *
* @param {string} name - Name of field to set property on.
* @param {string} prop - Name of property to set on field.
* @param {*} value - the value to set the property to.
* @throws {module:lib/config.InvalidField} if field is not defined. * @throws {module:lib/config.InvalidField} if field is not defined.
* @throws {module:lib/config.InvalidValue} if field is not an object. * @throws {module:lib/config.InvalidValue} if field is not an object.
*/ */
@@ -430,6 +464,10 @@ class ConfigGroup {
* *
* Overwrites the values of all the fields in this config group that * Overwrites the values of all the fields in this config group that
* has a valid value in the passed serialized group with that value. * has a valid value in the passed serialized group with that value.
*
* @param {Object} serializedGroup -
* Result from a previous call to .serialize().
* @param {boolean} notify - Invoke fieldChanged events if true.
*/ */
update(serializedGroup, notify) { update(serializedGroup, notify) {
if (basicType(serializedGroup) !== "object") { if (basicType(serializedGroup) !== "object") {
@@ -475,6 +513,8 @@ class ConfigGroup {
/** /**
* Serialize the config to a plain JavaScript object * Serialize the config to a plain JavaScript object
*
* @returns {Object} JSON serializable representation of the group.
*/ */
serialize() { serialize() {
let fields = {}; let fields = {};
@@ -517,23 +557,23 @@ class ConfigGroup {
/** /**
* Define a new configuration field * Define a new configuration field
* *
* The following properties are supported: * @param {Object} item - Field definition.
* - type: * @param {string} item.type -
* string declaring the type of the config value, supports * string declaring the type of the config value, supports
* boolean, string, number and object. * boolean, string, number and object.
* - name: * @param {string} item.name -
* Name of the configuration field. Should follow the * Name of the configuration field. Should follow the
* lower_case_underscore style. * lower_case_underscore style.
* - title: * @param {string} item.title -
* Text used to identify the config field in user interfaces. * Text used to identify the config field in user interfaces.
* - description: * @param {string} item.description -
* Text used to describe the config field in user interfaces. * Text used to describe the config field in user interfaces.
* - enum (optional): * @param {Array=} item.enum -
* Array of all values that are acceptible. Useful for making * Array of all values that are acceptible. Useful for making
* enumerated values. * enumerated values.
* - optional (optional): * @param {boolean=} item.optional -
* True if this field can be set to null. Defaults to false. * True if this field can be set to null. Defaults to false.
* - initial_value (optional): * @param {*=} item.initial_value -
* Value this config field should take in a newly initialized * Value this config field should take in a newly initialized
* config. This can also be an async function returning the * config. This can also be an async function returning the
* value to use. * value to use.
+5
View File
@@ -314,6 +314,7 @@ function validateGroup(pluginInfo, groupName) {
/** /**
* Registers the config groups for the provided plugin infos * Registers the config groups for the provided plugin infos
* *
* @param {Array<Object>} pluginInfos - Array of plugin info objects.
* @memberof module:lib/config * @memberof module:lib/config
*/ */
function registerPluginConfigGroups(pluginInfos) { function registerPluginConfigGroups(pluginInfos) {
@@ -362,6 +363,7 @@ function finalizeConfigs() {
* Can be passed to yargs.command to implement a config command. Use * Can be passed to yargs.command to implement a config command. Use
* handleConfigCommand to do the requested action. * handleConfigCommand to do the requested action.
* *
* @param {Object} yargs - yargs command builder.
* @memberof module:lib/config * @memberof module:lib/config
*/ */
function configCommand(yargs) { function configCommand(yargs) {
@@ -379,6 +381,9 @@ function configCommand(yargs) {
* *
* Handle the actions that are made available by configCommand. * Handle the actions that are made available by configCommand.
* *
* @param {Object} args - yargs args object.
* @param {module:lib/config.Config} instance - Config instance.
* @param {string} configPath - Path to configuration file.
* @memberof module:lib/config * @memberof module:lib/config
*/ */
async function handleConfigCommand(args, instance, configPath) { async function handleConfigCommand(args, instance, configPath) {
+7 -3
View File
@@ -106,8 +106,11 @@ async function loadFile(server, modVersions, modPath) {
* *
* @param {module:lib/factorio.FactorioServer} server - * @param {module:lib/factorio.FactorioServer} server -
* The server to generate the export mod for. * The server to generate the export mod for.
* @param {Map<string, string>} modVersions -
* Mapping of mod name to versions to get icons from.
* @param {Array<Object>} items - Array of item prototypes. * @param {Array<Object>} items - Array of item prototypes.
* @return {itemSheet: Jimp, itemData: Map<string, Object>} Item spritesheet and metadata. * @return {{itemSheet: Jimp, itemData: Map<string,Object>}}
* Item spritesheet and metadata.
* @memberof module:lib/factorio * @memberof module:lib/factorio
* @private * @private
* @inner * @inner
@@ -259,9 +262,10 @@ async function exportItems(server, modVersions, items) {
* *
* @param {module:lib/factorio.FactorioServer} server - * @param {module:lib/factorio.FactorioServer} server -
* The server to export the locale from. * The server to export the locale from.
* @param modVersions {Map<string, string>} modVersions - * @param {Map<string, string>} modVersions -
* Mapping of mod name to version to export locale from. * Mapping of mod name to version to export locale from.
* @param modOrder {Array<string>} modOrder - Load order of the mods. * @param {Array<string>} modOrder - Load order of the mods.
* @param {string} languageCode - Language to export locale for.
* @returns {Map<string, string>} merged locale information * @returns {Map<string, string>} merged locale information
* @memberof module:lib/factorio * @memberof module:lib/factorio
* @private * @private
+2
View File
@@ -27,6 +27,7 @@ const knownScenarios = {
* Returns the name of the folder that all files in the zip file is * Returns the name of the folder that all files in the zip file is
* contained in. Throws an error if there are multiple such folders. * contained in. Throws an error if there are multiple such folders.
* *
* @param {module:jszip.JSZip} zip - Zip to search through.
* @returns {string} name of the root folder. * @returns {string} name of the root folder.
* @memberof module:lib/factorio * @memberof module:lib/factorio
* @private * @private
@@ -60,6 +61,7 @@ function findRoot(zip) {
* Generates control.lua code for loading the Clusterio modules * Generates control.lua code for loading the Clusterio modules
* *
* @param {Object} patchInfo - The patch info files's json content * @param {Object} patchInfo - The patch info files's json content
* @returns {string} Generated control.lua code.
* @memberof module:lib/factorio * @memberof module:lib/factorio
* @private * @private
* @inner * @inner
+15
View File
@@ -16,6 +16,7 @@ const errors = require("lib/errors");
* Determines the version of Factorio the datadir is pointing to by * Determines the version of Factorio the datadir is pointing to by
* reading the changelog.txt in it. * reading the changelog.txt in it.
* *
* @param {string} changelogPath - Path to changelog.txt.
* @memberof module:lib/factorio * @memberof module:lib/factorio
* @private * @private
* @inner * @inner
@@ -47,6 +48,9 @@ async function getVersion(changelogPath) {
/** /**
* Comparison function for sorting Factorio version strings * Comparison function for sorting Factorio version strings
* *
* @param {string} a - Version to compare.
* @param {string} b - Version to compare.
* @returns {number} 1 if a < b, 0 if a = b and -1 if a > b.
* @memberof module:lib/factorio * @memberof module:lib/factorio
* @private * @private
* @inner * @inner
@@ -74,6 +78,11 @@ function versionOrder(a, b) {
* Searches the given factorio dir for an installation of Factorio of * Searches the given factorio dir for an installation of Factorio of
* the target version. * the target version.
* *
* @param {string} factorioDir - Path to Factorio installation dir(s).
* @param {string} targetVersion -
* Version to look for, supports the special value "latest" for the
* latest version available.
* @returns {Array} Array with path to data dir and version found.
* @memberof module:lib/factorio * @memberof module:lib/factorio
* @private * @private
* @inner * @inner
@@ -1001,6 +1010,9 @@ class FactorioServer extends events.EventEmitter {
* Creates a path using path.join with the given parts that's relative to * Creates a path using path.join with the given parts that's relative to
* the data directory of the Factorio server. Not valid before init has * the data directory of the Factorio server. Not valid before init has
* been called. * been called.
*
* @param {...string} parts - Extra parts to add to the data path.
* @returns {string} Data directory path.
*/ */
dataPath(...parts) { dataPath(...parts) {
return path.join(this._dataDir, ...parts); return path.join(this._dataDir, ...parts);
@@ -1011,6 +1023,9 @@ class FactorioServer extends events.EventEmitter {
* *
* Creates a path using path.join with the given parts that's relative to * Creates a path using path.join with the given parts that's relative to
* the write directory of the Factorio server. * the write directory of the Factorio server.
*
* @param {...string} parts - Extra parts to add to the write path.
* @returns {string} Write directory path.
*/ */
writePath(...parts) { writePath(...parts) {
return path.join(this._writeDir, ...parts); return path.join(this._writeDir, ...parts);
+1 -1
View File
@@ -10,7 +10,7 @@ const fs = require("fs");
/** /**
* Returns a promise that resolves to the SHA1 hash of the stream given * Returns a promise that resolves to the SHA1 hash of the stream given
* *
* @param stream - Node stream of the content to hash. * @param {Stream} stream - Node stream of the content to hash.
* @returns {Promise<string>} hash of the stream. * @returns {Promise<string>} hash of the stream.
*/ */
function hashStream(stream) { function hashStream(stream) {
+1 -1
View File
@@ -10,7 +10,7 @@
* Works the same as typeof, excpet that null and array types get their * Works the same as typeof, excpet that null and array types get their
* own string. * own string.
* *
* @param value - value to return the type of. * @param {*} value - value to return the type of.
* @returns {string} basic type of the value passed. * @returns {string} basic type of the value passed.
*/ */
function basicType(value) { function basicType(value) {
+12 -2
View File
@@ -94,7 +94,9 @@ class WebSocketBaseConnector extends events.EventEmitter {
/** /**
* Send a message over the socket * Send a message over the socket
* *
* @returns the sequence number of the message sent * @param {string} type - Message type to send.
* @param {Object} data - Data to send with message.
* @returns {number} the sequence number of the message sent
*/ */
send(type, data) { send(type, data) {
if (!["handshake", "connected", "closing"].includes(this._state)) { if (!["handshake", "connected", "closing"].includes(this._state)) {
@@ -181,6 +183,9 @@ class WebSocketClientConnector extends WebSocketBaseConnector {
* *
* Used in the register function in order to send the register handshake * Used in the register function in order to send the register handshake
* message over the WebSocket. * message over the WebSocket.
*
* @param {string} type - Message type to send.
* @param {Object} data - Data to send with message.
*/ */
sendHandshake(type, data) { sendHandshake(type, data) {
this._check(["handshake"]); this._check(["handshake"]);
@@ -191,6 +196,9 @@ class WebSocketClientConnector extends WebSocketBaseConnector {
* Close the connection with the given reason. * Close the connection with the given reason.
* *
* Sends a close frame and disconnects the connector. * Sends a close frame and disconnects the connector.
*
* @param {number} code - WebSocket close code.
* @param {string} reason - WebSocket close reason.
*/ */
async close(code, reason) { async close(code, reason) {
if (this._state === "new") { if (this._state === "new") {
@@ -449,7 +457,9 @@ class VirtualConnector extends events.EventEmitter {
/** /**
* Send a message to the other end of the connector * Send a message to the other end of the connector
* *
* @returns the sequence number of the message sent * @param {string} type - Message type to send.
* @param {Object} data - Data to send with message.
* @returns {number} the sequence number of the message sent
*/ */
send(type, data) { send(type, data) {
this.other.emit("message", { seq: this._seq, type, data }); this.other.emit("message", { seq: this._seq, type, data });
+6
View File
@@ -72,6 +72,7 @@ class Link {
* Validates and invokes the handler and/or waiters for a message that has * Validates and invokes the handler and/or waiters for a message that has
* been received. An unhandled message is considered to be an error. * been received. An unhandled message is considered to be an error.
* *
* @param {Object} message - Message to process.
* @throws {module:lib/errors.InvalidMessage} * @throws {module:lib/errors.InvalidMessage}
* if validation failed, is missing, the message is invalid, or no * if validation failed, is missing, the message is invalid, or no
* handlers/waiters were invoked to handle the message. * handlers/waiters were invoked to handle the message.
@@ -102,6 +103,7 @@ class Link {
/** /**
* Invoke the handler for this message if it exists * Invoke the handler for this message if it exists
* *
* @param {Object} message - Message to invoke handlers on.
* @returns {Boolean} true if a handler was invoked. * @returns {Boolean} true if a handler was invoked.
*/ */
_processHandler(message) { _processHandler(message) {
@@ -117,6 +119,7 @@ class Link {
/** /**
* Invokes the waiters for this message if any * Invokes the waiters for this message if any
* *
* @param {Object} message - Message to invoke waiters on.
* @returns {Boolean} true if a waiter was triggered. * @returns {Boolean} true if a waiter was triggered.
*/ */
_processWaiters(message) { _processWaiters(message) {
@@ -196,6 +199,9 @@ class Link {
* as any properties specified in data. For example specifying { foo: * as any properties specified in data. For example specifying { foo:
* 21 } as the data will cause it to wait until a message with the right * 21 } as the data will cause it to wait until a message with the right
* type and a foo property value of 21 in the data payload. * type and a foo property value of 21 in the data payload.
*
* @param {string} type - Message type to wait for.
* @param {Object} data - Properties to match in the message data.
*/ */
async waitFor(type, data) { async waitFor(type, data) {
if (!this._validators.has(type)) { if (!this._validators.has(type)) {
+6
View File
@@ -208,6 +208,8 @@ class Request extends Message {
* Sends the given data over the link as the request payload and waits * Sends the given data over the link as the request payload and waits
* for the response. * for the response.
* *
* @param {module:lib/link.Link} link - Link to send request over.
* @param {Object} data - Data to send with the request.
* @returns {object} response data * @returns {object} response data
*/ */
async send(link, data = {}) { async send(link, data = {}) {
@@ -726,6 +728,9 @@ class Event extends Message {
* Send event over the given link * Send event over the given link
* *
* Sends the given event data over the link. * Sends the given event data over the link.
*
* @param {module:lib/link.Link} link - Link to send event over.
* @param {Object} data - Data to send with the event.
*/ */
send(link, data = {}) { send(link, data = {}) {
if (!this._eventValidator({ seq: 0, type: this.eventType, data })) { if (!this._eventValidator({ seq: 0, type: this.eventType, data })) {
@@ -843,6 +848,7 @@ messages.playerEvent = new Event({
* link instance as the concatenation of the name of the message, the * link instance as the concatenation of the name of the message, the
* name of message class, and 'Handler'. * name of message class, and 'Handler'.
* *
* @param {module:lib/link.Link} link - Link to attach messages to.
* @memberof module:lib/link * @memberof module:lib/link
*/ */
function attachAllMessages(link) { function attachAllMessages(link) {
+3
View File
@@ -6,6 +6,9 @@
/** /**
* Escapes a string for inclusion into a lua string * Escapes a string for inclusion into a lua string
*
* @param {string} content - String to escape.
* @returns {string} Escaped string.
*/ */
function escapeString(content) { function escapeString(content) {
return content return content
+2
View File
@@ -37,6 +37,7 @@ function formatBytes(size, decimals) {
/** /**
Lists mods for an instance as a table. Warning, handles printing internally. Lists mods for an instance as a table. Warning, handles printing internally.
@param {Object} config - Obsolete config
@param {Instance} instance - Instance object, see slave.js @param {Instance} instance - Instance object, see slave.js
@example @example
@@ -109,6 +110,7 @@ async function listMods(config, instance) {
Searches mods.factorio.com for mods matching a search term and prints Searches mods.factorio.com for mods matching a search term and prints
the results to console as a neat looking table the results to console as a neat looking table
@param {Object} config - Obsolete config
@param {string} searchTerm What to search for @param {string} searchTerm What to search for
*/ */
async function findMods(config, searchTerm) { async function findMods(config, searchTerm) {
+2 -2
View File
@@ -7,7 +7,7 @@ Helper functions related to objects
/** /**
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} @returns {object} The cloned object.
@example @example
a = {"thingy":"with a value"}; a = {"thingy":"with a value"};
@@ -22,7 +22,7 @@ module.exports.deepclone = function(obj){
/** /**
Checks if a string is valid JSON using try/catch. If passed an object it will always return 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 @param {string} string to verify
@returns {boolean} @returns {boolean} true if valid JSON.
@example @example
objectOps.isJSON("99 bottles of beer"); // false objectOps.isJSON("99 bottles of beer"); // false
+29 -15
View File
@@ -9,6 +9,11 @@ const path = require("path");
const errors = require("lib/errors"); const errors = require("lib/errors");
/**
* Conceptual base for master and instance plugins.
* @typedef {module:lib/plugin.BaseMasterPlugin|module:lib/plugin.BaseInstancePlugin} module:lib/plugin.BasePlugin
*/
/** /**
* Base class for instance plugins * Base class for instance plugins
* @static * @static
@@ -51,7 +56,7 @@ class BaseInstancePlugin {
* @param {module:lib/config.ConfigGroup} group - * @param {module:lib/config.ConfigGroup} group -
* The group who's field got changed on. * The group who's field got changed on.
* @param {string} field - Name of the field that changed. * @param {string} field - Name of the field that changed.
* @param prev - The previous value of the field. * @param {*} prev - The previous value of the field.
*/ */
async onInstanceConfigFieldChanged(group, field, prev) { } async onInstanceConfigFieldChanged(group, field, prev) { }
@@ -68,7 +73,7 @@ class BaseInstancePlugin {
* the Gauges/Counters/etc in onMetric and let Clusterio deal will * the Gauges/Counters/etc in onMetric and let Clusterio deal will
* collecting the values. * collecting the values.
* *
* @returns an async iterator of prometheus metric results or undefined. * @returns {*} an async iterator of prometheus metric results or undefined.
*/ */
async onMetrics() { } async onMetrics() { }
@@ -99,16 +104,23 @@ class BaseInstancePlugin {
* *
* Called when the Factorio server outputs a line on either stdout or * Called when the Factorio server outputs a line on either stdout or
* stderr. The output is a parsed form of the line and contains the * stderr. The output is a parsed form of the line and contains the
* following properties (those marked with ? are optional): * following properties:
* *
* - source: Where the message came from, one of "stdout" and "stderr". * @param {Object} output - parsed server output.
* - format: Timestamp format, one of "date", "seconds" and "none". * @param {string} output.source -
* - time?: Timestamp of the message. Not present if format is "none". * Where the message came from, one of "stdout" and "stderr".
* - type: Type of message, one of "log", "action" and "generic". * @param {string} output.format -
* - level?: Log level for "log" type. i.e "Info" normally. * Timestamp format, one of "date", "seconds" and "none".
* - file?: File reported for "log" type. * @param {string=} output.time -
* - action?: Kind of action for "action" type. i.e "CHAT" for chat. * Timestamp of the message. Not present if format is "none".
* - message: Main content of the line. * @param {string} output.type -
* Type of message, one of "log", "action" and "generic".
* @param {string=} output.level -
* Log level for "log" type. i.e "Info" normally.
* @param {string=} output.file - File reported for "log" type.
* @param {string=} output.action -
* Kind of action for "action" type. i.e "CHAT" for chat.
* @param {string} output.message - Main content of the line.
*/ */
async onOutput(output) { } async onOutput(output) { }
@@ -215,7 +227,7 @@ class BaseMasterPlugin {
* the Gauges/Counters/etc in onMetric and let Clusterio deal will * the Gauges/Counters/etc in onMetric and let Clusterio deal will
* collecting the values. * collecting the values.
* *
* @returns an async iterator of prometheus metric results or undefined. * @returns {*} an async iterator of prometheus metric results or undefined.
*/ */
async onMetrics() { } async onMetrics() { }
@@ -249,9 +261,9 @@ class BaseMasterPlugin {
* *
* Invoked when the connection to the slave has been closed. * Invoked when the connection to the slave has been closed.
* *
* @param {string} event - one of connect, drop, and close
* @param {module:master~SlaveConnection} connection - * @param {module:master~SlaveConnection} connection -
* The connection the event occured on. * The connection the event occured on.
* @param {string} event - one of connect, drop, and close
*/ */
onSlaveConnectionEvent(connection, event) { } onSlaveConnectionEvent(connection, event) { }
@@ -311,6 +323,7 @@ class BaseMasterPlugin {
* module. Once loaded the info modules will not be reloaded should this * module. Once loaded the info modules will not be reloaded should this
* function be called again. * function be called again.
* *
* @param {string} baseDir - posix relative path to plugin directory.
* @returns {Map<string, Object>} mapping of plugin name to info module. * @returns {Map<string, Object>} mapping of plugin name to info module.
* @static * @static
*/ */
@@ -350,7 +363,8 @@ async function loadPluginInfos(baseDir) {
* *
* @param {module:lib/link.Link} link - Link to attach handlers to. * @param {module:lib/link.Link} link - Link to attach handlers to.
* @param {object} pluginInfo - Plugin info object. * @param {object} pluginInfo - Plugin info object.
* @param plugin - The instance of the plugin to use handlers from. * @param {module:lib/plugin.BasePlugin} plugin -
* The instance of the plugin to use handlers from.
*/ */
function attachPluginMessages(link, pluginInfo, plugin) { function attachPluginMessages(link, pluginInfo, plugin) {
let messageDefinitions = pluginInfo.messages || []; let messageDefinitions = pluginInfo.messages || [];
@@ -374,7 +388,7 @@ function attachPluginMessages(link, pluginInfo, plugin) {
/** /**
* Invokes the given hook on all plugins * Invokes the given hook on all plugins
* *
* @param {Map<string, Object} plugins - * @param {Map<string, Object>} plugins -
* Mapping of plugin names to plugins to invoke the hook on. * Mapping of plugin names to plugins to invoke the hook on.
* @param {string} hook - Name of hook to invoke. * @param {string} hook - Name of hook to invoke.
* @param {...*} args - Arguments to pass on to the hook. * @param {...*} args - Arguments to pass on to the hook.
+6 -3
View File
@@ -95,6 +95,7 @@ class Role {
* *
* Ensures the role with id 0 exisits and has the core.admin permission. * Ensures the role with id 0 exisits and has the core.admin permission.
* *
* @param {Map<number, module:lib/user.Role>} roles - role storage to modify.
* @returns {module:lib/permission.Role} the default admin role * @returns {module:lib/permission.Role} the default admin role
* @static * @static
*/ */
@@ -115,7 +116,7 @@ function ensureDefaultAdminRole(roles) {
* assigned by default. Note that this may not be the same role as the one * assigned by default. Note that this may not be the same role as the one
* that is assigned to new users by default. * that is assigned to new users by default.
* *
* @returns {module:lib/permission.Role} the default player role * @param {Map<number, module:lib/user.Role>} roles - role storage to modify.
* @static * @static
*/ */
function ensureDefaultPlayerRole(roles) { function ensureDefaultPlayerRole(roles) {
@@ -156,7 +157,7 @@ class User {
/** /**
* Roles this user has * Roles this user has
* @type {Set<module:lib/permissions.Role} * @type {Set<module:lib/permissions.Role>}
*/ */
this.roles = new Set(); this.roles = new Set();
if (roles) { if (roles) {
@@ -186,6 +187,7 @@ class User {
* Generate access token for this user * Generate access token for this user
* *
* @param {string} secret - Secret to sign token with. * @param {string} secret - Secret to sign token with.
* @returns {string} JWT access token for the user.
*/ */
createToken(secret) { createToken(secret) {
return jwt.sign({ aud: "user", user: this.name }, secret); return jwt.sign({ aud: "user", user: this.name }, secret);
@@ -197,7 +199,7 @@ class User {
* Sets the tokenValidAfter property to the current time, which causes * Sets the tokenValidAfter property to the current time, which causes
* all currently issued tokens for the user to become invalid. * all currently issued tokens for the user to become invalid.
*/ */
invalidateToken(secret) { invalidateToken() {
this.tokenValidAfter = Math.floor(Date.now() / 1000); this.tokenValidAfter = Math.floor(Date.now() / 1000);
} }
@@ -208,6 +210,7 @@ class User {
* permission. If the permission is not granted for the user a * permission. If the permission is not granted for the user a
* "Permission denied" error is thrown. * "Permission denied" error is thrown.
* *
* @param {string} permission - The permission to check for.
* @throws {Error} if the user does noh have the given permission. * @throws {Error} if the user does noh have the given permission.
*/ */
checkPermission(permission) { checkPermission(permission) {
+24 -1
View File
@@ -247,6 +247,10 @@ const db = {};
/** /**
* Load Map from JSON file in the database directory. * Load Map from JSON file in the database directory.
*
* @param {string} databaseDirectory - Path to master database directory.
* @param {string} file - Name of file to load.
* @returns {Map} file loaded as a map.
*/ */
async function loadMap(databaseDirectory, file) { async function loadMap(databaseDirectory, file) {
let databasePath = path.resolve(databaseDirectory, file); let databasePath = path.resolve(databaseDirectory, file);
@@ -326,6 +330,10 @@ function createUser(name) {
/** /**
* Save Map to JSON file in the database directory. * Save Map to JSON file in the database directory.
*
* @param {string} databaseDirectory - Path to master database directory.
* @param {string} file - Name of file to save.
* @param {Map} map - Mapping to save into file.
*/ */
async function saveMap(databaseDirectory, file, map) { async function saveMap(databaseDirectory, file, map) {
let databasePath = path.resolve(databaseDirectory, file); let databasePath = path.resolve(databaseDirectory, file);
@@ -977,7 +985,7 @@ const wss = new WebSocket.Server({
/** /**
* Returns true if value is a signed 32-bit integer * Returns true if value is a signed 32-bit integer
* *
* @param value - value to test. * @param {number} value - value to test.
* @returns {Boolean} * @returns {Boolean}
* true if value is an integer between -2<sup>31</sup> and * true if value is an integer between -2<sup>31</sup> and
* 2<sup>31</sup>-1. * 2<sup>31</sup>-1.
@@ -1021,6 +1029,9 @@ class WebSocketServerConnector extends link.WebSocketBaseConnector {
* Send ready over the socket * Send ready over the socket
* *
* Sends the ready message over the socket to initiate the session. * Sends the ready message over the socket to initiate the session.
*
* @param {string} sessionToken -
* the session token to send to the client.
*/ */
ready(sessionToken) { ready(sessionToken) {
this._heartbeatInterval = masterConfig.get("master.heartbeat_interval"); this._heartbeatInterval = masterConfig.get("master.heartbeat_interval");
@@ -1044,6 +1055,9 @@ class WebSocketServerConnector extends link.WebSocketBaseConnector {
* *
* Terminates the current socket and contiunes the session over the * Terminates the current socket and contiunes the session over the
* socket given from the message sequence given. * socket given from the message sequence given.
*
* @param {module:net.Socket} socket - New socket to continue on.
* @param {number} lastSeq - The last message the client received.
*/ */
continue(socket, lastSeq) { continue(socket, lastSeq) {
this._socket.terminate(); this._socket.terminate();
@@ -1164,6 +1178,9 @@ class WebSocketServerConnector extends link.WebSocketBaseConnector {
* Close the connection with the given reason. * Close the connection with the given reason.
* *
* Sends a close frame and disconnects the connector. * Sends a close frame and disconnects the connector.
*
* @param {number} code - WebSocket close code.
* @param {string} reason - WebSocket close reason.
*/ */
async close(code, reason) { async close(code, reason) {
if (this._state === "closed") { if (this._state === "closed") {
@@ -1399,6 +1416,10 @@ async function loadPlugins(pluginInfos) {
* Calls listen on server capturing any errors that occurs * Calls listen on server capturing any errors that occurs
* binding to the port. Also adds handler for WebSocket * binding to the port. Also adds handler for WebSocket
* upgrade event. * upgrade event.
*
* @param {module:net.Server} server - Server to start the listening on.
* @param {*} args - Arguments to the .listen() call on the server.
* @returns {Promise} promise that resolves the server is listening.
*/ */
function listen(server, ...args) { function listen(server, ...args) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@@ -1432,6 +1453,8 @@ function _setConfig(config) {
/** /**
* Returns the URL needed to connect to the master server. * Returns the URL needed to connect to the master server.
*
* @returns {string} master URL.
*/ */
function getMasterUrl() { function getMasterUrl() {
let url = masterConfig.get("master.external_address"); let url = masterConfig.get("master.external_address");
+3
View File
@@ -8,6 +8,9 @@ const luaTools = require("lib/luaTools");
/** /**
* Removes gps and train tags from messags * Removes gps and train tags from messags
*
* @param {string} content - string to strip tags from.
* @returns {string} stripped string.
*/ */
function removeTags(content) { function removeTags(content) {
return content.replace(/(\[gps=-?\d+,-?\d+\]|\[train=\d+\])/g, ""); return content.replace(/(\[gps=-?\d+,-?\d+\]|\[train=\d+\])/g, "");
+10 -6
View File
@@ -240,7 +240,8 @@ class Instance extends link.Link{
* entries from the given settings object. * entries from the given settings object.
* *
* @param {Object} overrides - Server settings to override. * @param {Object} overrides - Server settings to override.
* @returns server example settings with the given settings applied over it. * @returns {Object}
* server example settings with the given settings applied over it.
*/ */
async resolveServerSettings(overrides) { async resolveServerSettings(overrides) {
let serverSettings = await this.server.exampleSettings(); let serverSettings = await this.server.exampleSettings();
@@ -276,13 +277,11 @@ class Instance extends link.Link{
* Creates the neccessary files for starting up a new instance into the * Creates the neccessary files for starting up a new instance into the
* provided instance directory. * provided instance directory.
* *
* @param {Number} id -
* ID of the new instance. Must be unique to the cluster.
* @param {String} instanceDir - * @param {String} instanceDir -
* Directory to create the new instance into. * Directory to create the new instance into.
* @param {String} factorioDir - Path to factorio installation. * @param {String} factorioDir - Path to factorio installation.
*/ */
static async create(instanceConfig, instanceDir, factorioDir) { static async create(instanceDir, factorioDir) {
console.log(`Clusterio | Creating ${instanceDir}`); console.log(`Clusterio | Creating ${instanceDir}`);
await fs.ensureDir(instanceDir); await fs.ensureDir(instanceDir);
await fs.ensureDir(path.join(instanceDir, "script-output")); await fs.ensureDir(path.join(instanceDir, "script-output"));
@@ -570,6 +569,8 @@ class Instance extends link.Link{
* the directory of the instance. For example instance.path("mods") * the directory of the instance. For example instance.path("mods")
* returns a path to the mods directory of the instance. If no parts are * returns a path to the mods directory of the instance. If no parts are
* given it returns a path to the directory of the instance. * given it returns a path to the directory of the instance.
*
* @returns {string} path in instance directory.
*/ */
path(...parts) { path(...parts) {
return path.join(this._dir, ...parts); return path.join(this._dir, ...parts);
@@ -586,7 +587,7 @@ class Instance extends link.Link{
* @param {Map<integer, Object>} instanceInfos - * @param {Map<integer, Object>} instanceInfos -
* mapping between instance id and information about this instance. * mapping between instance id and information about this instance.
* @param {string} instancesDir - Directory containing instances * @param {string} instancesDir - Directory containing instances
* @param logger - console like logging interface. * @param {Object} logger - console like logging interface.
*/ */
async function discoverInstances(instanceInfos, instancesDir, logger) { async function discoverInstances(instanceInfos, instancesDir, logger) {
for (let entry of await fs.readdir(instancesDir, { withFileTypes: true })) { for (let entry of await fs.readdir(instancesDir, { withFileTypes: true })) {
@@ -862,7 +863,7 @@ class Slave extends link.Link {
// XXX: race condition on multiple simultanious calls // XXX: race condition on multiple simultanious calls
let instanceDir = await this._findNewInstanceDir(instanceConfig.get("instance.name")); let instanceDir = await this._findNewInstanceDir(instanceConfig.get("instance.name"));
await Instance.create(instanceConfig, instanceDir, this.config.get("slave.factorio_directory")); await Instance.create(instanceDir, this.config.get("slave.factorio_directory"));
instanceInfo = { instanceInfo = {
path: instanceDir, path: instanceDir,
config: instanceConfig, config: instanceConfig,
@@ -885,6 +886,9 @@ class Slave extends link.Link {
/** /**
* Initialize and connect an unloaded instance * Initialize and connect an unloaded instance
*
* @param {number} instanceId - ID of instance to initialize.
* @returns {module:slave~InstanceConnection} connection to instance.
*/ */
async _connectInstance(instanceId) { async _connectInstance(instanceId) {
let instanceInfo = this.instanceInfos.get(instanceId); let instanceInfo = this.instanceInfos.get(instanceId);