@heyplaybook/hydrogen 0.6.0 → 0.7.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.d.ts CHANGED
@@ -479,6 +479,114 @@ declare function playbookHeadSnippet(cloak: PlaybookCloakConfig | null | undefin
479
479
  /** The same nodes as an HTML string, for a non-React head. '' when untargeted. */
480
480
  declare function playbookHeadSnippetHtml(cloak: PlaybookCloakConfig | null | undefined, options?: PlaybookHeadSnippetOptions): string;
481
481
 
482
+ interface SsrSnapshotNode {
483
+ id: string;
484
+ html: string;
485
+ css: string;
486
+ mt?: number;
487
+ mb?: number;
488
+ }
489
+ interface SsrSnapshot {
490
+ v: number;
491
+ nodes: SsrSnapshotNode[];
492
+ }
493
+ interface SsrArm {
494
+ id: string;
495
+ w: number;
496
+ c: 0 | 1;
497
+ x: string | null;
498
+ a: {
499
+ s: string;
500
+ p: 'before' | 'after' | 'prepend' | 'append';
501
+ f?: string;
502
+ } | null;
503
+ hide: string[];
504
+ }
505
+ interface SsrExperiment {
506
+ id: string;
507
+ ok: 0 | 1;
508
+ why?: string;
509
+ seed: string;
510
+ hv: number;
511
+ settled: string | null;
512
+ arms: SsrArm[];
513
+ aud?: unknown;
514
+ }
515
+ interface SsrDoc {
516
+ keys: Record<string, number[]>;
517
+ prefixes: Array<[string, number[]]>;
518
+ exps: SsrExperiment[];
519
+ }
520
+ interface SsrPayload {
521
+ doc: SsrDoc;
522
+ snapshots: Record<string, SsrSnapshot>;
523
+ }
524
+ declare function ssrUrl(platformUrl: string, shopDomain: string): string;
525
+ /** The shop's SSR doc, or null when the read isn't healthy (then: cloak only). Never throws. */
526
+ declare function getSsrPayload(args: {
527
+ platformUrl: string;
528
+ shopDomain: string;
529
+ waitUntil?: (p: Promise<unknown>) => void;
530
+ fetchImpl?: typeof fetch;
531
+ }): Promise<SsrPayload | null>;
532
+ /**
533
+ * The arm index for `seed` + `id` over `weights` (coverage 1), or -1. GrowthBook
534
+ * v2: `fnv32a(fnv32a(seed + id) + "") % 10000 / 10000`; weights that don't sum
535
+ * to ~1 are replaced by equal weights. Same as the embed's `pbBucket`.
536
+ */
537
+ declare function bucketIndex(seed: string, id: string, weights: readonly number[]): number;
538
+ interface SsrDecision {
539
+ experimentId: string;
540
+ armId: string;
541
+ experienceId: string | null;
542
+ /** The visitor id the roll used ('' for a prior / settled arm). */
543
+ idSource: 'prior' | 'settled' | 'roll';
544
+ arm: SsrArm;
545
+ snapshot: SsrSnapshot | null;
546
+ page: {
547
+ t: string;
548
+ h: string;
549
+ };
550
+ }
551
+ type SsrOutcome = {
552
+ decision: SsrDecision;
553
+ } | {
554
+ skip: string;
555
+ };
556
+ /**
557
+ * The server's arm for this page, or why it can't decide (→ cloak). Pure.
558
+ * `consent` = the request's analytics consent as the SDK would read it.
559
+ */
560
+ declare function decideSsr(input: {
561
+ payload: SsrPayload;
562
+ pageKey: string;
563
+ cookies: Record<string, string | undefined>;
564
+ consent: 'allowed' | 'denied' | 'unknown';
565
+ /**
566
+ * The id to roll on when the long-lived ids can't be used: the package's own
567
+ * visitor id for this request (`_pb_visitor_id`, or the session-scoped
568
+ * `_pb_session_vid` while consent isn't granted). Stable across page loads,
569
+ * so a visitor without consent keeps one arm, and no new cookie is written.
570
+ */
571
+ fallbackVisitorId?: string | null;
572
+ nowSec?: number;
573
+ }): SsrOutcome;
574
+ /**
575
+ * The host's inner HTML: a Declarative Shadow DOM tree identical in structure
576
+ * to the embed's `build()`, so `ssr-adopt.ts` finds and adopts it. The node
577
+ * markup was sanitized by the platform (ssr-doc.ts uses the import sanitizer);
578
+ * it is the trust boundary for this `innerHTML`, as for the embed's.
579
+ */
580
+ declare function ssrHostInnerHtml(snapshot: SsrSnapshot, page: {
581
+ t: string;
582
+ h: string;
583
+ }): string;
584
+ /** Does this slot serve the decision's anchor? Exact selector + position match. */
585
+ declare function slotMatches(d: SsrDecision, slot: {
586
+ anchor: string;
587
+ position?: string;
588
+ }): boolean;
589
+
482
590
  /** The env keys the kit reads (all optional). */
483
591
  interface PlaybookEnv {
484
592
  PUBLIC_PLAYBOOK_SHOP_ID?: string;
@@ -519,6 +627,18 @@ interface CreatePlaybookContextOptions {
519
627
  * targets (`loaderData().cloak`, `playbookHeadSnippet`). Default `true`.
520
628
  */
521
629
  cloak?: boolean;
630
+ /**
631
+ * 0.7.0: the `<PlaybookSlot>`s this store renders (anchor selector +
632
+ * position, exactly as the slot props). On a page an all-traffic test
633
+ * targets, `loaderData()` picks the visitor's arm on the server and returns
634
+ * it as `ssr` when one of these slots serves the arm's anchor (or the arm is
635
+ * the original page); the cloak then stays off for that page. Empty/absent =
636
+ * no server render, the 0.6.0 cloak only.
637
+ */
638
+ ssrSlots?: ReadonlyArray<{
639
+ anchor: string;
640
+ position?: 'before' | 'after' | 'prepend' | 'append';
641
+ }>;
522
642
  /**
523
643
  * 0.6.0: the storefront DOMAIN the targeting manifest is keyed by (its
524
644
  * `?shop=`; the Playbook UUID doesn't work there). Overrides
@@ -548,6 +668,13 @@ interface PlaybookLoaderData {
548
668
  targetedPage: string | null;
549
669
  /** 0.6.0: pass to `playbookHeadSnippet(cloak, {nonce})`. Null = no cloak. */
550
670
  cloak: PlaybookCloakConfig | null;
671
+ /**
672
+ * 0.7.0: the visitor's server-rendered arm for `<PlaybookSsrHead>` /
673
+ * `<PlaybookSlot>`, or null (no test here, or it falls back to the cloak).
674
+ */
675
+ ssr: SsrDecision | null;
676
+ /** 0.7.0: why there's no `ssr` on a targeted page (debugging), else null. */
677
+ ssrSkip: string | null;
551
678
  }
552
679
  interface PlaybookRequestContext {
553
680
  readonly shopId: string | null;
@@ -591,7 +718,7 @@ interface PlaybookRequestContext {
591
718
  */
592
719
  finalize(response: Response): Promise<Response>;
593
720
  }
594
- declare function createPlaybookContext({ request, env, waitUntil, shopId: shopIdOption, platformUrl: platformUrlOption, disabled: disabledOption, consentRequired, consent, experienceAttribution, cloak: cloakOption, shopDomain: shopDomainOption, apiBase: apiBaseOption, fetchImpl, }: CreatePlaybookContextOptions): PlaybookRequestContext;
721
+ declare function createPlaybookContext({ request, env, waitUntil, shopId: shopIdOption, platformUrl: platformUrlOption, disabled: disabledOption, consentRequired, consent, experienceAttribution, cloak: cloakOption, ssrSlots, shopDomain: shopDomainOption, apiBase: apiBaseOption, fetchImpl, }: CreatePlaybookContextOptions): PlaybookRequestContext;
595
722
  /**
596
723
  * Wrapper form: creates the context, runs the store's handler with it, then
597
724
  * finalizes whatever response the handler returns (incl. a redirect built
@@ -663,6 +790,27 @@ declare function targetPageKey(pathname: string): string | null;
663
790
  */
664
791
  declare function matchTargetedPage(pages: readonly string[] | null | undefined, pathname: string): string | null;
665
792
 
793
+ /**
794
+ * `window.__pbSsr` (so the SDK adopts the arm and reports it as shown) and the
795
+ * arm's theme-section hides, before first paint. Renders nothing without a
796
+ * decision.
797
+ */
798
+ declare function PlaybookSsrHead({ ssr, nonce }: {
799
+ ssr: SsrDecision | null | undefined;
800
+ nonce?: string;
801
+ }): react_jsx_runtime.JSX.Element | null;
802
+ /**
803
+ * The server-rendered arm, placed by the store where the test's anchor is.
804
+ * Renders only when the decision's arm targets exactly this anchor + position;
805
+ * otherwise nothing (and the SDK renders as usual).
806
+ */
807
+ declare function PlaybookSlot({ ssr, anchor, position, }: {
808
+ ssr: SsrDecision | null | undefined;
809
+ /** The CSS selector the test anchors to, exactly as Playbook stores it. */
810
+ anchor: string;
811
+ position?: 'before' | 'after' | 'prepend' | 'append';
812
+ }): react_jsx_runtime.JSX.Element | null;
813
+
666
814
  /**
667
815
  * Store-specific "why not in test" text for the QA panel. Return a string to
668
816
  * show it (it wins over the generic reason), or null to fall back to the
@@ -1203,4 +1351,4 @@ declare function inNamespace(hashValue: string, namespace: [string, number, numb
1203
1351
  declare function chooseVariation(n: number, ranges: VariationRange[]): number;
1204
1352
  declare function getBucketRanges(numVariations: number, coverage: number | undefined, weights?: number[]): VariationRange[];
1205
1353
 
1206
- export { AA_SITEWIDE_TEST, type AddToCartSource, type AddedLineInput, CART_SYNC_IDLE_MS, CART_VISITOR_ATTRIBUTE, CLOAK_MAX_MS, CLOAK_STYLE_ID, CONSENT_LOADED_EVENTS, CONTROL_ARM, type CartAttribute, type CartAttributeReader, type CartAttributeWriter, type CartLineSnapshot, type CartSyncEvent, type CartSyncSnapshot, type CartWriteResult, type ConsentState, type CreatePlaybookContextOptions, type CreatePlaybookOptions, 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, type ExperienceAttributionConsent, type ExperienceAttributionInput, type HeadSnippetParts, LEGACY_VISITOR_COOKIE, MAX_WRITES_PER_CART, PlaybookAAExposure, type PlaybookArm, type PlaybookAssignReason, type PlaybookAssignment, PlaybookBoundary, type PlaybookCartAdapter, type PlaybookClientConsent, type PlaybookCloakConfig, PlaybookCloakHead, type PlaybookConsentAdapter, type PlaybookDataLayerOption, type PlaybookDebugExplain, type PlaybookDebugOptions, PlaybookDebugPanel, type PlaybookDevice, type PlaybookEnv, PlaybookExposure, PlaybookHead, type PlaybookHeadProps, type PlaybookHeadSnippetOptions, type PlaybookLoaderData, type PlaybookPreview, PlaybookProvider, type PlaybookProxyOptions, type PlaybookRequestContext, PlaybookRoot, type PlaybookRootProps, type PlaybookRuleset, type PlaybookServerConsent, type PlaybookServerResult, type PlaybookState, type PlaybookStoreContext, type PlaybookTestRule, type PlaybookTestStatus, type PlaybookVariant, type PlaybookVisitorType, type RulesetSource, SESSION_VISITOR_COOKIE, STANDARD_EVENTS, type StandardEvent, TRUEVAULT_CONSENT_COOKIE, type TrackScope, type TrackedEntry, type TrueVaultConsentOptions, 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 };
1354
+ export { AA_SITEWIDE_TEST, type AddToCartSource, type AddedLineInput, CART_SYNC_IDLE_MS, CART_VISITOR_ATTRIBUTE, CLOAK_MAX_MS, CLOAK_STYLE_ID, CONSENT_LOADED_EVENTS, CONTROL_ARM, type CartAttribute, type CartAttributeReader, type CartAttributeWriter, type CartLineSnapshot, type CartSyncEvent, type CartSyncSnapshot, type CartWriteResult, type ConsentState, type CreatePlaybookContextOptions, type CreatePlaybookOptions, 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, type ExperienceAttributionConsent, type ExperienceAttributionInput, type HeadSnippetParts, LEGACY_VISITOR_COOKIE, MAX_WRITES_PER_CART, PlaybookAAExposure, type PlaybookArm, type PlaybookAssignReason, type PlaybookAssignment, PlaybookBoundary, type PlaybookCartAdapter, type PlaybookClientConsent, type PlaybookCloakConfig, PlaybookCloakHead, type PlaybookConsentAdapter, type PlaybookDataLayerOption, type PlaybookDebugExplain, type PlaybookDebugOptions, PlaybookDebugPanel, type PlaybookDevice, type PlaybookEnv, PlaybookExposure, PlaybookHead, type PlaybookHeadProps, type PlaybookHeadSnippetOptions, type PlaybookLoaderData, type PlaybookPreview, PlaybookProvider, type PlaybookProxyOptions, type PlaybookRequestContext, PlaybookRoot, type PlaybookRootProps, type PlaybookRuleset, type PlaybookServerConsent, type PlaybookServerResult, PlaybookSlot, PlaybookSsrHead, type PlaybookState, type PlaybookStoreContext, type PlaybookTestRule, type PlaybookTestStatus, type PlaybookVariant, type PlaybookVisitorType, type RulesetSource, SESSION_VISITOR_COOKIE, STANDARD_EVENTS, type SsrDecision, type SsrOutcome, type SsrPayload, type StandardEvent, TRUEVAULT_CONSENT_COOKIE, type TrackScope, type TrackedEntry, type TrueVaultConsentOptions, VISITOR_COOKIE, addedLinesFrom, analyticsConsentFromCookie, assignTest, bucketIndex, buildHeadSnippet, cartHasPlaybookAttribute, chooseVariation, consentFromAnalytics, createCartAttributeReader, createCartAttributeSync, createCartAttributeWriter, createPlaybook, createPlaybookContext, createPlaybookProxyHandler, createTrueVaultConsent, debugPanelAllowed, decideSsr, declareConsentRequired, detectDevice, detectGeo, experienceVisitorIdFromCookies, getBucketRanges, getConsentState, getEqualWeights, getServerTrackedLog, getSessionContext, getSsrPayload, 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, slotMatches, ssrHostInnerHtml, ssrUrl, subscribeTrackedLog, syncVisitorId, takeAddSource, targetPageKey, trackAddToCart, trackAddToCartLines, trueVaultDecision, truevaultConsent, useAnalyticsAllowed, usePageEngagement, usePlaybookConsent, usePlaybookExposure, usePlaybookInteraction, usePlaybookState, usePlaybookVariant, usePreviewParamRedirect, visitorInRunningTest, visitorSeedScript, waitForConsentAPI, withPlaybook, withPlaybookCartAttribute };
package/dist/index.js CHANGED
@@ -1072,6 +1072,155 @@ function hasOwnedPreviewParams(search) {
1072
1072
  return OWNED_PARAM_RE.test(search || "");
1073
1073
  }
1074
1074
 
1075
+ // src/ssr.ts
1076
+ var SSR_SNAPSHOT_VERSION = 1;
1077
+ function ssrUrl(platformUrl, shopDomain) {
1078
+ const url = new URL("/api/storefront/ssr", platformUrl);
1079
+ url.searchParams.set("shop", shopDomain);
1080
+ return url.toString();
1081
+ }
1082
+ function sanitizeSsrPayload(json) {
1083
+ if (!json || typeof json !== "object") return null;
1084
+ const j = json;
1085
+ const doc = j.doc;
1086
+ if (!doc || typeof doc !== "object") return null;
1087
+ if (!doc.keys || typeof doc.keys !== "object" || !Array.isArray(doc.prefixes) || !Array.isArray(doc.exps)) return null;
1088
+ const snapshots = j.snapshots && typeof j.snapshots === "object" ? j.snapshots : {};
1089
+ return { doc, snapshots };
1090
+ }
1091
+ var ssrFetcher = createCachedJsonFetcher({ label: "ssr doc", sanitize: sanitizeSsrPayload });
1092
+ var HEALTHY2 = /* @__PURE__ */ new Set(["memory", "stale", "fetched"]);
1093
+ async function getSsrPayload(args) {
1094
+ try {
1095
+ const { value, source } = await ssrFetcher.getWithSource({
1096
+ url: ssrUrl(args.platformUrl, args.shopDomain),
1097
+ waitUntil: args.waitUntil,
1098
+ fetchImpl: args.fetchImpl
1099
+ });
1100
+ return value && HEALTHY2.has(source) ? value : null;
1101
+ } catch {
1102
+ return null;
1103
+ }
1104
+ }
1105
+ function fnv32a(s2) {
1106
+ let h = 2166136261;
1107
+ for (let i = 0; i < s2.length; i++) {
1108
+ h ^= s2.charCodeAt(i);
1109
+ h += (h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24);
1110
+ }
1111
+ return h >>> 0;
1112
+ }
1113
+ function bucketIndex(seed, id, weights) {
1114
+ const k = weights.length;
1115
+ if (!k) return -1;
1116
+ const n = fnv32a(String(fnv32a(seed + id))) % 1e4 / 1e4;
1117
+ const total = weights.reduce((a, b) => a + b, 0);
1118
+ const w = total < 0.99 || total > 1.01 ? weights.map(() => 1 / k) : weights;
1119
+ let cum = 0;
1120
+ for (let i = 0; i < k; i++) {
1121
+ const start = cum;
1122
+ cum += w[i];
1123
+ if (n >= start && n < start + w[i]) return i;
1124
+ }
1125
+ return -1;
1126
+ }
1127
+ function priorArmFromExposure(raw, experimentId, nowSec = Math.floor(Date.now() / 1e3)) {
1128
+ if (!raw) return null;
1129
+ let v = raw;
1130
+ if (v.includes("%")) {
1131
+ try {
1132
+ v = decodeURIComponent(v);
1133
+ } catch {
1134
+ }
1135
+ }
1136
+ v = v.slice(0, 4096);
1137
+ const RE = /^[A-Za-z0-9-]{1,64}$/;
1138
+ for (const part of v.split("_")) {
1139
+ const f = part.split(".");
1140
+ if (f.length !== 4 || f[0] !== experimentId || !RE.test(f[1])) continue;
1141
+ const s2 = parseInt(f[3], 36);
1142
+ if (Number.isFinite(s2) && nowSec - s2 <= EXPOSURE_TTL_DAYS * 86400) return f[1];
1143
+ }
1144
+ return null;
1145
+ }
1146
+ function experimentsForPage(doc, pageKey) {
1147
+ const out = new Set(doc.keys[pageKey] ?? []);
1148
+ for (const [prefix, idx] of doc.prefixes) if (pageKey.startsWith(prefix)) idx.forEach((i) => out.add(i));
1149
+ return [...out];
1150
+ }
1151
+ function decideSsr(input) {
1152
+ const { payload, pageKey, cookies, consent } = input;
1153
+ const idx = experimentsForPage(payload.doc, pageKey);
1154
+ if (idx.length === 0) return { skip: "no-test" };
1155
+ if (idx.length > 1) return { skip: "multi-test" };
1156
+ const exp = payload.doc.exps[idx[0]];
1157
+ if (!exp) return { skip: "no-test" };
1158
+ if (exp.ok !== 1) return { skip: `ineligible:${exp.why || "unknown"}` };
1159
+ if (exp.aud) return { skip: "audience" };
1160
+ if (!exp.settled && exp.hv !== 2 && exp.hv !== 3) return { skip: "hash-version" };
1161
+ const arms = exp.arms || [];
1162
+ let arm;
1163
+ let idSource = "roll";
1164
+ if (exp.settled) {
1165
+ arm = arms.find((a) => a.id === exp.settled);
1166
+ idSource = "settled";
1167
+ } else {
1168
+ const allowed = consent === "allowed";
1169
+ const prior = allowed ? priorArmFromExposure(cookies[EXPOSURE_COOKIE], exp.id, input.nowSec) : null;
1170
+ if (prior) {
1171
+ arm = arms.find((a) => a.id === prior && a.w > 0);
1172
+ if (arm) idSource = "prior";
1173
+ }
1174
+ if (!arm) {
1175
+ const vid = (allowed ? experienceVisitorIdFromCookies(cookies) : null) ?? input.fallbackVisitorId ?? null;
1176
+ if (!vid) return { skip: "no-visitor-id" };
1177
+ const i = bucketIndex(exp.seed, vid, arms.map((a) => a.w));
1178
+ arm = i >= 0 ? arms[i] : arms.find((a) => a.c === 1) ?? arms[0];
1179
+ }
1180
+ }
1181
+ if (!arm) return { skip: "no-arm" };
1182
+ const [t, h = ""] = pageKey.split(":");
1183
+ const snapshot = arm.x ? payload.snapshots[arm.x] ?? null : null;
1184
+ if (arm.x && (!snapshot || snapshot.v !== SSR_SNAPSHOT_VERSION || !snapshot.nodes?.length)) {
1185
+ return { skip: "no-snapshot" };
1186
+ }
1187
+ return { decision: { experimentId: exp.id, armId: arm.id, experienceId: arm.x, idSource, arm, snapshot, page: { t, h } } };
1188
+ }
1189
+ var BASE = ":host{all:initial}*,*::before,*::after{box-sizing:border-box}[data-pb-experience-root]{font-family:system-ui,-apple-system,sans-serif;color:#111827;display:flex;flex-direction:column}img,video{max-width:100%;display:block}";
1190
+ var HTML_BASE = ":host{display:block}*,*::before,*::after{box-sizing:border-box}";
1191
+ var escAttr = (s2) => s2.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
1192
+ var escStyle = (s2) => s2.replace(/<\/(style)/gi, "<\\/$1");
1193
+ function ssrHostInnerHtml(snapshot, page) {
1194
+ const nodes = snapshot.nodes.map((nd) => {
1195
+ const style = [
1196
+ "display:block",
1197
+ "width:100%",
1198
+ typeof nd.mt === "number" ? `margin-top:${nd.mt}px` : "",
1199
+ typeof nd.mb === "number" ? `margin-bottom:${nd.mb}px` : ""
1200
+ ].filter(Boolean).join(";");
1201
+ return `<div data-proto-id="${escAttr(nd.id)}" data-proto-type="html" style="${style}"><template shadowrootmode="open"><style>${escStyle(HTML_BASE + "\n" + (nd.css || ""))}</style><div class="pb-html-root" data-pb-page-type="${escAttr(page.t === "home" ? "home" : page.t)}" data-pb-handle="${escAttr(page.h)}">${nd.html || ""}</div></template></div>`;
1202
+ }).join("");
1203
+ return `<template shadowrootmode="open"><style data-pb-ssr-snapshot>${BASE}</style><div data-pb-experience-root data-pb-ssr-snapshot>${nodes}</div></template>`;
1204
+ }
1205
+ function ssrStateScript(d) {
1206
+ const state = {
1207
+ experimentId: d.experimentId,
1208
+ armId: d.armId,
1209
+ experienceId: d.experienceId,
1210
+ placed: !!d.experienceId,
1211
+ reason: d.experienceId ? null : "control",
1212
+ idSource: d.idSource,
1213
+ placedAt: null,
1214
+ server: true
1215
+ };
1216
+ return `window.__pbSsr=${JSON.stringify(state).replace(/</g, "\\u003c")};`;
1217
+ }
1218
+ function slotMatches(d, slot) {
1219
+ const a = d.arm.a;
1220
+ if (!a) return false;
1221
+ return a.s.trim() === slot.anchor.trim() && a.p === (slot.position ?? "after");
1222
+ }
1223
+
1075
1224
  // src/request-context.ts
1076
1225
  var FINALIZE_WAIT_MS = 2e3;
1077
1226
  var FINALIZE_REDIRECT_WAIT_MS = 0;
@@ -1092,6 +1241,7 @@ function createPlaybookContext({
1092
1241
  consent,
1093
1242
  experienceAttribution = true,
1094
1243
  cloak: cloakOption = true,
1244
+ ssrSlots = [],
1095
1245
  shopDomain: shopDomainOption,
1096
1246
  apiBase: apiBaseOption,
1097
1247
  fetchImpl
@@ -1193,6 +1343,32 @@ function createPlaybookContext({
1193
1343
  }
1194
1344
  return cloakPromise;
1195
1345
  };
1346
+ let ssrRendered = false;
1347
+ let ssrPromise = null;
1348
+ const ssrFor = (cloak) => {
1349
+ if (!ssrPromise) {
1350
+ ssrPromise = (async () => {
1351
+ if (!cloak || ssrSlots.length === 0) return { ssr: null, skip: null };
1352
+ const payload = await getSsrPayload({ platformUrl, shopDomain: cloak.shopDomain, waitUntil, fetchImpl });
1353
+ if (!payload) return { ssr: null, skip: "doc-unavailable" };
1354
+ const cookies = parseCookies(request.headers.get("cookie"));
1355
+ const own = (await get())?.state?.visitorId ?? null;
1356
+ const out = decideSsr({
1357
+ payload,
1358
+ pageKey: cloak.targetedPage,
1359
+ cookies,
1360
+ consent: cartConsent(cookies),
1361
+ fallbackVisitorId: own
1362
+ });
1363
+ if ("skip" in out) return { ssr: null, skip: out.skip };
1364
+ const d = out.decision;
1365
+ if (d.experienceId && !ssrSlots.some((s2) => slotMatches(d, s2))) return { ssr: null, skip: "no-slot" };
1366
+ ssrRendered = true;
1367
+ return { ssr: d, skip: null };
1368
+ })().catch(() => ({ ssr: null, skip: "error" }));
1369
+ }
1370
+ return ssrPromise;
1371
+ };
1196
1372
  const append = (headers, cookies) => {
1197
1373
  for (const cookie of cookies) headers.append("Set-Cookie", cookie);
1198
1374
  };
@@ -1203,11 +1379,15 @@ function createPlaybookContext({
1203
1379
  get,
1204
1380
  async loaderData() {
1205
1381
  const [result, cloak] = await Promise.all([get(), cloakFor()]);
1382
+ const { ssr, skip } = await ssrFor(cloak);
1206
1383
  return {
1207
1384
  playbook: result?.state ?? null,
1208
1385
  hasPlaybookParams: hasPlaybookParams(request.url),
1209
1386
  targetedPage: cloak?.targetedPage ?? null,
1210
- cloak
1387
+ // A server-rendered arm needs no hide: its design is already in the HTML.
1388
+ cloak: ssr ? null : cloak,
1389
+ ssr,
1390
+ ssrSkip: ssr ? null : skip
1211
1391
  };
1212
1392
  },
1213
1393
  cartAttribute() {
@@ -1243,6 +1423,7 @@ function createPlaybookContext({
1243
1423
  async appendCookies(headers) {
1244
1424
  try {
1245
1425
  append(headers, await cookiesFor(FINALIZE_WAIT_MS));
1426
+ if (ssrRendered) headers.set("Cache-Control", "private, no-store");
1246
1427
  } catch {
1247
1428
  }
1248
1429
  },
@@ -1252,13 +1433,15 @@ function createPlaybookContext({
1252
1433
  const cookies = await cookiesFor(
1253
1434
  isRedirect ? FINALIZE_REDIRECT_WAIT_MS : FINALIZE_WAIT_MS
1254
1435
  );
1255
- if (!cookies.length) return response;
1436
+ if (!cookies.length && !ssrRendered) return response;
1256
1437
  try {
1257
1438
  append(response.headers, cookies);
1439
+ if (ssrRendered) response.headers.set("Cache-Control", "private, no-store");
1258
1440
  return response;
1259
1441
  } catch {
1260
1442
  const headers = new Headers(response.headers);
1261
1443
  append(headers, cookies);
1444
+ if (ssrRendered) headers.set("Cache-Control", "private, no-store");
1262
1445
  return new Response(response.body, {
1263
1446
  status: response.status,
1264
1447
  statusText: response.statusText,
@@ -1456,6 +1639,32 @@ function playbookHeadSnippetHtml(cloak, options = {}) {
1456
1639
  const attrs = Object.entries(parts.sdk.attrs).map(([k, v]) => ` ${k}="${escapeAttr(v)}"`).join("");
1457
1640
  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
1641
  }
1642
+ function PlaybookSsrHead({ ssr, nonce }) {
1643
+ if (!ssr) return null;
1644
+ const hide = ssr.experienceId ? (ssr.arm.hide || []).map((s2) => `${s2}{display:none!important}`).join("") : "";
1645
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
1646
+ /* @__PURE__ */ jsx("script", { nonce, "data-pb-ssr-state": "", dangerouslySetInnerHTML: { __html: ssrStateScript(ssr) } }),
1647
+ hide ? /* @__PURE__ */ jsx("style", { id: "pb-ssr-hide", nonce, dangerouslySetInnerHTML: { __html: escStyle(hide) } }) : null
1648
+ ] });
1649
+ }
1650
+ function PlaybookSlot({
1651
+ ssr,
1652
+ anchor,
1653
+ position = "after"
1654
+ }) {
1655
+ if (!ssr || !ssr.experienceId || !ssr.snapshot || !slotMatches(ssr, { anchor, position })) return null;
1656
+ return /* @__PURE__ */ jsx(
1657
+ "div",
1658
+ {
1659
+ id: "pb-experience-root",
1660
+ "data-pb-experience-mount": "",
1661
+ "data-pb-ssr": ssr.experimentId,
1662
+ style: { display: "block", boxSizing: "border-box", maxWidth: "100%" },
1663
+ suppressHydrationWarning: true,
1664
+ dangerouslySetInnerHTML: { __html: ssrHostInnerHtml(ssr.snapshot, ssr.page) }
1665
+ }
1666
+ );
1667
+ }
1459
1668
  var PlaybookBoundary = class extends Component {
1460
1669
  state = { failed: false };
1461
1670
  static getDerivedStateFromError() {
@@ -2926,4 +3135,4 @@ function trackAddToCartLines(lines, cartLines, source) {
2926
3135
  }
2927
3136
  }
2928
3137
 
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 };
3138
+ 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, PlaybookSlot, PlaybookSsrHead, SESSION_VISITOR_COOKIE, STANDARD_EVENTS, TRUEVAULT_CONSENT_COOKIE, VISITOR_COOKIE, addedLinesFrom, analyticsConsentFromCookie, assignTest, bucketIndex, buildHeadSnippet, cartHasPlaybookAttribute, chooseVariation, consentFromAnalytics, createCartAttributeReader, createCartAttributeSync, createCartAttributeWriter, createPlaybook, createPlaybookContext, createPlaybookProxyHandler, createTrueVaultConsent, debugPanelAllowed, decideSsr, declareConsentRequired, detectDevice, detectGeo, experienceVisitorIdFromCookies, getBucketRanges, getConsentState, getEqualWeights, getServerTrackedLog, getSessionContext, getSsrPayload, 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, slotMatches, ssrHostInnerHtml, ssrUrl, subscribeTrackedLog, syncVisitorId, takeAddSource, targetPageKey, trackAddToCart, trackAddToCartLines, trueVaultDecision, truevaultConsent, useAnalyticsAllowed, usePageEngagement, usePlaybookConsent, usePlaybookExposure, usePlaybookInteraction, usePlaybookState, usePlaybookVariant, usePreviewParamRedirect, visitorInRunningTest, visitorSeedScript, waitForConsentAPI, withPlaybook, withPlaybookCartAttribute };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@heyplaybook/hydrogen",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Playbook store-edit tests for Shopify Hydrogen storefronts: server-side assignment, consent-gated visitor cookie, in-view exposures and cart attribution.",
5
5
  "license": "MIT",
6
6
  "author": "Pack Digital Inc.",