@adhub-so/adhub-nextjs-sdk 0.1.1 → 0.2.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
@@ -1,30 +1,28 @@
1
1
  # AdHub Next.js SDK
2
2
 
3
- `@adhub-so/adhub-nextjs-sdk` is AdHub's first-party SDK for Next.js. It captures Google Ads landing touchpoints, maintains anonymous and authenticated identity, records page and product behavior, sends browser business events, and proxies requests through a Next.js Route Handler so AdHub receives the original browser IP, user agent, and edge geo headers.
3
+ `@adhub-so/adhub-nextjs-sdk` captures Google Ads landing touchpoints, connects anonymous visits to authenticated SaaS users, and records page, product, and business events in Next.js applications.
4
4
 
5
- This package targets Next.js only. It does not publish a framework-neutral browser entry, SPA bootstrap API, or global IIFE bundle.
5
+ For most applications, integration consists of installing the package and rendering `AdHubComponent` once in the root layout. A Route Handler, custom `endpoint`, and manual `flush()` calls are not required.
6
6
 
7
- ## Install
7
+ ## Minimal setup
8
+
9
+ ### 1. Install
8
10
 
9
11
  ```bash
10
12
  npm install @adhub-so/adhub-nextjs-sdk
11
13
  ```
12
14
 
13
- For a local sibling checkout:
15
+ Add the public Project key to the application environment:
14
16
 
15
- ```json
16
- {
17
- "dependencies": {
18
- "@adhub-so/adhub-nextjs-sdk": "file:../adhub-nextjs-sdk"
19
- }
20
- }
17
+ ```dotenv
18
+ NEXT_PUBLIC_ADHUB_PROJECT_KEY=<project-key>
21
19
  ```
22
20
 
23
- ## App Router setup
21
+ The Project key is a public browser identifier. Never put an ingestion key or another server secret in a `NEXT_PUBLIC_*` variable.
24
22
 
25
- ### 1. Add the component
23
+ ### 2. Add the component
26
24
 
27
- Render `AdHubComponent` once in the root layout. A relative `endpoint` sends browser requests through your own Next.js origin, which improves delivery and preserves the real browser context through the Route Handler in the next step.
25
+ Render `AdHubComponent` once in the root layout:
28
26
 
29
27
  ```tsx
30
28
  // app/layout.tsx
@@ -36,7 +34,6 @@ export default function RootLayout({ children }: { children: React.ReactNode })
36
34
  <body>
37
35
  <AdHubComponent
38
36
  projectKey={process.env.NEXT_PUBLIC_ADHUB_PROJECT_KEY!}
39
- endpoint="/api/adhub"
40
37
  />
41
38
  {children}
42
39
  </body>
@@ -45,85 +42,144 @@ export default function RootLayout({ children }: { children: React.ReactNode })
45
42
  }
46
43
  ```
47
44
 
48
- The Project key is a public browser identifier. Never pass an ingestion key or another server secret to `AdHubComponent` or a `NEXT_PUBLIC_*` environment variable.
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
+
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).
48
+
49
+ Do not add a Route Handler or call `flush()` after every event for this setup.
50
+
51
+ ### 3. Connect authenticated users
49
52
 
50
- If authenticated profile data is already available to the layout, it can be supplied as a serializable prop:
53
+ When the authenticated user is available, pass the application's existing stable user ID. No AdHub-specific identity table is required.
51
54
 
52
55
  ```tsx
53
56
  <AdHubComponent
54
57
  projectKey={process.env.NEXT_PUBLIC_ADHUB_PROJECT_KEY!}
55
- endpoint="/api/adhub"
56
58
  profile={{ profileId: user.id, email: user.email }}
57
59
  />
