Skip to content

Instantly share code, notes, and snippets.

@HeGanjie
Created March 18, 2022 02:28
Show Gist options
  • Save HeGanjie/4e2ce36e49c42c5d26d1b8ae7cda3c1c to your computer and use it in GitHub Desktop.
Save HeGanjie/4e2ce36e49c42c5d26d1b8ae7cda3c1c to your computer and use it in GitHub Desktop.
intercept object function call
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