This commit is contained in:
Boris D
2025-09-22 18:35:02 +03:00
parent 51f8b0d773
commit fbbbd61838
23 changed files with 282 additions and 67 deletions

View File

@ -1,4 +1,12 @@
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async function asyncCall(reference, args) {
return await reference.apply(undefined, args, { result: { promise: true } });
if (!Array.isArray(args)) {
args = [args];
}
const resJson = await reference.apply(undefined, args, {
result: { promise: true },
});
return JSON.parse(resJson);
}

View File

@ -12,31 +12,39 @@ export class DatabasePlugin extends Plugin {
super(name);
}
static init(
static async init(
name: string,
config: {
host: string;
port: number;
user: string;
password: string;
database: string;
}
): DatabasePlugin {
const dbConnection = mysql.createConnection({
): Promise<DatabasePlugin> {
const dbConnection = await mysql.createConnection({
host: config.host,
user: config.user,
port: config.port,
password: config.password,
database: config.database,
enableKeepAlive: true,
});
return new DatabasePlugin(name, dbConnection);
}
async run(query): Promise<{
rows: any[];
fields: any[];
}> {
const [rows, fields] = await this.dbConnection.execute(query);
return { rows, fields };
async run(query): Promise<any> {
try {
const [rows, fields] = await this.dbConnection.execute(query);
return JSON.stringify({
rows: rows,
fields: fields ?? [],
});
} catch (error) {
console.log("error", error);
}
}
onFinish() {

View File

@ -28,13 +28,17 @@ export class Vm {
this.jail.set("global", this.jail.derefInto());
for (const mod of this.modules) {
this.jail.setSync(mod.getName(), mod.getSource());
await this.context.eval(mod.getSource());
}
for (const plugin of this.plugins) {
this.jail.setSync(
plugin.getName(),
new ivm.Reference(plugin.run.bind(plugin))
new ivm.Reference(async (...args) => {
const res = await plugin.run(...args);
return res;
})
);
}
@ -61,6 +65,9 @@ export class Vm {
});
// TODO: log
this.setFunction("log", (...args) => {
console.log("vm log:", args);
});
this.setFunction("error", (error: any) => {
console.error("Script error:", error);
@ -82,9 +89,12 @@ export class Vm {
const compiledScript = await this.isolate.compileScript(scriptWithResult);
compiledScript.run(this.context);
this.onFinish();
return await resultPromise;
try {
return await resultPromise;
} finally {
this.onFinish();
}
}
onFinish() {