@wealthreach/site-kit 1.0.2 → 1.1.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.
@@ -14,6 +14,20 @@ interface SkipLinkProps {
14
14
  */
15
15
  declare function SkipLink({ targetId, label, className, }: SkipLinkProps): React.JSX.Element;
16
16
 
17
+ interface BotIdProtectedRoute {
18
+ path: string;
19
+ method: string;
20
+ advancedOptions?: {
21
+ checkLevel?: "basic" | "deepAnalysis";
22
+ };
23
+ }
24
+ declare const DEFAULT_BOTID_PROTECTED_ROUTES: BotIdProtectedRoute[];
25
+ interface SiteShellBotIdConfig {
26
+ /** Override protected mutating routes (defaults to `[{ path: "/api/leads", method: "POST" }]`). Never protect `GET` pages so AI crawlers & AEO stay untouched. */
27
+ protect?: BotIdProtectedRoute[];
28
+ /** Render BotIdClient even outside Vercel (primarily for tests). */
29
+ force?: boolean;
30
+ }
17
31
  interface SiteShellProps {
18
32
  config: SiteConfig;
19
33
  header?: React.ReactNode;
@@ -24,6 +38,8 @@ interface SiteShellProps {
24
38
  analytics?: React.ReactNode;
25
39
  /** Extra elements to render inside `<head>` (fonts, custom preconnects, etc.). */
26
40
  head?: React.ReactNode;
41
+ /** Invisible Vercel BotID protection scoped strictly to mutating form routes (`POST /api/leads` by default). Active automatically on Vercel deployments; dormant on `GET` pages and local/sandbox builds. Set `false` to disable. */
42
+ botId?: boolean | SiteShellBotIdConfig;
27
43
  htmlClassName?: string;
28
44
  bodyClassName?: string;
29
45
  mainClassName?: string;
@@ -31,13 +47,26 @@ interface SiteShellProps {
31
47
  privacyModeEndpoint?: string;
32
48
  children: React.ReactNode;
33
49
  }
50
+ declare function resolveBotIdRoutes(botId: SiteShellProps["botId"]): BotIdProtectedRoute[];
51
+ /**
52
+ * Captures the native `window.fetch` before `<BotIdClient>` wraps it so
53
+ * `buildBotIdPostScript` can detect when BotID's challenge succeeded vs failed
54
+ * or timed out — without ever double-posting or bypassing a real `403` verdict.
55
+ */
56
+ declare function buildBotIdPreScript(): string;
57
+ /**
58
+ * Bounds BotID challenge loading (4s) and resets stuck failed `<script>` tags
59
+ * on challenge load errors so a blocked/unavailable challenge script never
60
+ * hangs same-page retries and always lets the server policy decide.
61
+ */
62
+ declare function buildBotIdPostScript(routes: BotIdProtectedRoute[], challengeTimeoutMs?: number): string;
34
63
  /**
35
64
  * Invisible compliance, consent, accessibility, and SEO root shell.
36
65
  *
37
66
  * HARD STATIC-SSG INVARIANT: SiteShell NEVER calls `cookies()` or `headers()`
38
67
  * from `next/headers`, keeping every page 100% statically cacheable on Vercel CDN.
39
68
  */
40
- declare function SiteShell({ config, header, footer, consentBanner, analytics, head, htmlClassName, bodyClassName, mainClassName, privacyModeEndpoint, children, }: SiteShellProps): React.JSX.Element;
69
+ declare function SiteShell({ config, header, footer, consentBanner, analytics, head, botId, htmlClassName, bodyClassName, mainClassName, privacyModeEndpoint, children, }: SiteShellProps): React.JSX.Element;
41
70
 
42
- export { SiteShell, SkipLink };
43
- export type { SiteShellProps, SkipLinkProps };
71
+ export { DEFAULT_BOTID_PROTECTED_ROUTES, SiteShell, SkipLink, buildBotIdPostScript, buildBotIdPreScript, resolveBotIdRoutes };
72
+ export type { BotIdProtectedRoute, SiteShellBotIdConfig, SiteShellProps, SkipLinkProps };
@@ -53,6 +53,9 @@ function SkipLink({
53
53
  ] });
54
54
  }
55
55
 
56
+ // src/a11y/site-shell.tsx
57
+ import { BotIdClient } from "botid/client";
58
+
56
59
  // src/config/metadata.ts
57
60
  function buildOrganizationJsonLd(config) {
58
61
  const org = config.jsonLd?.organization;
@@ -79,10 +82,13 @@ var MODE_MAX_AGE = 60 * 60 * 24;
79
82
  var VISITOR_SCRIPT_ID = "wr-site-script";
80
83
  var GTM_SCRIPT_ID = "wr-gtm-script";
81
84
  var GA4_SCRIPT_ID = "wr-ga4-script";
85
+ function legacyConsentStorageKey(siteId) {
86
+ return `wr:consent:${siteId?.trim() || "site"}`;
87
+ }
82
88
 
83
89
  // src/consent/bootstrap.ts
84
90
  function safeJson(value) {
85
- return JSON.stringify(value).replace(/</g, "\\u003c");
91
+ return JSON.stringify(value).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
86
92
  }
87
93
  var GTM_ID_RE = /^GTM-[A-Z0-9]{4,16}$/;
88
94
  var GA4_ID_RE = /^G-[A-Z0-9]{4,16}$/;
@@ -116,6 +122,7 @@ function buildConsentBootstrapScript(options) {
116
122
  const ga4Id = sanitizeGa4Id(options.ga4MeasurementId);
117
123
  if (!visitorUrl && !gtmId && !ga4Id) return null;
118
124
  const legacy = options.legacyConsentCookies ?? [];
125
+ const legacyStorageCheck = options.siteId !== void 0 ? `if(!c){try{if(window.localStorage.getItem(${safeJson(legacyConsentStorageKey(options.siteId))})==='declined')c='analytics:no';}catch(e){}}` : "";
119
126
  const loaders = [];
120
127
  if (visitorUrl) {
121
128
  loaders.push(
@@ -132,12 +139,50 @@ function buildConsentBootstrapScript(options) {
132
139
  `if(!document.getElementById('${GA4_SCRIPT_ID}')){window.dataLayer=window.dataLayer||[];function gtag(){window.dataLayer.push(arguments);}window.gtag=window.gtag||gtag;gtag('js',new Date());gtag('config',${safeJson(ga4Id)});var a=document.createElement('script');a.id='${GA4_SCRIPT_ID}';a.async=true;a.src=${safeJson(`https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(ga4Id)}`)};a.setAttribute('data-consent-category','analytics');document.head.appendChild(a);}`
133
140
  );
134
141
  }
135
- return `(function(){try{var g=function(n){var p=document.cookie.split('; ').find(function(v){return v.indexOf(n+'=')===0});return p?decodeURIComponent(p.slice(n.length+1)):null};var c=g('${CONSENT_COOKIE}');if(!c){var leg=${safeJson(legacy)};for(var i=0;i<leg.length;i++){var lv=g(leg[i]);if(lv){c=lv.indexOf('analytics:yes')>-1?'analytics:yes':lv.indexOf('analytics:no')>-1?'analytics:no':null;if(c)break;}}}if(c==='analytics:no')return;var gpc=navigator.globalPrivacyControl===true;if(c!=='analytics:yes'&&!(g('${MODE_COOKIE}')==='opt-out'&&!gpc))return;${loaders.join("")}}catch(e){}})();`;
142
+ return `(function(){try{var g=function(n){var p=document.cookie.split('; ').find(function(v){return v.indexOf(n+'=')===0});return p?decodeURIComponent(p.slice(n.length+1)):null};var c=g('${CONSENT_COOKIE}');if(!c){var leg=${safeJson(legacy)};for(var i=0;i<leg.length;i++){var lv=g(leg[i]);if(lv){c=lv.indexOf('analytics:yes')>-1?'analytics:yes':lv.indexOf('analytics:no')>-1?'analytics:no':null;if(c)break;}}}${legacyStorageCheck}if(c==='analytics:no')return;var gpc=navigator.globalPrivacyControl===true;if(c!=='analytics:yes'&&!(g('${MODE_COOKIE}')==='opt-out'&&!gpc))return;${loaders.join("")}}catch(e){}})();`;
136
143
  }
137
144
 
138
145
  // src/a11y/site-shell.tsx
139
146
  import { SiteShellClient } from "./shell-client.js";
140
- import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
147
+ import { Fragment as Fragment2, jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
148
+ var DEFAULT_BOTID_PROTECTED_ROUTES = [
149
+ { path: "/api/leads", method: "POST" }
150
+ ];
151
+ function shouldMountBotId(botId) {
152
+ if (botId === false) return false;
153
+ if (typeof botId === "object" && botId.force) return true;
154
+ if (process.env.WR_SANDBOX === "1" || process.env.WR_SYNTHETIC_LEADS === "1") {
155
+ return false;
156
+ }
157
+ return process.env.VERCEL === "1" || process.env.WR_ENABLE_BOTID === "1";
158
+ }
159
+ function safeInlineJson(value) {
160
+ return JSON.stringify(value).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
161
+ }
162
+ function resolveBotIdRoutes(botId) {
163
+ const configured = typeof botId === "object" && botId.protect && botId.protect.length > 0 ? botId.protect.filter(
164
+ (route) => typeof route.path === "string" && route.path.startsWith("/") && !/[<>]/.test(route.path) && typeof route.method === "string" && /^(?:POST|PUT|PATCH|DELETE)$/i.test(route.method)
165
+ ) : DEFAULT_BOTID_PROTECTED_ROUTES;
166
+ const routes = configured.length > 0 ? configured : DEFAULT_BOTID_PROTECTED_ROUTES;
167
+ const envLevel = process.env.WR_BOTID_CHECK_LEVEL?.trim();
168
+ if (envLevel === "basic" || envLevel === "deepAnalysis") {
169
+ return routes.map((route) => ({
170
+ ...route,
171
+ advancedOptions: {
172
+ checkLevel: envLevel,
173
+ ...route.advancedOptions
174
+ }
175
+ }));
176
+ }
177
+ return routes;
178
+ }
179
+ function buildBotIdPreScript() {
180
+ return `(function(){if(window.__wrBotId)return;var raw=window.fetch.bind(window);var active=new Map();window.__wrBotId={raw:raw,active:active,seq:0,wrapped:false};window.fetch=function(input,init){var id=null;if(init&&init.headers&&typeof init.headers.get==='function'){id=init.headers.get('x-wr-botid-req');if(id)init.headers.delete('x-wr-botid-req');}if(id&&active.has(id)){var st=active.get(id);active.delete(id);clearTimeout(st.timer);if(st.timedOut)return st.fallbackPromise;st.dispatched=true;}return raw(input,init);};})();`;
181
+ }
182
+ function buildBotIdPostScript(routes, challengeTimeoutMs = 4e3) {
183
+ const timeout = Math.max(100, Math.round(challengeTimeoutMs));
184
+ return `(function(){var rt=window.__wrBotId;if(!rt||rt.wrapped)return;rt.wrapped=true;var botFetch=window.fetch;var routes=${safeInlineJson(routes)};function match(url,method){if(url.origin!==location.origin)return false;for(var k=0;k<routes.length;k++){var r=routes[k];if(r.method.toLowerCase()!==method.toLowerCase())continue;var re=new RegExp('^'+r.path.replace(/[.?+^$[\\]\\\\(){}|-]/g,'\\\\$&').split('*').join('.*')+'$');if(re.test(url.pathname))return true;}return false;}function resetBotId(){try{document.querySelectorAll('script[src*="149e9513-01fa-4fb0-aad4-566afd725d1b"]').forEach(function(el){el.remove();});window.dispatchEvent(new Event('online'));}catch(e){}}window.fetch=function(input,init){var url,method;try{url=new URL(input instanceof Request?input.url:input,location.href);method=(init&&init.method)||(input instanceof Request?input.method:'GET');}catch(e){return botFetch(input,init);}if(!match(url,method))return botFetch(input,init);var hdrs=new Headers((init&&init.headers)||(input instanceof Request?input.headers:undefined));if(hdrs.has('x-wr-botid-req'))return botFetch(input,init);var id=String(++rt.seq);hdrs.set('x-wr-botid-req',id);var taggedInit=Object.assign({},init,{headers:hdrs});return new Promise(function(resolve,reject){var st={timedOut:false,dispatched:false,timer:0,fallbackPromise:null};function fallback(){if(st.dispatched||st.timedOut)return;st.timedOut=true;clearTimeout(st.timer);resetBotId();st.fallbackPromise=rt.raw(input,init);st.fallbackPromise.then(resolve,reject);}st.timer=setTimeout(fallback,${timeout});rt.active.set(id,st);Promise.resolve().then(function(){return botFetch(input,taggedInit);}).then(function(res){clearTimeout(st.timer);rt.active.delete(id);if(!st.timedOut)resolve(res);},function(err){clearTimeout(st.timer);rt.active.delete(id);if(st.dispatched){if(!st.timedOut)reject(err);}else{fallback();}});});};})();`;
185
+ }
141
186
  function SiteShell({
142
187
  config,
143
188
  header,
@@ -145,6 +190,7 @@ function SiteShell({
145
190
  consentBanner,
146
191
  analytics,
147
192
  head,
193
+ botId = true,
148
194
  htmlClassName,
149
195
  bodyClassName = "antialiased",
150
196
  mainClassName,
@@ -152,15 +198,35 @@ function SiteShell({
152
198
  children
153
199
  }) {
154
200
  const bootstrapScript = buildConsentBootstrapScript({
201
+ siteId: config.siteId,
155
202
  visitorScriptUrl: config.visitors?.enabled ? config.visitors.siteScriptUrl : void 0,
156
203
  gtmId: config.integrations?.gtmId,
157
204
  ga4MeasurementId: config.integrations?.ga4MeasurementId,
158
205
  legacyConsentCookies: config.consent?.legacyConsentCookies
159
206
  });
160
207
  const orgJsonLd = buildOrganizationJsonLd(config);
208
+ const mountBotId = shouldMountBotId(botId);
209
+ const botIdRoutes = mountBotId ? resolveBotIdRoutes(botId) : [];
161
210
  return /* @__PURE__ */ jsxs2("html", { lang: config.seo?.lang || "en", className: htmlClassName, children: [
162
211
  /* @__PURE__ */ jsxs2("head", { children: [
163
212
  bootstrapScript && /* @__PURE__ */ jsx2("script", { dangerouslySetInnerHTML: { __html: bootstrapScript } }),
213
+ mountBotId && /* @__PURE__ */ jsxs2(Fragment2, { children: [
214
+ /* @__PURE__ */ jsx2(
215
+ "script",
216
+ {
217
+ dangerouslySetInnerHTML: { __html: buildBotIdPreScript() }
218
+ }
219
+ ),
220
+ /* @__PURE__ */ jsx2(BotIdClient, { protect: botIdRoutes }),
221
+ /* @__PURE__ */ jsx2(
222
+ "script",
223
+ {
224
+ dangerouslySetInnerHTML: {
225
+ __html: buildBotIdPostScript(botIdRoutes)
226
+ }
227
+ }
228
+ )
229
+ ] }),
164
230
  head
165
231
  ] }),
166
232
  /* @__PURE__ */ jsxs2("body", { className: bodyClassName, children: [
@@ -189,6 +255,10 @@ function SiteShell({
189
255
  ] });
190
256
  }
191
257
  export {
258
+ DEFAULT_BOTID_PROTECTED_ROUTES,
192
259
  SiteShell,
193
- SkipLink
260
+ SkipLink,
261
+ buildBotIdPostScript,
262
+ buildBotIdPreScript,
263
+ resolveBotIdRoutes
194
264
  };
@@ -1,5 +1,5 @@
1
1
  import React__default from 'react';
2
- import { S as SiteConfig } from '../schema-DD0nDOD0.js';
2
+ import { S as SiteConfig } from '../schema-CYsBDpoU.js';
3
3
  import 'zod';
4
4
 
5
5
  interface SiteShellClientProps {
@@ -2,15 +2,15 @@
2
2
  "use client";
3
3
  import {
4
4
  ConsentBanner
5
- } from "../chunk-Y77ARZE4.js";
5
+ } from "../chunk-DHVKLLL7.js";
6
6
  import {
7
7
  PageTracker
8
- } from "../chunk-4YRCSRZZ.js";
9
- import "../chunk-QQP7VG2C.js";
8
+ } from "../chunk-SNTMH6M3.js";
9
+ import "../chunk-JPUCXNHR.js";
10
10
  import {
11
11
  ConsentGate,
12
12
  ConsentProvider
13
- } from "../chunk-7GDXQ6UB.js";
13
+ } from "../chunk-T4Q4VJ6K.js";
14
14
 
15
15
  // src/a11y/shell-client.tsx
16
16
  import { jsx, jsxs } from "react/jsx-runtime";
@@ -1,5 +1,5 @@
1
- export { A as AttributionSnapshot, W as WebsiteVisitSnapshot, c as captureAttributionOnLanding, r as readAttributionSnapshot, a as readConsentedWebsiteVisit } from '../attribution-DQaAWtA5.js';
2
- import { S as SiteConfig } from '../schema-DD0nDOD0.js';
1
+ export { A as AttributionSnapshot, M as MAX_JOURNEY_SERIALIZED_BYTES, W as WebsiteVisitJourneyEntry, a as WebsiteVisitSnapshot, c as captureAttributionOnLanding, r as readAttributionSnapshot, b as readConsentedWebsiteVisit, s as sanitizeWebsiteJourney, d as sanitizeWebsiteVisit } from '../attribution-BajAl0tG.js';
2
+ import { S as SiteConfig } from '../schema-CYsBDpoU.js';
3
3
  import React__default from 'react';
4
4
  import 'zod';
5
5
 
@@ -1,21 +1,24 @@
1
1
  "use client";
2
2
  import {
3
3
  PageTracker
4
- } from "../chunk-4YRCSRZZ.js";
4
+ } from "../chunk-SNTMH6M3.js";
5
5
  import {
6
+ MAX_JOURNEY_SERIALIZED_BYTES,
6
7
  captureAttributionOnLanding,
7
8
  pushDataLayerEvent,
8
9
  readAttributionSnapshot,
9
10
  readConsentedWebsiteVisit,
11
+ sanitizeWebsiteJourney,
12
+ sanitizeWebsiteVisit,
10
13
  trackBookingCompleted,
11
14
  trackCtaClick,
12
15
  trackEvent,
13
16
  trackFormSubmission,
14
17
  trackPageView
15
- } from "../chunk-QQP7VG2C.js";
18
+ } from "../chunk-JPUCXNHR.js";
16
19
  import {
17
20
  useConsent
18
- } from "../chunk-7GDXQ6UB.js";
21
+ } from "../chunk-T4Q4VJ6K.js";
19
22
 
20
23
  // src/analytics/booking.tsx
21
24
  import { useEffect } from "react";
@@ -108,11 +111,14 @@ function BookingEmbed({
108
111
  }
109
112
  export {
110
113
  BookingEmbed,
114
+ MAX_JOURNEY_SERIALIZED_BYTES,
111
115
  PageTracker,
112
116
  captureAttributionOnLanding,
113
117
  pushDataLayerEvent,
114
118
  readAttributionSnapshot,
115
119
  readConsentedWebsiteVisit,
120
+ sanitizeWebsiteJourney,
121
+ sanitizeWebsiteVisit,
116
122
  trackBookingCompleted,
117
123
  trackCtaClick,
118
124
  trackEvent,
@@ -13,15 +13,18 @@ interface AttributionSnapshot {
13
13
  referrer_host?: string;
14
14
  captured_at?: string;
15
15
  }
16
+ interface WebsiteVisitJourneyEntry {
17
+ sessionId: string;
18
+ startedAt: string;
19
+ pages: string[];
20
+ referrer?: string | null;
21
+ activeMs?: number;
22
+ }
16
23
  interface WebsiteVisitSnapshot {
17
24
  visitorKey: string;
18
25
  sessionId: string;
19
26
  device: "desktop" | "mobile";
20
- journey?: {
21
- landingPath?: string;
22
- referrerHost?: string;
23
- pagesViewed?: string[];
24
- };
27
+ journey?: WebsiteVisitJourneyEntry[];
25
28
  }
26
29
  /**
27
30
  * Cookie-free first-touch attribution capture (stored in sessionStorage only).
@@ -31,11 +34,18 @@ interface WebsiteVisitSnapshot {
31
34
  */
32
35
  declare function captureAttributionOnLanding(): AttributionSnapshot;
33
36
  declare function readAttributionSnapshot(): AttributionSnapshot;
37
+ /** Cap serialized optional journey well below `/api/leads` 64 KiB body limit so history never blocks lead capture. */
38
+ declare const MAX_JOURNEY_SERIALIZED_BYTES = 16384;
39
+ declare function sanitizeWebsiteJourney(raw: unknown): WebsiteVisitJourneyEntry[] | undefined;
40
+ declare function sanitizeWebsiteVisit(raw: unknown): WebsiteVisitSnapshot | undefined;
34
41
  /**
35
42
  * Reads optional first-party website visitor identity ONLY when caller has
36
43
  * already verified BrandywineOak consent (`allowed === true`).
44
+ * Supports the served visitor script's `window.__wrVisitor.getVisitContext()`
45
+ * bridge as well as direct fallback to the script's persisted `wr_vid`,
46
+ * `wr:visitors:session:<siteId>`, and `wr:journey:<siteId>` records.
37
47
  */
38
48
  declare function readConsentedWebsiteVisit(siteId: string, consentAllowed: boolean): WebsiteVisitSnapshot | undefined;
39
49
 
40
- export { readConsentedWebsiteVisit as a, captureAttributionOnLanding as c, readAttributionSnapshot as r };
41
- export type { AttributionSnapshot as A, WebsiteVisitSnapshot as W };
50
+ export { MAX_JOURNEY_SERIALIZED_BYTES as M, readConsentedWebsiteVisit as b, captureAttributionOnLanding as c, sanitizeWebsiteVisit as d, readAttributionSnapshot as r, sanitizeWebsiteJourney as s };
51
+ export type { AttributionSnapshot as A, WebsiteVisitJourneyEntry as W, WebsiteVisitSnapshot as a };
@@ -1,7 +1,7 @@
1
1
  "use client";
2
2
  import {
3
3
  useConsent
4
- } from "./chunk-7GDXQ6UB.js";
4
+ } from "./chunk-T4Q4VJ6K.js";
5
5
 
6
6
  // src/consent/banner.tsx
7
7
  import { useEffect, useId, useRef } from "react";
@@ -62,6 +62,8 @@ function ConsentBanner({
62
62
  if (config.consent?.enabled === false) return null;
63
63
  const isOptOut = mode === "opt-out" && !gpc;
64
64
  const message = config.consent?.message?.trim() || (isOptOut ? "We use cookies to understand website visits. You can turn analytics off at any time." : "May we use cookies to understand website visits? Forms and core site features work either way.");
65
+ const rawPolicyUrl = config.consent?.policyUrl?.trim() ?? "";
66
+ const safePolicyUrl = rawPolicyUrl.startsWith("/") && !rawPolicyUrl.startsWith("//") || /^https?:\/\//i.test(rawPolicyUrl) ? rawPolicyUrl : "";
65
67
  return /* @__PURE__ */ jsxs(Fragment, { children: [
66
68
  !config.consent?.hideFloatingPrivacyButton && /* @__PURE__ */ jsx(
67
69
  PrivacyChoicesButton,
@@ -134,10 +136,10 @@ function ConsentBanner({
134
136
  /* @__PURE__ */ jsxs("p", { style: { margin: 0, fontSize: "0.875rem", lineHeight: 1.5 }, children: [
135
137
  message,
136
138
  " ",
137
- config.consent?.policyUrl && /* @__PURE__ */ jsx(
139
+ safePolicyUrl && /* @__PURE__ */ jsx(
138
140
  "a",
139
141
  {
140
- href: config.consent.policyUrl,
142
+ href: safePolicyUrl,
141
143
  style: { textDecoration: "underline", color: "inherit" },
142
144
  children: "Privacy policy"
143
145
  }
@@ -6,7 +6,7 @@ import {
6
6
  readBrowserCookie,
7
7
  readGpcSignal,
8
8
  readStoredConsent
9
- } from "./chunk-7GDXQ6UB.js";
9
+ } from "./chunk-T4Q4VJ6K.js";
10
10
 
11
11
  // src/analytics/attribution.ts
12
12
  var ATTRIBUTION_STORAGE_KEY = "wr:attribution:v1";
@@ -84,52 +84,142 @@ function readAttributionSnapshot() {
84
84
  return captureAttributionOnLanding();
85
85
  }
86
86
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
87
+ var VISITOR_KEY_RE = /^[a-zA-Z0-9_-]{16,128}$/;
88
+ var ISO_OFFSET_DATETIME_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/i;
89
+ var SESSION_IDLE_MS = 30 * 60 * 1e3;
90
+ var MAX_JOURNEY_SERIALIZED_BYTES = 16384;
91
+ function sanitizeWebsiteJourney(raw) {
92
+ if (!Array.isArray(raw)) return void 0;
93
+ const entries = [];
94
+ for (const item of raw.slice(-10)) {
95
+ if (!item || typeof item !== "object" || Array.isArray(item)) continue;
96
+ const row = item;
97
+ const sessionId = typeof row.sessionId === "string" ? row.sessionId.trim() : "";
98
+ const startedAt = typeof row.startedAt === "string" ? row.startedAt.trim() : "";
99
+ if (!UUID_RE.test(sessionId) || !ISO_OFFSET_DATETIME_RE.test(startedAt) || Number.isNaN(Date.parse(startedAt))) {
100
+ continue;
101
+ }
102
+ const pages = Array.isArray(row.pages) ? row.pages.filter(
103
+ (page) => typeof page === "string" && page.length > 0 && page.length <= 2048
104
+ ).slice(-100) : [];
105
+ const referrer = typeof row.referrer === "string" && row.referrer.length <= 2048 ? row.referrer : row.referrer === null ? null : void 0;
106
+ const activeMs = typeof row.activeMs === "number" && Number.isFinite(row.activeMs) && row.activeMs >= 0 ? Math.min(864e5, Math.round(row.activeMs)) : void 0;
107
+ entries.push({
108
+ sessionId,
109
+ startedAt,
110
+ pages,
111
+ ...referrer !== void 0 ? { referrer } : {},
112
+ ...activeMs !== void 0 ? { activeMs } : {}
113
+ });
114
+ }
115
+ while (entries.length > 1 && JSON.stringify(entries).length > MAX_JOURNEY_SERIALIZED_BYTES) {
116
+ entries.shift();
117
+ }
118
+ if (entries.length === 1 && JSON.stringify(entries).length > MAX_JOURNEY_SERIALIZED_BYTES) {
119
+ const latest = entries[0];
120
+ while (latest.pages.length > 0 && JSON.stringify(entries).length > MAX_JOURNEY_SERIALIZED_BYTES) {
121
+ latest.pages.shift();
122
+ }
123
+ if (JSON.stringify(entries).length > MAX_JOURNEY_SERIALIZED_BYTES) {
124
+ return void 0;
125
+ }
126
+ }
127
+ return entries.length > 0 ? entries : void 0;
128
+ }
129
+ function sanitizeWebsiteVisit(raw) {
130
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
131
+ const obj = raw;
132
+ const visitorKey = typeof obj.visitorKey === "string" ? obj.visitorKey.trim() : "";
133
+ const sessionId = typeof obj.sessionId === "string" ? obj.sessionId.trim() : "";
134
+ if (!VISITOR_KEY_RE.test(visitorKey) || !UUID_RE.test(sessionId)) {
135
+ return void 0;
136
+ }
137
+ const device = obj.device === "mobile" ? "mobile" : "desktop";
138
+ const journey = sanitizeWebsiteJourney(obj.journey);
139
+ return {
140
+ visitorKey,
141
+ sessionId,
142
+ device,
143
+ ...journey ? { journey } : {}
144
+ };
145
+ }
87
146
  function readConsentedWebsiteVisit(siteId, consentAllowed) {
88
147
  if (!consentAllowed || typeof window === "undefined") return void 0;
89
148
  const win = window;
90
149
  let visitorKey;
91
150
  let sessionId;
92
- let journey;
151
+ let device;
152
+ let rawJourney;
93
153
  try {
94
- const bridge = win.__wrVisitor?.getVisitContext?.();
95
- if (bridge) {
96
- visitorKey = bridge.visitorKey;
97
- sessionId = bridge.sessionId;
98
- journey = bridge.journey;
154
+ if (typeof win.__wrVisitor?.getVisitContext === "function") {
155
+ const bridge = win.__wrVisitor.getVisitContext();
156
+ if (bridge === null) return void 0;
157
+ if (bridge) {
158
+ visitorKey = bridge.visitorKey;
159
+ sessionId = bridge.sessionId;
160
+ if (bridge.device === "desktop" || bridge.device === "mobile") {
161
+ device = bridge.device;
162
+ }
163
+ rawJourney = bridge.journey;
164
+ }
99
165
  } else if (win.__wrVisitor) {
100
166
  visitorKey = win.__wrVisitor.visitorKey;
101
167
  sessionId = win.__wrVisitor.sessionId;
102
168
  }
103
169
  } catch {
104
170
  }
171
+ if (!visitorKey) {
172
+ try {
173
+ visitorKey = readBrowserCookie("wr_vid") ?? window.localStorage.getItem("wr_vid") ?? window.localStorage.getItem("wr_visitor_key") ?? void 0;
174
+ } catch {
175
+ visitorKey = readBrowserCookie("wr_vid") ?? void 0;
176
+ }
177
+ }
178
+ if (!sessionId && siteId) {
179
+ try {
180
+ const rawSession = window.localStorage.getItem(
181
+ `wr:visitors:session:${siteId}`
182
+ );
183
+ if (rawSession) {
184
+ const state = JSON.parse(rawSession);
185
+ if (state && typeof state.id === "string" && UUID_RE.test(state.id) && (typeof state.last !== "number" || Date.now() - state.last <= SESSION_IDLE_MS) && (!state.vid || !visitorKey || state.vid === visitorKey)) {
186
+ sessionId = state.id;
187
+ }
188
+ }
189
+ } catch {
190
+ }
191
+ }
105
192
  if (!sessionId && siteId) {
106
193
  try {
107
194
  sessionId = window.sessionStorage.getItem(`wr:session:${siteId}`) ?? void 0;
108
195
  } catch {
109
196
  }
110
197
  }
111
- if (!visitorKey) {
198
+ if (!rawJourney && siteId) {
112
199
  try {
113
- visitorKey = window.localStorage.getItem("wr_visitor_key") ?? void 0;
200
+ const raw = window.localStorage.getItem(`wr:journey:${siteId}`);
201
+ if (raw) rawJourney = JSON.parse(raw);
114
202
  } catch {
115
203
  }
116
204
  }
117
- if (!visitorKey || !sessionId || !UUID_RE.test(visitorKey) || !UUID_RE.test(sessionId)) {
118
- return void 0;
205
+ if (!device) {
206
+ device = typeof window.matchMedia === "function" && window.matchMedia("(max-width: 767px)").matches ? "mobile" : "desktop";
119
207
  }
120
- const device = typeof window.matchMedia === "function" && window.matchMedia("(max-width: 767px)").matches ? "mobile" : "desktop";
121
- return {
208
+ return sanitizeWebsiteVisit({
122
209
  visitorKey,
123
210
  sessionId,
124
211
  device,
125
- ...journey ? { journey } : {}
126
- };
212
+ journey: rawJourney
213
+ });
127
214
  }
128
215
 
129
216
  // src/analytics/tracker.ts
130
217
  var inMemorySessionId = null;
131
218
  function isConsentCurrentlyAllowed(config) {
132
- const decision = readStoredConsent(config.consent?.legacyConsentCookies ?? []);
219
+ const decision = readStoredConsent(
220
+ config.consent?.legacyConsentCookies ?? [],
221
+ config.siteId
222
+ );
133
223
  const rawMode = readBrowserCookie(MODE_COOKIE);
134
224
  const mode = rawMode === "opt-out" ? "opt-out" : "opt-in";
135
225
  return analyticsAllowed(decision, mode, readGpcSignal());
@@ -221,6 +311,9 @@ function pushDataLayerEvent(event, extra, configOverride) {
221
311
  export {
222
312
  captureAttributionOnLanding,
223
313
  readAttributionSnapshot,
314
+ MAX_JOURNEY_SERIALIZED_BYTES,
315
+ sanitizeWebsiteJourney,
316
+ sanitizeWebsiteVisit,
224
317
  readConsentedWebsiteVisit,
225
318
  trackPageView,
226
319
  trackEvent,
@@ -2,10 +2,10 @@
2
2
  import {
3
3
  captureAttributionOnLanding,
4
4
  trackPageView
5
- } from "./chunk-QQP7VG2C.js";
5
+ } from "./chunk-JPUCXNHR.js";
6
6
  import {
7
7
  useConsent
8
- } from "./chunk-7GDXQ6UB.js";
8
+ } from "./chunk-T4Q4VJ6K.js";
9
9
 
10
10
  // src/analytics/page-tracker.tsx
11
11
  import { useEffect, useRef } from "react";