@joy-loyalty/hydrogen 0.2.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
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
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
 
@@ -90,6 +90,287 @@ 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
+
207
+ ### Points calculator (`<JoyPointsCalculator/>`)
208
+
209
+ The headless counterpart of the Liquid "Joy: Point calculator" block: the "Earn X points" estimate
210
+ on the product page, and the cart total's estimate on the cart page or drawer. The estimate is
211
+ computed in the widget core from the same program data the Liquid block reads, so the numbers match.
212
+ `context` is explicit (`"product"` or `"cart"`); anything else renders nothing and warns once.
213
+
214
+ Product page — pass the Storefront product, the selected variant and the quantity state:
215
+
216
+ ```tsx
217
+ import {JoyPointsCalculator} from '@joy-loyalty/hydrogen';
218
+
219
+ <JoyPointsCalculator
220
+ apiUrl={data.joyApiUrl}
221
+ shopDomain={data.joyShopDomain}
222
+ initialData={data.joy}
223
+ context="product"
224
+ product={product}
225
+ selectedVariant={selectedVariant}
226
+ quantity={quantity}
227
+ customerTags={data.joyPoints.customerTags}
228
+ isB2B={data.joyPoints.isB2B}
229
+ isLoggedIn={data.joyPoints.isLoggedIn}
230
+ />;
231
+ ```
232
+
233
+ Cart page or drawer — pass the cart (or rely on `<JoyProvider cart>`); one component for both, cart total only:
234
+
235
+ ```tsx
236
+ <JoyPointsCalculator
237
+ apiUrl={root.joyApiUrl}
238
+ shopDomain={root.joyShopDomain}
239
+ initialData={root.joy}
240
+ context="cart"
241
+ cart={cart}
242
+ customerTags={root.joyPoints.customerTags}
243
+ isB2B={root.joyPoints.isB2B}
244
+ isLoggedIn={root.joyPoints.isLoggedIn}
245
+ />;
246
+ ```
247
+
248
+ **Customer input (host contract).** Customer tags and the B2B flag live in Shopify, not in Joy, so
249
+ the host supplies them. In the loader that calls `getJoyInitialData`, for a logged-in customer run
250
+ the Customer Account query and pass the result through `toJoyPointsCustomerInput`; pass
251
+ `isLoggedIn` for **every** visitor:
252
+
253
+ ```ts
254
+ import {
255
+ JOY_POINTS_CUSTOMER_ACCOUNT_QUERY,
256
+ toJoyPointsCustomerInput,
257
+ } from '@joy-loyalty/hydrogen';
258
+
259
+ const isLoggedIn = await context.customerAccount.isLoggedIn();
260
+ // Never let this optional query throw into the root loader (an outage would take the whole page down),
261
+ // and run it in parallel with getJoyInitialData.
262
+ const [joy, account] = await Promise.all([
263
+ getJoyInitialData({/* … as above … */}),
264
+ isLoggedIn
265
+ ? context.customerAccount.query(JOY_POINTS_CUSTOMER_ACCOUNT_QUERY).catch(() => null)
266
+ : null,
267
+ ]);
268
+ const {customerTags, isB2B} = isLoggedIn
269
+ ? toJoyPointsCustomerInput(account?.data?.customer)
270
+ : {customerTags: undefined, isB2B: undefined};
271
+ return {joy, joyPoints: {customerTags, isB2B, isLoggedIn}};
272
+ ```
273
+
274
+ If the query fails, `customerTags` / `isB2B` are `undefined` and `isLoggedIn` stays `true`: the block
275
+ degrades as documented below instead of breaking the page.
276
+
277
+ - `isLoggedIn` lets the block **hide** (instead of showing guest numbers) when the Joy token mint
278
+ fails for a logged-in shopper.
279
+ - Never pass `customerTags` / `isB2B` for a guest: when `isLoggedIn` is omitted they imply "logged in".
280
+ - This is personalized data in your root loader — same cache rule as the rest of the logged-in
281
+ root data (see [Caching](#caching)). Nothing personal is rendered on the server: the block emits
282
+ only a small reserved placeholder and reads customer inputs after hydration.
283
+
284
+ | Prop | Type | Required | Notes |
285
+ |---|---|---|---|
286
+ | `apiUrl` | `string` | yes | Headless API base URL (`JOY_API_URL`). Used for "Join Program". |
287
+ | `shopDomain` | `string` | yes | The shop's `*.myshopify.com` domain. |
288
+ | `initialData` | `JoyInitialDataResult \| null` | yes | The root loader's `getJoyInitialData()` result. `null` → renders nothing. |
289
+ | `context` | `'product' \| 'cart'` | yes | Where the block lives. Explicit, never inferred. |
290
+ | `product` | `PointsStorefrontProduct \| null` | product | Storefront product (`JoyPointsProduct` fragment). |
291
+ | `selectedVariant` | `PointsStorefrontVariant \| null` | product | Selected variant (`JoyPointsVariant` fragment). |
292
+ | `quantity` | `number` | no | Quantity picked on the page; default 1. |
293
+ | `sellingPlanId` | `string \| null` | no | Selected selling plan GID; none → one-time purchase. |
294
+ | `cart` | `StorefrontCart \| () => StorefrontCart` | cart | Storefront cart (needs `JoyPointsCartLine`); falls back to `<JoyProvider cart>`. |
295
+ | `customerTags` | `string[]` | no | Customer Account `customer.tags` (logged-in only). |
296
+ | `isB2B` | `boolean` | no | Customer has a company contact (logged-in only). |
297
+ | `isLoggedIn` | `boolean` | no | `await customerAccount.isLoggedIn()` — pass for guests too (`false`). |
298
+ | `align` | `'left' \| 'center' \| 'right'` | no | Default left (as the Liquid block). Read at mount. |
299
+ | `loginUrl` | `string` | no | Fallback join/login target; the merchant's "Call to action link" wins, then this, then `initialData.login_url`, then `/account/login`. |
300
+ | `tokenRoute` | `string` | no | Default `/api/joy-token`. |
301
+ | `onNavigate` | `(url) => void` | no | `useNavigate()`; else a full page load. |
302
+ | `onJoinClick` | `(action) => boolean \| void` | no | Called before a join click is handled; return `true` to take over. |
303
+ | `assetUrl` | `string` | no | Override the widget-core CDN URL. |
304
+ | `className` | `string` | no | Wrapper div CSS class. |
305
+
306
+ **Fragments.** Spread them into your own queries (exported from the package root):
307
+
308
+ - `JOY_POINTS_PRODUCT_FRAGMENT` (on `Product`) and `JOY_POINTS_VARIANT_FRAGMENT` (on the selected
309
+ `ProductVariant`) in the product-page query.
310
+ - `JOY_POINTS_CART_LINE_FRAGMENT` spread **inside** your existing
311
+ `lines(first: $numCartLines) { nodes { … } }` — there is no Cart-level fragment with its own
312
+ `lines`. It and the product fragment select product `title` and `priceRange`, which the
313
+ engine uses; without `priceRange` the line/variant price is used.
314
+ - `collections(first: 20)` must stay 20 — it merges with the redeem-cart fragment's selection.
315
+ - **Cart-level discounts (required for `context="cart"`).** The line fragment carries only the
316
+ line-level allocations. Also select, on the `Cart`, `discountCodes { code applicable }` and the
317
+ order-level allocations — the same fields as the redeem-cart fragment above:
318
+ - default API (2025-10 → 2026-10): `Cart.discountAllocations { targetType discountedAmount { amount currencyCode } ... on CartCodeDiscountAllocation { code } }`;
319
+ - modern (2026-07+): `joyAllDiscounts: discountAllocations(lineLevelOnly: false) { … }` on each `CartLine`.
320
+
321
+ Without one of these two sources the calculator **hides** (one `[joy] JoyPointsCalculator: …`
322
+ warning) — whether or not a discount code is applied, because an automatic order discount
323
+ (no code) is only visible through them. It never shows a wrong estimate.
324
+ - Optional: `JOY_POINTS_VARIANT_SELLING_PLANS_FRAGMENT` / `JOY_POINTS_CART_LINE_SELLING_PLAN_FRAGMENT`
325
+ need the `unauthenticated_read_selling_plans` Storefront scope; without them subscription lines
326
+ count as one-time purchases.
327
+ - `JOY_POINTS_CUSTOMER_ACCOUNT_QUERY` (Customer Account API) as shown above.
328
+ - Don't wrap the query in `useAwaitableOptions`.
329
+
330
+ **Join button.** A guest's button: with the Joy setting `customerPointCalculatorBehavior = open widget`
331
+ it opens the widget via `#joy-open` (needs `<JoyWidget/>` mounted; otherwise it navigates to the
332
+ login URL). A logged-in shopper who has not joined sees "Join Program", which calls
333
+ `POST /customer/join-program` (`joinFrom: product_page`) and reloads on success. `onJoinClick`
334
+ returning `true` overrides both.
335
+
336
+ **Differences from the Liquid block**
337
+
338
+ - V4 look (Lit web component), no counting animation. The icon (preset type, custom `urlIcon` —
339
+ http(s) only — and `iconSize`) and the text size follow the admin settings like Liquid; the gap
340
+ between icon and text is the component's 12px (Liquid: 10px).
341
+ - HTML in the merchant's calculator texts is shown as plain text (tags stripped; entities such as
342
+ `&amp;` / `&nbsp;` decoded).
343
+ - Hidden when the cart/buyer currency differs from the shop's base currency (no market-rate
344
+ conversion yet).
345
+ - Cart: one estimate for the cart total — no per-cart-line estimate.
346
+ - The Joy free-gift residue (`shop.freeGiftMinUnitPrice`; DisplayManager `getCartWithoutJoyGiftResidue`)
347
+ is not applied in headless: a cart with a Joy free-gift line can read about one minor unit per gift
348
+ line higher than the Liquid block.
349
+ - Products in more than 20 collections may differ from Liquid (`collections(first: 20)`).
350
+ - Without the cart-line fragment, rules scoped to products/collections/tags are not matched on cart lines.
351
+ - A logged-in shopper whose Joy balance is not loaded (`deferCustomerBalance: true`, or the
352
+ `/customer` read failed) → the block is hidden with one warning; it is never shown with guest numbers.
353
+ - Customer-tag rules, hiding for `joy_customer_left_programs` and the B2B exclusion
354
+ (`exclude_b2b_customers`) need the host to pass `customerTags` / `isB2B`. Without them, tag rules
355
+ evaluate with no tags and B2B customers are not hidden (one warning on `exclude_b2b_customers` shops).
356
+ - A logged-in shopper whose Joy token mint fails → hidden with one warning, **only if** the host
357
+ passes `isLoggedIn` (or `customerTags` / `isB2B`). With none of them, the block shows the guest copy in
358
+ that one state.
359
+ - The join/login link uses the merchant's "Call to action link" (`callActionLink`) first and the
360
+ `loginUrl` prop only when it is empty. Merchant custom login redirects are not applied — use
361
+ `onJoinClick` to override.
362
+ - Default alignment is left on both the product page and the cart, like the Liquid block.
363
+ - No Weaverse block in v1 — use the component directly.
364
+
365
+ **Requirements**
366
+
367
+ - **Backend.** The partial earning-limit cap and the segment/"left" exclusion need a Joy backend
368
+ whose `GET /customer` returns `earningLimit.remainingCapacity` and `excludedFromLoyalty`
369
+ (released before this package). An older backend degrades to "no partial cap / not excluded";
370
+ the page is never affected.
371
+ - **Widget core.** Requires a core with `loadPointsCalculatorCore`. Against an older core the block
372
+ renders nothing and logs one `[joy] JoyPointsCalculator: …` warning. It never throws into your page.
373
+
93
374
  ## Optional resource routes
