@heyplaybook/hydrogen 0.7.1 → 0.8.1

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/README.md CHANGED
@@ -206,6 +206,97 @@ The manifest is cached per isolate exactly like the ruleset: 60 s fresh, 300 s
206
206
  stale, a 300 ms / 1.5 s render budget, a 30 s backoff after a failure. The kill
207
207
  switch and a missing shop id turn it off with everything else.
208
208
 
209
+ ### Server-side render: named slots and section slots (0.8.0)
210
+
211
+ The cloak hides the page until the browser has painted the test. With slots, the
212
+ store server renders the visitor's arm straight into the HTML instead: no hide, no
213
+ swap. Render a slot once per spot; any test a designer places at that slot is then
214
+ server-rendered, with no code change per test.
215
+
216
+ **Named slots** — one per spot, from a fixed vocabulary:
217
+
218
+ | Name | Page | Where |
219
+ |---|---|---|
220
+ | `buy-column-top` | product | first thing in the buy column, above the title / breadcrumbs |
221
+ | `after-add-to-cart` | product | right after the Add to Cart block, outside your button group |
222
+ | `under-size` | product | under the Size option's label, above its buttons |
223
+ | `collection-grid-top` | collection | right before the product grid |
224
+ | `after-home-hero` | home | right after the hero section |
225
+
226
+ ```tsx
227
+ import {PlaybookSlot} from '@heyplaybook/hydrogen';
228
+
229
+ const {playbookSsr} = useRootLoaderData(); // the root loader's `ssr`
230
+
231
+ <AddToCart … />
232
+ <PlaybookSlot ssr={playbookSsr} name="after-add-to-cart" />
233
+ ```
234
+
235
+ **Section slots** — wrap your section renderer and every CMS section gets a slot
236
+ before and after it (`section:<id>:before` / `section:<id>:after`), so home and
237
+ landing pages need no names agreed in advance. With Pack, replace
238
+ `<RenderSections content={page} />` with:
239
+
240
+ ```tsx
241
+ import {useSections} from '@pack/react';
242
+ import {PlaybookSections} from '@heyplaybook/hydrogen';
243
+
244
+ const sections = useSections({content: page}); // what RenderSections renders
245
+ <PlaybookSections ssr={playbookSsr} sections={sections} />
246
+ ```
247
+
248
+ The section id is each element's React key (`useSections` keys by section id).
249
+ Pass `sectionId={(el, i) => …}` if your elements are keyed differently.
250
+
251
+ **Declare what you render** in `server.ts`, so the server only drops the cloak for
252
+ a test it will actually render:
253
+
254
+ ```ts
255
+ import {createPlaybookContext, SECTION_SLOTS} from '@heyplaybook/hydrogen';
256
+
257
+ createPlaybookContext({
258
+ // …
259
+ ssrSlots: [
260
+ 'buy-column-top',
261
+ 'after-add-to-cart',
262
+ 'under-size',
263
+ 'collection-grid-top',
264
+ 'after-home-hero',
265
+ SECTION_SLOTS, // you render <PlaybookSections>
266
+ ],
267
+ });
268
+ ```
269
+
270
+ Root head, once:
271
+
272
+ ```tsx
273
+ <PlaybookSsrHead ssr={data.ssr} nonce={nonce} />
274
+ ```
275
+
276
+ How it behaves:
277
+
278
+ - **Matching.** A test's anchor carries a slot key. The server matches it first,
279
+ then falls back to the 0.7 exact-selector match, so `{anchor, position}` slots
280
+ keep working unchanged.
281
+ - **The marker.** Every slot renders an inert `<template data-pb-slot="<key>">`
282
+ (display none, no box, no layout effect). The browser path anchors to it
283
+ (`[data-pb-slot="<key>"]`), so a test at a slot also renders correctly for a
284
+ visitor the server didn't decide for.
285
+ - **Placement.** The design renders right after the marker (right before it for a
286
+ `before` anchor), exactly where the browser path would put it.
287
+ - **Slot report.** After hydration `<PlaybookRoot>` reports which markers a page
288
+ renders, so Playbook learns your slot list and its designer offers those slots as
289
+ placements. Sampled (1 in 10 page loads), at most once a day per browser per page
290
+ type, no shopper data. `slotReport={false}` turns it off.
291
+ - **Fallback.** Anything the server can't render (a test at a plain selector, a
292
+ slot this page doesn't declare, more than one test on the page, a non-html
293
+ design) keeps the cloak, as before.
294
+
295
+ Render each named slot only where it belongs, and only once per page. A declared
296
+ slot that a page doesn't actually render (e.g. `under-size` on a product with no
297
+ Size option) costs that page the cloak: the browser then places the design late, at
298
+ the test's fallback spot. Wrap such a slot in the same condition as its spot.
299
+
209
300
  ### Cart attribute at creation
210
301
 
