@tagadapay/headless-sdk 1.1.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/core/client.d.ts +2 -5
  2. package/dist/core/client.d.ts.map +1 -1
  3. package/dist/core/client.js +1 -3
  4. package/dist/core/client.js.map +1 -1
  5. package/dist/core/index.d.ts +1 -2
  6. package/dist/core/index.d.ts.map +1 -1
  7. package/dist/core/index.js +0 -1
  8. package/dist/core/index.js.map +1 -1
  9. package/dist/core/modules/offers.d.ts +64 -23
  10. package/dist/core/modules/offers.d.ts.map +1 -1
  11. package/dist/core/modules/offers.js +70 -33
  12. package/dist/core/modules/offers.js.map +1 -1
  13. package/dist/core/types.d.ts +26 -16
  14. package/dist/core/types.d.ts.map +1 -1
  15. package/dist/react/hooks/useOffers.d.ts +63 -22
  16. package/dist/react/hooks/useOffers.d.ts.map +1 -1
  17. package/dist/react/hooks/useOffers.js +36 -52
  18. package/dist/react/hooks/useOffers.js.map +1 -1
  19. package/dist/react/index.d.ts +1 -3
  20. package/dist/react/index.d.ts.map +1 -1
  21. package/dist/react/index.js +0 -1
  22. package/dist/react/index.js.map +1 -1
  23. package/dist/tagada-headless-react.min.js +2 -2
  24. package/dist/tagada-headless-react.min.js.map +4 -4
  25. package/dist/tagada-headless.js +67 -291
  26. package/dist/tagada-headless.min.js +2 -2
  27. package/dist/tagada-headless.min.js.map +4 -4
  28. package/package.json +3 -3
  29. package/dist/core/modules/analytics.d.ts +0 -79
  30. package/dist/core/modules/analytics.d.ts.map +0 -1
  31. package/dist/core/modules/analytics.js +0 -265
  32. package/dist/core/modules/analytics.js.map +0 -1
  33. package/dist/react/hooks/useAnalytics.d.ts +0 -59
  34. package/dist/react/hooks/useAnalytics.d.ts.map +0 -1
  35. package/dist/react/hooks/useAnalytics.js +0 -49
  36. package/dist/react/hooks/useAnalytics.js.map +0 -1
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @tagadapay/headless-sdk v1.1.1
2
+ * @tagadapay/headless-sdk v1.2.0
3
3
  * Headless checkout, payments, analytics, and CRM
4
4
  * @license MIT
5
5
  */
