diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index e5ee3c623d76..4c0753bf2017 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -32,6 +32,7 @@ export { getIntegrationsToSetup } from './integration'; export { FunctionToString, InboundFilters } from './integrations'; export { prepareEvent } from './utils/prepareEvent'; export { hasTracingEnabled } from './utils/hasTracingEnabled'; +export { buildMetadata } from './utils/buildMetadata'; export { DEFAULT_ENVIRONMENT } from './constants'; import * as Integrations from './integrations'; diff --git a/packages/core/src/utils/buildMetadata.ts b/packages/core/src/utils/buildMetadata.ts new file mode 100644 index 000000000000..2d721c494709 --- /dev/null +++ b/packages/core/src/utils/buildMetadata.ts @@ -0,0 +1,26 @@ +import type { Options, SdkInfo } from '@sentry/types'; + +import { SDK_VERSION } from '../version'; + +const PACKAGE_NAME_PREFIX = 'npm:@sentry/'; + +/** + * A builder for the SDK metadata in the options for the SDK initialization. + * + * @param options sdk options object that gets mutated + * @param sdkName name of the SDK (e.g. 'nextjs') + * @param packageNames list of package names (e.g. ['nextjs', 'react']) + */ +export function buildMetadata(options: Options, sdkName: string, packageNames: string[]): void { + options._metadata = options._metadata || {}; + options._metadata.sdk = + options._metadata.sdk || + ({ + name: `sentry.javascript.${sdkName}`, + packages: packageNames.map(name => ({ + name: `${PACKAGE_NAME_PREFIX}${name}`, + version: SDK_VERSION, + })), + version: SDK_VERSION, + } as SdkInfo); +} diff --git a/packages/core/test/lib/utils/buildMetadata.test.ts b/packages/core/test/lib/utils/buildMetadata.test.ts new file mode 100644 index 000000000000..7c3659f047b9 --- /dev/null +++ b/packages/core/test/lib/utils/buildMetadata.test.ts @@ -0,0 +1,45 @@ +import { buildMetadata } from '../../../src/utils/buildMetadata'; +import { SDK_VERSION } from '../../../src/version'; + +describe('buildMetadata', () => { + it('adds SDK name and packages to the passed options object', () => { + const options = {}; + const sdkName = 'jQuery'; + + buildMetadata(options, sdkName, ['jQuery', 'browser']); + + expect(options).toEqual({ + _metadata: { + sdk: { + name: `sentry.javascript.${sdkName}`, + packages: [ + { + name: 'npm:@sentry/jQuery', + version: SDK_VERSION, + }, + { + name: 'npm:@sentry/browser', + version: SDK_VERSION, + }, + ], + version: SDK_VERSION, + }, + }, + }); + }); + + it('does not overwrite existing SDK metadata', () => { + const options = { + _metadata: { + sdk: { + name: 'sentry.javascript.SomeSDK', + version: '7.40.0', + }, + }, + }; + + buildMetadata(options, 'jQuery', ['jQuery', 'browser']); + + expect(options).toStrictEqual(options); + }); +});