@adhub-so/adhub-nextjs-sdk 0.2.0 → 0.4.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.js CHANGED
@@ -13,6 +13,7 @@ function hashKey(input) {
13
13
  }
14
14
  return (hash >>> 0).toString(36);
15
15
  }
16
+ var ANONYMOUS_ID_COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 395;
16
17
  function validAnonymousId(value) {
17
18
  return value !== null && value.length >= 8 && value.length <= 255 && !/\s/.test(value);
18
19
  }
@@ -34,6 +35,27 @@ function readAdHubAnonymousIdFromCookie(cookieHeader, projectKey) {
34
35
  }
35
36
  return null;
36
37
  }
38
+ function cookieDomainForHost(domain, hostname) {
39
+ const candidate = domain?.trim().toLowerCase().replace(/^\./, "").replace(/\.$/, "");
40
+ const host = hostname?.trim().toLowerCase().replace(/\.$/, "");
41
+ if (!candidate || !host) return null;
42
+ if (!/^[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(candidate)) return null;
43
+ if (/^[\d.]+$/.test(candidate)) return null;
44
+ return host === candidate || host.endsWith(`.${candidate}`) ? candidate : null;
45
+ }
46
+ function serializeAdHubAnonymousIdCookie(input) {
47
+ const parts = [
48
+ `${getAdHubAnonymousIdCookieName(input.projectKey)}=${encodeURIComponent(input.anonymousId)}`
49
+ ];
50
+ if (input.domain) parts.push(`Domain=${input.domain}`);
51
+ parts.push(
52
+ "Path=/",
53
+ `Max-Age=${input.maxAgeSeconds ?? ANONYMOUS_ID_COOKIE_MAX_AGE_SECONDS}`,
54
+ "SameSite=Lax"
55
+ );
56
+ if (input.secure) parts.push("Secure");
57
+ return parts.join("; ");
58
+ }
37
59
 
38
60
  // src/utils.ts
39
61
  var MAX_PARAM_LENGTH = 2048;
@@ -243,7 +265,6 @@ function sanitizeProfile(profile) {
243
265
  }
244
266
 
245
267
  // src/storage.ts
246
- var COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 395;
247
268
  var MAX_QUEUE_SIZE = 100;
248
269
  function isPendingRequest(value) {
249
270
  if (!value || typeof value !== "object") return false;
@@ -252,6 +273,8 @@ function isPendingRequest(value) {
252
273
  }
253
274
  var BrowserStore = class {
254
275
  constructor(projectKey) {
276
+ this.cookieDomain = null;
277
+ this.projectKey = projectKey;
255
278
  this.suffix = getAdHubAnonymousIdCookieName(projectKey).slice("adhub_project_anonymous_id_".length);
256
279
  }
257
280
  get anonymousKey() {
@@ -263,6 +286,9 @@ var BrowserStore = class {
263
286
  get profileKey() {
264
287
  return `adhub_project_profile_id_${this.suffix}`;
265
288
  }
289
+ get cookieDomainKey() {
290
+ return `adhub_project_cookie_domain_${this.suffix}`;
291
+ }
266
292
  get sessionKey() {
267
293
  return `adhub_project_session_${this.suffix}`;
268
294
  }
@@ -272,11 +298,48 @@ var BrowserStore = class {
272
298
  const fromLocal = this.readLocal(this.anonymousKey);
273
299
  return this.validAnonymousId(fromLocal) ? fromLocal : null;
274
300
  }
301
+ /**
302
+ * Shares the anonymous-id cookie with every subdomain of `domain`.
303
+ * Returns false, and keeps the host-only cookie, when this page is not on that domain.
304
+ */
305
+ setCookieDomain(domain) {
306
+ let hostname = null;
307
+ try {
308
+ hostname = window.location.hostname;
309
+ } catch {
310
+ hostname = null;
311
+ }
312
+ this.cookieDomain = cookieDomainForHost(domain, hostname);
313
+ return this.cookieDomain !== null;
314
+ }
275
315
  writeAnonymousId(anonymousId) {
276
316
  this.writeLocal(this.anonymousKey, anonymousId);
277
317
  try {
278
- const secure = window.location.protocol === "https:" ? "; Secure" : "";
279
- document.cookie = `${this.anonymousKey}=${encodeURIComponent(anonymousId)}; Path=/; Max-Age=${COOKIE_MAX_AGE_SECONDS}; SameSite=Lax${secure}`;
318
+ const stored = this.readCookieValues(this.anonymousKey);
319
+ const unchanged = stored.length > 0 && stored.every((value) => value === anonymousId);
320
+ const domainApplied = (this.readLocal(this.cookieDomainKey) || null) === this.cookieDomain;
321
+ if (unchanged && domainApplied) return;
322
+ const secure = window.location.protocol === "https:";
323
+ const write = (domain, maxAgeSeconds = ANONYMOUS_ID_COOKIE_MAX_AGE_SECONDS) => {
324
+ document.cookie = serializeAdHubAnonymousIdCookie({
325
+ projectKey: this.projectKey,
326
+ anonymousId,
327
+ domain,
328
+ secure,
329
+ maxAgeSeconds
330
+ });
331
+ };
332
+ if (this.cookieDomain) {
333
+ write(null, 0);
334
+ write(this.cookieDomain);
335
+ if (this.readCookieValues(this.anonymousKey).includes(anonymousId)) {
336
+ this.writeLocal(this.cookieDomainKey, this.cookieDomain);
337
+ return;
338
+ }
339
+ this.cookieDomain = null;
340
+ }
341
+ write(null);
342
+ this.writeLocal(this.cookieDomainKey, "");
280
343
  } catch {
281
344
  }
282
345
  }
@@ -335,6 +398,19 @@ var BrowserStore = class {
335
398
  }
336
399
  return null;
337
400
  }
401
+ readCookieValues(name) {
402
+ const values = [];
403
+ for (const part of document.cookie.split(";")) {
404
+ const [rawName, ...rawValue] = part.trim().split("=");
405
+ if (rawName !== name) continue;
406
+ try {
407
+ values.push(decodeURIComponent(rawValue.join("=")));
408
+ } catch {
409
+ values.push("");
410
+ }
411
+ }
412
+ return values;
413
+ }
338
414
  readLocal(key) {
339
415
  try {
340
416
  return localStorage.getItem(key);
@@ -356,7 +432,7 @@ var BrowserStore = class {
356
432
  // src/client.ts
357
433
  var DEFAULT_ENDPOINT = "https://api.adhub.so";
358
434
  var SDK_NAME = "nextjs";
359
- var SDK_VERSION = "0.2.0";
435
+ var SDK_VERSION = "0.4.0";
360
436
  var REQUEST_TIMEOUT_MS = 5e3;
361
437
  var RETRY_INTERVAL_MS = 15e3;
362
438
  var PAGE_ENGAGEMENT_INTERVAL_MS = 5e3;
@@ -365,6 +441,7 @@ var BEHAVIOR_EVENTS_PATH = "/api/v1/saas/sdk/behavior-events";
365
441
  var PAGE_ENGAGEMENTS_PATH = "/api/v1/saas/sdk/page-engagements";
366
442
  var SDK_CONFIG_PATH = "/api/v1/saas/sdk/config";
367
443
  var GOOGLE_ADS_CONVERSION_ID = /^AW-\d{6,20}$/;
444
+ var CLARITY_PROJECT_ID = /^[0-9a-z]{4,32}$/;
368
445
  function decideGoogleAdsTag(payload) {
369
446
  if (!payload || typeof payload !== "object") return { action: "skip" };
370
447
  const tag = payload.googleAdsWebsiteTag;
@@ -422,6 +499,62 @@ function injectGoogleAdsWebsiteTag(conversionId) {
422
499
  marker.configuredIds.push(conversionId);
423
500
  gtag("config", conversionId);
424
501
  }
502
+ function decideClarity(payload) {
503
+ if (!payload || typeof payload !== "object") return { action: "skip" };
504
+ const clarity = payload.clarity;
505
+ if (!clarity || typeof clarity !== "object") return { action: "skip" };
506
+ const record = clarity;
507
+ if (record.enabled !== true) return { action: "skip" };
508
+ if (typeof record.projectId !== "string" || record.projectId.trim() === "") {
509
+ return { action: "skip" };
510
+ }
511
+ const projectId = record.projectId.trim();
512
+ if (!CLARITY_PROJECT_ID.test(projectId)) return { action: "invalid" };
513
+ return { action: "inject", projectId };
514
+ }
515
+ function clarityScriptSrc(projectId) {
516
+ return `https://www.clarity.ms/tag/${projectId}`;
517
+ }
518
+ function installClarityQueue() {
519
+ window.clarity = window.clarity || function clarity() {
520
+ const stub = window.clarity;
521
+ if (!stub) return;
522
+ (stub.q = stub.q || []).push(arguments);
523
+ };
524
+ }
525
+ function clarityProjectOnPage() {
526
+ const marker = window.__ADHUB_CLARITY__;
527
+ if (marker && typeof marker.projectId === "string" && CLARITY_PROJECT_ID.test(marker.projectId)) {
528
+ return marker.projectId;
529
+ }
530
+ const match = /^https:\/\/www\.clarity\.ms\/tag\/([0-9a-z]{4,32})$/;
531
+ for (const script of document.getElementsByTagName("script")) {
532
+ const projectId = match.exec(script.src)?.[1];
533
+ if (projectId) return projectId;
534
+ }
535
+ return null;
536
+ }
537
+ function injectClarity(projectId) {
538
+ const installed = clarityProjectOnPage();
539
+ if (installed) {
540
+ if (!window.__ADHUB_CLARITY__) window.__ADHUB_CLARITY__ = { projectId: installed };
541
+ if (installed === projectId) installClarityQueue();
542
+ return installed === projectId;
543
+ }
544
+ installClarityQueue();
545
+ const script = document.createElement("script");
546
+ script.async = true;
547
+ script.src = clarityScriptSrc(projectId);
548
+ script.setAttribute("data-adhub-clarity", projectId);
549
+ const firstScript = document.getElementsByTagName("script")[0];
550
+ if (firstScript?.parentNode) {
551
+ firstScript.parentNode.insertBefore(script, firstScript);
552
+ } else {
553
+ (document.head ?? document.documentElement).appendChild(script);
554
+ }
555
+ window.__ADHUB_CLARITY__ = { projectId };
556
+ return true;
557
+ }
425
558
  var EMPTY_STATE = {
426
559
  initialized: false,
427
560
  anonymousId: null,
@@ -530,6 +663,9 @@ var AdHubBrowserClient = class {
530
663
  this.store = null;
531
664
  this.queue = [];
532
665
  this.endpoint = DEFAULT_ENDPOINT;
666
+ this.cookieDomainOption = null;
667
+ /** The endpoint confirmed that it accepts and sets first-party cookies. */
668
+ this.endpointSharesCookies = false;
533
669
  this.projectKey = "";
534
670
  this.debug = false;
535
671
  this.flushPromise = null;
@@ -548,7 +684,8 @@ var AdHubBrowserClient = class {
548
684
  this.autoTrackDataAttributes = true;
549
685
  this.trackHashChanges = false;
550
686
  this.waitForConsent = false;
551
- this.gtagAbort = null;
687
+ this.sdkConfigAbort = null;
688
+ this.clarityIdentifiedProfileId = null;
552
689
  this.lastPageSignature = "";
553
690
  this.lastTrackedPageUrl = "";
554
691
  this.pendingPageReferrer = null;
@@ -605,12 +742,14 @@ var AdHubBrowserClient = class {
605
742
  if (this.state.initialized && this.projectKey === projectKey && this.endpoint === endpoint) {
606
743
  if (this.waitForConsent && options.waitForConsent !== true) {
607
744
  this.waitForConsent = false;
608
- this.scheduleGoogleAdsWebsiteTag();
745
+ this.scheduleSdkConfigTags();
609
746
  }
610
747
  return;
611
748
  }
612
749
  this.projectKey = projectKey;
613
750
  this.endpoint = endpoint;
751
+ this.cookieDomainOption = options.cookieDomain?.trim() || null;
752
+ this.endpointSharesCookies = false;
614
753
  this.debug = options.debug ?? false;
615
754
  this.waitForConsent = options.waitForConsent === true;
616
755
  this.autoFlush = options.autoFlush ?? true;
@@ -620,6 +759,9 @@ var AdHubBrowserClient = class {
620
759
  this.autoTrackDataAttributes = options.autoTrackDataAttributes ?? true;
621
760
  this.trackHashChanges = options.trackHashChanges ?? false;
622
761
  this.store = new BrowserStore(projectKey);
762
+ if (this.cookieDomainOption && !this.store.setCookieDomain(this.cookieDomainOption)) {
763
+ this.log("cookieDomain was ignored because this page is not on that domain.");
764
+ }
623
765
  this.queue = this.store.loadQueue();
624
766
  this.sessionTimeoutMs = Number.isFinite(options.sessionTimeoutMinutes) ? Math.max(1, Math.min(24 * 60, options.sessionTimeoutMinutes ?? 30)) * 60 * 1e3 : DEFAULT_SESSION_TIMEOUT_MS;
625
767
  const anonymousId = this.store.readAnonymousId() ?? randomId("anon");
@@ -658,7 +800,7 @@ var AdHubBrowserClient = class {
658
800
  this.installBehaviorTracking();
659
801
  }
660
802
  this.scheduleFlush();
661
- this.scheduleGoogleAdsWebsiteTag();
803
+ this.scheduleSdkConfigTags();
662
804
  } catch (error) {
663
805
  this.reportError(error);
664
806
  }
@@ -693,6 +835,7 @@ var AdHubBrowserClient = class {
693
835
  this.updateState({ profileId: profile.profileId, lastError: null });
694
836
  this.enqueue("/api/v1/saas/sdk/identify", "profile.identify", data);
695
837
  this.scheduleFlush();
838
+ this.identifyInClarity(profile.profileId);
696
839
  } catch (error) {
697
840
  this.reportError(error);
698
841
  }
@@ -784,6 +927,7 @@ var AdHubBrowserClient = class {
784
927
  const sessionId = randomId("sess");
785
928
  this.store.writeSession(sessionId);
786
929
  this.updateState({ anonymousId, sessionId, profileId: null, lastError: null });
930
+ this.clarityIdentifiedProfileId = null;
787
931
  this.lastPageSignature = "";
788
932
  this.lastTrackedPageUrl = "";
789
933
  this.pendingPageReferrer = null;
@@ -814,8 +958,8 @@ var AdHubBrowserClient = class {
814
958
  return () => this.listeners.delete(listener);
815
959
  }
816
960
  destroy() {
817
- this.gtagAbort?.abort();
818
- this.gtagAbort = null;
961
+ this.sdkConfigAbort?.abort();
962
+ this.sdkConfigAbort = null;
819
963
  this.finishPageVisit();
820
964
  if (browserAvailable() && this.lifecycleInstalled) {
821
965
  window.removeEventListener("online", this.onOnline);
@@ -1004,7 +1148,7 @@ var AdHubBrowserClient = class {
1004
1148
  }),
1005
1149
  body: JSON.stringify(item.body),
1006
1150
  keepalive: true,
1007
- credentials: "omit",
1151
+ credentials: this.credentialsMode(),
1008
1152
  signal: controller.signal
1009
1153
  });
1010
1154
  if (response.ok) {
@@ -1054,50 +1198,101 @@ var AdHubBrowserClient = class {
1054
1198
  this.store?.saveQueue(this.queue);
1055
1199
  this.updateState({ queuedCount: this.queue.length });
1056
1200
  }
1057
- scheduleGoogleAdsWebsiteTag() {
1201
+ scheduleSdkConfigTags() {
1058
1202
  if (!browserAvailable() || this.waitForConsent) return;
1059
- this.gtagAbort?.abort();
1203
+ this.sdkConfigAbort?.abort();
1060
1204
  const abort = new AbortController();
1061
- this.gtagAbort = abort;
1205
+ this.sdkConfigAbort = abort;
1062
1206
  queueMicrotask(() => {
1063
1207
  if (abort.signal.aborted) return;
1064
- void this.fetchAndInjectGoogleAdsWebsiteTag(abort);
1208
+ void this.fetchAndApplySdkConfig(abort);
1065
1209
  });
1066
1210
  }
1067
- async fetchAndInjectGoogleAdsWebsiteTag(abort) {
1211
+ async fetchAndApplySdkConfig(abort) {
1068
1212
  const timeout = setTimeout(() => abort.abort(), REQUEST_TIMEOUT_MS);
1069
1213
  try {
1070
1214
  const response = await fetch(`${this.endpoint}${SDK_CONFIG_PATH}`, {
1071
1215
  method: "GET",
1072
1216
  headers: this.sdkHeaders(),
1073
- credentials: "omit",
1217
+ credentials: this.endpointIsSameOrigin() ? "same-origin" : "omit",
1074
1218
  signal: abort.signal
1075
1219
  });
1076
1220
  if (abort.signal.aborted) return;
1077
1221
  if (!response.ok) {
1078
- this.log(`Google Ads website tag config returned HTTP ${response.status}.`);
1222
+ this.log(`SDK config returned HTTP ${response.status}.`);
1079
1223
  return;
1080
1224
  }
1081
1225
  let payload;
1082
1226
  try {
1083
1227
  payload = await response.json();
1084
1228
  } catch (error) {
1085
- this.log(`Google Ads website tag config was not applied: ${errorMessage(error)}`);
1229
+ this.log(`SDK config was not applied: ${errorMessage(error)}`);
1086
1230
  return;
1087
1231
  }
1088
1232
  if (abort.signal.aborted) return;
1089
- const decision = decideGoogleAdsTag(payload);
1233
+ this.applyIdentityCookieDomain(payload);
1234
+ this.applyGoogleAdsWebsiteTag(payload);
1235
+ this.applyClarity(payload);
1236
+ } catch (error) {
1237
+ if (abort.signal.aborted) return;
1238
+ this.log(`SDK config was not applied: ${errorMessage(error)}`);
1239
+ } finally {
1240
+ clearTimeout(timeout);
1241
+ }
1242
+ }
1243
+ endpointIsSameOrigin() {
1244
+ return this.endpoint === "" || this.endpoint.startsWith("/");
1245
+ }
1246
+ /**
1247
+ * Cookies travel to a same-origin proxy always, and to another host only
1248
+ * after its SDK config confirmed a shared cookie domain. The default API
1249
+ * answers with a wildcard CORS origin, which browsers reject for
1250
+ * credentialed requests, so it must stay "omit".
1251
+ */
1252
+ credentialsMode() {
1253
+ if (this.endpointIsSameOrigin()) return "same-origin";
1254
+ return this.endpointSharesCookies ? "include" : "omit";
1255
+ }
1256
+ applyIdentityCookieDomain(payload) {
1257
+ if (!this.store || !payload || typeof payload !== "object") return;
1258
+ const domain = payload.identityCookieDomain;
1259
+ if (typeof domain !== "string" || !domain.trim()) return;
1260
+ if (!this.store.setCookieDomain(this.cookieDomainOption ?? domain)) return;
1261
+ this.endpointSharesCookies = true;
1262
+ if (this.state.anonymousId) this.store.writeAnonymousId(this.state.anonymousId);
1263
+ }
1264
+ applyGoogleAdsWebsiteTag(payload) {
1265
+ const decision = decideGoogleAdsTag(payload);
1266
+ if (decision.action === "skip") return;
1267
+ if (decision.action === "invalid") {
1268
+ this.log("Google Ads website tag config did not include a valid AW- conversion id.");
1269
+ return;
1270
+ }
1271
+ injectGoogleAdsWebsiteTag(decision.conversionId);
1272
+ }
1273
+ applyClarity(payload) {
1274
+ try {
1275
+ const decision = decideClarity(payload);
1090
1276
  if (decision.action === "skip") return;
1091
1277
  if (decision.action === "invalid") {
1092
- this.log("Google Ads website tag config did not include a valid AW- conversion id.");
1278
+ this.log("Microsoft Clarity config did not include a valid project id.");
1093
1279
  return;
1094
1280
  }
1095
- injectGoogleAdsWebsiteTag(decision.conversionId);
1281
+ if (!injectClarity(decision.projectId)) return;
1282
+ const profileId = this.state.profileId;
1283
+ if (profileId) this.identifyInClarity(profileId);
1096
1284
  } catch (error) {
1097
- if (abort.signal.aborted) return;
1098
- this.log(`Google Ads website tag config was not applied: ${errorMessage(error)}`);
1099
- } finally {
1100
- clearTimeout(timeout);
1285
+ this.log(`Microsoft Clarity was not applied: ${errorMessage(error)}`);
1286
+ }
1287
+ }
1288
+ identifyInClarity(profileId) {
1289
+ if (!profileId || this.clarityIdentifiedProfileId === profileId) return;
1290
+ if (!browserAvailable() || typeof window.clarity !== "function") return;
1291
+ try {
1292
+ window.clarity("identify", profileId);
1293
+ this.clarityIdentifiedProfileId = profileId;
1294
+ } catch (error) {
1295
+ this.log(`Microsoft Clarity identify was not sent: ${errorMessage(error)}`);
1101
1296
  }
1102
1297
  }
1103
1298
  trackGoogleAdsPageView() {