@heyplaybook/hydrogen 0.8.1 → 0.9.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/dist/index.d.ts CHANGED
@@ -479,6 +479,30 @@ 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.9.0: product-field tokens (`{{product.rating}}`, `{{product.model_line}}`,
484
+ * …) in a server-rendered arm — a VENDORED copy of the fill in the platform's
485
+ * `shared/src/editor-protocol/product-fields.ts` (the package can't import the
486
+ * monorepo's internal packages). `__tests__/product-fields.test.ts` fails if
487
+ * the two drift: the browser SDK adopts the server's markup, so both must
488
+ * produce the same bytes for the same product.
489
+ *
490
+ * A token names a fact of the page's product; the platform reads the values
491
+ * (`/api/storefront/product-fields`) and this fills them in. A token with no
492
+ * value for the product hides its element (the nearest `data-pb-field`
493
+ * element, else the innermost one): `data-pb-field-missing` plus an inline
494
+ * `display:none !important`. Values are HTML-escaped.
495
+ */
496
+ type ProductFields = Record<string, string>;
497
+ declare const PRODUCT_FIELD_MISSING_ATTR = "data-pb-field-missing";
498
+ declare function productTokensIn(html: unknown): string[];
499
+ interface FillResult {
500
+ html: string;
501
+ used: string[];
502
+ missing: string[];
503
+ }
504
+ declare function fillProductTokens(html: string, fields: ProductFields | null | undefined): FillResult;
505
+
482
506
  /**
483
507
  * 0.8.0: the server-render slot vocabulary — a VENDORED copy of the
484
508
  * platform's `shared/src/editor-protocol/ssr-slots.ts` (the package can't
@@ -528,6 +552,13 @@ interface SsrSnapshotNode {
528
552
  interface SsrSnapshot {
529
553
  v: number;
530
554
  nodes: SsrSnapshotNode[];
555
+ /**
556
+ * 0.9.0: the product-field tokens the markup names (`rating`,
557
+ * `model_line`, …). The platform sends a snapshot with tokens only to a
558
+ * package that asked for them (`fields=1` on the doc URL); the package
559
+ * reads the page product's values and fills them before rendering.
560
+ */
561
+ pf?: string[];
531
562
  }
