@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.
- 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 +198 -0
- package/dist/host-adapter/capabilities.d.ts +4 -0
- package/dist/host-adapter/capabilities.js +15 -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 +38 -0
- package/dist/host-adapter/promoted-collections.d.ts +2 -0
- package/dist/host-adapter/promoted-collections.js +44 -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 +44 -0
- package/dist/lib/recommended-loader.js +113 -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 +267 -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 +338 -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 +39 -0
- package/dist/server/get-joy-initial-data.js +65 -0
- package/dist/server/get-joy-loyalty-page-data.d.ts +28 -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 +89 -0
- package/dist/widget-orchestrator.js +504 -0
- package/package.json +121 -4
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { createJoyServerClient, JoyApiError } from '@joy-loyalty/sdk/server';
|
|
2
|
+
const PUBLIC_CACHE = 'public, max-age=300, s-maxage=300';
|
|
3
|
+
const NO_STORE = 'private, no-store';
|
|
4
|
+
export async function loader({ context, request }) {
|
|
5
|
+
const { env } = context;
|
|
6
|
+
const { JOY_API_URL, JOY_SHOP_DOMAIN } = env ?? {};
|
|
7
|
+
if (!JOY_API_URL || !JOY_SHOP_DOMAIN) {
|
|
8
|
+
return json({ error: 'missing_env' }, 500);
|
|
9
|
+
}
|
|
10
|
+
const programId = new URL(request.url).searchParams.get('programId');
|
|
11
|
+
if (!programId) {
|
|
12
|
+
return json({ error: 'missing_program_id' }, 400);
|
|
13
|
+
}
|
|
14
|
+
const client = createJoyServerClient({ apiUrl: JOY_API_URL, shopDomain: JOY_SHOP_DOMAIN });
|
|
15
|
+
let scope;
|
|
16
|
+
try {
|
|
17
|
+
scope = await client.getPlaceOrderScope(programId);
|
|
18
|
+
}
|
|
19
|
+
catch (error) {
|
|
20
|
+
if (error instanceof JoyApiError && error.code === 'INVALID_PROGRAM') {
|
|
21
|
+
return json({ error: 'invalid_program' }, 404);
|
|
22
|
+
}
|
|
23
|
+
return json({ error: 'upstream_unreachable' }, 502);
|
|
24
|
+
}
|
|
25
|
+
return json(scope, 200);
|
|
26
|
+
}
|
|
27
|
+
function json(payload, status) {
|
|
28
|
+
return new Response(JSON.stringify(payload), {
|
|
29
|
+
status,
|
|
30
|
+
headers: { 'Content-Type': 'application/json', 'Cache-Control': status === 200 ? PUBLIC_CACHE : NO_STORE }
|
|
31
|
+
});
|
|
32
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
export interface JoyAjaxVariant {
|
|
2
|
+
id: string;
|
|
3
|
+
price: number | null;
|
|
4
|
+
compare_at_price: number | null;
|
|
5
|
+
sellingPlanAllocations: {
|
|
6
|
+
perDeliveryPrice: number;
|
|
7
|
+
}[];
|
|
8
|
+
}
|
|
9
|
+
export interface JoyAjaxProduct {
|
|
10
|
+
id: string;
|
|
11
|
+
handle: string;
|
|
12
|
+
title: string;
|
|
13
|
+
url: string;
|
|
14
|
+
price: number | null;
|
|
15
|
+
compare_at_price: number | null;
|
|
16
|
+
featured_image: string;
|
|
17
|
+
images: string[];
|
|
18
|
+
variants: JoyAjaxVariant[];
|
|
19
|
+
}
|
|
20
|
+
export interface JoyCollection {
|
|
21
|
+
id: string;
|
|
22
|
+
title: string;
|
|
23
|
+
handle: string;
|
|
24
|
+
image?: string;
|
|
25
|
+
url: string;
|
|
26
|
+
}
|
|
27
|
+
export interface JoyCollectionsResponse {
|
|
28
|
+
collections: JoyCollection[];
|
|
29
|
+
}
|
|
30
|
+
export interface JoyProductsResponse {
|
|
31
|
+
products: (JoyAjaxProduct | null)[];
|
|
32
|
+
currencyCode: string | null;
|
|
33
|
+
handles?: string[];
|
|
34
|
+
}
|
|
35
|
+
export interface JoyProductsStorefront {
|
|
36
|
+
query(query: string, options: {
|
|
37
|
+
variables?: Record<string, unknown>;
|
|
38
|
+
displayName?: string;
|
|
39
|
+
}): Promise<unknown>;
|
|
40
|
+
}
|
|
41
|
+
export interface JoyProductsContext {
|
|
42
|
+
storefront: JoyProductsStorefront;
|
|
43
|
+
}
|
|
44
|
+
export interface JoyProductsLoaderArgs {
|
|
45
|
+
context: JoyProductsContext;
|
|
46
|
+
request: Request;
|
|
47
|
+
}
|
|
48
|
+
export declare function loader({ context, request }: JoyProductsLoaderArgs): Promise<Response>;
|
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
const HANDLE_PATTERN = /^[a-z0-9][a-z0-9-]{0,127}$/;
|
|
2
|
+
const MAX_HANDLES = 20;
|
|
3
|
+
const MAX_COLLECTIONS = 20;
|
|
4
|
+
const FALLBACK_LIMIT = 10;
|
|
5
|
+
const PRIVATE_CACHE = 'private, max-age=60';
|
|
6
|
+
const NO_STORE = 'private, no-store';
|
|
7
|
+
const PRODUCT_CARD_FRAGMENT = `#graphql
|
|
8
|
+
fragment JoyProductCard on Product {
|
|
9
|
+
id
|
|
10
|
+
handle
|
|
11
|
+
title
|
|
12
|
+
featuredImage {
|
|
13
|
+
url
|
|
14
|
+
}
|
|
15
|
+
images(first: 3) {
|
|
16
|
+
nodes {
|
|
17
|
+
url
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
priceRange {
|
|
21
|
+
minVariantPrice {
|
|
22
|
+
amount
|
|
23
|
+
currencyCode
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
compareAtPriceRange {
|
|
27
|
+
maxVariantPrice {
|
|
28
|
+
amount
|
|
29
|
+
currencyCode
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
variants(first: 5) {
|
|
33
|
+
nodes {
|
|
34
|
+
id
|
|
35
|
+
price {
|
|
36
|
+
amount
|
|
37
|
+
currencyCode
|
|
38
|
+
}
|
|
39
|
+
compareAtPrice {
|
|
40
|
+
amount
|
|
41
|
+
currencyCode
|
|
42
|
+
}
|
|
43
|
+
sellingPlanAllocations(first: 5) {
|
|
44
|
+
nodes {
|
|
45
|
+
priceAdjustments {
|
|
46
|
+
perDeliveryPrice {
|
|
47
|
+
amount
|
|
48
|
+
currencyCode
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
`;
|
|
57
|
+
const COLLECTION_CARD_FRAGMENT = `#graphql
|
|
58
|
+
fragment JoyCollectionCard on Collection {
|
|
59
|
+
id
|
|
60
|
+
handle
|
|
61
|
+
title
|
|
62
|
+
image {
|
|
63
|
+
url(transform: {maxWidth: 400})
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
`;
|
|
67
|
+
const RECOMMENDATIONS_QUERY = `#graphql
|
|
68
|
+
query JoyProductRecommendations(
|
|
69
|
+
$handle: String!
|
|
70
|
+
$useRecommended: Boolean!
|
|
71
|
+
$collectionHandle: String!
|
|
72
|
+
$useCollection: Boolean!
|
|
73
|
+
$collectionSort: ProductCollectionSortKeys
|
|
74
|
+
$collectionReverse: Boolean
|
|
75
|
+
$country: CountryCode
|
|
76
|
+
$language: LanguageCode
|
|
77
|
+
) @inContext(country: $country, language: $language) {
|
|
78
|
+
recommended: productRecommendations(productHandle: $handle, intent: RELATED)
|
|
79
|
+
@include(if: $useRecommended) {
|
|
80
|
+
...JoyProductCard
|
|
81
|
+
}
|
|
82
|
+
fallbackCollection: collection(handle: $collectionHandle) @include(if: $useCollection) {
|
|
83
|
+
products(first: ${FALLBACK_LIMIT}, sortKey: $collectionSort, reverse: $collectionReverse) {
|
|
84
|
+
nodes {
|
|
85
|
+
...JoyProductCard
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
fallbackProducts: products(first: ${FALLBACK_LIMIT}, sortKey: BEST_SELLING) @skip(if: $useCollection) {
|
|
90
|
+
nodes {
|
|
91
|
+
...JoyProductCard
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
${PRODUCT_CARD_FRAGMENT}
|
|
96
|
+
`;
|
|
97
|
+
const AJAX_SORT_BY = {
|
|
98
|
+
manual: { sortKey: 'MANUAL', reverse: false },
|
|
99
|
+
'best-selling': { sortKey: 'BEST_SELLING', reverse: false },
|
|
100
|
+
'title-ascending': { sortKey: 'TITLE', reverse: false },
|
|
101
|
+
'title-descending': { sortKey: 'TITLE', reverse: true },
|
|
102
|
+
'price-ascending': { sortKey: 'PRICE', reverse: false },
|
|
103
|
+
'price-descending': { sortKey: 'PRICE', reverse: true },
|
|
104
|
+
'created-ascending': { sortKey: 'CREATED', reverse: false },
|
|
105
|
+
'created-descending': { sortKey: 'CREATED', reverse: true }
|
|
106
|
+
};
|
|
107
|
+
const COLLECTION_SORT_KEYS = new Set([
|
|
108
|
+
'BEST_SELLING',
|
|
109
|
+
'COLLECTION_DEFAULT',
|
|
110
|
+
'CREATED',
|
|
111
|
+
'ID',
|
|
112
|
+
'MANUAL',
|
|
113
|
+
'PRICE',
|
|
114
|
+
'TITLE'
|
|
115
|
+
]);
|
|
116
|
+
const DEFAULT_SORT = { sortKey: 'BEST_SELLING', reverse: false };
|
|
117
|
+
export async function loader({ context, request }) {
|
|
118
|
+
const params = new URL(request.url).searchParams;
|
|
119
|
+
const market = marketVariables(params);
|
|
120
|
+
if (params.has('recommend')) {
|
|
121
|
+
return loadRecommendations(context.storefront, params, market);
|
|
122
|
+
}
|
|
123
|
+
const collectionsParam = params.get('collections');
|
|
124
|
+
if (collectionsParam !== null) {
|
|
125
|
+
return loadCollections(context.storefront, collectionsParam, market);
|
|
126
|
+
}
|
|
127
|
+
const handlesParam = params.get('handles');
|
|
128
|
+
if (handlesParam !== null) {
|
|
129
|
+
return loadByHandles(context.storefront, handlesParam, market);
|
|
130
|
+
}
|
|
131
|
+
return json({ products: [], currencyCode: null }, 400);
|
|
132
|
+
}
|
|
133
|
+
function marketVariables(params) {
|
|
134
|
+
const country = params.get('country');
|
|
135
|
+
return country && /^[A-Z]{2}$/.test(country) ? { country } : {};
|
|
136
|
+
}
|
|
137
|
+
async function loadByHandles(storefront, raw, market) {
|
|
138
|
+
const handles = parseHandles(raw);
|
|
139
|
+
if (!handles.length)
|
|
140
|
+
return json({ products: [], currencyCode: null, handles }, 200);
|
|
141
|
+
const variables = { ...market };
|
|
142
|
+
handles.forEach((handle, index) => {
|
|
143
|
+
variables[`h${index}`] = handle;
|
|
144
|
+
});
|
|
145
|
+
let nodes;
|
|
146
|
+
try {
|
|
147
|
+
const data = (await storefront.query(buildBatchQuery(handles.length), {
|
|
148
|
+
variables,
|
|
149
|
+
displayName: 'JoyProductsByHandle'
|
|
150
|
+
}));
|
|
151
|
+
nodes = handles.map((_, index) => data?.[`p${index}`] ?? null);
|
|
152
|
+
}
|
|
153
|
+
catch {
|
|
154
|
+
return json({ products: handles.map(() => null), currencyCode: null, handles }, 200);
|
|
155
|
+
}
|
|
156
|
+
return json({ products: nodes.map(toAjaxProduct), currencyCode: pickCurrencyCode(nodes), handles }, 200);
|
|
157
|
+
}
|
|
158
|
+
async function loadRecommendations(storefront, params, market) {
|
|
159
|
+
const seed = sanitizeHandle(params.get('recommend'));
|
|
160
|
+
const collectionHandle = sanitizeHandle(params.get('fallbackCollection'));
|
|
161
|
+
const { sortKey, reverse } = resolveSort(params.get('fallbackSort'));
|
|
162
|
+
let nodes;
|
|
163
|
+
try {
|
|
164
|
+
const data = (await storefront.query(RECOMMENDATIONS_QUERY, {
|
|
165
|
+
variables: {
|
|
166
|
+
...market,
|
|
167
|
+
handle: seed,
|
|
168
|
+
useRecommended: !!seed,
|
|
169
|
+
collectionHandle,
|
|
170
|
+
useCollection: !!collectionHandle,
|
|
171
|
+
collectionSort: sortKey,
|
|
172
|
+
collectionReverse: reverse
|
|
173
|
+
},
|
|
174
|
+
displayName: 'JoyProductRecommendations'
|
|
175
|
+
}));
|
|
176
|
+
const recommended = data?.recommended ?? [];
|
|
177
|
+
nodes = recommended.length
|
|
178
|
+
? recommended
|
|
179
|
+
: data?.fallbackCollection?.products?.nodes ?? data?.fallbackProducts?.nodes ?? [];
|
|
180
|
+
}
|
|
181
|
+
catch {
|
|
182
|
+
return json({ products: [], currencyCode: null }, 200);
|
|
183
|
+
}
|
|
184
|
+
const products = nodes
|
|
185
|
+
.map(toAjaxProduct)
|
|
186
|
+
.filter((product) => !!product && product.handle !== seed);
|
|
187
|
+
return json({ products, currencyCode: pickCurrencyCode(nodes) }, 200);
|
|
188
|
+
}
|
|
189
|
+
async function loadCollections(storefront, raw, market) {
|
|
190
|
+
const handles = parseHandles(raw, MAX_COLLECTIONS);
|
|
191
|
+
if (!handles.length)
|
|
192
|
+
return json({ collections: [] }, 200);
|
|
193
|
+
const variables = { ...market };
|
|
194
|
+
handles.forEach((handle, index) => {
|
|
195
|
+
variables[`h${index}`] = handle;
|
|
196
|
+
});
|
|
197
|
+
try {
|
|
198
|
+
const data = (await storefront.query(buildCollectionsQuery(handles.length), {
|
|
199
|
+
variables,
|
|
200
|
+
displayName: 'JoyPromotedCollections'
|
|
201
|
+
}));
|
|
202
|
+
const collections = handles
|
|
203
|
+
.map((_, index) => toPromotedCollection(data?.[`c${index}`] ?? null))
|
|
204
|
+
.filter((collection) => collection !== null);
|
|
205
|
+
return json({ collections }, 200);
|
|
206
|
+
}
|
|
207
|
+
catch {
|
|
208
|
+
return json({ collections: [] }, 200);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
function parseHandles(raw, max = MAX_HANDLES) {
|
|
212
|
+
const handles = [];
|
|
213
|
+
for (const part of raw.split(',')) {
|
|
214
|
+
const handle = part.trim();
|
|
215
|
+
if (!HANDLE_PATTERN.test(handle) || handles.includes(handle))
|
|
216
|
+
continue;
|
|
217
|
+
handles.push(handle);
|
|
218
|
+
if (handles.length === max)
|
|
219
|
+
break;
|
|
220
|
+
}
|
|
221
|
+
return handles;
|
|
222
|
+
}
|
|
223
|
+
function sanitizeHandle(raw) {
|
|
224
|
+
const handle = (raw ?? '').trim();
|
|
225
|
+
return HANDLE_PATTERN.test(handle) ? handle : '';
|
|
226
|
+
}
|
|
227
|
+
function resolveSort(raw) {
|
|
228
|
+
const value = (raw ?? '').trim();
|
|
229
|
+
if (!value)
|
|
230
|
+
return DEFAULT_SORT;
|
|
231
|
+
const mapped = AJAX_SORT_BY[value.toLowerCase()];
|
|
232
|
+
if (mapped)
|
|
233
|
+
return mapped;
|
|
234
|
+
const upper = value.toUpperCase();
|
|
235
|
+
return COLLECTION_SORT_KEYS.has(upper) ? { sortKey: upper, reverse: false } : DEFAULT_SORT;
|
|
236
|
+
}
|
|
237
|
+
function buildBatchQuery(count) {
|
|
238
|
+
const declarations = Array.from({ length: count }, (_, i) => `$h${i}: String!`).join(', ');
|
|
239
|
+
const selections = Array.from({ length: count }, (_, i) => ` p${i}: product(handle: $h${i}) {\n ...JoyProductCard\n }`).join('\n');
|
|
240
|
+
return `#graphql
|
|
241
|
+
query JoyProductsByHandle(${declarations}, $country: CountryCode, $language: LanguageCode)
|
|
242
|
+
@inContext(country: $country, language: $language) {
|
|
243
|
+
${selections}
|
|
244
|
+
}
|
|
245
|
+
${PRODUCT_CARD_FRAGMENT}
|
|
246
|
+
`;
|
|
247
|
+
}
|
|
248
|
+
function buildCollectionsQuery(count) {
|
|
249
|
+
const declarations = Array.from({ length: count }, (_, i) => `$h${i}: String!`).join(', ');
|
|
250
|
+
const selections = Array.from({ length: count }, (_, i) => ` c${i}: collection(handle: $h${i}) {\n ...JoyCollectionCard\n }`).join('\n');
|
|
251
|
+
return `#graphql
|
|
252
|
+
query JoyPromotedCollections(${declarations}, $country: CountryCode, $language: LanguageCode)
|
|
253
|
+
@inContext(country: $country, language: $language) {
|
|
254
|
+
${selections}
|
|
255
|
+
}
|
|
256
|
+
${COLLECTION_CARD_FRAGMENT}
|
|
257
|
+
`;
|
|
258
|
+
}
|
|
259
|
+
function toPromotedCollection(node) {
|
|
260
|
+
if (!node?.handle)
|
|
261
|
+
return null;
|
|
262
|
+
const image = node.image?.url || undefined;
|
|
263
|
+
return {
|
|
264
|
+
id: numericId(node.id),
|
|
265
|
+
title: node.title ?? '',
|
|
266
|
+
handle: node.handle,
|
|
267
|
+
...(image ? { image } : {}),
|
|
268
|
+
url: `/collections/${node.handle}`
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
function toAjaxProduct(node) {
|
|
272
|
+
if (!node?.handle)
|
|
273
|
+
return null;
|
|
274
|
+
const images = (node.images?.nodes ?? [])
|
|
275
|
+
.map(image => image?.url)
|
|
276
|
+
.filter((url) => !!url);
|
|
277
|
+
const featuredImage = node.featuredImage?.url || images[0] || '';
|
|
278
|
+
return {
|
|
279
|
+
id: numericId(node.id),
|
|
280
|
+
handle: node.handle,
|
|
281
|
+
title: node.title ?? '',
|
|
282
|
+
url: `/products/${node.handle}`,
|
|
283
|
+
price: toPriceCents(node.priceRange?.minVariantPrice),
|
|
284
|
+
compare_at_price: toCents(node.compareAtPriceRange?.maxVariantPrice),
|
|
285
|
+
featured_image: featuredImage,
|
|
286
|
+
images,
|
|
287
|
+
variants: (node.variants?.nodes ?? [])
|
|
288
|
+
.filter((variant) => !!variant)
|
|
289
|
+
.map(toAjaxVariant)
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
function toAjaxVariant(variant) {
|
|
293
|
+
const allocations = (variant.sellingPlanAllocations?.nodes ?? []).flatMap(allocation => (allocation?.priceAdjustments ?? [])
|
|
294
|
+
.map(adjustment => toCents(adjustment?.perDeliveryPrice))
|
|
295
|
+
.filter((cents) => cents !== null)
|
|
296
|
+
.map(perDeliveryPrice => ({ perDeliveryPrice })));
|
|
297
|
+
return {
|
|
298
|
+
id: numericId(variant.id),
|
|
299
|
+
price: toPriceCents(variant.price),
|
|
300
|
+
compare_at_price: toCents(variant.compareAtPrice),
|
|
301
|
+
sellingPlanAllocations: allocations
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
function toPriceCents(money) {
|
|
305
|
+
const amount = Number(money?.amount);
|
|
306
|
+
if (money?.amount == null || !Number.isFinite(amount) || amount < 0)
|
|
307
|
+
return null;
|
|
308
|
+
return Math.round(amount * 100);
|
|
309
|
+
}
|
|
310
|
+
function toCents(money) {
|
|
311
|
+
const amount = Number(money?.amount);
|
|
312
|
+
if (!Number.isFinite(amount) || amount <= 0)
|
|
313
|
+
return null;
|
|
314
|
+
return Math.round(amount * 100);
|
|
315
|
+
}
|
|
316
|
+
function numericId(gid) {
|
|
317
|
+
if (!gid)
|
|
318
|
+
return '';
|
|
319
|
+
const match = gid.match(/\/(\d+)(?:[?#]|$)/);
|
|
320
|
+
return match ? match[1] : gid;
|
|
321
|
+
}
|
|
322
|
+
function pickCurrencyCode(nodes) {
|
|
323
|
+
for (const node of nodes) {
|
|
324
|
+
const code = node?.priceRange?.minVariantPrice?.currencyCode;
|
|
325
|
+
if (code)
|
|
326
|
+
return code;
|
|
327
|
+
}
|
|
328
|
+
return null;
|
|
329
|
+
}
|
|
330
|
+
function json(payload, status) {
|
|
331
|
+
return new Response(JSON.stringify(payload), {
|
|
332
|
+
status,
|
|
333
|
+
headers: {
|
|
334
|
+
'Content-Type': 'application/json',
|
|
335
|
+
'Cache-Control': status === 200 ? PRIVATE_CACHE : NO_STORE
|
|
336
|
+
}
|
|
337
|
+
});
|
|
338
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { JoyCustomerAccount } from '../lib/server-token.js';
|
|
2
|
+
export type { JoyCustomerAccount };
|
|
3
|
+
export interface JoyTokenEnv {
|
|
4
|
+
JOY_API_URL?: string;
|
|
5
|
+
JOY_SHOP_DOMAIN?: string;
|
|
6
|
+
JOY_API_SECRET?: string;
|
|
7
|
+
}
|
|
8
|
+
export interface JoyTokenContext {
|
|
9
|
+
customerAccount: JoyCustomerAccount;
|
|
10
|
+
env: JoyTokenEnv;
|
|
11
|
+
}
|
|
12
|
+
export interface JoyTokenLoaderArgs {
|
|
13
|
+
context: JoyTokenContext;
|
|
14
|
+
request?: Request;
|
|
15
|
+
}
|
|
16
|
+
export declare function loader({ context }: JoyTokenLoaderArgs): Promise<Response>;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { mintJoyToken } from '../lib/server-token.js';
|
|
2
|
+
const NO_STORE = 'private, no-store';
|
|
3
|
+
export async function loader({ context }) {
|
|
4
|
+
const { customerAccount, env } = context;
|
|
5
|
+
const { JOY_API_URL, JOY_SHOP_DOMAIN, JOY_API_SECRET } = env ?? {};
|
|
6
|
+
if (!JOY_API_URL || !JOY_SHOP_DOMAIN || !JOY_API_SECRET) {
|
|
7
|
+
return json({ error: 'missing_env' }, 500);
|
|
8
|
+
}
|
|
9
|
+
const result = await mintJoyToken({
|
|
10
|
+
customerAccount,
|
|
11
|
+
apiUrl: JOY_API_URL,
|
|
12
|
+
shopDomain: JOY_SHOP_DOMAIN,
|
|
13
|
+
secret: JOY_API_SECRET
|
|
14
|
+
});
|
|
15
|
+
if (!result.ok) {
|
|
16
|
+
return json({ error: result.reason }, result.status);
|
|
17
|
+
}
|
|
18
|
+
const firstName = result.identity.firstName;
|
|
19
|
+
return json({
|
|
20
|
+
token: result.token,
|
|
21
|
+
tokenType: result.tokenType,
|
|
22
|
+
expiresIn: result.expiresIn,
|
|
23
|
+
customerId: result.identity.id,
|
|
24
|
+
...(firstName ? { firstName } : {})
|
|
25
|
+
}, 200);
|
|
26
|
+
}
|
|
27
|
+
function json(payload, status) {
|
|
28
|
+
return new Response(JSON.stringify(payload), {
|
|
29
|
+
status,
|
|
30
|
+
headers: { 'Content-Type': 'application/json', 'Cache-Control': NO_STORE }
|
|
31
|
+
});
|
|
32
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { Customer } from '@joy-loyalty/sdk/client';
|
|
2
|
+
import type { JoyMetafieldBlob, JoyStorefrontClient } from '../lib/metafield-blob.js';
|
|
3
|
+
import type { JoyCustomerAccount, MintedCustomerIdentity } from '../lib/server-token.js';
|
|
4
|
+
import type { WidgetCoreManifest } from '../lib/core-loader.js';
|
|
5
|
+
export type { JoyMetafieldBlob, JoyStorefrontClient };
|
|
6
|
+
export interface GetJoyInitialDataOptions {
|
|
7
|
+
storefront: JoyStorefrontClient;
|
|
8
|
+
customerAccount: JoyCustomerAccount;
|
|
9
|
+
apiUrl: string;
|
|
10
|
+
shopDomain: string;
|
|
11
|
+
secret: string;
|
|
12
|
+
locale?: string;
|
|
13
|
+
loginUrl?: string;
|
|
14
|
+
registerUrl?: string;
|
|
15
|
+
accountUrl?: string;
|
|
16
|
+
request?: Request;
|
|
17
|
+
exposeToken?: boolean;
|
|
18
|
+
assetUrl?: string;
|
|
19
|
+
deferCustomerBalance?: boolean;
|
|
20
|
+
}
|
|
21
|
+
export interface JoyInitialDataPage {
|
|
22
|
+
type: string;
|
|
23
|
+
resourceId: string;
|
|
24
|
+
handle: string;
|
|
25
|
+
}
|
|
26
|
+
export interface JoyInitialDataResult {
|
|
27
|
+
blob?: JoyMetafieldBlob;
|
|
28
|
+
customer?: Customer;
|
|
29
|
+
shopifyCustomer?: MintedCustomerIdentity;
|
|
30
|
+
token?: string;
|
|
31
|
+
locale?: string;
|
|
32
|
+
country?: string;
|
|
33
|
+
core?: WidgetCoreManifest;
|
|
34
|
+
login_url: string;
|
|
35
|
+
register_url: string;
|
|
36
|
+
account_url: string;
|
|
37
|
+
page: JoyInitialDataPage;
|
|
38
|
+
}
|
|
39
|
+
export declare function getJoyInitialData(options: GetJoyInitialDataOptions): Promise<JoyInitialDataResult>;
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { createJoyClient } from '@joy-loyalty/sdk/client';
|
|
2
|
+
import { getJoyMetafieldBlob } from '../lib/metafield-blob.js';
|
|
3
|
+
import { mintJoyToken } from '../lib/server-token.js';
|
|
4
|
+
import { resolveShopLocale } from '../lib/shop-locale.js';
|
|
5
|
+
import { toShopifyLocale } from './get-joy-loyalty-page-data.js';
|
|
6
|
+
import { getWidgetCoreManifest } from '../lib/core-manifest.js';
|
|
7
|
+
const DEFAULT_LOGIN_URL = '/account/login';
|
|
8
|
+
const DEFAULT_REGISTER_URL = '/account/register';
|
|
9
|
+
const DEFAULT_ACCOUNT_URL = '/account';
|
|
10
|
+
export async function getJoyInitialData(options) {
|
|
11
|
+
const { storefront, customerAccount, apiUrl, shopDomain, secret, loginUrl = DEFAULT_LOGIN_URL, registerUrl = DEFAULT_REGISTER_URL, accountUrl = DEFAULT_ACCOUNT_URL, request, exposeToken = false, assetUrl, deferCustomerBalance = false } = options;
|
|
12
|
+
const i18n = storefront.i18n;
|
|
13
|
+
const locale = options.locale ?? (i18n?.language ? toShopifyLocale(i18n.language) : undefined);
|
|
14
|
+
const [blob, customerHalf, core] = await Promise.all([
|
|
15
|
+
getJoyMetafieldBlob(storefront),
|
|
16
|
+
fetchCustomerHalf({ customerAccount, apiUrl, shopDomain, secret, locale, deferCustomerBalance }),
|
|
17
|
+
getWidgetCoreManifest(assetUrl ? { assetUrl } : {})
|
|
18
|
+
]);
|
|
19
|
+
return {
|
|
20
|
+
...(blob !== undefined ? { blob } : {}),
|
|
21
|
+
...(core !== undefined ? { core } : {}),
|
|
22
|
+
...(customerHalf.customer !== undefined ? { customer: customerHalf.customer } : {}),
|
|
23
|
+
...(customerHalf.shopifyCustomer !== undefined ? { shopifyCustomer: customerHalf.shopifyCustomer } : {}),
|
|
24
|
+
...(exposeToken && customerHalf.token !== undefined ? { token: customerHalf.token } : {}),
|
|
25
|
+
...(locale !== undefined ? { locale: resolveShopLocale(locale, blob?.translation) } : {}),
|
|
26
|
+
...(i18n?.country ? { country: i18n.country } : {}),
|
|
27
|
+
login_url: loginUrl,
|
|
28
|
+
register_url: registerUrl,
|
|
29
|
+
account_url: accountUrl,
|
|
30
|
+
page: resolvePage(request)
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
async function fetchCustomerHalf(params) {
|
|
34
|
+
const { customerAccount, apiUrl, shopDomain, secret, locale, deferCustomerBalance } = params;
|
|
35
|
+
const mint = await mintJoyToken({ customerAccount, apiUrl, shopDomain, secret });
|
|
36
|
+
if (!mint.ok)
|
|
37
|
+
return {};
|
|
38
|
+
const half = { shopifyCustomer: mint.identity, token: mint.token };
|
|
39
|
+
if (deferCustomerBalance)
|
|
40
|
+
return half;
|
|
41
|
+
try {
|
|
42
|
+
const client = createJoyClient({ apiUrl, token: mint.token, locale });
|
|
43
|
+
half.customer = await client.getCustomer();
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
}
|
|
47
|
+
return half;
|
|
48
|
+
}
|
|
49
|
+
function resolvePage(request) {
|
|
50
|
+
const pathname = safePathname(request);
|
|
51
|
+
if (!pathname || pathname === '/')
|
|
52
|
+
return { type: 'index', resourceId: '', handle: '' };
|
|
53
|
+
const handle = pathname.split('/').filter(Boolean).pop() ?? '';
|
|
54
|
+
return { type: 'page', resourceId: '', handle };
|
|
55
|
+
}
|
|
56
|
+
function safePathname(request) {
|
|
57
|
+
if (!request)
|
|
58
|
+
return undefined;
|
|
59
|
+
try {
|
|
60
|
+
return new URL(request.url).pathname;
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return undefined;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { JoyMetafieldBlob, JoyStorefrontClient } from '../lib/metafield-blob.js';
|
|
2
|
+
import type { WidgetCoreManifest } from '../lib/core-loader.js';
|
|
3
|
+
export type { JoyStorefrontClient };
|
|
4
|
+
export interface JoyLoyaltyPageFaq {
|
|
5
|
+
title: string;
|
|
6
|
+
content: string;
|
|
7
|
+
orderBy?: number;
|
|
8
|
+
}
|
|
9
|
+
export interface JoyLoyaltyPageData {
|
|
10
|
+
structure?: unknown;
|
|
11
|
+
faqs?: JoyLoyaltyPageFaq[];
|
|
12
|
+
translations: Record<string, unknown>;
|
|
13
|
+
shop: Record<string, unknown>;
|
|
14
|
+
home?: Omit<JoyMetafieldBlob, 'translation' | 'shop'>;
|
|
15
|
+
country?: string;
|
|
16
|
+
locale?: string;
|
|
17
|
+
core?: WidgetCoreManifest;
|
|
18
|
+
}
|
|
19
|
+
export interface GetJoyLoyaltyPageDataOptions {
|
|
20
|
+
storefront: JoyStorefrontClient;
|
|
21
|
+
apiUrl: string;
|
|
22
|
+
shopDomain: string;
|
|
23
|
+
fetch?: typeof fetch;
|
|
24
|
+
assetUrl?: string;
|
|
25
|
+
}
|
|
26
|
+
export declare function getJoyLoyaltyPageData(options: GetJoyLoyaltyPageDataOptions): Promise<JoyLoyaltyPageData>;
|
|
27
|
+
export declare function projectTranslations(translations: Record<string, unknown>, locale: string): Record<string, unknown>;
|
|
28
|
+
export declare function toShopifyLocale(language: string): string;
|