@joy-loyalty/hydrogen 0.0.0-stage → 0.2.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/LICENSE +3 -0
- package/README.md +134 -2
- package/dist/cache-control.d.ts +8 -0
- package/dist/cache-control.js +6 -0
- package/dist/csp.d.ts +14 -0
- package/dist/csp.js +33 -0
- package/dist/headless-host-adapter.d.ts +5 -0
- package/dist/headless-host-adapter.js +197 -0
- package/dist/host-adapter/capabilities.d.ts +3 -0
- package/dist/host-adapter/capabilities.js +12 -0
- package/dist/host-adapter/data-source.d.ts +3 -0
- package/dist/host-adapter/data-source.js +49 -0
- package/dist/host-adapter/product-fetcher.d.ts +2 -0
- package/dist/host-adapter/product-fetcher.js +37 -0
- package/dist/host-adapter/promoted-collections.d.ts +2 -0
- package/dist/host-adapter/promoted-collections.js +43 -0
- package/dist/host-adapter/types.d.ts +212 -0
- package/dist/host-adapter/types.js +1 -0
- package/dist/hydrogen-cart-port.d.ts +134 -0
- package/dist/hydrogen-cart-port.js +245 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.js +15 -0
- package/dist/joy-widget.d.ts +29 -0
- package/dist/joy-widget.js +291 -0
- package/dist/lib/JoyProvider.d.ts +47 -0
- package/dist/lib/JoyProvider.js +95 -0
- package/dist/lib/account-links.d.ts +5 -0
- package/dist/lib/account-links.js +65 -0
- package/dist/lib/apply-behavior.d.ts +12 -0
- package/dist/lib/apply-behavior.js +26 -0
- package/dist/lib/core-loader.d.ts +63 -0
- package/dist/lib/core-loader.js +160 -0
- package/dist/lib/core-manifest.d.ts +7 -0
- package/dist/lib/core-manifest.js +54 -0
- package/dist/lib/core-preload-links.d.ts +8 -0
- package/dist/lib/core-preload-links.js +8 -0
- package/dist/lib/coupon-mapper.d.ts +95 -0
- package/dist/lib/coupon-mapper.js +167 -0
- package/dist/lib/custom-links.d.ts +22 -0
- package/dist/lib/custom-links.js +56 -0
- package/dist/lib/deeplink.d.ts +25 -0
- package/dist/lib/deeplink.js +92 -0
- package/dist/lib/earn-signup-gate.d.ts +3 -0
- package/dist/lib/earn-signup-gate.js +31 -0
- package/dist/lib/facebook-ref-link.d.ts +13 -0
- package/dist/lib/facebook-ref-link.js +31 -0
- package/dist/lib/headless-referral-origin.d.ts +2 -0
- package/dist/lib/headless-referral-origin.js +24 -0
- package/dist/lib/headless-source.d.ts +8 -0
- package/dist/lib/headless-source.js +71 -0
- package/dist/lib/image.d.ts +2 -0
- package/dist/lib/image.js +14 -0
- package/dist/lib/metafield-blob.d.ts +33 -0
- package/dist/lib/metafield-blob.js +76 -0
- package/dist/lib/money.d.ts +6 -0
- package/dist/lib/money.js +25 -0
- package/dist/lib/order-mapper.d.ts +44 -0
- package/dist/lib/order-mapper.js +141 -0
- package/dist/lib/place-order-scope.d.ts +6 -0
- package/dist/lib/place-order-scope.js +22 -0
- package/dist/lib/points.d.ts +5 -0
- package/dist/lib/points.js +10 -0
- package/dist/lib/recently-viewed-tracker.d.ts +1 -0
- package/dist/lib/recently-viewed-tracker.js +34 -0
- package/dist/lib/recommended-loader.d.ts +43 -0
- package/dist/lib/recommended-loader.js +111 -0
- package/dist/lib/referral-share.d.ts +4 -0
- package/dist/lib/referral-share.js +33 -0
- package/dist/lib/safe-navigation-url.d.ts +1 -0
- package/dist/lib/safe-navigation-url.js +9 -0
- package/dist/lib/server-token.d.ts +41 -0
- package/dist/lib/server-token.js +87 -0
- package/dist/lib/shop-locale.d.ts +1 -0
- package/dist/lib/shop-locale.js +21 -0
- package/dist/lib/social-earn.d.ts +11 -0
- package/dist/lib/social-earn.js +25 -0
- package/dist/lib/storefront-fonts.d.ts +5 -0
- package/dist/lib/storefront-fonts.js +52 -0
- package/dist/lib/token.d.ts +14 -0
- package/dist/lib/token.js +135 -0
- package/dist/lib/write-review.d.ts +2 -0
- package/dist/lib/write-review.js +44 -0
- package/dist/loyalty-page/JoyLoyaltyPage.d.ts +151 -0
- package/dist/loyalty-page/JoyLoyaltyPage.js +447 -0
- package/dist/loyalty-page/compose-home.d.ts +35 -0
- package/dist/loyalty-page/compose-home.js +177 -0
- package/dist/loyalty-page/skeleton.d.ts +11 -0
- package/dist/loyalty-page/skeleton.js +99 -0
- package/dist/orchestrator/context.d.ts +61 -0
- package/dist/orchestrator/context.js +64 -0
- package/dist/orchestrator/gated.d.ts +1 -0
- package/dist/orchestrator/gated.js +14 -0
- package/dist/orchestrator/handlers/account.d.ts +19 -0
- package/dist/orchestrator/handlers/account.js +266 -0
- package/dist/orchestrator/handlers/birthday.d.ts +6 -0
- package/dist/orchestrator/handlers/birthday.js +128 -0
- package/dist/orchestrator/handlers/earn.d.ts +5 -0
- package/dist/orchestrator/handlers/earn.js +258 -0
- package/dist/orchestrator/handlers/milestone-tier.d.ts +5 -0
- package/dist/orchestrator/handlers/milestone-tier.js +123 -0
- package/dist/orchestrator/handlers/profile.d.ts +5 -0
- package/dist/orchestrator/handlers/profile.js +262 -0
- package/dist/orchestrator/handlers/redeem.d.ts +6 -0
- package/dist/orchestrator/handlers/redeem.js +464 -0
- package/dist/orchestrator/handlers/referral.d.ts +5 -0
- package/dist/orchestrator/handlers/referral.js +218 -0
- package/dist/orchestrator/render.d.ts +2 -0
- package/dist/orchestrator/render.js +193 -0
- package/dist/render-adapter.d.ts +50 -0
- package/dist/render-adapter.js +422 -0
- package/dist/routes/joy-place-order-scope.d.ts +12 -0
- package/dist/routes/joy-place-order-scope.js +32 -0
- package/dist/routes/joy-products.d.ts +48 -0
- package/dist/routes/joy-products.js +326 -0
- package/dist/routes/joy-token.d.ts +16 -0
- package/dist/routes/joy-token.js +32 -0
- package/dist/server/get-joy-initial-data.d.ts +38 -0
- package/dist/server/get-joy-initial-data.js +61 -0
- package/dist/server/get-joy-loyalty-page-data.d.ts +27 -0
- package/dist/server/get-joy-loyalty-page-data.js +99 -0
- package/dist/server/index.d.ts +8 -0
- package/dist/server/index.js +4 -0
- package/dist/widget-controller.d.ts +2 -0
- package/dist/widget-controller.js +1 -0
- package/dist/widget-orchestrator.d.ts +88 -0
- package/dist/widget-orchestrator.js +499 -0
- package/package.json +121 -4
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { PointLabel } from '@joy-loyalty/sdk/client';
|
|
2
|
+
export declare const DEFAULT_POINTS_LABEL = "points";
|
|
3
|
+
export declare const POINTS_LABEL_HELP = "Leave it as it is to use your shop\u2019s own point name from Joy, singular or plural to match the number.";
|
|
4
|
+
export declare function resolvePointsLabel(count: number, setting: string, shopLabel?: PointLabel | null): string;
|
|
5
|
+
export declare function formatPointsNumber(value: number, locale?: string): string;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export const DEFAULT_POINTS_LABEL = 'points';
|
|
2
|
+
export const POINTS_LABEL_HELP = 'Leave it as it is to use your shop’s own point name from Joy, singular or plural to match the number.';
|
|
3
|
+
export function resolvePointsLabel(count, setting, shopLabel) {
|
|
4
|
+
if (setting !== DEFAULT_POINTS_LABEL || !shopLabel)
|
|
5
|
+
return setting;
|
|
6
|
+
return Math.abs(count) === 1 ? shopLabel.singular : shopLabel.plural;
|
|
7
|
+
}
|
|
8
|
+
export function formatPointsNumber(value, locale) {
|
|
9
|
+
return value.toLocaleString(locale || 'en-US');
|
|
10
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function trackRecentlyViewedProduct(pathname: string): void;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { PRODUCT_PATH_PATTERN, RECENTLY_VIEWED_STORAGE_KEY as STORAGE_KEY } from '@joy-loyalty/sdk/widget-contracts';
|
|
2
|
+
const MAX_ITEMS = 20;
|
|
3
|
+
function getLocalStorage() {
|
|
4
|
+
try {
|
|
5
|
+
return typeof localStorage === 'undefined' ? null : localStorage;
|
|
6
|
+
}
|
|
7
|
+
catch {
|
|
8
|
+
return null;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
function readStored(store) {
|
|
12
|
+
try {
|
|
13
|
+
const parsed = JSON.parse(store.getItem(STORAGE_KEY) || '[]');
|
|
14
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return [];
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
export function trackRecentlyViewedProduct(pathname) {
|
|
21
|
+
const handle = pathname.match(PRODUCT_PATH_PATTERN)?.[1];
|
|
22
|
+
if (!handle)
|
|
23
|
+
return;
|
|
24
|
+
const store = getLocalStorage();
|
|
25
|
+
if (!store)
|
|
26
|
+
return;
|
|
27
|
+
const items = readStored(store).filter(item => item.handle !== handle);
|
|
28
|
+
items.unshift({ id: handle, handle, title: handle, url: `/products/${handle}` });
|
|
29
|
+
try {
|
|
30
|
+
store.setItem(STORAGE_KEY, JSON.stringify(items.slice(0, MAX_ITEMS)));
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
}
|
|
34
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
export interface SubscriptionOffer {
|
|
2
|
+
productId: string;
|
|
3
|
+
handle: string;
|
|
4
|
+
lowestCents: number;
|
|
5
|
+
originalCents: number;
|
|
6
|
+
savingsPercent: number;
|
|
7
|
+
}
|
|
8
|
+
export interface ProductCardHelpers {
|
|
9
|
+
prepareCdnShopifyImage(url: string, width?: number): string;
|
|
10
|
+
formatShopifyPrice(cents: number, currency?: string): string;
|
|
11
|
+
extractProductImages(product: unknown): {
|
|
12
|
+
primary: string;
|
|
13
|
+
secondary: string;
|
|
14
|
+
};
|
|
15
|
+
extractCompareAtPriceCents(product: unknown): number | null;
|
|
16
|
+
extractSubscriptionOffer(product: unknown): SubscriptionOffer | null;
|
|
17
|
+
buildSubscriptionOfferIndex(offers: SubscriptionOffer[]): Record<string, SubscriptionOffer>;
|
|
18
|
+
resolveSubscriptionConfig(sections: unknown, legacySectionId?: string): {
|
|
19
|
+
enabled: boolean;
|
|
20
|
+
showDiscountedPrice: boolean;
|
|
21
|
+
showChip: boolean;
|
|
22
|
+
};
|
|
23
|
+
DEFAULT_CHIP_TEMPLATE: string;
|
|
24
|
+
}
|
|
25
|
+
export interface WidgetSection {
|
|
26
|
+
id?: string;
|
|
27
|
+
[key: string]: unknown;
|
|
28
|
+
}
|
|
29
|
+
export interface RecommendedWidgetElement {
|
|
30
|
+
recentProducts?: unknown[];
|
|
31
|
+
recentProductsLoading?: boolean;
|
|
32
|
+
subscriptionOffers?: Record<string, SubscriptionOffer>;
|
|
33
|
+
subscriptionChipTemplate?: string;
|
|
34
|
+
subscriptionShowChip?: boolean;
|
|
35
|
+
}
|
|
36
|
+
export interface LoadRecommendedOptions {
|
|
37
|
+
widgetEl: RecommendedWidgetElement;
|
|
38
|
+
sections: readonly WidgetSection[];
|
|
39
|
+
productCard?: ProductCardHelpers;
|
|
40
|
+
currency?: string;
|
|
41
|
+
productsRoute?: string;
|
|
42
|
+
}
|
|
43
|
+
export declare function loadRecommendedProducts({ widgetEl, sections, productCard, currency, productsRoute }: LoadRecommendedOptions): Promise<void>;
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { DEFAULT_PRODUCTS_ROUTE } from '../headless-host-adapter.js';
|
|
2
|
+
import { PRODUCT_PATH_PATTERN, RECENTLY_VIEWED_STORAGE_KEY as STORAGE_KEY } from '@joy-loyalty/sdk/widget-contracts';
|
|
3
|
+
const AUTO_SIGNALS = ['product_page', 'recently_viewed'];
|
|
4
|
+
const CARD_IMAGE_WIDTH = 400;
|
|
5
|
+
export async function loadRecommendedProducts({ widgetEl, sections, productCard, currency, productsRoute = DEFAULT_PRODUCTS_ROUTE }) {
|
|
6
|
+
try {
|
|
7
|
+
if (!productCard) {
|
|
8
|
+
console.warn('[joy] recommendations skipped: the loaded widget core has no `productCard` export ' +
|
|
9
|
+
'(CDN artifact predates it — rebuild/republish, or point `assetUrl` at a local build)');
|
|
10
|
+
return;
|
|
11
|
+
}
|
|
12
|
+
const section = (sections.find(entry => entry?.id === 'PRODUCTS') ?? {});
|
|
13
|
+
const { products, currencyCode } = await fetchRecommended(productsRoute, section);
|
|
14
|
+
if (!products.length)
|
|
15
|
+
return;
|
|
16
|
+
const subConfig = productCard.resolveSubscriptionConfig(sections, 'PRODUCTS');
|
|
17
|
+
const offers = [];
|
|
18
|
+
const displayCurrency = currencyCode || currency;
|
|
19
|
+
widgetEl.recentProducts = products.map(product => toCard(product, { productCard, subConfig, currency: displayCurrency, offers }));
|
|
20
|
+
widgetEl.subscriptionOffers = {
|
|
21
|
+
...(widgetEl.subscriptionOffers ?? {}),
|
|
22
|
+
...productCard.buildSubscriptionOfferIndex(offers)
|
|
23
|
+
};
|
|
24
|
+
widgetEl.subscriptionChipTemplate = productCard.DEFAULT_CHIP_TEMPLATE;
|
|
25
|
+
widgetEl.subscriptionShowChip = subConfig.showChip;
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
console.warn('[joy] product recommendations failed:', error);
|
|
29
|
+
}
|
|
30
|
+
finally {
|
|
31
|
+
widgetEl.recentProductsLoading = false;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
async function fetchRecommended(route, section) {
|
|
35
|
+
const empty = { products: [], currencyCode: null };
|
|
36
|
+
const params = new URLSearchParams({ recommend: resolveSeedHandle(section.personalizeFrom) });
|
|
37
|
+
if (section.fallbackCollectionHandle)
|
|
38
|
+
params.set('fallbackCollection', section.fallbackCollectionHandle);
|
|
39
|
+
if (section.fallbackSort)
|
|
40
|
+
params.set('fallbackSort', section.fallbackSort);
|
|
41
|
+
const response = await fetch(`${route}?${params}`, {
|
|
42
|
+
headers: { Accept: 'application/json' },
|
|
43
|
+
credentials: 'same-origin'
|
|
44
|
+
});
|
|
45
|
+
if (!response.ok)
|
|
46
|
+
return empty;
|
|
47
|
+
const body = (await response.json());
|
|
48
|
+
if (!Array.isArray(body.products))
|
|
49
|
+
return empty;
|
|
50
|
+
return {
|
|
51
|
+
products: body.products.filter((product) => !!product),
|
|
52
|
+
currencyCode: body.currencyCode ?? null
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
function resolveSeedHandle(strategy) {
|
|
56
|
+
const order = !strategy || strategy === 'auto' ? AUTO_SIGNALS : [strategy];
|
|
57
|
+
for (const signal of order) {
|
|
58
|
+
const handle = readSignal(signal);
|
|
59
|
+
if (handle)
|
|
60
|
+
return handle;
|
|
61
|
+
}
|
|
62
|
+
return '';
|
|
63
|
+
}
|
|
64
|
+
function readSignal(signal) {
|
|
65
|
+
if (signal === 'product_page')
|
|
66
|
+
return currentProductHandle();
|
|
67
|
+
if (signal === 'recently_viewed')
|
|
68
|
+
return firstRecentlyViewedHandle();
|
|
69
|
+
return '';
|
|
70
|
+
}
|
|
71
|
+
function currentProductHandle() {
|
|
72
|
+
if (typeof window === 'undefined')
|
|
73
|
+
return '';
|
|
74
|
+
return window.location?.pathname?.match(PRODUCT_PATH_PATTERN)?.[1] ?? '';
|
|
75
|
+
}
|
|
76
|
+
function firstRecentlyViewedHandle() {
|
|
77
|
+
try {
|
|
78
|
+
const stored = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]');
|
|
79
|
+
const newest = Array.isArray(stored) ? stored[0] : null;
|
|
80
|
+
const handle = newest?.handle || newest?.id;
|
|
81
|
+
return typeof handle === 'string' ? handle : '';
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
return '';
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
function toCard(product, ctx) {
|
|
88
|
+
const { productCard, subConfig, currency, offers } = ctx;
|
|
89
|
+
const { primary, secondary } = productCard.extractProductImages(product);
|
|
90
|
+
let price = typeof product.price === 'number' ? productCard.formatShopifyPrice(product.price, currency) : '';
|
|
91
|
+
const compareAtCents = productCard.extractCompareAtPriceCents(product);
|
|
92
|
+
let compareAtPrice = compareAtCents !== null ? productCard.formatShopifyPrice(compareAtCents, currency) : '';
|
|
93
|
+
const offer = subConfig.enabled ? productCard.extractSubscriptionOffer(product) : null;
|
|
94
|
+
if (offer) {
|
|
95
|
+
offers.push(offer);
|
|
96
|
+
if (subConfig.showDiscountedPrice) {
|
|
97
|
+
price = productCard.formatShopifyPrice(offer.lowestCents, currency);
|
|
98
|
+
compareAtPrice = productCard.formatShopifyPrice(offer.originalCents, currency);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return {
|
|
102
|
+
id: product.id ?? '',
|
|
103
|
+
handle: product.handle ?? '',
|
|
104
|
+
image: productCard.prepareCdnShopifyImage(primary, CARD_IMAGE_WIDTH),
|
|
105
|
+
imageHover: secondary ? productCard.prepareCdnShopifyImage(secondary, CARD_IMAGE_WIDTH) : '',
|
|
106
|
+
title: product.title ?? '',
|
|
107
|
+
price,
|
|
108
|
+
compareAtPrice,
|
|
109
|
+
url: product.url || (product.handle ? `/products/${product.handle}` : '')
|
|
110
|
+
};
|
|
111
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export declare const SOCIAL_EMAIL = "email";
|
|
2
|
+
export declare function getShareEmailUrl(m?: string): string;
|
|
3
|
+
export declare const CONTENT_MAIL_SHARE_LINK_REFERRAL = "mailto:example@mail.com?body=Click%20here%20to%20go%20to%20store%20";
|
|
4
|
+
export declare function getLinkSocial(app: string, message: string): string;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export const SOCIAL_EMAIL = 'email';
|
|
2
|
+
const SOCIAL_FACEBOOK = 'facebook';
|
|
3
|
+
const SOCIAL_WHATSAPP = 'whatsapp';
|
|
4
|
+
const SOCIAL_TWITTER = 'twitter';
|
|
5
|
+
const SOCIAL_THREADS = 'threads';
|
|
6
|
+
const SOCIAL_MESSENGER = 'messenger';
|
|
7
|
+
const SOCIAL_LINE = 'line';
|
|
8
|
+
export function getShareEmailUrl(m = '') {
|
|
9
|
+
return 'mailto:example@mail.com?body=' + encodeURIComponent(m);
|
|
10
|
+
}
|
|
11
|
+
export const CONTENT_MAIL_SHARE_LINK_REFERRAL = 'mailto:example@mail.com?body=Click%20here%20to%20go%20to%20store%20';
|
|
12
|
+
export function getLinkSocial(app, message) {
|
|
13
|
+
const encodeURI = encodeURIComponent(message);
|
|
14
|
+
const url = (() => {
|
|
15
|
+
switch (app) {
|
|
16
|
+
case SOCIAL_FACEBOOK:
|
|
17
|
+
return `https://www.facebook.com/sharer/sharer.php?u=${message}`;
|
|
18
|
+
case SOCIAL_WHATSAPP:
|
|
19
|
+
return `https://wa.me/?&text=`;
|
|
20
|
+
case SOCIAL_TWITTER:
|
|
21
|
+
return 'https://twitter.com/intent/tweet?&text=';
|
|
22
|
+
case SOCIAL_THREADS:
|
|
23
|
+
return 'https://www.threads.net/intent/post?text=';
|
|
24
|
+
case SOCIAL_MESSENGER:
|
|
25
|
+
return 'https://www.messenger.com/new?text=';
|
|
26
|
+
case SOCIAL_LINE:
|
|
27
|
+
return 'https://line.me/R/msg/text/?';
|
|
28
|
+
default:
|
|
29
|
+
return undefined;
|
|
30
|
+
}
|
|
31
|
+
})();
|
|
32
|
+
return `${url}${encodeURI}`;
|
|
33
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function safeNavigationUrl(url: string): URL | null;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
export interface JoyCustomerAccount {
|
|
2
|
+
isLoggedIn(): Promise<boolean>;
|
|
3
|
+
query(query: string, options?: unknown): Promise<{
|
|
4
|
+
data?: {
|
|
5
|
+
customer?: {
|
|
6
|
+
id?: string | null;
|
|
7
|
+
firstName?: string | null;
|
|
8
|
+
lastName?: string | null;
|
|
9
|
+
emailAddress?: {
|
|
10
|
+
emailAddress?: string | null;
|
|
11
|
+
} | null;
|
|
12
|
+
} | null;
|
|
13
|
+
} | null;
|
|
14
|
+
errors?: unknown;
|
|
15
|
+
}>;
|
|
16
|
+
}
|
|
17
|
+
export interface MintJoyTokenParams {
|
|
18
|
+
customerAccount: JoyCustomerAccount;
|
|
19
|
+
apiUrl: string;
|
|
20
|
+
shopDomain: string;
|
|
21
|
+
secret: string;
|
|
22
|
+
}
|
|
23
|
+
export type MintJoyTokenFailureReason = 'not_logged_in' | 'customer_unresolved' | 'upstream_unreachable' | 'upstream_bad_response' | 'exchange_failed';
|
|
24
|
+
export interface MintedCustomerIdentity {
|
|
25
|
+
id: string;
|
|
26
|
+
firstName: string | null;
|
|
27
|
+
lastName: string | null;
|
|
28
|
+
email: string;
|
|
29
|
+
}
|
|
30
|
+
export type MintJoyTokenResult = {
|
|
31
|
+
ok: true;
|
|
32
|
+
token: string;
|
|
33
|
+
tokenType: string;
|
|
34
|
+
expiresIn: number;
|
|
35
|
+
identity: MintedCustomerIdentity;
|
|
36
|
+
} | {
|
|
37
|
+
ok: false;
|
|
38
|
+
reason: MintJoyTokenFailureReason;
|
|
39
|
+
status: number;
|
|
40
|
+
};
|
|
41
|
+
export declare function mintJoyToken({ customerAccount, apiUrl, shopDomain, secret }: MintJoyTokenParams): Promise<MintJoyTokenResult>;
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
const CUSTOMER_QUERY = `#graphql
|
|
2
|
+
query JoyCustomer {
|
|
3
|
+
customer {
|
|
4
|
+
id
|
|
5
|
+
firstName
|
|
6
|
+
lastName
|
|
7
|
+
emailAddress {
|
|
8
|
+
emailAddress
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
`;
|
|
13
|
+
export async function mintJoyToken({ customerAccount, apiUrl, shopDomain, secret }) {
|
|
14
|
+
if (!(await customerAccount.isLoggedIn())) {
|
|
15
|
+
return { ok: false, reason: 'not_logged_in', status: 401 };
|
|
16
|
+
}
|
|
17
|
+
let customerId = null;
|
|
18
|
+
let email = null;
|
|
19
|
+
let firstName = null;
|
|
20
|
+
let lastName = null;
|
|
21
|
+
try {
|
|
22
|
+
const { data } = await customerAccount.query(CUSTOMER_QUERY);
|
|
23
|
+
customerId = numericCustomerId(data?.customer?.id);
|
|
24
|
+
email = data?.customer?.emailAddress?.emailAddress ?? null;
|
|
25
|
+
firstName = data?.customer?.firstName ?? null;
|
|
26
|
+
lastName = data?.customer?.lastName ?? null;
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return { ok: false, reason: 'customer_unresolved', status: 401 };
|
|
30
|
+
}
|
|
31
|
+
if (!customerId || !email) {
|
|
32
|
+
return { ok: false, reason: 'customer_unresolved', status: 401 };
|
|
33
|
+
}
|
|
34
|
+
const ts = Math.floor(Date.now() / 1000);
|
|
35
|
+
const hmac = await hmacHex(`${customerId}-${email.toLowerCase()}-${ts}`, secret);
|
|
36
|
+
let response;
|
|
37
|
+
try {
|
|
38
|
+
response = await fetch(`${apiUrl.replace(/\/+$/, '')}/auth/token`, {
|
|
39
|
+
method: 'POST',
|
|
40
|
+
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
|
41
|
+
body: JSON.stringify({
|
|
42
|
+
grant_type: 'hmac',
|
|
43
|
+
shopDomain,
|
|
44
|
+
customerId,
|
|
45
|
+
email,
|
|
46
|
+
hmac,
|
|
47
|
+
ts
|
|
48
|
+
})
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return { ok: false, reason: 'upstream_unreachable', status: 502 };
|
|
53
|
+
}
|
|
54
|
+
let body;
|
|
55
|
+
try {
|
|
56
|
+
body = await response.json();
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return { ok: false, reason: 'upstream_bad_response', status: 502 };
|
|
60
|
+
}
|
|
61
|
+
const token = body?.data?.token;
|
|
62
|
+
if (!response.ok || body?.success === false || !token) {
|
|
63
|
+
return { ok: false, reason: 'exchange_failed', status: response.status === 401 ? 401 : 502 };
|
|
64
|
+
}
|
|
65
|
+
return {
|
|
66
|
+
ok: true,
|
|
67
|
+
token,
|
|
68
|
+
tokenType: body?.data?.tokenType ?? 'Bearer',
|
|
69
|
+
expiresIn: body?.data?.expiresIn ?? 3600,
|
|
70
|
+
identity: { id: customerId, firstName, lastName, email }
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
function numericCustomerId(gid) {
|
|
74
|
+
if (!gid)
|
|
75
|
+
return null;
|
|
76
|
+
const last = gid
|
|
77
|
+
.split('/')
|
|
78
|
+
.pop()
|
|
79
|
+
?.split('?')[0] ?? '';
|
|
80
|
+
return /^\d+$/.test(last) ? last : null;
|
|
81
|
+
}
|
|
82
|
+
async function hmacHex(message, secret) {
|
|
83
|
+
const encoder = new TextEncoder();
|
|
84
|
+
const key = await crypto.subtle.importKey('raw', encoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
|
|
85
|
+
const signature = await crypto.subtle.sign('HMAC', key, encoder.encode(message));
|
|
86
|
+
return [...new Uint8Array(signature)].map(byte => byte.toString(16).padStart(2, '0')).join('');
|
|
87
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function resolveShopLocale(locale: string | undefined, blobTranslation: unknown): string | undefined;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export function resolveShopLocale(locale, blobTranslation) {
|
|
2
|
+
if (!isRecord(blobTranslation))
|
|
3
|
+
return locale;
|
|
4
|
+
const primary = blobTranslation.primaryLanguage;
|
|
5
|
+
if (typeof primary !== 'string' || !primary)
|
|
6
|
+
return locale;
|
|
7
|
+
if (!locale)
|
|
8
|
+
return primary;
|
|
9
|
+
if (blobTranslation.detectMethod === OPTIONAL_STOREFRONT_LANGUAGE)
|
|
10
|
+
return locale;
|
|
11
|
+
const norm = locale.replace(/_/g, '-').toLowerCase();
|
|
12
|
+
if (norm === primary.toLowerCase())
|
|
13
|
+
return primary;
|
|
14
|
+
const additional = Array.isArray(blobTranslation.additionalLanguages) ? blobTranslation.additionalLanguages : [];
|
|
15
|
+
const active = additional.find(lang => isRecord(lang) && lang.active && typeof lang.code === 'string' && lang.code.toLowerCase() === norm);
|
|
16
|
+
return active ? active.code : primary;
|
|
17
|
+
}
|
|
18
|
+
const OPTIONAL_STOREFRONT_LANGUAGE = 'optionalStorefrontLanguage';
|
|
19
|
+
function isRecord(value) {
|
|
20
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
21
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare const SOCIAL_EARN_EVENT_KEYS: ReadonlySet<string>;
|
|
2
|
+
export declare function isSocialEarnProgram(program: {
|
|
3
|
+
key: string;
|
|
4
|
+
}): boolean;
|
|
5
|
+
export declare function isLineFollowOaProgram(program: {
|
|
6
|
+
key: string;
|
|
7
|
+
lineJoinType?: string | null;
|
|
8
|
+
}): boolean;
|
|
9
|
+
export declare function isRepeatableSocialProgram(program: {
|
|
10
|
+
key: string;
|
|
11
|
+
}): boolean;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export const SOCIAL_EARN_EVENT_KEYS = new Set([
|
|
2
|
+
'follow_instagram',
|
|
3
|
+
'like_facebook',
|
|
4
|
+
'follow_tiktok',
|
|
5
|
+
'share_facebook',
|
|
6
|
+
'subscribe_youtube',
|
|
7
|
+
'follow_twitter',
|
|
8
|
+
'follow_pinterest',
|
|
9
|
+
'share_twitter',
|
|
10
|
+
'join_discord',
|
|
11
|
+
'join_telegram',
|
|
12
|
+
'join_whatsapp',
|
|
13
|
+
'join_line',
|
|
14
|
+
'join_reddit'
|
|
15
|
+
]);
|
|
16
|
+
export function isSocialEarnProgram(program) {
|
|
17
|
+
return SOCIAL_EARN_EVENT_KEYS.has(program.key);
|
|
18
|
+
}
|
|
19
|
+
export function isLineFollowOaProgram(program) {
|
|
20
|
+
return program.key === 'join_line' && program.lineJoinType === 'follow_oa';
|
|
21
|
+
}
|
|
22
|
+
const REPEATABLE_SOCIAL_KEYS = new Set(['share_facebook', 'share_twitter']);
|
|
23
|
+
export function isRepeatableSocialProgram(program) {
|
|
24
|
+
return REPEATABLE_SOCIAL_KEYS.has(program.key);
|
|
25
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
const JOY_SELECTOR = 'joy-loyalty-page-v2, [id*="joy" i], [class*="joy-" i], joy-fab-button';
|
|
2
|
+
const MAX_SAMPLE = 40;
|
|
3
|
+
const MIN_DISPLAY_PX = 24;
|
|
4
|
+
function isSampleable(el) {
|
|
5
|
+
if (!el.offsetParent && el !== document.body)
|
|
6
|
+
return false;
|
|
7
|
+
if (!el.textContent || el.textContent.trim().length < 4)
|
|
8
|
+
return false;
|
|
9
|
+
return !el.closest(JOY_SELECTOR);
|
|
10
|
+
}
|
|
11
|
+
function dominantFamily(selector, filter) {
|
|
12
|
+
const counts = new Map();
|
|
13
|
+
let sampled = 0;
|
|
14
|
+
for (const el of Array.from(document.querySelectorAll(selector))) {
|
|
15
|
+
if (sampled >= MAX_SAMPLE)
|
|
16
|
+
break;
|
|
17
|
+
if (!isSampleable(el) || (filter && !filter(el)))
|
|
18
|
+
continue;
|
|
19
|
+
sampled++;
|
|
20
|
+
const family = getComputedStyle(el).fontFamily;
|
|
21
|
+
if (family)
|
|
22
|
+
counts.set(family, (counts.get(family) || 0) + 1);
|
|
23
|
+
}
|
|
24
|
+
let best = '';
|
|
25
|
+
let bestCount = 0;
|
|
26
|
+
for (const [family, count] of counts) {
|
|
27
|
+
if (count > bestCount) {
|
|
28
|
+
best = family;
|
|
29
|
+
bestCount = count;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return best;
|
|
33
|
+
}
|
|
34
|
+
export function detectStorefrontFonts() {
|
|
35
|
+
const bodyFont = dominantFamily('main p, main li, article p, .rte p') ||
|
|
36
|
+
getComputedStyle(document.body).fontFamily ||
|
|
37
|
+
'';
|
|
38
|
+
const headingFont = dominantFamily('main h1, main h2, article h1, article h2', el => parseFloat(getComputedStyle(el).fontSize) >= MIN_DISPLAY_PX) || bodyFont;
|
|
39
|
+
return { bodyFont, headingFont };
|
|
40
|
+
}
|
|
41
|
+
export function publishStorefrontFonts() {
|
|
42
|
+
if (typeof document === 'undefined' || !document.body)
|
|
43
|
+
return;
|
|
44
|
+
const root = document.documentElement;
|
|
45
|
+
if (root.style.getPropertyValue('--joy-storefront-font-body'))
|
|
46
|
+
return;
|
|
47
|
+
const { bodyFont, headingFont } = detectStorefrontFonts();
|
|
48
|
+
if (bodyFont)
|
|
49
|
+
root.style.setProperty('--joy-storefront-font-body', bodyFont);
|
|
50
|
+
if (headingFont)
|
|
51
|
+
root.style.setProperty('--joy-storefront-font-heading', headingFont);
|
|
52
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export declare const DEFAULT_TOKEN_ROUTE = "/api/joy-token";
|
|
2
|
+
export declare const GUEST_INFO_SKIP = "joy:guest-info-skip";
|
|
3
|
+
export interface GetJoyTokenOptions {
|
|
4
|
+
tokenRoute?: string;
|
|
5
|
+
force?: boolean;
|
|
6
|
+
}
|
|
7
|
+
export declare function getJoyToken(options?: GetJoyTokenOptions): Promise<string | null>;
|
|
8
|
+
export declare function clearJoyToken(): void;
|
|
9
|
+
export declare function revokeAndClearJoyToken(options: {
|
|
10
|
+
apiBase: string;
|
|
11
|
+
}): void;
|
|
12
|
+
export declare function dropJoyTokenIfCustomerMismatch(customerId: string): boolean;
|
|
13
|
+
export declare function hasCachedJoyToken(): boolean;
|
|
14
|
+
export declare function getCachedJoyCustomerFirstName(): string | null;
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
export const DEFAULT_TOKEN_ROUTE = '/api/joy-token';
|
|
2
|
+
export const GUEST_INFO_SKIP = 'joy:guest-info-skip';
|
|
3
|
+
import { Joy } from '@joy-loyalty/sdk/client';
|
|
4
|
+
import { clearEarnSignupSent } from './earn-signup-gate.js';
|
|
5
|
+
const STORAGE_KEY = 'joy:token';
|
|
6
|
+
const EXPIRY_SKEW_MS = 30_000;
|
|
7
|
+
let inflight = null;
|
|
8
|
+
let guestRoute = null;
|
|
9
|
+
export async function getJoyToken(options = {}) {
|
|
10
|
+
const route = options.tokenRoute ?? DEFAULT_TOKEN_ROUTE;
|
|
11
|
+
if (!options.force) {
|
|
12
|
+
const cached = readStored();
|
|
13
|
+
if (cached && cached.expiresAt > Date.now() + EXPIRY_SKEW_MS)
|
|
14
|
+
return cached.token;
|
|
15
|
+
if (guestRoute === route)
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
if (inflight)
|
|
19
|
+
return inflight;
|
|
20
|
+
inflight = exchange(route).finally(() => {
|
|
21
|
+
inflight = null;
|
|
22
|
+
});
|
|
23
|
+
return inflight;
|
|
24
|
+
}
|
|
25
|
+
export function clearJoyToken() {
|
|
26
|
+
guestRoute = null;
|
|
27
|
+
writeStored(null);
|
|
28
|
+
clearEarnSignupSent();
|
|
29
|
+
}
|
|
30
|
+
export function revokeAndClearJoyToken(options) {
|
|
31
|
+
const cached = readStored();
|
|
32
|
+
if (cached?.token) {
|
|
33
|
+
try {
|
|
34
|
+
fetch(`${options.apiBase}/customer/auth/logout`, {
|
|
35
|
+
method: 'POST',
|
|
36
|
+
headers: { Authorization: `Bearer ${cached.token}` },
|
|
37
|
+
keepalive: true
|
|
38
|
+
}).catch(() => { });
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
clearJoyToken();
|
|
44
|
+
try {
|
|
45
|
+
Joy.getClient().logout();
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
export function dropJoyTokenIfCustomerMismatch(customerId) {
|
|
51
|
+
const cached = readStored();
|
|
52
|
+
if (!cached || cached.customerId === customerId)
|
|
53
|
+
return false;
|
|
54
|
+
clearJoyToken();
|
|
55
|
+
return true;
|
|
56
|
+
}
|
|
57
|
+
export function hasCachedJoyToken() {
|
|
58
|
+
const cached = readStored();
|
|
59
|
+
return cached !== null && cached.expiresAt > Date.now() + EXPIRY_SKEW_MS;
|
|
60
|
+
}
|
|
61
|
+
export function getCachedJoyCustomerFirstName() {
|
|
62
|
+
const cached = readStored();
|
|
63
|
+
if (!cached || cached.expiresAt <= Date.now() + EXPIRY_SKEW_MS)
|
|
64
|
+
return null;
|
|
65
|
+
return cached.firstName || null;
|
|
66
|
+
}
|
|
67
|
+
async function exchange(route) {
|
|
68
|
+
let response;
|
|
69
|
+
try {
|
|
70
|
+
response = await fetch(route, { headers: { Accept: 'application/json' }, credentials: 'same-origin' });
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
if (response.status === 401) {
|
|
76
|
+
guestRoute = route;
|
|
77
|
+
writeStored(null);
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
if (!response.ok)
|
|
81
|
+
return null;
|
|
82
|
+
let body;
|
|
83
|
+
try {
|
|
84
|
+
body = await response.json();
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
if (!body?.token)
|
|
90
|
+
return null;
|
|
91
|
+
guestRoute = null;
|
|
92
|
+
const expiresIn = typeof body.expiresIn === 'number' ? body.expiresIn : 3600;
|
|
93
|
+
const firstName = typeof body.firstName === 'string' && body.firstName ? { firstName: body.firstName } : {};
|
|
94
|
+
const customerId = typeof body.customerId === 'string' && body.customerId ? { customerId: body.customerId } : {};
|
|
95
|
+
writeStored({ token: body.token, expiresAt: Date.now() + expiresIn * 1000, ...firstName, ...customerId });
|
|
96
|
+
return body.token;
|
|
97
|
+
}
|
|
98
|
+
function getStore() {
|
|
99
|
+
try {
|
|
100
|
+
return typeof sessionStorage === 'undefined' ? null : sessionStorage;
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
function readStored() {
|
|
107
|
+
const store = getStore();
|
|
108
|
+
if (!store)
|
|
109
|
+
return null;
|
|
110
|
+
try {
|
|
111
|
+
const raw = store.getItem(STORAGE_KEY);
|
|
112
|
+
if (!raw)
|
|
113
|
+
return null;
|
|
114
|
+
const parsed = JSON.parse(raw);
|
|
115
|
+
if (typeof parsed?.token !== 'string' || typeof parsed?.expiresAt !== 'number')
|
|
116
|
+
return null;
|
|
117
|
+
return parsed;
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
function writeStored(value) {
|
|
124
|
+
const store = getStore();
|
|
125
|
+
if (!store)
|
|
126
|
+
return;
|
|
127
|
+
try {
|
|
128
|
+
if (value)
|
|
129
|
+
store.setItem(STORAGE_KEY, JSON.stringify(value));
|
|
130
|
+
else
|
|
131
|
+
store.removeItem(STORAGE_KEY);
|
|
132
|
+
}
|
|
133
|
+
catch {
|
|
134
|
+
}
|
|
135
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export declare function getWriteReviewUrl(rawSettings: Record<string, unknown> | undefined, extensions: unknown, productHandle: string, routesRoot: string | undefined): string;
|
|
2
|
+
export declare function buildWriteReviewProps(settings: Record<string, unknown> | undefined): Record<string, unknown>;
|