@adhub-so/adhub-nextjs-sdk 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -44,7 +44,7 @@ export default function RootLayout({ children }: { children: React.ReactNode })
44
44
 
45
45
  That completes the basic browser integration. With no `endpoint`, the SDK sends directly to `https://api.adhub.so`. It automatically captures landing parameters and pageviews, sends queued events, retries transient failures, and restores pending events after a reload.
46
46
 
47
- If the AdHub project has a Google Ads website tag enabled, the SDK also loads that `AW-…` tag so Google can measure its own sessions and conversions. This is not AdSense, and it does not replace AdHub offline conversion uploads. Set `waitForConsent` when the tag must wait for a consent choice. See [Google Ads website tag](#google-ads-website-tag).
47
+ If the AdHub project has a Google Ads website tag enabled, the SDK also loads that `AW-…` tag so Google can measure its own sessions and conversions. This is not AdSense, and it does not replace AdHub offline conversion uploads. If Microsoft Clarity is enabled for the project, the SDK loads that tag too. Set `waitForConsent` when those tags must wait for a consent choice. See [Google Ads website tag](#google-ads-website-tag) and [Microsoft Clarity](#microsoft-clarity).
48
48
 
49
49
  Do not add a Route Handler or call `flush()` after every event for this setup.
50
50
 
@@ -106,6 +106,7 @@ Browser payloads can be modified by users. Trusted payment, refund, subscription
106
106
  The minimal setup above does not require any of the following features. Use them only for a specific application requirement.
107
107
 
108
108
  - [Google Ads website tag](#google-ads-website-tag) for consent, SPA page views, and the same-origin config proxy.
109
+ - [Microsoft Clarity](#microsoft-clarity) when the project enables Clarity session recordings.
109
110
  - [First-party Route Handler](#first-party-route-handler) for a same-origin collection path, customer-edge geo headers, or a custom API target.
110
111
  - [Capture before hydration](#capture-before-hydration) when application code removes attribution parameters before React hydrates.
111
112
  - [Manual flush and queue control](#manual-flush-and-queue-control) for tests, diagnostics, or `autoFlush: false`.
@@ -125,7 +126,7 @@ After `init`, the SDK requests `GET /api/v1/saas/sdk/config`. When `googleAdsWeb
125
126
 
126
127
  A disabled tag, a null conversion id, a non-OK response, or a network failure does not throw and does not block touchpoints, identity, pageviews, or events. The SDK writes an `[AdHub SDK]` console warning only when `debug` is on.
127
128
 
128
- `waitForConsent` skips the config request and the tag. There is no consent callback. After the visitor allows advertising cookies, call `init` again for the same project with `waitForConsent` omitted or `false` and the SDK loads the tag. A tag that was already injected is not removed.
129
+ `waitForConsent` skips the config request, so neither this tag nor Microsoft Clarity is loaded. There is no consent callback. After the visitor allows the tags, call `init` again for the same project with `waitForConsent` omitted or `false` and the SDK loads them. A tag that was already injected is not removed.
129
130
 
130
131
  ```tsx
131
132
  <AdHubComponent
@@ -136,6 +137,27 @@ A disabled tag, a null conversion id, a non-OK response, or a network failure do
136
137
 
137
138
  Same-origin proxy mode must forward this GET. Export `GET` from the catch-all Route Handler as well as `POST` and `OPTIONS`. `script-src` must allow `https://www.googletagmanager.com` when the tag is enabled. Direct delivery to `https://api.adhub.so` does not need the Route Handler.
138
139
 
140
+ ### Microsoft Clarity
141
+
142
+ The same `GET /api/v1/saas/sdk/config` response may include `clarity`. When `clarity.enabled` is true and `clarity.projectId` is the Clarity project id, the SDK installs Microsoft's tag once for the page:
143
+
144
+ ```js
145
+ (function(c,l,a,r,i,t,y){
146
+ c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};
147
+ t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i;
148
+ y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y);
149
+ })(window, document, "clarity", "script", PROJECT_ID);
150
+ ```
151
+
152
+ - An existing `window.clarity` is reused. Otherwise the SDK defines the standard queue function.
153
+ - `https://www.clarity.ms/tag/<projectId>` is inserted once, before the first script tag (or appended when the page has none), and marked with `data-adhub-clarity`. A script whose `src` is already that URL is left in place. A Clarity script for a different project is also left in place; the SDK does not add a second tag.
154
+ - Injection is idempotent. `window.__ADHUB_CLARITY__` records `{ projectId }`, so a later `init` on the same page does not insert another script.
155
+ - `identify()` calls `clarity('identify', profileId)` when `window.clarity` is available. Only the AdHub profile id is sent. Email and name are not.
156
+
157
+ A disabled tag, a missing or invalid project id, a non-OK response, or a network failure does not throw and does not block touchpoints, identity, pageviews, or events. The SDK writes an `[AdHub SDK]` console warning only when `debug` is on.
158
+
159
+ `waitForConsent` skips the shared config request, so Clarity waits along with the Google Ads tag. `script-src` must allow `https://www.clarity.ms` when the tag is enabled. Clarity also sends its own beacons to `https://*.clarity.ms`.
160
+
139
161
  ### First-party Route Handler
140
162
 
141
163
  This is an optional delivery mode, not a prerequisite for using the browser SDK. Direct delivery already gives AdHub the browser connection IP, User-Agent, and site Origin.
package/dist/index.cjs CHANGED
@@ -383,7 +383,7 @@ var BrowserStore = class {
383
383
  // src/client.ts
384
384
  var DEFAULT_ENDPOINT = "https://api.adhub.so";
385
385
  var SDK_NAME = "nextjs";
386
- var SDK_VERSION = "0.2.0";
386
+ var SDK_VERSION = "0.3.0";
387
387
  var REQUEST_TIMEOUT_MS = 5e3;
388
388
  var RETRY_INTERVAL_MS = 15e3;
389
389
  var PAGE_ENGAGEMENT_INTERVAL_MS = 5e3;
@@ -392,6 +392,7 @@ var BEHAVIOR_EVENTS_PATH = "/api/v1/saas/sdk/behavior-events";
392
392
  var PAGE_ENGAGEMENTS_PATH = "/api/v1/saas/sdk/page-engagements";
393
393
  var SDK_CONFIG_PATH = "/api/v1/saas/sdk/config";
394
394
  var GOOGLE_ADS_CONVERSION_ID = /^AW-\d{6,20}$/;
395
+ var CLARITY_PROJECT_ID = /^[0-9a-z]{4,32}$/;
395
396
  function decideGoogleAdsTag(payload) {
396
397
  if (!payload || typeof payload !== "object") return { action: "skip" };
397
398
  const tag = payload.googleAdsWebsiteTag;
@@ -449,6 +450,62 @@ function injectGoogleAdsWebsiteTag(conversionId) {
449
450
  marker.configuredIds.push(conversionId);
450
451
  gtag("config", conversionId);
451
452
  }
453
+ function decideClarity(payload) {
454
+ if (!payload || typeof payload !== "object") return { action: "skip" };
455
+ const clarity = payload.clarity;
456
+ if (!clarity || typeof clarity !== "object") return { action: "skip" };
457
+ const record = clarity;
458
+ if (record.enabled !== true) return { action: "skip" };
459
+ if (typeof record.projectId !== "string" || record.projectId.trim() === "") {
460
+ return { action: "skip" };
461
+ }
462
+ const projectId = record.projectId.trim();
463
+ if (!CLARITY_PROJECT_ID.test(projectId)) return { action: "invalid" };
464
+ return { action: "inject", projectId };
465
+ }
466
+ function clarityScriptSrc(projectId) {
467
+ return `https://www.clarity.ms/tag/${projectId}`;
468
+ }
469
+ function installClarityQueue() {
470
+ window.clarity = window.clarity || function clarity() {
471
+ const stub = window.clarity;
472
+ if (!stub) return;
473
+ (stub.q = stub.q || []).push(arguments);
474
+ };
475
+ }
476
+ function clarityProjectOnPage() {
477
+ const marker = window.__ADHUB_CLARITY__;
478
+ if (marker && typeof marker.projectId === "string" && CLARITY_PROJECT_ID.test(marker.projectId)) {
479
+ return marker.projectId;
480
+ }
481
+ const match = /^https:\/\/www\.clarity\.ms\/tag\/([0-9a-z]{4,32})$/;
482
+ for (const script of document.getElementsByTagName("script")) {
483
+ const projectId = match.exec(script.src)?.[1];
484
+ if (projectId) return projectId;
485
+ }
486
+ return null;
487
+ }
488
+ function injectClarity(projectId) {
489
+ const installed = clarityProjectOnPage();
490
+ if (installed) {
491
+ if (!window.__ADHUB_CLARITY__) window.__ADHUB_CLARITY__ = { projectId: installed };
492
+ if (installed === projectId) installClarityQueue();
493
+ return installed === projectId;
494
+ }
495
+ installClarityQueue();
496
+ const script = document.createElement("script");
497
+ script.async = true;
498
+ script.src = clarityScriptSrc(projectId);
499
+ script.setAttribute("data-adhub-clarity", projectId);
500
+ const firstScript = document.getElementsByTagName("script")[0];
501
+ if (firstScript?.parentNode) {
502
+ firstScript.parentNode.insertBefore(script, firstScript);
503
+ } else {
504
+ (document.head ?? document.documentElement).appendChild(script);
505
+ }
506
+ window.__ADHUB_CLARITY__ = { projectId };
507
+ return true;
508
+ }
452
509
  var EMPTY_STATE = {
453
510
  initialized: false,
454
511
  anonymousId: null,
@@ -575,7 +632,8 @@ var AdHubBrowserClient = class {
575
632
  this.autoTrackDataAttributes = true;
576
633
  this.trackHashChanges = false;
577
634
  this.waitForConsent = false;
578
- this.gtagAbort = null;
635
+ this.sdkConfigAbort = null;
636
+ this.clarityIdentifiedProfileId = null;
579
637
  this.lastPageSignature = "";
580
638
  this.lastTrackedPageUrl = "";
581
639
  this.pendingPageReferrer = null;
@@ -632,7 +690,7 @@ var AdHubBrowserClient = class {
632
690
  if (this.state.initialized && this.projectKey === projectKey && this.endpoint === endpoint) {
633
691
  if (this.waitForConsent && options.waitForConsent !== true) {
634
692
  this.waitForConsent = false;
635
- this.scheduleGoogleAdsWebsiteTag();
693
+ this.scheduleSdkConfigTags();
636
694
  }
637
695
  return;
638
696
  }
@@ -685,7 +743,7 @@ var AdHubBrowserClient = class {
685
743
  this.installBehaviorTracking();
686
744
  }
687
745
  this.scheduleFlush();
688
- this.scheduleGoogleAdsWebsiteTag();
746
+ this.scheduleSdkConfigTags();
689
747
  } catch (error) {
690
748
  this.reportError(error);
691
749
  }
@@ -720,6 +778,7 @@ var AdHubBrowserClient = class {
720
778
  this.updateState({ profileId: profile.profileId, lastError: null });
721
779
  this.enqueue("/api/v1/saas/sdk/identify", "profile.identify", data);
722
780
  this.scheduleFlush();
781
+ this.identifyInClarity(profile.profileId);
723
782
  } catch (error) {
724
783
  this.reportError(error);
725
784
  }
@@ -811,6 +870,7 @@ var AdHubBrowserClient = class {
811
870
  const sessionId = randomId("sess");
812
871
  this.store.writeSession(sessionId);
813
872
  this.updateState({ anonymousId, sessionId, profileId: null, lastError: null });
873
+ this.clarityIdentifiedProfileId = null;
814
874
  this.lastPageSignature = "";
815
875
  this.lastTrackedPageUrl = "";
816
876
  this.pendingPageReferrer = null;
@@ -841,8 +901,8 @@ var AdHubBrowserClient = class {
841
901
  return () => this.listeners.delete(listener);
842
902
  }
843
903
  destroy() {
844
- this.gtagAbort?.abort();
845
- this.gtagAbort = null;
904
+ this.sdkConfigAbort?.abort();
905
+ this.sdkConfigAbort = null;
846
906
  this.finishPageVisit();
847
907
  if (browserAvailable() && this.lifecycleInstalled) {
848
908
  window.removeEventListener("online", this.onOnline);
@@ -1081,17 +1141,17 @@ var AdHubBrowserClient = class {
1081
1141
  this.store?.saveQueue(this.queue);
1082
1142
  this.updateState({ queuedCount: this.queue.length });
1083
1143
  }
1084
- scheduleGoogleAdsWebsiteTag() {
1144
+ scheduleSdkConfigTags() {
1085
1145
  if (!browserAvailable() || this.waitForConsent) return;
1086
- this.gtagAbort?.abort();
1146
+ this.sdkConfigAbort?.abort();
1087
1147
  const abort = new AbortController();
1088
- this.gtagAbort = abort;
1148
+ this.sdkConfigAbort = abort;
1089
1149
  queueMicrotask(() => {
1090
1150
  if (abort.signal.aborted) return;
1091
- void this.fetchAndInjectGoogleAdsWebsiteTag(abort);
1151
+ void this.fetchAndApplySdkConfig(abort);
1092
1152
  });
1093
1153
  }
1094
- async fetchAndInjectGoogleAdsWebsiteTag(abort) {
1154
+ async fetchAndApplySdkConfig(abort) {
1095
1155
  const timeout = setTimeout(() => abort.abort(), REQUEST_TIMEOUT_MS);
1096
1156
  try {
1097
1157
  const response = await fetch(`${this.endpoint}${SDK_CONFIG_PATH}`, {
@@ -1102,29 +1162,58 @@ var AdHubBrowserClient = class {
1102
1162
  });
1103
1163
  if (abort.signal.aborted) return;
1104
1164
  if (!response.ok) {
1105
- this.log(`Google Ads website tag config returned HTTP ${response.status}.`);
1165
+ this.log(`SDK config returned HTTP ${response.status}.`);
1106
1166
  return;
1107
1167
  }
1108
1168
  let payload;
1109
1169
  try {
1110
1170
  payload = await response.json();
1111
1171
  } catch (error) {
1112
- this.log(`Google Ads website tag config was not applied: ${errorMessage(error)}`);
1172
+ this.log(`SDK config was not applied: ${errorMessage(error)}`);
1113
1173
  return;
1114
1174
  }
1115
1175
  if (abort.signal.aborted) return;
1116
- const decision = decideGoogleAdsTag(payload);
1176
+ this.applyGoogleAdsWebsiteTag(payload);
1177
+ this.applyClarity(payload);
1178
+ } catch (error) {
1179
+ if (abort.signal.aborted) return;
1180
+ this.log(`SDK config was not applied: ${errorMessage(error)}`);
1181
+ } finally {
1182
+ clearTimeout(timeout);
1183
+ }
1184
+ }
1185
+ applyGoogleAdsWebsiteTag(payload) {
1186
+ const decision = decideGoogleAdsTag(payload);
1187
+ if (decision.action === "skip") return;
1188
+ if (decision.action === "invalid") {
1189
+ this.log("Google Ads website tag config did not include a valid AW- conversion id.");
1190
+ return;
1191
+ }
1192
+ injectGoogleAdsWebsiteTag(decision.conversionId);
1193
+ }
1194
+ applyClarity(payload) {
1195
+ try {
1196
+ const decision = decideClarity(payload);
1117
1197
  if (decision.action === "skip") return;
1118
1198
  if (decision.action === "invalid") {
1119
- this.log("Google Ads website tag config did not include a valid AW- conversion id.");
1199
+ this.log("Microsoft Clarity config did not include a valid project id.");
1120
1200
  return;
1121
1201
  }
1122
- injectGoogleAdsWebsiteTag(decision.conversionId);
1202
+ if (!injectClarity(decision.projectId)) return;
1203
+ const profileId = this.state.profileId;
1204
+ if (profileId) this.identifyInClarity(profileId);
1123
1205
  } catch (error) {
1124
- if (abort.signal.aborted) return;
1125
- this.log(`Google Ads website tag config was not applied: ${errorMessage(error)}`);
1126
- } finally {
1127
- clearTimeout(timeout);
1206
+ this.log(`Microsoft Clarity was not applied: ${errorMessage(error)}`);
1207
+ }
1208
+ }
1209
+ identifyInClarity(profileId) {
1210
+ if (!profileId || this.clarityIdentifiedProfileId === profileId) return;
1211
+ if (!browserAvailable() || typeof window.clarity !== "function") return;
1212
+ try {
1213
+ window.clarity("identify", profileId);
1214
+ this.clarityIdentifiedProfileId = profileId;
1215
+ } catch (error) {
1216
+ this.log(`Microsoft Clarity identify was not sent: ${errorMessage(error)}`);
1128
1217
  }
1129
1218
  }
1130
1219
  trackGoogleAdsPageView() {