@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/index.mjs
ADDED
|
@@ -0,0 +1,713 @@
|
|
|
1
|
+
// libs/storefront/src/core/errors.ts
|
|
2
|
+
var HandOffError = class _HandOffError extends Error {
|
|
3
|
+
constructor(code, message, details = {}) {
|
|
4
|
+
super(message);
|
|
5
|
+
this.name = "HandOffError";
|
|
6
|
+
this.code = code;
|
|
7
|
+
this.status = details.status ?? 0;
|
|
8
|
+
if (details.reason !== void 0) this.reason = details.reason;
|
|
9
|
+
if (details.fields !== void 0) this.fields = details.fields;
|
|
10
|
+
if (details.retryAfterMs !== void 0) this.retryAfterMs = details.retryAfterMs;
|
|
11
|
+
if (details.formToken !== void 0) this.formToken = details.formToken;
|
|
12
|
+
Object.setPrototypeOf(this, _HandOffError.prototype);
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
var invalidArgument = (message) => new HandOffError("INVALID_ARGUMENT", message);
|
|
16
|
+
|
|
17
|
+
// libs/storefront/src/core/transport.ts
|
|
18
|
+
function segment(value, what) {
|
|
19
|
+
const text = typeof value === "string" ? value.trim() : typeof value === "number" && Number.isFinite(value) ? String(value) : "";
|
|
20
|
+
if (text === "" || text === "." || text === ".." || text.length > 512) throw invalidArgument(`${what} is not valid.`);
|
|
21
|
+
return encodeURIComponent(text);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// libs/storefront/src/core/cart.ts
|
|
25
|
+
var quantityOf = (value, minimum) => {
|
|
26
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < minimum || value > 100) throw invalidArgument(`quantity is a whole number from ${minimum} to 100.`);
|
|
27
|
+
return value;
|
|
28
|
+
};
|
|
29
|
+
function cartResource(transport, discount, changed) {
|
|
30
|
+
const tell = (cart) => {
|
|
31
|
+
changed(cart);
|
|
32
|
+
return cart;
|
|
33
|
+
};
|
|
34
|
+
let queue = Promise.resolve();
|
|
35
|
+
let waiting = 0;
|
|
36
|
+
let started = 0;
|
|
37
|
+
const write = (work) => {
|
|
38
|
+
waiting++;
|
|
39
|
+
started++;
|
|
40
|
+
const answered = queue.then(work).then(
|
|
41
|
+
(cart) => {
|
|
42
|
+
waiting--;
|
|
43
|
+
return tell(cart);
|
|
44
|
+
},
|
|
45
|
+
(error) => {
|
|
46
|
+
waiting--;
|
|
47
|
+
throw error;
|
|
48
|
+
}
|
|
49
|
+
);
|
|
50
|
+
queue = answered.catch(() => void 0);
|
|
51
|
+
return answered;
|
|
52
|
+
};
|
|
53
|
+
let reads = 0;
|
|
54
|
+
let readTold = 0;
|
|
55
|
+
return {
|
|
56
|
+
async get() {
|
|
57
|
+
const quiet = waiting === 0;
|
|
58
|
+
const mark = started;
|
|
59
|
+
const order = ++reads;
|
|
60
|
+
const cart = (await transport.request("GET", "cart")).data;
|
|
61
|
+
if (!quiet || mark !== started || order < readTold) return cart;
|
|
62
|
+
readTold = order;
|
|
63
|
+
return tell(cart);
|
|
64
|
+
},
|
|
65
|
+
async add(item) {
|
|
66
|
+
if (!item || typeof item.productId !== "string" || !item.productId) throw invalidArgument("Send { productId }.");
|
|
67
|
+
const body = {
|
|
68
|
+
productId: item.productId,
|
|
69
|
+
quantity: quantityOf(item.quantity ?? 1, 1),
|
|
70
|
+
...item.combinationKey !== void 0 ? { combinationKey: item.combinationKey } : {},
|
|
71
|
+
...item.selectedAddOns !== void 0 ? { selectedAddOns: item.selectedAddOns } : {},
|
|
72
|
+
...item.personalizationText !== void 0 ? { personalizationText: item.personalizationText } : {}
|
|
73
|
+
};
|
|
74
|
+
return write(async () => (await transport.request("POST", "cart/items", body)).data);
|
|
75
|
+
},
|
|
76
|
+
async update(lineId, change) {
|
|
77
|
+
const path = `cart/items/${segment(lineId, "The cart line id")}`;
|
|
78
|
+
const wanted = typeof change === "number" ? { quantity: change } : change;
|
|
79
|
+
const body = {
|
|
80
|
+
quantity: quantityOf(wanted?.quantity, 0),
|
|
81
|
+
...wanted.combinationKey !== void 0 ? { combinationKey: wanted.combinationKey } : {},
|
|
82
|
+
...wanted.personalizationText !== void 0 ? { personalizationText: wanted.personalizationText } : {}
|
|
83
|
+
};
|
|
84
|
+
return write(async () => (await transport.request("PATCH", path, body)).data);
|
|
85
|
+
},
|
|
86
|
+
async remove(lineId) {
|
|
87
|
+
const path = `cart/items/${segment(lineId, "The cart line id")}`;
|
|
88
|
+
return write(async () => (await transport.request("DELETE", path)).data);
|
|
89
|
+
},
|
|
90
|
+
async clear() {
|
|
91
|
+
return write(async () => (await transport.request("DELETE", "cart")).data);
|
|
92
|
+
},
|
|
93
|
+
async applyDiscount(code) {
|
|
94
|
+
const cleaned = discount.checked(code);
|
|
95
|
+
return write(() => discount.apply(cleaned));
|
|
96
|
+
},
|
|
97
|
+
async removeDiscount(code) {
|
|
98
|
+
const cleaned = discount.checked(code);
|
|
99
|
+
return write(() => discount.remove(cleaned));
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// libs/storefront/src/core/collections.ts
|
|
105
|
+
function collectionsResource(transport) {
|
|
106
|
+
return {
|
|
107
|
+
async list() {
|
|
108
|
+
return (await transport.request("GET", "collections")).data;
|
|
109
|
+
},
|
|
110
|
+
async get(idOrSlug) {
|
|
111
|
+
return (await transport.request("GET", `collections/${segment(idOrSlug, "The collection")}`)).data;
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// libs/storefront/src/core/discount.ts
|
|
117
|
+
var DISCOUNT_CODE_MAX_LENGTH = 64;
|
|
118
|
+
function discountResource(transport) {
|
|
119
|
+
const clean = (code) => {
|
|
120
|
+
const text = typeof code === "string" ? code.trim() : "";
|
|
121
|
+
if (!text || text.length > DISCOUNT_CODE_MAX_LENGTH) throw invalidArgument("Send a discount code.");
|
|
122
|
+
return text;
|
|
123
|
+
};
|
|
124
|
+
return {
|
|
125
|
+
checked: clean,
|
|
126
|
+
async apply(code) {
|
|
127
|
+
return (await transport.request("POST", "cart/discount-codes", { code: clean(code) }, { retry: false })).data;
|
|
128
|
+
},
|
|
129
|
+
async remove(code) {
|
|
130
|
+
return (await transport.request("DELETE", `cart/discount-codes/${segment(clean(code), "The discount code")}`, void 0, { retry: false })).data;
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// libs/storefront/src/core/content.ts
|
|
136
|
+
function contentResource(transport) {
|
|
137
|
+
return {
|
|
138
|
+
async list(collection) {
|
|
139
|
+
return (await transport.request("GET", `content/${segment(collection, "The content collection")}`)).data;
|
|
140
|
+
},
|
|
141
|
+
async get(collection, item) {
|
|
142
|
+
return (await transport.request("GET", `content/${segment(collection, "The content collection")}/${segment(item, "The content entry")}`)).data;
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// libs/storefront/src/core/menus.ts
|
|
148
|
+
function menusResource(transport) {
|
|
149
|
+
return {
|
|
150
|
+
async get() {
|
|
151
|
+
return (await transport.request("GET", "menus")).data;
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// libs/storefront/src/core/products.ts
|
|
157
|
+
var DATABASE_ID = /^[a-f0-9]{24}$/i;
|
|
158
|
+
function productPath(ref) {
|
|
159
|
+
if (typeof ref === "string") return DATABASE_ID.test(ref) ? `products/${segment(ref, "The product id")}` : `products/by-slug/${segment(ref, "The product slug")}`;
|
|
160
|
+
if (ref && "id" in ref) return `products/${segment(ref.id, "The product id")}`;
|
|
161
|
+
if (ref && "slug" in ref) return `products/by-slug/${segment(ref.slug, "The product slug")}`;
|
|
162
|
+
throw invalidArgument("Name a product by its id or slug.");
|
|
163
|
+
}
|
|
164
|
+
function productsResource(transport) {
|
|
165
|
+
const get = async (ref) => (await transport.request("GET", productPath(ref))).data;
|
|
166
|
+
return {
|
|
167
|
+
async list(query = {}) {
|
|
168
|
+
const answer = await transport.request("GET", "products", void 0, {
|
|
169
|
+
query: {
|
|
170
|
+
limit: query.limit,
|
|
171
|
+
cursor: query.cursor,
|
|
172
|
+
search: query.search,
|
|
173
|
+
collectionId: query.collectionId,
|
|
174
|
+
categoryId: query.categoryId,
|
|
175
|
+
brandId: query.brandId,
|
|
176
|
+
sort: query.sort,
|
|
177
|
+
inStock: query.inStock ? "1" : void 0,
|
|
178
|
+
onSale: query.onSale ? "1" : void 0
|
|
179
|
+
}
|
|
180
|
+
});
|
|
181
|
+
return { items: answer.data, nextCursor: answer.page?.nextCursor ?? null };
|
|
182
|
+
},
|
|
183
|
+
get,
|
|
184
|
+
async variants(ref) {
|
|
185
|
+
return (await get(ref)).variants;
|
|
186
|
+
},
|
|
187
|
+
async related(productId, options = {}) {
|
|
188
|
+
return (await transport.request("GET", `products/${segment(productId, "The product id")}/related`, void 0, { query: { limit: options.limit } })).data;
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// libs/storefront/src/core/store.ts
|
|
194
|
+
function storeResource(transport) {
|
|
195
|
+
return {
|
|
196
|
+
async hours() {
|
|
197
|
+
const store = (await transport.request("GET", "store")).data;
|
|
198
|
+
const { isOpenNow, nextOpenAt, closesAt, closureUntil } = store.ordering;
|
|
199
|
+
return { timezone: store.timezone, hours: store.hours, ordering: { isOpenNow, nextOpenAt, closesAt, closureUntil }, fulfillment: store.fulfillment };
|
|
200
|
+
},
|
|
201
|
+
async policies() {
|
|
202
|
+
return (await transport.request("GET", "policies")).data.policies;
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// libs/storefront/src/entry/format.ts
|
|
208
|
+
function moneyFormatter(language, storeCurrency) {
|
|
209
|
+
const formatters = /* @__PURE__ */ new Map();
|
|
210
|
+
const formatterOf = (currency) => {
|
|
211
|
+
let entry = formatters.get(currency);
|
|
212
|
+
if (!entry) {
|
|
213
|
+
let format;
|
|
214
|
+
try {
|
|
215
|
+
format = new Intl.NumberFormat(language || void 0, { style: "currency", currency });
|
|
216
|
+
} catch {
|
|
217
|
+
format = new Intl.NumberFormat("en", { style: "currency", currency: /^[A-Za-z]{3}$/.test(currency) ? currency : "USD" });
|
|
218
|
+
}
|
|
219
|
+
entry = { format, digits: format.resolvedOptions().maximumFractionDigits ?? 2 };
|
|
220
|
+
formatters.set(currency, entry);
|
|
221
|
+
}
|
|
222
|
+
return entry;
|
|
223
|
+
};
|
|
224
|
+
return (amount, currency) => {
|
|
225
|
+
const value = typeof amount === "number" && Number.isFinite(amount) ? amount : 0;
|
|
226
|
+
const { format, digits } = formatterOf(typeof currency === "string" && currency ? currency : storeCurrency);
|
|
227
|
+
return format.format(value / 10 ** digits);
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// libs/storefront/src/transport/session.ts
|
|
232
|
+
var copy = (value) => ({
|
|
233
|
+
token: value.token,
|
|
234
|
+
expiresAt: value.expiresAt,
|
|
235
|
+
...value.kind !== void 0 ? { kind: value.kind } : {},
|
|
236
|
+
...value.refreshToken !== void 0 ? { refreshToken: value.refreshToken } : {},
|
|
237
|
+
...value.refreshExpiresAt !== void 0 ? { refreshExpiresAt: value.refreshExpiresAt } : {}
|
|
238
|
+
});
|
|
239
|
+
function memorySession(initial = null) {
|
|
240
|
+
let value = initial ? copy(initial) : null;
|
|
241
|
+
return {
|
|
242
|
+
get: () => value ? copy(value) : null,
|
|
243
|
+
set: (next) => {
|
|
244
|
+
value = next ? copy(next) : null;
|
|
245
|
+
}
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
function storageSession(storage, key = "handoff.session", now = () => Date.now()) {
|
|
249
|
+
const fallback = memorySession();
|
|
250
|
+
let usable = true;
|
|
251
|
+
const read = () => {
|
|
252
|
+
let text;
|
|
253
|
+
try {
|
|
254
|
+
text = storage.getItem(key);
|
|
255
|
+
} catch {
|
|
256
|
+
usable = false;
|
|
257
|
+
return fallback.get();
|
|
258
|
+
}
|
|
259
|
+
if (!text) return null;
|
|
260
|
+
try {
|
|
261
|
+
const parsed = JSON.parse(text);
|
|
262
|
+
if (typeof parsed.token !== "string" || parsed.token === "" || typeof parsed.expiresAt !== "string") return null;
|
|
263
|
+
if (parsed.kind === "shopper" || parsed.refreshToken !== void 0) return null;
|
|
264
|
+
const expires = Date.parse(parsed.expiresAt);
|
|
265
|
+
if (Number.isFinite(expires) && expires <= now()) return null;
|
|
266
|
+
return { token: parsed.token, expiresAt: parsed.expiresAt };
|
|
267
|
+
} catch {
|
|
268
|
+
return null;
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
let shopper = null;
|
|
272
|
+
return {
|
|
273
|
+
get: () => shopper ? copy(shopper) : usable ? read() : fallback.get(),
|
|
274
|
+
set: (next) => {
|
|
275
|
+
const isShopper = next !== null && (next.kind === "shopper" || next.refreshToken !== void 0);
|
|
276
|
+
shopper = isShopper && next ? copy(next) : null;
|
|
277
|
+
fallback.set(isShopper ? null : next);
|
|
278
|
+
if (!usable) return;
|
|
279
|
+
try {
|
|
280
|
+
if (next && !isShopper) storage.setItem(key, JSON.stringify(copy(next)));
|
|
281
|
+
else storage.removeItem(key);
|
|
282
|
+
} catch {
|
|
283
|
+
usable = false;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
// libs/storefront/src/transport/key.ts
|
|
290
|
+
var PUBLISHABLE_KEY_HEADER = "X-Storefront-Key";
|
|
291
|
+
var STOREFRONT_API_PATH = "storefront/api/v1/";
|
|
292
|
+
var LOCAL_HOSTNAMES = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
293
|
+
var RESERVED_HEADERS = /* @__PURE__ */ new Set(["authorization", PUBLISHABLE_KEY_HEADER.toLowerCase(), "cookie", "host", "content-type", "accept"]);
|
|
294
|
+
var DEFAULT_TIMEOUT_MS = 15e3;
|
|
295
|
+
function storefrontApiBase(shop) {
|
|
296
|
+
const refuse = () => new HandOffError("INVALID_ARGUMENT", "The shop address is not valid. Give its https address, such as https://acme.handoff.market.");
|
|
297
|
+
if (typeof shop !== "string" || shop.trim() === "") throw refuse();
|
|
298
|
+
let url;
|
|
299
|
+
try {
|
|
300
|
+
url = new URL(shop.trim());
|
|
301
|
+
} catch {
|
|
302
|
+
throw refuse();
|
|
303
|
+
}
|
|
304
|
+
const secure = url.protocol === "https:" || url.protocol === "http:" && LOCAL_HOSTNAMES.has(url.hostname);
|
|
305
|
+
if (!secure || url.username || url.password || url.search || url.hash) throw refuse();
|
|
306
|
+
const parts = url.pathname.split("/").filter((part) => part !== "");
|
|
307
|
+
if (parts.length > 2 || parts.some((part) => part === "." || part === "..")) throw refuse();
|
|
308
|
+
return `${url.origin}${parts.map((part) => `/${part}`).join("")}/${STOREFRONT_API_PATH}`;
|
|
309
|
+
}
|
|
310
|
+
function globalFetch() {
|
|
311
|
+
const found = globalThis.fetch;
|
|
312
|
+
if (typeof found !== "function") {
|
|
313
|
+
throw new HandOffError("INVALID_ARGUMENT", "No fetch here: pass `fetch` (Node 18 and later, and every browser, have one).");
|
|
314
|
+
}
|
|
315
|
+
return (url, init) => found.call(globalThis, url, init);
|
|
316
|
+
}
|
|
317
|
+
function understoodAnswer(status, text) {
|
|
318
|
+
let parsed;
|
|
319
|
+
try {
|
|
320
|
+
parsed = text === "" ? void 0 : JSON.parse(text);
|
|
321
|
+
} catch {
|
|
322
|
+
parsed = void 0;
|
|
323
|
+
}
|
|
324
|
+
const body = typeof parsed === "object" && parsed !== null ? parsed : null;
|
|
325
|
+
if (status >= 200 && status < 300 && body && Object.prototype.hasOwnProperty.call(body, "data")) {
|
|
326
|
+
const page = body["page"];
|
|
327
|
+
if (typeof page !== "object" || page === null) return { data: body["data"] };
|
|
328
|
+
const nextCursor = page["nextCursor"];
|
|
329
|
+
return { data: body["data"], page: { nextCursor: typeof nextCursor === "string" ? nextCursor : null } };
|
|
330
|
+
}
|
|
331
|
+
const error = body && typeof body["error"] === "object" && body["error"] !== null ? body["error"] : null;
|
|
332
|
+
const code = error?.["code"];
|
|
333
|
+
if (!error || typeof code !== "string") {
|
|
334
|
+
throw new HandOffError(status === 429 ? "RATE_LIMITED" : "INVALID_RESPONSE", status === 429 ? "Too many requests." : "The answer was not understood.", { status });
|
|
335
|
+
}
|
|
336
|
+
const message = typeof error["message"] === "string" && error["message"] ? error["message"].slice(0, 500) : "The request was refused.";
|
|
337
|
+
const fields = error["fields"];
|
|
338
|
+
const cleanFields = {};
|
|
339
|
+
if (typeof fields === "object" && fields !== null) {
|
|
340
|
+
for (const [name, value] of Object.entries(fields)) if (typeof value === "string") cleanFields[name] = value;
|
|
341
|
+
}
|
|
342
|
+
throw new HandOffError(code, message, {
|
|
343
|
+
status,
|
|
344
|
+
...typeof error["reason"] === "string" ? { reason: error["reason"] } : {},
|
|
345
|
+
...Object.keys(cleanFields).length > 0 ? { fields: cleanFields } : {},
|
|
346
|
+
...typeof error["retryAfterMs"] === "number" ? { retryAfterMs: error["retryAfterMs"] } : {},
|
|
347
|
+
...typeof error["formToken"] === "string" && error["formToken"] ? { formToken: error["formToken"] } : {}
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
function createKeyTransport(options) {
|
|
351
|
+
const base = storefrontApiBase(options.shop);
|
|
352
|
+
const baseUrl = new URL(base);
|
|
353
|
+
const session = options.session ?? memorySession();
|
|
354
|
+
const fetch = options.fetch ?? globalFetch();
|
|
355
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
356
|
+
const key = typeof options.publishableKey === "string" ? options.publishableKey.trim() : "";
|
|
357
|
+
if (options.publishableKey !== void 0 && (key === "" || /[\s\r\n]/.test(key) || key.length > 256)) {
|
|
358
|
+
throw new HandOffError("INVALID_ARGUMENT", "The publishable key is not valid.");
|
|
359
|
+
}
|
|
360
|
+
const extra = {};
|
|
361
|
+
for (const [name, value] of Object.entries(options.headers ?? {})) {
|
|
362
|
+
if (RESERVED_HEADERS.has(name.toLowerCase())) throw new HandOffError("INVALID_ARGUMENT", `The header ${name} is set by the library.`);
|
|
363
|
+
if (typeof value !== "string" || /[\r\n]/.test(value)) throw new HandOffError("INVALID_ARGUMENT", `The header ${name} is not valid.`);
|
|
364
|
+
extra[name] = value;
|
|
365
|
+
}
|
|
366
|
+
const addressOf = (path, query) => {
|
|
367
|
+
const outside = () => new HandOffError("INVALID_ARGUMENT", "That address is outside the storefront API.");
|
|
368
|
+
let url;
|
|
369
|
+
try {
|
|
370
|
+
url = new URL(base + path.replace(/^\/+/, ""));
|
|
371
|
+
} catch {
|
|
372
|
+
throw outside();
|
|
373
|
+
}
|
|
374
|
+
if (url.origin !== baseUrl.origin || !url.pathname.startsWith(baseUrl.pathname) || url.username || url.password) throw outside();
|
|
375
|
+
url.search = "";
|
|
376
|
+
url.hash = "";
|
|
377
|
+
for (const [name, value] of Object.entries(query ?? {})) {
|
|
378
|
+
if (value === void 0 || value === null || value === "") continue;
|
|
379
|
+
url.searchParams.set(name, String(value));
|
|
380
|
+
}
|
|
381
|
+
const address = url.toString();
|
|
382
|
+
if (!address.startsWith(base)) throw outside();
|
|
383
|
+
return address;
|
|
384
|
+
};
|
|
385
|
+
return {
|
|
386
|
+
base,
|
|
387
|
+
session,
|
|
388
|
+
async request(method, path, body, requestOptions = {}) {
|
|
389
|
+
const address = addressOf(path, requestOptions.query);
|
|
390
|
+
const headers = { ...extra, Accept: "application/json" };
|
|
391
|
+
if (body !== void 0) headers["Content-Type"] = "application/json";
|
|
392
|
+
if (key) headers[PUBLISHABLE_KEY_HEADER] = key;
|
|
393
|
+
const held = requestOptions.auth === false ? null : session.get();
|
|
394
|
+
if (held && held.token) headers["Authorization"] = `Bearer ${held.token}`;
|
|
395
|
+
const controller = timeoutMs > 0 && typeof AbortController === "function" ? new AbortController() : null;
|
|
396
|
+
const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
|
|
397
|
+
let status;
|
|
398
|
+
let text;
|
|
399
|
+
try {
|
|
400
|
+
const init = { method, headers, credentials: "omit", redirect: "error", ...controller ? { signal: controller.signal } : {} };
|
|
401
|
+
if (body !== void 0) init.body = JSON.stringify(body);
|
|
402
|
+
const answer = await fetch(address, init);
|
|
403
|
+
status = answer.status;
|
|
404
|
+
text = await answer.text();
|
|
405
|
+
if (typeof status !== "number" || typeof text !== "string") throw new TypeError("not an answer");
|
|
406
|
+
} catch {
|
|
407
|
+
throw new HandOffError("NETWORK_ERROR", controller?.signal.aborted ? "The request timed out." : "The request did not complete.");
|
|
408
|
+
} finally {
|
|
409
|
+
if (timer) clearTimeout(timer);
|
|
410
|
+
}
|
|
411
|
+
return understoodAnswer(status, text);
|
|
412
|
+
}
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
// libs/storefront/src/sdk/checkout.ts
|
|
417
|
+
function linesOfCart(cart) {
|
|
418
|
+
return cart.items.filter((item) => item.isGift !== true).map((item) => {
|
|
419
|
+
const addOns = Array.isArray(item.addOns) ? item.addOns.filter((addOn) => typeof addOn.addOnId === "string" && typeof addOn["optionId"] === "string").map((addOn) => ({ addOnId: addOn.addOnId, selectedOptionId: addOn["optionId"], quantity: addOn.quantity })) : [];
|
|
420
|
+
return {
|
|
421
|
+
productId: item.productId,
|
|
422
|
+
...item.combinationKey ? { combinationKey: item.combinationKey } : {},
|
|
423
|
+
quantity: item.quantity,
|
|
424
|
+
...addOns.length ? { selectedAddOns: addOns } : {},
|
|
425
|
+
...item.personalization?.value ? { personalizationText: item.personalization.value } : {}
|
|
426
|
+
};
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
var CHECKOUT_LINK_ID = /^cs_[A-Za-z0-9_-]{1,128}$/;
|
|
430
|
+
function checkoutResource(transport, cart) {
|
|
431
|
+
const create = async (input) => {
|
|
432
|
+
if (!input || typeof input.successUrl !== "string" || !input.successUrl) throw invalidArgument("Send { successUrl }.");
|
|
433
|
+
if (!Array.isArray(input.lines) || input.lines.length === 0 || input.lines.length > 100) throw invalidArgument("A checkout link takes 1 to 100 lines.");
|
|
434
|
+
const body = {
|
|
435
|
+
lines: input.lines,
|
|
436
|
+
successUrl: input.successUrl,
|
|
437
|
+
...input.cancelUrl !== void 0 ? { cancelUrl: input.cancelUrl } : {},
|
|
438
|
+
...input.expiresInMinutes !== void 0 ? { expiresInMinutes: input.expiresInMinutes } : {}
|
|
439
|
+
};
|
|
440
|
+
return (await transport.request("POST", "checkout-links", body, { retry: false, auth: false })).data;
|
|
441
|
+
};
|
|
442
|
+
const get = async (checkoutLinkId) => (await transport.request("GET", `checkout-links/${segment(checkoutLinkId, "The checkout link id")}`, void 0, { auth: false })).data;
|
|
443
|
+
return {
|
|
444
|
+
create,
|
|
445
|
+
async fromCart(input) {
|
|
446
|
+
const lines = linesOfCart(await cart.get());
|
|
447
|
+
if (lines.length === 0) throw new HandOffError("INVALID_ARGUMENT", "The cart is empty.");
|
|
448
|
+
return create({ ...input, lines });
|
|
449
|
+
},
|
|
450
|
+
get,
|
|
451
|
+
async handleReturn(address, options = {}) {
|
|
452
|
+
let url;
|
|
453
|
+
try {
|
|
454
|
+
url = typeof address === "string" ? new URL(address) : address;
|
|
455
|
+
} catch {
|
|
456
|
+
return null;
|
|
457
|
+
}
|
|
458
|
+
const id = url.searchParams.get("handoff_checkout_link");
|
|
459
|
+
if (!id || !CHECKOUT_LINK_ID.test(id)) return null;
|
|
460
|
+
const state = await get(id);
|
|
461
|
+
const paid = state.status === "COMPLETED";
|
|
462
|
+
if (paid && options.clearCart !== false) await cart.clear().catch(() => void 0);
|
|
463
|
+
return { checkoutLinkId: state.checkoutLinkId, status: state.status, orderNumber: state.orderNumber, paid };
|
|
464
|
+
}
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
// libs/storefront/src/sdk/session.ts
|
|
469
|
+
var SESSION_PREFIX = "session/";
|
|
470
|
+
var RENEW_BEFORE_MS = 6e4;
|
|
471
|
+
var isCartWrite = (method, path) => method !== "GET" && /^cart(?:\/|$)/.test(path);
|
|
472
|
+
var parsedTime = (value) => {
|
|
473
|
+
const time = value ? Date.parse(value) : NaN;
|
|
474
|
+
return Number.isFinite(time) ? time : NaN;
|
|
475
|
+
};
|
|
476
|
+
function shopperSession(tokens) {
|
|
477
|
+
return { token: tokens.accessToken, expiresAt: tokens.accessTokenExpiresAt, kind: "shopper", refreshToken: tokens.refreshToken, refreshExpiresAt: tokens.refreshTokenExpiresAt };
|
|
478
|
+
}
|
|
479
|
+
function sessionTransport(inner, now = () => Date.now()) {
|
|
480
|
+
const session = inner.session;
|
|
481
|
+
let creating = null;
|
|
482
|
+
let refreshing = null;
|
|
483
|
+
const createCartToken = () => {
|
|
484
|
+
if (creating) return creating;
|
|
485
|
+
creating = (async () => {
|
|
486
|
+
try {
|
|
487
|
+
const made = (await inner.request("POST", `${SESSION_PREFIX}cart-token`, void 0, { retry: false, auth: false })).data;
|
|
488
|
+
if (!made || typeof made.token !== "string" || !made.token) throw new HandOffError("INVALID_RESPONSE", "The answer was not understood.");
|
|
489
|
+
session.set({ token: made.token, expiresAt: made.expiresAt, kind: "cart" });
|
|
490
|
+
} finally {
|
|
491
|
+
creating = null;
|
|
492
|
+
}
|
|
493
|
+
})();
|
|
494
|
+
return creating;
|
|
495
|
+
};
|
|
496
|
+
const refresh = () => {
|
|
497
|
+
if (refreshing) return refreshing;
|
|
498
|
+
const held = session.get();
|
|
499
|
+
if (!held || held.kind !== "shopper" || !held.refreshToken) {
|
|
500
|
+
return Promise.reject(new HandOffError("SIGN_IN_REQUIRED", "The shopper is not signed in.", { status: 401 }));
|
|
501
|
+
}
|
|
502
|
+
const refreshToken = held.refreshToken;
|
|
503
|
+
refreshing = (async () => {
|
|
504
|
+
try {
|
|
505
|
+
let tokens;
|
|
506
|
+
try {
|
|
507
|
+
tokens = (await inner.request("POST", `${SESSION_PREFIX}shopper/refresh`, { refreshToken }, { retry: false, auth: false })).data;
|
|
508
|
+
} catch (error) {
|
|
509
|
+
if (!(error instanceof HandOffError && error.code === "NETWORK_ERROR") && session.get()?.refreshToken === refreshToken) session.set(null);
|
|
510
|
+
throw error;
|
|
511
|
+
}
|
|
512
|
+
if (!tokens || typeof tokens.accessToken !== "string" || typeof tokens.refreshToken !== "string") {
|
|
513
|
+
throw new HandOffError("INVALID_RESPONSE", "The answer was not understood.");
|
|
514
|
+
}
|
|
515
|
+
session.set(shopperSession(tokens));
|
|
516
|
+
} finally {
|
|
517
|
+
refreshing = null;
|
|
518
|
+
}
|
|
519
|
+
})();
|
|
520
|
+
return refreshing;
|
|
521
|
+
};
|
|
522
|
+
const ready = async () => {
|
|
523
|
+
if (refreshing) await refreshing.catch(() => void 0);
|
|
524
|
+
const held = session.get();
|
|
525
|
+
if (!held || held.kind !== "shopper" || !held.refreshToken) return;
|
|
526
|
+
const left = parsedTime(held.expiresAt) - now();
|
|
527
|
+
const refreshLeft = parsedTime(held.refreshExpiresAt) - now();
|
|
528
|
+
if (left > RENEW_BEFORE_MS) return;
|
|
529
|
+
if (refreshLeft <= 0) {
|
|
530
|
+
session.set(null);
|
|
531
|
+
return;
|
|
532
|
+
}
|
|
533
|
+
await refresh();
|
|
534
|
+
};
|
|
535
|
+
const ensureCartToken = async () => {
|
|
536
|
+
await ready();
|
|
537
|
+
if (!session.get()) await createCartToken();
|
|
538
|
+
};
|
|
539
|
+
return {
|
|
540
|
+
session,
|
|
541
|
+
ensureCartToken,
|
|
542
|
+
refresh,
|
|
543
|
+
async request(method, path, body, options = {}) {
|
|
544
|
+
const write = isCartWrite(method, path);
|
|
545
|
+
if (write) await ensureCartToken();
|
|
546
|
+
else await ready();
|
|
547
|
+
const sentWith = session.get();
|
|
548
|
+
try {
|
|
549
|
+
return await inner.request(method, SESSION_PREFIX + path, body, options);
|
|
550
|
+
} catch (error) {
|
|
551
|
+
if (!(error instanceof HandOffError) || error.status !== 401) throw error;
|
|
552
|
+
const code = error.code;
|
|
553
|
+
if (sentWith?.kind === "shopper" && code === "TOKEN_EXPIRED" && options.retry !== false) {
|
|
554
|
+
if (session.get()?.token === sentWith.token) await refresh();
|
|
555
|
+
return inner.request(method, SESSION_PREFIX + path, body, options);
|
|
556
|
+
}
|
|
557
|
+
if (sentWith?.kind === "cart" && (code === "TOKEN_INVALID" || code === "TOKEN_EXPIRED")) {
|
|
558
|
+
if (session.get()?.token === sentWith.token) session.set(null);
|
|
559
|
+
if (write && options.retry !== false) {
|
|
560
|
+
await createCartToken();
|
|
561
|
+
return inner.request(method, SESSION_PREFIX + path, body, options);
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
throw error;
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
};
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
// libs/storefront/src/sdk/shopper.ts
|
|
571
|
+
var PHONE = /^\+[1-9]\d{6,14}$/;
|
|
572
|
+
function shopperResource(transport) {
|
|
573
|
+
const signedInHere = () => transport.session.get()?.kind === "shopper";
|
|
574
|
+
const taken = (answer) => {
|
|
575
|
+
if ("needsProfile" in answer && answer.needsProfile) {
|
|
576
|
+
return { signedIn: false, needsProfile: true, registrationToken: answer.registrationToken, requirements: answer.requirements };
|
|
577
|
+
}
|
|
578
|
+
if (!("accessToken" in answer) || typeof answer.accessToken !== "string" || typeof answer.refreshToken !== "string") {
|
|
579
|
+
throw new HandOffError("INVALID_RESPONSE", "The answer was not understood.");
|
|
580
|
+
}
|
|
581
|
+
transport.session.set(shopperSession(answer));
|
|
582
|
+
return { signedIn: true, shopper: answer.shopper, cartMerged: answer.cartMerged === true };
|
|
583
|
+
};
|
|
584
|
+
return {
|
|
585
|
+
async start(phone) {
|
|
586
|
+
if (typeof phone !== "string" || !PHONE.test(phone.trim())) throw invalidArgument("Give the phone number in international form, such as +15551234567.");
|
|
587
|
+
return (await transport.request("POST", "shopper/start", { phone: phone.trim() }, { retry: false })).data;
|
|
588
|
+
},
|
|
589
|
+
async verify(input) {
|
|
590
|
+
if (!input || typeof input.phone !== "string" || typeof input.code !== "string" || !input.code.trim()) throw invalidArgument("Send { phone, code }.");
|
|
591
|
+
return taken((await transport.request("POST", "shopper/verify", { ...input, phone: input.phone.trim(), code: input.code.trim() }, { retry: false })).data);
|
|
592
|
+
},
|
|
593
|
+
async register(input) {
|
|
594
|
+
if (!input || typeof input.registrationToken !== "string" || !input.registrationToken) throw invalidArgument("Send { registrationToken }.");
|
|
595
|
+
return taken((await transport.request("POST", "shopper/register", input, { retry: false })).data);
|
|
596
|
+
},
|
|
597
|
+
email: {
|
|
598
|
+
async start(input) {
|
|
599
|
+
return (await transport.request("POST", "shopper/email/start", input, { retry: false })).data;
|
|
600
|
+
},
|
|
601
|
+
async verify(input) {
|
|
602
|
+
return (await transport.request("POST", "shopper/email/verify", input, { retry: false })).data;
|
|
603
|
+
}
|
|
604
|
+
},
|
|
605
|
+
async get() {
|
|
606
|
+
if (!signedInHere()) return null;
|
|
607
|
+
try {
|
|
608
|
+
return (await transport.request("GET", "shopper")).data;
|
|
609
|
+
} catch (error) {
|
|
610
|
+
if (error instanceof HandOffError && error.status === 401) return null;
|
|
611
|
+
throw error;
|
|
612
|
+
}
|
|
613
|
+
},
|
|
614
|
+
signedIn: signedInHere,
|
|
615
|
+
async signOut() {
|
|
616
|
+
const held = transport.session.get();
|
|
617
|
+
if (!held || held.kind !== "shopper") return;
|
|
618
|
+
try {
|
|
619
|
+
await transport.request("POST", "shopper/logout", held.refreshToken ? { refreshToken: held.refreshToken } : void 0, { retry: false });
|
|
620
|
+
} catch (error) {
|
|
621
|
+
if (!(error instanceof HandOffError) || error.code === "NETWORK_ERROR") {
|
|
622
|
+
transport.session.set(null);
|
|
623
|
+
throw error;
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
transport.session.set(null);
|
|
627
|
+
}
|
|
628
|
+
};
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
// libs/storefront/src/sdk/storefront.ts
|
|
632
|
+
var EMPTY_CART = Object.freeze(emptyCart());
|
|
633
|
+
function emptyCart() {
|
|
634
|
+
return {
|
|
635
|
+
currency: "",
|
|
636
|
+
items: [],
|
|
637
|
+
productsTotal: 0,
|
|
638
|
+
cartSubtotal: 0,
|
|
639
|
+
subtotal: 0,
|
|
640
|
+
discount: 0,
|
|
641
|
+
cartAddOns: [],
|
|
642
|
+
cartAddOnsTotal: 0,
|
|
643
|
+
shippingDiscount: 0,
|
|
644
|
+
shipping: 0,
|
|
645
|
+
paymentFee: 0,
|
|
646
|
+
total: 0,
|
|
647
|
+
itemCount: 0,
|
|
648
|
+
needsAttention: false,
|
|
649
|
+
attentionReason: null,
|
|
650
|
+
appliedDiscounts: [],
|
|
651
|
+
rejectedCodes: [],
|
|
652
|
+
appliedCodes: []
|
|
653
|
+
};
|
|
654
|
+
}
|
|
655
|
+
function createStorefront(options) {
|
|
656
|
+
const transport = createKeyTransport(options);
|
|
657
|
+
const store = storeResource(transport);
|
|
658
|
+
const sessions = sessionTransport(transport);
|
|
659
|
+
const cart = cartResource(sessions, discountResource(sessions), options.onCartChange ?? (() => void 0));
|
|
660
|
+
const cartGet = async () => transport.session.get() ? cart.get() : emptyCart();
|
|
661
|
+
const cartClear = async () => transport.session.get() ? cart.clear() : emptyCart();
|
|
662
|
+
return {
|
|
663
|
+
store: {
|
|
664
|
+
async get() {
|
|
665
|
+
return (await transport.request("GET", "store")).data;
|
|
666
|
+
},
|
|
667
|
+
hours: store.hours,
|
|
668
|
+
policies: store.policies
|
|
669
|
+
},
|
|
670
|
+
products: productsResource(transport),
|
|
671
|
+
variants: {
|
|
672
|
+
async get(variantId) {
|
|
673
|
+
return (await transport.request("GET", `variants/${segment(variantId, "The variant id")}`)).data;
|
|
674
|
+
}
|
|
675
|
+
},
|
|
676
|
+
collections: collectionsResource(transport),
|
|
677
|
+
categories: {
|
|
678
|
+
async list() {
|
|
679
|
+
return (await transport.request("GET", "categories")).data;
|
|
680
|
+
}
|
|
681
|
+
},
|
|
682
|
+
pages: {
|
|
683
|
+
async list() {
|
|
684
|
+
return (await transport.request("GET", "pages")).data;
|
|
685
|
+
},
|
|
686
|
+
async byPath(path) {
|
|
687
|
+
if (typeof path !== "string" || !path.startsWith("/") || path.length > 512) throw invalidArgument("Give the path from the shop root, such as /about.");
|
|
688
|
+
return (await transport.request("GET", "pages/by-path", void 0, { query: { path } })).data;
|
|
689
|
+
}
|
|
690
|
+
},
|
|
691
|
+
content: contentResource(transport),
|
|
692
|
+
menus: menusResource(transport),
|
|
693
|
+
cart: { ...cart, get: cartGet, clear: cartClear },
|
|
694
|
+
shopper: shopperResource(sessions),
|
|
695
|
+
checkout: checkoutResource(transport, { get: cartGet, clear: cartClear }),
|
|
696
|
+
transport
|
|
697
|
+
};
|
|
698
|
+
}
|
|
699
|
+
function formatMoney(amount, currency, language = "en") {
|
|
700
|
+
return moneyFormatter(language, currency)(amount);
|
|
701
|
+
}
|
|
702
|
+
export {
|
|
703
|
+
EMPTY_CART,
|
|
704
|
+
HandOffError,
|
|
705
|
+
PUBLISHABLE_KEY_HEADER,
|
|
706
|
+
createKeyTransport,
|
|
707
|
+
createStorefront,
|
|
708
|
+
formatMoney,
|
|
709
|
+
linesOfCart,
|
|
710
|
+
memorySession,
|
|
711
|
+
storageSession,
|
|
712
|
+
storefrontApiBase
|
|
713
|
+
};
|