@joy-loyalty/hydrogen 0.2.0 → 0.3.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 (33) hide show
  1. package/README.md +118 -4
  2. package/dist/csp.d.ts +1 -1
  3. package/dist/csp.js +2 -2
  4. package/dist/headless-host-adapter.js +3 -2
  5. package/dist/host-adapter/capabilities.d.ts +1 -0
  6. package/dist/host-adapter/capabilities.js +3 -0
  7. package/dist/host-adapter/product-fetcher.d.ts +1 -1
  8. package/dist/host-adapter/product-fetcher.js +3 -2
  9. package/dist/host-adapter/promoted-collections.d.ts +1 -1
  10. package/dist/host-adapter/promoted-collections.js +3 -2
  11. package/dist/hydrogen-cart-port.d.ts +49 -1
  12. package/dist/hydrogen-cart-port.js +24 -1
  13. package/dist/index.d.ts +3 -0
  14. package/dist/index.js +1 -0
  15. package/dist/joy-widget.js +2 -2
  16. package/dist/lib/core-loader.d.ts +23 -0
  17. package/dist/lib/recommended-loader.d.ts +2 -1
  18. package/dist/lib/recommended-loader.js +5 -3
  19. package/dist/lib/redeem-cart-snapshot.d.ts +51 -0
  20. package/dist/lib/redeem-cart-snapshot.js +173 -0
  21. package/dist/orchestrator/handlers/account.js +1 -1
  22. package/dist/orchestrator/handlers/earn.js +9 -0
  23. package/dist/orchestrator/handlers/milestone-tier.js +1 -1
  24. package/dist/redeem-cart/JoyRedeemCart.d.ts +19 -0
  25. package/dist/redeem-cart/JoyRedeemCart.js +321 -0
  26. package/dist/routes/joy-products.js +22 -10
  27. package/dist/server/get-joy-initial-data.d.ts +1 -0
  28. package/dist/server/get-joy-initial-data.js +5 -1
  29. package/dist/server/get-joy-loyalty-page-data.d.ts +1 -0
  30. package/dist/server/get-joy-loyalty-page-data.js +1 -1
  31. package/dist/widget-orchestrator.d.ts +1 -0
  32. package/dist/widget-orchestrator.js +8 -2
  33. package/package.json +2 -2
package/README.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # @joy-loyalty/hydrogen
2
2
 
3
- Joy Loyalty for Hydrogen / headless Shopify storefronts. Embeds the Joy Loyalty Widget V4 (`<JoyWidget/>`) and Loyalty Page V2 (`<JoyLoyaltyPage/>`) in any Hydrogen app, plus the server helpers and resource routes they need. No Weaverse dependency (for Weaverse use [`@joy-loyalty/weaverse-hydrogen`](../weaverse-hydrogen), which builds on this package).
3
+ Joy Loyalty for Hydrogen / headless Shopify storefronts. Embeds the Joy Loyalty Widget V4 (`<JoyWidget/>`) and the new loyalty page (`<JoyLoyaltyPage/>`) in any Hydrogen app, plus the server helpers and resource routes they need. No Weaverse dependency (for Weaverse use [`@joy-loyalty/weaverse-hydrogen`](../weaverse-hydrogen), which builds on this package).
4
4
 
5
- The widget core is a shared, host-neutral Lit bundle loaded at runtime from `https://static.joy.so`. It talks to the Joy Headless API; this package supplies the host side (token exchange, SSR data, cart wiring).
5
+ The widget core is a shared, host-neutral Lit bundle loaded at runtime from `https://api.joy.so`. It talks to the Joy Headless API; this package supplies the host side (token exchange, SSR data, cart wiring).
6
6
 
7
7
  > ESM-only. React 18 or 19 required. `@shopify/hydrogen` (>= 2025.5) is an optional peer, needed only when you wire the cart.
8
8
 
@@ -25,7 +25,7 @@ npm install @joy-loyalty/hydrogen
25
25
  | `JOY_API_URL` | server (may be passed to the browser as a prop) | e.g. `https://api.joy.so/app/api/v1/headless`. Not a credential. |
26
26
  | `JOY_SHOP_DOMAIN` | server | The shop's `*.myshopify.com` domain. |
27
27
  | `JOY_API_SECRET` | **server only** | The headless API secret from your Joy admin. |
