98 lines
2.5 KiB
JavaScript
98 lines
2.5 KiB
JavaScript
import EventEmitter from "eventemitter3";
|
|
let callModule;
|
|
let connectModule;
|
|
let log;
|
|
let logErr;
|
|
export class Client extends EventEmitter {
|
|
_callModule;
|
|
get callModule() {
|
|
return this._callModule;
|
|
}
|
|
_log;
|
|
get log() {
|
|
return this._log;
|
|
}
|
|
_logErr;
|
|
get logErr() {
|
|
return this._logErr;
|
|
}
|
|
_connectModule;
|
|
get connectModule() {
|
|
return this._connectModule;
|
|
}
|
|
async loadLibs(module) {
|
|
if (this._callModule && this._connectModule) {
|
|
return;
|
|
}
|
|
const moduleBag = await this.loadBound(module);
|
|
this._callModule = async (...args) => {
|
|
const ret = await moduleBag.callModule(...args);
|
|
this.handleError(ret);
|
|
return ret;
|
|
};
|
|
this._connectModule = moduleBag.connectModule;
|
|
this._log = log;
|
|
this._logErr = logErr;
|
|
}
|
|
async loadBound(module) {
|
|
return (await load(module));
|
|
}
|
|
handleError(ret) {
|
|
if (ret[1]) {
|
|
throw new Error(ret[1]);
|
|
}
|
|
}
|
|
handleErrorOrReturn(ret) {
|
|
this.handleError(ret);
|
|
return ret[0];
|
|
}
|
|
async callModuleReturn(method, data) {
|
|
const ret = await this.callModule(method, data);
|
|
return ret[0];
|
|
}
|
|
}
|
|
export async function load(module) {
|
|
if (callModule && connectModule) {
|
|
if (module) {
|
|
return {
|
|
callModule: callModule.bind(undefined, module),
|
|
connectModule: connectModule.bind(undefined, module),
|
|
log,
|
|
logErr,
|
|
};
|
|
}
|
|
return {
|
|
callModule,
|
|
connectModule,
|
|
log,
|
|
logErr,
|
|
};
|
|
}
|
|
const pkg = typeof window !== "undefined" && window?.document
|
|
? await import("libkernel")
|
|
: await import("libkmodule");
|
|
callModule = pkg.callModule;
|
|
connectModule = pkg.connectModule;
|
|
// @ts-ignore
|
|
log = pkg.log;
|
|
// @ts-ignore
|
|
logErr = pkg.logErr;
|
|
return load(module);
|
|
}
|
|
export const factory = function (type, module) {
|
|
return function (...args) {
|
|
return new Proxy(new type(...args), {
|
|
get(target, property) {
|
|
const prop = target[property];
|
|
if (typeof prop !== "function") {
|
|
return prop;
|
|
}
|
|
return async (...args) => {
|
|
await target.loadLibs(module);
|
|
return target[property](...args);
|
|
};
|
|
},
|
|
});
|
|
};
|
|
};
|