Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: avoid premature execution before sdk initialization #2056

Merged
merged 10 commits into from
Mar 2, 2025

Conversation

saikumarrs
Copy link
Member

@saikumarrs saikumarrs commented Feb 21, 2025

PR Description

I've fixed a couple of issues in the core module that would otherwise execute some logic before the SDK initialisation.

We create default instances of some resources so we should be careful in executing some code in their constructors. Otherwise, some code can get executed just by importing the package.

  • Attaching error event handlers
  • All storage engines default configuration

All the storage engine modules are refactored to create default instances which will be configured only when the SDK instance is created.
The default instances will be used throughout the code.
Now, there is no need for global singletons.

Linear task (optional)

https://linear.app/rudderstack/issue/SDK-3003/avoid-attaching-error-listeners-by-default

Cross Browser Tests

Please confirm you have tested for the following browsers:

  • Chrome
  • Firefox
  • IE11

Sanity Suite

  • All sanity suite test cases pass locally

Security

  • The code changed/added as part of this pull request won't create any security issues with how the software is being used.

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced dynamic configuration for analytics, allowing flexible key and endpoint setup.
    • Added a centralized initialization routine for global resources, enhancing error handling and storage services.
  • Refactor

    • Streamlined the initialization process and configuration for various storage modules to improve consistency and reliability.
    • Simplified error handling setup to ensure smoother operation during runtime and testing.
    • Updated storage engine configuration to remove explicit enabling, relying on default behavior.
    • Enhanced the ErrorHandler class with a new initialization method for improved setup.
    • Modified storage classes to remove unnecessary options parameters, simplifying their constructors.

@saikumarrs saikumarrs self-assigned this Feb 21, 2025
Copy link
Contributor

coderabbitai bot commented Feb 21, 2025

📝 Walkthrough

Walkthrough

This PR updates how the SDK and its associated components are initialized and configured. It replaces hardcoded initialization parameters with placeholders in the example, adds an init() method to both the ErrorHandler mock and implementation (and its interface), and adjusts the Store/Storage constructors and configuration methods to remove default fallbacks. In tests, explicit enable flags have been removed, and calls to engine.configure?.() have been added. Additionally, a new static method in the main analytics class centralizes global resource initialization.

Changes

