@hand-off/storefront 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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,207 @@
1
- # Temporary Holding Version
1
+ # @hand-off/storefront
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Build a shop on any stack against a [Hand-Off](https://hand-off.net) store: Next.js, Astro, Remix,
4
+ SvelteKit, a static page, or your own server. The library reads the store's catalogue and pages,
5
+ and (as each server part ships) keeps the visitor's cart, signs shoppers in and sends them to
6
+ Hand-Off's checkout.
7
+
8
+ - No dependencies. ES module and CommonJS builds, with TypeScript types for every answer.
9
+ - The same client the store builder's own pages run on (`window.HandOff` on a sealed page).
10
+ - Money is always an integer in minor units (cents) with its `currency`.
11
+
12
+ > **Status: preview (0.x).** The catalogue reads work today. The cart and shopper sign-in work
13
+ > where the store has token sessions on, checkout where it has checkout links on. Methods are
14
+ > added, never renamed.
15
+
16
+ ## Install
17
+
18
+ ```bash
19
+ npm install @hand-off/storefront
20
+ ```
21
+
22
+ ## Quick start
23
+
24
+ ```ts
25
+ import { createStorefront, formatMoney } from '@hand-off/storefront';
26
+
27
+ const shop = createStorefront({
28
+ shop: 'https://acme.handoff.market', // the shop's address: a handoff.market address or its own domain
29
+ });
30
+
31
+ const store = await shop.store.get();
32
+ const { items, nextCursor } = await shop.products.list({ limit: 12 });
33
+
34
+ for (const product of items) {
35
+ console.log(product.name, formatMoney(product.price, product.currency, store.language));
36
+ }
37
+ ```
38
+
39
+ `shop` is the address shoppers visit. In an organization with several stores, add the store's
40
+ slug: `https://acme.handoff.market/bakery`.
41
+
42
+ ## Where it runs
43
+
44
+ | Where | Today |
45
+ | --- | --- |
46
+ | A server: Node 18+, Next.js server components and route handlers, Remix/SvelteKit loaders, Astro, edge runtimes | Yes |
47
+ | 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 |
48
+
49
+ The store's owner creates the key, lists your site's exact origin (such as
50
+ `https://shop.example.com`, or `http://localhost:3000` while developing) and switches storefront
51
+ keys on for the store. Without a key, call the library from server code and send your page the
52
+ result.
53
+
54
+ ## What it reads
55
+
56
+ | Call | Answers |
57
+ | --- | --- |
58
+ | `store.get()` | The store: name, `url`, `currency`, `language`, branding, contact, hours, fulfillment |
59
+ | `store.hours()` | Opening hours, whether orders are taken now, each fulfillment method's hours |
60
+ | `store.policies()` | The policy pages |
61
+ | `products.list(query?)` | `{ items, nextCursor }`. `query`: `limit`, `cursor`, `search`, `collectionId`, `categoryId`, `brandId`, `sort`, `inStock`, `onSale` |
62
+ | `products.get(ref)` | One product with its media, options and variants; `ref` is an id, a slug, `{ id }` or `{ slug }` |
63
+ | `products.variants(ref)` | Its variants: price, stock and the `key` the cart takes |
64
+ | `products.related(productId, { limit }?)` | Products shown beside it |
65
+ | `variants.get(variantId)` | `{ variant, product }` |
66
+ | `collections.list()`, `collections.get(idOrSlug)` | Collections |
67
+ | `categories.list()` | Product categories, top-level first, then subcategories (`parentId`), with `url` and `productCount` |
68
+ | `pages.list()`, `pages.byPath('/about')` | The store's pages, and whatever lives at a path (a page, a blog list, an entry, a redirect) |
69
+ | `content.list(collection)`, `content.get(collection, entry)` | The store's own content collections (a blog, a team) |
70
+ | `menus.get()` | `{ header, footer }` |
71
+
72
+ Paging: pass `nextCursor` back as `cursor`; it is `null` on the last page.
73
+
74
+ ## Cart and shopper sign-in
75
+
76
+ These need the store's token sessions switched on and, in a browser, a publishable key.
77
+
78
+ ```ts
79
+ const shop = createStorefront({
80
+ shop: 'https://acme.handoff.market',
81
+ publishableKey: 'hopk_…',
82
+ session: storageSession(localStorage, 'acme.cart'), // keeps a guest's cart across visits
83
+ onCartChange: (cart) => renderBag(cart),
84
+ });
85
+
86
+ await shop.cart.add({ productId: product.id, combinationKey: variant.key, quantity: 1 });
87
+ const cart = await shop.cart.get(); // lines, list prices, itemCount
88
+ await shop.cart.update(cart.lines[0].id, 3); // 0 removes the line
89
+ await shop.cart.remove(lineId);
90
+
91
+ await shop.shopper.start('+15551234567'); // texts a sign-in code
92
+ const result = await shop.shopper.verify({ phone: '+15551234567', code: '123456' });
93
+ if (!result.signedIn) await shop.shopper.register({ registrationToken: result.registrationToken, firstName: 'Ada' });
94
+ await shop.cart.applyDiscount('SAVE10'); // discount codes need a signed-in shopper
95
+ await shop.shopper.signOut();
96
+ ```
97
+
98
+ - The first cart write makes the visitor's cart token; `cart.get()` before that answers an empty
99
+ cart without calling. On sign-in the guest's cart is merged into the shopper's.
100
+ - The library keeps every token in its `session` and renews a shopper's 15-minute access token on
101
+ its own. No method hands a token back.
102
+ - A discount code is sent once per call, never retried.
103
+
104
+ | Call | Does |
105
+ | --- | --- |
106
+ | `cart.get()`, `cart.add(item)`, `cart.update(lineId, quantity \| change)`, `cart.remove(lineId)`, `cart.clear()` | The visitor's cart |
107
+ | `cart.applyDiscount(code)`, `cart.removeDiscount(code)` | Discount codes (signed-in shoppers) |
108
+ | `shopper.start(phone)`, `shopper.verify({ phone, code })`, `shopper.register({ registrationToken, … })` | Sign in or sign up with a text-message code |
109
+ | `shopper.email.start({ email })`, `shopper.email.verify({ email, code })` | Stores that check email |
110
+ | `shopper.get()`, `shopper.signedIn()`, `shopper.signOut()` | The signed-in shopper |
111
+
112
+ ## Checkout
113
+
114
+ Payment happens on Hand-Off's checkout page. Make a one-time checkout link and send the shopper
115
+ to it; they come back to your `successUrl`. Needs the store's storefront key, and both addresses
116
+ must be on one of that key's allowed sites.
117
+
118
+ ```ts
119
+ // The bag's "Pay" button
120
+ const link = await shop.checkout.fromCart({
121
+ successUrl: 'https://shop.example.com/thanks',
122
+ cancelUrl: 'https://shop.example.com/bag',
123
+ });
124
+ location.assign(link.url);
125
+
126
+ // On https://shop.example.com/thanks
127
+ const result = await shop.checkout.handleReturn(location.href);
128
+ if (result?.paid) showThanks(result.orderNumber); // confirmed with the API, cart emptied
129
+ ```
130
+
131
+ | Call | Does |
132
+ | --- | --- |
133
+ | `checkout.fromCart({ successUrl, cancelUrl?, expiresInMinutes? })` | A link for the lines in the visitor's cart |
134
+ | `checkout.create({ lines, successUrl, cancelUrl?, expiresInMinutes? })` | A link for lines you name (`productId`, `combinationKey`, `quantity`, add-ons, personalization) |
135
+ | `checkout.get(checkoutLinkId)` | `OPEN`, `COMPLETED` with its `orderNumber`, or `EXPIRED` |
136
+ | `checkout.handleReturn(url)` | Reads `?handoff_checkout_link=` from the return address and confirms it; null when it is not a return |
137
+
138
+ - A link works once and lasts 60 minutes unless `expiresInMinutes` (5 to 1440) says otherwise.
139
+ - `handoff_order` in the return address is only a hint: trust `handleReturn(...).paid`.
140
+ - `INVALID_REQUEST` with `reason: 'RETURN_URL_REFUSED'`: an address is not on the key's allowed
141
+ sites. `UNAVAILABLE` with `reason: 'CHECKOUT_LINKS_OFF'`: the store has no checkout links.
142
+
143
+ ## Errors
144
+
145
+ Every failure rejects with a `HandOffError`. Branch on `code`, never on `message`:
146
+
147
+ ```ts
148
+ import { HandOffError } from '@hand-off/storefront';
149
+
150
+ try {
151
+ await shop.products.get('no-such-thing');
152
+ } catch (error) {
153
+ if (error instanceof HandOffError && error.code === 'NOT_FOUND') return notFound();
154
+ throw error;
155
+ }
156
+ ```
157
+
158
+ | Code | Means |
159
+ | --- | --- |
160
+ | `NOT_FOUND` | No such record, or it is not shown to shoppers (a draft, unpublished, hidden) |
161
+ | `AUTH_REQUIRED`, `REGISTRATION_REQUIRED`, `PENDING_APPROVAL` | A private store: the shopper must sign in or be approved |
162
+ | `RATE_LIMITED` | Slow down; `retryAfterMs` when the API says how long |
163
+ | `INVALID_ARGUMENT` | Refused before sending (a bad shop address, an empty id) |
164
+ | `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 |
165
+ | `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) |
166
+ | `SIGN_IN_REQUIRED` | Sign the shopper in first (discount codes) |
167
+ | `OUT_OF_STOCK`, `DISCOUNT_REFUSED` | The cart change was refused; `message` says why |
168
+ | `NETWORK_ERROR` | Nothing came back (offline, DNS, timeout after `timeoutMs`) |
169
+ | `INVALID_RESPONSE` | The answer was not the API's |
170
+
171
+ Mixing the ES module and CommonJS builds in one program gives two `HandOffError` classes; check
172
+ `error.name === 'HandOffError'` and `error.code` if you do.
173
+
174
+ ## Options
175
+
176
+ ```ts
177
+ createStorefront({
178
+ shop: 'https://acme.handoff.market',
179
+ publishableKey: 'hopk_…', // the store's publishable storefront key: safe to ship to browsers
180
+ session: storageSession(localStorage, 'acme.session'), // where the visitor's cart or shopper token is kept; memory by default
181
+ fetch, // your own fetch; the global one by default
182
+ headers: { 'Accept-Language': 'fr' },
183
+ timeoutMs: 15000,
184
+ });
185
+ ```
186
+
187
+ - `memorySession()` keeps the token for the life of the process or page. On a server, make one
188
+ storefront per request (or pass a `Session` backed by your own session store) so two visitors
189
+ never share a cart.
190
+ - `storageSession(storage, key)` keeps it in `localStorage` or `sessionStorage`. **Cart tokens
191
+ only:** every script on your site can read Web Storage, and a shopper's sign-in token reaches
192
+ their account. Keep a signed-in shopper's tokens in `memorySession()` or in an HttpOnly cookie
193
+ your own server sets (a `Session` of your own).
194
+ - No cookie is ever sent: the library carries the visitor's session itself.
195
+
196
+ `shop.transport.request(method, path, body?, { query })` calls any route under
197
+ `/storefront/api/v1/` the library has no method for yet.
198
+
199
+ ## Building a shop with a coding agent
200
+
201
+ The Hand-Off developer pages publish a skill (instructions a coding agent such as Claude Code
202
+ follows) for building a shop with this library: https://hand-off.net/developers/storefront-sdk/SKILL.md.
203
+ It is in the package too: `node_modules/@hand-off/storefront/skill/SKILL.md`.
204
+
205
+ ## License
206
+
207
+ MIT