@heyplaybook/hydrogen 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1320 @@
1
+ import { createContext, useContext, useMemo, useCallback, useState, useEffect } from 'react';
2
+ import { jsx, Fragment } from 'react/jsx-runtime';
3
+
4
+ // src/growthbook.ts
5
+ function hashFnv32a(str) {
6
+ let hval = 2166136261;
7
+ const l = str.length;
8
+ for (let i = 0; i < l; i++) {
9
+ hval ^= str.charCodeAt(i);
10
+ hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
11
+ }
12
+ return hval >>> 0;
13
+ }
14
+ function hash(seed, value, version) {
15
+ if (version === 2) {
16
+ return hashFnv32a(hashFnv32a(seed + value) + "") % 1e4 / 1e4;
17
+ }
18
+ if (version === 1) {
19
+ return hashFnv32a(value + seed) % 1e3 / 1e3;
20
+ }
21
+ return null;
22
+ }
23
+ function getEqualWeights(n) {
24
+ if (n <= 0) return [];
25
+ return new Array(n).fill(1 / n);
26
+ }
27
+ function inRange(n, range) {
28
+ return n >= range[0] && n < range[1];
29
+ }
30
+ function inNamespace(hashValue, namespace) {
31
+ const n = hash("__" + namespace[0], hashValue, 1);
32
+ if (n === null) return false;
33
+ return n >= namespace[1] && n < namespace[2];
34
+ }
35
+ function chooseVariation(n, ranges) {
36
+ for (let i = 0; i < ranges.length; i++) {
37
+ if (inRange(n, ranges[i])) return i;
38
+ }
39
+ return -1;
40
+ }
41
+ function getBucketRanges(numVariations, coverage, weights) {
42
+ let cov = coverage === void 0 ? 1 : coverage;
43
+ if (cov < 0) cov = 0;
44
+ else if (cov > 1) cov = 1;
45
+ const equal = getEqualWeights(numVariations);
46
+ let w = weights || equal;
47
+ if (w.length !== numVariations) w = equal;
48
+ const totalWeight = w.reduce((sum, x) => sum + x, 0);
49
+ if (totalWeight < 0.99 || totalWeight > 1.01) w = equal;
50
+ let cumulative = 0;
51
+ return w.map((x) => {
52
+ const start = cumulative;
53
+ cumulative += x;
54
+ return [start, start + cov * x];
55
+ });
56
+ }
57
+
58
+ // src/assign.ts
59
+ var CONTROL_ARM = "control";
60
+ function controlKey(test) {
61
+ return test.arms.find((a) => a.key === CONTROL_ARM)?.key ?? test.arms[0]?.key ?? CONTROL_ARM;
62
+ }
63
+ function assignTest(test, { visitorId, device, visitorType, preview }) {
64
+ const config2 = test.config && typeof test.config === "object" ? test.config : {};
65
+ const pathPrefix = test.targeting?.pathPrefix?.length ? test.targeting.pathPrefix : void 0;
66
+ const base = { config: config2, pathPrefix, status: test.status };
67
+ const control = (reason) => ({
68
+ ...base,
69
+ arm: controlKey(test),
70
+ inTest: false,
71
+ forced: false,
72
+ reason
73
+ });
74
+ if (preview && preview.testKey === test.key) {
75
+ if (test.arms.some((a) => a.key === preview.arm)) {
76
+ return {
77
+ ...base,
78
+ arm: preview.arm,
79
+ inTest: false,
80
+ forced: true,
81
+ reason: "preview"
82
+ };
83
+ }
84
+ }
85
+ if (test.status === "completed") {
86
+ if (test.winner && test.arms.some((a) => a.key === test.winner)) {
87
+ return {
88
+ ...base,
89
+ arm: test.winner,
90
+ inTest: false,
91
+ forced: false,
92
+ reason: "winner"
93
+ };
94
+ }
95
+ return control("not-running");
96
+ }
97
+ if (test.status !== "running") return control("not-running");
98
+ if (test.arms.length === 0) return control("not-running");
99
+ if (!visitorId) return control("no-visitor");
100
+ const t = test.targeting;
101
+ if (t?.device && t.device !== device) return control("targeting-device");
102
+ if (t?.visitorType && t.visitorType !== visitorType) {
103
+ return control("targeting-visitor-type");
104
+ }
105
+ if (test.namespace?.id && Array.isArray(test.namespace.range)) {
106
+ const [start, end] = test.namespace.range;
107
+ if (!inNamespace(visitorId, [test.namespace.id, start, end])) {
108
+ return control("namespace");
109
+ }
110
+ }
111
+ const n = hash(test.seed || test.key, visitorId, test.hashVersion ?? 2);
112
+ if (n === null) return control("hash-error");
113
+ const ranges = getBucketRanges(
114
+ test.arms.length,
115
+ test.coverage ?? 1,
116
+ test.arms.map((a) => a.weight)
117
+ );
118
+ const index = chooseVariation(n, ranges);
119
+ if (index < 0) return control("coverage");
120
+ return {
121
+ ...base,
122
+ arm: test.arms[index].key,
123
+ inTest: true,
124
+ forced: false,
125
+ reason: "assigned"
126
+ };
127
+ }
128
+ function matchesPathPrefix(pathname, prefixes) {
129
+ if (!prefixes?.length) return true;
130
+ const unlocalized = pathname.replace(/^\/[a-z]{2}(-[a-z]{2})?(?=\/)/i, "");
131
+ return prefixes.some(
132
+ (p) => pathname.startsWith(p) || unlocalized.startsWith(p)
133
+ );
134
+ }
135
+
136
+ // src/cookies.ts
137
+ var VISITOR_COOKIE = "_pb_visitor_id";
138
+ var SESSION_VISITOR_COOKIE = "_pb_session_vid";
139
+ var LEGACY_VISITOR_COOKIE = "pb_vid";
140
+ var NEW_SESSION_COOKIE = "pb_new";
141
+ var VISITOR_REFRESHED_COOKIE = "_pb_vs";
142
+ var PREVIEW_COOKIE = "pb_preview";
143
+ var PREVIEW_PARAM = "pb_preview";
144
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
145
+ function isValidVisitorId(value) {
146
+ return !!value && UUID_RE.test(value);
147
+ }
148
+ function parseCookies(header) {
149
+ const out = {};
150
+ if (!header) return out;
151
+ for (const part of header.split(";")) {
152
+ const idx = part.indexOf("=");
153
+ if (idx < 0) continue;
154
+ const name = part.slice(0, idx).trim();
155
+ if (!name || name in out) continue;
156
+ try {
157
+ out[name] = decodeURIComponent(part.slice(idx + 1).trim());
158
+ } catch {
159
+ out[name] = part.slice(idx + 1).trim();
160
+ }
161
+ }
162
+ return out;
163
+ }
164
+ function cookieDomainFor(hostname) {
165
+ if (hostname === "localhost" || /^[\d.]+$/.test(hostname) || /\.(myshopify\.(com|dev)|workers\.dev|shopifypreview\.com)$/.test(hostname)) {
166
+ return void 0;
167
+ }
168
+ const parts = hostname.split(".");
169
+ if (parts.length < 2) return void 0;
170
+ return `.${parts.slice(-2).join(".")}`;
171
+ }
172
+ function serializeCookie(name, value, opts) {
173
+ const sameSite = opts.sameSite ?? "Lax";
174
+ const parts = [
175
+ `${name}=${encodeURIComponent(value)}`,
176
+ "Path=/",
177
+ `SameSite=${sameSite}`
178
+ ];
179
+ if (opts.maxAge !== void 0) parts.push(`Max-Age=${opts.maxAge}`);
180
+ if (opts.domain) parts.push(`Domain=${opts.domain}`);
181
+ if (opts.secure || sameSite === "None") parts.push("Secure");
182
+ if (opts.httpOnly) parts.push("HttpOnly");
183
+ return parts.join("; ");
184
+ }
185
+ function randomUuid() {
186
+ const c = globalThis.crypto;
187
+ if (typeof c.randomUUID === "function") return c.randomUUID();
188
+ const b = new Uint8Array(16);
189
+ c.getRandomValues(b);
190
+ b[6] = b[6] & 15 | 64;
191
+ b[8] = b[8] & 63 | 128;
192
+ const h = Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
193
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
194
+ }
195
+
196
+ // src/consent.ts
197
+ var TRACKING_CONSENT_COOKIE = "_tracking_consent";
198
+ function shopify() {
199
+ if (typeof window === "undefined") return void 0;
200
+ return window.Shopify;
201
+ }
202
+ var consentRequiredOverride = false;
203
+ var consentAPIResolved = false;
204
+ var resolvePromise = null;
205
+ var listenerRegistered = false;
206
+ var callbacks = /* @__PURE__ */ new Set();
207
+ function declareConsentRequired() {
208
+ consentRequiredOverride = true;
209
+ }
210
+ function consentSystemLikelyPresent() {
211
+ if (consentRequiredOverride) return true;
212
+ if (shopify()) return true;
213
+ try {
214
+ return document.cookie.indexOf(TRACKING_CONSENT_COOKIE) !== -1;
215
+ } catch {
216
+ return false;
217
+ }
218
+ }
219
+ function readAnalyticsConsent() {
220
+ const privacy = shopify()?.customerPrivacy;
221
+ if (!privacy) return null;
222
+ try {
223
+ if (typeof privacy.analyticsProcessingAllowed === "function") {
224
+ return privacy.analyticsProcessingAllowed();
225
+ }
226
+ } catch {
227
+ }
228
+ try {
229
+ if (typeof privacy.currentVisitorConsent === "function") {
230
+ const analytics = privacy.currentVisitorConsent()?.analytics;
231
+ if (analytics === "yes") return true;
232
+ if (analytics === "no") return false;
233
+ if (typeof privacy.shouldShowBanner === "function") {
234
+ if (privacy.shouldShowBanner()) return false;
235
+ }
236
+ return true;
237
+ }
238
+ } catch {
239
+ }
240
+ try {
241
+ if (typeof privacy.userCanBeTracked === "function") {
242
+ return privacy.userCanBeTracked();
243
+ }
244
+ } catch {
245
+ }
246
+ return null;
247
+ }
248
+ function waitForConsentAPI() {
249
+ if (consentAPIResolved) return Promise.resolve();
250
+ if (resolvePromise) return resolvePromise;
251
+ if (!consentSystemLikelyPresent() || shopify()?.customerPrivacy) {
252
+ consentAPIResolved = true;
253
+ return Promise.resolve();
254
+ }
255
+ resolvePromise = new Promise((resolve) => {
256
+ let polling = false;
257
+ const done = () => {
258
+ if (consentAPIResolved) return;
259
+ consentAPIResolved = true;
260
+ resolve();
261
+ };
262
+ const startPolling = () => {
263
+ if (polling) return;
264
+ polling = true;
265
+ let checks = 0;
266
+ const interval = setInterval(() => {
267
+ checks++;
268
+ if (shopify()?.customerPrivacy || checks >= 20) {
269
+ clearInterval(interval);
270
+ done();
271
+ }
272
+ }, 100);
273
+ };
274
+ const loadFeatures = shopify()?.loadFeatures;
275
+ if (typeof loadFeatures === "function") {
276
+ try {
277
+ loadFeatures([{ name: "consent-tracking-api", version: "0.1" }], () => {
278
+ if (shopify()?.customerPrivacy) done();
279
+ else startPolling();
280
+ });
281
+ } catch {
282
+ startPolling();
283
+ }
284
+ setTimeout(() => {
285
+ if (!consentAPIResolved) startPolling();
286
+ }, 2e3);
287
+ } else {
288
+ startPolling();
289
+ }
290
+ });
291
+ return resolvePromise;
292
+ }
293
+ function isAnalyticsConsentGranted() {
294
+ const state = getConsentState();
295
+ return state === "granted" || state === "absent";
296
+ }
297
+ function getConsentState() {
298
+ if (!consentAPIResolved && consentSystemLikelyPresent()) return "pending";
299
+ const result = readAnalyticsConsent();
300
+ if (result === true) return "granted";
301
+ if (result === false) return "denied";
302
+ return "absent";
303
+ }
304
+ function onConsentChange(cb) {
305
+ callbacks.add(cb);
306
+ if (!listenerRegistered && typeof document !== "undefined") {
307
+ listenerRegistered = true;
308
+ document.addEventListener("visitorConsentCollected", (event) => {
309
+ consentAPIResolved = true;
310
+ const detail = event.detail;
311
+ const granted = detail && typeof detail.analyticsAllowed === "boolean" ? detail.analyticsAllowed : isAnalyticsConsentGranted();
312
+ for (const fn of callbacks) {
313
+ try {
314
+ fn(granted);
315
+ } catch {
316
+ }
317
+ }
318
+ });
319
+ }
320
+ return () => callbacks.delete(cb);
321
+ }
322
+ function analyticsConsentFromCookie(raw) {
323
+ if (raw === void 0) return "absent";
324
+ let data;
325
+ try {
326
+ data = JSON.parse(raw.startsWith("%") ? decodeURIComponent(raw) : raw);
327
+ } catch {
328
+ try {
329
+ data = JSON.parse(decodeURIComponent(raw));
330
+ } catch {
331
+ return "pending";
332
+ }
333
+ }
334
+ const d = data;
335
+ const cmp = d?.con?.CMP?.a;
336
+ if (cmp === "1") return "granted";
337
+ if (cmp === "0") return "denied";
338
+ const purpose = d?.purposes?.a;
339
+ if (purpose === true) return "granted";
340
+ if (purpose === false) return "denied";
341
+ return "pending";
342
+ }
343
+
344
+ // src/preview.ts
345
+ var VERIFY_TIMEOUT_MS = 1500;
346
+ var MAX_TOKEN_LENGTH = 2048;
347
+ function expiryMs(exp) {
348
+ if (typeof exp !== "number" || !Number.isFinite(exp)) return null;
349
+ return exp < 1e12 ? exp * 1e3 : exp;
350
+ }
351
+ function decodePreviewToken(token) {
352
+ if (!token || token.length > MAX_TOKEN_LENGTH) return null;
353
+ const [body2] = token.split(".");
354
+ if (!body2) return null;
355
+ try {
356
+ const b64 = body2.replace(/-/g, "+").replace(/_/g, "/");
357
+ const padded = b64 + "=".repeat((4 - b64.length % 4) % 4);
358
+ const json = JSON.parse(atob(padded));
359
+ return json && typeof json === "object" ? json : null;
360
+ } catch {
361
+ return null;
362
+ }
363
+ }
364
+ var verified = /* @__PURE__ */ new Map();
365
+ async function verifyPreviewToken({
366
+ token,
367
+ shopId,
368
+ platformUrl,
369
+ fetchImpl = fetch
370
+ }) {
371
+ const payload = decodePreviewToken(token);
372
+ if (!payload) return null;
373
+ if (payload.shopId && payload.shopId !== shopId) return null;
374
+ const exp = expiryMs(payload.exp);
375
+ if (exp !== null && exp < Date.now()) return null;
376
+ const cached = verified.get(token);
377
+ if (cached && cached.until > Date.now()) return cached.preview;
378
+ const url = new URL("/api/storefront/tests/preview/verify", platformUrl);
379
+ url.searchParams.set("token", token);
380
+ const controller = new AbortController();
381
+ const timer = setTimeout(() => controller.abort(), VERIFY_TIMEOUT_MS);
382
+ try {
383
+ const res = await fetchImpl(url.toString(), {
384
+ headers: { accept: "application/json" },
385
+ signal: controller.signal
386
+ });
387
+ if (!res.ok) return null;
388
+ const body2 = await res.json();
389
+ if (body2?.valid !== true) return null;
390
+ const testKey = body2.testKey ?? payload.testKey;
391
+ const arm = body2.arm ?? payload.arm;
392
+ const resolvedShop = body2.shopId ?? payload.shopId;
393
+ if (!testKey || !arm) return null;
394
+ if (resolvedShop && resolvedShop !== shopId) return null;
395
+ const preview = { testKey, arm };
396
+ const until = expiryMs(body2.exp) ?? exp ?? Date.now() + 60 * 60 * 1e3;
397
+ verified.set(token, { preview, until });
398
+ return preview;
399
+ } catch (error) {
400
+ console.warn("[playbook] preview verify failed", String(error));
401
+ return null;
402
+ } finally {
403
+ clearTimeout(timer);
404
+ }
405
+ }
406
+
407
+ // src/rules.ts
408
+ var FRESH_MS = 6e4;
409
+ var STALE_MS = 3e5;
410
+ var RENDER_BUDGET_MS = 300;
411
+ var FETCH_TIMEOUT_MS = 5e3;
412
+ var memory = /* @__PURE__ */ new Map();
413
+ function rulesUrl(platformUrl, shopId) {
414
+ const url = new URL("/api/storefront/tests/rules", platformUrl);
415
+ url.searchParams.set("shop", shopId);
416
+ return url.toString();
417
+ }
418
+ function isRuleset(value) {
419
+ const v = value;
420
+ return !!v && typeof v === "object" && Array.isArray(v.tests) && v.tests.every(
421
+ (t) => t && typeof t.key === "string" && typeof t.status === "string" && Array.isArray(t.arms) && t.arms.every((a) => a && typeof a.key === "string")
422
+ );
423
+ }
424
+ function refresh(key, url, entry, fetchImpl) {
425
+ if (entry.inflight) return entry.inflight;
426
+ const controller = new AbortController();
427
+ const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
428
+ entry.inflight = fetchImpl(url, {
429
+ headers: { accept: "application/json" },
430
+ signal: controller.signal
431
+ }).then(async (res) => {
432
+ if (!res.ok) throw new Error(`ruleset ${res.status}`);
433
+ const json = await res.json();
434
+ if (!isRuleset(json)) throw new Error("ruleset malformed");
435
+ entry.ruleset = json;
436
+ entry.fetchedAt = Date.now();
437
+ return json;
438
+ }).catch((error) => {
439
+ console.warn("[playbook] ruleset fetch failed", String(error));
440
+ return entry.ruleset;
441
+ }).finally(() => {
442
+ clearTimeout(timer);
443
+ entry.inflight = null;
444
+ });
445
+ memory.set(key, entry);
446
+ return entry.inflight;
447
+ }
448
+ var COLD_RENDER_BUDGET_MS = 1500;
449
+ async function getRulesetWithSource({
450
+ platformUrl,
451
+ shopId,
452
+ waitUntil,
453
+ fetchImpl = fetch
454
+ }) {
455
+ const url = rulesUrl(platformUrl, shopId);
456
+ const key = url;
457
+ const entry = memory.get(key) ?? {
458
+ ruleset: null,
459
+ fetchedAt: 0,
460
+ inflight: null
461
+ };
462
+ const age = Date.now() - entry.fetchedAt;
463
+ if (entry.ruleset && age < FRESH_MS) {
464
+ return { ruleset: entry.ruleset, source: "memory" };
465
+ }
466
+ if (entry.ruleset && age < FRESH_MS + STALE_MS) {
467
+ const p2 = refresh(key, url, entry, fetchImpl);
468
+ waitUntil?.(p2);
469
+ return { ruleset: entry.ruleset, source: "stale" };
470
+ }
471
+ const lastGood = entry.ruleset;
472
+ const p = refresh(key, url, entry, fetchImpl);
473
+ waitUntil?.(p);
474
+ let timer;
475
+ const budget = new Promise((resolve) => {
476
+ timer = setTimeout(
477
+ () => resolve(null),
478
+ lastGood ? RENDER_BUDGET_MS : COLD_RENDER_BUDGET_MS
479
+ );
480
+ });
481
+ const result = await Promise.race([p, budget]);
482
+ clearTimeout(timer);
483
+ if (result && result !== lastGood)
484
+ return { ruleset: result, source: "fetched" };
485
+ if (lastGood) return { ruleset: lastGood, source: "last-good" };
486
+ return { ruleset: null, source: "cold-fallback" };
487
+ }
488
+ function prefetchRuleset(args) {
489
+ const p = getRulesetWithSource(args).catch(() => null);
490
+ args.waitUntil?.(p);
491
+ }
492
+
493
+ // src/server.ts
494
+ var DEFAULT_PLATFORM_URL = "https://www.heyplaybook.com";
495
+ var VISITOR_MAX_AGE = 365 * 24 * 60 * 60;
496
+ function detectGeo(headers) {
497
+ const pick = (...names) => {
498
+ for (const n of names) {
499
+ const v = headers.get(n);
500
+ if (v) return v.slice(0, 64);
501
+ }
502
+ return null;
503
+ };
504
+ return {
505
+ country: pick(
506
+ "oxygen-buyer-country",
507
+ "cf-ipcountry",
508
+ "x-vercel-ip-country"
509
+ ),
510
+ region: pick(
511
+ "oxygen-buyer-region-code",
512
+ "oxygen-buyer-region",
513
+ "x-vercel-ip-country-region"
514
+ )
515
+ };
516
+ }
517
+ function detectDevice(userAgent) {
518
+ return userAgent && /Mobi|Android|iPhone|iPod/i.test(userAgent) ? "mobile" : "desktop";
519
+ }
520
+ async function createPlaybook({
521
+ shopId,
522
+ platformUrl,
523
+ request,
524
+ waitUntil,
525
+ fetchImpl,
526
+ overrides,
527
+ consentRequired = false
528
+ }) {
529
+ const url = new URL(request.url);
530
+ const device = detectDevice(request.headers.get("user-agent"));
531
+ const now = (/* @__PURE__ */ new Date()).toISOString();
532
+ if (!shopId) {
533
+ const state = {
534
+ enabled: false,
535
+ shopId: null,
536
+ visitorId: null,
537
+ visitorType: "new",
538
+ device,
539
+ now,
540
+ serverConsent: "absent",
541
+ consentRequired: false,
542
+ rulesetVersion: null,
543
+ rulesetSource: null,
544
+ tests: {},
545
+ previewToken: null
546
+ };
547
+ return {
548
+ state,
549
+ assignments: {},
550
+ visitorId: null,
551
+ preview: null,
552
+ previewSource: null,
553
+ setCookieHeaders: []
554
+ };
555
+ }
556
+ const base = platformUrl || DEFAULT_PLATFORM_URL;
557
+ const cookies = parseCookies(request.headers.get("cookie"));
558
+ const domain = cookieDomainFor(url.hostname);
559
+ const secure = url.protocol === "https:";
560
+ const setCookieHeaders = [];
561
+ let consent = analyticsConsentFromCookie(cookies[TRACKING_CONSENT_COOKIE]);
562
+ if (consent === "absent" && consentRequired) consent = "pending";
563
+ const persistentAllowed = consent === "granted" || consent === "absent";
564
+ const existing = [
565
+ cookies[VISITOR_COOKIE],
566
+ cookies[SESSION_VISITOR_COOKIE],
567
+ cookies[LEGACY_VISITOR_COOKIE]
568
+ ].find((v) => isValidVisitorId(v));
569
+ const visitorId = existing ?? randomUuid();
570
+ let visitorType = existing ? "returning" : "new";
571
+ if (!existing) {
572
+ setCookieHeaders.push(serializeCookie(NEW_SESSION_COOKIE, "1", { secure }));
573
+ } else if (cookies[NEW_SESSION_COOKIE] === "1") {
574
+ visitorType = "new";
575
+ }
576
+ if (persistentAllowed) {
577
+ const refreshed = cookies[VISITOR_REFRESHED_COOKIE] === "1";
578
+ if (cookies[VISITOR_COOKIE] !== visitorId || !refreshed) {
579
+ setCookieHeaders.push(
580
+ serializeCookie(VISITOR_COOKIE, visitorId, {
581
+ maxAge: VISITOR_MAX_AGE,
582
+ secure
583
+ })
584
+ );
585
+ }
586
+ if (!refreshed) {
587
+ setCookieHeaders.push(
588
+ serializeCookie(VISITOR_REFRESHED_COOKIE, "1", {
589
+ secure,
590
+ httpOnly: true
591
+ })
592
+ );
593
+ }
594
+ } else {
595
+ if (cookies[SESSION_VISITOR_COOKIE] !== visitorId) {
596
+ setCookieHeaders.push(
597
+ serializeCookie(SESSION_VISITOR_COOKIE, visitorId, {
598
+ secure,
599
+ httpOnly: true
600
+ })
601
+ );
602
+ }
603
+ if (cookies[VISITOR_COOKIE]) {
604
+ setCookieHeaders.push(
605
+ serializeCookie(VISITOR_COOKIE, "", { maxAge: 0, secure })
606
+ );
607
+ }
608
+ }
609
+ if (cookies[LEGACY_VISITOR_COOKIE]) {
610
+ setCookieHeaders.push(
611
+ serializeCookie(LEGACY_VISITOR_COOKIE, "", { maxAge: 0, secure })
612
+ );
613
+ if (domain) {
614
+ setCookieHeaders.push(
615
+ serializeCookie(LEGACY_VISITOR_COOKIE, "", { maxAge: 0, domain, secure })
616
+ );
617
+ }
618
+ }
619
+ const paramToken = url.searchParams.get(PREVIEW_PARAM);
620
+ const cookieToken = cookies[PREVIEW_COOKIE];
621
+ const PREVIEW_COOKIE_OPTS = { httpOnly: true, sameSite: "None" };
622
+ const clearPreview = () => setCookieHeaders.push(
623
+ serializeCookie(PREVIEW_COOKIE, "", { maxAge: 0, ...PREVIEW_COOKIE_OPTS })
624
+ );
625
+ let previewToken = null;
626
+ let previewSource = null;
627
+ let previewPromise = Promise.resolve(null);
628
+ if (paramToken === "off" || paramToken === "") {
629
+ if (cookieToken) clearPreview();
630
+ } else if (paramToken || cookieToken) {
631
+ const token = paramToken || cookieToken;
632
+ previewPromise = verifyPreviewToken({
633
+ token,
634
+ shopId,
635
+ platformUrl: base,
636
+ fetchImpl
637
+ }).then((preview2) => {
638
+ if (preview2) {
639
+ previewToken = token;
640
+ previewSource = paramToken ? "request" : "session";
641
+ }
642
+ if (preview2 && paramToken) {
643
+ setCookieHeaders.push(
644
+ serializeCookie(PREVIEW_COOKIE, token, PREVIEW_COOKIE_OPTS)
645
+ );
646
+ } else if (!preview2 && cookieToken) {
647
+ clearPreview();
648
+ }
649
+ return preview2;
650
+ });
651
+ }
652
+ const [{ ruleset, source: rulesetSource }, preview] = await Promise.all([
653
+ getRulesetWithSource({ platformUrl: base, shopId, waitUntil, fetchImpl }),
654
+ previewPromise
655
+ ]);
656
+ const assignments = {};
657
+ for (const test of ruleset?.tests ?? []) {
658
+ assignments[test.key] = assignTest(test, {
659
+ visitorId,
660
+ device,
661
+ visitorType,
662
+ preview
663
+ });
664
+ }
665
+ for (const o of overrides ?? []) {
666
+ if (preview?.testKey === o.testKey && !(previewSource === "session" && o.source === "request")) {
667
+ continue;
668
+ }
669
+ const test = ruleset?.tests.find((t) => t.key === o.testKey);
670
+ const a = assignments[o.testKey];
671
+ if (!test || !a || !test.arms.some((arm) => arm.key === o.arm)) continue;
672
+ assignments[o.testKey] = {
673
+ ...a,
674
+ arm: o.arm,
675
+ inTest: false,
676
+ forced: true,
677
+ reason: "override"
678
+ };
679
+ }
680
+ return {
681
+ state: {
682
+ enabled: true,
683
+ shopId,
684
+ visitorId,
685
+ visitorType,
686
+ device,
687
+ now,
688
+ serverConsent: consent,
689
+ geo: detectGeo(request.headers),
690
+ consentRequired,
691
+ rulesetVersion: ruleset?.version ?? null,
692
+ rulesetSource,
693
+ tests: assignments,
694
+ previewToken
695
+ },
696
+ assignments,
697
+ visitorId,
698
+ preview,
699
+ previewSource,
700
+ setCookieHeaders
701
+ };
702
+ }
703
+
704
+ // src/tracker.ts
705
+ var ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
706
+ var KEY_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
707
+ var EVENT_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/;
708
+ var MAX_PATH_LENGTH = 500;
709
+ var MAX_BODY_BYTES = 4e3;
710
+ var STANDARD_EVENTS = [
711
+ "add_to_cart",
712
+ "checkout_started",
713
+ "scroll_depth",
714
+ "engaged_time",
715
+ "variant_interaction"
716
+ ];
717
+ var DEFAULT_SUPPORTED_EVENTS = [...STANDARD_EVENTS];
718
+ var INTERACTION_NAME_RE = /^[a-z][a-z0-9_]{0,39}$/;
719
+ var MAX_PROPS = 20;
720
+ function legacyAlias(event, props) {
721
+ if (event === "variant_interaction" && props.name === "copy_code") {
722
+ return { event: "code_copied", props: {} };
723
+ }
724
+ return null;
725
+ }
726
+ function cleanProps(props) {
727
+ const out = {};
728
+ for (const [k, v] of Object.entries(props)) {
729
+ if (Object.keys(out).length >= MAX_PROPS) break;
730
+ if (v === null || v === void 0) continue;
731
+ if (typeof v === "string") out[k] = v.slice(0, 80);
732
+ else if (typeof v === "number" && Number.isFinite(v)) out[k] = v;
733
+ else if (typeof v === "boolean") out[k] = v;
734
+ }
735
+ return out;
736
+ }
737
+ var config = {
738
+ state: null,
739
+ consent: "pending",
740
+ pathname: "/",
741
+ exposureUrl: "/apps/playbook/api/storefront/tests/exposure",
742
+ eventUrl: "/apps/playbook/api/storefront/tests/event",
743
+ supportedEvents: new Set(DEFAULT_SUPPORTED_EVENTS),
744
+ store: {}
745
+ };
746
+ var seenOnPage = /* @__PURE__ */ new Set();
747
+ function configureTracker(next) {
748
+ if (next.pathname !== void 0 && next.pathname !== config.pathname) {
749
+ seenOnPage = /* @__PURE__ */ new Set();
750
+ }
751
+ config = { ...config, ...next };
752
+ }
753
+ function markSeenOnPage(testKey) {
754
+ seenOnPage.add(testKey);
755
+ }
756
+ function analyticsAllowed(consent = config.consent) {
757
+ return consent === "granted" || consent === "absent";
758
+ }
759
+ var LOG_SIZE = 12;
760
+ var log = [];
761
+ var EMPTY_LOG = [];
762
+ var listeners = /* @__PURE__ */ new Set();
763
+ function record(entry) {
764
+ log = [entry, ...log].slice(0, LOG_SIZE);
765
+ listeners.forEach((fn) => fn());
766
+ }
767
+ function getTrackedLog() {
768
+ return log;
769
+ }
770
+ function getServerTrackedLog() {
771
+ return EMPTY_LOG;
772
+ }
773
+ function subscribeTrackedLog(fn) {
774
+ listeners.add(fn);
775
+ return () => listeners.delete(fn);
776
+ }
777
+ var CONTEXT_KEY = "pb_ctx";
778
+ var UTM_KEYS = [
779
+ "utm_source",
780
+ "utm_medium",
781
+ "utm_campaign",
782
+ "utm_content",
783
+ "utm_term"
784
+ ];
785
+ var CLICK_IDS = [
786
+ ["fbclid", "fbclid"],
787
+ ["gclid", "gclid"],
788
+ ["gbraid", "gclid"],
789
+ ["wbraid", "gclid"],
790
+ ["ttclid", "ttclid"]
791
+ ];
792
+ function clip(value, max = 100) {
793
+ return value.slice(0, max);
794
+ }
795
+ function getSessionContext() {
796
+ if (typeof window === "undefined") return null;
797
+ try {
798
+ const stored = window.sessionStorage.getItem(CONTEXT_KEY);
799
+ if (stored) return JSON.parse(stored);
800
+ } catch {
801
+ }
802
+ const url = new URL(window.location.href);
803
+ const utm = {};
804
+ for (const key of UTM_KEYS) {
805
+ const v = url.searchParams.get(key);
806
+ if (v) utm[key.slice(4)] = clip(v);
807
+ }
808
+ let referrerHost = null;
809
+ try {
810
+ const ref = document.referrer ? new URL(document.referrer).hostname : "";
811
+ referrerHost = ref && ref !== url.hostname ? clip(ref) : null;
812
+ } catch {
813
+ referrerHost = null;
814
+ }
815
+ const ctx = {
816
+ utm,
817
+ referrerHost,
818
+ landingPath: clip(url.pathname, 200),
819
+ clickIdType: CLICK_IDS.find(([param]) => url.searchParams.has(param))?.[1] ?? null
820
+ };
821
+ try {
822
+ window.sessionStorage.setItem(CONTEXT_KEY, JSON.stringify(ctx));
823
+ } catch {
824
+ }
825
+ return ctx;
826
+ }
827
+ function coarseBrowser(ua) {
828
+ if (/Edg\//.test(ua)) return "edge";
829
+ if (/SamsungBrowser/.test(ua)) return "samsung";
830
+ if (/FBAN|FBAV|Instagram/.test(ua)) return "in-app";
831
+ if (/Firefox|FxiOS/.test(ua)) return "firefox";
832
+ if (/Chrome|CriOS/.test(ua)) return "chrome";
833
+ if (/Safari/.test(ua)) return "safari";
834
+ return "other";
835
+ }
836
+ function coarseOs(ua) {
837
+ if (/iPhone|iPad|iPod/.test(ua)) return "ios";
838
+ if (/Android/.test(ua)) return "android";
839
+ if (/Mac OS X/.test(ua)) return "macos";
840
+ if (/Windows/.test(ua)) return "windows";
841
+ if (/Linux|CrOS/.test(ua)) return "linux";
842
+ return "other";
843
+ }
844
+ function viewportBucket(width) {
845
+ if (width < 480) return "xs";
846
+ if (width < 768) return "sm";
847
+ if (width < 1024) return "md";
848
+ if (width < 1440) return "lg";
849
+ return "xl";
850
+ }
851
+ function exposureContext() {
852
+ const s = config.state;
853
+ const session = getSessionContext();
854
+ const ua = typeof navigator !== "undefined" ? navigator.userAgent : "";
855
+ return {
856
+ country: s?.geo?.country ?? null,
857
+ region: s?.geo?.region ?? null,
858
+ market: config.store.market ?? null,
859
+ locale: config.store.locale ?? null,
860
+ utm: session?.utm ?? {},
861
+ referrerHost: session?.referrerHost ?? null,
862
+ landingPath: session?.landingPath ?? null,
863
+ clickIdType: session?.clickIdType ?? null,
864
+ browser: coarseBrowser(ua),
865
+ os: coarseOs(ua),
866
+ viewportBucket: viewportBucket(window.innerWidth),
867
+ isLoggedIn: config.store.isLoggedIn ?? null
868
+ };
869
+ }
870
+ var sentThisPage = /* @__PURE__ */ new Set();
871
+ function exposureKey(visitorId, testKey) {
872
+ return `pb_exp:${visitorId}:${testKey}`;
873
+ }
874
+ function hasSentExposure(visitorId, testKey) {
875
+ const key = exposureKey(visitorId, testKey);
876
+ if (sentThisPage.has(key)) return true;
877
+ try {
878
+ return !!window.sessionStorage.getItem(key);
879
+ } catch {
880
+ return false;
881
+ }
882
+ }
883
+ function claimOnce(key, arm) {
884
+ if (sentThisPage.has(key)) return false;
885
+ sentThisPage.add(key);
886
+ try {
887
+ if (window.sessionStorage.getItem(key)) return false;
888
+ window.sessionStorage.setItem(key, arm);
889
+ } catch {
890
+ }
891
+ return true;
892
+ }
893
+ function post(url, body2, { beacon = false } = {}) {
894
+ if (beacon && typeof navigator !== "undefined" && navigator.sendBeacon) {
895
+ try {
896
+ const ok = navigator.sendBeacon(
897
+ url,
898
+ new Blob([body2], { type: "application/json" })
899
+ );
900
+ if (ok) return;
901
+ } catch {
902
+ }
903
+ }
904
+ fetch(url, {
905
+ method: "POST",
906
+ headers: { "content-type": "application/json" },
907
+ body: body2,
908
+ keepalive: true
909
+ }).catch(() => {
910
+ });
911
+ }
912
+ function baseValid(testKey, arm) {
913
+ const s = config.state;
914
+ if (!s?.enabled || !s.visitorId || !s.shopId) return null;
915
+ if (!ID_RE.test(s.shopId) || !ID_RE.test(s.visitorId)) return null;
916
+ if (!KEY_RE.test(testKey) || !KEY_RE.test(arm)) return null;
917
+ return s;
918
+ }
919
+ function body(s, testKey, arm, extra) {
920
+ const json = JSON.stringify({
921
+ shopId: s.shopId,
922
+ visitorId: s.visitorId,
923
+ testKey,
924
+ arm,
925
+ ...extra,
926
+ path: window.location.pathname.slice(0, MAX_PATH_LENGTH),
927
+ eventId: randomUuid(),
928
+ ts: (/* @__PURE__ */ new Date()).toISOString()
929
+ });
930
+ return json.length <= MAX_BODY_BYTES ? json : null;
931
+ }
932
+ function sendExposure(testKey, arm) {
933
+ const s = baseValid(testKey, arm);
934
+ if (!s || !analyticsAllowed()) return;
935
+ if (!claimOnce(exposureKey(s.visitorId, testKey), arm)) return;
936
+ const json = body(s, testKey, arm, {
937
+ device: s.device,
938
+ visitorType: s.visitorType,
939
+ context: exposureContext()
940
+ });
941
+ if (json) post(config.exposureUrl, json);
942
+ record({
943
+ at: (/* @__PURE__ */ new Date()).toISOString(),
944
+ kind: "exposure",
945
+ name: "exposure",
946
+ testKey,
947
+ arm,
948
+ status: "sent"
949
+ });
950
+ }
951
+ function testsFor(scope) {
952
+ const s = config.state;
953
+ if (!s?.enabled || !s.visitorId) return [];
954
+ const out = [];
955
+ for (const [key, a] of Object.entries(s.tests)) {
956
+ if (!a.inTest || a.forced) continue;
957
+ if (typeof scope === "object") {
958
+ if (scope.testKeys.includes(key)) out.push([key, a.arm]);
959
+ } else if (scope === "visitor") {
960
+ if (hasSentExposure(s.visitorId, key)) out.push([key, a.arm]);
961
+ } else if (
962
+ // Tested page type only: the test targets a pathPrefix that matches
963
+ // this page, and its slot was on screen during this page view.
964
+ a.pathPrefix?.length && seenOnPage.has(key) && matchesPathPrefix(config.pathname, a.pathPrefix)
965
+ ) {
966
+ out.push([key, a.arm]);
967
+ }
968
+ }
969
+ return out;
970
+ }
971
+ function playbookTrack(event, rawProps = {}, scope = "visitor", { oncePerSession, beacon } = {}) {
972
+ if (typeof window === "undefined" || !EVENT_RE.test(event)) return 0;
973
+ const props = cleanProps(rawProps);
974
+ if (event === "variant_interaction" && !INTERACTION_NAME_RE.test(String(props.name ?? ""))) {
975
+ return 0;
976
+ }
977
+ const targets = testsFor(scope);
978
+ if (!targets.length) return 0;
979
+ const allowed = analyticsAllowed();
980
+ for (const [testKey, arm] of targets) {
981
+ const s = baseValid(testKey, arm);
982
+ if (!s) continue;
983
+ const entry = {
984
+ at: (/* @__PURE__ */ new Date()).toISOString(),
985
+ kind: "event",
986
+ name: event,
987
+ testKey,
988
+ arm,
989
+ status: "blocked",
990
+ props
991
+ };
992
+ if (!allowed) {
993
+ record(entry);
994
+ continue;
995
+ }
996
+ if (oncePerSession && !claimOnce(`pb_evt:${s.visitorId}:${testKey}:${oncePerSession}`, arm)) {
997
+ continue;
998
+ }
999
+ let wire = {
1000
+ event,
1001
+ props
1002
+ };
1003
+ if (!config.supportedEvents.has(event)) {
1004
+ const alias = legacyAlias(event, props);
1005
+ wire = alias && config.supportedEvents.has(alias.event) ? alias : null;
1006
+ }
1007
+ if (!wire) {
1008
+ record({ ...entry, status: "held" });
1009
+ continue;
1010
+ }
1011
+ const json = body(
1012
+ s,
1013
+ testKey,
1014
+ arm,
1015
+ Object.keys(wire.props).length ? wire : { event: wire.event }
1016
+ );
1017
+ if (json) post(config.eventUrl, json, { beacon });
1018
+ record({ ...entry, status: "sent" });
1019
+ }
1020
+ return targets.length;
1021
+ }
1022
+
1023
+ // src/hooks.ts
1024
+ var DEFAULT_EXPOSURE_URL = "/apps/playbook/api/storefront/tests/exposure";
1025
+ var DEFAULT_EVENT_URL = "/apps/playbook/api/storefront/tests/event";
1026
+ var PlaybookContext = createContext({
1027
+ state: null,
1028
+ pathname: "/",
1029
+ exposureUrl: DEFAULT_EXPOSURE_URL,
1030
+ eventUrl: DEFAULT_EVENT_URL,
1031
+ consent: "pending"
1032
+ });
1033
+ function usePlaybookConsent() {
1034
+ return useContext(PlaybookContext).consent;
1035
+ }
1036
+ function useAnalyticsAllowed() {
1037
+ const consent = usePlaybookConsent();
1038
+ return consent === "granted" || consent === "absent";
1039
+ }
1040
+ function usePlaybookState() {
1041
+ return useContext(PlaybookContext).state;
1042
+ }
1043
+ var CONTROL = {
1044
+ arm: CONTROL_ARM,
1045
+ inTest: false,
1046
+ forced: false,
1047
+ config: {}
1048
+ };
1049
+ function usePlaybookVariant(testKey, { eligible = true } = {}) {
1050
+ const { state, pathname } = useContext(PlaybookContext);
1051
+ const a = state?.enabled ? state.tests[testKey] : void 0;
1052
+ return useMemo(() => {
1053
+ if (!a) return CONTROL;
1054
+ if (!eligible || !matchesPathPrefix(pathname, a.pathPrefix)) {
1055
+ return { ...CONTROL, config: a.config };
1056
+ }
1057
+ if (a.forced) {
1058
+ return { arm: a.arm, inTest: false, forced: true, config: a.config };
1059
+ }
1060
+ return { arm: a.arm, inTest: a.inTest, forced: false, config: a.config };
1061
+ }, [a, eligible, pathname]);
1062
+ }
1063
+ function usePlaybookInteraction(testKey, variant) {
1064
+ return useCallback(
1065
+ (name, target) => {
1066
+ if (!variant.inTest || variant.forced) return;
1067
+ playbookTrack(
1068
+ "variant_interaction",
1069
+ { name, target },
1070
+ { testKeys: [testKey] },
1071
+ { oncePerSession: `vi:${name}:${target ?? ""}` }
1072
+ );
1073
+ },
1074
+ [testKey, variant.inTest, variant.forced]
1075
+ );
1076
+ }
1077
+ function usePlaybookExposure(testKey, variant, { enabled = true } = {}) {
1078
+ const { state, consent } = useContext(PlaybookContext);
1079
+ const [el, setEl] = useState(null);
1080
+ const ref = useCallback(
1081
+ (node) => {
1082
+ node?.setAttribute("data-pb-slot", testKey);
1083
+ setEl(node);
1084
+ },
1085
+ [testKey]
1086
+ );
1087
+ const active = enabled && !!state?.enabled && variant.inTest && !variant.forced && (consent === "granted" || consent === "absent");
1088
+ useEffect(() => {
1089
+ if (!active || !el || !state) return void 0;
1090
+ if (typeof IntersectionObserver === "undefined") {
1091
+ markSeenOnPage(testKey);
1092
+ sendExposure(testKey, variant.arm);
1093
+ return void 0;
1094
+ }
1095
+ const observer = new IntersectionObserver((entries) => {
1096
+ if (entries.some((e) => e.isIntersecting)) {
1097
+ markSeenOnPage(testKey);
1098
+ sendExposure(testKey, variant.arm);
1099
+ observer.disconnect();
1100
+ }
1101
+ });
1102
+ observer.observe(el);
1103
+ return () => observer.disconnect();
1104
+ }, [active, el, state, testKey, variant.arm]);
1105
+ return ref;
1106
+ }
1107
+ function usePreviewParamRedirect(location) {
1108
+ const state = usePlaybookState();
1109
+ const token = state?.previewToken;
1110
+ if (!token) return null;
1111
+ const params = new URLSearchParams(location.search);
1112
+ if (params.get("pb_preview") === token) return null;
1113
+ if (params.get("pb_preview") === "off") return null;
1114
+ params.set("pb_preview", token);
1115
+ return `${location.pathname}?${params.toString()}${location.hash}`;
1116
+ }
1117
+
1118
+ // src/visitor-sync.ts
1119
+ function writeCookie(value, days) {
1120
+ try {
1121
+ const expires = new Date(Date.now() + days * 864e5).toUTCString();
1122
+ const secure = window.location.protocol === "https:" ? ";Secure" : "";
1123
+ document.cookie = `${VISITOR_COOKIE}=${value};expires=${expires};path=/;SameSite=Lax${secure}`;
1124
+ } catch {
1125
+ }
1126
+ }
1127
+ function readCookie() {
1128
+ try {
1129
+ const parts = `; ${document.cookie}`.split(`; ${VISITOR_COOKIE}=`);
1130
+ return parts.length === 2 ? parts.pop()?.split(";").shift() ?? null : null;
1131
+ } catch {
1132
+ return null;
1133
+ }
1134
+ }
1135
+ function syncVisitorId(visitorId, consent) {
1136
+ try {
1137
+ window.sessionStorage.setItem(VISITOR_COOKIE, visitorId);
1138
+ } catch {
1139
+ }
1140
+ if (consent === "granted" || consent === "absent") {
1141
+ if (readCookie() !== visitorId) writeCookie(visitorId, 365);
1142
+ } else if (readCookie() !== null) {
1143
+ writeCookie("", -1);
1144
+ }
1145
+ }
1146
+ function visitorSeedScript(visitorId) {
1147
+ return `try{sessionStorage.setItem(${JSON.stringify(VISITOR_COOKIE)},${JSON.stringify(visitorId)})}catch(e){}`;
1148
+ }
1149
+ function PlaybookProvider({
1150
+ state,
1151
+ pathname,
1152
+ exposureUrl = DEFAULT_EXPOSURE_URL,
1153
+ eventUrl = DEFAULT_EVENT_URL,
1154
+ supportedEvents = DEFAULT_SUPPORTED_EVENTS,
1155
+ storeContext,
1156
+ children
1157
+ }) {
1158
+ const [consent, setConsent] = useState("pending");
1159
+ const consentRequired = !!state?.consentRequired;
1160
+ useEffect(() => {
1161
+ if (consentRequired) declareConsentRequired();
1162
+ let live = true;
1163
+ const update = () => live && setConsent(getConsentState());
1164
+ waitForConsentAPI().then(update);
1165
+ const unsubscribe = onConsentChange(update);
1166
+ return () => {
1167
+ live = false;
1168
+ unsubscribe();
1169
+ };
1170
+ }, [consentRequired]);
1171
+ const visitorId = state?.enabled ? state.visitorId : null;
1172
+ useEffect(() => {
1173
+ if (visitorId) syncVisitorId(visitorId, consent);
1174
+ }, [visitorId, consent]);
1175
+ if (typeof window !== "undefined") {
1176
+ configureTracker({
1177
+ state: state ?? null,
1178
+ consent,
1179
+ pathname,
1180
+ exposureUrl,
1181
+ eventUrl,
1182
+ supportedEvents: new Set(supportedEvents),
1183
+ store: storeContext ?? {}
1184
+ });
1185
+ }
1186
+ const value = useMemo(
1187
+ () => ({ state: state ?? null, pathname, exposureUrl, eventUrl, consent }),
1188
+ [state, pathname, exposureUrl, eventUrl, consent]
1189
+ );
1190
+ return /* @__PURE__ */ jsx(PlaybookContext.Provider, { value, children });
1191
+ }
1192
+ function PlaybookExposure({
1193
+ testKey,
1194
+ variant,
1195
+ enabled,
1196
+ children
1197
+ }) {
1198
+ const ref = usePlaybookExposure(testKey, variant, { enabled });
1199
+ return /* @__PURE__ */ jsx(Fragment, { children: children(ref) });
1200
+ }
1201
+ var MILESTONES = [25, 50, 75, 100];
1202
+ var IDLE_MS = 5e3;
1203
+ var ACTIVITY = [
1204
+ "pointerdown",
1205
+ "pointermove",
1206
+ "keydown",
1207
+ "scroll",
1208
+ "touchstart"
1209
+ ];
1210
+ function usePageEngagement(pathname, enabled) {
1211
+ useEffect(() => {
1212
+ if (!enabled) return void 0;
1213
+ const reached = /* @__PURE__ */ new Set();
1214
+ let ticking = false;
1215
+ const measure = () => {
1216
+ ticking = false;
1217
+ const doc = document.documentElement;
1218
+ const max = Math.max(doc.scrollHeight - window.innerHeight, 1);
1219
+ const pct = Math.min(100, Math.round(window.scrollY / max * 100));
1220
+ for (const m of MILESTONES) {
1221
+ if (pct >= m && !reached.has(m)) {
1222
+ if (playbookTrack("scroll_depth", { percent: m }, "page") > 0) {
1223
+ reached.add(m);
1224
+ }
1225
+ }
1226
+ }
1227
+ };
1228
+ const onScroll = () => {
1229
+ if (!ticking) {
1230
+ ticking = true;
1231
+ requestAnimationFrame(measure);
1232
+ }
1233
+ };
1234
+ let lastActive = Date.now();
1235
+ let engagedMs = 0;
1236
+ let sent = false;
1237
+ const markActive = () => {
1238
+ lastActive = Date.now();
1239
+ };
1240
+ const tick = setInterval(() => {
1241
+ if (document.visibilityState === "visible" && Date.now() - lastActive < IDLE_MS) {
1242
+ engagedMs += 1e3;
1243
+ }
1244
+ }, 1e3);
1245
+ const flush = () => {
1246
+ if (sent || engagedMs < 1e3) return;
1247
+ sent = true;
1248
+ void playbookTrack(
1249
+ "engaged_time",
1250
+ { seconds: Math.min(3600, Math.round(engagedMs / 1e3)) },
1251
+ "page",
1252
+ { beacon: true }
1253
+ );
1254
+ };
1255
+ window.addEventListener("scroll", onScroll, { passive: true });
1256
+ for (const e of ACTIVITY) {
1257
+ window.addEventListener(e, markActive, { passive: true });
1258
+ }
1259
+ window.addEventListener("pagehide", flush);
1260
+ measure();
1261
+ return () => {
1262
+ flush();
1263
+ clearInterval(tick);
1264
+ window.removeEventListener("scroll", onScroll);
1265
+ for (const e of ACTIVITY) window.removeEventListener(e, markActive);
1266
+ window.removeEventListener("pagehide", flush);
1267
+ };
1268
+ }, [pathname, enabled]);
1269
+ }
1270
+
1271
+ // src/cart-events.ts
1272
+ var nextSource = null;
1273
+ function setNextAddSource(source) {
1274
+ nextSource = source;
1275
+ }
1276
+ function takeAddSource() {
1277
+ const source = nextSource ?? "other";
1278
+ nextSource = null;
1279
+ return source;
1280
+ }
1281
+ function numericId(gid) {
1282
+ const id = gid?.split("/").pop();
1283
+ return id && /^\d{1,30}$/.test(id) ? id : null;
1284
+ }
1285
+ function trackAddToCartLines(lines, cartLines, source) {
1286
+ try {
1287
+ for (const line of lines) {
1288
+ if (!line?.merchandiseId) continue;
1289
+ const match = cartLines.find(
1290
+ (n) => n.merchandise?.id === line.merchandiseId
1291
+ );
1292
+ const quantity = Math.min(
1293
+ 999,
1294
+ Math.max(1, Math.round(Number(line.quantity) || 1))
1295
+ );
1296
+ const unit = Number(match?.merchandise?.price?.amount);
1297
+ playbookTrack("add_to_cart", {
1298
+ productId: numericId(match?.merchandise?.product?.id),
1299
+ variantId: numericId(line.merchandiseId),
1300
+ quantity,
1301
+ valueCents: Number.isFinite(unit) ? Math.min(1e8, Math.round(unit * 100) * quantity) : null,
1302
+ source
1303
+ });
1304
+ }
1305
+ } catch {
1306
+ }
1307
+ }
1308
+
1309
+ // src/cart.ts
1310
+ var CART_VISITOR_ATTRIBUTE = "_pb_vid";
1311
+ function playbookCartAttribute(visitorId) {
1312
+ return { key: CART_VISITOR_ATTRIBUTE, value: visitorId };
1313
+ }
1314
+ function cartHasPlaybookAttribute(attributes, visitorId) {
1315
+ return !!attributes?.some(
1316
+ (a) => a.key === CART_VISITOR_ATTRIBUTE && a.value === visitorId
1317
+ );
1318
+ }
1319
+
1320
+ export { CART_VISITOR_ATTRIBUTE, CONTROL_ARM, DEFAULT_EVENT_URL, DEFAULT_EXPOSURE_URL, DEFAULT_PLATFORM_URL, DEFAULT_SUPPORTED_EVENTS, LEGACY_VISITOR_COOKIE, PlaybookExposure, PlaybookProvider, SESSION_VISITOR_COOKIE, STANDARD_EVENTS, VISITOR_COOKIE, analyticsConsentFromCookie, assignTest, cartHasPlaybookAttribute, chooseVariation, createPlaybook, declareConsentRequired, detectDevice, detectGeo, getBucketRanges, getConsentState, getEqualWeights, getServerTrackedLog, getSessionContext, getTrackedLog, hasSentExposure, hash, inNamespace, isAnalyticsConsentGranted, matchesPathPrefix, onConsentChange, playbookCartAttribute, playbookTrack, prefetchRuleset, setNextAddSource, subscribeTrackedLog, syncVisitorId, takeAddSource, trackAddToCartLines, useAnalyticsAllowed, usePageEngagement, usePlaybookConsent, usePlaybookExposure, usePlaybookInteraction, usePlaybookState, usePlaybookVariant, usePreviewParamRedirect, visitorSeedScript, waitForConsentAPI };