Skip to content

Add support for queryParams#66

Merged
steven-tey merged 3 commits intomainfrom
support-queryParams
Oct 7, 2025
Merged

Add support for queryParams#66
steven-tey merged 3 commits intomainfrom
support-queryParams

Conversation

@devkiran
Copy link
Collaborator

@devkiran devkiran commented Oct 7, 2025

Summary by CodeRabbit

  • New Features

    • Support for specifying multiple tracking query parameters; attribution picks the first matching value.
  • Deprecations

    • The single-parameter option is deprecated; switch to the multi-parameter setting.
  • Documentation

    • Guidance updated to show the new multi-parameter option and migration from the old setting.
  • Bug Fixes

    • Logs a warning when multi-parameter configuration is malformed.
  • Chores

    • Patch version bumps for script and web packages.

@vercel
Copy link

vercel bot commented Oct 7, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
analytics-nextjs-geolocation-script Ready Ready Preview Comment Oct 7, 2025 5:24pm

@coderabbitai
Copy link

coderabbitai bot commented Oct 7, 2025

Walkthrough

Replaces single-query-param resolution with support for multiple query params: script reads data-query-params (JSON) or data-query-param, builds a deduplicated QUERY_PARAMS array (default ['via']), then scans the URL for the first present param. Web layer can set queryParams; types add queryParams and deprecate queryParam. Script and web package versions bumped.

Changes

Cohort / File(s) Summary of edits
Query param resolution & public API
packages/script/src/base.js
Replaced single-param logic with a resolver that reads data-query-param and data-query-params (JSON-string or fallback), defaults to ['via'], deduplicates, warns on JSON parse failure, computes QUERY_PARAMS then finds the first matching query value. Adjusted window._dubAnalytics export: removed legacy p/v mappings and some legacy fields, added qm (queueManager), preserved core keys and exposes QUERY_PARAMS-based resolution. Also bumped package version in packages/script/package.json.
Web prop handling for multiple params
packages/web/src/generic.ts
When props.queryParams is provided, sets a data-query-params attribute with JSON.stringify(props.queryParams) on the injected script tag (keeps existing data-query-param behavior). Also bumped package version in packages/web/package.json.
Type additions & deprecation
packages/web/src/types.ts
Added AnalyticsProps.queryParams?: string[]. Marked AnalyticsProps.queryParam as @deprecated in JSDoc with guidance to use queryParams.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User as User
  participant Page as Web Page
  participant Web as web/generic.ts
  participant Tag as Script Tag (DOM)
  participant Script as script/base.js
  participant URL as Window.location

  Note over Web,Tag: Web layer may set data-query-param and/or data-query-params

  User->>Page: Load page
  Page->>Web: Render Analytics component (props)
  alt props.queryParams provided
    Web->>Tag: set data-query-params = JSON.stringify(props.queryParams)
  end
  opt props.queryParam provided
    Web->>Tag: set data-query-param = props.queryParam
  end
  Page->>Script: Execute analytics script
  Script->>Tag: Read data-query-params / data-query-param
  Script->>Script: Compute QUERY_PARAMS (parse, fallback, dedupe, default ['via'])
  Script->>URL: Scan query string for first matching param in QUERY_PARAMS
  alt Found
    Script->>Script: QUERY_PARAM_VALUE = first found value
  else None
    Script->>Script: QUERY_PARAM_VALUE = null
  end
  Script->>Window: Expose analytics surface (includes QUERY_PARAMS and qm)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

I nibbled through keys in a tidy heap,
Collected each clue the query might keep.
The first sweet crumb I find becomes my prize,
If none appear, I blink my gentle eyes.
New params, same hop — onward through the skies. 🐇✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title clearly and concisely conveys the primary change of adding support for the new queryParams feature in the analytics package, matching the core objective of the PR without extraneous detail.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch support-queryParams

📜 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 b0aecf1 and ac9ef25.

