@cimplify/sdk 0.6.6 → 0.6.7
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.d.mts +2 -2
- package/dist/advanced.d.ts +2 -2
- package/dist/advanced.js +113 -17
- package/dist/advanced.mjs +113 -17
- package/dist/{client-CUFdFugo.d.mts → client-B4etj3AD.d.mts} +5 -1
- package/dist/{client-CjqNbEM6.d.ts → client-CYVVuP5J.d.ts} +5 -1
- package/dist/{index-B5Bj-Ikg.d.ts → index-BOYF-efj.d.ts} +1 -1
- package/dist/{index-CJ9GkIXf.d.mts → index-DzNb32O3.d.mts} +1 -1
- package/dist/index.d.mts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +168 -42
- package/dist/index.mjs +166 -43
- package/dist/{payment-D-u3asA8.d.mts → payment-pjpfIKX8.d.mts} +13 -2
- package/dist/{payment-D-u3asA8.d.ts → payment-pjpfIKX8.d.ts} +13 -2
- package/dist/react.d.mts +129 -3
- package/dist/react.d.ts +129 -3
- package/dist/react.js +1270 -41
- package/dist/react.mjs +1265 -43
- package/dist/utils.d.mts +2 -2
- package/dist/utils.d.ts +2 -2
- package/package.json +1 -1
package/dist/react.js
CHANGED
|
@@ -406,9 +406,11 @@ function CimplifyCheckout({
|
|
|
406
406
|
const elementsRef = react.useRef(null);
|
|
407
407
|
const activeCheckoutRef = react.useRef(null);
|
|
408
408
|
const initialAppearanceRef = react.useRef(appearance);
|
|
409
|
+
const hasWarnedInlineAppearanceRef = react.useRef(false);
|
|
409
410
|
const isMountedRef = react.useRef(true);
|
|
410
411
|
const demoRunRef = react.useRef(0);
|
|
411
412
|
const isDemoCheckout = demoMode ?? client.getPublicKey().trim().length === 0;
|
|
413
|
+
const isTestMode = client.isTestMode();
|
|
412
414
|
const emitStatus = react.useCallback(
|
|
413
415
|
(nextStatus, context = {}) => {
|
|
414
416
|
setStatus(nextStatus);
|
|
@@ -422,6 +424,14 @@ function CimplifyCheckout({
|
|
|
422
424
|
setOrderType(resolvedOrderTypes[0] || "pickup");
|
|
423
425
|
}
|
|
424
426
|
}, [resolvedOrderTypes, orderType]);
|
|
427
|
+
react.useEffect(() => {
|
|
428
|
+
if (appearance && appearance !== initialAppearanceRef.current && !hasWarnedInlineAppearanceRef.current) {
|
|
429
|
+
hasWarnedInlineAppearanceRef.current = true;
|
|
430
|
+
console.warn(
|
|
431
|
+
"[Cimplify] `appearance` prop reference changed after mount. Elements keep the initial appearance to avoid iframe remount. Memoize appearance with useMemo() to remove this warning."
|
|
432
|
+
);
|
|
433
|
+
}
|
|
434
|
+
}, [appearance]);
|
|
425
435
|
react.useEffect(() => {
|
|
426
436
|
let cancelled = false;
|
|
427
437
|
async function bootstrap() {
|
|
@@ -628,6 +638,19 @@ function CimplifyCheckout({
|
|
|
628
638
|
return /* @__PURE__ */ jsxRuntime.jsx("div", { className, "data-cimplify-checkout": "", children: /* @__PURE__ */ jsxRuntime.jsx("p", { "data-cimplify-error": "", style: { fontSize: "14px", color: "#b91c1c" }, children: errorMessage || "Unable to initialize checkout. Please refresh and try again." }) });
|
|
629
639
|
}
|
|
630
640
|
return /* @__PURE__ */ jsxRuntime.jsxs("div", { className, "data-cimplify-checkout": "", children: [
|
|
641
|
+
isTestMode && !isDemoCheckout && /* @__PURE__ */ jsxRuntime.jsx(
|
|
642
|
+
"p",
|
|
643
|
+
{
|
|
644
|
+
"data-cimplify-test-mode": "",
|
|
645
|
+
style: {
|
|
646
|
+
marginBottom: "10px",
|
|
647
|
+
fontSize: "12px",
|
|
648
|
+
fontWeight: 600,
|
|
649
|
+
color: "#92400e"
|
|
650
|
+
},
|
|
651
|
+
children: "Test mode - no real charges"
|
|
652
|
+
}
|
|
653
|
+
),
|
|
631
654
|
/* @__PURE__ */ jsxRuntime.jsx("div", { "data-cimplify-section": "auth", children: /* @__PURE__ */ jsxRuntime.jsx("div", { ref: isDemoCheckout ? void 0 : authMountRef }) }),
|
|
632
655
|
/* @__PURE__ */ jsxRuntime.jsx("div", { "data-cimplify-section": "order-type", style: { marginTop: "12px" }, children: /* @__PURE__ */ jsxRuntime.jsx(
|
|
633
656
|
"div",
|
|
@@ -695,12 +718,74 @@ var ErrorCode = {
|
|
|
695
718
|
UNKNOWN_ERROR: "UNKNOWN_ERROR",
|
|
696
719
|
NETWORK_ERROR: "NETWORK_ERROR",
|
|
697
720
|
TIMEOUT: "TIMEOUT",
|
|
721
|
+
UNAUTHORIZED: "UNAUTHORIZED",
|
|
698
722
|
NOT_FOUND: "NOT_FOUND"};
|
|
723
|
+
var DOCS_ERROR_BASE_URL = "https://docs.cimplify.io/reference/error-codes";
|
|
724
|
+
function docsUrlForCode(code) {
|
|
725
|
+
return `${DOCS_ERROR_BASE_URL}#${code.toLowerCase().replace(/_/g, "-")}`;
|
|
726
|
+
}
|
|
727
|
+
var ERROR_SUGGESTIONS = {
|
|
728
|
+
UNKNOWN_ERROR: "An unexpected error occurred. Capture the request/response payload and retry with exponential backoff.",
|
|
729
|
+
NETWORK_ERROR: "Check the shopper's connection and retry. If this persists, inspect CORS, DNS, and API reachability.",
|
|
730
|
+
TIMEOUT: "The request exceeded the timeout. Retry once, then poll order status before charging again.",
|
|
731
|
+
UNAUTHORIZED: "Authentication is missing or expired. Ensure a valid access token is set and refresh the session if needed.",
|
|
732
|
+
FORBIDDEN: "The key/session lacks permission for this resource. Verify business ownership and API key scope.",
|
|
733
|
+
NOT_FOUND: "The requested resource does not exist or is not visible in this environment.",
|
|
734
|
+
VALIDATION_ERROR: "One or more fields are invalid. Validate required fields and enum values before retrying.",
|
|
735
|
+
CART_EMPTY: "The cart has no items. Redirect back to menu/catalogue and require at least one line item.",
|
|
736
|
+
CART_EXPIRED: "This cart is no longer active. Recreate a new cart and re-add shopper selections.",
|
|
737
|
+
CART_NOT_FOUND: "Cart could not be located. It may have expired or belongs to a different key/location.",
|
|
738
|
+
ITEM_UNAVAILABLE: "The selected item is unavailable at this location/time. Prompt the shopper to pick an alternative.",
|
|
739
|
+
VARIANT_NOT_FOUND: "The requested variant no longer exists. Refresh product data and require re-selection.",
|
|
740
|
+
VARIANT_OUT_OF_STOCK: "The selected variant is out of stock. Show in-stock variants and block checkout for this line.",
|
|
741
|
+
ADDON_REQUIRED: "A required add-on is missing. Ensure required modifier groups are completed before add-to-cart.",
|
|
742
|
+
ADDON_MAX_EXCEEDED: "Too many add-ons were selected. Enforce max selections client-side before submission.",
|
|
743
|
+
CHECKOUT_VALIDATION_FAILED: "Checkout payload failed validation. Verify customer, order type, and address fields are complete.",
|
|
744
|
+
DELIVERY_ADDRESS_REQUIRED: "Delivery orders require an address. Collect and pass address info before processing checkout.",
|
|
745
|
+
CUSTOMER_INFO_REQUIRED: "Customer details are required. Ensure name/email/phone are available before checkout.",
|
|
746
|
+
PAYMENT_FAILED: "Payment provider rejected or failed processing. Show retry/change-method options to the shopper.",
|
|
747
|
+
PAYMENT_CANCELLED: "Payment was cancelled by the shopper or provider flow. Allow a safe retry path.",
|
|
748
|
+
INSUFFICIENT_FUNDS: "Payment method has insufficient funds. Prompt shopper to use another method.",
|
|
749
|
+
CARD_DECLINED: "Card was declined. Ask shopper to retry or switch payment method.",
|
|
750
|
+
INVALID_OTP: "Authorization code is invalid. Let shopper re-enter OTP/PIN and retry.",
|
|
751
|
+
OTP_EXPIRED: "Authorization code expired. Request a new OTP and re-submit authorization.",
|
|
752
|
+
AUTHORIZATION_FAILED: "Additional payment authorization failed. Retry authorization or change payment method.",
|
|
753
|
+
PAYMENT_ACTION_NOT_COMPLETED: "Required payment action was not completed. Resume provider flow and poll for status.",
|
|
754
|
+
SLOT_UNAVAILABLE: "Selected schedule slot is unavailable. Refresh available slots and ask shopper to reselect.",
|
|
755
|
+
BOOKING_CONFLICT: "The requested booking conflicts with an existing reservation. Pick another slot/resource.",
|
|
756
|
+
SERVICE_NOT_FOUND: "Requested service no longer exists. Refresh service catalogue and retry selection.",
|
|
757
|
+
OUT_OF_STOCK: "Inventory is depleted for this item. Remove it or reduce quantity before checkout.",
|
|
758
|
+
INSUFFICIENT_QUANTITY: "Requested quantity exceeds available inventory. Reduce quantity and retry.",
|
|
759
|
+
BUSINESS_ID_REQUIRED: "Business context could not be resolved. Verify the public key and business bootstrap call.",
|
|
760
|
+
INVALID_CART: "Cart is invalid for checkout. Sync cart state, ensure items exist, then retry.",
|
|
761
|
+
ORDER_TYPE_REQUIRED: "Order type is required. Provide one of delivery, pickup, or dine_in before checkout.",
|
|
762
|
+
NO_PAYMENT_ELEMENT: "PaymentElement is required for processCheckout(). Mount it before triggering checkout.",
|
|
763
|
+
PAYMENT_NOT_MOUNTED: "PaymentElement iframe is not mounted. Mount it in the DOM before processCheckout().",
|
|
764
|
+
AUTH_INCOMPLETE: "AuthElement has not completed authentication. Wait for AUTHENTICATED before checkout.",
|
|
765
|
+
AUTH_LOST: "Session was cleared during checkout. Re-authenticate and restart checkout safely.",
|
|
766
|
+
ALREADY_PROCESSING: "Checkout is already in progress. Disable duplicate submits until completion.",
|
|
767
|
+
CHECKOUT_NOT_READY: "Checkout elements are still initializing. Wait for readiness before submit.",
|
|
768
|
+
CANCELLED: "Checkout was cancelled. Preserve cart state and allow shopper to retry.",
|
|
769
|
+
REQUEST_TIMEOUT: "Provider call timed out. Poll payment/order status before issuing another charge attempt.",
|
|
770
|
+
POPUP_BLOCKED: "Browser blocked provider popup. Ask shopper to enable popups and retry.",
|
|
771
|
+
FX_QUOTE_FAILED: "Failed to lock FX quote. Retry currency quote or fallback to base currency."
|
|
772
|
+
};
|
|
773
|
+
var ERROR_HINTS = Object.fromEntries(
|
|
774
|
+
Object.entries(ERROR_SUGGESTIONS).map(([code, suggestion]) => [
|
|
775
|
+
code,
|
|
776
|
+
{
|
|
777
|
+
docs_url: docsUrlForCode(code),
|
|
778
|
+
suggestion
|
|
779
|
+
}
|
|
780
|
+
])
|
|
781
|
+
);
|
|
699
782
|
var CimplifyError = class extends Error {
|
|
700
|
-
constructor(code, message, retryable = false) {
|
|
783
|
+
constructor(code, message, retryable = false, docs_url, suggestion) {
|
|
701
784
|
super(message);
|
|
702
785
|
this.code = code;
|
|
703
786
|
this.retryable = retryable;
|
|
787
|
+
this.docs_url = docs_url;
|
|
788
|
+
this.suggestion = suggestion;
|
|
704
789
|
this.name = "CimplifyError";
|
|
705
790
|
}
|
|
706
791
|
/** User-friendly message safe to display */
|
|
@@ -708,6 +793,28 @@ var CimplifyError = class extends Error {
|
|
|
708
793
|
return this.message;
|
|
709
794
|
}
|
|
710
795
|
};
|
|
796
|
+
function getErrorHint(code) {
|
|
797
|
+
return ERROR_HINTS[code];
|
|
798
|
+
}
|
|
799
|
+
function enrichError(error, options = {}) {
|
|
800
|
+
const hint = getErrorHint(error.code);
|
|
801
|
+
if (hint) {
|
|
802
|
+
if (!error.docs_url) {
|
|
803
|
+
error.docs_url = hint.docs_url;
|
|
804
|
+
}
|
|
805
|
+
if (!error.suggestion) {
|
|
806
|
+
error.suggestion = hint.suggestion;
|
|
807
|
+
}
|
|
808
|
+
} else if (!error.docs_url) {
|
|
809
|
+
error.docs_url = docsUrlForCode(error.code || ErrorCode.UNKNOWN_ERROR);
|
|
810
|
+
}
|
|
811
|
+
if (options.isTestMode && !error.message.includes("pk_test_")) {
|
|
812
|
+
error.message = `${error.message}
|
|
813
|
+
|
|
814
|
+
\u2139 Your API key is a test-mode key (pk_test_...). Verify test data/session before retrying.`;
|
|
815
|
+
}
|
|
816
|
+
return error;
|
|
817
|
+
}
|
|
711
818
|
|
|
712
819
|
// src/types/result.ts
|
|
713
820
|
function ok(value) {
|
|
@@ -719,11 +826,11 @@ function err(error) {
|
|
|
719
826
|
|
|
720
827
|
// src/catalogue.ts
|
|
721
828
|
function toCimplifyError(error) {
|
|
722
|
-
if (error instanceof CimplifyError) return error;
|
|
829
|
+
if (error instanceof CimplifyError) return enrichError(error);
|
|
723
830
|
if (error instanceof Error) {
|
|
724
|
-
return new CimplifyError(
|
|
831
|
+
return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, error.message, false));
|
|
725
832
|
}
|
|
726
|
-
return new CimplifyError(
|
|
833
|
+
return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, String(error), false));
|
|
727
834
|
}
|
|
728
835
|
async function safe(promise) {
|
|
729
836
|
try {
|
|
@@ -1018,11 +1125,11 @@ var CatalogueQueries = class {
|
|
|
1018
1125
|
|
|
1019
1126
|
// src/cart.ts
|
|
1020
1127
|
function toCimplifyError2(error) {
|
|
1021
|
-
if (error instanceof CimplifyError) return error;
|
|
1128
|
+
if (error instanceof CimplifyError) return enrichError(error);
|
|
1022
1129
|
if (error instanceof Error) {
|
|
1023
|
-
return new CimplifyError(
|
|
1130
|
+
return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, error.message, false));
|
|
1024
1131
|
}
|
|
1025
|
-
return new CimplifyError(
|
|
1132
|
+
return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, String(error), false));
|
|
1026
1133
|
}
|
|
1027
1134
|
async function safe2(promise) {
|
|
1028
1135
|
try {
|
|
@@ -1182,6 +1289,19 @@ var ORDER_MUTATION = {
|
|
|
1182
1289
|
UPDATE_CUSTOMER: "order.update_order_customer"
|
|
1183
1290
|
};
|
|
1184
1291
|
|
|
1292
|
+
// src/utils/price.ts
|
|
1293
|
+
function parsePrice(value) {
|
|
1294
|
+
if (value === void 0 || value === null) {
|
|
1295
|
+
return 0;
|
|
1296
|
+
}
|
|
1297
|
+
if (typeof value === "number") {
|
|
1298
|
+
return isNaN(value) ? 0 : value;
|
|
1299
|
+
}
|
|
1300
|
+
const cleaned = value.replace(/[^\d.-]/g, "");
|
|
1301
|
+
const parsed = parseFloat(cleaned);
|
|
1302
|
+
return isNaN(parsed) ? 0 : parsed;
|
|
1303
|
+
}
|
|
1304
|
+
|
|
1185
1305
|
// src/utils/payment.ts
|
|
1186
1306
|
var PAYMENT_SUCCESS_STATUSES = /* @__PURE__ */ new Set([
|
|
1187
1307
|
"success",
|
|
@@ -1861,11 +1981,11 @@ var CheckoutResolver = class {
|
|
|
1861
1981
|
|
|
1862
1982
|
// src/checkout.ts
|
|
1863
1983
|
function toCimplifyError3(error) {
|
|
1864
|
-
if (error instanceof CimplifyError) return error;
|
|
1984
|
+
if (error instanceof CimplifyError) return enrichError(error);
|
|
1865
1985
|
if (error instanceof Error) {
|
|
1866
|
-
return new CimplifyError(
|
|
1986
|
+
return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, error.message, false));
|
|
1867
1987
|
}
|
|
1868
|
-
return new CimplifyError(
|
|
1988
|
+
return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, String(error), false));
|
|
1869
1989
|
}
|
|
1870
1990
|
async function safe3(promise) {
|
|
1871
1991
|
try {
|
|
@@ -2041,11 +2161,11 @@ var CheckoutService = class {
|
|
|
2041
2161
|
|
|
2042
2162
|
// src/orders.ts
|
|
2043
2163
|
function toCimplifyError4(error) {
|
|
2044
|
-
if (error instanceof CimplifyError) return error;
|
|
2164
|
+
if (error instanceof CimplifyError) return enrichError(error);
|
|
2045
2165
|
if (error instanceof Error) {
|
|
2046
|
-
return new CimplifyError(
|
|
2166
|
+
return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, error.message, false));
|
|
2047
2167
|
}
|
|
2048
|
-
return new CimplifyError(
|
|
2168
|
+
return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, String(error), false));
|
|
2049
2169
|
}
|
|
2050
2170
|
async function safe4(promise) {
|
|
2051
2171
|
try {
|
|
@@ -2302,11 +2422,11 @@ var AuthService = class {
|
|
|
2302
2422
|
|
|
2303
2423
|
// src/business.ts
|
|
2304
2424
|
function toCimplifyError7(error) {
|
|
2305
|
-
if (error instanceof CimplifyError) return error;
|
|
2425
|
+
if (error instanceof CimplifyError) return enrichError(error);
|
|
2306
2426
|
if (error instanceof Error) {
|
|
2307
|
-
return new CimplifyError(
|
|
2427
|
+
return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, error.message, false));
|
|
2308
2428
|
}
|
|
2309
|
-
return new CimplifyError(
|
|
2429
|
+
return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, String(error), false));
|
|
2310
2430
|
}
|
|
2311
2431
|
async function safe7(promise) {
|
|
2312
2432
|
try {
|
|
@@ -2653,12 +2773,15 @@ var FxService = class {
|
|
|
2653
2773
|
|
|
2654
2774
|
// src/elements.ts
|
|
2655
2775
|
function toCheckoutError(code, message, recoverable) {
|
|
2776
|
+
const hint = getErrorHint(code);
|
|
2656
2777
|
return {
|
|
2657
2778
|
success: false,
|
|
2658
2779
|
error: {
|
|
2659
2780
|
code,
|
|
2660
2781
|
message,
|
|
2661
|
-
recoverable
|
|
2782
|
+
recoverable,
|
|
2783
|
+
docs_url: hint?.docs_url,
|
|
2784
|
+
suggestion: hint?.suggestion
|
|
2662
2785
|
}
|
|
2663
2786
|
};
|
|
2664
2787
|
}
|
|
@@ -2699,6 +2822,7 @@ var CimplifyElements = class {
|
|
|
2699
2822
|
this.paymentData = null;
|
|
2700
2823
|
this.checkoutInProgress = false;
|
|
2701
2824
|
this.activeCheckoutAbort = null;
|
|
2825
|
+
this.hasWarnedMissingAuthElement = false;
|
|
2702
2826
|
this.businessIdResolvePromise = null;
|
|
2703
2827
|
this.client = client;
|
|
2704
2828
|
this.businessId = businessId ?? null;
|
|
@@ -2794,6 +2918,12 @@ var CimplifyElements = class {
|
|
|
2794
2918
|
);
|
|
2795
2919
|
}
|
|
2796
2920
|
const authElement = this.elements.get(ELEMENT_TYPES.AUTH);
|
|
2921
|
+
if (!authElement && !this.hasWarnedMissingAuthElement) {
|
|
2922
|
+
this.hasWarnedMissingAuthElement = true;
|
|
2923
|
+
console.warn(
|
|
2924
|
+
"[Cimplify] processCheckout() called without AuthElement mounted. For best conversion and Link enrollment, mount <AuthElement> before checkout."
|
|
2925
|
+
);
|
|
2926
|
+
}
|
|
2797
2927
|
if (authElement && !this.accessToken) {
|
|
2798
2928
|
return toCheckoutError(
|
|
2799
2929
|
"AUTH_INCOMPLETE",
|
|
@@ -3230,28 +3360,37 @@ function isRetryable(error) {
|
|
|
3230
3360
|
}
|
|
3231
3361
|
return false;
|
|
3232
3362
|
}
|
|
3233
|
-
function toNetworkError(error) {
|
|
3363
|
+
function toNetworkError(error, isTestMode) {
|
|
3234
3364
|
if (error instanceof DOMException && error.name === "AbortError") {
|
|
3235
|
-
return
|
|
3236
|
-
|
|
3237
|
-
|
|
3238
|
-
|
|
3365
|
+
return enrichError(
|
|
3366
|
+
new CimplifyError(
|
|
3367
|
+
ErrorCode.TIMEOUT,
|
|
3368
|
+
"Request timed out. Please check your connection and try again.",
|
|
3369
|
+
true
|
|
3370
|
+
),
|
|
3371
|
+
{ isTestMode }
|
|
3239
3372
|
);
|
|
3240
3373
|
}
|
|
3241
3374
|
if (error instanceof TypeError && error.message.includes("fetch")) {
|
|
3242
|
-
return
|
|
3243
|
-
|
|
3244
|
-
|
|
3245
|
-
|
|
3375
|
+
return enrichError(
|
|
3376
|
+
new CimplifyError(
|
|
3377
|
+
ErrorCode.NETWORK_ERROR,
|
|
3378
|
+
"Network error. Please check your internet connection.",
|
|
3379
|
+
true
|
|
3380
|
+
),
|
|
3381
|
+
{ isTestMode }
|
|
3246
3382
|
);
|
|
3247
3383
|
}
|
|
3248
3384
|
if (error instanceof CimplifyError) {
|
|
3249
|
-
return error;
|
|
3385
|
+
return enrichError(error, { isTestMode });
|
|
3250
3386
|
}
|
|
3251
|
-
return
|
|
3252
|
-
|
|
3253
|
-
|
|
3254
|
-
|
|
3387
|
+
return enrichError(
|
|
3388
|
+
new CimplifyError(
|
|
3389
|
+
ErrorCode.UNKNOWN_ERROR,
|
|
3390
|
+
error instanceof Error ? error.message : "An unknown error occurred",
|
|
3391
|
+
false
|
|
3392
|
+
),
|
|
3393
|
+
{ isTestMode }
|
|
3255
3394
|
);
|
|
3256
3395
|
}
|
|
3257
3396
|
function deriveUrls() {
|
|
@@ -3313,6 +3452,9 @@ var CimplifyClient = class {
|
|
|
3313
3452
|
getPublicKey() {
|
|
3314
3453
|
return this.publicKey;
|
|
3315
3454
|
}
|
|
3455
|
+
isTestMode() {
|
|
3456
|
+
return this.publicKey.trim().startsWith("pk_test_");
|
|
3457
|
+
}
|
|
3316
3458
|
setAccessToken(token) {
|
|
3317
3459
|
const previous = this.accessToken;
|
|
3318
3460
|
this.accessToken = token;
|
|
@@ -3462,7 +3604,7 @@ var CimplifyClient = class {
|
|
|
3462
3604
|
return response;
|
|
3463
3605
|
} catch (error) {
|
|
3464
3606
|
lastError = error;
|
|
3465
|
-
const networkError = toNetworkError(error);
|
|
3607
|
+
const networkError = toNetworkError(error, this.isTestMode());
|
|
3466
3608
|
const errorRetryable = isRetryable(error);
|
|
3467
3609
|
if (!errorRetryable || attempt >= this.maxRetries) {
|
|
3468
3610
|
this.hooks.onRequestError?.({
|
|
@@ -3485,7 +3627,7 @@ var CimplifyClient = class {
|
|
|
3485
3627
|
await sleep(delay);
|
|
3486
3628
|
}
|
|
3487
3629
|
}
|
|
3488
|
-
const finalError = toNetworkError(lastError);
|
|
3630
|
+
const finalError = toNetworkError(lastError, this.isTestMode());
|
|
3489
3631
|
this.hooks.onRequestError?.({
|
|
3490
3632
|
...context,
|
|
3491
3633
|
error: finalError,
|
|
@@ -3603,22 +3745,40 @@ var CimplifyClient = class {
|
|
|
3603
3745
|
async handleRestResponse(response) {
|
|
3604
3746
|
const json = await response.json();
|
|
3605
3747
|
if (!response.ok) {
|
|
3606
|
-
|
|
3607
|
-
|
|
3608
|
-
|
|
3609
|
-
|
|
3748
|
+
const error = enrichError(
|
|
3749
|
+
new CimplifyError(
|
|
3750
|
+
json.error?.error_code || "API_ERROR",
|
|
3751
|
+
json.error?.error_message || "An error occurred",
|
|
3752
|
+
false
|
|
3753
|
+
),
|
|
3754
|
+
{ isTestMode: this.isTestMode() }
|
|
3610
3755
|
);
|
|
3756
|
+
if (response.status === 401 || error.code === ErrorCode.UNAUTHORIZED) {
|
|
3757
|
+
console.warn(
|
|
3758
|
+
"[Cimplify] Received 401 Unauthorized. Access token may be missing/expired. Refresh authentication and retry the request."
|
|
3759
|
+
);
|
|
3760
|
+
}
|
|
3761
|
+
throw error;
|
|
3611
3762
|
}
|
|
3612
3763
|
return json.data;
|
|
3613
3764
|
}
|
|
3614
3765
|
async handleResponse(response) {
|
|
3615
3766
|
const json = await response.json();
|
|
3616
3767
|
if (!json.success || json.error) {
|
|
3617
|
-
|
|
3618
|
-
|
|
3619
|
-
|
|
3620
|
-
|
|
3768
|
+
const error = enrichError(
|
|
3769
|
+
new CimplifyError(
|
|
3770
|
+
json.error?.code || "UNKNOWN_ERROR",
|
|
3771
|
+
json.error?.message || "An unknown error occurred",
|
|
3772
|
+
json.error?.retryable || false
|
|
3773
|
+
),
|
|
3774
|
+
{ isTestMode: this.isTestMode() }
|
|
3621
3775
|
);
|
|
3776
|
+
if (response.status === 401 || error.code === ErrorCode.UNAUTHORIZED) {
|
|
3777
|
+
console.warn(
|
|
3778
|
+
"[Cimplify] Received 401 Unauthorized. Access token may be missing/expired. Refresh authentication and retry the request."
|
|
3779
|
+
);
|
|
3780
|
+
}
|
|
3781
|
+
throw error;
|
|
3622
3782
|
}
|
|
3623
3783
|
return json.data;
|
|
3624
3784
|
}
|
|
@@ -3805,6 +3965,9 @@ function CimplifyProvider({
|
|
|
3805
3965
|
const nextLocations = locationsResult.ok && Array.isArray(locationsResult.value) ? locationsResult.value : [];
|
|
3806
3966
|
const initialLocation = resolveInitialLocation(nextLocations);
|
|
3807
3967
|
setBusiness(nextBusiness);
|
|
3968
|
+
if (nextBusiness?.id) {
|
|
3969
|
+
resolvedClient.setBusinessId(nextBusiness.id);
|
|
3970
|
+
}
|
|
3808
3971
|
setLocations(nextLocations);
|
|
3809
3972
|
if (initialLocation) {
|
|
3810
3973
|
setCurrentLocationState(initialLocation);
|
|
@@ -3863,6 +4026,1065 @@ function useCimplify() {
|
|
|
3863
4026
|
}
|
|
3864
4027
|
return context;
|
|
3865
4028
|
}
|
|
4029
|
+
function useOptionalCimplify() {
|
|
4030
|
+
return react.useContext(CimplifyContext);
|
|
4031
|
+
}
|
|
4032
|
+
var productsCache = /* @__PURE__ */ new Map();
|
|
4033
|
+
var productsInflight = /* @__PURE__ */ new Map();
|
|
4034
|
+
function buildProductsCacheKey(client, locationId, options) {
|
|
4035
|
+
return JSON.stringify({
|
|
4036
|
+
key: client.getPublicKey(),
|
|
4037
|
+
location_id: locationId || "__none__",
|
|
4038
|
+
options
|
|
4039
|
+
});
|
|
4040
|
+
}
|
|
4041
|
+
function useProducts(options = {}) {
|
|
4042
|
+
const context = useOptionalCimplify();
|
|
4043
|
+
const client = options.client ?? context?.client;
|
|
4044
|
+
if (!client) {
|
|
4045
|
+
throw new Error("useProducts must be used within CimplifyProvider or passed { client }.");
|
|
4046
|
+
}
|
|
4047
|
+
const enabled = options.enabled ?? true;
|
|
4048
|
+
const locationId = client.getLocationId();
|
|
4049
|
+
const previousLocationIdRef = react.useRef(locationId);
|
|
4050
|
+
const requestIdRef = react.useRef(0);
|
|
4051
|
+
const queryOptions = react.useMemo(
|
|
4052
|
+
() => ({
|
|
4053
|
+
category: options.category,
|
|
4054
|
+
collection: options.collection,
|
|
4055
|
+
search: options.search,
|
|
4056
|
+
featured: options.featured,
|
|
4057
|
+
limit: options.limit
|
|
4058
|
+
}),
|
|
4059
|
+
[options.category, options.collection, options.featured, options.limit, options.search]
|
|
4060
|
+
);
|
|
4061
|
+
const cacheKey = react.useMemo(
|
|
4062
|
+
() => buildProductsCacheKey(client, locationId, queryOptions),
|
|
4063
|
+
[client, locationId, queryOptions]
|
|
4064
|
+
);
|
|
4065
|
+
const cached = productsCache.get(cacheKey);
|
|
4066
|
+
const [products, setProducts] = react.useState(cached?.products ?? []);
|
|
4067
|
+
const [isLoading, setIsLoading] = react.useState(enabled && !cached);
|
|
4068
|
+
const [error, setError] = react.useState(null);
|
|
4069
|
+
react.useEffect(() => {
|
|
4070
|
+
if (previousLocationIdRef.current !== locationId) {
|
|
4071
|
+
productsCache.clear();
|
|
4072
|
+
productsInflight.clear();
|
|
4073
|
+
previousLocationIdRef.current = locationId;
|
|
4074
|
+
}
|
|
4075
|
+
}, [locationId]);
|
|
4076
|
+
const load = react.useCallback(
|
|
4077
|
+
async (force = false) => {
|
|
4078
|
+
if (!enabled) {
|
|
4079
|
+
setIsLoading(false);
|
|
4080
|
+
return;
|
|
4081
|
+
}
|
|
4082
|
+
const nextRequestId = ++requestIdRef.current;
|
|
4083
|
+
setError(null);
|
|
4084
|
+
if (!force) {
|
|
4085
|
+
const cacheEntry = productsCache.get(cacheKey);
|
|
4086
|
+
if (cacheEntry) {
|
|
4087
|
+
setProducts(cacheEntry.products);
|
|
4088
|
+
setIsLoading(false);
|
|
4089
|
+
return;
|
|
4090
|
+
}
|
|
4091
|
+
}
|
|
4092
|
+
setIsLoading(true);
|
|
4093
|
+
try {
|
|
4094
|
+
const existing = productsInflight.get(cacheKey);
|
|
4095
|
+
const promise = existing ?? (async () => {
|
|
4096
|
+
const result = await client.catalogue.getProducts(queryOptions);
|
|
4097
|
+
if (!result.ok) {
|
|
4098
|
+
throw result.error;
|
|
4099
|
+
}
|
|
4100
|
+
return result.value;
|
|
4101
|
+
})();
|
|
4102
|
+
if (!existing) {
|
|
4103
|
+
productsInflight.set(
|
|
4104
|
+
cacheKey,
|
|
4105
|
+
promise.finally(() => {
|
|
4106
|
+
productsInflight.delete(cacheKey);
|
|
4107
|
+
})
|
|
4108
|
+
);
|
|
4109
|
+
}
|
|
4110
|
+
const value = await promise;
|
|
4111
|
+
productsCache.set(cacheKey, { products: value });
|
|
4112
|
+
if (nextRequestId === requestIdRef.current) {
|
|
4113
|
+
setProducts(value);
|
|
4114
|
+
setError(null);
|
|
4115
|
+
}
|
|
4116
|
+
} catch (loadError) {
|
|
4117
|
+
if (nextRequestId === requestIdRef.current) {
|
|
4118
|
+
setError(loadError);
|
|
4119
|
+
}
|
|
4120
|
+
} finally {
|
|
4121
|
+
if (nextRequestId === requestIdRef.current) {
|
|
4122
|
+
setIsLoading(false);
|
|
4123
|
+
}
|
|
4124
|
+
}
|
|
4125
|
+
},
|
|
4126
|
+
[cacheKey, client, enabled, queryOptions]
|
|
4127
|
+
);
|
|
4128
|
+
react.useEffect(() => {
|
|
4129
|
+
void load(false);
|
|
4130
|
+
}, [load]);
|
|
4131
|
+
const refetch = react.useCallback(async () => {
|
|
4132
|
+
productsCache.delete(cacheKey);
|
|
4133
|
+
await load(true);
|
|
4134
|
+
}, [cacheKey, load]);
|
|
4135
|
+
return { products, isLoading, error, refetch };
|
|
4136
|
+
}
|
|
4137
|
+
var productCache = /* @__PURE__ */ new Map();
|
|
4138
|
+
var productInflight = /* @__PURE__ */ new Map();
|
|
4139
|
+
function isLikelySlug(value) {
|
|
4140
|
+
return /^[a-z0-9-]+$/.test(value);
|
|
4141
|
+
}
|
|
4142
|
+
function buildProductCacheKey(client, locationId, slugOrId) {
|
|
4143
|
+
return JSON.stringify({
|
|
4144
|
+
key: client.getPublicKey(),
|
|
4145
|
+
location_id: locationId || "__none__",
|
|
4146
|
+
slug_or_id: slugOrId
|
|
4147
|
+
});
|
|
4148
|
+
}
|
|
4149
|
+
function useProduct(slugOrId, options = {}) {
|
|
4150
|
+
const context = useOptionalCimplify();
|
|
4151
|
+
const client = options.client ?? context?.client;
|
|
4152
|
+
if (!client) {
|
|
4153
|
+
throw new Error("useProduct must be used within CimplifyProvider or passed { client }.");
|
|
4154
|
+
}
|
|
4155
|
+
const enabled = options.enabled ?? true;
|
|
4156
|
+
const locationId = client.getLocationId();
|
|
4157
|
+
const previousLocationIdRef = react.useRef(locationId);
|
|
4158
|
+
const requestIdRef = react.useRef(0);
|
|
4159
|
+
const normalizedSlugOrId = react.useMemo(() => (slugOrId || "").trim(), [slugOrId]);
|
|
4160
|
+
const cacheKey = react.useMemo(
|
|
4161
|
+
() => buildProductCacheKey(client, locationId, normalizedSlugOrId),
|
|
4162
|
+
[client, locationId, normalizedSlugOrId]
|
|
4163
|
+
);
|
|
4164
|
+
const cached = productCache.get(cacheKey);
|
|
4165
|
+
const [product, setProduct] = react.useState(cached?.product ?? null);
|
|
4166
|
+
const [isLoading, setIsLoading] = react.useState(
|
|
4167
|
+
enabled && normalizedSlugOrId.length > 0 && !cached
|
|
4168
|
+
);
|
|
4169
|
+
const [error, setError] = react.useState(null);
|
|
4170
|
+
react.useEffect(() => {
|
|
4171
|
+
if (previousLocationIdRef.current !== locationId) {
|
|
4172
|
+
productCache.clear();
|
|
4173
|
+
productInflight.clear();
|
|
4174
|
+
previousLocationIdRef.current = locationId;
|
|
4175
|
+
}
|
|
4176
|
+
}, [locationId]);
|
|
4177
|
+
const load = react.useCallback(
|
|
4178
|
+
async (force = false) => {
|
|
4179
|
+
if (!enabled || normalizedSlugOrId.length === 0) {
|
|
4180
|
+
setProduct(null);
|
|
4181
|
+
setIsLoading(false);
|
|
4182
|
+
return;
|
|
4183
|
+
}
|
|
4184
|
+
const nextRequestId = ++requestIdRef.current;
|
|
4185
|
+
setError(null);
|
|
4186
|
+
if (!force) {
|
|
4187
|
+
const cacheEntry = productCache.get(cacheKey);
|
|
4188
|
+
if (cacheEntry) {
|
|
4189
|
+
setProduct(cacheEntry.product);
|
|
4190
|
+
setIsLoading(false);
|
|
4191
|
+
return;
|
|
4192
|
+
}
|
|
4193
|
+
}
|
|
4194
|
+
setIsLoading(true);
|
|
4195
|
+
try {
|
|
4196
|
+
const existing = productInflight.get(cacheKey);
|
|
4197
|
+
const promise = existing ?? (async () => {
|
|
4198
|
+
const result = isLikelySlug(normalizedSlugOrId) ? await client.catalogue.getProductBySlug(normalizedSlugOrId) : await client.catalogue.getProduct(normalizedSlugOrId);
|
|
4199
|
+
if (!result.ok) {
|
|
4200
|
+
throw result.error;
|
|
4201
|
+
}
|
|
4202
|
+
return result.value;
|
|
4203
|
+
})();
|
|
4204
|
+
if (!existing) {
|
|
4205
|
+
productInflight.set(
|
|
4206
|
+
cacheKey,
|
|
4207
|
+
promise.finally(() => {
|
|
4208
|
+
productInflight.delete(cacheKey);
|
|
4209
|
+
})
|
|
4210
|
+
);
|
|
4211
|
+
}
|
|
4212
|
+
const value = await promise;
|
|
4213
|
+
productCache.set(cacheKey, { product: value });
|
|
4214
|
+
if (nextRequestId === requestIdRef.current) {
|
|
4215
|
+
setProduct(value);
|
|
4216
|
+
setError(null);
|
|
4217
|
+
}
|
|
4218
|
+
} catch (loadError) {
|
|
4219
|
+
if (nextRequestId === requestIdRef.current) {
|
|
4220
|
+
setError(loadError);
|
|
4221
|
+
}
|
|
4222
|
+
} finally {
|
|
4223
|
+
if (nextRequestId === requestIdRef.current) {
|
|
4224
|
+
setIsLoading(false);
|
|
4225
|
+
}
|
|
4226
|
+
}
|
|
4227
|
+
},
|
|
4228
|
+
[cacheKey, client, enabled, normalizedSlugOrId]
|
|
4229
|
+
);
|
|
4230
|
+
react.useEffect(() => {
|
|
4231
|
+
void load(false);
|
|
4232
|
+
}, [load]);
|
|
4233
|
+
const refetch = react.useCallback(async () => {
|
|
4234
|
+
productCache.delete(cacheKey);
|
|
4235
|
+
await load(true);
|
|
4236
|
+
}, [cacheKey, load]);
|
|
4237
|
+
return { product, isLoading, error, refetch };
|
|
4238
|
+
}
|
|
4239
|
+
var categoriesCache = /* @__PURE__ */ new Map();
|
|
4240
|
+
var categoriesInflight = /* @__PURE__ */ new Map();
|
|
4241
|
+
function buildCategoriesCacheKey(client) {
|
|
4242
|
+
return client.getPublicKey() || "__demo__";
|
|
4243
|
+
}
|
|
4244
|
+
function useCategories(options = {}) {
|
|
4245
|
+
const context = useOptionalCimplify();
|
|
4246
|
+
const client = options.client ?? context?.client;
|
|
4247
|
+
if (!client) {
|
|
4248
|
+
throw new Error("useCategories must be used within CimplifyProvider or passed { client }.");
|
|
4249
|
+
}
|
|
4250
|
+
const enabled = options.enabled ?? true;
|
|
4251
|
+
const cacheKey = react.useMemo(() => buildCategoriesCacheKey(client), [client]);
|
|
4252
|
+
const cached = categoriesCache.get(cacheKey);
|
|
4253
|
+
const [categories, setCategories] = react.useState(cached ?? []);
|
|
4254
|
+
const [isLoading, setIsLoading] = react.useState(enabled && !cached);
|
|
4255
|
+
const [error, setError] = react.useState(null);
|
|
4256
|
+
const load = react.useCallback(
|
|
4257
|
+
async (force = false) => {
|
|
4258
|
+
if (!enabled) {
|
|
4259
|
+
setIsLoading(false);
|
|
4260
|
+
return;
|
|
4261
|
+
}
|
|
4262
|
+
setError(null);
|
|
4263
|
+
if (!force) {
|
|
4264
|
+
const cachedCategories = categoriesCache.get(cacheKey);
|
|
4265
|
+
if (cachedCategories) {
|
|
4266
|
+
setCategories(cachedCategories);
|
|
4267
|
+
setIsLoading(false);
|
|
4268
|
+
return;
|
|
4269
|
+
}
|
|
4270
|
+
}
|
|
4271
|
+
setIsLoading(true);
|
|
4272
|
+
try {
|
|
4273
|
+
const existing = categoriesInflight.get(cacheKey);
|
|
4274
|
+
const promise = existing ?? (async () => {
|
|
4275
|
+
const result = await client.catalogue.getCategories();
|
|
4276
|
+
if (!result.ok) {
|
|
4277
|
+
throw result.error;
|
|
4278
|
+
}
|
|
4279
|
+
return result.value;
|
|
4280
|
+
})();
|
|
4281
|
+
if (!existing) {
|
|
4282
|
+
categoriesInflight.set(
|
|
4283
|
+
cacheKey,
|
|
4284
|
+
promise.finally(() => {
|
|
4285
|
+
categoriesInflight.delete(cacheKey);
|
|
4286
|
+
})
|
|
4287
|
+
);
|
|
4288
|
+
}
|
|
4289
|
+
const value = await promise;
|
|
4290
|
+
categoriesCache.set(cacheKey, value);
|
|
4291
|
+
setCategories(value);
|
|
4292
|
+
} catch (loadError) {
|
|
4293
|
+
setError(loadError);
|
|
4294
|
+
} finally {
|
|
4295
|
+
setIsLoading(false);
|
|
4296
|
+
}
|
|
4297
|
+
},
|
|
4298
|
+
[cacheKey, client, enabled]
|
|
4299
|
+
);
|
|
4300
|
+
react.useEffect(() => {
|
|
4301
|
+
void load(false);
|
|
4302
|
+
}, [load]);
|
|
4303
|
+
const refetch = react.useCallback(async () => {
|
|
4304
|
+
categoriesCache.delete(cacheKey);
|
|
4305
|
+
await load(true);
|
|
4306
|
+
}, [cacheKey, load]);
|
|
4307
|
+
return { categories, isLoading, error, refetch };
|
|
4308
|
+
}
|
|
4309
|
+
var CART_STORAGE_PREFIX = "cimplify:cart:v2";
|
|
4310
|
+
var DEFAULT_TAX_RATE = 0.08875;
|
|
4311
|
+
var cartStores = /* @__PURE__ */ new Map();
|
|
4312
|
+
function toNumber(value) {
|
|
4313
|
+
if (typeof value === "number" && Number.isFinite(value)) {
|
|
4314
|
+
return value;
|
|
4315
|
+
}
|
|
4316
|
+
if (typeof value === "string") {
|
|
4317
|
+
const parsed = Number.parseFloat(value);
|
|
4318
|
+
return Number.isFinite(parsed) ? parsed : 0;
|
|
4319
|
+
}
|
|
4320
|
+
return 0;
|
|
4321
|
+
}
|
|
4322
|
+
function roundMoney(value) {
|
|
4323
|
+
return Math.max(0, Number(value.toFixed(2)));
|
|
4324
|
+
}
|
|
4325
|
+
function clampQuantity(quantity) {
|
|
4326
|
+
if (!Number.isFinite(quantity)) {
|
|
4327
|
+
return 1;
|
|
4328
|
+
}
|
|
4329
|
+
return Math.max(1, Math.floor(quantity));
|
|
4330
|
+
}
|
|
4331
|
+
function normalizeOptionIds(value) {
|
|
4332
|
+
if (!value || value.length === 0) {
|
|
4333
|
+
return void 0;
|
|
4334
|
+
}
|
|
4335
|
+
const normalized = Array.from(
|
|
4336
|
+
new Set(
|
|
4337
|
+
value.map((entry) => entry.trim()).filter((entry) => entry.length > 0)
|
|
4338
|
+
)
|
|
4339
|
+
).sort();
|
|
4340
|
+
return normalized.length > 0 ? normalized : void 0;
|
|
4341
|
+
}
|
|
4342
|
+
function buildLineKey(productId, options) {
|
|
4343
|
+
const parts = [productId];
|
|
4344
|
+
if (options.locationId) {
|
|
4345
|
+
parts.push(`l:${options.locationId}`);
|
|
4346
|
+
}
|
|
4347
|
+
if (options.variantId) {
|
|
4348
|
+
parts.push(`v:${options.variantId}`);
|
|
4349
|
+
}
|
|
4350
|
+
const addOnOptionIds = normalizeOptionIds(options.addOnOptionIds);
|
|
4351
|
+
if (addOnOptionIds && addOnOptionIds.length > 0) {
|
|
4352
|
+
parts.push(`a:${addOnOptionIds.join(",")}`);
|
|
4353
|
+
}
|
|
4354
|
+
if (options.bundleSelections && options.bundleSelections.length > 0) {
|
|
4355
|
+
parts.push(`b:${JSON.stringify(options.bundleSelections)}`);
|
|
4356
|
+
}
|
|
4357
|
+
if (options.compositeSelections && options.compositeSelections.length > 0) {
|
|
4358
|
+
parts.push(`c:${JSON.stringify(options.compositeSelections)}`);
|
|
4359
|
+
}
|
|
4360
|
+
if (options.quoteId) {
|
|
4361
|
+
parts.push(`q:${options.quoteId}`);
|
|
4362
|
+
}
|
|
4363
|
+
return parts.join("|");
|
|
4364
|
+
}
|
|
4365
|
+
function calculateLineSubtotal(item) {
|
|
4366
|
+
let unitPrice = parsePrice(item.product.default_price);
|
|
4367
|
+
if (item.variant?.price_adjustment) {
|
|
4368
|
+
unitPrice += parsePrice(item.variant.price_adjustment);
|
|
4369
|
+
}
|
|
4370
|
+
for (const option of item.addOnOptions || []) {
|
|
4371
|
+
if (option.default_price) {
|
|
4372
|
+
unitPrice += parsePrice(option.default_price);
|
|
4373
|
+
}
|
|
4374
|
+
}
|
|
4375
|
+
return roundMoney(unitPrice * item.quantity);
|
|
4376
|
+
}
|
|
4377
|
+
function calculateSummary(items) {
|
|
4378
|
+
const subtotal = roundMoney(items.reduce((sum, item) => sum + calculateLineSubtotal(item), 0));
|
|
4379
|
+
const tax = roundMoney(subtotal * DEFAULT_TAX_RATE);
|
|
4380
|
+
return {
|
|
4381
|
+
subtotal,
|
|
4382
|
+
tax,
|
|
4383
|
+
total: roundMoney(subtotal + tax)
|
|
4384
|
+
};
|
|
4385
|
+
}
|
|
4386
|
+
function toProductFromServerItem(item, businessId) {
|
|
4387
|
+
return {
|
|
4388
|
+
id: item.item_id,
|
|
4389
|
+
business_id: businessId,
|
|
4390
|
+
category_id: item.category_id,
|
|
4391
|
+
name: item.name,
|
|
4392
|
+
slug: item.item_id,
|
|
4393
|
+
description: item.description,
|
|
4394
|
+
image_url: item.image_url,
|
|
4395
|
+
default_price: item.base_price,
|
|
4396
|
+
product_type: "product",
|
|
4397
|
+
inventory_type: "none",
|
|
4398
|
+
variant_strategy: "fetch_all",
|
|
4399
|
+
is_active: item.is_available,
|
|
4400
|
+
created_at: item.created_at,
|
|
4401
|
+
updated_at: item.updated_at,
|
|
4402
|
+
metadata: {
|
|
4403
|
+
from_sdk: true
|
|
4404
|
+
}
|
|
4405
|
+
};
|
|
4406
|
+
}
|
|
4407
|
+
function mapServerCart(serverCart) {
|
|
4408
|
+
const items = serverCart.items.map((item) => {
|
|
4409
|
+
const variant = item.variant_info || item.variant_name ? {
|
|
4410
|
+
id: item.variant_info?.id || item.variant_id || "",
|
|
4411
|
+
name: item.variant_info?.name || item.variant_name || "Variant",
|
|
4412
|
+
price_adjustment: item.variant_info?.price_adjustment
|
|
4413
|
+
} : void 0;
|
|
4414
|
+
const quoteId = typeof item.metadata?.quote_id === "string" ? item.metadata.quote_id : void 0;
|
|
4415
|
+
return {
|
|
4416
|
+
id: item.id,
|
|
4417
|
+
product: toProductFromServerItem(item, serverCart.business_id),
|
|
4418
|
+
quantity: clampQuantity(item.quantity),
|
|
4419
|
+
locationId: serverCart.location_id,
|
|
4420
|
+
variantId: item.variant_id,
|
|
4421
|
+
variant,
|
|
4422
|
+
quoteId,
|
|
4423
|
+
addOnOptionIds: item.add_on_option_ids || void 0,
|
|
4424
|
+
addOnOptions: (item.add_on_options || []).map((option) => ({
|
|
4425
|
+
id: option.id,
|
|
4426
|
+
name: option.name,
|
|
4427
|
+
default_price: option.price
|
|
4428
|
+
})),
|
|
4429
|
+
bundleSelections: item.bundle_selections || void 0,
|
|
4430
|
+
compositeSelections: item.composite_selections || void 0,
|
|
4431
|
+
specialInstructions: item.special_instructions
|
|
4432
|
+
};
|
|
4433
|
+
});
|
|
4434
|
+
return {
|
|
4435
|
+
items,
|
|
4436
|
+
subtotal: roundMoney(toNumber(serverCart.pricing.subtotal)),
|
|
4437
|
+
tax: roundMoney(toNumber(serverCart.pricing.tax_amount)),
|
|
4438
|
+
total: roundMoney(toNumber(serverCart.pricing.total_price)),
|
|
4439
|
+
currency: serverCart.pricing.currency || "USD"
|
|
4440
|
+
};
|
|
4441
|
+
}
|
|
4442
|
+
function buildStorageKey(storeKey) {
|
|
4443
|
+
return `${CART_STORAGE_PREFIX}:${storeKey}`;
|
|
4444
|
+
}
|
|
4445
|
+
function createEmptySnapshot(currency) {
|
|
4446
|
+
return {
|
|
4447
|
+
items: [],
|
|
4448
|
+
subtotal: 0,
|
|
4449
|
+
tax: 0,
|
|
4450
|
+
total: 0,
|
|
4451
|
+
currency,
|
|
4452
|
+
isLoading: true
|
|
4453
|
+
};
|
|
4454
|
+
}
|
|
4455
|
+
function createCartStore(params) {
|
|
4456
|
+
const { client, storeKey, locationId, isDemoMode, currency } = params;
|
|
4457
|
+
const storageKey = buildStorageKey(storeKey);
|
|
4458
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
4459
|
+
let snapshot = createEmptySnapshot(currency);
|
|
4460
|
+
let initialized = false;
|
|
4461
|
+
let initializePromise = null;
|
|
4462
|
+
function emit() {
|
|
4463
|
+
listeners.forEach((listener) => {
|
|
4464
|
+
listener();
|
|
4465
|
+
});
|
|
4466
|
+
}
|
|
4467
|
+
function setSnapshot(nextSnapshot) {
|
|
4468
|
+
snapshot = nextSnapshot;
|
|
4469
|
+
persistSnapshot();
|
|
4470
|
+
emit();
|
|
4471
|
+
}
|
|
4472
|
+
function updateSnapshot(updater) {
|
|
4473
|
+
setSnapshot(updater(snapshot));
|
|
4474
|
+
}
|
|
4475
|
+
function persistSnapshot() {
|
|
4476
|
+
if (typeof window === "undefined" || !window.localStorage) {
|
|
4477
|
+
return;
|
|
4478
|
+
}
|
|
4479
|
+
try {
|
|
4480
|
+
window.localStorage.setItem(
|
|
4481
|
+
storageKey,
|
|
4482
|
+
JSON.stringify({
|
|
4483
|
+
items: snapshot.items,
|
|
4484
|
+
subtotal: snapshot.subtotal,
|
|
4485
|
+
tax: snapshot.tax,
|
|
4486
|
+
total: snapshot.total,
|
|
4487
|
+
currency: snapshot.currency
|
|
4488
|
+
})
|
|
4489
|
+
);
|
|
4490
|
+
} catch {
|
|
4491
|
+
}
|
|
4492
|
+
}
|
|
4493
|
+
function hydrateFromStorage() {
|
|
4494
|
+
if (typeof window === "undefined" || !window.localStorage) {
|
|
4495
|
+
return;
|
|
4496
|
+
}
|
|
4497
|
+
try {
|
|
4498
|
+
const raw = window.localStorage.getItem(storageKey);
|
|
4499
|
+
if (!raw) {
|
|
4500
|
+
return;
|
|
4501
|
+
}
|
|
4502
|
+
const parsed = JSON.parse(raw);
|
|
4503
|
+
if (!parsed || !Array.isArray(parsed.items)) {
|
|
4504
|
+
return;
|
|
4505
|
+
}
|
|
4506
|
+
snapshot = {
|
|
4507
|
+
items: parsed.items,
|
|
4508
|
+
subtotal: toNumber(parsed.subtotal),
|
|
4509
|
+
tax: toNumber(parsed.tax),
|
|
4510
|
+
total: toNumber(parsed.total),
|
|
4511
|
+
currency: typeof parsed.currency === "string" && parsed.currency ? parsed.currency : currency,
|
|
4512
|
+
isLoading: !isDemoMode
|
|
4513
|
+
};
|
|
4514
|
+
emit();
|
|
4515
|
+
} catch {
|
|
4516
|
+
}
|
|
4517
|
+
}
|
|
4518
|
+
async function sync() {
|
|
4519
|
+
if (isDemoMode) {
|
|
4520
|
+
updateSnapshot((current) => ({
|
|
4521
|
+
...current,
|
|
4522
|
+
isLoading: false
|
|
4523
|
+
}));
|
|
4524
|
+
return;
|
|
4525
|
+
}
|
|
4526
|
+
updateSnapshot((current) => ({
|
|
4527
|
+
...current,
|
|
4528
|
+
isLoading: true
|
|
4529
|
+
}));
|
|
4530
|
+
const result = await client.cart.get();
|
|
4531
|
+
if (!result.ok) {
|
|
4532
|
+
updateSnapshot((current) => ({
|
|
4533
|
+
...current,
|
|
4534
|
+
isLoading: false
|
|
4535
|
+
}));
|
|
4536
|
+
throw result.error;
|
|
4537
|
+
}
|
|
4538
|
+
const next = mapServerCart(result.value);
|
|
4539
|
+
setSnapshot({
|
|
4540
|
+
...next,
|
|
4541
|
+
isLoading: false
|
|
4542
|
+
});
|
|
4543
|
+
}
|
|
4544
|
+
async function maybeResolveQuoteId(product, quantity, options) {
|
|
4545
|
+
if (options.quoteId) {
|
|
4546
|
+
return options.quoteId;
|
|
4547
|
+
}
|
|
4548
|
+
const addOnOptionIds = normalizeOptionIds(options.addOnOptionIds);
|
|
4549
|
+
const requiresQuote = Boolean(
|
|
4550
|
+
options.variantId || addOnOptionIds && addOnOptionIds.length > 0 || options.bundleSelections && options.bundleSelections.length > 0 || options.compositeSelections && options.compositeSelections.length > 0
|
|
4551
|
+
);
|
|
4552
|
+
if (!requiresQuote || isDemoMode) {
|
|
4553
|
+
return void 0;
|
|
4554
|
+
}
|
|
4555
|
+
const quoteResult = await client.catalogue.fetchQuote({
|
|
4556
|
+
product_id: product.id,
|
|
4557
|
+
quantity,
|
|
4558
|
+
location_id: options.locationId || locationId || void 0,
|
|
4559
|
+
variant_id: options.variantId,
|
|
4560
|
+
add_on_option_ids: addOnOptionIds,
|
|
4561
|
+
bundle_selections: options.bundleSelections,
|
|
4562
|
+
composite_selections: options.compositeSelections
|
|
4563
|
+
});
|
|
4564
|
+
if (!quoteResult.ok) {
|
|
4565
|
+
throw quoteResult.error;
|
|
4566
|
+
}
|
|
4567
|
+
return quoteResult.value.quote_id;
|
|
4568
|
+
}
|
|
4569
|
+
async function addItem(product, quantity = 1, options = {}) {
|
|
4570
|
+
const resolvedQuantity = clampQuantity(quantity);
|
|
4571
|
+
const normalizedOptions = {
|
|
4572
|
+
...options,
|
|
4573
|
+
locationId: options.locationId || locationId || void 0,
|
|
4574
|
+
addOnOptionIds: normalizeOptionIds(options.addOnOptionIds)
|
|
4575
|
+
};
|
|
4576
|
+
const maybeProductWithVariants = product;
|
|
4577
|
+
if (Array.isArray(maybeProductWithVariants.variants) && maybeProductWithVariants.variants.length > 0 && !normalizedOptions.variantId) {
|
|
4578
|
+
console.warn(
|
|
4579
|
+
"[Cimplify] addItem() called without variantId for a product that has variants. Default variant pricing will be used."
|
|
4580
|
+
);
|
|
4581
|
+
}
|
|
4582
|
+
const previousSnapshot = snapshot;
|
|
4583
|
+
const lineKey = buildLineKey(product.id, normalizedOptions);
|
|
4584
|
+
const optimisticItem = {
|
|
4585
|
+
id: `tmp_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`,
|
|
4586
|
+
product,
|
|
4587
|
+
quantity: resolvedQuantity,
|
|
4588
|
+
locationId: normalizedOptions.locationId,
|
|
4589
|
+
variantId: normalizedOptions.variantId,
|
|
4590
|
+
variant: normalizedOptions.variant,
|
|
4591
|
+
quoteId: normalizedOptions.quoteId,
|
|
4592
|
+
addOnOptionIds: normalizedOptions.addOnOptionIds,
|
|
4593
|
+
addOnOptions: normalizedOptions.addOnOptions,
|
|
4594
|
+
bundleSelections: normalizedOptions.bundleSelections,
|
|
4595
|
+
compositeSelections: normalizedOptions.compositeSelections,
|
|
4596
|
+
specialInstructions: normalizedOptions.specialInstructions
|
|
4597
|
+
};
|
|
4598
|
+
updateSnapshot((current) => {
|
|
4599
|
+
const existingIndex = current.items.findIndex((item) => {
|
|
4600
|
+
const itemKey = buildLineKey(item.product.id, {
|
|
4601
|
+
locationId: item.locationId,
|
|
4602
|
+
variantId: item.variantId,
|
|
4603
|
+
quoteId: item.quoteId,
|
|
4604
|
+
addOnOptionIds: item.addOnOptionIds,
|
|
4605
|
+
bundleSelections: item.bundleSelections,
|
|
4606
|
+
compositeSelections: item.compositeSelections
|
|
4607
|
+
});
|
|
4608
|
+
return itemKey === lineKey;
|
|
4609
|
+
});
|
|
4610
|
+
const nextItems = [...current.items];
|
|
4611
|
+
if (existingIndex >= 0) {
|
|
4612
|
+
const existing = nextItems[existingIndex];
|
|
4613
|
+
nextItems[existingIndex] = {
|
|
4614
|
+
...existing,
|
|
4615
|
+
quantity: existing.quantity + resolvedQuantity
|
|
4616
|
+
};
|
|
4617
|
+
} else {
|
|
4618
|
+
nextItems.push(optimisticItem);
|
|
4619
|
+
}
|
|
4620
|
+
const summary = calculateSummary(nextItems);
|
|
4621
|
+
return {
|
|
4622
|
+
...current,
|
|
4623
|
+
items: nextItems,
|
|
4624
|
+
subtotal: summary.subtotal,
|
|
4625
|
+
tax: summary.tax,
|
|
4626
|
+
total: summary.total
|
|
4627
|
+
};
|
|
4628
|
+
});
|
|
4629
|
+
if (isDemoMode) {
|
|
4630
|
+
return;
|
|
4631
|
+
}
|
|
4632
|
+
try {
|
|
4633
|
+
const quoteId = await maybeResolveQuoteId(product, resolvedQuantity, normalizedOptions);
|
|
4634
|
+
const result = await client.cart.addItem({
|
|
4635
|
+
item_id: product.id,
|
|
4636
|
+
quantity: resolvedQuantity,
|
|
4637
|
+
variant_id: normalizedOptions.variantId,
|
|
4638
|
+
quote_id: quoteId,
|
|
4639
|
+
add_on_options: normalizedOptions.addOnOptionIds,
|
|
4640
|
+
special_instructions: normalizedOptions.specialInstructions,
|
|
4641
|
+
bundle_selections: normalizedOptions.bundleSelections,
|
|
4642
|
+
composite_selections: normalizedOptions.compositeSelections
|
|
4643
|
+
});
|
|
4644
|
+
if (!result.ok) {
|
|
4645
|
+
throw result.error;
|
|
4646
|
+
}
|
|
4647
|
+
await sync();
|
|
4648
|
+
} catch (error) {
|
|
4649
|
+
snapshot = previousSnapshot;
|
|
4650
|
+
persistSnapshot();
|
|
4651
|
+
emit();
|
|
4652
|
+
throw error;
|
|
4653
|
+
}
|
|
4654
|
+
}
|
|
4655
|
+
async function removeItem(itemId) {
|
|
4656
|
+
const previousSnapshot = snapshot;
|
|
4657
|
+
updateSnapshot((current) => {
|
|
4658
|
+
const nextItems = current.items.filter((item) => item.id !== itemId);
|
|
4659
|
+
const summary = calculateSummary(nextItems);
|
|
4660
|
+
return {
|
|
4661
|
+
...current,
|
|
4662
|
+
items: nextItems,
|
|
4663
|
+
subtotal: summary.subtotal,
|
|
4664
|
+
tax: summary.tax,
|
|
4665
|
+
total: summary.total
|
|
4666
|
+
};
|
|
4667
|
+
});
|
|
4668
|
+
if (isDemoMode) {
|
|
4669
|
+
return;
|
|
4670
|
+
}
|
|
4671
|
+
try {
|
|
4672
|
+
const result = await client.cart.removeItem(itemId);
|
|
4673
|
+
if (!result.ok) {
|
|
4674
|
+
throw result.error;
|
|
4675
|
+
}
|
|
4676
|
+
await sync();
|
|
4677
|
+
} catch (error) {
|
|
4678
|
+
snapshot = previousSnapshot;
|
|
4679
|
+
persistSnapshot();
|
|
4680
|
+
emit();
|
|
4681
|
+
throw error;
|
|
4682
|
+
}
|
|
4683
|
+
}
|
|
4684
|
+
async function updateQuantity(itemId, quantity) {
|
|
4685
|
+
if (quantity <= 0) {
|
|
4686
|
+
await removeItem(itemId);
|
|
4687
|
+
return;
|
|
4688
|
+
}
|
|
4689
|
+
const resolvedQuantity = clampQuantity(quantity);
|
|
4690
|
+
const previousSnapshot = snapshot;
|
|
4691
|
+
updateSnapshot((current) => {
|
|
4692
|
+
const nextItems = current.items.map(
|
|
4693
|
+
(item) => item.id === itemId ? {
|
|
4694
|
+
...item,
|
|
4695
|
+
quantity: resolvedQuantity
|
|
4696
|
+
} : item
|
|
4697
|
+
);
|
|
4698
|
+
const summary = calculateSummary(nextItems);
|
|
4699
|
+
return {
|
|
4700
|
+
...current,
|
|
4701
|
+
items: nextItems,
|
|
4702
|
+
subtotal: summary.subtotal,
|
|
4703
|
+
tax: summary.tax,
|
|
4704
|
+
total: summary.total
|
|
4705
|
+
};
|
|
4706
|
+
});
|
|
4707
|
+
if (isDemoMode) {
|
|
4708
|
+
return;
|
|
4709
|
+
}
|
|
4710
|
+
try {
|
|
4711
|
+
const result = await client.cart.updateQuantity(itemId, resolvedQuantity);
|
|
4712
|
+
if (!result.ok) {
|
|
4713
|
+
throw result.error;
|
|
4714
|
+
}
|
|
4715
|
+
await sync();
|
|
4716
|
+
} catch (error) {
|
|
4717
|
+
snapshot = previousSnapshot;
|
|
4718
|
+
persistSnapshot();
|
|
4719
|
+
emit();
|
|
4720
|
+
throw error;
|
|
4721
|
+
}
|
|
4722
|
+
}
|
|
4723
|
+
async function clearCart() {
|
|
4724
|
+
const previousSnapshot = snapshot;
|
|
4725
|
+
updateSnapshot((current) => ({
|
|
4726
|
+
...current,
|
|
4727
|
+
items: [],
|
|
4728
|
+
subtotal: 0,
|
|
4729
|
+
tax: 0,
|
|
4730
|
+
total: 0
|
|
4731
|
+
}));
|
|
4732
|
+
if (isDemoMode) {
|
|
4733
|
+
return;
|
|
4734
|
+
}
|
|
4735
|
+
try {
|
|
4736
|
+
const result = await client.cart.clear();
|
|
4737
|
+
if (!result.ok) {
|
|
4738
|
+
throw result.error;
|
|
4739
|
+
}
|
|
4740
|
+
await sync();
|
|
4741
|
+
} catch (error) {
|
|
4742
|
+
snapshot = previousSnapshot;
|
|
4743
|
+
persistSnapshot();
|
|
4744
|
+
emit();
|
|
4745
|
+
throw error;
|
|
4746
|
+
}
|
|
4747
|
+
}
|
|
4748
|
+
async function initialize() {
|
|
4749
|
+
if (initialized) {
|
|
4750
|
+
if (initializePromise) {
|
|
4751
|
+
await initializePromise;
|
|
4752
|
+
}
|
|
4753
|
+
return;
|
|
4754
|
+
}
|
|
4755
|
+
initialized = true;
|
|
4756
|
+
hydrateFromStorage();
|
|
4757
|
+
if (isDemoMode) {
|
|
4758
|
+
updateSnapshot((current) => ({
|
|
4759
|
+
...current,
|
|
4760
|
+
isLoading: false
|
|
4761
|
+
}));
|
|
4762
|
+
return;
|
|
4763
|
+
}
|
|
4764
|
+
initializePromise = sync().catch(() => {
|
|
4765
|
+
updateSnapshot((current) => ({
|
|
4766
|
+
...current,
|
|
4767
|
+
isLoading: false
|
|
4768
|
+
}));
|
|
4769
|
+
});
|
|
4770
|
+
await initializePromise;
|
|
4771
|
+
initializePromise = null;
|
|
4772
|
+
}
|
|
4773
|
+
return {
|
|
4774
|
+
subscribe(listener) {
|
|
4775
|
+
listeners.add(listener);
|
|
4776
|
+
return () => {
|
|
4777
|
+
listeners.delete(listener);
|
|
4778
|
+
};
|
|
4779
|
+
},
|
|
4780
|
+
getSnapshot() {
|
|
4781
|
+
return snapshot;
|
|
4782
|
+
},
|
|
4783
|
+
initialize,
|
|
4784
|
+
addItem,
|
|
4785
|
+
removeItem,
|
|
4786
|
+
updateQuantity,
|
|
4787
|
+
clearCart,
|
|
4788
|
+
sync
|
|
4789
|
+
};
|
|
4790
|
+
}
|
|
4791
|
+
function getStoreKey(client, locationId, isDemoMode) {
|
|
4792
|
+
return [
|
|
4793
|
+
client.getPublicKey() || "__demo__",
|
|
4794
|
+
locationId || "__no_location__",
|
|
4795
|
+
isDemoMode ? "demo" : "live"
|
|
4796
|
+
].join(":");
|
|
4797
|
+
}
|
|
4798
|
+
function getOrCreateStore(params) {
|
|
4799
|
+
const { client, locationId, isDemoMode, currency } = params;
|
|
4800
|
+
const storeKey = getStoreKey(client, locationId, isDemoMode);
|
|
4801
|
+
const existing = cartStores.get(storeKey);
|
|
4802
|
+
if (existing) {
|
|
4803
|
+
return existing;
|
|
4804
|
+
}
|
|
4805
|
+
const created = createCartStore({
|
|
4806
|
+
client,
|
|
4807
|
+
storeKey,
|
|
4808
|
+
locationId,
|
|
4809
|
+
isDemoMode,
|
|
4810
|
+
currency
|
|
4811
|
+
});
|
|
4812
|
+
cartStores.set(storeKey, created);
|
|
4813
|
+
return created;
|
|
4814
|
+
}
|
|
4815
|
+
function useCart(options = {}) {
|
|
4816
|
+
const context = useOptionalCimplify();
|
|
4817
|
+
const client = options.client ?? context?.client;
|
|
4818
|
+
if (!client) {
|
|
4819
|
+
throw new Error("useCart must be used within CimplifyProvider or passed { client }.");
|
|
4820
|
+
}
|
|
4821
|
+
const locationId = options.locationId ?? client.getLocationId();
|
|
4822
|
+
const isDemoMode = options.demoMode ?? context?.isDemoMode ?? client.getPublicKey().trim().length === 0;
|
|
4823
|
+
const currency = options.currency ?? context?.currency ?? "USD";
|
|
4824
|
+
const store = react.useMemo(
|
|
4825
|
+
() => getOrCreateStore({
|
|
4826
|
+
client,
|
|
4827
|
+
locationId,
|
|
4828
|
+
isDemoMode,
|
|
4829
|
+
currency
|
|
4830
|
+
}),
|
|
4831
|
+
[client, currency, isDemoMode, locationId]
|
|
4832
|
+
);
|
|
4833
|
+
const snapshot = react.useSyncExternalStore(
|
|
4834
|
+
store.subscribe,
|
|
4835
|
+
store.getSnapshot,
|
|
4836
|
+
store.getSnapshot
|
|
4837
|
+
);
|
|
4838
|
+
react.useEffect(() => {
|
|
4839
|
+
void store.initialize();
|
|
4840
|
+
}, [store]);
|
|
4841
|
+
const addItem = react.useCallback(
|
|
4842
|
+
async (product, quantity, addOptions) => {
|
|
4843
|
+
await store.addItem(product, quantity, addOptions);
|
|
4844
|
+
},
|
|
4845
|
+
[store]
|
|
4846
|
+
);
|
|
4847
|
+
const removeItem = react.useCallback(
|
|
4848
|
+
async (itemId) => {
|
|
4849
|
+
await store.removeItem(itemId);
|
|
4850
|
+
},
|
|
4851
|
+
[store]
|
|
4852
|
+
);
|
|
4853
|
+
const updateQuantity = react.useCallback(
|
|
4854
|
+
async (itemId, quantity) => {
|
|
4855
|
+
await store.updateQuantity(itemId, quantity);
|
|
4856
|
+
},
|
|
4857
|
+
[store]
|
|
4858
|
+
);
|
|
4859
|
+
const clearCart = react.useCallback(async () => {
|
|
4860
|
+
await store.clearCart();
|
|
4861
|
+
}, [store]);
|
|
4862
|
+
const sync = react.useCallback(async () => {
|
|
4863
|
+
try {
|
|
4864
|
+
await store.sync();
|
|
4865
|
+
} catch (syncError) {
|
|
4866
|
+
throw syncError;
|
|
4867
|
+
}
|
|
4868
|
+
}, [store]);
|
|
4869
|
+
const itemCount = react.useMemo(
|
|
4870
|
+
() => snapshot.items.reduce((sum, item) => sum + item.quantity, 0),
|
|
4871
|
+
[snapshot.items]
|
|
4872
|
+
);
|
|
4873
|
+
return {
|
|
4874
|
+
items: snapshot.items,
|
|
4875
|
+
itemCount,
|
|
4876
|
+
subtotal: snapshot.subtotal,
|
|
4877
|
+
tax: snapshot.tax,
|
|
4878
|
+
total: snapshot.total,
|
|
4879
|
+
currency: snapshot.currency,
|
|
4880
|
+
isEmpty: itemCount === 0,
|
|
4881
|
+
isLoading: snapshot.isLoading,
|
|
4882
|
+
addItem,
|
|
4883
|
+
removeItem,
|
|
4884
|
+
updateQuantity,
|
|
4885
|
+
clearCart,
|
|
4886
|
+
sync
|
|
4887
|
+
};
|
|
4888
|
+
}
|
|
4889
|
+
var orderCache = /* @__PURE__ */ new Map();
|
|
4890
|
+
var orderInflight = /* @__PURE__ */ new Map();
|
|
4891
|
+
function buildOrderCacheKey(client, orderId) {
|
|
4892
|
+
return `${client.getPublicKey() || "__demo__"}:${orderId}`;
|
|
4893
|
+
}
|
|
4894
|
+
function useOrder(orderId, options = {}) {
|
|
4895
|
+
const context = useOptionalCimplify();
|
|
4896
|
+
const client = options.client ?? context?.client;
|
|
4897
|
+
if (!client) {
|
|
4898
|
+
throw new Error("useOrder must be used within CimplifyProvider or passed { client }.");
|
|
4899
|
+
}
|
|
4900
|
+
const normalizedOrderId = react.useMemo(() => (orderId || "").trim(), [orderId]);
|
|
4901
|
+
const enabled = options.enabled ?? true;
|
|
4902
|
+
const poll = options.poll ?? false;
|
|
4903
|
+
const pollInterval = options.pollInterval ?? 5e3;
|
|
4904
|
+
const requestIdRef = react.useRef(0);
|
|
4905
|
+
const cacheKey = react.useMemo(
|
|
4906
|
+
() => buildOrderCacheKey(client, normalizedOrderId),
|
|
4907
|
+
[client, normalizedOrderId]
|
|
4908
|
+
);
|
|
4909
|
+
const cached = orderCache.get(cacheKey);
|
|
4910
|
+
const [order, setOrder] = react.useState(cached?.order ?? null);
|
|
4911
|
+
const [isLoading, setIsLoading] = react.useState(
|
|
4912
|
+
enabled && normalizedOrderId.length > 0 && !cached
|
|
4913
|
+
);
|
|
4914
|
+
const [error, setError] = react.useState(null);
|
|
4915
|
+
const load = react.useCallback(
|
|
4916
|
+
async (force = false) => {
|
|
4917
|
+
if (!enabled || normalizedOrderId.length === 0) {
|
|
4918
|
+
setOrder(null);
|
|
4919
|
+
setIsLoading(false);
|
|
4920
|
+
return;
|
|
4921
|
+
}
|
|
4922
|
+
const nextRequestId = ++requestIdRef.current;
|
|
4923
|
+
setError(null);
|
|
4924
|
+
if (!force) {
|
|
4925
|
+
const cacheEntry = orderCache.get(cacheKey);
|
|
4926
|
+
if (cacheEntry) {
|
|
4927
|
+
setOrder(cacheEntry.order);
|
|
4928
|
+
setIsLoading(false);
|
|
4929
|
+
return;
|
|
4930
|
+
}
|
|
4931
|
+
}
|
|
4932
|
+
setIsLoading(true);
|
|
4933
|
+
try {
|
|
4934
|
+
const existing = orderInflight.get(cacheKey);
|
|
4935
|
+
const promise = existing ?? (async () => {
|
|
4936
|
+
const result = await client.orders.get(normalizedOrderId);
|
|
4937
|
+
if (!result.ok) {
|
|
4938
|
+
throw result.error;
|
|
4939
|
+
}
|
|
4940
|
+
return result.value;
|
|
4941
|
+
})();
|
|
4942
|
+
if (!existing) {
|
|
4943
|
+
orderInflight.set(
|
|
4944
|
+
cacheKey,
|
|
4945
|
+
promise.finally(() => {
|
|
4946
|
+
orderInflight.delete(cacheKey);
|
|
4947
|
+
})
|
|
4948
|
+
);
|
|
4949
|
+
}
|
|
4950
|
+
const value = await promise;
|
|
4951
|
+
orderCache.set(cacheKey, { order: value });
|
|
4952
|
+
if (nextRequestId === requestIdRef.current) {
|
|
4953
|
+
setOrder(value);
|
|
4954
|
+
setError(null);
|
|
4955
|
+
}
|
|
4956
|
+
} catch (loadError) {
|
|
4957
|
+
if (nextRequestId === requestIdRef.current) {
|
|
4958
|
+
setError(loadError);
|
|
4959
|
+
}
|
|
4960
|
+
} finally {
|
|
4961
|
+
if (nextRequestId === requestIdRef.current) {
|
|
4962
|
+
setIsLoading(false);
|
|
4963
|
+
}
|
|
4964
|
+
}
|
|
4965
|
+
},
|
|
4966
|
+
[cacheKey, client, enabled, normalizedOrderId]
|
|
4967
|
+
);
|
|
4968
|
+
react.useEffect(() => {
|
|
4969
|
+
void load(false);
|
|
4970
|
+
}, [load]);
|
|
4971
|
+
react.useEffect(() => {
|
|
4972
|
+
if (!poll || !enabled || normalizedOrderId.length === 0) {
|
|
4973
|
+
return;
|
|
4974
|
+
}
|
|
4975
|
+
const timer = window.setInterval(() => {
|
|
4976
|
+
void load(true);
|
|
4977
|
+
}, Math.max(1e3, pollInterval));
|
|
4978
|
+
return () => {
|
|
4979
|
+
window.clearInterval(timer);
|
|
4980
|
+
};
|
|
4981
|
+
}, [enabled, load, normalizedOrderId.length, poll, pollInterval]);
|
|
4982
|
+
const refetch = react.useCallback(async () => {
|
|
4983
|
+
orderCache.delete(cacheKey);
|
|
4984
|
+
await load(true);
|
|
4985
|
+
}, [cacheKey, load]);
|
|
4986
|
+
return { order, isLoading, error, refetch };
|
|
4987
|
+
}
|
|
4988
|
+
var LOCATION_STORAGE_KEY2 = "cimplify_location_id";
|
|
4989
|
+
function readStoredLocationId() {
|
|
4990
|
+
if (typeof window === "undefined" || !window.localStorage) {
|
|
4991
|
+
return null;
|
|
4992
|
+
}
|
|
4993
|
+
const value = window.localStorage.getItem(LOCATION_STORAGE_KEY2);
|
|
4994
|
+
if (!value) {
|
|
4995
|
+
return null;
|
|
4996
|
+
}
|
|
4997
|
+
const normalized = value.trim();
|
|
4998
|
+
return normalized.length > 0 ? normalized : null;
|
|
4999
|
+
}
|
|
5000
|
+
function writeStoredLocationId(locationId) {
|
|
5001
|
+
if (typeof window === "undefined" || !window.localStorage) {
|
|
5002
|
+
return;
|
|
5003
|
+
}
|
|
5004
|
+
if (!locationId) {
|
|
5005
|
+
window.localStorage.removeItem(LOCATION_STORAGE_KEY2);
|
|
5006
|
+
return;
|
|
5007
|
+
}
|
|
5008
|
+
window.localStorage.setItem(LOCATION_STORAGE_KEY2, locationId);
|
|
5009
|
+
}
|
|
5010
|
+
function resolveLocation(locations, preferredId) {
|
|
5011
|
+
if (locations.length === 0) {
|
|
5012
|
+
return null;
|
|
5013
|
+
}
|
|
5014
|
+
if (preferredId) {
|
|
5015
|
+
const found = locations.find((location) => location.id === preferredId);
|
|
5016
|
+
if (found) {
|
|
5017
|
+
return found;
|
|
5018
|
+
}
|
|
5019
|
+
}
|
|
5020
|
+
return locations[0];
|
|
5021
|
+
}
|
|
5022
|
+
function useLocations(options = {}) {
|
|
5023
|
+
const context = useOptionalCimplify();
|
|
5024
|
+
if (context && (!options.client || context.client === options.client)) {
|
|
5025
|
+
return {
|
|
5026
|
+
locations: context.locations,
|
|
5027
|
+
currentLocation: context.currentLocation,
|
|
5028
|
+
setCurrentLocation: context.setCurrentLocation,
|
|
5029
|
+
isLoading: !context.isReady
|
|
5030
|
+
};
|
|
5031
|
+
}
|
|
5032
|
+
const client = options.client;
|
|
5033
|
+
const [locations, setLocations] = react.useState([]);
|
|
5034
|
+
const [currentLocation, setCurrentLocationState] = react.useState(null);
|
|
5035
|
+
const [isLoading, setIsLoading] = react.useState(true);
|
|
5036
|
+
const setCurrentLocation = react.useCallback(
|
|
5037
|
+
(location) => {
|
|
5038
|
+
setCurrentLocationState(location);
|
|
5039
|
+
if (client) {
|
|
5040
|
+
client.setLocationId(location.id);
|
|
5041
|
+
}
|
|
5042
|
+
writeStoredLocationId(location.id);
|
|
5043
|
+
},
|
|
5044
|
+
[client]
|
|
5045
|
+
);
|
|
5046
|
+
react.useEffect(() => {
|
|
5047
|
+
if (!client) {
|
|
5048
|
+
setLocations([]);
|
|
5049
|
+
setCurrentLocationState(null);
|
|
5050
|
+
setIsLoading(false);
|
|
5051
|
+
return;
|
|
5052
|
+
}
|
|
5053
|
+
const activeClient = client;
|
|
5054
|
+
let cancelled = false;
|
|
5055
|
+
async function loadLocations() {
|
|
5056
|
+
setIsLoading(true);
|
|
5057
|
+
const result = await activeClient.business.getLocations();
|
|
5058
|
+
if (cancelled) {
|
|
5059
|
+
return;
|
|
5060
|
+
}
|
|
5061
|
+
if (!result.ok) {
|
|
5062
|
+
setLocations([]);
|
|
5063
|
+
setCurrentLocationState(null);
|
|
5064
|
+
setIsLoading(false);
|
|
5065
|
+
return;
|
|
5066
|
+
}
|
|
5067
|
+
const nextLocations = result.value;
|
|
5068
|
+
const preferredId = activeClient.getLocationId() ?? readStoredLocationId();
|
|
5069
|
+
const resolved = resolveLocation(nextLocations, preferredId);
|
|
5070
|
+
setLocations(nextLocations);
|
|
5071
|
+
setCurrentLocationState(resolved);
|
|
5072
|
+
activeClient.setLocationId(resolved?.id || null);
|
|
5073
|
+
writeStoredLocationId(resolved?.id || null);
|
|
5074
|
+
setIsLoading(false);
|
|
5075
|
+
}
|
|
5076
|
+
void loadLocations();
|
|
5077
|
+
return () => {
|
|
5078
|
+
cancelled = true;
|
|
5079
|
+
};
|
|
5080
|
+
}, [client]);
|
|
5081
|
+
return {
|
|
5082
|
+
locations,
|
|
5083
|
+
currentLocation,
|
|
5084
|
+
setCurrentLocation,
|
|
5085
|
+
isLoading
|
|
5086
|
+
};
|
|
5087
|
+
}
|
|
3866
5088
|
var ElementsContext = react.createContext({
|
|
3867
5089
|
elements: null,
|
|
3868
5090
|
isReady: false
|
|
@@ -4032,7 +5254,14 @@ exports.CimplifyProvider = CimplifyProvider;
|
|
|
4032
5254
|
exports.ElementsProvider = ElementsProvider;
|
|
4033
5255
|
exports.PaymentElement = PaymentElement;
|
|
4034
5256
|
exports.useAds = useAds;
|
|
5257
|
+
exports.useCart = useCart;
|
|
5258
|
+
exports.useCategories = useCategories;
|
|
4035
5259
|
exports.useCheckout = useCheckout;
|
|
4036
5260
|
exports.useCimplify = useCimplify;
|
|
4037
5261
|
exports.useElements = useElements;
|
|
4038
5262
|
exports.useElementsReady = useElementsReady;
|
|
5263
|
+
exports.useLocations = useLocations;
|
|
5264
|
+
exports.useOptionalCimplify = useOptionalCimplify;
|
|
5265
|
+
exports.useOrder = useOrder;
|
|
5266
|
+
exports.useProduct = useProduct;
|
|
5267
|
+
exports.useProducts = useProducts;
|