28
- | `JOY_WIDGET_ASSET_URL` | optional | Overrides the widget-core origin (default `https://static.joy.so`). Pass it as the `assetUrl` prop. |
28
+ | `JOY_WIDGET_ASSET_URL` | optional | Overrides the widget-core origin (default `https://api.joy.so`). Pass it as the `assetUrl` prop. |
29
29
 
30
30
  > **Warning: server-only secret.** `JOY_API_SECRET` must only be read on the server (Oxygen worker / loaders / resource routes). Never prefix it `PUBLIC_` or `VITE_`, never put it in a loader return value, and never import code that reads it into a client bundle. Anyone holding the secret can mint customer tokens for your shop.
31
31
  >
@@ -90,6 +90,120 @@ import {JoyLoyaltyPage} from '@joy-loyalty/hydrogen';
90
90
  ```
91
91
  The server-rendered data carries no customer information by design; customer data loads client-side with the JWT. Set `sectionId` to render a single section.
92
92
 
93
+ ### Cart drawer block (`<JoyRedeemCart/>`)
94
+
95
+ The headless counterpart of the Liquid "Joy: Redeem in Cart" block: points balance, redeemable
96
+ rewards (fixed and dynamic), apply to cart, applied-rewards list with revoke/remove, combinability
97
+ and best-value hints, earn-back line, and a guest "earn / sign in" state, styled from the Joy admin
98
+ Redeem-in-Cart design settings. Mount it inside your cart drawer or cart page:
99
+
100
+ ```tsx
101
+ import {JoyRedeemCart} from '@joy-loyalty/hydrogen';
102
+ import {useFetcher, useRevalidator} from 'react-router';
103
+
104
+ const cartFetcher = useFetcher({key: 'joy-redeem-cart'}); // dedicated key — don't share the merchant's cart form fetcher
105
+ const {revalidate} = useRevalidator();
106
+
107
+ <JoyRedeemCart
108
+ apiUrl={data.joyApiUrl}
109
+ shopDomain={data.joyShopDomain}
110
+ initialData={data.joy}
111
+ cart={cart}
112
+ cartFetcher={cartFetcher}
113
+ cartRevalidate={revalidate}
114
+ cartRoute="/cart" // locale-aware if your app uses markets, e.g. /fr-ca/cart
115
+ />;
116
+ ```
117
+
118
+ | Prop | Type | Required | Notes |
119
+ |---|---|---|---|
120
+ | `apiUrl` | `string` | yes | Headless API base URL (`JOY_API_URL`). |
121
+ | `shopDomain` | `string` | yes | The shop's `*.myshopify.com` domain. |
122
+ | `initialData` | `JoyInitialDataResult \| null` | yes | The root loader's `getJoyInitialData()` result — the same value `<JoyWidget/>` takes. |
123
+ | `cart` | `StorefrontCart \| () => StorefrontCart` | no | The storefront cart (needs the fragment fields below). Falls back to `<JoyProvider cart>`. Without a cart (or with an empty one) the block renders nothing, like the Liquid block. |
124
+ | `cartFetcher` | `useFetcher()` result | no | With `cartRevalidate`, enables applying codes to the cart. Falls back to the `<JoyProvider>` handlers. |
125
+ | `cartRevalidate` | `() => void` | no | `useRevalidator().revalidate`. |
126
+ | `cartRoute` | `string` | no | Cart action route; default `/cart`. |
127
+ | `onCartUpdated` | `(cart) => void` | no | Called with the cart each of this block's cart mutations returns. |
128
+ | `tokenRoute` | `string` | no | Same-origin token route; default `/api/joy-token`. |
129
+ | `loginUrl` | `string` | no | Overrides `initialData.login_url` for the guest "Sign in" link. |
130
+ | `onNavigate` | `(url) => void` | no | Client-side navigation (`useNavigate()`); omitted → full page load. |
131
+ | `assetUrl` | `string` | no | Overrides the widget-core CDN URL (`JOY_WIDGET_ASSET_URL`). |
132
+ | `className` | `string` | no | Class for the wrapper element. |
133
+
134
+ **Cart action requirement.** The cart route's action must return the updated `cart` in its
135
+ response — the Hydrogen skeleton's default `{cart, errors, warnings}` from `CartForm` actions does.
136
+ The block only trusts the cart returned by its own mutation: without it, it cannot confirm a
137
+ discount write, so every apply is rolled back (the shopper's own applicable codes are restored, as
138
+ in Liquid, and the reward is refunded when the merchant enabled that).
139
+
140
+ **No cart adapter (copy-code mode).** Without `cartFetcher` + `cartRevalidate` the block still
141
+ redeems: the issued code is shown with a Copy button and a "copy this code and apply it at
142
+ checkout" hint. "Copied" appears only after a confirmed clipboard write; on origins where the
143
+ Clipboard API is unavailable or rejected, the code is selected for manual copy instead. If the
144
+ optional cart-port chunk fails to load, the block falls back to this mode. Issued codes are
145
+ remembered per customer for the browser session only (never shown to a guest or another customer).
146
+
147
+ **Cart fragment.** Merge these fields into your `CART_QUERY_FRAGMENT`. Two variants, both
148
+ validated with the Shopify toolkit:
149
+
150
+ Default — Storefront API 2025-10 → 2026-10 (uses the deprecated-but-valid `Cart.discountAllocations`):
151
+
152
+ ```graphql
153
+ fragment JoyRedeemCartDefault on Cart {
154
+ discountCodes { code applicable }
155
+ cost { subtotalAmount { amount currencyCode } totalAmount { amount currencyCode } }
156
+ discountAllocations { targetType discountedAmount { amount currencyCode } ... on CartCodeDiscountAllocation { code } }
157
+ lines(first: $numCartLines) { nodes {
158
+ id quantity
159
+ cost { subtotalAmount { amount currencyCode } totalAmount { amount currencyCode } }
160
+ discountAllocations { targetType discountedAmount { amount currencyCode } ... on CartCodeDiscountAllocation { code } }
161
+ merchandise { ... on ProductVariant { id product { id collections(first: 20) { nodes { id } pageInfo { hasNextPage } } } } }
162
+ } }
163
+ }
164
+ ```
165
+
166
+ Modern — Storefront API 2026-07+ only (invalid on 2026-04 and earlier):
167
+
168
+ ```graphql
169
+ fragment JoyRedeemCartModern on Cart {
170
+ discountCodes { code applicable }
171
+ cost { subtotalAmount { amount currencyCode } totalAmount { amount currencyCode } }
172
+ lines(first: $numCartLines) { nodes {
173
+ id quantity
174
+ cost { subtotalAmount { amount currencyCode } totalAmount { amount currencyCode } }
175
+ discountAllocations { targetType discountedAmount { amount currencyCode } ... on CartCodeDiscountAllocation { code } }
176
+ joyAllDiscounts: discountAllocations(lineLevelOnly: false) { targetType discountedAmount { amount currencyCode } ... on CartCodeDiscountAllocation { code } }
177
+ merchandise { ... on ProductVariant { id product { id collections(first: 20) { nodes { id } pageInfo { hasNextPage } } } } }
178
+ } }
179
+ deliveryGroups(first: 10) { nodes { discountAllocations { targetType discountedAmount { amount currencyCode } ... on CartCodeDiscountAllocation { code } } } }
180
+ }
181
+ ```
182
+
183
+ **Notes**
184
+
185
+ - **Cart totals.** Merchandise totals are rebuilt from line costs + discount allocations
186
+ (product- vs order-level by which list an allocation appears in; shipping excluded), never from
187
+ `cost.totalAmount`, which can include tax, duties and delivery. If your merged fragment lacks the
188
+ allocation fields while a code is applied, the block treats the cart as unknown and disables
189
+ redemption; if it cannot tell an external code's class, it shows no pre-emptive "can't combine"
190
+ hint for it.
191
+ - **Collections.** `collections(first: 20)` is optional. Absent **or** truncated
192
+ (`pageInfo.hasNextPage: true`) collection data hides collection-scoped rewards (fail-closed).
193
+ - **Multi-market.** v1 has no market-rate conversion (planned for v1.1): when the cart's currency
194
+ differs from the shop's base currency the block renders nothing, so no amount is ever shown with
195
+ the wrong currency. Carts in the shop currency are unaffected.
196
+ - **Earn-back estimate (rule-engine shops).** The cart fragment carries no product tags, vendor,
197
+ type or collection details, so on shops migrated to the rule engine a place-order rule scoped
198
+ to a collection, tag or vendor is not matched and the "Earn X points" line can be lower than the
199
+ Liquid block shows for the same cart. It is an estimate only; points are awarded on the order.
200
+ - **Guests** see the earn-back line and a "Sign in" link (`login_url`), as in the Liquid block;
201
+ the "hide for guest" setting is honoured.
202
+ - **Requires a widget core with `loadRedeemCartCore`.** Against an older core the block renders
203
+ nothing and logs one `[joy] JoyRedeemCart: …` warning. It never throws into your drawer: any load
204
+ or mount failure collapses the block and warns once.
205
+ - **Not yet supported:** the "prefer higher-value reward" swap setting (planned for v1.1).
206
+
93
207
  ## Optional resource routes
94
208
 
95
209
  Each is a one-line re-export; the widget degrades gracefully without them.
@@ -123,7 +237,7 @@ Pages whose HTML includes personalized Joy data must not be shared-cached. Use `
123
237
  ## Security notes
