@cimplify/sdk 0.16.3 → 0.17.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/dist/advanced.js +90 -2913
- package/dist/advanced.mjs +3 -2893
- package/dist/chunk-FLPI2VVJ.js +72 -0
- package/dist/chunk-G6KNFYJD.mjs +687 -0
- package/dist/chunk-GFKBH7R2.mjs +2759 -0
- package/dist/chunk-J65U5SED.js +714 -0
- package/dist/chunk-LM3CJ4L7.mjs +69 -0
- package/dist/chunk-OITG2SEN.js +692 -0
- package/dist/chunk-OVM5YWM5.mjs +674 -0
- package/dist/chunk-REPTMTQ4.js +2810 -0
- package/dist/chunk-S6TU55KP.js +170 -0
- package/dist/chunk-WDIMISRC.mjs +166 -0
- package/dist/index.js +401 -4420
- package/dist/index.mjs +5 -4325
- package/dist/react.d.mts +9 -4
- package/dist/react.d.ts +9 -4
- package/dist/react.js +377 -3968
- package/dist/react.mjs +326 -3920
- package/dist/utils.js +122 -721
- package/dist/utils.mjs +2 -695
- package/package.json +1 -1
- package/registry/add-on-selector.json +1 -1
- package/registry/checkout-page.json +1 -1
- package/registry/composite-selector.json +1 -1
- package/registry/product-grid.json +1 -1
package/dist/advanced.mjs
CHANGED
|
@@ -1,2893 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
}
|
|
5
|
-
function err(error) {
|
|
6
|
-
return { ok: false, error };
|
|
7
|
-
}
|
|
8
|
-
|
|
9
|
-
// src/types/common.ts
|
|
10
|
-
function money(value) {
|
|
11
|
-
return typeof value === "string" ? parseFloat(value) || 0 : value;
|
|
12
|
-
}
|
|
13
|
-
function moneyFromNumber(value) {
|
|
14
|
-
return value;
|
|
15
|
-
}
|
|
16
|
-
function currencyCode(value) {
|
|
17
|
-
return value;
|
|
18
|
-
}
|
|
19
|
-
var ErrorCode = {
|
|
20
|
-
UNKNOWN_ERROR: "UNKNOWN_ERROR",
|
|
21
|
-
NOT_FOUND: "NOT_FOUND"};
|
|
22
|
-
var DOCS_ERROR_BASE_URL = "https://docs.cimplify.io/reference/error-codes";
|
|
23
|
-
function docsUrlForCode(code) {
|
|
24
|
-
return `${DOCS_ERROR_BASE_URL}#${code.toLowerCase().replace(/_/g, "-")}`;
|
|
25
|
-
}
|
|
26
|
-
var ERROR_SUGGESTIONS = {
|
|
27
|
-
UNKNOWN_ERROR: "An unexpected error occurred. Capture the request/response payload and retry with exponential backoff.",
|
|
28
|
-
NETWORK_ERROR: "Check the shopper's connection and retry. If this persists, inspect CORS, DNS, and API reachability.",
|
|
29
|
-
TIMEOUT: "The request exceeded the timeout. Retry once, then poll order status before charging again.",
|
|
30
|
-
UNAUTHORIZED: "Authentication is missing or expired. Ensure a valid access token is set and refresh the session if needed.",
|
|
31
|
-
FORBIDDEN: "The key/session lacks permission for this resource. Verify business ownership and API key scope.",
|
|
32
|
-
NOT_FOUND: "The requested resource does not exist or is not visible in this environment.",
|
|
33
|
-
VALIDATION_ERROR: "One or more fields are invalid. Validate required fields and enum values before retrying.",
|
|
34
|
-
CART_EMPTY: "The cart has no items. Redirect back to menu/catalogue and require at least one line item.",
|
|
35
|
-
CART_EXPIRED: "This cart is no longer active. Recreate a new cart and re-add shopper selections.",
|
|
36
|
-
CART_NOT_FOUND: "Cart could not be located. It may have expired or belongs to a different key/location.",
|
|
37
|
-
ITEM_UNAVAILABLE: "The selected item is unavailable at this location/time. Prompt the shopper to pick an alternative.",
|
|
38
|
-
VARIANT_NOT_FOUND: "The requested variant no longer exists. Refresh product data and require re-selection.",
|
|
39
|
-
VARIANT_OUT_OF_STOCK: "The selected variant is out of stock. Show in-stock variants and block checkout for this line.",
|
|
40
|
-
ADDON_REQUIRED: "A required add-on is missing. Ensure required modifier groups are completed before add-to-cart.",
|
|
41
|
-
ADDON_MAX_EXCEEDED: "Too many add-ons were selected. Enforce max selections client-side before submission.",
|
|
42
|
-
CHECKOUT_VALIDATION_FAILED: "Checkout payload failed validation. Verify customer, order type, and address fields are complete.",
|
|
43
|
-
DELIVERY_ADDRESS_REQUIRED: "Delivery orders require an address. Collect and pass address info before processing checkout.",
|
|
44
|
-
CUSTOMER_INFO_REQUIRED: "Customer details are required. Ensure name/email/phone are available before checkout.",
|
|
45
|
-
QUOTE_NOT_FOUND: "Quote could not be found. Refresh pricing and create a new quote before checkout.",
|
|
46
|
-
QUOTE_EXPIRED: "Quote has expired. Re-fetch pricing to generate a new quote with a valid expiry window.",
|
|
47
|
-
QUOTE_CONSUMED: "Quote has already been used. Request a fresh quote to prevent duplicate checkout attempts.",
|
|
48
|
-
QUOTE_STORAGE_UNAVAILABLE: "Quote storage is temporarily unavailable. Retry shortly and avoid charging until quote fetch succeeds.",
|
|
49
|
-
PAYMENT_FAILED: "Payment provider rejected or failed processing. Show retry/change-method options to the shopper.",
|
|
50
|
-
PAYMENT_CANCELLED: "Payment was cancelled by the shopper or provider flow. Allow a safe retry path.",
|
|
51
|
-
INSUFFICIENT_FUNDS: "Payment method has insufficient funds. Prompt shopper to use another method.",
|
|
52
|
-
CARD_DECLINED: "Card was declined. Ask shopper to retry or switch payment method.",
|
|
53
|
-
INVALID_OTP: "Authorization code is invalid. Let shopper re-enter OTP/PIN and retry.",
|
|
54
|
-
OTP_EXPIRED: "Authorization code expired. Request a new OTP and re-submit authorization.",
|
|
55
|
-
AUTHORIZATION_FAILED: "Additional payment authorization failed. Retry authorization or change payment method.",
|
|
56
|
-
PAYMENT_ACTION_NOT_COMPLETED: "Required payment action was not completed. Resume provider flow and poll for status.",
|
|
57
|
-
SLOT_UNAVAILABLE: "Selected schedule slot is unavailable. Refresh available slots and ask shopper to reselect.",
|
|
58
|
-
BOOKING_CONFLICT: "The requested booking conflicts with an existing reservation. Pick another slot/resource.",
|
|
59
|
-
SERVICE_NOT_FOUND: "Requested service no longer exists. Refresh service catalogue and retry selection.",
|
|
60
|
-
OUT_OF_STOCK: "Inventory is depleted for this item. Remove it or reduce quantity before checkout.",
|
|
61
|
-
INSUFFICIENT_QUANTITY: "Requested quantity exceeds available inventory. Reduce quantity and retry.",
|
|
62
|
-
BUSINESS_ID_REQUIRED: "Business context could not be resolved. Verify the public key and business bootstrap call.",
|
|
63
|
-
INVALID_CART: "Cart is invalid for checkout. Sync cart state, ensure items exist, then retry.",
|
|
64
|
-
ORDER_TYPE_REQUIRED: "Order type is required. Provide one of delivery, pickup, or dine_in before checkout.",
|
|
65
|
-
NO_PAYMENT_ELEMENT: "PaymentElement is required for processCheckout(). Mount it before triggering checkout.",
|
|
66
|
-
PAYMENT_NOT_MOUNTED: "PaymentElement iframe is not mounted. Mount it in the DOM before processCheckout().",
|
|
67
|
-
AUTH_INCOMPLETE: "AuthElement has not completed authentication. Wait for AUTHENTICATED before checkout.",
|
|
68
|
-
AUTH_LOST: "Session was cleared during checkout. Re-authenticate and restart checkout safely.",
|
|
69
|
-
ALREADY_PROCESSING: "Checkout is already in progress. Disable duplicate submits until completion.",
|
|
70
|
-
CHECKOUT_NOT_READY: "Checkout elements are still initializing. Wait for readiness before submit.",
|
|
71
|
-
CANCELLED: "Checkout was cancelled. Preserve cart state and allow shopper to retry.",
|
|
72
|
-
REQUEST_TIMEOUT: "Provider call timed out. Poll payment/order status before issuing another charge attempt.",
|
|
73
|
-
POPUP_BLOCKED: "Browser blocked provider popup. Ask shopper to enable popups and retry.",
|
|
74
|
-
FX_QUOTE_FAILED: "Failed to lock FX quote. Retry currency quote or fallback to base currency."
|
|
75
|
-
};
|
|
76
|
-
var ERROR_HINTS = Object.fromEntries(
|
|
77
|
-
Object.entries(ERROR_SUGGESTIONS).map(([code, suggestion]) => [
|
|
78
|
-
code,
|
|
79
|
-
{
|
|
80
|
-
docs_url: docsUrlForCode(code),
|
|
81
|
-
suggestion
|
|
82
|
-
}
|
|
83
|
-
])
|
|
84
|
-
);
|
|
85
|
-
var CimplifyError = class extends Error {
|
|
86
|
-
constructor(code, message, retryable = false, docs_url, suggestion) {
|
|
87
|
-
super(message);
|
|
88
|
-
this.code = code;
|
|
89
|
-
this.retryable = retryable;
|
|
90
|
-
this.docs_url = docs_url;
|
|
91
|
-
this.suggestion = suggestion;
|
|
92
|
-
this.name = "CimplifyError";
|
|
93
|
-
}
|
|
94
|
-
get userMessage() {
|
|
95
|
-
return this.message;
|
|
96
|
-
}
|
|
97
|
-
};
|
|
98
|
-
function getErrorHint(code) {
|
|
99
|
-
return ERROR_HINTS[code];
|
|
100
|
-
}
|
|
101
|
-
function enrichError(error, options = {}) {
|
|
102
|
-
const hint = getErrorHint(error.code);
|
|
103
|
-
if (hint) {
|
|
104
|
-
if (!error.docs_url) {
|
|
105
|
-
error.docs_url = hint.docs_url;
|
|
106
|
-
}
|
|
107
|
-
if (!error.suggestion) {
|
|
108
|
-
error.suggestion = hint.suggestion;
|
|
109
|
-
}
|
|
110
|
-
} else if (!error.docs_url) {
|
|
111
|
-
error.docs_url = docsUrlForCode(error.code || ErrorCode.UNKNOWN_ERROR);
|
|
112
|
-
}
|
|
113
|
-
if (options.isTestMode && !error.message.includes("pk_test_")) {
|
|
114
|
-
error.message = `${error.message}
|
|
115
|
-
|
|
116
|
-
\u2139 Your API key is a test-mode key (pk_test_...). Verify test data/session before retrying.`;
|
|
117
|
-
}
|
|
118
|
-
return error;
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
// src/internal/safe.ts
|
|
122
|
-
function toCimplifyError(error) {
|
|
123
|
-
if (error instanceof CimplifyError) return enrichError(error);
|
|
124
|
-
if (error instanceof Error) {
|
|
125
|
-
return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, error.message, false));
|
|
126
|
-
}
|
|
127
|
-
return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, String(error), false));
|
|
128
|
-
}
|
|
129
|
-
async function safe(promise) {
|
|
130
|
-
try {
|
|
131
|
-
return ok(await promise);
|
|
132
|
-
} catch (error) {
|
|
133
|
-
return err(toCimplifyError(error));
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
// src/catalogue.ts
|
|
138
|
-
function withQuery(path, params) {
|
|
139
|
-
const query2 = new URLSearchParams();
|
|
140
|
-
for (const [key, value] of Object.entries(params)) {
|
|
141
|
-
if (value === void 0) continue;
|
|
142
|
-
query2.set(key, String(value));
|
|
143
|
-
}
|
|
144
|
-
const queryString = query2.toString();
|
|
145
|
-
return queryString ? `${path}?${queryString}` : path;
|
|
146
|
-
}
|
|
147
|
-
function isRecord(value) {
|
|
148
|
-
return typeof value === "object" && value !== null;
|
|
149
|
-
}
|
|
150
|
-
function readFinalPrice(value) {
|
|
151
|
-
if (!isRecord(value)) return void 0;
|
|
152
|
-
const finalPrice = value.final_price;
|
|
153
|
-
if (typeof finalPrice === "string" || typeof finalPrice === "number") {
|
|
154
|
-
return finalPrice;
|
|
155
|
-
}
|
|
156
|
-
return void 0;
|
|
157
|
-
}
|
|
158
|
-
function normalizeAddOnPayload(addOn) {
|
|
159
|
-
if (!isRecord(addOn)) return addOn;
|
|
160
|
-
const normalizedAddOn = { ...addOn };
|
|
161
|
-
const options = normalizedAddOn["options"];
|
|
162
|
-
if (!Array.isArray(options)) return normalizedAddOn;
|
|
163
|
-
normalizedAddOn["options"] = options.map((option) => {
|
|
164
|
-
if (!isRecord(option)) return option;
|
|
165
|
-
const normalizedOption = { ...option };
|
|
166
|
-
const optionPrice = normalizedOption["default_price"];
|
|
167
|
-
if (optionPrice === void 0 || optionPrice === null || optionPrice === "") {
|
|
168
|
-
normalizedOption["default_price"] = readFinalPrice(normalizedOption["default_price_info"]) || readFinalPrice(normalizedOption["price_info"]) || "0";
|
|
169
|
-
}
|
|
170
|
-
return normalizedOption;
|
|
171
|
-
});
|
|
172
|
-
return normalizedAddOn;
|
|
173
|
-
}
|
|
174
|
-
function normalizeCatalogueProductPayload(product) {
|
|
175
|
-
const normalized = { ...product };
|
|
176
|
-
const defaultPrice = normalized["default_price"];
|
|
177
|
-
if (defaultPrice === void 0 || defaultPrice === null || defaultPrice === "") {
|
|
178
|
-
const derivedDefaultPrice = readFinalPrice(normalized["default_price_info"]) || readFinalPrice(normalized["price_info"]) || (typeof normalized["final_price"] === "string" || typeof normalized["final_price"] === "number" ? normalized["final_price"] : void 0);
|
|
179
|
-
normalized["default_price"] = derivedDefaultPrice ?? "0";
|
|
180
|
-
}
|
|
181
|
-
const addOns = normalized["add_ons"];
|
|
182
|
-
if (Array.isArray(addOns)) {
|
|
183
|
-
normalized["add_ons"] = addOns.map((addOn) => normalizeAddOnPayload(addOn));
|
|
184
|
-
}
|
|
185
|
-
return normalized;
|
|
186
|
-
}
|
|
187
|
-
function toFiniteNumber(value) {
|
|
188
|
-
if (typeof value === "number" && Number.isFinite(value)) {
|
|
189
|
-
return value;
|
|
190
|
-
}
|
|
191
|
-
if (typeof value === "string" && value.trim().length > 0) {
|
|
192
|
-
const parsed = Number(value);
|
|
193
|
-
if (Number.isFinite(parsed)) {
|
|
194
|
-
return parsed;
|
|
195
|
-
}
|
|
196
|
-
}
|
|
197
|
-
return void 0;
|
|
198
|
-
}
|
|
199
|
-
function normalizePagination(value) {
|
|
200
|
-
if (!isRecord(value)) {
|
|
201
|
-
return void 0;
|
|
202
|
-
}
|
|
203
|
-
const totalCount = toFiniteNumber(value.total_count);
|
|
204
|
-
const currentPage = toFiniteNumber(value.current_page);
|
|
205
|
-
const pageSize = toFiniteNumber(value.page_size);
|
|
206
|
-
const totalPages = toFiniteNumber(value.total_pages);
|
|
207
|
-
if (totalCount === void 0 || currentPage === void 0 || pageSize === void 0 || totalPages === void 0) {
|
|
208
|
-
return void 0;
|
|
209
|
-
}
|
|
210
|
-
return {
|
|
211
|
-
total_count: totalCount,
|
|
212
|
-
current_page: currentPage,
|
|
213
|
-
page_size: pageSize,
|
|
214
|
-
total_pages: totalPages,
|
|
215
|
-
has_more: value.has_more === true,
|
|
216
|
-
next_cursor: typeof value.next_cursor === "string" ? value.next_cursor : void 0
|
|
217
|
-
};
|
|
218
|
-
}
|
|
219
|
-
function normalizeCatalogueResult(payload) {
|
|
220
|
-
if (Array.isArray(payload)) {
|
|
221
|
-
return {
|
|
222
|
-
items: payload.map((product) => normalizeCatalogueProductPayload(product)),
|
|
223
|
-
is_complete: true
|
|
224
|
-
};
|
|
225
|
-
}
|
|
226
|
-
if (!isRecord(payload)) {
|
|
227
|
-
return {
|
|
228
|
-
items: [],
|
|
229
|
-
is_complete: true
|
|
230
|
-
};
|
|
231
|
-
}
|
|
232
|
-
const rawItems = Array.isArray(payload.products) ? payload.products : Array.isArray(payload.items) ? payload.items : [];
|
|
233
|
-
return {
|
|
234
|
-
items: rawItems.map((product) => normalizeCatalogueProductPayload(product)),
|
|
235
|
-
is_complete: typeof payload.is_complete === "boolean" ? payload.is_complete : true,
|
|
236
|
-
total_available: toFiniteNumber(payload.total_available),
|
|
237
|
-
pagination: normalizePagination(payload.pagination)
|
|
238
|
-
};
|
|
239
|
-
}
|
|
240
|
-
function normalizeCatalogueSnapshot(payload) {
|
|
241
|
-
if (Array.isArray(payload)) {
|
|
242
|
-
return {
|
|
243
|
-
categories: [],
|
|
244
|
-
products: payload.map((product) => normalizeCatalogueProductPayload(product)),
|
|
245
|
-
add_ons: [],
|
|
246
|
-
is_complete: true
|
|
247
|
-
};
|
|
248
|
-
}
|
|
249
|
-
if (!isRecord(payload)) {
|
|
250
|
-
return {
|
|
251
|
-
categories: [],
|
|
252
|
-
products: [],
|
|
253
|
-
add_ons: [],
|
|
254
|
-
is_complete: true
|
|
255
|
-
};
|
|
256
|
-
}
|
|
257
|
-
const rawProducts = Array.isArray(payload.products) ? payload.products : Array.isArray(payload.items) ? payload.items : [];
|
|
258
|
-
const rawCategories = Array.isArray(payload.categories) ? payload.categories : [];
|
|
259
|
-
const rawAddOns = Array.isArray(payload.add_ons) ? payload.add_ons : [];
|
|
260
|
-
return {
|
|
261
|
-
categories: rawCategories,
|
|
262
|
-
products: rawProducts.map((product) => normalizeCatalogueProductPayload(product)),
|
|
263
|
-
add_ons: rawAddOns.map((addOn) => normalizeAddOnPayload(addOn)),
|
|
264
|
-
is_complete: typeof payload.is_complete === "boolean" ? payload.is_complete : true,
|
|
265
|
-
total_available: toFiniteNumber(payload.total_available),
|
|
266
|
-
pagination: normalizePagination(payload.pagination)
|
|
267
|
-
};
|
|
268
|
-
}
|
|
269
|
-
var CatalogueQueries = class {
|
|
270
|
-
constructor(client) {
|
|
271
|
-
this.client = client;
|
|
272
|
-
}
|
|
273
|
-
async getCatalogue() {
|
|
274
|
-
const result = await safe(this.client.get("/api/v1/catalogue"));
|
|
275
|
-
if (!result.ok) return result;
|
|
276
|
-
return ok(normalizeCatalogueSnapshot(result.value));
|
|
277
|
-
}
|
|
278
|
-
async getProducts(options) {
|
|
279
|
-
const path = withQuery("/api/v1/catalogue/products", {
|
|
280
|
-
category_id: options?.category,
|
|
281
|
-
taxonomy_id: options?.taxonomy,
|
|
282
|
-
search: options?.search,
|
|
283
|
-
page: options?.page,
|
|
284
|
-
tags: options?.tags?.join(","),
|
|
285
|
-
featured: options?.featured,
|
|
286
|
-
in_stock: options?.in_stock,
|
|
287
|
-
min_price: options?.min_price,
|
|
288
|
-
max_price: options?.max_price,
|
|
289
|
-
sort_by: options?.sort_by,
|
|
290
|
-
sort_order: options?.sort_order,
|
|
291
|
-
limit: options?.limit,
|
|
292
|
-
offset: options?.offset,
|
|
293
|
-
cursor: options?.cursor
|
|
294
|
-
});
|
|
295
|
-
const result = await safe(this.client.get(path));
|
|
296
|
-
if (!result.ok) return result;
|
|
297
|
-
return ok(normalizeCatalogueResult(result.value));
|
|
298
|
-
}
|
|
299
|
-
async getProduct(id) {
|
|
300
|
-
const encodedId = encodeURIComponent(id);
|
|
301
|
-
const result = await safe(this.client.get(`/api/v1/catalogue/products/${encodedId}`));
|
|
302
|
-
if (!result.ok) return result;
|
|
303
|
-
return ok(normalizeCatalogueProductPayload(result.value));
|
|
304
|
-
}
|
|
305
|
-
async getProductBySlug(slug) {
|
|
306
|
-
const encodedSlug = encodeURIComponent(slug);
|
|
307
|
-
const result = await safe(this.client.get(`/api/v1/catalogue/products/slug/${encodedSlug}`));
|
|
308
|
-
if (!result.ok) return result;
|
|
309
|
-
return ok(normalizeCatalogueProductPayload(result.value));
|
|
310
|
-
}
|
|
311
|
-
async getVariants(productId) {
|
|
312
|
-
const encodedId = encodeURIComponent(productId);
|
|
313
|
-
return safe(this.client.get(`/api/v1/catalogue/products/${encodedId}/variants`));
|
|
314
|
-
}
|
|
315
|
-
async getVariantAxes(productId) {
|
|
316
|
-
const encodedId = encodeURIComponent(productId);
|
|
317
|
-
return safe(this.client.get(`/api/v1/catalogue/products/${encodedId}/variant-axes`));
|
|
318
|
-
}
|
|
319
|
-
async getVariantByAxisSelections(productId, selections) {
|
|
320
|
-
const encodedId = encodeURIComponent(productId);
|
|
321
|
-
return safe(
|
|
322
|
-
this.client.post(
|
|
323
|
-
`/api/v1/catalogue/products/${encodedId}/variants/find`,
|
|
324
|
-
{ axis_selections: selections }
|
|
325
|
-
)
|
|
326
|
-
);
|
|
327
|
-
}
|
|
328
|
-
async getVariantById(productId, variantId) {
|
|
329
|
-
const encodedProductId = encodeURIComponent(productId);
|
|
330
|
-
const encodedVariantId = encodeURIComponent(variantId);
|
|
331
|
-
return safe(
|
|
332
|
-
this.client.get(
|
|
333
|
-
`/api/v1/catalogue/products/${encodedProductId}/variants/${encodedVariantId}`
|
|
334
|
-
)
|
|
335
|
-
);
|
|
336
|
-
}
|
|
337
|
-
async getAddOns(productId) {
|
|
338
|
-
const encodedId = encodeURIComponent(productId);
|
|
339
|
-
return safe(this.client.get(`/api/v1/catalogue/products/${encodedId}/add-ons`));
|
|
340
|
-
}
|
|
341
|
-
async getCategories() {
|
|
342
|
-
return safe(this.client.get("/api/v1/catalogue/categories"));
|
|
343
|
-
}
|
|
344
|
-
async getCategory(id) {
|
|
345
|
-
const encodedId = encodeURIComponent(id);
|
|
346
|
-
return safe(this.client.get(`/api/v1/catalogue/categories/${encodedId}`));
|
|
347
|
-
}
|
|
348
|
-
async getCategoryBySlug(slug) {
|
|
349
|
-
const encodedSlug = encodeURIComponent(slug);
|
|
350
|
-
return safe(this.client.get(`/api/v1/catalogue/categories/slug/${encodedSlug}`));
|
|
351
|
-
}
|
|
352
|
-
async getCategoryProducts(categoryId) {
|
|
353
|
-
const encodedId = encodeURIComponent(categoryId);
|
|
354
|
-
return safe(this.client.get(`/api/v1/catalogue/categories/${encodedId}/products`));
|
|
355
|
-
}
|
|
356
|
-
async getCollections() {
|
|
357
|
-
return safe(this.client.get("/api/v1/catalogue/collections"));
|
|
358
|
-
}
|
|
359
|
-
async getCollection(id) {
|
|
360
|
-
const encodedId = encodeURIComponent(id);
|
|
361
|
-
return safe(this.client.get(`/api/v1/catalogue/collections/${encodedId}`));
|
|
362
|
-
}
|
|
363
|
-
async getCollectionBySlug(slug) {
|
|
364
|
-
const encodedSlug = encodeURIComponent(slug);
|
|
365
|
-
return safe(this.client.get(`/api/v1/catalogue/collections/slug/${encodedSlug}`));
|
|
366
|
-
}
|
|
367
|
-
async getCollectionProducts(collectionId) {
|
|
368
|
-
const encodedId = encodeURIComponent(collectionId);
|
|
369
|
-
return safe(this.client.get(`/api/v1/catalogue/collections/${encodedId}/products`));
|
|
370
|
-
}
|
|
371
|
-
async searchCollections(query2, limit = 20) {
|
|
372
|
-
const path = withQuery("/api/v1/catalogue/collections", { search: query2, limit });
|
|
373
|
-
return safe(this.client.get(path));
|
|
374
|
-
}
|
|
375
|
-
async getBundles() {
|
|
376
|
-
return safe(this.client.get("/api/v1/catalogue/bundles"));
|
|
377
|
-
}
|
|
378
|
-
async searchBundles(query2, limit = 20) {
|
|
379
|
-
const path = withQuery("/api/v1/catalogue/bundles", { search: query2, limit });
|
|
380
|
-
return safe(this.client.get(path));
|
|
381
|
-
}
|
|
382
|
-
async getComposites(options) {
|
|
383
|
-
const path = withQuery("/api/v1/catalogue/composites", { limit: options?.limit });
|
|
384
|
-
return safe(this.client.get(path));
|
|
385
|
-
}
|
|
386
|
-
async calculateCompositePrice(compositeId, selections, locationId) {
|
|
387
|
-
const encodedId = encodeURIComponent(compositeId);
|
|
388
|
-
return safe(
|
|
389
|
-
this.client.post(
|
|
390
|
-
`/api/v1/catalogue/composites/${encodedId}/calculate-price`,
|
|
391
|
-
{
|
|
392
|
-
selections,
|
|
393
|
-
location_id: locationId
|
|
394
|
-
}
|
|
395
|
-
)
|
|
396
|
-
);
|
|
397
|
-
}
|
|
398
|
-
async fetchQuote(input) {
|
|
399
|
-
return safe(this.client.post("/api/v1/catalogue/quotes", input));
|
|
400
|
-
}
|
|
401
|
-
async getQuote(quoteId) {
|
|
402
|
-
const encodedQuoteId = encodeURIComponent(quoteId);
|
|
403
|
-
return safe(this.client.get(`/api/v1/catalogue/quotes/${encodedQuoteId}`));
|
|
404
|
-
}
|
|
405
|
-
async refreshQuote(input) {
|
|
406
|
-
const encodedQuoteId = encodeURIComponent(input.quote_id);
|
|
407
|
-
return safe(
|
|
408
|
-
this.client.post(
|
|
409
|
-
`/api/v1/catalogue/quotes/${encodedQuoteId}/refresh`,
|
|
410
|
-
input
|
|
411
|
-
)
|
|
412
|
-
);
|
|
413
|
-
}
|
|
414
|
-
async getTaxonomies(parentId) {
|
|
415
|
-
const path = withQuery("/api/v1/catalogue/taxonomies", { parent_id: parentId });
|
|
416
|
-
return safe(this.client.get(path));
|
|
417
|
-
}
|
|
418
|
-
async getTaxonomy(id) {
|
|
419
|
-
const encodedId = encodeURIComponent(id);
|
|
420
|
-
return safe(this.client.get(`/api/v1/catalogue/taxonomies/${encodedId}`));
|
|
421
|
-
}
|
|
422
|
-
async getTaxonomyPath(id) {
|
|
423
|
-
const encodedId = encodeURIComponent(id);
|
|
424
|
-
return safe(this.client.get(`/api/v1/catalogue/taxonomies/${encodedId}/path`));
|
|
425
|
-
}
|
|
426
|
-
async searchTaxonomies(query2, limit) {
|
|
427
|
-
const path = withQuery("/api/v1/catalogue/taxonomies/search", { q: query2, limit });
|
|
428
|
-
return safe(this.client.get(path));
|
|
429
|
-
}
|
|
430
|
-
async getProductSchedules(productId) {
|
|
431
|
-
const encodedId = encodeURIComponent(productId);
|
|
432
|
-
return safe(this.client.get(`/api/v1/catalogue/products/${encodedId}/schedules`));
|
|
433
|
-
}
|
|
434
|
-
async checkProductAvailableNow(productId, locationId) {
|
|
435
|
-
const encodedId = encodeURIComponent(productId);
|
|
436
|
-
const path = withQuery(`/api/v1/catalogue/products/${encodedId}/available-now`, { location_id: locationId });
|
|
437
|
-
return safe(this.client.get(path));
|
|
438
|
-
}
|
|
439
|
-
async getDeals(locationId) {
|
|
440
|
-
const path = withQuery("/api/v1/catalogue/deals", { location_id: locationId });
|
|
441
|
-
return safe(this.client.get(path));
|
|
442
|
-
}
|
|
443
|
-
async getProductsOnSale() {
|
|
444
|
-
return safe(this.client.get("/api/v1/catalogue/deals/on-sale"));
|
|
445
|
-
}
|
|
446
|
-
async getProductDeals(productId) {
|
|
447
|
-
const encodedId = encodeURIComponent(productId);
|
|
448
|
-
return safe(this.client.get(`/api/v1/catalogue/products/${encodedId}/deals`));
|
|
449
|
-
}
|
|
450
|
-
async getCategoryDeals(categoryId) {
|
|
451
|
-
const encodedId = encodeURIComponent(categoryId);
|
|
452
|
-
return safe(this.client.get(`/api/v1/catalogue/categories/${encodedId}/deals`));
|
|
453
|
-
}
|
|
454
|
-
async getCollectionDeals(collectionId) {
|
|
455
|
-
const encodedId = encodeURIComponent(collectionId);
|
|
456
|
-
return safe(this.client.get(`/api/v1/catalogue/collections/${encodedId}/deals`));
|
|
457
|
-
}
|
|
458
|
-
async validateDiscountCode(code, orderSubtotal, locationId) {
|
|
459
|
-
return safe(
|
|
460
|
-
this.client.post("/api/v1/catalogue/deals/validate", {
|
|
461
|
-
discount_code: code,
|
|
462
|
-
order_subtotal: orderSubtotal,
|
|
463
|
-
location_id: locationId
|
|
464
|
-
})
|
|
465
|
-
);
|
|
466
|
-
}
|
|
467
|
-
async search(query2, options) {
|
|
468
|
-
const result = await this.getProducts({
|
|
469
|
-
search: query2,
|
|
470
|
-
category: options?.category,
|
|
471
|
-
limit: options?.limit ?? 20
|
|
472
|
-
});
|
|
473
|
-
if (!result.ok) return result;
|
|
474
|
-
return ok(result.value.items);
|
|
475
|
-
}
|
|
476
|
-
async searchProducts(query2, options) {
|
|
477
|
-
return this.search(query2, options);
|
|
478
|
-
}
|
|
479
|
-
async getMenu(options) {
|
|
480
|
-
const path = withQuery("/api/v1/catalogue/menu", {
|
|
481
|
-
category_id: options?.category,
|
|
482
|
-
limit: options?.limit
|
|
483
|
-
});
|
|
484
|
-
return safe(this.client.get(path));
|
|
485
|
-
}
|
|
486
|
-
async getMenuCategory(categoryId) {
|
|
487
|
-
const encodedId = encodeURIComponent(categoryId);
|
|
488
|
-
return safe(this.client.get(`/api/v1/catalogue/menu/categories/${encodedId}`));
|
|
489
|
-
}
|
|
490
|
-
async getMenuItem(itemId) {
|
|
491
|
-
const encodedId = encodeURIComponent(itemId);
|
|
492
|
-
return safe(this.client.get(`/api/v1/catalogue/menu/items/${encodedId}`));
|
|
493
|
-
}
|
|
494
|
-
async getTags(options) {
|
|
495
|
-
const path = withQuery("/api/v1/catalogue/tags", {
|
|
496
|
-
tag_group: options?.tag_group,
|
|
497
|
-
search: options?.search,
|
|
498
|
-
min_usage: options?.min_usage,
|
|
499
|
-
limit: options?.limit,
|
|
500
|
-
offset: options?.offset
|
|
501
|
-
});
|
|
502
|
-
return safe(this.client.get(path));
|
|
503
|
-
}
|
|
504
|
-
};
|
|
505
|
-
|
|
506
|
-
// src/cart.ts
|
|
507
|
-
function isUICartResponse(value) {
|
|
508
|
-
return "cart" in value;
|
|
509
|
-
}
|
|
510
|
-
function unwrapEnrichedCart(value) {
|
|
511
|
-
return isUICartResponse(value) ? value.cart : value;
|
|
512
|
-
}
|
|
513
|
-
var CartOperations = class {
|
|
514
|
-
constructor(client) {
|
|
515
|
-
this.client = client;
|
|
516
|
-
}
|
|
517
|
-
async get() {
|
|
518
|
-
const result = await safe(this.client.get("/api/v1/cart"));
|
|
519
|
-
if (!result.ok) return result;
|
|
520
|
-
return ok(unwrapEnrichedCart(result.value));
|
|
521
|
-
}
|
|
522
|
-
async getRaw() {
|
|
523
|
-
return safe(this.client.get("/api/v1/cart"));
|
|
524
|
-
}
|
|
525
|
-
async getItems() {
|
|
526
|
-
return safe(this.client.get("/api/v1/cart/items"));
|
|
527
|
-
}
|
|
528
|
-
async getCount() {
|
|
529
|
-
return safe(this.client.get("/api/v1/cart/count"));
|
|
530
|
-
}
|
|
531
|
-
async getTotal() {
|
|
532
|
-
return safe(this.client.get("/api/v1/cart/total"));
|
|
533
|
-
}
|
|
534
|
-
async getSummary() {
|
|
535
|
-
const cartResult = await this.get();
|
|
536
|
-
if (!cartResult.ok) return cartResult;
|
|
537
|
-
const cart = cartResult.value;
|
|
538
|
-
return ok({
|
|
539
|
-
item_count: cart.items.length,
|
|
540
|
-
total_items: cart.items.reduce((sum, item) => sum + item.quantity, 0),
|
|
541
|
-
subtotal: cart.pricing.subtotal,
|
|
542
|
-
discount_amount: cart.pricing.total_discounts,
|
|
543
|
-
tax_amount: cart.pricing.tax_amount,
|
|
544
|
-
total: cart.pricing.total_price,
|
|
545
|
-
currency: cart.pricing.currency
|
|
546
|
-
});
|
|
547
|
-
}
|
|
548
|
-
async addItem(input) {
|
|
549
|
-
return safe(this.client.post("/api/v1/cart/items", input));
|
|
550
|
-
}
|
|
551
|
-
async updateItem(cartItemId, updates) {
|
|
552
|
-
if (typeof updates.quantity === "number") {
|
|
553
|
-
return this.updateQuantity(cartItemId, updates.quantity);
|
|
554
|
-
}
|
|
555
|
-
const encodedId = encodeURIComponent(cartItemId);
|
|
556
|
-
return safe(this.client.patch(`/api/v1/cart/items/${encodedId}`, updates));
|
|
557
|
-
}
|
|
558
|
-
async updateQuantity(cartItemId, quantity) {
|
|
559
|
-
const encodedId = encodeURIComponent(cartItemId);
|
|
560
|
-
return safe(
|
|
561
|
-
this.client.patch(`/api/v1/cart/items/${encodedId}`, {
|
|
562
|
-
quantity
|
|
563
|
-
})
|
|
564
|
-
);
|
|
565
|
-
}
|
|
566
|
-
async removeItem(cartItemId) {
|
|
567
|
-
const encodedId = encodeURIComponent(cartItemId);
|
|
568
|
-
return safe(this.client.delete(`/api/v1/cart/items/${encodedId}`));
|
|
569
|
-
}
|
|
570
|
-
async clear() {
|
|
571
|
-
return safe(this.client.delete("/api/v1/cart"));
|
|
572
|
-
}
|
|
573
|
-
async applyCoupon(code) {
|
|
574
|
-
return safe(
|
|
575
|
-
this.client.post("/api/v1/cart/coupons", {
|
|
576
|
-
coupon_code: code
|
|
577
|
-
})
|
|
578
|
-
);
|
|
579
|
-
}
|
|
580
|
-
async removeCoupon() {
|
|
581
|
-
return safe(this.client.delete("/api/v1/cart/coupons/current"));
|
|
582
|
-
}
|
|
583
|
-
async isEmpty() {
|
|
584
|
-
const countResult = await this.getCount();
|
|
585
|
-
if (!countResult.ok) return countResult;
|
|
586
|
-
return ok(countResult.value === 0);
|
|
587
|
-
}
|
|
588
|
-
async hasItem(productId, variantId) {
|
|
589
|
-
const itemsResult = await this.getItems();
|
|
590
|
-
if (!itemsResult.ok) return itemsResult;
|
|
591
|
-
const found = itemsResult.value.some((item) => {
|
|
592
|
-
const matchesProduct = item.item_id === productId;
|
|
593
|
-
if (!variantId) return matchesProduct;
|
|
594
|
-
const config = item.configuration;
|
|
595
|
-
if ("variant" in config && config.variant) {
|
|
596
|
-
return matchesProduct && config.variant.variant_id === variantId;
|
|
597
|
-
}
|
|
598
|
-
return matchesProduct;
|
|
599
|
-
});
|
|
600
|
-
return ok(found);
|
|
601
|
-
}
|
|
602
|
-
async findItem(productId, variantId) {
|
|
603
|
-
const itemsResult = await this.getItems();
|
|
604
|
-
if (!itemsResult.ok) return itemsResult;
|
|
605
|
-
const found = itemsResult.value.find((item) => {
|
|
606
|
-
const matchesProduct = item.item_id === productId;
|
|
607
|
-
if (!variantId) return matchesProduct;
|
|
608
|
-
const config = item.configuration;
|
|
609
|
-
if ("variant" in config && config.variant) {
|
|
610
|
-
return matchesProduct && config.variant.variant_id === variantId;
|
|
611
|
-
}
|
|
612
|
-
return matchesProduct;
|
|
613
|
-
});
|
|
614
|
-
return ok(found);
|
|
615
|
-
}
|
|
616
|
-
};
|
|
617
|
-
|
|
618
|
-
// src/constants.ts
|
|
619
|
-
var MOBILE_MONEY_PROVIDER = {
|
|
620
|
-
MTN: "mtn",
|
|
621
|
-
VODAFONE: "vodafone",
|
|
622
|
-
AIRTEL: "airtel"
|
|
623
|
-
};
|
|
624
|
-
|
|
625
|
-
// src/utils/payment.ts
|
|
626
|
-
var PAYMENT_SUCCESS_STATUSES = /* @__PURE__ */ new Set([
|
|
627
|
-
"success",
|
|
628
|
-
"succeeded",
|
|
629
|
-
"paid",
|
|
630
|
-
"captured",
|
|
631
|
-
"completed",
|
|
632
|
-
"authorized"
|
|
633
|
-
]);
|
|
634
|
-
var PAYMENT_FAILURE_STATUSES = /* @__PURE__ */ new Set([
|
|
635
|
-
"failed",
|
|
636
|
-
"declined",
|
|
637
|
-
"cancelled",
|
|
638
|
-
"voided",
|
|
639
|
-
"error",
|
|
640
|
-
"abandoned"
|
|
641
|
-
]);
|
|
642
|
-
var PAYMENT_REQUIRES_ACTION_STATUSES = /* @__PURE__ */ new Set([
|
|
643
|
-
"requires_action",
|
|
644
|
-
"requires_payment_method",
|
|
645
|
-
"requires_capture"
|
|
646
|
-
]);
|
|
647
|
-
var PAYMENT_STATUS_ALIAS_MAP = {
|
|
648
|
-
ok: "success",
|
|
649
|
-
done: "success",
|
|
650
|
-
paid: "paid",
|
|
651
|
-
paid_in_full: "paid",
|
|
652
|
-
paid_successfully: "paid",
|
|
653
|
-
succeeded: "success",
|
|
654
|
-
captured: "captured",
|
|
655
|
-
completed: "completed",
|
|
656
|
-
pending_confirmation: "pending_confirmation",
|
|
657
|
-
requires_authorization: "requires_action",
|
|
658
|
-
requires_action: "requires_action",
|
|
659
|
-
requires_payment_method: "requires_payment_method",
|
|
660
|
-
requires_capture: "requires_capture",
|
|
661
|
-
partially_paid: "partially_paid",
|
|
662
|
-
partially_refunded: "partially_refunded",
|
|
663
|
-
card_declined: "declined",
|
|
664
|
-
canceled: "cancelled",
|
|
665
|
-
authorized: "authorized",
|
|
666
|
-
cancelled: "cancelled",
|
|
667
|
-
unresolved: "pending"
|
|
668
|
-
};
|
|
669
|
-
var KNOWN_PAYMENT_STATUSES = /* @__PURE__ */ new Set([
|
|
670
|
-
"initialized",
|
|
671
|
-
"pending",
|
|
672
|
-
"processing",
|
|
673
|
-
"authorized",
|
|
674
|
-
"captured",
|
|
675
|
-
"failed",
|
|
676
|
-
"cancelled",
|
|
677
|
-
"refunded",
|
|
678
|
-
"unknown",
|
|
679
|
-
"voided",
|
|
680
|
-
"requires_action",
|
|
681
|
-
"abandoned",
|
|
682
|
-
"reversed",
|
|
683
|
-
"disputed",
|
|
684
|
-
"refund_pending",
|
|
685
|
-
"created",
|
|
686
|
-
"pending_confirmation",
|
|
687
|
-
"success",
|
|
688
|
-
"succeeded",
|
|
689
|
-
"declined",
|
|
690
|
-
"partially_refunded",
|
|
691
|
-
"partially_paid",
|
|
692
|
-
"paid",
|
|
693
|
-
"unpaid",
|
|
694
|
-
"requires_payment_method",
|
|
695
|
-
"requires_capture",
|
|
696
|
-
"completed",
|
|
697
|
-
"error"
|
|
698
|
-
]);
|
|
699
|
-
function normalizeStatusToken(status) {
|
|
700
|
-
return status?.trim().toLowerCase().replace(/[\s-]+/g, "_") ?? "";
|
|
701
|
-
}
|
|
702
|
-
function normalizePaymentStatusValue(status) {
|
|
703
|
-
const normalized = normalizeStatusToken(status);
|
|
704
|
-
if (Object.prototype.hasOwnProperty.call(PAYMENT_STATUS_ALIAS_MAP, normalized)) {
|
|
705
|
-
return PAYMENT_STATUS_ALIAS_MAP[normalized];
|
|
706
|
-
}
|
|
707
|
-
return KNOWN_PAYMENT_STATUSES.has(normalized) ? normalized : "unknown";
|
|
708
|
-
}
|
|
709
|
-
function isPaymentStatusSuccess(status) {
|
|
710
|
-
const normalizedStatus = normalizePaymentStatusValue(status);
|
|
711
|
-
return PAYMENT_SUCCESS_STATUSES.has(normalizedStatus);
|
|
712
|
-
}
|
|
713
|
-
function isPaymentStatusFailure(status) {
|
|
714
|
-
const normalizedStatus = normalizePaymentStatusValue(status);
|
|
715
|
-
return PAYMENT_FAILURE_STATUSES.has(normalizedStatus);
|
|
716
|
-
}
|
|
717
|
-
function isPaymentStatusRequiresAction(status) {
|
|
718
|
-
const normalizedStatus = normalizePaymentStatusValue(status);
|
|
719
|
-
return PAYMENT_REQUIRES_ACTION_STATUSES.has(normalizedStatus);
|
|
720
|
-
}
|
|
721
|
-
function normalizeStatusResponse(response) {
|
|
722
|
-
if (!response || typeof response !== "object") {
|
|
723
|
-
return {
|
|
724
|
-
status: "pending",
|
|
725
|
-
paid: false,
|
|
726
|
-
amount: moneyFromNumber(0),
|
|
727
|
-
currency: "",
|
|
728
|
-
message: "No status available"
|
|
729
|
-
};
|
|
730
|
-
}
|
|
731
|
-
const res = response;
|
|
732
|
-
const normalizedStatus = normalizePaymentStatusValue(res.status ?? void 0);
|
|
733
|
-
const normalizedAmount = typeof res.amount === "string" ? money(res.amount) : typeof res.amount === "number" && Number.isFinite(res.amount) ? moneyFromNumber(res.amount) : moneyFromNumber(0);
|
|
734
|
-
const normalizedCurrency = typeof res.currency === "string" && res.currency.trim().length > 0 ? res.currency : "";
|
|
735
|
-
const paidValue = res.paid === true;
|
|
736
|
-
const derivedPaid = paidValue || [
|
|
737
|
-
"success",
|
|
738
|
-
"succeeded",
|
|
739
|
-
"paid",
|
|
740
|
-
"captured",
|
|
741
|
-
"authorized",
|
|
742
|
-
"completed"
|
|
743
|
-
].includes(normalizedStatus);
|
|
744
|
-
return {
|
|
745
|
-
status: normalizedStatus,
|
|
746
|
-
paid: derivedPaid,
|
|
747
|
-
amount: normalizedAmount,
|
|
748
|
-
currency: normalizedCurrency,
|
|
749
|
-
reference: res.reference,
|
|
750
|
-
message: res.message || ""
|
|
751
|
-
};
|
|
752
|
-
}
|
|
753
|
-
|
|
754
|
-
// src/utils/paystack.ts
|
|
755
|
-
async function openPaystackPopup(options, signal) {
|
|
756
|
-
if (typeof window === "undefined") {
|
|
757
|
-
return { success: false, error: "PROVIDER_UNAVAILABLE" };
|
|
758
|
-
}
|
|
759
|
-
let PaystackPop;
|
|
760
|
-
try {
|
|
761
|
-
const imported = await import('@paystack/inline-js');
|
|
762
|
-
PaystackPop = imported.default;
|
|
763
|
-
} catch {
|
|
764
|
-
return { success: false, error: "PROVIDER_UNAVAILABLE" };
|
|
765
|
-
}
|
|
766
|
-
return new Promise((resolve) => {
|
|
767
|
-
let settled = false;
|
|
768
|
-
const resolveOnce = (result) => {
|
|
769
|
-
if (settled) {
|
|
770
|
-
return;
|
|
771
|
-
}
|
|
772
|
-
settled = true;
|
|
773
|
-
if (signal) {
|
|
774
|
-
signal.removeEventListener("abort", onAbort);
|
|
775
|
-
}
|
|
776
|
-
resolve(result);
|
|
777
|
-
};
|
|
778
|
-
const onAbort = () => {
|
|
779
|
-
resolveOnce({ success: false, error: "CANCELLED" });
|
|
780
|
-
};
|
|
781
|
-
if (signal?.aborted) {
|
|
782
|
-
resolveOnce({ success: false, error: "CANCELLED" });
|
|
783
|
-
return;
|
|
784
|
-
}
|
|
785
|
-
if (signal) {
|
|
786
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
787
|
-
}
|
|
788
|
-
try {
|
|
789
|
-
const popup = new PaystackPop();
|
|
790
|
-
popup.newTransaction({
|
|
791
|
-
key: options.key,
|
|
792
|
-
email: options.email,
|
|
793
|
-
amount: options.amount,
|
|
794
|
-
currency: options.currency,
|
|
795
|
-
reference: options.reference,
|
|
796
|
-
accessCode: options.accessCode,
|
|
797
|
-
onSuccess: (transaction) => {
|
|
798
|
-
resolveOnce({
|
|
799
|
-
success: true,
|
|
800
|
-
reference: transaction.reference ?? options.reference
|
|
801
|
-
});
|
|
802
|
-
},
|
|
803
|
-
onCancel: () => {
|
|
804
|
-
resolveOnce({ success: false, error: "PAYMENT_CANCELLED" });
|
|
805
|
-
},
|
|
806
|
-
onError: (error) => {
|
|
807
|
-
resolveOnce({
|
|
808
|
-
success: false,
|
|
809
|
-
error: error?.message || "PAYMENT_FAILED"
|
|
810
|
-
});
|
|
811
|
-
}
|
|
812
|
-
});
|
|
813
|
-
} catch {
|
|
814
|
-
resolveOnce({ success: false, error: "POPUP_BLOCKED" });
|
|
815
|
-
}
|
|
816
|
-
});
|
|
817
|
-
}
|
|
818
|
-
|
|
819
|
-
// src/utils/checkout-resolver.ts
|
|
820
|
-
var DEFAULT_POLL_INTERVAL_MS = 3e3;
|
|
821
|
-
var DEFAULT_MAX_POLL_ATTEMPTS = 60;
|
|
822
|
-
var MAX_CONSECUTIVE_NETWORK_ERRORS = 5;
|
|
823
|
-
var CARD_PROVIDER_PAYSTACK = "paystack";
|
|
824
|
-
var NEXT_ACTION_NONE = "none";
|
|
825
|
-
var NEXT_ACTION_CARD_POPUP = "card_popup";
|
|
826
|
-
var NEXT_ACTION_REDIRECT = "redirect";
|
|
827
|
-
var NEXT_ACTION_AUTHORIZATION = "authorization";
|
|
828
|
-
function normalizeCardPopupError(error) {
|
|
829
|
-
if (!error || error === "PAYMENT_CANCELLED" || error === "CANCELLED") {
|
|
830
|
-
return "PAYMENT_CANCELLED";
|
|
831
|
-
}
|
|
832
|
-
if (error === "PROVIDER_UNAVAILABLE") {
|
|
833
|
-
return "PROVIDER_UNAVAILABLE";
|
|
834
|
-
}
|
|
835
|
-
if (error === "POPUP_BLOCKED") {
|
|
836
|
-
return "POPUP_BLOCKED";
|
|
837
|
-
}
|
|
838
|
-
return "PAYMENT_FAILED";
|
|
839
|
-
}
|
|
840
|
-
function normalizeCardProvider(value) {
|
|
841
|
-
const normalized = value?.trim().toLowerCase();
|
|
842
|
-
return normalized && normalized.length > 0 ? normalized : CARD_PROVIDER_PAYSTACK;
|
|
843
|
-
}
|
|
844
|
-
async function openCardPopup(provider, checkoutResult, email, currency, signal) {
|
|
845
|
-
if (typeof window === "undefined") {
|
|
846
|
-
return { success: false, error: "PROVIDER_UNAVAILABLE" };
|
|
847
|
-
}
|
|
848
|
-
if (provider === CARD_PROVIDER_PAYSTACK) {
|
|
849
|
-
return openPaystackPopup(
|
|
850
|
-
{
|
|
851
|
-
key: checkoutResult.public_key || "",
|
|
852
|
-
email,
|
|
853
|
-
accessCode: checkoutResult.client_secret,
|
|
854
|
-
reference: checkoutResult.payment_reference || checkoutResult.client_secret,
|
|
855
|
-
currency
|
|
856
|
-
},
|
|
857
|
-
signal
|
|
858
|
-
);
|
|
859
|
-
}
|
|
860
|
-
return { success: false, error: "PROVIDER_UNAVAILABLE" };
|
|
861
|
-
}
|
|
862
|
-
var VALID_MOBILE_MONEY_PROVIDERS = new Set(Object.values(MOBILE_MONEY_PROVIDER));
|
|
863
|
-
function isValidMobileMoneyProvider(value) {
|
|
864
|
-
return VALID_MOBILE_MONEY_PROVIDERS.has(value);
|
|
865
|
-
}
|
|
866
|
-
function normalizeAuthorizationType(value) {
|
|
867
|
-
if (value && typeof value === "object" && "address" in value) {
|
|
868
|
-
return "address";
|
|
869
|
-
}
|
|
870
|
-
if (typeof value !== "string") return void 0;
|
|
871
|
-
const normalized = value.trim().toLowerCase().replace(/[\s-]+/g, "_");
|
|
872
|
-
if (normalized === "otp" || normalized === "pin") return normalized;
|
|
873
|
-
if (normalized === "phone" || normalized === "birthday" || normalized === "address") {
|
|
874
|
-
return normalized;
|
|
875
|
-
}
|
|
876
|
-
return void 0;
|
|
877
|
-
}
|
|
878
|
-
function formatMoney2(value) {
|
|
879
|
-
if (typeof value === "number" && Number.isFinite(value)) {
|
|
880
|
-
return value.toFixed(2);
|
|
881
|
-
}
|
|
882
|
-
if (typeof value === "string" && value.trim().length > 0) {
|
|
883
|
-
return value;
|
|
884
|
-
}
|
|
885
|
-
return "0.00";
|
|
886
|
-
}
|
|
887
|
-
function createAbortError() {
|
|
888
|
-
const error = new Error("CANCELLED");
|
|
889
|
-
error.name = "AbortError";
|
|
890
|
-
return error;
|
|
891
|
-
}
|
|
892
|
-
function isAbortError(error) {
|
|
893
|
-
if (error instanceof DOMException && error.name === "AbortError") {
|
|
894
|
-
return true;
|
|
895
|
-
}
|
|
896
|
-
return error instanceof Error && (error.name === "AbortError" || error.message === "CANCELLED");
|
|
897
|
-
}
|
|
898
|
-
var CheckoutResolver = class {
|
|
899
|
-
constructor(options) {
|
|
900
|
-
this.client = options.client;
|
|
901
|
-
this.checkoutData = options.checkoutData;
|
|
902
|
-
this.pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
|
|
903
|
-
this.maxPollAttempts = options.maxPollAttempts ?? DEFAULT_MAX_POLL_ATTEMPTS;
|
|
904
|
-
this.onStatusChange = options.onStatusChange;
|
|
905
|
-
this.onAuthorizationRequired = options.onAuthorizationRequired;
|
|
906
|
-
this.signal = options.signal;
|
|
907
|
-
this.returnUrl = options.returnUrl;
|
|
908
|
-
this.enrollInLink = options.enrollInLink !== false;
|
|
909
|
-
this.businessId = options.businessId;
|
|
910
|
-
this.addressData = options.addressData;
|
|
911
|
-
this.paymentData = options.paymentData;
|
|
912
|
-
this.orderType = options.orderType;
|
|
913
|
-
this.cartTotal = options.cartTotal;
|
|
914
|
-
this.cartCurrency = options.cartCurrency;
|
|
915
|
-
this.allowPopups = options.allowPopups ?? typeof window !== "undefined";
|
|
916
|
-
}
|
|
917
|
-
async resolve(checkoutResult) {
|
|
918
|
-
try {
|
|
919
|
-
this.ensureNotAborted();
|
|
920
|
-
if (!checkoutResult.order_id) {
|
|
921
|
-
return this.fail("CHECKOUT_FAILED", "Checkout did not return an order ID.", false);
|
|
922
|
-
}
|
|
923
|
-
if (checkoutResult.next_action) {
|
|
924
|
-
return this.resolveNextAction(checkoutResult);
|
|
925
|
-
}
|
|
926
|
-
let latestCheckoutResult = checkoutResult;
|
|
927
|
-
let authorizationType = normalizeAuthorizationType(checkoutResult.authorization_type);
|
|
928
|
-
let paymentReference = checkoutResult.payment_reference;
|
|
929
|
-
if (this.isSuccessfulStatus(checkoutResult.payment_status)) {
|
|
930
|
-
return this.finalizeSuccess(checkoutResult);
|
|
931
|
-
}
|
|
932
|
-
if (checkoutResult.client_secret && checkoutResult.public_key) {
|
|
933
|
-
const provider = normalizeCardProvider(checkoutResult.provider);
|
|
934
|
-
this.emit("awaiting_authorization", {
|
|
935
|
-
display_text: "Complete payment in the card authorization popup.",
|
|
936
|
-
order_id: checkoutResult.order_id,
|
|
937
|
-
order_number: checkoutResult.order_number
|
|
938
|
-
});
|
|
939
|
-
if (!this.allowPopups) {
|
|
940
|
-
return this.fail(
|
|
941
|
-
"PROVIDER_UNAVAILABLE",
|
|
942
|
-
"Card payment popup is unavailable in this environment.",
|
|
943
|
-
false
|
|
944
|
-
);
|
|
945
|
-
}
|
|
946
|
-
const popupResult = await openCardPopup(
|
|
947
|
-
provider,
|
|
948
|
-
checkoutResult,
|
|
949
|
-
this.checkoutData.customer.email || "customer@cimplify.io",
|
|
950
|
-
this.getOrderCurrency(checkoutResult),
|
|
951
|
-
this.signal
|
|
952
|
-
);
|
|
953
|
-
if (!popupResult.success) {
|
|
954
|
-
const popupError = normalizeCardPopupError(popupResult.error);
|
|
955
|
-
if (popupError === "POPUP_BLOCKED") {
|
|
956
|
-
return this.fail(
|
|
957
|
-
"POPUP_BLOCKED",
|
|
958
|
-
"Unable to open card payment popup. Please allow popups and try again.",
|
|
959
|
-
true
|
|
960
|
-
);
|
|
961
|
-
}
|
|
962
|
-
if (popupError === "PROVIDER_UNAVAILABLE") {
|
|
963
|
-
return this.fail(
|
|
964
|
-
"PROVIDER_UNAVAILABLE",
|
|
965
|
-
"Card payment provider is unavailable.",
|
|
966
|
-
false
|
|
967
|
-
);
|
|
968
|
-
}
|
|
969
|
-
return this.fail(
|
|
970
|
-
"PAYMENT_CANCELLED",
|
|
971
|
-
"Card payment was cancelled before completion.",
|
|
972
|
-
true
|
|
973
|
-
);
|
|
974
|
-
}
|
|
975
|
-
paymentReference = popupResult.reference || paymentReference;
|
|
976
|
-
}
|
|
977
|
-
if (checkoutResult.authorization_url) {
|
|
978
|
-
if (typeof window !== "undefined" && this.returnUrl) {
|
|
979
|
-
window.location.assign(checkoutResult.authorization_url);
|
|
980
|
-
return this.fail(
|
|
981
|
-
"REDIRECT_REQUIRED",
|
|
982
|
-
"Redirecting to complete payment authorization.",
|
|
983
|
-
true
|
|
984
|
-
);
|
|
985
|
-
}
|
|
986
|
-
if (typeof window !== "undefined") {
|
|
987
|
-
const popup = window.open(
|
|
988
|
-
checkoutResult.authorization_url,
|
|
989
|
-
"cimplify-auth",
|
|
990
|
-
"width=520,height=760,noopener,noreferrer"
|
|
991
|
-
);
|
|
992
|
-
if (!popup) {
|
|
993
|
-
return this.fail(
|
|
994
|
-
"POPUP_BLOCKED",
|
|
995
|
-
"Authorization popup was blocked. Please allow popups and retry.",
|
|
996
|
-
true
|
|
997
|
-
);
|
|
998
|
-
}
|
|
999
|
-
}
|
|
1000
|
-
}
|
|
1001
|
-
if (checkoutResult.requires_authorization || isPaymentStatusRequiresAction(checkoutResult.payment_status)) {
|
|
1002
|
-
const authorization = await this.handleAuthorization({
|
|
1003
|
-
authorizationType,
|
|
1004
|
-
paymentReference,
|
|
1005
|
-
displayText: checkoutResult.display_text,
|
|
1006
|
-
provider: checkoutResult.provider
|
|
1007
|
-
});
|
|
1008
|
-
if (!authorization.ok) {
|
|
1009
|
-
return authorization.result;
|
|
1010
|
-
}
|
|
1011
|
-
if (authorization.value) {
|
|
1012
|
-
latestCheckoutResult = authorization.value;
|
|
1013
|
-
paymentReference = authorization.value.payment_reference || paymentReference;
|
|
1014
|
-
authorizationType = normalizeAuthorizationType(authorization.value.authorization_type) || authorizationType;
|
|
1015
|
-
if (this.isSuccessfulStatus(authorization.value.payment_status)) {
|
|
1016
|
-
return this.finalizeSuccess(authorization.value);
|
|
1017
|
-
}
|
|
1018
|
-
if (this.isFailureStatus(authorization.value.payment_status)) {
|
|
1019
|
-
return this.fail(
|
|
1020
|
-
"AUTHORIZATION_FAILED",
|
|
1021
|
-
authorization.value.display_text || "Payment authorization failed.",
|
|
1022
|
-
false
|
|
1023
|
-
);
|
|
1024
|
-
}
|
|
1025
|
-
}
|
|
1026
|
-
}
|
|
1027
|
-
return this.pollUntilTerminal({
|
|
1028
|
-
orderId: checkoutResult.order_id,
|
|
1029
|
-
latestCheckoutResult,
|
|
1030
|
-
paymentReference,
|
|
1031
|
-
authorizationType
|
|
1032
|
-
});
|
|
1033
|
-
} catch (error) {
|
|
1034
|
-
if (isAbortError(error)) {
|
|
1035
|
-
return this.fail("CANCELLED", "Checkout was cancelled.", true);
|
|
1036
|
-
}
|
|
1037
|
-
const message = error instanceof Error ? error.message : "Checkout failed unexpectedly.";
|
|
1038
|
-
return this.fail("CHECKOUT_FAILED", message, true);
|
|
1039
|
-
}
|
|
1040
|
-
}
|
|
1041
|
-
async resolveNextAction(checkoutResult) {
|
|
1042
|
-
const action = checkoutResult.next_action;
|
|
1043
|
-
if (this.isSuccessfulStatus(checkoutResult.payment_status)) {
|
|
1044
|
-
return this.finalizeSuccess(checkoutResult);
|
|
1045
|
-
}
|
|
1046
|
-
let latestCheckoutResult = checkoutResult;
|
|
1047
|
-
let paymentReference = checkoutResult.payment_reference;
|
|
1048
|
-
switch (action.type) {
|
|
1049
|
-
case NEXT_ACTION_NONE:
|
|
1050
|
-
return this.finalizeSuccess(checkoutResult);
|
|
1051
|
-
case NEXT_ACTION_CARD_POPUP: {
|
|
1052
|
-
const provider = normalizeCardProvider(action.provider);
|
|
1053
|
-
this.emit("awaiting_authorization", {
|
|
1054
|
-
display_text: "Complete payment in the card authorization popup.",
|
|
1055
|
-
order_id: checkoutResult.order_id,
|
|
1056
|
-
order_number: checkoutResult.order_number
|
|
1057
|
-
});
|
|
1058
|
-
if (!this.allowPopups) {
|
|
1059
|
-
return this.fail(
|
|
1060
|
-
"PROVIDER_UNAVAILABLE",
|
|
1061
|
-
"Card payment popup is unavailable in this environment.",
|
|
1062
|
-
false
|
|
1063
|
-
);
|
|
1064
|
-
}
|
|
1065
|
-
const popupResult = await openCardPopup(
|
|
1066
|
-
provider,
|
|
1067
|
-
checkoutResult,
|
|
1068
|
-
this.checkoutData.customer.email || "customer@cimplify.io",
|
|
1069
|
-
this.getOrderCurrency(checkoutResult),
|
|
1070
|
-
this.signal
|
|
1071
|
-
);
|
|
1072
|
-
if (!popupResult.success) {
|
|
1073
|
-
const popupError = normalizeCardPopupError(popupResult.error);
|
|
1074
|
-
if (popupError === "POPUP_BLOCKED") {
|
|
1075
|
-
return this.fail(
|
|
1076
|
-
"POPUP_BLOCKED",
|
|
1077
|
-
"Unable to open card payment popup. Please allow popups and try again.",
|
|
1078
|
-
true
|
|
1079
|
-
);
|
|
1080
|
-
}
|
|
1081
|
-
if (popupError === "PROVIDER_UNAVAILABLE") {
|
|
1082
|
-
return this.fail("PROVIDER_UNAVAILABLE", "Card payment provider is unavailable.", false);
|
|
1083
|
-
}
|
|
1084
|
-
return this.fail("PAYMENT_CANCELLED", "Card payment was cancelled before completion.", true);
|
|
1085
|
-
}
|
|
1086
|
-
paymentReference = popupResult.reference || paymentReference;
|
|
1087
|
-
break;
|
|
1088
|
-
}
|
|
1089
|
-
case NEXT_ACTION_REDIRECT: {
|
|
1090
|
-
if (typeof window !== "undefined" && this.returnUrl) {
|
|
1091
|
-
window.location.assign(action.authorization_url);
|
|
1092
|
-
return this.fail("REDIRECT_REQUIRED", "Redirecting to complete payment authorization.", true);
|
|
1093
|
-
}
|
|
1094
|
-
if (typeof window !== "undefined") {
|
|
1095
|
-
const popup = window.open(
|
|
1096
|
-
action.authorization_url,
|
|
1097
|
-
"cimplify-auth",
|
|
1098
|
-
"width=520,height=760,noopener,noreferrer"
|
|
1099
|
-
);
|
|
1100
|
-
if (!popup) {
|
|
1101
|
-
return this.fail(
|
|
1102
|
-
"POPUP_BLOCKED",
|
|
1103
|
-
"Authorization popup was blocked. Please allow popups and retry.",
|
|
1104
|
-
true
|
|
1105
|
-
);
|
|
1106
|
-
}
|
|
1107
|
-
}
|
|
1108
|
-
break;
|
|
1109
|
-
}
|
|
1110
|
-
case NEXT_ACTION_AUTHORIZATION: {
|
|
1111
|
-
const authType = normalizeAuthorizationType(action.authorization_type);
|
|
1112
|
-
const authorization = await this.handleAuthorization({
|
|
1113
|
-
authorizationType: authType,
|
|
1114
|
-
paymentReference,
|
|
1115
|
-
displayText: action.display_text,
|
|
1116
|
-
provider: checkoutResult.provider
|
|
1117
|
-
});
|
|
1118
|
-
if (!authorization.ok) {
|
|
1119
|
-
return authorization.result;
|
|
1120
|
-
}
|
|
1121
|
-
if (authorization.value) {
|
|
1122
|
-
latestCheckoutResult = authorization.value;
|
|
1123
|
-
paymentReference = authorization.value.payment_reference || paymentReference;
|
|
1124
|
-
if (this.isSuccessfulStatus(authorization.value.payment_status)) {
|
|
1125
|
-
return this.finalizeSuccess(authorization.value);
|
|
1126
|
-
}
|
|
1127
|
-
if (this.isFailureStatus(authorization.value.payment_status)) {
|
|
1128
|
-
return this.fail(
|
|
1129
|
-
"AUTHORIZATION_FAILED",
|
|
1130
|
-
authorization.value.display_text || "Payment authorization failed.",
|
|
1131
|
-
false
|
|
1132
|
-
);
|
|
1133
|
-
}
|
|
1134
|
-
}
|
|
1135
|
-
break;
|
|
1136
|
-
}
|
|
1137
|
-
}
|
|
1138
|
-
return this.pollUntilTerminal({
|
|
1139
|
-
orderId: checkoutResult.order_id,
|
|
1140
|
-
latestCheckoutResult,
|
|
1141
|
-
paymentReference,
|
|
1142
|
-
authorizationType: normalizeAuthorizationType(checkoutResult.authorization_type)
|
|
1143
|
-
});
|
|
1144
|
-
}
|
|
1145
|
-
async pollUntilTerminal(input) {
|
|
1146
|
-
let consecutiveErrors = 0;
|
|
1147
|
-
let latestCheckoutResult = input.latestCheckoutResult;
|
|
1148
|
-
let paymentReference = input.paymentReference;
|
|
1149
|
-
let authorizationType = input.authorizationType;
|
|
1150
|
-
for (let attempt = 0; attempt < this.maxPollAttempts; attempt++) {
|
|
1151
|
-
this.ensureNotAborted();
|
|
1152
|
-
this.emit("polling", {
|
|
1153
|
-
poll_attempt: attempt,
|
|
1154
|
-
max_poll_attempts: this.maxPollAttempts,
|
|
1155
|
-
order_id: input.orderId,
|
|
1156
|
-
order_number: latestCheckoutResult.order_number
|
|
1157
|
-
});
|
|
1158
|
-
const statusResult = await this.client.checkout.pollPaymentStatus(input.orderId);
|
|
1159
|
-
if (!statusResult.ok) {
|
|
1160
|
-
consecutiveErrors += 1;
|
|
1161
|
-
if (consecutiveErrors >= MAX_CONSECUTIVE_NETWORK_ERRORS) {
|
|
1162
|
-
return this.fail(
|
|
1163
|
-
"NETWORK_ERROR",
|
|
1164
|
-
"Unable to confirm payment due to repeated network errors.",
|
|
1165
|
-
true
|
|
1166
|
-
);
|
|
1167
|
-
}
|
|
1168
|
-
await this.wait(this.pollIntervalMs);
|
|
1169
|
-
continue;
|
|
1170
|
-
}
|
|
1171
|
-
consecutiveErrors = 0;
|
|
1172
|
-
if (statusResult.value.reference) {
|
|
1173
|
-
paymentReference = statusResult.value.reference;
|
|
1174
|
-
}
|
|
1175
|
-
const normalized = normalizeStatusResponse(statusResult.value);
|
|
1176
|
-
if (normalized.paid || isPaymentStatusSuccess(normalized.status)) {
|
|
1177
|
-
return this.finalizeSuccess(latestCheckoutResult);
|
|
1178
|
-
}
|
|
1179
|
-
if (isPaymentStatusFailure(normalized.status)) {
|
|
1180
|
-
return this.fail(
|
|
1181
|
-
normalized.status ? normalized.status.toUpperCase() : "PAYMENT_FAILED",
|
|
1182
|
-
normalized.message || "Payment failed during confirmation.",
|
|
1183
|
-
false
|
|
1184
|
-
);
|
|
1185
|
-
}
|
|
1186
|
-
if (isPaymentStatusRequiresAction(normalized.status)) {
|
|
1187
|
-
const authorization = await this.handleAuthorization({
|
|
1188
|
-
authorizationType,
|
|
1189
|
-
paymentReference,
|
|
1190
|
-
displayText: normalized.message || latestCheckoutResult.display_text,
|
|
1191
|
-
provider: latestCheckoutResult.provider
|
|
1192
|
-
});
|
|
1193
|
-
if (!authorization.ok) {
|
|
1194
|
-
return authorization.result;
|
|
1195
|
-
}
|
|
1196
|
-
if (authorization.value) {
|
|
1197
|
-
latestCheckoutResult = authorization.value;
|
|
1198
|
-
paymentReference = authorization.value.payment_reference || paymentReference;
|
|
1199
|
-
authorizationType = normalizeAuthorizationType(authorization.value.authorization_type) || authorizationType;
|
|
1200
|
-
if (this.isSuccessfulStatus(authorization.value.payment_status)) {
|
|
1201
|
-
return this.finalizeSuccess(authorization.value);
|
|
1202
|
-
}
|
|
1203
|
-
if (this.isFailureStatus(authorization.value.payment_status)) {
|
|
1204
|
-
return this.fail(
|
|
1205
|
-
"AUTHORIZATION_FAILED",
|
|
1206
|
-
authorization.value.display_text || "Payment authorization failed.",
|
|
1207
|
-
false
|
|
1208
|
-
);
|
|
1209
|
-
}
|
|
1210
|
-
}
|
|
1211
|
-
}
|
|
1212
|
-
await this.wait(this.pollIntervalMs);
|
|
1213
|
-
}
|
|
1214
|
-
try {
|
|
1215
|
-
const finalResult = await this.client.checkout.pollPaymentStatus(input.orderId);
|
|
1216
|
-
if (finalResult.ok) {
|
|
1217
|
-
const normalized = normalizeStatusResponse(finalResult.value);
|
|
1218
|
-
if (normalized.paid || isPaymentStatusSuccess(normalized.status)) {
|
|
1219
|
-
return this.finalizeSuccess(latestCheckoutResult);
|
|
1220
|
-
}
|
|
1221
|
-
}
|
|
1222
|
-
} catch {
|
|
1223
|
-
}
|
|
1224
|
-
return this.fail(
|
|
1225
|
-
"PAYMENT_TIMEOUT",
|
|
1226
|
-
"Payment confirmation timed out. Please retry checkout.",
|
|
1227
|
-
true
|
|
1228
|
-
);
|
|
1229
|
-
}
|
|
1230
|
-
async handleAuthorization(input) {
|
|
1231
|
-
const authorizationType = input.authorizationType;
|
|
1232
|
-
const paymentReference = input.paymentReference;
|
|
1233
|
-
if (!authorizationType || !paymentReference) {
|
|
1234
|
-
return { ok: true };
|
|
1235
|
-
}
|
|
1236
|
-
this.emit("awaiting_authorization", {
|
|
1237
|
-
authorization_type: authorizationType,
|
|
1238
|
-
display_text: input.displayText,
|
|
1239
|
-
provider: input.provider
|
|
1240
|
-
});
|
|
1241
|
-
let authorizationResult;
|
|
1242
|
-
const submit = async (code) => {
|
|
1243
|
-
this.ensureNotAborted();
|
|
1244
|
-
const trimmedCode = code.trim();
|
|
1245
|
-
if (!trimmedCode) {
|
|
1246
|
-
throw new Error("Authorization code is required.");
|
|
1247
|
-
}
|
|
1248
|
-
const submitResult = await this.client.checkout.submitAuthorization({
|
|
1249
|
-
reference: paymentReference,
|
|
1250
|
-
auth_type: authorizationType,
|
|
1251
|
-
value: trimmedCode
|
|
1252
|
-
});
|
|
1253
|
-
if (!submitResult.ok) {
|
|
1254
|
-
throw new Error(submitResult.error.message || "Authorization failed.");
|
|
1255
|
-
}
|
|
1256
|
-
authorizationResult = submitResult.value;
|
|
1257
|
-
};
|
|
1258
|
-
try {
|
|
1259
|
-
if (this.onAuthorizationRequired) {
|
|
1260
|
-
await this.onAuthorizationRequired(authorizationType, submit);
|
|
1261
|
-
} else {
|
|
1262
|
-
return {
|
|
1263
|
-
ok: false,
|
|
1264
|
-
result: this.fail(
|
|
1265
|
-
"AUTHORIZATION_REQUIRED",
|
|
1266
|
-
"Authorization callback is required in headless checkout mode.",
|
|
1267
|
-
false
|
|
1268
|
-
)
|
|
1269
|
-
};
|
|
1270
|
-
}
|
|
1271
|
-
} catch (error) {
|
|
1272
|
-
if (isAbortError(error)) {
|
|
1273
|
-
return {
|
|
1274
|
-
ok: false,
|
|
1275
|
-
result: this.fail("CANCELLED", "Checkout was cancelled.", true)
|
|
1276
|
-
};
|
|
1277
|
-
}
|
|
1278
|
-
const message = error instanceof Error ? error.message : "Payment authorization failed.";
|
|
1279
|
-
return {
|
|
1280
|
-
ok: false,
|
|
1281
|
-
result: this.fail("AUTHORIZATION_FAILED", message, true)
|
|
1282
|
-
};
|
|
1283
|
-
}
|
|
1284
|
-
return {
|
|
1285
|
-
ok: true,
|
|
1286
|
-
value: authorizationResult
|
|
1287
|
-
};
|
|
1288
|
-
}
|
|
1289
|
-
async finalizeSuccess(checkoutResult) {
|
|
1290
|
-
this.emit("finalizing", {
|
|
1291
|
-
order_id: checkoutResult.order_id,
|
|
1292
|
-
order_number: checkoutResult.order_number
|
|
1293
|
-
});
|
|
1294
|
-
const enrolledInLink = await this.maybeEnrollInLink(checkoutResult.order_id);
|
|
1295
|
-
this.emit("success", {
|
|
1296
|
-
order_id: checkoutResult.order_id,
|
|
1297
|
-
order_number: checkoutResult.order_number
|
|
1298
|
-
});
|
|
1299
|
-
return {
|
|
1300
|
-
success: true,
|
|
1301
|
-
order: {
|
|
1302
|
-
id: checkoutResult.order_id,
|
|
1303
|
-
order_number: checkoutResult.order_number || checkoutResult.order_id,
|
|
1304
|
-
status: checkoutResult.payment_status || "paid",
|
|
1305
|
-
total: this.getOrderTotal(checkoutResult),
|
|
1306
|
-
currency: this.getOrderCurrency(checkoutResult)
|
|
1307
|
-
},
|
|
1308
|
-
enrolled_in_link: enrolledInLink
|
|
1309
|
-
};
|
|
1310
|
-
}
|
|
1311
|
-
async maybeEnrollInLink(orderId) {
|
|
1312
|
-
if (!this.enrollInLink || !orderId) {
|
|
1313
|
-
return false;
|
|
1314
|
-
}
|
|
1315
|
-
let businessId = this.businessId;
|
|
1316
|
-
if (!businessId) {
|
|
1317
|
-
const businessResult = await this.client.business.getInfo();
|
|
1318
|
-
if (!businessResult.ok || !businessResult.value?.id) {
|
|
1319
|
-
return false;
|
|
1320
|
-
}
|
|
1321
|
-
businessId = businessResult.value.id;
|
|
1322
|
-
}
|
|
1323
|
-
const address = this.getEnrollmentAddress();
|
|
1324
|
-
const mobileMoney = this.getEnrollmentMobileMoney();
|
|
1325
|
-
try {
|
|
1326
|
-
const enrollment = await this.client.link.enrollAndLinkOrder({
|
|
1327
|
-
order_id: orderId,
|
|
1328
|
-
business_id: businessId,
|
|
1329
|
-
order_type: this.orderType || this.checkoutData.order_type,
|
|
1330
|
-
address,
|
|
1331
|
-
mobile_money: mobileMoney
|
|
1332
|
-
});
|
|
1333
|
-
return enrollment.ok && enrollment.value.success;
|
|
1334
|
-
} catch {
|
|
1335
|
-
return false;
|
|
1336
|
-
}
|
|
1337
|
-
}
|
|
1338
|
-
getEnrollmentAddress() {
|
|
1339
|
-
const source = this.addressData ?? this.checkoutData.address_info;
|
|
1340
|
-
if (!source?.street_address) {
|
|
1341
|
-
return void 0;
|
|
1342
|
-
}
|
|
1343
|
-
return {
|
|
1344
|
-
label: "Default",
|
|
1345
|
-
street_address: source.street_address,
|
|
1346
|
-
apartment: source.apartment || void 0,
|
|
1347
|
-
city: source.city || "",
|
|
1348
|
-
region: source.region || "",
|
|
1349
|
-
delivery_instructions: source.delivery_instructions || void 0,
|
|
1350
|
-
phone_for_delivery: source.phone_for_delivery || void 0
|
|
1351
|
-
};
|
|
1352
|
-
}
|
|
1353
|
-
getEnrollmentMobileMoney() {
|
|
1354
|
-
if (this.paymentData?.type === "mobile_money" && this.paymentData.phone_number && this.paymentData.provider && isValidMobileMoneyProvider(this.paymentData.provider)) {
|
|
1355
|
-
return {
|
|
1356
|
-
phone_number: this.paymentData.phone_number,
|
|
1357
|
-
provider: this.paymentData.provider,
|
|
1358
|
-
label: this.paymentData.label || "Mobile Money"
|
|
1359
|
-
};
|
|
1360
|
-
}
|
|
1361
|
-
if (this.checkoutData.mobile_money_details?.phone_number) {
|
|
1362
|
-
return {
|
|
1363
|
-
phone_number: this.checkoutData.mobile_money_details.phone_number,
|
|
1364
|
-
provider: this.checkoutData.mobile_money_details.provider,
|
|
1365
|
-
label: "Mobile Money"
|
|
1366
|
-
};
|
|
1367
|
-
}
|
|
1368
|
-
return void 0;
|
|
1369
|
-
}
|
|
1370
|
-
getOrderTotal(checkoutResult) {
|
|
1371
|
-
if (checkoutResult.fx?.pay_amount !== void 0) {
|
|
1372
|
-
return formatMoney2(checkoutResult.fx.pay_amount);
|
|
1373
|
-
}
|
|
1374
|
-
if (this.cartTotal !== void 0) {
|
|
1375
|
-
return formatMoney2(this.cartTotal);
|
|
1376
|
-
}
|
|
1377
|
-
return "0.00";
|
|
1378
|
-
}
|
|
1379
|
-
getOrderCurrency(checkoutResult) {
|
|
1380
|
-
if (checkoutResult.fx?.pay_currency) {
|
|
1381
|
-
return checkoutResult.fx.pay_currency;
|
|
1382
|
-
}
|
|
1383
|
-
if (this.cartCurrency) {
|
|
1384
|
-
return this.cartCurrency;
|
|
1385
|
-
}
|
|
1386
|
-
if (this.checkoutData.pay_currency) {
|
|
1387
|
-
return this.checkoutData.pay_currency;
|
|
1388
|
-
}
|
|
1389
|
-
return "GHS";
|
|
1390
|
-
}
|
|
1391
|
-
emit(status, context = {}) {
|
|
1392
|
-
if (!this.onStatusChange) {
|
|
1393
|
-
return;
|
|
1394
|
-
}
|
|
1395
|
-
try {
|
|
1396
|
-
this.onStatusChange(status, context);
|
|
1397
|
-
} catch {
|
|
1398
|
-
}
|
|
1399
|
-
}
|
|
1400
|
-
fail(code, message, recoverable) {
|
|
1401
|
-
this.emit("failed", {
|
|
1402
|
-
display_text: message
|
|
1403
|
-
});
|
|
1404
|
-
return {
|
|
1405
|
-
success: false,
|
|
1406
|
-
error: {
|
|
1407
|
-
code,
|
|
1408
|
-
message,
|
|
1409
|
-
recoverable
|
|
1410
|
-
}
|
|
1411
|
-
};
|
|
1412
|
-
}
|
|
1413
|
-
isSuccessfulStatus(status) {
|
|
1414
|
-
const normalized = normalizeStatusResponse({ status, paid: false });
|
|
1415
|
-
return normalized.paid || isPaymentStatusSuccess(normalized.status);
|
|
1416
|
-
}
|
|
1417
|
-
isFailureStatus(status) {
|
|
1418
|
-
const normalized = normalizeStatusResponse({ status, paid: false });
|
|
1419
|
-
return isPaymentStatusFailure(normalized.status);
|
|
1420
|
-
}
|
|
1421
|
-
ensureNotAborted() {
|
|
1422
|
-
if (this.signal?.aborted) {
|
|
1423
|
-
throw createAbortError();
|
|
1424
|
-
}
|
|
1425
|
-
}
|
|
1426
|
-
wait(ms) {
|
|
1427
|
-
this.ensureNotAborted();
|
|
1428
|
-
return new Promise((resolve, reject) => {
|
|
1429
|
-
const timer = setTimeout(() => {
|
|
1430
|
-
if (this.signal) {
|
|
1431
|
-
this.signal.removeEventListener("abort", onAbort);
|
|
1432
|
-
}
|
|
1433
|
-
resolve();
|
|
1434
|
-
}, ms);
|
|
1435
|
-
const onAbort = () => {
|
|
1436
|
-
clearTimeout(timer);
|
|
1437
|
-
reject(createAbortError());
|
|
1438
|
-
};
|
|
1439
|
-
if (this.signal) {
|
|
1440
|
-
this.signal.addEventListener("abort", onAbort, { once: true });
|
|
1441
|
-
}
|
|
1442
|
-
});
|
|
1443
|
-
}
|
|
1444
|
-
};
|
|
1445
|
-
|
|
1446
|
-
// src/checkout.ts
|
|
1447
|
-
function toTerminalFailure(code, message, recoverable) {
|
|
1448
|
-
return {
|
|
1449
|
-
success: false,
|
|
1450
|
-
error: {
|
|
1451
|
-
code,
|
|
1452
|
-
message,
|
|
1453
|
-
recoverable
|
|
1454
|
-
}
|
|
1455
|
-
};
|
|
1456
|
-
}
|
|
1457
|
-
function generateIdempotencyKey() {
|
|
1458
|
-
if (typeof crypto !== "undefined" && crypto.randomUUID) {
|
|
1459
|
-
return `idem_${crypto.randomUUID()}`;
|
|
1460
|
-
}
|
|
1461
|
-
const timestamp = Date.now().toString(36);
|
|
1462
|
-
const random = Math.random().toString(36).substring(2, 15);
|
|
1463
|
-
return `idem_${timestamp}_${random}`;
|
|
1464
|
-
}
|
|
1465
|
-
var CheckoutService = class {
|
|
1466
|
-
constructor(client) {
|
|
1467
|
-
this.client = client;
|
|
1468
|
-
}
|
|
1469
|
-
orderTokenParam(orderId) {
|
|
1470
|
-
const token = this.client.getOrderToken(orderId);
|
|
1471
|
-
return token ? `?token=${encodeURIComponent(token)}` : "";
|
|
1472
|
-
}
|
|
1473
|
-
async process(data) {
|
|
1474
|
-
const checkoutData = {
|
|
1475
|
-
...data,
|
|
1476
|
-
idempotency_key: data.idempotency_key || generateIdempotencyKey()
|
|
1477
|
-
};
|
|
1478
|
-
const result = await safe(
|
|
1479
|
-
this.client.post("/api/v1/checkout", {
|
|
1480
|
-
checkout_data: checkoutData
|
|
1481
|
-
})
|
|
1482
|
-
);
|
|
1483
|
-
if (result.ok && result.value.bill_token) {
|
|
1484
|
-
this.client.setOrderToken(result.value.order_id, result.value.bill_token);
|
|
1485
|
-
}
|
|
1486
|
-
return result;
|
|
1487
|
-
}
|
|
1488
|
-
async initializePayment(_orderId, _method) {
|
|
1489
|
-
return err(
|
|
1490
|
-
new CimplifyError(
|
|
1491
|
-
"NOT_IMPLEMENTED",
|
|
1492
|
-
"initializePayment is not available in REST mode.",
|
|
1493
|
-
false
|
|
1494
|
-
)
|
|
1495
|
-
);
|
|
1496
|
-
}
|
|
1497
|
-
async submitAuthorization(input) {
|
|
1498
|
-
return safe(this.client.post("/api/v1/payments/authorization", input));
|
|
1499
|
-
}
|
|
1500
|
-
async pollPaymentStatus(orderId) {
|
|
1501
|
-
const encodedId = encodeURIComponent(orderId);
|
|
1502
|
-
const tokenParam = this.orderTokenParam(orderId);
|
|
1503
|
-
return safe(this.client.get(`/api/v1/orders/${encodedId}/payment-status${tokenParam}`));
|
|
1504
|
-
}
|
|
1505
|
-
async updateOrderCustomer(orderId, customer) {
|
|
1506
|
-
const encodedId = encodeURIComponent(orderId);
|
|
1507
|
-
const tokenParam = this.orderTokenParam(orderId);
|
|
1508
|
-
return safe(this.client.post(`/api/v1/orders/${encodedId}/customer${tokenParam}`, customer));
|
|
1509
|
-
}
|
|
1510
|
-
async verifyPayment(orderId) {
|
|
1511
|
-
const encodedId = encodeURIComponent(orderId);
|
|
1512
|
-
const tokenParam = this.orderTokenParam(orderId);
|
|
1513
|
-
return safe(this.client.post(`/api/v1/orders/${encodedId}/verify-payment${tokenParam}`));
|
|
1514
|
-
}
|
|
1515
|
-
async processAndResolve(data) {
|
|
1516
|
-
data.on_status_change?.("preparing", {});
|
|
1517
|
-
if (!data.cart_id) {
|
|
1518
|
-
return ok(
|
|
1519
|
-
toTerminalFailure(
|
|
1520
|
-
"INVALID_CART",
|
|
1521
|
-
"A valid cart is required before checkout can start.",
|
|
1522
|
-
false
|
|
1523
|
-
)
|
|
1524
|
-
);
|
|
1525
|
-
}
|
|
1526
|
-
const cartResult = await this.client.cart.get();
|
|
1527
|
-
if (!cartResult.ok || !cartResult.value?.id) {
|
|
1528
|
-
return ok(
|
|
1529
|
-
toTerminalFailure(
|
|
1530
|
-
"INVALID_CART",
|
|
1531
|
-
"Unable to load cart for checkout.",
|
|
1532
|
-
false
|
|
1533
|
-
)
|
|
1534
|
-
);
|
|
1535
|
-
}
|
|
1536
|
-
const cart = cartResult.value;
|
|
1537
|
-
if (cart.id !== data.cart_id || cart.items.length === 0) {
|
|
1538
|
-
return ok(
|
|
1539
|
-
toTerminalFailure(
|
|
1540
|
-
"INVALID_CART",
|
|
1541
|
-
"Cart is empty or no longer valid. Please refresh and try again.",
|
|
1542
|
-
false
|
|
1543
|
-
)
|
|
1544
|
-
);
|
|
1545
|
-
}
|
|
1546
|
-
const checkoutData = {
|
|
1547
|
-
cart_id: data.cart_id,
|
|
1548
|
-
location_id: data.location_id,
|
|
1549
|
-
customer: data.customer,
|
|
1550
|
-
order_type: data.order_type,
|
|
1551
|
-
address_info: data.address_info,
|
|
1552
|
-
payment_method: data.payment_method,
|
|
1553
|
-
mobile_money_details: data.mobile_money_details,
|
|
1554
|
-
special_instructions: data.special_instructions,
|
|
1555
|
-
link_address_id: data.link_address_id,
|
|
1556
|
-
link_payment_method_id: data.link_payment_method_id,
|
|
1557
|
-
idempotency_key: data.idempotency_key || generateIdempotencyKey(),
|
|
1558
|
-
metadata: data.metadata,
|
|
1559
|
-
pay_currency: data.pay_currency,
|
|
1560
|
-
fx_quote_id: data.fx_quote_id
|
|
1561
|
-
};
|
|
1562
|
-
const baseCurrency = currencyCode(
|
|
1563
|
-
(cart.pricing.currency || checkoutData.pay_currency || "GHS").toUpperCase()
|
|
1564
|
-
);
|
|
1565
|
-
const payCurrency = data.pay_currency?.trim().toUpperCase();
|
|
1566
|
-
const payCurrencyCode = payCurrency ? currencyCode(payCurrency) : void 0;
|
|
1567
|
-
const cartTotalAmount = typeof cart.pricing.total_price === "number" ? cart.pricing.total_price : Number.parseFloat(cart.pricing.total_price || "0");
|
|
1568
|
-
if (payCurrencyCode && payCurrencyCode !== baseCurrency && !checkoutData.fx_quote_id && Number.isFinite(cartTotalAmount) && cartTotalAmount > 0) {
|
|
1569
|
-
const fxQuoteResult = await this.client.fx.lockQuote({
|
|
1570
|
-
from: baseCurrency,
|
|
1571
|
-
to: payCurrencyCode,
|
|
1572
|
-
amount: cart.pricing.total_price
|
|
1573
|
-
});
|
|
1574
|
-
if (!fxQuoteResult.ok) {
|
|
1575
|
-
return ok(
|
|
1576
|
-
toTerminalFailure(
|
|
1577
|
-
"FX_QUOTE_FAILED",
|
|
1578
|
-
fxQuoteResult.error.message || "Unable to lock FX quote for checkout.",
|
|
1579
|
-
true
|
|
1580
|
-
)
|
|
1581
|
-
);
|
|
1582
|
-
}
|
|
1583
|
-
checkoutData.pay_currency = payCurrencyCode;
|
|
1584
|
-
checkoutData.fx_quote_id = fxQuoteResult.value.id;
|
|
1585
|
-
}
|
|
1586
|
-
data.on_status_change?.("processing", {});
|
|
1587
|
-
const processResult = await this.process(checkoutData);
|
|
1588
|
-
if (!processResult.ok) {
|
|
1589
|
-
return ok(
|
|
1590
|
-
toTerminalFailure(
|
|
1591
|
-
processResult.error.code || "CHECKOUT_FAILED",
|
|
1592
|
-
processResult.error.message || "Unable to process checkout.",
|
|
1593
|
-
processResult.error.retryable ?? true
|
|
1594
|
-
)
|
|
1595
|
-
);
|
|
1596
|
-
}
|
|
1597
|
-
const resolver = new CheckoutResolver({
|
|
1598
|
-
client: this.client,
|
|
1599
|
-
checkoutData,
|
|
1600
|
-
pollIntervalMs: data.poll_interval_ms,
|
|
1601
|
-
maxPollAttempts: data.max_poll_attempts,
|
|
1602
|
-
onStatusChange: data.on_status_change,
|
|
1603
|
-
onAuthorizationRequired: data.on_authorization_required,
|
|
1604
|
-
signal: data.signal,
|
|
1605
|
-
returnUrl: data.return_url,
|
|
1606
|
-
enrollInLink: data.enroll_in_link,
|
|
1607
|
-
cartTotal: cart.pricing.total_price,
|
|
1608
|
-
cartCurrency: checkoutData.pay_currency || cart.pricing.currency || "GHS",
|
|
1609
|
-
orderType: checkoutData.order_type,
|
|
1610
|
-
allowPopups: data.allow_popups
|
|
1611
|
-
});
|
|
1612
|
-
const resolved = await resolver.resolve(processResult.value);
|
|
1613
|
-
return ok(resolved);
|
|
1614
|
-
}
|
|
1615
|
-
};
|
|
1616
|
-
|
|
1617
|
-
// src/orders.ts
|
|
1618
|
-
var OrderQueries = class {
|
|
1619
|
-
constructor(client) {
|
|
1620
|
-
this.client = client;
|
|
1621
|
-
}
|
|
1622
|
-
orderTokenParam(orderId) {
|
|
1623
|
-
const token = this.client.getOrderToken(orderId);
|
|
1624
|
-
return token ? `?token=${encodeURIComponent(token)}` : "";
|
|
1625
|
-
}
|
|
1626
|
-
async list(options) {
|
|
1627
|
-
const params = new URLSearchParams();
|
|
1628
|
-
if (options?.status) params.set("status", options.status);
|
|
1629
|
-
if (options?.limit) params.set("limit", String(options.limit));
|
|
1630
|
-
if (options?.offset) params.set("offset", String(options.offset));
|
|
1631
|
-
const path = params.toString() ? `/api/v1/orders?${params.toString()}` : "/api/v1/orders";
|
|
1632
|
-
return safe(this.client.get(path));
|
|
1633
|
-
}
|
|
1634
|
-
async get(orderId) {
|
|
1635
|
-
const encodedId = encodeURIComponent(orderId);
|
|
1636
|
-
const tokenParam = this.orderTokenParam(orderId);
|
|
1637
|
-
return safe(this.client.get(`/api/v1/orders/${encodedId}${tokenParam}`));
|
|
1638
|
-
}
|
|
1639
|
-
async getRecent(limit = 5) {
|
|
1640
|
-
return this.list({ limit });
|
|
1641
|
-
}
|
|
1642
|
-
async getByStatus(status) {
|
|
1643
|
-
return this.list({ status });
|
|
1644
|
-
}
|
|
1645
|
-
async cancel(orderId, reason) {
|
|
1646
|
-
const encodedId = encodeURIComponent(orderId);
|
|
1647
|
-
const tokenParam = this.orderTokenParam(orderId);
|
|
1648
|
-
return safe(
|
|
1649
|
-
this.client.post(`/api/v1/orders/${encodedId}/cancel${tokenParam}`, {
|
|
1650
|
-
reason
|
|
1651
|
-
})
|
|
1652
|
-
);
|
|
1653
|
-
}
|
|
1654
|
-
};
|
|
1655
|
-
|
|
1656
|
-
// src/link.ts
|
|
1657
|
-
function encodePathSegment(value) {
|
|
1658
|
-
return encodeURIComponent(value);
|
|
1659
|
-
}
|
|
1660
|
-
function toCreateAddressPayload(input) {
|
|
1661
|
-
return {
|
|
1662
|
-
label: input.label,
|
|
1663
|
-
street_address: input.address_line1,
|
|
1664
|
-
apartment: input.address_line2,
|
|
1665
|
-
city: input.city,
|
|
1666
|
-
region: input.state ?? "",
|
|
1667
|
-
postal_code: input.postal_code,
|
|
1668
|
-
country: input.country
|
|
1669
|
-
};
|
|
1670
|
-
}
|
|
1671
|
-
function toUpdateAddressPayload(input) {
|
|
1672
|
-
return {
|
|
1673
|
-
label: input.label,
|
|
1674
|
-
street_address: input.address_line1,
|
|
1675
|
-
apartment: input.address_line2,
|
|
1676
|
-
city: input.city,
|
|
1677
|
-
region: input.state,
|
|
1678
|
-
postal_code: input.postal_code,
|
|
1679
|
-
country: input.country
|
|
1680
|
-
};
|
|
1681
|
-
}
|
|
1682
|
-
function toCreateMobileMoneyPayload(input) {
|
|
1683
|
-
return {
|
|
1684
|
-
phone_number: input.phone_number,
|
|
1685
|
-
provider: input.provider,
|
|
1686
|
-
label: input.account_name
|
|
1687
|
-
};
|
|
1688
|
-
}
|
|
1689
|
-
var LinkService = class {
|
|
1690
|
-
constructor(client) {
|
|
1691
|
-
this.client = client;
|
|
1692
|
-
}
|
|
1693
|
-
async getProfile() {
|
|
1694
|
-
return safe(this.client.linkGet("/v1/link/profile"));
|
|
1695
|
-
}
|
|
1696
|
-
async requestOtp(input) {
|
|
1697
|
-
return safe(this.client.linkPost("/v1/link/auth/request-otp", input));
|
|
1698
|
-
}
|
|
1699
|
-
async verifyOtp(input) {
|
|
1700
|
-
const result = await safe(
|
|
1701
|
-
this.client.linkPost("/v1/link/auth/verify-otp", input)
|
|
1702
|
-
);
|
|
1703
|
-
if (result.ok && result.value.session_token) {
|
|
1704
|
-
this.client.setAccessToken(result.value.session_token);
|
|
1705
|
-
}
|
|
1706
|
-
return result;
|
|
1707
|
-
}
|
|
1708
|
-
async logout() {
|
|
1709
|
-
const result = await safe(this.client.linkPost("/v1/link/auth/logout"));
|
|
1710
|
-
if (result.ok) {
|
|
1711
|
-
this.client.clearSession();
|
|
1712
|
-
}
|
|
1713
|
-
return result;
|
|
1714
|
-
}
|
|
1715
|
-
async checkStatus(contact) {
|
|
1716
|
-
return safe(this.client.linkPost("/v1/link/check-status", { contact }));
|
|
1717
|
-
}
|
|
1718
|
-
async getLinkData() {
|
|
1719
|
-
return safe(this.client.linkGet("/v1/link/data"));
|
|
1720
|
-
}
|
|
1721
|
-
async getAddresses() {
|
|
1722
|
-
return safe(this.client.linkGet("/v1/link/addresses"));
|
|
1723
|
-
}
|
|
1724
|
-
async getMobileMoney() {
|
|
1725
|
-
return safe(this.client.linkGet("/v1/link/mobile-money"));
|
|
1726
|
-
}
|
|
1727
|
-
async getPreferences() {
|
|
1728
|
-
return safe(this.client.linkGet("/v1/link/preferences"));
|
|
1729
|
-
}
|
|
1730
|
-
async enroll(data) {
|
|
1731
|
-
return safe(this.client.linkPost("/v1/link/enroll", data));
|
|
1732
|
-
}
|
|
1733
|
-
async enrollAndLinkOrder(data) {
|
|
1734
|
-
return safe(
|
|
1735
|
-
this.client.linkPost("/v1/link/enroll-and-link-order", data)
|
|
1736
|
-
);
|
|
1737
|
-
}
|
|
1738
|
-
async updatePreferences(preferences) {
|
|
1739
|
-
return safe(this.client.linkPost("/v1/link/preferences", preferences));
|
|
1740
|
-
}
|
|
1741
|
-
async createAddress(input) {
|
|
1742
|
-
return safe(
|
|
1743
|
-
this.client.linkPost("/v1/link/addresses", toCreateAddressPayload(input))
|
|
1744
|
-
);
|
|
1745
|
-
}
|
|
1746
|
-
async updateAddress(input) {
|
|
1747
|
-
return safe(
|
|
1748
|
-
this.client.linkPost(
|
|
1749
|
-
`/v1/link/addresses/${encodePathSegment(input.address_id)}`,
|
|
1750
|
-
toUpdateAddressPayload(input)
|
|
1751
|
-
)
|
|
1752
|
-
);
|
|
1753
|
-
}
|
|
1754
|
-
async deleteAddress(addressId) {
|
|
1755
|
-
return safe(
|
|
1756
|
-
this.client.linkDelete(`/v1/link/addresses/${encodePathSegment(addressId)}`)
|
|
1757
|
-
);
|
|
1758
|
-
}
|
|
1759
|
-
async setDefaultAddress(addressId) {
|
|
1760
|
-
return safe(
|
|
1761
|
-
this.client.linkPost(
|
|
1762
|
-
`/v1/link/addresses/${encodePathSegment(addressId)}/default`
|
|
1763
|
-
)
|
|
1764
|
-
);
|
|
1765
|
-
}
|
|
1766
|
-
async trackAddressUsage(addressId) {
|
|
1767
|
-
return safe(
|
|
1768
|
-
this.client.linkPost(
|
|
1769
|
-
`/v1/link/addresses/${encodePathSegment(addressId)}/track-usage`
|
|
1770
|
-
)
|
|
1771
|
-
);
|
|
1772
|
-
}
|
|
1773
|
-
async createMobileMoney(input) {
|
|
1774
|
-
return safe(
|
|
1775
|
-
this.client.linkPost(
|
|
1776
|
-
"/v1/link/mobile-money",
|
|
1777
|
-
toCreateMobileMoneyPayload(input)
|
|
1778
|
-
)
|
|
1779
|
-
);
|
|
1780
|
-
}
|
|
1781
|
-
async deleteMobileMoney(mobileMoneyId) {
|
|
1782
|
-
return safe(
|
|
1783
|
-
this.client.linkDelete(
|
|
1784
|
-
`/v1/link/mobile-money/${encodePathSegment(mobileMoneyId)}`
|
|
1785
|
-
)
|
|
1786
|
-
);
|
|
1787
|
-
}
|
|
1788
|
-
async setDefaultMobileMoney(mobileMoneyId) {
|
|
1789
|
-
return safe(
|
|
1790
|
-
this.client.linkPost(
|
|
1791
|
-
`/v1/link/mobile-money/${encodePathSegment(mobileMoneyId)}/default`
|
|
1792
|
-
)
|
|
1793
|
-
);
|
|
1794
|
-
}
|
|
1795
|
-
async trackMobileMoneyUsage(mobileMoneyId) {
|
|
1796
|
-
return safe(
|
|
1797
|
-
this.client.linkPost(
|
|
1798
|
-
`/v1/link/mobile-money/${encodePathSegment(mobileMoneyId)}/track-usage`
|
|
1799
|
-
)
|
|
1800
|
-
);
|
|
1801
|
-
}
|
|
1802
|
-
async verifyMobileMoney(mobileMoneyId) {
|
|
1803
|
-
return safe(
|
|
1804
|
-
this.client.linkPost(
|
|
1805
|
-
`/v1/link/mobile-money/${encodePathSegment(mobileMoneyId)}/verify`
|
|
1806
|
-
)
|
|
1807
|
-
);
|
|
1808
|
-
}
|
|
1809
|
-
async getSessions() {
|
|
1810
|
-
return safe(this.client.linkGet("/v1/link/sessions"));
|
|
1811
|
-
}
|
|
1812
|
-
async revokeSession(sessionId) {
|
|
1813
|
-
return safe(this.client.linkDelete(`/v1/link/sessions/${sessionId}`));
|
|
1814
|
-
}
|
|
1815
|
-
async revokeAllSessions() {
|
|
1816
|
-
return safe(this.client.linkDelete("/v1/link/sessions"));
|
|
1817
|
-
}
|
|
1818
|
-
};
|
|
1819
|
-
|
|
1820
|
-
// src/auth.ts
|
|
1821
|
-
var AuthService = class {
|
|
1822
|
-
constructor(client) {
|
|
1823
|
-
this.client = client;
|
|
1824
|
-
}
|
|
1825
|
-
async getStatus() {
|
|
1826
|
-
return safe(this.client.get("/api/v1/auth/status"));
|
|
1827
|
-
}
|
|
1828
|
-
async getCurrentUser() {
|
|
1829
|
-
const result = await this.getStatus();
|
|
1830
|
-
if (!result.ok) return result;
|
|
1831
|
-
return ok(result.value.customer || null);
|
|
1832
|
-
}
|
|
1833
|
-
async isAuthenticated() {
|
|
1834
|
-
const result = await this.getStatus();
|
|
1835
|
-
if (!result.ok) return result;
|
|
1836
|
-
return ok(result.value.is_authenticated);
|
|
1837
|
-
}
|
|
1838
|
-
async requestOtp(contact, contactType) {
|
|
1839
|
-
return safe(
|
|
1840
|
-
this.client.post("/api/v1/auth/request-otp", {
|
|
1841
|
-
contact,
|
|
1842
|
-
contact_type: contactType
|
|
1843
|
-
})
|
|
1844
|
-
);
|
|
1845
|
-
}
|
|
1846
|
-
async verifyOtp(code, contact) {
|
|
1847
|
-
return safe(
|
|
1848
|
-
this.client.post("/api/v1/auth/verify-otp", {
|
|
1849
|
-
otp_code: code,
|
|
1850
|
-
contact
|
|
1851
|
-
})
|
|
1852
|
-
);
|
|
1853
|
-
}
|
|
1854
|
-
async logout() {
|
|
1855
|
-
return safe(this.client.post("/api/v1/auth/logout"));
|
|
1856
|
-
}
|
|
1857
|
-
async updateProfile(input) {
|
|
1858
|
-
return safe(this.client.post("/api/v1/auth/profile", input));
|
|
1859
|
-
}
|
|
1860
|
-
};
|
|
1861
|
-
|
|
1862
|
-
// src/business.ts
|
|
1863
|
-
var BusinessService = class {
|
|
1864
|
-
constructor(client) {
|
|
1865
|
-
this.client = client;
|
|
1866
|
-
}
|
|
1867
|
-
async getInfo() {
|
|
1868
|
-
return safe(this.client.get("/api/v1/business"));
|
|
1869
|
-
}
|
|
1870
|
-
async getByHandle(handle) {
|
|
1871
|
-
const encodedHandle = encodeURIComponent(handle);
|
|
1872
|
-
return safe(this.client.get(`/api/v1/business/by-handle/${encodedHandle}`));
|
|
1873
|
-
}
|
|
1874
|
-
async getByDomain(domain) {
|
|
1875
|
-
const encodedDomain = encodeURIComponent(domain);
|
|
1876
|
-
return safe(this.client.get(`/api/v1/business/by-domain?domain=${encodedDomain}`));
|
|
1877
|
-
}
|
|
1878
|
-
async getSettings() {
|
|
1879
|
-
return safe(this.client.get("/api/v1/business/settings"));
|
|
1880
|
-
}
|
|
1881
|
-
async getLocations() {
|
|
1882
|
-
return safe(this.client.get("/api/v1/business/locations"));
|
|
1883
|
-
}
|
|
1884
|
-
async getLocation(locationId) {
|
|
1885
|
-
const result = await this.getLocations();
|
|
1886
|
-
if (!result.ok) return err(result.error);
|
|
1887
|
-
const location = result.value.find((item) => item.id === locationId);
|
|
1888
|
-
if (!location) {
|
|
1889
|
-
return err(new CimplifyError(ErrorCode.NOT_FOUND, `Location not found: ${locationId}`, false));
|
|
1890
|
-
}
|
|
1891
|
-
return ok(location);
|
|
1892
|
-
}
|
|
1893
|
-
async getHours() {
|
|
1894
|
-
return safe(this.client.get("/api/v1/business/hours"));
|
|
1895
|
-
}
|
|
1896
|
-
async getLocationHours(locationId) {
|
|
1897
|
-
const result = await this.getHours();
|
|
1898
|
-
if (!result.ok) return result;
|
|
1899
|
-
return ok(result.value.filter((hour) => hour.location_id === locationId));
|
|
1900
|
-
}
|
|
1901
|
-
async getBootstrap() {
|
|
1902
|
-
return safe(this.client.get("/api/v1/bootstrap"));
|
|
1903
|
-
}
|
|
1904
|
-
};
|
|
1905
|
-
|
|
1906
|
-
// src/inventory.ts
|
|
1907
|
-
var InventoryService = class {
|
|
1908
|
-
constructor(client) {
|
|
1909
|
-
this.client = client;
|
|
1910
|
-
}
|
|
1911
|
-
withQuery(path, params) {
|
|
1912
|
-
const searchParams = new URLSearchParams();
|
|
1913
|
-
for (const [key, value] of Object.entries(params)) {
|
|
1914
|
-
if (value === void 0) continue;
|
|
1915
|
-
searchParams.set(key, String(value));
|
|
1916
|
-
}
|
|
1917
|
-
const query2 = searchParams.toString();
|
|
1918
|
-
return query2 ? `${path}?${query2}` : path;
|
|
1919
|
-
}
|
|
1920
|
-
async getProductStock(productId, locationId) {
|
|
1921
|
-
const encodedId = encodeURIComponent(productId);
|
|
1922
|
-
const path = this.withQuery(`/api/v1/inventory/products/${encodedId}/stock`, {
|
|
1923
|
-
location_id: locationId
|
|
1924
|
-
});
|
|
1925
|
-
return safe(this.client.get(path));
|
|
1926
|
-
}
|
|
1927
|
-
async getVariantStock(variantId, locationId) {
|
|
1928
|
-
const encodedId = encodeURIComponent(variantId);
|
|
1929
|
-
const path = this.withQuery(`/api/v1/inventory/variants/${encodedId}/stock`, {
|
|
1930
|
-
location_id: locationId
|
|
1931
|
-
});
|
|
1932
|
-
return safe(this.client.get(path));
|
|
1933
|
-
}
|
|
1934
|
-
async checkProductAvailability(productId, quantity, locationId) {
|
|
1935
|
-
const encodedId = encodeURIComponent(productId);
|
|
1936
|
-
const path = this.withQuery(`/api/v1/inventory/products/${encodedId}/availability`, {
|
|
1937
|
-
quantity,
|
|
1938
|
-
location_id: locationId
|
|
1939
|
-
});
|
|
1940
|
-
return safe(this.client.get(path));
|
|
1941
|
-
}
|
|
1942
|
-
async checkVariantAvailability(variantId, quantity, locationId) {
|
|
1943
|
-
const encodedId = encodeURIComponent(variantId);
|
|
1944
|
-
const path = this.withQuery(`/api/v1/inventory/variants/${encodedId}/availability`, {
|
|
1945
|
-
quantity,
|
|
1946
|
-
location_id: locationId
|
|
1947
|
-
});
|
|
1948
|
-
return safe(this.client.get(path));
|
|
1949
|
-
}
|
|
1950
|
-
async checkMultipleAvailability(items, locationId) {
|
|
1951
|
-
const results = await Promise.all(
|
|
1952
|
-
items.map(
|
|
1953
|
-
(item) => item.variant_id ? this.checkVariantAvailability(item.variant_id, item.quantity, locationId) : this.checkProductAvailability(item.product_id, item.quantity, locationId)
|
|
1954
|
-
)
|
|
1955
|
-
);
|
|
1956
|
-
for (const result of results) {
|
|
1957
|
-
if (!result.ok) return result;
|
|
1958
|
-
}
|
|
1959
|
-
return ok(results.map((r) => r.value));
|
|
1960
|
-
}
|
|
1961
|
-
async isInStock(productId, locationId) {
|
|
1962
|
-
const result = await this.checkProductAvailability(productId, 1, locationId);
|
|
1963
|
-
if (!result.ok) return result;
|
|
1964
|
-
return ok(result.value.is_available);
|
|
1965
|
-
}
|
|
1966
|
-
async getAvailableQuantity(productId, locationId) {
|
|
1967
|
-
const result = await this.getProductStock(productId, locationId);
|
|
1968
|
-
if (!result.ok) return result;
|
|
1969
|
-
return ok(result.value.available_quantity);
|
|
1970
|
-
}
|
|
1971
|
-
};
|
|
1972
|
-
|
|
1973
|
-
// src/scheduling.ts
|
|
1974
|
-
function withQuery2(path, params) {
|
|
1975
|
-
const searchParams = new URLSearchParams();
|
|
1976
|
-
for (const [key, value] of Object.entries(params)) {
|
|
1977
|
-
if (value === void 0) continue;
|
|
1978
|
-
searchParams.set(key, String(value));
|
|
1979
|
-
}
|
|
1980
|
-
const query2 = searchParams.toString();
|
|
1981
|
-
return query2 ? `${path}?${query2}` : path;
|
|
1982
|
-
}
|
|
1983
|
-
function firstScheduledTime(booking) {
|
|
1984
|
-
return booking.service_items.find((item) => typeof item.scheduled_start === "string")?.scheduled_start || booking.created_at;
|
|
1985
|
-
}
|
|
1986
|
-
var SchedulingService = class {
|
|
1987
|
-
constructor(client) {
|
|
1988
|
-
this.client = client;
|
|
1989
|
-
}
|
|
1990
|
-
async getServices() {
|
|
1991
|
-
return safe(this.client.get("/api/v1/scheduling/services"));
|
|
1992
|
-
}
|
|
1993
|
-
async getService(serviceId) {
|
|
1994
|
-
const encodedId = encodeURIComponent(serviceId);
|
|
1995
|
-
return safe(this.client.get(`/api/v1/scheduling/services/${encodedId}`));
|
|
1996
|
-
}
|
|
1997
|
-
async getAvailableSlots(input) {
|
|
1998
|
-
const path = withQuery2("/api/v1/scheduling/slots", {
|
|
1999
|
-
service_id: input.service_id,
|
|
2000
|
-
date: input.date,
|
|
2001
|
-
participant_count: input.participant_count,
|
|
2002
|
-
duration_minutes: input.duration_minutes
|
|
2003
|
-
});
|
|
2004
|
-
return safe(this.client.get(path));
|
|
2005
|
-
}
|
|
2006
|
-
async checkSlotAvailability(input) {
|
|
2007
|
-
const path = withQuery2("/api/v1/scheduling/slots/check", {
|
|
2008
|
-
service_id: input.service_id,
|
|
2009
|
-
slot_time: input.slot_time,
|
|
2010
|
-
duration_minutes: input.duration_minutes,
|
|
2011
|
-
participant_count: input.participant_count
|
|
2012
|
-
});
|
|
2013
|
-
return safe(this.client.get(path));
|
|
2014
|
-
}
|
|
2015
|
-
async getServiceAvailability(params) {
|
|
2016
|
-
const path = withQuery2("/api/v1/scheduling/availability", {
|
|
2017
|
-
service_id: params.service_id,
|
|
2018
|
-
start_date: params.start_date,
|
|
2019
|
-
end_date: params.end_date,
|
|
2020
|
-
location_id: params.location_id,
|
|
2021
|
-
participant_count: params.participant_count
|
|
2022
|
-
});
|
|
2023
|
-
return safe(this.client.get(path));
|
|
2024
|
-
}
|
|
2025
|
-
async getBooking(bookingId) {
|
|
2026
|
-
const encodedId = encodeURIComponent(bookingId);
|
|
2027
|
-
return safe(this.client.get(`/api/v1/scheduling/bookings/${encodedId}`));
|
|
2028
|
-
}
|
|
2029
|
-
async getCustomerBookings(customerId) {
|
|
2030
|
-
const path = withQuery2("/api/v1/scheduling/bookings", {
|
|
2031
|
-
customer_id: customerId
|
|
2032
|
-
});
|
|
2033
|
-
return safe(this.client.get(path));
|
|
2034
|
-
}
|
|
2035
|
-
async getUpcomingBookings() {
|
|
2036
|
-
const result = await this.getCustomerBookings();
|
|
2037
|
-
if (!result.ok) return result;
|
|
2038
|
-
const upcoming = result.value.filter((booking) => {
|
|
2039
|
-
const status = String(booking.status).toLowerCase();
|
|
2040
|
-
return status !== "completed" && status !== "cancelled";
|
|
2041
|
-
}).sort((a, b) => firstScheduledTime(a).localeCompare(firstScheduledTime(b)));
|
|
2042
|
-
return ok(upcoming);
|
|
2043
|
-
}
|
|
2044
|
-
async getPastBookings(limit = 10) {
|
|
2045
|
-
const result = await this.getCustomerBookings();
|
|
2046
|
-
if (!result.ok) return result;
|
|
2047
|
-
const past = result.value.filter((booking) => String(booking.status).toLowerCase() === "completed").sort((a, b) => firstScheduledTime(b).localeCompare(firstScheduledTime(a))).slice(0, Math.max(0, limit));
|
|
2048
|
-
return ok(past);
|
|
2049
|
-
}
|
|
2050
|
-
async cancelBooking(input) {
|
|
2051
|
-
const encodedId = encodeURIComponent(input.booking_id);
|
|
2052
|
-
return safe(
|
|
2053
|
-
this.client.post(`/api/v1/scheduling/bookings/${encodedId}/cancel`, {
|
|
2054
|
-
reason: input.reason
|
|
2055
|
-
})
|
|
2056
|
-
);
|
|
2057
|
-
}
|
|
2058
|
-
async rescheduleBooking(input) {
|
|
2059
|
-
return safe(
|
|
2060
|
-
this.client.post("/api/v1/scheduling/bookings/reschedule", input)
|
|
2061
|
-
);
|
|
2062
|
-
}
|
|
2063
|
-
async getNextAvailableSlot(serviceId, fromDate) {
|
|
2064
|
-
const date = fromDate || (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
2065
|
-
const result = await this.getAvailableSlots({
|
|
2066
|
-
service_id: serviceId,
|
|
2067
|
-
date
|
|
2068
|
-
});
|
|
2069
|
-
if (!result.ok) return result;
|
|
2070
|
-
return ok(result.value.find((slot) => slot.is_available) || null);
|
|
2071
|
-
}
|
|
2072
|
-
async hasAvailabilityOn(serviceId, date) {
|
|
2073
|
-
const result = await this.getAvailableSlots({
|
|
2074
|
-
service_id: serviceId,
|
|
2075
|
-
date
|
|
2076
|
-
});
|
|
2077
|
-
if (!result.ok) return result;
|
|
2078
|
-
return ok(result.value.some((slot) => slot.is_available));
|
|
2079
|
-
}
|
|
2080
|
-
};
|
|
2081
|
-
|
|
2082
|
-
// src/lite.ts
|
|
2083
|
-
var LiteService = class {
|
|
2084
|
-
constructor(client) {
|
|
2085
|
-
this.client = client;
|
|
2086
|
-
}
|
|
2087
|
-
async getBootstrap() {
|
|
2088
|
-
return safe(this.client.get("/api/v1/lite/bootstrap"));
|
|
2089
|
-
}
|
|
2090
|
-
async getTable(tableId) {
|
|
2091
|
-
const encodedId = encodeURIComponent(tableId);
|
|
2092
|
-
return safe(this.client.get(`/api/v1/lite/tables/${encodedId}`));
|
|
2093
|
-
}
|
|
2094
|
-
async getMenu() {
|
|
2095
|
-
return safe(this.client.get("/api/v1/lite/menu"));
|
|
2096
|
-
}
|
|
2097
|
-
async getMenuByCategory(categoryId) {
|
|
2098
|
-
const encodedId = encodeURIComponent(categoryId);
|
|
2099
|
-
return safe(this.client.get(`/api/v1/lite/menu/categories/${encodedId}`));
|
|
2100
|
-
}
|
|
2101
|
-
};
|
|
2102
|
-
|
|
2103
|
-
// src/fx.ts
|
|
2104
|
-
var FxService = class {
|
|
2105
|
-
constructor(client) {
|
|
2106
|
-
this.client = client;
|
|
2107
|
-
}
|
|
2108
|
-
async getRate(from, to) {
|
|
2109
|
-
const path = `/api/v1/fx/rate?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`;
|
|
2110
|
-
return safe(this.client.get(path));
|
|
2111
|
-
}
|
|
2112
|
-
async lockQuote(request) {
|
|
2113
|
-
return safe(this.client.post("/api/v1/fx/quotes", request));
|
|
2114
|
-
}
|
|
2115
|
-
};
|
|
2116
|
-
|
|
2117
|
-
// src/types/elements.ts
|
|
2118
|
-
var ELEMENT_TYPES = {
|
|
2119
|
-
AUTH: "auth",
|
|
2120
|
-
ADDRESS: "address",
|
|
2121
|
-
PAYMENT: "payment",
|
|
2122
|
-
CHECKOUT: "checkout"
|
|
2123
|
-
};
|
|
2124
|
-
var MESSAGE_TYPES = {
|
|
2125
|
-
INIT: "init",
|
|
2126
|
-
SET_TOKEN: "set_token",
|
|
2127
|
-
SET_CART: "set_cart",
|
|
2128
|
-
GET_DATA: "get_data",
|
|
2129
|
-
REFRESH_TOKEN: "refresh_token",
|
|
2130
|
-
LOGOUT: "logout",
|
|
2131
|
-
PROCESS_CHECKOUT: "process_checkout",
|
|
2132
|
-
ABORT_CHECKOUT: "abort_checkout",
|
|
2133
|
-
READY: "ready",
|
|
2134
|
-
HEIGHT_CHANGE: "height_change",
|
|
2135
|
-
AUTHENTICATED: "authenticated",
|
|
2136
|
-
REQUIRES_OTP: "requires_otp",
|
|
2137
|
-
ERROR: "error",
|
|
2138
|
-
ADDRESS_CHANGED: "address_changed",
|
|
2139
|
-
ADDRESS_SELECTED: "address_selected",
|
|
2140
|
-
PAYMENT_METHOD_SELECTED: "payment_method_selected",
|
|
2141
|
-
TOKEN_REFRESHED: "token_refreshed",
|
|
2142
|
-
LOGOUT_COMPLETE: "logout_complete",
|
|
2143
|
-
CONTACT_PROVIDED: "contact_provided",
|
|
2144
|
-
CHECKOUT_STATUS: "checkout_status",
|
|
2145
|
-
CHECKOUT_COMPLETE: "checkout_complete",
|
|
2146
|
-
ORDER_TYPE_CHANGED: "order_type_changed",
|
|
2147
|
-
REQUEST_SUBMIT: "request_submit"
|
|
2148
|
-
};
|
|
2149
|
-
var EVENT_TYPES = {
|
|
2150
|
-
READY: "ready",
|
|
2151
|
-
AUTHENTICATED: "authenticated",
|
|
2152
|
-
REQUIRES_OTP: "requires_otp",
|
|
2153
|
-
ERROR: "error",
|
|
2154
|
-
CHANGE: "change",
|
|
2155
|
-
BLUR: "blur",
|
|
2156
|
-
FOCUS: "focus",
|
|
2157
|
-
ORDER_TYPE_CHANGED: "order_type_changed",
|
|
2158
|
-
REQUEST_SUBMIT: "request_submit"
|
|
2159
|
-
};
|
|
2160
|
-
|
|
2161
|
-
// src/elements.ts
|
|
2162
|
-
function toCheckoutError(code, message, recoverable) {
|
|
2163
|
-
const hint = getErrorHint(code);
|
|
2164
|
-
return {
|
|
2165
|
-
success: false,
|
|
2166
|
-
error: {
|
|
2167
|
-
code,
|
|
2168
|
-
message,
|
|
2169
|
-
recoverable,
|
|
2170
|
-
docs_url: hint?.docs_url,
|
|
2171
|
-
suggestion: hint?.suggestion
|
|
2172
|
-
}
|
|
2173
|
-
};
|
|
2174
|
-
}
|
|
2175
|
-
var DEFAULT_LINK_URL = "https://link.cimplify.io";
|
|
2176
|
-
function generateNonce() {
|
|
2177
|
-
if (typeof crypto !== "undefined" && crypto.randomUUID) {
|
|
2178
|
-
return crypto.randomUUID().replace(/-/g, "").slice(0, 16);
|
|
2179
|
-
}
|
|
2180
|
-
return Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2);
|
|
2181
|
-
}
|
|
2182
|
-
function isAllowedOrigin(origin) {
|
|
2183
|
-
try {
|
|
2184
|
-
const url = new URL(origin);
|
|
2185
|
-
const hostname = url.hostname;
|
|
2186
|
-
if (hostname === "localhost" || hostname === "127.0.0.1") {
|
|
2187
|
-
return true;
|
|
2188
|
-
}
|
|
2189
|
-
if (url.protocol !== "https:") {
|
|
2190
|
-
return false;
|
|
2191
|
-
}
|
|
2192
|
-
return hostname === "cimplify.io" || hostname.endsWith(".cimplify.io");
|
|
2193
|
-
} catch {
|
|
2194
|
-
return false;
|
|
2195
|
-
}
|
|
2196
|
-
}
|
|
2197
|
-
function parseIframeMessage(data) {
|
|
2198
|
-
if (!data || typeof data !== "object") {
|
|
2199
|
-
return null;
|
|
2200
|
-
}
|
|
2201
|
-
const maybeType = data.type;
|
|
2202
|
-
if (typeof maybeType !== "string") {
|
|
2203
|
-
return null;
|
|
2204
|
-
}
|
|
2205
|
-
return data;
|
|
2206
|
-
}
|
|
2207
|
-
var CimplifyElements = class {
|
|
2208
|
-
constructor(client, businessId, options = {}) {
|
|
2209
|
-
this.elements = /* @__PURE__ */ new Map();
|
|
2210
|
-
this.accessToken = null;
|
|
2211
|
-
this.accountId = null;
|
|
2212
|
-
this.customerId = null;
|
|
2213
|
-
this.customerData = null;
|
|
2214
|
-
this.addressData = null;
|
|
2215
|
-
this.paymentData = null;
|
|
2216
|
-
this.checkoutInProgress = false;
|
|
2217
|
-
this.activeCheckoutAbort = null;
|
|
2218
|
-
this.businessIdResolvePromise = null;
|
|
2219
|
-
this.client = client;
|
|
2220
|
-
this.businessId = businessId ?? null;
|
|
2221
|
-
this.linkUrl = options.linkUrl || DEFAULT_LINK_URL;
|
|
2222
|
-
this.options = options;
|
|
2223
|
-
this.boundHandleMessage = this.handleMessage.bind(this);
|
|
2224
|
-
if (typeof window !== "undefined") {
|
|
2225
|
-
window.addEventListener("message", this.boundHandleMessage);
|
|
2226
|
-
}
|
|
2227
|
-
}
|
|
2228
|
-
debug(...args) {
|
|
2229
|
-
if (this.client.isTestMode()) {
|
|
2230
|
-
console.debug(...args);
|
|
2231
|
-
}
|
|
2232
|
-
}
|
|
2233
|
-
create(type, options = {}) {
|
|
2234
|
-
const existing = this.elements.get(type);
|
|
2235
|
-
if (existing) return existing;
|
|
2236
|
-
const element = new CimplifyElement(type, this.businessId, this.linkUrl, options, this);
|
|
2237
|
-
this.elements.set(type, element);
|
|
2238
|
-
return element;
|
|
2239
|
-
}
|
|
2240
|
-
getElement(type) {
|
|
2241
|
-
return this.elements.get(type);
|
|
2242
|
-
}
|
|
2243
|
-
_removeElement(type, instance) {
|
|
2244
|
-
const current = this.elements.get(type);
|
|
2245
|
-
if (current === instance) {
|
|
2246
|
-
this.elements.delete(type);
|
|
2247
|
-
}
|
|
2248
|
-
}
|
|
2249
|
-
destroy() {
|
|
2250
|
-
this.elements.forEach((element) => element.destroy());
|
|
2251
|
-
this.elements.clear();
|
|
2252
|
-
if (typeof window !== "undefined") {
|
|
2253
|
-
window.removeEventListener("message", this.boundHandleMessage);
|
|
2254
|
-
}
|
|
2255
|
-
}
|
|
2256
|
-
async submitCheckout(data) {
|
|
2257
|
-
const result = await this.processCheckout({
|
|
2258
|
-
cart_id: data.cart_id,
|
|
2259
|
-
order_type: data.order_type ?? "delivery",
|
|
2260
|
-
location_id: data.location_id,
|
|
2261
|
-
notes: data.notes,
|
|
2262
|
-
scheduled_time: data.scheduled_time,
|
|
2263
|
-
tip_amount: data.tip_amount,
|
|
2264
|
-
enroll_in_link: true
|
|
2265
|
-
});
|
|
2266
|
-
if (result.success) {
|
|
2267
|
-
return {
|
|
2268
|
-
success: true,
|
|
2269
|
-
order: {
|
|
2270
|
-
id: result.order?.id || "",
|
|
2271
|
-
status: result.order?.status || "unknown",
|
|
2272
|
-
total: result.order?.total || ""
|
|
2273
|
-
}
|
|
2274
|
-
};
|
|
2275
|
-
}
|
|
2276
|
-
return {
|
|
2277
|
-
success: false,
|
|
2278
|
-
error: {
|
|
2279
|
-
code: result.error?.code || "CHECKOUT_FAILED",
|
|
2280
|
-
message: result.error?.message || "Checkout failed"
|
|
2281
|
-
}
|
|
2282
|
-
};
|
|
2283
|
-
}
|
|
2284
|
-
processCheckout(options) {
|
|
2285
|
-
let abortFn = null;
|
|
2286
|
-
const task = (async () => {
|
|
2287
|
-
this.debug("[cimplify:checkout] processCheckout called", { cart_id: options.cart_id, order_type: options.order_type, location_id: options.location_id });
|
|
2288
|
-
if (this.checkoutInProgress) {
|
|
2289
|
-
this.debug("[cimplify:checkout] BLOCKED: already processing");
|
|
2290
|
-
return toCheckoutError(
|
|
2291
|
-
"ALREADY_PROCESSING",
|
|
2292
|
-
"Checkout is already in progress.",
|
|
2293
|
-
false
|
|
2294
|
-
);
|
|
2295
|
-
}
|
|
2296
|
-
this.checkoutInProgress = true;
|
|
2297
|
-
if (!options.cart_id) {
|
|
2298
|
-
this.debug("[cimplify:checkout] BLOCKED: no cart_id");
|
|
2299
|
-
this.checkoutInProgress = false;
|
|
2300
|
-
return toCheckoutError(
|
|
2301
|
-
"INVALID_CART",
|
|
2302
|
-
"A valid cart is required before checkout can start.",
|
|
2303
|
-
false
|
|
2304
|
-
);
|
|
2305
|
-
}
|
|
2306
|
-
if (!options.order_type) {
|
|
2307
|
-
this.debug("[cimplify:checkout] BLOCKED: no order_type");
|
|
2308
|
-
this.checkoutInProgress = false;
|
|
2309
|
-
return toCheckoutError(
|
|
2310
|
-
"ORDER_TYPE_REQUIRED",
|
|
2311
|
-
"Order type is required before checkout can start.",
|
|
2312
|
-
false
|
|
2313
|
-
);
|
|
2314
|
-
}
|
|
2315
|
-
const checkoutElement = this.elements.get(ELEMENT_TYPES.CHECKOUT) || this.elements.get(ELEMENT_TYPES.PAYMENT);
|
|
2316
|
-
if (!checkoutElement) {
|
|
2317
|
-
this.debug("[cimplify:checkout] BLOCKED: no checkout element");
|
|
2318
|
-
this.checkoutInProgress = false;
|
|
2319
|
-
return toCheckoutError(
|
|
2320
|
-
"NO_PAYMENT_ELEMENT",
|
|
2321
|
-
"Checkout element must be mounted before checkout.",
|
|
2322
|
-
false
|
|
2323
|
-
);
|
|
2324
|
-
}
|
|
2325
|
-
if (!checkoutElement.isMounted()) {
|
|
2326
|
-
this.debug("[cimplify:checkout] BLOCKED: checkout element not mounted");
|
|
2327
|
-
this.checkoutInProgress = false;
|
|
2328
|
-
return toCheckoutError(
|
|
2329
|
-
"PAYMENT_NOT_MOUNTED",
|
|
2330
|
-
"Checkout element must be mounted before checkout.",
|
|
2331
|
-
false
|
|
2332
|
-
);
|
|
2333
|
-
}
|
|
2334
|
-
const isUnifiedCheckout = this.elements.has(ELEMENT_TYPES.CHECKOUT);
|
|
2335
|
-
if (!isUnifiedCheckout) {
|
|
2336
|
-
const authElement = this.elements.get(ELEMENT_TYPES.AUTH);
|
|
2337
|
-
if (authElement && !this.accessToken) {
|
|
2338
|
-
this.debug("[cimplify:checkout] BLOCKED: auth incomplete");
|
|
2339
|
-
this.checkoutInProgress = false;
|
|
2340
|
-
return toCheckoutError(
|
|
2341
|
-
"AUTH_INCOMPLETE",
|
|
2342
|
-
"Authentication must complete before checkout can start.",
|
|
2343
|
-
true
|
|
2344
|
-
);
|
|
2345
|
-
}
|
|
2346
|
-
const addressElement = this.elements.get(ELEMENT_TYPES.ADDRESS);
|
|
2347
|
-
if (addressElement) {
|
|
2348
|
-
this.debug("[cimplify:checkout] getting address data...");
|
|
2349
|
-
await addressElement.getData();
|
|
2350
|
-
this.debug("[cimplify:checkout] address data resolved", this.addressData);
|
|
2351
|
-
}
|
|
2352
|
-
await this.hydrateCustomerData();
|
|
2353
|
-
}
|
|
2354
|
-
this.debug("[cimplify:checkout] customer data hydrated", { customerData: this.customerData, accountId: this.accountId, isUnifiedCheckout });
|
|
2355
|
-
const processMessage = {
|
|
2356
|
-
type: MESSAGE_TYPES.PROCESS_CHECKOUT,
|
|
2357
|
-
cart_id: options.cart_id,
|
|
2358
|
-
order_type: options.order_type,
|
|
2359
|
-
location_id: options.location_id,
|
|
2360
|
-
notes: options.notes,
|
|
2361
|
-
scheduled_time: options.scheduled_time,
|
|
2362
|
-
tip_amount: options.tip_amount,
|
|
2363
|
-
pay_currency: options.pay_currency,
|
|
2364
|
-
enroll_in_link: options.enroll_in_link ?? true,
|
|
2365
|
-
address: isUnifiedCheckout ? void 0 : this.addressData ?? void 0,
|
|
2366
|
-
customer: isUnifiedCheckout ? void 0 : this.customerData ? {
|
|
2367
|
-
name: this.customerData.name,
|
|
2368
|
-
email: this.customerData.email,
|
|
2369
|
-
phone: this.customerData.phone
|
|
2370
|
-
} : null,
|
|
2371
|
-
account_id: this.accountId ?? void 0,
|
|
2372
|
-
customer_id: this.customerId ?? void 0
|
|
2373
|
-
};
|
|
2374
|
-
const timeoutMs = options.timeout_ms ?? 18e4;
|
|
2375
|
-
const paymentWindow = checkoutElement.getContentWindow();
|
|
2376
|
-
return new Promise((resolve) => {
|
|
2377
|
-
let settled = false;
|
|
2378
|
-
const cleanup = () => {
|
|
2379
|
-
if (typeof window !== "undefined") {
|
|
2380
|
-
window.removeEventListener("message", handleCheckoutMessage);
|
|
2381
|
-
}
|
|
2382
|
-
clearTimeout(timeout);
|
|
2383
|
-
this.checkoutInProgress = false;
|
|
2384
|
-
this.activeCheckoutAbort = null;
|
|
2385
|
-
};
|
|
2386
|
-
const settle = (result) => {
|
|
2387
|
-
if (settled) {
|
|
2388
|
-
return;
|
|
2389
|
-
}
|
|
2390
|
-
settled = true;
|
|
2391
|
-
cleanup();
|
|
2392
|
-
resolve(result);
|
|
2393
|
-
};
|
|
2394
|
-
const timeout = setTimeout(() => {
|
|
2395
|
-
settle(
|
|
2396
|
-
toCheckoutError(
|
|
2397
|
-
"TIMEOUT",
|
|
2398
|
-
"Checkout timed out before receiving a terminal response.",
|
|
2399
|
-
true
|
|
2400
|
-
)
|
|
2401
|
-
);
|
|
2402
|
-
}, timeoutMs);
|
|
2403
|
-
const handleCheckoutMessage = (event) => {
|
|
2404
|
-
if (!isAllowedOrigin(event.origin)) {
|
|
2405
|
-
return;
|
|
2406
|
-
}
|
|
2407
|
-
const message = parseIframeMessage(event.data);
|
|
2408
|
-
if (!message) {
|
|
2409
|
-
return;
|
|
2410
|
-
}
|
|
2411
|
-
if (message.type === MESSAGE_TYPES.LOGOUT_COMPLETE) {
|
|
2412
|
-
checkoutElement.sendMessage({ type: MESSAGE_TYPES.ABORT_CHECKOUT });
|
|
2413
|
-
settle(
|
|
2414
|
-
toCheckoutError(
|
|
2415
|
-
"AUTH_LOST",
|
|
2416
|
-
"Authentication was cleared during checkout.",
|
|
2417
|
-
true
|
|
2418
|
-
)
|
|
2419
|
-
);
|
|
2420
|
-
return;
|
|
2421
|
-
}
|
|
2422
|
-
if (paymentWindow && event.source && event.source !== paymentWindow) {
|
|
2423
|
-
return;
|
|
2424
|
-
}
|
|
2425
|
-
if (message.type === MESSAGE_TYPES.CHECKOUT_STATUS) {
|
|
2426
|
-
options.on_status_change?.(message.status, message.context);
|
|
2427
|
-
return;
|
|
2428
|
-
}
|
|
2429
|
-
if (message.type === MESSAGE_TYPES.CHECKOUT_COMPLETE) {
|
|
2430
|
-
this.debug("[cimplify:checkout] received checkout_complete", { success: message.success, error: message.error });
|
|
2431
|
-
settle({
|
|
2432
|
-
success: message.success,
|
|
2433
|
-
order: message.order,
|
|
2434
|
-
error: message.error,
|
|
2435
|
-
enrolled_in_link: message.enrolled_in_link
|
|
2436
|
-
});
|
|
2437
|
-
}
|
|
2438
|
-
};
|
|
2439
|
-
if (typeof window !== "undefined") {
|
|
2440
|
-
window.addEventListener("message", handleCheckoutMessage);
|
|
2441
|
-
}
|
|
2442
|
-
abortFn = () => {
|
|
2443
|
-
checkoutElement.sendMessage({ type: MESSAGE_TYPES.ABORT_CHECKOUT });
|
|
2444
|
-
settle(
|
|
2445
|
-
toCheckoutError(
|
|
2446
|
-
"CANCELLED",
|
|
2447
|
-
"Checkout was cancelled.",
|
|
2448
|
-
true
|
|
2449
|
-
)
|
|
2450
|
-
);
|
|
2451
|
-
};
|
|
2452
|
-
this.activeCheckoutAbort = abortFn;
|
|
2453
|
-
this.debug("[cimplify:checkout] sending process_checkout to checkout iframe", { cart_id: processMessage.cart_id, order_type: processMessage.order_type, hasCustomer: !!processMessage.customer, hasAddress: !!processMessage.address, isUnifiedCheckout });
|
|
2454
|
-
checkoutElement.sendMessage(processMessage);
|
|
2455
|
-
this.debug("[cimplify:checkout] postMessage sent, waiting for checkout_complete...");
|
|
2456
|
-
});
|
|
2457
|
-
})();
|
|
2458
|
-
const abortable = task;
|
|
2459
|
-
abortable.abort = () => {
|
|
2460
|
-
if (abortFn) {
|
|
2461
|
-
abortFn();
|
|
2462
|
-
}
|
|
2463
|
-
};
|
|
2464
|
-
return abortable;
|
|
2465
|
-
}
|
|
2466
|
-
isAuthenticated() {
|
|
2467
|
-
return this.accessToken !== null;
|
|
2468
|
-
}
|
|
2469
|
-
getAccessToken() {
|
|
2470
|
-
return this.accessToken;
|
|
2471
|
-
}
|
|
2472
|
-
getPublicKey() {
|
|
2473
|
-
return this.client.getPublicKey();
|
|
2474
|
-
}
|
|
2475
|
-
getBusinessId() {
|
|
2476
|
-
return this.businessId;
|
|
2477
|
-
}
|
|
2478
|
-
async resolveBusinessId() {
|
|
2479
|
-
if (this.businessId) {
|
|
2480
|
-
return this.businessId;
|
|
2481
|
-
}
|
|
2482
|
-
if (this.businessIdResolvePromise) {
|
|
2483
|
-
return this.businessIdResolvePromise;
|
|
2484
|
-
}
|
|
2485
|
-
this.businessIdResolvePromise = this.client.resolveBusinessId().then((resolvedBusinessId) => {
|
|
2486
|
-
this.businessId = resolvedBusinessId;
|
|
2487
|
-
return resolvedBusinessId;
|
|
2488
|
-
}).catch(() => null).finally(() => {
|
|
2489
|
-
this.businessIdResolvePromise = null;
|
|
2490
|
-
});
|
|
2491
|
-
return this.businessIdResolvePromise;
|
|
2492
|
-
}
|
|
2493
|
-
getAppearance() {
|
|
2494
|
-
return this.options.appearance;
|
|
2495
|
-
}
|
|
2496
|
-
async hydrateCustomerData() {
|
|
2497
|
-
if (!this.accessToken || this.customerData) {
|
|
2498
|
-
return;
|
|
2499
|
-
}
|
|
2500
|
-
if (!this.client.getAccessToken()) {
|
|
2501
|
-
this.client.setAccessToken(this.accessToken);
|
|
2502
|
-
}
|
|
2503
|
-
const linkDataResult = await this.client.link.getLinkData();
|
|
2504
|
-
if (!linkDataResult.ok || !linkDataResult.value?.customer) {
|
|
2505
|
-
return;
|
|
2506
|
-
}
|
|
2507
|
-
const customer = linkDataResult.value.customer;
|
|
2508
|
-
this.customerData = {
|
|
2509
|
-
name: customer.name || "",
|
|
2510
|
-
email: customer.email || null,
|
|
2511
|
-
phone: customer.phone || null
|
|
2512
|
-
};
|
|
2513
|
-
}
|
|
2514
|
-
handleMessage(event) {
|
|
2515
|
-
if (!isAllowedOrigin(event.origin)) {
|
|
2516
|
-
return;
|
|
2517
|
-
}
|
|
2518
|
-
const message = parseIframeMessage(event.data);
|
|
2519
|
-
if (!message) return;
|
|
2520
|
-
switch (message.type) {
|
|
2521
|
-
case MESSAGE_TYPES.AUTHENTICATED:
|
|
2522
|
-
const customer = message.customer ?? {
|
|
2523
|
-
name: "",
|
|
2524
|
-
email: null,
|
|
2525
|
-
phone: null
|
|
2526
|
-
};
|
|
2527
|
-
this.accessToken = message.token;
|
|
2528
|
-
this.accountId = message.accountId;
|
|
2529
|
-
this.customerId = message.customerId;
|
|
2530
|
-
this.customerData = customer;
|
|
2531
|
-
this.client.setAccessToken(message.token);
|
|
2532
|
-
this.elements.forEach((element, type) => {
|
|
2533
|
-
if (type !== ELEMENT_TYPES.AUTH && type !== ELEMENT_TYPES.CHECKOUT) {
|
|
2534
|
-
element.sendMessage({ type: MESSAGE_TYPES.SET_TOKEN, token: message.token });
|
|
2535
|
-
}
|
|
2536
|
-
});
|
|
2537
|
-
break;
|
|
2538
|
-
case MESSAGE_TYPES.TOKEN_REFRESHED:
|
|
2539
|
-
this.accessToken = message.token;
|
|
2540
|
-
break;
|
|
2541
|
-
case MESSAGE_TYPES.ADDRESS_CHANGED:
|
|
2542
|
-
case MESSAGE_TYPES.ADDRESS_SELECTED:
|
|
2543
|
-
this.addressData = message.address;
|
|
2544
|
-
break;
|
|
2545
|
-
case MESSAGE_TYPES.PAYMENT_METHOD_SELECTED:
|
|
2546
|
-
this.paymentData = message.method;
|
|
2547
|
-
break;
|
|
2548
|
-
case MESSAGE_TYPES.CONTACT_PROVIDED:
|
|
2549
|
-
if (!this.customerData) {
|
|
2550
|
-
this.customerData = { name: "", email: null, phone: null };
|
|
2551
|
-
}
|
|
2552
|
-
if (message.contactType === "email") {
|
|
2553
|
-
this.customerData.email = message.contact;
|
|
2554
|
-
} else {
|
|
2555
|
-
this.customerData.phone = message.contact;
|
|
2556
|
-
}
|
|
2557
|
-
break;
|
|
2558
|
-
case MESSAGE_TYPES.LOGOUT_COMPLETE:
|
|
2559
|
-
if (this.checkoutInProgress && this.activeCheckoutAbort) {
|
|
2560
|
-
this.activeCheckoutAbort();
|
|
2561
|
-
}
|
|
2562
|
-
this.accessToken = null;
|
|
2563
|
-
this.accountId = null;
|
|
2564
|
-
this.customerId = null;
|
|
2565
|
-
this.customerData = null;
|
|
2566
|
-
this.addressData = null;
|
|
2567
|
-
this.paymentData = null;
|
|
2568
|
-
this.client.clearSession();
|
|
2569
|
-
break;
|
|
2570
|
-
}
|
|
2571
|
-
}
|
|
2572
|
-
_setAddressData(data) {
|
|
2573
|
-
this.addressData = data;
|
|
2574
|
-
}
|
|
2575
|
-
_setPaymentData(data) {
|
|
2576
|
-
this.paymentData = data;
|
|
2577
|
-
}
|
|
2578
|
-
_setGuestContact(contact, contactType) {
|
|
2579
|
-
if (!this.customerData) {
|
|
2580
|
-
this.customerData = { name: "", email: null, phone: null };
|
|
2581
|
-
}
|
|
2582
|
-
if (contactType === "email") {
|
|
2583
|
-
this.customerData.email = contact;
|
|
2584
|
-
} else {
|
|
2585
|
-
this.customerData.phone = contact;
|
|
2586
|
-
}
|
|
2587
|
-
}
|
|
2588
|
-
};
|
|
2589
|
-
var CimplifyElement = class {
|
|
2590
|
-
constructor(type, businessId, linkUrl, options, parent) {
|
|
2591
|
-
this.iframe = null;
|
|
2592
|
-
this.container = null;
|
|
2593
|
-
this.mounted = false;
|
|
2594
|
-
this.pendingInit = null;
|
|
2595
|
-
this.eventHandlers = /* @__PURE__ */ new Map();
|
|
2596
|
-
this.resolvers = /* @__PURE__ */ new Map();
|
|
2597
|
-
this.listening = false;
|
|
2598
|
-
this.type = type;
|
|
2599
|
-
this.businessId = businessId;
|
|
2600
|
-
this.linkUrl = linkUrl;
|
|
2601
|
-
this.options = options;
|
|
2602
|
-
this.parent = parent;
|
|
2603
|
-
this.nonce = generateNonce();
|
|
2604
|
-
this.boundHandleMessage = this.handleMessage.bind(this);
|
|
2605
|
-
if (typeof window !== "undefined") {
|
|
2606
|
-
window.addEventListener("message", this.boundHandleMessage);
|
|
2607
|
-
this.listening = true;
|
|
2608
|
-
}
|
|
2609
|
-
}
|
|
2610
|
-
mount(container) {
|
|
2611
|
-
if (this.mounted) {
|
|
2612
|
-
console.warn(`Element ${this.type} is already mounted`);
|
|
2613
|
-
return;
|
|
2614
|
-
}
|
|
2615
|
-
const target = typeof container === "string" ? document.querySelector(container) : container;
|
|
2616
|
-
if (!target) {
|
|
2617
|
-
console.error(`Container not found: ${container}`);
|
|
2618
|
-
return;
|
|
2619
|
-
}
|
|
2620
|
-
this.container = target;
|
|
2621
|
-
this.mounted = true;
|
|
2622
|
-
if (!this.listening && typeof window !== "undefined") {
|
|
2623
|
-
window.addEventListener("message", this.boundHandleMessage);
|
|
2624
|
-
this.listening = true;
|
|
2625
|
-
}
|
|
2626
|
-
void this.createIframe();
|
|
2627
|
-
}
|
|
2628
|
-
destroy() {
|
|
2629
|
-
if (this.iframe) {
|
|
2630
|
-
this.iframe.remove();
|
|
2631
|
-
this.iframe = null;
|
|
2632
|
-
}
|
|
2633
|
-
this.container = null;
|
|
2634
|
-
this.mounted = false;
|
|
2635
|
-
this.eventHandlers.clear();
|
|
2636
|
-
this.resolvers.forEach((entry) => clearTimeout(entry.timeoutId));
|
|
2637
|
-
this.resolvers.clear();
|
|
2638
|
-
if (this.listening && typeof window !== "undefined") {
|
|
2639
|
-
window.removeEventListener("message", this.boundHandleMessage);
|
|
2640
|
-
this.listening = false;
|
|
2641
|
-
}
|
|
2642
|
-
this.parent._removeElement(this.type, this);
|
|
2643
|
-
}
|
|
2644
|
-
on(event, handler) {
|
|
2645
|
-
if (!this.eventHandlers.has(event)) {
|
|
2646
|
-
this.eventHandlers.set(event, /* @__PURE__ */ new Set());
|
|
2647
|
-
}
|
|
2648
|
-
this.eventHandlers.get(event).add(handler);
|
|
2649
|
-
}
|
|
2650
|
-
off(event, handler) {
|
|
2651
|
-
this.eventHandlers.get(event)?.delete(handler);
|
|
2652
|
-
}
|
|
2653
|
-
async getData() {
|
|
2654
|
-
if (!this.isMounted()) {
|
|
2655
|
-
return null;
|
|
2656
|
-
}
|
|
2657
|
-
return new Promise((resolve) => {
|
|
2658
|
-
const id = Math.random().toString(36).slice(2);
|
|
2659
|
-
const timeoutId = setTimeout(() => {
|
|
2660
|
-
const entry = this.resolvers.get(id);
|
|
2661
|
-
if (!entry) {
|
|
2662
|
-
return;
|
|
2663
|
-
}
|
|
2664
|
-
this.resolvers.delete(id);
|
|
2665
|
-
entry.resolve(null);
|
|
2666
|
-
}, 5e3);
|
|
2667
|
-
this.resolvers.set(id, { resolve, timeoutId });
|
|
2668
|
-
this.sendMessage({ type: MESSAGE_TYPES.GET_DATA });
|
|
2669
|
-
});
|
|
2670
|
-
}
|
|
2671
|
-
setCart(cart) {
|
|
2672
|
-
this.sendMessage({ type: MESSAGE_TYPES.SET_CART, cart });
|
|
2673
|
-
}
|
|
2674
|
-
sendMessage(message) {
|
|
2675
|
-
if (this.iframe?.contentWindow) {
|
|
2676
|
-
this.iframe.contentWindow.postMessage(message, this.linkUrl);
|
|
2677
|
-
} else {
|
|
2678
|
-
console.warn("[cimplify:checkout] sendMessage DROPPED \u2014 no contentWindow", { type: message.type, hasIframe: !!this.iframe, isConnected: this.iframe?.isConnected });
|
|
2679
|
-
}
|
|
2680
|
-
}
|
|
2681
|
-
getContentWindow() {
|
|
2682
|
-
return this.iframe?.contentWindow ?? null;
|
|
2683
|
-
}
|
|
2684
|
-
isMounted() {
|
|
2685
|
-
return this.mounted && Boolean(this.iframe) && this.iframe?.isConnected === true;
|
|
2686
|
-
}
|
|
2687
|
-
async createIframe() {
|
|
2688
|
-
if (!this.container) return;
|
|
2689
|
-
const resolvedBusinessId = this.businessId ?? await this.parent.resolveBusinessId();
|
|
2690
|
-
if (!resolvedBusinessId || !this.container || !this.mounted) {
|
|
2691
|
-
console.error("Unable to mount element without a resolved business ID");
|
|
2692
|
-
this.emit(EVENT_TYPES.ERROR, {
|
|
2693
|
-
code: "BUSINESS_ID_REQUIRED",
|
|
2694
|
-
message: "Unable to initialize checkout without a business ID."
|
|
2695
|
-
});
|
|
2696
|
-
return;
|
|
2697
|
-
}
|
|
2698
|
-
this.businessId = resolvedBusinessId;
|
|
2699
|
-
const iframe = document.createElement("iframe");
|
|
2700
|
-
const url = new URL(`${this.linkUrl}/elements/${this.type}`);
|
|
2701
|
-
url.searchParams.set("businessId", resolvedBusinessId);
|
|
2702
|
-
url.searchParams.set("nonce", this.nonce);
|
|
2703
|
-
if (this.options.prefillEmail) url.searchParams.set("email", this.options.prefillEmail);
|
|
2704
|
-
if (this.options.mode) url.searchParams.set("mode", this.options.mode);
|
|
2705
|
-
iframe.src = url.toString();
|
|
2706
|
-
iframe.style.border = "none";
|
|
2707
|
-
iframe.style.width = "100%";
|
|
2708
|
-
iframe.style.minHeight = "200px";
|
|
2709
|
-
iframe.style.display = "block";
|
|
2710
|
-
iframe.style.overflow = "hidden";
|
|
2711
|
-
iframe.style.background = "transparent";
|
|
2712
|
-
iframe.setAttribute("allowtransparency", "true");
|
|
2713
|
-
iframe.setAttribute("frameborder", "0");
|
|
2714
|
-
iframe.setAttribute("allow", "geolocation");
|
|
2715
|
-
iframe.setAttribute(
|
|
2716
|
-
"sandbox",
|
|
2717
|
-
"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"
|
|
2718
|
-
);
|
|
2719
|
-
this.iframe = iframe;
|
|
2720
|
-
this.container.appendChild(iframe);
|
|
2721
|
-
this.pendingInit = {
|
|
2722
|
-
businessId: resolvedBusinessId,
|
|
2723
|
-
publicKey: this.parent.getPublicKey()
|
|
2724
|
-
};
|
|
2725
|
-
}
|
|
2726
|
-
handleMessage(event) {
|
|
2727
|
-
if (!isAllowedOrigin(event.origin)) {
|
|
2728
|
-
return;
|
|
2729
|
-
}
|
|
2730
|
-
const data = event.data;
|
|
2731
|
-
if (data?.nonce) {
|
|
2732
|
-
if (data.nonce !== this.nonce) return;
|
|
2733
|
-
} else {
|
|
2734
|
-
const iframeWindow = this.iframe?.contentWindow;
|
|
2735
|
-
if (iframeWindow && event.source && event.source !== iframeWindow) {
|
|
2736
|
-
return;
|
|
2737
|
-
}
|
|
2738
|
-
}
|
|
2739
|
-
const message = parseIframeMessage(event.data);
|
|
2740
|
-
if (!message) return;
|
|
2741
|
-
switch (message.type) {
|
|
2742
|
-
case MESSAGE_TYPES.READY:
|
|
2743
|
-
if (this.iframe && message.height) this.iframe.style.height = `${message.height}px`;
|
|
2744
|
-
if (this.pendingInit) {
|
|
2745
|
-
const { publicKey } = this.pendingInit;
|
|
2746
|
-
this.sendMessage({
|
|
2747
|
-
type: MESSAGE_TYPES.INIT,
|
|
2748
|
-
businessId: this.pendingInit.businessId,
|
|
2749
|
-
publicKey,
|
|
2750
|
-
demoMode: publicKey.length === 0,
|
|
2751
|
-
prefillEmail: this.options.prefillEmail,
|
|
2752
|
-
appearance: this.parent.getAppearance(),
|
|
2753
|
-
orderTypes: this.options.orderTypes,
|
|
2754
|
-
defaultOrderType: this.options.defaultOrderType,
|
|
2755
|
-
renderSubmitButton: true,
|
|
2756
|
-
submitLabel: this.options.submitLabel
|
|
2757
|
-
});
|
|
2758
|
-
const token = this.parent.getAccessToken();
|
|
2759
|
-
if (token && this.type !== ELEMENT_TYPES.AUTH) {
|
|
2760
|
-
this.sendMessage({ type: MESSAGE_TYPES.SET_TOKEN, token });
|
|
2761
|
-
}
|
|
2762
|
-
this.pendingInit = null;
|
|
2763
|
-
}
|
|
2764
|
-
this.emit(EVENT_TYPES.READY, { height: message.height });
|
|
2765
|
-
break;
|
|
2766
|
-
case MESSAGE_TYPES.HEIGHT_CHANGE:
|
|
2767
|
-
if (this.iframe) this.iframe.style.height = `${message.height}px`;
|
|
2768
|
-
break;
|
|
2769
|
-
case MESSAGE_TYPES.AUTHENTICATED:
|
|
2770
|
-
const customer = message.customer ?? {
|
|
2771
|
-
name: "",
|
|
2772
|
-
email: null,
|
|
2773
|
-
phone: null
|
|
2774
|
-
};
|
|
2775
|
-
this.emit(EVENT_TYPES.AUTHENTICATED, {
|
|
2776
|
-
accountId: message.accountId,
|
|
2777
|
-
customerId: message.customerId,
|
|
2778
|
-
token: message.token,
|
|
2779
|
-
customer
|
|
2780
|
-
});
|
|
2781
|
-
break;
|
|
2782
|
-
case MESSAGE_TYPES.REQUIRES_OTP:
|
|
2783
|
-
this.emit(EVENT_TYPES.REQUIRES_OTP, { contactMasked: message.contactMasked });
|
|
2784
|
-
break;
|
|
2785
|
-
case MESSAGE_TYPES.ERROR:
|
|
2786
|
-
this.emit(EVENT_TYPES.ERROR, { code: message.code, message: message.message });
|
|
2787
|
-
break;
|
|
2788
|
-
case MESSAGE_TYPES.ADDRESS_CHANGED:
|
|
2789
|
-
case MESSAGE_TYPES.ADDRESS_SELECTED:
|
|
2790
|
-
this.parent._setAddressData(message.address);
|
|
2791
|
-
this.emit(EVENT_TYPES.CHANGE, { address: message.address });
|
|
2792
|
-
this.resolveData(message.address);
|
|
2793
|
-
break;
|
|
2794
|
-
case MESSAGE_TYPES.PAYMENT_METHOD_SELECTED:
|
|
2795
|
-
this.parent._setPaymentData(message.method);
|
|
2796
|
-
this.emit(EVENT_TYPES.CHANGE, { paymentMethod: message.method });
|
|
2797
|
-
this.resolveData(message.method);
|
|
2798
|
-
break;
|
|
2799
|
-
case MESSAGE_TYPES.CONTACT_PROVIDED:
|
|
2800
|
-
this.parent._setGuestContact(message.contact, message.contactType);
|
|
2801
|
-
break;
|
|
2802
|
-
case MESSAGE_TYPES.ORDER_TYPE_CHANGED:
|
|
2803
|
-
this.emit(EVENT_TYPES.ORDER_TYPE_CHANGED, { orderType: message.orderType });
|
|
2804
|
-
break;
|
|
2805
|
-
case MESSAGE_TYPES.REQUEST_SUBMIT:
|
|
2806
|
-
this.emit(EVENT_TYPES.REQUEST_SUBMIT, {});
|
|
2807
|
-
break;
|
|
2808
|
-
}
|
|
2809
|
-
}
|
|
2810
|
-
emit(event, data) {
|
|
2811
|
-
this.eventHandlers.get(event)?.forEach((handler) => handler(data));
|
|
2812
|
-
}
|
|
2813
|
-
resolveData(data) {
|
|
2814
|
-
this.resolvers.forEach((entry) => {
|
|
2815
|
-
clearTimeout(entry.timeoutId);
|
|
2816
|
-
entry.resolve(data);
|
|
2817
|
-
});
|
|
2818
|
-
this.resolvers.clear();
|
|
2819
|
-
}
|
|
2820
|
-
};
|
|
2821
|
-
function createElements(client, businessId, options) {
|
|
2822
|
-
return new CimplifyElements(client, businessId, options);
|
|
2823
|
-
}
|
|
2824
|
-
|
|
2825
|
-
// src/query/builder.ts
|
|
2826
|
-
function escapeQueryValue(value) {
|
|
2827
|
-
return value.replace(/'/g, "\\'");
|
|
2828
|
-
}
|
|
2829
|
-
var QueryBuilder = class {
|
|
2830
|
-
constructor(entity) {
|
|
2831
|
-
this.filters = [];
|
|
2832
|
-
this.modifiers = [];
|
|
2833
|
-
this.pathSegments = [];
|
|
2834
|
-
this.entity = entity;
|
|
2835
|
-
}
|
|
2836
|
-
path(segment) {
|
|
2837
|
-
this.pathSegments.push(segment);
|
|
2838
|
-
return this;
|
|
2839
|
-
}
|
|
2840
|
-
where(field, op, value) {
|
|
2841
|
-
const v = typeof value === "string" ? `'${escapeQueryValue(value)}'` : value;
|
|
2842
|
-
if (op === "contains" || op === "startsWith") {
|
|
2843
|
-
this.filters.push(`@.${field} ${op} ${v}`);
|
|
2844
|
-
} else {
|
|
2845
|
-
this.filters.push(`@.${field}${op}${v}`);
|
|
2846
|
-
}
|
|
2847
|
-
return this;
|
|
2848
|
-
}
|
|
2849
|
-
and(field, op, value) {
|
|
2850
|
-
return this.where(field, op, value);
|
|
2851
|
-
}
|
|
2852
|
-
sort(field, order = "asc") {
|
|
2853
|
-
this.modifiers.push(`sort(${field},${order})`);
|
|
2854
|
-
return this;
|
|
2855
|
-
}
|
|
2856
|
-
limit(n) {
|
|
2857
|
-
this.modifiers.push(`limit(${n})`);
|
|
2858
|
-
return this;
|
|
2859
|
-
}
|
|
2860
|
-
offset(n) {
|
|
2861
|
-
this.modifiers.push(`offset(${n})`);
|
|
2862
|
-
return this;
|
|
2863
|
-
}
|
|
2864
|
-
count() {
|
|
2865
|
-
this.modifiers.push("count");
|
|
2866
|
-
return this;
|
|
2867
|
-
}
|
|
2868
|
-
enriched() {
|
|
2869
|
-
this.modifiers.push("enriched");
|
|
2870
|
-
return this;
|
|
2871
|
-
}
|
|
2872
|
-
build() {
|
|
2873
|
-
let query2 = this.entity;
|
|
2874
|
-
if (this.pathSegments.length > 0) {
|
|
2875
|
-
query2 += "." + this.pathSegments.join(".");
|
|
2876
|
-
}
|
|
2877
|
-
if (this.filters.length > 0) {
|
|
2878
|
-
query2 += `[?(${this.filters.join(" && ")})]`;
|
|
2879
|
-
}
|
|
2880
|
-
for (const mod of this.modifiers) {
|
|
2881
|
-
query2 += `#${mod}`;
|
|
2882
|
-
}
|
|
2883
|
-
return query2;
|
|
2884
|
-
}
|
|
2885
|
-
toString() {
|
|
2886
|
-
return this.build();
|
|
2887
|
-
}
|
|
2888
|
-
};
|
|
2889
|
-
function query(entity) {
|
|
2890
|
-
return new QueryBuilder(entity);
|
|
2891
|
-
}
|
|
2892
|
-
|
|
2893
|
-
export { AuthService, BusinessService, CartOperations, CatalogueQueries, CheckoutService as CheckoutOperations, CheckoutService, CimplifyElement, CimplifyElements, ELEMENT_TYPES, EVENT_TYPES, FxService, InventoryService, LinkService, LiteService, MESSAGE_TYPES, OrderQueries, QueryBuilder, SchedulingService, createElements, generateIdempotencyKey, query };
|
|
1
|
+
export { QueryBuilder, query } from './chunk-LM3CJ4L7.mjs';
|
|
2
|
+
export { AuthService, BusinessService, CartOperations, CatalogueQueries, CheckoutService as CheckoutOperations, CheckoutService, CimplifyElement, CimplifyElements, ELEMENT_TYPES, EVENT_TYPES, FxService, InventoryService, LinkService, LiteService, MESSAGE_TYPES, OrderQueries, SchedulingService, createElements, generateIdempotencyKey } from './chunk-GFKBH7R2.mjs';
|
|
3
|
+
import './chunk-OVM5YWM5.mjs';
|