diff --git a/.oxlintrc.base.json b/.oxlintrc.base.json index a2256c9a2803..34bc67bc4f56 100644 --- a/.oxlintrc.base.json +++ b/.oxlintrc.base.json @@ -94,7 +94,8 @@ "files": ["**/src/**/*.ts", "**/src/**/*.tsx", "**/addon/**/*.ts"], "rules": { "sdk/no-unguarded-span-apis": "error", - "sdk/no-unguarded-debug-logs": "error" + "sdk/no-unguarded-debug-logs": "error", + "sdk/require-define-integration": "error" } }, { diff --git a/packages/eslint-plugin-sdk/src/index.js b/packages/eslint-plugin-sdk/src/index.js index e1f27895b734..e3d5e94786ef 100644 --- a/packages/eslint-plugin-sdk/src/index.js +++ b/packages/eslint-plugin-sdk/src/index.js @@ -20,5 +20,6 @@ module.exports = { 'no-unfiltered-url-attributes': require('./rules/no-unfiltered-url-attributes'), 'no-unguarded-span-apis': require('./rules/no-unguarded-span-apis'), 'no-unsafe-html-writes': require('./rules/no-unsafe-html-writes'), + 'require-define-integration': require('./rules/require-define-integration'), }, }; diff --git a/packages/eslint-plugin-sdk/src/rules/require-define-integration.js b/packages/eslint-plugin-sdk/src/rules/require-define-integration.js new file mode 100644 index 000000000000..80012088fd71 --- /dev/null +++ b/packages/eslint-plugin-sdk/src/rules/require-define-integration.js @@ -0,0 +1,189 @@ +'use strict'; + +/** + * @fileoverview Rule to require that integrations are created with `defineIntegration`. + * + * `defineIntegration` records the options an integration was created with on `_options`. An + * integration that returns its object directly works, but its options are never recorded. + * + * Oxlint offers no type information to JS plugins, so the rule looks for the shape of an integration + * instead: an object literal with a `name` and at least one integration hook. Such an object is fine + * when the function that builds it reaches `defineIntegration` within the same file, either because + * it is passed to it or because a function that is passed to it uses it. + */ + +const { splitPackagePath } = require('../utils/browser-facing'); + +const INTEGRATION_HOOKS = new Set([ + 'setupOnce', + 'beforeSetup', + 'setup', + 'afterAllSetup', + 'preprocessEvent', + 'processEvent', + 'processSpan', + 'processSegmentSpan', +]); + +/** + * Bundler and framework plugins are also `{ name, setup }` objects, so the files that define them are + * skipped. Paths are relative to `packages/`. + */ +const PLUGIN_PATHS = [ + /^bundler-plugins\//, + /^server-runtime-injection\//, + /^bun\/src\/plugin\.ts$/, + /^nitro\/src\/(?:module|orchestrion)\.ts$/, + /^node\/src\/bundler-plugin\//, + /^nuxt\/src\/runtime\/plugins\//, + /^server-utils\/src\/orchestrion\/bundler\//, + /^tanstackstart-react\/src\/vite\//, +]; + +const TRANSPARENT_WRAPPERS = new Set([ + 'TSSatisfiesExpression', + 'TSAsExpression', + 'TSNonNullExpression', + 'ParenthesizedExpression', +]); + +const FUNCTIONS = new Set(['ArrowFunctionExpression', 'FunctionExpression', 'FunctionDeclaration']); + +function isPluginFile(filename) { + const location = splitPackagePath(filename); + if (!location) { + return false; + } + + const path = `${location.pkg}/${location.path}`; + + return PLUGIN_PATHS.some(pattern => pattern.test(path)); +} + +function isDefineIntegrationCall(node) { + if (node.type !== 'CallExpression') { + return false; + } + + const callee = node.callee; + + return ( + (callee.type === 'Identifier' && callee.name === 'defineIntegration') || + (callee.type === 'MemberExpression' && !callee.computed && callee.property.name === 'defineIntegration') + ); +} + +function getPropertyName(property) { + if (property.type !== 'Property' || property.computed) { + return undefined; + } + + return property.key.type === 'Identifier' ? property.key.name : property.key.value; +} + +/** The name a function can be referred to by: its own, or the variable it is assigned to. */ +function getFunctionName(node) { + if (node.id) { + return node.id.name; + } + + let parent = node.parent; + while (parent && TRANSPARENT_WRAPPERS.has(parent.type)) { + parent = parent.parent; + } + + return parent?.type === 'VariableDeclarator' && parent.id.type === 'Identifier' ? parent.id.name : undefined; +} + +module.exports = { + meta: { + type: 'problem', + docs: { + description: 'Require integrations to be created with `defineIntegration`', + category: 'Possible Errors', + recommended: true, + }, + fixable: null, + schema: [], + messages: { + requireDefineIntegration: + 'Integrations must be created with `defineIntegration`. Without it, the options the integration was created with are not recorded.', + }, + }, + create: function (context) { + if (isPluginFile(context.getFilename())) { + return {}; + } + + /** Names used inside a `defineIntegration(...)` call. */ + const defined = new Set(); + /** Names used inside each named function, to follow helpers that build the object. */ + const usedByFunction = new Map(); + const candidates = []; + + /** Names of the functions around `node`, or `undefined` when it is inside `defineIntegration(...)`. */ + function getEnclosingFunctionNames(node) { + const names = []; + for (let parent = node.parent; parent; parent = parent.parent) { + if (isDefineIntegrationCall(parent)) { + return undefined; + } + + const name = FUNCTIONS.has(parent.type) ? getFunctionName(parent) : undefined; + if (name) { + names.push(name); + } + } + + return names; + } + + return { + Identifier(node) { + const functionNames = getEnclosingFunctionNames(node); + if (!functionNames) { + defined.add(node.name); + + return; + } + + for (const functionName of functionNames) { + if (!usedByFunction.has(functionName)) { + usedByFunction.set(functionName, new Set()); + } + usedByFunction.get(functionName).add(node.name); + } + }, + + ObjectExpression(node) { + const names = node.properties.map(getPropertyName); + if (!names.includes('name') || !names.some(name => INTEGRATION_HOOKS.has(name))) { + return; + } + + const functionNames = getEnclosingFunctionNames(node); + if (functionNames) { + candidates.push({ node, functionNames }); + } + }, + + 'Program:exit'() { + const pending = [...defined]; + while (pending.length) { + for (const name of usedByFunction.get(pending.pop()) || []) { + if (!defined.has(name)) { + defined.add(name); + pending.push(name); + } + } + } + + for (const { node, functionNames } of candidates) { + if (!functionNames.some(name => defined.has(name))) { + context.report({ node, messageId: 'requireDefineIntegration' }); + } + } + }, + }; + }, +}; diff --git a/packages/eslint-plugin-sdk/test/lib/rules/require-define-integration.test.ts b/packages/eslint-plugin-sdk/test/lib/rules/require-define-integration.test.ts new file mode 100644 index 000000000000..536f817354b3 --- /dev/null +++ b/packages/eslint-plugin-sdk/test/lib/rules/require-define-integration.test.ts @@ -0,0 +1,114 @@ +import { RuleTester } from 'eslint'; +import { describe, test } from 'vitest'; +// @ts-expect-error untyped module +import rule from '../../../src/rules/require-define-integration'; + +const errors = [{ messageId: 'requireDefineIntegration', type: 'ObjectExpression' }]; + +describe('require-define-integration', () => { + test('ruleTester', () => { + const ruleTester = new RuleTester({ + parserOptions: { + ecmaVersion: 2020, + sourceType: 'module', + }, + }); + + ruleTester.run('require-define-integration', rule, { + valid: [ + { + code: "export const fooIntegration = defineIntegration(() => ({ name: 'Foo', setup() {} }));", + }, + { + code: "export const fooIntegration = core.defineIntegration(() => ({ name: 'Foo', setup() {} }));", + }, + { + code: ` + const _fooIntegration = () => { + return { name: 'Foo', setupOnce() {} }; + }; + export const fooIntegration = defineIntegration(_fooIntegration); + `, + }, + // The object is built by a helper of the function that is passed to `defineIntegration`. + { + code: ` + function buildFoo(options) { + return { name: 'Foo', processEvent: event => event }; + } + const _fooIntegration = options => buildFoo(options); + export const fooIntegration = defineIntegration(_fooIntegration); + `, + }, + { + code: ` + function buildFoo(options) { + return { name: 'Foo', setup() {} }; + } + export const fooIntegration = defineIntegration(options => buildFoo(options)); + `, + }, + // A factory that wraps the integration itself. + { + code: ` + export function createFooIntegration(name) { + return defineIntegration(() => ({ name, setup() {} })); + } + `, + }, + // No hook, so not an integration. + { + code: "export const foo = () => ({ name: 'Foo', handler() {} });", + }, + // No name, so not an integration. + { + code: 'export const foo = () => ({ setup() {} });', + }, + // Bundler plugins share the `{ name, setup }` shape. + { + filename: '/repo/packages/bundler-plugins/src/esbuild/index.ts', + code: "export const plugin = () => ({ name: 'sentry-esbuild-plugin', setup(build) {} });", + }, + ], + invalid: [ + { + code: "export const fooIntegration = () => ({ name: 'Foo', setup() {} });", + errors, + }, + { + code: ` + export function fooIntegration() { + return { name: 'Foo', setupOnce() {} }; + } + `, + errors, + }, + // The function is never passed to `defineIntegration`. + { + code: ` + const _fooIntegration = () => { + return { name: 'Foo', processSpan() {} }; + }; + export const fooIntegration = _fooIntegration; + `, + errors, + }, + // `defineIntegration` wraps another integration of the file, not this one. + { + code: ` + const _fooIntegration = () => ({ name: 'Foo', setup() {} }); + const _barIntegration = () => ({ name: 'Bar', setup() {} }); + export const fooIntegration = defineIntegration(_fooIntegration); + export const barIntegration = _barIntegration; + `, + errors, + }, + { + filename: '/repo/packages/node/src/integrations/foo.ts', + code: "export const fooIntegration = () => ({ name: 'Foo', afterAllSetup() {} });", + errors, + }, + ], + }); + }); +}); diff --git a/packages/feedback/src/modal/integration.tsx b/packages/feedback/src/modal/integration.tsx index d424cd1de813..3b4c7c81343d 100644 --- a/packages/feedback/src/modal/integration.tsx +++ b/packages/feedback/src/modal/integration.tsx @@ -1,5 +1,5 @@ import type { FeedbackFormData, FeedbackModalIntegration, IntegrationFn, User } from '@sentry/core'; -import { getClient, getCurrentScope, getGlobalScope, getIsolationScope } from '@sentry/core'; +import { defineIntegration, getClient, getCurrentScope, getGlobalScope, getIsolationScope } from '@sentry/core'; import { h, render } from 'preact'; import * as hooks from 'preact/hooks'; import { DOCUMENT } from '../constants'; @@ -19,7 +19,7 @@ function getUser(): User | undefined { return globalUser; } -export const feedbackModalIntegration = ((): FeedbackModalIntegration => { +const _feedbackModalIntegration = ((): FeedbackModalIntegration => { return { name: 'FeedbackModal' as const, setupOnce() {}, @@ -131,3 +131,7 @@ export const feedbackModalIntegration = ((): FeedbackModalIntegration => { }, }; }) satisfies IntegrationFn; + +export const feedbackModalIntegration = defineIntegration( + _feedbackModalIntegration, +) as typeof _feedbackModalIntegration; diff --git a/packages/feedback/src/screenshot/integration.ts b/packages/feedback/src/screenshot/integration.ts index 38c6349cd1a6..fdf1faf3081c 100644 --- a/packages/feedback/src/screenshot/integration.ts +++ b/packages/feedback/src/screenshot/integration.ts @@ -1,10 +1,11 @@ import type { Attachment, FeedbackScreenshotIntegration, IntegrationFn } from '@sentry/core'; +import { defineIntegration } from '@sentry/core'; import type { h as hType } from 'preact'; import type * as Hooks from 'preact/hooks'; import { DOCUMENT } from '../constants'; import { ScreenshotEditorFactory } from './components/ScreenshotEditor'; -export const feedbackScreenshotIntegration = ((): FeedbackScreenshotIntegration => { +const _feedbackScreenshotIntegration = ((): FeedbackScreenshotIntegration => { return { name: 'FeedbackScreenshot' as const, setupOnce() {}, @@ -40,3 +41,7 @@ export const feedbackScreenshotIntegration = ((): FeedbackScreenshotIntegration }, }; }) satisfies IntegrationFn; + +export const feedbackScreenshotIntegration = defineIntegration( + _feedbackScreenshotIntegration, +) as typeof _feedbackScreenshotIntegration; diff --git a/packages/nextjs/src/cloudflare/index.ts b/packages/nextjs/src/cloudflare/index.ts index ae2fa26a4e2b..561bac1d9fd8 100644 --- a/packages/nextjs/src/cloudflare/index.ts +++ b/packages/nextjs/src/cloudflare/index.ts @@ -3,10 +3,10 @@ import type { Context, TextMapGetter } from '@opentelemetry/api'; import { context, propagation, trace } from '@opentelemetry/api'; import type { CloudflareOptions } from '@sentry/cloudflare'; import { withSentry as withSentryCloudflare } from '@sentry/cloudflare'; -import type { Integration } from '@sentry/core'; import { _INTERNAL_captureOptionsSetByUser, applySdkMetadata, + defineIntegration, extractTraceparentData, getRootSpan, GLOBAL_OBJ, @@ -52,7 +52,7 @@ class NextjsCloudflarePropagator extends NextSentryPropagator { } } -const nextjsIntegration = (): Integration => ({ +const nextjsIntegration = defineIntegration(() => ({ name: 'Nextjs', setup: client => { if ((client.getOptions() as CloudflareOptions).enableOpenTelemetrySetup) { @@ -72,7 +72,7 @@ const nextjsIntegration = (): Integration => ({ } }); }, -}); +})); /** * `withSentry` of `@sentry/cloudflare` for the Worker entry of a Next.js app, e.g. `.open-next/worker.js`. It adds the diff --git a/packages/node/src/integrations/http/httpServerIntegration.ts b/packages/node/src/integrations/http/httpServerIntegration.ts index 0000e54bc683..4b5a7ff81e24 100644 --- a/packages/node/src/integrations/http/httpServerIntegration.ts +++ b/packages/node/src/integrations/http/httpServerIntegration.ts @@ -1,7 +1,7 @@ import type { RequestOptions } from 'node:http'; import { context, createContextKey, propagation } from '@opentelemetry/api'; import type { Integration, IntegrationFn } from '@sentry/core'; -import { addNonEnumerableProperty, debug, getClient } from '@sentry/core'; +import { addNonEnumerableProperty, debug, defineIntegration, getClient } from '@sentry/core'; import type { HttpIncomingMessage, HttpServerResponse } from '@sentry/core/server'; import { getHttpServerSubscriptions, @@ -166,7 +166,7 @@ const _httpServerIntegration = ((options: HttpServerIntegrationOptions = {}) => * * @see {@link ../../light/integrations/httpServerIntegration.ts} for the lightweight version without OpenTelemetry */ -export const httpServerIntegration = _httpServerIntegration as ( +export const httpServerIntegration = defineIntegration(_httpServerIntegration) as ( options?: HttpServerIntegrationOptions, ) => Integration & { name: 'Http.Server'; diff --git a/packages/node/src/integrations/http/httpServerSpansIntegration.ts b/packages/node/src/integrations/http/httpServerSpansIntegration.ts index bf067c50e0da..1b657af7113f 100644 --- a/packages/node/src/integrations/http/httpServerSpansIntegration.ts +++ b/packages/node/src/integrations/http/httpServerSpansIntegration.ts @@ -38,6 +38,7 @@ import { } from '@sentry/core/server'; import { debug, + defineIntegration, safeCallback, getSpanStatusFromHttpCode, httpHeadersToSpanAttributes, @@ -279,7 +280,7 @@ const _httpServerSpansIntegration = ((options: HttpServerSpansIntegrationOptions * This integration emits spans for incoming requests handled via the node `http` module. * It requires the `httpServerIntegration` to be present. */ -export const httpServerSpansIntegration = _httpServerSpansIntegration as ( +export const httpServerSpansIntegration = defineIntegration(_httpServerSpansIntegration) as ( options?: HttpServerSpansIntegrationOptions, ) => Integration & { name: 'Http.ServerSpans'; diff --git a/packages/node/src/integrations/modules.ts b/packages/node/src/integrations/modules.ts index 5891d0c73710..95275cf3717a 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 { Module } from 'node:module'; -import { GLOBAL_OBJ, type IntegrationFn } from '@sentry/core'; +import { defineIntegration, GLOBAL_OBJ, type IntegrationFn } from '@sentry/core'; import { collectInstalledModules } from '@sentry/server-utils'; type ModuleInfo = Record; @@ -50,7 +50,7 @@ const _modulesIntegration = (() => { * 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; +export const modulesIntegration = defineIntegration(_modulesIntegration); function readFile(path: string): string | undefined { try { diff --git a/packages/server-utils/src/integrations/openai-compatible.ts b/packages/server-utils/src/integrations/openai-compatible.ts index d817702c1292..0b0b8c7aab5b 100644 --- a/packages/server-utils/src/integrations/openai-compatible.ts +++ b/packages/server-utils/src/integrations/openai-compatible.ts @@ -86,6 +86,7 @@ export function createOpenAiCompatibleIntegration { + // oxlint-disable-next-line sdk/require-define-integration -- callers pass the returned function to `defineIntegration` return { name: provider.integrationName, setup(client) { diff --git a/packages/sveltekit/src/server-common/integrations/svelteKitSpans.ts b/packages/sveltekit/src/server-common/integrations/svelteKitSpans.ts index 78081dfaacb4..1767fb315da8 100644 --- a/packages/sveltekit/src/server-common/integrations/svelteKitSpans.ts +++ b/packages/sveltekit/src/server-common/integrations/svelteKitSpans.ts @@ -1,5 +1,5 @@ -import type { Integration, SpanJSON, SpanOrigin, StreamedSpanJSON } from '@sentry/core'; -import { safeSetSpanJSONAttributes } from '@sentry/core'; +import type { SpanJSON, SpanOrigin, StreamedSpanJSON } from '@sentry/core'; +import { defineIntegration, safeSetSpanJSONAttributes } from '@sentry/core'; import { SENTRY_DESCRIPTION, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes'; import { FUNCTION } from '@sentry/conventions/op'; @@ -8,7 +8,7 @@ import { FUNCTION } from '@sentry/conventions/op'; * (via Kit's tracing feature since 2.31.0) get the correct Sentry attributes * and data. */ -export function svelteKitSpansIntegration(): Integration { +export const svelteKitSpansIntegration = defineIntegration(() => { return { name: 'SvelteKitSpansEnhancement' as const, // Using preprocessEvent to ensure the processing happens before user-configured @@ -26,7 +26,7 @@ export function svelteKitSpansIntegration(): Integration { _enhanceKitSpanStreamed(span); }, }; -} +}); /** * Adds sentry-specific attributes and data to a span emitted by SvelteKit's native tracing (since 2.31.0) diff --git a/packages/tanstackstart-react/src/server/index.ts b/packages/tanstackstart-react/src/server/index.ts index ba40c0b8223d..66deef3616af 100644 --- a/packages/tanstackstart-react/src/server/index.ts +++ b/packages/tanstackstart-react/src/server/index.ts @@ -2,6 +2,7 @@ // can be removed once following issue is fixed: https://github.com/import-js/eslint-plugin-import/issues/703 /* eslint-disable import/export */ import type { Integration } from '@sentry/core'; +import { defineIntegration } from '@sentry/core'; export * from '@sentry/node'; @@ -17,12 +18,19 @@ export { createSentryTunnelRoute, registerSentryServerTunnelRoute, setTunnelRout * A no-op stub of the replay integration for the server. Router setup code is shared between client and server, * so this stub is needed to prevent build errors during SSR bundling. */ -export function replayIntegration(_options?: Record): Integration { +export const replayIntegration = defineIntegration((_options?: Record) => { return { name: 'Replay', setup() {}, }; -} +}); + +const _browserTracingIntegration = defineIntegration((_options?: Record) => { + return { + name: 'BrowserTracing', + setup() {}, + }; +}); /** * A no-op stub of the browser tracing integration for the server. Router setup code is shared between client and server, @@ -30,12 +38,9 @@ export function replayIntegration(_options?: Record): Integrati */ export function tanstackRouterBrowserTracingIntegration( _router: unknown, - _options?: Record, + options?: Record, ): Integration { - return { - name: 'BrowserTracing', - setup() {}, - }; + return _browserTracingIntegration(options); } /**