@adhub-so/adhub-nextjs-sdk 0.1.1 → 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/dist/index.cjs CHANGED
@@ -383,13 +383,129 @@ 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.1.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;
390
390
  var DEFAULT_SESSION_TIMEOUT_MS = 30 * 60 * 1e3;
391
391
  var BEHAVIOR_EVENTS_PATH = "/api/v1/saas/sdk/behavior-events";
392
392
  var PAGE_ENGAGEMENTS_PATH = "/api/v1/saas/sdk/page-engagements";
393
+ var SDK_CONFIG_PATH = "/api/v1/saas/sdk/config";
394
+ var GOOGLE_ADS_CONVERSION_ID = /^AW-\d{6,20}$/;
395
+ var CLARITY_PROJECT_ID = /^[0-9a-z]{4,32}$/;
396
+ function decideGoogleAdsTag(payload) {
397
+ if (!payload || typeof payload !== "object") return { action: "skip" };
398
+ const tag = payload.googleAdsWebsiteTag;
399
+ if (!tag || typeof tag !== "object") return { action: "skip" };
400
+ const record = tag;
401
+ if (record.enabled !== true) return { action: "skip" };
402
+ if (typeof record.conversionId !== "string" || record.conversionId.trim() === "") {
403
+ return { action: "skip" };
404
+ }
405
+ const conversionId = record.conversionId.trim();
406
+ if (!GOOGLE_ADS_CONVERSION_ID.test(conversionId)) return { action: "invalid" };
407
+ return { action: "inject", conversionId };
408
+ }
409
+ function adHubGtagMarker() {
410
+ const current = window.__ADHUB_GTAG__;
411
+ if (current && typeof current.js === "boolean" && Array.isArray(current.configuredIds)) {
412
+ return current;
413
+ }
414
+ const marker = { js: false, configuredIds: [] };
415
+ window.__ADHUB_GTAG__ = marker;
416
+ return marker;
417
+ }
418
+ function gtagScriptSrc(conversionId) {
419
+ return `https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(conversionId)}`;
420
+ }
421
+ function installGtagShim() {
422
+ window.dataLayer = window.dataLayer || [];
423
+ if (typeof window.gtag === "function") return;
424
+ window.gtag = function gtag() {
425
+ window.dataLayer?.push(arguments);
426
+ };
427
+ }
428
+ function ensureGtagScript(conversionId) {
429
+ const src = gtagScriptSrc(conversionId);
430
+ for (const script2 of document.getElementsByTagName("script")) {
431
+ if (script2.src === src) return;
432
+ }
433
+ const script = document.createElement("script");
434
+ script.async = true;
435
+ script.src = src;
436
+ script.setAttribute("data-adhub-gtag", conversionId);
437
+ (document.head ?? document.documentElement).appendChild(script);
438
+ }
439
+ function injectGoogleAdsWebsiteTag(conversionId) {
440
+ const marker = adHubGtagMarker();
441
+ if (marker.configuredIds.includes(conversionId)) return;
442
+ installGtagShim();
443
+ ensureGtagScript(conversionId);
444
+ const gtag = window.gtag;
445
+ if (typeof gtag !== "function") return;
446
+ if (!marker.js) {
447
+ marker.js = true;
448
+ gtag("js", /* @__PURE__ */ new Date());
449
+ }
450
+ marker.configuredIds.push(conversionId);
451
+ gtag("config", conversionId);
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
+ }
393
509
  var EMPTY_STATE = {
394
510
  initialized: false,
395
511
  anonymousId: null,
@@ -515,7 +631,12 @@ var AdHubBrowserClient = class {
515
631
  this.autoTrackOutgoingLinks = true;
516
632
  this.autoTrackDataAttributes = true;
517
633
  this.trackHashChanges = false;
634
+ this.waitForConsent = false;
635
+ this.sdkConfigAbort = null;
636
+ this.clarityIdentifiedProfileId = null;
518
637
  this.lastPageSignature = "";
638
+ this.lastTrackedPageUrl = "";
639
+ this.pendingPageReferrer = null;
519
640
  this.originalPushState = null;
520
641
  this.originalReplaceState = null;
521
642
  this.patchedPushState = null;
@@ -566,10 +687,17 @@ var AdHubBrowserClient = class {
566
687
  return;
567
688
  }
568
689
  if (!browserAvailable()) return;
569
- if (this.state.initialized && this.projectKey === projectKey && this.endpoint === endpoint) return;
690
+ if (this.state.initialized && this.projectKey === projectKey && this.endpoint === endpoint) {
691
+ if (this.waitForConsent && options.waitForConsent !== true) {
692
+ this.waitForConsent = false;
693
+ this.scheduleSdkConfigTags();
694
+ }
695
+ return;
696
+ }
570
697
  this.projectKey = projectKey;
571
698
  this.endpoint = endpoint;
572
699
  this.debug = options.debug ?? false;
700
+ this.waitForConsent = options.waitForConsent === true;
573
701
  this.autoFlush = options.autoFlush ?? true;
574
702
  this.autoPageview = options.autoPageview ?? true;
575
703
  this.autoPageEngagement = options.autoPageEngagement ?? true;
@@ -615,6 +743,7 @@ var AdHubBrowserClient = class {
615
743
  this.installBehaviorTracking();
616
744
  }
617
745
  this.scheduleFlush();
746
+ this.scheduleSdkConfigTags();
618
747
  } catch (error) {
619
748
  this.reportError(error);
620
749
  }
@@ -649,6 +778,7 @@ var AdHubBrowserClient = class {
649
778
  this.updateState({ profileId: profile.profileId, lastError: null });
650
779
  this.enqueue("/api/v1/saas/sdk/identify", "profile.identify", data);
651
780
  this.scheduleFlush();
781
+ this.identifyInClarity(profile.profileId);
652
782
  } catch (error) {
653
783
  this.reportError(error);
654
784
  }
@@ -669,7 +799,10 @@ var AdHubBrowserClient = class {
669
799
  normalized.title,
670
800
  normalized.eventId
671
801
  ].join("|");
672
- if (!input.eventId && signature === this.lastPageSignature) return;
802
+ if (!input.eventId && signature === this.lastPageSignature) {
803
+ this.pendingPageReferrer = null;
804
+ return;
805
+ }
673
806
  this.lastPageSignature = signature;
674
807
  this.finishPageVisit();
675
808
  const pageViewId = normalized.eventId ?? randomId("page");
@@ -677,6 +810,9 @@ var AdHubBrowserClient = class {
677
810
  if (this.autoPageEngagement) {
678
811
  this.startPageVisit(normalized, pageViewId, sessionId);
679
812
  }
813
+ this.lastTrackedPageUrl = normalized.pageUrl ?? safePageUrl(window.location.href);
814
+ this.pendingPageReferrer = null;
815
+ this.trackGoogleAdsPageView();
680
816
  } catch (error) {
681
817
  this.reportError(error);
682
818
  }
@@ -734,7 +870,10 @@ var AdHubBrowserClient = class {
734
870
  const sessionId = randomId("sess");
735
871
  this.store.writeSession(sessionId);
736
872
  this.updateState({ anonymousId, sessionId, profileId: null, lastError: null });
873
+ this.clarityIdentifiedProfileId = null;
737
874
  this.lastPageSignature = "";
875
+ this.lastTrackedPageUrl = "";
876
+ this.pendingPageReferrer = null;
738
877
  if (this.autoPageview) this.page();
739
878
  } catch (error) {
740
879
  this.reportError(error);
@@ -762,6 +901,8 @@ var AdHubBrowserClient = class {
762
901
  return () => this.listeners.delete(listener);
763
902
  }
764
903
  destroy() {
904
+ this.sdkConfigAbort?.abort();
905
+ this.sdkConfigAbort = null;
765
906
  this.finishPageVisit();
766
907
  if (browserAvailable() && this.lifecycleInstalled) {
767
908
  window.removeEventListener("online", this.onOnline);
@@ -827,11 +968,13 @@ var AdHubBrowserClient = class {
827
968
  return sessionId;
828
969
  }
829
970
  currentPageFields() {
971
+ const pageUrl = safePageUrl(window.location.href);
972
+ const referrer = this.pendingPageReferrer ?? (this.lastTrackedPageUrl && this.lastTrackedPageUrl !== pageUrl ? this.lastTrackedPageUrl : document.referrer || null);
830
973
  return {
831
- pageUrl: safePageUrl(window.location.href),
974
+ pageUrl,
832
975
  path: window.location.pathname || "/",
833
976
  title: document.title,
834
- referrer: document.referrer || null
977
+ referrer
835
978
  };
836
979
  }
837
980
  enqueueBehaviorEvent(normalized) {
@@ -942,13 +1085,10 @@ var AdHubBrowserClient = class {
942
1085
  try {
943
1086
  const response = await fetch(`${this.endpoint}${item.path}`, {
944
1087
  method: "POST",
945
- headers: {
1088
+ headers: this.sdkHeaders({
946
1089
  "Content-Type": "application/json",
947
- "Idempotency-Key": item.requestId,
948
- "X-AdHub-Project-Key": this.projectKey,
949
- "X-AdHub-SDK": SDK_NAME,
950
- "X-AdHub-SDK-Version": SDK_VERSION
951
- },
1090
+ "Idempotency-Key": item.requestId
1091
+ }),
952
1092
  body: JSON.stringify(item.body),
953
1093
  keepalive: true,
954
1094
  credentials: "omit",
@@ -1001,6 +1141,103 @@ var AdHubBrowserClient = class {
1001
1141
  this.store?.saveQueue(this.queue);
1002
1142
  this.updateState({ queuedCount: this.queue.length });
1003
1143
  }
1144
+ scheduleSdkConfigTags() {
1145
+ if (!browserAvailable() || this.waitForConsent) return;
1146
+ this.sdkConfigAbort?.abort();
1147
+ const abort = new AbortController();
1148
+ this.sdkConfigAbort = abort;
1149
+ queueMicrotask(() => {
1150
+ if (abort.signal.aborted) return;
1151
+ void this.fetchAndApplySdkConfig(abort);
1152
+ });
1153
+ }
1154
+ async fetchAndApplySdkConfig(abort) {
1155
+ const timeout = setTimeout(() => abort.abort(), REQUEST_TIMEOUT_MS);
1156
+ try {
1157
+ const response = await fetch(`${this.endpoint}${SDK_CONFIG_PATH}`, {
1158
+ method: "GET",
1159
+ headers: this.sdkHeaders(),
1160
+ credentials: "omit",
1161
+ signal: abort.signal
1162
+ });
1163
+ if (abort.signal.aborted) return;
1164
+ if (!response.ok) {
1165
+ this.log(`SDK config returned HTTP ${response.status}.`);
1166
+ return;
1167
+ }
1168
+ let payload;
1169
+ try {
1170
+ payload = await response.json();
1171
+ } catch (error) {
1172
+ this.log(`SDK config was not applied: ${errorMessage(error)}`);
1173
+ return;
1174
+ }
1175
+ if (abort.signal.aborted) return;
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);
1197
+ if (decision.action === "skip") return;
1198
+ if (decision.action === "invalid") {
1199
+ this.log("Microsoft Clarity config did not include a valid project id.");
1200
+ return;
1201
+ }
1202
+ if (!injectClarity(decision.projectId)) return;
1203
+ const profileId = this.state.profileId;
1204
+ if (profileId) this.identifyInClarity(profileId);
1205
+ } catch (error) {
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)}`);
1217
+ }
1218
+ }
1219
+ trackGoogleAdsPageView() {
1220
+ if (!this.autoPageview || !browserAvailable()) return;
1221
+ const marker = window.__ADHUB_GTAG__;
1222
+ if (!marker?.configuredIds.length || typeof window.gtag !== "function") return;
1223
+ try {
1224
+ window.gtag("event", "page_view", {
1225
+ page_location: window.location.href,
1226
+ page_path: `${window.location.pathname}${window.location.search}`,
1227
+ page_title: document.title
1228
+ });
1229
+ } catch (error) {
1230
+ this.log(`Google Ads page_view was not sent: ${errorMessage(error)}`);
1231
+ }
1232
+ }
1233
+ sdkHeaders(extra) {
1234
+ return {
1235
+ "X-AdHub-Project-Key": this.projectKey,
1236
+ "X-AdHub-SDK": SDK_NAME,
1237
+ "X-AdHub-SDK-Version": SDK_VERSION,
1238
+ ...extra
1239
+ };
1240
+ }
1004
1241
  installLifecycle() {
1005
1242
  if (this.lifecycleInstalled) return;
1006
1243
  window.addEventListener("online", this.onOnline);
@@ -1029,14 +1266,25 @@ var AdHubBrowserClient = class {
1029
1266
  };
1030
1267
  const originalPushState = this.originalPushState;
1031
1268
  const originalReplaceState = this.originalReplaceState;
1269
+ const client = this;
1032
1270
  this.patchedPushState = function pushState(...args) {
1271
+ const previousPageUrl = safePageUrl(window.location.href);
1033
1272
  const result = originalPushState.apply(this, args);
1034
- dispatchLocationChange();
1273
+ const nextPageUrl = safePageUrl(window.location.href);
1274
+ if (previousPageUrl !== nextPageUrl) {
1275
+ client.pendingPageReferrer ?? (client.pendingPageReferrer = client.lastTrackedPageUrl || previousPageUrl);
1276
+ dispatchLocationChange();
1277
+ }
1035
1278
  return result;
1036
1279
  };
1037
1280
  this.patchedReplaceState = function replaceState(...args) {
1281
+ const previousPageUrl = safePageUrl(window.location.href);
1038
1282
  const result = originalReplaceState.apply(this, args);
1039
- dispatchLocationChange();
1283
+ const nextPageUrl = safePageUrl(window.location.href);
1284
+ if (previousPageUrl !== nextPageUrl) {
1285
+ client.pendingPageReferrer ?? (client.pendingPageReferrer = client.lastTrackedPageUrl || previousPageUrl);
1286
+ dispatchLocationChange();
1287
+ }
1040
1288
  return result;
1041
1289
  };
1042
1290
  history.pushState = this.patchedPushState;