| 49 | * }); |
| 50 | */ |
| 51 | export function patch( |
| 52 | proto: Record<string, any>, |
| 53 | name: string, |
| 54 | fn: (...args: any[]) => any, |
| 55 | ): void { |
| 56 | // use the object prototype if possible |
| 57 | if (typeof proto.prototype !== "undefined") { |
| 58 | proto = proto.prototype; |
| 59 | } |
| 60 | // reuse the logic behind object extends |
| 61 | if (typeof proto[name] === "function") { |
| 62 | // save the original function |
| 63 | const _parent = proto[name]; |
| 64 | // override the function with the new one |
| 65 | Object.defineProperty(proto, name, { |
| 66 | configurable: true, |
| 67 | value: (function (_name: string, fn: (...args: any[]) => any) { |
| 68 | return function (this: any, ...args: any[]) { |
| 69 | this._patched = _parent; |
| 70 | const ret = fn.apply(this, args); |
| 71 | this._patched = null; |
| 72 | return ret; |
| 73 | }; |
| 74 | })(name, fn), |
| 75 | }); |
| 76 | } else { |
| 77 | throw new Error(`${name} is not an existing function`); |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | /** |
| 82 | * Register a plugin. |