📒 Files selected for processing (2)
  • packages/script/package.json (1 hunks)
  • packages/web/package.json (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • packages/web/package.json
  • packages/script/package.json

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@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/web/src/generic.ts (1)

82-84: LGTM! Consider documenting the precedence when both properties are set.

The code correctly sets data-query-params when props.queryParams is provided. However, since both queryParam and queryParams can be set simultaneously (lines 78-80 and 82-84), and the script layer gives precedence to data-query-param, it may be helpful to document this behavior to avoid user confusion during the migration from the deprecated queryParam to queryParams.

packages/web/src/types.ts (1)

146-146: Consider enhancing the deprecation notice with precedence details.

The deprecation message correctly directs users to queryParams, but could benefit from clarifying that if both queryParam and queryParams are set simultaneously, queryParam takes precedence (based on the script layer's implementation).

Apply this diff to improve the deprecation notice:

-  * @deprecated Use queryParams instead
+  * @deprecated Use queryParams instead. Note: if both are set, queryParam takes precedence.
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 565567c and e558f2d.

📒 Files selected for processing (3)
  • packages/script/src/base.js (2 hunks)
  • packages/web/src/generic.ts (1 hunks)
  • packages/web/src/types.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
packages/web/src/generic.ts (1)
packages/script/src/base.js (1)
  • script (3-3)
🔇 Additional comments (4)
packages/script/src/base.js (3)

66-90: LGTM! Clear fallback hierarchy and good error handling.

The resolution logic correctly implements the priority: data-query-paramdata-query-params → default ['via'], with deduplication via Set. The warning on parse failure is appropriate.


92-102: LGTM! First-match strategy is correct.

The loop returns the first query parameter with a non-null value, providing a sensible fallback mechanism across multiple candidates.


306-306: No internal references to _dubAnalytics.p were found; verify downstream consumers handle the change from a string to an array.

packages/web/src/types.ts (1)

150-155: LGTM! Clear documentation of the new property.

The queryParams property is well-documented with an appropriate default value and clear usage examples from the existing queryParam documentation.

Copy link

@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 (3)
packages/script/src/base.js (3)

73-87: Clarify behavior when both attributes are present.

The else if logic means only data-query-param is processed when both data-query-param and data-query-params are present. While the web layer types deprecate queryParam in favor of queryParams, the script should handle edge cases where both attributes exist.

Consider documenting this behavior or handling both attributes by merging them instead of mutual exclusion.

Apply this diff to merge both attributes when present:

-    if (queryParam) {
+    if (queryParam && !queryParams) {
       resolvedQueryParams = [queryParam, ...resolvedQueryParams];
-    } else if (queryParams) {
+    } else if (queryParams && !queryParam) {
       try {
         resolvedQueryParams = [
           ...JSON.parse(queryParams),
           ...resolvedQueryParams,
         ];
       } catch (error) {
         console.warn(
           '[dubAnalytics] Failed to parse data-query-params.',
           error,
         );
       }
+    } else if (queryParam && queryParams) {
+      try {
+        resolvedQueryParams = [
+          queryParam,
+          ...JSON.parse(queryParams),
+          ...resolvedQueryParams,
+        ];
+      } catch (error) {
+        console.warn(
+          '[dubAnalytics] Failed to parse data-query-params.',
+          error,
+        );
+        resolvedQueryParams = [queryParam, ...resolvedQueryParams];
+      }
     }

Alternatively, if mutual exclusivity is intentional, add a warning when both are present to guide developers toward the new API.


82-85: Include the failed value in the error message.

When JSON parsing fails, logging the attempted value would aid debugging.

Apply this diff:

       } catch (error) {
         console.warn(
-          '[dubAnalytics] Failed to parse data-query-params.',
+          `[dubAnalytics] Failed to parse data-query-params: "${queryParams}".`,
           error,
         );
       }

92-102: Optimize redundant params.get() calls.

The current logic calls params.get(param) twice per iteration—once to check and once to return. Store the result to avoid redundant lookups.

Apply this diff:

   const QUERY_PARAM_VALUE = (() => {
     const params = new URLSearchParams(location.search);
 
     for (const param of QUERY_PARAMS) {
-      if (params.get(param)) {
-        return params.get(param);
+      const value = params.get(param);
+      if (value) {
+        return value;
       }
     }
 
     return null;
   })();
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e558f2d and b0aecf1.

📒 Files selected for processing (1)
  • packages/script/src/base.js (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
packages/script/src/base.js (2)
packages/script/src/extensions/outbound-domains.js (1)
  • cookieManager (3-8)
packages/script/src/extensions/site-visit.js (1)
  • cookieManager (3-10)
🔇 Additional comments (1)
packages/script/src/base.js (1)

298-308: Confirm external dependencies on removed window._dubAnalytics properties
Internal search shows no references to the removed p, m, or o exports. If any external integrations or published extensions rely on these properties, update them accordingly; otherwise the removal is safe.

@devkiran
Copy link
Collaborator Author

devkiran commented Oct 7, 2025

@coderabbitai final review, any breaking changes?

@coderabbitai
Copy link

coderabbitai bot commented Oct 7, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash

# Get the diff for base.js to see what changed in window._dubAnalytics
git diff main...support-queryParams -- packages/script/src/base.js

echo "---"
echo "Checking types.ts changes:"
git diff main...support-queryParams -- packages/web/src/types.ts

echo "---"
echo "Checking generic.ts changes:"
git diff main...support-queryParams -- packages/web/src/generic.ts

Length of output: 210


🏁 Script executed:

#!/bin/bash

# Fetch the branches
git fetch origin main:main 2>/dev/null || true
git fetch origin support-queryParams:support-queryParams 2>/dev/null || true

# Get the diff using the correct syntax
git diff main..HEAD -- packages/script/src/base.js

echo "---"
echo "Checking types.ts changes:"
git diff main..HEAD -- packages/web/src/types.ts

echo "---"
echo "Checking generic.ts changes:"
git diff main..HEAD -- packages/web/src/generic.ts

Length of output: 3754


@devkiran: Here's the final review focusing on breaking changes:

⚠️ Breaking Changes Identified

1. window._dubAnalytics API Changes (HIGH IMPACT)

The following properties have been removed from the window._dubAnalytics object:

  • o (COOKIE_OPTIONS) - Removed entirely
  • m (ATTRIBUTION_MODEL) - Removed entirely
  • p (QUERY_PARAM) - Removed entirely (replaced by multi-param logic)

Impact: Any code that directly accesses these properties will break.

// ❌ BREAKS - These will now be undefined
window._dubAnalytics.o // was COOKIE_OPTIONS
window._dubAnalytics.m // was ATTRIBUTION_MODEL
window._dubAnalytics.p // was QUERY_PARAM

2. QUERY_PARAM_VALUE Behavior Change (MEDIUM IMPACT)

The v property (QUERY_PARAM_VALUE) behavior has changed:

  • Before: Returned undefined if query param not found
  • After: Returns null if no query params found, and now checks multiple params in priority order

Impact: Code checking for undefined vs null may behave differently.

// Before: new URLSearchParams(location.search).get(QUERY_PARAM) → undefined if not found
// After: Iterates through QUERY_PARAMS, returns first match or null

✅ Non-Breaking Changes

  1. queryParam property - Deprecated but not removed, fully backward compatible
  2. queryParams property - New additive feature, backward compatible
  3. qm (queueManager) - New property in window._dubAnalytics, additive

Recommendations

  1. Document the breaking changes in the PR description and CHANGELOG
  2. Consider version bump: This should be a major version bump (e.g., 1.x.x → 2.0.0) if you follow semver
  3. Migration guide: If the removed properties were intended for external use, provide migration guidance
  4. Internal API consideration: If window._dubAnalytics is purely internal and not documented as a public API, these changes may be acceptable

Are these breaking changes intentional, or should we preserve the removed properties for backward compatibility?

@steven-tey steven-tey merged commit 8b88934 into main Oct 7, 2025
4 checks passed
@steven-tey steven-tey deleted the support-queryParams branch October 7, 2025 17:25
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.

2 participants