@heyplaybook/hydrogen 0.2.1 → 0.6.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 CHANGED
@@ -1,12 +1,12 @@
1
- import { createContext, useContext, useMemo, useCallback, useState, useEffect } from 'react';
2
- import { jsx, Fragment } from 'react/jsx-runtime';
1
+ import { jsxs, Fragment, jsx } from 'react/jsx-runtime';
2
+ import { memo, createContext, Component, useContext, useMemo, useCallback, useState, useEffect, useSyncExternalStore, useRef } from 'react';
3
3
 
4
4
  // src/growthbook.ts
5
- function hashFnv32a(str) {
5
+ function hashFnv32a(str2) {
6
6
  let hval = 2166136261;
7
- const l = str.length;
7
+ const l = str2.length;
8
8
  for (let i = 0; i < l; i++) {
9
- hval ^= str.charCodeAt(i);
9
+ hval ^= str2.charCodeAt(i);
10
10
  hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
11
11
  }
12
12
  return hval >>> 0;
@@ -142,6 +142,10 @@ var SESSION_VISITOR_COOKIE = "_pb_session_vid";
142
142
  var LEGACY_VISITOR_COOKIE = "pb_vid";
143
143
  var NEW_SESSION_COOKIE = "pb_new";
144
144
  var VISITOR_REFRESHED_COOKIE = "_pb_vs";
145
+ var SERVER_VISITOR_MARKER_COOKIE = "_pb_vsrc";
146
+ function serverVisitorMarker(visitorId) {
147
+ return `s.${visitorId.slice(0, 8)}`;
148
+ }
145
149
  var PREVIEW_COOKIE = "pb_preview";
146
150
  var PREVIEW_PARAM = "pb_preview";
147
151
  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;
@@ -207,6 +211,7 @@ var consentAPIResolved = false;
207
211
  var resolvePromise = null;
208
212
  var listenerRegistered = false;
209
213
  var callbacks = /* @__PURE__ */ new Set();
214
+ var eventDecision = null;
210
215
  function declareConsentRequired() {
211
216
  consentRequiredOverride = true;
212
217
  }
@@ -297,13 +302,54 @@ function isAnalyticsConsentGranted() {
297
302
  const state = getConsentState();
298
303
  return state === "granted" || state === "absent";
299
304
  }
305
+ function consentDataLoading() {
306
+ try {
307
+ const status = shopify()?.customerPrivacy?.consentStatus;
308
+ return typeof status === "string" && status !== "loaded";
309
+ } catch {
310
+ return false;
311
+ }
312
+ }
313
+ var fromDecision = (granted) => granted ? "granted" : "denied";
300
314
  function getConsentState() {
301
- if (!consentAPIResolved && consentSystemLikelyPresent()) return "pending";
315
+ if (!consentAPIResolved && consentSystemLikelyPresent()) {
316
+ return eventDecision === null ? "pending" : fromDecision(eventDecision);
317
+ }
318
+ if (consentDataLoading()) {
319
+ return eventDecision === null ? "pending" : fromDecision(eventDecision);
320
+ }
302
321
  const result = readAnalyticsConsent();
303
322
  if (result === true) return "granted";
304
323
  if (result === false) return "denied";
324
+ if (eventDecision !== null) return fromDecision(eventDecision);
305
325
  return "absent";
306
326
  }
327
+ var CONSENT_LOADED_EVENTS = [
328
+ "consentTrackingApiLoaded",
329
+ "shopifyCustomerPrivacyApiLoaded"
330
+ ];
331
+ function onConsentLoaded(cb) {
332
+ if (typeof document === "undefined" || typeof window === "undefined") {
333
+ return () => {
334
+ };
335
+ }
336
+ const handler = () => {
337
+ try {
338
+ cb();
339
+ } catch {
340
+ }
341
+ };
342
+ for (const name of CONSENT_LOADED_EVENTS) {
343
+ document.addEventListener(name, handler);
344
+ window.addEventListener(name, handler);
345
+ }
346
+ return () => {
347
+ for (const name of CONSENT_LOADED_EVENTS) {
348
+ document.removeEventListener(name, handler);
349
+ window.removeEventListener(name, handler);
350
+ }
351
+ };
352
+ }
307
353
  function onConsentChange(cb) {
308
354
  callbacks.add(cb);
309
355
  if (!listenerRegistered && typeof document !== "undefined") {
@@ -311,6 +357,9 @@ function onConsentChange(cb) {
311
357
  document.addEventListener("visitorConsentCollected", (event) => {
312
358
  consentAPIResolved = true;
313
359
  const detail = event.detail;
360
+ if (detail && typeof detail.analyticsAllowed === "boolean") {
361
+ eventDecision = detail.analyticsAllowed;
362
+ }
314
363
  const granted = detail && typeof detail.analyticsAllowed === "boolean" ? detail.analyticsAllowed : isAnalyticsConsentGranted();
315
364
  for (const fn of callbacks) {
316
365
  try {
@@ -413,95 +462,168 @@ var STALE_MS = 3e5;
413
462
  var RENDER_BUDGET_MS = 300;
414
463
  var FAILURE_BACKOFF_MS = 3e4;
415
464
  var FETCH_TIMEOUT_MS = 5e3;
416
- var memory = /* @__PURE__ */ new Map();
465
+ var droppedWarned = /* @__PURE__ */ new Set();
466
+ var DROPPED_WARNED_MAX = 64;
417
467
  function rulesUrl(platformUrl, shopId) {
418
468
  const url = new URL("/api/storefront/tests/rules", platformUrl);
419
469
  url.searchParams.set("shop", shopId);
420
470
  return url.toString();
421
471
  }
422
- function isRuleset(value) {
423
- const v = value;
424
- return !!v && typeof v === "object" && Array.isArray(v.tests) && v.tests.every(
425
- (t) => t && typeof t.key === "string" && typeof t.status === "string" && Array.isArray(t.arms) && t.arms.every((a) => a && typeof a.key === "string")
472
+ var STATUSES = /* @__PURE__ */ new Set(["running", "paused", "completed"]);
473
+ var isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
474
+ var isNum = (v) => typeof v === "number" && Number.isFinite(v);
475
+ var optional = (v, check) => v === void 0 || v === null || check(v);
476
+ function isValidRule(t) {
477
+ if (!isObj(t)) return false;
478
+ if (typeof t.key !== "string" || !t.key || t.key.length > 64) return false;
479
+ if (typeof t.status !== "string" || !STATUSES.has(t.status)) return false;
480
+ if (!Array.isArray(t.arms) || !t.arms.every(
481
+ (a) => isObj(a) && typeof a.key === "string" && !!a.key && isNum(a.weight) && a.weight >= 0
482
+ )) {
483
+ return false;
484
+ }
485
+ if (!optional(t.seed, (v) => typeof v === "string")) return false;
486
+ if (!optional(t.hashVersion, isNum)) return false;
487
+ if (!optional(t.coverage, (v) => isNum(v) && v >= 0 && v <= 1)) return false;
488
+ if (!optional(t.winner, (v) => typeof v === "string")) return false;
489
+ if (!optional(t.config, isObj)) return false;
490
+ if (!optional(
491
+ t.namespace,
492
+ (v) => isObj(v) && typeof v.id === "string" && Array.isArray(v.range) && v.range.length === 2 && v.range.every(isNum)
493
+ )) {
494
+ return false;
495
+ }
496
+ return optional(
497
+ t.targeting,
498
+ (v) => isObj(v) && optional(
499
+ v.pathPrefix,
500
+ (p) => Array.isArray(p) && p.every((s2) => typeof s2 === "string")
501
+ ) && optional(v.device, (d) => d === "mobile" || d === "desktop") && optional(v.visitorType, (d) => d === "new" || d === "returning")
426
502
  );
427
503
  }
504
+ function sanitizeRuleset(value) {
505
+ if (!isObj(value) || !Array.isArray(value.tests)) return null;
506
+ if (typeof value.version !== "string") return null;
507
+ const tests = value.tests.filter(isValidRule);
508
+ if (tests.length !== value.tests.length && !droppedWarned.has(value.version)) {
509
+ if (droppedWarned.size >= DROPPED_WARNED_MAX) droppedWarned.clear();
510
+ droppedWarned.add(value.version);
511
+ console.warn(
512
+ "[playbook] dropped invalid rules",
513
+ value.tests.length - tests.length,
514
+ value.version
515
+ );
516
+ }
517
+ return { ...value, tests };
518
+ }
428
519
  function inBackoff(entry, now) {
429
520
  return entry.failedAt > 0 && now - entry.failedAt < FAILURE_BACKOFF_MS;
430
521
  }
431
- function refresh(key, url, entry, fetchImpl) {
432
- if (entry.inflight) return entry.inflight;
433
- const controller = new AbortController();
434
- const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
435
- entry.inflight = fetchImpl(url, {
436
- headers: { accept: "application/json" },
437
- signal: controller.signal
438
- }).then(async (res) => {
439
- if (!res.ok) throw new Error(`ruleset ${res.status}`);
440
- const json = await res.json();
441
- if (!isRuleset(json)) throw new Error("ruleset malformed");
442
- entry.ruleset = json;
443
- entry.fetchedAt = Date.now();
444
- entry.failedAt = 0;
445
- return json;
446
- }).catch((error) => {
447
- entry.failedAt = Date.now();
448
- console.warn("[playbook] ruleset fetch failed", String(error));
449
- return entry.ruleset;
450
- }).finally(() => {
451
- clearTimeout(timer);
452
- entry.inflight = null;
453
- });
454
- memory.set(key, entry);
455
- return entry.inflight;
456
- }
457
522
  var COLD_RENDER_BUDGET_MS = 1500;
458
523
  var BUDGET_MISSED = /* @__PURE__ */ Symbol("budget-missed");
524
+ function createCachedJsonFetcher({
525
+ label,
526
+ sanitize
527
+ }) {
528
+ const memory = /* @__PURE__ */ new Map();
529
+ const failingKeys = /* @__PURE__ */ new Set();
530
+ function refresh(key, url, entry, fetchImpl) {
531
+ if (entry.inflight) return entry.inflight;
532
+ const controller = new AbortController();
533
+ const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
534
+ entry.inflight = fetchImpl(url, {
535
+ headers: { accept: "application/json" },
536
+ signal: controller.signal
537
+ }).then(async (res) => {
538
+ if (!res.ok) throw new Error(`${label} ${res.status}`);
539
+ const json = sanitize(await res.json());
540
+ if (!json) throw new Error(`${label} malformed`);
541
+ entry.value = json;
542
+ entry.fetchedAt = Date.now();
543
+ entry.failedAt = 0;
544
+ failingKeys.delete(key);
545
+ return json;
546
+ }).catch((error) => {
547
+ entry.failedAt = Date.now();
548
+ if (!failingKeys.has(key)) {
549
+ failingKeys.add(key);
550
+ console.warn(`[playbook] ${label} fetch failed`, String(error));
551
+ }
552
+ return entry.value;
553
+ }).finally(() => {
554
+ clearTimeout(timer);
555
+ entry.inflight = null;
556
+ });
557
+ memory.set(key, entry);
558
+ return entry.inflight;
559
+ }
560
+ async function getWithSource({
561
+ url,
562
+ waitUntil,
563
+ fetchImpl = fetch
564
+ }) {
565
+ const key = url;
566
+ const entry = memory.get(key) ?? {
567
+ value: null,
568
+ fetchedAt: 0,
569
+ failedAt: 0,
570
+ inflight: null
571
+ };
572
+ const now = Date.now();
573
+ const age = now - entry.fetchedAt;
574
+ if (entry.value && age < FRESH_MS) {
575
+ return { value: entry.value, source: "memory" };
576
+ }
577
+ if (inBackoff(entry, now)) {
578
+ return { value: entry.value, source: "backoff" };
579
+ }
580
+ if (entry.value && age < FRESH_MS + STALE_MS) {
581
+ const p2 = refresh(key, url, entry, fetchImpl);
582
+ waitUntil?.(p2);
583
+ return { value: entry.value, source: "stale" };
584
+ }
585
+ const lastGood = entry.value;
586
+ const p = refresh(key, url, entry, fetchImpl);
587
+ waitUntil?.(p);
588
+ let timer;
589
+ const budget = new Promise((resolve) => {
590
+ timer = setTimeout(
591
+ () => resolve(BUDGET_MISSED),
592
+ lastGood ? RENDER_BUDGET_MS : COLD_RENDER_BUDGET_MS
593
+ );
594
+ });
595
+ const result = await Promise.race([p, budget]);
596
+ clearTimeout(timer);
597
+ if (result === BUDGET_MISSED) {
598
+ if (entry.inflight && entry.failedAt === 0) entry.failedAt = Date.now();
599
+ } else if (result && result !== lastGood) {
600
+ return { value: result, source: "fetched" };
601
+ }
602
+ if (lastGood) return { value: lastGood, source: "last-good" };
603
+ return { value: null, source: "cold-fallback" };
604
+ }
605
+ const reset = () => {
606
+ memory.clear();
607
+ failingKeys.clear();
608
+ };
609
+ return { getWithSource, reset };
610
+ }
611
+ var rulesetFetcher = createCachedJsonFetcher({
612
+ label: "ruleset",
613
+ sanitize: sanitizeRuleset
614
+ });
459
615
  async function getRulesetWithSource({
460
616
  platformUrl,
461
617
  shopId,
462
618
  waitUntil,
463
- fetchImpl = fetch
619
+ fetchImpl
464
620
  }) {
465
- const url = rulesUrl(platformUrl, shopId);
466
- const key = url;
467
- const entry = memory.get(key) ?? {
468
- ruleset: null,
469
- fetchedAt: 0,
470
- failedAt: 0,
471
- inflight: null
472
- };
473
- const now = Date.now();
474
- const age = now - entry.fetchedAt;
475
- if (entry.ruleset && age < FRESH_MS) {
476
- return { ruleset: entry.ruleset, source: "memory" };
477
- }
478
- if (inBackoff(entry, now)) {
479
- return { ruleset: entry.ruleset, source: "backoff" };
480
- }
481
- if (entry.ruleset && age < FRESH_MS + STALE_MS) {
482
- const p2 = refresh(key, url, entry, fetchImpl);
483
- waitUntil?.(p2);
484
- return { ruleset: entry.ruleset, source: "stale" };
485
- }
486
- const lastGood = entry.ruleset;
487
- const p = refresh(key, url, entry, fetchImpl);
488
- waitUntil?.(p);
489
- let timer;
490
- const budget = new Promise((resolve) => {
491
- timer = setTimeout(
492
- () => resolve(BUDGET_MISSED),
493
- lastGood ? RENDER_BUDGET_MS : COLD_RENDER_BUDGET_MS
494
- );
621
+ const { value, source } = await rulesetFetcher.getWithSource({
622
+ url: rulesUrl(platformUrl, shopId),
623
+ waitUntil,
624
+ fetchImpl
495
625
  });
496
- const result = await Promise.race([p, budget]);
497
- clearTimeout(timer);
498
- if (result === BUDGET_MISSED) {
499
- if (entry.inflight && entry.failedAt === 0) entry.failedAt = Date.now();
500
- } else if (result && result !== lastGood) {
501
- return { ruleset: result, source: "fetched" };
502
- }
503
- if (lastGood) return { ruleset: lastGood, source: "last-good" };
504
- return { ruleset: null, source: "cold-fallback" };
626
+ return { ruleset: value, source };
505
627
  }
506
628
  function prefetchRuleset(args) {
507
629
  const p = getRulesetWithSource(args).catch(() => null);
@@ -541,8 +663,8 @@ async function createPlaybook({
541
663
  request,
542
664
  waitUntil,
543
665
  fetchImpl,
544
- overrides,
545
- consentRequired = false
666
+ consentRequired = false,
667
+ consent: consentAdapter
546
668
  }) {
547
669
  const url = new URL(request.url);
548
670
  const device = detectDevice(request.headers.get("user-agent"));
@@ -576,7 +698,7 @@ async function createPlaybook({
576
698
  const domain = cookieDomainFor(url.hostname);
577
699
  const secure = url.protocol === "https:";
578
700
  const setCookieHeaders = [];
579
- let consent = analyticsConsentFromCookie(cookies[TRACKING_CONSENT_COOKIE]);
701
+ let consent = consentAdapter ? consentAdapter.fromRequest(request) : analyticsConsentFromCookie(cookies[TRACKING_CONSENT_COOKIE]);
580
702
  if (consent === "absent" && consentRequired) consent = "pending";
581
703
  const persistentAllowed = consent === "granted" || consent === "absent";
582
704
  const existing = [
@@ -601,6 +723,15 @@ async function createPlaybook({
601
723
  })
602
724
  );
603
725
  }
726
+ const marker = serverVisitorMarker(visitorId);
727
+ if (cookies[SERVER_VISITOR_MARKER_COOKIE] !== marker || !refreshed) {
728
+ setCookieHeaders.push(
729
+ serializeCookie(SERVER_VISITOR_MARKER_COOKIE, marker, {
730
+ maxAge: VISITOR_MAX_AGE,
731
+ secure
732
+ })
733
+ );
734
+ }
604
735
  if (!refreshed) {
605
736
  setCookieHeaders.push(
606
737
  serializeCookie(VISITOR_REFRESHED_COOKIE, "1", {
@@ -618,11 +749,16 @@ async function createPlaybook({
618
749
  })
619
750
  );
620
751
  }
621
- if (cookies[VISITOR_COOKIE]) {
752
+ if (consent === "denied" && cookies[VISITOR_COOKIE]) {
622
753
  setCookieHeaders.push(
623
754
  serializeCookie(VISITOR_COOKIE, "", { maxAge: 0, secure })
624
755
  );
625
756
  }
757
+ if (consent === "denied" && cookies[SERVER_VISITOR_MARKER_COOKIE]) {
758
+ setCookieHeaders.push(
759
+ serializeCookie(SERVER_VISITOR_MARKER_COOKIE, "", { maxAge: 0, secure })
760
+ );
761
+ }
626
762
  }
627
763
  if (cookies[LEGACY_VISITOR_COOKIE]) {
628
764
  setCookieHeaders.push(
@@ -689,22 +825,6 @@ async function createPlaybook({
689
825
  });
690
826
  assignments[test.key] = isolated && preview?.testKey !== test.key ? { ...a, arm: controlArmOf(test), inTest: false, forced: false, reason: "preview-isolated" } : a;
691
827
  }
692
- for (const o of overrides ?? []) {
693
- if (isolated && preview?.testKey !== o.testKey) continue;
694
- if (preview?.testKey === o.testKey && !(previewSource === "session" && o.source === "request")) {
695
- continue;
696
- }
697
- const test = ruleset?.tests.find((t) => t.key === o.testKey);
698
- const a = assignments[o.testKey];
699
- if (!test || !a || !test.arms.some((arm) => arm.key === o.arm)) continue;
700
- assignments[o.testKey] = {
701
- ...a,
702
- arm: o.arm,
703
- inTest: false,
704
- forced: true,
705
- reason: "override"
706
- };
707
- }
708
828
  return {
709
829
  state: {
710
830
  enabled: true,
@@ -729,177 +849,980 @@ async function createPlaybook({
729
849
  };
730
850
  }
731
851
 
732
- // src/tracker.ts
733
- var ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
734
- var KEY_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
735
- var EVENT_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/;
736
- var MAX_PATH_LENGTH = 500;
737
- var MAX_BODY_BYTES = 4e3;
738
- var STANDARD_EVENTS = [
739
- "add_to_cart",
740
- "checkout_started",
741
- "scroll_depth",
742
- "engaged_time",
743
- "variant_interaction"
744
- ];
745
- var DEFAULT_SUPPORTED_EVENTS = [...STANDARD_EVENTS];
746
- var INTERACTION_NAME_RE = /^[a-z][a-z0-9_]{0,39}$/;
747
- var MAX_PROPS = 20;
748
- function legacyAlias(event, props) {
749
- if (event === "variant_interaction" && props.name === "copy_code") {
750
- return { event: "code_copied", props: {} };
751
- }
752
- return null;
753
- }
754
- function cleanProps(props) {
755
- const out = {};
756
- for (const [k, v] of Object.entries(props)) {
757
- if (Object.keys(out).length >= MAX_PROPS) break;
758
- if (v === null || v === void 0) continue;
759
- if (typeof v === "string") out[k] = v.slice(0, 80);
760
- else if (typeof v === "number" && Number.isFinite(v)) out[k] = v;
761
- else if (typeof v === "boolean") out[k] = v;
762
- }
763
- return out;
764
- }
765
- var config = {
766
- state: null,
767
- consent: "pending",
768
- pathname: "/",
769
- exposureUrl: "/apps/playbook/api/storefront/tests/exposure",
770
- eventUrl: "/apps/playbook/api/storefront/tests/event",
771
- supportedEvents: new Set(DEFAULT_SUPPORTED_EVENTS),
772
- store: {}
773
- };
774
- var seenOnPage = /* @__PURE__ */ new Set();
775
- function configureTracker(next) {
776
- if (next.pathname !== void 0 && next.pathname !== config.pathname) {
777
- seenOnPage = /* @__PURE__ */ new Set();
778
- }
779
- config = { ...config, ...next };
780
- }
781
- function markSeenOnPage(testKey) {
782
- seenOnPage.add(testKey);
783
- }
784
- function analyticsAllowed(consent = config.consent) {
785
- return consent === "granted" || consent === "absent";
852
+ // src/cart.ts
853
+ var CART_VISITOR_ATTRIBUTE = "_pb_vid";
854
+ function playbookCartAttribute(visitorId) {
855
+ return { key: CART_VISITOR_ATTRIBUTE, value: visitorId };
786
856
  }
787
- var LOG_SIZE = 12;
788
- var log = [];
789
- var EMPTY_LOG = [];
790
- var listeners = /* @__PURE__ */ new Set();
791
- function record(entry) {
792
- log = [entry, ...log].slice(0, LOG_SIZE);
793
- listeners.forEach((fn) => fn());
857
+ function cartHasPlaybookAttribute(attributes, visitorId) {
858
+ return !!attributes?.some(
859
+ (a) => a.key === CART_VISITOR_ATTRIBUTE && a.value === visitorId
860
+ );
794
861
  }
795
- function getTrackedLog() {
796
- return log;
862
+ function reconcilePlaybookCartAttribute(current, visitorId) {
863
+ const attributes = current ?? [];
864
+ const ours = attributes.filter((a) => a.key === CART_VISITOR_ATTRIBUTE);
865
+ const correct = visitorId ? ours.length === 1 && ours[0].value === visitorId : ours.length === 0;
866
+ if (correct) return null;
867
+ const kept = attributes.filter((a) => a.key !== CART_VISITOR_ATTRIBUTE).map((a) => ({ key: a.key, value: a.value ?? "" }));
868
+ return visitorId ? [...kept, { key: CART_VISITOR_ATTRIBUTE, value: visitorId }] : kept;
797
869
  }
798
- function getServerTrackedLog() {
799
- return EMPTY_LOG;
870
+
871
+ // src/env.ts
872
+ function hasPlaybookParams(url) {
873
+ let search;
874
+ try {
875
+ search = (typeof url === "string" ? new URL(url) : url).search;
876
+ } catch {
877
+ return false;
878
+ }
879
+ return search.includes("_pv=") || search.includes("pbk=") || search.includes("pb_mode=brand_preview") || search.includes("_preview=true");
800
880
  }
801
- function subscribeTrackedLog(fn) {
802
- listeners.add(fn);
803
- return () => listeners.delete(fn);
881
+ function isKillSwitchOn(value) {
882
+ const v = (value ?? "").trim().toLowerCase();
883
+ return v === "1" || v === "true" || v === "yes" || v === "on";
804
884
  }
805
- var CONTEXT_KEY = "pb_ctx";
806
- var UTM_KEYS = [
807
- "utm_source",
808
- "utm_medium",
809
- "utm_campaign",
810
- "utm_content",
811
- "utm_term"
812
- ];
813
- var CLICK_IDS = [
814
- ["fbclid", "fbclid"],
815
- ["gclid", "gclid"],
816
- ["gbraid", "gclid"],
817
- ["wbraid", "gclid"],
818
- ["ttclid", "ttclid"]
819
- ];
820
- function clip(value, max = 100) {
821
- return value.slice(0, max);
885
+ function isPreviewHost(hostname) {
886
+ const h = hostname.toLowerCase();
887
+ return h === "localhost" || h === "127.0.0.1" || /\.myshopify\.(dev|com)$/.test(h) || /\.shopifypreview\.com$/.test(h) || /\.workers\.dev$/.test(h);
822
888
  }
823
- function getSessionContext() {
824
- if (typeof window === "undefined") return null;
889
+
890
+ // src/experience-attribution.ts
891
+ var EXPOSURE_COOKIE = "_pb_exp";
892
+ var EXPOSURE_CART_ATTRIBUTE = "pb_exp__";
893
+ var EXPERIENCE_VISITOR_CART_ATTRIBUTE = "pb_vid__";
894
+ var MAX_EXPOSURES = 8;
895
+ var EXPOSURE_TTL_DAYS = 30;
896
+ var EXPOSURE_ID_RE = /^[A-Za-z0-9-]{1,64}$/;
897
+ var VISITOR_ID_RE = /^[A-Za-z0-9._:-]{8,128}$/;
898
+ var ENTRY_SEP = "_";
899
+ var FIELD_SEP = ".";
900
+ function nowSeconds() {
901
+ return Math.floor(Date.now() / 1e3);
902
+ }
903
+ function maybeDecode(value) {
904
+ if (!value.includes("%")) return value;
825
905
  try {
826
- const stored = window.sessionStorage.getItem(CONTEXT_KEY);
827
- if (stored) return JSON.parse(stored);
906
+ return decodeURIComponent(value);
828
907
  } catch {
908
+ return value;
829
909
  }
830
- const url = new URL(window.location.href);
831
- const utm = {};
832
- for (const key of UTM_KEYS) {
833
- const v = url.searchParams.get(key);
834
- if (v) utm[key.slice(4)] = clip(v);
910
+ }
911
+ function normalize(list, now) {
912
+ const oldest = now - EXPOSURE_TTL_DAYS * 86400;
913
+ const sorted = list.filter(
914
+ (e) => EXPOSURE_ID_RE.test(e.experimentId) && EXPOSURE_ID_RE.test(e.armId) && EXPOSURE_ID_RE.test(e.impressionId) && Number.isFinite(e.seenAt) && e.seenAt >= oldest
915
+ ).sort((a, b) => b.seenAt - a.seenAt);
916
+ const seen = /* @__PURE__ */ new Set();
917
+ const out = [];
918
+ for (const e of sorted) {
919
+ if (seen.has(e.experimentId)) continue;
920
+ seen.add(e.experimentId);
921
+ out.push(e);
922
+ if (out.length >= MAX_EXPOSURES) break;
835
923
  }
836
- let referrerHost = null;
837
- try {
838
- const ref = document.referrer ? new URL(document.referrer).hostname : "";
839
- referrerHost = ref && ref !== url.hostname ? clip(ref) : null;
840
- } catch {
841
- referrerHost = null;
924
+ return out;
925
+ }
926
+ function normalizeExposureList(raw, now = nowSeconds()) {
927
+ if (typeof raw !== "string" || !raw) return null;
928
+ let value = maybeDecode(raw);
929
+ if (value.length > 4096) value = value.slice(0, 4096);
930
+ const parsed = [];
931
+ for (const part of value.split(ENTRY_SEP)) {
932
+ const fields = part.split(FIELD_SEP);
933
+ if (fields.length !== 4) continue;
934
+ const [experimentId, armId, impressionId, seen36] = fields;
935
+ const seenAt = parseInt(seen36, 36);
936
+ if (!Number.isFinite(seenAt)) continue;
937
+ parsed.push({ experimentId, armId, impressionId, seenAt });
842
938
  }
843
- const ctx = {
844
- utm,
845
- referrerHost,
846
- landingPath: clip(url.pathname, 200),
847
- clickIdType: CLICK_IDS.find(([param]) => url.searchParams.has(param))?.[1] ?? null
848
- };
939
+ const list = normalize(parsed, now);
940
+ if (!list.length) return null;
941
+ return list.map(
942
+ (e) => [
943
+ e.experimentId,
944
+ e.armId,
945
+ e.impressionId,
946
+ Math.max(0, Math.floor(e.seenAt)).toString(36)
947
+ ].join(FIELD_SEP)
948
+ ).join(ENTRY_SEP);
949
+ }
950
+ function validId(value) {
951
+ if (!value) return null;
952
+ const decoded = maybeDecode(value).trim();
953
+ return VISITOR_ID_RE.test(decoded) ? decoded : null;
954
+ }
955
+ function experienceVisitorIdFromCookies(cookies) {
956
+ return validId(cookies._y) ?? validId(cookies.shopify_client_id) ?? validId(cookies._shopify_y) ?? validId(cookies[VISITOR_COOKIE]);
957
+ }
958
+ function hasValue(attributes, key) {
959
+ return attributes.some((a) => a.key === key && !!a.value);
960
+ }
961
+ function reconcileExperienceCartAttributes(current, { consent, exposureCookie, visitorId, now }) {
962
+ const attributes = current ?? [];
963
+ const ours = /* @__PURE__ */ new Set([EXPOSURE_CART_ATTRIBUTE, EXPERIENCE_VISITOR_CART_ATTRIBUTE]);
964
+ const kept = () => attributes.map((a) => ({ key: a.key, value: a.value ?? "" }));
965
+ if (consent === "denied") {
966
+ if (!attributes.some((a) => ours.has(a.key))) return null;
967
+ return attributes.filter((a) => !ours.has(a.key)).map((a) => ({ key: a.key, value: a.value ?? "" }));
968
+ }
969
+ if (consent !== "allowed") return null;
970
+ const exposures = normalizeExposureList(exposureCookie, now);
971
+ if (!exposures) return null;
972
+ const additions = [];
973
+ if (!hasValue(attributes, EXPOSURE_CART_ATTRIBUTE)) {
974
+ additions.push({ key: EXPOSURE_CART_ATTRIBUTE, value: exposures });
975
+ }
976
+ const vid = visitorId && VISITOR_ID_RE.test(visitorId) ? visitorId : null;
977
+ if (vid && !hasValue(attributes, EXPERIENCE_VISITOR_CART_ATTRIBUTE)) {
978
+ additions.push({ key: EXPERIENCE_VISITOR_CART_ATTRIBUTE, value: vid });
979
+ }
980
+ if (!additions.length) return null;
981
+ const filling = new Set(additions.map((a) => a.key));
982
+ return [...kept().filter((a) => !filling.has(a.key)), ...additions];
983
+ }
984
+
985
+ // src/targeting.ts
986
+ function manifestUrl(platformUrl, shopDomain) {
987
+ const url = new URL("/api/storefront/targeting", platformUrl);
988
+ url.searchParams.set("shop", shopDomain);
989
+ return url.toString();
990
+ }
991
+ var MAX_PAGES = 500;
992
+ var MAX_KEY_LENGTH = 300;
993
+ function sanitizeManifestPages(value) {
994
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
995
+ const v = value;
996
+ if (typeof v.salt !== "string" || !Array.isArray(v.entries)) return null;
997
+ if (!Array.isArray(v.pages)) return [];
998
+ return v.pages.filter(
999
+ (p) => typeof p === "string" && p.length > 0 && p.length <= MAX_KEY_LENGTH
1000
+ ).slice(0, MAX_PAGES);
1001
+ }
1002
+ var manifestFetcher = createCachedJsonFetcher({
1003
+ label: "targeting manifest",
1004
+ sanitize: (json) => {
1005
+ const pages = sanitizeManifestPages(json);
1006
+ return pages ? { pages } : null;
1007
+ }
1008
+ });
1009
+ var HEALTHY = /* @__PURE__ */ new Set([
1010
+ "memory",
1011
+ "stale",
1012
+ "fetched"
1013
+ ]);
1014
+ async function getTargetedPages({
1015
+ platformUrl,
1016
+ shopDomain,
1017
+ waitUntil,
1018
+ fetchImpl
1019
+ }) {
849
1020
  try {
850
- window.sessionStorage.setItem(CONTEXT_KEY, JSON.stringify(ctx));
1021
+ const { value, source } = await manifestFetcher.getWithSource({
1022
+ url: manifestUrl(platformUrl, shopDomain),
1023
+ waitUntil,
1024
+ fetchImpl
1025
+ });
1026
+ return { pages: value && HEALTHY.has(source) ? value.pages : null, source };
851
1027
  } catch {
1028
+ return { pages: null, source: "cold-fallback" };
852
1029
  }
853
- return ctx;
854
1030
  }
855
- function coarseBrowser(ua) {
856
- if (/Edg\//.test(ua)) return "edge";
857
- if (/SamsungBrowser/.test(ua)) return "samsung";
858
- if (/FBAN|FBAV|Instagram/.test(ua)) return "in-app";
859
- if (/Firefox|FxiOS/.test(ua)) return "firefox";
860
- if (/Chrome|CriOS/.test(ua)) return "chrome";
861
- if (/Safari/.test(ua)) return "safari";
862
- return "other";
863
- }
864
- function coarseOs(ua) {
865
- if (/iPhone|iPad|iPod/.test(ua)) return "ios";
866
- if (/Android/.test(ua)) return "android";
867
- if (/Mac OS X/.test(ua)) return "macos";
868
- if (/Windows/.test(ua)) return "windows";
869
- if (/Linux|CrOS/.test(ua)) return "linux";
870
- return "other";
1031
+ var UNTARGETABLE_PATH_RE = /^\/(account|checkout|checkouts|orders|password|challenge|apps|tools|admin|services)(\/|$)/i;
1032
+ function targetPageKey(pathname) {
1033
+ let path = (pathname || "/").replace(/\/+$/, "") || "/";
1034
+ path = path.replace(/^\/[a-z]{2}(-[a-z]{2})?(?=\/|$)/i, "") || "/";
1035
+ if (path === "/") return "home:";
1036
+ if (UNTARGETABLE_PATH_RE.test(path)) return null;
1037
+ const decode = (raw) => {
1038
+ let h = raw;
1039
+ try {
1040
+ h = decodeURIComponent(h);
1041
+ } catch {
1042
+ }
1043
+ h = h.trim().toLowerCase();
1044
+ return h.length > 0 ? h : null;
1045
+ };
1046
+ const handle = (re) => {
1047
+ const m = re.exec(path);
1048
+ return m ? decode(m[1]) : null;
1049
+ };
1050
+ const product = handle(/\/products\/([^/?#]+)/);
1051
+ if (product) return `product:${product}`;
1052
+ const collection = handle(/^\/collections\/([^/?#]+)$/);
1053
+ if (collection) return `collection:${collection}`;
1054
+ const page = handle(/^\/pages\/([^/?#]+)$/);
1055
+ if (page) return `page:${page}`;
1056
+ const other = decode(path.replace(/^\//, ""));
1057
+ return other ? `page:${other}` : null;
1058
+ }
1059
+ function matchTargetedPage(pages, pathname) {
1060
+ if (!pages || pages.length === 0) return null;
1061
+ const key = targetPageKey(pathname);
1062
+ if (!key) return null;
1063
+ const hit = pages.some((p) => {
1064
+ if (typeof p !== "string") return false;
1065
+ const k = p.toLowerCase();
1066
+ return k.endsWith("*") ? key.startsWith(k.slice(0, -1)) : k === key;
1067
+ });
1068
+ return hit ? key : null;
871
1069
  }
872
- function viewportBucket(width) {
873
- if (width < 480) return "xs";
874
- if (width < 768) return "sm";
875
- if (width < 1024) return "md";
876
- if (width < 1440) return "lg";
877
- return "xl";
1070
+ var OWNED_PARAM_RE = /[?&](pbk|pb|_pv|_preview|pb_mode|pbThumb)=/;
1071
+ function hasOwnedPreviewParams(search) {
1072
+ return OWNED_PARAM_RE.test(search || "");
878
1073
  }
879
- function exposureContext() {
880
- const s = config.state;
881
- const session = getSessionContext();
882
- const ua = typeof navigator !== "undefined" ? navigator.userAgent : "";
883
- return {
884
- country: s?.geo?.country ?? null,
885
- region: s?.geo?.region ?? null,
886
- market: config.store.market ?? null,
887
- locale: config.store.locale ?? null,
888
- utm: session?.utm ?? {},
889
- referrerHost: session?.referrerHost ?? null,
890
- landingPath: session?.landingPath ?? null,
891
- clickIdType: session?.clickIdType ?? null,
892
- browser: coarseBrowser(ua),
893
- os: coarseOs(ua),
894
- viewportBucket: viewportBucket(window.innerWidth),
895
- isLoggedIn: config.store.isLoggedIn ?? null
896
- };
1074
+
1075
+ // src/request-context.ts
1076
+ var FINALIZE_WAIT_MS = 2e3;
1077
+ var FINALIZE_REDIRECT_WAIT_MS = 0;
1078
+ function str(v) {
1079
+ return typeof v === "string" && v ? v : void 0;
897
1080
  }
898
- var sentThisPage = /* @__PURE__ */ new Set();
899
- function exposureKey(visitorId, testKey) {
900
- return `pb_exp:${visitorId}:${testKey}`;
1081
+ function normalizeDomain(raw) {
1082
+ return raw.trim().toLowerCase().replace(/^https?:\/\//, "").replace(/[/?#].*$/, "");
901
1083
  }
902
- function hasSentExposure(visitorId, testKey) {
1084
+ function createPlaybookContext({
1085
+ request,
1086
+ env,
1087
+ waitUntil,
1088
+ shopId: shopIdOption,
1089
+ platformUrl: platformUrlOption,
1090
+ disabled: disabledOption,
1091
+ consentRequired = false,
1092
+ consent,
1093
+ experienceAttribution = true,
1094
+ cloak: cloakOption = true,
1095
+ shopDomain: shopDomainOption,
1096
+ apiBase: apiBaseOption,
1097
+ fetchImpl
1098
+ }) {
1099
+ const e = env ?? {};
1100
+ const disabled = disabledOption ?? isKillSwitchOn(str(e.PLAYBOOK_TESTS_DISABLED));
1101
+ const configuredShop = shopIdOption ?? str(e.PUBLIC_PLAYBOOK_SHOP_ID) ?? null;
1102
+ const shopId = disabled ? null : configuredShop;
1103
+ const platformUrl = platformUrlOption || str(e.PLAYBOOK_PLATFORM_URL) || DEFAULT_PLATFORM_URL;
1104
+ let promise = null;
1105
+ let settled = false;
1106
+ if (shopId && request.method === "GET") {
1107
+ try {
1108
+ prefetchRuleset({ platformUrl, shopId, waitUntil, fetchImpl });
1109
+ } catch {
1110
+ }
1111
+ }
1112
+ const get = () => {
1113
+ if (!promise) {
1114
+ promise = createPlaybook({
1115
+ // Kill switch → shopId null → createPlaybook's disabled path:
1116
+ // everyone control, no cookies, `enabled: false` on the client.
1117
+ shopId,
1118
+ platformUrl,
1119
+ request,
1120
+ waitUntil,
1121
+ fetchImpl,
1122
+ consentRequired,
1123
+ consent
1124
+ }).catch((error) => {
1125
+ console.error("[playbook] createPlaybook failed", String(error));
1126
+ return null;
1127
+ }).finally(() => {
1128
+ settled = true;
1129
+ });
1130
+ }
1131
+ return promise;
1132
+ };
1133
+ const cookiesFor = async (waitMs) => {
1134
+ if (!promise) return [];
1135
+ if (!settled) {
1136
+ let timer;
1137
+ const timeout = new Promise((resolve) => {
1138
+ timer = setTimeout(() => resolve("timeout"), waitMs);
1139
+ });
1140
+ const winner = await Promise.race([promise, timeout]);
1141
+ clearTimeout(timer);
1142
+ if (winner === "timeout") return [];
1143
+ return winner?.setCookieHeaders ?? [];
1144
+ }
1145
+ return (await promise)?.setCookieHeaders ?? [];
1146
+ };
1147
+ const cartConsent = (cookies) => {
1148
+ const state = consent ? consent.fromRequest(request) : analyticsConsentFromCookie(cookies[TRACKING_CONSENT_COOKIE]);
1149
+ if (state === "granted" || state === "absent" && !consentRequired) {
1150
+ return "allowed";
1151
+ }
1152
+ return state === "denied" ? "denied" : "unknown";
1153
+ };
1154
+ const cartVisitorId = () => {
1155
+ if (!shopId) return null;
1156
+ try {
1157
+ const cookies = parseCookies(request.headers.get("cookie"));
1158
+ if (cartConsent(cookies) !== "allowed") return null;
1159
+ return [cookies[VISITOR_COOKIE], cookies[SESSION_VISITOR_COOKIE]].find(
1160
+ (v) => isValidVisitorId(v)
1161
+ ) ?? null;
1162
+ } catch {
1163
+ return null;
1164
+ }
1165
+ };
1166
+ let cloakPromise = null;
1167
+ const cloakFor = () => {
1168
+ if (!cloakPromise) {
1169
+ cloakPromise = (async () => {
1170
+ if (!shopId || !cloakOption || request.method !== "GET") return null;
1171
+ const url = new URL(request.url);
1172
+ if (url.pathname.endsWith(".data")) return null;
1173
+ if (hasOwnedPreviewParams(url.search)) return null;
1174
+ if (!targetPageKey(url.pathname)) return null;
1175
+ const shopDomain = normalizeDomain(
1176
+ shopDomainOption ?? str(e.PUBLIC_PLAYBOOK_SHOP_DOMAIN) ?? url.hostname
1177
+ );
1178
+ if (!shopDomain) return null;
1179
+ const { pages } = await getTargetedPages({
1180
+ platformUrl,
1181
+ shopDomain,
1182
+ waitUntil,
1183
+ fetchImpl
1184
+ });
1185
+ const targetedPage = matchTargetedPage(pages, url.pathname);
1186
+ if (!targetedPage) return null;
1187
+ return {
1188
+ targetedPage,
1189
+ shopDomain,
1190
+ apiBase: apiBaseOption || `${url.origin}/apps/playbook`
1191
+ };
1192
+ })().catch(() => null);
1193
+ }
1194
+ return cloakPromise;
1195
+ };
1196
+ const append = (headers, cookies) => {
1197
+ for (const cookie of cookies) headers.append("Set-Cookie", cookie);
1198
+ };
1199
+ return {
1200
+ shopId,
1201
+ platformUrl,
1202
+ disabled: disabled || !configuredShop,
1203
+ get,
1204
+ async loaderData() {
1205
+ const [result, cloak] = await Promise.all([get(), cloakFor()]);
1206
+ return {
1207
+ playbook: result?.state ?? null,
1208
+ hasPlaybookParams: hasPlaybookParams(request.url),
1209
+ targetedPage: cloak?.targetedPage ?? null,
1210
+ cloak
1211
+ };
1212
+ },
1213
+ cartAttribute() {
1214
+ const id = cartVisitorId();
1215
+ return id ? { key: CART_VISITOR_ATTRIBUTE, value: id } : null;
1216
+ },
1217
+ cartVisitorId,
1218
+ reconcileCartAttributes(current) {
1219
+ if (!shopId) return null;
1220
+ let storeEdit = null;
1221
+ try {
1222
+ storeEdit = reconcilePlaybookCartAttribute(current, cartVisitorId());
1223
+ } catch {
1224
+ return null;
1225
+ }
1226
+ if (!experienceAttribution) return storeEdit;
1227
+ try {
1228
+ const cookies = parseCookies(request.headers.get("cookie"));
1229
+ const consentState = cartConsent(cookies);
1230
+ const experience = reconcileExperienceCartAttributes(
1231
+ storeEdit ?? current,
1232
+ {
1233
+ consent: consentState,
1234
+ exposureCookie: cookies[EXPOSURE_COOKIE],
1235
+ visitorId: consentState === "allowed" ? experienceVisitorIdFromCookies(cookies) : null
1236
+ }
1237
+ );
1238
+ return experience ?? storeEdit;
1239
+ } catch {
1240
+ return storeEdit;
1241
+ }
1242
+ },
1243
+ async appendCookies(headers) {
1244
+ try {
1245
+ append(headers, await cookiesFor(FINALIZE_WAIT_MS));
1246
+ } catch {
1247
+ }
1248
+ },
1249
+ async finalize(response) {
1250
+ try {
1251
+ const isRedirect = response.status >= 300 && response.status < 400;
1252
+ const cookies = await cookiesFor(
1253
+ isRedirect ? FINALIZE_REDIRECT_WAIT_MS : FINALIZE_WAIT_MS
1254
+ );
1255
+ if (!cookies.length) return response;
1256
+ try {
1257
+ append(response.headers, cookies);
1258
+ return response;
1259
+ } catch {
1260
+ const headers = new Headers(response.headers);
1261
+ append(headers, cookies);
1262
+ return new Response(response.body, {
1263
+ status: response.status,
1264
+ statusText: response.statusText,
1265
+ headers
1266
+ });
1267
+ }
1268
+ } catch {
1269
+ return response;
1270
+ }
1271
+ }
1272
+ };
1273
+ }
1274
+ async function withPlaybook(options, handler) {
1275
+ const playbook = createPlaybookContext(options);
1276
+ return playbook.finalize(await handler(playbook));
1277
+ }
1278
+
1279
+ // src/visitor-sync.ts
1280
+ function writeCookie(value, days) {
1281
+ try {
1282
+ const expires = new Date(Date.now() + days * 864e5).toUTCString();
1283
+ const secure = window.location.protocol === "https:" ? ";Secure" : "";
1284
+ document.cookie = `${VISITOR_COOKIE}=${value};expires=${expires};path=/;SameSite=Lax${secure}`;
1285
+ } catch {
1286
+ }
1287
+ }
1288
+ function readCookie() {
1289
+ try {
1290
+ const parts = `; ${document.cookie}`.split(`; ${VISITOR_COOKIE}=`);
1291
+ return parts.length === 2 ? parts.pop()?.split(";").shift() ?? null : null;
1292
+ } catch {
1293
+ return null;
1294
+ }
1295
+ }
1296
+ function syncVisitorId(visitorId, consent) {
1297
+ try {
1298
+ window.sessionStorage.setItem(VISITOR_COOKIE, visitorId);
1299
+ } catch {
1300
+ }
1301
+ if (consent === "granted" || consent === "absent") {
1302
+ if (readCookie() !== visitorId) writeCookie(visitorId, 365);
1303
+ } else if (consent === "denied" && readCookie() !== null) {
1304
+ writeCookie("", -1);
1305
+ }
1306
+ }
1307
+ function visitorSeedScript(visitorId) {
1308
+ if (!isValidVisitorId(visitorId ?? void 0)) return "";
1309
+ return `try{sessionStorage.setItem(${JSON.stringify(VISITOR_COOKIE)},${JSON.stringify(visitorId)})}catch(e){}`;
1310
+ }
1311
+ var DEFAULT_SDK_URL = "https://cdn.heyplaybook.com/playbook.js";
1312
+ var DEFAULT_PROXY_ENDPOINT = "/apps/playbook";
1313
+ var ANTI_FLICKER_CSS = "html:not(.pb-ready){opacity:0!important}html.pb-ready{opacity:1!important;transition:opacity 0.3s ease-in!important}";
1314
+ function revealScript(hasPlaybookParams2) {
1315
+ return `
1316
+ (function(){
1317
+ function reveal() {
1318
+ document.documentElement.classList.add('pb-ready');
1319
+ if (window.__pbFlickerTimeout) {
1320
+ clearTimeout(window.__pbFlickerTimeout);
1321
+ window.__pbFlickerTimeout = null;
1322
+ }
1323
+ }
1324
+
1325
+ ${hasPlaybookParams2 ? "window.__pbFlickerTimeout = setTimeout(reveal, 3000);" : ""}
1326
+
1327
+ window.Playbook = window.Playbook || {};
1328
+ window.Playbook.pageReady = reveal;
1329
+ })();
1330
+ `;
1331
+ }
1332
+ function PlaybookHead({
1333
+ shopId,
1334
+ apiEndpoint = DEFAULT_PROXY_ENDPOINT,
1335
+ sdkUrl = DEFAULT_SDK_URL,
1336
+ hasPlaybookParams: hasPlaybookParams2 = false,
1337
+ state,
1338
+ visitorId,
1339
+ nonce
1340
+ }) {
1341
+ if (!shopId) return null;
1342
+ const id = visitorId !== void 0 ? visitorId : state?.enabled ? state.visitorId : null;
1343
+ const seed = visitorSeedScript(id);
1344
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
1345
+ hasPlaybookParams2 && /* @__PURE__ */ jsx(
1346
+ "style",
1347
+ {
1348
+ id: "pb-anti-flicker",
1349
+ nonce,
1350
+ dangerouslySetInnerHTML: { __html: ANTI_FLICKER_CSS }
1351
+ }
1352
+ ),
1353
+ /* @__PURE__ */ jsx(
1354
+ "script",
1355
+ {
1356
+ nonce,
1357
+ dangerouslySetInnerHTML: { __html: revealScript(hasPlaybookParams2) }
1358
+ }
1359
+ ),
1360
+ seed && /* @__PURE__ */ jsx("script", { nonce, dangerouslySetInnerHTML: { __html: seed } }),
1361
+ /* @__PURE__ */ jsx(
1362
+ "script",
1363
+ {
1364
+ src: sdkUrl,
1365
+ nonce,
1366
+ "data-pb-config": JSON.stringify({ shopId, apiEndpoint }),
1367
+ async: true
1368
+ }
1369
+ )
1370
+ ] });
1371
+ }
1372
+ var CLOAK_MAX_MS = 1500;
1373
+ var DEFAULT_EXPERIENCE_SDK_URL = "https://cdn.heyplaybook.com/experience-sdk.js";
1374
+ var CLOAK_STYLE_ID = "pb-cloak";
1375
+ var EXPERIENCE_SDK_SCRIPT_ID = "pb-experience-sdk";
1376
+ function jsLiteral(value) {
1377
+ return JSON.stringify(value).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
1378
+ }
1379
+ function safeSdkUrl(raw) {
1380
+ if (!raw) return DEFAULT_EXPERIENCE_SDK_URL;
1381
+ try {
1382
+ const u = new URL(raw);
1383
+ return u.protocol === "https:" && !u.username && !u.password ? u.toString() : DEFAULT_EXPERIENCE_SDK_URL;
1384
+ } catch {
1385
+ return DEFAULT_EXPERIENCE_SDK_URL;
1386
+ }
1387
+ }
1388
+ function clampHide(ms) {
1389
+ if (typeof ms !== "number" || !Number.isFinite(ms)) return CLOAK_MAX_MS;
1390
+ return Math.min(CLOAK_MAX_MS, Math.max(100, Math.round(ms)));
1391
+ }
1392
+ function buildHeadSnippet(cloak, options = {}) {
1393
+ if (!cloak || !cloak.targetedPage || !cloak.shopDomain || !cloak.apiBase) {
1394
+ return null;
1395
+ }
1396
+ const ms = clampHide(options.maxHideMs);
1397
+ const src = safeSdkUrl(options.sdkUrl);
1398
+ const css = `html:not(.pb-ready){opacity:0;animation:pb-uncloak 0s linear ${ms}ms forwards}@keyframes pb-uncloak{to{opacity:1}}`;
1399
+ const script = "(function(){var w=window,d=document;if(w.__pbCloak)return;var st=d.getElementById(" + jsLiteral(CLOAK_STYLE_ID) + ");function now(){try{return Math.round(performance.now())}catch(e){return 0}}var state={armedAt:now(),liftedAt:null,reason:null,rules:1,sdk:" + jsLiteral(src) + ",page:" + jsLiteral(cloak.targetedPage) + '};var timer=null;function lift(reason){if(state.liftedAt!==null)return;if(timer)clearTimeout(timer);state.liftedAt=now();state.reason=reason||"sdk";try{if(st){st.disabled=true;if(st.sheet)st.sheet.disabled=true}}catch(e){}try{performance.mark("pb:cloak:lift")}catch(e){}}state.lift=lift;w.__pbCloak=state;try{d.addEventListener("error",function(e){var t=e&&e.target;if(t&&t.id===' + jsLiteral(EXPERIENCE_SDK_SCRIPT_ID) + '){state.sdk=null;lift("sdk-error")}},true)}catch(e){}try{if(w.top!==w.self)return lift("iframe");if(/(\\.vercel\\.app|heyplaybook\\.com)$/.test(location.hostname))return lift("preview-host");if(/[?&](pbk|pb|_pv|_preview|pb_mode|pbThumb)=/.test(location.search))return lift("param")}catch(e){return lift("error")}timer=setTimeout(function(){lift("timeout")},' + ms + ");})();";
1400
+ const attrs = {
1401
+ "data-pb-api-base": cloak.apiBase,
1402
+ "data-pb-shop": cloak.shopDomain,
1403
+ "data-pb-targeted": "1"
1404
+ };
1405
+ if (options.consentRequired) attrs["data-pb-consent"] = "required";
1406
+ return { css, script, sdk: { src, attrs }, nonce: options.nonce };
1407
+ }
1408
+ var PlaybookCloakHead = memo(
1409
+ function PlaybookCloakHead2({
1410
+ cloak,
1411
+ ...options
1412
+ }) {
1413
+ const parts = buildHeadSnippet(cloak, options);
1414
+ if (!parts) return null;
1415
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
1416
+ /* @__PURE__ */ jsx(
1417
+ "style",
1418
+ {
1419
+ id: CLOAK_STYLE_ID,
1420
+ nonce: parts.nonce,
1421
+ dangerouslySetInnerHTML: { __html: parts.css }
1422
+ }
1423
+ ),
1424
+ /* @__PURE__ */ jsx(
1425
+ "script",
1426
+ {
1427
+ nonce: parts.nonce,
1428
+ dangerouslySetInnerHTML: { __html: parts.script }
1429
+ }
1430
+ ),
1431
+ /* @__PURE__ */ jsx(
1432
+ "script",
1433
+ {
1434
+ id: EXPERIENCE_SDK_SCRIPT_ID,
1435
+ src: parts.sdk.src,
1436
+ nonce: parts.nonce,
1437
+ async: true,
1438
+ ...parts.sdk.attrs
1439
+ }
1440
+ )
1441
+ ] });
1442
+ },
1443
+ () => true
1444
+ );
1445
+ function playbookHeadSnippet(cloak, options = {}) {
1446
+ if (!buildHeadSnippet(cloak, options)) return null;
1447
+ return /* @__PURE__ */ jsx(PlaybookCloakHead, { cloak, ...options });
1448
+ }
1449
+ function escapeAttr(value) {
1450
+ return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1451
+ }
1452
+ function playbookHeadSnippetHtml(cloak, options = {}) {
1453
+ const parts = buildHeadSnippet(cloak, options);
1454
+ if (!parts) return "";
1455
+ const nonce = parts.nonce ? ` nonce="${escapeAttr(parts.nonce)}"` : "";
1456
+ const attrs = Object.entries(parts.sdk.attrs).map(([k, v]) => ` ${k}="${escapeAttr(v)}"`).join("");
1457
+ return `<style id="${CLOAK_STYLE_ID}"${nonce}>${parts.css}</style><script${nonce}>${parts.script}</script><script id="${EXPERIENCE_SDK_SCRIPT_ID}" src="${escapeAttr(parts.sdk.src)}"${nonce} async${attrs}></script>`;
1458
+ }
1459
+ var PlaybookBoundary = class extends Component {
1460
+ state = { failed: false };
1461
+ static getDerivedStateFromError() {
1462
+ return { failed: true };
1463
+ }
1464
+ componentDidCatch(error) {
1465
+ try {
1466
+ console.warn(`[playbook] ${this.props.name} disabled`, String(error));
1467
+ } catch {
1468
+ }
1469
+ }
1470
+ render() {
1471
+ return this.state.failed ? null : this.props.children ?? null;
1472
+ }
1473
+ };
1474
+
1475
+ // src/cart-sync.ts
1476
+ function mergeAttributes(current, add) {
1477
+ const map = /* @__PURE__ */ new Map();
1478
+ for (const a of current ?? []) {
1479
+ if (a?.key) map.set(a.key, a.value ?? "");
1480
+ }
1481
+ for (const a of add) {
1482
+ if (!a.value) map.delete(a.key);
1483
+ else map.set(a.key, a.value);
1484
+ }
1485
+ return [...map].map(([key, value]) => ({ key, value }));
1486
+ }
1487
+ var WRITE_TIMEOUT_MS = 8e3;
1488
+ async function withTimeout(fetchImpl, url, init) {
1489
+ const controller = new AbortController();
1490
+ const timer = setTimeout(() => controller.abort(), WRITE_TIMEOUT_MS);
1491
+ try {
1492
+ return await fetchImpl(url, { ...init, signal: controller.signal });
1493
+ } finally {
1494
+ clearTimeout(timer);
1495
+ }
1496
+ }
1497
+ function attributesFrom(data) {
1498
+ const attrs = data?.cart?.attributes;
1499
+ return Array.isArray(attrs) ? attrs : null;
1500
+ }
1501
+ function createCartAttributeWriter({
1502
+ endpoint = "/api/cart",
1503
+ serverMerges = false,
1504
+ fetchImpl
1505
+ } = {}) {
1506
+ return async (add, current) => {
1507
+ try {
1508
+ const list = serverMerges ? add.map((a) => ({ key: a.key, value: a.value ?? "" })) : mergeAttributes(current, add);
1509
+ const form = new FormData();
1510
+ form.append("action", "AttributesUpdateInput");
1511
+ form.append("attributes", JSON.stringify(list));
1512
+ form.append(
1513
+ "cartFormInput",
1514
+ JSON.stringify({
1515
+ action: "AttributesUpdateInput",
1516
+ inputs: { attributes: list }
1517
+ })
1518
+ );
1519
+ const res = await withTimeout(fetchImpl ?? fetch, endpoint, {
1520
+ method: "POST",
1521
+ body: form,
1522
+ headers: { accept: "application/json" }
1523
+ });
1524
+ if (!res.ok) return { ok: false };
1525
+ let data = null;
1526
+ try {
1527
+ data = await res.json();
1528
+ } catch {
1529
+ return { ok: true, attributes: null };
1530
+ }
1531
+ const d = data;
1532
+ const failed = !!(d?.userErrors?.length || d?.errors?.length);
1533
+ return { ok: !failed, attributes: attributesFrom(data) };
1534
+ } catch {
1535
+ return { ok: false };
1536
+ }
1537
+ };
1538
+ }
1539
+ function createCartAttributeReader({
1540
+ endpoint = "/api/cart",
1541
+ fetchImpl
1542
+ } = {}) {
1543
+ return async () => {
1544
+ try {
1545
+ const res = await withTimeout(fetchImpl ?? fetch, endpoint, {
1546
+ headers: { accept: "application/json" }
1547
+ });
1548
+ if (!res.ok) return null;
1549
+ return attributesFrom(await res.json());
1550
+ } catch {
1551
+ return null;
1552
+ }
1553
+ };
1554
+ }
1555
+ var CART_SYNC_IDLE_MS = 3e3;
1556
+ var MAX_WRITES_PER_CART = 3;
1557
+ function createCartAttributeSync({
1558
+ write,
1559
+ read,
1560
+ maxWritesPerCart = MAX_WRITES_PER_CART,
1561
+ idleMs = CART_SYNC_IDLE_MS,
1562
+ protectedKeyPrefixes = ["_ig"],
1563
+ onEvent
1564
+ }) {
1565
+ let counted = {
1566
+ cartId: null,
1567
+ count: 0
1568
+ };
1569
+ let inFlight = false;
1570
+ let timer = null;
1571
+ let disposed = false;
1572
+ const emit = (e) => {
1573
+ try {
1574
+ onEvent?.(e);
1575
+ } catch {
1576
+ }
1577
+ };
1578
+ const isProtected = (key) => protectedKeyPrefixes.some((p) => key.startsWith(p));
1579
+ const cancel = () => {
1580
+ if (timer) clearTimeout(timer);
1581
+ timer = null;
1582
+ };
1583
+ async function run(s2) {
1584
+ if (disposed || inFlight) return;
1585
+ if (counted.cartId !== s2.cartId) counted = { cartId: s2.cartId, count: 0 };
1586
+ if (counted.count >= maxWritesPerCart) {
1587
+ emit({ type: "capped", cartId: s2.cartId });
1588
+ return;
1589
+ }
1590
+ counted.count += 1;
1591
+ inFlight = true;
1592
+ try {
1593
+ const before = (s2.attributes ?? []).filter(
1594
+ (a) => a?.key && isProtected(a.key) && a.value
1595
+ );
1596
+ const attribute = { key: CART_VISITOR_ATTRIBUTE, value: s2.visitorId };
1597
+ const result = await write([attribute], s2.attributes);
1598
+ emit({ type: "written", cartId: s2.cartId, ok: result.ok });
1599
+ if (!before.length) return;
1600
+ const after = result.attributes ?? (read ? await read() : null) ?? null;
1601
+ if (!after) return;
1602
+ const present = new Set(after.map((a) => a.key));
1603
+ const lost = before.filter((a) => !present.has(a.key));
1604
+ if (!lost.length) return;
1605
+ const restored = await write(lost, after);
1606
+ emit({
1607
+ type: "restored",
1608
+ cartId: s2.cartId,
1609
+ keys: lost.map((a) => a.key),
1610
+ ok: restored.ok
1611
+ });
1612
+ } catch {
1613
+ } finally {
1614
+ inFlight = false;
1615
+ }
1616
+ }
1617
+ return {
1618
+ update(s2) {
1619
+ cancel();
1620
+ if (disposed || !s2.eligible || !s2.cartId || !s2.visitorId) return;
1621
+ if (s2.status && s2.status !== "idle") return;
1622
+ if (cartHasPlaybookAttribute(s2.attributes, s2.visitorId)) return;
1623
+ if (inFlight) return;
1624
+ if (counted.cartId === s2.cartId && counted.count >= maxWritesPerCart) {
1625
+ return;
1626
+ }
1627
+ const ready = { ...s2, cartId: s2.cartId, visitorId: s2.visitorId };
1628
+ emit({ type: "scheduled", cartId: s2.cartId });
1629
+ timer = setTimeout(() => {
1630
+ timer = null;
1631
+ void run(ready);
1632
+ }, idleMs);
1633
+ },
1634
+ dispose() {
1635
+ disposed = true;
1636
+ cancel();
1637
+ },
1638
+ /** Test/debug: writes made for the current cart. */
1639
+ writesForCart(cartId) {
1640
+ return counted.cartId === cartId ? counted.count : 0;
1641
+ }
1642
+ };
1643
+ }
1644
+ function withPlaybookCartAttribute(input, attribute) {
1645
+ const base = input ?? {};
1646
+ if (!attribute?.value) return base;
1647
+ return {
1648
+ ...base,
1649
+ attributes: mergeAttributes(base.attributes, [attribute])
1650
+ };
1651
+ }
1652
+
1653
+ // src/tracker.ts
1654
+ var ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
1655
+ var KEY_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
1656
+ var EVENT_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/;
1657
+ var MAX_PATH_LENGTH = 500;
1658
+ var MAX_BODY_BYTES = 4e3;
1659
+ var STANDARD_EVENTS = [
1660
+ "add_to_cart",
1661
+ "checkout_started",
1662
+ "scroll_depth",
1663
+ "engaged_time",
1664
+ "variant_interaction"
1665
+ ];
1666
+ var DEFAULT_SUPPORTED_EVENTS = [...STANDARD_EVENTS];
1667
+ var INTERACTION_NAME_RE = /^[a-z][a-z0-9_]{0,39}$/;
1668
+ var MAX_PROPS = 20;
1669
+ function legacyAlias(event, props) {
1670
+ if (event === "variant_interaction" && props.name === "copy_code") {
1671
+ return { event: "code_copied", props: {} };
1672
+ }
1673
+ return null;
1674
+ }
1675
+ function cleanProps(props) {
1676
+ const out = {};
1677
+ for (const [k, v] of Object.entries(props)) {
1678
+ if (Object.keys(out).length >= MAX_PROPS) break;
1679
+ if (v === null || v === void 0) continue;
1680
+ if (typeof v === "string") out[k] = v.slice(0, 80);
1681
+ else if (typeof v === "number" && Number.isFinite(v)) out[k] = v;
1682
+ else if (typeof v === "boolean") out[k] = v;
1683
+ }
1684
+ return out;
1685
+ }
1686
+ var DEFAULT_DATALAYER_EVENT = "view_experiment";
1687
+ var config = {
1688
+ state: null,
1689
+ consent: "pending",
1690
+ pathname: "/",
1691
+ exposureUrl: "/apps/playbook/api/storefront/tests/exposure",
1692
+ eventUrl: "/apps/playbook/api/storefront/tests/event",
1693
+ supportedEvents: new Set(DEFAULT_SUPPORTED_EVENTS),
1694
+ store: {},
1695
+ dataLayer: false
1696
+ };
1697
+ var seenOnPage = /* @__PURE__ */ new Set();
1698
+ function configureTracker(next) {
1699
+ if (next.pathname !== void 0 && next.pathname !== config.pathname) {
1700
+ seenOnPage = /* @__PURE__ */ new Set();
1701
+ }
1702
+ config = { ...config, ...next };
1703
+ }
1704
+ function markSeenOnPage(testKey) {
1705
+ seenOnPage.add(testKey);
1706
+ }
1707
+ function analyticsAllowed(consent = config.consent) {
1708
+ return consent === "granted" || consent === "absent";
1709
+ }
1710
+ var LOG_SIZE = 12;
1711
+ var log = [];
1712
+ var EMPTY_LOG = [];
1713
+ var listeners = /* @__PURE__ */ new Set();
1714
+ function record(entry) {
1715
+ log = [entry, ...log].slice(0, LOG_SIZE);
1716
+ listeners.forEach((fn) => fn());
1717
+ }
1718
+ function getTrackedLog() {
1719
+ return log;
1720
+ }
1721
+ function getServerTrackedLog() {
1722
+ return EMPTY_LOG;
1723
+ }
1724
+ function subscribeTrackedLog(fn) {
1725
+ listeners.add(fn);
1726
+ return () => listeners.delete(fn);
1727
+ }
1728
+ var CONTEXT_KEY = "pb_ctx";
1729
+ var UTM_KEYS = [
1730
+ "utm_source",
1731
+ "utm_medium",
1732
+ "utm_campaign",
1733
+ "utm_content",
1734
+ "utm_term"
1735
+ ];
1736
+ var CLICK_IDS = [
1737
+ ["fbclid", "fbclid"],
1738
+ ["gclid", "gclid"],
1739
+ ["gbraid", "gclid"],
1740
+ ["wbraid", "gclid"],
1741
+ ["ttclid", "ttclid"]
1742
+ ];
1743
+ function clip(value, max = 100) {
1744
+ return value.slice(0, max);
1745
+ }
1746
+ function getSessionContext() {
1747
+ if (typeof window === "undefined") return null;
1748
+ try {
1749
+ const stored = window.sessionStorage.getItem(CONTEXT_KEY);
1750
+ if (stored) return JSON.parse(stored);
1751
+ } catch {
1752
+ }
1753
+ const url = new URL(window.location.href);
1754
+ const utm = {};
1755
+ for (const key of UTM_KEYS) {
1756
+ const v = url.searchParams.get(key);
1757
+ if (v) utm[key.slice(4)] = clip(v);
1758
+ }
1759
+ let referrerHost = null;
1760
+ try {
1761
+ const ref = document.referrer ? new URL(document.referrer).hostname : "";
1762
+ referrerHost = ref && ref !== url.hostname ? clip(ref) : null;
1763
+ } catch {
1764
+ referrerHost = null;
1765
+ }
1766
+ const ctx = {
1767
+ utm,
1768
+ referrerHost,
1769
+ landingPath: clip(url.pathname, 200),
1770
+ clickIdType: CLICK_IDS.find(([param]) => url.searchParams.has(param))?.[1] ?? null
1771
+ };
1772
+ try {
1773
+ window.sessionStorage.setItem(CONTEXT_KEY, JSON.stringify(ctx));
1774
+ } catch {
1775
+ }
1776
+ return ctx;
1777
+ }
1778
+ function coarseBrowser(ua) {
1779
+ if (/Edg\//.test(ua)) return "edge";
1780
+ if (/SamsungBrowser/.test(ua)) return "samsung";
1781
+ if (/FBAN|FBAV|Instagram/.test(ua)) return "in-app";
1782
+ if (/Firefox|FxiOS/.test(ua)) return "firefox";
1783
+ if (/Chrome|CriOS/.test(ua)) return "chrome";
1784
+ if (/Safari/.test(ua)) return "safari";
1785
+ return "other";
1786
+ }
1787
+ function coarseOs(ua) {
1788
+ if (/iPhone|iPad|iPod/.test(ua)) return "ios";
1789
+ if (/Android/.test(ua)) return "android";
1790
+ if (/Mac OS X/.test(ua)) return "macos";
1791
+ if (/Windows/.test(ua)) return "windows";
1792
+ if (/Linux|CrOS/.test(ua)) return "linux";
1793
+ return "other";
1794
+ }
1795
+ function viewportBucket(width) {
1796
+ if (width < 480) return "xs";
1797
+ if (width < 768) return "sm";
1798
+ if (width < 1024) return "md";
1799
+ if (width < 1440) return "lg";
1800
+ return "xl";
1801
+ }
1802
+ function exposureContext() {
1803
+ const s2 = config.state;
1804
+ const session = getSessionContext();
1805
+ const ua = typeof navigator !== "undefined" ? navigator.userAgent : "";
1806
+ return {
1807
+ country: s2?.geo?.country ?? null,
1808
+ region: s2?.geo?.region ?? null,
1809
+ market: config.store.market ?? null,
1810
+ locale: config.store.locale ?? null,
1811
+ utm: session?.utm ?? {},
1812
+ referrerHost: session?.referrerHost ?? null,
1813
+ landingPath: session?.landingPath ?? null,
1814
+ clickIdType: session?.clickIdType ?? null,
1815
+ browser: coarseBrowser(ua),
1816
+ os: coarseOs(ua),
1817
+ viewportBucket: viewportBucket(window.innerWidth),
1818
+ isLoggedIn: config.store.isLoggedIn ?? null
1819
+ };
1820
+ }
1821
+ var sentThisPage = /* @__PURE__ */ new Set();
1822
+ function exposureKey(visitorId, testKey) {
1823
+ return `pb_exp:${visitorId}:${testKey}`;
1824
+ }
1825
+ function hasSentExposure(visitorId, testKey) {
903
1826
  const key = exposureKey(visitorId, testKey);
904
1827
  if (sentThisPage.has(key)) return true;
905
1828
  try {
@@ -938,16 +1861,16 @@ function post(url, body2, { beacon = false } = {}) {
938
1861
  });
939
1862
  }
940
1863
  function baseValid(testKey, arm) {
941
- const s = config.state;
942
- if (!s?.enabled || !s.visitorId || !s.shopId) return null;
943
- if (!ID_RE.test(s.shopId) || !ID_RE.test(s.visitorId)) return null;
1864
+ const s2 = config.state;
1865
+ if (!s2?.enabled || !s2.visitorId || !s2.shopId) return null;
1866
+ if (!ID_RE.test(s2.shopId) || !ID_RE.test(s2.visitorId)) return null;
944
1867
  if (!KEY_RE.test(testKey) || !KEY_RE.test(arm)) return null;
945
- return s;
1868
+ return s2;
946
1869
  }
947
- function body(s, testKey, arm, extra) {
1870
+ function body(s2, testKey, arm, extra) {
948
1871
  const json = JSON.stringify({
949
- shopId: s.shopId,
950
- visitorId: s.visitorId,
1872
+ shopId: s2.shopId,
1873
+ visitorId: s2.visitorId,
951
1874
  testKey,
952
1875
  arm,
953
1876
  ...extra,
@@ -957,13 +1880,41 @@ function body(s, testKey, arm, extra) {
957
1880
  });
958
1881
  return json.length <= MAX_BODY_BYTES ? json : null;
959
1882
  }
1883
+ function pushExposureToDataLayer(s2, testKey, arm) {
1884
+ const option = config.dataLayer;
1885
+ if (!option) return;
1886
+ const eventName = option !== true && option.eventName || DEFAULT_DATALAYER_EVENT;
1887
+ try {
1888
+ const dl = window.dataLayer;
1889
+ if (!Array.isArray(dl) && typeof dl?.push !== "function") {
1890
+ return;
1891
+ }
1892
+ const assignment = s2.tests[testKey];
1893
+ if (!assignment?.inTest || assignment.forced) return;
1894
+ const cfg = assignment?.config ?? {};
1895
+ const str2 = (v) => typeof v === "string" && v ? v.slice(0, 100) : null;
1896
+ dl.push({
1897
+ event: eventName,
1898
+ experiment_id: testKey,
1899
+ // The ruleset carries no display names yet; an explicit
1900
+ // `config.experimentName` wins, else the key (never a variant's copy).
1901
+ experiment_name: str2(cfg.experimentName) ?? testKey,
1902
+ variant_id: arm,
1903
+ variant_name: arm,
1904
+ experiment_variant: arm,
1905
+ pb_vid: s2.visitorId
1906
+ });
1907
+ } catch {
1908
+ }
1909
+ }
960
1910
  function sendExposure(testKey, arm) {
961
- const s = baseValid(testKey, arm);
962
- if (!s || !analyticsAllowed()) return;
963
- if (!claimOnce(exposureKey(s.visitorId, testKey), arm)) return;
964
- const json = body(s, testKey, arm, {
965
- device: s.device,
966
- visitorType: s.visitorType,
1911
+ const s2 = baseValid(testKey, arm);
1912
+ if (!s2 || !analyticsAllowed()) return;
1913
+ if (!claimOnce(exposureKey(s2.visitorId, testKey), arm)) return;
1914
+ pushExposureToDataLayer(s2, testKey, arm);
1915
+ const json = body(s2, testKey, arm, {
1916
+ device: s2.device,
1917
+ visitorType: s2.visitorType,
967
1918
  context: exposureContext()
968
1919
  });
969
1920
  if (json) post(config.exposureUrl, json);
@@ -977,15 +1928,15 @@ function sendExposure(testKey, arm) {
977
1928
  });
978
1929
  }
979
1930
  function testsFor(scope) {
980
- const s = config.state;
981
- if (!s?.enabled || !s.visitorId) return [];
1931
+ const s2 = config.state;
1932
+ if (!s2?.enabled || !s2.visitorId) return [];
982
1933
  const out = [];
983
- for (const [key, a] of Object.entries(s.tests)) {
1934
+ for (const [key, a] of Object.entries(s2.tests)) {
984
1935
  if (!a.inTest || a.forced) continue;
985
1936
  if (typeof scope === "object") {
986
1937
  if (scope.testKeys.includes(key)) out.push([key, a.arm]);
987
1938
  } else if (scope === "visitor") {
988
- if (hasSentExposure(s.visitorId, key)) out.push([key, a.arm]);
1939
+ if (hasSentExposure(s2.visitorId, key)) out.push([key, a.arm]);
989
1940
  } else if (
990
1941
  // Tested page type only: the test targets a pathPrefix that matches
991
1942
  // this page, and its slot was on screen during this page view.
@@ -1006,8 +1957,8 @@ function playbookTrack(event, rawProps = {}, scope = "visitor", { oncePerSession
1006
1957
  if (!targets.length) return 0;
1007
1958
  const allowed = analyticsAllowed();
1008
1959
  for (const [testKey, arm] of targets) {
1009
- const s = baseValid(testKey, arm);
1010
- if (!s) continue;
1960
+ const s2 = baseValid(testKey, arm);
1961
+ if (!s2) continue;
1011
1962
  const entry = {
1012
1963
  at: (/* @__PURE__ */ new Date()).toISOString(),
1013
1964
  kind: "event",
@@ -1021,7 +1972,7 @@ function playbookTrack(event, rawProps = {}, scope = "visitor", { oncePerSession
1021
1972
  record(entry);
1022
1973
  continue;
1023
1974
  }
1024
- if (oncePerSession && !claimOnce(`pb_evt:${s.visitorId}:${testKey}:${oncePerSession}`, arm)) {
1975
+ if (oncePerSession && !claimOnce(`pb_evt:${s2.visitorId}:${testKey}:${oncePerSession}`, arm)) {
1025
1976
  continue;
1026
1977
  }
1027
1978
  let wire = {
@@ -1037,7 +1988,7 @@ function playbookTrack(event, rawProps = {}, scope = "visitor", { oncePerSession
1037
1988
  continue;
1038
1989
  }
1039
1990
  const json = body(
1040
- s,
1991
+ s2,
1041
1992
  testKey,
1042
1993
  arm,
1043
1994
  Object.keys(wire.props).length ? wire : { event: wire.event }
@@ -1056,7 +2007,8 @@ var PlaybookContext = createContext({
1056
2007
  pathname: "/",
1057
2008
  exposureUrl: DEFAULT_EXPOSURE_URL,
1058
2009
  eventUrl: DEFAULT_EVENT_URL,
1059
- consent: "pending"
2010
+ consent: "pending",
2011
+ previewIgnoresTargeting: false
1060
2012
  });
1061
2013
  function usePlaybookConsent() {
1062
2014
  return useContext(PlaybookContext).consent;
@@ -1075,10 +2027,13 @@ var CONTROL = {
1075
2027
  config: {}
1076
2028
  };
1077
2029
  function usePlaybookVariant(testKey, { eligible = true } = {}) {
1078
- const { state, pathname } = useContext(PlaybookContext);
2030
+ const { state, pathname, previewIgnoresTargeting } = useContext(PlaybookContext);
1079
2031
  const a = state?.enabled ? state.tests[testKey] : void 0;
1080
2032
  return useMemo(() => {
1081
2033
  if (!a) return CONTROL;
2034
+ if (a.forced && previewIgnoresTargeting) {
2035
+ return { arm: a.arm, inTest: false, forced: true, config: a.config };
2036
+ }
1082
2037
  if (!eligible || !matchesPathPrefix(pathname, a.pathPrefix)) {
1083
2038
  return { ...CONTROL, config: a.config };
1084
2039
  }
@@ -1086,7 +2041,7 @@ function usePlaybookVariant(testKey, { eligible = true } = {}) {
1086
2041
  return { arm: a.arm, inTest: false, forced: true, config: a.config };
1087
2042
  }
1088
2043
  return { arm: a.arm, inTest: a.inTest, forced: false, config: a.config };
1089
- }, [a, eligible, pathname]);
2044
+ }, [a, eligible, pathname, previewIgnoresTargeting]);
1090
2045
  }
1091
2046
  function usePlaybookInteraction(testKey, variant) {
1092
2047
  return useCallback(
@@ -1141,90 +2096,208 @@ function usePreviewParamRedirect(location) {
1141
2096
  if (params.get("pb_preview") === "off") return null;
1142
2097
  params.set("pb_preview", token);
1143
2098
  return `${location.pathname}?${params.toString()}${location.hash}`;
1144
- }
1145
-
1146
- // src/visitor-sync.ts
1147
- function writeCookie(value, days) {
2099
+ }
2100
+ var FLAG = "pb_debug";
2101
+ function readFlag() {
1148
2102
  try {
1149
- const expires = new Date(Date.now() + days * 864e5).toUTCString();
1150
- const secure = window.location.protocol === "https:" ? ";Secure" : "";
1151
- document.cookie = `${VISITOR_COOKIE}=${value};expires=${expires};path=/;SameSite=Lax${secure}`;
2103
+ return window.sessionStorage.getItem(FLAG) === "1";
1152
2104
  } catch {
2105
+ return false;
1153
2106
  }
1154
2107
  }
1155
- function readCookie() {
2108
+ function writeFlag(on) {
1156
2109
  try {
1157
- const parts = `; ${document.cookie}`.split(`; ${VISITOR_COOKIE}=`);
1158
- return parts.length === 2 ? parts.pop()?.split(";").shift() ?? null : null;
2110
+ window.sessionStorage.setItem(FLAG, on ? "1" : "0");
1159
2111
  } catch {
1160
- return null;
1161
2112
  }
1162
2113
  }
1163
- function syncVisitorId(visitorId, consent) {
1164
- try {
1165
- window.sessionStorage.setItem(VISITOR_COOKIE, visitorId);
1166
- } catch {
2114
+ var SERVER_REASONS = {
2115
+ "not-running": "not running",
2116
+ "no-visitor": "no visitor id",
2117
+ "targeting-device": "targeting: device",
2118
+ "targeting-visitor-type": "targeting: new vs returning",
2119
+ namespace: "out of namespace",
2120
+ "hash-error": "hash error",
2121
+ coverage: "out of coverage",
2122
+ winner: "completed: winner served",
2123
+ preview: "forced: preview link",
2124
+ "preview-isolated": "another test is being previewed"
2125
+ };
2126
+ function whyNotInTest(key, a, pathname, implementedTests, explain) {
2127
+ if (implementedTests && !implementedTests.has(key)) {
2128
+ return "no code on this storefront";
1167
2129
  }
1168
- if (consent === "granted" || consent === "absent") {
1169
- if (readCookie() !== visitorId) writeCookie(visitorId, 365);
1170
- } else if (readCookie() !== null) {
1171
- writeCookie("", -1);
2130
+ if (explain) {
2131
+ try {
2132
+ const custom = explain(key, a, pathname);
2133
+ if (typeof custom === "string" && custom) return custom;
2134
+ } catch {
2135
+ }
1172
2136
  }
2137
+ if (a.forced) return SERVER_REASONS[a.reason] ?? "forced";
2138
+ if (!a.inTest) {
2139
+ if (a.reason === "not-running") return a.status;
2140
+ return SERVER_REASONS[a.reason] ?? a.reason;
2141
+ }
2142
+ if (!matchesPathPrefix(pathname, a.pathPrefix)) return "targeting: path";
2143
+ return null;
1173
2144
  }
1174
- function visitorSeedScript(visitorId) {
1175
- return `try{sessionStorage.setItem(${JSON.stringify(VISITOR_COOKIE)},${JSON.stringify(visitorId)})}catch(e){}`;
2145
+ function debugPanelAllowed(state, hostname, allowed) {
2146
+ if (allowed !== void 0) return allowed;
2147
+ return isPreviewHost(hostname) || !!state?.previewToken;
2148
+ }
2149
+ var s = {
2150
+ panel: {
2151
+ position: "fixed",
2152
+ bottom: 16,
2153
+ left: 16,
2154
+ zIndex: 2147483e3,
2155
+ maxHeight: "70vh",
2156
+ width: "min(380px, calc(100vw - 2rem))",
2157
+ overflowY: "auto",
2158
+ borderRadius: 12,
2159
+ background: "#fff",
2160
+ color: "#111",
2161
+ padding: 12,
2162
+ font: "12px/1.45 ui-sans-serif, system-ui, -apple-system, sans-serif",
2163
+ boxShadow: "0 8px 30px rgba(0,0,0,0.18)"
2164
+ },
2165
+ row: { display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8, marginBottom: 8 },
2166
+ title: { fontWeight: 600, margin: 0 },
2167
+ close: { width: 24, height: 24, border: 0, borderRadius: 999, background: "#f2f2f2", cursor: "pointer", fontSize: 14, lineHeight: 1 },
2168
+ card: { background: "#f6f6f6", borderRadius: 8, padding: 8, marginBottom: 8 },
2169
+ muted: { color: "#666", margin: 0 },
2170
+ p: { margin: 0 },
2171
+ grid: { display: "grid", gridTemplateColumns: "auto 1fr", columnGap: 12, rowGap: 4, margin: 0 },
2172
+ dd: { margin: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" },
2173
+ btn: { border: 0, borderRadius: 4, background: "#fff", padding: "2px 6px", cursor: "pointer", fontWeight: 500 },
2174
+ list: { listStyle: "none", margin: 0, padding: 0 }
2175
+ };
2176
+ function copyText(text) {
2177
+ if (navigator.clipboard?.writeText) {
2178
+ navigator.clipboard.writeText(text).catch(() => window.prompt("", text));
2179
+ } else {
2180
+ window.prompt("", text);
2181
+ }
1176
2182
  }
1177
- function PlaybookProvider({
2183
+ function PlaybookDebugPanel({
1178
2184
  state,
1179
- pathname,
1180
- exposureUrl = DEFAULT_EXPOSURE_URL,
1181
- eventUrl = DEFAULT_EVENT_URL,
1182
- supportedEvents = DEFAULT_SUPPORTED_EVENTS,
1183
- storeContext,
1184
- children
2185
+ location,
2186
+ allowed,
2187
+ implementedTests,
2188
+ explain
1185
2189
  }) {
1186
- const [consent, setConsent] = useState("pending");
1187
- const consentRequired = !!state?.consentRequired;
1188
- useEffect(() => {
1189
- if (consentRequired) declareConsentRequired();
1190
- let live = true;
1191
- const update = () => live && setConsent(getConsentState());
1192
- waitForConsentAPI().then(update);
1193
- const unsubscribe = onConsentChange(update);
1194
- return () => {
1195
- live = false;
1196
- unsubscribe();
1197
- };
1198
- }, [consentRequired]);
1199
- const visitorId = state?.enabled ? state.visitorId : null;
1200
- useEffect(() => {
1201
- if (visitorId) syncVisitorId(visitorId, consent);
1202
- }, [visitorId, consent]);
1203
- if (typeof window !== "undefined") {
1204
- configureTracker({
1205
- state: state ?? null,
1206
- consent,
1207
- pathname,
1208
- exposureUrl,
1209
- eventUrl,
1210
- supportedEvents: new Set(supportedEvents),
1211
- store: storeContext ?? {}
1212
- });
1213
- }
1214
- const value = useMemo(
1215
- () => ({ state: state ?? null, pathname, exposureUrl, eventUrl, consent }),
1216
- [state, pathname, exposureUrl, eventUrl, consent]
2190
+ const { pathname, search = "" } = location;
2191
+ const param = new URLSearchParams(search).get(FLAG);
2192
+ const [stored, setStored] = useState(readFlag);
2193
+ const [copied, setCopied] = useState(false);
2194
+ const consent = usePlaybookConsent();
2195
+ const tracked = useSyncExternalStore(
2196
+ subscribeTrackedLog,
2197
+ getTrackedLog,
2198
+ getServerTrackedLog
1217
2199
  );
1218
- return /* @__PURE__ */ jsx(PlaybookContext.Provider, { value, children });
1219
- }
1220
- function PlaybookExposure({
1221
- testKey,
1222
- variant,
1223
- enabled,
1224
- children
1225
- }) {
1226
- const ref = usePlaybookExposure(testKey, variant, { enabled });
1227
- return /* @__PURE__ */ jsx(Fragment, { children: children(ref) });
2200
+ const permitted = debugPanelAllowed(state, window.location.hostname, allowed);
2201
+ const open = permitted && (param === "1" ? true : param === "0" ? false : stored);
2202
+ useEffect(() => {
2203
+ if (permitted && (param === "1" || param === "0")) writeFlag(param === "1");
2204
+ }, [param, permitted]);
2205
+ if (!open) return null;
2206
+ const close = () => {
2207
+ writeFlag(false);
2208
+ setStored(false);
2209
+ if (param === "1") {
2210
+ try {
2211
+ const url = new URL(window.location.href);
2212
+ url.searchParams.set(FLAG, "0");
2213
+ window.history.replaceState(window.history.state, "", url);
2214
+ } catch {
2215
+ }
2216
+ }
2217
+ };
2218
+ const implemented = implementedTests ? new Set(implementedTests) : void 0;
2219
+ const tests = Object.entries(state?.tests ?? {});
2220
+ const vid = state?.visitorId;
2221
+ return /* @__PURE__ */ jsxs("aside", { "aria-label": "Playbook tests debug", style: s.panel, children: [
2222
+ /* @__PURE__ */ jsxs("div", { style: s.row, children: [
2223
+ /* @__PURE__ */ jsx("p", { style: s.title, children: "Playbook tests" }),
2224
+ /* @__PURE__ */ jsx("button", { type: "button", "aria-label": "Close debug panel", style: s.close, onClick: close, children: "\xD7" })
2225
+ ] }),
2226
+ !state?.enabled ? /* @__PURE__ */ jsx("p", { style: s.p, children: "Disabled: no shop id, or PLAYBOOK_TESTS_DISABLED is on." }) : /* @__PURE__ */ jsxs(Fragment, { children: [
2227
+ /* @__PURE__ */ jsxs("dl", { style: { ...s.grid, ...s.card }, children: [
2228
+ /* @__PURE__ */ jsx("dt", { style: s.muted, children: "Visitor" }),
2229
+ /* @__PURE__ */ jsxs("dd", { style: { ...s.dd, display: "flex", gap: 8, alignItems: "center" }, children: [
2230
+ /* @__PURE__ */ jsx("code", { style: { overflow: "hidden", textOverflow: "ellipsis" }, children: vid ?? "none (preview)" }),
2231
+ vid && /* @__PURE__ */ jsx(
2232
+ "button",
2233
+ {
2234
+ type: "button",
2235
+ style: s.btn,
2236
+ onClick: () => {
2237
+ copyText(vid);
2238
+ setCopied(true);
2239
+ setTimeout(() => setCopied(false), 1500);
2240
+ },
2241
+ children: copied ? "Copied" : "Copy"
2242
+ }
2243
+ )
2244
+ ] }),
2245
+ /* @__PURE__ */ jsx("dt", { style: s.muted, children: "Type" }),
2246
+ /* @__PURE__ */ jsxs("dd", { style: s.dd, children: [
2247
+ state.visitorType,
2248
+ " \xB7 ",
2249
+ state.device
2250
+ ] }),
2251
+ /* @__PURE__ */ jsx("dt", { style: s.muted, children: "Analytics" }),
2252
+ /* @__PURE__ */ jsxs("dd", { style: s.dd, children: [
2253
+ consent === "absent" ? "API absent" : consent,
2254
+ " (server: ",
2255
+ state.serverConsent,
2256
+ ")",
2257
+ consent === "denied" || consent === "pending" ? " \xB7 no beacons" : ""
2258
+ ] }),
2259
+ /* @__PURE__ */ jsx("dt", { style: s.muted, children: "Ruleset" }),
2260
+ /* @__PURE__ */ jsx("dd", { style: s.dd, children: state.rulesetSource === "cold-fallback" ? "cold fallback (everyone gets control)" : `${state.rulesetVersion ?? "none"} \xB7 ${state.rulesetSource}` })
2261
+ ] }),
2262
+ !tests.length && /* @__PURE__ */ jsx("p", { style: s.p, children: "No tests in the ruleset." }),
2263
+ /* @__PURE__ */ jsx("ul", { style: s.list, children: tests.map(([key, a]) => {
2264
+ const why = whyNotInTest(key, a, pathname, implemented, explain);
2265
+ const exposed = !!vid && hasSentExposure(vid, key);
2266
+ return /* @__PURE__ */ jsxs("li", { style: s.card, children: [
2267
+ /* @__PURE__ */ jsx("p", { style: { ...s.p, fontWeight: 600 }, children: key }),
2268
+ /* @__PURE__ */ jsxs("p", { style: s.p, children: [
2269
+ a.status,
2270
+ " \xB7 arm ",
2271
+ /* @__PURE__ */ jsx("strong", { children: a.arm }),
2272
+ " \xB7 inTest ",
2273
+ String(a.inTest && !why),
2274
+ " \xB7 forced",
2275
+ " ",
2276
+ String(a.forced)
2277
+ ] }),
2278
+ why && /* @__PURE__ */ jsxs("p", { style: s.muted, children: [
2279
+ "Why: ",
2280
+ why
2281
+ ] }),
2282
+ /* @__PURE__ */ jsxs("p", { style: s.muted, children: [
2283
+ "Exposure this session: ",
2284
+ exposed ? "sent" : "not sent"
2285
+ ] })
2286
+ ] }, key);
2287
+ }) }),
2288
+ /* @__PURE__ */ jsx("p", { style: { ...s.p, fontWeight: 600, marginTop: 4 }, children: "Last beacons" }),
2289
+ tracked.length ? /* @__PURE__ */ jsx("ol", { style: s.list, children: tracked.slice(0, 8).map((t) => /* @__PURE__ */ jsxs("li", { style: { ...s.dd, display: "flex", gap: 8 }, children: [
2290
+ /* @__PURE__ */ jsx("span", { style: t.status === "sent" ? void 0 : s.muted, children: t.status }),
2291
+ /* @__PURE__ */ jsx("span", { style: { fontWeight: 500 }, children: t.name }),
2292
+ /* @__PURE__ */ jsxs("span", { style: { ...s.muted, overflow: "hidden", textOverflow: "ellipsis" }, children: [
2293
+ t.testKey,
2294
+ ":",
2295
+ t.arm,
2296
+ t.props && Object.keys(t.props).length ? ` ${JSON.stringify(t.props)}` : ""
2297
+ ] })
2298
+ ] }, `${t.at}-${t.name}-${t.testKey}`)) }) : /* @__PURE__ */ jsx("p", { style: s.muted, children: "None yet this page." })
2299
+ ] })
2300
+ ] });
1228
2301
  }
1229
2302
  var MILESTONES = [25, 50, 75, 100];
1230
2303
  var IDLE_MS = 5e3;
@@ -1296,6 +2369,492 @@ function usePageEngagement(pathname, enabled) {
1296
2369
  }, [pathname, enabled]);
1297
2370
  }
1298
2371
 
2372
+ // src/consent-adapters.ts
2373
+ function consentFromAnalytics(value) {
2374
+ if (value === true || value === "granted" || value === "yes") {
2375
+ return "granted";
2376
+ }
2377
+ if (value === false || value === "denied" || value === "no") return "denied";
2378
+ return "pending";
2379
+ }
2380
+ var shopifyCustomerPrivacyConsent = {
2381
+ id: "shopify-customer-privacy",
2382
+ read() {
2383
+ if (typeof window === "undefined") return "pending";
2384
+ try {
2385
+ return getConsentState();
2386
+ } catch {
2387
+ return "pending";
2388
+ }
2389
+ },
2390
+ subscribe(onChange) {
2391
+ if (typeof window === "undefined") return () => {
2392
+ };
2393
+ let live = true;
2394
+ const notify = () => {
2395
+ if (live) onChange();
2396
+ };
2397
+ waitForConsentAPI().then(notify, notify);
2398
+ const offLoaded = onConsentLoaded(notify);
2399
+ const offChange = onConsentChange(notify);
2400
+ return () => {
2401
+ live = false;
2402
+ offLoaded();
2403
+ offChange();
2404
+ };
2405
+ }
2406
+ };
2407
+ var TRUEVAULT_CONSENT_COOKIE = "polaris_consent_settings";
2408
+ var TRUEVAULT_CONSENT_EVENT = "consentChanged";
2409
+ var POLL_INTERVAL_MS = 500;
2410
+ var POLL_CHECKS = 20;
2411
+ function trueVaultDecision(raw, gpc, { whenMissing = "pending", gpc: gpcMode = "follow-banner" } = {}) {
2412
+ if (gpc && gpcMode === "deny") return "denied";
2413
+ if (raw === null || raw === void 0 || raw === "") return whenMissing;
2414
+ let data = null;
2415
+ for (const candidate of [raw, safeDecode(raw)]) {
2416
+ if (candidate === null) continue;
2417
+ try {
2418
+ data = JSON.parse(candidate);
2419
+ break;
2420
+ } catch {
2421
+ }
2422
+ }
2423
+ const permitted = data?.analyticsPermitted;
2424
+ if (permitted === true) return "granted";
2425
+ if (permitted === false) return "denied";
2426
+ return "pending";
2427
+ }
2428
+ function safeDecode(raw) {
2429
+ try {
2430
+ return decodeURIComponent(raw);
2431
+ } catch {
2432
+ return null;
2433
+ }
2434
+ }
2435
+ function readDocumentCookie(name) {
2436
+ try {
2437
+ const match = document.cookie.match(
2438
+ new RegExp(`(?:^|; )${name}=([^;]*)`)
2439
+ );
2440
+ return match ? match[1] : null;
2441
+ } catch {
2442
+ return null;
2443
+ }
2444
+ }
2445
+ function clientGpc() {
2446
+ try {
2447
+ return navigator.globalPrivacyControl === true;
2448
+ } catch {
2449
+ return false;
2450
+ }
2451
+ }
2452
+ function createTrueVaultConsent(options = {}) {
2453
+ return {
2454
+ id: "truevault",
2455
+ fromRequest(request) {
2456
+ try {
2457
+ const cookies = parseCookies(request.headers.get("cookie"));
2458
+ const gpc = request.headers.get("sec-gpc") === "1";
2459
+ return trueVaultDecision(
2460
+ cookies[TRUEVAULT_CONSENT_COOKIE],
2461
+ gpc,
2462
+ options
2463
+ );
2464
+ } catch {
2465
+ return "pending";
2466
+ }
2467
+ },
2468
+ read() {
2469
+ if (typeof document === "undefined") return "pending";
2470
+ return trueVaultDecision(
2471
+ readDocumentCookie(TRUEVAULT_CONSENT_COOKIE),
2472
+ clientGpc(),
2473
+ options
2474
+ );
2475
+ },
2476
+ subscribe(onChange) {
2477
+ if (typeof window === "undefined") return () => {
2478
+ };
2479
+ const handler = () => setTimeout(onChange, 0);
2480
+ const onVisible = () => {
2481
+ if (document.visibilityState === "visible") onChange();
2482
+ };
2483
+ window.addEventListener(TRUEVAULT_CONSENT_EVENT, handler);
2484
+ document.addEventListener("visibilitychange", onVisible);
2485
+ let poll = null;
2486
+ if (readDocumentCookie(TRUEVAULT_CONSENT_COOKIE) === null) {
2487
+ let checks = 0;
2488
+ poll = setInterval(() => {
2489
+ checks += 1;
2490
+ const present = readDocumentCookie(TRUEVAULT_CONSENT_COOKIE) !== null;
2491
+ if (present || checks >= POLL_CHECKS) {
2492
+ if (poll) clearInterval(poll);
2493
+ poll = null;
2494
+ if (present) onChange();
2495
+ }
2496
+ }, POLL_INTERVAL_MS);
2497
+ }
2498
+ return () => {
2499
+ window.removeEventListener(TRUEVAULT_CONSENT_EVENT, handler);
2500
+ document.removeEventListener("visibilitychange", onVisible);
2501
+ if (poll) clearInterval(poll);
2502
+ };
2503
+ }
2504
+ };
2505
+ }
2506
+ var truevaultConsent = createTrueVaultConsent();
2507
+ function PlaybookProvider({
2508
+ state,
2509
+ pathname,
2510
+ exposureUrl = DEFAULT_EXPOSURE_URL,
2511
+ eventUrl = DEFAULT_EVENT_URL,
2512
+ supportedEvents = DEFAULT_SUPPORTED_EVENTS,
2513
+ storeContext,
2514
+ consent: consentAdapter,
2515
+ dataLayer = false,
2516
+ previewIgnoresTargeting = false,
2517
+ children
2518
+ }) {
2519
+ const [consent, setConsent] = useState("pending");
2520
+ const consentRequired = !!state?.consentRequired;
2521
+ useEffect(() => {
2522
+ let live = true;
2523
+ const source = consentAdapter ?? shopifyCustomerPrivacyConsent;
2524
+ if (!consentAdapter && consentRequired) declareConsentRequired();
2525
+ const update = () => {
2526
+ if (!live) return;
2527
+ try {
2528
+ setConsent(source.read());
2529
+ } catch {
2530
+ setConsent("pending");
2531
+ }
2532
+ };
2533
+ update();
2534
+ let unsubscribe = () => {
2535
+ };
2536
+ try {
2537
+ unsubscribe = source.subscribe(update);
2538
+ } catch {
2539
+ }
2540
+ return () => {
2541
+ live = false;
2542
+ unsubscribe();
2543
+ };
2544
+ }, [consentRequired, consentAdapter]);
2545
+ const visitorId = state?.enabled ? state.visitorId : null;
2546
+ useEffect(() => {
2547
+ if (visitorId) syncVisitorId(visitorId, consent);
2548
+ }, [visitorId, consent]);
2549
+ if (typeof window !== "undefined") {
2550
+ try {
2551
+ configureTracker({
2552
+ state: state ?? null,
2553
+ consent,
2554
+ pathname,
2555
+ exposureUrl,
2556
+ eventUrl,
2557
+ supportedEvents: new Set(supportedEvents),
2558
+ store: storeContext ?? {},
2559
+ dataLayer
2560
+ });
2561
+ } catch {
2562
+ }
2563
+ }
2564
+ const value = useMemo(
2565
+ () => ({
2566
+ state: state ?? null,
2567
+ pathname,
2568
+ exposureUrl,
2569
+ eventUrl,
2570
+ consent,
2571
+ previewIgnoresTargeting
2572
+ }),
2573
+ [state, pathname, exposureUrl, eventUrl, consent, previewIgnoresTargeting]
2574
+ );
2575
+ return /* @__PURE__ */ jsx(PlaybookContext.Provider, { value, children });
2576
+ }
2577
+ function PlaybookExposure({
2578
+ testKey,
2579
+ variant,
2580
+ enabled,
2581
+ children
2582
+ }) {
2583
+ const ref = usePlaybookExposure(testKey, variant, { enabled });
2584
+ return /* @__PURE__ */ jsx(Fragment, { children: children(ref) });
2585
+ }
2586
+ var AA_SITEWIDE_TEST = "aa-sitewide";
2587
+ var noopSubscribe = () => () => {
2588
+ };
2589
+ function useHydrated() {
2590
+ return useSyncExternalStore(
2591
+ noopSubscribe,
2592
+ () => true,
2593
+ () => false
2594
+ );
2595
+ }
2596
+ function visitorInRunningTest(state) {
2597
+ if (!state?.enabled || !state.visitorId) return false;
2598
+ return Object.values(state.tests).some(
2599
+ (a) => a.inTest && !a.forced && a.status === "running"
2600
+ );
2601
+ }
2602
+ function CartAttributeSync({
2603
+ state,
2604
+ cart,
2605
+ onEvent
2606
+ }) {
2607
+ const allowed = useAnalyticsAllowed();
2608
+ const cartRef = useRef(cart);
2609
+ cartRef.current = cart;
2610
+ const onEventRef = useRef(onEvent);
2611
+ onEventRef.current = onEvent;
2612
+ const sync = useMemo(
2613
+ () => createCartAttributeSync({
2614
+ write: (add, current) => {
2615
+ const c = cartRef.current;
2616
+ const writer = c.write ?? createCartAttributeWriter({
2617
+ endpoint: c.endpoint,
2618
+ serverMerges: c.serverMerges
2619
+ });
2620
+ return writer(add, current);
2621
+ },
2622
+ read: () => {
2623
+ const c = cartRef.current;
2624
+ return (c.read ?? createCartAttributeReader({ endpoint: c.endpoint }))();
2625
+ },
2626
+ onEvent: (e) => onEventRef.current?.(e)
2627
+ }),
2628
+ []
2629
+ );
2630
+ useEffect(() => () => sync.dispose(), [sync]);
2631
+ const eligible = allowed && visitorInRunningTest(state);
2632
+ let attrSignature = "";
2633
+ try {
2634
+ attrSignature = JSON.stringify(cart.attributes ?? []);
2635
+ } catch {
2636
+ attrSignature = String(cart.attributes?.length ?? 0);
2637
+ }
2638
+ useEffect(() => {
2639
+ sync.update({
2640
+ cartId: cartRef.current.cartId,
2641
+ attributes: cartRef.current.attributes,
2642
+ status: cartRef.current.status,
2643
+ visitorId: state.visitorId,
2644
+ eligible
2645
+ });
2646
+ }, [sync, cart.cartId, attrSignature, cart.status, state.visitorId, eligible]);
2647
+ return null;
2648
+ }
2649
+ function PreviewParam({
2650
+ location,
2651
+ navigate
2652
+ }) {
2653
+ const target = usePreviewParamRedirect({
2654
+ pathname: location.pathname,
2655
+ search: location.search ?? "",
2656
+ hash: location.hash ?? ""
2657
+ });
2658
+ useEffect(() => {
2659
+ if (!target) return;
2660
+ if (navigate) navigate(target, { replace: true, preventScrollReset: true });
2661
+ else window.location.replace(target);
2662
+ }, [target]);
2663
+ return null;
2664
+ }
2665
+ var SENTINEL_STYLE = {
2666
+ position: "fixed",
2667
+ top: 0,
2668
+ left: 0,
2669
+ width: 1,
2670
+ height: 1,
2671
+ opacity: 0,
2672
+ pointerEvents: "none"
2673
+ };
2674
+ function PlaybookAAExposure({ testKey = AA_SITEWIDE_TEST }) {
2675
+ const variant = usePlaybookVariant(testKey);
2676
+ const ref = usePlaybookExposure(testKey, variant);
2677
+ return /* @__PURE__ */ jsx("span", { ref, "aria-hidden": "true", style: SENTINEL_STYLE });
2678
+ }
2679
+ function Engagement({ pathname, enabled }) {
2680
+ usePageEngagement(pathname, enabled);
2681
+ return null;
2682
+ }
2683
+ function PlaybookRoot({
2684
+ state,
2685
+ location,
2686
+ navigate,
2687
+ cart,
2688
+ consent,
2689
+ storeContext,
2690
+ editorPreview = false,
2691
+ aaSentinel = true,
2692
+ debug,
2693
+ dataLayer,
2694
+ previewIgnoresTargeting,
2695
+ onCartSyncEvent,
2696
+ exposureUrl,
2697
+ eventUrl,
2698
+ supportedEvents,
2699
+ children
2700
+ }) {
2701
+ const hydrated = useHydrated();
2702
+ const enabled = !!state?.enabled;
2703
+ return /* @__PURE__ */ jsxs(
2704
+ PlaybookProvider,
2705
+ {
2706
+ state,
2707
+ pathname: location.pathname,
2708
+ storeContext,
2709
+ consent,
2710
+ dataLayer,
2711
+ previewIgnoresTargeting,
2712
+ exposureUrl,
2713
+ eventUrl,
2714
+ supportedEvents,
2715
+ children: [
2716
+ children,
2717
+ hydrated && /* @__PURE__ */ jsxs(Fragment, { children: [
2718
+ /* @__PURE__ */ jsx(PlaybookBoundary, { name: "engagement", children: /* @__PURE__ */ jsx(Engagement, { pathname: location.pathname, enabled }) }),
2719
+ enabled && state?.visitorId && cart && !editorPreview && /* @__PURE__ */ jsx(PlaybookBoundary, { name: "cart attribute", children: /* @__PURE__ */ jsx(
2720
+ CartAttributeSync,
2721
+ {
2722
+ state,
2723
+ cart,
2724
+ onEvent: onCartSyncEvent
2725
+ }
2726
+ ) }),
2727
+ state?.previewToken && /* @__PURE__ */ jsx(PlaybookBoundary, { name: "preview param", children: /* @__PURE__ */ jsx(PreviewParam, { location, navigate }) }),
2728
+ enabled && aaSentinel && !editorPreview && /* @__PURE__ */ jsx(PlaybookBoundary, { name: "aa sentinel", children: /* @__PURE__ */ jsx(PlaybookAAExposure, {}) }),
2729
+ /* @__PURE__ */ jsx(PlaybookBoundary, { name: "debug panel", children: /* @__PURE__ */ jsx(
2730
+ PlaybookDebugPanel,
2731
+ {
2732
+ state,
2733
+ location,
2734
+ allowed: debug?.allowed,
2735
+ implementedTests: debug?.implementedTests,
2736
+ explain: debug?.explain
2737
+ }
2738
+ ) })
2739
+ ] })
2740
+ ]
2741
+ }
2742
+ );
2743
+ }
2744
+
2745
+ // src/proxy.ts
2746
+ var FORWARDED_REQUEST_HEADERS = [
2747
+ "accept",
2748
+ "accept-language",
2749
+ "content-type",
2750
+ "referer",
2751
+ "user-agent",
2752
+ "x-forwarded-for"
2753
+ ];
2754
+ var FORWARDED_RESPONSE_HEADERS = ["content-type", "cache-control", "etag"];
2755
+ var CORS_HEADERS = {
2756
+ "access-control-allow-origin": "*",
2757
+ "access-control-allow-methods": "GET, POST, OPTIONS",
2758
+ "access-control-allow-headers": "Content-Type"
2759
+ };
2760
+ var ALLOWED_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "POST", "OPTIONS"]);
2761
+ var NULL_BODY_STATUSES = /* @__PURE__ */ new Set([101, 204, 205, 304]);
2762
+ var PROXY_PREFIX = "/apps/playbook/";
2763
+ var PROXY_TIMEOUT_MS = 5e3;
2764
+ var PROXY_MAX_BODY_BYTES = 64 * 1024;
2765
+ function playbookBackendUrl(requestUrl, platformUrl) {
2766
+ const url = new URL(requestUrl);
2767
+ const idx = url.pathname.indexOf(PROXY_PREFIX);
2768
+ const subPath = idx !== -1 ? url.pathname.slice(idx + PROXY_PREFIX.length) : "";
2769
+ const backendPath = subPath.startsWith("api/") ? `/${subPath}` : `/api/${subPath}`;
2770
+ const backend = new URL(backendPath, platformUrl);
2771
+ backend.search = url.search;
2772
+ return backend.toString();
2773
+ }
2774
+ function plain(status, text) {
2775
+ return new Response(text, {
2776
+ status,
2777
+ headers: {
2778
+ ...CORS_HEADERS,
2779
+ "content-type": "text/plain; charset=utf-8",
2780
+ "cache-control": "no-store"
2781
+ }
2782
+ });
2783
+ }
2784
+ function resolvePlatformUrl(option, args) {
2785
+ const fromOption = typeof option === "function" ? option(args) : option;
2786
+ if (fromOption) return fromOption;
2787
+ const env = args.context?.env;
2788
+ const fromEnv = env?.PLAYBOOK_PLATFORM_URL;
2789
+ return typeof fromEnv === "string" && fromEnv ? fromEnv : DEFAULT_PLATFORM_URL;
2790
+ }
2791
+ async function readCappedBody(request, max) {
2792
+ const declared = Number(request.headers.get("content-length"));
2793
+ if (Number.isFinite(declared) && declared > max) return null;
2794
+ const text = await request.text();
2795
+ return new TextEncoder().encode(text).length > max ? null : text;
2796
+ }
2797
+ function createPlaybookProxyHandler({
2798
+ platformUrl,
2799
+ timeoutMs = PROXY_TIMEOUT_MS,
2800
+ maxBodyBytes = PROXY_MAX_BODY_BYTES,
2801
+ fetchImpl
2802
+ } = {}) {
2803
+ const proxy = async (args) => {
2804
+ const { request } = args;
2805
+ const method = request.method.toUpperCase();
2806
+ if (method === "OPTIONS") {
2807
+ return new Response(null, {
2808
+ status: 204,
2809
+ headers: { ...CORS_HEADERS, "access-control-max-age": "86400" }
2810
+ });
2811
+ }
2812
+ if (!ALLOWED_METHODS.has(method)) return plain(405, "Method Not Allowed");
2813
+ const controller = new AbortController();
2814
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
2815
+ try {
2816
+ const backendUrl = playbookBackendUrl(
2817
+ request.url,
2818
+ resolvePlatformUrl(platformUrl, args)
2819
+ );
2820
+ const headers = new Headers();
2821
+ for (const name of FORWARDED_REQUEST_HEADERS) {
2822
+ const value = request.headers.get(name);
2823
+ if (value) headers.set(name, value);
2824
+ }
2825
+ headers.set("x-forwarded-host", new URL(request.url).host);
2826
+ const init = { method, headers, signal: controller.signal };
2827
+ if (method !== "GET" && method !== "HEAD") {
2828
+ const body3 = await readCappedBody(request, maxBodyBytes);
2829
+ if (body3 === null) return plain(413, "Payload Too Large");
2830
+ init.body = body3;
2831
+ }
2832
+ const upstream = await (fetchImpl ?? fetch)(backendUrl, init);
2833
+ const responseHeaders = new Headers();
2834
+ for (const name of FORWARDED_RESPONSE_HEADERS) {
2835
+ const value = upstream.headers.get(name);
2836
+ if (value) responseHeaders.set(name, value);
2837
+ }
2838
+ for (const [k, v] of Object.entries(CORS_HEADERS)) responseHeaders.set(k, v);
2839
+ responseHeaders.set("cache-control", "no-store");
2840
+ const nullBody = NULL_BODY_STATUSES.has(upstream.status) || method === "HEAD";
2841
+ const body2 = nullBody ? null : await upstream.arrayBuffer();
2842
+ return new Response(body2, { status: upstream.status, headers: responseHeaders });
2843
+ } catch (error) {
2844
+ const timedOut = controller.signal.aborted;
2845
+ console.warn(
2846
+ "[playbook] proxy",
2847
+ timedOut ? "upstream timeout" : "upstream failed",
2848
+ String(error)
2849
+ );
2850
+ return timedOut ? plain(504, "Gateway Timeout") : plain(502, "Bad Gateway");
2851
+ } finally {
2852
+ clearTimeout(timer);
2853
+ }
2854
+ };
2855
+ return { loader: proxy, action: proxy };
2856
+ }
2857
+
1299
2858
  // src/cart-events.ts
1300
2859
  var nextSource = null;
1301
2860
  function setNextAddSource(source) {
@@ -1310,6 +2869,39 @@ function numericId(gid) {
1310
2869
  const id = gid?.split("/").pop();
1311
2870
  return id && /^\d{1,30}$/.test(id) ? id : null;
1312
2871
  }
2872
+ function parseJson(value) {
2873
+ if (typeof value !== "string" || !value) return null;
2874
+ try {
2875
+ return JSON.parse(value);
2876
+ } catch {
2877
+ return null;
2878
+ }
2879
+ }
2880
+ function addedLinesFrom(input) {
2881
+ if (!input) return [];
2882
+ if (Array.isArray(input)) return input;
2883
+ if (typeof FormData === "undefined" || !(input instanceof FormData)) return [];
2884
+ const formInput = parseJson(input.get("cartFormInput"));
2885
+ if (formInput?.inputs?.lines) return formInput.inputs.lines;
2886
+ const action = input.get("action");
2887
+ const raw = action === "Create" ? parseJson(input.get("cart"))?.lines : parseJson(input.get("lines"));
2888
+ return Array.isArray(raw) ? raw : [];
2889
+ }
2890
+ function trackAddToCart(source, {
2891
+ lines,
2892
+ cart
2893
+ }) {
2894
+ try {
2895
+ const conn = cart?.lines;
2896
+ const snapshots = Array.isArray(conn) ? conn : conn?.nodes ?? conn?.edges?.map((e) => e.node) ?? [];
2897
+ trackAddToCartLines(
2898
+ addedLinesFrom(lines),
2899
+ snapshots,
2900
+ source ?? takeAddSource()
2901
+ );
2902
+ } catch {
2903
+ }
2904
+ }
1313
2905
  function trackAddToCartLines(lines, cartLines, source) {
1314
2906
  try {
1315
2907
  for (const line of lines) {
@@ -1334,15 +2926,4 @@ function trackAddToCartLines(lines, cartLines, source) {
1334
2926
  }
1335
2927
  }
1336
2928
 
1337
- // src/cart.ts
1338
- var CART_VISITOR_ATTRIBUTE = "_pb_vid";
1339
- function playbookCartAttribute(visitorId) {
1340
- return { key: CART_VISITOR_ATTRIBUTE, value: visitorId };
1341
- }
1342
- function cartHasPlaybookAttribute(attributes, visitorId) {
1343
- return !!attributes?.some(
1344
- (a) => a.key === CART_VISITOR_ATTRIBUTE && a.value === visitorId
1345
- );
1346
- }
1347
-
1348
- 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 };
2929
+ export { AA_SITEWIDE_TEST, CART_SYNC_IDLE_MS, CART_VISITOR_ATTRIBUTE, CLOAK_MAX_MS, CLOAK_STYLE_ID, CONSENT_LOADED_EVENTS, CONTROL_ARM, DEFAULT_DATALAYER_EVENT, DEFAULT_EVENT_URL, DEFAULT_EXPERIENCE_SDK_URL, DEFAULT_EXPOSURE_URL, DEFAULT_PLATFORM_URL, DEFAULT_PROXY_ENDPOINT, DEFAULT_SDK_URL, DEFAULT_SUPPORTED_EVENTS, EXPERIENCE_SDK_SCRIPT_ID, EXPERIENCE_VISITOR_CART_ATTRIBUTE, EXPOSURE_CART_ATTRIBUTE, EXPOSURE_COOKIE, LEGACY_VISITOR_COOKIE, MAX_WRITES_PER_CART, PlaybookAAExposure, PlaybookBoundary, PlaybookCloakHead, PlaybookDebugPanel, PlaybookExposure, PlaybookHead, PlaybookProvider, PlaybookRoot, SESSION_VISITOR_COOKIE, STANDARD_EVENTS, TRUEVAULT_CONSENT_COOKIE, VISITOR_COOKIE, addedLinesFrom, analyticsConsentFromCookie, assignTest, buildHeadSnippet, cartHasPlaybookAttribute, chooseVariation, consentFromAnalytics, createCartAttributeReader, createCartAttributeSync, createCartAttributeWriter, createPlaybook, createPlaybookContext, createPlaybookProxyHandler, createTrueVaultConsent, debugPanelAllowed, declareConsentRequired, detectDevice, detectGeo, experienceVisitorIdFromCookies, getBucketRanges, getConsentState, getEqualWeights, getServerTrackedLog, getSessionContext, getTargetedPages, getTrackedLog, hasPlaybookParams, hasSentExposure, hash, inNamespace, isAnalyticsConsentGranted, isKillSwitchOn, isPreviewHost, manifestUrl, matchTargetedPage, matchesPathPrefix, mergeAttributes, normalizeExposureList, onConsentChange, onConsentLoaded, playbookBackendUrl, playbookCartAttribute, playbookHeadSnippet, playbookHeadSnippetHtml, playbookTrack, prefetchRuleset, reconcileExperienceCartAttributes, reconcilePlaybookCartAttribute, revealScript, sanitizeManifestPages, sanitizeRuleset, setNextAddSource, shopifyCustomerPrivacyConsent, subscribeTrackedLog, syncVisitorId, takeAddSource, targetPageKey, trackAddToCart, trackAddToCartLines, trueVaultDecision, truevaultConsent, useAnalyticsAllowed, usePageEngagement, usePlaybookConsent, usePlaybookExposure, usePlaybookInteraction, usePlaybookState, usePlaybookVariant, usePreviewParamRedirect, visitorInRunningTest, visitorSeedScript, waitForConsentAPI, withPlaybook, withPlaybookCartAttribute };