211
302
  Writing `_pb_vid` after the fact can race other attribute writers (Intelligems writes when
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
2
  import * as react from 'react';
3
- import { ReactNode, Component } from 'react';
3
+ import { ReactNode, ReactElement, Component } from 'react';
4
4
 
5
5
  /**
6
6
  * Analytics consent — vendored from the Playbook platform's shared consent module (the
@@ -479,6 +479,45 @@ 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
+ /**
483
+ * 0.8.0: the server-render slot vocabulary — a VENDORED copy of the
484
+ * platform's `shared/src/editor-protocol/ssr-slots.ts` (the package can't
485
+ * import the monorepo's internal packages). `__tests__/slots.test.ts` fails if the two drift, so
486
+ * a name added on one side must be added on the other in the same change.
487
+ *
488
+ * Two kinds of slot:
489
+ *
490
+ * - NAMED: `<PlaybookSlot name="after-add-to-cart" />`, one per spot, from
491
+ * the list below.
492
+ * - SECTION: `<PlaybookSections>` renders `section:<id>:before` and
493
+ * `section:<id>:after` around each CMS section (home, landing pages).
494
+ *
495
+ * Every slot renders an inert `<template data-pb-slot="<key>">` marker, so a
496
+ * slot is also a CSS anchor (`[data-pb-slot="<key>"]`) for the browser path,
497
+ * and the package can report which slots a page renders.
498
+ */
499
+ declare const SSR_SLOT_ATTR = "data-pb-slot";
500
+ /** The named slots. Extend in step with the platform's list. */
501
+ declare const SSR_SLOT_NAMES: readonly ["buy-column-top", "after-add-to-cart", "under-size", "collection-grid-top", "after-home-hero"];
502
+ type PlaybookSlotName = (typeof SSR_SLOT_NAMES)[number];
503
+ type SectionSlotSide = 'before' | 'after';
504
+ type SectionSlotKey = `section:${string}:${SectionSlotSide}`;
505
+ type PlaybookSlotKey = PlaybookSlotName | SectionSlotKey;
506
+ /**
507
+ * Declare in `createPlaybookContext({ssrSlots})` that the store wraps its
508
+ * sections in `<PlaybookSections>`: a test anchored to any section slot is
509
+ * then server-rendered.
510
+ */
511
+ declare const SECTION_SLOTS: "section:*";
512
+ /** A named slot or a well-formed section slot key. */
513
+ declare function isSlotKey(v: unknown): v is PlaybookSlotKey;
514
+ /** `section:<id>:before|after`, or null for an id that isn't selector-safe. */
515
+ declare function sectionSlotKey(id: unknown, side: SectionSlotSide): SectionSlotKey | null;
516
+ /** The CSS selector of a slot's marker. */
517
+ declare function slotSelector(key: PlaybookSlotKey): string;
518
+ /** The slot a selector names when it is exactly a slot marker selector, else null. */
519
+ declare function slotFromSelector(selector: unknown): PlaybookSlotKey | null;
520
+
482
521
  interface SsrSnapshotNode {
483
522
  id: string;
484
523
  html: string;
@@ -495,10 +534,16 @@ interface SsrArm {
495
534
  w: number;
496
535
  c: 0 | 1;
497
536
  x: string | null;
537
+ /**
538
+ * Anchor: selector + position (+ fallback). 0.8.0: `slot` = the named or
539
+ * section slot the arm mounts at (platform `ExperienceAnchor.slot`); the
540
+ * slot match comes first, the exact selector is the 0.7 fallback.
541
+ */
498
542
  a: {
499
543
  s: string;
500
544
  p: 'before' | 'after' | 'prepend' | 'append';
501
545
  f?: string;
546
+ slot?: string;
502
547
  } | null;
503
548
  hide: string[];
504
549
  }
@@ -546,6 +591,26 @@ declare function getSsrPayload(args: {
546
591
  waitUntil?: (p: Promise<unknown>) => void;
547
592
  fetchImpl?: typeof fetch;
548
593
  }): Promise<SsrPayload | null>;
594
+ /**
595
+ * 0.8.1: the TOTAL budget for the uncached preview read, retry included. Only
596
+ * a `?pb=` preview (staff and the merchant looking at one test) ever waits on
597
+ * it; shopper reads keep `COLD_RENDER_BUDGET_MS` / `RENDER_BUDGET_MS`
598
+ * (./rules.ts). 0.7.1 had 1.5s, and a cold platform function missed it, so
599
+ * the first open of a preview link fell back to the browser's `?pb` path.
600
+ */
601
+ declare const PREVIEW_FETCH_BUDGET_MS = 5000;
602
+ /** 0.8.1: one attempt's share of the budget; a timed-out first attempt leaves room for the retry. */
603
+ declare const PREVIEW_ATTEMPT_BUDGET_MS = 3000;
604
+ /**
605
+ * 0.8.1: the cookie that carries a preview code across CLIENT-SIDE
606
+ * navigations. The browser strips `?pb=` from the address bar once it has
607
+ * resolved the code, so React Router's `.data` requests for later pages don't
608
+ * carry it. Session-only, HttpOnly, Lax. Set when a document request's code
609
+ * is valid; honoured ONLY on `.data` requests; cleared by any document
610
+ * request without `?pb=` (Exit reloads, a new tab, a typed URL), so it can't
611
+ * follow anyone out of the preview.
612
+ */
613
+ declare const PREVIEW_CODE_COOKIE = "_pb_preview_code";
549
614
  /**
550
615
  * The arm index for `seed` + `id` over `weights` (coverage 1), or -1. GrowthBook
551
616
  * v2: `fnv32a(fnv32a(seed + id) + "") % 10000 / 10000`; weights that don't sum
@@ -569,7 +634,21 @@ interface SsrDecision {
569
634
  code: string;
570
635
  testName: string;
571
636
  armLabel: string;
637
+ /**
638
+ * 0.8.1: decided on a `.data` request (a client-side navigation). It
639
+ * reaches the page through React, not the HTML, so `<PlaybookSlot>` and
640
+ * `<PlaybookSsrHead>` render it only in a tab previewing this code
641
+ * (`carriedPreviewAllowed`).
642
+ */
643
+ carried?: boolean;
572
644
  };
645
+ /**
646
+ * 0.8.0: which kind of declared slot serves the arm (`loaderData()` sets it):
647
+ * `slot` = a named / section slot (by slot key), `anchor` = a 0.7 selector
648
+ * slot. Only that kind of `<PlaybookSlot>` renders the design, so a store
649
+ * that has both for one spot never renders it twice.
650
+ */
651
+ matchedBy?: 'slot' | 'anchor';
573
652
  }
