mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-19 23:33:13 +09:00
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:
1 parent
50f12c719b
commit
0b3550b472
51 files changed
+1033
-1026
No files matched your search
@@ -1,21 +1,22 @@
|
||||
"use strict";
|
||||
const fs = require("fs-extra");
|
||||
const path = require("path");
|
||||
import type ControlConnection from "@clusterio/controller/src/ControlConnection";
|
||||
|
||||
const lib = require("@clusterio/lib");
|
||||
const { Counter, Gauge, RateLimiter } = lib;
|
||||
import fs from "fs-extra";
|
||||
import path from "path";
|
||||
|
||||
const routes = require("./routes");
|
||||
const dole = require("./dole");
|
||||
import * as lib from "@clusterio/lib";
|
||||
const { Counter, Gauge } = lib;
|
||||
|
||||
const {
|
||||
import * as routes from "./routes";
|
||||
import * as dole from "./dole";
|
||||
|
||||
import {
|
||||
Item,
|
||||
PlaceEvent,
|
||||
RemoveRequest,
|
||||
GetStorageRequest,
|
||||
UpdateStorageEvent,
|
||||
SetStorageSubscriptionRequest,
|
||||
} = require("./messages");
|
||||
} from "./messages";
|
||||
|
||||
|
||||
const exportCounter = new Counter(
|
||||
@@ -35,14 +36,17 @@ const controllerInventoryGauge = new Gauge(
|
||||
);
|
||||
|
||||
|
||||
async function loadDatabase(config, logger) {
|
||||
async function loadDatabase(
|
||||
config: lib.ControllerConfig,
|
||||
logger: lib.Logger
|
||||
): Promise<lib.ItemDatabase> {
|
||||
let itemsPath = path.resolve(config.get("controller.database_directory"), "items.json");
|
||||
logger.verbose(`Loading ${itemsPath}`);
|
||||
try {
|
||||
let content = await fs.readFile(itemsPath);
|
||||
let content = await fs.readFile(itemsPath, { encoding: "utf8" });
|
||||
return new lib.ItemDatabase(JSON.parse(content));
|
||||
|
||||
} catch (err) {
|
||||
} catch (err: any) {
|
||||
if (err.code === "ENOENT") {
|
||||
logger.verbose("Creating new item database");
|
||||
return new lib.ItemDatabase();
|
||||
@@ -51,7 +55,11 @@ async function loadDatabase(config, logger) {
|
||||
}
|
||||
}
|
||||
|
||||
async function saveDatabase(controllerConfig, items, logger) {
|
||||
async function saveDatabase(
|
||||
controllerConfig: lib.ControllerConfig,
|
||||
items: lib.ItemDatabase,
|
||||
logger: lib.Logger,
|
||||
) {
|
||||
if (items && items.size < 50000) {
|
||||
let file = path.resolve(controllerConfig.get("controller.database_directory"), "items.json");
|
||||
logger.verbose(`writing ${file}`);
|
||||
@@ -62,21 +70,28 @@ async function saveDatabase(controllerConfig, items, logger) {
|
||||
}
|
||||
}
|
||||
|
||||
class ControllerPlugin extends lib.BaseControllerPlugin {
|
||||
async init() {
|
||||
export class ControllerPlugin extends lib.BaseControllerPlugin {
|
||||
items!: lib.ItemDatabase;
|
||||
itemUpdateRateLimiter!: lib.RateLimiter;
|
||||
itemsLastUpdate!: Map<string, number>;
|
||||
subscribedControlLinks!: Set<ControlConnection>;
|
||||
autosaveId!: ReturnType<typeof setInterval>;
|
||||
doleMagicId!: ReturnType<typeof setInterval>;
|
||||
neuralDole!: dole.NeuralDole;
|
||||
|
||||
async init() {
|
||||
this.items = await loadDatabase(this.controller.config, this.logger);
|
||||
this.itemUpdateRateLimiter = new RateLimiter({
|
||||
this.itemUpdateRateLimiter = new lib.RateLimiter({
|
||||
maxRate: 1,
|
||||
action: () => {
|
||||
try {
|
||||
this.broadcastStorage();
|
||||
} catch (err) {
|
||||
} catch (err: any) {
|
||||
this.logger.error(`Unexpected error sending storage update:\n${err.stack}`);
|
||||
}
|
||||
},
|
||||
});
|
||||
this.itemsLastUpdate = new Map(this.items._items.entries());
|
||||
this.itemsLastUpdate = new Map(this.items.getEntries());
|
||||
this.autosaveId = setInterval(() => {
|
||||
saveDatabase(this.controller.config, this.items, this.logger).catch(err => {
|
||||
this.logger.error(`Unexpected error autosaving items:\n${err.stack}`);
|
||||
@@ -105,32 +120,32 @@ class ControllerPlugin extends lib.BaseControllerPlugin {
|
||||
}
|
||||
|
||||
broadcastStorage() {
|
||||
let itemsToUpdate = new Map();
|
||||
for (let [name, count] of this.items._items) {
|
||||
let itemsToUpdateMap:Map<string, number> = new Map();
|
||||
for (let [name, count] of this.items.getEntries()) {
|
||||
if (this.itemsLastUpdate.get(name) === count) {
|
||||
continue;
|
||||
}
|
||||
itemsToUpdate.set(name, count);
|
||||
itemsToUpdateMap.set(name, count);
|
||||
}
|
||||
|
||||
if (!itemsToUpdate.size) {
|
||||
if (!itemsToUpdateMap.size) {
|
||||
return;
|
||||
}
|
||||
|
||||
itemsToUpdate = [...itemsToUpdate.entries()];
|
||||
let update = new UpdateStorageEvent(itemsToUpdate);
|
||||
let itemsToUpdate = [...itemsToUpdateMap.entries()];
|
||||
let update = UpdateStorageEvent.fromJSON({ items: itemsToUpdate });
|
||||
this.controller.sendTo("allInstances", update);
|
||||
for (let link of this.subscribedControlLinks) {
|
||||
link.send(update);
|
||||
}
|
||||
this.itemsLastUpdate = new Map(this.items._items.entries());
|
||||
this.itemsLastUpdate = new Map(this.items.getEntries());
|
||||
}
|
||||
|
||||
async handleGetStorageRequest() {
|
||||
return [...this.items._items.entries()];
|
||||
return [...this.items.getEntries()];
|
||||
}
|
||||
|
||||
async handlePlaceEvent(request, src) {
|
||||
async handlePlaceEvent(request: PlaceEvent, src: lib.Address) {
|
||||
let instanceId = src.id;
|
||||
|
||||
for (let item of request.items) {
|
||||
@@ -147,7 +162,7 @@ class ControllerPlugin extends lib.BaseControllerPlugin {
|
||||
}
|
||||
}
|
||||
|
||||
async handleRemoveRequest(request, src) {
|
||||
async handleRemoveRequest(request: RemoveRequest, src: lib.Address) {
|
||||
let method = this.controller.config.get("subspace_storage.division_method");
|
||||
let instanceId = src.id;
|
||||
|
||||
@@ -171,7 +186,7 @@ class ControllerPlugin extends lib.BaseControllerPlugin {
|
||||
// use fancy neural net to calculate a "fair" dole division rate.
|
||||
if (method === "neural_dole") {
|
||||
for (let item of request.items) {
|
||||
let count = neuralDole.divider({ name: item.name, count: item.count, instanceId, instanceName });
|
||||
let count = this.neuralDole.divider({ name: item.name, count: item.count, instanceId, instanceName });
|
||||
if (count > 0) {
|
||||
itemsRemoved.push(new Item(item.name, count));
|
||||
}
|
||||
@@ -212,7 +227,7 @@ class ControllerPlugin extends lib.BaseControllerPlugin {
|
||||
return itemsRemoved;
|
||||
}
|
||||
|
||||
async handleSetStorageSubscriptionRequest(request, src) {
|
||||
async handleSetStorageSubscriptionRequest(request: SetStorageSubscriptionRequest, src: lib.Address) {
|
||||
let link = this.controller.wsServer.controlConnections.get(src.id);
|
||||
if (request.storage) {
|
||||
this.subscribedControlLinks.add(link);
|
||||
@@ -221,15 +236,15 @@ class ControllerPlugin extends lib.BaseControllerPlugin {
|
||||
}
|
||||
}
|
||||
|
||||
onControlConnectionEvent(connection, event) {
|
||||
onControlConnectionEvent(connection: ControlConnection, event: string) {
|
||||
if (event === "close") {
|
||||
this.subscribedControlLinks.delete(connection);
|
||||
}
|
||||
}
|
||||
|
||||
onMetrics() {
|
||||
async onMetrics() {
|
||||
if (this.items) {
|
||||
for (let [key, count] of this.items._items) {
|
||||
for (let [key, count] of this.items.getEntries()) {
|
||||
controllerInventoryGauge.labels(key).set(Number(count) || 0);
|
||||
}
|
||||
}
|
||||
@@ -242,7 +257,3 @@ class ControllerPlugin extends lib.BaseControllerPlugin {
|
||||
await saveDatabase(this.controller.config, this.items, this.logger);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
ControllerPlugin,
|
||||
};
|
||||
@@ -1,7 +1,6 @@
|
||||
"use strict";
|
||||
const doleNN = require("./dole_nn_base");
|
||||
import * as doleNN from "./dole_nn_base";
|
||||
|
||||
const lib = require("@clusterio/lib");
|
||||
import * as lib from "@clusterio/lib";
|
||||
const { Gauge } = lib;
|
||||
|
||||
|
||||
@@ -17,8 +16,8 @@ const prometheusDoleFactorGauge = new Gauge(
|
||||
{ labels: ["resource"] }
|
||||
);
|
||||
|
||||
class NeuralDole {
|
||||
getRequestStats(itemname, samples) {
|
||||
export class NeuralDole {
|
||||
getRequestStats(itemname: string, samples: number): number {
|
||||
let sum = 0;
|
||||
samples = Math.min(samples, (this.stats[itemname] || []).length - 1);
|
||||
if (samples < 1) {
|
||||
@@ -33,25 +32,25 @@ class NeuralDole {
|
||||
return sum / samples;
|
||||
}
|
||||
|
||||
constructor({
|
||||
items,
|
||||
}) {
|
||||
items: lib.ItemDatabase;
|
||||
itemsLastTick: Map<string, number>;
|
||||
dole: any = {};
|
||||
carry: any = {};
|
||||
lastRequest: any = {};
|
||||
stats: any = {};
|
||||
debt: any = {};
|
||||
constructor({ items }: { items: lib.ItemDatabase }) {
|
||||
// Set some storage variables for the dole divider
|
||||
this.items = items;
|
||||
this.itemsLastTick = new Map(items._items);
|
||||
this.dole = {};
|
||||
this.carry = {};
|
||||
this.lastRequest = {};
|
||||
this.stats=[];
|
||||
this.debt= {};
|
||||
this.itemsLastTick = new Map(items.getEntries());
|
||||
}
|
||||
|
||||
doMagic() {
|
||||
for (let [name, count] of this.items._items) {
|
||||
for (let [name, count] of this.items.getEntries()) {
|
||||
let magicData = doleNN.tick(
|
||||
count,
|
||||
this.dole[name],
|
||||
this.itemsLastTick.get(name),
|
||||
this.itemsLastTick.get(name) || 0,
|
||||
this.getRequestStats(name, 5)
|
||||
);
|
||||
this.stats[name] = this.stats[name] || [];
|
||||
@@ -64,31 +63,31 @@ class NeuralDole {
|
||||
// DONE handle magicData[1] for graphing for our users
|
||||
prometheusNNDoleGauge.labels(name).set(magicData[1] || 0);
|
||||
}
|
||||
this.itemsLastTick = new Map(this.items._items);
|
||||
this.itemsLastTick = new Map(this.items.getEntries());
|
||||
}
|
||||
|
||||
divider(object) {
|
||||
divider(object: { name:string, count:number, instanceId:number, instanceName:string }): number {
|
||||
let magicData = doleNN.dose(
|
||||
object.count, // numReq
|
||||
this.items.getItemCount(object.name),
|
||||
this.items.getItemCount(object.name) || 0,
|
||||
this.itemsLastTick.get(object.name) || 0,
|
||||
this.dole[object.name],
|
||||
this.carry[`${object.name} ${object.instanceID}`] || 0,
|
||||
this.lastRequest[`${object.name}_${object.instanceID}_${object.instanceName}`] || 0,
|
||||
this.carry[`${object.name} ${object.instanceId}`] || 0,
|
||||
this.lastRequest[`${object.name}_${object.instanceId}_${object.instanceName}`] || 0,
|
||||
this.getRequestStats(object.name, 5),
|
||||
this.debt[`${object.name} ${object.instanceID}`] || 0
|
||||
this.debt[`${object.name} ${object.instanceId}`] || 0
|
||||
);
|
||||
if ((this.stats[object.name] || []).length > 0) {
|
||||
this.stats[object.name][0].req += Number(object.count);
|
||||
this.stats[object.name][0].given += Number(magicData[0]);
|
||||
}
|
||||
this.lastRequest[`${object.name}_${object.instanceID}_${object.instanceName}`] = object.count;
|
||||
this.lastRequest[`${object.name}_${object.instanceId}_${object.instanceName}`] = object.count;
|
||||
// 0. Number of items to give in that dose
|
||||
// 1. New dole for item X
|
||||
// 2. New carry for item X instance Y
|
||||
this.dole[object.name] = magicData[1];
|
||||
this.carry[`${object.name} ${object.instanceID}`] = magicData[2];
|
||||
this.debt[`${object.name} ${object.instanceID}`] = magicData[3];
|
||||
this.carry[`${object.name} ${object.instanceId}`] = magicData[2];
|
||||
this.debt[`${object.name} ${object.instanceId}`] = magicData[3];
|
||||
|
||||
// Remove item from DB and send it
|
||||
this.items.removeItem(object.name, magicData[0]);
|
||||
@@ -99,13 +98,19 @@ class NeuralDole {
|
||||
|
||||
// If the server regularly can't fulfill requests, this number grows until
|
||||
// it can. Then it slowly shrinks back down.
|
||||
let _doleDivisionFactor = {};
|
||||
function doleDivider({
|
||||
object,
|
||||
items,
|
||||
logItemTransfers,
|
||||
logger,
|
||||
}) {
|
||||
let _doleDivisionFactor: { [key:string]: number } = {};
|
||||
export function doleDivider({
|
||||
object,
|
||||
items,
|
||||
logItemTransfers,
|
||||
logger,
|
||||
} :{
|
||||
object: { name:string, count:number, instanceId:number, instanceName:string },
|
||||
items: lib.ItemDatabase,
|
||||
logItemTransfers: boolean,
|
||||
logger: lib.Logger,
|
||||
},
|
||||
) {
|
||||
let itemCount = items.getItemCount(object.name);
|
||||
// lower rates will equal more dramatic swings
|
||||
const doleDivisionRetardation = 10;
|
||||
@@ -143,8 +148,3 @@ function doleDivider({
|
||||
return 0;
|
||||
// console.log(`failure out of ${object.name}/${object.count} from ${object.instanceID} (${object.instanceName})`);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
doleDivider,
|
||||
NeuralDole,
|
||||
};
|
||||
+21
-10
@@ -1,25 +1,24 @@
|
||||
// Sigmoids...
|
||||
|
||||
"use strict";
|
||||
function sigmoid0(x) {
|
||||
function sigmoid0(x: number): number {
|
||||
return x / (1 + Math.abs(x));
|
||||
}
|
||||
|
||||
function sigmoid1(x) {
|
||||
function sigmoid1(x: number): number {
|
||||
if (x >= 0.0) {
|
||||
return 1.0;
|
||||
}
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
function sigmoid2(x) {
|
||||
function sigmoid2(x: number): number {
|
||||
if (x >= 0.0) {
|
||||
return x;
|
||||
}
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
function sigmoid3(x) {
|
||||
function sigmoid3(x: number) {
|
||||
return x;
|
||||
}
|
||||
|
||||
@@ -36,12 +35,21 @@ function sigmoid3(x) {
|
||||
// requests for item, numinstance - number of instances requesting that item
|
||||
// debt - debt for item X instance Y
|
||||
|
||||
// Returns: Array of 3 elements
|
||||
// Returns: Array of 4 elements
|
||||
// 0.Number of items to give in that dose
|
||||
// 1.New dole for item X
|
||||
// 2.New carry for item X instance Y
|
||||
// 3.New debt
|
||||
function dose(numreq, instore, store_last_tick, dole, carry, prev_req, numreq_total_adj, debt) {
|
||||
export function dose(
|
||||
numreq: number,
|
||||
instore: number,
|
||||
store_last_tick: number,
|
||||
dole: number,
|
||||
carry: number,
|
||||
prev_req: number,
|
||||
numreq_total_adj: number,
|
||||
debt: number,
|
||||
): [number, number, number, number] {
|
||||
numreq = Number(numreq);
|
||||
instore = Number(instore);
|
||||
let instore_adj = instore;
|
||||
@@ -115,7 +123,12 @@ function dose(numreq, instore, store_last_tick, dole, carry, prev_req, numreq_to
|
||||
// Returns: Array of 2 elements
|
||||
// 0.New dole for item X
|
||||
// 1.Guessed percentage average of items supplied in last 10 ticks
|
||||
function tick(instore, dole, store_last_tick, numreq_total_adj) {
|
||||
export function tick(
|
||||
instore: number,
|
||||
dole: number,
|
||||
store_last_tick: number,
|
||||
numreq_total_adj: number,
|
||||
): [number, number] {
|
||||
let instore_adj = instore;
|
||||
if (instore_adj === 0) {
|
||||
instore_adj = 0.1;
|
||||
@@ -148,5 +161,3 @@ function tick(instore, dole, store_last_tick, numreq_total_adj) {
|
||||
|
||||
return [sigmoid0(outputs[0]), avg];
|
||||
}
|
||||
|
||||
module.exports = { dose, tick };
|
||||
@@ -1,6 +1,5 @@
|
||||
"use strict";
|
||||
const lib = require("@clusterio/lib");
|
||||
const messages = require("./messages");
|
||||
import * as lib from "@clusterio/lib";
|
||||
import * as messages from "./messages";
|
||||
|
||||
class ControllerConfigGroup extends lib.PluginConfigGroup {}
|
||||
ControllerConfigGroup.defaultAccess = ["controller", "host", "control"];
|
||||
@@ -52,10 +51,10 @@ module.exports.default = {
|
||||
name: "subspace_storage",
|
||||
title: "Subspace Storage",
|
||||
description: "Provides shared storage across instances for the Subspace Storage mod",
|
||||
instanceEntrypoint: "instance",
|
||||
instanceEntrypoint: "dist/plugin/instance",
|
||||
InstanceConfigGroup,
|
||||
|
||||
controllerEntrypoint: "controller",
|
||||
controllerEntrypoint: "dist/plugin/controller",
|
||||
ControllerConfigGroup,
|
||||
|
||||
messages: [
|
||||
@@ -1,24 +1,29 @@
|
||||
"use strict";
|
||||
const lib = require("@clusterio/lib");
|
||||
import * as lib from "@clusterio/lib";
|
||||
|
||||
const {
|
||||
import {
|
||||
PlaceEvent,
|
||||
RemoveRequest,
|
||||
GetStorageRequest,
|
||||
UpdateStorageEvent,
|
||||
} = require("./messages");
|
||||
Item,
|
||||
} from "./messages";
|
||||
|
||||
class InstancePlugin extends lib.BaseInstancePlugin {
|
||||
unexpectedError(err) {
|
||||
type IpcItems = { name: string, count: number }[];
|
||||
|
||||
export class InstancePlugin extends lib.BaseInstancePlugin {
|
||||
pendingTasks!: Set<any>;
|
||||
pingId?: ReturnType<typeof setTimeout>;
|
||||
|
||||
unexpectedError(err: Error) {
|
||||
this.logger.error(`Unexpected error:\n${err.stack}`);
|
||||
}
|
||||
|
||||
async init() {
|
||||
this.pendingTasks = new Set();
|
||||
this.instance.server.on("ipc-subspace_storage:output", (output) => {
|
||||
this.instance.server.on("ipc-subspace_storage:output", (output: IpcItems) => {
|
||||
this.provideItems(output).catch(err => this.unexpectedError(err));
|
||||
});
|
||||
this.instance.server.on("ipc-subspace_storage:orders", (orders) => {
|
||||
this.instance.server.on("ipc-subspace_storage:orders", (orders: IpcItems) => {
|
||||
if (this.instance.status !== "running" || !this.host.connected) {
|
||||
return;
|
||||
}
|
||||
@@ -57,7 +62,7 @@ class InstancePlugin extends lib.BaseInstancePlugin {
|
||||
}
|
||||
|
||||
// provide items --------------------------------------------------------------
|
||||
async provideItems(items) {
|
||||
async provideItems(items: IpcItems) {
|
||||
if (!this.host.connector.hasSession) {
|
||||
// For now the items are voided if the controller connection is
|
||||
// down, which is no different from the previous behaviour.
|
||||
@@ -68,7 +73,8 @@ class InstancePlugin extends lib.BaseInstancePlugin {
|
||||
return;
|
||||
}
|
||||
|
||||
this.instance.sendTo("controller", new PlaceEvent(items));
|
||||
const fromIpcItems = items.map(item => new Item(item.name, item.count))
|
||||
this.instance.sendTo("controller", new PlaceEvent(fromIpcItems));
|
||||
|
||||
if (this.instance.config.get("subspace_storage.log_item_transfers")) {
|
||||
this.logger.verbose("Exported the following to controller:");
|
||||
@@ -77,9 +83,10 @@ class InstancePlugin extends lib.BaseInstancePlugin {
|
||||
}
|
||||
|
||||
// request items --------------------------------------------------------------
|
||||
async requestItems(requestItems) {
|
||||
async requestItems(requestItems: IpcItems) {
|
||||
// Request the items all at once
|
||||
let items = await this.instance.sendTo("controller", new RemoveRequest(requestItems));
|
||||
let fromIpcItems = requestItems.map(item => new Item(item.name, item.count))
|
||||
let items = await this.instance.sendTo("controller", new RemoveRequest(fromIpcItems));
|
||||
|
||||
if (!items.length) {
|
||||
return;
|
||||
@@ -95,14 +102,14 @@ class InstancePlugin extends lib.BaseInstancePlugin {
|
||||
}
|
||||
|
||||
// combinator signals ---------------------------------------------------------
|
||||
async handleUpdateStorageEvent(request) {
|
||||
async handleUpdateStorageEvent(event: UpdateStorageEvent) {
|
||||
if (this.instance.status !== "running") {
|
||||
return;
|
||||
}
|
||||
let items = request.items;
|
||||
let items = event.items;
|
||||
|
||||
// XXX this should be moved to instance/clusterio api
|
||||
items.push(["signal-unixtime", Math.floor(Date.now()/1000)]);
|
||||
items.push(new Item("signal-unixtime", Math.floor(Date.now()/1000)));
|
||||
|
||||
let itemsJson = lib.escapeString(JSON.stringify(items));
|
||||
let task = this.sendRcon(`/sc __subspace_storage__ UpdateInvData("${itemsJson}")`, true);
|
||||
@@ -111,7 +118,3 @@ class InstancePlugin extends lib.BaseInstancePlugin {
|
||||
await task;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
InstancePlugin,
|
||||
};
|
||||
@@ -1,167 +0,0 @@
|
||||
"use strict";
|
||||
const lib = require("@clusterio/lib");
|
||||
|
||||
class Item {
|
||||
/** @type {string} */
|
||||
name;
|
||||
/** @type {number} */
|
||||
count;
|
||||
|
||||
constructor(name, count) {
|
||||
this.name = name;
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
static jsonSchema = {
|
||||
type: "array",
|
||||
minItems: 2,
|
||||
maxItems: 2,
|
||||
items: [
|
||||
{ type: "string" },
|
||||
{ type: "integer" },
|
||||
],
|
||||
};
|
||||
|
||||
toJSON() {
|
||||
return [this.name, this.count];
|
||||
}
|
||||
|
||||
static fromJSON(json) {
|
||||
return new this(json[0], json[1]);
|
||||
}
|
||||
}
|
||||
|
||||
// XXX this should be a request to be reliable
|
||||
class PlaceEvent {
|
||||
static type = "event";
|
||||
static src = "instance";
|
||||
static dst = "controller";
|
||||
static plugin = "subspace_storage";
|
||||
|
||||
/** @type {Array<Item>} */
|
||||
items;
|
||||
|
||||
constructor(items) {
|
||||
this.items = items;
|
||||
}
|
||||
|
||||
static jsonSchema = {
|
||||
type: "object",
|
||||
required: ["items"],
|
||||
properties: {
|
||||
"items": {
|
||||
type: "array",
|
||||
items: Item.jsonSchema,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
static fromJSON(json) {
|
||||
return new this(json.items);
|
||||
}
|
||||
}
|
||||
|
||||
class RemoveRequest {
|
||||
static type = "request";
|
||||
static src = "instance";
|
||||
static dst = "controller";
|
||||
static plugin = "subspace_storage";
|
||||
|
||||
/** @type {Array<Item>} */
|
||||
items;
|
||||
|
||||
constructor(items) {
|
||||
this.items = items;
|
||||
}
|
||||
|
||||
static jsonSchema = {
|
||||
type: "object",
|
||||
required: ["items"],
|
||||
properties: {
|
||||
"items": {
|
||||
type: "array",
|
||||
items: Item.jsonSchema,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
static fromJSON(json) {
|
||||
return new this(json.items);
|
||||
}
|
||||
|
||||
static Response = lib.jsonArray(Item);
|
||||
}
|
||||
|
||||
class GetStorageRequest {
|
||||
static type = "request";
|
||||
static src = ["instance", "control"];
|
||||
static dst = "controller";
|
||||
static plugin = "subspace_storage";
|
||||
static permission = "subspace_storage.storage.view";
|
||||
static Response = lib.jsonArray(Item);
|
||||
}
|
||||
|
||||
class UpdateStorageEvent {
|
||||
static type = "request";
|
||||
static src = "controller";
|
||||
static dst = ["instance", "control"];
|
||||
static plugin = "subspace_storage";
|
||||
|
||||
/** @type {Array<Item>} */
|
||||
items;
|
||||
|
||||
constructor(items) {
|
||||
this.items = items;
|
||||
}
|
||||
|
||||
static jsonSchema = {
|
||||
type: "object",
|
||||
required: ["items"],
|
||||
properties: {
|
||||
"items": {
|
||||
type: "array",
|
||||
items: Item.jsonSchema,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
static fromJSON(json) {
|
||||
return new this(json.items);
|
||||
}
|
||||
}
|
||||
|
||||
class SetStorageSubscriptionRequest {
|
||||
static type = "request";
|
||||
static src = "control";
|
||||
static dst = "controller";
|
||||
static plugin = "subspace_storage";
|
||||
static permission = "subspace_storage.storage.view";
|
||||
|
||||
/** @type {boolean} */
|
||||
storage;
|
||||
|
||||
constructor(storage) {
|
||||
this.storage = storage;
|
||||
}
|
||||
|
||||
static jsonSchema = {
|
||||
type: "object",
|
||||
required: ["storage"],
|
||||
properties: {
|
||||
"storage": { type: "boolean" },
|
||||
},
|
||||
};
|
||||
|
||||
static fromJSON(json) {
|
||||
return new this(json.storage);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
Item,
|
||||
PlaceEvent,
|
||||
RemoveRequest,
|
||||
GetStorageRequest,
|
||||
UpdateStorageEvent,
|
||||
SetStorageSubscriptionRequest,
|
||||
};
|
||||
@@ -0,0 +1,122 @@
|
||||
import { Type, Static } from "@sinclair/typebox";
|
||||
import * as lib from "@clusterio/lib";
|
||||
import { type } from "os";
|
||||
|
||||
export class Item {
|
||||
constructor(
|
||||
public name: string,
|
||||
public count: number
|
||||
) {
|
||||
}
|
||||
|
||||
static jsonSchema = Type.Tuple([
|
||||
Type.String(),
|
||||
Type.Number(),
|
||||
]);
|
||||
|
||||
toJSON() {
|
||||
return [this.name, this.count];
|
||||
}
|
||||
|
||||
static fromJSON(json: Static<typeof Item.jsonSchema>): Item {
|
||||
return new this(json[0], json[1]);
|
||||
}
|
||||
}
|
||||
|
||||
// XXX this should be a request to be reliable
|
||||
export class PlaceEvent {
|
||||
declare ["constructor"]: typeof PlaceEvent;
|
||||
static type = "event" as const;
|
||||
static src = "instance" as const;
|
||||
static dst = "controller" as const;
|
||||
static plugin = "subspace_storage" as const;
|
||||
|
||||
constructor(
|
||||
public items: Item[]
|
||||
) {
|
||||
}
|
||||
|
||||
static jsonSchema = Type.Object({
|
||||
"items": Type.Array(Item.jsonSchema)
|
||||
})
|
||||
|
||||
static fromJSON(json: Static<typeof PlaceEvent.jsonSchema>): PlaceEvent {
|
||||
return new this(json.items.map(item => Item.fromJSON(item)));
|
||||
}
|
||||
}
|
||||
|
||||
export class RemoveRequest {
|
||||
declare ["constructor"]: typeof RemoveRequest;
|
||||
static type = "request" as const;
|
||||
static src = "instance" as const;
|
||||
static dst = "controller" as const;
|
||||
static plugin = "subspace_storage" as const;
|
||||
|
||||
constructor(
|
||||
public items: Item[]
|
||||
) {
|
||||
}
|
||||
|
||||
static jsonSchema = Type.Object({
|
||||
"items": Type.Array(Item.jsonSchema)
|
||||
})
|
||||
|
||||
static fromJSON(json: Static<typeof RemoveRequest.jsonSchema>): RemoveRequest {
|
||||
return new this(json.items.map(item => Item.fromJSON(item)));
|
||||
}
|
||||
|
||||
static Response = lib.jsonArray(Item);
|
||||
}
|
||||
|
||||
export class GetStorageRequest {
|
||||
declare ["constructor"]: typeof GetStorageRequest;
|
||||
static type = "request" as const;
|
||||
static src = ["instance", "control"] as const;
|
||||
static dst = "controller" as const;
|
||||
static plugin = "subspace_storage" as const;
|
||||
static permission = "subspace_storage.storage.view" as const;
|
||||
static Response = lib.jsonArray(Item);
|
||||
}
|
||||
|
||||
export class UpdateStorageEvent {
|
||||
declare ["constructor"]: typeof UpdateStorageEvent;
|
||||
static type = "request" as const;
|
||||
static src = "controller" as const;
|
||||
static dst = ["instance", "control"] as const;
|
||||
static plugin = "subspace_storage" as const;
|
||||
|
||||
constructor(
|
||||
public items: Item[]
|
||||
) {
|
||||
}
|
||||
|
||||
static jsonSchema = Type.Object({
|
||||
"items": Type.Array(Item.jsonSchema)
|
||||
})
|
||||
|
||||
static fromJSON(json: Static<typeof UpdateStorageEvent.jsonSchema>): UpdateStorageEvent {
|
||||
return new this(json.items.map(item => Item.fromJSON(item)));
|
||||
}
|
||||
}
|
||||
|
||||
export class SetStorageSubscriptionRequest {
|
||||
declare ["constructor"]: typeof SetStorageSubscriptionRequest;
|
||||
static type = "request" as const;
|
||||
static src = "control" as const;
|
||||
static dst = "controller" as const;
|
||||
static plugin = "subspace_storage" as const;
|
||||
static permission = "subspace_storage.storage.view" as const;
|
||||
|
||||
constructor(
|
||||
public storage: boolean
|
||||
) {
|
||||
}
|
||||
|
||||
static jsonSchema = Type.Object({
|
||||
"storage": Type.Boolean()
|
||||
})
|
||||
|
||||
static fromJSON(json: Static<typeof SetStorageSubscriptionRequest.jsonSchema>): SetStorageSubscriptionRequest {
|
||||
return new this(json.storage);
|
||||
}
|
||||
}
|
||||
@@ -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/express": "^4.17.17",
|
||||
"@types/fs-extra": "^11.0.1",
|
||||
"@types/node": "^20.4.5",
|
||||
"antd": "^5.7.3",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
"use strict";
|
||||
function addApiRoutes(app, items) {
|
||||
import type { Application, Request, Response } from "express";
|
||||
import * as lib from "@clusterio/lib";
|
||||
|
||||
export function addApiRoutes(app: Application, items: lib.ItemDatabase) {
|
||||
|
||||
/**
|
||||
* GET endpoint to read the controllers current inventory of items.
|
||||
@@ -9,12 +11,12 @@ function addApiRoutes(app, items) {
|
||||
* @alias api/inventory
|
||||
* @returns {object[]} JSON [{name:"iron-plate", count:100},{name:"copper-plate",count:5}]
|
||||
*/
|
||||
app.get("/api/inventory", (req, res) => {
|
||||
app.get("/api/inventory", (req: Request, res: Response) => {
|
||||
res.header("Access-Control-Allow-Origin", "*");
|
||||
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
|
||||
// Check it and send it
|
||||
let inventory = [];
|
||||
for (let [name, count] of items._items) {
|
||||
for (let [name, count] of items.getEntries()) {
|
||||
inventory.push({ name, count });
|
||||
}
|
||||
res.type("json");
|
||||
@@ -29,15 +31,11 @@ function addApiRoutes(app, items) {
|
||||
* @alias api/inventoryAsObject
|
||||
* @returns {object} JSON {"iron-plate":100, "copper-plate":5}
|
||||
*/
|
||||
app.get("/api/inventoryAsObject", (req, res) => {
|
||||
app.get("/api/inventoryAsObject", (req: Request, res: Response) => {
|
||||
res.header("Access-Control-Allow-Origin", "*");
|
||||
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
|
||||
// Check it and send it
|
||||
res.type("json");
|
||||
res.send(JSON.stringify(items.serialise()));
|
||||
res.send(JSON.stringify(items.serialize()));
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
addApiRoutes,
|
||||
};
|
||||
@@ -2,7 +2,7 @@
|
||||
// required here in order to track coverage for them.
|
||||
|
||||
"use strict";
|
||||
require("../instance");
|
||||
require("../controller");
|
||||
require("../dole");
|
||||
require("../dole_nn_base");
|
||||
require("../dist/plugin/instance");
|
||||
require("../dist/plugin/controller");
|
||||
require("../dist/plugin/dole");
|
||||
require("../dist/plugin/dole_nn_base");
|
||||
@@ -1,7 +1,7 @@
|
||||
"use strict";
|
||||
const assert = require("assert").strict;
|
||||
|
||||
const routes = require("../routes");
|
||||
const routes = require("../dist/plugin/routes");
|
||||
const { get } = require("../../../test/integration");
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import { Input, Table, Typography } from "antd";
|
||||
|
||||
import * as lib from "@clusterio/lib";
|
||||
import { notifyErrorHandler, useItemMetadata, useLocale, PageLayout, ControlContext } from "@clusterio/web_ui";
|
||||
import { GetStorageRequest, SetStorageSubscriptionRequest } from "../messages";
|
||||
import { GetStorageRequest, SetStorageSubscriptionRequest } from "../dist/plugin/messages";
|
||||
|
||||
import "./index.css";
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ module.exports = (env = {}) => merge(common(env), {
|
||||
name: "subspace_storage",
|
||||
library: { type: "var", name: "plugin_subspace_storage" },
|
||||
exposes: {
|
||||
"./info": "./info.js",
|
||||
"./info": "./dist/plugin/info.js",
|
||||
"./package.json": "./package.json",
|
||||
"./web": "./web/index.jsx",
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user