Skip to content

Commit

Permalink
bootstrap-capable monkey-patch
Browse files Browse the repository at this point in the history
  • Loading branch information
retorquere committed Jan 4, 2024
1 parent 1c62f3c commit 77a3632
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions monkey-patch.ts
Original file line number Diff line number Diff line change
@@ -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
}
}

0 comments on commit 77a3632

Please sign in to comment.