diff --git a/packages/datadog-shimmer/src/shimmer.js b/packages/datadog-shimmer/src/shimmer.js index add93b8b8f8..bdbd0201856 100644 --- a/packages/datadog-shimmer/src/shimmer.js +++ b/packages/datadog-shimmer/src/shimmer.js @@ -13,6 +13,8 @@ const skipMethodSize = skipMethods.size const nonConfigurableModuleExports = new WeakMap() +const safetyMap = new WeakMap() + /** * Copies properties from the original function to the wrapped function. * @@ -75,8 +77,17 @@ function copyObjectProperties (original, wrapped, skipKey) { function wrapFunction (original, wrapper) { if (typeof original !== 'function') return original + // Safe guard: If the wrapper is identical, we double wrap. + // This will not catch all types of double wrapping, just most. + const oldWrapper = safetyMap.get(original) + if (oldWrapper === wrapper) { + return original + } + const wrapped = wrapper(original) + safetyMap.set(wrapped, wrapper) + if (typeof original === 'function') { assertNotClass(original) copyProperties(original, wrapped) @@ -138,8 +149,16 @@ function wrap (target, name, wrapper, options) { assertMethod(target, name, original) + // Safe guard: If the wrapper is identical, we double wrap. + // This will not catch all types of double wrapping, just most. + const oldWrapper = safetyMap.get(original) + if (oldWrapper === wrapper) { + return + } const wrapped = wrapper(original) + safetyMap.set(wrapped, wrapper) + copyProperties(original, wrapped) if (descriptor.writable) {