@tagadapay/headless-sdk 1.3.0 → 1.3.1

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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @tagadapay/headless-sdk
2
2
 
3
- Use TagadaPay as a **headless checkout, analytics, and CRM backend** from any website — React, Vue, vanilla JS, or plain HTML. Zero runtime dependencies in core.
3
+ Use TagadaPay as a **headless checkout and CRM backend** from any website — React, Vue, vanilla JS, or plain HTML. Zero runtime dependencies in core.
4
4
 
5
5
  ## Install
6
6
 
@@ -34,14 +34,6 @@ const result = await tagada.payment.pay({
34
34
  checkoutSessionId: session.id,
35
35
  tagadaToken,
36
36
  });
37
-
38
- if (result.payment.status === 'succeeded') {
39
- tagada.analytics.trackPurchase({
40
- orderId: result.payment.id,
41
- amount: result.payment.amount,
42
- currency: result.payment.currency,
43
- });
44
- }
45
37
  ```
46
38
 
47
39
  ## Quick Start (React)
@@ -77,9 +69,9 @@ function CheckoutPage() {
77
69
  |--------|-------------|
78
70
  | `tagada.checkout` | Session management — load, update cart, promo codes, shipping |
79
71
  | `tagada.payment` | Full payment lifecycle — APMs, tokenize, 3DS, pay, poll, express checkout |
80
- | `tagada.analytics` | Pixel tracking — auto-loads Meta/TikTok/Snap/GTM from store config |
81
- | `tagada.offers` | Post-purchase — load, accept, decline upsells and order bumps |
72
+ | `tagada.offers` | Upsells & order bumps — preview, pay, post-purchase accept/decline |
82
73
  | `tagada.customer` | CRM data — profile, orders, subscriptions |
74
+ | `tagada.catalog` | Product browsing — list products, variants, prices |
83
75
 
84
76
  ## CDN Usage
85
77
 
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @tagadapay/headless-sdk v1.3.0
3
- * Headless checkout, payments, analytics, and CRM
2
+ * @tagadapay/headless-sdk v1.3.1
3
+ * Headless checkout, payments, offers, and CRM
4
4
  * @license MIT
5
5
  */
6
6
  "use strict";var TagadaHeadlessReactBundle=(()=>{var Le=Object.create;var B=Object.defineProperty;var Ee=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var De=Object.getPrototypeOf,Ue=Object.prototype.hasOwnProperty;var L=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var Ne=(s,e)=>{for(var t in e)B(s,t,{get:e[t],enumerable:!0})},pe=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Te(e))!Ue.call(s,n)&&n!==t&&B(s,n,{get:()=>e[n],enumerable:!(r=Ee(e,n))||r.enumerable});return s};var $e=(s,e,t)=>(t=s!=null?Le(De(s)):{},pe(e||!s||!s.__esModule?B(t,"default",{value:s,enumerable:!0}):t,s)),Ge=s=>pe(B({},"__esModule",{value:!0}),s);var Be={};Ne(Be,{CurrencyUtils:()=>H,GoogleAutocompleteCore:()=>T,ISODataCore:()=>D,TagadaHeadlessProvider:()=>ye,formatMoney:()=>le,loadGoogleMapsScript:()=>j,useCatalog:()=>Ce,useCheckout:()=>Pe,useCountryOptions:()=>be,useCustomer:()=>we,useGoogleAutocomplete:()=>Re,useHeadlessClient:()=>x,useISOData:()=>ne,useOffers:()=>Ie,usePayment:()=>Se,useRegionOptions:()=>Oe});var $=L("react");var E=class extends Error{constructor(e,t,r,n){super(e),this.name="TagadaError",this.code=t,this.statusCode=r,this.details=n}},z=class extends E{constructor(e="Authentication failed. Check your API key or checkout token."){super(e,"auth_error",401),this.name="TagadaAuthError"}},J=class extends E{constructor(e,t=[]){super(e,"validation_error",422,{errors:t}),this.name="TagadaValidationError",this.errors=t}},Y=class extends E{constructor(e,t){super(`${e} "${t}" not found.`,"not_found",404),this.name="TagadaNotFoundError"}},V=class extends E{constructor(e=1e3){super(`Rate limited. Retry after ${e}ms.`,"rate_limit",429),this.name="TagadaRateLimitError",this.retryAfterMs=e}};var M=class extends E{constructor(e="Network request failed. Check your connection."){super(e,"network_error"),this.name="TagadaNetworkError"}};var me={production:"https://app.tagadapay.com",development:"https://app.dev.tagadapay.com",local:"http://localhost:3000"},_=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??me[e]??me.production}async request(e,t={}){var f;let{method:r="GET",body:n,headers:i={},params:o,token:c,signal:u}=t,a=`${this.baseUrl}${e}`;if(o){let y=new URLSearchParams;for(let[P,l]of Object.entries(o))l!==void 0&&y.set(P,String(l));let S=y.toString();S&&(a+=`?${S}`)}let d={"Content-Type":"application/json",...i},g=c??this.apiKey??((f=this.getToken)==null?void 0:f.call(this));g&&(d["x-cms-token"]=g);let h=new AbortController,p=setTimeout(()=>h.abort(),this.timeout);try{let y=await fetch(a,{method:r,headers:d,body:n!=null?JSON.stringify(n):void 0,signal:u??h.signal});if(clearTimeout(p),y.ok){let S=await y.text();return S?JSON.parse(S):{}}throw await this.handleErrorResponse(y,e),new E("Unexpected error","unknown",y.status)}catch(y){throw clearTimeout(p),y instanceof E?y:y instanceof DOMException&&y.name==="AbortError"?new M(`Request to ${e} timed out after ${this.timeout}ms.`):new M(y instanceof Error?y.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 n=r.message??r.error??`Request failed: ${e.status} ${e.statusText} on ${t}`;switch(e.status){case 401:case 403:throw new z(n);case 404:throw new Y(t,"");case 422:{let i=Array.isArray(r.errors)?r.errors:[];throw new J(n,i)}case 429:{let i=Number(e.headers.get("Retry-After")??"1")*1e3;throw new V(i)}default:throw new E(n,"api_error",e.status,r)}}};var W=class{constructor(e,t,r){this.http=e;this.storeId=t;this.onTokenChange=r}async loadSession(e,t){var n;t&&(this.sessionToken=t,(n=this.onTokenChange)==null||n.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 c;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 n=await this.http.post("/api/v1/checkout/session/init",r),o=new URL(n.checkoutUrl).searchParams.get("token")??"";return this.sessionToken=o,o&&((c=this.onTokenChange)==null||c.call(this,o)),{checkoutUrl:n.checkoutUrl,checkoutToken:n.checkoutToken,sessionToken:o,customerId:n.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=n=>{if(n)return{address1:n.line1,address2:n.line2,city:n.city,state:n.state,postal:n.postalCode,country:n.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??[],n=e.summary??t.summary??r[0]??{},i=t.sessionLineItems??[],o=t.customer,c=i.map(a=>{let d=a.price,g=(d==null?void 0:d.variant)??{},h=g.product??{},p=(d==null?void 0:d.currencyOptions)??{},f=p.USD??p[Object.keys(p)[0]];return{id:a.id,variantId:a.variantId,priceId:a.priceId,productName:h.name??"",variantName:g.name??"",quantity:a.quantity??1,unitAmount:(f==null?void 0:f.amount)??0,totalAmount:((f==null?void 0:f.amount)??0)*(a.quantity??1),currency:t.selectedPresentmentCurrency??"USD",imageUrl:g.imageUrl??""}}),u=n.items??[];return{id:t.id,storeId:t.storeId,checkoutToken:t.checkoutToken,currency:t.selectedPresentmentCurrency??"USD",items:c,totals:{subtotal:n.subtotalAmount??0,discount:n.totalPromotionAmount??0,shipping:n.shippingCost??0,tax:n.totalTaxAmount??0,total:n.totalAmount??u.reduce((a,d)=>a+(d.amount??0),0),currency:n.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 Z=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 n of t.methods??[]){let i=n.provider?`${n.method}:${n.provider}`:n.method;r[i]=n}return r}async getExpressMethods(e){var n,i;let t=await this.getPaymentSetup(e),r={};for(let[,o]of Object.entries(t)){if(!o.enabled||!o.express)continue;let c=o.method,u={type:c,available:!0,processorId:o.processorId,publishableKey:o.publishableKey,metadata:o.metadata};if(c==="apple_pay"||o.type==="apple_pay"){let a=typeof window<"u"&&"ApplePaySession"in window&&((i=(n=window.ApplePaySession)==null?void 0:n.canMakePayments)==null?void 0:i.call(n));r.applePay={...u,available:!!a}}else c==="google_pay"||o.type==="google_pay"?r.googlePay=u:c==="paypal"?r.paypal=u:c==="klarna"||c==="klarna_express"?r.klarna=u:c==="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 n={cardNumber:e.cardNumber,expiryDate:e.expiryDate,cvc:e.cvc};e.cardholderName&&(n.cardholderName=e.cardholderName);let[i,o]=await Promise.all([r.tokenizeCard(n),r.tokenizeCardRaw(n)]);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:n}=await r.tokenizeApplePay(e.applePayToken);return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:n,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:n}=await r.tokenizeGooglePay(e.googlePayToken);return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:n,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,n=(t==null?void 0:t.timeoutMs)??6e4,i=Date.now();for(;Date.now()-i<n;){let o=await this.getPaymentStatus(e);if(o.status==="succeeded"||o.status==="failed"||o.status==="declined")return o;await new Promise(c=>setTimeout(c,r))}throw new Error(`Payment ${e} did not reach terminal status within ${n}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 Q=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 X=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 ee=class{constructor(e,t){this.http=e;this.storeId=t}async getProducts(e){var n,i;let t={storeId:this.storeId,includeVariants:!0,includePrices:!0};return(n=e==null?void 0:e.productIds)!=null&&n.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 oe=class{constructor(e){let t=e.environment??"production",r=_.resolveBaseUrl(t,e.baseUrl);this.config={...e,environment:t,baseUrl:r,timeout:e.timeout??3e4},this.http=new _({baseUrl:r,timeout:this.config.timeout,apiKey:e.apiKey,getToken:()=>this._sessionToken});let n=i=>{this._sessionToken=i};this.checkout=new W(this.http,this.config.storeId,n),this.payment=new Z(this.http,this.config.storeId,t),this.offers=new Q(this.http,this.config.storeId),this.customer=new X(this.http,this.config.storeId),this.catalog=new ee(this.http,this.config.storeId)}setSessionToken(e){this._sessionToken=e}};function ge(s){return new oe(s)}var he=L("react/jsx-runtime"),fe=(0,$.createContext)(null);function ye({storeId:s,environment:e,apiKey:t,baseUrl:r,config:n,children:i}){let o=(0,$.useMemo)(()=>ge(n??{storeId:s,environment:e,apiKey:t,baseUrl:r}),[s,e,t,r,n]),c=(0,$.useMemo)(()=>({client:o}),[o]);return(0,he.jsx)(fe.Provider,{value:c,children:i})}function x(){let s=(0,$.useContext)(fe);if(!s)throw new Error("useHeadlessClient must be used within <TagadaHeadlessProvider>");return s.client}var A=L("react");function Pe(s,e){let t=x(),[r,n]=(0,A.useState)(null),[i,o]=(0,A.useState)(!1),[c,u]=(0,A.useState)(null),a=(0,A.useCallback)(async()=>{if(s){o(!0),u(null);try{let l=await t.checkout.loadSession(s,e);n(l)}catch(l){u(l instanceof Error?l:new Error(String(l)))}finally{o(!1)}}},[t,s,e]);(0,A.useEffect)(()=>{a()},[a]);let d=(0,A.useCallback)(async l=>{o(!0),u(null);try{let m=await t.checkout.createSession(l),I=new URL(window.location.href);I.searchParams.set("checkoutToken",m.checkoutToken),I.searchParams.set("token",m.sessionToken),window.history.replaceState({},"",I.toString());let U=await t.checkout.loadSession(m.checkoutToken,m.sessionToken);n(U)}catch(m){u(m instanceof Error?m:new Error(String(m)))}finally{o(!1)}},[t]),g=(0,A.useCallback)(async l=>{if(!r)return;let m=await t.checkout.updateCart(r.id,l);n(m)},[t,r]),h=(0,A.useCallback)(async l=>{if(r){o(!0);try{await t.checkout.updateCustomer(r.id,l),await a()}catch(m){u(m instanceof Error?m:new Error(String(m)))}finally{o(!1)}}},[t,r,a]),p=(0,A.useCallback)(async l=>{if(r){o(!0);try{await t.checkout.updateAddress(r.id,l),await a()}catch(m){u(m instanceof Error?m:new Error(String(m)))}finally{o(!1)}}},[t,r,a]),f=(0,A.useCallback)(async l=>{if(r){o(!0);try{await t.checkout.applyPromoCode(r.id,l),await a()}catch(m){u(m instanceof Error?m:new Error(String(m)))}finally{o(!1)}}},[t,r,a]),y=(0,A.useCallback)(async l=>{if(r){o(!0);try{await t.checkout.removePromoCode(r.id,l),await a()}catch(m){u(m instanceof Error?m:new Error(String(m)))}finally{o(!1)}}},[t,r,a]),S=(0,A.useCallback)(async()=>r?t.checkout.getShippingRates(r.id):[],[t,r]),P=(0,A.useCallback)(async l=>{if(r){o(!0);try{await t.checkout.selectShippingRate(r.id,l),await a()}catch(m){u(m instanceof Error?m:new Error(String(m)))}finally{o(!1)}}},[t,r,a]);return{session:r,isLoading:i,error:c,refresh:a,createSession:d,updateCart:g,updateCustomer:h,updateAddress:p,applyPromo:f,removePromo:y,getShippingRates:S,selectShippingRate:P}}var k=L("react");function Se(){let s=x(),[e,t]=(0,k.useState)(null),[r,n]=(0,k.useState)(null),[i,o]=(0,k.useState)(null),[c,u]=(0,k.useState)(!1),[a,d]=(0,k.useState)(null),[g,h]=(0,k.useState)(null),p=(0,k.useRef)(!1),f=(0,k.useCallback)(async C=>{if(!p.current){p.current=!0;try{let[w,R,xe]=await Promise.all([s.payment.getPaymentSetup(C),s.payment.getExpressMethods(C),s.payment.getStoreConfig()]);t(w),n(R),o(xe)}catch(w){p.current=!1,h(w instanceof Error?w:new Error(String(w)))}}},[s]),y=(0,k.useCallback)(C=>async()=>{u(!0),h(null);try{return await C()}catch(w){let R=w instanceof Error?w:new Error(String(w));throw h(R),R}finally{u(!1)}},[]),S=(0,k.useCallback)(async C=>{u(!0),h(null);try{let w=await s.payment.pay(C);return d(w),w}catch(w){let R=w instanceof Error?w:new Error(String(w));throw h(R),R}finally{u(!1)}},[s]),P=(0,k.useCallback)(C=>s.payment.tokenizeCard(C),[s]),l=(0,k.useCallback)(async C=>{let R=await y(()=>s.payment.processApplePay(C))();return d(R),R},[s,y]),m=(0,k.useCallback)(async C=>{let R=await y(()=>s.payment.processGooglePay(C))();return d(R),R},[s,y]),I=(0,k.useCallback)(async C=>{let R=await y(()=>s.payment.processApm(C))();return d(R),R},[s,y]),U=(0,k.useCallback)(C=>s.payment.pollPaymentStatus(C),[s]);return{paymentSetup:e,expressMethods:r,storeConfig:i,isProcessing:c,result:a,error:g,loadPaymentSetup:f,pay:S,tokenizeCard:P,processApplePay:l,processGooglePay:m,processApm:I,pollStatus:U}}var b=L("react");function Ie(){let s=x(),[e,t]=(0,b.useState)(null),[r,n]=(0,b.useState)(null),[i,o]=(0,b.useState)(!1),[c,u]=(0,b.useState)(null),a=(0,b.useCallback)(async l=>{o(!0),u(null);try{return await l()}catch(m){let I=m instanceof Error?m:new Error(String(m));throw u(I),I}finally{o(!1)}},[]),d=(0,b.useCallback)(l=>a(async()=>{let m=await s.offers.getOffer(l);return t(m),m}),[s,a]),g=(0,b.useCallback)(l=>s.offers.listOffers(l),[s]),h=(0,b.useCallback)(l=>a(async()=>{let m=await s.offers.previewOffer(l);return n(m),m}),[s,a]),p=(0,b.useCallback)(l=>a(()=>s.offers.payPreviewedOffer(l)),[s,a]),f=(0,b.useCallback)(l=>s.offers.toggleOrderBump(l),[s]),y=(0,b.useCallback)(l=>s.offers.listPostPurchaseOffers(l),[s]),S=(0,b.useCallback)(l=>a(()=>s.offers.acceptPostPurchaseOffer(l)),[s,a]),P=(0,b.useCallback)(l=>a(()=>s.offers.declinePostPurchaseOffer(l)),[s,a]);return{offer:e,preview:r,isLoading:i,error:c,getOffer:d,listOffers:g,previewOffer:h,payPreviewedOffer:p,toggleOrderBump:f,listPostPurchaseOffers:y,acceptPostPurchaseOffer:S,declinePostPurchaseOffer:P}}var O=L("react");function we(s){let e=x(),[t,r]=(0,O.useState)(null),[n,i]=(0,O.useState)([]),[o,c]=(0,O.useState)([]),[u,a]=(0,O.useState)(!1),[d,g]=(0,O.useState)(null),h=(0,O.useCallback)(async S=>{a(!0),g(null);try{let P=await e.customer.getProfile(S);r(P)}catch(P){g(P instanceof Error?P:new Error(String(P)))}finally{a(!1)}},[e]),p=(0,O.useCallback)(async S=>{try{let P=await e.customer.getOrders(S);i(P.orders)}catch(P){g(P instanceof Error?P:new Error(String(P)))}},[e]),f=(0,O.useCallback)(async S=>{try{let P=await e.customer.getSubscriptions(S);c(P)}catch(P){g(P instanceof Error?P:new Error(String(P)))}},[e]),y=(0,O.useCallback)(async(S,P)=>{try{let l=await e.customer.updateProfile(S,P);r(l)}catch(l){g(l instanceof Error?l:new Error(String(l)))}},[e]);return(0,O.useEffect)(()=>{s&&h(s)},[s,h]),{customer:t,orders:n,subscriptions:o,isLoading:u,error:d,loadCustomer:h,loadOrders:p,loadSubscriptions:f,updateProfile:y}}var G=L("react");function Ce(){let s=x(),[e,t]=(0,G.useState)([]),[r,n]=(0,G.useState)(!1),[i,o]=(0,G.useState)(null),c=(0,G.useCallback)(async a=>{n(!0),o(null);try{let d=await s.catalog.getProducts(a);return t(d),d}catch(d){let g=d instanceof Error?d:new Error(String(d));throw o(g),g}finally{n(!1)}},[s]),u=(0,G.useCallback)(async a=>{n(!0),o(null);try{return await s.catalog.getProduct(a)}catch(d){let g=d instanceof Error?d:new Error(String(d));throw o(g),g}finally{n(!1)}},[s]);return{products:e,isLoading:r,error:i,loadProducts:c,loadProduct:u}}var v=L("react");var ke=!1,ve=!1,te=[];function ie(){ve=!0;for(let s of te)s();te.length=0}function j(s,e={}){var t,r;return ve||(r=(t=window.google)==null?void 0:t.maps)!=null&&r.places?(ie(),Promise.resolve()):ke?new Promise(n=>te.push(n)):(ke=!0,new Promise((n,i)=>{if(te.push(n),document.querySelector('script[src*="maps.googleapis.com"]')){let a=()=>{var d,g;(g=(d=window.google)==null?void 0:d.maps)!=null&&g.places?ie():setTimeout(a,100)};a();return}let c=new URLSearchParams({key:s,libraries:"places",v:e.version??"weekly"});e.language&&c.set("language",e.language),e.region&&c.set("region",e.region);let u=document.createElement("script");u.src=`https://maps.googleapis.com/maps/api/js?${c}`,u.async=!0,u.defer=!0,u.onload=()=>ie(),u.onerror=()=>i(new Error("Failed to load Google Maps script")),document.head.appendChild(u)}))}var T=class s{static async searchPlaces(e,t={}){var n,i;if(!((i=(n=window.google)==null?void 0:n.maps)!=null&&i.places)||!e.trim())return[];let r=new window.google.maps.places.AutocompleteService;return new Promise(o=>{r.getPlacePredictions({input:e,types:t.types??["address"],componentRestrictions:t.componentRestrictions},(c,u)=>{var a,d,g;o(u===((g=(d=(a=window.google)==null?void 0:a.maps)==null?void 0:d.places)==null?void 0:g.PlacesServiceStatus.OK)&&c?c:[])})})}static async getPlaceDetails(e){var r,n;if(!((n=(r=window.google)==null?void 0:r.maps)!=null&&n.places))return null;let t=new window.google.maps.places.PlacesService(document.createElement("div"));return new Promise(i=>{t.getDetails({placeId:e,fields:["place_id","formatted_address","address_components","geometry"]},(o,c)=>{var u,a,d;i(c===((d=(a=(u=window.google)==null?void 0:u.maps)==null?void 0:a.places)==null?void 0:d.PlacesServiceStatus.OK)&&o?o:null)})})}static extractAddressComponents(e){let t={subpremise:"",streetNumber:"",route:"",locality:"",administrativeAreaLevel1:"",administrativeAreaLevel1Long:"",administrativeAreaLevel2:"",administrativeAreaLevel2Long:"",country:"",postalCode:"",fullStreetAddress:""},r="",n="",i="",o="",c="",u="",a="",d="";for(let p of e.address_components??[]){let f=p.types;f.includes("subpremise")&&(t.subpremise=p.long_name),f.includes("street_number")&&(t.streetNumber=p.long_name),f.includes("premise")&&(r=p.long_name),f.includes("route")&&(t.route=p.long_name),f.includes("neighborhood")&&(n=p.long_name),f.includes("sublocality_level_5")&&(i=p.long_name),f.includes("sublocality_level_4")&&(o=p.long_name),f.includes("sublocality_level_3")&&(c=p.long_name),f.includes("sublocality_level_2")&&(u=p.long_name),f.includes("sublocality_level_1")&&(a=p.long_name),f.includes("locality")&&(t.locality=p.long_name),f.includes("postal_town")&&(d=p.long_name),f.includes("administrative_area_level_2")&&(t.administrativeAreaLevel2=p.short_name,t.administrativeAreaLevel2Long=p.long_name),f.includes("administrative_area_level_1")&&(t.administrativeAreaLevel1=p.short_name,t.administrativeAreaLevel1Long=p.long_name),f.includes("country")&&(t.country=p.short_name),f.includes("postal_code")&&(t.postalCode=p.long_name)}t.locality||(t.locality=d||u||a||""),!t.administrativeAreaLevel1&&t.administrativeAreaLevel2&&(t.administrativeAreaLevel1=t.administrativeAreaLevel2Long||t.administrativeAreaLevel2,t.administrativeAreaLevel1Long=t.administrativeAreaLevel2Long);let g=t.streetNumber||r,h=t.route||i||o||c||n;if(t.subpremise&&g&&h)t.fullStreetAddress=`${t.subpremise}/${g} ${h}`;else if(g&&h)if(r&&o&&c){let p=`${c}-${o}-${r}`;u&&(p=`${p} ${u}`),t.fullStreetAddress=p}else t.fullStreetAddress=`${g} ${h}`;else h?t.fullStreetAddress=h:g&&(t.fullStreetAddress=g);return t.fullStreetAddress=t.fullStreetAddress.trim(),t}static extractFormattedAddress(e){let t=s.extractAddressComponents(e);return{address1:t.fullStreetAddress,city:t.locality,country:t.country,state:t.administrativeAreaLevel1,postal:t.postalCode}}};function Re(s){let{apiKey:e,language:t,region:r,version:n,defer:i=!1}=s,[o,c]=(0,v.useState)([]),[u,a]=(0,v.useState)(!1),[d,g]=(0,v.useState)(!1),h=(0,v.useRef)(null),p=(0,v.useRef)(null),f=(0,v.useCallback)(()=>{j(e,{language:t,region:r,version:n}).then(()=>g(!0))},[e,t,r,n]);(0,v.useEffect)(()=>{!e||i||f()},[e,i,f]),(0,v.useEffect)(()=>{if(d&&p.current){let{input:I,country:U}=p.current;p.current=null,y(I,U)}},[d]);let y=(0,v.useCallback)((I,U)=>{if(!d){i&&(p.current={input:I,country:U},f());return}if(I.length<3){c([]);return}h.current&&clearTimeout(h.current),h.current=setTimeout(async()=>{a(!0);let C=await T.searchPlaces(I,{componentRestrictions:U?{country:U.toLowerCase()}:void 0});c(C),a(!1)},300)},[d,i,f]),S=(0,v.useCallback)(I=>T.getPlaceDetails(I),[]),P=(0,v.useCallback)(I=>T.extractAddressComponents(I),[]),l=(0,v.useCallback)(I=>T.extractFormattedAddress(I),[]),m=(0,v.useCallback)(()=>c([]),[]);return{predictions:o,isLoading:u,isScriptLoaded:d,searchPlaces:y,getPlaceDetails:S,extractAddressComponents:P,extractFormattedAddress:l,clearPredictions:m}}var N=L("react");var Ae="https://cvwnizdbugpz6jwk.public.blob.vercel-storage.com/geodata/v1",ue=["en","ru","de","da","fr","es","zh","hi","pt","ja","ar","it","he"],K=new Map,re=new Map,ae=new Map,ce=new Map;async function He(s){let e=K.get(s);if(e)return e;let t=ae.get(s);return t||(t=(async()=>{let r=`${Ae}/${s}/countries.json`,n=await fetch(r);if(!n.ok)throw new Error(`Geodata fetch failed: ${r} (${n.status})`);let i=await n.json();return K.set(s,i),ae.delete(s),i})(),ae.set(s,t),t)}async function Me(s){let e=re.get(s);if(e)return e;let t=ce.get(s);return t||(t=(async()=>{let r=`${Ae}/${s}/regions.json`,n=await fetch(r);if(!n.ok)throw new Error(`Geodata fetch failed: ${r} (${n.status})`);let i=await n.json();return re.set(s,i),ce.delete(s),i})(),ce.set(s,t),t)}function _e(s){return K.get(s)||K.get("en")||{}}function je(s){return re.get(s)||re.get("en")||{}}async function F(s="en"){await Promise.all([He(s),Me(s)])}var se=(s="en")=>{let e=_e(s);return Object.entries(e).map(([t,r])=>({code:t,name:r.n,iso3:r.i3,numeric:r.nu})).sort((t,r)=>t.name.localeCompare(r.name))},de=(s,e="en")=>{let r=je(e)[s];return r?r.map(([n,i])=>({code:n,name:i,countryCode:s})).sort((n,i)=>n.name.localeCompare(i.name)):[]};function q(s){return K.has(s)}var D=class s{static ensureLoaded(e="en"){return F(e)}static getCountries(e="en"){let t=se(e),r={};for(let n of t)r[n.code]={iso:n.code,iso3:n.iso3??"",numeric:n.numeric??0,name:n.name};return r}static getCountryOptions(e="en"){return se(e).map(t=>({value:t.code,label:t.name}))}static getRegions(e,t="en"){return de(e,t).map(r=>({iso:r.code,name:r.name}))}static getRegionOptions(e,t="en"){return s.getRegions(e,t).map(r=>({value:r.iso,label:r.name}))}static findRegion(e,t,r="en"){return s.getRegions(e,r).find(n=>n.iso===t)??null}static mapGoogleToISO(e,t,r,n="en"){let i=s.getRegions(r,n);if(i.length===0)return null;let o=i.find(c=>c.iso===e);return o||(o=i.find(c=>c.name.toLowerCase()===e.toLowerCase()),o)||(o=i.find(c=>c.name.toLowerCase()===t.toLowerCase()),o)?o:(o=i.find(c=>c.name.toLowerCase().includes(t.toLowerCase())||t.toLowerCase().includes(c.name.toLowerCase())),o??null)}static isLanguageLoaded(e){return q(e)}static getAvailableLanguages(){return ue}};function ne(s="en"){let[e,t]=(0,N.useState)(q(s));return(0,N.useEffect)(()=>{let r=!1;return F(s).then(()=>{r||t(!0)}).catch(n=>console.error("[headless-sdk] Failed to load geodata:",n)),()=>{r=!0}},[s]),(0,N.useMemo)(()=>e?{countries:D.getCountries(s),getRegions:r=>D.getRegions(r,s),findRegion:(r,n)=>D.findRegion(r,n,s),mapGoogleToISO:(r,n,i)=>D.mapGoogleToISO(r,n,i,s),isLoaded:!0}:{countries:{},getRegions:()=>[],findRegion:()=>null,mapGoogleToISO:()=>null,isLoaded:!1},[s,e])}function be(s="en"){let{countries:e,isLoaded:t}=ne(s);return(0,N.useMemo)(()=>t?Object.values(e).map(r=>({value:r.iso,label:r.name})).sort((r,n)=>r.label.localeCompare(n.label)):[],[e,t])}function Oe(s,e="en"){let{getRegions:t,isLoaded:r}=ne(e);return(0,N.useMemo)(()=>!r||!s?[]:t(s).map(n=>({value:n.iso,label:n.name})).sort((n,i)=>n.label.localeCompare(i.label)),[s,t,r])}var Ke={USD:"$",EUR:"\u20AC",GBP:"\xA3",JPY:"\xA5",CAD:"C$",AUD:"A$",CHF:"CHF",CNY:"\xA5",SEK:"kr",NOK:"kr",DKK:"kr",PLN:"z\u0142",CZK:"K\u010D",HUF:"Ft",RON:"lei",BGN:"\u043B\u0432",HRK:"kn",RUB:"\u20BD",UAH:"\u20B4",TRY:"\u20BA",BRL:"R$",MXN:"$",ZAR:"R",INR:"\u20B9",KRW:"\u20A9",THB:"\u0E3F",VND:"\u20AB",IDR:"Rp",MYR:"RM",SGD:"S$",PHP:"\u20B1",TWD:"NT$",HKD:"HK$",ILS:"\u20AA",AED:"\u062F.\u0625",SAR:"\u0631.\u0633",QAR:"\u0631.\u0642",KWD:"\u062F.\u0643",BHD:"\u062F.\u0628",OMR:"\u0631.\u0639.",EGP:"\xA3",NGN:"\u20A6",KES:"KSh",GHS:"\u20B5",COP:"$",ARS:"$",CLP:"$",PEN:"S/",CRC:"\u20A1",DOP:"RD$",JMD:"J$",BOB:"Bs",PYG:"\u20B2",GTQ:"Q",NIO:"C$",PAB:"B/.",PKR:"\u20A8",BDT:"\u09F3",LKR:"\u20A8",NPR:"\u20A8",GEL:"\u20BE",AMD:"\u058F",AZN:"\u20BC",KZT:"\u20B8"},Fe={USD:"US Dollar",EUR:"Euro",GBP:"British Pound",JPY:"Japanese Yen",CAD:"Canadian Dollar",AUD:"Australian Dollar",CHF:"Swiss Franc",CNY:"Chinese Yuan",SEK:"Swedish Krona",NOK:"Norwegian Krone",DKK:"Danish Krone",PLN:"Polish Zloty",CZK:"Czech Koruna",HUF:"Hungarian Forint",BRL:"Brazilian Real",MXN:"Mexican Peso",INR:"Indian Rupee",KRW:"South Korean Won",THB:"Thai Baht",SGD:"Singapore Dollar",HKD:"Hong Kong Dollar",TWD:"Taiwan Dollar",ILS:"Israeli Shekel",AED:"UAE Dirham",SAR:"Saudi Riyal",ZAR:"South African Rand",TRY:"Turkish Lira",RUB:"Russian Ruble",NGN:"Nigerian Naira"},qe=new Set(["JPY","KRW","VND","IDR","LAK","KHR","MMK","PYG"]),H=class s{static getSymbol(e){return Ke[e]??e}static getName(e){return Fe[e]??e}static getDecimalPlaces(e){return qe.has(e)?0:2}static getCurrency(e){return{code:e,symbol:s.getSymbol(e),name:s.getName(e),decimalPlaces:s.getDecimalPlaces(e)}}};function le(s,e="USD",t="en-US"){let r=H.getDecimalPlaces(e),n=s/(r===0?100:Math.pow(10,r));try{return new Intl.NumberFormat(t,{style:"currency",currency:e,minimumFractionDigits:r,maximumFractionDigits:r}).format(n)}catch{return`${H.getSymbol(e)}${n.toFixed(r)}`}}return Ge(Be);})();
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @tagadapay/headless-sdk v1.3.0
3
- * Headless checkout, payments, analytics, and CRM
2
+ * @tagadapay/headless-sdk v1.3.1
3
+ * Headless checkout, payments, offers, and CRM
4
4
  * @license MIT
