refactor: path only script + weak ref hmr

This commit is contained in:
cha0s 2024-10-21 07:52:34 -05:00
parent bd5c069090
commit c499afb246

View File

@ -22,27 +22,19 @@ export default class Script {
return this.fn(this.locals).next().value;
}
static load(pathOrFunction, locals) {
let fn;
if (this.registered[pathOrFunction]) {
fn = this.registered[pathOrFunction];
}
else if (pathOrFunction) {
try {
fn = eval(pathOrFunction);
}
catch (error) {
console.error("Couldn't eval script", pathOrFunction);
console.error(error);
}
}
static load(path, locals) {
const fn = this.registered[path];
if (!fn) {
return undefined;
throw new Error(`no such script: ${path}`);
}
const script = new this(fn, locals);
if (import.meta.hot) {
const hotRef = new WeakRef(script);
import.meta.hot.accept('./scripts.js', ({default: scripts}) => {
script.fn = scripts[`../..${pathOrFunction}`];
const ref = hotRef.deref();
if (ref) {
ref.fn = scripts[`../..${path}`];
}
});
}
return script;