Created
March 18, 2022 02:28
-
-
Save HeGanjie/4e2ce36e49c42c5d26d1b8ae7cda3c1c to your computer and use it in GitHub Desktop.
intercept object function call
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function interceptFuncCall(object: any, fnName: any, fnReplace: (originalObj: any, ...originalArgs: any[]) => any) { | |
const obj = new Proxy(object, { | |
get: function(target, propKey, receiver) { | |
if (propKey === fnName) { | |
return function() { | |
return fnReplace(target, ...arguments) | |
} | |
} | |
const val = Reflect.get(target, propKey, receiver) | |
return val | |
} | |
}) | |
return obj | |
// const fnToWrap = object[fnName] | |
// object[fnName] = function() { | |
// return fnReplace(fnToWrap.bind(this), ...arguments) | |
// } | |
// return object | |
} | |
function notebookDefinitionInject( | |
defineFn: Function, | |
overridingVariables: Record<string, any> | |
) { | |
return function define(runtime: any, observer: Function) { | |
const runtimeProxy = interceptFuncCall(runtime, 'module', (originRuntime, ...args0) => { | |
return interceptFuncCall(originRuntime.module(...args0), 'variable', (originModule, ...args1) => { | |
return interceptFuncCall(originModule.variable(...args1), 'define', (originVar, ...args2) => { | |
const [varName, deps, fn] = args2 | |
if (_.isString(varName) && (varName in overridingVariables)) { | |
if (_.isFunction(deps)) { | |
// no deps | |
return originVar.define(varName, overridingVariables[varName]) | |
} else if (_.isFunction(fn)) { | |
return originVar.define(varName, deps, overridingVariables[varName]) | |
} | |
} | |
// no name, skip | |
return originVar.define(...args2) | |
}) | |
}) | |
}) | |
return defineFn(runtimeProxy, observer) | |
// const main = runtime.module(); | |
// main.variable(observer("React")).define("React", ["requires"], _React); | |
// return main; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment