### Custom Test Setup Example Source: https://github.com/datadog/browser-sdk/blob/main/test/e2e/AGENTS.md Shows how to specify a single test setup (e.g., CDN) instead of the default multiple setups. This is not recommended for comprehensive testing. ```typescript createTest('should work with custom setup') .withRum() .withSetup(cdnSetup) // Only test CDN setup .run(async ({ intakeRegistry, flushEvents }) => { // Test code }) ``` -------------------------------- ### Development Server Source: https://github.com/datadog/browser-sdk/blob/main/AGENTS.md Starts the development server for the project. Ensure Yarn is installed and configured. ```bash yarn dev ``` -------------------------------- ### Complete Vue App Setup with RUM and Router Source: https://github.com/datadog/browser-sdk/blob/main/packages/browser-rum-vue/README.md This comprehensive example demonstrates wiring together the RUM SDK initialization, Datadog-wrapped router creation, and Vue application setup, including error handling. ```javascript import { createApp } from 'vue' import { createWebHistory } from 'vue-router' import { datadogRum } from '@datadog/browser-rum' import { vuePlugin, addVueError } from '@datadog/browser-rum-vue' import { createRouter } from '@datadog/browser-rum-vue/vue-router-v4' import App from './App.vue' datadogRum.init({ applicationId: '', clientToken: '', site: 'datadoghq.com', plugins: [vuePlugin({ router: true })], }) const router = createRouter({ history: createWebHistory(), routes: [ { path: '/', component: Home }, { path: '/users', component: Users }, { path: '/users/:id', component: UserDetail }, ], }) const app = createApp(App) app.config.errorHandler = addVueError app.use(router) app.mount('#app') ``` -------------------------------- ### Setup End-to-End Tests Source: https://github.com/datadog/browser-sdk/blob/main/AGENTS.md Installs Playwright and builds test applications, preparing the environment for End-to-End (E2E) testing. ```bash yarn test:e2e:setup ``` -------------------------------- ### Install @datadog/js-core with npm Source: https://github.com/datadog/browser-sdk/blob/main/packages/js-core/README.md Use this command to install the package using npm. ```sh npm install @datadog/js-core ``` -------------------------------- ### Install @datadog/js-core with yarn Source: https://github.com/datadog/browser-sdk/blob/main/packages/js-core/README.md Use this command to install the package using yarn. ```sh yarn add @datadog/js-core ``` -------------------------------- ### Install Dependencies with Yarn Source: https://github.com/datadog/browser-sdk/blob/main/test/apps/react-shopist-like/README.md Installs project dependencies using Yarn. Ensure Node.js 20+ is installed. ```bash yarn install ``` -------------------------------- ### Setup and Run E2E Tests Source: https://github.com/datadog/browser-sdk/blob/main/test/e2e/AGENTS.md Use these commands to set up Playwright browsers, run all E2E tests, or run tests matching a specific pattern. ```bash yarn test:e2e:setup ``` ```bash yarn test:e2e ``` ```bash yarn test:e2e -g "unhandled rejections" ``` -------------------------------- ### Initialize Datadog Logs SDK Source: https://github.com/datadog/browser-sdk/blob/main/sandbox/index.html Call `DD_LOGS.init` with your application credentials and telemetry settings. This setup is necessary for sending logs to Datadog. ```javascript DD_LOGS.init({ clientToken: 'xxx', telemetrySampleRate: 100, telemetryConfigurationSampleRate: 100, telemetryUsageSampleRate: 100, enableExperimentalFeatures: [], proxy: '/proxy', }) ``` -------------------------------- ### Initialize Datadog Debugger Source: https://github.com/datadog/browser-sdk/blob/main/packages/browser-debugger/README.md Initialize the Datadog debugger with essential configuration parameters. Ensure you have the `@datadog/browser-debugger` package installed. ```javascript import { datadogDebugger } from '@datadog/browser-debugger' datadogDebugger.init({ clientToken: '', site: '', service: 'my-web-application', // env: 'production', // version: 'my-deployed-build-version', }) ``` -------------------------------- ### CSV Dependency Entry Example Source: https://github.com/datadog/browser-sdk/blob/main/docs/DEVELOPMENT.md Format for adding new dependencies to the LICENSE-3rdparty.csv file. Use 'dev' prefix for development dependencies and list package names without version numbers. ```csv dev,chokidar,MIT,Copyright (c) 2012 Paul Miller / Elan Shanker ``` -------------------------------- ### Angular Router Integration (NgModule Setup) Source: https://github.com/datadog/browser-sdk/blob/main/packages/browser-rum-angular/README.md Configure Datadog RUM with Angular's NgModule-based setup to track route changes. Ensure `angularPlugin` is initialized with `router: true` and `provideDatadogRouter()` is added to your module's providers. ```typescript import { angularPlugin, provideDatadogRouter } from '@datadog/browser-rum-angular' import { datadogRum } from '@datadog/browser-rum' datadogRum.init({ ... // other init options plugins: [angularPlugin({ router: true })], }) @NgModule({ imports: [RouterModule.forRoot(routes)], providers: [provideDatadogRouter()], }) export class AppModule {} ``` -------------------------------- ### Angular Router Integration (Standalone Setup) Source: https://github.com/datadog/browser-sdk/blob/main/packages/browser-rum-angular/README.md Configure Datadog RUM with Angular's standalone application setup to track route changes. Ensure `angularPlugin` is initialized with `router: true` and `provideDatadogRouter()` is added to your application's providers. ```typescript import { bootstrapApplication } from '@angular/platform-browser' import { provideRouter } from '@angular/router' import { angularPlugin, provideDatadogRouter } from '@datadog/browser-rum-angular' import { datadogRum } from '@datadog/browser-rum' datadogRum.init({ ... // other init options plugins: [angularPlugin({ router: true })], }) bootstrapApplication(AppComponent, { providers: [provideRouter(routes), provideDatadogRouter()], }) ``` -------------------------------- ### Use Option Parameter for Customer Functions Source: https://github.com/datadog/browser-sdk/blob/main/docs/CONVENTIONS.md When defining functions that accept customer-provided callbacks or configurations, use a single options object parameter. This allows for easier addition of new properties in the future without breaking existing implementations. The example shows the preferred method using object destructuring. ```javascript function customerFn({ foo, bar }) {} // OK function customerFn(foo, bar) {} // KO ``` -------------------------------- ### relativeNow Source: https://github.com/datadog/browser-sdk/blob/main/packages/js-core/api/time.api.md Returns the current time relative to the navigation start. ```APIDOC ## relativeNow ### Description Returns the current time as a `RelativeTime` value, measured in milliseconds since the navigation start. ### Method `relativeNow(): RelativeTime` ### Returns A `RelativeTime` object representing the current time relative to navigation start. ``` -------------------------------- ### Conditional Test Execution (Chromium Only) Source: https://github.com/datadog/browser-sdk/blob/main/test/e2e/AGENTS.md Shows how to conditionally skip a test based on the browser name. This example runs only in Chromium, skipping on other browsers. ```typescript createTest('should work in chromium only') .withRum() .run(async ({ browserName }) => { test.skip(browserName !== 'chromium', 'Chromium-only feature') // Test chromium-specific behavior }) ``` -------------------------------- ### Rebuild SDK Applications Source: https://github.com/datadog/browser-sdk/blob/main/test/e2e/AGENTS.md Rebuild the SDK and test applications. Use the --help flag to list available apps or specify individual apps to build. ```bash yarn build:apps --help ``` ```bash yarn build:apps --app vanilla ``` ```bash yarn build:apps --app vanilla --app react-heavy-spa ``` -------------------------------- ### Initialize Datadog RUM SDK Source: https://github.com/datadog/browser-sdk/blob/main/sandbox/index.html Call `DD_RUM.init` with your application credentials and desired configuration. Ensure all required parameters like `clientToken` and `applicationId` are provided. ```javascript DD_RUM.init({ clientToken: 'xxx', applicationId: 'xxx', sessionReplaySampleRate: 100, profilingSampleRate: 100, trackResources: true, trackLongTasks: true, telemetrySampleRate: 100, telemetryConfigurationSampleRate: 100, telemetryUsageSampleRate: 100, enableExperimentalFeatures: [], proxy: '/proxy', }) ``` -------------------------------- ### Build and Develop Browser SDK Extension Source: https://github.com/datadog/browser-sdk/blob/main/developer-extension/README.md Commands to build and run the browser extension in development mode. Assumes you are in the `developer-extension` folder. ```bash yarn build yarn dev ``` -------------------------------- ### Get Type function Source: https://github.com/datadog/browser-sdk/blob/main/packages/js-core/api/util.api.md Determines and returns the type of a given value. Supports primitive types, 'object', 'function', and 'null'. ```typescript // @public export function getType(value: unknown): "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" | "null" | "array"; ``` -------------------------------- ### Initialize Datadog RUM with Nuxt Plugin Source: https://github.com/datadog/browser-sdk/blob/main/packages/browser-rum-nuxt/README.md Create a client-side Nuxt plugin to initialize the Datadog RUM SDK with the nuxtRumPlugin. Using 'enforce: "pre"' captures startup errors early. Passing 'nuxtApp' is recommended for automatic error reporting. ```typescript import { datadogRum } from '@datadog/browser-rum' import { nuxtRumPlugin } from '@datadog/browser-rum-nuxt' import { defineNuxtPlugin, useNuxtApp, useRouter } from 'nuxt/app' export default defineNuxtPlugin({ name: 'datadog-rum', enforce: 'pre', setup() { datadogRum.init({ applicationId: '', clientToken: '', site: 'datadoghq.com', plugins: [ nuxtRumPlugin({ router: useRouter(), nuxtApp: useNuxtApp(), }), ], }) }, }) ``` -------------------------------- ### Basic Script Structure with Utilities Source: https://github.com/datadog/browser-sdk/blob/main/scripts/AGENTS.md All scripts follow a pattern using `runMain()` for async handling and error reporting, `printLog()` for console output, and the `command` template literal for shell commands. Import utilities with the `.ts` extension. ```typescript import { printLog, runMain } from './lib/executionUtils.ts' import { command } from './lib/command.ts' runMain(async () => { printLog('Starting task...') // Script logic here command`yarn build`.run() printLog('Task completed.') }) ``` -------------------------------- ### Get Debug Mode function Source: https://github.com/datadog/browser-sdk/blob/main/packages/js-core/api/util.api.md Retrieves the current debug mode status. Returns true if debug mode is enabled, false otherwise. ```typescript // @public export function getDebugMode(): boolean; ``` -------------------------------- ### Initialize Datadog RUM Source: https://github.com/datadog/browser-sdk/blob/main/packages/browser-rum/README.md Initialize the Datadog RUM SDK with your application's credentials and configuration settings. Ensure you replace placeholder values with your actual IDs and tokens. ```javascript import { datadogRum } from '@datadog/browser-rum' datadogRum.init({ applicationId: '', clientToken: '', site: '', // service: 'my-web-application', // env: 'production', // version: '1.0.0', sessionSampleRate: 100, sessionReplaySampleRate: 100, trackResources: true, trackLongTasks: true, trackUserInteractions: true, }) ``` -------------------------------- ### Initialize Datadog Browser Logs SDK Source: https://github.com/datadog/browser-sdk/blob/main/packages/browser-logs/README.md Initialize the Datadog browser logs SDK with your client token, site, and other configuration options. Ensure `@datadog/browser-logs` is added to your package.json. ```javascript import { datadogLogs } from '@datadog/browser-logs' datadogLogs.init({ clientToken: '', site: '', forwardErrorsToLogs: true, sessionSampleRate: 100, }) ``` -------------------------------- ### Initialize Datadog RUM SDK with Angular Plugin Source: https://github.com/datadog/browser-sdk/blob/main/packages/browser-rum-angular/README.md Import and initialize the Datadog RUM SDK, including the Angular plugin, with your application ID, client token, and site. ```typescript import { datadogRum } from '@datadog/browser-rum' import { angularPlugin } from '@datadog/browser-rum-angular' datadogRum.init({ applicationId: '', clientToken: '', site: 'datadoghq.com', plugins: [angularPlugin()], }) ``` -------------------------------- ### TypeScript 3.8.2 Compatibility Fix Source: https://github.com/datadog/browser-sdk/blob/main/docs/DEVELOPMENT.md Example of fixing TypeScript 3.8.2 compatibility issues by splitting combined type and non-type exports into separate lines. This ensures compatibility with older TypeScript versions. ```typescript // ✅ export type { ProfilingContextManager } from './domain/contexts/profilingContext' export { createProfilingContextManager } from './domain/contexts/profilingContext' ``` -------------------------------- ### Initialize Datadog RUM SDK with Next.js Plugin Source: https://github.com/datadog/browser-sdk/blob/main/packages/browser-rum-nextjs/README.md Initialize the Datadog RUM SDK with the nextjsPlugin and re-export onRouterTransitionStart for client-side navigations in Next.js applications. ```javascript import { datadogRum } from '@datadog/browser-rum' import { nextjsPlugin, onRouterTransitionStart } from '@datadog/browser-rum-nextjs' export { onRouterTransitionStart } datadogRum.init({ applicationId: '', clientToken: '', site: 'datadoghq.com', plugins: [nextjsPlugin()], }) ``` -------------------------------- ### Initialize Datadog RUM SDK with Next.js Plugin Source: https://github.com/datadog/browser-sdk/blob/main/packages/browser-rum-nextjs/README.md Initialize the Datadog RUM SDK in your Next.js project. The `onRouterTransitionStart` export is not needed for Pages Router. ```javascript import { datadogRum } from '@datadog/browser-rum' import { nextjsPlugin } from '@datadog/browser-rum-nextjs' datadogRum.init({ applicationId: '', clientToken: '', site: 'datadoghq.com', plugins: [nextjsPlugin()], }) ``` -------------------------------- ### Initialize Datadog RUM SDK with Vue Plugin Source: https://github.com/datadog/browser-sdk/blob/main/packages/browser-rum-vue/README.md Initialize the Datadog RUM SDK and include the Vue plugin in your main application file. Ensure you replace placeholders with your actual application ID and client token. ```javascript import { datadogRum } from '@datadog/browser-rum' import { vuePlugin } from '@datadog/browser-rum-vue' datadogRum.init({ applicationId: '', clientToken: '', site: 'datadoghq.com', plugins: [vuePlugin()], }) ``` -------------------------------- ### Add datadogInit Component to Salesforce FlexiPage Source: https://github.com/datadog/browser-sdk/blob/main/packages/browser-rum-slim/src/salesforce/README.md Configure the datadogInit component within your Salesforce flexipage metadata file. Ensure 'eager' is set to 'true' for immediate initialization. ```xml applicationId YOUR_APPLICATION_ID clientToken YOUR_CLIENT_TOKEN site datadoghq.com service your-service-name env production eager decorator true datadogInit datadogInit utilityItems Region ``` -------------------------------- ### Initialize RUM SDK with Router Tracking Source: https://github.com/datadog/browser-sdk/blob/main/packages/browser-rum-vue/README.md Enable router tracking by setting the `router: true` option during RUM SDK initialization. This snippet shows the necessary imports and configuration. ```javascript import { datadogRum } from '@datadog/browser-rum' import { vuePlugin } from '@datadog/browser-rum-vue' datadogRum.init({ applicationId: '', clientToken: '', site: 'datadoghq.com', plugins: [vuePlugin({ router: true })], }) ``` -------------------------------- ### Preview Production Build with Yarn Source: https://github.com/datadog/browser-sdk/blob/main/test/apps/react-shopist-like/README.md Previews the production build of the application locally. This allows you to test the production version before deployment. ```bash yarn preview ``` -------------------------------- ### Build Test Applications Source: https://github.com/datadog/browser-sdk/blob/main/AGENTS.md Builds the test applications used for End-to-End (E2E) and performance testing. This prepares the testing environment. ```bash yarn build:apps ``` -------------------------------- ### createDisplay Source: https://github.com/datadog/browser-sdk/blob/main/packages/js-core/api/util.api.md Creates a display object with methods for logging messages with a specific prefix. ```APIDOC ## createDisplay ### Description Creates a display object with methods for logging messages with a specific prefix. ### Signature ```typescript function createDisplay(prefix: string): Display; ``` ### Parameters * **prefix** (string) - The prefix to prepend to all log messages. ### Returns * Display - An object with `log`, `debug`, `info`, `warn`, and `error` methods. ``` -------------------------------- ### Dependency Injection (OK) Source: https://github.com/datadog/browser-sdk/blob/main/docs/CONVENTIONS.md Favor passing dependencies as parameters to modules. This improves readability, testability, and extensibility by allowing easy substitution of dependencies. ```typescript // boot myDependency = startMyDependency() myOtherDependency = getOrCreateMyDependency() myModule = startMyModule(myDependency, myOtherDependency) // myModule.ts function startMyModule(myDependency, myOtherDependency) { myDependency.interact() myOtherDependency.interact() } ``` -------------------------------- ### Load Unpacked Extension in Chrome Source: https://github.com/datadog/browser-sdk/blob/main/developer-extension/README.md Instructions for loading the unpacked browser extension into Chrome. Requires Developer Mode to be enabled. ```bash Load unpacked ``` -------------------------------- ### Run Unit Tests Source: https://github.com/datadog/browser-sdk/blob/main/AGENTS.md Executes all unit tests for the project. This command is crucial for verifying the correctness of individual code components. ```bash yarn test:unit ``` -------------------------------- ### Build All Packages Source: https://github.com/datadog/browser-sdk/blob/main/AGENTS.md Compiles all packages within the monorepo. This command is essential for preparing the project for testing or deployment. ```bash yarn build ``` -------------------------------- ### LWC Datadog Initialization Component Metadata Source: https://github.com/datadog/browser-sdk/blob/main/packages/browser-rum-slim/src/salesforce/README.md Metadata file for the LWC DatadogInit component, exposing it to the Salesforce utility bar with configurable properties. ```xml 59.0 true lightning__UtilityBar ``` -------------------------------- ### originalConsoleMethods Source: https://github.com/datadog/browser-sdk/blob/main/packages/js-core/api/util.api.md Stores the original console methods before they might have been overridden. ```APIDOC ## originalConsoleMethods ### Description Stores the original console methods before they might have been overridden. ### Type ```typescript const originalConsoleMethods: Display; ``` ### Usage This constant can be used to restore or access the default console logging behavior. ``` -------------------------------- ### Format Code Source: https://github.com/datadog/browser-sdk/blob/main/AGENTS.md Automatically formats the code according to project style guidelines. This command helps maintain code consistency. ```bash yarn format ``` -------------------------------- ### Create Monitor Instance Source: https://github.com/datadog/browser-sdk/blob/main/packages/js-core/api/monitor.api.md Use this function to create a new monitor instance. It requires a display object and an error collection callback. ```typescript // @public export function createMonitor(display: Display, onMonitorErrorCollected: (error: unknown) => void): Monitor; ``` -------------------------------- ### Basic E2E Test Structure Source: https://github.com/datadog/browser-sdk/blob/main/test/e2e/AGENTS.md Demonstrates the fundamental structure of an E2E test using the `createTest()` builder pattern. Initializes the RUM SDK and runs a test scenario. ```typescript import { test, expect } from '@playwright/test' import { createTest } from '../lib/framework' test.describe('feature name', () => { createTest('should track user interactions') .withRum() // Initialize RUM SDK .run(async ({ intakeRegistry, flushEvents, page }) => { // Interact with page await page.click('button') // Wait for SDK to flush events await flushEvents() // Assert on captured events expect(intakeRegistry.rumEvents).toHaveLength(1) expect(intakeRegistry.rumEvents[0].type).toBe('action') }) }) ``` -------------------------------- ### Class vs. Function for Minification Source: https://github.com/datadog/browser-sdk/blob/main/docs/CONVENTIONS.md Demonstrates how class syntax can lead to larger minified code compared to using functions and closures. Prefer functions for better minification results. ```javascript class Batch { pendingMessages = [] add(message) { this.pendingMessages.push(message) } } // bundled as (64 bytes): class s { pendingMessages = [] add(s) { this.pendingMessages.push(s) } } ``` ```javascript function createBatch() { const pendingMessages = [] return { add(message) { pendingMessages.push(message) }, } } // bundled as (50 bytes): function n() { const n = [] return { add(t) { n.push(t) }, } } ``` -------------------------------- ### Run Specific Unit Test File Source: https://github.com/datadog/browser-sdk/blob/main/AGENTS.md Executes a specific unit test file. Use this to focus testing on a particular feature or bug fix. ```bash yarn test:unit --spec packages/browser-core/src/path/to/feature.spec.ts ``` -------------------------------- ### globalConsole Source: https://github.com/datadog/browser-sdk/blob/main/packages/js-core/api/util.api.md Provides access to the global `Console` object. ```APIDOC ## globalConsole ### Description Provides access to the global `Console` object. ### Type ```typescript const globalConsole: Console; ``` ### Usage This constant can be used to interact with the browser's built-in console API. ``` -------------------------------- ### Datadog Browser SDK Package Dependencies Source: https://github.com/datadog/browser-sdk/blob/main/docs/ARCHITECTURE.md Visual representation of the monorepo package structure and their interdependencies. ```mermaid graph TD core["@datadog/browser-core\n(shared utilities)"] rum-core["@datadog/browser-rum-core\n(core RUM)"] rum["@datadog/browser-rum\n(full RUM)"] rum-slim["@datadog/browser-rum-slim\n(lightweight RUM)"] rum-react["@datadog/browser-rum-react\n(React integration)"] logs["@datadog/browser-logs"] worker["@datadog/browser-worker"] core --> rum-core core --> logs rum-core --> rum rum-core --> rum-slim rum --> rum-react ``` -------------------------------- ### LWC Datadog Initialization Component Source: https://github.com/datadog/browser-sdk/blob/main/packages/browser-rum-slim/src/salesforce/README.md JavaScript for an LWC component that initializes Datadog RUM and tracks page views. ```html ``` ```javascript import { LightningElement, api, wire } from 'lwc' import { NavigationMixin, CurrentPageReference } from 'lightning/navigation' import datadogRumSlim from '@salesforce/resourceUrl/datadog_rum_slim' import { loadScript } from 'lightning/platformResourceLoader' let datadogInitialization let lastStartedUrl export default class DatadogInit extends NavigationMixin(LightningElement) { @api applicationId @api clientToken @api site @api service @api env connectedCallback() { this.initialize() } @wire(CurrentPageReference) handleCurrentPageReference(pageReference) { if (!pageReference) { return } this.initialize() if (window.DD_RUM) { this.startViewForPageReference(pageReference) } } startViewForPageReference(pageReference) { const urlPromise = this[NavigationMixin.GenerateUrl](pageReference) urlPromise.then((url) => { if (url === lastStartedUrl) { return } lastStartedUrl = url const absoluteUrl = new URL(url, window.location.origin).href window.DD_RUM.startView({ name: url, url: absoluteUrl }) }) } initialize() { if (!datadogInitialization) { datadogInitialization = this.loadDatadogRum() } } loadDatadogRum() { return loadScript(this, datadogRumSlim).then(() => { const initConfig = { applicationId: this.applicationId, clientToken: this.clientToken, env: this.env, service: this.service, site: this.site, trackViewsManually: true, trackEarlyRequests: true, trackLongTasks: true, trackResources: true, trackUserInteractions: true, } window.DD_RUM.init(initConfig) lastStartedUrl = window.location.pathname + window.location.search + window.location.hash window.DD_RUM.startView({ name: lastStartedUrl, url: window.location.href, }) }) } } ``` -------------------------------- ### Datadog RUM Slim Static Resource Metadata Source: https://github.com/datadog/browser-sdk/blob/main/packages/browser-rum-slim/src/salesforce/README.md XML metadata file for the datadog-rum-slim.js static resource in Salesforce. ```xml Public application/javascript ``` -------------------------------- ### Display Source: https://github.com/datadog/browser-sdk/blob/main/packages/js-core/api/util.api.md An interface representing a set of console logging methods. ```APIDOC ## Display ### Description An interface representing a set of console logging methods. ### Properties * **log**: `typeof console.log` - Logs a message to the console. * **debug**: `typeof console.debug` - Logs a debug message to the console. * **info**: `typeof console.info` - Logs an informational message to the console. * **warn**: `typeof console.warn` - Logs a warning message to the console. * **error**: `typeof console.error` - Logs an error message to the console. ``` -------------------------------- ### Create Vue Router with Datadog Wrapper Source: https://github.com/datadog/browser-sdk/blob/main/packages/browser-rum-vue/README.md Replace Vue Router's native `createRouter` with the Datadog wrapper from `@datadog/browser-rum-vue/vue-router-v4`. This ensures route changes are correctly tracked. ```javascript import { createWebHistory } from 'vue-router' import { createRouter } from '@datadog/browser-rum-vue/vue-router-v4' const router = createRouter({ history: createWebHistory(), routes: [ { path: '/', component: Home }, { path: '/users', component: Users }, { path: '/users/:id', component: UserDetail }, ], }) ``` -------------------------------- ### Statically Import Generic Utilities Source: https://github.com/datadog/browser-sdk/blob/main/docs/CONVENTIONS.md It is acceptable to statically import generic utility functions. ```typescript import { find } from 'utils' ``` -------------------------------- ### Avoid Global Polyfills Source: https://github.com/datadog/browser-sdk/blob/main/docs/CONVENTIONS.md Demonstrates the incorrect way to overwrite global APIs and the correct way to use internal utilities to prevent conflicts with existing polyfills. ```typescript window.URL = window.URL || buildUrl(url: string, base?: string) { ... } ``` ```typescript export function buildUrl(url: string, base?: string) { ... } ``` -------------------------------- ### Configure Datadog RUM SDK in Vue Source: https://github.com/datadog/browser-sdk/blob/main/test/apps/vue-router-app/index.html Set up the RUM_CONFIGURATION object with your Datadog application ID, client token, site, and enable user interaction tracking. This configuration is typically done once when initializing your application. ```javascript window.RUM_CONFIGURATION = { applicationId: 'xxx', clientToken: 'xxx', site: 'datadoghq.com', trackUserInteractions: true, } ``` -------------------------------- ### createMonitor Source: https://github.com/datadog/browser-sdk/blob/main/packages/js-core/api/monitor.api.md Creates a new Monitor instance. This instance can be used to wrap functions for monitoring and error collection. ```APIDOC ## createMonitor ### Description Creates a new Monitor instance that can be used to wrap functions for monitoring and error collection. ### Signature ```typescript createMonitor(display: Display, onMonitorErrorCollected: (error: unknown) => void): Monitor ``` ### Parameters * **display** (Display) - An object representing the display context for monitoring. * **onMonitorErrorCollected** ((error: unknown) => void) - A callback function that is invoked when an error is collected by the monitor. ### Returns * Monitor - A Monitor instance with methods for monitoring functions and reporting errors. ``` -------------------------------- ### Node.js Import Best Practices Source: https://github.com/datadog/browser-sdk/blob/main/scripts/AGENTS.md Use modern TypeScript and latest Node.js APIs. Prefer built-in Node.js modules over dependencies and always use the `node:` prefix for Node.js imports. ```typescript // ✅ Good - built-in Node.js APIs import { globSync } from 'node:fs' import { parseArgs } from 'node:util' import * as path from 'node:path' // ❌ Bad - unnecessary dependencies import glob from 'glob' import minimist from 'minimist' ``` -------------------------------- ### Datadog RUM SDK Data Processing Flow Source: https://github.com/datadog/browser-sdk/blob/main/docs/ARCHITECTURE.md High-level flowchart illustrating the RUM SDK data processing stages from initialization to batching. ```mermaid flowchart TD startRum["startRum\n(boot)"] collections["collections\n(views, actions, resources, errors…)"] assembly["assembly\n(adds common attributes)"] batch["batch\n(in-memory buffer)"] startRum --> collections collections -->|"raw RUM events"| assembly assembly -->|"enriched events"| batch ``` -------------------------------- ### ConsoleApiName Source: https://github.com/datadog/browser-sdk/blob/main/packages/js-core/api/util.api.md Defines the string literals for standard console API method names. ```APIDOC ## ConsoleApiName ### Description Defines the string literals for standard console API method names. ### Type ```typescript export type ConsoleApiName = "log" | "debug" | "info" | "warn" | "error"; ``` ### Usage This type can be used to ensure that a string is one of the valid console method names. ``` -------------------------------- ### Create a Hook Source: https://github.com/datadog/browser-sdk/blob/main/packages/js-core/api/assembly.api.md Use `createHook` to create a new hook instance. This function is used to manage callbacks and trigger events within the system. ```typescript // @public export function createHook(): Hook; ``` -------------------------------- ### Run Unit Tests with Specific Seed Source: https://github.com/datadog/browser-sdk/blob/main/AGENTS.md Runs unit tests using a specific seed for reproducible test results. Useful for debugging intermittent test failures. ```bash yarn test:unit --seed 123 ``` -------------------------------- ### Check JS Core API Surface Source: https://github.com/datadog/browser-sdk/blob/main/packages/js-core/AGENTS.md Verify the API surface of the JS Core package hasn't changed. This command is typically run in CI. ```bash yarn workspace @datadog/js-core build yarn api:check ``` -------------------------------- ### Send Custom Log Entries Source: https://github.com/datadog/browser-sdk/blob/main/packages/browser-logs/README.md Send custom log entries with optional context to Datadog after the SDK is initialized. This includes logging informational messages and capturing errors. ```javascript import { datadogLogs } from '@datadog/browser-logs' datadogLogs.logger.info('Button clicked', { name: 'buttonName', id: 123 }) try { ... throw new Error('Wrong behavior') ... } catch (ex) { datadogLogs.logger.error('Error occurred', { team: 'myTeam' }, ex) } ``` -------------------------------- ### Search RUM Events with Key-Value Syntax Source: https://github.com/datadog/browser-sdk/blob/main/developer-extension/README.md Use `key:value` syntax for searching RUM events. Supports searching within RUM event structures. Multiple conditions can be combined with whitespace. ```text type:view application.id:2 action.target.name:my_action_name ``` -------------------------------- ### Linting Source: https://github.com/datadog/browser-sdk/blob/main/AGENTS.md Runs the linter to check for code style violations and potential issues. Ensures code consistency across the project. ```bash yarn lint ``` -------------------------------- ### Configure Service Worker with Logs SDK Source: https://github.com/datadog/browser-sdk/blob/main/test/e2e/AGENTS.md Use `createWorker` to initialize the Logs SDK within a service worker for testing. This snippet demonstrates forwarding all console logs to the worker. ```typescript import { createTest, createWorker } from '../lib/framework' createTest('worker with logs') .withWorker(createWorker().withLogs({ forwardConsoleLogs: 'all' })) .run(async ({ evaluateInWorker, flushEvents, intakeRegistry }) => { await evaluateInWorker(() => { DD_LOGS!.logger.log('hello from worker') }) await flushEvents() expect(intakeRegistry.logsEvents[0].message).toBe('hello from worker') }) ``` -------------------------------- ### Run End-to-End Tests Source: https://github.com/datadog/browser-sdk/blob/main/AGENTS.md Executes all End-to-End (E2E) tests for the project using Playwright. This verifies the application's behavior from a user's perspective. ```bash yarn test:e2e ``` -------------------------------- ### Statically Import Sub-Behaviors Source: https://github.com/datadog/browser-sdk/blob/main/docs/CONVENTIONS.md When splitting a file for maintenance, it is acceptable to statically import different parts of the module. ```typescript import { mySubBehavior } from './mySubBehavior' import { myOtherSubBehavior } from './myOtherSubBehavior' function startMyModule() { mySubBehavior() myOtherSubBehavior() } ``` -------------------------------- ### Validating Console Logs with Handler Source: https://github.com/datadog/browser-sdk/blob/main/test/e2e/AGENTS.md Demonstrates how to test console logs when the Logs SDK is configured to use the 'console' handler. It checks for specific warning messages in the browser's console output. ```typescript createTest('should display logs in console when using console handler') .withLogs() .run(async ({ intakeRegistry, flushEvents, page, withBrowserLogs }) => { await page.evaluate(() => { window.DD_LOGS!.logger.setHandler('console') window.DD_LOGS!.logger.warn('hello') }) await flushEvents() // Check console logs withBrowserLogs((logs) => { expect(logs).toHaveLength(1) expect(logs[0].level).toBe('warning') expect(logs[0].message).toEqual(expect.stringContaining('hello')) }) }) ``` -------------------------------- ### Include DatadogAppRouter in Root Layout Source: https://github.com/datadog/browser-sdk/blob/main/packages/browser-rum-nextjs/README.md Include the DatadogAppRouter component in your root layout to enable RUM monitoring for your Next.js application. ```tsx import { DatadogAppRouter } from '@datadog/browser-rum-nextjs' export default function RootLayout({ children }: { children: React.ReactNode }) { return ( {children} ) } ``` -------------------------------- ### Statically Expose Dependency Part (KO) Source: https://github.com/datadog/browser-sdk/blob/main/docs/CONVENTIONS.md Avoid statically exposing a part of a dependency. This makes it difficult to manage and test dependencies. ```typescript // boot myDependency = startMyDependency() myModule = startMyModule() // myModule.ts import { interactWithMyDependency } from './myDependency' function startMyModule() { interactWithMyDependency() } ``` -------------------------------- ### clocksOrigin Source: https://github.com/datadog/browser-sdk/blob/main/packages/js-core/api/time.api.md Retrieves the origin time state, which is the time when the clocks were first initialized. ```APIDOC ## clocksOrigin ### Description Returns the origin time state, representing the initial time when the clocks were set up. ### Method `clocksOrigin(): ClocksState` ### Returns An object of type `ClocksState` containing `relative` and `timeStamp` at the origin. ``` -------------------------------- ### Statically Retrieve Dependency (KO) Source: https://github.com/datadog/browser-sdk/blob/main/docs/CONVENTIONS.md It is not recommended to statically retrieve a dependency when two modules have a dependency relationship. This hinders testability and extensibility. ```typescript import { getOrCreateMyDependency } from './myDependency' function startMyModule() { myDependency = getOrCreateMyDependency() myDependency.interact() } ``` -------------------------------- ### Check TypeScript 3.8.2 Compatibility Source: https://github.com/datadog/browser-sdk/blob/main/docs/DEVELOPMENT.md Command to reproduce TypeScript 3.8.2 compatibility issues locally. This helps in identifying and fixing syntax errors that are not supported by older TypeScript versions. ```bash yarn test:compat:tsc ``` -------------------------------- ### Create Display function Source: https://github.com/datadog/browser-sdk/blob/main/packages/js-core/api/util.api.md Creates a display object with methods for logging messages. The display object mirrors the console API. ```typescript // @public export function createDisplay(prefix: string): Display; ``` -------------------------------- ### Access Captured Events with IntakeRegistry Source: https://github.com/datadog/browser-sdk/blob/main/test/e2e/AGENTS.md The `intakeRegistry` object captures all events sent by the SDK, allowing for inspection of RUM, Logs, and Telemetry events, as well as raw HTTP requests. ```typescript intakeRegistry.rumEvents // All RUM events intakeRegistry.rumViewEvents // View events intakeRegistry.rumActionEvents // Action events intakeRegistry.rumErrorEvents // Error events intakeRegistry.rumResourceEvents // Resource events intakeRegistry.rumLongTaskEvents // Long task events intakeRegistry.logsEvents // All log events intakeRegistry.telemetryEvents // Telemetry events intakeRegistry.telemetryErrorEvents // Telemetry errors intakeRegistry.rumRequests // Raw HTTP requests (RUM) intakeRegistry.logsRequests // Raw HTTP requests (Logs) ``` -------------------------------- ### Monitor Interface Source: https://github.com/datadog/browser-sdk/blob/main/packages/js-core/api/monitor.api.md The Monitor interface provides methods for managing monitored functions and reporting errors. ```APIDOC ## Monitor Interface ### Description Represents an instance capable of monitoring function calls and collecting errors. ### Methods #### callMonitored Wraps a function to execute it within the monitoring context. It captures the return value of the function. * **Signature**: ```typescript callMonitored unknown>(fn: T, context: ThisParameterType, args: Parameters): ReturnType | undefined; callMonitored unknown>(fn: T): ReturnType | undefined; ``` #### monitor Applies monitoring to a given function, returning a new function that includes monitoring logic. * **Signature**: ```typescript monitor unknown>(fn: T): T; ``` #### monitored A decorator that can be applied to class methods to enable monitoring. * **Signature**: ```typescript monitored unknown>(_: any, __: string, descriptor: TypedPropertyDescriptor): void; ``` #### monitorError Manually reports an error to the monitor. * **Signature**: ```typescript monitorError(e: unknown): void; ``` ``` -------------------------------- ### CSP Trusted Site for Datadog RUM Source: https://github.com/datadog/browser-sdk/blob/main/packages/browser-rum-slim/src/salesforce/README.md XML metadata file to configure a CSP trusted site for Datadog's browser intake endpoint. ```xml false false All Datadog browser RUM intake for US1 https://browser-intake-datadoghq.com true true false false false false false ``` -------------------------------- ### dateNow Source: https://github.com/datadog/browser-sdk/blob/main/packages/js-core/api/time.api.md Returns the current time in milliseconds since the Unix epoch. ```APIDOC ## dateNow ### Description Returns the current time as a number representing milliseconds since the Unix epoch. ### Method `dateNow(): number` ### Returns A number representing the current time in milliseconds. ``` -------------------------------- ### createHook Source: https://github.com/datadog/browser-sdk/blob/main/packages/js-core/api/assembly.api.md Creates a new hook with associated registration and triggering functions. Hooks allow for managing callbacks that can be registered and triggered with specific parameters, potentially returning DISCARDED or SKIPPED. ```APIDOC ## createHook() ### Description Creates a hook that allows registering callbacks and triggering them with parameters. The callbacks can return `DISCARDED` or `SKIPPED`. ### Method `createHook()` ### Returns A `Hook` object with `register` and `trigger` methods. ``` -------------------------------- ### Display interface Source: https://github.com/datadog/browser-sdk/blob/main/packages/js-core/api/util.api.md Defines the structure of a display object, which includes standard console logging methods. ```typescript // @public export interface Display { // (undocumented) debug: typeof console.debug; // (undocumented) error: typeof console.error; // (undocumented) info: typeof console.info; // (undocumented) log: typeof console.log; // (undocumented) warn: typeof console.warn; } ``` -------------------------------- ### Datadog RUM SDK Data Transfer Flow Source: https://github.com/datadog/browser-sdk/blob/main/docs/ARCHITECTURE.md Flowchart detailing the data transfer process from the in-memory batch to the Datadog intake. ```mermaid flowchart TD batch["batch\n(in-memory buffer)"] httpRetry["httpRetry\n(retry & throttle)"] httpRequest["httpRequest\n(fetch / XHR)"] intake["Datadog intake"] batch -->|"flush"| httpRetry httpRetry -->|"send"| httpRequest httpRequest --> intake ``` -------------------------------- ### toServerDuration Source: https://github.com/datadog/browser-sdk/blob/main/packages/js-core/api/time.api.md Converts a Duration to a ServerDuration. ```APIDOC ## toServerDuration ### Description Converts a `Duration` (in milliseconds) to a `ServerDuration` (in nanoseconds). ### Method `toServerDuration(duration: Duration): ServerDuration` `toServerDuration(duration: Duration | undefined): ServerDuration | undefined` ### Parameters - **duration**: The `Duration` value to convert. ### Returns A `ServerDuration` object representing the duration in nanoseconds. ``` -------------------------------- ### Original Console Methods object Source: https://github.com/datadog/browser-sdk/blob/main/packages/js-core/api/util.api.md Stores the original console methods before they might have been overridden. Useful for restoring or comparing console behavior. ```typescript // @public export const originalConsoleMethods: Display; ```