@usesophi/sophi-web-object 1.3.0 → 1.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/sophi.esm.js +574 -20
- package/dist/sophi.esm.js.map +1 -1
- package/dist/sophi.js +572 -44
- package/dist/sophi.js.map +1 -1
- package/dist/sophi.min.js +2 -2
- package/dist/types/attribution.d.ts +19 -0
- package/dist/types/auth.d.ts +7 -0
- package/dist/types/collector.d.ts +13 -1
- package/dist/types/iife.d.ts +13 -0
- package/dist/types/index.d.ts +14 -2
- package/dist/types/objects/entry.d.ts +16 -0
- package/dist/types/queue.d.ts +11 -2
- package/dist/types/sender.d.ts +2 -2
- package/dist/types/types.d.ts +40 -0
- package/package.json +2 -1
package/dist/sophi.js
CHANGED
|
@@ -1,10 +1,44 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* sophi-web-object v1.3.
|
|
2
|
+
* sophi-web-object v1.3.2
|
|
3
3
|
* Framework-agnostic e-commerce tracking script
|
|
4
4
|
*/
|
|
5
|
-
|
|
5
|
+
(function () {
|
|
6
6
|
'use strict';
|
|
7
7
|
|
|
8
|
+
/******************************************************************************
|
|
9
|
+
Copyright (c) Microsoft Corporation.
|
|
10
|
+
|
|
11
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
|
12
|
+
purpose with or without fee is hereby granted.
|
|
13
|
+
|
|
14
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
15
|
+
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
16
|
+
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
17
|
+
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
18
|
+
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
19
|
+
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
20
|
+
PERFORMANCE OF THIS SOFTWARE.
|
|
21
|
+
***************************************************************************** */
|
|
22
|
+
/* global Reflect, Promise, SuppressedError, Symbol, Iterator */
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
function __rest(s, e) {
|
|
26
|
+
var t = {};
|
|
27
|
+
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
|
|
28
|
+
t[p] = s[p];
|
|
29
|
+
if (s != null && typeof Object.getOwnPropertySymbols === "function")
|
|
30
|
+
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
|
|
31
|
+
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
|
|
32
|
+
t[p[i]] = s[p[i]];
|
|
33
|
+
}
|
|
34
|
+
return t;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
|
|
38
|
+
var e = new Error(message);
|
|
39
|
+
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
|
40
|
+
};
|
|
41
|
+
|
|
8
42
|
/** Sophi API origin — set via SOPHI_API_URL in .env at build time. */
|
|
9
43
|
const SOPHI_API_ORIGIN = "https://api.usesophi.com";
|
|
10
44
|
const DEFAULTS = {
|
|
@@ -112,6 +146,16 @@ var SophiTracker = (function (exports) {
|
|
|
112
146
|
}
|
|
113
147
|
// ─── Public API ───────────────────────────────────────────────────────────────
|
|
114
148
|
let sessionPromise = null;
|
|
149
|
+
let resolvedSession = null;
|
|
150
|
+
/**
|
|
151
|
+
* Synchronous view of the established session, or null if none has resolved
|
|
152
|
+
* yet. The unload flush runs inside a visibilitychange(hidden) handler where
|
|
153
|
+
* awaiting a promise is unreliable — the page can be torn down before the
|
|
154
|
+
* microtask runs — so it must read the session without going async.
|
|
155
|
+
*/
|
|
156
|
+
function getResolvedSession() {
|
|
157
|
+
return resolvedSession;
|
|
158
|
+
}
|
|
115
159
|
function getSession() {
|
|
116
160
|
if (sessionPromise)
|
|
117
161
|
return sessionPromise;
|
|
@@ -155,7 +199,8 @@ var SophiTracker = (function (exports) {
|
|
|
155
199
|
writeCookie(ns("client-id"), clientId);
|
|
156
200
|
writeCookie(ns("external-user-id"), userId !== null && userId !== void 0 ? userId : "");
|
|
157
201
|
log("Session created and stored in cookies");
|
|
158
|
-
|
|
202
|
+
resolvedSession = { accessToken, clientId };
|
|
203
|
+
return resolvedSession;
|
|
159
204
|
})();
|
|
160
205
|
return sessionPromise;
|
|
161
206
|
}
|
|
@@ -167,10 +212,12 @@ var SophiTracker = (function (exports) {
|
|
|
167
212
|
*/
|
|
168
213
|
function resetSession() {
|
|
169
214
|
sessionPromise = null;
|
|
215
|
+
resolvedSession = null;
|
|
170
216
|
log("Session promise reset (cookies preserved)");
|
|
171
217
|
}
|
|
172
218
|
function clearSession() {
|
|
173
219
|
sessionPromise = null;
|
|
220
|
+
resolvedSession = null;
|
|
174
221
|
clearCookie(ns("access-token"));
|
|
175
222
|
clearCookie(ns("client-id"));
|
|
176
223
|
clearCookie(ns("external-user-id"));
|
|
@@ -221,14 +268,41 @@ var SophiTracker = (function (exports) {
|
|
|
221
268
|
xhr.send(body);
|
|
222
269
|
});
|
|
223
270
|
}
|
|
224
|
-
function
|
|
271
|
+
function sendOnUnload(envelope, session) {
|
|
225
272
|
const { endpoint } = getConfig();
|
|
226
273
|
const url = `${endpoint}/event/v1/external-events`;
|
|
274
|
+
const body = JSON.stringify(envelope);
|
|
275
|
+
// navigator.sendBeacon cannot carry headers, and the external-events route
|
|
276
|
+
// sits behind an authorizer — an unauthenticated beacon is always rejected
|
|
277
|
+
// server-side. fetch keepalive survives page teardown like a beacon while
|
|
278
|
+
// keeping the auth headers, so it is the primary path; the beacon is only a
|
|
279
|
+
// last-resort fallback for browsers without fetch.
|
|
280
|
+
if (typeof fetch !== "undefined") {
|
|
281
|
+
try {
|
|
282
|
+
fetch(url, {
|
|
283
|
+
method: "POST",
|
|
284
|
+
keepalive: true,
|
|
285
|
+
headers: {
|
|
286
|
+
"Content-Type": "application/json",
|
|
287
|
+
Authorization: `Bearer ${session.accessToken}`,
|
|
288
|
+
"x-sophi-client-id": session.clientId,
|
|
289
|
+
},
|
|
290
|
+
body,
|
|
291
|
+
}).catch(() => {
|
|
292
|
+
// Page is going away — nothing left to retry against.
|
|
293
|
+
});
|
|
294
|
+
return true;
|
|
295
|
+
}
|
|
296
|
+
catch (_a) {
|
|
297
|
+
// keepalive rejected synchronously (e.g. body over the in-flight quota) —
|
|
298
|
+
// fall through to the beacon attempt below.
|
|
299
|
+
}
|
|
300
|
+
}
|
|
227
301
|
if (typeof navigator === "undefined" || !navigator.sendBeacon) {
|
|
228
302
|
warn("sendBeacon not available — event may be lost on page unload");
|
|
229
303
|
return false;
|
|
230
304
|
}
|
|
231
|
-
const blob = new Blob([
|
|
305
|
+
const blob = new Blob([body], { type: "application/json" });
|
|
232
306
|
return navigator.sendBeacon(url, blob);
|
|
233
307
|
}
|
|
234
308
|
|
|
@@ -262,6 +336,26 @@ var SophiTracker = (function (exports) {
|
|
|
262
336
|
log(`Queued event: ${envelope.event_type} (queue size: ${queue.length})`);
|
|
263
337
|
scheduleFlush();
|
|
264
338
|
}
|
|
339
|
+
/**
|
|
340
|
+
* Send one event right away, bypassing the debounce window. Used for Sophi
|
|
341
|
+
* button clicks, which are usually followed by a same-tab navigation.
|
|
342
|
+
*
|
|
343
|
+
* With an established session the event goes out through fetch keepalive
|
|
344
|
+
* (with auth headers), which survives the page being torn down. Without a
|
|
345
|
+
* session yet it falls back to the normal queue.
|
|
346
|
+
*/
|
|
347
|
+
function sendImmediate(envelope) {
|
|
348
|
+
if (!hasStorageConsent()) {
|
|
349
|
+
log(`Dropped event (no storage consent): ${envelope.event_type}`);
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
const session = getResolvedSession();
|
|
353
|
+
if (session && sendOnUnload(envelope, session)) {
|
|
354
|
+
log(`Sent event immediately: ${envelope.event_type}`);
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
enqueue(envelope);
|
|
358
|
+
}
|
|
265
359
|
function scheduleFlush() {
|
|
266
360
|
if (debounceTimer !== null)
|
|
267
361
|
return;
|
|
@@ -299,19 +393,229 @@ var SophiTracker = (function (exports) {
|
|
|
299
393
|
}
|
|
300
394
|
flushing = false;
|
|
301
395
|
}
|
|
302
|
-
/** Flush remaining events
|
|
303
|
-
|
|
396
|
+
/** Flush remaining events before page teardown. */
|
|
397
|
+
function flushOnUnload() {
|
|
304
398
|
if (queue.length === 0)
|
|
305
399
|
return;
|
|
306
|
-
|
|
400
|
+
// Runs inside visibilitychange(hidden) — the page may be torn down before a
|
|
401
|
+
// microtask resolves, so only an already-established session is usable here.
|
|
402
|
+
// No session yet means no event ever left this page anyway.
|
|
403
|
+
const session = getResolvedSession();
|
|
307
404
|
if (!session)
|
|
308
405
|
return;
|
|
309
406
|
for (const item of queue) {
|
|
310
|
-
|
|
407
|
+
sendOnUnload(item.envelope, session);
|
|
311
408
|
}
|
|
312
409
|
queue.length = 0;
|
|
313
410
|
}
|
|
314
411
|
|
|
412
|
+
/**
|
|
413
|
+
* Campaign attribution (opt-in via `config.attribution: true`).
|
|
414
|
+
*
|
|
415
|
+
* On boot the SDK reads UTM parameters, ad click IDs and the external referrer
|
|
416
|
+
* hostname of the current page view. A page view that has any of them is a
|
|
417
|
+
* "touch". The first touch is kept for 30 days; the last touch is replaced by
|
|
418
|
+
* every new touch; direct visits and internal navigation change nothing.
|
|
419
|
+
*
|
|
420
|
+
* The value is held in memory and written to localStorage only while storage
|
|
421
|
+
* consent is granted. It is attached to every event under
|
|
422
|
+
* `page.custom._sophi.attribution` by the collector.
|
|
423
|
+
*/
|
|
424
|
+
const UTM_FIELDS = {
|
|
425
|
+
utm_source: 'source',
|
|
426
|
+
utm_medium: 'medium',
|
|
427
|
+
utm_campaign: 'campaign',
|
|
428
|
+
utm_term: 'term',
|
|
429
|
+
utm_content: 'content',
|
|
430
|
+
};
|
|
431
|
+
const CLICK_ID_SOURCES = {
|
|
432
|
+
gclid: 'google',
|
|
433
|
+
gbraid: 'google',
|
|
434
|
+
wbraid: 'google',
|
|
435
|
+
fbclid: 'facebook',
|
|
436
|
+
msclkid: 'bing',
|
|
437
|
+
ttclid: 'tiktok',
|
|
438
|
+
li_fat_id: 'linkedin',
|
|
439
|
+
};
|
|
440
|
+
const TOUCH_TTL_SECONDS = 30 * 86400;
|
|
441
|
+
const MAX_VALUE_LENGTH = 256;
|
|
442
|
+
/** Touch detected on this page view (null = direct / internal). */
|
|
443
|
+
let pageTouch = null;
|
|
444
|
+
/** Resolved attribution for this page view, attached to events. */
|
|
445
|
+
let current = null;
|
|
446
|
+
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
|
447
|
+
function isEnabled() {
|
|
448
|
+
return getConfig().attribution === true;
|
|
449
|
+
}
|
|
450
|
+
function storageKey() {
|
|
451
|
+
return `sophi-${hashKey(getConfig().apiKey)}-attribution`;
|
|
452
|
+
}
|
|
453
|
+
function clip(value) {
|
|
454
|
+
const trimmed = value === null || value === void 0 ? void 0 : value.trim();
|
|
455
|
+
return trimmed ? trimmed.slice(0, MAX_VALUE_LENGTH) : undefined;
|
|
456
|
+
}
|
|
457
|
+
function bareHost(host) {
|
|
458
|
+
return host.toLowerCase().replace(/^www\./, '');
|
|
459
|
+
}
|
|
460
|
+
function isTouch(value) {
|
|
461
|
+
return (typeof value === 'object' &&
|
|
462
|
+
value !== null &&
|
|
463
|
+
typeof value.timestamp === 'number');
|
|
464
|
+
}
|
|
465
|
+
function readStored() {
|
|
466
|
+
try {
|
|
467
|
+
const raw = localStorage.getItem(storageKey());
|
|
468
|
+
if (!raw)
|
|
469
|
+
return null;
|
|
470
|
+
const parsed = JSON.parse(raw);
|
|
471
|
+
return {
|
|
472
|
+
first: isTouch(parsed === null || parsed === void 0 ? void 0 : parsed.first) ? parsed.first : undefined,
|
|
473
|
+
last: isTouch(parsed === null || parsed === void 0 ? void 0 : parsed.last) ? parsed.last : undefined,
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
catch (_a) {
|
|
477
|
+
return null;
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
function writeStored(value) {
|
|
481
|
+
try {
|
|
482
|
+
if (value) {
|
|
483
|
+
localStorage.setItem(storageKey(), JSON.stringify(value));
|
|
484
|
+
}
|
|
485
|
+
else {
|
|
486
|
+
localStorage.removeItem(storageKey());
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
catch (_a) {
|
|
490
|
+
// Storage unavailable (private mode, blocked) — keep the in-memory value.
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
function fresh(touch, now) {
|
|
494
|
+
return touch && now - touch.timestamp < TOUCH_TTL_SECONDS ? touch : undefined;
|
|
495
|
+
}
|
|
496
|
+
/** Combines stored state with this page view's touch. */
|
|
497
|
+
function mergeAttribution(stored, touch, now) {
|
|
498
|
+
let first = fresh(stored === null || stored === void 0 ? void 0 : stored.first, now);
|
|
499
|
+
let last = fresh(stored === null || stored === void 0 ? void 0 : stored.last, now);
|
|
500
|
+
if (touch) {
|
|
501
|
+
last = touch;
|
|
502
|
+
first = first !== null && first !== void 0 ? first : touch;
|
|
503
|
+
}
|
|
504
|
+
if (!first && !last)
|
|
505
|
+
return null;
|
|
506
|
+
const result = {};
|
|
507
|
+
if (first)
|
|
508
|
+
result.first = first;
|
|
509
|
+
if (last)
|
|
510
|
+
result.last = last;
|
|
511
|
+
return result;
|
|
512
|
+
}
|
|
513
|
+
/**
|
|
514
|
+
* Reads the touch from a page URL and referrer. Returns null for a direct
|
|
515
|
+
* visit or internal navigation. Only the referrer hostname is kept, and the
|
|
516
|
+
* landing URL keeps only its origin, path, UTM and click-ID parameters.
|
|
517
|
+
*/
|
|
518
|
+
function detectTouch(href, referrer, now) {
|
|
519
|
+
var _a, _b;
|
|
520
|
+
let url;
|
|
521
|
+
try {
|
|
522
|
+
url = new URL(href);
|
|
523
|
+
}
|
|
524
|
+
catch (_c) {
|
|
525
|
+
return null;
|
|
526
|
+
}
|
|
527
|
+
const params = url.searchParams;
|
|
528
|
+
const touch = { timestamp: now };
|
|
529
|
+
const kept = new URLSearchParams();
|
|
530
|
+
for (const [param, field] of Object.entries(UTM_FIELDS)) {
|
|
531
|
+
const value = clip(params.get(param));
|
|
532
|
+
if (value) {
|
|
533
|
+
touch[field] = value;
|
|
534
|
+
kept.set(param, value);
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
for (const param of Object.keys(CLICK_ID_SOURCES)) {
|
|
538
|
+
const value = clip(params.get(param));
|
|
539
|
+
if (value) {
|
|
540
|
+
kept.set(param, value);
|
|
541
|
+
if (!touch.click_id) {
|
|
542
|
+
touch.click_id = value;
|
|
543
|
+
touch.click_id_type = param;
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
let referrerHost;
|
|
548
|
+
if (referrer) {
|
|
549
|
+
try {
|
|
550
|
+
const host = new URL(referrer).hostname;
|
|
551
|
+
if (host && bareHost(host) !== bareHost(url.hostname)) {
|
|
552
|
+
referrerHost = host.toLowerCase();
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
catch (_d) {
|
|
556
|
+
// Malformed referrer — ignore.
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
const hasCampaign = kept.toString() !== '';
|
|
560
|
+
if (!hasCampaign && !referrerHost)
|
|
561
|
+
return null;
|
|
562
|
+
if (referrerHost)
|
|
563
|
+
touch.referrer = referrerHost;
|
|
564
|
+
if (!touch.source) {
|
|
565
|
+
if (touch.click_id_type) {
|
|
566
|
+
touch.source = CLICK_ID_SOURCES[touch.click_id_type];
|
|
567
|
+
}
|
|
568
|
+
else if (referrerHost) {
|
|
569
|
+
touch.source = referrerHost;
|
|
570
|
+
touch.medium = (_a = touch.medium) !== null && _a !== void 0 ? _a : 'referral';
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
const query = kept.toString();
|
|
574
|
+
touch.landing_url = (_b = clip(`${url.origin}${url.pathname}${query ? `?${query}` : ''}`)) !== null && _b !== void 0 ? _b : url.origin;
|
|
575
|
+
return touch;
|
|
576
|
+
}
|
|
577
|
+
// ─── Public API ───────────────────────────────────────────────────────────────
|
|
578
|
+
/** Called once at bootstrap. Does nothing unless `config.attribution` is true. */
|
|
579
|
+
function captureAttribution() {
|
|
580
|
+
pageTouch = null;
|
|
581
|
+
current = null;
|
|
582
|
+
if (!isEnabled())
|
|
583
|
+
return;
|
|
584
|
+
const now = Math.floor(Date.now() / 1000);
|
|
585
|
+
pageTouch = detectTouch(window.location.href, document.referrer, now);
|
|
586
|
+
if (hasStorageConsent()) {
|
|
587
|
+
current = mergeAttribution(readStored(), pageTouch, now);
|
|
588
|
+
writeStored(current);
|
|
589
|
+
}
|
|
590
|
+
else {
|
|
591
|
+
// No consent: keep this page view's touch in memory only.
|
|
592
|
+
current = mergeAttribution(null, pageTouch, now);
|
|
593
|
+
}
|
|
594
|
+
if (current)
|
|
595
|
+
log('Attribution captured', current);
|
|
596
|
+
}
|
|
597
|
+
/** Called once storage consent is granted: merges with stored state and persists. */
|
|
598
|
+
function persistAttribution() {
|
|
599
|
+
if (!isEnabled() || !hasStorageConsent())
|
|
600
|
+
return;
|
|
601
|
+
const now = Math.floor(Date.now() / 1000);
|
|
602
|
+
current = mergeAttribution(readStored(), pageTouch, now);
|
|
603
|
+
writeStored(current);
|
|
604
|
+
}
|
|
605
|
+
/** Called when storage consent is withdrawn: removes the stored value. */
|
|
606
|
+
function clearAttribution() {
|
|
607
|
+
if (!isEnabled())
|
|
608
|
+
return;
|
|
609
|
+
writeStored(null);
|
|
610
|
+
current = mergeAttribution(null, pageTouch, Math.floor(Date.now() / 1000));
|
|
611
|
+
}
|
|
612
|
+
/** Attribution to attach to events, or undefined when there is none. */
|
|
613
|
+
function getAttribution() {
|
|
614
|
+
if (!current || !isEnabled())
|
|
615
|
+
return undefined;
|
|
616
|
+
return Object.assign({}, current);
|
|
617
|
+
}
|
|
618
|
+
|
|
315
619
|
function mapPageEvent(page, sdkVersion, context) {
|
|
316
620
|
if (!page.type) {
|
|
317
621
|
warn('page.type is required — skipping page_view event');
|
|
@@ -324,6 +628,90 @@ var SophiTracker = (function (exports) {
|
|
|
324
628
|
return Object.assign({ event_type: 'page_view', client_timestamp: Math.floor(Date.now() / 1000), sdk_version: sdkVersion, page }, context);
|
|
325
629
|
}
|
|
326
630
|
|
|
631
|
+
const MAX_LENGTH = 64;
|
|
632
|
+
const ENTRY_TYPES = [
|
|
633
|
+
'search_bar',
|
|
634
|
+
'post_search',
|
|
635
|
+
'floating_trigger',
|
|
636
|
+
'homepage_widget',
|
|
637
|
+
'pdp',
|
|
638
|
+
'product_grid',
|
|
639
|
+
'menu',
|
|
640
|
+
'checkout',
|
|
641
|
+
];
|
|
642
|
+
/**
|
|
643
|
+
* Returns a copy of `page` with `patch` merged into `page.custom._sophi`.
|
|
644
|
+
* The integrator's own `page.custom` keys are kept, and the original object
|
|
645
|
+
* is never mutated (writing back into sophi_object.page would make the Proxy
|
|
646
|
+
* emit an extra page_view).
|
|
647
|
+
*/
|
|
648
|
+
function withSophi(page, patch) {
|
|
649
|
+
var _a;
|
|
650
|
+
const custom = (_a = page.custom) !== null && _a !== void 0 ? _a : {};
|
|
651
|
+
const existing = custom._sophi;
|
|
652
|
+
const previous = typeof existing === 'object' && existing !== null && !Array.isArray(existing)
|
|
653
|
+
? existing
|
|
654
|
+
: {};
|
|
655
|
+
return Object.assign(Object.assign({}, page), { custom: Object.assign(Object.assign({}, custom), { _sophi: Object.assign(Object.assign({}, previous), patch) }) });
|
|
656
|
+
}
|
|
657
|
+
/** Validates and normalises an entry. Returns null (after a warning) when invalid. */
|
|
658
|
+
function normalizeEntry(input) {
|
|
659
|
+
const placement = typeof (input === null || input === void 0 ? void 0 : input.placement) === 'string' ? input.placement.trim() : '';
|
|
660
|
+
if (!placement) {
|
|
661
|
+
warn('entry.placement is required — skipping entry event');
|
|
662
|
+
return null;
|
|
663
|
+
}
|
|
664
|
+
if (placement.length > MAX_LENGTH) {
|
|
665
|
+
warn(`entry.placement must be at most ${MAX_LENGTH} characters — skipping entry event`);
|
|
666
|
+
return null;
|
|
667
|
+
}
|
|
668
|
+
const entry = { placement };
|
|
669
|
+
if ((input === null || input === void 0 ? void 0 : input.group) !== undefined) {
|
|
670
|
+
const group = typeof input.group === 'string' ? input.group.trim() : '';
|
|
671
|
+
if (!group) {
|
|
672
|
+
warn('entry.group must be a non-empty string — sending without group');
|
|
673
|
+
}
|
|
674
|
+
else if (group.length > MAX_LENGTH) {
|
|
675
|
+
warn(`entry.group must be at most ${MAX_LENGTH} characters — sending without group`);
|
|
676
|
+
}
|
|
677
|
+
else {
|
|
678
|
+
entry.group = group;
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
if ((input === null || input === void 0 ? void 0 : input.type) !== undefined) {
|
|
682
|
+
if (ENTRY_TYPES.includes(input.type)) {
|
|
683
|
+
entry.type = input.type;
|
|
684
|
+
}
|
|
685
|
+
else {
|
|
686
|
+
warn(`entry.type "${String(input.type)}" is not a standard type — sending without type`);
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
return entry;
|
|
690
|
+
}
|
|
691
|
+
/**
|
|
692
|
+
* Maps a Sophi button click to a `custom` event. The entry travels under
|
|
693
|
+
* `page.custom._sophi.entry`, so no change to the ingest contract is needed.
|
|
694
|
+
*/
|
|
695
|
+
function mapEntryEvent(input, page, sdkVersion) {
|
|
696
|
+
if (!page.type) {
|
|
697
|
+
warn('page.type is required — skipping entry event');
|
|
698
|
+
return null;
|
|
699
|
+
}
|
|
700
|
+
if (!page.url) {
|
|
701
|
+
warn('page.url is required — skipping entry event');
|
|
702
|
+
return null;
|
|
703
|
+
}
|
|
704
|
+
const entry = normalizeEntry(input);
|
|
705
|
+
if (!entry)
|
|
706
|
+
return null;
|
|
707
|
+
return {
|
|
708
|
+
event_type: 'custom',
|
|
709
|
+
client_timestamp: Math.floor(Date.now() / 1000),
|
|
710
|
+
sdk_version: sdkVersion,
|
|
711
|
+
page: withSophi(page, { entry }),
|
|
712
|
+
};
|
|
713
|
+
}
|
|
714
|
+
|
|
327
715
|
function mapUserEvent(user, page, sdkVersion, context) {
|
|
328
716
|
if (!user.consent) {
|
|
329
717
|
warn('user.consent is required — skipping identify event');
|
|
@@ -459,7 +847,7 @@ var SophiTracker = (function (exports) {
|
|
|
459
847
|
}
|
|
460
848
|
|
|
461
849
|
// Injected at build time via rollup-plugin-replace; falls back to package version.
|
|
462
|
-
const SDK_VERSION = '"1.3.
|
|
850
|
+
const SDK_VERSION = '"1.3.2"';
|
|
463
851
|
// ─── Default event types per object key ──────────────────────────────────────
|
|
464
852
|
const DEFAULT_EVENT_TYPE = {
|
|
465
853
|
page: 'page_view',
|
|
@@ -555,16 +943,53 @@ var SophiTracker = (function (exports) {
|
|
|
555
943
|
if (shouldLogCollection) {
|
|
556
944
|
log(`Collected: ${envelope.event_type} (triggered by: ${triggeredBy})`);
|
|
557
945
|
}
|
|
558
|
-
enqueue(envelope);
|
|
946
|
+
enqueue(withAttribution(envelope));
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
/**
|
|
950
|
+
* Attach campaign attribution under `page.custom._sophi.attribution` when it
|
|
951
|
+
* is enabled and known. Returns the envelope unchanged otherwise, so events
|
|
952
|
+
* stay byte-identical for integrations that have not opted in.
|
|
953
|
+
*/
|
|
954
|
+
function withAttribution(envelope) {
|
|
955
|
+
const attribution = getAttribution();
|
|
956
|
+
if (!attribution)
|
|
957
|
+
return envelope;
|
|
958
|
+
return Object.assign(Object.assign({}, envelope), { page: withSophi(envelope.page, { attribution }) });
|
|
959
|
+
}
|
|
960
|
+
/**
|
|
961
|
+
* Collect a Sophi button click (`SophiTracker.trackEntry` or a tagged element)
|
|
962
|
+
* and send it immediately. The click usually triggers a same-tab navigation,
|
|
963
|
+
* so it bypasses the debounced queue when a session is available.
|
|
964
|
+
*/
|
|
965
|
+
function collectEntry(entry, obj) {
|
|
966
|
+
var _a;
|
|
967
|
+
const page = obj === null || obj === void 0 ? void 0 : obj.page;
|
|
968
|
+
if (!page) {
|
|
969
|
+
warn(`sophi_object.page is required to send any event — skipping`);
|
|
970
|
+
return;
|
|
971
|
+
}
|
|
972
|
+
const envelope = mapEntryEvent(entry, page, SDK_VERSION);
|
|
973
|
+
if (envelope) {
|
|
974
|
+
log(`Collected: custom (entry: ${((_a = envelope.page.custom) === null || _a === void 0 ? void 0 : _a._sophi).entry.placement})`);
|
|
975
|
+
sendImmediate(withAttribution(envelope));
|
|
559
976
|
}
|
|
560
977
|
}
|
|
978
|
+
/**
|
|
979
|
+
* When `transaction` is among the keys to collect, omit `page`.
|
|
980
|
+
* `page` remains on the object as envelope context for purchase; it must not
|
|
981
|
+
* also emit a sibling `page_view`.
|
|
982
|
+
*/
|
|
983
|
+
function omitPageWhenTransactionPresent(keys) {
|
|
984
|
+
if (!keys.includes('transaction'))
|
|
985
|
+
return keys;
|
|
986
|
+
return keys.filter((k) => k !== 'page');
|
|
987
|
+
}
|
|
561
988
|
/** Collect all present sub-objects from the full sophi_object snapshot at load time. */
|
|
562
989
|
function collectAll(obj) {
|
|
563
|
-
const
|
|
564
|
-
for (const key of
|
|
565
|
-
|
|
566
|
-
collect(key, obj);
|
|
567
|
-
}
|
|
990
|
+
const present = ['page', 'user', 'product', 'basket', 'listing', 'transaction'].filter((key) => obj[key] !== undefined);
|
|
991
|
+
for (const key of omitPageWhenTransactionPresent(present)) {
|
|
992
|
+
collect(key, obj);
|
|
568
993
|
}
|
|
569
994
|
}
|
|
570
995
|
|
|
@@ -639,14 +1064,6 @@ var SophiTracker = (function (exports) {
|
|
|
639
1064
|
function setState(s) {
|
|
640
1065
|
state = s;
|
|
641
1066
|
}
|
|
642
|
-
/**
|
|
643
|
-
* Reset all module-level state to initial values.
|
|
644
|
-
* For test isolation only — do not call in production code.
|
|
645
|
-
*/
|
|
646
|
-
function resetTrackerState() {
|
|
647
|
-
state = TrackerState.BUFFERING;
|
|
648
|
-
pendingQueue.length = 0;
|
|
649
|
-
}
|
|
650
1067
|
|
|
651
1068
|
// ─── Bootstrap guard ──────────────────────────────────────────────────────────
|
|
652
1069
|
/**
|
|
@@ -655,6 +1072,7 @@ var SophiTracker = (function (exports) {
|
|
|
655
1072
|
*/
|
|
656
1073
|
let bootstrapGuard = false;
|
|
657
1074
|
let unloadFlushRegistered = false;
|
|
1075
|
+
let entryClickListenerRegistered = false;
|
|
658
1076
|
// ─── Private push implementation ──────────────────────────────────────────────
|
|
659
1077
|
/**
|
|
660
1078
|
* Execute a push() call immediately against the current sophi_object state.
|
|
@@ -680,9 +1098,10 @@ var SophiTracker = (function (exports) {
|
|
|
680
1098
|
finally {
|
|
681
1099
|
endInternalPushSuppression();
|
|
682
1100
|
}
|
|
683
|
-
const
|
|
1101
|
+
const eventPartial = omitEmptyBasketOnRemove(partial);
|
|
1102
|
+
const explicitTrigger = resolveExplicitTriggeredKey(eventPartial);
|
|
684
1103
|
if (explicitTrigger) {
|
|
685
|
-
const scopedObj = buildExplicitScopedObject(
|
|
1104
|
+
const scopedObj = buildExplicitScopedObject(eventPartial, window.sophi_object);
|
|
686
1105
|
collectExplicit(explicitTrigger, scopedObj);
|
|
687
1106
|
}
|
|
688
1107
|
log(`Explicit push ${String((_a = partial.event_type) !== null && _a !== void 0 ? _a : 'custom')} queued once`);
|
|
@@ -699,7 +1118,9 @@ var SophiTracker = (function (exports) {
|
|
|
699
1118
|
finally {
|
|
700
1119
|
endInternalPushSuppression();
|
|
701
1120
|
}
|
|
702
|
-
|
|
1121
|
+
// When transaction is present, skip collecting `page` so confirmation
|
|
1122
|
+
// pushes emit one purchase (page is envelope context, not page_view).
|
|
1123
|
+
const triggeredKeys = omitPageWhenTransactionPresent(watchedKeys.filter((k) => k in partial));
|
|
703
1124
|
for (const key of triggeredKeys) {
|
|
704
1125
|
collect(key, window.sophi_object);
|
|
705
1126
|
}
|
|
@@ -768,6 +1189,13 @@ var SophiTracker = (function (exports) {
|
|
|
768
1189
|
initConfig(Object.assign(Object.assign({}, getConfig()), { userId }));
|
|
769
1190
|
resetSession();
|
|
770
1191
|
window.sophi_object.config.userId = userId !== null && userId !== void 0 ? userId : '';
|
|
1192
|
+
// Without storage consent the SDK stays passive: no session request and no
|
|
1193
|
+
// cookies. The new userId is kept in config, so setConsent(true) creates
|
|
1194
|
+
// the session for this user (and merges a guest session if one exists).
|
|
1195
|
+
if (!hasStorageConsent()) {
|
|
1196
|
+
log('updateUser: no storage consent — session will be created when consent is granted.');
|
|
1197
|
+
return;
|
|
1198
|
+
}
|
|
771
1199
|
void getSession();
|
|
772
1200
|
},
|
|
773
1201
|
/**
|
|
@@ -799,6 +1227,7 @@ var SophiTracker = (function (exports) {
|
|
|
799
1227
|
void (async () => {
|
|
800
1228
|
try {
|
|
801
1229
|
await getSession();
|
|
1230
|
+
persistAttribution();
|
|
802
1231
|
if (window.sophi_object) {
|
|
803
1232
|
collectAll(window.sophi_object);
|
|
804
1233
|
}
|
|
@@ -817,13 +1246,62 @@ var SophiTracker = (function (exports) {
|
|
|
817
1246
|
return;
|
|
818
1247
|
setStorageConsentState(false);
|
|
819
1248
|
clearSession();
|
|
1249
|
+
clearAttribution();
|
|
820
1250
|
log('Storage consent withdrawn — Web Object is now passive.');
|
|
821
1251
|
}
|
|
822
1252
|
},
|
|
1253
|
+
/**
|
|
1254
|
+
* Record a click on a Sophi entry point (a button or link that opens Sophi).
|
|
1255
|
+
* Sent as a `custom` event with the entry under `page.custom._sophi.entry`.
|
|
1256
|
+
*
|
|
1257
|
+
* Use this for flows where no element tagged with `data-sophi-placement` is
|
|
1258
|
+
* clicked (e.g. a search submitted with Enter). Do not combine it with the
|
|
1259
|
+
* data attributes on the same button, or the click is counted twice.
|
|
1260
|
+
*
|
|
1261
|
+
* @example
|
|
1262
|
+
* SophiTracker.trackEntry({ placement: 'header_search', group: 'search', type: 'search_bar' })
|
|
1263
|
+
*/
|
|
1264
|
+
trackEntry(entry) {
|
|
1265
|
+
if (getState() === TrackerState.FAILED) {
|
|
1266
|
+
warn('SophiTracker.trackEntry() called after bootstrap failure — ignoring.');
|
|
1267
|
+
return;
|
|
1268
|
+
}
|
|
1269
|
+
try {
|
|
1270
|
+
getConfig();
|
|
1271
|
+
}
|
|
1272
|
+
catch (_a) {
|
|
1273
|
+
warn('SophiTracker.trackEntry() called before initialisation — ignoring.');
|
|
1274
|
+
return;
|
|
1275
|
+
}
|
|
1276
|
+
if (!hasStorageConsent()) {
|
|
1277
|
+
log('trackEntry ignored — no storage consent.');
|
|
1278
|
+
return;
|
|
1279
|
+
}
|
|
1280
|
+
collectEntry(entry, window.sophi_object);
|
|
1281
|
+
},
|
|
823
1282
|
/** Expose session info for debugging */
|
|
824
1283
|
getSession,
|
|
825
1284
|
};
|
|
826
1285
|
// ─── Private helpers ──────────────────────────────────────────────────────────
|
|
1286
|
+
/**
|
|
1287
|
+
* Removing the last item leaves an empty basket. The external-events contract
|
|
1288
|
+
* rejects an empty `basket.line_items` and represents an empty basket by
|
|
1289
|
+
* omitting `basket`, so `remove_from_cart` is sent by its product without the
|
|
1290
|
+
* basket. Applies only to `remove_from_cart` with a product: anywhere else an
|
|
1291
|
+
* empty basket is an integration error and still skips with a warning.
|
|
1292
|
+
* Only the event changes — `sophi_object` keeps what the integrator pushed.
|
|
1293
|
+
*/
|
|
1294
|
+
function omitEmptyBasketOnRemove(partial) {
|
|
1295
|
+
var _a;
|
|
1296
|
+
if (partial.event_type !== 'remove_from_cart' || !partial.product)
|
|
1297
|
+
return partial;
|
|
1298
|
+
const lineItems = (_a = partial.basket) === null || _a === void 0 ? void 0 : _a.line_items;
|
|
1299
|
+
if (!Array.isArray(lineItems) || lineItems.length > 0)
|
|
1300
|
+
return partial;
|
|
1301
|
+
log('remove_from_cart: basket is empty — sending the event without basket.');
|
|
1302
|
+
const { basket: _emptyBasket } = partial, rest = __rest(partial, ["basket"]);
|
|
1303
|
+
return rest;
|
|
1304
|
+
}
|
|
827
1305
|
function resolveExplicitTriggeredKey(partial) {
|
|
828
1306
|
var _a;
|
|
829
1307
|
// Prefer specific commerce objects over page when multiple keys are present.
|
|
@@ -872,6 +1350,12 @@ var SophiTracker = (function (exports) {
|
|
|
872
1350
|
// no session, no cookies, no events — until SophiTracker.setConsent(true).
|
|
873
1351
|
const consentGranted = getConfig().storageConsent !== false;
|
|
874
1352
|
setStorageConsentState(consentGranted);
|
|
1353
|
+
// Opt-in campaign attribution (no-op unless config.attribution is true).
|
|
1354
|
+
// Held in memory without consent; persisted only with consent.
|
|
1355
|
+
captureAttribution();
|
|
1356
|
+
// Sophi button clicks on elements tagged with data-sophi-placement. Installed
|
|
1357
|
+
// in passive mode too; trackEntry() ignores clicks until consent is granted.
|
|
1358
|
+
registerEntryClickListener();
|
|
875
1359
|
if (!consentGranted) {
|
|
876
1360
|
log('Initialised in anonymous mode — no session, cookies, or events until consent is granted.');
|
|
877
1361
|
// Keep the object reactive so its state is current when consent arrives.
|
|
@@ -904,7 +1388,7 @@ var SophiTracker = (function (exports) {
|
|
|
904
1388
|
// Drain pre-load and bootstrap-time push() calls in FIFO order.
|
|
905
1389
|
// collectAll events are already enqueued before any push() drain entries.
|
|
906
1390
|
drainPendingQueue();
|
|
907
|
-
// Flush remaining events on page unload (
|
|
1391
|
+
// Flush remaining events on page unload (keepalive fetch with auth headers).
|
|
908
1392
|
registerUnloadFlush();
|
|
909
1393
|
log('Ready');
|
|
910
1394
|
}
|
|
@@ -914,10 +1398,68 @@ var SophiTracker = (function (exports) {
|
|
|
914
1398
|
unloadFlushRegistered = true;
|
|
915
1399
|
window.addEventListener('visibilitychange', () => {
|
|
916
1400
|
if (document.visibilityState === 'hidden') {
|
|
917
|
-
|
|
1401
|
+
flushOnUnload();
|
|
918
1402
|
}
|
|
919
1403
|
});
|
|
920
1404
|
}
|
|
1405
|
+
/**
|
|
1406
|
+
* One capture-phase click listener on window. Capture runs before the page's
|
|
1407
|
+
* own handlers, so a `stopPropagation()` in an integrator's onclick cannot
|
|
1408
|
+
* hide the click. The innermost tagged element wins, so a chip nested inside a
|
|
1409
|
+
* tagged banner is counted once, as the chip. Never stops or cancels the click.
|
|
1410
|
+
*/
|
|
1411
|
+
function registerEntryClickListener() {
|
|
1412
|
+
if (entryClickListenerRegistered)
|
|
1413
|
+
return;
|
|
1414
|
+
entryClickListenerRegistered = true;
|
|
1415
|
+
window.addEventListener('click', handleEntryClick, true);
|
|
1416
|
+
}
|
|
1417
|
+
function handleEntryClick(event) {
|
|
1418
|
+
try {
|
|
1419
|
+
const entry = readEntryFromEvent(event);
|
|
1420
|
+
if (entry)
|
|
1421
|
+
SophiTracker.trackEntry(entry);
|
|
1422
|
+
}
|
|
1423
|
+
catch (err) {
|
|
1424
|
+
warn('Entry click tracking failed', err);
|
|
1425
|
+
}
|
|
1426
|
+
}
|
|
1427
|
+
/**
|
|
1428
|
+
* Finds the innermost element with `data-sophi-placement` on the event path
|
|
1429
|
+
* (composedPath also crosses open shadow roots) and reads `data-sophi-group`
|
|
1430
|
+
* and `data-sophi-type` from it or its nearest ancestor on the path.
|
|
1431
|
+
*/
|
|
1432
|
+
function readEntryFromEvent(event) {
|
|
1433
|
+
var _a;
|
|
1434
|
+
const path = [];
|
|
1435
|
+
if (typeof event.composedPath === 'function') {
|
|
1436
|
+
for (const node of event.composedPath()) {
|
|
1437
|
+
if (node instanceof Element)
|
|
1438
|
+
path.push(node);
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
else {
|
|
1442
|
+
let node = event.target instanceof Element ? event.target : null;
|
|
1443
|
+
while (node) {
|
|
1444
|
+
path.push(node);
|
|
1445
|
+
node = node.parentElement;
|
|
1446
|
+
}
|
|
1447
|
+
}
|
|
1448
|
+
const index = path.findIndex((el) => el.hasAttribute('data-sophi-placement'));
|
|
1449
|
+
if (index === -1)
|
|
1450
|
+
return null;
|
|
1451
|
+
const inherited = (name) => { var _a, _b; return (_b = (_a = path.slice(index).find((el) => el.hasAttribute(name))) === null || _a === void 0 ? void 0 : _a.getAttribute(name)) !== null && _b !== void 0 ? _b : undefined; };
|
|
1452
|
+
const entry = {
|
|
1453
|
+
placement: (_a = path[index].getAttribute('data-sophi-placement')) !== null && _a !== void 0 ? _a : '',
|
|
1454
|
+
};
|
|
1455
|
+
const group = inherited('data-sophi-group');
|
|
1456
|
+
const type = inherited('data-sophi-type');
|
|
1457
|
+
if (group !== undefined)
|
|
1458
|
+
entry.group = group;
|
|
1459
|
+
if (type !== undefined)
|
|
1460
|
+
entry.type = type;
|
|
1461
|
+
return entry;
|
|
1462
|
+
}
|
|
921
1463
|
// ─── Stub adoption ────────────────────────────────────────────────────────────
|
|
922
1464
|
/**
|
|
923
1465
|
* Inspect the existing window.SophiTracker value before replacing it.
|
|
@@ -967,20 +1509,6 @@ var SophiTracker = (function (exports) {
|
|
|
967
1509
|
else {
|
|
968
1510
|
void bootstrap();
|
|
969
1511
|
}
|
|
970
|
-
/** Reset the bootstrap guard between tests. */
|
|
971
|
-
function _resetBootstrapGuard() {
|
|
972
|
-
bootstrapGuard = false;
|
|
973
|
-
unloadFlushRegistered = false;
|
|
974
|
-
}
|
|
975
|
-
|
|
976
|
-
exports._bootstrap = bootstrap;
|
|
977
|
-
exports._resetBootstrapGuard = _resetBootstrapGuard;
|
|
978
|
-
exports.default = SophiTracker;
|
|
979
|
-
exports.resetTrackerState = resetTrackerState;
|
|
980
|
-
|
|
981
|
-
Object.defineProperty(exports, '__esModule', { value: true });
|
|
982
|
-
|
|
983
|
-
return exports;
|
|
984
1512
|
|
|
985
|
-
})(
|
|
1513
|
+
})();
|
|
986
1514
|
//# sourceMappingURL=sophi.js.map
|