94
375
 
95
376
  Each is a one-line re-export; the widget degrades gracefully without them.
@@ -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 {};
@@ -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,13 @@ 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';
8
+ export { JoyPointsCalculator } from './points-calculator/JoyPointsCalculator.js';
9
+ export type { JoyPointsCalculatorProps } from './points-calculator/JoyPointsCalculator.js';
10
+ export { toJoyPointsCustomerInput } from './lib/points-calculator-snapshot.js';
11
+ export { JOY_POINTS_CART_LINE_FRAGMENT, JOY_POINTS_CART_LINE_SELLING_PLAN_FRAGMENT, JOY_POINTS_CUSTOMER_ACCOUNT_QUERY, JOY_POINTS_CUSTOMER_FRAGMENT, JOY_POINTS_PRODUCT_FRAGMENT, JOY_POINTS_VARIANT_FRAGMENT, JOY_POINTS_VARIANT_SELLING_PLANS_FRAGMENT } from './points-calculator/fragments.js';
5
12
  export { createHeadlessHostAdapter, createJoyDataSource } from './headless-host-adapter.js';
6
13
  export type { ActivityQuery, DataCapabilities, EarnRequest, HeadlessHostAdapter, HeadlessHostAdapterOptions, HeadlessHostContext, HeadlessDataPort, JoyDataSource, JoyInitialData, RedeemOptions, RedeemRecipient, ReferralHistoryItem, ReferralHistoryPage, RewardQuery } from './headless-host-adapter.js';
