@joy-loyalty/hydrogen 0.0.0-stage → 0.2.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.
Files changed (127) hide show
  1. package/LICENSE +3 -0
  2. package/README.md +134 -2
  3. package/dist/cache-control.d.ts +8 -0
  4. package/dist/cache-control.js +6 -0
  5. package/dist/csp.d.ts +14 -0
  6. package/dist/csp.js +33 -0
  7. package/dist/headless-host-adapter.d.ts +5 -0
  8. package/dist/headless-host-adapter.js +198 -0
  9. package/dist/host-adapter/capabilities.d.ts +4 -0
  10. package/dist/host-adapter/capabilities.js +15 -0
  11. package/dist/host-adapter/data-source.d.ts +3 -0
  12. package/dist/host-adapter/data-source.js +49 -0
  13. package/dist/host-adapter/product-fetcher.d.ts +2 -0
  14. package/dist/host-adapter/product-fetcher.js +38 -0
  15. package/dist/host-adapter/promoted-collections.d.ts +2 -0
  16. package/dist/host-adapter/promoted-collections.js +44 -0
  17. package/dist/host-adapter/types.d.ts +212 -0
  18. package/dist/host-adapter/types.js +1 -0
  19. package/dist/hydrogen-cart-port.d.ts +134 -0
  20. package/dist/hydrogen-cart-port.js +245 -0
  21. package/dist/index.d.ts +26 -0
  22. package/dist/index.js +15 -0
  23. package/dist/joy-widget.d.ts +29 -0
  24. package/dist/joy-widget.js +291 -0
  25. package/dist/lib/JoyProvider.d.ts +47 -0
  26. package/dist/lib/JoyProvider.js +95 -0
  27. package/dist/lib/account-links.d.ts +5 -0
  28. package/dist/lib/account-links.js +65 -0
  29. package/dist/lib/apply-behavior.d.ts +12 -0
  30. package/dist/lib/apply-behavior.js +26 -0
  31. package/dist/lib/core-loader.d.ts +63 -0
  32. package/dist/lib/core-loader.js +160 -0
  33. package/dist/lib/core-manifest.d.ts +7 -0
  34. package/dist/lib/core-manifest.js +54 -0
  35. package/dist/lib/core-preload-links.d.ts +8 -0
  36. package/dist/lib/core-preload-links.js +8 -0
  37. package/dist/lib/coupon-mapper.d.ts +95 -0
  38. package/dist/lib/coupon-mapper.js +167 -0
  39. package/dist/lib/custom-links.d.ts +22 -0
  40. package/dist/lib/custom-links.js +56 -0
  41. package/dist/lib/deeplink.d.ts +25 -0
  42. package/dist/lib/deeplink.js +92 -0
  43. package/dist/lib/earn-signup-gate.d.ts +3 -0
  44. package/dist/lib/earn-signup-gate.js +31 -0
  45. package/dist/lib/facebook-ref-link.d.ts +13 -0
  46. package/dist/lib/facebook-ref-link.js +31 -0
  47. package/dist/lib/headless-referral-origin.d.ts +2 -0
  48. package/dist/lib/headless-referral-origin.js +24 -0
  49. package/dist/lib/headless-source.d.ts +8 -0
  50. package/dist/lib/headless-source.js +71 -0
  51. package/dist/lib/image.d.ts +2 -0
  52. package/dist/lib/image.js +14 -0
  53. package/dist/lib/metafield-blob.d.ts +33 -0
  54. package/dist/lib/metafield-blob.js +76 -0
  55. package/dist/lib/money.d.ts +6 -0
  56. package/dist/lib/money.js +25 -0
  57. package/dist/lib/order-mapper.d.ts +44 -0
  58. package/dist/lib/order-mapper.js +141 -0
  59. package/dist/lib/place-order-scope.d.ts +6 -0
  60. package/dist/lib/place-order-scope.js +22 -0
  61. package/dist/lib/points.d.ts +5 -0
  62. package/dist/lib/points.js +10 -0
  63. package/dist/lib/recently-viewed-tracker.d.ts +1 -0
  64. package/dist/lib/recently-viewed-tracker.js +34 -0
  65. package/dist/lib/recommended-loader.d.ts +44 -0
  66. package/dist/lib/recommended-loader.js +113 -0
  67. package/dist/lib/referral-share.d.ts +4 -0
  68. package/dist/lib/referral-share.js +33 -0
  69. package/dist/lib/safe-navigation-url.d.ts +1 -0
  70. package/dist/lib/safe-navigation-url.js +9 -0
  71. package/dist/lib/server-token.d.ts +41 -0
  72. package/dist/lib/server-token.js +87 -0
  73. package/dist/lib/shop-locale.d.ts +1 -0
  74. package/dist/lib/shop-locale.js +21 -0
  75. package/dist/lib/social-earn.d.ts +11 -0
  76. package/dist/lib/social-earn.js +25 -0
  77. package/dist/lib/storefront-fonts.d.ts +5 -0
  78. package/dist/lib/storefront-fonts.js +52 -0
  79. package/dist/lib/token.d.ts +14 -0
  80. package/dist/lib/token.js +135 -0
  81. package/dist/lib/write-review.d.ts +2 -0
  82. package/dist/lib/write-review.js +44 -0
  83. package/dist/loyalty-page/JoyLoyaltyPage.d.ts +151 -0
  84. package/dist/loyalty-page/JoyLoyaltyPage.js +447 -0
  85. package/dist/loyalty-page/compose-home.d.ts +35 -0
  86. package/dist/loyalty-page/compose-home.js +177 -0
  87. package/dist/loyalty-page/skeleton.d.ts +11 -0
  88. package/dist/loyalty-page/skeleton.js +99 -0
  89. package/dist/orchestrator/context.d.ts +61 -0
  90. package/dist/orchestrator/context.js +64 -0
  91. package/dist/orchestrator/gated.d.ts +1 -0
  92. package/dist/orchestrator/gated.js +14 -0
  93. package/dist/orchestrator/handlers/account.d.ts +19 -0
  94. package/dist/orchestrator/handlers/account.js +266 -0
  95. package/dist/orchestrator/handlers/birthday.d.ts +6 -0
  96. package/dist/orchestrator/handlers/birthday.js +128 -0
  97. package/dist/orchestrator/handlers/earn.d.ts +5 -0
  98. package/dist/orchestrator/handlers/earn.js +267 -0
  99. package/dist/orchestrator/handlers/milestone-tier.d.ts +5 -0
  100. package/dist/orchestrator/handlers/milestone-tier.js +123 -0
  101. package/dist/orchestrator/handlers/profile.d.ts +5 -0
  102. package/dist/orchestrator/handlers/profile.js +262 -0
  103. package/dist/orchestrator/handlers/redeem.d.ts +6 -0
  104. package/dist/orchestrator/handlers/redeem.js +464 -0
  105. package/dist/orchestrator/handlers/referral.d.ts +5 -0
  106. package/dist/orchestrator/handlers/referral.js +218 -0
  107. package/dist/orchestrator/render.d.ts +2 -0
  108. package/dist/orchestrator/render.js +193 -0
  109. package/dist/render-adapter.d.ts +50 -0
  110. package/dist/render-adapter.js +422 -0
  111. package/dist/routes/joy-place-order-scope.d.ts +12 -0
  112. package/dist/routes/joy-place-order-scope.js +32 -0
  113. package/dist/routes/joy-products.d.ts +48 -0
  114. package/dist/routes/joy-products.js +338 -0
  115. package/dist/routes/joy-token.d.ts +16 -0
  116. package/dist/routes/joy-token.js +32 -0
  117. package/dist/server/get-joy-initial-data.d.ts +39 -0
  118. package/dist/server/get-joy-initial-data.js +65 -0
  119. package/dist/server/get-joy-loyalty-page-data.d.ts +28 -0
  120. package/dist/server/get-joy-loyalty-page-data.js +99 -0
  121. package/dist/server/index.d.ts +8 -0
  122. package/dist/server/index.js +4 -0
  123. package/dist/widget-controller.d.ts +2 -0
  124. package/dist/widget-controller.js +1 -0
  125. package/dist/widget-orchestrator.d.ts +89 -0
  126. package/dist/widget-orchestrator.js +504 -0
  127. package/package.json +121 -4
