@stitch-money/client 3.15.0 → 3.18.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.
package/build/index.d.ts CHANGED
@@ -27,20 +27,9 @@ interface SamsungPayClient {
27
27
  loadPaymentSheet: (paymentMethods: SamsungPayPaymentMethods, transactionDetail: SamsungPayTransactionDetail) => Promise<SamsungPayPaymentCredential>;
28
28
  notify: (paymentResult: SamsungPayPaymentResult) => void;
29
29
  }
30
+ /** Opaque merchant session returned by Apple — shape is owned by Apple and may change without notice. Cast at your boundary if you need to read fields. */
31
+ type ApplePaySession = any;
30
32
  type WalletPaySession = ApplePaySession;
31
- interface ApplePaySession {
32
- epochTimestamp: number;
33
- expiresAt: number;
34
- merchantSessionIdentifier: string;
35
- nonce: string;
36
- merchantIdentifier: string;
37
- domainName: string;
38
- displayName: string;
39
- signature: string;
40
- operationalAnalyticsIdentifier?: string;
41
- retries?: number;
42
- pspId?: string;
43
- }
44
33
  interface SamsungPayPaymentResult {
45
34
  status: 'CHARGED' | 'REJECTED' | 'CANCELED' | 'ERRED';
46
35
  provider?: string;
package/build/index.js CHANGED
@@ -23,5 +23,5 @@ ${n}`:t}function Wi(e){return Ee(e,[]).join(`
23
23
  ${n}`);return r.name="Decoding error",r}else return n}function _(e){function t(c){return e(c,kn,u=>Tn(xn(u)?u:$(c,u)))}function n(c,u=Gi){let p=t(c);if(p.ok)return p.value;throw Ui(p.error,u)}function r(c){return t(c).value}function o(c){return i($i(c))}function a(c,u){return l(p=>c(p)?null:u)}function i(c){return _((u,p,g)=>{let m=t(u);if(!m.ok)return m;let d=vn(c)?c:c(m.value,p,g);return vn(d)?d.decode(m.value):d})}function s(c){return i(c)}function l(c){return i((u,p,g)=>{let m=c(u);return m===null?p(u):g(typeof m=="string"?$(u,m):m)})}function f(c){return _((u,p,g)=>{let m=t(u);return m.ok?m:g($(m.error,c))})}return Zi({verify:n,value:r,decode:t,transform:o,refine:a,reject:l,describe:f,then:i,pipe:s})}var Nn=new WeakSet;function Zi(e){return Nn.add(e),e}function vn(e){return Nn.has(e)}var Hi=_((e,t,n)=>Array.isArray(e)?t(e):n("Must be an array"));function Yi(e,t,n,r){let o=[];for(let a=0;a<e.length;++a){let i=e[a];if(i.ok)o.push(i.value);else{let s=i.error,l=t.slice();return l.splice(a,1,$(s,s.text?`${s.text} (at index ${a})`:`index ${a}`)),r($(l))}}return n(o)}function st(e){let t=e.decode;return Hi.then((n,r,o)=>{let a=n.map(t);return Yi(a,n,r,o)})}function zi(e){return _((t,n,r)=>t instanceof e?n(t):r(`Must be ${e.name} instance`))}function Mn(e){return _(t=>e().decode(t))}function Bi(e,t){let n=new Set;for(let r of e)t.has(r)||n.add(r);return n}var Ln=_((e,t,n)=>Rn(e)?t(e):n("Must be an object"));function K(e){let t=new Set(Object.keys(e));return Ln.then((n,r,o)=>{let a=new Set(Object.keys(n)),i=Bi(t,a),s={},l=null;for(let f of Object.keys(e)){let c=e[f],u=n[f],p=c.decode(u);if(p.ok){let g=p.value;g!==void 0&&(s[f]=g),i.delete(f)}else{let g=p.error;u===void 0?i.add(f):(l===null&&(l=new Map),l.set(f,g))}}if(l||i.size>0){let f=An(n);if(l&&(f=In(f,l)),i.size>0){let c=Array.from(i).map(Z).join(", "),u=i.size>1?"keys":"key";f=_n(f,`Missing ${u}: ${c}`)}return o(f)}return r(s)})}var rt=`Either:
24
24
  `;function Xi(e){return`-${it(e).substring(1)}`}function Ji(e){return e.startsWith(rt)?e.substring(rt.length):Xi(e)}function ae(...e){if(e.length===0)throw new Error("Pass at least one decoder to either()");return _((t,n,r)=>{let o=[];for(let i=0;i<e.length;i++){let s=e[i].decode(t);if(s.ok)return s;o.push(s.error)}let a=rt+o.map(i=>Ji(Ee(i).join(`
25
25
  `))).join(`
26
- `);return r(a)})}function Fn(e){return _((t,n,r)=>{let o=e.find(a=>a===t);return o!==void 0?n(o):r(`Must be one of ${e.map(a=>Z(a)).join(", ")}`)})}function Dn(e){return typeof e=="function"?e():e}var Ki=jn(null),qi=jn(void 0),Qi=_((e,t,n)=>e==null?t(e):n("Must be undefined or null"));function se(e,t){let n=ae(qi,e);return arguments.length>=2?n.transform(r=>r!=null?r:Dn(t)):n}function ct(e,t){let n=ae(Qi,e);return arguments.length>=2?n.transform(r=>r!=null?r:Dn(t)):n}function jn(e){return _((t,n,r)=>t===e?n(e):r(`Must be ${typeof e=="symbol"?String(e):Z(e)}`))}var Xa=_((e,t,n)=>t(e));var ce=_((e,t,n)=>typeof e=="boolean"?t(e):n("Must be boolean")),Ja=_((e,t,n)=>t(!!e));function ea(e,t){let n=t!==void 0?e:void 0,r=t!==void 0?t:e;return Ln.then((o,a,i)=>{var f;let s={},l=new Map;for(let c of Object.keys(o)){let u=o[c],p=n==null?void 0:n.decode(c);if((p==null?void 0:p.ok)===!1)return i($(o,`Invalid key ${Z(c)}: ${Wi(p.error)}`));let g=(f=p==null?void 0:p.value)!=null?f:c,m=r.decode(u);m.ok?l.size===0&&(s[g]=m.value):(l.set(c,m.error),s={})}return l.size>0?i(In(An(o),l)):a(s)})}var ta=/^([A-Za-z]{3,9}(?:[+][A-Za-z]{3,9})?):\/\/(?:([-;:&=+$,\w]+)@)?(?:([A-Za-z0-9.-]+)(?::([0-9]{2,5}))?)(\/(?:[-+~%/.,\w]*)?(?:\?[-+=&;%@.,/\w]*)?(?:#[.,!/\w]*)?)?$/,Vn=_((e,t,n)=>ki(e)?t(e):n("Must be string")),j=G(/\S/,"Must be non-empty string");function G(e,t){return Vn.refine(n=>e.test(n),t)}var Ka=G(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,"Must be email"),na=ae(G(ta,"Must be URL").transform(e=>new URL(e)),zi(URL)),qa=na.refine(e=>e.protocol==="https:","Must be an HTTPS URL"),Qa=G(/^[a-z_][a-z0-9_]*$/i,"Must be valid identifier");var Gn=G(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,"Must be uuid"),es=Gn.refine(e=>e[14]==="1","Must be uuidv1"),ts=Gn.refine(e=>e[14]==="4","Must be uuidv4"),ra=G(/^[0-9]+$/,"Must only contain digits"),ns=G(/^[0-9a-f]+$/i,"Must only contain hexadecimal digits"),rs=ra.transform(Number),oa=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:[.]\d+)?(?:Z|[+-]\d{2}:?\d{2})$/,ia=_((e,t,n)=>Sn(e)?t(e):n("Must be a Date")),aa=G(oa,"Must be ISO8601 format").transform(e=>{let t=new Date(e);if(isNaN(t.getTime()))throw new Error("Must be valid date/time value");return t}),os=ae(ia,aa).describe("Must be a Date or date string"),sa=_((e,t,n)=>Oi(e)?t(e):n("Must be number")),ue=sa.refine(e=>Number.isFinite(e),"Number must be finite"),ca=ue.refine(e=>Number.isInteger(e),"Number must be an integer"),Wn=ue.refine(e=>e>=0&&!Object.is(e,-0),"Number must be positive"),is=ca.refine(e=>e>=0&&!Object.is(e,-0),"Number must be positive"),as=_((e,t,n)=>Ti(e)?t(e):n("Must be bigint")),ua=Mn(()=>ea($n)),la=Mn(()=>st($n)),$n=ae(Ki,Vn,ue,ce,ua,la).describe("Must be valid JSON value");var _e=3,Un=500,Hn={prod:"https://public-config.stitch.money",staging:"https://public-config-staging.stitch.money",preprod:"https://public-config-pre-prod.stitch.money"},fa=Fn(["visa","mastercard","amex"]),Ie=ct(K({allowedNetworks:ct(st(fa))})),da=K({analytics:K({changeEventDebounceDelayMs:Wn}),evervault:K({teamId:j,appId:j}),ipAddress:se(j),ipAddressProof:se(j),fingerprintContext:se(j),fingerprint:K({disabled:ce,useEmulation:ce,ossEnabled:se(ce),publicKey:j,endpoint:j,scriptUrlPattern:j,cacheDurationInSeconds:ue}),card:Ie,applePay:Ie,googlePay:Ie,samsungPay:Ie});function Zn(e){return e!=null&&typeof e=="object"&&"aborted"in e&&"addEventListener"in e}function pa(e){return typeof e=="string"&&Object.prototype.hasOwnProperty.call(Hn,e)}function ma(e){let t=pa(e==null?void 0:e.environment)?e.environment:"prod";return Hn[t]}function ga(e,t){return`${ma(t)}/config/${e}`}function le(e,t,n){return b(this,null,function*(){let r=Zn(t)?t:void 0,o=Zn(t)?n:t,a=ga(e,o);try{let i=0;for(;i<_e;)try{let s=yield fetch(a,{signal:r});if(s.ok)return{type:"success",runtimeConfig:da.verify(yield s.json())};if(i++,i===_e)return{type:"error",error:new Error(`[${le.name}] Failed to retrieve runtime config after ${_e} attempts. Runtime config endpoint returned ${s.status} response`)};yield new Promise(l=>setTimeout(l,Un))}catch(s){if(i++,i===_e)throw s;yield new Promise(l=>setTimeout(l,Un))}return{type:"error",error:new Error(`[${le.name}] Failed to retrieve runtime config`)}}catch(i){return i instanceof Error?{type:"error",error:i}:typeof i=="string"?{type:"error",error:new Error(i)}:{type:"error",error:new Error(`[${le.name}] Failed to retrieve runtime config. Unknown error thrown`)}}})}import{v4 as ba}from"uuid";var ya="9ba67dd8d5b247cfb3f76e";function xe(e){return{version:"2",serviceId:ya,protocol:"PROTOCOL_3DS",allowedBrands:ee(e==null?void 0:e.samsungPay).map(t=>ht(t))}}function Yn(e){return{apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:[{type:"CARD",parameters:{allowedAuthMethods:["CRYPTOGRAM_3DS"],allowedCardNetworks:ee(e==null?void 0:e.googlePay).map(t=>yt(t))}}]}}function zn(e){return b(this,null,function*(){if(!window.ApplePaySession)return!1;let t=ApplePaySession;if(t.applePayCapabilities&&e)try{return(yield t.applePayCapabilities(e)).paymentCredentialStatus!=="applePayUnsupported"}catch(n){P("[determineApplePaySupport] failed to get applePayCapabilities, falling back to canMakePayments",n,{merchantIdentifier:e})}return t.canMakePayments()})}function Bn(){if(!window.ApplePaySession)return-1;let t=n=>n===0?-1:ApplePaySession.supportsVersion(n)?n:t(n-1);return t(14)}function Xn(e,t){return b(this,null,function*(){if(!e)return!1;try{return(yield e.isReadyToPay(Yn(t))).result}catch(n){return!1}})}function Jn(e,t){return b(this,null,function*(){if(!e)return!1;try{return(yield e.isReadyToPay(xe(t))).result}catch(n){return!1}})}var L=class extends Error{constructor(t){super(t),this.name="SessionError"}};var fe=e=>e instanceof Error?e.toString():JSON.stringify(e);var ut="3.14.0";var wa="[onvalidatemerchant]",Kn="[onpaymentauthorized]",q="[onClickSamsungPaySessionHandler]",lt="[onClickGooglePaySessionHandler]",qn=class{constructor(t){k(this,"onCancelPayment");k(this,"clientId");k(this,"gatewayMerchantId");k(this,"runtimeConfigEnvironment");k(this,"applePayIsSupported",!1);k(this,"samsungPayIsSupported",!1);k(this,"googlePayIsSupported",!1);k(this,"runtimeConfig");k(this,"fingerprintAgent");k(this,"googlePayClient");k(this,"samsungPayClient");var s,l,f;Ve({source:"wallets-client",version:ut});let{onCancelPayment:n,clientId:r,gatewayMerchantId:o,runtimeConfigEnvironment:a}=t,i=(f=(l=(s=globalThis.google)==null?void 0:s.payments)==null?void 0:l.api)==null?void 0:f.PaymentsClient;this.googlePayClient=i?new i({environment:r!=null&&r.startsWith("test-")?"TEST":"PRODUCTION"}):void 0,this.samsungPayClient=window.SamsungPay?new window.SamsungPay.PaymentClient({environment:r!=null&&r.startsWith("test-")?"STAGE":"PRODUCTION",nonce:ba()}):void 0,this.onCancelPayment=n!=null?n:()=>{},this.clientId=r,this.gatewayMerchantId=o,this.runtimeConfigEnvironment=a,this.loadFingerprintAgent()}loadRuntimeConfig(){return b(this,null,function*(){var t,n;if(this.runtimeConfig===void 0&&this.clientId){let r=yield le(this.clientId,{environment:this.runtimeConfigEnvironment});if(r.type==="error"){let o=(n=(t=r.error)==null?void 0:t.message)!=null?n:"Failed to load runtime configuration";throw P(o,r.error,{clientId:this.clientId}),r.error?r.error:new Error(o)}this.runtimeConfig=r.runtimeConfig}})}loadFingerprintAgent(){return b(this,null,function*(){this.fingerprintAgent===void 0&&(this.runtimeConfig===void 0&&(yield this.loadRuntimeConfig()),this.runtimeConfig!==void 0&&!this.runtimeConfig.fingerprint.disabled&&(this.fingerprintAgent=yield bn({config:this.runtimeConfig.fingerprint})))})}fingerprint(){return b(this,null,function*(){var n,r,o,a;let t=yield wn({config:(n=this.runtimeConfig)==null?void 0:n.fingerprint,agent:this.fingerprintAgent,clientId:this.clientId,sdkVersion:ut,ipAddress:(r=this.runtimeConfig)==null?void 0:r.ipAddress,ipAddressProof:(o=this.runtimeConfig)==null?void 0:o.ipAddressProof,fingerprintContext:(a=this.runtimeConfig)==null?void 0:a.fingerprintContext});return Ve({fingerprint:t}),t})}supportedPaymentMethods(){return b(this,null,function*(){let t=[];try{yield this.loadRuntimeConfig()}catch(n){}return this.applePayIsSupported=yield zn(this.gatewayMerchantId),this.applePayIsSupported&&t.push("APPLE_PAY"),this.samsungPayIsSupported=yield Jn(this.samsungPayClient,this.runtimeConfig),this.samsungPayIsSupported&&t.push("SAMSUNG_PAY"),this.googlePayIsSupported=yield Xn(this.googlePayClient,this.runtimeConfig),this.googlePayIsSupported&&t.push("GOOGLE_PAY"),t})}onClickApplePaySessionHandler(t,n,r,o,a,i){let s=Bn();return()=>{var u,p,g;let l=ee((u=this.runtimeConfig)==null?void 0:u.applePay).map(m=>gt(m)),f={countryCode:"ZA",currencyCode:t,supportedNetworks:l,merchantCapabilities:["supports3DS"],total:{label:r,amount:n.toString()}};i&&(f.recurringPaymentRequest={paymentDescription:r,billingAgreement:i.billingAgreement,regularBilling:{label:r,amount:((p=i.recurringAmount)!=null?p:n).toString(),paymentTiming:"recurring",recurringPaymentIntervalUnit:i.recurringIntervalUnit,recurringPaymentIntervalCount:(g=i.recurringIntervalCount)!=null?g:1},managementURL:i.managementUrl});let c;try{c=new ApplePaySession(s,f)}catch(m){P("Failed to create Apple Pay session",m,{clientId:this.clientId});return}c.onvalidatemerchant=m=>b(this,null,function*(){try{let d=yield o(m.validationURL);if(!c)throw new Error("ApplePaySession is missing");if(d==null||typeof d!="object")throw new Error(`verifyCallbackResponse is not an object: ${JSON.stringify(d)}`);if(Object.keys(d).length===0)throw new Error(`verifyCallbackResponse is an empty object: ${JSON.stringify(d)}`);c.completeMerchantValidation(d)}catch(d){throw P(`${wa} Failed to complete merchant validation`,d,{clientId:this.clientId}),new L(`Failed to complete merchant validation: ${fe(d)}`)}}),c.onpaymentauthorized=m=>b(this,null,function*(){try{let d=m.payment.token,y=yield this.fingerprint(),h=yield a(d,y);switch(h.status){case"TransactionPending":case"TransactionSuccess":{c==null||c.completePayment(ApplePaySession.STATUS_SUCCESS);break}case"TransactionFailure":{c==null||c.completePayment(ApplePaySession.STATUS_FAILURE);break}default:{let I="Invalid transaction status",x=new L(`${I} ${h.status}`);throw P(`${Kn} Invalid transaction status`,x,{clientId:this.clientId}),x}}}catch(d){throw c==null||c.completePayment(ApplePaySession.STATUS_FAILURE),P(`${Kn} Failed to create payment`,d,{clientId:this.clientId}),new L(`Failed to create payment: ${fe(d)}`)}}),c.oncancel=()=>{this.onCancelPayment()},c.begin()}}onClickSamsungPaySessionHandler(t,n,r,o,a,i,s){return()=>b(this,null,function*(){if(!this.samsungPayClient){let l="Samsung Pay client not initialized",f=new Error(l);throw P(`${q} ${l}`,f,{clientId:this.clientId}),f}try{let l={orderNumber:o,merchant:{name:r,url:a,id:i,countryCode:"ZA"},amount:{option:"FORMAT_TOTAL_PRICE_ONLY",currency:t,total:n}},f=yield this.fingerprint(),c=xe(this.runtimeConfig);Ge(`${q} Loading payment sheet`,{clientId:this.clientId,type:"SAMSUNG_PAY",samsungPay:{paymentMethods:c,transactionDetail:l}});let u=yield this.samsungPayClient.loadPaymentSheet(c,l);Ge(`${q} Received payment credential`,{clientId:this.clientId,type:"SAMSUNG_PAY",samsungPay:{paymentCredential:u}});let p=yield s(u,f);switch(p.status){case"TransactionPending":break;case"TransactionFailure":{this.samsungPayClient.notify({status:"REJECTED"});break}case"TransactionSuccess":{this.samsungPayClient.notify({status:"CHARGED"});break}default:{this.samsungPayClient.notify({status:"ERRED"});let g=`${q} Invalid transaction status: ${p.status}`,m=new L(g);throw P(g,m,{clientId:this.clientId,type:"SAMSUNG_PAY"}),m}}}catch(l){throw P(`${q} Failed to create payment`,l,{clientId:this.clientId,type:"SAMSUNG_PAY"}),new L(`${q} Failed to create payment: ${fe(l)}`)}})}onClickGooglePaySessionHandler(t){return n=>b(this,null,function*(){try{let r=yield this.fingerprint(),o=yield t(n.paymentMethodData.tokenizationData.token,r);switch(o.status){case"TransactionPending":case"TransactionFailure":case"TransactionSuccess":break;default:{let a=`${lt} Invalid transaction status: ${o.status}`,i=new L(a);throw P(a,i,{clientId:this.clientId}),i}}}catch(r){throw P(`${lt} Failed to create payment`,r,{clientId:this.clientId}),new L(`${lt} Failed to create payment: ${fe(r)}`)}})}};export{qn as StitchWalletClientSdk,mt as WalletType};
26
+ `);return r(a)})}function Fn(e){return _((t,n,r)=>{let o=e.find(a=>a===t);return o!==void 0?n(o):r(`Must be one of ${e.map(a=>Z(a)).join(", ")}`)})}function Dn(e){return typeof e=="function"?e():e}var Ki=jn(null),qi=jn(void 0),Qi=_((e,t,n)=>e==null?t(e):n("Must be undefined or null"));function se(e,t){let n=ae(qi,e);return arguments.length>=2?n.transform(r=>r!=null?r:Dn(t)):n}function ct(e,t){let n=ae(Qi,e);return arguments.length>=2?n.transform(r=>r!=null?r:Dn(t)):n}function jn(e){return _((t,n,r)=>t===e?n(e):r(`Must be ${typeof e=="symbol"?String(e):Z(e)}`))}var Xa=_((e,t,n)=>t(e));var ce=_((e,t,n)=>typeof e=="boolean"?t(e):n("Must be boolean")),Ja=_((e,t,n)=>t(!!e));function ea(e,t){let n=t!==void 0?e:void 0,r=t!==void 0?t:e;return Ln.then((o,a,i)=>{var f;let s={},l=new Map;for(let c of Object.keys(o)){let u=o[c],p=n==null?void 0:n.decode(c);if((p==null?void 0:p.ok)===!1)return i($(o,`Invalid key ${Z(c)}: ${Wi(p.error)}`));let g=(f=p==null?void 0:p.value)!=null?f:c,m=r.decode(u);m.ok?l.size===0&&(s[g]=m.value):(l.set(c,m.error),s={})}return l.size>0?i(In(An(o),l)):a(s)})}var ta=/^([A-Za-z]{3,9}(?:[+][A-Za-z]{3,9})?):\/\/(?:([-;:&=+$,\w]+)@)?(?:([A-Za-z0-9.-]+)(?::([0-9]{2,5}))?)(\/(?:[-+~%/.,\w]*)?(?:\?[-+=&;%@.,/\w]*)?(?:#[.,!/\w]*)?)?$/,Vn=_((e,t,n)=>ki(e)?t(e):n("Must be string")),j=G(/\S/,"Must be non-empty string");function G(e,t){return Vn.refine(n=>e.test(n),t)}var Ka=G(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,"Must be email"),na=ae(G(ta,"Must be URL").transform(e=>new URL(e)),zi(URL)),qa=na.refine(e=>e.protocol==="https:","Must be an HTTPS URL"),Qa=G(/^[a-z_][a-z0-9_]*$/i,"Must be valid identifier");var Gn=G(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,"Must be uuid"),es=Gn.refine(e=>e[14]==="1","Must be uuidv1"),ts=Gn.refine(e=>e[14]==="4","Must be uuidv4"),ra=G(/^[0-9]+$/,"Must only contain digits"),ns=G(/^[0-9a-f]+$/i,"Must only contain hexadecimal digits"),rs=ra.transform(Number),oa=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:[.]\d+)?(?:Z|[+-]\d{2}:?\d{2})$/,ia=_((e,t,n)=>Sn(e)?t(e):n("Must be a Date")),aa=G(oa,"Must be ISO8601 format").transform(e=>{let t=new Date(e);if(isNaN(t.getTime()))throw new Error("Must be valid date/time value");return t}),os=ae(ia,aa).describe("Must be a Date or date string"),sa=_((e,t,n)=>Oi(e)?t(e):n("Must be number")),ue=sa.refine(e=>Number.isFinite(e),"Number must be finite"),ca=ue.refine(e=>Number.isInteger(e),"Number must be an integer"),Wn=ue.refine(e=>e>=0&&!Object.is(e,-0),"Number must be positive"),is=ca.refine(e=>e>=0&&!Object.is(e,-0),"Number must be positive"),as=_((e,t,n)=>Ti(e)?t(e):n("Must be bigint")),ua=Mn(()=>ea($n)),la=Mn(()=>st($n)),$n=ae(Ki,Vn,ue,ce,ua,la).describe("Must be valid JSON value");var _e=3,Un=500,Hn={prod:"https://public-config.stitch.money",staging:"https://public-config-staging.stitch.money",preprod:"https://public-config-pre-prod.stitch.money"},fa=Fn(["visa","mastercard","amex"]),Ie=ct(K({allowedNetworks:ct(st(fa))})),da=K({analytics:K({changeEventDebounceDelayMs:Wn}),evervault:K({teamId:j,appId:j}),ipAddress:se(j),ipAddressProof:se(j),fingerprintContext:se(j),fingerprint:K({disabled:ce,useEmulation:ce,ossEnabled:se(ce),publicKey:j,endpoint:j,scriptUrlPattern:j,cacheDurationInSeconds:ue}),card:Ie,applePay:Ie,googlePay:Ie,samsungPay:Ie});function Zn(e){return e!=null&&typeof e=="object"&&"aborted"in e&&"addEventListener"in e}function pa(e){return typeof e=="string"&&Object.prototype.hasOwnProperty.call(Hn,e)}function ma(e){let t=pa(e==null?void 0:e.environment)?e.environment:"prod";return Hn[t]}function ga(e,t){return`${ma(t)}/config/${e}`}function le(e,t,n){return b(this,null,function*(){let r=Zn(t)?t:void 0,o=Zn(t)?n:t,a=ga(e,o);try{let i=0;for(;i<_e;)try{let s=yield fetch(a,{signal:r});if(s.ok)return{type:"success",runtimeConfig:da.verify(yield s.json())};if(i++,i===_e)return{type:"error",error:new Error(`[${le.name}] Failed to retrieve runtime config after ${_e} attempts. Runtime config endpoint returned ${s.status} response`)};yield new Promise(l=>setTimeout(l,Un))}catch(s){if(i++,i===_e)throw s;yield new Promise(l=>setTimeout(l,Un))}return{type:"error",error:new Error(`[${le.name}] Failed to retrieve runtime config`)}}catch(i){return i instanceof Error?{type:"error",error:i}:typeof i=="string"?{type:"error",error:new Error(i)}:{type:"error",error:new Error(`[${le.name}] Failed to retrieve runtime config. Unknown error thrown`)}}})}import{v4 as ba}from"uuid";var ya="9ba67dd8d5b247cfb3f76e";function xe(e){return{version:"2",serviceId:ya,protocol:"PROTOCOL_3DS",allowedBrands:ee(e==null?void 0:e.samsungPay).map(t=>ht(t))}}function Yn(e){return{apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:[{type:"CARD",parameters:{allowedAuthMethods:["CRYPTOGRAM_3DS"],allowedCardNetworks:ee(e==null?void 0:e.googlePay).map(t=>yt(t))}}]}}function zn(e){return b(this,null,function*(){if(!window.ApplePaySession)return!1;let t=ApplePaySession;if(t.applePayCapabilities&&e)try{return(yield t.applePayCapabilities(e)).paymentCredentialStatus!=="applePayUnsupported"}catch(n){P("[determineApplePaySupport] failed to get applePayCapabilities, falling back to canMakePayments",n,{merchantIdentifier:e})}return t.canMakePayments()})}function Bn(){if(!window.ApplePaySession)return-1;let t=n=>n===0?-1:ApplePaySession.supportsVersion(n)?n:t(n-1);return t(14)}function Xn(e,t){return b(this,null,function*(){if(!e)return!1;try{return(yield e.isReadyToPay(Yn(t))).result}catch(n){return!1}})}function Jn(e,t){return b(this,null,function*(){if(!e)return!1;try{return(yield e.isReadyToPay(xe(t))).result}catch(n){return!1}})}var L=class extends Error{constructor(t){super(t),this.name="SessionError"}};var fe=e=>e instanceof Error?e.toString():JSON.stringify(e);var ut="3.17.0";var wa="[onvalidatemerchant]",Kn="[onpaymentauthorized]",q="[onClickSamsungPaySessionHandler]",lt="[onClickGooglePaySessionHandler]",qn=class{constructor(t){k(this,"onCancelPayment");k(this,"clientId");k(this,"gatewayMerchantId");k(this,"runtimeConfigEnvironment");k(this,"applePayIsSupported",!1);k(this,"samsungPayIsSupported",!1);k(this,"googlePayIsSupported",!1);k(this,"runtimeConfig");k(this,"fingerprintAgent");k(this,"googlePayClient");k(this,"samsungPayClient");var s,l,f;Ve({source:"wallets-client",version:ut});let{onCancelPayment:n,clientId:r,gatewayMerchantId:o,runtimeConfigEnvironment:a}=t,i=(f=(l=(s=globalThis.google)==null?void 0:s.payments)==null?void 0:l.api)==null?void 0:f.PaymentsClient;this.googlePayClient=i?new i({environment:r!=null&&r.startsWith("test-")?"TEST":"PRODUCTION"}):void 0,this.samsungPayClient=window.SamsungPay?new window.SamsungPay.PaymentClient({environment:r!=null&&r.startsWith("test-")?"STAGE":"PRODUCTION",nonce:ba()}):void 0,this.onCancelPayment=n!=null?n:()=>{},this.clientId=r,this.gatewayMerchantId=o,this.runtimeConfigEnvironment=a,this.loadFingerprintAgent()}loadRuntimeConfig(){return b(this,null,function*(){var t,n;if(this.runtimeConfig===void 0&&this.clientId){let r=yield le(this.clientId,{environment:this.runtimeConfigEnvironment});if(r.type==="error"){let o=(n=(t=r.error)==null?void 0:t.message)!=null?n:"Failed to load runtime configuration";throw P(o,r.error,{clientId:this.clientId}),r.error?r.error:new Error(o)}this.runtimeConfig=r.runtimeConfig}})}loadFingerprintAgent(){return b(this,null,function*(){this.fingerprintAgent===void 0&&(this.runtimeConfig===void 0&&(yield this.loadRuntimeConfig()),this.runtimeConfig!==void 0&&!this.runtimeConfig.fingerprint.disabled&&(this.fingerprintAgent=yield bn({config:this.runtimeConfig.fingerprint})))})}fingerprint(){return b(this,null,function*(){var n,r,o,a;let t=yield wn({config:(n=this.runtimeConfig)==null?void 0:n.fingerprint,agent:this.fingerprintAgent,clientId:this.clientId,sdkVersion:ut,ipAddress:(r=this.runtimeConfig)==null?void 0:r.ipAddress,ipAddressProof:(o=this.runtimeConfig)==null?void 0:o.ipAddressProof,fingerprintContext:(a=this.runtimeConfig)==null?void 0:a.fingerprintContext});return Ve({fingerprint:t}),t})}supportedPaymentMethods(){return b(this,null,function*(){try{yield this.loadRuntimeConfig()}catch(n){}[this.applePayIsSupported,this.samsungPayIsSupported,this.googlePayIsSupported]=yield Promise.all([zn(this.gatewayMerchantId),Jn(this.samsungPayClient,this.runtimeConfig),Xn(this.googlePayClient,this.runtimeConfig)]);let t=[];return this.applePayIsSupported&&t.push("APPLE_PAY"),this.samsungPayIsSupported&&t.push("SAMSUNG_PAY"),this.googlePayIsSupported&&t.push("GOOGLE_PAY"),t})}onClickApplePaySessionHandler(t,n,r,o,a,i){let s=Bn();return()=>{var u,p,g;let l=ee((u=this.runtimeConfig)==null?void 0:u.applePay).map(m=>gt(m)),f={countryCode:"ZA",currencyCode:t,supportedNetworks:l,merchantCapabilities:["supports3DS"],total:{label:r,amount:n.toString()}};i&&(f.recurringPaymentRequest={paymentDescription:r,billingAgreement:i.billingAgreement,regularBilling:{label:r,amount:((p=i.recurringAmount)!=null?p:n).toString(),paymentTiming:"recurring",recurringPaymentIntervalUnit:i.recurringIntervalUnit,recurringPaymentIntervalCount:(g=i.recurringIntervalCount)!=null?g:1},managementURL:i.managementUrl});let c;try{c=new ApplePaySession(s,f)}catch(m){P("Failed to create Apple Pay session",m,{clientId:this.clientId});return}c.onvalidatemerchant=m=>b(this,null,function*(){try{let d=yield o(m.validationURL);if(!c)throw new Error("ApplePaySession is missing");if(d==null||typeof d!="object")throw new Error(`verifyCallbackResponse is not an object: ${JSON.stringify(d)}`);if(Object.keys(d).length===0)throw new Error(`verifyCallbackResponse is an empty object: ${JSON.stringify(d)}`);c.completeMerchantValidation(d)}catch(d){throw P(`${wa} Failed to complete merchant validation`,d,{clientId:this.clientId}),new L(`Failed to complete merchant validation: ${fe(d)}`)}}),c.onpaymentauthorized=m=>b(this,null,function*(){try{let d=m.payment.token,y=yield this.fingerprint(),h=yield a(d,y);switch(h.status){case"TransactionPending":case"TransactionSuccess":{c==null||c.completePayment(ApplePaySession.STATUS_SUCCESS);break}case"TransactionFailure":{c==null||c.completePayment(ApplePaySession.STATUS_FAILURE);break}default:{let I="Invalid transaction status",x=new L(`${I} ${h.status}`);throw P(`${Kn} Invalid transaction status`,x,{clientId:this.clientId}),x}}}catch(d){throw c==null||c.completePayment(ApplePaySession.STATUS_FAILURE),P(`${Kn} Failed to create payment`,d,{clientId:this.clientId}),new L(`Failed to create payment: ${fe(d)}`)}}),c.oncancel=()=>{this.onCancelPayment()},c.begin()}}onClickSamsungPaySessionHandler(t,n,r,o,a,i,s){return()=>b(this,null,function*(){if(!this.samsungPayClient){let l="Samsung Pay client not initialized",f=new Error(l);throw P(`${q} ${l}`,f,{clientId:this.clientId}),f}try{let l={orderNumber:o,merchant:{name:r,url:a,id:i,countryCode:"ZA"},amount:{option:"FORMAT_TOTAL_PRICE_ONLY",currency:t,total:n}},f=yield this.fingerprint(),c=xe(this.runtimeConfig);Ge(`${q} Loading payment sheet`,{clientId:this.clientId,type:"SAMSUNG_PAY",samsungPay:{paymentMethods:c,transactionDetail:l}});let u=yield this.samsungPayClient.loadPaymentSheet(c,l);Ge(`${q} Received payment credential`,{clientId:this.clientId,type:"SAMSUNG_PAY",samsungPay:{paymentCredential:u}});let p=yield s(u,f);switch(p.status){case"TransactionPending":break;case"TransactionFailure":{this.samsungPayClient.notify({status:"REJECTED"});break}case"TransactionSuccess":{this.samsungPayClient.notify({status:"CHARGED"});break}default:{this.samsungPayClient.notify({status:"ERRED"});let g=`${q} Invalid transaction status: ${p.status}`,m=new L(g);throw P(g,m,{clientId:this.clientId,type:"SAMSUNG_PAY"}),m}}}catch(l){throw P(`${q} Failed to create payment`,l,{clientId:this.clientId,type:"SAMSUNG_PAY"}),new L(`${q} Failed to create payment: ${fe(l)}`)}})}onClickGooglePaySessionHandler(t){return n=>b(this,null,function*(){try{let r=yield this.fingerprint(),o=yield t(n.paymentMethodData.tokenizationData.token,r);switch(o.status){case"TransactionPending":case"TransactionFailure":case"TransactionSuccess":break;default:{let a=`${lt} Invalid transaction status: ${o.status}`,i=new L(a);throw P(a,i,{clientId:this.clientId}),i}}}catch(r){throw P(`${lt} Failed to create payment`,r,{clientId:this.clientId}),new L(`${lt} Failed to create payment: ${fe(r)}`)}})}};export{qn as StitchWalletClientSdk,mt as WalletType};
27
27
  //# sourceMappingURL=index.js.map