@getopenpay/openpay-js 0.3.1 → 0.3.2

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.umd.js CHANGED
@@ -1,17 +1,17 @@
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 Ko;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 En;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(En||(En={}));const w=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 w.undefined;case"string":return w.string;case"number":return isNaN(t)?w.nan:w.number;case"boolean":return w.boolean;case"function":return w.function;case"bigint":return w.bigint;case"symbol":return w.symbol;case"object":return Array.isArray(t)?w.array:t===null?w.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?w.promise:typeof Map<"u"&&t instanceof Map?w.map:typeof Set<"u"&&t instanceof Set?w.set:typeof Date<"u"&&t instanceof Date?w.date:w.object;default:return w.unknown}},_=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"]),Jo=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 _.invalid_type:t.received===w.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case _.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,N.jsonStringifyReplacer)}`;break;case _.unrecognized_keys:n=`Unrecognized key(s) in object: ${N.joinValues(t.keys,", ")}`;break;case _.invalid_union:n="Invalid input";break;case _.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${N.joinValues(t.options)}`;break;case _.invalid_enum_value:n=`Invalid enum value. Expected ${N.joinValues(t.options)}, received '${t.received}'`;break;case _.invalid_arguments:n="Invalid function arguments";break;case _.invalid_return_type:n="Invalid function return type";break;case _.invalid_date:n="Invalid date";break;case _.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 _.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 _.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 _.custom:n="Invalid input";break;case _.invalid_intersection_types:n="Intersection results could not be merged";break;case _.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case _.not_finite:n="Number must be finite";break;default:n=e.defaultError,N.assertNever(t)}return{message:n}};let Qn=Je;function Qo(t){Qn=t}function Bt(){return Qn}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}},Xo=[];function v(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}),kn=t=>t.status==="aborted",Cn=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 Xn(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 ye{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 er=(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 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 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 er(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 er(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:_.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 ue({schema:this,typeName:C.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return ge.create(this,this._def)}nullable(){return Fe.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return le.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 ue({...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 An({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 es=/^c[^\s-]{8,}$/i,ts=/^[0-9a-z]+$/,ns=/^[0-9A-HJKMNP-TV-Z]{26}$/,rs=/^[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,os=/^[a-z0-9_-]{21}$/i,ss=/^[-+]?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)?)??$/,as=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,is="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Sn;const cs=/^(?:(?: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])$/,ls=/^(([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})))$/,us=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,tr="((\\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])))",ds=new RegExp(`^${tr}$`);function nr(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 ps(t){return new RegExp(`^${nr(t)}$`)}function rr(t){let e=`${tr}T${nr(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 fs(t,e){return!!((e==="v4"||!e)&&cs.test(t)||(e==="v6"||!e)&&ls.test(t))}class ce extends I{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==w.string){const s=this._getOrReturnCtx(e);return v(s,{code:_.invalid_type,expected:w.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),v(o,{code:_.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),v(o,{code:_.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?v(o,{code:_.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):c&&v(o,{code:_.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")as.test(e.data)||(o=this._getOrReturnCtx(e,o),v(o,{validation:"email",code:_.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Sn||(Sn=new RegExp(is,"u")),Sn.test(e.data)||(o=this._getOrReturnCtx(e,o),v(o,{validation:"emoji",code:_.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")rs.test(e.data)||(o=this._getOrReturnCtx(e,o),v(o,{validation:"uuid",code:_.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")os.test(e.data)||(o=this._getOrReturnCtx(e,o),v(o,{validation:"nanoid",code:_.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")es.test(e.data)||(o=this._getOrReturnCtx(e,o),v(o,{validation:"cuid",code:_.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")ts.test(e.data)||(o=this._getOrReturnCtx(e,o),v(o,{validation:"cuid2",code:_.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")ns.test(e.data)||(o=this._getOrReturnCtx(e,o),v(o,{validation:"ulid",code:_.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),v(o,{validation:"url",code:_.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),v(o,{validation:"regex",code:_.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),v(o,{code:_.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),v(o,{code:_.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),v(o,{code:_.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?rr(s).test(e.data)||(o=this._getOrReturnCtx(e,o),v(o,{code:_.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?ds.test(e.data)||(o=this._getOrReturnCtx(e,o),v(o,{code:_.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?ps(s).test(e.data)||(o=this._getOrReturnCtx(e,o),v(o,{code:_.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?ss.test(e.data)||(o=this._getOrReturnCtx(e,o),v(o,{validation:"duration",code:_.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?fs(e.data,s.version)||(o=this._getOrReturnCtx(e,o),v(o,{validation:"ip",code:_.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?us.test(e.data)||(o=this._getOrReturnCtx(e,o),v(o,{validation:"base64",code:_.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:_.invalid_string,...b.errToObj(r)})}_addCheck(e){return new ce({...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 ce({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ce({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ce({...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}}ce.create=t=>{var e;return new ce({checks:[],typeName:C.ZodString,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...T(t)})};function ms(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 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)!==w.number){const s=this._getOrReturnCtx(e);return v(s,{code:_.invalid_type,expected:w.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),v(r,{code:_.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),v(r,{code:_.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),v(r,{code:_.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?ms(e.data,s.value)!==0&&(r=this._getOrReturnCtx(e,r),v(r,{code:_.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),v(r,{code:_.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 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)!==w.bigint){const s=this._getOrReturnCtx(e);return v(s,{code:_.invalid_type,expected:w.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),v(r,{code:_.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),v(r,{code:_.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),v(r,{code:_.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 I{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==w.boolean){const r=this._getOrReturnCtx(e);return v(r,{code:_.invalid_type,expected:w.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 I{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==w.date){const s=this._getOrReturnCtx(e);return v(s,{code:_.invalid_type,expected:w.date,received:s.parsedType}),S}if(isNaN(e.data.getTime())){const s=this._getOrReturnCtx(e);return v(s,{code:_.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),v(o,{code:_.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),v(o,{code:_.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 I{_parse(e){if(this._getType(e)!==w.symbol){const r=this._getOrReturnCtx(e);return v(r,{code:_.invalid_type,expected:w.symbol,received:r.parsedType}),S}return Q(e.data)}}Wt.create=t=>new Wt({typeName:C.ZodSymbol,...T(t)});class gt extends I{_parse(e){if(this._getType(e)!==w.undefined){const r=this._getOrReturnCtx(e);return v(r,{code:_.invalid_type,expected:w.undefined,received:r.parsedType}),S}return Q(e.data)}}gt.create=t=>new gt({typeName:C.ZodUndefined,...T(t)});class vt extends I{_parse(e){if(this._getType(e)!==w.null){const r=this._getOrReturnCtx(e);return v(r,{code:_.invalid_type,expected:w.null,received:r.parsedType}),S}return Q(e.data)}}vt.create=t=>new vt({typeName:C.ZodNull,...T(t)});class Xe extends I{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 I{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 I{_parse(e){const n=this._getOrReturnCtx(e);return v(n,{code:_.invalid_type,expected:w.never,received:n.parsedType}),S}}Te.create=t=>new Te({typeName:C.ZodNever,...T(t)});class Ht extends I{_parse(e){if(this._getType(e)!==w.undefined){const r=this._getOrReturnCtx(e);return v(r,{code:_.invalid_type,expected:w.void,received:r.parsedType}),S}return Q(e.data)}}Ht.create=t=>new Ht({typeName:C.ZodVoid,...T(t)});class le extends I{_parse(e){const{ctx:n,status:r}=this._processInputParams(e),o=this._def;if(n.parsedType!==w.array)return v(n,{code:_.invalid_type,expected:w.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)&&(v(n,{code:i?_.too_big:_.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&&(v(n,{code:_.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&&(v(n,{code:_.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 ye(n,i,n.path,c)))).then(i=>K.mergeArray(r,i));const s=[...n.data].map((i,c)=>o.type._parseSync(new ye(n,i,n.path,c)));return K.mergeArray(r,s)}get element(){return this._def.type}min(e,n){return new le({...this._def,minLength:{value:e,message:b.toString(n)}})}max(e,n){return new le({...this._def,maxLength:{value:e,message:b.toString(n)}})}length(e,n){return new le({...this._def,exactLength:{value:e,message:b.toString(n)}})}nonempty(e){return this.min(1,e)}}le.create=(t,e)=>new le({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]=ge.create(et(r))}return new j({...t._def,shape:()=>e})}else return t instanceof le?new le({...t._def,type:et(t.element)}):t instanceof ge?ge.create(et(t.unwrap())):t instanceof Fe?Fe.create(et(t.unwrap())):t instanceof _e?_e.create(t.items.map(e=>et(e))):t}class j 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(),n=N.objectKeys(e);return this._cached={shape:e,keys:n}}_parse(e){if(this._getType(e)!==w.object){const u=this._getOrReturnCtx(e);return v(u,{code:_.invalid_type,expected:w.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],p=o.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new ye(o,p,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&&(v(o,{code:_.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 ye(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,m=await d.value;u.push({key:p,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 ge;)s=s._def.innerType;n[r]=s}}),new j({...this._def,shape:()=>n})}keyof(){return or(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 I{_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 v(n,{code:_.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 v(n,{code:_.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 ue?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 ge?[void 0,...Ie(t.unwrap())]:t instanceof Fe?[null,...Ie(t.unwrap())]:t instanceof An||t instanceof It?Ie(t.unwrap()):t instanceof At?Ie(t._def.innerType):[];class Kt extends I{_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==w.object)return v(n,{code:_.invalid_type,expected:w.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}):(v(n,{code:_.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 Pn(t,e){const n=Ne(t),r=Ne(e);if(t===e)return{valid:!0,data:t};if(n===w.object&&r===w.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=Pn(t[c],e[c]);if(!l.valid)return{valid:!1};i[c]=l.data}return{valid:!0,data:i}}else if(n===w.array&&r===w.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=Pn(i,c);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===w.date&&r===w.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class bt extends I{_parse(e){const{status:n,ctx:r}=this._processInputParams(e),o=(s,i)=>{if(kn(s)||kn(i))return S;const c=Pn(s.value,i.value);return c.valid?((Cn(s)||Cn(i))&&n.dirty(),{status:n.value,value:c.data}):(v(r,{code:_.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 _e extends I{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==w.array)return v(r,{code:_.invalid_type,expected:w.array,received:r.parsedType}),S;if(r.data.length<this._def.items.length)return v(r,{code:_.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),S;!this._def.rest&&r.data.length>this._def.items.length&&(v(r,{code:_.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 ye(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 _e({...this._def,rest:e})}}_e.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new _e({items:t,typeName:C.ZodTuple,rest:null,...T(e)})};class Et extends I{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!==w.object)return v(r,{code:_.invalid_type,expected:w.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 ye(r,c,r.path,c)),value:i._parse(new ye(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 I?new Et({keyType:e,valueType:n,typeName:C.ZodRecord,...T(r)}):new Et({keyType:ce.create(),valueType:e,typeName:C.ZodRecord,...T(n)})}}class Jt extends I{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!==w.map)return v(r,{code:_.invalid_type,expected:w.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 ye(r,c,r.path,[u,"key"])),value:s._parse(new ye(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 I{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==w.set)return v(r,{code:_.invalid_type,expected:w.set,received:r.parsedType}),S;const o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(v(r,{code:_.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&&(v(r,{code:_.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 ye(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 I{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==w.function)return v(n,{code:_.invalid_type,expected:w.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:_.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:_.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(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 ne([r(l,u.error)]);const d=Reflect.apply(i,this,u.data),p=c._def.returns.safeParse(d,s);if(!p.success)throw new ne([o(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new tt({...this._def,args:_e.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||_e.create([]).rest(Ve.create()),returns:n||Ve.create(),typeName:C.ZodFunction,...T(r)})}}class kt extends I{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 I{_parse(e){if(e.data!==this._def.value){const n=this._getOrReturnCtx(e);return v(n,{received:n.data,code:_.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 or(t,e){return new De({values:t,typeName:C.ZodEnum,...T(e)})}class De extends I{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 v(n,{expected:N.joinValues(r),received:n.parsedType,code:_.invalid_type}),S}if(Yt(this,ht)||Xn(this,ht,new Set(this._def.values)),!Yt(this,ht).has(e.data)){const n=this._getOrReturnCtx(e),r=this._def.values;return v(n,{received:n.data,code:_.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=or;class St extends I{constructor(){super(...arguments),yt.set(this,void 0)}_parse(e){const n=N.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==w.string&&r.parsedType!==w.number){const o=N.objectValues(n);return v(r,{expected:N.joinValues(o),received:r.parsedType,code:_.invalid_type}),S}if(Yt(this,yt)||Xn(this,yt,new Set(N.getValidEnumValues(this._def.values))),!Yt(this,yt).has(e.data)){const o=N.objectValues(n);return v(r,{received:r.data,code:_.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 I{unwrap(){return this._def.type}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==w.promise&&n.common.async===!1)return v(n,{code:_.invalid_type,expected:w.promise,received:n.parsedType}),S;const r=n.parsedType===w.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 ue extends I{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=>{v(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)}}ue.create=(t,e,n)=>new ue({schema:t,typeName:C.ZodEffects,effect:e,...T(n)}),ue.createWithPreprocess=(t,e,n)=>new ue({schema:e,effect:{type:"preprocess",transform:t},typeName:C.ZodEffects,...T(n)});class ge extends I{_parse(e){return this._getType(e)===w.undefined?Q(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ge.create=(t,e)=>new ge({innerType:t,typeName:C.ZodOptional,...T(e)});class Fe extends I{_parse(e){return this._getType(e)===w.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 I{_parse(e){const{ctx:n}=this._processInputParams(e);let r=n.data;return n.parsedType===w.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 I{_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 I{_parse(e){if(this._getType(e)!==w.nan){const r=this._getOrReturnCtx(e);return v(r,{code:_.invalid_type,expected:w.nan,received:r.parsedType}),S}return{status:"valid",value:e.data}}}Qt.create=t=>new Qt({typeName:C.ZodNaN,...T(t)});const hs=Symbol("zod_brand");class An extends I{_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 I{_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 I{_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 sr(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 ys={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 _s=(t,e={message:`Input not instance of ${t.name}`})=>sr(n=>n instanceof t,e),ar=ce.create,ir=Oe.create,gs=Qt.create,vs=Me.create,cr=_t.create,ws=$e.create,bs=Wt.create,Es=gt.create,ks=vt.create,Cs=Xe.create,Ss=Ve.create,Ps=Te.create,As=Ht.create,Ts=le.create,Is=j.create,xs=j.strictCreate,Rs=wt.create,Ns=Kt.create,Os=bt.create,Ms=_e.create,Ds=Et.create,Fs=Jt.create,Ls=Ze.create,js=tt.create,Us=kt.create,$s=Ct.create,Vs=De.create,Zs=St.create,zs=nt.create,lr=ue.create,Gs=ge.create,Bs=Fe.create,qs=ue.createWithPreprocess,Ys=Tt.create;var a=Object.freeze({__proto__:null,defaultErrorMap:Je,setErrorMap:Qo,getErrorMap:Bt,makeIssue:qt,EMPTY_PATH:Xo,addIssueToContext:v,ParseStatus:K,INVALID:S,DIRTY:Qe,OK:Q,isAborted:kn,isDirty:Cn,isValid:ft,isAsync:mt,get util(){return N},get objectUtil(){return En},ZodParsedType:w,getParsedType:Ne,ZodType:I,datetimeRegex:rr,ZodString:ce,ZodNumber:Oe,ZodBigInt:Me,ZodBoolean:_t,ZodDate:$e,ZodSymbol:Wt,ZodUndefined:gt,ZodNull:vt,ZodAny:Xe,ZodUnknown:Ve,ZodNever:Te,ZodVoid:Ht,ZodArray:le,ZodObject:j,ZodUnion:wt,ZodDiscriminatedUnion:Kt,ZodIntersection:bt,ZodTuple:_e,ZodRecord:Et,ZodMap:Jt,ZodSet:Ze,ZodFunction:tt,ZodLazy:kt,ZodLiteral:Ct,ZodEnum:De,ZodNativeEnum:St,ZodPromise:nt,ZodEffects:ue,ZodTransformer:ue,ZodOptional:ge,ZodNullable:Fe,ZodDefault:Pt,ZodCatch:At,ZodNaN:Qt,BRAND:hs,ZodBranded:An,ZodPipeline:Tt,ZodReadonly:It,custom:sr,Schema:I,ZodSchema:I,late:ys,get ZodFirstPartyTypeKind(){return C},coerce:{string:t=>ce.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:Cs,array:Ts,bigint:vs,boolean:cr,date:ws,discriminatedUnion:Ns,effect:lr,enum:Vs,function:js,instanceof:_s,intersection:Os,lazy:Us,literal:$s,map:Fs,nan:gs,nativeEnum:Zs,never:Ps,null:ks,nullable:Bs,number:ir,object:Is,oboolean:()=>cr().optional(),onumber:()=>ir().optional(),optional:Gs,ostring:()=>ar().optional(),pipeline:Ys,preprocess:qs,promise:zs,record:Ds,set:Ls,strictObject:xs,string:ar,symbol:bs,transformer:lr,tuple:Ms,undefined:Es,union:Rs,unknown:Ss,void:As,NEVER:S,ZodIssueCode:_,quotelessJson:Jo,ZodError:ne});const Ws=a.object({type:a.string(),loc:a.array(a.string()),msg:a.string(),url:a.string()}),Hs=a.array(Ws),Ks=a.object({code:a.string(),message:a.string(),path:a.array(a.string())}),Js=a.array(Ks),Qs={"failed to fetch":"Connection error: please double check if you are connected to the internet, then try again"},Tn=t=>{const e=t.toLowerCase().trim();return Qs[e]??t},Xs=t=>{try{return typeof JSON.parse(t)=="object"}catch{return!1}},ea=t=>t.length===1?Tn(t[0].msg):`Please fix the following errors:
2
- ${t.map(n=>`• ${Tn(n.msg)}`).join(`
3
- `)}`,ta=t=>`Encountered the following errors:
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",mt=t=>t.status==="valid",ht=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 yt,_t;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(mt(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(ht(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(ht(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 bt.create([this,e],this._def)}and(e){return Et.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 At({...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 Tt({...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 It.create(this,e)}readonly(){return xt.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 gt 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)}}gt.create=t=>new gt({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 vt 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)}}vt.create=t=>new vt({typeName:C.ZodUndefined,...T(t)});class wt 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)}}wt.create=t=>new wt({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 bt 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}}bt.create=(t,e)=>new bt({options:t,typeName:C.ZodUnion,...T(e)});const Ie=t=>t instanceof Ct?Ie(t.schema):t instanceof le?Ie(t.innerType()):t instanceof St?[t.value]:t instanceof De?t.options:t instanceof Pt?N.objectValues(t.enum):t instanceof At?Ie(t._def.innerType):t instanceof vt?[void 0]:t instanceof wt?[null]:t instanceof _e?[void 0,...Ie(t.unwrap())]:t instanceof Fe?[null,...Ie(t.unwrap())]:t instanceof Pn||t instanceof xt?Ie(t.unwrap()):t instanceof Tt?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 Et 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}))}}Et.create=(t,e,n)=>new Et({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 kt 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 kt({keyType:e,valueType:n,typeName:C.ZodRecord,...T(r)}):new kt({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 Ct 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})}}Ct.create=(t,e)=>new Ct({getter:t,typeName:C.ZodLazy,...T(e)});class St 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}}St.create=(t,e)=>new St({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),yt.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,yt)||Qn(this,yt,new Set(this._def.values)),!Yt(this,yt).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})}}yt=new WeakMap,De.create=rr;class Pt extends R{constructor(){super(...arguments),_t.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,_t)||Qn(this,_t,new Set(N.getValidEnumValues(this._def.values))),!Yt(this,_t).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}}_t=new WeakMap,Pt.create=(t,e)=>new Pt({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(!mt(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=>mt(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 At 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}}At.create=(t,e)=>new At({innerType:t,typeName:C.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...T(e)});class Tt 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 ht(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}}Tt.create=(t,e)=>new Tt({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 It 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 It({in:e,out:n,typeName:C.ZodPipeline})}}class xt extends R{_parse(e){const n=this._def.innerType._parse(e),r=o=>(mt(o)&&(o.value=Object.freeze(o.value)),o);return ht(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}}xt.create=(t,e)=>new xt({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=gt.create,vs=$e.create,ws=Wt.create,bs=vt.create,Es=wt.create,ks=Xe.create,Cs=Ve.create,Ss=Te.create,Ps=Ht.create,As=ce.create,Ts=j.create,Is=j.strictCreate,xs=bt.create,Rs=Kt.create,Ns=Et.create,Os=ye.create,Ms=kt.create,Ds=Jt.create,Fs=Ze.create,Ls=tt.create,js=Ct.create,Us=St.create,$s=De.create,Vs=Pt.create,Zs=nt.create,cr=le.create,zs=_e.create,Gs=Fe.create,Bs=le.createWithPreprocess,qs=It.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:mt,isAsync:ht,get util(){return N},get objectUtil(){return bn},ZodParsedType:v,getParsedType:Ne,ZodType:R,datetimeRegex:nr,ZodString:ie,ZodNumber:Oe,ZodBigInt:Me,ZodBoolean:gt,ZodDate:$e,ZodSymbol:Wt,ZodUndefined:vt,ZodNull:wt,ZodAny:Xe,ZodUnknown:Ve,ZodNever:Te,ZodVoid:Ht,ZodArray:ce,ZodObject:j,ZodUnion:bt,ZodDiscriminatedUnion:Kt,ZodIntersection:Et,ZodTuple:ye,ZodRecord:kt,ZodMap:Jt,ZodSet:Ze,ZodFunction:tt,ZodLazy:Ct,ZodLiteral:St,ZodEnum:De,ZodNativeEnum:Pt,ZodPromise:nt,ZodEffects:le,ZodTransformer:le,ZodOptional:_e,ZodNullable:Fe,ZodDefault:At,ZodCatch:Tt,ZodNaN:Qt,BRAND:ms,ZodBranded:Pn,ZodPipeline:It,ZodReadonly:xt,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=>gt.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
4
  ${t.map(n=>`- ${n.path.join("/")}: ${n.message}`).join(`
5
- `)}`,re=t=>{if(t instanceof Error)if(Xs(t.message)){const e=JSON.parse(t.message);return Hs.safeParse(e).success?ea(e):Js.safeParse(e).success?ta(e):(console.warn(`Encountered unknown stringified JSON object:
6
- ${t.message}`),t.message)}else return Tn(t.message);if(typeof t=="object")try{return JSON.stringify(t)}catch(e){return e+""}else return t+""},na=(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 ra=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 ur=a.nativeEnum(h);var dr=(t=>(t.CARD_NUMBER="cardNumber",t.CARD_EXPIRY="cardExpiry",t.CARD_CVC="cardCvc",t))(dr||{});const pr=a.nativeEnum(dr),fr=a.union([ur,pr]);var ve=(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))(ve||{});const oa=a.nativeEnum(ve),Xt=a.object({provider:a.string(),processor_name:q(a.string()),metadata:q(a.record(a.string(),a.any()))}),sa=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 de=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"]),aa=de.extract(["TOKENIZE_STARTED","CHECKOUT_STARTED"]),ia=a.object({type:aa}),ca=de.extract(["BLUR","FOCUS","CHANGE"]),la=a.object({type:ca,elementType:pr,errors:a.array(a.string()).optional()}),ua=de.extract(["LOAD_ERROR","TOKENIZE_ERROR","CHECKOUT_ERROR"]),da=a.object({type:ua,message:Z,headers:a.record(a.string(),a.string()).optional()}),pa=de.extract(["VALIDATION_ERROR"]),fa=a.object({type:pa,elementType:fr,errors:a.array(a.string())}),ma=a.object({type:a.literal(de.enum.LAYOUT),height:Z}),ha=a.object({type:a.literal(de.enum.LOADED),sessionId:Z,totalAmountAtoms:a.number(),currency:O,checkoutPaymentMethods:a.array(Xt)}),ya=a.object({type:a.literal(de.enum.PAYMENT_FLOW_STARTED),nextActionMetadata:a.record(a.string(),a.any()),paymentFlowMetadata:a.any().optional(),startPFMetadata:a.optional(a.record(a.string(),a.any()))}),_a=a.object({type:a.literal(de.enum.SETUP_PAYMENT_METHOD_SUCCESS),paymentMethodId:a.string()}),xt=a.object({firstName:Z,lastName:Z,email:Z,zipCode:Z,country:Z,promotionCode:O}),ga=a.object({firstName:O,lastName:O,email:Z,zipCode:Z,country:Z,promotionCode:O,address:O,city:O,state:O}),va=de.extract(["TOKENIZE","CHECKOUT","START_PAYMENT_FLOW"]),wa=a.object({type:va,sessionId:Z,checkoutPaymentMethod:Xt,paymentFlowMetadata:a.any().optional(),doNotUseLegacyCCFlow:a.boolean().optional(),existingCCPMId:O,paymentRouteId:O}).extend(xt.shape),ba=a.object({type:a.literal(de.enum.TOKENIZE_SUCCESS),isReadyForCheckout:a.boolean()}),Ea=a.object({type:a.literal(de.enum.CHECKOUT_SUCCESS),invoiceUrls:a.array(a.string()),subscriptionIds:a.array(a.string()),customerId:a.string()}),ka=a.discriminatedUnion("type",[ia,la,da,fa,ma,ha,wa,ba,Ea,ya,_a]),Ca=a.object({payload:ka,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 In=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()))}),Sa=a.object({elementType:a.string(),errors:a.array(a.string())});a.object({session_id:a.string()});const Pa=a.object({success:a.literal(!1),error_type:a.literal("validation_error"),errors:a.array(Sa)}),Aa=a.discriminatedUnion("success",[a.object({success:a.literal(!0)}),Pa]);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 G=(t=>(t.SUCCESS="success",t.FAILURE="failure",t.CANCELLED="cancelled",t))(G||{});const Ta=a.object({status:a.enum(["success","failure","cancelled"]),href:a.string().optional().nullable()});a.object({href:a.string().optional().nullable()});const Ia=a.object({type:a.string(),redirect_url:a.string(),initial_intent_id:a.string(),consent_id:a.string(),their_pm_id:a.string().optional()}),mr=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()))}),xa=a.discriminatedUnion("present",[a.object({present:a.literal(!0),href:a.string()}),a.object({present:a.literal(!1)})]),Ra=a.object({payment_methods:a.array(sa),pay_first_success_response:q(In),required_user_actions:q(a.array(mr))}),hr=t=>{const e={};return Object.entries(t).forEach(([n,r])=>{try{const o=ur.parse(n);Array.isArray(r)?e[o]=r:Array.isArray(r._errors)&&(e[o]=r._errors)}catch{return}}),e},Na=a.object({stripe_pk:a.string(),client_secret:a.string(),stripe_pm_id:a.string()}),Oa=a.object({type:a.string(),client_secret:a.string(),stripe_pk:a.string()}),Ma={usd:"usd",brl:"brl"},en=async t=>{for(let n=0;n<10;n++)yr()||await tn(500);if(!yr())throw console.log("Stripe JS not found."),new Error("Stripe JS not found.");return new Stripe(t)},Da=async(t,e)=>{const n=await en(t);return{elements:n.elements(e),stripe:n}},Fa=async(t,e,n,r,o)=>{const s=await en(t),i=Ma[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)}),yr=()=>"Stripe"in window,La=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)}}),ja=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},Ua=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."}`)},$a=t=>JSON.stringify(t);for(var Y=[],xn=0;xn<256;++xn)Y.push((xn+256).toString(16).slice(1));function Va(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,Za=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(Za)}var Ga=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const _r={randomUUID:Ga};function Rt(t,e,n){if(_r.randomUUID&&!e&&!t)return _r.randomUUID();t=t||{};var r=t.random||(t.rng||za)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,Va(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},{}),Ba=t=>{try{return Ca.parse(t)}catch(e){throw console.error("Error parsing event payload:",t,e),e}};var we;(function(t){t.Call="call",t.Reply="reply",t.Syn="syn",t.SynAck="synAck",t.Ack="ack"})(we||(we={}));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 Rn;(function(t){t.DataCloneError="DataCloneError"})(Rn||(Rn={}));var Le;(function(t){t.Message="message"})(Le||(Le={}));const qa=(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)}}},Ya=t=>(...e)=>{t&&console.log("[Penpal]",...e)},Wa={"http:":"80","https:":"443"},Ha=/^(https?:)?\/\/([^/:]+)?(:(\d+))?/,Ka=["file:","data:"],Ja=t=>{if(t&&Ka.find(c=>t.startsWith(c)))return"null";const e=document.location,n=Ha.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!==Wa[r]?`:${s}`:"";return`${r}//${o}${i}`},gr=({name:t,message:e,stack:n})=>({name:t,message:e,stack:n}),Qa=t=>{const e=new Error;return Object.keys(t).forEach(n=>e[n]=t[n]),e},Xa=(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!==we.Call)return;if(c!=="*"&&d.origin!==c){n(`${r} received message from origin ${d.origin} which did not match expected origin ${c}`);return}const p=d.data,{methodName:m,args:f,id:y}=p;n(`${r}: Received ${m}() call`);const g=A=>k=>{if(n(`${r}: Sending ${m}() reply`),l){n(`${r}: Unable to send ${m}() reply due to destroyed connection`);return}const x={penpal:we.Reply,id:y,resolution:A,returnValue:k};A===ze.Rejected&&k instanceof Error&&(x.returnValue=gr(k),x.returnValueIsError=!0);try{s.postMessage(x,i)}catch(R){if(R.name===Rn.DataCloneError){const M={penpal:we.Reply,id:y,resolution:ze.Rejected,returnValue:gr(R),returnValueIsError:!0};s.postMessage(M,i)}throw R}};new Promise(A=>A(e[m].apply(e,f))).then(g(ze.Fulfilled),g(ze.Rejected))};return o.addEventListener(Le.Message,u),()=>{l=!0,o.removeEventListener(Le.Message,u)}};let ei=0;const ti=()=>++ei,vr=".",wr=t=>t?t.split(vr):[],ni=t=>t.join(vr),ri=(t,e)=>{const n=wr(e||"");return n.push(t),ni(n)},oi=(t,e,n)=>{const r=wr(e);return r.reduce((o,s,i)=>(typeof o[s]>"u"&&(o[s]={}),i===r.length-1&&(o[s]=n),o[s]),t),t},br=(t,e)=>{const n={};return Object.keys(t).forEach(r=>{const o=t[r],s=ri(r,e);typeof o=="object"&&Object.assign(n,br(o,s)),typeof o=="function"&&(n[s]=o)}),n},si=t=>{const e={};for(const n in t)oi(e,n,t[n]);return e},ai=(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 p=f=>(...y)=>{o(`${s}: Sending ${f}() call`);let g;try{c.closed&&(g=!0)}catch{g=!0}if(g&&r(),d){const A=new Error(`Unable to send ${f}() call due to destroyed connection`);throw A.code=Nt.ConnectionDestroyed,A}return new Promise((A,k)=>{const x=ti(),R=V=>{if(V.source!==c||V.data.penpal!==we.Reply||V.data.id!==x)return;if(u!=="*"&&V.origin!==u){o(`${s} received message from origin ${V.origin} which did not match expected origin ${u}`);return}const z=V.data;o(`${s}: Received ${f}() reply`),i.removeEventListener(Le.Message,R);let ie=z.returnValue;z.returnValueIsError&&(ie=Qa(ie)),(z.resolution===ze.Fulfilled?A:k)(ie)};i.addEventListener(Le.Message,R);const M={penpal:we.Call,id:x,methodName:f,args:y};c.postMessage(M,l)})},m=n.reduce((f,y)=>(f[y]=p(y),f),{});return Object.assign(t,si(m)),()=>{d=!0}},ii=(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 p={localName:"Parent",local:window,remote:d.source,originForSending:n,originForReceiving:e};c&&c(),c=Xa(p,t,o),i(c),l&&l.forEach(f=>{delete u[f]}),l=d.data.methodNames;const m=ai(u,p,l,s,o);return i(m),u}},ci=(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:we.SynAck,methodNames:Object.keys(e)};o.source.postMessage(s,r)},li=6e4,ui=(t,e)=>{const{destroy:n,onDestroy:r}=e,o=setInterval(()=>{t.isConnected||(clearInterval(o),n())},li);r(()=>{clearInterval(o)})},di=(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)}},pi=t=>{if(!t.src&&!t.srcdoc){const e=new Error("Iframe must have src or srcdoc property defined.");throw e.code=Nt.NoIframeSrc,e}},Er=t=>{let{iframe:e,methods:n={},childOrigin:r,timeout:o,debug:s=!1}=t;const i=Ya(s),c=qa("Parent",i),{onDestroy:l,destroy:u}=c;r||(pi(e),r=Ja(e.src));const d=r==="null"?"*":r,p=br(n),m=ci(i,p,r,d),f=ii(p,r,d,c,i);return{promise:new Promise((g,A)=>{const k=di(o,u),x=R=>{if(!(R.source!==e.contentWindow||!R.data)){if(R.data.penpal===we.Syn){m(R);return}if(R.data.penpal===we.Ack){const M=f(R);M&&(k(),g(M));return}}};window.addEventListener(Le.Message,x),i("Parent: Awaiting handshake"),ui(e,c),l(R=>{window.removeEventListener(Le.Message,x),R&&A(R)})}),destroy(){u()}}},fi=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}},mi=(t,e)=>!!t&&e,P=t=>a.nullable(t.optional());a.string().trim().min(1,{message:"Cannot be blank"});const hi=a.object({cde_response_type:a.literal("error"),message:a.string(),headers:a.record(a.string(),a.string()).optional()});a.enum(["usd","brl"]);const kr=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())}),Cr=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()}),yi=a.record(a.string(),a.any()),_i=a.object({name:a.string(),settings:P(yi)}),rt=a.object({provider:a.string(),processor_name:P(a.string()),metadata:P(a.record(a.string(),a.any()))}),gi=a.object({quantity:a.number()}),vi=a.object({id:P(a.string()),billing_interval:P(a.string()),billing_interval_count:P(a.number().int()),subscription_items:a.array(gi),trial_start:P(a.string()),trial_end:P(a.string())}),Sr=a.object({amount_atom:a.number()}),wi=a.object({amount_atom:a.number(),amount_atom_considering_discount_applied:a.number(),currency:a.string(),discount_amount_atoms:a.array(Sr),subscription_item_id:a.string()}),bi=a.object({coupon:kr}),Ei=a.object({currency:a.string(),discounts:a.array(bi),hosted_invoice_url:P(a.string()),lines:a.array(wi),remaining_amount_atom:a.number(),tax_amount_atom:a.number(),total_amount_atom:a.number(),total_discount_amount_atoms:a.array(Sr)}),Pr=a.object({created:a.array(vi),invoices:a.array(Ei),processors_used:P(a.array(a.string()))}),Ar=a.object({preview:Pr,preview_post_trial:P(Pr),coupons:a.array(kr)}),Tr=a.object({status:a.literal("open"),locale:P(a.string()),token:a.string(),email:P(a.string()),line_items:a.array(Cr),amount_subtotal_atom:a.number().int(),amount_total_atom:a.number().int(),brand:_i,subs_preview:P(Ar),methods_available:a.array(rt)}),Ir=a.discriminatedUnion("mode",[a.object({mode:a.literal("setup"),currency:a.nullable(a.undefined())}).extend(Tr.shape),a.object({mode:a.enum(["payment","subscription"]),currency:a.string()}).extend(Tr.shape)]),ki=a.object({status:a.literal("complete")}),Ci=a.object({status:a.literal("expired")});a.union([Ir,ki,Ci]),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(Cr),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 xr=a.object({payment_method_id:a.string()});a.object({id:a.string(),return_url:a.string()});const Si=a.object({type:a.string(),loc:a.array(a.string()),msg:a.string(),url:a.string()});a.array(Si);const Pi=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()}),Ai=a.object({price_id:a.string(),quantity:a.number().int()}),Ti=a.object({line_items:a.array(Ai),promotion_code:a.string().optional(),displayed_total_amount_atom:a.number().int()}),Ii=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:Ti.optional()}).extend(Pi.shape).extend(Ii.shape);const Rr=a.object({required_user_actions:a.array(a.record(a.string(),a.any())),checkout_attempt_id:P(a.string())});a.object({fields:ga,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 xi=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 Ri=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 Ni=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 Oi=a.object({}),Mi=t=>t.reduce((e,n)=>e+n,0);function Di(t,e){var n=Object.setPrototypeOf;n?n(t,e):t.__proto__=e}function Fi(t,e){e===void 0&&(e=t.constructor);var n=Error.captureStackTrace;n&&n(t,e)}var Li=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)}}(),ji=function(t){Li(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}),Di(s,o.prototype),Fi(s),s}return e}(Error);const Nn=10,Nr=(t=0)=>e=>`\x1B[${e+t}m`,Or=(t=0)=>e=>`\x1B[${38+t};5;${e}m`,Mr=(t=0)=>(e,n,r)=>`\x1B[${38+t};2;${e};${n};${r}m`,D={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(D.modifier);const Ui=Object.keys(D.color),$i=Object.keys(D.bgColor);[...Ui,...$i];function Vi(){const t=new Map;for(const[e,n]of Object.entries(D)){for(const[r,o]of Object.entries(n))D[r]={open:`\x1B[${o[0]}m`,close:`\x1B[${o[1]}m`},n[r]=D[r],t.set(o[0],o[1]);Object.defineProperty(D,e,{value:n,enumerable:!1})}return Object.defineProperty(D,"codes",{value:t,enumerable:!1}),D.color.close="\x1B[39m",D.bgColor.close="\x1B[49m",D.color.ansi=Nr(),D.color.ansi256=Or(),D.color.ansi16m=Mr(),D.bgColor.ansi=Nr(Nn),D.bgColor.ansi256=Or(Nn),D.bgColor.ansi16m=Mr(Nn),Object.defineProperties(D,{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=>D.rgbToAnsi256(...D.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)=>D.ansi256ToAnsi(D.rgbToAnsi256(e,n,r)),enumerable:!1},hexToAnsi:{value:e=>D.ansi256ToAnsi(D.hexToAnsi256(e)),enumerable:!1}}),D}const be=Vi(),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})(),Dr=rn!==0&&{level:rn,hasBasic:!0,has256:rn>=2,has16m:rn>=3},Zi={stdout:Dr,stderr:Dr};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 Gi(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
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),V=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:V,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:V}),ma=a.object({type:a.literal(ue.enum.LOADED),sessionId:V,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()}),Rt=a.object({firstName:V,lastName:V,email:V,zipCode:V,country:V,promotionCode:O}),_a=a.object({firstName:O,lastName:O,email:V,zipCode:V,country:V,promotionCode:O,address:O,city:O,state:O}),ga=ue.extract(["TOKENIZE","CHECKOUT","START_PAYMENT_FLOW"]),va=a.object({type:ga,sessionId:V,checkoutPaymentMethod:Xt,paymentFlowMetadata:a.any().optional(),doNotUseLegacyCCFlow:a.boolean().optional(),existingCCPMId:O,paymentRouteId:O}).extend(Rt.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:V,formId:V,elementId:V});a.object({amountAtom:a.number(),currency:V}),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:Rt,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:Rt,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 $=B.data;o(`${s}: Received ${p}() reply`),i.removeEventListener(Le.Message,I);let Pe=$.returnValue;$.returnValueIsError&&(Pe=Ja(Pe)),($.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)}),ot=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(ot)}),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:ot,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:ot,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:ot,payment_route_id:P(a.string())}),a.object({session_id:a.string(),non_cde_form_fields:Rt,checkout_payment_method:ot,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:ot,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
8
  `)+n,o=r+1,r=t.indexOf(`
9
- `,o)}while(r!==-1);return s+=t.slice(o),s}const{stdout:Fr,stderr:Lr}=Zi,On=Symbol("GENERATOR"),ot=Symbol("STYLER"),Ot=Symbol("IS_EMPTY"),jr=["ansi","ansi","ansi256","ansi16m"],st=Object.create(null),Bi=(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=Fr?Fr.level:0;t.level=e.level===void 0?n:e.level},qi=t=>{const e=(...n)=>n.join(" ");return Bi(e,t),Object.setPrototypeOf(e,Mt.prototype),e};function Mt(t){return qi(t)}Object.setPrototypeOf(Mt.prototype,Function.prototype);for(const[t,e]of Object.entries(be))st[t]={get(){const n=on(this,Dn(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 Mn=(t,e,n,...r)=>t==="rgb"?e==="ansi16m"?be[n].ansi16m(...r):e==="ansi256"?be[n].ansi256(be.rgbToAnsi256(...r)):be[n].ansi(be.rgbToAnsi(...r)):t==="hex"?Mn("rgb",e,n,...be.hexToRgb(...r)):be[n][t](...r),Yi=["rgb","hex","ansi256"];for(const t of Yi){st[t]={get(){const{level:n}=this;return function(...r){const o=Dn(Mn(t,jr[n],"color",...r),be.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=Dn(Mn(t,jr[n],"bgColor",...r),be.bgColor.close,this[ot]);return on(this,o,this[Ot])}}}}const Wi=Object.defineProperties(()=>{},{...st,level:{enumerable:!0,get(){return this[On].level},set(t){this[On].level=t}}}),Dn=(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)=>Hi(r,o.length===1?""+o[0]:o.join(" "));return Object.setPrototypeOf(r,Wi),r[On]=t,r[ot]=e,r[Ot]=n,r},Hi=(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=Gi(e,o,r,s)),r+e+o};Object.defineProperties(Mt.prototype,st);const sn=Mt();Mt({level:Lr?Lr.level:0});const Ee=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 lo(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}=F("init-error-catcher"),o=re(n),s=await lo(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}}},F=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 Fn=function(t,e){return Fn=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])},Fn(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");Fn(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function Ki(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(p){i(p)}}function l(d){try{u(r.throw(d))}catch(p){i(p)}}function u(d){d.done?s(d.value):o(d.value).then(c,l)}u((r=r.apply(t,e||[])).next())})}function Ur(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 Ji(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(f){return function(y){return Promise.resolve(y).then(f,p)}}function c(f,y){r[f]&&(o[f]=function(g){return new Promise(function(A,k){s.push([f,g,A,k])>1||l(f,g)})},y&&(o[f]=y(o[f])))}function l(f,y){try{u(r[f](y))}catch(g){m(s[0][3],g)}}function u(f){f.value instanceof it?Promise.resolve(f.value.v).then(d,p):m(s[0][2],f)}function d(f){l("next",f)}function p(f){l("throw",f)}function m(f,y){f(y),s.shift(),s.length&&l(s[0][0],s[0][1])}}function Qi(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 Ln=ln(function(t){return function(n){t(this),this.message=n?n.length+` errors occurred during unsubscription:
9
+ `,o)}while(r!==-1);return s+=t.slice(o),s}const{stdout:Dr,stderr:Fr}=Vi,Nn=Symbol("GENERATOR"),st=Symbol("STYLER"),Ot=Symbol("IS_EMPTY"),Lr=["ansi","ansi","ansi256","ansi16m"],at=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))at[t]={get(){const n=on(this,Mn(e.open,e.close,this[st]),this[Ot]);return Object.defineProperty(this,t,{value:n}),n}};at.visible={get(){const t=on(this,this[st],!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){at[t]={get(){const{level:n}=this;return function(...r){const o=Mn(On(t,Lr[n],"color",...r),we.color.close,this[st]);return on(this,o,this[Ot])}}};const e="bg"+t[0].toUpperCase()+t.slice(1);at[e]={get(){const{level:n}=this;return function(...r){const o=Mn(On(t,Lr[n],"bgColor",...r),we.bgColor.close,this[st]);return on(this,o,this[Ot])}}}}const Yi=Object.defineProperties(()=>{},{...at,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[st]=e,r[Ot]=n,r},Wi=(t,e)=>{if(t.level<=0||!e)return t[Ot]?"":e;let n=t[st];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,at);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 it(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 ct(t){return this instanceof ct?(this.v=t,this):new ct(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 ct?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 it=="function"?it(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
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(g){e={error:g}}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(g){s=g instanceof Ln?g.errors:[g]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var m=at(p),f=m.next();!f.done;f=m.next()){var y=f.value;try{Zr(y)}catch(g){s=s??[],g instanceof Ln?s=cn(cn([],an(s)),an(g.errors)):s.push(g)}}}catch(g){r={error:g}}finally{try{f&&!f.done&&(o=m.return)&&o.call(m)}finally{if(r)throw r.error}}}if(s)throw new Ln(s)}},t.prototype.add=function(e){var n;if(e&&e!==this)if(this.closed)Zr(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}(),$r=Dt.EMPTY;function Vr(t){return t instanceof Dt||t&&"closed"in t&&W(t.remove)&&W(t.add)&&W(t.unsubscribe)}function Zr(t){W(t)?t():t.unsubscribe()}var zr={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},Gr={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=Gr.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(t)},delegate:void 0};function Br(t){Gr.setTimeout(function(){throw t})}function qr(){}function dn(t){t()}var jn=function(t){je(e,t);function e(n){var r=t.call(this)||this;return r.isStopped=!1,n?(r.destination=n,Vr(n)&&n.add(r)):r.destination=nc,r}return e.create=function(n,r,o){return new $n(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),Xi=Function.prototype.bind;function Un(t,e){return Xi.call(t,e)}var ec=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}(),$n=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&&Un(n.next,c),error:n.error&&Un(n.error,c),complete:n.complete&&Un(n.complete,c)}):i=n}return s.destination=new ec(i),s}return e}(jn);function pn(t){Br(t)}function tc(t){throw t}var nc={closed:!0,next:qr,error:tc,complete:qr},Vn=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function rc(t){return t}function oc(t){return t.length===0?rc: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=ac(e)?e:new $n(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=Yr(n),new n(function(o,s){var i=new $n({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[Vn]=function(){return this},t.prototype.pipe=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return oc(e)(this)},t.prototype.toPromise=function(e){var n=this;return e=Yr(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 Yr(t){var e;return(e=t??zr.Promise)!==null&&e!==void 0?e:Promise}function sc(t){return t&&W(t.next)&&W(t.error)&&W(t.complete)}function ac(t){return t&&t instanceof jn||sc(t)&&Vr(t)}function ic(t){return W(t==null?void 0:t.lift)}function cc(t){return function(e){if(ic(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 lc(t,e,n,r,o){return new uc(t,e,n,r,o)}var uc=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}(jn),dc=ln(function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),Wr=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 Hr(this,this);return r.operator=n,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new dc},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?$r:(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 Hr(n,r)},e}(xe),Hr=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:$r},e}(Wr),pc={now:function(){return Date.now()},delegate:void 0},fc=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),Kr={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},mc=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),Kr.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&&Kr.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}(fc),Jr=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=pc.now,t}(),hc=function(t){je(e,t);function e(n,r){r===void 0&&(r=Jr.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}(Jr),yc=new hc(mc),_c=function(t){return t&&typeof t.length=="number"&&typeof t!="function"};function gc(t){return W(t==null?void 0:t.then)}function vc(t){return W(t[Vn])}function wc(t){return Symbol.asyncIterator&&W(t==null?void 0:t[Symbol.asyncIterator])}function bc(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 Ec(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var kc=Ec();function Cc(t){return W(t==null?void 0:t[kc])}function Sc(t){return Ji(this,arguments,function(){var n,r,o,s;return Ur(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 Pc(t){return W(t==null?void 0:t.getReader)}function Ac(t){if(t instanceof xe)return t;if(t!=null){if(vc(t))return Tc(t);if(_c(t))return Ic(t);if(gc(t))return xc(t);if(wc(t))return Qr(t);if(Cc(t))return Rc(t);if(Pc(t))return Nc(t)}throw bc(t)}function Tc(t){return new xe(function(e){var n=t[Vn]();if(W(n.subscribe))return n.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Ic(t){return new xe(function(e){for(var n=0;n<t.length&&!e.closed;n++)e.next(t[n]);e.complete()})}function xc(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,Br)})}function Rc(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 Qr(t){return new xe(function(e){Oc(t,e).catch(function(n){return e.error(n)})})}function Nc(t){return Qr(Sc(t))}function Oc(t,e){var n,r,o,s;return Ki(this,void 0,void 0,function(){var i,c;return Ur(this,function(l){switch(l.label){case 0:l.trys.push([0,5,6,11]),n=Qi(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 Mc(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 Dc(t,e){var n=W(t)?t:function(){return t},r=function(o){return o.error(n())};return new xe(r)}var Fc=ln(function(t){return function(){t(this),this.name="EmptyError",this.message="no elements in sequence"}});function Lc(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 Fc)}})})}function jc(t){return t instanceof Date&&!isNaN(t)}var Uc=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 $c(t,e){var n=jc(t)?{first:t}:typeof t=="number"?{each:t}:t,r=n.first,o=n.each,s=n.with,i=s===void 0?Vc:s,c=n.scheduler,l=c===void 0?yc:c,u=n.meta,d=u===void 0?null:u;if(r==null&&o==null)throw new TypeError("No timeout provided.");return cc(function(p,m){var f,y,g=null,A=0,k=function(x){y=Mc(m,l,function(){try{f.unsubscribe(),Ac(i({meta:d,lastValue:g,seen:A})).subscribe(m)}catch(R){m.error(R)}},x)};f=p.subscribe(lc(m,function(x){y==null||y.unsubscribe(),A++,m.next(g=x),o>0&&k(o)},void 0,void 0,function(){y!=null&&y.closed||y==null||y.unsubscribe(),g=null})),!A&&k(r!=null?typeof r=="number"?r:+r-l.now():o)})}function Vc(t){throw new Uc(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:()=>Dc(()=>new Error(e.timeoutErrMsg))};return Lc(this._subject.pipe($c(n)))},this._current={status:"initial",isSuccess:!1},this._subject=new Wr}get current(){return this._current}}const Xr=a.enum(["dev","stg","prod"]),Zc={prod:"https://connto.getopenpay.com",stg:"https://connto.openpaystaging.com",dev:"http://localhost:8000"},zc=t=>Zc[t],Zn={},eo=async t=>{if(Zn[t])return Zn[t];try{const e=await fetch(new URL("/health/environment",t)).then(r=>r.json()),n=Xr.parse(e.environment);return Zn[t]=n,n}catch{return Xr.Values.prod}};function fn(t){throw new Error(`Unhandled case: ${t}`)}const to=(t,e)=>Object.fromEntries(Object.entries(t).filter(([n])=>!e.includes(n))),$=()=>{if(!(typeof window>"u"))return window},zn=new Ft,no="op_metrics_queue",Gc=3,Bc=3,qc=1e3,{log__:mn}=F("op-metrics");class Yc{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(no);r&&(this.queue=JSON.parse(r))}catch{this.queue=[],this.saveQueueToStorage()}}saveQueueToStorage(){var e;(e=$())==null||e.localStorage.setItem(no,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()},qc))}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,Bc);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<Gc);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 ro=new Yc,E=(t,e,n)=>{ro.addEvent(t,e,n)},oo=t=>{const e=re(t.reason);E("unhandled_rejection_error",{error_message:e,error_name:t.reason})},so=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})},Wc=()=>{var t,e;(t=$())==null||t.addEventListener("error",so),(e=$())==null||e.addEventListener("unhandledrejection",oo)},Hc=()=>{var t,e;(t=$())==null||t.removeEventListener("error",so),(e=$())==null||e.removeEventListener("unhandledrejection",oo)};(Ko=$())==null||Ko.addEventListener("beforeunload",()=>{ro.processQueue()});class ao extends ji{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(Jc(o))throw new ao(o);if(!Kc(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},Kc=(t,e)=>e.safeParse(t).success,Jc=t=>hi.safeParse(t).success,Qc=async(t,e)=>await J(t,{type:"get_checkout_preview",payload:e},Ar),B=async t=>await J(t,{type:"get_prefill",payload:{}},Ir),ct=async(t,e)=>await J(t,{type:"v2_start_payment_flow",payload:e},Rr,"start_payment_flow"),Xc=async(t,e)=>await J(t,{type:"start_payment_flow_for_cc",payload:e},xi,"start_payment_flow_for_cc"),el=async(t,e)=>{E("start_payment_flow_for_pr",{...e});const n=await J(t,{type:"start_payment_flow_for_pr",payload:e},Rr);return E("start_payment_flow_for_pr_result",{...n}),n},se=async(t,e)=>await J(t,{type:"confirm_payment_flow",payload:e},Ra,"confirm_payment_flow"),tl=async(t,e)=>await J(t,{type:"finalize_setup_payment_method",payload:e},xr,"finalize_setup_payment_method"),nl=async(t,e)=>await J(t,{type:"check_if_popup_window_verified",payload:e},xa,"check_if_popup_window_verified"),rl=async(t,e,n)=>{const r=await Qc(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=Mi(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 rl(t,e,r);return{amountAtom:o.amountAtom,currency:o.currency}}},ol=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},Aa)))},io=async(t,e)=>await J(t,{type:"checkout_card_elements",payload:e},In,"checkout_card_elements"),sl=async(t,e)=>await J(t,{type:"setup_payment_method",payload:e},xr,"setup_checkout"),Gn=async(t,e)=>await J(t,{type:"checkout",payload:e},In,"perform_checkout"),co=1e3,al=async(t,e)=>{console.log(e);const r=await Er({iframe:t,debug:!0,timeout:co,childOrigin:"*"}).promise,o=await J(r,{type:"ping-3ds-status"},Ta);return console.log("🟢 CDE connection successful! Stopping polling... Result:",o),o},Bn=async(t,e)=>await J(t,{type:"prepare_payment_flow",payload:e},Ni,"prepare_payment_flow"),lo=async(t,e)=>{try{return(await J(t,{type:"get_standardized_error_code",payload:{message:e}},Ri)).error_code}catch(n){return console.error("[cde-client] Error during getStandardizedErrorCode:",re(n)),"PAYMENT_FAILED_GENERIC"}},il=async(t,e)=>await J(t,{type:"set_user_device_token",payload:{device_token:e}},Oi),pe=a.enum(["stripe","airwallex","authorize_net"]);pe.Enum.stripe;const uo=({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})})},po=()=>uo({scriptId:"__op_internal_apple_pay_sdk",src:"https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",checkLoadedFn:()=>!!window.ApplePaySession||!!window.ApplePaySDK}),fo=(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 cl=({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}`}},ll=({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}}},mo=({overridePaymentRequest:t,initialPreview:e,prefill:n,defaultLabel:r})=>{const{currencyCode:o,total:s}=ll({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:cl({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__:ho}=F("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 ho("No CPMs found for model. All models:",t),new Error("No CPMs found for model");return e.parse(n)},yo=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}=F(t.logPrefix),n=await B(t.anyCdeConnection),r=Lt(t.confirmResult);if(n.mode==="setup")return e("Setting up payment method..."),{mode:"setup",result:await tl(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 ho("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 Gn(t.anyCdeConnection,o)}}},ul="@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}",_o=t=>{const e=document.createElement("template");e.innerHTML=`
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=it(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=it(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=it(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,ct(n.read())];case 3:return r=i.sent(),o=r.value,s=r.done,s?[4,ct(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,ct(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=it(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))),z=()=>{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=z())==null||e.addEventListener("offline",this.offlineListener),(n=z())==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=z())==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=z())==null||e.localStorage.setItem(to,JSON.stringify(this.queue))}scheduleBatchProcessing(){const e=z();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=z())==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=z())==null||e.removeEventListener("offline",this.offlineListener),(n=z())==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=z())==null||t.addEventListener("error",oo),(e=z())==null||e.addEventListener("unhandledrejection",ro)},Wc=()=>{var t,e;(t=z())==null||t.removeEventListener("error",oo),(e=z())==null||e.removeEventListener("unhandledrejection",ro)};(Ho=z())==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),lt=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}},ut=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__:td,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
- ${ul}
14
+ ${ll}
15
15
  </style>
16
16
  <div class="overlay">
17
17
  <div class="container">
@@ -19,10 +19,10 @@ ${t.message}`),t.message)}else return Tn(t.message);if(typeof t=="object")try{re
19
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 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 dl(t,e,n){const r=async()=>{try{const s=await al(t,n);s&&(clearInterval(o),e(s))}catch{}};r();const o=setInterval(r,co);return o}function pl({elements:t,pollingInterval:e,resolve:n}){const r=()=>{clearInterval(e),t.host.remove(),n({status:G.CANCELLED})};return t.cancelButton.addEventListener("click",r),()=>{t.cancelButton.removeEventListener("click",r)}}async function hn(t){const{url:e,baseUrl:n}=t,r=_o(e);return new Promise(o=>{const s=l=>{setTimeout(()=>{r.host.remove()},1e3),o(l),c==null||c()},i=dl(r.iframe,s,new URL(n).origin),c=pl({elements:r,pollingInterval:i,resolve:o})})}const go=async t=>{const e=await hn(t);if(e.status===G.CANCELLED)throw new Error("3DS verification cancelled");if(e.status===G.FAILURE)throw new Error("3DS verification failed");return e.status!==G.SUCCESS&&fn(e.status),{href:e.href}},fl=(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},vo=async(t,e,n,r)=>{const{err__:o}=F("popup-verify");return new Promise((s,i)=>{const c=fl(t,r),l=setInterval(async()=>{try{const u=await nl(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__:ml,err__:qn}=F("airwallex-cc"),hl=a.object({"op-airwallex-3ds-url":a.string(),"op-airwallex-initial-intent-id":a.string(),"op-airwallex-consent-id":a.string()}),yl=t=>{const e=hl.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 qn(r),new Error(n)}return e.data},_l=t=>(t==null?void 0:t["op-airwallex-3ds-url"])!==void 0,gl=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 ml(`Airwallex 3DS verification success. [Intent ID: ${e}]`),e}catch(e){const n="Error verifying Airwallex 3DS verification result.";throw qn(n,`Resulting URL: ${t}.
23
- Error: ${re(e)}`),new Error(n)}},vl=async(t,e)=>{const n=yl(e),r=await go({url:n["op-airwallex-3ds-url"],baseUrl:t}),o=gl(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 qn(l),new Error(c)}return{existing_cc:{initial_intent_id:o,consent_id:n["op-airwallex-consent-id"]}}},wo=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()})}),bo=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__:Eo,err__:ko}=F("common-cc"),Re=(t,e,n)=>{if(n){Eo(`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=hr(o);for(const[i,c]of Object.entries(s))e(i,c,i);throw ko("Got validation errors in non-CDE form fields",s),new Error("Got validation errors in non-CDE form fields")}return r.data},wl=(t,e)=>{for(const n of t)if(n.success===!1)throw n.errors.forEach(r=>{const o=fr.safeParse(r.elementType);if(!o.success)ko(`Unknown field name in onValidationError: ${r.elementType}. Error object:`,r);else{const s=o.data;e(s,r.errors)}}),Eo(`Error tokenizing card: got validation errors: ${JSON.stringify(n.errors)}`),new Error("Got validation errors while tokenizing card")},{log__:yn}=F("awx-apple-pay");async function bl(t,e){try{const r=(await Bn(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 El(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===G.CANCELLED)throw new Error("3DS verification cancelled");if(n===G.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 kl(t,e){var n,r,o,s,i;try{const c=t.payment,l=fo(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 f=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",f);let y=(r=(n=f.payment_methods)==null?void 0:n[0])==null?void 0:r.id;const g=(o=f.required_user_actions)==null?void 0:o.find(k=>k.type==="airwallex_payment_consent");if(g!=null&&g.redirect_url&&g.consent_id&&g.their_pm_id&&(f=await El(g,e),y=(i=(s=f.payment_methods)==null?void 0:s[0])==null?void 0:i.id),!y)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:f,usePayFirstFlow:!1})}catch(c){const l={status:ApplePaySession.STATUS_FAILURE};throw e.session.completePayment(l),c}}const{log__:Ut,err__:Co}=F("awx-apple-pay"),Cl=Ge(async({context:t,formCallbacks:e})=>{const n={processor:pe.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ae(t.checkoutPaymentMethods,wo);if(!r)return n;if(Ut("Loading Apple Pay script"),await po(),!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 B(i),l=c.mode==="setup",u=await lt(i,c.token,l,void 0),d=async p=>{try{await U.airwallexApplePay.run({context:t,checkoutPaymentMethod:r,nonCdeFormInputs:oe(t.formDiv),formCallbacks:e,customParams:{...p,initialPreview:u},initResult:void 0})}catch(m){Co("Apple Pay payment error",m),e.get.onCheckoutError((m==null?void 0:m.message)??"Unknown error")}};return{processor:pe.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),Sl=Ee(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,customParams:r,formCallbacks:o})=>{var y;const s=ae(t.checkoutPaymentMethods,wo),{overridePaymentRequest:i,initialPreview:c}=r,l=t.anyCdeConnection,u=await B(l),d=u.mode==="setup",p=mo({overridePaymentRequest:i,initialPreview:c,prefill:{...u},defaultLabel:(y=s==null?void 0:s.metadata)==null?void 0:y.processor_account_name}),m=new ApplePaySession(3,p),f={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:to(u,["brand"]),overridePaymentRequest:i}),new Promise((g,A)=>{const k=()=>{Ut("Payment cancelled by user"),A(new Error("Payment cancelled by user"))};m.oncancel=k,m.onvalidatemerchant=async x=>{try{await bl(x,f)}catch(R){A(R)}},m.onpaymentmethodselected=()=>{const x={newTotal:{...p.total}};m.completePaymentMethodSelection(x)},m.onpaymentauthorized=async x=>{E("apple_pay_payment_authorized");try{const R=await kl(x,f);g(R)}catch(R){A(R)}},m.begin()}).catch(g=>{throw Co("Apple Pay payment error",g),E("apple_pay_payment_error",{error:g}),g})}),_n=({gateway:t,gatewayMerchantId:e,merchantName:n,merchantId:r,initialPreview:o,overridePaymentRequest:s,prefill:i})=>{var p,m;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=(((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},So=()=>uo({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 Yn=null;const Po=async t=>await eo(t)==="prod"?"PRODUCTION":"TEST",gn=async(t,e)=>{const n=await Po(t);return Yn===null&&(Yn=new window.google.payments.api.PaymentsClient({environment:n,merchantInfo:e.merchantInfo})),Yn},Pl=t=>{const e=t.required_user_actions.find(n=>n.type==="airwallex_payment_consent");return e?mr.parse(e):null},Ao=(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 p=n[h.FIRST_NAME]||l||"",m=n[h.LAST_NAME]||d||"";p||m?(n[h.FIRST_NAME]=p,n[h.LAST_NAME]=m):(n[h.FIRST_NAME]="_OP_UNKNOWN",n[h.LAST_NAME]="")}return n},{log__:fe,err__:ut}=F("awx-google-pay"),Al=Ge(async({context:t,formCallbacks:e})=>{var p,m;const n={processor:pe.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ae(t.checkoutPaymentMethods,bo);if(!r)return n;fe("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(fe("Loading Google Pay script"),await So(),!((m=(p=window.google)==null?void 0:p.payments)!=null&&m.api))return ut("Google Pay SDK not loaded properly"),n;if(await Po(t.baseUrl)==="PRODUCTION"&&!o.google_pay_merchant_id)return ut("Google Pay merchant ID is required for production environment"),n;fe("Google Pay SDK loaded",window.google.payments);try{const f=_n({gateway:"airwallex",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),y=await gn(t.baseUrl,f),{result:g}=await y.isReadyToPay(f);if(!g)return fe("Google Pay is not available for this user"),n}catch(f){return ut("Error checking Google Pay availability",f),n}const i=t.anyCdeConnection,c=await B(i),l=c.mode==="setup",u=await lt(i,c.token,l,void 0),d=async f=>{try{U.airwallexGooglePay.run({context:t,checkoutPaymentMethod:r,nonCdeFormInputs:oe(t.formDiv),formCallbacks:e,initResult:void 0,customParams:{...f,initialPreview:u}})}catch(y){ut("Google Pay payment error",y),e.get.onCheckoutError((y==null?void 0:y.message)??"Unknown error")}};return{processor:pe.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),Tl=Ee(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o})=>{var f,y,g,A,k,x,R;fe("Starting Google Pay flow...");const s=ae(t.checkoutPaymentMethods,bo),{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,p=await B(d);E("google_pay_flow_started",{processor_name:s.processor_name,prefill:to(p,["brand"]),overridePaymentRequest:c});const m=await gn(t.baseUrl,u);try{const M=await m.loadPaymentData(u);fe("Google Pay Payment data",M);const V=Ao(n,M),z=Re(V,r.get.onValidationError,o==null?void 0:o.defaultFieldValues);E("billing_details_received",{...z});const ie=(y=(f=M.paymentMethodData)==null?void 0:f.tokenizationData)==null?void 0:y.token;if(!ie)throw new Error("No payment token received from Google Pay");const wn=await ct(d,{payment_provider:e.provider,checkout_payment_method:e,new_customer_email:z[h.EMAIL],new_customer_first_name:z[h.FIRST_NAME],new_customer_last_name:z[h.LAST_NAME],new_customer_address:{zip_code:z[h.ZIP_CODE],country:z[h.COUNTRY]}}),bn=Pl(wn);fe("Start flow next actions",bn);let We=await se(d,{secure_token:p.token,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:bn==null?void 0:bn.consent_id,airwallex_payment_method_data:{type:"googlepay",googlepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:ie}}}});fe("[1st] Confirm payment flow response",We);let Jn=(A=(g=We.payment_methods)==null?void 0:g[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){fe("3DS Required, starting verification...",He);const{status:Gt}=await hn({url:He.redirect_url,baseUrl:t.baseUrl});if(fe(`╰ 3DS verification completed [Status: ${Gt}]`),Gt===G.CANCELLED)throw new Error("3DS verification cancelled");if(Gt===G.FAILURE)throw new Error("3DS verification failed")}if(He&&!Jn&&(We=await se(d,{secure_token:p.token,their_pm_id:He.their_pm_id,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:He.consent_id}}),fe("[2nd] Confirm payment flow response",We),Jn=(R=(x=We.payment_methods)==null?void 0:x[0])==null?void 0:R.id),!Jn)throw new Error("No PM ID found");return jt({logPrefix:"awx-googlepay",anyCdeConnection:d,checkoutPaymentMethod:e,requiredFormFields:z,confirmResult:We,usePayFirstFlow:!1})}catch(M){throw ut("Google Pay payment error",M),E("google_pay_payment_error",{error:M}),new Error((M==null?void 0:M.message)??"Unknown error")}}),To=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()})}),Io=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 Il(t,e){try{const r=(await Bn(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 xl(t,e){var n,r;try{const o=t.payment,s=fo(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__:xo}=F("authnet-applepay"),Rl=Ge(async({context:t,formCallbacks:e})=>{const n={processor:pe.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ae(t.checkoutPaymentMethods,To);if(!r)return n;if(vn("Loading Apple Pay script"),await po(),!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 B(i),l=c.mode==="setup",u=await lt(i,c.token,l,void 0),d=async p=>{try{await U.authorizeNetApplePay.run({context:t,checkoutPaymentMethod:r,nonCdeFormInputs:oe(t.formDiv),formCallbacks:e,customParams:{...p,initialPreview:u},initResult:void 0})}catch(m){xo("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:pe.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:d}}),Nl=Ee(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,customParams:r,formCallbacks:o})=>{var y;const{initialPreview:s,overridePaymentRequest:i}=r,c=ae(t.checkoutPaymentMethods,To),l=t.anyCdeConnection,u=await B(l),d=u.mode==="setup",p=mo({overridePaymentRequest:i,initialPreview:s,prefill:u,defaultLabel:(y=c==null?void 0:c.metadata)==null?void 0:y.processor_account_name});E("apple_pay_flow_started",{processor_name:e.processor_name,prefill:u,overridePaymentRequest:i});const m=new ApplePaySession(3,p),f={session:m,connection:t.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:n,processorAccount:e.metadata,prefill:u,isSetupMode:d,baseUrl:t.baseUrl,formCallbacks:o};return new Promise((g,A)=>{m.oncancel=()=>{vn("Payment cancelled by user"),A(new Error("Payment cancelled by user"))},m.onvalidatemerchant=async k=>{try{await Il(k,f)}catch(x){A(x)}},m.onpaymentmethodselected=()=>{const k={newTotal:p.total};m.completePaymentMethodSelection(k)},m.onpaymentauthorized=async k=>{E("apple_pay_payment_authorized");try{const x=await xl(k,f);g(x)}catch(x){A(x)}},m.begin()}).catch(g=>{throw xo("Apple Pay payment error",g),E("apple_pay_payment_error",{error:g}),g})}),{log__:Be,err__:$t}=F("authnet-googlepay"),Ol=Ge(async({context:t,formCallbacks:e})=>{var d,p;Be("Initializing Authnet GooglePay flow");const n={processor:pe.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ae(t.checkoutPaymentMethods,Io);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 So(),!((p=(d=window.google)==null?void 0:d.payments)!=null&&p.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"}}),f=await gn(t.baseUrl,m),{result:y}=await f.isReadyToPay(m);if(!y)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 B(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(f){$t("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:pe.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:u}}),Ml=Ee(async({context:t,nonCdeFormInputs:e,checkoutPaymentMethod:n,formCallbacks:r,customParams:o})=>{var f,y,g,A;const{initialPreview:s,overridePaymentRequest:i}=o,l=ae(t.checkoutPaymentMethods,Io).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,p=await B(d);E("google_pay_flow_started",{processor_name:n.processor_name,prefill:p,overridePaymentRequest:i});const m=await gn(t.baseUrl,u);try{const k=await m.loadPaymentData(u);Be("Google Pay Payment data",k);const x=Ao(e,k),R=Re(x,r.get.onValidationError);E("billing_details_received",{...R});const M=(y=(f=k.paymentMethodData)==null?void 0:f.tokenizationData)==null?void 0:y.token;if(!M)throw new Error("No payment token received from Google Pay");const V=await ct(d,{payment_provider:n.provider,checkout_payment_method:n,new_customer_email:R[h.EMAIL],new_customer_first_name:R[h.FIRST_NAME],new_customer_last_name:R[h.LAST_NAME],new_customer_address:{zip_code:R[h.ZIP_CODE],country:R[h.COUNTRY]}});Be("Start payment flow response",V);const z=await se(d,{secure_token:p.token,processor_specific_metadata:{payment_provider:n.provider,mobile_wallet_payment_data:{dataDescriptor:"COMMON.GOOGLE.INAPP.PAYMENT",dataValue:window.btoa(M)}}});if(!((A=(g=z.payment_methods)==null?void 0:g[0])==null?void 0:A.id))throw new Error("No PM ID found");return jt({logPrefix:"authnet-googlepay",anyCdeConnection:d,checkoutPaymentMethod:n,requiredFormFields:R,confirmResult:z,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__:Dl,err__:Ro}=F("pockyt-cc"),Fl=a.object({"op-pockyt-3ds-url":a.string(),"op-pockyt-txn-no":a.string(),"op-pockyt-ref-no":a.string()}),Ll=t=>{const e=Fl.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 Ro(r),new Error(n)}return e.data},No=t=>{try{const e=new URL(t??"").searchParams.get("vaultId");if(!e)throw new Error("No vault ID found in 3DS verification result");return Dl(`3DS verification success. [Vault ID: ${e}]`),e}catch(e){const n="Error verifying 3DS verification result.";throw Ro(n,`Resulting URL: ${t}.
24
- Error: ${re(e)}`),new Error(n)}},Wn=(t,e)=>new URL(t).searchParams.get(e),jl=t=>(t==null?void 0:t["op-pockyt-3ds-url"])!==void 0,Ul=async(t,e)=>{const n=Ll(e),r=await go({url:n["op-pockyt-3ds-url"],baseUrl:t});return{existing_cc:{vault_id:No(r.href??""),transaction_no:n["op-pockyt-txn-no"],reference_no:n["op-pockyt-ref-no"]}}},$l=a.enum(["test","live","live-us","live-in","live-apse","live-au"]),Vl=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}=F("adyen-cc"),Zl=a.object({"op-account-id":a.string(),"op-adyen-client-key":a.string(),"op-adyen-environment":$l,"op-adyen-action":a.string()}),Oo="Unable to process your credit card. Please contact support for assistance.",zl=t=>{const e=Zl.safeParse(t);if(!e.success)throw Vt(`Adyen 3DS is required but headers are malformed. Got: ${JSON.stringify(t)}`),new Error(Oo);return e.data},Gl=t=>JSON.parse(t),Mo=()=>"AdyenWeb"in window&&"AdyenCheckout"in window.AdyenWeb,Bl=async()=>{dt("Waiting for Adyen SDK to load...");for(let t=0;t<10;t++)Mo()||await tn(500);if(!Mo())throw Vt("Adyen SDK not loaded properly"),new Error(Oo);return dt("Adyen SDK loaded successfully"),window.AdyenWeb.AdyenCheckout},ql=t=>{const{headers:e,locale:n,countryCode:r,component:o,host:s,cancelButton:i}=t,c=Gl(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=y=>{Vt("Authentication failed. Result:",y),l({status:G.FAILURE,cleanup:u})},p=y=>{Vt("Adyen error:",y),l({status:G.FAILURE,cleanup:u})},m=()=>{l({status:G.CANCELLED,cleanup:u})};i.addEventListener("click",m);const f=(y,g,A)=>{s.remove(),l({status:G.SUCCESS,additionalDetails:y,cleanup:u})};Bl().then(y=>y({clientKey:e["op-adyen-client-key"],environment:e["op-adyen-environment"],locale:n,countryCode:r,onAdditionalDetails:f,onPaymentFailed:d,onError:p})).then(y=>{y.createFromAction(c,{challengeWindowSize:"03"}).mount(o)})})},Yl=t=>{const e=navigator.languages&&navigator.languages.length?navigator.languages[0]:navigator.language,n=t??e,r=Vl.safeParse(n);return r.success?(dt(`Resolved locale: ${r.data}`),r.data):(Vt(`Resolved invalid locale: ${n}. Defaulting to en-US.`),"en-US")},Wl=t=>(t==null?void 0:t["op-adyen-action"])!==void 0,Hl=async(t,e,n)=>{const r=zl(e),o=document.createElement("div");o.id="adyen-container";const{host:s,iframe:i,cancelButton:c}=_o("http://example.com");i.replaceWith(o);const l=await ql({headers:r,locale:Yl(n),countryCode:t,component:o,host:s,cancelButton:c});if(l.cleanup(),l.status===G.FAILURE)throw new Error("3DS verification failed");if(l.status===G.CANCELLED)throw new Error("3DS verification cancelled");if(l.status===G.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__:L,err__:Do}=F("common-cc"),{log__:Fo}=F("stripe-cc");a.array(a.object({our_existing_pm_id:a.string()})).length(1);const Kl=Ee(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o})=>{var u;L("├ Running common CC flow...",{checkoutPaymentMethod:e});const s=t.anyCdeConnection,i=await B(s);E("common_cc_flow_started",{...e,prefill:i}),L(`├ 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{L(`├ Tokenizing card info in CDE [Session: ${t.elementsSessionId}]`);const d=await ol(o.currentCdeConnections,{session_id:t.elementsSessionId});if(wl(d,r.get.onValidationError),i.mode==="setup"){L(`├ Setting up payment method in CDE [Token: ${i.token}]`);const p=await sl(s,l);return L(`╰ Setup completed successfully [PM ID: ${p.payment_method_id}]`),{mode:"setup",result:p}}else{L(`├ Initial checkout flow. Checking out card info in CDE [Session: ${t.elementsSessionId}]`);const p=await io(s,l);return L("╰ Checkout completed successfully."),{mode:"checkout",result:p}}}catch(d){if(d instanceof ao&&d.originalErrorMessage.includes("3DS_REQUIRED")){L("├ Card requires 3DS, starting non-legacy payment flow"),L("Received 3DS error response headers:",d.response.headers),E("3ds_required",{...e,...d.response.headers});const p=jl(d.response.headers);if(p){L("├ Pockyt 3DS case detected. Going through Pockyt 3DS flow.");const k=await Ul(t.baseUrl,d.response.headers);l.extra_metadata.pockyt=k}if(_l(d.response.headers)){L("├ Airwallex 3DS case detected. Going through Airwallex 3DS flow.");const k=await vl(t.baseUrl,d.response.headers);l.extra_metadata.airwallex=k}if(Wl(d.response.headers)){L("├ Adyen 3DS case detected. Going through Adyen 3DS flow.");const k=await Hl(n[h.COUNTRY],d.response.headers,i.locale);l.extra_metadata.adyen=k}const y=await Xc(s,l);L("├ Payment flow result:",y);const g=((u=d.response.headers)==null?void 0:u["op-should-use-new-flow"])!=="true";p?L("├ Pre-start 3DS is successful, other 3DS flows will be skipped."):g?(L("├ Using stripe 3DS flow"),await tu(y)):(L("├ Using common 3DS flow"),await eu(y,t.baseUrl));const A=y.cc_pm_id;if(i.mode==="setup"){L(`├ Confirming payment flow [cc_pm_id: ${A}]`);const k=await se(s,{secure_token:i.token,existing_cc_pm_id:A});L("├ Confirm payment flow result received Result:",k);const x=Lt(k);return L(`╰ Setup completed successfully [PM ID: ${x.payment_method_id}]`),{mode:"setup",result:x}}else{L(`├ Checking out after 3DS flow [Flow: ${g?"legacy":"new"}]`);const k=await io(s,{...l,existing_cc_pm_id:A,do_not_use_legacy_cc_flow:g});return L("╰ Checkout completed successfully."),{mode:"checkout",result:k}}}throw Do("╰ Error checking out card info in CDE"),Do(d),d}}),Jl=t=>{const e=t.required_user_actions.find(n=>n.type==="stripe_3ds");if(!e)throw new Error("No stripe 3DS action found");return Na.parse(e)},Ql=["airwallex_payment_consent","adyen"],Xl=t=>{const e=t.required_user_actions.find(n=>Ql.includes(n.type));if(!e)throw new Error("No common 3DS action found");return Ia.parse(e)},eu=async(t,e)=>{const n=Xl(t);if(n.redirect_url==="3DS_COMPLETE"){L("├ 3DS flow completed successfully"),E("3ds_complete");return}L(`├ Using common 3DS flow [URL: ${n.redirect_url}]`),E("3ds_redirect",{...n});const{status:r}=await hn({url:n.redirect_url,baseUrl:e});if(L(`╰ 3DS verification completed [Status: ${r}]`),r===G.CANCELLED)throw E("3ds_cancelled"),new Error("3DS verification cancelled");if(r===G.FAILURE)throw E("3ds_failure"),new Error("3DS verification failed")},tu=async t=>{const e=Jl(t);E("3ds_stripe_redirect",{...e}),Fo(`├ Using stripe 3DS flow [Client Secret: ${e.client_secret.substring(0,8)}...]`),await Ua(e),E("3ds_stripe_complete"),Fo("╰ Stripe 3DS flow completed successfully")},nu=1,ru=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__:Lo}=F("loop-crypto"),ou=a.object({loopFirstName:Z,loopLastName:Z,loopEmail:Z,[h.PROMOTION_CODE]:O}),su=a.object({loopFirstName:O,loopLastName:O,loopEmail:O,[h.PROMOTION_CODE]:O}),jo=(t,e,n,r)=>{const o=n.safeParse(t);if(!o.success){const s=o.error.format(),i=hr(s);for(const[c,l]of Object.entries(i))e(c,l,c);throw Lo("Got validation errors in non-CDE form fields",i),new Error("Got validation errors in non-CDE form fields")}return o.data},au=Ge(async({context:t})=>{te("Checking if there are any CPMs for Loop Crypto...");const e=ae(t.checkoutPaymentMethods,ru);te(`checkoutPaymentMethod: ${JSON.stringify(e)}`),te("Starting Loop Crypto flow...");const n=await B(t.anyCdeConnection),r=await Bn(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=nu: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}}),iu=Ee(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=jo(n,r.get.onValidationError,ou):s=jo(n,r.get.onValidationError,su);const i=t.anyCdeConnection,c=await B(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 p=Lt(d);return te(`╰ Setup completed successfully [PM ID: ${p.payment_method_id}]`),{mode:"setup",result:p}}else{if(te("Doing checkout..."),!d.pay_first_success_response)throw Lo("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__:ke,err__:Uo}=F("pockyt-paypal"),cu=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 lu=Ee(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o})=>{var z,ie;ke("Running Pockyt Paypal flow...");const s=t.anyCdeConnection,i=await B(s);ke("Verifying CPM...");const c=cu.parse(e);ke("├ 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=yo(u);ke(`Starting payment flow... Mode: ${i.mode}`);const p=Rt(),m=i.mode!=="setup",f={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:!!((z=o==null?void 0:o.settings)!=null&&z.useRedirectFlow),frontend_token_for_redirect_flow:p},...d},y=new URL("/app/pre-action/start/",t.baseUrl).toString(),g=btoa(JSON.stringify(f)),A=new URLSearchParams({st:i.token,r:g}),k=`${y}?${A.toString()}`;if((ie=o==null?void 0:o.settings)!=null&&ie.useRedirectFlow)throw ke("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.");ke("Starting popup mode for PayPal..."),ke("Opening paypal iframe...");const x=await vo("PayPal",s,p,k);ke("Paypal flow result",x);const R=No(x.href),M=Wn(x.href,"catt");if(!M)throw Uo("Checkout attempt ID not found in redirect URL:",x.href),new Error("Checkout attempt ID not found in redirect URL");ke(`Confirming payment flow using vault ID ${R}`);const V=await se(s,{secure_token:i.token,their_pm_id:R,checkout_attempt_id:m?M:void 0});if(ke("Confirm payment flow result",V),i.mode==="setup")return{mode:"setup",result:{payment_method_id:V.payment_methods[0].id}};if(!V.pay_first_success_response)throw Uo("Checkout failed, no pay-first success response:",V),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:V.pay_first_success_response}}),$o="ojs-stripe-link-btn",{log__:H,err__:uu}=F("stripe-link"),du=a.object({provider:a.literal("stripe_link"),processor_name:a.literal("stripe"),metadata:a.object({stripe_pk:a.string()})}),pu=a.array(a.object({our_existing_pm_id:a.string()})).length(1),fu=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,du);H("Starting stripe link flow...");const o=t.anyCdeConnection,s=await B(o),i=s.mode==="setup";H("Creating stripe elements...");const c=await lt(o,s.token,i,void 0),{elements:l,stripe:u}=await Da(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"}}),p=()=>{d.mount(`#${$o}`)},m=()=>{d.unmount()};return n!=null&&n.doNotMountOnInit?H("NOT mounting stripe link button (doNotMountOnInit is true)"):(H("Mounting stripe link button..."),p()),d.on("click",async f=>{if(H("Stripe Link button clicked"),n!=null&&n.overrideLinkSubmit&&!await n.overrideLinkSubmit()){H("Stripe Link submit aborted by overrideLinkSubmit");return}f.resolve()}),d.on("confirm",async f=>{H("Stripe Link window confirmed",f);const y=await u.createPaymentMethod({elements:l,params:{billing_details:f.billingDetails}});y.error?(uu("error",y.error),e.get.onCheckoutError(y.error.message??"Stripe Link unknown error")):(H("paymentMethod",y.paymentMethod),U.stripeLink.run({context:t,checkoutPaymentMethod:r,nonCdeFormInputs:oe(t.formDiv),formCallbacks:e,customParams:{stripePM:y.paymentMethod},initResult:{isAvailable:!0}}))}),{isAvailable:!0,controller:{mountButton:p,dismountButton:m,waitForButtonToMount:async()=>await yu($o)}}}),mu=Ee(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=hu(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=pu.parse(l.required_user_actions)[0].our_existing_pm_id,p=await B(s);if(p.mode==="setup"){H("Doing payment setup...");const m=await se(s,{secure_token:p.token,existing_cc_pm_id:d});return{mode:"setup",result:Lt(m)}}else{H("Doing checkout...");const m={secure_token:p.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:p.line_items,total_amount_atom:p.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await Gn(s,m)}}}),hu=(t,e)=>{var l,u,d,p,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]||((p=e.billing_details.address)==null?void 0:p.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},yu=t=>new Promise(e=>{const n=()=>{const r=document.getElementById(t);r?e(r):requestAnimationFrame(n)};n()}),{log__:ee,err__:_u}=F("stripe-pr"),gu=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()})}),vu=Ge(async({context:t,formCallbacks:e})=>{ee("Checking if there are any CPMs for Stripe PR...");const n=ae(t.checkoutPaymentMethods,gu);ee("Initializing Stripe PR flow...");const r=t.anyCdeConnection,o=await B(r),s=o.mode==="setup";ee("Getting initial preview amount");const i=await lt(r,o.token,s,void 0),c=await Fa(n.metadata.stripe_pk,i.amountAtom,i.currency,s);ee("Checking if can make payment");const l=await c.canMakePayment();if(l===null)return _u("canMakePayment returned null"),{isAvailable:!1,reason:"canMakePayment returned null"};ee("Stripe PR flow initialized successfully. Can make payment",l);const u=(d,p)=>U.stripePR.run({context:t,checkoutPaymentMethod:pt(t.checkoutPaymentMethods,d),nonCdeFormInputs:oe(t.formDiv),formCallbacks:e,customParams:{provider:d,overridePaymentRequest:p==null?void 0:p.overridePaymentRequest},initResult:{processor:pe.Enum.stripe,pr:c,isAvailable:!0,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}});return{processor:pe.Enum.stripe,isAvailable:!0,pr:c,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}}),wu=Ee(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 y=o.overridePaymentRequest;ee("Overriding PR amount with",y);const g=typeof y.applePayPaymentRequest=="function"?y.applePayPaymentRequest({}):y.applePayPaymentRequest;Eu(c,y.amount,y.pending,g,y.label)}ee("Showing PR dialog..."),c.show();const l=await La(c);ee("Stripe PM added event:",l),ee("Merging PM fields with form fields...");const u=bu(n,l),d=Re(u,r.get.onValidationError);E("billing_details_received",{...d}),ee("PR dialog finished. Starting payment flow...",d);const p=await el(i,{fields:d,checkoutPaymentMethod:e}),m=ku(p);ee("Confirming PR with Stripe..."),await ja(m,l);const f=await B(i);if(f.mode==="setup"){ee("Confirming payment flow for setup...");const y=await se(i,{secure_token:f.token});return{mode:"setup",result:Lt(y)}}else{ee("Performing checkout...");const y={secure_token:f.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:f.line_items,total_amount_atom:f.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await Gn(i,y)}}}),bu=(t,e)=>{var d,p,m,f;const n={...t},[r,...o]=((p=(d=e.payerName)==null?void 0:d.trim())==null?void 0:p.split(/\s+/))??[],s=o.join(" ")||void 0,i=(f=(m=e.paymentMethod)==null?void 0:m.billing_details)==null?void 0:f.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},Eu=(t,e,n,r,o)=>{t.update({total:{amount:e.amountAtom,label:o??"Total",pending:n},currency:e.currency,applePay:r})},ku=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 Oa.parse(t.required_user_actions[0])},{log__:qe,err__:Cu}=F("paypal"),Vo=a.object({provider:a.literal("paypal"),metadata:a.object({client_id:a.string()}),processor_name:a.literal("paypal")}),Su=async({context:t,formCallbacks:e})=>{const n=ae(t.checkoutPaymentMethods,Vo);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:{}})}},Pu=Ee(async({context:t,nonCdeFormInputs:e,checkoutPaymentMethod:n,formCallbacks:r,customParams:o})=>{var s,i;try{qe("Running PayPal flow...");const c=t.anyCdeConnection,l=await B(c),u=((s=o==null?void 0:o.settings)==null?void 0:s.useRedirectFlow)??!1,d=(i=o==null?void 0:o.settings)==null?void 0:i.defaultFieldValues;qe("Verifying CPM...");const p=Vo.parse(n);qe("├ Validating non-CDE form fields");const m=Re(e,r.get.onValidationError,d),f=yo(m);qe(`Starting payment flow... Mode: ${l.mode}`);const y=Rt(),g=l.mode!=="setup",A={payment_provider:p.provider,checkout_payment_method:p,use_pay_first_flow:g,pay_first_flow_cart_info:g?{line_items:l.line_items,displayed_total_amount_atom:l.amount_total_atom}:void 0,processor_specific_metadata:{use_paypal_redirect_flow:u,frontend_token_for_redirect_flow:y},...f},k=new URL("/app/pre-action/start/",t.baseUrl).toString(),x=btoa(JSON.stringify(A)),R=new URLSearchParams({st:l.token,r:x}),M=`${k}?${R.toString()}`;if(u)throw qe("Starting redirect mode for PayPal..."),window.location.href=M,await tn(20*1e3),new Error("Paypal flow timed out, please try again with another payment method.");const V=await vo("PayPal",c,y,M);qe("Paypal flow result",V);const z=Wn(V.href,"catt"),ie=Wn(V.href,"approval_session_id"),wn=await se(c,{secure_token:l.token,checkout_attempt_id:g?z:void 0,their_pm_id:g?ie:void 0});return qe("Confirm payment flow result",wn),jt({logPrefix:"paypal",anyCdeConnection:c,checkoutPaymentMethod:p,requiredFormFields:m,confirmResult:wn,usePayFirstFlow:g})}catch(c){throw Cu("PayPal payment error",c),E("checkout_error",{payment_method:"paypal",error:c}),new Error((c==null?void 0:c.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:Kl},stripePR:{init:vu,run:wu},stripeLink:{init:fu,run:mu},pockytPaypal:{run:lu},paypal:{init:Su,run:Pu},airwallexGooglePay:{init:Al,run:Tl},airwallexApplePay:{init:Cl,run:Sl},loopCrypto:{init:au,run:iu},authorizeNetApplePay:{init:Rl,run:Nl},authorizeNetGooglePay:{init:Ol,run:Ml}},{log__:Au,err__:Tu}=F("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);Au(`✔ ${t} flow initialized successfully. Result:`,o),n.set(o)}catch(o){Tu(`𝙭 ${t} flow initialization failed. Error:`,re(o),"Details:",o),n.throw(o,re(o))}}}},Iu=async(t,e,n)=>{await Promise.all(Object.values(t).map(r=>r.initialize({context:e,formCallbacks:n})))},xu=()=>({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__:Ru}=F("form-callbacks"),me=a.function().optional(),Zo=a.object({onFocus:me,onBlur:me,onChange:me,onLoad:me,onLoadError:me,onValidationError:me,onCheckoutStarted:me,onCheckoutSuccess:me,onSetupPaymentMethodSuccess:me,onCheckoutError:me,onPaymentRequestLoad:me}),Se=class Se{constructor(){this.setCallbacks=e=>{this._callbacks=Se.createEmptyCallbacks(),Object.entries(e).forEach(([n,r])=>{const o=na(n,r??Se.NOOP,Ru);this._callbacks[n]=o})},this._callbacks=Se.createEmptyCallbacks()}get get(){return{...this._callbacks}}};Se.NOOP=()=>{},Se.createEmptyCallbacks=()=>{const e={};return Object.keys(Zo.keyof().enum).forEach(n=>{e[n]=Se.NOOP}),e},Se.fromObject=e=>{const n=new Se;return n.setCallbacks(Zo.parse(e)),n};let Hn=Se;const zo="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Zt=32,Nu=16,Go=10,Bo=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 Ou(t){let e=Math.floor(t()*Zt);return e===Zt&&(e=Zt-1),zo.charAt(e)}function Mu(t){const e=Du(),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 Du(){return ju()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function Fu(t,e){let n="";for(;t>0;t--)n=Ou(e)+n;return n}function Lu(t,e=Go){if(isNaN(t))throw new zt(Ye.EncodeTimeValueMalformed,`Time must be a number: ${t}`);if(t>Bo)throw new zt(Ye.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${Bo}: ${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 ju(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function Uu(t,e){const n=Mu(),r=Date.now();return Lu(r,Go)+Fu(Nu,n)}const qo="op_analytics_device_token",$u=()=>{const t=document.cookie.split(";").find(n=>n.includes(qo));if(t)return t.split("=")[1];const e=Uu();return Vu(e),e},Vu=t=>{const e=new Date;e.setFullYear(e.getFullYear()+1),document.cookie=`${qo}=${t}; path=/; expires=${e.toUTCString()}`};function Zu(){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 Gu(){const t=Zu(),e=zu(t);return{framework:t,version:e}}class Bu{constructor(e,n,r,o){this.handleMessage=s=>{if(!s.source){console.warn("[OJS] No source found");return}if(Yo(s.origin)!==Yo(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=Ba(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 Yo=t=>new URL(t).origin;async function qu(t,e){const r=await Er({iframe:t,debug:!1,childOrigin:e}).promise,o=await fi(r);if(!mi(r,o))throw new Error("Got invalid CDE connection object");return r}class Yu{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 Wu=(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&&Wo("apple_pay",s,e,n,u)}},google_pay:{isLoading:!1,isAvailable:c,startFlow:async u=>{c&&Wo("google_pay",s,e,n,u)}}};n.get.onPaymentRequestLoad(l)}})},Wo=(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}),Ho="The secure form failed to load properly. Please check your internet connection, or try again later.",{log__:Ce,err__:he}=F("op-form"),Pe=class Pe{constructor(e){var o;this.isDestroyed=!1,this.cdeLoadEvent=new Ft,this.anyCdeConn=new Ft,this.context=new Ft,this.initFlows=xu(),this.startFormInit=async()=>{try{const s=this.createElement(ve.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"),Ce("CDE bridge element mounted"),Ce("Initializing OpenPay form:"),Ce("├ Waiting for CDE load event...");const i=await this.cdeLoadEvent.waitForLoad({timeoutSec:120,timeoutErrMsg:Ho});Ce("├ CDE load event received"),Ce("├ Waiting for CDE connection...");const c=await this.anyCdeConn.waitForLoad({timeoutSec:120,timeoutErrMsg:Ho});Ce("├ CDE connection received"),await il(c,this.deviceToken),Ce("├ Creating OJS context, setting up handlers...");const l=Pe.buildOjsFlowContext(this.config,i,c,this.getFormDiv());this.context.set(l),Wu(this.initFlows,l,this.formCallbacks),Ce("├ Starting OJS init flows..."),await Iu(this.initFlows,l,this.formCallbacks),this.formCallbacks.get.onLoad(i.totalAmountAtoms,i.currency),Ce("╰ Done initializing OJS flows."),E("form_loaded")}catch(s){const i=re(s);he("╰ 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===ve.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=oa.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={[ve.CARD]:void 0,[ve.CARD_NUMBER]:void 0,[ve.CARD_EXPIRY]:void 0,[ve.CARD_CVC]:void 0,[ve.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",$a(s.styles)),i.append("secureToken",this.config.checkoutSecureToken),i},this.connectToElement=s=>{qu(s.node).then(i=>{this.connectionManager.addConnection(s.type,i),!this.anyCdeConn.current.isSuccess&&s.type===ve.CDE_BRIDGE&&this.anyCdeConn.set(i)}).catch(i=>he("[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){he("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)){he("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){he("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){he("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){he("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){he("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){he("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;Ce("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)),Hc(),this.registeredElements=null,delete window.ojs,E("form_destroyed")},this.updateCallbacks=s=>{this.formCallbacks.setCallbacks(s)},Pe.assignAsSingleton(this),this.ojsVersion="0.3.1",this.ojsReleaseVersion="0.3.1",this.baseUrl=e.baseUrl??"https://cde.getopenpay.com",this.config={...e,baseUrl:this.baseUrl},this.formCallbacks=Hn.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 Yu,this.deviceToken=$u(),Wc();const{framework:n,version:r}=Gu();eo(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 Bu(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=Pe.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=`
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=Rt.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 lt(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 ut(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__:dt}=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 dt("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 dt("Google Pay SDK not loaded properly"),n;if(await So(t.baseUrl)==="PRODUCTION"&&!o.google_pay_merchant_id)return dt("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 dt("Error checking Google Pay availability",p),n}const i=t.anyCdeConnection,c=await G(i),l=c.mode==="setup",u=await ut(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(_){dt("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),$=Re(B,r.get.onValidationError,o==null?void 0:o.defaultFieldValues);E("billing_details_received",{...$});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 Hu=await lt(d,{payment_provider:e.provider,checkout_payment_method:e,new_customer_email:$[h.EMAIL],new_customer_first_name:$[h.FIRST_NAME],new_customer_last_name:$[h.LAST_NAME],new_customer_address:{zip_code:$[h.ZIP_CODE],country:$[h.COUNTRY]}}),wn=Sl(Hu);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:$,confirmResult:We,usePayFirstFlow:!1})}catch(L){throw dt("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 lt(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 ut(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 ut(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 lt(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 $=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=$.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:$,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__:pt,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()=>{pt("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 pt("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 pt(`Running Adyen 3DS flow for action type: ${c.type}`),new Promise(l=>{const u=()=>{pt("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?(pt(`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 pt("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:V,loopLastName:V,loopEmail:V,[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 lt(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 $,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:!!(($=o==null?void 0:o.settings)!=null&&$.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 ut(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 lt(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 ut(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:ft(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])},ku=()=>{const t=rt().split("-")[0];return{firstName:`xx_${t}`,lastName:`xx_${t}`,email:`xx_${t}@email.com`,zipCode:`xx_${t}`,country:"US"}},{log__:qe,err__:Cu}=D("paypal"),$o=a.object({provider:a.literal("paypal"),metadata:a.object({client_id:a.string()}),processor_name:a.literal("paypal")}),Su=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:{settings:{}}})}},Pu=be(async({context:t,nonCdeFormInputs:e,checkoutPaymentMethod:n,formCallbacks:r,customParams:o})=>{try{qe("Running PayPal flow...");const s=t.anyCdeConnection,i=await G(s),{isAnonymous:c,useRedirectFlow:l}=o.settings??{};qe("Verifying CPM...");const u=$o.parse(n);qe("├ Validating non-CDE form fields");const d=Re(e,r.get.onValidationError,c?ku():void 0),f=ho(d);qe(`Starting payment flow... Mode: ${i.mode}`);const m=rt(),p=i.mode!=="setup",_={payment_provider:u.provider,checkout_payment_method:u,use_pay_first_flow:p,pay_first_flow_cart_info:p?{line_items:i.line_items,displayed_total_amount_atom:i.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:i.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",s,m,x);qe("Paypal flow result",I);const L=Yn(I.href,"catt"),B=Yn(I.href,"approval_session_id"),$=await se(s,{secure_token:i.token,checkout_attempt_id:p?L:void 0,their_pm_id:p?B:void 0});return qe("Confirm payment flow result",$),jt({logPrefix:"paypal",anyCdeConnection:s,checkoutPaymentMethod:u,requiredFormFields:d,confirmResult:$,usePayFirstFlow:p})}catch(s){throw Cu("PayPal payment error",s),E("checkout_error",{payment_method:"paypal",error:s}),new Error((s==null?void 0:s.message)??"Unknown error")}}),ft=(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:Su,run:Pu},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__:Au,err__:Tu}=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);Au(`✔ ${t} flow initialized successfully. Result:`,o),n.set(o)}catch(o){Tu(`𝙭 ${t} flow initialization failed. Error:`,re(o),"Details:",o),n.throw(o,re(o))}}}},Iu=async(t,e,n)=>{await Promise.all(Object.values(t).map(r=>r.initialize({context:e,formCallbacks:n})))},xu=()=>({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__:Ru}=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,Ru);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,Nu=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 Ou(t){let e=Math.floor(t()*Zt);return e===Zt&&(e=Zt-1),Zo.charAt(e)}function Mu(t){const e=Du(),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 Du(){return ju()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function Fu(t,e){let n="";for(;t>0;t--)n=Ou(e)+n;return n}function Lu(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 ju(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function Uu(t,e){const n=Mu(),r=Date.now();return Lu(r,zo)+Fu(Nu,n)}const Bo="op_analytics_device_token",$u=()=>{const t=document.cookie.split(";").find(n=>n.includes(Bo));if(t)return t.split("=")[1];const e=Uu();return Vu(e),e},Vu=t=>{const e=new Date;e.setFullYear(e.getFullYear()+1),document.cookie=`${Bo}=${t}; path=/; expires=${e.toUTCString()}`};function Zu(){try{const t=z(),e=t;if(e!=null&&e.next||e!=null&&e.__NEXT_DATA__||document.querySelector("#__next"))return"nextjs";const n=t;if(n!=null&&n.__NUXT__||document.querySelector("#__nuxt"))return"nuxt";if(Object.keys(document).find(o=>o.includes("react"))||Array.from(document.body.querySelectorAll("body > *")).find(o=>o._reactRootContainer))return"react";const r=t;return r!=null&&r.Vue||r!=null&&r.__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 s=z();return((e=s==null?void 0:s.next)==null?void 0:e.version)||((n=s==null?void 0:s.__NEXT_DATA__)==null?void 0:n.buildId)||null}case"nuxt":return null;case"vue":return null;case"angular":{const o=(r=z())==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 Gu(){const t=Zu(),e=zu(t);return{framework:t,version:e}}class Bu{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 qu(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 Yu{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 Wu=(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:ft(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=xu(),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),Wu(this.initFlows,l,this.formCallbacks),ke("├ Starting OJS init flows..."),await Iu(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=>{qu(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:ft(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:ft(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:ft(c.checkoutPaymentMethods,"paypal","paypal"),nonCdeFormInputs:oe(c.formDiv),initResult:void 0,customParams:{settings:{...i,useRedirectFlow:!0}},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:ft(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=z())==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.2",this.ojsReleaseVersion="0.3.2",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 Yu,this.deviceToken=$u(),Yc();const{framework:n,version:r}=Gu();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 Bu(this.formId,this.baseUrl,this.formCallbacks,{setFormHeight:this.setFormHeight,onCdeLoaded:this.onCdeLoaded,onCdeLoadError:this.onCdeLoadError}),(o=z())==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 ${t.required_user_actions.length} required user actions`);return Oa
33
33
  - current_active_form_id: ${r.currentFormId}
34
34
  - is_destroyed: ${r.isDestroyed}
35
35
  - checkout_token: ${r.checkoutToken}
36
- `;return this.isDestroyed?(he(o),E("outdated_form_instance",{error:o}),!1):!n||n.formId!==this.formId?(he(o),E("outdated_form_instance",{error:o}),!1):!0}};Pe.ojsFlows=U,Pe.assignAsSingleton=e=>{if(Pe.getInstance())throw new Error("OpenPay instance already exists. Only one instance is allowed.");window.ojs=e},Pe.getInstance=()=>window.ojs??null,Pe.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 Kn=Pe;Ae.FieldName=h,Ae.OpenPayForm=Kn,Ae.SubmitMethod=ra,Ae.SubmitMethods=X,Object.defineProperty(Ae,Symbol.toStringTag,{value:"Module"})});
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"})});