5
5
  */
6
6
  "use strict";
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @tagadapay/headless-sdk v1.3.0
3
- * Headless checkout, payments, analytics, and CRM
2
+ * @tagadapay/headless-sdk v1.3.1
3
+ * Headless checkout, payments, offers, and CRM
4
4
  * @license MIT
5
5
  */
6
6
  "use strict";var TagadaHeadlessBundle=(()=>{var re=Object.create;var G=Object.defineProperty;var se=Object.getOwnPropertyDescriptor;var ne=Object.getOwnPropertyNames;var oe=Object.getPrototypeOf,ie=Object.prototype.hasOwnProperty;var ae=(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 ce=(n,e)=>{for(var t in e)G(n,t,{get:e[t],enumerable:!0})},V=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ne(e))!ie.call(n,s)&&s!==t&&G(n,s,{get:()=>e[s],enumerable:!(r=se(e,s))||r.enumerable});return n};var de=(n,e,t)=>(t=n!=null?re(oe(n)):{},V(e||!n||!n.__esModule?G(t,"default",{value:n,enumerable:!0}):t,n)),ue=n=>V(G({},"__esModule",{value:!0}),n);var Ie={};ce(Ie,{AVAILABLE_LANGUAGES:()=>D,CatalogModule:()=>L,CheckoutModule:()=>C,CurrencyUtils:()=>w,CustomerModule:()=>R,GoogleAutocompleteCore:()=>E,HeadlessClient:()=>O,HttpClient:()=>I,ISODataCore:()=>U,OffersModule:()=>b,PaymentModule:()=>A,TagadaAuthError:()=>P,TagadaError:()=>y,TagadaNetworkError:()=>f,TagadaNotFoundError:()=>S,TagadaPaymentError:()=>H,TagadaRateLimitError:()=>v,TagadaValidationError:()=>k,createHeadlessClient:()=>Z,ensureGeoDataLoaded:()=>N,formatMoney:()=>J,getCountries:()=>T,getStatesForCountry:()=>_,isLanguageLoaded:()=>M,loadGoogleMapsScript:()=>B});var y=class extends Error{constructor(e,t,r,s){super(e),this.name="TagadaError",this.code=t,this.statusCode=r,this.details=s}},P=class extends y{constructor(e="Authentication failed. Check your API key or checkout token."){super(e,"auth_error",401),this.name="TagadaAuthError"}},k=class extends y{constructor(e,t=[]){super(e,"validation_error",422,{errors:t}),this.name="TagadaValidationError",this.errors=t}},S=class extends y{constructor(e,t){super(`${e} "${t}" not found.`,"not_found",404),this.name="TagadaNotFoundError"}},v=class extends y{constructor(e=1e3){super(`Rate limited. Retry after ${e}ms.`,"rate_limit",429),this.name="TagadaRateLimitError",this.retryAfterMs=e}},H=class extends y{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}},f=class extends y{constructor(e="Network request failed. Check your connection."){super(e,"network_error"),this.name="TagadaNetworkError"}};var W={production:"https://app.tagadapay.com",development:"https://app.dev.tagadapay.com",local:"http://localhost:3000"},I=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??W[e]??W.production}async request(e,t={}){var u;let{method:r="GET",body:s,headers:i={},params:o,token:a,signal:c}=t,l=`${this.baseUrl}${e}`;if(o){let g=new URLSearchParams;for(let[te,Y]of Object.entries(o))Y!==void 0&&g.set(te,String(Y));let x=g.toString();x&&(l+=`?${x}`)}let m={"Content-Type":"application/json",...i},p=a??this.apiKey??((u=this.getToken)==null?void 0:u.call(this));p&&(m["x-cms-token"]=p);let h=new AbortController,d=setTimeout(()=>h.abort(),this.timeout);try{let g=await fetch(l,{method:r,headers:m,body:s!=null?JSON.stringify(s):void 0,signal:c??h.signal});if(clearTimeout(d),g.ok){let x=await g.text();return x?JSON.parse(x):{}}throw await this.handleErrorResponse(g,e),new y("Unexpected error","unknown",g.status)}catch(g){throw clearTimeout(d),g instanceof y?g:g instanceof DOMException&&g.name==="AbortError"?new f(`Request to ${e} timed out after ${this.timeout}ms.`):new f(g instanceof Error?g.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 P(s);case 404:throw new S(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 v(i)}default:throw new y(s,"api_error",e.status,r)}}};var C=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(c=>({variantId:c.variantId,priceId:c.priceId,quantity:c.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(l=>{let m=l.price,p=(m==null?void 0:m.variant)??{},h=p.product??{},d=(m==null?void 0:m.currencyOptions)??{},u=d.USD??d[Object.keys(d)[0]];return{id:l.id,variantId:l.variantId,priceId:l.priceId,productName:h.name??"",variantName:p.name??"",quantity:l.quantity??1,unitAmount:(u==null?void 0:u.amount)??0,totalAmount:((u==null?void 0:u.amount)??0)*(l.quantity??1),currency:t.selectedPresentmentCurrency??"USD",imageUrl:p.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((l,m)=>l+(m.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 A=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,c={type:a,available:!0,processorId:o.processorId,publishableKey:o.publishableKey,metadata:o.metadata};if(a==="apple_pay"||o.type==="apple_pay"){let l=typeof window<"u"&&"ApplePaySession"in window&&((i=(s=window.ApplePaySession)==null?void 0:s.canMakePayments)==null?void 0:i.call(s));r.applePay={...c,available:!!l}}else a==="google_pay"||o.type==="google_pay"?r.googlePay=c:a==="paypal"?r.paypal=c:a==="klarna"||a==="klarna_express"?r.klarna=c:a==="link"&&(r.link=c)}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 b=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 R=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 L=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 O=class{constructor(e){let t=e.environment??"production",r=I.resolveBaseUrl(t,e.baseUrl);this.config={...e,environment:t,baseUrl:r,timeout:e.timeout??3e4},this.http=new I({baseUrl:r,timeout:this.config.timeout,apiKey:e.apiKey,getToken:()=>this._sessionToken});let s=i=>{this._sessionToken=i};this.checkout=new C(this.http,this.config.storeId,s),this.payment=new A(this.http,this.config.storeId,t),this.offers=new b(this.http,this.config.storeId),this.customer=new R(this.http,this.config.storeId),this.catalog=new L(this.http,this.config.storeId)}setSessionToken(e){this._sessionToken=e}};function Z(n){return new O(n)}var Q=!1,X=!1,K=[];function q(){X=!0;for(let n of K)n();K.length=0}function B(n,e={}){var t,r;return X||(r=(t=window.google)==null?void 0:t.maps)!=null&&r.places?(q(),Promise.resolve()):Q?new Promise(s=>K.push(s)):(Q=!0,new Promise((s,i)=>{if(K.push(s),document.querySelector('script[src*="maps.googleapis.com"]')){let l=()=>{var m,p;(p=(m=window.google)==null?void 0:m.maps)!=null&&p.places?q():setTimeout(l,100)};l();return}let a=new URLSearchParams({key:n,libraries:"places",v:e.version??"weekly"});e.language&&a.set("language",e.language),e.region&&a.set("region",e.region);let c=document.createElement("script");c.src=`https://maps.googleapis.com/maps/api/js?${a}`,c.async=!0,c.defer=!0,c.onload=()=>q(),c.onerror=()=>i(new Error("Failed to load Google Maps script")),document.head.appendChild(c)}))}var E=class n{static async searchPlaces(e,t={}){var s,i;if(!((i=(s=window.google)==null?void 0:s.maps)!=null&&i.places)||!e.trim())return[];let r=new window.google.maps.places.AutocompleteService;return new Promise(o=>{r.getPlacePredictions({input:e,types:t.types??["address"],componentRestrictions:t.componentRestrictions},(a,c)=>{var l,m,p;o(c===((p=(m=(l=window.google)==null?void 0:l.maps)==null?void 0:m.places)==null?void 0:p.PlacesServiceStatus.OK)&&a?a:[])})})}static async getPlaceDetails(e){var r,s;if(!((s=(r=window.google)==null?void 0:r.maps)!=null&&s.places))return null;let t=new window.google.maps.places.PlacesService(document.createElement("div"));return new Promise(i=>{t.getDetails({placeId:e,fields:["place_id","formatted_address","address_components","geometry"]},(o,a)=>{var c,l,m;i(a===((m=(l=(c=window.google)==null?void 0:c.maps)==null?void 0:l.places)==null?void 0:m.PlacesServiceStatus.OK)&&o?o:null)})})}static extractAddressComponents(e){let t={subpremise:"",streetNumber:"",route:"",locality:"",administrativeAreaLevel1:"",administrativeAreaLevel1Long:"",administrativeAreaLevel2:"",administrativeAreaLevel2Long:"",country:"",postalCode:"",fullStreetAddress:""},r="",s="",i="",o="",a="",c="",l="",m="";for(let d of e.address_components??[]){let u=d.types;u.includes("subpremise")&&(t.subpremise=d.long_name),u.includes("street_number")&&(t.streetNumber=d.long_name),u.includes("premise")&&(r=d.long_name),u.includes("route")&&(t.route=d.long_name),u.includes("neighborhood")&&(s=d.long_name),u.includes("sublocality_level_5")&&(i=d.long_name),u.includes("sublocality_level_4")&&(o=d.long_name),u.includes("sublocality_level_3")&&(a=d.long_name),u.includes("sublocality_level_2")&&(c=d.long_name),u.includes("sublocality_level_1")&&(l=d.long_name),u.includes("locality")&&(t.locality=d.long_name),u.includes("postal_town")&&(m=d.long_name),u.includes("administrative_area_level_2")&&(t.administrativeAreaLevel2=d.short_name,t.administrativeAreaLevel2Long=d.long_name),u.includes("administrative_area_level_1")&&(t.administrativeAreaLevel1=d.short_name,t.administrativeAreaLevel1Long=d.long_name),u.includes("country")&&(t.country=d.short_name),u.includes("postal_code")&&(t.postalCode=d.long_name)}t.locality||(t.locality=m||c||l||""),!t.administrativeAreaLevel1&&t.administrativeAreaLevel2&&(t.administrativeAreaLevel1=t.administrativeAreaLevel2Long||t.administrativeAreaLevel2,t.administrativeAreaLevel1Long=t.administrativeAreaLevel2Long);let p=t.streetNumber||r,h=t.route||i||o||a||s;if(t.subpremise&&p&&h)t.fullStreetAddress=`${t.subpremise}/${p} ${h}`;else if(p&&h)if(r&&o&&a){let d=`${a}-${o}-${r}`;c&&(d=`${d} ${c}`),t.fullStreetAddress=d}else t.fullStreetAddress=`${p} ${h}`;else h?t.fullStreetAddress=h:p&&(t.fullStreetAddress=p);return t.fullStreetAddress=t.fullStreetAddress.trim(),t}static extractFormattedAddress(e){let t=n.extractAddressComponents(e);return{address1:t.fullStreetAddress,city:t.locality,country:t.country,state:t.administrativeAreaLevel1,postal:t.postalCode}}};var ee="https://cvwnizdbugpz6jwk.public.blob.vercel-storage.com/geodata/v1",D=["en","ru","de","da","fr","es","zh","hi","pt","ja","ar","it","he"],$=new Map,F=new Map,j=new Map,z=new Map;async function le(n){let e=$.get(n);if(e)return e;let t=j.get(n);return t||(t=(async()=>{let r=`${ee}/${n}/countries.json`,s=await fetch(r);if(!s.ok)throw new Error(`Geodata fetch failed: ${r} (${s.status})`);let i=await s.json();return $.set(n,i),j.delete(n),i})(),j.set(n,t),t)}async function me(n){let e=F.get(n);if(e)return e;let t=z.get(n);return t||(t=(async()=>{let r=`${ee}/${n}/regions.json`,s=await fetch(r);if(!s.ok)throw new Error(`Geodata fetch failed: ${r} (${s.status})`);let i=await s.json();return F.set(n,i),z.delete(n),i})(),z.set(n,t),t)}function pe(n){return $.get(n)||$.get("en")||{}}function ge(n){return F.get(n)||F.get("en")||{}}async function N(n="en"){await Promise.all([le(n),me(n)])}var T=(n="en")=>{let e=pe(n);return Object.entries(e).map(([t,r])=>({code:t,name:r.n,iso3:r.i3,numeric:r.nu})).sort((t,r)=>t.name.localeCompare(r.name))},_=(n,e="en")=>{let r=ge(e)[n];return r?r.map(([s,i])=>({code:s,name:i,countryCode:n})).sort((s,i)=>s.name.localeCompare(i.name)):[]};function M(n){return $.has(n)}var U=class n{static ensureLoaded(e="en"){return N(e)}static getCountries(e="en"){let t=T(e),r={};for(let s of t)r[s.code]={iso:s.code,iso3:s.iso3??"",numeric:s.numeric??0,name:s.name};return r}static getCountryOptions(e="en"){return T(e).map(t=>({value:t.code,label:t.name}))}static getRegions(e,t="en"){return _(e,t).map(r=>({iso:r.code,name:r.name}))}static getRegionOptions(e,t="en"){return n.getRegions(e,t).map(r=>({value:r.iso,label:r.name}))}static findRegion(e,t,r="en"){return n.getRegions(e,r).find(s=>s.iso===t)??null}static mapGoogleToISO(e,t,r,s="en"){let i=n.getRegions(r,s);if(i.length===0)return null;let o=i.find(a=>a.iso===e);return o||(o=i.find(a=>a.name.toLowerCase()===e.toLowerCase()),o)||(o=i.find(a=>a.name.toLowerCase()===t.toLowerCase()),o)?o:(o=i.find(a=>a.name.toLowerCase().includes(t.toLowerCase())||t.toLowerCase().includes(a.name.toLowerCase())),o??null)}static isLanguageLoaded(e){return M(e)}static getAvailableLanguages(){return D}};var ye={USD:"$",EUR:"\u20AC",GBP:"\xA3",JPY:"\xA5",CAD:"C$",AUD:"A$",CHF:"CHF",CNY:"\xA5",SEK:"kr",NOK:"kr",DKK:"kr",PLN:"z\u0142",CZK:"K\u010D",HUF:"Ft",RON:"lei",BGN:"\u043B\u0432",HRK:"kn",RUB:"\u20BD",UAH:"\u20B4",TRY:"\u20BA",BRL:"R$",MXN:"$",ZAR:"R",INR:"\u20B9",KRW:"\u20A9",THB:"\u0E3F",VND:"\u20AB",IDR:"Rp",MYR:"RM",SGD:"S$",PHP:"\u20B1",TWD:"NT$",HKD:"HK$",ILS:"\u20AA",AED:"\u062F.\u0625",SAR:"\u0631.\u0633",QAR:"\u0631.\u0642",KWD:"\u062F.\u0643",BHD:"\u062F.\u0628",OMR:"\u0631.\u0639.",EGP:"\xA3",NGN:"\u20A6",KES:"KSh",GHS:"\u20B5",COP:"$",ARS:"$",CLP:"$",PEN:"S/",CRC:"\u20A1",DOP:"RD$",JMD:"J$",BOB:"Bs",PYG:"\u20B2",GTQ:"Q",NIO:"C$",PAB:"B/.",PKR:"\u20A8",BDT:"\u09F3",LKR:"\u20A8",NPR:"\u20A8",GEL:"\u20BE",AMD:"\u058F",AZN:"\u20BC",KZT:"\u20B8"},he={USD:"US Dollar",EUR:"Euro",GBP:"British Pound",JPY:"Japanese Yen",CAD:"Canadian Dollar",AUD:"Australian Dollar",CHF:"Swiss Franc",CNY:"Chinese Yuan",SEK:"Swedish Krona",NOK:"Norwegian Krone",DKK:"Danish Krone",PLN:"Polish Zloty",CZK:"Czech Koruna",HUF:"Hungarian Forint",BRL:"Brazilian Real",MXN:"Mexican Peso",INR:"Indian Rupee",KRW:"South Korean Won",THB:"Thai Baht",SGD:"Singapore Dollar",HKD:"Hong Kong Dollar",TWD:"Taiwan Dollar",ILS:"Israeli Shekel",AED:"UAE Dirham",SAR:"Saudi Riyal",ZAR:"South African Rand",TRY:"Turkish Lira",RUB:"Russian Ruble",NGN:"Nigerian Naira"},fe=new Set(["JPY","KRW","VND","IDR","LAK","KHR","MMK","PYG"]),w=class n{static getSymbol(e){return ye[e]??e}static getName(e){return he[e]??e}static getDecimalPlaces(e){return fe.has(e)?0:2}static getCurrency(e){return{code:e,symbol:n.getSymbol(e),name:n.getName(e),decimalPlaces:n.getDecimalPlaces(e)}}};function J(n,e="USD",t="en-US"){let r=w.getDecimalPlaces(e),s=n/(r===0?100:Math.pow(10,r));try{return new Intl.NumberFormat(t,{style:"currency",currency:e,minimumFractionDigits:r,maximumFractionDigits:r}).format(s)}catch{return`${w.getSymbol(e)}${s.toFixed(r)}`}}return ue(Ie);})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tagadapay/headless-sdk",
3
- "version": "1.3.0",
3
+ "version": "1.3.1",
4
4
  "description": "Headless SDK for using TagadaPay as a checkout, offers, and CRM backend from any external website",
5
5
  "type": "module",
6
6
  "main": "dist/core/index.js",