124
238
 
125
239
  - The customer JWT is kept in `sessionStorage` (about 1 hour TTL) so the widget can call the Headless API from the browser. Any script running on your storefront origin (for example via XSS) can read it. Keep a strict CSP and avoid untrusted third-party scripts.
126
- - The widget core is executed code loaded from `static.joy.so` (or your `assetUrl`). Allow-list only the origins you trust.
240
+ - The widget core is executed code loaded from `api.joy.so` (or your `assetUrl`). Allow-list only the origins you trust.
127
241
  - The token route responds with `Cache-Control: private, no-store`; do not override that.
128
242
 
129
243
  ## Other exports
package/dist/csp.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const JOY_CDN_ORIGIN = "https://static.joy.so";
1
+ export declare const JOY_CDN_ORIGIN = "https://api.joy.so";
2
2
  export declare const JOY_API_ORIGIN = "https://api.joy.so";
3
3
  export interface JoyCspDirectives {
4
4
  scriptSrc: string[];
package/dist/csp.js CHANGED
@@ -1,8 +1,8 @@
1
- export const JOY_CDN_ORIGIN = 'https://static.joy.so';
1
+ export const JOY_CDN_ORIGIN = 'https://api.joy.so';
2
2
  export const JOY_API_ORIGIN = 'https://api.joy.so';
3
3
  export const JOY_CSP_DIRECTIVES = {
4
4
  scriptSrc: [JOY_CDN_ORIGIN],
5
- connectSrc: [JOY_CDN_ORIGIN, JOY_API_ORIGIN],
5
+ connectSrc: unique([JOY_CDN_ORIGIN, JOY_API_ORIGIN]),
6
6
  styleSrc: [JOY_CDN_ORIGIN],
7
7
  imgSrc: [JOY_CDN_ORIGIN],
8
8
  fontSrc: [JOY_CDN_ORIGIN]
@@ -50,8 +50,9 @@ function parsePageQuery(query) {
50
50
  export function createHeadlessHostAdapter(options) {
51
51
  const { context: contextInput, initialData = null, source, getToken, productsRoute = DEFAULT_PRODUCTS_ROUTE } = options;
52
52
  const context = { ...contextInput, translation: contextInput.translation ?? {} };
53
- const getProductByHandle = createProductByHandleFetcher(productsRoute);
54
- const getPromotedCollections = createPromotedCollectionsFetcher(productsRoute);
53
+ const getCountry = () => context.country || undefined;
54
+ const getProductByHandle = createProductByHandleFetcher(productsRoute, getCountry);
55
+ const getPromotedCollections = createPromotedCollectionsFetcher(productsRoute, getCountry);
55
56
  let appleWalletPassCache = {
56
57
  createdApplePass: !!initialData?.customer?.createdApplePass,
57
58
  qrCodeDownloadApplePass: initialData?.customer?.qrCodeDownloadApplePass || ''
@@ -1,3 +1,4 @@
1
1
  import type { DataCapabilities } from './types.js';
2
2
  export declare const HEADLESS_CAPABILITIES: DataCapabilities;
3
3
  export declare const DEFAULT_PRODUCTS_ROUTE = "/api/joy-products";
4
+ export declare function withMarketCountry(query: string, country?: string): string;
@@ -10,3 +10,6 @@ export const HEADLESS_CAPABILITIES = {
10
10
  googleWalletPass: true
11
11
  };
12
12
  export const DEFAULT_PRODUCTS_ROUTE = '/api/joy-products';
13
+ export function withMarketCountry(query, country) {
14
+ return country ? `${query}&country=${encodeURIComponent(country)}` : query;
15
+ }
@@ -1,2 +1,2 @@
1
1
  import type { CurrentProduct } from './types.js';
2
- export declare function createProductByHandleFetcher(productsRoute: string): (handle: string) => Promise<CurrentProduct | null>;
2
+ export declare function createProductByHandleFetcher(productsRoute: string, getCountry?: () => string | undefined): (handle: string) => Promise<CurrentProduct | null>;
@@ -1,4 +1,5 @@
1
- export function createProductByHandleFetcher(productsRoute) {
1
+ import { withMarketCountry } from './capabilities.js';
2
+ export function createProductByHandleFetcher(productsRoute, getCountry = () => undefined) {
2
3
  let pending = [];
3
4
  let scheduled = false;
4
5
  async function flush() {
@@ -11,7 +12,7 @@ export function createProductByHandleFetcher(productsRoute) {
11
12
  return;
12
13
  }
13
14
  try {
14
- const url = `${productsRoute}?handles=${handles.map(encodeURIComponent).join(',')}`;
15
+ const url = withMarketCountry(`${productsRoute}?handles=${handles.map(encodeURIComponent).join(',')}`, getCountry());
15
16
  const response = await fetch(url, { headers: { Accept: 'application/json' }, credentials: 'same-origin' });
16
17
  if (!response.ok)
17
18
  throw new Error(`joy-products ${response.status}`);
@@ -1,2 +1,2 @@
1
1
  import type { PromotedCollection, PromotedCollectionSelection } from './types.js';
2
- export declare function createPromotedCollectionsFetcher(productsRoute: string): (selections: PromotedCollectionSelection[]) => Promise<PromotedCollection[]>;
2
+ export declare function createPromotedCollectionsFetcher(productsRoute: string, getCountry?: () => string | undefined): (selections: PromotedCollectionSelection[]) => Promise<PromotedCollection[]>;
@@ -1,4 +1,5 @@
1
- export function createPromotedCollectionsFetcher(productsRoute) {
1
+ import { withMarketCountry } from './capabilities.js';
2
+ export function createPromotedCollectionsFetcher(productsRoute, getCountry = () => undefined) {
2
3
  return async function getPromotedCollections(selections) {
3
4
  const handles = Array.from(new Set((selections ?? []).map(selection => selection?.handle).filter(Boolean)));
4
5
  if (!handles.length)
@@ -18,7 +19,7 @@ export function createPromotedCollectionsFetcher(productsRoute) {
18
19
  .map(handle => snapshotByHandle.get(handle))
19
20
  .filter(Boolean);
20
21
  try {
21
- const url = `${productsRoute}?collections=${handles.map(encodeURIComponent).join(',')}`;
22
+ const url = withMarketCountry(`${productsRoute}?collections=${handles.map(encodeURIComponent).join(',')}`, getCountry());
22
23
  const response = await fetch(url, {
23
24
  headers: { Accept: 'application/json' },
24
25
  credentials: 'same-origin'
@@ -1,10 +1,37 @@
1
- type CartLine = {
1
+ import type { CartPort } from '@joy-loyalty/sdk/ports';
2
+ type StorefrontMoney = {
3
+ amount?: string | null;
4
+ currencyCode?: string | null;
5
+ };
6
+ export type StorefrontCartDiscountAllocation = {
7
+ targetType?: string | null;
8
+ discountedAmount?: StorefrontMoney | null;
9
+ code?: string | null;
10
+ };
11
+ export type CartLine = {
2
12
  id?: string | null;
3
13
  merchandise?: {
4
14
  id?: string | null;
5
15
  availableForSale?: boolean | null;
16
+ product?: {
17
+ id?: string | null;
18
+ collections?: {
19
+ nodes?: Array<{
20
+ id?: string | null;
21
+ } | null> | null;
22
+ pageInfo?: {
23
+ hasNextPage?: boolean | null;
24
+ } | null;
25
+ } | null;
26
+ } | null;
6
27
  } | null;
7
28
  quantity?: number | null;
29
+ cost?: {
30
+ totalAmount?: StorefrontMoney | null;
31
+ subtotalAmount?: StorefrontMoney | null;
32
+ } | null;
33
+ discountAllocations?: StorefrontCartDiscountAllocation[] | null;
34
+ joyAllDiscounts?: StorefrontCartDiscountAllocation[] | null;
8
35
  };
9
36
  export type StorefrontCart = {
10
37
  updatedAt?: string | null;
@@ -25,6 +52,12 @@ export type StorefrontCart = {
25
52
  currencyCode?: string | null;
26
53
  } | null;
27
54
  } | null;
55
+ discountAllocations?: StorefrontCartDiscountAllocation[] | null;
56
+ deliveryGroups?: {
57
+ nodes?: Array<{
58
+ discountAllocations?: StorefrontCartDiscountAllocation[] | null;
59
+ } | null> | null;
60
+ } | null;
28
61
  };
29
62
  export interface HydrogenCartFetcher {
30
63
  state: string;
@@ -41,6 +74,17 @@ export interface HydrogenCartPortOptions {
41
74
  cartRoute?: string;
42
75
  onCartUpdated?: (cart: StorefrontCart) => void;
43
76
  }
77
+ export type SetDiscountCodesResult = {
78
+ ok: true;
79
+ discountCodes: Array<{
80
+ code: string;
81
+ applicable: boolean;
82
+ }>;
83
+ source: 'mutation' | 'host';
84
+ } | {
85
+ ok: false;
86
+ reason: string;
87
+ };
44
88
  export declare function normalizeHydrogenCart(cart: StorefrontCart | null | undefined): {
45
89
  lines: {
46
90
  variantId: string;
@@ -113,6 +157,7 @@ export declare class HydrogenCartPort {
113
157
  reason: string;
114
158
  }>;
115
159
  removeDiscount(code: string): Promise<void>;
160
+ setDiscountCodes(codes: string[]): Promise<SetDiscountCodesResult>;
116
161
  addLines(lines: Array<{
117
162
  id: string;
118
163
  quantity?: number;
@@ -130,5 +175,8 @@ export declare class HydrogenCartPort {
130
175
  private submit;
131
176
  private publishCart;
132
177
  }
178
+ export type RedeemCartPort = CartPort & {
179
+ setDiscountCodes: HydrogenCartPort['setDiscountCodes'];
180
+ };
133
181
  export declare function settleHydrogenCartPort(port: HydrogenCartPort): void;
134
182
  export {};
@@ -97,7 +97,7 @@ export class HydrogenCartPort {
97
97
  if (cart &&
98
98
  discountCodes.length === existingCodes.length &&
99
99
  discountCodes.every(existingCode => existingCodes.includes(existingCode))) {
100
- return { ok: true, applied: true };
100
+ return { ok: true, applied: cart.discountCodes.find(discount => discount.code === code)?.applicable === true };
101
101
  }
102
102
  try {
103
103
  const result = await this.submit(CartForm.ACTIONS.DiscountCodesUpdate, { discountCodes });
@@ -123,6 +123,29 @@ export class HydrogenCartPort {
123
123
  });
124
124
  });
125
125
  }
126
+ setDiscountCodes(codes) {
127
+ return this.serialize(async () => {
128
+ try {
129
+ const seen = new Set();
130
+ const discountCodes = codes.filter(code => {
131
+ const key = code.toLowerCase();
132
+ if (seen.has(key))
133
+ return false;
134
+ seen.add(key);
135
+ return true;
136
+ });
137
+ const result = await this.submit(CartForm.ACTIONS.DiscountCodesUpdate, { discountCodes });
138
+ const updated = normalizeHydrogenCart(cartFromResult(result));
139
+ if (updated)
140
+ return { ok: true, discountCodes: updated.discountCodes, source: 'mutation' };
141
+ const host = this.getCart();
142
+ return host ? { ok: true, discountCodes: host.discountCodes, source: 'host' } : { ok: false, reason: 'NO_CART' };
143
+ }
144
+ catch (error) {
145
+ return { ok: false, reason: error.message };
146
+ }
147
+ });
148
+ }
126
149
  addLines(lines) {
127
150
  for (const line of lines) {
128
151
  if (!isVariantGid(line.id))
package/dist/index.d.ts CHANGED
@@ -2,6 +2,9 @@ export { JoyWidget } from './joy-widget.js';
2
2
  export type { JoyWidgetProps } from './joy-widget.js';
3
3
  export { JoyLoyaltyPage, isLoyaltyPageV2Enabled } from './loyalty-page/JoyLoyaltyPage.js';
4
4
  export type { JoyLoyaltyPageInitialData, JoyLoyaltyPageProps } from './loyalty-page/JoyLoyaltyPage.js';
5
+ export { JoyRedeemCart } from './redeem-cart/JoyRedeemCart.js';
6
+ export type { JoyRedeemCartProps } from './redeem-cart/JoyRedeemCart.js';
7
+ export type { StorefrontCart } from './hydrogen-cart-port.js';
5
8
  export { createHeadlessHostAdapter, createJoyDataSource } from './headless-host-adapter.js';
6
9
  export type { ActivityQuery, DataCapabilities, EarnRequest, HeadlessHostAdapter, HeadlessHostAdapterOptions, HeadlessHostContext, HeadlessDataPort, JoyDataSource, JoyInitialData, RedeemOptions, RedeemRecipient, ReferralHistoryItem, ReferralHistoryPage, RewardQuery } from './headless-host-adapter.js';
7
10
  export { JOY_API_ORIGIN, JOY_CDN_ORIGIN, JOY_CSP_DIRECTIVES, joyCspDirectives } from './csp.js';
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  export { JoyWidget } from './joy-widget.js';
2
2
  export { JoyLoyaltyPage, isLoyaltyPageV2Enabled } from './loyalty-page/JoyLoyaltyPage.js';
3
+ export { JoyRedeemCart } from './redeem-cart/JoyRedeemCart.js';
3
4
  export { createHeadlessHostAdapter, createJoyDataSource } from './headless-host-adapter.js';
4
5
  export { JOY_API_ORIGIN, JOY_CDN_ORIGIN, JOY_CSP_DIRECTIVES, joyCspDirectives } from './csp.js';
5
6
  export { JOY_PERSONALIZED_CACHE_CONTROL, isJoyInitialDataPersonalized } from './cache-control.js';
@@ -61,7 +61,7 @@ export function JoyWidget({ apiUrl = null, tokenRoute, loginUrl = '/account', lo
61
61
  const [open, setOpen] = useState(false);
62
62
  const [coreLoaded, setCoreLoaded] = useState(false);
63
63
  const [coreFailed, setCoreFailed] = useState(false);
64
- const hostConfig = useJoyConfig({ apiUrl, loginUrl, locale, shopDomain });
64
+ const hostConfig = useJoyConfig({ apiUrl, loginUrl, locale: locale ?? initialData?.locale, shopDomain });
65
65
  const config = {
66
66
  ...hostConfig,
67
67
  locale: resolveShopLocale(hostConfig.locale, initialData?.blob?.translation)
@@ -162,7 +162,7 @@ export function JoyWidget({ apiUrl = null, tokenRoute, loginUrl = '/account', lo
162
162
  registerUrl: authUrls.registerUrl,
163
163
  loyaltyPageUrl,
164
164
  accountUrl: '/account',
165
- country: country ?? 'US',
165
+ country: country ?? initialData?.country ?? 'US',
166
166
  viewport: { width: window.innerWidth }
167
167
  },
168
168
  source
@@ -33,8 +33,31 @@ export interface WidgetCoreExports {
33
33
  }) => Promise<unknown[]>;
34
34
  getDeeplinkByHash?: (hash: string) => unknown;
35
35
  resolveDeeplinkHash?: (param: string | null) => string | null;
36
+ loadRedeemCartCore?: () => Promise<{
37
+ mountRedeemCartCore: MountRedeemCartCore;
38
+ }>;
36
39
  [key: string]: unknown;
37
40
  }
41
+ export interface RedeemCartCoreHandle {
42
+ update(): void;
43
+ dispose(): void;
44
+ }
45
+ export type MountRedeemCartCore = (el: HTMLElement, options: {
46
+ source: {
47
+ blob: unknown;
48
+ customer: unknown;
49
+ customerKey: string | null;
50
+ translation: Record<string, string>;
51
+ locale: string;
52
+ loginUrl?: string;
53
+ };
54
+ client: unknown;
55
+ cartPort: unknown;
56
+ getSnapshot: () => unknown;
57
+ hooks: {
58
+ navigate: (url: string) => void;
59
+ };
60
+ }) => RedeemCartCoreHandle | Promise<RedeemCartCoreHandle>;
38
61
  export interface LoadWidgetCoreOptions {
39
62
  assetUrl?: string;
40
63
  core?: WidgetCoreManifest | null;
@@ -39,5 +39,6 @@ export interface LoadRecommendedOptions {
39
39
  productCard?: ProductCardHelpers;
40
40
  currency?: string;
41
41
  productsRoute?: string;
42
+ country?: string;
42
43
  }
43
- export declare function loadRecommendedProducts({ widgetEl, sections, productCard, currency, productsRoute }: LoadRecommendedOptions): Promise<void>;
44
+ export declare function loadRecommendedProducts({ widgetEl, sections, productCard, currency, productsRoute, country }: LoadRecommendedOptions): Promise<void>;
@@ -2,7 +2,7 @@ import { DEFAULT_PRODUCTS_ROUTE } from '../headless-host-adapter.js';
2
2
  import { PRODUCT_PATH_PATTERN, RECENTLY_VIEWED_STORAGE_KEY as STORAGE_KEY } from '@joy-loyalty/sdk/widget-contracts';
3
3
  const AUTO_SIGNALS = ['product_page', 'recently_viewed'];
4
4
  const CARD_IMAGE_WIDTH = 400;
5
- export async function loadRecommendedProducts({ widgetEl, sections, productCard, currency, productsRoute = DEFAULT_PRODUCTS_ROUTE }) {
5
+ export async function loadRecommendedProducts({ widgetEl, sections, productCard, currency, productsRoute = DEFAULT_PRODUCTS_ROUTE, country }) {
6
6
  try {
7
7
  if (!productCard) {
8
8
  console.warn('[joy] recommendations skipped: the loaded widget core has no `productCard` export ' +
@@ -10,7 +10,7 @@ export async function loadRecommendedProducts({ widgetEl, sections, productCard,
10
10
  return;
11
11
  }
12
12
  const section = (sections.find(entry => entry?.id === 'PRODUCTS') ?? {});
13
- const { products, currencyCode } = await fetchRecommended(productsRoute, section);
13
+ const { products, currencyCode } = await fetchRecommended(productsRoute, section, country);
14
14
  if (!products.length)
15
15
  return;
16
16
  const subConfig = productCard.resolveSubscriptionConfig(sections, 'PRODUCTS');
@@ -31,13 +31,15 @@ export async function loadRecommendedProducts({ widgetEl, sections, productCard,
31
31
  widgetEl.recentProductsLoading = false;
32
32
  }
33
33
  }
34
- async function fetchRecommended(route, section) {
34
+ async function fetchRecommended(route, section, country) {
35
35
  const empty = { products: [], currencyCode: null };
36
36
  const params = new URLSearchParams({ recommend: resolveSeedHandle(section.personalizeFrom) });
37
37
  if (section.fallbackCollectionHandle)
38
38
  params.set('fallbackCollection', section.fallbackCollectionHandle);
39
39
  if (section.fallbackSort)
40
40
  params.set('fallbackSort', section.fallbackSort);
41
+ if (country)
42
+ params.set('country', country);
41
43
  const response = await fetch(`${route}?${params}`, {
42
44
  headers: { Accept: 'application/json' },
43
45
  credentials: 'same-origin'
@@ -0,0 +1,51 @@
1
+ import type { StorefrontCart } from '../hydrogen-cart-port.js';
2
+ export type RedeemCartLineAllocation = {
3
+ amount: number;
4
+ discount_application: {
5
+ type: string;
6
+ title: string;
7
+ };
8
+ };
9
+ export type RedeemCartLevelApplication = {
10
+ type: string;
11
+ title: string;
12
+ total_allocated_amount: number;
13
+ };
14
+ export type RedeemCartItem = {
15
+ id: number | null;
16
+ product_id: number | null;
17
+ variant_id: number | null;
18
+ quantity: number;
19
+ original_line_price: number;
20
+ final_line_price: number;
21
+ final_price: number;
22
+ collectionIds: number[];
23
+ };
24
+ export type RedeemCartInfoItem = {
25
+ variant_id: number | null;
26
+ product_id: number | null;
27
+ quantity: number;
28
+ original_line_price: number;
29
+ final_line_price: number;
30
+ line_level_total_discount: number;
31
+ line_level_discount_allocations: RedeemCartLineAllocation[];
32
+ };
33
+ export type RedeemCartInfo = {
34
+ currency: string | null;
35
+ original_total_price: number;
36
+ total_discount: number;
37
+ discount_codes: Array<{
38
+ code: string;
39
+ applicable: boolean;
40
+ }>;
41
+ items?: RedeemCartInfoItem[];
42
+ cart_level_discount_applications?: RedeemCartLevelApplication[];
43
+ };
44
+ export type RedeemCartSnapshot = {
45
+ cartItems: RedeemCartItem[];
46
+ cartInfo: RedeemCartInfo;
47
+ cartStateKnown: boolean;
48
+ collectionIdsKnown: boolean;
49
+ currency: string | null;
50
+ };
51
+ export declare function normalizeRedeemCartSnapshot(cart: StorefrontCart | null | undefined): RedeemCartSnapshot | null;