@@ -43,7 +43,6 @@ var TagadaHeadlessBundle = (() => {
43
43
  // src/core/index.ts
44
44
  var core_exports = {};
45
45
  __export(core_exports, {
46
- AnalyticsModule: () => AnalyticsModule,
47
46
  CatalogModule: () => CatalogModule,
48
47
  CheckoutModule: () => CheckoutModule,
49
48
  CustomerModule: () => CustomerModule,
@@ -717,315 +716,93 @@ var TagadaHeadlessBundle = (() => {
717
716
  }
718
717
  };
719
718
 
720
- // src/core/modules/analytics.ts
721
- var AnalyticsModule = class {
719
+ // src/core/modules/offers.ts
720
+ var OffersModule = class {
722
721
  constructor(http, storeId) {
723
722
  this.http = http;
724
723
  this.storeId = storeId;
725
- this.pixels = { loaded: false };
726
- this.eventQueue = [];
727
- this.dedupeSet = /* @__PURE__ */ new Set();
728
- }
729
- /**
730
- * Initialize analytics by loading pixel configuration from the store.
731
- * Call this once on page load. Events fired before init completes are queued.
732
- */
733
- async init(opts) {
734
- if (this.pixels.loaded)
735
- return;
736
- let config = opts == null ? void 0 : opts.pixelConfig;
737
- if (!config) {
738
- try {
739
- const res = await this.http.get(
740
- "/api/v1/checkout/config",
741
- { params: { storeId: this.storeId } }
742
- );
743
- config = res.pixels;
744
- } catch {
745
- }
746
- }
747
- this.pixels = { loaded: true, config };
748
- if (typeof window !== "undefined" && config) {
749
- this.loadPixelScripts(config);
750
- }
751
- this.flushQueue();
752
724
  }
753
725
  // ---------------------------------------------------------------------------
754
- // Standard e-commerce events
726
+ // Offer loading
755
727
  // ---------------------------------------------------------------------------
756
- trackPageView(page) {
757
- this.fireEvent("PageView", { page: page ?? this.getCurrentPath() });
758
- }
759
- trackViewContent(data) {
760
- this.fireEvent("ViewContent", data);
761
- }
762
- trackAddToCart(data) {
763
- this.fireEvent("AddToCart", data);
764
- }
765
- trackInitiateCheckout(data) {
766
- this.fireEvent("InitiateCheckout", data ?? {});
728
+ /** Get a single offer by ID. */
729
+ async getOffer(offerId) {
730
+ return this.http.get(`/api/v1/offers/${offerId}`);
767
731
  }
768
- trackAddPaymentInfo(data) {
769
- this.fireEvent("AddPaymentInfo", data ?? {});
770
- }
771
- trackPurchase(data) {
772
- this.fireEvent("Purchase", data, true);
773
- }
774
- trackCustomEvent(event, data) {
775
- this.fireEvent(event, data ?? {});
776
- }
777
- /** Track a funnel step (maps to Tagada's funnel tracking endpoint). */
778
- trackStep(data) {
779
- this.fireEvent("FunnelStep", data);
780
- this.http.post("/api/v1/funnel-tracking/step", {
781
- storeId: this.storeId,
782
- ...data
783
- }).catch(() => {
784
- });
785
- }
786
- trackConversion(data) {
787
- this.fireEvent("Conversion", data, true);
788
- }
789
- // ---------------------------------------------------------------------------
790
- // Internals
791
- // ---------------------------------------------------------------------------
792
- fireEvent(event, data, dedupe = false) {
793
- if (dedupe) {
794
- const key = `${event}:${JSON.stringify(data)}`;
795
- if (this.dedupeSet.has(key))
796
- return;
797
- this.dedupeSet.add(key);
798
- }
799
- if (!this.pixels.loaded) {
800
- this.eventQueue.push({ event, data });
801
- return;
802
- }
803
- this.sendToMeta(event, data);
804
- this.sendToTikTok(event, data);
805
- this.sendToSnapchat(event, data);
806
- this.sendToGTM(event, data);
807
- this.sendToGA(event, data);
808
- }
809
- flushQueue() {
810
- const queue = [...this.eventQueue];
811
- this.eventQueue = [];
812
- for (const { event, data } of queue) {
813
- this.fireEvent(event, data);
732
+ /** List offers for the current store. Optionally filter by type or a set of IDs. */
733
+ async listOffers(opts) {
734
+ var _a;
735
+ let url = `/api/v1/stores/${this.storeId}/offers`;
736
+ const queryParts = [];
737
+ if (opts == null ? void 0 : opts.type)
738
+ queryParts.push(`type=${encodeURIComponent(opts.type)}`);
739
+ if ((_a = opts == null ? void 0 : opts.ids) == null ? void 0 : _a.length) {
740
+ for (const id of opts.ids)
741
+ queryParts.push(`ids=${encodeURIComponent(id)}`);
814
742
  }
815
- }
816
- getCurrentPath() {
817
- return typeof window !== "undefined" ? window.location.pathname : "/";
818
- }
819
- // ---------------------------------------------------------------------------
820
- // Pixel script loaders
821
- // ---------------------------------------------------------------------------
822
- loadPixelScripts(config) {
823
- if (config.metaPixelId)
824
- this.loadMetaPixel(config.metaPixelId);
825
- if (config.tiktokPixelId)
826
- this.loadTikTokPixel(config.tiktokPixelId);
827
- if (config.snapchatPixelId)
828
- this.loadSnapchatPixel(config.snapchatPixelId);
829
- if (config.gtmId)
830
- this.loadGTM(config.gtmId);
831
- if (config.gaId)
832
- this.loadGA(config.gaId);
833
- }
834
- loadMetaPixel(pixelId) {
835
- if (typeof window === "undefined")
836
- return;
837
- const w = window;
838
- if (w.fbq)
839
- return;
840
- const n = w.fbq = function(...args) {
841
- n.callMethod ? n.callMethod(...args) : n.queue.push(args);
842
- };
843
- n.queue = [];
844
- n.loaded = true;
845
- n.version = "2.0";
846
- this.injectScript("https://connect.facebook.net/en_US/fbevents.js");
847
- w.fbq("init", pixelId);
848
- }
849
- loadTikTokPixel(pixelId) {
850
- if (typeof window === "undefined")
851
- return;
852
- const w = window;
853
- if (w.ttq)
854
- return;
855
- const ttq = {};
856
- ttq.methods = ["page", "track", "identify", "instances", "debug", "on", "off", "once", "ready", "alias", "group", "enableCookie", "disableCookie"];
857
- ttq.setAndDefer = function(t, e) {
858
- t[e] = function(...args) {
859
- t.push([e, ...args]);
860
- };
861
- };
862
- w.ttq = ttq;
863
- this.injectScript("https://analytics.tiktok.com/i18n/pixel/events.js?sdkid=" + pixelId);
864
- }
865
- loadSnapchatPixel(pixelId) {
866
- if (typeof window === "undefined")
867
- return;
868
- const w = window;
869
- if (w.snaptr)
870
- return;
871
- w.snaptr = function(...args) {
872
- w.snaptr.handleRequest ? w.snaptr.handleRequest(...args) : w.snaptr.queue.push(args);
873
- };
874
- w.snaptr.queue = [];
875
- this.injectScript("https://sc-static.net/scevent.min.js");
876
- w.snaptr("init", pixelId);
877
- }
878
- loadGTM(gtmId) {
879
- if (typeof window === "undefined")
880
- return;
881
- const w = window;
882
- w.dataLayer = w.dataLayer ?? [];
883
- w.dataLayer.push({ "gtm.start": Date.now(), event: "gtm.js" });
884
- this.injectScript(`https://www.googletagmanager.com/gtm.js?id=${gtmId}`);
885
- }
886
- loadGA(gaId) {
887
- if (typeof window === "undefined")
888
- return;
889
- this.injectScript(`https://www.googletagmanager.com/gtag/js?id=${gaId}`);
890
- const w = window;
891
- w.dataLayer = w.dataLayer ?? [];
892
- w.gtag = function(...args) {
893
- w.dataLayer.push(args);
894
- };
895
- w.gtag("js", /* @__PURE__ */ new Date());
896
- w.gtag("config", gaId);
897
- }
898
- injectScript(src) {
899
- if (typeof document === "undefined")
900
- return;
901
- const s = document.createElement("script");
902
- s.async = true;
903
- s.src = src;
904
- document.head.appendChild(s);
743
+ if (queryParts.length)
744
+ url += `?${queryParts.join("&")}`;
745
+ const res = await this.http.get(url);
746
+ return res.offers ?? [];
905
747
  }
906
748
  // ---------------------------------------------------------------------------
907
- // Event dispatchers per pixel
749
+ // Preview & pay (one-click upsell flow from plugin-sdk)
908
750
  // ---------------------------------------------------------------------------
909
- sendToMeta(event, data) {
910
- const w = typeof window !== "undefined" ? window : null;
911
- const fbq = w == null ? void 0 : w.fbq;
912
- if (!fbq)
913
- return;
914
- const metaEventMap = {
915
- PageView: "PageView",
916
- ViewContent: "ViewContent",
917
- AddToCart: "AddToCart",
918
- InitiateCheckout: "InitiateCheckout",
919
- AddPaymentInfo: "AddPaymentInfo",
920
- Purchase: "Purchase"
921
- };
922
- const mapped = metaEventMap[event];
923
- if (mapped) {
924
- fbq("track", mapped, data);
925
- } else {
926
- fbq("trackCustom", event, data);
927
- }
928
- }
929
- sendToTikTok(event, data) {
930
- var _a, _b;
931
- const w = typeof window !== "undefined" ? window : null;
932
- const ttq = w == null ? void 0 : w.ttq;
933
- if (!ttq)
934
- return;
935
- if (event === "PageView") {
936
- (_a = ttq.page) == null ? void 0 : _a.call(ttq);
937
- } else {
938
- (_b = ttq.track) == null ? void 0 : _b.call(ttq, event, data);
939
- }
940
- }
941
- sendToSnapchat(event, data) {
942
- const w = typeof window !== "undefined" ? window : null;
943
- const snaptr = w == null ? void 0 : w.snaptr;
944
- if (!snaptr)
945
- return;
946
- const snapEventMap = {
947
- PageView: "PAGE_VIEW",
948
- ViewContent: "VIEW_CONTENT",
949
- AddToCart: "ADD_CART",
950
- InitiateCheckout: "START_CHECKOUT",
951
- Purchase: "PURCHASE"
952
- };
953
- const mapped = snapEventMap[event];
954
- if (mapped)
955
- snaptr("track", mapped, data);
956
- }
957
- sendToGTM(event, data) {
958
- const w = typeof window !== "undefined" ? window : null;
959
- const dataLayer = w == null ? void 0 : w.dataLayer;
960
- if (!dataLayer)
961
- return;
962
- dataLayer.push({ event, ...data });
963
- }
964
- sendToGA(event, data) {
965
- const w = typeof window !== "undefined" ? window : null;
966
- const gtag = w == null ? void 0 : w.gtag;
967
- if (!gtag)
968
- return;
969
- gtag("event", event, data);
970
- }
971
- };
972
-
973
- // src/core/modules/offers.ts
974
- var OffersModule = class {
975
- constructor(http, storeId) {
976
- this.http = http;
977
- this.storeId = storeId;
978
- }
979
- /** Load offer details by ID. */
980
- async loadOffer(offerId) {
981
- const res = await this.http.get(
982
- `/api/v1/checkout-offers/${offerId}`,
983
- { params: { storeId: this.storeId } }
984
- );
985
- return res.offer;
986
- }
987
- /** List all offers for the store. */
988
- async listOffers(opts) {
989
- const res = await this.http.get(
990
- "/api/v1/checkout-offers",
991
- { params: { storeId: this.storeId, type: opts == null ? void 0 : opts.type } }
992
- );
993
- return res.offers;
751
+ /** Preview offer pricing. Returns line items with amounts and totals. */
752
+ async previewOffer(opts) {
753
+ return this.http.post(`/api/v1/offers/${opts.offerId}/preview`, {
754
+ offerId: opts.offerId,
755
+ currency: opts.currency ?? "",
756
+ lineItems: opts.lineItems
757
+ });
994
758
  }
995
759
  /**
996
- * Accept an offer (one-click upsell).
997
- * Charges the stored payment instrument from the main checkout order.
760
+ * Pay a previously previewed offer (one-click charge).
761
+ * Used after a main order so the stored payment instrument is reused.
998
762
  */
999
- async acceptOffer(opts) {
1000
- return this.http.post("/api/v1/checkout-offers/accept", {
763
+ async payPreviewedOffer(opts) {
764
+ return this.http.post(`/api/v1/offers/${opts.offerId}/pay-preview`, {
1001
765
  offerId: opts.offerId,
1002
- checkoutSessionId: opts.checkoutSessionId,
1003
- storeId: this.storeId,
766
+ currency: opts.currency ?? "",
767
+ lineItems: opts.lineItems,
768
+ returnUrl: opts.returnUrl ?? (typeof window !== "undefined" ? window.location.href : ""),
769
+ mainOrderId: opts.mainOrderId,
1004
770
  paymentInstrumentId: opts.paymentInstrumentId
1005
771
  });
1006
772
  }
1007
- /** Decline an offer. Advances the funnel to the next step. */
1008
- async declineOffer(opts) {
1009
- return this.http.post("/api/v1/checkout-offers/decline", {
1010
- offerId: opts.offerId,
1011
- checkoutSessionId: opts.checkoutSessionId,
1012
- storeId: this.storeId
1013
- });
773
+ // ---------------------------------------------------------------------------
774
+ // Order bumps (checkout-session scoped)
775
+ // ---------------------------------------------------------------------------
776
+ /** Toggle an order bump on/off within a checkout session. */
777
+ async toggleOrderBump(opts) {
778
+ return this.http.post(
779
+ `/api/v1/checkout-sessions/${opts.checkoutSessionId}/toggle-order-bump`,
780
+ {
781
+ orderBumpOfferId: opts.orderBumpOfferId,
782
+ selected: opts.selected
783
+ }
784
+ );
1014
785
  }
1015
- /** List order bumps available for a checkout session (shown on the checkout page). */
1016
- async listOrderBumps(checkoutSessionId) {
1017
- const res = await this.http.get(
1018
- "/api/v1/checkout-offers",
1019
- { params: { storeId: this.storeId, checkoutSessionId, type: "orderbump" } }
786
+ // ---------------------------------------------------------------------------
787
+ // Post-purchase offers (order-scoped)
788
+ // ---------------------------------------------------------------------------
789
+ /** List post-purchase offers for an order. */
790
+ async listPostPurchaseOffers(orderId) {
791
+ const res = await this.http.get(`/api/v1/post-purchase/${orderId}/offers`);
792
+ return Array.isArray(res) ? res : [];
793
+ }
794
+ /** Accept a post-purchase offer. */
795
+ async acceptPostPurchaseOffer(opts) {
796
+ return this.http.post(
797
+ `/api/v1/orders/${opts.orderId}/post-purchase-offers/${opts.offerId}/accept`,
798
+ { items: opts.items ?? [] }
1020
799
  );
1021
- return res.offers;
1022
800
  }
1023
- /** Toggle an order bump on/off for a checkout session. */
1024
- async toggleOrderBump(opts) {
1025
- await this.http.post(`/api/v1/checkout-sessions/${opts.checkoutSessionId}/order-bumps`, {
1026
- offerId: opts.offerId,
1027
- selected: opts.selected
1028
- });
801
+ /** Decline a post-purchase offer. */
802
+ async declinePostPurchaseOffer(opts) {
803
+ return this.http.post(
804
+ `/api/v1/orders/${opts.orderId}/post-purchase-offers/${opts.offerId}/decline`
805
+ );
1029
806
  }
1030
807
  };
1031
808
 
@@ -1155,7 +932,6 @@ var TagadaHeadlessBundle = (() => {
1155
932
  };
1156
933
  this.checkout = new CheckoutModule(this.http, this.config.storeId, setToken);
1157
934
  this.payment = new PaymentModule(this.http, this.config.storeId, environment);
1158
- this.analytics = new AnalyticsModule(this.http, this.config.storeId);
1159
935
  this.offers = new OffersModule(this.http, this.config.storeId);
1160
936
  this.customer = new CustomerModule(this.http, this.config.storeId);
1161
937
  this.catalog = new CatalogModule(this.http, this.config.storeId);
@@ -1,8 +1,8 @@
1
1
  /**
2
- * @tagadapay/headless-sdk v1.1.1
2
+ * @tagadapay/headless-sdk v1.2.0
3
3
  * Headless checkout, payments, analytics, and CRM
4
4
  * @license MIT
5
5
  */
6
- "use strict";var TagadaHeadlessBundle=(()=>{var U=Object.create;var O=Object.defineProperty;var _=Object.getOwnPropertyDescriptor;var D=Object.getOwnPropertyNames;var L=Object.getPrototypeOf,F=Object.prototype.hasOwnProperty;var z=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var V=(o,e)=>{for(var t in e)O(o,t,{get:e[t],enumerable:!0})},N=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of D(e))!F.call(o,s)&&s!==t&&O(o,s,{get:()=>e[s],enumerable:!(n=_(e,s))||n.enumerable});return o};var G=(o,e,t)=>(t=o!=null?U(L(o)):{},N(e||!o||!o.__esModule?O(t,"default",{value:o,enumerable:!0}):t,o)),J=o=>N(O({},"__esModule",{value:!0}),o);var K={};V(K,{AnalyticsModule:()=>T,CatalogModule:()=>R,CheckoutModule:()=>P,CustomerModule:()=>b,HeadlessClient:()=>A,HttpClient:()=>g,OffersModule:()=>S,PaymentModule:()=>C,TagadaAuthError:()=>k,TagadaError:()=>u,TagadaNetworkError:()=>l,TagadaNotFoundError:()=>I,TagadaPaymentError:()=>M,TagadaRateLimitError:()=>v,TagadaValidationError:()=>w,createHeadlessClient:()=>H});var u=class extends Error{constructor(e,t,n,s){super(e),this.name="TagadaError",this.code=t,this.statusCode=n,this.details=s}},k=class extends u{constructor(e="Authentication failed. Check your API key or checkout token."){super(e,"auth_error",401),this.name="TagadaAuthError"}},w=class extends u{constructor(e,t=[]){super(e,"validation_error",422,{errors:t}),this.name="TagadaValidationError",this.errors=t}},I=class extends u{constructor(e,t){super(`${e} "${t}" not found.`,"not_found",404),this.name="TagadaNotFoundError"}},v=class extends u{constructor(e=1e3){super(`Rate limited. Retry after ${e}ms.`,"rate_limit",429),this.name="TagadaRateLimitError",this.retryAfterMs=e}},M=class extends u{constructor(e,t){super(e,"payment_error",void 0,t==null?void 0:t.details),this.name="TagadaPaymentError",this.paymentId=t==null?void 0:t.paymentId,this.requireAction=t==null?void 0:t.requireAction}},l=class extends u{constructor(e="Network request failed. Check your connection."){super(e,"network_error"),this.name="TagadaNetworkError"}};var $={production:"https://app.tagadapay.com",development:"https://app.dev.tagadapay.com",local:"http://localhost:3000"},g=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.timeout=e.timeout,this.apiKey=e.apiKey,this.getToken=e.getToken}static resolveBaseUrl(e,t){return t??$[e]??$.production}async request(e,t={}){var h;let{method:n="GET",body:s,headers:i={},params:r,token:a,signal:c}=t,p=`${this.baseUrl}${e}`;if(r){let d=new URLSearchParams;for(let[j,q]of Object.entries(r))q!==void 0&&d.set(j,String(q));let x=d.toString();x&&(p+=`?${x}`)}let m={"Content-Type":"application/json",...i},y=a??this.apiKey??((h=this.getToken)==null?void 0:h.call(this));y&&(m["x-cms-token"]=y);let E=new AbortController,f=setTimeout(()=>E.abort(),this.timeout);try{let d=await fetch(p,{method:n,headers:m,body:s!=null?JSON.stringify(s):void 0,signal:c??E.signal});if(clearTimeout(f),d.ok){let x=await d.text();return x?JSON.parse(x):{}}throw await this.handleErrorResponse(d,e),new u("Unexpected error","unknown",d.status)}catch(d){throw clearTimeout(f),d instanceof u?d:d instanceof DOMException&&d.name==="AbortError"?new l(`Request to ${e} timed out after ${this.timeout}ms.`):new l(d instanceof Error?d.message:"Network request failed.")}}get(e,t){return this.request(e,{...t,method:"GET"})}post(e,t,n){return this.request(e,{...n,method:"POST",body:t})}patch(e,t,n){return this.request(e,{...n,method:"PATCH",body:t})}put(e,t,n){return this.request(e,{...n,method:"PUT",body:t})}delete(e,t){return this.request(e,{...t,method:"DELETE"})}async handleErrorResponse(e,t){let n={};try{n=await e.json()}catch{}let s=n.message??n.error??`Request failed: ${e.status} ${e.statusText} on ${t}`;switch(e.status){case 401:case 403:throw new k(s);case 404:throw new I(t,"");case 422:{let i=Array.isArray(n.errors)?n.errors:[];throw new w(s,i)}case 429:{let i=Number(e.headers.get("Retry-After")??"1")*1e3;throw new v(i)}default:throw new u(s,"api_error",e.status,n)}}};var P=class{constructor(e,t,n){this.http=e;this.storeId=t;this.onTokenChange=n}async loadSession(e,t){var s;t&&(this.sessionToken=t,(s=this.onTokenChange)==null||s.call(this,t));let n=await this.http.get(`/api/v1/checkout-sessions/${e}/v2`,{params:{skipAsyncWait:"false"},token:this.sessionToken});return this.normalizeSession(n)}async createSession(e){var a;let t=e.items.map(c=>({variantId:c.variantId,priceId:c.priceId,quantity:c.quantity})),n={storeId:this.storeId,lineItems:t};e.currency&&(n.currency=e.currency),e.returnUrl&&(n.returnUrl=e.returnUrl),e.customerEmail&&(n.customer={email:e.customerEmail,firstName:e.customerFirstName,lastName:e.customerLastName,currency:e.currency});let s=await this.http.post("/api/v1/checkout/session/init",n),r=new URL(s.checkoutUrl).searchParams.get("token")??"";return this.sessionToken=r,r&&((a=this.onTokenChange)==null||a.call(this,r)),{checkoutUrl:s.checkoutUrl,checkoutToken:s.checkoutToken,sessionToken:r,customerId:s.customerId}}async updateCart(e,t){return this.http.post(`/api/v1/checkout-sessions/${e}/line-items`,{items:t},{token:this.sessionToken})}async updateCustomer(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/customer-and-session-info`,{checkoutSessionId:e,partial:!0,customerData:{email:t.email},shippingAddress:{firstName:t.firstName,lastName:t.lastName,phone:t.phone},billingAddress:{},differentBillingAddress:!1},{token:this.sessionToken})}async updateAddress(e,t){let n=s=>{if(s)return{address1:s.line1,address2:s.line2,city:s.city,state:s.state,postal:s.postalCode,country:s.country}};await this.http.post(`/api/v1/checkout-sessions/${e}/address`,{checkoutSessionId:e,data:{shippingAddress:n(t.shippingAddress)??{},billingAddress:n(t.billingAddress)}},{token:this.sessionToken})}async applyPromoCode(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/promotions/apply`,{checkoutSessionId:e,code:t},{token:this.sessionToken})}async removePromoCode(e,t){let n=t??"default";await this.http.delete(`/api/v1/checkout-sessions/${e}/promotions/${n}`,{token:this.sessionToken})}async getShippingRates(e){return(await this.http.get(`/api/v1/checkout-sessions/${e}/shipping-rates`,{token:this.sessionToken})).rates??[]}async selectShippingRate(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/shipping-rate`,{checkoutSessionId:e,shippingRateId:t},{token:this.sessionToken})}normalizeSession(e){let t=e.checkoutSession,n=t.orderSummaries??[],s=e.summary??t.summary??n[0]??{},i=t.sessionLineItems??[],r=t.customer,a=i.map(p=>{let m=p.price,y=(m==null?void 0:m.variant)??{},E=y.product??{},f=(m==null?void 0:m.currencyOptions)??{},h=f.USD??f[Object.keys(f)[0]];return{id:p.id,variantId:p.variantId,priceId:p.priceId,productName:E.name??"",variantName:y.name??"",quantity:p.quantity??1,unitAmount:(h==null?void 0:h.amount)??0,totalAmount:((h==null?void 0:h.amount)??0)*(p.quantity??1),currency:t.selectedPresentmentCurrency??"USD",imageUrl:y.imageUrl??""}}),c=s.items??[];return{id:t.id,storeId:t.storeId,checkoutToken:t.checkoutToken,currency:t.selectedPresentmentCurrency??"USD",items:a,totals:{subtotal:s.subtotalAmount??0,discount:s.totalPromotionAmount??0,shipping:s.shippingCost??0,tax:s.totalTaxAmount??0,total:s.totalAmount??c.reduce((p,m)=>p+(m.amount??0),0),currency:s.currency??t.selectedPresentmentCurrency??"USD"},customer:r?{id:r.id,email:r.email,firstName:r.firstName,lastName:r.lastName}:void 0,shippingAddress:t.shippingAddress,billingAddress:t.billingAddress,metadata:t.metadata}}};var C=class{constructor(e,t,n){this.http=e;this.storeId=t;this.environment=n}async getPaymentSetup(e){let t=await this.http.get("/api/v1/payment-methods",{params:{checkoutSessionId:e}}),n={};for(let s of t.methods??[]){let i=s.provider?`${s.method}:${s.provider}`:s.method;n[i]=s}return n}async getExpressMethods(e){var s,i;let t=await this.getPaymentSetup(e),n={};for(let[,r]of Object.entries(t)){if(!r.enabled||!r.express)continue;let a=r.method,c={type:a,available:!0,processorId:r.processorId,publishableKey:r.publishableKey,metadata:r.metadata};if(a==="apple_pay"||r.type==="apple_pay"){let p=typeof window<"u"&&"ApplePaySession"in window&&((i=(s=window.ApplePaySession)==null?void 0:s.canMakePayments)==null?void 0:i.call(s));n.applePay={...c,available:!!p}}else a==="google_pay"||r.type==="google_pay"?n.googlePay=c:a==="paypal"?n.paypal=c:a==="klarna"||a==="klarna_express"?n.klarna=c:a==="link"&&(n.link=c)}return n}async getStoreConfig(){let e=await this.http.get("/api/v1/checkout/config",{params:{storeId:this.storeId}});return e.config??e}async getEnabledMethods(e){let t=await this.getPaymentSetup(e);return Object.entries(t).filter(([,n])=>n.enabled).map(([n])=>n)}async tokenizeCard(e){let t=await this.loadCoreJs(),n=new t.Tokenizer({environment:this.environment});await n.initialize();let s={cardNumber:e.cardNumber,expiryDate:e.expiryDate,cvc:e.cvc};e.cardholderName&&(s.cardholderName=e.cardholderName);let[i,r]=await Promise.all([n.tokenizeCard(s),n.tokenizeCardRaw(s)]);return{tagadaToken:i,rawToken:r}}async createInstrument(e){return this.http.post("/api/v1/payment/create-instrument-from-token",{tagadaToken:e.tagadaToken})}async create3dsSession(e){return this.http.post("/api/public/v1/threeds/create-session",{provider:e.provider??"basis_theory",storeId:this.storeId,paymentInstrumentId:e.paymentInstrumentId,sessionData:e.sessionData})}async pay(e){return e.tagadaToken&&!e.paymentInstrumentId?this.http.post("/api/v1/payment/pay-with-token",{tagadaToken:e.tagadaToken,checkoutSessionId:e.checkoutSessionId,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,metadata:e.metadata}):this.http.post("/api/public/v1/checkout/pay-v2",{checkoutSessionId:e.checkoutSessionId,paymentInstrumentId:e.paymentInstrumentId,storeId:this.storeId,paymentFlowId:e.paymentFlowId,threedsSessionId:e.threedsSessionId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,metadata:e.metadata})}async payDirect(e){return this.http.post("/api/public/v1/checkout/pay-v2",{checkoutSessionId:e.checkoutSessionId,paymentInstrumentId:e.paymentInstrumentId??"",storeId:this.storeId,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,threedsSessionId:e.threedsSessionId})}async processApplePay(e){let t=await this.loadCoreJs(),n=new t.Tokenizer({environment:this.environment});await n.initialize();let{tagadaToken:s}=await n.tokenizeApplePay(e.applePayToken);return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:s,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:"apple_pay",isExpress:!0})}async processGooglePay(e){let t=await this.loadCoreJs(),n=new t.Tokenizer({environment:this.environment});await n.initialize();let{tagadaToken:s}=await n.tokenizeGooglePay(e.googlePayToken);return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:s,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:"google_pay",isExpress:!0})}async processApm(e){return this.payDirect({checkoutSessionId:e.checkoutSessionId,paymentMethod:e.paymentMethod,processorId:e.processorId,paymentFlowId:e.paymentFlowId})}async getPaymentStatus(e){return this.http.get(`/api/v1/payments/${e}`)}async pollPaymentStatus(e,t){let n=(t==null?void 0:t.intervalMs)??1500,s=(t==null?void 0:t.timeoutMs)??6e4,i=Date.now();for(;Date.now()-i<s;){let r=await this.getPaymentStatus(e);if(r.status==="succeeded"||r.status==="failed"||r.status==="declined")return r;await new Promise(a=>setTimeout(a,n))}throw new Error(`Payment ${e} did not reach terminal status within ${s}ms.`)}async completeAfter3ds(e){return this.http.post("/api/v1/payments/complete-after-3ds",{paymentId:e})}async loadCoreJs(){try{return await import("@tagadapay/core-js")}catch{throw new Error("This method requires @tagadapay/core-js. Install it: npm install @tagadapay/core-js")}}};var T=class{constructor(e,t){this.http=e;this.storeId=t;this.pixels={loaded:!1};this.eventQueue=[];this.dedupeSet=new Set}async init(e){if(this.pixels.loaded)return;let t=e==null?void 0:e.pixelConfig;if(!t)try{t=(await this.http.get("/api/v1/checkout/config",{params:{storeId:this.storeId}})).pixels}catch{}this.pixels={loaded:!0,config:t},typeof window<"u"&&t&&this.loadPixelScripts(t),this.flushQueue()}trackPageView(e){this.fireEvent("PageView",{page:e??this.getCurrentPath()})}trackViewContent(e){this.fireEvent("ViewContent",e)}trackAddToCart(e){this.fireEvent("AddToCart",e)}trackInitiateCheckout(e){this.fireEvent("InitiateCheckout",e??{})}trackAddPaymentInfo(e){this.fireEvent("AddPaymentInfo",e??{})}trackPurchase(e){this.fireEvent("Purchase",e,!0)}trackCustomEvent(e,t){this.fireEvent(e,t??{})}trackStep(e){this.fireEvent("FunnelStep",e),this.http.post("/api/v1/funnel-tracking/step",{storeId:this.storeId,...e}).catch(()=>{})}trackConversion(e){this.fireEvent("Conversion",e,!0)}fireEvent(e,t,n=!1){if(n){let s=`${e}:${JSON.stringify(t)}`;if(this.dedupeSet.has(s))return;this.dedupeSet.add(s)}if(!this.pixels.loaded){this.eventQueue.push({event:e,data:t});return}this.sendToMeta(e,t),this.sendToTikTok(e,t),this.sendToSnapchat(e,t),this.sendToGTM(e,t),this.sendToGA(e,t)}flushQueue(){let e=[...this.eventQueue];this.eventQueue=[];for(let{event:t,data:n}of e)this.fireEvent(t,n)}getCurrentPath(){return typeof window<"u"?window.location.pathname:"/"}loadPixelScripts(e){e.metaPixelId&&this.loadMetaPixel(e.metaPixelId),e.tiktokPixelId&&this.loadTikTokPixel(e.tiktokPixelId),e.snapchatPixelId&&this.loadSnapchatPixel(e.snapchatPixelId),e.gtmId&&this.loadGTM(e.gtmId),e.gaId&&this.loadGA(e.gaId)}loadMetaPixel(e){if(typeof window>"u")return;let t=window;if(t.fbq)return;let n=t.fbq=function(...s){n.callMethod?n.callMethod(...s):n.queue.push(s)};n.queue=[],n.loaded=!0,n.version="2.0",this.injectScript("https://connect.facebook.net/en_US/fbevents.js"),t.fbq("init",e)}loadTikTokPixel(e){if(typeof window>"u")return;let t=window;if(t.ttq)return;let n={};n.methods=["page","track","identify","instances","debug","on","off","once","ready","alias","group","enableCookie","disableCookie"],n.setAndDefer=function(s,i){s[i]=function(...r){s.push([i,...r])}},t.ttq=n,this.injectScript("https://analytics.tiktok.com/i18n/pixel/events.js?sdkid="+e)}loadSnapchatPixel(e){if(typeof window>"u")return;let t=window;t.snaptr||(t.snaptr=function(...n){t.snaptr.handleRequest?t.snaptr.handleRequest(...n):t.snaptr.queue.push(n)},t.snaptr.queue=[],this.injectScript("https://sc-static.net/scevent.min.js"),t.snaptr("init",e))}loadGTM(e){if(typeof window>"u")return;let t=window;t.dataLayer=t.dataLayer??[],t.dataLayer.push({"gtm.start":Date.now(),event:"gtm.js"}),this.injectScript(`https://www.googletagmanager.com/gtm.js?id=${e}`)}loadGA(e){if(typeof window>"u")return;this.injectScript(`https://www.googletagmanager.com/gtag/js?id=${e}`);let t=window;t.dataLayer=t.dataLayer??[],t.gtag=function(...n){t.dataLayer.push(n)},t.gtag("js",new Date),t.gtag("config",e)}injectScript(e){if(typeof document>"u")return;let t=document.createElement("script");t.async=!0,t.src=e,document.head.appendChild(t)}sendToMeta(e,t){let n=typeof window<"u"?window:null,s=n==null?void 0:n.fbq;if(!s)return;let r={PageView:"PageView",ViewContent:"ViewContent",AddToCart:"AddToCart",InitiateCheckout:"InitiateCheckout",AddPaymentInfo:"AddPaymentInfo",Purchase:"Purchase"}[e];r?s("track",r,t):s("trackCustom",e,t)}sendToTikTok(e,t){var i,r;let n=typeof window<"u"?window:null,s=n==null?void 0:n.ttq;s&&(e==="PageView"?(i=s.page)==null||i.call(s):(r=s.track)==null||r.call(s,e,t))}sendToSnapchat(e,t){let n=typeof window<"u"?window:null,s=n==null?void 0:n.snaptr;if(!s)return;let r={PageView:"PAGE_VIEW",ViewContent:"VIEW_CONTENT",AddToCart:"ADD_CART",InitiateCheckout:"START_CHECKOUT",Purchase:"PURCHASE"}[e];r&&s("track",r,t)}sendToGTM(e,t){let n=typeof window<"u"?window:null,s=n==null?void 0:n.dataLayer;s&&s.push({event:e,...t})}sendToGA(e,t){let n=typeof window<"u"?window:null,s=n==null?void 0:n.gtag;s&&s("event",e,t)}};var S=class{constructor(e,t){this.http=e;this.storeId=t}async loadOffer(e){return(await this.http.get(`/api/v1/checkout-offers/${e}`,{params:{storeId:this.storeId}})).offer}async listOffers(e){return(await this.http.get("/api/v1/checkout-offers",{params:{storeId:this.storeId,type:e==null?void 0:e.type}})).offers}async acceptOffer(e){return this.http.post("/api/v1/checkout-offers/accept",{offerId:e.offerId,checkoutSessionId:e.checkoutSessionId,storeId:this.storeId,paymentInstrumentId:e.paymentInstrumentId})}async declineOffer(e){return this.http.post("/api/v1/checkout-offers/decline",{offerId:e.offerId,checkoutSessionId:e.checkoutSessionId,storeId:this.storeId})}async listOrderBumps(e){return(await this.http.get("/api/v1/checkout-offers",{params:{storeId:this.storeId,checkoutSessionId:e,type:"orderbump"}})).offers}async toggleOrderBump(e){await this.http.post(`/api/v1/checkout-sessions/${e.checkoutSessionId}/order-bumps`,{offerId:e.offerId,selected:e.selected})}};var b=class{constructor(e,t){this.http=e;this.storeId=t}async getProfile(e){return(await this.http.get(`/api/v1/customers/${e}`,{params:{storeId:this.storeId}})).customer}async getByEmail(e){try{return(await this.http.get("/api/v1/customers/by-email",{params:{email:e,storeId:this.storeId}})).customer}catch{return null}}async updateProfile(e,t){return(await this.http.patch(`/api/v1/customers/${e}`,{storeId:this.storeId,...t})).customer}async getOrders(e,t){return this.http.get(`/api/v1/customers/${e}/orders`,{params:{storeId:this.storeId,limit:t==null?void 0:t.limit,offset:t==null?void 0:t.offset}})}async getOrder(e){return(await this.http.get(`/api/v1/orders/${e}`,{params:{storeId:this.storeId}})).order}async getSubscriptions(e){return(await this.http.get(`/api/v1/customers/${e}/subscriptions`,{params:{storeId:this.storeId}})).subscriptions}async getSubscription(e){return(await this.http.get(`/api/v1/subscriptions/${e}`,{params:{storeId:this.storeId}})).subscription}};var R=class{constructor(e,t){this.http=e;this.storeId=t}async getProducts(e){var s,i;let t={storeId:this.storeId,includeVariants:!0,includePrices:!0};return(s=e==null?void 0:e.productIds)!=null&&s.length&&(t.productIds=e.productIds),(i=e==null?void 0:e.variantIds)!=null&&i.length&&(t.variantIds=e.variantIds),(await this.http.post("/api/v1/products",t)).items??[]}async getProduct(e){return(await this.getProducts({productIds:[e]}))[0]??null}};var A=class{constructor(e){let t=e.environment??"production",n=g.resolveBaseUrl(t,e.baseUrl);this.config={...e,environment:t,baseUrl:n,timeout:e.timeout??3e4},this.http=new g({baseUrl:n,timeout:this.config.timeout,apiKey:e.apiKey,getToken:()=>this._sessionToken});let s=i=>{this._sessionToken=i};this.checkout=new P(this.http,this.config.storeId,s),this.payment=new C(this.http,this.config.storeId,t),this.analytics=new T(this.http,this.config.storeId),this.offers=new S(this.http,this.config.storeId),this.customer=new b(this.http,this.config.storeId),this.catalog=new R(this.http,this.config.storeId)}setSessionToken(e){this._sessionToken=e}};function H(o){return new A(o)}return J(K);})();
6
+ "use strict";var TagadaHeadlessBundle=(()=>{var H=Object.create;var x=Object.defineProperty;var j=Object.getOwnPropertyDescriptor;var _=Object.getOwnPropertyNames;var D=Object.getPrototypeOf,F=Object.prototype.hasOwnProperty;var z=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var L=(n,e)=>{for(var t in e)x(n,t,{get:e[t],enumerable:!0})},M=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of _(e))!F.call(n,s)&&s!==t&&x(n,s,{get:()=>e[s],enumerable:!(r=j(e,s))||r.enumerable});return n};var B=(n,e,t)=>(t=n!=null?H(D(n)):{},M(e||!n||!n.__esModule?x(t,"default",{value:n,enumerable:!0}):t,n)),J=n=>M(x({},"__esModule",{value:!0}),n);var K={};L(K,{CatalogModule:()=>S,CheckoutModule:()=>v,CustomerModule:()=>b,HeadlessClient:()=>R,HttpClient:()=>g,OffersModule:()=>T,PaymentModule:()=>C,TagadaAuthError:()=>I,TagadaError:()=>c,TagadaNetworkError:()=>h,TagadaNotFoundError:()=>w,TagadaPaymentError:()=>E,TagadaRateLimitError:()=>P,TagadaValidationError:()=>k,createHeadlessClient:()=>N});var c=class extends Error{constructor(e,t,r,s){super(e),this.name="TagadaError",this.code=t,this.statusCode=r,this.details=s}},I=class extends c{constructor(e="Authentication failed. Check your API key or checkout token."){super(e,"auth_error",401),this.name="TagadaAuthError"}},k=class extends c{constructor(e,t=[]){super(e,"validation_error",422,{errors:t}),this.name="TagadaValidationError",this.errors=t}},w=class extends c{constructor(e,t){super(`${e} "${t}" not found.`,"not_found",404),this.name="TagadaNotFoundError"}},P=class extends c{constructor(e=1e3){super(`Rate limited. Retry after ${e}ms.`,"rate_limit",429),this.name="TagadaRateLimitError",this.retryAfterMs=e}},E=class extends c{constructor(e,t){super(e,"payment_error",void 0,t==null?void 0:t.details),this.name="TagadaPaymentError",this.paymentId=t==null?void 0:t.paymentId,this.requireAction=t==null?void 0:t.requireAction}},h=class extends c{constructor(e="Network request failed. Check your connection."){super(e,"network_error"),this.name="TagadaNetworkError"}};var q={production:"https://app.tagadapay.com",development:"https://app.dev.tagadapay.com",local:"http://localhost:3000"},g=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.timeout=e.timeout,this.apiKey=e.apiKey,this.getToken=e.getToken}static resolveBaseUrl(e,t){return t??q[e]??q.production}async request(e,t={}){var l;let{method:r="GET",body:s,headers:i={},params:o,token:a,signal:u}=t,m=`${this.baseUrl}${e}`;if(o){let d=new URLSearchParams;for(let[U,$]of Object.entries(o))$!==void 0&&d.set(U,String($));let O=d.toString();O&&(m+=`?${O}`)}let p={"Content-Type":"application/json",...i},y=a??this.apiKey??((l=this.getToken)==null?void 0:l.call(this));y&&(p["x-cms-token"]=y);let A=new AbortController,f=setTimeout(()=>A.abort(),this.timeout);try{let d=await fetch(m,{method:r,headers:p,body:s!=null?JSON.stringify(s):void 0,signal:u??A.signal});if(clearTimeout(f),d.ok){let O=await d.text();return O?JSON.parse(O):{}}throw await this.handleErrorResponse(d,e),new c("Unexpected error","unknown",d.status)}catch(d){throw clearTimeout(f),d instanceof c?d:d instanceof DOMException&&d.name==="AbortError"?new h(`Request to ${e} timed out after ${this.timeout}ms.`):new h(d instanceof Error?d.message:"Network request failed.")}}get(e,t){return this.request(e,{...t,method:"GET"})}post(e,t,r){return this.request(e,{...r,method:"POST",body:t})}patch(e,t,r){return this.request(e,{...r,method:"PATCH",body:t})}put(e,t,r){return this.request(e,{...r,method:"PUT",body:t})}delete(e,t){return this.request(e,{...t,method:"DELETE"})}async handleErrorResponse(e,t){let r={};try{r=await e.json()}catch{}let s=r.message??r.error??`Request failed: ${e.status} ${e.statusText} on ${t}`;switch(e.status){case 401:case 403:throw new I(s);case 404:throw new w(t,"");case 422:{let i=Array.isArray(r.errors)?r.errors:[];throw new k(s,i)}case 429:{let i=Number(e.headers.get("Retry-After")??"1")*1e3;throw new P(i)}default:throw new c(s,"api_error",e.status,r)}}};var v=class{constructor(e,t,r){this.http=e;this.storeId=t;this.onTokenChange=r}async loadSession(e,t){var s;t&&(this.sessionToken=t,(s=this.onTokenChange)==null||s.call(this,t));let r=await this.http.get(`/api/v1/checkout-sessions/${e}/v2`,{params:{skipAsyncWait:"false"},token:this.sessionToken});return this.normalizeSession(r)}async createSession(e){var a;let t=e.items.map(u=>({variantId:u.variantId,priceId:u.priceId,quantity:u.quantity})),r={storeId:this.storeId,lineItems:t};e.currency&&(r.currency=e.currency),e.returnUrl&&(r.returnUrl=e.returnUrl),e.customerEmail&&(r.customer={email:e.customerEmail,firstName:e.customerFirstName,lastName:e.customerLastName,currency:e.currency});let s=await this.http.post("/api/v1/checkout/session/init",r),o=new URL(s.checkoutUrl).searchParams.get("token")??"";return this.sessionToken=o,o&&((a=this.onTokenChange)==null||a.call(this,o)),{checkoutUrl:s.checkoutUrl,checkoutToken:s.checkoutToken,sessionToken:o,customerId:s.customerId}}async updateCart(e,t){return this.http.post(`/api/v1/checkout-sessions/${e}/line-items`,{items:t},{token:this.sessionToken})}async updateCustomer(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/customer-and-session-info`,{checkoutSessionId:e,partial:!0,customerData:{email:t.email},shippingAddress:{firstName:t.firstName,lastName:t.lastName,phone:t.phone},billingAddress:{},differentBillingAddress:!1},{token:this.sessionToken})}async updateAddress(e,t){let r=s=>{if(s)return{address1:s.line1,address2:s.line2,city:s.city,state:s.state,postal:s.postalCode,country:s.country}};await this.http.post(`/api/v1/checkout-sessions/${e}/address`,{checkoutSessionId:e,data:{shippingAddress:r(t.shippingAddress)??{},billingAddress:r(t.billingAddress)}},{token:this.sessionToken})}async applyPromoCode(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/promotions/apply`,{checkoutSessionId:e,code:t},{token:this.sessionToken})}async removePromoCode(e,t){let r=t??"default";await this.http.delete(`/api/v1/checkout-sessions/${e}/promotions/${r}`,{token:this.sessionToken})}async getShippingRates(e){return(await this.http.get(`/api/v1/checkout-sessions/${e}/shipping-rates`,{token:this.sessionToken})).rates??[]}async selectShippingRate(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/shipping-rate`,{checkoutSessionId:e,shippingRateId:t},{token:this.sessionToken})}normalizeSession(e){let t=e.checkoutSession,r=t.orderSummaries??[],s=e.summary??t.summary??r[0]??{},i=t.sessionLineItems??[],o=t.customer,a=i.map(m=>{let p=m.price,y=(p==null?void 0:p.variant)??{},A=y.product??{},f=(p==null?void 0:p.currencyOptions)??{},l=f.USD??f[Object.keys(f)[0]];return{id:m.id,variantId:m.variantId,priceId:m.priceId,productName:A.name??"",variantName:y.name??"",quantity:m.quantity??1,unitAmount:(l==null?void 0:l.amount)??0,totalAmount:((l==null?void 0:l.amount)??0)*(m.quantity??1),currency:t.selectedPresentmentCurrency??"USD",imageUrl:y.imageUrl??""}}),u=s.items??[];return{id:t.id,storeId:t.storeId,checkoutToken:t.checkoutToken,currency:t.selectedPresentmentCurrency??"USD",items:a,totals:{subtotal:s.subtotalAmount??0,discount:s.totalPromotionAmount??0,shipping:s.shippingCost??0,tax:s.totalTaxAmount??0,total:s.totalAmount??u.reduce((m,p)=>m+(p.amount??0),0),currency:s.currency??t.selectedPresentmentCurrency??"USD"},customer:o?{id:o.id,email:o.email,firstName:o.firstName,lastName:o.lastName}:void 0,shippingAddress:t.shippingAddress,billingAddress:t.billingAddress,metadata:t.metadata}}};var C=class{constructor(e,t,r){this.http=e;this.storeId=t;this.environment=r}async getPaymentSetup(e){let t=await this.http.get("/api/v1/payment-methods",{params:{checkoutSessionId:e}}),r={};for(let s of t.methods??[]){let i=s.provider?`${s.method}:${s.provider}`:s.method;r[i]=s}return r}async getExpressMethods(e){var s,i;let t=await this.getPaymentSetup(e),r={};for(let[,o]of Object.entries(t)){if(!o.enabled||!o.express)continue;let a=o.method,u={type:a,available:!0,processorId:o.processorId,publishableKey:o.publishableKey,metadata:o.metadata};if(a==="apple_pay"||o.type==="apple_pay"){let m=typeof window<"u"&&"ApplePaySession"in window&&((i=(s=window.ApplePaySession)==null?void 0:s.canMakePayments)==null?void 0:i.call(s));r.applePay={...u,available:!!m}}else a==="google_pay"||o.type==="google_pay"?r.googlePay=u:a==="paypal"?r.paypal=u:a==="klarna"||a==="klarna_express"?r.klarna=u:a==="link"&&(r.link=u)}return r}async getStoreConfig(){let e=await this.http.get("/api/v1/checkout/config",{params:{storeId:this.storeId}});return e.config??e}async getEnabledMethods(e){let t=await this.getPaymentSetup(e);return Object.entries(t).filter(([,r])=>r.enabled).map(([r])=>r)}async tokenizeCard(e){let t=await this.loadCoreJs(),r=new t.Tokenizer({environment:this.environment});await r.initialize();let s={cardNumber:e.cardNumber,expiryDate:e.expiryDate,cvc:e.cvc};e.cardholderName&&(s.cardholderName=e.cardholderName);let[i,o]=await Promise.all([r.tokenizeCard(s),r.tokenizeCardRaw(s)]);return{tagadaToken:i,rawToken:o}}async createInstrument(e){return this.http.post("/api/v1/payment/create-instrument-from-token",{tagadaToken:e.tagadaToken})}async create3dsSession(e){return this.http.post("/api/public/v1/threeds/create-session",{provider:e.provider??"basis_theory",storeId:this.storeId,paymentInstrumentId:e.paymentInstrumentId,sessionData:e.sessionData})}async pay(e){return e.tagadaToken&&!e.paymentInstrumentId?this.http.post("/api/v1/payment/pay-with-token",{tagadaToken:e.tagadaToken,checkoutSessionId:e.checkoutSessionId,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,metadata:e.metadata}):this.http.post("/api/public/v1/checkout/pay-v2",{checkoutSessionId:e.checkoutSessionId,paymentInstrumentId:e.paymentInstrumentId,storeId:this.storeId,paymentFlowId:e.paymentFlowId,threedsSessionId:e.threedsSessionId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,metadata:e.metadata})}async payDirect(e){return this.http.post("/api/public/v1/checkout/pay-v2",{checkoutSessionId:e.checkoutSessionId,paymentInstrumentId:e.paymentInstrumentId??"",storeId:this.storeId,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,threedsSessionId:e.threedsSessionId})}async processApplePay(e){let t=await this.loadCoreJs(),r=new t.Tokenizer({environment:this.environment});await r.initialize();let{tagadaToken:s}=await r.tokenizeApplePay(e.applePayToken);return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:s,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:"apple_pay",isExpress:!0})}async processGooglePay(e){let t=await this.loadCoreJs(),r=new t.Tokenizer({environment:this.environment});await r.initialize();let{tagadaToken:s}=await r.tokenizeGooglePay(e.googlePayToken);return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:s,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:"google_pay",isExpress:!0})}async processApm(e){return this.payDirect({checkoutSessionId:e.checkoutSessionId,paymentMethod:e.paymentMethod,processorId:e.processorId,paymentFlowId:e.paymentFlowId})}async getPaymentStatus(e){return this.http.get(`/api/v1/payments/${e}`)}async pollPaymentStatus(e,t){let r=(t==null?void 0:t.intervalMs)??1500,s=(t==null?void 0:t.timeoutMs)??6e4,i=Date.now();for(;Date.now()-i<s;){let o=await this.getPaymentStatus(e);if(o.status==="succeeded"||o.status==="failed"||o.status==="declined")return o;await new Promise(a=>setTimeout(a,r))}throw new Error(`Payment ${e} did not reach terminal status within ${s}ms.`)}async completeAfter3ds(e){return this.http.post("/api/v1/payments/complete-after-3ds",{paymentId:e})}async loadCoreJs(){try{return await import("@tagadapay/core-js")}catch{throw new Error("This method requires @tagadapay/core-js. Install it: npm install @tagadapay/core-js")}}};var T=class{constructor(e,t){this.http=e;this.storeId=t}async getOffer(e){return this.http.get(`/api/v1/offers/${e}`)}async listOffers(e){var i;let t=`/api/v1/stores/${this.storeId}/offers`,r=[];if(e!=null&&e.type&&r.push(`type=${encodeURIComponent(e.type)}`),(i=e==null?void 0:e.ids)!=null&&i.length)for(let o of e.ids)r.push(`ids=${encodeURIComponent(o)}`);return r.length&&(t+=`?${r.join("&")}`),(await this.http.get(t)).offers??[]}async previewOffer(e){return this.http.post(`/api/v1/offers/${e.offerId}/preview`,{offerId:e.offerId,currency:e.currency??"",lineItems:e.lineItems})}async payPreviewedOffer(e){return this.http.post(`/api/v1/offers/${e.offerId}/pay-preview`,{offerId:e.offerId,currency:e.currency??"",lineItems:e.lineItems,returnUrl:e.returnUrl??(typeof window<"u"?window.location.href:""),mainOrderId:e.mainOrderId,paymentInstrumentId:e.paymentInstrumentId})}async toggleOrderBump(e){return this.http.post(`/api/v1/checkout-sessions/${e.checkoutSessionId}/toggle-order-bump`,{orderBumpOfferId:e.orderBumpOfferId,selected:e.selected})}async listPostPurchaseOffers(e){let t=await this.http.get(`/api/v1/post-purchase/${e}/offers`);return Array.isArray(t)?t:[]}async acceptPostPurchaseOffer(e){return this.http.post(`/api/v1/orders/${e.orderId}/post-purchase-offers/${e.offerId}/accept`,{items:e.items??[]})}async declinePostPurchaseOffer(e){return this.http.post(`/api/v1/orders/${e.orderId}/post-purchase-offers/${e.offerId}/decline`)}};var b=class{constructor(e,t){this.http=e;this.storeId=t}async getProfile(e){return(await this.http.get(`/api/v1/customers/${e}`,{params:{storeId:this.storeId}})).customer}async getByEmail(e){try{return(await this.http.get("/api/v1/customers/by-email",{params:{email:e,storeId:this.storeId}})).customer}catch{return null}}async updateProfile(e,t){return(await this.http.patch(`/api/v1/customers/${e}`,{storeId:this.storeId,...t})).customer}async getOrders(e,t){return this.http.get(`/api/v1/customers/${e}/orders`,{params:{storeId:this.storeId,limit:t==null?void 0:t.limit,offset:t==null?void 0:t.offset}})}async getOrder(e){return(await this.http.get(`/api/v1/orders/${e}`,{params:{storeId:this.storeId}})).order}async getSubscriptions(e){return(await this.http.get(`/api/v1/customers/${e}/subscriptions`,{params:{storeId:this.storeId}})).subscriptions}async getSubscription(e){return(await this.http.get(`/api/v1/subscriptions/${e}`,{params:{storeId:this.storeId}})).subscription}};var S=class{constructor(e,t){this.http=e;this.storeId=t}async getProducts(e){var s,i;let t={storeId:this.storeId,includeVariants:!0,includePrices:!0};return(s=e==null?void 0:e.productIds)!=null&&s.length&&(t.productIds=e.productIds),(i=e==null?void 0:e.variantIds)!=null&&i.length&&(t.variantIds=e.variantIds),(await this.http.post("/api/v1/products",t)).items??[]}async getProduct(e){return(await this.getProducts({productIds:[e]}))[0]??null}};var R=class{constructor(e){let t=e.environment??"production",r=g.resolveBaseUrl(t,e.baseUrl);this.config={...e,environment:t,baseUrl:r,timeout:e.timeout??3e4},this.http=new g({baseUrl:r,timeout:this.config.timeout,apiKey:e.apiKey,getToken:()=>this._sessionToken});let s=i=>{this._sessionToken=i};this.checkout=new v(this.http,this.config.storeId,s),this.payment=new C(this.http,this.config.storeId,t),this.offers=new T(this.http,this.config.storeId),this.customer=new b(this.http,this.config.storeId),this.catalog=new S(this.http,this.config.storeId)}setSessionToken(e){this._sessionToken=e}};function N(n){return new R(n)}return J(K);})();
7
7
  if(typeof window!=="undefined"&&TagadaHeadlessBundle){ window.TagadaHeadless=TagadaHeadlessBundle; window.TagadaHeadless.create=TagadaHeadlessBundle.createHeadlessClient;}
8
8
  //# sourceMappingURL=tagada-headless.min.js.map