Skip to content

Commit c69f877

Browse files
authored
fix(hooks): hooks double patching (#7601)
* fix hooks double patching * Prevent fix on builtin modules * testing with out weakmap * fix hook cache logic * fix onrequire wrapping
1 parent e52cd32 commit c69f877

File tree

1 file changed

+17
-11
lines changed
  • packages/datadog-instrumentations/src/helpers

1 file changed

+17
-11
lines changed

packages/datadog-instrumentations/src/helpers/hook.js

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -26,31 +26,37 @@ function Hook (modules, hookOptions, onrequire) {
2626
const parts = [moduleBaseDir, moduleName].filter(Boolean)
2727
const filename = path.join(...parts)
2828

29-
if (this._patched[filename] && patched.has(moduleExports)) {
30-
return patched.get(moduleExports)
31-
}
32-
3329
let defaultWrapResult
3430

31+
const wrappedOnrequire = (moduleExports, ...args) => {
32+
if (this._patched[filename] && patched.has(moduleExports)) {
33+
return patched.get(moduleExports)
34+
}
35+
36+
const result = onrequire(moduleExports, ...args)
37+
if (result && (typeof result === 'object' || typeof result === 'function')) {
38+
patched.set(moduleExports, result)
39+
patched.set(result, result)
40+
}
41+
42+
return result
43+
}
44+
3545
if (
3646
isIitm &&
3747
moduleExports.default &&
3848
(typeof moduleExports.default === 'object' ||
3949
typeof moduleExports.default === 'function')
4050
) {
41-
defaultWrapResult = onrequire(moduleExports.default, moduleName, moduleBaseDir, moduleVersion, isIitm)
51+
defaultWrapResult = wrappedOnrequire(moduleExports.default, moduleName, moduleBaseDir, moduleVersion, isIitm)
4252
}
4353

44-
const newExports = onrequire(moduleExports, moduleName, moduleBaseDir, moduleVersion, isIitm)
54+
const newExports = wrappedOnrequire(moduleExports, moduleName, moduleBaseDir, moduleVersion, isIitm)
4555

4656
if (defaultWrapResult) newExports.default = defaultWrapResult
4757

4858
this._patched[filename] = true
49-
if (newExports &&
50-
(typeof newExports === 'object' ||
51-
typeof newExports === 'function')) {
52-
patched.set(moduleExports, newExports)
53-
}
59+
5460
return newExports
5561
}
5662

0 commit comments

Comments
 (0)