@getopenpay/openpay-js 0.2.36 → 0.3.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/dist/index.d.ts +27 -6
- package/dist/index.es.js +1775 -1669
- package/dist/index.umd.js +18 -18
- package/package.json +1 -1
package/dist/index.umd.js
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
|
-
(function(Pe,He){typeof exports=="object"&&typeof module<"u"?He(exports):typeof define=="function"&&define.amd?define(["exports"],He):(Pe=typeof globalThis<"u"?globalThis:Pe||self,He(Pe.OpenPay={}))})(this,function(Pe){"use strict";var zo;const He="https://cde.getopenpay.com";var N;(function(n){n.assertEqual=o=>o;function e(o){}n.assertIs=e;function t(o){throw new Error}n.assertNever=t,n.arrayToEnum=o=>{const s={};for(const i of o)s[i]=i;return s},n.getValidEnumValues=o=>{const s=n.objectKeys(o).filter(c=>typeof o[o[c]]!="number"),i={};for(const c of s)i[c]=o[c];return n.objectValues(i)},n.objectValues=o=>n.objectKeys(o).map(function(s){return o[s]}),n.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const s=[];for(const i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},n.find=(o,s)=>{for(const i of o)if(s(i))return i},n.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}n.joinValues=r,n.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(N||(N={}));var vn;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(vn||(vn={}));const v=N.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Re=n=>{switch(typeof n){case"undefined":return v.undefined;case"string":return v.string;case"number":return isNaN(n)?v.nan:v.number;case"boolean":return v.boolean;case"function":return v.function;case"bigint":return v.bigint;case"symbol":return v.symbol;case"object":return Array.isArray(n)?v.array:n===null?v.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?v.promise:typeof Map<"u"&&n instanceof Map?v.map:typeof Set<"u"&&n instanceof Set?v.set:typeof Date<"u"&&n instanceof Date?v.date:v.object;default:return v.unknown}},y=N.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Go=n=>JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:");class te extends Error{constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){const t=e||function(s){return s.message},r={_errors:[]},o=s=>{for(const i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)r._errors.push(t(i));else{let c=r,l=0;for(;l<i.path.length;){const u=i.path[l];l===i.path.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(t(i))):c[u]=c[u]||{_errors:[]},c=c[u],l++}}};return o(this),r}static assert(e){if(!(e instanceof te))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,N.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},r=[];for(const o of this.issues)o.path.length>0?(t[o.path[0]]=t[o.path[0]]||[],t[o.path[0]].push(e(o))):r.push(e(o));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}te.create=n=>new te(n);const Ke=(n,e)=>{let t;switch(n.code){case y.invalid_type:n.received===v.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case y.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,N.jsonStringifyReplacer)}`;break;case y.unrecognized_keys:t=`Unrecognized key(s) in object: ${N.joinValues(n.keys,", ")}`;break;case y.invalid_union:t="Invalid input";break;case y.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${N.joinValues(n.options)}`;break;case y.invalid_enum_value:t=`Invalid enum value. Expected ${N.joinValues(n.options)}, received '${n.received}'`;break;case y.invalid_arguments:t="Invalid function arguments";break;case y.invalid_return_type:t="Invalid function return type";break;case y.invalid_date:t="Invalid date";break;case y.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:N.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case y.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case y.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case y.custom:t="Invalid input";break;case y.invalid_intersection_types:t="Intersection results could not be merged";break;case y.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case y.not_finite:t="Number must be finite";break;default:t=e.defaultError,N.assertNever(n)}return{message:t}};let Hn=Ke;function Bo(n){Hn=n}function Zt(){return Hn}const zt=n=>{const{data:e,path:t,errorMaps:r,issueData:o}=n,s=[...t,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let c="";const l=r.filter(u=>!!u).slice().reverse();for(const u of l)c=u(i,{data:e,defaultError:c}).message;return{...o,path:s,message:c}},qo=[];function g(n,e){const t=Zt(),r=zt({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===Ke?void 0:Ke].filter(o=>!!o)});n.common.issues.push(r)}class H{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const o of t){if(o.status==="aborted")return S;o.status==="dirty"&&e.dirty(),r.push(o.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const o of t){const s=await o.key,i=await o.value;r.push({key:s,value:i})}return H.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const o of t){const{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return S;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(r[s.value]=i.value)}return{status:e.value,value:r}}}const S=Object.freeze({status:"aborted"}),Je=n=>({status:"dirty",value:n}),Q=n=>({status:"valid",value:n}),wn=n=>n.status==="aborted",bn=n=>n.status==="dirty",dt=n=>n.status==="valid",pt=n=>typeof Promise<"u"&&n instanceof Promise;function Gt(n,e,t,r){if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(n)}function Kn(n,e,t,r,o){if(typeof e=="function"?n!==e||!o:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(n,t),t}typeof SuppressedError=="function"&&SuppressedError;var b;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(b||(b={}));var ft,mt;class me{constructor(e,t,r,o){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=o}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Jn=(n,e)=>{if(dt(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new te(n.common.issues);return this._error=t,this._error}}};function A(n){if(!n)return{};const{errorMap:e,invalid_type_error:t,required_error:r,description:o}=n;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,c)=>{var l,u;const{message:d}=n;return i.code==="invalid_enum_value"?{message:d??c.defaultError}:typeof c.data>"u"?{message:(l=d??r)!==null&&l!==void 0?l:c.defaultError}:i.code!=="invalid_type"?{message:c.defaultError}:{message:(u=d??t)!==null&&u!==void 0?u:c.defaultError}},description:o}}class I{constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(e){return Re(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Re(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new H,ctx:{common:e.parent.common,data:e.data,parsedType:Re(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(pt(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){var r;const o={common:{issues:[],async:(r=t==null?void 0:t.async)!==null&&r!==void 0?r:!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Re(e)},s=this._parseSync({data:e,path:o.path,parent:o});return Jn(o,s)}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Re(e)},o=this._parse({data:e,path:r.path,parent:r}),s=await(pt(o)?o:Promise.resolve(o));return Jn(r,s)}refine(e,t){const r=o=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(o):t;return this._refinement((o,s)=>{const i=e(o),c=()=>s.addIssue({code:y.custom,...r(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(c(),!1)):i?!0:(c(),!1)})}refinement(e,t){return this._refinement((r,o)=>e(r)?!0:(o.addIssue(typeof t=="function"?t(r,o):t),!1))}_refinement(e){return new ae({schema:this,typeName:k.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return ye.create(this,this._def)}nullable(){return De.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return se.create(this,this._def)}promise(){return tt.create(this,this._def)}or(e){return gt.create([this,e],this._def)}and(e){return vt.create(this,e,this._def)}transform(e){return new ae({...A(this._def),schema:this,typeName:k.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new Ct({...A(this._def),innerType:this,defaultValue:t,typeName:k.ZodDefault})}brand(){return new Cn({typeName:k.ZodBranded,type:this,...A(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new St({...A(this._def),innerType:this,catchValue:t,typeName:k.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Pt.create(this,e)}readonly(){return At.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Yo=/^c[^\s-]{8,}$/i,Wo=/^[0-9a-z]+$/,Ho=/^[0-9A-HJKMNP-TV-Z]{26}$/,Ko=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Jo=/^[a-z0-9_-]{21}$/i,Qo=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Xo=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,es="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let En;const ts=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ns=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,rs=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Qn="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",os=new RegExp(`^${Qn}$`);function Xn(n){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`),e}function ss(n){return new RegExp(`^${Xn(n)}$`)}function er(n){let e=`${Qn}T${Xn(n)}`;const t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function as(n,e){return!!((e==="v4"||!e)&&ts.test(n)||(e==="v6"||!e)&&ns.test(n))}class oe extends I{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==v.string){const s=this._getOrReturnCtx(e);return g(s,{code:y.invalid_type,expected:v.string,received:s.parsedType}),S}const r=new H;let o;for(const s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),g(o,{code:y.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),g(o,{code:y.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){const i=e.data.length>s.value,c=e.data.length<s.value;(i||c)&&(o=this._getOrReturnCtx(e,o),i?g(o,{code:y.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):c&&g(o,{code:y.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")Xo.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"email",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")En||(En=new RegExp(es,"u")),En.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"emoji",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")Ko.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"uuid",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")Jo.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"nanoid",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")Yo.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"cuid",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")Wo.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"cuid2",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")Ho.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"ulid",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),g(o,{validation:"url",code:y.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"regex",code:y.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?er(s).test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?os.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?ss(s).test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?Qo.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"duration",code:y.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?as(e.data,s.version)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"ip",code:y.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?rs.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"base64",code:y.invalid_string,message:s.message}),r.dirty()):N.assertNever(s);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(o=>e.test(o),{validation:t,code:y.invalid_string,...b.errToObj(r)})}_addCheck(e){return new oe({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...b.errToObj(e)})}url(e){return this._addCheck({kind:"url",...b.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...b.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...b.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...b.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...b.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...b.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...b.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...b.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...b.errToObj(e)})}datetime(e){var t,r;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(t=e==null?void 0:e.offset)!==null&&t!==void 0?t:!1,local:(r=e==null?void 0:e.local)!==null&&r!==void 0?r:!1,...b.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...b.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...b.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...b.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...b.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...b.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...b.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...b.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...b.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...b.errToObj(t)})}nonempty(e){return this.min(1,b.errToObj(e))}trim(){return new oe({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new oe({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new oe({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}oe.create=n=>{var e;return new oe({checks:[],typeName:k.ZodString,coerce:(e=n==null?void 0:n.coerce)!==null&&e!==void 0?e:!1,...A(n)})};function is(n,e){const t=(n.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=t>r?t:r,s=parseInt(n.toFixed(o).replace(".","")),i=parseInt(e.toFixed(o).replace(".",""));return s%i/Math.pow(10,o)}class Ne extends I{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==v.number){const s=this._getOrReturnCtx(e);return g(s,{code:y.invalid_type,expected:v.number,received:s.parsedType}),S}let r;const o=new H;for(const s of this._def.checks)s.kind==="int"?N.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),g(r,{code:y.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),g(r,{code:y.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),g(r,{code:y.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?is(e.data,s.value)!==0&&(r=this._getOrReturnCtx(e,r),g(r,{code:y.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),g(r,{code:y.not_finite,message:s.message}),o.dirty()):N.assertNever(s);return{status:o.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,b.toString(t))}gt(e,t){return this.setLimit("min",e,!1,b.toString(t))}lte(e,t){return this.setLimit("max",e,!0,b.toString(t))}lt(e,t){return this.setLimit("max",e,!1,b.toString(t))}setLimit(e,t,r,o){return new Ne({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:b.toString(o)}]})}_addCheck(e){return new Ne({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:b.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:b.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:b.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:b.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:b.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:b.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:b.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:b.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:b.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&N.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(t===null||r.value>t)&&(t=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}Ne.create=n=>new Ne({checks:[],typeName:k.ZodNumber,coerce:(n==null?void 0:n.coerce)||!1,...A(n)});class Oe extends I{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce&&(e.data=BigInt(e.data)),this._getType(e)!==v.bigint){const s=this._getOrReturnCtx(e);return g(s,{code:y.invalid_type,expected:v.bigint,received:s.parsedType}),S}let r;const o=new H;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),g(r,{code:y.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),g(r,{code:y.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),g(r,{code:y.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):N.assertNever(s);return{status:o.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,b.toString(t))}gt(e,t){return this.setLimit("min",e,!1,b.toString(t))}lte(e,t){return this.setLimit("max",e,!0,b.toString(t))}lt(e,t){return this.setLimit("max",e,!1,b.toString(t))}setLimit(e,t,r,o){return new Oe({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:b.toString(o)}]})}_addCheck(e){return new Oe({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:b.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:b.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:b.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:b.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:b.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}Oe.create=n=>{var e;return new Oe({checks:[],typeName:k.ZodBigInt,coerce:(e=n==null?void 0:n.coerce)!==null&&e!==void 0?e:!1,...A(n)})};class ht extends I{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==v.boolean){const r=this._getOrReturnCtx(e);return g(r,{code:y.invalid_type,expected:v.boolean,received:r.parsedType}),S}return Q(e.data)}}ht.create=n=>new ht({typeName:k.ZodBoolean,coerce:(n==null?void 0:n.coerce)||!1,...A(n)});class Ue extends I{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==v.date){const s=this._getOrReturnCtx(e);return g(s,{code:y.invalid_type,expected:v.date,received:s.parsedType}),S}if(isNaN(e.data.getTime())){const s=this._getOrReturnCtx(e);return g(s,{code:y.invalid_date}),S}const r=new H;let o;for(const s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),g(o,{code:y.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),g(o,{code:y.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):N.assertNever(s);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Ue({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:b.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:b.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}Ue.create=n=>new Ue({checks:[],coerce:(n==null?void 0:n.coerce)||!1,typeName:k.ZodDate,...A(n)});class Bt extends I{_parse(e){if(this._getType(e)!==v.symbol){const r=this._getOrReturnCtx(e);return g(r,{code:y.invalid_type,expected:v.symbol,received:r.parsedType}),S}return Q(e.data)}}Bt.create=n=>new Bt({typeName:k.ZodSymbol,...A(n)});class yt extends I{_parse(e){if(this._getType(e)!==v.undefined){const r=this._getOrReturnCtx(e);return g(r,{code:y.invalid_type,expected:v.undefined,received:r.parsedType}),S}return Q(e.data)}}yt.create=n=>new yt({typeName:k.ZodUndefined,...A(n)});class _t extends I{_parse(e){if(this._getType(e)!==v.null){const r=this._getOrReturnCtx(e);return g(r,{code:y.invalid_type,expected:v.null,received:r.parsedType}),S}return Q(e.data)}}_t.create=n=>new _t({typeName:k.ZodNull,...A(n)});class Qe extends I{constructor(){super(...arguments),this._any=!0}_parse(e){return Q(e.data)}}Qe.create=n=>new Qe({typeName:k.ZodAny,...A(n)});class $e extends I{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Q(e.data)}}$e.create=n=>new $e({typeName:k.ZodUnknown,...A(n)});class Ae extends I{_parse(e){const t=this._getOrReturnCtx(e);return g(t,{code:y.invalid_type,expected:v.never,received:t.parsedType}),S}}Ae.create=n=>new Ae({typeName:k.ZodNever,...A(n)});class qt extends I{_parse(e){if(this._getType(e)!==v.undefined){const r=this._getOrReturnCtx(e);return g(r,{code:y.invalid_type,expected:v.void,received:r.parsedType}),S}return Q(e.data)}}qt.create=n=>new qt({typeName:k.ZodVoid,...A(n)});class se extends I{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),o=this._def;if(t.parsedType!==v.array)return g(t,{code:y.invalid_type,expected:v.array,received:t.parsedType}),S;if(o.exactLength!==null){const i=t.data.length>o.exactLength.value,c=t.data.length<o.exactLength.value;(i||c)&&(g(t,{code:i?y.too_big:y.too_small,minimum:c?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&t.data.length<o.minLength.value&&(g(t,{code:y.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&t.data.length>o.maxLength.value&&(g(t,{code:y.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((i,c)=>o.type._parseAsync(new me(t,i,t.path,c)))).then(i=>H.mergeArray(r,i));const s=[...t.data].map((i,c)=>o.type._parseSync(new me(t,i,t.path,c)));return H.mergeArray(r,s)}get element(){return this._def.type}min(e,t){return new se({...this._def,minLength:{value:e,message:b.toString(t)}})}max(e,t){return new se({...this._def,maxLength:{value:e,message:b.toString(t)}})}length(e,t){return new se({...this._def,exactLength:{value:e,message:b.toString(t)}})}nonempty(e){return this.min(1,e)}}se.create=(n,e)=>new se({type:n,minLength:null,maxLength:null,exactLength:null,typeName:k.ZodArray,...A(e)});function Xe(n){if(n instanceof L){const e={};for(const t in n.shape){const r=n.shape[t];e[t]=ye.create(Xe(r))}return new L({...n._def,shape:()=>e})}else return n instanceof se?new se({...n._def,type:Xe(n.element)}):n instanceof ye?ye.create(Xe(n.unwrap())):n instanceof De?De.create(Xe(n.unwrap())):n instanceof he?he.create(n.items.map(e=>Xe(e))):n}class L extends I{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=N.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==v.object){const u=this._getOrReturnCtx(e);return g(u,{code:y.invalid_type,expected:v.object,received:u.parsedType}),S}const{status:r,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),c=[];if(!(this._def.catchall instanceof Ae&&this._def.unknownKeys==="strip"))for(const u in o.data)i.includes(u)||c.push(u);const l=[];for(const u of i){const d=s[u],p=o.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new me(o,p,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof Ae){const u=this._def.unknownKeys;if(u==="passthrough")for(const d of c)l.push({key:{status:"valid",value:d},value:{status:"valid",value:o.data[d]}});else if(u==="strict")c.length>0&&(g(o,{code:y.unrecognized_keys,keys:c}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const d of c){const p=o.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new me(o,p,o.path,d)),alwaysSet:d in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const u=[];for(const d of l){const p=await d.key,h=await d.value;u.push({key:p,value:h,alwaysSet:d.alwaysSet})}return u}).then(u=>H.mergeObjectSync(r,u)):H.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return b.errToObj,new L({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{var o,s,i,c;const l=(i=(s=(o=this._def).errorMap)===null||s===void 0?void 0:s.call(o,t,r).message)!==null&&i!==void 0?i:r.defaultError;return t.code==="unrecognized_keys"?{message:(c=b.errToObj(e).message)!==null&&c!==void 0?c:l}:{message:l}}}:{}})}strip(){return new L({...this._def,unknownKeys:"strip"})}passthrough(){return new L({...this._def,unknownKeys:"passthrough"})}extend(e){return new L({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new L({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:k.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new L({...this._def,catchall:e})}pick(e){const t={};return N.objectKeys(e).forEach(r=>{e[r]&&this.shape[r]&&(t[r]=this.shape[r])}),new L({...this._def,shape:()=>t})}omit(e){const t={};return N.objectKeys(this.shape).forEach(r=>{e[r]||(t[r]=this.shape[r])}),new L({...this._def,shape:()=>t})}deepPartial(){return Xe(this)}partial(e){const t={};return N.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];e&&!e[r]?t[r]=o:t[r]=o.optional()}),new L({...this._def,shape:()=>t})}required(e){const t={};return N.objectKeys(this.shape).forEach(r=>{if(e&&!e[r])t[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof ye;)s=s._def.innerType;t[r]=s}}),new L({...this._def,shape:()=>t})}keyof(){return tr(N.objectKeys(this.shape))}}L.create=(n,e)=>new L({shape:()=>n,unknownKeys:"strip",catchall:Ae.create(),typeName:k.ZodObject,...A(e)}),L.strictCreate=(n,e)=>new L({shape:()=>n,unknownKeys:"strict",catchall:Ae.create(),typeName:k.ZodObject,...A(e)}),L.lazycreate=(n,e)=>new L({shape:n,unknownKeys:"strip",catchall:Ae.create(),typeName:k.ZodObject,...A(e)});class gt extends I{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;function o(s){for(const c of s)if(c.result.status==="valid")return c.result;for(const c of s)if(c.result.status==="dirty")return t.common.issues.push(...c.ctx.common.issues),c.result;const i=s.map(c=>new te(c.ctx.common.issues));return g(t,{code:y.invalid_union,unionErrors:i}),S}if(t.common.async)return Promise.all(r.map(async s=>{const i={...t,common:{...t.common,issues:[]},parent:null};return{result:await s._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(o);{let s;const i=[];for(const l of r){const u={...t,common:{...t.common,issues:[]},parent:null},d=l._parseSync({data:t.data,path:t.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!s&&(s={result:d,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return t.common.issues.push(...s.ctx.common.issues),s.result;const c=i.map(l=>new te(l));return g(t,{code:y.invalid_union,unionErrors:c}),S}}get options(){return this._def.options}}gt.create=(n,e)=>new gt({options:n,typeName:k.ZodUnion,...A(e)});const Te=n=>n instanceof bt?Te(n.schema):n instanceof ae?Te(n.innerType()):n instanceof Et?[n.value]:n instanceof Me?n.options:n instanceof kt?N.objectValues(n.enum):n instanceof Ct?Te(n._def.innerType):n instanceof yt?[void 0]:n instanceof _t?[null]:n instanceof ye?[void 0,...Te(n.unwrap())]:n instanceof De?[null,...Te(n.unwrap())]:n instanceof Cn||n instanceof At?Te(n.unwrap()):n instanceof St?Te(n._def.innerType):[];class Yt extends I{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==v.object)return g(t,{code:y.invalid_type,expected:v.object,received:t.parsedType}),S;const r=this.discriminator,o=t.data[r],s=this.optionsMap.get(o);return s?t.common.async?s._parseAsync({data:t.data,path:t.path,parent:t}):s._parseSync({data:t.data,path:t.path,parent:t}):(g(t,{code:y.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),S)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const o=new Map;for(const s of t){const i=Te(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const c of i){if(o.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);o.set(c,s)}}return new Yt({typeName:k.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:o,...A(r)})}}function kn(n,e){const t=Re(n),r=Re(e);if(n===e)return{valid:!0,data:n};if(t===v.object&&r===v.object){const o=N.objectKeys(e),s=N.objectKeys(n).filter(c=>o.indexOf(c)!==-1),i={...n,...e};for(const c of s){const l=kn(n[c],e[c]);if(!l.valid)return{valid:!1};i[c]=l.data}return{valid:!0,data:i}}else if(t===v.array&&r===v.array){if(n.length!==e.length)return{valid:!1};const o=[];for(let s=0;s<n.length;s++){const i=n[s],c=e[s],l=kn(i,c);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return t===v.date&&r===v.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}class vt extends I{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),o=(s,i)=>{if(wn(s)||wn(i))return S;const c=kn(s.value,i.value);return c.valid?((bn(s)||bn(i))&&t.dirty(),{status:t.value,value:c.data}):(g(r,{code:y.invalid_intersection_types}),S)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}vt.create=(n,e,t)=>new vt({left:n,right:e,typeName:k.ZodIntersection,...A(t)});class he extends I{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==v.array)return g(r,{code:y.invalid_type,expected:v.array,received:r.parsedType}),S;if(r.data.length<this._def.items.length)return g(r,{code:y.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),S;!this._def.rest&&r.data.length>this._def.items.length&&(g(r,{code:y.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const s=[...r.data].map((i,c)=>{const l=this._def.items[c]||this._def.rest;return l?l._parse(new me(r,i,r.path,c)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>H.mergeArray(t,i)):H.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new he({...this._def,rest:e})}}he.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new he({items:n,typeName:k.ZodTuple,rest:null,...A(e)})};class wt extends I{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==v.object)return g(r,{code:y.invalid_type,expected:v.object,received:r.parsedType}),S;const o=[],s=this._def.keyType,i=this._def.valueType;for(const c in r.data)o.push({key:s._parse(new me(r,c,r.path,c)),value:i._parse(new me(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?H.mergeObjectAsync(t,o):H.mergeObjectSync(t,o)}get element(){return this._def.valueType}static create(e,t,r){return t instanceof I?new wt({keyType:e,valueType:t,typeName:k.ZodRecord,...A(r)}):new wt({keyType:oe.create(),valueType:e,typeName:k.ZodRecord,...A(t)})}}class Wt extends I{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==v.map)return g(r,{code:y.invalid_type,expected:v.map,received:r.parsedType}),S;const o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([c,l],u)=>({key:o._parse(new me(r,c,r.path,[u,"key"])),value:s._parse(new me(r,l,r.path,[u,"value"]))}));if(r.common.async){const c=new Map;return Promise.resolve().then(async()=>{for(const l of i){const u=await l.key,d=await l.value;if(u.status==="aborted"||d.status==="aborted")return S;(u.status==="dirty"||d.status==="dirty")&&t.dirty(),c.set(u.value,d.value)}return{status:t.value,value:c}})}else{const c=new Map;for(const l of i){const u=l.key,d=l.value;if(u.status==="aborted"||d.status==="aborted")return S;(u.status==="dirty"||d.status==="dirty")&&t.dirty(),c.set(u.value,d.value)}return{status:t.value,value:c}}}}Wt.create=(n,e,t)=>new Wt({valueType:e,keyType:n,typeName:k.ZodMap,...A(t)});class Ve extends I{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==v.set)return g(r,{code:y.invalid_type,expected:v.set,received:r.parsedType}),S;const o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(g(r,{code:y.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),t.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(g(r,{code:y.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),t.dirty());const s=this._def.valueType;function i(l){const u=new Set;for(const d of l){if(d.status==="aborted")return S;d.status==="dirty"&&t.dirty(),u.add(d.value)}return{status:t.value,value:u}}const c=[...r.data.values()].map((l,u)=>s._parse(new me(r,l,r.path,u)));return r.common.async?Promise.all(c).then(l=>i(l)):i(c)}min(e,t){return new Ve({...this._def,minSize:{value:e,message:b.toString(t)}})}max(e,t){return new Ve({...this._def,maxSize:{value:e,message:b.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Ve.create=(n,e)=>new Ve({valueType:n,minSize:null,maxSize:null,typeName:k.ZodSet,...A(e)});class et extends I{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==v.function)return g(t,{code:y.invalid_type,expected:v.function,received:t.parsedType}),S;function r(c,l){return zt({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Zt(),Ke].filter(u=>!!u),issueData:{code:y.invalid_arguments,argumentsError:l}})}function o(c,l){return zt({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Zt(),Ke].filter(u=>!!u),issueData:{code:y.invalid_return_type,returnTypeError:l}})}const s={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof tt){const c=this;return Q(async function(...l){const u=new te([]),d=await c._def.args.parseAsync(l,s).catch(f=>{throw u.addIssue(r(l,f)),u}),p=await Reflect.apply(i,this,d);return await c._def.returns._def.type.parseAsync(p,s).catch(f=>{throw u.addIssue(o(p,f)),u})})}else{const c=this;return Q(function(...l){const u=c._def.args.safeParse(l,s);if(!u.success)throw new te([r(l,u.error)]);const d=Reflect.apply(i,this,u.data),p=c._def.returns.safeParse(d,s);if(!p.success)throw new te([o(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new et({...this._def,args:he.create(e).rest($e.create())})}returns(e){return new et({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new et({args:e||he.create([]).rest($e.create()),returns:t||$e.create(),typeName:k.ZodFunction,...A(r)})}}class bt extends I{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}bt.create=(n,e)=>new bt({getter:n,typeName:k.ZodLazy,...A(e)});class Et extends I{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return g(t,{received:t.data,code:y.invalid_literal,expected:this._def.value}),S}return{status:"valid",value:e.data}}get value(){return this._def.value}}Et.create=(n,e)=>new Et({value:n,typeName:k.ZodLiteral,...A(e)});function tr(n,e){return new Me({values:n,typeName:k.ZodEnum,...A(e)})}class Me extends I{constructor(){super(...arguments),ft.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),r=this._def.values;return g(t,{expected:N.joinValues(r),received:t.parsedType,code:y.invalid_type}),S}if(Gt(this,ft)||Kn(this,ft,new Set(this._def.values)),!Gt(this,ft).has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return g(t,{received:t.data,code:y.invalid_enum_value,options:r}),S}return Q(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Me.create(e,{...this._def,...t})}exclude(e,t=this._def){return Me.create(this.options.filter(r=>!e.includes(r)),{...this._def,...t})}}ft=new WeakMap,Me.create=tr;class kt extends I{constructor(){super(...arguments),mt.set(this,void 0)}_parse(e){const t=N.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==v.string&&r.parsedType!==v.number){const o=N.objectValues(t);return g(r,{expected:N.joinValues(o),received:r.parsedType,code:y.invalid_type}),S}if(Gt(this,mt)||Kn(this,mt,new Set(N.getValidEnumValues(this._def.values))),!Gt(this,mt).has(e.data)){const o=N.objectValues(t);return g(r,{received:r.data,code:y.invalid_enum_value,options:o}),S}return Q(e.data)}get enum(){return this._def.values}}mt=new WeakMap,kt.create=(n,e)=>new kt({values:n,typeName:k.ZodNativeEnum,...A(e)});class tt extends I{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==v.promise&&t.common.async===!1)return g(t,{code:y.invalid_type,expected:v.promise,received:t.parsedType}),S;const r=t.parsedType===v.promise?t.data:Promise.resolve(t.data);return Q(r.then(o=>this._def.type.parseAsync(o,{path:t.path,errorMap:t.common.contextualErrorMap})))}}tt.create=(n,e)=>new tt({type:n,typeName:k.ZodPromise,...A(e)});class ae extends I{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===k.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{g(r,i),i.fatal?t.abort():t.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const i=o.transform(r.data,s);if(r.common.async)return Promise.resolve(i).then(async c=>{if(t.value==="aborted")return S;const l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?S:l.status==="dirty"||t.value==="dirty"?Je(l.value):l});{if(t.value==="aborted")return S;const c=this._def.schema._parseSync({data:i,path:r.path,parent:r});return c.status==="aborted"?S:c.status==="dirty"||t.value==="dirty"?Je(c.value):c}}if(o.type==="refinement"){const i=c=>{const l=o.refinement(c,s);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(r.common.async===!1){const c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?S:(c.status==="dirty"&&t.dirty(),i(c.value),{status:t.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?S:(c.status==="dirty"&&t.dirty(),i(c.value).then(()=>({status:t.value,value:c.value}))))}if(o.type==="transform")if(r.common.async===!1){const i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!dt(i))return i;const c=o.transform(i.value,s);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>dt(i)?Promise.resolve(o.transform(i.value,s)).then(c=>({status:t.value,value:c})):i);N.assertNever(o)}}ae.create=(n,e,t)=>new ae({schema:n,typeName:k.ZodEffects,effect:e,...A(t)}),ae.createWithPreprocess=(n,e,t)=>new ae({schema:e,effect:{type:"preprocess",transform:n},typeName:k.ZodEffects,...A(t)});class ye extends I{_parse(e){return this._getType(e)===v.undefined?Q(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ye.create=(n,e)=>new ye({innerType:n,typeName:k.ZodOptional,...A(e)});class De extends I{_parse(e){return this._getType(e)===v.null?Q(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}De.create=(n,e)=>new De({innerType:n,typeName:k.ZodNullable,...A(e)});class Ct extends I{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===v.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Ct.create=(n,e)=>new Ct({innerType:n,typeName:k.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...A(e)});class St extends I{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return pt(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new te(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new te(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}St.create=(n,e)=>new St({innerType:n,typeName:k.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...A(e)});class Ht extends I{_parse(e){if(this._getType(e)!==v.nan){const r=this._getOrReturnCtx(e);return g(r,{code:y.invalid_type,expected:v.nan,received:r.parsedType}),S}return{status:"valid",value:e.data}}}Ht.create=n=>new Ht({typeName:k.ZodNaN,...A(n)});const cs=Symbol("zod_brand");class Cn extends I{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class Pt extends I{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?S:s.status==="dirty"?(t.dirty(),Je(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?S:o.status==="dirty"?(t.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(e,t){return new Pt({in:e,out:t,typeName:k.ZodPipeline})}}class At extends I{_parse(e){const t=this._def.innerType._parse(e),r=o=>(dt(o)&&(o.value=Object.freeze(o.value)),o);return pt(t)?t.then(o=>r(o)):r(t)}unwrap(){return this._def.innerType}}At.create=(n,e)=>new At({innerType:n,typeName:k.ZodReadonly,...A(e)});function nr(n,e={},t){return n?Qe.create().superRefine((r,o)=>{var s,i;if(!n(r)){const c=typeof e=="function"?e(r):typeof e=="string"?{message:e}:e,l=(i=(s=c.fatal)!==null&&s!==void 0?s:t)!==null&&i!==void 0?i:!0,u=typeof c=="string"?{message:c}:c;o.addIssue({code:"custom",...u,fatal:l})}}):Qe.create()}const ls={object:L.lazycreate};var k;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(k||(k={}));const us=(n,e={message:`Input not instance of ${n.name}`})=>nr(t=>t instanceof n,e),rr=oe.create,or=Ne.create,ds=Ht.create,ps=Oe.create,sr=ht.create,fs=Ue.create,ms=Bt.create,hs=yt.create,ys=_t.create,_s=Qe.create,gs=$e.create,vs=Ae.create,ws=qt.create,bs=se.create,Es=L.create,ks=L.strictCreate,Cs=gt.create,Ss=Yt.create,Ps=vt.create,As=he.create,Ts=wt.create,Is=Wt.create,xs=Ve.create,Rs=et.create,Ns=bt.create,Os=Et.create,Ms=Me.create,Ds=kt.create,Ls=tt.create,ar=ae.create,Fs=ye.create,js=De.create,Us=ae.createWithPreprocess,$s=Pt.create;var a=Object.freeze({__proto__:null,defaultErrorMap:Ke,setErrorMap:Bo,getErrorMap:Zt,makeIssue:zt,EMPTY_PATH:qo,addIssueToContext:g,ParseStatus:H,INVALID:S,DIRTY:Je,OK:Q,isAborted:wn,isDirty:bn,isValid:dt,isAsync:pt,get util(){return N},get objectUtil(){return vn},ZodParsedType:v,getParsedType:Re,ZodType:I,datetimeRegex:er,ZodString:oe,ZodNumber:Ne,ZodBigInt:Oe,ZodBoolean:ht,ZodDate:Ue,ZodSymbol:Bt,ZodUndefined:yt,ZodNull:_t,ZodAny:Qe,ZodUnknown:$e,ZodNever:Ae,ZodVoid:qt,ZodArray:se,ZodObject:L,ZodUnion:gt,ZodDiscriminatedUnion:Yt,ZodIntersection:vt,ZodTuple:he,ZodRecord:wt,ZodMap:Wt,ZodSet:Ve,ZodFunction:et,ZodLazy:bt,ZodLiteral:Et,ZodEnum:Me,ZodNativeEnum:kt,ZodPromise:tt,ZodEffects:ae,ZodTransformer:ae,ZodOptional:ye,ZodNullable:De,ZodDefault:Ct,ZodCatch:St,ZodNaN:Ht,BRAND:cs,ZodBranded:Cn,ZodPipeline:Pt,ZodReadonly:At,custom:nr,Schema:I,ZodSchema:I,late:ls,get ZodFirstPartyTypeKind(){return k},coerce:{string:n=>oe.create({...n,coerce:!0}),number:n=>Ne.create({...n,coerce:!0}),boolean:n=>ht.create({...n,coerce:!0}),bigint:n=>Oe.create({...n,coerce:!0}),date:n=>Ue.create({...n,coerce:!0})},any:_s,array:bs,bigint:ps,boolean:sr,date:fs,discriminatedUnion:Ss,effect:ar,enum:Ms,function:Rs,instanceof:us,intersection:Ps,lazy:Ns,literal:Os,map:Is,nan:ds,nativeEnum:Ds,never:vs,null:ys,nullable:js,number:or,object:Es,oboolean:()=>sr().optional(),onumber:()=>or().optional(),optional:Fs,ostring:()=>rr().optional(),pipeline:$s,preprocess:Us,promise:Ls,record:Ts,set:xs,strictObject:ks,string:rr,symbol:ms,transformer:ar,tuple:As,undefined:hs,union:Cs,unknown:gs,void:ws,NEVER:S,ZodIssueCode:y,quotelessJson:Go,ZodError:te});const Vs=a.object({type:a.string(),loc:a.array(a.string()),msg:a.string(),url:a.string()}),Zs=a.array(Vs),zs=a.object({code:a.string(),message:a.string(),path:a.array(a.string())}),Gs=a.array(zs),Bs={"failed to fetch":"Connection error: please double check if you are connected to the internet, then try again"},Sn=n=>{const e=n.toLowerCase().trim();return Bs[e]??n},qs=n=>{try{return typeof JSON.parse(n)=="object"}catch{return!1}},Ys=n=>n.length===1?Sn(n[0].msg):`Please fix the following errors:
|
|
2
|
-
${
|
|
3
|
-
`)}`,
|
|
4
|
-
${
|
|
5
|
-
`)}`,re=
|
|
6
|
-
${n.message}`),n.message)}else return Sn(n.message);if(typeof n=="object")try{return JSON.stringify(n)}catch(e){return e+""}else return n+""},Hs=(n,e,t)=>(...r)=>{try{return e(...r)}catch(o){t(`[form] Error running callback (${n}):`,o);return}};var ne=(n=>(n.pockytPaypal="pockyt-paypal",n.airwallexGooglePay="airwallex-google-pay",n.airwallexApplePay="airwallex-apple-pay",n.authorizenetGooglePay="authorizenet-google-pay",n.authorizenetApplePay="authorizenet-apple-pay",n.loopCrypto="loop-crypto",n))(ne||{});const Ks=a.nativeEnum(ne),$=a.string().trim().min(1,{message:"Cannot be blank"}),O=a.string().trim().optional(),z=n=>a.nullable(n.optional());var m=(n=>(n.FIRST_NAME="firstName",n.LAST_NAME="lastName",n.EMAIL="email",n.ZIP_CODE="zipCode",n.CITY="city",n.STATE="state",n.COUNTRY="country",n.ADDRESS="address",n.PHONE="phone",n.PROMOTION_CODE="promotionCode",n))(m||{});const ir=a.nativeEnum(m);var cr=(n=>(n.CARD_NUMBER="cardNumber",n.CARD_EXPIRY="cardExpiry",n.CARD_CVC="cardCvc",n))(cr||{});const lr=a.nativeEnum(cr),ur=a.union([ir,lr]);var _e=(n=>(n.CARD="card",n.CARD_NUMBER="card-number",n.CARD_EXPIRY="card-expiry",n.CARD_CVC="card-cvc",n.CDE_BRIDGE="cde-bridge",n))(_e||{});const Js=a.nativeEnum(_e),Kt=a.object({provider:a.string(),processor_name:z(a.string()),metadata:z(a.record(a.string(),a.any()))}),Qs=a.object({id:a.string()});a.object({cardNumber:O,expiry:O,cvc:O}),a.object({backgroundColor:O,color:O,fontFamily:O,fontSize:O,fontWeight:O,margin:O,padding:O,letterSpacing:O,lineHeight:O,hideIcon:O});const ie=a.enum(["LAYOUT","LOADED","BLUR","FOCUS","CHANGE","TOKENIZE_STARTED","CHECKOUT_STARTED","PAYMENT_FLOW_STARTED","TOKENIZE_SUCCESS","CHECKOUT_SUCCESS","LOAD_ERROR","VALIDATION_ERROR","TOKENIZE_ERROR","CHECKOUT_ERROR","SETUP_PAYMENT_METHOD_SUCCESS","TOKENIZE","CHECKOUT","START_PAYMENT_FLOW"]),Xs=ie.extract(["TOKENIZE_STARTED","CHECKOUT_STARTED"]),ea=a.object({type:Xs}),ta=ie.extract(["BLUR","FOCUS","CHANGE"]),na=a.object({type:ta,elementType:lr,errors:a.array(a.string()).optional()}),ra=ie.extract(["LOAD_ERROR","TOKENIZE_ERROR","CHECKOUT_ERROR"]),oa=a.object({type:ra,message:$,headers:a.record(a.string(),a.string()).optional()}),sa=ie.extract(["VALIDATION_ERROR"]),aa=a.object({type:sa,elementType:ur,errors:a.array(a.string())}),ia=a.object({type:a.literal(ie.enum.LAYOUT),height:$}),ca=a.object({type:a.literal(ie.enum.LOADED),sessionId:$,totalAmountAtoms:a.number(),currency:O,checkoutPaymentMethods:a.array(Kt)}),la=a.object({type:a.literal(ie.enum.PAYMENT_FLOW_STARTED),nextActionMetadata:a.record(a.string(),a.any()),paymentFlowMetadata:a.any().optional(),startPFMetadata:a.optional(a.record(a.string(),a.any()))}),ua=a.object({type:a.literal(ie.enum.SETUP_PAYMENT_METHOD_SUCCESS),paymentMethodId:a.string()}),Tt=a.object({firstName:$,lastName:$,email:$,zipCode:$,country:$,promotionCode:O}),da=a.object({firstName:O,lastName:O,email:$,zipCode:$,country:$,promotionCode:O,address:O,city:O,state:O}),pa=ie.extract(["TOKENIZE","CHECKOUT","START_PAYMENT_FLOW"]),fa=a.object({type:pa,sessionId:$,checkoutPaymentMethod:Kt,paymentFlowMetadata:a.any().optional(),doNotUseLegacyCCFlow:a.boolean().optional(),existingCCPMId:O,paymentRouteId:O}).extend(Tt.shape),ma=a.object({type:a.literal(ie.enum.TOKENIZE_SUCCESS),isReadyForCheckout:a.boolean()}),ha=a.object({type:a.literal(ie.enum.CHECKOUT_SUCCESS),invoiceUrls:a.array(a.string()),subscriptionIds:a.array(a.string()),customerId:a.string()}),ya=a.discriminatedUnion("type",[ea,na,oa,aa,ia,ca,fa,ma,ha,la,ua]),_a=a.object({payload:ya,nonce:$,formId:$,elementId:$});a.object({amountAtom:a.number(),currency:$}),a.enum(["apple_pay","google_pay"]),a.object({secure_token:a.string(),promotion_code:a.string().optional()}),a.object({secure_token:a.string(),existing_cc_pm_id:z(a.string()),their_pm_id:z(a.string()),checkout_attempt_id:z(a.string()),processor_specific_metadata:z(a.record(a.string(),a.any()))});const Pn=a.object({invoice_urls:a.array(a.string()),subscription_ids:a.array(a.string()),customer_id:a.string(),processors_used:z(a.array(a.string()))}),ga=a.object({elementType:a.string(),errors:a.array(a.string())});a.object({session_id:a.string()});const va=a.object({success:a.literal(!1),error_type:a.literal("validation_error"),errors:a.array(ga)}),wa=a.discriminatedUnion("success",[a.object({success:a.literal(!0)}),va]);a.object({session_id:a.string(),checkout_payment_method:Kt,non_cde_form_fields:Tt,do_not_use_legacy_cc_flow:a.boolean().optional(),existing_cc_pm_id:z(a.string()),extra_metadata:a.record(a.string(),a.any()),payment_route_id:z(a.string())}),a.object({session_id:a.string(),checkout_payment_method:Kt,non_cde_form_fields:Tt,extra_metadata:a.record(a.string(),a.any()).optional(),payment_route_id:z(a.string())});var V=(n=>(n.SUCCESS="success",n.FAILURE="failure",n.CANCELLED="cancelled",n))(V||{});const ba=a.object({status:a.enum(["success","failure","cancelled"]),href:a.string().optional().nullable()});a.object({href:a.string().optional().nullable()});const Ea=a.object({type:a.string(),redirect_url:a.string(),initial_intent_id:a.string(),consent_id:a.string(),their_pm_id:a.string().optional()}),dr=a.object({type:a.string(),redirect_url:z(a.string()),initial_intent_id:z(a.string()),consent_id:z(a.string()),their_pm_id:z(a.string()),payment_session:z(a.record(a.string(),a.any()))}),ka=a.discriminatedUnion("present",[a.object({present:a.literal(!0),href:a.string()}),a.object({present:a.literal(!1)})]),Ca=a.object({payment_methods:a.array(Qs),pay_first_success_response:z(Pn),required_user_actions:z(a.array(dr))}),pr=n=>{const e={};return Object.entries(n).forEach(([t,r])=>{try{const o=ir.parse(t);Array.isArray(r)?e[o]=r:Array.isArray(r._errors)&&(e[o]=r._errors)}catch{return}}),e},Sa=a.object({stripe_pk:a.string(),client_secret:a.string(),stripe_pm_id:a.string()}),Pa=a.object({type:a.string(),client_secret:a.string(),stripe_pk:a.string()}),Aa={usd:"usd",brl:"brl"},Jt=async n=>{for(let t=0;t<10;t++)fr()||await An(500);if(!fr())throw console.log("Stripe JS not found."),new Error("Stripe JS not found.");return new Stripe(n)},Ta=async(n,e)=>{const t=await Jt(n);return{elements:t.elements(e),stripe:t}},Ia=async(n,e,t,r,o)=>{const s=await Jt(n),i=Aa[t.toLowerCase().trim()];return s.paymentRequest({country:"US",currency:i,total:{label:"Total",amount:e,pending:r},requestPayerName:!0,requestPayerEmail:!0,disableWallets:[]})},An=n=>new Promise(e=>{setTimeout(e,n)}),fr=()=>"Stripe"in window,xa=async n=>new Promise((e,t)=>{try{n.on("paymentmethod",async r=>{console.log("paymentmethod EVT:: ",r),e(r)}),n.on("token",async r=>{console.log("token EVT:: ",r)}),n.on("cancel",()=>{t(new Error("Payment cancelled, please click Submit again to pay"))})}catch(r){t(r)}}),Ra=async(n,e)=>{if(!n.stripe_pk||!n.client_secret)throw new Error(`Invalid next action metadata format: ${JSON.stringify(n)}`);const r=await(await Jt(n.stripe_pk)).confirmCardSetup(n.client_secret,{payment_method:e.paymentMethod.id});if(r.error)throw e.complete("fail"),new Error(`Payment failed: ${r.error.message??"unknown"}`);return e.complete("success"),r},Na=async n=>{var o,s,i,c;const t=await(await Jt(n.stripe_pk)).confirmCardSetup(n.client_secret,{payment_method:n.stripe_pm_id}),r=(o=t.setupIntent)==null?void 0:o.status;if(r==="succeeded")console.log("[3DS] CONFIRMING PM:",n.stripe_pm_id),console.log("[3DS] Setup intent created:",t.setupIntent);else throw r==="canceled"?new Error("Payment cancelled, please click Submit again to pay"):new Error(`${((s=t.error)==null?void 0:s.message)??((c=(i=t.setupIntent)==null?void 0:i.last_setup_error)==null?void 0:c.message)??"Payment failed, please click submit again to pay."}`)},Oa=n=>JSON.stringify(n);for(var G=[],Tn=0;Tn<256;++Tn)G.push((Tn+256).toString(16).slice(1));function Ma(n,e=0){return(G[n[e+0]]+G[n[e+1]]+G[n[e+2]]+G[n[e+3]]+"-"+G[n[e+4]]+G[n[e+5]]+"-"+G[n[e+6]]+G[n[e+7]]+"-"+G[n[e+8]]+G[n[e+9]]+"-"+G[n[e+10]]+G[n[e+11]]+G[n[e+12]]+G[n[e+13]]+G[n[e+14]]+G[n[e+15]]).toLowerCase()}var Qt,Da=new Uint8Array(16);function La(){if(!Qt&&(Qt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Qt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Qt(Da)}var Fa=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const mr={randomUUID:Fa};function Xt(n,e,t){if(mr.randomUUID&&!e&&!n)return mr.randomUUID();n=n||{};var r=n.random||(n.rng||La)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,Ma(r)}const ge=(n,e)=>Array.from(n.querySelectorAll("[data-opid]")??[]).reduce((o,s)=>{const i=s.getAttribute("data-opid");return i?{...o,[i]:s.value}:o},{}),ja=n=>{try{return _a.parse(n)}catch(e){throw console.error("Error parsing event payload:",n,e),e}};var ve;(function(n){n.Call="call",n.Reply="reply",n.Syn="syn",n.SynAck="synAck",n.Ack="ack"})(ve||(ve={}));var Ze;(function(n){n.Fulfilled="fulfilled",n.Rejected="rejected"})(Ze||(Ze={}));var It;(function(n){n.ConnectionDestroyed="ConnectionDestroyed",n.ConnectionTimeout="ConnectionTimeout",n.NoIframeSrc="NoIframeSrc"})(It||(It={}));var In;(function(n){n.DataCloneError="DataCloneError"})(In||(In={}));var Le;(function(n){n.Message="message"})(Le||(Le={}));const Ua=(n,e)=>{const t=[];let r=!1;return{destroy(o){r||(r=!0,e(`${n}: Destroying connection`),t.forEach(s=>{s(o)}))},onDestroy(o){r?o():t.push(o)}}},$a=n=>(...e)=>{n&&console.log("[Penpal]",...e)},Va={"http:":"80","https:":"443"},Za=/^(https?:)?\/\/([^/:]+)?(:(\d+))?/,za=["file:","data:"],Ga=n=>{if(n&&za.find(c=>n.startsWith(c)))return"null";const e=document.location,t=Za.exec(n);let r,o,s;t?(r=t[1]?t[1]:e.protocol,o=t[2],s=t[4]):(r=e.protocol,o=e.hostname,s=e.port);const i=s&&s!==Va[r]?`:${s}`:"";return`${r}//${o}${i}`},hr=({name:n,message:e,stack:t})=>({name:n,message:e,stack:t}),Ba=n=>{const e=new Error;return Object.keys(n).forEach(t=>e[t]=n[t]),e},qa=(n,e,t)=>{const{localName:r,local:o,remote:s,originForSending:i,originForReceiving:c}=n;let l=!1;const u=d=>{if(d.source!==s||d.data.penpal!==ve.Call)return;if(c!=="*"&&d.origin!==c){t(`${r} received message from origin ${d.origin} which did not match expected origin ${c}`);return}const p=d.data,{methodName:h,args:f,id:_}=p;t(`${r}: Received ${h}() call`);const w=T=>C=>{if(t(`${r}: Sending ${h}() reply`),l){t(`${r}: Unable to send ${h}() reply due to destroyed connection`);return}const x={penpal:ve.Reply,id:_,resolution:T,returnValue:C};T===Ze.Rejected&&C instanceof Error&&(x.returnValue=hr(C),x.returnValueIsError=!0);try{s.postMessage(x,i)}catch(R){if(R.name===In.DataCloneError){const j={penpal:ve.Reply,id:_,resolution:Ze.Rejected,returnValue:hr(R),returnValueIsError:!0};s.postMessage(j,i)}throw R}};new Promise(T=>T(e[h].apply(e,f))).then(w(Ze.Fulfilled),w(Ze.Rejected))};return o.addEventListener(Le.Message,u),()=>{l=!0,o.removeEventListener(Le.Message,u)}};let Ya=0;const Wa=()=>++Ya,yr=".",_r=n=>n?n.split(yr):[],Ha=n=>n.join(yr),Ka=(n,e)=>{const t=_r(e||"");return t.push(n),Ha(t)},Ja=(n,e,t)=>{const r=_r(e);return r.reduce((o,s,i)=>(typeof o[s]>"u"&&(o[s]={}),i===r.length-1&&(o[s]=t),o[s]),n),n},gr=(n,e)=>{const t={};return Object.keys(n).forEach(r=>{const o=n[r],s=Ka(r,e);typeof o=="object"&&Object.assign(t,gr(o,s)),typeof o=="function"&&(t[s]=o)}),t},Qa=n=>{const e={};for(const t in n)Ja(e,t,n[t]);return e},Xa=(n,e,t,r,o)=>{const{localName:s,local:i,remote:c,originForSending:l,originForReceiving:u}=e;let d=!1;o(`${s}: Connecting call sender`);const p=f=>(..._)=>{o(`${s}: Sending ${f}() call`);let w;try{c.closed&&(w=!0)}catch{w=!0}if(w&&r(),d){const T=new Error(`Unable to send ${f}() call due to destroyed connection`);throw T.code=It.ConnectionDestroyed,T}return new Promise((T,C)=>{const x=Wa(),R=J=>{if(J.source!==c||J.data.penpal!==ve.Reply||J.data.id!==x)return;if(u!=="*"&&J.origin!==u){o(`${s} received message from origin ${J.origin} which did not match expected origin ${u}`);return}const W=J.data;o(`${s}: Received ${f}() reply`),i.removeEventListener(Le.Message,R);let Se=W.returnValue;W.returnValueIsError&&(Se=Ba(Se)),(W.resolution===Ze.Fulfilled?T:C)(Se)};i.addEventListener(Le.Message,R);const j={penpal:ve.Call,id:x,methodName:f,args:_};c.postMessage(j,l)})},h=t.reduce((f,_)=>(f[_]=p(_),f),{});return Object.assign(n,Qa(h)),()=>{d=!0}},ei=(n,e,t,r,o)=>{const{destroy:s,onDestroy:i}=r;let c,l;const u={};return d=>{if(e!=="*"&&d.origin!==e){o(`Parent: Handshake - Received ACK message from origin ${d.origin} which did not match expected origin ${e}`);return}o("Parent: Handshake - Received ACK");const p={localName:"Parent",local:window,remote:d.source,originForSending:t,originForReceiving:e};c&&c(),c=qa(p,n,o),i(c),l&&l.forEach(f=>{delete u[f]}),l=d.data.methodNames;const h=Xa(u,p,l,s,o);return i(h),u}},ti=(n,e,t,r)=>o=>{if(!o.source)return;if(t!=="*"&&o.origin!==t){n(`Parent: Handshake - Received SYN message from origin ${o.origin} which did not match expected origin ${t}`);return}n("Parent: Handshake - Received SYN, responding with SYN-ACK");const s={penpal:ve.SynAck,methodNames:Object.keys(e)};o.source.postMessage(s,r)},ni=6e4,ri=(n,e)=>{const{destroy:t,onDestroy:r}=e,o=setInterval(()=>{n.isConnected||(clearInterval(o),t())},ni);r(()=>{clearInterval(o)})},oi=(n,e)=>{let t;return n!==void 0&&(t=window.setTimeout(()=>{const r=new Error(`Connection timed out after ${n}ms`);r.code=It.ConnectionTimeout,e(r)},n)),()=>{clearTimeout(t)}},si=n=>{if(!n.src&&!n.srcdoc){const e=new Error("Iframe must have src or srcdoc property defined.");throw e.code=It.NoIframeSrc,e}},vr=n=>{let{iframe:e,methods:t={},childOrigin:r,timeout:o,debug:s=!1}=n;const i=$a(s),c=Ua("Parent",i),{onDestroy:l,destroy:u}=c;r||(si(e),r=Ga(e.src));const d=r==="null"?"*":r,p=gr(t),h=ti(i,p,r,d),f=ei(p,r,d,c,i);return{promise:new Promise((w,T)=>{const C=oi(o,u),x=R=>{if(!(R.source!==e.contentWindow||!R.data)){if(R.data.penpal===ve.Syn){h(R);return}if(R.data.penpal===ve.Ack){const j=f(R);j&&(C(),w(j));return}}};window.addEventListener(Le.Message,x),i("Parent: Awaiting handshake"),ri(e,c),l(R=>{window.removeEventListener(Le.Message,x),R&&T(R)})}),destroy(){u()}}},ai=async n=>{if(typeof n!="object"||!n)return!1;try{const e={type:"ping"},t=await n.send(e);if(t!==!0)throw new Error(`Expected 'true' after ping, got ${JSON.stringify(t)}`);return!0}catch(e){return console.error("Invalid CDE connection check:",e),!1}},ii=(n,e)=>!!n&&e,P=n=>a.nullable(n.optional());a.string().trim().min(1,{message:"Cannot be blank"});const ci=a.object({cde_response_type:a.literal("error"),message:a.string(),headers:a.record(a.string(),a.string()).optional()});a.enum(["usd","brl"]);const wr=a.object({name:a.string(),amount_atom_off:P(a.number()),percent_off:P(a.number()),currency:P(a.string()),duration:a.string(),duration_in_months:P(a.number())}),br=a.object({amount_subtotal_atom:a.number().int(),amount_total_atom:a.number().int(),currency:a.string(),description:P(a.string()),price_id:a.string(),billing_interval:P(a.string()),billing_interval_count:P(a.number().int()),quantity:a.number().int()}),li=a.record(a.string(),a.any()),ui=a.object({name:a.string(),settings:P(li)}),nt=a.object({provider:a.string(),processor_name:P(a.string()),metadata:P(a.record(a.string(),a.any()))}),di=a.object({quantity:a.number()}),pi=a.object({id:P(a.string()),billing_interval:P(a.string()),billing_interval_count:P(a.number().int()),subscription_items:a.array(di),trial_start:P(a.string()),trial_end:P(a.string())}),Er=a.object({amount_atom:a.number()}),fi=a.object({amount_atom:a.number(),amount_atom_considering_discount_applied:a.number(),currency:a.string(),discount_amount_atoms:a.array(Er),subscription_item_id:a.string()}),mi=a.object({coupon:wr}),hi=a.object({currency:a.string(),discounts:a.array(mi),hosted_invoice_url:P(a.string()),lines:a.array(fi),remaining_amount_atom:a.number(),tax_amount_atom:a.number(),total_amount_atom:a.number(),total_discount_amount_atoms:a.array(Er)}),kr=a.object({created:a.array(pi),invoices:a.array(hi),processors_used:P(a.array(a.string()))}),Cr=a.object({preview:kr,preview_post_trial:P(kr),coupons:a.array(wr)}),Sr=a.object({status:a.literal("open"),locale:P(a.string()),token:a.string(),email:P(a.string()),line_items:a.array(br),amount_subtotal_atom:a.number().int(),amount_total_atom:a.number().int(),brand:ui,subs_preview:P(Cr),methods_available:a.array(nt)}),Pr=a.discriminatedUnion("mode",[a.object({mode:a.literal("setup"),currency:a.nullable(a.undefined())}).extend(Sr.shape),a.object({mode:a.enum(["payment","subscription"]),currency:a.string()}).extend(Sr.shape)]),yi=a.object({status:a.literal("complete")}),_i=a.object({status:a.literal("expired")});a.union([Pr,yi,_i]),a.object({logo:a.string(),icon:a.string(),primary_color:a.string(),secondary_color:a.string()}),a.object({secure_token:a.string(),pm_id:a.string()}),a.object({secure_token:a.string(),payment_input:a.any(),customer_first_name:a.string().optional(),customer_last_name:a.string().optional(),customer_email:a.string(),customer_zip_code:a.string(),customer_country:a.string(),line_items:a.array(br),total_amount_atom:a.number().int(),cancel_at_end:a.boolean(),checkout_payment_method:nt,promotion_code:a.string().optional(),do_not_use_legacy_cc_flow:a.boolean().optional(),use_confirmed_pm_id:P(a.string()),payment_route_id:P(a.string())});const Ar=a.object({payment_method_id:a.string()});a.object({id:a.string(),return_url:a.string()});const gi=a.object({type:a.string(),loc:a.array(a.string()),msg:a.string(),url:a.string()});a.array(gi);const vi=a.object({new_customer_email:a.string().optional(),new_customer_address:a.record(a.string(),a.any()).optional(),new_customer_first_name:a.string().optional(),new_customer_last_name:a.string().optional()}),wi=a.object({price_id:a.string(),quantity:a.number().int()}),bi=a.object({line_items:a.array(wi),promotion_code:a.string().optional(),displayed_total_amount_atom:a.number().int()}),Ei=a.object({processor_specific_metadata:P(a.record(a.string(),a.any()))});a.object({payment_provider:a.string(),checkout_payment_method:nt,existing_cc_pm_id:a.string().optional(),their_existing_pm_id:a.string().optional(),use_pay_first_flow:a.boolean().optional(),pay_first_flow_cart_info:bi.optional()}).extend(vi.shape).extend(Ei.shape);const Tr=a.object({required_user_actions:a.array(a.record(a.string(),a.any())),checkout_attempt_id:P(a.string())});a.object({fields:da,checkoutPaymentMethod:nt,payment_route_id:P(a.string())}),a.object({session_id:a.string(),non_cde_form_fields:Tt,checkout_payment_method:nt,extra_metadata:a.record(a.string(),a.any()),payment_route_id:P(a.string())});const ki=a.object({required_user_actions:a.array(a.record(a.string(),a.any())),cc_pm_id:a.string()});a.record(a.any()),a.object({first_name:P(a.string()),last_name:P(a.string()),line1:P(a.string()),line2:P(a.string()),line3:P(a.string()),city:P(a.string()),state:P(a.string()),country:P(a.string()),zip_code:P(a.string()),email:P(a.string()),billing_email:P(a.string()),phone_number:P(a.string()),update_processor_customer:P(a.boolean())}),a.object({id:a.string(),email:P(a.string()),first_name:P(a.string()),last_name:P(a.string()),phone_number:P(a.string()),billing_email:P(a.string()),address:P(a.record(a.string(),a.any()))}),a.object({message:a.string()});const Ci=a.object({error_code:a.string()});a.object({checkout_payment_method:nt,processor_specific_metadata:a.record(a.any()).optional(),payment_route_id:P(a.string())});const Si=a.object({next_action_metadata:P(a.record(a.any()))});a.object({events:a.array(a.object({event_name:a.string(),device_token:a.string(),properties:a.record(a.any()).optional(),context_properties:a.record(a.any()).optional()}))}),a.any().optional(),a.object({device_token:a.string()});const Pi=a.object({}),Ai=n=>n.reduce((e,t)=>e+t,0);function Ti(n,e){var t=Object.setPrototypeOf;t?t(n,e):n.__proto__=e}function Ii(n,e){e===void 0&&(e=n.constructor);var t=Error.captureStackTrace;t&&t(n,e)}var xi=function(){var n=function(t,r){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(o,s){o.__proto__=s}||function(o,s){for(var i in s)Object.prototype.hasOwnProperty.call(s,i)&&(o[i]=s[i])},n(t,r)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),Ri=function(n){xi(e,n);function e(t,r){var o=this.constructor,s=n.call(this,t,r)||this;return Object.defineProperty(s,"name",{value:o.name,enumerable:!1,configurable:!0}),Ti(s,o.prototype),Ii(s),s}return e}(Error);const xn=10,Ir=(n=0)=>e=>`\x1B[${e+n}m`,xr=(n=0)=>e=>`\x1B[${38+n};5;${e}m`,Rr=(n=0)=>(e,t,r)=>`\x1B[${38+n};2;${e};${t};${r}m`,M={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(M.modifier);const Ni=Object.keys(M.color),Oi=Object.keys(M.bgColor);[...Ni,...Oi];function Mi(){const n=new Map;for(const[e,t]of Object.entries(M)){for(const[r,o]of Object.entries(t))M[r]={open:`\x1B[${o[0]}m`,close:`\x1B[${o[1]}m`},t[r]=M[r],n.set(o[0],o[1]);Object.defineProperty(M,e,{value:t,enumerable:!1})}return Object.defineProperty(M,"codes",{value:n,enumerable:!1}),M.color.close="\x1B[39m",M.bgColor.close="\x1B[49m",M.color.ansi=Ir(),M.color.ansi256=xr(),M.color.ansi16m=Rr(),M.bgColor.ansi=Ir(xn),M.bgColor.ansi256=xr(xn),M.bgColor.ansi16m=Rr(xn),Object.defineProperties(M,{rgbToAnsi256:{value(e,t,r){return e===t&&t===r?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(r/255*5)},enumerable:!1},hexToRgb:{value(e){const t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[r]=t;r.length===3&&(r=[...r].map(s=>s+s).join(""));const o=Number.parseInt(r,16);return[o>>16&255,o>>8&255,o&255]},enumerable:!1},hexToAnsi256:{value:e=>M.rgbToAnsi256(...M.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,r,o;if(e>=232)t=((e-232)*10+8)/255,r=t,o=t;else{e-=16;const c=e%36;t=Math.floor(e/36)/5,r=Math.floor(c/6)/5,o=c%6/5}const s=Math.max(t,r,o)*2;if(s===0)return 30;let i=30+(Math.round(o)<<2|Math.round(r)<<1|Math.round(t));return s===2&&(i+=60),i},enumerable:!1},rgbToAnsi:{value:(e,t,r)=>M.ansi256ToAnsi(M.rgbToAnsi256(e,t,r)),enumerable:!1},hexToAnsi:{value:e=>M.ansi256ToAnsi(M.hexToAnsi256(e)),enumerable:!1}}),M}const we=Mi(),en=(()=>{if(navigator.userAgentData){const n=navigator.userAgentData.brands.find(({brand:e})=>e==="Chromium");if(n&&n.version>93)return 3}return/\b(Chrome|Chromium)\//.test(navigator.userAgent)?1:0})(),Nr=en!==0&&{level:en,hasBasic:!0,has256:en>=2,has16m:en>=3},Di={stdout:Nr,stderr:Nr};function Li(n,e,t){let r=n.indexOf(e);if(r===-1)return n;const o=e.length;let s=0,i="";do i+=n.slice(s,r)+e+t,s=r+o,r=n.indexOf(e,s);while(r!==-1);return i+=n.slice(s),i}function Fi(n,e,t,r){let o=0,s="";do{const i=n[r-1]==="\r";s+=n.slice(o,i?r-1:r)+e+(i?`\r
|
|
1
|
+
(function(Ae,Ke){typeof exports=="object"&&typeof module<"u"?Ke(exports):typeof define=="function"&&define.amd?define(["exports"],Ke):(Ae=typeof globalThis<"u"?globalThis:Ae||self,Ke(Ae.OpenPay={}))})(this,function(Ae){"use strict";var Ho;const Ke="https://cde.getopenpay.com";var N;(function(t){t.assertEqual=o=>o;function e(o){}t.assertIs=e;function n(o){throw new Error}t.assertNever=n,t.arrayToEnum=o=>{const s={};for(const i of o)s[i]=i;return s},t.getValidEnumValues=o=>{const s=t.objectKeys(o).filter(c=>typeof o[o[c]]!="number"),i={};for(const c of s)i[c]=o[c];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const s=[];for(const i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(const i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=r,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(N||(N={}));var bn;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(bn||(bn={}));const v=N.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ne=t=>{switch(typeof t){case"undefined":return v.undefined;case"string":return v.string;case"number":return isNaN(t)?v.nan:v.number;case"boolean":return v.boolean;case"function":return v.function;case"bigint":return v.bigint;case"symbol":return v.symbol;case"object":return Array.isArray(t)?v.array:t===null?v.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?v.promise:typeof Map<"u"&&t instanceof Map?v.map:typeof Set<"u"&&t instanceof Set?v.set:typeof Date<"u"&&t instanceof Date?v.date:v.object;default:return v.unknown}},y=N.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Ko=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");class ne extends Error{constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){const n=e||function(s){return s.message},r={_errors:[]},o=s=>{for(const i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let c=r,l=0;for(;l<i.path.length;){const u=i.path[l];l===i.path.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(n(i))):c[u]=c[u]||{_errors:[]},c=c[u],l++}}};return o(this),r}static assert(e){if(!(e instanceof ne))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,N.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){const n={},r=[];for(const o of this.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(e(o))):r.push(e(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}ne.create=t=>new ne(t);const Je=(t,e)=>{let n;switch(t.code){case y.invalid_type:t.received===v.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case y.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,N.jsonStringifyReplacer)}`;break;case y.unrecognized_keys:n=`Unrecognized key(s) in object: ${N.joinValues(t.keys,", ")}`;break;case y.invalid_union:n="Invalid input";break;case y.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${N.joinValues(t.options)}`;break;case y.invalid_enum_value:n=`Invalid enum value. Expected ${N.joinValues(t.options)}, received '${t.received}'`;break;case y.invalid_arguments:n="Invalid function arguments";break;case y.invalid_return_type:n="Invalid function return type";break;case y.invalid_date:n="Invalid date";break;case y.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:N.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case y.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case y.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case y.custom:n="Invalid input";break;case y.invalid_intersection_types:n="Intersection results could not be merged";break;case y.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case y.not_finite:n="Number must be finite";break;default:n=e.defaultError,N.assertNever(t)}return{message:n}};let Jn=Je;function Jo(t){Jn=t}function Bt(){return Jn}const qt=t=>{const{data:e,path:n,errorMaps:r,issueData:o}=t,s=[...n,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let c="";const l=r.filter(u=>!!u).slice().reverse();for(const u of l)c=u(i,{data:e,defaultError:c}).message;return{...o,path:s,message:c}},Qo=[];function g(t,e){const n=Bt(),r=qt({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Je?void 0:Je].filter(o=>!!o)});t.common.issues.push(r)}class K{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){const r=[];for(const o of n){if(o.status==="aborted")return S;o.status==="dirty"&&e.dirty(),r.push(o.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){const r=[];for(const o of n){const s=await o.key,i=await o.value;r.push({key:s,value:i})}return K.mergeObjectSync(e,r)}static mergeObjectSync(e,n){const r={};for(const o of n){const{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return S;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(r[s.value]=i.value)}return{status:e.value,value:r}}}const S=Object.freeze({status:"aborted"}),Qe=t=>({status:"dirty",value:t}),Q=t=>({status:"valid",value:t}),En=t=>t.status==="aborted",kn=t=>t.status==="dirty",ft=t=>t.status==="valid",mt=t=>typeof Promise<"u"&&t instanceof Promise;function Yt(t,e,n,r){if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(t)}function Qn(t,e,n,r,o){if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,n),n}typeof SuppressedError=="function"&&SuppressedError;var b;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(b||(b={}));var ht,yt;class he{constructor(e,n,r,o){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Xn=(t,e)=>{if(ft(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new ne(t.common.issues);return this._error=n,this._error}}};function T(t){if(!t)return{};const{errorMap:e,invalid_type_error:n,required_error:r,description:o}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,c)=>{var l,u;const{message:d}=t;return i.code==="invalid_enum_value"?{message:d??c.defaultError}:typeof c.data>"u"?{message:(l=d??r)!==null&&l!==void 0?l:c.defaultError}:i.code!=="invalid_type"?{message:c.defaultError}:{message:(u=d??n)!==null&&u!==void 0?u:c.defaultError}},description:o}}class R{constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(e){return Ne(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Ne(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new K,ctx:{common:e.parent.common,data:e.data,parsedType:Ne(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const n=this._parse(e);if(mt(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){const n=this._parse(e);return Promise.resolve(n)}parse(e,n){const r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){var r;const o={common:{issues:[],async:(r=n==null?void 0:n.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ne(e)},s=this._parseSync({data:e,path:o.path,parent:o});return Xn(o,s)}async parseAsync(e,n){const r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ne(e)},o=this._parse({data:e,path:r.path,parent:r}),s=await(mt(o)?o:Promise.resolve(o));return Xn(r,s)}refine(e,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{const i=e(o),c=()=>s.addIssue({code:y.custom,...r(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(c(),!1)):i?!0:(c(),!1)})}refinement(e,n){return this._refinement((r,o)=>e(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(e){return new le({schema:this,typeName:C.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return _e.create(this,this._def)}nullable(){return Fe.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ce.create(this,this._def)}promise(){return nt.create(this,this._def)}or(e){return wt.create([this,e],this._def)}and(e){return bt.create(this,e,this._def)}transform(e){return new le({...T(this._def),schema:this,typeName:C.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const n=typeof e=="function"?e:()=>e;return new Pt({...T(this._def),innerType:this,defaultValue:n,typeName:C.ZodDefault})}brand(){return new Pn({typeName:C.ZodBranded,type:this,...T(this._def)})}catch(e){const n=typeof e=="function"?e:()=>e;return new At({...T(this._def),innerType:this,catchValue:n,typeName:C.ZodCatch})}describe(e){const n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Tt.create(this,e)}readonly(){return It.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Xo=/^c[^\s-]{8,}$/i,es=/^[0-9a-z]+$/,ts=/^[0-9A-HJKMNP-TV-Z]{26}$/,ns=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,rs=/^[a-z0-9_-]{21}$/i,os=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,ss=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,as="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Cn;const is=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,cs=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ls=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,er="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",us=new RegExp(`^${er}$`);function tr(t){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`),e}function ds(t){return new RegExp(`^${tr(t)}$`)}function nr(t){let e=`${er}T${tr(t)}`;const n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function ps(t,e){return!!((e==="v4"||!e)&&is.test(t)||(e==="v6"||!e)&&cs.test(t))}class ie extends R{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==v.string){const s=this._getOrReturnCtx(e);return g(s,{code:y.invalid_type,expected:v.string,received:s.parsedType}),S}const r=new K;let o;for(const s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),g(o,{code:y.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),g(o,{code:y.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){const i=e.data.length>s.value,c=e.data.length<s.value;(i||c)&&(o=this._getOrReturnCtx(e,o),i?g(o,{code:y.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):c&&g(o,{code:y.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")ss.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"email",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Cn||(Cn=new RegExp(as,"u")),Cn.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"emoji",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")ns.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"uuid",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")rs.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"nanoid",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")Xo.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"cuid",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")es.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"cuid2",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")ts.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"ulid",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),g(o,{validation:"url",code:y.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"regex",code:y.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?nr(s).test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?us.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?ds(s).test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?os.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"duration",code:y.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?ps(e.data,s.version)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"ip",code:y.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?ls.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"base64",code:y.invalid_string,message:s.message}),r.dirty()):N.assertNever(s);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(o=>e.test(o),{validation:n,code:y.invalid_string,...b.errToObj(r)})}_addCheck(e){return new ie({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...b.errToObj(e)})}url(e){return this._addCheck({kind:"url",...b.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...b.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...b.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...b.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...b.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...b.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...b.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...b.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...b.errToObj(e)})}datetime(e){var n,r;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(n=e==null?void 0:e.offset)!==null&&n!==void 0?n:!1,local:(r=e==null?void 0:e.local)!==null&&r!==void 0?r:!1,...b.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...b.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...b.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...b.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n==null?void 0:n.position,...b.errToObj(n==null?void 0:n.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...b.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...b.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...b.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...b.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...b.errToObj(n)})}nonempty(e){return this.min(1,b.errToObj(e))}trim(){return new ie({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ie({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ie({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get minLength(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}ie.create=t=>{var e;return new ie({checks:[],typeName:C.ZodString,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...T(t)})};function fs(t,e){const n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,s=parseInt(t.toFixed(o).replace(".","")),i=parseInt(e.toFixed(o).replace(".",""));return s%i/Math.pow(10,o)}class Oe extends R{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==v.number){const s=this._getOrReturnCtx(e);return g(s,{code:y.invalid_type,expected:v.number,received:s.parsedType}),S}let r;const o=new K;for(const s of this._def.checks)s.kind==="int"?N.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),g(r,{code:y.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),g(r,{code:y.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),g(r,{code:y.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?fs(e.data,s.value)!==0&&(r=this._getOrReturnCtx(e,r),g(r,{code:y.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),g(r,{code:y.not_finite,message:s.message}),o.dirty()):N.assertNever(s);return{status:o.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,b.toString(n))}gt(e,n){return this.setLimit("min",e,!1,b.toString(n))}lte(e,n){return this.setLimit("max",e,!0,b.toString(n))}lt(e,n){return this.setLimit("max",e,!1,b.toString(n))}setLimit(e,n,r,o){return new Oe({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:b.toString(o)}]})}_addCheck(e){return new Oe({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:b.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:b.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:b.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:b.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:b.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:b.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:b.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:b.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:b.toString(e)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&N.isInteger(e.value))}get isFinite(){let e=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}}Oe.create=t=>new Oe({checks:[],typeName:C.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...T(t)});class Me extends R{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce&&(e.data=BigInt(e.data)),this._getType(e)!==v.bigint){const s=this._getOrReturnCtx(e);return g(s,{code:y.invalid_type,expected:v.bigint,received:s.parsedType}),S}let r;const o=new K;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),g(r,{code:y.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),g(r,{code:y.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),g(r,{code:y.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):N.assertNever(s);return{status:o.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,b.toString(n))}gt(e,n){return this.setLimit("min",e,!1,b.toString(n))}lte(e,n){return this.setLimit("max",e,!0,b.toString(n))}lt(e,n){return this.setLimit("max",e,!1,b.toString(n))}setLimit(e,n,r,o){return new Me({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:b.toString(o)}]})}_addCheck(e){return new Me({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:b.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:b.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:b.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:b.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:b.toString(n)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}Me.create=t=>{var e;return new Me({checks:[],typeName:C.ZodBigInt,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...T(t)})};class _t extends R{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==v.boolean){const r=this._getOrReturnCtx(e);return g(r,{code:y.invalid_type,expected:v.boolean,received:r.parsedType}),S}return Q(e.data)}}_t.create=t=>new _t({typeName:C.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...T(t)});class $e extends R{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==v.date){const s=this._getOrReturnCtx(e);return g(s,{code:y.invalid_type,expected:v.date,received:s.parsedType}),S}if(isNaN(e.data.getTime())){const s=this._getOrReturnCtx(e);return g(s,{code:y.invalid_date}),S}const r=new K;let o;for(const s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),g(o,{code:y.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),g(o,{code:y.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):N.assertNever(s);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new $e({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:b.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:b.toString(n)})}get minDate(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}}$e.create=t=>new $e({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:C.ZodDate,...T(t)});class Wt extends R{_parse(e){if(this._getType(e)!==v.symbol){const r=this._getOrReturnCtx(e);return g(r,{code:y.invalid_type,expected:v.symbol,received:r.parsedType}),S}return Q(e.data)}}Wt.create=t=>new Wt({typeName:C.ZodSymbol,...T(t)});class gt extends R{_parse(e){if(this._getType(e)!==v.undefined){const r=this._getOrReturnCtx(e);return g(r,{code:y.invalid_type,expected:v.undefined,received:r.parsedType}),S}return Q(e.data)}}gt.create=t=>new gt({typeName:C.ZodUndefined,...T(t)});class vt extends R{_parse(e){if(this._getType(e)!==v.null){const r=this._getOrReturnCtx(e);return g(r,{code:y.invalid_type,expected:v.null,received:r.parsedType}),S}return Q(e.data)}}vt.create=t=>new vt({typeName:C.ZodNull,...T(t)});class Xe extends R{constructor(){super(...arguments),this._any=!0}_parse(e){return Q(e.data)}}Xe.create=t=>new Xe({typeName:C.ZodAny,...T(t)});class Ve extends R{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Q(e.data)}}Ve.create=t=>new Ve({typeName:C.ZodUnknown,...T(t)});class Te extends R{_parse(e){const n=this._getOrReturnCtx(e);return g(n,{code:y.invalid_type,expected:v.never,received:n.parsedType}),S}}Te.create=t=>new Te({typeName:C.ZodNever,...T(t)});class Ht extends R{_parse(e){if(this._getType(e)!==v.undefined){const r=this._getOrReturnCtx(e);return g(r,{code:y.invalid_type,expected:v.void,received:r.parsedType}),S}return Q(e.data)}}Ht.create=t=>new Ht({typeName:C.ZodVoid,...T(t)});class ce extends R{_parse(e){const{ctx:n,status:r}=this._processInputParams(e),o=this._def;if(n.parsedType!==v.array)return g(n,{code:y.invalid_type,expected:v.array,received:n.parsedType}),S;if(o.exactLength!==null){const i=n.data.length>o.exactLength.value,c=n.data.length<o.exactLength.value;(i||c)&&(g(n,{code:i?y.too_big:y.too_small,minimum:c?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(g(n,{code:y.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(g(n,{code:y.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,c)=>o.type._parseAsync(new he(n,i,n.path,c)))).then(i=>K.mergeArray(r,i));const s=[...n.data].map((i,c)=>o.type._parseSync(new he(n,i,n.path,c)));return K.mergeArray(r,s)}get element(){return this._def.type}min(e,n){return new ce({...this._def,minLength:{value:e,message:b.toString(n)}})}max(e,n){return new ce({...this._def,maxLength:{value:e,message:b.toString(n)}})}length(e,n){return new ce({...this._def,exactLength:{value:e,message:b.toString(n)}})}nonempty(e){return this.min(1,e)}}ce.create=(t,e)=>new ce({type:t,minLength:null,maxLength:null,exactLength:null,typeName:C.ZodArray,...T(e)});function et(t){if(t instanceof j){const e={};for(const n in t.shape){const r=t.shape[n];e[n]=_e.create(et(r))}return new j({...t._def,shape:()=>e})}else return t instanceof ce?new ce({...t._def,type:et(t.element)}):t instanceof _e?_e.create(et(t.unwrap())):t instanceof Fe?Fe.create(et(t.unwrap())):t instanceof ye?ye.create(t.items.map(e=>et(e))):t}class j extends R{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),n=N.objectKeys(e);return this._cached={shape:e,keys:n}}_parse(e){if(this._getType(e)!==v.object){const u=this._getOrReturnCtx(e);return g(u,{code:y.invalid_type,expected:v.object,received:u.parsedType}),S}const{status:r,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),c=[];if(!(this._def.catchall instanceof Te&&this._def.unknownKeys==="strip"))for(const u in o.data)i.includes(u)||c.push(u);const l=[];for(const u of i){const d=s[u],f=o.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new he(o,f,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof Te){const u=this._def.unknownKeys;if(u==="passthrough")for(const d of c)l.push({key:{status:"valid",value:d},value:{status:"valid",value:o.data[d]}});else if(u==="strict")c.length>0&&(g(o,{code:y.unrecognized_keys,keys:c}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const d of c){const f=o.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new he(o,f,o.path,d)),alwaysSet:d in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const u=[];for(const d of l){const f=await d.key,m=await d.value;u.push({key:f,value:m,alwaysSet:d.alwaysSet})}return u}).then(u=>K.mergeObjectSync(r,u)):K.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return b.errToObj,new j({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{var o,s,i,c;const l=(i=(s=(o=this._def).errorMap)===null||s===void 0?void 0:s.call(o,n,r).message)!==null&&i!==void 0?i:r.defaultError;return n.code==="unrecognized_keys"?{message:(c=b.errToObj(e).message)!==null&&c!==void 0?c:l}:{message:l}}}:{}})}strip(){return new j({...this._def,unknownKeys:"strip"})}passthrough(){return new j({...this._def,unknownKeys:"passthrough"})}extend(e){return new j({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new j({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:C.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new j({...this._def,catchall:e})}pick(e){const n={};return N.objectKeys(e).forEach(r=>{e[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new j({...this._def,shape:()=>n})}omit(e){const n={};return N.objectKeys(this.shape).forEach(r=>{e[r]||(n[r]=this.shape[r])}),new j({...this._def,shape:()=>n})}deepPartial(){return et(this)}partial(e){const n={};return N.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];e&&!e[r]?n[r]=o:n[r]=o.optional()}),new j({...this._def,shape:()=>n})}required(e){const n={};return N.objectKeys(this.shape).forEach(r=>{if(e&&!e[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof _e;)s=s._def.innerType;n[r]=s}}),new j({...this._def,shape:()=>n})}keyof(){return rr(N.objectKeys(this.shape))}}j.create=(t,e)=>new j({shape:()=>t,unknownKeys:"strip",catchall:Te.create(),typeName:C.ZodObject,...T(e)}),j.strictCreate=(t,e)=>new j({shape:()=>t,unknownKeys:"strict",catchall:Te.create(),typeName:C.ZodObject,...T(e)}),j.lazycreate=(t,e)=>new j({shape:t,unknownKeys:"strip",catchall:Te.create(),typeName:C.ZodObject,...T(e)});class wt extends R{_parse(e){const{ctx:n}=this._processInputParams(e),r=this._def.options;function o(s){for(const c of s)if(c.result.status==="valid")return c.result;for(const c of s)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;const i=s.map(c=>new ne(c.ctx.common.issues));return g(n,{code:y.invalid_union,unionErrors:i}),S}if(n.common.async)return Promise.all(r.map(async s=>{const i={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(o);{let s;const i=[];for(const l of r){const u={...n,common:{...n.common,issues:[]},parent:null},d=l._parseSync({data:n.data,path:n.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!s&&(s={result:d,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;const c=i.map(l=>new ne(l));return g(n,{code:y.invalid_union,unionErrors:c}),S}}get options(){return this._def.options}}wt.create=(t,e)=>new wt({options:t,typeName:C.ZodUnion,...T(e)});const Ie=t=>t instanceof kt?Ie(t.schema):t instanceof le?Ie(t.innerType()):t instanceof Ct?[t.value]:t instanceof De?t.options:t instanceof St?N.objectValues(t.enum):t instanceof Pt?Ie(t._def.innerType):t instanceof gt?[void 0]:t instanceof vt?[null]:t instanceof _e?[void 0,...Ie(t.unwrap())]:t instanceof Fe?[null,...Ie(t.unwrap())]:t instanceof Pn||t instanceof It?Ie(t.unwrap()):t instanceof At?Ie(t._def.innerType):[];class Kt extends R{_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==v.object)return g(n,{code:y.invalid_type,expected:v.object,received:n.parsedType}),S;const r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(g(n,{code:y.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),S)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){const o=new Map;for(const s of n){const i=Ie(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const c of i){if(o.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);o.set(c,s)}}return new Kt({typeName:C.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:o,...T(r)})}}function Sn(t,e){const n=Ne(t),r=Ne(e);if(t===e)return{valid:!0,data:t};if(n===v.object&&r===v.object){const o=N.objectKeys(e),s=N.objectKeys(t).filter(c=>o.indexOf(c)!==-1),i={...t,...e};for(const c of s){const l=Sn(t[c],e[c]);if(!l.valid)return{valid:!1};i[c]=l.data}return{valid:!0,data:i}}else if(n===v.array&&r===v.array){if(t.length!==e.length)return{valid:!1};const o=[];for(let s=0;s<t.length;s++){const i=t[s],c=e[s],l=Sn(i,c);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===v.date&&r===v.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class bt extends R{_parse(e){const{status:n,ctx:r}=this._processInputParams(e),o=(s,i)=>{if(En(s)||En(i))return S;const c=Sn(s.value,i.value);return c.valid?((kn(s)||kn(i))&&n.dirty(),{status:n.value,value:c.data}):(g(r,{code:y.invalid_intersection_types}),S)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}bt.create=(t,e,n)=>new bt({left:t,right:e,typeName:C.ZodIntersection,...T(n)});class ye extends R{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==v.array)return g(r,{code:y.invalid_type,expected:v.array,received:r.parsedType}),S;if(r.data.length<this._def.items.length)return g(r,{code:y.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),S;!this._def.rest&&r.data.length>this._def.items.length&&(g(r,{code:y.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const s=[...r.data].map((i,c)=>{const l=this._def.items[c]||this._def.rest;return l?l._parse(new he(r,i,r.path,c)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>K.mergeArray(n,i)):K.mergeArray(n,s)}get items(){return this._def.items}rest(e){return new ye({...this._def,rest:e})}}ye.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ye({items:t,typeName:C.ZodTuple,rest:null,...T(e)})};class Et extends R{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==v.object)return g(r,{code:y.invalid_type,expected:v.object,received:r.parsedType}),S;const o=[],s=this._def.keyType,i=this._def.valueType;for(const c in r.data)o.push({key:s._parse(new he(r,c,r.path,c)),value:i._parse(new he(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?K.mergeObjectAsync(n,o):K.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof R?new Et({keyType:e,valueType:n,typeName:C.ZodRecord,...T(r)}):new Et({keyType:ie.create(),valueType:e,typeName:C.ZodRecord,...T(n)})}}class Jt extends R{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==v.map)return g(r,{code:y.invalid_type,expected:v.map,received:r.parsedType}),S;const o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([c,l],u)=>({key:o._parse(new he(r,c,r.path,[u,"key"])),value:s._parse(new he(r,l,r.path,[u,"value"]))}));if(r.common.async){const c=new Map;return Promise.resolve().then(async()=>{for(const l of i){const u=await l.key,d=await l.value;if(u.status==="aborted"||d.status==="aborted")return S;(u.status==="dirty"||d.status==="dirty")&&n.dirty(),c.set(u.value,d.value)}return{status:n.value,value:c}})}else{const c=new Map;for(const l of i){const u=l.key,d=l.value;if(u.status==="aborted"||d.status==="aborted")return S;(u.status==="dirty"||d.status==="dirty")&&n.dirty(),c.set(u.value,d.value)}return{status:n.value,value:c}}}}Jt.create=(t,e,n)=>new Jt({valueType:e,keyType:t,typeName:C.ZodMap,...T(n)});class Ze extends R{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==v.set)return g(r,{code:y.invalid_type,expected:v.set,received:r.parsedType}),S;const o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(g(r,{code:y.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(g(r,{code:y.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const s=this._def.valueType;function i(l){const u=new Set;for(const d of l){if(d.status==="aborted")return S;d.status==="dirty"&&n.dirty(),u.add(d.value)}return{status:n.value,value:u}}const c=[...r.data.values()].map((l,u)=>s._parse(new he(r,l,r.path,u)));return r.common.async?Promise.all(c).then(l=>i(l)):i(c)}min(e,n){return new Ze({...this._def,minSize:{value:e,message:b.toString(n)}})}max(e,n){return new Ze({...this._def,maxSize:{value:e,message:b.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}}Ze.create=(t,e)=>new Ze({valueType:t,minSize:null,maxSize:null,typeName:C.ZodSet,...T(e)});class tt extends R{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==v.function)return g(n,{code:y.invalid_type,expected:v.function,received:n.parsedType}),S;function r(c,l){return qt({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Bt(),Je].filter(u=>!!u),issueData:{code:y.invalid_arguments,argumentsError:l}})}function o(c,l){return qt({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Bt(),Je].filter(u=>!!u),issueData:{code:y.invalid_return_type,returnTypeError:l}})}const s={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof nt){const c=this;return Q(async function(...l){const u=new ne([]),d=await c._def.args.parseAsync(l,s).catch(p=>{throw u.addIssue(r(l,p)),u}),f=await Reflect.apply(i,this,d);return await c._def.returns._def.type.parseAsync(f,s).catch(p=>{throw u.addIssue(o(f,p)),u})})}else{const c=this;return Q(function(...l){const u=c._def.args.safeParse(l,s);if(!u.success)throw new ne([r(l,u.error)]);const d=Reflect.apply(i,this,u.data),f=c._def.returns.safeParse(d,s);if(!f.success)throw new ne([o(d,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new tt({...this._def,args:ye.create(e).rest(Ve.create())})}returns(e){return new tt({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new tt({args:e||ye.create([]).rest(Ve.create()),returns:n||Ve.create(),typeName:C.ZodFunction,...T(r)})}}class kt extends R{get schema(){return this._def.getter()}_parse(e){const{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}kt.create=(t,e)=>new kt({getter:t,typeName:C.ZodLazy,...T(e)});class Ct extends R{_parse(e){if(e.data!==this._def.value){const n=this._getOrReturnCtx(e);return g(n,{received:n.data,code:y.invalid_literal,expected:this._def.value}),S}return{status:"valid",value:e.data}}get value(){return this._def.value}}Ct.create=(t,e)=>new Ct({value:t,typeName:C.ZodLiteral,...T(e)});function rr(t,e){return new De({values:t,typeName:C.ZodEnum,...T(e)})}class De extends R{constructor(){super(...arguments),ht.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const n=this._getOrReturnCtx(e),r=this._def.values;return g(n,{expected:N.joinValues(r),received:n.parsedType,code:y.invalid_type}),S}if(Yt(this,ht)||Qn(this,ht,new Set(this._def.values)),!Yt(this,ht).has(e.data)){const n=this._getOrReturnCtx(e),r=this._def.values;return g(n,{received:n.data,code:y.invalid_enum_value,options:r}),S}return Q(e.data)}get options(){return this._def.values}get enum(){const e={};for(const n of this._def.values)e[n]=n;return e}get Values(){const e={};for(const n of this._def.values)e[n]=n;return e}get Enum(){const e={};for(const n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return De.create(e,{...this._def,...n})}exclude(e,n=this._def){return De.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}}ht=new WeakMap,De.create=rr;class St extends R{constructor(){super(...arguments),yt.set(this,void 0)}_parse(e){const n=N.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==v.string&&r.parsedType!==v.number){const o=N.objectValues(n);return g(r,{expected:N.joinValues(o),received:r.parsedType,code:y.invalid_type}),S}if(Yt(this,yt)||Qn(this,yt,new Set(N.getValidEnumValues(this._def.values))),!Yt(this,yt).has(e.data)){const o=N.objectValues(n);return g(r,{received:r.data,code:y.invalid_enum_value,options:o}),S}return Q(e.data)}get enum(){return this._def.values}}yt=new WeakMap,St.create=(t,e)=>new St({values:t,typeName:C.ZodNativeEnum,...T(e)});class nt extends R{unwrap(){return this._def.type}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==v.promise&&n.common.async===!1)return g(n,{code:y.invalid_type,expected:v.promise,received:n.parsedType}),S;const r=n.parsedType===v.promise?n.data:Promise.resolve(n.data);return Q(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}nt.create=(t,e)=>new nt({type:t,typeName:C.ZodPromise,...T(e)});class le extends R{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===C.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:n,ctx:r}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{g(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const i=o.transform(r.data,s);if(r.common.async)return Promise.resolve(i).then(async c=>{if(n.value==="aborted")return S;const l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?S:l.status==="dirty"||n.value==="dirty"?Qe(l.value):l});{if(n.value==="aborted")return S;const c=this._def.schema._parseSync({data:i,path:r.path,parent:r});return c.status==="aborted"?S:c.status==="dirty"||n.value==="dirty"?Qe(c.value):c}}if(o.type==="refinement"){const i=c=>{const l=o.refinement(c,s);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(r.common.async===!1){const c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?S:(c.status==="dirty"&&n.dirty(),i(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?S:(c.status==="dirty"&&n.dirty(),i(c.value).then(()=>({status:n.value,value:c.value}))))}if(o.type==="transform")if(r.common.async===!1){const i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!ft(i))return i;const c=o.transform(i.value,s);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>ft(i)?Promise.resolve(o.transform(i.value,s)).then(c=>({status:n.value,value:c})):i);N.assertNever(o)}}le.create=(t,e,n)=>new le({schema:t,typeName:C.ZodEffects,effect:e,...T(n)}),le.createWithPreprocess=(t,e,n)=>new le({schema:e,effect:{type:"preprocess",transform:t},typeName:C.ZodEffects,...T(n)});class _e extends R{_parse(e){return this._getType(e)===v.undefined?Q(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}_e.create=(t,e)=>new _e({innerType:t,typeName:C.ZodOptional,...T(e)});class Fe extends R{_parse(e){return this._getType(e)===v.null?Q(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Fe.create=(t,e)=>new Fe({innerType:t,typeName:C.ZodNullable,...T(e)});class Pt extends R{_parse(e){const{ctx:n}=this._processInputParams(e);let r=n.data;return n.parsedType===v.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Pt.create=(t,e)=>new Pt({innerType:t,typeName:C.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...T(e)});class At extends R{_parse(e){const{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return mt(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ne(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ne(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}At.create=(t,e)=>new At({innerType:t,typeName:C.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...T(e)});class Qt extends R{_parse(e){if(this._getType(e)!==v.nan){const r=this._getOrReturnCtx(e);return g(r,{code:y.invalid_type,expected:v.nan,received:r.parsedType}),S}return{status:"valid",value:e.data}}}Qt.create=t=>new Qt({typeName:C.ZodNaN,...T(t)});const ms=Symbol("zod_brand");class Pn extends R{_parse(e){const{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class Tt extends R{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?S:s.status==="dirty"?(n.dirty(),Qe(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?S:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(e,n){return new Tt({in:e,out:n,typeName:C.ZodPipeline})}}class It extends R{_parse(e){const n=this._def.innerType._parse(e),r=o=>(ft(o)&&(o.value=Object.freeze(o.value)),o);return mt(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}}It.create=(t,e)=>new It({innerType:t,typeName:C.ZodReadonly,...T(e)});function or(t,e={},n){return t?Xe.create().superRefine((r,o)=>{var s,i;if(!t(r)){const c=typeof e=="function"?e(r):typeof e=="string"?{message:e}:e,l=(i=(s=c.fatal)!==null&&s!==void 0?s:n)!==null&&i!==void 0?i:!0,u=typeof c=="string"?{message:c}:c;o.addIssue({code:"custom",...u,fatal:l})}}):Xe.create()}const hs={object:j.lazycreate};var C;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(C||(C={}));const ys=(t,e={message:`Input not instance of ${t.name}`})=>or(n=>n instanceof t,e),sr=ie.create,ar=Oe.create,_s=Qt.create,gs=Me.create,ir=_t.create,vs=$e.create,ws=Wt.create,bs=gt.create,Es=vt.create,ks=Xe.create,Cs=Ve.create,Ss=Te.create,Ps=Ht.create,As=ce.create,Ts=j.create,Is=j.strictCreate,xs=wt.create,Rs=Kt.create,Ns=bt.create,Os=ye.create,Ms=Et.create,Ds=Jt.create,Fs=Ze.create,Ls=tt.create,js=kt.create,Us=Ct.create,$s=De.create,Vs=St.create,Zs=nt.create,cr=le.create,zs=_e.create,Gs=Fe.create,Bs=le.createWithPreprocess,qs=Tt.create;var a=Object.freeze({__proto__:null,defaultErrorMap:Je,setErrorMap:Jo,getErrorMap:Bt,makeIssue:qt,EMPTY_PATH:Qo,addIssueToContext:g,ParseStatus:K,INVALID:S,DIRTY:Qe,OK:Q,isAborted:En,isDirty:kn,isValid:ft,isAsync:mt,get util(){return N},get objectUtil(){return bn},ZodParsedType:v,getParsedType:Ne,ZodType:R,datetimeRegex:nr,ZodString:ie,ZodNumber:Oe,ZodBigInt:Me,ZodBoolean:_t,ZodDate:$e,ZodSymbol:Wt,ZodUndefined:gt,ZodNull:vt,ZodAny:Xe,ZodUnknown:Ve,ZodNever:Te,ZodVoid:Ht,ZodArray:ce,ZodObject:j,ZodUnion:wt,ZodDiscriminatedUnion:Kt,ZodIntersection:bt,ZodTuple:ye,ZodRecord:Et,ZodMap:Jt,ZodSet:Ze,ZodFunction:tt,ZodLazy:kt,ZodLiteral:Ct,ZodEnum:De,ZodNativeEnum:St,ZodPromise:nt,ZodEffects:le,ZodTransformer:le,ZodOptional:_e,ZodNullable:Fe,ZodDefault:Pt,ZodCatch:At,ZodNaN:Qt,BRAND:ms,ZodBranded:Pn,ZodPipeline:Tt,ZodReadonly:It,custom:or,Schema:R,ZodSchema:R,late:hs,get ZodFirstPartyTypeKind(){return C},coerce:{string:t=>ie.create({...t,coerce:!0}),number:t=>Oe.create({...t,coerce:!0}),boolean:t=>_t.create({...t,coerce:!0}),bigint:t=>Me.create({...t,coerce:!0}),date:t=>$e.create({...t,coerce:!0})},any:ks,array:As,bigint:gs,boolean:ir,date:vs,discriminatedUnion:Rs,effect:cr,enum:$s,function:Ls,instanceof:ys,intersection:Ns,lazy:js,literal:Us,map:Ds,nan:_s,nativeEnum:Vs,never:Ss,null:Es,nullable:Gs,number:ar,object:Ts,oboolean:()=>ir().optional(),onumber:()=>ar().optional(),optional:zs,ostring:()=>sr().optional(),pipeline:qs,preprocess:Bs,promise:Zs,record:Ms,set:Fs,strictObject:Is,string:sr,symbol:ws,transformer:cr,tuple:Os,undefined:bs,union:xs,unknown:Cs,void:Ps,NEVER:S,ZodIssueCode:y,quotelessJson:Ko,ZodError:ne});const Ys=a.object({type:a.string(),loc:a.array(a.string()),msg:a.string(),url:a.string()}),Ws=a.array(Ys),Hs=a.object({code:a.string(),message:a.string(),path:a.array(a.string())}),Ks=a.array(Hs),Js={"failed to fetch":"Connection error: please double check if you are connected to the internet, then try again"},An=t=>{const e=t.toLowerCase().trim();return Js[e]??t},Qs=t=>{try{return typeof JSON.parse(t)=="object"}catch{return!1}},Xs=t=>t.length===1?An(t[0].msg):`Please fix the following errors:
|
|
2
|
+
${t.map(n=>`• ${An(n.msg)}`).join(`
|
|
3
|
+
`)}`,ea=t=>`Encountered the following errors:
|
|
4
|
+
${t.map(n=>`- ${n.path.join("/")}: ${n.message}`).join(`
|
|
5
|
+
`)}`,re=t=>{if(t instanceof Error)if(Qs(t.message)){const e=JSON.parse(t.message);return Ws.safeParse(e).success?Xs(e):Ks.safeParse(e).success?ea(e):(console.warn(`Encountered unknown stringified JSON object:
|
|
6
|
+
${t.message}`),t.message)}else return An(t.message);if(typeof t=="object")try{return JSON.stringify(t)}catch(e){return e+""}else return t+""},ta=(t,e,n)=>(...r)=>{try{return e(...r)}catch(o){n(`[form] Error running callback (${t}):`,o);return}};var X=(t=>(t.pockytPaypal="pockyt-paypal",t.airwallexGooglePay="airwallex-google-pay",t.airwallexApplePay="airwallex-apple-pay",t.authorizenetGooglePay="authorizenet-google-pay",t.authorizenetApplePay="authorizenet-apple-pay",t.loopCrypto="loop-crypto",t.paypal="paypal",t))(X||{});const na=a.nativeEnum(X),Z=a.string().trim().min(1,{message:"Cannot be blank"}),O=a.string().trim().optional(),q=t=>a.nullable(t.optional());var h=(t=>(t.FIRST_NAME="firstName",t.LAST_NAME="lastName",t.EMAIL="email",t.ZIP_CODE="zipCode",t.CITY="city",t.STATE="state",t.COUNTRY="country",t.ADDRESS="address",t.PHONE="phone",t.PROMOTION_CODE="promotionCode",t))(h||{});const lr=a.nativeEnum(h);var ur=(t=>(t.CARD_NUMBER="cardNumber",t.CARD_EXPIRY="cardExpiry",t.CARD_CVC="cardCvc",t))(ur||{});const dr=a.nativeEnum(ur),pr=a.union([lr,dr]);var ge=(t=>(t.CARD="card",t.CARD_NUMBER="card-number",t.CARD_EXPIRY="card-expiry",t.CARD_CVC="card-cvc",t.CDE_BRIDGE="cde-bridge",t))(ge||{});const ra=a.nativeEnum(ge),Xt=a.object({provider:a.string(),processor_name:q(a.string()),metadata:q(a.record(a.string(),a.any()))}),oa=a.object({id:a.string()});a.object({cardNumber:O,expiry:O,cvc:O}),a.object({backgroundColor:O,color:O,fontFamily:O,fontSize:O,fontWeight:O,margin:O,padding:O,letterSpacing:O,lineHeight:O,hideIcon:O});const ue=a.enum(["LAYOUT","LOADED","BLUR","FOCUS","CHANGE","TOKENIZE_STARTED","CHECKOUT_STARTED","PAYMENT_FLOW_STARTED","TOKENIZE_SUCCESS","CHECKOUT_SUCCESS","LOAD_ERROR","VALIDATION_ERROR","TOKENIZE_ERROR","CHECKOUT_ERROR","SETUP_PAYMENT_METHOD_SUCCESS","TOKENIZE","CHECKOUT","START_PAYMENT_FLOW"]),sa=ue.extract(["TOKENIZE_STARTED","CHECKOUT_STARTED"]),aa=a.object({type:sa}),ia=ue.extract(["BLUR","FOCUS","CHANGE"]),ca=a.object({type:ia,elementType:dr,errors:a.array(a.string()).optional()}),la=ue.extract(["LOAD_ERROR","TOKENIZE_ERROR","CHECKOUT_ERROR"]),ua=a.object({type:la,message:Z,headers:a.record(a.string(),a.string()).optional()}),da=ue.extract(["VALIDATION_ERROR"]),pa=a.object({type:da,elementType:pr,errors:a.array(a.string())}),fa=a.object({type:a.literal(ue.enum.LAYOUT),height:Z}),ma=a.object({type:a.literal(ue.enum.LOADED),sessionId:Z,totalAmountAtoms:a.number(),currency:O,checkoutPaymentMethods:a.array(Xt)}),ha=a.object({type:a.literal(ue.enum.PAYMENT_FLOW_STARTED),nextActionMetadata:a.record(a.string(),a.any()),paymentFlowMetadata:a.any().optional(),startPFMetadata:a.optional(a.record(a.string(),a.any()))}),ya=a.object({type:a.literal(ue.enum.SETUP_PAYMENT_METHOD_SUCCESS),paymentMethodId:a.string()}),xt=a.object({firstName:Z,lastName:Z,email:Z,zipCode:Z,country:Z,promotionCode:O}),_a=a.object({firstName:O,lastName:O,email:Z,zipCode:Z,country:Z,promotionCode:O,address:O,city:O,state:O}),ga=ue.extract(["TOKENIZE","CHECKOUT","START_PAYMENT_FLOW"]),va=a.object({type:ga,sessionId:Z,checkoutPaymentMethod:Xt,paymentFlowMetadata:a.any().optional(),doNotUseLegacyCCFlow:a.boolean().optional(),existingCCPMId:O,paymentRouteId:O}).extend(xt.shape),wa=a.object({type:a.literal(ue.enum.TOKENIZE_SUCCESS),isReadyForCheckout:a.boolean()}),ba=a.object({type:a.literal(ue.enum.CHECKOUT_SUCCESS),invoiceUrls:a.array(a.string()),subscriptionIds:a.array(a.string()),customerId:a.string()}),Ea=a.discriminatedUnion("type",[aa,ca,ua,pa,fa,ma,va,wa,ba,ha,ya]),ka=a.object({payload:Ea,nonce:Z,formId:Z,elementId:Z});a.object({amountAtom:a.number(),currency:Z}),a.enum(["apple_pay","google_pay"]),a.object({secure_token:a.string(),promotion_code:a.string().optional()}),a.object({secure_token:a.string(),existing_cc_pm_id:q(a.string()),their_pm_id:q(a.string()),checkout_attempt_id:q(a.string()),processor_specific_metadata:q(a.record(a.string(),a.any()))});const Tn=a.object({invoice_urls:a.array(a.string()),subscription_ids:a.array(a.string()),customer_id:a.string(),processors_used:q(a.array(a.string()))}),Ca=a.object({elementType:a.string(),errors:a.array(a.string())});a.object({session_id:a.string()});const Sa=a.object({success:a.literal(!1),error_type:a.literal("validation_error"),errors:a.array(Ca)}),Pa=a.discriminatedUnion("success",[a.object({success:a.literal(!0)}),Sa]);a.object({session_id:a.string(),checkout_payment_method:Xt,non_cde_form_fields:xt,do_not_use_legacy_cc_flow:a.boolean().optional(),existing_cc_pm_id:q(a.string()),extra_metadata:a.record(a.string(),a.any()),payment_route_id:q(a.string())}),a.object({session_id:a.string(),checkout_payment_method:Xt,non_cde_form_fields:xt,extra_metadata:a.record(a.string(),a.any()).optional(),payment_route_id:q(a.string())});var z=(t=>(t.SUCCESS="success",t.FAILURE="failure",t.CANCELLED="cancelled",t))(z||{});const Aa=a.object({status:a.enum(["success","failure","cancelled"]),href:a.string().optional().nullable()});a.object({href:a.string().optional().nullable()});const Ta=a.object({type:a.string(),redirect_url:a.string(),initial_intent_id:a.string(),consent_id:a.string(),their_pm_id:a.string().optional()}),fr=a.object({type:a.string(),redirect_url:q(a.string()),initial_intent_id:q(a.string()),consent_id:q(a.string()),their_pm_id:q(a.string()),payment_session:q(a.record(a.string(),a.any()))}),Ia=a.discriminatedUnion("present",[a.object({present:a.literal(!0),href:a.string()}),a.object({present:a.literal(!1)})]),xa=a.object({payment_methods:a.array(oa),pay_first_success_response:q(Tn),required_user_actions:q(a.array(fr))}),mr=t=>{const e={};return Object.entries(t).forEach(([n,r])=>{try{const o=lr.parse(n);Array.isArray(r)?e[o]=r:Array.isArray(r._errors)&&(e[o]=r._errors)}catch{return}}),e},Ra=a.object({stripe_pk:a.string(),client_secret:a.string(),stripe_pm_id:a.string()}),Na=a.object({type:a.string(),client_secret:a.string(),stripe_pk:a.string()}),Oa={usd:"usd",brl:"brl"},en=async t=>{for(let n=0;n<10;n++)hr()||await tn(500);if(!hr())throw console.log("Stripe JS not found."),new Error("Stripe JS not found.");return new Stripe(t)},Ma=async(t,e)=>{const n=await en(t);return{elements:n.elements(e),stripe:n}},Da=async(t,e,n,r,o)=>{const s=await en(t),i=Oa[n.toLowerCase().trim()];return s.paymentRequest({country:"US",currency:i,total:{label:"Total",amount:e,pending:r},requestPayerName:!0,requestPayerEmail:!0,disableWallets:[]})},tn=t=>new Promise(e=>{setTimeout(e,t)}),hr=()=>"Stripe"in window,Fa=async t=>new Promise((e,n)=>{try{t.on("paymentmethod",async r=>{console.log("paymentmethod EVT:: ",r),e(r)}),t.on("token",async r=>{console.log("token EVT:: ",r)}),t.on("cancel",()=>{n(new Error("Payment cancelled, please click Submit again to pay"))})}catch(r){n(r)}}),La=async(t,e)=>{if(!t.stripe_pk||!t.client_secret)throw new Error(`Invalid next action metadata format: ${JSON.stringify(t)}`);const r=await(await en(t.stripe_pk)).confirmCardSetup(t.client_secret,{payment_method:e.paymentMethod.id});if(r.error)throw e.complete("fail"),new Error(`Payment failed: ${r.error.message??"unknown"}`);return e.complete("success"),r},ja=async t=>{var o,s,i,c;const n=await(await en(t.stripe_pk)).confirmCardSetup(t.client_secret,{payment_method:t.stripe_pm_id}),r=(o=n.setupIntent)==null?void 0:o.status;if(r==="succeeded")console.log("[3DS] CONFIRMING PM:",t.stripe_pm_id),console.log("[3DS] Setup intent created:",n.setupIntent);else throw r==="canceled"?new Error("Payment cancelled, please click Submit again to pay"):new Error(`${((s=n.error)==null?void 0:s.message)??((c=(i=n.setupIntent)==null?void 0:i.last_setup_error)==null?void 0:c.message)??"Payment failed, please click submit again to pay."}`)},Ua=t=>JSON.stringify(t);for(var Y=[],In=0;In<256;++In)Y.push((In+256).toString(16).slice(1));function $a(t,e=0){return(Y[t[e+0]]+Y[t[e+1]]+Y[t[e+2]]+Y[t[e+3]]+"-"+Y[t[e+4]]+Y[t[e+5]]+"-"+Y[t[e+6]]+Y[t[e+7]]+"-"+Y[t[e+8]]+Y[t[e+9]]+"-"+Y[t[e+10]]+Y[t[e+11]]+Y[t[e+12]]+Y[t[e+13]]+Y[t[e+14]]+Y[t[e+15]]).toLowerCase()}var nn,Va=new Uint8Array(16);function Za(){if(!nn&&(nn=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!nn))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return nn(Va)}var za=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const yr={randomUUID:za};function Rt(t,e,n){if(yr.randomUUID&&!e&&!t)return yr.randomUUID();t=t||{};var r=t.random||(t.rng||Za)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,$a(r)}const oe=(t,e)=>Array.from(t.querySelectorAll("[data-opid]")??[]).reduce((o,s)=>{const i=s.getAttribute("data-opid");return i?{...o,[i]:s.value}:o},{}),Ga=t=>{try{return ka.parse(t)}catch(e){throw console.error("Error parsing event payload:",t,e),e}};var ve;(function(t){t.Call="call",t.Reply="reply",t.Syn="syn",t.SynAck="synAck",t.Ack="ack"})(ve||(ve={}));var ze;(function(t){t.Fulfilled="fulfilled",t.Rejected="rejected"})(ze||(ze={}));var Nt;(function(t){t.ConnectionDestroyed="ConnectionDestroyed",t.ConnectionTimeout="ConnectionTimeout",t.NoIframeSrc="NoIframeSrc"})(Nt||(Nt={}));var xn;(function(t){t.DataCloneError="DataCloneError"})(xn||(xn={}));var Le;(function(t){t.Message="message"})(Le||(Le={}));const Ba=(t,e)=>{const n=[];let r=!1;return{destroy(o){r||(r=!0,e(`${t}: Destroying connection`),n.forEach(s=>{s(o)}))},onDestroy(o){r?o():n.push(o)}}},qa=t=>(...e)=>{t&&console.log("[Penpal]",...e)},Ya={"http:":"80","https:":"443"},Wa=/^(https?:)?\/\/([^/:]+)?(:(\d+))?/,Ha=["file:","data:"],Ka=t=>{if(t&&Ha.find(c=>t.startsWith(c)))return"null";const e=document.location,n=Wa.exec(t);let r,o,s;n?(r=n[1]?n[1]:e.protocol,o=n[2],s=n[4]):(r=e.protocol,o=e.hostname,s=e.port);const i=s&&s!==Ya[r]?`:${s}`:"";return`${r}//${o}${i}`},_r=({name:t,message:e,stack:n})=>({name:t,message:e,stack:n}),Ja=t=>{const e=new Error;return Object.keys(t).forEach(n=>e[n]=t[n]),e},Qa=(t,e,n)=>{const{localName:r,local:o,remote:s,originForSending:i,originForReceiving:c}=t;let l=!1;const u=d=>{if(d.source!==s||d.data.penpal!==ve.Call)return;if(c!=="*"&&d.origin!==c){n(`${r} received message from origin ${d.origin} which did not match expected origin ${c}`);return}const f=d.data,{methodName:m,args:p,id:_}=f;n(`${r}: Received ${m}() call`);const w=A=>k=>{if(n(`${r}: Sending ${m}() reply`),l){n(`${r}: Unable to send ${m}() reply due to destroyed connection`);return}const x={penpal:ve.Reply,id:_,resolution:A,returnValue:k};A===ze.Rejected&&k instanceof Error&&(x.returnValue=_r(k),x.returnValueIsError=!0);try{s.postMessage(x,i)}catch(I){if(I.name===xn.DataCloneError){const L={penpal:ve.Reply,id:_,resolution:ze.Rejected,returnValue:_r(I),returnValueIsError:!0};s.postMessage(L,i)}throw I}};new Promise(A=>A(e[m].apply(e,p))).then(w(ze.Fulfilled),w(ze.Rejected))};return o.addEventListener(Le.Message,u),()=>{l=!0,o.removeEventListener(Le.Message,u)}};let Xa=0;const ei=()=>++Xa,gr=".",vr=t=>t?t.split(gr):[],ti=t=>t.join(gr),ni=(t,e)=>{const n=vr(e||"");return n.push(t),ti(n)},ri=(t,e,n)=>{const r=vr(e);return r.reduce((o,s,i)=>(typeof o[s]>"u"&&(o[s]={}),i===r.length-1&&(o[s]=n),o[s]),t),t},wr=(t,e)=>{const n={};return Object.keys(t).forEach(r=>{const o=t[r],s=ni(r,e);typeof o=="object"&&Object.assign(n,wr(o,s)),typeof o=="function"&&(n[s]=o)}),n},oi=t=>{const e={};for(const n in t)ri(e,n,t[n]);return e},si=(t,e,n,r,o)=>{const{localName:s,local:i,remote:c,originForSending:l,originForReceiving:u}=e;let d=!1;o(`${s}: Connecting call sender`);const f=p=>(..._)=>{o(`${s}: Sending ${p}() call`);let w;try{c.closed&&(w=!0)}catch{w=!0}if(w&&r(),d){const A=new Error(`Unable to send ${p}() call due to destroyed connection`);throw A.code=Nt.ConnectionDestroyed,A}return new Promise((A,k)=>{const x=ei(),I=B=>{if(B.source!==c||B.data.penpal!==ve.Reply||B.data.id!==x)return;if(u!=="*"&&B.origin!==u){o(`${s} received message from origin ${B.origin} which did not match expected origin ${u}`);return}const V=B.data;o(`${s}: Received ${p}() reply`),i.removeEventListener(Le.Message,I);let Pe=V.returnValue;V.returnValueIsError&&(Pe=Ja(Pe)),(V.resolution===ze.Fulfilled?A:k)(Pe)};i.addEventListener(Le.Message,I);const L={penpal:ve.Call,id:x,methodName:p,args:_};c.postMessage(L,l)})},m=n.reduce((p,_)=>(p[_]=f(_),p),{});return Object.assign(t,oi(m)),()=>{d=!0}},ai=(t,e,n,r,o)=>{const{destroy:s,onDestroy:i}=r;let c,l;const u={};return d=>{if(e!=="*"&&d.origin!==e){o(`Parent: Handshake - Received ACK message from origin ${d.origin} which did not match expected origin ${e}`);return}o("Parent: Handshake - Received ACK");const f={localName:"Parent",local:window,remote:d.source,originForSending:n,originForReceiving:e};c&&c(),c=Qa(f,t,o),i(c),l&&l.forEach(p=>{delete u[p]}),l=d.data.methodNames;const m=si(u,f,l,s,o);return i(m),u}},ii=(t,e,n,r)=>o=>{if(!o.source)return;if(n!=="*"&&o.origin!==n){t(`Parent: Handshake - Received SYN message from origin ${o.origin} which did not match expected origin ${n}`);return}t("Parent: Handshake - Received SYN, responding with SYN-ACK");const s={penpal:ve.SynAck,methodNames:Object.keys(e)};o.source.postMessage(s,r)},ci=6e4,li=(t,e)=>{const{destroy:n,onDestroy:r}=e,o=setInterval(()=>{t.isConnected||(clearInterval(o),n())},ci);r(()=>{clearInterval(o)})},ui=(t,e)=>{let n;return t!==void 0&&(n=window.setTimeout(()=>{const r=new Error(`Connection timed out after ${t}ms`);r.code=Nt.ConnectionTimeout,e(r)},t)),()=>{clearTimeout(n)}},di=t=>{if(!t.src&&!t.srcdoc){const e=new Error("Iframe must have src or srcdoc property defined.");throw e.code=Nt.NoIframeSrc,e}},br=t=>{let{iframe:e,methods:n={},childOrigin:r,timeout:o,debug:s=!1}=t;const i=qa(s),c=Ba("Parent",i),{onDestroy:l,destroy:u}=c;r||(di(e),r=Ka(e.src));const d=r==="null"?"*":r,f=wr(n),m=ii(i,f,r,d),p=ai(f,r,d,c,i);return{promise:new Promise((w,A)=>{const k=ui(o,u),x=I=>{if(!(I.source!==e.contentWindow||!I.data)){if(I.data.penpal===ve.Syn){m(I);return}if(I.data.penpal===ve.Ack){const L=p(I);L&&(k(),w(L));return}}};window.addEventListener(Le.Message,x),i("Parent: Awaiting handshake"),li(e,c),l(I=>{window.removeEventListener(Le.Message,x),I&&A(I)})}),destroy(){u()}}},pi=async t=>{if(typeof t!="object"||!t)return!1;try{const e={type:"ping"},n=await t.send(e);if(n!==!0)throw new Error(`Expected 'true' after ping, got ${JSON.stringify(n)}`);return!0}catch(e){return console.error("Invalid CDE connection check:",e),!1}},fi=(t,e)=>!!t&&e,P=t=>a.nullable(t.optional());a.string().trim().min(1,{message:"Cannot be blank"});const mi=a.object({cde_response_type:a.literal("error"),message:a.string(),headers:a.record(a.string(),a.string()).optional()});a.enum(["usd","brl"]);const Er=a.object({name:a.string(),amount_atom_off:P(a.number()),percent_off:P(a.number()),currency:P(a.string()),duration:a.string(),duration_in_months:P(a.number())}),kr=a.object({amount_subtotal_atom:a.number().int(),amount_total_atom:a.number().int(),currency:a.string(),description:P(a.string()),price_id:a.string(),billing_interval:P(a.string()),billing_interval_count:P(a.number().int()),quantity:a.number().int()}),hi=a.record(a.string(),a.any()),yi=a.object({name:a.string(),settings:P(hi)}),rt=a.object({provider:a.string(),processor_name:P(a.string()),metadata:P(a.record(a.string(),a.any()))}),_i=a.object({quantity:a.number()}),gi=a.object({id:P(a.string()),billing_interval:P(a.string()),billing_interval_count:P(a.number().int()),subscription_items:a.array(_i),trial_start:P(a.string()),trial_end:P(a.string())}),Cr=a.object({amount_atom:a.number()}),vi=a.object({amount_atom:a.number(),amount_atom_considering_discount_applied:a.number(),currency:a.string(),discount_amount_atoms:a.array(Cr),subscription_item_id:a.string()}),wi=a.object({coupon:Er}),bi=a.object({currency:a.string(),discounts:a.array(wi),hosted_invoice_url:P(a.string()),lines:a.array(vi),remaining_amount_atom:a.number(),tax_amount_atom:a.number(),total_amount_atom:a.number(),total_discount_amount_atoms:a.array(Cr)}),Sr=a.object({created:a.array(gi),invoices:a.array(bi),processors_used:P(a.array(a.string()))}),Pr=a.object({preview:Sr,preview_post_trial:P(Sr),coupons:a.array(Er)}),Ar=a.object({status:a.literal("open"),locale:P(a.string()),token:a.string(),email:P(a.string()),line_items:a.array(kr),amount_subtotal_atom:a.number().int(),amount_total_atom:a.number().int(),brand:yi,subs_preview:P(Pr),methods_available:a.array(rt)}),Tr=a.discriminatedUnion("mode",[a.object({mode:a.literal("setup"),currency:a.nullable(a.undefined())}).extend(Ar.shape),a.object({mode:a.enum(["payment","subscription"]),currency:a.string()}).extend(Ar.shape)]),Ei=a.object({status:a.literal("complete")}),ki=a.object({status:a.literal("expired")});a.union([Tr,Ei,ki]),a.object({logo:a.string(),icon:a.string(),primary_color:a.string(),secondary_color:a.string()}),a.object({secure_token:a.string(),pm_id:a.string()}),a.object({secure_token:a.string(),payment_input:a.any(),customer_first_name:a.string().optional(),customer_last_name:a.string().optional(),customer_email:a.string(),customer_zip_code:a.string(),customer_country:a.string(),line_items:a.array(kr),total_amount_atom:a.number().int(),cancel_at_end:a.boolean(),checkout_payment_method:rt,promotion_code:a.string().optional(),do_not_use_legacy_cc_flow:a.boolean().optional(),use_confirmed_pm_id:P(a.string()),payment_route_id:P(a.string())});const Ir=a.object({payment_method_id:a.string()});a.object({id:a.string(),return_url:a.string()});const Ci=a.object({type:a.string(),loc:a.array(a.string()),msg:a.string(),url:a.string()});a.array(Ci);const Si=a.object({new_customer_email:a.string().optional(),new_customer_address:a.record(a.string(),a.any()).optional(),new_customer_first_name:a.string().optional(),new_customer_last_name:a.string().optional()}),Pi=a.object({price_id:a.string(),quantity:a.number().int()}),Ai=a.object({line_items:a.array(Pi),promotion_code:a.string().optional(),displayed_total_amount_atom:a.number().int()}),Ti=a.object({processor_specific_metadata:P(a.record(a.string(),a.any()))});a.object({payment_provider:a.string(),checkout_payment_method:rt,existing_cc_pm_id:a.string().optional(),their_existing_pm_id:a.string().optional(),use_pay_first_flow:a.boolean().optional(),pay_first_flow_cart_info:Ai.optional()}).extend(Si.shape).extend(Ti.shape);const xr=a.object({required_user_actions:a.array(a.record(a.string(),a.any())),checkout_attempt_id:P(a.string())});a.object({fields:_a,checkoutPaymentMethod:rt,payment_route_id:P(a.string())}),a.object({session_id:a.string(),non_cde_form_fields:xt,checkout_payment_method:rt,extra_metadata:a.record(a.string(),a.any()),payment_route_id:P(a.string())});const Ii=a.object({required_user_actions:a.array(a.record(a.string(),a.any())),cc_pm_id:a.string()});a.record(a.any()),a.object({first_name:P(a.string()),last_name:P(a.string()),line1:P(a.string()),line2:P(a.string()),line3:P(a.string()),city:P(a.string()),state:P(a.string()),country:P(a.string()),zip_code:P(a.string()),email:P(a.string()),billing_email:P(a.string()),phone_number:P(a.string()),update_processor_customer:P(a.boolean())}),a.object({id:a.string(),email:P(a.string()),first_name:P(a.string()),last_name:P(a.string()),phone_number:P(a.string()),billing_email:P(a.string()),address:P(a.record(a.string(),a.any()))}),a.object({message:a.string()});const xi=a.object({error_code:a.string()});a.object({checkout_payment_method:rt,processor_specific_metadata:a.record(a.any()).optional(),payment_route_id:P(a.string())});const Ri=a.object({next_action_metadata:P(a.record(a.any()))});a.object({events:a.array(a.object({event_name:a.string(),device_token:a.string(),properties:a.record(a.any()).optional(),context_properties:a.record(a.any()).optional()}))}),a.any().optional(),a.object({device_token:a.string()});const Ni=a.object({}),Oi=t=>t.reduce((e,n)=>e+n,0);function Mi(t,e){var n=Object.setPrototypeOf;n?n(t,e):t.__proto__=e}function Di(t,e){e===void 0&&(e=t.constructor);var n=Error.captureStackTrace;n&&n(t,e)}var Fi=function(){var t=function(n,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(o,s){o.__proto__=s}||function(o,s){for(var i in s)Object.prototype.hasOwnProperty.call(s,i)&&(o[i]=s[i])},t(n,r)};return function(e,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");t(e,n);function r(){this.constructor=e}e.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}}(),Li=function(t){Fi(e,t);function e(n,r){var o=this.constructor,s=t.call(this,n,r)||this;return Object.defineProperty(s,"name",{value:o.name,enumerable:!1,configurable:!0}),Mi(s,o.prototype),Di(s),s}return e}(Error);const Rn=10,Rr=(t=0)=>e=>`\x1B[${e+t}m`,Nr=(t=0)=>e=>`\x1B[${38+t};5;${e}m`,Or=(t=0)=>(e,n,r)=>`\x1B[${38+t};2;${e};${n};${r}m`,M={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(M.modifier);const ji=Object.keys(M.color),Ui=Object.keys(M.bgColor);[...ji,...Ui];function $i(){const t=new Map;for(const[e,n]of Object.entries(M)){for(const[r,o]of Object.entries(n))M[r]={open:`\x1B[${o[0]}m`,close:`\x1B[${o[1]}m`},n[r]=M[r],t.set(o[0],o[1]);Object.defineProperty(M,e,{value:n,enumerable:!1})}return Object.defineProperty(M,"codes",{value:t,enumerable:!1}),M.color.close="\x1B[39m",M.bgColor.close="\x1B[49m",M.color.ansi=Rr(),M.color.ansi256=Nr(),M.color.ansi16m=Or(),M.bgColor.ansi=Rr(Rn),M.bgColor.ansi256=Nr(Rn),M.bgColor.ansi16m=Or(Rn),Object.defineProperties(M,{rgbToAnsi256:{value(e,n,r){return e===n&&n===r?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(n/255*5)+Math.round(r/255*5)},enumerable:!1},hexToRgb:{value(e){const n=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!n)return[0,0,0];let[r]=n;r.length===3&&(r=[...r].map(s=>s+s).join(""));const o=Number.parseInt(r,16);return[o>>16&255,o>>8&255,o&255]},enumerable:!1},hexToAnsi256:{value:e=>M.rgbToAnsi256(...M.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let n,r,o;if(e>=232)n=((e-232)*10+8)/255,r=n,o=n;else{e-=16;const c=e%36;n=Math.floor(e/36)/5,r=Math.floor(c/6)/5,o=c%6/5}const s=Math.max(n,r,o)*2;if(s===0)return 30;let i=30+(Math.round(o)<<2|Math.round(r)<<1|Math.round(n));return s===2&&(i+=60),i},enumerable:!1},rgbToAnsi:{value:(e,n,r)=>M.ansi256ToAnsi(M.rgbToAnsi256(e,n,r)),enumerable:!1},hexToAnsi:{value:e=>M.ansi256ToAnsi(M.hexToAnsi256(e)),enumerable:!1}}),M}const we=$i(),rn=(()=>{if(navigator.userAgentData){const t=navigator.userAgentData.brands.find(({brand:e})=>e==="Chromium");if(t&&t.version>93)return 3}return/\b(Chrome|Chromium)\//.test(navigator.userAgent)?1:0})(),Mr=rn!==0&&{level:rn,hasBasic:!0,has256:rn>=2,has16m:rn>=3},Vi={stdout:Mr,stderr:Mr};function Zi(t,e,n){let r=t.indexOf(e);if(r===-1)return t;const o=e.length;let s=0,i="";do i+=t.slice(s,r)+e+n,s=r+o,r=t.indexOf(e,s);while(r!==-1);return i+=t.slice(s),i}function zi(t,e,n,r){let o=0,s="";do{const i=t[r-1]==="\r";s+=t.slice(o,i?r-1:r)+e+(i?`\r
|
|
7
7
|
`:`
|
|
8
|
-
`)+
|
|
9
|
-
`,o)}while(r!==-1);return s+=
|
|
10
|
-
`);return s!==-1&&(e=
|
|
11
|
-
`+
|
|
12
|
-
`):"",this.name="UnsubscriptionError",this.errors=t}});function an(n,e){if(n){var t=n.indexOf(e);0<=t&&n.splice(t,1)}}var Nt=function(){function n(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return n.prototype.unsubscribe=function(){var e,t,r,o,s;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var c=st(i),l=c.next();!l.done;l=c.next()){var u=l.value;u.remove(this)}}catch(w){e={error:w}}finally{try{l&&!l.done&&(t=c.return)&&t.call(c)}finally{if(e)throw e.error}}else i.remove(this);var d=this.initialTeardown;if(B(d))try{d()}catch(w){s=w instanceof Dn?w.errors:[w]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var h=st(p),f=h.next();!f.done;f=h.next()){var _=f.value;try{Ur(_)}catch(w){s=s??[],w instanceof Dn?s=on(on([],rn(s)),rn(w.errors)):s.push(w)}}}catch(w){r={error:w}}finally{try{f&&!f.done&&(o=h.return)&&o.call(h)}finally{if(r)throw r.error}}}if(s)throw new Dn(s)}},n.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)Ur(e);else{if(e instanceof n){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},n.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},n.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},n.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&an(t,e)},n.prototype.remove=function(e){var t=this._finalizers;t&&an(t,e),e instanceof n&&e._removeParent(this)},n.EMPTY=function(){var e=new n;return e.closed=!0,e}(),n}(),Fr=Nt.EMPTY;function jr(n){return n instanceof Nt||n&&"closed"in n&&B(n.remove)&&B(n.add)&&B(n.unsubscribe)}function Ur(n){B(n)?n():n.unsubscribe()}var $r={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},Vr={setTimeout:function(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];return setTimeout.apply(void 0,on([n,e],rn(t)))},clearTimeout:function(n){var e=Vr.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(n)},delegate:void 0};function Zr(n){Vr.setTimeout(function(){throw n})}function zr(){}function cn(n){n()}var Ln=function(n){Fe(e,n);function e(t){var r=n.call(this)||this;return r.isStopped=!1,t?(r.destination=t,jr(t)&&t.add(r)):r.destination=Hi,r}return e.create=function(t,r,o){return new jn(t,r,o)},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,n.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(Nt),qi=Function.prototype.bind;function Fn(n,e){return qi.call(n,e)}var Yi=function(){function n(e){this.partialObserver=e}return n.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(r){ln(r)}},n.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(r){ln(r)}else ln(e)},n.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){ln(t)}},n}(),jn=function(n){Fe(e,n);function e(t,r,o){var s=n.call(this)||this,i;if(B(t)||!t)i={next:t??void 0,error:r??void 0,complete:o??void 0};else{var c;s&&$r.useDeprecatedNextContext?(c=Object.create(t),c.unsubscribe=function(){return s.unsubscribe()},i={next:t.next&&Fn(t.next,c),error:t.error&&Fn(t.error,c),complete:t.complete&&Fn(t.complete,c)}):i=t}return s.destination=new Yi(i),s}return e}(Ln);function ln(n){Zr(n)}function Wi(n){throw n}var Hi={closed:!0,next:zr,error:Wi,complete:zr},Un=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function Ki(n){return n}function Ji(n){return n.length===0?Ki:n.length===1?n[0]:function(t){return n.reduce(function(r,o){return o(r)},t)}}var xe=function(){function n(e){e&&(this._subscribe=e)}return n.prototype.lift=function(e){var t=new n;return t.source=this,t.operator=e,t},n.prototype.subscribe=function(e,t,r){var o=this,s=Xi(e)?e:new jn(e,t,r);return cn(function(){var i=o,c=i.operator,l=i.source;s.add(c?c.call(s,l):l?o._subscribe(s):o._trySubscribe(s))}),s},n.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},n.prototype.forEach=function(e,t){var r=this;return t=Gr(t),new t(function(o,s){var i=new jn({next:function(c){try{e(c)}catch(l){s(l),i.unsubscribe()}},error:s,complete:o});r.subscribe(i)})},n.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},n.prototype[Un]=function(){return this},n.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ji(e)(this)},n.prototype.toPromise=function(e){var t=this;return e=Gr(e),new e(function(r,o){var s;t.subscribe(function(i){return s=i},function(i){return o(i)},function(){return r(s)})})},n.create=function(e){return new n(e)},n}();function Gr(n){var e;return(e=n??$r.Promise)!==null&&e!==void 0?e:Promise}function Qi(n){return n&&B(n.next)&&B(n.error)&&B(n.complete)}function Xi(n){return n&&n instanceof Ln||Qi(n)&&jr(n)}function ec(n){return B(n==null?void 0:n.lift)}function tc(n){return function(e){if(ec(e))return e.lift(function(t){try{return n(t,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function nc(n,e,t,r,o){return new rc(n,e,t,r,o)}var rc=function(n){Fe(e,n);function e(t,r,o,s,i,c){var l=n.call(this,t)||this;return l.onFinalize=i,l.shouldUnsubscribe=c,l._next=r?function(u){try{r(u)}catch(d){t.error(d)}}:n.prototype._next,l._error=s?function(u){try{s(u)}catch(d){t.error(d)}finally{this.unsubscribe()}}:n.prototype._error,l._complete=o?function(){try{o()}catch(u){t.error(u)}finally{this.unsubscribe()}}:n.prototype._complete,l}return e.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;n.prototype.unsubscribe.call(this),!r&&((t=this.onFinalize)===null||t===void 0||t.call(this))}},e}(Ln),oc=sn(function(n){return function(){n(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),Br=function(n){Fe(e,n);function e(){var t=n.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return e.prototype.lift=function(t){var r=new qr(this,this);return r.operator=t,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new oc},e.prototype.next=function(t){var r=this;cn(function(){var o,s;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var i=st(r.currentObservers),c=i.next();!c.done;c=i.next()){var l=c.value;l.next(t)}}catch(u){o={error:u}}finally{try{c&&!c.done&&(s=i.return)&&s.call(i)}finally{if(o)throw o.error}}}})},e.prototype.error=function(t){var r=this;cn(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=t;for(var o=r.observers;o.length;)o.shift().error(t)}})},e.prototype.complete=function(){var t=this;cn(function(){if(t._throwIfClosed(),!t.isStopped){t.isStopped=!0;for(var r=t.observers;r.length;)r.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var t;return((t=this.observers)===null||t===void 0?void 0:t.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(t){return this._throwIfClosed(),n.prototype._trySubscribe.call(this,t)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var r=this,o=this,s=o.hasError,i=o.isStopped,c=o.observers;return s||i?Fr:(this.currentObservers=null,c.push(t),new Nt(function(){r.currentObservers=null,an(c,t)}))},e.prototype._checkFinalizedStatuses=function(t){var r=this,o=r.hasError,s=r.thrownError,i=r.isStopped;o?t.error(s):i&&t.complete()},e.prototype.asObservable=function(){var t=new xe;return t.source=this,t},e.create=function(t,r){return new qr(t,r)},e}(xe),qr=function(n){Fe(e,n);function e(t,r){var o=n.call(this)||this;return o.destination=t,o.source=r,o}return e.prototype.next=function(t){var r,o;(o=(r=this.destination)===null||r===void 0?void 0:r.next)===null||o===void 0||o.call(r,t)},e.prototype.error=function(t){var r,o;(o=(r=this.destination)===null||r===void 0?void 0:r.error)===null||o===void 0||o.call(r,t)},e.prototype.complete=function(){var t,r;(r=(t=this.destination)===null||t===void 0?void 0:t.complete)===null||r===void 0||r.call(t)},e.prototype._subscribe=function(t){var r,o;return(o=(r=this.source)===null||r===void 0?void 0:r.subscribe(t))!==null&&o!==void 0?o:Fr},e}(Br),sc={now:function(){return Date.now()},delegate:void 0},ac=function(n){Fe(e,n);function e(t,r){return n.call(this)||this}return e.prototype.schedule=function(t,r){return this},e}(Nt),Yr={setInterval:function(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];return setInterval.apply(void 0,on([n,e],rn(t)))},clearInterval:function(n){return clearInterval(n)},delegate:void 0},ic=function(n){Fe(e,n);function e(t,r){var o=n.call(this,t,r)||this;return o.scheduler=t,o.work=r,o.pending=!1,o}return e.prototype.schedule=function(t,r){var o;if(r===void 0&&(r=0),this.closed)return this;this.state=t;var s=this.id,i=this.scheduler;return s!=null&&(this.id=this.recycleAsyncId(i,s,r)),this.pending=!0,this.delay=r,this.id=(o=this.id)!==null&&o!==void 0?o:this.requestAsyncId(i,this.id,r),this},e.prototype.requestAsyncId=function(t,r,o){return o===void 0&&(o=0),Yr.setInterval(t.flush.bind(t,this),o)},e.prototype.recycleAsyncId=function(t,r,o){if(o===void 0&&(o=0),o!=null&&this.delay===o&&this.pending===!1)return r;r!=null&&Yr.clearInterval(r)},e.prototype.execute=function(t,r){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var o=this._execute(t,r);if(o)return o;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(t,r){var o=!1,s;try{this.work(t)}catch(i){o=!0,s=i||new Error("Scheduled action threw falsy error")}if(o)return this.unsubscribe(),s},e.prototype.unsubscribe=function(){if(!this.closed){var t=this,r=t.id,o=t.scheduler,s=o.actions;this.work=this.state=this.scheduler=null,this.pending=!1,an(s,this),r!=null&&(this.id=this.recycleAsyncId(o,r,null)),this.delay=null,n.prototype.unsubscribe.call(this)}},e}(ac),Wr=function(){function n(e,t){t===void 0&&(t=n.now),this.schedulerActionCtor=e,this.now=t}return n.prototype.schedule=function(e,t,r){return t===void 0&&(t=0),new this.schedulerActionCtor(this,e).schedule(r,t)},n.now=sc.now,n}(),cc=function(n){Fe(e,n);function e(t,r){r===void 0&&(r=Wr.now);var o=n.call(this,t,r)||this;return o.actions=[],o._active=!1,o}return e.prototype.flush=function(t){var r=this.actions;if(this._active){r.push(t);return}var o;this._active=!0;do if(o=t.execute(t.state,t.delay))break;while(t=r.shift());if(this._active=!1,o){for(;t=r.shift();)t.unsubscribe();throw o}},e}(Wr),lc=new cc(ic),uc=function(n){return n&&typeof n.length=="number"&&typeof n!="function"};function dc(n){return B(n==null?void 0:n.then)}function pc(n){return B(n[Un])}function fc(n){return Symbol.asyncIterator&&B(n==null?void 0:n[Symbol.asyncIterator])}function mc(n){return new TypeError("You provided "+(n!==null&&typeof n=="object"?"an invalid object":"'"+n+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function hc(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var yc=hc();function _c(n){return B(n==null?void 0:n[yc])}function gc(n){return Gi(this,arguments,function(){var t,r,o,s;return Lr(this,function(i){switch(i.label){case 0:t=n.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,at(t.read())];case 3:return r=i.sent(),o=r.value,s=r.done,s?[4,at(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,at(o)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function vc(n){return B(n==null?void 0:n.getReader)}function wc(n){if(n instanceof xe)return n;if(n!=null){if(pc(n))return bc(n);if(uc(n))return Ec(n);if(dc(n))return kc(n);if(fc(n))return Hr(n);if(_c(n))return Cc(n);if(vc(n))return Sc(n)}throw mc(n)}function bc(n){return new xe(function(e){var t=n[Un]();if(B(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Ec(n){return new xe(function(e){for(var t=0;t<n.length&&!e.closed;t++)e.next(n[t]);e.complete()})}function kc(n){return new xe(function(e){n.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,Zr)})}function Cc(n){return new xe(function(e){var t,r;try{for(var o=st(n),s=o.next();!s.done;s=o.next()){var i=s.value;if(e.next(i),e.closed)return}}catch(c){t={error:c}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}e.complete()})}function Hr(n){return new xe(function(e){Pc(n,e).catch(function(t){return e.error(t)})})}function Sc(n){return Hr(gc(n))}function Pc(n,e){var t,r,o,s;return zi(this,void 0,void 0,function(){var i,c;return Lr(this,function(l){switch(l.label){case 0:l.trys.push([0,5,6,11]),t=Bi(n),l.label=1;case 1:return[4,t.next()];case 2:if(r=l.sent(),!!r.done)return[3,4];if(i=r.value,e.next(i),e.closed)return[2];l.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return c=l.sent(),o={error:c},[3,11];case 6:return l.trys.push([6,,9,10]),r&&!r.done&&(s=t.return)?[4,s.call(t)]:[3,8];case 7:l.sent(),l.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function Ac(n,e,t,r,o){r===void 0&&(r=0),o===void 0&&(o=!1);var s=e.schedule(function(){t(),o?n.add(this.schedule(null,r)):this.unsubscribe()},r);if(n.add(s),!o)return s}function Tc(n,e){var t=B(n)?n:function(){return n},r=function(o){return o.error(t())};return new xe(r)}var Ic=sn(function(n){return function(){n(this),this.name="EmptyError",this.message="no elements in sequence"}});function xc(n,e){return new Promise(function(t,r){var o=!1,s;n.subscribe({next:function(i){s=i,o=!0},error:r,complete:function(){o?t(s):r(new Ic)}})})}function Rc(n){return n instanceof Date&&!isNaN(n)}var Nc=sn(function(n){return function(t){t===void 0&&(t=null),n(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}});function Oc(n,e){var t=Rc(n)?{first:n}:typeof n=="number"?{each:n}:n,r=t.first,o=t.each,s=t.with,i=s===void 0?Mc:s,c=t.scheduler,l=c===void 0?lc:c,u=t.meta,d=u===void 0?null:u;if(r==null&&o==null)throw new TypeError("No timeout provided.");return tc(function(p,h){var f,_,w=null,T=0,C=function(x){_=Ac(h,l,function(){try{f.unsubscribe(),wc(i({meta:d,lastValue:w,seen:T})).subscribe(h)}catch(R){h.error(R)}},x)};f=p.subscribe(nc(h,function(x){_==null||_.unsubscribe(),T++,h.next(w=x),o>0&&C(o)},void 0,void 0,function(){_!=null&&_.closed||_==null||_.unsubscribe(),w=null})),!T&&C(r!=null?typeof r=="number"?r:+r-l.now():o)})}function Mc(n){throw new Nc(n)}class Ot{constructor(){this.set=e=>{if(this._current.status==="success")throw new Error("LoadedOnce is already in success state");this._current={status:"success",isSuccess:!0,loadedValue:e},this._subject.next(e),this._subject.complete()},this.throw=(e,t)=>{if(this._current.status==="success")throw new Error("LoadedOnce is already in success state");this._current={status:"error",isSuccess:!1,error:e,errMsg:t},this._subject.error(e)},this.getValueIfLoadedElse=e=>this._current.status==="success"?this._current.loadedValue:e,this.subscribe=e=>{if(this._current.status==="success"){e(this._current);return}this._current.status==="error"&&e(this._current);const t=this._subject.subscribe({next:()=>{if(this._current.status!=="success")throw new Error("Invalid state (next): please make sure to update _current before the subject");e(this._current),t.unsubscribe()},error:()=>{if(this._current.status!=="error")throw new Error("Invalid state (error): please make sure to update _current before the subject");e(this._current)}})},this.waitForLoad=e=>{if(this._current.status==="success")return Promise.resolve(this._current.loadedValue);if(this._current.status==="error")return Promise.reject(this._current.error);this._current.status!=="initial"&&un(this._current);const t={first:e.timeoutSec*1e3,with:()=>Tc(()=>new Error(e.timeoutErrMsg))};return xc(this._subject.pipe(Oc(t)))},this._current={status:"initial",isSuccess:!1},this._subject=new Br}get current(){return this._current}}const Kr=a.enum(["dev","stg","prod"]),Dc={prod:"https://connto.getopenpay.com",stg:"https://connto.openpaystaging.com",dev:"http://localhost:8000"},Lc=n=>Dc[n],$n={},Jr=async n=>{if($n[n])return $n[n];try{const e=await fetch(new URL("/health/environment",n)).then(r=>r.json()),t=Kr.parse(e.environment);return $n[n]=t,t}catch{return Kr.Values.prod}};function un(n){throw new Error(`Unhandled case: ${n}`)}const Qr=(n,e)=>Object.fromEntries(Object.entries(n).filter(([t])=>!e.includes(t))),U=()=>{if(!(typeof window>"u"))return window},Vn=new Ot,Xr="op_metrics_queue",Fc=3,jc=3,Uc=1e3,{log__:dn}=F("op-metrics");class $c{constructor(){var e,t;this.queue=[],this.processingQueue=!1,this.batchTimeout=null,this.lastEventTimestamp=0,this.offlineListener=()=>{dn("Network offline, metrics will be queued"),this.cancelBatchProcessing()},this.onlineListener=()=>{dn("Network online, processing metrics queue"),this.processQueue()},this.loadQueueFromStorage(),(e=U())==null||e.addEventListener("offline",this.offlineListener),(t=U())==null||t.addEventListener("online",this.onlineListener)}addEvent(e,t,r){const o={eventName:e,properties:t||{},contextProperties:r||{},nonce:Xt(),timestamp:performance.now(),datetime:new Date().toISOString(),attemptCount:0,timeDiffFromPreviousEvent:this.lastEventTimestamp?performance.now()-this.lastEventTimestamp:0};this.lastEventTimestamp=o.timestamp,this.queue.push(o),this.saveQueueToStorage(),this.scheduleBatchProcessing()}loadQueueFromStorage(){var e,t;try{const r=(t=(e=U())==null?void 0:e.localStorage)==null?void 0:t.getItem(Xr);r&&(this.queue=JSON.parse(r))}catch{this.queue=[],this.saveQueueToStorage()}}saveQueueToStorage(){var e;(e=U())==null||e.localStorage.setItem(Xr,JSON.stringify(this.queue))}scheduleBatchProcessing(){const e=U();e&&navigator.onLine&&!this.processingQueue&&this.queue.length>0&&!this.batchTimeout&&(this.batchTimeout=e.setTimeout(()=>{this.batchTimeout=null,this.processQueue()},Uc))}cancelBatchProcessing(){var e;this.batchTimeout&&((e=U())==null||e.clearTimeout(this.batchTimeout),this.batchTimeout=null),this.processingQueue=!1}processQueue(){!navigator.onLine||this.processingQueue||this.queue.length===0||(this.processingQueue=!0,this.sendBatch().finally(()=>{this.processingQueue=!1,this.queue.length>0&&this.scheduleBatchProcessing()}))}async sendBatch(){if(this.queue.length===0)return;const e=Vn.getValueIfLoadedElse(void 0);if(!e){dn("Metrics context not available, will retry later");return}const t=this.queue.slice(0,jc);try{const r={events:t.map(c=>({event_name:c.eventName,device_token:e.deviceToken,context_properties:{...e,...c.contextProperties},properties:{nonce:c.nonce,datetime:c.datetime,timestamp:c.timestamp,time_diff_from_previous_event:c.timeDiffFromPreviousEvent,checkout_secure_token:e.checkoutSecureToken,...c.properties}}))},o=Lc(e.environment),s=new URL("/metrics/public/capture",o);(await fetch(s.toString(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)})).ok?(this.queue=this.queue.slice(t.length),this.saveQueueToStorage()):this.handleFailedBatch(t)}catch(r){dn("Error sending metrics batch:",r),this.handleFailedBatch(t)}}handleFailedBatch(e){e.forEach(r=>{r.attemptCount++});const t=e.filter(r=>r.attemptCount<Fc);this.queue=this.queue.slice(e.length),this.queue=[...t,...this.queue],this.saveQueueToStorage()}cleanup(){var e,t;(e=U())==null||e.removeEventListener("offline",this.offlineListener),(t=U())==null||t.removeEventListener("online",this.onlineListener),this.cancelBatchProcessing()}}const eo=new $c,E=(n,e,t)=>{eo.addEvent(n,e,t)},to=n=>{const e=re(n.reason);E("unhandled_rejection_error",{error_message:e,error_name:n.reason})},no=n=>{var t,r;const e=re(n.error);E("uncaught_error",{error_message:e,error_name:(t=n.error)==null?void 0:t.name,error_stack:(r=n.error)==null?void 0:r.stack,file_name:n.filename,line_number:n.lineno,column_number:n.colno})},Vc=()=>{var n,e;(n=U())==null||n.addEventListener("error",no),(e=U())==null||e.addEventListener("unhandledrejection",to)},Zc=()=>{var n,e;(n=U())==null||n.removeEventListener("error",no),(e=U())==null||e.removeEventListener("unhandledrejection",to)};(zo=U())==null||zo.addEventListener("beforeunload",()=>{eo.processQueue()});class ro extends Ri{constructor(e){const t=`${e.message}`;super(t),this.response=e}get originalErrorMessage(){return this.response.message}}const K=async(n,e,t,r)=>{r&&E(r,{...e});const o=await n.send(e);if(Gc(o))throw new ro(o);if(!zc(o,t)){const s=t.safeParse(o);throw s.success?new Error("Invalid state"):(console.error("OJS queryApi got a schema error. Expected schema:",t,"Actual:",o),s.error)}return r&&E(r,{...o}),o},zc=(n,e)=>e.safeParse(n).success,Gc=n=>ci.safeParse(n).success,Bc=async(n,e)=>await K(n,{type:"get_checkout_preview",payload:e},Cr),q=async n=>await K(n,{type:"get_prefill",payload:{}},Pr),it=async(n,e)=>await K(n,{type:"v2_start_payment_flow",payload:e},Tr,"start_payment_flow"),qc=async(n,e)=>await K(n,{type:"start_payment_flow_for_cc",payload:e},ki,"start_payment_flow_for_cc"),Yc=async(n,e)=>{E("start_payment_flow_for_pr",{...e});const t=await K(n,{type:"start_payment_flow_for_pr",payload:e},Tr);return E("start_payment_flow_for_pr_result",{...t}),t},ce=async(n,e)=>await K(n,{type:"confirm_payment_flow",payload:e},Ca,"confirm_payment_flow"),Wc=async(n,e)=>await K(n,{type:"finalize_setup_payment_method",payload:e},Ar,"finalize_setup_payment_method"),Hc=async(n,e)=>await K(n,{type:"check_if_popup_window_verified",payload:e},ka,"check_if_popup_window_verified"),Kc=async(n,e,t)=>{const r=await Bc(n,{secure_token:e,promotion_code:t}),o=new Set(r.preview.invoices.map(c=>c.currency));if(o.size!==1)throw new Error(`Expected exactly one currency, got ${o.size}`);const s=o.values().next().value??"usd",i=Ai(r.preview.invoices.map(c=>c.remaining_amount_atom));return{currency:s,amountAtom:i}},ct=async(n,e,t,r)=>{if(t)return{amountAtom:0,currency:"usd"};{r=r||void 0;const o=await Kc(n,e,r);return{amountAtom:o.amountAtom,currency:o.currency}}},Jc=async(n,e)=>{if(n.size===0)throw new Error("No CDE connections found");return await Promise.all(Array.from(n.values()).map(r=>K(r,{type:"tokenize_card",payload:e},wa)))},oo=async(n,e)=>await K(n,{type:"checkout_card_elements",payload:e},Pn,"checkout_card_elements"),Qc=async(n,e)=>await K(n,{type:"setup_payment_method",payload:e},Ar,"setup_checkout"),Zn=async(n,e)=>await K(n,{type:"checkout",payload:e},Pn,"perform_checkout"),so=1e3,Xc=async(n,e)=>{console.log(e);const r=await vr({iframe:n,debug:!0,timeout:so,childOrigin:"*"}).promise,o=await K(r,{type:"ping-3ds-status"},ba);return console.log("🟢 CDE connection successful! Stopping polling... Result:",o),o},zn=async(n,e)=>await K(n,{type:"prepare_payment_flow",payload:e},Si,"prepare_payment_flow"),ao=async(n,e)=>{try{return(await K(n,{type:"get_standardized_error_code",payload:{message:e}},Ci)).error_code}catch(t){return console.error("[cde-client] Error during getStandardizedErrorCode:",re(t)),"PAYMENT_FAILED_GENERIC"}},el=async(n,e)=>await K(n,{type:"set_user_device_token",payload:{device_token:e}},Pi),le=a.enum(["stripe","airwallex","authorize_net"]);le.Enum.stripe;const io=({scriptId:n,src:e,checkLoadedFn:t})=>{const r=new AbortController;return new Promise((o,s)=>{let i=document.createElement("script");i.src=e,i.id=n,i.async=!0;const c=document.getElementById(n);t()?o():c?i=c:document.body.appendChild(i),i.addEventListener("load",()=>{r.abort(),o()},{signal:r.signal}),i.addEventListener("error",()=>{r.abort(),s("Failed to load the script")},{signal:r.signal})})},co=()=>io({scriptId:"__op_internal_apple_pay_sdk",src:"https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",checkLoadedFn:()=>!!window.ApplePaySession||!!window.ApplePaySDK}),lo=(n,e)=>{const t=e.token.paymentMethod.billingContact,r=e.billingContact,o=e.shippingContact,s={...n};if(t||r||o){s[m.EMAIL]=s[m.EMAIL]||(t==null?void 0:t.emailAddress)||(r==null?void 0:r.emailAddress)||(o==null?void 0:o.emailAddress)||"op_unfilled@email.com",s[m.COUNTRY]=s[m.COUNTRY]||(t==null?void 0:t.countryCode)||(r==null?void 0:r.countryCode)||(o==null?void 0:o.countryCode)||"US",s[m.ZIP_CODE]=s[m.ZIP_CODE]||(t==null?void 0:t.postalCode)||(r==null?void 0:r.postalCode)||(o==null?void 0:o.postalCode)||"00000";const i=s[m.FIRST_NAME]||(t==null?void 0:t.givenName)||(r==null?void 0:r.givenName)||(o==null?void 0:o.givenName)||"",c=s[m.LAST_NAME]||(t==null?void 0:t.familyName)||(r==null?void 0:r.familyName)||(o==null?void 0:o.familyName)||"";i||c?(s[m.FIRST_NAME]=i,s[m.LAST_NAME]=c):(s[m.FIRST_NAME]="_OP_UNKNOWN",s[m.LAST_NAME]="")}return s};a.object({data:a.object({messageHeaders:a.record(a.string(),a.any()),errors:a.array(a.any()),messageType:a.string(),messageBody:a.record(a.string(),a.any())}),origin:a.literal("https://applepay.cdn-apple.com")});const tl=({total:n,prefill:e})=>{var r;if(e.mode==="setup")return{paymentDescription:"Setup recurring payment",regularBilling:{amount:n.amount,label:"Setup recurring payment",paymentTiming:"recurring",type:"final"},managementURL:new URL(`/pay/${e.token}`,He).toString()};const t=(r=e.line_items)==null?void 0:r[0];if(t)return{paymentDescription:(t==null?void 0:t.description)??"",regularBilling:{amount:n.amount,label:(t==null?void 0:t.description)??"",recurringPaymentIntervalUnit:t==null?void 0:t.billing_interval,recurringPaymentIntervalCount:(t==null?void 0:t.billing_interval_count)??void 0,paymentTiming:"recurring",type:"final"},managementURL:`https://cde.getopenpay.com/pay/${e.token}`}},nl=({overridePaymentRequest:n,initialPreview:e,prefill:t,defaultLabel:r="Total"})=>{var c,l;const o=(((c=n==null?void 0:n.amount)==null?void 0:c.currency)??(t==null?void 0:t.currency)??e.currency).toUpperCase(),i=((((l=n==null?void 0:n.amount)==null?void 0:l.amountAtom)??(e==null?void 0:e.amountAtom)??0)/100).toFixed(2);return{currencyCode:o,total:{label:(n==null?void 0:n.label)??r??"Total",type:n!=null&&n.pending?"pending":"final",amount:i}}},uo=({overridePaymentRequest:n,initialPreview:e,prefill:t,defaultLabel:r})=>{const{currencyCode:o,total:s}=nl({overridePaymentRequest:n,initialPreview:e,prefill:t,defaultLabel:r});let i={countryCode:"US",currencyCode:o,requiredBillingContactFields:["email","postalAddress","name"],requiredShippingContactFields:["email"],supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit","supportsEMV"],total:s,recurringPaymentRequest:tl({total:s,prefill:t})};return n!=null&&n.applePayPaymentRequest&&(typeof n.applePayPaymentRequest=="function"?i={...i,...n.applePayPaymentRequest(i)}:i={...i,...n.applePayPaymentRequest}),i},{log__:Hu,err__:rl}=F("common"),Mt=n=>{if(n.payment_methods.length!==1)throw new Error(`Expected exactly one payment method, got ${n.payment_methods.length}`);return{payment_method_id:n.payment_methods[0].id}},ue=(n,e)=>{const t=n.find(r=>e.safeParse(r).success);if(!t)throw rl("No CPMs found for model. All models:",n),new Error("No CPMs found for model");return e.parse(t)},ol=n=>({new_customer_email:n.email,new_customer_address:{zip_code:n.zipCode,country:n.country},new_customer_first_name:n.firstName,new_customer_last_name:n.lastName}),pn=async n=>{const{log__:e}=F(n.logPrefix),t=await q(n.anyCdeConnection),r=Mt(n.confirmResult);if(t.mode==="setup")return e("Setting up payment method..."),{mode:"setup",result:await Wc(n.anyCdeConnection,{secure_token:t.token,pm_id:r.payment_method_id})};{e("Doing checkout...");const o={secure_token:t.token,payment_input:{provider_type:n.checkoutPaymentMethod.provider},customer_email:n.requiredFormFields[m.EMAIL],customer_zip_code:n.requiredFormFields[m.ZIP_CODE],customer_country:n.requiredFormFields[m.COUNTRY],promotion_code:n.requiredFormFields[m.PROMOTION_CODE],line_items:t.line_items,total_amount_atom:t.amount_total_atom,cancel_at_end:!1,checkout_payment_method:n.checkoutPaymentMethod,use_confirmed_pm_id:r.payment_method_id};return{mode:"checkout",result:await Zn(n.anyCdeConnection,o)}}},sl="@keyframes fadeIn{0%{opacity:0;transform:scale(.9)}to{opacity:1;transform:scale(1)}}.overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483648!important;display:flex;justify-content:center;align-items:center;background-color:#00000080}.container{max-width:500px;max-height:600px;width:100%;height:100%;background-color:#fff;position:relative;animation:fadeIn .3s ease-out}.frame,#adyen-container,#adyen-container>*{max-width:500px;max-height:600px;width:100%;height:100%;border:none}.cancel-button{position:absolute;background:transparent;border:none;font-size:1rem;color:#fff;cursor:pointer;top:-1.5rem;padding:0;right:0}",po=n=>{const e=document.createElement("template");e.innerHTML=`
|
|
8
|
+
`)+n,o=r+1,r=t.indexOf(`
|
|
9
|
+
`,o)}while(r!==-1);return s+=t.slice(o),s}const{stdout:Dr,stderr:Fr}=Vi,Nn=Symbol("GENERATOR"),ot=Symbol("STYLER"),Ot=Symbol("IS_EMPTY"),Lr=["ansi","ansi","ansi256","ansi16m"],st=Object.create(null),Gi=(t,e={})=>{if(e.level&&!(Number.isInteger(e.level)&&e.level>=0&&e.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");const n=Dr?Dr.level:0;t.level=e.level===void 0?n:e.level},Bi=t=>{const e=(...n)=>n.join(" ");return Gi(e,t),Object.setPrototypeOf(e,Mt.prototype),e};function Mt(t){return Bi(t)}Object.setPrototypeOf(Mt.prototype,Function.prototype);for(const[t,e]of Object.entries(we))st[t]={get(){const n=on(this,Mn(e.open,e.close,this[ot]),this[Ot]);return Object.defineProperty(this,t,{value:n}),n}};st.visible={get(){const t=on(this,this[ot],!0);return Object.defineProperty(this,"visible",{value:t}),t}};const On=(t,e,n,...r)=>t==="rgb"?e==="ansi16m"?we[n].ansi16m(...r):e==="ansi256"?we[n].ansi256(we.rgbToAnsi256(...r)):we[n].ansi(we.rgbToAnsi(...r)):t==="hex"?On("rgb",e,n,...we.hexToRgb(...r)):we[n][t](...r),qi=["rgb","hex","ansi256"];for(const t of qi){st[t]={get(){const{level:n}=this;return function(...r){const o=Mn(On(t,Lr[n],"color",...r),we.color.close,this[ot]);return on(this,o,this[Ot])}}};const e="bg"+t[0].toUpperCase()+t.slice(1);st[e]={get(){const{level:n}=this;return function(...r){const o=Mn(On(t,Lr[n],"bgColor",...r),we.bgColor.close,this[ot]);return on(this,o,this[Ot])}}}}const Yi=Object.defineProperties(()=>{},{...st,level:{enumerable:!0,get(){return this[Nn].level},set(t){this[Nn].level=t}}}),Mn=(t,e,n)=>{let r,o;return n===void 0?(r=t,o=e):(r=n.openAll+t,o=e+n.closeAll),{open:t,close:e,openAll:r,closeAll:o,parent:n}},on=(t,e,n)=>{const r=(...o)=>Wi(r,o.length===1?""+o[0]:o.join(" "));return Object.setPrototypeOf(r,Yi),r[Nn]=t,r[ot]=e,r[Ot]=n,r},Wi=(t,e)=>{if(t.level<=0||!e)return t[Ot]?"":e;let n=t[ot];if(n===void 0)return e;const{openAll:r,closeAll:o}=n;if(e.includes("\x1B"))for(;n!==void 0;)e=Zi(e,n.close,n.open),n=n.parent;const s=e.indexOf(`
|
|
10
|
+
`);return s!==-1&&(e=zi(e,o,r,s)),r+e+o};Object.defineProperties(Mt.prototype,st);const sn=Mt();Mt({level:Fr?Fr.level:0});const be=t=>async e=>{var n,r;try{(r=(n=e.formCallbacks.get).onCheckoutStarted)==null||r.call(n),E("checkout_started",{cpm:e.checkoutPaymentMethod});const o=await t(e);if(E("checkout_success",{cpm:e.checkoutPaymentMethod,...o}),o.mode==="setup")e.formCallbacks.get.onSetupPaymentMethodSuccess(o.result.payment_method_id);else if(o.mode==="checkout")e.formCallbacks.get.onCheckoutSuccess(o.result.invoice_urls,o.result.subscription_ids,o.result.customer_id,o.result.processors_used??[]);else throw new Error(`Unhandled mode: ${o}`)}catch(o){const s=re(o),i=await co(e.context.anyCdeConnection,s);e.formCallbacks.get.onCheckoutError(s,i),E("checkout_error",{cpm:e.checkoutPaymentMethod,errorMessage:s,errorCode:i})}},Ge=t=>async e=>{try{return await t(e)}catch(n){const{err__:r}=D("init-error-catcher"),o=re(n),s=await co(e.context.anyCdeConnection,o);return r(s,o,n),E("init_flow_error",{errorMessage:o,errorCode:s}),{isAvailable:!1,reason:o,errorCode:s,isLoading:!1}}},D=t=>{const e=(...r)=>{window.console.log(`${sn.green.bold("ojs/")}${sn.bold.gray(`${t}`)} `,...r)},n=(...r)=>{window.console.warn(`${sn.red.bold("ojs/")}${sn.bold.gray(`${t}`)} `,...r)};return{log:e,err:n,log__:e,err__:n}};var Dn=function(t,e){return Dn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[o]=r[o])},Dn(t,e)};function je(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Dn(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function Hi(t,e,n,r){function o(s){return s instanceof n?s:new n(function(i){i(s)})}return new(n||(n=Promise))(function(s,i){function c(d){try{u(r.next(d))}catch(f){i(f)}}function l(d){try{u(r.throw(d))}catch(f){i(f)}}function u(d){d.done?s(d.value):o(d.value).then(c,l)}u((r=r.apply(t,e||[])).next())})}function jr(t,e){var n={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,o,s,i=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return i.next=c(0),i.throw=c(1),i.return=c(2),typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function c(u){return function(d){return l([u,d])}}function l(u){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,u[0]&&(n=0)),n;)try{if(r=1,o&&(s=u[0]&2?o.return:u[0]?o.throw||((s=o.return)&&s.call(o),0):o.next)&&!(s=s.call(o,u[1])).done)return s;switch(o=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return n.label++,{value:u[1],done:!1};case 5:n.label++,o=u[1],u=[0];continue;case 7:u=n.ops.pop(),n.trys.pop();continue;default:if(s=n.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){n=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){n.label=u[1];break}if(u[0]===6&&n.label<s[1]){n.label=s[1],s=u;break}if(s&&n.label<s[2]){n.label=s[2],n.ops.push(u);break}s[2]&&n.ops.pop(),n.trys.pop();continue}u=e.call(t,n)}catch(d){u=[6,d],o=0}finally{r=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function at(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function an(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),o,s=[],i;try{for(;(e===void 0||e-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(c){i={error:c}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(i)throw i.error}}return s}function cn(t,e,n){if(n||arguments.length===2)for(var r=0,o=e.length,s;r<o;r++)(s||!(r in e))&&(s||(s=Array.prototype.slice.call(e,0,r)),s[r]=e[r]);return t.concat(s||Array.prototype.slice.call(e))}function it(t){return this instanceof it?(this.v=t,this):new it(t)}function Ki(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),o,s=[];return o=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),c("next"),c("throw"),c("return",i),o[Symbol.asyncIterator]=function(){return this},o;function i(p){return function(_){return Promise.resolve(_).then(p,f)}}function c(p,_){r[p]&&(o[p]=function(w){return new Promise(function(A,k){s.push([p,w,A,k])>1||l(p,w)})},_&&(o[p]=_(o[p])))}function l(p,_){try{u(r[p](_))}catch(w){m(s[0][3],w)}}function u(p){p.value instanceof it?Promise.resolve(p.value.v).then(d,f):m(s[0][2],p)}function d(p){l("next",p)}function f(p){l("throw",p)}function m(p,_){p(_),s.shift(),s.length&&l(s[0][0],s[0][1])}}function Ji(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof at=="function"?at(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(s){n[s]=t[s]&&function(i){return new Promise(function(c,l){i=t[s](i),o(c,l,i.done,i.value)})}}function o(s,i,c,l){Promise.resolve(l).then(function(u){s({value:u,done:c})},i)}}typeof SuppressedError=="function"&&SuppressedError;function W(t){return typeof t=="function"}function ln(t){var e=function(r){Error.call(r),r.stack=new Error().stack},n=t(e);return n.prototype=Object.create(Error.prototype),n.prototype.constructor=n,n}var Fn=ln(function(t){return function(n){t(this),this.message=n?n.length+` errors occurred during unsubscription:
|
|
11
|
+
`+n.map(function(r,o){return o+1+") "+r.toString()}).join(`
|
|
12
|
+
`):"",this.name="UnsubscriptionError",this.errors=n}});function un(t,e){if(t){var n=t.indexOf(e);0<=n&&t.splice(n,1)}}var Dt=function(){function t(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var e,n,r,o,s;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var c=at(i),l=c.next();!l.done;l=c.next()){var u=l.value;u.remove(this)}}catch(w){e={error:w}}finally{try{l&&!l.done&&(n=c.return)&&n.call(c)}finally{if(e)throw e.error}}else i.remove(this);var d=this.initialTeardown;if(W(d))try{d()}catch(w){s=w instanceof Fn?w.errors:[w]}var f=this._finalizers;if(f){this._finalizers=null;try{for(var m=at(f),p=m.next();!p.done;p=m.next()){var _=p.value;try{Vr(_)}catch(w){s=s??[],w instanceof Fn?s=cn(cn([],an(s)),an(w.errors)):s.push(w)}}}catch(w){r={error:w}}finally{try{p&&!p.done&&(o=m.return)&&o.call(m)}finally{if(r)throw r.error}}}if(s)throw new Fn(s)}},t.prototype.add=function(e){var n;if(e&&e!==this)if(this.closed)Vr(e);else{if(e instanceof t){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(n=this._finalizers)!==null&&n!==void 0?n:[]).push(e)}},t.prototype._hasParent=function(e){var n=this._parentage;return n===e||Array.isArray(n)&&n.includes(e)},t.prototype._addParent=function(e){var n=this._parentage;this._parentage=Array.isArray(n)?(n.push(e),n):n?[n,e]:e},t.prototype._removeParent=function(e){var n=this._parentage;n===e?this._parentage=null:Array.isArray(n)&&un(n,e)},t.prototype.remove=function(e){var n=this._finalizers;n&&un(n,e),e instanceof t&&e._removeParent(this)},t.EMPTY=function(){var e=new t;return e.closed=!0,e}(),t}(),Ur=Dt.EMPTY;function $r(t){return t instanceof Dt||t&&"closed"in t&&W(t.remove)&&W(t.add)&&W(t.unsubscribe)}function Vr(t){W(t)?t():t.unsubscribe()}var Zr={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},zr={setTimeout:function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return setTimeout.apply(void 0,cn([t,e],an(n)))},clearTimeout:function(t){var e=zr.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(t)},delegate:void 0};function Gr(t){zr.setTimeout(function(){throw t})}function Br(){}function dn(t){t()}var Ln=function(t){je(e,t);function e(n){var r=t.call(this)||this;return r.isStopped=!1,n?(r.destination=n,$r(n)&&n.add(r)):r.destination=tc,r}return e.create=function(n,r,o){return new Un(n,r,o)},e.prototype.next=function(n){this.isStopped||this._next(n)},e.prototype.error=function(n){this.isStopped||(this.isStopped=!0,this._error(n))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(n){this.destination.next(n)},e.prototype._error=function(n){try{this.destination.error(n)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(Dt),Qi=Function.prototype.bind;function jn(t,e){return Qi.call(t,e)}var Xi=function(){function t(e){this.partialObserver=e}return t.prototype.next=function(e){var n=this.partialObserver;if(n.next)try{n.next(e)}catch(r){pn(r)}},t.prototype.error=function(e){var n=this.partialObserver;if(n.error)try{n.error(e)}catch(r){pn(r)}else pn(e)},t.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(n){pn(n)}},t}(),Un=function(t){je(e,t);function e(n,r,o){var s=t.call(this)||this,i;if(W(n)||!n)i={next:n??void 0,error:r??void 0,complete:o??void 0};else{var c;s&&Zr.useDeprecatedNextContext?(c=Object.create(n),c.unsubscribe=function(){return s.unsubscribe()},i={next:n.next&&jn(n.next,c),error:n.error&&jn(n.error,c),complete:n.complete&&jn(n.complete,c)}):i=n}return s.destination=new Xi(i),s}return e}(Ln);function pn(t){Gr(t)}function ec(t){throw t}var tc={closed:!0,next:Br,error:ec,complete:Br},$n=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function nc(t){return t}function rc(t){return t.length===0?nc:t.length===1?t[0]:function(n){return t.reduce(function(r,o){return o(r)},n)}}var xe=function(){function t(e){e&&(this._subscribe=e)}return t.prototype.lift=function(e){var n=new t;return n.source=this,n.operator=e,n},t.prototype.subscribe=function(e,n,r){var o=this,s=sc(e)?e:new Un(e,n,r);return dn(function(){var i=o,c=i.operator,l=i.source;s.add(c?c.call(s,l):l?o._subscribe(s):o._trySubscribe(s))}),s},t.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(n){e.error(n)}},t.prototype.forEach=function(e,n){var r=this;return n=qr(n),new n(function(o,s){var i=new Un({next:function(c){try{e(c)}catch(l){s(l),i.unsubscribe()}},error:s,complete:o});r.subscribe(i)})},t.prototype._subscribe=function(e){var n;return(n=this.source)===null||n===void 0?void 0:n.subscribe(e)},t.prototype[$n]=function(){return this},t.prototype.pipe=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return rc(e)(this)},t.prototype.toPromise=function(e){var n=this;return e=qr(e),new e(function(r,o){var s;n.subscribe(function(i){return s=i},function(i){return o(i)},function(){return r(s)})})},t.create=function(e){return new t(e)},t}();function qr(t){var e;return(e=t??Zr.Promise)!==null&&e!==void 0?e:Promise}function oc(t){return t&&W(t.next)&&W(t.error)&&W(t.complete)}function sc(t){return t&&t instanceof Ln||oc(t)&&$r(t)}function ac(t){return W(t==null?void 0:t.lift)}function ic(t){return function(e){if(ac(e))return e.lift(function(n){try{return t(n,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function cc(t,e,n,r,o){return new lc(t,e,n,r,o)}var lc=function(t){je(e,t);function e(n,r,o,s,i,c){var l=t.call(this,n)||this;return l.onFinalize=i,l.shouldUnsubscribe=c,l._next=r?function(u){try{r(u)}catch(d){n.error(d)}}:t.prototype._next,l._error=s?function(u){try{s(u)}catch(d){n.error(d)}finally{this.unsubscribe()}}:t.prototype._error,l._complete=o?function(){try{o()}catch(u){n.error(u)}finally{this.unsubscribe()}}:t.prototype._complete,l}return e.prototype.unsubscribe=function(){var n;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;t.prototype.unsubscribe.call(this),!r&&((n=this.onFinalize)===null||n===void 0||n.call(this))}},e}(Ln),uc=ln(function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),Yr=function(t){je(e,t);function e(){var n=t.call(this)||this;return n.closed=!1,n.currentObservers=null,n.observers=[],n.isStopped=!1,n.hasError=!1,n.thrownError=null,n}return e.prototype.lift=function(n){var r=new Wr(this,this);return r.operator=n,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new uc},e.prototype.next=function(n){var r=this;dn(function(){var o,s;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var i=at(r.currentObservers),c=i.next();!c.done;c=i.next()){var l=c.value;l.next(n)}}catch(u){o={error:u}}finally{try{c&&!c.done&&(s=i.return)&&s.call(i)}finally{if(o)throw o.error}}}})},e.prototype.error=function(n){var r=this;dn(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=n;for(var o=r.observers;o.length;)o.shift().error(n)}})},e.prototype.complete=function(){var n=this;dn(function(){if(n._throwIfClosed(),!n.isStopped){n.isStopped=!0;for(var r=n.observers;r.length;)r.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var n;return((n=this.observers)===null||n===void 0?void 0:n.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(n){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,n)},e.prototype._subscribe=function(n){return this._throwIfClosed(),this._checkFinalizedStatuses(n),this._innerSubscribe(n)},e.prototype._innerSubscribe=function(n){var r=this,o=this,s=o.hasError,i=o.isStopped,c=o.observers;return s||i?Ur:(this.currentObservers=null,c.push(n),new Dt(function(){r.currentObservers=null,un(c,n)}))},e.prototype._checkFinalizedStatuses=function(n){var r=this,o=r.hasError,s=r.thrownError,i=r.isStopped;o?n.error(s):i&&n.complete()},e.prototype.asObservable=function(){var n=new xe;return n.source=this,n},e.create=function(n,r){return new Wr(n,r)},e}(xe),Wr=function(t){je(e,t);function e(n,r){var o=t.call(this)||this;return o.destination=n,o.source=r,o}return e.prototype.next=function(n){var r,o;(o=(r=this.destination)===null||r===void 0?void 0:r.next)===null||o===void 0||o.call(r,n)},e.prototype.error=function(n){var r,o;(o=(r=this.destination)===null||r===void 0?void 0:r.error)===null||o===void 0||o.call(r,n)},e.prototype.complete=function(){var n,r;(r=(n=this.destination)===null||n===void 0?void 0:n.complete)===null||r===void 0||r.call(n)},e.prototype._subscribe=function(n){var r,o;return(o=(r=this.source)===null||r===void 0?void 0:r.subscribe(n))!==null&&o!==void 0?o:Ur},e}(Yr),dc={now:function(){return Date.now()},delegate:void 0},pc=function(t){je(e,t);function e(n,r){return t.call(this)||this}return e.prototype.schedule=function(n,r){return this},e}(Dt),Hr={setInterval:function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return setInterval.apply(void 0,cn([t,e],an(n)))},clearInterval:function(t){return clearInterval(t)},delegate:void 0},fc=function(t){je(e,t);function e(n,r){var o=t.call(this,n,r)||this;return o.scheduler=n,o.work=r,o.pending=!1,o}return e.prototype.schedule=function(n,r){var o;if(r===void 0&&(r=0),this.closed)return this;this.state=n;var s=this.id,i=this.scheduler;return s!=null&&(this.id=this.recycleAsyncId(i,s,r)),this.pending=!0,this.delay=r,this.id=(o=this.id)!==null&&o!==void 0?o:this.requestAsyncId(i,this.id,r),this},e.prototype.requestAsyncId=function(n,r,o){return o===void 0&&(o=0),Hr.setInterval(n.flush.bind(n,this),o)},e.prototype.recycleAsyncId=function(n,r,o){if(o===void 0&&(o=0),o!=null&&this.delay===o&&this.pending===!1)return r;r!=null&&Hr.clearInterval(r)},e.prototype.execute=function(n,r){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var o=this._execute(n,r);if(o)return o;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(n,r){var o=!1,s;try{this.work(n)}catch(i){o=!0,s=i||new Error("Scheduled action threw falsy error")}if(o)return this.unsubscribe(),s},e.prototype.unsubscribe=function(){if(!this.closed){var n=this,r=n.id,o=n.scheduler,s=o.actions;this.work=this.state=this.scheduler=null,this.pending=!1,un(s,this),r!=null&&(this.id=this.recycleAsyncId(o,r,null)),this.delay=null,t.prototype.unsubscribe.call(this)}},e}(pc),Kr=function(){function t(e,n){n===void 0&&(n=t.now),this.schedulerActionCtor=e,this.now=n}return t.prototype.schedule=function(e,n,r){return n===void 0&&(n=0),new this.schedulerActionCtor(this,e).schedule(r,n)},t.now=dc.now,t}(),mc=function(t){je(e,t);function e(n,r){r===void 0&&(r=Kr.now);var o=t.call(this,n,r)||this;return o.actions=[],o._active=!1,o}return e.prototype.flush=function(n){var r=this.actions;if(this._active){r.push(n);return}var o;this._active=!0;do if(o=n.execute(n.state,n.delay))break;while(n=r.shift());if(this._active=!1,o){for(;n=r.shift();)n.unsubscribe();throw o}},e}(Kr),hc=new mc(fc),yc=function(t){return t&&typeof t.length=="number"&&typeof t!="function"};function _c(t){return W(t==null?void 0:t.then)}function gc(t){return W(t[$n])}function vc(t){return Symbol.asyncIterator&&W(t==null?void 0:t[Symbol.asyncIterator])}function wc(t){return new TypeError("You provided "+(t!==null&&typeof t=="object"?"an invalid object":"'"+t+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function bc(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var Ec=bc();function kc(t){return W(t==null?void 0:t[Ec])}function Cc(t){return Ki(this,arguments,function(){var n,r,o,s;return jr(this,function(i){switch(i.label){case 0:n=t.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,it(n.read())];case 3:return r=i.sent(),o=r.value,s=r.done,s?[4,it(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,it(o)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return n.releaseLock(),[7];case 10:return[2]}})})}function Sc(t){return W(t==null?void 0:t.getReader)}function Pc(t){if(t instanceof xe)return t;if(t!=null){if(gc(t))return Ac(t);if(yc(t))return Tc(t);if(_c(t))return Ic(t);if(vc(t))return Jr(t);if(kc(t))return xc(t);if(Sc(t))return Rc(t)}throw wc(t)}function Ac(t){return new xe(function(e){var n=t[$n]();if(W(n.subscribe))return n.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Tc(t){return new xe(function(e){for(var n=0;n<t.length&&!e.closed;n++)e.next(t[n]);e.complete()})}function Ic(t){return new xe(function(e){t.then(function(n){e.closed||(e.next(n),e.complete())},function(n){return e.error(n)}).then(null,Gr)})}function xc(t){return new xe(function(e){var n,r;try{for(var o=at(t),s=o.next();!s.done;s=o.next()){var i=s.value;if(e.next(i),e.closed)return}}catch(c){n={error:c}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}e.complete()})}function Jr(t){return new xe(function(e){Nc(t,e).catch(function(n){return e.error(n)})})}function Rc(t){return Jr(Cc(t))}function Nc(t,e){var n,r,o,s;return Hi(this,void 0,void 0,function(){var i,c;return jr(this,function(l){switch(l.label){case 0:l.trys.push([0,5,6,11]),n=Ji(t),l.label=1;case 1:return[4,n.next()];case 2:if(r=l.sent(),!!r.done)return[3,4];if(i=r.value,e.next(i),e.closed)return[2];l.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return c=l.sent(),o={error:c},[3,11];case 6:return l.trys.push([6,,9,10]),r&&!r.done&&(s=n.return)?[4,s.call(n)]:[3,8];case 7:l.sent(),l.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function Oc(t,e,n,r,o){r===void 0&&(r=0),o===void 0&&(o=!1);var s=e.schedule(function(){n(),o?t.add(this.schedule(null,r)):this.unsubscribe()},r);if(t.add(s),!o)return s}function Mc(t,e){var n=W(t)?t:function(){return t},r=function(o){return o.error(n())};return new xe(r)}var Dc=ln(function(t){return function(){t(this),this.name="EmptyError",this.message="no elements in sequence"}});function Fc(t,e){return new Promise(function(n,r){var o=!1,s;t.subscribe({next:function(i){s=i,o=!0},error:r,complete:function(){o?n(s):r(new Dc)}})})}function Lc(t){return t instanceof Date&&!isNaN(t)}var jc=ln(function(t){return function(n){n===void 0&&(n=null),t(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=n}});function Uc(t,e){var n=Lc(t)?{first:t}:typeof t=="number"?{each:t}:t,r=n.first,o=n.each,s=n.with,i=s===void 0?$c:s,c=n.scheduler,l=c===void 0?hc:c,u=n.meta,d=u===void 0?null:u;if(r==null&&o==null)throw new TypeError("No timeout provided.");return ic(function(f,m){var p,_,w=null,A=0,k=function(x){_=Oc(m,l,function(){try{p.unsubscribe(),Pc(i({meta:d,lastValue:w,seen:A})).subscribe(m)}catch(I){m.error(I)}},x)};p=f.subscribe(cc(m,function(x){_==null||_.unsubscribe(),A++,m.next(w=x),o>0&&k(o)},void 0,void 0,function(){_!=null&&_.closed||_==null||_.unsubscribe(),w=null})),!A&&k(r!=null?typeof r=="number"?r:+r-l.now():o)})}function $c(t){throw new jc(t)}class Ft{constructor(){this.set=e=>{if(this._current.status==="success")throw new Error("LoadedOnce is already in success state");this._current={status:"success",isSuccess:!0,loadedValue:e},this._subject.next(e),this._subject.complete()},this.throw=(e,n)=>{if(this._current.status==="success")throw new Error("LoadedOnce is already in success state");this._current={status:"error",isSuccess:!1,error:e,errMsg:n},this._subject.error(e)},this.getValueIfLoadedElse=e=>this._current.status==="success"?this._current.loadedValue:e,this.subscribe=e=>{if(this._current.status==="success"){e(this._current);return}this._current.status==="error"&&e(this._current);const n=this._subject.subscribe({next:()=>{if(this._current.status!=="success")throw new Error("Invalid state (next): please make sure to update _current before the subject");e(this._current),n.unsubscribe()},error:()=>{if(this._current.status!=="error")throw new Error("Invalid state (error): please make sure to update _current before the subject");e(this._current)}})},this.waitForLoad=e=>{if(this._current.status==="success")return Promise.resolve(this._current.loadedValue);if(this._current.status==="error")return Promise.reject(this._current.error);this._current.status!=="initial"&&fn(this._current);const n={first:e.timeoutSec*1e3,with:()=>Mc(()=>new Error(e.timeoutErrMsg))};return Fc(this._subject.pipe(Uc(n)))},this._current={status:"initial",isSuccess:!1},this._subject=new Yr}get current(){return this._current}}const Qr=a.enum(["dev","stg","prod"]),Vc={prod:"https://connto.getopenpay.com",stg:"https://connto.openpaystaging.com",dev:"http://localhost:8000"},Zc=t=>Vc[t],Vn={},Xr=async t=>{if(Vn[t])return Vn[t];try{const e=await fetch(new URL("/health/environment",t)).then(r=>r.json()),n=Qr.parse(e.environment);return Vn[t]=n,n}catch{return Qr.Values.prod}};function fn(t){throw new Error(`Unhandled case: ${t}`)}const eo=(t,e)=>Object.fromEntries(Object.entries(t).filter(([n])=>!e.includes(n))),$=()=>{if(!(typeof window>"u"))return window},Zn=new Ft,to="op_metrics_queue",zc=3,Gc=3,Bc=1e3,{log__:mn}=D("op-metrics");class qc{constructor(){var e,n;this.queue=[],this.processingQueue=!1,this.batchTimeout=null,this.lastEventTimestamp=0,this.offlineListener=()=>{mn("Network offline, metrics will be queued"),this.cancelBatchProcessing()},this.onlineListener=()=>{mn("Network online, processing metrics queue"),this.processQueue()},this.loadQueueFromStorage(),(e=$())==null||e.addEventListener("offline",this.offlineListener),(n=$())==null||n.addEventListener("online",this.onlineListener)}addEvent(e,n,r){const o={eventName:e,properties:n||{},contextProperties:r||{},nonce:Rt(),timestamp:performance.now(),datetime:new Date().toISOString(),attemptCount:0,timeDiffFromPreviousEvent:this.lastEventTimestamp?performance.now()-this.lastEventTimestamp:0};this.lastEventTimestamp=o.timestamp,this.queue.push(o),this.saveQueueToStorage(),this.scheduleBatchProcessing()}loadQueueFromStorage(){var e,n;try{const r=(n=(e=$())==null?void 0:e.localStorage)==null?void 0:n.getItem(to);r&&(this.queue=JSON.parse(r))}catch{this.queue=[],this.saveQueueToStorage()}}saveQueueToStorage(){var e;(e=$())==null||e.localStorage.setItem(to,JSON.stringify(this.queue))}scheduleBatchProcessing(){const e=$();e&&navigator.onLine&&!this.processingQueue&&this.queue.length>0&&!this.batchTimeout&&(this.batchTimeout=e.setTimeout(()=>{this.batchTimeout=null,this.processQueue()},Bc))}cancelBatchProcessing(){var e;this.batchTimeout&&((e=$())==null||e.clearTimeout(this.batchTimeout),this.batchTimeout=null),this.processingQueue=!1}processQueue(){!navigator.onLine||this.processingQueue||this.queue.length===0||(this.processingQueue=!0,this.sendBatch().finally(()=>{this.processingQueue=!1,this.queue.length>0&&this.scheduleBatchProcessing()}))}async sendBatch(){if(this.queue.length===0)return;const e=Zn.getValueIfLoadedElse(void 0);if(!e){mn("Metrics context not available, will retry later");return}const n=this.queue.slice(0,Gc);try{const r={events:n.map(c=>({event_name:c.eventName,device_token:e.deviceToken,context_properties:{...e,...c.contextProperties},properties:{nonce:c.nonce,datetime:c.datetime,timestamp:c.timestamp,time_diff_from_previous_event:c.timeDiffFromPreviousEvent,checkout_secure_token:e.checkoutSecureToken,...c.properties}}))},o=Zc(e.environment),s=new URL("/metrics/public/capture",o);(await fetch(s.toString(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)})).ok?(this.queue=this.queue.slice(n.length),this.saveQueueToStorage()):this.handleFailedBatch(n)}catch(r){mn("Error sending metrics batch:",r),this.handleFailedBatch(n)}}handleFailedBatch(e){e.forEach(r=>{r.attemptCount++});const n=e.filter(r=>r.attemptCount<zc);this.queue=this.queue.slice(e.length),this.queue=[...n,...this.queue],this.saveQueueToStorage()}cleanup(){var e,n;(e=$())==null||e.removeEventListener("offline",this.offlineListener),(n=$())==null||n.removeEventListener("online",this.onlineListener),this.cancelBatchProcessing()}}const no=new qc,E=(t,e,n)=>{no.addEvent(t,e,n)},ro=t=>{const e=re(t.reason);E("unhandled_rejection_error",{error_message:e,error_name:t.reason})},oo=t=>{var n,r;const e=re(t.error);E("uncaught_error",{error_message:e,error_name:(n=t.error)==null?void 0:n.name,error_stack:(r=t.error)==null?void 0:r.stack,file_name:t.filename,line_number:t.lineno,column_number:t.colno})},Yc=()=>{var t,e;(t=$())==null||t.addEventListener("error",oo),(e=$())==null||e.addEventListener("unhandledrejection",ro)},Wc=()=>{var t,e;(t=$())==null||t.removeEventListener("error",oo),(e=$())==null||e.removeEventListener("unhandledrejection",ro)};(Ho=$())==null||Ho.addEventListener("beforeunload",()=>{no.processQueue()});class so extends Li{constructor(e){const n=`${e.message}`;super(n),this.response=e}get originalErrorMessage(){return this.response.message}}const J=async(t,e,n,r)=>{r&&E(r,{...e});const o=await t.send(e);if(Kc(o))throw new so(o);if(!Hc(o,n)){const s=n.safeParse(o);throw s.success?new Error("Invalid state"):(console.error("OJS queryApi got a schema error. Expected schema:",n,"Actual:",o),s.error)}return r&&E(r,{...o}),o},Hc=(t,e)=>e.safeParse(t).success,Kc=t=>mi.safeParse(t).success,Jc=async(t,e)=>await J(t,{type:"get_checkout_preview",payload:e},Pr),G=async t=>await J(t,{type:"get_prefill",payload:{}},Tr),ct=async(t,e)=>await J(t,{type:"v2_start_payment_flow",payload:e},xr,"start_payment_flow"),Qc=async(t,e)=>await J(t,{type:"start_payment_flow_for_cc",payload:e},Ii,"start_payment_flow_for_cc"),Xc=async(t,e)=>{E("start_payment_flow_for_pr",{...e});const n=await J(t,{type:"start_payment_flow_for_pr",payload:e},xr);return E("start_payment_flow_for_pr_result",{...n}),n},se=async(t,e)=>await J(t,{type:"confirm_payment_flow",payload:e},xa,"confirm_payment_flow"),el=async(t,e)=>await J(t,{type:"finalize_setup_payment_method",payload:e},Ir,"finalize_setup_payment_method"),tl=async(t,e)=>await J(t,{type:"check_if_popup_window_verified",payload:e},Ia,"check_if_popup_window_verified"),nl=async(t,e,n)=>{const r=await Jc(t,{secure_token:e,promotion_code:n}),o=new Set(r.preview.invoices.map(c=>c.currency));if(o.size!==1)throw new Error(`Expected exactly one currency, got ${o.size}`);const s=o.values().next().value??"usd",i=Oi(r.preview.invoices.map(c=>c.remaining_amount_atom));return{currency:s,amountAtom:i}},lt=async(t,e,n,r)=>{if(n)return{amountAtom:0,currency:"usd"};{r=r||void 0;const o=await nl(t,e,r);return{amountAtom:o.amountAtom,currency:o.currency}}},rl=async(t,e)=>{if(t.size===0)throw new Error("No CDE connections found");return await Promise.all(Array.from(t.values()).map(r=>J(r,{type:"tokenize_card",payload:e},Pa)))},ao=async(t,e)=>await J(t,{type:"checkout_card_elements",payload:e},Tn,"checkout_card_elements"),ol=async(t,e)=>await J(t,{type:"setup_payment_method",payload:e},Ir,"setup_checkout"),zn=async(t,e)=>await J(t,{type:"checkout",payload:e},Tn,"perform_checkout"),io=1e3,sl=async(t,e)=>{console.log(e);const r=await br({iframe:t,debug:!0,timeout:io,childOrigin:"*"}).promise,o=await J(r,{type:"ping-3ds-status"},Aa);return console.log("🟢 CDE connection successful! Stopping polling... Result:",o),o},Gn=async(t,e)=>await J(t,{type:"prepare_payment_flow",payload:e},Ri,"prepare_payment_flow"),co=async(t,e)=>{try{return(await J(t,{type:"get_standardized_error_code",payload:{message:e}},xi)).error_code}catch(n){return console.error("[cde-client] Error during getStandardizedErrorCode:",re(n)),"PAYMENT_FAILED_GENERIC"}},al=async(t,e)=>await J(t,{type:"set_user_device_token",payload:{device_token:e}},Ni),de=a.enum(["stripe","airwallex","authorize_net"]);de.Enum.stripe;const lo=({scriptId:t,src:e,checkLoadedFn:n})=>{const r=new AbortController;return new Promise((o,s)=>{let i=document.createElement("script");i.src=e,i.id=t,i.async=!0;const c=document.getElementById(t);n()?o():c?i=c:document.body.appendChild(i),i.addEventListener("load",()=>{r.abort(),o()},{signal:r.signal}),i.addEventListener("error",()=>{r.abort(),s("Failed to load the script")},{signal:r.signal})})},uo=()=>lo({scriptId:"__op_internal_apple_pay_sdk",src:"https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",checkLoadedFn:()=>!!window.ApplePaySession||!!window.ApplePaySDK}),po=(t,e)=>{const n=e.token.paymentMethod.billingContact,r=e.billingContact,o=e.shippingContact,s={...t};if(n||r||o){s[h.EMAIL]=s[h.EMAIL]||(n==null?void 0:n.emailAddress)||(r==null?void 0:r.emailAddress)||(o==null?void 0:o.emailAddress)||"op_unfilled@email.com",s[h.COUNTRY]=s[h.COUNTRY]||(n==null?void 0:n.countryCode)||(r==null?void 0:r.countryCode)||(o==null?void 0:o.countryCode)||"US",s[h.ZIP_CODE]=s[h.ZIP_CODE]||(n==null?void 0:n.postalCode)||(r==null?void 0:r.postalCode)||(o==null?void 0:o.postalCode)||"00000";const i=s[h.FIRST_NAME]||(n==null?void 0:n.givenName)||(r==null?void 0:r.givenName)||(o==null?void 0:o.givenName)||"",c=s[h.LAST_NAME]||(n==null?void 0:n.familyName)||(r==null?void 0:r.familyName)||(o==null?void 0:o.familyName)||"";i||c?(s[h.FIRST_NAME]=i,s[h.LAST_NAME]=c):(s[h.FIRST_NAME]="_OP_UNKNOWN",s[h.LAST_NAME]="")}return s};a.object({data:a.object({messageHeaders:a.record(a.string(),a.any()),errors:a.array(a.any()),messageType:a.string(),messageBody:a.record(a.string(),a.any())}),origin:a.literal("https://applepay.cdn-apple.com")});const il=({total:t,prefill:e})=>{var r;if(e.mode==="setup")return{paymentDescription:"Setup recurring payment",regularBilling:{amount:t.amount,label:"Setup recurring payment",paymentTiming:"recurring",type:"final"},managementURL:new URL(`/pay/${e.token}`,Ke).toString()};const n=(r=e.line_items)==null?void 0:r[0];if(n)return{paymentDescription:(n==null?void 0:n.description)??"",regularBilling:{amount:t.amount,label:(n==null?void 0:n.description)??"",recurringPaymentIntervalUnit:n==null?void 0:n.billing_interval,recurringPaymentIntervalCount:(n==null?void 0:n.billing_interval_count)??void 0,paymentTiming:"recurring",type:"final"},managementURL:`https://cde.getopenpay.com/pay/${e.token}`}},cl=({overridePaymentRequest:t,initialPreview:e,prefill:n,defaultLabel:r="Total"})=>{var c,l;const o=(((c=t==null?void 0:t.amount)==null?void 0:c.currency)??(n==null?void 0:n.currency)??e.currency).toUpperCase(),i=((((l=t==null?void 0:t.amount)==null?void 0:l.amountAtom)??(e==null?void 0:e.amountAtom)??0)/100).toFixed(2);return{currencyCode:o,total:{label:(t==null?void 0:t.label)??r??"Total",type:t!=null&&t.pending?"pending":"final",amount:i}}},fo=({overridePaymentRequest:t,initialPreview:e,prefill:n,defaultLabel:r})=>{const{currencyCode:o,total:s}=cl({overridePaymentRequest:t,initialPreview:e,prefill:n,defaultLabel:r});let i={countryCode:"US",currencyCode:o,requiredBillingContactFields:["email","postalAddress","name"],requiredShippingContactFields:["email"],supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit","supportsEMV"],total:s,recurringPaymentRequest:il({total:s,prefill:n})};return t!=null&&t.applePayPaymentRequest&&(typeof t.applePayPaymentRequest=="function"?i={...i,...t.applePayPaymentRequest(i)}:i={...i,...t.applePayPaymentRequest}),i},{log__:ed,err__:mo}=D("common"),Lt=t=>{if(t.payment_methods.length!==1)throw new Error(`Expected exactly one payment method, got ${t.payment_methods.length}`);return{payment_method_id:t.payment_methods[0].id}},ae=(t,e)=>{const n=t.find(r=>e.safeParse(r).success);if(!n)throw mo("No CPMs found for model. All models:",t),new Error("No CPMs found for model");return e.parse(n)},ho=t=>({new_customer_email:t.email,new_customer_address:{zip_code:t.zipCode,country:t.country},new_customer_first_name:t.firstName,new_customer_last_name:t.lastName}),jt=async t=>{const{log__:e}=D(t.logPrefix),n=await G(t.anyCdeConnection),r=Lt(t.confirmResult);if(n.mode==="setup")return e("Setting up payment method..."),{mode:"setup",result:await el(t.anyCdeConnection,{secure_token:n.token,pm_id:r.payment_method_id})};{if(t.usePayFirstFlow){if(e("Using pay-first flow..."),!t.confirmResult.pay_first_success_response)throw mo("Checkout failed, no pay-first success response:",t.confirmResult),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:t.confirmResult.pay_first_success_response}}e("Doing checkout...");const o={secure_token:n.token,payment_input:{provider_type:t.checkoutPaymentMethod.provider},customer_email:t.requiredFormFields[h.EMAIL],customer_zip_code:t.requiredFormFields[h.ZIP_CODE],customer_country:t.requiredFormFields[h.COUNTRY],promotion_code:t.requiredFormFields[h.PROMOTION_CODE],line_items:n.line_items,total_amount_atom:n.amount_total_atom,cancel_at_end:!1,checkout_payment_method:t.checkoutPaymentMethod,use_confirmed_pm_id:r.payment_method_id};return{mode:"checkout",result:await zn(t.anyCdeConnection,o)}}},ll="@keyframes fadeIn{0%{opacity:0;transform:scale(.9)}to{opacity:1;transform:scale(1)}}.overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483648!important;display:flex;justify-content:center;align-items:center;background-color:#00000080}.container{max-width:500px;max-height:600px;width:100%;height:100%;background-color:#fff;position:relative;animation:fadeIn .3s ease-out}.frame,#adyen-container,#adyen-container>*{max-width:500px;max-height:600px;width:100%;height:100%;border:none}.cancel-button{position:absolute;background:transparent;border:none;font-size:1rem;color:#fff;cursor:pointer;top:-1.5rem;padding:0;right:0}",yo=t=>{const e=document.createElement("template");e.innerHTML=`
|
|
13
13
|
<style>
|
|
14
|
-
${
|
|
14
|
+
${ll}
|
|
15
15
|
</style>
|
|
16
16
|
<div class="overlay">
|
|
17
17
|
<div class="container">
|
|
18
18
|
<button class="cancel-button">Cancel</button>
|
|
19
|
-
<iframe src="${
|
|
19
|
+
<iframe src="${t}" class="frame" id="three-ds-iframe" title="3D Secure verification" allow="payment"></iframe>
|
|
20
20
|
</div>
|
|
21
21
|
</div>
|
|
22
|
-
`;const
|
|
23
|
-
Error: ${re(e)}`),new Error(t)}},hl=async(n,e)=>{const t=pl(e),r=await fo({url:t["op-airwallex-3ds-url"],baseUrl:n}),o=ml(r.href??""),s=t["op-airwallex-initial-intent-id"];if(s!==o){const c="Unable to process your credit card. Please contact support for assistance.",l=`Intent ID from callback (${o}) does not match the initial intent ID (${s}).`;throw Gn(l),new Error(c)}return{existing_cc:{initial_intent_id:o,consent_id:t["op-airwallex-consent-id"]}}},mo=a.object({provider:a.literal("apple_pay"),processor_name:a.literal("airwallex"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string()})}),ho=a.object({provider:a.literal("google_pay"),processor_name:a.literal("airwallex"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string(),google_pay_merchant_id:a.string().nullish()})}),{log__:yo,err__:_o}=F("common-cc"),je=(n,e,t)=>{if(t){yo(`Received default field values: ${JSON.stringify(t)}`);for(const[o,s]of Object.entries(t))n[o]||(n[o]=s)}const r=Tt.safeParse(n);if(!r.success){const o=r.error.format(),s=pr(o);for(const[i,c]of Object.entries(s))e(i,c,i);throw _o("Got validation errors in non-CDE form fields",s),new Error("Got validation errors in non-CDE form fields")}return r.data},yl=(n,e)=>{for(const t of n)if(t.success===!1)throw t.errors.forEach(r=>{const o=ur.safeParse(r.elementType);if(!o.success)_o(`Unknown field name in onValidationError: ${r.elementType}. Error object:`,r);else{const s=o.data;e(s,r.errors)}}),yo(`Error tokenizing card: got validation errors: ${JSON.stringify(t.errors)}`),new Error("Got validation errors while tokenizing card")},{log__:mn}=F("awx-apple-pay");async function _l(n,e){try{const r=(await zn(e.connection,{checkout_payment_method:e.checkoutPaymentMethod,processor_specific_metadata:{airwallex_payment_session:{validation_url:n.validationURL,initiative_context:window.location.hostname,their_account_id:e.processorAccount.processor_account_id}}})).next_action_metadata,o=r==null?void 0:r.apple_pay_session;if(!o)throw new Error("No session data received from payment flow");e.session.completeMerchantValidation(o),E("apple_pay_complete_merchant_validation",{...o})}catch(t){throw e.session.abort(),t}}async function gl(n,e){if(!n.redirect_url)throw new Error("No redirect URL found");mn("3DS Required, starting verification...",n);const{status:t}=await fn({url:n.redirect_url,baseUrl:e.baseUrl});if(mn(`╰ 3DS verification completed [Status: ${t}]`),t===V.CANCELLED)throw new Error("3DS verification cancelled");if(t===V.FAILURE)throw new Error("3DS verification failed");const r=await ce(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{their_pm_id:n.their_pm_id,airwallex_consent_id:n.consent_id,payment_provider:e.checkoutPaymentMethod.provider}});return mn("[2nd] Confirm payment flow response",r),r}async function vl(n,e){var t,r,o,s,i;try{const c=n.payment,l=lo(e.nonCdeFormInputs,c),u=je(l,e.formCallbacks.get.onValidationError,e.defaultFieldValues);E("billing_details_received",{...u});const h=(await it(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:u[m.EMAIL],new_customer_first_name:u[m.FIRST_NAME],new_customer_last_name:u[m.LAST_NAME],new_customer_address:{zip_code:u[m.ZIP_CODE],country:u[m.COUNTRY]}})).required_user_actions[0].consent_id;if(!h)throw new Error("No consent ID received from payment flow");let f=await ce(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{payment_provider:e.checkoutPaymentMethod.provider,airwallex_consent_id:h,airwallex_payment_method_data:{type:"applepay",applepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:JSON.stringify(c.token)}}}});mn("[1st] Confirm payment flow response",f);let _=(r=(t=f.payment_methods)==null?void 0:t[0])==null?void 0:r.id;const w=(o=f.required_user_actions)==null?void 0:o.find(C=>C.type==="airwallex_payment_consent");if(w!=null&&w.redirect_url&&w.consent_id&&w.their_pm_id&&(f=await gl(w,e),_=(i=(s=f.payment_methods)==null?void 0:s[0])==null?void 0:i.id),!_)throw new Error("No PM ID found");const T={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(T),pn({logPrefix:"awx-applepay",anyCdeConnection:e.connection,checkoutPaymentMethod:e.checkoutPaymentMethod,requiredFormFields:u,confirmResult:f,usePayFirstFlow:!1})}catch(c){const l={status:ApplePaySession.STATUS_FAILURE};throw e.session.completePayment(l),c}}const{log__:Dt,err__:go}=F("awx-apple-pay"),wl=ze(async({context:n,formCallbacks:e})=>{const t={processor:le.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ue(n.checkoutPaymentMethods,mo);if(!r)return t;if(Dt("Loading Apple Pay script"),await co(),!window.ApplePaySession||!ApplePaySession.canMakePayments())return Dt("Apple Pay is not available on this device/browser"),t;if(Dt("Apple Pay Loaded"),!await ApplePaySession.canMakePayments())return Dt("No active cards available for Apple Pay"),t;if(!r.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const i=n.anyCdeConnection,c=await q(i),l=c.mode==="setup",u=await ct(i,c.token,l,void 0),d=async p=>{try{await Z.airwallexApplePay.run({context:n,checkoutPaymentMethod:r,nonCdeFormInputs:ge(n.formDiv),formCallbacks:e,customParams:{...p,initialPreview:u},initResult:void 0})}catch(h){go("Apple Pay payment error",h),e.get.onCheckoutError((h==null?void 0:h.message)??"Unknown error")}};return{processor:le.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),bl=Ie(async({context:n,checkoutPaymentMethod:e,nonCdeFormInputs:t,customParams:r,formCallbacks:o})=>{var _;const s=ue(n.checkoutPaymentMethods,mo),{overridePaymentRequest:i,initialPreview:c}=r,l=n.anyCdeConnection,u=await q(l),d=u.mode==="setup",p=uo({overridePaymentRequest:i,initialPreview:c,prefill:{...u},defaultLabel:(_=s==null?void 0:s.metadata)==null?void 0:_.processor_account_name}),h=new ApplePaySession(3,p),f={session:h,connection:n.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:t,processorAccount:s.metadata,prefill:u,isSetupMode:d,baseUrl:n.baseUrl,formCallbacks:o,defaultFieldValues:r==null?void 0:r.defaultFieldValues};return E("apple_pay_flow_started",{processor_name:e.processor_name,prefill:Qr(u,["brand"]),overridePaymentRequest:i}),new Promise((w,T)=>{const C=()=>{Dt("Payment cancelled by user"),T(new Error("Payment cancelled by user"))};h.oncancel=C,h.onvalidatemerchant=async x=>{try{await _l(x,f)}catch(R){T(R)}},h.onpaymentmethodselected=()=>{const x={newTotal:{...p.total}};h.completePaymentMethodSelection(x)},h.onpaymentauthorized=async x=>{E("apple_pay_payment_authorized");try{const R=await vl(x,f);w(R)}catch(R){T(R)}},h.begin()}).catch(w=>{throw go("Apple Pay payment error",w),E("apple_pay_payment_error",{error:w}),w})}),hn=({gateway:n,gatewayMerchantId:e,merchantName:t,merchantId:r,initialPreview:o,overridePaymentRequest:s,prefill:i})=>{var p,h;const c=((p=s==null?void 0:s.amount)==null?void 0:p.amountAtom)??(o==null?void 0:o.amountAtom)??0,l=Math.max(c/100,0),u=(((h=s==null?void 0:s.amount)==null?void 0:h.currency)??(i==null?void 0:i.currency)??o.currency).toUpperCase(),d={apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:[{type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:["AMEX","DISCOVER","INTERAC","JCB","MASTERCARD","VISA"],billingAddressRequired:!0,billingAddressParameters:{format:"FULL"},allowCreditCards:!0,allowPrepaidCards:!0},tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:n,gatewayMerchantId:e}}}],emailRequired:!0,merchantInfo:{merchantId:r??"",merchantName:t},transactionInfo:{countryCode:"US",currencyCode:u,totalPriceStatus:s!=null&&s.pending?"ESTIMATED":"FINAL",totalPrice:l.toFixed(2)}};return s!=null&&s.googlePayPaymentRequest?typeof s.googlePayPaymentRequest=="function"?{...d,...s.googlePayPaymentRequest(d)}:{...d,...s.googlePayPaymentRequest}:d},vo=()=>io({scriptId:"__op_internal_google_pay_sdk",src:"https://pay.google.com/gp/p/js/pay.js",checkLoadedFn:()=>{var n,e;return!!((e=(n=window.google)==null?void 0:n.payments)!=null&&e.api)}});let Bn=null;const wo=async n=>await Jr(n)==="prod"?"PRODUCTION":"TEST",yn=async(n,e)=>{const t=await wo(n);return Bn===null&&(Bn=new window.google.payments.api.PaymentsClient({environment:t,merchantInfo:e.merchantInfo})),Bn},El=n=>{const e=n.required_user_actions.find(t=>t.type==="airwallex_payment_consent");return e?dr.parse(e):null},bo=(n,e)=>{var o,s,i,c;const t={...n},r=(s=(o=e.paymentMethodData)==null?void 0:o.info)==null?void 0:s.billingAddress;if(r){const[l,...u]=((c=(i=r.name)==null?void 0:i.trim())==null?void 0:c.split(/\s+/))??[],d=u.join(" ")||void 0;t[m.EMAIL]=t[m.EMAIL]||e.email||"op_unfilled@getopenpay.com",t[m.COUNTRY]=t[m.COUNTRY]||r.countryCode||"US",t[m.ADDRESS]=t[m.ADDRESS]||r.address1||"",t[m.CITY]=t[m.CITY]||r.locality||"",t[m.ZIP_CODE]=t[m.ZIP_CODE]||r.postalCode||"00000",t[m.STATE]=t[m.STATE]||r.administrativeArea||"";const p=t[m.FIRST_NAME]||l||"",h=t[m.LAST_NAME]||d||"";p||h?(t[m.FIRST_NAME]=p,t[m.LAST_NAME]=h):(t[m.FIRST_NAME]="_OP_UNKNOWN",t[m.LAST_NAME]="")}return t},{log__:de,err__:lt}=F("awx-google-pay"),kl=ze(async({context:n,formCallbacks:e})=>{var p,h;const t={processor:le.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ue(n.checkoutPaymentMethods,ho);if(!r)return t;de("Google Pay CPM",r);const o=r.metadata;if(!o.processor_account_id)return lt("No gateway merchant ID found in processor account"),t;if(de("Loading Google Pay script"),await vo(),!((h=(p=window.google)==null?void 0:p.payments)!=null&&h.api))return lt("Google Pay SDK not loaded properly"),t;if(await wo(n.baseUrl)==="PRODUCTION"&&!o.google_pay_merchant_id)return lt("Google Pay merchant ID is required for production environment"),t;de("Google Pay SDK loaded",window.google.payments);try{const f=hn({gateway:"airwallex",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),_=await yn(n.baseUrl,f),{result:w}=await _.isReadyToPay(f);if(!w)return de("Google Pay is not available for this user"),t}catch(f){return lt("Error checking Google Pay availability",f),t}const i=n.anyCdeConnection,c=await q(i),l=c.mode==="setup",u=await ct(i,c.token,l,void 0),d=async f=>{try{Z.airwallexGooglePay.run({context:n,checkoutPaymentMethod:r,nonCdeFormInputs:ge(n.formDiv),formCallbacks:e,initResult:void 0,customParams:{...f,initialPreview:u}})}catch(_){lt("Google Pay payment error",_),e.get.onCheckoutError((_==null?void 0:_.message)??"Unknown error")}};return{processor:le.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),Cl=Ie(async({context:n,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:r,customParams:o})=>{var f,_,w,T,C,x,R;de("Starting Google Pay flow...");const s=ue(n.checkoutPaymentMethods,ho),{initialPreview:i,overridePaymentRequest:c}=o,l=s.metadata;if(!l.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const u=hn({gateway:"airwallex",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:i,overridePaymentRequest:c}),d=n.anyCdeConnection,p=await q(d);E("google_pay_flow_started",{processor_name:s.processor_name,prefill:Qr(p,["brand"]),overridePaymentRequest:c});const h=await yn(n.baseUrl,u);try{const j=await h.loadPaymentData(u);de("Google Pay Payment data",j);const J=bo(t,j),W=je(J,r.get.onValidationError,o==null?void 0:o.defaultFieldValues);E("billing_details_received",{...W});const Se=(_=(f=j.paymentMethodData)==null?void 0:f.tokenizationData)==null?void 0:_.token;if(!Se)throw new Error("No payment token received from Google Pay");const zu=await it(d,{payment_provider:e.provider,checkout_payment_method:e,new_customer_email:W[m.EMAIL],new_customer_first_name:W[m.FIRST_NAME],new_customer_last_name:W[m.LAST_NAME],new_customer_address:{zip_code:W[m.ZIP_CODE],country:W[m.COUNTRY]}}),gn=El(zu);de("Start flow next actions",gn);let Ye=await ce(d,{secure_token:p.token,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:gn==null?void 0:gn.consent_id,airwallex_payment_method_data:{type:"googlepay",googlepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:Se}}}});de("[1st] Confirm payment flow response",Ye);let Wn=(T=(w=Ye.payment_methods)==null?void 0:w[0])==null?void 0:T.id;const We=(C=Ye.required_user_actions)==null?void 0:C.find(Vt=>Vt.type==="airwallex_payment_consent");if(We&&We.redirect_url){de("3DS Required, starting verification...",We);const{status:Vt}=await fn({url:We.redirect_url,baseUrl:n.baseUrl});if(de(`╰ 3DS verification completed [Status: ${Vt}]`),Vt===V.CANCELLED)throw new Error("3DS verification cancelled");if(Vt===V.FAILURE)throw new Error("3DS verification failed")}if(We&&!Wn&&(Ye=await ce(d,{secure_token:p.token,their_pm_id:We.their_pm_id,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:We.consent_id}}),de("[2nd] Confirm payment flow response",Ye),Wn=(R=(x=Ye.payment_methods)==null?void 0:x[0])==null?void 0:R.id),!Wn)throw new Error("No PM ID found");return pn({logPrefix:"awx-googlepay",anyCdeConnection:d,checkoutPaymentMethod:e,requiredFormFields:W,confirmResult:Ye,usePayFirstFlow:!1})}catch(j){throw lt("Google Pay payment error",j),E("google_pay_payment_error",{error:j}),new Error((j==null?void 0:j.message)??"Unknown error")}}),Eo=a.object({provider:a.literal("apple_pay"),processor_name:a.literal("authorize_net"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string()})}),ko=a.object({provider:a.literal("google_pay"),processor_name:a.literal("authorize_net"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string(),google_pay_merchant_id:a.string().nullish()})});async function Sl(n,e){try{const r=(await zn(e.connection,{checkout_payment_method:e.checkoutPaymentMethod,processor_specific_metadata:{apple_payment_session:{validation_url:n.validationURL,initiative_context:window.location.hostname,their_account_id:e.processorAccount.processor_account_id}}})).next_action_metadata,o=r==null?void 0:r.apple_pay_session;if(!o)throw new Error("No session data received from payment flow");e.session.completeMerchantValidation(o),E("apple_pay_complete_merchant_validation",{...o})}catch(t){throw e.session.abort(),t}}async function Pl(n,e){var t,r;try{const o=n.payment,s=lo(e.nonCdeFormInputs,o),i=je(s,e.formCallbacks.get.onValidationError);E("billing_details_received",{...i}),await it(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:i[m.EMAIL],new_customer_first_name:i[m.FIRST_NAME],new_customer_last_name:i[m.LAST_NAME],new_customer_address:{zip_code:i[m.ZIP_CODE],country:i[m.COUNTRY]}});const c={dataDescriptor:"COMMON.APPLE.INAPP.PAYMENT",dataValue:window.btoa(JSON.stringify(o.token.paymentData))},l=await ce(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{payment_provider:e.checkoutPaymentMethod.provider,mobile_wallet_payment_data:c}});if(!((r=(t=l.payment_methods)==null?void 0:t[0])==null?void 0:r.id))throw new Error("No PM ID found");const d={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(d),pn({logPrefix:"authnet-applepay",anyCdeConnection:e.connection,checkoutPaymentMethod:e.checkoutPaymentMethod,requiredFormFields:i,confirmResult:l,usePayFirstFlow:!1})}catch(o){const s={status:ApplePaySession.STATUS_FAILURE};throw e.session.completePayment(s),o}}const{log__:_n,err__:Co}=F("authnet-applepay"),Al=ze(async({context:n,formCallbacks:e})=>{const t={processor:le.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ue(n.checkoutPaymentMethods,Eo);if(!r)return t;if(_n("Loading Apple Pay script"),await co(),!window.ApplePaySession||!ApplePaySession.canMakePayments())return _n("Apple Pay is not available on this device/browser"),t;if(!await ApplePaySession.canMakePayments())return _n("No active cards available for Apple Pay"),t;if(!r.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const i=n.anyCdeConnection,c=await q(i),l=c.mode==="setup",u=await ct(i,c.token,l,void 0),d=async p=>{try{await Z.authorizeNetApplePay.run({context:n,checkoutPaymentMethod:r,nonCdeFormInputs:ge(n.formDiv),formCallbacks:e,customParams:{...p,initialPreview:u},initResult:void 0})}catch(h){Co("Apple Pay payment error",h),E("apple_pay_payment_error",{error:h}),e.get.onCheckoutError((h==null?void 0:h.message)??"Unknown error")}};return{processor:le.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:d}}),Tl=Ie(async({context:n,checkoutPaymentMethod:e,nonCdeFormInputs:t,customParams:r,formCallbacks:o})=>{var _;const{initialPreview:s,overridePaymentRequest:i}=r,c=ue(n.checkoutPaymentMethods,Eo),l=n.anyCdeConnection,u=await q(l),d=u.mode==="setup",p=uo({overridePaymentRequest:i,initialPreview:s,prefill:u,defaultLabel:(_=c==null?void 0:c.metadata)==null?void 0:_.processor_account_name});E("apple_pay_flow_started",{processor_name:e.processor_name,prefill:u,overridePaymentRequest:i});const h=new ApplePaySession(3,p),f={session:h,connection:n.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:t,processorAccount:e.metadata,prefill:u,isSetupMode:d,baseUrl:n.baseUrl,formCallbacks:o};return new Promise((w,T)=>{h.oncancel=()=>{_n("Payment cancelled by user"),T(new Error("Payment cancelled by user"))},h.onvalidatemerchant=async C=>{try{await Sl(C,f)}catch(x){T(x)}},h.onpaymentmethodselected=()=>{const C={newTotal:p.total};h.completePaymentMethodSelection(C)},h.onpaymentauthorized=async C=>{E("apple_pay_payment_authorized");try{const x=await Pl(C,f);w(x)}catch(x){T(x)}},h.begin()}).catch(w=>{throw Co("Apple Pay payment error",w),E("apple_pay_payment_error",{error:w}),w})}),{log__:Ge,err__:Lt}=F("authnet-googlepay"),Il=ze(async({context:n,formCallbacks:e})=>{var d,p;Ge("Initializing Authnet GooglePay flow");const t={processor:le.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ue(n.checkoutPaymentMethods,ko);if(!r)return t;Ge("Google Pay CPM",r);const o=r.metadata;if(!o.processor_account_id)return Lt("No gateway merchant ID found in processor account"),t;if(Ge("Loading Google Pay script"),await vo(),!((p=(d=window.google)==null?void 0:d.payments)!=null&&p.api))return Lt("Google Pay SDK not loaded properly"),t;Ge("Google Pay SDK loaded",window.google.payments);try{const h=hn({gateway:"authorizenet",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),f=await yn(n.baseUrl,h),{result:_}=await f.isReadyToPay(h);if(!_)return Ge("Google Pay is not available for this user"),t}catch(h){return Lt("Error checking Google Pay availability",h),t}const s=n.anyCdeConnection,i=await q(s),c=i.mode==="setup",l=await ct(s,i.token,c,void 0),u=async h=>{try{Z.authorizeNetGooglePay.run({context:n,checkoutPaymentMethod:r,nonCdeFormInputs:ge(n.formDiv),formCallbacks:e,initResult:void 0,customParams:{...h,initialPreview:l}})}catch(f){Lt("Google Pay payment error",f),E("google_pay_payment_error",{error:f}),e.get.onCheckoutError((f==null?void 0:f.message)??"Unknown error")}};return{processor:le.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:u}}),xl=Ie(async({context:n,nonCdeFormInputs:e,checkoutPaymentMethod:t,formCallbacks:r,customParams:o})=>{var f,_,w,T;const{initialPreview:s,overridePaymentRequest:i}=o,l=ue(n.checkoutPaymentMethods,ko).metadata,u=hn({gateway:"authorizenet",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:s,overridePaymentRequest:i}),d=n.anyCdeConnection,p=await q(d);E("google_pay_flow_started",{processor_name:t.processor_name,prefill:p,overridePaymentRequest:i});const h=await yn(n.baseUrl,u);try{const C=await h.loadPaymentData(u);Ge("Google Pay Payment data",C);const x=bo(e,C),R=je(x,r.get.onValidationError);E("billing_details_received",{...R});const j=(_=(f=C.paymentMethodData)==null?void 0:f.tokenizationData)==null?void 0:_.token;if(!j)throw new Error("No payment token received from Google Pay");const J=await it(d,{payment_provider:t.provider,checkout_payment_method:t,new_customer_email:R[m.EMAIL],new_customer_first_name:R[m.FIRST_NAME],new_customer_last_name:R[m.LAST_NAME],new_customer_address:{zip_code:R[m.ZIP_CODE],country:R[m.COUNTRY]}});Ge("Start payment flow response",J);const W=await ce(d,{secure_token:p.token,processor_specific_metadata:{payment_provider:t.provider,mobile_wallet_payment_data:{dataDescriptor:"COMMON.GOOGLE.INAPP.PAYMENT",dataValue:window.btoa(j)}}});if(!((T=(w=W.payment_methods)==null?void 0:w[0])==null?void 0:T.id))throw new Error("No PM ID found");return pn({logPrefix:"authnet-googlepay",anyCdeConnection:d,checkoutPaymentMethod:t,requiredFormFields:R,confirmResult:W,usePayFirstFlow:!1})}catch(C){throw Lt("Google Pay payment error",C),E("google_pay_payment_error",{error:C}),new Error((C==null?void 0:C.message)??"Unknown error")}}),{log__:Rl,err__:So}=F("pockyt-cc"),Nl=a.object({"op-pockyt-3ds-url":a.string(),"op-pockyt-txn-no":a.string(),"op-pockyt-ref-no":a.string()}),Ol=n=>{const e=Nl.safeParse(n);if(!e.success){const t="Unable to process your credit card. Please contact support for assistance.",r=`Pockyt 3DS is required but headers are malformed. Got: ${JSON.stringify(n)}`;throw So(r),new Error(t)}return e.data},Po=n=>{try{const e=new URL(n??"").searchParams.get("vaultId");if(!e)throw new Error("No vault ID found in 3DS verification result");return Rl(`3DS verification success. [Vault ID: ${e}]`),e}catch(e){const t="Error verifying 3DS verification result.";throw So(t,`Resulting URL: ${n}.
|
|
24
|
-
Error: ${re(e)}`),new Error(t)}},Ml=(n,e)=>new URL(n).searchParams.get(e),Dl=n=>(n==null?void 0:n["op-pockyt-3ds-url"])!==void 0,Ll=async(n,e)=>{const t=Ol(e),r=await fo({url:t["op-pockyt-3ds-url"],baseUrl:n});return{existing_cc:{vault_id:Po(r.href??""),transaction_no:t["op-pockyt-txn-no"],reference_no:t["op-pockyt-ref-no"]}}},Fl=a.enum(["test","live","live-us","live-in","live-apse","live-au"]),jl=a.enum(["ar","bg-BG","ca-ES","cs-CZ","da-DK","de-DE","el-GR","en-US","es-ES","et-EE","fi-FI","fr-FR","hr-HR","hu-HU","is-IS","it-IT","ja-JP","ko-KR","lt-LT","lv-LV","nl-NL","no-NO","pl-PL","pt-BR","pt-PT","ro-RO","ru-RU","sk-SK","sl-SI","sv-SE","zh-CN","zh-TW"]),{log__:ut,err__:Ft}=F("adyen-cc"),Ul=a.object({"op-account-id":a.string(),"op-adyen-client-key":a.string(),"op-adyen-environment":Fl,"op-adyen-action":a.string()}),Ao="Unable to process your credit card. Please contact support for assistance.",$l=n=>{const e=Ul.safeParse(n);if(!e.success)throw Ft(`Adyen 3DS is required but headers are malformed. Got: ${JSON.stringify(n)}`),new Error(Ao);return e.data},Vl=n=>JSON.parse(n),To=()=>"AdyenWeb"in window&&"AdyenCheckout"in window.AdyenWeb,Zl=async()=>{ut("Waiting for Adyen SDK to load...");for(let n=0;n<10;n++)To()||await An(500);if(!To())throw Ft("Adyen SDK not loaded properly"),new Error(Ao);return ut("Adyen SDK loaded successfully"),window.AdyenWeb.AdyenCheckout},zl=n=>{const{headers:e,locale:t,countryCode:r,component:o,host:s,cancelButton:i}=n,c=Vl(e["op-adyen-action"]);return ut(`Running Adyen 3DS flow for action type: ${c.type}`),new Promise(l=>{const u=()=>{ut("Cleaning up Adyen 3DS flow"),i.removeEventListener("click",h),s.remove()},d=_=>{Ft("Authentication failed. Result:",_),l({status:V.FAILURE,cleanup:u})},p=_=>{Ft("Adyen error:",_),l({status:V.FAILURE,cleanup:u})},h=()=>{l({status:V.CANCELLED,cleanup:u})};i.addEventListener("click",h);const f=(_,w,T)=>{s.remove(),l({status:V.SUCCESS,additionalDetails:_,cleanup:u})};Zl().then(_=>_({clientKey:e["op-adyen-client-key"],environment:e["op-adyen-environment"],locale:t,countryCode:r,onAdditionalDetails:f,onPaymentFailed:d,onError:p})).then(_=>{_.createFromAction(c,{challengeWindowSize:"03"}).mount(o)})})},Gl=n=>{const e=navigator.languages&&navigator.languages.length?navigator.languages[0]:navigator.language,t=n??e,r=jl.safeParse(t);return r.success?(ut(`Resolved locale: ${r.data}`),r.data):(Ft(`Resolved invalid locale: ${t}. Defaulting to en-US.`),"en-US")},Bl=n=>(n==null?void 0:n["op-adyen-action"])!==void 0,ql=async(n,e,t)=>{const r=$l(e),o=document.createElement("div");o.id="adyen-container";const{host:s,iframe:i,cancelButton:c}=po("http://example.com");i.replaceWith(o);const l=await zl({headers:r,locale:Gl(t),countryCode:n,component:o,host:s,cancelButton:c});if(l.cleanup(),l.status===V.FAILURE)throw new Error("3DS verification failed");if(l.status===V.CANCELLED)throw new Error("3DS verification cancelled");if(l.status===V.SUCCESS){if(!l.additionalDetails)throw new Error("3DS verification succeeded but no additional details were returned");return ut("3DS verification succeeded"),{existing_cc:{additional_details:l.additionalDetails.data}}}else un(l.status)},{log__:D,err__:Io}=F("common-cc"),{log__:xo}=F("stripe-cc");a.array(a.object({our_existing_pm_id:a.string()})).length(1);const Yl=Ie(async({context:n,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:r,customParams:o})=>{var u;D("├ Running common CC flow...",{checkoutPaymentMethod:e});const s=n.anyCdeConnection,i=await q(s);E("common_cc_flow_started",{...e,prefill:i}),D(`├ Validating non-CDE form fields [Mode: ${i.mode}]`);const c=je(t,r.get.onValidationError);E("billing_details_received",{...c});const l={session_id:n.elementsSessionId,checkout_payment_method:e,non_cde_form_fields:c,extra_metadata:{origin:window.location.origin},payment_route_id:o.paymentRouteId};try{D(`├ Tokenizing card info in CDE [Session: ${n.elementsSessionId}]`);const d=await Jc(o.currentCdeConnections,{session_id:n.elementsSessionId});if(yl(d,r.get.onValidationError),i.mode==="setup"){D(`├ Setting up payment method in CDE [Token: ${i.token}]`);const p=await Qc(s,l);return D(`╰ Setup completed successfully [PM ID: ${p.payment_method_id}]`),{mode:"setup",result:p}}else{D(`├ Initial checkout flow. Checking out card info in CDE [Session: ${n.elementsSessionId}]`);const p=await oo(s,l);return D("╰ Checkout completed successfully."),{mode:"checkout",result:p}}}catch(d){if(d instanceof ro&&d.originalErrorMessage.includes("3DS_REQUIRED")){D("├ Card requires 3DS, starting non-legacy payment flow"),D("Received 3DS error response headers:",d.response.headers),E("3ds_required",{...e,...d.response.headers});const p=Dl(d.response.headers);if(p){D("├ Pockyt 3DS case detected. Going through Pockyt 3DS flow.");const C=await Ll(n.baseUrl,d.response.headers);l.extra_metadata.pockyt=C}if(fl(d.response.headers)){D("├ Airwallex 3DS case detected. Going through Airwallex 3DS flow.");const C=await hl(n.baseUrl,d.response.headers);l.extra_metadata.airwallex=C}if(Bl(d.response.headers)){D("├ Adyen 3DS case detected. Going through Adyen 3DS flow.");const C=await ql(t[m.COUNTRY],d.response.headers,i.locale);l.extra_metadata.adyen=C}const _=await qc(s,l);D("├ Payment flow result:",_);const w=((u=d.response.headers)==null?void 0:u["op-should-use-new-flow"])!=="true";p?D("├ Pre-start 3DS is successful, other 3DS flows will be skipped."):w?(D("├ Using stripe 3DS flow"),await Ql(_)):(D("├ Using common 3DS flow"),await Jl(_,n.baseUrl));const T=_.cc_pm_id;if(i.mode==="setup"){D(`├ Confirming payment flow [cc_pm_id: ${T}]`);const C=await ce(s,{secure_token:i.token,existing_cc_pm_id:T});D("├ Confirm payment flow result received Result:",C);const x=Mt(C);return D(`╰ Setup completed successfully [PM ID: ${x.payment_method_id}]`),{mode:"setup",result:x}}else{D(`├ Checking out after 3DS flow [Flow: ${w?"legacy":"new"}]`);const C=await oo(s,{...l,existing_cc_pm_id:T,do_not_use_legacy_cc_flow:w});return D("╰ Checkout completed successfully."),{mode:"checkout",result:C}}}throw Io("╰ Error checking out card info in CDE"),Io(d),d}}),Wl=n=>{const e=n.required_user_actions.find(t=>t.type==="stripe_3ds");if(!e)throw new Error("No stripe 3DS action found");return Sa.parse(e)},Hl=["airwallex_payment_consent","adyen"],Kl=n=>{const e=n.required_user_actions.find(t=>Hl.includes(t.type));if(!e)throw new Error("No common 3DS action found");return Ea.parse(e)},Jl=async(n,e)=>{const t=Kl(n);if(t.redirect_url==="3DS_COMPLETE"){D("├ 3DS flow completed successfully"),E("3ds_complete");return}D(`├ Using common 3DS flow [URL: ${t.redirect_url}]`),E("3ds_redirect",{...t});const{status:r}=await fn({url:t.redirect_url,baseUrl:e});if(D(`╰ 3DS verification completed [Status: ${r}]`),r===V.CANCELLED)throw E("3ds_cancelled"),new Error("3DS verification cancelled");if(r===V.FAILURE)throw E("3ds_failure"),new Error("3DS verification failed")},Ql=async n=>{const e=Wl(n);E("3ds_stripe_redirect",{...e}),xo(`├ Using stripe 3DS flow [Client Secret: ${e.client_secret.substring(0,8)}...]`),await Na(e),E("3ds_stripe_complete"),xo("╰ Stripe 3DS flow completed successfully")},Xl=1,eu=a.object({processor_name:a.literal("loop"),provider:a.literal("crypto"),metadata:a.object({merchant_id:a.string(),entity_id:a.string(),api_token:a.string(),supported_currencies:a.array(a.string()),environment:a.string()})}),{log__:ee,err__:Ro}=F("loop-crypto"),tu=a.object({loopFirstName:$,loopLastName:$,loopEmail:$,[m.PROMOTION_CODE]:O}),nu=a.object({loopFirstName:O,loopLastName:O,loopEmail:O,[m.PROMOTION_CODE]:O}),No=(n,e,t,r)=>{const o=t.safeParse(n);if(!o.success){const s=o.error.format(),i=pr(s);for(const[c,l]of Object.entries(i))e(c,l,c);throw Ro("Got validation errors in non-CDE form fields",i),new Error("Got validation errors in non-CDE form fields")}return o.data},ru=ze(async({context:n})=>{ee("Checking if there are any CPMs for Loop Crypto...");const e=ue(n.checkoutPaymentMethods,eu);ee(`checkoutPaymentMethod: ${JSON.stringify(e)}`),ee("Starting Loop Crypto flow...");const t=await q(n.anyCdeConnection),r=await zn(n.anyCdeConnection,{checkout_payment_method:e});if(t.mode!=="setup"&&!e.metadata.supported_currencies.includes(t.currency))throw Error(`Currency ${t.currency} not enabled for Loop. Enabled currencies: ${e.metadata.supported_currencies}`);if(!r||!r.next_action_metadata)throw Error("Failed to fetch necessary setup data for Loop");const o=r.next_action_metadata;let s;t.mode==="setup"?s=Xl:s=t.amount_total_atom*o.token_price;const i=s,c=o.authorization_amount,l=Xt(),u={paymentUsdAmount:i,suggestedAuthorizationUsdAmount:c,customerRefId:l},d={apiKey:e.metadata.api_token,entityId:e.metadata.entity_id,merchantId:e.metadata.merchant_id,environment:e.metadata.environment};return{isAvailable:!0,widgetProps:u,initLoopConnectProps:d}}),ou=Ie(async({context:n,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:r,customParams:o})=>{ee("Running Loop flow..."),ee("context",n),ee("checkoutPaymentMethod",e),ee("nonCdeFormInputs",t),ee("flowCallbacks",r),ee("customParams",o);let s;o!=null&&o.success?s=No(t,r.get.onValidationError,tu):s=No(t,r.get.onValidationError,nu);const i=n.anyCdeConnection,c=await q(n.anyCdeConnection),l=c.mode!=="setup",u=await it(n.anyCdeConnection,{checkout_payment_method:e,payment_provider:e.provider,new_customer_email:s.loopEmail,new_customer_first_name:s.loopFirstName,new_customer_last_name:s.loopLastName,use_pay_first_flow:l,pay_first_flow_cart_info:l?{line_items:c.line_items,displayed_total_amount_atom:c.amount_total_atom}:void 0});if(!o)throw Error("Checkout failed. Failed to properly submit form data.");const d=await ce(i,{secure_token:c.token,their_pm_id:o.success?o.payin.paymentMethod.paymentMethodId:void 0,checkout_attempt_id:c.mode!=="setup"?u.checkout_attempt_id:void 0,processor_specific_metadata:{loop_customer:o.success?o.customer:void 0,loop_payin:o.success?o.payin:void 0,loop_failure_details:o.success?void 0:o.failureDetails,loop_debug_info:o.success?void 0:o.debugInfo,loop_success:o.success}});if(ee(`Confirm result: ${d}`),c.mode==="setup"){ee("Doing payment setup..."),ee("├ Confirm payment flow result received Result:",d);const p=Mt(d);return ee(`╰ Setup completed successfully [PM ID: ${p.payment_method_id}]`),{mode:"setup",result:p}}else{if(ee("Doing checkout..."),!d.pay_first_success_response)throw Ro("Checkout failed, no pay-first success response:",d),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:d.pay_first_success_response}}}),{log__:be,err__:Oo}=F("pockyt-paypal"),su=a.object({processor_name:a.literal("pockyt"),provider:a.literal("paypal")});a.array(a.object({paypal_iframe_url:a.string(),verify_token:a.string()})).length(1);const au=Ie(async({context:n,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:r,customParams:o})=>{var W,Se;be("Running Pockyt Paypal flow...");const s=n.anyCdeConnection,i=await q(s);be("Verifying CPM...");const c=su.parse(e);be("├ Validating non-CDE form fields");const l=o==null?void 0:o.settings,u=je(t,r.get.onValidationError,l==null?void 0:l.defaultFieldValues),d=ol(u);be(`Starting payment flow... Mode: ${i.mode}`);const p=Xt(),h=i.mode!=="setup",f={payment_provider:c.provider,checkout_payment_method:c,use_pay_first_flow:h,pay_first_flow_cart_info:h?{line_items:i.line_items,displayed_total_amount_atom:i.amount_total_atom}:void 0,processor_specific_metadata:{use_paypal_redirect_flow:!!((W=o==null?void 0:o.settings)!=null&&W.useRedirectFlow),frontend_token_for_redirect_flow:p},...d},_=new URL("/app/pre-action/start/",n.baseUrl).toString(),w=btoa(JSON.stringify(f)),T=new URLSearchParams({st:i.token,r:w}),C=`${_}?${T.toString()}`;if((Se=o==null?void 0:o.settings)!=null&&Se.useRedirectFlow)throw be("Starting redirect mode for PayPal..."),window.location.href=C,await An(20*1e3),new Error("Paypal flow timed out, please try again with another payment method.");be("Starting popup mode for PayPal..."),be("Opening paypal iframe...");const x=await ll("PayPal",s,p,C);be("Paypal flow result",x);const R=Po(x.href),j=Ml(x.href,"catt");if(!j)throw Oo("Checkout attempt ID not found in redirect URL:",x.href),new Error("Checkout attempt ID not found in redirect URL");be(`Confirming payment flow using vault ID ${R}`);const J=await ce(s,{secure_token:i.token,their_pm_id:R,checkout_attempt_id:h?j:void 0});if(be("Confirm payment flow result",J),i.mode==="setup")return{mode:"setup",result:{payment_method_id:J.payment_methods[0].id}};if(!J.pay_first_success_response)throw Oo("Checkout failed, no pay-first success response:",J),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:J.pay_first_success_response}}),Mo="ojs-stripe-link-btn",{log__:Y,err__:iu}=F("stripe-link"),cu=a.object({provider:a.literal("stripe_link"),processor_name:a.literal("stripe"),metadata:a.object({stripe_pk:a.string()})}),lu=a.array(a.object({our_existing_pm_id:a.string()})).length(1),uu=ze(async({context:n,formCallbacks:e})=>{const t=n.customInitParams.stripeLink;Y("Checking if there are any CPMs for Stripe Link...");const r=ue(n.checkoutPaymentMethods,cu);Y("Starting stripe link flow...");const o=n.anyCdeConnection,s=await q(o),i=s.mode==="setup";Y("Creating stripe elements...");const c=await ct(o,s.token,i,void 0),{elements:l,stripe:u}=await Ta(r.metadata.stripe_pk,{mode:"setup",currency:c.currency,setup_future_usage:"off_session",paymentMethodCreation:"manual"});Y("Creating express checkout...");const d=l.create("expressCheckout",{buttonHeight:t==null?void 0:t.buttonHeight,paymentMethods:{amazonPay:"never",applePay:"never",googlePay:"never",paypal:"never"}}),p=()=>{d.mount(`#${Mo}`)},h=()=>{d.unmount()};return t!=null&&t.doNotMountOnInit?Y("NOT mounting stripe link button (doNotMountOnInit is true)"):(Y("Mounting stripe link button..."),p()),d.on("click",async f=>{if(Y("Stripe Link button clicked"),t!=null&&t.overrideLinkSubmit&&!await t.overrideLinkSubmit()){Y("Stripe Link submit aborted by overrideLinkSubmit");return}f.resolve()}),d.on("confirm",async f=>{Y("Stripe Link window confirmed",f);const _=await u.createPaymentMethod({elements:l,params:{billing_details:f.billingDetails}});_.error?(iu("error",_.error),e.get.onCheckoutError(_.error.message??"Stripe Link unknown error")):(Y("paymentMethod",_.paymentMethod),Z.stripeLink.run({context:n,checkoutPaymentMethod:r,nonCdeFormInputs:ge(n.formDiv),formCallbacks:e,customParams:{stripePM:_.paymentMethod},initResult:{isAvailable:!0}}))}),{isAvailable:!0,controller:{mountButton:p,dismountButton:h,waitForButtonToMount:async()=>await fu(Mo)}}}),du=Ie(async({context:n,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:r,customParams:o})=>{Y("Running Stripe Link flow...");const s=n.anyCdeConnection;Y("Merging PM fields with form fields...");const i=pu(t,o.stripePM),c=je(i,r.get.onValidationError);E("billing_details_received",{...c}),Y("Starting payment flow...");const l=await it(s,{payment_provider:e.provider,checkout_payment_method:e,their_existing_pm_id:o.stripePM.id,new_customer_email:c[m.EMAIL],new_customer_first_name:c[m.FIRST_NAME],new_customer_last_name:c[m.LAST_NAME],new_customer_address:{zip_code:c[m.ZIP_CODE],country:c[m.COUNTRY]}});Y("Start payment flow response",l);const d=lu.parse(l.required_user_actions)[0].our_existing_pm_id,p=await q(s);if(p.mode==="setup"){Y("Doing payment setup...");const h=await ce(s,{secure_token:p.token,existing_cc_pm_id:d});return{mode:"setup",result:Mt(h)}}else{Y("Doing checkout...");const h={secure_token:p.token,payment_input:{provider_type:e.provider},customer_email:c[m.EMAIL],customer_zip_code:c[m.ZIP_CODE],customer_country:c[m.COUNTRY],promotion_code:c[m.PROMOTION_CODE],line_items:p.line_items,total_amount_atom:p.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await Zn(s,h)}}}),pu=(n,e)=>{var l,u,d,p,h;const t={...n},[r,...o]=((u=(l=e.billing_details.name)==null?void 0:l.trim())==null?void 0:u.split(/\s+/))??[],s=o.join(" ")||void 0;t[m.EMAIL]=t[m.EMAIL]||((d=e.link)==null?void 0:d.email)||e.billing_details.email||"op_unfilled@getopenpay.com",t[m.ZIP_CODE]=t[m.ZIP_CODE]||((p=e.billing_details.address)==null?void 0:p.postal_code)||"00000",t[m.COUNTRY]=t[m.COUNTRY]||((h=e.billing_details.address)==null?void 0:h.country)||"US";const i=t[m.FIRST_NAME]||r||"",c=t[m.LAST_NAME]||s||"";return i||c?(t[m.FIRST_NAME]=i,t[m.LAST_NAME]=c):(t[m.FIRST_NAME]="_OP_UNKNOWN",t[m.LAST_NAME]=""),Y("Final form inputs:",t),t},fu=n=>new Promise(e=>{const t=()=>{const r=document.getElementById(n);r?e(r):requestAnimationFrame(t)};t()}),{log__:X,err__:mu}=F("stripe-pr"),hu=a.object({provider:a.union([a.literal("apple_pay"),a.literal("google_pay")]),processor_name:a.literal("stripe"),metadata:a.object({stripe_pk:a.string()})}),yu=ze(async({context:n,formCallbacks:e})=>{X("Checking if there are any CPMs for Stripe PR...");const t=ue(n.checkoutPaymentMethods,hu);X("Initializing Stripe PR flow...");const r=n.anyCdeConnection,o=await q(r),s=o.mode==="setup";X("Getting initial preview amount");const i=await ct(r,o.token,s,void 0),c=await Ia(t.metadata.stripe_pk,i.amountAtom,i.currency,s);X("Checking if can make payment");const l=await c.canMakePayment();if(l===null)return mu("canMakePayment returned null"),{isAvailable:!1,reason:"canMakePayment returned null"};X("Stripe PR flow initialized successfully. Can make payment",l);const u=(d,p)=>Z.stripePR.run({context:n,checkoutPaymentMethod:jt(n.checkoutPaymentMethods,d),nonCdeFormInputs:ge(n.formDiv),formCallbacks:e,customParams:{provider:d,overridePaymentRequest:p==null?void 0:p.overridePaymentRequest},initResult:{processor:le.Enum.stripe,pr:c,isAvailable:!0,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}});return{processor:le.Enum.stripe,isAvailable:!0,pr:c,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}}),_u=Ie(async({context:n,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:r,customParams:o,initResult:s})=>{if(X("Running Stripe PR flow..."),o.provider!==e.provider)throw new Error(`Provider mismatch. Expected ${o.provider}, got ${e.provider}`);const i=n.anyCdeConnection,c=s.pr;if(o!=null&&o.overridePaymentRequest){const _=o.overridePaymentRequest;X("Overriding PR amount with",_);const w=typeof _.applePayPaymentRequest=="function"?_.applePayPaymentRequest({}):_.applePayPaymentRequest;vu(c,_.amount,_.pending,w,_.label)}X("Showing PR dialog..."),c.show();const l=await xa(c);X("Stripe PM added event:",l),X("Merging PM fields with form fields...");const u=gu(t,l),d=je(u,r.get.onValidationError);E("billing_details_received",{...d}),X("PR dialog finished. Starting payment flow...",d);const p=await Yc(i,{fields:d,checkoutPaymentMethod:e}),h=wu(p);X("Confirming PR with Stripe..."),await Ra(h,l);const f=await q(i);if(f.mode==="setup"){X("Confirming payment flow for setup...");const _=await ce(i,{secure_token:f.token});return{mode:"setup",result:Mt(_)}}else{X("Performing checkout...");const _={secure_token:f.token,payment_input:{provider_type:e.provider},customer_first_name:d[m.FIRST_NAME],customer_last_name:d[m.LAST_NAME],customer_email:d[m.EMAIL],customer_zip_code:d[m.ZIP_CODE],customer_country:d[m.COUNTRY],promotion_code:d[m.PROMOTION_CODE],line_items:f.line_items,total_amount_atom:f.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await Zn(i,_)}}}),gu=(n,e)=>{var d,p,h,f;const t={...n},[r,...o]=((p=(d=e.payerName)==null?void 0:d.trim())==null?void 0:p.split(/\s+/))??[],s=o.join(" ")||void 0,i=(f=(h=e.paymentMethod)==null?void 0:h.billing_details)==null?void 0:f.address,c=e.shippingAddress;t[m.EMAIL]=t[m.EMAIL]||e.payerEmail||"op_unfilled@getopenpay.com",t[m.ZIP_CODE]=t[m.ZIP_CODE]||(i==null?void 0:i.postal_code)||(c==null?void 0:c.postalCode)||"00000",t[m.COUNTRY]=t[m.COUNTRY]||(i==null?void 0:i.country)||(c==null?void 0:c.country)||"US";const l=t[m.FIRST_NAME]||r||"",u=t[m.LAST_NAME]||s||"";return l||u?(t[m.FIRST_NAME]=l,t[m.LAST_NAME]=u):(t[m.FIRST_NAME]="_OP_UNKNOWN",t[m.LAST_NAME]=""),X("Final form inputs:",t),t},vu=(n,e,t,r,o)=>{n.update({total:{amount:e.amountAtom,label:o??"Total",pending:t},currency:e.currency,applePay:r})},wu=n=>{if(n.required_user_actions.length!==1)throw new Error(`Error occurred.
|
|
25
|
-
Details: got ${n.required_user_actions.length} required user actions`);return Pa.parse(n.required_user_actions[0])},jt=(n,e,t)=>{const r=n.filter(o=>{const s=t===void 0?!0:o.processor_name===t,i=o.provider===e;return s&&i});if(r.length===0)throw console.warn("CPMs list",n),new Error(`No CPMs found with provider '${e}' and processor '${t}'`);return r.length!==1&&(console.warn("CPMs list",n),console.warn(`More than one CPM found with provider '${e}' and processor '${t}'`),E("more_than_one_cpm_found",{provider:e,processor:t,cpms:n})),r[0]},Z={commonCC:{init:async()=>{},run:Yl},stripePR:{init:yu,run:_u},stripeLink:{init:uu,run:du},pockytPaypal:{run:au},airwallexGooglePay:{init:kl,run:Cl},airwallexApplePay:{init:wl,run:bl},loopCrypto:{init:ru,run:ou},authorizeNetApplePay:{init:Al,run:Tl},authorizeNetGooglePay:{init:Il,run:xl}},{log__:bu,err__:Eu}=F("init-flows"),Be=(n,e)=>{const t=new Ot;return{publisher:t,initialize:async r=>{try{if(t.current.isSuccess)throw new Error("This flow has already been initialized.");const o=await e(r);bu(`✔ ${n} flow initialized successfully. Result:`,o),t.set(o)}catch(o){Eu(`𝙭 ${n} flow initialization failed. Error:`,re(o),"Details:",o),t.throw(o,re(o))}}}},ku=async(n,e,t)=>{await Promise.all(Object.values(n).map(r=>r.initialize({context:e,formCallbacks:t})))},Cu=()=>({stripePR:Be("Stripe PR",Z.stripePR.init),stripeLink:Be("Stripe Link",Z.stripeLink.init),airwallexGooglePay:Be("Airwallex GooglePay",Z.airwallexGooglePay.init),airwallexApplePay:Be("Airwallex ApplePay",Z.airwallexApplePay.init),loop:Be("Loop",Z.loopCrypto.init),authorizeNetGooglePay:Be("Authnet GooglePay",Z.authorizeNetGooglePay.init),authorizeNetApplePay:Be("Authnet ApplePay",Z.authorizeNetApplePay.init)}),{err__:Su}=F("form-callbacks"),pe=a.function().optional(),Do=a.object({onFocus:pe,onBlur:pe,onChange:pe,onLoad:pe,onLoadError:pe,onValidationError:pe,onCheckoutStarted:pe,onCheckoutSuccess:pe,onSetupPaymentMethodSuccess:pe,onCheckoutError:pe,onPaymentRequestLoad:pe}),ke=class ke{constructor(){this.setCallbacks=e=>{this._callbacks=ke.createEmptyCallbacks(),Object.entries(e).forEach(([t,r])=>{const o=Hs(t,r??ke.NOOP,Su);this._callbacks[t]=o})},this._callbacks=ke.createEmptyCallbacks()}get get(){return{...this._callbacks}}};ke.NOOP=()=>{},ke.createEmptyCallbacks=()=>{const e={};return Object.keys(Do.keyof().enum).forEach(t=>{e[t]=ke.NOOP}),e},ke.fromObject=e=>{const t=new ke;return t.setCallbacks(Do.parse(e)),t};let qn=ke;const Lo="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Ut=32,Pu=16,Fo=10,jo=0xffffffffffff;var qe;(function(n){n.Base32IncorrectEncoding="B32_ENC_INVALID",n.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",n.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",n.EncodeTimeNegative="ENC_TIME_NEG",n.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",n.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",n.PRNGDetectFailure="PRNG_DETECT",n.ULIDInvalid="ULID_INVALID",n.Unexpected="UNEXPECTED",n.UUIDInvalid="UUID_INVALID"})(qe||(qe={}));class $t extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e}}function Au(n){let e=Math.floor(n()*Ut);return e===Ut&&(e=Ut-1),Lo.charAt(e)}function Tu(n){const e=Iu(),t=e&&(e.crypto||e.msCrypto)||null;if(typeof(t==null?void 0:t.getRandomValues)=="function")return()=>{const r=new Uint8Array(1);return t.getRandomValues(r),r[0]/255};if(typeof(t==null?void 0:t.randomBytes)=="function")return()=>t.randomBytes(1).readUInt8()/255;throw new $t(qe.PRNGDetectFailure,"Failed to find a reliable PRNG")}function Iu(){return Nu()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function xu(n,e){let t="";for(;n>0;n--)t=Au(e)+t;return t}function Ru(n,e=Fo){if(isNaN(n))throw new $t(qe.EncodeTimeValueMalformed,`Time must be a number: ${n}`);if(n>jo)throw new $t(qe.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${jo}: ${n}`);if(n<0)throw new $t(qe.EncodeTimeNegative,`Time must be positive: ${n}`);if(Number.isInteger(n)===!1)throw new $t(qe.EncodeTimeValueMalformed,`Time must be an integer: ${n}`);let t,r="";for(let o=e;o>0;o--)t=n%Ut,r=Lo.charAt(t)+r,n=(n-t)/Ut;return r}function Nu(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function Ou(n,e){const t=Tu(),r=Date.now();return Ru(r,Fo)+xu(Pu,t)}const Uo="op_analytics_device_token",Mu=()=>{const n=document.cookie.split(";").find(t=>t.includes(Uo));if(n)return n.split("=")[1];const e=Ou();return Du(e),e},Du=n=>{const e=new Date;e.setFullYear(e.getFullYear()+1),document.cookie=`${Uo}=${n}; path=/; expires=${e.toUTCString()}`};function Lu(){try{const n=U();if(n!=null&&n.next||n!=null&&n.__NEXT_DATA__||document.querySelector("#__next"))return"nextjs";const e=U();if(e!=null&&e.__NUXT__||document.querySelector("#__nuxt"))return"nuxt";if(Object.keys(document).find(r=>r.includes("react"))||Array.from(document.body.querySelectorAll("body > *")).find(r=>r._reactRootContainer))return"react";const t=U();return t!=null&&t.Vue||t!=null&&t.__VUE__?"vue":document.querySelector("[ng-version]")?"angular":"vanilla"}catch{return"unknown"}}function Fu(n){var e,t,r;try{switch(n){case"react":return null;case"nextjs":{const o=U();return((e=o==null?void 0:o.next)==null?void 0:e.version)||((t=o==null?void 0:o.__NEXT_DATA__)==null?void 0:t.buildId)||null}case"nuxt":return null;case"vue":return null;case"angular":{const o=(r=U())==null?void 0:r.document,s=o==null?void 0:o.querySelector("[ng-version]");return s?s.getAttribute("ng-version"):null}default:return null}}catch{return null}}function ju(){const n=Lu(),e=Fu(n);return{framework:n,version:e}}class Uu{constructor(e,t,r,o){this.handleMessage=s=>{if(!s.source){console.warn("[OJS] No source found");return}if($o(s.origin)!==$o(this.baseUrl)||typeof s.data=="object"&&s.data.penpal||typeof s.data=="object"&&s.data.source&&s.data.source==="react-devtools-bridge")return;let i=null;try{i=ja(JSON.parse(s.data))}catch{return}if(!this.validateEvent(i))return;const{elementId:l,payload:u}=i,d=u.type;switch(d){case"LAYOUT":this.internalCallbacks.setFormHeight(u.height?`${u.height}px`:"100%");break;case"FOCUS":this.formCallbacks.get.onFocus(l,u.elementType);break;case"BLUR":this.formCallbacks.get.onBlur(l,u.elementType);break;case"CHANGE":this.formCallbacks.get.onChange(l,u.elementType,u.errors);break;case"LOADED":this.eventTargets[l]=s.source,this.internalCallbacks.onCdeLoaded(u);break;case"LOAD_ERROR":this.internalCallbacks.onCdeLoadError(u.message);break;case"VALIDATION_ERROR":this.formCallbacks.get.onValidationError(u.elementType,u.errors,l);break;default:console.warn("[form] Unhandled event type:",d)}},this.validateEvent=s=>s.formId!==this.formId||!s.elementId?(console.log("[OJS] formId",this.formId,s.formId),console.warn("[form] Ignoring unknown event:",s),!1):this.nonces.has(s.nonce)?(console.warn("[form] Ignoring duplicate event:",s),!1):(this.nonces.add(s.nonce),!0),this.eventTargets={},this.nonces=new Set,this.formId=e,this.baseUrl=t,this.formCallbacks=r,this.internalCallbacks=o}}const $o=n=>new URL(n).origin;async function $u(n,e){const r=await vr({iframe:n,debug:!1,childOrigin:e}).promise,o=await ai(r);if(!ii(r,o))throw new Error("Got invalid CDE connection object");return r}class Vu{constructor(){this.connections=new Map}addConnection(e,t){this.connections.set(e,t)}getConnection(){const e=this.connections.values().next().value;if(!e)throw new Error("Connection not found");return e}getAllConnections(){return this.connections}}const Zu=(n,e,t)=>{const{stripePR:r}=n;r.publisher.subscribe(o=>{if(o.isSuccess){const s=o.loadedValue,i=s.isAvailable&&s.availableProviders.applePay,c=s.isAvailable&&s.availableProviders.googlePay,l={apple_pay:{isLoading:!1,isAvailable:i,startFlow:async u=>{i&&Vo("apple_pay",s,e,t,u)}},google_pay:{isLoading:!1,isAvailable:c,startFlow:async u=>{c&&Vo("google_pay",s,e,t,u)}}};t.get.onPaymentRequestLoad(l)}})},Vo=(n,e,t,r,o)=>Z.stripePR.run({context:t,checkoutPaymentMethod:jt(t.checkoutPaymentMethods,n),nonCdeFormInputs:ge(t.formDiv),formCallbacks:r,customParams:{provider:n,overridePaymentRequest:o==null?void 0:o.overridePaymentRequest},initResult:e}),Zo="The secure form failed to load properly. Please check your internet connection, or try again later.",{log__:Ee,err__:fe}=F("op-form"),Ce=class Ce{constructor(e){var o;this.isDestroyed=!1,this.cdeLoadEvent=new Ot,this.anyCdeConn=new Ot,this.context=new Ot,this.initFlows=Cu(),this.startFormInit=async()=>{try{const s=this.createElement(_e.CDE_BRIDGE);s.node.id="__op_internal_cde_bridge",s.node.ariaHidden="true",Object.assign(s.node.style,{border:"none",margin:"0px",padding:"0px",width:"1px",height:"1px",overflow:"hidden",visibility:"hidden",position:"fixed",pointerEvents:"none",userSelect:"none"}),s.mount("body"),Ee("CDE bridge element mounted"),Ee("Initializing OpenPay form:"),Ee("├ Waiting for CDE load event...");const i=await this.cdeLoadEvent.waitForLoad({timeoutSec:120,timeoutErrMsg:Zo});Ee("├ CDE load event received"),Ee("├ Waiting for CDE connection...");const c=await this.anyCdeConn.waitForLoad({timeoutSec:120,timeoutErrMsg:Zo});Ee("├ CDE connection received"),await el(c,this.deviceToken),Ee("├ Creating OJS context, setting up handlers...");const l=Ce.buildOjsFlowContext(this.config,i,c,this.getFormDiv());this.context.set(l),Zu(this.initFlows,l,this.formCallbacks),Ee("├ Starting OJS init flows..."),await ku(this.initFlows,l,this.formCallbacks),this.formCallbacks.get.onLoad(i.totalAmountAtoms,i.currency),Ee("╰ Done initializing OJS flows."),E("form_loaded")}catch(s){const i=re(s);fe("╰ Error initializing OP form:",i),E("form_init_error",{error:i}),this.formCallbacks.get.onLoadError(i)}},this.setFormHeight=s=>{this.formProperties.height=s,this.registeredElements&&Object.values(this.registeredElements).forEach(i=>{!i||i.type===_e.CDE_BRIDGE||(i.node.style.height=s)})},this.onCdeLoaded=s=>{this.cdeLoadEvent.current.isSuccess||(this.cdeLoadEvent.set(s),E("cde_loaded"))},this.onCdeLoadError=s=>{this.cdeLoadEvent.current.isSuccess||(this.cdeLoadEvent.throw(new Error(s),s),E("cde_load_error",{error:s}))},this.createElement=(s,i={})=>{if(this.checkValidFormInstance("createElement"),!this.config)throw new Error("OpenPay form not initialized");const c=Js.parse(s),l=document.createElement("iframe"),u=this.buildQueryString(i);l.name=`${c}-element`;const d=new URL(`/app/v1/${l.name}/`,this.config.baseUrl);return d.search=u.toString(),l.src=d.href,l.style.border="none",l.style.width="100%",this.registerIframe(c,l)},this.registerIframe=(s,i)=>{const c={type:s,node:i,mount:l=>{var u;(u=document.querySelector(l))==null||u.appendChild(i),E("element_mounted",{element_type:s})}};return this.connectToElement({type:c.type,node:c.node}),this.registeredElements||(this.registeredElements={[_e.CARD]:void 0,[_e.CARD_NUMBER]:void 0,[_e.CARD_EXPIRY]:void 0,[_e.CARD_CVC]:void 0,[_e.CDE_BRIDGE]:void 0}),this.registeredElements[s]=c,c},this.buildQueryString=s=>{const i=new URLSearchParams;return i.append("referer",this.referrer),i.append("formId",this.formId),s.styles&&i.append("styles",Oa(s.styles)),i.append("secureToken",this.config.checkoutSecureToken),i},this.connectToElement=s=>{$u(s.node).then(i=>{this.connectionManager.addConnection(s.type,i),!this.anyCdeConn.current.isSuccess&&s.type===_e.CDE_BRIDGE&&this.anyCdeConn.set(i)}).catch(i=>fe("[FORM] Error connecting to CDE iframe",i))},this.getFormDiv=()=>document.querySelector(this.formTarget)??document.body,this.submitCard=s=>{E("submit_card",{...s}),this.checkValidFormInstance("submitCard");const i=this.context.getValueIfLoadedElse(null);if(!i){fe("Please wait for the form to finish loading before submitting.");return}Z.commonCC.run({context:i,checkoutPaymentMethod:jt(i.checkoutPaymentMethods,"credit_card"),nonCdeFormInputs:ge(i.formDiv),formCallbacks:this.formCallbacks,customParams:{currentCdeConnections:this.connectionManager.getAllConnections(),paymentRouteId:s==null?void 0:s.paymentRouteId},initResult:void 0})},this.getAvailablePaymentMethods=()=>{if(this.checkValidFormInstance("getAvailablePaymentMethods"),!this.context.getValueIfLoadedElse(null)){fe("Please wait for the form to finish loading before getting available payment methods.");return}const i={airwallexGooglePay:ne.airwallexGooglePay,airwallexApplePay:ne.airwallexApplePay,authorizeNetGooglePay:ne.authorizenetGooglePay,authorizeNetApplePay:ne.authorizenetApplePay},c=Object.entries(this.initFlows).map(([l,u])=>({name:i[l]??l,...u.publisher.getValueIfLoadedElse(null)}));return E("get_available_payment_methods",{available_payment_methods:c}),c},this.generalSubmit=(s,i)=>{E("general_form_submit",{method:s,settings:i}),this.checkValidFormInstance("generalSubmit");const c=this.context.getValueIfLoadedElse(null);if(!c){fe("Please wait for the form to finish loading before submitting.");return}switch(s){case ne.pockytPaypal:return Z.pockytPaypal.run({context:c,checkoutPaymentMethod:jt(c.checkoutPaymentMethods,"paypal","pockyt"),nonCdeFormInputs:ge(c.formDiv),formCallbacks:this.formCallbacks,customParams:{settings:i},initResult:void 0});case ne.airwallexGooglePay:{const l=this.initFlows.airwallexGooglePay.publisher.getValueIfLoadedElse(null);if(!l){fe("airwallex-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case ne.airwallexApplePay:{const l=this.initFlows.airwallexApplePay.publisher.getValueIfLoadedElse(null);if(!l){fe("airwallex-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case ne.authorizenetGooglePay:{const l=this.initFlows.authorizeNetGooglePay.publisher.getValueIfLoadedElse(null);if(!l){fe("authorize-net-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case ne.authorizenetApplePay:{const l=this.initFlows.authorizeNetApplePay.publisher.getValueIfLoadedElse(null);if(!l){fe("authorize-net-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case ne.loopCrypto:return Z.loopCrypto.run({context:c,checkoutPaymentMethod:jt(c.checkoutPaymentMethods,"crypto","loop"),nonCdeFormInputs:ge(c.formDiv),formCallbacks:this.formCallbacks,customParams:i,initResult:void 0});default:un(s)}},this.submit=this.submitCard,this.destroy=()=>{var s;Ee("Destroying OpenPay form..."),this.checkValidFormInstance("destroy"),this.isDestroyed=!0;for(const i of Object.values(this.registeredElements??{}))i&&i.node.remove();(s=U())==null||s.removeEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),Zc(),this.registeredElements=null,delete window.ojs,E("form_destroyed")},this.updateCallbacks=s=>{this.formCallbacks.setCallbacks(s)},Ce.assignAsSingleton(this),this.ojsVersion="0.2.36",this.ojsReleaseVersion="0.2.36",this.baseUrl=e.baseUrl??"https://cde.getopenpay.com",this.config={...e,baseUrl:this.baseUrl},this.formCallbacks=qn.fromObject(e),this.registeredElements=null,this.formId=`opjs-form-${Xt()}`,this.referrer=window.location.origin,this.formTarget=e.formTarget??"body",this.formProperties={height:"1px"},this.connectionManager=new Vu,this.deviceToken=Mu(),Vc();const{framework:t,version:r}=ju();Jr(this.baseUrl).then(s=>{if(!Vn.current.isSuccess){const i={checkoutSecureToken:this.config.checkoutSecureToken,deviceToken:this.deviceToken,environment:s,framework:t,frameworkVersion:r,ojsVersion:this.ojsVersion,ojsReleaseVersion:this.ojsReleaseVersion,referrer:this.referrer,baseUrl:this.baseUrl};Vn.set(i)}}),E("form_init"),this.eventHandler=new Uu(this.formId,this.baseUrl,this.formCallbacks,{setFormHeight:this.setFormHeight,onCdeLoaded:this.onCdeLoaded,onCdeLoadError:this.onCdeLoadError}),(o=U())==null||o.addEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),this.startFormInit()}get checkoutSecureToken(){return this.config.checkoutSecureToken}checkValidFormInstance(e="unknown"){const t=Ce.getInstance(),r={caller:e,thisFormId:this.formId,currentFormId:(t==null?void 0:t.formId)||"no-current-instance",isDestroyed:this.isDestroyed,checkoutToken:this.config.checkoutSecureToken.substring(0,10)+"..."},o=`
|
|
22
|
+
`;const n=document.createElement("div"),r=n.attachShadow({mode:"open"});r.appendChild(e.content.cloneNode(!0));const o=r.querySelector("#three-ds-iframe"),s=r.querySelector(".cancel-button");return document.body.appendChild(n),{host:n,iframe:o,cancelButton:s}};function ul(t,e,n){const r=async()=>{try{const s=await sl(t,n);s&&(clearInterval(o),e(s))}catch{}};r();const o=setInterval(r,io);return o}function dl({elements:t,pollingInterval:e,resolve:n}){const r=()=>{clearInterval(e),t.host.remove(),n({status:z.CANCELLED})};return t.cancelButton.addEventListener("click",r),()=>{t.cancelButton.removeEventListener("click",r)}}async function hn(t){const{url:e,baseUrl:n}=t,r=yo(e);return new Promise(o=>{const s=l=>{setTimeout(()=>{r.host.remove()},1e3),o(l),c==null||c()},i=ul(r.iframe,s,new URL(n).origin),c=dl({elements:r,pollingInterval:i,resolve:o})})}const _o=async t=>{const e=await hn(t);if(e.status===z.CANCELLED)throw new Error("3DS verification cancelled");if(e.status===z.FAILURE)throw new Error("3DS verification failed");return e.status!==z.SUCCESS&&fn(e.status),{href:e.href}},pl=(t,e)=>{const n=window.open(e,"_blank");if(!n)throw new Error(`${t} popup window blocked. Please allow popups for this site.`);return n},go=async(t,e,n,r)=>{const{err__:o}=D("popup-verify");return new Promise((s,i)=>{const c=pl(t,r),l=setInterval(async()=>{try{const u=await tl(e,n);if(u.present)clearInterval(l),c.close(),s({href:u.href});else if(c.closed)throw new Error(`${t} payment cancelled`)}catch(u){o(re(u)),clearInterval(l),i(re(u))}},1e3)})},{log__:fl,err__:Bn}=D("airwallex-cc"),ml=a.object({"op-airwallex-3ds-url":a.string(),"op-airwallex-initial-intent-id":a.string(),"op-airwallex-consent-id":a.string()}),hl=t=>{const e=ml.safeParse(t);if(!e.success){const n="Unable to process your credit card. Please contact support for assistance.",r=`Airwallex 3DS is required but headers are malformed. Got: ${JSON.stringify(t)}`;throw Bn(r),new Error(n)}return e.data},yl=t=>(t==null?void 0:t["op-airwallex-3ds-url"])!==void 0,_l=t=>{try{const e=new URL(t??"").searchParams.get("payment_intent_id");if(!e)throw new Error("No intent ID found in Airwallex 3DS verification result");return fl(`Airwallex 3DS verification success. [Intent ID: ${e}]`),e}catch(e){const n="Error verifying Airwallex 3DS verification result.";throw Bn(n,`Resulting URL: ${t}.
|
|
23
|
+
Error: ${re(e)}`),new Error(n)}},gl=async(t,e)=>{const n=hl(e),r=await _o({url:n["op-airwallex-3ds-url"],baseUrl:t}),o=_l(r.href??""),s=n["op-airwallex-initial-intent-id"];if(s!==o){const c="Unable to process your credit card. Please contact support for assistance.",l=`Intent ID from callback (${o}) does not match the initial intent ID (${s}).`;throw Bn(l),new Error(c)}return{existing_cc:{initial_intent_id:o,consent_id:n["op-airwallex-consent-id"]}}},vo=a.object({provider:a.literal("apple_pay"),processor_name:a.literal("airwallex"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string()})}),wo=a.object({provider:a.literal("google_pay"),processor_name:a.literal("airwallex"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string(),google_pay_merchant_id:a.string().nullish()})}),{log__:bo,err__:Eo}=D("common-cc"),Re=(t,e,n)=>{if(n){bo(`Received default field values: ${JSON.stringify(n)}`);for(const[o,s]of Object.entries(n))t[o]||(t[o]=s)}const r=xt.safeParse(t);if(!r.success){const o=r.error.format(),s=mr(o);for(const[i,c]of Object.entries(s))e(i,c,i);throw Eo("Got validation errors in non-CDE form fields",s),new Error("Got validation errors in non-CDE form fields")}return r.data},vl=(t,e)=>{for(const n of t)if(n.success===!1)throw n.errors.forEach(r=>{const o=pr.safeParse(r.elementType);if(!o.success)Eo(`Unknown field name in onValidationError: ${r.elementType}. Error object:`,r);else{const s=o.data;e(s,r.errors)}}),bo(`Error tokenizing card: got validation errors: ${JSON.stringify(n.errors)}`),new Error("Got validation errors while tokenizing card")},{log__:yn}=D("awx-apple-pay");async function wl(t,e){try{const r=(await Gn(e.connection,{checkout_payment_method:e.checkoutPaymentMethod,processor_specific_metadata:{airwallex_payment_session:{validation_url:t.validationURL,initiative_context:window.location.hostname,their_account_id:e.processorAccount.processor_account_id}}})).next_action_metadata,o=r==null?void 0:r.apple_pay_session;if(!o)throw new Error("No session data received from payment flow");e.session.completeMerchantValidation(o),E("apple_pay_complete_merchant_validation",{...o})}catch(n){throw e.session.abort(),n}}async function bl(t,e){if(!t.redirect_url)throw new Error("No redirect URL found");yn("3DS Required, starting verification...",t);const{status:n}=await hn({url:t.redirect_url,baseUrl:e.baseUrl});if(yn(`╰ 3DS verification completed [Status: ${n}]`),n===z.CANCELLED)throw new Error("3DS verification cancelled");if(n===z.FAILURE)throw new Error("3DS verification failed");const r=await se(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{their_pm_id:t.their_pm_id,airwallex_consent_id:t.consent_id,payment_provider:e.checkoutPaymentMethod.provider}});return yn("[2nd] Confirm payment flow response",r),r}async function El(t,e){var n,r,o,s,i;try{const c=t.payment,l=po(e.nonCdeFormInputs,c),u=Re(l,e.formCallbacks.get.onValidationError,e.defaultFieldValues);E("billing_details_received",{...u});const m=(await ct(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:u[h.EMAIL],new_customer_first_name:u[h.FIRST_NAME],new_customer_last_name:u[h.LAST_NAME],new_customer_address:{zip_code:u[h.ZIP_CODE],country:u[h.COUNTRY]}})).required_user_actions[0].consent_id;if(!m)throw new Error("No consent ID received from payment flow");let p=await se(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{payment_provider:e.checkoutPaymentMethod.provider,airwallex_consent_id:m,airwallex_payment_method_data:{type:"applepay",applepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:JSON.stringify(c.token)}}}});yn("[1st] Confirm payment flow response",p);let _=(r=(n=p.payment_methods)==null?void 0:n[0])==null?void 0:r.id;const w=(o=p.required_user_actions)==null?void 0:o.find(k=>k.type==="airwallex_payment_consent");if(w!=null&&w.redirect_url&&w.consent_id&&w.their_pm_id&&(p=await bl(w,e),_=(i=(s=p.payment_methods)==null?void 0:s[0])==null?void 0:i.id),!_)throw new Error("No PM ID found");const A={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(A),jt({logPrefix:"awx-applepay",anyCdeConnection:e.connection,checkoutPaymentMethod:e.checkoutPaymentMethod,requiredFormFields:u,confirmResult:p,usePayFirstFlow:!1})}catch(c){const l={status:ApplePaySession.STATUS_FAILURE};throw e.session.completePayment(l),c}}const{log__:Ut,err__:ko}=D("awx-apple-pay"),kl=Ge(async({context:t,formCallbacks:e})=>{const n={processor:de.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ae(t.checkoutPaymentMethods,vo);if(!r)return n;if(Ut("Loading Apple Pay script"),await uo(),!window.ApplePaySession||!ApplePaySession.canMakePayments())return Ut("Apple Pay is not available on this device/browser"),n;if(Ut("Apple Pay Loaded"),!await ApplePaySession.canMakePayments())return Ut("No active cards available for Apple Pay"),n;if(!r.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const i=t.anyCdeConnection,c=await G(i),l=c.mode==="setup",u=await lt(i,c.token,l,void 0),d=async f=>{try{await U.airwallexApplePay.run({context:t,checkoutPaymentMethod:r,nonCdeFormInputs:oe(t.formDiv),formCallbacks:e,customParams:{...f,initialPreview:u},initResult:void 0})}catch(m){ko("Apple Pay payment error",m),e.get.onCheckoutError((m==null?void 0:m.message)??"Unknown error")}};return{processor:de.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),Cl=be(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,customParams:r,formCallbacks:o})=>{var _;const s=ae(t.checkoutPaymentMethods,vo),{overridePaymentRequest:i,initialPreview:c}=r,l=t.anyCdeConnection,u=await G(l),d=u.mode==="setup",f=fo({overridePaymentRequest:i,initialPreview:c,prefill:{...u},defaultLabel:(_=s==null?void 0:s.metadata)==null?void 0:_.processor_account_name}),m=new ApplePaySession(3,f),p={session:m,connection:t.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:n,processorAccount:s.metadata,prefill:u,isSetupMode:d,baseUrl:t.baseUrl,formCallbacks:o,defaultFieldValues:r==null?void 0:r.defaultFieldValues};return E("apple_pay_flow_started",{processor_name:e.processor_name,prefill:eo(u,["brand"]),overridePaymentRequest:i}),new Promise((w,A)=>{const k=()=>{Ut("Payment cancelled by user"),A(new Error("Payment cancelled by user"))};m.oncancel=k,m.onvalidatemerchant=async x=>{try{await wl(x,p)}catch(I){A(I)}},m.onpaymentmethodselected=()=>{const x={newTotal:{...f.total}};m.completePaymentMethodSelection(x)},m.onpaymentauthorized=async x=>{E("apple_pay_payment_authorized");try{const I=await El(x,p);w(I)}catch(I){A(I)}},m.begin()}).catch(w=>{throw ko("Apple Pay payment error",w),E("apple_pay_payment_error",{error:w}),w})}),_n=({gateway:t,gatewayMerchantId:e,merchantName:n,merchantId:r,initialPreview:o,overridePaymentRequest:s,prefill:i})=>{var f,m;const c=((f=s==null?void 0:s.amount)==null?void 0:f.amountAtom)??(o==null?void 0:o.amountAtom)??0,l=Math.max(c/100,0),u=(((m=s==null?void 0:s.amount)==null?void 0:m.currency)??(i==null?void 0:i.currency)??o.currency).toUpperCase(),d={apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:[{type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:["AMEX","DISCOVER","INTERAC","JCB","MASTERCARD","VISA"],billingAddressRequired:!0,billingAddressParameters:{format:"FULL"},allowCreditCards:!0,allowPrepaidCards:!0},tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:t,gatewayMerchantId:e}}}],emailRequired:!0,merchantInfo:{merchantId:r??"",merchantName:n},transactionInfo:{countryCode:"US",currencyCode:u,totalPriceStatus:s!=null&&s.pending?"ESTIMATED":"FINAL",totalPrice:l.toFixed(2)}};return s!=null&&s.googlePayPaymentRequest?typeof s.googlePayPaymentRequest=="function"?{...d,...s.googlePayPaymentRequest(d)}:{...d,...s.googlePayPaymentRequest}:d},Co=()=>lo({scriptId:"__op_internal_google_pay_sdk",src:"https://pay.google.com/gp/p/js/pay.js",checkLoadedFn:()=>{var t,e;return!!((e=(t=window.google)==null?void 0:t.payments)!=null&&e.api)}});let qn=null;const So=async t=>await Xr(t)==="prod"?"PRODUCTION":"TEST",gn=async(t,e)=>{const n=await So(t);return qn===null&&(qn=new window.google.payments.api.PaymentsClient({environment:n,merchantInfo:e.merchantInfo})),qn},Sl=t=>{const e=t.required_user_actions.find(n=>n.type==="airwallex_payment_consent");return e?fr.parse(e):null},Po=(t,e)=>{var o,s,i,c;const n={...t},r=(s=(o=e.paymentMethodData)==null?void 0:o.info)==null?void 0:s.billingAddress;if(r){const[l,...u]=((c=(i=r.name)==null?void 0:i.trim())==null?void 0:c.split(/\s+/))??[],d=u.join(" ")||void 0;n[h.EMAIL]=n[h.EMAIL]||e.email||"op_unfilled@getopenpay.com",n[h.COUNTRY]=n[h.COUNTRY]||r.countryCode||"US",n[h.ADDRESS]=n[h.ADDRESS]||r.address1||"",n[h.CITY]=n[h.CITY]||r.locality||"",n[h.ZIP_CODE]=n[h.ZIP_CODE]||r.postalCode||"00000",n[h.STATE]=n[h.STATE]||r.administrativeArea||"";const f=n[h.FIRST_NAME]||l||"",m=n[h.LAST_NAME]||d||"";f||m?(n[h.FIRST_NAME]=f,n[h.LAST_NAME]=m):(n[h.FIRST_NAME]="_OP_UNKNOWN",n[h.LAST_NAME]="")}return n},{log__:pe,err__:ut}=D("awx-google-pay"),Pl=Ge(async({context:t,formCallbacks:e})=>{var f,m;const n={processor:de.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ae(t.checkoutPaymentMethods,wo);if(!r)return n;pe("Google Pay CPM",r);const o=r.metadata;if(!o.processor_account_id)return ut("No gateway merchant ID found in processor account"),n;if(pe("Loading Google Pay script"),await Co(),!((m=(f=window.google)==null?void 0:f.payments)!=null&&m.api))return ut("Google Pay SDK not loaded properly"),n;if(await So(t.baseUrl)==="PRODUCTION"&&!o.google_pay_merchant_id)return ut("Google Pay merchant ID is required for production environment"),n;pe("Google Pay SDK loaded",window.google.payments);try{const p=_n({gateway:"airwallex",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),_=await gn(t.baseUrl,p),{result:w}=await _.isReadyToPay(p);if(!w)return pe("Google Pay is not available for this user"),n}catch(p){return ut("Error checking Google Pay availability",p),n}const i=t.anyCdeConnection,c=await G(i),l=c.mode==="setup",u=await lt(i,c.token,l,void 0),d=async p=>{try{U.airwallexGooglePay.run({context:t,checkoutPaymentMethod:r,nonCdeFormInputs:oe(t.formDiv),formCallbacks:e,initResult:void 0,customParams:{...p,initialPreview:u}})}catch(_){ut("Google Pay payment error",_),e.get.onCheckoutError((_==null?void 0:_.message)??"Unknown error")}};return{processor:de.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),Al=be(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o})=>{var p,_,w,A,k,x,I;pe("Starting Google Pay flow...");const s=ae(t.checkoutPaymentMethods,wo),{initialPreview:i,overridePaymentRequest:c}=o,l=s.metadata;if(!l.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const u=_n({gateway:"airwallex",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:i,overridePaymentRequest:c}),d=t.anyCdeConnection,f=await G(d);E("google_pay_flow_started",{processor_name:s.processor_name,prefill:eo(f,["brand"]),overridePaymentRequest:c});const m=await gn(t.baseUrl,u);try{const L=await m.loadPaymentData(u);pe("Google Pay Payment data",L);const B=Po(n,L),V=Re(B,r.get.onValidationError,o==null?void 0:o.defaultFieldValues);E("billing_details_received",{...V});const Pe=(_=(p=L.paymentMethodData)==null?void 0:p.tokenizationData)==null?void 0:_.token;if(!Pe)throw new Error("No payment token received from Google Pay");const Wu=await ct(d,{payment_provider:e.provider,checkout_payment_method:e,new_customer_email:V[h.EMAIL],new_customer_first_name:V[h.FIRST_NAME],new_customer_last_name:V[h.LAST_NAME],new_customer_address:{zip_code:V[h.ZIP_CODE],country:V[h.COUNTRY]}}),wn=Sl(Wu);pe("Start flow next actions",wn);let We=await se(d,{secure_token:f.token,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:wn==null?void 0:wn.consent_id,airwallex_payment_method_data:{type:"googlepay",googlepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:Pe}}}});pe("[1st] Confirm payment flow response",We);let Kn=(A=(w=We.payment_methods)==null?void 0:w[0])==null?void 0:A.id;const He=(k=We.required_user_actions)==null?void 0:k.find(Gt=>Gt.type==="airwallex_payment_consent");if(He&&He.redirect_url){pe("3DS Required, starting verification...",He);const{status:Gt}=await hn({url:He.redirect_url,baseUrl:t.baseUrl});if(pe(`╰ 3DS verification completed [Status: ${Gt}]`),Gt===z.CANCELLED)throw new Error("3DS verification cancelled");if(Gt===z.FAILURE)throw new Error("3DS verification failed")}if(He&&!Kn&&(We=await se(d,{secure_token:f.token,their_pm_id:He.their_pm_id,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:He.consent_id}}),pe("[2nd] Confirm payment flow response",We),Kn=(I=(x=We.payment_methods)==null?void 0:x[0])==null?void 0:I.id),!Kn)throw new Error("No PM ID found");return jt({logPrefix:"awx-googlepay",anyCdeConnection:d,checkoutPaymentMethod:e,requiredFormFields:V,confirmResult:We,usePayFirstFlow:!1})}catch(L){throw ut("Google Pay payment error",L),E("google_pay_payment_error",{error:L}),new Error((L==null?void 0:L.message)??"Unknown error")}}),Ao=a.object({provider:a.literal("apple_pay"),processor_name:a.literal("authorize_net"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string()})}),To=a.object({provider:a.literal("google_pay"),processor_name:a.literal("authorize_net"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string(),google_pay_merchant_id:a.string().nullish()})});async function Tl(t,e){try{const r=(await Gn(e.connection,{checkout_payment_method:e.checkoutPaymentMethod,processor_specific_metadata:{apple_payment_session:{validation_url:t.validationURL,initiative_context:window.location.hostname,their_account_id:e.processorAccount.processor_account_id}}})).next_action_metadata,o=r==null?void 0:r.apple_pay_session;if(!o)throw new Error("No session data received from payment flow");e.session.completeMerchantValidation(o),E("apple_pay_complete_merchant_validation",{...o})}catch(n){throw e.session.abort(),n}}async function Il(t,e){var n,r;try{const o=t.payment,s=po(e.nonCdeFormInputs,o),i=Re(s,e.formCallbacks.get.onValidationError);E("billing_details_received",{...i}),await ct(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:i[h.EMAIL],new_customer_first_name:i[h.FIRST_NAME],new_customer_last_name:i[h.LAST_NAME],new_customer_address:{zip_code:i[h.ZIP_CODE],country:i[h.COUNTRY]}});const c={dataDescriptor:"COMMON.APPLE.INAPP.PAYMENT",dataValue:window.btoa(JSON.stringify(o.token.paymentData))},l=await se(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{payment_provider:e.checkoutPaymentMethod.provider,mobile_wallet_payment_data:c}});if(!((r=(n=l.payment_methods)==null?void 0:n[0])==null?void 0:r.id))throw new Error("No PM ID found");const d={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(d),jt({logPrefix:"authnet-applepay",anyCdeConnection:e.connection,checkoutPaymentMethod:e.checkoutPaymentMethod,requiredFormFields:i,confirmResult:l,usePayFirstFlow:!1})}catch(o){const s={status:ApplePaySession.STATUS_FAILURE};throw e.session.completePayment(s),o}}const{log__:vn,err__:Io}=D("authnet-applepay"),xl=Ge(async({context:t,formCallbacks:e})=>{const n={processor:de.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ae(t.checkoutPaymentMethods,Ao);if(!r)return n;if(vn("Loading Apple Pay script"),await uo(),!window.ApplePaySession||!ApplePaySession.canMakePayments())return vn("Apple Pay is not available on this device/browser"),n;if(!await ApplePaySession.canMakePayments())return vn("No active cards available for Apple Pay"),n;if(!r.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const i=t.anyCdeConnection,c=await G(i),l=c.mode==="setup",u=await lt(i,c.token,l,void 0),d=async f=>{try{await U.authorizeNetApplePay.run({context:t,checkoutPaymentMethod:r,nonCdeFormInputs:oe(t.formDiv),formCallbacks:e,customParams:{...f,initialPreview:u},initResult:void 0})}catch(m){Io("Apple Pay payment error",m),E("apple_pay_payment_error",{error:m}),e.get.onCheckoutError((m==null?void 0:m.message)??"Unknown error")}};return{processor:de.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:d}}),Rl=be(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,customParams:r,formCallbacks:o})=>{var _;const{initialPreview:s,overridePaymentRequest:i}=r,c=ae(t.checkoutPaymentMethods,Ao),l=t.anyCdeConnection,u=await G(l),d=u.mode==="setup",f=fo({overridePaymentRequest:i,initialPreview:s,prefill:u,defaultLabel:(_=c==null?void 0:c.metadata)==null?void 0:_.processor_account_name});E("apple_pay_flow_started",{processor_name:e.processor_name,prefill:u,overridePaymentRequest:i});const m=new ApplePaySession(3,f),p={session:m,connection:t.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:n,processorAccount:e.metadata,prefill:u,isSetupMode:d,baseUrl:t.baseUrl,formCallbacks:o};return new Promise((w,A)=>{m.oncancel=()=>{vn("Payment cancelled by user"),A(new Error("Payment cancelled by user"))},m.onvalidatemerchant=async k=>{try{await Tl(k,p)}catch(x){A(x)}},m.onpaymentmethodselected=()=>{const k={newTotal:f.total};m.completePaymentMethodSelection(k)},m.onpaymentauthorized=async k=>{E("apple_pay_payment_authorized");try{const x=await Il(k,p);w(x)}catch(x){A(x)}},m.begin()}).catch(w=>{throw Io("Apple Pay payment error",w),E("apple_pay_payment_error",{error:w}),w})}),{log__:Be,err__:$t}=D("authnet-googlepay"),Nl=Ge(async({context:t,formCallbacks:e})=>{var d,f;Be("Initializing Authnet GooglePay flow");const n={processor:de.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ae(t.checkoutPaymentMethods,To);if(!r)return n;Be("Google Pay CPM",r);const o=r.metadata;if(!o.processor_account_id)return $t("No gateway merchant ID found in processor account"),n;if(Be("Loading Google Pay script"),await Co(),!((f=(d=window.google)==null?void 0:d.payments)!=null&&f.api))return $t("Google Pay SDK not loaded properly"),n;Be("Google Pay SDK loaded",window.google.payments);try{const m=_n({gateway:"authorizenet",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),p=await gn(t.baseUrl,m),{result:_}=await p.isReadyToPay(m);if(!_)return Be("Google Pay is not available for this user"),n}catch(m){return $t("Error checking Google Pay availability",m),n}const s=t.anyCdeConnection,i=await G(s),c=i.mode==="setup",l=await lt(s,i.token,c,void 0),u=async m=>{try{U.authorizeNetGooglePay.run({context:t,checkoutPaymentMethod:r,nonCdeFormInputs:oe(t.formDiv),formCallbacks:e,initResult:void 0,customParams:{...m,initialPreview:l}})}catch(p){$t("Google Pay payment error",p),E("google_pay_payment_error",{error:p}),e.get.onCheckoutError((p==null?void 0:p.message)??"Unknown error")}};return{processor:de.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:u}}),Ol=be(async({context:t,nonCdeFormInputs:e,checkoutPaymentMethod:n,formCallbacks:r,customParams:o})=>{var p,_,w,A;const{initialPreview:s,overridePaymentRequest:i}=o,l=ae(t.checkoutPaymentMethods,To).metadata,u=_n({gateway:"authorizenet",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:s,overridePaymentRequest:i}),d=t.anyCdeConnection,f=await G(d);E("google_pay_flow_started",{processor_name:n.processor_name,prefill:f,overridePaymentRequest:i});const m=await gn(t.baseUrl,u);try{const k=await m.loadPaymentData(u);Be("Google Pay Payment data",k);const x=Po(e,k),I=Re(x,r.get.onValidationError);E("billing_details_received",{...I});const L=(_=(p=k.paymentMethodData)==null?void 0:p.tokenizationData)==null?void 0:_.token;if(!L)throw new Error("No payment token received from Google Pay");const B=await ct(d,{payment_provider:n.provider,checkout_payment_method:n,new_customer_email:I[h.EMAIL],new_customer_first_name:I[h.FIRST_NAME],new_customer_last_name:I[h.LAST_NAME],new_customer_address:{zip_code:I[h.ZIP_CODE],country:I[h.COUNTRY]}});Be("Start payment flow response",B);const V=await se(d,{secure_token:f.token,processor_specific_metadata:{payment_provider:n.provider,mobile_wallet_payment_data:{dataDescriptor:"COMMON.GOOGLE.INAPP.PAYMENT",dataValue:window.btoa(L)}}});if(!((A=(w=V.payment_methods)==null?void 0:w[0])==null?void 0:A.id))throw new Error("No PM ID found");return jt({logPrefix:"authnet-googlepay",anyCdeConnection:d,checkoutPaymentMethod:n,requiredFormFields:I,confirmResult:V,usePayFirstFlow:!1})}catch(k){throw $t("Google Pay payment error",k),E("google_pay_payment_error",{error:k}),new Error((k==null?void 0:k.message)??"Unknown error")}}),{log__:Ml,err__:xo}=D("pockyt-cc"),Dl=a.object({"op-pockyt-3ds-url":a.string(),"op-pockyt-txn-no":a.string(),"op-pockyt-ref-no":a.string()}),Fl=t=>{const e=Dl.safeParse(t);if(!e.success){const n="Unable to process your credit card. Please contact support for assistance.",r=`Pockyt 3DS is required but headers are malformed. Got: ${JSON.stringify(t)}`;throw xo(r),new Error(n)}return e.data},Ro=t=>{try{const e=new URL(t??"").searchParams.get("vaultId");if(!e)throw new Error("No vault ID found in 3DS verification result");return Ml(`3DS verification success. [Vault ID: ${e}]`),e}catch(e){const n="Error verifying 3DS verification result.";throw xo(n,`Resulting URL: ${t}.
|
|
24
|
+
Error: ${re(e)}`),new Error(n)}},Yn=(t,e)=>new URL(t).searchParams.get(e),Ll=t=>(t==null?void 0:t["op-pockyt-3ds-url"])!==void 0,jl=async(t,e)=>{const n=Fl(e),r=await _o({url:n["op-pockyt-3ds-url"],baseUrl:t});return{existing_cc:{vault_id:Ro(r.href??""),transaction_no:n["op-pockyt-txn-no"],reference_no:n["op-pockyt-ref-no"]}}},Ul=a.enum(["test","live","live-us","live-in","live-apse","live-au"]),$l=a.enum(["ar","bg-BG","ca-ES","cs-CZ","da-DK","de-DE","el-GR","en-US","es-ES","et-EE","fi-FI","fr-FR","hr-HR","hu-HU","is-IS","it-IT","ja-JP","ko-KR","lt-LT","lv-LV","nl-NL","no-NO","pl-PL","pt-BR","pt-PT","ro-RO","ru-RU","sk-SK","sl-SI","sv-SE","zh-CN","zh-TW"]),{log__:dt,err__:Vt}=D("adyen-cc"),Vl=a.object({"op-account-id":a.string(),"op-adyen-client-key":a.string(),"op-adyen-environment":Ul,"op-adyen-action":a.string()}),No="Unable to process your credit card. Please contact support for assistance.",Zl=t=>{const e=Vl.safeParse(t);if(!e.success)throw Vt(`Adyen 3DS is required but headers are malformed. Got: ${JSON.stringify(t)}`),new Error(No);return e.data},zl=t=>JSON.parse(t),Oo=()=>"AdyenWeb"in window&&"AdyenCheckout"in window.AdyenWeb,Gl=async()=>{dt("Waiting for Adyen SDK to load...");for(let t=0;t<10;t++)Oo()||await tn(500);if(!Oo())throw Vt("Adyen SDK not loaded properly"),new Error(No);return dt("Adyen SDK loaded successfully"),window.AdyenWeb.AdyenCheckout},Bl=t=>{const{headers:e,locale:n,countryCode:r,component:o,host:s,cancelButton:i}=t,c=zl(e["op-adyen-action"]);return dt(`Running Adyen 3DS flow for action type: ${c.type}`),new Promise(l=>{const u=()=>{dt("Cleaning up Adyen 3DS flow"),i.removeEventListener("click",m),s.remove()},d=_=>{Vt("Authentication failed. Result:",_),l({status:z.FAILURE,cleanup:u})},f=_=>{Vt("Adyen error:",_),l({status:z.FAILURE,cleanup:u})},m=()=>{l({status:z.CANCELLED,cleanup:u})};i.addEventListener("click",m);const p=(_,w,A)=>{s.remove(),l({status:z.SUCCESS,additionalDetails:_,cleanup:u})};Gl().then(_=>_({clientKey:e["op-adyen-client-key"],environment:e["op-adyen-environment"],locale:n,countryCode:r,onAdditionalDetails:p,onPaymentFailed:d,onError:f})).then(_=>{_.createFromAction(c,{challengeWindowSize:"03"}).mount(o)})})},ql=t=>{const e=navigator.languages&&navigator.languages.length?navigator.languages[0]:navigator.language,n=t??e,r=$l.safeParse(n);return r.success?(dt(`Resolved locale: ${r.data}`),r.data):(Vt(`Resolved invalid locale: ${n}. Defaulting to en-US.`),"en-US")},Yl=t=>(t==null?void 0:t["op-adyen-action"])!==void 0,Wl=async(t,e,n)=>{const r=Zl(e),o=document.createElement("div");o.id="adyen-container";const{host:s,iframe:i,cancelButton:c}=yo("http://example.com");i.replaceWith(o);const l=await Bl({headers:r,locale:ql(n),countryCode:t,component:o,host:s,cancelButton:c});if(l.cleanup(),l.status===z.FAILURE)throw new Error("3DS verification failed");if(l.status===z.CANCELLED)throw new Error("3DS verification cancelled");if(l.status===z.SUCCESS){if(!l.additionalDetails)throw new Error("3DS verification succeeded but no additional details were returned");return dt("3DS verification succeeded"),{existing_cc:{additional_details:l.additionalDetails.data}}}else fn(l.status)},{log__:F,err__:Mo}=D("common-cc"),{log__:Do}=D("stripe-cc");a.array(a.object({our_existing_pm_id:a.string()})).length(1);const Hl=be(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o})=>{var u;F("├ Running common CC flow...",{checkoutPaymentMethod:e});const s=t.anyCdeConnection,i=await G(s);E("common_cc_flow_started",{...e,prefill:i}),F(`├ Validating non-CDE form fields [Mode: ${i.mode}]`);const c=Re(n,r.get.onValidationError);E("billing_details_received",{...c});const l={session_id:t.elementsSessionId,checkout_payment_method:e,non_cde_form_fields:c,extra_metadata:{origin:window.location.origin},payment_route_id:o.paymentRouteId};try{F(`├ Tokenizing card info in CDE [Session: ${t.elementsSessionId}]`);const d=await rl(o.currentCdeConnections,{session_id:t.elementsSessionId});if(vl(d,r.get.onValidationError),i.mode==="setup"){F(`├ Setting up payment method in CDE [Token: ${i.token}]`);const f=await ol(s,l);return F(`╰ Setup completed successfully [PM ID: ${f.payment_method_id}]`),{mode:"setup",result:f}}else{F(`├ Initial checkout flow. Checking out card info in CDE [Session: ${t.elementsSessionId}]`);const f=await ao(s,l);return F("╰ Checkout completed successfully."),{mode:"checkout",result:f}}}catch(d){if(d instanceof so&&d.originalErrorMessage.includes("3DS_REQUIRED")){F("├ Card requires 3DS, starting non-legacy payment flow"),F("Received 3DS error response headers:",d.response.headers),E("3ds_required",{...e,...d.response.headers});const f=Ll(d.response.headers);if(f){F("├ Pockyt 3DS case detected. Going through Pockyt 3DS flow.");const k=await jl(t.baseUrl,d.response.headers);l.extra_metadata.pockyt=k}if(yl(d.response.headers)){F("├ Airwallex 3DS case detected. Going through Airwallex 3DS flow.");const k=await gl(t.baseUrl,d.response.headers);l.extra_metadata.airwallex=k}if(Yl(d.response.headers)){F("├ Adyen 3DS case detected. Going through Adyen 3DS flow.");const k=await Wl(n[h.COUNTRY],d.response.headers,i.locale);l.extra_metadata.adyen=k}const _=await Qc(s,l);F("├ Payment flow result:",_);const w=((u=d.response.headers)==null?void 0:u["op-should-use-new-flow"])!=="true";f?F("├ Pre-start 3DS is successful, other 3DS flows will be skipped."):w?(F("├ Using stripe 3DS flow"),await eu(_)):(F("├ Using common 3DS flow"),await Xl(_,t.baseUrl));const A=_.cc_pm_id;if(i.mode==="setup"){F(`├ Confirming payment flow [cc_pm_id: ${A}]`);const k=await se(s,{secure_token:i.token,existing_cc_pm_id:A});F("├ Confirm payment flow result received Result:",k);const x=Lt(k);return F(`╰ Setup completed successfully [PM ID: ${x.payment_method_id}]`),{mode:"setup",result:x}}else{F(`├ Checking out after 3DS flow [Flow: ${w?"legacy":"new"}]`);const k=await ao(s,{...l,existing_cc_pm_id:A,do_not_use_legacy_cc_flow:w});return F("╰ Checkout completed successfully."),{mode:"checkout",result:k}}}throw Mo("╰ Error checking out card info in CDE"),Mo(d),d}}),Kl=t=>{const e=t.required_user_actions.find(n=>n.type==="stripe_3ds");if(!e)throw new Error("No stripe 3DS action found");return Ra.parse(e)},Jl=["airwallex_payment_consent","adyen"],Ql=t=>{const e=t.required_user_actions.find(n=>Jl.includes(n.type));if(!e)throw new Error("No common 3DS action found");return Ta.parse(e)},Xl=async(t,e)=>{const n=Ql(t);if(n.redirect_url==="3DS_COMPLETE"){F("├ 3DS flow completed successfully"),E("3ds_complete");return}F(`├ Using common 3DS flow [URL: ${n.redirect_url}]`),E("3ds_redirect",{...n});const{status:r}=await hn({url:n.redirect_url,baseUrl:e});if(F(`╰ 3DS verification completed [Status: ${r}]`),r===z.CANCELLED)throw E("3ds_cancelled"),new Error("3DS verification cancelled");if(r===z.FAILURE)throw E("3ds_failure"),new Error("3DS verification failed")},eu=async t=>{const e=Kl(t);E("3ds_stripe_redirect",{...e}),Do(`├ Using stripe 3DS flow [Client Secret: ${e.client_secret.substring(0,8)}...]`),await ja(e),E("3ds_stripe_complete"),Do("╰ Stripe 3DS flow completed successfully")},tu=1,nu=a.object({processor_name:a.literal("loop"),provider:a.literal("crypto"),metadata:a.object({merchant_id:a.string(),entity_id:a.string(),api_token:a.string(),supported_currencies:a.array(a.string()),environment:a.string()})}),{log__:te,err__:Fo}=D("loop-crypto"),ru=a.object({loopFirstName:Z,loopLastName:Z,loopEmail:Z,[h.PROMOTION_CODE]:O}),ou=a.object({loopFirstName:O,loopLastName:O,loopEmail:O,[h.PROMOTION_CODE]:O}),Lo=(t,e,n,r)=>{const o=n.safeParse(t);if(!o.success){const s=o.error.format(),i=mr(s);for(const[c,l]of Object.entries(i))e(c,l,c);throw Fo("Got validation errors in non-CDE form fields",i),new Error("Got validation errors in non-CDE form fields")}return o.data},su=Ge(async({context:t})=>{te("Checking if there are any CPMs for Loop Crypto...");const e=ae(t.checkoutPaymentMethods,nu);te(`checkoutPaymentMethod: ${JSON.stringify(e)}`),te("Starting Loop Crypto flow...");const n=await G(t.anyCdeConnection),r=await Gn(t.anyCdeConnection,{checkout_payment_method:e});if(n.mode!=="setup"&&!e.metadata.supported_currencies.includes(n.currency))throw Error(`Currency ${n.currency} not enabled for Loop. Enabled currencies: ${e.metadata.supported_currencies}`);if(!r||!r.next_action_metadata)throw Error("Failed to fetch necessary setup data for Loop");const o=r.next_action_metadata;let s;n.mode==="setup"?s=tu:s=n.amount_total_atom*o.token_price;const i=s,c=o.authorization_amount,l=Rt(),u={paymentUsdAmount:i,suggestedAuthorizationUsdAmount:c,customerRefId:l},d={apiKey:e.metadata.api_token,entityId:e.metadata.entity_id,merchantId:e.metadata.merchant_id,environment:e.metadata.environment};return{isAvailable:!0,widgetProps:u,initLoopConnectProps:d}}),au=be(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o})=>{te("Running Loop flow..."),te("context",t),te("checkoutPaymentMethod",e),te("nonCdeFormInputs",n),te("flowCallbacks",r),te("customParams",o);let s;o!=null&&o.success?s=Lo(n,r.get.onValidationError,ru):s=Lo(n,r.get.onValidationError,ou);const i=t.anyCdeConnection,c=await G(t.anyCdeConnection),l=c.mode!=="setup",u=await ct(t.anyCdeConnection,{checkout_payment_method:e,payment_provider:e.provider,new_customer_email:s.loopEmail,new_customer_first_name:s.loopFirstName,new_customer_last_name:s.loopLastName,use_pay_first_flow:l,pay_first_flow_cart_info:l?{line_items:c.line_items,displayed_total_amount_atom:c.amount_total_atom}:void 0});if(!o)throw Error("Checkout failed. Failed to properly submit form data.");const d=await se(i,{secure_token:c.token,their_pm_id:o.success?o.payin.paymentMethod.paymentMethodId:void 0,checkout_attempt_id:c.mode!=="setup"?u.checkout_attempt_id:void 0,processor_specific_metadata:{loop_customer:o.success?o.customer:void 0,loop_payin:o.success?o.payin:void 0,loop_failure_details:o.success?void 0:o.failureDetails,loop_debug_info:o.success?void 0:o.debugInfo,loop_success:o.success}});if(te(`Confirm result: ${d}`),c.mode==="setup"){te("Doing payment setup..."),te("├ Confirm payment flow result received Result:",d);const f=Lt(d);return te(`╰ Setup completed successfully [PM ID: ${f.payment_method_id}]`),{mode:"setup",result:f}}else{if(te("Doing checkout..."),!d.pay_first_success_response)throw Fo("Checkout failed, no pay-first success response:",d),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:d.pay_first_success_response}}}),{log__:Ee,err__:jo}=D("pockyt-paypal"),iu=a.object({processor_name:a.literal("pockyt"),provider:a.literal("paypal")});a.array(a.object({paypal_iframe_url:a.string(),verify_token:a.string()})).length(1);const cu=be(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o})=>{var V,Pe;Ee("Running Pockyt Paypal flow...");const s=t.anyCdeConnection,i=await G(s);Ee("Verifying CPM...");const c=iu.parse(e);Ee("├ Validating non-CDE form fields");const l=o==null?void 0:o.settings,u=Re(n,r.get.onValidationError,l==null?void 0:l.defaultFieldValues),d=ho(u);Ee(`Starting payment flow... Mode: ${i.mode}`);const f=Rt(),m=i.mode!=="setup",p={payment_provider:c.provider,checkout_payment_method:c,use_pay_first_flow:m,pay_first_flow_cart_info:m?{line_items:i.line_items,displayed_total_amount_atom:i.amount_total_atom}:void 0,processor_specific_metadata:{use_paypal_redirect_flow:!!((V=o==null?void 0:o.settings)!=null&&V.useRedirectFlow),frontend_token_for_redirect_flow:f},...d},_=new URL("/app/pre-action/start/",t.baseUrl).toString(),w=btoa(JSON.stringify(p)),A=new URLSearchParams({st:i.token,r:w}),k=`${_}?${A.toString()}`;if((Pe=o==null?void 0:o.settings)!=null&&Pe.useRedirectFlow)throw Ee("Starting redirect mode for PayPal..."),window.location.href=k,await tn(20*1e3),new Error("Paypal flow timed out, please try again with another payment method.");Ee("Starting popup mode for PayPal..."),Ee("Opening paypal iframe...");const x=await go("PayPal",s,f,k);Ee("Paypal flow result",x);const I=Ro(x.href),L=Yn(x.href,"catt");if(!L)throw jo("Checkout attempt ID not found in redirect URL:",x.href),new Error("Checkout attempt ID not found in redirect URL");Ee(`Confirming payment flow using vault ID ${I}`);const B=await se(s,{secure_token:i.token,their_pm_id:I,checkout_attempt_id:m?L:void 0});if(Ee("Confirm payment flow result",B),i.mode==="setup")return{mode:"setup",result:{payment_method_id:B.payment_methods[0].id}};if(!B.pay_first_success_response)throw jo("Checkout failed, no pay-first success response:",B),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:B.pay_first_success_response}}),Uo="ojs-stripe-link-btn",{log__:H,err__:lu}=D("stripe-link"),uu=a.object({provider:a.literal("stripe_link"),processor_name:a.literal("stripe"),metadata:a.object({stripe_pk:a.string()})}),du=a.array(a.object({our_existing_pm_id:a.string()})).length(1),pu=Ge(async({context:t,formCallbacks:e})=>{const n=t.customInitParams.stripeLink;H("Checking if there are any CPMs for Stripe Link...");const r=ae(t.checkoutPaymentMethods,uu);H("Starting stripe link flow...");const o=t.anyCdeConnection,s=await G(o),i=s.mode==="setup";H("Creating stripe elements...");const c=await lt(o,s.token,i,void 0),{elements:l,stripe:u}=await Ma(r.metadata.stripe_pk,{mode:"setup",currency:c.currency,setup_future_usage:"off_session",paymentMethodCreation:"manual"});H("Creating express checkout...");const d=l.create("expressCheckout",{buttonHeight:n==null?void 0:n.buttonHeight,paymentMethods:{amazonPay:"never",applePay:"never",googlePay:"never",paypal:"never"}}),f=()=>{d.mount(`#${Uo}`)},m=()=>{d.unmount()};return n!=null&&n.doNotMountOnInit?H("NOT mounting stripe link button (doNotMountOnInit is true)"):(H("Mounting stripe link button..."),f()),d.on("click",async p=>{if(H("Stripe Link button clicked"),n!=null&&n.overrideLinkSubmit&&!await n.overrideLinkSubmit()){H("Stripe Link submit aborted by overrideLinkSubmit");return}p.resolve()}),d.on("confirm",async p=>{H("Stripe Link window confirmed",p);const _=await u.createPaymentMethod({elements:l,params:{billing_details:p.billingDetails}});_.error?(lu("error",_.error),e.get.onCheckoutError(_.error.message??"Stripe Link unknown error")):(H("paymentMethod",_.paymentMethod),U.stripeLink.run({context:t,checkoutPaymentMethod:r,nonCdeFormInputs:oe(t.formDiv),formCallbacks:e,customParams:{stripePM:_.paymentMethod},initResult:{isAvailable:!0}}))}),{isAvailable:!0,controller:{mountButton:f,dismountButton:m,waitForButtonToMount:async()=>await hu(Uo)}}}),fu=be(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o})=>{H("Running Stripe Link flow...");const s=t.anyCdeConnection;H("Merging PM fields with form fields...");const i=mu(n,o.stripePM),c=Re(i,r.get.onValidationError);E("billing_details_received",{...c}),H("Starting payment flow...");const l=await ct(s,{payment_provider:e.provider,checkout_payment_method:e,their_existing_pm_id:o.stripePM.id,new_customer_email:c[h.EMAIL],new_customer_first_name:c[h.FIRST_NAME],new_customer_last_name:c[h.LAST_NAME],new_customer_address:{zip_code:c[h.ZIP_CODE],country:c[h.COUNTRY]}});H("Start payment flow response",l);const d=du.parse(l.required_user_actions)[0].our_existing_pm_id,f=await G(s);if(f.mode==="setup"){H("Doing payment setup...");const m=await se(s,{secure_token:f.token,existing_cc_pm_id:d});return{mode:"setup",result:Lt(m)}}else{H("Doing checkout...");const m={secure_token:f.token,payment_input:{provider_type:e.provider},customer_email:c[h.EMAIL],customer_zip_code:c[h.ZIP_CODE],customer_country:c[h.COUNTRY],promotion_code:c[h.PROMOTION_CODE],line_items:f.line_items,total_amount_atom:f.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await zn(s,m)}}}),mu=(t,e)=>{var l,u,d,f,m;const n={...t},[r,...o]=((u=(l=e.billing_details.name)==null?void 0:l.trim())==null?void 0:u.split(/\s+/))??[],s=o.join(" ")||void 0;n[h.EMAIL]=n[h.EMAIL]||((d=e.link)==null?void 0:d.email)||e.billing_details.email||"op_unfilled@getopenpay.com",n[h.ZIP_CODE]=n[h.ZIP_CODE]||((f=e.billing_details.address)==null?void 0:f.postal_code)||"00000",n[h.COUNTRY]=n[h.COUNTRY]||((m=e.billing_details.address)==null?void 0:m.country)||"US";const i=n[h.FIRST_NAME]||r||"",c=n[h.LAST_NAME]||s||"";return i||c?(n[h.FIRST_NAME]=i,n[h.LAST_NAME]=c):(n[h.FIRST_NAME]="_OP_UNKNOWN",n[h.LAST_NAME]=""),H("Final form inputs:",n),n},hu=t=>new Promise(e=>{const n=()=>{const r=document.getElementById(t);r?e(r):requestAnimationFrame(n)};n()}),{log__:ee,err__:yu}=D("stripe-pr"),_u=a.object({provider:a.union([a.literal("apple_pay"),a.literal("google_pay")]),processor_name:a.literal("stripe"),metadata:a.object({stripe_pk:a.string()})}),gu=Ge(async({context:t,formCallbacks:e})=>{ee("Checking if there are any CPMs for Stripe PR...");const n=ae(t.checkoutPaymentMethods,_u);ee("Initializing Stripe PR flow...");const r=t.anyCdeConnection,o=await G(r),s=o.mode==="setup";ee("Getting initial preview amount");const i=await lt(r,o.token,s,void 0),c=await Da(n.metadata.stripe_pk,i.amountAtom,i.currency,s);ee("Checking if can make payment");const l=await c.canMakePayment();if(l===null)return yu("canMakePayment returned null"),{isAvailable:!1,reason:"canMakePayment returned null"};ee("Stripe PR flow initialized successfully. Can make payment",l);const u=(d,f)=>U.stripePR.run({context:t,checkoutPaymentMethod:pt(t.checkoutPaymentMethods,d),nonCdeFormInputs:oe(t.formDiv),formCallbacks:e,customParams:{provider:d,overridePaymentRequest:f==null?void 0:f.overridePaymentRequest},initResult:{processor:de.Enum.stripe,pr:c,isAvailable:!0,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}});return{processor:de.Enum.stripe,isAvailable:!0,pr:c,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}}),vu=be(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o,initResult:s})=>{if(ee("Running Stripe PR flow..."),o.provider!==e.provider)throw new Error(`Provider mismatch. Expected ${o.provider}, got ${e.provider}`);const i=t.anyCdeConnection,c=s.pr;if(o!=null&&o.overridePaymentRequest){const _=o.overridePaymentRequest;ee("Overriding PR amount with",_);const w=typeof _.applePayPaymentRequest=="function"?_.applePayPaymentRequest({}):_.applePayPaymentRequest;bu(c,_.amount,_.pending,w,_.label)}ee("Showing PR dialog..."),c.show();const l=await Fa(c);ee("Stripe PM added event:",l),ee("Merging PM fields with form fields...");const u=wu(n,l),d=Re(u,r.get.onValidationError);E("billing_details_received",{...d}),ee("PR dialog finished. Starting payment flow...",d);const f=await Xc(i,{fields:d,checkoutPaymentMethod:e}),m=Eu(f);ee("Confirming PR with Stripe..."),await La(m,l);const p=await G(i);if(p.mode==="setup"){ee("Confirming payment flow for setup...");const _=await se(i,{secure_token:p.token});return{mode:"setup",result:Lt(_)}}else{ee("Performing checkout...");const _={secure_token:p.token,payment_input:{provider_type:e.provider},customer_first_name:d[h.FIRST_NAME],customer_last_name:d[h.LAST_NAME],customer_email:d[h.EMAIL],customer_zip_code:d[h.ZIP_CODE],customer_country:d[h.COUNTRY],promotion_code:d[h.PROMOTION_CODE],line_items:p.line_items,total_amount_atom:p.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await zn(i,_)}}}),wu=(t,e)=>{var d,f,m,p;const n={...t},[r,...o]=((f=(d=e.payerName)==null?void 0:d.trim())==null?void 0:f.split(/\s+/))??[],s=o.join(" ")||void 0,i=(p=(m=e.paymentMethod)==null?void 0:m.billing_details)==null?void 0:p.address,c=e.shippingAddress;n[h.EMAIL]=n[h.EMAIL]||e.payerEmail||"op_unfilled@getopenpay.com",n[h.ZIP_CODE]=n[h.ZIP_CODE]||(i==null?void 0:i.postal_code)||(c==null?void 0:c.postalCode)||"00000",n[h.COUNTRY]=n[h.COUNTRY]||(i==null?void 0:i.country)||(c==null?void 0:c.country)||"US";const l=n[h.FIRST_NAME]||r||"",u=n[h.LAST_NAME]||s||"";return l||u?(n[h.FIRST_NAME]=l,n[h.LAST_NAME]=u):(n[h.FIRST_NAME]="_OP_UNKNOWN",n[h.LAST_NAME]=""),ee("Final form inputs:",n),n},bu=(t,e,n,r,o)=>{t.update({total:{amount:e.amountAtom,label:o??"Total",pending:n},currency:e.currency,applePay:r})},Eu=t=>{if(t.required_user_actions.length!==1)throw new Error(`Error occurred.
|
|
25
|
+
Details: got ${t.required_user_actions.length} required user actions`);return Na.parse(t.required_user_actions[0])},{log__:qe,err__:ku}=D("paypal"),$o=a.object({provider:a.literal("paypal"),metadata:a.object({client_id:a.string()}),processor_name:a.literal("paypal")}),Cu=async({context:t,formCallbacks:e})=>{const n=ae(t.checkoutPaymentMethods,$o);if(!n)throw new Error("PayPal CPM not found in available payment methods");return{isLoading:!1,isAvailable:!0,startFlow:()=>U.paypal.run({context:t,checkoutPaymentMethod:n,nonCdeFormInputs:oe(t.formDiv),formCallbacks:e,initResult:void 0,customParams:{}})}},Su=be(async({context:t,nonCdeFormInputs:e,checkoutPaymentMethod:n,formCallbacks:r,customParams:o})=>{var s;try{qe("Running PayPal flow...");const i=t.anyCdeConnection,c=await G(i),l=((s=o==null?void 0:o.settings)==null?void 0:s.useRedirectFlow)??!1;qe("Verifying CPM...");const u=$o.parse(n);qe("├ Validating non-CDE form fields");const d=Re(e,r.get.onValidationError),f=ho(d);qe(`Starting payment flow... Mode: ${c.mode}`);const m=Rt(),p=c.mode!=="setup",_={payment_provider:u.provider,checkout_payment_method:u,use_pay_first_flow:p,pay_first_flow_cart_info:p?{line_items:c.line_items,displayed_total_amount_atom:c.amount_total_atom}:void 0,processor_specific_metadata:{use_paypal_redirect_flow:l,frontend_token_for_redirect_flow:m},...f},w=new URL("/app/pre-action/start/",t.baseUrl).toString(),A=btoa(JSON.stringify(_)),k=new URLSearchParams({st:c.token,r:A}),x=`${w}?${k.toString()}`;if(l)throw qe("Starting redirect mode for PayPal..."),window.location.href=x,await tn(20*1e3),new Error("Paypal flow timed out, please try again with another payment method.");const I=await go("PayPal",i,m,x);qe("Paypal flow result",I);const L=Yn(I.href,"catt"),B=Yn(I.href,"approval_session_id"),V=await se(i,{secure_token:c.token,checkout_attempt_id:p?L:void 0,their_pm_id:p?B:void 0});return qe("Confirm payment flow result",V),jt({logPrefix:"paypal",anyCdeConnection:i,checkoutPaymentMethod:u,requiredFormFields:d,confirmResult:V,usePayFirstFlow:p})}catch(i){throw ku("PayPal payment error",i),E("checkout_error",{payment_method:"paypal",error:i}),new Error((i==null?void 0:i.message)??"Unknown error")}}),pt=(t,e,n)=>{const r=t.filter(o=>{const s=n===void 0?!0:o.processor_name===n,i=o.provider===e;return s&&i});if(r.length===0)throw console.warn("CPMs list",t),new Error(`No CPMs found with provider '${e}' and processor '${n}'`);return r.length!==1&&(console.warn("CPMs list",t),console.warn(`More than one CPM found with provider '${e}' and processor '${n}'`),E("more_than_one_cpm_found",{provider:e,processor:n,cpms:t})),r[0]},U={commonCC:{init:async()=>{},run:Hl},stripePR:{init:gu,run:vu},stripeLink:{init:pu,run:fu},pockytPaypal:{run:cu},paypal:{init:Cu,run:Su},airwallexGooglePay:{init:Pl,run:Al},airwallexApplePay:{init:kl,run:Cl},loopCrypto:{init:su,run:au},authorizeNetApplePay:{init:xl,run:Rl},authorizeNetGooglePay:{init:Nl,run:Ol}},{log__:Pu,err__:Au}=D("init-flows"),Ue=(t,e)=>{const n=new Ft;return{publisher:n,initialize:async r=>{try{if(n.current.isSuccess)throw new Error("This flow has already been initialized.");const o=await e(r);Pu(`✔ ${t} flow initialized successfully. Result:`,o),n.set(o)}catch(o){Au(`𝙭 ${t} flow initialization failed. Error:`,re(o),"Details:",o),n.throw(o,re(o))}}}},Tu=async(t,e,n)=>{await Promise.all(Object.values(t).map(r=>r.initialize({context:e,formCallbacks:n})))},Iu=()=>({stripePR:Ue("Stripe PR",U.stripePR.init),stripeLink:Ue("Stripe Link",U.stripeLink.init),airwallexGooglePay:Ue("Airwallex GooglePay",U.airwallexGooglePay.init),airwallexApplePay:Ue("Airwallex ApplePay",U.airwallexApplePay.init),loop:Ue("Loop",U.loopCrypto.init),paypal:Ue("PayPal",U.paypal.init),authorizeNetGooglePay:Ue("Authnet GooglePay",U.authorizeNetGooglePay.init),authorizeNetApplePay:Ue("Authnet ApplePay",U.authorizeNetApplePay.init)}),{err__:xu}=D("form-callbacks"),fe=a.function().optional(),Vo=a.object({onFocus:fe,onBlur:fe,onChange:fe,onLoad:fe,onLoadError:fe,onValidationError:fe,onCheckoutStarted:fe,onCheckoutSuccess:fe,onSetupPaymentMethodSuccess:fe,onCheckoutError:fe,onPaymentRequestLoad:fe}),Ce=class Ce{constructor(){this.setCallbacks=e=>{this._callbacks=Ce.createEmptyCallbacks(),Object.entries(e).forEach(([n,r])=>{const o=ta(n,r??Ce.NOOP,xu);this._callbacks[n]=o})},this._callbacks=Ce.createEmptyCallbacks()}get get(){return{...this._callbacks}}};Ce.NOOP=()=>{},Ce.createEmptyCallbacks=()=>{const e={};return Object.keys(Vo.keyof().enum).forEach(n=>{e[n]=Ce.NOOP}),e},Ce.fromObject=e=>{const n=new Ce;return n.setCallbacks(Vo.parse(e)),n};let Wn=Ce;const Zo="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Zt=32,Ru=16,zo=10,Go=0xffffffffffff;var Ye;(function(t){t.Base32IncorrectEncoding="B32_ENC_INVALID",t.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",t.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",t.EncodeTimeNegative="ENC_TIME_NEG",t.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",t.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",t.PRNGDetectFailure="PRNG_DETECT",t.ULIDInvalid="ULID_INVALID",t.Unexpected="UNEXPECTED",t.UUIDInvalid="UUID_INVALID"})(Ye||(Ye={}));class zt extends Error{constructor(e,n){super(`${n} (${e})`),this.name="ULIDError",this.code=e}}function Nu(t){let e=Math.floor(t()*Zt);return e===Zt&&(e=Zt-1),Zo.charAt(e)}function Ou(t){const e=Mu(),n=e&&(e.crypto||e.msCrypto)||null;if(typeof(n==null?void 0:n.getRandomValues)=="function")return()=>{const r=new Uint8Array(1);return n.getRandomValues(r),r[0]/255};if(typeof(n==null?void 0:n.randomBytes)=="function")return()=>n.randomBytes(1).readUInt8()/255;throw new zt(Ye.PRNGDetectFailure,"Failed to find a reliable PRNG")}function Mu(){return Lu()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function Du(t,e){let n="";for(;t>0;t--)n=Nu(e)+n;return n}function Fu(t,e=zo){if(isNaN(t))throw new zt(Ye.EncodeTimeValueMalformed,`Time must be a number: ${t}`);if(t>Go)throw new zt(Ye.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${Go}: ${t}`);if(t<0)throw new zt(Ye.EncodeTimeNegative,`Time must be positive: ${t}`);if(Number.isInteger(t)===!1)throw new zt(Ye.EncodeTimeValueMalformed,`Time must be an integer: ${t}`);let n,r="";for(let o=e;o>0;o--)n=t%Zt,r=Zo.charAt(n)+r,t=(t-n)/Zt;return r}function Lu(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function ju(t,e){const n=Ou(),r=Date.now();return Fu(r,zo)+Du(Ru,n)}const Bo="op_analytics_device_token",Uu=()=>{const t=document.cookie.split(";").find(n=>n.includes(Bo));if(t)return t.split("=")[1];const e=ju();return $u(e),e},$u=t=>{const e=new Date;e.setFullYear(e.getFullYear()+1),document.cookie=`${Bo}=${t}; path=/; expires=${e.toUTCString()}`};function Vu(){try{const t=$();if(t!=null&&t.next||t!=null&&t.__NEXT_DATA__||document.querySelector("#__next"))return"nextjs";const e=$();if(e!=null&&e.__NUXT__||document.querySelector("#__nuxt"))return"nuxt";if(Object.keys(document).find(r=>r.includes("react"))||Array.from(document.body.querySelectorAll("body > *")).find(r=>r._reactRootContainer))return"react";const n=$();return n!=null&&n.Vue||n!=null&&n.__VUE__?"vue":document.querySelector("[ng-version]")?"angular":"vanilla"}catch{return"unknown"}}function Zu(t){var e,n,r;try{switch(t){case"react":return null;case"nextjs":{const o=$();return((e=o==null?void 0:o.next)==null?void 0:e.version)||((n=o==null?void 0:o.__NEXT_DATA__)==null?void 0:n.buildId)||null}case"nuxt":return null;case"vue":return null;case"angular":{const o=(r=$())==null?void 0:r.document,s=o==null?void 0:o.querySelector("[ng-version]");return s?s.getAttribute("ng-version"):null}default:return null}}catch{return null}}function zu(){const t=Vu(),e=Zu(t);return{framework:t,version:e}}class Gu{constructor(e,n,r,o){this.handleMessage=s=>{if(!s.source){console.warn("[OJS] No source found");return}if(qo(s.origin)!==qo(this.baseUrl)||typeof s.data=="object"&&s.data.penpal||typeof s.data=="object"&&s.data.source&&s.data.source==="react-devtools-bridge")return;let i=null;try{i=Ga(JSON.parse(s.data))}catch{return}if(!this.validateEvent(i))return;const{elementId:l,payload:u}=i,d=u.type;switch(d){case"LAYOUT":this.internalCallbacks.setFormHeight(u.height?`${u.height}px`:"100%");break;case"FOCUS":this.formCallbacks.get.onFocus(l,u.elementType);break;case"BLUR":this.formCallbacks.get.onBlur(l,u.elementType);break;case"CHANGE":this.formCallbacks.get.onChange(l,u.elementType,u.errors);break;case"LOADED":this.eventTargets[l]=s.source,this.internalCallbacks.onCdeLoaded(u);break;case"LOAD_ERROR":this.internalCallbacks.onCdeLoadError(u.message);break;case"VALIDATION_ERROR":this.formCallbacks.get.onValidationError(u.elementType,u.errors,l);break;default:console.warn("[form] Unhandled event type:",d)}},this.validateEvent=s=>s.formId!==this.formId||!s.elementId?(console.log("[OJS] formId",this.formId,s.formId),console.warn("[form] Ignoring unknown event:",s),!1):this.nonces.has(s.nonce)?(console.warn("[form] Ignoring duplicate event:",s),!1):(this.nonces.add(s.nonce),!0),this.eventTargets={},this.nonces=new Set,this.formId=e,this.baseUrl=n,this.formCallbacks=r,this.internalCallbacks=o}}const qo=t=>new URL(t).origin;async function Bu(t,e){const r=await br({iframe:t,debug:!1,childOrigin:e}).promise,o=await pi(r);if(!fi(r,o))throw new Error("Got invalid CDE connection object");return r}class qu{constructor(){this.connections=new Map}addConnection(e,n){this.connections.set(e,n)}getConnection(){const e=this.connections.values().next().value;if(!e)throw new Error("Connection not found");return e}getAllConnections(){return this.connections}}const Yu=(t,e,n)=>{const{stripePR:r}=t;r.publisher.subscribe(o=>{if(o.isSuccess){const s=o.loadedValue,i=s.isAvailable&&s.availableProviders.applePay,c=s.isAvailable&&s.availableProviders.googlePay,l={apple_pay:{isLoading:!1,isAvailable:i,startFlow:async u=>{i&&Yo("apple_pay",s,e,n,u)}},google_pay:{isLoading:!1,isAvailable:c,startFlow:async u=>{c&&Yo("google_pay",s,e,n,u)}}};n.get.onPaymentRequestLoad(l)}})},Yo=(t,e,n,r,o)=>U.stripePR.run({context:n,checkoutPaymentMethod:pt(n.checkoutPaymentMethods,t),nonCdeFormInputs:oe(n.formDiv),formCallbacks:r,customParams:{provider:t,overridePaymentRequest:o==null?void 0:o.overridePaymentRequest},initResult:e}),Wo="The secure form failed to load properly. Please check your internet connection, or try again later.",{log__:ke,err__:me}=D("op-form"),Se=class Se{constructor(e){var o;this.isDestroyed=!1,this.cdeLoadEvent=new Ft,this.anyCdeConn=new Ft,this.context=new Ft,this.initFlows=Iu(),this.startFormInit=async()=>{try{const s=this.createElement(ge.CDE_BRIDGE);s.node.id="__op_internal_cde_bridge",s.node.ariaHidden="true",Object.assign(s.node.style,{border:"none",margin:"0px",padding:"0px",width:"1px",height:"1px",overflow:"hidden",visibility:"hidden",position:"fixed",pointerEvents:"none",userSelect:"none"}),s.mount("body"),ke("CDE bridge element mounted"),ke("Initializing OpenPay form:"),ke("├ Waiting for CDE load event...");const i=await this.cdeLoadEvent.waitForLoad({timeoutSec:120,timeoutErrMsg:Wo});ke("├ CDE load event received"),ke("├ Waiting for CDE connection...");const c=await this.anyCdeConn.waitForLoad({timeoutSec:120,timeoutErrMsg:Wo});ke("├ CDE connection received"),await al(c,this.deviceToken),ke("├ Creating OJS context, setting up handlers...");const l=Se.buildOjsFlowContext(this.config,i,c,this.getFormDiv());this.context.set(l),Yu(this.initFlows,l,this.formCallbacks),ke("├ Starting OJS init flows..."),await Tu(this.initFlows,l,this.formCallbacks),this.formCallbacks.get.onLoad(i.totalAmountAtoms,i.currency),ke("╰ Done initializing OJS flows."),E("form_loaded")}catch(s){const i=re(s);me("╰ Error initializing OP form:",i),E("form_init_error",{error:i}),this.formCallbacks.get.onLoadError(i)}},this.setFormHeight=s=>{this.formProperties.height=s,this.registeredElements&&Object.values(this.registeredElements).forEach(i=>{!i||i.type===ge.CDE_BRIDGE||(i.node.style.height=s)})},this.onCdeLoaded=s=>{this.cdeLoadEvent.current.isSuccess||(this.cdeLoadEvent.set(s),E("cde_loaded"))},this.onCdeLoadError=s=>{this.cdeLoadEvent.current.isSuccess||(this.cdeLoadEvent.throw(new Error(s),s),E("cde_load_error",{error:s}))},this.createElement=(s,i={})=>{if(this.checkValidFormInstance("createElement"),!this.config)throw new Error("OpenPay form not initialized");const c=ra.parse(s),l=document.createElement("iframe"),u=this.buildQueryString(i);l.name=`${c}-element`;const d=new URL(`/app/v1/${l.name}/`,this.config.baseUrl);return d.search=u.toString(),l.src=d.href,l.style.border="none",l.style.width="100%",this.registerIframe(c,l)},this.registerIframe=(s,i)=>{const c={type:s,node:i,mount:l=>{var u;(u=document.querySelector(l))==null||u.appendChild(i),E("element_mounted",{element_type:s})}};return this.connectToElement({type:c.type,node:c.node}),this.registeredElements||(this.registeredElements={[ge.CARD]:void 0,[ge.CARD_NUMBER]:void 0,[ge.CARD_EXPIRY]:void 0,[ge.CARD_CVC]:void 0,[ge.CDE_BRIDGE]:void 0}),this.registeredElements[s]=c,c},this.buildQueryString=s=>{const i=new URLSearchParams;return i.append("referer",this.referrer),i.append("formId",this.formId),s.styles&&i.append("styles",Ua(s.styles)),i.append("secureToken",this.config.checkoutSecureToken),i},this.connectToElement=s=>{Bu(s.node).then(i=>{this.connectionManager.addConnection(s.type,i),!this.anyCdeConn.current.isSuccess&&s.type===ge.CDE_BRIDGE&&this.anyCdeConn.set(i)}).catch(i=>me("[FORM] Error connecting to CDE iframe",i))},this.getFormDiv=()=>document.querySelector(this.formTarget)??document.body,this.submitCard=s=>{E("submit_card",{...s}),this.checkValidFormInstance("submitCard");const i=this.context.getValueIfLoadedElse(null);if(!i){me("Please wait for the form to finish loading before submitting.");return}U.commonCC.run({context:i,checkoutPaymentMethod:pt(i.checkoutPaymentMethods,"credit_card"),nonCdeFormInputs:oe(i.formDiv),formCallbacks:this.formCallbacks,customParams:{currentCdeConnections:this.connectionManager.getAllConnections(),paymentRouteId:s==null?void 0:s.paymentRouteId},initResult:void 0})},this.getAvailablePaymentMethods=()=>{if(this.checkValidFormInstance("getAvailablePaymentMethods"),!this.context.getValueIfLoadedElse(null)){me("Please wait for the form to finish loading before getting available payment methods.");return}const i={paypal:X.paypal,airwallexGooglePay:X.airwallexGooglePay,airwallexApplePay:X.airwallexApplePay,authorizeNetGooglePay:X.authorizenetGooglePay,authorizeNetApplePay:X.authorizenetApplePay},c=Object.entries(this.initFlows).map(([l,u])=>({name:i[l]??l,...u.publisher.getValueIfLoadedElse(null)}));return E("get_available_payment_methods",{available_payment_methods:c}),c},this.generalSubmit=(s,i)=>{E("general_form_submit",{method:s,settings:i}),this.checkValidFormInstance("generalSubmit");const c=this.context.getValueIfLoadedElse(null);if(!c){me("Please wait for the form to finish loading before submitting.");return}switch(s){case X.pockytPaypal:return U.pockytPaypal.run({context:c,checkoutPaymentMethod:pt(c.checkoutPaymentMethods,"paypal","pockyt"),nonCdeFormInputs:oe(c.formDiv),formCallbacks:this.formCallbacks,customParams:{settings:i},initResult:void 0});case X.paypal:return U.paypal.run({context:c,checkoutPaymentMethod:pt(c.checkoutPaymentMethods,"paypal","paypal"),nonCdeFormInputs:oe(c.formDiv),initResult:void 0,customParams:{settings:i},formCallbacks:this.formCallbacks});case X.airwallexGooglePay:{const l=this.initFlows.airwallexGooglePay.publisher.getValueIfLoadedElse(null);if(!l){me("airwallex-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case X.airwallexApplePay:{const l=this.initFlows.airwallexApplePay.publisher.getValueIfLoadedElse(null);if(!l){me("airwallex-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case X.authorizenetGooglePay:{const l=this.initFlows.authorizeNetGooglePay.publisher.getValueIfLoadedElse(null);if(!l){me("authorize-net-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case X.authorizenetApplePay:{const l=this.initFlows.authorizeNetApplePay.publisher.getValueIfLoadedElse(null);if(!l){me("authorize-net-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case X.loopCrypto:return U.loopCrypto.run({context:c,checkoutPaymentMethod:pt(c.checkoutPaymentMethods,"crypto","loop"),nonCdeFormInputs:oe(c.formDiv),formCallbacks:this.formCallbacks,customParams:i,initResult:void 0});default:fn(s)}},this.submit=this.submitCard,this.destroy=()=>{var s;ke("Destroying OpenPay form..."),this.checkValidFormInstance("destroy"),this.isDestroyed=!0;for(const i of Object.values(this.registeredElements??{}))i&&i.node.remove();(s=$())==null||s.removeEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),Wc(),this.registeredElements=null,delete window.ojs,E("form_destroyed")},this.updateCallbacks=s=>{this.formCallbacks.setCallbacks(s)},Se.assignAsSingleton(this),this.ojsVersion="0.3.0",this.ojsReleaseVersion="0.3.0",this.baseUrl=e.baseUrl??"https://cde.getopenpay.com",this.config={...e,baseUrl:this.baseUrl},this.formCallbacks=Wn.fromObject(e),this.registeredElements=null,this.formId=`opjs-form-${Rt()}`,this.referrer=window.location.origin,this.formTarget=e.formTarget??"body",this.formProperties={height:"1px"},this.connectionManager=new qu,this.deviceToken=Uu(),Yc();const{framework:n,version:r}=zu();Xr(this.baseUrl).then(s=>{if(!Zn.current.isSuccess){const i={checkoutSecureToken:this.config.checkoutSecureToken,deviceToken:this.deviceToken,environment:s,framework:n,frameworkVersion:r,ojsVersion:this.ojsVersion,ojsReleaseVersion:this.ojsReleaseVersion,referrer:this.referrer,baseUrl:this.baseUrl};Zn.set(i)}}),E("form_init"),this.eventHandler=new Gu(this.formId,this.baseUrl,this.formCallbacks,{setFormHeight:this.setFormHeight,onCdeLoaded:this.onCdeLoaded,onCdeLoadError:this.onCdeLoadError}),(o=$())==null||o.addEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),this.startFormInit()}get checkoutSecureToken(){return this.config.checkoutSecureToken}checkValidFormInstance(e="unknown"){const n=Se.getInstance(),r={caller:e,thisFormId:this.formId,currentFormId:(n==null?void 0:n.formId)||"no-current-instance",isDestroyed:this.isDestroyed,checkoutToken:this.config.checkoutSecureToken.substring(0,10)+"..."},o=`
|
|
26
26
|
[Warning] Invalid form instance detected.
|
|
27
27
|
It looks like you are still using an old instance that has been destroyed.
|
|
28
28
|
Please make sure you are using the latest instance of the form and cleanup event listeners.
|
|
@@ -33,4 +33,4 @@ Details: got ${n.required_user_actions.length} required user actions`);return Pa
|
|
|
33
33
|
- current_active_form_id: ${r.currentFormId}
|
|
34
34
|
- is_destroyed: ${r.isDestroyed}
|
|
35
35
|
- checkout_token: ${r.checkoutToken}
|
|
36
|
-
`;return this.isDestroyed?(
|
|
36
|
+
`;return this.isDestroyed?(me(o),E("outdated_form_instance",{error:o}),!1):!n||n.formId!==this.formId?(me(o),E("outdated_form_instance",{error:o}),!1):!0}};Se.ojsFlows=U,Se.assignAsSingleton=e=>{if(Se.getInstance())throw new Error("OpenPay instance already exists. Only one instance is allowed.");window.ojs=e},Se.getInstance=()=>window.ojs??null,Se.buildOjsFlowContext=(e,n,r,o)=>({checkoutSecureToken:e.checkoutSecureToken,baseUrl:new URL(e.baseUrl??Ke).origin,formDiv:o,elementsSessionId:n.sessionId,checkoutPaymentMethods:n.checkoutPaymentMethods,anyCdeConnection:r,customInitParams:e.customInitParams??{}});let Hn=Se;Ae.FieldName=h,Ae.OpenPayForm=Hn,Ae.SubmitMethod=na,Ae.SubmitMethods=X,Object.defineProperty(Ae,Symbol.toStringTag,{value:"Module"})});
|