From 8b3870d3fc00f9a3bcc1dd1948d01039dbae0a7d Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:41:24 +0000 Subject: [PATCH 01/14] feat(node,deno): Report installed package versions in modulesIntegration Rework how `modulesIntegration` collects packages so that it gives the same result for CommonJS and ESM, in Node.js, Bun and Deno. The app's `package.json` is found from the entry file (falling back to cwd), and each declared dependency gets the exact version from its installed `package.json`, resolved the way a bare import would resolve it. Previously ESM apps (and the Next.js build-time injection) reported the version ranges from `package.json`, and only CommonJS apps got exact versions from `require.cache`. `require.cache` still adds loaded transitive packages in CJS. The resolver lives in `@sentry/core/server` behind a `readFile` callback, so Next.js uses it at build time and `@sentry/deno` uses it with permission checks. `@sentry/deno` gets `modulesIntegration` as a default integration, which also reads `deno.lock` for `jsr:` and `npm:` specifiers and never prompts for read permission. Co-Authored-By: Francesco Gringl-Novy <2411343+mydea@users.noreply.github.com> --- .../node-suites/excludes.ts | 6 - .../suites/modules/esm-app/lib/package.json | 3 + .../lib/scenario.js} | 5 +- .../suites/modules/esm-app/package.json | 10 + .../suites/modules/scenario.js | 12 + .../suites/modules/scenario.mjs | 11 + .../suites/modules/server.js | 23 -- .../suites/modules/server.mjs | 10 - .../suites/modules/test.ts | 71 ++++-- packages/core/src/server.ts | 4 + packages/core/src/utils/installedModules.ts | 210 ++++++++++++++++++ .../test/lib/utils/installedModules.test.ts | 186 ++++++++++++++++ packages/deno/src/index.ts | 1 + packages/deno/src/integrations/modules.ts | 97 ++++++++ packages/deno/src/sdk.ts | 2 + .../deno/test/__snapshots__/mod.test.ts.snap | 9 + packages/deno/test/exports.test.ts | 1 + packages/deno/test/fixtures/modules/deno.lock | 7 + packages/deno/test/fixtures/modules/main.ts | 15 ++ .../deno/test/fixtures/modules/package.json | 7 + packages/deno/test/modules.test.ts | 26 +++ packages/deno/test/normalize.ts | 5 + packages/nextjs/src/config/util.ts | 32 ++- packages/node/src/integrations/modules.ts | 149 +++---------- 24 files changed, 702 insertions(+), 200 deletions(-) create mode 100644 dev-packages/node-integration-tests/suites/modules/esm-app/lib/package.json rename dev-packages/node-integration-tests/suites/modules/{instrument.mjs => esm-app/lib/scenario.js} (53%) create mode 100644 dev-packages/node-integration-tests/suites/modules/esm-app/package.json create mode 100644 dev-packages/node-integration-tests/suites/modules/scenario.js create mode 100644 dev-packages/node-integration-tests/suites/modules/scenario.mjs delete mode 100644 dev-packages/node-integration-tests/suites/modules/server.js delete mode 100644 dev-packages/node-integration-tests/suites/modules/server.mjs create mode 100644 packages/core/src/utils/installedModules.ts create mode 100644 packages/core/test/lib/utils/installedModules.test.ts create mode 100644 packages/deno/src/integrations/modules.ts create mode 100644 packages/deno/test/fixtures/modules/deno.lock create mode 100644 packages/deno/test/fixtures/modules/main.ts create mode 100644 packages/deno/test/fixtures/modules/package.json create mode 100644 packages/deno/test/modules.test.ts diff --git a/dev-packages/bun-integration-tests/node-suites/excludes.ts b/dev-packages/bun-integration-tests/node-suites/excludes.ts index e42f348bc04b..0667a3ce5748 100644 --- a/dev-packages/bun-integration-tests/node-suites/excludes.ts +++ b/dev-packages/bun-integration-tests/node-suites/excludes.ts @@ -146,11 +146,6 @@ export const NO_AUTO_INSTRUMENTATION = [ // `new`, and the top-level frame of a CommonJS module is ``, not `Object.?`. const BUN_STACK_FRAMES_DIFFER = ['suites/contextLines/filename-with-spaces/test.ts']; -// The CJS and ESM cases need Express to capture the route error, which `bun run` does not -// instrument. A bundled app does not help: it has no `require.cache`, and the isolated packages -// are inlined, so the module versions do not match. -const MODULES_NEED_UNBUNDLED_EXPRESS = ['suites/modules/test.ts']; - // The scenario configures `nativeNodeFetchIntegration`, which `@sentry/bun` does not export. const NO_NATIVE_NODE_FETCH_INTEGRATION = [ 'suites/tracing/http-client-spans/fetch-forward-request-hook/test.ts', @@ -189,7 +184,6 @@ export const NODE_SUITES_EXCLUDE = [ ...NODE_ONLY, ...NO_AUTO_INSTRUMENTATION, ...BUN_STACK_FRAMES_DIFFER, - ...MODULES_NEED_UNBUNDLED_EXPRESS, ]; // Excluded only in the `node-suites` project, which runs the suites with `@sentry/node`. diff --git a/dev-packages/node-integration-tests/suites/modules/esm-app/lib/package.json b/dev-packages/node-integration-tests/suites/modules/esm-app/lib/package.json new file mode 100644 index 000000000000..3dbc1ca591c0 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/modules/esm-app/lib/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/dev-packages/node-integration-tests/suites/modules/instrument.mjs b/dev-packages/node-integration-tests/suites/modules/esm-app/lib/scenario.js similarity index 53% rename from dev-packages/node-integration-tests/suites/modules/instrument.mjs rename to dev-packages/node-integration-tests/suites/modules/esm-app/lib/scenario.js index c8cdc9cac0a2..733c3a99111a 100644 --- a/dev-packages/node-integration-tests/suites/modules/instrument.mjs +++ b/dev-packages/node-integration-tests/suites/modules/esm-app/lib/scenario.js @@ -5,7 +5,6 @@ Sentry.init({ dsn: 'https://public@dsn.ingest.sentry.io/1337', release: '1.0', transport: loggingTransport, - // Tracing is off, so `expressIntegration()` is not a default integration; opt in explicitly to - // capture the thrown route error this test inspects. - integrations: [Sentry.expressIntegration()], }); + +Sentry.captureException(new Error('error_1')); diff --git a/dev-packages/node-integration-tests/suites/modules/esm-app/package.json b/dev-packages/node-integration-tests/suites/modules/esm-app/package.json new file mode 100644 index 000000000000..7c4e56ac3728 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/modules/esm-app/package.json @@ -0,0 +1,10 @@ +{ + "name": "esm-app", + "private": true, + "dependencies": { + "esm-app-dependency": "^1.0.0" + }, + "devDependencies": { + "esm-app-missing-dependency": "^2.0.0" + } +} diff --git a/dev-packages/node-integration-tests/suites/modules/scenario.js b/dev-packages/node-integration-tests/suites/modules/scenario.js new file mode 100644 index 000000000000..fc966f0457fb --- /dev/null +++ b/dev-packages/node-integration-tests/suites/modules/scenario.js @@ -0,0 +1,12 @@ +const { loggingTransport } = require('@sentry-internal/node-integration-tests'); +const Sentry = require('@sentry/node'); + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + release: '1.0', + transport: loggingTransport, +}); + +require('express'); + +Sentry.captureException(new Error('error_1')); diff --git a/dev-packages/node-integration-tests/suites/modules/scenario.mjs b/dev-packages/node-integration-tests/suites/modules/scenario.mjs new file mode 100644 index 000000000000..874679d5b877 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/modules/scenario.mjs @@ -0,0 +1,11 @@ +import * as Sentry from '@sentry/node'; +import { loggingTransport } from '@sentry-internal/node-integration-tests'; +import 'express'; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + release: '1.0', + transport: loggingTransport, +}); + +Sentry.captureException(new Error('error_1')); diff --git a/dev-packages/node-integration-tests/suites/modules/server.js b/dev-packages/node-integration-tests/suites/modules/server.js deleted file mode 100644 index bf5ec659e060..000000000000 --- a/dev-packages/node-integration-tests/suites/modules/server.js +++ /dev/null @@ -1,23 +0,0 @@ -const { loggingTransport } = require('@sentry-internal/node-integration-tests'); -const Sentry = require('@sentry/node'); - -Sentry.init({ - dsn: 'https://public@dsn.ingest.sentry.io/1337', - release: '1.0', - transport: loggingTransport, - // Tracing is off, so `expressIntegration()` is not a default integration; opt in explicitly to - // capture the thrown route error this test inspects. - integrations: [Sentry.expressIntegration()], -}); - -// express must be required after Sentry is initialized -const express = require('express'); -const { startExpressServerAndSendPortToRunner } = require('@sentry-internal/node-integration-tests'); - -const app = express(); - -app.get('/test1', () => { - throw new Error('error_1'); -}); - -startExpressServerAndSendPortToRunner(app); diff --git a/dev-packages/node-integration-tests/suites/modules/server.mjs b/dev-packages/node-integration-tests/suites/modules/server.mjs deleted file mode 100644 index d34710e81dad..000000000000 --- a/dev-packages/node-integration-tests/suites/modules/server.mjs +++ /dev/null @@ -1,10 +0,0 @@ -import { startExpressServerAndSendPortToRunner } from '@sentry-internal/node-integration-tests'; -import express from 'express'; - -const app = express(); - -app.get('/test1', () => { - throw new Error('error_1'); -}); - -startExpressServerAndSendPortToRunner(app); diff --git a/dev-packages/node-integration-tests/suites/modules/test.ts b/dev-packages/node-integration-tests/suites/modules/test.ts index 5e6b65cc8672..a1e986c24b98 100644 --- a/dev-packages/node-integration-tests/suites/modules/test.ts +++ b/dev-packages/node-integration-tests/suites/modules/test.ts @@ -1,35 +1,42 @@ import { SDK_VERSION } from '@sentry/core'; -import { mkdirSync, rmSync, symlinkSync, writeFileSync } from 'fs'; +import { copyFileSync, cpSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'fs'; import { dirname, join } from 'path'; import { afterAll, describe, expect, test } from 'vitest'; import { cleanupChildProcesses, createRunner } from '../../utils/runner'; +// Each test writes its packages into a folder of its own, because the Bun integration tests run this suite in +// several projects at the same time. +function makeTempDir(): string { + return mkdtempSync(join(__dirname, 'tmp-')); +} + describe('modulesIntegration', () => { afterAll(() => { cleanupChildProcesses(); }); test('CJS', async () => { - const runner = createRunner(__dirname, 'server.js') - .withMockSentryServer() + await createRunner(__dirname, 'scenario.js') .expect({ event: { modules: { - // exact version comes from require.caches express: expect.stringMatching(/^4\.\d+\.\d+$/), - // this comes from package.json '@sentry/node': SDK_VERSION, - yargs: '^18.2.0', + // Declared in package.json and installed, but never loaded + yargs: expect.stringMatching(/^18\.\d+\.\d+$/), + // Not declared, but loaded by express, so it is in require.cache + finalhandler: expect.stringMatching(/^\d+\.\d+\.\d+$/), }, }, }) - .start(); - runner.makeRequest('get', '/test1', { expectError: true }); - await runner.completed(); + .start() + .completed(); }); test('CJS with the isolated layouts of pnpm and Bun', async () => { - const nodeModulesDir = join(__dirname, 'node_modules'); + const tempDir = makeTempDir(); + copyFileSync(join(__dirname, 'scenario-isolated.js'), join(tempDir, 'scenario-isolated.js')); + const nodeModulesDir = join(tempDir, 'node_modules'); for (const [storeDir, name, version, linked] of [ ['.pnpm', 'pnpm-isolated-package', '1.2.3', true], // Only a dependency of the app uses this version, so it is not linked into `node_modules` @@ -50,7 +57,7 @@ describe('modulesIntegration', () => { } try { - await createRunner(__dirname, 'scenario-isolated.js') + await createRunner(tempDir, 'scenario-isolated.js') .expect({ event: { modules: { @@ -64,26 +71,48 @@ describe('modulesIntegration', () => { .start() .completed(); } finally { - rmSync(nodeModulesDir, { recursive: true, force: true }); + rmSync(tempDir, { recursive: true, force: true }); } }); test('ESM', async () => { - const runner = createRunner(__dirname, 'server.mjs') - .withInstrument(join(__dirname, 'instrument.mjs')) - .withMockSentryServer() + await createRunner(__dirname, 'scenario.mjs') .expect({ event: { modules: { - // this comes from package.json - express: expect.stringMatching(/^\^4\.\d+\.\d+$/), + express: expect.stringMatching(/^4\.\d+\.\d+$/), '@sentry/node': SDK_VERSION, - yargs: '^18.2.0', + yargs: expect.stringMatching(/^18\.\d+\.\d+$/), }, }, }) - .start(); - runner.makeRequest('get', '/test1', { expectError: true }); - await runner.completed(); + .start() + .completed(); + }); + + test('ESM app in a subfolder with its own package.json', async () => { + const tempDir = makeTempDir(); + const appDir = join(tempDir, 'esm-app'); + cpSync(join(__dirname, 'esm-app'), appDir, { recursive: true }); + const packageDir = join(appDir, 'node_modules', 'esm-app-dependency'); + mkdirSync(packageDir, { recursive: true }); + writeFileSync(join(packageDir, 'package.json'), JSON.stringify({ name: 'esm-app-dependency', version: '1.4.0' })); + + try { + await createRunner(appDir, 'lib', 'scenario.js') + .expect({ + event: event => { + expect(event.modules).toEqual({ + 'esm-app-dependency': '1.4.0', + // Not installed, so the range from package.json is all there is + 'esm-app-missing-dependency': '^2.0.0', + }); + }, + }) + .start() + .completed(); + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } }); }); diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index e3636550b77c..cde70d8e37d0 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -34,6 +34,10 @@ export { trpcMiddleware } from './trpc'; export { wrapMcpServerWithSentry } from './integrations/mcp-server'; export { isNodeEnv, loadModule } from './utils/node'; export { filenameIsInApp, node, nodeStackLineParser } from './utils/node-stack-trace'; +export { + collectInstalledModules as _INTERNAL_collectInstalledModules, + parseDenoLockModules as _INTERNAL_parseDenoLockModules, +} from './utils/installedModules'; export { vercelWaitUntil } from './utils/vercelWaitUntil'; export { getReleaseMetaTag as _INTERNAL_getReleaseMetaTag } from './utils/meta'; export { diff --git a/packages/core/src/utils/installedModules.ts b/packages/core/src/utils/installedModules.ts new file mode 100644 index 000000000000..9c095627aa2a --- /dev/null +++ b/packages/core/src/utils/installedModules.ts @@ -0,0 +1,210 @@ +import { dirname, join } from './path'; + +/** Package names mapped to versions, as sent in `event.modules`. */ +export type ModuleInfo = Record; + +/** Reads a UTF-8 file. Returns `undefined` when the file does not exist or cannot be read. */ +export type ReadFileFn = (path: string) => string | undefined; + +export interface CollectInstalledModulesOptions { + readFile: ReadFileFn; + /** Absolute path of the entry file of the app, such as `process.argv[1]`. */ + entryPath?: string; + /** Used to find the app's `package.json` when the entry file does not lead to one. */ + cwd?: string; + /** Absolute paths of the files that the runtime loaded, such as the keys of `require.cache`. */ + loadedFiles?: string[]; +} + +export interface InstalledModules { + /** The `dependencies` and `devDependencies` of the app's `package.json`, with the version ranges as declared. */ + declared: ModuleInfo; + /** Exact versions read from the installed `package.json` of each package. */ + installed: ModuleInfo; +} + +interface PackageJson { + name?: string; + version?: string; + dependencies?: Record; + devDependencies?: Record; +} + +const NODE_MODULES_SEGMENT = '/node_modules/'; + +/** + * Finds the app's `package.json` and returns each dependency it declares, plus the exact version of every package + * that resolves from the app's `node_modules` folders. + * + * Packages resolve the way Node.js resolves a bare `require(name)` or `import name` from the entry file, so the + * result is the same for CommonJS and ESM apps, and for the flat (npm, Yarn, Bun) and isolated (pnpm, Bun) layouts. + */ +export function collectInstalledModules(options: CollectInstalledModulesOptions): InstalledModules { + const { readFile, loadedFiles = [] } = options; + const entryDir = options.entryPath ? dirname(toPosixPath(options.entryPath)) : undefined; + const cwd = options.cwd ? toPosixPath(options.cwd) : undefined; + + // An entry file outside the working directory usually belongs to a launcher, such as the AWS Lambda runtime. + const appRoot = findAppRoot(readFile, entryDir && cwd && !isInDir(entryDir, cwd) ? [cwd, entryDir] : [entryDir, cwd]); + // Resolve from the entry file when it lives in the app, so nested `node_modules` between the two are searched too. + const resolveFrom = entryDir && appRoot && isInDir(entryDir, appRoot) ? entryDir : appRoot || entryDir || cwd; + const nodeModulesDirs = resolveFrom ? getAncestorDirs(resolveFrom).map(dir => join(dir, 'node_modules')) : []; + + const packageJson = appRoot ? readPackageJson(readFile, appRoot) : undefined; + const declared: ModuleInfo = { + ...packageJson?.dependencies, + ...packageJson?.devDependencies, + }; + + const installed = getLoadedModules(readFile, loadedFiles, nodeModulesDirs); + for (const name of Object.keys(declared)) { + const version = resolveInstalledVersion(readFile, name, nodeModulesDirs); + if (version) { + installed[name] = version; + } + } + + return { declared, installed }; +} + +/** + * Reads the exact versions of the packages in a `deno.lock` file (versions 3 to 5). + * Returns an empty object when the content is not a lockfile that this function understands. + */ +export function parseDenoLockModules(content: string): ModuleInfo { + let specifiers: unknown; + try { + const lock = JSON.parse(content) as { specifiers?: unknown; packages?: { specifiers?: unknown } }; + specifiers = lock.specifiers ?? lock.packages?.specifiers; + } catch { + return {}; + } + + const modules: ModuleInfo = {}; + if (!specifiers || typeof specifiers !== 'object') { + return modules; + } + + for (const [specifier, resolved] of Object.entries(specifiers)) { + const name = /^(?:npm|jsr):(@?[^@]+)@/.exec(specifier)?.[1]; + if (!name || typeof resolved !== 'string') { + continue; + } + // Version 3 stores the full specifier (`npm:express@4.21.2`), later versions only the version. + // npm versions can carry a peer dependency suffix (`18.3.0_react@18.3.1`). + const version = (resolved.includes(':') ? resolved.slice(resolved.lastIndexOf('@') + 1) : resolved).split('_')[0]; + if (version) { + modules[name] = version; + } + } + + return modules; +} + +/** + * The nearest folder above one of `startDirs` that has a `package.json` for an app. + * Skips start folders inside `node_modules` (such as the binary of `next start`) and `package.json` files that only + * set a field such as `"type": "module"` for a build output folder. + */ +function findAppRoot(readFile: ReadFileFn, startDirs: Array): string | undefined { + for (const startDir of startDirs) { + if (!startDir || `${startDir}/`.includes(NODE_MODULES_SEGMENT)) { + continue; + } + for (const dir of getAncestorDirs(startDir)) { + const packageJson = readPackageJson(readFile, dir); + if (packageJson && (packageJson.name || packageJson.dependencies || packageJson.devDependencies)) { + return dir; + } + } + } + return undefined; +} + +/** The version of the package that a bare `require(name)` loads when it searches `nodeModulesDirs`. */ +function resolveInstalledVersion(readFile: ReadFileFn, name: string, nodeModulesDirs: string[]): string | undefined { + for (const dir of nodeModulesDirs) { + const packageJson = readPackageJson(readFile, join(dir, name)); + if (packageJson) { + return typeof packageJson.version === 'string' ? packageJson.version : undefined; + } + } + return undefined; +} + +/** The packages of the loaded files that live in one of `nodeModulesDirs`, including pnpm and Bun stores there. */ +function getLoadedModules(readFile: ReadFileFn, loadedFiles: string[], nodeModulesDirs: string[]): ModuleInfo { + const versionsByName: Record = {}; + const seenPackageDirs = new Set(); + + for (const file of loadedFiles) { + const path = toPosixPath(file); + if (!nodeModulesDirs.some(dir => isInDir(path, dir))) { + continue; + } + + const packageDir = getPackageDir(path); + if (!packageDir || seenPackageDirs.has(packageDir.dir)) { + continue; + } + seenPackageDirs.add(packageDir.dir); + + const version = readPackageJson(readFile, packageDir.dir)?.version; + if (typeof version === 'string') { + versionsByName[packageDir.name] = [...(versionsByName[packageDir.name] || []), version]; + } + } + + const modules: ModuleInfo = {}; + for (const [name, versions] of Object.entries(versionsByName)) { + // pnpm and Bun stores can hold several loaded versions of one package. Prefer the one the app itself resolves. + const appVersion = versions.length > 1 ? resolveInstalledVersion(readFile, name, nodeModulesDirs) : undefined; + modules[name] = appVersion && versions.includes(appVersion) ? appVersion : (versions[0] as string); + } + return modules; +} + +/** The innermost `node_modules/` or `node_modules/@scope/` folder that contains `path`. */ +function getPackageDir(path: string): { name: string; dir: string } | undefined { + const index = path.lastIndexOf(NODE_MODULES_SEGMENT); + if (index === -1) { + return undefined; + } + const base = path.slice(0, index + NODE_MODULES_SEGMENT.length); + const [first, second] = path.slice(base.length).split('/'); + const name = first?.startsWith('@') && second ? `${first}/${second}` : first; + return name ? { name, dir: base + name } : undefined; +} + +function readPackageJson(readFile: ReadFileFn, dir: string): PackageJson | undefined { + const content = readFile(join(dir, 'package.json')); + if (!content) { + return undefined; + } + try { + const packageJson = JSON.parse(content) as PackageJson | null; + return packageJson && typeof packageJson === 'object' ? packageJson : undefined; + } catch { + return undefined; + } +} + +function getAncestorDirs(dir: string): string[] { + const dirs = [dir]; + for ( + let parent = dirname(dir); + parent && parent !== '.' && parent !== dirs[dirs.length - 1]; + parent = dirname(parent) + ) { + dirs.push(parent); + } + return dirs; +} + +function isInDir(path: string, dir: string): boolean { + return path === dir || path.startsWith(dir.endsWith('/') ? dir : `${dir}/`); +} + +function toPosixPath(path: string): string { + return path.replace(/\\/g, '/'); +} diff --git a/packages/core/test/lib/utils/installedModules.test.ts b/packages/core/test/lib/utils/installedModules.test.ts new file mode 100644 index 000000000000..b3395c29f489 --- /dev/null +++ b/packages/core/test/lib/utils/installedModules.test.ts @@ -0,0 +1,186 @@ +import { describe, expect, it } from 'vitest'; +import { collectInstalledModules, parseDenoLockModules } from '../../../src/utils/installedModules'; + +function makeFs(files: Record): (path: string) => string | undefined { + return path => { + const content = files[path]; + if (content === undefined) { + return undefined; + } + return typeof content === 'string' ? content : JSON.stringify(content); + }; +} + +describe('collectInstalledModules', () => { + it('resolves declared dependencies to their installed versions and keeps the range of the rest', () => { + const readFile = makeFs({ + '/app/package.json': { + name: 'app', + dependencies: { express: '^4.0.0', '@scope/lib': '^2.0.0' }, + devDependencies: { vitest: '^3.0.0' }, + }, + '/app/node_modules/express/package.json': { name: 'express', version: '4.21.2' }, + '/app/node_modules/@scope/lib/package.json': { name: '@scope/lib', version: '2.3.4' }, + }); + + expect(collectInstalledModules({ readFile, entryPath: '/app/dist/index.js' })).toEqual({ + declared: { express: '^4.0.0', '@scope/lib': '^2.0.0', vitest: '^3.0.0' }, + installed: { express: '4.21.2', '@scope/lib': '2.3.4' }, + }); + }); + + it('resolves packages hoisted to a monorepo root', () => { + const readFile = makeFs({ + '/repo/package.json': { name: 'repo', devDependencies: { turbo: '^2.0.0' } }, + '/repo/apps/api/package.json': { name: 'api', dependencies: { hono: '^4.0.0' } }, + '/repo/node_modules/hono/package.json': { version: '4.6.0' }, + }); + + expect(collectInstalledModules({ readFile, entryPath: '/repo/apps/api/dist/server.mjs', cwd: '/repo' })).toEqual({ + declared: { hono: '^4.0.0' }, + installed: { hono: '4.6.0' }, + }); + }); + + it('skips package.json files that only configure a build output folder', () => { + const readFile = makeFs({ + '/app/package.json': { name: 'app', dependencies: { koa: '^2.0.0' } }, + '/app/dist/package.json': { type: 'module' }, + '/app/node_modules/koa/package.json': { version: '2.15.3' }, + }); + + expect(collectInstalledModules({ readFile, entryPath: '/app/dist/index.js' }).installed).toEqual({ koa: '2.15.3' }); + }); + + it('uses cwd when the entry file is inside node_modules', () => { + const readFile = makeFs({ + '/app/package.json': { name: 'app', dependencies: { next: '^15.0.0' } }, + '/app/node_modules/next/package.json': { name: 'next', version: '15.1.0' }, + }); + + expect( + collectInstalledModules({ readFile, entryPath: '/app/node_modules/next/dist/bin/next', cwd: '/app' }), + ).toEqual({ + declared: { next: '^15.0.0' }, + installed: { next: '15.1.0' }, + }); + }); + + it('prefers cwd when the entry file is outside of it', () => { + const readFile = makeFs({ + '/var/runtime/package.json': { name: 'lambda-runtime', dependencies: { 'aws-sdk': '^2.0.0' } }, + '/var/task/package.json': { name: 'app', dependencies: { pg: '^8.0.0' } }, + '/var/task/node_modules/pg/package.json': { version: '8.13.1' }, + }); + + expect(collectInstalledModules({ readFile, entryPath: '/var/runtime/index.mjs', cwd: '/var/task' })).toEqual({ + declared: { pg: '^8.0.0' }, + installed: { pg: '8.13.1' }, + }); + }); + + it('uses the entry file when cwd has no package.json', () => { + const readFile = makeFs({ + '/srv/app/package.json': { name: 'app', dependencies: { pg: '^8.0.0' } }, + '/srv/app/node_modules/pg/package.json': { version: '8.13.1' }, + }); + + expect(collectInstalledModules({ readFile, entryPath: '/srv/app/index.js', cwd: '/' }).installed).toEqual({ + pg: '8.13.1', + }); + }); + + it('adds loaded packages from node_modules, including pnpm and Bun stores, and ignores other files', () => { + const readFile = makeFs({ + '/app/package.json': { name: 'app', dependencies: {} }, + '/app/node_modules/.pnpm/debug@4.3.7/node_modules/debug/package.json': { version: '4.3.7' }, + '/app/node_modules/.bun/@scope+pkg@1.0.0/node_modules/@scope/pkg/package.json': { version: '1.0.0' }, + '/usr/lib/node_modules/pm2/package.json': { version: '5.0.0' }, + }); + + expect( + collectInstalledModules({ + readFile, + entryPath: '/app/index.js', + loadedFiles: [ + '/app/index.js', + '/app/node_modules/.pnpm/debug@4.3.7/node_modules/debug/src/index.js', + '/app/node_modules/.pnpm/debug@4.3.7/node_modules/debug/src/node.js', + '/app/node_modules/.bun/@scope+pkg@1.0.0/node_modules/@scope/pkg/index.js', + '/usr/lib/node_modules/pm2/index.js', + ], + }).installed, + ).toEqual({ debug: '4.3.7', '@scope/pkg': '1.0.0' }); + }); + + it('prefers the version that the app resolves when several versions of a package are loaded', () => { + const readFile = makeFs({ + '/app/package.json': { name: 'app' }, + '/app/node_modules/ms/package.json': { version: '2.1.3' }, + '/app/node_modules/.pnpm/ms@2.0.0/node_modules/ms/package.json': { version: '2.0.0' }, + '/app/node_modules/.pnpm/ms@2.1.3/node_modules/ms/package.json': { version: '2.1.3' }, + }); + + expect( + collectInstalledModules({ + readFile, + entryPath: '/app/index.js', + loadedFiles: [ + '/app/node_modules/.pnpm/ms@2.0.0/node_modules/ms/index.js', + '/app/node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js', + ], + }).installed, + ).toEqual({ ms: '2.1.3' }); + }); + + it('handles Windows paths', () => { + const readFile = makeFs({ + 'C:/app/package.json': { name: 'app', dependencies: { express: '^4.0.0' } }, + 'C:/app/node_modules/express/package.json': { version: '4.21.2' }, + }); + + expect(collectInstalledModules({ readFile, entryPath: 'C:\\app\\index.js' }).installed).toEqual({ + express: '4.21.2', + }); + }); + + it('returns nothing without a package.json', () => { + expect(collectInstalledModules({ readFile: () => undefined, entryPath: '/app/index.js', cwd: '/' })).toEqual({ + declared: {}, + installed: {}, + }); + }); +}); + +describe('parseDenoLockModules', () => { + it('reads version 4 and 5 lockfiles', () => { + expect( + parseDenoLockModules( + JSON.stringify({ + version: '5', + specifiers: { + 'jsr:@std/assert@^1.0.0': '1.0.13', + 'npm:express@^4.18.2': '4.21.2', + 'npm:@types/react-dom@18': '18.3.0_@types+react@18.3.1', + }, + }), + ), + ).toEqual({ '@std/assert': '1.0.13', express: '4.21.2', '@types/react-dom': '18.3.0' }); + }); + + it('reads version 3 lockfiles', () => { + expect( + parseDenoLockModules( + JSON.stringify({ + version: '3', + packages: { specifiers: { 'npm:chalk@5': 'npm:chalk@5.3.0', 'jsr:@std/path@1': 'jsr:@std/path@1.0.8' } }, + }), + ), + ).toEqual({ chalk: '5.3.0', '@std/path': '1.0.8' }); + }); + + it('returns nothing for invalid content', () => { + expect(parseDenoLockModules('not json')).toEqual({}); + expect(parseDenoLockModules('{}')).toEqual({}); + }); +}); diff --git a/packages/deno/src/index.ts b/packages/deno/src/index.ts index e76ae70e0ed1..31b4bbc66a7e 100644 --- a/packages/deno/src/index.ts +++ b/packages/deno/src/index.ts @@ -150,6 +150,7 @@ export type { DenoServeIntegrationOptions } from './integrations/deno-serve'; export { fetchIntegration } from './integrations/fetch'; export type { FetchIntegrationOptions } from '@sentry/core'; export { denoHttpIntegration } from './integrations/http'; +export { modulesIntegration } from './integrations/modules'; export type { DenoHttpIntegrationOptions } from './integrations/http'; // The orchestrion channel integrations, re-exported from `@sentry/server-utils`. diff --git a/packages/deno/src/integrations/modules.ts b/packages/deno/src/integrations/modules.ts new file mode 100644 index 000000000000..561c73d99f08 --- /dev/null +++ b/packages/deno/src/integrations/modules.ts @@ -0,0 +1,97 @@ +import { fileURLToPath } from 'node:url'; +import type { IntegrationFn } from '@sentry/core'; +import { defineIntegration, dirname, join } from '@sentry/core'; +import { _INTERNAL_collectInstalledModules, _INTERNAL_parseDenoLockModules } from '@sentry/core/server'; + +const INTEGRATION_NAME = 'Modules' as const; + +/** Never prompts: a read without permission is skipped instead. */ +function canRead(path?: string): boolean { + try { + return Deno.permissions.querySync(path ? { name: 'read', path } : { name: 'read' }).state === 'granted'; + } catch { + return false; + } +} + +function readFile(path: string): string | undefined { + if (!canRead(path)) { + return undefined; + } + try { + return Deno.readTextFileSync(path); + } catch { + return undefined; + } +} + +function getEntryPath(): string | undefined { + try { + return Deno.mainModule.startsWith('file:') ? fileURLToPath(Deno.mainModule) : undefined; + } catch { + return undefined; + } +} + +function getCwd(): string | undefined { + if (!canRead()) { + return undefined; + } + try { + return Deno.cwd(); + } catch { + return undefined; + } +} + +/** The packages in the nearest `deno.lock` above `startDir`, which covers `jsr:` and `npm:` specifiers. */ +function getDenoLockModules(startDir: string): Record { + let previous: string | undefined; + for (let dir = startDir; dir && dir !== '.' && dir !== previous; dir = dirname(dir)) { + const content = readFile(join(dir, 'deno.lock')); + if (content) { + return _INTERNAL_parseDenoLockModules(content); + } + previous = dir; + } + return {}; +} + +function collectModules(): Record { + const entryPath = getEntryPath(); + const cwd = getCwd(); + const { declared, installed } = _INTERNAL_collectInstalledModules({ readFile, entryPath, cwd }); + const startDir = entryPath ? dirname(entryPath.replace(/\\/g, '/')) : cwd?.replace(/\\/g, '/'); + + return { + ...declared, + ...(startDir ? getDenoLockModules(startDir) : {}), + ...installed, + }; +} + +const _modulesIntegration = (() => { + let modules: Record | undefined; + + return { + name: INTEGRATION_NAME, + processEvent(event) { + if (!modules) { + modules = collectModules(); + } + event.modules = { + ...event.modules, + ...modules, + }; + return event; + }, + }; +}) satisfies IntegrationFn; + +/** + * Adds the packages of the app and their versions to the event. + * + * The versions come from the nearest `deno.lock` (for `jsr:` and `npm:` specifiers) and from the `package.json` and + * `node_modules` of the app, if it has them. Files are only read with read permission, so this never prompts. + */ +export const modulesIntegration = defineIntegration(_modulesIntegration); diff --git a/packages/deno/src/sdk.ts b/packages/deno/src/sdk.ts index 997fc73523e8..ba481e948a9b 100644 --- a/packages/deno/src/sdk.ts +++ b/packages/deno/src/sdk.ts @@ -24,6 +24,7 @@ import { denoServeIntegration } from './integrations/deno-serve'; import { fetchIntegration } from './integrations/fetch'; import { denoHttpIntegration } from './integrations/http'; import { globalHandlersIntegration } from './integrations/globalhandlers'; +import { modulesIntegration } from './integrations/modules'; import { normalizePathsIntegration } from './integrations/normalizepaths'; import { setupOpenTelemetryTracer } from './opentelemetry/tracer'; import { makeFetchTransport } from './transports'; @@ -48,6 +49,7 @@ export function getDefaultIntegrationsWithoutPerformance(): Integration[] { fetchIntegration(), denoHttpIntegration(), contextLinesIntegration(), + modulesIntegration(), normalizePathsIntegration(), globalHandlersIntegration(), // server-utils integrations diff --git a/packages/deno/test/__snapshots__/mod.test.ts.snap b/packages/deno/test/__snapshots__/mod.test.ts.snap index a38158657b59..fca4d16bd8f0 100644 --- a/packages/deno/test/__snapshots__/mod.test.ts.snap +++ b/packages/deno/test/__snapshots__/mod.test.ts.snap @@ -44,6 +44,9 @@ snapshot[`captureMessage 1`] = ` event_id: "{{id}}", level: "info", message: "Some error message", + modules: { + "{{modules}}": "{{version}}", + }, platform: "javascript", sdk: { integrations: [ @@ -114,6 +117,9 @@ snapshot[`captureMessage twice 1`] = ` event_id: "{{id}}", level: "info", message: "Some error message", + modules: { + "{{modules}}": "{{version}}", + }, platform: "javascript", sdk: { integrations: [ @@ -191,6 +197,9 @@ snapshot[`captureMessage twice 2`] = ` event_id: "{{id}}", level: "info", message: "Another error message", + modules: { + "{{modules}}": "{{version}}", + }, platform: "javascript", sdk: { integrations: [ diff --git a/packages/deno/test/exports.test.ts b/packages/deno/test/exports.test.ts index 771873d5377e..baab4f229e0d 100644 --- a/packages/deno/test/exports.test.ts +++ b/packages/deno/test/exports.test.ts @@ -37,6 +37,7 @@ const EXPECTED_FUNCTION_EXPORTS = [ // ./sdk 'initWithoutDefaultIntegrations', 'getDefaultIntegrationsWithoutPerformance', + 'modulesIntegration', ]; for (const name of EXPECTED_FUNCTION_EXPORTS) { diff --git a/packages/deno/test/fixtures/modules/deno.lock b/packages/deno/test/fixtures/modules/deno.lock new file mode 100644 index 000000000000..eeedaa73a0fd --- /dev/null +++ b/packages/deno/test/fixtures/modules/deno.lock @@ -0,0 +1,7 @@ +{ + "version": "5", + "specifiers": { + "jsr:@std/assert@^1.0.0": "1.0.13", + "npm:express@^4.18.2": "4.21.2" + } +} diff --git a/packages/deno/test/fixtures/modules/main.ts b/packages/deno/test/fixtures/modules/main.ts new file mode 100644 index 000000000000..ad02f94d6bcd --- /dev/null +++ b/packages/deno/test/fixtures/modules/main.ts @@ -0,0 +1,15 @@ +import * as Sentry from '../../../build/esm/index.js'; + +Sentry.init({ + dsn: 'https://username@domain/123', + defaultIntegrations: false, + integrations: [Sentry.modulesIntegration()], + beforeSend(event) { + // oxlint-disable-next-line no-console + console.log(JSON.stringify(event.modules)); + return null; + }, +}); + +Sentry.captureException(new Error('test')); +await Sentry.flush(); diff --git a/packages/deno/test/fixtures/modules/package.json b/packages/deno/test/fixtures/modules/package.json new file mode 100644 index 000000000000..6d7664335910 --- /dev/null +++ b/packages/deno/test/fixtures/modules/package.json @@ -0,0 +1,7 @@ +{ + "name": "deno-modules-fixture", + "private": true, + "dependencies": { + "left-pad": "^1.3.0" + } +} diff --git a/packages/deno/test/modules.test.ts b/packages/deno/test/modules.test.ts new file mode 100644 index 000000000000..23352e25a7cf --- /dev/null +++ b/packages/deno/test/modules.test.ts @@ -0,0 +1,26 @@ +import { assertEquals } from 'https://deno.land/std@0.212.0/assert/assert_equals.ts'; + +const fixtureDir = new URL('./fixtures/modules/', import.meta.url); + +async function runFixture(permissions: string[]): Promise { + const { stdout, stderr, success } = await new Deno.Command(Deno.execPath(), { + // `--no-lock` keeps Deno from rewriting the fixture lockfile. + args: ['run', '--no-prompt', '--no-lock', ...permissions, new URL('main.ts', fixtureDir).pathname], + cwd: fixtureDir.pathname, + stdin: 'null', + }).output(); + assertEquals(success, true, new TextDecoder().decode(stderr)); + return JSON.parse(new TextDecoder().decode(stdout).trim()); +} + +Deno.test('modulesIntegration reads deno.lock and package.json', async () => { + assertEquals(await runFixture([`--allow-read=${fixtureDir.pathname}`]), { + 'left-pad': '^1.3.0', + '@std/assert': '1.0.13', + express: '4.21.2', + }); +}); + +Deno.test('modulesIntegration reads nothing without read permission', async () => { + assertEquals(await runFixture([]), {}); +}); diff --git a/packages/deno/test/normalize.ts b/packages/deno/test/normalize.ts index 15af97f30b7b..0ef199b4fbaa 100644 --- a/packages/deno/test/normalize.ts +++ b/packages/deno/test/normalize.ts @@ -85,6 +85,11 @@ function normalizeEvent(event: Event): Event { event.sdk.integrations = ['{{integrations}}']; } + // Installed packages depend on the checkout, so collapse them to a placeholder. + if (event.modules) { + event.modules = { '{{modules}}': '{{version}}' }; + } + if (event.contexts?.app?.app_start_time) { event.contexts.app.app_start_time = '{{time}}'; } diff --git a/packages/nextjs/src/config/util.ts b/packages/nextjs/src/config/util.ts index 1473b86bd745..764fdded307f 100644 --- a/packages/nextjs/src/config/util.ts +++ b/packages/nextjs/src/config/util.ts @@ -1,7 +1,7 @@ import { parseSemver } from '@sentry/core'; +import { _INTERNAL_collectInstalledModules } from '@sentry/core/server'; import * as fs from 'fs'; import { createRequire } from 'module'; -import * as path from 'path'; // Default page extensions per https://github.com/vercel/next.js/blob/f1dbc9260d48c7995f6c52f8fbcc65f08e627992/packages/next/server/config-shared.ts#L161 export const DEFAULT_PAGE_EXTENSIONS = ['tsx', 'ts', 'jsx', 'js']; @@ -221,22 +221,20 @@ export function detectActiveBundler(): 'turbopack' | 'webpack' { } /** - * Extract modules from project directory's package.json + * The dependencies of the project's package.json, with the exact installed version of each one that resolves from + * the project's `node_modules`, and the declared version range for the rest. */ export function getPackageModules(projectDir: string): Record { - try { - const packageJson = path.join(projectDir, 'package.json'); - const packageJsonContent = fs.readFileSync(packageJson, 'utf8'); - const packageJsonObject = JSON.parse(packageJsonContent) as { - dependencies?: Record; - devDependencies?: Record; - }; - - return { - ...packageJsonObject.dependencies, - ...packageJsonObject.devDependencies, - }; - } catch { - return {}; - } + const { declared, installed } = _INTERNAL_collectInstalledModules({ + readFile: filePath => { + try { + return fs.readFileSync(filePath, 'utf8'); + } catch { + return undefined; + } + }, + cwd: projectDir, + }); + + return { ...declared, ...installed }; } diff --git a/packages/node/src/integrations/modules.ts b/packages/node/src/integrations/modules.ts index 54842d0cd5a3..71f916a3c4ca 100644 --- a/packages/node/src/integrations/modules.ts +++ b/packages/node/src/integrations/modules.ts @@ -1,6 +1,6 @@ -import { existsSync, readFileSync, realpathSync } from 'node:fs'; -import { basename, dirname, join } from 'node:path'; +import { readFileSync } from 'node:fs'; import { GLOBAL_OBJ, type IntegrationFn } from '@sentry/core'; +import { _INTERNAL_collectInstalledModules } from '@sentry/core/server'; type ModuleInfo = Record; @@ -46,14 +46,23 @@ const _modulesIntegration = (() => { }) satisfies IntegrationFn; /** - * Add node modules / packages to the event. - * For this, multiple sources are used: - * - They can be injected at build time into the __SENTRY_SERVER_MODULES__ variable (e.g. in Next.js) - * - They are extracted from the dependencies & devDependencies in the package.json file - * - They are extracted from the require.cache (CJS only) + * Add the packages of the app and their versions to the event. + * + * The packages are the dependencies and devDependencies of the app's `package.json`, found from the entry file of the + * process. Each one gets the exact version from its installed `package.json`, which works the same for CommonJS and + * ESM, in Node.js and Bun. In CommonJS, packages in `require.cache` are added too. Versions injected at build time + * (e.g. by the Next.js SDK) are used for packages that are not installed at runtime, such as bundled ones. */ export const modulesIntegration = _modulesIntegration; +function readFile(path: string): string | undefined { + try { + return readFileSync(path, 'utf8'); + } catch { + return undefined; + } +} + function getRequireCachePaths(): string[] { try { return require.cache ? Object.keys(require.cache) : []; @@ -62,100 +71,25 @@ function getRequireCachePaths(): string[] { } } -/** Extract information about package.json modules */ function collectModules(): ModuleInfo { + const { declared, installed } = _INTERNAL_collectInstalledModules({ + readFile, + entryPath: process.argv[1], + cwd: process.cwd(), + loadedFiles: [ + /*! rollup-include-cjs-only */ + ...getRequireCachePaths(), + /*! rollup-include-cjs-only-end */ + ], + }); + return { + ...declared, ...getServerModules(), - ...getModulesFromPackageJson(), - /*! rollup-include-cjs-only */ - ...collectRequireModules(), - /*! rollup-include-cjs-only-end */ + ...installed, }; } -/** - * Whether `dir` is a node_modules folder of the main module, a folder - * `/<.pnpm or .bun>//node_modules`, where the isolated layouts of pnpm and Bun keep - * each package, or a scope folder (`@scope`) in one of these folders. - */ -function isMainModulesDir(dir: string, mainPaths: string[]): boolean { - if (basename(dir).startsWith('@')) { - return isMainModulesDir(dirname(dir), mainPaths); - } - - if (mainPaths.includes(dir)) { - return true; - } - - const storeDir = dirname(dirname(dir)); - return ( - basename(dir) === 'node_modules' && - ['.pnpm', '.bun'].includes(basename(storeDir)) && - mainPaths.includes(dirname(storeDir)) - ); -} - -/** Whether `require(name)` in the main module loads the package in `packageDir`. */ -function isResolvedFromMain(name: string, packageDir: string, mainPaths: string[]): boolean { - const resolvedDir = mainPaths.map(dir => join(dir, name)).find(dir => existsSync(dir)); - return !!resolvedDir && realpathSync(resolvedDir) === realpathSync(packageDir); -} - -/** Extract information about package.json modules from require.cache */ -function collectRequireModules(): ModuleInfo { - const mainPaths = require.main?.paths || []; - const paths = getRequireCachePaths(); - - // We start with the modules from package.json (if possible) - // These may be overwritten by more specific versions from the require.cache - const infos: ModuleInfo = {}; - const packageDirs: Record = {}; - const seen = new Set(); - - paths.forEach(path => { - let dir = path; - - /** Traverse directories upward in the search of package.json file */ - const updir = (): void | (() => void) => { - const orig = dir; - dir = dirname(orig); - - if (!dir || orig === dir || seen.has(orig)) { - return undefined; - } - if (!isMainModulesDir(dir, mainPaths)) { - return updir(); - } - - const pkgfile = join(orig, 'package.json'); - seen.add(orig); - - if (!existsSync(pkgfile)) { - return updir(); - } - - try { - const info = JSON.parse(readFileSync(pkgfile, 'utf8')) as { - name: string; - version: string; - }; - // The isolated layouts of pnpm and Bun keep every version of a package. Keep the one that the main module loads. - const previousDir = packageDirs[info.name]; - if (!previousDir || !isResolvedFromMain(info.name, previousDir, mainPaths)) { - infos[info.name] = info.version; - packageDirs[info.name] = orig; - } - } catch { - // no-empty - } - }; - - updir(); - }); - - return infos; -} - /** Fetches the list of modules and the versions loaded by the entry file for your node.js app. */ function _getModules(): ModuleInfo { if (!moduleCache) { @@ -163,28 +97,3 @@ function _getModules(): ModuleInfo { } return moduleCache; } - -interface PackageJson { - dependencies?: Record; - devDependencies?: Record; -} - -function getPackageJson(): PackageJson { - try { - const filePath = join(process.cwd(), 'package.json'); - const packageJson = JSON.parse(readFileSync(filePath, 'utf8')) as PackageJson; - - return packageJson; - } catch { - return {}; - } -} - -function getModulesFromPackageJson(): ModuleInfo { - const packageJson = getPackageJson(); - - return { - ...packageJson.dependencies, - ...packageJson.devDependencies, - }; -} From 24509365eb0f674525cca3463102791a88eb01e4 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:06:46 +0000 Subject: [PATCH 02/14] ref(core,deno): Compact installed modules resolver Move deno.lock parsing into @sentry/deno, inline minimal POSIX path helpers instead of pulling in core's path utils, and simplify duplicate-version handling. Co-Authored-By: Francesco Gringl-Novy <2411343+mydea@users.noreply.github.com> --- packages/core/src/server.ts | 5 +- packages/core/src/utils/installedModules.ts | 245 ++++++------------ .../test/lib/utils/installedModules.test.ts | 35 +-- packages/deno/src/integrations/modules.ts | 99 +++---- packages/deno/test/fixtures/modules/deno.lock | 1 + packages/deno/test/modules.test.ts | 1 + packages/nextjs/src/config/util.ts | 6 +- packages/node/src/integrations/modules.ts | 15 +- 8 files changed, 123 insertions(+), 284 deletions(-) diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index cde70d8e37d0..f58e7cb4135e 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -34,10 +34,7 @@ export { trpcMiddleware } from './trpc'; export { wrapMcpServerWithSentry } from './integrations/mcp-server'; export { isNodeEnv, loadModule } from './utils/node'; export { filenameIsInApp, node, nodeStackLineParser } from './utils/node-stack-trace'; -export { - collectInstalledModules as _INTERNAL_collectInstalledModules, - parseDenoLockModules as _INTERNAL_parseDenoLockModules, -} from './utils/installedModules'; +export { collectInstalledModules as _INTERNAL_collectInstalledModules } from './utils/installedModules'; export { vercelWaitUntil } from './utils/vercelWaitUntil'; export { getReleaseMetaTag as _INTERNAL_getReleaseMetaTag } from './utils/meta'; export { diff --git a/packages/core/src/utils/installedModules.ts b/packages/core/src/utils/installedModules.ts index 9c095627aa2a..cd6f14fed8d3 100644 --- a/packages/core/src/utils/installedModules.ts +++ b/packages/core/src/utils/installedModules.ts @@ -1,64 +1,72 @@ -import { dirname, join } from './path'; - -/** Package names mapped to versions, as sent in `event.modules`. */ -export type ModuleInfo = Record; - -/** Reads a UTF-8 file. Returns `undefined` when the file does not exist or cannot be read. */ -export type ReadFileFn = (path: string) => string | undefined; - -export interface CollectInstalledModulesOptions { - readFile: ReadFileFn; - /** Absolute path of the entry file of the app, such as `process.argv[1]`. */ - entryPath?: string; - /** Used to find the app's `package.json` when the entry file does not lead to one. */ - cwd?: string; - /** Absolute paths of the files that the runtime loaded, such as the keys of `require.cache`. */ - loadedFiles?: string[]; -} - -export interface InstalledModules { - /** The `dependencies` and `devDependencies` of the app's `package.json`, with the version ranges as declared. */ - declared: ModuleInfo; - /** Exact versions read from the installed `package.json` of each package. */ - installed: ModuleInfo; -} - +type ModuleInfo = Record; +type ReadFileFn = (path: string) => string | undefined; interface PackageJson { name?: string; version?: string; - dependencies?: Record; - devDependencies?: Record; + dependencies?: ModuleInfo; + devDependencies?: ModuleInfo; } -const NODE_MODULES_SEGMENT = '/node_modules/'; +const NODE_MODULES = '/node_modules/'; /** - * Finds the app's `package.json` and returns each dependency it declares, plus the exact version of every package - * that resolves from the app's `node_modules` folders. - * - * Packages resolve the way Node.js resolves a bare `require(name)` or `import name` from the entry file, so the - * result is the same for CommonJS and ESM apps, and for the flat (npm, Yarn, Bun) and isolated (pnpm, Bun) layouts. + * Returns the dependencies declared in the app's `package.json`, and the exact version of each declared or loaded + * package, resolved through `node_modules` the way a bare import from the entry file resolves it. */ -export function collectInstalledModules(options: CollectInstalledModulesOptions): InstalledModules { - const { readFile, loadedFiles = [] } = options; - const entryDir = options.entryPath ? dirname(toPosixPath(options.entryPath)) : undefined; - const cwd = options.cwd ? toPosixPath(options.cwd) : undefined; +export function collectInstalledModules({ + readFile, + entryPath, + cwd, + loadedFiles = [], +}: { + readFile: ReadFileFn; + entryPath?: string; + cwd?: string; + loadedFiles?: string[]; +}): { declared: ModuleInfo; installed: ModuleInfo } { + const entryDir = entryPath && dirname(toPosix(entryPath)); + const cwdDir = cwd && toPosix(cwd); + // An entry file outside cwd usually belongs to a launcher, such as the AWS Lambda runtime. + const appRoot = findAppRoot( + readFile, + entryDir && cwdDir && !isIn(entryDir, cwdDir) ? [cwdDir, entryDir] : [entryDir, cwdDir], + ); + const resolveFrom = entryDir && appRoot && isIn(entryDir, appRoot) ? entryDir : appRoot || entryDir || cwdDir; + const nodeModulesDirs = resolveFrom ? ancestors(resolveFrom).map(dir => join(dir, 'node_modules')) : []; + const resolve = (name: string): string | undefined => { + for (const dir of nodeModulesDirs) { + const pkg = readPackageJson(readFile, join(dir, name)); + if (pkg) { + return pkg.version; + } + } + return undefined; + }; - // An entry file outside the working directory usually belongs to a launcher, such as the AWS Lambda runtime. - const appRoot = findAppRoot(readFile, entryDir && cwd && !isInDir(entryDir, cwd) ? [cwd, entryDir] : [entryDir, cwd]); - // Resolve from the entry file when it lives in the app, so nested `node_modules` between the two are searched too. - const resolveFrom = entryDir && appRoot && isInDir(entryDir, appRoot) ? entryDir : appRoot || entryDir || cwd; - const nodeModulesDirs = resolveFrom ? getAncestorDirs(resolveFrom).map(dir => join(dir, 'node_modules')) : []; + const pkg = appRoot ? readPackageJson(readFile, appRoot) : undefined; + const declared: ModuleInfo = { ...pkg?.dependencies, ...pkg?.devDependencies }; + const installed: ModuleInfo = {}; - const packageJson = appRoot ? readPackageJson(readFile, appRoot) : undefined; - const declared: ModuleInfo = { - ...packageJson?.dependencies, - ...packageJson?.devDependencies, - }; + for (const file of loadedFiles) { + const path = toPosix(file); + const index = path.lastIndexOf(NODE_MODULES); + if (index === -1 || !nodeModulesDirs.some(dir => isIn(path, dir))) { + continue; + } + const base = path.slice(0, index + NODE_MODULES.length); + const [first = '', second] = path.slice(base.length).split('/'); + const name = first.startsWith('@') ? `${first}/${second}` : first; + // pnpm and Bun stores can hold several versions of a package; prefer the one the app resolves. + if (!(name in installed)) { + const version = resolve(name) || readPackageJson(readFile, base + name)?.version; + if (version) { + installed[name] = version; + } + } + } - const installed = getLoadedModules(readFile, loadedFiles, nodeModulesDirs); for (const name of Object.keys(declared)) { - const version = resolveInstalledVersion(readFile, name, nodeModulesDirs); + const version = resolve(name); if (version) { installed[name] = version; } @@ -67,144 +75,53 @@ export function collectInstalledModules(options: CollectInstalledModulesOptions) return { declared, installed }; } -/** - * Reads the exact versions of the packages in a `deno.lock` file (versions 3 to 5). - * Returns an empty object when the content is not a lockfile that this function understands. - */ -export function parseDenoLockModules(content: string): ModuleInfo { - let specifiers: unknown; - try { - const lock = JSON.parse(content) as { specifiers?: unknown; packages?: { specifiers?: unknown } }; - specifiers = lock.specifiers ?? lock.packages?.specifiers; - } catch { - return {}; - } - - const modules: ModuleInfo = {}; - if (!specifiers || typeof specifiers !== 'object') { - return modules; - } - - for (const [specifier, resolved] of Object.entries(specifiers)) { - const name = /^(?:npm|jsr):(@?[^@]+)@/.exec(specifier)?.[1]; - if (!name || typeof resolved !== 'string') { - continue; - } - // Version 3 stores the full specifier (`npm:express@4.21.2`), later versions only the version. - // npm versions can carry a peer dependency suffix (`18.3.0_react@18.3.1`). - const version = (resolved.includes(':') ? resolved.slice(resolved.lastIndexOf('@') + 1) : resolved).split('_')[0]; - if (version) { - modules[name] = version; - } - } - - return modules; -} - -/** - * The nearest folder above one of `startDirs` that has a `package.json` for an app. - * Skips start folders inside `node_modules` (such as the binary of `next start`) and `package.json` files that only - * set a field such as `"type": "module"` for a build output folder. - */ +/** Skips start dirs inside `node_modules` and `package.json` files that only set fields like `"type"`. */ function findAppRoot(readFile: ReadFileFn, startDirs: Array): string | undefined { for (const startDir of startDirs) { - if (!startDir || `${startDir}/`.includes(NODE_MODULES_SEGMENT)) { - continue; - } - for (const dir of getAncestorDirs(startDir)) { - const packageJson = readPackageJson(readFile, dir); - if (packageJson && (packageJson.name || packageJson.dependencies || packageJson.devDependencies)) { - return dir; + if (startDir && !`${startDir}/`.includes(NODE_MODULES)) { + const root = ancestors(startDir).find(dir => { + const pkg = readPackageJson(readFile, dir); + return pkg && (pkg.name || pkg.dependencies || pkg.devDependencies); + }); + if (root) { + return root; } } } return undefined; } -/** The version of the package that a bare `require(name)` loads when it searches `nodeModulesDirs`. */ -function resolveInstalledVersion(readFile: ReadFileFn, name: string, nodeModulesDirs: string[]): string | undefined { - for (const dir of nodeModulesDirs) { - const packageJson = readPackageJson(readFile, join(dir, name)); - if (packageJson) { - return typeof packageJson.version === 'string' ? packageJson.version : undefined; - } - } - return undefined; -} - -/** The packages of the loaded files that live in one of `nodeModulesDirs`, including pnpm and Bun stores there. */ -function getLoadedModules(readFile: ReadFileFn, loadedFiles: string[], nodeModulesDirs: string[]): ModuleInfo { - const versionsByName: Record = {}; - const seenPackageDirs = new Set(); - - for (const file of loadedFiles) { - const path = toPosixPath(file); - if (!nodeModulesDirs.some(dir => isInDir(path, dir))) { - continue; - } - - const packageDir = getPackageDir(path); - if (!packageDir || seenPackageDirs.has(packageDir.dir)) { - continue; - } - seenPackageDirs.add(packageDir.dir); - - const version = readPackageJson(readFile, packageDir.dir)?.version; - if (typeof version === 'string') { - versionsByName[packageDir.name] = [...(versionsByName[packageDir.name] || []), version]; - } - } - - const modules: ModuleInfo = {}; - for (const [name, versions] of Object.entries(versionsByName)) { - // pnpm and Bun stores can hold several loaded versions of one package. Prefer the one the app itself resolves. - const appVersion = versions.length > 1 ? resolveInstalledVersion(readFile, name, nodeModulesDirs) : undefined; - modules[name] = appVersion && versions.includes(appVersion) ? appVersion : (versions[0] as string); - } - return modules; -} - -/** The innermost `node_modules/` or `node_modules/@scope/` folder that contains `path`. */ -function getPackageDir(path: string): { name: string; dir: string } | undefined { - const index = path.lastIndexOf(NODE_MODULES_SEGMENT); - if (index === -1) { - return undefined; - } - const base = path.slice(0, index + NODE_MODULES_SEGMENT.length); - const [first, second] = path.slice(base.length).split('/'); - const name = first?.startsWith('@') && second ? `${first}/${second}` : first; - return name ? { name, dir: base + name } : undefined; -} - function readPackageJson(readFile: ReadFileFn, dir: string): PackageJson | undefined { - const content = readFile(join(dir, 'package.json')); - if (!content) { - return undefined; - } try { - const packageJson = JSON.parse(content) as PackageJson | null; - return packageJson && typeof packageJson === 'object' ? packageJson : undefined; + return (JSON.parse(readFile(join(dir, 'package.json')) || 'null') as PackageJson | null) || undefined; } catch { return undefined; } } -function getAncestorDirs(dir: string): string[] { +/** `dir` and its parents, up to the root. */ +function ancestors(dir: string): string[] { const dirs = [dir]; - for ( - let parent = dirname(dir); - parent && parent !== '.' && parent !== dirs[dirs.length - 1]; - parent = dirname(parent) - ) { + for (let parent = dirname(dir); parent !== dirs[dirs.length - 1]; parent = dirname(parent)) { dirs.push(parent); } return dirs; } -function isInDir(path: string, dir: string): boolean { +// Minimal POSIX helpers: all paths are converted with `toPosix` first. +function dirname(path: string): string { + const index = path.lastIndexOf('/'); + return index > 0 ? path.slice(0, index) : index === 0 ? '/' : path; +} + +function join(dir: string, name: string): string { + return dir.endsWith('/') ? dir + name : `${dir}/${name}`; +} + +function isIn(path: string, dir: string): boolean { return path === dir || path.startsWith(dir.endsWith('/') ? dir : `${dir}/`); } -function toPosixPath(path: string): string { +function toPosix(path: string): string { return path.replace(/\\/g, '/'); } diff --git a/packages/core/test/lib/utils/installedModules.test.ts b/packages/core/test/lib/utils/installedModules.test.ts index b3395c29f489..d5df83d221c6 100644 --- a/packages/core/test/lib/utils/installedModules.test.ts +++ b/packages/core/test/lib/utils/installedModules.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { collectInstalledModules, parseDenoLockModules } from '../../../src/utils/installedModules'; +import { collectInstalledModules } from '../../../src/utils/installedModules'; function makeFs(files: Record): (path: string) => string | undefined { return path => { @@ -151,36 +151,3 @@ describe('collectInstalledModules', () => { }); }); }); - -describe('parseDenoLockModules', () => { - it('reads version 4 and 5 lockfiles', () => { - expect( - parseDenoLockModules( - JSON.stringify({ - version: '5', - specifiers: { - 'jsr:@std/assert@^1.0.0': '1.0.13', - 'npm:express@^4.18.2': '4.21.2', - 'npm:@types/react-dom@18': '18.3.0_@types+react@18.3.1', - }, - }), - ), - ).toEqual({ '@std/assert': '1.0.13', express: '4.21.2', '@types/react-dom': '18.3.0' }); - }); - - it('reads version 3 lockfiles', () => { - expect( - parseDenoLockModules( - JSON.stringify({ - version: '3', - packages: { specifiers: { 'npm:chalk@5': 'npm:chalk@5.3.0', 'jsr:@std/path@1': 'jsr:@std/path@1.0.8' } }, - }), - ), - ).toEqual({ chalk: '5.3.0', '@std/path': '1.0.8' }); - }); - - it('returns nothing for invalid content', () => { - expect(parseDenoLockModules('not json')).toEqual({}); - expect(parseDenoLockModules('{}')).toEqual({}); - }); -}); diff --git a/packages/deno/src/integrations/modules.ts b/packages/deno/src/integrations/modules.ts index 561c73d99f08..25e053fefda3 100644 --- a/packages/deno/src/integrations/modules.ts +++ b/packages/deno/src/integrations/modules.ts @@ -1,97 +1,66 @@ import { fileURLToPath } from 'node:url'; import type { IntegrationFn } from '@sentry/core'; import { defineIntegration, dirname, join } from '@sentry/core'; -import { _INTERNAL_collectInstalledModules, _INTERNAL_parseDenoLockModules } from '@sentry/core/server'; +import { _INTERNAL_collectInstalledModules } from '@sentry/core/server'; -const INTEGRATION_NAME = 'Modules' as const; - -/** Never prompts: a read without permission is skipped instead. */ -function canRead(path?: string): boolean { - try { - return Deno.permissions.querySync(path ? { name: 'read', path } : { name: 'read' }).state === 'granted'; - } catch { - return false; - } -} - -function readFile(path: string): string | undefined { - if (!canRead(path)) { - return undefined; - } +/** Reads only with granted permission, so it never prompts. */ +function readFile(path?: string): string | undefined { try { - return Deno.readTextFileSync(path); - } catch { - return undefined; - } -} - -function getEntryPath(): string | undefined { - try { - return Deno.mainModule.startsWith('file:') ? fileURLToPath(Deno.mainModule) : undefined; - } catch { - return undefined; - } -} - -function getCwd(): string | undefined { - if (!canRead()) { - return undefined; - } - try { - return Deno.cwd(); + if (Deno.permissions.querySync({ name: 'read', path }).state === 'granted') { + return path ? Deno.readTextFileSync(path) : Deno.cwd(); + } } catch { - return undefined; + // not readable } + return undefined; } -/** The packages in the nearest `deno.lock` above `startDir`, which covers `jsr:` and `npm:` specifiers. */ +/** Exact versions of the `jsr:` and `npm:` specifiers in the nearest `deno.lock` (versions 3 to 5). */ function getDenoLockModules(startDir: string): Record { - let previous: string | undefined; - for (let dir = startDir; dir && dir !== '.' && dir !== previous; dir = dirname(dir)) { + const modules: Record = {}; + for (let dir = startDir, prev = ''; dir !== prev && dir !== '.'; prev = dir, dir = dirname(dir)) { const content = readFile(join(dir, 'deno.lock')); if (content) { - return _INTERNAL_parseDenoLockModules(content); + try { + const lock = JSON.parse(content) as { specifiers?: object; packages?: { specifiers?: object } }; + for (const [specifier, resolved] of Object.entries(lock.specifiers || lock.packages?.specifiers || {})) { + const name = /^(?:npm|jsr):(@?[^@]+)@/.exec(specifier)?.[1]; + // v3 stores `npm:express@4.21.2`, later versions `4.21.2`; npm versions can end in `_`. + const version = typeof resolved === 'string' && resolved.replace(/^(?:npm|jsr):@?[^@]+@/, '').split('_')[0]; + if (name && version) { + modules[name] = version; + } + } + } catch { + // invalid lockfile + } + break; } - previous = dir; } - return {}; + return modules; } function collectModules(): Record { - const entryPath = getEntryPath(); - const cwd = getCwd(); + const entryPath = Deno.mainModule.startsWith('file:') ? fileURLToPath(Deno.mainModule) : undefined; + const cwd = readFile(); const { declared, installed } = _INTERNAL_collectInstalledModules({ readFile, entryPath, cwd }); - const startDir = entryPath ? dirname(entryPath.replace(/\\/g, '/')) : cwd?.replace(/\\/g, '/'); - - return { - ...declared, - ...(startDir ? getDenoLockModules(startDir) : {}), - ...installed, - }; + const startDir = (entryPath ? dirname(entryPath.replace(/\\/g, '/')) : cwd?.replace(/\\/g, '/')) || '.'; + return { ...declared, ...getDenoLockModules(startDir), ...installed }; } const _modulesIntegration = (() => { let modules: Record | undefined; - return { - name: INTEGRATION_NAME, + name: 'Modules', processEvent(event) { - if (!modules) { - modules = collectModules(); - } - event.modules = { - ...event.modules, - ...modules, - }; + modules = modules || collectModules(); + event.modules = { ...event.modules, ...modules }; return event; }, }; }) satisfies IntegrationFn; /** - * Adds the packages of the app and their versions to the event. - * - * The versions come from the nearest `deno.lock` (for `jsr:` and `npm:` specifiers) and from the `package.json` and - * `node_modules` of the app, if it has them. Files are only read with read permission, so this never prompts. + * Adds the app's packages and versions to events, from `deno.lock` and from `package.json` and `node_modules`. */ export const modulesIntegration = defineIntegration(_modulesIntegration); diff --git a/packages/deno/test/fixtures/modules/deno.lock b/packages/deno/test/fixtures/modules/deno.lock index eeedaa73a0fd..54aabb729fe2 100644 --- a/packages/deno/test/fixtures/modules/deno.lock +++ b/packages/deno/test/fixtures/modules/deno.lock @@ -2,6 +2,7 @@ "version": "5", "specifiers": { "jsr:@std/assert@^1.0.0": "1.0.13", + "npm:@types/react-dom@18": "18.3.0_@types+react@18.3.1", "npm:express@^4.18.2": "4.21.2" } } diff --git a/packages/deno/test/modules.test.ts b/packages/deno/test/modules.test.ts index 23352e25a7cf..2a60d3b880fd 100644 --- a/packages/deno/test/modules.test.ts +++ b/packages/deno/test/modules.test.ts @@ -17,6 +17,7 @@ Deno.test('modulesIntegration reads deno.lock and package.json', async () => { assertEquals(await runFixture([`--allow-read=${fixtureDir.pathname}`]), { 'left-pad': '^1.3.0', '@std/assert': '1.0.13', + '@types/react-dom': '18.3.0', express: '4.21.2', }); }); diff --git a/packages/nextjs/src/config/util.ts b/packages/nextjs/src/config/util.ts index 764fdded307f..ff84873b14f2 100644 --- a/packages/nextjs/src/config/util.ts +++ b/packages/nextjs/src/config/util.ts @@ -220,10 +220,7 @@ export function detectActiveBundler(): 'turbopack' | 'webpack' { } } -/** - * The dependencies of the project's package.json, with the exact installed version of each one that resolves from - * the project's `node_modules`, and the declared version range for the rest. - */ +/** The project's dependencies, with exact installed versions where they resolve and declared ranges otherwise. */ export function getPackageModules(projectDir: string): Record { const { declared, installed } = _INTERNAL_collectInstalledModules({ readFile: filePath => { @@ -235,6 +232,5 @@ export function getPackageModules(projectDir: string): Record { }, cwd: projectDir, }); - return { ...declared, ...installed }; } diff --git a/packages/node/src/integrations/modules.ts b/packages/node/src/integrations/modules.ts index 71f916a3c4ca..204bbafefb01 100644 --- a/packages/node/src/integrations/modules.ts +++ b/packages/node/src/integrations/modules.ts @@ -46,12 +46,8 @@ const _modulesIntegration = (() => { }) satisfies IntegrationFn; /** - * Add the packages of the app and their versions to the event. - * - * The packages are the dependencies and devDependencies of the app's `package.json`, found from the entry file of the - * process. Each one gets the exact version from its installed `package.json`, which works the same for CommonJS and - * ESM, in Node.js and Bun. In CommonJS, packages in `require.cache` are added too. Versions injected at build time - * (e.g. by the Next.js SDK) are used for packages that are not installed at runtime, such as bundled ones. + * Adds the app's packages to the event, with exact installed versions where they resolve from the entry file. + * Declared ranges and build-time injected versions fill in packages that are not installed, such as bundled ones. */ export const modulesIntegration = _modulesIntegration; @@ -82,12 +78,7 @@ function collectModules(): ModuleInfo { /*! rollup-include-cjs-only-end */ ], }); - - return { - ...declared, - ...getServerModules(), - ...installed, - }; + return { ...declared, ...getServerModules(), ...installed }; } /** Fetches the list of modules and the versions loaded by the entry file for your node.js app. */ From 29961e3c4abae09ed2e9aa36f7ada31771f5bb7d Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:16:17 +0000 Subject: [PATCH 03/14] fix(node): Don't throw on missing files when collecting modules Collecting versions threw an ENOENT for every missing package.json. With localVariables capturing caught exceptions, each throw pauses the debugger and trips its rate limit. Check existence first, and only resolve loaded packages through node_modules when several versions of one are loaded. --- packages/core/src/utils/installedModules.ts | 15 +++++++++------ packages/node/src/integrations/modules.ts | 6 ++++-- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/packages/core/src/utils/installedModules.ts b/packages/core/src/utils/installedModules.ts index cd6f14fed8d3..6799944ee15c 100644 --- a/packages/core/src/utils/installedModules.ts +++ b/packages/core/src/utils/installedModules.ts @@ -47,6 +47,7 @@ export function collectInstalledModules({ const declared: ModuleInfo = { ...pkg?.dependencies, ...pkg?.devDependencies }; const installed: ModuleInfo = {}; + const seen = new Set(); for (const file of loadedFiles) { const path = toPosix(file); const index = path.lastIndexOf(NODE_MODULES); @@ -56,12 +57,14 @@ export function collectInstalledModules({ const base = path.slice(0, index + NODE_MODULES.length); const [first = '', second] = path.slice(base.length).split('/'); const name = first.startsWith('@') ? `${first}/${second}` : first; - // pnpm and Bun stores can hold several versions of a package; prefer the one the app resolves. - if (!(name in installed)) { - const version = resolve(name) || readPackageJson(readFile, base + name)?.version; - if (version) { - installed[name] = version; - } + if (seen.has(base + name)) { + continue; + } + seen.add(base + name); + const version = readPackageJson(readFile, base + name)?.version; + if (version && installed[name] !== version) { + // pnpm and Bun stores can hold several versions of a package; prefer the one the app resolves. + installed[name] = (name in installed && resolve(name)) || installed[name] || version; } } diff --git a/packages/node/src/integrations/modules.ts b/packages/node/src/integrations/modules.ts index 204bbafefb01..6ae9a1c4aa2d 100644 --- a/packages/node/src/integrations/modules.ts +++ b/packages/node/src/integrations/modules.ts @@ -1,4 +1,4 @@ -import { readFileSync } from 'node:fs'; +import { existsSync, readFileSync } from 'node:fs'; import { GLOBAL_OBJ, type IntegrationFn } from '@sentry/core'; import { _INTERNAL_collectInstalledModules } from '@sentry/core/server'; @@ -53,7 +53,9 @@ export const modulesIntegration = _modulesIntegration; function readFile(path: string): string | undefined { try { - return readFileSync(path, 'utf8'); + // Throwing on the many missing files would pause the debugger each time when localVariables captures caught + // exceptions, which trips its rate limit. + return existsSync(path) ? readFileSync(path, 'utf8') : undefined; } catch { return undefined; } From 363dc3f6c39a659428655dcb9ee9399553cc4875 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:25:06 +0000 Subject: [PATCH 04/14] ref(core): Export collectInstalledModules without _INTERNAL_ prefix --- packages/core/src/server.ts | 2 +- packages/deno/src/integrations/modules.ts | 4 ++-- packages/nextjs/src/config/util.ts | 4 ++-- packages/node/src/integrations/modules.ts | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index f58e7cb4135e..bd856546efca 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -34,7 +34,7 @@ export { trpcMiddleware } from './trpc'; export { wrapMcpServerWithSentry } from './integrations/mcp-server'; export { isNodeEnv, loadModule } from './utils/node'; export { filenameIsInApp, node, nodeStackLineParser } from './utils/node-stack-trace'; -export { collectInstalledModules as _INTERNAL_collectInstalledModules } from './utils/installedModules'; +export { collectInstalledModules } from './utils/installedModules'; export { vercelWaitUntil } from './utils/vercelWaitUntil'; export { getReleaseMetaTag as _INTERNAL_getReleaseMetaTag } from './utils/meta'; export { diff --git a/packages/deno/src/integrations/modules.ts b/packages/deno/src/integrations/modules.ts index 25e053fefda3..47f14f8beab3 100644 --- a/packages/deno/src/integrations/modules.ts +++ b/packages/deno/src/integrations/modules.ts @@ -1,7 +1,7 @@ import { fileURLToPath } from 'node:url'; import type { IntegrationFn } from '@sentry/core'; import { defineIntegration, dirname, join } from '@sentry/core'; -import { _INTERNAL_collectInstalledModules } from '@sentry/core/server'; +import { collectInstalledModules } from '@sentry/core/server'; /** Reads only with granted permission, so it never prompts. */ function readFile(path?: string): string | undefined { @@ -43,7 +43,7 @@ function getDenoLockModules(startDir: string): Record { function collectModules(): Record { const entryPath = Deno.mainModule.startsWith('file:') ? fileURLToPath(Deno.mainModule) : undefined; const cwd = readFile(); - const { declared, installed } = _INTERNAL_collectInstalledModules({ readFile, entryPath, cwd }); + const { declared, installed } = collectInstalledModules({ readFile, entryPath, cwd }); const startDir = (entryPath ? dirname(entryPath.replace(/\\/g, '/')) : cwd?.replace(/\\/g, '/')) || '.'; return { ...declared, ...getDenoLockModules(startDir), ...installed }; } diff --git a/packages/nextjs/src/config/util.ts b/packages/nextjs/src/config/util.ts index ff84873b14f2..849e3b9be84f 100644 --- a/packages/nextjs/src/config/util.ts +++ b/packages/nextjs/src/config/util.ts @@ -1,5 +1,5 @@ import { parseSemver } from '@sentry/core'; -import { _INTERNAL_collectInstalledModules } from '@sentry/core/server'; +import { collectInstalledModules } from '@sentry/core/server'; import * as fs from 'fs'; import { createRequire } from 'module'; @@ -222,7 +222,7 @@ export function detectActiveBundler(): 'turbopack' | 'webpack' { /** The project's dependencies, with exact installed versions where they resolve and declared ranges otherwise. */ export function getPackageModules(projectDir: string): Record { - const { declared, installed } = _INTERNAL_collectInstalledModules({ + const { declared, installed } = collectInstalledModules({ readFile: filePath => { try { return fs.readFileSync(filePath, 'utf8'); diff --git a/packages/node/src/integrations/modules.ts b/packages/node/src/integrations/modules.ts index 6ae9a1c4aa2d..a5dfb6e1b88e 100644 --- a/packages/node/src/integrations/modules.ts +++ b/packages/node/src/integrations/modules.ts @@ -1,6 +1,6 @@ import { existsSync, readFileSync } from 'node:fs'; import { GLOBAL_OBJ, type IntegrationFn } from '@sentry/core'; -import { _INTERNAL_collectInstalledModules } from '@sentry/core/server'; +import { collectInstalledModules } from '@sentry/core/server'; type ModuleInfo = Record; @@ -70,7 +70,7 @@ function getRequireCachePaths(): string[] { } function collectModules(): ModuleInfo { - const { declared, installed } = _INTERNAL_collectInstalledModules({ + const { declared, installed } = collectInstalledModules({ readFile, entryPath: process.argv[1], cwd: process.cwd(), From 05afe19f0fcc747b11112799fe2c87c99965b8df Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:40:33 +0000 Subject: [PATCH 05/14] ref(node): Skip runtime module resolution when versions were injected at build time Also document what loadedFiles does in collectInstalledModules. --- packages/core/src/utils/installedModules.ts | 5 +++++ packages/node/src/integrations/modules.ts | 11 ++++++++--- packages/node/test/integrations/modules.test.ts | 8 +++----- 3 files changed, 16 insertions(+), 8 deletions(-) diff --git a/packages/core/src/utils/installedModules.ts b/packages/core/src/utils/installedModules.ts index 6799944ee15c..78af5711f445 100644 --- a/packages/core/src/utils/installedModules.ts +++ b/packages/core/src/utils/installedModules.ts @@ -22,6 +22,11 @@ export function collectInstalledModules({ readFile: ReadFileFn; entryPath?: string; cwd?: string; + /** + * Paths of files the process has already loaded, such as the keys of `require.cache`. Packages these files belong + * to are added to `installed` too, which covers transitive dependencies that are not in `package.json`. ESM has no + * equivalent of `require.cache`, so only CommonJS passes this; without it, only declared dependencies are resolved. + */ loadedFiles?: string[]; }): { declared: ModuleInfo; installed: ModuleInfo } { const entryDir = entryPath && dirname(toPosix(entryPath)); diff --git a/packages/node/src/integrations/modules.ts b/packages/node/src/integrations/modules.ts index a5dfb6e1b88e..d85418de2e06 100644 --- a/packages/node/src/integrations/modules.ts +++ b/packages/node/src/integrations/modules.ts @@ -46,8 +46,8 @@ const _modulesIntegration = (() => { }) satisfies IntegrationFn; /** - * Adds the app's packages to the event, with exact installed versions where they resolve from the entry file. - * Declared ranges and build-time injected versions fill in packages that are not installed, such as bundled ones. + * Adds the app's packages to the event. Versions injected at build time (e.g. by the Next.js SDK) are used as is. + * Otherwise, it uses exact installed versions where they resolve from the entry file, and declared ranges for the rest. */ export const modulesIntegration = _modulesIntegration; @@ -70,6 +70,11 @@ function getRequireCachePaths(): string[] { } function collectModules(): ModuleInfo { + const serverModules = getServerModules(); + // The build already resolved exact versions, so skip the file reads at runtime. + if (Object.keys(serverModules).length) { + return serverModules; + } const { declared, installed } = collectInstalledModules({ readFile, entryPath: process.argv[1], @@ -80,7 +85,7 @@ function collectModules(): ModuleInfo { /*! rollup-include-cjs-only-end */ ], }); - return { ...declared, ...getServerModules(), ...installed }; + return { ...declared, ...installed }; } /** Fetches the list of modules and the versions loaded by the entry file for your node.js app. */ diff --git a/packages/node/test/integrations/modules.test.ts b/packages/node/test/integrations/modules.test.ts index 31ee5671e40a..8fc3ed484c41 100644 --- a/packages/node/test/integrations/modules.test.ts +++ b/packages/node/test/integrations/modules.test.ts @@ -20,17 +20,15 @@ describe('modulesIntegration', () => { // The runtime injection happens only now — after the module is already evaluated. (GLOBAL_OBJ as GlobalWithModules).__SENTRY_SERVER_MODULES__ = { '@sentry/turbopack-injected': '1.2.3' }; - const modules = modulesIntegration().getModules?.() ?? {}; - expect(modules['@sentry/turbopack-injected']).toBe('1.2.3'); + expect(modulesIntegration().getModules?.()).toEqual({ '@sentry/turbopack-injected': '1.2.3' }); }); - it('reads modules already present before evaluation (webpack DefinePlugin / pre-set global)', async () => { + it('uses only modules already present before evaluation (webpack DefinePlugin / pre-set global)', async () => { (GLOBAL_OBJ as GlobalWithModules).__SENTRY_SERVER_MODULES__ = { '@sentry/prebuilt-injected': '4.5.6' }; vi.resetModules(); const { modulesIntegration } = await import('../../src/integrations/modules'); - const modules = modulesIntegration().getModules?.() ?? {}; - expect(modules['@sentry/prebuilt-injected']).toBe('4.5.6'); + expect(modulesIntegration().getModules?.()).toEqual({ '@sentry/prebuilt-injected': '4.5.6' }); }); }); From b16432e38c164c06d15c32df466abb5f8c5d8403 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:43:39 +0000 Subject: [PATCH 06/14] ref(core): Return one merged module map from collectInstalledModules --- packages/core/src/utils/installedModules.ts | 10 +++--- .../test/lib/utils/installedModules.test.ts | 31 +++++++------------ packages/deno/src/integrations/modules.ts | 5 +-- packages/nextjs/src/config/util.ts | 3 +- packages/node/src/integrations/modules.ts | 3 +- 5 files changed, 22 insertions(+), 30 deletions(-) diff --git a/packages/core/src/utils/installedModules.ts b/packages/core/src/utils/installedModules.ts index 78af5711f445..bd9aaf50c5ff 100644 --- a/packages/core/src/utils/installedModules.ts +++ b/packages/core/src/utils/installedModules.ts @@ -10,8 +10,8 @@ interface PackageJson { const NODE_MODULES = '/node_modules/'; /** - * Returns the dependencies declared in the app's `package.json`, and the exact version of each declared or loaded - * package, resolved through `node_modules` the way a bare import from the entry file resolves it. + * Returns the app's packages: the dependencies declared in its `package.json`, plus loaded packages. Each gets the exact + * version that a bare import from the entry file resolves through `node_modules`, or its declared range otherwise. */ export function collectInstalledModules({ readFile, @@ -24,11 +24,11 @@ export function collectInstalledModules({ cwd?: string; /** * Paths of files the process has already loaded, such as the keys of `require.cache`. Packages these files belong - * to are added to `installed` too, which covers transitive dependencies that are not in `package.json`. ESM has no + * to are added too, which covers transitive dependencies that are not in `package.json`. ESM has no * equivalent of `require.cache`, so only CommonJS passes this; without it, only declared dependencies are resolved. */ loadedFiles?: string[]; -}): { declared: ModuleInfo; installed: ModuleInfo } { +}): ModuleInfo { const entryDir = entryPath && dirname(toPosix(entryPath)); const cwdDir = cwd && toPosix(cwd); // An entry file outside cwd usually belongs to a launcher, such as the AWS Lambda runtime. @@ -80,7 +80,7 @@ export function collectInstalledModules({ } } - return { declared, installed }; + return { ...declared, ...installed }; } /** Skips start dirs inside `node_modules` and `package.json` files that only set fields like `"type"`. */ diff --git a/packages/core/test/lib/utils/installedModules.test.ts b/packages/core/test/lib/utils/installedModules.test.ts index d5df83d221c6..2f3da1f31adc 100644 --- a/packages/core/test/lib/utils/installedModules.test.ts +++ b/packages/core/test/lib/utils/installedModules.test.ts @@ -24,8 +24,9 @@ describe('collectInstalledModules', () => { }); expect(collectInstalledModules({ readFile, entryPath: '/app/dist/index.js' })).toEqual({ - declared: { express: '^4.0.0', '@scope/lib': '^2.0.0', vitest: '^3.0.0' }, - installed: { express: '4.21.2', '@scope/lib': '2.3.4' }, + express: '4.21.2', + '@scope/lib': '2.3.4', + vitest: '^3.0.0', }); }); @@ -37,8 +38,7 @@ describe('collectInstalledModules', () => { }); expect(collectInstalledModules({ readFile, entryPath: '/repo/apps/api/dist/server.mjs', cwd: '/repo' })).toEqual({ - declared: { hono: '^4.0.0' }, - installed: { hono: '4.6.0' }, + hono: '4.6.0', }); }); @@ -49,7 +49,7 @@ describe('collectInstalledModules', () => { '/app/node_modules/koa/package.json': { version: '2.15.3' }, }); - expect(collectInstalledModules({ readFile, entryPath: '/app/dist/index.js' }).installed).toEqual({ koa: '2.15.3' }); + expect(collectInstalledModules({ readFile, entryPath: '/app/dist/index.js' })).toEqual({ koa: '2.15.3' }); }); it('uses cwd when the entry file is inside node_modules', () => { @@ -60,10 +60,7 @@ describe('collectInstalledModules', () => { expect( collectInstalledModules({ readFile, entryPath: '/app/node_modules/next/dist/bin/next', cwd: '/app' }), - ).toEqual({ - declared: { next: '^15.0.0' }, - installed: { next: '15.1.0' }, - }); + ).toEqual({ next: '15.1.0' }); }); it('prefers cwd when the entry file is outside of it', () => { @@ -74,8 +71,7 @@ describe('collectInstalledModules', () => { }); expect(collectInstalledModules({ readFile, entryPath: '/var/runtime/index.mjs', cwd: '/var/task' })).toEqual({ - declared: { pg: '^8.0.0' }, - installed: { pg: '8.13.1' }, + pg: '8.13.1', }); }); @@ -85,7 +81,7 @@ describe('collectInstalledModules', () => { '/srv/app/node_modules/pg/package.json': { version: '8.13.1' }, }); - expect(collectInstalledModules({ readFile, entryPath: '/srv/app/index.js', cwd: '/' }).installed).toEqual({ + expect(collectInstalledModules({ readFile, entryPath: '/srv/app/index.js', cwd: '/' })).toEqual({ pg: '8.13.1', }); }); @@ -109,7 +105,7 @@ describe('collectInstalledModules', () => { '/app/node_modules/.bun/@scope+pkg@1.0.0/node_modules/@scope/pkg/index.js', '/usr/lib/node_modules/pm2/index.js', ], - }).installed, + }), ).toEqual({ debug: '4.3.7', '@scope/pkg': '1.0.0' }); }); @@ -129,7 +125,7 @@ describe('collectInstalledModules', () => { '/app/node_modules/.pnpm/ms@2.0.0/node_modules/ms/index.js', '/app/node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js', ], - }).installed, + }), ).toEqual({ ms: '2.1.3' }); }); @@ -139,15 +135,12 @@ describe('collectInstalledModules', () => { 'C:/app/node_modules/express/package.json': { version: '4.21.2' }, }); - expect(collectInstalledModules({ readFile, entryPath: 'C:\\app\\index.js' }).installed).toEqual({ + expect(collectInstalledModules({ readFile, entryPath: 'C:\\app\\index.js' })).toEqual({ express: '4.21.2', }); }); it('returns nothing without a package.json', () => { - expect(collectInstalledModules({ readFile: () => undefined, entryPath: '/app/index.js', cwd: '/' })).toEqual({ - declared: {}, - installed: {}, - }); + expect(collectInstalledModules({ readFile: () => undefined, entryPath: '/app/index.js', cwd: '/' })).toEqual({}); }); }); diff --git a/packages/deno/src/integrations/modules.ts b/packages/deno/src/integrations/modules.ts index 47f14f8beab3..d06db4359ab6 100644 --- a/packages/deno/src/integrations/modules.ts +++ b/packages/deno/src/integrations/modules.ts @@ -43,9 +43,10 @@ function getDenoLockModules(startDir: string): Record { function collectModules(): Record { const entryPath = Deno.mainModule.startsWith('file:') ? fileURLToPath(Deno.mainModule) : undefined; const cwd = readFile(); - const { declared, installed } = collectInstalledModules({ readFile, entryPath, cwd }); + const modules = collectInstalledModules({ readFile, entryPath, cwd }); const startDir = (entryPath ? dirname(entryPath.replace(/\\/g, '/')) : cwd?.replace(/\\/g, '/')) || '.'; - return { ...declared, ...getDenoLockModules(startDir), ...installed }; + // Without `node_modules`, `modules` only has declared ranges, so the exact versions from `deno.lock` win. + return { ...modules, ...getDenoLockModules(startDir) }; } const _modulesIntegration = (() => { diff --git a/packages/nextjs/src/config/util.ts b/packages/nextjs/src/config/util.ts index 849e3b9be84f..1dd20a8727e7 100644 --- a/packages/nextjs/src/config/util.ts +++ b/packages/nextjs/src/config/util.ts @@ -222,7 +222,7 @@ export function detectActiveBundler(): 'turbopack' | 'webpack' { /** The project's dependencies, with exact installed versions where they resolve and declared ranges otherwise. */ export function getPackageModules(projectDir: string): Record { - const { declared, installed } = collectInstalledModules({ + return collectInstalledModules({ readFile: filePath => { try { return fs.readFileSync(filePath, 'utf8'); @@ -232,5 +232,4 @@ export function getPackageModules(projectDir: string): Record { }, cwd: projectDir, }); - return { ...declared, ...installed }; } diff --git a/packages/node/src/integrations/modules.ts b/packages/node/src/integrations/modules.ts index d85418de2e06..cc1f6adf3029 100644 --- a/packages/node/src/integrations/modules.ts +++ b/packages/node/src/integrations/modules.ts @@ -75,7 +75,7 @@ function collectModules(): ModuleInfo { if (Object.keys(serverModules).length) { return serverModules; } - const { declared, installed } = collectInstalledModules({ + return collectInstalledModules({ readFile, entryPath: process.argv[1], cwd: process.cwd(), @@ -85,7 +85,6 @@ function collectModules(): ModuleInfo { /*! rollup-include-cjs-only-end */ ], }); - return { ...declared, ...installed }; } /** Fetches the list of modules and the versions loaded by the entry file for your node.js app. */ From d4c2461b0d65bc5e583ec3e9da7701de590e371f Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:45:50 +0000 Subject: [PATCH 07/14] ref(deno): Move Deno modulesIntegration to a separate PR Co-Authored-By: Francesco Gringl-Novy <2411343+mydea@users.noreply.github.com> --- packages/deno/src/index.ts | 1 - packages/deno/src/integrations/modules.ts | 67 ------------------- packages/deno/src/sdk.ts | 2 - .../deno/test/__snapshots__/mod.test.ts.snap | 9 --- packages/deno/test/exports.test.ts | 1 - packages/deno/test/fixtures/modules/deno.lock | 8 --- packages/deno/test/fixtures/modules/main.ts | 15 ----- .../deno/test/fixtures/modules/package.json | 7 -- packages/deno/test/modules.test.ts | 27 -------- packages/deno/test/normalize.ts | 5 -- 10 files changed, 142 deletions(-) delete mode 100644 packages/deno/src/integrations/modules.ts delete mode 100644 packages/deno/test/fixtures/modules/deno.lock delete mode 100644 packages/deno/test/fixtures/modules/main.ts delete mode 100644 packages/deno/test/fixtures/modules/package.json delete mode 100644 packages/deno/test/modules.test.ts diff --git a/packages/deno/src/index.ts b/packages/deno/src/index.ts index 31b4bbc66a7e..e76ae70e0ed1 100644 --- a/packages/deno/src/index.ts +++ b/packages/deno/src/index.ts @@ -150,7 +150,6 @@ export type { DenoServeIntegrationOptions } from './integrations/deno-serve'; export { fetchIntegration } from './integrations/fetch'; export type { FetchIntegrationOptions } from '@sentry/core'; export { denoHttpIntegration } from './integrations/http'; -export { modulesIntegration } from './integrations/modules'; export type { DenoHttpIntegrationOptions } from './integrations/http'; // The orchestrion channel integrations, re-exported from `@sentry/server-utils`. diff --git a/packages/deno/src/integrations/modules.ts b/packages/deno/src/integrations/modules.ts deleted file mode 100644 index d06db4359ab6..000000000000 --- a/packages/deno/src/integrations/modules.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { fileURLToPath } from 'node:url'; -import type { IntegrationFn } from '@sentry/core'; -import { defineIntegration, dirname, join } from '@sentry/core'; -import { collectInstalledModules } from '@sentry/core/server'; - -/** Reads only with granted permission, so it never prompts. */ -function readFile(path?: string): string | undefined { - try { - if (Deno.permissions.querySync({ name: 'read', path }).state === 'granted') { - return path ? Deno.readTextFileSync(path) : Deno.cwd(); - } - } catch { - // not readable - } - return undefined; -} - -/** Exact versions of the `jsr:` and `npm:` specifiers in the nearest `deno.lock` (versions 3 to 5). */ -function getDenoLockModules(startDir: string): Record { - const modules: Record = {}; - for (let dir = startDir, prev = ''; dir !== prev && dir !== '.'; prev = dir, dir = dirname(dir)) { - const content = readFile(join(dir, 'deno.lock')); - if (content) { - try { - const lock = JSON.parse(content) as { specifiers?: object; packages?: { specifiers?: object } }; - for (const [specifier, resolved] of Object.entries(lock.specifiers || lock.packages?.specifiers || {})) { - const name = /^(?:npm|jsr):(@?[^@]+)@/.exec(specifier)?.[1]; - // v3 stores `npm:express@4.21.2`, later versions `4.21.2`; npm versions can end in `_`. - const version = typeof resolved === 'string' && resolved.replace(/^(?:npm|jsr):@?[^@]+@/, '').split('_')[0]; - if (name && version) { - modules[name] = version; - } - } - } catch { - // invalid lockfile - } - break; - } - } - return modules; -} - -function collectModules(): Record { - const entryPath = Deno.mainModule.startsWith('file:') ? fileURLToPath(Deno.mainModule) : undefined; - const cwd = readFile(); - const modules = collectInstalledModules({ readFile, entryPath, cwd }); - const startDir = (entryPath ? dirname(entryPath.replace(/\\/g, '/')) : cwd?.replace(/\\/g, '/')) || '.'; - // Without `node_modules`, `modules` only has declared ranges, so the exact versions from `deno.lock` win. - return { ...modules, ...getDenoLockModules(startDir) }; -} - -const _modulesIntegration = (() => { - let modules: Record | undefined; - return { - name: 'Modules', - processEvent(event) { - modules = modules || collectModules(); - event.modules = { ...event.modules, ...modules }; - return event; - }, - }; -}) satisfies IntegrationFn; - -/** - * Adds the app's packages and versions to events, from `deno.lock` and from `package.json` and `node_modules`. - */ -export const modulesIntegration = defineIntegration(_modulesIntegration); diff --git a/packages/deno/src/sdk.ts b/packages/deno/src/sdk.ts index ba481e948a9b..997fc73523e8 100644 --- a/packages/deno/src/sdk.ts +++ b/packages/deno/src/sdk.ts @@ -24,7 +24,6 @@ import { denoServeIntegration } from './integrations/deno-serve'; import { fetchIntegration } from './integrations/fetch'; import { denoHttpIntegration } from './integrations/http'; import { globalHandlersIntegration } from './integrations/globalhandlers'; -import { modulesIntegration } from './integrations/modules'; import { normalizePathsIntegration } from './integrations/normalizepaths'; import { setupOpenTelemetryTracer } from './opentelemetry/tracer'; import { makeFetchTransport } from './transports'; @@ -49,7 +48,6 @@ export function getDefaultIntegrationsWithoutPerformance(): Integration[] { fetchIntegration(), denoHttpIntegration(), contextLinesIntegration(), - modulesIntegration(), normalizePathsIntegration(), globalHandlersIntegration(), // server-utils integrations diff --git a/packages/deno/test/__snapshots__/mod.test.ts.snap b/packages/deno/test/__snapshots__/mod.test.ts.snap index fca4d16bd8f0..a38158657b59 100644 --- a/packages/deno/test/__snapshots__/mod.test.ts.snap +++ b/packages/deno/test/__snapshots__/mod.test.ts.snap @@ -44,9 +44,6 @@ snapshot[`captureMessage 1`] = ` event_id: "{{id}}", level: "info", message: "Some error message", - modules: { - "{{modules}}": "{{version}}", - }, platform: "javascript", sdk: { integrations: [ @@ -117,9 +114,6 @@ snapshot[`captureMessage twice 1`] = ` event_id: "{{id}}", level: "info", message: "Some error message", - modules: { - "{{modules}}": "{{version}}", - }, platform: "javascript", sdk: { integrations: [ @@ -197,9 +191,6 @@ snapshot[`captureMessage twice 2`] = ` event_id: "{{id}}", level: "info", message: "Another error message", - modules: { - "{{modules}}": "{{version}}", - }, platform: "javascript", sdk: { integrations: [ diff --git a/packages/deno/test/exports.test.ts b/packages/deno/test/exports.test.ts index baab4f229e0d..771873d5377e 100644 --- a/packages/deno/test/exports.test.ts +++ b/packages/deno/test/exports.test.ts @@ -37,7 +37,6 @@ const EXPECTED_FUNCTION_EXPORTS = [ // ./sdk 'initWithoutDefaultIntegrations', 'getDefaultIntegrationsWithoutPerformance', - 'modulesIntegration', ]; for (const name of EXPECTED_FUNCTION_EXPORTS) { diff --git a/packages/deno/test/fixtures/modules/deno.lock b/packages/deno/test/fixtures/modules/deno.lock deleted file mode 100644 index 54aabb729fe2..000000000000 --- a/packages/deno/test/fixtures/modules/deno.lock +++ /dev/null @@ -1,8 +0,0 @@ -{ - "version": "5", - "specifiers": { - "jsr:@std/assert@^1.0.0": "1.0.13", - "npm:@types/react-dom@18": "18.3.0_@types+react@18.3.1", - "npm:express@^4.18.2": "4.21.2" - } -} diff --git a/packages/deno/test/fixtures/modules/main.ts b/packages/deno/test/fixtures/modules/main.ts deleted file mode 100644 index ad02f94d6bcd..000000000000 --- a/packages/deno/test/fixtures/modules/main.ts +++ /dev/null @@ -1,15 +0,0 @@ -import * as Sentry from '../../../build/esm/index.js'; - -Sentry.init({ - dsn: 'https://username@domain/123', - defaultIntegrations: false, - integrations: [Sentry.modulesIntegration()], - beforeSend(event) { - // oxlint-disable-next-line no-console - console.log(JSON.stringify(event.modules)); - return null; - }, -}); - -Sentry.captureException(new Error('test')); -await Sentry.flush(); diff --git a/packages/deno/test/fixtures/modules/package.json b/packages/deno/test/fixtures/modules/package.json deleted file mode 100644 index 6d7664335910..000000000000 --- a/packages/deno/test/fixtures/modules/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "deno-modules-fixture", - "private": true, - "dependencies": { - "left-pad": "^1.3.0" - } -} diff --git a/packages/deno/test/modules.test.ts b/packages/deno/test/modules.test.ts deleted file mode 100644 index 2a60d3b880fd..000000000000 --- a/packages/deno/test/modules.test.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { assertEquals } from 'https://deno.land/std@0.212.0/assert/assert_equals.ts'; - -const fixtureDir = new URL('./fixtures/modules/', import.meta.url); - -async function runFixture(permissions: string[]): Promise { - const { stdout, stderr, success } = await new Deno.Command(Deno.execPath(), { - // `--no-lock` keeps Deno from rewriting the fixture lockfile. - args: ['run', '--no-prompt', '--no-lock', ...permissions, new URL('main.ts', fixtureDir).pathname], - cwd: fixtureDir.pathname, - stdin: 'null', - }).output(); - assertEquals(success, true, new TextDecoder().decode(stderr)); - return JSON.parse(new TextDecoder().decode(stdout).trim()); -} - -Deno.test('modulesIntegration reads deno.lock and package.json', async () => { - assertEquals(await runFixture([`--allow-read=${fixtureDir.pathname}`]), { - 'left-pad': '^1.3.0', - '@std/assert': '1.0.13', - '@types/react-dom': '18.3.0', - express: '4.21.2', - }); -}); - -Deno.test('modulesIntegration reads nothing without read permission', async () => { - assertEquals(await runFixture([]), {}); -}); diff --git a/packages/deno/test/normalize.ts b/packages/deno/test/normalize.ts index 0ef199b4fbaa..15af97f30b7b 100644 --- a/packages/deno/test/normalize.ts +++ b/packages/deno/test/normalize.ts @@ -85,11 +85,6 @@ function normalizeEvent(event: Event): Event { event.sdk.integrations = ['{{integrations}}']; } - // Installed packages depend on the checkout, so collapse them to a placeholder. - if (event.modules) { - event.modules = { '{{modules}}': '{{version}}' }; - } - if (event.contexts?.app?.app_start_time) { event.contexts.app.app_start_time = '{{time}}'; } From baaf81ea512f05eae33f1e9a8762160ffc8f4517 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:52:38 +0000 Subject: [PATCH 08/14] feat(node): Report transitive CommonJS packages in ESM apps too Read the CommonJS module cache through node:module instead of require.cache, so CommonJS packages imported from ESM are included as well. --- .../suites/modules/esm-app/lib/scenario.js | 1 + .../node-integration-tests/suites/modules/test.ts | 9 ++++++++- packages/core/src/utils/installedModules.ts | 5 ++--- packages/node/src/integrations/modules.ts | 12 +++++------- 4 files changed, 16 insertions(+), 11 deletions(-) diff --git a/dev-packages/node-integration-tests/suites/modules/esm-app/lib/scenario.js b/dev-packages/node-integration-tests/suites/modules/esm-app/lib/scenario.js index 733c3a99111a..115249cf6d38 100644 --- a/dev-packages/node-integration-tests/suites/modules/esm-app/lib/scenario.js +++ b/dev-packages/node-integration-tests/suites/modules/esm-app/lib/scenario.js @@ -1,5 +1,6 @@ import * as Sentry from '@sentry/node'; import { loggingTransport } from '@sentry-internal/node-integration-tests'; +import 'esm-app-transitive'; Sentry.init({ dsn: 'https://public@dsn.ingest.sentry.io/1337', diff --git a/dev-packages/node-integration-tests/suites/modules/test.ts b/dev-packages/node-integration-tests/suites/modules/test.ts index a1e986c24b98..0fcb48780b09 100644 --- a/dev-packages/node-integration-tests/suites/modules/test.ts +++ b/dev-packages/node-integration-tests/suites/modules/test.ts @@ -97,13 +97,20 @@ describe('modulesIntegration', () => { const packageDir = join(appDir, 'node_modules', 'esm-app-dependency'); mkdirSync(packageDir, { recursive: true }); writeFileSync(join(packageDir, 'package.json'), JSON.stringify({ name: 'esm-app-dependency', version: '1.4.0' })); + // A CommonJS package that the app imports but does not declare, like a transitive dependency + const transitiveDir = join(appDir, 'node_modules', 'esm-app-transitive'); + mkdirSync(transitiveDir, { recursive: true }); + writeFileSync(join(transitiveDir, 'package.json'), JSON.stringify({ name: 'esm-app-transitive', version: '3.1.0' })); + writeFileSync(join(transitiveDir, 'index.js'), 'module.exports = {};'); try { await createRunner(appDir, 'lib', 'scenario.js') .expect({ event: event => { - expect(event.modules).toEqual({ + // Packages the SDK itself loads from the repo's node_modules can show up too + expect(event.modules).toMatchObject({ 'esm-app-dependency': '1.4.0', + 'esm-app-transitive': '3.1.0', // Not installed, so the range from package.json is all there is 'esm-app-missing-dependency': '^2.0.0', }); diff --git a/packages/core/src/utils/installedModules.ts b/packages/core/src/utils/installedModules.ts index bd9aaf50c5ff..4d0d3d556d5a 100644 --- a/packages/core/src/utils/installedModules.ts +++ b/packages/core/src/utils/installedModules.ts @@ -23,9 +23,8 @@ export function collectInstalledModules({ entryPath?: string; cwd?: string; /** - * Paths of files the process has already loaded, such as the keys of `require.cache`. Packages these files belong - * to are added too, which covers transitive dependencies that are not in `package.json`. ESM has no - * equivalent of `require.cache`, so only CommonJS passes this; without it, only declared dependencies are resolved. + * Paths of files the process has already loaded, such as the keys of the CommonJS module cache. Packages these files + * belong to are added too, which covers transitive dependencies that are not in `package.json`. */ loadedFiles?: string[]; }): ModuleInfo { diff --git a/packages/node/src/integrations/modules.ts b/packages/node/src/integrations/modules.ts index cc1f6adf3029..7dfadda9e5ba 100644 --- a/packages/node/src/integrations/modules.ts +++ b/packages/node/src/integrations/modules.ts @@ -1,4 +1,5 @@ import { existsSync, readFileSync } from 'node:fs'; +import { Module } from 'node:module'; import { GLOBAL_OBJ, type IntegrationFn } from '@sentry/core'; import { collectInstalledModules } from '@sentry/core/server'; @@ -61,9 +62,10 @@ function readFile(path: string): string | undefined { } } -function getRequireCachePaths(): string[] { +/** Files loaded through the CommonJS loader, which includes CommonJS packages imported from ESM. */ +function getLoadedCommonJsFiles(): string[] { try { - return require.cache ? Object.keys(require.cache) : []; + return Object.keys((Module as unknown as { _cache?: Record })._cache || {}); } catch { return []; } @@ -79,11 +81,7 @@ function collectModules(): ModuleInfo { readFile, entryPath: process.argv[1], cwd: process.cwd(), - loadedFiles: [ - /*! rollup-include-cjs-only */ - ...getRequireCachePaths(), - /*! rollup-include-cjs-only-end */ - ], + loadedFiles: getLoadedCommonJsFiles(), }); } From fa3bbcf90f4a78c79c2f019f03a6a67572cc3752 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:14:37 +0000 Subject: [PATCH 09/14] ref(server-utils): Move collectInstalledModules from core to server-utils --- packages/core/src/server.ts | 1 - packages/nextjs/src/config/util.ts | 2 +- packages/node/src/integrations/modules.ts | 2 +- packages/server-utils/src/exports.ts | 1 + packages/{core => server-utils}/src/utils/installedModules.ts | 0 .../lib => server-utils/test}/utils/installedModules.test.ts | 2 +- 6 files changed, 4 insertions(+), 4 deletions(-) rename packages/{core => server-utils}/src/utils/installedModules.ts (100%) rename packages/{core/test/lib => server-utils/test}/utils/installedModules.test.ts (98%) diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index bd856546efca..e3636550b77c 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -34,7 +34,6 @@ export { trpcMiddleware } from './trpc'; export { wrapMcpServerWithSentry } from './integrations/mcp-server'; export { isNodeEnv, loadModule } from './utils/node'; export { filenameIsInApp, node, nodeStackLineParser } from './utils/node-stack-trace'; -export { collectInstalledModules } from './utils/installedModules'; export { vercelWaitUntil } from './utils/vercelWaitUntil'; export { getReleaseMetaTag as _INTERNAL_getReleaseMetaTag } from './utils/meta'; export { diff --git a/packages/nextjs/src/config/util.ts b/packages/nextjs/src/config/util.ts index 1dd20a8727e7..49e3e3080944 100644 --- a/packages/nextjs/src/config/util.ts +++ b/packages/nextjs/src/config/util.ts @@ -1,5 +1,5 @@ import { parseSemver } from '@sentry/core'; -import { collectInstalledModules } from '@sentry/core/server'; +import { collectInstalledModules } from '@sentry/server-utils/no-diagnostic-channels'; import * as fs from 'fs'; import { createRequire } from 'module'; diff --git a/packages/node/src/integrations/modules.ts b/packages/node/src/integrations/modules.ts index 7dfadda9e5ba..f80167404b79 100644 --- a/packages/node/src/integrations/modules.ts +++ b/packages/node/src/integrations/modules.ts @@ -1,7 +1,7 @@ import { existsSync, readFileSync } from 'node:fs'; import { Module } from 'node:module'; import { GLOBAL_OBJ, type IntegrationFn } from '@sentry/core'; -import { collectInstalledModules } from '@sentry/core/server'; +import { collectInstalledModules } from '@sentry/server-utils'; type ModuleInfo = Record; diff --git a/packages/server-utils/src/exports.ts b/packages/server-utils/src/exports.ts index d9fae4eb0f29..94e49d229749 100644 --- a/packages/server-utils/src/exports.ts +++ b/packages/server-utils/src/exports.ts @@ -6,6 +6,7 @@ export * from './ai'; export { getSqlQuerySummary, sanitizeSqlQuery, getSqlQueryAttributes, getSqlSpanName } from './utils/sql'; export type { SqlDialect } from './utils/sql'; export { isBun, isCloudflareWorkers, isDeno } from './utils/runtime'; +export { collectInstalledModules } from './utils/installedModules'; export { instrumentPostgresJsSql } from './integrations/postgresjs-wrapper'; export type { PostgresConnectionContext } from './integrations/postgresjs-wrapper'; diff --git a/packages/core/src/utils/installedModules.ts b/packages/server-utils/src/utils/installedModules.ts similarity index 100% rename from packages/core/src/utils/installedModules.ts rename to packages/server-utils/src/utils/installedModules.ts diff --git a/packages/core/test/lib/utils/installedModules.test.ts b/packages/server-utils/test/utils/installedModules.test.ts similarity index 98% rename from packages/core/test/lib/utils/installedModules.test.ts rename to packages/server-utils/test/utils/installedModules.test.ts index 2f3da1f31adc..0cca7bf500c3 100644 --- a/packages/core/test/lib/utils/installedModules.test.ts +++ b/packages/server-utils/test/utils/installedModules.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { collectInstalledModules } from '../../../src/utils/installedModules'; +import { collectInstalledModules } from '../../src/utils/installedModules'; function makeFs(files: Record): (path: string) => string | undefined { return path => { From cea69f65ba81e47fc70b4647f7a1dfeedd2c663e Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:17:15 +0000 Subject: [PATCH 10/14] ref(server-utils): Shrink collectInstalledModules Co-Authored-By: Francesco Gringl-Novy <2411343+mydea@users.noreply.github.com> --- .../src/utils/installedModules.ts | 78 ++++++++----------- 1 file changed, 33 insertions(+), 45 deletions(-) diff --git a/packages/server-utils/src/utils/installedModules.ts b/packages/server-utils/src/utils/installedModules.ts index 4d0d3d556d5a..7410e7350034 100644 --- a/packages/server-utils/src/utils/installedModules.ts +++ b/packages/server-utils/src/utils/installedModules.ts @@ -1,5 +1,4 @@ type ModuleInfo = Record; -type ReadFileFn = (path: string) => string | undefined; interface PackageJson { name?: string; version?: string; @@ -11,7 +10,7 @@ const NODE_MODULES = '/node_modules/'; /** * Returns the app's packages: the dependencies declared in its `package.json`, plus loaded packages. Each gets the exact - * version that a bare import from the entry file resolves through `node_modules`, or its declared range otherwise. + * version that a bare import from the app resolves through `node_modules`, or its declared range otherwise. */ export function collectInstalledModules({ readFile, @@ -19,7 +18,7 @@ export function collectInstalledModules({ cwd, loadedFiles = [], }: { - readFile: ReadFileFn; + readFile: (path: string) => string | undefined; entryPath?: string; cwd?: string; /** @@ -28,44 +27,57 @@ export function collectInstalledModules({ */ loadedFiles?: string[]; }): ModuleInfo { + const read = (dir: string): PackageJson | undefined => { + try { + return JSON.parse(readFile(join(dir, 'package.json')) || 'null') || undefined; + } catch { + return undefined; + } + }; + const entryDir = entryPath && dirname(toPosix(entryPath)); const cwdDir = cwd && toPosix(cwd); + let appRoot: string | undefined; // An entry file outside cwd usually belongs to a launcher, such as the AWS Lambda runtime. - const appRoot = findAppRoot( - readFile, - entryDir && cwdDir && !isIn(entryDir, cwdDir) ? [cwdDir, entryDir] : [entryDir, cwdDir], - ); + for (const dir of entryDir && cwdDir && !isIn(entryDir, cwdDir) ? [cwdDir, entryDir] : [entryDir, cwdDir]) { + // Skip `package.json` files that only set fields like `"type"`. + appRoot ||= + dir && !`${dir}/`.includes(NODE_MODULES) + ? ancestors(dir).find(d => { + const pkg = read(d); + return pkg && (pkg.name || pkg.dependencies || pkg.devDependencies); + }) + : undefined; + } + const resolveFrom = entryDir && appRoot && isIn(entryDir, appRoot) ? entryDir : appRoot || entryDir || cwdDir; const nodeModulesDirs = resolveFrom ? ancestors(resolveFrom).map(dir => join(dir, 'node_modules')) : []; const resolve = (name: string): string | undefined => { for (const dir of nodeModulesDirs) { - const pkg = readPackageJson(readFile, join(dir, name)); - if (pkg) { - return pkg.version; + const version = read(join(dir, name))?.version; + if (version) { + return version; } } return undefined; }; - const pkg = appRoot ? readPackageJson(readFile, appRoot) : undefined; + const pkg = appRoot ? read(appRoot) : undefined; const declared: ModuleInfo = { ...pkg?.dependencies, ...pkg?.devDependencies }; const installed: ModuleInfo = {}; - const seen = new Set(); + for (const file of loadedFiles) { const path = toPosix(file); - const index = path.lastIndexOf(NODE_MODULES); - if (index === -1 || !nodeModulesDirs.some(dir => isIn(path, dir))) { - continue; - } - const base = path.slice(0, index + NODE_MODULES.length); - const [first = '', second] = path.slice(base.length).split('/'); + const start = path.lastIndexOf(NODE_MODULES) + NODE_MODULES.length; + const [first = '', second] = path.slice(start).split('/'); const name = first.startsWith('@') ? `${first}/${second}` : first; - if (seen.has(base + name)) { + const dir = path.slice(0, start) + name; + if (start < NODE_MODULES.length || seen.has(dir) || !nodeModulesDirs.some(d => isIn(path, d))) { continue; } - seen.add(base + name); - const version = readPackageJson(readFile, base + name)?.version; + seen.add(dir); + const version = read(dir)?.version; if (version && installed[name] !== version) { // pnpm and Bun stores can hold several versions of a package; prefer the one the app resolves. installed[name] = (name in installed && resolve(name)) || installed[name] || version; @@ -82,30 +94,6 @@ export function collectInstalledModules({ return { ...declared, ...installed }; } -/** Skips start dirs inside `node_modules` and `package.json` files that only set fields like `"type"`. */ -function findAppRoot(readFile: ReadFileFn, startDirs: Array): string | undefined { - for (const startDir of startDirs) { - if (startDir && !`${startDir}/`.includes(NODE_MODULES)) { - const root = ancestors(startDir).find(dir => { - const pkg = readPackageJson(readFile, dir); - return pkg && (pkg.name || pkg.dependencies || pkg.devDependencies); - }); - if (root) { - return root; - } - } - } - return undefined; -} - -function readPackageJson(readFile: ReadFileFn, dir: string): PackageJson | undefined { - try { - return (JSON.parse(readFile(join(dir, 'package.json')) || 'null') as PackageJson | null) || undefined; - } catch { - return undefined; - } -} - /** `dir` and its parents, up to the root. */ function ancestors(dir: string): string[] { const dirs = [dir]; From 7662a4c6401d823ff8327584db5c57324cae747f Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:23:01 +0000 Subject: [PATCH 11/14] test(node): Format modules integration test --- dev-packages/node-integration-tests/suites/modules/test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/dev-packages/node-integration-tests/suites/modules/test.ts b/dev-packages/node-integration-tests/suites/modules/test.ts index 0fcb48780b09..cee120ea4f03 100644 --- a/dev-packages/node-integration-tests/suites/modules/test.ts +++ b/dev-packages/node-integration-tests/suites/modules/test.ts @@ -100,7 +100,10 @@ describe('modulesIntegration', () => { // A CommonJS package that the app imports but does not declare, like a transitive dependency const transitiveDir = join(appDir, 'node_modules', 'esm-app-transitive'); mkdirSync(transitiveDir, { recursive: true }); - writeFileSync(join(transitiveDir, 'package.json'), JSON.stringify({ name: 'esm-app-transitive', version: '3.1.0' })); + writeFileSync( + join(transitiveDir, 'package.json'), + JSON.stringify({ name: 'esm-app-transitive', version: '3.1.0' }), + ); writeFileSync(join(transitiveDir, 'index.js'), 'module.exports = {};'); try { From 2097265993c2f44af85301264da422bf1d50a98f Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:33:02 +0000 Subject: [PATCH 12/14] ref(server-utils): Extract findAppRoot to stay under the complexity limit --- .../src/utils/installedModules.ts | 35 +++++++++++++------ 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/packages/server-utils/src/utils/installedModules.ts b/packages/server-utils/src/utils/installedModules.ts index 7410e7350034..534df2b95d92 100644 --- a/packages/server-utils/src/utils/installedModules.ts +++ b/packages/server-utils/src/utils/installedModules.ts @@ -37,18 +37,11 @@ export function collectInstalledModules({ const entryDir = entryPath && dirname(toPosix(entryPath)); const cwdDir = cwd && toPosix(cwd); - let appRoot: string | undefined; // An entry file outside cwd usually belongs to a launcher, such as the AWS Lambda runtime. - for (const dir of entryDir && cwdDir && !isIn(entryDir, cwdDir) ? [cwdDir, entryDir] : [entryDir, cwdDir]) { - // Skip `package.json` files that only set fields like `"type"`. - appRoot ||= - dir && !`${dir}/`.includes(NODE_MODULES) - ? ancestors(dir).find(d => { - const pkg = read(d); - return pkg && (pkg.name || pkg.dependencies || pkg.devDependencies); - }) - : undefined; - } + const appRoot = findAppRoot( + read, + entryDir && cwdDir && !isIn(entryDir, cwdDir) ? [cwdDir, entryDir] : [entryDir, cwdDir], + ); const resolveFrom = entryDir && appRoot && isIn(entryDir, appRoot) ? entryDir : appRoot || entryDir || cwdDir; const nodeModulesDirs = resolveFrom ? ancestors(resolveFrom).map(dir => join(dir, 'node_modules')) : []; @@ -94,6 +87,26 @@ export function collectInstalledModules({ return { ...declared, ...installed }; } +/** Skips start dirs inside `node_modules` and `package.json` files that only set fields like `"type"`. */ +function findAppRoot( + read: (dir: string) => PackageJson | undefined, + startDirs: Array, +): string | undefined { + for (const startDir of startDirs) { + const root = + startDir && !`${startDir}/`.includes(NODE_MODULES) + ? ancestors(startDir).find(dir => { + const pkg = read(dir); + return pkg && (pkg.name || pkg.dependencies || pkg.devDependencies); + }) + : undefined; + if (root) { + return root; + } + } + return undefined; +} + /** `dir` and its parents, up to the root. */ function ancestors(dir: string): string[] { const dirs = [dir]; From df5052213927411d904bead1938929b4a67a602a Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:36:01 +0000 Subject: [PATCH 13/14] ref(node): Drop double cast on Module._cache --- packages/node/src/integrations/modules.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/node/src/integrations/modules.ts b/packages/node/src/integrations/modules.ts index f80167404b79..5891d0c73710 100644 --- a/packages/node/src/integrations/modules.ts +++ b/packages/node/src/integrations/modules.ts @@ -65,7 +65,7 @@ function readFile(path: string): string | undefined { /** Files loaded through the CommonJS loader, which includes CommonJS packages imported from ESM. */ function getLoadedCommonJsFiles(): string[] { try { - return Object.keys((Module as unknown as { _cache?: Record })._cache || {}); + return Object.keys((Module as { _cache?: Record })._cache || {}); } catch { return []; } From c8217e9c671886c413b47d0bea66740eb48bda52 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 09:26:28 +0000 Subject: [PATCH 14/14] fix(server-utils): Don't resolve app dependencies from a launcher's node_modules --- packages/server-utils/src/utils/installedModules.ts | 11 +++++++++-- .../server-utils/test/utils/installedModules.test.ts | 6 ++++-- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/packages/server-utils/src/utils/installedModules.ts b/packages/server-utils/src/utils/installedModules.ts index 534df2b95d92..4095c96f1428 100644 --- a/packages/server-utils/src/utils/installedModules.ts +++ b/packages/server-utils/src/utils/installedModules.ts @@ -43,7 +43,10 @@ export function collectInstalledModules({ entryDir && cwdDir && !isIn(entryDir, cwdDir) ? [cwdDir, entryDir] : [entryDir, cwdDir], ); - const resolveFrom = entryDir && appRoot && isIn(entryDir, appRoot) ? entryDir : appRoot || entryDir || cwdDir; + const resolveFrom = + entryDir && appRoot && isIn(entryDir, appRoot) && !inNodeModules(entryDir) + ? entryDir + : appRoot || entryDir || cwdDir; const nodeModulesDirs = resolveFrom ? ancestors(resolveFrom).map(dir => join(dir, 'node_modules')) : []; const resolve = (name: string): string | undefined => { for (const dir of nodeModulesDirs) { @@ -94,7 +97,7 @@ function findAppRoot( ): string | undefined { for (const startDir of startDirs) { const root = - startDir && !`${startDir}/`.includes(NODE_MODULES) + startDir && !inNodeModules(startDir) ? ancestors(startDir).find(dir => { const pkg = read(dir); return pkg && (pkg.name || pkg.dependencies || pkg.devDependencies); @@ -107,6 +110,10 @@ function findAppRoot( return undefined; } +function inNodeModules(dir: string): boolean { + return `${dir}/`.includes(NODE_MODULES); +} + /** `dir` and its parents, up to the root. */ function ancestors(dir: string): string[] { const dirs = [dir]; diff --git a/packages/server-utils/test/utils/installedModules.test.ts b/packages/server-utils/test/utils/installedModules.test.ts index 0cca7bf500c3..d487abc0bfea 100644 --- a/packages/server-utils/test/utils/installedModules.test.ts +++ b/packages/server-utils/test/utils/installedModules.test.ts @@ -54,13 +54,15 @@ describe('collectInstalledModules', () => { it('uses cwd when the entry file is inside node_modules', () => { const readFile = makeFs({ - '/app/package.json': { name: 'app', dependencies: { next: '^15.0.0' } }, + '/app/package.json': { name: 'app', dependencies: { next: '^15.0.0', react: '^19.0.0' } }, '/app/node_modules/next/package.json': { name: 'next', version: '15.1.0' }, + '/app/node_modules/react/package.json': { name: 'react', version: '19.1.0' }, + '/app/node_modules/next/node_modules/react/package.json': { name: 'react', version: '18.3.1' }, }); expect( collectInstalledModules({ readFile, entryPath: '/app/node_modules/next/dist/bin/next', cwd: '/app' }), - ).toEqual({ next: '15.1.0' }); + ).toEqual({ next: '15.1.0', react: '19.1.0' }); }); it('prefers cwd when the entry file is outside of it', () => {