File(s) Change Summary
examples/v3/index.html Replaced hardcoded write key and dataplane URL with placeholder strings in the SDK initialization call.
packages/analytics-js-common/__mocks__/ErrorHandler.ts, packages/analytics-js-common/src/types/ErrorHandler.ts, packages/analytics-js/src/services/ErrorHandler/ErrorHandler.ts, packages/analytics-js/__tests__/services/ErrorHandler/ErrorHandler.test.ts Added an init() method to the ErrorHandler (and its interface) and updated tests to call init() for proper error listener attachment.
packages/analytics-js-common/__mocks__/Store.ts, packages/analytics-js-common/src/types/Store.ts, packages/analytics-js/src/services/StoreManager/Store.ts Removed the default fallback assignment for the engine property and updated the configure method signature to accept optional options.
packages/analytics-js/__tests__/services/StoreManager/{StoreManager.test.ts, storages/*.test.ts} Removed explicit enabled: true flags and added engine.configure?.() calls in test setups for storage engines.
packages/analytics-js/src/app/RudderAnalytics.ts Introduced a new static initializeGlobalResources() method to centralize global resource initialization and refactored the load method to retrieve the analytics instance via getAnalyticsInstance(writeKey).
packages/analytics-js/src/services/StoreManager/storages/{CookieStorage.ts, InMemoryStorage.ts, LocalStorage.ts, sessionStorage.ts} Revised storage engine classes by removing the options parameter from constructors, updating their configure() methods to accept optional options, and modifying default instance creation (e.g., exporting defaultCookieStorage in CookieStorage).
packages/analytics-js/src/services/StoreManager/storages/storageEngine.ts Updated the storage factory to return the pre-initialized defaultCookieStorage instance instead of creating a new CookieStorage.

Sequence Diagram(s)

sequenceDiagram
    participant RA as RudderAnalytics
    participant EH as ErrorHandler
    participant CS as CookieStorage
    participant LS as LocalStorage
    participant SS as SessionStorage
    participant IMS as InMemoryStorage

    RA->>RA: initializeGlobalResources()
    RA->>EH: init()
    Note over EH: Attaches error listeners
    RA->>CS: configure?()
    RA->>LS: configure?()
    RA->>SS: configure?()
    RA->>IMS: configure?()
Loading

Possibly related PRs

  • fix: improve sdk loading snippet #1745: The changes in the main PR, which involve modifying the parameters for the rudderanalytics.load method, are related to the retrieved PR that improves the SDK loading snippet by ensuring proper initialization and handling of the window.rudderanalytics object, as both involve the initialization and configuration of the RudderAnalytics SDK.
  • feat: track time spent on a page #1876: The changes in the main PR, which modify the parameters for the rudderanalytics.load method, are related to the enhancements in the retrieved PR that introduces new methods for tracking page lifecycle events, including modifications to the load method in the RudderAnalytics class. Both PRs involve updates to the initialization and configuration of analytics functionality.
  • fix: sdk instrumentation in example apps loading snippet #2051: The changes in the main PR, which involve modifying the parameters passed to the rudderanalytics.load method and updating the destSDKBaseURL and pluginsSDKBaseURL, are related to the changes in the retrieved PR, which also involve updates to the loadOptions object and the construction of these URLs, indicating a direct connection in how the SDK is initialized.

Suggested reviewers

  • ChryssaAliferi
  • ItsSudip
  • MoumitaM

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 762eaeb and 8a5db91.

⛔ Files ignored due to path filters (1)
  • .github/dependabot.yml is excluded by !**/*.yml
📒 Files selected for processing (21)
  • examples/v3/index.html (1 hunks)
  • packages/analytics-js-common/__mocks__/ErrorHandler.ts (1 hunks)
  • packages/analytics-js-common/__mocks__/Store.ts (1 hunks)
  • packages/analytics-js-common/src/types/ErrorHandler.ts (1 hunks)
  • packages/analytics-js-common/src/types/Store.ts (1 hunks)
  • packages/analytics-js/__tests__/services/ErrorHandler/ErrorHandler.test.ts (1 hunks)
  • packages/analytics-js/__tests__/services/StoreManager/StoreManager.test.ts (1 hunks)
  • packages/analytics-js/__tests__/services/StoreManager/storages/CookieStorage.test.ts (3 hunks)
  • packages/analytics-js/__tests__/services/StoreManager/storages/InMemoryStorage.test.ts (1 hunks)
  • packages/analytics-js/__tests__/services/StoreManager/storages/LocalStorage.test.ts (1 hunks)
  • packages/analytics-js/__tests__/services/StoreManager/storages/defaultOptions.test.ts (1 hunks)
  • packages/analytics-js/__tests__/services/StoreManager/storages/sessionStorage.test.ts (1 hunks)
  • packages/analytics-js/src/app/RudderAnalytics.ts (3 hunks)
  • packages/analytics-js/src/services/ErrorHandler/ErrorHandler.ts (3 hunks)
  • packages/analytics-js/src/services/StoreManager/Store.ts (2 hunks)
  • packages/analytics-js/src/services/StoreManager/StoreManager.ts (1 hunks)
  • packages/analytics-js/src/services/StoreManager/storages/CookieStorage.ts (2 hunks)
  • packages/analytics-js/src/services/StoreManager/storages/InMemoryStorage.ts (2 hunks)
  • packages/analytics-js/src/services/StoreManager/storages/LocalStorage.ts (2 hunks)
  • packages/analytics-js/src/services/StoreManager/storages/sessionStorage.ts (2 hunks)
  • packages/analytics-js/src/services/StoreManager/storages/storageEngine.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (20)
  • packages/analytics-js/tests/services/StoreManager/storages/defaultOptions.test.ts
  • packages/analytics-js/tests/services/StoreManager/storages/LocalStorage.test.ts
  • packages/analytics-js/tests/services/StoreManager/storages/sessionStorage.test.ts
  • packages/analytics-js/tests/services/StoreManager/storages/InMemoryStorage.test.ts
  • packages/analytics-js/tests/services/ErrorHandler/ErrorHandler.test.ts
  • packages/analytics-js-common/src/types/Store.ts
  • packages/analytics-js/src/services/StoreManager/storages/storageEngine.ts
  • packages/analytics-js/src/services/StoreManager/Store.ts
  • packages/analytics-js-common/src/types/ErrorHandler.ts
  • packages/analytics-js/tests/services/StoreManager/StoreManager.test.ts
  • packages/analytics-js-common/mocks/Store.ts
  • packages/analytics-js/src/services/StoreManager/StoreManager.ts
  • examples/v3/index.html
  • packages/analytics-js/src/services/ErrorHandler/ErrorHandler.ts
  • packages/analytics-js/src/app/RudderAnalytics.ts
  • packages/analytics-js/src/services/StoreManager/storages/LocalStorage.ts
  • packages/analytics-js/src/services/StoreManager/storages/sessionStorage.ts
  • packages/analytics-js/src/services/StoreManager/storages/InMemoryStorage.ts
  • packages/analytics-js/tests/services/StoreManager/storages/CookieStorage.test.ts
  • packages/analytics-js-common/mocks/ErrorHandler.ts
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Bundle size checks
  • GitHub Check: Security and code quality checks
  • GitHub Check: Unit Tests and Lint
🔇 Additional comments (5)
packages/analytics-js/src/services/StoreManager/storages/CookieStorage.ts (5)

10-10: Good addition of defaultLogger import.

This import supports the singleton pattern implemented at the end of the file, aligning with the PR's goal of controlling SDK initialization.


17-17: Property type refinement looks good.

The options property is now more explicitly typed as ICookieStorageOptions with initialization moved to the constructor.


22-22: Simplified constructor improves initialization control.

Removing direct options initialization from the constructor is a good approach that enforces proper initialization order and prevents premature configuration.


27-29: Well-implemented optional configuration pattern.

Making the options parameter optional with a fallback to an empty object improves the API flexibility while maintaining type safety. The use of nullish coalescing operator is a good modern JavaScript practice.

- configure(options?: Partial<ICookieStorageOptions>): ICookieStorageOptions {
-   this.options = mergeDeepRight(this.options, options ?? {});
+ configure(options?: Partial<ICookieStorageOptions>): ICookieStorageOptions {
+   this.options = mergeDeepRight(this.options, options ?? {});

74-76: Effective singleton implementation with proper exports.

Creating a default instance with the defaultLogger and exporting it alongside the class provides both flexibility and control. This pattern allows for controlled initialization of the storage engine, addressing the PR's goal of preventing premature execution.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@saikumarrs saikumarrs changed the title Fix.avoid pre mature initialization sdk 3003 fix: avoid initialising components before initialization Feb 21, 2025
Copy link

codecov bot commented Feb 21, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 61.44%. Comparing base (d4c79a3) to head (8a5db91).
Report is 3 commits behind head on develop.

Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #2056      +/-   ##
===========================================
+ Coverage    61.42%   61.44%   +0.02%     
===========================================
  Files          478      478              
  Lines        16407    16411       +4     
  Branches      3231     3259      +28     
===========================================
+ Hits         10078    10084       +6     
+ Misses        5140     5076      -64     
- Partials      1189     1251      +62     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (7)
packages/analytics-js/src/services/ErrorHandler/ErrorHandler.ts (1)

43-45: Add JSDoc documentation and prevent multiple initialization.

The init() method lacks documentation and doesn't protect against multiple initialization calls.

Consider applying these improvements:

+  private initialized = false;
+
+  /**
+   * Initializes the error handler by attaching global error listeners.
+   * This method should be called once after construction.
+   */
   init() {
+    if (this.initialized) {
+      this.logger.warn('ErrorHandler already initialized');
+      return;
+    }
     this.attachErrorListeners();
+    this.initialized = true;
   }
packages/analytics-js/__tests__/services/ErrorHandler/ErrorHandler.test.ts (1)

13-13: Add test cases for init() method behavior.

While the initialization is correctly added to beforeEach, specific test cases for the init() method are missing.

Consider adding these test cases:

describe('init', () => {
  it('should attach error listeners only once', () => {
    const attachListenersSpy = jest.spyOn(errorHandlerInstance, 'attachErrorListeners');
    
    // Second init() call should not attach listeners again
    errorHandlerInstance.init();
    
    expect(attachListenersSpy).not.toHaveBeenCalled();
    attachListenersSpy.mockRestore();
  });
});
packages/analytics-js/__tests__/services/StoreManager/storages/LocalStorage.test.ts (1)

9-9: LGTM! Consider adding error handling.

The addition of engine.configure?.() ensures proper initialization before usage, aligning with the PR's goal of fixing premature initialization. The optional chaining operator prevents runtime errors.

Consider adding error handling to catch and log configuration failures:

-    engine.configure?.();
+    try {
+      engine.configure?.();
+    } catch (error) {
+      console.error('Failed to configure localStorage engine:', error);
+    }
packages/analytics-js/__tests__/services/StoreManager/storages/CookieStorage.test.ts (1)

12-12: LGTM! Consider additional cookie configuration tests.

The addition of engine.configure?.() maintains consistent initialization pattern. The existing domain configuration test is valuable for security.

Consider adding tests for other cookie configuration options:

it('should properly configure cookie attributes', () => {
  configureCookieStorageEngine({
    samesite: 'Strict',
    secure: true,
    path: '/app',
    maxage: 3600000,
  });
  const newEngine = getStorageEngine('cookieStorage');
  expect(newEngine.options.samesite).toBe('Strict');
  expect(newEngine.options.secure).toBe(true);
  expect(newEngine.options.path).toBe('/app');
  expect(newEngine.options.maxage).toBe(3600000);
});
packages/analytics-js/__tests__/services/StoreManager/storages/sessionStorage.test.ts (1)

9-9: LGTM! Consider testing configuration with unavailable storage.

The addition of engine.configure?.() maintains consistent initialization pattern. The tests for unavailable storage are thorough.

Consider adding a test to verify configuration behavior when storage is unavailable:

it('should handle configuration when session storage is unavailable', () => {
  const sessionStorageEngine = getStorageEngine('sessionStorage');
  sessionStorageEngine.store = undefined;
  
  // Should not throw error when configuring unavailable storage
  expect(() => sessionStorageEngine.configure?.()).not.toThrow();
});
packages/analytics-js/src/services/StoreManager/storages/LocalStorage.ts (1)

12-15: Address TODO comment about storejs dependency.

The TODO comment indicates potential bundle size improvements by removing the storejs dependency. Since you're modifying the storage implementation, this would be a good time to evaluate this optimization.

Would you like me to help analyze the usage of storejs methods and propose an alternative implementation that could reduce the bundle size?

packages/analytics-js/__tests__/services/StoreManager/StoreManager.test.ts (1)

69-71: Consider documenting default storage behavior.

The shift from explicit to implicit storage configuration makes the code cleaner but less transparent. Consider:

  1. Adding JSDoc comments to document the default behavior of each storage type
  2. Creating a configuration guide in the README
  3. Adding debug logs when falling back to default configurations

Also applies to: 81-83

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 148a22a and a1011e4.

⛔ Files ignored due to path filters (1)
  • .github/workflows/draft-new-release.yml is excluded by !**/*.yml
📒 Files selected for processing (21)
  • examples/v3/index.html (1 hunks)
  • packages/analytics-js-common/__mocks__/ErrorHandler.ts (1 hunks)
  • packages/analytics-js-common/__mocks__/Store.ts (1 hunks)
  • packages/analytics-js-common/src/types/ErrorHandler.ts (1 hunks)
  • packages/analytics-js-common/src/types/Store.ts (1 hunks)
  • packages/analytics-js/__tests__/services/ErrorHandler/ErrorHandler.test.ts (1 hunks)
  • packages/analytics-js/__tests__/services/StoreManager/StoreManager.test.ts (1 hunks)
  • packages/analytics-js/__tests__/services/StoreManager/storages/CookieStorage.test.ts (1 hunks)
  • packages/analytics-js/__tests__/services/StoreManager/storages/InMemoryStorage.test.ts (1 hunks)
  • packages/analytics-js/__tests__/services/StoreManager/storages/LocalStorage.test.ts (1 hunks)
  • packages/analytics-js/__tests__/services/StoreManager/storages/defaultOptions.test.ts (1 hunks)
  • packages/analytics-js/__tests__/services/StoreManager/storages/sessionStorage.test.ts (1 hunks)
  • packages/analytics-js/src/app/RudderAnalytics.ts (3 hunks)
  • packages/analytics-js/src/services/ErrorHandler/ErrorHandler.ts (1 hunks)
  • packages/analytics-js/src/services/StoreManager/Store.ts (1 hunks)
  • packages/analytics-js/src/services/StoreManager/StoreManager.ts (1 hunks)
  • packages/analytics-js/src/services/StoreManager/storages/CookieStorage.ts (2 hunks)
  • packages/analytics-js/src/services/StoreManager/storages/InMemoryStorage.ts (2 hunks)
  • packages/analytics-js/src/services/StoreManager/storages/LocalStorage.ts (2 hunks)
  • packages/analytics-js/src/services/StoreManager/storages/sessionStorage.ts (2 hunks)
  • packages/analytics-js/src/services/StoreManager/storages/storageEngine.ts (3 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/analytics-js/tests/services/StoreManager/storages/defaultOptions.test.ts
🧰 Additional context used
🧠 Learnings (1)
packages/analytics-js-common/src/types/ErrorHandler.ts (1)
Learnt from: saikumarrs
PR: rudderlabs/rudder-sdk-js#1907
File: packages/analytics-js/src/services/ErrorHandler/ErrorHandler.ts:172-174
Timestamp: 2024-11-12T15:14:23.319Z
Learning: The function `onError` in `packages/analytics-js/src/services/ErrorHandler/ErrorHandler.ts` is acceptable as currently implemented, and refactoring suggestions are not required unless necessary.
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Bundle size checks
  • GitHub Check: Unit Tests and Lint
  • GitHub Check: Security and code quality checks
🔇 Additional comments (24)
packages/analytics-js-common/__mocks__/ErrorHandler.ts (1)

9-9: LGTM! Mock implementation matches interface changes.

The mock implementation correctly adds the init method as a Jest mock function, maintaining consistency with the interface changes.

packages/analytics-js-common/src/types/ErrorHandler.ts (1)

10-10: LGTM! Interface change improves initialization control.

The addition of init(): void to the interface makes the initialization step explicit, following the principle of separation of concerns.

packages/analytics-js/src/app/RudderAnalytics.ts (3)

40-44: LGTM! Imports added for global resources.

The imports are correctly added for the error handler and storage engines that need to be initialized globally.


114-123: LGTM! Well-structured initialization of global resources.

The initializeGlobalResources method follows a good initialization pattern:

  1. Initializes error handler first to catch any initialization errors
  2. Configures storage engines with default options

73-73: LGTM! Global resources initialized at the right time.

The initializeGlobalResources is called early in the constructor, ensuring all global resources are ready before any SDK operations.

examples/v3/index.html (1)

99-99: LGTM! Using placeholders in example code.

Replacing hardcoded values with placeholders (__WRITE_KEY__ and __DATAPLANE_URL__) is a good practice in example code as it:

  1. Makes the example more generic
  2. Prevents accidental exposure of actual credentials
packages/analytics-js/__tests__/services/StoreManager/storages/InMemoryStorage.test.ts (1)

9-9: LGTM! Consistent with other storage implementations.

The addition of engine.configure?.() maintains a consistent initialization pattern across different storage types.

packages/analytics-js/src/services/StoreManager/storages/InMemoryStorage.ts (3)

21-24: LGTM! Constructor simplified to prevent premature initialization.

The removal of options from the constructor aligns with the PR's objective of avoiding premature initialization. The logger-only constructor is a cleaner approach.


26-28: LGTM! Configure method made more flexible.

The optional options parameter with nullish coalescing operator provides a safe default while maintaining backward compatibility.


68-68: LGTM! Default instance creation updated.

The simplified constructor usage for default instance aligns with the new initialization pattern.

packages/analytics-js-common/src/types/Store.ts (1)

56-56:

❓ Verification inconclusive

Verify impact of optional configure method.

Making configure optional in the IStorage interface is a breaking change that could affect existing code expecting this method to be present.


🏁 Script executed:

#!/bin/bash
# Search for direct calls to configure method
rg -A 2 '\.configure\(' --type ts

Length of output: 184


Action Required: Verify Impact of Optional configure Method in IStorage Interface

The change making the configure method optional is potentially breaking since existing implementations might expect this method to be defined. The initial search for direct calls to configure did not yield results due to filtering issues. Please manually verify or run an updated script (see below) to ensure no parts of the codebase rely on a guaranteed implementation of configure:

  • Re-run the search without filtering by file type to verify all potential usages:

    # Re-run the search command without restricting to TypeScript files
    rg --debug -A 2 '\.configure\('
  • If any direct calls to configure are found, adjust them to safely handle its potential absence.

packages/analytics-js-common/__mocks__/Store.ts (1)

16-16: LGTM! Removed implicit engine fallback.

Direct assignment of the engine parameter without fallback aligns with the PR's objective of avoiding premature initialization.

packages/analytics-js/src/services/StoreManager/storages/LocalStorage.ts (3)

26-29: LGTM! Constructor simplified to prevent premature initialization.

The removal of options from the constructor aligns with the PR's objective of avoiding premature initialization.


31-33: LGTM! Configure method made more flexible.

The optional options parameter with nullish coalescing operator provides a safe default while maintaining backward compatibility.


70-70: LGTM! Default instance creation updated.

The simplified constructor usage for default instance aligns with the new initialization pattern.

packages/analytics-js/src/services/StoreManager/storages/sessionStorage.ts (3)

25-28: LGTM! Constructor refactored to prevent premature initialization.

The removal of options from the constructor and initialization of options with defaults aligns with the PR's objective of avoiding premature initialization.


30-32: LGTM! Improved options handling in configure method.

The use of optional parameter with nullish coalescing operator (??) is a good practice for handling undefined options.


90-90: LGTM! Simplified default storage instance creation.

The simplified instantiation with just the logger parameter aligns with the changes in the constructor.

packages/analytics-js/src/services/StoreManager/storages/CookieStorage.ts (3)

17-17: LGTM! Constructor refactored consistently with other storage classes.

The changes maintain consistency with other storage implementations while preventing premature initialization.

Also applies to: 22-25


27-35: LGTM! Improved options handling with domain cleanup.

The configure method properly handles optional parameters and includes domain cleanup when sameDomainCookiesOnly is true.


74-76: LGTM! Added defaultCookieStorage export.

The addition of defaultCookieStorage aligns with the pattern used in other storage implementations.

packages/analytics-js/src/services/StoreManager/storages/storageEngine.ts (1)

43-44: LGTM! Simplified cookie storage configuration.

The change to use defaultCookieStorage.configure maintains consistency with other storage engines while reducing initialization complexity.

packages/analytics-js/src/services/StoreManager/StoreManager.ts (1)

69-71:

❓ Verification inconclusive

Verify storage engine initialization behavior.

The removal of explicit storage options could affect how storage engines are initialized. Ensure that the storage engines have appropriate default behaviors when initialized with empty options.


🏁 Script executed:

#!/bin/bash
# Description: Check storage engine initialization behavior
# Search for default configurations in storage engine implementations

# Look for default configurations in storage implementations
ast-grep --pattern 'class $_ {
  constructor($_) {
    $$$
  }
}'

# Search for any fallback configurations
rg -A 5 "default.*config|fallback.*config"

Length of output: 112


Attention: Verify Default Initialization in Storage Engines

The removal of explicit storage options (i.e. passing empty objects for local, in-memory, and session storages) means we must ensure that each storage engine correctly falls back to default settings during initialization. Our automated check didn't locate any obvious fallback logic in the constructors. Please manually verify that each storage engine (likely implemented in files under packages/analytics-js/src/services/StoreManager/) properly assigns and handles default configurations when initialized with empty options.

  • Confirm in each storage engine’s constructor (e.g., for LocalStorageEngine, InMemoryStorageEngine, and SessionStorageEngine) that if options are empty, the engine sets or infers the correct defaults.
  • Ensure that removing the explicit configurations does not lead to unintended behavior.
packages/analytics-js/__tests__/services/StoreManager/StoreManager.test.ts (1)

81-83: LGTM! Test expectations updated to match implementation.

The test has been correctly updated to verify the new storage engine configuration behavior with empty objects.

@saikumarrs saikumarrs changed the title fix: avoid initialising components before initialization fix: avoid premature execution before initialization Feb 21, 2025
@saikumarrs saikumarrs changed the title fix: avoid premature execution before initialization fix: avoid premature execution before sdk initialization Feb 21, 2025
coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 21, 2025
Copy link

github-actions bot commented Feb 21, 2025

size-limit report 📦

Name Size (Base) Size (Current) Size Limit Status
Cookies Utils - Legacy - NPM (ESM) 1.54 KB 1.54 KB (0%) 2 KB
Cookies Utils - Legacy - NPM (CJS) 1.75 KB 1.75 KB (0%) 2 KB
Cookies Utils - Legacy - NPM (UMD) 1.54 KB 1.54 KB (0%) 2 KB
Cookies Utils - Modern - NPM (ESM) 1.17 KB 1.17 KB (0%) 1.5 KB
Cookies Utils - Modern - NPM (CJS) 1.4 KB 1.4 KB (0%) 1.5 KB
Cookies Utils - Modern - NPM (UMD) 1.16 KB 1.16 KB (0%) 1.5 KB
Plugins Module Federation Mapping - Legacy - CDN 332 B 332 B (0%) 512 B
Plugins Module Federation Mapping - Modern - CDN 331 B 331 B (0%) 512 B
Plugins - Legacy - CDN 13.66 KB 13.66 KB (0%) 14 KB
Plugins - Modern - CDN 5.64 KB 5.64 KB (0%) 6 KB
Common - No bundling 17.96 KB 17.93 KB (-0.14% ▼) 18.4 KB
Load Snippet 765 B 765 B (0%) 1 KB
Core (v1.1) - NPM (ESM) 30.13 KB 30.13 KB (0%) 32 KB
Core (v1.1) - NPM (CJS) 30.32 KB 30.32 KB (0%) 32 KB
Core (v1.1) - NPM (UMD) 30.16 KB 30.16 KB (0%) 32 KB
Core (Content Script - v1.1) - NPM (ESM) 29.6 KB 29.6 KB (0%) 30.5 KB
Core (Content Script - v1.1) - NPM (CJS) 29.85 KB 29.85 KB (0%) 30.5 KB
Core (Content Script - v1.1) - NPM (UMD) 29.71 KB 29.71 KB (0%) 30.5 KB
Core (v1.1) - Legacy - CDN 32.03 KB 32.03 KB (0%) 32.5 KB
Core (v1.1) - Modern - CDN 30.01 KB 30.01 KB (0%) 32 KB
Service Worker - Legacy - NPM (ESM) 30.54 KB 30.54 KB (0%) 31 KB
Service Worker - Legacy - NPM (CJS) 30.85 KB 30.85 KB (0%) 31 KB
Service Worker - Legacy - NPM (UMD) 30.69 KB 30.69 KB (0%) 31 KB
Service Worker - Modern - NPM (ESM) 25.73 KB 25.73 KB (0%) 26 KB
Service Worker - Modern - NPM (CJS) 26 KB 26 KB (0%) 26.5 KB
Service Worker - Modern - NPM (UMD) 25.75 KB 25.75 KB (0%) 26 KB
Core - Legacy - NPM (ESM) 47.38 KB 47.38 KB (+0.01% ▲) 48 KB
Core - Legacy - NPM (CJS) 47.66 KB 47.63 KB (-0.05% ▼) 48 KB
Core - Legacy - NPM (UMD) 47.46 KB 47.42 KB (-0.1% ▼) 48 KB
Core - Legacy - CDN 47.54 KB 47.48 KB (-0.14% ▼) 47.6 KB
Core - Modern - NPM (ESM) 26.85 KB 26.87 KB (+0.07% ▲) 27 KB
Core - Modern - NPM (CJS) 27.11 KB 27.07 KB (-0.15% ▼) 27.2 KB
Core - Modern - NPM (UMD) 26.9 KB 26.89 KB (-0.04% ▼) 27 KB
Core - Modern - CDN 27.17 KB 27.15 KB (-0.08% ▼) 27.5 KB
Core (Bundled) - Legacy - NPM (ESM) 47.38 KB 47.38 KB (+0.01% ▲) 48 KB
Core (Bundled) - Legacy - NPM (CJS) 47.62 KB 47.63 KB (+0.02% ▲) 48 KB
Core (Bundled) - Legacy - NPM (UMD) 47.46 KB 47.42 KB (-0.1% ▼) 48 KB
Core (Bundled) - Modern - NPM (ESM) 38.61 KB 38.55 KB (-0.17% ▼) 39 KB
Core (Bundled) - Modern - NPM (CJS) 38.86 KB 38.83 KB (-0.07% ▼) 39 KB
Core (Bundled) - Modern - NPM (UMD) 38.64 KB 38.6 KB (-0.09% ▼) 39 KB
Core (Content Script) - Legacy - NPM (ESM) 47.41 KB 47.34 KB (-0.15% ▼) 48 KB
Core (Content Script) - Legacy - NPM (CJS) 47.59 KB 47.59 KB (0%) 48 KB
Core (Content Script) - Legacy - NPM (UMD) 47.41 KB 47.33 KB (-0.16% ▼) 48 KB
Core (Content Script) - Modern - NPM (ESM) 38.51 KB 38.5 KB (-0.03% ▼) 39 KB
Core (Content Script) - Modern - NPM (CJS) 38.75 KB 38.78 KB (+0.07% ▲) 39 KB
Core (Content Script) - Modern - NPM (UMD) 38.52 KB 38.56 KB (+0.11% ▲) 39 KB
All Integrations - Legacy - CDN 95.1 KB 95.1 KB (0%) 95.3 KB
All Integrations - Modern - CDN 90.67 KB 90.67 KB (0%) 91 KB

coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 21, 2025
@saikumarrs saikumarrs marked this pull request as ready for review February 21, 2025 13:06
@saikumarrs saikumarrs requested a review from a team as a code owner February 21, 2025 13:06
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
packages/analytics-js/src/services/ErrorHandler/ErrorHandler.ts (2)

44-55: Consider adding explicit access modifier and handling concurrent initialization.

The init() method implementation looks good, but consider these improvements:

  1. Add explicit public modifier for better clarity
  2. Consider using a synchronization mechanism to handle concurrent initialization calls safely
-  init() {
+  public init() {
     if (this.initialized) {
       return;
     }
 
+    // Consider using a more robust synchronization mechanism
+    // if concurrent initialization is possible
     this.attachErrorListeners();
     this.initialized = true;
   }

157-157: Add documentation for initialization requirement.

The defaultErrorHandler instance is created but not initialized. Consider adding a comment to document that init() must be called before use.

+// Note: Remember to call defaultErrorHandler.init() before use
 const defaultErrorHandler = new ErrorHandler(defaultHttpClient, defaultLogger);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9cafb17 and 571a542.

📒 Files selected for processing (2)
  • packages/analytics-js/__tests__/services/StoreManager/storages/CookieStorage.test.ts (3 hunks)
  • packages/analytics-js/src/services/ErrorHandler/ErrorHandler.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/analytics-js/tests/services/StoreManager/storages/CookieStorage.test.ts
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Bundle size checks
  • GitHub Check: Unit Tests and Lint
  • GitHub Check: Security and code quality checks
🔇 Additional comments (4)
packages/analytics-js/src/services/ErrorHandler/ErrorHandler.ts (4)

36-36: LGTM! Good use of private flag for initialization control.

The private initialized flag is a good addition to prevent multiple initializations of the error handler.


39-42: LGTM! Good separation of construction and initialization.

Moving initialization out of the constructor aligns with the PR's objective of avoiding premature execution and follows good practices for better initialization control.


44-48: LGTM! Clear and comprehensive documentation.

The added JSDoc comments provide clear explanations of method purposes and usage, which improves code maintainability.

Also applies to: 57-59, 73-79


33-159:

❓ Verification inconclusive

Verify the initialization sequence in the SDK.

The changes look good and align with the PR objective of avoiding premature execution. Let's verify the initialization sequence:


🏁 Script executed:

#!/bin/bash
# Search for init() calls to ensure proper initialization sequence
rg -A 5 "defaultErrorHandler.init\(\)" --type ts

Length of output: 199


Let's re-run the search without the file type filter to ensure we capture any initialization calls for the default error handler. This should give us a more complete picture of where and how defaultErrorHandler.init() is invoked.

Once this script runs, please share its output or verify the results manually so we can confidently assess the initialization sequence in the SDK.


🏁 Script executed:

#!/bin/bash
# Search for defaultErrorHandler.init() call across the repository without type filtering
rg -A 5 "defaultErrorHandler\.init\(" .

Length of output: 41


Ensure SDK initialization is correctly triggered.

The implementation in ErrorHandler.ts aligns with the PR objective to avoid premature execution by deferring the error handler initialization. However, our repository search did not find any calls to defaultErrorHandler.init(). This likely means that initialization is expected to be triggered manually by the consuming application. Please verify that this initialization strategy is intentional and that the application documentation or bootstrap logic explicitly includes a call to init() when appropriate.

coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 21, 2025
@saikumarrs saikumarrs force-pushed the fix.avoid-pre-mature-initialization-sdk-3003 branch from 1810a87 to 762eaeb Compare February 24, 2025 05:19
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
packages/analytics-js/src/services/ErrorHandler/ErrorHandler.ts (2)

48-55: Add dependency validation in init method.

While the initialization control is well-implemented, consider validating the required dependencies (httpClient and logger) to prevent potential runtime errors.

 public init() {
   if (this.initialized) {
     return;
   }

+  if (!this.httpClient || !this.logger) {
+    throw new Error('ErrorHandler dependencies not properly initialized');
+  }
+
   this.attachErrorListeners();
   this.initialized = true;
 }

157-158: Consider enforcing initialization at type level.

While the note is helpful, consider enforcing initialization through TypeScript to catch usage errors at compile time rather than runtime.

Here's a pattern you could use:

class ErrorHandler implements IErrorHandler {
  private constructor(httpClient: IHttpClient, logger: ILogger) {
    // ... existing constructor code
  }

  public static create(httpClient: IHttpClient, logger: ILogger): ErrorHandler {
    const handler = new ErrorHandler(httpClient, logger);
    handler.init();
    return handler;
  }
}

// Usage
const defaultErrorHandler = ErrorHandler.create(defaultHttpClient, defaultLogger);

This pattern ensures that the error handler is always initialized at creation time.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 571a542 and 762eaeb.

📒 Files selected for processing (21)
  • examples/v3/index.html (1 hunks)
  • packages/analytics-js-common/__mocks__/ErrorHandler.ts (1 hunks)
  • packages/analytics-js-common/__mocks__/Store.ts (1 hunks)
  • packages/analytics-js-common/src/types/ErrorHandler.ts (1 hunks)
  • packages/analytics-js-common/src/types/Store.ts (1 hunks)
  • packages/analytics-js/__tests__/services/ErrorHandler/ErrorHandler.test.ts (1 hunks)
  • packages/analytics-js/__tests__/services/StoreManager/StoreManager.test.ts (1 hunks)
  • packages/analytics-js/__tests__/services/StoreManager/storages/CookieStorage.test.ts (3 hunks)
  • packages/analytics-js/__tests__/services/StoreManager/storages/InMemoryStorage.test.ts (1 hunks)
  • packages/analytics-js/__tests__/services/StoreManager/storages/LocalStorage.test.ts (1 hunks)
  • packages/analytics-js/__tests__/services/StoreManager/storages/defaultOptions.test.ts (1 hunks)
  • packages/analytics-js/__tests__/services/StoreManager/storages/sessionStorage.test.ts (1 hunks)
  • packages/analytics-js/src/app/RudderAnalytics.ts (3 hunks)
  • packages/analytics-js/src/services/ErrorHandler/ErrorHandler.ts (3 hunks)
  • packages/analytics-js/src/services/StoreManager/Store.ts (2 hunks)
  • packages/analytics-js/src/services/StoreManager/StoreManager.ts (1 hunks)
  • packages/analytics-js/src/services/StoreManager/storages/CookieStorage.ts (2 hunks)
  • packages/analytics-js/src/services/StoreManager/storages/InMemoryStorage.ts (2 hunks)
  • packages/analytics-js/src/services/StoreManager/storages/LocalStorage.ts (2 hunks)
  • packages/analytics-js/src/services/StoreManager/storages/sessionStorage.ts (2 hunks)
  • packages/analytics-js/src/services/StoreManager/storages/storageEngine.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (20)
  • packages/analytics-js/tests/services/StoreManager/storages/defaultOptions.test.ts
  • packages/analytics-js/tests/services/StoreManager/storages/sessionStorage.test.ts
  • packages/analytics-js-common/mocks/ErrorHandler.ts
  • packages/analytics-js/tests/services/ErrorHandler/ErrorHandler.test.ts
  • packages/analytics-js/tests/services/StoreManager/storages/InMemoryStorage.test.ts
  • packages/analytics-js/src/services/StoreManager/Store.ts
  • packages/analytics-js-common/mocks/Store.ts
  • packages/analytics-js-common/src/types/ErrorHandler.ts
  • packages/analytics-js-common/src/types/Store.ts
  • packages/analytics-js/src/services/StoreManager/storages/storageEngine.ts
  • examples/v3/index.html
  • packages/analytics-js/src/services/StoreManager/StoreManager.ts
  • packages/analytics-js/tests/services/StoreManager/storages/CookieStorage.test.ts
  • packages/analytics-js/src/app/RudderAnalytics.ts
  • packages/analytics-js/tests/services/StoreManager/StoreManager.test.ts
  • packages/analytics-js/src/services/StoreManager/storages/InMemoryStorage.ts
  • packages/analytics-js/src/services/StoreManager/storages/sessionStorage.ts
  • packages/analytics-js/src/services/StoreManager/storages/CookieStorage.ts
  • packages/analytics-js/src/services/StoreManager/storages/LocalStorage.ts
  • packages/analytics-js/tests/services/StoreManager/storages/LocalStorage.test.ts
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Bundle size checks
  • GitHub Check: Security and code quality checks
  • GitHub Check: Unit Tests and Lint
🔇 Additional comments (2)
packages/analytics-js/src/services/ErrorHandler/ErrorHandler.ts (2)

36-36: LGTM! Good use of private flag for initialization control.

The private initialized flag is well-designed to prevent multiple initializations.


44-47: LGTM! Well-documented methods.

The JSDoc comments are clear, comprehensive, and follow best practices.

Also applies to: 57-59, 73-79

coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 24, 2025
@saikumarrs saikumarrs force-pushed the fix.avoid-pre-mature-initialization-sdk-3003 branch from 762eaeb to 8a5db91 Compare February 27, 2025 09:10
@saikumarrs saikumarrs merged commit 9c7e2a6 into develop Mar 2, 2025
12 checks passed
@saikumarrs saikumarrs deleted the fix.avoid-pre-mature-initialization-sdk-3003 branch March 2, 2025 12:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

BUG : v3.14.0 throwing constant globalThis.addEventListener is not a function errors
2 participants