fix(api/patcher): allow cancelling lazy patching

This commit is contained in:
amsyarasyiq 2024-05-22 03:32:41 +08:00
parent 0d6462c226
commit e70f598306
2 changed files with 11 additions and 19 deletions

View file

@ -9,10 +9,15 @@ function shim<T extends (...args: any) => any>(fn: T) {
return function shimmed(this: any, ...args: Parameters<T>) {
const proxyInfo = getFindProxyInfo(args[1]);
if (proxyInfo && !proxyInfo.cache) {
return void proxyInfo.subscribe(exp => {
let cancel = false;
let unpatch = () => cancel = true;
proxyInfo.subscribe(exp => {
args[1] = exp;
fn.apply(this, args);
if (cancel) return;
unpatch = fn.apply(this, args);
});
return () => unpatch();
}
return fn.apply(this, args);
};

View file

@ -141,7 +141,8 @@ function onModuleRequire(moduleExports: any, id: Metro.ModuleID) {
});
}
moduleSubscriptions.get(Number(id))?.forEach(s => s());
moduleSubscriptions.get(Number(id))?.forEach(s => s())
&& moduleSubscriptions.delete(Number(id));
}
export function getImportingModuleId() {
@ -151,24 +152,10 @@ export function getImportingModuleId() {
export function subscribeModule(id: number, cb: () => void): () => void {
const subs = moduleSubscriptions.get(id) ?? new Set();
const deleteIfEmpty = () => {
subs.delete(cb);
if (moduleSubscriptions.get(id)?.size === 0) {
moduleSubscriptions.delete(id);
}
};
const wrappedCb = () => {
cb();
deleteIfEmpty();
};
subs.add(wrappedCb);
subs.add(cb);
moduleSubscriptions.set(id, subs);
return () => {
subs.delete(wrappedCb);
deleteIfEmpty();
};
return () => subs.delete(cb);
}
export function requireModule(id: Metro.ModuleID) {