@cimplify/sdk 0.6.4 → 0.6.6

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/react.mjs CHANGED
@@ -9,6 +9,27 @@ var ELEMENT_TYPES = {
9
9
  ADDRESS: "address",
10
10
  PAYMENT: "payment"
11
11
  };
12
+ var MESSAGE_TYPES = {
13
+ // Parent → Iframe
14
+ INIT: "init",
15
+ SET_TOKEN: "set_token",
16
+ GET_DATA: "get_data",
17
+ PROCESS_CHECKOUT: "process_checkout",
18
+ ABORT_CHECKOUT: "abort_checkout",
19
+ // Iframe → Parent
20
+ READY: "ready",
21
+ HEIGHT_CHANGE: "height_change",
22
+ AUTHENTICATED: "authenticated",
23
+ REQUIRES_OTP: "requires_otp",
24
+ ERROR: "error",
25
+ ADDRESS_CHANGED: "address_changed",
26
+ ADDRESS_SELECTED: "address_selected",
27
+ PAYMENT_METHOD_SELECTED: "payment_method_selected",
28
+ TOKEN_REFRESHED: "token_refreshed",
29
+ LOGOUT_COMPLETE: "logout_complete",
30
+ CHECKOUT_STATUS: "checkout_status",
31
+ CHECKOUT_COMPLETE: "checkout_complete"
32
+ };
12
33
  var EVENT_TYPES = {
13
34
  READY: "ready",
14
35
  AUTHENTICATED: "authenticated",
@@ -362,6 +383,7 @@ function CimplifyCheckout({
362
383
  onError,
363
384
  onStatusChange,
364
385
  appearance,
386
+ demoMode,
365
387
  className
366
388
  }) {
367
389
  const resolvedOrderTypes = useMemo(
@@ -370,20 +392,121 @@ function CimplifyCheckout({
370
392
  );
371
393
  const [orderType, setOrderType] = useState(resolvedOrderTypes[0] || "pickup");
372
394
  const [status, setStatus] = useState(null);
395
+ const [statusText, setStatusText] = useState("");
373
396
  const [isSubmitting, setIsSubmitting] = useState(false);
397
+ const [isInitializing, setIsInitializing] = useState(false);
374
398
  const [errorMessage, setErrorMessage] = useState(null);
399
+ const [resolvedBusinessId, setResolvedBusinessId] = useState(businessId ?? null);
400
+ const [resolvedCartId, setResolvedCartId] = useState(cartId ?? null);
375
401
  const authMountRef = useRef(null);
376
402
  const addressMountRef = useRef(null);
377
403
  const paymentMountRef = useRef(null);
378
404
  const elementsRef = useRef(null);
379
405
  const activeCheckoutRef = useRef(null);
406
+ const initialAppearanceRef = useRef(appearance);
407
+ const isMountedRef = useRef(true);
408
+ const demoRunRef = useRef(0);
409
+ const isDemoCheckout = demoMode ?? client.getPublicKey().trim().length === 0;
410
+ const emitStatus = useCallback(
411
+ (nextStatus, context = {}) => {
412
+ setStatus(nextStatus);
413
+ setStatusText(context.display_text || "");
414
+ onStatusChange?.(nextStatus, context);
415
+ },
416
+ [onStatusChange]
417
+ );
380
418
  useEffect(() => {
381
419
  if (!resolvedOrderTypes.includes(orderType)) {
382
420
  setOrderType(resolvedOrderTypes[0] || "pickup");
383
421
  }
384
422
  }, [resolvedOrderTypes, orderType]);
385
423
  useEffect(() => {
386
- const elements = client.elements(businessId, { appearance });
424
+ let cancelled = false;
425
+ async function bootstrap() {
426
+ if (isDemoCheckout) {
427
+ if (!cancelled) {
428
+ setResolvedBusinessId(businessId ?? null);
429
+ setResolvedCartId(cartId ?? "cart_demo");
430
+ setIsInitializing(false);
431
+ setErrorMessage(null);
432
+ }
433
+ return;
434
+ }
435
+ const needsBusinessResolve = !businessId;
436
+ const needsCartResolve = !cartId;
437
+ if (!needsBusinessResolve && !needsCartResolve) {
438
+ if (!cancelled) {
439
+ setResolvedBusinessId(businessId || null);
440
+ setResolvedCartId(cartId || null);
441
+ setIsInitializing(false);
442
+ setErrorMessage(null);
443
+ }
444
+ return;
445
+ }
446
+ if (!cancelled) {
447
+ setIsInitializing(true);
448
+ setErrorMessage(null);
449
+ }
450
+ let nextBusinessId = businessId ?? null;
451
+ if (!nextBusinessId) {
452
+ try {
453
+ nextBusinessId = await client.resolveBusinessId();
454
+ } catch {
455
+ if (!cancelled) {
456
+ const message = "Unable to initialize checkout business context.";
457
+ setResolvedBusinessId(null);
458
+ setResolvedCartId(null);
459
+ setErrorMessage(message);
460
+ setIsInitializing(false);
461
+ onError?.({ code: "BUSINESS_ID_REQUIRED", message });
462
+ }
463
+ return;
464
+ }
465
+ }
466
+ let nextCartId = cartId ?? null;
467
+ if (!nextCartId) {
468
+ const cartResult = await client.cart.get();
469
+ if (!cartResult.ok || !cartResult.value?.id || cartResult.value.items.length === 0) {
470
+ if (!cancelled) {
471
+ const message = "Your cart is empty. Add items before checkout.";
472
+ setResolvedBusinessId(nextBusinessId);
473
+ setResolvedCartId(null);
474
+ setErrorMessage(message);
475
+ setIsInitializing(false);
476
+ onError?.({ code: "CART_EMPTY", message });
477
+ }
478
+ return;
479
+ }
480
+ nextCartId = cartResult.value.id;
481
+ }
482
+ if (!cancelled) {
483
+ setResolvedBusinessId(nextBusinessId);
484
+ setResolvedCartId(nextCartId);
485
+ setIsInitializing(false);
486
+ setErrorMessage(null);
487
+ }
488
+ }
489
+ void bootstrap();
490
+ return () => {
491
+ cancelled = true;
492
+ };
493
+ }, [businessId, cartId, client, isDemoCheckout, onError]);
494
+ useEffect(() => {
495
+ return () => {
496
+ isMountedRef.current = false;
497
+ demoRunRef.current += 1;
498
+ activeCheckoutRef.current?.abort();
499
+ activeCheckoutRef.current = null;
500
+ };
501
+ }, []);
502
+ useEffect(() => {
503
+ if (isDemoCheckout || !resolvedBusinessId) {
504
+ elementsRef.current = null;
505
+ return;
506
+ }
507
+ const elements = client.elements(resolvedBusinessId, {
508
+ appearance: initialAppearanceRef.current
509
+ });
387
510
  elementsRef.current = elements;
388
511
  const auth = elements.create("auth");
389
512
  const address = elements.create("address", { mode: "shipping" });
@@ -403,27 +526,68 @@ function CimplifyCheckout({
403
526
  elements.destroy();
404
527
  elementsRef.current = null;
405
528
  };
406
- }, [client, businessId, appearance]);
407
- const handleStatusChange = useCallback(
408
- (nextStatus, context) => {
409
- setStatus(nextStatus);
410
- onStatusChange?.(nextStatus, context);
411
- },
412
- [onStatusChange]
413
- );
529
+ }, [client, resolvedBusinessId, isDemoCheckout]);
414
530
  const handleSubmit = useCallback(async () => {
415
- if (!elementsRef.current || isSubmitting) {
531
+ if (isSubmitting || isInitializing || !resolvedCartId) {
532
+ if (!resolvedCartId && !isInitializing) {
533
+ const message = "Your cart is empty. Add items before checkout.";
534
+ setErrorMessage(message);
535
+ onError?.({ code: "CART_EMPTY", message });
536
+ }
416
537
  return;
417
538
  }
418
539
  setErrorMessage(null);
419
540
  setIsSubmitting(true);
420
- setStatus("preparing");
541
+ emitStatus("preparing", { display_text: statusToLabel("preparing") });
542
+ if (isDemoCheckout) {
543
+ const runId = demoRunRef.current + 1;
544
+ demoRunRef.current = runId;
545
+ const wait = async (ms) => {
546
+ await new Promise((resolve) => setTimeout(resolve, ms));
547
+ return isMountedRef.current && runId === demoRunRef.current;
548
+ };
549
+ try {
550
+ if (!await wait(400)) return;
551
+ emitStatus("processing", { display_text: statusToLabel("processing") });
552
+ if (!await wait(900)) return;
553
+ emitStatus("polling", { display_text: statusToLabel("polling") });
554
+ if (!await wait(1200)) return;
555
+ const result = {
556
+ success: true,
557
+ order: {
558
+ id: `ord_demo_${Date.now()}`,
559
+ order_number: `DEMO-${Math.random().toString(36).slice(2, 8).toUpperCase()}`,
560
+ status: "confirmed",
561
+ total: "0.00",
562
+ currency: "USD"
563
+ }
564
+ };
565
+ emitStatus("success", {
566
+ order_id: result.order?.id,
567
+ order_number: result.order?.order_number,
568
+ display_text: statusToLabel("success")
569
+ });
570
+ onComplete(result);
571
+ } finally {
572
+ if (isMountedRef.current && runId === demoRunRef.current) {
573
+ setIsSubmitting(false);
574
+ }
575
+ }
576
+ return;
577
+ }
578
+ if (!elementsRef.current) {
579
+ const message = "Checkout is still initializing. Please try again.";
580
+ setErrorMessage(message);
581
+ onError?.({ code: "CHECKOUT_NOT_READY", message });
582
+ setIsSubmitting(false);
583
+ return;
584
+ }
421
585
  const checkout = elementsRef.current.processCheckout({
422
- cart_id: cartId,
423
- location_id: locationId,
586
+ cart_id: resolvedCartId,
587
+ location_id: locationId ?? client.getLocationId() ?? void 0,
424
588
  order_type: orderType,
425
589
  enroll_in_link: enrollInLink,
426
- on_status_change: handleStatusChange
590
+ on_status_change: emitStatus
427
591
  });
428
592
  activeCheckoutRef.current = checkout;
429
593
  try {
@@ -437,21 +601,32 @@ function CimplifyCheckout({
437
601
  setErrorMessage(message);
438
602
  onError?.({ code, message });
439
603
  } finally {
440
- activeCheckoutRef.current = null;
441
- setIsSubmitting(false);
604
+ if (isMountedRef.current) {
605
+ activeCheckoutRef.current = null;
606
+ setIsSubmitting(false);
607
+ }
442
608
  }
443
609
  }, [
444
- cartId,
610
+ resolvedCartId,
611
+ client,
445
612
  enrollInLink,
446
- handleStatusChange,
613
+ emitStatus,
614
+ isDemoCheckout,
615
+ isInitializing,
447
616
  isSubmitting,
448
617
  locationId,
449
618
  onComplete,
450
619
  onError,
451
620
  orderType
452
621
  ]);
622
+ if (isInitializing) {
623
+ return /* @__PURE__ */ jsx("div", { className, "data-cimplify-checkout": "", children: /* @__PURE__ */ jsx("p", { "data-cimplify-status": "", style: { fontSize: "14px", color: "#52525b" }, children: "Preparing checkout..." }) });
624
+ }
625
+ if (!isDemoCheckout && (!resolvedBusinessId || !resolvedCartId)) {
626
+ return /* @__PURE__ */ jsx("div", { className, "data-cimplify-checkout": "", children: /* @__PURE__ */ jsx("p", { "data-cimplify-error": "", style: { fontSize: "14px", color: "#b91c1c" }, children: errorMessage || "Unable to initialize checkout. Please refresh and try again." }) });
627
+ }
453
628
  return /* @__PURE__ */ jsxs("div", { className, "data-cimplify-checkout": "", children: [
454
- /* @__PURE__ */ jsx("div", { "data-cimplify-section": "auth", children: /* @__PURE__ */ jsx("div", { ref: authMountRef }) }),
629
+ /* @__PURE__ */ jsx("div", { "data-cimplify-section": "auth", children: /* @__PURE__ */ jsx("div", { ref: isDemoCheckout ? void 0 : authMountRef }) }),
455
630
  /* @__PURE__ */ jsx("div", { "data-cimplify-section": "order-type", style: { marginTop: "12px" }, children: /* @__PURE__ */ jsx(
456
631
  "div",
457
632
  {
@@ -485,10 +660,10 @@ function CimplifyCheckout({
485
660
  {
486
661
  "data-cimplify-section": "address",
487
662
  style: { marginTop: "12px", display: orderType === "delivery" ? "block" : "none" },
488
- children: /* @__PURE__ */ jsx("div", { ref: addressMountRef })
663
+ children: /* @__PURE__ */ jsx("div", { ref: isDemoCheckout ? void 0 : addressMountRef })
489
664
  }
490
665
  ),
491
- /* @__PURE__ */ jsx("div", { "data-cimplify-section": "payment", style: { marginTop: "12px" }, children: /* @__PURE__ */ jsx("div", { ref: paymentMountRef }) }),
666
+ /* @__PURE__ */ jsx("div", { "data-cimplify-section": "payment", style: { marginTop: "12px" }, children: /* @__PURE__ */ jsx("div", { ref: isDemoCheckout ? void 0 : paymentMountRef }) }),
492
667
  /* @__PURE__ */ jsx("div", { style: { marginTop: "12px" }, children: /* @__PURE__ */ jsx(
493
668
  "button",
494
669
  {
@@ -507,34 +682,3234 @@ function CimplifyCheckout({
507
682
  children: isSubmitting ? "Processing..." : "Complete Order"
508
683
  }
509
684
  ) }),
510
- status && /* @__PURE__ */ jsx("p", { "data-cimplify-status": "", style: { marginTop: "10px", fontSize: "14px", color: "#52525b" }, children: statusToLabel(status) }),
685
+ status && /* @__PURE__ */ jsx("p", { "data-cimplify-status": "", style: { marginTop: "10px", fontSize: "14px", color: "#52525b" }, children: statusText || statusToLabel(status) }),
511
686
  errorMessage && /* @__PURE__ */ jsx("p", { "data-cimplify-error": "", style: { marginTop: "8px", fontSize: "14px", color: "#b91c1c" }, children: errorMessage })
512
687
  ] });
513
688
  }
514
- var ElementsContext = createContext({
515
- elements: null,
516
- isReady: false
517
- });
518
- function useElements() {
519
- return useContext(ElementsContext).elements;
689
+
690
+ // src/types/common.ts
691
+ var ErrorCode = {
692
+ // General
693
+ UNKNOWN_ERROR: "UNKNOWN_ERROR",
694
+ NETWORK_ERROR: "NETWORK_ERROR",
695
+ TIMEOUT: "TIMEOUT",
696
+ NOT_FOUND: "NOT_FOUND"};
697
+ var CimplifyError = class extends Error {
698
+ constructor(code, message, retryable = false) {
699
+ super(message);
700
+ this.code = code;
701
+ this.retryable = retryable;
702
+ this.name = "CimplifyError";
703
+ }
704
+ /** User-friendly message safe to display */
705
+ get userMessage() {
706
+ return this.message;
707
+ }
708
+ };
709
+
710
+ // src/types/result.ts
711
+ function ok(value) {
712
+ return { ok: true, value };
520
713
  }
521
- function useElementsReady() {
522
- return useContext(ElementsContext).isReady;
714
+ function err(error) {
715
+ return { ok: false, error };
523
716
  }
524
- function ElementsProvider({
525
- client,
526
- businessId,
527
- options,
528
- children
529
- }) {
530
- const [elements, setElements] = useState(null);
531
- const [isReady, setIsReady] = useState(false);
532
- useEffect(() => {
533
- const instance = client.elements(businessId, options);
534
- setElements(instance);
535
- setIsReady(true);
536
- return () => instance.destroy();
537
- }, [client, businessId, options]);
717
+
718
+ // src/catalogue.ts
719
+ function toCimplifyError(error) {
720
+ if (error instanceof CimplifyError) return error;
721
+ if (error instanceof Error) {
722
+ return new CimplifyError("UNKNOWN_ERROR", error.message, false);
723
+ }
724
+ return new CimplifyError("UNKNOWN_ERROR", String(error), false);
725
+ }
726
+ async function safe(promise) {
727
+ try {
728
+ return ok(await promise);
729
+ } catch (error) {
730
+ return err(toCimplifyError(error));
731
+ }
732
+ }
733
+ function isRecord(value) {
734
+ return typeof value === "object" && value !== null;
735
+ }
736
+ function readFinalPrice(value) {
737
+ if (!isRecord(value)) return void 0;
738
+ const finalPrice = value.final_price;
739
+ if (typeof finalPrice === "string" || typeof finalPrice === "number") {
740
+ return finalPrice;
741
+ }
742
+ return void 0;
743
+ }
744
+ function normalizeCatalogueProductPayload(product) {
745
+ const normalized = { ...product };
746
+ const defaultPrice = normalized["default_price"];
747
+ if (defaultPrice === void 0 || defaultPrice === null || defaultPrice === "") {
748
+ 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);
749
+ normalized["default_price"] = derivedDefaultPrice ?? "0";
750
+ }
751
+ const variants = normalized["variants"];
752
+ if (Array.isArray(variants)) {
753
+ normalized["variants"] = variants.map((variant) => {
754
+ if (!isRecord(variant)) return variant;
755
+ const normalizedVariant = { ...variant };
756
+ const variantAdjustment = normalizedVariant["price_adjustment"];
757
+ if (variantAdjustment === void 0 || variantAdjustment === null || variantAdjustment === "") {
758
+ normalizedVariant["price_adjustment"] = readFinalPrice(normalizedVariant["price_info"]) ?? "0";
759
+ }
760
+ return normalizedVariant;
761
+ });
762
+ }
763
+ const addOns = normalized["add_ons"];
764
+ if (Array.isArray(addOns)) {
765
+ normalized["add_ons"] = addOns.map((addOn) => {
766
+ if (!isRecord(addOn)) return addOn;
767
+ const normalizedAddOn = { ...addOn };
768
+ const options = normalizedAddOn["options"];
769
+ if (!Array.isArray(options)) return normalizedAddOn;
770
+ normalizedAddOn["options"] = options.map((option) => {
771
+ if (!isRecord(option)) return option;
772
+ const normalizedOption = { ...option };
773
+ const optionPrice = normalizedOption["default_price"];
774
+ if (optionPrice === void 0 || optionPrice === null || optionPrice === "") {
775
+ normalizedOption["default_price"] = readFinalPrice(normalizedOption["default_price_info"]) || readFinalPrice(normalizedOption["price_info"]) || "0";
776
+ }
777
+ return normalizedOption;
778
+ });
779
+ return normalizedAddOn;
780
+ });
781
+ }
782
+ return normalized;
783
+ }
784
+ function findProductBySlug(products, slug) {
785
+ return products.find((product) => {
786
+ const value = product["slug"];
787
+ return typeof value === "string" && value === slug;
788
+ });
789
+ }
790
+ var CatalogueQueries = class {
791
+ constructor(client) {
792
+ this.client = client;
793
+ }
794
+ async getProducts(options) {
795
+ let query = "products";
796
+ const filters = [];
797
+ if (options?.category) {
798
+ filters.push(`@.category_id=='${options.category}'`);
799
+ }
800
+ if (options?.featured !== void 0) {
801
+ filters.push(`@.featured==${options.featured}`);
802
+ }
803
+ if (options?.in_stock !== void 0) {
804
+ filters.push(`@.in_stock==${options.in_stock}`);
805
+ }
806
+ if (options?.search) {
807
+ filters.push(`@.name contains '${options.search}'`);
808
+ }
809
+ if (options?.min_price !== void 0) {
810
+ filters.push(`@.price>=${options.min_price}`);
811
+ }
812
+ if (options?.max_price !== void 0) {
813
+ filters.push(`@.price<=${options.max_price}`);
814
+ }
815
+ if (filters.length > 0) {
816
+ query += `[?(${filters.join(" && ")})]`;
817
+ }
818
+ if (options?.sort_by) {
819
+ query += `#sort(${options.sort_by},${options.sort_order || "asc"})`;
820
+ }
821
+ if (options?.limit) {
822
+ query += `#limit(${options.limit})`;
823
+ }
824
+ if (options?.offset) {
825
+ query += `#offset(${options.offset})`;
826
+ }
827
+ const result = await safe(this.client.query(query));
828
+ if (!result.ok) return result;
829
+ return ok(result.value.map((product) => normalizeCatalogueProductPayload(product)));
830
+ }
831
+ async getProduct(id) {
832
+ const result = await safe(this.client.query(`products.${id}`));
833
+ if (!result.ok) return result;
834
+ return ok(normalizeCatalogueProductPayload(result.value));
835
+ }
836
+ async getProductBySlug(slug) {
837
+ const filteredResult = await safe(
838
+ this.client.query(`products[?(@.slug=='${slug}')]`)
839
+ );
840
+ if (!filteredResult.ok) return filteredResult;
841
+ const exactMatch = findProductBySlug(filteredResult.value, slug);
842
+ if (exactMatch) {
843
+ return ok(normalizeCatalogueProductPayload(exactMatch));
844
+ }
845
+ if (filteredResult.value.length === 1) {
846
+ return ok(normalizeCatalogueProductPayload(filteredResult.value[0]));
847
+ }
848
+ const unfilteredResult = await safe(this.client.query("products"));
849
+ if (!unfilteredResult.ok) return unfilteredResult;
850
+ const fallbackMatch = findProductBySlug(unfilteredResult.value, slug);
851
+ if (!fallbackMatch) {
852
+ return err(new CimplifyError("NOT_FOUND", `Product not found: ${slug}`, false));
853
+ }
854
+ return ok(normalizeCatalogueProductPayload(fallbackMatch));
855
+ }
856
+ async getVariants(productId) {
857
+ return safe(this.client.query(`products.${productId}.variants`));
858
+ }
859
+ async getVariantAxes(productId) {
860
+ return safe(this.client.query(`products.${productId}.variant_axes`));
861
+ }
862
+ /**
863
+ * Find a variant by axis selections (e.g., { "Size": "Large", "Color": "Red" })
864
+ * Returns the matching variant or null if no match found.
865
+ */
866
+ async getVariantByAxisSelections(productId, selections) {
867
+ return safe(
868
+ this.client.query(`products.${productId}.variant`, {
869
+ axis_selections: selections
870
+ })
871
+ );
872
+ }
873
+ /**
874
+ * Get a specific variant by its ID
875
+ */
876
+ async getVariantById(productId, variantId) {
877
+ return safe(this.client.query(`products.${productId}.variant.${variantId}`));
878
+ }
879
+ async getAddOns(productId) {
880
+ return safe(this.client.query(`products.${productId}.add_ons`));
881
+ }
882
+ async getCategories() {
883
+ return safe(this.client.query("categories"));
884
+ }
885
+ async getCategory(id) {
886
+ return safe(this.client.query(`categories.${id}`));
887
+ }
888
+ async getCategoryBySlug(slug) {
889
+ const result = await safe(
890
+ this.client.query(`categories[?(@.slug=='${slug}')]`)
891
+ );
892
+ if (!result.ok) return result;
893
+ if (!result.value.length) {
894
+ return err(new CimplifyError("NOT_FOUND", `Category not found: ${slug}`, false));
895
+ }
896
+ return ok(result.value[0]);
897
+ }
898
+ async getCategoryProducts(categoryId) {
899
+ return safe(this.client.query(`products[?(@.category_id=='${categoryId}')]`));
900
+ }
901
+ async getCollections() {
902
+ return safe(this.client.query("collections"));
903
+ }
904
+ async getCollection(id) {
905
+ return safe(this.client.query(`collections.${id}`));
906
+ }
907
+ async getCollectionBySlug(slug) {
908
+ const result = await safe(
909
+ this.client.query(`collections[?(@.slug=='${slug}')]`)
910
+ );
911
+ if (!result.ok) return result;
912
+ if (!result.value.length) {
913
+ return err(new CimplifyError("NOT_FOUND", `Collection not found: ${slug}`, false));
914
+ }
915
+ return ok(result.value[0]);
916
+ }
917
+ async getCollectionProducts(collectionId) {
918
+ return safe(this.client.query(`collections.${collectionId}.products`));
919
+ }
920
+ async searchCollections(query, limit = 20) {
921
+ return safe(
922
+ this.client.query(`collections[?(@.name contains '${query}')]#limit(${limit})`)
923
+ );
924
+ }
925
+ async getBundles() {
926
+ return safe(this.client.query("bundles"));
927
+ }
928
+ async getBundle(id) {
929
+ return safe(this.client.query(`bundles.${id}`));
930
+ }
931
+ async getBundleBySlug(slug) {
932
+ const result = await safe(
933
+ this.client.query(`bundles[?(@.slug=='${slug}')]`)
934
+ );
935
+ if (!result.ok) return result;
936
+ if (!result.value.length) {
937
+ return err(new CimplifyError("NOT_FOUND", `Bundle not found: ${slug}`, false));
938
+ }
939
+ return ok(result.value[0]);
940
+ }
941
+ async searchBundles(query, limit = 20) {
942
+ return safe(
943
+ this.client.query(`bundles[?(@.name contains '${query}')]#limit(${limit})`)
944
+ );
945
+ }
946
+ async getComposites(options) {
947
+ let query = "composites";
948
+ if (options?.limit) {
949
+ query += `#limit(${options.limit})`;
950
+ }
951
+ return safe(this.client.query(query));
952
+ }
953
+ async getComposite(id) {
954
+ return safe(this.client.query(`composites.${id}`));
955
+ }
956
+ async getCompositeByProductId(productId) {
957
+ return safe(this.client.query(`composites.by_product.${productId}`));
958
+ }
959
+ async calculateCompositePrice(compositeId, selections, locationId) {
960
+ return safe(
961
+ this.client.call("composite.calculatePrice", {
962
+ composite_id: compositeId,
963
+ selections,
964
+ location_id: locationId
965
+ })
966
+ );
967
+ }
968
+ async fetchQuote(input) {
969
+ return safe(this.client.call("catalogue.createQuote", input));
970
+ }
971
+ async getQuote(quoteId) {
972
+ return safe(
973
+ this.client.call("catalogue.getQuote", {
974
+ quote_id: quoteId
975
+ })
976
+ );
977
+ }
978
+ async refreshQuote(input) {
979
+ return safe(this.client.call("catalogue.refreshQuote", input));
980
+ }
981
+ async search(query, options) {
982
+ const limit = options?.limit ?? 20;
983
+ let searchQuery = `products[?(@.name contains '${query}')]`;
984
+ if (options?.category) {
985
+ searchQuery = `products[?(@.name contains '${query}' && @.category_id=='${options.category}')]`;
986
+ }
987
+ searchQuery += `#limit(${limit})`;
988
+ return safe(this.client.query(searchQuery));
989
+ }
990
+ async searchProducts(query, options) {
991
+ return safe(
992
+ this.client.call("catalogue.search", {
993
+ query,
994
+ limit: options?.limit ?? 20,
995
+ category: options?.category
996
+ })
997
+ );
998
+ }
999
+ async getMenu(options) {
1000
+ let query = "menu";
1001
+ if (options?.category) {
1002
+ query = `menu[?(@.category=='${options.category}')]`;
1003
+ }
1004
+ if (options?.limit) {
1005
+ query += `#limit(${options.limit})`;
1006
+ }
1007
+ return safe(this.client.query(query));
1008
+ }
1009
+ async getMenuCategory(categoryId) {
1010
+ return safe(this.client.query(`menu.category.${categoryId}`));
1011
+ }
1012
+ async getMenuItem(itemId) {
1013
+ return safe(this.client.query(`menu.${itemId}`));
1014
+ }
1015
+ };
1016
+
1017
+ // src/cart.ts
1018
+ function toCimplifyError2(error) {
1019
+ if (error instanceof CimplifyError) return error;
1020
+ if (error instanceof Error) {
1021
+ return new CimplifyError("UNKNOWN_ERROR", error.message, false);
1022
+ }
1023
+ return new CimplifyError("UNKNOWN_ERROR", String(error), false);
1024
+ }
1025
+ async function safe2(promise) {
1026
+ try {
1027
+ return ok(await promise);
1028
+ } catch (error) {
1029
+ return err(toCimplifyError2(error));
1030
+ }
1031
+ }
1032
+ function isUICartResponse(value) {
1033
+ return "cart" in value;
1034
+ }
1035
+ function unwrapEnrichedCart(value) {
1036
+ return isUICartResponse(value) ? value.cart : value;
1037
+ }
1038
+ var CartOperations = class {
1039
+ constructor(client) {
1040
+ this.client = client;
1041
+ }
1042
+ async get() {
1043
+ const result = await safe2(this.client.query("cart#enriched"));
1044
+ if (!result.ok) return result;
1045
+ return ok(unwrapEnrichedCart(result.value));
1046
+ }
1047
+ async getRaw() {
1048
+ return safe2(this.client.query("cart"));
1049
+ }
1050
+ async getItems() {
1051
+ return safe2(this.client.query("cart_items"));
1052
+ }
1053
+ async getCount() {
1054
+ return safe2(this.client.query("cart#count"));
1055
+ }
1056
+ async getTotal() {
1057
+ return safe2(this.client.query("cart#total"));
1058
+ }
1059
+ async getSummary() {
1060
+ const cartResult = await this.get();
1061
+ if (!cartResult.ok) return cartResult;
1062
+ const cart = cartResult.value;
1063
+ return ok({
1064
+ item_count: cart.items.length,
1065
+ total_items: cart.items.reduce((sum, item) => sum + item.quantity, 0),
1066
+ subtotal: cart.pricing.subtotal,
1067
+ discount_amount: cart.pricing.total_discounts,
1068
+ tax_amount: cart.pricing.tax_amount,
1069
+ total: cart.pricing.total_price,
1070
+ currency: cart.pricing.currency
1071
+ });
1072
+ }
1073
+ async addItem(input) {
1074
+ return safe2(this.client.call("cart.addItem", input));
1075
+ }
1076
+ async updateItem(cartItemId, updates) {
1077
+ return safe2(
1078
+ this.client.call("cart.updateItem", {
1079
+ cart_item_id: cartItemId,
1080
+ ...updates
1081
+ })
1082
+ );
1083
+ }
1084
+ async updateQuantity(cartItemId, quantity) {
1085
+ return safe2(
1086
+ this.client.call("cart.updateItemQuantity", {
1087
+ cart_item_id: cartItemId,
1088
+ quantity
1089
+ })
1090
+ );
1091
+ }
1092
+ async removeItem(cartItemId) {
1093
+ return safe2(
1094
+ this.client.call("cart.removeItem", {
1095
+ cart_item_id: cartItemId
1096
+ })
1097
+ );
1098
+ }
1099
+ async clear() {
1100
+ return safe2(this.client.call("cart.clearCart"));
1101
+ }
1102
+ async applyCoupon(code) {
1103
+ return safe2(
1104
+ this.client.call("cart.applyCoupon", {
1105
+ coupon_code: code
1106
+ })
1107
+ );
1108
+ }
1109
+ async removeCoupon() {
1110
+ return safe2(this.client.call("cart.removeCoupon"));
1111
+ }
1112
+ async isEmpty() {
1113
+ const countResult = await this.getCount();
1114
+ if (!countResult.ok) return countResult;
1115
+ return ok(countResult.value === 0);
1116
+ }
1117
+ async hasItem(productId, variantId) {
1118
+ const itemsResult = await this.getItems();
1119
+ if (!itemsResult.ok) return itemsResult;
1120
+ const found = itemsResult.value.some((item) => {
1121
+ const matchesProduct = item.item_id === productId;
1122
+ if (!variantId) return matchesProduct;
1123
+ const config = item.configuration;
1124
+ if ("variant" in config && config.variant) {
1125
+ return matchesProduct && config.variant.variant_id === variantId;
1126
+ }
1127
+ return matchesProduct;
1128
+ });
1129
+ return ok(found);
1130
+ }
1131
+ async findItem(productId, variantId) {
1132
+ const itemsResult = await this.getItems();
1133
+ if (!itemsResult.ok) return itemsResult;
1134
+ const found = itemsResult.value.find((item) => {
1135
+ const matchesProduct = item.item_id === productId;
1136
+ if (!variantId) return matchesProduct;
1137
+ const config = item.configuration;
1138
+ if ("variant" in config && config.variant) {
1139
+ return matchesProduct && config.variant.variant_id === variantId;
1140
+ }
1141
+ return matchesProduct;
1142
+ });
1143
+ return ok(found);
1144
+ }
1145
+ };
1146
+
1147
+ // src/constants.ts
1148
+ var LINK_QUERY = {
1149
+ DATA: "link.data",
1150
+ ADDRESSES: "link.addresses",
1151
+ MOBILE_MONEY: "link.mobile_money",
1152
+ PREFERENCES: "link.preferences"};
1153
+ var LINK_MUTATION = {
1154
+ CHECK_STATUS: "link.check_status",
1155
+ ENROLL: "link.enroll",
1156
+ ENROLL_AND_LINK_ORDER: "link.enroll_and_link_order",
1157
+ UPDATE_PREFERENCES: "link.update_preferences",
1158
+ CREATE_ADDRESS: "link.create_address",
1159
+ UPDATE_ADDRESS: "link.update_address",
1160
+ DELETE_ADDRESS: "link.delete_address",
1161
+ SET_DEFAULT_ADDRESS: "link.set_default_address",
1162
+ TRACK_ADDRESS_USAGE: "link.track_address_usage",
1163
+ CREATE_MOBILE_MONEY: "link.create_mobile_money",
1164
+ DELETE_MOBILE_MONEY: "link.delete_mobile_money",
1165
+ SET_DEFAULT_MOBILE_MONEY: "link.set_default_mobile_money",
1166
+ TRACK_MOBILE_MONEY_USAGE: "link.track_mobile_money_usage",
1167
+ VERIFY_MOBILE_MONEY: "link.verify_mobile_money"};
1168
+ var AUTH_MUTATION = {
1169
+ REQUEST_OTP: "auth.request_otp",
1170
+ VERIFY_OTP: "auth.verify_otp"
1171
+ };
1172
+ var CHECKOUT_MUTATION = {
1173
+ PROCESS: "checkout.process"
1174
+ };
1175
+ var PAYMENT_MUTATION = {
1176
+ SUBMIT_AUTHORIZATION: "payment.submit_authorization",
1177
+ CHECK_STATUS: "order.poll_payment_status"
1178
+ };
1179
+ var ORDER_MUTATION = {
1180
+ UPDATE_CUSTOMER: "order.update_order_customer"
1181
+ };
1182
+
1183
+ // src/utils/payment.ts
1184
+ var PAYMENT_SUCCESS_STATUSES = /* @__PURE__ */ new Set([
1185
+ "success",
1186
+ "succeeded",
1187
+ "paid",
1188
+ "captured",
1189
+ "completed",
1190
+ "authorized"
1191
+ ]);
1192
+ var PAYMENT_FAILURE_STATUSES = /* @__PURE__ */ new Set([
1193
+ "failed",
1194
+ "declined",
1195
+ "cancelled",
1196
+ "voided",
1197
+ "error"
1198
+ ]);
1199
+ var PAYMENT_REQUIRES_ACTION_STATUSES = /* @__PURE__ */ new Set([
1200
+ "requires_action",
1201
+ "requires_payment_method",
1202
+ "requires_capture"
1203
+ ]);
1204
+ var PAYMENT_STATUS_ALIAS_MAP = {
1205
+ ok: "success",
1206
+ done: "success",
1207
+ paid: "paid",
1208
+ paid_in_full: "paid",
1209
+ paid_successfully: "paid",
1210
+ succeeded: "success",
1211
+ captured: "captured",
1212
+ completed: "completed",
1213
+ pending_confirmation: "pending_confirmation",
1214
+ requires_authorization: "requires_action",
1215
+ requires_action: "requires_action",
1216
+ requires_payment_method: "requires_payment_method",
1217
+ requires_capture: "requires_capture",
1218
+ partially_paid: "partially_paid",
1219
+ partially_refunded: "partially_refunded",
1220
+ card_declined: "declined",
1221
+ canceled: "cancelled",
1222
+ authorized: "authorized",
1223
+ cancelled: "cancelled",
1224
+ unresolved: "pending"
1225
+ };
1226
+ var KNOWN_PAYMENT_STATUSES = /* @__PURE__ */ new Set([
1227
+ "pending",
1228
+ "processing",
1229
+ "created",
1230
+ "pending_confirmation",
1231
+ "success",
1232
+ "succeeded",
1233
+ "failed",
1234
+ "declined",
1235
+ "authorized",
1236
+ "refunded",
1237
+ "partially_refunded",
1238
+ "partially_paid",
1239
+ "paid",
1240
+ "unpaid",
1241
+ "requires_action",
1242
+ "requires_payment_method",
1243
+ "requires_capture",
1244
+ "captured",
1245
+ "cancelled",
1246
+ "completed",
1247
+ "voided",
1248
+ "error",
1249
+ "unknown"
1250
+ ]);
1251
+ function normalizeStatusToken(status) {
1252
+ return status?.trim().toLowerCase().replace(/[\s-]+/g, "_") ?? "";
1253
+ }
1254
+ function normalizePaymentStatusValue(status) {
1255
+ const normalized = normalizeStatusToken(status);
1256
+ if (Object.prototype.hasOwnProperty.call(PAYMENT_STATUS_ALIAS_MAP, normalized)) {
1257
+ return PAYMENT_STATUS_ALIAS_MAP[normalized];
1258
+ }
1259
+ return KNOWN_PAYMENT_STATUSES.has(normalized) ? normalized : "unknown";
1260
+ }
1261
+ function isPaymentStatusSuccess(status) {
1262
+ const normalizedStatus = normalizePaymentStatusValue(status);
1263
+ return PAYMENT_SUCCESS_STATUSES.has(normalizedStatus);
1264
+ }
1265
+ function isPaymentStatusFailure(status) {
1266
+ const normalizedStatus = normalizePaymentStatusValue(status);
1267
+ return PAYMENT_FAILURE_STATUSES.has(normalizedStatus);
1268
+ }
1269
+ function isPaymentStatusRequiresAction(status) {
1270
+ const normalizedStatus = normalizePaymentStatusValue(status);
1271
+ return PAYMENT_REQUIRES_ACTION_STATUSES.has(normalizedStatus);
1272
+ }
1273
+ function normalizeStatusResponse(response) {
1274
+ if (!response || typeof response !== "object") {
1275
+ return {
1276
+ status: "pending",
1277
+ paid: false,
1278
+ message: "No status available"
1279
+ };
1280
+ }
1281
+ const res = response;
1282
+ const normalizedStatus = normalizePaymentStatusValue(res.status ?? void 0);
1283
+ const paidValue = res.paid === true;
1284
+ const derivedPaid = paidValue || [
1285
+ "success",
1286
+ "succeeded",
1287
+ "paid",
1288
+ "captured",
1289
+ "authorized",
1290
+ "completed"
1291
+ ].includes(normalizedStatus);
1292
+ return {
1293
+ status: normalizedStatus,
1294
+ paid: derivedPaid,
1295
+ amount: res.amount,
1296
+ currency: res.currency,
1297
+ reference: res.reference,
1298
+ message: res.message || ""
1299
+ };
1300
+ }
1301
+
1302
+ // src/utils/paystack.ts
1303
+ async function openPaystackPopup(options, signal) {
1304
+ if (typeof window === "undefined") {
1305
+ return { success: false, error: "PROVIDER_UNAVAILABLE" };
1306
+ }
1307
+ let PaystackPop;
1308
+ try {
1309
+ const imported = await import('@paystack/inline-js');
1310
+ PaystackPop = imported.default;
1311
+ } catch {
1312
+ return { success: false, error: "PROVIDER_UNAVAILABLE" };
1313
+ }
1314
+ return new Promise((resolve) => {
1315
+ let settled = false;
1316
+ const resolveOnce = (result) => {
1317
+ if (settled) {
1318
+ return;
1319
+ }
1320
+ settled = true;
1321
+ if (signal) {
1322
+ signal.removeEventListener("abort", onAbort);
1323
+ }
1324
+ resolve(result);
1325
+ };
1326
+ const onAbort = () => {
1327
+ resolveOnce({ success: false, error: "CANCELLED" });
1328
+ };
1329
+ if (signal?.aborted) {
1330
+ resolveOnce({ success: false, error: "CANCELLED" });
1331
+ return;
1332
+ }
1333
+ if (signal) {
1334
+ signal.addEventListener("abort", onAbort, { once: true });
1335
+ }
1336
+ try {
1337
+ const popup = new PaystackPop();
1338
+ popup.newTransaction({
1339
+ key: options.key,
1340
+ email: options.email,
1341
+ amount: options.amount,
1342
+ currency: options.currency,
1343
+ reference: options.reference,
1344
+ accessCode: options.accessCode,
1345
+ onSuccess: (transaction) => {
1346
+ resolveOnce({
1347
+ success: true,
1348
+ reference: transaction.reference ?? options.reference
1349
+ });
1350
+ },
1351
+ onCancel: () => {
1352
+ resolveOnce({ success: false, error: "PAYMENT_CANCELLED" });
1353
+ },
1354
+ onError: (error) => {
1355
+ resolveOnce({
1356
+ success: false,
1357
+ error: error?.message || "PAYMENT_FAILED"
1358
+ });
1359
+ }
1360
+ });
1361
+ } catch {
1362
+ resolveOnce({ success: false, error: "POPUP_BLOCKED" });
1363
+ }
1364
+ });
1365
+ }
1366
+
1367
+ // src/utils/checkout-resolver.ts
1368
+ var DEFAULT_POLL_INTERVAL_MS = 3e3;
1369
+ var DEFAULT_MAX_POLL_ATTEMPTS = 60;
1370
+ var MAX_CONSECUTIVE_NETWORK_ERRORS = 5;
1371
+ var CARD_PROVIDER_PAYSTACK = "paystack";
1372
+ function normalizeCardPopupError(error) {
1373
+ if (!error || error === "PAYMENT_CANCELLED" || error === "CANCELLED") {
1374
+ return "PAYMENT_CANCELLED";
1375
+ }
1376
+ if (error === "PROVIDER_UNAVAILABLE") {
1377
+ return "PROVIDER_UNAVAILABLE";
1378
+ }
1379
+ if (error === "POPUP_BLOCKED") {
1380
+ return "POPUP_BLOCKED";
1381
+ }
1382
+ return "PAYMENT_FAILED";
1383
+ }
1384
+ function normalizeCardProvider(value) {
1385
+ const normalized = value?.trim().toLowerCase();
1386
+ return normalized && normalized.length > 0 ? normalized : CARD_PROVIDER_PAYSTACK;
1387
+ }
1388
+ async function openCardPopup(provider, checkoutResult, email, currency, signal) {
1389
+ if (typeof window === "undefined") {
1390
+ return { success: false, error: "PROVIDER_UNAVAILABLE" };
1391
+ }
1392
+ if (provider === CARD_PROVIDER_PAYSTACK) {
1393
+ return openPaystackPopup(
1394
+ {
1395
+ key: checkoutResult.public_key || "",
1396
+ email,
1397
+ accessCode: checkoutResult.client_secret,
1398
+ reference: checkoutResult.payment_reference || checkoutResult.client_secret,
1399
+ currency
1400
+ },
1401
+ signal
1402
+ );
1403
+ }
1404
+ return { success: false, error: "PROVIDER_UNAVAILABLE" };
1405
+ }
1406
+ function normalizeAuthorizationType(value) {
1407
+ return value === "otp" || value === "pin" ? value : void 0;
1408
+ }
1409
+ function formatMoney2(value) {
1410
+ if (typeof value === "number" && Number.isFinite(value)) {
1411
+ return value.toFixed(2);
1412
+ }
1413
+ if (typeof value === "string" && value.trim().length > 0) {
1414
+ return value;
1415
+ }
1416
+ return "0.00";
1417
+ }
1418
+ function createAbortError() {
1419
+ const error = new Error("CANCELLED");
1420
+ error.name = "AbortError";
1421
+ return error;
1422
+ }
1423
+ function isAbortError(error) {
1424
+ if (error instanceof DOMException && error.name === "AbortError") {
1425
+ return true;
1426
+ }
1427
+ return error instanceof Error && (error.name === "AbortError" || error.message === "CANCELLED");
1428
+ }
1429
+ var CheckoutResolver = class {
1430
+ constructor(options) {
1431
+ this.client = options.client;
1432
+ this.checkoutData = options.checkoutData;
1433
+ this.pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
1434
+ this.maxPollAttempts = options.maxPollAttempts ?? DEFAULT_MAX_POLL_ATTEMPTS;
1435
+ this.onStatusChange = options.onStatusChange;
1436
+ this.onAuthorizationRequired = options.onAuthorizationRequired;
1437
+ this.signal = options.signal;
1438
+ this.returnUrl = options.returnUrl;
1439
+ this.enrollInLink = options.enrollInLink !== false;
1440
+ this.businessId = options.businessId;
1441
+ this.addressData = options.addressData;
1442
+ this.paymentData = options.paymentData;
1443
+ this.orderType = options.orderType;
1444
+ this.cartTotal = options.cartTotal;
1445
+ this.cartCurrency = options.cartCurrency;
1446
+ this.allowPopups = options.allowPopups ?? typeof window !== "undefined";
1447
+ }
1448
+ async resolve(checkoutResult) {
1449
+ try {
1450
+ this.ensureNotAborted();
1451
+ if (!checkoutResult.order_id) {
1452
+ return this.fail("CHECKOUT_FAILED", "Checkout did not return an order ID.", false);
1453
+ }
1454
+ let latestCheckoutResult = checkoutResult;
1455
+ let authorizationType = normalizeAuthorizationType(checkoutResult.authorization_type);
1456
+ let paymentReference = checkoutResult.payment_reference;
1457
+ if (this.isSuccessfulStatus(checkoutResult.payment_status)) {
1458
+ return this.finalizeSuccess(checkoutResult);
1459
+ }
1460
+ if (checkoutResult.client_secret && checkoutResult.public_key) {
1461
+ const provider = normalizeCardProvider(checkoutResult.provider);
1462
+ this.emit("awaiting_authorization", {
1463
+ display_text: "Complete payment in the card authorization popup.",
1464
+ order_id: checkoutResult.order_id,
1465
+ order_number: checkoutResult.order_number
1466
+ });
1467
+ if (!this.allowPopups) {
1468
+ return this.fail(
1469
+ "PROVIDER_UNAVAILABLE",
1470
+ "Card payment popup is unavailable in this environment.",
1471
+ false
1472
+ );
1473
+ }
1474
+ const popupResult = await openCardPopup(
1475
+ provider,
1476
+ checkoutResult,
1477
+ this.checkoutData.customer.email || "customer@cimplify.io",
1478
+ this.getOrderCurrency(checkoutResult),
1479
+ this.signal
1480
+ );
1481
+ if (!popupResult.success) {
1482
+ const popupError = normalizeCardPopupError(popupResult.error);
1483
+ if (popupError === "POPUP_BLOCKED") {
1484
+ return this.fail(
1485
+ "POPUP_BLOCKED",
1486
+ "Unable to open card payment popup. Please allow popups and try again.",
1487
+ true
1488
+ );
1489
+ }
1490
+ if (popupError === "PROVIDER_UNAVAILABLE") {
1491
+ return this.fail(
1492
+ "PROVIDER_UNAVAILABLE",
1493
+ "Card payment provider is unavailable.",
1494
+ false
1495
+ );
1496
+ }
1497
+ return this.fail(
1498
+ "PAYMENT_CANCELLED",
1499
+ "Card payment was cancelled before completion.",
1500
+ true
1501
+ );
1502
+ }
1503
+ paymentReference = popupResult.reference || paymentReference;
1504
+ }
1505
+ if (checkoutResult.authorization_url) {
1506
+ if (typeof window !== "undefined" && this.returnUrl) {
1507
+ window.location.assign(checkoutResult.authorization_url);
1508
+ return this.fail(
1509
+ "REDIRECT_REQUIRED",
1510
+ "Redirecting to complete payment authorization.",
1511
+ true
1512
+ );
1513
+ }
1514
+ if (typeof window !== "undefined") {
1515
+ const popup = window.open(
1516
+ checkoutResult.authorization_url,
1517
+ "cimplify-auth",
1518
+ "width=520,height=760,noopener,noreferrer"
1519
+ );
1520
+ if (!popup) {
1521
+ return this.fail(
1522
+ "POPUP_BLOCKED",
1523
+ "Authorization popup was blocked. Please allow popups and retry.",
1524
+ true
1525
+ );
1526
+ }
1527
+ }
1528
+ }
1529
+ if (checkoutResult.requires_authorization || isPaymentStatusRequiresAction(checkoutResult.payment_status)) {
1530
+ const authorization = await this.handleAuthorization({
1531
+ authorizationType,
1532
+ paymentReference,
1533
+ displayText: checkoutResult.display_text,
1534
+ provider: checkoutResult.provider
1535
+ });
1536
+ if (!authorization.ok) {
1537
+ return authorization.result;
1538
+ }
1539
+ if (authorization.value) {
1540
+ latestCheckoutResult = authorization.value;
1541
+ paymentReference = authorization.value.payment_reference || paymentReference;
1542
+ authorizationType = normalizeAuthorizationType(authorization.value.authorization_type) || authorizationType;
1543
+ if (this.isSuccessfulStatus(authorization.value.payment_status)) {
1544
+ return this.finalizeSuccess(authorization.value);
1545
+ }
1546
+ if (this.isFailureStatus(authorization.value.payment_status)) {
1547
+ return this.fail(
1548
+ "AUTHORIZATION_FAILED",
1549
+ authorization.value.display_text || "Payment authorization failed.",
1550
+ false
1551
+ );
1552
+ }
1553
+ }
1554
+ }
1555
+ return this.pollUntilTerminal({
1556
+ orderId: checkoutResult.order_id,
1557
+ latestCheckoutResult,
1558
+ paymentReference,
1559
+ authorizationType
1560
+ });
1561
+ } catch (error) {
1562
+ if (isAbortError(error)) {
1563
+ return this.fail("CANCELLED", "Checkout was cancelled.", true);
1564
+ }
1565
+ const message = error instanceof Error ? error.message : "Checkout failed unexpectedly.";
1566
+ return this.fail("CHECKOUT_FAILED", message, true);
1567
+ }
1568
+ }
1569
+ async pollUntilTerminal(input) {
1570
+ let consecutiveErrors = 0;
1571
+ let latestCheckoutResult = input.latestCheckoutResult;
1572
+ let paymentReference = input.paymentReference;
1573
+ let authorizationType = input.authorizationType;
1574
+ for (let attempt = 0; attempt < this.maxPollAttempts; attempt++) {
1575
+ this.ensureNotAborted();
1576
+ this.emit("polling", {
1577
+ poll_attempt: attempt,
1578
+ max_poll_attempts: this.maxPollAttempts,
1579
+ order_id: input.orderId,
1580
+ order_number: latestCheckoutResult.order_number
1581
+ });
1582
+ const statusResult = await this.client.checkout.pollPaymentStatus(input.orderId);
1583
+ if (!statusResult.ok) {
1584
+ consecutiveErrors += 1;
1585
+ if (consecutiveErrors >= MAX_CONSECUTIVE_NETWORK_ERRORS) {
1586
+ return this.fail(
1587
+ "NETWORK_ERROR",
1588
+ "Unable to confirm payment due to repeated network errors.",
1589
+ true
1590
+ );
1591
+ }
1592
+ await this.wait(this.pollIntervalMs);
1593
+ continue;
1594
+ }
1595
+ consecutiveErrors = 0;
1596
+ if (statusResult.value.reference) {
1597
+ paymentReference = statusResult.value.reference;
1598
+ }
1599
+ const normalized = normalizeStatusResponse(statusResult.value);
1600
+ if (normalized.paid || isPaymentStatusSuccess(normalized.status)) {
1601
+ return this.finalizeSuccess(latestCheckoutResult);
1602
+ }
1603
+ if (isPaymentStatusFailure(normalized.status)) {
1604
+ return this.fail(
1605
+ normalized.status ? normalized.status.toUpperCase() : "PAYMENT_FAILED",
1606
+ normalized.message || "Payment failed during confirmation.",
1607
+ false
1608
+ );
1609
+ }
1610
+ if (isPaymentStatusRequiresAction(normalized.status)) {
1611
+ const authorization = await this.handleAuthorization({
1612
+ authorizationType,
1613
+ paymentReference,
1614
+ displayText: normalized.message || latestCheckoutResult.display_text,
1615
+ provider: latestCheckoutResult.provider
1616
+ });
1617
+ if (!authorization.ok) {
1618
+ return authorization.result;
1619
+ }
1620
+ if (authorization.value) {
1621
+ latestCheckoutResult = authorization.value;
1622
+ paymentReference = authorization.value.payment_reference || paymentReference;
1623
+ authorizationType = normalizeAuthorizationType(authorization.value.authorization_type) || authorizationType;
1624
+ if (this.isSuccessfulStatus(authorization.value.payment_status)) {
1625
+ return this.finalizeSuccess(authorization.value);
1626
+ }
1627
+ if (this.isFailureStatus(authorization.value.payment_status)) {
1628
+ return this.fail(
1629
+ "AUTHORIZATION_FAILED",
1630
+ authorization.value.display_text || "Payment authorization failed.",
1631
+ false
1632
+ );
1633
+ }
1634
+ }
1635
+ }
1636
+ await this.wait(this.pollIntervalMs);
1637
+ }
1638
+ return this.fail(
1639
+ "PAYMENT_TIMEOUT",
1640
+ "Payment confirmation timed out. Please retry checkout.",
1641
+ true
1642
+ );
1643
+ }
1644
+ async handleAuthorization(input) {
1645
+ const authorizationType = input.authorizationType;
1646
+ const paymentReference = input.paymentReference;
1647
+ if (!authorizationType || !paymentReference) {
1648
+ return { ok: true };
1649
+ }
1650
+ this.emit("awaiting_authorization", {
1651
+ authorization_type: authorizationType,
1652
+ display_text: input.displayText,
1653
+ provider: input.provider
1654
+ });
1655
+ let authorizationResult;
1656
+ const submit = async (code) => {
1657
+ this.ensureNotAborted();
1658
+ const trimmedCode = code.trim();
1659
+ if (!trimmedCode) {
1660
+ throw new Error("Authorization code is required.");
1661
+ }
1662
+ const submitResult = await this.client.checkout.submitAuthorization({
1663
+ reference: paymentReference,
1664
+ auth_type: authorizationType,
1665
+ value: trimmedCode
1666
+ });
1667
+ if (!submitResult.ok) {
1668
+ throw new Error(submitResult.error.message || "Authorization failed.");
1669
+ }
1670
+ authorizationResult = submitResult.value;
1671
+ };
1672
+ try {
1673
+ if (this.onAuthorizationRequired) {
1674
+ await this.onAuthorizationRequired(authorizationType, submit);
1675
+ } else {
1676
+ return {
1677
+ ok: false,
1678
+ result: this.fail(
1679
+ "AUTHORIZATION_REQUIRED",
1680
+ "Authorization callback is required in headless checkout mode.",
1681
+ false
1682
+ )
1683
+ };
1684
+ }
1685
+ } catch (error) {
1686
+ if (isAbortError(error)) {
1687
+ return {
1688
+ ok: false,
1689
+ result: this.fail("CANCELLED", "Checkout was cancelled.", true)
1690
+ };
1691
+ }
1692
+ const message = error instanceof Error ? error.message : "Payment authorization failed.";
1693
+ return {
1694
+ ok: false,
1695
+ result: this.fail("AUTHORIZATION_FAILED", message, true)
1696
+ };
1697
+ }
1698
+ return {
1699
+ ok: true,
1700
+ value: authorizationResult
1701
+ };
1702
+ }
1703
+ async finalizeSuccess(checkoutResult) {
1704
+ this.emit("finalizing", {
1705
+ order_id: checkoutResult.order_id,
1706
+ order_number: checkoutResult.order_number
1707
+ });
1708
+ const enrolledInLink = await this.maybeEnrollInLink(checkoutResult.order_id);
1709
+ this.emit("success", {
1710
+ order_id: checkoutResult.order_id,
1711
+ order_number: checkoutResult.order_number
1712
+ });
1713
+ return {
1714
+ success: true,
1715
+ order: {
1716
+ id: checkoutResult.order_id,
1717
+ order_number: checkoutResult.order_number || checkoutResult.order_id,
1718
+ status: checkoutResult.payment_status || "paid",
1719
+ total: this.getOrderTotal(checkoutResult),
1720
+ currency: this.getOrderCurrency(checkoutResult)
1721
+ },
1722
+ enrolled_in_link: enrolledInLink
1723
+ };
1724
+ }
1725
+ async maybeEnrollInLink(orderId) {
1726
+ if (!this.enrollInLink || !orderId) {
1727
+ return false;
1728
+ }
1729
+ let businessId = this.businessId;
1730
+ if (!businessId) {
1731
+ const businessResult = await this.client.business.getInfo();
1732
+ if (!businessResult.ok || !businessResult.value?.id) {
1733
+ return false;
1734
+ }
1735
+ businessId = businessResult.value.id;
1736
+ }
1737
+ const address = this.getEnrollmentAddress();
1738
+ const mobileMoney = this.getEnrollmentMobileMoney();
1739
+ try {
1740
+ const enrollment = await this.client.link.enrollAndLinkOrder({
1741
+ order_id: orderId,
1742
+ business_id: businessId,
1743
+ order_type: this.orderType || this.checkoutData.order_type,
1744
+ address,
1745
+ mobile_money: mobileMoney
1746
+ });
1747
+ return enrollment.ok && enrollment.value.success;
1748
+ } catch {
1749
+ return false;
1750
+ }
1751
+ }
1752
+ getEnrollmentAddress() {
1753
+ const source = this.addressData ?? this.checkoutData.address_info;
1754
+ if (!source?.street_address) {
1755
+ return void 0;
1756
+ }
1757
+ return {
1758
+ label: "Default",
1759
+ street_address: source.street_address,
1760
+ apartment: source.apartment || void 0,
1761
+ city: source.city || "",
1762
+ region: source.region || "",
1763
+ delivery_instructions: source.delivery_instructions || void 0,
1764
+ phone_for_delivery: source.phone_for_delivery || void 0
1765
+ };
1766
+ }
1767
+ getEnrollmentMobileMoney() {
1768
+ if (this.paymentData?.type === "mobile_money" && this.paymentData.phone_number && this.paymentData.provider) {
1769
+ return {
1770
+ phone_number: this.paymentData.phone_number,
1771
+ provider: this.paymentData.provider,
1772
+ label: this.paymentData.label || "Mobile Money"
1773
+ };
1774
+ }
1775
+ if (this.checkoutData.mobile_money_details?.phone_number) {
1776
+ return {
1777
+ phone_number: this.checkoutData.mobile_money_details.phone_number,
1778
+ provider: this.checkoutData.mobile_money_details.provider,
1779
+ label: "Mobile Money"
1780
+ };
1781
+ }
1782
+ return void 0;
1783
+ }
1784
+ getOrderTotal(checkoutResult) {
1785
+ if (checkoutResult.fx?.pay_amount !== void 0) {
1786
+ return formatMoney2(checkoutResult.fx.pay_amount);
1787
+ }
1788
+ if (this.cartTotal !== void 0) {
1789
+ return formatMoney2(this.cartTotal);
1790
+ }
1791
+ return "0.00";
1792
+ }
1793
+ getOrderCurrency(checkoutResult) {
1794
+ if (checkoutResult.fx?.pay_currency) {
1795
+ return checkoutResult.fx.pay_currency;
1796
+ }
1797
+ if (this.cartCurrency) {
1798
+ return this.cartCurrency;
1799
+ }
1800
+ if (this.checkoutData.pay_currency) {
1801
+ return this.checkoutData.pay_currency;
1802
+ }
1803
+ return "GHS";
1804
+ }
1805
+ emit(status, context = {}) {
1806
+ if (!this.onStatusChange) {
1807
+ return;
1808
+ }
1809
+ try {
1810
+ this.onStatusChange(status, context);
1811
+ } catch {
1812
+ }
1813
+ }
1814
+ fail(code, message, recoverable) {
1815
+ this.emit("failed", {
1816
+ display_text: message
1817
+ });
1818
+ return {
1819
+ success: false,
1820
+ error: {
1821
+ code,
1822
+ message,
1823
+ recoverable
1824
+ }
1825
+ };
1826
+ }
1827
+ isSuccessfulStatus(status) {
1828
+ const normalized = normalizeStatusResponse({ status, paid: false });
1829
+ return normalized.paid || isPaymentStatusSuccess(normalized.status);
1830
+ }
1831
+ isFailureStatus(status) {
1832
+ const normalized = normalizeStatusResponse({ status, paid: false });
1833
+ return isPaymentStatusFailure(normalized.status);
1834
+ }
1835
+ ensureNotAborted() {
1836
+ if (this.signal?.aborted) {
1837
+ throw createAbortError();
1838
+ }
1839
+ }
1840
+ wait(ms) {
1841
+ this.ensureNotAborted();
1842
+ return new Promise((resolve, reject) => {
1843
+ const timer = setTimeout(() => {
1844
+ if (this.signal) {
1845
+ this.signal.removeEventListener("abort", onAbort);
1846
+ }
1847
+ resolve();
1848
+ }, ms);
1849
+ const onAbort = () => {
1850
+ clearTimeout(timer);
1851
+ reject(createAbortError());
1852
+ };
1853
+ if (this.signal) {
1854
+ this.signal.addEventListener("abort", onAbort, { once: true });
1855
+ }
1856
+ });
1857
+ }
1858
+ };
1859
+
1860
+ // src/checkout.ts
1861
+ function toCimplifyError3(error) {
1862
+ if (error instanceof CimplifyError) return error;
1863
+ if (error instanceof Error) {
1864
+ return new CimplifyError("UNKNOWN_ERROR", error.message, false);
1865
+ }
1866
+ return new CimplifyError("UNKNOWN_ERROR", String(error), false);
1867
+ }
1868
+ async function safe3(promise) {
1869
+ try {
1870
+ return ok(await promise);
1871
+ } catch (error) {
1872
+ return err(toCimplifyError3(error));
1873
+ }
1874
+ }
1875
+ function toTerminalFailure(code, message, recoverable) {
1876
+ return {
1877
+ success: false,
1878
+ error: {
1879
+ code,
1880
+ message,
1881
+ recoverable
1882
+ }
1883
+ };
1884
+ }
1885
+ function generateIdempotencyKey() {
1886
+ if (typeof crypto !== "undefined" && crypto.randomUUID) {
1887
+ return `idem_${crypto.randomUUID()}`;
1888
+ }
1889
+ const timestamp = Date.now().toString(36);
1890
+ const random = Math.random().toString(36).substring(2, 15);
1891
+ return `idem_${timestamp}_${random}`;
1892
+ }
1893
+ var CheckoutService = class {
1894
+ constructor(client) {
1895
+ this.client = client;
1896
+ }
1897
+ async process(data) {
1898
+ const checkoutData = {
1899
+ ...data,
1900
+ idempotency_key: data.idempotency_key || generateIdempotencyKey()
1901
+ };
1902
+ return safe3(
1903
+ this.client.call(CHECKOUT_MUTATION.PROCESS, {
1904
+ checkout_data: checkoutData
1905
+ })
1906
+ );
1907
+ }
1908
+ async initializePayment(orderId, method) {
1909
+ return safe3(
1910
+ this.client.call("order.initializePayment", {
1911
+ order_id: orderId,
1912
+ payment_method: method
1913
+ })
1914
+ );
1915
+ }
1916
+ async submitAuthorization(input) {
1917
+ return safe3(
1918
+ this.client.call(PAYMENT_MUTATION.SUBMIT_AUTHORIZATION, input)
1919
+ );
1920
+ }
1921
+ async pollPaymentStatus(orderId) {
1922
+ return safe3(
1923
+ this.client.call(PAYMENT_MUTATION.CHECK_STATUS, orderId)
1924
+ );
1925
+ }
1926
+ async updateOrderCustomer(orderId, customer) {
1927
+ return safe3(
1928
+ this.client.call(ORDER_MUTATION.UPDATE_CUSTOMER, {
1929
+ order_id: orderId,
1930
+ ...customer
1931
+ })
1932
+ );
1933
+ }
1934
+ async verifyPayment(orderId) {
1935
+ return safe3(
1936
+ this.client.call("order.verifyPayment", {
1937
+ order_id: orderId
1938
+ })
1939
+ );
1940
+ }
1941
+ async processAndResolve(data) {
1942
+ data.on_status_change?.("preparing", {});
1943
+ if (!data.cart_id) {
1944
+ return ok(
1945
+ toTerminalFailure(
1946
+ "INVALID_CART",
1947
+ "A valid cart is required before checkout can start.",
1948
+ false
1949
+ )
1950
+ );
1951
+ }
1952
+ const cartResult = await this.client.cart.get();
1953
+ if (!cartResult.ok || !cartResult.value?.id) {
1954
+ return ok(
1955
+ toTerminalFailure(
1956
+ "INVALID_CART",
1957
+ "Unable to load cart for checkout.",
1958
+ false
1959
+ )
1960
+ );
1961
+ }
1962
+ const cart = cartResult.value;
1963
+ if (cart.id !== data.cart_id || cart.items.length === 0) {
1964
+ return ok(
1965
+ toTerminalFailure(
1966
+ "INVALID_CART",
1967
+ "Cart is empty or no longer valid. Please refresh and try again.",
1968
+ false
1969
+ )
1970
+ );
1971
+ }
1972
+ const checkoutData = {
1973
+ cart_id: data.cart_id,
1974
+ location_id: data.location_id,
1975
+ customer: data.customer,
1976
+ order_type: data.order_type,
1977
+ address_info: data.address_info,
1978
+ payment_method: data.payment_method,
1979
+ mobile_money_details: data.mobile_money_details,
1980
+ special_instructions: data.special_instructions,
1981
+ link_address_id: data.link_address_id,
1982
+ link_payment_method_id: data.link_payment_method_id,
1983
+ idempotency_key: data.idempotency_key || generateIdempotencyKey(),
1984
+ metadata: data.metadata,
1985
+ pay_currency: data.pay_currency,
1986
+ fx_quote_id: data.fx_quote_id
1987
+ };
1988
+ const baseCurrency = (cart.pricing.currency || checkoutData.pay_currency || "GHS").toUpperCase();
1989
+ const payCurrency = data.pay_currency?.trim().toUpperCase();
1990
+ const cartTotalAmount = Number.parseFloat(cart.pricing.total_price || "0");
1991
+ if (payCurrency && payCurrency !== baseCurrency && !checkoutData.fx_quote_id && Number.isFinite(cartTotalAmount) && cartTotalAmount > 0) {
1992
+ const fxQuoteResult = await this.client.fx.lockQuote({
1993
+ from: baseCurrency,
1994
+ to: payCurrency,
1995
+ amount: cartTotalAmount
1996
+ });
1997
+ if (!fxQuoteResult.ok) {
1998
+ return ok(
1999
+ toTerminalFailure(
2000
+ "FX_QUOTE_FAILED",
2001
+ fxQuoteResult.error.message || "Unable to lock FX quote for checkout.",
2002
+ true
2003
+ )
2004
+ );
2005
+ }
2006
+ checkoutData.pay_currency = payCurrency;
2007
+ checkoutData.fx_quote_id = fxQuoteResult.value.id;
2008
+ }
2009
+ data.on_status_change?.("processing", {});
2010
+ const processResult = await this.process(checkoutData);
2011
+ if (!processResult.ok) {
2012
+ return ok(
2013
+ toTerminalFailure(
2014
+ processResult.error.code || "CHECKOUT_FAILED",
2015
+ processResult.error.message || "Unable to process checkout.",
2016
+ processResult.error.retryable ?? true
2017
+ )
2018
+ );
2019
+ }
2020
+ const resolver = new CheckoutResolver({
2021
+ client: this.client,
2022
+ checkoutData,
2023
+ pollIntervalMs: data.poll_interval_ms,
2024
+ maxPollAttempts: data.max_poll_attempts,
2025
+ onStatusChange: data.on_status_change,
2026
+ onAuthorizationRequired: data.on_authorization_required,
2027
+ signal: data.signal,
2028
+ returnUrl: data.return_url,
2029
+ enrollInLink: data.enroll_in_link,
2030
+ cartTotal: cart.pricing.total_price,
2031
+ cartCurrency: checkoutData.pay_currency || cart.pricing.currency || "GHS",
2032
+ orderType: checkoutData.order_type,
2033
+ allowPopups: data.allow_popups
2034
+ });
2035
+ const resolved = await resolver.resolve(processResult.value);
2036
+ return ok(resolved);
2037
+ }
2038
+ };
2039
+
2040
+ // src/orders.ts
2041
+ function toCimplifyError4(error) {
2042
+ if (error instanceof CimplifyError) return error;
2043
+ if (error instanceof Error) {
2044
+ return new CimplifyError("UNKNOWN_ERROR", error.message, false);
2045
+ }
2046
+ return new CimplifyError("UNKNOWN_ERROR", String(error), false);
2047
+ }
2048
+ async function safe4(promise) {
2049
+ try {
2050
+ return ok(await promise);
2051
+ } catch (error) {
2052
+ return err(toCimplifyError4(error));
2053
+ }
2054
+ }
2055
+ var OrderQueries = class {
2056
+ constructor(client) {
2057
+ this.client = client;
2058
+ }
2059
+ async list(options) {
2060
+ let query = "orders";
2061
+ if (options?.status) {
2062
+ query += `[?(@.status=='${options.status}')]`;
2063
+ }
2064
+ query += "#sort(created_at,desc)";
2065
+ if (options?.limit) {
2066
+ query += `#limit(${options.limit})`;
2067
+ }
2068
+ if (options?.offset) {
2069
+ query += `#offset(${options.offset})`;
2070
+ }
2071
+ return safe4(this.client.query(query));
2072
+ }
2073
+ async get(orderId) {
2074
+ return safe4(this.client.query(`orders.${orderId}`));
2075
+ }
2076
+ async getRecent(limit = 5) {
2077
+ return safe4(this.client.query(`orders#sort(created_at,desc)#limit(${limit})`));
2078
+ }
2079
+ async getByStatus(status) {
2080
+ return safe4(this.client.query(`orders[?(@.status=='${status}')]`));
2081
+ }
2082
+ async cancel(orderId, reason) {
2083
+ return safe4(
2084
+ this.client.call("order.cancelOrder", {
2085
+ order_id: orderId,
2086
+ reason
2087
+ })
2088
+ );
2089
+ }
2090
+ };
2091
+
2092
+ // src/link.ts
2093
+ function toCimplifyError5(error) {
2094
+ if (error instanceof CimplifyError) return error;
2095
+ if (error instanceof Error) {
2096
+ return new CimplifyError("UNKNOWN_ERROR", error.message, false);
2097
+ }
2098
+ return new CimplifyError("UNKNOWN_ERROR", String(error), false);
2099
+ }
2100
+ async function safe5(promise) {
2101
+ try {
2102
+ return ok(await promise);
2103
+ } catch (error) {
2104
+ return err(toCimplifyError5(error));
2105
+ }
2106
+ }
2107
+ var LinkService = class {
2108
+ constructor(client) {
2109
+ this.client = client;
2110
+ }
2111
+ async requestOtp(input) {
2112
+ return safe5(this.client.linkPost("/v1/link/auth/request-otp", input));
2113
+ }
2114
+ async verifyOtp(input) {
2115
+ const result = await safe5(
2116
+ this.client.linkPost("/v1/link/auth/verify-otp", input)
2117
+ );
2118
+ if (result.ok && result.value.session_token) {
2119
+ this.client.setSessionToken(result.value.session_token);
2120
+ }
2121
+ return result;
2122
+ }
2123
+ async logout() {
2124
+ const result = await safe5(this.client.linkPost("/v1/link/auth/logout"));
2125
+ if (result.ok) {
2126
+ this.client.clearSession();
2127
+ }
2128
+ return result;
2129
+ }
2130
+ async checkStatus(contact) {
2131
+ return safe5(
2132
+ this.client.call(LINK_MUTATION.CHECK_STATUS, {
2133
+ contact
2134
+ })
2135
+ );
2136
+ }
2137
+ async getLinkData() {
2138
+ return safe5(this.client.query(LINK_QUERY.DATA));
2139
+ }
2140
+ async getAddresses() {
2141
+ return safe5(this.client.query(LINK_QUERY.ADDRESSES));
2142
+ }
2143
+ async getMobileMoney() {
2144
+ return safe5(this.client.query(LINK_QUERY.MOBILE_MONEY));
2145
+ }
2146
+ async getPreferences() {
2147
+ return safe5(this.client.query(LINK_QUERY.PREFERENCES));
2148
+ }
2149
+ async enroll(data) {
2150
+ return safe5(this.client.call(LINK_MUTATION.ENROLL, data));
2151
+ }
2152
+ async enrollAndLinkOrder(data) {
2153
+ return safe5(
2154
+ this.client.call(LINK_MUTATION.ENROLL_AND_LINK_ORDER, data)
2155
+ );
2156
+ }
2157
+ async updatePreferences(preferences) {
2158
+ return safe5(this.client.call(LINK_MUTATION.UPDATE_PREFERENCES, preferences));
2159
+ }
2160
+ async createAddress(input) {
2161
+ return safe5(this.client.call(LINK_MUTATION.CREATE_ADDRESS, input));
2162
+ }
2163
+ async updateAddress(input) {
2164
+ return safe5(this.client.call(LINK_MUTATION.UPDATE_ADDRESS, input));
2165
+ }
2166
+ async deleteAddress(addressId) {
2167
+ return safe5(this.client.call(LINK_MUTATION.DELETE_ADDRESS, addressId));
2168
+ }
2169
+ async setDefaultAddress(addressId) {
2170
+ return safe5(this.client.call(LINK_MUTATION.SET_DEFAULT_ADDRESS, addressId));
2171
+ }
2172
+ async trackAddressUsage(addressId) {
2173
+ return safe5(
2174
+ this.client.call(LINK_MUTATION.TRACK_ADDRESS_USAGE, {
2175
+ address_id: addressId
2176
+ })
2177
+ );
2178
+ }
2179
+ async createMobileMoney(input) {
2180
+ return safe5(this.client.call(LINK_MUTATION.CREATE_MOBILE_MONEY, input));
2181
+ }
2182
+ async deleteMobileMoney(mobileMoneyId) {
2183
+ return safe5(this.client.call(LINK_MUTATION.DELETE_MOBILE_MONEY, mobileMoneyId));
2184
+ }
2185
+ async setDefaultMobileMoney(mobileMoneyId) {
2186
+ return safe5(
2187
+ this.client.call(LINK_MUTATION.SET_DEFAULT_MOBILE_MONEY, mobileMoneyId)
2188
+ );
2189
+ }
2190
+ async trackMobileMoneyUsage(mobileMoneyId) {
2191
+ return safe5(
2192
+ this.client.call(LINK_MUTATION.TRACK_MOBILE_MONEY_USAGE, {
2193
+ mobile_money_id: mobileMoneyId
2194
+ })
2195
+ );
2196
+ }
2197
+ async verifyMobileMoney(mobileMoneyId) {
2198
+ return safe5(
2199
+ this.client.call(LINK_MUTATION.VERIFY_MOBILE_MONEY, mobileMoneyId)
2200
+ );
2201
+ }
2202
+ async getSessions() {
2203
+ return safe5(this.client.linkGet("/v1/link/sessions"));
2204
+ }
2205
+ async revokeSession(sessionId) {
2206
+ return safe5(this.client.linkDelete(`/v1/link/sessions/${sessionId}`));
2207
+ }
2208
+ async revokeAllSessions() {
2209
+ return safe5(this.client.linkDelete("/v1/link/sessions"));
2210
+ }
2211
+ async getAddressesRest() {
2212
+ return safe5(this.client.linkGet("/v1/link/addresses"));
2213
+ }
2214
+ async createAddressRest(input) {
2215
+ return safe5(this.client.linkPost("/v1/link/addresses", input));
2216
+ }
2217
+ async deleteAddressRest(addressId) {
2218
+ return safe5(this.client.linkDelete(`/v1/link/addresses/${addressId}`));
2219
+ }
2220
+ async setDefaultAddressRest(addressId) {
2221
+ return safe5(this.client.linkPost(`/v1/link/addresses/${addressId}/default`));
2222
+ }
2223
+ async getMobileMoneyRest() {
2224
+ return safe5(this.client.linkGet("/v1/link/mobile-money"));
2225
+ }
2226
+ async createMobileMoneyRest(input) {
2227
+ return safe5(this.client.linkPost("/v1/link/mobile-money", input));
2228
+ }
2229
+ async deleteMobileMoneyRest(mobileMoneyId) {
2230
+ return safe5(this.client.linkDelete(`/v1/link/mobile-money/${mobileMoneyId}`));
2231
+ }
2232
+ async setDefaultMobileMoneyRest(mobileMoneyId) {
2233
+ return safe5(
2234
+ this.client.linkPost(`/v1/link/mobile-money/${mobileMoneyId}/default`)
2235
+ );
2236
+ }
2237
+ };
2238
+
2239
+ // src/auth.ts
2240
+ function toCimplifyError6(error) {
2241
+ if (error instanceof CimplifyError) return error;
2242
+ if (error instanceof Error) {
2243
+ return new CimplifyError("UNKNOWN_ERROR", error.message, false);
2244
+ }
2245
+ return new CimplifyError("UNKNOWN_ERROR", String(error), false);
2246
+ }
2247
+ async function safe6(promise) {
2248
+ try {
2249
+ return ok(await promise);
2250
+ } catch (error) {
2251
+ return err(toCimplifyError6(error));
2252
+ }
2253
+ }
2254
+ var AuthService = class {
2255
+ constructor(client) {
2256
+ this.client = client;
2257
+ }
2258
+ async getStatus() {
2259
+ return safe6(this.client.query("auth"));
2260
+ }
2261
+ async getCurrentUser() {
2262
+ const result = await this.getStatus();
2263
+ if (!result.ok) return result;
2264
+ return ok(result.value.customer || null);
2265
+ }
2266
+ async isAuthenticated() {
2267
+ const result = await this.getStatus();
2268
+ if (!result.ok) return result;
2269
+ return ok(result.value.is_authenticated);
2270
+ }
2271
+ async requestOtp(contact, contactType) {
2272
+ return safe6(
2273
+ this.client.call(AUTH_MUTATION.REQUEST_OTP, {
2274
+ contact,
2275
+ contact_type: contactType
2276
+ })
2277
+ );
2278
+ }
2279
+ async verifyOtp(code, contact) {
2280
+ return safe6(
2281
+ this.client.call(AUTH_MUTATION.VERIFY_OTP, {
2282
+ otp_code: code,
2283
+ contact
2284
+ })
2285
+ );
2286
+ }
2287
+ async logout() {
2288
+ return safe6(this.client.call("auth.logout"));
2289
+ }
2290
+ async updateProfile(input) {
2291
+ return safe6(this.client.call("auth.update_profile", input));
2292
+ }
2293
+ async changePassword(input) {
2294
+ return safe6(this.client.call("auth.change_password", input));
2295
+ }
2296
+ async resetPassword(email) {
2297
+ return safe6(this.client.call("auth.reset_password", { email }));
2298
+ }
2299
+ };
2300
+
2301
+ // src/business.ts
2302
+ function toCimplifyError7(error) {
2303
+ if (error instanceof CimplifyError) return error;
2304
+ if (error instanceof Error) {
2305
+ return new CimplifyError("UNKNOWN_ERROR", error.message, false);
2306
+ }
2307
+ return new CimplifyError("UNKNOWN_ERROR", String(error), false);
2308
+ }
2309
+ async function safe7(promise) {
2310
+ try {
2311
+ return ok(await promise);
2312
+ } catch (error) {
2313
+ return err(toCimplifyError7(error));
2314
+ }
2315
+ }
2316
+ var BusinessService = class {
2317
+ constructor(client) {
2318
+ this.client = client;
2319
+ }
2320
+ async getInfo() {
2321
+ return safe7(this.client.query("business.info"));
2322
+ }
2323
+ async getByHandle(handle) {
2324
+ return safe7(this.client.query(`business.handle.${handle}`));
2325
+ }
2326
+ async getByDomain(domain) {
2327
+ return safe7(this.client.query("business.domain", { domain }));
2328
+ }
2329
+ async getSettings() {
2330
+ return safe7(this.client.query("business.settings"));
2331
+ }
2332
+ async getTheme() {
2333
+ return safe7(this.client.query("business.theme"));
2334
+ }
2335
+ async getLocations() {
2336
+ return safe7(this.client.query("business.locations"));
2337
+ }
2338
+ async getLocation(locationId) {
2339
+ return safe7(this.client.query(`business.locations.${locationId}`));
2340
+ }
2341
+ async getHours() {
2342
+ return safe7(this.client.query("business.hours"));
2343
+ }
2344
+ async getLocationHours(locationId) {
2345
+ return safe7(this.client.query(`business.locations.${locationId}.hours`));
2346
+ }
2347
+ async getBootstrap() {
2348
+ const [businessResult, locationsResult, categoriesResult] = await Promise.all([
2349
+ this.getInfo(),
2350
+ this.getLocations(),
2351
+ safe7(this.client.query("categories#select(id,name,slug)"))
2352
+ ]);
2353
+ if (!businessResult.ok) return businessResult;
2354
+ if (!locationsResult.ok) return locationsResult;
2355
+ if (!categoriesResult.ok) return categoriesResult;
2356
+ const business = businessResult.value;
2357
+ const locations = locationsResult.value;
2358
+ const categories = categoriesResult.value;
2359
+ const defaultLocation = locations[0];
2360
+ return ok({
2361
+ business,
2362
+ location: defaultLocation,
2363
+ locations,
2364
+ categories,
2365
+ currency: business.default_currency,
2366
+ is_open: defaultLocation?.accepts_online_orders ?? false,
2367
+ accepts_orders: defaultLocation?.accepts_online_orders ?? false
2368
+ });
2369
+ }
2370
+ };
2371
+
2372
+ // src/inventory.ts
2373
+ function toCimplifyError8(error) {
2374
+ if (error instanceof CimplifyError) return error;
2375
+ if (error instanceof Error) {
2376
+ return new CimplifyError("UNKNOWN_ERROR", error.message, false);
2377
+ }
2378
+ return new CimplifyError("UNKNOWN_ERROR", String(error), false);
2379
+ }
2380
+ async function safe8(promise) {
2381
+ try {
2382
+ return ok(await promise);
2383
+ } catch (error) {
2384
+ return err(toCimplifyError8(error));
2385
+ }
2386
+ }
2387
+ var InventoryService = class {
2388
+ constructor(client) {
2389
+ this.client = client;
2390
+ }
2391
+ async getStockLevels() {
2392
+ return safe8(this.client.query("inventory.stock_levels"));
2393
+ }
2394
+ async getProductStock(productId, locationId) {
2395
+ if (locationId) {
2396
+ return safe8(
2397
+ this.client.query("inventory.product", {
2398
+ product_id: productId,
2399
+ location_id: locationId
2400
+ })
2401
+ );
2402
+ }
2403
+ return safe8(
2404
+ this.client.query("inventory.product", {
2405
+ product_id: productId
2406
+ })
2407
+ );
2408
+ }
2409
+ async getVariantStock(variantId, locationId) {
2410
+ return safe8(
2411
+ this.client.query("inventory.variant", {
2412
+ variant_id: variantId,
2413
+ location_id: locationId
2414
+ })
2415
+ );
2416
+ }
2417
+ async checkProductAvailability(productId, quantity, locationId) {
2418
+ return safe8(
2419
+ this.client.query("inventory.check_availability", {
2420
+ product_id: productId,
2421
+ quantity,
2422
+ location_id: locationId
2423
+ })
2424
+ );
2425
+ }
2426
+ async checkVariantAvailability(variantId, quantity, locationId) {
2427
+ return safe8(
2428
+ this.client.query("inventory.check_availability", {
2429
+ variant_id: variantId,
2430
+ quantity,
2431
+ location_id: locationId
2432
+ })
2433
+ );
2434
+ }
2435
+ async checkMultipleAvailability(items, locationId) {
2436
+ const results = await Promise.all(
2437
+ items.map(
2438
+ (item) => item.variant_id ? this.checkVariantAvailability(item.variant_id, item.quantity, locationId) : this.checkProductAvailability(item.product_id, item.quantity, locationId)
2439
+ )
2440
+ );
2441
+ for (const result of results) {
2442
+ if (!result.ok) return result;
2443
+ }
2444
+ return ok(results.map((r) => r.value));
2445
+ }
2446
+ async getSummary() {
2447
+ return safe8(this.client.query("inventory.summary"));
2448
+ }
2449
+ async isInStock(productId, locationId) {
2450
+ const result = await this.checkProductAvailability(productId, 1, locationId);
2451
+ if (!result.ok) return result;
2452
+ return ok(result.value.is_available);
2453
+ }
2454
+ async getAvailableQuantity(productId, locationId) {
2455
+ const result = await this.getProductStock(productId, locationId);
2456
+ if (!result.ok) return result;
2457
+ return ok(result.value.available_quantity);
2458
+ }
2459
+ };
2460
+
2461
+ // src/scheduling.ts
2462
+ function toVariables(input) {
2463
+ return Object.fromEntries(Object.entries(input));
2464
+ }
2465
+ function toCimplifyError9(error) {
2466
+ if (error instanceof CimplifyError) return error;
2467
+ if (error instanceof Error) {
2468
+ return new CimplifyError("UNKNOWN_ERROR", error.message, false);
2469
+ }
2470
+ return new CimplifyError("UNKNOWN_ERROR", String(error), false);
2471
+ }
2472
+ async function safe9(promise) {
2473
+ try {
2474
+ return ok(await promise);
2475
+ } catch (error) {
2476
+ return err(toCimplifyError9(error));
2477
+ }
2478
+ }
2479
+ var SchedulingService = class {
2480
+ constructor(client) {
2481
+ this.client = client;
2482
+ }
2483
+ async getServices() {
2484
+ return safe9(this.client.query("scheduling.services"));
2485
+ }
2486
+ /**
2487
+ * Get a specific service by ID
2488
+ * Note: Filters from all services client-side (no single-service endpoint)
2489
+ */
2490
+ async getService(serviceId) {
2491
+ const result = await this.getServices();
2492
+ if (!result.ok) return result;
2493
+ return ok(result.value.find((s) => s.id === serviceId) || null);
2494
+ }
2495
+ async getAvailableSlots(input) {
2496
+ return safe9(
2497
+ this.client.query("scheduling.slots", toVariables(input))
2498
+ );
2499
+ }
2500
+ async checkSlotAvailability(input) {
2501
+ return safe9(
2502
+ this.client.query(
2503
+ "scheduling.check_availability",
2504
+ toVariables(input)
2505
+ )
2506
+ );
2507
+ }
2508
+ async getServiceAvailability(params) {
2509
+ return safe9(
2510
+ this.client.query(
2511
+ "scheduling.availability",
2512
+ toVariables(params)
2513
+ )
2514
+ );
2515
+ }
2516
+ async getBooking(bookingId) {
2517
+ return safe9(this.client.query(`scheduling.${bookingId}`));
2518
+ }
2519
+ async getCustomerBookings() {
2520
+ return safe9(this.client.query("scheduling"));
2521
+ }
2522
+ async getUpcomingBookings() {
2523
+ return safe9(
2524
+ this.client.query(
2525
+ "scheduling[?(@.status!='completed' && @.status!='cancelled')]#sort(start_time,asc)"
2526
+ )
2527
+ );
2528
+ }
2529
+ async getPastBookings(limit = 10) {
2530
+ return safe9(
2531
+ this.client.query(
2532
+ `scheduling[?(@.status=='completed')]#sort(start_time,desc)#limit(${limit})`
2533
+ )
2534
+ );
2535
+ }
2536
+ async cancelBooking(input) {
2537
+ return safe9(this.client.call("scheduling.cancel_booking", input));
2538
+ }
2539
+ async rescheduleBooking(input) {
2540
+ return safe9(this.client.call("scheduling.reschedule_booking", input));
2541
+ }
2542
+ async getNextAvailableSlot(serviceId, fromDate) {
2543
+ const date = fromDate || (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
2544
+ const result = await this.getAvailableSlots({
2545
+ service_id: serviceId,
2546
+ date
2547
+ });
2548
+ if (!result.ok) return result;
2549
+ return ok(result.value.find((slot) => slot.is_available) || null);
2550
+ }
2551
+ async hasAvailabilityOn(serviceId, date) {
2552
+ const result = await this.getAvailableSlots({
2553
+ service_id: serviceId,
2554
+ date
2555
+ });
2556
+ if (!result.ok) return result;
2557
+ return ok(result.value.some((slot) => slot.is_available));
2558
+ }
2559
+ };
2560
+
2561
+ // src/lite.ts
2562
+ function toCimplifyError10(error) {
2563
+ if (error instanceof CimplifyError) return error;
2564
+ if (error instanceof Error) {
2565
+ return new CimplifyError("UNKNOWN_ERROR", error.message, false);
2566
+ }
2567
+ return new CimplifyError("UNKNOWN_ERROR", String(error), false);
2568
+ }
2569
+ async function safe10(promise) {
2570
+ try {
2571
+ return ok(await promise);
2572
+ } catch (error) {
2573
+ return err(toCimplifyError10(error));
2574
+ }
2575
+ }
2576
+ var LiteService = class {
2577
+ constructor(client) {
2578
+ this.client = client;
2579
+ }
2580
+ async getBootstrap() {
2581
+ return safe10(this.client.query("lite.bootstrap"));
2582
+ }
2583
+ async getTable(tableId) {
2584
+ return safe10(this.client.query(`lite.table.${tableId}`));
2585
+ }
2586
+ async getTableByNumber(tableNumber, locationId) {
2587
+ return safe10(
2588
+ this.client.query("lite.table_by_number", {
2589
+ table_number: tableNumber,
2590
+ location_id: locationId
2591
+ })
2592
+ );
2593
+ }
2594
+ async sendToKitchen(tableId, items) {
2595
+ return safe10(
2596
+ this.client.call("lite.send_to_kitchen", {
2597
+ table_id: tableId,
2598
+ items
2599
+ })
2600
+ );
2601
+ }
2602
+ async callWaiter(tableId, reason) {
2603
+ return safe10(
2604
+ this.client.call("lite.call_waiter", {
2605
+ table_id: tableId,
2606
+ reason
2607
+ })
2608
+ );
2609
+ }
2610
+ async requestBill(tableId) {
2611
+ return safe10(
2612
+ this.client.call("lite.request_bill", {
2613
+ table_id: tableId
2614
+ })
2615
+ );
2616
+ }
2617
+ async getMenu() {
2618
+ return safe10(this.client.query("lite.menu"));
2619
+ }
2620
+ async getMenuByCategory(categoryId) {
2621
+ return safe10(this.client.query(`lite.menu.category.${categoryId}`));
2622
+ }
2623
+ };
2624
+
2625
+ // src/fx.ts
2626
+ function toCimplifyError11(error) {
2627
+ if (error instanceof CimplifyError) return error;
2628
+ if (error instanceof Error) {
2629
+ return new CimplifyError("UNKNOWN_ERROR", error.message, false);
2630
+ }
2631
+ return new CimplifyError("UNKNOWN_ERROR", String(error), false);
2632
+ }
2633
+ async function safe11(promise) {
2634
+ try {
2635
+ return ok(await promise);
2636
+ } catch (error) {
2637
+ return err(toCimplifyError11(error));
2638
+ }
2639
+ }
2640
+ var FxService = class {
2641
+ constructor(client) {
2642
+ this.client = client;
2643
+ }
2644
+ async getRate(from, to) {
2645
+ return safe11(this.client.call("fx.getRate", { from, to }));
2646
+ }
2647
+ async lockQuote(request) {
2648
+ return safe11(this.client.call("fx.lockQuote", request));
2649
+ }
2650
+ };
2651
+
2652
+ // src/elements.ts
2653
+ function toCheckoutError(code, message, recoverable) {
2654
+ return {
2655
+ success: false,
2656
+ error: {
2657
+ code,
2658
+ message,
2659
+ recoverable
2660
+ }
2661
+ };
2662
+ }
2663
+ var DEFAULT_LINK_URL = "https://link.cimplify.io";
2664
+ function isAllowedOrigin(origin) {
2665
+ try {
2666
+ const url = new URL(origin);
2667
+ const hostname = url.hostname;
2668
+ if (hostname === "localhost" || hostname === "127.0.0.1") {
2669
+ return true;
2670
+ }
2671
+ if (url.protocol !== "https:") {
2672
+ return false;
2673
+ }
2674
+ return hostname === "cimplify.io" || hostname.endsWith(".cimplify.io");
2675
+ } catch {
2676
+ return false;
2677
+ }
2678
+ }
2679
+ function parseIframeMessage(data) {
2680
+ if (!data || typeof data !== "object") {
2681
+ return null;
2682
+ }
2683
+ const maybeType = data.type;
2684
+ if (typeof maybeType !== "string") {
2685
+ return null;
2686
+ }
2687
+ return data;
2688
+ }
2689
+ var CimplifyElements = class {
2690
+ constructor(client, businessId, options = {}) {
2691
+ this.elements = /* @__PURE__ */ new Map();
2692
+ this.accessToken = null;
2693
+ this.accountId = null;
2694
+ this.customerId = null;
2695
+ this.customerData = null;
2696
+ this.addressData = null;
2697
+ this.paymentData = null;
2698
+ this.checkoutInProgress = false;
2699
+ this.activeCheckoutAbort = null;
2700
+ this.businessIdResolvePromise = null;
2701
+ this.client = client;
2702
+ this.businessId = businessId ?? null;
2703
+ this.linkUrl = options.linkUrl || DEFAULT_LINK_URL;
2704
+ this.options = options;
2705
+ this.boundHandleMessage = this.handleMessage.bind(this);
2706
+ if (typeof window !== "undefined") {
2707
+ window.addEventListener("message", this.boundHandleMessage);
2708
+ }
2709
+ }
2710
+ create(type, options = {}) {
2711
+ const existing = this.elements.get(type);
2712
+ if (existing) return existing;
2713
+ const element = new CimplifyElement(type, this.businessId, this.linkUrl, options, this);
2714
+ this.elements.set(type, element);
2715
+ return element;
2716
+ }
2717
+ getElement(type) {
2718
+ return this.elements.get(type);
2719
+ }
2720
+ destroy() {
2721
+ this.elements.forEach((element) => element.destroy());
2722
+ this.elements.clear();
2723
+ if (typeof window !== "undefined") {
2724
+ window.removeEventListener("message", this.boundHandleMessage);
2725
+ }
2726
+ }
2727
+ async submitCheckout(data) {
2728
+ const result = await this.processCheckout({
2729
+ cart_id: data.cart_id,
2730
+ order_type: data.order_type ?? "delivery",
2731
+ location_id: data.location_id,
2732
+ notes: data.notes,
2733
+ scheduled_time: data.scheduled_time,
2734
+ tip_amount: data.tip_amount,
2735
+ enroll_in_link: true
2736
+ });
2737
+ if (result.success) {
2738
+ return {
2739
+ success: true,
2740
+ order: {
2741
+ id: result.order?.id || "",
2742
+ status: result.order?.status || "unknown",
2743
+ total: result.order?.total || ""
2744
+ }
2745
+ };
2746
+ }
2747
+ return {
2748
+ success: false,
2749
+ error: {
2750
+ code: result.error?.code || "CHECKOUT_FAILED",
2751
+ message: result.error?.message || "Checkout failed"
2752
+ }
2753
+ };
2754
+ }
2755
+ processCheckout(options) {
2756
+ let abortFn = null;
2757
+ const task = (async () => {
2758
+ if (this.checkoutInProgress) {
2759
+ return toCheckoutError(
2760
+ "ALREADY_PROCESSING",
2761
+ "Checkout is already in progress.",
2762
+ false
2763
+ );
2764
+ }
2765
+ if (!options.cart_id) {
2766
+ return toCheckoutError(
2767
+ "INVALID_CART",
2768
+ "A valid cart is required before checkout can start.",
2769
+ false
2770
+ );
2771
+ }
2772
+ if (!options.order_type) {
2773
+ return toCheckoutError(
2774
+ "ORDER_TYPE_REQUIRED",
2775
+ "Order type is required before checkout can start.",
2776
+ false
2777
+ );
2778
+ }
2779
+ const paymentElement = this.elements.get(ELEMENT_TYPES.PAYMENT);
2780
+ if (!paymentElement) {
2781
+ return toCheckoutError(
2782
+ "NO_PAYMENT_ELEMENT",
2783
+ "Payment element must be mounted before checkout.",
2784
+ false
2785
+ );
2786
+ }
2787
+ if (!paymentElement.isMounted()) {
2788
+ return toCheckoutError(
2789
+ "PAYMENT_NOT_MOUNTED",
2790
+ "Payment element must be mounted before checkout.",
2791
+ false
2792
+ );
2793
+ }
2794
+ const authElement = this.elements.get(ELEMENT_TYPES.AUTH);
2795
+ if (authElement && !this.accessToken) {
2796
+ return toCheckoutError(
2797
+ "AUTH_INCOMPLETE",
2798
+ "Authentication must complete before checkout can start.",
2799
+ true
2800
+ );
2801
+ }
2802
+ const addressElement = this.elements.get(ELEMENT_TYPES.ADDRESS);
2803
+ if (addressElement) {
2804
+ await addressElement.getData();
2805
+ }
2806
+ await this.hydrateCustomerData();
2807
+ const processMessage = {
2808
+ type: MESSAGE_TYPES.PROCESS_CHECKOUT,
2809
+ cart_id: options.cart_id,
2810
+ order_type: options.order_type,
2811
+ location_id: options.location_id,
2812
+ notes: options.notes,
2813
+ scheduled_time: options.scheduled_time,
2814
+ tip_amount: options.tip_amount,
2815
+ pay_currency: options.pay_currency,
2816
+ enroll_in_link: options.enroll_in_link ?? true,
2817
+ address: this.addressData ?? void 0,
2818
+ customer: this.customerData ? {
2819
+ name: this.customerData.name,
2820
+ email: this.customerData.email,
2821
+ phone: this.customerData.phone
2822
+ } : null,
2823
+ account_id: this.accountId ?? void 0,
2824
+ customer_id: this.customerId ?? void 0
2825
+ };
2826
+ const timeoutMs = options.timeout_ms ?? 18e4;
2827
+ const paymentWindow = paymentElement.getContentWindow();
2828
+ this.checkoutInProgress = true;
2829
+ return new Promise((resolve) => {
2830
+ let settled = false;
2831
+ const cleanup = () => {
2832
+ if (typeof window !== "undefined") {
2833
+ window.removeEventListener("message", handleCheckoutMessage);
2834
+ }
2835
+ clearTimeout(timeout);
2836
+ this.checkoutInProgress = false;
2837
+ this.activeCheckoutAbort = null;
2838
+ };
2839
+ const settle = (result) => {
2840
+ if (settled) {
2841
+ return;
2842
+ }
2843
+ settled = true;
2844
+ cleanup();
2845
+ resolve(result);
2846
+ };
2847
+ const timeout = setTimeout(() => {
2848
+ settle(
2849
+ toCheckoutError(
2850
+ "TIMEOUT",
2851
+ "Checkout timed out before receiving a terminal response.",
2852
+ true
2853
+ )
2854
+ );
2855
+ }, timeoutMs);
2856
+ const handleCheckoutMessage = (event) => {
2857
+ if (!isAllowedOrigin(event.origin)) {
2858
+ return;
2859
+ }
2860
+ const message = parseIframeMessage(event.data);
2861
+ if (!message) {
2862
+ return;
2863
+ }
2864
+ if (message.type === MESSAGE_TYPES.LOGOUT_COMPLETE) {
2865
+ paymentElement.sendMessage({ type: MESSAGE_TYPES.ABORT_CHECKOUT });
2866
+ settle(
2867
+ toCheckoutError(
2868
+ "AUTH_LOST",
2869
+ "Authentication was cleared during checkout.",
2870
+ true
2871
+ )
2872
+ );
2873
+ return;
2874
+ }
2875
+ if (paymentWindow && event.source && event.source !== paymentWindow) {
2876
+ return;
2877
+ }
2878
+ if (message.type === MESSAGE_TYPES.CHECKOUT_STATUS) {
2879
+ options.on_status_change?.(message.status, message.context);
2880
+ return;
2881
+ }
2882
+ if (message.type === MESSAGE_TYPES.CHECKOUT_COMPLETE) {
2883
+ settle({
2884
+ success: message.success,
2885
+ order: message.order,
2886
+ error: message.error,
2887
+ enrolled_in_link: message.enrolled_in_link
2888
+ });
2889
+ }
2890
+ };
2891
+ if (typeof window !== "undefined") {
2892
+ window.addEventListener("message", handleCheckoutMessage);
2893
+ }
2894
+ abortFn = () => {
2895
+ paymentElement.sendMessage({ type: MESSAGE_TYPES.ABORT_CHECKOUT });
2896
+ settle(
2897
+ toCheckoutError(
2898
+ "CANCELLED",
2899
+ "Checkout was cancelled.",
2900
+ true
2901
+ )
2902
+ );
2903
+ };
2904
+ this.activeCheckoutAbort = abortFn;
2905
+ paymentElement.sendMessage(processMessage);
2906
+ });
2907
+ })();
2908
+ const abortable = task;
2909
+ abortable.abort = () => {
2910
+ if (abortFn) {
2911
+ abortFn();
2912
+ }
2913
+ };
2914
+ return abortable;
2915
+ }
2916
+ isAuthenticated() {
2917
+ return this.accessToken !== null;
2918
+ }
2919
+ getAccessToken() {
2920
+ return this.accessToken;
2921
+ }
2922
+ getPublicKey() {
2923
+ return this.client.getPublicKey();
2924
+ }
2925
+ getBusinessId() {
2926
+ return this.businessId;
2927
+ }
2928
+ async resolveBusinessId() {
2929
+ if (this.businessId) {
2930
+ return this.businessId;
2931
+ }
2932
+ if (this.businessIdResolvePromise) {
2933
+ return this.businessIdResolvePromise;
2934
+ }
2935
+ this.businessIdResolvePromise = this.client.resolveBusinessId().then((resolvedBusinessId) => {
2936
+ this.businessId = resolvedBusinessId;
2937
+ return resolvedBusinessId;
2938
+ }).catch(() => null).finally(() => {
2939
+ this.businessIdResolvePromise = null;
2940
+ });
2941
+ return this.businessIdResolvePromise;
2942
+ }
2943
+ getAppearance() {
2944
+ return this.options.appearance;
2945
+ }
2946
+ async hydrateCustomerData() {
2947
+ if (!this.accessToken || this.customerData) {
2948
+ return;
2949
+ }
2950
+ if (!this.client.getAccessToken()) {
2951
+ this.client.setAccessToken(this.accessToken);
2952
+ }
2953
+ const linkDataResult = await this.client.link.getLinkData();
2954
+ if (!linkDataResult.ok || !linkDataResult.value?.customer) {
2955
+ return;
2956
+ }
2957
+ const customer = linkDataResult.value.customer;
2958
+ this.customerData = {
2959
+ name: customer.name || "",
2960
+ email: customer.email || null,
2961
+ phone: customer.phone || null
2962
+ };
2963
+ }
2964
+ handleMessage(event) {
2965
+ if (!isAllowedOrigin(event.origin)) {
2966
+ return;
2967
+ }
2968
+ const message = parseIframeMessage(event.data);
2969
+ if (!message) return;
2970
+ switch (message.type) {
2971
+ case MESSAGE_TYPES.AUTHENTICATED:
2972
+ const customer = message.customer ?? {
2973
+ name: "",
2974
+ email: null,
2975
+ phone: null
2976
+ };
2977
+ this.accessToken = message.token;
2978
+ this.accountId = message.accountId;
2979
+ this.customerId = message.customerId;
2980
+ this.customerData = customer;
2981
+ this.client.setAccessToken(message.token);
2982
+ this.elements.forEach((element, type) => {
2983
+ if (type !== ELEMENT_TYPES.AUTH) {
2984
+ element.sendMessage({ type: MESSAGE_TYPES.SET_TOKEN, token: message.token });
2985
+ }
2986
+ });
2987
+ break;
2988
+ case MESSAGE_TYPES.TOKEN_REFRESHED:
2989
+ this.accessToken = message.token;
2990
+ break;
2991
+ case MESSAGE_TYPES.ADDRESS_CHANGED:
2992
+ case MESSAGE_TYPES.ADDRESS_SELECTED:
2993
+ this.addressData = message.address;
2994
+ break;
2995
+ case MESSAGE_TYPES.PAYMENT_METHOD_SELECTED:
2996
+ this.paymentData = message.method;
2997
+ break;
2998
+ case MESSAGE_TYPES.LOGOUT_COMPLETE:
2999
+ if (this.checkoutInProgress && this.activeCheckoutAbort) {
3000
+ this.activeCheckoutAbort();
3001
+ }
3002
+ this.accessToken = null;
3003
+ this.accountId = null;
3004
+ this.customerId = null;
3005
+ this.customerData = null;
3006
+ this.addressData = null;
3007
+ this.paymentData = null;
3008
+ this.client.clearSession();
3009
+ break;
3010
+ }
3011
+ }
3012
+ _setAddressData(data) {
3013
+ this.addressData = data;
3014
+ }
3015
+ _setPaymentData(data) {
3016
+ this.paymentData = data;
3017
+ }
3018
+ };
3019
+ var CimplifyElement = class {
3020
+ constructor(type, businessId, linkUrl, options, parent) {
3021
+ this.iframe = null;
3022
+ this.container = null;
3023
+ this.mounted = false;
3024
+ this.eventHandlers = /* @__PURE__ */ new Map();
3025
+ this.resolvers = /* @__PURE__ */ new Map();
3026
+ this.type = type;
3027
+ this.businessId = businessId;
3028
+ this.linkUrl = linkUrl;
3029
+ this.options = options;
3030
+ this.parent = parent;
3031
+ this.boundHandleMessage = this.handleMessage.bind(this);
3032
+ if (typeof window !== "undefined") {
3033
+ window.addEventListener("message", this.boundHandleMessage);
3034
+ }
3035
+ }
3036
+ mount(container) {
3037
+ if (this.mounted) {
3038
+ console.warn(`Element ${this.type} is already mounted`);
3039
+ return;
3040
+ }
3041
+ const target = typeof container === "string" ? document.querySelector(container) : container;
3042
+ if (!target) {
3043
+ console.error(`Container not found: ${container}`);
3044
+ return;
3045
+ }
3046
+ this.container = target;
3047
+ this.mounted = true;
3048
+ void this.createIframe();
3049
+ }
3050
+ destroy() {
3051
+ if (this.iframe) {
3052
+ this.iframe.remove();
3053
+ this.iframe = null;
3054
+ }
3055
+ this.container = null;
3056
+ this.mounted = false;
3057
+ this.eventHandlers.clear();
3058
+ this.resolvers.forEach((entry) => clearTimeout(entry.timeoutId));
3059
+ this.resolvers.clear();
3060
+ if (typeof window !== "undefined") {
3061
+ window.removeEventListener("message", this.boundHandleMessage);
3062
+ }
3063
+ }
3064
+ on(event, handler) {
3065
+ if (!this.eventHandlers.has(event)) {
3066
+ this.eventHandlers.set(event, /* @__PURE__ */ new Set());
3067
+ }
3068
+ this.eventHandlers.get(event).add(handler);
3069
+ }
3070
+ off(event, handler) {
3071
+ this.eventHandlers.get(event)?.delete(handler);
3072
+ }
3073
+ async getData() {
3074
+ if (!this.isMounted()) {
3075
+ return null;
3076
+ }
3077
+ return new Promise((resolve) => {
3078
+ const id = Math.random().toString(36).slice(2);
3079
+ const timeoutId = setTimeout(() => {
3080
+ const entry = this.resolvers.get(id);
3081
+ if (!entry) {
3082
+ return;
3083
+ }
3084
+ this.resolvers.delete(id);
3085
+ entry.resolve(null);
3086
+ }, 5e3);
3087
+ this.resolvers.set(id, { resolve, timeoutId });
3088
+ this.sendMessage({ type: MESSAGE_TYPES.GET_DATA });
3089
+ });
3090
+ }
3091
+ sendMessage(message) {
3092
+ if (this.iframe?.contentWindow) {
3093
+ this.iframe.contentWindow.postMessage(message, this.linkUrl);
3094
+ }
3095
+ }
3096
+ getContentWindow() {
3097
+ return this.iframe?.contentWindow ?? null;
3098
+ }
3099
+ isMounted() {
3100
+ return this.mounted && Boolean(this.iframe) && this.iframe?.isConnected === true;
3101
+ }
3102
+ async createIframe() {
3103
+ if (!this.container) return;
3104
+ const resolvedBusinessId = this.businessId ?? await this.parent.resolveBusinessId();
3105
+ if (!resolvedBusinessId || !this.container || !this.mounted) {
3106
+ console.error("Unable to mount element without a resolved business ID");
3107
+ this.emit(EVENT_TYPES.ERROR, {
3108
+ code: "BUSINESS_ID_REQUIRED",
3109
+ message: "Unable to initialize checkout without a business ID."
3110
+ });
3111
+ return;
3112
+ }
3113
+ this.businessId = resolvedBusinessId;
3114
+ const iframe = document.createElement("iframe");
3115
+ const url = new URL(`${this.linkUrl}/elements/${this.type}`);
3116
+ url.searchParams.set("businessId", resolvedBusinessId);
3117
+ if (this.options.prefillEmail) url.searchParams.set("email", this.options.prefillEmail);
3118
+ if (this.options.mode) url.searchParams.set("mode", this.options.mode);
3119
+ iframe.src = url.toString();
3120
+ iframe.style.border = "none";
3121
+ iframe.style.width = "100%";
3122
+ iframe.style.display = "block";
3123
+ iframe.style.overflow = "hidden";
3124
+ iframe.setAttribute("allowtransparency", "true");
3125
+ iframe.setAttribute("frameborder", "0");
3126
+ iframe.setAttribute(
3127
+ "sandbox",
3128
+ "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"
3129
+ );
3130
+ this.iframe = iframe;
3131
+ this.container.appendChild(iframe);
3132
+ iframe.onload = () => {
3133
+ const publicKey = this.parent.getPublicKey();
3134
+ this.sendMessage({
3135
+ type: MESSAGE_TYPES.INIT,
3136
+ businessId: resolvedBusinessId,
3137
+ publicKey,
3138
+ demoMode: publicKey.length === 0,
3139
+ prefillEmail: this.options.prefillEmail,
3140
+ appearance: this.parent.getAppearance()
3141
+ });
3142
+ const token = this.parent.getAccessToken();
3143
+ if (token && this.type !== ELEMENT_TYPES.AUTH) {
3144
+ this.sendMessage({ type: MESSAGE_TYPES.SET_TOKEN, token });
3145
+ }
3146
+ };
3147
+ }
3148
+ handleMessage(event) {
3149
+ if (!isAllowedOrigin(event.origin)) {
3150
+ return;
3151
+ }
3152
+ const message = parseIframeMessage(event.data);
3153
+ if (!message) return;
3154
+ switch (message.type) {
3155
+ case MESSAGE_TYPES.READY:
3156
+ this.emit(EVENT_TYPES.READY, { height: message.height });
3157
+ break;
3158
+ case MESSAGE_TYPES.HEIGHT_CHANGE:
3159
+ if (this.iframe) this.iframe.style.height = `${message.height}px`;
3160
+ break;
3161
+ case MESSAGE_TYPES.AUTHENTICATED:
3162
+ const customer = message.customer ?? {
3163
+ name: "",
3164
+ email: null,
3165
+ phone: null
3166
+ };
3167
+ this.emit(EVENT_TYPES.AUTHENTICATED, {
3168
+ accountId: message.accountId,
3169
+ customerId: message.customerId,
3170
+ token: message.token,
3171
+ customer
3172
+ });
3173
+ break;
3174
+ case MESSAGE_TYPES.REQUIRES_OTP:
3175
+ this.emit(EVENT_TYPES.REQUIRES_OTP, { contactMasked: message.contactMasked });
3176
+ break;
3177
+ case MESSAGE_TYPES.ERROR:
3178
+ this.emit(EVENT_TYPES.ERROR, { code: message.code, message: message.message });
3179
+ break;
3180
+ case MESSAGE_TYPES.ADDRESS_CHANGED:
3181
+ case MESSAGE_TYPES.ADDRESS_SELECTED:
3182
+ this.parent._setAddressData(message.address);
3183
+ this.emit(EVENT_TYPES.CHANGE, { address: message.address });
3184
+ this.resolveData(message.address);
3185
+ break;
3186
+ case MESSAGE_TYPES.PAYMENT_METHOD_SELECTED:
3187
+ this.parent._setPaymentData(message.method);
3188
+ this.emit(EVENT_TYPES.CHANGE, { paymentMethod: message.method });
3189
+ this.resolveData(message.method);
3190
+ break;
3191
+ }
3192
+ }
3193
+ emit(event, data) {
3194
+ this.eventHandlers.get(event)?.forEach((handler) => handler(data));
3195
+ }
3196
+ resolveData(data) {
3197
+ this.resolvers.forEach((entry) => {
3198
+ clearTimeout(entry.timeoutId);
3199
+ entry.resolve(data);
3200
+ });
3201
+ this.resolvers.clear();
3202
+ }
3203
+ };
3204
+ function createElements(client, businessId, options) {
3205
+ return new CimplifyElements(client, businessId, options);
3206
+ }
3207
+
3208
+ // src/client.ts
3209
+ var ACCESS_TOKEN_STORAGE_KEY = "cimplify_access_token";
3210
+ var DEFAULT_TIMEOUT_MS = 3e4;
3211
+ var DEFAULT_MAX_RETRIES = 3;
3212
+ var DEFAULT_RETRY_DELAY_MS = 1e3;
3213
+ function sleep(ms) {
3214
+ return new Promise((resolve) => setTimeout(resolve, ms));
3215
+ }
3216
+ function isRetryable(error) {
3217
+ if (error instanceof TypeError && error.message.includes("fetch")) {
3218
+ return true;
3219
+ }
3220
+ if (error instanceof DOMException && error.name === "AbortError") {
3221
+ return true;
3222
+ }
3223
+ if (error instanceof CimplifyError) {
3224
+ return error.retryable;
3225
+ }
3226
+ if (error instanceof CimplifyError && error.code === "SERVER_ERROR") {
3227
+ return true;
3228
+ }
3229
+ return false;
3230
+ }
3231
+ function toNetworkError(error) {
3232
+ if (error instanceof DOMException && error.name === "AbortError") {
3233
+ return new CimplifyError(
3234
+ ErrorCode.TIMEOUT,
3235
+ "Request timed out. Please check your connection and try again.",
3236
+ true
3237
+ );
3238
+ }
3239
+ if (error instanceof TypeError && error.message.includes("fetch")) {
3240
+ return new CimplifyError(
3241
+ ErrorCode.NETWORK_ERROR,
3242
+ "Network error. Please check your internet connection.",
3243
+ true
3244
+ );
3245
+ }
3246
+ if (error instanceof CimplifyError) {
3247
+ return error;
3248
+ }
3249
+ return new CimplifyError(
3250
+ ErrorCode.UNKNOWN_ERROR,
3251
+ error instanceof Error ? error.message : "An unknown error occurred",
3252
+ false
3253
+ );
3254
+ }
3255
+ function deriveUrls() {
3256
+ const hostname = typeof window !== "undefined" ? window.location.hostname : "";
3257
+ if (hostname === "localhost" || hostname === "127.0.0.1") {
3258
+ const protocol = window.location.protocol;
3259
+ return {
3260
+ baseUrl: `${protocol}//${hostname}:8082`,
3261
+ linkApiUrl: `${protocol}//${hostname}:8080`
3262
+ };
3263
+ }
3264
+ return {
3265
+ baseUrl: "https://storefronts.cimplify.io",
3266
+ linkApiUrl: "https://api.cimplify.io"
3267
+ };
3268
+ }
3269
+ function getEnvPublicKey() {
3270
+ try {
3271
+ const env = globalThis.process;
3272
+ return env?.env.NEXT_PUBLIC_CIMPLIFY_PUBLIC_KEY || void 0;
3273
+ } catch {
3274
+ return void 0;
3275
+ }
3276
+ }
3277
+ var CimplifyClient = class {
3278
+ constructor(config = {}) {
3279
+ this.accessToken = null;
3280
+ this.context = {};
3281
+ this.businessId = null;
3282
+ this.businessIdResolvePromise = null;
3283
+ this.inflightRequests = /* @__PURE__ */ new Map();
3284
+ this.publicKey = config.publicKey || getEnvPublicKey() || "";
3285
+ const urls = deriveUrls();
3286
+ this.baseUrl = urls.baseUrl;
3287
+ this.linkApiUrl = urls.linkApiUrl;
3288
+ this.credentials = config.credentials || "include";
3289
+ this.timeout = config.timeout ?? DEFAULT_TIMEOUT_MS;
3290
+ this.maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;
3291
+ this.retryDelay = config.retryDelay ?? DEFAULT_RETRY_DELAY_MS;
3292
+ this.hooks = config.hooks ?? {};
3293
+ this.accessToken = this.loadAccessToken();
3294
+ if (!this.publicKey) {
3295
+ console.warn(
3296
+ '[Cimplify] No public key found. Set NEXT_PUBLIC_CIMPLIFY_PUBLIC_KEY in your environment, or pass { publicKey: "pk_..." } to createCimplifyClient().'
3297
+ );
3298
+ }
3299
+ }
3300
+ /** @deprecated Use getAccessToken() instead */
3301
+ getSessionToken() {
3302
+ return this.accessToken;
3303
+ }
3304
+ /** @deprecated Use setAccessToken() instead */
3305
+ setSessionToken(token) {
3306
+ this.setAccessToken(token);
3307
+ }
3308
+ getAccessToken() {
3309
+ return this.accessToken;
3310
+ }
3311
+ getPublicKey() {
3312
+ return this.publicKey;
3313
+ }
3314
+ setAccessToken(token) {
3315
+ const previous = this.accessToken;
3316
+ this.accessToken = token;
3317
+ this.saveAccessToken(token);
3318
+ this.hooks.onSessionChange?.({
3319
+ previousToken: previous,
3320
+ newToken: token,
3321
+ source: "manual"
3322
+ });
3323
+ }
3324
+ clearSession() {
3325
+ const previous = this.accessToken;
3326
+ this.accessToken = null;
3327
+ this.saveAccessToken(null);
3328
+ this.hooks.onSessionChange?.({
3329
+ previousToken: previous,
3330
+ newToken: null,
3331
+ source: "clear"
3332
+ });
3333
+ }
3334
+ /** Set the active location/branch for all subsequent requests */
3335
+ setLocationId(locationId) {
3336
+ if (locationId) {
3337
+ this.context.location_id = locationId;
3338
+ } else {
3339
+ delete this.context.location_id;
3340
+ }
3341
+ }
3342
+ /** Get the currently active location ID */
3343
+ getLocationId() {
3344
+ return this.context.location_id ?? null;
3345
+ }
3346
+ /** Cache a resolved business ID for future element/checkouts initialization. */
3347
+ setBusinessId(businessId) {
3348
+ const normalized = businessId.trim();
3349
+ if (!normalized) {
3350
+ return;
3351
+ }
3352
+ this.businessId = normalized;
3353
+ }
3354
+ /** Get cached business ID if available. */
3355
+ getBusinessId() {
3356
+ return this.businessId;
3357
+ }
3358
+ /**
3359
+ * Resolve business ID from public key once and cache it.
3360
+ * Subsequent calls return the cached value (or shared in-flight promise).
3361
+ */
3362
+ async resolveBusinessId() {
3363
+ if (this.businessId) {
3364
+ return this.businessId;
3365
+ }
3366
+ if (this.businessIdResolvePromise) {
3367
+ return this.businessIdResolvePromise;
3368
+ }
3369
+ this.businessIdResolvePromise = (async () => {
3370
+ const result = await this.business.getInfo();
3371
+ if (!result.ok || !result.value?.id) {
3372
+ throw new CimplifyError(
3373
+ ErrorCode.NOT_FOUND,
3374
+ "Unable to resolve business ID from the current public key.",
3375
+ true
3376
+ );
3377
+ }
3378
+ this.businessId = result.value.id;
3379
+ return result.value.id;
3380
+ })();
3381
+ try {
3382
+ return await this.businessIdResolvePromise;
3383
+ } finally {
3384
+ this.businessIdResolvePromise = null;
3385
+ }
3386
+ }
3387
+ loadAccessToken() {
3388
+ if (typeof window !== "undefined" && window.localStorage) {
3389
+ return localStorage.getItem(ACCESS_TOKEN_STORAGE_KEY);
3390
+ }
3391
+ return null;
3392
+ }
3393
+ saveAccessToken(token) {
3394
+ if (typeof window !== "undefined" && window.localStorage) {
3395
+ if (token) {
3396
+ localStorage.setItem(ACCESS_TOKEN_STORAGE_KEY, token);
3397
+ } else {
3398
+ localStorage.removeItem(ACCESS_TOKEN_STORAGE_KEY);
3399
+ }
3400
+ }
3401
+ }
3402
+ getHeaders() {
3403
+ const headers = {
3404
+ "Content-Type": "application/json",
3405
+ "X-API-Key": this.publicKey
3406
+ };
3407
+ if (this.accessToken) {
3408
+ headers["Authorization"] = `Bearer ${this.accessToken}`;
3409
+ }
3410
+ return headers;
3411
+ }
3412
+ async resilientFetch(url, options) {
3413
+ const method = options.method || "GET";
3414
+ const path = url.replace(this.baseUrl, "").replace(this.linkApiUrl, "");
3415
+ const startTime = Date.now();
3416
+ let retryCount = 0;
3417
+ const context = {
3418
+ method,
3419
+ path,
3420
+ url,
3421
+ body: options.body ? JSON.parse(options.body) : void 0,
3422
+ startTime
3423
+ };
3424
+ this.hooks.onRequestStart?.(context);
3425
+ let lastError;
3426
+ for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
3427
+ try {
3428
+ const controller = new AbortController();
3429
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
3430
+ const response = await fetch(url, {
3431
+ ...options,
3432
+ signal: controller.signal
3433
+ });
3434
+ clearTimeout(timeoutId);
3435
+ if (response.ok || response.status >= 400 && response.status < 500) {
3436
+ this.hooks.onRequestSuccess?.({
3437
+ ...context,
3438
+ status: response.status,
3439
+ durationMs: Date.now() - startTime
3440
+ });
3441
+ return response;
3442
+ }
3443
+ if (response.status >= 500 && attempt < this.maxRetries) {
3444
+ retryCount++;
3445
+ const delay = this.retryDelay * Math.pow(2, attempt);
3446
+ this.hooks.onRetry?.({
3447
+ ...context,
3448
+ attempt: retryCount,
3449
+ delayMs: delay,
3450
+ error: new Error(`Server error: ${response.status}`)
3451
+ });
3452
+ await sleep(delay);
3453
+ continue;
3454
+ }
3455
+ this.hooks.onRequestSuccess?.({
3456
+ ...context,
3457
+ status: response.status,
3458
+ durationMs: Date.now() - startTime
3459
+ });
3460
+ return response;
3461
+ } catch (error) {
3462
+ lastError = error;
3463
+ const networkError = toNetworkError(error);
3464
+ const errorRetryable = isRetryable(error);
3465
+ if (!errorRetryable || attempt >= this.maxRetries) {
3466
+ this.hooks.onRequestError?.({
3467
+ ...context,
3468
+ error: networkError,
3469
+ durationMs: Date.now() - startTime,
3470
+ retryCount,
3471
+ retryable: errorRetryable
3472
+ });
3473
+ throw networkError;
3474
+ }
3475
+ retryCount++;
3476
+ const delay = this.retryDelay * Math.pow(2, attempt);
3477
+ this.hooks.onRetry?.({
3478
+ ...context,
3479
+ attempt: retryCount,
3480
+ delayMs: delay,
3481
+ error: networkError
3482
+ });
3483
+ await sleep(delay);
3484
+ }
3485
+ }
3486
+ const finalError = toNetworkError(lastError);
3487
+ this.hooks.onRequestError?.({
3488
+ ...context,
3489
+ error: finalError,
3490
+ durationMs: Date.now() - startTime,
3491
+ retryCount,
3492
+ retryable: false
3493
+ });
3494
+ throw finalError;
3495
+ }
3496
+ getDedupeKey(type, payload) {
3497
+ return `${type}:${JSON.stringify(payload)}`;
3498
+ }
3499
+ async deduplicatedRequest(key, requestFn) {
3500
+ const existing = this.inflightRequests.get(key);
3501
+ if (existing) {
3502
+ return existing;
3503
+ }
3504
+ const request = requestFn().finally(() => {
3505
+ this.inflightRequests.delete(key);
3506
+ });
3507
+ this.inflightRequests.set(key, request);
3508
+ return request;
3509
+ }
3510
+ async query(query, variables) {
3511
+ const body = { query };
3512
+ if (variables) {
3513
+ body.variables = variables;
3514
+ }
3515
+ if (Object.keys(this.context).length > 0) {
3516
+ body.context = this.context;
3517
+ }
3518
+ const key = this.getDedupeKey("query", body);
3519
+ return this.deduplicatedRequest(key, async () => {
3520
+ const response = await this.resilientFetch(`${this.baseUrl}/api/q`, {
3521
+ method: "POST",
3522
+ credentials: this.credentials,
3523
+ headers: this.getHeaders(),
3524
+ body: JSON.stringify(body)
3525
+ });
3526
+ return this.handleResponse(response);
3527
+ });
3528
+ }
3529
+ async call(method, args) {
3530
+ const body = {
3531
+ method,
3532
+ args: args !== void 0 ? [args] : []
3533
+ };
3534
+ if (Object.keys(this.context).length > 0) {
3535
+ body.context = this.context;
3536
+ }
3537
+ const response = await this.resilientFetch(`${this.baseUrl}/api/m`, {
3538
+ method: "POST",
3539
+ credentials: this.credentials,
3540
+ headers: this.getHeaders(),
3541
+ body: JSON.stringify(body)
3542
+ });
3543
+ return this.handleResponse(response);
3544
+ }
3545
+ async get(path) {
3546
+ const key = this.getDedupeKey("get", path);
3547
+ return this.deduplicatedRequest(key, async () => {
3548
+ const response = await this.resilientFetch(`${this.baseUrl}${path}`, {
3549
+ method: "GET",
3550
+ credentials: this.credentials,
3551
+ headers: this.getHeaders()
3552
+ });
3553
+ return this.handleRestResponse(response);
3554
+ });
3555
+ }
3556
+ async post(path, body) {
3557
+ const response = await this.resilientFetch(`${this.baseUrl}${path}`, {
3558
+ method: "POST",
3559
+ credentials: this.credentials,
3560
+ headers: this.getHeaders(),
3561
+ body: body ? JSON.stringify(body) : void 0
3562
+ });
3563
+ return this.handleRestResponse(response);
3564
+ }
3565
+ async delete(path) {
3566
+ const response = await this.resilientFetch(`${this.baseUrl}${path}`, {
3567
+ method: "DELETE",
3568
+ credentials: this.credentials,
3569
+ headers: this.getHeaders()
3570
+ });
3571
+ return this.handleRestResponse(response);
3572
+ }
3573
+ async linkGet(path) {
3574
+ const key = this.getDedupeKey("linkGet", path);
3575
+ return this.deduplicatedRequest(key, async () => {
3576
+ const response = await this.resilientFetch(`${this.linkApiUrl}${path}`, {
3577
+ method: "GET",
3578
+ credentials: this.credentials,
3579
+ headers: this.getHeaders()
3580
+ });
3581
+ return this.handleRestResponse(response);
3582
+ });
3583
+ }
3584
+ async linkPost(path, body) {
3585
+ const response = await this.resilientFetch(`${this.linkApiUrl}${path}`, {
3586
+ method: "POST",
3587
+ credentials: this.credentials,
3588
+ headers: this.getHeaders(),
3589
+ body: body ? JSON.stringify(body) : void 0
3590
+ });
3591
+ return this.handleRestResponse(response);
3592
+ }
3593
+ async linkDelete(path) {
3594
+ const response = await this.resilientFetch(`${this.linkApiUrl}${path}`, {
3595
+ method: "DELETE",
3596
+ credentials: this.credentials,
3597
+ headers: this.getHeaders()
3598
+ });
3599
+ return this.handleRestResponse(response);
3600
+ }
3601
+ async handleRestResponse(response) {
3602
+ const json = await response.json();
3603
+ if (!response.ok) {
3604
+ throw new CimplifyError(
3605
+ json.error?.error_code || "API_ERROR",
3606
+ json.error?.error_message || "An error occurred",
3607
+ false
3608
+ );
3609
+ }
3610
+ return json.data;
3611
+ }
3612
+ async handleResponse(response) {
3613
+ const json = await response.json();
3614
+ if (!json.success || json.error) {
3615
+ throw new CimplifyError(
3616
+ json.error?.code || "UNKNOWN_ERROR",
3617
+ json.error?.message || "An unknown error occurred",
3618
+ json.error?.retryable || false
3619
+ );
3620
+ }
3621
+ return json.data;
3622
+ }
3623
+ get catalogue() {
3624
+ if (!this._catalogue) {
3625
+ this._catalogue = new CatalogueQueries(this);
3626
+ }
3627
+ return this._catalogue;
3628
+ }
3629
+ get cart() {
3630
+ if (!this._cart) {
3631
+ this._cart = new CartOperations(this);
3632
+ }
3633
+ return this._cart;
3634
+ }
3635
+ get checkout() {
3636
+ if (!this._checkout) {
3637
+ this._checkout = new CheckoutService(this);
3638
+ }
3639
+ return this._checkout;
3640
+ }
3641
+ get orders() {
3642
+ if (!this._orders) {
3643
+ this._orders = new OrderQueries(this);
3644
+ }
3645
+ return this._orders;
3646
+ }
3647
+ get link() {
3648
+ if (!this._link) {
3649
+ this._link = new LinkService(this);
3650
+ }
3651
+ return this._link;
3652
+ }
3653
+ get auth() {
3654
+ if (!this._auth) {
3655
+ this._auth = new AuthService(this);
3656
+ }
3657
+ return this._auth;
3658
+ }
3659
+ get business() {
3660
+ if (!this._business) {
3661
+ this._business = new BusinessService(this);
3662
+ }
3663
+ return this._business;
3664
+ }
3665
+ get inventory() {
3666
+ if (!this._inventory) {
3667
+ this._inventory = new InventoryService(this);
3668
+ }
3669
+ return this._inventory;
3670
+ }
3671
+ get scheduling() {
3672
+ if (!this._scheduling) {
3673
+ this._scheduling = new SchedulingService(this);
3674
+ }
3675
+ return this._scheduling;
3676
+ }
3677
+ get lite() {
3678
+ if (!this._lite) {
3679
+ this._lite = new LiteService(this);
3680
+ }
3681
+ return this._lite;
3682
+ }
3683
+ get fx() {
3684
+ if (!this._fx) {
3685
+ this._fx = new FxService(this);
3686
+ }
3687
+ return this._fx;
3688
+ }
3689
+ /**
3690
+ * Create a CimplifyElements instance for embedding checkout components.
3691
+ * Like Stripe's stripe.elements().
3692
+ *
3693
+ * @param businessId - The business ID for checkout context
3694
+ * @param options - Optional configuration for elements
3695
+ *
3696
+ * @example
3697
+ * ```ts
3698
+ * const elements = client.elements('bus_xxx');
3699
+ * const authElement = elements.create('auth');
3700
+ * authElement.mount('#auth-container');
3701
+ * ```
3702
+ */
3703
+ elements(businessId, options) {
3704
+ if (businessId) {
3705
+ this.setBusinessId(businessId);
3706
+ }
3707
+ return createElements(this, businessId ?? this.businessId ?? void 0, options);
3708
+ }
3709
+ };
3710
+ function createCimplifyClient(config = {}) {
3711
+ return new CimplifyClient(config);
3712
+ }
3713
+ var LOCATION_STORAGE_KEY = "cimplify_location_id";
3714
+ var DEFAULT_CURRENCY = "USD";
3715
+ var DEFAULT_COUNTRY = "US";
3716
+ function createDefaultClient() {
3717
+ const processRef = globalThis.process;
3718
+ const envPublicKey = processRef?.env?.NEXT_PUBLIC_CIMPLIFY_PUBLIC_KEY || "";
3719
+ return createCimplifyClient({ publicKey: envPublicKey });
3720
+ }
3721
+ function getStoredLocationId() {
3722
+ if (typeof window === "undefined" || !window.localStorage) {
3723
+ return null;
3724
+ }
3725
+ const value = window.localStorage.getItem(LOCATION_STORAGE_KEY);
3726
+ if (!value) {
3727
+ return null;
3728
+ }
3729
+ const normalized = value.trim();
3730
+ return normalized.length > 0 ? normalized : null;
3731
+ }
3732
+ function setStoredLocationId(locationId) {
3733
+ if (typeof window === "undefined" || !window.localStorage) {
3734
+ return;
3735
+ }
3736
+ if (!locationId) {
3737
+ window.localStorage.removeItem(LOCATION_STORAGE_KEY);
3738
+ return;
3739
+ }
3740
+ window.localStorage.setItem(LOCATION_STORAGE_KEY, locationId);
3741
+ }
3742
+ function resolveInitialLocation(locations) {
3743
+ if (locations.length === 0) {
3744
+ return null;
3745
+ }
3746
+ const storedId = getStoredLocationId();
3747
+ if (storedId) {
3748
+ const matched = locations.find((location) => location.id === storedId);
3749
+ if (matched) {
3750
+ return matched;
3751
+ }
3752
+ }
3753
+ return locations[0];
3754
+ }
3755
+ var CimplifyContext = createContext(null);
3756
+ function CimplifyProvider({
3757
+ client,
3758
+ children,
3759
+ onLocationChange
3760
+ }) {
3761
+ const resolvedClient = useMemo(() => client ?? createDefaultClient(), [client]);
3762
+ const onLocationChangeRef = useRef(onLocationChange);
3763
+ const [business, setBusiness] = useState(null);
3764
+ const [locations, setLocations] = useState([]);
3765
+ const [currentLocation, setCurrentLocationState] = useState(null);
3766
+ const [isReady, setIsReady] = useState(false);
3767
+ useEffect(() => {
3768
+ onLocationChangeRef.current = onLocationChange;
3769
+ }, [onLocationChange]);
3770
+ const isDemoMode = resolvedClient.getPublicKey().trim().length === 0;
3771
+ const setCurrentLocation = useCallback(
3772
+ (location) => {
3773
+ setCurrentLocationState(location);
3774
+ resolvedClient.setLocationId(location.id);
3775
+ setStoredLocationId(location.id);
3776
+ onLocationChangeRef.current?.(location);
3777
+ },
3778
+ [resolvedClient]
3779
+ );
3780
+ useEffect(() => {
3781
+ let cancelled = false;
3782
+ async function bootstrap() {
3783
+ setIsReady(false);
3784
+ if (isDemoMode) {
3785
+ if (!cancelled) {
3786
+ setBusiness(null);
3787
+ setLocations([]);
3788
+ setCurrentLocationState(null);
3789
+ resolvedClient.setLocationId(null);
3790
+ setStoredLocationId(null);
3791
+ setIsReady(true);
3792
+ }
3793
+ return;
3794
+ }
3795
+ const [businessResult, locationsResult] = await Promise.all([
3796
+ resolvedClient.business.getInfo(),
3797
+ resolvedClient.business.getLocations()
3798
+ ]);
3799
+ if (cancelled) {
3800
+ return;
3801
+ }
3802
+ const nextBusiness = businessResult.ok ? businessResult.value : null;
3803
+ const nextLocations = locationsResult.ok && Array.isArray(locationsResult.value) ? locationsResult.value : [];
3804
+ const initialLocation = resolveInitialLocation(nextLocations);
3805
+ setBusiness(nextBusiness);
3806
+ setLocations(nextLocations);
3807
+ if (initialLocation) {
3808
+ setCurrentLocationState(initialLocation);
3809
+ resolvedClient.setLocationId(initialLocation.id);
3810
+ setStoredLocationId(initialLocation.id);
3811
+ } else {
3812
+ setCurrentLocationState(null);
3813
+ resolvedClient.setLocationId(null);
3814
+ setStoredLocationId(null);
3815
+ }
3816
+ setIsReady(true);
3817
+ }
3818
+ bootstrap().catch(() => {
3819
+ if (cancelled) {
3820
+ return;
3821
+ }
3822
+ setBusiness(null);
3823
+ setLocations([]);
3824
+ setCurrentLocationState(null);
3825
+ resolvedClient.setLocationId(null);
3826
+ setStoredLocationId(null);
3827
+ setIsReady(true);
3828
+ });
3829
+ return () => {
3830
+ cancelled = true;
3831
+ };
3832
+ }, [resolvedClient, isDemoMode]);
3833
+ const contextValue = useMemo(
3834
+ () => ({
3835
+ client: resolvedClient,
3836
+ business,
3837
+ currency: business?.default_currency || DEFAULT_CURRENCY,
3838
+ country: business?.country_code || DEFAULT_COUNTRY,
3839
+ locations,
3840
+ currentLocation,
3841
+ setCurrentLocation,
3842
+ isReady,
3843
+ isDemoMode
3844
+ }),
3845
+ [
3846
+ resolvedClient,
3847
+ business,
3848
+ locations,
3849
+ currentLocation,
3850
+ setCurrentLocation,
3851
+ isReady,
3852
+ isDemoMode
3853
+ ]
3854
+ );
3855
+ return /* @__PURE__ */ jsx(CimplifyContext.Provider, { value: contextValue, children });
3856
+ }
3857
+ function useCimplify() {
3858
+ const context = useContext(CimplifyContext);
3859
+ if (!context) {
3860
+ throw new Error("useCimplify must be used within CimplifyProvider");
3861
+ }
3862
+ return context;
3863
+ }
3864
+ var ElementsContext = createContext({
3865
+ elements: null,
3866
+ isReady: false
3867
+ });
3868
+ function useElements() {
3869
+ return useContext(ElementsContext).elements;
3870
+ }
3871
+ function useElementsReady() {
3872
+ return useContext(ElementsContext).isReady;
3873
+ }
3874
+ function ElementsProvider({
3875
+ client,
3876
+ businessId,
3877
+ options,
3878
+ children
3879
+ }) {
3880
+ const [elements, setElements] = useState(null);
3881
+ const [isReady, setIsReady] = useState(false);
3882
+ const initialOptionsRef = useRef(options);
3883
+ useEffect(() => {
3884
+ let cancelled = false;
3885
+ let instance = null;
3886
+ setIsReady(false);
3887
+ setElements(null);
3888
+ async function bootstrap() {
3889
+ const resolvedBusinessId = businessId ?? await client.resolveBusinessId().catch(() => null);
3890
+ if (!resolvedBusinessId) {
3891
+ if (!cancelled) {
3892
+ setIsReady(false);
3893
+ setElements(null);
3894
+ }
3895
+ return;
3896
+ }
3897
+ instance = client.elements(resolvedBusinessId, initialOptionsRef.current);
3898
+ if (cancelled) {
3899
+ instance.destroy();
3900
+ return;
3901
+ }
3902
+ setElements(instance);
3903
+ setIsReady(true);
3904
+ }
3905
+ void bootstrap();
3906
+ return () => {
3907
+ cancelled = true;
3908
+ if (instance) {
3909
+ instance.destroy();
3910
+ }
3911
+ };
3912
+ }, [client, businessId]);
538
3913
  return /* @__PURE__ */ jsx(ElementsContext.Provider, { value: { elements, isReady }, children });
539
3914
  }
540
3915
  function AuthElement({
@@ -646,4 +4021,4 @@ function useCheckout() {
646
4021
  return { submit, process, isLoading };
647
4022
  }
648
4023
 
649
- export { Ad, AdProvider, AddressElement, AuthElement, CimplifyCheckout, ElementsProvider, PaymentElement, useAds, useCheckout, useElements, useElementsReady };
4024
+ export { Ad, AdProvider, AddressElement, AuthElement, CimplifyCheckout, CimplifyProvider, ElementsProvider, PaymentElement, useAds, useCheckout, useCimplify, useElements, useElementsReady };