58
60
  ```
59
61
 
60
- `profileId` can be passed directly when no other profile fields are needed. Changing directly from one non-null profile to another rotates the browser identity boundary before identifying the next user. Passing `null` resets the authenticated identity while retaining a new anonymous browser identity.
62
+ Use `profile={undefined}` while authentication is loading, the profile object after login, and `profile={null}` only after logout is confirmed. Changing from one non-null profile to another automatically creates a new browser identity boundary before identifying the next user.
61
63
 
62
- ### 2. Add the Route Handler
64
+ ## Common client events
63
65
 
64
- ```ts
65
- // app/api/adhub/[...path]/route.ts
66
- import { createRouteHandler } from "@adhub-so/adhub-nextjs-sdk/server";
66
+ Use `useAdHub()` in Client Components. Events are sent automatically; normal application code does not need `flush()`.
67
67
 
68
- export const runtime = "nodejs";
68
+ ```tsx
69
+ "use client";
69
70
 
70
- const handler = createRouteHandler({
71
- apiUrl: process.env.ADHUB_API_URL ?? "https://api.adhub.so",
72
- });
71
+ import { useAdHub } from "@adhub-so/adhub-nextjs-sdk";
72
+
73
+ export function PricingButton() {
74
+ const adhub = useAdHub();
73
75
 
74
- export const { POST, OPTIONS } = handler;
76
+ return (
77
+ <button
78
+ onClick={() => adhub.behavior({
79
+ eventName: "pricing_cta_clicked",
80
+ properties: { plan: "growth" },
81
+ })}
82
+ >
83
+ Choose Growth
84
+ </button>
85
+ );
86
+ }
75
87
  ```
76
88
 
77
- The handler only forwards the supported SDK ingestion paths. It carries the original `Origin`, `User-Agent`, client IP, country, region, city, project key, idempotency key, SDK name, and SDK version to AdHub. It does not proxy general SaaS APIs.
89
+ `behavior()` records non-sensitive product analytics and works for anonymous visitors. `track()` records a configured AdHub business event and requires an identified profile:
78
90
 
79
- ### 3. Track from Client Components
91
+ ```ts
92
+ adhub.track({
93
+ eventType: "signup.completed",
94
+ eventId: `signup:${createdUser.id}`,
95
+ occurredAt: createdUser.createdAt,
96
+ });
97
+ ```
80
98
 
81
- `useAdHub()` is the client API for Next.js Client Components. It exposes a reactive `state` plus identity, page, behavior, event, reset, and flush actions.
99
+ Call this from the account-creation success path. Ordinary login only identifies
100
+ the profile; `identify()` never creates a signup event.
82
101
 
