From 3e76c0bd1fb104132015ac7a8c5fb6d3d9ac69ce Mon Sep 17 00:00:00 2001 From: Andrew Jaynes Date: Fri, 13 Nov 2026 09:09:53 -0700 Subject: [PATCH 01/17] fix(commerce): carry shopper customization details through add-to-cart AIROBUILD-9325 AddToCartItemInput was narrowed to { skuId, name, quantity }, so shopper customization (uploaded designs, add-ons, metafields) never reached order-api or checkout. Widen the cart contract end-to-end: - order-subgraph.ts: add optional details (productAssetUrl, selectedAddons) and metafields to AddToCartItemInput, forward them in buildAddLineItemBySkuIdInput with length/HTTPS/count validation, and select metafields in getCartOrderQuery so they round-trip on read. - cart/[id]/items/POST.ts: forward the full validated body instead of a hand-picked three-field literal. - cart-model.ts: widen the storefront-side AddToCartItemInput identically. - commerce-provider.tsx: addItem() was rebuilding a narrowed { skuId, name, quantity } object before calling addToCart(), dropping details/metafields even after the type widened; pass the full item through instead. --- .../src/lib/commerce/order-subgraph.ts | 91 ++++++++++++++++++- packages/commerce-server/src/router.test.ts | 84 +++++++++++++++++ .../src/server/api/commerce/cart/POST.ts | 2 +- .../api/commerce/cart/[id]/items/POST.ts | 10 +- .../commerce-storefront/src/cart-model.ts | 20 ++++ .../src/cart-parts.test.tsx | 41 +++++++++ .../src/commerce-provider.tsx | 6 +- 7 files changed, 239 insertions(+), 15 deletions(-) diff --git a/packages/commerce-server/src/lib/commerce/order-subgraph.ts b/packages/commerce-server/src/lib/commerce/order-subgraph.ts index 7eef6751..92712161 100644 --- a/packages/commerce-server/src/lib/commerce/order-subgraph.ts +++ b/packages/commerce-server/src/lib/commerce/order-subgraph.ts @@ -94,6 +94,12 @@ export interface CartNote { createdAt?: string | null; } +export interface CartMetafield { + key?: string | null; + type?: string | null; + value?: string | null; +} + export interface CartLineItem { id?: string | null; name?: string | null; @@ -106,6 +112,7 @@ export interface CartLineItem { discounts?: CartDiscount[] | null; taxes?: CartTax[] | null; notes?: CartNote[] | null; + metafields?: CartMetafield[] | null; createdAt?: string | null; updatedAt?: string | null; } @@ -190,6 +197,26 @@ export interface CreateDraftLineItemInput { details?: LineItemDetailsInput; } +// Distinct from `LineItemDetailsInput`: the GraphQL `AddLineItemInput.details.selectedAddons` +// field takes `{ optionId, values: [{ inputValue | optionValueId }] }` — the catalog-option +// *input* shape — not the `{ attribute, sku, values: [{ name, costAdjustment }] }` *output* +// shape a line item returns once built. +export interface AddLineItemSelectedAddonInput { + optionId: string; + values: Array<{ inputValue: string }>; +} + +export interface AddLineItemDetailsInput { + productAssetUrl?: string; + selectedAddons?: AddLineItemSelectedAddonInput[]; +} + +export interface AddLineItemMetafieldInput { + key: string; + value: string; + type: 'JSON'; +} + export interface AddLineItemBySkuIdInput { orderId: string; skuId: string; @@ -198,7 +225,8 @@ export interface AddLineItemBySkuIdInput { fulfillmentMode?: string; status?: string; type?: string; - details?: LineItemDetailsInput; + details?: AddLineItemDetailsInput; + metafields?: AddLineItemMetafieldInput[]; } export interface UpdateLineItemByIdInput { @@ -275,10 +303,61 @@ export interface EmptyCartOrderInput { currencyCode?: string; } +export const PRODUCT_ASSET_URL_MAX_LENGTH = 2048; +export const SELECTED_ADDON_VALUE_MAX_LENGTH = 500; +export const MAX_SELECTED_ADDONS = 20; +export const MAX_METAFIELDS = 10; +export const METAFIELD_VALUE_MAX_LENGTH = 2000; + +export interface AddToCartMetafieldInput { + key: string; + value: string; + type?: 'JSON'; +} + export interface AddToCartItemInput { skuId: string; name: string; quantity: number; + details?: AddLineItemDetailsInput; + metafields?: AddToCartMetafieldInput[]; +} + +// UX-only guard; `order-api`'s schema is the authoritative enforcement point. +function assertValidCartItemInput(item: AddToCartItemInput): void { + const assetUrl = item.details?.productAssetUrl; + if (assetUrl !== undefined) { + if (assetUrl.length > PRODUCT_ASSET_URL_MAX_LENGTH) { + throw new Error(`productAssetUrl cannot exceed ${PRODUCT_ASSET_URL_MAX_LENGTH} characters`); + } + let parsed: URL; + try { + parsed = new URL(assetUrl); + } catch { + throw new Error('productAssetUrl must be an absolute URL'); + } + if (parsed.protocol !== 'https:') throw new Error('productAssetUrl must use https'); + } + const addons = item.details?.selectedAddons ?? []; + if (addons.length > MAX_SELECTED_ADDONS) { + throw new Error(`selectedAddons cannot exceed ${MAX_SELECTED_ADDONS} entries`); + } + for (const addon of addons) { + for (const value of addon.values) { + if (value.inputValue.length > SELECTED_ADDON_VALUE_MAX_LENGTH) { + throw new Error(`selectedAddons value cannot exceed ${SELECTED_ADDON_VALUE_MAX_LENGTH} characters`); + } + } + } + const metafields = item.metafields ?? []; + if (metafields.length > MAX_METAFIELDS) { + throw new Error(`metafields cannot exceed ${MAX_METAFIELDS} entries`); + } + for (const metafield of metafields) { + if (metafield.value.length > METAFIELD_VALUE_MAX_LENGTH) { + throw new Error(`metafield value cannot exceed ${METAFIELD_VALUE_MAX_LENGTH} characters`); + } + } } export interface CartSummaryTotals { @@ -326,6 +405,7 @@ export function buildAddLineItemBySkuIdInput( orderId: string, item: AddToCartItemInput, ): AddLineItemBySkuIdInput { + assertValidCartItemInput(item); return { orderId, skuId: item.skuId, @@ -333,6 +413,10 @@ export function buildAddLineItemBySkuIdInput( quantity: item.quantity, fulfillmentMode: 'NONE', status: 'DRAFT', + ...(item.details ? { details: item.details } : {}), + ...(item.metafields + ? { metafields: item.metafields.map((metafield) => ({ ...metafield, type: metafield.type ?? 'JSON' })) } + : {}), }; } @@ -498,6 +582,11 @@ export const getCartOrderQuery = ` author authorType } + metafields { + key + type + value + } } totals { subTotal { diff --git a/packages/commerce-server/src/router.test.ts b/packages/commerce-server/src/router.test.ts index 24773dac..f4feaa04 100644 --- a/packages/commerce-server/src/router.test.ts +++ b/packages/commerce-server/src/router.test.ts @@ -358,6 +358,90 @@ describe('Commerce scoped routes', () => { }, ); + it('forwards details and metafields to addLineItemBySkuId when creating a cart', async (): Promise => { + vi.mocked(gqlRequest) + .mockResolvedValueOnce({ addDraftOrder: { id: 'cart-1' } }) + .mockResolvedValueOnce({ addLineItemBySkuId: { id: 'item-1' } }) + .mockResolvedValueOnce({ orderById: { id: 'cart-1', lineItems: [] } }); + const res = response(); + const details = { + productAssetUrl: 'https://cdn.example.com/design.png', + selectedAddons: [{ optionId: 'opt-1', values: [{ inputValue: 'Custom design 123' }] }], + }; + const metafields = [{ key: 'designId', value: 'design-123' }]; + await createCart( + { + headers: {}, + body: { lineItems: [{ skuId: 'sku-1', name: 'Product', quantity: 1, details, metafields }] }, + } as unknown as Request, + res as unknown as Response, + ); + expect(vi.mocked(gqlRequest).mock.calls[1]?.[0].variables).toEqual({ + input: expect.objectContaining({ + details, + metafields: [{ key: 'designId', value: 'design-123', type: 'JSON' }], + }), + }); + }); + + it('forwards details and metafields to addLineItemBySkuId when adding to an existing cart', async (): Promise => { + vi.mocked(gqlRequest) + .mockResolvedValueOnce({ addLineItemBySkuId: { id: 'item-1' } }) + .mockResolvedValueOnce({ orderById: { id: 'cart-1', lineItems: [] } }); + const res = response(); + const details = { productAssetUrl: 'https://cdn.example.com/design.png' }; + const metafields = [{ key: 'designId', value: 'design-123' }]; + await addItem( + { + headers: {}, + params: { id: 'cart-1' }, + body: { skuId: 'sku-1', name: 'Product', quantity: 1, details, metafields }, + } as unknown as Request, + res as unknown as Response, + ); + expect(vi.mocked(gqlRequest).mock.calls[0]?.[0].variables).toEqual({ + input: expect.objectContaining({ + details, + metafields: [{ key: 'designId', value: 'design-123', type: 'JSON' }], + }), + }); + }); + + it.each([ + ['http://cdn.example.com/design.png', 'non-https productAssetUrl'], + [`https://cdn.example.com/${'a'.repeat(2049)}.png`, 'oversized productAssetUrl'], + ])('rejects an add-item with %s (%s)', async (productAssetUrl): Promise => { + const res = response(); + await addItem( + { + headers: {}, + params: { id: 'cart-1' }, + body: { skuId: 'sku-1', name: 'Product', quantity: 1, details: { productAssetUrl } }, + } as unknown as Request, + res as unknown as Response, + ); + expect(res.status).toHaveBeenCalledWith(500); + expect(gqlRequest).not.toHaveBeenCalled(); + }); + + it('rejects an add-item with more selectedAddons than the configured maximum', async (): Promise => { + const res = response(); + const selectedAddons = Array.from({ length: 21 }, (_, index) => ({ + optionId: `opt-${index}`, + values: [{ inputValue: 'value' }], + })); + await addItem( + { + headers: {}, + params: { id: 'cart-1' }, + body: { skuId: 'sku-1', name: 'Product', quantity: 1, details: { selectedAddons } }, + } as unknown as Request, + res as unknown as Response, + ); + expect(res.status).toHaveBeenCalledWith(500); + expect(gqlRequest).not.toHaveBeenCalled(); + }); + const scopedRequest = { headers: {}, query: {}, diff --git a/packages/commerce-server/src/server/api/commerce/cart/POST.ts b/packages/commerce-server/src/server/api/commerce/cart/POST.ts index 0d94b4fb..cdae9916 100644 --- a/packages/commerce-server/src/server/api/commerce/cart/POST.ts +++ b/packages/commerce-server/src/server/api/commerce/cart/POST.ts @@ -17,7 +17,7 @@ * * Body: * currencyCode? - override the configured currency (defaults to GODADDY_CURRENCY_CODE) - * lineItems? - [{ skuId, name, quantity }] added one-by-one after create + * lineItems? - [{ skuId, name, quantity, details?, metafields? }] added one-by-one after create * * Response: { cart: CartOrder | null } * Same shape as GET /api/commerce/cart/:id and the other cart mutation diff --git a/packages/commerce-server/src/server/api/commerce/cart/[id]/items/POST.ts b/packages/commerce-server/src/server/api/commerce/cart/[id]/items/POST.ts index 0731bff9..5cf00518 100644 --- a/packages/commerce-server/src/server/api/commerce/cart/[id]/items/POST.ts +++ b/packages/commerce-server/src/server/api/commerce/cart/[id]/items/POST.ts @@ -5,7 +5,7 @@ * (which creates the cart via POST /api/commerce/cart); subsequent adds * for the same cart go here. * - * Body: { skuId: string, name: string, quantity: number } + * Body: { skuId: string, name: string, quantity: number, details?, metafields? } * * Response: { cart: CartOrder | null } * The underlying `addLineItemBySkuId` GraphQL mutation only returns the @@ -63,13 +63,7 @@ async function addLineItem(req: Request, res: Response): Promise { await gqlRequest({ endpoint, query: addLineItemBySkuIdMutation, - variables: { - input: buildAddLineItemBySkuIdInput(cartId, { - skuId: body.skuId, - name: body.name, - quantity: body.quantity, - }), - }, + variables: { input: buildAddLineItemBySkuIdInput(cartId, body as AddToCartItemInput) }, headers, }); diff --git a/packages/commerce-storefront/src/cart-model.ts b/packages/commerce-storefront/src/cart-model.ts index d93d855f..fa5af96d 100644 --- a/packages/commerce-storefront/src/cart-model.ts +++ b/packages/commerce-storefront/src/cart-model.ts @@ -77,6 +77,12 @@ export interface CartNote { createdAt?: string | null; } +export interface CartMetafield { + key?: string | null; + type?: string | null; + value?: string | null; +} + export interface CartLineItem { id?: string | null; name?: string | null; @@ -89,6 +95,7 @@ export interface CartLineItem { discounts?: CartDiscount[] | null; taxes?: CartTax[] | null; notes?: CartNote[] | null; + metafields?: CartMetafield[] | null; createdAt?: string | null; updatedAt?: string | null; } @@ -129,10 +136,23 @@ export interface CartOrder { tags?: string[] | null; } +export interface AddToCartSelectedAddonInput { + optionId: string; + values: Array<{ inputValue: string }>; +} + +export interface AddToCartMetafieldInput { + key: string; + value: string; + type?: 'JSON'; +} + export interface AddToCartItemInput { skuId: string; name: string; quantity: number; + details?: { productAssetUrl?: string; selectedAddons?: AddToCartSelectedAddonInput[] }; + metafields?: AddToCartMetafieldInput[]; } export interface CartSummaryTotals { diff --git a/packages/commerce-storefront/src/cart-parts.test.tsx b/packages/commerce-storefront/src/cart-parts.test.tsx index 4217e421..e600bca4 100644 --- a/packages/commerce-storefront/src/cart-parts.test.tsx +++ b/packages/commerce-storefront/src/cart-parts.test.tsx @@ -561,6 +561,47 @@ describe('composable cart', () => { expect(added).toHaveBeenCalledWith({ name: 'Product 2', quantity: 1, isSample: true }); }); + it('forwards details and metafields from a custom addItem call to the cart POST body', async () => { + const fetchMock = mockStore(); + function CustomAdd(): ReactElement { + const { addItem } = useCommerce(); + return ( + + ); + } + render(app()); + await userEvent.click(screen.getByRole('button', { name: 'Add customized' })); + await waitFor(() => expect(fetchMock).toHaveBeenCalled()); + const itemsCall = fetchMock.mock.calls.find(([input]) => String(input).includes('/items')); + const body = JSON.parse(String(itemsCall?.[1]?.body)); + expect(body).toEqual({ + skuId: 'sku-mug', + name: 'Mug', + quantity: 1, + details: { + productAssetUrl: 'https://cdn.test/design.png', + selectedAddons: [{ optionId: 'opt-1', values: [{ inputValue: 'Custom design 123' }] }], + }, + metafields: [{ key: 'designId', value: 'design-123' }], + }); + }); + it('renders the packaged drawer from CommerceStorefront with dividers between lines', async () => { mockStore(); render( diff --git a/packages/commerce-storefront/src/commerce-provider.tsx b/packages/commerce-storefront/src/commerce-provider.tsx index fc172700..3179ffa5 100644 --- a/packages/commerce-storefront/src/commerce-provider.tsx +++ b/packages/commerce-storefront/src/commerce-provider.tsx @@ -664,11 +664,7 @@ function BoundCommerceProvider({ headers.set('X-Commerce-Scope', config.cartScope); return checkedFetch(input, { ...init, headers }); }; - const result: CartResponse = await addToCart( - id.current, - { skuId: item.skuId, name: item.name, quantity: item.quantity }, - fetchCart, - ); + const result: CartResponse = await addToCart(id.current, item, fetchCart); if (!result.cart?.id || !result.cart.lineItems?.length) throw new StorefrontError('addReturnedNoCart'); if (!isActive()) return; commit(result.cart); From cc8b6c6cb01246900ef754fc5af9ed14f91d1309 Mon Sep 17 00:00:00 2001 From: Andrew Jaynes Date: Fri, 13 Nov 2026 10:37:06 -0700 Subject: [PATCH 02/17] chore: add changeset for cart customization fields --- .changeset/cart-customization-details.md | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .changeset/cart-customization-details.md diff --git a/.changeset/cart-customization-details.md b/.changeset/cart-customization-details.md new file mode 100644 index 00000000..472b47d9 --- /dev/null +++ b/.changeset/cart-customization-details.md @@ -0,0 +1,6 @@ +--- +"@godaddy/gd-commerce-server": patch +"@godaddy/gd-commerce-storefront": patch +--- + +Carry optional `details` (`productAssetUrl`, `selectedAddons`) and `metafields` through every add-to-cart call, so a shopper's product customization reaches checkout and the order instead of staying client-side only. Existing calls without these fields behave exactly as before. From 454ab95bcd53363a9716e26d06b756d207e5a14e Mon Sep 17 00:00:00 2001 From: Andrew Jaynes Date: Fri, 13 Nov 2026 17:15:40 -0700 Subject: [PATCH 03/17] fix(commerce-storefront): show selected add-ons in the cart drawer The cart drawer mapped only catalog selectedOptions (Color, Size) into CartItemOptions, so a line's selectedAddons (shopper customization) showed the preview image but not the add-on text, leaving the drawer out of sync with checkout. Fold selectedAddons into the same options list useCart() already exposes, reusing the existing "Label: value" rendering. --- .../src/cart-parts.test.tsx | 41 +++++++++++++++++++ .../commerce-storefront/src/cart-state.ts | 14 +++++-- 2 files changed, 51 insertions(+), 4 deletions(-) diff --git a/packages/commerce-storefront/src/cart-parts.test.tsx b/packages/commerce-storefront/src/cart-parts.test.tsx index e600bca4..ff69b2fd 100644 --- a/packages/commerce-storefront/src/cart-parts.test.tsx +++ b/packages/commerce-storefront/src/cart-parts.test.tsx @@ -602,6 +602,47 @@ describe('composable cart', () => { }); }); + it('surfaces selectedAddons in useCart() options alongside selectedOptions', async () => { + localStorage.setItem(storageKey, 'cart-1'); + vi.stubGlobal( + 'fetch', + vi.fn(async (input: RequestInfo | URL) => { + const url = new URL(String(input), 'https://host.test'); + if (url.pathname.endsWith('/config')) return response({ cartScope: 's', currencyCode: 'USD' }); + return response({ + cart: { + id: 'cart-1', + lineItems: [ + { + id: 'line-1', + name: 'Mug', + quantity: 1, + details: { + selectedAddons: [{ attribute: 'Design', values: [{ name: 'Custom design 123' }] }], + }, + totals: { subTotal: { value: 1200, currencyCode: 'USD' } }, + }, + ], + totals: { + subTotal: { value: 1200, currencyCode: 'USD' }, + total: { value: 1200, currencyCode: 'USD' }, + }, + }, + }); + }), + ); + function Options(): ReactElement { + const { items } = useCart(); + return {JSON.stringify(items[0]?.options ?? [])}; + } + render(app()); + await waitFor(() => + expect(screen.getByTestId('options')).toHaveTextContent( + JSON.stringify([{ attribute: 'Design', values: ['Custom design 123'] }]), + ), + ); + }); + it('renders the packaged drawer from CommerceStorefront with dividers between lines', async () => { mockStore(); render( diff --git a/packages/commerce-storefront/src/cart-state.ts b/packages/commerce-storefront/src/cart-state.ts index 90b90b8c..5380e6d6 100644 --- a/packages/commerce-storefront/src/cart-state.ts +++ b/packages/commerce-storefront/src/cart-state.ts @@ -64,10 +64,16 @@ export function useCart(): CartState { name: item.name ?? '', quantity: item.quantity ?? 0, imageUrl: item.details?.productAssetUrl || null, - options: (item.details?.selectedOptions ?? []).map((option) => ({ - attribute: option.attribute ?? '', - values: option.values ?? [], - })), + options: [ + ...(item.details?.selectedOptions ?? []).map((option) => ({ + attribute: option.attribute ?? '', + values: option.values ?? [], + })), + ...(item.details?.selectedAddons ?? []).map((addon) => ({ + attribute: addon.attribute ?? '', + values: (addon.values ?? []).map((value) => value.name ?? ''), + })), + ], subtotal: typeof item.totals?.subTotal?.value === 'number' ? item.totals.subTotal.value : null, currency: item.totals?.subTotal?.currencyCode ?? currency, sample: null, From b01409402cc5254a71d281b683e28032d87929b3 Mon Sep 17 00:00:00 2001 From: Andrew Jaynes Date: Fri, 13 Nov 2026 17:16:23 -0700 Subject: [PATCH 04/17] fix(commerce-server): validate cart customization before creating the cart MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit assertValidCartItemInput ran inside buildAddLineItemBySkuIdInput, which on POST /cart is only reached after addDraftOrder already created the cart — an invalid productAssetUrl or an oversized add-on list orphaned that cart and, since it threw a plain Error, came back as a 500 instead of a 400. Run the same validation in the pre-create loop, and switch every check to InvalidRequestError so it maps to 400. Also reject a LIST-option addon value ({ optionValueId }) explicitly: only TEXT/NUMBER options ({ inputValue }) are supported by this change, and an optionValueId-only value previously crashed with a TypeError on .inputValue.length instead of a clean validation error. Correct a comment that called this guard UX-only with order-api's schema as the authoritative enforcement point — order-api's schema has no such length/HTTPS/count limits, so this is the only place they're enforced. --- .../src/lib/commerce/order-subgraph.ts | 40 ++++++++++++----- packages/commerce-server/src/router.test.ts | 45 ++++++++++++++++++- .../src/server/api/commerce/cart/POST.ts | 4 ++ 3 files changed, 77 insertions(+), 12 deletions(-) diff --git a/packages/commerce-server/src/lib/commerce/order-subgraph.ts b/packages/commerce-server/src/lib/commerce/order-subgraph.ts index 92712161..783d1d95 100644 --- a/packages/commerce-server/src/lib/commerce/order-subgraph.ts +++ b/packages/commerce-server/src/lib/commerce/order-subgraph.ts @@ -14,6 +14,7 @@ * - Money values are integers in the currency's smallest unit (cents for USD). */ +import { InvalidRequestError } from './errors'; import type { Money } from './gql'; export interface OrderStorefrontEndpointInput { @@ -323,39 +324,58 @@ export interface AddToCartItemInput { metafields?: AddToCartMetafieldInput[]; } -// UX-only guard; `order-api`'s schema is the authoritative enforcement point. -function assertValidCartItemInput(item: AddToCartItemInput): void { +// Only TEXT/NUMBER catalog options (shopper-typed `inputValue`) are supported here. A LIST +// option's pre-defined `optionValueId` is a distinct, unvalidated shape — out of scope for this +// change (see the ticket's addon-value-shape decision) — so reject it explicitly rather than +// letting it reach `order-api` unchecked or crash on a missing `inputValue`. +function assertSupportedAddonValueShape(value: { inputValue?: string }): string { + if (typeof value.inputValue !== 'string') { + throw new InvalidRequestError( + 'selectedAddons values must use { inputValue }; LIST-option values ({ optionValueId }) are not supported', + ); + } + return value.inputValue; +} + +// This is the only place these length/HTTPS/count limits are enforced — `order-api`'s schema +// uses a plain `z.string()` for these fields with no such caps. +export function assertValidCartItemInput(item: AddToCartItemInput): void { const assetUrl = item.details?.productAssetUrl; if (assetUrl !== undefined) { if (assetUrl.length > PRODUCT_ASSET_URL_MAX_LENGTH) { - throw new Error(`productAssetUrl cannot exceed ${PRODUCT_ASSET_URL_MAX_LENGTH} characters`); + throw new InvalidRequestError( + `productAssetUrl cannot exceed ${PRODUCT_ASSET_URL_MAX_LENGTH} characters`, + ); } let parsed: URL; try { parsed = new URL(assetUrl); } catch { - throw new Error('productAssetUrl must be an absolute URL'); + throw new InvalidRequestError('productAssetUrl must be an absolute URL'); } - if (parsed.protocol !== 'https:') throw new Error('productAssetUrl must use https'); + if (parsed.protocol !== 'https:') throw new InvalidRequestError('productAssetUrl must use https'); } const addons = item.details?.selectedAddons ?? []; if (addons.length > MAX_SELECTED_ADDONS) { - throw new Error(`selectedAddons cannot exceed ${MAX_SELECTED_ADDONS} entries`); + throw new InvalidRequestError(`selectedAddons cannot exceed ${MAX_SELECTED_ADDONS} entries`); } for (const addon of addons) { for (const value of addon.values) { - if (value.inputValue.length > SELECTED_ADDON_VALUE_MAX_LENGTH) { - throw new Error(`selectedAddons value cannot exceed ${SELECTED_ADDON_VALUE_MAX_LENGTH} characters`); + const inputValue = assertSupportedAddonValueShape(value); + if (inputValue.length > SELECTED_ADDON_VALUE_MAX_LENGTH) { + throw new InvalidRequestError( + `selectedAddons value cannot exceed ${SELECTED_ADDON_VALUE_MAX_LENGTH} characters`, + ); } } } const metafields = item.metafields ?? []; if (metafields.length > MAX_METAFIELDS) { - throw new Error(`metafields cannot exceed ${MAX_METAFIELDS} entries`); + throw new InvalidRequestError(`metafields cannot exceed ${MAX_METAFIELDS} entries`); } for (const metafield of metafields) { if (metafield.value.length > METAFIELD_VALUE_MAX_LENGTH) { - throw new Error(`metafield value cannot exceed ${METAFIELD_VALUE_MAX_LENGTH} characters`); + throw new InvalidRequestError(`metafield value cannot exceed ${METAFIELD_VALUE_MAX_LENGTH} characters`); } } } diff --git a/packages/commerce-server/src/router.test.ts b/packages/commerce-server/src/router.test.ts index f4feaa04..11555f90 100644 --- a/packages/commerce-server/src/router.test.ts +++ b/packages/commerce-server/src/router.test.ts @@ -420,7 +420,7 @@ describe('Commerce scoped routes', () => { } as unknown as Request, res as unknown as Response, ); - expect(res.status).toHaveBeenCalledWith(500); + expect(res.status).toHaveBeenCalledWith(400); expect(gqlRequest).not.toHaveBeenCalled(); }); @@ -438,7 +438,48 @@ describe('Commerce scoped routes', () => { } as unknown as Request, res as unknown as Response, ); - expect(res.status).toHaveBeenCalledWith(500); + expect(res.status).toHaveBeenCalledWith(400); + expect(gqlRequest).not.toHaveBeenCalled(); + }); + + it('rejects an add-item with a LIST-option (optionValueId) addon value', async (): Promise => { + const res = response(); + await addItem( + { + headers: {}, + params: { id: 'cart-1' }, + body: { + skuId: 'sku-1', + name: 'Product', + quantity: 1, + details: { selectedAddons: [{ optionId: 'opt-1', values: [{ optionValueId: 'val-1' }] }] }, + }, + } as unknown as Request, + res as unknown as Response, + ); + expect(res.status).toHaveBeenCalledWith(400); + expect(gqlRequest).not.toHaveBeenCalled(); + }); + + it('rejects cart creation with an invalid customization before creating the cart', async (): Promise => { + const res = response(); + await createCart( + { + headers: {}, + body: { + lineItems: [ + { + skuId: 'sku-1', + name: 'Product', + quantity: 1, + details: { productAssetUrl: 'http://cdn.example.com/design.png' }, + }, + ], + }, + } as unknown as Request, + res as unknown as Response, + ); + expect(res.status).toHaveBeenCalledWith(400); expect(gqlRequest).not.toHaveBeenCalled(); }); diff --git a/packages/commerce-server/src/server/api/commerce/cart/POST.ts b/packages/commerce-server/src/server/api/commerce/cart/POST.ts index cdae9916..976e6a37 100644 --- a/packages/commerce-server/src/server/api/commerce/cart/POST.ts +++ b/packages/commerce-server/src/server/api/commerce/cart/POST.ts @@ -36,6 +36,7 @@ import { type AddLineItemBySkuIdResult, type AddLineItemBySkuIdVariables, type AddToCartItemInput, + assertValidCartItemInput, buildAddLineItemBySkuIdInput, buildEmptyCartOrderInput, type GetCartOrderResult, @@ -72,12 +73,15 @@ async function createCart(req: Request, res: Response): Promise { // Validate all items BEFORE creating the cart so a bad payload can't // produce an orphaned cart (cart created, item add fails, client never // gets the id). Mirrors the validation in POST /api/commerce/cart/:id/items. + // assertValidCartItemInput also runs later inside buildAddLineItemBySkuIdInput, + // but by then the cart already exists — it must run here too, before creation. for (const item of initialItems) { if (!item.skuId || !item.name || typeof item.quantity !== 'number') { throw new InvalidRequestError( 'Each lineItem must have skuId, a non-empty name, and a numeric quantity', ); } + assertValidCartItemInput(item); } const config: CommerceConfig = readCommerceConfigForResponse(res); From fcde81e183e1aa56640f550b67d01601b2494171 Mon Sep 17 00:00:00 2001 From: Andrew Jaynes Date: Mon, 16 Nov 2026 23:24:12 -0700 Subject: [PATCH 05/17] fix(commerce-server): reject malformed cart item shapes with 400 instead of 500 assertValidCartItemInput assumed metafields/selectedAddons already matched their TypeScript shapes, so a non-array selectedAddons, a metafield missing key/value, or a non-string metafield value threw an uncaught TypeError instead of InvalidRequestError. The add-item route also cast the request body to AddToCartItemInput before any validation ran. Validate the body's shape explicitly before the cast, and check each field's type before reading off it. --- .../src/lib/commerce/order-subgraph.ts | 83 ++++++++++++++----- packages/commerce-server/src/router.test.ts | 70 ++++++++++++++++ .../api/commerce/cart/[id]/items/POST.ts | 6 +- 3 files changed, 136 insertions(+), 23 deletions(-) diff --git a/packages/commerce-server/src/lib/commerce/order-subgraph.ts b/packages/commerce-server/src/lib/commerce/order-subgraph.ts index 783d1d95..432d0ccc 100644 --- a/packages/commerce-server/src/lib/commerce/order-subgraph.ts +++ b/packages/commerce-server/src/lib/commerce/order-subgraph.ts @@ -328,20 +328,29 @@ export interface AddToCartItemInput { // option's pre-defined `optionValueId` is a distinct, unvalidated shape — out of scope for this // change (see the ticket's addon-value-shape decision) — so reject it explicitly rather than // letting it reach `order-api` unchecked or crash on a missing `inputValue`. -function assertSupportedAddonValueShape(value: { inputValue?: string }): string { - if (typeof value.inputValue !== 'string') { +function assertSupportedAddonValueShape(value: unknown): string { + if ( + typeof value !== 'object' || + value === null || + typeof (value as { inputValue?: unknown }).inputValue !== 'string' + ) { throw new InvalidRequestError( 'selectedAddons values must use { inputValue }; LIST-option values ({ optionValueId }) are not supported', ); } - return value.inputValue; + return (value as { inputValue: string }).inputValue; } -// This is the only place these length/HTTPS/count limits are enforced — `order-api`'s schema -// uses a plain `z.string()` for these fields with no such caps. +// This is the only place these shapes, length/HTTPS/count limits are enforced — `order-api`'s +// schema uses a plain `z.string()` for these fields with no such caps, and the request body +// arrives as untyped JSON, so every field read here must be shape-checked before use rather +// than trusted from a TypeScript cast. export function assertValidCartItemInput(item: AddToCartItemInput): void { const assetUrl = item.details?.productAssetUrl; if (assetUrl !== undefined) { + if (typeof assetUrl !== 'string') { + throw new InvalidRequestError('productAssetUrl must be a string'); + } if (assetUrl.length > PRODUCT_ASSET_URL_MAX_LENGTH) { throw new InvalidRequestError( `productAssetUrl cannot exceed ${PRODUCT_ASSET_URL_MAX_LENGTH} characters`, @@ -355,29 +364,59 @@ export function assertValidCartItemInput(item: AddToCartItemInput): void { } if (parsed.protocol !== 'https:') throw new InvalidRequestError('productAssetUrl must use https'); } - const addons = item.details?.selectedAddons ?? []; - if (addons.length > MAX_SELECTED_ADDONS) { - throw new InvalidRequestError(`selectedAddons cannot exceed ${MAX_SELECTED_ADDONS} entries`); + const addons = item.details?.selectedAddons; + if (addons !== undefined) { + if (!Array.isArray(addons)) throw new InvalidRequestError('selectedAddons must be an array'); + if (addons.length > MAX_SELECTED_ADDONS) { + throw new InvalidRequestError(`selectedAddons cannot exceed ${MAX_SELECTED_ADDONS} entries`); + } + for (const addon of addons) { + if ( + typeof addon !== 'object' || + addon === null || + typeof addon.optionId !== 'string' || + !addon.optionId + ) { + throw new InvalidRequestError('Each selectedAddons entry must have a non-empty optionId'); + } + if (!Array.isArray(addon.values)) { + throw new InvalidRequestError('Each selectedAddons entry must have a values array'); + } + for (const value of addon.values) { + const inputValue = assertSupportedAddonValueShape(value); + if (inputValue.length > SELECTED_ADDON_VALUE_MAX_LENGTH) { + throw new InvalidRequestError( + `selectedAddons value cannot exceed ${SELECTED_ADDON_VALUE_MAX_LENGTH} characters`, + ); + } + } + } } - for (const addon of addons) { - for (const value of addon.values) { - const inputValue = assertSupportedAddonValueShape(value); - if (inputValue.length > SELECTED_ADDON_VALUE_MAX_LENGTH) { + const metafields = item.metafields; + if (metafields !== undefined) { + if (!Array.isArray(metafields)) throw new InvalidRequestError('metafields must be an array'); + if (metafields.length > MAX_METAFIELDS) { + throw new InvalidRequestError(`metafields cannot exceed ${MAX_METAFIELDS} entries`); + } + for (const metafield of metafields) { + if ( + typeof metafield !== 'object' || + metafield === null || + !metafield.key || + typeof metafield.key !== 'string' + ) { + throw new InvalidRequestError('Each metafield must have a non-empty string key'); + } + if (typeof metafield.value !== 'string') { + throw new InvalidRequestError('Each metafield value must be a string'); + } + if (metafield.value.length > METAFIELD_VALUE_MAX_LENGTH) { throw new InvalidRequestError( - `selectedAddons value cannot exceed ${SELECTED_ADDON_VALUE_MAX_LENGTH} characters`, + `metafield value cannot exceed ${METAFIELD_VALUE_MAX_LENGTH} characters`, ); } } } - const metafields = item.metafields ?? []; - if (metafields.length > MAX_METAFIELDS) { - throw new InvalidRequestError(`metafields cannot exceed ${MAX_METAFIELDS} entries`); - } - for (const metafield of metafields) { - if (metafield.value.length > METAFIELD_VALUE_MAX_LENGTH) { - throw new InvalidRequestError(`metafield value cannot exceed ${METAFIELD_VALUE_MAX_LENGTH} characters`); - } - } } export interface CartSummaryTotals { diff --git a/packages/commerce-server/src/router.test.ts b/packages/commerce-server/src/router.test.ts index 11555f90..6fa364b2 100644 --- a/packages/commerce-server/src/router.test.ts +++ b/packages/commerce-server/src/router.test.ts @@ -461,6 +461,76 @@ describe('Commerce scoped routes', () => { expect(gqlRequest).not.toHaveBeenCalled(); }); + it.each([ + ['non-array selectedAddons', { selectedAddons: 'not-an-array' }], + ['selectedAddons entry missing optionId', { selectedAddons: [{ values: [{ inputValue: 'x' }] }] }], + ['selectedAddons entry with non-array values', { selectedAddons: [{ optionId: 'opt-1', values: 'x' }] }], + ['selectedAddons value that is null', { selectedAddons: [{ optionId: 'opt-1', values: [null] }] }], + ['non-string productAssetUrl', { productAssetUrl: 42 }], + ])('rejects an add-item with %s instead of a 500', async (_label, details): Promise => { + const res = response(); + await addItem( + { + headers: {}, + params: { id: 'cart-1' }, + body: { skuId: 'sku-1', name: 'Product', quantity: 1, details }, + } as unknown as Request, + res as unknown as Response, + ); + expect(res.status).toHaveBeenCalledWith(400); + expect(gqlRequest).not.toHaveBeenCalled(); + }); + + it.each([ + ['non-array metafields', 'not-an-array'], + ['metafields entry missing key', [{ value: 'x' }]], + ['metafields entry with non-string key', [{ key: 42, value: 'x' }]], + ['metafields entry with non-string value', [{ key: 'designId', value: 42 }]], + ['metafields entry that is null', [null]], + ])('rejects an add-item with %s instead of a 500', async (_label, metafields): Promise => { + const res = response(); + await addItem( + { + headers: {}, + params: { id: 'cart-1' }, + body: { skuId: 'sku-1', name: 'Product', quantity: 1, metafields }, + } as unknown as Request, + res as unknown as Response, + ); + expect(res.status).toHaveBeenCalledWith(400); + expect(gqlRequest).not.toHaveBeenCalled(); + }); + + it('rejects an add-item with more metafields than the configured maximum', async (): Promise => { + const res = response(); + const metafields = Array.from({ length: 11 }, (_, index) => ({ key: `k${index}`, value: 'v' })); + await addItem( + { + headers: {}, + params: { id: 'cart-1' }, + body: { skuId: 'sku-1', name: 'Product', quantity: 1, metafields }, + } as unknown as Request, + res as unknown as Response, + ); + expect(res.status).toHaveBeenCalledWith(400); + expect(gqlRequest).not.toHaveBeenCalled(); + }); + + it('rejects an add-item with an oversized metafield value', async (): Promise => { + const res = response(); + const metafields = [{ key: 'designId', value: 'a'.repeat(2001) }]; + await addItem( + { + headers: {}, + params: { id: 'cart-1' }, + body: { skuId: 'sku-1', name: 'Product', quantity: 1, metafields }, + } as unknown as Request, + res as unknown as Response, + ); + expect(res.status).toHaveBeenCalledWith(400); + expect(gqlRequest).not.toHaveBeenCalled(); + }); + it('rejects cart creation with an invalid customization before creating the cart', async (): Promise => { const res = response(); await createCart( diff --git a/packages/commerce-server/src/server/api/commerce/cart/[id]/items/POST.ts b/packages/commerce-server/src/server/api/commerce/cart/[id]/items/POST.ts index 5cf00518..13d4677e 100644 --- a/packages/commerce-server/src/server/api/commerce/cart/[id]/items/POST.ts +++ b/packages/commerce-server/src/server/api/commerce/cart/[id]/items/POST.ts @@ -24,6 +24,7 @@ import { type AddLineItemBySkuIdResult, type AddLineItemBySkuIdVariables, type AddToCartItemInput, + assertValidCartItemInput, buildAddLineItemBySkuIdInput, type GetCartOrderResult, type GetCartOrderVariables, @@ -50,6 +51,9 @@ async function addLineItem(req: Request, res: Response): Promise { if (!body.skuId || !body.name || typeof body.quantity !== 'number') { throw new InvalidRequestError('Missing required fields: skuId, name, quantity'); } + // `body` is untyped JSON past this point — validate its shape before trusting the cast below. + const item = body as AddToCartItemInput; + assertValidCartItemInput(item); const config: CommerceConfig = readCommerceConfigForResponse(res); assertCommerceCartScope(req, config); @@ -63,7 +67,7 @@ async function addLineItem(req: Request, res: Response): Promise { await gqlRequest({ endpoint, query: addLineItemBySkuIdMutation, - variables: { input: buildAddLineItemBySkuIdInput(cartId, body as AddToCartItemInput) }, + variables: { input: buildAddLineItemBySkuIdInput(cartId, item) }, headers, }); From 369d84fef90f9312e1b1abb193ad2eb1fa28e47f Mon Sep 17 00:00:00 2001 From: Andrew Jaynes Date: Mon, 16 Nov 2026 23:25:35 -0700 Subject: [PATCH 06/17] fix(commerce-server): force metafield type to JSON server-side AddLineItemMetafieldInput passed through metafield.type ?? 'JSON', so a client-supplied type reached order-api unchecked (order-api rejects anything but a literal 'JSON', turning it into a 502) and any other client property on a metafield object was forwarded too. JSON is the only supported type, so build the mutation input by picking key/value explicitly and always setting type: 'JSON'. Drop the now-pointless type field from AddToCartMetafieldInput in both packages. --- .../src/lib/commerce/order-subgraph.ts | 11 ++++++-- packages/commerce-server/src/router.test.ts | 25 +++++++++++++++++++ .../commerce-storefront/src/cart-model.ts | 3 ++- 3 files changed, 36 insertions(+), 3 deletions(-) diff --git a/packages/commerce-server/src/lib/commerce/order-subgraph.ts b/packages/commerce-server/src/lib/commerce/order-subgraph.ts index 432d0ccc..f2736956 100644 --- a/packages/commerce-server/src/lib/commerce/order-subgraph.ts +++ b/packages/commerce-server/src/lib/commerce/order-subgraph.ts @@ -310,10 +310,11 @@ export const MAX_SELECTED_ADDONS = 20; export const MAX_METAFIELDS = 10; export const METAFIELD_VALUE_MAX_LENGTH = 2000; +// JSON is the only metafield type the storefront's add-to-cart surface supports — no `type` +// field here, so a client can't request a different one. export interface AddToCartMetafieldInput { key: string; value: string; - type?: 'JSON'; } export interface AddToCartItemInput { @@ -474,7 +475,13 @@ export function buildAddLineItemBySkuIdInput( status: 'DRAFT', ...(item.details ? { details: item.details } : {}), ...(item.metafields - ? { metafields: item.metafields.map((metafield) => ({ ...metafield, type: metafield.type ?? 'JSON' })) } + ? { + metafields: item.metafields.map(({ key, value }) => ({ + key, + value, + type: 'JSON' as const, + })), + } : {}), }; } diff --git a/packages/commerce-server/src/router.test.ts b/packages/commerce-server/src/router.test.ts index 6fa364b2..c5e7e282 100644 --- a/packages/commerce-server/src/router.test.ts +++ b/packages/commerce-server/src/router.test.ts @@ -407,6 +407,31 @@ describe('Commerce scoped routes', () => { }); }); + it('ignores a client-supplied metafield type and always sends JSON', async (): Promise => { + vi.mocked(gqlRequest) + .mockResolvedValueOnce({ addLineItemBySkuId: { id: 'item-1' } }) + .mockResolvedValueOnce({ orderById: { id: 'cart-1', lineItems: [] } }); + const res = response(); + await addItem( + { + headers: {}, + params: { id: 'cart-1' }, + body: { + skuId: 'sku-1', + name: 'Product', + quantity: 1, + metafields: [{ key: 'designId', value: 'design-123', type: 'NOT_JSON', extra: 'nope' }], + }, + } as unknown as Request, + res as unknown as Response, + ); + expect(vi.mocked(gqlRequest).mock.calls[0]?.[0].variables).toEqual({ + input: expect.objectContaining({ + metafields: [{ key: 'designId', value: 'design-123', type: 'JSON' }], + }), + }); + }); + it.each([ ['http://cdn.example.com/design.png', 'non-https productAssetUrl'], [`https://cdn.example.com/${'a'.repeat(2049)}.png`, 'oversized productAssetUrl'], diff --git a/packages/commerce-storefront/src/cart-model.ts b/packages/commerce-storefront/src/cart-model.ts index fa5af96d..ae9ead01 100644 --- a/packages/commerce-storefront/src/cart-model.ts +++ b/packages/commerce-storefront/src/cart-model.ts @@ -141,10 +141,11 @@ export interface AddToCartSelectedAddonInput { values: Array<{ inputValue: string }>; } +// JSON is the only metafield type the server accepts here — no `type` field, so there is +// nothing for a caller to get wrong. export interface AddToCartMetafieldInput { key: string; value: string; - type?: 'JSON'; } export interface AddToCartItemInput { From a9e6460285346041b8b51c114aaac8bb77a9bcab Mon Sep 17 00:00:00 2001 From: Andrew Jaynes Date: Mon, 16 Nov 2026 23:33:37 -0700 Subject: [PATCH 07/17] fix(commerce-storefront): show addon surcharges and drop blank addon names in the drawer useCart() mapped selectedAddons values with value.name ?? '', so a value missing a name rendered a blank "Attribute: " line, and costAdjustment was read from the API response but never surfaced, so a priced addon's surcharge was invisible next to a subtotal that already included it. Skip values with no name, and append the formatted cost adjustment to the ones that have a price. --- .../src/cart-parts.test.tsx | 49 +++++++++++++++++ .../commerce-storefront/src/cart-state.ts | 54 +++++++++++-------- 2 files changed, 82 insertions(+), 21 deletions(-) diff --git a/packages/commerce-storefront/src/cart-parts.test.tsx b/packages/commerce-storefront/src/cart-parts.test.tsx index ff69b2fd..c6204afd 100644 --- a/packages/commerce-storefront/src/cart-parts.test.tsx +++ b/packages/commerce-storefront/src/cart-parts.test.tsx @@ -643,6 +643,55 @@ describe('composable cart', () => { ); }); + it('includes a priced addon surcharge and drops a nameless addon value', async () => { + localStorage.setItem(storageKey, 'cart-1'); + vi.stubGlobal( + 'fetch', + vi.fn(async (input: RequestInfo | URL) => { + const url = new URL(String(input), 'https://host.test'); + if (url.pathname.endsWith('/config')) return response({ cartScope: 's', currencyCode: 'USD' }); + return response({ + cart: { + id: 'cart-1', + lineItems: [ + { + id: 'line-1', + name: 'Mug', + quantity: 1, + details: { + selectedAddons: [ + { + attribute: 'Engraving', + values: [ + { name: 'Custom design 123', costAdjustment: { value: 500, currencyCode: 'USD' } }, + { name: null }, + ], + }, + ], + }, + totals: { subTotal: { value: 1700, currencyCode: 'USD' } }, + }, + ], + totals: { + subTotal: { value: 1700, currencyCode: 'USD' }, + total: { value: 1700, currencyCode: 'USD' }, + }, + }, + }); + }), + ); + function Options(): ReactElement { + const { items } = useCart(); + return {JSON.stringify(items[0]?.options ?? [])}; + } + render(app()); + await waitFor(() => + expect(screen.getByTestId('options')).toHaveTextContent( + JSON.stringify([{ attribute: 'Engraving', values: ['Custom design 123 (+$5.00)'] }]), + ), + ); + }); + it('renders the packaged drawer from CommerceStorefront with dividers between lines', async () => { mockStore(); render( diff --git a/packages/commerce-storefront/src/cart-state.ts b/packages/commerce-storefront/src/cart-state.ts index 5380e6d6..f58ac853 100644 --- a/packages/commerce-storefront/src/cart-state.ts +++ b/packages/commerce-storefront/src/cart-state.ts @@ -1,4 +1,5 @@ import { useMemo } from 'react'; +import { money } from './api'; import { useCommerce } from './commerce-provider'; import { type SampleProduct, sampleCurrency, useSampleCart } from './sample-cart'; @@ -31,7 +32,7 @@ export interface CartState { /** Read the cart from anywhere inside `CommerceProvider`, for example to build a custom cart button. */ export function useCart(): CartState { - const { cart, config, connection, hydrating } = useCommerce(); + const { cart, config, connection, hydrating, locale } = useCommerce(); const sample = useSampleCart(); const isSample: boolean = connection === 'unbound'; const sampleItems = sample.items; @@ -59,30 +60,41 @@ export function useCart(): CartState { const lines = cart?.lineItems ?? []; const subtotal = cart?.totals?.subTotal?.value; return { - items: lines.map((item) => ({ - id: item.id ?? '', - name: item.name ?? '', - quantity: item.quantity ?? 0, - imageUrl: item.details?.productAssetUrl || null, - options: [ - ...(item.details?.selectedOptions ?? []).map((option) => ({ - attribute: option.attribute ?? '', - values: option.values ?? [], - })), - ...(item.details?.selectedAddons ?? []).map((addon) => ({ - attribute: addon.attribute ?? '', - values: (addon.values ?? []).map((value) => value.name ?? ''), - })), - ], - subtotal: typeof item.totals?.subTotal?.value === 'number' ? item.totals.subTotal.value : null, - currency: item.totals?.subTotal?.currencyCode ?? currency, - sample: null, - })), + items: lines.map((item) => { + const itemCurrency = item.totals?.subTotal?.currencyCode ?? currency; + return { + id: item.id ?? '', + name: item.name ?? '', + quantity: item.quantity ?? 0, + imageUrl: item.details?.productAssetUrl || null, + options: [ + ...(item.details?.selectedOptions ?? []).map((option) => ({ + attribute: option.attribute ?? '', + values: option.values ?? [], + })), + ...(item.details?.selectedAddons ?? []).map((addon) => ({ + attribute: addon.attribute ?? '', + // A value without a name has nothing to show; skip it rather than render a blank entry. + values: (addon.values ?? []) + .filter((value) => !!value.name) + .map((value) => { + const cost = value.costAdjustment; + if (typeof cost?.value !== 'number' || cost.value === 0) return value.name as string; + const formatted = money(cost.value, cost.currencyCode ?? itemCurrency, locale); + return `${value.name} (${cost.value > 0 ? '+' : ''}${formatted})`; + }), + })), + ], + subtotal: typeof item.totals?.subTotal?.value === 'number' ? item.totals.subTotal.value : null, + currency: itemCurrency, + sample: null, + }; + }), itemCount: lines.reduce((total, item) => total + (item.quantity ?? 0), 0), subtotal: typeof subtotal === 'number' ? subtotal : null, currency: cart?.totals?.subTotal?.currencyCode ?? currency, isSample, loading: hydrating, }; - }, [cart, config.currencyCode, hydrating, isSample, sampleItems]); + }, [cart, config.currencyCode, hydrating, isSample, locale, sampleItems]); } From f4256d4352a77a9fa7dd9cec3cc901f0c74ea8fb Mon Sep 17 00:00:00 2001 From: Andrew Jaynes Date: Wed, 18 Nov 2026 19:38:08 -0700 Subject: [PATCH 08/17] fix(commerce-server): map order-api BAD_USER_INPUT to 400, not 502 order-api reports its own input validation (catalog option min/max, the TEXT/NUMBER single-value rule, a SKU with no price, etc.) as a BAD_USER_INPUT GraphQL error code on addLineItemBySkuId and addDraftOrder. The shopper can't have known a catalog-side rule in advance, but every cart route still answered this the same as a true upstream outage: a generic 502 internal_error. Add a classifyCartUpstreamError rule matching BAD_USER_INPUT and mapping it to InvalidRequestError (400), reused across all existing saved-cart routes. POST /cart had no classifier at all (its "no existing cart to miss" note in classifyCartUpstreamError excludes it from that one), so give it its own classifyCartCreationUpstreamError for just this rule. --- .../src/lib/commerce/upstream-errors.ts | 28 +++++++++++- packages/commerce-server/src/router.test.ts | 43 +++++++++++++++++++ .../src/server/api/commerce/cart/POST.ts | 5 ++- 3 files changed, 74 insertions(+), 2 deletions(-) diff --git a/packages/commerce-server/src/lib/commerce/upstream-errors.ts b/packages/commerce-server/src/lib/commerce/upstream-errors.ts index 5d6dfe7b..fdb33868 100644 --- a/packages/commerce-server/src/lib/commerce/upstream-errors.ts +++ b/packages/commerce-server/src/lib/commerce/upstream-errors.ts @@ -7,7 +7,7 @@ * upstream errors stay 502; the server log carries their codes and statuses so new rules can * be derived from real responses rather than guessed. */ -import { type CommerceError, NotFoundError, type UpstreamError } from './errors'; +import { type CommerceError, InvalidRequestError, NotFoundError, type UpstreamError } from './errors'; import { GraphQLErrorWithCodes } from './gql'; export function isCartNotFoundError(error: unknown): boolean { @@ -34,20 +34,46 @@ export function isCartNotFoundError(error: unknown): boolean { }); } +// order-api reports its own input validation (catalog option min/max, the TEXT/NUMBER +// single-value rule, a SKU with no price, etc.) with this code on addLineItemBySkuId and +// addDraftOrder. The browser can't have known the catalog-side rule in advance, so this is a +// 400, not a generic 502 — unlike a true upstream outage or an unexpected shape. +export function isBadUserInputError(error: unknown): boolean { + if (!(error instanceof GraphQLErrorWithCodes)) { + return false; + } + return error.errors.length > 0 && error.errors.every(({ code }) => code === 'BAD_USER_INPUT'); +} + interface UpstreamErrorRule { matches(error: UpstreamError): boolean; toError(error: UpstreamError): CommerceError; } +const BAD_USER_INPUT_RULE: UpstreamErrorRule = { + matches: isBadUserInputError, + toError: (error) => + new InvalidRequestError('The requested change is not valid for this cart or its items.', { + cause: error, + message: error.message, + }), +}; + const CART_UPSTREAM_ERROR_RULES: readonly UpstreamErrorRule[] = [ { // A completed (paid) draft is reported the same way, so this is "no longer a usable cart". matches: isCartNotFoundError, toError: (error) => new NotFoundError('Cart not found', { cause: error }), }, + BAD_USER_INPUT_RULE, ]; /** For routes acting on an existing saved cart (`/cart/:id`); creating a cart has none to miss. */ export function classifyCartUpstreamError(error: UpstreamError): CommerceError { return CART_UPSTREAM_ERROR_RULES.find((rule) => rule.matches(error))?.toError(error) ?? error; } + +/** For `POST /cart`: no existing cart to report missing, but addDraftOrder/addLineItemBySkuId can still reject input. */ +export function classifyCartCreationUpstreamError(error: UpstreamError): CommerceError { + return BAD_USER_INPUT_RULE.matches(error) ? BAD_USER_INPUT_RULE.toError(error) : error; +} diff --git a/packages/commerce-server/src/router.test.ts b/packages/commerce-server/src/router.test.ts index c5e7e282..33b16e09 100644 --- a/packages/commerce-server/src/router.test.ts +++ b/packages/commerce-server/src/router.test.ts @@ -578,6 +578,49 @@ describe('Commerce scoped routes', () => { expect(gqlRequest).not.toHaveBeenCalled(); }); + it('reports order-api BAD_USER_INPUT on addLineItemBySkuId as 400, not 502', async (): Promise => { + const res = response(); + vi.mocked(gqlRequest).mockRejectedValueOnce( + new GraphQLErrorWithCodes([{ code: 'BAD_USER_INPUT', message: 'SKU has no price' }]), + ); + await addItem( + { + headers: {}, + params: { id: 'cart-1' }, + body: { skuId: 'sku-1', name: 'Product', quantity: 1 }, + } as unknown as Request, + res as unknown as Response, + ); + expect(res.status).toHaveBeenCalledWith(400); + expect(res.json).toHaveBeenCalledWith({ + error: 'The requested change is not valid for this cart or its items.', + code: 'invalid_request', + requestId: expect.any(String), + }); + }); + + it('reports order-api BAD_USER_INPUT on cart creation as 400, not 502', async (): Promise => { + const res = response(); + vi.mocked(gqlRequest) + .mockResolvedValueOnce({ addDraftOrder: { id: 'cart-1' } }) + .mockRejectedValueOnce( + new GraphQLErrorWithCodes([{ code: 'BAD_USER_INPUT', message: 'SKU has no price' }]), + ); + await createCart( + { + headers: {}, + body: { lineItems: [{ skuId: 'sku-1', name: 'Product', quantity: 1 }] }, + } as unknown as Request, + res as unknown as Response, + ); + expect(res.status).toHaveBeenCalledWith(400); + expect(res.json).toHaveBeenCalledWith({ + error: 'The requested change is not valid for this cart or its items.', + code: 'invalid_request', + requestId: expect.any(String), + }); + }); + const scopedRequest = { headers: {}, query: {}, diff --git a/packages/commerce-server/src/server/api/commerce/cart/POST.ts b/packages/commerce-server/src/server/api/commerce/cart/POST.ts index 976e6a37..1d1dc836 100644 --- a/packages/commerce-server/src/server/api/commerce/cart/POST.ts +++ b/packages/commerce-server/src/server/api/commerce/cart/POST.ts @@ -44,6 +44,7 @@ import { getCartOrderQuery, orderStorefrontEndpoint, } from '@/lib/commerce/order-subgraph'; +import { classifyCartCreationUpstreamError } from '@/lib/commerce/upstream-errors'; const addCartOrderMutation = ` mutation AddCartOrder($input: AddDraftOrderInput!) { @@ -139,4 +140,6 @@ async function createCart(req: Request, res: Response): Promise { res.status(201).json({ cart: hydrated.orderById ?? null }); } -export default commerceRoute('Failed to create cart', createCart); +export default commerceRoute('Failed to create cart', createCart, { + classifyUpstreamError: classifyCartCreationUpstreamError, +}); From 8a6552eda718d42851539651fb354e25325a6ca3 Mon Sep 17 00:00:00 2001 From: Andrew Jaynes Date: Wed, 18 Nov 2026 20:28:08 -0700 Subject: [PATCH 09/17] docs(commerce-server): document order-api's same-SKU merge limitation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit order-api's findMatchingLineItem only treats an addLineItemBySkuId call as a new line when details.selectedAddons is present; it ignores metafields and details.productAssetUrl entirely. So two adds of the same skuId that differ only by metafields or productAssetUrl, with no selectedAddons on either, merge into one line in order-api, and buildLineItemFromSku replaces the first add's details/metafields with the second's rather than merging them — the first customization is silently lost. This is order-api behavior, not something this repo's route code can fix. Document it on AddToCartItemInput so a caller needing metafield-only or image-only customizations to stay on distinct lines knows to also include a distinguishing selectedAddons entry, and add a test pinning what this route actually sends (two independent mutation calls, each with its own metafields) so the limitation is visible rather than silently assumed. --- .../src/lib/commerce/order-subgraph.ts | 10 +++++ packages/commerce-server/src/router.test.ts | 37 +++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/packages/commerce-server/src/lib/commerce/order-subgraph.ts b/packages/commerce-server/src/lib/commerce/order-subgraph.ts index f2736956..77c188e8 100644 --- a/packages/commerce-server/src/lib/commerce/order-subgraph.ts +++ b/packages/commerce-server/src/lib/commerce/order-subgraph.ts @@ -317,6 +317,16 @@ export interface AddToCartMetafieldInput { value: string; } +// KNOWN LIMITATION (order-api behavior, not this file's): adding the same skuId twice produces +// two distinct line items only when at least one of the two adds includes `details.selectedAddons`. +// order-api's line-matching (`findMatchingLineItem`) looks at `selectedAddons` alone — it ignores +// `details.productAssetUrl` and `metafields` entirely. So two adds of the same skuId that differ +// only by `metafields` or `productAssetUrl`, with no `selectedAddons` on either, merge into one +// line: the quantities combine, and the second add's `details`/`metafields` silently overwrite the +// first's rather than merging with them (`buildLineItemFromSku` spreads the stored line and then +// replaces both fields wholesale). A caller that needs metafield-only or image-only customizations +// to stay on distinct lines must also include a distinguishing `selectedAddons` entry. +// Tracked as a follow-up against order-api; see `createFromSkuId.ts`'s own design-doc link. export interface AddToCartItemInput { skuId: string; name: string; diff --git a/packages/commerce-server/src/router.test.ts b/packages/commerce-server/src/router.test.ts index 33b16e09..3f7c8468 100644 --- a/packages/commerce-server/src/router.test.ts +++ b/packages/commerce-server/src/router.test.ts @@ -432,6 +432,43 @@ describe('Commerce scoped routes', () => { }); }); + it('sends two metafield-only customizations of the same SKU as two independent mutation calls', async (): Promise => { + // This route always issues one addLineItemBySkuId call per add-item request, each carrying + // its own distinct metafields. Known limitation (order-api behavior, not this route's): when + // neither add includes `details.selectedAddons`, order-api's own line-matching merges the two + // into a single line and the second add's details/metafields overwrite the first's, rather + // than this route's two calls producing two lines. See the KNOWN LIMITATION comment on + // AddToCartItemInput in order-subgraph.ts. + vi.mocked(gqlRequest) + .mockResolvedValueOnce({ addLineItemBySkuId: { id: 'item-1' } }) + .mockResolvedValueOnce({ orderById: { id: 'cart-1', lineItems: [] } }) + .mockResolvedValueOnce({ addLineItemBySkuId: { id: 'item-2' } }) + .mockResolvedValueOnce({ orderById: { id: 'cart-1', lineItems: [] } }); + const res = response(); + await addItem( + { + headers: {}, + params: { id: 'cart-1' }, + body: { skuId: 'sku-1', name: 'Mug', quantity: 1, metafields: [{ key: 'designId', value: 'A' }] }, + } as unknown as Request, + res as unknown as Response, + ); + await addItem( + { + headers: {}, + params: { id: 'cart-1' }, + body: { skuId: 'sku-1', name: 'Mug', quantity: 1, metafields: [{ key: 'designId', value: 'B' }] }, + } as unknown as Request, + res as unknown as Response, + ); + expect(vi.mocked(gqlRequest).mock.calls[0]?.[0].variables).toEqual({ + input: expect.objectContaining({ metafields: [{ key: 'designId', value: 'A', type: 'JSON' }] }), + }); + expect(vi.mocked(gqlRequest).mock.calls[2]?.[0].variables).toEqual({ + input: expect.objectContaining({ metafields: [{ key: 'designId', value: 'B', type: 'JSON' }] }), + }); + }); + it.each([ ['http://cdn.example.com/design.png', 'non-https productAssetUrl'], [`https://cdn.example.com/${'a'.repeat(2049)}.png`, 'oversized productAssetUrl'], From b52c9b8f5c0607786fdeb14c1248442a0e9cb742 Mon Sep 17 00:00:00 2001 From: Andrew Jaynes Date: Wed, 18 Nov 2026 21:13:59 -0700 Subject: [PATCH 10/17] fix(commerce-storefront): stop addItem from forwarding the whole caller object addItem(item) passed item straight through to addToCart(), so a caller spreading a larger object (e.g. addItem({ ...product, skuId, name, quantity })) now serialized every other property on product into the cart POST body. order-api rejects unknown fields on its strict schema, so this surfaced as a 502 instead of a clean validation error. Pick only skuId, name, quantity, details, and metafields before calling addToCart, the same allowlist AddToCartButton already applies. --- .../src/cart-parts.test.tsx | 27 +++++++++++++++++++ .../src/commerce-provider.tsx | 12 ++++++++- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/packages/commerce-storefront/src/cart-parts.test.tsx b/packages/commerce-storefront/src/cart-parts.test.tsx index c6204afd..7822a16c 100644 --- a/packages/commerce-storefront/src/cart-parts.test.tsx +++ b/packages/commerce-storefront/src/cart-parts.test.tsx @@ -602,6 +602,33 @@ describe('composable cart', () => { }); }); + it('drops extra properties from a spread object passed to addItem', async () => { + const fetchMock = mockStore(); + function CustomAdd(): ReactElement { + const { addItem } = useCommerce(); + const product = { + id: 'sku-mug', + description: 'A mug', + price: 1200, + mediaUrl: 'https://cdn.test/mug.png', + }; + return ( + + ); + } + render(app()); + await userEvent.click(screen.getByRole('button', { name: 'Add from product card' })); + await waitFor(() => expect(fetchMock).toHaveBeenCalled()); + const itemsCall = fetchMock.mock.calls.find(([input]) => String(input).includes('/items')); + const body = JSON.parse(String(itemsCall?.[1]?.body)); + expect(body).toEqual({ skuId: 'sku-mug', name: 'Mug', quantity: 1 }); + }); + it('surfaces selectedAddons in useCart() options alongside selectedOptions', async () => { localStorage.setItem(storageKey, 'cart-1'); vi.stubGlobal( diff --git a/packages/commerce-storefront/src/commerce-provider.tsx b/packages/commerce-storefront/src/commerce-provider.tsx index b6980048..81fc8d40 100644 --- a/packages/commerce-storefront/src/commerce-provider.tsx +++ b/packages/commerce-storefront/src/commerce-provider.tsx @@ -691,7 +691,17 @@ function BoundCommerceProvider({ headers.set('X-Commerce-Scope', config.cartScope); return checkedFetch(input, { ...init, headers }); }; - const result: CartResponse = await addToCart(id.current, item, fetchCart); + // Pick only the supported fields: a caller spreading a larger object (e.g. + // addItem({ ...product, skuId, name, quantity })) must not forward the rest of it — + // order-api rejects unknown fields, which would otherwise surface as a 502. + const payload: AddToCartItemInput = { + skuId: item.skuId, + name: item.name, + quantity: item.quantity, + ...(item.details ? { details: item.details } : {}), + ...(item.metafields ? { metafields: item.metafields } : {}), + }; + const result: CartResponse = await addToCart(id.current, payload, fetchCart); if (!result.cart?.id || !result.cart.lineItems?.length) throw new StorefrontError('addReturnedNoCart'); if (!isActive()) return; commit(result.cart); From c43a61265bf1ad1537f0657efe64ef797d78d76e Mon Sep 17 00:00:00 2001 From: Andrew Jaynes Date: Wed, 18 Nov 2026 21:19:16 -0700 Subject: [PATCH 11/17] fix(commerce-server): add a single parseCartItemInput for both cart routes Both cart/POST.ts and cart/[id]/items/POST.ts read the required fields off the untyped request body by hand, then cast the rest of the body straight to AddToCartItemInput before calling assertValidCartItemInput separately. The cast was a type-only annotation with no runtime filtering, so a body carrying extra properties (or a malformed one that assertValidCartItemInput didn't happen to check) had no single place guaranteeing it was shaped and allowlisted before use, and the two routes' required-field checks had already drifted into slightly different messages. Add parseCartItemInput(body) in order-subgraph.ts: validates skuId/name/ quantity, allowlists exactly the known fields (skuId, name, quantity, details, metafields), and runs assertValidCartItemInput, returning a trusted AddToCartItemInput. Both routes now call this once instead of hand-rolling their own field checks and casting the remainder. --- .../src/lib/commerce/order-subgraph.ts | 29 ++++++++ packages/commerce-server/src/router.test.ts | 74 +++++++++++++++++++ .../src/server/api/commerce/cart/POST.ts | 26 ++----- .../api/commerce/cart/[id]/items/POST.ts | 11 +-- 4 files changed, 113 insertions(+), 27 deletions(-) diff --git a/packages/commerce-server/src/lib/commerce/order-subgraph.ts b/packages/commerce-server/src/lib/commerce/order-subgraph.ts index 77c188e8..7bdd9b65 100644 --- a/packages/commerce-server/src/lib/commerce/order-subgraph.ts +++ b/packages/commerce-server/src/lib/commerce/order-subgraph.ts @@ -430,6 +430,35 @@ export function assertValidCartItemInput(item: AddToCartItemInput): void { } } +// The single place a cart-item request body is turned into a trusted AddToCartItemInput. Reads +// only the known top-level fields off the untyped body — any other property the client sent +// (e.g. a spread product object) is dropped here rather than riding along to order-api, which +// would otherwise reject it as an unknown field and surface as a 502 instead of this 400. +export function parseCartItemInput(body: unknown): AddToCartItemInput { + if (typeof body !== 'object' || body === null) { + throw new InvalidRequestError('Request body must be an object'); + } + const candidate = body as Partial; + if (!candidate.skuId || typeof candidate.skuId !== 'string') { + throw new InvalidRequestError('skuId must be a non-empty string'); + } + if (!candidate.name || typeof candidate.name !== 'string') { + throw new InvalidRequestError('name must be a non-empty string'); + } + if (typeof candidate.quantity !== 'number') { + throw new InvalidRequestError('quantity must be a number'); + } + const item: AddToCartItemInput = { + skuId: candidate.skuId, + name: candidate.name, + quantity: candidate.quantity, + ...(candidate.details !== undefined ? { details: candidate.details } : {}), + ...(candidate.metafields !== undefined ? { metafields: candidate.metafields } : {}), + }; + assertValidCartItemInput(item); + return item; +} + export interface CartSummaryTotals { itemCount: number; currencyCode: string; diff --git a/packages/commerce-server/src/router.test.ts b/packages/commerce-server/src/router.test.ts index 3f7c8468..5cd2610a 100644 --- a/packages/commerce-server/src/router.test.ts +++ b/packages/commerce-server/src/router.test.ts @@ -469,6 +469,80 @@ describe('Commerce scoped routes', () => { }); }); + it('drops unknown request body properties before the addLineItemBySkuId mutation', async (): Promise => { + vi.mocked(gqlRequest) + .mockResolvedValueOnce({ addLineItemBySkuId: { id: 'item-1' } }) + .mockResolvedValueOnce({ orderById: { id: 'cart-1', lineItems: [] } }); + const res = response(); + await addItem( + { + headers: {}, + params: { id: 'cart-1' }, + body: { + skuId: 'sku-1', + name: 'Product', + quantity: 1, + description: 'A product description', + price: 1200, + mediaUrl: 'https://cdn.example.com/product.png', + }, + } as unknown as Request, + res as unknown as Response, + ); + expect(vi.mocked(gqlRequest).mock.calls[0]?.[0].variables).toEqual({ + input: { + orderId: 'cart-1', + skuId: 'sku-1', + name: 'Product', + quantity: 1, + fulfillmentMode: 'NONE', + status: 'DRAFT', + }, + }); + }); + + it('drops unknown lineItem properties before creating the cart', async (): Promise => { + vi.mocked(gqlRequest) + .mockResolvedValueOnce({ addDraftOrder: { id: 'cart-1' } }) + .mockResolvedValueOnce({ addLineItemBySkuId: { id: 'item-1' } }) + .mockResolvedValueOnce({ orderById: { id: 'cart-1', lineItems: [] } }); + const res = response(); + await createCart( + { + headers: {}, + body: { + lineItems: [{ skuId: 'sku-1', name: 'Product', quantity: 1, description: 'A product description' }], + }, + } as unknown as Request, + res as unknown as Response, + ); + expect(vi.mocked(gqlRequest).mock.calls[1]?.[0].variables).toEqual({ + input: { + orderId: 'cart-1', + skuId: 'sku-1', + name: 'Product', + quantity: 1, + fulfillmentMode: 'NONE', + status: 'DRAFT', + }, + }); + }); + + it.each([ + [{ name: 'Product', quantity: 1 }, 'missing skuId'], + [{ skuId: 'sku-1', quantity: 1 }, 'missing name'], + [{ skuId: 'sku-1', name: 'Product' }, 'missing quantity'], + [{ skuId: 'sku-1', name: 'Product', quantity: 'one' }, 'non-numeric quantity'], + ])('rejects an add-item body with %j (%s)', async (body, _description): Promise => { + const res = response(); + await addItem( + { headers: {}, params: { id: 'cart-1' }, body } as unknown as Request, + res as unknown as Response, + ); + expect(res.status).toHaveBeenCalledWith(400); + expect(gqlRequest).not.toHaveBeenCalled(); + }); + it.each([ ['http://cdn.example.com/design.png', 'non-https productAssetUrl'], [`https://cdn.example.com/${'a'.repeat(2049)}.png`, 'oversized productAssetUrl'], diff --git a/packages/commerce-server/src/server/api/commerce/cart/POST.ts b/packages/commerce-server/src/server/api/commerce/cart/POST.ts index 1d1dc836..f3475876 100644 --- a/packages/commerce-server/src/server/api/commerce/cart/POST.ts +++ b/packages/commerce-server/src/server/api/commerce/cart/POST.ts @@ -28,21 +28,20 @@ import type { Request, Response } from 'express'; import { assertCommerceCartScope } from '@/lib/commerce/cart-scope'; import { commerceRoute } from '@/lib/commerce/commerce-route'; import { type CommerceConfig, readCommerceConfigForResponse } from '@/lib/commerce/config'; -import { InvalidRequestError, UpstreamError } from '@/lib/commerce/errors'; +import { UpstreamError } from '@/lib/commerce/errors'; import { gqlRequest, storefrontHeaders } from '@/lib/commerce/gql'; import { type AddCartOrderResult, type AddCartOrderVariables, type AddLineItemBySkuIdResult, type AddLineItemBySkuIdVariables, - type AddToCartItemInput, - assertValidCartItemInput, buildAddLineItemBySkuIdInput, buildEmptyCartOrderInput, type GetCartOrderResult, type GetCartOrderVariables, getCartOrderQuery, orderStorefrontEndpoint, + parseCartItemInput, } from '@/lib/commerce/order-subgraph'; import { classifyCartCreationUpstreamError } from '@/lib/commerce/upstream-errors'; @@ -64,26 +63,17 @@ const addLineItemBySkuIdMutation = ` interface CreateCartBody { currencyCode?: string; - lineItems?: AddToCartItemInput[]; + lineItems?: unknown[]; } async function createCart(req: Request, res: Response): Promise { const body = (req.body ?? {}) as CreateCartBody; - const initialItems = Array.isArray(body.lineItems) ? body.lineItems : []; + const rawItems = Array.isArray(body.lineItems) ? body.lineItems : []; - // Validate all items BEFORE creating the cart so a bad payload can't - // produce an orphaned cart (cart created, item add fails, client never - // gets the id). Mirrors the validation in POST /api/commerce/cart/:id/items. - // assertValidCartItemInput also runs later inside buildAddLineItemBySkuIdInput, - // but by then the cart already exists — it must run here too, before creation. - for (const item of initialItems) { - if (!item.skuId || !item.name || typeof item.quantity !== 'number') { - throw new InvalidRequestError( - 'Each lineItem must have skuId, a non-empty name, and a numeric quantity', - ); - } - assertValidCartItemInput(item); - } + // Parse and validate every item BEFORE creating the cart so a bad payload can't produce an + // orphaned cart (cart created, item add fails, client never gets the id). parseCartItemInput + // also allowlists each item to its known fields, dropping anything else the client sent. + const initialItems = rawItems.map((item) => parseCartItemInput(item)); const config: CommerceConfig = readCommerceConfigForResponse(res); assertCommerceCartScope(req, config); diff --git a/packages/commerce-server/src/server/api/commerce/cart/[id]/items/POST.ts b/packages/commerce-server/src/server/api/commerce/cart/[id]/items/POST.ts index 13d4677e..8c85f91b 100644 --- a/packages/commerce-server/src/server/api/commerce/cart/[id]/items/POST.ts +++ b/packages/commerce-server/src/server/api/commerce/cart/[id]/items/POST.ts @@ -23,13 +23,12 @@ import { gqlRequest, storefrontHeaders } from '@/lib/commerce/gql'; import { type AddLineItemBySkuIdResult, type AddLineItemBySkuIdVariables, - type AddToCartItemInput, - assertValidCartItemInput, buildAddLineItemBySkuIdInput, type GetCartOrderResult, type GetCartOrderVariables, getCartOrderQuery, orderStorefrontEndpoint, + parseCartItemInput, } from '@/lib/commerce/order-subgraph'; import { classifyCartUpstreamError } from '@/lib/commerce/upstream-errors'; @@ -47,13 +46,7 @@ async function addLineItem(req: Request, res: Response): Promise { throw new InvalidRequestError('Missing cart id'); } - const body = (req.body ?? {}) as Partial; - if (!body.skuId || !body.name || typeof body.quantity !== 'number') { - throw new InvalidRequestError('Missing required fields: skuId, name, quantity'); - } - // `body` is untyped JSON past this point — validate its shape before trusting the cast below. - const item = body as AddToCartItemInput; - assertValidCartItemInput(item); + const item = parseCartItemInput(req.body); const config: CommerceConfig = readCommerceConfigForResponse(res); assertCommerceCartScope(req, config); From 2d84c4a2d3f1d49249e576241d9ba685056e06ee Mon Sep 17 00:00:00 2001 From: Andrew Jaynes Date: Thu, 19 Nov 2026 09:20:23 -0700 Subject: [PATCH 12/17] fix(commerce-server): scope BAD_USER_INPUT mapping to the add-item route only MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adding BAD_USER_INPUT_RULE to the shared CART_UPSTREAM_ERROR_RULES applied it to every route using classifyCartUpstreamError — cart GET, discounts POST, and item PATCH/DELETE — not just add-item, which is the only path this PR actually exercises for that code. A promo code or other BAD_USER_INPUT on those other routes would now have silently become a 400 with an add-item-flavored message, untested. Split it into a dedicated classifyAddItemUpstreamError (cart-not-found + BAD_USER_INPUT) used only by cart/[id]/items/POST.ts, and revert classifyCartUpstreamError back to just the cart-not-found rule for the other routes. classifyCartCreationUpstreamError (POST /cart) already only applied BAD_USER_INPUT and is unaffected. --- .../src/lib/commerce/upstream-errors.ts | 25 ++++++++++++---- packages/commerce-server/src/router.test.ts | 30 +++++++++++++++++++ .../api/commerce/cart/[id]/items/POST.ts | 4 +-- 3 files changed, 51 insertions(+), 8 deletions(-) diff --git a/packages/commerce-server/src/lib/commerce/upstream-errors.ts b/packages/commerce-server/src/lib/commerce/upstream-errors.ts index fdb33868..b64bf3d9 100644 --- a/packages/commerce-server/src/lib/commerce/upstream-errors.ts +++ b/packages/commerce-server/src/lib/commerce/upstream-errors.ts @@ -59,12 +59,20 @@ const BAD_USER_INPUT_RULE: UpstreamErrorRule = { }), }; -const CART_UPSTREAM_ERROR_RULES: readonly UpstreamErrorRule[] = [ - { - // A completed (paid) draft is reported the same way, so this is "no longer a usable cart". - matches: isCartNotFoundError, - toError: (error) => new NotFoundError('Cart not found', { cause: error }), - }, +const CART_NOT_FOUND_RULE: UpstreamErrorRule = { + // A completed (paid) draft is reported the same way, so this is "no longer a usable cart". + matches: isCartNotFoundError, + toError: (error) => new NotFoundError('Cart not found', { cause: error }), +}; + +const CART_UPSTREAM_ERROR_RULES: readonly UpstreamErrorRule[] = [CART_NOT_FOUND_RULE]; + +// Add-item is the only route BAD_USER_INPUT is mapped for today: it's the one order-api path +// this PR actually exercises for that code. Applying it to every classifyCartUpstreamError +// route (GET, discounts, PATCH, DELETE) would be untested scope creep — add it to +// CART_UPSTREAM_ERROR_RULES too only once those routes' BAD_USER_INPUT cases are understood. +const ADD_ITEM_UPSTREAM_ERROR_RULES: readonly UpstreamErrorRule[] = [ + CART_NOT_FOUND_RULE, BAD_USER_INPUT_RULE, ]; @@ -73,6 +81,11 @@ export function classifyCartUpstreamError(error: UpstreamError): CommerceError { return CART_UPSTREAM_ERROR_RULES.find((rule) => rule.matches(error))?.toError(error) ?? error; } +/** For `POST /cart/:id/items`: an existing cart can still go missing, and the new item can still fail validation. */ +export function classifyAddItemUpstreamError(error: UpstreamError): CommerceError { + return ADD_ITEM_UPSTREAM_ERROR_RULES.find((rule) => rule.matches(error))?.toError(error) ?? error; +} + /** For `POST /cart`: no existing cart to report missing, but addDraftOrder/addLineItemBySkuId can still reject input. */ export function classifyCartCreationUpstreamError(error: UpstreamError): CommerceError { return BAD_USER_INPUT_RULE.matches(error) ? BAD_USER_INPUT_RULE.toError(error) : error; diff --git a/packages/commerce-server/src/router.test.ts b/packages/commerce-server/src/router.test.ts index 5cd2610a..3f8ea3a5 100644 --- a/packages/commerce-server/src/router.test.ts +++ b/packages/commerce-server/src/router.test.ts @@ -732,6 +732,36 @@ describe('Commerce scoped routes', () => { }); }); + it.each([ + ['read', readCart, 'Failed to load cart'], + ['update', updateItem, 'Failed to update line item'], + ['remove', deleteItem, 'Failed to delete line item'], + ['discount', applyDiscount, 'Failed to apply discount codes'], + ] as const)( + 'does not map order-api BAD_USER_INPUT to 400 on %s — stays a generic 502', + async (_name, handler, label): Promise => { + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}); + const res = response(); + const error = new GraphQLErrorWithCodes([{ code: 'BAD_USER_INPUT', message: 'Invalid discount code' }]); + vi.mocked(gqlRequest).mockRejectedValueOnce(error); + await handler( + { + headers: {}, + params: { id: 'cart-1', itemId: 'item-1' }, + body: { discountCodes: ['PROMO'] }, + } as unknown as Request, + res as unknown as Response, + ); + expect(res.status).toHaveBeenCalledWith(502); + expect(res.json).toHaveBeenCalledWith({ + error: label, + code: 'upstream_error', + requestId: expect.any(String), + }); + consoleError.mockRestore(); + }, + ); + const scopedRequest = { headers: {}, query: {}, diff --git a/packages/commerce-server/src/server/api/commerce/cart/[id]/items/POST.ts b/packages/commerce-server/src/server/api/commerce/cart/[id]/items/POST.ts index 8c85f91b..600ee184 100644 --- a/packages/commerce-server/src/server/api/commerce/cart/[id]/items/POST.ts +++ b/packages/commerce-server/src/server/api/commerce/cart/[id]/items/POST.ts @@ -30,7 +30,7 @@ import { orderStorefrontEndpoint, parseCartItemInput, } from '@/lib/commerce/order-subgraph'; -import { classifyCartUpstreamError } from '@/lib/commerce/upstream-errors'; +import { classifyAddItemUpstreamError } from '@/lib/commerce/upstream-errors'; const addLineItemBySkuIdMutation = ` mutation AddLineItemBySkuId($input: AddLineItemInput!) { @@ -75,5 +75,5 @@ async function addLineItem(req: Request, res: Response): Promise { } export default commerceRoute('Failed to add line item', addLineItem, { - classifyUpstreamError: classifyCartUpstreamError, + classifyUpstreamError: classifyAddItemUpstreamError, }); From 6888f2882a3e486e1b0c3bbc2926100f2a35b519 Mon Sep 17 00:00:00 2001 From: Andrew Jaynes Date: Thu, 19 Nov 2026 09:22:42 -0700 Subject: [PATCH 13/17] fix(commerce-server): allowlist details/metafields fields and drop the double validation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit parseCartItemInput forwarded candidate.details wholesale, so unknown keys inside it (sku, unitOfMeasure, or extra properties on an addon or its values) still reached order-api — cosmetic now that BAD_USER_INPUT maps to 400, but incomplete next to the explicit metafields pick already in place. Validate the candidate first, then rebuild details by picking only productAssetUrl and selectedAddons (each addon narrowed to optionId and values: [{ inputValue }]), the same way metafields is narrowed to key/value. Validating before picking also means every field the pick reads is already known-valid, so buildAddLineItemBySkuIdInput's own assertValidCartItemInput call is now pure duplication for both of its only two callers — both already go through parseCartItemInput. Remove it and document the precondition on the function instead. --- .../src/lib/commerce/order-subgraph.ts | 32 ++++++++++++--- packages/commerce-server/src/router.test.ts | 41 +++++++++++++++++++ 2 files changed, 67 insertions(+), 6 deletions(-) diff --git a/packages/commerce-server/src/lib/commerce/order-subgraph.ts b/packages/commerce-server/src/lib/commerce/order-subgraph.ts index 7bdd9b65..d7953c28 100644 --- a/packages/commerce-server/src/lib/commerce/order-subgraph.ts +++ b/packages/commerce-server/src/lib/commerce/order-subgraph.ts @@ -448,15 +448,34 @@ export function parseCartItemInput(body: unknown): AddToCartItemInput { if (typeof candidate.quantity !== 'number') { throw new InvalidRequestError('quantity must be a number'); } - const item: AddToCartItemInput = { + // Validate before picking: every field the pick below reads has already been shape-checked + // here, so it can be destructured directly without repeating the same guards. + assertValidCartItemInput(candidate as AddToCartItemInput); + return { skuId: candidate.skuId, name: candidate.name, quantity: candidate.quantity, - ...(candidate.details !== undefined ? { details: candidate.details } : {}), - ...(candidate.metafields !== undefined ? { metafields: candidate.metafields } : {}), + ...(candidate.details !== undefined + ? { + details: { + ...(candidate.details.productAssetUrl !== undefined + ? { productAssetUrl: candidate.details.productAssetUrl } + : {}), + ...(candidate.details.selectedAddons !== undefined + ? { + selectedAddons: candidate.details.selectedAddons.map((addon) => ({ + optionId: addon.optionId, + values: addon.values.map((value) => ({ inputValue: value.inputValue })), + })), + } + : {}), + }, + } + : {}), + ...(candidate.metafields !== undefined + ? { metafields: candidate.metafields.map(({ key, value }) => ({ key, value })) } + : {}), }; - assertValidCartItemInput(item); - return item; } export interface CartSummaryTotals { @@ -500,11 +519,12 @@ export function buildEmptyCartOrderInput({ }; } +// Caller must have already validated `item` (e.g. via `parseCartItemInput`) — this function +// does not re-validate. export function buildAddLineItemBySkuIdInput( orderId: string, item: AddToCartItemInput, ): AddLineItemBySkuIdInput { - assertValidCartItemInput(item); return { orderId, skuId: item.skuId, diff --git a/packages/commerce-server/src/router.test.ts b/packages/commerce-server/src/router.test.ts index 3f8ea3a5..8faa296c 100644 --- a/packages/commerce-server/src/router.test.ts +++ b/packages/commerce-server/src/router.test.ts @@ -501,6 +501,47 @@ describe('Commerce scoped routes', () => { }); }); + it('drops unknown properties inside details and each selectedAddons value', async (): Promise => { + vi.mocked(gqlRequest) + .mockResolvedValueOnce({ addLineItemBySkuId: { id: 'item-1' } }) + .mockResolvedValueOnce({ orderById: { id: 'cart-1', lineItems: [] } }); + const res = response(); + await addItem( + { + headers: {}, + params: { id: 'cart-1' }, + body: { + skuId: 'sku-1', + name: 'Product', + quantity: 1, + details: { + productAssetUrl: 'https://cdn.example.com/design.png', + sku: 'sneaky', + unitOfMeasure: 'each', + selectedAddons: [ + { + optionId: 'opt-1', + values: [{ inputValue: 'Custom design 123', optionValueId: 'sneaky-id' }], + extra: 'sneaky', + }, + ], + }, + metafields: [{ key: 'designId', value: 'design-123', type: 'NOT_JSON', extra: 'sneaky' }], + }, + } as unknown as Request, + res as unknown as Response, + ); + expect(vi.mocked(gqlRequest).mock.calls[0]?.[0].variables).toEqual({ + input: expect.objectContaining({ + details: { + productAssetUrl: 'https://cdn.example.com/design.png', + selectedAddons: [{ optionId: 'opt-1', values: [{ inputValue: 'Custom design 123' }] }], + }, + metafields: [{ key: 'designId', value: 'design-123', type: 'JSON' }], + }), + }); + }); + it('drops unknown lineItem properties before creating the cart', async (): Promise => { vi.mocked(gqlRequest) .mockResolvedValueOnce({ addDraftOrder: { id: 'cart-1' } }) From 3c95afbaa4e4bbd22908e9faa0149069b33f7e69 Mon Sep 17 00:00:00 2001 From: Andrew Jaynes Date: Thu, 19 Nov 2026 09:24:51 -0700 Subject: [PATCH 14/17] fix(commerce): drop metafields from the browser-facing cart shape MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cart reads returned every line-item metafield to the browser, including ones written by the merchant or other apps that have nothing to do with this storefront, to anyone holding a cart id. Metafields added here are a write-only mechanism (e.g. a designId reference) for the merchant's order, not a display surface — anything a shopper should see echoed back (engraving text, a selected addon) already has a home in details.selectedAddons, which still round-trips on read. Remove metafields from getCartOrderQuery's lineItems selection and the CartMetafield/CartLineItem.metafields read-side type in both order-subgraph.ts and the storefront's cart-model.ts. Add-to-cart can still send metafields; the browser just no longer reads them back. --- .../src/lib/commerce/order-subgraph.ts | 12 ------------ packages/commerce-storefront/src/cart-model.ts | 7 ------- 2 files changed, 19 deletions(-) diff --git a/packages/commerce-server/src/lib/commerce/order-subgraph.ts b/packages/commerce-server/src/lib/commerce/order-subgraph.ts index d7953c28..d9315cd4 100644 --- a/packages/commerce-server/src/lib/commerce/order-subgraph.ts +++ b/packages/commerce-server/src/lib/commerce/order-subgraph.ts @@ -95,12 +95,6 @@ export interface CartNote { createdAt?: string | null; } -export interface CartMetafield { - key?: string | null; - type?: string | null; - value?: string | null; -} - export interface CartLineItem { id?: string | null; name?: string | null; @@ -113,7 +107,6 @@ export interface CartLineItem { discounts?: CartDiscount[] | null; taxes?: CartTax[] | null; notes?: CartNote[] | null; - metafields?: CartMetafield[] | null; createdAt?: string | null; updatedAt?: string | null; } @@ -707,11 +700,6 @@ export const getCartOrderQuery = ` author authorType } - metafields { - key - type - value - } } totals { subTotal { diff --git a/packages/commerce-storefront/src/cart-model.ts b/packages/commerce-storefront/src/cart-model.ts index ae9ead01..c73ec255 100644 --- a/packages/commerce-storefront/src/cart-model.ts +++ b/packages/commerce-storefront/src/cart-model.ts @@ -77,12 +77,6 @@ export interface CartNote { createdAt?: string | null; } -export interface CartMetafield { - key?: string | null; - type?: string | null; - value?: string | null; -} - export interface CartLineItem { id?: string | null; name?: string | null; @@ -95,7 +89,6 @@ export interface CartLineItem { discounts?: CartDiscount[] | null; taxes?: CartTax[] | null; notes?: CartNote[] | null; - metafields?: CartMetafield[] | null; createdAt?: string | null; updatedAt?: string | null; } From 5d5a10db2a1a71dddc0771be04c42f1cfc07eecd Mon Sep 17 00:00:00 2001 From: Andrew Jaynes Date: Thu, 19 Nov 2026 09:28:58 -0700 Subject: [PATCH 15/17] fix(commerce-storefront): route the addon surcharge through the message catalog MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit useCart() built "(+$5.00)" with raw string interpolation and a manual cost.value > 0 ? '+' : '' ternary, bypassing messages.ts/fr-fr.ts entirely — every other package string goes through a message key, and the manual ternary never added a sign for a negative adjustment (it relied on Intl's default negative rendering, untested). Add addonValueWithCost: '{name} ({amount})' to messages.ts and fr-fr.ts (a pure interpolation template with no localizable wording, so it's exempted from messages.test.tsx's English/French identity check the same way skuOptionLabel already is). Format the signed amount with a small dedicated Intl.NumberFormat using signDisplay: 'exceptZero' instead of the manual ternary — kept separate from api.ts's shared money() cache since signDisplay is only needed on this path. --- .../src/cart-parts.test.tsx | 46 +++++++++++++++++++ .../commerce-storefront/src/cart-state.ts | 26 +++++++++-- .../commerce-storefront/src/locales/fr-fr.ts | 1 + .../commerce-storefront/src/messages.test.tsx | 3 +- packages/commerce-storefront/src/messages.ts | 1 + 5 files changed, 71 insertions(+), 6 deletions(-) diff --git a/packages/commerce-storefront/src/cart-parts.test.tsx b/packages/commerce-storefront/src/cart-parts.test.tsx index 7822a16c..6459ac61 100644 --- a/packages/commerce-storefront/src/cart-parts.test.tsx +++ b/packages/commerce-storefront/src/cart-parts.test.tsx @@ -719,6 +719,52 @@ describe('composable cart', () => { ); }); + it('shows a negative addon surcharge with a minus sign, not a double negative', async () => { + localStorage.setItem(storageKey, 'cart-1'); + vi.stubGlobal( + 'fetch', + vi.fn(async (input: RequestInfo | URL) => { + const url = new URL(String(input), 'https://host.test'); + if (url.pathname.endsWith('/config')) return response({ cartScope: 's', currencyCode: 'USD' }); + return response({ + cart: { + id: 'cart-1', + lineItems: [ + { + id: 'line-1', + name: 'Mug', + quantity: 1, + details: { + selectedAddons: [ + { + attribute: 'Size', + values: [{ name: 'Small', costAdjustment: { value: -200, currencyCode: 'USD' } }], + }, + ], + }, + totals: { subTotal: { value: 1000, currencyCode: 'USD' } }, + }, + ], + totals: { + subTotal: { value: 1000, currencyCode: 'USD' }, + total: { value: 1000, currencyCode: 'USD' }, + }, + }, + }); + }), + ); + function Options(): ReactElement { + const { items } = useCart(); + return {JSON.stringify(items[0]?.options ?? [])}; + } + render(app()); + await waitFor(() => + expect(screen.getByTestId('options')).toHaveTextContent( + JSON.stringify([{ attribute: 'Size', values: ['Small (-$2.00)'] }]), + ), + ); + }); + it('renders the packaged drawer from CommerceStorefront with dividers between lines', async () => { mockStore(); render( diff --git a/packages/commerce-storefront/src/cart-state.ts b/packages/commerce-storefront/src/cart-state.ts index f58ac853..8f713f31 100644 --- a/packages/commerce-storefront/src/cart-state.ts +++ b/packages/commerce-storefront/src/cart-state.ts @@ -1,8 +1,23 @@ import { useMemo } from 'react'; -import { money } from './api'; -import { useCommerce } from './commerce-provider'; +import { useCommerce, useMessage } from './commerce-provider'; import { type SampleProduct, sampleCurrency, useSampleCart } from './sample-cart'; +// A dedicated formatter cache for signed addon-cost adjustments, separate from `api.ts`'s +// `money()` cache: `signDisplay` is only needed here, not for the much hotter plain-price path +// `money()`/`useMoney()` serve everywhere else, so it isn't worth widening that shared cache's +// key or public signature for this one case. +const signedCurrencyFormats = new Map(); +function formatSignedCost(value: number, currency: string, locale: string): string { + const key = `${locale}|${currency}`; + let format = signedCurrencyFormats.get(key); + if (!format) { + format = new Intl.NumberFormat(locale, { style: 'currency', currency, signDisplay: 'exceptZero' }); + signedCurrencyFormats.set(key, format); + } + const scale = 10 ** (format.resolvedOptions().maximumFractionDigits ?? 2); + return format.format(value / scale); +} + /** One cart line, for custom cart parts. */ export interface CartItemState { /** Empty when the server returned a line without an ID. Such a line cannot be changed or removed. */ @@ -33,6 +48,7 @@ export interface CartState { /** Read the cart from anywhere inside `CommerceProvider`, for example to build a custom cart button. */ export function useCart(): CartState { const { cart, config, connection, hydrating, locale } = useCommerce(); + const text = useMessage(); const sample = useSampleCart(); const isSample: boolean = connection === 'unbound'; const sampleItems = sample.items; @@ -80,8 +96,8 @@ export function useCart(): CartState { .map((value) => { const cost = value.costAdjustment; if (typeof cost?.value !== 'number' || cost.value === 0) return value.name as string; - const formatted = money(cost.value, cost.currencyCode ?? itemCurrency, locale); - return `${value.name} (${cost.value > 0 ? '+' : ''}${formatted})`; + const amount = formatSignedCost(cost.value, cost.currencyCode ?? itemCurrency, locale); + return text('addonValueWithCost', { name: value.name as string, amount }); }), })), ], @@ -96,5 +112,5 @@ export function useCart(): CartState { isSample, loading: hydrating, }; - }, [cart, config.currencyCode, hydrating, isSample, locale, sampleItems]); + }, [cart, config.currencyCode, hydrating, isSample, locale, sampleItems, text]); } diff --git a/packages/commerce-storefront/src/locales/fr-fr.ts b/packages/commerce-storefront/src/locales/fr-fr.ts index e992fa5e..049856eb 100644 --- a/packages/commerce-storefront/src/locales/fr-fr.ts +++ b/packages/commerce-storefront/src/locales/fr-fr.ts @@ -76,6 +76,7 @@ export const frFR: StorefrontMessages = { quantityPrefix: `Quantité${colon} `, remove: 'Retirer', itemOption: `{attribute}${colon} {values}`, + addonValueWithCost: '{name} ({amount})', cartEmpty: 'Votre panier est vide', cartEmptyHint: 'Ajoutez un article qui vous plaît et il apparaîtra ici.', sampleCartEmptyHint: "Ajoutez un produit d'exemple pour essayer le panier.", diff --git a/packages/commerce-storefront/src/messages.test.tsx b/packages/commerce-storefront/src/messages.test.tsx index 728c04af..405482e9 100644 --- a/packages/commerce-storefront/src/messages.test.tsx +++ b/packages/commerce-storefront/src/messages.test.tsx @@ -130,7 +130,8 @@ describe('formatMessage', () => { const keys = Object.keys(enUS) as StorefrontMessageKey[]; expect(Object.keys(frFR).sort()).toEqual(keys.sort()); for (const key of keys) { - if (key === 'skuOptionLabel') continue; + // Pure interpolation templates with no localizable wording — identical in every language. + if (key === 'skuOptionLabel' || key === 'addonValueWithCost') continue; expect.soft(frFR[key], key).not.toEqual(enUS[key]); } }); diff --git a/packages/commerce-storefront/src/messages.ts b/packages/commerce-storefront/src/messages.ts index 22e8cb7c..31098b03 100644 --- a/packages/commerce-storefront/src/messages.ts +++ b/packages/commerce-storefront/src/messages.ts @@ -65,6 +65,7 @@ const englishText = { quantityPrefix: 'Quantity: ', remove: 'Remove', itemOption: '{attribute}: {values}', + addonValueWithCost: '{name} ({amount})', cartEmpty: 'Your cart is empty', cartEmptyHint: 'Add something you love and it will show up here.', sampleCartEmptyHint: 'Add a sample product to try the cart.', From c8909c796f18617559ab66aa330f36100b68d555 Mon Sep 17 00:00:00 2001 From: Andrew Jaynes Date: Thu, 19 Nov 2026 09:30:27 -0700 Subject: [PATCH 16/17] docs(commerce-storefront): document the details/metafields contract on add-item server-api.md's endpoint table and cart-response description still showed the pre-widening three-field contract, with no mention of details, metafields, their limits, the https-only productAssetUrl rule, the unsupported LIST-option addon shape, or the same-SKU merge limitation that order-api's own line-matching has today. --- packages/commerce-storefront/docs/server-api.md | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/packages/commerce-storefront/docs/server-api.md b/packages/commerce-storefront/docs/server-api.md index d02cab5a..d5148f17 100644 --- a/packages/commerce-storefront/docs/server-api.md +++ b/packages/commerce-storefront/docs/server-api.md @@ -22,8 +22,8 @@ Server implementations can use GoDaddy Commerce APIs or their existing integrati | `GET /products/:id` | URI-encoded product ID | `{ skuGroup: SKUGroup \| null }` | | `GET /products/:id?attributeValues=blue&attributeValues=large` | Repeated selected attribute **names**, not IDs | `{ skuGroup: SKUGroup \| null }` with matching SKU connection | | `GET /cart/:id` | URI-encoded cart ID | `{ cart: CartOrder \| null }` | -| `POST /cart` | `{ lineItems: [{ skuId, name, quantity }] }` | `{ cart: CartOrder }` | -| `POST /cart/:id/items` | `{ skuId, name, quantity }` | `{ cart: CartOrder }` | +| `POST /cart` | `{ lineItems: [{ skuId, name, quantity, details?, metafields? }] }` | `{ cart: CartOrder }` | +| `POST /cart/:id/items` | `{ skuId, name, quantity, details?, metafields? }` | `{ cart: CartOrder }` | | `PATCH /cart/:id/items/:itemId` | `{ quantity }` | `{ cart: CartOrder }` | | `DELETE /cart/:id/items/:itemId` | No body | `{ cart: CartOrder }` | | `POST /cart/:id/discounts` | `{ discountCodes: string[] }` | `{ cart: CartOrder }` | @@ -96,7 +96,18 @@ A cart is a draft order. Return its `id`, complete `lineItems`, and authoritativ } ``` -Optional totals include `shippingTotal`, `taxTotal`, and `discountTotal`. Optional line details include `productAssetUrl` and `selectedOptions: [{ attribute, values: string[] }]`. The drawer shows supplied totals; it does not calculate authoritative prices from catalog values. A missing total disables checkout. +Optional totals include `shippingTotal`, `taxTotal`, and `discountTotal`. Optional line details include `productAssetUrl`, `selectedOptions: [{ attribute, values: string[] }]`, and `selectedAddons: [{ attribute, values: [{ name, costAdjustment? }] }]`. The drawer shows supplied totals; it does not calculate authoritative prices from catalog values. A missing total disables checkout. + +`metafields` on an add-item request are accepted and stored on the order, but are not returned on cart reads — the browser never sees any line item's metafields, whether written by this storefront, the merchant, or another app. Anything a shopper should see echoed back (a customization, a selected option) belongs in `details`, not `metafields`. + +### Customization fields on add-item requests + +`POST /cart` and `POST /cart/:id/items` accept an optional `details` and `metafields` alongside `skuId`, `name`, and `quantity`: + +- `details.productAssetUrl` must be an absolute `https://` URL (max 2048 characters). It is additive to the SKU's own catalog image, not a replacement for it at the catalog level — but it does take priority over the catalog image everywhere a line item's image is shown (the shopper's cart, the merchant's order view, emails, fulfillment/packing views), since it is meant for the shopper's own design or customization preview. +- `details.selectedAddons` is `[{ optionId, values: [{ inputValue }] }]` — only the shopper-typed TEXT/NUMBER catalog-option shape. A pre-defined LIST-option value (`{ optionValueId }`) is not supported by this contract and is rejected. Up to 20 addon entries per item; each `inputValue` up to 500 characters. +- `metafields` is `[{ key, value }]`, up to 10 entries per item, each value up to 2000 characters. The server always sends `type: "JSON"` to the upstream order system regardless of any `type` the client supplies. +- **Known limitation:** two add-item calls for the same `skuId` reliably produce two distinct cart lines only when at least one of them includes `details.selectedAddons`. If neither call includes `selectedAddons` — for example, two calls that differ only by `metafields` or `productAssetUrl` — they merge into a single line, and the second call's customization silently replaces the first's. ## Checkout boundary From 760c7470b7b9f54521e7b3f92e189b3ea316f123 Mon Sep 17 00:00:00 2001 From: Andrew Jaynes Date: Thu, 19 Nov 2026 12:50:03 -0700 Subject: [PATCH 17/17] docs(commerce-storefront): clarify productAssetUrl wording, cap the surcharge format cache MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit server-api.md described productAssetUrl as both "additive to the catalog image" and taking "priority over the catalog image everywhere" in the same sentence, which reads as contradictory. State plainly that it replaces the image for this line item only; the catalog itself is unchanged. Also cap the addon-surcharge Intl.NumberFormat cache added for the signDisplay fix, matching api.ts's currencyFormat eviction pattern — not a correctness issue (locale/currency pairs are few in practice), just consistency with the existing cache nearby. --- packages/commerce-storefront/docs/server-api.md | 2 +- packages/commerce-storefront/src/cart-state.ts | 8 +++++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/packages/commerce-storefront/docs/server-api.md b/packages/commerce-storefront/docs/server-api.md index d5148f17..74223fb0 100644 --- a/packages/commerce-storefront/docs/server-api.md +++ b/packages/commerce-storefront/docs/server-api.md @@ -104,7 +104,7 @@ Optional totals include `shippingTotal`, `taxTotal`, and `discountTotal`. Option `POST /cart` and `POST /cart/:id/items` accept an optional `details` and `metafields` alongside `skuId`, `name`, and `quantity`: -- `details.productAssetUrl` must be an absolute `https://` URL (max 2048 characters). It is additive to the SKU's own catalog image, not a replacement for it at the catalog level — but it does take priority over the catalog image everywhere a line item's image is shown (the shopper's cart, the merchant's order view, emails, fulfillment/packing views), since it is meant for the shopper's own design or customization preview. +- `details.productAssetUrl` must be an absolute `https://` URL (max 2048 characters), meant for the shopper's own design or customization preview. It replaces the catalog image for this line item only — the cart, the merchant's order view, emails, and fulfillment/packing views — the catalog itself and its own SKU media are unchanged. - `details.selectedAddons` is `[{ optionId, values: [{ inputValue }] }]` — only the shopper-typed TEXT/NUMBER catalog-option shape. A pre-defined LIST-option value (`{ optionValueId }`) is not supported by this contract and is rejected. Up to 20 addon entries per item; each `inputValue` up to 500 characters. - `metafields` is `[{ key, value }]`, up to 10 entries per item, each value up to 2000 characters. The server always sends `type: "JSON"` to the upstream order system regardless of any `type` the client supplies. - **Known limitation:** two add-item calls for the same `skuId` reliably produce two distinct cart lines only when at least one of them includes `details.selectedAddons`. If neither call includes `selectedAddons` — for example, two calls that differ only by `metafields` or `productAssetUrl` — they merge into a single line, and the second call's customization silently replaces the first's. diff --git a/packages/commerce-storefront/src/cart-state.ts b/packages/commerce-storefront/src/cart-state.ts index 8f713f31..7fbecdb0 100644 --- a/packages/commerce-storefront/src/cart-state.ts +++ b/packages/commerce-storefront/src/cart-state.ts @@ -5,13 +5,19 @@ import { type SampleProduct, sampleCurrency, useSampleCart } from './sample-cart // A dedicated formatter cache for signed addon-cost adjustments, separate from `api.ts`'s // `money()` cache: `signDisplay` is only needed here, not for the much hotter plain-price path // `money()`/`useMoney()` serve everywhere else, so it isn't worth widening that shared cache's -// key or public signature for this one case. +// key or public signature for this one case. Capped the same way, for the same reason: a page +// uses a few pairs, but a long-running server rendering many locales/currencies should not grow +// this map unbounded. const signedCurrencyFormats = new Map(); +const maxSignedCurrencyFormats: number = 64; function formatSignedCost(value: number, currency: string, locale: string): string { const key = `${locale}|${currency}`; let format = signedCurrencyFormats.get(key); if (!format) { format = new Intl.NumberFormat(locale, { style: 'currency', currency, signDisplay: 'exceptZero' }); + // Maps keep insertion order, so the first key is the oldest. + if (signedCurrencyFormats.size >= maxSignedCurrencyFormats) + signedCurrencyFormats.delete(signedCurrencyFormats.keys().next().value ?? ''); signedCurrencyFormats.set(key, format); } const scale = 10 ** (format.resolvedOptions().maximumFractionDigits ?? 2);