tusk
Version:
Tusk lets you carve into JavaScript, TypeScript, and beyond with raw power.
2 lines (1 loc) • 1.04 kB
JavaScript
function c(e,n,i){if(!e||typeof e!="object")throw new TypeError("Target must be a non-null object.");if(!n||typeof n!="string")throw new TypeError("Method must be a valid string.");if(typeof i!="function")throw new TypeError("Patch function must be a function.")}var a=new WeakMap,t=new WeakMap;function p(e,n,i){c(e,n,i);let r=e[n];if(typeof r!="function")throw new TypeError(`${String(n)} is not a function.`);if(t.has(e)&&t.get(e).has(n))throw new TypeError(`Method ${String(n)} is already patched.`);t.has(e)||t.set(e,new Map),t.get(e).set(n,{target:e,methodName:n,originalMethod:r,implementation:function(...y){return i.call(this,r,...y)}}),Object.defineProperty(e,n,{value:t.get(e).get(n).implementation,configurable:!0,writable:!0})}function T(e,n){let i=t.get(e)?.get(n),r=a.get(e)?.get(n);if(i)Object.defineProperty(e,n,{value:i.originalMethod,configurable:!0,writable:!0}),t.get(e).delete(n);else if(r)a.get(e).delete(n);else throw new TypeError(`Method ${String(n)} was not patched or extended.`)}export{p as patch,T as unpatch};