@hand-off/storefront 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +464 -2
- package/index.cjs +736 -0
- package/index.mjs +713 -0
- package/package.json +44 -4
- package/skill/SKILL.md +207 -0
- package/types/core/cart.d.ts +47 -0
- package/types/core/collections.d.ts +7 -0
- package/types/core/content.d.ts +8 -0
- package/types/core/discount.d.ts +15 -0
- package/types/core/errors.d.ts +34 -0
- package/types/core/menus.d.ts +7 -0
- package/types/core/products.d.ts +34 -0
- package/types/core/store.d.ts +15 -0
- package/types/core/transport.d.ts +47 -0
- package/types/entry/format.d.ts +5 -0
- package/types/entry/index.d.ts +30 -0
- package/types/sdk/checkout.d.ts +51 -0
- package/types/sdk/session.d.ts +29 -0
- package/types/sdk/shopper.d.ts +64 -0
- package/types/sdk/storefront.d.ts +86 -0
- package/types/transport/key.d.ts +77 -0
- package/types/transport/session.d.ts +21 -0
- package/types/types/api.d.ts +658 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Hand-Off
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,465 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @hand-off/storefront
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Build a shop on any stack against a [Hand-Off](https://handoff.store) store: Next.js, Astro, Remix,
|
|
4
|
+
SvelteKit, a static page, or your own server. The library reads the store's catalogue and pages,
|
|
5
|
+
keeps the visitor's cart, signs shoppers in and sends them to Hand-Off's checkout.
|
|
6
|
+
|
|
7
|
+
- No dependencies. ES module and CommonJS builds, with TypeScript types for every answer.
|
|
8
|
+
- The same client the store builder's own pages run on (`window.HandOff` on a sealed page).
|
|
9
|
+
- Money is always an integer in minor units (cents) with its `currency`.
|
|
10
|
+
|
|
11
|
+
> **Status: preview (0.x).** The catalogue reads work today. The cart and shopper sign-in work
|
|
12
|
+
> where the store has token sessions on, checkout where it has checkout links on. Methods are
|
|
13
|
+
> added, never renamed.
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npm install @hand-off/storefront
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Quick start
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import { createStorefront, formatMoney } from '@hand-off/storefront';
|
|
25
|
+
|
|
26
|
+
const shop = createStorefront({
|
|
27
|
+
shop: 'https://acme.handoff.market', // the shop's address: a handoff.market address or its own domain
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
const store = await shop.store.get();
|
|
31
|
+
const { items, nextCursor } = await shop.products.list({ limit: 12 });
|
|
32
|
+
|
|
33
|
+
for (const product of items) {
|
|
34
|
+
console.log(product.name, formatMoney(product.price, product.currency, store.language));
|
|
35
|
+
}
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
`shop` is the address shoppers visit. In an organization with several stores, add the store's
|
|
39
|
+
slug: `https://acme.handoff.market/bakery`.
|
|
40
|
+
|
|
41
|
+
## Where it runs
|
|
42
|
+
|
|
43
|
+
| Where | Today |
|
|
44
|
+
| --- | --- |
|
|
45
|
+
| A server: Node 18+, Next.js server components and route handlers, Remix/SvelteKit loaders, Astro, edge runtimes | Yes |
|
|
46
|
+
| The browser, on your own domain | With the store's publishable storefront key (`hopk_…`) and your site's address on that key's allowed sites |
|
|
47
|
+
|
|
48
|
+
The store's owner creates the key, lists your site's exact origin (such as
|
|
49
|
+
`https://shop.example.com`, or `http://localhost:3000` while developing) and switches storefront
|
|
50
|
+
keys on for the store. Without a key, call the library from server code and send your page the
|
|
51
|
+
result.
|
|
52
|
+
|
|
53
|
+
## What it reads
|
|
54
|
+
|
|
55
|
+
| Call | Answers |
|
|
56
|
+
| --- | --- |
|
|
57
|
+
| `store.get()` | The store: name, `url`, `currency`, `language`, branding, contact, hours, fulfillment |
|
|
58
|
+
| `store.hours()` | Opening hours, whether orders are taken now, each fulfillment method's hours |
|
|
59
|
+
| `store.policies()` | The policy pages |
|
|
60
|
+
| `products.list(query?)` | `{ items, nextCursor }`. `query`: `limit`, `cursor`, `search`, `collectionId`, `categoryId`, `brandId`, `sort`, `inStock`, `onSale` |
|
|
61
|
+
| `products.get(ref)` | One product with its media, options and variants; `ref` is an id, a slug, `{ id }` or `{ slug }` |
|
|
62
|
+
| `products.variants(ref)` | Its variants: price, stock and the `key` the cart takes |
|
|
63
|
+
| `products.related(productId, { limit }?)` | Products shown beside it |
|
|
64
|
+
| `variants.get(variantId)` | `{ variant, product }` |
|
|
65
|
+
| `collections.list()`, `collections.get(idOrSlug)` | Collections |
|
|
66
|
+
| `categories.list()` | Product categories, top-level first, then subcategories (`parentId`), with `url` and `productCount` |
|
|
67
|
+
| `pages.list()`, `pages.byPath('/about')` | The store's pages, and whatever lives at a path (a page, a blog list, an entry, a redirect) |
|
|
68
|
+
| `content.list(collection)`, `content.get(collection, entry)` | The store's own content collections (a blog, a team) |
|
|
69
|
+
| `menus.get()` | `{ header, footer }` |
|
|
70
|
+
|
|
71
|
+
Paging: pass `nextCursor` back as `cursor`; it is `null` on the last page.
|
|
72
|
+
|
|
73
|
+
## Cart and shopper sign-in
|
|
74
|
+
|
|
75
|
+
These need the store's token sessions switched on and, in a browser, a publishable key.
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
const shop = createStorefront({
|
|
79
|
+
shop: 'https://acme.handoff.market',
|
|
80
|
+
publishableKey: 'hopk_…',
|
|
81
|
+
session: storageSession(localStorage, 'acme.cart'), // keeps a guest's cart across visits
|
|
82
|
+
onCartChange: (cart) => renderBag(cart),
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
await shop.cart.add({ productId: product.id, combinationKey: variant.key, quantity: 1 });
|
|
86
|
+
const cart = await shop.cart.get(); // lines, list prices, itemCount
|
|
87
|
+
await shop.cart.update(cart.lines[0].id, 3); // 0 removes the line
|
|
88
|
+
await shop.cart.remove(lineId);
|
|
89
|
+
|
|
90
|
+
await shop.shopper.start('+15551234567'); // texts a sign-in code
|
|
91
|
+
const result = await shop.shopper.verify({ phone: '+15551234567', code: '123456' });
|
|
92
|
+
if (!result.signedIn) await shop.shopper.register({ registrationToken: result.registrationToken, firstName: 'Ada' });
|
|
93
|
+
await shop.cart.applyDiscount('SAVE10'); // discount codes need a signed-in shopper
|
|
94
|
+
await shop.shopper.signOut();
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
- The first cart write makes the visitor's cart token; `cart.get()` before that answers an empty
|
|
98
|
+
cart without calling. On sign-in the guest's cart is merged into the shopper's.
|
|
99
|
+
- The library keeps every token in its `session` and renews a shopper's 15-minute access token on
|
|
100
|
+
its own. No method hands a token back.
|
|
101
|
+
- A discount code is sent once per call, never retried.
|
|
102
|
+
- Sign-in codes belong to the key's store: start with `shopper.start`. A code from the shop's own
|
|
103
|
+
sign-in page is refused by `shopper.verify`.
|
|
104
|
+
|
|
105
|
+
| Call | Does |
|
|
106
|
+
| --- | --- |
|
|
107
|
+
| `cart.get()`, `cart.add(item)`, `cart.update(lineId, quantity \| change)`, `cart.remove(lineId)`, `cart.clear()` | The visitor's cart |
|
|
108
|
+
| `cart.applyDiscount(code)`, `cart.removeDiscount(code)` | Discount codes (signed-in shoppers) |
|
|
109
|
+
| `shopper.start(phone)`, `shopper.verify({ phone, code })`, `shopper.register({ registrationToken, … })` | Sign in or sign up with a text-message code |
|
|
110
|
+
| `shopper.email.start({ email })`, `shopper.email.verify({ email, code })` | Stores that check email |
|
|
111
|
+
| `shopper.get()`, `shopper.signedIn()`, `shopper.signOut()` | The signed-in shopper |
|
|
112
|
+
|
|
113
|
+
## Checkout
|
|
114
|
+
|
|
115
|
+
Payment happens on Hand-Off's checkout page. Make a one-time checkout link and send the shopper
|
|
116
|
+
to it; they come back to your `successUrl`. Needs the store's storefront key, and both addresses
|
|
117
|
+
must be on one of that key's allowed sites.
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
// The bag's "Pay" button
|
|
121
|
+
const link = await shop.checkout.fromCart({
|
|
122
|
+
successUrl: 'https://shop.example.com/thanks',
|
|
123
|
+
cancelUrl: 'https://shop.example.com/bag',
|
|
124
|
+
});
|
|
125
|
+
location.assign(link.url);
|
|
126
|
+
|
|
127
|
+
// On https://shop.example.com/thanks
|
|
128
|
+
const result = await shop.checkout.handleReturn(location.href);
|
|
129
|
+
if (result?.paid) showThanks(result.orderNumber); // confirmed with the API, cart emptied
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
| Call | Does |
|
|
133
|
+
| --- | --- |
|
|
134
|
+
| `checkout.fromCart({ successUrl, cancelUrl?, expiresInMinutes? })` | A link for the lines in the visitor's cart |
|
|
135
|
+
| `checkout.create({ lines, successUrl, cancelUrl?, expiresInMinutes? })` | A link for lines you name (`productId`, `combinationKey`, `quantity`, add-ons, personalization) |
|
|
136
|
+
| `checkout.get(checkoutLinkId)` | `OPEN`, `COMPLETED` with its `orderNumber`, or `EXPIRED` |
|
|
137
|
+
| `checkout.handleReturn(url)` | Reads `?handoff_checkout_link=` from the return address and confirms it; null when it is not a return |
|
|
138
|
+
|
|
139
|
+
- A link works once and lasts 60 minutes unless `expiresInMinutes` (5 to 1440) says otherwise.
|
|
140
|
+
- `handoff_order` in the return address is only a hint: trust `handleReturn(...).paid`.
|
|
141
|
+
- `INVALID_REQUEST` with `reason: 'RETURN_URL_REFUSED'`: an address is not on the key's allowed
|
|
142
|
+
sites. `UNAVAILABLE` with `reason: 'CHECKOUT_LINKS_OFF'`: the store has no checkout links.
|
|
143
|
+
|
|
144
|
+
## Set up the store (the owner)
|
|
145
|
+
|
|
146
|
+
The store's owner does this once, in the Hand-Off dashboard (or by asking the Hand-Off Assistant
|
|
147
|
+
or a connected AI, which have the same tools: `set_storefront_keys_enabled`, `create_storefront_key`):
|
|
148
|
+
|
|
149
|
+
1. **Publish the store's Hand-Off storefront.** The API serves only a published store.
|
|
150
|
+
2. **Switch storefront keys on** for the store (off by default) and **create a key** (`hopk_…`).
|
|
151
|
+
It is publishable: it may sit in your site's JavaScript.
|
|
152
|
+
3. **List the sites allowed to use it**: exact origins such as `https://shop.example.com`, plus
|
|
153
|
+
`http://localhost:3000` while developing. A browser call from any other origin is refused
|
|
154
|
+
(`ORIGIN_REFUSED`); server calls send no origin and are accepted.
|
|
155
|
+
4. **Token sessions and checkout links** (the cart, shopper sign-in and checkout from your site)
|
|
156
|
+
are rolling out store by store: ask Hand-Off support to switch them on for the store. Until
|
|
157
|
+
then those calls answer `NOT_FOUND` or `UNAVAILABLE`, and catalogue reads still work.
|
|
158
|
+
|
|
159
|
+
Rotate a key that leaked (the old one keeps working until the time you set) or revoke it; both
|
|
160
|
+
are in the same settings.
|
|
161
|
+
|
|
162
|
+
## Next.js (App Router) walk-through
|
|
163
|
+
|
|
164
|
+
Server components read the catalogue on the server, with no key needed. The browser gets the
|
|
165
|
+
publishable key for the cart and checkout, and nothing else.
|
|
166
|
+
|
|
167
|
+
```bash
|
|
168
|
+
# .env.local
|
|
169
|
+
HAND_OFF_SHOP_URL=https://acme.handoff.market
|
|
170
|
+
NEXT_PUBLIC_HAND_OFF_SHOP_URL=https://acme.handoff.market
|
|
171
|
+
NEXT_PUBLIC_HAND_OFF_STOREFRONT_KEY=hopk_… # publishable; browser only
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
```ts
|
|
175
|
+
// lib/shop.server.ts: catalogue reads on the server (no visitor state, so one client for every request)
|
|
176
|
+
import { createStorefront } from '@hand-off/storefront';
|
|
177
|
+
export const shop = createStorefront({ shop: process.env.HAND_OFF_SHOP_URL! });
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
```tsx
|
|
181
|
+
// app/page.tsx: the product list, paged with ?cursor=
|
|
182
|
+
import Link from 'next/link';
|
|
183
|
+
import { formatMoney } from '@hand-off/storefront';
|
|
184
|
+
import { shop } from '@/lib/shop.server';
|
|
185
|
+
|
|
186
|
+
export const revalidate = 60;
|
|
187
|
+
|
|
188
|
+
export default async function Home({ searchParams }: { searchParams: Promise<{ cursor?: string }> }) {
|
|
189
|
+
const { cursor } = await searchParams;
|
|
190
|
+
const [store, page] = await Promise.all([shop.store.get(), shop.products.list({ limit: 24, cursor })]);
|
|
191
|
+
return (
|
|
192
|
+
<main>
|
|
193
|
+
<h1>{store.name}</h1>
|
|
194
|
+
<ul>
|
|
195
|
+
{page.items.map((p) => (
|
|
196
|
+
<li key={p.id}>
|
|
197
|
+
<Link href={`/products/${p.slug}`}>
|
|
198
|
+
{p.image && <img src={p.image.url} srcSet={p.image.srcset || undefined} alt={p.image.alt} />}
|
|
199
|
+
{p.name} · {formatMoney(p.price, p.currency, store.language)}
|
|
200
|
+
</Link>
|
|
201
|
+
</li>
|
|
202
|
+
))}
|
|
203
|
+
</ul>
|
|
204
|
+
{page.nextCursor && <Link href={`/?cursor=${encodeURIComponent(page.nextCursor)}`}>More</Link>}
|
|
205
|
+
</main>
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
```tsx
|
|
211
|
+
// app/products/[slug]/page.tsx: one product by its slug
|
|
212
|
+
import { notFound } from 'next/navigation';
|
|
213
|
+
import { formatMoney, HandOffError } from '@hand-off/storefront';
|
|
214
|
+
import { shop } from '@/lib/shop.server';
|
|
215
|
+
import { AddToBag } from './add-to-bag';
|
|
216
|
+
|
|
217
|
+
export const revalidate = 60;
|
|
218
|
+
|
|
219
|
+
export default async function ProductPage({ params }: { params: Promise<{ slug: string }> }) {
|
|
220
|
+
const { slug } = await params;
|
|
221
|
+
const product = await shop.products.get({ slug }).catch((error) => {
|
|
222
|
+
if (error instanceof HandOffError && error.code === 'NOT_FOUND') notFound();
|
|
223
|
+
throw error;
|
|
224
|
+
});
|
|
225
|
+
return (
|
|
226
|
+
<main>
|
|
227
|
+
<h1>{product.name}</h1>
|
|
228
|
+
{/* descriptionHtml is sanitised by Hand-Off */}
|
|
229
|
+
<div dangerouslySetInnerHTML={{ __html: product.descriptionHtml ?? '' }} />
|
|
230
|
+
<AddToBag
|
|
231
|
+
productId={product.id}
|
|
232
|
+
variants={product.variants.map((v) => ({ key: v.key, title: v.title, price: formatMoney(v.price, v.currency), soldOut: v.stock.state === 'out_of_stock' }))}
|
|
233
|
+
/>
|
|
234
|
+
</main>
|
|
235
|
+
);
|
|
236
|
+
}
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
```tsx
|
|
240
|
+
// lib/shop.client.ts: the browser's client, with the publishable key and the guest cart kept across visits
|
|
241
|
+
'use client';
|
|
242
|
+
import { createStorefront, storageSession } from '@hand-off/storefront';
|
|
243
|
+
|
|
244
|
+
let client: ReturnType<typeof createStorefront> | undefined;
|
|
245
|
+
export function browserShop() {
|
|
246
|
+
client ??= createStorefront({
|
|
247
|
+
shop: process.env.NEXT_PUBLIC_HAND_OFF_SHOP_URL!,
|
|
248
|
+
publishableKey: process.env.NEXT_PUBLIC_HAND_OFF_STOREFRONT_KEY!,
|
|
249
|
+
session: storageSession(window.localStorage, 'hand-off.cart'),
|
|
250
|
+
});
|
|
251
|
+
return client;
|
|
252
|
+
}
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
```tsx
|
|
256
|
+
// app/products/[slug]/add-to-bag.tsx: the cart, in the browser
|
|
257
|
+
'use client';
|
|
258
|
+
import { useState } from 'react';
|
|
259
|
+
import { HandOffError } from '@hand-off/storefront';
|
|
260
|
+
import { browserShop } from '@/lib/shop.client';
|
|
261
|
+
|
|
262
|
+
export function AddToBag({ productId, variants }: { productId: string; variants: { key: string; title: string; price: string; soldOut: boolean }[] }) {
|
|
263
|
+
const [key, setKey] = useState(variants.find((v) => !v.soldOut)?.key ?? variants[0]?.key);
|
|
264
|
+
const [message, setMessage] = useState('');
|
|
265
|
+
async function add() {
|
|
266
|
+
try {
|
|
267
|
+
const cart = await browserShop().cart.add({ productId, combinationKey: key, quantity: 1 });
|
|
268
|
+
setMessage(`${cart.itemCount} in your bag`);
|
|
269
|
+
} catch (error) {
|
|
270
|
+
setMessage(error instanceof HandOffError && error.code === 'OUT_OF_STOCK' ? 'Sold out' : 'Could not add it');
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return (
|
|
274
|
+
<div>
|
|
275
|
+
<select value={key} onChange={(e) => setKey(e.target.value)}>
|
|
276
|
+
{variants.map((v) => (
|
|
277
|
+
<option key={v.key} value={v.key} disabled={v.soldOut}>{v.title} · {v.price}</option>
|
|
278
|
+
))}
|
|
279
|
+
</select>
|
|
280
|
+
<button onClick={add}>Add to bag</button>
|
|
281
|
+
<p role="status">{message}</p>
|
|
282
|
+
</div>
|
|
283
|
+
);
|
|
284
|
+
}
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
```tsx
|
|
288
|
+
// app/bag/pay-button.tsx: checkout on Hand-Off
|
|
289
|
+
'use client';
|
|
290
|
+
import { browserShop } from '@/lib/shop.client';
|
|
291
|
+
|
|
292
|
+
export function PayButton() {
|
|
293
|
+
async function pay() {
|
|
294
|
+
const link = await browserShop().checkout.fromCart({
|
|
295
|
+
successUrl: `${location.origin}/thanks`,
|
|
296
|
+
cancelUrl: `${location.origin}/bag`,
|
|
297
|
+
});
|
|
298
|
+
location.assign(link.url);
|
|
299
|
+
}
|
|
300
|
+
return <button onClick={pay}>Pay</button>;
|
|
301
|
+
}
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
```tsx
|
|
305
|
+
// app/thanks/page.tsx: confirm the order (never trust handoff_order in the address alone)
|
|
306
|
+
'use client';
|
|
307
|
+
import { useEffect, useState } from 'react';
|
|
308
|
+
import { browserShop } from '@/lib/shop.client';
|
|
309
|
+
|
|
310
|
+
export default function Thanks() {
|
|
311
|
+
const [text, setText] = useState('Checking your order…');
|
|
312
|
+
useEffect(() => {
|
|
313
|
+
browserShop().checkout.handleReturn(location.href).then((result) => {
|
|
314
|
+
setText(result?.paid ? `Thank you! Order ${result.orderNumber}.` : 'Your order is not paid yet.');
|
|
315
|
+
});
|
|
316
|
+
}, []);
|
|
317
|
+
return <main><p>{text}</p></main>;
|
|
318
|
+
}
|
|
319
|
+
```
|
|
320
|
+
|
|
321
|
+
Your site's origins (production, and `http://localhost:3000` while developing) must be on the
|
|
322
|
+
key's allowed sites, and `successUrl` / `cancelUrl` must be on one of them.
|
|
323
|
+
|
|
324
|
+
## Public vs sign-in-only catalogue
|
|
325
|
+
|
|
326
|
+
A store is public by default: anyone can read its catalogue. Its owner can make it private (the
|
|
327
|
+
store's visibility setting in the Hand-Off dashboard, or `update_storefront_availability` with
|
|
328
|
+
`visibility: 'PRIVATE'`), optionally with registration rules (approval, verification, a referral
|
|
329
|
+
code, a minimum age). A private store's catalogue is for its signed-in, approved shoppers only.
|
|
330
|
+
|
|
331
|
+
On a private store the reads answer:
|
|
332
|
+
|
|
333
|
+
| Code | Means | Show |
|
|
334
|
+
| --- | --- | --- |
|
|
335
|
+
| `AUTH_REQUIRED` | No signed-in shopper | A sign-in form |
|
|
336
|
+
| `REGISTRATION_REQUIRED` | Signed in, but not registered at this store | The sign-up (`shopper.register`) |
|
|
337
|
+
| `PENDING_APPROVAL` | Registered, waiting for the store's approval | A "we'll let you know" note |
|
|
338
|
+
| `VERIFICATION_REQUIRED` | The store needs email or ID verification first | The verification step |
|
|
339
|
+
|
|
340
|
+
```tsx
|
|
341
|
+
// A server component that falls back to sign-in on a private store
|
|
342
|
+
import { HandOffError } from '@hand-off/storefront';
|
|
343
|
+
import { shop } from '@/lib/shop.server';
|
|
344
|
+
import { SignIn } from './sign-in';
|
|
345
|
+
|
|
346
|
+
export default async function Catalogue() {
|
|
347
|
+
try {
|
|
348
|
+
const { items } = await shop.products.list({ limit: 24 });
|
|
349
|
+
return <ProductGrid items={items} />;
|
|
350
|
+
} catch (error) {
|
|
351
|
+
if (error instanceof HandOffError && ['AUTH_REQUIRED', 'REGISTRATION_REQUIRED', 'PENDING_APPROVAL', 'VERIFICATION_REQUIRED'].includes(error.code)) {
|
|
352
|
+
return <SignIn reason={error.code} />;
|
|
353
|
+
}
|
|
354
|
+
throw error;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
```
|
|
358
|
+
|
|
359
|
+
```tsx
|
|
360
|
+
// sign-in.tsx: shopper.start, then verify (with register when the store needs a profile)
|
|
361
|
+
'use client';
|
|
362
|
+
import { useState } from 'react';
|
|
363
|
+
import { browserShop } from '@/lib/shop.client';
|
|
364
|
+
|
|
365
|
+
export function SignIn({ reason }: { reason: string }) {
|
|
366
|
+
const [phone, setPhone] = useState('');
|
|
367
|
+
const [code, setCode] = useState('');
|
|
368
|
+
const [sent, setSent] = useState(false);
|
|
369
|
+
if (reason === 'PENDING_APPROVAL') return <p>Your account is waiting for the store's approval.</p>;
|
|
370
|
+
async function submit() {
|
|
371
|
+
const shop = browserShop();
|
|
372
|
+
if (!sent) {
|
|
373
|
+
await shop.shopper.start(phone); // always start here: codes belong to the key's store
|
|
374
|
+
setSent(true);
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
const result = await shop.shopper.verify({ phone, code, progressive: true });
|
|
378
|
+
if (!result.signedIn) {
|
|
379
|
+
// ask for result.requirements (name, email, referral…), then:
|
|
380
|
+
await shop.shopper.register({ registrationToken: result.registrationToken /* , firstName, … */ });
|
|
381
|
+
}
|
|
382
|
+
location.reload();
|
|
383
|
+
}
|
|
384
|
+
return (
|
|
385
|
+
<form onSubmit={(e) => { e.preventDefault(); void submit(); }}>
|
|
386
|
+
<input value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="+15551234567" />
|
|
387
|
+
{sent && <input value={code} onChange={(e) => setCode(e.target.value)} placeholder="Code" />}
|
|
388
|
+
<button>{sent ? 'Sign in' : 'Text me a code'}</button>
|
|
389
|
+
</form>
|
|
390
|
+
);
|
|
391
|
+
}
|
|
392
|
+
```
|
|
393
|
+
|
|
394
|
+
> **Not yet: a private store's catalogue through the SDK.** Sign-in works, but the API reads a
|
|
395
|
+
> shopper's token on the cart and sign-in routes only, so the catalogue of a private store still
|
|
396
|
+
> answers `AUTH_REQUIRED` to an outside site after sign-in. Until that ships, keep a store whose
|
|
397
|
+
> catalogue you show on your own site public. The cart, sign-in and checkout already work on a
|
|
398
|
+
> private store's session routes.
|
|
399
|
+
|
|
400
|
+
## Errors
|
|
401
|
+
|
|
402
|
+
Every failure rejects with a `HandOffError`. Branch on `code`, never on `message`:
|
|
403
|
+
|
|
404
|
+
```ts
|
|
405
|
+
import { HandOffError } from '@hand-off/storefront';
|
|
406
|
+
|
|
407
|
+
try {
|
|
408
|
+
await shop.products.get('no-such-thing');
|
|
409
|
+
} catch (error) {
|
|
410
|
+
if (error instanceof HandOffError && error.code === 'NOT_FOUND') return notFound();
|
|
411
|
+
throw error;
|
|
412
|
+
}
|
|
413
|
+
```
|
|
414
|
+
|
|
415
|
+
| Code | Means |
|
|
416
|
+
| --- | --- |
|
|
417
|
+
| `NOT_FOUND` | No such record, or it is not shown to shoppers (a draft, unpublished, hidden) |
|
|
418
|
+
| `AUTH_REQUIRED`, `REGISTRATION_REQUIRED`, `PENDING_APPROVAL` | A private store: the shopper must sign in or be approved |
|
|
419
|
+
| `RATE_LIMITED` | Slow down; `retryAfterMs` when the API says how long |
|
|
420
|
+
| `INVALID_ARGUMENT` | Refused before sending (a bad shop address, an empty id) |
|
|
421
|
+
| `KEY_REQUIRED`, `KEY_INVALID`, `ORIGIN_REFUSED` | The call needs the store's storefront key; the key is unknown, revoked, expired or switched off (`reason`); or your site is not on its allowed sites |
|
|
422
|
+
| `TOKEN_REQUIRED`, `TOKEN_INVALID`, `TOKEN_EXPIRED` | The visitor's cart or sign-in token is missing or no longer works (the library renews or replaces it where it can) |
|
|
423
|
+
| `SIGN_IN_REQUIRED` | Sign the shopper in first (discount codes) |
|
|
424
|
+
| `OUT_OF_STOCK`, `DISCOUNT_REFUSED` | The cart change was refused; `message` says why |
|
|
425
|
+
| `NETWORK_ERROR` | Nothing came back (offline, DNS, timeout after `timeoutMs`) |
|
|
426
|
+
| `INVALID_RESPONSE` | The answer was not the API's |
|
|
427
|
+
|
|
428
|
+
Mixing the ES module and CommonJS builds in one program gives two `HandOffError` classes; check
|
|
429
|
+
`error.name === 'HandOffError'` and `error.code` if you do.
|
|
430
|
+
|
|
431
|
+
## Options
|
|
432
|
+
|
|
433
|
+
```ts
|
|
434
|
+
createStorefront({
|
|
435
|
+
shop: 'https://acme.handoff.market',
|
|
436
|
+
publishableKey: 'hopk_…', // the store's publishable storefront key: safe to ship to browsers
|
|
437
|
+
session: storageSession(localStorage, 'acme.session'), // where the visitor's cart or shopper token is kept; memory by default
|
|
438
|
+
fetch, // your own fetch; the global one by default
|
|
439
|
+
headers: { 'Accept-Language': 'fr' },
|
|
440
|
+
timeoutMs: 15000,
|
|
441
|
+
});
|
|
442
|
+
```
|
|
443
|
+
|
|
444
|
+
- `memorySession()` keeps the token for the life of the process or page. On a server, make one
|
|
445
|
+
storefront per request (or pass a `Session` backed by your own session store) so two visitors
|
|
446
|
+
never share a cart.
|
|
447
|
+
- `storageSession(storage, key)` keeps it in `localStorage` or `sessionStorage`. **Cart tokens
|
|
448
|
+
only:** every script on your site can read Web Storage, and a shopper's sign-in token reaches
|
|
449
|
+
their account. Keep a signed-in shopper's tokens in `memorySession()` or in an HttpOnly cookie
|
|
450
|
+
your own server sets (a `Session` of your own).
|
|
451
|
+
- No cookie is ever sent: the library carries the visitor's session itself.
|
|
452
|
+
|
|
453
|
+
`shop.transport.request(method, path, body?, { query })` calls any route under
|
|
454
|
+
`/storefront/api/v1/` the library has no method for yet.
|
|
455
|
+
|
|
456
|
+
## Building a shop with a coding agent
|
|
457
|
+
|
|
458
|
+
The package ships a skill (instructions a coding agent such as Claude Code follows) for building a
|
|
459
|
+
shop with this library: `node_modules/@hand-off/storefront/skill/SKILL.md`. Copy it into your
|
|
460
|
+
project (for Claude Code: `.claude/skills/build-hand-off-shop/SKILL.md`). A page for it on
|
|
461
|
+
handoff.store/developers is coming soon.
|
|
462
|
+
|
|
463
|
+
## License
|
|
464
|
+
|
|
465
|
+
MIT
|