7
14
  export { JOY_API_ORIGIN, JOY_CDN_ORIGIN, JOY_CSP_DIRECTIVES, joyCspDirectives } from './csp.js';
package/dist/index.js CHANGED
@@ -1,5 +1,9 @@
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';
4
+ export { JoyPointsCalculator } from './points-calculator/JoyPointsCalculator.js';
5
+ export { toJoyPointsCustomerInput } from './lib/points-calculator-snapshot.js';
6
+ export { JOY_POINTS_CART_LINE_FRAGMENT, JOY_POINTS_CART_LINE_SELLING_PLAN_FRAGMENT, JOY_POINTS_CUSTOMER_ACCOUNT_QUERY, JOY_POINTS_CUSTOMER_FRAGMENT, JOY_POINTS_PRODUCT_FRAGMENT, JOY_POINTS_VARIANT_FRAGMENT, JOY_POINTS_VARIANT_SELLING_PLANS_FRAGMENT } from './points-calculator/fragments.js';
3
7
  export { createHeadlessHostAdapter, createJoyDataSource } from './headless-host-adapter.js';
4
8
  export { JOY_API_ORIGIN, JOY_CDN_ORIGIN, JOY_CSP_DIRECTIVES, joyCspDirectives } from './csp.js';
5
9
  export { JOY_PERSONALIZED_CACHE_CONTROL, isJoyInitialDataPersonalized } from './cache-control.js';