83
- ```tsx
84
- "use client";
102
+ Browser payloads can be modified by users. Trusted payment, refund, subscription, and order facts should be sent from the server.
85
103
 
86
- import { useAdHub } from "@adhub-so/adhub-nextjs-sdk";
104
+ ## Advanced configuration
87
105
 
88
- export function SignupButton({ userId }: { userId: string }) {
89
- const adhub = useAdHub();
106
+ The minimal setup above does not require any of the following features. Use them only for a specific application requirement.
90
107
 
91
- async function completeSignup() {
92
- const currentProfileId = adhub.getState().profileId;
93
- if (currentProfileId && currentProfileId !== userId) adhub.reset();
94
- if (adhub.getState().profileId !== userId) {
95
- adhub.identify({ profileId: userId });
96
- }
108
+ - [Google Ads website tag](#google-ads-website-tag) for consent, SPA page views, and the same-origin config proxy.
109
+ - [First-party Route Handler](#first-party-route-handler) for a same-origin collection path, customer-edge geo headers, or a custom API target.
110
+ - [Capture before hydration](#capture-before-hydration) when application code removes attribution parameters before React hydrates.
111
+ - [Manual flush and queue control](#manual-flush-and-queue-control) for tests, diagnostics, or `autoFlush: false`.
112
+ - [Trusted server events](#trusted-server-events) for payments and other authoritative business facts.
113
+ - [OAuth signup attribution](#oauth-signup-attribution) when a callback must distinguish signup from normal login.
114
+ - [Attribution testing](#attribution-testing) for zero-write dashboard previews.
97
115
 
98
- adhub.track({ eventType: "signup.completed" });
99
- await adhub.flush();
100
- }
116
+ ### Google Ads website tag
101
117
 
102
- return <button onClick={() => void completeSignup()}>Create account</button>;
103
- }
118
+ After `init`, the SDK requests `GET /api/v1/saas/sdk/config`. When `googleAdsWebsiteTag.enabled` is true and `conversionId` is an `AW-…` id, it installs Google's website tag:
119
+
120
+ - An existing `window.gtag` and `dataLayer` are reused. Otherwise the SDK defines the standard `dataLayer` push helper.
121
+ - `https://www.googletagmanager.com/gtag/js?id=AW-…` is added once, marked with `data-adhub-gtag`. A script with the same `src` is left in place.
122
+ - `gtag('js', new Date())` runs once, and `gtag('config', conversionId)` runs once per id.
123
+ - The script stays loaded across client-side route changes. With `autoPageview` left on, those navigations also send a Google `page_view`.
124
+ - Injection is idempotent. `window.__ADHUB_GTAG__` records the installed ids, so a later `init` on the same page does not insert a second script or call `gtag('config')` again for an id that is already installed.
125
+
126
+ 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
+ `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
+
130
+ ```tsx
131
+ <AdHubComponent
132
+ projectKey={process.env.NEXT_PUBLIC_ADHUB_PROJECT_KEY!}
133
+ waitForConsent
134
+ />
104
135
  ```
105
136
 
106
- Use `behavior()` for non-sensitive product analytics and `track()` for configured AdHub business events:
137
+ 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
+ ### First-party Route Handler
140
+
141
+ 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.
142
+
143
+ The optional Route Handler can provide:
144
+
145
+ - A first-party request path on the application's own origin.
146
+ - Reduced blocking by some third-party-domain filters, without promising to bypass every blocker.
147
+ - A browser-to-Next.js request that does not rely on cross-origin CORS.
148
+ - Vercel, Cloudflare, or CloudFront geo headers available at the customer's edge.
149
+ - A centralized self-hosted, regional, or test AdHub API target through `apiUrl`.
150
+ - A restricted proxy that accepts only supported SDK ingestion paths.
151
+
152
+ The tradeoff is an extra network hop, another Next.js server request, and an additional failure point. It requires an App Router server runtime and does not work with a purely static export. It also does not make browser events trusted and must not use an ingestion key.
107
153
 
108
154
  ```ts
109
- adhub.behavior({
110
- eventName: "pricing_cta_clicked",
111
- properties: { plan: "growth" },
112
- });
155
+ // app/api/adhub/[...path]/route.ts
156
+ import { createRouteHandler } from "@adhub-so/adhub-nextjs-sdk/server";
113
157
 