532
563
  interface SsrArm {
533
564
  id: string;
@@ -584,6 +615,22 @@ interface SsrPreview {
584
615
  why: string | null;
585
616
  }
586
617
  declare function ssrUrl(platformUrl: string, shopDomain: string): string;
618
+ /** 0.9.0: the platform's read of one product's field values for one design. */
619
+ declare function productFieldsUrl(platformUrl: string, shopDomain: string, experienceId: string, handle: string): string;
620
+ /** The decision with its snapshot's tokens filled (`./product-fields`); a missing value hides its element. */
621
+ declare function fillSsrDecision(d: SsrDecision, fields: ProductFields | null): SsrDecision;
622
+ /**
623
+ * 0.9.0: fill a decision's product-field tokens before it renders. A product
624
+ * page reads its product's values; any other page has no product, so every
625
+ * token's element is hidden. `{skip}` when the values couldn't be read in
626
+ * time (the browser path draws the arm instead, filled by the platform).
627
+ */
628
+ declare function withProductFields(d: SsrDecision, args: {
629
+ platformUrl: string;
630
+ shopDomain: string;
631
+ waitUntil?: (p: Promise<unknown>) => void;
632
+ fetchImpl?: typeof fetch;
633
+ }): Promise<SsrOutcome>;
587
634
  /** The shop's SSR doc, or null when the read isn't healthy (then: cloak only). Never throws. */
588
635
  declare function getSsrPayload(args: {
589
636
  platformUrl: string;
@@ -606,9 +653,9 @@ declare const PREVIEW_ATTEMPT_BUDGET_MS = 3000;
606
653
  * navigations. The browser strips `?pb=` from the address bar once it has
607
654
  * resolved the code, so React Router's `.data` requests for later pages don't
608
655
  * 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.
656
+ * is valid; honoured ONLY on `.data` requests; cleared by any full page
657
+ * load without `?pb=` (Exit reloads, a new tab, a typed URL — see
658
+ * `isDocumentRequest`), so it can't follow anyone out of the preview.
612
659
  */
613
660
  declare const PREVIEW_CODE_COOKIE = "_pb_preview_code";
614
661
  /**
@@ -1557,4 +1604,4 @@ declare function inNamespace(hashValue: string, namespace: [string, number, numb
1557
1604
  declare function chooseVariation(n: number, ranges: VariationRange[]): number;
1558
1605
  declare function getBucketRanges(numVariations: number, coverage: number | undefined, weights?: number[]): VariationRange[];
1559
1606
 
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 };
1607
+ 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, PRODUCT_FIELD_MISSING_ATTR, 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 ProductFields, 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, fillProductTokens, fillSsrDecision, 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, productFieldsUrl, productTokensIn, 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, withProductFields };
package/dist/index.js CHANGED
@@ -1110,13 +1110,200 @@ function slotFromSelector(selector) {
1110
1110
  return isSlotKey(key) ? key : null;
1111
1111
  }
1112
1112
 
1113
+ // src/product-fields.ts
1114
+ var PRODUCT_FIELD_MISSING_ATTR = "data-pb-field-missing";
1115
+ var SEGMENT = /^[A-Za-z0-9_-]{1,64}$/;
1116
+ var TOKEN_RE = /\{\{\s*product\.([A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+){0,2})\s*\}\}/g;
1117
+ function mayHaveProductTokens(html) {
1118
+ return typeof html === "string" && html.includes("{{") && /\{\{\s*product\./.test(html);
1119
+ }
1120
+ function normalizeFieldPath(raw) {
1121
+ const parts = raw.split(".");
1122
+ if (!parts.every((p) => SEGMENT.test(p))) return null;
1123
+ const head = parts[0].toLowerCase();
1124
+ if (head === "metafield") return parts.length === 3 ? `metafield.${parts[1]}.${parts[2]}` : null;
1125
+ if (head === "detail") return parts.length === 2 ? `detail.${parts[1].toLowerCase().replace(/-/g, "_")}` : null;
1126
+ return parts.length === 1 ? head : null;
1127
+ }
1128
+ function productTokensIn(html) {
1129
+ if (!mayHaveProductTokens(html)) return [];
1130
+ const out = [];
1131
+ for (const m of html.matchAll(TOKEN_RE)) {
1132
+ const path = normalizeFieldPath(m[1]);
1133
+ if (path && !out.includes(path)) out.push(path);
1134
+ }
1135
+ return out;
1136
+ }
1137
+ var escapeHtml = (s2) => s2.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
1138
+ var VOID = /* @__PURE__ */ new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"]);
1139
+ var GROUP_RE = /\sdata-pb-field(?=[\s=/>]|$)/i;
1140
+ function hideTag(tag) {
1141
+ if (tag.includes(PRODUCT_FIELD_MISSING_ATTR)) return tag;
1142
+ const name = /^<[A-Za-z][A-Za-z0-9-]*/.exec(tag)?.[0] ?? "";
1143
+ if (!name) return tag;
1144
+ let rest = tag.slice(name.length);
1145
+ const style = /(\sstyle\s*=\s*)("([^"]*)"|'([^']*)')/i.exec(rest);
1146
+ if (style) {
1147
+ const quote = style[2][0];
1148
+ const value = style[3] ?? style[4] ?? "";
1149
+ rest = rest.slice(0, style.index) + `${style[1]}${quote}display:none !important;${value}${quote}` + rest.slice(style.index + style[0].length);
1150
+ return `${name} ${PRODUCT_FIELD_MISSING_ATTR}=""${rest}`;
1151
+ }
1152
+ return `${name} ${PRODUCT_FIELD_MISSING_ATTR}="" style="display:none !important"${rest}`;
1153
+ }
1154
+ function tagEnd(html, i) {
1155
+ let quote = null;
1156
+ for (let j = i + 1; j < html.length; j++) {
1157
+ const c = html[j];
1158
+ if (quote) {
1159
+ if (c === quote) quote = null;
1160
+ } else if (c === '"' || c === "'") quote = c;
1161
+ else if (c === ">") return j;
1162
+ }
1163
+ return -1;
1164
+ }
1165
+ function fillProductTokens(html, fields) {
1166
+ if (typeof html !== "string" || !mayHaveProductTokens(html)) return { html: typeof html === "string" ? html : "", used: [], missing: [] };
1167
+ const used = [];
1168
+ const missing = [];
1169
+ const valueOf = (raw) => {
1170
+ const path = normalizeFieldPath(raw);
1171
+ if (path && !used.includes(path)) used.push(path);
1172
+ const v = path && fields ? fields[path] : void 0;
1173
+ const ok = typeof v === "string" && v.trim().length > 0;
1174
+ if (!ok && path && !missing.includes(path)) missing.push(path);
1175
+ return ok ? v.trim() : null;
1176
+ };
1177
+ const fillRun = (run) => {
1178
+ let missed = false;
1179
+ const text = run.replace(TOKEN_RE, (_m, raw) => {
1180
+ const v = valueOf(raw);
1181
+ if (v == null) {
1182
+ missed = true;
1183
+ return "";
1184
+ }
1185
+ return escapeHtml(v);
1186
+ });
1187
+ return { text, missed };
1188
+ };
1189
+ const out = [];
1190
+ const stack = [];
1191
+ const hidden = /* @__PURE__ */ new Set();
1192
+ const hideFor = (self) => {
1193
+ const chain = self ? [...stack, self] : stack;
1194
+ for (let k = chain.length - 1; k >= 0; k--) {
1195
+ if (chain[k].group) {
1196
+ hidden.add(chain[k].slot);
1197
+ return;
1198
+ }
1199
+ }
1200
+ const target = self ?? stack[stack.length - 1];
1201
+ if (target) hidden.add(target.slot);
1202
+ };
1203
+ let i = 0;
1204
+ while (i < html.length) {
1205
+ const lt = html.indexOf("<", i);
1206
+ const textEnd = lt === -1 ? html.length : lt;
1207
+ if (textEnd > i) {
1208
+ const { text: text2, missed: missed2 } = fillRun(html.slice(i, textEnd));
1209
+ out.push(text2);
1210
+ if (missed2) hideFor(null);
1211
+ i = textEnd;
1212
+ continue;
1213
+ }
1214
+ if (html.startsWith("<!--", i)) {
1215
+ const end2 = html.indexOf("-->", i + 4);
1216
+ const stop = end2 === -1 ? html.length : end2 + 3;
1217
+ out.push(html.slice(i, stop));
1218
+ i = stop;
1219
+ continue;
1220
+ }
1221
+ const close = /^<\/([A-Za-z][A-Za-z0-9-]*)[^>]*>/.exec(html.slice(i, i + 200));
1222
+ if (close) {
1223
+ const name2 = close[1].toLowerCase();
1224
+ const at = stack.map((t) => t.name).lastIndexOf(name2);
1225
+ if (at !== -1) stack.length = at;
1226
+ out.push(close[0]);
1227
+ i += close[0].length;
1228
+ continue;
1229
+ }
1230
+ if (!/[A-Za-z]/.test(html[i + 1] ?? "")) {
1231
+ out.push("<");
1232
+ i += 1;
1233
+ continue;
1234
+ }
1235
+ const end = tagEnd(html, i);
1236
+ if (end === -1) {
1237
+ out.push(fillRun(html.slice(i)).text);
1238
+ break;
1239
+ }
1240
+ const raw = html.slice(i, end + 1);
1241
+ const name = (/^<([A-Za-z][A-Za-z0-9-]*)/.exec(raw)?.[1] ?? "").toLowerCase();
1242
+ const { text, missed } = fillRun(raw);
1243
+ const tag = { name, slot: out.length, group: GROUP_RE.test(raw) };
1244
+ out.push(text);
1245
+ if (missed) hideFor(tag);
1246
+ if (!VOID.has(name) && !/\/\s*>$/.test(raw)) stack.push(tag);
1247
+ i = end + 1;
1248
+ }
1249
+ for (const slot of hidden) out[slot] = hideTag(out[slot]);
1250
+ return { html: out.join(""), used, missing };
1251
+ }
1252
+
1113
1253
  // src/ssr.ts
1114
1254
  var SSR_SNAPSHOT_VERSION = 1;
1115
1255
  function ssrUrl(platformUrl, shopDomain) {
1116
1256
  const url = new URL("/api/storefront/ssr", platformUrl);
1117
1257
  url.searchParams.set("shop", shopDomain);
1258
+ url.searchParams.set("fields", "1");
1118
1259
  return url.toString();
1119
1260
  }
1261
+ function productFieldsUrl(platformUrl, shopDomain, experienceId, handle) {
1262
+ const url = new URL("/api/storefront/product-fields", platformUrl);
1263
+ url.searchParams.set("shop", shopDomain);
1264
+ url.searchParams.set("x", experienceId);
1265
+ url.searchParams.set("handle", handle);
1266
+ return url.toString();
1267
+ }
1268
+ function sanitizeProductFields(json) {
1269
+ if (!json || typeof json !== "object") return null;
1270
+ const f = json.fields;
1271
+ if (!f || typeof f !== "object" || Array.isArray(f)) return null;
1272
+ const fields = {};
1273
+ for (const [k, v] of Object.entries(f)) if (typeof v === "string") fields[k] = v;
1274
+ return { fields };
1275
+ }
1276
+ var productFieldsFetcher = createCachedJsonFetcher({ label: "product fields", sanitize: sanitizeProductFields });
1277
+ function decisionNeedsProductFields(d) {
1278
+ if (!d.snapshot) return false;
1279
+ return !!d.snapshot.pf?.length || d.snapshot.nodes.some((n) => mayHaveProductTokens(n.html));
1280
+ }
1281
+ async function getSsrProductFields(args) {
1282
+ try {
1283
+ const { value, source } = await productFieldsFetcher.getWithSource({
1284
+ url: productFieldsUrl(args.platformUrl, args.shopDomain, args.experienceId, args.handle),
1285
+ waitUntil: args.waitUntil,
1286
+ fetchImpl: args.fetchImpl
1287
+ });
1288
+ return value && HEALTHY2.has(source) ? value.fields : null;
1289
+ } catch {
1290
+ return null;
1291
+ }
1292
+ }
1293
+ function fillSsrDecision(d, fields) {
1294
+ if (!d.snapshot) return d;
1295
+ return {
1296
+ ...d,
1297
+ snapshot: { ...d.snapshot, nodes: d.snapshot.nodes.map((n) => ({ ...n, html: fillProductTokens(n.html || "", fields).html })) }
1298
+ };
1299
+ }
1300
+ async function withProductFields(d, args) {
1301
+ if (!decisionNeedsProductFields(d) || !d.experienceId) return { decision: d };
1302
+ if (d.page.t !== "product" || !d.page.h) return { decision: fillSsrDecision(d, null) };
1303
+ const fields = await getSsrProductFields({ ...args, experienceId: d.experienceId, handle: d.page.h });
1304
+ if (!fields) return { skip: "product-fields-unavailable" };
1305
+ return { decision: fillSsrDecision(d, fields) };
1306
+ }
1120
1307
  function sanitizeSsrPayload(json) {
1121
1308
  if (!json || typeof json !== "object") return null;
1122
1309
  const j = json;
@@ -1188,6 +1375,13 @@ function normalizePreviewCode(raw) {
1188
1375
  function isDataRequest(url) {
1189
1376
  return url.pathname.endsWith(".data");
1190
1377
  }
1378
+ var DOCUMENT_FETCH_DESTS = /* @__PURE__ */ new Set(["document", "iframe", "frame"]);
1379
+ function isDocumentRequest(request, url) {
1380
+ if (isDataRequest(url) || url.pathname === "/__manifest") return false;
1381
+ const dest = request.headers.get("sec-fetch-dest");
1382
+ if (dest) return DOCUMENT_FETCH_DESTS.has(dest.trim().toLowerCase());
1383
+ return (request.headers.get("accept") ?? "").toLowerCase().includes("text/html");
1384
+ }
1191
1385
  function dataRequestPagePath(pathname) {
1192
1386
  if (!pathname.endsWith(".data")) return pathname;
1193
1387
  if (pathname === "/_root.data") return "/";
@@ -1426,11 +1620,13 @@ function createPlaybookContext({
1426
1620
  const secure = requestUrl?.protocol === "https:";
1427
1621
  const setCarry = (code) => extraCookies.push(serializeCookie(PREVIEW_CODE_COOKIE, code, { httpOnly: true, secure }));
1428
1622
  const clearCarry = () => extraCookies.push(serializeCookie(PREVIEW_CODE_COOKIE, "", { httpOnly: true, secure, maxAge: 0 }));
1429
- if (shopId && isGet && !isData && !urlCode && carryCookieRaw !== void 0) clearCarry();
1623
+ const isDocument = !!requestUrl && isDocumentRequest(request, requestUrl);
1624
+ if (shopId && isGet && isDocument && !urlCode && carryCookieRaw !== void 0) clearCarry();
1430
1625
  let previewFetch = null;
1626
+ const previewShopDomain = () => requestUrl ? normalizeDomain(shopDomainOption ?? str(e.PUBLIC_PLAYBOOK_SHOP_DOMAIN) ?? requestUrl.hostname) : "";
1431
1627
  const previewPayload = () => {
1432
1628
  if (!previewFetch) {
1433
- const shopDomain = requestUrl ? normalizeDomain(shopDomainOption ?? str(e.PUBLIC_PLAYBOOK_SHOP_DOMAIN) ?? requestUrl.hostname) : "";
1629
+ const shopDomain = previewShopDomain();
1434
1630
  previewFetch = previewCode && shopDomain ? getSsrPreviewPayload({ platformUrl, shopDomain, code: previewCode, fetchImpl }).catch(() => null) : Promise.resolve(null);
1435
1631
  }
1436
1632
  return previewFetch;
@@ -1552,6 +1748,9 @@ function createPlaybookContext({
1552
1748
  if (!via) return { ssr: null, skip: "preview-no-slot" };
1553
1749
  d2 = { ...d2, matchedBy: via };
1554
1750
  }
1751
+ const filled2 = await withProductFields(d2, { platformUrl, shopDomain: previewShopDomain(), waitUntil, fetchImpl });
1752
+ if ("skip" in filled2) return { ssr: null, skip: filled2.skip };
1753
+ d2 = filled2.decision;
1555
1754
  ssrRendered = true;
1556
1755
  return { ssr: d2, skip: null };
1557
1756
  }
@@ -1574,6 +1773,9 @@ function createPlaybookContext({
1574
1773
  if (!via) return { ssr: null, skip: "no-slot" };
1575
1774
  d = { ...d, matchedBy: via };
1576
1775
  }
1776
+ const filled = await withProductFields(d, { platformUrl, shopDomain: cloak.shopDomain, waitUntil, fetchImpl });
1777
+ if ("skip" in filled) return { ssr: null, skip: filled.skip };
1778
+ d = filled.decision;
1577
1779
  ssrRendered = true;
1578
1780
  return { ssr: d, skip: null };
1579
1781
  })().catch(() => ({ ssr: null, skip: "error" }));
@@ -3536,4 +3738,4 @@ function trackAddToCartLines(lines, cartLines, source) {
3536
3738
  }
3537
3739
  }
3538
3740
 
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 };
3741
+ 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, PRODUCT_FIELD_MISSING_ATTR, 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, fillProductTokens, fillSsrDecision, 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, productFieldsUrl, productTokensIn, 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, withProductFields };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@heyplaybook/hydrogen",
3
- "version": "0.8.1",
3
+ "version": "0.9.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.",