Port remaining plugins to Typescript (#499)

* .js to .ts

* Allow access to _items entries; getItemCount return number

* add permission field to PluginPage interface

* port plugins to typescript

* update Request classes

* fix IpcFlowType
This commit is contained in:
Luciole authored and GitHub committed 2023-08-22 16:17:16 +02:00
1 parent 50f12c719b
commit 0b3550b472
51 files changed
+1033 -1026

No files matched your search

@@ -1,42 +1,52 @@
"use strict";
const fs = require("fs-extra");
const path = require("path");
import fs from "fs-extra";
import path from "path";
const lib = require("@clusterio/lib");
import * as lib from "@clusterio/lib";
const { RateLimiter } = lib;
const {
import {
ContributionEvent,
ProgressEvent,
FinishedEvent,
Technology,
SyncTechnologiesRequest,
} = require("./messages");
} from "./messages";
async function loadTechnologies(controllerConfig, logger) {
async function loadTechnologies(
controllerConfig: lib.ControllerConfig,
logger: lib.Logger
): Promise<Map<any, any>> {
let filePath = path.join(controllerConfig.get("controller.database_directory"), "technologies.json");
logger.verbose(`Loading ${filePath}`);
try {
return new Map(JSON.parse(await fs.readFile(filePath)));
return new Map(JSON.parse(await fs.readFile(filePath, { encoding: "utf8" })));
} catch (err) {
} catch (err: any) {
if (err.code === "ENOENT") {
logger.verbose("Creating new technologies database");
return new Map();
}
throw err;
}
}
async function saveTechnologies(controllerConfig, technologies, logger) {
async function saveTechnologies(
controllerConfig: lib.ControllerConfig,
technologies: Map<any, any>,
logger: lib.Logger
) {
let filePath = path.join(controllerConfig.get("controller.database_directory"), "technologies.json");
logger.verbose(`writing ${filePath}`);
await lib.safeOutputFile(filePath, JSON.stringify([...technologies.entries()], null, 4));
}
class ControllerPlugin extends lib.BaseControllerPlugin {
export class ControllerPlugin extends lib.BaseControllerPlugin {
technologies!: Map<string, Technology>;
progressRateLimiter!: lib.RateLimiter;
progressBroadcastId!: ReturnType<typeof setInterval> | null;
progressToBroadcast!: Set<string>;
async init() {
this.technologies = await loadTechnologies(this.controller.config, this.logger);
this.progressRateLimiter = new RateLimiter({
@@ -61,8 +71,8 @@ class ControllerPlugin extends lib.BaseControllerPlugin {
let techs = [];
for (let name of this.progressToBroadcast) {
let tech = this.technologies.get(name);
if (tech.progress) {
techs.push({ name, level: tech.level, progress: tech.progress });
if (tech && tech.progress) {
techs.push(new Technology(name, tech.level, tech.progress, false));
}
}
this.progressToBroadcast.clear();
@@ -72,11 +82,11 @@ class ControllerPlugin extends lib.BaseControllerPlugin {
}
}
async handleContributionEvent(event) {
async handleContributionEvent(event: ContributionEvent) {
let { name, level, contribution } = event;
let tech = this.technologies.get(name);
if (!tech) {
tech = { level, progress: 0, researched: false };
tech = new Technology(name, level, 0, false);
this.technologies.set(name, tech);
// Ignore contribution to already researched technologies
@@ -95,11 +105,11 @@ class ControllerPlugin extends lib.BaseControllerPlugin {
return;
}
let newProgress = tech.progress + contribution;
let newProgress = tech.progress! + contribution;
if (newProgress < 1) {
tech.progress = newProgress;
this.progressToBroadcast.add(name);
this.progressRateLimiter.activate();
this.progressRateLimiter!.activate();
} else {
tech.researched = true;
@@ -110,17 +120,17 @@ class ControllerPlugin extends lib.BaseControllerPlugin {
}
}
async handleFinishedEvent(event) {
async handleFinishedEvent(event: FinishedEvent) {
let { name, level } = event;
let tech = this.technologies.get(name);
if (!tech || tech.level <= level) {
this.progressToBroadcast.delete(name);
this.technologies.set(name, { level, progress: null, researched: true });
this.technologies.set(name, new Technology(name, level, null, true));
}
}
async handleSyncTechnologiesRequest(request) {
function baseLevel(name) {
async handleSyncTechnologiesRequest(request: SyncTechnologiesRequest): Promise<Technology[]> {
function baseLevel(name: string): number {
let match = /-(\d+)$/.exec(name);
if (!match) {
return 1;
@@ -132,11 +142,11 @@ class ControllerPlugin extends lib.BaseControllerPlugin {
let { name, level, progress, researched } = instanceTech;
let tech = this.technologies.get(name);
if (!tech) {
this.technologies.set(name, { level, progress, researched });
this.technologies.set(name, new Technology(name, level, progress, researched));
if (progress) {
this.progressToBroadcast.add(name);
} else if (researched || baseLevel(name) !== level) {
this.controller.sendTo("allInstances", new FinishedEvent(name, tech));
this.controller.sendTo("allInstances", new FinishedEvent(name, level));
}
} else {
@@ -146,8 +156,8 @@ class ControllerPlugin extends lib.BaseControllerPlugin {
if (tech.level < level || researched) {
// Send update if the unlocked level is greater
if (level - !researched > tech.level - !tech.researched) {
this.controller.sendTo("allInstances", new FinishedEvent(name, level - !researched));
if (level - Number(!researched) > tech.level - Number(!tech.researched)) {
this.controller.sendTo("allInstances", new FinishedEvent(name, level - Number(!researched)));
}
tech.level = level;
tech.progress = progress;
@@ -159,7 +169,7 @@ class ControllerPlugin extends lib.BaseControllerPlugin {
this.progressToBroadcast.delete(name);
}
} else if (tech.progress < progress) {
} else if (tech.progress && progress && tech.progress < progress) {
tech.progress = progress;
this.progressToBroadcast.add(name);
}
@@ -175,8 +185,3 @@ class ControllerPlugin extends lib.BaseControllerPlugin {
return technologies;
}
}
module.exports = {
ControllerPlugin,
};
@@ -1,12 +1,13 @@
"use strict";
const messages = require("./messages");
import type { PluginInfo } from "@clusterio/lib";
module.exports.default = {
import * as messages from "./messages";
const info: PluginInfo = {
name: "research_sync",
title: "Research Sync",
description: "Synchronises technology research progress between instances.",
instanceEntrypoint: "instance",
controllerEntrypoint: "controller",
instanceEntrypoint: "dist/plugin/instance",
controllerEntrypoint: "dist/plugin/controller",
messages: [
messages.ContributionEvent,
@@ -15,3 +16,5 @@ module.exports.default = {
messages.SyncTechnologiesRequest,
],
};
export default info;
@@ -1,16 +1,27 @@
"use strict";
const lib = require("@clusterio/lib");
const {
import * as lib from "@clusterio/lib";
import {
ContributionEvent,
ProgressEvent,
FinishedEvent,
Technology,
SyncTechnologiesRequest,
} = require("./messages");
} from "./messages";
// ./module/sync.lua
type IpcContribution = {
name: string,
level: number,
contribution: number,
};
type IpcFinished = {
name: string,
level: number,
};
class InstancePlugin extends lib.BaseInstancePlugin {
unexpectedError(err) {
export class InstancePlugin extends lib.BaseInstancePlugin {
syncStarted!: boolean;
unexpectedError(err: Error) {
this.logger.error(`Unexpected error:\n${err.stack}`);
}
@@ -19,10 +30,10 @@ class InstancePlugin extends lib.BaseInstancePlugin {
throw new Error("research_sync plugin requires save patching.");
}
this.instance.server.on("ipc-research_sync:contribution", (tech) => {
this.instance.server.on("ipc-research_sync:contribution", (tech: IpcContribution) => {
this.researchContribution(tech).catch(err => this.unexpectedError(err));
});
this.instance.server.on("ipc-research_sync:finished", (tech) => {
this.instance.server.on("ipc-research_sync:finished", (tech: IpcFinished) => {
this.researchFinished(tech).catch(err => this.unexpectedError(err));
});
@@ -31,11 +42,11 @@ class InstancePlugin extends lib.BaseInstancePlugin {
this.instance.handle(FinishedEvent, this.handleFinishedEvent.bind(this));
}
async researchContribution(tech) {
async researchContribution(tech: IpcContribution) {
this.instance.sendTo("controller", new ContributionEvent(tech.name, tech.level, tech.contribution));
}
async handleProgressEvent(event) {
async handleProgressEvent(event: ProgressEvent) {
if (!this.syncStarted || !["starting", "running"].includes(this.instance.status)) {
return;
}
@@ -43,11 +54,11 @@ class InstancePlugin extends lib.BaseInstancePlugin {
await this.sendOrderedRcon(`/sc research_sync.update_progress("${techsJson}")`, true);
}
async researchFinished(tech) {
async researchFinished(tech: IpcFinished) {
this.instance.sendTo("allInstances", new FinishedEvent(tech.name, tech.level));
}
async handleFinishedEvent(event) {
async handleFinishedEvent(event: FinishedEvent) {
if (!this.syncStarted || !["starting", "running"].includes(this.instance.status)) {
return;
}
@@ -93,7 +104,3 @@ class InstancePlugin extends lib.BaseInstancePlugin {
}
}
}
module.exports = {
InstancePlugin,
};
-179
View File
@@ -1,179 +0,0 @@
"use strict";
const lib = require("@clusterio/lib");
class ContributionEvent {
static type = "event";
static src = "instance";
static dst = "controller";
static plugin = "research_sync";
/** @type {string} */
name;
/** @type {number} */
level;
/** @type {number} */
contribution;
constructor(name, level, contribution) {
this.name = name;
this.level = level;
this.contribution = contribution;
}
static jsonSchema = {
type: "object",
required: ["name", "level", "contribution"],
properties: {
name: { type: "string" },
level: { type: "integer" },
contribution: { type: "number" },
},
};
static fromJSON(json) {
return new this(json.name, json.level, json.contribution);
}
}
class ProgressEvent {
static type = "event";
static src = "controller";
static dst = "instance";
static plugin = "research_sync";
/** @type {Array<Technology>} */
technologies;
constructor(technologies) {
this.technologies = technologies;
}
static jsonSchema = {
type: "object",
required: ["technologies"],
properties: {
technologies: {
type: "array",
items: {
type: "object",
required: ["name", "level", "progress"],
properties: {
name: { type: "string" },
level: { type: "integer" },
progress: { type: "number" },
},
additionalProperties: false,
},
},
},
};
static fromJSON(json) {
return new this(json.technologies);
}
}
class FinishedEvent {
static type = "event";
static src = ["instance", "controller"];
static dst = "instance";
static plugin = "research_sync";
/** @type {string} */
name;
/** @type {number} */
level;
constructor(name, level) {
this.name = name;
this.level = level;
}
static jsonSchema = {
type: "object",
required: ["name", "level"],
properties: {
name: { type: "string" },
level: { type: "integer" },
},
};
static fromJSON(json) {
return new this(json.name, json.level);
}
}
class Technology {
/** @type {string} */
name;
/** @type {number} */
level;
/** @type {?number} */
progress;
/** @type {boolean} */
researched;
constructor(name, level, progress, researched) {
this.name = name;
this.level = level;
this.progress = progress;
this.researched = researched;
}
static jsonSchema = {
type: "array",
minItems: 4,
maxItems: 4,
items: [
{ type: "string" },
{ type: "integer" },
{ type: ["null", "number"] },
{ type: "boolean" },
],
};
toJSON() {
return [this.name, this.level, this.progress, this.researched];
}
static fromJSON(json) {
return new this(json[0], json[1], json[2], json[3]);
}
}
class SyncTechnologiesRequest {
static type = "request";
static src = "instance";
static dst = "controller";
static plugin = "research_sync";
/** @type {Array<Technology>} */
technologies;
constructor(technologies) {
this.technologies = technologies;
}
static jsonSchema = {
type: "array",
items: Technology.jsonSchema,
};
toJSON() {
return this.technologies;
}
static fromJSON(json) {
return new this(json.map(e => Technology.fromJSON(e)));
}
static Response = lib.jsonArray(Technology);
}
module.exports = {
ContributionEvent,
ProgressEvent,
FinishedEvent,
Technology,
SyncTechnologiesRequest,
};
+137
View File
@@ -0,0 +1,137 @@
import { Type, Static } from "@sinclair/typebox";
import * as lib from "@clusterio/lib";
export class ContributionEvent {
declare ["constructor"]: typeof ContributionEvent;
static type = "event" as const;
static src = "instance" as const;
static dst = "controller" as const;
static plugin = "research_sync" as const;
constructor(
public name: string,
public level: number,
public contribution: number
) {
}
static jsonSchema = Type.Object({
"name": Type.String(),
"level": Type.Integer(),
"contribution": Type.Number(),
})
static fromJSON(json: Static<typeof ContributionEvent.jsonSchema>): ContributionEvent {
return new this(json.name, json.level, json.contribution);
}
}
export class TechnologyProgress {
constructor(
public name: string,
public level: number,
public progress: number | null,
) {
}
static jsonSchema = Type.Object({
"name": Type.String(),
"level": Type.Integer(),
"progress": Type.Number(),
})
}
export class ProgressEvent {
declare ["constructor"]: typeof ProgressEvent;
static type = "event" as const;
static src = "controller" as const;
static dst = "instance" as const;
static plugin = "research_sync" as const;
constructor(
public technologies: TechnologyProgress[],
) {
}
static jsonSchema = Type.Object({
"technologies": Type.Array(
TechnologyProgress.jsonSchema
)
})
static fromJSON(json: Static<typeof ProgressEvent.jsonSchema>): ProgressEvent {
return new this(json.technologies);
}
}
export class FinishedEvent {
declare ["constructor"]: typeof FinishedEvent;
static type = "event" as const;
static src = ["instance", "controller"] as const;
static dst = "instance" as const;
static plugin = "research_sync" as const;
constructor(
public name: string,
public level: number,
) {
}
static jsonSchema = Type.Object({
"name": Type.String(),
"level": Type.Integer(),
})
static fromJSON(json: Static<typeof FinishedEvent.jsonSchema>): FinishedEvent {
return new this(json.name, json.level);
}
}
export class Technology {
constructor(
public name: string,
public level: number,
public progress: number | null,
public researched: boolean,
) {
}
static jsonSchema = Type.Tuple([
Type.String(),
Type.Integer(),
Type.Union([ Type.Number(), Type.Null() ]),
Type.Boolean(),
])
toJSON() {
return [this.name, this.level, this.progress, this.researched];
}
static fromJSON(json: Static<typeof Technology.jsonSchema>): Technology {
return new this(json[0], json[1], json[2], json[3]);
}
}
export class SyncTechnologiesRequest {
declare ["constructor"]: typeof SyncTechnologiesRequest;
static type = "request" as const;
static src = "instance" as const;
static dst = "controller" as const;
static plugin = "research_sync" as const;
constructor(
public technologies: Technology[]
) {
}
static jsonSchema = Type.Array(Technology.jsonSchema);
toJSON() {
return this.technologies;
}
static fromJSON(json: Static<typeof SyncTechnologiesRequest.jsonSchema>): SyncTechnologiesRequest {
return new this(json.map(e => Technology.fromJSON(e)));
}
static Response = lib.jsonArray(Technology);
}
+6 -2
View File
@@ -6,9 +6,9 @@
"homepage": "https://github.com/clusterio/clusterio#readme",
"license": "MIT",
"repository": "clusterio/clusterio",
"main": "./info.js",
"main": "dist/plugin/info.js",
"scripts": {
"prepare": "webpack-cli --env production",
"prepare": "tsc --build && webpack-cli --env production",
"test": "echo \"Error: run tests from root\" && exit 1"
},
"bugs": {
@@ -21,11 +21,15 @@
"@clusterio/lib": "^2.0.0-alpha.0"
},
"dependencies": {
"@sinclair/typebox": "^0.30.4",
"fs-extra": "^8.1.0"
},
"devDependencies": {
"@clusterio/lib": "^2.0.0-alpha.13",
"@clusterio/web_ui": "^2.0.0-alpha.13",
"@types/node": "^20.4.5",
"@types/fs-extra": "^11.0.1",
"typescript": "^5.1.6",
"webpack": "^5.88.2",
"webpack-cli": "^5.1.4",
"webpack-merge": "^5.9.0"
+2 -2
View File
@@ -2,5 +2,5 @@
// required here in order to track coverage for them.
"use strict";
require("../instance");
require("../controller");
require("../dist/plugin/instance");
require("../dist/plugin/controller");
+16
View File
@@ -0,0 +1,16 @@
{
"include": ["./**/*.ts"],
"exclude": ["test/*", "./dist/*"],
"compilerOptions": {
"lib": ["es2023"],
"module": "commonjs",
"target": "es2022",
"rootDir": ".",
"outDir": "dist/plugin",
"sourceMap": true,
"strict": true,
"alwaysStrict": true,
"esModuleInterop": true,
"skipLibCheck": true
}
}
+1 -1
View File
@@ -16,7 +16,7 @@ module.exports = (env = {}) => merge(common(env), {
name: "research_sync",
library: { type: "var", name: "plugin_research_sync" },
exposes: {
"./info": "./info.js",
"./info": "./dist/plugin/info.js",
"./package.json": "./package.json",
},
shared: {