@@ -33,8 +33,63 @@ 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
+ }>;
39
+ loadPointsCalculatorCore?: () => Promise<{
40
+ mountPointsCalculatorCore: MountPointsCalculatorCore;
41
+ }>;
36
42
  [key: string]: unknown;
37
43
  }
44
+ export interface RedeemCartCoreHandle {
45
+ update(): void;
46
+ dispose(): void;
47
+ }
48
+ export type MountRedeemCartCore = (el: HTMLElement, options: {
49
+ source: {
50
+ blob: unknown;
51
+ customer: unknown;
52
+ customerKey: string | null;
53
+ translation: Record<string, string>;
54
+ locale: string;
55
+ loginUrl?: string;
56
+ };
57
+ client: unknown;
58
+ cartPort: unknown;
59
+ getSnapshot: () => unknown;
60
+ hooks: {
61
+ navigate: (url: string) => void;
62
+ };
63
+ }) => RedeemCartCoreHandle | Promise<RedeemCartCoreHandle>;
64
+ export type PointsCalculatorCoreHandle = RedeemCartCoreHandle;
65
+ export type MountPointsCalculatorCore = (el: HTMLElement, options: {
66
+ source: {
67
+ blob: unknown;
68
+ customer: unknown;
69
+ customerKey: string | null;
70
+ translation: Record<string, string>;
71
+ locale: string;
72
+ loginUrl: string;
73
+ isLoggedIn: boolean;
74
+ customerTags?: string[];
75
+ isB2B?: boolean;
76
+ };
77
+ context: 'product' | 'cart';
78
+ getSnapshot: () => unknown;
79
+ align?: 'left' | 'center' | 'right';
80
+ client: {
81
+ joinProgram: (joinFrom: 'product_page') => Promise<unknown>;
82
+ } | null;
83
+ hooks: {
84
+ navigate: (url: string) => void;
85
+ openWidget: () => boolean;
86
+ reload: () => void;
87
+ onJoinClick?: (action: {
88
+ kind: 'open_widget' | 'login' | 'join_program';
89
+ href: string;
90
+ }) => boolean | void | Promise<boolean | void>;
91
+ };
92
+ }) => PointsCalculatorCoreHandle | Promise<PointsCalculatorCoreHandle>;
38
93
  export interface LoadWidgetCoreOptions {
39
94
  assetUrl?: string;
40
95
  core?: WidgetCoreManifest | null;
@@ -0,0 +1,155 @@
1
+ import type { CartLine, StorefrontCart } from '../hydrogen-cart-port.js';
2
+ type StorefrontMoney = {
3
+ amount?: string | null;
4
+ currencyCode?: string | null;
5
+ };
6
+ type StorefrontCollections = {
7
+ nodes?: Array<{
8
+ id?: string | null;
9
+ title?: string | null;
10
+ } | null> | null;
11
+ pageInfo?: {
12
+ hasNextPage?: boolean | null;
13
+ } | null;
14
+ } | null;
15
+ export type PointsProductVariant = {
16
+ id: number;
17
+ price: number;
18
+ compare_at_price: number | null;
19
+ selling_plan_allocations: Array<{
20
+ selling_plan_id: number;
21
+ price: number;
22
+ }>;
23
+ };
24
+ export type PointsProductLine = {
25
+ id: number;
26
+ title: string;
27
+ price: number;
28
+ tags: string[];
29
+ type: string;
30
+ vendor: string;
31
+ collections: string[];
32
+ collectionIds: number[];
33
+ collectionDetails: Array<{
34
+ id: number;
35
+ title: string;
36
+ }>;
37
+ variants: PointsProductVariant[];
38
+ };
39
+ export type PointsCartLine = {
40
+ product_id: number;
41
+ id: number;
42
+ title: string;
43
+ price: number;
44
+ tags: string[];
45
+ vendor: string;
46
+ type: string;
47
+ collections: string[];
48
+ collectionIds: number[];
49
+ collectionDetails: Array<{
50
+ id: number;
51
+ title: string;
52
+ }>;
53
+ quantity: number;
54
+ variant_id: number;
55
+ final_line_price: number;
56
+ variant_compare_at_price: number | null;
57
+ has_selling_plan: boolean;
58
+ };
59
+ export type PointsSnapshot = {
60
+ surface: 'product' | 'cart';
61
+ moneyUnit: 'cents' | 'units';
62
+ currency: {
63
+ active: string;
64
+ rate: number;
65
+ };
66
+ localePrimary?: boolean;
67
+ now: Date | string | number;
68
+ product?: PointsProductLine;
69
+ selectedVariantId?: number;
70
+ quantity?: number;
71
+ sellingPlanId?: number | null;
72
+ unitPriceOverride?: number | null;
73
+ cart?: {
74
+ items: PointsCartLine[];
75
+ totalDiscount: number;
76
+ lineLevelDiscounts: number[];
77
+ };
78
+ };
79
+ export type PointsStorefrontProduct = {
80
+ id?: string | null;
81
+ title?: string | null;
82
+ tags?: string[] | null;
83
+ vendor?: string | null;
84
+ productType?: string | null;
85
+ priceRange?: {
86
+ minVariantPrice?: StorefrontMoney | null;
87
+ } | null;
88
+ collections?: StorefrontCollections;
89
+ };
90
+ export type PointsStorefrontVariant = {
91
+ id?: string | null;
92
+ price?: StorefrontMoney | null;
93
+ compareAtPrice?: StorefrontMoney | null;
94
+ sellingPlanAllocations?: {
95
+ nodes?: Array<{
96
+ sellingPlan?: {
97
+ id?: string | null;
98
+ } | null;
99
+ checkoutChargeAmount?: StorefrontMoney | null;
100
+ priceAdjustments?: Array<{
101
+ price?: StorefrontMoney | null;
102
+ } | null> | null;
103
+ } | null> | null;
104
+ } | null;
105
+ };
106
+ export type PointsStorefrontCartLine = CartLine & {
107
+ merchandise?: {
108
+ price?: StorefrontMoney | null;
109
+ compareAtPrice?: StorefrontMoney | null;
110
+ product?: PointsStorefrontProduct | null;
111
+ } | null;
112
+ cost?: {
113
+ compareAtAmountPerQuantity?: StorefrontMoney | null;
114
+ } | null;
115
+ sellingPlanAllocation?: {
116
+ sellingPlan?: {
117
+ id?: string | null;
118
+ } | null;
119
+ } | null;
120
+ };
121
+ export type PointsAccountCustomer = {
122
+ tags?: string[] | null;
123
+ companyContacts?: {
124
+ nodes?: Array<{
125
+ id?: string | null;
126
+ } | null> | null;
127
+ } | null;
128
+ };
129
+ export type PointsProductSnapshotInput = {
130
+ product: PointsStorefrontProduct | null | undefined;
131
+ selectedVariant: PointsStorefrontVariant | null | undefined;
132
+ quantity?: number | null;
133
+ sellingPlanId?: string | number | null;
134
+ localePrimary?: boolean;
135
+ };
136
+ export declare function normalizePointsProductSnapshot({ product, selectedVariant, quantity, sellingPlanId, localePrimary }: PointsProductSnapshotInput): {
137
+ snapshot: PointsSnapshot;
138
+ currency: string | null;
139
+ } | null;
140
+ export declare function normalizePointsCartSnapshot(cart: (StorefrontCart & {
141
+ lines?: {
142
+ nodes?: PointsStorefrontCartLine[] | null;
143
+ } | null;
144
+ }) | null | undefined, { localePrimary }?: {
145
+ localePrimary?: boolean;
146
+ }): {
147
+ snapshot: PointsSnapshot;
148
+ currency: string | null;
149
+ cartStateKnown: boolean;
150
+ } | null;
151
+ export declare function toJoyPointsCustomerInput(customer: PointsAccountCustomer | null | undefined): {
152
+ customerTags: string[] | undefined;
153
+ isB2B: boolean | undefined;
154
+ };
155
+ export {};