@vulcantech/analytics 0.1.2 → 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 +24 -2
- package/dist/index.d.mts +60 -6
- package/dist/index.d.ts +60 -6
- package/dist/index.js +132 -3
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +133 -6
- package/dist/index.mjs.map +1 -1
- package/dist/route.d.mts +7 -1
- package/dist/route.d.ts +7 -1
- package/dist/route.js +4 -1
- package/dist/route.js.map +1 -1
- package/dist/route.mjs +4 -1
- package/dist/route.mjs.map +1 -1
- package/dist/tags.d.mts +53 -3
- package/dist/tags.d.ts +53 -3
- package/dist/tags.js +42 -3
- package/dist/tags.js.map +1 -1
- package/dist/tags.mjs +42 -3
- package/dist/tags.mjs.map +1 -1
- package/package.json +4 -3
- package/src/PhoneLink.tsx +69 -0
- package/src/index.tsx +2 -0
- package/src/route.ts +10 -1
- package/src/tags.tsx +134 -5
- package/src/tracker.ts +225 -10
package/README.md
CHANGED
|
@@ -66,15 +66,35 @@ interface TrackingTags {
|
|
|
66
66
|
ga4Id?: string; // GA4 measurement ID — CMS validates /^G-[A-Z0-9]{4,14}$/
|
|
67
67
|
googleAdsId?: string; // Google Ads conversion ID — CMS validates /^AW-\d{6,12}$/
|
|
68
68
|
metaPixelId?: string; // Meta Pixel ID — CMS validates /^\d{6,20}$/ (numeric string)
|
|
69
|
+
// Google Ads form-conversion send_to — CMS validates /^AW-\d{6,12}\/[A-Za-z0-9_-]{6,64}$/
|
|
70
|
+
formConversionSendTo?: string;
|
|
69
71
|
}
|
|
70
72
|
```
|
|
71
73
|
|
|
72
|
-
- **`fetchTrackingTags()` returns `null`, not `{}`,** when all three resolve empty. `CMSTags` renders `null` in that case.
|
|
74
|
+
- **`fetchTrackingTags()` returns `null`, not `{}`,** when all three tag IDs resolve empty (`formConversionSendTo` does not count — see below). `CMSTags` renders `null` in that case.
|
|
73
75
|
- **Format validation is CMS-side only.** Those patterns are enforced when a staff user saves the config in the dashboard. Values coming from the `NEXT_PUBLIC_*` env fallbacks are **not** validated by this package — a typo'd env ID is injected verbatim.
|
|
74
76
|
- **`CMSTags` is an async React Server Component.** Do not add `"use client"` to a wrapper around it and do not call `fetchTrackingTags()` from client code — it reads `VULCANTECH_API_KEY`.
|
|
75
77
|
- **What it renders:** one shared `next/script` `gtag.js` loader with `strategy="afterInteractive"`, keyed to the **first** present Google ID, plus an inline init that `gtag('config', …)`s every present Google ID; and, for Meta, the standard inline `fbq` bootstrap with `fbq('track','PageView')` and a `<noscript>` tracking-pixel `<img>`. Because it uses `next/script`, mounting it in `<body>` is correct — it does not need to be in `<head>`.
|
|
76
78
|
- **No consent gating.** Tags load as soon as the page hydrates. If the site needs a CMP / GDPR consent gate, `CMSTags` does not provide one and must not be mounted unconditionally on a site that requires consent.
|
|
77
79
|
|
|
80
|
+
### `formConversionSendTo` — the form-submit Ads conversion
|
|
81
|
+
|
|
82
|
+
`formConversionSendTo` is **not a tag loader**. It is the Google Ads `send_to` value (`AW-<conversion id>/<label>`, e.g. `AW-18321257894/AbC-D3fGhIjKlmNoP`) that `@vulcantech/forms` fires when one of its forms submits successfully:
|
|
83
|
+
|
|
84
|
+
```js
|
|
85
|
+
gtag("event", "conversion", { send_to: "AW-18321257894/AbC-D3fGhIjKlmNoP" });
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
The two packages have no dependency on each other, so `CMSTags` hands the value over through a global: the inline `vt-gtag-init` script assigns it to **`window.__vtFormConversionSendTo`**, and `DynamicForm` reads it there on success. A form's own `submitConfig.conversion.sendTo` takes precedence.
|
|
89
|
+
|
|
90
|
+
Consequences worth knowing:
|
|
91
|
+
|
|
92
|
+
- **It needs a Google ID to ride on.** The label is only published inside the `gtag` init block, which renders only when `ga4Id` or `googleAdsId` is set. A `formConversionSendTo` on its own renders nothing and does not count towards "something is configured" — `fetchTrackingTags()` still returns `null`.
|
|
93
|
+
- **Set it once per project, not per form.** Nothing in a consumer app should hardcode the label.
|
|
94
|
+
- **The `form_submit_success` dataLayer event fires regardless of this field** — see the `@vulcantech/forms` README. This field only controls the *direct* `gtag` conversion, which sites without a GTM container need.
|
|
95
|
+
|
|
96
|
+
**Where to get the value:** Google Ads → Goals → Summary → the conversion action → Tag setup → "Install the tag yourself"; the `send_to` in the snippet is the whole value, ID and label together.
|
|
97
|
+
|
|
78
98
|
### The `enabled` toggle does not override env fallbacks
|
|
79
99
|
|
|
80
100
|
Turning tracking tags **off** in the CMS makes `/api/analytics/config` return `config: null` — which is the *same* response as "never configured". `fetchTrackingTags` then fills each field from `NEXT_PUBLIC_GA_ID` / `NEXT_PUBLIC_GOOGLE_ADS_ID` / `NEXT_PUBLIC_META_PIXEL_ID`. **So a site with those env vars set keeps firing its tags after the CMS switch is off.** To actually disable tags on such a site you must unset the env vars and redeploy. Sites that rely purely on the CMS (no `NEXT_PUBLIC_*` set) honor the toggle as expected.
|
|
@@ -151,8 +171,9 @@ When the CMS omits a field (unreachable, unconfigured, or key lacks scope), each
|
|
|
151
171
|
| GA4 | `ga4Id` | `NEXT_PUBLIC_GA_ID` |
|
|
152
172
|
| Google Ads | `googleAdsId` | `NEXT_PUBLIC_GOOGLE_ADS_ID` |
|
|
153
173
|
| Meta Pixel | `metaPixelId` | `NEXT_PUBLIC_META_PIXEL_ID` |
|
|
174
|
+
| Form conversion `send_to` | `formConversionSendTo` | `NEXT_PUBLIC_FORM_CONVERSION_SEND_TO` |
|
|
154
175
|
|
|
155
|
-
If all three end up empty, `CMSTags` renders nothing.
|
|
176
|
+
If all three **tag IDs** end up empty, `CMSTags` renders nothing — a `formConversionSendTo` alone is not enough, since it has no tag to attach to.
|
|
156
177
|
|
|
157
178
|
### Per-app values
|
|
158
179
|
None beyond env — analytics and tags are fully config-driven from the CMS.
|
|
@@ -163,6 +184,7 @@ None beyond env — analytics and tags are fully config-driven from the CMS.
|
|
|
163
184
|
```js
|
|
164
185
|
Object.keys(window.google_tag_manager) // includes both G-… and AW-…
|
|
165
186
|
window.dataLayer.filter(a => a[0] === "config")
|
|
187
|
+
window.__vtFormConversionSendTo // the form-conversion label, when set
|
|
166
188
|
```
|
|
167
189
|
|
|
168
190
|
### Notes
|
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import * as react from 'react';
|
|
2
|
+
import { AnchorHTMLAttributes, ReactNode } from 'react';
|
|
2
3
|
|
|
3
4
|
/**
|
|
4
5
|
* VulcanTech Analytics — lightweight first-party tracker.
|
|
@@ -29,7 +30,8 @@ interface AnalyticsEvent {
|
|
|
29
30
|
/**
|
|
30
31
|
* `document.referrer` on pageviews, `""` on custom events. Truncated to
|
|
31
32
|
* 2048 chars. Together with {@link AnalyticsEvent.utm} this drives the CMS
|
|
32
|
-
* traffic-source classification
|
|
33
|
+
* traffic-source classification; custom events have no referrer, so their
|
|
34
|
+
* attribution rides entirely on {@link AnalyticsEvent.utm}.
|
|
33
35
|
*/
|
|
34
36
|
ref: string;
|
|
35
37
|
/** Session id from `sessionStorage` — see {@link getSessionId}. Capped at 64 chars. */
|
|
@@ -43,7 +45,14 @@ interface AnalyticsEvent {
|
|
|
43
45
|
vh: number;
|
|
44
46
|
/** `Date.now()` on the client. The CMS stores its own `serverTs` alongside it. */
|
|
45
47
|
ts: number;
|
|
46
|
-
/**
|
|
48
|
+
/**
|
|
49
|
+
* Campaign context. On pageviews: the `utm_*` params and click ids present
|
|
50
|
+
* in the URL, or — on later pages of the same visit — the ones the visit
|
|
51
|
+
* landed with (see {@link getSessionCampaign}). The CMS tells a landing from
|
|
52
|
+
* a later page by whether `url` itself carries them. On custom events:
|
|
53
|
+
* `utm_source`/`utm_medium`/`utm_campaign` from the 30-day ad-referral
|
|
54
|
+
* cookie, else the session's landing params.
|
|
55
|
+
*/
|
|
47
56
|
utm?: Record<string, string>;
|
|
48
57
|
/**
|
|
49
58
|
* Custom events only. Truncated to 128 chars.
|
|
@@ -100,6 +109,18 @@ declare function trackFormSubmit(formId: string, formName?: string, submissionTy
|
|
|
100
109
|
* JS).
|
|
101
110
|
*/
|
|
102
111
|
declare function trackPhoneClick(phoneNumber?: string): void;
|
|
112
|
+
/**
|
|
113
|
+
* Record that Google's forwarding-number swap showed this visitor a call
|
|
114
|
+
* tracking number — i.e. an ad visitor was eligible to place a tracked call.
|
|
115
|
+
*
|
|
116
|
+
* Fired automatically (see the registration block below) when `CMSTags`'
|
|
117
|
+
* swap callback dispatches `vt-phone`; once per session, since gtag runs the
|
|
118
|
+
* callback on every full page load. The calls themselves never reach us —
|
|
119
|
+
* they go Google → shop — so this is the first-party half of call tracking.
|
|
120
|
+
*
|
|
121
|
+
* @param formatted The forwarding number as Google formatted it.
|
|
122
|
+
*/
|
|
123
|
+
declare function trackPhoneSwap(formatted?: string): void;
|
|
103
124
|
/**
|
|
104
125
|
* Track when an email link is clicked.
|
|
105
126
|
*
|
|
@@ -110,12 +131,45 @@ declare function trackEmailClick(email?: string): void;
|
|
|
110
131
|
/**
|
|
111
132
|
* Track a 404 page.
|
|
112
133
|
*
|
|
113
|
-
*
|
|
114
|
-
*
|
|
115
|
-
*
|
|
134
|
+
* `url` defaults to the current pathname. No-ops during SSR and on dev
|
|
135
|
+
* hostnames, and never throws — like every other tracker in this module.
|
|
136
|
+
*
|
|
137
|
+
* @param url Optional path to report instead of the current pathname.
|
|
116
138
|
*/
|
|
117
139
|
declare function track404(url?: string): void;
|
|
118
140
|
|
|
119
141
|
declare function AnalyticsTracker(): react.JSX.Element;
|
|
120
142
|
|
|
121
|
-
|
|
143
|
+
interface PhoneLinkProps extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, "href" | "children" | "prefix"> {
|
|
144
|
+
/** The number as displayed, e.g. `"602.904.9109"`. */
|
|
145
|
+
display: string;
|
|
146
|
+
/** E.164 dial string without `tel:`, e.g. `"+16029049109"`. */
|
|
147
|
+
tel: string;
|
|
148
|
+
/** Rendered before the number, e.g. `"Or call · "` or an icon. */
|
|
149
|
+
prefix?: ReactNode;
|
|
150
|
+
/** Rendered after the number. */
|
|
151
|
+
suffix?: ReactNode;
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* A `tel:` link that shows Google's forwarding number to visitors who arrived
|
|
155
|
+
* from an ad.
|
|
156
|
+
*
|
|
157
|
+
* `CMSTags` configures Google's number swap (when the project has a
|
|
158
|
+
* `callConversionSendTo` + `callConversionNumber`) with a callback that stores
|
|
159
|
+
* the forwarding number on `window.__vtPhone` and fires `vt-phone`; this
|
|
160
|
+
* component re-renders on that event. Doing it in React rather than letting
|
|
161
|
+
* gtag rewrite the DOM matters: React would put the original number back on
|
|
162
|
+
* the next render or client-side navigation.
|
|
163
|
+
*
|
|
164
|
+
* Everyone else — and the server render — sees `display` / `tel`. Taps are
|
|
165
|
+
* tracked by the delegated listener `AnalyticsTracker` installs; don't add an
|
|
166
|
+
* `onClick` tracker here or the tap double-counts.
|
|
167
|
+
*
|
|
168
|
+
* @param props.display Number as shown on the page (must match `callConversionNumber`).
|
|
169
|
+
* @param props.tel E.164 dial string, without the `tel:` scheme.
|
|
170
|
+
* @param props.prefix Optional content before the number.
|
|
171
|
+
* @param props.suffix Optional content after the number.
|
|
172
|
+
*/
|
|
173
|
+
declare function PhoneLink({ display, tel, prefix, suffix, ...rest }: PhoneLinkProps): react.JSX.Element;
|
|
174
|
+
|
|
175
|
+
export { type AnalyticsEvent, AnalyticsTracker, PhoneLink, type PhoneLinkProps, track404, trackEmailClick, trackEvent, trackFormSubmit, trackFormView, trackPageView, trackPhoneClick, trackPhoneSwap };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import * as react from 'react';
|
|
2
|
+
import { AnchorHTMLAttributes, ReactNode } from 'react';
|
|
2
3
|
|
|
3
4
|
/**
|
|
4
5
|
* VulcanTech Analytics — lightweight first-party tracker.
|
|
@@ -29,7 +30,8 @@ interface AnalyticsEvent {
|
|
|
29
30
|
/**
|
|
30
31
|
* `document.referrer` on pageviews, `""` on custom events. Truncated to
|
|
31
32
|
* 2048 chars. Together with {@link AnalyticsEvent.utm} this drives the CMS
|
|
32
|
-
* traffic-source classification
|
|
33
|
+
* traffic-source classification; custom events have no referrer, so their
|
|
34
|
+
* attribution rides entirely on {@link AnalyticsEvent.utm}.
|
|
33
35
|
*/
|
|
34
36
|
ref: string;
|
|
35
37
|
/** Session id from `sessionStorage` — see {@link getSessionId}. Capped at 64 chars. */
|
|
@@ -43,7 +45,14 @@ interface AnalyticsEvent {
|
|
|
43
45
|
vh: number;
|
|
44
46
|
/** `Date.now()` on the client. The CMS stores its own `serverTs` alongside it. */
|
|
45
47
|
ts: number;
|
|
46
|
-
/**
|
|
48
|
+
/**
|
|
49
|
+
* Campaign context. On pageviews: the `utm_*` params and click ids present
|
|
50
|
+
* in the URL, or — on later pages of the same visit — the ones the visit
|
|
51
|
+
* landed with (see {@link getSessionCampaign}). The CMS tells a landing from
|
|
52
|
+
* a later page by whether `url` itself carries them. On custom events:
|
|
53
|
+
* `utm_source`/`utm_medium`/`utm_campaign` from the 30-day ad-referral
|
|
54
|
+
* cookie, else the session's landing params.
|
|
55
|
+
*/
|
|
47
56
|
utm?: Record<string, string>;
|
|
48
57
|
/**
|
|
49
58
|
* Custom events only. Truncated to 128 chars.
|
|
@@ -100,6 +109,18 @@ declare function trackFormSubmit(formId: string, formName?: string, submissionTy
|
|
|
100
109
|
* JS).
|
|
101
110
|
*/
|
|
102
111
|
declare function trackPhoneClick(phoneNumber?: string): void;
|
|
112
|
+
/**
|
|
113
|
+
* Record that Google's forwarding-number swap showed this visitor a call
|
|
114
|
+
* tracking number — i.e. an ad visitor was eligible to place a tracked call.
|
|
115
|
+
*
|
|
116
|
+
* Fired automatically (see the registration block below) when `CMSTags`'
|
|
117
|
+
* swap callback dispatches `vt-phone`; once per session, since gtag runs the
|
|
118
|
+
* callback on every full page load. The calls themselves never reach us —
|
|
119
|
+
* they go Google → shop — so this is the first-party half of call tracking.
|
|
120
|
+
*
|
|
121
|
+
* @param formatted The forwarding number as Google formatted it.
|
|
122
|
+
*/
|
|
123
|
+
declare function trackPhoneSwap(formatted?: string): void;
|
|
103
124
|
/**
|
|
104
125
|
* Track when an email link is clicked.
|
|
105
126
|
*
|
|
@@ -110,12 +131,45 @@ declare function trackEmailClick(email?: string): void;
|
|
|
110
131
|
/**
|
|
111
132
|
* Track a 404 page.
|
|
112
133
|
*
|
|
113
|
-
*
|
|
114
|
-
*
|
|
115
|
-
*
|
|
134
|
+
* `url` defaults to the current pathname. No-ops during SSR and on dev
|
|
135
|
+
* hostnames, and never throws — like every other tracker in this module.
|
|
136
|
+
*
|
|
137
|
+
* @param url Optional path to report instead of the current pathname.
|
|
116
138
|
*/
|
|
117
139
|
declare function track404(url?: string): void;
|
|
118
140
|
|
|
119
141
|
declare function AnalyticsTracker(): react.JSX.Element;
|
|
120
142
|
|
|
121
|
-
|
|
143
|
+
interface PhoneLinkProps extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, "href" | "children" | "prefix"> {
|
|
144
|
+
/** The number as displayed, e.g. `"602.904.9109"`. */
|
|
145
|
+
display: string;
|
|
146
|
+
/** E.164 dial string without `tel:`, e.g. `"+16029049109"`. */
|
|
147
|
+
tel: string;
|
|
148
|
+
/** Rendered before the number, e.g. `"Or call · "` or an icon. */
|
|
149
|
+
prefix?: ReactNode;
|
|
150
|
+
/** Rendered after the number. */
|
|
151
|
+
suffix?: ReactNode;
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* A `tel:` link that shows Google's forwarding number to visitors who arrived
|
|
155
|
+
* from an ad.
|
|
156
|
+
*
|
|
157
|
+
* `CMSTags` configures Google's number swap (when the project has a
|
|
158
|
+
* `callConversionSendTo` + `callConversionNumber`) with a callback that stores
|
|
159
|
+
* the forwarding number on `window.__vtPhone` and fires `vt-phone`; this
|
|
160
|
+
* component re-renders on that event. Doing it in React rather than letting
|
|
161
|
+
* gtag rewrite the DOM matters: React would put the original number back on
|
|
162
|
+
* the next render or client-side navigation.
|
|
163
|
+
*
|
|
164
|
+
* Everyone else — and the server render — sees `display` / `tel`. Taps are
|
|
165
|
+
* tracked by the delegated listener `AnalyticsTracker` installs; don't add an
|
|
166
|
+
* `onClick` tracker here or the tap double-counts.
|
|
167
|
+
*
|
|
168
|
+
* @param props.display Number as shown on the page (must match `callConversionNumber`).
|
|
169
|
+
* @param props.tel E.164 dial string, without the `tel:` scheme.
|
|
170
|
+
* @param props.prefix Optional content before the number.
|
|
171
|
+
* @param props.suffix Optional content after the number.
|
|
172
|
+
*/
|
|
173
|
+
declare function PhoneLink({ display, tel, prefix, suffix, ...rest }: PhoneLinkProps): react.JSX.Element;
|
|
174
|
+
|
|
175
|
+
export { type AnalyticsEvent, AnalyticsTracker, PhoneLink, type PhoneLinkProps, track404, trackEmailClick, trackEvent, trackFormSubmit, trackFormView, trackPageView, trackPhoneClick, trackPhoneSwap };
|
package/dist/index.js
CHANGED
|
@@ -20,6 +20,33 @@ function getSessionId() {
|
|
|
20
20
|
return Math.random().toString(36).slice(2);
|
|
21
21
|
}
|
|
22
22
|
}
|
|
23
|
+
var AD_REFERRAL_COOKIE = "vt_ad_ref";
|
|
24
|
+
function getAdReferralUtm() {
|
|
25
|
+
if (typeof document === "undefined") return null;
|
|
26
|
+
for (const cookie of document.cookie.split(";")) {
|
|
27
|
+
const sep = cookie.indexOf("=");
|
|
28
|
+
if (sep === -1) continue;
|
|
29
|
+
if (cookie.slice(0, sep).trim() !== AD_REFERRAL_COOKIE) continue;
|
|
30
|
+
try {
|
|
31
|
+
const parsed = JSON.parse(decodeURIComponent(cookie.slice(sep + 1)));
|
|
32
|
+
if (!parsed || typeof parsed !== "object") return null;
|
|
33
|
+
const utm = {};
|
|
34
|
+
if (typeof parsed.source === "string" && parsed.source) {
|
|
35
|
+
utm.utm_source = parsed.source;
|
|
36
|
+
}
|
|
37
|
+
if (typeof parsed.medium === "string" && parsed.medium) {
|
|
38
|
+
utm.utm_medium = parsed.medium;
|
|
39
|
+
}
|
|
40
|
+
if (Object.keys(utm).length > 0 && typeof parsed.campaign === "string" && parsed.campaign && parsed.campaign !== "(not set)") {
|
|
41
|
+
utm.utm_campaign = parsed.campaign;
|
|
42
|
+
}
|
|
43
|
+
return Object.keys(utm).length > 0 ? utm : null;
|
|
44
|
+
} catch {
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
23
50
|
function getUtmParams() {
|
|
24
51
|
if (typeof window === "undefined") return {};
|
|
25
52
|
const params = new URLSearchParams(window.location.search);
|
|
@@ -29,13 +56,49 @@ function getUtmParams() {
|
|
|
29
56
|
"utm_medium",
|
|
30
57
|
"utm_campaign",
|
|
31
58
|
"utm_term",
|
|
32
|
-
"utm_content"
|
|
59
|
+
"utm_content",
|
|
60
|
+
"gclid",
|
|
61
|
+
"gbraid",
|
|
62
|
+
"wbraid",
|
|
63
|
+
"gad_source",
|
|
64
|
+
"gad_campaignid",
|
|
65
|
+
"fbclid",
|
|
66
|
+
"msclkid"
|
|
33
67
|
]) {
|
|
34
68
|
const val = params.get(key);
|
|
35
69
|
if (val) utms[key] = val;
|
|
36
70
|
}
|
|
37
71
|
return utms;
|
|
38
72
|
}
|
|
73
|
+
var SESSION_CAMPAIGN_KEY = "__vt_utm";
|
|
74
|
+
var SESSION_CAMPAIGN_IDLE_MS = 30 * 60 * 1e3;
|
|
75
|
+
function getSessionCampaign() {
|
|
76
|
+
try {
|
|
77
|
+
const raw = sessionStorage.getItem(SESSION_CAMPAIGN_KEY);
|
|
78
|
+
if (!raw) return null;
|
|
79
|
+
const parsed = JSON.parse(raw);
|
|
80
|
+
if (!parsed || typeof parsed.at !== "number" || Date.now() - parsed.at > SESSION_CAMPAIGN_IDLE_MS || !parsed.utm || typeof parsed.utm !== "object") {
|
|
81
|
+
sessionStorage.removeItem(SESSION_CAMPAIGN_KEY);
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
const utm = {};
|
|
85
|
+
for (const [k, v] of Object.entries(parsed.utm)) {
|
|
86
|
+
if (typeof v === "string" && v) utm[k] = v;
|
|
87
|
+
}
|
|
88
|
+
return Object.keys(utm).length > 0 ? utm : null;
|
|
89
|
+
} catch {
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
function setSessionCampaign(utm) {
|
|
94
|
+
try {
|
|
95
|
+
sessionStorage.setItem(
|
|
96
|
+
SESSION_CAMPAIGN_KEY,
|
|
97
|
+
JSON.stringify({ utm, at: Date.now() })
|
|
98
|
+
);
|
|
99
|
+
} catch {
|
|
100
|
+
}
|
|
101
|
+
}
|
|
39
102
|
function isDev() {
|
|
40
103
|
if (typeof window === "undefined") return true;
|
|
41
104
|
const host = window.location.hostname;
|
|
@@ -61,7 +124,16 @@ function send(event) {
|
|
|
61
124
|
}
|
|
62
125
|
function trackPageView() {
|
|
63
126
|
if (typeof window === "undefined") return;
|
|
64
|
-
|
|
127
|
+
let utms = getUtmParams();
|
|
128
|
+
if (Object.keys(utms).length > 0) {
|
|
129
|
+
setSessionCampaign(utms);
|
|
130
|
+
} else {
|
|
131
|
+
const session = getSessionCampaign();
|
|
132
|
+
if (session) {
|
|
133
|
+
utms = session;
|
|
134
|
+
setSessionCampaign(session);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
65
137
|
send({
|
|
66
138
|
type: "pageview",
|
|
67
139
|
url: window.location.pathname + window.location.search,
|
|
@@ -75,6 +147,7 @@ function trackPageView() {
|
|
|
75
147
|
}
|
|
76
148
|
function trackEvent(name, props) {
|
|
77
149
|
if (typeof window === "undefined") return;
|
|
150
|
+
const utm = getAdReferralUtm() ?? getSessionCampaign();
|
|
78
151
|
send({
|
|
79
152
|
type: "event",
|
|
80
153
|
url: window.location.pathname,
|
|
@@ -83,6 +156,7 @@ function trackEvent(name, props) {
|
|
|
83
156
|
vw: window.innerWidth,
|
|
84
157
|
vh: window.innerHeight,
|
|
85
158
|
ts: Date.now(),
|
|
159
|
+
...utm ? { utm } : {},
|
|
86
160
|
name,
|
|
87
161
|
props
|
|
88
162
|
});
|
|
@@ -99,12 +173,37 @@ function trackFormSubmit(formId, formName, submissionType) {
|
|
|
99
173
|
}
|
|
100
174
|
function trackPhoneClick(phoneNumber) {
|
|
101
175
|
trackEvent("phone_click", { phone: phoneNumber ?? "" });
|
|
176
|
+
sendGooglePhoneClick(phoneNumber ?? "");
|
|
177
|
+
}
|
|
178
|
+
function sendGooglePhoneClick(phoneNumber) {
|
|
179
|
+
if (typeof window === "undefined") return;
|
|
180
|
+
const w = window;
|
|
181
|
+
if (typeof w.gtag !== "function") return;
|
|
182
|
+
try {
|
|
183
|
+
const sendTo = w.__vtPhoneConversionSendTo;
|
|
184
|
+
if (typeof sendTo === "string" && sendTo.trim() !== "") {
|
|
185
|
+
w.gtag("event", "conversion", { send_to: sendTo.trim() });
|
|
186
|
+
}
|
|
187
|
+
w.gtag("event", "phone_click", { link_url: `tel:${phoneNumber}` });
|
|
188
|
+
} catch {
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
var PHONE_SWAP_SENT_KEY = "vt_phone_swap_sent";
|
|
192
|
+
function trackPhoneSwap(formatted) {
|
|
193
|
+
if (typeof window === "undefined") return;
|
|
194
|
+
try {
|
|
195
|
+
if (window.sessionStorage.getItem(PHONE_SWAP_SENT_KEY)) return;
|
|
196
|
+
window.sessionStorage.setItem(PHONE_SWAP_SENT_KEY, "1");
|
|
197
|
+
} catch {
|
|
198
|
+
}
|
|
199
|
+
trackEvent("phone_swap", { phone: formatted ?? "" });
|
|
102
200
|
}
|
|
103
201
|
function trackEmailClick(email) {
|
|
104
202
|
trackEvent("email_click", { email: email ?? "" });
|
|
105
203
|
}
|
|
106
204
|
function track404(url) {
|
|
107
|
-
|
|
205
|
+
const path = url ?? (typeof window === "undefined" ? "" : window.location.pathname);
|
|
206
|
+
trackEvent("404", { url: path });
|
|
108
207
|
}
|
|
109
208
|
if (typeof window !== "undefined") {
|
|
110
209
|
const w = window;
|
|
@@ -114,6 +213,15 @@ if (typeof window !== "undefined") {
|
|
|
114
213
|
trackPhoneClick,
|
|
115
214
|
trackEmailClick
|
|
116
215
|
};
|
|
216
|
+
if (!w.__vtPhoneSwapListenerInstalled) {
|
|
217
|
+
w.__vtPhoneSwapListenerInstalled = true;
|
|
218
|
+
const sendSwap = () => {
|
|
219
|
+
const swapped = w.__vtPhone;
|
|
220
|
+
if (swapped) trackPhoneSwap(swapped.formatted);
|
|
221
|
+
};
|
|
222
|
+
window.addEventListener("vt-phone", sendSwap);
|
|
223
|
+
if (w.__vtPhone) sendSwap();
|
|
224
|
+
}
|
|
117
225
|
if (!w.__vtClickTrackingInstalled) {
|
|
118
226
|
w.__vtClickTrackingInstalled = true;
|
|
119
227
|
document.addEventListener(
|
|
@@ -149,8 +257,28 @@ function AnalyticsTrackerInner() {
|
|
|
149
257
|
function AnalyticsTracker() {
|
|
150
258
|
return /* @__PURE__ */ jsxRuntime.jsx(react.Suspense, { fallback: null, children: /* @__PURE__ */ jsxRuntime.jsx(AnalyticsTrackerInner, {}) });
|
|
151
259
|
}
|
|
260
|
+
function subscribe(onChange) {
|
|
261
|
+
window.addEventListener("vt-phone", onChange);
|
|
262
|
+
return () => window.removeEventListener("vt-phone", onChange);
|
|
263
|
+
}
|
|
264
|
+
function getSnapshot() {
|
|
265
|
+
return window.__vtPhone ?? null;
|
|
266
|
+
}
|
|
267
|
+
function getServerSnapshot() {
|
|
268
|
+
return null;
|
|
269
|
+
}
|
|
270
|
+
function PhoneLink({ display, tel, prefix, suffix, ...rest }) {
|
|
271
|
+
const swapped = react.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
|
|
272
|
+
const mobile = swapped?.mobile ? swapped.mobile : tel;
|
|
273
|
+
return /* @__PURE__ */ jsxRuntime.jsxs("a", { ...rest, href: `tel:${mobile}`, children: [
|
|
274
|
+
prefix,
|
|
275
|
+
swapped?.formatted || display,
|
|
276
|
+
suffix
|
|
277
|
+
] });
|
|
278
|
+
}
|
|
152
279
|
|
|
153
280
|
exports.AnalyticsTracker = AnalyticsTracker;
|
|
281
|
+
exports.PhoneLink = PhoneLink;
|
|
154
282
|
exports.track404 = track404;
|
|
155
283
|
exports.trackEmailClick = trackEmailClick;
|
|
156
284
|
exports.trackEvent = trackEvent;
|
|
@@ -158,5 +286,6 @@ exports.trackFormSubmit = trackFormSubmit;
|
|
|
158
286
|
exports.trackFormView = trackFormView;
|
|
159
287
|
exports.trackPageView = trackPageView;
|
|
160
288
|
exports.trackPhoneClick = trackPhoneClick;
|
|
289
|
+
exports.trackPhoneSwap = trackPhoneSwap;
|
|
161
290
|
//# sourceMappingURL=index.js.map
|
|
162
291
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/tracker.ts","../src/AnalyticsTracker.tsx"],"names":["usePathname","useSearchParams","useRef","useEffect","Suspense","jsx"],"mappings":";;;;;;;AAQA,IAAM,QAAA,GAAW,QAAA;AACjB,IAAM,WAAA,GAAc,UAAA;AAWpB,SAAS,YAAA,GAAuB;AAC9B,EAAA,IAAI,OAAO,MAAA,KAAW,WAAA,EAAa,OAAO,EAAA;AAC1C,EAAA,IAAI;AACF,IAAA,IAAI,GAAA,GAAM,cAAA,CAAe,OAAA,CAAQ,WAAW,CAAA;AAC5C,IAAA,IAAI,CAAC,GAAA,EAAK;AACR,MAAA,GAAA,GAAM,IAAA,CAAK,MAAA,EAAO,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,KAAA,CAAM,CAAC,CAAA,GAAI,IAAA,CAAK,GAAA,EAAI,CAAE,SAAS,EAAE,CAAA;AAClE,MAAA,cAAA,CAAe,OAAA,CAAQ,aAAa,GAAG,CAAA;AAAA,IACzC;AACA,IAAA,OAAO,GAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAK,MAAA,EAAO,CAAE,SAAS,EAAE,CAAA,CAAE,MAAM,CAAC,CAAA;AAAA,EAC3C;AACF;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AAA,CAAM,CAAC,CAAC,CAAA;AAAA,aACrD,eAAA,CAAgB,IAAA,CAAK,KAAA,CAAM,CAAC,CAAC,CAAA;AAAA,MACpC,CAAA;AAAA,MACA;AAAA,KACF;AAAA,EACF;AACF;ACnRA,SAAS,qBAAA,GAAwB;AAC/B,EAAA,MAAM,WAAWA,sBAAA,EAAY;AAC7B,EAAA,MAAM,eAAeC,0BAAA,EAAgB;AACrC,EAAA,MAAM,aAAA,GAAgBC,aAAO,IAAI,CAAA;AAEjC,EAAAC,eAAA,CAAU,MAAM;AACd,IAAA,IAAI,cAAc,OAAA,EAAS;AACzB,MAAA,aAAA,CAAc,OAAA,GAAU,KAAA;AACxB,MAAA;AAAA,IACF;AACA,IAAA,aAAA,EAAc;AAAA,EAChB,CAAA,EAAG,CAAC,QAAA,EAAU,YAAY,CAAC,CAAA;AAE3B,EAAAA,eAAA,CAAU,MAAM;AACd,IAAA,aAAA,EAAc;AAAA,EAChB,CAAA,EAAG,EAAE,CAAA;AAEL,EAAA,OAAO,IAAA;AACT;AAEO,SAAS,gBAAA,GAAmB;AACjC,EAAA,sCACGC,cAAA,EAAA,EAAS,QAAA,EAAU,IAAA,EAClB,QAAA,kBAAAC,cAAA,CAAC,yBAAsB,CAAA,EACzB,CAAA;AAEJ","file":"index.js","sourcesContent":["/**\n * VulcanTech Analytics — lightweight first-party tracker.\n *\n * < 1KB gzipped. No cookies, no fingerprinting, no DOM manipulation.\n * Sends page views and custom events to /api/a on the same domain\n * via navigator.sendBeacon (falls back to fetch).\n */\n\nconst ENDPOINT = \"/api/a\";\nconst SESSION_KEY = \"__vt_sid\";\n\n/**\n * Generate a random session ID (stored in sessionStorage, not cookies).\n *\n * No cookies means nothing survives a tab close, and there is no cross-tab or\n * cross-visit identity by design. When `sessionStorage` throws (private mode,\n * blocked storage) this returns a FRESH id per call, so each event from that\n * visitor counts as its own session — inflating session counts rather than\n * failing.\n */\nfunction getSessionId(): string {\n if (typeof window === \"undefined\") return \"\";\n try {\n let sid = sessionStorage.getItem(SESSION_KEY);\n if (!sid) {\n sid = Math.random().toString(36).slice(2) + Date.now().toString(36);\n sessionStorage.setItem(SESSION_KEY, sid);\n }\n return sid;\n } catch {\n return Math.random().toString(36).slice(2);\n }\n}\n\n/** Extract UTM params from the current URL. */\nfunction getUtmParams(): Record<string, string> {\n if (typeof window === \"undefined\") return {};\n const params = new URLSearchParams(window.location.search);\n const utms: Record<string, string> = {};\n for (const key of [\n \"utm_source\",\n \"utm_medium\",\n \"utm_campaign\",\n \"utm_term\",\n \"utm_content\",\n ]) {\n const val = params.get(key);\n if (val) utms[key] = val;\n }\n return utms;\n}\n\n/**\n * One analytics event as sent to `/api/a` and forwarded to the CMS.\n *\n * The limits noted per field are enforced SERVER-SIDE on ingest\n * (`/api/analytics` → `lib/analytics/ingest` in vulcantech-cms). Over-length\n * values are truncated and unsupported shapes are dropped — never rejected —\n * so an oversized event is stored lossily rather than failing loudly.\n *\n * `type`, `url`, `sid` and `ts` are required; an event missing any of them is\n * rejected at ingest with a 400.\n */\nexport interface AnalyticsEvent {\n /** The only two valid values. */\n type: \"pageview\" | \"event\";\n /**\n * Pageviews send `pathname + search`; custom events send `pathname` only.\n * Truncated to 2048 chars on ingest, with HTML tags stripped.\n */\n url: string;\n /**\n * `document.referrer` on pageviews, `\"\"` on custom events. Truncated to\n * 2048 chars. Together with {@link AnalyticsEvent.utm} this drives the CMS\n * traffic-source classification — so custom events carry no attribution.\n */\n ref: string;\n /** Session id from `sessionStorage` — see {@link getSessionId}. Capped at 64 chars. */\n sid: string;\n /**\n * `window.innerWidth`. Not merely diagnostic: the CMS derives the device\n * breakdown from it (<768 mobile, <1024 tablet, else desktop).\n */\n vw: number;\n /** `window.innerHeight`. */\n vh: number;\n /** `Date.now()` on the client. The CMS stores its own `serverTs` alongside it. */\n ts: number;\n /** Pageviews only, and only for UTM params actually present in the URL. */\n utm?: Record<string, string>;\n /**\n * Custom events only. Truncated to 128 chars.\n *\n * `\"tracker_test\"` is RESERVED — the CMS discards events with that name\n * (and events with url `/__analytics_test__`) so the connection self-test\n * never pollutes stats. They will never appear in the dashboard.\n */\n name?: string;\n /**\n * Custom events only. Must be FLAT primitives: nested objects and arrays\n * are dropped on ingest, so flatten before sending. At most 32 keys\n * survive; keys are truncated to 64 chars, string values to 256, and HTML\n * tags are stripped from both.\n */\n props?: Record<string, string | number | boolean>;\n}\n\n/**\n * Check if we're in a dev environment — skip all tracking if so.\n *\n * Matches `localhost`, `127.0.0.1`, `0.0.0.0`, any `*.local` host, and any\n * hostname CONTAINING \"localhost\". Tracker functions stay safe to call on\n * those hosts; they simply do nothing, so no dev-only guard is needed at the\n * call site. Test conversions against a deployed URL.\n */\nfunction isDev(): boolean {\n if (typeof window === \"undefined\") return true;\n const host = window.location.hostname;\n return (\n host === \"localhost\" ||\n host === \"127.0.0.1\" ||\n host === \"0.0.0.0\" ||\n host.endsWith(\".local\") ||\n host.includes(\"localhost\")\n );\n}\n\n/**\n * Send an analytics event via beacon (non-blocking).\n *\n * Never throws and never reports failure: send errors are swallowed, and the\n * `/api/a` proxy answers 204 even when the CMS was unreachable or rejected\n * the event. The CMS additionally drops events silently when the request is\n * bot-flagged by user agent or rate limited (100/min per `sid`, 600/min per\n * IP). Confirm ingestion in the CMS dashboard, not from the network tab.\n */\nfunction send(event: AnalyticsEvent): void {\n if (isDev()) return;\n const payload = JSON.stringify(event);\n try {\n if (navigator.sendBeacon) {\n navigator.sendBeacon(ENDPOINT, payload);\n } else {\n fetch(ENDPOINT, {\n method: \"POST\",\n body: payload,\n headers: { \"Content-Type\": \"application/json\" },\n keepalive: true,\n }).catch(() => {});\n }\n } catch {\n // Silently fail — analytics should never break the app\n }\n}\n\n/** Track a page view. */\nexport function trackPageView(): void {\n if (typeof window === \"undefined\") return;\n const utms = getUtmParams();\n send({\n type: \"pageview\",\n url: window.location.pathname + window.location.search,\n ref: document.referrer,\n sid: getSessionId(),\n vw: window.innerWidth,\n vh: window.innerHeight,\n ts: Date.now(),\n ...(Object.keys(utms).length > 0 ? { utm: utms } : {}),\n });\n}\n\n/**\n * Track a custom event.\n *\n * `props` must be FLAT primitives — nested objects and arrays are dropped by\n * the CMS on ingest, along with anything past the 32nd key. See\n * {@link AnalyticsEvent.props} for the full set of caps.\n *\n * Avoid the reserved name `\"tracker_test\"`; the CMS discards it.\n *\n * No-ops during SSR and on dev hostnames, and never throws.\n */\nexport function trackEvent(\n name: string,\n props?: Record<string, string | number | boolean>,\n): void {\n if (typeof window === \"undefined\") return;\n send({\n type: \"event\",\n url: window.location.pathname,\n ref: \"\",\n sid: getSessionId(),\n vw: window.innerWidth,\n vh: window.innerHeight,\n ts: Date.now(),\n name,\n props,\n });\n}\n\n/**\n * Track when a form comes into view.\n *\n * Usually you do NOT call this yourself: `@vulcantech/forms` finds it on\n * `window.__vtTrack` and fires it automatically for every rendered form. Only\n * call it manually for a form this package's global hook can't see.\n */\nexport function trackFormView(formId: string, formName?: string): void {\n trackEvent(\"form_view\", { formId, formName: formName ?? \"\" });\n}\n\n/**\n * Track when a form is submitted successfully.\n *\n * Like {@link trackFormView}, `@vulcantech/forms` fires this automatically via\n * `window.__vtTrack`. `submissionType` defaults to `\"contact\"`.\n */\nexport function trackFormSubmit(\n formId: string,\n formName?: string,\n submissionType?: string,\n): void {\n trackEvent(\"form_submit\", {\n formId,\n formName: formName ?? \"\",\n submissionType: submissionType ?? \"contact\",\n });\n}\n\n/**\n * Track when a phone number link is clicked.\n *\n * ⚠ Do NOT wire this into an `onClick` on an `<a href=\"tel:…\">` — importing\n * this module installs a delegated document listener that already fires it for\n * every such anchor, so adding your own handler DOUBLE-COUNTS the conversion.\n * Call it manually only for a non-anchor trigger (e.g. a button that dials via\n * JS).\n */\nexport function trackPhoneClick(phoneNumber?: string): void {\n trackEvent(\"phone_click\", { phone: phoneNumber ?? \"\" });\n}\n\n/**\n * Track when an email link is clicked.\n *\n * ⚠ Same double-count caveat as {@link trackPhoneClick}: `<a href=\"mailto:…\">`\n * clicks are already captured by the delegated listener installed on import.\n */\nexport function trackEmailClick(email?: string): void {\n trackEvent(\"email_click\", { email: email ?? \"\" });\n}\n\n/**\n * Track a 404 page.\n *\n * Client-only. Unlike the other trackers, this dereferences `window` while\n * building its argument, so calling it during SSR throws a ReferenceError —\n * call it from a client component (or an effect), or pass `url` explicitly.\n */\nexport function track404(url?: string): void {\n trackEvent(\"404\", { url: url ?? window?.location?.pathname ?? \"\" });\n}\n\n/* ------------------------------------------------------------------ */\n/* Global hook registration */\n/* ------------------------------------------------------------------ */\n\n// TWO IMPORT-TIME SIDE EFFECTS, client-only. Importing this module (which\n// AnalyticsTracker does) is enough to activate both — integrators get them\n// whether or not they ask.\n//\n// 1. `window.__vtTrack` exposes the conversion trackers so UI packages (e.g.\n// @vulcantech/forms) can report form views/submits without a hard\n// dependency on this module. Passing onFormView/onFormSubmit props to\n// DynamicForm OVERRIDES these rather than adding to them.\n//\n// 2. ONE delegated capture-phase click listener makes every\n// `a[href^=\"tel:\"]` / `a[href^=\"mailto:\"]` on the site track a phone/email\n// conversion with zero per-component wiring. Consequently, adding a manual\n// onClick tracker to such an anchor double-counts it.\nif (typeof window !== \"undefined\") {\n const w = window as unknown as Record<string, unknown>;\n w.__vtTrack = {\n trackFormView,\n trackFormSubmit,\n trackPhoneClick,\n trackEmailClick,\n };\n if (!w.__vtClickTrackingInstalled) {\n w.__vtClickTrackingInstalled = true;\n document.addEventListener(\n \"click\",\n (e) => {\n const target = e.target as Element | null;\n const link = target?.closest?.(\"a[href^='tel:'], a[href^='mailto:']\");\n if (!link) return;\n const href = link.getAttribute(\"href\") || \"\";\n if (href.startsWith(\"tel:\")) trackPhoneClick(href.slice(4));\n else trackEmailClick(href.slice(7));\n },\n true,\n );\n }\n}\n","\"use client\";\n\n/**\n * Drop-in analytics component for Next.js App Router.\n *\n * Place ONCE in your root layout — tracks page views on every route change.\n * Renders `null`, and wraps itself in Suspense to satisfy Next.js 16's\n * requirement that useSearchParams sits inside a Suspense boundary, so it is\n * safe to drop directly into a server layout despite being a client component.\n *\n * Firing rules: exactly ONE trackPageView() on mount (the isFirstRender guard\n * below stops the mount from double-firing), then one per `pathname` OR\n * `searchParams` change. Because search params are watched, `/x?page=2` counts\n * as a separate pageview from `/x`.\n *\n * Mounting this also activates the module-level side effects in `./tracker` —\n * `window.__vtTrack` (which @vulcantech/forms uses for automatic form\n * conversions) and the delegated tel:/mailto: click listener.\n *\n * Usage:\n * import { AnalyticsTracker } from \"@vulcantech/analytics\";\n * <AnalyticsTracker />\n */\n\nimport { Suspense, useEffect, useRef } from \"react\";\nimport { usePathname, useSearchParams } from \"next/navigation\";\nimport { trackPageView } from \"./tracker\";\n\nfunction AnalyticsTrackerInner() {\n const pathname = usePathname();\n const searchParams = useSearchParams();\n const isFirstRender = useRef(true);\n\n useEffect(() => {\n if (isFirstRender.current) {\n isFirstRender.current = false;\n return;\n }\n trackPageView();\n }, [pathname, searchParams]);\n\n useEffect(() => {\n trackPageView();\n }, []);\n\n return null;\n}\n\nexport function AnalyticsTracker() {\n return (\n <Suspense fallback={null}>\n <AnalyticsTrackerInner />\n </Suspense>\n );\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/tracker.ts","../src/AnalyticsTracker.tsx","../src/PhoneLink.tsx"],"names":["usePathname","useSearchParams","useRef","useEffect","Suspense","jsx","useSyncExternalStore"],"mappings":";;;;;;;AAQA,IAAM,QAAA,GAAW,QAAA;AACjB,IAAM,WAAA,GAAc,UAAA;AAWpB,SAAS,YAAA,GAAuB;AAC9B,EAAA,IAAI,OAAO,MAAA,KAAW,WAAA,EAAa,OAAO,EAAA;AAC1C,EAAA,IAAI;AACF,IAAA,IAAI,GAAA,GAAM,cAAA,CAAe,OAAA,CAAQ,WAAW,CAAA;AAC5C,IAAA,IAAI,CAAC,GAAA,EAAK;AACR,MAAA,GAAA,GAAM,IAAA,CAAK,MAAA,EAAO,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,KAAA,CAAM,CAAC,CAAA,GAAI,IAAA,CAAK,G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,CAAQ,MAAA,GAAS,GAAA;AAClD,EAAA,uCACG,GAAA,EAAA,EAAG,GAAG,MAAM,IAAA,EAAM,CAAA,IAAA,EAAO,MAAM,CAAA,CAAA,EAC7B,QAAA,EAAA;AAAA,IAAA,MAAA;AAAA,IACA,SAAS,SAAA,IAAa,OAAA;AAAA,IACtB;AAAA,GAAA,EACH,CAAA;AAEJ","file":"index.js","sourcesContent":["/**\n * VulcanTech Analytics — lightweight first-party tracker.\n *\n * < 1KB gzipped. No cookies, no fingerprinting, no DOM manipulation.\n * Sends page views and custom events to /api/a on the same domain\n * via navigator.sendBeacon (falls back to fetch).\n */\n\nconst ENDPOINT = \"/api/a\";\nconst SESSION_KEY = \"__vt_sid\";\n\n/**\n * Generate a random session ID (stored in sessionStorage, not cookies).\n *\n * No cookies means nothing survives a tab close, and there is no cross-tab or\n * cross-visit identity by design. When `sessionStorage` throws (private mode,\n * blocked storage) this returns a FRESH id per call, so each event from that\n * visitor counts as its own session — inflating session counts rather than\n * failing.\n */\nfunction getSessionId(): string {\n if (typeof window === \"undefined\") return \"\";\n try {\n let sid = sessionStorage.getItem(SESSION_KEY);\n if (!sid) {\n sid = Math.random().toString(36).slice(2) + Date.now().toString(36);\n sessionStorage.setItem(SESSION_KEY, sid);\n }\n return sid;\n } catch {\n return Math.random().toString(36).slice(2);\n }\n}\n\n/**\n * Ad-referral cookie written by `@vulcantech/forms`' `AdReferralTracker`.\n *\n * Read by NAME rather than by importing that package: this tracker's whole\n * selling point is that it pulls in nothing, and importing the forms entry\n * point would drag formik, yup and Radix into every page. The cookie name and\n * its JSON shape are the contract — keep them in step with\n * `packages/forms/src/tracking/adReferral.ts`.\n */\nconst AD_REFERRAL_COOKIE = \"vt_ad_ref\";\n\n/**\n * Campaign context for the visit, as UTM keys, or null when this visitor\n * never arrived on a tagged ad click (or the site mounts no AdReferralTracker).\n *\n * `source`/`medium` drive the CMS source classification; `campaign` feeds its\n * per-campaign conversion rollup. The cookie's `\"(not set)\"` placeholder (an\n * auto-tagged click with no utm_campaign) is dropped so the CMS can name it\n * itself. Term, content, click id and landing data stay in the cookie — the\n * lead carries those.\n */\nfunction getAdReferralUtm(): Record<string, string> | null {\n if (typeof document === \"undefined\") return null;\n for (const cookie of document.cookie.split(\";\")) {\n const sep = cookie.indexOf(\"=\");\n if (sep === -1) continue;\n if (cookie.slice(0, sep).trim() !== AD_REFERRAL_COOKIE) continue;\n try {\n const parsed = JSON.parse(decodeURIComponent(cookie.slice(sep + 1)));\n if (!parsed || typeof parsed !== \"object\") return null;\n const utm: Record<string, string> = {};\n if (typeof parsed.source === \"string\" && parsed.source) {\n utm.utm_source = parsed.source;\n }\n if (typeof parsed.medium === \"string\" && parsed.medium) {\n utm.utm_medium = parsed.medium;\n }\n if (\n Object.keys(utm).length > 0 &&\n typeof parsed.campaign === \"string\" &&\n parsed.campaign &&\n parsed.campaign !== \"(not set)\"\n ) {\n utm.utm_campaign = parsed.campaign;\n }\n return Object.keys(utm).length > 0 ? utm : null;\n } catch {\n return null;\n }\n }\n return null;\n}\n\n/**\n * Extract campaign params from the current URL.\n *\n * Click ids are read alongside the UTMs because Google Ads auto-tagging is on\n * by default and adds NO utm_* params — without them an auto-tagged pageview\n * would carry no structured campaign data at all, and the CMS would classify\n * it by its google.com referrer as organic. `gad_source`/`gad_campaignid` are\n * read too: Safari's tracking protection strips `gclid` but leaves them.\n */\nfunction getUtmParams(): Record<string, string> {\n if (typeof window === \"undefined\") return {};\n const params = new URLSearchParams(window.location.search);\n const utms: Record<string, string> = {};\n for (const key of [\n \"utm_source\",\n \"utm_medium\",\n \"utm_campaign\",\n \"utm_term\",\n \"utm_content\",\n \"gclid\",\n \"gbraid\",\n \"wbraid\",\n \"gad_source\",\n \"gad_campaignid\",\n \"fbclid\",\n \"msclkid\",\n ]) {\n const val = params.get(key);\n if (val) utms[key] = val;\n }\n return utms;\n}\n\nconst SESSION_CAMPAIGN_KEY = \"__vt_utm\";\n\n/** A session's campaign goes stale after this long with no pageview (GA's default). */\nconst SESSION_CAMPAIGN_IDLE_MS = 30 * 60 * 1000;\n\n/**\n * The campaign params this tab session landed with, or null.\n *\n * Only the LANDING URL carries `gclid`/`utm_*`; the next page's URL is clean\n * while `document.referrer` still says google.com, so without this every\n * pageview after an ad landing classified as organic search. Kept in\n * `sessionStorage` (no cookies, gone with the tab) and dropped after 30\n * minutes idle, so a later organic return in the same tab isn't credited to\n * the ad. Never throws.\n */\nfunction getSessionCampaign(): Record<string, string> | null {\n try {\n const raw = sessionStorage.getItem(SESSION_CAMPAIGN_KEY);\n if (!raw) return null;\n const parsed = JSON.parse(raw);\n if (\n !parsed ||\n typeof parsed.at !== \"number\" ||\n Date.now() - parsed.at > SESSION_CAMPAIGN_IDLE_MS ||\n !parsed.utm ||\n typeof parsed.utm !== \"object\"\n ) {\n sessionStorage.removeItem(SESSION_CAMPAIGN_KEY);\n return null;\n }\n const utm: Record<string, string> = {};\n for (const [k, v] of Object.entries(parsed.utm)) {\n if (typeof v === \"string\" && v) utm[k] = v;\n }\n return Object.keys(utm).length > 0 ? utm : null;\n } catch {\n return null;\n }\n}\n\n/** Store (or refresh the idle clock on) this session's campaign. Never throws. */\nfunction setSessionCampaign(utm: Record<string, string>): void {\n try {\n sessionStorage.setItem(\n SESSION_CAMPAIGN_KEY,\n JSON.stringify({ utm, at: Date.now() }),\n );\n } catch {\n // Storage blocked — later pageviews fall back to referrer classification.\n }\n}\n\n/**\n * One analytics event as sent to `/api/a` and forwarded to the CMS.\n *\n * The limits noted per field are enforced SERVER-SIDE on ingest\n * (`/api/analytics` → `lib/analytics/ingest` in vulcantech-cms). Over-length\n * values are truncated and unsupported shapes are dropped — never rejected —\n * so an oversized event is stored lossily rather than failing loudly.\n *\n * `type`, `url`, `sid` and `ts` are required; an event missing any of them is\n * rejected at ingest with a 400.\n */\nexport interface AnalyticsEvent {\n /** The only two valid values. */\n type: \"pageview\" | \"event\";\n /**\n * Pageviews send `pathname + search`; custom events send `pathname` only.\n * Truncated to 2048 chars on ingest, with HTML tags stripped.\n */\n url: string;\n /**\n * `document.referrer` on pageviews, `\"\"` on custom events. Truncated to\n * 2048 chars. Together with {@link AnalyticsEvent.utm} this drives the CMS\n * traffic-source classification; custom events have no referrer, so their\n * attribution rides entirely on {@link AnalyticsEvent.utm}.\n */\n ref: string;\n /** Session id from `sessionStorage` — see {@link getSessionId}. Capped at 64 chars. */\n sid: string;\n /**\n * `window.innerWidth`. Not merely diagnostic: the CMS derives the device\n * breakdown from it (<768 mobile, <1024 tablet, else desktop).\n */\n vw: number;\n /** `window.innerHeight`. */\n vh: number;\n /** `Date.now()` on the client. The CMS stores its own `serverTs` alongside it. */\n ts: number;\n /**\n * Campaign context. On pageviews: the `utm_*` params and click ids present\n * in the URL, or — on later pages of the same visit — the ones the visit\n * landed with (see {@link getSessionCampaign}). The CMS tells a landing from\n * a later page by whether `url` itself carries them. On custom events:\n * `utm_source`/`utm_medium`/`utm_campaign` from the 30-day ad-referral\n * cookie, else the session's landing params.\n */\n utm?: Record<string, string>;\n /**\n * Custom events only. Truncated to 128 chars.\n *\n * `\"tracker_test\"` is RESERVED — the CMS discards events with that name\n * (and events with url `/__analytics_test__`) so the connection self-test\n * never pollutes stats. They will never appear in the dashboard.\n */\n name?: string;\n /**\n * Custom events only. Must be FLAT primitives: nested objects and arrays\n * are dropped on ingest, so flatten before sending. At most 32 keys\n * survive; keys are truncated to 64 chars, string values to 256, and HTML\n * tags are stripped from both.\n */\n props?: Record<string, string | number | boolean>;\n}\n\n/**\n * Check if we're in a dev environment — skip all tracking if so.\n *\n * Matches `localhost`, `127.0.0.1`, `0.0.0.0`, any `*.local` host, and any\n * hostname CONTAINING \"localhost\". Tracker functions stay safe to call on\n * those hosts; they simply do nothing, so no dev-only guard is needed at the\n * call site. Test conversions against a deployed URL.\n */\nfunction isDev(): boolean {\n if (typeof window === \"undefined\") return true;\n const host = window.location.hostname;\n return (\n host === \"localhost\" ||\n host === \"127.0.0.1\" ||\n host === \"0.0.0.0\" ||\n host.endsWith(\".local\") ||\n host.includes(\"localhost\")\n );\n}\n\n/**\n * Send an analytics event via beacon (non-blocking).\n *\n * Never throws and never reports failure: send errors are swallowed, and the\n * `/api/a` proxy answers 204 even when the CMS was unreachable or rejected\n * the event. The CMS additionally drops events silently when the request is\n * bot-flagged by user agent or rate limited (100/min per `sid`, 600/min per\n * IP). Confirm ingestion in the CMS dashboard, not from the network tab.\n */\nfunction send(event: AnalyticsEvent): void {\n if (isDev()) return;\n const payload = JSON.stringify(event);\n try {\n if (navigator.sendBeacon) {\n navigator.sendBeacon(ENDPOINT, payload);\n } else {\n fetch(ENDPOINT, {\n method: \"POST\",\n body: payload,\n headers: { \"Content-Type\": \"application/json\" },\n keepalive: true,\n }).catch(() => {});\n }\n } catch {\n // Silently fail — analytics should never break the app\n }\n}\n\n/** Track a page view. */\nexport function trackPageView(): void {\n if (typeof window === \"undefined\") return;\n let utms = getUtmParams();\n if (Object.keys(utms).length > 0) {\n setSessionCampaign(utms);\n } else {\n const session = getSessionCampaign();\n if (session) {\n utms = session;\n setSessionCampaign(session);\n }\n }\n send({\n type: \"pageview\",\n url: window.location.pathname + window.location.search,\n ref: document.referrer,\n sid: getSessionId(),\n vw: window.innerWidth,\n vh: window.innerHeight,\n ts: Date.now(),\n ...(Object.keys(utms).length > 0 ? { utm: utms } : {}),\n });\n}\n\n/**\n * Track a custom event.\n *\n * `props` must be FLAT primitives — nested objects and arrays are dropped by\n * the CMS on ingest, along with anything past the 32nd key. See\n * {@link AnalyticsEvent.props} for the full set of caps.\n *\n * Avoid the reserved name `\"tracker_test\"`; the CMS discards it.\n *\n * No-ops during SSR and on dev hostnames, and never throws.\n */\nexport function trackEvent(\n name: string,\n props?: Record<string, string | number | boolean>,\n): void {\n if (typeof window === \"undefined\") return;\n\n // Carry the visit's campaign context onto the conversion.\n //\n // Custom events send no referrer (there isn't one — the visitor is already\n // on the site), and the CMS derives traffic source from referrer + utm. So\n // without this EVERY conversion classified as \"direct\", which both lost the\n // attribution and inflated the direct bucket in the source breakdown by one\n // per phone tap, mail click and form submit. The 30-day cookie wins (it\n // credits a conversion days after the ad click); the session's landing\n // params cover sites that mount no AdReferralTracker.\n const utm = getAdReferralUtm() ?? getSessionCampaign();\n\n send({\n type: \"event\",\n url: window.location.pathname,\n ref: \"\",\n sid: getSessionId(),\n vw: window.innerWidth,\n vh: window.innerHeight,\n ts: Date.now(),\n ...(utm ? { utm } : {}),\n name,\n props,\n });\n}\n\n/**\n * Track when a form comes into view.\n *\n * Usually you do NOT call this yourself: `@vulcantech/forms` finds it on\n * `window.__vtTrack` and fires it automatically for every rendered form. Only\n * call it manually for a form this package's global hook can't see.\n */\nexport function trackFormView(formId: string, formName?: string): void {\n trackEvent(\"form_view\", { formId, formName: formName ?? \"\" });\n}\n\n/**\n * Track when a form is submitted successfully.\n *\n * Like {@link trackFormView}, `@vulcantech/forms` fires this automatically via\n * `window.__vtTrack`. `submissionType` defaults to `\"contact\"`.\n */\nexport function trackFormSubmit(\n formId: string,\n formName?: string,\n submissionType?: string,\n): void {\n trackEvent(\"form_submit\", {\n formId,\n formName: formName ?? \"\",\n submissionType: submissionType ?? \"contact\",\n });\n}\n\n/**\n * Track when a phone number link is clicked.\n *\n * ⚠ Do NOT wire this into an `onClick` on an `<a href=\"tel:…\">` — importing\n * this module installs a delegated document listener that already fires it for\n * every such anchor, so adding your own handler DOUBLE-COUNTS the conversion.\n * Call it manually only for a non-anchor trigger (e.g. a button that dials via\n * JS).\n */\nexport function trackPhoneClick(phoneNumber?: string): void {\n trackEvent(\"phone_click\", { phone: phoneNumber ?? \"\" });\n sendGooglePhoneClick(phoneNumber ?? \"\");\n}\n\n/**\n * Mirror a phone tap to Google: a GA4 `phone_click` event and, when `CMSTags`\n * published a `phoneConversionSendTo` label, a Google Ads conversion. No-op\n * without `gtag`; never throws.\n */\nfunction sendGooglePhoneClick(phoneNumber: string): void {\n if (typeof window === \"undefined\") return;\n const w = window as unknown as {\n gtag?: (...args: unknown[]) => void;\n __vtPhoneConversionSendTo?: unknown;\n };\n if (typeof w.gtag !== \"function\") return;\n try {\n const sendTo = w.__vtPhoneConversionSendTo;\n if (typeof sendTo === \"string\" && sendTo.trim() !== \"\") {\n w.gtag(\"event\", \"conversion\", { send_to: sendTo.trim() });\n }\n w.gtag(\"event\", \"phone_click\", { link_url: `tel:${phoneNumber}` });\n } catch {\n // Analytics must never break a tap.\n }\n}\n\n/** sessionStorage key marking that this session already sent `phone_swap`. */\nconst PHONE_SWAP_SENT_KEY = \"vt_phone_swap_sent\";\n\n/**\n * Record that Google's forwarding-number swap showed this visitor a call\n * tracking number — i.e. an ad visitor was eligible to place a tracked call.\n *\n * Fired automatically (see the registration block below) when `CMSTags`'\n * swap callback dispatches `vt-phone`; once per session, since gtag runs the\n * callback on every full page load. The calls themselves never reach us —\n * they go Google → shop — so this is the first-party half of call tracking.\n *\n * @param formatted The forwarding number as Google formatted it.\n */\nexport function trackPhoneSwap(formatted?: string): void {\n if (typeof window === \"undefined\") return;\n try {\n if (window.sessionStorage.getItem(PHONE_SWAP_SENT_KEY)) return;\n window.sessionStorage.setItem(PHONE_SWAP_SENT_KEY, \"1\");\n } catch {\n // Storage blocked (private mode): send anyway — an occasional duplicate\n // beats never counting the swap.\n }\n trackEvent(\"phone_swap\", { phone: formatted ?? \"\" });\n}\n\n/**\n * Track when an email link is clicked.\n *\n * ⚠ Same double-count caveat as {@link trackPhoneClick}: `<a href=\"mailto:…\">`\n * clicks are already captured by the delegated listener installed on import.\n */\nexport function trackEmailClick(email?: string): void {\n trackEvent(\"email_click\", { email: email ?? \"\" });\n}\n\n/**\n * Track a 404 page.\n *\n * `url` defaults to the current pathname. No-ops during SSR and on dev\n * hostnames, and never throws — like every other tracker in this module.\n *\n * @param url Optional path to report instead of the current pathname.\n */\nexport function track404(url?: string): void {\n const path =\n url ?? (typeof window === \"undefined\" ? \"\" : window.location.pathname);\n trackEvent(\"404\", { url: path });\n}\n\n/* ------------------------------------------------------------------ */\n/* Global hook registration */\n/* ------------------------------------------------------------------ */\n\n// THREE IMPORT-TIME SIDE EFFECTS, client-only. Importing this module (which\n// AnalyticsTracker does) is enough to activate all three — integrators get them\n// whether or not they ask.\n//\n// 1. `window.__vtTrack` exposes the conversion trackers so UI packages (e.g.\n// @vulcantech/forms) can report form views/submits without a hard\n// dependency on this module. Passing onFormView/onFormSubmit props to\n// DynamicForm OVERRIDES these rather than adding to them.\n//\n// 2. ONE delegated capture-phase click listener makes every\n// `a[href^=\"tel:\"]` / `a[href^=\"mailto:\"]` on the site track a phone/email\n// conversion with zero per-component wiring. Consequently, adding a manual\n// onClick tracker to such an anchor double-counts it.\nif (typeof window !== \"undefined\") {\n const w = window as unknown as Record<string, unknown>;\n w.__vtTrack = {\n trackFormView,\n trackFormSubmit,\n trackPhoneClick,\n trackEmailClick,\n };\n // 3. Google's number swap (CMSTags) stores the forwarding number on\n // `window.__vtPhone` and fires `vt-phone`. The callback can land before\n // this module loads, so check for an already-stored number too.\n if (!w.__vtPhoneSwapListenerInstalled) {\n w.__vtPhoneSwapListenerInstalled = true;\n const sendSwap = () => {\n const swapped = w.__vtPhone as { formatted?: string } | undefined;\n if (swapped) trackPhoneSwap(swapped.formatted);\n };\n window.addEventListener(\"vt-phone\", sendSwap);\n if (w.__vtPhone) sendSwap();\n }\n if (!w.__vtClickTrackingInstalled) {\n w.__vtClickTrackingInstalled = true;\n document.addEventListener(\n \"click\",\n (e) => {\n const target = e.target as Element | null;\n const link = target?.closest?.(\"a[href^='tel:'], a[href^='mailto:']\");\n if (!link) return;\n const href = link.getAttribute(\"href\") || \"\";\n if (href.startsWith(\"tel:\")) trackPhoneClick(href.slice(4));\n else trackEmailClick(href.slice(7));\n },\n true,\n );\n }\n}\n","\"use client\";\n\n/**\n * Drop-in analytics component for Next.js App Router.\n *\n * Place ONCE in your root layout — tracks page views on every route change.\n * Renders `null`, and wraps itself in Suspense to satisfy Next.js 16's\n * requirement that useSearchParams sits inside a Suspense boundary, so it is\n * safe to drop directly into a server layout despite being a client component.\n *\n * Firing rules: exactly ONE trackPageView() on mount (the isFirstRender guard\n * below stops the mount from double-firing), then one per `pathname` OR\n * `searchParams` change. Because search params are watched, `/x?page=2` counts\n * as a separate pageview from `/x`.\n *\n * Mounting this also activates the module-level side effects in `./tracker` —\n * `window.__vtTrack` (which @vulcantech/forms uses for automatic form\n * conversions) and the delegated tel:/mailto: click listener.\n *\n * Usage:\n * import { AnalyticsTracker } from \"@vulcantech/analytics\";\n * <AnalyticsTracker />\n */\n\nimport { Suspense, useEffect, useRef } from \"react\";\nimport { usePathname, useSearchParams } from \"next/navigation\";\nimport { trackPageView } from \"./tracker\";\n\nfunction AnalyticsTrackerInner() {\n const pathname = usePathname();\n const searchParams = useSearchParams();\n const isFirstRender = useRef(true);\n\n useEffect(() => {\n if (isFirstRender.current) {\n isFirstRender.current = false;\n return;\n }\n trackPageView();\n }, [pathname, searchParams]);\n\n useEffect(() => {\n trackPageView();\n }, []);\n\n return null;\n}\n\nexport function AnalyticsTracker() {\n return (\n <Suspense fallback={null}>\n <AnalyticsTrackerInner />\n </Suspense>\n );\n}\n","\"use client\";\n\nimport { useSyncExternalStore, type AnchorHTMLAttributes, type ReactNode } from \"react\";\n\n/** The number Google's forwarding-number swap hands back, if any. */\ninterface SwappedPhone {\n formatted: string;\n mobile: string;\n}\n\ntype PhoneWindow = Window & { __vtPhone?: SwappedPhone };\n\nfunction subscribe(onChange: () => void): () => void {\n window.addEventListener(\"vt-phone\", onChange);\n return () => window.removeEventListener(\"vt-phone\", onChange);\n}\n\nfunction getSnapshot(): SwappedPhone | null {\n return (window as PhoneWindow).__vtPhone ?? null;\n}\n\n/** The server always renders the real number. */\nfunction getServerSnapshot(): SwappedPhone | null {\n return null;\n}\n\nexport interface PhoneLinkProps\n extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, \"href\" | \"children\" | \"prefix\"> {\n /** The number as displayed, e.g. `\"602.904.9109\"`. */\n display: string;\n /** E.164 dial string without `tel:`, e.g. `\"+16029049109\"`. */\n tel: string;\n /** Rendered before the number, e.g. `\"Or call · \"` or an icon. */\n prefix?: ReactNode;\n /** Rendered after the number. */\n suffix?: ReactNode;\n}\n\n/**\n * A `tel:` link that shows Google's forwarding number to visitors who arrived\n * from an ad.\n *\n * `CMSTags` configures Google's number swap (when the project has a\n * `callConversionSendTo` + `callConversionNumber`) with a callback that stores\n * the forwarding number on `window.__vtPhone` and fires `vt-phone`; this\n * component re-renders on that event. Doing it in React rather than letting\n * gtag rewrite the DOM matters: React would put the original number back on\n * the next render or client-side navigation.\n *\n * Everyone else — and the server render — sees `display` / `tel`. Taps are\n * tracked by the delegated listener `AnalyticsTracker` installs; don't add an\n * `onClick` tracker here or the tap double-counts.\n *\n * @param props.display Number as shown on the page (must match `callConversionNumber`).\n * @param props.tel E.164 dial string, without the `tel:` scheme.\n * @param props.prefix Optional content before the number.\n * @param props.suffix Optional content after the number.\n */\nexport function PhoneLink({ display, tel, prefix, suffix, ...rest }: PhoneLinkProps) {\n const swapped = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\n const mobile = swapped?.mobile ? swapped.mobile : tel;\n return (\n <a {...rest} href={`tel:${mobile}`}>\n {prefix}\n {swapped?.formatted || display}\n {suffix}\n </a>\n );\n}\n"]}
|