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