From d43173697945c9362d77e14e9404a712bc5f13ed Mon Sep 17 00:00:00 2001 From: vmarchaud Date: Sun, 26 Jan 2020 11:37:48 +0100 Subject: [PATCH] chore: extract package name from require.cache --- .../src/instrumentation/PluginLoader.ts | 4 ++- .../src/instrumentation/utils.ts | 27 +++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/packages/opentelemetry-node/src/instrumentation/PluginLoader.ts b/packages/opentelemetry-node/src/instrumentation/PluginLoader.ts index 453bc36ae43..760013d4624 100644 --- a/packages/opentelemetry-node/src/instrumentation/PluginLoader.ts +++ b/packages/opentelemetry-node/src/instrumentation/PluginLoader.ts @@ -85,7 +85,9 @@ export class PluginLoader { const alreadyRequiredModules = Object.keys(require.cache); const requiredModulesToHook = modulesToHook.filter(name => - alreadyRequiredModules.some(cached => cached.includes(name)) + alreadyRequiredModules.some( + cached => utils.packageNameFromPath(cached) === name + ) ); if (requiredModulesToHook.length > 0) { this.logger.warn( diff --git a/packages/opentelemetry-node/src/instrumentation/utils.ts b/packages/opentelemetry-node/src/instrumentation/utils.ts index 9460de4ad8d..de4503c323c 100644 --- a/packages/opentelemetry-node/src/instrumentation/utils.ts +++ b/packages/opentelemetry-node/src/instrumentation/utils.ts @@ -72,3 +72,30 @@ export function isSupportedVersion( export function searchPathForTest(searchPath: string) { module.paths.push(searchPath); } + +// Includes support for npm '@org/name' packages +// Regex: .*?node_modules(?!.*node_modules)\/(@[^\/]*\/[^\/]*|[^\/]*).* +// Tests: https://regex101.com/r/lW2bE3/6 +const moduleRegex = new RegExp( + [ + '.*?node_modules(?!.*node_modules)\\', + '(@[^\\', + ']*\\', + '[^\\', + ']*|[^\\', + ']*).*', + ].join(path.sep) +); + +/** + * Retrieves a package name from the full import path. + * For example: + * './node_modules/bar/index/foo.js' => 'bar' + * + * @param path The full import path. + * Extracted from https://github.com/googleapis/cloud-trace-nodejs/blob/master/src/util.ts#L214 + */ +export function packageNameFromPath(importPath: string) { + const matches = moduleRegex.exec(importPath); + return matches && matches.length > 1 ? matches[1] : null; +}