@@ -0,0 +1,44 @@
1
+ const EVENT_WRITE_REVIEW = 'write_review';
2
+ const REVIEWS_EXTENSION_ID = 'joy-reviews';
3
+ const DEFAULT_PROVIDER = 'air-reviews';
4
+ const PROVIDER_REVIEW_HASH = {
5
+ 'air-reviews': '#AirReviews-BlockWrapperSubmit',
6
+ judgeme: '#judgeme_product_reviews'
7
+ };
8
+ function reviewsExtension(settings) {
9
+ const extensions = settings?.extensions;
10
+ if (!Array.isArray(extensions))
11
+ return undefined;
12
+ return extensions.find(ext => ext?.id === REVIEWS_EXTENSION_ID);
13
+ }
14
+ export function getWriteReviewUrl(rawSettings, extensions, productHandle, routesRoot) {
15
+ const settings = rawSettings;
16
+ const links = settings?.links;
17
+ const isV4 = Boolean(settings?.version);
18
+ const enabled = isV4 ? links?.customEarning : settings?.isCustomEarningLink;
19
+ const customUrl = String((isV4 ? links?.earningUrl : settings?.customEarningLink) || '');
20
+ const applied = settings?.customEarningLinkApplied;
21
+ if (enabled && customUrl && Array.isArray(applied) && applied.includes(EVENT_WRITE_REVIEW)) {
22
+ return customUrl;
23
+ }
24
+ if (!productHandle)
25
+ return '';
26
+ const provider = String(reviewsExtension({ extensions })?.config?.provider || DEFAULT_PROVIDER);
27
+ const hash = PROVIDER_REVIEW_HASH[provider] || PROVIDER_REVIEW_HASH[DEFAULT_PROVIDER] || '';
28
+ return `${routesRoot || '/'}products/${productHandle}${hash}`.replace(/\/+/g, '/');
29
+ }
30
+ export function buildWriteReviewProps(settings) {
31
+ const ext = reviewsExtension(settings);
32
+ if (!ext?.enabled)
33
+ return {};
34
+ const props = {
35
+ extensions: [{ ...ext, config: { ...(ext.config || {}), items: [], loading: false } }]
36
+ };
37
+ const footerItems = settings?.footerNav?.items;
38
+ const reviewsNavItem = Array.isArray(footerItems)
39
+ ? footerItems.find(item => item?.id === 'reviews' || item?.view === 'reviews')
40
+ : undefined;
41
+ if (reviewsNavItem?.icon)
42
+ props.reviewsNavIcon = reviewsNavItem.icon;
43
+ return props;
44
+ }
@@ -0,0 +1,151 @@
1
+ import type { ReactNode } from 'react';
2
+ import type { LoyaltyPageDataClient } from '@joy-loyalty/sdk/loyalty-page-contracts';
3
+ import type { ApplyBehaviorSettings } from '../lib/apply-behavior.js';
4
+ import type { JoyMetafieldBlob } from '../lib/metafield-blob.js';
5
+ import type { JoyLoyaltyPageData, JoyLoyaltyPageFaq } from '../server/get-joy-loyalty-page-data.js';
6
+ import type { HydrogenCartFetcher, HydrogenCartPort, StorefrontCart } from '../hydrogen-cart-port.js';
7
+ export interface JoyLoyaltyPageProps {
8
+ apiUrl: string;
9
+ shopDomain: string;
10
+ tokenRoute?: string;
11
+ sectionId?: string;
12
+ data: JoyLoyaltyPageData;
13
+ assetUrl?: string;
14
+ cart?: StorefrontCart | (() => StorefrontCart | null | undefined);
15
+ cartFetcher?: HydrogenCartFetcher;
16
+ cartRevalidate?: () => void;
17
+ cartRoute?: string;
18
+ onCartUpdated?: (cart: StorefrontCart) => void;
19
+ onOpenCartDrawer?: () => void;
20
+ onNavigate?: (url: string) => void;
21
+ initialData?: JoyLoyaltyPageInitialData | null;
22
+ }
23
+ export interface JoyLoyaltyPageInitialData {
24
+ customer?: {
25
+ points?: number | null;
26
+ tier?: {
27
+ id?: string | null;
28
+ name?: string | null;
29
+ } | null;
30
+ } | null;
31
+ shopifyCustomer?: {
32
+ firstName?: string | null;
33
+ email?: string | null;
34
+ } | null;
35
+ }
36
+ export interface LoyaltyPageSeedCustomer {
37
+ loggedIn: boolean;
38
+ enrolled: boolean;
39
+ name: string;
40
+ points: number | null;
41
+ tierId: string;
42
+ tier: string;
43
+ }
44
+ export declare function escapeJsonForScript(json: string): string;
45
+ export declare function buildInitialLoyaltyPageCustomer(initialData: JoyLoyaltyPageInitialData | null | undefined, session: {
46
+ hasCachedToken: boolean;
47
+ }): LoyaltyPageSeedCustomer | null;
48
+ export declare function toAjaxCart(cart: ReturnType<HydrogenCartPort['getCart']>): {
49
+ items: {
50
+ variant_id: string;
51
+ quantity: number;
52
+ discounts: {
53
+ title: string;
54
+ }[];
55
+ }[];
56
+ item_count: number;
57
+ total_price: number;
58
+ original_total_price: number;
59
+ } | null;
60
+ export declare function releaseStaleSeed(el: HTMLElement, seed: unknown): void;
61
+ type Translation = Record<string, unknown> | undefined;
62
+ type StockMap = Record<string, {
63
+ available?: boolean;
64
+ variants?: Record<string, boolean>;
65
+ } | unknown[]>;
66
+ interface ApplyRewardParams {
67
+ program?: {
68
+ event?: string;
69
+ appliedTo?: string;
70
+ freeProductQuantity?: string;
71
+ variantId?: string | number;
72
+ variantIds?: Array<string | number>;
73
+ specificProducts?: Array<{
74
+ quantity?: unknown;
75
+ variants?: Array<{
76
+ id?: string | number;
77
+ }>;
78
+ }>;
79
+ };
80
+ settings?: ApplyBehaviorSettings & {
81
+ alwaysOverrideDiscount?: boolean;
82
+ };
83
+ couponCode?: string;
84
+ customer?: unknown;
85
+ variantIdFreeGiftSelected?: string | number;
86
+ stockMap?: StockMap;
87
+ translation?: Translation;
88
+ onCartDrawerOpen?: () => void;
89
+ }
90
+ export declare function buildHydrogenHostPorts(port: HydrogenCartPort, { cartRoute, navigate, openCartDrawer, clientNavigate }?: {
91
+ cartRoute?: string;
92
+ navigate?: (url: string) => void;
93
+ openCartDrawer?: () => boolean | void;
94
+ clientNavigate?: (url: string) => void;
95
+ }): {
96
+ navigate: (url: string, { sameTab }?: {
97
+ sameTab?: boolean;
98
+ }) => void;
99
+ applyDiscountCode: ({ couponCode, settings, isRedirect }: {
100
+ couponCode: string;
101
+ settings?: ApplyRewardParams["settings"];
102
+ isRedirect?: boolean;
103
+ }) => Promise<{
104
+ droppedCodes?: string[] | undefined;
105
+ ok: boolean;
106
+ applied: boolean;
107
+ reason?: undefined;
108
+ } | {
109
+ ok: boolean;
110
+ applied: boolean;
111
+ reason: string;
112
+ }>;
113
+ addToCartAfterRedeem: ({ program, settings, variantIdFreeGiftSelected, couponCode, stockMap, translation, onCartDrawerOpen }: ApplyRewardParams) => Promise<void>;
114
+ applyReward: ({ program, settings, couponCode, customer, variantIdFreeGiftSelected, stockMap, translation, onCartDrawerOpen }: ApplyRewardParams) => Promise<{
115
+ error: string;
116
+ success?: undefined;
117
+ } | {
118
+ success: boolean;
119
+ error?: undefined;
120
+ }>;
121
+ getCart: () => Promise<{
122
+ items: {
123
+ variant_id: string;
124
+ quantity: number;
125
+ discounts: {
126
+ title: string;
127
+ }[];
128
+ }[];
129
+ item_count: number;
130
+ total_price: number;
131
+ original_total_price: number;
132
+ } | null>;
133
+ };
134
+ export declare function buildLoyaltyPageSource({ structure, faqs, translations, shop, cartPort, locale }: {
135
+ structure: unknown;
136
+ faqs?: JoyLoyaltyPageFaq[];
137
+ translations: unknown;
138
+ shop: unknown;
139
+ cartPort?: HydrogenCartPort;
140
+ locale?: string;
141
+ }): Record<string, unknown>;
142
+ export declare function withHomeComposite(client: LoyaltyPageDataClient, blob: JoyMetafieldBlob, hints?: {
143
+ detectCountry?: string;
144
+ locale?: string;
145
+ getCustomerFirstName?: () => string | null;
146
+ accountUrl?: string;
147
+ rehostReferralLink?: (link: string) => string;
148
+ }): LoyaltyPageDataClient;
149
+ export declare function isLoyaltyPageV2Enabled(data: Pick<JoyLoyaltyPageData, 'shop'> | undefined): boolean;
150
+ export declare function JoyLoyaltyPage({ apiUrl, shopDomain, tokenRoute, sectionId, data, assetUrl, cart, cartFetcher, cartRevalidate, cartRoute, onCartUpdated, onOpenCartDrawer, onNavigate, initialData }: JoyLoyaltyPageProps): ReactNode;
151
+ export {};
@@ -0,0 +1,447 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { createElement, useEffect, useMemo, useRef } from 'react';
3
+ import { LOYALTY_PAGE_DEFAULT_SECTION_IDS } from '@joy-loyalty/sdk/loyalty-page-contracts';
4
+ import { followApplyBehavior } from '../lib/apply-behavior.js';
5
+ import { loadWidgetCore } from '../lib/core-loader.js';
6
+ import { WidgetCorePreloadLinks } from '../lib/core-preload-links.js';
7
+ import { publishStorefrontFonts } from '../lib/storefront-fonts.js';
8
+ import { toHeadlessReferralLink, withHeadlessReferralOrigin } from '../lib/headless-referral-origin.js';
9
+ import { getCachedJoyCustomerFirstName, getJoyToken, hasCachedJoyToken } from '../lib/token.js';
10
+ import { composeLoyaltyPageHome, withResolvedPointLabel } from './compose-home.js';
11
+ import { LoyaltyPageV2Skeleton, LoyaltyPageV2SkeletonStyles } from './skeleton.js';
12
+ import { safeNavigationUrl } from '../lib/safe-navigation-url.js';
13
+ function resolveSectionIds(sectionId, structure) {
14
+ if (sectionId)
15
+ return [sectionId];
16
+ const sections = structure?.sections;
17
+ if (Array.isArray(sections) && sections.length) {
18
+ return sections
19
+ .filter((section) => Boolean(section?.enabled && section.id))
20
+ .map(section => section.id);
21
+ }
22
+ return [...LOYALTY_PAGE_DEFAULT_SECTION_IDS];
23
+ }
24
+ function isFaqSectionRendering(sectionIds) {
25
+ return sectionIds.includes('faq');
26
+ }
27
+ function FaqJsonLd({ faqs }) {
28
+ const json = JSON.stringify({
29
+ '@context': 'https://schema.org',
30
+ '@type': 'FAQPage',
31
+ mainEntity: faqs.map(faq => ({
32
+ '@type': 'Question',
33
+ name: faq.title,
34
+ acceptedAnswer: { '@type': 'Answer', text: faq.content }
35
+ }))
36
+ });
37
+ return _jsx("script", { type: "application/ld+json", dangerouslySetInnerHTML: { __html: escapeJsonForScript(json) } });
38
+ }
39
+ export function escapeJsonForScript(json) {
40
+ return json
41
+ .replace(/</g, '\\u003c')
42
+ .replace(/>/g, '\\u003e')
43
+ .replace(/&/g, '\\u0026')
44
+ .replace(/\u2028/g, '\\u2028')
45
+ .replace(/\u2029/g, '\\u2029');
46
+ }
47
+ function toLoyaltyPageCartPort(port) {
48
+ return {
49
+ async getTotal() {
50
+ const cart = port.getCart();
51
+ const amount = Number(cart?.cost.subtotalAmount.amount);
52
+ return Number.isFinite(amount) ? Math.round(amount * 100) : null;
53
+ }
54
+ };
55
+ }
56
+ export function buildInitialLoyaltyPageCustomer(initialData, session) {
57
+ if (initialData) {
58
+ const identity = initialData.shopifyCustomer;
59
+ if (!identity)
60
+ return null;
61
+ const customer = initialData.customer;
62
+ return {
63
+ loggedIn: true,
64
+ enrolled: true,
65
+ name: identity.firstName || identity.email || '',
66
+ points: typeof customer?.points === 'number' ? customer.points : null,
67
+ tierId: customer?.tier?.id || '',
68
+ tier: customer?.tier?.name || ''
69
+ };
70
+ }
71
+ if (!session.hasCachedToken)
72
+ return null;
73
+ return { loggedIn: true, enrolled: true, name: '', points: null, tierId: '', tier: '' };
74
+ }
75
+ export function toAjaxCart(cart) {
76
+ if (!cart)
77
+ return null;
78
+ const discounts = cart.discountCodes.filter(discount => discount.applicable).map(discount => ({ title: discount.code }));
79
+ const items = cart.lines.map(line => ({ variant_id: line.variantId, quantity: line.quantity, discounts }));
80
+ const total = Number(cart.cost.totalAmount.amount);
81
+ const subtotal = Number(cart.cost.subtotalAmount.amount);
82
+ return {
83
+ items,
84
+ item_count: items.reduce((sum, item) => sum + item.quantity, 0),
85
+ total_price: Number.isFinite(total) ? Math.round(total * 100) : 0,
86
+ original_total_price: Number.isFinite(subtotal) ? Math.round(subtotal * 100) : 0
87
+ };
88
+ }
89
+ function toVariantGid(raw) {
90
+ const id = String(raw);
91
+ return id.startsWith('gid://') ? id : `gid://shopify/ProductVariant/${id}`;
92
+ }
93
+ export function releaseStaleSeed(el, seed) {
94
+ const host = el;
95
+ if (!seed || host.customer !== seed)
96
+ return;
97
+ if (seed.points != null)
98
+ return;
99
+ host.customer = null;
100
+ }
101
+ function translate(key, translation) {
102
+ const value = translation?.[key];
103
+ return typeof value === 'string' && value ? value : key.replace(/\[\[(.*?)\]\]/g, '');
104
+ }
105
+ function applyCouponFailedMessage(translation) {
106
+ const value = translation?.failedToApplyCoupon;
107
+ return typeof value === 'string' && value
108
+ ? value
109
+ : 'Failed to apply coupon. Please check if the coupon is valid or has expired.';
110
+ }
111
+ function freeGiftQuantity(product) {
112
+ const parsed = parseInt(String(product?.quantity || '1'), 10);
113
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 1;
114
+ }
115
+ const MISSING_VARIANT_IDS_KEY = '__missingVariantIds';
116
+ function invalidVariantIds(stockMap, variantIds) {
117
+ const missing = stockMap[MISSING_VARIANT_IDS_KEY] || [];
118
+ if (!missing.length)
119
+ return [];
120
+ const missingSet = new Set(missing.map(String));
121
+ return variantIds.filter(id => missingSet.has(id));
122
+ }
123
+ function availableVariantIds(stockMap, variantIds) {
124
+ const invalid = new Set(invalidVariantIds(stockMap, variantIds));
125
+ const candidates = variantIds.filter(id => !invalid.has(id));
126
+ const products = Object.keys(stockMap)
127
+ .filter(key => key !== MISSING_VARIANT_IDS_KEY)
128
+ .map(key => stockMap[key]);
129
+ if (!products.length)
130
+ return candidates;
131
+ return candidates.filter(id => {
132
+ const entry = products.find(product => product?.variants && Object.hasOwn(product.variants, id));
133
+ return !entry || entry.variants?.[id] !== false;
134
+ });
135
+ }
136
+ const AUTO_ADD_GIFT_BEHAVIORS = ['auto_add_to_cart', 'auto_add_to_cart_drawer_hide_modal'];
137
+ function giftVariantIds(program, selected) {
138
+ const allVariantIds = program.variantIds?.length ? program.variantIds : [program.variantId];
139
+ return ((program.freeProductQuantity || 'all') === 'all' ? allVariantIds : [selected])
140
+ .filter(id => id != null && id !== '')
141
+ .map(String);
142
+ }
143
+ function giftQuantities(program) {
144
+ const quantities = {};
145
+ for (const product of program.specificProducts || []) {
146
+ for (const variant of product.variants || [])
147
+ quantities[String(variant.id)] = freeGiftQuantity(product);
148
+ }
149
+ return quantities;
150
+ }
151
+ export function buildHydrogenHostPorts(port, { cartRoute = '/cart', navigate = (url) => window.location.replace(url), openCartDrawer, clientNavigate } = {}) {
152
+ const followBehavior = (settings = {}, onCartDrawerOpen) => followApplyBehavior(settings, { navigate, cartRoute, openCartDrawer, onCartDrawerOpen });
153
+ return {
154
+ navigate: (url, { sameTab } = {}) => {
155
+ const target = safeNavigationUrl(url);
156
+ if (!target)
157
+ return;
158
+ if (!sameTab) {
159
+ window.open(target.href, '_blank', 'noopener,noreferrer');
160
+ return;
161
+ }
162
+ if (clientNavigate && target.origin === window.location.origin) {
163
+ clientNavigate(`${target.pathname}${target.search}${target.hash}`);
164
+ return;
165
+ }
166
+ window.location.assign(target.href);
167
+ },
168
+ applyDiscountCode: async ({ couponCode, settings = {}, isRedirect = true }) => {
169
+ const result = await port.applyDiscount(couponCode, { alwaysOverrideDiscount: !!settings.alwaysOverrideDiscount });
170
+ if (!result.ok)
171
+ return result;
172
+ const behavior = settings.customerApplyDiscountBehavior || 'go_to_cart';
173
+ if (behavior === 'open_cart_drawer' || (isRedirect && behavior === 'go_to_cart')) {
174
+ followBehavior({ ...settings, customerFreeGiftBehavior: undefined, customerApplyDiscountBehavior: behavior });
175
+ }
176
+ return result;
177
+ },
178
+ addToCartAfterRedeem: async ({ program = {}, settings = {}, variantIdFreeGiftSelected, couponCode, stockMap = {}, translation, onCartDrawerOpen }) => {
179
+ if (program.event !== 'free_gift' || program.appliedTo !== 'sf_product')
180
+ return;
181
+ if (!AUTO_ADD_GIFT_BEHAVIORS.includes(settings.customerFreeGiftBehavior || ''))
182
+ return;
183
+ const variantIds = giftVariantIds(program, variantIdFreeGiftSelected);
184
+ if (!variantIds.length)
185
+ return;
186
+ const inStock = availableVariantIds(stockMap, variantIds);
187
+ if (!inStock.length)
188
+ throw new Error(translate('All products are currently out of stock', translation));
189
+ const quantities = giftQuantities(program);
190
+ let added = inStock.length;
191
+ try {
192
+ added = await port.addGiftLines(inStock.map(id => ({ id: toVariantGid(id), quantity: quantities[id] || 1 })));
193
+ }
194
+ catch (error) {
195
+ if (inStock.length === 1)
196
+ throw error;
197
+ console.warn('[joy] some free gift lines could not be added', error);
198
+ }
199
+ if (!added)
200
+ throw new Error(translate('All products are currently out of stock', translation));
201
+ if (!couponCode)
202
+ return;
203
+ const result = await port.applyDiscount(couponCode, { alwaysOverrideDiscount: !!settings.alwaysOverrideDiscount });
204
+ if (!result.ok)
205
+ throw new Error(applyCouponFailedMessage(translation));
206
+ followBehavior(settings, onCartDrawerOpen);
207
+ },
208
+ applyReward: async ({ program = {}, settings = {}, couponCode, customer, variantIdFreeGiftSelected, stockMap = {}, translation, onCartDrawerOpen }) => {
209
+ if (!couponCode)
210
+ return { error: 'Missing coupon code' };
211
+ const isSpecificGift = program.event === 'free_gift' && (!program.appliedTo || program.appliedTo === 'sf_product');
212
+ const variantIds = giftVariantIds(program, variantIdFreeGiftSelected);
213
+ if (isSpecificGift && variantIds.length && settings.customerFreeGiftBehavior !== 'auto_add_to_cart') {
214
+ if (invalidVariantIds(stockMap, variantIds).length === variantIds.length) {
215
+ return {
216
+ error: translate('[[WidgetV4]]This reward is temporarily unavailable, please contact the store', translation)
217
+ };
218
+ }
219
+ const inStock = availableVariantIds(stockMap, variantIds);
220
+ if (!inStock.length)
221
+ return { error: translate('All products are currently out of stock', translation) };
222
+ const quantities = giftQuantities(program);
223
+ let added;
224
+ try {
225
+ added = await port.addGiftLines(inStock.map(id => ({ id: toVariantGid(id), quantity: quantities[id] || 1 })));
226
+ }
227
+ catch {
228
+ return { error: applyCouponFailedMessage(translation) };
229
+ }
230
+ if (!added)
231
+ return { error: translate('All products are currently out of stock', translation) };
232
+ }
233
+ const result = await port.applyDiscount(couponCode, { alwaysOverrideDiscount: !!settings.alwaysOverrideDiscount });
234
+ if (!result.ok)
235
+ return { error: applyCouponFailedMessage(translation) };
236
+ window.dispatchEvent(new CustomEvent('joy:applyCoupon', { detail: { couponCode, program: program || {}, customer: customer || {} } }));
237
+ followBehavior(settings, onCartDrawerOpen);
238
+ return { success: true };
239
+ },
240
+ getCart: async () => toAjaxCart(port.getCart())
241
+ };
242
+ }
243
+ export function buildLoyaltyPageSource({ structure, faqs, translations, shop, cartPort, locale }) {
244
+ return {
245
+ structure,
246
+ ...(locale ? { locale } : {}),
247
+ ...(faqs?.length ? { faqs } : {}),
248
+ translations,
249
+ shop,
250
+ ...(cartPort ? { cart: toLoyaltyPageCartPort(cartPort) } : {})
251
+ };
252
+ }
253
+ function isGuestAuthError(error) {
254
+ const e = error;
255
+ return !!e && (e.code === 'UNAUTHORIZED' || e.statusCode === 401);
256
+ }
257
+ export function withHomeComposite(client, blob, hints = {}) {
258
+ let servedCustomer = false;
259
+ return {
260
+ ...client,
261
+ async getLoyaltyPageV2Home(...args) {
262
+ let apiHalf;
263
+ try {
264
+ apiHalf = await client.getLoyaltyPageV2Home(...args);
265
+ }
266
+ catch (error) {
267
+ if (servedCustomer || !isGuestAuthError(error))
268
+ throw error;
269
+ apiHalf = { customer: {}, applePassWalletSetting: {}, customEarnStatus: {} };
270
+ }
271
+ if (apiHalf.customer?.id)
272
+ servedCustomer = true;
273
+ const composite = composeLoyaltyPageHome(blob, apiHalf, {
274
+ detectCountry: hints.detectCountry,
275
+ locale: hints.locale,
276
+ customerFirstName: hints.getCustomerFirstName?.()
277
+ });
278
+ return {
279
+ accountUrl: hints.accountUrl ?? '/account',
280
+ ...apiHalf,
281
+ ...composite,
282
+ customer: withRehostedReferralLink(composite.customer, hints.rehostReferralLink)
283
+ };
284
+ }
285
+ };
286
+ }
287
+ function withRehostedReferralLink(customer, rehost) {
288
+ const url = customer?.urlReferral;
289
+ if (!rehost || typeof url !== 'string' || !url)
290
+ return customer;
291
+ const rehosted = rehost(url);
292
+ return rehosted === url ? customer : { ...customer, urlReferral: rehosted };
293
+ }
294
+ function resolveCart(cart) {
295
+ return typeof cart === 'function' ? cart() : cart;
296
+ }
297
+ export function isLoyaltyPageV2Enabled(data) {
298
+ return data?.shop?.loyaltyPageVersion === 'v2';
299
+ }
300
+ export function JoyLoyaltyPage({ apiUrl, shopDomain, tokenRoute, sectionId, data, assetUrl, cart, cartFetcher, cartRevalidate, cartRoute, onCartUpdated, onOpenCartDrawer, onNavigate, initialData }) {
301
+ const { structure, faqs, translations, shop, home, country, locale } = data;
302
+ const enabled = isLoyaltyPageV2Enabled(data);
303
+ const sectionIds = useMemo(() => resolveSectionIds(sectionId, structure), [sectionId, structure]);
304
+ const faqEntities = useMemo(() => (isFaqSectionRendering(sectionIds) && faqs?.length ? faqs : null), [sectionIds, faqs]);
305
+ const cartRef = useRef(cart);
306
+ cartRef.current = cart;
307
+ const cartFetcherRef = useRef(cartFetcher);
308
+ cartFetcherRef.current = cartFetcher;
309
+ const cartRevalidateRef = useRef(cartRevalidate);
310
+ cartRevalidateRef.current = cartRevalidate;
311
+ const initialDataRef = useRef(initialData);
312
+ initialDataRef.current = initialData;
313
+ const onCartUpdatedRef = useRef(onCartUpdated);
314
+ onCartUpdatedRef.current = onCartUpdated;
315
+ const onOpenCartDrawerRef = useRef(onOpenCartDrawer);
316
+ onOpenCartDrawerRef.current = onOpenCartDrawer;
317
+ const onNavigateRef = useRef(onNavigate);
318
+ onNavigateRef.current = onNavigate;
319
+ const cartPortRef = useRef(null);
320
+ useEffect(() => {
321
+ cartPortRef.current?.settle();
322
+ });
323
+ const hostRef = useRef(null);
324
+ useEffect(() => {
325
+ if (typeof document === 'undefined' || !enabled)
326
+ return;
327
+ let cancelled = false;
328
+ let disposeMount;
329
+ publishStorefrontFonts();
330
+ const seedHost = hostRef.current;
331
+ if (seedHost && !seedHost.customer) {
332
+ const seed = buildInitialLoyaltyPageCustomer(initialDataRef.current, {
333
+ hasCachedToken: hasCachedJoyToken()
334
+ });
335
+ if (seed)
336
+ seedHost.customer = seed;
337
+ }
338
+ const seeded = seedHost?.customer;
339
+ const options = {
340
+ ...(assetUrl ? { assetUrl } : {}),
341
+ ...(data.core ? { core: data.core, preloadLazy: ['loyaltyPageV2'] } : {})
342
+ };
343
+ void loadWidgetCore(options).then(async ({ loaded, coreExports }) => {
344
+ if (cancelled || !loaded)
345
+ return;
346
+ const host = hostRef.current;
347
+ if (!host)
348
+ return;
349
+ const loadSurface = coreExports?.loadLoyaltyPageV2Core;
350
+ const surface = typeof loadSurface === 'function'
351
+ ? await loadSurface()
352
+ : {
353
+ mountLoyaltyPageV2Core: coreExports?.mountLoyaltyPageV2Core,
354
+ hydrateLoyaltyPageV2Live: coreExports?.hydrateLoyaltyPageV2Live
355
+ };
356
+ if (cancelled)
357
+ return;
358
+ const mount = surface.mountLoyaltyPageV2Core;
359
+ if (typeof mount !== 'function')
360
+ return;
361
+ const hydrate = surface.hydrateLoyaltyPageV2Live;
362
+ let cartPort;
363
+ if (cartFetcherRef.current && cartRevalidateRef.current) {
364
+ const { HydrogenCartPort: Port } = await import('../hydrogen-cart-port.js');
365
+ if (cancelled)
366
+ return;
367
+ cartPort = new Port({
368
+ fetcher: {
369
+ get state() {
370
+ return cartFetcherRef.current?.state ?? 'idle';
371
+ },
372
+ get data() {
373
+ return cartFetcherRef.current?.data;
374
+ },
375
+ submit: (data, submitOptions) => cartFetcherRef.current?.submit(data, submitOptions)
376
+ },
377
+ getCart: () => resolveCart(cartRef.current),
378
+ revalidate: () => cartRevalidateRef.current?.(),
379
+ onCartUpdated: updated => onCartUpdatedRef.current?.(updated),
380
+ ...(cartRoute ? { cartRoute } : {})
381
+ });
382
+ cartPortRef.current = cartPort;
383
+ host.hostPorts = buildHydrogenHostPorts(cartPort, {
384
+ ...(cartRoute ? { cartRoute } : {}),
385
+ openCartDrawer: () => {
386
+ if (!onOpenCartDrawerRef.current)
387
+ return false;
388
+ onOpenCartDrawerRef.current();
389
+ },
390
+ clientNavigate: url => (onNavigateRef.current ? onNavigateRef.current(url) : window.location.assign(safeNavigationUrl(url)?.href ?? '/'))
391
+ });
392
+ }
393
+ const { createHeadlessLoyaltyPageClient } = await import('@joy-loyalty/sdk/headless-loyalty-page-client');
394
+ if (cancelled)
395
+ return;
396
+ const referralShop = withHeadlessReferralOrigin(shop, window.location.origin);
397
+ disposeMount = mount(host, {
398
+ joyInstance: withHomeComposite(createHeadlessLoyaltyPageClient({
399
+ apiUrl,
400
+ shop: shopDomain,
401
+ ...(locale ? { locale } : {}),
402
+ getToken: () => getJoyToken(tokenRoute ? { tokenRoute } : {})
403
+ }), { ...home, translation: translations, shop: referralShop }, {
404
+ detectCountry: country,
405
+ locale,
406
+ getCustomerFirstName: getCachedJoyCustomerFirstName,
407
+ rehostReferralLink: link => toHeadlessReferralLink(link, shop, window.location.origin)
408
+ }),
409
+ source: buildLoyaltyPageSource({
410
+ structure,
411
+ faqs,
412
+ translations: withResolvedPointLabel(translations, home?.settings),
413
+ shop: referralShop,
414
+ cartPort,
415
+ locale
416
+ }),
417
+ ...(hydrate
418
+ ? {
419
+ hydrate: (el, joyInstance) => Promise.resolve()
420
+ .then(() => hydrate(el, joyInstance))
421
+ .finally(() => releaseStaleSeed(el, seeded))
422
+ }
423
+ : {})
424
+ });
425
+ if (!hydrate)
426
+ releaseStaleSeed(host, seeded);
427
+ }).catch(err => {
428
+ console.warn('[joy] failed to mount the loyalty page', err);
429
+ if (!cancelled && seedHost)
430
+ releaseStaleSeed(seedHost, seeded);
431
+ });
432
+ return () => {
433
+ cancelled = true;
434
+ disposeMount?.();
435
+ if (seedHost) {
436
+ const h = seedHost;
437
+ delete h.copy;
438
+ delete h.structure;
439
+ delete h.customer;
440
+ h.__joyLpV2HydrationStarted = false;
441
+ }
442
+ };
443
+ }, [apiUrl, shopDomain, tokenRoute, assetUrl, sectionId, enabled, locale]);
444
+ if (!enabled)
445
+ return null;
446
+ return (_jsxs("div", { children: [_jsx(WidgetCorePreloadLinks, { core: data.core, assetUrl: assetUrl, lazy: ['loyaltyPageV2'] }), _jsx(LoyaltyPageV2SkeletonStyles, {}), faqEntities ? _jsx(FaqJsonLd, { faqs: faqEntities }) : null, createElement('joy-loyalty-page-v2', { key: locale ?? '', ref: hostRef, ...(sectionId ? { 'section-id': sectionId } : {}) }, _jsx(LoyaltyPageV2Skeleton, { sectionIds: sectionIds, structure: structure }))] }));
447
+ }
@@ -0,0 +1,35 @@
1
+ import type { JoyMetafieldBlob } from '../lib/metafield-blob.js';
2
+ export interface LoyaltyPageHomeApiHalf {
3
+ customer?: unknown;
4
+ applePassWalletSetting?: unknown;
5
+ customEarnStatus?: Record<string, boolean>;
6
+ rewards?: unknown;
7
+ primaryTranslation?: Record<string, unknown>;
8
+ }
9
+ export interface LoyaltyPageHomeHostHints {
10
+ detectCountry?: string;
11
+ customerFirstName?: string | null;
12
+ locale?: string;
13
+ }
14
+ export interface LoyaltyPageHomeComposite {
15
+ earning: unknown[];
16
+ spending: unknown[];
17
+ tiers: Array<Record<string, unknown>>;
18
+ settings: unknown;
19
+ translation: Record<string, unknown>;
20
+ shopInfo: unknown;
21
+ shop: unknown;
22
+ shopId: string;
23
+ tierProgram: unknown;
24
+ settingsInteractWebsite: unknown;
25
+ interactWebsiteProgram: unknown;
26
+ settingsReferral: unknown;
27
+ referralProgram: unknown;
28
+ customer: unknown;
29
+ applePassWalletSetting: unknown;
30
+ rewards: unknown[];
31
+ detectCountry?: string;
32
+ detectLocale: string;
33
+ }
34
+ export declare function composeLoyaltyPageHome(blob: JoyMetafieldBlob | undefined, apiHalf: LoyaltyPageHomeApiHalf, hints?: LoyaltyPageHomeHostHints): LoyaltyPageHomeComposite;
35
+ export declare function withResolvedPointLabel(translations: unknown, settings: unknown): Record<string, unknown>;