@aranova/tracking-react 0.24.1 → 0.25.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.
@@ -0,0 +1,3680 @@
1
+ "use client";
2
+
3
+ // src/ConsentBanner.tsx
4
+ import { useEffect as useEffect2, useState as useState2 } from "react";
5
+
6
+ // src/hooks.ts
7
+ import { useCallback, useEffect, useState } from "react";
8
+
9
+ // ../tracking-core/src/phone.ts
10
+ import { AsYouType, parsePhoneNumberFromString } from "libphonenumber-js";
11
+ var DEFAULT_PHONE_COUNTRY = "CA";
12
+ function parsePhone(raw, country) {
13
+ const region = country ?? DEFAULT_PHONE_COUNTRY;
14
+ const parsed = parsePhoneNumberFromString(raw ?? "", region);
15
+ if (!parsed) {
16
+ return { e164: null, national: "", international: "", country: region, isValid: false };
17
+ }
18
+ const isValid = parsed.isValid();
19
+ return {
20
+ // E.164 is only surfaced for a *valid* number — a possible-but-invalid input
21
+ // (e.g. too few digits) still parses but must not be transmitted.
22
+ e164: isValid ? parsed.number : null,
23
+ national: parsed.formatNational(),
24
+ international: parsed.formatInternational(),
25
+ country: parsed.country ?? region,
26
+ isValid
27
+ };
28
+ }
29
+ function toE164(raw, country) {
30
+ return parsePhone(raw, country).e164;
31
+ }
32
+ function formatPhone(value, format = "national", country) {
33
+ const parsed = parsePhone(value, country);
34
+ if (typeof format === "function") return format(parsed);
35
+ switch (format) {
36
+ case "international":
37
+ return parsed.international || value;
38
+ case "e164":
39
+ return parsed.e164 ?? value;
40
+ case "national":
41
+ default:
42
+ return parsed.national || value;
43
+ }
44
+ }
45
+ function formatPhoneAsTyped(raw, country) {
46
+ return new AsYouType(country ?? DEFAULT_PHONE_COUNTRY).input(raw ?? "");
47
+ }
48
+
49
+ // ../tracking-core/src/user-data.ts
50
+ var EMAIL_SHAPE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
51
+ var EMAIL_NAME_HINT = /e[-_]?mail/i;
52
+ var PHONE_NAME_HINT = /(^|[^a-z])(phone|tel|mobile|cell)/i;
53
+ var stash = { email: null, phoneNumber: null };
54
+ function normalizeEmail(raw) {
55
+ if (typeof raw !== "string") return null;
56
+ const cleaned = raw.trim().toLowerCase();
57
+ return EMAIL_SHAPE.test(cleaned) ? cleaned : null;
58
+ }
59
+ function fieldText(field, key) {
60
+ const value = field[key];
61
+ return typeof value === "string" ? value : "";
62
+ }
63
+ function extractUserDataFromFormFields(fields, country) {
64
+ const result = { email: null, phoneNumber: null };
65
+ if (!Array.isArray(fields)) return result;
66
+ const passes = [
67
+ (field, _hint, type) => fieldText(field, "type").toLowerCase() === type,
68
+ (field, hint) => hint.test(fieldText(field, "name")) || hint.test(fieldText(field, "label"))
69
+ ];
70
+ for (const matches of passes) {
71
+ for (const raw of fields) {
72
+ if (raw === null || typeof raw !== "object") continue;
73
+ const field = raw;
74
+ if (typeof field.value !== "string" || field.value.length === 0) continue;
75
+ if (result.email === null && matches(field, EMAIL_NAME_HINT, "email")) {
76
+ result.email = normalizeEmail(field.value);
77
+ }
78
+ if (result.phoneNumber === null && matches(field, PHONE_NAME_HINT, "tel")) {
79
+ try {
80
+ result.phoneNumber = toE164(field.value, country);
81
+ } catch {
82
+ }
83
+ }
84
+ }
85
+ if (result.email !== null && result.phoneNumber !== null) break;
86
+ }
87
+ return result;
88
+ }
89
+ function stashUserDataFromFormFields(fields, country) {
90
+ try {
91
+ const extracted = extractUserDataFromFormFields(fields, country);
92
+ stash = {
93
+ email: extracted.email ?? stash.email,
94
+ phoneNumber: extracted.phoneNumber ?? stash.phoneNumber
95
+ };
96
+ } catch {
97
+ }
98
+ }
99
+ function clearStashedUserData() {
100
+ stash = { email: null, phoneNumber: null };
101
+ }
102
+ function applyUserDataForConversion(explicit, country) {
103
+ if (typeof window === "undefined" || typeof window.gtag !== "function") return false;
104
+ let email = stash.email;
105
+ let phoneNumber = stash.phoneNumber;
106
+ if (explicit) {
107
+ const normalizedEmail = normalizeEmail(explicit.email);
108
+ if (normalizedEmail) email = normalizedEmail;
109
+ if (typeof explicit.phone === "string" && explicit.phone.length > 0) {
110
+ try {
111
+ phoneNumber = toE164(explicit.phone, country) ?? phoneNumber;
112
+ } catch {
113
+ }
114
+ }
115
+ }
116
+ if (email === null && phoneNumber === null) return false;
117
+ try {
118
+ window.gtag("set", "user_data", {
119
+ ...email !== null ? { email } : {},
120
+ ...phoneNumber !== null ? { phone_number: phoneNumber } : {}
121
+ });
122
+ return true;
123
+ } catch {
124
+ return false;
125
+ }
126
+ }
127
+
128
+ // ../tracking-core/src/consent.ts
129
+ var CONSENT_STATE_KEY = "consent_state";
130
+ var CONSENT_TIMESTAMP_KEY = "consent_timestamp";
131
+ var CONSENT_EXPIRES_AT_KEY = "consent_expires_at";
132
+ var DEFAULT_DECLINE_TTL_DAYS = 90;
133
+ var DAY_MS = 864e5;
134
+ var DEFAULT_CHOICE = {
135
+ state: "granted",
136
+ source: "default",
137
+ updatedAt: null,
138
+ expiresAt: null
139
+ };
140
+ var changeListeners = /* @__PURE__ */ new Set();
141
+ function onConsentChange(listener) {
142
+ changeListeners.add(listener);
143
+ return () => {
144
+ changeListeners.delete(listener);
145
+ };
146
+ }
147
+ function notifyConsentChanged(choice) {
148
+ for (const listener of changeListeners) {
149
+ try {
150
+ listener(choice);
151
+ } catch {
152
+ }
153
+ }
154
+ }
155
+ function buildConsentPayload(state) {
156
+ return {
157
+ ad_storage: state,
158
+ ad_user_data: state,
159
+ ad_personalization: state,
160
+ analytics_storage: state
161
+ };
162
+ }
163
+ function getConsentChoice() {
164
+ if (typeof window === "undefined") return DEFAULT_CHOICE;
165
+ try {
166
+ const stored = window.localStorage.getItem(CONSENT_STATE_KEY);
167
+ const updatedAt = window.localStorage.getItem(CONSENT_TIMESTAMP_KEY);
168
+ if (stored === "granted")
169
+ return { state: "granted", source: "explicit", updatedAt, expiresAt: null };
170
+ if (stored === "denied") {
171
+ let expiresAt = window.localStorage.getItem(CONSENT_EXPIRES_AT_KEY);
172
+ if (!expiresAt) {
173
+ expiresAt = new Date(Date.now() + DEFAULT_DECLINE_TTL_DAYS * DAY_MS).toISOString();
174
+ try {
175
+ window.localStorage.setItem(CONSENT_EXPIRES_AT_KEY, expiresAt);
176
+ } catch {
177
+ }
178
+ }
179
+ if (!(Date.parse(expiresAt) <= Date.now()))
180
+ return { state: "denied", source: "explicit", updatedAt, expiresAt };
181
+ }
182
+ } catch {
183
+ }
184
+ return DEFAULT_CHOICE;
185
+ }
186
+ function getConsentState() {
187
+ return getConsentChoice().state;
188
+ }
189
+ function pushConsentToPlatforms(state) {
190
+ if (typeof window === "undefined") return;
191
+ if (typeof window.gtag === "function")
192
+ window.gtag("consent", "update", buildConsentPayload(state));
193
+ if (typeof window.fbq === "function")
194
+ window.fbq("consent", state === "granted" ? "grant" : "revoke");
195
+ }
196
+ function setConsentState(state, options) {
197
+ if (typeof window === "undefined") return;
198
+ const requestedTtl = options?.declineTtlDays;
199
+ const ttlDays = typeof requestedTtl === "number" && Number.isFinite(requestedTtl) && requestedTtl > 0 ? requestedTtl : DEFAULT_DECLINE_TTL_DAYS;
200
+ const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
201
+ const expiresAt = state === "denied" ? new Date(Date.now() + ttlDays * DAY_MS).toISOString() : null;
202
+ try {
203
+ window.localStorage.setItem(CONSENT_STATE_KEY, state);
204
+ window.localStorage.setItem(CONSENT_TIMESTAMP_KEY, updatedAt);
205
+ if (expiresAt !== null) {
206
+ window.localStorage.setItem(CONSENT_EXPIRES_AT_KEY, expiresAt);
207
+ } else {
208
+ window.localStorage.removeItem(CONSENT_EXPIRES_AT_KEY);
209
+ }
210
+ } catch {
211
+ }
212
+ pushConsentToPlatforms(state);
213
+ if (state === "denied") {
214
+ clearStashedUserData();
215
+ try {
216
+ if (typeof window.gtag === "function") window.gtag("set", "user_data", null);
217
+ } catch {
218
+ }
219
+ }
220
+ notifyConsentChanged({ state, source: "explicit", updatedAt, expiresAt });
221
+ }
222
+ function optIn() {
223
+ setConsentState("granted");
224
+ }
225
+ function optOut(options) {
226
+ setConsentState("denied", options);
227
+ }
228
+ function resetConsent() {
229
+ if (typeof window === "undefined") return;
230
+ try {
231
+ window.localStorage.removeItem(CONSENT_STATE_KEY);
232
+ window.localStorage.removeItem(CONSENT_TIMESTAMP_KEY);
233
+ window.localStorage.removeItem(CONSENT_EXPIRES_AT_KEY);
234
+ } catch {
235
+ }
236
+ pushConsentToPlatforms("granted");
237
+ notifyConsentChanged(DEFAULT_CHOICE);
238
+ }
239
+
240
+ // ../tracking-core/src/capabilities.ts
241
+ var TRACKING_CAPABILITIES = [
242
+ "ad_tags_google",
243
+ "ad_tags_meta",
244
+ "base_tracking",
245
+ "blog_rendering",
246
+ "calendar_read",
247
+ "calendar_write",
248
+ "consent_controls",
249
+ "conversion_goals_auto",
250
+ "conversion_goals_manual",
251
+ "cta_click_capture",
252
+ "form_capture",
253
+ "phone_click_capture",
254
+ "phone_fields"
255
+ ];
256
+ var CAPABILITY_DOM_ATTRIBUTE = "data-aranova-capability";
257
+ var registered = /* @__PURE__ */ new Set();
258
+ function registerCapability(capability) {
259
+ registered.add(capability);
260
+ }
261
+ function getRegisteredCapabilities() {
262
+ const all = new Set(registered);
263
+ for (const marker of readDomMarkers()) all.add(marker);
264
+ return Array.from(all).sort();
265
+ }
266
+ function readDomMarkers() {
267
+ if (typeof document === "undefined") return [];
268
+ const known = new Set(TRACKING_CAPABILITIES);
269
+ const found = [];
270
+ for (const node of document.querySelectorAll(`[${CAPABILITY_DOM_ATTRIBUTE}]`)) {
271
+ const value = node.getAttribute(CAPABILITY_DOM_ATTRIBUTE);
272
+ if (value && known.has(value)) found.push(value);
273
+ }
274
+ return found;
275
+ }
276
+
277
+ // ../tracking-core/src/tracking.ts
278
+ var TRACKING_COOKIE_MAX_AGE_SECONDS = 7776e3;
279
+ var TRACKING_PARAM_KEYS = [
280
+ "gclid",
281
+ // Google's iOS/Safari replacement click IDs — issued when privacy features
282
+ // withhold gclid (wbraid: web-to-web, gbraid: app-to-web). First-class
283
+ // citizens: captured, persisted, and attributed exactly like gclid.
284
+ "wbraid",
285
+ "gbraid",
286
+ // Yelp Ads click id (40 hex chars), appended to ad-click URLs.
287
+ "ylpcid",
288
+ "fbclid",
289
+ "utm_source",
290
+ "utm_medium",
291
+ "utm_campaign",
292
+ "utm_term",
293
+ "utm_content"
294
+ ];
295
+ function createEmptyTrackingParams() {
296
+ return {
297
+ gclid: null,
298
+ wbraid: null,
299
+ gbraid: null,
300
+ ylpcid: null,
301
+ fbclid: null,
302
+ utm_source: null,
303
+ utm_medium: null,
304
+ utm_campaign: null,
305
+ utm_term: null,
306
+ utm_content: null
307
+ };
308
+ }
309
+ function normalizeTrackingCookieValue(value) {
310
+ return typeof value === "string" && value.length > 0 ? value : null;
311
+ }
312
+ function getTrackingParamsFromCookieReader(readCookie) {
313
+ return TRACKING_PARAM_KEYS.reduce((params, key) => {
314
+ params[key] = normalizeTrackingCookieValue(readCookie(key));
315
+ return params;
316
+ }, createEmptyTrackingParams());
317
+ }
318
+ function getTrackingQueryValues(searchParams) {
319
+ return TRACKING_PARAM_KEYS.reduce((params, key) => {
320
+ const value = searchParams.get(key);
321
+ if (typeof value === "string" && value.trim().length > 0) {
322
+ params[key] = value;
323
+ }
324
+ return params;
325
+ }, {});
326
+ }
327
+ var FALLBACK_STORAGE_PREFIX = "_aranova_track_";
328
+ function fallbackKey(name) {
329
+ return `${FALLBACK_STORAGE_PREFIX}${name}`;
330
+ }
331
+ function persistCookieValue(name, value, maxAgeSeconds = TRACKING_COOKIE_MAX_AGE_SECONDS) {
332
+ const encoded = encodeURIComponent(value);
333
+ if (typeof document !== "undefined") {
334
+ try {
335
+ document.cookie = `${name}=${encoded}; Max-Age=${maxAgeSeconds}; Path=/; SameSite=Lax`;
336
+ } catch {
337
+ }
338
+ }
339
+ if (typeof window !== "undefined") {
340
+ try {
341
+ window.localStorage.setItem(fallbackKey(name), encoded);
342
+ } catch {
343
+ }
344
+ }
345
+ }
346
+ function readCookieValue(name) {
347
+ if (typeof document !== "undefined") {
348
+ const cookies = document.cookie ? document.cookie.split("; ") : [];
349
+ const match = cookies.find((cookie) => cookie.startsWith(`${name}=`));
350
+ if (match) {
351
+ const [, rawValue = ""] = match.split("=");
352
+ return normalizeTrackingCookieValue(decodeURIComponent(rawValue));
353
+ }
354
+ }
355
+ if (typeof window !== "undefined") {
356
+ try {
357
+ const stored = window.localStorage.getItem(fallbackKey(name));
358
+ if (stored) return normalizeTrackingCookieValue(decodeURIComponent(stored));
359
+ } catch {
360
+ }
361
+ }
362
+ return null;
363
+ }
364
+ function getCookieValueFromDocument(key) {
365
+ return readCookieValue(key);
366
+ }
367
+ function setTrackingCookie(key, value, maxAgeSeconds = TRACKING_COOKIE_MAX_AGE_SECONDS) {
368
+ persistCookieValue(key, value, maxAgeSeconds);
369
+ }
370
+ function mergeTrackingParams(primary, fallback) {
371
+ return TRACKING_PARAM_KEYS.reduce((merged, key) => {
372
+ merged[key] = primary[key] ?? fallback[key];
373
+ return merged;
374
+ }, createEmptyTrackingParams());
375
+ }
376
+ function persistTrackingParamsFromSearchParams(searchParams, maxAgeSeconds = TRACKING_COOKIE_MAX_AGE_SECONDS) {
377
+ const trackingValues = getTrackingQueryValues(searchParams);
378
+ Object.entries(trackingValues).forEach(([key, value]) => {
379
+ setTrackingCookie(key, value, maxAgeSeconds);
380
+ });
381
+ return trackingValues;
382
+ }
383
+ function captureTrackingParamsFromLocation(url = typeof window === "undefined" ? "" : window.location.href, maxAgeSeconds = TRACKING_COOKIE_MAX_AGE_SECONDS) {
384
+ const resolvedUrl = typeof window === "undefined" ? new URL(url || "https://example.invalid") : new URL(url, window.location.origin);
385
+ persistTrackingParamsFromSearchParams(resolvedUrl.searchParams, maxAgeSeconds);
386
+ return getTrackingParamsFromCookieReader(getCookieValueFromDocument);
387
+ }
388
+
389
+ // ../tracking-core/src/gtag.ts
390
+ var GTAG_SCRIPT_HOST = "https://www.googletagmanager.com/gtag/js";
391
+ var TRACKING_SCRIPT_ATTRIBUTE = "data-aranova-tracking";
392
+ function getScriptMarker(id) {
393
+ return `aranova-${id}`;
394
+ }
395
+ var GTAG_ID_PATTERN = /^[A-Z]{1,3}-[A-Za-z0-9_-]+$/;
396
+ function isValidGtagId(id) {
397
+ return GTAG_ID_PATTERN.test(id);
398
+ }
399
+ function ensureGtagFunction() {
400
+ window.dataLayer = window.dataLayer || [];
401
+ if (typeof window.gtag === "function") return window.gtag;
402
+ function gtag() {
403
+ window.dataLayer?.push(arguments);
404
+ }
405
+ window.gtag = gtag;
406
+ return window.gtag;
407
+ }
408
+ var SEND_TO_RE = /^AW-[A-Za-z0-9]+\/[A-Za-z0-9_-]+$/;
409
+ function isValidSendTo(sendTo) {
410
+ return SEND_TO_RE.test(sendTo);
411
+ }
412
+ function fireGtagConversion(input) {
413
+ if (typeof window === "undefined" || typeof window.gtag !== "function") return false;
414
+ if (!isValidSendTo(input.sendTo)) return false;
415
+ const params = { send_to: input.sendTo };
416
+ if (input.value != null) params.value = input.value;
417
+ if (input.currency) params.currency = input.currency;
418
+ if (input.transactionId) params.transaction_id = input.transactionId;
419
+ try {
420
+ window.gtag("event", "conversion", params);
421
+ return true;
422
+ } catch {
423
+ return false;
424
+ }
425
+ }
426
+ function applyDefaultConsentState() {
427
+ const gtag = ensureGtagFunction();
428
+ gtag(
429
+ "consent",
430
+ "default",
431
+ buildConsentPayload(getConsentState() === "denied" ? "denied" : "granted")
432
+ );
433
+ }
434
+ function loadGtagScript(gtagId) {
435
+ if (typeof document === "undefined") return;
436
+ const marker = getScriptMarker("gtag-loader");
437
+ const existingScript = document.querySelector(
438
+ `script[${TRACKING_SCRIPT_ATTRIBUTE}="${marker}"]`
439
+ );
440
+ if (existingScript) return;
441
+ const script = document.createElement("script");
442
+ script.async = true;
443
+ script.src = `${GTAG_SCRIPT_HOST}?id=${encodeURIComponent(gtagId)}`;
444
+ script.setAttribute(TRACKING_SCRIPT_ATTRIBUTE, marker);
445
+ document.head.append(script);
446
+ }
447
+ function initializeGtag(gtagId) {
448
+ const gtag = ensureGtagFunction();
449
+ gtag("js", /* @__PURE__ */ new Date());
450
+ gtag("config", gtagId);
451
+ }
452
+ function bootstrapGoogleAdsTracking(gtagId) {
453
+ if (typeof window === "undefined" || typeof document === "undefined") return;
454
+ if (!isValidGtagId(gtagId)) return;
455
+ applyDefaultConsentState();
456
+ loadGtagScript(gtagId);
457
+ initializeGtag(gtagId);
458
+ }
459
+ function bootstrapMultipleGtags(gtagIds) {
460
+ if (typeof window === "undefined" || typeof document === "undefined") return;
461
+ const ids = Object.values(gtagIds).filter(
462
+ (id) => typeof id === "string" && isValidGtagId(id)
463
+ );
464
+ if (ids.length === 0) return;
465
+ applyDefaultConsentState();
466
+ loadGtagScript(ids[0]);
467
+ const gtag = ensureGtagFunction();
468
+ gtag("js", /* @__PURE__ */ new Date());
469
+ for (const id of ids) {
470
+ gtag("config", id);
471
+ }
472
+ }
473
+
474
+ // ../tracking-core/src/fbq.ts
475
+ var FB_EVENTS_SCRIPT_HOST = "https://connect.facebook.net/en_US/fbevents.js";
476
+ var FBC_COOKIE = "_fbc";
477
+ var FBP_COOKIE = "_fbp";
478
+ var META_PIXEL_ID_PATTERN = /^\d{15,16}$/;
479
+ function isValidMetaPixelId(id) {
480
+ return META_PIXEL_ID_PATTERN.test(id);
481
+ }
482
+ function computeFbSubdomainIndex(hostname) {
483
+ const labels = hostname.split(".").filter(Boolean);
484
+ return Math.max(0, labels.length - 1);
485
+ }
486
+ function buildFbc(fbclid, now, hostname) {
487
+ const host = hostname ?? (typeof window === "undefined" ? "" : window.location.hostname);
488
+ return `fb.${computeFbSubdomainIndex(host)}.${now}.${fbclid}`;
489
+ }
490
+ function getFbcCookie() {
491
+ return readCookieValue(FBC_COOKIE);
492
+ }
493
+ function getFbpCookie() {
494
+ return readCookieValue(FBP_COOKIE);
495
+ }
496
+ function readFbclidFromUrl() {
497
+ if (typeof window === "undefined") return null;
498
+ try {
499
+ const value = new URL(window.location.href).searchParams.get("fbclid");
500
+ return value && value.trim().length > 0 ? value : null;
501
+ } catch {
502
+ return null;
503
+ }
504
+ }
505
+ function captureFbc(now = typeof Date === "undefined" ? 0 : Date.now()) {
506
+ if (typeof window === "undefined") return;
507
+ if (getFbcCookie()) return;
508
+ const fbclid = readFbclidFromUrl() ?? readCookieValue("fbclid");
509
+ if (!fbclid) return;
510
+ persistCookieValue(FBC_COOKIE, buildFbc(fbclid, now), TRACKING_COOKIE_MAX_AGE_SECONDS);
511
+ }
512
+ function getScriptMarker2(id) {
513
+ return `aranova-${id}`;
514
+ }
515
+ function ensureFbqFunction() {
516
+ const w = window;
517
+ if (typeof w.fbq === "function") return w.fbq;
518
+ const fbq = function(...args) {
519
+ if (fbq.callMethod) fbq.callMethod.apply(fbq, args);
520
+ else fbq.queue.push(args);
521
+ };
522
+ fbq.push = fbq;
523
+ fbq.loaded = true;
524
+ fbq.version = "2.0";
525
+ fbq.queue = [];
526
+ w.fbq = fbq;
527
+ if (!w._fbq) w._fbq = fbq;
528
+ return fbq;
529
+ }
530
+ function applyDefaultMetaConsentState() {
531
+ ensureFbqFunction()("consent", getConsentState() === "denied" ? "revoke" : "grant");
532
+ }
533
+ function loadFbeventsScript() {
534
+ if (typeof document === "undefined") return;
535
+ const marker = getScriptMarker2("fbq-loader");
536
+ const existing = document.querySelector(
537
+ `script[${TRACKING_SCRIPT_ATTRIBUTE}="${marker}"]`
538
+ );
539
+ if (existing) return;
540
+ const script = document.createElement("script");
541
+ script.async = true;
542
+ script.src = FB_EVENTS_SCRIPT_HOST;
543
+ script.setAttribute(TRACKING_SCRIPT_ATTRIBUTE, marker);
544
+ document.head.append(script);
545
+ }
546
+ function initializeMetaPixel(pixelId) {
547
+ const fbq = ensureFbqFunction();
548
+ fbq("init", pixelId);
549
+ fbq("track", "PageView");
550
+ }
551
+ function bootstrapMetaPixel(pixelId) {
552
+ if (typeof window === "undefined" || typeof document === "undefined") return;
553
+ if (!isValidMetaPixelId(pixelId)) return;
554
+ applyDefaultMetaConsentState();
555
+ loadFbeventsScript();
556
+ initializeMetaPixel(pixelId);
557
+ captureFbc();
558
+ }
559
+ function bootstrapMultiplePixels(pixelIds) {
560
+ if (typeof window === "undefined" || typeof document === "undefined") return;
561
+ const ids = Object.values(pixelIds).filter(
562
+ (id) => typeof id === "string" && isValidMetaPixelId(id)
563
+ );
564
+ if (ids.length === 0) return;
565
+ applyDefaultMetaConsentState();
566
+ loadFbeventsScript();
567
+ const fbq = ensureFbqFunction();
568
+ for (const id of ids) {
569
+ fbq("init", id);
570
+ }
571
+ fbq("track", "PageView");
572
+ captureFbc();
573
+ }
574
+
575
+ // ../tracking-core/src/landing.ts
576
+ var LANDING_STORAGE_KEY = "_aranova_track_landing";
577
+ var memoryRecord = null;
578
+ function sanitizeParams(value) {
579
+ if (typeof value !== "object" || value === null) return {};
580
+ const source = value;
581
+ return TRACKING_PARAM_KEYS.reduce((params, key) => {
582
+ const entry = source[key];
583
+ if (typeof entry === "string" && entry.length > 0) params[key] = entry;
584
+ return params;
585
+ }, {});
586
+ }
587
+ function readStoredRecord() {
588
+ try {
589
+ const raw = window.localStorage.getItem(LANDING_STORAGE_KEY);
590
+ if (!raw) return null;
591
+ const parsed = JSON.parse(raw);
592
+ if (typeof parsed.session_id !== "string" || parsed.session_id.length === 0) return null;
593
+ return { session_id: parsed.session_id, params: sanitizeParams(parsed.params) };
594
+ } catch {
595
+ return null;
596
+ }
597
+ }
598
+ function writeRecord(record) {
599
+ memoryRecord = record;
600
+ try {
601
+ window.localStorage.setItem(LANDING_STORAGE_KEY, JSON.stringify(record));
602
+ } catch {
603
+ }
604
+ }
605
+ function captureFromUrl(url) {
606
+ try {
607
+ const resolved = new URL(url ?? window.location.href, window.location.origin);
608
+ return getTrackingQueryValues(resolved.searchParams);
609
+ } catch {
610
+ return {};
611
+ }
612
+ }
613
+ function getOrCaptureLandingParams(sessionId, url) {
614
+ if (typeof window === "undefined") return {};
615
+ const stored = readStoredRecord();
616
+ if (stored && stored.session_id === sessionId) {
617
+ memoryRecord = stored;
618
+ return stored.params;
619
+ }
620
+ if (memoryRecord && memoryRecord.session_id === sessionId) {
621
+ return memoryRecord.params;
622
+ }
623
+ const record = { session_id: sessionId, params: captureFromUrl(url) };
624
+ writeRecord(record);
625
+ return record.params;
626
+ }
627
+ function buildLandingPayloadFields(sessionId, override) {
628
+ const params = override ?? (typeof window === "undefined" ? null : getOrCaptureLandingParams(sessionId));
629
+ if (params === null) return {};
630
+ return {
631
+ landing_gclid: params.gclid ?? null,
632
+ landing_wbraid: params.wbraid ?? null,
633
+ landing_gbraid: params.gbraid ?? null,
634
+ landing_ylpcid: params.ylpcid ?? null,
635
+ landing_fbclid: params.fbclid ?? null,
636
+ landing_utm_source: params.utm_source ?? null,
637
+ landing_utm_medium: params.utm_medium ?? null,
638
+ landing_utm_campaign: params.utm_campaign ?? null,
639
+ landing_utm_term: params.utm_term ?? null,
640
+ landing_utm_content: params.utm_content ?? null
641
+ };
642
+ }
643
+
644
+ // ../tracking-core/src/resources/conversion-firing.ts
645
+ var DEDUP_PREFIX = "_aranova_conv_";
646
+ function dedupKey(input) {
647
+ return `${DEDUP_PREFIX}${input.transactionId ?? ""}:${input.sendTo}`;
648
+ }
649
+ function alreadyFired(input) {
650
+ if (!input.transactionId || typeof window === "undefined") return false;
651
+ try {
652
+ return window.sessionStorage.getItem(dedupKey(input)) !== null;
653
+ } catch {
654
+ return false;
655
+ }
656
+ }
657
+ function markFired(input) {
658
+ if (!input.transactionId || typeof window === "undefined") return;
659
+ try {
660
+ window.sessionStorage.setItem(dedupKey(input), "1");
661
+ } catch {
662
+ }
663
+ }
664
+ function fireConversionWithConsent(input, options) {
665
+ if (getConsentState() === "denied") return "denied";
666
+ if (alreadyFired(input)) return "duplicate";
667
+ if (!isValidSendTo(input.sendTo)) return "invalid";
668
+ try {
669
+ applyUserDataForConversion(options?.userData);
670
+ if (!fireGtagConversion(input)) return "retryable";
671
+ markFired(input);
672
+ return "fired";
673
+ } catch {
674
+ return "retryable";
675
+ }
676
+ }
677
+
678
+ // ../tracking-core/src/resources/conversion-config.ts
679
+ function isStringMap(value) {
680
+ return typeof value === "object" && value !== null && Object.values(value).every((v) => typeof v === "string");
681
+ }
682
+ function parseFiring(value) {
683
+ if (!value || typeof value !== "object") return null;
684
+ const f = value;
685
+ if (typeof f.send_to !== "string") return null;
686
+ return {
687
+ send_to: f.send_to,
688
+ value_cents: typeof f.value_cents === "number" ? f.value_cents : null,
689
+ currency: typeof f.currency === "string" ? f.currency : null
690
+ };
691
+ }
692
+ function parseTrigger(value) {
693
+ if (!value || typeof value !== "object") return null;
694
+ const t = value;
695
+ if (typeof t.event_type !== "string") return null;
696
+ const spec = { event_type: t.event_type };
697
+ if (typeof t.threshold_percent === "number") spec.threshold_percent = t.threshold_percent;
698
+ if (typeof t.threshold_seconds === "number") spec.threshold_seconds = t.threshold_seconds;
699
+ if (typeof t.page_threshold === "number") spec.page_threshold = t.page_threshold;
700
+ if (typeof t.page_name === "string") spec.page_name = t.page_name;
701
+ return spec;
702
+ }
703
+ function parseConversionConfig(raw) {
704
+ if (!raw || typeof raw !== "object") return null;
705
+ const obj = raw;
706
+ const servicesRaw = Array.isArray(obj.services) ? obj.services : [];
707
+ const services = servicesRaw.flatMap((entry) => {
708
+ if (!entry || typeof entry !== "object") return [];
709
+ const s = entry;
710
+ if (typeof s.key !== "string") return [];
711
+ return [
712
+ {
713
+ key: s.key,
714
+ label: typeof s.label === "string" ? s.label : void 0,
715
+ firing: parseFiring(s.firing)
716
+ }
717
+ ];
718
+ });
719
+ const goalsRaw = Array.isArray(obj.goals) ? obj.goals : null;
720
+ const goals = goalsRaw ? goalsRaw.flatMap((entry) => {
721
+ if (!entry || typeof entry !== "object") return [];
722
+ const g = entry;
723
+ if (typeof g.key !== "string") return [];
724
+ return [
725
+ {
726
+ key: g.key,
727
+ label: typeof g.label === "string" ? g.label : void 0,
728
+ kind: g.kind === "event" ? "event" : "sale",
729
+ trigger: parseTrigger(g.trigger),
730
+ firing: parseFiring(g.firing)
731
+ }
732
+ ];
733
+ }) : services.map((s) => ({
734
+ key: s.key,
735
+ label: s.label,
736
+ kind: "sale",
737
+ trigger: null,
738
+ firing: s.firing
739
+ }));
740
+ return {
741
+ schema_version: typeof obj.schema_version === "number" ? obj.schema_version : 1,
742
+ config_version: typeof obj.config_version === "number" ? obj.config_version : 0,
743
+ business_id: typeof obj.business_id === "string" ? obj.business_id : void 0,
744
+ customer_id: typeof obj.customer_id === "string" ? obj.customer_id : null,
745
+ environment: typeof obj.environment === "string" ? obj.environment : void 0,
746
+ google_tracking_state: obj.google_tracking_state === "active" ? "active" : "disabled",
747
+ gtag_ids: isStringMap(obj.gtag_ids) ? obj.gtag_ids : {},
748
+ meta_pixel_ids: isStringMap(obj.meta_pixel_ids) ? obj.meta_pixel_ids : {},
749
+ services,
750
+ goals
751
+ };
752
+ }
753
+ var CACHE_PREFIX = "_aranova_cfg_";
754
+ function cacheKey(url) {
755
+ return `${CACHE_PREFIX}${url}`;
756
+ }
757
+ function readCache(url) {
758
+ if (typeof window === "undefined") return null;
759
+ try {
760
+ const raw = window.sessionStorage.getItem(cacheKey(url));
761
+ if (!raw) return null;
762
+ const parsed = JSON.parse(raw);
763
+ const config = parseConversionConfig(parsed.config);
764
+ if (!config) return null;
765
+ return {
766
+ etag: typeof parsed.etag === "string" ? parsed.etag : null,
767
+ config
768
+ };
769
+ } catch {
770
+ return null;
771
+ }
772
+ }
773
+ function writeCache(url, entry) {
774
+ if (typeof window === "undefined") return;
775
+ try {
776
+ window.sessionStorage.setItem(cacheKey(url), JSON.stringify(entry));
777
+ } catch {
778
+ }
779
+ }
780
+ function resolveConversionConfig(options) {
781
+ const cached = readCache(options.cdnUrl);
782
+ let current = cached?.config ?? options.baked ?? null;
783
+ let etag = cached?.etag ?? null;
784
+ const goalsByKey = /* @__PURE__ */ new Map();
785
+ const resolveListeners = /* @__PURE__ */ new Set();
786
+ function rebuildIndex() {
787
+ goalsByKey.clear();
788
+ for (const goal of current?.goals ?? []) {
789
+ goalsByKey.set(goal.key, goal);
790
+ }
791
+ }
792
+ function notifyResolved() {
793
+ const listeners2 = [...resolveListeners];
794
+ resolveListeners.clear();
795
+ for (const listener of listeners2) {
796
+ try {
797
+ listener();
798
+ } catch {
799
+ }
800
+ }
801
+ }
802
+ function adopt(next, nextEtag) {
803
+ if (!next) return;
804
+ if (current && next.config_version <= current.config_version) return;
805
+ const wasEmpty = current === null;
806
+ current = next;
807
+ etag = nextEtag;
808
+ rebuildIndex();
809
+ writeCache(options.cdnUrl, { etag, config: next });
810
+ if (wasEmpty) notifyResolved();
811
+ }
812
+ async function revalidate() {
813
+ if (typeof window === "undefined") return;
814
+ try {
815
+ const doFetch = options.fetchImpl ?? globalThis.fetch;
816
+ if (!doFetch) return;
817
+ const headers = {};
818
+ if (etag) headers["If-None-Match"] = etag;
819
+ const response = await doFetch(options.cdnUrl, {
820
+ method: "GET",
821
+ headers
822
+ });
823
+ if (response.status === 304 || !response.ok) return;
824
+ adopt(parseConversionConfig(await response.json()), response.headers.get("ETag"));
825
+ } catch {
826
+ }
827
+ }
828
+ rebuildIndex();
829
+ void revalidate();
830
+ return {
831
+ getFiring: (key) => goalsByKey.get(key)?.firing ?? null,
832
+ getGoal: (key) => goalsByKey.get(key) ?? null,
833
+ listGoals: () => [...goalsByKey.values()],
834
+ current: () => current,
835
+ isReady: () => current !== null,
836
+ onResolve: (listener) => {
837
+ if (current !== null) {
838
+ listener();
839
+ return () => {
840
+ };
841
+ }
842
+ resolveListeners.add(listener);
843
+ return () => resolveListeners.delete(listener);
844
+ },
845
+ revalidate
846
+ };
847
+ }
848
+
849
+ // ../tracking-core/src/resources/automatic-transaction.ts
850
+ var STORAGE_KEY = "_aranova_auto_txn_map";
851
+ var transactionIds = /* @__PURE__ */ new Map();
852
+ var legacyCounter = 0;
853
+ function scopeKey(sessionId, goalKey, path) {
854
+ return JSON.stringify([sessionId, goalKey, path]);
855
+ }
856
+ function randomId() {
857
+ const cryptoApi = globalThis.crypto;
858
+ if (typeof cryptoApi?.randomUUID === "function") return cryptoApi.randomUUID();
859
+ if (typeof cryptoApi?.getRandomValues === "function") {
860
+ const bytes = cryptoApi.getRandomValues(new Uint8Array(16));
861
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
862
+ }
863
+ legacyCounter = (legacyCounter + 1) % 4294967296;
864
+ const timestamp = Date.now().toString(16).padStart(12, "0");
865
+ const counter = legacyCounter.toString(16).padStart(8, "0");
866
+ const random = Math.floor(Math.random() * 281474976710655).toString(16).padStart(12, "0");
867
+ return `${timestamp}${counter}${random}`.slice(0, 32);
868
+ }
869
+ function isValidTransactionId(value) {
870
+ return typeof value === "string" && /^auto:(?:[0-9a-f]{32}|[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})$/i.test(
871
+ value
872
+ ) && value.length <= 64;
873
+ }
874
+ function readStoredMap(sessionId) {
875
+ if (typeof window === "undefined") return { sessionId, entries: {} };
876
+ try {
877
+ const raw = window.localStorage.getItem(STORAGE_KEY);
878
+ if (!raw) return { sessionId, entries: {} };
879
+ const parsed = JSON.parse(raw);
880
+ if (parsed.sessionId !== sessionId || !parsed.entries || typeof parsed.entries !== "object" || Array.isArray(parsed.entries)) {
881
+ return { sessionId, entries: {} };
882
+ }
883
+ return { sessionId, entries: parsed.entries };
884
+ } catch {
885
+ return { sessionId, entries: {} };
886
+ }
887
+ }
888
+ function writeStoredMap(stored) {
889
+ if (typeof window === "undefined") return;
890
+ try {
891
+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify(stored));
892
+ } catch {
893
+ }
894
+ }
895
+ function getAutomaticTransactionId(sessionId, goalKey, path) {
896
+ const key = scopeKey(sessionId, goalKey, path);
897
+ const existing = transactionIds.get(key);
898
+ if (existing) return existing;
899
+ const stored = readStoredMap(sessionId);
900
+ const storedId = stored.entries[key];
901
+ if (isValidTransactionId(storedId)) {
902
+ transactionIds.set(key, storedId);
903
+ return storedId;
904
+ }
905
+ const transactionId = `auto:${randomId()}`;
906
+ transactionIds.set(key, transactionId);
907
+ const latest = readStoredMap(sessionId);
908
+ const concurrentId = latest.entries[key];
909
+ if (isValidTransactionId(concurrentId)) {
910
+ transactionIds.set(key, concurrentId);
911
+ return concurrentId;
912
+ }
913
+ latest.entries[key] = transactionId;
914
+ writeStoredMap(latest);
915
+ return transactionId;
916
+ }
917
+
918
+ // ../tracking-core/src/resources/automatic-trigger.ts
919
+ function hasNumberField(metadata, key) {
920
+ return typeof metadata[key] === "number";
921
+ }
922
+ function hasStringField(metadata, key) {
923
+ return typeof metadata[key] === "string";
924
+ }
925
+ function automaticThresholdMet(goal, eventType, metadata) {
926
+ const trigger = goal.trigger;
927
+ if (!trigger || trigger.event_type !== eventType) return false;
928
+ switch (eventType) {
929
+ case "scroll_depth":
930
+ return hasNumberField(metadata, "depth_percent") && trigger.threshold_percent != null && metadata.depth_percent >= trigger.threshold_percent;
931
+ case "time_on_site":
932
+ return hasNumberField(metadata, "duration_ms") && trigger.threshold_seconds != null && metadata.duration_ms >= trigger.threshold_seconds * 1e3;
933
+ case "multi_page_session":
934
+ return hasNumberField(metadata, "page_count") && trigger.page_threshold != null && metadata.page_count >= trigger.page_threshold;
935
+ case "specific_page_visit":
936
+ return hasStringField(metadata, "page_name") && metadata.page_name === trigger.page_name;
937
+ case "page_view":
938
+ case "form_start":
939
+ case "phone_click":
940
+ return true;
941
+ default:
942
+ return false;
943
+ }
944
+ }
945
+
946
+ // ../tracking-core/src/resources/sales/money.ts
947
+ var MINOR_UNIT_EXPONENT = {
948
+ USD: 2,
949
+ CAD: 2
950
+ };
951
+ function exponentFor(currency) {
952
+ return MINOR_UNIT_EXPONENT[currency] ?? 2;
953
+ }
954
+ function fromMinor(cents, currency) {
955
+ return cents / 10 ** exponentFor(currency);
956
+ }
957
+
958
+ // ../tracking-core/src/resources/tracking-config-runtime.ts
959
+ var DEFAULT_CDN_BASE_URL = "https://demos.aranova.io";
960
+ function trackingConfigKey(businessId, environment) {
961
+ return `tracking-config/v1/${businessId}-${environment}.json`;
962
+ }
963
+ function resolveTrackingConfigUrl(ref) {
964
+ if (ref.cdnUrl) return ref.cdnUrl;
965
+ const configured = ref.cdnBaseUrl?.trim();
966
+ const base = (configured || DEFAULT_CDN_BASE_URL).replace(/\/+$/, "");
967
+ return `${base}/${trackingConfigKey(ref.businessId, ref.environment)}`;
968
+ }
969
+ var CACHE_PREFIX2 = "_aranova_cfg_runtime_";
970
+ var AUTHORITY_TTL_MS = 6e4;
971
+ var MAX_QUEUE_LENGTH = 50;
972
+ var RETRY_BASE_MS = 5e3;
973
+ var RETRY_MAX_MS = 5 * 6e4;
974
+ var runtimes = /* @__PURE__ */ new Map();
975
+ var configuredIds = /* @__PURE__ */ new Set();
976
+ var scriptLoad = null;
977
+ var jsInitialized = false;
978
+ function cacheKey2(url) {
979
+ return `${CACHE_PREFIX2}${url}`;
980
+ }
981
+ function pushBounded(queue, item) {
982
+ queue.push(item);
983
+ if (queue.length > MAX_QUEUE_LENGTH) queue.splice(0, queue.length - MAX_QUEUE_LENGTH);
984
+ }
985
+ function readCache2(url) {
986
+ if (typeof window === "undefined") return null;
987
+ try {
988
+ const raw = window.sessionStorage.getItem(cacheKey2(url));
989
+ if (!raw) return null;
990
+ const parsed = JSON.parse(raw);
991
+ const config = parseConversionConfig(parsed.config);
992
+ if (!config) return null;
993
+ return {
994
+ etag: typeof parsed.etag === "string" ? parsed.etag : null,
995
+ config
996
+ };
997
+ } catch {
998
+ return null;
999
+ }
1000
+ }
1001
+ function writeCache2(url, entry) {
1002
+ if (typeof window === "undefined") return;
1003
+ try {
1004
+ window.sessionStorage.setItem(cacheKey2(url), JSON.stringify(entry));
1005
+ } catch {
1006
+ }
1007
+ }
1008
+ function isTombstone(config) {
1009
+ return config.google_tracking_state === "disabled" || Object.keys(config.gtag_ids).length === 0;
1010
+ }
1011
+ function validateConfig(config, ref) {
1012
+ return config.business_id === ref.businessId && config.environment === ref.environment && (config.google_tracking_state === "active" || config.google_tracking_state === "disabled");
1013
+ }
1014
+ function pageViewSnapshot() {
1015
+ if (typeof window === "undefined" || typeof document === "undefined") return null;
1016
+ return {
1017
+ href: window.location.href,
1018
+ title: document.title || null,
1019
+ referrer: document.referrer || null
1020
+ };
1021
+ }
1022
+ function ensureScript(gtagId) {
1023
+ if (typeof window === "undefined" || typeof document === "undefined") return Promise.resolve();
1024
+ applyDefaultConsentState();
1025
+ loadGtagScript(gtagId);
1026
+ if (scriptLoad) return scriptLoad;
1027
+ scriptLoad = new Promise((resolve) => {
1028
+ const script = document.querySelector(
1029
+ 'script[data-aranova-tracking="aranova-gtag-loader"]'
1030
+ );
1031
+ if (!script) {
1032
+ resolve();
1033
+ return;
1034
+ }
1035
+ if (script.dataset.loaded === "true") {
1036
+ resolve();
1037
+ return;
1038
+ }
1039
+ window.setTimeout(resolve, 0);
1040
+ script.addEventListener(
1041
+ "load",
1042
+ () => {
1043
+ script.dataset.loaded = "true";
1044
+ resolve();
1045
+ },
1046
+ { once: true }
1047
+ );
1048
+ script.addEventListener("error", () => resolve(), { once: true });
1049
+ });
1050
+ return scriptLoad;
1051
+ }
1052
+ var TrackingConfigRuntime = class {
1053
+ constructor(ref, fetchImpl = globalThis.fetch) {
1054
+ this.ref = ref;
1055
+ this.current = null;
1056
+ this.etag = null;
1057
+ this.stateValue = "unconfirmed";
1058
+ this.confirmedAt = 0;
1059
+ this.authorityGeneration = 0;
1060
+ this.inFlight = null;
1061
+ this.flushInFlight = null;
1062
+ this.flushRequested = false;
1063
+ this.retryTimer = null;
1064
+ this.started = false;
1065
+ /** Consecutive failed authority attempts — drives the revalidate backoff. */
1066
+ this.authorityFailures = 0;
1067
+ /** Epoch ms before which `ensureAuthority` must not issue another request. */
1068
+ this.nextAuthorityAttemptAt = 0;
1069
+ this.conversionQueue = [];
1070
+ this.automaticQueue = [];
1071
+ this.pageQueue = [];
1072
+ this.listeners = /* @__PURE__ */ new Set();
1073
+ this.fetchImpl = fetchImpl.bind(globalThis);
1074
+ this.url = resolveTrackingConfigUrl(ref);
1075
+ const cached = readCache2(this.url);
1076
+ this.current = cached?.config ?? null;
1077
+ this.etag = cached?.etag ?? null;
1078
+ this.start();
1079
+ }
1080
+ /** The URL this runtime actually fetches (composed or explicit). */
1081
+ configUrl() {
1082
+ return this.url;
1083
+ }
1084
+ /**
1085
+ * Explicitly start authority resolution and Google-tag bootstrap.
1086
+ *
1087
+ * Idempotent so framework effects can call it after hydration without
1088
+ * depending on constructor timing.
1089
+ */
1090
+ start() {
1091
+ if (this.started) {
1092
+ void this.flush();
1093
+ return;
1094
+ }
1095
+ this.started = true;
1096
+ void this.revalidate();
1097
+ if (typeof window !== "undefined") {
1098
+ window.addEventListener("visibilitychange", () => {
1099
+ if (document.visibilityState === "visible") void this.revalidate();
1100
+ });
1101
+ window.addEventListener("focus", () => void this.revalidate());
1102
+ }
1103
+ }
1104
+ state() {
1105
+ return this.stateValue;
1106
+ }
1107
+ config() {
1108
+ return this.stateValue === "active" || this.stateValue === "tombstone" ? this.current : null;
1109
+ }
1110
+ __unsafeExpireAuthorityForTests() {
1111
+ this.confirmedAt = Number.NEGATIVE_INFINITY;
1112
+ this.nextAuthorityAttemptAt = 0;
1113
+ }
1114
+ /** Queue depths — asserted by tests to pin the bound. */
1115
+ __queueDepthsForTests() {
1116
+ return {
1117
+ conversions: this.conversionQueue.length,
1118
+ automatic: this.automaticQueue.length,
1119
+ pages: this.pageQueue.length
1120
+ };
1121
+ }
1122
+ subscribe(listener) {
1123
+ this.listeners.add(listener);
1124
+ return () => this.listeners.delete(listener);
1125
+ }
1126
+ async ensureAuthority() {
1127
+ if (this.stateValue !== "unconfirmed" && Date.now() - this.confirmedAt < AUTHORITY_TTL_MS) {
1128
+ return true;
1129
+ }
1130
+ if (Date.now() < this.nextAuthorityAttemptAt) return false;
1131
+ await this.revalidateAuthority();
1132
+ return this.stateValue !== "unconfirmed" && Date.now() - this.confirmedAt < AUTHORITY_TTL_MS;
1133
+ }
1134
+ async revalidate() {
1135
+ this.nextAuthorityAttemptAt = 0;
1136
+ await this.revalidateAuthority();
1137
+ await this.flush();
1138
+ }
1139
+ async revalidateAuthority() {
1140
+ if (typeof window === "undefined" || !this.fetchImpl) return;
1141
+ if (this.inFlight) return this.inFlight;
1142
+ this.inFlight = this.revalidateNow().finally(() => {
1143
+ this.inFlight = null;
1144
+ });
1145
+ return this.inFlight;
1146
+ }
1147
+ queuePageView(snapshot = pageViewSnapshot()) {
1148
+ if (!snapshot) return;
1149
+ pushBounded(this.pageQueue, snapshot);
1150
+ void this.flush();
1151
+ }
1152
+ fireConversion(key, options) {
1153
+ pushBounded(this.conversionQueue, { key, ...options });
1154
+ void this.flush();
1155
+ }
1156
+ queueAutomaticEvent(eventType, metadata, transactionPath, transactionScope) {
1157
+ pushBounded(this.automaticQueue, {
1158
+ eventType,
1159
+ metadata,
1160
+ transactionPath,
1161
+ transactionScope
1162
+ });
1163
+ void this.flush();
1164
+ }
1165
+ listGoals() {
1166
+ return this.current?.goals ?? [];
1167
+ }
1168
+ async revalidateNow() {
1169
+ try {
1170
+ const headers = {};
1171
+ if (this.etag) headers["If-None-Match"] = this.etag;
1172
+ const response = await this.fetchImpl(this.url, {
1173
+ method: "GET",
1174
+ headers,
1175
+ cache: "no-cache"
1176
+ });
1177
+ if (response.status === 304 && this.current && validateConfig(this.current, this.ref)) {
1178
+ this.confirm(this.current, this.etag);
1179
+ return;
1180
+ }
1181
+ if (!response.ok) {
1182
+ this.expireAuthority();
1183
+ return;
1184
+ }
1185
+ const next = parseConversionConfig(await response.json());
1186
+ if (!next || !validateConfig(next, this.ref)) {
1187
+ this.expireAuthority();
1188
+ return;
1189
+ }
1190
+ if (this.current && next.config_version < this.current.config_version) {
1191
+ this.expireAuthority();
1192
+ return;
1193
+ }
1194
+ this.confirm(next, response.headers.get("ETag"));
1195
+ } catch {
1196
+ this.expireAuthority();
1197
+ }
1198
+ }
1199
+ expireAuthority() {
1200
+ this.authorityGeneration += 1;
1201
+ if (this.stateValue !== "unconfirmed") this.stateValue = "unconfirmed";
1202
+ this.authorityFailures += 1;
1203
+ const delay = Math.min(RETRY_MAX_MS, RETRY_BASE_MS * 2 ** (this.authorityFailures - 1));
1204
+ this.nextAuthorityAttemptAt = Date.now() + delay;
1205
+ }
1206
+ confirm(config, etag) {
1207
+ this.authorityGeneration += 1;
1208
+ this.current = config;
1209
+ this.etag = etag;
1210
+ this.confirmedAt = Date.now();
1211
+ this.authorityFailures = 0;
1212
+ this.nextAuthorityAttemptAt = 0;
1213
+ this.stateValue = isTombstone(config) ? "tombstone" : "active";
1214
+ writeCache2(this.url, { etag, config });
1215
+ if (this.stateValue === "tombstone") {
1216
+ if (this.retryTimer !== null) {
1217
+ window.clearTimeout(this.retryTimer);
1218
+ this.retryTimer = null;
1219
+ }
1220
+ this.conversionQueue.length = 0;
1221
+ this.automaticQueue.length = 0;
1222
+ this.pageQueue.length = 0;
1223
+ }
1224
+ for (const listener of this.listeners) listener();
1225
+ }
1226
+ async flush() {
1227
+ if (this.flushInFlight) {
1228
+ this.flushRequested = true;
1229
+ return this.flushInFlight;
1230
+ }
1231
+ this.flushRequested = false;
1232
+ this.flushInFlight = this.flushNow().finally(() => {
1233
+ this.flushInFlight = null;
1234
+ if (this.flushRequested && this.stateValue === "active") void this.flush();
1235
+ });
1236
+ return this.flushInFlight;
1237
+ }
1238
+ scheduleRetry() {
1239
+ if (this.retryTimer !== null || typeof window === "undefined") return;
1240
+ this.retryTimer = window.setTimeout(() => {
1241
+ this.retryTimer = null;
1242
+ void this.flush();
1243
+ }, 1e3);
1244
+ }
1245
+ async flushNow() {
1246
+ if (!await this.ensureAuthority()) return;
1247
+ if (this.stateValue !== "active" || !this.current) return;
1248
+ const config = this.current;
1249
+ const generation = this.authorityGeneration;
1250
+ const ids = Object.values(config.gtag_ids).filter(
1251
+ (id) => typeof id === "string" && isValidGtagId(id)
1252
+ );
1253
+ if (ids.length === 0) return;
1254
+ await ensureScript(ids[0]);
1255
+ if (this.authorityGeneration !== generation || this.stateValue !== "active" || this.current !== config) {
1256
+ return;
1257
+ }
1258
+ const gtag = window.gtag;
1259
+ if (typeof gtag !== "function") return;
1260
+ try {
1261
+ if (!jsInitialized) {
1262
+ gtag("js", /* @__PURE__ */ new Date());
1263
+ jsInitialized = true;
1264
+ }
1265
+ for (const id of ids) {
1266
+ if (configuredIds.has(id)) continue;
1267
+ gtag("config", id, { send_page_view: false });
1268
+ configuredIds.add(id);
1269
+ }
1270
+ } catch {
1271
+ this.scheduleRetry();
1272
+ return;
1273
+ }
1274
+ while (this.pageQueue.length > 0) {
1275
+ const page = this.pageQueue[0];
1276
+ try {
1277
+ gtag("event", "page_view", {
1278
+ page_location: page.href,
1279
+ page_title: page.title ?? void 0,
1280
+ page_referrer: page.referrer ?? void 0
1281
+ });
1282
+ this.pageQueue.shift();
1283
+ } catch {
1284
+ this.scheduleRetry();
1285
+ return;
1286
+ }
1287
+ }
1288
+ while (this.automaticQueue.length > 0) {
1289
+ const event = this.automaticQueue[0];
1290
+ for (const goal of config.goals) {
1291
+ if (goal.kind !== "event" || !goal.firing) continue;
1292
+ if (!automaticThresholdMet(goal, event.eventType, event.metadata)) continue;
1293
+ pushBounded(this.conversionQueue, {
1294
+ key: goal.key,
1295
+ transactionId: getAutomaticTransactionId(
1296
+ event.transactionScope,
1297
+ goal.key,
1298
+ event.transactionPath
1299
+ )
1300
+ });
1301
+ }
1302
+ this.automaticQueue.shift();
1303
+ }
1304
+ while (this.conversionQueue.length > 0) {
1305
+ const item = this.conversionQueue[0];
1306
+ const goal = config.goals.find((g) => g.key === item.key);
1307
+ const firing = goal?.firing;
1308
+ if (!firing) {
1309
+ this.conversionQueue.shift();
1310
+ continue;
1311
+ }
1312
+ const currency = item.currency ?? firing.currency ?? null;
1313
+ const value = item.value ?? (firing.value_cents != null && currency ? fromMinor(firing.value_cents, currency) : null);
1314
+ const outcome = fireConversionWithConsent({
1315
+ sendTo: firing.send_to,
1316
+ value,
1317
+ currency,
1318
+ transactionId: item.transactionId ?? null
1319
+ });
1320
+ if (outcome === "retryable") {
1321
+ this.scheduleRetry();
1322
+ return;
1323
+ }
1324
+ this.conversionQueue.shift();
1325
+ }
1326
+ }
1327
+ };
1328
+ function getTrackingConfigRuntime(ref, fetchImpl) {
1329
+ const key = `${resolveTrackingConfigUrl(ref)}|${ref.businessId}|${ref.environment}`;
1330
+ const existing = runtimes.get(key);
1331
+ if (existing) return existing;
1332
+ const runtime = new TrackingConfigRuntime(ref, fetchImpl ?? globalThis.fetch);
1333
+ runtimes.set(key, runtime);
1334
+ return runtime;
1335
+ }
1336
+
1337
+ // ../tracking-core/src/resources/conversion-autofire.ts
1338
+ function currentPath() {
1339
+ return typeof window === "undefined" ? "" : window.location.pathname;
1340
+ }
1341
+ var MAX_BUFFERED_EVENTS = 50;
1342
+ function createConversionAutoFire(store) {
1343
+ const pending = [];
1344
+ let subscribed = false;
1345
+ function fireMatching(eventType, metadata, transactionScope) {
1346
+ for (const goal of store.listGoals()) {
1347
+ if (goal.kind !== "event" || !goal.firing) continue;
1348
+ if (!automaticThresholdMet(goal, eventType, metadata)) continue;
1349
+ const transactionId = getAutomaticTransactionId(transactionScope, goal.key, currentPath());
1350
+ if ("queueAutomaticEvent" in store) {
1351
+ store.fireConversion(goal.key, {
1352
+ transactionId
1353
+ });
1354
+ continue;
1355
+ }
1356
+ const firing = goal.firing;
1357
+ const cents = firing.value_cents ?? null;
1358
+ const currency = firing.currency ?? null;
1359
+ fireConversionWithConsent({
1360
+ sendTo: firing.send_to,
1361
+ value: cents != null && currency ? fromMinor(cents, currency) : null,
1362
+ currency,
1363
+ transactionId
1364
+ });
1365
+ }
1366
+ }
1367
+ return {
1368
+ onAutomaticEvent(eventType, metadata, transactionScope) {
1369
+ if ("queueAutomaticEvent" in store) {
1370
+ store.queueAutomaticEvent(eventType, metadata, currentPath(), transactionScope);
1371
+ return;
1372
+ }
1373
+ if (store.isReady()) {
1374
+ fireMatching(eventType, metadata, transactionScope);
1375
+ return;
1376
+ }
1377
+ if (pending.length < MAX_BUFFERED_EVENTS) {
1378
+ pending.push({ eventType, metadata, transactionScope });
1379
+ }
1380
+ if (!subscribed) {
1381
+ subscribed = true;
1382
+ store.onResolve(() => {
1383
+ const buffered = pending.splice(0);
1384
+ for (const event of buffered) {
1385
+ fireMatching(event.eventType, event.metadata, event.transactionScope);
1386
+ }
1387
+ });
1388
+ }
1389
+ }
1390
+ };
1391
+ }
1392
+ function withConversionAutoFire(client, autoFire) {
1393
+ return {
1394
+ ...client,
1395
+ trackEvent: (input) => {
1396
+ client.trackEvent(input);
1397
+ try {
1398
+ autoFire.onAutomaticEvent(input.eventType, input.metadata ?? {}, client.getSessionId());
1399
+ } catch {
1400
+ }
1401
+ }
1402
+ };
1403
+ }
1404
+
1405
+ // ../tracking-core/src/session.ts
1406
+ var VISITOR_STORAGE_KEY = "aranova_tracking_visitor";
1407
+ var SESSION_STORAGE_KEY = "aranova_tracking_session";
1408
+ var SESSION_IDLE_MS = 30 * 60 * 1e3;
1409
+ function safeUuid() {
1410
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function")
1411
+ return crypto.randomUUID();
1412
+ return `${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}-${Math.random().toString(16).slice(2)}`;
1413
+ }
1414
+ function readLocalStorage(key) {
1415
+ try {
1416
+ return window.localStorage.getItem(key);
1417
+ } catch {
1418
+ return null;
1419
+ }
1420
+ }
1421
+ function writeLocalStorage(key, value) {
1422
+ try {
1423
+ window.localStorage.setItem(key, value);
1424
+ } catch {
1425
+ }
1426
+ }
1427
+ function getVisitorId() {
1428
+ if (typeof window === "undefined") return safeUuid();
1429
+ const existing = readLocalStorage(VISITOR_STORAGE_KEY);
1430
+ if (existing && existing.length > 0) return existing;
1431
+ const fresh = safeUuid();
1432
+ writeLocalStorage(VISITOR_STORAGE_KEY, fresh);
1433
+ return fresh;
1434
+ }
1435
+ function getOrRotateSessionId(now = Date.now()) {
1436
+ if (typeof window === "undefined") return { id: safeUuid(), isNew: true };
1437
+ const raw = readLocalStorage(SESSION_STORAGE_KEY);
1438
+ if (raw) {
1439
+ try {
1440
+ const parsed = JSON.parse(raw);
1441
+ if (typeof parsed.id === "string" && typeof parsed.last_event_at === "number") {
1442
+ if (now - parsed.last_event_at <= SESSION_IDLE_MS) {
1443
+ const refreshed = { id: parsed.id, last_event_at: now };
1444
+ writeLocalStorage(SESSION_STORAGE_KEY, JSON.stringify(refreshed));
1445
+ return { id: parsed.id, isNew: false };
1446
+ }
1447
+ }
1448
+ } catch {
1449
+ }
1450
+ }
1451
+ const fresh = { id: safeUuid(), last_event_at: now };
1452
+ writeLocalStorage(SESSION_STORAGE_KEY, JSON.stringify(fresh));
1453
+ return { id: fresh.id, isNew: true };
1454
+ }
1455
+
1456
+ // ../tracking-core/src/events/page-view.ts
1457
+ import { z } from "zod";
1458
+ var pageViewMetadataSchema = z.object({
1459
+ page: z.object({
1460
+ title: z.string().nullable(),
1461
+ path: z.string(),
1462
+ search: z.string(),
1463
+ hash: z.string()
1464
+ }).strict(),
1465
+ referrer: z.string().nullable(),
1466
+ // `.nullable().optional()` — absent (undefined) OR explicit null OR a
1467
+ // real viewport object. Mirrors Pydantic's `_Viewport | None = None`
1468
+ // on the backend side so the drift test stays clean.
1469
+ viewport: z.object({
1470
+ w: z.number(),
1471
+ h: z.number()
1472
+ }).strict().nullable().optional()
1473
+ }).strict();
1474
+ var pageViewConfigSchema = z.object({}).strict();
1475
+
1476
+ // ../tracking-core/src/page-view.ts
1477
+ var LAST_FIRED_URL_STORAGE_KEY = "aranova_tracking_last_fired_url";
1478
+ var lastFiredUrl = null;
1479
+ var lastFiredUrlHydrated = false;
1480
+ function readSessionStorage(key) {
1481
+ try {
1482
+ if (typeof window === "undefined") return null;
1483
+ return window.sessionStorage.getItem(key);
1484
+ } catch {
1485
+ return null;
1486
+ }
1487
+ }
1488
+ function writeSessionStorage(key, value) {
1489
+ try {
1490
+ if (typeof window === "undefined") return;
1491
+ window.sessionStorage.setItem(key, value);
1492
+ } catch {
1493
+ }
1494
+ }
1495
+ function getLastFiredUrl() {
1496
+ if (!lastFiredUrlHydrated) {
1497
+ lastFiredUrlHydrated = true;
1498
+ const stored = readSessionStorage(LAST_FIRED_URL_STORAGE_KEY);
1499
+ if (stored !== null) lastFiredUrl = stored;
1500
+ }
1501
+ return lastFiredUrl;
1502
+ }
1503
+ function setLastFiredUrl(url) {
1504
+ lastFiredUrl = url;
1505
+ lastFiredUrlHydrated = true;
1506
+ writeSessionStorage(LAST_FIRED_URL_STORAGE_KEY, url);
1507
+ }
1508
+ function buildPageViewMetadata(referrerOverride) {
1509
+ if (typeof window === "undefined" || typeof document === "undefined") return null;
1510
+ return pageViewMetadataSchema.parse({
1511
+ page: {
1512
+ title: document.title || null,
1513
+ path: window.location.pathname,
1514
+ search: window.location.search,
1515
+ hash: window.location.hash
1516
+ },
1517
+ referrer: referrerOverride !== void 0 ? referrerOverride : document.referrer || null,
1518
+ viewport: { w: window.innerWidth, h: window.innerHeight }
1519
+ });
1520
+ }
1521
+ function fireManualPageView(client) {
1522
+ if (typeof window === "undefined") return;
1523
+ const currentHref = window.location.href;
1524
+ const previousFiredUrl = getLastFiredUrl();
1525
+ const internalReferrer = previousFiredUrl !== null && previousFiredUrl !== currentHref ? previousFiredUrl : null;
1526
+ const externalReferrer = typeof document !== "undefined" ? document.referrer || null : null;
1527
+ const referrer = internalReferrer ?? externalReferrer;
1528
+ const metadata = buildPageViewMetadata(referrer);
1529
+ client.trackEvent({
1530
+ eventType: "page_view",
1531
+ pageUrl: currentHref,
1532
+ metadata
1533
+ });
1534
+ if (currentHref !== previousFiredUrl) {
1535
+ setLastFiredUrl(currentHref);
1536
+ }
1537
+ }
1538
+ function attachBfcacheRestore(client) {
1539
+ if (typeof window === "undefined") return () => {
1540
+ };
1541
+ function handlePageShow(event) {
1542
+ if (!event.persisted) return;
1543
+ fireManualPageView(client);
1544
+ }
1545
+ window.addEventListener("pageshow", handlePageShow);
1546
+ return () => {
1547
+ window.removeEventListener("pageshow", handlePageShow);
1548
+ };
1549
+ }
1550
+ function attachAutoPageView(client, options = {}) {
1551
+ if (typeof window === "undefined" || typeof history === "undefined") {
1552
+ return () => {
1553
+ };
1554
+ }
1555
+ let lastPath = window.location.pathname + window.location.search;
1556
+ function maybeFire() {
1557
+ const current = window.location.pathname + window.location.search;
1558
+ if (current === lastPath) return;
1559
+ lastPath = current;
1560
+ fireManualPageView(client);
1561
+ }
1562
+ const originalPushState = history.pushState.bind(history);
1563
+ const originalReplaceState = history.replaceState.bind(history);
1564
+ function patchedPushState(...args) {
1565
+ originalPushState(...args);
1566
+ setTimeout(maybeFire, 0);
1567
+ }
1568
+ function patchedReplaceState(...args) {
1569
+ originalReplaceState(...args);
1570
+ setTimeout(maybeFire, 0);
1571
+ }
1572
+ function handlePageShow(event) {
1573
+ if (!event.persisted) return;
1574
+ fireManualPageView(client);
1575
+ }
1576
+ history.pushState = patchedPushState;
1577
+ history.replaceState = patchedReplaceState;
1578
+ window.addEventListener("popstate", maybeFire);
1579
+ window.addEventListener("pageshow", handlePageShow);
1580
+ if (!options.skipInitial) fireManualPageView(client);
1581
+ return () => {
1582
+ history.pushState = originalPushState;
1583
+ history.replaceState = originalReplaceState;
1584
+ window.removeEventListener("popstate", maybeFire);
1585
+ window.removeEventListener("pageshow", handlePageShow);
1586
+ };
1587
+ }
1588
+
1589
+ // ../tracking-core/src/heartbeat.ts
1590
+ function serializeValue(value) {
1591
+ if (value instanceof RegExp) return value.source;
1592
+ if (Array.isArray(value)) return value.map(serializeValue);
1593
+ if (value !== null && typeof value === "object") {
1594
+ const out = {};
1595
+ for (const [k, v] of Object.entries(value)) {
1596
+ out[k] = serializeValue(v);
1597
+ }
1598
+ return out;
1599
+ }
1600
+ return value;
1601
+ }
1602
+ function buildHeartbeatMetadata(surface, sdkVersion, packageName, triggers, gtagIds = null) {
1603
+ const automaticNames = triggers ? Object.keys(triggers.automatic) : [];
1604
+ const manualNames = triggers?.manual ? Object.keys(triggers.manual) : [];
1605
+ let triggerConfig = null;
1606
+ if (triggers) {
1607
+ const cfg = {};
1608
+ for (const [name, config] of Object.entries(triggers.automatic)) {
1609
+ const serialized = serializeValue(config);
1610
+ if (Object.keys(serialized).length > 0) {
1611
+ cfg[name] = serialized;
1612
+ }
1613
+ }
1614
+ if (triggers.manual) {
1615
+ for (const [name, config] of Object.entries(triggers.manual)) {
1616
+ if (config === void 0) continue;
1617
+ const serialized = serializeValue(config);
1618
+ if (Object.keys(serialized).length > 0) {
1619
+ cfg[name] = serialized;
1620
+ }
1621
+ }
1622
+ }
1623
+ if (Object.keys(cfg).length > 0) {
1624
+ triggerConfig = cfg;
1625
+ }
1626
+ }
1627
+ return {
1628
+ sdk_version: sdkVersion ?? "unknown",
1629
+ package_name: packageName,
1630
+ surface,
1631
+ triggers: {
1632
+ automatic: automaticNames,
1633
+ manual: manualNames
1634
+ },
1635
+ trigger_config: triggerConfig,
1636
+ configured_gtag_ids: gtagIds
1637
+ };
1638
+ }
1639
+
1640
+ // ../tracking-core/src/ingest.ts
1641
+ var DEFAULT_FLUSH_INTERVAL_MS = 2e3;
1642
+ var DEFAULT_MAX_QUEUE_SIZE = 10;
1643
+ var HARD_MAX_BATCH = 50;
1644
+ var MAX_RETRY_BACKOFF_MS = 6e4;
1645
+ var MAX_BUFFERED_EVENTS2 = 200;
1646
+ var RETRY_BUFFER_KEY_PREFIX = "aranova_tracking_pending_v1";
1647
+ var API_KEY_HEADER = "X-Aranova-Api-Key";
1648
+ var SDK_VERSION_HEADER = "X-Aranova-Sdk-Version";
1649
+ var SDK_PACKAGE_HEADER = "X-Aranova-Sdk-Package";
1650
+ var SDK_SURFACE_HEADER = "X-Aranova-Sdk-Surface";
1651
+ var SDK_ENVIRONMENT_HEADER = "X-Aranova-Sdk-Environment";
1652
+ function buildContext(surface, sdkVersion, packageName, environment, activeGtagIds) {
1653
+ return {
1654
+ surface,
1655
+ sdk_version: sdkVersion,
1656
+ package_name: packageName,
1657
+ site_origin: typeof window === "undefined" ? null : window.location.origin,
1658
+ page_title: typeof document === "undefined" ? null : document.title || null,
1659
+ referrer: typeof document === "undefined" ? null : document.referrer || null,
1660
+ environment,
1661
+ active_gtag_ids: activeGtagIds,
1662
+ // Rebuilt per flush (this runs inside the payload builder), so a client
1663
+ // constructed later on a deeper route still gets reported.
1664
+ capabilities: getRegisteredCapabilities()
1665
+ };
1666
+ }
1667
+ function readTrackingParams() {
1668
+ if (typeof window === "undefined") return createEmptyTrackingParams();
1669
+ try {
1670
+ captureTrackingParamsFromLocation();
1671
+ } catch {
1672
+ }
1673
+ return getTrackingParamsFromCookieReader(getCookieValueFromDocument);
1674
+ }
1675
+ function consentSnapshot() {
1676
+ try {
1677
+ const choice = getConsentChoice();
1678
+ return {
1679
+ state: choice.state,
1680
+ source: choice.source,
1681
+ updated_at: choice.updatedAt,
1682
+ expires_at: choice.expiresAt
1683
+ };
1684
+ } catch {
1685
+ return null;
1686
+ }
1687
+ }
1688
+ async function postWithFetch(url, body, apiKey, identity, keepalive) {
1689
+ if (typeof fetch !== "function") return "drop";
1690
+ try {
1691
+ const response = await fetch(url, {
1692
+ method: "POST",
1693
+ headers: {
1694
+ "Content-Type": "application/json",
1695
+ [API_KEY_HEADER]: apiKey,
1696
+ [SDK_VERSION_HEADER]: identity.sdkVersion,
1697
+ [SDK_PACKAGE_HEADER]: identity.packageName,
1698
+ [SDK_SURFACE_HEADER]: identity.surface,
1699
+ [SDK_ENVIRONMENT_HEADER]: identity.environment
1700
+ },
1701
+ body,
1702
+ keepalive,
1703
+ // CORS is open on the tracking endpoint; never send cookies.
1704
+ credentials: "omit",
1705
+ mode: "cors"
1706
+ });
1707
+ if (response.ok) return "ok";
1708
+ if (response.status === 408 || response.status === 429 || response.status >= 500) {
1709
+ return "retry";
1710
+ }
1711
+ return "drop";
1712
+ } catch {
1713
+ return "retry";
1714
+ }
1715
+ }
1716
+ function retryBufferKey(apiKey, endpoint) {
1717
+ return `${RETRY_BUFFER_KEY_PREFIX}:${apiKey}:${endpoint}`;
1718
+ }
1719
+ function readPendingBatches(key) {
1720
+ if (typeof window === "undefined") return [];
1721
+ try {
1722
+ const raw = window.localStorage.getItem(key);
1723
+ if (!raw) return [];
1724
+ const parsed = JSON.parse(raw);
1725
+ if (!Array.isArray(parsed)) return [];
1726
+ return parsed.filter(
1727
+ (entry) => typeof entry === "object" && entry !== null && "session" in entry && Array.isArray(entry.events)
1728
+ );
1729
+ } catch {
1730
+ return [];
1731
+ }
1732
+ }
1733
+ function writePendingBatches(key, batches) {
1734
+ if (typeof window === "undefined") return;
1735
+ try {
1736
+ if (batches.length === 0) window.localStorage.removeItem(key);
1737
+ else window.localStorage.setItem(key, JSON.stringify(batches));
1738
+ } catch {
1739
+ }
1740
+ }
1741
+ function trimToBufferCap(batches) {
1742
+ let total = batches.reduce((sum, batch) => sum + batch.events.length, 0);
1743
+ const trimmed = batches.slice();
1744
+ while (total > MAX_BUFFERED_EVENTS2 && trimmed.length > 1) {
1745
+ const dropped = trimmed.shift();
1746
+ total -= dropped ? dropped.events.length : 0;
1747
+ }
1748
+ return trimmed;
1749
+ }
1750
+ var globalClient = null;
1751
+ var globalClientKey = null;
1752
+ function clientConfigKey(config) {
1753
+ return `${config.apiKey}@${config.endpoint}#${config.surface}`;
1754
+ }
1755
+ function getOrCreateTrackingClient(config) {
1756
+ const key = clientConfigKey(config);
1757
+ if (globalClient !== null && globalClientKey === key) {
1758
+ return globalClient;
1759
+ }
1760
+ if (globalClient !== null) {
1761
+ globalClient.destroy();
1762
+ }
1763
+ globalClient = createTrackingClient(config);
1764
+ globalClientKey = key;
1765
+ return globalClient;
1766
+ }
1767
+ var clientCaptureRegistry = /* @__PURE__ */ new WeakMap();
1768
+ function attachClientCapturesOnce(client, build) {
1769
+ let entry = clientCaptureRegistry.get(client);
1770
+ if (entry === void 0) {
1771
+ entry = { detach: build(), refCount: 0 };
1772
+ clientCaptureRegistry.set(client, entry);
1773
+ }
1774
+ entry.refCount += 1;
1775
+ let released = false;
1776
+ return () => {
1777
+ if (released) return;
1778
+ released = true;
1779
+ const current = clientCaptureRegistry.get(client);
1780
+ if (current === void 0) return;
1781
+ current.refCount -= 1;
1782
+ if (current.refCount <= 0) {
1783
+ current.detach();
1784
+ clientCaptureRegistry.delete(client);
1785
+ }
1786
+ };
1787
+ }
1788
+ function createTrackingClient(config) {
1789
+ const flushIntervalMs = config.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS;
1790
+ const maxQueueSize = Math.min(config.maxQueueSize ?? DEFAULT_MAX_QUEUE_SIZE, HARD_MAX_BATCH);
1791
+ const sdkVersion = config.sdkVersion ?? null;
1792
+ const packageName = config.packageName ?? null;
1793
+ const environment = config.environment ?? "production";
1794
+ const activeGtagIds = config.activeGtagIds ?? null;
1795
+ const endpointBase = config.endpoint.replace(/\/$/, "");
1796
+ const eventsUrl = `${endpointBase}/events`;
1797
+ const identityHeaders = {
1798
+ sdkVersion: sdkVersion ?? "",
1799
+ packageName: packageName ?? "",
1800
+ surface: config.surface,
1801
+ environment
1802
+ };
1803
+ let queue = [];
1804
+ let flushTimer = null;
1805
+ const bufferKey = retryBufferKey(config.apiKey, endpointBase);
1806
+ let pending = readPendingBatches(bufferKey);
1807
+ let flushChain = Promise.resolve();
1808
+ let retryAttempt = 0;
1809
+ let firstPage = null;
1810
+ let initialParams = createEmptyTrackingParams();
1811
+ let destroyed = false;
1812
+ const visitorId = getVisitorId();
1813
+ const initialSession = getOrRotateSessionId();
1814
+ let sessionId = initialSession.id;
1815
+ if (typeof window !== "undefined") {
1816
+ firstPage = window.location.href;
1817
+ try {
1818
+ initialParams = captureTrackingParamsFromLocation();
1819
+ } catch {
1820
+ }
1821
+ getOrCaptureLandingParams(sessionId);
1822
+ try {
1823
+ captureFbc();
1824
+ } catch {
1825
+ }
1826
+ }
1827
+ function enqueueHeartbeat() {
1828
+ const metadata = buildHeartbeatMetadata(
1829
+ config.surface,
1830
+ sdkVersion,
1831
+ packageName,
1832
+ config.triggers ?? null,
1833
+ activeGtagIds
1834
+ );
1835
+ queue.push({
1836
+ event_type: "sdk_heartbeat",
1837
+ page_url: typeof window === "undefined" ? null : window.location.href,
1838
+ metadata,
1839
+ occurred_at: (/* @__PURE__ */ new Date()).toISOString()
1840
+ });
1841
+ }
1842
+ if (initialSession.isNew) {
1843
+ enqueueHeartbeat();
1844
+ }
1845
+ if (pending.length > 0) {
1846
+ scheduleFlush();
1847
+ }
1848
+ function buildSessionPayload() {
1849
+ const rotated = getOrRotateSessionId();
1850
+ if (rotated.isNew && rotated.id !== sessionId) {
1851
+ enqueueHeartbeat();
1852
+ }
1853
+ sessionId = rotated.id;
1854
+ const params = mergeTrackingParams(readTrackingParams(), initialParams);
1855
+ const context = buildContext(
1856
+ config.surface,
1857
+ sdkVersion,
1858
+ packageName,
1859
+ environment,
1860
+ activeGtagIds
1861
+ );
1862
+ return {
1863
+ session_id: sessionId,
1864
+ visitor_id: visitorId,
1865
+ gclid: params.gclid,
1866
+ wbraid: params.wbraid,
1867
+ gbraid: params.gbraid,
1868
+ ylpcid: params.ylpcid,
1869
+ fbclid: params.fbclid,
1870
+ fbc: getFbcCookie(),
1871
+ fbp: getFbpCookie(),
1872
+ utm_source: params.utm_source,
1873
+ utm_medium: params.utm_medium,
1874
+ utm_campaign: params.utm_campaign,
1875
+ utm_term: params.utm_term,
1876
+ utm_content: params.utm_content,
1877
+ // Landing params for the CURRENT session id — captured on the spot when
1878
+ // the session just rotated (the current URL is the rotated session's
1879
+ // landing), reused from the stored record otherwise. Keys are omitted
1880
+ // entirely when the landing isn't observable (SSR).
1881
+ ...buildLandingPayloadFields(sessionId),
1882
+ first_page: firstPage,
1883
+ consent_state: consentSnapshot(),
1884
+ context
1885
+ };
1886
+ }
1887
+ function scheduleFlush(delayMs = flushIntervalMs) {
1888
+ if (flushTimer !== null || destroyed) return;
1889
+ flushTimer = setTimeout(() => {
1890
+ flushTimer = null;
1891
+ void flush();
1892
+ }, delayMs);
1893
+ }
1894
+ function clearScheduledFlush() {
1895
+ if (flushTimer !== null) {
1896
+ clearTimeout(flushTimer);
1897
+ flushTimer = null;
1898
+ }
1899
+ }
1900
+ function bufferQueued() {
1901
+ if (queue.length === 0) return;
1902
+ const events = queue.slice(0, HARD_MAX_BATCH);
1903
+ queue = queue.slice(events.length);
1904
+ pending = trimToBufferCap([...pending, { session: buildSessionPayload(), events }]);
1905
+ writePendingBatches(bufferKey, pending);
1906
+ }
1907
+ function flush() {
1908
+ flushChain = flushChain.then(runFlush).catch(() => {
1909
+ });
1910
+ return flushChain;
1911
+ }
1912
+ async function runFlush() {
1913
+ if (destroyed) return;
1914
+ clearScheduledFlush();
1915
+ bufferQueued();
1916
+ if (pending.length === 0) return;
1917
+ try {
1918
+ while (pending.length > 0) {
1919
+ const batch = pending[0];
1920
+ const body = { session: batch.session, events: batch.events };
1921
+ const outcome = await postWithFetch(
1922
+ eventsUrl,
1923
+ JSON.stringify(body),
1924
+ config.apiKey,
1925
+ identityHeaders,
1926
+ false
1927
+ );
1928
+ if (outcome === "retry") {
1929
+ retryAttempt += 1;
1930
+ return;
1931
+ }
1932
+ pending = pending.slice(1);
1933
+ writePendingBatches(bufferKey, pending);
1934
+ retryAttempt = 0;
1935
+ }
1936
+ } finally {
1937
+ if (pending.length > 0) {
1938
+ const backoff = Math.min(flushIntervalMs * 2 ** retryAttempt, MAX_RETRY_BACKOFF_MS);
1939
+ scheduleFlush(backoff);
1940
+ } else if (queue.length > 0) {
1941
+ scheduleFlush();
1942
+ }
1943
+ }
1944
+ }
1945
+ function trackEvent(input) {
1946
+ if (destroyed) return;
1947
+ if (!input || typeof input.eventType !== "string" || input.eventType.length === 0) return;
1948
+ if (input.eventType === "form_submit" && getConsentState() !== "denied") {
1949
+ try {
1950
+ const fields = input.metadata?.form?.fields;
1951
+ if (fields) stashUserDataFromFormFields(fields, config.phone?.defaultCountry);
1952
+ } catch {
1953
+ }
1954
+ }
1955
+ const occurredAt = input.occurredAt instanceof Date ? input.occurredAt.toISOString() : typeof input.occurredAt === "string" ? input.occurredAt : (/* @__PURE__ */ new Date()).toISOString();
1956
+ queue.push({
1957
+ event_type: input.eventType,
1958
+ page_url: input.pageUrl ?? (typeof window === "undefined" ? null : window.location.href),
1959
+ metadata: input.metadata ?? null,
1960
+ occurred_at: occurredAt
1961
+ });
1962
+ if (queue.length >= maxQueueSize) {
1963
+ void flush();
1964
+ } else {
1965
+ scheduleFlush();
1966
+ }
1967
+ }
1968
+ function flushOnUnload() {
1969
+ bufferQueued();
1970
+ clearScheduledFlush();
1971
+ if (pending.length === 0) return;
1972
+ const batch = pending[0];
1973
+ pending = pending.slice(1);
1974
+ writePendingBatches(bufferKey, pending);
1975
+ const body = { session: batch.session, events: batch.events };
1976
+ void postWithFetch(eventsUrl, JSON.stringify(body), config.apiKey, identityHeaders, true);
1977
+ }
1978
+ if (typeof window !== "undefined") {
1979
+ window.addEventListener("pagehide", flushOnUnload);
1980
+ window.addEventListener("visibilitychange", () => {
1981
+ if (document.visibilityState === "hidden") flushOnUnload();
1982
+ });
1983
+ }
1984
+ return {
1985
+ trackEvent,
1986
+ flush,
1987
+ flushBeacon: flushOnUnload,
1988
+ getSessionId: () => sessionId,
1989
+ getVisitorId: () => visitorId,
1990
+ destroy: () => {
1991
+ destroyed = true;
1992
+ if (queue.length > 0) {
1993
+ flushOnUnload();
1994
+ }
1995
+ clearScheduledFlush();
1996
+ queue = [];
1997
+ if (typeof window !== "undefined") {
1998
+ window.removeEventListener("pagehide", flushOnUnload);
1999
+ }
2000
+ }
2001
+ };
2002
+ }
2003
+
2004
+ // ../tracking-core/src/events/cta-click.ts
2005
+ import { z as z2 } from "zod";
2006
+ var ctaClickMetadataSchema = z2.object({
2007
+ cta_name: z2.string(),
2008
+ page: z2.object({
2009
+ path: z2.string()
2010
+ }).strict(),
2011
+ section: z2.string().nullable().optional(),
2012
+ destination_url: z2.string().nullable().optional(),
2013
+ // Set by auto-capture (and available to manual callers): the link target
2014
+ // and a short element descriptor (tag#id) for tying clicks to specific UI.
2015
+ href: z2.string().nullable().optional(),
2016
+ element: z2.string().nullable().optional()
2017
+ }).strict();
2018
+ var ctaClickConfigSchema = z2.object({
2019
+ autoCapture: z2.object({
2020
+ selector: z2.string().optional()
2021
+ }).strict().optional()
2022
+ }).strict();
2023
+
2024
+ // ../tracking-core/src/events/sdk-heartbeat.ts
2025
+ import { z as z3 } from "zod";
2026
+ var sdkHeartbeatTriggersSchema = z3.object({
2027
+ automatic: z3.array(z3.string()),
2028
+ manual: z3.array(z3.string())
2029
+ }).strict();
2030
+ var sdkHeartbeatMetadataSchema = z3.object({
2031
+ sdk_version: z3.string(),
2032
+ package_name: z3.string().nullable(),
2033
+ surface: z3.enum(["next", "react", "script"]),
2034
+ triggers: sdkHeartbeatTriggersSchema,
2035
+ trigger_config: z3.record(z3.string(), z3.record(z3.string(), z3.unknown())).nullable().optional(),
2036
+ configured_gtag_ids: z3.record(z3.string(), z3.string()).nullable().optional()
2037
+ }).strict();
2038
+ var sdkHeartbeatConfigSchema = z3.object({}).strict();
2039
+
2040
+ // ../tracking-core/src/events/form-start.ts
2041
+ import { z as z4 } from "zod";
2042
+ var formStartMetadataSchema = z4.object({
2043
+ form: z4.object({
2044
+ id: z4.string(),
2045
+ action: z4.string().nullable()
2046
+ }).strict(),
2047
+ page: z4.object({
2048
+ path: z4.string()
2049
+ }).strict()
2050
+ }).strict();
2051
+ var formStartConfigSchema = z4.object({
2052
+ selector: z4.string().optional()
2053
+ }).strict();
2054
+
2055
+ // ../tracking-core/src/events/form-submit.ts
2056
+ import { z as z5 } from "zod";
2057
+ var jsonValueSchema = z5.lazy(
2058
+ () => z5.union([
2059
+ z5.string(),
2060
+ z5.number().finite(),
2061
+ z5.boolean(),
2062
+ z5.null(),
2063
+ z5.array(jsonValueSchema),
2064
+ z5.record(jsonValueSchema)
2065
+ ])
2066
+ );
2067
+ var formSubmitMetadataSchema = z5.object({
2068
+ form: z5.object({
2069
+ id: z5.string(),
2070
+ action: z5.string().nullable(),
2071
+ fields: z5.array(
2072
+ z5.object({
2073
+ name: z5.string(),
2074
+ type: z5.string(),
2075
+ label: z5.string().nullable(),
2076
+ value: jsonValueSchema
2077
+ }).strict()
2078
+ ).optional()
2079
+ }).strict(),
2080
+ page: z5.object({
2081
+ path: z5.string()
2082
+ }).strict()
2083
+ }).strict();
2084
+ var formSubmitConfigSchema = z5.object({}).strict();
2085
+
2086
+ // ../tracking-core/src/events/multi-page-session.ts
2087
+ import { z as z6 } from "zod";
2088
+ var multiPageSessionMetadataSchema = z6.object({
2089
+ page_count: z6.number().int().min(2),
2090
+ page: z6.object({
2091
+ path: z6.string()
2092
+ }).strict()
2093
+ }).strict();
2094
+ var multiPageSessionConfigSchema = z6.object({
2095
+ pageThreshold: z6.number().int().min(2)
2096
+ }).strict();
2097
+
2098
+ // ../tracking-core/src/events/page-exit.ts
2099
+ import { z as z7 } from "zod";
2100
+ var pageExitMetadataSchema = z7.object({
2101
+ dwell_ms: z7.number().int().min(0),
2102
+ // null = left without any scroll signal; floor is 0 so a valid 0% is never
2103
+ // rejected (a single bad field 422s the whole keepalive beacon batch).
2104
+ max_scroll_percent: z7.number().int().min(0).max(100).nullable(),
2105
+ // The gating baseline: the fraction of the page visible at load with
2106
+ // zero scrolling — or, for pages that grew after the post-paint snapshot
2107
+ // (skeleton/streaming renders), the first-scroll position that
2108
+ // established it. null = page had no scrollable range, or the segment
2109
+ // ended before the snapshot. `.optional()` is load-bearing: SDK builds
2110
+ // predating this field keep POSTing page_exit without the key —
2111
+ // requiring it would 422 whole keepalive beacon batches.
2112
+ scroll_baseline_percent: z7.number().int().min(0).max(100).nullable().optional(),
2113
+ page: z7.object({
2114
+ path: z7.string()
2115
+ }).strict()
2116
+ }).strict();
2117
+ var pageExitConfigSchema = z7.object({}).strict();
2118
+
2119
+ // ../tracking-core/src/events/phone-click.ts
2120
+ import { z as z8 } from "zod";
2121
+ var phoneClickMetadataSchema = z8.object({
2122
+ phone_number: z8.string(),
2123
+ page: z8.object({
2124
+ path: z8.string()
2125
+ }).strict(),
2126
+ section: z8.string().nullable().optional()
2127
+ }).strict();
2128
+ var phoneClickConfigSchema = z8.object({
2129
+ autoCapture: z8.object({
2130
+ selector: z8.string().optional()
2131
+ }).strict().optional()
2132
+ }).strict();
2133
+
2134
+ // ../tracking-core/src/events/scroll-depth.ts
2135
+ import { z as z9 } from "zod";
2136
+ var scrollDepthMetadataSchema = z9.object({
2137
+ depth_percent: z9.number().int().min(1).max(100),
2138
+ page: z9.object({
2139
+ path: z9.string()
2140
+ }).strict()
2141
+ }).strict();
2142
+ var scrollDepthConfigSchema = z9.object({
2143
+ thresholds: z9.array(z9.number().int().min(1).max(100)).min(1)
2144
+ }).strict();
2145
+
2146
+ // ../tracking-core/src/events/specific-page-visit.ts
2147
+ import { z as z10 } from "zod";
2148
+ var PAGE_IDENTITY_MAX_LENGTH = 64;
2149
+ var PAGE_IDENTITY_PATTERN = /^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/;
2150
+ var pageIdentitySchema = z10.string().max(PAGE_IDENTITY_MAX_LENGTH).regex(PAGE_IDENTITY_PATTERN, {
2151
+ message: "page identity must be lowercase snake_case, start with a letter, and contain at most 64 characters"
2152
+ });
2153
+ var specificPageNameSchema = pageIdentitySchema;
2154
+ var specificPageVisitMetadataSchema = z10.object({
2155
+ page_name: specificPageNameSchema,
2156
+ page: z10.object({
2157
+ path: z10.string()
2158
+ }).strict()
2159
+ }).strict();
2160
+ var specificPageVisitConfigSchema = z10.object({
2161
+ pages: z10.array(
2162
+ z10.object({
2163
+ name: specificPageNameSchema,
2164
+ pathPattern: z10.custom((value) => value instanceof RegExp, {
2165
+ message: "pathPattern must be a RegExp"
2166
+ })
2167
+ }).strict()
2168
+ ).min(1)
2169
+ }).strict();
2170
+
2171
+ // ../tracking-core/src/events/time-on-site.ts
2172
+ import { z as z11 } from "zod";
2173
+ var timeOnSiteMetadataSchema = z11.object({
2174
+ duration_ms: z11.number().int().nonnegative(),
2175
+ page: z11.object({
2176
+ path: z11.string()
2177
+ }).strict()
2178
+ }).strict();
2179
+ var timeOnSiteConfigSchema = z11.object({
2180
+ thresholdSeconds: z11.number().int().positive()
2181
+ }).strict();
2182
+
2183
+ // ../tracking-core/src/events/semantics.ts
2184
+ var EVENT_SEMANTICS = {
2185
+ page_view: {
2186
+ label: "Page view",
2187
+ category: "page",
2188
+ outcomeRole: "navigation",
2189
+ clientVisibility: "simple"
2190
+ },
2191
+ time_on_site: {
2192
+ label: "Time on site",
2193
+ category: "engagement",
2194
+ outcomeRole: "engagement",
2195
+ clientVisibility: "detailed"
2196
+ },
2197
+ specific_page_visit: {
2198
+ label: "Key page visit",
2199
+ category: "engagement",
2200
+ outcomeRole: "engagement",
2201
+ clientVisibility: "detailed"
2202
+ },
2203
+ scroll_depth: {
2204
+ label: "Scroll depth",
2205
+ category: "engagement",
2206
+ outcomeRole: "engagement",
2207
+ clientVisibility: "detailed"
2208
+ },
2209
+ multi_page_session: {
2210
+ label: "Multi-page session",
2211
+ category: "engagement",
2212
+ outcomeRole: "engagement",
2213
+ clientVisibility: "detailed"
2214
+ },
2215
+ form_start: {
2216
+ label: "Form started",
2217
+ category: "engagement",
2218
+ outcomeRole: "engagement",
2219
+ clientVisibility: "simple"
2220
+ },
2221
+ sdk_heartbeat: {
2222
+ label: "SDK heartbeat",
2223
+ category: "system",
2224
+ outcomeRole: "diagnostic",
2225
+ clientVisibility: "hidden"
2226
+ },
2227
+ page_exit: {
2228
+ label: "Page exit",
2229
+ category: "engagement",
2230
+ outcomeRole: "diagnostic",
2231
+ clientVisibility: "detailed"
2232
+ },
2233
+ form_submit: {
2234
+ label: "Form submitted",
2235
+ category: "lead",
2236
+ outcomeRole: "lead",
2237
+ clientVisibility: "simple"
2238
+ },
2239
+ phone_click: {
2240
+ label: "Phone click",
2241
+ category: "lead",
2242
+ outcomeRole: "lead",
2243
+ clientVisibility: "simple"
2244
+ },
2245
+ cta_click: {
2246
+ label: "CTA click",
2247
+ category: "engagement",
2248
+ outcomeRole: "engagement",
2249
+ clientVisibility: "simple"
2250
+ }
2251
+ };
2252
+
2253
+ // ../tracking-core/src/events/registry.ts
2254
+ var EVENT_REGISTRY = {
2255
+ // --- automatic triggers ---
2256
+ page_view: {
2257
+ kind: "automatic",
2258
+ semantics: EVENT_SEMANTICS.page_view,
2259
+ metadataSchema: pageViewMetadataSchema,
2260
+ configSchema: pageViewConfigSchema
2261
+ },
2262
+ time_on_site: {
2263
+ kind: "automatic",
2264
+ semantics: EVENT_SEMANTICS.time_on_site,
2265
+ metadataSchema: timeOnSiteMetadataSchema,
2266
+ configSchema: timeOnSiteConfigSchema
2267
+ },
2268
+ specific_page_visit: {
2269
+ kind: "automatic",
2270
+ semantics: EVENT_SEMANTICS.specific_page_visit,
2271
+ metadataSchema: specificPageVisitMetadataSchema,
2272
+ configSchema: specificPageVisitConfigSchema
2273
+ },
2274
+ scroll_depth: {
2275
+ kind: "automatic",
2276
+ semantics: EVENT_SEMANTICS.scroll_depth,
2277
+ metadataSchema: scrollDepthMetadataSchema,
2278
+ configSchema: scrollDepthConfigSchema
2279
+ },
2280
+ multi_page_session: {
2281
+ kind: "automatic",
2282
+ semantics: EVENT_SEMANTICS.multi_page_session,
2283
+ metadataSchema: multiPageSessionMetadataSchema,
2284
+ configSchema: multiPageSessionConfigSchema
2285
+ },
2286
+ form_start: {
2287
+ kind: "automatic",
2288
+ semantics: EVENT_SEMANTICS.form_start,
2289
+ metadataSchema: formStartMetadataSchema,
2290
+ configSchema: formStartConfigSchema
2291
+ },
2292
+ // --- SDK-internal automatic (not consumer-configurable) ---
2293
+ sdk_heartbeat: {
2294
+ kind: "automatic",
2295
+ semantics: EVENT_SEMANTICS.sdk_heartbeat,
2296
+ metadataSchema: sdkHeartbeatMetadataSchema,
2297
+ configSchema: sdkHeartbeatConfigSchema
2298
+ },
2299
+ page_exit: {
2300
+ kind: "automatic",
2301
+ semantics: EVENT_SEMANTICS.page_exit,
2302
+ metadataSchema: pageExitMetadataSchema,
2303
+ configSchema: pageExitConfigSchema
2304
+ },
2305
+ // --- manual triggers ---
2306
+ form_submit: {
2307
+ kind: "manual",
2308
+ semantics: EVENT_SEMANTICS.form_submit,
2309
+ metadataSchema: formSubmitMetadataSchema,
2310
+ configSchema: formSubmitConfigSchema
2311
+ },
2312
+ phone_click: {
2313
+ kind: "manual",
2314
+ semantics: EVENT_SEMANTICS.phone_click,
2315
+ metadataSchema: phoneClickMetadataSchema,
2316
+ configSchema: phoneClickConfigSchema
2317
+ },
2318
+ cta_click: {
2319
+ kind: "manual",
2320
+ semantics: EVENT_SEMANTICS.cta_click,
2321
+ metadataSchema: ctaClickMetadataSchema,
2322
+ configSchema: ctaClickConfigSchema
2323
+ }
2324
+ };
2325
+ var ALL_AUTOMATIC_EVENT_NAMES = Object.entries(EVENT_REGISTRY).filter(([, def]) => def.kind === "automatic").map(([name]) => name);
2326
+ var ALL_MANUAL_EVENT_NAMES = Object.entries(EVENT_REGISTRY).filter(([, def]) => def.kind === "manual").map(([name]) => name);
2327
+ var ALL_LEAD_EVENT_NAMES = Object.entries(EVENT_REGISTRY).filter(([, def]) => def.semantics.outcomeRole === "lead").map(([name]) => name);
2328
+ function getEventDefinition(name) {
2329
+ return EVENT_REGISTRY[name];
2330
+ }
2331
+
2332
+ // ../tracking-core/src/ingest-typed.ts
2333
+ function createTypedClient(raw, registry, options = {}) {
2334
+ const debug = options.debug ?? false;
2335
+ if (registry.manual?.form_submit) registerCapability("form_capture");
2336
+ return {
2337
+ trackEvent(eventType, metadata, opts) {
2338
+ if (debug) {
2339
+ const def = getEventDefinition(eventType);
2340
+ def.metadataSchema.parse(metadata);
2341
+ }
2342
+ raw.trackEvent({
2343
+ eventType,
2344
+ metadata,
2345
+ pageUrl: opts?.pageUrl ?? null,
2346
+ occurredAt: opts?.occurredAt ?? null
2347
+ });
2348
+ },
2349
+ flush: raw.flush.bind(raw),
2350
+ getSessionId: raw.getSessionId.bind(raw),
2351
+ getVisitorId: raw.getVisitorId.bind(raw)
2352
+ };
2353
+ }
2354
+
2355
+ // ../tracking-core/src/triggers/time-on-site.ts
2356
+ function attachTimeOnSite(client, config) {
2357
+ if (typeof window === "undefined" || typeof document === "undefined") {
2358
+ return () => {
2359
+ };
2360
+ }
2361
+ const thresholdMs = config.thresholdSeconds * 1e3;
2362
+ let accumulatedMs = 0;
2363
+ let activeSince = document.visibilityState === "visible" ? Date.now() : null;
2364
+ let timer = null;
2365
+ let fired = false;
2366
+ function fire() {
2367
+ if (fired) return;
2368
+ fired = true;
2369
+ client.trackEvent({
2370
+ eventType: "time_on_site",
2371
+ metadata: {
2372
+ duration_ms: thresholdMs,
2373
+ page: { path: window.location.pathname }
2374
+ },
2375
+ pageUrl: window.location.href,
2376
+ occurredAt: null
2377
+ });
2378
+ }
2379
+ function scheduleNext() {
2380
+ if (fired || activeSince === null) return;
2381
+ const remaining = thresholdMs - accumulatedMs;
2382
+ if (remaining <= 0) {
2383
+ fire();
2384
+ return;
2385
+ }
2386
+ timer = setTimeout(fire, remaining);
2387
+ }
2388
+ function clearTimer() {
2389
+ if (timer !== null) {
2390
+ clearTimeout(timer);
2391
+ timer = null;
2392
+ }
2393
+ }
2394
+ function onVisibilityChange() {
2395
+ if (fired) return;
2396
+ if (document.visibilityState === "hidden") {
2397
+ if (activeSince !== null) {
2398
+ accumulatedMs += Date.now() - activeSince;
2399
+ activeSince = null;
2400
+ }
2401
+ clearTimer();
2402
+ } else {
2403
+ activeSince = Date.now();
2404
+ scheduleNext();
2405
+ }
2406
+ }
2407
+ document.addEventListener("visibilitychange", onVisibilityChange);
2408
+ scheduleNext();
2409
+ return () => {
2410
+ clearTimer();
2411
+ document.removeEventListener("visibilitychange", onVisibilityChange);
2412
+ };
2413
+ }
2414
+
2415
+ // ../tracking-core/src/triggers/specific-page-visit.ts
2416
+ function attachSpecificPageVisit(client, config) {
2417
+ if (typeof window === "undefined" || typeof history === "undefined") {
2418
+ return () => {
2419
+ };
2420
+ }
2421
+ const { pages } = config;
2422
+ const firedSet = /* @__PURE__ */ new Set();
2423
+ function check() {
2424
+ const path = window.location.pathname;
2425
+ for (const { name, pathPattern } of pages) {
2426
+ pathPattern.lastIndex = 0;
2427
+ if (!pathPattern.test(path)) continue;
2428
+ const key = `${name}:${path}`;
2429
+ if (firedSet.has(key)) continue;
2430
+ firedSet.add(key);
2431
+ client.trackEvent({
2432
+ eventType: "specific_page_visit",
2433
+ metadata: { page_name: name, page: { path } },
2434
+ pageUrl: window.location.href,
2435
+ occurredAt: null
2436
+ });
2437
+ }
2438
+ }
2439
+ const originalPushState = history.pushState.bind(history);
2440
+ const originalReplaceState = history.replaceState.bind(history);
2441
+ function patchedPushState(...args) {
2442
+ originalPushState(...args);
2443
+ setTimeout(check, 0);
2444
+ }
2445
+ function patchedReplaceState(...args) {
2446
+ originalReplaceState(...args);
2447
+ setTimeout(check, 0);
2448
+ }
2449
+ history.pushState = patchedPushState;
2450
+ history.replaceState = patchedReplaceState;
2451
+ window.addEventListener("popstate", check);
2452
+ check();
2453
+ return () => {
2454
+ history.pushState = originalPushState;
2455
+ history.replaceState = originalReplaceState;
2456
+ window.removeEventListener("popstate", check);
2457
+ };
2458
+ }
2459
+
2460
+ // ../tracking-core/src/triggers/navigation.ts
2461
+ var listeners = /* @__PURE__ */ new Set();
2462
+ var restorePatch = null;
2463
+ function notify() {
2464
+ for (const listener of listeners) listener();
2465
+ }
2466
+ function notifyDeferred() {
2467
+ setTimeout(notify, 0);
2468
+ }
2469
+ function installPatch() {
2470
+ const originalPushState = history.pushState;
2471
+ const originalReplaceState = history.replaceState;
2472
+ function patchedPushState(...args) {
2473
+ originalPushState.apply(this, args);
2474
+ notifyDeferred();
2475
+ }
2476
+ function patchedReplaceState(...args) {
2477
+ originalReplaceState.apply(this, args);
2478
+ notifyDeferred();
2479
+ }
2480
+ history.pushState = patchedPushState;
2481
+ history.replaceState = patchedReplaceState;
2482
+ window.addEventListener("popstate", notify);
2483
+ restorePatch = () => {
2484
+ history.pushState = originalPushState;
2485
+ history.replaceState = originalReplaceState;
2486
+ window.removeEventListener("popstate", notify);
2487
+ restorePatch = null;
2488
+ };
2489
+ }
2490
+ function onHistoryChange(listener) {
2491
+ if (listeners.size === 0) installPatch();
2492
+ listeners.add(listener);
2493
+ return () => {
2494
+ if (!listeners.delete(listener)) return;
2495
+ if (listeners.size === 0) restorePatch?.();
2496
+ };
2497
+ }
2498
+
2499
+ // ../tracking-core/src/triggers/scroll-measurement.ts
2500
+ var BOTTOM_EPSILON_PX = 2;
2501
+ function measureScrollPercent() {
2502
+ const root = document.scrollingElement ?? document.documentElement;
2503
+ const scrollHeight = root.scrollHeight;
2504
+ const clientHeight = root.clientHeight;
2505
+ if (scrollHeight <= 0 || clientHeight <= 0) return null;
2506
+ if (scrollHeight <= clientHeight + BOTTOM_EPSILON_PX) return null;
2507
+ const maxTop = scrollHeight - clientHeight;
2508
+ const scrollTop = Math.min(Math.max(root.scrollTop, 0), maxTop);
2509
+ if (scrollTop + clientHeight >= scrollHeight - BOTTOM_EPSILON_PX) return 100;
2510
+ return Math.max(1, Math.min(100, Math.round((scrollTop + clientHeight) / scrollHeight * 100)));
2511
+ }
2512
+ function scheduleBaselineSnapshot(onSnapshot) {
2513
+ let rafId = requestAnimationFrame(() => {
2514
+ rafId = requestAnimationFrame(() => {
2515
+ onSnapshot(measureScrollPercent());
2516
+ });
2517
+ });
2518
+ return () => cancelAnimationFrame(rafId);
2519
+ }
2520
+ function createBaselineGate() {
2521
+ let baselinePercent = null;
2522
+ let ready = false;
2523
+ let cancelSnapshot = null;
2524
+ return {
2525
+ rebaseline() {
2526
+ cancelSnapshot?.();
2527
+ ready = false;
2528
+ baselinePercent = null;
2529
+ cancelSnapshot = scheduleBaselineSnapshot((b) => {
2530
+ baselinePercent = b;
2531
+ ready = true;
2532
+ });
2533
+ },
2534
+ cancel() {
2535
+ cancelSnapshot?.();
2536
+ },
2537
+ baseline() {
2538
+ return ready ? baselinePercent : null;
2539
+ },
2540
+ sample() {
2541
+ if (!ready) return null;
2542
+ if (baselinePercent === null) {
2543
+ baselinePercent = measureScrollPercent();
2544
+ return null;
2545
+ }
2546
+ return measureScrollPercent();
2547
+ }
2548
+ };
2549
+ }
2550
+
2551
+ // ../tracking-core/src/triggers/scroll-depth.ts
2552
+ function attachScrollDepth(client, config) {
2553
+ if (typeof window === "undefined" || typeof document === "undefined") {
2554
+ return () => {
2555
+ };
2556
+ }
2557
+ const thresholds = new Set(config.thresholds);
2558
+ let firedForPath = /* @__PURE__ */ new Set();
2559
+ let currentPath2 = window.location.pathname;
2560
+ let rafId = null;
2561
+ const gate = createBaselineGate();
2562
+ function checkThresholds() {
2563
+ const percent = gate.sample();
2564
+ if (percent === null) return;
2565
+ const baseline = gate.baseline();
2566
+ if (baseline === null) return;
2567
+ for (const threshold of thresholds) {
2568
+ if (threshold <= baseline) continue;
2569
+ if (percent >= threshold && !firedForPath.has(threshold)) {
2570
+ firedForPath.add(threshold);
2571
+ client.trackEvent({
2572
+ eventType: "scroll_depth",
2573
+ metadata: {
2574
+ depth_percent: threshold,
2575
+ page: { path: currentPath2 }
2576
+ },
2577
+ pageUrl: window.location.href,
2578
+ occurredAt: null
2579
+ });
2580
+ }
2581
+ }
2582
+ }
2583
+ function onScroll() {
2584
+ if (rafId !== null) return;
2585
+ rafId = requestAnimationFrame(() => {
2586
+ rafId = null;
2587
+ checkThresholds();
2588
+ });
2589
+ }
2590
+ function resetIfPathChanged() {
2591
+ const newPath = window.location.pathname;
2592
+ if (newPath === currentPath2) return;
2593
+ currentPath2 = newPath;
2594
+ firedForPath = /* @__PURE__ */ new Set();
2595
+ gate.rebaseline();
2596
+ }
2597
+ const unsubscribeNav = onHistoryChange(resetIfPathChanged);
2598
+ window.addEventListener("scroll", onScroll, { passive: true });
2599
+ gate.rebaseline();
2600
+ return () => {
2601
+ if (rafId !== null) cancelAnimationFrame(rafId);
2602
+ gate.cancel();
2603
+ unsubscribeNav();
2604
+ window.removeEventListener("scroll", onScroll);
2605
+ };
2606
+ }
2607
+
2608
+ // ../tracking-core/src/triggers/multi-page-session.ts
2609
+ var STORAGE_KEY2 = "aranova_tracking_mps_paths";
2610
+ var SESSION_KEY = "aranova_tracking_mps_session";
2611
+ var FIRED_KEY = "aranova_tracking_mps_fired";
2612
+ function getSessionStorage() {
2613
+ try {
2614
+ return typeof window !== "undefined" ? window.sessionStorage : null;
2615
+ } catch {
2616
+ return null;
2617
+ }
2618
+ }
2619
+ function attachMultiPageSession(client, config) {
2620
+ if (typeof window === "undefined" || typeof history === "undefined") {
2621
+ return () => {
2622
+ };
2623
+ }
2624
+ const storage = getSessionStorage();
2625
+ if (!storage) return () => {
2626
+ };
2627
+ const { pageThreshold } = config;
2628
+ let lastCheckedPath = "";
2629
+ function getDistinctPaths() {
2630
+ try {
2631
+ const raw = storage.getItem(STORAGE_KEY2);
2632
+ return raw ? new Set(JSON.parse(raw)) : /* @__PURE__ */ new Set();
2633
+ } catch {
2634
+ return /* @__PURE__ */ new Set();
2635
+ }
2636
+ }
2637
+ function saveDistinctPaths(paths) {
2638
+ try {
2639
+ storage.setItem(STORAGE_KEY2, JSON.stringify([...paths]));
2640
+ } catch {
2641
+ }
2642
+ }
2643
+ function resetIfSessionChanged() {
2644
+ const currentSession = getOrRotateSessionId().id;
2645
+ const storedSession = storage.getItem(SESSION_KEY);
2646
+ if (storedSession !== currentSession) {
2647
+ storage.setItem(SESSION_KEY, currentSession);
2648
+ storage.removeItem(STORAGE_KEY2);
2649
+ storage.removeItem(FIRED_KEY);
2650
+ }
2651
+ }
2652
+ function hasFired() {
2653
+ return storage.getItem(FIRED_KEY) === "1";
2654
+ }
2655
+ function check() {
2656
+ const currentPath2 = window.location.pathname;
2657
+ if (currentPath2 === lastCheckedPath) return;
2658
+ lastCheckedPath = currentPath2;
2659
+ resetIfSessionChanged();
2660
+ if (hasFired()) return;
2661
+ const paths = getDistinctPaths();
2662
+ paths.add(currentPath2);
2663
+ saveDistinctPaths(paths);
2664
+ if (paths.size >= pageThreshold) {
2665
+ storage.setItem(FIRED_KEY, "1");
2666
+ client.trackEvent({
2667
+ eventType: "multi_page_session",
2668
+ metadata: {
2669
+ page_count: paths.size,
2670
+ page: { path: window.location.pathname }
2671
+ },
2672
+ pageUrl: window.location.href,
2673
+ occurredAt: null
2674
+ });
2675
+ }
2676
+ }
2677
+ const originalPushState = history.pushState.bind(history);
2678
+ const originalReplaceState = history.replaceState.bind(history);
2679
+ function patchedPushState(...args) {
2680
+ originalPushState(...args);
2681
+ setTimeout(check, 0);
2682
+ }
2683
+ function patchedReplaceState(...args) {
2684
+ originalReplaceState(...args);
2685
+ setTimeout(check, 0);
2686
+ }
2687
+ history.pushState = patchedPushState;
2688
+ history.replaceState = patchedReplaceState;
2689
+ window.addEventListener("popstate", check);
2690
+ check();
2691
+ return () => {
2692
+ history.pushState = originalPushState;
2693
+ history.replaceState = originalReplaceState;
2694
+ window.removeEventListener("popstate", check);
2695
+ };
2696
+ }
2697
+
2698
+ // ../tracking-core/src/triggers/form-start.ts
2699
+ function attachFormStart(client, config) {
2700
+ if (typeof window === "undefined" || typeof document === "undefined") {
2701
+ return () => {
2702
+ };
2703
+ }
2704
+ const selector = config.selector ?? "form";
2705
+ let firedForms = /* @__PURE__ */ new Set();
2706
+ let currentPath2 = window.location.pathname;
2707
+ function getFormKey(form) {
2708
+ if (form.id) return `id:${form.id}`;
2709
+ const explicitAction = form.getAttribute("action");
2710
+ if (explicitAction) return `action:${explicitAction}`;
2711
+ const forms = Array.from(document.querySelectorAll(selector));
2712
+ return `index:${forms.indexOf(form)}`;
2713
+ }
2714
+ function onFocusIn(event) {
2715
+ const target = event.target;
2716
+ if (!(target instanceof HTMLElement)) return;
2717
+ const form = target.closest(selector);
2718
+ if (!form || form.tagName !== "FORM") return;
2719
+ const key = getFormKey(form);
2720
+ if (firedForms.has(key)) return;
2721
+ firedForms.add(key);
2722
+ client.trackEvent({
2723
+ eventType: "form_start",
2724
+ metadata: {
2725
+ form: {
2726
+ id: form.id || "",
2727
+ action: form.getAttribute("action") ?? null
2728
+ },
2729
+ page: { path: window.location.pathname }
2730
+ },
2731
+ pageUrl: window.location.href,
2732
+ occurredAt: null
2733
+ });
2734
+ }
2735
+ function resetIfPathChanged() {
2736
+ const newPath = window.location.pathname;
2737
+ if (newPath === currentPath2) return;
2738
+ currentPath2 = newPath;
2739
+ firedForms = /* @__PURE__ */ new Set();
2740
+ }
2741
+ const originalPushState = history.pushState.bind(history);
2742
+ const originalReplaceState = history.replaceState.bind(history);
2743
+ function patchedPushState(...args) {
2744
+ originalPushState(...args);
2745
+ setTimeout(resetIfPathChanged, 0);
2746
+ }
2747
+ function patchedReplaceState(...args) {
2748
+ originalReplaceState(...args);
2749
+ setTimeout(resetIfPathChanged, 0);
2750
+ }
2751
+ history.pushState = patchedPushState;
2752
+ history.replaceState = patchedReplaceState;
2753
+ window.addEventListener("popstate", resetIfPathChanged);
2754
+ document.addEventListener("focusin", onFocusIn);
2755
+ return () => {
2756
+ history.pushState = originalPushState;
2757
+ history.replaceState = originalReplaceState;
2758
+ window.removeEventListener("popstate", resetIfPathChanged);
2759
+ document.removeEventListener("focusin", onFocusIn);
2760
+ };
2761
+ }
2762
+
2763
+ // ../tracking-core/src/triggers/page-exit.ts
2764
+ var MIN_SEGMENT_MS = 50;
2765
+ function attachPageExit(client) {
2766
+ if (typeof window === "undefined" || typeof document === "undefined") {
2767
+ return () => {
2768
+ };
2769
+ }
2770
+ let currentPath2 = window.location.pathname;
2771
+ let activeSince = document.visibilityState === "visible" ? Date.now() : null;
2772
+ let accumulatedMs = 0;
2773
+ let maxScrollPercent = null;
2774
+ let rafId = null;
2775
+ const gate = createBaselineGate();
2776
+ function onScroll() {
2777
+ if (rafId !== null) return;
2778
+ rafId = requestAnimationFrame(() => {
2779
+ rafId = null;
2780
+ const percent = gate.sample();
2781
+ if (percent !== null && (maxScrollPercent === null || percent > maxScrollPercent)) {
2782
+ maxScrollPercent = percent;
2783
+ }
2784
+ });
2785
+ }
2786
+ function settledDwellMs() {
2787
+ let total = accumulatedMs;
2788
+ if (activeSince !== null) {
2789
+ total += Date.now() - activeSince;
2790
+ }
2791
+ return Math.max(0, Math.round(total));
2792
+ }
2793
+ function emitSegment(path, flush) {
2794
+ const dwell = settledDwellMs();
2795
+ if (dwell < MIN_SEGMENT_MS) return;
2796
+ client.trackEvent({
2797
+ eventType: "page_exit",
2798
+ metadata: {
2799
+ dwell_ms: dwell,
2800
+ max_scroll_percent: maxScrollPercent,
2801
+ // Lets the backend tell "scrolled to the bottom" apart from "the page
2802
+ // was barely scrollable". null = unscrollable page or the segment
2803
+ // ended before the post-paint snapshot landed. For pages that grew
2804
+ // after the snapshot this is the first-scroll position, not the
2805
+ // at-load fraction (see BaselineGate.baseline).
2806
+ scroll_baseline_percent: gate.baseline(),
2807
+ page: { path }
2808
+ },
2809
+ pageUrl: window.location.href,
2810
+ occurredAt: null
2811
+ });
2812
+ if (flush) {
2813
+ client.flushBeacon();
2814
+ }
2815
+ accumulatedMs = 0;
2816
+ activeSince = null;
2817
+ }
2818
+ function onNavigate() {
2819
+ const newPath = window.location.pathname;
2820
+ if (newPath === currentPath2) return;
2821
+ emitSegment(currentPath2, false);
2822
+ currentPath2 = newPath;
2823
+ maxScrollPercent = null;
2824
+ gate.rebaseline();
2825
+ accumulatedMs = 0;
2826
+ activeSince = document.visibilityState === "visible" ? Date.now() : null;
2827
+ }
2828
+ function onVisibilityChange() {
2829
+ if (document.visibilityState === "hidden") {
2830
+ emitSegment(currentPath2, true);
2831
+ } else {
2832
+ activeSince = Date.now();
2833
+ }
2834
+ }
2835
+ function onPageHide() {
2836
+ emitSegment(currentPath2, true);
2837
+ }
2838
+ const unsubscribeNav = onHistoryChange(onNavigate);
2839
+ window.addEventListener("scroll", onScroll, { passive: true });
2840
+ document.addEventListener("visibilitychange", onVisibilityChange);
2841
+ window.addEventListener("pagehide", onPageHide);
2842
+ gate.rebaseline();
2843
+ return () => {
2844
+ if (rafId !== null) cancelAnimationFrame(rafId);
2845
+ gate.cancel();
2846
+ unsubscribeNav();
2847
+ window.removeEventListener("scroll", onScroll);
2848
+ document.removeEventListener("visibilitychange", onVisibilityChange);
2849
+ window.removeEventListener("pagehide", onPageHide);
2850
+ };
2851
+ }
2852
+
2853
+ // ../tracking-core/src/triggers/cta-click-capture.ts
2854
+ var DEFAULT_CTA_SELECTOR = "[data-aranova-cta]";
2855
+ var CTA_NAME_MAX_LENGTH = 120;
2856
+ function describeElement(el) {
2857
+ const tag = el.tagName.toLowerCase();
2858
+ return el.id ? `${tag}#${el.id}` : tag;
2859
+ }
2860
+ function resolveCtaName(el) {
2861
+ const explicit = el.getAttribute("data-aranova-cta");
2862
+ if (explicit && explicit.trim().length > 0) return explicit.trim();
2863
+ const text = (el.textContent ?? "").trim().replaceAll(/\s+/g, " ");
2864
+ if (text.length > 0) return text.slice(0, CTA_NAME_MAX_LENGTH);
2865
+ return describeElement(el);
2866
+ }
2867
+ function attachCtaClickCapture(client, config) {
2868
+ if (typeof window === "undefined" || typeof document === "undefined") {
2869
+ return () => {
2870
+ };
2871
+ }
2872
+ const autoCapture = config.autoCapture;
2873
+ if (!autoCapture) {
2874
+ return () => {
2875
+ };
2876
+ }
2877
+ registerCapability("cta_click_capture");
2878
+ const selector = autoCapture.selector ?? DEFAULT_CTA_SELECTOR;
2879
+ function onClick(event) {
2880
+ const target = event.target;
2881
+ if (!(target instanceof Element)) return;
2882
+ let matched = null;
2883
+ try {
2884
+ matched = target.closest(selector);
2885
+ } catch {
2886
+ return;
2887
+ }
2888
+ if (matched === null) return;
2889
+ const href = matched instanceof HTMLAnchorElement ? matched.href || null : matched.getAttribute("href");
2890
+ client.trackEvent({
2891
+ eventType: "cta_click",
2892
+ metadata: {
2893
+ cta_name: resolveCtaName(matched),
2894
+ page: { path: window.location.pathname },
2895
+ section: matched.getAttribute("data-aranova-section"),
2896
+ destination_url: href,
2897
+ href,
2898
+ element: describeElement(matched)
2899
+ },
2900
+ pageUrl: window.location.href,
2901
+ occurredAt: null
2902
+ });
2903
+ }
2904
+ document.addEventListener("click", onClick, true);
2905
+ return () => {
2906
+ document.removeEventListener("click", onClick, true);
2907
+ };
2908
+ }
2909
+
2910
+ // ../tracking-core/src/triggers/phone-click-capture.ts
2911
+ var DEFAULT_TEL_SELECTOR = 'a[href^="tel:"]';
2912
+ function safeDecodeURIComponent(value) {
2913
+ try {
2914
+ return decodeURIComponent(value);
2915
+ } catch {
2916
+ return value;
2917
+ }
2918
+ }
2919
+ function resolvePhoneNumber(el) {
2920
+ const href = el instanceof HTMLAnchorElement ? el.href : el.getAttribute("href") ?? "";
2921
+ const raw = safeDecodeURIComponent(href.replace(/^tel:/i, "").split(";")[0]).trim();
2922
+ return toE164(raw) ?? raw;
2923
+ }
2924
+ function attachPhoneClickCapture(client, config) {
2925
+ if (typeof window === "undefined" || typeof document === "undefined") {
2926
+ return () => {
2927
+ };
2928
+ }
2929
+ const autoCapture = config.autoCapture;
2930
+ if (!autoCapture) {
2931
+ return () => {
2932
+ };
2933
+ }
2934
+ registerCapability("phone_click_capture");
2935
+ const selector = autoCapture.selector ?? DEFAULT_TEL_SELECTOR;
2936
+ function onClick(event) {
2937
+ const target = event.target;
2938
+ if (!(target instanceof Element)) return;
2939
+ let matched = null;
2940
+ try {
2941
+ matched = target.closest(selector);
2942
+ } catch {
2943
+ return;
2944
+ }
2945
+ if (matched === null) return;
2946
+ const metadata = {
2947
+ phone_number: resolvePhoneNumber(matched),
2948
+ page: { path: window.location.pathname },
2949
+ section: matched.getAttribute("data-aranova-section")
2950
+ };
2951
+ client.trackEvent({
2952
+ eventType: "phone_click",
2953
+ metadata,
2954
+ pageUrl: window.location.href,
2955
+ occurredAt: null
2956
+ });
2957
+ }
2958
+ document.addEventListener("click", onClick, true);
2959
+ return () => {
2960
+ document.removeEventListener("click", onClick, true);
2961
+ };
2962
+ }
2963
+
2964
+ // ../tracking-core/src/resources/sales/schema.ts
2965
+ import { z as z12 } from "zod";
2966
+ var SUPPORTED_CURRENCIES = ["USD", "CAD"];
2967
+ var TRACKING_ENVIRONMENTS = ["production", "development"];
2968
+ var currencySchema = z12.enum(SUPPORTED_CURRENCIES);
2969
+ var centsSchema = z12.number().int().nonnegative();
2970
+ var quantitySchema = z12.string().regex(/^\d+(\.\d{1,3})?$/);
2971
+ var metadataSchema = z12.record(z12.unknown());
2972
+ var saleItemSchema = z12.object({
2973
+ external_item_id: z12.string().nullable().optional(),
2974
+ name: z12.string().nullable().optional(),
2975
+ category: z12.string().nullable().optional(),
2976
+ quantity: quantitySchema,
2977
+ unit_price_cents: centsSchema,
2978
+ // Non-negativity validated on the wire — same contract as the other cents
2979
+ // fields — and backstopped by the DB CHECK.
2980
+ unit_cost_cents: centsSchema.nullable().optional()
2981
+ }).strict();
2982
+ var saleServiceSchema = z12.object({
2983
+ service: z12.string(),
2984
+ amount_cents: centsSchema
2985
+ }).strict();
2986
+ var customerNameSchema = z12.string().max(200);
2987
+ var customerPhoneSchema = z12.string().max(64);
2988
+ var customerEmailSchema = z12.string().max(320).email();
2989
+ function refineServiceXor(val, ctx, { requireAmount }) {
2990
+ if (val.services != null) {
2991
+ if (val.service != null) {
2992
+ ctx.addIssue({
2993
+ code: z12.ZodIssueCode.custom,
2994
+ message: "pass either `service` or `services`, not both",
2995
+ path: ["services"]
2996
+ });
2997
+ }
2998
+ if (val.services.length === 0) {
2999
+ ctx.addIssue({
3000
+ code: z12.ZodIssueCode.custom,
3001
+ message: "`services` must not be empty",
3002
+ path: ["services"]
3003
+ });
3004
+ }
3005
+ const keys = val.services.map((s) => s.service);
3006
+ if (new Set(keys).size !== keys.length) {
3007
+ ctx.addIssue({
3008
+ code: z12.ZodIssueCode.custom,
3009
+ message: "`services` must not list the same service more than once",
3010
+ path: ["services"]
3011
+ });
3012
+ }
3013
+ if (val.amount_total_cents != null) {
3014
+ const sum = val.services.reduce((acc, s) => acc + s.amount_cents, 0);
3015
+ if (val.amount_total_cents !== sum) {
3016
+ ctx.addIssue({
3017
+ code: z12.ZodIssueCode.custom,
3018
+ message: "amount_total_cents must equal the sum of the services amounts (omit it to derive it automatically)",
3019
+ path: ["amount_total_cents"]
3020
+ });
3021
+ }
3022
+ }
3023
+ } else if (requireAmount && val.amount_total_cents == null) {
3024
+ ctx.addIssue({
3025
+ code: z12.ZodIssueCode.custom,
3026
+ message: "amount_total_cents is required unless `services` is provided",
3027
+ path: ["amount_total_cents"]
3028
+ });
3029
+ }
3030
+ }
3031
+ var saleCreateSchema = z12.object({
3032
+ external_id: z12.string().nullable().optional(),
3033
+ description: z12.string().nullable().optional(),
3034
+ service: z12.string().nullable().optional(),
3035
+ services: z12.array(saleServiceSchema).nullable().optional(),
3036
+ currency: currencySchema,
3037
+ // Optional only because the plural `services` form derives it from the sum
3038
+ // (see refineServiceXor); the singular/serviceless path still requires it.
3039
+ amount_total_cents: centsSchema.nullable().optional(),
3040
+ occurred_at: z12.string().datetime(),
3041
+ environment: z12.enum(TRACKING_ENVIRONMENTS).default("production"),
3042
+ items: z12.array(saleItemSchema).default([]),
3043
+ metadata: metadataSchema.nullable().optional(),
3044
+ customer_name: customerNameSchema.nullable().optional(),
3045
+ customer_phone: customerPhoneSchema.nullable().optional(),
3046
+ customer_email: customerEmailSchema.nullable().optional(),
3047
+ // CASL consent attestation: the customer agreed to receive SMS. Recorded
3048
+ // with a timestamp server-side; every SMS send path gates on it.
3049
+ //
3050
+ // Tri-state: omit it (or send null) to let the server apply the business's
3051
+ // configured default-opt-in policy, honouring a returning customer's
3052
+ // remembered preference. Send an explicit boolean to assert consent state
3053
+ // yourself — `false` records a deliberate opt-out.
3054
+ sms_consent: z12.boolean().nullable().optional()
3055
+ }).strict().superRefine((val, ctx) => refineServiceXor(val, ctx, { requireAmount: true }));
3056
+ var saleUpdateSchema = z12.object({
3057
+ description: z12.string().nullable().optional(),
3058
+ service: z12.string().nullable().optional(),
3059
+ services: z12.array(saleServiceSchema).nullable().optional(),
3060
+ currency: currencySchema.optional(),
3061
+ amount_total_cents: centsSchema.optional(),
3062
+ occurred_at: z12.string().datetime().optional(),
3063
+ items: z12.array(saleItemSchema).optional(),
3064
+ metadata: metadataSchema.nullable().optional(),
3065
+ customer_name: customerNameSchema.nullable().optional(),
3066
+ // Re-attest when changing a filler-looking name; the server clears the
3067
+ // prior attestation whenever `customer_name` changes.
3068
+ customer_name_placeholder_confirmed: z12.boolean().optional(),
3069
+ customer_phone: customerPhoneSchema.nullable().optional(),
3070
+ customer_email: customerEmailSchema.nullable().optional(),
3071
+ // NOT NULL server-side: omit to leave unchanged (explicit null is rejected).
3072
+ sms_consent: z12.boolean().optional()
3073
+ }).strict().superRefine((val, ctx) => refineServiceXor(val, ctx, { requireAmount: false }));
3074
+
3075
+ // src/hooks.ts
3076
+ function useGclid() {
3077
+ const [gclid, setGclid] = useState(null);
3078
+ useEffect(() => {
3079
+ setGclid(getCookieValueFromDocument("gclid"));
3080
+ }, []);
3081
+ return gclid;
3082
+ }
3083
+ function useTrackingParams() {
3084
+ const [trackingParams, setTrackingParams] = useState(createEmptyTrackingParams());
3085
+ useEffect(() => {
3086
+ setTrackingParams(getTrackingParamsFromCookieReader(getCookieValueFromDocument));
3087
+ }, []);
3088
+ return trackingParams;
3089
+ }
3090
+ var DEFAULT_CHOICE2 = {
3091
+ state: "granted",
3092
+ source: "default",
3093
+ updatedAt: null,
3094
+ expiresAt: null
3095
+ };
3096
+ function useCookiePreferences(options) {
3097
+ registerCapability("consent_controls");
3098
+ const [choice, setChoice] = useState(DEFAULT_CHOICE2);
3099
+ const ttlDays = options?.declineTtlDays;
3100
+ useEffect(() => {
3101
+ const sync = () => setChoice(getConsentChoice());
3102
+ sync();
3103
+ const handleStorage = (event) => {
3104
+ if (event.key === null || event.key === CONSENT_STATE_KEY || event.key === CONSENT_EXPIRES_AT_KEY || event.key === CONSENT_TIMESTAMP_KEY)
3105
+ sync();
3106
+ };
3107
+ window.addEventListener("storage", handleStorage);
3108
+ const unsubscribe = onConsentChange(sync);
3109
+ return () => {
3110
+ window.removeEventListener("storage", handleStorage);
3111
+ unsubscribe();
3112
+ };
3113
+ }, []);
3114
+ const optOutAction = useCallback(() => {
3115
+ optOut(ttlDays != null ? { declineTtlDays: ttlDays } : void 0);
3116
+ }, [ttlDays]);
3117
+ const optInAction = useCallback(() => {
3118
+ optIn();
3119
+ }, []);
3120
+ const reset = useCallback(() => {
3121
+ resetConsent();
3122
+ }, []);
3123
+ return {
3124
+ state: choice.state,
3125
+ source: choice.source,
3126
+ isDefault: choice.source === "default",
3127
+ isGranted: choice.state === "granted",
3128
+ isDenied: choice.state === "denied",
3129
+ updatedAt: choice.updatedAt,
3130
+ expiresAt: choice.expiresAt,
3131
+ optOut: optOutAction,
3132
+ optIn: optInAction,
3133
+ reset
3134
+ };
3135
+ }
3136
+ function useConsentState() {
3137
+ return useConsent().state;
3138
+ }
3139
+ function useConsent() {
3140
+ const {
3141
+ state,
3142
+ isGranted,
3143
+ isDenied,
3144
+ optIn: accept,
3145
+ optOut: decline,
3146
+ reset
3147
+ } = useCookiePreferences();
3148
+ return {
3149
+ state,
3150
+ isPending: false,
3151
+ isGranted,
3152
+ isDenied,
3153
+ accept,
3154
+ decline,
3155
+ reset
3156
+ };
3157
+ }
3158
+
3159
+ // src/ConsentBanner.tsx
3160
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
3161
+ var LIGHT_THEME = {
3162
+ background: "#ffffff",
3163
+ border: "#e5e7eb",
3164
+ text: "#111827",
3165
+ mutedText: "#4b5563",
3166
+ acceptBg: "#111827",
3167
+ acceptText: "#ffffff",
3168
+ declineBg: "transparent",
3169
+ declineText: "#111827",
3170
+ declineBorder: "#d1d5db",
3171
+ shadow: "0 -4px 16px -2px rgba(15, 23, 42, 0.08), 0 -2px 6px -1px rgba(15, 23, 42, 0.04)",
3172
+ linkColor: "#1f2937"
3173
+ };
3174
+ var DARK_THEME = {
3175
+ background: "#0f172a",
3176
+ border: "#1e293b",
3177
+ text: "#f1f5f9",
3178
+ mutedText: "#cbd5e1",
3179
+ acceptBg: "#f1f5f9",
3180
+ acceptText: "#0f172a",
3181
+ declineBg: "transparent",
3182
+ declineText: "#f1f5f9",
3183
+ declineBorder: "#334155",
3184
+ shadow: "0 -4px 16px -2px rgba(0, 0, 0, 0.5), 0 -2px 6px -1px rgba(0, 0, 0, 0.3)",
3185
+ linkColor: "#e2e8f0"
3186
+ };
3187
+ function useResolvedTheme(theme) {
3188
+ const [prefersDark, setPrefersDark] = useState2(false);
3189
+ useEffect2(() => {
3190
+ if (theme !== "auto" || typeof window === "undefined" || !window.matchMedia) return;
3191
+ const mql = window.matchMedia("(prefers-color-scheme: dark)");
3192
+ setPrefersDark(mql.matches);
3193
+ const onChange = (e) => setPrefersDark(e.matches);
3194
+ mql.addEventListener("change", onChange);
3195
+ return () => mql.removeEventListener("change", onChange);
3196
+ }, [theme]);
3197
+ if (theme === "dark") return DARK_THEME;
3198
+ if (theme === "auto" && prefersDark) return DARK_THEME;
3199
+ return LIGHT_THEME;
3200
+ }
3201
+ var DEFAULT_MESSAGE = "We use cookies to understand ad performance and improve how our marketing works across visits. You can accept or decline this tracking.";
3202
+ function ConsentBanner({
3203
+ message,
3204
+ title,
3205
+ acceptLabel = "Accept",
3206
+ declineLabel = "Decline",
3207
+ policyHref,
3208
+ policyLabel = "Learn more",
3209
+ onAccept,
3210
+ onDecline,
3211
+ position = "bottom",
3212
+ theme = "light",
3213
+ className,
3214
+ style
3215
+ } = {}) {
3216
+ const { isPending, accept, decline } = useConsent();
3217
+ const tokens = useResolvedTheme(theme);
3218
+ const [hasMounted, setHasMounted] = useState2(false);
3219
+ useEffect2(() => {
3220
+ setHasMounted(true);
3221
+ }, []);
3222
+ if (!hasMounted || !isPending) return null;
3223
+ const wrapperStyle = {
3224
+ position: "fixed",
3225
+ left: 0,
3226
+ right: 0,
3227
+ [position]: 0,
3228
+ zIndex: 2147483640,
3229
+ background: tokens.background,
3230
+ color: tokens.text,
3231
+ borderTop: position === "bottom" ? `1px solid ${tokens.border}` : "none",
3232
+ borderBottom: position === "top" ? `1px solid ${tokens.border}` : "none",
3233
+ boxShadow: tokens.shadow,
3234
+ padding: "16px 20px",
3235
+ boxSizing: "border-box",
3236
+ animation: `${ANIMATION_NAME}-${position} 200ms ease-out`,
3237
+ fontFamily: 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
3238
+ ...style
3239
+ };
3240
+ const innerStyle = {
3241
+ maxWidth: 1100,
3242
+ margin: "0 auto",
3243
+ display: "flex",
3244
+ flexWrap: "wrap",
3245
+ gap: 16,
3246
+ alignItems: "center",
3247
+ justifyContent: "space-between"
3248
+ };
3249
+ const messageStyle = {
3250
+ flex: "1 1 320px",
3251
+ margin: 0,
3252
+ fontSize: 14,
3253
+ lineHeight: 1.5,
3254
+ color: tokens.mutedText
3255
+ };
3256
+ const titleStyle = {
3257
+ margin: "0 0 4px 0",
3258
+ fontSize: 14,
3259
+ fontWeight: 600,
3260
+ color: tokens.text
3261
+ };
3262
+ const actionsStyle = {
3263
+ display: "flex",
3264
+ gap: 8,
3265
+ flexShrink: 0
3266
+ };
3267
+ const buttonBase = {
3268
+ appearance: "none",
3269
+ fontFamily: "inherit",
3270
+ fontSize: 14,
3271
+ fontWeight: 500,
3272
+ padding: "8px 16px",
3273
+ borderRadius: 6,
3274
+ cursor: "pointer",
3275
+ border: "1px solid transparent",
3276
+ transition: "opacity 120ms ease"
3277
+ };
3278
+ const declineStyle = {
3279
+ ...buttonBase,
3280
+ background: tokens.declineBg,
3281
+ color: tokens.declineText,
3282
+ borderColor: tokens.declineBorder
3283
+ };
3284
+ const acceptStyle = {
3285
+ ...buttonBase,
3286
+ background: tokens.acceptBg,
3287
+ color: tokens.acceptText
3288
+ };
3289
+ const linkStyle = {
3290
+ color: tokens.linkColor,
3291
+ textDecoration: "underline",
3292
+ textUnderlineOffset: 2
3293
+ };
3294
+ const handleAccept = () => {
3295
+ accept();
3296
+ onAccept?.();
3297
+ };
3298
+ const handleDecline = () => {
3299
+ decline();
3300
+ onDecline?.();
3301
+ };
3302
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
3303
+ /* @__PURE__ */ jsx("style", { children: ANIMATION_KEYFRAMES }),
3304
+ /* @__PURE__ */ jsx(
3305
+ "div",
3306
+ {
3307
+ role: "dialog",
3308
+ "aria-live": "polite",
3309
+ "aria-label": "Cookie consent",
3310
+ className,
3311
+ style: wrapperStyle,
3312
+ children: /* @__PURE__ */ jsxs("div", { style: innerStyle, children: [
3313
+ /* @__PURE__ */ jsxs("div", { style: { flex: "1 1 320px" }, children: [
3314
+ title ? /* @__PURE__ */ jsx("p", { style: titleStyle, children: title }) : null,
3315
+ /* @__PURE__ */ jsxs("p", { style: messageStyle, children: [
3316
+ message ?? DEFAULT_MESSAGE,
3317
+ policyHref ? /* @__PURE__ */ jsxs(Fragment, { children: [
3318
+ " ",
3319
+ /* @__PURE__ */ jsx("a", { href: policyHref, style: linkStyle, children: policyLabel })
3320
+ ] }) : null
3321
+ ] })
3322
+ ] }),
3323
+ /* @__PURE__ */ jsxs("div", { style: actionsStyle, children: [
3324
+ /* @__PURE__ */ jsx("button", { type: "button", onClick: handleDecline, style: declineStyle, children: declineLabel }),
3325
+ /* @__PURE__ */ jsx("button", { type: "button", onClick: handleAccept, style: acceptStyle, children: acceptLabel })
3326
+ ] })
3327
+ ] })
3328
+ }
3329
+ )
3330
+ ] });
3331
+ }
3332
+ var ANIMATION_NAME = "aranova-consent-banner";
3333
+ var ANIMATION_KEYFRAMES = `
3334
+ @keyframes ${ANIMATION_NAME}-bottom {
3335
+ from { transform: translateY(100%); opacity: 0; }
3336
+ to { transform: translateY(0); opacity: 1; }
3337
+ }
3338
+ @keyframes ${ANIMATION_NAME}-top {
3339
+ from { transform: translateY(-100%); opacity: 0; }
3340
+ to { transform: translateY(0); opacity: 1; }
3341
+ }
3342
+ `;
3343
+
3344
+ // src/AdPlatformTracking.tsx
3345
+ import { useEffect as useEffect3, useMemo } from "react";
3346
+ function AdPlatformTracking({
3347
+ gtagId,
3348
+ gtagIds,
3349
+ trackingConfig,
3350
+ standalonePageView = false,
3351
+ metaPixelId,
3352
+ metaPixelIds
3353
+ }) {
3354
+ const trackingConfigKey2 = trackingConfig ? `${resolveTrackingConfigUrl(trackingConfig)}:${trackingConfig.businessId}:${trackingConfig.environment}` : "";
3355
+ const gtagIdsKey = useMemo(() => gtagIds ? JSON.stringify(gtagIds) : "", [gtagIds]);
3356
+ const metaPixelIdsKey = useMemo(
3357
+ () => metaPixelIds ? JSON.stringify(metaPixelIds) : "",
3358
+ [metaPixelIds]
3359
+ );
3360
+ if (trackingConfig || gtagId || gtagIds && Object.keys(gtagIds).length > 0) {
3361
+ registerCapability("ad_tags_google");
3362
+ }
3363
+ if (metaPixelId || metaPixelIds && Object.keys(metaPixelIds).length > 0) {
3364
+ registerCapability("ad_tags_meta");
3365
+ }
3366
+ useEffect3(() => {
3367
+ if (trackingConfig) {
3368
+ const runtime = getTrackingConfigRuntime(trackingConfig);
3369
+ if (standalonePageView) runtime.queuePageView();
3370
+ else void runtime.revalidate();
3371
+ } else if (gtagIds && Object.keys(gtagIds).length > 0) {
3372
+ bootstrapMultipleGtags(gtagIds);
3373
+ } else if (gtagId) {
3374
+ bootstrapGoogleAdsTracking(gtagId);
3375
+ }
3376
+ }, [gtagId, gtagIdsKey, trackingConfigKey2, standalonePageView]);
3377
+ useEffect3(() => {
3378
+ if (metaPixelIds && Object.keys(metaPixelIds).length > 0) {
3379
+ bootstrapMultiplePixels(metaPixelIds);
3380
+ } else if (metaPixelId) {
3381
+ bootstrapMetaPixel(metaPixelId);
3382
+ }
3383
+ }, [metaPixelId, metaPixelIdsKey]);
3384
+ return null;
3385
+ }
3386
+
3387
+ // src/GoogleAdsTracking.tsx
3388
+ import { useEffect as useEffect4, useMemo as useMemo2 } from "react";
3389
+ function GoogleAdsTracking(props) {
3390
+ const { gtagId, gtagIds } = props;
3391
+ const gtagIdsKey = useMemo2(() => gtagIds ? JSON.stringify(gtagIds) : "", [gtagIds]);
3392
+ useEffect4(() => {
3393
+ if (gtagIds && Object.keys(gtagIds).length > 0) {
3394
+ bootstrapMultipleGtags(gtagIds);
3395
+ } else if (gtagId) {
3396
+ bootstrapGoogleAdsTracking(gtagId);
3397
+ }
3398
+ }, [gtagId, gtagIdsKey]);
3399
+ return null;
3400
+ }
3401
+
3402
+ // src/factory.tsx
3403
+ import { createContext as createContext2, useContext as useContext2, useEffect as useEffect5, useMemo as useMemo4 } from "react";
3404
+
3405
+ // package.json
3406
+ var version = "0.25.0";
3407
+
3408
+ // ../tracking-core/src/phone-react.tsx
3409
+ import {
3410
+ createContext,
3411
+ forwardRef,
3412
+ useCallback as useCallback2,
3413
+ useContext,
3414
+ useMemo as useMemo3,
3415
+ useState as useState3
3416
+ } from "react";
3417
+ import { jsx as jsx2 } from "react/jsx-runtime";
3418
+ var _phoneConfigContext;
3419
+ function phoneConfigContext() {
3420
+ return _phoneConfigContext ?? (_phoneConfigContext = createContext(null));
3421
+ }
3422
+ function PhoneConfigProvider({
3423
+ value,
3424
+ children
3425
+ }) {
3426
+ const Ctx = phoneConfigContext();
3427
+ return /* @__PURE__ */ jsx2(Ctx.Provider, { value, children });
3428
+ }
3429
+ function usePhoneConfig() {
3430
+ const ctx = useContext(phoneConfigContext());
3431
+ return {
3432
+ defaultCountry: ctx?.defaultCountry ?? DEFAULT_PHONE_COUNTRY,
3433
+ display: ctx?.display ?? "national"
3434
+ };
3435
+ }
3436
+ function usePhoneField(opts = {}) {
3437
+ registerCapability("phone_fields");
3438
+ const cfg = usePhoneConfig();
3439
+ const country = opts.country ?? cfg.defaultCountry;
3440
+ const display = opts.display ?? cfg.display;
3441
+ const { onValueChange } = opts;
3442
+ const [value, setValue] = useState3(() => formatPhoneAsTyped(opts.defaultValue ?? "", country));
3443
+ const [touched, setTouched] = useState3(false);
3444
+ const parsed = useMemo3(() => parsePhone(value, country), [value, country]);
3445
+ const onChange = useCallback2(
3446
+ (event) => {
3447
+ const next = formatPhoneAsTyped(event.target.value, country);
3448
+ setValue(next);
3449
+ onValueChange?.(parsePhone(next, country).e164);
3450
+ },
3451
+ [country, onValueChange]
3452
+ );
3453
+ const onBlur = useCallback2(
3454
+ (_event) => {
3455
+ setTouched(true);
3456
+ setValue((current) => {
3457
+ const p = parsePhone(current, country);
3458
+ return p.isValid ? formatPhone(current, display, country) : current;
3459
+ });
3460
+ },
3461
+ [country, display]
3462
+ );
3463
+ const error = touched && value.length > 0 && !parsed.isValid ? "Enter a valid phone number" : null;
3464
+ return {
3465
+ value,
3466
+ e164: parsed.e164,
3467
+ isValid: parsed.isValid,
3468
+ error,
3469
+ parsed,
3470
+ inputProps: { value, onChange, onBlur, type: "tel", inputMode: "tel", autoComplete: "tel" }
3471
+ };
3472
+ }
3473
+ var PhoneField = forwardRef(function PhoneField2({ country, value, defaultValue, onChange, onE164Change, ...rest }, ref) {
3474
+ const cfg = usePhoneConfig();
3475
+ const resolvedCountry = country ?? cfg.defaultCountry;
3476
+ const isControlled = value !== void 0;
3477
+ const [internal, setInternal] = useState3(
3478
+ () => formatPhoneAsTyped(defaultValue ?? "", resolvedCountry)
3479
+ );
3480
+ const handleChange = (event) => {
3481
+ const formatted = formatPhoneAsTyped(event.target.value, resolvedCountry);
3482
+ event.target.value = formatted;
3483
+ onE164Change?.(parsePhone(formatted, resolvedCountry).e164);
3484
+ if (!isControlled) setInternal(formatted);
3485
+ onChange?.(event);
3486
+ };
3487
+ const shown = isControlled ? formatPhoneAsTyped(value, resolvedCountry) : internal;
3488
+ return /* @__PURE__ */ jsx2(
3489
+ "input",
3490
+ {
3491
+ ...rest,
3492
+ ref,
3493
+ type: "tel",
3494
+ inputMode: "tel",
3495
+ autoComplete: "tel",
3496
+ value: shown,
3497
+ onChange: handleChange
3498
+ }
3499
+ );
3500
+ });
3501
+
3502
+ // src/factory.tsx
3503
+ import { jsx as jsx3 } from "react/jsx-runtime";
3504
+ var NOOP_CLIENT = {
3505
+ trackEvent: () => {
3506
+ },
3507
+ flush: async () => {
3508
+ },
3509
+ getSessionId: () => "",
3510
+ getVisitorId: () => ""
3511
+ };
3512
+ function createTracking(options) {
3513
+ const {
3514
+ apiKey,
3515
+ endpoint,
3516
+ triggers,
3517
+ environment,
3518
+ debug,
3519
+ phone,
3520
+ conversionConfig,
3521
+ trackingConfig
3522
+ } = options;
3523
+ registerCapability("base_tracking");
3524
+ if (trackingConfig) registerCapability("conversion_goals_auto");
3525
+ if (!apiKey || !endpoint) {
3526
+ if (apiKey || endpoint) {
3527
+ console.warn(
3528
+ "[AranovaTracking] createTracking() requires both `apiKey` and `endpoint`. Tracking is disabled for this session."
3529
+ );
3530
+ }
3531
+ const noopTyped = NOOP_CLIENT;
3532
+ return {
3533
+ // Still publish phone config so usePhoneField/<PhoneField> work even when
3534
+ // tracking is disabled (missing apiKey/endpoint).
3535
+ TrackingProvider: ({ children }) => /* @__PURE__ */ jsx3(PhoneConfigProvider, { value: phone ?? null, children }),
3536
+ useTracking: () => noopTyped
3537
+ };
3538
+ }
3539
+ const TrackingContext = createContext2(null);
3540
+ function TrackingProvider({
3541
+ gtagId,
3542
+ gtagIds,
3543
+ metaPixelId,
3544
+ metaPixelIds,
3545
+ children
3546
+ }) {
3547
+ const gtagIdsKey = useMemo4(() => gtagIds ? JSON.stringify(gtagIds) : "", [gtagIds]);
3548
+ const resolvedGtagIds = useMemo4(
3549
+ () => gtagIds ? Object.fromEntries(
3550
+ Object.entries(gtagIds).filter((e) => e[1] != null)
3551
+ ) : gtagId ? { default: gtagId } : void 0,
3552
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- gtagIdsKey is stable proxy
3553
+ [gtagId, gtagIdsKey]
3554
+ );
3555
+ const rawClient = useMemo4(
3556
+ () => getOrCreateTrackingClient({
3557
+ apiKey,
3558
+ endpoint,
3559
+ surface: "react",
3560
+ packageName: "@aranova/tracking-react",
3561
+ sdkVersion: version,
3562
+ triggers,
3563
+ environment,
3564
+ activeGtagIds: resolvedGtagIds,
3565
+ debug
3566
+ }),
3567
+ [resolvedGtagIds]
3568
+ );
3569
+ const conversionStore = useMemo4(
3570
+ () => trackingConfig ? getTrackingConfigRuntime(trackingConfig) : conversionConfig ? resolveConversionConfig({
3571
+ cdnUrl: conversionConfig.cdnUrl,
3572
+ baked: conversionConfig.baked
3573
+ }) : null,
3574
+ []
3575
+ );
3576
+ const conversionClient = useMemo4(
3577
+ () => conversionStore ? withConversionAutoFire(rawClient, createConversionAutoFire(conversionStore)) : rawClient,
3578
+ [rawClient, conversionStore]
3579
+ );
3580
+ const client = useMemo4(
3581
+ () => createTypedClient(conversionClient, triggers, { debug }),
3582
+ [conversionClient]
3583
+ );
3584
+ useEffect5(() => {
3585
+ if (trackingConfig) {
3586
+ getTrackingConfigRuntime(trackingConfig).start();
3587
+ } else if (gtagIds && Object.keys(gtagIds).length > 0) {
3588
+ bootstrapMultipleGtags(gtagIds);
3589
+ } else if (gtagId) {
3590
+ bootstrapGoogleAdsTracking(gtagId);
3591
+ }
3592
+ }, [gtagId, gtagIdsKey]);
3593
+ const metaPixelIdsKey = useMemo4(
3594
+ () => metaPixelIds ? JSON.stringify(metaPixelIds) : "",
3595
+ [metaPixelIds]
3596
+ );
3597
+ useEffect5(() => {
3598
+ if (metaPixelIds && Object.keys(metaPixelIds).length > 0) {
3599
+ bootstrapMultiplePixels(metaPixelIds);
3600
+ } else if (metaPixelId) {
3601
+ bootstrapMetaPixel(metaPixelId);
3602
+ }
3603
+ }, [metaPixelId, metaPixelIdsKey]);
3604
+ useEffect5(() => {
3605
+ return attachClientCapturesOnce(rawClient, () => {
3606
+ const detachers = [];
3607
+ const detectorClient = conversionStore ? conversionClient : rawClient;
3608
+ const pageClient = trackingConfig && conversionStore && "queuePageView" in conversionStore ? {
3609
+ ...detectorClient,
3610
+ trackEvent: (input) => {
3611
+ detectorClient.trackEvent(input);
3612
+ if (input.eventType === "page_view") conversionStore.queuePageView();
3613
+ }
3614
+ } : detectorClient;
3615
+ detachers.push(attachAutoPageView(pageClient));
3616
+ detachers.push(attachBfcacheRestore(pageClient));
3617
+ detachers.push(attachPageExit(detectorClient));
3618
+ const timeOnSite = triggers.automatic.time_on_site;
3619
+ if (timeOnSite) {
3620
+ detachers.push(attachTimeOnSite(detectorClient, timeOnSite));
3621
+ }
3622
+ const specificPageVisit = triggers.automatic.specific_page_visit;
3623
+ if (specificPageVisit) {
3624
+ detachers.push(attachSpecificPageVisit(detectorClient, specificPageVisit));
3625
+ }
3626
+ const scrollDepth = triggers.automatic.scroll_depth;
3627
+ if (scrollDepth) {
3628
+ detachers.push(attachScrollDepth(detectorClient, scrollDepth));
3629
+ }
3630
+ const multiPageSession = triggers.automatic.multi_page_session;
3631
+ if (multiPageSession) {
3632
+ detachers.push(attachMultiPageSession(detectorClient, multiPageSession));
3633
+ }
3634
+ const formStart = triggers.automatic.form_start;
3635
+ if (formStart) {
3636
+ detachers.push(attachFormStart(detectorClient, formStart));
3637
+ }
3638
+ const ctaClick = triggers.manual?.cta_click;
3639
+ if (ctaClick) {
3640
+ detachers.push(attachCtaClickCapture(detectorClient, ctaClick));
3641
+ }
3642
+ const phoneClick = triggers.manual?.phone_click;
3643
+ if (phoneClick) {
3644
+ detachers.push(attachPhoneClickCapture(detectorClient, phoneClick));
3645
+ }
3646
+ return () => {
3647
+ for (let i = detachers.length - 1; i >= 0; i--) {
3648
+ detachers[i]();
3649
+ }
3650
+ };
3651
+ });
3652
+ }, [conversionClient, conversionStore, rawClient]);
3653
+ return /* @__PURE__ */ jsx3(TrackingContext.Provider, { value: client, children: /* @__PURE__ */ jsx3(PhoneConfigProvider, { value: phone ?? null, children }) });
3654
+ }
3655
+ function useTracking() {
3656
+ const client = useContext2(TrackingContext);
3657
+ if (client === null) {
3658
+ throw new Error(
3659
+ "useTracking must be called inside a <TrackingProvider> returned by createTracking()"
3660
+ );
3661
+ }
3662
+ return client;
3663
+ }
3664
+ return { TrackingProvider, useTracking };
3665
+ }
3666
+ export {
3667
+ AdPlatformTracking,
3668
+ ConsentBanner,
3669
+ GoogleAdsTracking,
3670
+ PhoneField,
3671
+ createTracking,
3672
+ useConsent,
3673
+ useConsentState,
3674
+ useCookiePreferences,
3675
+ useGclid,
3676
+ usePhoneConfig,
3677
+ usePhoneField,
3678
+ useTrackingParams
3679
+ };
3680
+ //# sourceMappingURL=client.mjs.map