Skip to content
Merged
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
3 changes: 1 addition & 2 deletions .github/CODEOWNERS
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@ packages/plugins/metrics @DataDog/f
packages/plugins/error-tracking @yoannmoinet

# Rum
packages/plugins/rum @yoannmoinet
packages/plugins/rum/src/privacy @DataDog/rum-browser
packages/plugins/rum @DataDog/rum-browser @yoannmoinet

# Analytics
packages/plugins/analytics @yoannmoinet
Expand Down
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
2 changes: 1 addition & 1 deletion packages/plugins/rum/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
"chalk": "2.3.1"
},
"devDependencies": {
"@datadog/browser-rum": "6.24.0",
"@datadog/browser-rum": "6.26.0",
"typescript": "5.4.3"
}
}
24 changes: 24 additions & 0 deletions packages/plugins/rum/src/getSourceCodeContextSnippet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2019-Present Datadog, Inc.

import type { SourceCodeContextOptions } from './types';

export const DEFAULT_SOURCE_CODE_CONTEXT_VARIABLE = 'DD_SOURCE_CODE_CONTEXT' as const;

// The source code context snippet - single injection with function definition and call
// SSR-safe: checks window before accessing, never throws
//
// Unminified version:
// (function(c, n) {
// try {
// if (typeof window === 'undefined') return;
// var w = window,
// m = w[n] = w[n] || {},
// s = new Error().stack;
// s && (m[s] = c)
// } catch (e) {}
// })(context, variableName);
export const getSourceCodeContextSnippet = (context: SourceCodeContextOptions): string => {
return `(function(c,n){try{if(typeof window==='undefined')return;var w=window,m=w[n]=w[n]||{},s=new Error().stack;s&&(m[s]=c)}catch(e){}})(${JSON.stringify(context)},${JSON.stringify(DEFAULT_SOURCE_CODE_CONTEXT_VARIABLE)});`;
};
26 changes: 15 additions & 11 deletions packages/plugins/rum/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,14 @@ describe('RUM Plugin', () => {
const injections = {
'browser-sdk': path.resolve('../plugins/rum/src/rum-browser-sdk.js'),
'sdk-init': injectionValue,
'source-code-context':
/(?=.*DD_SOURCE_CODE_CONTEXT)(?=.*"service":"checkout")(?=.*"version":"1\.2\.3")/,
};

const expectations: {
type: string;
config: RumOptions;
should: { inject: (keyof typeof injections)[]; throw?: boolean };
should: { inject: (keyof typeof injections)[] };
}[] = [
{
type: 'no sdk',
Expand All @@ -38,6 +40,16 @@ describe('RUM Plugin', () => {
config: { sdk: { applicationId: 'app-id' } },
should: { inject: ['browser-sdk', 'sdk-init'] },
},
{
type: 'source code context',
config: {
sourceCodeContext: {
service: 'checkout',
version: '1.2.3',
},
},
should: { inject: ['source-code-context'] },
},
];
describe('getPlugins', () => {
const injectMock = jest.fn();
Expand Down Expand Up @@ -79,21 +91,13 @@ describe('RUM Plugin', () => {
const mockContext = getContextMock();
const pluginConfig = { ...defaultPluginOptions, rum: config };

const expectResult = expect(() => {
getPlugins(getGetPluginsArg(pluginConfig, mockContext));
});

if (should.throw) {
expectResult.toThrow();
} else {
expectResult.not.toThrow();
}
getPlugins(getGetPluginsArg(pluginConfig, mockContext));

expect(mockContext.inject).toHaveBeenCalledTimes(should.inject.length);
for (const inject of should.inject) {
expect(mockContext.inject).toHaveBeenCalledWith(
expect.objectContaining({
value: injections[inject],
value: expect.stringMatching(injections[inject]),
}),
);
}
Expand Down
10 changes: 10 additions & 0 deletions packages/plugins/rum/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { InjectPosition } from '@dd/core/types';
import path from 'path';

import { CONFIG_KEY, PLUGIN_NAME } from './constants';
import { getSourceCodeContextSnippet } from './getSourceCodeContextSnippet';
import { getPrivacyPlugin } from './privacy';
import { getInjectionValue } from './sdk';
import type { RumOptions, RumOptionsWithSdk, RumPublicApi, RumInitConfiguration } from './types';
Expand Down Expand Up @@ -36,6 +37,15 @@ export const getPlugins: GetPlugins = ({ options, context }) => {
return plugins;
}

if (validatedOptions.sourceCodeContext) {
context.inject({
type: 'code',
position: InjectPosition.BEFORE,
injectIntoAllChunks: true,
value: getSourceCodeContextSnippet(validatedOptions.sourceCodeContext),
});
}

// NOTE: These files are built from "@dd/tools/rollupConfig.mjs" and available in the distributed package.
if (validatedOptions.sdk) {
// Inject the SDK from the CDN.
Expand Down
7 changes: 7 additions & 0 deletions packages/plugins/rum/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,16 @@ import type { Assign } from '@dd/core/types';

import type { PrivacyOptions, PrivacyOptionsWithDefaults } from './privacy/types';

export type SourceCodeContextOptions = {
service: string;
version?: string;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❓ question: ‏is there a use case that we want to explicitly support with omitting version?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if you want to enrich the event with the owner (service) but don’t care about the version or unminification?
Do you think we should enforce the version to prepare customers for the unminification use case?

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hum, maybe we add could have everything optional then 🤔
And later add context in the options as well.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, for now the use case is ownership assignment. Since we don’t have other features to inject yet, I’d rather make the field required to prevent empty options. We can definitely reassess once we add new capabilities.

};

export type RumOptions = {
enable?: boolean;
sdk?: SDKOptions;
privacy?: PrivacyOptions;
sourceCodeContext?: SourceCodeContextOptions;
};

export type RumPublicApi = typeof datadogRum;
Expand Down Expand Up @@ -57,6 +63,7 @@ export type RumOptionsWithDefaults = {
enable?: boolean;
sdk?: SDKOptionsWithDefaults;
privacy?: PrivacyOptionsWithDefaults;
sourceCodeContext?: SourceCodeContextOptions;
};

export type RumOptionsWithSdk = Assign<RumOptionsWithDefaults, { sdk: SDKOptionsWithDefaults }>;
33 changes: 32 additions & 1 deletion packages/plugins/rum/src/validate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import { defaultPluginOptions } from '@dd/tests/_jest/helpers/mocks';
import { createFilter } from '@rollup/pluginutils';

import { validatePrivacyOptions } from './validate';
import { validatePrivacyOptions, validateSourceCodeContextOptions } from './validate';

describe('Test privacy plugin option exclude regex', () => {
let filter: (path: string) => boolean;
Expand Down Expand Up @@ -34,3 +34,34 @@ describe('Test privacy plugin option exclude regex', () => {
expect(filter(path)).toBe(expected);
});
});

describe('sourceCodeContext validation', () => {
test('should return empty result when not configured', () => {
const pluginOptions = { ...defaultPluginOptions, rum: {} };
const result = validateSourceCodeContextOptions(pluginOptions);
expect(result.errors).toHaveLength(0);
expect(result.config).toBeUndefined();
});

test('should accept when only service is provided (version optional)', () => {
const pluginOptions = {
...defaultPluginOptions,
rum: { sourceCodeContext: { service: 'checkout' } },
};
const result = validateSourceCodeContextOptions(pluginOptions);
expect(result.errors).toHaveLength(0);
expect(result.config).toEqual(expect.objectContaining({ service: 'checkout' }));
});

test('should error when service is missing', () => {
const pluginOptions = {
...defaultPluginOptions,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
rum: { sourceCodeContext: { version: '1.2.3' } as any },
};
const result = validateSourceCodeContextOptions(pluginOptions);
expect(result.errors).toEqual(
expect.arrayContaining([expect.stringContaining('"rum.sourceCodeContext.service"')]),
);
});
});
37 changes: 36 additions & 1 deletion packages/plugins/rum/src/validate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@ import chalk from 'chalk';

import { CONFIG_KEY, PLUGIN_NAME } from './constants';
import type { PrivacyOptionsWithDefaults } from './privacy/types';
import type { RumOptions, RumOptionsWithDefaults, SDKOptionsWithDefaults } from './types';
import type {
RumOptions,
RumOptionsWithDefaults,
SDKOptionsWithDefaults,
SourceCodeContextOptions,
} from './types';

export const validateOptions = (
options: OptionsWithDefaults,
Expand All @@ -18,9 +23,11 @@ export const validateOptions = (
// Validate and add defaults sub-options.
const sdkResults = validateSDKOptions(options);
const privacyResults = validatePrivacyOptions(options);
const sourceCodeContextResults = validateSourceCodeContextOptions(options);

errors.push(...sdkResults.errors);
errors.push(...privacyResults.errors);
errors.push(...sourceCodeContextResults.errors);

// Throw if there are any errors.
if (errors.length) {
Expand All @@ -34,6 +41,7 @@ export const validateOptions = (
...options[CONFIG_KEY],
sdk: undefined,
privacy: undefined,
sourceCodeContext: undefined,
};

// Fill in the defaults.
Expand All @@ -55,6 +63,10 @@ export const validateOptions = (
);
}

if (sourceCodeContextResults.config) {
toReturn.sourceCodeContext = sourceCodeContextResults.config;
}

return toReturn;
};

Expand Down Expand Up @@ -141,3 +153,26 @@ export const validatePrivacyOptions = (options: Options): ToReturn<PrivacyOption

return toReturn;
};

export const validateSourceCodeContextOptions = (
options: OptionsWithDefaults,
): ToReturn<SourceCodeContextOptions> => {
const red = chalk.bold.red;
const validatedOptions: RumOptions = options[CONFIG_KEY] || {};
const toReturn: ToReturn<SourceCodeContextOptions> = {
errors: [],
};

if (!validatedOptions.sourceCodeContext) {
return toReturn;
}

const cfg: SourceCodeContextOptions = validatedOptions.sourceCodeContext;

if (!cfg?.service || typeof cfg.service !== 'string') {
toReturn.errors.push(`Missing ${red('"rum.sourceCodeContext.service"')}.`);
}

toReturn.config = cfg;
return toReturn;
};
1 change: 1 addition & 0 deletions packages/tests/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@datadog/browser-rum": "6.26.0",
"@datadog/esbuild-plugin": "workspace:*",
"@datadog/rollup-plugin": "workspace:*",
"@datadog/rspack-plugin": "workspace:*",
Expand Down
3 changes: 2 additions & 1 deletion packages/tests/src/_playwright/helpers/buildProject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import typescript from '@rollup/plugin-typescript';
import fs from 'fs';
import path from 'path';

type BuildConfigOverride = Partial<Pick<BundlerConfig, 'entry' | 'plugins'>>;
type BuildConfigOverride = Partial<Pick<BundlerConfig, 'entry' | 'plugins' | 'splitting'>>;

// Build a given project with a given bundler.
const buildProject = async (
Expand Down Expand Up @@ -60,6 +60,7 @@ const buildProject = async (
outDir: path.resolve(cwd, './dist'),
// Use a consistent entry name to avoid injection conflicts
entry: { [bundler]: bundlerEntry },
splitting: buildConfigOverride?.splitting,
plugins: [plugin, ...additionalPlugins],
});

Expand Down
15 changes: 15 additions & 0 deletions packages/tests/src/e2e/sourceCodeContext/project/chunk.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2019-Present Datadog, Inc.

/* eslint-env browser */
import { datadogRum } from '@datadog/browser-rum';

// Used by Playwright tests to ensure the chunk module has been evaluated.
window.chunkLoaded = true;

const $ = document.querySelector.bind(document);

$('#trigger_chunk_error').addEventListener('click', () => {
datadogRum.addError(new Error('chunk_error'));
});
21 changes: 21 additions & 0 deletions packages/tests/src/e2e/sourceCodeContext/project/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" type="image/svg+xml" sizes="21x21" href="data:image/svg+xml," />
<title>Source Code Context Test</title>
</head>

<body>
<h1>Source Code Context Test - {{bundler}}</h1>
<p>Testing source code context injection.</p>

<button id="load_chunk" role="button">Load chunk</button>

<button id="trigger_entry_error" role="button">Entry error</button>
<button id="trigger_chunk_error" role="button">Chunk error</button>

<script type="module" src="./dist/{{bundler}}.js"></script>
</body>
</html>
17 changes: 17 additions & 0 deletions packages/tests/src/e2e/sourceCodeContext/project/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2019-Present Datadog, Inc.

/* eslint-env browser */

import { datadogRum } from '@datadog/browser-rum';

const $ = document.querySelector.bind(document);

$('#trigger_entry_error').addEventListener('click', () => {
datadogRum.addError(new Error('entry_error'));
});

$('#load_chunk').addEventListener('click', async () => {
await import('./chunk.js');
});
Loading