@heyplaybook/hydrogen 0.8.1 → 0.10.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/README.md +4 -0
- package/dist/index.d.ts +52 -5
- package/dist/index.js +211 -4
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -222,6 +222,8 @@ server-rendered, with no code change per test.
|
|
|
222
222
|
| `under-size` | product | under the Size option's label, above its buttons |
|
|
223
223
|
| `collection-grid-top` | collection | right before the product grid |
|
|
224
224
|
| `after-home-hero` | home | right after the hero section |
|
|
225
|
+
| `product-top` | product | immediately before the product section, above the gallery (the route's first child) |
|
|
226
|
+
| `site-top` | every page | first child of your layout's `<main>`, right under the header |
|
|
225
227
|
|
|
226
228
|
```tsx
|
|
227
229
|
import {PlaybookSlot} from '@heyplaybook/hydrogen';
|
|
@@ -262,6 +264,8 @@ createPlaybookContext({
|
|
|
262
264
|
'under-size',
|
|
263
265
|
'collection-grid-top',
|
|
264
266
|
'after-home-hero',
|
|
267
|
+
'product-top',
|
|
268
|
+
'site-top',
|
|
265
269
|
SECTION_SLOTS, // you render <PlaybookSections>
|
|
266
270
|
],
|
|
267
271
|
});
|
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
|
|
@@ -498,7 +522,7 @@ declare function playbookHeadSnippetHtml(cloak: PlaybookCloakConfig | null | und
|
|
|
498
522
|
*/
|
|
499
523
|
declare const SSR_SLOT_ATTR = "data-pb-slot";
|
|
500
524
|
/** 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"];
|
|
525
|
+
declare const SSR_SLOT_NAMES: readonly ["buy-column-top", "after-add-to-cart", "under-size", "collection-grid-top", "after-home-hero", "product-top", "site-top"];
|
|
502
526
|
type PlaybookSlotName = (typeof SSR_SLOT_NAMES)[number];
|
|
503
527
|
type SectionSlotSide = 'before' | 'after';
|
|
504
528
|
type SectionSlotKey = `section:${string}:${SectionSlotSide}`;
|
|
@@ -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
|
|
610
|
-
*
|
|
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
|
@@ -1079,7 +1079,12 @@ var SSR_SLOT_NAMES = [
|
|
|
1079
1079
|
"after-add-to-cart",
|
|
1080
1080
|
"under-size",
|
|
1081
1081
|
"collection-grid-top",
|
|
1082
|
-
"after-home-hero"
|
|
1082
|
+
"after-home-hero",
|
|
1083
|
+
// 0.10.0
|
|
1084
|
+
"product-top",
|
|
1085
|
+
// product page: immediately before the product section, above the gallery
|
|
1086
|
+
"site-top"
|
|
1087
|
+
// every page: first child of the layout's <main>, right under the header
|
|
1083
1088
|
];
|
|
1084
1089
|
var SECTION_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
1085
1090
|
var SECTION_KEY_RE = /^section:([A-Za-z0-9_-]{1,64}):(before|after)$/;
|
|
@@ -1110,13 +1115,200 @@ function slotFromSelector(selector) {
|
|
|
1110
1115
|
return isSlotKey(key) ? key : null;
|
|
1111
1116
|
}
|
|
1112
1117
|
|
|
1118
|
+
// src/product-fields.ts
|
|
1119
|
+
var PRODUCT_FIELD_MISSING_ATTR = "data-pb-field-missing";
|
|
1120
|
+
var SEGMENT = /^[A-Za-z0-9_-]{1,64}$/;
|
|
1121
|
+
var TOKEN_RE = /\{\{\s*product\.([A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+){0,2})\s*\}\}/g;
|
|
1122
|
+
function mayHaveProductTokens(html) {
|
|
1123
|
+
return typeof html === "string" && html.includes("{{") && /\{\{\s*product\./.test(html);
|
|
1124
|
+
}
|
|
1125
|
+
function normalizeFieldPath(raw) {
|
|
1126
|
+
const parts = raw.split(".");
|
|
1127
|
+
if (!parts.every((p) => SEGMENT.test(p))) return null;
|
|
1128
|
+
const head = parts[0].toLowerCase();
|
|
1129
|
+
if (head === "metafield") return parts.length === 3 ? `metafield.${parts[1]}.${parts[2]}` : null;
|
|
1130
|
+
if (head === "detail") return parts.length === 2 ? `detail.${parts[1].toLowerCase().replace(/-/g, "_")}` : null;
|
|
1131
|
+
return parts.length === 1 ? head : null;
|
|
1132
|
+
}
|
|
1133
|
+
function productTokensIn(html) {
|
|
1134
|
+
if (!mayHaveProductTokens(html)) return [];
|
|
1135
|
+
const out = [];
|
|
1136
|
+
for (const m of html.matchAll(TOKEN_RE)) {
|
|
1137
|
+
const path = normalizeFieldPath(m[1]);
|
|
1138
|
+
if (path && !out.includes(path)) out.push(path);
|
|
1139
|
+
}
|
|
1140
|
+
return out;
|
|
1141
|
+
}
|
|
1142
|
+
var escapeHtml = (s2) => s2.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
1143
|
+
var VOID = /* @__PURE__ */ new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"]);
|
|
1144
|
+
var GROUP_RE = /\sdata-pb-field(?=[\s=/>]|$)/i;
|
|
1145
|
+
function hideTag(tag) {
|
|
1146
|
+
if (tag.includes(PRODUCT_FIELD_MISSING_ATTR)) return tag;
|
|
1147
|
+
const name = /^<[A-Za-z][A-Za-z0-9-]*/.exec(tag)?.[0] ?? "";
|
|
1148
|
+
if (!name) return tag;
|
|
1149
|
+
let rest = tag.slice(name.length);
|
|
1150
|
+
const style = /(\sstyle\s*=\s*)("([^"]*)"|'([^']*)')/i.exec(rest);
|
|
1151
|
+
if (style) {
|
|
1152
|
+
const quote = style[2][0];
|
|
1153
|
+
const value = style[3] ?? style[4] ?? "";
|
|
1154
|
+
rest = rest.slice(0, style.index) + `${style[1]}${quote}display:none !important;${value}${quote}` + rest.slice(style.index + style[0].length);
|
|
1155
|
+
return `${name} ${PRODUCT_FIELD_MISSING_ATTR}=""${rest}`;
|
|
1156
|
+
}
|
|
1157
|
+
return `${name} ${PRODUCT_FIELD_MISSING_ATTR}="" style="display:none !important"${rest}`;
|
|
1158
|
+
}
|
|
1159
|
+
function tagEnd(html, i) {
|
|
1160
|
+
let quote = null;
|
|
1161
|
+
for (let j = i + 1; j < html.length; j++) {
|
|
1162
|
+
const c = html[j];
|
|
1163
|
+
if (quote) {
|
|
1164
|
+
if (c === quote) quote = null;
|
|
1165
|
+
} else if (c === '"' || c === "'") quote = c;
|
|
1166
|
+
else if (c === ">") return j;
|
|
1167
|
+
}
|
|
1168
|
+
return -1;
|
|
1169
|
+
}
|
|
1170
|
+
function fillProductTokens(html, fields) {
|
|
1171
|
+
if (typeof html !== "string" || !mayHaveProductTokens(html)) return { html: typeof html === "string" ? html : "", used: [], missing: [] };
|
|
1172
|
+
const used = [];
|
|
1173
|
+
const missing = [];
|
|
1174
|
+
const valueOf = (raw) => {
|
|
1175
|
+
const path = normalizeFieldPath(raw);
|
|
1176
|
+
if (path && !used.includes(path)) used.push(path);
|
|
1177
|
+
const v = path && fields ? fields[path] : void 0;
|
|
1178
|
+
const ok = typeof v === "string" && v.trim().length > 0;
|
|
1179
|
+
if (!ok && path && !missing.includes(path)) missing.push(path);
|
|
1180
|
+
return ok ? v.trim() : null;
|
|
1181
|
+
};
|
|
1182
|
+
const fillRun = (run) => {
|
|
1183
|
+
let missed = false;
|
|
1184
|
+
const text = run.replace(TOKEN_RE, (_m, raw) => {
|
|
1185
|
+
const v = valueOf(raw);
|
|
1186
|
+
if (v == null) {
|
|
1187
|
+
missed = true;
|
|
1188
|
+
return "";
|
|
1189
|
+
}
|
|
1190
|
+
return escapeHtml(v);
|
|
1191
|
+
});
|
|
1192
|
+
return { text, missed };
|
|
1193
|
+
};
|
|
1194
|
+
const out = [];
|
|
1195
|
+
const stack = [];
|
|
1196
|
+
const hidden = /* @__PURE__ */ new Set();
|
|
1197
|
+
const hideFor = (self) => {
|
|
1198
|
+
const chain = self ? [...stack, self] : stack;
|
|
1199
|
+
for (let k = chain.length - 1; k >= 0; k--) {
|
|
1200
|
+
if (chain[k].group) {
|
|
1201
|
+
hidden.add(chain[k].slot);
|
|
1202
|
+
return;
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
const target = self ?? stack[stack.length - 1];
|
|
1206
|
+
if (target) hidden.add(target.slot);
|
|
1207
|
+
};
|
|
1208
|
+
let i = 0;
|
|
1209
|
+
while (i < html.length) {
|
|
1210
|
+
const lt = html.indexOf("<", i);
|
|
1211
|
+
const textEnd = lt === -1 ? html.length : lt;
|
|
1212
|
+
if (textEnd > i) {
|
|
1213
|
+
const { text: text2, missed: missed2 } = fillRun(html.slice(i, textEnd));
|
|
1214
|
+
out.push(text2);
|
|
1215
|
+
if (missed2) hideFor(null);
|
|
1216
|
+
i = textEnd;
|
|
1217
|
+
continue;
|
|
1218
|
+
}
|
|
1219
|
+
if (html.startsWith("<!--", i)) {
|
|
1220
|
+
const end2 = html.indexOf("-->", i + 4);
|
|
1221
|
+
const stop = end2 === -1 ? html.length : end2 + 3;
|
|
1222
|
+
out.push(html.slice(i, stop));
|
|
1223
|
+
i = stop;
|
|
1224
|
+
continue;
|
|
1225
|
+
}
|
|
1226
|
+
const close = /^<\/([A-Za-z][A-Za-z0-9-]*)[^>]*>/.exec(html.slice(i, i + 200));
|
|
1227
|
+
if (close) {
|
|
1228
|
+
const name2 = close[1].toLowerCase();
|
|
1229
|
+
const at = stack.map((t) => t.name).lastIndexOf(name2);
|
|
1230
|
+
if (at !== -1) stack.length = at;
|
|
1231
|
+
out.push(close[0]);
|
|
1232
|
+
i += close[0].length;
|
|
1233
|
+
continue;
|
|
1234
|
+
}
|
|
1235
|
+
if (!/[A-Za-z]/.test(html[i + 1] ?? "")) {
|
|
1236
|
+
out.push("<");
|
|
1237
|
+
i += 1;
|
|
1238
|
+
continue;
|
|
1239
|
+
}
|
|
1240
|
+
const end = tagEnd(html, i);
|
|
1241
|
+
if (end === -1) {
|
|
1242
|
+
out.push(fillRun(html.slice(i)).text);
|
|
1243
|
+
break;
|
|
1244
|
+
}
|
|
1245
|
+
const raw = html.slice(i, end + 1);
|
|
1246
|
+
const name = (/^<([A-Za-z][A-Za-z0-9-]*)/.exec(raw)?.[1] ?? "").toLowerCase();
|
|
1247
|
+
const { text, missed } = fillRun(raw);
|
|
1248
|
+
const tag = { name, slot: out.length, group: GROUP_RE.test(raw) };
|
|
1249
|
+
out.push(text);
|
|
1250
|
+
if (missed) hideFor(tag);
|
|
1251
|
+
if (!VOID.has(name) && !/\/\s*>$/.test(raw)) stack.push(tag);
|
|
1252
|
+
i = end + 1;
|
|
1253
|
+
}
|
|
1254
|
+
for (const slot of hidden) out[slot] = hideTag(out[slot]);
|
|
1255
|
+
return { html: out.join(""), used, missing };
|
|
1256
|
+
}
|
|
1257
|
+
|
|
1113
1258
|
// src/ssr.ts
|
|
1114
1259
|
var SSR_SNAPSHOT_VERSION = 1;
|
|
1115
1260
|
function ssrUrl(platformUrl, shopDomain) {
|
|
1116
1261
|
const url = new URL("/api/storefront/ssr", platformUrl);
|
|
1117
1262
|
url.searchParams.set("shop", shopDomain);
|
|
1263
|
+
url.searchParams.set("fields", "1");
|
|
1118
1264
|
return url.toString();
|
|
1119
1265
|
}
|
|
1266
|
+
function productFieldsUrl(platformUrl, shopDomain, experienceId, handle) {
|
|
1267
|
+
const url = new URL("/api/storefront/product-fields", platformUrl);
|
|
1268
|
+
url.searchParams.set("shop", shopDomain);
|
|
1269
|
+
url.searchParams.set("x", experienceId);
|
|
1270
|
+
url.searchParams.set("handle", handle);
|
|
1271
|
+
return url.toString();
|
|
1272
|
+
}
|
|
1273
|
+
function sanitizeProductFields(json) {
|
|
1274
|
+
if (!json || typeof json !== "object") return null;
|
|
1275
|
+
const f = json.fields;
|
|
1276
|
+
if (!f || typeof f !== "object" || Array.isArray(f)) return null;
|
|
1277
|
+
const fields = {};
|
|
1278
|
+
for (const [k, v] of Object.entries(f)) if (typeof v === "string") fields[k] = v;
|
|
1279
|
+
return { fields };
|
|
1280
|
+
}
|
|
1281
|
+
var productFieldsFetcher = createCachedJsonFetcher({ label: "product fields", sanitize: sanitizeProductFields });
|
|
1282
|
+
function decisionNeedsProductFields(d) {
|
|
1283
|
+
if (!d.snapshot) return false;
|
|
1284
|
+
return !!d.snapshot.pf?.length || d.snapshot.nodes.some((n) => mayHaveProductTokens(n.html));
|
|
1285
|
+
}
|
|
1286
|
+
async function getSsrProductFields(args) {
|
|
1287
|
+
try {
|
|
1288
|
+
const { value, source } = await productFieldsFetcher.getWithSource({
|
|
1289
|
+
url: productFieldsUrl(args.platformUrl, args.shopDomain, args.experienceId, args.handle),
|
|
1290
|
+
waitUntil: args.waitUntil,
|
|
1291
|
+
fetchImpl: args.fetchImpl
|
|
1292
|
+
});
|
|
1293
|
+
return value && HEALTHY2.has(source) ? value.fields : null;
|
|
1294
|
+
} catch {
|
|
1295
|
+
return null;
|
|
1296
|
+
}
|
|
1297
|
+
}
|
|
1298
|
+
function fillSsrDecision(d, fields) {
|
|
1299
|
+
if (!d.snapshot) return d;
|
|
1300
|
+
return {
|
|
1301
|
+
...d,
|
|
1302
|
+
snapshot: { ...d.snapshot, nodes: d.snapshot.nodes.map((n) => ({ ...n, html: fillProductTokens(n.html || "", fields).html })) }
|
|
1303
|
+
};
|
|
1304
|
+
}
|
|
1305
|
+
async function withProductFields(d, args) {
|
|
1306
|
+
if (!decisionNeedsProductFields(d) || !d.experienceId) return { decision: d };
|
|
1307
|
+
if (d.page.t !== "product" || !d.page.h) return { decision: fillSsrDecision(d, null) };
|
|
1308
|
+
const fields = await getSsrProductFields({ ...args, experienceId: d.experienceId, handle: d.page.h });
|
|
1309
|
+
if (!fields) return { skip: "product-fields-unavailable" };
|
|
1310
|
+
return { decision: fillSsrDecision(d, fields) };
|
|
1311
|
+
}
|
|
1120
1312
|
function sanitizeSsrPayload(json) {
|
|
1121
1313
|
if (!json || typeof json !== "object") return null;
|
|
1122
1314
|
const j = json;
|
|
@@ -1188,6 +1380,13 @@ function normalizePreviewCode(raw) {
|
|
|
1188
1380
|
function isDataRequest(url) {
|
|
1189
1381
|
return url.pathname.endsWith(".data");
|
|
1190
1382
|
}
|
|
1383
|
+
var DOCUMENT_FETCH_DESTS = /* @__PURE__ */ new Set(["document", "iframe", "frame"]);
|
|
1384
|
+
function isDocumentRequest(request, url) {
|
|
1385
|
+
if (isDataRequest(url) || url.pathname === "/__manifest") return false;
|
|
1386
|
+
const dest = request.headers.get("sec-fetch-dest");
|
|
1387
|
+
if (dest) return DOCUMENT_FETCH_DESTS.has(dest.trim().toLowerCase());
|
|
1388
|
+
return (request.headers.get("accept") ?? "").toLowerCase().includes("text/html");
|
|
1389
|
+
}
|
|
1191
1390
|
function dataRequestPagePath(pathname) {
|
|
1192
1391
|
if (!pathname.endsWith(".data")) return pathname;
|
|
1193
1392
|
if (pathname === "/_root.data") return "/";
|
|
@@ -1426,11 +1625,13 @@ function createPlaybookContext({
|
|
|
1426
1625
|
const secure = requestUrl?.protocol === "https:";
|
|
1427
1626
|
const setCarry = (code) => extraCookies.push(serializeCookie(PREVIEW_CODE_COOKIE, code, { httpOnly: true, secure }));
|
|
1428
1627
|
const clearCarry = () => extraCookies.push(serializeCookie(PREVIEW_CODE_COOKIE, "", { httpOnly: true, secure, maxAge: 0 }));
|
|
1429
|
-
|
|
1628
|
+
const isDocument = !!requestUrl && isDocumentRequest(request, requestUrl);
|
|
1629
|
+
if (shopId && isGet && isDocument && !urlCode && carryCookieRaw !== void 0) clearCarry();
|
|
1430
1630
|
let previewFetch = null;
|
|
1631
|
+
const previewShopDomain = () => requestUrl ? normalizeDomain(shopDomainOption ?? str(e.PUBLIC_PLAYBOOK_SHOP_DOMAIN) ?? requestUrl.hostname) : "";
|
|
1431
1632
|
const previewPayload = () => {
|
|
1432
1633
|
if (!previewFetch) {
|
|
1433
|
-
const shopDomain =
|
|
1634
|
+
const shopDomain = previewShopDomain();
|
|
1434
1635
|
previewFetch = previewCode && shopDomain ? getSsrPreviewPayload({ platformUrl, shopDomain, code: previewCode, fetchImpl }).catch(() => null) : Promise.resolve(null);
|
|
1435
1636
|
}
|
|
1436
1637
|
return previewFetch;
|
|
@@ -1552,6 +1753,9 @@ function createPlaybookContext({
|
|
|
1552
1753
|
if (!via) return { ssr: null, skip: "preview-no-slot" };
|
|
1553
1754
|
d2 = { ...d2, matchedBy: via };
|
|
1554
1755
|
}
|
|
1756
|
+
const filled2 = await withProductFields(d2, { platformUrl, shopDomain: previewShopDomain(), waitUntil, fetchImpl });
|
|
1757
|
+
if ("skip" in filled2) return { ssr: null, skip: filled2.skip };
|
|
1758
|
+
d2 = filled2.decision;
|
|
1555
1759
|
ssrRendered = true;
|
|
1556
1760
|
return { ssr: d2, skip: null };
|
|
1557
1761
|
}
|
|
@@ -1574,6 +1778,9 @@ function createPlaybookContext({
|
|
|
1574
1778
|
if (!via) return { ssr: null, skip: "no-slot" };
|
|
1575
1779
|
d = { ...d, matchedBy: via };
|
|
1576
1780
|
}
|
|
1781
|
+
const filled = await withProductFields(d, { platformUrl, shopDomain: cloak.shopDomain, waitUntil, fetchImpl });
|
|
1782
|
+
if ("skip" in filled) return { ssr: null, skip: filled.skip };
|
|
1783
|
+
d = filled.decision;
|
|
1577
1784
|
ssrRendered = true;
|
|
1578
1785
|
return { ssr: d, skip: null };
|
|
1579
1786
|
})().catch(() => ({ ssr: null, skip: "error" }));
|
|
@@ -3536,4 +3743,4 @@ function trackAddToCartLines(lines, cartLines, source) {
|
|
|
3536
3743
|
}
|
|
3537
3744
|
}
|
|
3538
3745
|
|
|
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 };
|
|
3746
|
+
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.
|
|
3
|
+
"version": "0.10.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.",
|