@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.
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 +197 -0
  9. package/dist/host-adapter/capabilities.d.ts +3 -0
  10. package/dist/host-adapter/capabilities.js +12 -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 +37 -0
  15. package/dist/host-adapter/promoted-collections.d.ts +2 -0
  16. package/dist/host-adapter/promoted-collections.js +43 -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 +43 -0
  66. package/dist/lib/recommended-loader.js +111 -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 +258 -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 +326 -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 +38 -0
  118. package/dist/server/get-joy-initial-data.js +61 -0
  119. package/dist/server/get-joy-loyalty-page-data.d.ts +27 -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 +88 -0
  126. package/dist/widget-orchestrator.js +499 -0
  127. 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,326 @@
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
+ if (params.has('recommend')) {
120
+ return loadRecommendations(context.storefront, params);
121
+ }
122
+ const collectionsParam = params.get('collections');
123
+ if (collectionsParam !== null) {
124
+ return loadCollections(context.storefront, collectionsParam);
125
+ }
126
+ const handlesParam = params.get('handles');
127
+ if (handlesParam !== null) {
128
+ return loadByHandles(context.storefront, handlesParam);
129
+ }
130
+ return json({ products: [], currencyCode: null }, 400);
131
+ }
132
+ async function loadByHandles(storefront, raw) {
133
+ const handles = parseHandles(raw);
134
+ if (!handles.length)
135
+ return json({ products: [], currencyCode: null, handles }, 200);
136
+ const variables = {};
137
+ handles.forEach((handle, index) => {
138
+ variables[`h${index}`] = handle;
139
+ });
140
+ let nodes;
141
+ try {
142
+ const data = (await storefront.query(buildBatchQuery(handles.length), {
143
+ variables,
144
+ displayName: 'JoyProductsByHandle'
145
+ }));
146
+ nodes = handles.map((_, index) => data?.[`p${index}`] ?? null);
147
+ }
148
+ catch {
149
+ return json({ products: handles.map(() => null), currencyCode: null, handles }, 200);
150
+ }
151
+ return json({ products: nodes.map(toAjaxProduct), currencyCode: pickCurrencyCode(nodes), handles }, 200);
152
+ }
153
+ async function loadRecommendations(storefront, params) {
154
+ const seed = sanitizeHandle(params.get('recommend'));
155
+ const collectionHandle = sanitizeHandle(params.get('fallbackCollection'));
156
+ const { sortKey, reverse } = resolveSort(params.get('fallbackSort'));
157
+ let nodes;
158
+ try {
159
+ const data = (await storefront.query(RECOMMENDATIONS_QUERY, {
160
+ variables: {
161
+ handle: seed,
162
+ useRecommended: !!seed,
163
+ collectionHandle,
164
+ useCollection: !!collectionHandle,
165
+ collectionSort: sortKey,
166
+ collectionReverse: reverse
167
+ },
168
+ displayName: 'JoyProductRecommendations'
169
+ }));
170
+ const recommended = data?.recommended ?? [];
171
+ nodes = recommended.length
172
+ ? recommended
173
+ : data?.fallbackCollection?.products?.nodes ?? data?.fallbackProducts?.nodes ?? [];
174
+ }
175
+ catch {
176
+ return json({ products: [], currencyCode: null }, 200);
177
+ }
178
+ const products = nodes
179
+ .map(toAjaxProduct)
180
+ .filter((product) => !!product && product.handle !== seed);
181
+ return json({ products, currencyCode: pickCurrencyCode(nodes) }, 200);
182
+ }
183
+ async function loadCollections(storefront, raw) {
184
+ const handles = parseHandles(raw, MAX_COLLECTIONS);
185
+ if (!handles.length)
186
+ return json({ collections: [] }, 200);
187
+ const variables = {};
188
+ handles.forEach((handle, index) => {
189
+ variables[`h${index}`] = handle;
190
+ });
191
+ try {
192
+ const data = (await storefront.query(buildCollectionsQuery(handles.length), {
193
+ variables,
194
+ displayName: 'JoyPromotedCollections'
195
+ }));
196
+ const collections = handles
197
+ .map((_, index) => toPromotedCollection(data?.[`c${index}`] ?? null))
198
+ .filter((collection) => collection !== null);
199
+ return json({ collections }, 200);
200
+ }
201
+ catch {
202
+ return json({ collections: [] }, 200);
203
+ }
204
+ }
205
+ function parseHandles(raw, max = MAX_HANDLES) {
206
+ const handles = [];
207
+ for (const part of raw.split(',')) {
208
+ const handle = part.trim();
209
+ if (!HANDLE_PATTERN.test(handle) || handles.includes(handle))
210
+ continue;
211
+ handles.push(handle);
212
+ if (handles.length === max)
213
+ break;
214
+ }
215
+ return handles;
216
+ }
217
+ function sanitizeHandle(raw) {
218
+ const handle = (raw ?? '').trim();
219
+ return HANDLE_PATTERN.test(handle) ? handle : '';
220
+ }
221
+ function resolveSort(raw) {
222
+ const value = (raw ?? '').trim();
223
+ if (!value)
224
+ return DEFAULT_SORT;
225
+ const mapped = AJAX_SORT_BY[value.toLowerCase()];
226
+ if (mapped)
227
+ return mapped;
228
+ const upper = value.toUpperCase();
229
+ return COLLECTION_SORT_KEYS.has(upper) ? { sortKey: upper, reverse: false } : DEFAULT_SORT;
230
+ }
231
+ function buildBatchQuery(count) {
232
+ const declarations = Array.from({ length: count }, (_, i) => `$h${i}: String!`).join(', ');
233
+ const selections = Array.from({ length: count }, (_, i) => ` p${i}: product(handle: $h${i}) {\n ...JoyProductCard\n }`).join('\n');
234
+ return `#graphql
235
+ query JoyProductsByHandle(${declarations}, $country: CountryCode, $language: LanguageCode)
236
+ @inContext(country: $country, language: $language) {
237
+ ${selections}
238
+ }
239
+ ${PRODUCT_CARD_FRAGMENT}
240
+ `;
241
+ }
242
+ function buildCollectionsQuery(count) {
243
+ const declarations = Array.from({ length: count }, (_, i) => `$h${i}: String!`).join(', ');
244
+ const selections = Array.from({ length: count }, (_, i) => ` c${i}: collection(handle: $h${i}) {\n ...JoyCollectionCard\n }`).join('\n');
245
+ return `#graphql
246
+ query JoyPromotedCollections(${declarations}, $country: CountryCode, $language: LanguageCode)
247
+ @inContext(country: $country, language: $language) {
248
+ ${selections}
249
+ }
250
+ ${COLLECTION_CARD_FRAGMENT}
251
+ `;
252
+ }
253
+ function toPromotedCollection(node) {
254
+ if (!node?.handle)
255
+ return null;
256
+ const image = node.image?.url || undefined;
257
+ return {
258
+ id: numericId(node.id),
259
+ title: node.title ?? '',
260
+ handle: node.handle,
261
+ ...(image ? { image } : {}),
262
+ url: `/collections/${node.handle}`
263
+ };
264
+ }
265
+ function toAjaxProduct(node) {
266
+ if (!node?.handle)
267
+ return null;
268
+ const images = (node.images?.nodes ?? [])
269
+ .map(image => image?.url)
270
+ .filter((url) => !!url);
271
+ const featuredImage = node.featuredImage?.url || images[0] || '';
272
+ return {
273
+ id: numericId(node.id),
274
+ handle: node.handle,
275
+ title: node.title ?? '',
276
+ url: `/products/${node.handle}`,
277
+ price: toCents(node.priceRange?.minVariantPrice),
278
+ compare_at_price: toCents(node.compareAtPriceRange?.maxVariantPrice),
279
+ featured_image: featuredImage,
280
+ images,
281
+ variants: (node.variants?.nodes ?? [])
282
+ .filter((variant) => !!variant)
283
+ .map(toAjaxVariant)
284
+ };
285
+ }
286
+ function toAjaxVariant(variant) {
287
+ const allocations = (variant.sellingPlanAllocations?.nodes ?? []).flatMap(allocation => (allocation?.priceAdjustments ?? [])
288
+ .map(adjustment => toCents(adjustment?.perDeliveryPrice))
289
+ .filter((cents) => cents !== null)
290
+ .map(perDeliveryPrice => ({ perDeliveryPrice })));
291
+ return {
292
+ id: numericId(variant.id),
293
+ price: toCents(variant.price),
294
+ compare_at_price: toCents(variant.compareAtPrice),
295
+ sellingPlanAllocations: allocations
296
+ };
297
+ }
298
+ function toCents(money) {
299
+ const amount = Number(money?.amount);
300
+ if (!Number.isFinite(amount) || amount <= 0)
301
+ return null;
302
+ return Math.round(amount * 100);
303
+ }
304
+ function numericId(gid) {
305
+ if (!gid)
306
+ return '';
307
+ const match = gid.match(/\/(\d+)(?:[?#]|$)/);
308
+ return match ? match[1] : gid;
309
+ }
310
+ function pickCurrencyCode(nodes) {
311
+ for (const node of nodes) {
312
+ const code = node?.priceRange?.minVariantPrice?.currencyCode;
313
+ if (code)
314
+ return code;
315
+ }
316
+ return null;
317
+ }
318
+ function json(payload, status) {
319
+ return new Response(JSON.stringify(payload), {
320
+ status,
321
+ headers: {
322
+ 'Content-Type': 'application/json',
323
+ 'Cache-Control': status === 200 ? PRIVATE_CACHE : NO_STORE
324
+ }
325
+ });
326
+ }
@@ -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,38 @@
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
+ core?: WidgetCoreManifest;
33
+ login_url: string;
34
+ register_url: string;
35
+ account_url: string;
36
+ page: JoyInitialDataPage;
37
+ }
38
+ export declare function getJoyInitialData(options: GetJoyInitialDataOptions): Promise<JoyInitialDataResult>;
@@ -0,0 +1,61 @@
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 { getWidgetCoreManifest } from '../lib/core-manifest.js';
6
+ const DEFAULT_LOGIN_URL = '/account/login';
7
+ const DEFAULT_REGISTER_URL = '/account/register';
8
+ const DEFAULT_ACCOUNT_URL = '/account';
9
+ export async function getJoyInitialData(options) {
10
+ const { storefront, customerAccount, apiUrl, shopDomain, secret, locale, loginUrl = DEFAULT_LOGIN_URL, registerUrl = DEFAULT_REGISTER_URL, accountUrl = DEFAULT_ACCOUNT_URL, request, exposeToken = false, assetUrl, deferCustomerBalance = false } = options;
11
+ const [blob, customerHalf, core] = await Promise.all([
12
+ getJoyMetafieldBlob(storefront),
13
+ fetchCustomerHalf({ customerAccount, apiUrl, shopDomain, secret, locale, deferCustomerBalance }),
14
+ getWidgetCoreManifest(assetUrl ? { assetUrl } : {})
15
+ ]);
16
+ return {
17
+ ...(blob !== undefined ? { blob } : {}),
18
+ ...(core !== undefined ? { core } : {}),
19
+ ...(customerHalf.customer !== undefined ? { customer: customerHalf.customer } : {}),
20
+ ...(customerHalf.shopifyCustomer !== undefined ? { shopifyCustomer: customerHalf.shopifyCustomer } : {}),
21
+ ...(exposeToken && customerHalf.token !== undefined ? { token: customerHalf.token } : {}),
22
+ ...(locale !== undefined ? { locale: resolveShopLocale(locale, blob?.translation) } : {}),
23
+ login_url: loginUrl,
24
+ register_url: registerUrl,
25
+ account_url: accountUrl,
26
+ page: resolvePage(request)
27
+ };
28
+ }
29
+ async function fetchCustomerHalf(params) {
30
+ const { customerAccount, apiUrl, shopDomain, secret, locale, deferCustomerBalance } = params;
31
+ const mint = await mintJoyToken({ customerAccount, apiUrl, shopDomain, secret });
32
+ if (!mint.ok)
33
+ return {};
34
+ const half = { shopifyCustomer: mint.identity, token: mint.token };
35
+ if (deferCustomerBalance)
36
+ return half;
37
+ try {
38
+ const client = createJoyClient({ apiUrl, token: mint.token, locale });
39
+ half.customer = await client.getCustomer();
40
+ }
41
+ catch {
42
+ }
43
+ return half;
44
+ }
45
+ function resolvePage(request) {
46
+ const pathname = safePathname(request);
47
+ if (!pathname || pathname === '/')
48
+ return { type: 'index', resourceId: '', handle: '' };
49
+ const handle = pathname.split('/').filter(Boolean).pop() ?? '';
50
+ return { type: 'page', resourceId: '', handle };
51
+ }
52
+ function safePathname(request) {
53
+ if (!request)
54
+ return undefined;
55
+ try {
56
+ return new URL(request.url).pathname;
57
+ }
58
+ catch {
59
+ return undefined;
60
+ }
61
+ }
@@ -0,0 +1,27 @@
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>;
@@ -0,0 +1,99 @@
1
+ import { getJoyMetafieldBlob } from '../lib/metafield-blob.js';
2
+ import { resolveShopLocale } from '../lib/shop-locale.js';
3
+ import { getWidgetCoreManifest } from '../lib/core-manifest.js';
4
+ const structureByStorefront = new WeakMap();
5
+ async function fetchStructureAndFaqs(options) {
6
+ const fetchImpl = options.fetch ?? globalThis.fetch;
7
+ const url = `${options.apiUrl.replace(/\/+$/, '')}/loyalty-page/structure?shop=${encodeURIComponent(options.shopDomain)}`;
8
+ try {
9
+ const response = await fetchImpl(url, { headers: { Accept: 'application/json' } });
10
+ if (!response.ok)
11
+ return undefined;
12
+ const envelope = (await response.json());
13
+ if (!envelope || envelope.success !== true)
14
+ return undefined;
15
+ return envelope.data;
16
+ }
17
+ catch {
18
+ return undefined;
19
+ }
20
+ }
21
+ function sharedStructureAndFaqs(options) {
22
+ const cached = structureByStorefront.get(options.storefront);
23
+ if (cached)
24
+ return cached;
25
+ const pending = fetchStructureAndFaqs(options);
26
+ structureByStorefront.set(options.storefront, pending);
27
+ return pending;
28
+ }
29
+ function blobToHostFields(blob) {
30
+ const translations = blob?.translation;
31
+ const shop = blob?.shop;
32
+ return {
33
+ translations: isRecord(translations) ? translations : {},
34
+ shop: isRecord(shop) ? shop : {}
35
+ };
36
+ }
37
+ function isRecord(value) {
38
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
39
+ }
40
+ export async function getJoyLoyaltyPageData(options) {
41
+ const [structureAndFaqs, blob, core] = await Promise.all([
42
+ sharedStructureAndFaqs(options),
43
+ getJoyMetafieldBlob(options.storefront),
44
+ getWidgetCoreManifest({
45
+ ...(options.assetUrl ? { assetUrl: options.assetUrl } : {}),
46
+ ...(options.fetch ? { fetch: options.fetch } : {})
47
+ })
48
+ ]);
49
+ const locale = options.storefront.i18n?.language
50
+ ? resolveShopLocale(toShopifyLocale(options.storefront.i18n.language), blob?.translation)
51
+ : undefined;
52
+ const hostFields = blobToHostFields(blob);
53
+ return {
54
+ ...(structureAndFaqs?.structure != null ? { structure: structureAndFaqs.structure } : {}),
55
+ ...(structureAndFaqs?.faqs !== undefined ? { faqs: structureAndFaqs.faqs } : {}),
56
+ ...hostFields,
57
+ translations: locale ? projectTranslations(hostFields.translations, locale) : hostFields.translations,
58
+ ...(blob ? { home: blobWithoutHostFields(blob) } : {}),
59
+ ...(options.storefront.i18n?.country ? { country: options.storefront.i18n.country } : {}),
60
+ ...(locale ? { locale } : {}),
61
+ ...(core ? { core } : {})
62
+ };
63
+ }
64
+ export function projectTranslations(translations, locale) {
65
+ const dictKeys = Object.keys(translations).filter(key => isRecord(translations[key]));
66
+ if (dictKeys.length === 0)
67
+ return translations;
68
+ const primary = typeof translations.primaryLanguage === 'string' ? translations.primaryLanguage : undefined;
69
+ const keep = new Set();
70
+ for (const wanted of [locale, primary]) {
71
+ const hit = wanted ? matchLocaleKey(dictKeys, wanted) : undefined;
72
+ if (hit)
73
+ keep.add(hit);
74
+ }
75
+ if (keep.size === 0)
76
+ return translations;
77
+ const out = {};
78
+ for (const [key, value] of Object.entries(translations)) {
79
+ if (!isRecord(value) || keep.has(key))
80
+ out[key] = value;
81
+ }
82
+ return out;
83
+ }
84
+ function matchLocaleKey(keys, wanted) {
85
+ const lower = wanted.toLowerCase();
86
+ const base = lower.split('-')[0];
87
+ return (keys.find(key => key === wanted) ??
88
+ keys.find(key => key.toLowerCase() === lower) ??
89
+ keys.find(key => key.toLowerCase() === base) ??
90
+ keys.find(key => key.toLowerCase().split('-')[0] === base));
91
+ }
92
+ function blobWithoutHostFields(blob) {
93
+ const { translation: _translation, shop: _shop, ...rest } = blob;
94
+ return rest;
95
+ }
96
+ function toShopifyLocale(language) {
97
+ const [lang, region] = language.split('_');
98
+ return region ? `${lang.toLowerCase()}-${region.toUpperCase()}` : lang.toLowerCase();
99
+ }
@@ -0,0 +1,8 @@
1
+ export { getJoyInitialData } from './get-joy-initial-data.js';
2
+ export type { GetJoyInitialDataOptions, JoyInitialDataPage, JoyInitialDataResult, JoyMetafieldBlob, JoyStorefrontClient } from './get-joy-initial-data.js';
3
+ export { JOY_PERSONALIZED_CACHE_CONTROL, isJoyInitialDataPersonalized } from '../cache-control.js';
4
+ export { getJoyLoyaltyPageData } from './get-joy-loyalty-page-data.js';
5
+ export { getWidgetCoreManifest } from '../lib/core-manifest.js';
6
+ export type { GetWidgetCoreManifestOptions } from '../lib/core-manifest.js';
7
+ export type { WidgetCoreManifest } from '../lib/core-loader.js';
8
+ export type { GetJoyLoyaltyPageDataOptions, JoyLoyaltyPageData, JoyLoyaltyPageFaq } from './get-joy-loyalty-page-data.js';