Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/deno/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
67 changes: 67 additions & 0 deletions packages/deno/src/integrations/modules.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { fileURLToPath } from 'node:url';
import type { IntegrationFn } from '@sentry/core';
import { defineIntegration, dirname, join } from '@sentry/core';
import { collectInstalledModules } from '@sentry/server-utils';

/** 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<string, string> {
const modules: Record<string, string> = {};
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 `_<peer deps>`.
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<string, string> {
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<string, string> | 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);
2 changes: 2 additions & 0 deletions packages/deno/src/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -48,6 +49,7 @@ export function getDefaultIntegrationsWithoutPerformance(): Integration[] {
fetchIntegration(),
denoHttpIntegration(),
contextLinesIntegration(),
modulesIntegration(),
normalizePathsIntegration(),
globalHandlersIntegration(),
// server-utils integrations
Expand Down
9 changes: 9 additions & 0 deletions packages/deno/test/__snapshots__/mod.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ snapshot[`captureMessage 1`] = `
event_id: "{{id}}",
level: "info",
message: "Some error message",
modules: {
"{{modules}}": "{{version}}",
},
platform: "javascript",
sdk: {
integrations: [
Expand Down Expand Up @@ -114,6 +117,9 @@ snapshot[`captureMessage twice 1`] = `
event_id: "{{id}}",
level: "info",
message: "Some error message",
modules: {
"{{modules}}": "{{version}}",
},
platform: "javascript",
sdk: {
integrations: [
Expand Down Expand Up @@ -191,6 +197,9 @@ snapshot[`captureMessage twice 2`] = `
event_id: "{{id}}",
level: "info",
message: "Another error message",
modules: {
"{{modules}}": "{{version}}",
},
platform: "javascript",
sdk: {
integrations: [
Expand Down
1 change: 1 addition & 0 deletions packages/deno/test/exports.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ const EXPECTED_FUNCTION_EXPORTS = [
// ./sdk
'initWithoutDefaultIntegrations',
'getDefaultIntegrationsWithoutPerformance',
'modulesIntegration',
];

for (const name of EXPECTED_FUNCTION_EXPORTS) {
Expand Down
8 changes: 8 additions & 0 deletions packages/deno/test/fixtures/modules/deno.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions packages/deno/test/fixtures/modules/main.ts
Original file line number Diff line number Diff line change
@@ -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();
7 changes: 7 additions & 0 deletions packages/deno/test/fixtures/modules/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"name": "deno-modules-fixture",
"private": true,
"dependencies": {
"left-pad": "^1.3.0"
}
}
27 changes: 27 additions & 0 deletions packages/deno/test/modules.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
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<unknown> {
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([]), {});
});
5 changes: 5 additions & 0 deletions packages/deno/test/normalize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}}';
}
Expand Down
Loading