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..115249cf6d38 100644 --- a/dev-packages/node-integration-tests/suites/modules/instrument.mjs +++ b/dev-packages/node-integration-tests/suites/modules/esm-app/lib/scenario.js @@ -1,11 +1,11 @@ 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', 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..cee120ea4f03 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,58 @@ 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' })); + // 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 => { + // 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', + }); + }, + }) + .start() + .completed(); + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } }); }); diff --git a/packages/nextjs/src/config/util.ts b/packages/nextjs/src/config/util.ts index 1473b86bd745..49e3e3080944 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 { collectInstalledModules } from '@sentry/server-utils/no-diagnostic-channels'; 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']; @@ -220,23 +220,16 @@ export function detectActiveBundler(): 'turbopack' | 'webpack' { } } -/** - * Extract modules from project directory's package.json - */ +/** The project's dependencies, with exact installed versions where they resolve and declared ranges otherwise. */ 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 {}; - } + return collectInstalledModules({ + readFile: filePath => { + try { + return fs.readFileSync(filePath, 'utf8'); + } catch { + return undefined; + } + }, + cwd: projectDir, + }); } diff --git a/packages/node/src/integrations/modules.ts b/packages/node/src/integrations/modules.ts index 54842d0cd5a3..5891d0c73710 100644 --- a/packages/node/src/integrations/modules.ts +++ b/packages/node/src/integrations/modules.ts @@ -1,6 +1,7 @@ -import { existsSync, readFileSync, realpathSync } from 'node:fs'; -import { basename, dirname, join } from 'node:path'; +import { existsSync, readFileSync } from 'node:fs'; +import { Module } from 'node:module'; import { GLOBAL_OBJ, type IntegrationFn } from '@sentry/core'; +import { collectInstalledModules } from '@sentry/server-utils'; type ModuleInfo = Record; @@ -46,114 +47,42 @@ 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) + * 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; -function getRequireCachePaths(): string[] { +function readFile(path: string): string | undefined { try { - return require.cache ? Object.keys(require.cache) : []; + // 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 []; + return undefined; } } -/** Extract information about package.json modules */ -function collectModules(): ModuleInfo { - return { - ...getServerModules(), - ...getModulesFromPackageJson(), - /*! rollup-include-cjs-only */ - ...collectRequireModules(), - /*! rollup-include-cjs-only-end */ - }; -} - -/** - * 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; +/** Files loaded through the CommonJS loader, which includes CommonJS packages imported from ESM. */ +function getLoadedCommonJsFiles(): string[] { + try { + return Object.keys((Module as { _cache?: Record })._cache || {}); + } catch { + return []; } - - 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(); +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; + } + return collectInstalledModules({ + readFile, + entryPath: process.argv[1], + cwd: process.cwd(), + loadedFiles: getLoadedCommonJsFiles(), }); - - return infos; } /** Fetches the list of modules and the versions loaded by the entry file for your node.js app. */ @@ -163,28 +92,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, - }; -} 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' }); }); }); 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/server-utils/src/utils/installedModules.ts b/packages/server-utils/src/utils/installedModules.ts new file mode 100644 index 000000000000..4095c96f1428 --- /dev/null +++ b/packages/server-utils/src/utils/installedModules.ts @@ -0,0 +1,142 @@ +type ModuleInfo = Record; +interface PackageJson { + name?: string; + version?: string; + dependencies?: ModuleInfo; + devDependencies?: ModuleInfo; +} + +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 app resolves through `node_modules`, or its declared range otherwise. + */ +export function collectInstalledModules({ + readFile, + entryPath, + cwd, + loadedFiles = [], +}: { + readFile: (path: string) => string | undefined; + entryPath?: string; + cwd?: string; + /** + * 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 { + 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); + // An entry file outside cwd usually belongs to a launcher, such as the AWS Lambda runtime. + const appRoot = findAppRoot( + read, + entryDir && cwdDir && !isIn(entryDir, cwdDir) ? [cwdDir, entryDir] : [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) { + const version = read(join(dir, name))?.version; + if (version) { + return version; + } + } + return 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 start = path.lastIndexOf(NODE_MODULES) + NODE_MODULES.length; + const [first = '', second] = path.slice(start).split('/'); + const name = first.startsWith('@') ? `${first}/${second}` : first; + const dir = path.slice(0, start) + name; + if (start < NODE_MODULES.length || seen.has(dir) || !nodeModulesDirs.some(d => isIn(path, d))) { + continue; + } + 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; + } + } + + for (const name of Object.keys(declared)) { + const version = resolve(name); + if (version) { + installed[name] = version; + } + } + + 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 && !inNodeModules(startDir) + ? ancestors(startDir).find(dir => { + const pkg = read(dir); + return pkg && (pkg.name || pkg.dependencies || pkg.devDependencies); + }) + : undefined; + if (root) { + return root; + } + } + 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]; + for (let parent = dirname(dir); parent !== dirs[dirs.length - 1]; parent = dirname(parent)) { + dirs.push(parent); + } + return dirs; +} + +// 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 toPosix(path: string): string { + return path.replace(/\\/g, '/'); +} diff --git a/packages/server-utils/test/utils/installedModules.test.ts b/packages/server-utils/test/utils/installedModules.test.ts new file mode 100644 index 000000000000..d487abc0bfea --- /dev/null +++ b/packages/server-utils/test/utils/installedModules.test.ts @@ -0,0 +1,148 @@ +import { describe, expect, it } from 'vitest'; +import { collectInstalledModules } 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({ + express: '4.21.2', + '@scope/lib': '2.3.4', + vitest: '^3.0.0', + }); + }); + + 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({ + 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' })).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', 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', react: '19.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({ + 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: '/' })).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', + ], + }), + ).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', + ], + }), + ).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' })).toEqual({ + express: '4.21.2', + }); + }); + + it('returns nothing without a package.json', () => { + expect(collectInstalledModules({ readFile: () => undefined, entryPath: '/app/index.js', cwd: '/' })).toEqual({}); + }); +});