From 77a36322b55b3b8f2c8701452751a463b783589f Mon Sep 17 00:00:00 2001 From: Emiliano Heyns Date: Thu, 4 Jan 2024 13:26:48 +0100 Subject: [PATCH] bootstrap-capable monkey-patch --- monkey-patch.ts | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 monkey-patch.ts diff --git a/monkey-patch.ts b/monkey-patch.ts new file mode 100644 index 0000000..f3adca1 --- /dev/null +++ b/monkey-patch.ts @@ -0,0 +1,22 @@ +/* eslint-disable @typescript-eslint/ban-types, prefer-rest-params, @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-argument */ + +export type Trampoline = Function & { disabled?: boolean } +const trampolines: Trampoline[] = [] + +export function patch(object: any, method: string, patcher: (f: Function) => Function, mem?: Trampoline[]): void { + if (typeof object[method] !== 'function') throw new Error(`monkey-patch: ${method} is not a function`) + + const orig = object[method] + const patched = patcher(orig) + object[method] = function trampoline() { + return (trampoline as Trampoline).disabled ? orig.apply(this, arguments) : patched.apply(this, arguments) + } + trampolines.push(object[method]) + if (mem) mem.push(object[method]) +} + +export function unpatch(functions?: Trampoline[]) { + for (const trampoline of (functions || trampolines)) { + trampoline.disabled = true + } +}