### Install Dependencies and Run Tests Source: https://github.com/mparticle/mparticle-web-sdk/blob/master/CONTRIBUTING.md Installs project dependencies and runs the mParticle bundles and tests. Ensure you have npm installed. ```bash $ npm install $ npm run test // builds mparticle bundles and runs tests ``` -------------------------------- ### Install mParticle Web SDK via NPM Source: https://github.com/mparticle/mparticle-web-sdk/blob/master/README.md To self-host the mParticle SDK, add it to your project's dependencies using NPM. This command installs the latest version of the SDK. ```bash npm install @mparticle/web-sdk ``` -------------------------------- ### Initialize and Get SDK Instance Source: https://github.com/mparticle/mparticle-web-sdk/blob/master/AGENTS.md Use `mParticle.init` to initialize an SDK instance with an API key and configuration. `mParticle.getInstance` retrieves an existing instance, defaulting to 'default_instance' if none is specified. ```javascript mParticle.init(apiKey, config, instanceName?) mParticle.getInstance(instanceName?) ``` -------------------------------- ### Karma Test Setup Patterns Source: https://github.com/mparticle/mparticle-web-sdk/blob/master/AGENTS.md Key patterns for Karma browser integration tests, including state resetting, mocking HTTP, and using helper functions. ```javascript // Reset state with `mParticle._resetForTests(MPConfig)` in `beforeEach` // Mock HTTP with fetch-mock/esm/client // Use `waitForCondition()` helper from `test/src/config/utils.ts` for async operations // Chai assertions: `expect(...).to.equal()`, `expect(...).to.be.ok`, `expect(...).to.have.keys()` // Sinon for spies/stubs ``` -------------------------------- ### Jest Test Setup Patterns Source: https://github.com/mparticle/mparticle-web-sdk/blob/master/AGENTS.md Key patterns for Jest TypeScript unit tests, including mocking timers, global fetch, and creating mock instances. ```javascript // Mock timers with `jest.useFakeTimers()` and `jest.advanceTimersByTime()` // Mock global.fetch with `jest.fn().mockResolvedValue()` // Create mock mpInstance objects as needed // Jest matchers: `toBe()`, `toEqual()`, `toBeDefined()`, `toHaveBeenCalled()` ``` -------------------------------- ### Conventional Commits Examples Source: https://github.com/mparticle/mparticle-web-sdk/blob/master/AGENTS.md Examples of valid conventional commit messages for different types of changes, including features, fixes, documentation, and tests. ```text feat: add consent state filtering for forwarders fix: prevent duplicate events in batch upload docs: update API reference for eCommerce methods test: add cross-browser tests for identity API ``` -------------------------------- ### Log an Event with mParticle SDK Source: https://github.com/mparticle/mparticle-web-sdk/blob/master/README.md After initializing the SDK, you can log events using the `logEvent` method. This example shows how to log a 'Play Movie' event with custom attributes. ```javascript mParticle.logEvent('Play Movie', mParticle.EventType.Navigation, { movie_length: '127 minutes', rating: 'PG', }); ``` -------------------------------- ### Session Management Source: https://context7.com/mparticle/mparticle-web-sdk/llms.txt Sets session-scoped key-value attributes, manually starts a new session, or explicitly ends the current session. ```APIDOC ## Session Management — `setSessionAttribute()` / `startNewSession()` / `endSession()` Sets session-scoped key-value attributes, manually starts a new session, or explicitly ends the current session. ```javascript // Attach metadata to the current session mParticle.setSessionAttribute('entry_page', '/home'); mParticle.setSessionAttribute('ab_test_group', 'control'); mParticle.setSessionAttribute('referral_code', 'SUMMER25'); // Force a new session (e.g., after re-login or significant context change) mParticle.startNewSession(); // Explicitly end the session (e.g., on explicit logout flow) mParticle.endSession(); ``` ``` -------------------------------- ### Session Management with setSessionAttribute, startNewSession, endSession Source: https://context7.com/mparticle/mparticle-web-sdk/llms.txt Manages session-scoped attributes, manually starts new sessions, or explicitly ends the current session. Useful for tracking session-specific metadata or controlling session lifecycle. ```javascript // Attach metadata to the current session mParticle.setSessionAttribute('entry_page', '/home'); mParticle.setSessionAttribute('ab_test_group', 'control'); mParticle.setSessionAttribute('referral_code', 'SUMMER25'); // Force a new session (e.g., after re-login or significant context change) mParticle.startNewSession(); // Explicitly end the session (e.g., on explicit logout flow) mParticle.endSession(); ``` -------------------------------- ### Conventional Commits Breaking Change Example Source: https://github.com/mparticle/mparticle-web-sdk/blob/master/AGENTS.md Indicate breaking changes in commit messages using the 'BREAKING CHANGE' footer. This example shows a breaking change in the identity API. ```text feat: new API for identity management BREAKING CHANGE: Identity.login() now requires a callback parameter ``` -------------------------------- ### Set and Get Integration Attributes Source: https://context7.com/mparticle/mparticle-web-sdk/llms.txt Use `setIntegrationAttribute()` to set key-value pairs for specific integrations (identified by mParticle integration ID) and `getIntegrationAttributes()` to retrieve them. Pass `null` to `setIntegrationAttribute()` to clear attributes for an integration. ```javascript // Set integration attributes for a specific integration (by its mParticle integration ID) // e.g., integration ID 28 = Google Analytics mParticle.setIntegrationAttribute(28, { 'clientId': 'GA1.2.123456789.1620000000', }); // Set for multiple integrations mParticle.setIntegrationAttribute(64, { 'braze_id': 'braze-user-abc123' }); // Read back attributes const gaAttrs = mParticle.getIntegrationAttributes(28); console.log('GA client ID:', gaAttrs['clientId']); // Clear integration attributes mParticle.setIntegrationAttribute(28, null); ``` -------------------------------- ### Initialize and Use Multiple SDK Instances Source: https://context7.com/mparticle/mparticle-web-sdk/llms.txt Supports multiple named instances for multi-brand or multi-workspace deployments. Each instance maintains independent state and configuration. ```javascript // Initialize a second instance named 'brand_b' mParticle.init('API_KEY_BRAND_B', { isDevelopmentMode: false, appName: 'Brand B', identityCallback: function(result) { console.log('Brand B user:', result.getUser()?.getMPID()); }, }, 'brand_b'); // Use the named instance explicitly const brandBInstance = mParticle.getInstance('brand_b'); brandBInstance.logEvent('Product Viewed', mParticle.EventType.Navigation, { product_id: 'B-SKU-001', }); brandBInstance.eCommerce.logProductAction( mParticle.ProductActionType.ViewDetail, product1 ); // Default instance still uses shorthand mParticle.logPageView('Home'); ``` -------------------------------- ### Initialization — mParticle.init(apiKey, config) Source: https://context7.com/mparticle/mparticle-web-sdk/llms.txt Initializes the SDK with your API key and configuration object. This must be called before any other SDK method. ```APIDOC ## Initialization — mParticle.init(apiKey, config) ### Description Initializes the SDK, fetches server-side configuration (kit settings, data plans, feature flags), restores persisted user identity, fires the `identityCallback`, and drains any pre-initialization event queue. Must be called before any other SDK method. ### Method `mParticle.init(apiKey, config)` ### Parameters #### Path Parameters - **apiKey** (string) - Required - Your mParticle API key. - **config** (object) - Required - Configuration object for the SDK. - **isDevelopmentMode** (boolean) - Optional - Set to `false` in production. - **logLevel** (string) - Optional - Controls the verbosity of logs (`'verbose'`, `'warning'`, `'none'`). - **appName** (string) - Optional - The name of your application. - **appVersion** (string) - Optional - The version of your application. - **dataPlan** (object) - Optional - Configuration for data plan adherence. - **planId** (string) - Required if `dataPlan` is provided - The ID of the data plan. - **planVersion** (number) - Required if `dataPlan` is provided - The version of the data plan. - **identifyRequest** (object) - Optional - Initial user identity information. - **userIdentities** (object) - Optional - User identity key-value pairs (e.g., `email`, `customerid`). - **identityCallback** (function) - Optional - A callback function executed after identity resolution. ### Request Example ```javascript import mParticle from '@mparticle/web-sdk'; const mParticleConfig = { isDevelopmentMode: true, logLevel: 'verbose', appName: 'My App', appVersion: '1.2.3', dataPlan: { planId: 'my_data_plan', planVersion: 2, }, identifyRequest: { userIdentities: { email: 'user@example.com', customerid: 'cust_123', }, }, identityCallback: function(result) { if (result.getUser()) { const user = result.getUser(); console.log('Identified user MPID:', user.getMPID()); user.setUserAttribute('plan_tier', 'premium'); } }, }; mParticle.init('YOUR_API_KEY', mParticleConfig); // Check initialization status if (mParticle.isInitialized()) { console.log('SDK version:', mParticle.getVersion()); console.log('Environment:', mParticle.getEnvironment()); } ``` ``` -------------------------------- ### Initialize SDK via CDN Snippet Source: https://context7.com/mparticle/mparticle-web-sdk/llms.txt Loads the SDK asynchronously via CDN snippet in non-npm environments. Method stubs are pre-populated, allowing immediate API calls before the bundle loads. ```html ``` -------------------------------- ### Production Build Commands Source: https://github.com/mparticle/mparticle-web-sdk/blob/master/AGENTS.md Commands for creating production-ready builds of the SDK in different formats. ```bash # Production Builds npm run build # Build all formats npm run build:iife # Browser bundle (dist/mparticle.js) npm run build:npm # CommonJS (dist/mparticle.common.js) npm run build:esm # ES Modules (dist/mparticle.esm.js) npm run build:stub # Stub file (pre-init API) ``` -------------------------------- ### Initialize mParticle SDK via Script Tag Source: https://github.com/mparticle/mparticle-web-sdk/blob/master/README.md Include this snippet in your site's HTML, ideally in the
element. Customize 'YOUR_API_KEY' and 'mParticle.config' as needed. This method pre-populates method stubs for the public SDK API. ```javascript ``` ``` -------------------------------- ### Log Promotions and Product Impressions Source: https://context7.com/mparticle/mparticle-web-sdk/llms.txt Track merchandising effectiveness by logging promotion views/clicks using `createPromotion()` and `logPromotion()`. Product impressions can be logged with `createImpression()` and `logImpression()`. Use `setCurrencyCode()` to set the currency for subsequent events. ```javascript // Create and log a promotion view const promo = mParticle.eCommerce.createPromotion( 'PROMO-SUMMER-01', // id 'summer-hero-banner', // creative 'Summer Sale', // name 1 // position ); mParticle.eCommerce.logPromotion( mParticle.PromotionType.PromotionView, promo ); // Log a promotion click mParticle.eCommerce.logPromotion( mParticle.PromotionType.PromotionClick, promo, { click_source: 'homepage' } ); // Log product impressions (e.g., products visible in a listing) const impression = mParticle.eCommerce.createImpression( 'search-results-list', // impression name/list product1 // product ); mParticle.eCommerce.logImpression(impression); // Set currency code for all subsequent commerce events mParticle.eCommerce.setCurrencyCode('USD'); ``` -------------------------------- ### e-Commerce — Create Product and Log Product Action Source: https://context7.com/mparticle/mparticle-web-sdk/llms.txt This section details how to create product objects and log various e-commerce actions such as adding to cart and purchases using the `createProduct` and `logProductAction` methods. ```APIDOC ## e-Commerce — Create Product and Log Product Action Creates product objects and logs commerce events like add-to-cart, purchase, and refund using `mParticle.eCommerce.createProduct()` and `logProductAction()`. ```javascript // Create product objects const product1 = mParticle.eCommerce.createProduct( 'Trail Running Shoes', // name 'SKU-TRS-001', // sku 129.99, // price 1, // quantity 'Red/Black', // variant 'Footwear', // category 'TrailBlazer', // brand 1, // position 'SAVE10', // coupon { waterproof: 'true' } // custom attributes ); const product2 = mParticle.eCommerce.createProduct('Running Socks', 'SKU-SOC-002', 12.99, 2); // Log Add to Cart mParticle.eCommerce.logProductAction( mParticle.ProductActionType.AddToCart, [product1, product2], { source: 'product_page' } ); // Create transaction attributes and log Purchase const transactionAttributes = mParticle.eCommerce.createTransactionAttributes( 'TXN-20240101', // id 'Online Store', // affiliation 'SAVE10', // coupon code 142.98 * 1.08, // revenue (with tax) 'standard', // shipping 142.98 * 0.08 // tax ); mParticle.eCommerce.logProductAction( mParticle.ProductActionType.Purchase, [product1, product2], { payment_method: 'credit_card' }, {}, // custom flags transactionAttributes ); ``` ``` -------------------------------- ### Watch for File Changes and Rebuild Source: https://github.com/mparticle/mparticle-web-sdk/blob/master/CONTRIBUTING.md Continuously rebuilds bundles as source files change. Useful for active development. ```bash $ npm run watch // watches src/ files and continuously rebuilds bundles as changes are made ``` -------------------------------- ### Multiple Instances Source: https://context7.com/mparticle/mparticle-web-sdk/llms.txt Supports multiple named instances for multi-brand or multi-workspace deployments in self-hosted environments. Each instance maintains independent state, persistence, and configuration. ```APIDOC ## Multiple Instances The SDK supports multiple named instances for multi-brand or multi-workspace deployments in self-hosted environments. Each instance maintains independent state, persistence, and configuration. ```javascript // Initialize a second instance named 'brand_b' mParticle.init('API_KEY_BRAND_B', { isDevelopmentMode: false, appName: 'Brand B', identityCallback: function(result) { console.log('Brand B user:', result.getUser()?.getMPID()); }, }, 'brand_b'); // Use the named instance explicitly const brandBInstance = mParticle.getInstance('brand_b'); brandBInstance.logEvent('Product Viewed', mParticle.EventType.Navigation, { product_id: 'B-SKU-001', }); brandBInstance.eCommerce.logProductAction( mParticle.ProductActionType.ViewDetail, product1 ); // Default instance still uses shorthand mParticle.logPageView('Home'); ``` ``` -------------------------------- ### Development Build Commands Source: https://github.com/mparticle/mparticle-web-sdk/blob/master/AGENTS.md Commands for development builds, including watching for changes and rebuilding various formats. ```bash # Development npm run watch # Watch IIFE and rebuild npm run watch:all # Watch all formats npm run watch:tests # Watch and rebuild tests npm run build:dev # Dev build with sourcemap ``` -------------------------------- ### Execute Code After SDK Initialization Source: https://context7.com/mparticle/mparticle-web-sdk/llms.txt Safely executes a callback function once the mParticle SDK is initialized. This is useful for ensuring that SDK methods are called only after initialization is complete. ```javascript mParticle.ready(function() { console.log('SDK is ready, current user:', mParticle.Identity.getCurrentUser()?.getMPID()); mParticle.logPageView('Home Page'); }); ``` -------------------------------- ### Run Tests with Custom Browser Source: https://github.com/mparticle/mparticle-web-sdk/blob/master/README.md Execute tests using npm run testBrowser. Specify a browser brand like Edge or IE using the BROWSER environment variable. ```bash $ BROWSER=[browserBrand] npm run testBrowser ``` -------------------------------- ### Linting and Code Quality Commands Source: https://github.com/mparticle/mparticle-web-sdk/blob/master/AGENTS.md Execute these npm scripts for linting checks, Prettier formatting checks, and bundle analysis. Ensure code quality and optimize bundle size. ```bash # Linting npm run lint # ESLint check (both .js and .ts files) npm run prettier # Prettier check (.js files only) # Bundle Analysis npm run bundle # Uglify + gzip for size reporting npm run uglify # Minify bundle npm run gzip # Gzip bundle ``` -------------------------------- ### Full Test Suite Command Source: https://github.com/mparticle/mparticle-web-sdk/blob/master/AGENTS.md Executes the complete test suite, combining Karma for browser integration tests and Jest for TypeScript unit tests. ```bash npm run test # Full suite (Karma + Jest) ``` -------------------------------- ### Create Product Objects and Log Commerce Events Source: https://context7.com/mparticle/mparticle-web-sdk/llms.txt Use `createProduct()` to define product details and `logProductAction()` to track events like AddToCart and Purchase. Transaction attributes can be created with `createTransactionAttributes()` for purchase events. ```javascript // Create product objects const product1 = mParticle.eCommerce.createProduct( 'Trail Running Shoes', // name 'SKU-TRS-001', // sku 129.99, // price 1, // quantity 'Red/Black', // variant 'Footwear', // category 'TrailBlazer', // brand 1, // position 'SAVE10', // coupon { waterproof: 'true' } // custom attributes ); const product2 = mParticle.eCommerce.createProduct('Running Socks', 'SKU-SOC-002', 12.99, 2); // Log Add to Cart mParticle.eCommerce.logProductAction( mParticle.ProductActionType.AddToCart, [product1, product2], { source: 'product_page' } ); // Create transaction attributes and log Purchase const transactionAttributes = mParticle.eCommerce.createTransactionAttributes( 'TXN-20240101', // id 'Online Store', // affiliation 'SAVE10', // coupon code 142.98 * 1.08, // revenue (with tax) 'standard', // shipping 142.98 * 0.08 // tax ); mParticle.eCommerce.logProductAction( mParticle.ProductActionType.Purchase, [product1, product2], { payment_method: 'credit_card' }, {}, // custom flags transactionAttributes ); ``` -------------------------------- ### Register Sideloaded Kits Programmatically Source: https://context7.com/mparticle/mparticle-web-sdk/llms.txt Registers a third-party integration kit with the SDK programmatically before initialization. Kit settings are still applied via the mParticle dashboard. ```javascript import MyCustomKit from './my-custom-kit'; // Register the kit before init mParticle.addForwarder(MyCustomKit); mParticle.init('YOUR_API_KEY', { isDevelopmentMode: true, // Kit settings are still applied via the mParticle dashboard }); ``` -------------------------------- ### Identity - mParticle.Identity.login(data, callback) Source: https://context7.com/mparticle/mparticle-web-sdk/llms.txt Initiates a login IDSync request, associating the current session with the given identity set and transitioning the active user profile. ```APIDOC ## Identity — `mParticle.Identity.login(data, callback)` Initiates a login IDSync request, associating the current session with the given identity set and transitioning the active user profile. ```javascript mParticle.Identity.login( { userIdentities: { email: 'john@example.com', customerid: 'USER-001', }, }, function(result) { if (result.httpCode === 200) { const user = result.getUser(); user.setUserAttribute('login_method', 'email'); user.setUserAttribute('last_login', new Date().toISOString()); } } ); ``` ``` -------------------------------- ### Watch Test Files and Rebuild Source: https://github.com/mparticle/mparticle-web-sdk/blob/master/CONTRIBUTING.md Continuously rebuilds test bundles as test files change. Useful for TDD workflows. ```bash $ npm run watch:tests // watches test/ files and continuously rebuilds test bundles as changes are made ``` -------------------------------- ### Cross-Browser and Integration Test Commands Source: https://github.com/mparticle/mparticle-web-sdk/blob/master/AGENTS.md Commands for running cross-browser tests on BrowserStack and testing all integrations across different module formats. ```bash npm run test:browserstack # BrowserStack cross-browser tests npm run test:integrations # All integrations (CJS, ESM, RequireJS) ``` -------------------------------- ### Sideloaded Kits Source: https://context7.com/mparticle/mparticle-web-sdk/llms.txt Registers a third-party integration kit with the SDK programmatically without relying on the mParticle server configuration, enabling custom or private integrations. ```APIDOC ## Sideloaded Kits — `addForwarder()` Registers a third-party integration kit with the SDK programmatically without relying on the mParticle server configuration, enabling custom or private integrations. ```javascript import MyCustomKit from './my-custom-kit'; // Register the kit before init mParticle.addForwarder(MyCustomKit); mParticle.init('YOUR_API_KEY', { isDevelopmentMode: true, // Kit settings are still applied via the mParticle dashboard }); ``` ``` -------------------------------- ### Force Event Upload Source: https://context7.com/mparticle/mparticle-web-sdk/llms.txt Use `mParticle.upload()` to immediately send all queued events to mParticle servers, bypassing the regular batching interval. This is crucial before page navigation or for critical user actions to ensure event delivery. ```javascript document.getElementById('checkout-complete').addEventListener('click', function() { mParticle.logEvent('Checkout Complete', mParticle.EventType.Transaction, { order_total: 99.99, currency: 'USD', }); mParticle.upload(); // ensure delivery before page transitions }); ``` -------------------------------- ### Specialized Build Commands Source: https://github.com/mparticle/mparticle-web-sdk/blob/master/AGENTS.md Commands for specialized builds, such as minified snippets or TypeScript compilation. ```bash # Specialized npm run build:snippet # Minified snippets npm run build:ts # TypeScript compilation only ``` -------------------------------- ### Run Tests in Debug Mode Source: https://github.com/mparticle/mparticle-web-sdk/blob/master/CONTRIBUTING.md Opens a browser to allow stepping through mParticle and test code for debugging purposes. ```bash $ npm run test:debug // opens a browser so you can step through mParticle and test code ``` -------------------------------- ### Opt-Out Functionality with mParticle.setOptOut Source: https://context7.com/mparticle/mparticle-web-sdk/llms.txt Enables or disables all event logging for the current user. When opted out, events are discarded and forwarding is halted. Use `true` to opt-out and `false` to re-enable. ```javascript // User opts out of data collection (e.g., from privacy settings) mParticle.setOptOut(true); // Re-enable tracking when user consents again mParticle.setOptOut(false); mParticle.logEvent('Opt-In Confirmed', mParticle.EventType.UserPreference); ``` -------------------------------- ### e-Commerce — Promotions and Impressions Source: https://context7.com/mparticle/mparticle-web-sdk/llms.txt This section covers logging promotion views, clicks, and product impressions to track merchandising effectiveness, as well as setting the currency code for commerce events. ```APIDOC ## e-Commerce — Promotions and Impressions Logs promotion views/clicks and product impression events for tracking merchandising effectiveness. ```javascript // Create and log a promotion view const promo = mParticle.eCommerce.createPromotion( 'PROMO-SUMMER-01', // id 'summer-hero-banner', // creative 'Summer Sale', // name 1 // position ); mParticle.eCommerce.logPromotion( mParticle.PromotionType.PromotionView, promo ); // Log a promotion click mParticle.eCommerce.logPromotion( mParticle.PromotionType.PromotionClick, promo, { click_source: 'homepage' } ); // Log product impressions (e.g., products visible in a listing) const impression = mParticle.eCommerce.createImpression( 'search-results-list', // impression name/list product1 // product ); mParticle.eCommerce.logImpression(impression); // Set currency code for all subsequent commerce events mParticle.eCommerce.setCurrencyCode('USD'); ``` ``` -------------------------------- ### Login User Source: https://context7.com/mparticle/mparticle-web-sdk/llms.txt Use `mParticle.Identity.login` to associate the current session with a given set of identities and transition the active user profile. The callback function can be used to update user attributes after a successful login. ```javascript mParticle.Identity.login( { userIdentities: { email: 'john@example.com', customerid: 'USER-001', }, }, function(result) { if (result.httpCode === 200) { const user = result.getUser(); user.setUserAttribute('login_method', 'email'); user.setUserAttribute('last_login', new Date().toISOString()); } } ); ``` -------------------------------- ### Manage GDPR and CCPA Consent States Source: https://context7.com/mparticle/mparticle-web-sdk/llms.txt Create and apply GDPR and CCPA consent states to control integration forwarding. Use `createGDPRConsent()` and `createCCPAConsent()` to build consent objects, `createConsentState()` to group them, and `setConsentState()` to apply to the current user. ```javascript // Build a GDPR consent state for multiple purposes const analyticsConsent = mParticle.Consent.createGDPRConsent( true, // consented Date.now(), // timestamp 'gdpr-privacy-policy-v3', // consent document 'https://example.com/privacy', // location navigator.userAgent // hardwareId (optional context) ); const marketingConsent = mParticle.Consent.createGDPRConsent( false, // user declined marketing Date.now(), 'gdpr-privacy-policy-v3' ); const consentState = mParticle.Consent.createConsentState(); consentState.addGDPRConsentState('analytics_storage', analyticsConsent); consentState.addGDPRConsentState('ad_personalization', marketingConsent); // CCPA data sale opt-out const ccpaConsent = mParticle.Consent.createCCPAConsent( true, // opted out of data sale Date.now(), 'ccpa-notice-v2' ); consentState.setCCPAConsentState(ccpaConsent); // Apply to current user const user = mParticle.Identity.getCurrentUser(); if (user) { user.setConsentState(consentState); } // Read current consent state const currentConsent = user.getConsentState(); const gdpr = currentConsent.getGDPRConsentState(); console.log('Analytics consented:', gdpr['analytics_storage']?.Consented); ``` -------------------------------- ### Accessing Persistence Layer in Web SDK Source: https://github.com/mparticle/mparticle-web-sdk/blob/master/AGENTS.md Use these methods to interact with the SDK's persistence layer, which prioritizes LocalStorage and falls back to cookies. Ensure you are using the correct instance of the SDK. ```javascript // Via instance mpInstance._Persistence.setLocalStorage(key, value); const value = mpInstance._Persistence.getLocalStorage(key); ``` ```javascript // Store for runtime state mpInstance._Store.devToken = 'xyz'; ``` -------------------------------- ### Logging Errors and Warnings in Web SDK Source: https://github.com/mparticle/mparticle-web-sdk/blob/master/AGENTS.md Utilize the SDK's logger for consistent error reporting and debugging. It's recommended to use the logger over console methods and include context in messages. ```javascript // Via instance mpInstance.Logger.error('Error message'); mpInstance.Logger.warning('Warning message'); mpInstance.Logger.verbose('Debug message'); ``` -------------------------------- ### Debug and Unit Test Commands Source: https://github.com/mparticle/mparticle-web-sdk/blob/master/AGENTS.md Commands for debugging tests interactively and running Jest unit tests in watch mode. ```bash # Test Commands: npm run test:debug # Interactive Chrome debug mode npm run test:jest # Jest unit tests only (TypeScript) npm run test:jest:watch # Jest watch mode ``` -------------------------------- ### Consent — GDPR and CCPA Source: https://context7.com/mparticle/mparticle-web-sdk/llms.txt This section explains how to create and apply GDPR and CCPA consent state objects to control integration forwarding behavior based on user consent purposes. ```APIDOC ## Consent — GDPR and CCPA Creates and applies GDPR/CCPA consent state objects to the current user, controlling integration forwarding behavior based on consent purposes. ```javascript // Build a GDPR consent state for multiple purposes const analyticsConsent = mParticle.Consent.createGDPRConsent( true, // consented Date.now(), // timestamp 'gdpr-privacy-policy-v3', // consent document 'https://example.com/privacy', // location navigator.userAgent // hardwareId (optional context) ); const marketingConsent = mParticle.Consent.createGDPRConsent( false, // user declined marketing Date.now(), 'gdpr-privacy-policy-v3' ); const consentState = mParticle.Consent.createConsentState(); consentState.addGDPRConsentState('analytics_storage', analyticsConsent); consentState.addGDPRConsentState('ad_personalization', marketingConsent); // CCPA data sale opt-out const ccpaConsent = mParticle.Consent.createCCPAConsent( true, // opted out of data sale Date.now(), 'ccpa-notice-v2' ); consentState.setCCPAConsentState(ccpaConsent); // Apply to current user const user = mParticle.Identity.getCurrentUser(); if (user) { user.setConsentState(consentState); } // Read current consent state const currentConsent = user.getConsentState(); const gdpr = currentConsent.getGDPRConsentState(); console.log('Analytics consented:', gdpr['analytics_storage']?.Consented); ``` ``` -------------------------------- ### Location Tracking with startTrackingLocation, stopTrackingLocation, setPosition Source: https://context7.com/mparticle/mparticle-web-sdk/llms.txt Requests browser Geolocation API for user position or manually sets coordinates. Events logged after `startTrackingLocation` will include location data. ```javascript // Request geolocation with a callback mParticle.startTrackingLocation(function(position) { console.log('Location acquired:', position.coords.latitude, position.coords.longitude); // Events logged after this will include the location mParticle.logEvent('Store Locator Opened', mParticle.EventType.Location); }); // Stop tracking mParticle.stopTrackingLocation(); // Manually set coordinates (e.g., from a IP-geo lookup) mParticle.setPosition(37.7749, -122.4194); ``` -------------------------------- ### Log Page View Events Source: https://context7.com/mparticle/mparticle-web-sdk/llms.txt Logs a page or screen view. If no attributes are provided, it automatically captures the hostname and document title. Custom attributes and flags can be included. ```javascript // Auto-captures window.location.hostname and document.title mParticle.logPageView(); // Custom page view with explicit attributes mParticle.logPageView( 'Product Detail Page', { product_id: 'SKU-9876', category: 'Electronics', referrer: document.referrer, }, { 'Adobe.eVar1': 'ProductDetailView' } ); ``` -------------------------------- ### Web SDK Data Flow Architecture Source: https://github.com/mparticle/mparticle-web-sdk/blob/master/AGENTS.md Visual representation of the data flow within the mParticle Web SDK, from event logging to batch upload. ```text Event Logged → Validation → Consent Check → Kit Forwarding → Batch Upload ↓ ↓ ↓ ↓ Data Plan Consent State Active Kits API Client ``` -------------------------------- ### Constant and Method Naming Conventions Source: https://github.com/mparticle/mparticle-web-sdk/blob/master/AGENTS.md Adhere to these conventions for constants and methods. Constants should use UPPER_SNAKE_CASE, while methods follow standard JavaScript/TypeScript conventions. ```typescript const UPPER_SNAKE_CASE = 'value'; function publicMethod() { } function _privateMethod() { } function getProperty() { } function setProperty() { } ``` -------------------------------- ### Page View Tracking — mParticle.logPageView(name, attrs, flags, options) Source: https://context7.com/mparticle/mparticle-web-sdk/llms.txt Logs a page or screen view event. Can automatically capture hostname and title if no name or attributes are provided. ```APIDOC ## Page View Tracking — mParticle.logPageView(name, attrs, flags, options) ### Description Logs a page/screen view. Defaults the event name to `'PageView'` and automatically captures `hostname` and `title` when no attributes are provided. ### Method `mParticle.logPageView(name, attrs, flags, options)` ### Parameters #### Path Parameters - **name** (string) - Optional - The name of the page view. Defaults to `'PageView'`. - **attrs** (object) - Optional - Key-value pairs of attributes to associate with the page view. - **flags** (object) - Optional - Custom flags to pass to specific integrations. - **options** (object) - Optional - Additional options for page view logging. ### Request Example ```javascript // Auto-captures window.location.hostname and document.title mParticle.logPageView(); // Custom page view with explicit attributes mParticle.logPageView( 'Product Detail Page', { product_id: 'SKU-9876', category: 'Electronics', referrer: document.referrer, }, { 'Adobe.eVar1': 'ProductDetailView' } ); ``` ``` -------------------------------- ### Log Base Event Programmatically Source: https://context7.com/mparticle/mparticle-web-sdk/llms.txt The `logBaseEvent` method allows for programmatic construction and logging of fully formed event objects. This is useful for custom event creation or when integrating with SDK wrappers. ```javascript mParticle.logBaseEvent({ name: 'Custom SDK Event', eventType: mParticle.EventType.Other, messageType: 4, // MessageType.PageEvent data: { custom_key: 'custom_value', timestamp_override: Date.now(), }, customFlags: { 'Segment.IO': 'track' }, }); ``` -------------------------------- ### Base Event Logging - mParticle.logBaseEvent(event, options) Source: https://context7.com/mparticle/mparticle-web-sdk/llms.txt A low-level method to log a fully constructed event object directly. This is useful for programmatic event construction or when integrating with SDK wrappers. ```APIDOC ## Base Event Logging — `mParticle.logBaseEvent(event, options)` Low-level method to log a fully constructed event object directly, useful for programmatic event construction or SDK wrapper integrations. ```javascript mParticle.logBaseEvent({ name: 'Custom SDK Event', eventType: mParticle.EventType.Other, messageType: 4, // MessageType.PageEvent data: { custom_key: 'custom_value', timestamp_override: Date.now(), }, customFlags: { 'Segment.IO': 'track' }, }); ``` ``` -------------------------------- ### Identify User Profile Source: https://context7.com/mparticle/mparticle-web-sdk/llms.txt The `mParticle.Identity.identify` method sends an IDSync request to resolve or create a user profile based on provided identities like email or customer ID. It returns the resolved or created user profile and potentially the previous one. ```javascript mParticle.Identity.identify( { userIdentities: { email: 'jane.doe@example.com', customerid: 'cust_789', }, }, function(result) { const httpCode = result.httpCode; if (httpCode === 200) { const user = result.getUser(); console.log('Resolved MPID:', user.getMPID()); const prevUser = result.getPreviousUser(); if (prevUser) { console.log('Previous MPID:', prevUser.getMPID()); } } else { console.error('Identity failed with code:', httpCode); } } ); ``` -------------------------------- ### Forced Upload - mParticle.upload() Source: https://context7.com/mparticle/mparticle-web-sdk/llms.txt Immediately flushes all queued events to mParticle servers, bypassing the normal batching interval. This is useful before navigation or on critical user actions to ensure immediate delivery. ```APIDOC ## Forced Upload — `mParticle.upload()` Immediately flushes all queued events to mParticle servers, bypassing the normal batching interval. Useful before navigation or on critical user actions. ```javascript document.getElementById('checkout-complete').addEventListener('click', function() { mParticle.logEvent('Checkout Complete', mParticle.EventType.Transaction, { order_total: 99.99, currency: 'USD', }); mParticle.upload(); // ensure delivery before page transitions }); ``` ``` -------------------------------- ### Identity - mParticle.Identity.search(data, callback) Source: https://context7.com/mparticle/mparticle-web-sdk/llms.txt Sends a read-only IDSync search request to check if a given identity set matches an existing mParticle profile, without creating or modifying any profile. ```APIDOC ## Identity — `mParticle.Identity.search(data, callback)` Sends a read-only IDSync search request to check whether a given identity set matches an existing mParticle profile, without creating or modifying any profile. ```javascript mParticle.Identity.search( { userIdentities: { email: 'lookup@example.com', }, }, function(result) { if (result.httpCode === 200 && result.body?.mpid) { console.log('Found existing profile:', result.body.mpid); console.log('Matched identities:', result.body.matched_identities); } else if (result.httpCode === 404) { console.log('No existing profile found'); } } ); ``` ``` -------------------------------- ### App Metadata Source: https://context7.com/mparticle/mparticle-web-sdk/llms.txt Sets application-level metadata and device identifiers that are included in all event payloads. ```APIDOC ## App Metadata — `setAppName()` / `setAppVersion()` / `setDeviceId()` Sets application-level metadata and device identifiers that are included in all event payloads. ```javascript mParticle.setAppName('My Web App'); mParticle.setAppVersion('3.1.4'); // Provide or override the device ID (UUIDv4 format) mParticle.setDeviceId('550e8400-e29b-41d4-a716-446655440000'); console.log('Device ID:', mParticle.getDeviceId()); // Log level can be changed at runtime mParticle.setLogLevel('verbose'); // 'verbose' | 'warning' | 'none' ``` ``` -------------------------------- ### Search for User Profile by Identity Source: https://context7.com/mparticle/mparticle-web-sdk/llms.txt The `mParticle.Identity.search` method performs a read-only IDSync search to check if a given identity set matches an existing mParticle profile, without creating or modifying any profiles. It returns the MPID and matched identities if found, or a 404 if not. ```javascript mParticle.Identity.search( { userIdentities: { email: 'lookup@example.com', }, }, function(result) { if (result.httpCode === 200 && result.body?.mpid) { console.log('Found existing profile:', result.body.mpid); console.log('Matched identities:', result.body.matched_identities); } else if (result.httpCode === 404) { console.log('No existing profile found'); } } ); ```