114
- adhub.track({
115
- eventType: "purchase",
116
- eventId: `order:${order.id}`,
117
- value: order.total,
118
- currency: order.currency,
158
+ export const runtime = "nodejs";
159
+
160
+ const handler = createRouteHandler({
161
+ apiUrl: process.env.ADHUB_API_URL ?? "https://api.adhub.so",
119
162
  });
163
+
164
+ export const { GET, POST, OPTIONS } = handler;
165
+ ```
166
+
167
+ Then opt the single browser initialization into that path:
168
+
169
+ ```tsx
170
+ <AdHubComponent
171
+ projectKey={process.env.NEXT_PUBLIC_ADHUB_PROJECT_KEY!}
172
+ endpoint="/api/adhub"
173
+ />
120
174
  ```
121
175
 
122
- Browser `track()` requires an identified profile. Trusted payment, refund, and subscription facts should normally be sent from the server instead.
176
+ The handler preserves the original Origin, User-Agent, client IP, supported edge geo fields, Project key, idempotency key, SDK name, and SDK version. The real site Origin must still be allowed in the AdHub Project.
123
177
 
124
- ## Capture before hydration
178
+ Do not configure only one half of proxy mode. Setting `endpoint="/api/adhub"` without deploying the matching catch-all Route Handler causes 404 responses and leaves requests in the retry queue.
125
179
 
126
- Next.js 15.3 and newer can initialize AdHub synchronously from `instrumentation-client.ts`. Use this advanced setup when application code may remove attribution query parameters before React hydrates. In that case, use `initAdHub()` here instead of relying on `AdHubComponent` to initialize.
180
+ ### Capture before hydration
181
+
182
+ Next.js 15.3 and newer can initialize AdHub synchronously from `instrumentation-client.ts`. Use this only when application code may remove attribution query parameters before React hydrates.
127
183
 
128
184
  ```ts
129
185
  // src/instrumentation-client.ts
@@ -131,15 +187,30 @@ import { initAdHub } from "@adhub-so/adhub-nextjs-sdk";
131
187
 
132
188
  initAdHub({
133
189
  projectKey: process.env.NEXT_PUBLIC_ADHUB_PROJECT_KEY!,
134
- endpoint: "/api/adhub",
135
190
  });
136
191
  ```
137
192
 
138
- Only synchronous top-level work in `instrumentation-client.ts` is guaranteed to complete before hydration. `initAdHub()` captures and persists the landing touchpoint synchronously; network delivery remains queued and asynchronous.
193
+ Top-level initialization captures and persists the landing touchpoint synchronously. Network delivery remains automatic and asynchronous. Add `endpoint: "/api/adhub"` only when the optional Route Handler is deployed.
194
+
195
+ ### Manual flush and queue control
139
196
 
140
- ## Server events
197
+ The SDK uses a persistent FIFO queue to preserve touchpoint, identity, and event order and to retry transient failures. With the default `autoFlush: true`, `init`, `identify`, `page`, `behavior`, and `track` automatically schedule delivery. It also retries when the browser comes online, the page is hidden, the page is left, and while pending events remain.
141
198
 
142
- Import trusted server functionality only from `@adhub-so/adhub-nextjs-sdk/server` so ingestion credentials cannot enter the client module graph.
199
+ `flush()` only starts an immediate attempt to drain the current queue and lets the caller wait for that attempt:
200
+
201
+ ```ts
202
+ const result = await adhub.flush();
203
+
204
+ console.log(result.sent);
205
+ console.log(result.failed);
206
+ console.log(result.remaining);
207
+ ```
208
+
209
+ Use it explicitly only for automated tests, diagnostics, `autoFlush: false`, or a flow that needs to wait for the current delivery attempt before a full-page navigation. It is not required after `track()` or `behavior()`, and it is not a final-delivery guarantee.
210
+
211
+ ### Trusted server events
212
+
213
+ Import trusted server functionality only from the server entry so ingestion credentials cannot enter the client module graph:
143
214
 
144
215
  ```ts
145
216
  import { createAdHubServerClient } from "@adhub-so/adhub-nextjs-sdk/server";
@@ -160,11 +231,14 @@ await adhub.track({
160
231
  });
161
232
  ```
162
233
 
163
- `eventId` is required for trusted server events and is used as the idempotency key. Reuse the same ID for retries of the same business fact.
234
+ `eventId` is required and acts as the idempotency key. Reuse the same ID when retrying the same business fact. The server `profileId` must match the stable ID used by the browser integration.
235
+
236
+ ### Signup attribution
164
237
 
165
- When a trusted event is sent during an OAuth callback, pass the anonymous ID
166
- that this SDK persisted in the browser cookie. AdHub will claim that anonymous
167
- identity for the profile before attributing the event:
238
+ Send signup from the account-creation success path, database hook, or auth
239
+ webhook that owns that business fact. A shared OAuth callback can represent
240
+ either signup or login, so the SDK does not infer signup from callback or
241
+ identify activity:
168
242
 
169
243
  ```ts
170
244
  import {
@@ -172,23 +246,29 @@ import {
172
246
  readAdHubAnonymousId,
173
247
  } from "@adhub-so/adhub-nextjs-sdk/server";
174
248
 
175
- const adhub = createAdHubServerClient({
176
- projectKey: process.env.ADHUB_PROJECT_KEY!,
177
- ingestionKey: process.env.ADHUB_INGESTION_KEY!,
178
- });
179
-
180
249
  await adhub.track({
181
250
  eventType: process.env.ADHUB_SIGNUP_EVENT_TYPE_ID!,
182
- profileId: user.id,
183
- anonymousId: readAdHubAnonymousId(request.headers.get("cookie"), process.env.ADHUB_PROJECT_KEY!),
184
- eventId: `signup:${user.id}`,
185
- occurredAt: user.created_at,
251
+ profileId: createdUser.id,
252
+ anonymousId: readAdHubAnonymousId(
253
+ request.headers.get("cookie"),
254
+ process.env.ADHUB_PROJECT_KEY!,
255
+ ) ?? undefined,
256
+ eventId: `signup:${createdUser.id}`,
257
+ occurredAt: createdUser.created_at,
186
258
  });
187
259
  ```
188
260
 
189
- ## Attribution testing
261
+ The SDK keeps one generic `track()` API. When this AdHub event is bound to a
262
+ Google Ads conversion action whose category is `SIGNUP`, AdHub automatically
263
+ treats the event as a once-per-profile fact. Later login callbacks cannot
264
+ reattribute or upload the signup again, even if application code sends a new
265
+ `eventId`. The account creation timestamp remains the correct `occurredAt` for
266
+ normal retries and prevents a historical account from being attributed to a
267
+ newer ad click.
268
+
269
+ ### Attribution testing
190
270
 
191
- AdHub's dashboard can create zero-write preview envelopes through the explicit testing entry:
271
+ The dashboard can generate zero-write preview envelopes from the explicit testing entry:
192
272
 
193
273
  ```ts
194
274
  import { createAttributionTestEnvelopes } from "@adhub-so/adhub-nextjs-sdk/testing";
@@ -200,6 +280,6 @@ This helper does not initialize browser tracking, modify storage, or send networ
200
280
 
201
281
  - `@adhub-so/adhub-nextjs-sdk`: `AdHubComponent`, `initAdHub`, `useAdHub`, and client-side types.
202
282
  - `@adhub-so/adhub-nextjs-sdk/server`: `createRouteHandler`, `createAdHubServerClient`, server payload helpers, errors, and server types.
203
- - `@adhub-so/adhub-nextjs-sdk/testing`: the dashboard attribution-test envelope helper and its types.
283
+ - `@adhub-so/adhub-nextjs-sdk/testing`: attribution-test envelope helpers and types.
204
284
 
205
- The package does not expose `./browser`, redundant framework subpaths, a global IIFE, a client factory, or generic singleton event functions. Browser operations stay behind the Next.js component, initialization entry, and client Hook.
285
+ This package targets Next.js. Browser operations stay behind the component, initialization entry, and client Hook; it does not publish a global IIFE or generic singleton event functions.
package/dist/index.cjs CHANGED
@@ -383,13 +383,72 @@ 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.2.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
+ function decideGoogleAdsTag(payload) {
396
+ if (!payload || typeof payload !== "object") return { action: "skip" };
397
+ const tag = payload.googleAdsWebsiteTag;
398
+ if (!tag || typeof tag !== "object") return { action: "skip" };
399
+ const record = tag;
400
+ if (record.enabled !== true) return { action: "skip" };
401
+ if (typeof record.conversionId !== "string" || record.conversionId.trim() === "") {
402
+ return { action: "skip" };
403
+ }
404
+ const conversionId = record.conversionId.trim();
405
+ if (!GOOGLE_ADS_CONVERSION_ID.test(conversionId)) return { action: "invalid" };
406
+ return { action: "inject", conversionId };
407
+ }
408
+ function adHubGtagMarker() {
409
+ const current = window.__ADHUB_GTAG__;
410
+ if (current && typeof current.js === "boolean" && Array.isArray(current.configuredIds)) {
411
+ return current;
412
+ }
413
+ const marker = { js: false, configuredIds: [] };
414
+ window.__ADHUB_GTAG__ = marker;
415
+ return marker;
416
+ }
417
+ function gtagScriptSrc(conversionId) {
418
+ return `https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(conversionId)}`;
419
+ }
420
+ function installGtagShim() {
421
+ window.dataLayer = window.dataLayer || [];
422
+ if (typeof window.gtag === "function") return;
423
+ window.gtag = function gtag() {
424
+ window.dataLayer?.push(arguments);
425
+ };
426
+ }
427
+ function ensureGtagScript(conversionId) {
428
+ const src = gtagScriptSrc(conversionId);
429
+ for (const script2 of document.getElementsByTagName("script")) {
430
+ if (script2.src === src) return;
431
+ }
432
+ const script = document.createElement("script");
433
+ script.async = true;
434
+ script.src = src;
435
+ script.setAttribute("data-adhub-gtag", conversionId);
436
+ (document.head ?? document.documentElement).appendChild(script);
437
+ }
438
+ function injectGoogleAdsWebsiteTag(conversionId) {
439
+ const marker = adHubGtagMarker();
440
+ if (marker.configuredIds.includes(conversionId)) return;
441
+ installGtagShim();
442
+ ensureGtagScript(conversionId);
443
+ const gtag = window.gtag;
444
+ if (typeof gtag !== "function") return;
445
+ if (!marker.js) {
446
+ marker.js = true;
447
+ gtag("js", /* @__PURE__ */ new Date());
448
+ }
449
+ marker.configuredIds.push(conversionId);
450
+ gtag("config", conversionId);
451
+ }
393
452
  var EMPTY_STATE = {
394
453
  initialized: false,
395
454
  anonymousId: null,
@@ -515,7 +574,11 @@ var AdHubBrowserClient = class {
515
574
  this.autoTrackOutgoingLinks = true;
516
575
  this.autoTrackDataAttributes = true;
517
576
  this.trackHashChanges = false;
577
+ this.waitForConsent = false;
578
+ this.gtagAbort = null;
518
579
  this.lastPageSignature = "";
580
+ this.lastTrackedPageUrl = "";
581
+ this.pendingPageReferrer = null;
519
582
  this.originalPushState = null;
520
583
  this.originalReplaceState = null;
521
584
  this.patchedPushState = null;
@@ -566,10 +629,17 @@ var AdHubBrowserClient = class {
566
629
  return;
567
630
  }
568
631
  if (!browserAvailable()) return;
569
- if (this.state.initialized && this.projectKey === projectKey && this.endpoint === endpoint) return;
632
+ if (this.state.initialized && this.projectKey === projectKey && this.endpoint === endpoint) {
633
+ if (this.waitForConsent && options.waitForConsent !== true) {
634
+ this.waitForConsent = false;
635
+ this.scheduleGoogleAdsWebsiteTag();
636
+ }
637
+ return;
638
+ }
570
639
  this.projectKey = projectKey;
571
640
  this.endpoint = endpoint;
572
641
  this.debug = options.debug ?? false;
642
+ this.waitForConsent = options.waitForConsent === true;
573
643
  this.autoFlush = options.autoFlush ?? true;
574
644
  this.autoPageview = options.autoPageview ?? true;
575
645
  this.autoPageEngagement = options.autoPageEngagement ?? true;
@@ -615,6 +685,7 @@ var AdHubBrowserClient = class {
615
685
  this.installBehaviorTracking();
616
686
  }
617
687
  this.scheduleFlush();
688
+ this.scheduleGoogleAdsWebsiteTag();
618
689
  } catch (error) {
619
690
  this.reportError(error);
620
691
  }
@@ -669,7 +740,10 @@ var AdHubBrowserClient = class {
669
740
  normalized.title,
670
741
  normalized.eventId
671
742
  ].join("|");
672
- if (!input.eventId && signature === this.lastPageSignature) return;
743
+ if (!input.eventId && signature === this.lastPageSignature) {
744
+ this.pendingPageReferrer = null;
745
+ return;
746
+ }
673
747
  this.lastPageSignature = signature;
674
748
  this.finishPageVisit();
675
749
  const pageViewId = normalized.eventId ?? randomId("page");
@@ -677,6 +751,9 @@ var AdHubBrowserClient = class {
677
751
  if (this.autoPageEngagement) {
678
752
  this.startPageVisit(normalized, pageViewId, sessionId);
679
753
  }
754
+ this.lastTrackedPageUrl = normalized.pageUrl ?? safePageUrl(window.location.href);
755
+ this.pendingPageReferrer = null;
756
+ this.trackGoogleAdsPageView();
680
757
  } catch (error) {
681
758
  this.reportError(error);
682
759
  }
@@ -735,6 +812,8 @@ var AdHubBrowserClient = class {
735
812
  this.store.writeSession(sessionId);
736
813
  this.updateState({ anonymousId, sessionId, profileId: null, lastError: null });
737
814
  this.lastPageSignature = "";
815
+ this.lastTrackedPageUrl = "";
816
+ this.pendingPageReferrer = null;
738
817
  if (this.autoPageview) this.page();
739
818
  } catch (error) {
740
819
  this.reportError(error);
@@ -762,6 +841,8 @@ var AdHubBrowserClient = class {
762
841
  return () => this.listeners.delete(listener);
763
842
  }
764
843
  destroy() {
844
+ this.gtagAbort?.abort();
845
+ this.gtagAbort = null;
765
846
  this.finishPageVisit();
766
847
  if (browserAvailable() && this.lifecycleInstalled) {
767
848
  window.removeEventListener("online", this.onOnline);
@@ -827,11 +908,13 @@ var AdHubBrowserClient = class {
827
908
  return sessionId;
828
909
  }
829
910
  currentPageFields() {
911
+ const pageUrl = safePageUrl(window.location.href);
912
+ const referrer = this.pendingPageReferrer ?? (this.lastTrackedPageUrl && this.lastTrackedPageUrl !== pageUrl ? this.lastTrackedPageUrl : document.referrer || null);
830
913
  return {
831
- pageUrl: safePageUrl(window.location.href),
914
+ pageUrl,
832
915
  path: window.location.pathname || "/",
833
916
  title: document.title,
834
- referrer: document.referrer || null
917
+ referrer
835
918
  };
836
919
  }
837
920
  enqueueBehaviorEvent(normalized) {
@@ -942,13 +1025,10 @@ var AdHubBrowserClient = class {
942
1025
  try {
943
1026
  const response = await fetch(`${this.endpoint}${item.path}`, {
944
1027
  method: "POST",
945
- headers: {
1028
+ headers: this.sdkHeaders({
946
1029
  "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
- },
1030
+ "Idempotency-Key": item.requestId
1031
+ }),
952
1032
  body: JSON.stringify(item.body),
953
1033
  keepalive: true,
954
1034
  credentials: "omit",
@@ -1001,6 +1081,74 @@ var AdHubBrowserClient = class {
1001
1081
  this.store?.saveQueue(this.queue);
1002
1082
  this.updateState({ queuedCount: this.queue.length });
1003
1083
  }
1084
+ scheduleGoogleAdsWebsiteTag() {
1085
+ if (!browserAvailable() || this.waitForConsent) return;
1086
+ this.gtagAbort?.abort();
1087
+ const abort = new AbortController();
1088
+ this.gtagAbort = abort;
1089
+ queueMicrotask(() => {
1090
+ if (abort.signal.aborted) return;
1091
+ void this.fetchAndInjectGoogleAdsWebsiteTag(abort);
1092
+ });
1093
+ }
1094
+ async fetchAndInjectGoogleAdsWebsiteTag(abort) {
1095
+ const timeout = setTimeout(() => abort.abort(), REQUEST_TIMEOUT_MS);
1096
+ try {
1097
+ const response = await fetch(`${this.endpoint}${SDK_CONFIG_PATH}`, {
1098
+ method: "GET",
1099
+ headers: this.sdkHeaders(),
1100
+ credentials: "omit",
1101
+ signal: abort.signal
1102
+ });
1103
+ if (abort.signal.aborted) return;
1104
+ if (!response.ok) {
1105
+ this.log(`Google Ads website tag config returned HTTP ${response.status}.`);
1106
+ return;
1107
+ }
1108
+ let payload;
1109
+ try {
1110
+ payload = await response.json();
1111
+ } catch (error) {
1112
+ this.log(`Google Ads website tag config was not applied: ${errorMessage(error)}`);
1113
+ return;
1114
+ }
1115
+ if (abort.signal.aborted) return;
1116
+ const decision = decideGoogleAdsTag(payload);
1117
+ if (decision.action === "skip") return;
1118
+ if (decision.action === "invalid") {
1119
+ this.log("Google Ads website tag config did not include a valid AW- conversion id.");
1120
+ return;
1121
+ }
1122
+ injectGoogleAdsWebsiteTag(decision.conversionId);
1123
+ } 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);
1128
+ }
1129
+ }
1130
+ trackGoogleAdsPageView() {
1131
+ if (!this.autoPageview || !browserAvailable()) return;
1132
+ const marker = window.__ADHUB_GTAG__;
1133
+ if (!marker?.configuredIds.length || typeof window.gtag !== "function") return;
1134
+ try {
1135
+ window.gtag("event", "page_view", {
1136
+ page_location: window.location.href,
1137
+ page_path: `${window.location.pathname}${window.location.search}`,
1138
+ page_title: document.title
1139
+ });
1140
+ } catch (error) {
1141
+ this.log(`Google Ads page_view was not sent: ${errorMessage(error)}`);
1142
+ }
1143
+ }
1144
+ sdkHeaders(extra) {
1145
+ return {
1146
+ "X-AdHub-Project-Key": this.projectKey,
1147
+ "X-AdHub-SDK": SDK_NAME,
1148
+ "X-AdHub-SDK-Version": SDK_VERSION,
1149
+ ...extra
1150
+ };
1151
+ }
1004
1152
  installLifecycle() {
1005
1153
  if (this.lifecycleInstalled) return;
1006
1154
  window.addEventListener("online", this.onOnline);
@@ -1029,14 +1177,25 @@ var AdHubBrowserClient = class {
1029
1177
  };
1030
1178
  const originalPushState = this.originalPushState;
1031
1179
  const originalReplaceState = this.originalReplaceState;
1180
+ const client = this;
1032
1181
  this.patchedPushState = function pushState(...args) {
1182
+ const previousPageUrl = safePageUrl(window.location.href);
1033
1183
  const result = originalPushState.apply(this, args);
1034
- dispatchLocationChange();
1184
+ const nextPageUrl = safePageUrl(window.location.href);
1185
+ if (previousPageUrl !== nextPageUrl) {
1186
+ client.pendingPageReferrer ?? (client.pendingPageReferrer = client.lastTrackedPageUrl || previousPageUrl);
1187
+ dispatchLocationChange();
1188
+ }
1035
1189
  return result;
1036
1190
  };
1037
1191
  this.patchedReplaceState = function replaceState(...args) {
1192
+ const previousPageUrl = safePageUrl(window.location.href);
1038
1193
  const result = originalReplaceState.apply(this, args);
1039
- dispatchLocationChange();
1194
+ const nextPageUrl = safePageUrl(window.location.href);
1195
+ if (previousPageUrl !== nextPageUrl) {
1196
+ client.pendingPageReferrer ?? (client.pendingPageReferrer = client.lastTrackedPageUrl || previousPageUrl);
1197
+ dispatchLocationChange();
1198
+ }
1040
1199
  return result;
1041
1200
  };
1042
1201
  history.pushState = this.patchedPushState;