574
653
  type SsrOutcome = {
575
654
  decision: SsrDecision;
@@ -604,11 +683,32 @@ declare function ssrHostInnerHtml(snapshot: SsrSnapshot, page: {
604
683
  t: string;
605
684
  h: string;
606
685
  }): string;
607
- /** Does this slot serve the decision's anchor? Exact selector + position match. */
608
- declare function slotMatches(d: SsrDecision, slot: {
609
- anchor: string;
610
- position?: string;
611
- }): boolean;
686
+ /**
687
+ * 0.8.0: the slot an arm's anchor serves — its `slot`, else the slot its
688
+ * selector names when the selector is exactly a marker
689
+ * (`[data-pb-slot="…"]`). Null for a plain CSS anchor.
690
+ */
691
+ declare function armSlot(a: SsrArm['a'] | null | undefined): PlaybookSlotKey | null;
692
+ /**
693
+ * A slot the store renders, as `<PlaybookSlot>` props or a
694
+ * `createPlaybookContext({ssrSlots})` entry:
695
+ *
696
+ * - `{name}` — a named slot or a section slot key; `{name: SECTION_SLOTS}`
697
+ * = any section slot (`<PlaybookSections>`);
698
+ * - `{anchor, position}` — the 0.7 exact-selector slot.
699
+ */
700
+ interface SsrSlotRef {
701
+ name?: string;
702
+ anchor?: string;
703
+ position?: 'before' | 'after' | 'prepend' | 'append';
704
+ }
705
+ /**
706
+ * Does this slot serve the decision's arm? By SLOT KEY first (a named or
707
+ * section slot: the arm's `slot`, or the slot its selector names), then the
708
+ * 0.7 exact selector + position match, so a store's selector-keyed slots
709
+ * keep working unchanged.
710
+ */
711
+ declare function slotMatches(d: SsrDecision, slot: SsrSlotRef): boolean;
612
712
 
613
713
  /** The env keys the kit reads (all optional). */
614
714
  interface PlaybookEnv {
@@ -651,17 +751,19 @@ interface CreatePlaybookContextOptions {
651
751
  */
652
752
  cloak?: boolean;
653
753
  /**
654
- * 0.7.0: the `<PlaybookSlot>`s this store renders (anchor selector +
655
- * position, exactly as the slot props). On a page an all-traffic test
656
- * targets, `loaderData()` picks the visitor's arm on the server and returns
657
- * it as `ssr` when one of these slots serves the arm's anchor (or the arm is
658
- * the original page); the cloak then stays off for that page. Empty/absent =
659
- * no server render, the 0.6.0 cloak only.
754
+ * The slots this store renders. On a page an all-traffic test targets,
755
+ * `loaderData()` picks the visitor's arm on the server and returns it as
756
+ * `ssr` when one of these slots serves the arm (or the arm is the original
757
+ * page); the cloak then stays off for that page. Empty/absent = no server
758
+ * render, the 0.6.0 cloak only.
759
+ *
760
+ * - 0.8.0 a slot NAME (`'after-add-to-cart'`, the `<PlaybookSlot name>`s
761
+ * the store renders) or `SECTION_SLOTS` (the store wraps its sections
762
+ * in `<PlaybookSections>`). Matched by the arm's slot key.
763
+ * - 0.7.0 `{anchor, position}`, exactly as the `<PlaybookSlot>` props.
764
+ * Matched by exact selector, after the slot key.
660
765
  */
661
- ssrSlots?: ReadonlyArray<{
662
- anchor: string;
663
- position?: 'before' | 'after' | 'prepend' | 'append';
664
- }>;
766
+ ssrSlots?: ReadonlyArray<string | SsrSlotRef>;
665
767
  /**
666
768
  * 0.6.0: the storefront DOMAIN the targeting manifest is keyed by (its
667
769
  * `?shop=`; the Playbook UUID doesn't work there). Overrides
@@ -817,23 +919,94 @@ declare function matchTargetedPage(pages: readonly string[] | null | undefined,
817
919
  * `window.__pbSsr` (so the SDK adopts the arm and reports it as shown) and the
818
920
  * arm's theme-section hides, before first paint. Renders nothing without a
819
921
  * decision.
922
+ *
923
+ * 0.8.1: a carried preview decision arrives with a client-side navigation, so
924
+ * an inline <script> would never run: `window.__pbSsr` is set from a layout
925
+ * effect instead, in the same commit that inserts the host, before the
926
+ * experience SDK looks at the new page.
820
927
  */
821
928
  declare function PlaybookSsrHead({ ssr, nonce }: {
822
929
  ssr: SsrDecision | null | undefined;
823
930
  nonce?: string;
824
931
  }): react_jsx_runtime.JSX.Element | null;
825
- /**
826
- * The server-rendered arm, placed by the store where the test's anchor is.
827
- * Renders only when the decision's arm targets exactly this anchor + position;
828
- * otherwise nothing (and the SDK renders as usual).
829
- */
830
- declare function PlaybookSlot({ ssr, anchor, position, }: {
932
+ type PlaybookSlotProps = {
831
933
  ssr: SsrDecision | null | undefined;
832
- /** The CSS selector the test anchors to, exactly as Playbook stores it. */
934
+ /**
935
+ * 0.8.0: the slot's name (`after-add-to-cart`, …) or a section slot key
936
+ * (`section:<id>:after`; `<PlaybookSections>` renders those for you).
937
+ */
938
+ name: PlaybookSlotKey;
939
+ anchor?: never;
940
+ position?: never;
941
+ } | {
942
+ ssr: SsrDecision | null | undefined;
943
+ name?: never;
944
+ /** 0.7: the CSS selector the test anchors to, exactly as Playbook stores it. */
833
945
  anchor: string;
834
946
  position?: 'before' | 'after' | 'prepend' | 'append';
947
+ };
948
+ /**
949
+ * The server-rendered arm, placed by the store where the test mounts.
950
+ *
951
+ * A NAMED slot always renders an inert marker, `<template data-pb-slot>`
952
+ * (no box, nothing in layout), so the page says which slots it has: the
953
+ * browser path anchors to it (`[data-pb-slot="<name>"]`) and the package
954
+ * reports it to Playbook. When the decision's arm mounts at this slot the
955
+ * design renders beside the marker (before it for a `before` anchor, else
956
+ * after), exactly where the browser path would put it.
957
+ *
958
+ * A 0.7 SELECTOR slot renders only when the arm targets exactly this anchor +
959
+ * position; otherwise nothing (and the SDK renders as usual).
960
+ *
961
+ * Slot key first: when `loaderData()` matched the arm to a declared named /
962
+ * section slot (`ssr.matchedBy === 'slot'`), only that slot renders it, so a
963
+ * store keeping an old selector slot at the same spot never renders it twice.
964
+ */
965
+ declare function PlaybookSlot(props: PlaybookSlotProps): react_jsx_runtime.JSX.Element | null;
966
+ /**
967
+ * 0.8.0 SECTION slots: renders the store's sections with a slot before and
968
+ * after each one (`section:<id>:before|after`), so a test can mount between
969
+ * any two sections of a home or landing page with no name agreed in advance.
970
+ *
971
+ * // Pack: same output as <RenderSections content={page} />, plus the slots.
972
+ * const sections = useSections({content: page});
973
+ * <PlaybookSections ssr={playbookSsr} sections={sections} />
974
+ *
975
+ * The id is each element's React key (`useSections` keys by section id), or
976
+ * `sectionId(element, index)` when the store keys them differently. A section
977
+ * without a usable id renders as is, with no slots. Declare `SECTION_SLOTS`
978
+ * in `createPlaybookContext({ssrSlots})`.
979
+ */
980
+ declare function PlaybookSections({ ssr, sections, sectionId, }: {
981
+ ssr: SsrDecision | null | undefined;
982
+ sections: ReadonlyArray<ReactNode> | null | undefined;
983
+ sectionId?: (element: ReactElement, index: number) => string | null | undefined;
835
984
  }): react_jsx_runtime.JSX.Element | null;
836
985
 
986
+ declare const SLOT_REPORT_URL = "/apps/playbook/api/storefront/ssr/slots";
987
+ declare const SLOT_REPORT_SAMPLE_RATE = 0.1;
988
+ /** The slot keys the markup under `root` renders, in page order, de-duplicated and capped. */
989
+ declare function renderedSlotKeys(root: ParentNode): string[];
990
+ interface StorageLike {
991
+ getItem(key: string): string | null;
992
+ setItem(key: string, value: string): void;
993
+ }
994
+ /**
995
+ * Read this page's markers and report them when the dedupe + sample allow.
996
+ * Returns whether it sent. Browser only; never throws.
997
+ */
998
+ declare function reportPageSlots(input: {
999
+ shopId: string | null | undefined;
1000
+ pathname: string;
1001
+ url?: string;
1002
+ sampleRate?: number;
1003
+ fetchImpl?: typeof fetch;
1004
+ root?: ParentNode;
1005
+ storage?: StorageLike | null;
1006
+ random?: () => number;
1007
+ now?: () => number;
1008
+ }): boolean;
1009
+
837
1010
  /**
838
1011
  * Store-specific "why not in test" text for the QA panel. Return a string to
839
1012
  * show it (it wins over the generic reason), or null to fall back to the
@@ -990,6 +1163,16 @@ interface PlaybookRootProps {
990
1163
  previewIgnoresTargeting?: boolean;
991
1164
  /** Observe cart-sync decisions (debug/logging). */
992
1165
  onCartSyncEvent?: (event: CartSyncEvent) => void;
1166
+ /**
1167
+ * 0.8.0: report which server-render slots each page renders (its
1168
+ * `<template data-pb-slot>` markers) so Playbook learns the store's slot
1169
+ * list. Sampled, deduped per browser per day, no shopper data (see
1170
+ * `./slot-report`). Default on; `false` turns it off.
1171
+ */
1172
+ slotReport?: boolean | {
1173
+ sampleRate?: number;
1174
+ url?: string;
1175
+ };
993
1176
  exposureUrl?: string;
994
1177
  eventUrl?: string;
995
1178
  supportedEvents?: string[];
@@ -1005,7 +1188,7 @@ declare function visitorInRunningTest(state: PlaybookState | null | undefined):
1005
1188
  declare function PlaybookAAExposure({ testKey }: {
1006
1189
  testKey?: string;
1007
1190
  }): react_jsx_runtime.JSX.Element;
1008
- declare function PlaybookRoot({ state, location, navigate, cart, consent, storeContext, editorPreview, aaSentinel, debug, dataLayer, previewIgnoresTargeting, onCartSyncEvent, exposureUrl, eventUrl, supportedEvents, children, }: PlaybookRootProps): react_jsx_runtime.JSX.Element;
1191
+ declare function PlaybookRoot({ state, location, navigate, cart, consent, storeContext, editorPreview, aaSentinel, debug, dataLayer, previewIgnoresTargeting, onCartSyncEvent, exposureUrl, eventUrl, supportedEvents, slotReport, children, }: PlaybookRootProps): react_jsx_runtime.JSX.Element;
1009
1192
 
1010
1193
  interface Props {
1011
1194
  /** For the console warning only. */
@@ -1374,4 +1557,4 @@ declare function inNamespace(hashValue: string, namespace: [string, number, numb
1374
1557
  declare function chooseVariation(n: number, ranges: VariationRange[]): number;
1375
1558
  declare function getBucketRanges(numVariations: number, coverage: number | undefined, weights?: number[]): VariationRange[];
1376
1559
 
1377
- 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 };
1560
+ 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, PREVIEW_ATTEMPT_BUDGET_MS, PREVIEW_CODE_COOKIE, PREVIEW_FETCH_BUDGET_MS, 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, PlaybookSections, type PlaybookServerConsent, type PlaybookServerResult, PlaybookSlot, type PlaybookSlotKey, type PlaybookSlotName, type PlaybookSlotProps, PlaybookSsrHead, type PlaybookState, type PlaybookStoreContext, type PlaybookTestRule, type PlaybookTestStatus, type PlaybookVariant, type PlaybookVisitorType, type RulesetSource, SECTION_SLOTS, SESSION_VISITOR_COOKIE, SLOT_REPORT_SAMPLE_RATE, SLOT_REPORT_URL, SSR_SLOT_ATTR, SSR_SLOT_NAMES, STANDARD_EVENTS, type SectionSlotKey, type SsrDecision, type SsrOutcome, type SsrPayload, type SsrSlotRef, type StandardEvent, TRUEVAULT_CONSENT_COOKIE, type TrackScope, type TrackedEntry, type TrueVaultConsentOptions, VISITOR_COOKIE, addedLinesFrom, analyticsConsentFromCookie, armSlot, 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, isSlotKey, manifestUrl, matchTargetedPage, matchesPathPrefix, mergeAttributes, normalizeExposureList, onConsentChange, onConsentLoaded, playbookBackendUrl, playbookCartAttribute, playbookHeadSnippet, playbookHeadSnippetHtml, playbookTrack, prefetchRuleset, reconcileExperienceCartAttributes, reconcilePlaybookCartAttribute, renderedSlotKeys, reportPageSlots, revealScript, sanitizeManifestPages, sanitizeRuleset, sectionSlotKey, setNextAddSource, shopifyCustomerPrivacyConsent, slotFromSelector, slotMatches, slotSelector, 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
@@ -1,5 +1,5 @@
1
1
  import { jsxs, Fragment, jsx } from 'react/jsx-runtime';
2
- import { memo, createContext, Component, useContext, useMemo, useCallback, useState, useEffect, useSyncExternalStore, useRef } from 'react';
2
+ import { memo, createContext, isValidElement, Fragment as Fragment$1, Component, useContext, useMemo, useCallback, useState, useEffect, useSyncExternalStore, useLayoutEffect, useRef } from 'react';
3
3
 
4
4
  // src/growthbook.ts
5
5
  function hashFnv32a(str2) {
@@ -1072,6 +1072,44 @@ function hasOwnedPreviewParams(search) {
1072
1072
  return OWNED_PARAM_RE.test(search || "");
1073
1073
  }
1074
1074
 
1075
+ // src/slots.ts
1076
+ var SSR_SLOT_ATTR = "data-pb-slot";
1077
+ var SSR_SLOT_NAMES = [
1078
+ "buy-column-top",
1079
+ "after-add-to-cart",
1080
+ "under-size",
1081
+ "collection-grid-top",
1082
+ "after-home-hero"
1083
+ ];
1084
+ var SECTION_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
1085
+ var SECTION_KEY_RE = /^section:([A-Za-z0-9_-]{1,64}):(before|after)$/;
1086
+ var SLOT_KEY_MAX = 80;
1087
+ var SECTION_SLOTS = "section:*";
1088
+ function isSlotName(v) {
1089
+ return typeof v === "string" && SSR_SLOT_NAMES.includes(v);
1090
+ }
1091
+ function isSlotKey(v) {
1092
+ if (typeof v !== "string" || !v || v.length > SLOT_KEY_MAX) return false;
1093
+ return isSlotName(v) || SECTION_KEY_RE.test(v);
1094
+ }
1095
+ function isSectionSlotKey(v) {
1096
+ return typeof v === "string" && SECTION_KEY_RE.test(v);
1097
+ }
1098
+ function sectionSlotKey(id, side) {
1099
+ const v = typeof id === "string" || typeof id === "number" ? String(id).trim() : "";
1100
+ return SECTION_ID_RE.test(v) ? `section:${v}:${side}` : null;
1101
+ }
1102
+ function slotSelector(key) {
1103
+ return `[${SSR_SLOT_ATTR}="${key}"]`;
1104
+ }
1105
+ function slotFromSelector(selector) {
1106
+ if (typeof selector !== "string") return null;
1107
+ const m = /^\s*(?:template)?\[data-pb-slot=(?:"([^"]*)"|'([^']*)')\]\s*$/.exec(selector);
1108
+ if (!m) return null;
1109
+ const key = m[1] ?? m[2];
1110
+ return isSlotKey(key) ? key : null;
1111
+ }
1112
+
1075
1113
  // src/ssr.ts
1076
1114
  var SSR_SNAPSHOT_VERSION = 1;
1077
1115
  function ssrUrl(platformUrl, shopDomain) {
@@ -1106,31 +1144,77 @@ async function getSsrPayload(args) {
1106
1144
  }
1107
1145
  var PREVIEW_CODE_RE = /^[0-9A-HJKMNP-TV-Z]{4,8}$/;
1108
1146
  function previewCodeFromRequestUrl(url) {
1109
- const raw = url.searchParams.get("pb");
1110
- if (!raw) return null;
1111
- const code = raw.trim().toUpperCase();
1112
- return PREVIEW_CODE_RE.test(code) ? code : null;
1147
+ return normalizePreviewCode(url.searchParams.get("pb"));
1113
1148
  }
1114
- var PREVIEW_FETCH_BUDGET_MS = 1500;
1115
- async function getSsrPreviewPayload(args) {
1149
+ var PREVIEW_FETCH_BUDGET_MS = 5e3;
1150
+ var PREVIEW_ATTEMPT_BUDGET_MS = 3e3;
1151
+ var PREVIEW_RETRY_MIN_MS = 500;
1152
+ async function previewAttempt(url, timeoutMs, fetchImpl) {
1116
1153
  const controller = new AbortController();
1117
- const timer = setTimeout(() => controller.abort(), PREVIEW_FETCH_BUDGET_MS);
1154
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
1155
+ try {
1156
+ const res = await fetchImpl(url, { headers: { accept: "application/json" }, signal: controller.signal });
1157
+ if (!res.ok) return { payload: null, retry: res.status >= 500 };
1158
+ return { payload: sanitizeSsrPayload(await res.json()), retry: false };
1159
+ } catch {
1160
+ return { payload: null, retry: true };
1161
+ } finally {
1162
+ clearTimeout(timer);
1163
+ }
1164
+ }
1165
+ async function getSsrPreviewPayload(args) {
1118
1166
  try {
1119
1167
  const url = new URL(ssrUrl(args.platformUrl, args.shopDomain));
1120
1168
  url.searchParams.set("pb", args.code);
1121
- const res = await (args.fetchImpl ?? fetch)(url.toString(), {
1122
- headers: { accept: "application/json" },
1123
- signal: controller.signal
1124
- });
1125
- if (!res.ok) return null;
1126
- return sanitizeSsrPayload(await res.json());
1169
+ const budget = args.budgetMs ?? PREVIEW_FETCH_BUDGET_MS;
1170
+ const perAttempt = Math.min(args.attemptBudgetMs ?? PREVIEW_ATTEMPT_BUDGET_MS, budget);
1171
+ const fetchImpl = args.fetchImpl ?? fetch;
1172
+ const started = Date.now();
1173
+ const first = await previewAttempt(url.toString(), perAttempt, fetchImpl);
1174
+ if (first.payload || !first.retry) return first.payload;
1175
+ const left = budget - (Date.now() - started);
1176
+ if (left < Math.min(PREVIEW_RETRY_MIN_MS, budget / 4)) return null;
1177
+ return (await previewAttempt(url.toString(), left, fetchImpl)).payload;
1127
1178
  } catch {
1128
1179
  return null;
1129
- } finally {
1130
- clearTimeout(timer);
1131
1180
  }
1132
1181
  }
1133
- function decidePreviewSsr(payload, pageKey, matchesPage) {
1182
+ var PREVIEW_CODE_COOKIE = "_pb_preview_code";
1183
+ function normalizePreviewCode(raw) {
1184
+ if (!raw) return null;
1185
+ const code = raw.trim().toUpperCase();
1186
+ return PREVIEW_CODE_RE.test(code) ? code : null;
1187
+ }
1188
+ function isDataRequest(url) {
1189
+ return url.pathname.endsWith(".data");
1190
+ }
1191
+ function dataRequestPagePath(pathname) {
1192
+ if (!pathname.endsWith(".data")) return pathname;
1193
+ if (pathname === "/_root.data") return "/";
1194
+ return pathname.slice(0, -".data".length) || "/";
1195
+ }
1196
+ var PREVIEW_SESSION_STORAGE_KEY = "_pb_preview";
1197
+ function carriedPreviewAllowed(d) {
1198
+ if (!d?.preview) return false;
1199
+ if (!d.preview.carried) return true;
1200
+ if (typeof window === "undefined") return false;
1201
+ const code = d.preview.code;
1202
+ try {
1203
+ const live = window.__pbSsr;
1204
+ if (live?.preview?.code === code) return true;
1205
+ } catch {
1206
+ }
1207
+ try {
1208
+ const raw = window.sessionStorage?.getItem(PREVIEW_SESSION_STORAGE_KEY);
1209
+ if (!raw) return false;
1210
+ const s2 = JSON.parse(raw);
1211
+ if (typeof s2?.code !== "string" || s2.code.toUpperCase() !== code) return false;
1212
+ return typeof s2.expiresAt !== "string" || Date.parse(s2.expiresAt) > Date.now();
1213
+ } catch {
1214
+ return false;
1215
+ }
1216
+ }
1217
+ function decidePreviewSsr(payload, pageKey, matchesPage, carried = false) {
1134
1218
  const p = payload.preview;
1135
1219
  if (!p) return { skip: "preview-unresolved" };
1136
1220
  if (p.why) return { skip: `preview-${p.why}` };
@@ -1148,7 +1232,7 @@ function decidePreviewSsr(payload, pageKey, matchesPage) {
1148
1232
  arm: p.arm,
1149
1233
  snapshot: p.snapshot,
1150
1234
  page: { t, h },
1151
- preview: { code: p.code, testName: p.testName, armLabel: p.armLabel }
1235
+ preview: { code: p.code, testName: p.testName, armLabel: p.armLabel, ...carried ? { carried: true } : {} }
1152
1236
  }
1153
1237
  };
1154
1238
  }
@@ -1253,7 +1337,10 @@ function ssrHostInnerHtml(snapshot, page) {
1253
1337
  return `<template shadowrootmode="open"><style data-pb-ssr-snapshot>${BASE}</style><div data-pb-experience-root data-pb-ssr-snapshot>${nodes}</div></template>`;
1254
1338
  }
1255
1339
  function ssrStateScript(d) {
1256
- const state = {
1340
+ return `window.__pbSsr=${JSON.stringify(ssrStateObject(d)).replace(/</g, "\\u003c")};`;
1341
+ }
1342
+ function ssrStateObject(d) {
1343
+ return {
1257
1344
  experimentId: d.experimentId,
1258
1345
  armId: d.armId,
1259
1346
  experienceId: d.experienceId,
@@ -1265,13 +1352,30 @@ function ssrStateScript(d) {
1265
1352
  // A preview render: the SDK keeps it without resolving or recording.
1266
1353
  ...d.preview ? { preview: d.preview } : {}
1267
1354
  };
1268
- return `window.__pbSsr=${JSON.stringify(state).replace(/</g, "\\u003c")};`;
1355
+ }
1356
+ function armSlot(a) {
1357
+ if (!a) return null;
1358
+ return isSlotKey(a.slot) ? a.slot : slotFromSelector(a.s);
1269
1359
  }
1270
1360
  function slotMatches(d, slot) {
1271
1361
  const a = d.arm.a;
1272
1362
  if (!a) return false;
1363
+ if (typeof slot.name === "string" && slot.name) {
1364
+ const key = armSlot(a);
1365
+ if (!key) return false;
1366
+ return slot.name === SECTION_SLOTS ? isSectionSlotKey(key) : key === slot.name;
1367
+ }
1368
+ if (typeof slot.anchor !== "string") return false;
1273
1369
  return a.s.trim() === slot.anchor.trim() && a.p === (slot.position ?? "after");
1274
1370
  }
1371
+ function toSlotRef(decl) {
1372
+ return typeof decl === "string" ? { name: decl } : decl;
1373
+ }
1374
+ function declaredSlotFor(d, refs) {
1375
+ if (refs.some((r) => typeof r.name === "string" && r.name && slotMatches(d, r))) return "slot";
1376
+ if (refs.some((r) => !r.name && slotMatches(d, r))) return "anchor";
1377
+ return null;
1378
+ }
1275
1379
 
1276
1380
  // src/request-context.ts
1277
1381
  var FINALIZE_WAIT_MS = 2e3;
@@ -1305,6 +1409,33 @@ function createPlaybookContext({
1305
1409
  const platformUrl = platformUrlOption || str(e.PLAYBOOK_PLATFORM_URL) || DEFAULT_PLATFORM_URL;
1306
1410
  let promise = null;
1307
1411
  let settled = false;
1412
+ const requestUrl = (() => {
1413
+ try {
1414
+ return new URL(request.url);
1415
+ } catch {
1416
+ return null;
1417
+ }
1418
+ })();
1419
+ const isGet = request.method === "GET";
1420
+ const isData = !!requestUrl && isDataRequest(requestUrl);
1421
+ const urlCode = requestUrl ? previewCodeFromRequestUrl(requestUrl) : null;
1422
+ const carryCookieRaw = isGet ? parseCookies(request.headers.get("cookie"))[PREVIEW_CODE_COOKIE] : void 0;
1423
+ const carryCode = normalizePreviewCode(carryCookieRaw);
1424
+ const previewCode = shopId && isGet && ssrSlots.length > 0 ? isData ? urlCode ?? carryCode : urlCode : null;
1425
+ const extraCookies = [];
1426
+ const secure = requestUrl?.protocol === "https:";
1427
+ const setCarry = (code) => extraCookies.push(serializeCookie(PREVIEW_CODE_COOKIE, code, { httpOnly: true, secure }));
1428
+ const clearCarry = () => extraCookies.push(serializeCookie(PREVIEW_CODE_COOKIE, "", { httpOnly: true, secure, maxAge: 0 }));
1429
+ if (shopId && isGet && !isData && !urlCode && carryCookieRaw !== void 0) clearCarry();
1430
+ let previewFetch = null;
1431
+ const previewPayload = () => {
1432
+ if (!previewFetch) {
1433
+ const shopDomain = requestUrl ? normalizeDomain(shopDomainOption ?? str(e.PUBLIC_PLAYBOOK_SHOP_DOMAIN) ?? requestUrl.hostname) : "";
1434
+ previewFetch = previewCode && shopDomain ? getSsrPreviewPayload({ platformUrl, shopDomain, code: previewCode, fetchImpl }).catch(() => null) : Promise.resolve(null);
1435
+ }
1436
+ return previewFetch;
1437
+ };
1438
+ if (previewCode) void previewPayload();
1308
1439
  if (shopId && request.method === "GET") {
1309
1440
  try {
1310
1441
  prefetchRuleset({ platformUrl, shopId, waitUntil, fetchImpl });
@@ -1396,23 +1527,31 @@ function createPlaybookContext({
1396
1527
  return cloakPromise;
1397
1528
  };
1398
1529
  let ssrRendered = false;
1530
+ const noStore = () => ssrRendered || !!previewCode;
1531
+ const slotRefs = ssrSlots.map(toSlotRef);
1399
1532
  let ssrPromise = null;
1400
1533
  const ssrFor = (cloak) => {
1401
1534
  if (!ssrPromise) {
1402
1535
  ssrPromise = (async () => {
1403
1536
  if (ssrSlots.length === 0) return { ssr: null, skip: null };
1404
- const url = new URL(request.url);
1405
- const code = request.method === "GET" && !url.pathname.endsWith(".data") ? previewCodeFromRequestUrl(url) : null;
1406
- if (code && shopId) {
1407
- const shopDomain = normalizeDomain(shopDomainOption ?? str(e.PUBLIC_PLAYBOOK_SHOP_DOMAIN) ?? url.hostname);
1408
- if (!shopDomain) return { ssr: null, skip: "preview-no-shop" };
1409
- const payload2 = await getSsrPreviewPayload({ platformUrl, shopDomain, code, fetchImpl });
1537
+ if (previewCode && requestUrl) {
1538
+ const payload2 = await previewPayload();
1410
1539
  if (!payload2) return { ssr: null, skip: "preview-unavailable" };
1411
- const pageKey = targetPageKey(url.pathname);
1412
- const out2 = decidePreviewSsr(payload2, pageKey, (pages) => matchTargetedPage(pages, url.pathname) !== null);
1540
+ if (!payload2.preview) {
1541
+ if (carryCookieRaw !== void 0 && (carryCode === previewCode || !carryCode)) clearCarry();
1542
+ } else if (!isData && carryCode !== previewCode) {
1543
+ setCarry(previewCode);
1544
+ }
1545
+ const pagePath = dataRequestPagePath(requestUrl.pathname);
1546
+ const pageKey = targetPageKey(pagePath);
1547
+ const out2 = decidePreviewSsr(payload2, pageKey, (pages) => matchTargetedPage(pages, pagePath) !== null, isData);
1413
1548
  if ("skip" in out2) return { ssr: null, skip: out2.skip };
1414
- const d2 = out2.decision;
1415
- if (d2.experienceId && !ssrSlots.some((s2) => slotMatches(d2, s2))) return { ssr: null, skip: "preview-no-slot" };
1549
+ let d2 = out2.decision;
1550
+ if (d2.experienceId) {
1551
+ const via = declaredSlotFor(d2, slotRefs);
1552
+ if (!via) return { ssr: null, skip: "preview-no-slot" };
1553
+ d2 = { ...d2, matchedBy: via };
1554
+ }
1416
1555
  ssrRendered = true;
1417
1556
  return { ssr: d2, skip: null };
1418
1557
  }
@@ -1429,8 +1568,12 @@ function createPlaybookContext({
1429
1568
  fallbackVisitorId: own
1430
1569
  });
1431
1570
  if ("skip" in out) return { ssr: null, skip: out.skip };
1432
- const d = out.decision;
1433
- if (d.experienceId && !ssrSlots.some((s2) => slotMatches(d, s2))) return { ssr: null, skip: "no-slot" };
1571
+ let d = out.decision;
1572
+ if (d.experienceId) {
1573
+ const via = declaredSlotFor(d, slotRefs);
1574
+ if (!via) return { ssr: null, skip: "no-slot" };
1575
+ d = { ...d, matchedBy: via };
1576
+ }
1434
1577
  ssrRendered = true;
1435
1578
  return { ssr: d, skip: null };
1436
1579
  })().catch(() => ({ ssr: null, skip: "error" }));
@@ -1490,26 +1633,28 @@ function createPlaybookContext({
1490
1633
  },
1491
1634
  async appendCookies(headers) {
1492
1635
  try {
1493
- append(headers, await cookiesFor(FINALIZE_WAIT_MS));
1494
- if (ssrRendered) headers.set("Cache-Control", "private, no-store");
1636
+ append(headers, [...await cookiesFor(FINALIZE_WAIT_MS), ...extraCookies]);
1637
+ if (noStore()) headers.set("Cache-Control", "private, no-store");
1495
1638
  } catch {
1496
1639
  }
1497
1640
  },
1498
1641
  async finalize(response) {
1499
1642
  try {
1500
1643
  const isRedirect = response.status >= 300 && response.status < 400;
1501
- const cookies = await cookiesFor(
1502
- isRedirect ? FINALIZE_REDIRECT_WAIT_MS : FINALIZE_WAIT_MS
1503
- );
1504
- if (!cookies.length && !ssrRendered) return response;
1644
+ const cookies = [
1645
+ ...await cookiesFor(isRedirect ? FINALIZE_REDIRECT_WAIT_MS : FINALIZE_WAIT_MS),
1646
+ ...extraCookies
1647
+ ];
1648
+ const privateResponse = noStore();
1649
+ if (!cookies.length && !privateResponse) return response;
1505
1650
  try {
1506
1651
  append(response.headers, cookies);
1507
- if (ssrRendered) response.headers.set("Cache-Control", "private, no-store");
1652
+ if (privateResponse) response.headers.set("Cache-Control", "private, no-store");
1508
1653
  return response;
1509
1654
  } catch {
1510
1655
  const headers = new Headers(response.headers);
1511
1656
  append(headers, cookies);
1512
- if (ssrRendered) headers.set("Cache-Control", "private, no-store");
1657
+ if (privateResponse) headers.set("Cache-Control", "private, no-store");
1513
1658
  return new Response(response.body, {
1514
1659
  status: response.status,
1515
1660
  statusText: response.statusText,
@@ -1707,32 +1852,204 @@ function playbookHeadSnippetHtml(cloak, options = {}) {
1707
1852
  const attrs = Object.entries(parts.sdk.attrs).map(([k, v]) => ` ${k}="${escapeAttr(v)}"`).join("");
1708
1853
  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>`;
1709
1854
  }
1710
- function PlaybookSsrHead({ ssr, nonce }) {
1855
+ var useIsoLayoutEffect = typeof window === "undefined" ? useEffect : useLayoutEffect;
1856
+ function renderable(ssr) {
1711
1857
  if (!ssr) return null;
1712
- const hide = ssr.experienceId ? (ssr.arm.hide || []).map((s2) => `${s2}{display:none!important}`).join("") : "";
1858
+ if (ssr.preview?.carried && !carriedPreviewAllowed(ssr)) return null;
1859
+ return ssr;
1860
+ }
1861
+ function PlaybookSsrHead({ ssr, nonce }) {
1862
+ const d = renderable(ssr);
1863
+ const carried = !!d?.preview?.carried;
1864
+ const stateKey = carried && d ? `${d.experimentId}:${d.armId}:${d.page.t}:${d.page.h}` : null;
1865
+ useIsoLayoutEffect(() => {
1866
+ if (!carried || !d) return;
1867
+ try {
1868
+ window.__pbSsr = ssrStateObject(d);
1869
+ } catch {
1870
+ }
1871
+ }, [stateKey]);
1872
+ if (!d) return null;
1873
+ const hide = d.experienceId ? (d.arm.hide || []).map((s2) => `${s2}{display:none!important}`).join("") : "";
1713
1874
  return /* @__PURE__ */ jsxs(Fragment, { children: [
1714
- /* @__PURE__ */ jsx("script", { nonce, "data-pb-ssr-state": "", dangerouslySetInnerHTML: { __html: ssrStateScript(ssr) } }),
1875
+ carried ? null : /* @__PURE__ */ jsx("script", { nonce, "data-pb-ssr-state": "", dangerouslySetInnerHTML: { __html: ssrStateScript(d) } }),
1715
1876
  hide ? /* @__PURE__ */ jsx("style", { id: "pb-ssr-hide", nonce, dangerouslySetInnerHTML: { __html: escStyle(hide) } }) : null
1716
1877
  ] });
1717
1878
  }
1718
- function PlaybookSlot({
1719
- ssr,
1720
- anchor,
1721
- position = "after"
1722
- }) {
1723
- if (!ssr || !ssr.experienceId || !ssr.snapshot || !slotMatches(ssr, { anchor, position })) return null;
1879
+ function attachDeclarativeShadow(host) {
1880
+ if (host.shadowRoot) return true;
1881
+ const tpl = Array.from(host.children).find(
1882
+ (c) => c.tagName === "TEMPLATE" && c.hasAttribute("shadowrootmode")
1883
+ );
1884
+ if (!tpl) return false;
1885
+ try {
1886
+ const root = host.attachShadow({ mode: "open" });
1887
+ root.appendChild(host.ownerDocument.importNode(tpl.content, true));
1888
+ tpl.remove();
1889
+ root.querySelectorAll("template[shadowrootmode]").forEach((t) => {
1890
+ if (t.parentElement) attachDeclarativeShadow(t.parentElement);
1891
+ });
1892
+ return true;
1893
+ } catch {
1894
+ return false;
1895
+ }
1896
+ }
1897
+ function ssrHostRef(el) {
1898
+ if (el) attachDeclarativeShadow(el);
1899
+ }
1900
+ function SsrHost({ ssr }) {
1724
1901
  return /* @__PURE__ */ jsx(
1725
1902
  "div",
1726
1903
  {
1904
+ ref: ssrHostRef,
1727
1905
  id: "pb-experience-root",
1728
1906
  "data-pb-experience-mount": "",
1729
1907
  "data-pb-ssr": ssr.experimentId,
1730
1908
  style: { display: "block", boxSizing: "border-box", maxWidth: "100%" },
1731
1909
  suppressHydrationWarning: true,
1732
1910
  dangerouslySetInnerHTML: { __html: ssrHostInnerHtml(ssr.snapshot, ssr.page) }
1733
- }
1911
+ },
1912
+ `${ssr.experimentId}:${ssr.armId}:${ssr.page.t}:${ssr.page.h}`
1734
1913
  );
1735
1914
  }
1915
+ function PlaybookSlot(props) {
1916
+ const ssr = renderable(props.ssr);
1917
+ if (typeof props.name === "string") {
1918
+ const key = props.name;
1919
+ if (!isSlotKey(key)) return null;
1920
+ const marker = /* @__PURE__ */ jsx("template", { "data-pb-slot": key });
1921
+ const hit = !!ssr && !!ssr.experienceId && !!ssr.snapshot && ssr.matchedBy !== "anchor" && slotMatches(ssr, { name: key });
1922
+ if (!hit) return marker;
1923
+ return ssr.arm.a?.p === "before" ? /* @__PURE__ */ jsxs(Fragment, { children: [
1924
+ /* @__PURE__ */ jsx(SsrHost, { ssr }),
1925
+ marker
1926
+ ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
1927
+ marker,
1928
+ /* @__PURE__ */ jsx(SsrHost, { ssr })
1929
+ ] });
1930
+ }
1931
+ if (!ssr || !ssr.experienceId || !ssr.snapshot || typeof props.anchor !== "string") return null;
1932
+ if (ssr.matchedBy === "slot") return null;
1933
+ if (!slotMatches(ssr, { anchor: props.anchor, position: props.position ?? "after" })) return null;
1934
+ return /* @__PURE__ */ jsx(SsrHost, { ssr });
1935
+ }
1936
+ function keyOf(el) {
1937
+ if (!isValidElement(el) || el.key == null) return null;
1938
+ return String(el.key);
1939
+ }
1940
+ function PlaybookSections({
1941
+ ssr,
1942
+ sections,
1943
+ sectionId
1944
+ }) {
1945
+ if (!sections?.length) return null;
1946
+ return /* @__PURE__ */ jsx(Fragment, { children: sections.map((el, index) => {
1947
+ if (el == null || el === false) return null;
1948
+ const id = (isValidElement(el) && sectionId ? sectionId(el, index) : null) ?? keyOf(el);
1949
+ const before = id ? sectionSlotKey(id, "before") : null;
1950
+ const after = id ? sectionSlotKey(id, "after") : null;
1951
+ const key = id ?? `pb-section-${index}`;
1952
+ if (!before || !after) return /* @__PURE__ */ jsx(Fragment$1, { children: el }, key);
1953
+ return /* @__PURE__ */ jsxs(Fragment$1, { children: [
1954
+ /* @__PURE__ */ jsx(PlaybookSlot, { ssr, name: before }),
1955
+ el,
1956
+ /* @__PURE__ */ jsx(PlaybookSlot, { ssr, name: after })
1957
+ ] }, key);
1958
+ }) });
1959
+ }
1960
+
1961
+ // src/slot-report.ts
1962
+ var SLOT_REPORT_URL = "/apps/playbook/api/storefront/ssr/slots";
1963
+ var SLOT_REPORT_SAMPLE_RATE = 0.1;
1964
+ var SLOT_REPORT_TTL_MS = 24 * 60 * 60 * 1e3;
1965
+ var SLOT_REPORT_MAX_SLOTS = 100;
1966
+ var STORAGE_PREFIX = "_pb_slots:";
1967
+ function renderedSlotKeys(root) {
1968
+ const out = [];
1969
+ try {
1970
+ for (const el of Array.from(root.querySelectorAll(`[${SSR_SLOT_ATTR}]`))) {
1971
+ const key = el.getAttribute(SSR_SLOT_ATTR);
1972
+ if (isSlotKey(key) && !out.includes(key)) out.push(key);
1973
+ if (out.length >= SLOT_REPORT_MAX_SLOTS) break;
1974
+ }
1975
+ } catch {
1976
+ }
1977
+ return out;
1978
+ }
1979
+ function slotReportScope(pageKey) {
1980
+ const type = pageKey.split(":")[0];
1981
+ return type === "product" || type === "collection" ? `${type}:*` : pageKey;
1982
+ }
1983
+ function slotListSignature(slots) {
1984
+ const s2 = [...slots].sort().join("|");
1985
+ let h = 2166136261;
1986
+ for (let i = 0; i < s2.length; i++) {
1987
+ h ^= s2.charCodeAt(i);
1988
+ h = Math.imul(h, 16777619);
1989
+ }
1990
+ return (h >>> 0).toString(36);
1991
+ }
1992
+ function shouldReportSlots(input) {
1993
+ if (!input.slots.length) return false;
1994
+ const sig = slotListSignature(input.slots);
1995
+ try {
1996
+ const raw = input.storage?.getItem(STORAGE_PREFIX + input.scope);
1997
+ if (raw) {
1998
+ const [prevSig, at] = raw.split("|");
1999
+ if (prevSig === sig && input.now - Number(at) < SLOT_REPORT_TTL_MS) return false;
2000
+ }
2001
+ } catch {
2002
+ }
2003
+ return input.random < input.sampleRate;
2004
+ }
2005
+ function rememberSlotReport(storage, scope, slots, now) {
2006
+ try {
2007
+ storage?.setItem(STORAGE_PREFIX + scope, `${slotListSignature(slots)}|${now}`);
2008
+ } catch {
2009
+ }
2010
+ }
2011
+ function slotReportBody(shopId, pageKey, slots) {
2012
+ return JSON.stringify({ shopId, page: pageKey, slots: slots.slice(0, SLOT_REPORT_MAX_SLOTS) });
2013
+ }
2014
+ function localStore() {
2015
+ try {
2016
+ return window.localStorage;
2017
+ } catch {
2018
+ return null;
2019
+ }
2020
+ }
2021
+ function reportPageSlots(input) {
2022
+ try {
2023
+ if (!input.shopId) return false;
2024
+ const pageKey = targetPageKey(input.pathname);
2025
+ if (!pageKey) return false;
2026
+ const slots = renderedSlotKeys(input.root ?? document);
2027
+ const storage = input.storage === void 0 ? localStore() : input.storage;
2028
+ const now = (input.now ?? Date.now)();
2029
+ const scope = slotReportScope(pageKey);
2030
+ const go = shouldReportSlots({
2031
+ scope,
2032
+ slots,
2033
+ now,
2034
+ random: (input.random ?? Math.random)(),
2035
+ sampleRate: input.sampleRate ?? SLOT_REPORT_SAMPLE_RATE,
2036
+ storage
2037
+ });
2038
+ if (!go) return false;
2039
+ rememberSlotReport(storage, scope, slots, now);
2040
+ const f = input.fetchImpl ?? fetch;
2041
+ void f(input.url ?? SLOT_REPORT_URL, {
2042
+ method: "POST",
2043
+ headers: { "content-type": "application/json" },
2044
+ body: slotReportBody(input.shopId, pageKey, slots),
2045
+ keepalive: true,
2046
+ credentials: "omit"
2047
+ }).catch(() => void 0);
2048
+ return true;
2049
+ } catch {
2050
+ return false;
2051
+ }
2052
+ }
1736
2053
  var PlaybookBoundary = class extends Component {
1737
2054
  state = { failed: false };
1738
2055
  static getDerivedStateFromError() {
@@ -2953,6 +3270,19 @@ function PlaybookAAExposure({ testKey = AA_SITEWIDE_TEST }) {
2953
3270
  const ref = usePlaybookExposure(testKey, variant);
2954
3271
  return /* @__PURE__ */ jsx("span", { ref, "aria-hidden": "true", style: SENTINEL_STYLE });
2955
3272
  }
3273
+ var SLOT_REPORT_DELAY_MS = 1500;
3274
+ function SlotReport({
3275
+ shopId,
3276
+ pathname,
3277
+ options
3278
+ }) {
3279
+ const { sampleRate, url } = options;
3280
+ useEffect(() => {
3281
+ const timer = setTimeout(() => reportPageSlots({ shopId, pathname, sampleRate, url }), SLOT_REPORT_DELAY_MS);
3282
+ return () => clearTimeout(timer);
3283
+ }, [shopId, pathname, sampleRate, url]);
3284
+ return null;
3285
+ }
2956
3286
  function Engagement({ pathname, enabled }) {
2957
3287
  usePageEngagement(pathname, enabled);
2958
3288
  return null;
@@ -2973,10 +3303,12 @@ function PlaybookRoot({
2973
3303
  exposureUrl,
2974
3304
  eventUrl,
2975
3305
  supportedEvents,
3306
+ slotReport = true,
2976
3307
  children
2977
3308
  }) {
2978
3309
  const hydrated = useHydrated();
2979
3310
  const enabled = !!state?.enabled;
3311
+ const slotReportOptions = slotReport === false ? null : slotReport === true ? {} : slotReport;
2980
3312
  return /* @__PURE__ */ jsxs(
2981
3313
  PlaybookProvider,
2982
3314
  {
@@ -3002,6 +3334,7 @@ function PlaybookRoot({
3002
3334
  }
3003
3335
  ) }),
3004
3336
  state?.previewToken && /* @__PURE__ */ jsx(PlaybookBoundary, { name: "preview param", children: /* @__PURE__ */ jsx(PreviewParam, { location, navigate }) }),
3337
+ enabled && state?.shopId && slotReportOptions && !editorPreview && /* @__PURE__ */ jsx(PlaybookBoundary, { name: "slot report", children: /* @__PURE__ */ jsx(SlotReport, { shopId: state.shopId, pathname: location.pathname, options: slotReportOptions }) }),
3005
3338
  enabled && aaSentinel && !editorPreview && /* @__PURE__ */ jsx(PlaybookBoundary, { name: "aa sentinel", children: /* @__PURE__ */ jsx(PlaybookAAExposure, {}) }),
3006
3339
  /* @__PURE__ */ jsx(PlaybookBoundary, { name: "debug panel", children: /* @__PURE__ */ jsx(
3007
3340
  PlaybookDebugPanel,
@@ -3203,4 +3536,4 @@ function trackAddToCartLines(lines, cartLines, source) {
3203
3536
  }
3204
3537
  }
3205
3538
 
3206
- 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 };
3539
+ 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, PREVIEW_ATTEMPT_BUDGET_MS, PREVIEW_CODE_COOKIE, PREVIEW_FETCH_BUDGET_MS, PlaybookAAExposure, PlaybookBoundary, PlaybookCloakHead, PlaybookDebugPanel, PlaybookExposure, PlaybookHead, PlaybookProvider, PlaybookRoot, PlaybookSections, PlaybookSlot, PlaybookSsrHead, SECTION_SLOTS, SESSION_VISITOR_COOKIE, SLOT_REPORT_SAMPLE_RATE, SLOT_REPORT_URL, SSR_SLOT_ATTR, SSR_SLOT_NAMES, STANDARD_EVENTS, TRUEVAULT_CONSENT_COOKIE, VISITOR_COOKIE, addedLinesFrom, analyticsConsentFromCookie, armSlot, 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, isSlotKey, manifestUrl, matchTargetedPage, matchesPathPrefix, mergeAttributes, normalizeExposureList, onConsentChange, onConsentLoaded, playbookBackendUrl, playbookCartAttribute, playbookHeadSnippet, playbookHeadSnippetHtml, playbookTrack, prefetchRuleset, reconcileExperienceCartAttributes, reconcilePlaybookCartAttribute, renderedSlotKeys, reportPageSlots, revealScript, sanitizeManifestPages, sanitizeRuleset, sectionSlotKey, setNextAddSource, shopifyCustomerPrivacyConsent, slotFromSelector, slotMatches, slotSelector, 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.7.1",
3
+ "version": "0.8.1",
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.",