# @returnflows/shop-overlay

A modular exchange/return widget with a programmatic API for headless Shopify storefronts and custom e-commerce implementations.

## Table of Contents

- [Installation](#installation)
- [Quick Start](#quick-start)
- [Configuration](#configuration)
- [API Reference](#api-reference)
  - [Initialization](#initialization)
  - [Drawer API](#drawer-api)
  - [Cart API](#cart-api)
  - [Data API](#data-api)
  - [Toast API](#toast-api)
  - [Events](#events)
- [Cart Providers](#cart-providers)
- [Storefront API Support](#storefront-api-support)
- [Examples](#examples)
  - [Vanilla JavaScript](#vanilla-javascript)
  - [React](#react)
- [TypeScript Support](#typescript-support)
- [Troubleshooting](#troubleshooting)

## Installation

```bash
npm install @returnflows/shop-overlay
# or
pnpm add @returnflows/shop-overlay
# or
yarn add @returnflows/shop-overlay
```

## Quick Start

### Vanilla JavaScript

```javascript
import { Returnflows } from "@returnflows/shop-overlay";

// Initialize the widget
await Returnflows.init({
	onReady: () => {
		console.log("Widget ready!");
	},
	onError: error => {
		console.error("Widget error:", error);
	}
});

// Open the drawer
Returnflows.drawer.open();
```

### React

```tsx
import { useEffect } from "react";
import { Returnflows } from "@returnflows/shop-overlay";

function App() {
	useEffect(() => {
		Returnflows.init({
			onReady: () => console.log("Ready"),
			onError: err => console.error(err)
		});
	}, []);

	return (
		<button onClick={() => Returnflows.drawer.toggle()}>Open Returns</button>
	);
}
```

## Configuration

### `ReturnflowsConfig`

Configuration options passed to `Returnflows.init()`:

| Property                    | Type                                                         | Default                                            | Description                                         |
| --------------------------- | ------------------------------------------------------------ | -------------------------------------------------- | --------------------------------------------------- |
| `env`                       | `'development' \| 'test' \| 'production'`                    | `'production'`                                     | Environment for API endpoints                       |
| `debug`                     | `boolean`                                                    | `false`                                            | Enable debug logging                                |
| `autoOpen`                  | `boolean`                                                    | `false`                                            | Automatically open drawer on cart changes           |
| `autoOpenTriggerMethod`     | `'endpoint' \| 'change' \| 'combination'`                    | `'change'`                                         | How to detect cart changes for auto-open            |
| `autoOpenTriggerEndpoint`   | `'add' \| 'update' \| 'change'`                              | `'change'`                                         | Which cart endpoint triggers auto-open              |
| `networkInterceptionMethod` | `'none' \| 'fetch' \| 'xhr' \| 'both' \| 'events' \| 'auto'` | `'auto'` (embedded widget), `'none'` (ESM package) | How cart changes are detected (see below)           |
| `defaultLocale`             | `string`                                                     | `'en'`                                             | Default locale for translations                     |
| `defaultCurrency`           | `string`                                                     | `'USD'`                                            | Default currency code                               |
| `clearCartOnStart`          | `boolean`                                                    | `false`                                            | Clear cart state on initialization                  |
| `cartProvider`              | `CartProvider`                                               | `undefined`                                        | Custom cart provider for headless setups            |
| `getProductUrl`             | `(product: ShopifyCartItem \| OrderProduct) => string`       | `undefined`                                        | Custom function to generate product URLs (ESM only) |
| `onReady`                   | `() => void`                                                 | `undefined`                                        | Callback when widget is ready                       |
| `onError`                   | `(error: Error) => void`                                     | `undefined`                                        | Callback on initialization error                    |

### Cart Change Detection

`networkInterceptionMethod` controls how the widget notices that the storefront cart changed:

| Value      | Behaviour                                                                                                                                                                                     |
| ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `'auto'`   | Uses `'events'` only when the theme has configured `Shopify.actions.updateCart`, otherwise falls back to `'both'`. The default for the embedded widget, including when the option is omitted. |
| `'events'` | Listens for the `shopify:cart:lines-update` and `shopify:cart:error` DOM events. Non-destructive, but requires a theme that dispatches them.                                                  |
| `'fetch'`  | Proxies `window.fetch` and matches Ajax cart endpoints.                                                                                                                                       |
| `'xhr'`    | Proxies `XMLHttpRequest` and matches Ajax cart endpoints.                                                                                                                                     |
| `'both'`   | Proxies both. The legacy default.                                                                                                                                                             |
| `'none'`   | No detection. Default for the ESM package, where `cartProvider` is the intended integration point.                                                                                            |

Standard storefront events are dispatched by theme code, so there is no way for the widget to enable them on a theme that hasn't adopted them — `'auto'` detects and falls back instead.

Detection is deliberately conservative. A theme that merely loads the standard events library may still dispatch only a subset of events, so `'auto'` treats that as unproven and stays on `'both'`; only a configured `Shopify.actions.updateCart` confirms that cart events are delivered. Choosing `'events'` explicitly skips detection entirely. Enable debug mode to see which method was resolved and why.

`monitorNetworkOverwrites` only applies to the `fetch`/`xhr`/`both` paths, since it exists to restore patched globals and event listeners have nothing to restore. Under `'auto'` it therefore applies when detection falls back to `'both'`, but not when detection selects `'events'`.

### Custom Product URLs

By default, product links in the widget point to `/products/{handle}`. If your storefront uses a different URL structure, you can provide a `getProductUrl` function to customize the product URLs. The function receives the full product object (`ShopifyCartItem` for exchange products, `OrderProduct` for return products) and should return the URL path. Both types share a `handle` field.

> **Note:** This option is only available when using the ESM module (npm package).

```typescript
await Returnflows.init({
	getProductUrl: product => `/product/${product.handle}`
});
```

```typescript
// Use any product field to build the URL
await Returnflows.init({
	getProductUrl: product => `/shop/items/${product.handle}`
});
```

### Supported Locales

The widget includes translations for:

- `da` - Danish
- `de` - German
- `en` - English (default)
- `es` - Spanish
- `fi` - Finnish
- `fr` - French
- `it` - Italian
- `nb` - Norwegian Bokmål
- `nl` - Dutch
- `pl` - Polish
- `pt` - Portuguese
- `sv` - Swedish

## API Reference

### Initialization

#### `Returnflows.init(config?)`

Initialize the widget. Returns a Promise that resolves when the widget is ready.

```typescript
await Returnflows.init({
	defaultLocale: "en",
	defaultCurrency: "USD",
	onReady: () => console.log("Widget initialized"),
	onError: error => console.error("Init failed:", error)
});
```

#### `Returnflows.destroy()`

Destroy the widget instance and clean up resources.

```typescript
Returnflows.destroy();
```

#### `Returnflows.isInitialized()`

Check if the widget is currently initialized.

```typescript
if (Returnflows.isInitialized()) {
	Returnflows.drawer.open();
}
```

#### `Returnflows.version`

Get the current widget version.

```typescript
console.log(Returnflows.version); // "1.0.0"
```

### Drawer API

Control the widget drawer visibility.

#### `Returnflows.drawer.open()`

Open the drawer.

```typescript
Returnflows.drawer.open();
```

#### `Returnflows.drawer.close()`

Close the drawer.

```typescript
Returnflows.drawer.close();
```

#### `Returnflows.drawer.toggle()`

Toggle the drawer open/closed state.

```typescript
Returnflows.drawer.toggle();
```

#### `Returnflows.drawer.isOpen()`

Check if the drawer is currently open.

```typescript
if (Returnflows.drawer.isOpen()) {
	console.log("Drawer is open");
}
```

### Cart API

Manage the cart state programmatically.

#### `Returnflows.cart.setCart(cart)`

Set the cart data. Accepts both Shopify AJAX API format and Storefront API format.

```typescript
// Shopify AJAX API format
const result = await Returnflows.cart.setCart({
	items: [
		{
			variant_id: 12345,
			quantity: 1,
			title: "Product Name",
			price: 2999,
			product_id: 67890,
			product_title: "Product Name",
			handle: "product-handle",
			image: "https://...",
			grams: 500,
			line_price: 2999,
			final_price: 2999,
			final_line_price: 2999
		}
	],
	item_count: 1
});

console.log(result.hasChanged); // true if cart was updated
console.log(result.cart); // normalized cart data
console.log(result.calculation); // return calculation
```

Returns: `Promise<{ cart: ShopifyCart | null; calculation: CalculationResponse | null; hasChanged: boolean }>`

#### `Returnflows.cart.refetch()`

Refetch cart data from the cart provider or default source.

```typescript
await Returnflows.cart.refetch();
```

#### `Returnflows.cart.clear()`

Clear the current cart.

```typescript
await Returnflows.cart.clear();
```

### Data API

Access widget state data.

#### `Returnflows.data.getCart()`

Get the current cart data.

```typescript
const cart = Returnflows.data.getCart();
// Returns ShopifyCart | null
```

#### `Returnflows.data.getCalculation()`

Get the current return calculation.

```typescript
const calculation = Returnflows.data.getCalculation();
// Returns CalculationResponse | null
```

#### `Returnflows.data.getOrder()`

Get the current order data.

```typescript
const order = Returnflows.data.getOrder();
// Returns OrderData | null
```

#### `Returnflows.data.isLoading()`

Check if data is currently loading.

```typescript
if (Returnflows.data.isLoading()) {
	console.log("Loading...");
}
```

### Toast API

Display toast notifications within the widget.

#### `Returnflows.toast.show(options)`

Show a toast notification. Returns the toast ID.

```typescript
const toastId = Returnflows.toast.show({
	message: "Item added successfully",
	tone: "info", // 'info' | 'tip' | 'action' | 'error' | 'giftcard'
	duration: 5000, // auto-dismiss after 5 seconds
	onClose: () => console.log("Toast closed")
});
```

#### `Returnflows.toast.dismiss(id)`

Dismiss a specific toast by ID.

```typescript
Returnflows.toast.dismiss(toastId);
```

#### `Returnflows.toast.clear()`

Clear all toasts.

```typescript
Returnflows.toast.clear();
```

### Events

Subscribe to widget events.

#### `Returnflows.on(event, callback)`

Subscribe to an event. Returns an unsubscribe function.

```typescript
const unsubscribe = Returnflows.on("drawer:open", () => {
	console.log("Drawer opened");
});

// Later: unsubscribe
unsubscribe();
```

#### `Returnflows.off(event, callback)`

Unsubscribe from an event.

```typescript
const handler = () => console.log("Cart updated");
Returnflows.on("cart:updated", handler);

// Later: unsubscribe
Returnflows.off("cart:updated", handler);
```

#### Available Events

| Event                 | Callback Type                                | Description                     |
| --------------------- | -------------------------------------------- | ------------------------------- |
| `ready`               | `() => void`                                 | Widget is initialized and ready |
| `drawer:open`         | `() => void`                                 | Drawer was opened               |
| `drawer:close`        | `() => void`                                 | Drawer was closed               |
| `cart:updated`        | `(cart: ShopifyCart) => void`                | Cart data was updated           |
| `calculation:updated` | `(calculation: CalculationResponse) => void` | Return calculation was updated  |
| `error`               | `(error: Error) => void`                     | An error occurred               |

## Cart Providers

For headless implementations, you can provide a custom cart provider to manage cart operations.

### `CartProvider` Interface

```typescript
interface CartProvider<T extends CartInput = CartInput> {
	getCart(): Promise<T | undefined>;
	clearCart(): Promise<T>;
	addItems(items: CartAddItem[]): Promise<T>;
	updateItems(items: CartUpdateItem[]): Promise<T>;
	removeItems(lineIds: string[]): Promise<T>;
}

interface CartAddItem {
	merchandiseId: string;
	quantity: number;
}

interface CartUpdateItem {
	id: string;
	merchandiseId: string;
	quantity: number;
}
```

### Example: Custom Cart Provider

```typescript
import {
	Returnflows,
	CartProvider,
	StorefrontCart
} from "@returnflows/shop-overlay";

const cartProvider: CartProvider<StorefrontCart> = {
	async getCart() {
		const response = await fetch("/api/cart");
		return response.json();
	},

	async clearCart() {
		const response = await fetch("/api/cart", { method: "DELETE" });
		return response.json();
	},

	async addItems(items) {
		const response = await fetch("/api/cart/add", {
			method: "POST",
			body: JSON.stringify({ items })
		});
		return response.json();
	},

	async updateItems(items) {
		const response = await fetch("/api/cart/update", {
			method: "POST",
			body: JSON.stringify({ items })
		});
		return response.json();
	},

	async removeItems(lineIds) {
		const response = await fetch("/api/cart/remove", {
			method: "POST",
			body: JSON.stringify({ lineIds })
		});
		return response.json();
	}
};

await Returnflows.init({ cartProvider });
```

## Storefront API Support

The widget automatically normalizes Shopify Storefront API cart format to the internal format. You can pass either format to `setCart()` or return it from your `CartProvider`.

### Storefront API Cart Format

```typescript
interface StorefrontCart {
	id?: string;
	totalQuantity?: number;
	lines: StorefrontCartLine[] | { edges: Array<{ node: StorefrontCartLine }> };
	checkoutUrl?: string;
	note?: string;
}

interface StorefrontCartLine {
	id?: string;
	quantity: number;
	cost?: {
		totalAmount: { amount: string; currencyCode: string };
		amountPerQuantity?: { amount: string; currencyCode: string };
	};
	merchandise: {
		id: string; // GID format: "gid://shopify/ProductVariant/12345"
		title?: string;
		price?: { amount: string; currencyCode: string };
		image?: { url: string; altText?: string } | null;
		product: {
			id: string;
			handle: string;
			title: string;
			vendor?: string;
		};
	};
}
```

### Using Storefront API Cart

```typescript
// Storefront API cart (GraphQL format)
const storefrontCart = {
	id: "gid://shopify/Cart/abc123",
	totalQuantity: 2,
	lines: {
		edges: [
			{
				node: {
					id: "gid://shopify/CartLine/xyz",
					quantity: 2,
					cost: {
						totalAmount: { amount: "59.98", currencyCode: "USD" },
						amountPerQuantity: { amount: "29.99", currencyCode: "USD" }
					},
					merchandise: {
						id: "gid://shopify/ProductVariant/12345",
						title: "Medium / Blue",
						product: {
							id: "gid://shopify/Product/67890",
							handle: "t-shirt",
							title: "Classic T-Shirt"
						}
					}
				}
			}
		]
	}
};

// Pass directly - widget handles normalization
await Returnflows.cart.setCart(storefrontCart);
```

## Examples

### Vanilla JavaScript

#### Basic Integration

```html
<!DOCTYPE html>
<html>
	<head>
		<title>My Store</title>
	</head>
	<body>
		<button id="returns-btn">Start Return</button>

		<script type="module">
			import { Returnflows } from "@returnflows/shop-overlay";

			// Initialize when DOM is ready
			document.addEventListener("DOMContentLoaded", async () => {
				try {
					await Returnflows.init({
						defaultLocale: "en",
						defaultCurrency: "USD",
						onReady: () => {
							document.getElementById("returns-btn").disabled = false;
						}
					});

					// Listen for events
					Returnflows.on("drawer:open", () => {
						document.body.style.overflow = "hidden";
					});

					Returnflows.on("drawer:close", () => {
						document.body.style.overflow = "";
					});

					Returnflows.on("calculation:updated", calc => {
						console.log("Return value:", calc.total);
					});
				} catch (error) {
					console.error("Failed to initialize:", error);
				}
			});

			// Button handler
			document.getElementById("returns-btn").addEventListener("click", () => {
				Returnflows.drawer.toggle();
			});
		</script>
	</body>
</html>
```

#### With Cart Provider (Headless)

```javascript
import { Returnflows } from "@returnflows/shop-overlay";

// Shopify Storefront API client
const storefrontClient = {
	async query(query, variables) {
		const response = await fetch("/api/storefront", {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			body: JSON.stringify({ query, variables })
		});
		return response.json();
	}
};

// Cart provider using Storefront API
const cartProvider = {
	async getCart() {
		const { data } = await storefrontClient.query(
			`
      query GetCart($cartId: ID!) {
        cart(id: $cartId) {
          id
          totalQuantity
          lines(first: 100) {
            edges {
              node {
                id
                quantity
                cost {
                  totalAmount { amount currencyCode }
                  amountPerQuantity { amount currencyCode }
                }
                merchandise {
                  ... on ProductVariant {
                    id
                    title
                    image { url altText }
                    product {
                      id
                      handle
                      title
                      vendor
                    }
                  }
                }
              }
            }
          }
        }
      }
    `,
			{ cartId: localStorage.getItem("cartId") }
		);

		return data?.cart;
	},

	async addItems(items) {
		const lines = items.map(item => ({
			merchandiseId: item.merchandiseId,
			quantity: item.quantity
		}));

		const { data } = await storefrontClient.query(
			`
      mutation AddToCart($cartId: ID!, $lines: [CartLineInput!]!) {
        cartLinesAdd(cartId: $cartId, lines: $lines) {
          cart { id totalQuantity lines(first: 100) { edges { node { id quantity } } } }
        }
      }
    `,
			{ cartId: localStorage.getItem("cartId"), lines }
		);

		return data.cartLinesAdd.cart;
	},

	async updateItems(items) {
		const lines = items.map(item => ({
			id: item.id,
			merchandiseId: item.merchandiseId,
			quantity: item.quantity
		}));

		const { data } = await storefrontClient.query(
			`
      mutation UpdateCart($cartId: ID!, $lines: [CartLineUpdateInput!]!) {
        cartLinesUpdate(cartId: $cartId, lines: $lines) {
          cart { id totalQuantity lines(first: 100) { edges { node { id quantity } } } }
        }
      }
    `,
			{ cartId: localStorage.getItem("cartId"), lines }
		);

		return data.cartLinesUpdate.cart;
	},

	async removeItems(lineIds) {
		const { data } = await storefrontClient.query(
			`
      mutation RemoveFromCart($cartId: ID!, $lineIds: [ID!]!) {
        cartLinesRemove(cartId: $cartId, lineIds: $lineIds) {
          cart { id totalQuantity lines(first: 100) { edges { node { id quantity } } } }
        }
      }
    `,
			{ cartId: localStorage.getItem("cartId"), lineIds }
		);

		return data.cartLinesRemove.cart;
	},

	async clearCart() {
		// Create a new cart
		const { data } = await storefrontClient.query(`
      mutation CreateCart {
        cartCreate { cart { id } }
      }
    `);
		localStorage.setItem("cartId", data.cartCreate.cart.id);
		return data.cartCreate.cart;
	}
};

// Initialize with cart provider
await Returnflows.init({
	cartProvider,
	onReady: () => console.log("Widget ready with headless cart")
});
```

### React

#### Basic Hook

```tsx
import { useEffect, useCallback, useState } from "react";
import {
	Returnflows,
	type ShopifyCart,
	type CalculationResponse
} from "@returnflows/shop-overlay";

function useReturnflows() {
	const [isReady, setIsReady] = useState(false);
	const [isOpen, setIsOpen] = useState(false);
	const [cart, setCart] = useState<ShopifyCart | null>(null);
	const [calculation, setCalculation] = useState<CalculationResponse | null>(
		null
	);

	useEffect(() => {
		let mounted = true;

		const init = async () => {
			try {
				await Returnflows.init({
					onReady: () => {
						if (mounted) setIsReady(true);
					}
				});
			} catch (error) {
				console.error("Returnflows init failed:", error);
			}
		};

		init();

		// Subscribe to events
		const unsubOpen = Returnflows.on("drawer:open", () => setIsOpen(true));
		const unsubClose = Returnflows.on("drawer:close", () => setIsOpen(false));
		const unsubCart = Returnflows.on("cart:updated", setCart);
		const unsubCalc = Returnflows.on("calculation:updated", setCalculation);

		return () => {
			mounted = false;
			unsubOpen();
			unsubClose();
			unsubCart();
			unsubCalc();
		};
	}, []);

	const openDrawer = useCallback(() => Returnflows.drawer.open(), []);
	const closeDrawer = useCallback(() => Returnflows.drawer.close(), []);
	const toggleDrawer = useCallback(() => Returnflows.drawer.toggle(), []);

	return {
		isReady,
		isOpen,
		cart,
		calculation,
		openDrawer,
		closeDrawer,
		toggleDrawer
	};
}

export default useReturnflows;
```

#### React Component Example

```tsx
import { useEffect, useState } from "react";
import { Returnflows } from "@returnflows/shop-overlay";
import type {
	ShopifyCart,
	CalculationResponse
} from "@returnflows/shop-overlay";

function ReturnflowsProvider({ children }: { children: React.ReactNode }) {
	const [initialized, setInitialized] = useState(false);

	useEffect(() => {
		Returnflows.init({
			defaultLocale: "en",
			defaultCurrency: "USD",
			onReady: () => setInitialized(true),
			onError: error => console.error("Widget error:", error)
		});
	}, []);

	if (!initialized) {
		return <div>Loading returns widget...</div>;
	}

	return <>{children}</>;
}

function ReturnsButton() {
	const [isOpen, setIsOpen] = useState(false);

	useEffect(() => {
		const unsubOpen = Returnflows.on("drawer:open", () => setIsOpen(true));
		const unsubClose = Returnflows.on("drawer:close", () => setIsOpen(false));

		return () => {
			unsubOpen();
			unsubClose();
		};
	}, []);

	return (
		<button onClick={() => Returnflows.drawer.toggle()} aria-expanded={isOpen}>
			{isOpen ? "Close Returns" : "Start Return"}
		</button>
	);
}

function ReturnsSummary() {
	const [calculation, setCalculation] = useState<CalculationResponse | null>(
		null
	);

	useEffect(() => {
		// Get initial calculation
		setCalculation(Returnflows.data.getCalculation());

		// Subscribe to updates
		const unsub = Returnflows.on("calculation:updated", setCalculation);
		return unsub;
	}, []);

	if (!calculation) return null;

	return (
		<div>
			<p>
				Return Value: {calculation.currency.localCurrency}{" "}
				{(calculation.total / 100).toFixed(2)}
			</p>
			<p>Items: {calculation.lineItems.length}</p>
		</div>
	);
}

// Usage
function App() {
	return (
		<ReturnflowsProvider>
			<header>
				<ReturnsButton />
			</header>
			<main>
				<ReturnsSummary />
			</main>
		</ReturnflowsProvider>
	);
}
```

## TypeScript Support

The package includes full TypeScript definitions. All types are exported from the main entry point:

```typescript
import {
	// API Types
	Returnflows,
	ReturnflowsAPI,
	ReturnflowsConfig,

	// Cart Types
	CartInput,
	CartProvider,
	CartAddItem,
	CartUpdateItem,
	ShopifyCart,
	ShopifyCartItem,
	StorefrontCart,
	StorefrontCartLine,

	// Data Types
	CalculationResponse,
	OrderData,

	// API Interfaces
	DrawerAPI,
	CartAPI,
	DataAPI,
	ToastAPI,
	ToastOptions,
	ToastTone,

	// Events
	EventName,
	EventCallback,

	// Other
	Environment,
	ThemeVariables,
	WidgetViewState
} from "@returnflows/shop-overlay";
```

## Troubleshooting

### Widget not initializing

Ensure you're calling `init()` after the DOM is ready:

```javascript
// Vanilla JS
document.addEventListener("DOMContentLoaded", () => {
	Returnflows.init();
});

// React - use useEffect
useEffect(() => {
	Returnflows.init();
}, []);
```

### "Widget not initialized" errors

Always check `isInitialized()` before calling API methods:

```javascript
if (Returnflows.isInitialized()) {
	Returnflows.drawer.open();
} else {
	console.warn("Widget not ready yet");
}
```

### Cart not updating

If using a custom cart provider, ensure all methods return the updated cart:

```javascript
const cartProvider = {
  async addItems(items) {
    await fetch('/api/cart/add', { ... });
    // Must return the updated cart!
    return this.getCart();
  }
};
```

### Storefront API cart not recognized

Ensure your cart has the `lines` property with the correct structure:

```javascript
// Correct - has lines array or edges
{ lines: [...] }
{ lines: { edges: [...] } }

// Incorrect - using items instead of lines
{ items: [...] }  // This is AJAX API format
```

### Multiple instances

Only one widget instance can exist. Call `destroy()` before re-initializing:

```javascript
Returnflows.destroy();
await Returnflows.init({
	/* new config */
});
```

---

## License

Copyright (c) 2026 Returnflows Systems ApS

All rights reserved.

This software and associated documentation files (the "Software") are the
proprietary property of Returnflows Systems ApS.

Unauthorized copying, distribution, modification, sublicensing, or use of
the Software is strictly prohibited without prior written permission from
Returnflows Systems ApS.
